Instruction.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. //===-- llvm/Instruction.h - Instruction class definition -------*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file contains the declaration of the Instruction class, which is the
  11. // base class for all of the LLVM instructions.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #ifndef LLVM_IR_INSTRUCTION_H
  15. #define LLVM_IR_INSTRUCTION_H
  16. #include "llvm/ADT/ArrayRef.h"
  17. #include "llvm/ADT/ilist_node.h"
  18. #include "llvm/IR/DebugLoc.h"
  19. #include "llvm/IR/SymbolTableListTraits.h"
  20. #include "llvm/IR/User.h"
  21. namespace llvm {
  22. class FastMathFlags;
  23. class LLVMContext;
  24. class MDNode;
  25. class BasicBlock;
  26. struct AAMDNodes;
  27. template <>
  28. struct ilist_traits<Instruction>
  29. : public SymbolTableListTraits<Instruction, BasicBlock> {
  30. /// \brief Return a node that marks the end of a list.
  31. ///
  32. /// The sentinel is relative to this instance, so we use a non-static
  33. /// method.
  34. Instruction *createSentinel() const;
  35. static void destroySentinel(Instruction *) {}
  36. Instruction *provideInitialHead() const { return createSentinel(); }
  37. Instruction *ensureHead(Instruction *) const { return createSentinel(); }
  38. static void noteHead(Instruction *, Instruction *) {}
  39. private:
  40. mutable ilist_half_node<Instruction> Sentinel;
  41. };
  42. class Instruction : public User, public ilist_node<Instruction> {
  43. void operator=(const Instruction &) = delete;
  44. Instruction(const Instruction &) = delete;
  45. BasicBlock *Parent;
  46. DebugLoc DbgLoc; // 'dbg' Metadata cache.
  47. enum {
  48. /// HasMetadataBit - This is a bit stored in the SubClassData field which
  49. /// indicates whether this instruction has metadata attached to it or not.
  50. HasMetadataBit = 1 << 15
  51. };
  52. public:
  53. // Out of line virtual method, so the vtable, etc has a home.
  54. ~Instruction() override;
  55. /// user_back - Specialize the methods defined in Value, as we know that an
  56. /// instruction can only be used by other instructions.
  57. Instruction *user_back() { return cast<Instruction>(*user_begin());}
  58. const Instruction *user_back() const { return cast<Instruction>(*user_begin());}
  59. inline const BasicBlock *getParent() const { return Parent; }
  60. inline BasicBlock *getParent() { return Parent; }
  61. /// \brief Return the module owning the function this instruction belongs to
  62. /// or nullptr it the function does not have a module.
  63. ///
  64. /// Note: this is undefined behavior if the instruction does not have a
  65. /// parent, or the parent basic block does not have a parent function.
  66. const Module *getModule() const;
  67. Module *getModule();
  68. /// removeFromParent - This method unlinks 'this' from the containing basic
  69. /// block, but does not delete it.
  70. ///
  71. void removeFromParent();
  72. /// eraseFromParent - This method unlinks 'this' from the containing basic
  73. /// block and deletes it.
  74. ///
  75. /// \returns an iterator pointing to the element after the erased one
  76. iplist<Instruction>::iterator eraseFromParent();
  77. /// Insert an unlinked instruction into a basic block immediately before
  78. /// the specified instruction.
  79. void insertBefore(Instruction *InsertPos);
  80. /// Insert an unlinked instruction into a basic block immediately after the
  81. /// specified instruction.
  82. void insertAfter(Instruction *InsertPos);
  83. /// moveBefore - Unlink this instruction from its current basic block and
  84. /// insert it into the basic block that MovePos lives in, right before
  85. /// MovePos.
  86. void moveBefore(Instruction *MovePos);
  87. //===--------------------------------------------------------------------===//
  88. // Subclass classification.
  89. //===--------------------------------------------------------------------===//
  90. /// getOpcode() returns a member of one of the enums like Instruction::Add.
  91. unsigned getOpcode() const { return getValueID() - InstructionVal; }
  92. const char *getOpcodeName() const { return getOpcodeName(getOpcode()); }
  93. bool isTerminator() const { return isTerminator(getOpcode()); }
  94. bool isBinaryOp() const { return isBinaryOp(getOpcode()); }
  95. bool isShift() { return isShift(getOpcode()); }
  96. bool isCast() const { return isCast(getOpcode()); }
  97. static const char* getOpcodeName(unsigned OpCode);
  98. static inline bool isTerminator(unsigned OpCode) {
  99. return OpCode >= TermOpsBegin && OpCode < TermOpsEnd;
  100. }
  101. static inline bool isBinaryOp(unsigned Opcode) {
  102. return Opcode >= BinaryOpsBegin && Opcode < BinaryOpsEnd;
  103. }
  104. /// @brief Determine if the Opcode is one of the shift instructions.
  105. static inline bool isShift(unsigned Opcode) {
  106. return Opcode >= Shl && Opcode <= AShr;
  107. }
  108. /// isLogicalShift - Return true if this is a logical shift left or a logical
  109. /// shift right.
  110. inline bool isLogicalShift() const {
  111. return getOpcode() == Shl || getOpcode() == LShr;
  112. }
  113. /// isArithmeticShift - Return true if this is an arithmetic shift right.
  114. inline bool isArithmeticShift() const {
  115. return getOpcode() == AShr;
  116. }
  117. /// @brief Determine if the OpCode is one of the CastInst instructions.
  118. static inline bool isCast(unsigned OpCode) {
  119. return OpCode >= CastOpsBegin && OpCode < CastOpsEnd;
  120. }
  121. //===--------------------------------------------------------------------===//
  122. // Metadata manipulation.
  123. //===--------------------------------------------------------------------===//
  124. /// hasMetadata() - Return true if this instruction has any metadata attached
  125. /// to it.
  126. bool hasMetadata() const { return DbgLoc || hasMetadataHashEntry(); }
  127. /// hasMetadataOtherThanDebugLoc - Return true if this instruction has
  128. /// metadata attached to it other than a debug location.
  129. bool hasMetadataOtherThanDebugLoc() const {
  130. return hasMetadataHashEntry();
  131. }
  132. /// getMetadata - Get the metadata of given kind attached to this Instruction.
  133. /// If the metadata is not found then return null.
  134. MDNode *getMetadata(unsigned KindID) const {
  135. if (!hasMetadata()) return nullptr;
  136. return getMetadataImpl(KindID);
  137. }
  138. /// getMetadata - Get the metadata of given kind attached to this Instruction.
  139. /// If the metadata is not found then return null.
  140. MDNode *getMetadata(StringRef Kind) const {
  141. if (!hasMetadata()) return nullptr;
  142. return getMetadataImpl(Kind);
  143. }
  144. /// getAllMetadata - Get all metadata attached to this Instruction. The first
  145. /// element of each pair returned is the KindID, the second element is the
  146. /// metadata value. This list is returned sorted by the KindID.
  147. void
  148. getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
  149. if (hasMetadata())
  150. getAllMetadataImpl(MDs);
  151. }
  152. /// getAllMetadataOtherThanDebugLoc - This does the same thing as
  153. /// getAllMetadata, except that it filters out the debug location.
  154. void getAllMetadataOtherThanDebugLoc(
  155. SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
  156. if (hasMetadataOtherThanDebugLoc())
  157. getAllMetadataOtherThanDebugLocImpl(MDs);
  158. }
  159. /// getAAMetadata - Fills the AAMDNodes structure with AA metadata from
  160. /// this instruction. When Merge is true, the existing AA metadata is
  161. /// merged with that from this instruction providing the most-general result.
  162. void getAAMetadata(AAMDNodes &N, bool Merge = false) const;
  163. /// setMetadata - Set the metadata of the specified kind to the specified
  164. /// node. This updates/replaces metadata if already present, or removes it if
  165. /// Node is null.
  166. void setMetadata(unsigned KindID, MDNode *Node);
  167. void setMetadata(StringRef Kind, MDNode *Node);
  168. /// \brief Drop unknown metadata.
  169. /// Passes are required to drop metadata they don't understand. This is a
  170. /// convenience method for passes to do so.
  171. void dropUnknownMetadata(ArrayRef<unsigned> KnownIDs);
  172. void dropUnknownMetadata() {
  173. return dropUnknownMetadata(None);
  174. }
  175. void dropUnknownMetadata(unsigned ID1) {
  176. return dropUnknownMetadata(makeArrayRef(ID1));
  177. }
  178. void dropUnknownMetadata(unsigned ID1, unsigned ID2) {
  179. unsigned IDs[] = {ID1, ID2};
  180. return dropUnknownMetadata(IDs);
  181. }
  182. /// setAAMetadata - Sets the metadata on this instruction from the
  183. /// AAMDNodes structure.
  184. void setAAMetadata(const AAMDNodes &N);
  185. /// setDebugLoc - Set the debug location information for this instruction.
  186. void setDebugLoc(DebugLoc Loc) { DbgLoc = std::move(Loc); }
  187. /// getDebugLoc - Return the debug location for this node as a DebugLoc.
  188. const DebugLoc &getDebugLoc() const { return DbgLoc; }
  189. /// Set or clear the unsafe-algebra flag on this instruction, which must be an
  190. /// operator which supports this flag. See LangRef.html for the meaning of
  191. /// this flag.
  192. void setHasUnsafeAlgebra(bool B);
  193. /// Set or clear the no-nans flag on this instruction, which must be an
  194. /// operator which supports this flag. See LangRef.html for the meaning of
  195. /// this flag.
  196. void setHasNoNaNs(bool B);
  197. /// Set or clear the no-infs flag on this instruction, which must be an
  198. /// operator which supports this flag. See LangRef.html for the meaning of
  199. /// this flag.
  200. void setHasNoInfs(bool B);
  201. /// Set or clear the no-signed-zeros flag on this instruction, which must be
  202. /// an operator which supports this flag. See LangRef.html for the meaning of
  203. /// this flag.
  204. void setHasNoSignedZeros(bool B);
  205. /// Set or clear the allow-reciprocal flag on this instruction, which must be
  206. /// an operator which supports this flag. See LangRef.html for the meaning of
  207. /// this flag.
  208. void setHasAllowReciprocal(bool B);
  209. /// Convenience function for setting multiple fast-math flags on this
  210. /// instruction, which must be an operator which supports these flags. See
  211. /// LangRef.html for the meaning of these flags.
  212. void setFastMathFlags(FastMathFlags FMF);
  213. /// Convenience function for transferring all fast-math flag values to this
  214. /// instruction, which must be an operator which supports these flags. See
  215. /// LangRef.html for the meaning of these flags.
  216. void copyFastMathFlags(FastMathFlags FMF);
  217. /// Determine whether the unsafe-algebra flag is set.
  218. bool hasUnsafeAlgebra() const;
  219. /// Determine whether the no-NaNs flag is set.
  220. bool hasNoNaNs() const;
  221. /// Determine whether the no-infs flag is set.
  222. bool hasNoInfs() const;
  223. /// Determine whether the no-signed-zeros flag is set.
  224. bool hasNoSignedZeros() const;
  225. /// Determine whether the allow-reciprocal flag is set.
  226. bool hasAllowReciprocal() const;
  227. /// Convenience function for getting all the fast-math flags, which must be an
  228. /// operator which supports these flags. See LangRef.html for the meaning of
  229. /// these flags.
  230. FastMathFlags getFastMathFlags() const;
  231. /// Copy I's fast-math flags
  232. void copyFastMathFlags(const Instruction *I);
  233. private:
  234. /// hasMetadataHashEntry - Return true if we have an entry in the on-the-side
  235. /// metadata hash.
  236. bool hasMetadataHashEntry() const {
  237. return (getSubclassDataFromValue() & HasMetadataBit) != 0;
  238. }
  239. // These are all implemented in Metadata.cpp.
  240. MDNode *getMetadataImpl(unsigned KindID) const;
  241. MDNode *getMetadataImpl(StringRef Kind) const;
  242. void
  243. getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
  244. void getAllMetadataOtherThanDebugLocImpl(
  245. SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
  246. void clearMetadataHashEntries();
  247. public:
  248. //===--------------------------------------------------------------------===//
  249. // Predicates and helper methods.
  250. //===--------------------------------------------------------------------===//
  251. /// isAssociative - Return true if the instruction is associative:
  252. ///
  253. /// Associative operators satisfy: x op (y op z) === (x op y) op z
  254. ///
  255. /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
  256. ///
  257. bool isAssociative() const;
  258. static bool isAssociative(unsigned op);
  259. /// isCommutative - Return true if the instruction is commutative:
  260. ///
  261. /// Commutative operators satisfy: (x op y) === (y op x)
  262. ///
  263. /// In LLVM, these are the associative operators, plus SetEQ and SetNE, when
  264. /// applied to any type.
  265. ///
  266. bool isCommutative() const { return isCommutative(getOpcode()); }
  267. static bool isCommutative(unsigned op);
  268. /// isIdempotent - Return true if the instruction is idempotent:
  269. ///
  270. /// Idempotent operators satisfy: x op x === x
  271. ///
  272. /// In LLVM, the And and Or operators are idempotent.
  273. ///
  274. bool isIdempotent() const { return isIdempotent(getOpcode()); }
  275. static bool isIdempotent(unsigned op);
  276. /// isNilpotent - Return true if the instruction is nilpotent:
  277. ///
  278. /// Nilpotent operators satisfy: x op x === Id,
  279. ///
  280. /// where Id is the identity for the operator, i.e. a constant such that
  281. /// x op Id === x and Id op x === x for all x.
  282. ///
  283. /// In LLVM, the Xor operator is nilpotent.
  284. ///
  285. bool isNilpotent() const { return isNilpotent(getOpcode()); }
  286. static bool isNilpotent(unsigned op);
  287. /// mayWriteToMemory - Return true if this instruction may modify memory.
  288. ///
  289. bool mayWriteToMemory() const;
  290. /// mayReadFromMemory - Return true if this instruction may read memory.
  291. ///
  292. bool mayReadFromMemory() const;
  293. /// mayReadOrWriteMemory - Return true if this instruction may read or
  294. /// write memory.
  295. ///
  296. bool mayReadOrWriteMemory() const {
  297. return mayReadFromMemory() || mayWriteToMemory();
  298. }
  299. /// isAtomic - Return true if this instruction has an
  300. /// AtomicOrdering of unordered or higher.
  301. ///
  302. bool isAtomic() const;
  303. /// mayThrow - Return true if this instruction may throw an exception.
  304. ///
  305. bool mayThrow() const;
  306. /// mayReturn - Return true if this is a function that may return.
  307. /// this is true for all normal instructions. The only exception
  308. /// is functions that are marked with the 'noreturn' attribute.
  309. ///
  310. bool mayReturn() const;
  311. /// mayHaveSideEffects - Return true if the instruction may have side effects.
  312. ///
  313. /// Note that this does not consider malloc and alloca to have side
  314. /// effects because the newly allocated memory is completely invisible to
  315. /// instructions which don't use the returned value. For cases where this
  316. /// matters, isSafeToSpeculativelyExecute may be more appropriate.
  317. bool mayHaveSideEffects() const {
  318. return mayWriteToMemory() || mayThrow() || !mayReturn();
  319. }
  320. /// clone() - Create a copy of 'this' instruction that is identical in all
  321. /// ways except the following:
  322. /// * The instruction has no parent
  323. /// * The instruction has no name
  324. ///
  325. Instruction *clone() const;
  326. /// isIdenticalTo - Return true if the specified instruction is exactly
  327. /// identical to the current one. This means that all operands match and any
  328. /// extra information (e.g. load is volatile) agree.
  329. bool isIdenticalTo(const Instruction *I) const;
  330. /// isIdenticalToWhenDefined - This is like isIdenticalTo, except that it
  331. /// ignores the SubclassOptionalData flags, which specify conditions
  332. /// under which the instruction's result is undefined.
  333. bool isIdenticalToWhenDefined(const Instruction *I) const;
  334. /// When checking for operation equivalence (using isSameOperationAs) it is
  335. /// sometimes useful to ignore certain attributes.
  336. enum OperationEquivalenceFlags {
  337. /// Check for equivalence ignoring load/store alignment.
  338. CompareIgnoringAlignment = 1<<0,
  339. /// Check for equivalence treating a type and a vector of that type
  340. /// as equivalent.
  341. CompareUsingScalarTypes = 1<<1
  342. };
  343. /// This function determines if the specified instruction executes the same
  344. /// operation as the current one. This means that the opcodes, type, operand
  345. /// types and any other factors affecting the operation must be the same. This
  346. /// is similar to isIdenticalTo except the operands themselves don't have to
  347. /// be identical.
  348. /// @returns true if the specified instruction is the same operation as
  349. /// the current one.
  350. /// @brief Determine if one instruction is the same operation as another.
  351. bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const;
  352. /// isUsedOutsideOfBlock - Return true if there are any uses of this
  353. /// instruction in blocks other than the specified block. Note that PHI nodes
  354. /// are considered to evaluate their operands in the corresponding predecessor
  355. /// block.
  356. bool isUsedOutsideOfBlock(const BasicBlock *BB) const;
  357. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  358. static inline bool classof(const Value *V) {
  359. return V->getValueID() >= Value::InstructionVal;
  360. }
  361. //----------------------------------------------------------------------
  362. // Exported enumerations.
  363. //
  364. enum TermOps { // These terminate basic blocks
  365. #define FIRST_TERM_INST(N) TermOpsBegin = N,
  366. #define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N,
  367. #define LAST_TERM_INST(N) TermOpsEnd = N+1
  368. #include "llvm/IR/Instruction.def"
  369. };
  370. enum BinaryOps {
  371. #define FIRST_BINARY_INST(N) BinaryOpsBegin = N,
  372. #define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N,
  373. #define LAST_BINARY_INST(N) BinaryOpsEnd = N+1
  374. #include "llvm/IR/Instruction.def"
  375. };
  376. enum MemoryOps {
  377. #define FIRST_MEMORY_INST(N) MemoryOpsBegin = N,
  378. #define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N,
  379. #define LAST_MEMORY_INST(N) MemoryOpsEnd = N+1
  380. #include "llvm/IR/Instruction.def"
  381. };
  382. enum CastOps {
  383. #define FIRST_CAST_INST(N) CastOpsBegin = N,
  384. #define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N,
  385. #define LAST_CAST_INST(N) CastOpsEnd = N+1
  386. #include "llvm/IR/Instruction.def"
  387. };
  388. enum OtherOps {
  389. #define FIRST_OTHER_INST(N) OtherOpsBegin = N,
  390. #define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N,
  391. #define LAST_OTHER_INST(N) OtherOpsEnd = N+1
  392. #include "llvm/IR/Instruction.def"
  393. };
  394. private:
  395. // Shadow Value::setValueSubclassData with a private forwarding method so that
  396. // subclasses cannot accidentally use it.
  397. void setValueSubclassData(unsigned short D) {
  398. Value::setValueSubclassData(D);
  399. }
  400. unsigned short getSubclassDataFromValue() const {
  401. return Value::getSubclassDataFromValue();
  402. }
  403. void setHasMetadataHashEntry(bool V) {
  404. setValueSubclassData((getSubclassDataFromValue() & ~HasMetadataBit) |
  405. (V ? HasMetadataBit : 0));
  406. }
  407. friend class SymbolTableListTraits<Instruction, BasicBlock>;
  408. void setParent(BasicBlock *P);
  409. protected:
  410. // Instruction subclasses can stick up to 15 bits of stuff into the
  411. // SubclassData field of instruction with these members.
  412. // Verify that only the low 15 bits are used.
  413. void setInstructionSubclassData(unsigned short D) {
  414. assert((D & HasMetadataBit) == 0 && "Out of range value put into field");
  415. setValueSubclassData((getSubclassDataFromValue() & HasMetadataBit) | D);
  416. }
  417. unsigned getSubclassDataFromInstruction() const {
  418. return getSubclassDataFromValue() & ~HasMetadataBit;
  419. }
  420. Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
  421. Instruction *InsertBefore = nullptr);
  422. Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
  423. BasicBlock *InsertAtEnd);
  424. private:
  425. /// Create a copy of this instruction.
  426. Instruction *cloneImpl() const;
  427. };
  428. inline Instruction *ilist_traits<Instruction>::createSentinel() const {
  429. // Since i(p)lists always publicly derive from their corresponding traits,
  430. // placing a data member in this class will augment the i(p)list. But since
  431. // the NodeTy is expected to be publicly derive from ilist_node<NodeTy>,
  432. // there is a legal viable downcast from it to NodeTy. We use this trick to
  433. // superimpose an i(p)list with a "ghostly" NodeTy, which becomes the
  434. // sentinel. Dereferencing the sentinel is forbidden (save the
  435. // ilist_node<NodeTy>), so no one will ever notice the superposition.
  436. return static_cast<Instruction *>(&Sentinel);
  437. }
  438. // Instruction* is only 4-byte aligned.
  439. template<>
  440. class PointerLikeTypeTraits<Instruction*> {
  441. typedef Instruction* PT;
  442. public:
  443. static inline void *getAsVoidPointer(PT P) { return P; }
  444. static inline PT getFromVoidPointer(void *P) {
  445. return static_cast<PT>(P);
  446. }
  447. enum { NumLowBitsAvailable = 2 };
  448. };
  449. } // End llvm namespace
  450. #endif