|
|
|||
File indexing completed on 2026-05-10 08:44:02
0001 //===-- llvm/Instruction.h - Instruction class definition -------*- C++ -*-===// 0002 // 0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 0004 // See https://llvm.org/LICENSE.txt for license information. 0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 0006 // 0007 //===----------------------------------------------------------------------===// 0008 // 0009 // This file contains the declaration of the Instruction class, which is the 0010 // base class for all of the LLVM instructions. 0011 // 0012 //===----------------------------------------------------------------------===// 0013 0014 #ifndef LLVM_IR_INSTRUCTION_H 0015 #define LLVM_IR_INSTRUCTION_H 0016 0017 #include "llvm/ADT/ArrayRef.h" 0018 #include "llvm/ADT/Bitfields.h" 0019 #include "llvm/ADT/StringRef.h" 0020 #include "llvm/ADT/ilist_node.h" 0021 #include "llvm/IR/DebugLoc.h" 0022 #include "llvm/IR/SymbolTableListTraits.h" 0023 #include "llvm/IR/User.h" 0024 #include "llvm/IR/Value.h" 0025 #include "llvm/Support/AtomicOrdering.h" 0026 #include <cstdint> 0027 #include <utility> 0028 0029 namespace llvm { 0030 0031 class BasicBlock; 0032 class DataLayout; 0033 class DbgMarker; 0034 class FastMathFlags; 0035 class MDNode; 0036 class Module; 0037 struct AAMDNodes; 0038 class DbgMarker; 0039 class DbgRecord; 0040 0041 template <> struct ilist_alloc_traits<Instruction> { 0042 static inline void deleteNode(Instruction *V); 0043 }; 0044 0045 iterator_range<simple_ilist<DbgRecord>::iterator> 0046 getDbgRecordRange(DbgMarker *); 0047 0048 class InsertPosition { 0049 using InstListType = SymbolTableList<Instruction, ilist_iterator_bits<true>, 0050 ilist_parent<BasicBlock>>; 0051 InstListType::iterator InsertAt; 0052 0053 public: 0054 InsertPosition(std::nullptr_t) : InsertAt() {} 0055 LLVM_DEPRECATED("Use BasicBlock::iterators for insertion instead", 0056 "BasicBlock::iterator") 0057 InsertPosition(Instruction *InsertBefore); 0058 InsertPosition(BasicBlock *InsertAtEnd); 0059 InsertPosition(InstListType::iterator InsertAt) : InsertAt(InsertAt) {} 0060 operator InstListType::iterator() const { return InsertAt; } 0061 bool isValid() const { return InsertAt.isValid(); } 0062 BasicBlock *getBasicBlock() { return InsertAt.getNodeParent(); } 0063 }; 0064 0065 class Instruction : public User, 0066 public ilist_node_with_parent<Instruction, BasicBlock, 0067 ilist_iterator_bits<true>, 0068 ilist_parent<BasicBlock>> { 0069 public: 0070 using InstListType = SymbolTableList<Instruction, ilist_iterator_bits<true>, 0071 ilist_parent<BasicBlock>>; 0072 0073 private: 0074 DebugLoc DbgLoc; // 'dbg' Metadata cache. 0075 0076 /// Relative order of this instruction in its parent basic block. Used for 0077 /// O(1) local dominance checks between instructions. 0078 mutable unsigned Order = 0; 0079 0080 public: 0081 /// Optional marker recording the position for debugging information that 0082 /// takes effect immediately before this instruction. Null unless there is 0083 /// debugging information present. 0084 DbgMarker *DebugMarker = nullptr; 0085 0086 /// Clone any debug-info attached to \p From onto this instruction. Used to 0087 /// copy debugging information from one block to another, when copying entire 0088 /// blocks. \see DebugProgramInstruction.h , because the ordering of 0089 /// DbgRecords is still important, fine grain control of which instructions 0090 /// are moved and where they go is necessary. 0091 /// \p From The instruction to clone debug-info from. 0092 /// \p from_here Optional iterator to limit DbgRecords cloned to be a range 0093 /// from 0094 /// from_here to end(). 0095 /// \p InsertAtHead Whether the cloned DbgRecords should be placed at the end 0096 /// or the beginning of existing DbgRecords attached to this. 0097 /// \returns A range over the newly cloned DbgRecords. 0098 iterator_range<simple_ilist<DbgRecord>::iterator> cloneDebugInfoFrom( 0099 const Instruction *From, 0100 std::optional<simple_ilist<DbgRecord>::iterator> FromHere = std::nullopt, 0101 bool InsertAtHead = false); 0102 0103 /// Return a range over the DbgRecords attached to this instruction. 0104 iterator_range<simple_ilist<DbgRecord>::iterator> getDbgRecordRange() const { 0105 return llvm::getDbgRecordRange(DebugMarker); 0106 } 0107 0108 /// Return an iterator to the position of the "Next" DbgRecord after this 0109 /// instruction, or std::nullopt. This is the position to pass to 0110 /// BasicBlock::reinsertInstInDbgRecords when re-inserting an instruction. 0111 std::optional<simple_ilist<DbgRecord>::iterator> getDbgReinsertionPosition(); 0112 0113 /// Returns true if any DbgRecords are attached to this instruction. 0114 bool hasDbgRecords() const; 0115 0116 /// Transfer any DbgRecords on the position \p It onto this instruction, 0117 /// by simply adopting the sequence of DbgRecords (which is efficient) if 0118 /// possible, by merging two sequences otherwise. 0119 void adoptDbgRecords(BasicBlock *BB, InstListType::iterator It, 0120 bool InsertAtHead); 0121 0122 /// Erase any DbgRecords attached to this instruction. 0123 void dropDbgRecords(); 0124 0125 /// Erase a single DbgRecord \p I that is attached to this instruction. 0126 void dropOneDbgRecord(DbgRecord *I); 0127 0128 /// Handle the debug-info implications of this instruction being removed. Any 0129 /// attached DbgRecords need to "fall" down onto the next instruction. 0130 void handleMarkerRemoval(); 0131 0132 protected: 0133 // The 15 first bits of `Value::SubclassData` are available for subclasses of 0134 // `Instruction` to use. 0135 using OpaqueField = Bitfield::Element<uint16_t, 0, 15>; 0136 0137 // Template alias so that all Instruction storing alignment use the same 0138 // definiton. 0139 // Valid alignments are powers of two from 2^0 to 2^MaxAlignmentExponent = 0140 // 2^32. We store them as Log2(Alignment), so we need 6 bits to encode the 33 0141 // possible values. 0142 template <unsigned Offset> 0143 using AlignmentBitfieldElementT = 0144 typename Bitfield::Element<unsigned, Offset, 6, 0145 Value::MaxAlignmentExponent>; 0146 0147 template <unsigned Offset> 0148 using BoolBitfieldElementT = typename Bitfield::Element<bool, Offset, 1>; 0149 0150 template <unsigned Offset> 0151 using AtomicOrderingBitfieldElementT = 0152 typename Bitfield::Element<AtomicOrdering, Offset, 3, 0153 AtomicOrdering::LAST>; 0154 0155 private: 0156 // The last bit is used to store whether the instruction has metadata attached 0157 // or not. 0158 using HasMetadataField = Bitfield::Element<bool, 15, 1>; 0159 0160 protected: 0161 ~Instruction(); // Use deleteValue() to delete a generic Instruction. 0162 0163 public: 0164 Instruction(const Instruction &) = delete; 0165 Instruction &operator=(const Instruction &) = delete; 0166 0167 /// Specialize the methods defined in Value, as we know that an instruction 0168 /// can only be used by other instructions. 0169 Instruction *user_back() { return cast<Instruction>(*user_begin());} 0170 const Instruction *user_back() const { return cast<Instruction>(*user_begin());} 0171 0172 /// Return the module owning the function this instruction belongs to 0173 /// or nullptr it the function does not have a module. 0174 /// 0175 /// Note: this is undefined behavior if the instruction does not have a 0176 /// parent, or the parent basic block does not have a parent function. 0177 const Module *getModule() const; 0178 Module *getModule() { 0179 return const_cast<Module *>( 0180 static_cast<const Instruction *>(this)->getModule()); 0181 } 0182 0183 /// Return the function this instruction belongs to. 0184 /// 0185 /// Note: it is undefined behavior to call this on an instruction not 0186 /// currently inserted into a function. 0187 const Function *getFunction() const; 0188 Function *getFunction() { 0189 return const_cast<Function *>( 0190 static_cast<const Instruction *>(this)->getFunction()); 0191 } 0192 0193 /// Get the data layout of the module this instruction belongs to. 0194 /// 0195 /// Requires the instruction to have a parent module. 0196 const DataLayout &getDataLayout() const; 0197 0198 /// This method unlinks 'this' from the containing basic block, but does not 0199 /// delete it. 0200 void removeFromParent(); 0201 0202 /// This method unlinks 'this' from the containing basic block and deletes it. 0203 /// 0204 /// \returns an iterator pointing to the element after the erased one 0205 InstListType::iterator eraseFromParent(); 0206 0207 /// Insert an unlinked instruction into a basic block immediately before 0208 /// the specified instruction. 0209 /// 0210 /// Deprecated in favour of the iterator-accepting flavour. Iterators at the 0211 /// start of a block such as BasicBlock::getFirstNonPHIIt must be passed into 0212 /// insertBefore without unwrapping/rewrapping. For all other positions, call 0213 /// getIterator to fetch the instruction iterator. 0214 LLVM_DEPRECATED("Use iterators as instruction positions", "") 0215 void insertBefore(Instruction *InsertPos); 0216 0217 /// Insert an unlinked instruction into a basic block immediately before 0218 /// the specified position. 0219 void insertBefore(InstListType::iterator InsertPos); 0220 0221 /// Insert an unlinked instruction into a basic block immediately after the 0222 /// specified instruction. 0223 void insertAfter(Instruction *InsertPos); 0224 0225 /// Insert an unlinked instruction into a basic block immediately after the 0226 /// specified position. 0227 void insertAfter(InstListType::iterator InsertPos); 0228 0229 /// Inserts an unlinked instruction into \p ParentBB at position \p It and 0230 /// returns the iterator of the inserted instruction. 0231 InstListType::iterator insertInto(BasicBlock *ParentBB, 0232 InstListType::iterator It); 0233 0234 void insertBefore(BasicBlock &BB, InstListType::iterator InsertPos); 0235 0236 /// Unlink this instruction from its current basic block and insert it into 0237 /// the basic block that MovePos lives in, right before MovePos. 0238 /// 0239 /// Deprecated in favour of the iterator-accepting flavour. Iterators at the 0240 /// start of a block such as BasicBlock::getFirstNonPHIIt must be passed into 0241 /// moveBefore without unwrapping/rewrapping. For all other positions, call 0242 /// getIterator to fetch the instruction iterator. 0243 LLVM_DEPRECATED("Use iterators as instruction positions", "") 0244 void moveBefore(Instruction *MovePos); 0245 0246 /// Unlink this instruction from its current basic block and insert it into 0247 /// the basic block that MovePos lives in, right before MovePos. 0248 void moveBefore(InstListType::iterator InsertPos); 0249 0250 /// Perform a \ref moveBefore operation, while signalling that the caller 0251 /// intends to preserve the original ordering of instructions. This implicitly 0252 /// means that any adjacent debug-info should move with this instruction. 0253 void moveBeforePreserving(InstListType::iterator MovePos); 0254 0255 /// Perform a \ref moveBefore operation, while signalling that the caller 0256 /// intends to preserve the original ordering of instructions. This implicitly 0257 /// means that any adjacent debug-info should move with this instruction. 0258 void moveBeforePreserving(BasicBlock &BB, InstListType::iterator I); 0259 0260 /// Perform a \ref moveBefore operation, while signalling that the caller 0261 /// intends to preserve the original ordering of instructions. This implicitly 0262 /// means that any adjacent debug-info should move with this instruction. 0263 /// 0264 /// Deprecated in favour of the iterator-accepting flavour of 0265 /// moveBeforePreserving, as all insertions should be at iterator positions. 0266 LLVM_DEPRECATED("Use iterators as instruction positions", "") 0267 void moveBeforePreserving(Instruction *MovePos); 0268 0269 private: 0270 /// RemoveDIs project: all other moves implemented with this method, 0271 /// centralising debug-info updates into one place. 0272 void moveBeforeImpl(BasicBlock &BB, InstListType::iterator I, bool Preserve); 0273 0274 public: 0275 /// Unlink this instruction and insert into BB before I. 0276 /// 0277 /// \pre I is a valid iterator into BB. 0278 void moveBefore(BasicBlock &BB, InstListType::iterator I); 0279 0280 /// Unlink this instruction from its current basic block and insert it into 0281 /// the basic block that MovePos lives in, right after MovePos. 0282 void moveAfter(Instruction *MovePos); 0283 0284 /// Unlink this instruction from its current basic block and insert it into 0285 /// the basic block that MovePos lives in, right after MovePos. 0286 void moveAfter(InstListType::iterator MovePos); 0287 0288 /// See \ref moveBeforePreserving . 0289 void moveAfterPreserving(Instruction *MovePos); 0290 0291 /// Given an instruction Other in the same basic block as this instruction, 0292 /// return true if this instruction comes before Other. In this worst case, 0293 /// this takes linear time in the number of instructions in the block. The 0294 /// results are cached, so in common cases when the block remains unmodified, 0295 /// it takes constant time. 0296 bool comesBefore(const Instruction *Other) const; 0297 0298 /// Get the first insertion point at which the result of this instruction 0299 /// is defined. This is *not* the directly following instruction in a number 0300 /// of cases, e.g. phi nodes or terminators that return values. This function 0301 /// may return null if the insertion after the definition is not possible, 0302 /// e.g. due to a catchswitch terminator. 0303 std::optional<InstListType::iterator> getInsertionPointAfterDef(); 0304 0305 //===--------------------------------------------------------------------===// 0306 // Subclass classification. 0307 //===--------------------------------------------------------------------===// 0308 0309 /// Returns a member of one of the enums like Instruction::Add. 0310 unsigned getOpcode() const { return getValueID() - InstructionVal; } 0311 0312 const char *getOpcodeName() const { return getOpcodeName(getOpcode()); } 0313 bool isTerminator() const { return isTerminator(getOpcode()); } 0314 bool isUnaryOp() const { return isUnaryOp(getOpcode()); } 0315 bool isBinaryOp() const { return isBinaryOp(getOpcode()); } 0316 bool isIntDivRem() const { return isIntDivRem(getOpcode()); } 0317 bool isFPDivRem() const { return isFPDivRem(getOpcode()); } 0318 bool isShift() const { return isShift(getOpcode()); } 0319 bool isCast() const { return isCast(getOpcode()); } 0320 bool isFuncletPad() const { return isFuncletPad(getOpcode()); } 0321 bool isSpecialTerminator() const { return isSpecialTerminator(getOpcode()); } 0322 0323 /// It checks if this instruction is the only user of at least one of 0324 /// its operands. 0325 bool isOnlyUserOfAnyOperand(); 0326 0327 static const char *getOpcodeName(unsigned Opcode); 0328 0329 static inline bool isTerminator(unsigned Opcode) { 0330 return Opcode >= TermOpsBegin && Opcode < TermOpsEnd; 0331 } 0332 0333 static inline bool isUnaryOp(unsigned Opcode) { 0334 return Opcode >= UnaryOpsBegin && Opcode < UnaryOpsEnd; 0335 } 0336 static inline bool isBinaryOp(unsigned Opcode) { 0337 return Opcode >= BinaryOpsBegin && Opcode < BinaryOpsEnd; 0338 } 0339 0340 static inline bool isIntDivRem(unsigned Opcode) { 0341 return Opcode == UDiv || Opcode == SDiv || Opcode == URem || Opcode == SRem; 0342 } 0343 0344 static inline bool isFPDivRem(unsigned Opcode) { 0345 return Opcode == FDiv || Opcode == FRem; 0346 } 0347 0348 /// Determine if the Opcode is one of the shift instructions. 0349 static inline bool isShift(unsigned Opcode) { 0350 return Opcode >= Shl && Opcode <= AShr; 0351 } 0352 0353 /// Return true if this is a logical shift left or a logical shift right. 0354 inline bool isLogicalShift() const { 0355 return getOpcode() == Shl || getOpcode() == LShr; 0356 } 0357 0358 /// Return true if this is an arithmetic shift right. 0359 inline bool isArithmeticShift() const { 0360 return getOpcode() == AShr; 0361 } 0362 0363 /// Determine if the Opcode is and/or/xor. 0364 static inline bool isBitwiseLogicOp(unsigned Opcode) { 0365 return Opcode == And || Opcode == Or || Opcode == Xor; 0366 } 0367 0368 /// Return true if this is and/or/xor. 0369 inline bool isBitwiseLogicOp() const { 0370 return isBitwiseLogicOp(getOpcode()); 0371 } 0372 0373 /// Determine if the Opcode is one of the CastInst instructions. 0374 static inline bool isCast(unsigned Opcode) { 0375 return Opcode >= CastOpsBegin && Opcode < CastOpsEnd; 0376 } 0377 0378 /// Determine if the Opcode is one of the FuncletPadInst instructions. 0379 static inline bool isFuncletPad(unsigned Opcode) { 0380 return Opcode >= FuncletPadOpsBegin && Opcode < FuncletPadOpsEnd; 0381 } 0382 0383 /// Returns true if the Opcode is a "special" terminator that does more than 0384 /// branch to a successor (e.g. have a side effect or return a value). 0385 static inline bool isSpecialTerminator(unsigned Opcode) { 0386 switch (Opcode) { 0387 case Instruction::CatchSwitch: 0388 case Instruction::CatchRet: 0389 case Instruction::CleanupRet: 0390 case Instruction::Invoke: 0391 case Instruction::Resume: 0392 case Instruction::CallBr: 0393 return true; 0394 default: 0395 return false; 0396 } 0397 } 0398 0399 //===--------------------------------------------------------------------===// 0400 // Metadata manipulation. 0401 //===--------------------------------------------------------------------===// 0402 0403 /// Return true if this instruction has any metadata attached to it. 0404 bool hasMetadata() const { return DbgLoc || Value::hasMetadata(); } 0405 0406 // Return true if this instruction contains loop metadata other than 0407 // a debug location 0408 bool hasNonDebugLocLoopMetadata() const; 0409 0410 /// Return true if this instruction has metadata attached to it other than a 0411 /// debug location. 0412 bool hasMetadataOtherThanDebugLoc() const { return Value::hasMetadata(); } 0413 0414 /// Return true if this instruction has the given type of metadata attached. 0415 bool hasMetadata(unsigned KindID) const { 0416 return getMetadata(KindID) != nullptr; 0417 } 0418 0419 /// Return true if this instruction has the given type of metadata attached. 0420 bool hasMetadata(StringRef Kind) const { 0421 return getMetadata(Kind) != nullptr; 0422 } 0423 0424 /// Get the metadata of given kind attached to this Instruction. 0425 /// If the metadata is not found then return null. 0426 MDNode *getMetadata(unsigned KindID) const { 0427 // Handle 'dbg' as a special case since it is not stored in the hash table. 0428 if (KindID == LLVMContext::MD_dbg) 0429 return DbgLoc.getAsMDNode(); 0430 return Value::getMetadata(KindID); 0431 } 0432 0433 /// Get the metadata of given kind attached to this Instruction. 0434 /// If the metadata is not found then return null. 0435 MDNode *getMetadata(StringRef Kind) const { 0436 if (!hasMetadata()) return nullptr; 0437 return getMetadataImpl(Kind); 0438 } 0439 0440 /// Get all metadata attached to this Instruction. The first element of each 0441 /// pair returned is the KindID, the second element is the metadata value. 0442 /// This list is returned sorted by the KindID. 0443 void 0444 getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const { 0445 if (hasMetadata()) 0446 getAllMetadataImpl(MDs); 0447 } 0448 0449 /// This does the same thing as getAllMetadata, except that it filters out the 0450 /// debug location. 0451 void getAllMetadataOtherThanDebugLoc( 0452 SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const { 0453 Value::getAllMetadata(MDs); 0454 } 0455 0456 /// Set the metadata of the specified kind to the specified node. This updates 0457 /// or replaces metadata if already present, or removes it if Node is null. 0458 void setMetadata(unsigned KindID, MDNode *Node); 0459 void setMetadata(StringRef Kind, MDNode *Node); 0460 0461 /// Copy metadata from \p SrcInst to this instruction. \p WL, if not empty, 0462 /// specifies the list of meta data that needs to be copied. If \p WL is 0463 /// empty, all meta data will be copied. 0464 void copyMetadata(const Instruction &SrcInst, 0465 ArrayRef<unsigned> WL = ArrayRef<unsigned>()); 0466 0467 /// Erase all metadata that matches the predicate. 0468 void eraseMetadataIf(function_ref<bool(unsigned, MDNode *)> Pred); 0469 0470 /// If the instruction has "branch_weights" MD_prof metadata and the MDNode 0471 /// has three operands (including name string), swap the order of the 0472 /// metadata. 0473 void swapProfMetadata(); 0474 0475 /// Drop all unknown metadata except for debug locations. 0476 /// @{ 0477 /// Passes are required to drop metadata they don't understand. This is a 0478 /// convenience method for passes to do so. 0479 /// dropUBImplyingAttrsAndUnknownMetadata should be used instead of 0480 /// this API if the Instruction being modified is a call. 0481 void dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs = {}); 0482 /// @} 0483 0484 /// Adds an !annotation metadata node with \p Annotation to this instruction. 0485 /// If this instruction already has !annotation metadata, append \p Annotation 0486 /// to the existing node. 0487 void addAnnotationMetadata(StringRef Annotation); 0488 /// Adds an !annotation metadata node with an array of \p Annotations 0489 /// as a tuple to this instruction. If this instruction already has 0490 /// !annotation metadata, append the tuple to 0491 /// the existing node. 0492 void addAnnotationMetadata(SmallVector<StringRef> Annotations); 0493 /// Returns the AA metadata for this instruction. 0494 AAMDNodes getAAMetadata() const; 0495 0496 /// Sets the AA metadata on this instruction from the AAMDNodes structure. 0497 void setAAMetadata(const AAMDNodes &N); 0498 0499 /// Sets the nosanitize metadata on this instruction. 0500 void setNoSanitizeMetadata(); 0501 0502 /// Retrieve total raw weight values of a branch. 0503 /// Returns true on success with profile total weights filled in. 0504 /// Returns false if no metadata was found. 0505 bool extractProfTotalWeight(uint64_t &TotalVal) const; 0506 0507 /// Set the debug location information for this instruction. 0508 void setDebugLoc(DebugLoc Loc) { DbgLoc = std::move(Loc); } 0509 0510 /// Return the debug location for this node as a DebugLoc. 0511 const DebugLoc &getDebugLoc() const { return DbgLoc; } 0512 0513 /// Fetch the debug location for this node, unless this is a debug intrinsic, 0514 /// in which case fetch the debug location of the next non-debug node. 0515 const DebugLoc &getStableDebugLoc() const; 0516 0517 /// Set or clear the nuw flag on this instruction, which must be an operator 0518 /// which supports this flag. See LangRef.html for the meaning of this flag. 0519 void setHasNoUnsignedWrap(bool b = true); 0520 0521 /// Set or clear the nsw flag on this instruction, which must be an operator 0522 /// which supports this flag. See LangRef.html for the meaning of this flag. 0523 void setHasNoSignedWrap(bool b = true); 0524 0525 /// Set or clear the exact flag on this instruction, which must be an operator 0526 /// which supports this flag. See LangRef.html for the meaning of this flag. 0527 void setIsExact(bool b = true); 0528 0529 /// Set or clear the nneg flag on this instruction, which must be a zext 0530 /// instruction. 0531 void setNonNeg(bool b = true); 0532 0533 /// Determine whether the no unsigned wrap flag is set. 0534 bool hasNoUnsignedWrap() const LLVM_READONLY; 0535 0536 /// Determine whether the no signed wrap flag is set. 0537 bool hasNoSignedWrap() const LLVM_READONLY; 0538 0539 /// Determine whether the the nneg flag is set. 0540 bool hasNonNeg() const LLVM_READONLY; 0541 0542 /// Return true if this operator has flags which may cause this instruction 0543 /// to evaluate to poison despite having non-poison inputs. 0544 bool hasPoisonGeneratingFlags() const LLVM_READONLY; 0545 0546 /// Drops flags that may cause this instruction to evaluate to poison despite 0547 /// having non-poison inputs. 0548 void dropPoisonGeneratingFlags(); 0549 0550 /// Return true if this instruction has poison-generating metadata. 0551 bool hasPoisonGeneratingMetadata() const LLVM_READONLY; 0552 0553 /// Drops metadata that may generate poison. 0554 void dropPoisonGeneratingMetadata(); 0555 0556 /// Return true if this instruction has poison-generating attribute. 0557 bool hasPoisonGeneratingReturnAttributes() const LLVM_READONLY; 0558 0559 /// Drops return attributes that may generate poison. 0560 void dropPoisonGeneratingReturnAttributes(); 0561 0562 /// Return true if this instruction has poison-generating flags, 0563 /// return attributes or metadata. 0564 bool hasPoisonGeneratingAnnotations() const { 0565 return hasPoisonGeneratingFlags() || 0566 hasPoisonGeneratingReturnAttributes() || 0567 hasPoisonGeneratingMetadata(); 0568 } 0569 0570 /// Drops flags, return attributes and metadata that may generate poison. 0571 void dropPoisonGeneratingAnnotations() { 0572 dropPoisonGeneratingFlags(); 0573 dropPoisonGeneratingReturnAttributes(); 0574 dropPoisonGeneratingMetadata(); 0575 } 0576 0577 /// This function drops non-debug unknown metadata (through 0578 /// dropUnknownNonDebugMetadata). For calls, it also drops parameter and 0579 /// return attributes that can cause undefined behaviour. Both of these should 0580 /// be done by passes which move instructions in IR. 0581 void dropUBImplyingAttrsAndUnknownMetadata(ArrayRef<unsigned> KnownIDs = {}); 0582 0583 /// Drop any attributes or metadata that can cause immediate undefined 0584 /// behavior. Retain other attributes/metadata on a best-effort basis. 0585 /// This should be used when speculating instructions. 0586 void dropUBImplyingAttrsAndMetadata(); 0587 0588 /// Determine whether the exact flag is set. 0589 bool isExact() const LLVM_READONLY; 0590 0591 /// Set or clear all fast-math-flags on this instruction, which must be an 0592 /// operator which supports this flag. See LangRef.html for the meaning of 0593 /// this flag. 0594 void setFast(bool B); 0595 0596 /// Set or clear the reassociation flag on this instruction, which must be 0597 /// an operator which supports this flag. See LangRef.html for the meaning of 0598 /// this flag. 0599 void setHasAllowReassoc(bool B); 0600 0601 /// Set or clear the no-nans flag on this instruction, which must be an 0602 /// operator which supports this flag. See LangRef.html for the meaning of 0603 /// this flag. 0604 void setHasNoNaNs(bool B); 0605 0606 /// Set or clear the no-infs flag on this instruction, which must be an 0607 /// operator which supports this flag. See LangRef.html for the meaning of 0608 /// this flag. 0609 void setHasNoInfs(bool B); 0610 0611 /// Set or clear the no-signed-zeros flag on this instruction, which must be 0612 /// an operator which supports this flag. See LangRef.html for the meaning of 0613 /// this flag. 0614 void setHasNoSignedZeros(bool B); 0615 0616 /// Set or clear the allow-reciprocal flag on this instruction, which must be 0617 /// an operator which supports this flag. See LangRef.html for the meaning of 0618 /// this flag. 0619 void setHasAllowReciprocal(bool B); 0620 0621 /// Set or clear the allow-contract flag on this instruction, which must be 0622 /// an operator which supports this flag. See LangRef.html for the meaning of 0623 /// this flag. 0624 void setHasAllowContract(bool B); 0625 0626 /// Set or clear the approximate-math-functions flag on this instruction, 0627 /// which must be an operator which supports this flag. See LangRef.html for 0628 /// the meaning of this flag. 0629 void setHasApproxFunc(bool B); 0630 0631 /// Convenience function for setting multiple fast-math flags on this 0632 /// instruction, which must be an operator which supports these flags. See 0633 /// LangRef.html for the meaning of these flags. 0634 void setFastMathFlags(FastMathFlags FMF); 0635 0636 /// Convenience function for transferring all fast-math flag values to this 0637 /// instruction, which must be an operator which supports these flags. See 0638 /// LangRef.html for the meaning of these flags. 0639 void copyFastMathFlags(FastMathFlags FMF); 0640 0641 /// Determine whether all fast-math-flags are set. 0642 bool isFast() const LLVM_READONLY; 0643 0644 /// Determine whether the allow-reassociation flag is set. 0645 bool hasAllowReassoc() const LLVM_READONLY; 0646 0647 /// Determine whether the no-NaNs flag is set. 0648 bool hasNoNaNs() const LLVM_READONLY; 0649 0650 /// Determine whether the no-infs flag is set. 0651 bool hasNoInfs() const LLVM_READONLY; 0652 0653 /// Determine whether the no-signed-zeros flag is set. 0654 bool hasNoSignedZeros() const LLVM_READONLY; 0655 0656 /// Determine whether the allow-reciprocal flag is set. 0657 bool hasAllowReciprocal() const LLVM_READONLY; 0658 0659 /// Determine whether the allow-contract flag is set. 0660 bool hasAllowContract() const LLVM_READONLY; 0661 0662 /// Determine whether the approximate-math-functions flag is set. 0663 bool hasApproxFunc() const LLVM_READONLY; 0664 0665 /// Convenience function for getting all the fast-math flags, which must be an 0666 /// operator which supports these flags. See LangRef.html for the meaning of 0667 /// these flags. 0668 FastMathFlags getFastMathFlags() const LLVM_READONLY; 0669 0670 /// Copy I's fast-math flags 0671 void copyFastMathFlags(const Instruction *I); 0672 0673 /// Convenience method to copy supported exact, fast-math, and (optionally) 0674 /// wrapping flags from V to this instruction. 0675 void copyIRFlags(const Value *V, bool IncludeWrapFlags = true); 0676 0677 /// Logical 'and' of any supported wrapping, exact, and fast-math flags of 0678 /// V and this instruction. 0679 void andIRFlags(const Value *V); 0680 0681 /// Merge 2 debug locations and apply it to the Instruction. If the 0682 /// instruction is a CallIns, we need to traverse the inline chain to find 0683 /// the common scope. This is not efficient for N-way merging as each time 0684 /// you merge 2 iterations, you need to rebuild the hashmap to find the 0685 /// common scope. However, we still choose this API because: 0686 /// 1) Simplicity: it takes 2 locations instead of a list of locations. 0687 /// 2) In worst case, it increases the complexity from O(N*I) to 0688 /// O(2*N*I), where N is # of Instructions to merge, and I is the 0689 /// maximum level of inline stack. So it is still linear. 0690 /// 3) Merging of call instructions should be extremely rare in real 0691 /// applications, thus the N-way merging should be in code path. 0692 /// The DebugLoc attached to this instruction will be overwritten by the 0693 /// merged DebugLoc. 0694 void applyMergedLocation(DILocation *LocA, DILocation *LocB); 0695 0696 /// Updates the debug location given that the instruction has been hoisted 0697 /// from a block to a predecessor of that block. 0698 /// Note: it is undefined behavior to call this on an instruction not 0699 /// currently inserted into a function. 0700 void updateLocationAfterHoist(); 0701 0702 /// Drop the instruction's debug location. This does not guarantee removal 0703 /// of the !dbg source location attachment, as it must set a line 0 location 0704 /// with scope information attached on call instructions. To guarantee 0705 /// removal of the !dbg attachment, use the \ref setDebugLoc() API. 0706 /// Note: it is undefined behavior to call this on an instruction not 0707 /// currently inserted into a function. 0708 void dropLocation(); 0709 0710 /// Merge the DIAssignID metadata from this instruction and those attached to 0711 /// instructions in \p SourceInstructions. This process performs a RAUW on 0712 /// the MetadataAsValue uses of the merged DIAssignID nodes. Not every 0713 /// instruction in \p SourceInstructions needs to have DIAssignID 0714 /// metadata. If none of them do then nothing happens. If this instruction 0715 /// does not have a DIAssignID attachment but at least one in \p 0716 /// SourceInstructions does then the merged one will be attached to 0717 /// it. However, instructions without attachments in \p SourceInstructions 0718 /// are not modified. 0719 void mergeDIAssignID(ArrayRef<const Instruction *> SourceInstructions); 0720 0721 private: 0722 // These are all implemented in Metadata.cpp. 0723 MDNode *getMetadataImpl(StringRef Kind) const; 0724 void 0725 getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const; 0726 0727 /// Update the LLVMContext ID-to-Instruction(s) mapping. If \p ID is nullptr 0728 /// then clear the mapping for this instruction. 0729 void updateDIAssignIDMapping(DIAssignID *ID); 0730 0731 public: 0732 //===--------------------------------------------------------------------===// 0733 // Predicates and helper methods. 0734 //===--------------------------------------------------------------------===// 0735 0736 /// Return true if the instruction is associative: 0737 /// 0738 /// Associative operators satisfy: x op (y op z) === (x op y) op z 0739 /// 0740 /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative. 0741 /// 0742 bool isAssociative() const LLVM_READONLY; 0743 static bool isAssociative(unsigned Opcode) { 0744 return Opcode == And || Opcode == Or || Opcode == Xor || 0745 Opcode == Add || Opcode == Mul; 0746 } 0747 0748 /// Return true if the instruction is commutative: 0749 /// 0750 /// Commutative operators satisfy: (x op y) === (y op x) 0751 /// 0752 /// In LLVM, these are the commutative operators, plus SetEQ and SetNE, when 0753 /// applied to any type. 0754 /// 0755 bool isCommutative() const LLVM_READONLY; 0756 static bool isCommutative(unsigned Opcode) { 0757 switch (Opcode) { 0758 case Add: case FAdd: 0759 case Mul: case FMul: 0760 case And: case Or: case Xor: 0761 return true; 0762 default: 0763 return false; 0764 } 0765 } 0766 0767 /// Return true if the instruction is idempotent: 0768 /// 0769 /// Idempotent operators satisfy: x op x === x 0770 /// 0771 /// In LLVM, the And and Or operators are idempotent. 0772 /// 0773 bool isIdempotent() const { return isIdempotent(getOpcode()); } 0774 static bool isIdempotent(unsigned Opcode) { 0775 return Opcode == And || Opcode == Or; 0776 } 0777 0778 /// Return true if the instruction is nilpotent: 0779 /// 0780 /// Nilpotent operators satisfy: x op x === Id, 0781 /// 0782 /// where Id is the identity for the operator, i.e. a constant such that 0783 /// x op Id === x and Id op x === x for all x. 0784 /// 0785 /// In LLVM, the Xor operator is nilpotent. 0786 /// 0787 bool isNilpotent() const { return isNilpotent(getOpcode()); } 0788 static bool isNilpotent(unsigned Opcode) { 0789 return Opcode == Xor; 0790 } 0791 0792 /// Return true if this instruction may modify memory. 0793 bool mayWriteToMemory() const LLVM_READONLY; 0794 0795 /// Return true if this instruction may read memory. 0796 bool mayReadFromMemory() const LLVM_READONLY; 0797 0798 /// Return true if this instruction may read or write memory. 0799 bool mayReadOrWriteMemory() const { 0800 return mayReadFromMemory() || mayWriteToMemory(); 0801 } 0802 0803 /// Return true if this instruction has an AtomicOrdering of unordered or 0804 /// higher. 0805 bool isAtomic() const LLVM_READONLY; 0806 0807 /// Return true if this atomic instruction loads from memory. 0808 bool hasAtomicLoad() const LLVM_READONLY; 0809 0810 /// Return true if this atomic instruction stores to memory. 0811 bool hasAtomicStore() const LLVM_READONLY; 0812 0813 /// Return true if this instruction has a volatile memory access. 0814 bool isVolatile() const LLVM_READONLY; 0815 0816 /// Return the type this instruction accesses in memory, if any. 0817 Type *getAccessType() const LLVM_READONLY; 0818 0819 /// Return true if this instruction may throw an exception. 0820 /// 0821 /// If IncludePhaseOneUnwind is set, this will also include cases where 0822 /// phase one unwinding may unwind past this frame due to skipping of 0823 /// cleanup landingpads. 0824 bool mayThrow(bool IncludePhaseOneUnwind = false) const LLVM_READONLY; 0825 0826 /// Return true if this instruction behaves like a memory fence: it can load 0827 /// or store to memory location without being given a memory location. 0828 bool isFenceLike() const { 0829 switch (getOpcode()) { 0830 default: 0831 return false; 0832 // This list should be kept in sync with the list in mayWriteToMemory for 0833 // all opcodes which don't have a memory location. 0834 case Instruction::Fence: 0835 case Instruction::CatchPad: 0836 case Instruction::CatchRet: 0837 case Instruction::Call: 0838 case Instruction::Invoke: 0839 return true; 0840 } 0841 } 0842 0843 /// Return true if the instruction may have side effects. 0844 /// 0845 /// Side effects are: 0846 /// * Writing to memory. 0847 /// * Unwinding. 0848 /// * Not returning (e.g. an infinite loop). 0849 /// 0850 /// Note that this does not consider malloc and alloca to have side 0851 /// effects because the newly allocated memory is completely invisible to 0852 /// instructions which don't use the returned value. For cases where this 0853 /// matters, isSafeToSpeculativelyExecute may be more appropriate. 0854 bool mayHaveSideEffects() const LLVM_READONLY; 0855 0856 /// Return true if the instruction can be removed if the result is unused. 0857 /// 0858 /// When constant folding some instructions cannot be removed even if their 0859 /// results are unused. Specifically terminator instructions and calls that 0860 /// may have side effects cannot be removed without semantically changing the 0861 /// generated program. 0862 bool isSafeToRemove() const LLVM_READONLY; 0863 0864 /// Return true if the instruction will return (unwinding is considered as 0865 /// a form of returning control flow here). 0866 bool willReturn() const LLVM_READONLY; 0867 0868 /// Return true if the instruction is a variety of EH-block. 0869 bool isEHPad() const { 0870 switch (getOpcode()) { 0871 case Instruction::CatchSwitch: 0872 case Instruction::CatchPad: 0873 case Instruction::CleanupPad: 0874 case Instruction::LandingPad: 0875 return true; 0876 default: 0877 return false; 0878 } 0879 } 0880 0881 /// Return true if the instruction is a llvm.lifetime.start or 0882 /// llvm.lifetime.end marker. 0883 bool isLifetimeStartOrEnd() const LLVM_READONLY; 0884 0885 /// Return true if the instruction is a llvm.launder.invariant.group or 0886 /// llvm.strip.invariant.group. 0887 bool isLaunderOrStripInvariantGroup() const LLVM_READONLY; 0888 0889 /// Return true if the instruction is a DbgInfoIntrinsic or PseudoProbeInst. 0890 bool isDebugOrPseudoInst() const LLVM_READONLY; 0891 0892 /// Return a pointer to the next non-debug instruction in the same basic 0893 /// block as 'this', or nullptr if no such instruction exists. Skip any pseudo 0894 /// operations if \c SkipPseudoOp is true. 0895 const Instruction * 0896 getNextNonDebugInstruction(bool SkipPseudoOp = false) const; 0897 Instruction *getNextNonDebugInstruction(bool SkipPseudoOp = false) { 0898 return const_cast<Instruction *>( 0899 static_cast<const Instruction *>(this)->getNextNonDebugInstruction( 0900 SkipPseudoOp)); 0901 } 0902 0903 /// Return a pointer to the previous non-debug instruction in the same basic 0904 /// block as 'this', or nullptr if no such instruction exists. Skip any pseudo 0905 /// operations if \c SkipPseudoOp is true. 0906 const Instruction * 0907 getPrevNonDebugInstruction(bool SkipPseudoOp = false) const; 0908 Instruction *getPrevNonDebugInstruction(bool SkipPseudoOp = false) { 0909 return const_cast<Instruction *>( 0910 static_cast<const Instruction *>(this)->getPrevNonDebugInstruction( 0911 SkipPseudoOp)); 0912 } 0913 0914 /// Create a copy of 'this' instruction that is identical in all ways except 0915 /// the following: 0916 /// * The instruction has no parent 0917 /// * The instruction has no name 0918 /// 0919 Instruction *clone() const; 0920 0921 /// Return true if the specified instruction is exactly identical to the 0922 /// current one. This means that all operands match and any extra information 0923 /// (e.g. load is volatile) agree. 0924 bool isIdenticalTo(const Instruction *I) const LLVM_READONLY; 0925 0926 /// This is like isIdenticalTo, except that it ignores the 0927 /// SubclassOptionalData flags, which may specify conditions under which the 0928 /// instruction's result is undefined. 0929 bool 0930 isIdenticalToWhenDefined(const Instruction *I, 0931 bool IntersectAttrs = false) const LLVM_READONLY; 0932 0933 /// When checking for operation equivalence (using isSameOperationAs) it is 0934 /// sometimes useful to ignore certain attributes. 0935 enum OperationEquivalenceFlags { 0936 /// Check for equivalence ignoring load/store alignment. 0937 CompareIgnoringAlignment = 1 << 0, 0938 /// Check for equivalence treating a type and a vector of that type 0939 /// as equivalent. 0940 CompareUsingScalarTypes = 1 << 1, 0941 /// Check for equivalence with intersected callbase attrs. 0942 CompareUsingIntersectedAttrs = 1 << 2, 0943 }; 0944 0945 /// This function determines if the specified instruction executes the same 0946 /// operation as the current one. This means that the opcodes, type, operand 0947 /// types and any other factors affecting the operation must be the same. This 0948 /// is similar to isIdenticalTo except the operands themselves don't have to 0949 /// be identical. 0950 /// @returns true if the specified instruction is the same operation as 0951 /// the current one. 0952 /// Determine if one instruction is the same operation as another. 0953 bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const LLVM_READONLY; 0954 0955 /// This function determines if the speficied instruction has the same 0956 /// "special" characteristics as the current one. This means that opcode 0957 /// specific details are the same. As a common example, if we are comparing 0958 /// loads, then hasSameSpecialState would compare the alignments (among 0959 /// other things). 0960 /// @returns true if the specific instruction has the same opcde specific 0961 /// characteristics as the current one. Determine if one instruction has the 0962 /// same state as another. 0963 bool hasSameSpecialState(const Instruction *I2, bool IgnoreAlignment = false, 0964 bool IntersectAttrs = false) const LLVM_READONLY; 0965 0966 /// Return true if there are any uses of this instruction in blocks other than 0967 /// the specified block. Note that PHI nodes are considered to evaluate their 0968 /// operands in the corresponding predecessor block. 0969 bool isUsedOutsideOfBlock(const BasicBlock *BB) const LLVM_READONLY; 0970 0971 /// Return the number of successors that this instruction has. The instruction 0972 /// must be a terminator. 0973 unsigned getNumSuccessors() const LLVM_READONLY; 0974 0975 /// Return the specified successor. This instruction must be a terminator. 0976 BasicBlock *getSuccessor(unsigned Idx) const LLVM_READONLY; 0977 0978 /// Update the specified successor to point at the provided block. This 0979 /// instruction must be a terminator. 0980 void setSuccessor(unsigned Idx, BasicBlock *BB); 0981 0982 /// Replace specified successor OldBB to point at the provided block. 0983 /// This instruction must be a terminator. 0984 void replaceSuccessorWith(BasicBlock *OldBB, BasicBlock *NewBB); 0985 0986 /// Methods for support type inquiry through isa, cast, and dyn_cast: 0987 static bool classof(const Value *V) { 0988 return V->getValueID() >= Value::InstructionVal; 0989 } 0990 0991 //---------------------------------------------------------------------- 0992 // Exported enumerations. 0993 // 0994 enum TermOps { // These terminate basic blocks 0995 #define FIRST_TERM_INST(N) TermOpsBegin = N, 0996 #define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N, 0997 #define LAST_TERM_INST(N) TermOpsEnd = N+1 0998 #include "llvm/IR/Instruction.def" 0999 }; 1000 1001 enum UnaryOps { 1002 #define FIRST_UNARY_INST(N) UnaryOpsBegin = N, 1003 #define HANDLE_UNARY_INST(N, OPC, CLASS) OPC = N, 1004 #define LAST_UNARY_INST(N) UnaryOpsEnd = N+1 1005 #include "llvm/IR/Instruction.def" 1006 }; 1007 1008 enum BinaryOps { 1009 #define FIRST_BINARY_INST(N) BinaryOpsBegin = N, 1010 #define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N, 1011 #define LAST_BINARY_INST(N) BinaryOpsEnd = N+1 1012 #include "llvm/IR/Instruction.def" 1013 }; 1014 1015 enum MemoryOps { 1016 #define FIRST_MEMORY_INST(N) MemoryOpsBegin = N, 1017 #define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N, 1018 #define LAST_MEMORY_INST(N) MemoryOpsEnd = N+1 1019 #include "llvm/IR/Instruction.def" 1020 }; 1021 1022 enum CastOps { 1023 #define FIRST_CAST_INST(N) CastOpsBegin = N, 1024 #define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N, 1025 #define LAST_CAST_INST(N) CastOpsEnd = N+1 1026 #include "llvm/IR/Instruction.def" 1027 }; 1028 1029 enum FuncletPadOps { 1030 #define FIRST_FUNCLETPAD_INST(N) FuncletPadOpsBegin = N, 1031 #define HANDLE_FUNCLETPAD_INST(N, OPC, CLASS) OPC = N, 1032 #define LAST_FUNCLETPAD_INST(N) FuncletPadOpsEnd = N+1 1033 #include "llvm/IR/Instruction.def" 1034 }; 1035 1036 enum OtherOps { 1037 #define FIRST_OTHER_INST(N) OtherOpsBegin = N, 1038 #define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N, 1039 #define LAST_OTHER_INST(N) OtherOpsEnd = N+1 1040 #include "llvm/IR/Instruction.def" 1041 }; 1042 1043 private: 1044 friend class SymbolTableListTraits<Instruction, ilist_iterator_bits<true>, 1045 ilist_parent<BasicBlock>>; 1046 friend class BasicBlock; // For renumbering. 1047 1048 // Shadow Value::setValueSubclassData with a private forwarding method so that 1049 // subclasses cannot accidentally use it. 1050 void setValueSubclassData(unsigned short D) { 1051 Value::setValueSubclassData(D); 1052 } 1053 1054 unsigned short getSubclassDataFromValue() const { 1055 return Value::getSubclassDataFromValue(); 1056 } 1057 1058 protected: 1059 // Instruction subclasses can stick up to 15 bits of stuff into the 1060 // SubclassData field of instruction with these members. 1061 1062 template <typename BitfieldElement> 1063 typename BitfieldElement::Type getSubclassData() const { 1064 static_assert( 1065 std::is_same<BitfieldElement, HasMetadataField>::value || 1066 !Bitfield::isOverlapping<BitfieldElement, HasMetadataField>(), 1067 "Must not overlap with the metadata bit"); 1068 return Bitfield::get<BitfieldElement>(getSubclassDataFromValue()); 1069 } 1070 1071 template <typename BitfieldElement> 1072 void setSubclassData(typename BitfieldElement::Type Value) { 1073 static_assert( 1074 std::is_same<BitfieldElement, HasMetadataField>::value || 1075 !Bitfield::isOverlapping<BitfieldElement, HasMetadataField>(), 1076 "Must not overlap with the metadata bit"); 1077 auto Storage = getSubclassDataFromValue(); 1078 Bitfield::set<BitfieldElement>(Storage, Value); 1079 setValueSubclassData(Storage); 1080 } 1081 1082 Instruction(Type *Ty, unsigned iType, AllocInfo AllocInfo, 1083 InsertPosition InsertBefore = nullptr); 1084 1085 private: 1086 /// Create a copy of this instruction. 1087 Instruction *cloneImpl() const; 1088 }; 1089 1090 inline void ilist_alloc_traits<Instruction>::deleteNode(Instruction *V) { 1091 V->deleteValue(); 1092 } 1093 1094 } // end namespace llvm 1095 1096 #endif // LLVM_IR_INSTRUCTION_H
| [ Source navigation ] | [ Diff markup ] | [ Identifier search ] | [ general search ] |
|
This page was automatically generated by the 2.3.7 LXR engine. The LXR team |
|