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