LLVM  mainline
Instruction.h
Go to the documentation of this file.
00001 //===-- llvm/Instruction.h - Instruction class definition -------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains the declaration of the Instruction class, which is the
00011 // base class for all of the LLVM instructions.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #ifndef LLVM_IR_INSTRUCTION_H
00016 #define LLVM_IR_INSTRUCTION_H
00017 
00018 #include "llvm/ADT/ArrayRef.h"
00019 #include "llvm/ADT/ilist_node.h"
00020 #include "llvm/IR/DebugLoc.h"
00021 #include "llvm/IR/SymbolTableListTraits.h"
00022 #include "llvm/IR/User.h"
00023 
00024 namespace llvm {
00025 
00026 class FastMathFlags;
00027 class LLVMContext;
00028 class MDNode;
00029 class BasicBlock;
00030 struct AAMDNodes;
00031 
00032 template <>
00033 struct SymbolTableListSentinelTraits<Instruction>
00034     : public ilist_half_embedded_sentinel_traits<Instruction> {};
00035 
00036 class Instruction : public User,
00037                     public ilist_node_with_parent<Instruction, BasicBlock> {
00038   void operator=(const Instruction &) = delete;
00039   Instruction(const Instruction &) = delete;
00040 
00041   BasicBlock *Parent;
00042   DebugLoc DbgLoc;                         // 'dbg' Metadata cache.
00043 
00044   enum {
00045     /// HasMetadataBit - This is a bit stored in the SubClassData field which
00046     /// indicates whether this instruction has metadata attached to it or not.
00047     HasMetadataBit = 1 << 15
00048   };
00049 public:
00050   // Out of line virtual method, so the vtable, etc has a home.
00051   ~Instruction() override;
00052 
00053   /// user_back - Specialize the methods defined in Value, as we know that an
00054   /// instruction can only be used by other instructions.
00055   Instruction       *user_back()       { return cast<Instruction>(*user_begin());}
00056   const Instruction *user_back() const { return cast<Instruction>(*user_begin());}
00057 
00058   inline const BasicBlock *getParent() const { return Parent; }
00059   inline       BasicBlock *getParent()       { return Parent; }
00060 
00061   /// \brief Return the module owning the function this instruction belongs to
00062   /// or nullptr it the function does not have a module.
00063   ///
00064   /// Note: this is undefined behavior if the instruction does not have a
00065   /// parent, or the parent basic block does not have a parent function.
00066   const Module *getModule() const;
00067   Module *getModule();
00068 
00069   /// \brief Return the function this instruction belongs to.
00070   ///
00071   /// Note: it is undefined behavior to call this on an instruction not
00072   /// currently inserted into a function.
00073   const Function *getFunction() const;
00074   Function *getFunction();
00075 
00076   /// removeFromParent - This method unlinks 'this' from the containing basic
00077   /// block, but does not delete it.
00078   ///
00079   void removeFromParent();
00080 
00081   /// eraseFromParent - This method unlinks 'this' from the containing basic
00082   /// block and deletes it.
00083   ///
00084   /// \returns an iterator pointing to the element after the erased one
00085   SymbolTableList<Instruction>::iterator eraseFromParent();
00086 
00087   /// Insert an unlinked instruction into a basic block immediately before
00088   /// the specified instruction.
00089   void insertBefore(Instruction *InsertPos);
00090 
00091   /// Insert an unlinked instruction into a basic block immediately after the
00092   /// specified instruction.
00093   void insertAfter(Instruction *InsertPos);
00094 
00095   /// moveBefore - Unlink this instruction from its current basic block and
00096   /// insert it into the basic block that MovePos lives in, right before
00097   /// MovePos.
00098   void moveBefore(Instruction *MovePos);
00099 
00100   //===--------------------------------------------------------------------===//
00101   // Subclass classification.
00102   //===--------------------------------------------------------------------===//
00103 
00104   /// getOpcode() returns a member of one of the enums like Instruction::Add.
00105   unsigned getOpcode() const { return getValueID() - InstructionVal; }
00106 
00107   const char *getOpcodeName() const { return getOpcodeName(getOpcode()); }
00108   bool isTerminator() const { return isTerminator(getOpcode()); }
00109   bool isBinaryOp() const { return isBinaryOp(getOpcode()); }
00110   bool isShift() { return isShift(getOpcode()); }
00111   bool isCast() const { return isCast(getOpcode()); }
00112   bool isFuncletPad() const { return isFuncletPad(getOpcode()); }
00113 
00114   static const char* getOpcodeName(unsigned OpCode);
00115 
00116   static inline bool isTerminator(unsigned OpCode) {
00117     return OpCode >= TermOpsBegin && OpCode < TermOpsEnd;
00118   }
00119 
00120   static inline bool isBinaryOp(unsigned Opcode) {
00121     return Opcode >= BinaryOpsBegin && Opcode < BinaryOpsEnd;
00122   }
00123 
00124   /// @brief Determine if the Opcode is one of the shift instructions.
00125   static inline bool isShift(unsigned Opcode) {
00126     return Opcode >= Shl && Opcode <= AShr;
00127   }
00128 
00129   /// isLogicalShift - Return true if this is a logical shift left or a logical
00130   /// shift right.
00131   inline bool isLogicalShift() const {
00132     return getOpcode() == Shl || getOpcode() == LShr;
00133   }
00134 
00135   /// isArithmeticShift - Return true if this is an arithmetic shift right.
00136   inline bool isArithmeticShift() const {
00137     return getOpcode() == AShr;
00138   }
00139 
00140   /// @brief Determine if the OpCode is one of the CastInst instructions.
00141   static inline bool isCast(unsigned OpCode) {
00142     return OpCode >= CastOpsBegin && OpCode < CastOpsEnd;
00143   }
00144 
00145   /// @brief Determine if the OpCode is one of the FuncletPadInst instructions.
00146   static inline bool isFuncletPad(unsigned OpCode) {
00147     return OpCode >= FuncletPadOpsBegin && OpCode < FuncletPadOpsEnd;
00148   }
00149 
00150   //===--------------------------------------------------------------------===//
00151   // Metadata manipulation.
00152   //===--------------------------------------------------------------------===//
00153 
00154   /// hasMetadata() - Return true if this instruction has any metadata attached
00155   /// to it.
00156   bool hasMetadata() const { return DbgLoc || hasMetadataHashEntry(); }
00157 
00158   /// hasMetadataOtherThanDebugLoc - Return true if this instruction has
00159   /// metadata attached to it other than a debug location.
00160   bool hasMetadataOtherThanDebugLoc() const {
00161     return hasMetadataHashEntry();
00162   }
00163 
00164   /// getMetadata - Get the metadata of given kind attached to this Instruction.
00165   /// If the metadata is not found then return null.
00166   MDNode *getMetadata(unsigned KindID) const {
00167     if (!hasMetadata()) return nullptr;
00168     return getMetadataImpl(KindID);
00169   }
00170 
00171   /// getMetadata - Get the metadata of given kind attached to this Instruction.
00172   /// If the metadata is not found then return null.
00173   MDNode *getMetadata(StringRef Kind) const {
00174     if (!hasMetadata()) return nullptr;
00175     return getMetadataImpl(Kind);
00176   }
00177 
00178   /// getAllMetadata - Get all metadata attached to this Instruction.  The first
00179   /// element of each pair returned is the KindID, the second element is the
00180   /// metadata value.  This list is returned sorted by the KindID.
00181   void
00182   getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
00183     if (hasMetadata())
00184       getAllMetadataImpl(MDs);
00185   }
00186 
00187   /// getAllMetadataOtherThanDebugLoc - This does the same thing as
00188   /// getAllMetadata, except that it filters out the debug location.
00189   void getAllMetadataOtherThanDebugLoc(
00190       SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
00191     if (hasMetadataOtherThanDebugLoc())
00192       getAllMetadataOtherThanDebugLocImpl(MDs);
00193   }
00194 
00195   /// getAAMetadata - Fills the AAMDNodes structure with AA metadata from
00196   /// this instruction. When Merge is true, the existing AA metadata is
00197   /// merged with that from this instruction providing the most-general result.
00198   void getAAMetadata(AAMDNodes &N, bool Merge = false) const;
00199 
00200   /// setMetadata - Set the metadata of the specified kind to the specified
00201   /// node.  This updates/replaces metadata if already present, or removes it if
00202   /// Node is null.
00203   void setMetadata(unsigned KindID, MDNode *Node);
00204   void setMetadata(StringRef Kind, MDNode *Node);
00205 
00206   /// Drop all unknown metadata except for debug locations.
00207   /// @{
00208   /// Passes are required to drop metadata they don't understand. This is a
00209   /// convenience method for passes to do so.
00210   void dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs);
00211   void dropUnknownNonDebugMetadata() {
00212     return dropUnknownNonDebugMetadata(None);
00213   }
00214   void dropUnknownNonDebugMetadata(unsigned ID1) {
00215     return dropUnknownNonDebugMetadata(makeArrayRef(ID1));
00216   }
00217   void dropUnknownNonDebugMetadata(unsigned ID1, unsigned ID2) {
00218     unsigned IDs[] = {ID1, ID2};
00219     return dropUnknownNonDebugMetadata(IDs);
00220   }
00221   /// @}
00222 
00223   /// setAAMetadata - Sets the metadata on this instruction from the
00224   /// AAMDNodes structure.
00225   void setAAMetadata(const AAMDNodes &N);
00226 
00227   /// setDebugLoc - Set the debug location information for this instruction.
00228   void setDebugLoc(DebugLoc Loc) { DbgLoc = std::move(Loc); }
00229 
00230   /// getDebugLoc - Return the debug location for this node as a DebugLoc.
00231   const DebugLoc &getDebugLoc() const { return DbgLoc; }
00232 
00233   /// Set or clear the unsafe-algebra flag on this instruction, which must be an
00234   /// operator which supports this flag. See LangRef.html for the meaning of
00235   /// this flag.
00236   void setHasUnsafeAlgebra(bool B);
00237 
00238   /// Set or clear the no-nans flag on this instruction, which must be an
00239   /// operator which supports this flag. See LangRef.html for the meaning of
00240   /// this flag.
00241   void setHasNoNaNs(bool B);
00242 
00243   /// Set or clear the no-infs flag on this instruction, which must be an
00244   /// operator which supports this flag. See LangRef.html for the meaning of
00245   /// this flag.
00246   void setHasNoInfs(bool B);
00247 
00248   /// Set or clear the no-signed-zeros flag on this instruction, which must be
00249   /// an operator which supports this flag. See LangRef.html for the meaning of
00250   /// this flag.
00251   void setHasNoSignedZeros(bool B);
00252 
00253   /// Set or clear the allow-reciprocal flag on this instruction, which must be
00254   /// an operator which supports this flag. See LangRef.html for the meaning of
00255   /// this flag.
00256   void setHasAllowReciprocal(bool B);
00257 
00258   /// Convenience function for setting multiple fast-math flags on this
00259   /// instruction, which must be an operator which supports these flags. See
00260   /// LangRef.html for the meaning of these flags.
00261   void setFastMathFlags(FastMathFlags FMF);
00262 
00263   /// Convenience function for transferring all fast-math flag values to this
00264   /// instruction, which must be an operator which supports these flags. See
00265   /// LangRef.html for the meaning of these flags.
00266   void copyFastMathFlags(FastMathFlags FMF);
00267 
00268   /// Determine whether the unsafe-algebra flag is set.
00269   bool hasUnsafeAlgebra() const;
00270 
00271   /// Determine whether the no-NaNs flag is set.
00272   bool hasNoNaNs() const;
00273 
00274   /// Determine whether the no-infs flag is set.
00275   bool hasNoInfs() const;
00276 
00277   /// Determine whether the no-signed-zeros flag is set.
00278   bool hasNoSignedZeros() const;
00279 
00280   /// Determine whether the allow-reciprocal flag is set.
00281   bool hasAllowReciprocal() const;
00282 
00283   /// Convenience function for getting all the fast-math flags, which must be an
00284   /// operator which supports these flags. See LangRef.html for the meaning of
00285   /// these flags.
00286   FastMathFlags getFastMathFlags() const;
00287 
00288   /// Copy I's fast-math flags
00289   void copyFastMathFlags(const Instruction *I);
00290 
00291 private:
00292   /// hasMetadataHashEntry - Return true if we have an entry in the on-the-side
00293   /// metadata hash.
00294   bool hasMetadataHashEntry() const {
00295     return (getSubclassDataFromValue() & HasMetadataBit) != 0;
00296   }
00297 
00298   // These are all implemented in Metadata.cpp.
00299   MDNode *getMetadataImpl(unsigned KindID) const;
00300   MDNode *getMetadataImpl(StringRef Kind) const;
00301   void
00302   getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
00303   void getAllMetadataOtherThanDebugLocImpl(
00304       SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
00305   void clearMetadataHashEntries();
00306 public:
00307   //===--------------------------------------------------------------------===//
00308   // Predicates and helper methods.
00309   //===--------------------------------------------------------------------===//
00310 
00311 
00312   /// isAssociative - Return true if the instruction is associative:
00313   ///
00314   ///   Associative operators satisfy:  x op (y op z) === (x op y) op z
00315   ///
00316   /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
00317   ///
00318   bool isAssociative() const;
00319   static bool isAssociative(unsigned op);
00320 
00321   /// isCommutative - Return true if the instruction is commutative:
00322   ///
00323   ///   Commutative operators satisfy: (x op y) === (y op x)
00324   ///
00325   /// In LLVM, these are the associative operators, plus SetEQ and SetNE, when
00326   /// applied to any type.
00327   ///
00328   bool isCommutative() const { return isCommutative(getOpcode()); }
00329   static bool isCommutative(unsigned op);
00330 
00331   /// isIdempotent - Return true if the instruction is idempotent:
00332   ///
00333   ///   Idempotent operators satisfy:  x op x === x
00334   ///
00335   /// In LLVM, the And and Or operators are idempotent.
00336   ///
00337   bool isIdempotent() const { return isIdempotent(getOpcode()); }
00338   static bool isIdempotent(unsigned op);
00339 
00340   /// isNilpotent - Return true if the instruction is nilpotent:
00341   ///
00342   ///   Nilpotent operators satisfy:  x op x === Id,
00343   ///
00344   ///   where Id is the identity for the operator, i.e. a constant such that
00345   ///     x op Id === x and Id op x === x for all x.
00346   ///
00347   /// In LLVM, the Xor operator is nilpotent.
00348   ///
00349   bool isNilpotent() const { return isNilpotent(getOpcode()); }
00350   static bool isNilpotent(unsigned op);
00351 
00352   /// mayWriteToMemory - Return true if this instruction may modify memory.
00353   ///
00354   bool mayWriteToMemory() const;
00355 
00356   /// mayReadFromMemory - Return true if this instruction may read memory.
00357   ///
00358   bool mayReadFromMemory() const;
00359 
00360   /// mayReadOrWriteMemory - Return true if this instruction may read or
00361   /// write memory.
00362   ///
00363   bool mayReadOrWriteMemory() const {
00364     return mayReadFromMemory() || mayWriteToMemory();
00365   }
00366 
00367   /// isAtomic - Return true if this instruction has an
00368   /// AtomicOrdering of unordered or higher.
00369   ///
00370   bool isAtomic() const;
00371 
00372   /// mayThrow - Return true if this instruction may throw an exception.
00373   ///
00374   bool mayThrow() const;
00375 
00376   /// mayReturn - Return true if this is a function that may return.
00377   /// this is true for all normal instructions. The only exception
00378   /// is functions that are marked with the 'noreturn' attribute.
00379   ///
00380   bool mayReturn() const;
00381 
00382   /// mayHaveSideEffects - Return true if the instruction may have side effects.
00383   ///
00384   /// Note that this does not consider malloc and alloca to have side
00385   /// effects because the newly allocated memory is completely invisible to
00386   /// instructions which don't use the returned value.  For cases where this
00387   /// matters, isSafeToSpeculativelyExecute may be more appropriate.
00388   bool mayHaveSideEffects() const {
00389     return mayWriteToMemory() || mayThrow() || !mayReturn();
00390   }
00391 
00392   /// \brief Return true if the instruction is a variety of EH-block.
00393   bool isEHPad() const {
00394     switch (getOpcode()) {
00395     case Instruction::CatchSwitch:
00396     case Instruction::CatchPad:
00397     case Instruction::CleanupPad:
00398     case Instruction::LandingPad:
00399       return true;
00400     default:
00401       return false;
00402     }
00403   }
00404 
00405   /// clone() - Create a copy of 'this' instruction that is identical in all
00406   /// ways except the following:
00407   ///   * The instruction has no parent
00408   ///   * The instruction has no name
00409   ///
00410   Instruction *clone() const;
00411 
00412   /// isIdenticalTo - Return true if the specified instruction is exactly
00413   /// identical to the current one.  This means that all operands match and any
00414   /// extra information (e.g. load is volatile) agree.
00415   bool isIdenticalTo(const Instruction *I) const;
00416 
00417   /// isIdenticalToWhenDefined - This is like isIdenticalTo, except that it
00418   /// ignores the SubclassOptionalData flags, which specify conditions
00419   /// under which the instruction's result is undefined.
00420   bool isIdenticalToWhenDefined(const Instruction *I) const;
00421 
00422   /// When checking for operation equivalence (using isSameOperationAs) it is
00423   /// sometimes useful to ignore certain attributes.
00424   enum OperationEquivalenceFlags {
00425     /// Check for equivalence ignoring load/store alignment.
00426     CompareIgnoringAlignment = 1<<0,
00427     /// Check for equivalence treating a type and a vector of that type
00428     /// as equivalent.
00429     CompareUsingScalarTypes = 1<<1
00430   };
00431 
00432   /// This function determines if the specified instruction executes the same
00433   /// operation as the current one. This means that the opcodes, type, operand
00434   /// types and any other factors affecting the operation must be the same. This
00435   /// is similar to isIdenticalTo except the operands themselves don't have to
00436   /// be identical.
00437   /// @returns true if the specified instruction is the same operation as
00438   /// the current one.
00439   /// @brief Determine if one instruction is the same operation as another.
00440   bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const;
00441 
00442   /// isUsedOutsideOfBlock - Return true if there are any uses of this
00443   /// instruction in blocks other than the specified block.  Note that PHI nodes
00444   /// are considered to evaluate their operands in the corresponding predecessor
00445   /// block.
00446   bool isUsedOutsideOfBlock(const BasicBlock *BB) const;
00447 
00448 
00449   /// Methods for support type inquiry through isa, cast, and dyn_cast:
00450   static inline bool classof(const Value *V) {
00451     return V->getValueID() >= Value::InstructionVal;
00452   }
00453 
00454   //----------------------------------------------------------------------
00455   // Exported enumerations.
00456   //
00457   enum TermOps {       // These terminate basic blocks
00458 #define  FIRST_TERM_INST(N)             TermOpsBegin = N,
00459 #define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N,
00460 #define   LAST_TERM_INST(N)             TermOpsEnd = N+1
00461 #include "llvm/IR/Instruction.def"
00462   };
00463 
00464   enum BinaryOps {
00465 #define  FIRST_BINARY_INST(N)             BinaryOpsBegin = N,
00466 #define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N,
00467 #define   LAST_BINARY_INST(N)             BinaryOpsEnd = N+1
00468 #include "llvm/IR/Instruction.def"
00469   };
00470 
00471   enum MemoryOps {
00472 #define  FIRST_MEMORY_INST(N)             MemoryOpsBegin = N,
00473 #define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N,
00474 #define   LAST_MEMORY_INST(N)             MemoryOpsEnd = N+1
00475 #include "llvm/IR/Instruction.def"
00476   };
00477 
00478   enum CastOps {
00479 #define  FIRST_CAST_INST(N)             CastOpsBegin = N,
00480 #define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N,
00481 #define   LAST_CAST_INST(N)             CastOpsEnd = N+1
00482 #include "llvm/IR/Instruction.def"
00483   };
00484 
00485   enum FuncletPadOps {
00486 #define  FIRST_FUNCLETPAD_INST(N)             FuncletPadOpsBegin = N,
00487 #define HANDLE_FUNCLETPAD_INST(N, OPC, CLASS) OPC = N,
00488 #define   LAST_FUNCLETPAD_INST(N)             FuncletPadOpsEnd = N+1
00489 #include "llvm/IR/Instruction.def"
00490   };
00491 
00492   enum OtherOps {
00493 #define  FIRST_OTHER_INST(N)             OtherOpsBegin = N,
00494 #define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N,
00495 #define   LAST_OTHER_INST(N)             OtherOpsEnd = N+1
00496 #include "llvm/IR/Instruction.def"
00497   };
00498 private:
00499   // Shadow Value::setValueSubclassData with a private forwarding method so that
00500   // subclasses cannot accidentally use it.
00501   void setValueSubclassData(unsigned short D) {
00502     Value::setValueSubclassData(D);
00503   }
00504   unsigned short getSubclassDataFromValue() const {
00505     return Value::getSubclassDataFromValue();
00506   }
00507 
00508   void setHasMetadataHashEntry(bool V) {
00509     setValueSubclassData((getSubclassDataFromValue() & ~HasMetadataBit) |
00510                          (V ? HasMetadataBit : 0));
00511   }
00512 
00513   friend class SymbolTableListTraits<Instruction>;
00514   void setParent(BasicBlock *P);
00515 protected:
00516   // Instruction subclasses can stick up to 15 bits of stuff into the
00517   // SubclassData field of instruction with these members.
00518 
00519   // Verify that only the low 15 bits are used.
00520   void setInstructionSubclassData(unsigned short D) {
00521     assert((D & HasMetadataBit) == 0 && "Out of range value put into field");
00522     setValueSubclassData((getSubclassDataFromValue() & HasMetadataBit) | D);
00523   }
00524 
00525   unsigned getSubclassDataFromInstruction() const {
00526     return getSubclassDataFromValue() & ~HasMetadataBit;
00527   }
00528 
00529   Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
00530               Instruction *InsertBefore = nullptr);
00531   Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
00532               BasicBlock *InsertAtEnd);
00533 
00534 private:
00535   /// Create a copy of this instruction.
00536   Instruction *cloneImpl() const;
00537 };
00538 
00539 // Instruction* is only 4-byte aligned.
00540 template<>
00541 class PointerLikeTypeTraits<Instruction*> {
00542   typedef Instruction* PT;
00543 public:
00544   static inline void *getAsVoidPointer(PT P) { return P; }
00545   static inline PT getFromVoidPointer(void *P) {
00546     return static_cast<PT>(P);
00547   }
00548   enum { NumLowBitsAvailable = 2 };
00549 };
00550 
00551 } // End llvm namespace
00552 
00553 #endif