1 //===- SandboxIR.h ----------------------------------------------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // Sandbox IR is a lightweight overlay transactional IR on top of LLVM IR. 10 // Features: 11 // - You can save/rollback the state of the IR at any time. 12 // - Any changes made to Sandbox IR will automatically update the underlying 13 // LLVM IR so both IRs are always in sync. 14 // - Feels like LLVM IR, similar API. 15 // 16 // SandboxIR forms a class hierarchy that resembles that of LLVM IR 17 // but is in the `sandboxir` namespace: 18 // 19 // namespace sandboxir { 20 // 21 // Value -+- Argument 22 // | 23 // +- BasicBlock 24 // | 25 // +- User ------+- Constant ------ Function 26 // | 27 // +- Instruction -+- BinaryOperator 28 // | 29 // +- BranchInst 30 // | 31 // +- CastInst --------+- AddrSpaceCastInst 32 // | | 33 // | +- BitCastInst 34 // | | 35 // | +- FPExtInst 36 // | | 37 // | +- FPToSIInst 38 // | | 39 // | +- FPToUIInst 40 // | | 41 // | +- FPTruncInst 42 // | | 43 // | +- IntToPtrInst 44 // | | 45 // | +- PtrToIntInst 46 // | | 47 // | +- SExtInst 48 // | | 49 // | +- SIToFPInst 50 // | | 51 // | +- TruncInst 52 // | | 53 // | +- UIToFPInst 54 // | | 55 // | +- ZExtInst 56 // | 57 // +- CallBase -----------+- CallBrInst 58 // | | 59 // +- CmpInst +- CallInst 60 // | | 61 // +- ExtractElementInst +- InvokeInst 62 // | 63 // +- GetElementPtrInst 64 // | 65 // +- InsertElementInst 66 // | 67 // +- OpaqueInst 68 // | 69 // +- PHINode 70 // | 71 // +- ReturnInst 72 // | 73 // +- SelectInst 74 // | 75 // +- ShuffleVectorInst 76 // | 77 // +- StoreInst 78 // | 79 // +- UnaryInstruction -+- LoadInst 80 // | | 81 // | +- CastInst 82 // | 83 // +- UnaryOperator 84 // | 85 // +- UnreachableInst 86 // 87 // Use 88 // 89 // } // namespace sandboxir 90 // 91 92 #ifndef LLVM_SANDBOXIR_SANDBOXIR_H 93 #define LLVM_SANDBOXIR_SANDBOXIR_H 94 95 #include "llvm/IR/Function.h" 96 #include "llvm/IR/IRBuilder.h" 97 #include "llvm/IR/Instruction.h" 98 #include "llvm/IR/User.h" 99 #include "llvm/IR/Value.h" 100 #include "llvm/SandboxIR/Tracker.h" 101 #include "llvm/SandboxIR/Use.h" 102 #include "llvm/Support/raw_ostream.h" 103 #include <iterator> 104 105 namespace llvm { 106 107 namespace sandboxir { 108 109 class BasicBlock; 110 class ConstantInt; 111 class Context; 112 class Function; 113 class Instruction; 114 class SelectInst; 115 class ExtractElementInst; 116 class InsertElementInst; 117 class ShuffleVectorInst; 118 class BranchInst; 119 class UnaryInstruction; 120 class LoadInst; 121 class ReturnInst; 122 class StoreInst; 123 class User; 124 class UnreachableInst; 125 class Value; 126 class CallBase; 127 class CallInst; 128 class InvokeInst; 129 class CallBrInst; 130 class FuncletPadInst; 131 class CatchPadInst; 132 class CleanupPadInst; 133 class CatchReturnInst; 134 class GetElementPtrInst; 135 class CastInst; 136 class PtrToIntInst; 137 class BitCastInst; 138 class AllocaInst; 139 class CatchSwitchInst; 140 class SwitchInst; 141 class UnaryOperator; 142 class BinaryOperator; 143 class AtomicRMWInst; 144 class AtomicCmpXchgInst; 145 146 /// Iterator for the `Use` edges of a User's operands. 147 /// \Returns the operand `Use` when dereferenced. 148 class OperandUseIterator { 149 sandboxir::Use Use; 150 /// Don't let the user create a non-empty OperandUseIterator. OperandUseIterator(const class Use & Use)151 OperandUseIterator(const class Use &Use) : Use(Use) {} 152 friend class User; // For constructor 153 #define DEF_INSTR(ID, OPC, CLASS) friend class CLASS; // For constructor 154 #include "llvm/SandboxIR/SandboxIRValues.def" 155 156 public: 157 using difference_type = std::ptrdiff_t; 158 using value_type = sandboxir::Use; 159 using pointer = value_type *; 160 using reference = value_type &; 161 using iterator_category = std::input_iterator_tag; 162 163 OperandUseIterator() = default; 164 value_type operator*() const; 165 OperandUseIterator &operator++(); 166 OperandUseIterator operator++(int) { 167 auto Copy = *this; 168 this->operator++(); 169 return Copy; 170 } 171 bool operator==(const OperandUseIterator &Other) const { 172 return Use == Other.Use; 173 } 174 bool operator!=(const OperandUseIterator &Other) const { 175 return !(*this == Other); 176 } 177 OperandUseIterator operator+(unsigned Num) const; 178 OperandUseIterator operator-(unsigned Num) const; 179 int operator-(const OperandUseIterator &Other) const; 180 }; 181 182 /// Iterator for the `Use` edges of a Value's users. 183 /// \Returns a `Use` when dereferenced. 184 class UserUseIterator { 185 sandboxir::Use Use; 186 /// Don't let the user create a non-empty UserUseIterator. UserUseIterator(const class Use & Use)187 UserUseIterator(const class Use &Use) : Use(Use) {} 188 friend class Value; // For constructor 189 190 public: 191 using difference_type = std::ptrdiff_t; 192 using value_type = sandboxir::Use; 193 using pointer = value_type *; 194 using reference = value_type &; 195 using iterator_category = std::input_iterator_tag; 196 197 UserUseIterator() = default; 198 value_type operator*() const { return Use; } 199 UserUseIterator &operator++(); 200 bool operator==(const UserUseIterator &Other) const { 201 return Use == Other.Use; 202 } 203 bool operator!=(const UserUseIterator &Other) const { 204 return !(*this == Other); 205 } getUse()206 const sandboxir::Use &getUse() const { return Use; } 207 }; 208 209 /// A SandboxIR Value has users. This is the base class. 210 class Value { 211 public: 212 enum class ClassID : unsigned { 213 #define DEF_VALUE(ID, CLASS) ID, 214 #define DEF_USER(ID, CLASS) ID, 215 #define DEF_INSTR(ID, OPC, CLASS) ID, 216 #include "llvm/SandboxIR/SandboxIRValues.def" 217 }; 218 219 protected: getSubclassIDStr(ClassID ID)220 static const char *getSubclassIDStr(ClassID ID) { 221 switch (ID) { 222 #define DEF_VALUE(ID, CLASS) \ 223 case ClassID::ID: \ 224 return #ID; 225 #define DEF_USER(ID, CLASS) \ 226 case ClassID::ID: \ 227 return #ID; 228 #define DEF_INSTR(ID, OPC, CLASS) \ 229 case ClassID::ID: \ 230 return #ID; 231 #include "llvm/SandboxIR/SandboxIRValues.def" 232 } 233 llvm_unreachable("Unimplemented ID"); 234 } 235 236 /// For isa/dyn_cast. 237 ClassID SubclassID; 238 #ifndef NDEBUG 239 /// A unique ID used for forming the name (used for debugging). 240 unsigned UID; 241 #endif 242 /// The LLVM Value that corresponds to this SandboxIR Value. 243 /// NOTE: Some sandboxir Instructions, like Packs, may include more than one 244 /// value and in these cases `Val` points to the last instruction in program 245 /// order. 246 llvm::Value *Val = nullptr; 247 248 friend class Context; // For getting `Val`. 249 friend class User; // For getting `Val`. 250 friend class Use; // For getting `Val`. 251 friend class SelectInst; // For getting `Val`. 252 friend class ExtractElementInst; // For getting `Val`. 253 friend class InsertElementInst; // For getting `Val`. 254 friend class ShuffleVectorInst; // For getting `Val`. 255 friend class BranchInst; // For getting `Val`. 256 friend class LoadInst; // For getting `Val`. 257 friend class StoreInst; // For getting `Val`. 258 friend class ReturnInst; // For getting `Val`. 259 friend class CallBase; // For getting `Val`. 260 friend class CallInst; // For getting `Val`. 261 friend class InvokeInst; // For getting `Val`. 262 friend class CallBrInst; // For getting `Val`. 263 friend class FuncletPadInst; // For getting `Val`. 264 friend class CatchPadInst; // For getting `Val`. 265 friend class CleanupPadInst; // For getting `Val`. 266 friend class CatchReturnInst; // For getting `Val`. 267 friend class GetElementPtrInst; // For getting `Val`. 268 friend class CatchSwitchInst; // For getting `Val`. 269 friend class SwitchInst; // For getting `Val`. 270 friend class UnaryOperator; // For getting `Val`. 271 friend class BinaryOperator; // For getting `Val`. 272 friend class AtomicRMWInst; // For getting `Val`. 273 friend class AtomicCmpXchgInst; // For getting `Val`. 274 friend class AllocaInst; // For getting `Val`. 275 friend class CastInst; // For getting `Val`. 276 friend class PHINode; // For getting `Val`. 277 friend class UnreachableInst; // For getting `Val`. 278 friend class CatchSwitchAddHandler; // For `Val`. 279 280 /// All values point to the context. 281 Context &Ctx; 282 // This is used by eraseFromParent(). clearValue()283 void clearValue() { Val = nullptr; } 284 template <typename ItTy, typename SBTy> friend class LLVMOpUserItToSBTy; 285 286 Value(ClassID SubclassID, llvm::Value *Val, Context &Ctx); 287 /// Disable copies. 288 Value(const Value &) = delete; 289 Value &operator=(const Value &) = delete; 290 291 public: 292 virtual ~Value() = default; getSubclassID()293 ClassID getSubclassID() const { return SubclassID; } 294 295 using use_iterator = UserUseIterator; 296 using const_use_iterator = UserUseIterator; 297 298 use_iterator use_begin(); use_begin()299 const_use_iterator use_begin() const { 300 return const_cast<Value *>(this)->use_begin(); 301 } use_end()302 use_iterator use_end() { return use_iterator(Use(nullptr, nullptr, Ctx)); } use_end()303 const_use_iterator use_end() const { 304 return const_cast<Value *>(this)->use_end(); 305 } 306 uses()307 iterator_range<use_iterator> uses() { 308 return make_range<use_iterator>(use_begin(), use_end()); 309 } uses()310 iterator_range<const_use_iterator> uses() const { 311 return make_range<const_use_iterator>(use_begin(), use_end()); 312 } 313 314 /// Helper for mapped_iterator. 315 struct UseToUser { operatorUseToUser316 User *operator()(const Use &Use) const { return &*Use.getUser(); } 317 }; 318 319 using user_iterator = mapped_iterator<sandboxir::UserUseIterator, UseToUser>; 320 using const_user_iterator = user_iterator; 321 322 user_iterator user_begin(); user_end()323 user_iterator user_end() { 324 return user_iterator(Use(nullptr, nullptr, Ctx), UseToUser()); 325 } user_begin()326 const_user_iterator user_begin() const { 327 return const_cast<Value *>(this)->user_begin(); 328 } user_end()329 const_user_iterator user_end() const { 330 return const_cast<Value *>(this)->user_end(); 331 } 332 users()333 iterator_range<user_iterator> users() { 334 return make_range<user_iterator>(user_begin(), user_end()); 335 } users()336 iterator_range<const_user_iterator> users() const { 337 return make_range<const_user_iterator>(user_begin(), user_end()); 338 } 339 /// \Returns the number of user edges (not necessarily to unique users). 340 /// WARNING: This is a linear-time operation. 341 unsigned getNumUses() const; 342 /// Return true if this value has N uses or more. 343 /// This is logically equivalent to getNumUses() >= N. 344 /// WARNING: This can be expensive, as it is linear to the number of users. hasNUsesOrMore(unsigned Num)345 bool hasNUsesOrMore(unsigned Num) const { 346 unsigned Cnt = 0; 347 for (auto It = use_begin(), ItE = use_end(); It != ItE; ++It) { 348 if (++Cnt >= Num) 349 return true; 350 } 351 return false; 352 } 353 /// Return true if this Value has exactly N uses. hasNUses(unsigned Num)354 bool hasNUses(unsigned Num) const { 355 unsigned Cnt = 0; 356 for (auto It = use_begin(), ItE = use_end(); It != ItE; ++It) { 357 if (++Cnt > Num) 358 return false; 359 } 360 return Cnt == Num; 361 } 362 getType()363 Type *getType() const { return Val->getType(); } 364 getContext()365 Context &getContext() const { return Ctx; } 366 367 void replaceUsesWithIf(Value *OtherV, 368 llvm::function_ref<bool(const Use &)> ShouldReplace); 369 void replaceAllUsesWith(Value *Other); 370 371 /// \Returns the LLVM IR name of the bottom-most LLVM value. getName()372 StringRef getName() const { return Val->getName(); } 373 374 #ifndef NDEBUG 375 /// Should crash if there is something wrong with the instruction. 376 virtual void verify() const = 0; 377 /// Returns the unique id in the form 'SB<number>.' like 'SB1.' 378 std::string getUid() const; 379 virtual void dumpCommonHeader(raw_ostream &OS) const; 380 void dumpCommonFooter(raw_ostream &OS) const; 381 void dumpCommonPrefix(raw_ostream &OS) const; 382 void dumpCommonSuffix(raw_ostream &OS) const; 383 void printAsOperandCommon(raw_ostream &OS) const; 384 friend raw_ostream &operator<<(raw_ostream &OS, const sandboxir::Value &V) { 385 V.dumpOS(OS); 386 return OS; 387 } 388 virtual void dumpOS(raw_ostream &OS) const = 0; 389 LLVM_DUMP_METHOD void dump() const; 390 #endif 391 }; 392 393 /// Argument of a sandboxir::Function. 394 class Argument : public sandboxir::Value { Argument(llvm::Argument * Arg,sandboxir::Context & Ctx)395 Argument(llvm::Argument *Arg, sandboxir::Context &Ctx) 396 : sandboxir::Value(ClassID::Argument, Arg, Ctx) {} 397 friend class Context; // For constructor. 398 399 public: classof(const sandboxir::Value * From)400 static bool classof(const sandboxir::Value *From) { 401 return From->getSubclassID() == ClassID::Argument; 402 } 403 #ifndef NDEBUG verify()404 void verify() const final { 405 assert(isa<llvm::Argument>(Val) && "Expected Argument!"); 406 } 407 void printAsOperand(raw_ostream &OS) const; 408 void dumpOS(raw_ostream &OS) const final; 409 #endif 410 }; 411 412 /// A sandboxir::User has operands. 413 class User : public Value { 414 protected: User(ClassID ID,llvm::Value * V,Context & Ctx)415 User(ClassID ID, llvm::Value *V, Context &Ctx) : Value(ID, V, Ctx) {} 416 417 /// \Returns the Use edge that corresponds to \p OpIdx. 418 /// Note: This is the default implementation that works for instructions that 419 /// match the underlying LLVM instruction. All others should use a different 420 /// implementation. 421 Use getOperandUseDefault(unsigned OpIdx, bool Verify) const; 422 /// \Returns the Use for the \p OpIdx'th operand. This is virtual to allow 423 /// instructions to deviate from the LLVM IR operands, which is a requirement 424 /// for sandboxir Instructions that consist of more than one LLVM Instruction. 425 virtual Use getOperandUseInternal(unsigned OpIdx, bool Verify) const = 0; 426 friend class OperandUseIterator; // for getOperandUseInternal() 427 428 /// The default implementation works only for single-LLVMIR-instruction 429 /// Users and only if they match exactly the LLVM instruction. getUseOperandNoDefault(const Use & Use)430 unsigned getUseOperandNoDefault(const Use &Use) const { 431 return Use.LLVMUse->getOperandNo(); 432 } 433 /// \Returns the operand index of \p Use. 434 virtual unsigned getUseOperandNo(const Use &Use) const = 0; 435 friend unsigned Use::getOperandNo() const; // For getUseOperandNo() 436 swapOperandsInternal(unsigned OpIdxA,unsigned OpIdxB)437 void swapOperandsInternal(unsigned OpIdxA, unsigned OpIdxB) { 438 assert(OpIdxA < getNumOperands() && "OpIdxA out of bounds!"); 439 assert(OpIdxB < getNumOperands() && "OpIdxB out of bounds!"); 440 auto UseA = getOperandUse(OpIdxA); 441 auto UseB = getOperandUse(OpIdxB); 442 UseA.swap(UseB); 443 } 444 445 #ifndef NDEBUG 446 void verifyUserOfLLVMUse(const llvm::Use &Use) const; 447 #endif // NDEBUG 448 449 public: 450 /// For isa/dyn_cast. 451 static bool classof(const Value *From); 452 using op_iterator = OperandUseIterator; 453 using const_op_iterator = OperandUseIterator; 454 using op_range = iterator_range<op_iterator>; 455 using const_op_range = iterator_range<const_op_iterator>; 456 op_begin()457 virtual op_iterator op_begin() { 458 assert(isa<llvm::User>(Val) && "Expect User value!"); 459 return op_iterator(getOperandUseInternal(0, /*Verify=*/false)); 460 } op_end()461 virtual op_iterator op_end() { 462 assert(isa<llvm::User>(Val) && "Expect User value!"); 463 return op_iterator( 464 getOperandUseInternal(getNumOperands(), /*Verify=*/false)); 465 } op_begin()466 virtual const_op_iterator op_begin() const { 467 return const_cast<User *>(this)->op_begin(); 468 } op_end()469 virtual const_op_iterator op_end() const { 470 return const_cast<User *>(this)->op_end(); 471 } 472 operands()473 op_range operands() { return make_range<op_iterator>(op_begin(), op_end()); } operands()474 const_op_range operands() const { 475 return make_range<const_op_iterator>(op_begin(), op_end()); 476 } getOperand(unsigned OpIdx)477 Value *getOperand(unsigned OpIdx) const { return getOperandUse(OpIdx).get(); } 478 /// \Returns the operand edge for \p OpIdx. NOTE: This should also work for 479 /// OpIdx == getNumOperands(), which is used for op_end(). getOperandUse(unsigned OpIdx)480 Use getOperandUse(unsigned OpIdx) const { 481 return getOperandUseInternal(OpIdx, /*Verify=*/true); 482 } getNumOperands()483 virtual unsigned getNumOperands() const { 484 return isa<llvm::User>(Val) ? cast<llvm::User>(Val)->getNumOperands() : 0; 485 } 486 487 virtual void setOperand(unsigned OperandIdx, Value *Operand); 488 /// Replaces any operands that match \p FromV with \p ToV. Returns whether any 489 /// operands were replaced. 490 bool replaceUsesOfWith(Value *FromV, Value *ToV); 491 492 #ifndef NDEBUG verify()493 void verify() const override { 494 assert(isa<llvm::User>(Val) && "Expected User!"); 495 } 496 void dumpCommonHeader(raw_ostream &OS) const final; dumpOS(raw_ostream & OS)497 void dumpOS(raw_ostream &OS) const override { 498 // TODO: Remove this tmp implementation once we get the Instruction classes. 499 } 500 #endif 501 }; 502 503 class Constant : public sandboxir::User { Constant(llvm::Constant * C,sandboxir::Context & SBCtx)504 Constant(llvm::Constant *C, sandboxir::Context &SBCtx) 505 : sandboxir::User(ClassID::Constant, C, SBCtx) {} Constant(ClassID ID,llvm::Constant * C,sandboxir::Context & SBCtx)506 Constant(ClassID ID, llvm::Constant *C, sandboxir::Context &SBCtx) 507 : sandboxir::User(ID, C, SBCtx) {} 508 friend class ConstantInt; // For constructor. 509 friend class Function; // For constructor 510 friend class Context; // For constructor. getOperandUseInternal(unsigned OpIdx,bool Verify)511 Use getOperandUseInternal(unsigned OpIdx, bool Verify) const override { 512 return getOperandUseDefault(OpIdx, Verify); 513 } 514 515 public: 516 /// For isa/dyn_cast. classof(const sandboxir::Value * From)517 static bool classof(const sandboxir::Value *From) { 518 return From->getSubclassID() == ClassID::Constant || 519 From->getSubclassID() == ClassID::ConstantInt || 520 From->getSubclassID() == ClassID::Function; 521 } getParent()522 sandboxir::Context &getParent() const { return getContext(); } getUseOperandNo(const Use & Use)523 unsigned getUseOperandNo(const Use &Use) const override { 524 return getUseOperandNoDefault(Use); 525 } 526 #ifndef NDEBUG verify()527 void verify() const override { 528 assert(isa<llvm::Constant>(Val) && "Expected Constant!"); 529 } 530 void dumpOS(raw_ostream &OS) const override; 531 #endif 532 }; 533 534 class ConstantInt : public Constant { ConstantInt(llvm::ConstantInt * C,sandboxir::Context & Ctx)535 ConstantInt(llvm::ConstantInt *C, sandboxir::Context &Ctx) 536 : Constant(ClassID::ConstantInt, C, Ctx) {} 537 friend class Context; // For constructor. 538 getOperandUseInternal(unsigned OpIdx,bool Verify)539 Use getOperandUseInternal(unsigned OpIdx, bool Verify) const final { 540 llvm_unreachable("ConstantInt has no operands!"); 541 } 542 543 public: 544 /// If Ty is a vector type, return a Constant with a splat of the given 545 /// value. Otherwise return a ConstantInt for the given value. 546 static ConstantInt *get(Type *Ty, uint64_t V, Context &Ctx, 547 bool IsSigned = false); 548 549 // TODO: Implement missing functions. 550 551 /// For isa/dyn_cast. classof(const sandboxir::Value * From)552 static bool classof(const sandboxir::Value *From) { 553 return From->getSubclassID() == ClassID::ConstantInt; 554 } getUseOperandNo(const Use & Use)555 unsigned getUseOperandNo(const Use &Use) const override { 556 llvm_unreachable("ConstantInt has no operands!"); 557 } 558 #ifndef NDEBUG verify()559 void verify() const override { 560 assert(isa<llvm::ConstantInt>(Val) && "Expected a ConstantInst!"); 561 } dumpOS(raw_ostream & OS)562 void dumpOS(raw_ostream &OS) const override { 563 dumpCommonPrefix(OS); 564 dumpCommonSuffix(OS); 565 } 566 #endif 567 }; 568 569 /// Iterator for `Instruction`s in a `BasicBlock. 570 /// \Returns an sandboxir::Instruction & when derereferenced. 571 class BBIterator { 572 public: 573 using difference_type = std::ptrdiff_t; 574 using value_type = Instruction; 575 using pointer = value_type *; 576 using reference = value_type &; 577 using iterator_category = std::bidirectional_iterator_tag; 578 579 private: 580 llvm::BasicBlock *BB; 581 llvm::BasicBlock::iterator It; 582 Context *Ctx; 583 pointer getInstr(llvm::BasicBlock::iterator It) const; 584 585 public: BBIterator()586 BBIterator() : BB(nullptr), Ctx(nullptr) {} BBIterator(llvm::BasicBlock * BB,llvm::BasicBlock::iterator It,Context * Ctx)587 BBIterator(llvm::BasicBlock *BB, llvm::BasicBlock::iterator It, Context *Ctx) 588 : BB(BB), It(It), Ctx(Ctx) {} 589 reference operator*() const { return *getInstr(It); } 590 BBIterator &operator++(); 591 BBIterator operator++(int) { 592 auto Copy = *this; 593 ++*this; 594 return Copy; 595 } 596 BBIterator &operator--(); 597 BBIterator operator--(int) { 598 auto Copy = *this; 599 --*this; 600 return Copy; 601 } 602 bool operator==(const BBIterator &Other) const { 603 assert(Ctx == Other.Ctx && "BBIterators in different context!"); 604 return It == Other.It; 605 } 606 bool operator!=(const BBIterator &Other) const { return !(*this == Other); } 607 /// \Returns the SBInstruction that corresponds to this iterator, or null if 608 /// the instruction is not found in the IR-to-SandboxIR tables. get()609 pointer get() const { return getInstr(It); } 610 }; 611 612 /// Contains a list of sandboxir::Instruction's. 613 class BasicBlock : public Value { 614 /// Builds a graph that contains all values in \p BB in their original form 615 /// i.e., no vectorization is taking place here. 616 void buildBasicBlockFromLLVMIR(llvm::BasicBlock *LLVMBB); 617 friend class Context; // For `buildBasicBlockFromIR` 618 friend class Instruction; // For LLVM Val. 619 BasicBlock(llvm::BasicBlock * BB,Context & SBCtx)620 BasicBlock(llvm::BasicBlock *BB, Context &SBCtx) 621 : Value(ClassID::Block, BB, SBCtx) { 622 buildBasicBlockFromLLVMIR(BB); 623 } 624 625 public: 626 ~BasicBlock() = default; 627 /// For isa/dyn_cast. classof(const Value * From)628 static bool classof(const Value *From) { 629 return From->getSubclassID() == Value::ClassID::Block; 630 } 631 Function *getParent() const; 632 using iterator = BBIterator; 633 iterator begin() const; end()634 iterator end() const { 635 auto *BB = cast<llvm::BasicBlock>(Val); 636 return iterator(BB, BB->end(), &Ctx); 637 } rbegin()638 std::reverse_iterator<iterator> rbegin() const { 639 return std::make_reverse_iterator(end()); 640 } rend()641 std::reverse_iterator<iterator> rend() const { 642 return std::make_reverse_iterator(begin()); 643 } getContext()644 Context &getContext() const { return Ctx; } 645 Instruction *getTerminator() const; empty()646 bool empty() const { return begin() == end(); } 647 Instruction &front() const; 648 Instruction &back() const; 649 650 #ifndef NDEBUG verify()651 void verify() const final { 652 assert(isa<llvm::BasicBlock>(Val) && "Expected BasicBlock!"); 653 } 654 void dumpOS(raw_ostream &OS) const final; 655 #endif 656 }; 657 658 /// A sandboxir::User with operands, opcode and linked with previous/next 659 /// instructions in an instruction list. 660 class Instruction : public sandboxir::User { 661 public: 662 enum class Opcode { 663 #define OP(OPC) OPC, 664 #define OPCODES(...) __VA_ARGS__ 665 #define DEF_INSTR(ID, OPC, CLASS) OPC 666 #include "llvm/SandboxIR/SandboxIRValues.def" 667 }; 668 669 protected: Instruction(ClassID ID,Opcode Opc,llvm::Instruction * I,sandboxir::Context & SBCtx)670 Instruction(ClassID ID, Opcode Opc, llvm::Instruction *I, 671 sandboxir::Context &SBCtx) 672 : sandboxir::User(ID, I, SBCtx), Opc(Opc) {} 673 674 Opcode Opc; 675 676 /// A SandboxIR Instruction may map to multiple LLVM IR Instruction. This 677 /// returns its topmost LLVM IR instruction. 678 llvm::Instruction *getTopmostLLVMInstruction() const; 679 friend class SelectInst; // For getTopmostLLVMInstruction(). 680 friend class ExtractElementInst; // For getTopmostLLVMInstruction(). 681 friend class InsertElementInst; // For getTopmostLLVMInstruction(). 682 friend class ShuffleVectorInst; // For getTopmostLLVMInstruction(). 683 friend class BranchInst; // For getTopmostLLVMInstruction(). 684 friend class LoadInst; // For getTopmostLLVMInstruction(). 685 friend class StoreInst; // For getTopmostLLVMInstruction(). 686 friend class ReturnInst; // For getTopmostLLVMInstruction(). 687 friend class CallInst; // For getTopmostLLVMInstruction(). 688 friend class InvokeInst; // For getTopmostLLVMInstruction(). 689 friend class CallBrInst; // For getTopmostLLVMInstruction(). 690 friend class CatchPadInst; // For getTopmostLLVMInstruction(). 691 friend class CleanupPadInst; // For getTopmostLLVMInstruction(). 692 friend class CatchReturnInst; // For getTopmostLLVMInstruction(). 693 friend class GetElementPtrInst; // For getTopmostLLVMInstruction(). 694 friend class CatchSwitchInst; // For getTopmostLLVMInstruction(). 695 friend class SwitchInst; // For getTopmostLLVMInstruction(). 696 friend class UnaryOperator; // For getTopmostLLVMInstruction(). 697 friend class BinaryOperator; // For getTopmostLLVMInstruction(). 698 friend class AtomicRMWInst; // For getTopmostLLVMInstruction(). 699 friend class AtomicCmpXchgInst; // For getTopmostLLVMInstruction(). 700 friend class AllocaInst; // For getTopmostLLVMInstruction(). 701 friend class CastInst; // For getTopmostLLVMInstruction(). 702 friend class PHINode; // For getTopmostLLVMInstruction(). 703 friend class UnreachableInst; // For getTopmostLLVMInstruction(). 704 705 /// \Returns the LLVM IR Instructions that this SandboxIR maps to in program 706 /// order. 707 virtual SmallVector<llvm::Instruction *, 1> getLLVMInstrs() const = 0; 708 friend class EraseFromParent; // For getLLVMInstrs(). 709 710 public: 711 static const char *getOpcodeName(Opcode Opc); 712 /// This is used by BasicBlock::iterator. 713 virtual unsigned getNumOfIRInstrs() const = 0; 714 /// \Returns a BasicBlock::iterator for this Instruction. 715 BBIterator getIterator() const; 716 /// \Returns the next sandboxir::Instruction in the block, or nullptr if at 717 /// the end of the block. 718 Instruction *getNextNode() const; 719 /// \Returns the previous sandboxir::Instruction in the block, or nullptr if 720 /// at the beginning of the block. 721 Instruction *getPrevNode() const; 722 /// \Returns this Instruction's opcode. Note that SandboxIR has its own opcode 723 /// state to allow for new SandboxIR-specific instructions. getOpcode()724 Opcode getOpcode() const { return Opc; } 725 /// Detach this from its parent BasicBlock without deleting it. 726 void removeFromParent(); 727 /// Detach this Value from its parent and delete it. 728 void eraseFromParent(); 729 /// Insert this detached instruction before \p BeforeI. 730 void insertBefore(Instruction *BeforeI); 731 /// Insert this detached instruction after \p AfterI. 732 void insertAfter(Instruction *AfterI); 733 /// Insert this detached instruction into \p BB at \p WhereIt. 734 void insertInto(BasicBlock *BB, const BBIterator &WhereIt); 735 /// Move this instruction to \p WhereIt. 736 void moveBefore(BasicBlock &BB, const BBIterator &WhereIt); 737 /// Move this instruction before \p Before. moveBefore(Instruction * Before)738 void moveBefore(Instruction *Before) { 739 moveBefore(*Before->getParent(), Before->getIterator()); 740 } 741 /// Move this instruction after \p After. moveAfter(Instruction * After)742 void moveAfter(Instruction *After) { 743 moveBefore(*After->getParent(), std::next(After->getIterator())); 744 } 745 /// \Returns the BasicBlock containing this Instruction, or null if it is 746 /// detached. 747 BasicBlock *getParent() const; 748 /// For isa/dyn_cast. 749 static bool classof(const sandboxir::Value *From); 750 751 /// Determine whether the no signed wrap flag is set. hasNoUnsignedWrap()752 bool hasNoUnsignedWrap() const { 753 return cast<llvm::Instruction>(Val)->hasNoUnsignedWrap(); 754 } 755 /// Set or clear the nuw flag on this instruction, which must be an operator 756 /// which supports this flag. See LangRef.html for the meaning of this flag. 757 void setHasNoUnsignedWrap(bool B = true); 758 /// Determine whether the no signed wrap flag is set. hasNoSignedWrap()759 bool hasNoSignedWrap() const { 760 return cast<llvm::Instruction>(Val)->hasNoSignedWrap(); 761 } 762 /// Set or clear the nsw flag on this instruction, which must be an operator 763 /// which supports this flag. See LangRef.html for the meaning of this flag. 764 void setHasNoSignedWrap(bool B = true); 765 /// Determine whether all fast-math-flags are set. isFast()766 bool isFast() const { return cast<llvm::Instruction>(Val)->isFast(); } 767 /// Set or clear all fast-math-flags on this instruction, which must be an 768 /// operator which supports this flag. See LangRef.html for the meaning of 769 /// this flag. 770 void setFast(bool B); 771 /// Determine whether the allow-reassociation flag is set. hasAllowReassoc()772 bool hasAllowReassoc() const { 773 return cast<llvm::Instruction>(Val)->hasAllowReassoc(); 774 } 775 /// Set or clear the reassociation flag on this instruction, which must be 776 /// an operator which supports this flag. See LangRef.html for the meaning of 777 /// this flag. 778 void setHasAllowReassoc(bool B); 779 /// Determine whether the exact flag is set. isExact()780 bool isExact() const { return cast<llvm::Instruction>(Val)->isExact(); } 781 /// Set or clear the exact flag on this instruction, which must be an operator 782 /// which supports this flag. See LangRef.html for the meaning of this flag. 783 void setIsExact(bool B = true); 784 /// Determine whether the no-NaNs flag is set. hasNoNaNs()785 bool hasNoNaNs() const { return cast<llvm::Instruction>(Val)->hasNoNaNs(); } 786 /// Set or clear the no-nans flag on this instruction, which must be an 787 /// operator which supports this flag. See LangRef.html for the meaning of 788 /// this flag. 789 void setHasNoNaNs(bool B); 790 /// Determine whether the no-infs flag is set. hasNoInfs()791 bool hasNoInfs() const { return cast<llvm::Instruction>(Val)->hasNoInfs(); } 792 /// Set or clear the no-infs flag on this instruction, which must be an 793 /// operator which supports this flag. See LangRef.html for the meaning of 794 /// this flag. 795 void setHasNoInfs(bool B); 796 /// Determine whether the no-signed-zeros flag is set. hasNoSignedZeros()797 bool hasNoSignedZeros() const { 798 return cast<llvm::Instruction>(Val)->hasNoSignedZeros(); 799 } 800 /// Set or clear the no-signed-zeros flag on this instruction, which must be 801 /// an operator which supports this flag. See LangRef.html for the meaning of 802 /// this flag. 803 void setHasNoSignedZeros(bool B); 804 /// Determine whether the allow-reciprocal flag is set. hasAllowReciprocal()805 bool hasAllowReciprocal() const { 806 return cast<llvm::Instruction>(Val)->hasAllowReciprocal(); 807 } 808 /// Set or clear the allow-reciprocal flag on this instruction, which must be 809 /// an operator which supports this flag. See LangRef.html for the meaning of 810 /// this flag. 811 void setHasAllowReciprocal(bool B); 812 /// Determine whether the allow-contract flag is set. hasAllowContract()813 bool hasAllowContract() const { 814 return cast<llvm::Instruction>(Val)->hasAllowContract(); 815 } 816 /// Set or clear the allow-contract flag on this instruction, which must be 817 /// an operator which supports this flag. See LangRef.html for the meaning of 818 /// this flag. 819 void setHasAllowContract(bool B); 820 /// Determine whether the approximate-math-functions flag is set. hasApproxFunc()821 bool hasApproxFunc() const { 822 return cast<llvm::Instruction>(Val)->hasApproxFunc(); 823 } 824 /// Set or clear the approximate-math-functions flag on this instruction, 825 /// which must be an operator which supports this flag. See LangRef.html for 826 /// the meaning of this flag. 827 void setHasApproxFunc(bool B); 828 /// Convenience function for getting all the fast-math flags, which must be an 829 /// operator which supports these flags. See LangRef.html for the meaning of 830 /// these flags. getFastMathFlags()831 FastMathFlags getFastMathFlags() const { 832 return cast<llvm::Instruction>(Val)->getFastMathFlags(); 833 } 834 /// Convenience function for setting multiple fast-math flags on this 835 /// instruction, which must be an operator which supports these flags. See 836 /// LangRef.html for the meaning of these flags. 837 void setFastMathFlags(FastMathFlags FMF); 838 /// Convenience function for transferring all fast-math flag values to this 839 /// instruction, which must be an operator which supports these flags. See 840 /// LangRef.html for the meaning of these flags. 841 void copyFastMathFlags(FastMathFlags FMF); 842 843 #ifndef NDEBUG 844 void dumpOS(raw_ostream &OS) const override; 845 #endif 846 }; 847 848 /// Instructions that contain a single LLVM Instruction can inherit from this. 849 template <typename LLVMT> class SingleLLVMInstructionImpl : public Instruction { SingleLLVMInstructionImpl(ClassID ID,Opcode Opc,llvm::Instruction * I,sandboxir::Context & SBCtx)850 SingleLLVMInstructionImpl(ClassID ID, Opcode Opc, llvm::Instruction *I, 851 sandboxir::Context &SBCtx) 852 : Instruction(ID, Opc, I, SBCtx) {} 853 854 // All instructions are friends with this so they can call the constructor. 855 #define DEF_INSTR(ID, OPC, CLASS) friend class CLASS; 856 #include "llvm/SandboxIR/SandboxIRValues.def" 857 friend class UnaryInstruction; 858 friend class CallBase; 859 friend class FuncletPadInst; 860 getOperandUseInternal(unsigned OpIdx,bool Verify)861 Use getOperandUseInternal(unsigned OpIdx, bool Verify) const final { 862 return getOperandUseDefault(OpIdx, Verify); 863 } getLLVMInstrs()864 SmallVector<llvm::Instruction *, 1> getLLVMInstrs() const final { 865 return {cast<llvm::Instruction>(Val)}; 866 } 867 868 public: getUseOperandNo(const Use & Use)869 unsigned getUseOperandNo(const Use &Use) const final { 870 return getUseOperandNoDefault(Use); 871 } getNumOfIRInstrs()872 unsigned getNumOfIRInstrs() const final { return 1u; } 873 #ifndef NDEBUG verify()874 void verify() const final { assert(isa<LLVMT>(Val) && "Expected LLVMT!"); } dumpOS(raw_ostream & OS)875 void dumpOS(raw_ostream &OS) const override { 876 dumpCommonPrefix(OS); 877 dumpCommonSuffix(OS); 878 } 879 #endif 880 }; 881 882 class SelectInst : public SingleLLVMInstructionImpl<llvm::SelectInst> { 883 /// Use Context::createSelectInst(). Don't call the 884 /// constructor directly. SelectInst(llvm::SelectInst * CI,Context & Ctx)885 SelectInst(llvm::SelectInst *CI, Context &Ctx) 886 : SingleLLVMInstructionImpl(ClassID::Select, Opcode::Select, CI, Ctx) {} 887 friend Context; // for SelectInst() 888 static Value *createCommon(Value *Cond, Value *True, Value *False, 889 const Twine &Name, IRBuilder<> &Builder, 890 Context &Ctx); 891 892 public: 893 static Value *create(Value *Cond, Value *True, Value *False, 894 Instruction *InsertBefore, Context &Ctx, 895 const Twine &Name = ""); 896 static Value *create(Value *Cond, Value *True, Value *False, 897 BasicBlock *InsertAtEnd, Context &Ctx, 898 const Twine &Name = ""); getCondition()899 Value *getCondition() { return getOperand(0); } getTrueValue()900 Value *getTrueValue() { return getOperand(1); } getFalseValue()901 Value *getFalseValue() { return getOperand(2); } 902 setCondition(Value * New)903 void setCondition(Value *New) { setOperand(0, New); } setTrueValue(Value * New)904 void setTrueValue(Value *New) { setOperand(1, New); } setFalseValue(Value * New)905 void setFalseValue(Value *New) { setOperand(2, New); } swapValues()906 void swapValues() { cast<llvm::SelectInst>(Val)->swapValues(); } 907 /// For isa/dyn_cast. 908 static bool classof(const Value *From); 909 }; 910 911 class InsertElementInst final 912 : public SingleLLVMInstructionImpl<llvm::InsertElementInst> { 913 /// Use Context::createInsertElementInst() instead. InsertElementInst(llvm::Instruction * I,Context & Ctx)914 InsertElementInst(llvm::Instruction *I, Context &Ctx) 915 : SingleLLVMInstructionImpl(ClassID::InsertElement, Opcode::InsertElement, 916 I, Ctx) {} 917 friend class Context; // For accessing the constructor in create*() 918 919 public: 920 static Value *create(Value *Vec, Value *NewElt, Value *Idx, 921 Instruction *InsertBefore, Context &Ctx, 922 const Twine &Name = ""); 923 static Value *create(Value *Vec, Value *NewElt, Value *Idx, 924 BasicBlock *InsertAtEnd, Context &Ctx, 925 const Twine &Name = ""); classof(const Value * From)926 static bool classof(const Value *From) { 927 return From->getSubclassID() == ClassID::InsertElement; 928 } isValidOperands(const Value * Vec,const Value * NewElt,const Value * Idx)929 static bool isValidOperands(const Value *Vec, const Value *NewElt, 930 const Value *Idx) { 931 return llvm::InsertElementInst::isValidOperands(Vec->Val, NewElt->Val, 932 Idx->Val); 933 } 934 }; 935 936 class ExtractElementInst final 937 : public SingleLLVMInstructionImpl<llvm::ExtractElementInst> { 938 /// Use Context::createExtractElementInst() instead. ExtractElementInst(llvm::Instruction * I,Context & Ctx)939 ExtractElementInst(llvm::Instruction *I, Context &Ctx) 940 : SingleLLVMInstructionImpl(ClassID::ExtractElement, 941 Opcode::ExtractElement, I, Ctx) {} 942 friend class Context; // For accessing the constructor in 943 // create*() 944 945 public: 946 static Value *create(Value *Vec, Value *Idx, Instruction *InsertBefore, 947 Context &Ctx, const Twine &Name = ""); 948 static Value *create(Value *Vec, Value *Idx, BasicBlock *InsertAtEnd, 949 Context &Ctx, const Twine &Name = ""); classof(const Value * From)950 static bool classof(const Value *From) { 951 return From->getSubclassID() == ClassID::ExtractElement; 952 } 953 isValidOperands(const Value * Vec,const Value * Idx)954 static bool isValidOperands(const Value *Vec, const Value *Idx) { 955 return llvm::ExtractElementInst::isValidOperands(Vec->Val, Idx->Val); 956 } getVectorOperand()957 Value *getVectorOperand() { return getOperand(0); } getIndexOperand()958 Value *getIndexOperand() { return getOperand(1); } getVectorOperand()959 const Value *getVectorOperand() const { return getOperand(0); } getIndexOperand()960 const Value *getIndexOperand() const { return getOperand(1); } 961 getVectorOperandType()962 VectorType *getVectorOperandType() const { 963 return cast<VectorType>(getVectorOperand()->getType()); 964 } 965 }; 966 967 class ShuffleVectorInst final 968 : public SingleLLVMInstructionImpl<llvm::ShuffleVectorInst> { 969 /// Use Context::createShuffleVectorInst() instead. ShuffleVectorInst(llvm::Instruction * I,Context & Ctx)970 ShuffleVectorInst(llvm::Instruction *I, Context &Ctx) 971 : SingleLLVMInstructionImpl(ClassID::ShuffleVector, Opcode::ShuffleVector, 972 I, Ctx) {} 973 friend class Context; // For accessing the constructor in create*() 974 975 public: 976 static Value *create(Value *V1, Value *V2, Value *Mask, 977 Instruction *InsertBefore, Context &Ctx, 978 const Twine &Name = ""); 979 static Value *create(Value *V1, Value *V2, Value *Mask, 980 BasicBlock *InsertAtEnd, Context &Ctx, 981 const Twine &Name = ""); 982 static Value *create(Value *V1, Value *V2, ArrayRef<int> Mask, 983 Instruction *InsertBefore, Context &Ctx, 984 const Twine &Name = ""); 985 static Value *create(Value *V1, Value *V2, ArrayRef<int> Mask, 986 BasicBlock *InsertAtEnd, Context &Ctx, 987 const Twine &Name = ""); classof(const Value * From)988 static bool classof(const Value *From) { 989 return From->getSubclassID() == ClassID::ShuffleVector; 990 } 991 992 /// Swap the operands and adjust the mask to preserve the semantics of the 993 /// instruction. commute()994 void commute() { cast<llvm::ShuffleVectorInst>(Val)->commute(); } 995 996 /// Return true if a shufflevector instruction can be formed with the 997 /// specified operands. isValidOperands(const Value * V1,const Value * V2,const Value * Mask)998 static bool isValidOperands(const Value *V1, const Value *V2, 999 const Value *Mask) { 1000 return llvm::ShuffleVectorInst::isValidOperands(V1->Val, V2->Val, 1001 Mask->Val); 1002 } isValidOperands(const Value * V1,const Value * V2,ArrayRef<int> Mask)1003 static bool isValidOperands(const Value *V1, const Value *V2, 1004 ArrayRef<int> Mask) { 1005 return llvm::ShuffleVectorInst::isValidOperands(V1->Val, V2->Val, Mask); 1006 } 1007 1008 /// Overload to return most specific vector type. getType()1009 VectorType *getType() const { 1010 return cast<llvm::ShuffleVectorInst>(Val)->getType(); 1011 } 1012 1013 /// Return the shuffle mask value of this instruction for the given element 1014 /// index. Return PoisonMaskElem if the element is undef. getMaskValue(unsigned Elt)1015 int getMaskValue(unsigned Elt) const { 1016 return cast<llvm::ShuffleVectorInst>(Val)->getMaskValue(Elt); 1017 } 1018 1019 /// Convert the input shuffle mask operand to a vector of integers. Undefined 1020 /// elements of the mask are returned as PoisonMaskElem. getShuffleMask(const Constant * Mask,SmallVectorImpl<int> & Result)1021 static void getShuffleMask(const Constant *Mask, 1022 SmallVectorImpl<int> &Result) { 1023 llvm::ShuffleVectorInst::getShuffleMask(cast<llvm::Constant>(Mask->Val), 1024 Result); 1025 } 1026 1027 /// Return the mask for this instruction as a vector of integers. Undefined 1028 /// elements of the mask are returned as PoisonMaskElem. getShuffleMask(SmallVectorImpl<int> & Result)1029 void getShuffleMask(SmallVectorImpl<int> &Result) const { 1030 cast<llvm::ShuffleVectorInst>(Val)->getShuffleMask(Result); 1031 } 1032 1033 /// Return the mask for this instruction, for use in bitcode. 1034 Constant *getShuffleMaskForBitcode() const; 1035 1036 static Constant *convertShuffleMaskForBitcode(ArrayRef<int> Mask, 1037 Type *ResultTy, Context &Ctx); 1038 1039 void setShuffleMask(ArrayRef<int> Mask); 1040 getShuffleMask()1041 ArrayRef<int> getShuffleMask() const { 1042 return cast<llvm::ShuffleVectorInst>(Val)->getShuffleMask(); 1043 } 1044 1045 /// Return true if this shuffle returns a vector with a different number of 1046 /// elements than its source vectors. 1047 /// Examples: shufflevector <4 x n> A, <4 x n> B, <1,2,3> 1048 /// shufflevector <4 x n> A, <4 x n> B, <1,2,3,4,5> changesLength()1049 bool changesLength() const { 1050 return cast<llvm::ShuffleVectorInst>(Val)->changesLength(); 1051 } 1052 1053 /// Return true if this shuffle returns a vector with a greater number of 1054 /// elements than its source vectors. 1055 /// Example: shufflevector <2 x n> A, <2 x n> B, <1,2,3> increasesLength()1056 bool increasesLength() const { 1057 return cast<llvm::ShuffleVectorInst>(Val)->increasesLength(); 1058 } 1059 1060 /// Return true if this shuffle mask chooses elements from exactly one source 1061 /// vector. 1062 /// Example: <7,5,undef,7> 1063 /// This assumes that vector operands (of length \p NumSrcElts) are the same 1064 /// length as the mask. isSingleSourceMask(ArrayRef<int> Mask,int NumSrcElts)1065 static bool isSingleSourceMask(ArrayRef<int> Mask, int NumSrcElts) { 1066 return llvm::ShuffleVectorInst::isSingleSourceMask(Mask, NumSrcElts); 1067 } isSingleSourceMask(const Constant * Mask,int NumSrcElts)1068 static bool isSingleSourceMask(const Constant *Mask, int NumSrcElts) { 1069 return llvm::ShuffleVectorInst::isSingleSourceMask( 1070 cast<llvm::Constant>(Mask->Val), NumSrcElts); 1071 } 1072 1073 /// Return true if this shuffle chooses elements from exactly one source 1074 /// vector without changing the length of that vector. 1075 /// Example: shufflevector <4 x n> A, <4 x n> B, <3,0,undef,3> isSingleSource()1076 bool isSingleSource() const { 1077 return cast<llvm::ShuffleVectorInst>(Val)->isSingleSource(); 1078 } 1079 1080 /// Return true if this shuffle mask chooses elements from exactly one source 1081 /// vector without lane crossings. A shuffle using this mask is not 1082 /// necessarily a no-op because it may change the number of elements from its 1083 /// input vectors or it may provide demanded bits knowledge via undef lanes. 1084 /// Example: <undef,undef,2,3> isIdentityMask(ArrayRef<int> Mask,int NumSrcElts)1085 static bool isIdentityMask(ArrayRef<int> Mask, int NumSrcElts) { 1086 return llvm::ShuffleVectorInst::isIdentityMask(Mask, NumSrcElts); 1087 } isIdentityMask(const Constant * Mask,int NumSrcElts)1088 static bool isIdentityMask(const Constant *Mask, int NumSrcElts) { 1089 return llvm::ShuffleVectorInst::isIdentityMask( 1090 cast<llvm::Constant>(Mask->Val), NumSrcElts); 1091 } 1092 1093 /// Return true if this shuffle chooses elements from exactly one source 1094 /// vector without lane crossings and does not change the number of elements 1095 /// from its input vectors. 1096 /// Example: shufflevector <4 x n> A, <4 x n> B, <4,undef,6,undef> isIdentity()1097 bool isIdentity() const { 1098 return cast<llvm::ShuffleVectorInst>(Val)->isIdentity(); 1099 } 1100 1101 /// Return true if this shuffle lengthens exactly one source vector with 1102 /// undefs in the high elements. isIdentityWithPadding()1103 bool isIdentityWithPadding() const { 1104 return cast<llvm::ShuffleVectorInst>(Val)->isIdentityWithPadding(); 1105 } 1106 1107 /// Return true if this shuffle extracts the first N elements of exactly one 1108 /// source vector. isIdentityWithExtract()1109 bool isIdentityWithExtract() const { 1110 return cast<llvm::ShuffleVectorInst>(Val)->isIdentityWithExtract(); 1111 } 1112 1113 /// Return true if this shuffle concatenates its 2 source vectors. This 1114 /// returns false if either input is undefined. In that case, the shuffle is 1115 /// is better classified as an identity with padding operation. isConcat()1116 bool isConcat() const { 1117 return cast<llvm::ShuffleVectorInst>(Val)->isConcat(); 1118 } 1119 1120 /// Return true if this shuffle mask chooses elements from its source vectors 1121 /// without lane crossings. A shuffle using this mask would be 1122 /// equivalent to a vector select with a constant condition operand. 1123 /// Example: <4,1,6,undef> 1124 /// This returns false if the mask does not choose from both input vectors. 1125 /// In that case, the shuffle is better classified as an identity shuffle. 1126 /// This assumes that vector operands are the same length as the mask 1127 /// (a length-changing shuffle can never be equivalent to a vector select). isSelectMask(ArrayRef<int> Mask,int NumSrcElts)1128 static bool isSelectMask(ArrayRef<int> Mask, int NumSrcElts) { 1129 return llvm::ShuffleVectorInst::isSelectMask(Mask, NumSrcElts); 1130 } isSelectMask(const Constant * Mask,int NumSrcElts)1131 static bool isSelectMask(const Constant *Mask, int NumSrcElts) { 1132 return llvm::ShuffleVectorInst::isSelectMask( 1133 cast<llvm::Constant>(Mask->Val), NumSrcElts); 1134 } 1135 1136 /// Return true if this shuffle chooses elements from its source vectors 1137 /// without lane crossings and all operands have the same number of elements. 1138 /// In other words, this shuffle is equivalent to a vector select with a 1139 /// constant condition operand. 1140 /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,1,6,3> 1141 /// This returns false if the mask does not choose from both input vectors. 1142 /// In that case, the shuffle is better classified as an identity shuffle. isSelect()1143 bool isSelect() const { 1144 return cast<llvm::ShuffleVectorInst>(Val)->isSelect(); 1145 } 1146 1147 /// Return true if this shuffle mask swaps the order of elements from exactly 1148 /// one source vector. 1149 /// Example: <7,6,undef,4> 1150 /// This assumes that vector operands (of length \p NumSrcElts) are the same 1151 /// length as the mask. isReverseMask(ArrayRef<int> Mask,int NumSrcElts)1152 static bool isReverseMask(ArrayRef<int> Mask, int NumSrcElts) { 1153 return llvm::ShuffleVectorInst::isReverseMask(Mask, NumSrcElts); 1154 } isReverseMask(const Constant * Mask,int NumSrcElts)1155 static bool isReverseMask(const Constant *Mask, int NumSrcElts) { 1156 return llvm::ShuffleVectorInst::isReverseMask( 1157 cast<llvm::Constant>(Mask->Val), NumSrcElts); 1158 } 1159 1160 /// Return true if this shuffle swaps the order of elements from exactly 1161 /// one source vector. 1162 /// Example: shufflevector <4 x n> A, <4 x n> B, <3,undef,1,undef> isReverse()1163 bool isReverse() const { 1164 return cast<llvm::ShuffleVectorInst>(Val)->isReverse(); 1165 } 1166 1167 /// Return true if this shuffle mask chooses all elements with the same value 1168 /// as the first element of exactly one source vector. 1169 /// Example: <4,undef,undef,4> 1170 /// This assumes that vector operands (of length \p NumSrcElts) are the same 1171 /// length as the mask. isZeroEltSplatMask(ArrayRef<int> Mask,int NumSrcElts)1172 static bool isZeroEltSplatMask(ArrayRef<int> Mask, int NumSrcElts) { 1173 return llvm::ShuffleVectorInst::isZeroEltSplatMask(Mask, NumSrcElts); 1174 } isZeroEltSplatMask(const Constant * Mask,int NumSrcElts)1175 static bool isZeroEltSplatMask(const Constant *Mask, int NumSrcElts) { 1176 return llvm::ShuffleVectorInst::isZeroEltSplatMask( 1177 cast<llvm::Constant>(Mask->Val), NumSrcElts); 1178 } 1179 1180 /// Return true if all elements of this shuffle are the same value as the 1181 /// first element of exactly one source vector without changing the length 1182 /// of that vector. 1183 /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,0,undef,0> isZeroEltSplat()1184 bool isZeroEltSplat() const { 1185 return cast<llvm::ShuffleVectorInst>(Val)->isZeroEltSplat(); 1186 } 1187 1188 /// Return true if this shuffle mask is a transpose mask. 1189 /// Transpose vector masks transpose a 2xn matrix. They read corresponding 1190 /// even- or odd-numbered vector elements from two n-dimensional source 1191 /// vectors and write each result into consecutive elements of an 1192 /// n-dimensional destination vector. Two shuffles are necessary to complete 1193 /// the transpose, one for the even elements and another for the odd elements. 1194 /// This description closely follows how the TRN1 and TRN2 AArch64 1195 /// instructions operate. 1196 /// 1197 /// For example, a simple 2x2 matrix can be transposed with: 1198 /// 1199 /// ; Original matrix 1200 /// m0 = < a, b > 1201 /// m1 = < c, d > 1202 /// 1203 /// ; Transposed matrix 1204 /// t0 = < a, c > = shufflevector m0, m1, < 0, 2 > 1205 /// t1 = < b, d > = shufflevector m0, m1, < 1, 3 > 1206 /// 1207 /// For matrices having greater than n columns, the resulting nx2 transposed 1208 /// matrix is stored in two result vectors such that one vector contains 1209 /// interleaved elements from all the even-numbered rows and the other vector 1210 /// contains interleaved elements from all the odd-numbered rows. For example, 1211 /// a 2x4 matrix can be transposed with: 1212 /// 1213 /// ; Original matrix 1214 /// m0 = < a, b, c, d > 1215 /// m1 = < e, f, g, h > 1216 /// 1217 /// ; Transposed matrix 1218 /// t0 = < a, e, c, g > = shufflevector m0, m1 < 0, 4, 2, 6 > 1219 /// t1 = < b, f, d, h > = shufflevector m0, m1 < 1, 5, 3, 7 > isTransposeMask(ArrayRef<int> Mask,int NumSrcElts)1220 static bool isTransposeMask(ArrayRef<int> Mask, int NumSrcElts) { 1221 return llvm::ShuffleVectorInst::isTransposeMask(Mask, NumSrcElts); 1222 } isTransposeMask(const Constant * Mask,int NumSrcElts)1223 static bool isTransposeMask(const Constant *Mask, int NumSrcElts) { 1224 return llvm::ShuffleVectorInst::isTransposeMask( 1225 cast<llvm::Constant>(Mask->Val), NumSrcElts); 1226 } 1227 1228 /// Return true if this shuffle transposes the elements of its inputs without 1229 /// changing the length of the vectors. This operation may also be known as a 1230 /// merge or interleave. See the description for isTransposeMask() for the 1231 /// exact specification. 1232 /// Example: shufflevector <4 x n> A, <4 x n> B, <0,4,2,6> isTranspose()1233 bool isTranspose() const { 1234 return cast<llvm::ShuffleVectorInst>(Val)->isTranspose(); 1235 } 1236 1237 /// Return true if this shuffle mask is a splice mask, concatenating the two 1238 /// inputs together and then extracts an original width vector starting from 1239 /// the splice index. 1240 /// Example: shufflevector <4 x n> A, <4 x n> B, <1,2,3,4> 1241 /// This assumes that vector operands (of length \p NumSrcElts) are the same 1242 /// length as the mask. isSpliceMask(ArrayRef<int> Mask,int NumSrcElts,int & Index)1243 static bool isSpliceMask(ArrayRef<int> Mask, int NumSrcElts, int &Index) { 1244 return llvm::ShuffleVectorInst::isSpliceMask(Mask, NumSrcElts, Index); 1245 } isSpliceMask(const Constant * Mask,int NumSrcElts,int & Index)1246 static bool isSpliceMask(const Constant *Mask, int NumSrcElts, int &Index) { 1247 return llvm::ShuffleVectorInst::isSpliceMask( 1248 cast<llvm::Constant>(Mask->Val), NumSrcElts, Index); 1249 } 1250 1251 /// Return true if this shuffle splices two inputs without changing the length 1252 /// of the vectors. This operation concatenates the two inputs together and 1253 /// then extracts an original width vector starting from the splice index. 1254 /// Example: shufflevector <4 x n> A, <4 x n> B, <1,2,3,4> isSplice(int & Index)1255 bool isSplice(int &Index) const { 1256 return cast<llvm::ShuffleVectorInst>(Val)->isSplice(Index); 1257 } 1258 1259 /// Return true if this shuffle mask is an extract subvector mask. 1260 /// A valid extract subvector mask returns a smaller vector from a single 1261 /// source operand. The base extraction index is returned as well. isExtractSubvectorMask(ArrayRef<int> Mask,int NumSrcElts,int & Index)1262 static bool isExtractSubvectorMask(ArrayRef<int> Mask, int NumSrcElts, 1263 int &Index) { 1264 return llvm::ShuffleVectorInst::isExtractSubvectorMask(Mask, NumSrcElts, 1265 Index); 1266 } isExtractSubvectorMask(const Constant * Mask,int NumSrcElts,int & Index)1267 static bool isExtractSubvectorMask(const Constant *Mask, int NumSrcElts, 1268 int &Index) { 1269 return llvm::ShuffleVectorInst::isExtractSubvectorMask( 1270 cast<llvm::Constant>(Mask->Val), NumSrcElts, Index); 1271 } 1272 1273 /// Return true if this shuffle mask is an extract subvector mask. isExtractSubvectorMask(int & Index)1274 bool isExtractSubvectorMask(int &Index) const { 1275 return cast<llvm::ShuffleVectorInst>(Val)->isExtractSubvectorMask(Index); 1276 } 1277 1278 /// Return true if this shuffle mask is an insert subvector mask. 1279 /// A valid insert subvector mask inserts the lowest elements of a second 1280 /// source operand into an in-place first source operand. 1281 /// Both the sub vector width and the insertion index is returned. isInsertSubvectorMask(ArrayRef<int> Mask,int NumSrcElts,int & NumSubElts,int & Index)1282 static bool isInsertSubvectorMask(ArrayRef<int> Mask, int NumSrcElts, 1283 int &NumSubElts, int &Index) { 1284 return llvm::ShuffleVectorInst::isInsertSubvectorMask(Mask, NumSrcElts, 1285 NumSubElts, Index); 1286 } isInsertSubvectorMask(const Constant * Mask,int NumSrcElts,int & NumSubElts,int & Index)1287 static bool isInsertSubvectorMask(const Constant *Mask, int NumSrcElts, 1288 int &NumSubElts, int &Index) { 1289 return llvm::ShuffleVectorInst::isInsertSubvectorMask( 1290 cast<llvm::Constant>(Mask->Val), NumSrcElts, NumSubElts, Index); 1291 } 1292 1293 /// Return true if this shuffle mask is an insert subvector mask. isInsertSubvectorMask(int & NumSubElts,int & Index)1294 bool isInsertSubvectorMask(int &NumSubElts, int &Index) const { 1295 return cast<llvm::ShuffleVectorInst>(Val)->isInsertSubvectorMask(NumSubElts, 1296 Index); 1297 } 1298 1299 /// Return true if this shuffle mask replicates each of the \p VF elements 1300 /// in a vector \p ReplicationFactor times. 1301 /// For example, the mask for \p ReplicationFactor=3 and \p VF=4 is: 1302 /// <0,0,0,1,1,1,2,2,2,3,3,3> isReplicationMask(ArrayRef<int> Mask,int & ReplicationFactor,int & VF)1303 static bool isReplicationMask(ArrayRef<int> Mask, int &ReplicationFactor, 1304 int &VF) { 1305 return llvm::ShuffleVectorInst::isReplicationMask(Mask, ReplicationFactor, 1306 VF); 1307 } isReplicationMask(const Constant * Mask,int & ReplicationFactor,int & VF)1308 static bool isReplicationMask(const Constant *Mask, int &ReplicationFactor, 1309 int &VF) { 1310 return llvm::ShuffleVectorInst::isReplicationMask( 1311 cast<llvm::Constant>(Mask->Val), ReplicationFactor, VF); 1312 } 1313 1314 /// Return true if this shuffle mask is a replication mask. isReplicationMask(int & ReplicationFactor,int & VF)1315 bool isReplicationMask(int &ReplicationFactor, int &VF) const { 1316 return cast<llvm::ShuffleVectorInst>(Val)->isReplicationMask( 1317 ReplicationFactor, VF); 1318 } 1319 1320 /// Return true if this shuffle mask represents "clustered" mask of size VF, 1321 /// i.e. each index between [0..VF) is used exactly once in each submask of 1322 /// size VF. 1323 /// For example, the mask for \p VF=4 is: 1324 /// 0, 1, 2, 3, 3, 2, 0, 1 - "clustered", because each submask of size 4 1325 /// (0,1,2,3 and 3,2,0,1) uses indices [0..VF) exactly one time. 1326 /// 0, 1, 2, 3, 3, 3, 1, 0 - not "clustered", because 1327 /// element 3 is used twice in the second submask 1328 /// (3,3,1,0) and index 2 is not used at all. isOneUseSingleSourceMask(ArrayRef<int> Mask,int VF)1329 static bool isOneUseSingleSourceMask(ArrayRef<int> Mask, int VF) { 1330 return llvm::ShuffleVectorInst::isOneUseSingleSourceMask(Mask, VF); 1331 } 1332 1333 /// Return true if this shuffle mask is a one-use-single-source("clustered") 1334 /// mask. isOneUseSingleSourceMask(int VF)1335 bool isOneUseSingleSourceMask(int VF) const { 1336 return cast<llvm::ShuffleVectorInst>(Val)->isOneUseSingleSourceMask(VF); 1337 } 1338 1339 /// Change values in a shuffle permute mask assuming the two vector operands 1340 /// of length InVecNumElts have swapped position. commuteShuffleMask(MutableArrayRef<int> Mask,unsigned InVecNumElts)1341 static void commuteShuffleMask(MutableArrayRef<int> Mask, 1342 unsigned InVecNumElts) { 1343 llvm::ShuffleVectorInst::commuteShuffleMask(Mask, InVecNumElts); 1344 } 1345 1346 /// Return if this shuffle interleaves its two input vectors together. isInterleave(unsigned Factor)1347 bool isInterleave(unsigned Factor) const { 1348 return cast<llvm::ShuffleVectorInst>(Val)->isInterleave(Factor); 1349 } 1350 1351 /// Return true if the mask interleaves one or more input vectors together. 1352 /// 1353 /// I.e. <0, LaneLen, ... , LaneLen*(Factor - 1), 1, LaneLen + 1, ...> 1354 /// E.g. For a Factor of 2 (LaneLen=4): 1355 /// <0, 4, 1, 5, 2, 6, 3, 7> 1356 /// E.g. For a Factor of 3 (LaneLen=4): 1357 /// <4, 0, 9, 5, 1, 10, 6, 2, 11, 7, 3, 12> 1358 /// E.g. For a Factor of 4 (LaneLen=2): 1359 /// <0, 2, 6, 4, 1, 3, 7, 5> 1360 /// 1361 /// NumInputElts is the total number of elements in the input vectors. 1362 /// 1363 /// StartIndexes are the first indexes of each vector being interleaved, 1364 /// substituting any indexes that were undef 1365 /// E.g. <4, -1, 2, 5, 1, 3> (Factor=3): StartIndexes=<4, 0, 2> 1366 /// 1367 /// Note that this does not check if the input vectors are consecutive: 1368 /// It will return true for masks such as 1369 /// <0, 4, 6, 1, 5, 7> (Factor=3, LaneLen=2) isInterleaveMask(ArrayRef<int> Mask,unsigned Factor,unsigned NumInputElts,SmallVectorImpl<unsigned> & StartIndexes)1370 static bool isInterleaveMask(ArrayRef<int> Mask, unsigned Factor, 1371 unsigned NumInputElts, 1372 SmallVectorImpl<unsigned> &StartIndexes) { 1373 return llvm::ShuffleVectorInst::isInterleaveMask(Mask, Factor, NumInputElts, 1374 StartIndexes); 1375 } isInterleaveMask(ArrayRef<int> Mask,unsigned Factor,unsigned NumInputElts)1376 static bool isInterleaveMask(ArrayRef<int> Mask, unsigned Factor, 1377 unsigned NumInputElts) { 1378 return llvm::ShuffleVectorInst::isInterleaveMask(Mask, Factor, 1379 NumInputElts); 1380 } 1381 1382 /// Check if the mask is a DE-interleave mask of the given factor 1383 /// \p Factor like: 1384 /// <Index, Index+Factor, ..., Index+(NumElts-1)*Factor> isDeInterleaveMaskOfFactor(ArrayRef<int> Mask,unsigned Factor,unsigned & Index)1385 static bool isDeInterleaveMaskOfFactor(ArrayRef<int> Mask, unsigned Factor, 1386 unsigned &Index) { 1387 return llvm::ShuffleVectorInst::isDeInterleaveMaskOfFactor(Mask, Factor, 1388 Index); 1389 } isDeInterleaveMaskOfFactor(ArrayRef<int> Mask,unsigned Factor)1390 static bool isDeInterleaveMaskOfFactor(ArrayRef<int> Mask, unsigned Factor) { 1391 return llvm::ShuffleVectorInst::isDeInterleaveMaskOfFactor(Mask, Factor); 1392 } 1393 1394 /// Checks if the shuffle is a bit rotation of the first operand across 1395 /// multiple subelements, e.g: 1396 /// 1397 /// shuffle <8 x i8> %a, <8 x i8> poison, <8 x i32> <1, 0, 3, 2, 5, 4, 7, 6> 1398 /// 1399 /// could be expressed as 1400 /// 1401 /// rotl <4 x i16> %a, 8 1402 /// 1403 /// If it can be expressed as a rotation, returns the number of subelements to 1404 /// group by in NumSubElts and the number of bits to rotate left in RotateAmt. isBitRotateMask(ArrayRef<int> Mask,unsigned EltSizeInBits,unsigned MinSubElts,unsigned MaxSubElts,unsigned & NumSubElts,unsigned & RotateAmt)1405 static bool isBitRotateMask(ArrayRef<int> Mask, unsigned EltSizeInBits, 1406 unsigned MinSubElts, unsigned MaxSubElts, 1407 unsigned &NumSubElts, unsigned &RotateAmt) { 1408 return llvm::ShuffleVectorInst::isBitRotateMask( 1409 Mask, EltSizeInBits, MinSubElts, MaxSubElts, NumSubElts, RotateAmt); 1410 } 1411 }; 1412 1413 class BranchInst : public SingleLLVMInstructionImpl<llvm::BranchInst> { 1414 /// Use Context::createBranchInst(). Don't call the constructor directly. BranchInst(llvm::BranchInst * BI,Context & Ctx)1415 BranchInst(llvm::BranchInst *BI, Context &Ctx) 1416 : SingleLLVMInstructionImpl(ClassID::Br, Opcode::Br, BI, Ctx) {} 1417 friend Context; // for BranchInst() 1418 1419 public: 1420 static BranchInst *create(BasicBlock *IfTrue, Instruction *InsertBefore, 1421 Context &Ctx); 1422 static BranchInst *create(BasicBlock *IfTrue, BasicBlock *InsertAtEnd, 1423 Context &Ctx); 1424 static BranchInst *create(BasicBlock *IfTrue, BasicBlock *IfFalse, 1425 Value *Cond, Instruction *InsertBefore, 1426 Context &Ctx); 1427 static BranchInst *create(BasicBlock *IfTrue, BasicBlock *IfFalse, 1428 Value *Cond, BasicBlock *InsertAtEnd, Context &Ctx); 1429 /// For isa/dyn_cast. 1430 static bool classof(const Value *From); isUnconditional()1431 bool isUnconditional() const { 1432 return cast<llvm::BranchInst>(Val)->isUnconditional(); 1433 } isConditional()1434 bool isConditional() const { 1435 return cast<llvm::BranchInst>(Val)->isConditional(); 1436 } 1437 Value *getCondition() const; setCondition(Value * V)1438 void setCondition(Value *V) { setOperand(0, V); } getNumSuccessors()1439 unsigned getNumSuccessors() const { return 1 + isConditional(); } 1440 BasicBlock *getSuccessor(unsigned SuccIdx) const; 1441 void setSuccessor(unsigned Idx, BasicBlock *NewSucc); swapSuccessors()1442 void swapSuccessors() { swapOperandsInternal(1, 2); } 1443 1444 private: 1445 struct LLVMBBToSBBB { 1446 Context &Ctx; LLVMBBToSBBBLLVMBBToSBBB1447 LLVMBBToSBBB(Context &Ctx) : Ctx(Ctx) {} 1448 BasicBlock *operator()(llvm::BasicBlock *BB) const; 1449 }; 1450 1451 struct ConstLLVMBBToSBBB { 1452 Context &Ctx; ConstLLVMBBToSBBBConstLLVMBBToSBBB1453 ConstLLVMBBToSBBB(Context &Ctx) : Ctx(Ctx) {} 1454 const BasicBlock *operator()(const llvm::BasicBlock *BB) const; 1455 }; 1456 1457 public: 1458 using sb_succ_op_iterator = 1459 mapped_iterator<llvm::BranchInst::succ_op_iterator, LLVMBBToSBBB>; successors()1460 iterator_range<sb_succ_op_iterator> successors() { 1461 iterator_range<llvm::BranchInst::succ_op_iterator> LLVMRange = 1462 cast<llvm::BranchInst>(Val)->successors(); 1463 LLVMBBToSBBB BBMap(Ctx); 1464 sb_succ_op_iterator MappedBegin = map_iterator(LLVMRange.begin(), BBMap); 1465 sb_succ_op_iterator MappedEnd = map_iterator(LLVMRange.end(), BBMap); 1466 return make_range(MappedBegin, MappedEnd); 1467 } 1468 1469 using const_sb_succ_op_iterator = 1470 mapped_iterator<llvm::BranchInst::const_succ_op_iterator, 1471 ConstLLVMBBToSBBB>; successors()1472 iterator_range<const_sb_succ_op_iterator> successors() const { 1473 iterator_range<llvm::BranchInst::const_succ_op_iterator> ConstLLVMRange = 1474 static_cast<const llvm::BranchInst *>(cast<llvm::BranchInst>(Val)) 1475 ->successors(); 1476 ConstLLVMBBToSBBB ConstBBMap(Ctx); 1477 const_sb_succ_op_iterator ConstMappedBegin = 1478 map_iterator(ConstLLVMRange.begin(), ConstBBMap); 1479 const_sb_succ_op_iterator ConstMappedEnd = 1480 map_iterator(ConstLLVMRange.end(), ConstBBMap); 1481 return make_range(ConstMappedBegin, ConstMappedEnd); 1482 } 1483 }; 1484 1485 /// An abstract class, parent of unary instructions. 1486 class UnaryInstruction 1487 : public SingleLLVMInstructionImpl<llvm::UnaryInstruction> { 1488 protected: UnaryInstruction(ClassID ID,Opcode Opc,llvm::Instruction * LLVMI,Context & Ctx)1489 UnaryInstruction(ClassID ID, Opcode Opc, llvm::Instruction *LLVMI, 1490 Context &Ctx) 1491 : SingleLLVMInstructionImpl(ID, Opc, LLVMI, Ctx) {} 1492 1493 public: classof(const Instruction * I)1494 static bool classof(const Instruction *I) { 1495 return isa<LoadInst>(I) || isa<CastInst>(I); 1496 } classof(const Value * V)1497 static bool classof(const Value *V) { 1498 return isa<Instruction>(V) && classof(cast<Instruction>(V)); 1499 } 1500 }; 1501 1502 class LoadInst final : public UnaryInstruction { 1503 /// Use LoadInst::create() instead of calling the constructor. LoadInst(llvm::LoadInst * LI,Context & Ctx)1504 LoadInst(llvm::LoadInst *LI, Context &Ctx) 1505 : UnaryInstruction(ClassID::Load, Opcode::Load, LI, Ctx) {} 1506 friend Context; // for LoadInst() 1507 1508 public: 1509 /// Return true if this is a load from a volatile memory location. isVolatile()1510 bool isVolatile() const { return cast<llvm::LoadInst>(Val)->isVolatile(); } 1511 /// Specify whether this is a volatile load or not. 1512 void setVolatile(bool V); 1513 1514 static LoadInst *create(Type *Ty, Value *Ptr, MaybeAlign Align, 1515 Instruction *InsertBefore, Context &Ctx, 1516 const Twine &Name = ""); 1517 static LoadInst *create(Type *Ty, Value *Ptr, MaybeAlign Align, 1518 Instruction *InsertBefore, bool IsVolatile, 1519 Context &Ctx, const Twine &Name = ""); 1520 static LoadInst *create(Type *Ty, Value *Ptr, MaybeAlign Align, 1521 BasicBlock *InsertAtEnd, Context &Ctx, 1522 const Twine &Name = ""); 1523 static LoadInst *create(Type *Ty, Value *Ptr, MaybeAlign Align, 1524 BasicBlock *InsertAtEnd, bool IsVolatile, 1525 Context &Ctx, const Twine &Name = ""); 1526 1527 /// For isa/dyn_cast. 1528 static bool classof(const Value *From); 1529 Value *getPointerOperand() const; getAlign()1530 Align getAlign() const { return cast<llvm::LoadInst>(Val)->getAlign(); } isUnordered()1531 bool isUnordered() const { return cast<llvm::LoadInst>(Val)->isUnordered(); } isSimple()1532 bool isSimple() const { return cast<llvm::LoadInst>(Val)->isSimple(); } 1533 }; 1534 1535 class StoreInst final : public SingleLLVMInstructionImpl<llvm::StoreInst> { 1536 /// Use StoreInst::create(). StoreInst(llvm::StoreInst * SI,Context & Ctx)1537 StoreInst(llvm::StoreInst *SI, Context &Ctx) 1538 : SingleLLVMInstructionImpl(ClassID::Store, Opcode::Store, SI, Ctx) {} 1539 friend Context; // for StoreInst() 1540 1541 public: 1542 /// Return true if this is a store from a volatile memory location. isVolatile()1543 bool isVolatile() const { return cast<llvm::StoreInst>(Val)->isVolatile(); } 1544 /// Specify whether this is a volatile store or not. 1545 void setVolatile(bool V); 1546 1547 static StoreInst *create(Value *V, Value *Ptr, MaybeAlign Align, 1548 Instruction *InsertBefore, Context &Ctx); 1549 static StoreInst *create(Value *V, Value *Ptr, MaybeAlign Align, 1550 Instruction *InsertBefore, bool IsVolatile, 1551 Context &Ctx); 1552 static StoreInst *create(Value *V, Value *Ptr, MaybeAlign Align, 1553 BasicBlock *InsertAtEnd, Context &Ctx); 1554 static StoreInst *create(Value *V, Value *Ptr, MaybeAlign Align, 1555 BasicBlock *InsertAtEnd, bool IsVolatile, 1556 Context &Ctx); 1557 /// For isa/dyn_cast. 1558 static bool classof(const Value *From); 1559 Value *getValueOperand() const; 1560 Value *getPointerOperand() const; getAlign()1561 Align getAlign() const { return cast<llvm::StoreInst>(Val)->getAlign(); } isSimple()1562 bool isSimple() const { return cast<llvm::StoreInst>(Val)->isSimple(); } isUnordered()1563 bool isUnordered() const { return cast<llvm::StoreInst>(Val)->isUnordered(); } 1564 }; 1565 1566 class UnreachableInst final : public Instruction { 1567 /// Use UnreachableInst::create() instead of calling the constructor. UnreachableInst(llvm::UnreachableInst * I,Context & Ctx)1568 UnreachableInst(llvm::UnreachableInst *I, Context &Ctx) 1569 : Instruction(ClassID::Unreachable, Opcode::Unreachable, I, Ctx) {} 1570 friend Context; getOperandUseInternal(unsigned OpIdx,bool Verify)1571 Use getOperandUseInternal(unsigned OpIdx, bool Verify) const final { 1572 return getOperandUseDefault(OpIdx, Verify); 1573 } getLLVMInstrs()1574 SmallVector<llvm::Instruction *, 1> getLLVMInstrs() const final { 1575 return {cast<llvm::Instruction>(Val)}; 1576 } 1577 1578 public: 1579 static UnreachableInst *create(Instruction *InsertBefore, Context &Ctx); 1580 static UnreachableInst *create(BasicBlock *InsertAtEnd, Context &Ctx); 1581 static bool classof(const Value *From); getNumSuccessors()1582 unsigned getNumSuccessors() const { return 0; } getUseOperandNo(const Use & Use)1583 unsigned getUseOperandNo(const Use &Use) const final { 1584 llvm_unreachable("UnreachableInst has no operands!"); 1585 } getNumOfIRInstrs()1586 unsigned getNumOfIRInstrs() const final { return 1u; } 1587 }; 1588 1589 class ReturnInst final : public SingleLLVMInstructionImpl<llvm::ReturnInst> { 1590 /// Use ReturnInst::create() instead of calling the constructor. ReturnInst(llvm::Instruction * I,Context & Ctx)1591 ReturnInst(llvm::Instruction *I, Context &Ctx) 1592 : SingleLLVMInstructionImpl(ClassID::Ret, Opcode::Ret, I, Ctx) {} ReturnInst(ClassID SubclassID,llvm::Instruction * I,Context & Ctx)1593 ReturnInst(ClassID SubclassID, llvm::Instruction *I, Context &Ctx) 1594 : SingleLLVMInstructionImpl(SubclassID, Opcode::Ret, I, Ctx) {} 1595 friend class Context; // For accessing the constructor in create*() 1596 static ReturnInst *createCommon(Value *RetVal, IRBuilder<> &Builder, 1597 Context &Ctx); 1598 1599 public: 1600 static ReturnInst *create(Value *RetVal, Instruction *InsertBefore, 1601 Context &Ctx); 1602 static ReturnInst *create(Value *RetVal, BasicBlock *InsertAtEnd, 1603 Context &Ctx); classof(const Value * From)1604 static bool classof(const Value *From) { 1605 return From->getSubclassID() == ClassID::Ret; 1606 } 1607 /// \Returns null if there is no return value. 1608 Value *getReturnValue() const; 1609 }; 1610 1611 class CallBase : public SingleLLVMInstructionImpl<llvm::CallBase> { CallBase(ClassID ID,Opcode Opc,llvm::Instruction * I,Context & Ctx)1612 CallBase(ClassID ID, Opcode Opc, llvm::Instruction *I, Context &Ctx) 1613 : SingleLLVMInstructionImpl(ID, Opc, I, Ctx) {} 1614 friend class CallInst; // For constructor. 1615 friend class InvokeInst; // For constructor. 1616 friend class CallBrInst; // For constructor. 1617 1618 public: classof(const Value * From)1619 static bool classof(const Value *From) { 1620 auto Opc = From->getSubclassID(); 1621 return Opc == Instruction::ClassID::Call || 1622 Opc == Instruction::ClassID::Invoke || 1623 Opc == Instruction::ClassID::CallBr; 1624 } 1625 getFunctionType()1626 FunctionType *getFunctionType() const { 1627 return cast<llvm::CallBase>(Val)->getFunctionType(); 1628 } 1629 data_operands_begin()1630 op_iterator data_operands_begin() { return op_begin(); } data_operands_begin()1631 const_op_iterator data_operands_begin() const { 1632 return const_cast<CallBase *>(this)->data_operands_begin(); 1633 } data_operands_end()1634 op_iterator data_operands_end() { 1635 auto *LLVMCB = cast<llvm::CallBase>(Val); 1636 auto Dist = LLVMCB->data_operands_end() - LLVMCB->data_operands_begin(); 1637 return op_begin() + Dist; 1638 } data_operands_end()1639 const_op_iterator data_operands_end() const { 1640 auto *LLVMCB = cast<llvm::CallBase>(Val); 1641 auto Dist = LLVMCB->data_operands_end() - LLVMCB->data_operands_begin(); 1642 return op_begin() + Dist; 1643 } data_ops()1644 iterator_range<op_iterator> data_ops() { 1645 return make_range(data_operands_begin(), data_operands_end()); 1646 } data_ops()1647 iterator_range<const_op_iterator> data_ops() const { 1648 return make_range(data_operands_begin(), data_operands_end()); 1649 } data_operands_empty()1650 bool data_operands_empty() const { 1651 return data_operands_end() == data_operands_begin(); 1652 } data_operands_size()1653 unsigned data_operands_size() const { 1654 return std::distance(data_operands_begin(), data_operands_end()); 1655 } isDataOperand(Use U)1656 bool isDataOperand(Use U) const { 1657 assert(this == U.getUser() && 1658 "Only valid to query with a use of this instruction!"); 1659 return cast<llvm::CallBase>(Val)->isDataOperand(U.LLVMUse); 1660 } getDataOperandNo(Use U)1661 unsigned getDataOperandNo(Use U) const { 1662 assert(isDataOperand(U) && "Data operand # out of range!"); 1663 return cast<llvm::CallBase>(Val)->getDataOperandNo(U.LLVMUse); 1664 } 1665 1666 /// Return the total number operands (not operand bundles) used by 1667 /// every operand bundle in this OperandBundleUser. getNumTotalBundleOperands()1668 unsigned getNumTotalBundleOperands() const { 1669 return cast<llvm::CallBase>(Val)->getNumTotalBundleOperands(); 1670 } 1671 arg_begin()1672 op_iterator arg_begin() { return op_begin(); } arg_begin()1673 const_op_iterator arg_begin() const { return op_begin(); } arg_end()1674 op_iterator arg_end() { 1675 return data_operands_end() - getNumTotalBundleOperands(); 1676 } arg_end()1677 const_op_iterator arg_end() const { 1678 return const_cast<CallBase *>(this)->arg_end(); 1679 } args()1680 iterator_range<op_iterator> args() { 1681 return make_range(arg_begin(), arg_end()); 1682 } args()1683 iterator_range<const_op_iterator> args() const { 1684 return make_range(arg_begin(), arg_end()); 1685 } arg_empty()1686 bool arg_empty() const { return arg_end() == arg_begin(); } arg_size()1687 unsigned arg_size() const { return arg_end() - arg_begin(); } 1688 getArgOperand(unsigned OpIdx)1689 Value *getArgOperand(unsigned OpIdx) const { 1690 assert(OpIdx < arg_size() && "Out of bounds!"); 1691 return getOperand(OpIdx); 1692 } setArgOperand(unsigned OpIdx,Value * NewOp)1693 void setArgOperand(unsigned OpIdx, Value *NewOp) { 1694 assert(OpIdx < arg_size() && "Out of bounds!"); 1695 setOperand(OpIdx, NewOp); 1696 } 1697 getArgOperandUse(unsigned Idx)1698 Use getArgOperandUse(unsigned Idx) const { 1699 assert(Idx < arg_size() && "Out of bounds!"); 1700 return getOperandUse(Idx); 1701 } getArgOperandUse(unsigned Idx)1702 Use getArgOperandUse(unsigned Idx) { 1703 assert(Idx < arg_size() && "Out of bounds!"); 1704 return getOperandUse(Idx); 1705 } 1706 isArgOperand(Use U)1707 bool isArgOperand(Use U) const { 1708 return cast<llvm::CallBase>(Val)->isArgOperand(U.LLVMUse); 1709 } getArgOperandNo(Use U)1710 unsigned getArgOperandNo(Use U) const { 1711 return cast<llvm::CallBase>(Val)->getArgOperandNo(U.LLVMUse); 1712 } hasArgument(const Value * V)1713 bool hasArgument(const Value *V) const { return is_contained(args(), V); } 1714 1715 Value *getCalledOperand() const; 1716 Use getCalledOperandUse() const; 1717 1718 Function *getCalledFunction() const; isIndirectCall()1719 bool isIndirectCall() const { 1720 return cast<llvm::CallBase>(Val)->isIndirectCall(); 1721 } isCallee(Use U)1722 bool isCallee(Use U) const { 1723 return cast<llvm::CallBase>(Val)->isCallee(U.LLVMUse); 1724 } 1725 Function *getCaller(); getCaller()1726 const Function *getCaller() const { 1727 return const_cast<CallBase *>(this)->getCaller(); 1728 } isMustTailCall()1729 bool isMustTailCall() const { 1730 return cast<llvm::CallBase>(Val)->isMustTailCall(); 1731 } isTailCall()1732 bool isTailCall() const { return cast<llvm::CallBase>(Val)->isTailCall(); } getIntrinsicID()1733 Intrinsic::ID getIntrinsicID() const { 1734 return cast<llvm::CallBase>(Val)->getIntrinsicID(); 1735 } setCalledOperand(Value * V)1736 void setCalledOperand(Value *V) { getCalledOperandUse().set(V); } 1737 void setCalledFunction(Function *F); getCallingConv()1738 CallingConv::ID getCallingConv() const { 1739 return cast<llvm::CallBase>(Val)->getCallingConv(); 1740 } isInlineAsm()1741 bool isInlineAsm() const { return cast<llvm::CallBase>(Val)->isInlineAsm(); } 1742 }; 1743 1744 class CallInst final : public CallBase { 1745 /// Use Context::createCallInst(). Don't call the 1746 /// constructor directly. CallInst(llvm::Instruction * I,Context & Ctx)1747 CallInst(llvm::Instruction *I, Context &Ctx) 1748 : CallBase(ClassID::Call, Opcode::Call, I, Ctx) {} 1749 friend class Context; // For accessing the constructor in 1750 // create*() 1751 1752 public: 1753 static CallInst *create(FunctionType *FTy, Value *Func, 1754 ArrayRef<Value *> Args, BBIterator WhereIt, 1755 BasicBlock *WhereBB, Context &Ctx, 1756 const Twine &NameStr = ""); 1757 static CallInst *create(FunctionType *FTy, Value *Func, 1758 ArrayRef<Value *> Args, Instruction *InsertBefore, 1759 Context &Ctx, const Twine &NameStr = ""); 1760 static CallInst *create(FunctionType *FTy, Value *Func, 1761 ArrayRef<Value *> Args, BasicBlock *InsertAtEnd, 1762 Context &Ctx, const Twine &NameStr = ""); 1763 classof(const Value * From)1764 static bool classof(const Value *From) { 1765 return From->getSubclassID() == ClassID::Call; 1766 } 1767 }; 1768 1769 class InvokeInst final : public CallBase { 1770 /// Use Context::createInvokeInst(). Don't call the 1771 /// constructor directly. InvokeInst(llvm::Instruction * I,Context & Ctx)1772 InvokeInst(llvm::Instruction *I, Context &Ctx) 1773 : CallBase(ClassID::Invoke, Opcode::Invoke, I, Ctx) {} 1774 friend class Context; // For accessing the constructor in 1775 // create*() 1776 1777 public: 1778 static InvokeInst *create(FunctionType *FTy, Value *Func, 1779 BasicBlock *IfNormal, BasicBlock *IfException, 1780 ArrayRef<Value *> Args, BBIterator WhereIt, 1781 BasicBlock *WhereBB, Context &Ctx, 1782 const Twine &NameStr = ""); 1783 static InvokeInst *create(FunctionType *FTy, Value *Func, 1784 BasicBlock *IfNormal, BasicBlock *IfException, 1785 ArrayRef<Value *> Args, Instruction *InsertBefore, 1786 Context &Ctx, const Twine &NameStr = ""); 1787 static InvokeInst *create(FunctionType *FTy, Value *Func, 1788 BasicBlock *IfNormal, BasicBlock *IfException, 1789 ArrayRef<Value *> Args, BasicBlock *InsertAtEnd, 1790 Context &Ctx, const Twine &NameStr = ""); 1791 classof(const Value * From)1792 static bool classof(const Value *From) { 1793 return From->getSubclassID() == ClassID::Invoke; 1794 } 1795 BasicBlock *getNormalDest() const; 1796 BasicBlock *getUnwindDest() const; 1797 void setNormalDest(BasicBlock *BB); 1798 void setUnwindDest(BasicBlock *BB); 1799 // TODO: Return a `LandingPadInst` once implemented. 1800 Instruction *getLandingPadInst() const; 1801 BasicBlock *getSuccessor(unsigned SuccIdx) const; setSuccessor(unsigned SuccIdx,BasicBlock * NewSucc)1802 void setSuccessor(unsigned SuccIdx, BasicBlock *NewSucc) { 1803 assert(SuccIdx < 2 && "Successor # out of range for invoke!"); 1804 if (SuccIdx == 0) 1805 setNormalDest(NewSucc); 1806 else 1807 setUnwindDest(NewSucc); 1808 } getNumSuccessors()1809 unsigned getNumSuccessors() const { 1810 return cast<llvm::InvokeInst>(Val)->getNumSuccessors(); 1811 } 1812 }; 1813 1814 class CallBrInst final : public CallBase { 1815 /// Use Context::createCallBrInst(). Don't call the 1816 /// constructor directly. CallBrInst(llvm::Instruction * I,Context & Ctx)1817 CallBrInst(llvm::Instruction *I, Context &Ctx) 1818 : CallBase(ClassID::CallBr, Opcode::CallBr, I, Ctx) {} 1819 friend class Context; // For accessing the constructor in 1820 // create*() 1821 1822 public: 1823 static CallBrInst *create(FunctionType *FTy, Value *Func, 1824 BasicBlock *DefaultDest, 1825 ArrayRef<BasicBlock *> IndirectDests, 1826 ArrayRef<Value *> Args, BBIterator WhereIt, 1827 BasicBlock *WhereBB, Context &Ctx, 1828 const Twine &NameStr = ""); 1829 static CallBrInst *create(FunctionType *FTy, Value *Func, 1830 BasicBlock *DefaultDest, 1831 ArrayRef<BasicBlock *> IndirectDests, 1832 ArrayRef<Value *> Args, Instruction *InsertBefore, 1833 Context &Ctx, const Twine &NameStr = ""); 1834 static CallBrInst *create(FunctionType *FTy, Value *Func, 1835 BasicBlock *DefaultDest, 1836 ArrayRef<BasicBlock *> IndirectDests, 1837 ArrayRef<Value *> Args, BasicBlock *InsertAtEnd, 1838 Context &Ctx, const Twine &NameStr = ""); classof(const Value * From)1839 static bool classof(const Value *From) { 1840 return From->getSubclassID() == ClassID::CallBr; 1841 } getNumIndirectDests()1842 unsigned getNumIndirectDests() const { 1843 return cast<llvm::CallBrInst>(Val)->getNumIndirectDests(); 1844 } 1845 Value *getIndirectDestLabel(unsigned Idx) const; 1846 Value *getIndirectDestLabelUse(unsigned Idx) const; 1847 BasicBlock *getDefaultDest() const; 1848 BasicBlock *getIndirectDest(unsigned Idx) const; 1849 SmallVector<BasicBlock *, 16> getIndirectDests() const; 1850 void setDefaultDest(BasicBlock *BB); 1851 void setIndirectDest(unsigned Idx, BasicBlock *BB); 1852 BasicBlock *getSuccessor(unsigned Idx) const; getNumSuccessors()1853 unsigned getNumSuccessors() const { 1854 return cast<llvm::CallBrInst>(Val)->getNumSuccessors(); 1855 } 1856 }; 1857 1858 class FuncletPadInst : public SingleLLVMInstructionImpl<llvm::FuncletPadInst> { FuncletPadInst(ClassID SubclassID,Opcode Opc,llvm::Instruction * I,Context & Ctx)1859 FuncletPadInst(ClassID SubclassID, Opcode Opc, llvm::Instruction *I, 1860 Context &Ctx) 1861 : SingleLLVMInstructionImpl(SubclassID, Opc, I, Ctx) {} 1862 friend class CatchPadInst; // For constructor. 1863 friend class CleanupPadInst; // For constructor. 1864 1865 public: 1866 /// Return the number of funcletpad arguments. arg_size()1867 unsigned arg_size() const { 1868 return cast<llvm::FuncletPadInst>(Val)->arg_size(); 1869 } 1870 /// Return the outer EH-pad this funclet is nested within. 1871 /// 1872 /// Note: This returns the associated CatchSwitchInst if this FuncletPadInst 1873 /// is a CatchPadInst. 1874 Value *getParentPad() const; 1875 void setParentPad(Value *ParentPad); 1876 /// Return the Idx-th funcletpad argument. 1877 Value *getArgOperand(unsigned Idx) const; 1878 /// Set the Idx-th funcletpad argument. 1879 void setArgOperand(unsigned Idx, Value *V); 1880 1881 // TODO: Implement missing functions: arg_operands(). classof(const Value * From)1882 static bool classof(const Value *From) { 1883 return From->getSubclassID() == ClassID::CatchPad || 1884 From->getSubclassID() == ClassID::CleanupPad; 1885 } 1886 }; 1887 1888 class CatchPadInst : public FuncletPadInst { CatchPadInst(llvm::CatchPadInst * CPI,Context & Ctx)1889 CatchPadInst(llvm::CatchPadInst *CPI, Context &Ctx) 1890 : FuncletPadInst(ClassID::CatchPad, Opcode::CatchPad, CPI, Ctx) {} 1891 friend class Context; // For constructor. 1892 1893 public: 1894 CatchSwitchInst *getCatchSwitch() const; 1895 // TODO: We have not implemented setCatchSwitch() because we can't revert it 1896 // for now, as there is no CatchPadInst member function that can undo it. 1897 1898 static CatchPadInst *create(Value *ParentPad, ArrayRef<Value *> Args, 1899 BBIterator WhereIt, BasicBlock *WhereBB, 1900 Context &Ctx, const Twine &Name = ""); classof(const Value * From)1901 static bool classof(const Value *From) { 1902 return From->getSubclassID() == ClassID::CatchPad; 1903 } 1904 }; 1905 1906 class CleanupPadInst : public FuncletPadInst { CleanupPadInst(llvm::CleanupPadInst * CPI,Context & Ctx)1907 CleanupPadInst(llvm::CleanupPadInst *CPI, Context &Ctx) 1908 : FuncletPadInst(ClassID::CleanupPad, Opcode::CleanupPad, CPI, Ctx) {} 1909 friend class Context; // For constructor. 1910 1911 public: 1912 static CleanupPadInst *create(Value *ParentPad, ArrayRef<Value *> Args, 1913 BBIterator WhereIt, BasicBlock *WhereBB, 1914 Context &Ctx, const Twine &Name = ""); classof(const Value * From)1915 static bool classof(const Value *From) { 1916 return From->getSubclassID() == ClassID::CleanupPad; 1917 } 1918 }; 1919 1920 class CatchReturnInst 1921 : public SingleLLVMInstructionImpl<llvm::CatchReturnInst> { CatchReturnInst(llvm::CatchReturnInst * CRI,Context & Ctx)1922 CatchReturnInst(llvm::CatchReturnInst *CRI, Context &Ctx) 1923 : SingleLLVMInstructionImpl(ClassID::CatchRet, Opcode::CatchRet, CRI, 1924 Ctx) {} 1925 friend class Context; // For constructor. 1926 1927 public: 1928 static CatchReturnInst *create(CatchPadInst *CatchPad, BasicBlock *BB, 1929 BBIterator WhereIt, BasicBlock *WhereBB, 1930 Context &Ctx); 1931 CatchPadInst *getCatchPad() const; 1932 void setCatchPad(CatchPadInst *CatchPad); 1933 BasicBlock *getSuccessor() const; 1934 void setSuccessor(BasicBlock *NewSucc); getNumSuccessors()1935 unsigned getNumSuccessors() { 1936 return cast<llvm::CatchReturnInst>(Val)->getNumSuccessors(); 1937 } 1938 Value *getCatchSwitchParentPad() const; classof(const Value * From)1939 static bool classof(const Value *From) { 1940 return From->getSubclassID() == ClassID::CatchRet; 1941 } 1942 }; 1943 1944 class GetElementPtrInst final 1945 : public SingleLLVMInstructionImpl<llvm::GetElementPtrInst> { 1946 /// Use Context::createGetElementPtrInst(). Don't call 1947 /// the constructor directly. GetElementPtrInst(llvm::Instruction * I,Context & Ctx)1948 GetElementPtrInst(llvm::Instruction *I, Context &Ctx) 1949 : SingleLLVMInstructionImpl(ClassID::GetElementPtr, Opcode::GetElementPtr, 1950 I, Ctx) {} GetElementPtrInst(ClassID SubclassID,llvm::Instruction * I,Context & Ctx)1951 GetElementPtrInst(ClassID SubclassID, llvm::Instruction *I, Context &Ctx) 1952 : SingleLLVMInstructionImpl(SubclassID, Opcode::GetElementPtr, I, Ctx) {} 1953 friend class Context; // For accessing the constructor in 1954 // create*() 1955 1956 public: 1957 static Value *create(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList, 1958 BBIterator WhereIt, BasicBlock *WhereBB, Context &Ctx, 1959 const Twine &NameStr = ""); 1960 static Value *create(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList, 1961 Instruction *InsertBefore, Context &Ctx, 1962 const Twine &NameStr = ""); 1963 static Value *create(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList, 1964 BasicBlock *InsertAtEnd, Context &Ctx, 1965 const Twine &NameStr = ""); 1966 classof(const Value * From)1967 static bool classof(const Value *From) { 1968 return From->getSubclassID() == ClassID::GetElementPtr; 1969 } 1970 getSourceElementType()1971 Type *getSourceElementType() const { 1972 return cast<llvm::GetElementPtrInst>(Val)->getSourceElementType(); 1973 } getResultElementType()1974 Type *getResultElementType() const { 1975 return cast<llvm::GetElementPtrInst>(Val)->getResultElementType(); 1976 } getAddressSpace()1977 unsigned getAddressSpace() const { 1978 return cast<llvm::GetElementPtrInst>(Val)->getAddressSpace(); 1979 } 1980 idx_begin()1981 inline op_iterator idx_begin() { return op_begin() + 1; } idx_begin()1982 inline const_op_iterator idx_begin() const { 1983 return const_cast<GetElementPtrInst *>(this)->idx_begin(); 1984 } idx_end()1985 inline op_iterator idx_end() { return op_end(); } idx_end()1986 inline const_op_iterator idx_end() const { 1987 return const_cast<GetElementPtrInst *>(this)->idx_end(); 1988 } indices()1989 inline iterator_range<op_iterator> indices() { 1990 return make_range(idx_begin(), idx_end()); 1991 } indices()1992 inline iterator_range<const_op_iterator> indices() const { 1993 return const_cast<GetElementPtrInst *>(this)->indices(); 1994 } 1995 1996 Value *getPointerOperand() const; getPointerOperandIndex()1997 static unsigned getPointerOperandIndex() { 1998 return llvm::GetElementPtrInst::getPointerOperandIndex(); 1999 } getPointerOperandType()2000 Type *getPointerOperandType() const { 2001 return cast<llvm::GetElementPtrInst>(Val)->getPointerOperandType(); 2002 } getPointerAddressSpace()2003 unsigned getPointerAddressSpace() const { 2004 return cast<llvm::GetElementPtrInst>(Val)->getPointerAddressSpace(); 2005 } getNumIndices()2006 unsigned getNumIndices() const { 2007 return cast<llvm::GetElementPtrInst>(Val)->getNumIndices(); 2008 } hasIndices()2009 bool hasIndices() const { 2010 return cast<llvm::GetElementPtrInst>(Val)->hasIndices(); 2011 } hasAllConstantIndices()2012 bool hasAllConstantIndices() const { 2013 return cast<llvm::GetElementPtrInst>(Val)->hasAllConstantIndices(); 2014 } getNoWrapFlags()2015 GEPNoWrapFlags getNoWrapFlags() const { 2016 return cast<llvm::GetElementPtrInst>(Val)->getNoWrapFlags(); 2017 } isInBounds()2018 bool isInBounds() const { 2019 return cast<llvm::GetElementPtrInst>(Val)->isInBounds(); 2020 } hasNoUnsignedSignedWrap()2021 bool hasNoUnsignedSignedWrap() const { 2022 return cast<llvm::GetElementPtrInst>(Val)->hasNoUnsignedSignedWrap(); 2023 } hasNoUnsignedWrap()2024 bool hasNoUnsignedWrap() const { 2025 return cast<llvm::GetElementPtrInst>(Val)->hasNoUnsignedWrap(); 2026 } accumulateConstantOffset(const DataLayout & DL,APInt & Offset)2027 bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const { 2028 return cast<llvm::GetElementPtrInst>(Val)->accumulateConstantOffset(DL, 2029 Offset); 2030 } 2031 // TODO: Add missing member functions. 2032 }; 2033 2034 class CatchSwitchInst 2035 : public SingleLLVMInstructionImpl<llvm::CatchSwitchInst> { 2036 public: CatchSwitchInst(llvm::CatchSwitchInst * CSI,Context & Ctx)2037 CatchSwitchInst(llvm::CatchSwitchInst *CSI, Context &Ctx) 2038 : SingleLLVMInstructionImpl(ClassID::CatchSwitch, Opcode::CatchSwitch, 2039 CSI, Ctx) {} 2040 2041 static CatchSwitchInst *create(Value *ParentPad, BasicBlock *UnwindBB, 2042 unsigned NumHandlers, BBIterator WhereIt, 2043 BasicBlock *WhereBB, Context &Ctx, 2044 const Twine &Name = ""); 2045 2046 Value *getParentPad() const; 2047 void setParentPad(Value *ParentPad); 2048 hasUnwindDest()2049 bool hasUnwindDest() const { 2050 return cast<llvm::CatchSwitchInst>(Val)->hasUnwindDest(); 2051 } unwindsToCaller()2052 bool unwindsToCaller() const { 2053 return cast<llvm::CatchSwitchInst>(Val)->unwindsToCaller(); 2054 } 2055 BasicBlock *getUnwindDest() const; 2056 void setUnwindDest(BasicBlock *UnwindDest); 2057 getNumHandlers()2058 unsigned getNumHandlers() const { 2059 return cast<llvm::CatchSwitchInst>(Val)->getNumHandlers(); 2060 } 2061 2062 private: handler_helper(Value * V)2063 static BasicBlock *handler_helper(Value *V) { return cast<BasicBlock>(V); } handler_helper(const Value * V)2064 static const BasicBlock *handler_helper(const Value *V) { 2065 return cast<BasicBlock>(V); 2066 } 2067 2068 public: 2069 using DerefFnTy = BasicBlock *(*)(Value *); 2070 using handler_iterator = mapped_iterator<op_iterator, DerefFnTy>; 2071 using handler_range = iterator_range<handler_iterator>; 2072 using ConstDerefFnTy = const BasicBlock *(*)(const Value *); 2073 using const_handler_iterator = 2074 mapped_iterator<const_op_iterator, ConstDerefFnTy>; 2075 using const_handler_range = iterator_range<const_handler_iterator>; 2076 handler_begin()2077 handler_iterator handler_begin() { 2078 op_iterator It = op_begin() + 1; 2079 if (hasUnwindDest()) 2080 ++It; 2081 return handler_iterator(It, DerefFnTy(handler_helper)); 2082 } handler_begin()2083 const_handler_iterator handler_begin() const { 2084 const_op_iterator It = op_begin() + 1; 2085 if (hasUnwindDest()) 2086 ++It; 2087 return const_handler_iterator(It, ConstDerefFnTy(handler_helper)); 2088 } handler_end()2089 handler_iterator handler_end() { 2090 return handler_iterator(op_end(), DerefFnTy(handler_helper)); 2091 } handler_end()2092 const_handler_iterator handler_end() const { 2093 return const_handler_iterator(op_end(), ConstDerefFnTy(handler_helper)); 2094 } handlers()2095 handler_range handlers() { 2096 return make_range(handler_begin(), handler_end()); 2097 } handlers()2098 const_handler_range handlers() const { 2099 return make_range(handler_begin(), handler_end()); 2100 } 2101 2102 void addHandler(BasicBlock *Dest); 2103 2104 // TODO: removeHandler() cannot be reverted because there is no equivalent 2105 // addHandler() with a handler_iterator to specify the position. So we can't 2106 // implement it for now. 2107 getNumSuccessors()2108 unsigned getNumSuccessors() const { return getNumOperands() - 1; } getSuccessor(unsigned Idx)2109 BasicBlock *getSuccessor(unsigned Idx) const { 2110 assert(Idx < getNumSuccessors() && 2111 "Successor # out of range for catchswitch!"); 2112 return cast<BasicBlock>(getOperand(Idx + 1)); 2113 } setSuccessor(unsigned Idx,BasicBlock * NewSucc)2114 void setSuccessor(unsigned Idx, BasicBlock *NewSucc) { 2115 assert(Idx < getNumSuccessors() && 2116 "Successor # out of range for catchswitch!"); 2117 setOperand(Idx + 1, NewSucc); 2118 } 2119 classof(const Value * From)2120 static bool classof(const Value *From) { 2121 return From->getSubclassID() == ClassID::CatchSwitch; 2122 } 2123 }; 2124 2125 class SwitchInst : public SingleLLVMInstructionImpl<llvm::SwitchInst> { 2126 public: SwitchInst(llvm::SwitchInst * SI,Context & Ctx)2127 SwitchInst(llvm::SwitchInst *SI, Context &Ctx) 2128 : SingleLLVMInstructionImpl(ClassID::Switch, Opcode::Switch, SI, Ctx) {} 2129 2130 static constexpr const unsigned DefaultPseudoIndex = 2131 llvm::SwitchInst::DefaultPseudoIndex; 2132 2133 static SwitchInst *create(Value *V, BasicBlock *Dest, unsigned NumCases, 2134 BasicBlock::iterator WhereIt, BasicBlock *WhereBB, 2135 Context &Ctx, const Twine &Name = ""); 2136 2137 Value *getCondition() const; 2138 void setCondition(Value *V); 2139 BasicBlock *getDefaultDest() const; defaultDestUndefined()2140 bool defaultDestUndefined() const { 2141 return cast<llvm::SwitchInst>(Val)->defaultDestUndefined(); 2142 } 2143 void setDefaultDest(BasicBlock *DefaultCase); getNumCases()2144 unsigned getNumCases() const { 2145 return cast<llvm::SwitchInst>(Val)->getNumCases(); 2146 } 2147 2148 using CaseHandle = 2149 llvm::SwitchInst::CaseHandleImpl<SwitchInst, ConstantInt, BasicBlock>; 2150 using ConstCaseHandle = 2151 llvm::SwitchInst::CaseHandleImpl<const SwitchInst, const ConstantInt, 2152 const BasicBlock>; 2153 using CaseIt = llvm::SwitchInst::CaseIteratorImpl<CaseHandle>; 2154 using ConstCaseIt = llvm::SwitchInst::CaseIteratorImpl<ConstCaseHandle>; 2155 2156 /// Returns a read/write iterator that points to the first case in the 2157 /// SwitchInst. case_begin()2158 CaseIt case_begin() { return CaseIt(this, 0); } case_begin()2159 ConstCaseIt case_begin() const { return ConstCaseIt(this, 0); } 2160 /// Returns a read/write iterator that points one past the last in the 2161 /// SwitchInst. case_end()2162 CaseIt case_end() { return CaseIt(this, getNumCases()); } case_end()2163 ConstCaseIt case_end() const { return ConstCaseIt(this, getNumCases()); } 2164 /// Iteration adapter for range-for loops. cases()2165 iterator_range<CaseIt> cases() { 2166 return make_range(case_begin(), case_end()); 2167 } cases()2168 iterator_range<ConstCaseIt> cases() const { 2169 return make_range(case_begin(), case_end()); 2170 } case_default()2171 CaseIt case_default() { return CaseIt(this, DefaultPseudoIndex); } case_default()2172 ConstCaseIt case_default() const { 2173 return ConstCaseIt(this, DefaultPseudoIndex); 2174 } findCaseValue(const ConstantInt * C)2175 CaseIt findCaseValue(const ConstantInt *C) { 2176 return CaseIt( 2177 this, 2178 const_cast<const SwitchInst *>(this)->findCaseValue(C)->getCaseIndex()); 2179 } findCaseValue(const ConstantInt * C)2180 ConstCaseIt findCaseValue(const ConstantInt *C) const { 2181 ConstCaseIt I = llvm::find_if(cases(), [C](const ConstCaseHandle &Case) { 2182 return Case.getCaseValue() == C; 2183 }); 2184 if (I != case_end()) 2185 return I; 2186 return case_default(); 2187 } 2188 ConstantInt *findCaseDest(BasicBlock *BB); 2189 2190 void addCase(ConstantInt *OnVal, BasicBlock *Dest); 2191 /// This method removes the specified case and its successor from the switch 2192 /// instruction. Note that this operation may reorder the remaining cases at 2193 /// index idx and above. 2194 /// Note: 2195 /// This action invalidates iterators for all cases following the one removed, 2196 /// including the case_end() iterator. It returns an iterator for the next 2197 /// case. 2198 CaseIt removeCase(CaseIt It); 2199 getNumSuccessors()2200 unsigned getNumSuccessors() const { 2201 return cast<llvm::SwitchInst>(Val)->getNumSuccessors(); 2202 } 2203 BasicBlock *getSuccessor(unsigned Idx) const; 2204 void setSuccessor(unsigned Idx, BasicBlock *NewSucc); classof(const Value * From)2205 static bool classof(const Value *From) { 2206 return From->getSubclassID() == ClassID::Switch; 2207 } 2208 }; 2209 2210 class UnaryOperator : public UnaryInstruction { getUnaryOpcode(llvm::Instruction::UnaryOps UnOp)2211 static Opcode getUnaryOpcode(llvm::Instruction::UnaryOps UnOp) { 2212 switch (UnOp) { 2213 case llvm::Instruction::FNeg: 2214 return Opcode::FNeg; 2215 case llvm::Instruction::UnaryOpsEnd: 2216 llvm_unreachable("Bad UnOp!"); 2217 } 2218 llvm_unreachable("Unhandled UnOp!"); 2219 } UnaryOperator(llvm::UnaryOperator * UO,Context & Ctx)2220 UnaryOperator(llvm::UnaryOperator *UO, Context &Ctx) 2221 : UnaryInstruction(ClassID::UnOp, getUnaryOpcode(UO->getOpcode()), UO, 2222 Ctx) {} 2223 friend Context; // for constructor. 2224 public: 2225 static Value *create(Instruction::Opcode Op, Value *OpV, BBIterator WhereIt, 2226 BasicBlock *WhereBB, Context &Ctx, 2227 const Twine &Name = ""); 2228 static Value *create(Instruction::Opcode Op, Value *OpV, 2229 Instruction *InsertBefore, Context &Ctx, 2230 const Twine &Name = ""); 2231 static Value *create(Instruction::Opcode Op, Value *OpV, 2232 BasicBlock *InsertAtEnd, Context &Ctx, 2233 const Twine &Name = ""); 2234 static Value *createWithCopiedFlags(Instruction::Opcode Op, Value *OpV, 2235 Value *CopyFrom, BBIterator WhereIt, 2236 BasicBlock *WhereBB, Context &Ctx, 2237 const Twine &Name = ""); 2238 static Value *createWithCopiedFlags(Instruction::Opcode Op, Value *OpV, 2239 Value *CopyFrom, 2240 Instruction *InsertBefore, Context &Ctx, 2241 const Twine &Name = ""); 2242 static Value *createWithCopiedFlags(Instruction::Opcode Op, Value *OpV, 2243 Value *CopyFrom, BasicBlock *InsertAtEnd, 2244 Context &Ctx, const Twine &Name = ""); 2245 /// For isa/dyn_cast. classof(const Value * From)2246 static bool classof(const Value *From) { 2247 return From->getSubclassID() == ClassID::UnOp; 2248 } 2249 }; 2250 2251 class BinaryOperator : public SingleLLVMInstructionImpl<llvm::BinaryOperator> { getBinOpOpcode(llvm::Instruction::BinaryOps BinOp)2252 static Opcode getBinOpOpcode(llvm::Instruction::BinaryOps BinOp) { 2253 switch (BinOp) { 2254 case llvm::Instruction::Add: 2255 return Opcode::Add; 2256 case llvm::Instruction::FAdd: 2257 return Opcode::FAdd; 2258 case llvm::Instruction::Sub: 2259 return Opcode::Sub; 2260 case llvm::Instruction::FSub: 2261 return Opcode::FSub; 2262 case llvm::Instruction::Mul: 2263 return Opcode::Mul; 2264 case llvm::Instruction::FMul: 2265 return Opcode::FMul; 2266 case llvm::Instruction::UDiv: 2267 return Opcode::UDiv; 2268 case llvm::Instruction::SDiv: 2269 return Opcode::SDiv; 2270 case llvm::Instruction::FDiv: 2271 return Opcode::FDiv; 2272 case llvm::Instruction::URem: 2273 return Opcode::URem; 2274 case llvm::Instruction::SRem: 2275 return Opcode::SRem; 2276 case llvm::Instruction::FRem: 2277 return Opcode::FRem; 2278 case llvm::Instruction::Shl: 2279 return Opcode::Shl; 2280 case llvm::Instruction::LShr: 2281 return Opcode::LShr; 2282 case llvm::Instruction::AShr: 2283 return Opcode::AShr; 2284 case llvm::Instruction::And: 2285 return Opcode::And; 2286 case llvm::Instruction::Or: 2287 return Opcode::Or; 2288 case llvm::Instruction::Xor: 2289 return Opcode::Xor; 2290 case llvm::Instruction::BinaryOpsEnd: 2291 llvm_unreachable("Bad BinOp!"); 2292 } 2293 llvm_unreachable("Unhandled BinOp!"); 2294 } BinaryOperator(llvm::BinaryOperator * BinOp,Context & Ctx)2295 BinaryOperator(llvm::BinaryOperator *BinOp, Context &Ctx) 2296 : SingleLLVMInstructionImpl(ClassID::BinaryOperator, 2297 getBinOpOpcode(BinOp->getOpcode()), BinOp, 2298 Ctx) {} 2299 friend class Context; // For constructor. 2300 2301 public: 2302 static Value *create(Instruction::Opcode Op, Value *LHS, Value *RHS, 2303 BBIterator WhereIt, BasicBlock *WhereBB, Context &Ctx, 2304 const Twine &Name = ""); 2305 static Value *create(Instruction::Opcode Op, Value *LHS, Value *RHS, 2306 Instruction *InsertBefore, Context &Ctx, 2307 const Twine &Name = ""); 2308 static Value *create(Instruction::Opcode Op, Value *LHS, Value *RHS, 2309 BasicBlock *InsertAtEnd, Context &Ctx, 2310 const Twine &Name = ""); 2311 2312 static Value *createWithCopiedFlags(Instruction::Opcode Op, Value *LHS, 2313 Value *RHS, Value *CopyFrom, 2314 BBIterator WhereIt, BasicBlock *WhereBB, 2315 Context &Ctx, const Twine &Name = ""); 2316 static Value *createWithCopiedFlags(Instruction::Opcode Op, Value *LHS, 2317 Value *RHS, Value *CopyFrom, 2318 Instruction *InsertBefore, Context &Ctx, 2319 const Twine &Name = ""); 2320 static Value *createWithCopiedFlags(Instruction::Opcode Op, Value *LHS, 2321 Value *RHS, Value *CopyFrom, 2322 BasicBlock *InsertAtEnd, Context &Ctx, 2323 const Twine &Name = ""); 2324 /// For isa/dyn_cast. classof(const Value * From)2325 static bool classof(const Value *From) { 2326 return From->getSubclassID() == ClassID::BinaryOperator; 2327 } swapOperands()2328 void swapOperands() { swapOperandsInternal(0, 1); } 2329 }; 2330 2331 class AtomicRMWInst : public SingleLLVMInstructionImpl<llvm::AtomicRMWInst> { AtomicRMWInst(llvm::AtomicRMWInst * Atomic,Context & Ctx)2332 AtomicRMWInst(llvm::AtomicRMWInst *Atomic, Context &Ctx) 2333 : SingleLLVMInstructionImpl(ClassID::AtomicRMW, 2334 Instruction::Opcode::AtomicRMW, Atomic, Ctx) { 2335 } 2336 friend class Context; // For constructor. 2337 2338 public: 2339 using BinOp = llvm::AtomicRMWInst::BinOp; getOperation()2340 BinOp getOperation() const { 2341 return cast<llvm::AtomicRMWInst>(Val)->getOperation(); 2342 } getOperationName(BinOp Op)2343 static StringRef getOperationName(BinOp Op) { 2344 return llvm::AtomicRMWInst::getOperationName(Op); 2345 } isFPOperation(BinOp Op)2346 static bool isFPOperation(BinOp Op) { 2347 return llvm::AtomicRMWInst::isFPOperation(Op); 2348 } setOperation(BinOp Op)2349 void setOperation(BinOp Op) { 2350 cast<llvm::AtomicRMWInst>(Val)->setOperation(Op); 2351 } getAlign()2352 Align getAlign() const { return cast<llvm::AtomicRMWInst>(Val)->getAlign(); } 2353 void setAlignment(Align Align); isVolatile()2354 bool isVolatile() const { 2355 return cast<llvm::AtomicRMWInst>(Val)->isVolatile(); 2356 } 2357 void setVolatile(bool V); getOrdering()2358 AtomicOrdering getOrdering() const { 2359 return cast<llvm::AtomicRMWInst>(Val)->getOrdering(); 2360 } 2361 void setOrdering(AtomicOrdering Ordering); getSyncScopeID()2362 SyncScope::ID getSyncScopeID() const { 2363 return cast<llvm::AtomicRMWInst>(Val)->getSyncScopeID(); 2364 } 2365 void setSyncScopeID(SyncScope::ID SSID); 2366 Value *getPointerOperand(); getPointerOperand()2367 const Value *getPointerOperand() const { 2368 return const_cast<AtomicRMWInst *>(this)->getPointerOperand(); 2369 } 2370 Value *getValOperand(); getValOperand()2371 const Value *getValOperand() const { 2372 return const_cast<AtomicRMWInst *>(this)->getValOperand(); 2373 } getPointerAddressSpace()2374 unsigned getPointerAddressSpace() const { 2375 return cast<llvm::AtomicRMWInst>(Val)->getPointerAddressSpace(); 2376 } isFloatingPointOperation()2377 bool isFloatingPointOperation() const { 2378 return cast<llvm::AtomicRMWInst>(Val)->isFloatingPointOperation(); 2379 } classof(const Value * From)2380 static bool classof(const Value *From) { 2381 return From->getSubclassID() == ClassID::AtomicRMW; 2382 } 2383 2384 static AtomicRMWInst *create(BinOp Op, Value *Ptr, Value *Val, 2385 MaybeAlign Align, AtomicOrdering Ordering, 2386 BBIterator WhereIt, BasicBlock *WhereBB, 2387 Context &Ctx, 2388 SyncScope::ID SSID = SyncScope::System, 2389 const Twine &Name = ""); 2390 static AtomicRMWInst *create(BinOp Op, Value *Ptr, Value *Val, 2391 MaybeAlign Align, AtomicOrdering Ordering, 2392 Instruction *InsertBefore, Context &Ctx, 2393 SyncScope::ID SSID = SyncScope::System, 2394 const Twine &Name = ""); 2395 static AtomicRMWInst *create(BinOp Op, Value *Ptr, Value *Val, 2396 MaybeAlign Align, AtomicOrdering Ordering, 2397 BasicBlock *InsertAtEnd, Context &Ctx, 2398 SyncScope::ID SSID = SyncScope::System, 2399 const Twine &Name = ""); 2400 }; 2401 2402 class AtomicCmpXchgInst 2403 : public SingleLLVMInstructionImpl<llvm::AtomicCmpXchgInst> { AtomicCmpXchgInst(llvm::AtomicCmpXchgInst * Atomic,Context & Ctx)2404 AtomicCmpXchgInst(llvm::AtomicCmpXchgInst *Atomic, Context &Ctx) 2405 : SingleLLVMInstructionImpl(ClassID::AtomicCmpXchg, 2406 Instruction::Opcode::AtomicCmpXchg, Atomic, 2407 Ctx) {} 2408 friend class Context; // For constructor. 2409 2410 public: 2411 /// Return the alignment of the memory that is being allocated by the 2412 /// instruction. getAlign()2413 Align getAlign() const { 2414 return cast<llvm::AtomicCmpXchgInst>(Val)->getAlign(); 2415 } 2416 2417 void setAlignment(Align Align); 2418 /// Return true if this is a cmpxchg from a volatile memory 2419 /// location. isVolatile()2420 bool isVolatile() const { 2421 return cast<llvm::AtomicCmpXchgInst>(Val)->isVolatile(); 2422 } 2423 /// Specify whether this is a volatile cmpxchg. 2424 void setVolatile(bool V); 2425 /// Return true if this cmpxchg may spuriously fail. isWeak()2426 bool isWeak() const { return cast<llvm::AtomicCmpXchgInst>(Val)->isWeak(); } 2427 void setWeak(bool IsWeak); isValidSuccessOrdering(AtomicOrdering Ordering)2428 static bool isValidSuccessOrdering(AtomicOrdering Ordering) { 2429 return llvm::AtomicCmpXchgInst::isValidSuccessOrdering(Ordering); 2430 } isValidFailureOrdering(AtomicOrdering Ordering)2431 static bool isValidFailureOrdering(AtomicOrdering Ordering) { 2432 return llvm::AtomicCmpXchgInst::isValidFailureOrdering(Ordering); 2433 } getSuccessOrdering()2434 AtomicOrdering getSuccessOrdering() const { 2435 return cast<llvm::AtomicCmpXchgInst>(Val)->getSuccessOrdering(); 2436 } 2437 void setSuccessOrdering(AtomicOrdering Ordering); 2438 getFailureOrdering()2439 AtomicOrdering getFailureOrdering() const { 2440 return cast<llvm::AtomicCmpXchgInst>(Val)->getFailureOrdering(); 2441 } 2442 void setFailureOrdering(AtomicOrdering Ordering); getMergedOrdering()2443 AtomicOrdering getMergedOrdering() const { 2444 return cast<llvm::AtomicCmpXchgInst>(Val)->getMergedOrdering(); 2445 } getSyncScopeID()2446 SyncScope::ID getSyncScopeID() const { 2447 return cast<llvm::AtomicCmpXchgInst>(Val)->getSyncScopeID(); 2448 } 2449 void setSyncScopeID(SyncScope::ID SSID); 2450 Value *getPointerOperand(); getPointerOperand()2451 const Value *getPointerOperand() const { 2452 return const_cast<AtomicCmpXchgInst *>(this)->getPointerOperand(); 2453 } 2454 2455 Value *getCompareOperand(); getCompareOperand()2456 const Value *getCompareOperand() const { 2457 return const_cast<AtomicCmpXchgInst *>(this)->getCompareOperand(); 2458 } 2459 2460 Value *getNewValOperand(); getNewValOperand()2461 const Value *getNewValOperand() const { 2462 return const_cast<AtomicCmpXchgInst *>(this)->getNewValOperand(); 2463 } 2464 2465 /// Returns the address space of the pointer operand. getPointerAddressSpace()2466 unsigned getPointerAddressSpace() const { 2467 return cast<llvm::AtomicCmpXchgInst>(Val)->getPointerAddressSpace(); 2468 } 2469 2470 static AtomicCmpXchgInst * 2471 create(Value *Ptr, Value *Cmp, Value *New, MaybeAlign Align, 2472 AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering, 2473 BBIterator WhereIt, BasicBlock *WhereBB, Context &Ctx, 2474 SyncScope::ID SSID = SyncScope::System, const Twine &Name = ""); 2475 static AtomicCmpXchgInst * 2476 create(Value *Ptr, Value *Cmp, Value *New, MaybeAlign Align, 2477 AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering, 2478 Instruction *InsertBefore, Context &Ctx, 2479 SyncScope::ID SSID = SyncScope::System, const Twine &Name = ""); 2480 static AtomicCmpXchgInst * 2481 create(Value *Ptr, Value *Cmp, Value *New, MaybeAlign Align, 2482 AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering, 2483 BasicBlock *InsertAtEnd, Context &Ctx, 2484 SyncScope::ID SSID = SyncScope::System, const Twine &Name = ""); 2485 }; 2486 2487 class AllocaInst final : public UnaryInstruction { AllocaInst(llvm::AllocaInst * AI,Context & Ctx)2488 AllocaInst(llvm::AllocaInst *AI, Context &Ctx) 2489 : UnaryInstruction(ClassID::Alloca, Instruction::Opcode::Alloca, AI, 2490 Ctx) {} 2491 friend class Context; // For constructor. 2492 2493 public: 2494 static AllocaInst *create(Type *Ty, unsigned AddrSpace, BBIterator WhereIt, 2495 BasicBlock *WhereBB, Context &Ctx, 2496 Value *ArraySize = nullptr, const Twine &Name = ""); 2497 static AllocaInst *create(Type *Ty, unsigned AddrSpace, 2498 Instruction *InsertBefore, Context &Ctx, 2499 Value *ArraySize = nullptr, const Twine &Name = ""); 2500 static AllocaInst *create(Type *Ty, unsigned AddrSpace, 2501 BasicBlock *InsertAtEnd, Context &Ctx, 2502 Value *ArraySize = nullptr, const Twine &Name = ""); 2503 2504 /// Return true if there is an allocation size parameter to the allocation 2505 /// instruction that is not 1. isArrayAllocation()2506 bool isArrayAllocation() const { 2507 return cast<llvm::AllocaInst>(Val)->isArrayAllocation(); 2508 } 2509 /// Get the number of elements allocated. For a simple allocation of a single 2510 /// element, this will return a constant 1 value. 2511 Value *getArraySize(); getArraySize()2512 const Value *getArraySize() const { 2513 return const_cast<AllocaInst *>(this)->getArraySize(); 2514 } 2515 /// Overload to return most specific pointer type. getType()2516 PointerType *getType() const { 2517 return cast<llvm::AllocaInst>(Val)->getType(); 2518 } 2519 /// Return the address space for the allocation. getAddressSpace()2520 unsigned getAddressSpace() const { 2521 return cast<llvm::AllocaInst>(Val)->getAddressSpace(); 2522 } 2523 /// Get allocation size in bytes. Returns std::nullopt if size can't be 2524 /// determined, e.g. in case of a VLA. getAllocationSize(const DataLayout & DL)2525 std::optional<TypeSize> getAllocationSize(const DataLayout &DL) const { 2526 return cast<llvm::AllocaInst>(Val)->getAllocationSize(DL); 2527 } 2528 /// Get allocation size in bits. Returns std::nullopt if size can't be 2529 /// determined, e.g. in case of a VLA. getAllocationSizeInBits(const DataLayout & DL)2530 std::optional<TypeSize> getAllocationSizeInBits(const DataLayout &DL) const { 2531 return cast<llvm::AllocaInst>(Val)->getAllocationSizeInBits(DL); 2532 } 2533 /// Return the type that is being allocated by the instruction. getAllocatedType()2534 Type *getAllocatedType() const { 2535 return cast<llvm::AllocaInst>(Val)->getAllocatedType(); 2536 } 2537 /// for use only in special circumstances that need to generically 2538 /// transform a whole instruction (eg: IR linking and vectorization). 2539 void setAllocatedType(Type *Ty); 2540 /// Return the alignment of the memory that is being allocated by the 2541 /// instruction. getAlign()2542 Align getAlign() const { return cast<llvm::AllocaInst>(Val)->getAlign(); } 2543 void setAlignment(Align Align); 2544 /// Return true if this alloca is in the entry block of the function and is a 2545 /// constant size. If so, the code generator will fold it into the 2546 /// prolog/epilog code, so it is basically free. isStaticAlloca()2547 bool isStaticAlloca() const { 2548 return cast<llvm::AllocaInst>(Val)->isStaticAlloca(); 2549 } 2550 /// Return true if this alloca is used as an inalloca argument to a call. Such 2551 /// allocas are never considered static even if they are in the entry block. isUsedWithInAlloca()2552 bool isUsedWithInAlloca() const { 2553 return cast<llvm::AllocaInst>(Val)->isUsedWithInAlloca(); 2554 } 2555 /// Specify whether this alloca is used to represent the arguments to a call. 2556 void setUsedWithInAlloca(bool V); 2557 classof(const Value * From)2558 static bool classof(const Value *From) { 2559 if (auto *I = dyn_cast<Instruction>(From)) 2560 return I->getSubclassID() == Instruction::ClassID::Alloca; 2561 return false; 2562 } 2563 }; 2564 2565 class CastInst : public UnaryInstruction { getCastOpcode(llvm::Instruction::CastOps CastOp)2566 static Opcode getCastOpcode(llvm::Instruction::CastOps CastOp) { 2567 switch (CastOp) { 2568 case llvm::Instruction::ZExt: 2569 return Opcode::ZExt; 2570 case llvm::Instruction::SExt: 2571 return Opcode::SExt; 2572 case llvm::Instruction::FPToUI: 2573 return Opcode::FPToUI; 2574 case llvm::Instruction::FPToSI: 2575 return Opcode::FPToSI; 2576 case llvm::Instruction::FPExt: 2577 return Opcode::FPExt; 2578 case llvm::Instruction::PtrToInt: 2579 return Opcode::PtrToInt; 2580 case llvm::Instruction::IntToPtr: 2581 return Opcode::IntToPtr; 2582 case llvm::Instruction::SIToFP: 2583 return Opcode::SIToFP; 2584 case llvm::Instruction::UIToFP: 2585 return Opcode::UIToFP; 2586 case llvm::Instruction::Trunc: 2587 return Opcode::Trunc; 2588 case llvm::Instruction::FPTrunc: 2589 return Opcode::FPTrunc; 2590 case llvm::Instruction::BitCast: 2591 return Opcode::BitCast; 2592 case llvm::Instruction::AddrSpaceCast: 2593 return Opcode::AddrSpaceCast; 2594 case llvm::Instruction::CastOpsEnd: 2595 llvm_unreachable("Bad CastOp!"); 2596 } 2597 llvm_unreachable("Unhandled CastOp!"); 2598 } 2599 /// Use Context::createCastInst(). Don't call the 2600 /// constructor directly. CastInst(llvm::CastInst * CI,Context & Ctx)2601 CastInst(llvm::CastInst *CI, Context &Ctx) 2602 : UnaryInstruction(ClassID::Cast, getCastOpcode(CI->getOpcode()), CI, 2603 Ctx) {} 2604 friend Context; // for SBCastInstruction() 2605 2606 public: 2607 static Value *create(Type *DestTy, Opcode Op, Value *Operand, 2608 BBIterator WhereIt, BasicBlock *WhereBB, Context &Ctx, 2609 const Twine &Name = ""); 2610 static Value *create(Type *DestTy, Opcode Op, Value *Operand, 2611 Instruction *InsertBefore, Context &Ctx, 2612 const Twine &Name = ""); 2613 static Value *create(Type *DestTy, Opcode Op, Value *Operand, 2614 BasicBlock *InsertAtEnd, Context &Ctx, 2615 const Twine &Name = ""); 2616 /// For isa/dyn_cast. 2617 static bool classof(const Value *From); getSrcTy()2618 Type *getSrcTy() const { return cast<llvm::CastInst>(Val)->getSrcTy(); } getDestTy()2619 Type *getDestTy() const { return cast<llvm::CastInst>(Val)->getDestTy(); } 2620 }; 2621 2622 // Helper class to simplify stamping out CastInst subclasses. 2623 template <Instruction::Opcode Op> class CastInstImpl : public CastInst { 2624 public: 2625 static Value *create(Value *Src, Type *DestTy, BBIterator WhereIt, 2626 BasicBlock *WhereBB, Context &Ctx, 2627 const Twine &Name = "") { 2628 return CastInst::create(DestTy, Op, Src, WhereIt, WhereBB, Ctx, Name); 2629 } 2630 static Value *create(Value *Src, Type *DestTy, Instruction *InsertBefore, 2631 Context &Ctx, const Twine &Name = "") { 2632 return create(Src, DestTy, InsertBefore->getIterator(), 2633 InsertBefore->getParent(), Ctx, Name); 2634 } 2635 static Value *create(Value *Src, Type *DestTy, BasicBlock *InsertAtEnd, 2636 Context &Ctx, const Twine &Name = "") { 2637 return create(Src, DestTy, InsertAtEnd->end(), InsertAtEnd, Ctx, Name); 2638 } 2639 classof(const Value * From)2640 static bool classof(const Value *From) { 2641 if (auto *I = dyn_cast<Instruction>(From)) 2642 return I->getOpcode() == Op; 2643 return false; 2644 } 2645 }; 2646 2647 class TruncInst final : public CastInstImpl<Instruction::Opcode::Trunc> {}; 2648 class ZExtInst final : public CastInstImpl<Instruction::Opcode::ZExt> {}; 2649 class SExtInst final : public CastInstImpl<Instruction::Opcode::SExt> {}; 2650 class FPTruncInst final : public CastInstImpl<Instruction::Opcode::FPTrunc> {}; 2651 class FPExtInst final : public CastInstImpl<Instruction::Opcode::FPExt> {}; 2652 class UIToFPInst final : public CastInstImpl<Instruction::Opcode::UIToFP> {}; 2653 class SIToFPInst final : public CastInstImpl<Instruction::Opcode::SIToFP> {}; 2654 class FPToUIInst final : public CastInstImpl<Instruction::Opcode::FPToUI> {}; 2655 class FPToSIInst final : public CastInstImpl<Instruction::Opcode::FPToSI> {}; 2656 class IntToPtrInst final : public CastInstImpl<Instruction::Opcode::IntToPtr> { 2657 }; 2658 class PtrToIntInst final : public CastInstImpl<Instruction::Opcode::PtrToInt> { 2659 }; 2660 class BitCastInst final : public CastInstImpl<Instruction::Opcode::BitCast> {}; 2661 class AddrSpaceCastInst final 2662 : public CastInstImpl<Instruction::Opcode::AddrSpaceCast> { 2663 public: 2664 /// \Returns the pointer operand. getPointerOperand()2665 Value *getPointerOperand() { return getOperand(0); } 2666 /// \Returns the pointer operand. getPointerOperand()2667 const Value *getPointerOperand() const { 2668 return const_cast<AddrSpaceCastInst *>(this)->getPointerOperand(); 2669 } 2670 /// \Returns the operand index of the pointer operand. getPointerOperandIndex()2671 static unsigned getPointerOperandIndex() { return 0u; } 2672 /// \Returns the address space of the pointer operand. getSrcAddressSpace()2673 unsigned getSrcAddressSpace() const { 2674 return getPointerOperand()->getType()->getPointerAddressSpace(); 2675 } 2676 /// \Returns the address space of the result. getDestAddressSpace()2677 unsigned getDestAddressSpace() const { 2678 return getType()->getPointerAddressSpace(); 2679 } 2680 }; 2681 2682 class PHINode final : public SingleLLVMInstructionImpl<llvm::PHINode> { 2683 /// Use Context::createPHINode(). Don't call the constructor directly. PHINode(llvm::PHINode * PHI,Context & Ctx)2684 PHINode(llvm::PHINode *PHI, Context &Ctx) 2685 : SingleLLVMInstructionImpl(ClassID::PHI, Opcode::PHI, PHI, Ctx) {} 2686 friend Context; // for PHINode() 2687 /// Helper for mapped_iterator. 2688 struct LLVMBBToBB { 2689 Context &Ctx; LLVMBBToBBLLVMBBToBB2690 LLVMBBToBB(Context &Ctx) : Ctx(Ctx) {} 2691 BasicBlock *operator()(llvm::BasicBlock *LLVMBB) const; 2692 }; 2693 2694 public: 2695 static PHINode *create(Type *Ty, unsigned NumReservedValues, 2696 Instruction *InsertBefore, Context &Ctx, 2697 const Twine &Name = ""); 2698 /// For isa/dyn_cast. 2699 static bool classof(const Value *From); 2700 2701 using const_block_iterator = 2702 mapped_iterator<llvm::PHINode::const_block_iterator, LLVMBBToBB>; 2703 block_begin()2704 const_block_iterator block_begin() const { 2705 LLVMBBToBB BBGetter(Ctx); 2706 return const_block_iterator(cast<llvm::PHINode>(Val)->block_begin(), 2707 BBGetter); 2708 } block_end()2709 const_block_iterator block_end() const { 2710 LLVMBBToBB BBGetter(Ctx); 2711 return const_block_iterator(cast<llvm::PHINode>(Val)->block_end(), 2712 BBGetter); 2713 } blocks()2714 iterator_range<const_block_iterator> blocks() const { 2715 return make_range(block_begin(), block_end()); 2716 } 2717 incoming_values()2718 op_range incoming_values() { return operands(); } 2719 incoming_values()2720 const_op_range incoming_values() const { return operands(); } 2721 getNumIncomingValues()2722 unsigned getNumIncomingValues() const { 2723 return cast<llvm::PHINode>(Val)->getNumIncomingValues(); 2724 } 2725 Value *getIncomingValue(unsigned Idx) const; 2726 void setIncomingValue(unsigned Idx, Value *V); getOperandNumForIncomingValue(unsigned Idx)2727 static unsigned getOperandNumForIncomingValue(unsigned Idx) { 2728 return llvm::PHINode::getOperandNumForIncomingValue(Idx); 2729 } getIncomingValueNumForOperand(unsigned Idx)2730 static unsigned getIncomingValueNumForOperand(unsigned Idx) { 2731 return llvm::PHINode::getIncomingValueNumForOperand(Idx); 2732 } 2733 BasicBlock *getIncomingBlock(unsigned Idx) const; 2734 BasicBlock *getIncomingBlock(const Use &U) const; 2735 2736 void setIncomingBlock(unsigned Idx, BasicBlock *BB); 2737 2738 void addIncoming(Value *V, BasicBlock *BB); 2739 2740 Value *removeIncomingValue(unsigned Idx); 2741 Value *removeIncomingValue(BasicBlock *BB); 2742 2743 int getBasicBlockIndex(const BasicBlock *BB) const; 2744 Value *getIncomingValueForBlock(const BasicBlock *BB) const; 2745 2746 Value *hasConstantValue() const; 2747 hasConstantOrUndefValue()2748 bool hasConstantOrUndefValue() const { 2749 return cast<llvm::PHINode>(Val)->hasConstantOrUndefValue(); 2750 } isComplete()2751 bool isComplete() const { return cast<llvm::PHINode>(Val)->isComplete(); } 2752 void replaceIncomingBlockWith(const BasicBlock *Old, BasicBlock *New); 2753 void removeIncomingValueIf(function_ref<bool(unsigned)> Predicate); 2754 // TODO: Implement 2755 // void copyIncomingBlocks(iterator_range<const_block_iterator> BBRange, 2756 // uint32_t ToIdx = 0) 2757 }; 2758 2759 /// An LLLVM Instruction that has no SandboxIR equivalent class gets mapped to 2760 /// an OpaqueInstr. 2761 class OpaqueInst : public SingleLLVMInstructionImpl<llvm::Instruction> { OpaqueInst(llvm::Instruction * I,sandboxir::Context & Ctx)2762 OpaqueInst(llvm::Instruction *I, sandboxir::Context &Ctx) 2763 : SingleLLVMInstructionImpl(ClassID::Opaque, Opcode::Opaque, I, Ctx) {} OpaqueInst(ClassID SubclassID,llvm::Instruction * I,sandboxir::Context & Ctx)2764 OpaqueInst(ClassID SubclassID, llvm::Instruction *I, sandboxir::Context &Ctx) 2765 : SingleLLVMInstructionImpl(SubclassID, Opcode::Opaque, I, Ctx) {} 2766 friend class Context; // For constructor. 2767 2768 public: classof(const sandboxir::Value * From)2769 static bool classof(const sandboxir::Value *From) { 2770 return From->getSubclassID() == ClassID::Opaque; 2771 } 2772 }; 2773 2774 class Context { 2775 protected: 2776 LLVMContext &LLVMCtx; 2777 Tracker IRTracker; 2778 2779 /// Maps LLVM Value to the corresponding sandboxir::Value. Owns all 2780 /// SandboxIR objects. 2781 DenseMap<llvm::Value *, std::unique_ptr<sandboxir::Value>> 2782 LLVMValueToValueMap; 2783 2784 /// Remove \p V from the maps and returns the unique_ptr. 2785 std::unique_ptr<Value> detachLLVMValue(llvm::Value *V); 2786 /// Remove \p SBV from all SandboxIR maps and stop owning it. This effectively 2787 /// detaches \p V from the underlying IR. 2788 std::unique_ptr<Value> detach(Value *V); 2789 friend void Instruction::eraseFromParent(); // For detach(). 2790 /// Take ownership of VPtr and store it in `LLVMValueToValueMap`. 2791 Value *registerValue(std::unique_ptr<Value> &&VPtr); 2792 friend class EraseFromParent; // For registerValue(). 2793 /// This is the actual function that creates sandboxir values for \p V, 2794 /// and among others handles all instruction types. 2795 Value *getOrCreateValueInternal(llvm::Value *V, llvm::User *U = nullptr); 2796 /// Get or create a sandboxir::Argument for an existing LLVM IR \p LLVMArg. getOrCreateArgument(llvm::Argument * LLVMArg)2797 Argument *getOrCreateArgument(llvm::Argument *LLVMArg) { 2798 auto Pair = LLVMValueToValueMap.insert({LLVMArg, nullptr}); 2799 auto It = Pair.first; 2800 if (Pair.second) { 2801 It->second = std::unique_ptr<Argument>(new Argument(LLVMArg, *this)); 2802 return cast<Argument>(It->second.get()); 2803 } 2804 return cast<Argument>(It->second.get()); 2805 } 2806 /// Get or create a sandboxir::Value for an existing LLVM IR \p LLVMV. getOrCreateValue(llvm::Value * LLVMV)2807 Value *getOrCreateValue(llvm::Value *LLVMV) { 2808 return getOrCreateValueInternal(LLVMV, 0); 2809 } 2810 /// Get or create a sandboxir::Constant from an existing LLVM IR \p LLVMC. getOrCreateConstant(llvm::Constant * LLVMC)2811 Constant *getOrCreateConstant(llvm::Constant *LLVMC) { 2812 return cast<Constant>(getOrCreateValueInternal(LLVMC, 0)); 2813 } 2814 friend class ConstantInt; // For getOrCreateConstant(). 2815 /// Create a sandboxir::BasicBlock for an existing LLVM IR \p BB. This will 2816 /// also create all contents of the block. 2817 BasicBlock *createBasicBlock(llvm::BasicBlock *BB); 2818 2819 friend class BasicBlock; // For getOrCreateValue(). 2820 2821 IRBuilder<ConstantFolder> LLVMIRBuilder; getLLVMIRBuilder()2822 auto &getLLVMIRBuilder() { return LLVMIRBuilder; } 2823 2824 SelectInst *createSelectInst(llvm::SelectInst *SI); 2825 friend SelectInst; // For createSelectInst() 2826 InsertElementInst *createInsertElementInst(llvm::InsertElementInst *IEI); 2827 friend InsertElementInst; // For createInsertElementInst() 2828 ExtractElementInst *createExtractElementInst(llvm::ExtractElementInst *EEI); 2829 friend ExtractElementInst; // For createExtractElementInst() 2830 ShuffleVectorInst *createShuffleVectorInst(llvm::ShuffleVectorInst *SVI); 2831 friend ShuffleVectorInst; // For createShuffleVectorInst() 2832 BranchInst *createBranchInst(llvm::BranchInst *I); 2833 friend BranchInst; // For createBranchInst() 2834 LoadInst *createLoadInst(llvm::LoadInst *LI); 2835 friend LoadInst; // For createLoadInst() 2836 StoreInst *createStoreInst(llvm::StoreInst *SI); 2837 friend StoreInst; // For createStoreInst() 2838 ReturnInst *createReturnInst(llvm::ReturnInst *I); 2839 friend ReturnInst; // For createReturnInst() 2840 CallInst *createCallInst(llvm::CallInst *I); 2841 friend CallInst; // For createCallInst() 2842 InvokeInst *createInvokeInst(llvm::InvokeInst *I); 2843 friend InvokeInst; // For createInvokeInst() 2844 CallBrInst *createCallBrInst(llvm::CallBrInst *I); 2845 friend CallBrInst; // For createCallBrInst() 2846 CatchPadInst *createCatchPadInst(llvm::CatchPadInst *I); 2847 friend CatchPadInst; // For createCatchPadInst() 2848 CleanupPadInst *createCleanupPadInst(llvm::CleanupPadInst *I); 2849 friend CleanupPadInst; // For createCleanupPadInst() 2850 CatchReturnInst *createCatchReturnInst(llvm::CatchReturnInst *I); 2851 friend CatchReturnInst; // For createCatchReturnInst() 2852 GetElementPtrInst *createGetElementPtrInst(llvm::GetElementPtrInst *I); 2853 friend GetElementPtrInst; // For createGetElementPtrInst() 2854 CatchSwitchInst *createCatchSwitchInst(llvm::CatchSwitchInst *I); 2855 friend CatchSwitchInst; // For createCatchSwitchInst() 2856 SwitchInst *createSwitchInst(llvm::SwitchInst *I); 2857 friend SwitchInst; // For createSwitchInst() 2858 UnaryOperator *createUnaryOperator(llvm::UnaryOperator *I); 2859 friend UnaryOperator; // For createUnaryOperator() 2860 BinaryOperator *createBinaryOperator(llvm::BinaryOperator *I); 2861 friend BinaryOperator; // For createBinaryOperator() 2862 AtomicRMWInst *createAtomicRMWInst(llvm::AtomicRMWInst *I); 2863 friend AtomicRMWInst; // For createAtomicRMWInst() 2864 AtomicCmpXchgInst *createAtomicCmpXchgInst(llvm::AtomicCmpXchgInst *I); 2865 friend AtomicCmpXchgInst; // For createAtomicCmpXchgInst() 2866 AllocaInst *createAllocaInst(llvm::AllocaInst *I); 2867 friend AllocaInst; // For createAllocaInst() 2868 CastInst *createCastInst(llvm::CastInst *I); 2869 friend CastInst; // For createCastInst() 2870 PHINode *createPHINode(llvm::PHINode *I); 2871 friend PHINode; // For createPHINode() 2872 UnreachableInst *createUnreachableInst(llvm::UnreachableInst *UI); 2873 friend UnreachableInst; // For createUnreachableInst() 2874 2875 public: Context(LLVMContext & LLVMCtx)2876 Context(LLVMContext &LLVMCtx) 2877 : LLVMCtx(LLVMCtx), IRTracker(*this), 2878 LLVMIRBuilder(LLVMCtx, ConstantFolder()) {} 2879 getTracker()2880 Tracker &getTracker() { return IRTracker; } 2881 /// Convenience function for `getTracker().save()` save()2882 void save() { IRTracker.save(); } 2883 /// Convenience function for `getTracker().revert()` revert()2884 void revert() { IRTracker.revert(); } 2885 /// Convenience function for `getTracker().accept()` accept()2886 void accept() { IRTracker.accept(); } 2887 2888 sandboxir::Value *getValue(llvm::Value *V) const; getValue(const llvm::Value * V)2889 const sandboxir::Value *getValue(const llvm::Value *V) const { 2890 return getValue(const_cast<llvm::Value *>(V)); 2891 } 2892 /// Create a sandboxir::Function for an existing LLVM IR \p F, including all 2893 /// blocks and instructions. 2894 /// This is the main API function for creating Sandbox IR. 2895 Function *createFunction(llvm::Function *F); 2896 2897 /// \Returns the number of values registered with Context. getNumValues()2898 size_t getNumValues() const { return LLVMValueToValueMap.size(); } 2899 }; 2900 2901 class Function : public Constant { 2902 /// Helper for mapped_iterator. 2903 struct LLVMBBToBB { 2904 Context &Ctx; LLVMBBToBBLLVMBBToBB2905 LLVMBBToBB(Context &Ctx) : Ctx(Ctx) {} operatorLLVMBBToBB2906 BasicBlock &operator()(llvm::BasicBlock &LLVMBB) const { 2907 return *cast<BasicBlock>(Ctx.getValue(&LLVMBB)); 2908 } 2909 }; 2910 /// Use Context::createFunction() instead. Function(llvm::Function * F,sandboxir::Context & Ctx)2911 Function(llvm::Function *F, sandboxir::Context &Ctx) 2912 : Constant(ClassID::Function, F, Ctx) {} 2913 friend class Context; // For constructor. 2914 2915 public: 2916 /// For isa/dyn_cast. classof(const sandboxir::Value * From)2917 static bool classof(const sandboxir::Value *From) { 2918 return From->getSubclassID() == ClassID::Function; 2919 } 2920 getArg(unsigned Idx)2921 Argument *getArg(unsigned Idx) const { 2922 llvm::Argument *Arg = cast<llvm::Function>(Val)->getArg(Idx); 2923 return cast<Argument>(Ctx.getValue(Arg)); 2924 } 2925 arg_size()2926 size_t arg_size() const { return cast<llvm::Function>(Val)->arg_size(); } arg_empty()2927 bool arg_empty() const { return cast<llvm::Function>(Val)->arg_empty(); } 2928 2929 using iterator = mapped_iterator<llvm::Function::iterator, LLVMBBToBB>; begin()2930 iterator begin() const { 2931 LLVMBBToBB BBGetter(Ctx); 2932 return iterator(cast<llvm::Function>(Val)->begin(), BBGetter); 2933 } end()2934 iterator end() const { 2935 LLVMBBToBB BBGetter(Ctx); 2936 return iterator(cast<llvm::Function>(Val)->end(), BBGetter); 2937 } getFunctionType()2938 FunctionType *getFunctionType() const { 2939 return cast<llvm::Function>(Val)->getFunctionType(); 2940 } 2941 2942 #ifndef NDEBUG verify()2943 void verify() const final { 2944 assert(isa<llvm::Function>(Val) && "Expected Function!"); 2945 } 2946 void dumpNameAndArgs(raw_ostream &OS) const; 2947 void dumpOS(raw_ostream &OS) const final; 2948 #endif 2949 }; 2950 2951 } // namespace sandboxir 2952 } // namespace llvm 2953 2954 #endif // LLVM_SANDBOXIR_SANDBOXIR_H 2955