LLVM API Documentation

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