Instruction.h 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===-- llvm/Instruction.h - Instruction class definition -------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file contains the declaration of the Instruction class, which is the
  15. // base class for all of the LLVM instructions.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #ifndef LLVM_IR_INSTRUCTION_H
  19. #define LLVM_IR_INSTRUCTION_H
  20. #include "llvm/ADT/ArrayRef.h"
  21. #include "llvm/ADT/Bitfields.h"
  22. #include "llvm/ADT/StringRef.h"
  23. #include "llvm/ADT/ilist_node.h"
  24. #include "llvm/IR/DebugLoc.h"
  25. #include "llvm/IR/SymbolTableListTraits.h"
  26. #include "llvm/IR/User.h"
  27. #include "llvm/IR/Value.h"
  28. #include "llvm/Support/AtomicOrdering.h"
  29. #include <cstdint>
  30. #include <utility>
  31. namespace llvm {
  32. class BasicBlock;
  33. class FastMathFlags;
  34. class MDNode;
  35. class Module;
  36. struct AAMDNodes;
  37. template <> struct ilist_alloc_traits<Instruction> {
  38. static inline void deleteNode(Instruction *V);
  39. };
  40. class Instruction : public User,
  41. public ilist_node_with_parent<Instruction, BasicBlock> {
  42. BasicBlock *Parent;
  43. DebugLoc DbgLoc; // 'dbg' Metadata cache.
  44. /// Relative order of this instruction in its parent basic block. Used for
  45. /// O(1) local dominance checks between instructions.
  46. mutable unsigned Order = 0;
  47. protected:
  48. // The 15 first bits of `Value::SubclassData` are available for subclasses of
  49. // `Instruction` to use.
  50. using OpaqueField = Bitfield::Element<uint16_t, 0, 15>;
  51. // Template alias so that all Instruction storing alignment use the same
  52. // definiton.
  53. // Valid alignments are powers of two from 2^0 to 2^MaxAlignmentExponent =
  54. // 2^32. We store them as Log2(Alignment), so we need 6 bits to encode the 33
  55. // possible values.
  56. template <unsigned Offset>
  57. using AlignmentBitfieldElementT =
  58. typename Bitfield::Element<unsigned, Offset, 6,
  59. Value::MaxAlignmentExponent>;
  60. template <unsigned Offset>
  61. using BoolBitfieldElementT = typename Bitfield::Element<bool, Offset, 1>;
  62. template <unsigned Offset>
  63. using AtomicOrderingBitfieldElementT =
  64. typename Bitfield::Element<AtomicOrdering, Offset, 3,
  65. AtomicOrdering::LAST>;
  66. private:
  67. // The last bit is used to store whether the instruction has metadata attached
  68. // or not.
  69. using HasMetadataField = Bitfield::Element<bool, 15, 1>;
  70. protected:
  71. ~Instruction(); // Use deleteValue() to delete a generic Instruction.
  72. public:
  73. Instruction(const Instruction &) = delete;
  74. Instruction &operator=(const Instruction &) = delete;
  75. /// Specialize the methods defined in Value, as we know that an instruction
  76. /// can only be used by other instructions.
  77. Instruction *user_back() { return cast<Instruction>(*user_begin());}
  78. const Instruction *user_back() const { return cast<Instruction>(*user_begin());}
  79. inline const BasicBlock *getParent() const { return Parent; }
  80. inline BasicBlock *getParent() { return Parent; }
  81. /// Return the module owning the function this instruction belongs to
  82. /// or nullptr it the function does not have a module.
  83. ///
  84. /// Note: this is undefined behavior if the instruction does not have a
  85. /// parent, or the parent basic block does not have a parent function.
  86. const Module *getModule() const;
  87. Module *getModule() {
  88. return const_cast<Module *>(
  89. static_cast<const Instruction *>(this)->getModule());
  90. }
  91. /// Return the function this instruction belongs to.
  92. ///
  93. /// Note: it is undefined behavior to call this on an instruction not
  94. /// currently inserted into a function.
  95. const Function *getFunction() const;
  96. Function *getFunction() {
  97. return const_cast<Function *>(
  98. static_cast<const Instruction *>(this)->getFunction());
  99. }
  100. /// This method unlinks 'this' from the containing basic block, but does not
  101. /// delete it.
  102. void removeFromParent();
  103. /// This method unlinks 'this' from the containing basic block and deletes it.
  104. ///
  105. /// \returns an iterator pointing to the element after the erased one
  106. SymbolTableList<Instruction>::iterator eraseFromParent();
  107. /// Insert an unlinked instruction into a basic block immediately before
  108. /// the specified instruction.
  109. void insertBefore(Instruction *InsertPos);
  110. /// Insert an unlinked instruction into a basic block immediately after the
  111. /// specified instruction.
  112. void insertAfter(Instruction *InsertPos);
  113. /// Inserts an unlinked instruction into \p ParentBB at position \p It and
  114. /// returns the iterator of the inserted instruction.
  115. SymbolTableList<Instruction>::iterator
  116. insertInto(BasicBlock *ParentBB, SymbolTableList<Instruction>::iterator It);
  117. /// Unlink this instruction from its current basic block and insert it into
  118. /// the basic block that MovePos lives in, right before MovePos.
  119. void moveBefore(Instruction *MovePos);
  120. /// Unlink this instruction and insert into BB before I.
  121. ///
  122. /// \pre I is a valid iterator into BB.
  123. void moveBefore(BasicBlock &BB, SymbolTableList<Instruction>::iterator I);
  124. /// Unlink this instruction from its current basic block and insert it into
  125. /// the basic block that MovePos lives in, right after MovePos.
  126. void moveAfter(Instruction *MovePos);
  127. /// Given an instruction Other in the same basic block as this instruction,
  128. /// return true if this instruction comes before Other. In this worst case,
  129. /// this takes linear time in the number of instructions in the block. The
  130. /// results are cached, so in common cases when the block remains unmodified,
  131. /// it takes constant time.
  132. bool comesBefore(const Instruction *Other) const;
  133. /// Get the first insertion point at which the result of this instruction
  134. /// is defined. This is *not* the directly following instruction in a number
  135. /// of cases, e.g. phi nodes or terminators that return values. This function
  136. /// may return null if the insertion after the definition is not possible,
  137. /// e.g. due to a catchswitch terminator.
  138. Instruction *getInsertionPointAfterDef();
  139. //===--------------------------------------------------------------------===//
  140. // Subclass classification.
  141. //===--------------------------------------------------------------------===//
  142. /// Returns a member of one of the enums like Instruction::Add.
  143. unsigned getOpcode() const { return getValueID() - InstructionVal; }
  144. const char *getOpcodeName() const { return getOpcodeName(getOpcode()); }
  145. bool isTerminator() const { return isTerminator(getOpcode()); }
  146. bool isUnaryOp() const { return isUnaryOp(getOpcode()); }
  147. bool isBinaryOp() const { return isBinaryOp(getOpcode()); }
  148. bool isIntDivRem() const { return isIntDivRem(getOpcode()); }
  149. bool isShift() const { return isShift(getOpcode()); }
  150. bool isCast() const { return isCast(getOpcode()); }
  151. bool isFuncletPad() const { return isFuncletPad(getOpcode()); }
  152. bool isExceptionalTerminator() const {
  153. return isExceptionalTerminator(getOpcode());
  154. }
  155. /// It checks if this instruction is the only user of at least one of
  156. /// its operands.
  157. bool isOnlyUserOfAnyOperand();
  158. static const char* getOpcodeName(unsigned OpCode);
  159. static inline bool isTerminator(unsigned OpCode) {
  160. return OpCode >= TermOpsBegin && OpCode < TermOpsEnd;
  161. }
  162. static inline bool isUnaryOp(unsigned Opcode) {
  163. return Opcode >= UnaryOpsBegin && Opcode < UnaryOpsEnd;
  164. }
  165. static inline bool isBinaryOp(unsigned Opcode) {
  166. return Opcode >= BinaryOpsBegin && Opcode < BinaryOpsEnd;
  167. }
  168. static inline bool isIntDivRem(unsigned Opcode) {
  169. return Opcode == UDiv || Opcode == SDiv || Opcode == URem || Opcode == SRem;
  170. }
  171. /// Determine if the Opcode is one of the shift instructions.
  172. static inline bool isShift(unsigned Opcode) {
  173. return Opcode >= Shl && Opcode <= AShr;
  174. }
  175. /// Return true if this is a logical shift left or a logical shift right.
  176. inline bool isLogicalShift() const {
  177. return getOpcode() == Shl || getOpcode() == LShr;
  178. }
  179. /// Return true if this is an arithmetic shift right.
  180. inline bool isArithmeticShift() const {
  181. return getOpcode() == AShr;
  182. }
  183. /// Determine if the Opcode is and/or/xor.
  184. static inline bool isBitwiseLogicOp(unsigned Opcode) {
  185. return Opcode == And || Opcode == Or || Opcode == Xor;
  186. }
  187. /// Return true if this is and/or/xor.
  188. inline bool isBitwiseLogicOp() const {
  189. return isBitwiseLogicOp(getOpcode());
  190. }
  191. /// Determine if the OpCode is one of the CastInst instructions.
  192. static inline bool isCast(unsigned OpCode) {
  193. return OpCode >= CastOpsBegin && OpCode < CastOpsEnd;
  194. }
  195. /// Determine if the OpCode is one of the FuncletPadInst instructions.
  196. static inline bool isFuncletPad(unsigned OpCode) {
  197. return OpCode >= FuncletPadOpsBegin && OpCode < FuncletPadOpsEnd;
  198. }
  199. /// Returns true if the OpCode is a terminator related to exception handling.
  200. static inline bool isExceptionalTerminator(unsigned OpCode) {
  201. switch (OpCode) {
  202. case Instruction::CatchSwitch:
  203. case Instruction::CatchRet:
  204. case Instruction::CleanupRet:
  205. case Instruction::Invoke:
  206. case Instruction::Resume:
  207. return true;
  208. default:
  209. return false;
  210. }
  211. }
  212. //===--------------------------------------------------------------------===//
  213. // Metadata manipulation.
  214. //===--------------------------------------------------------------------===//
  215. /// Return true if this instruction has any metadata attached to it.
  216. bool hasMetadata() const { return DbgLoc || Value::hasMetadata(); }
  217. /// Return true if this instruction has metadata attached to it other than a
  218. /// debug location.
  219. bool hasMetadataOtherThanDebugLoc() const { return Value::hasMetadata(); }
  220. /// Return true if this instruction has the given type of metadata attached.
  221. bool hasMetadata(unsigned KindID) const {
  222. return getMetadata(KindID) != nullptr;
  223. }
  224. /// Return true if this instruction has the given type of metadata attached.
  225. bool hasMetadata(StringRef Kind) const {
  226. return getMetadata(Kind) != nullptr;
  227. }
  228. /// Get the metadata of given kind attached to this Instruction.
  229. /// If the metadata is not found then return null.
  230. MDNode *getMetadata(unsigned KindID) const {
  231. if (!hasMetadata()) return nullptr;
  232. return getMetadataImpl(KindID);
  233. }
  234. /// Get the metadata of given kind attached to this Instruction.
  235. /// If the metadata is not found then return null.
  236. MDNode *getMetadata(StringRef Kind) const {
  237. if (!hasMetadata()) return nullptr;
  238. return getMetadataImpl(Kind);
  239. }
  240. /// Get all metadata attached to this Instruction. The first element of each
  241. /// pair returned is the KindID, the second element is the metadata value.
  242. /// This list is returned sorted by the KindID.
  243. void
  244. getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
  245. if (hasMetadata())
  246. getAllMetadataImpl(MDs);
  247. }
  248. /// This does the same thing as getAllMetadata, except that it filters out the
  249. /// debug location.
  250. void getAllMetadataOtherThanDebugLoc(
  251. SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
  252. Value::getAllMetadata(MDs);
  253. }
  254. /// Set the metadata of the specified kind to the specified node. This updates
  255. /// or replaces metadata if already present, or removes it if Node is null.
  256. void setMetadata(unsigned KindID, MDNode *Node);
  257. void setMetadata(StringRef Kind, MDNode *Node);
  258. /// Copy metadata from \p SrcInst to this instruction. \p WL, if not empty,
  259. /// specifies the list of meta data that needs to be copied. If \p WL is
  260. /// empty, all meta data will be copied.
  261. void copyMetadata(const Instruction &SrcInst,
  262. ArrayRef<unsigned> WL = ArrayRef<unsigned>());
  263. /// If the instruction has "branch_weights" MD_prof metadata and the MDNode
  264. /// has three operands (including name string), swap the order of the
  265. /// metadata.
  266. void swapProfMetadata();
  267. /// Drop all unknown metadata except for debug locations.
  268. /// @{
  269. /// Passes are required to drop metadata they don't understand. This is a
  270. /// convenience method for passes to do so.
  271. /// dropUndefImplyingAttrsAndUnknownMetadata should be used instead of
  272. /// this API if the Instruction being modified is a call.
  273. void dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs);
  274. void dropUnknownNonDebugMetadata() {
  275. return dropUnknownNonDebugMetadata(std::nullopt);
  276. }
  277. void dropUnknownNonDebugMetadata(unsigned ID1) {
  278. return dropUnknownNonDebugMetadata(ArrayRef(ID1));
  279. }
  280. void dropUnknownNonDebugMetadata(unsigned ID1, unsigned ID2) {
  281. unsigned IDs[] = {ID1, ID2};
  282. return dropUnknownNonDebugMetadata(IDs);
  283. }
  284. /// @}
  285. /// Adds an !annotation metadata node with \p Annotation to this instruction.
  286. /// If this instruction already has !annotation metadata, append \p Annotation
  287. /// to the existing node.
  288. void addAnnotationMetadata(StringRef Annotation);
  289. /// Returns the AA metadata for this instruction.
  290. AAMDNodes getAAMetadata() const;
  291. /// Sets the AA metadata on this instruction from the AAMDNodes structure.
  292. void setAAMetadata(const AAMDNodes &N);
  293. /// Retrieve total raw weight values of a branch.
  294. /// Returns true on success with profile total weights filled in.
  295. /// Returns false if no metadata was found.
  296. bool extractProfTotalWeight(uint64_t &TotalVal) const;
  297. /// Set the debug location information for this instruction.
  298. void setDebugLoc(DebugLoc Loc) { DbgLoc = std::move(Loc); }
  299. /// Return the debug location for this node as a DebugLoc.
  300. const DebugLoc &getDebugLoc() const { return DbgLoc; }
  301. /// Set or clear the nuw flag on this instruction, which must be an operator
  302. /// which supports this flag. See LangRef.html for the meaning of this flag.
  303. void setHasNoUnsignedWrap(bool b = true);
  304. /// Set or clear the nsw flag on this instruction, which must be an operator
  305. /// which supports this flag. See LangRef.html for the meaning of this flag.
  306. void setHasNoSignedWrap(bool b = true);
  307. /// Set or clear the exact flag on this instruction, which must be an operator
  308. /// which supports this flag. See LangRef.html for the meaning of this flag.
  309. void setIsExact(bool b = true);
  310. /// Determine whether the no unsigned wrap flag is set.
  311. bool hasNoUnsignedWrap() const LLVM_READONLY;
  312. /// Determine whether the no signed wrap flag is set.
  313. bool hasNoSignedWrap() const LLVM_READONLY;
  314. /// Return true if this operator has flags which may cause this instruction
  315. /// to evaluate to poison despite having non-poison inputs.
  316. bool hasPoisonGeneratingFlags() const LLVM_READONLY;
  317. /// Drops flags that may cause this instruction to evaluate to poison despite
  318. /// having non-poison inputs.
  319. void dropPoisonGeneratingFlags();
  320. /// Return true if this instruction has poison-generating metadata.
  321. bool hasPoisonGeneratingMetadata() const LLVM_READONLY;
  322. /// Drops metadata that may generate poison.
  323. void dropPoisonGeneratingMetadata();
  324. /// Return true if this instruction has poison-generating flags or metadata.
  325. bool hasPoisonGeneratingFlagsOrMetadata() const {
  326. return hasPoisonGeneratingFlags() || hasPoisonGeneratingMetadata();
  327. }
  328. /// Drops flags and metadata that may generate poison.
  329. void dropPoisonGeneratingFlagsAndMetadata() {
  330. dropPoisonGeneratingFlags();
  331. dropPoisonGeneratingMetadata();
  332. }
  333. /// This function drops non-debug unknown metadata (through
  334. /// dropUnknownNonDebugMetadata). For calls, it also drops parameter and
  335. /// return attributes that can cause undefined behaviour. Both of these should
  336. /// be done by passes which move instructions in IR.
  337. void
  338. dropUndefImplyingAttrsAndUnknownMetadata(ArrayRef<unsigned> KnownIDs = {});
  339. /// Determine whether the exact flag is set.
  340. bool isExact() const LLVM_READONLY;
  341. /// Set or clear all fast-math-flags on this instruction, which must be an
  342. /// operator which supports this flag. See LangRef.html for the meaning of
  343. /// this flag.
  344. void setFast(bool B);
  345. /// Set or clear the reassociation flag on this instruction, which must be
  346. /// an operator which supports this flag. See LangRef.html for the meaning of
  347. /// this flag.
  348. void setHasAllowReassoc(bool B);
  349. /// Set or clear the no-nans flag on this instruction, which must be an
  350. /// operator which supports this flag. See LangRef.html for the meaning of
  351. /// this flag.
  352. void setHasNoNaNs(bool B);
  353. /// Set or clear the no-infs flag on this instruction, which must be an
  354. /// operator which supports this flag. See LangRef.html for the meaning of
  355. /// this flag.
  356. void setHasNoInfs(bool B);
  357. /// Set or clear the no-signed-zeros flag on this instruction, which must be
  358. /// an operator which supports this flag. See LangRef.html for the meaning of
  359. /// this flag.
  360. void setHasNoSignedZeros(bool B);
  361. /// Set or clear the allow-reciprocal flag on this instruction, which must be
  362. /// an operator which supports this flag. See LangRef.html for the meaning of
  363. /// this flag.
  364. void setHasAllowReciprocal(bool B);
  365. /// Set or clear the allow-contract flag on this instruction, which must be
  366. /// an operator which supports this flag. See LangRef.html for the meaning of
  367. /// this flag.
  368. void setHasAllowContract(bool B);
  369. /// Set or clear the approximate-math-functions flag on this instruction,
  370. /// which must be an operator which supports this flag. See LangRef.html for
  371. /// the meaning of this flag.
  372. void setHasApproxFunc(bool B);
  373. /// Convenience function for setting multiple fast-math flags on this
  374. /// instruction, which must be an operator which supports these flags. See
  375. /// LangRef.html for the meaning of these flags.
  376. void setFastMathFlags(FastMathFlags FMF);
  377. /// Convenience function for transferring all fast-math flag values to this
  378. /// instruction, which must be an operator which supports these flags. See
  379. /// LangRef.html for the meaning of these flags.
  380. void copyFastMathFlags(FastMathFlags FMF);
  381. /// Determine whether all fast-math-flags are set.
  382. bool isFast() const LLVM_READONLY;
  383. /// Determine whether the allow-reassociation flag is set.
  384. bool hasAllowReassoc() const LLVM_READONLY;
  385. /// Determine whether the no-NaNs flag is set.
  386. bool hasNoNaNs() const LLVM_READONLY;
  387. /// Determine whether the no-infs flag is set.
  388. bool hasNoInfs() const LLVM_READONLY;
  389. /// Determine whether the no-signed-zeros flag is set.
  390. bool hasNoSignedZeros() const LLVM_READONLY;
  391. /// Determine whether the allow-reciprocal flag is set.
  392. bool hasAllowReciprocal() const LLVM_READONLY;
  393. /// Determine whether the allow-contract flag is set.
  394. bool hasAllowContract() const LLVM_READONLY;
  395. /// Determine whether the approximate-math-functions flag is set.
  396. bool hasApproxFunc() const LLVM_READONLY;
  397. /// Convenience function for getting all the fast-math flags, which must be an
  398. /// operator which supports these flags. See LangRef.html for the meaning of
  399. /// these flags.
  400. FastMathFlags getFastMathFlags() const LLVM_READONLY;
  401. /// Copy I's fast-math flags
  402. void copyFastMathFlags(const Instruction *I);
  403. /// Convenience method to copy supported exact, fast-math, and (optionally)
  404. /// wrapping flags from V to this instruction.
  405. void copyIRFlags(const Value *V, bool IncludeWrapFlags = true);
  406. /// Logical 'and' of any supported wrapping, exact, and fast-math flags of
  407. /// V and this instruction.
  408. void andIRFlags(const Value *V);
  409. /// Merge 2 debug locations and apply it to the Instruction. If the
  410. /// instruction is a CallIns, we need to traverse the inline chain to find
  411. /// the common scope. This is not efficient for N-way merging as each time
  412. /// you merge 2 iterations, you need to rebuild the hashmap to find the
  413. /// common scope. However, we still choose this API because:
  414. /// 1) Simplicity: it takes 2 locations instead of a list of locations.
  415. /// 2) In worst case, it increases the complexity from O(N*I) to
  416. /// O(2*N*I), where N is # of Instructions to merge, and I is the
  417. /// maximum level of inline stack. So it is still linear.
  418. /// 3) Merging of call instructions should be extremely rare in real
  419. /// applications, thus the N-way merging should be in code path.
  420. /// The DebugLoc attached to this instruction will be overwritten by the
  421. /// merged DebugLoc.
  422. void applyMergedLocation(const DILocation *LocA, const DILocation *LocB);
  423. /// Updates the debug location given that the instruction has been hoisted
  424. /// from a block to a predecessor of that block.
  425. /// Note: it is undefined behavior to call this on an instruction not
  426. /// currently inserted into a function.
  427. void updateLocationAfterHoist();
  428. /// Drop the instruction's debug location. This does not guarantee removal
  429. /// of the !dbg source location attachment, as it must set a line 0 location
  430. /// with scope information attached on call instructions. To guarantee
  431. /// removal of the !dbg attachment, use the \ref setDebugLoc() API.
  432. /// Note: it is undefined behavior to call this on an instruction not
  433. /// currently inserted into a function.
  434. void dropLocation();
  435. /// Merge the DIAssignID metadata from this instruction and those attached to
  436. /// instructions in \p SourceInstructions. This process performs a RAUW on
  437. /// the MetadataAsValue uses of the merged DIAssignID nodes. Not every
  438. /// instruction in \p SourceInstructions needs to have DIAssignID
  439. /// metadata. If none of them do then nothing happens. If this instruction
  440. /// does not have a DIAssignID attachment but at least one in \p
  441. /// SourceInstructions does then the merged one will be attached to
  442. /// it. However, instructions without attachments in \p SourceInstructions
  443. /// are not modified.
  444. void mergeDIAssignID(ArrayRef<const Instruction *> SourceInstructions);
  445. private:
  446. // These are all implemented in Metadata.cpp.
  447. MDNode *getMetadataImpl(unsigned KindID) const;
  448. MDNode *getMetadataImpl(StringRef Kind) const;
  449. void
  450. getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
  451. /// Update the LLVMContext ID-to-Instruction(s) mapping. If \p ID is nullptr
  452. /// then clear the mapping for this instruction.
  453. void updateDIAssignIDMapping(DIAssignID *ID);
  454. public:
  455. //===--------------------------------------------------------------------===//
  456. // Predicates and helper methods.
  457. //===--------------------------------------------------------------------===//
  458. /// Return true if the instruction is associative:
  459. ///
  460. /// Associative operators satisfy: x op (y op z) === (x op y) op z
  461. ///
  462. /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
  463. ///
  464. bool isAssociative() const LLVM_READONLY;
  465. static bool isAssociative(unsigned Opcode) {
  466. return Opcode == And || Opcode == Or || Opcode == Xor ||
  467. Opcode == Add || Opcode == Mul;
  468. }
  469. /// Return true if the instruction is commutative:
  470. ///
  471. /// Commutative operators satisfy: (x op y) === (y op x)
  472. ///
  473. /// In LLVM, these are the commutative operators, plus SetEQ and SetNE, when
  474. /// applied to any type.
  475. ///
  476. bool isCommutative() const LLVM_READONLY;
  477. static bool isCommutative(unsigned Opcode) {
  478. switch (Opcode) {
  479. case Add: case FAdd:
  480. case Mul: case FMul:
  481. case And: case Or: case Xor:
  482. return true;
  483. default:
  484. return false;
  485. }
  486. }
  487. /// Return true if the instruction is idempotent:
  488. ///
  489. /// Idempotent operators satisfy: x op x === x
  490. ///
  491. /// In LLVM, the And and Or operators are idempotent.
  492. ///
  493. bool isIdempotent() const { return isIdempotent(getOpcode()); }
  494. static bool isIdempotent(unsigned Opcode) {
  495. return Opcode == And || Opcode == Or;
  496. }
  497. /// Return true if the instruction is nilpotent:
  498. ///
  499. /// Nilpotent operators satisfy: x op x === Id,
  500. ///
  501. /// where Id is the identity for the operator, i.e. a constant such that
  502. /// x op Id === x and Id op x === x for all x.
  503. ///
  504. /// In LLVM, the Xor operator is nilpotent.
  505. ///
  506. bool isNilpotent() const { return isNilpotent(getOpcode()); }
  507. static bool isNilpotent(unsigned Opcode) {
  508. return Opcode == Xor;
  509. }
  510. /// Return true if this instruction may modify memory.
  511. bool mayWriteToMemory() const LLVM_READONLY;
  512. /// Return true if this instruction may read memory.
  513. bool mayReadFromMemory() const LLVM_READONLY;
  514. /// Return true if this instruction may read or write memory.
  515. bool mayReadOrWriteMemory() const {
  516. return mayReadFromMemory() || mayWriteToMemory();
  517. }
  518. /// Return true if this instruction has an AtomicOrdering of unordered or
  519. /// higher.
  520. bool isAtomic() const LLVM_READONLY;
  521. /// Return true if this atomic instruction loads from memory.
  522. bool hasAtomicLoad() const LLVM_READONLY;
  523. /// Return true if this atomic instruction stores to memory.
  524. bool hasAtomicStore() const LLVM_READONLY;
  525. /// Return true if this instruction has a volatile memory access.
  526. bool isVolatile() const LLVM_READONLY;
  527. /// Return true if this instruction may throw an exception.
  528. bool mayThrow() const LLVM_READONLY;
  529. /// Return true if this instruction behaves like a memory fence: it can load
  530. /// or store to memory location without being given a memory location.
  531. bool isFenceLike() const {
  532. switch (getOpcode()) {
  533. default:
  534. return false;
  535. // This list should be kept in sync with the list in mayWriteToMemory for
  536. // all opcodes which don't have a memory location.
  537. case Instruction::Fence:
  538. case Instruction::CatchPad:
  539. case Instruction::CatchRet:
  540. case Instruction::Call:
  541. case Instruction::Invoke:
  542. return true;
  543. }
  544. }
  545. /// Return true if the instruction may have side effects.
  546. ///
  547. /// Side effects are:
  548. /// * Writing to memory.
  549. /// * Unwinding.
  550. /// * Not returning (e.g. an infinite loop).
  551. ///
  552. /// Note that this does not consider malloc and alloca to have side
  553. /// effects because the newly allocated memory is completely invisible to
  554. /// instructions which don't use the returned value. For cases where this
  555. /// matters, isSafeToSpeculativelyExecute may be more appropriate.
  556. bool mayHaveSideEffects() const LLVM_READONLY;
  557. /// Return true if the instruction can be removed if the result is unused.
  558. ///
  559. /// When constant folding some instructions cannot be removed even if their
  560. /// results are unused. Specifically terminator instructions and calls that
  561. /// may have side effects cannot be removed without semantically changing the
  562. /// generated program.
  563. bool isSafeToRemove() const LLVM_READONLY;
  564. /// Return true if the instruction will return (unwinding is considered as
  565. /// a form of returning control flow here).
  566. bool willReturn() const LLVM_READONLY;
  567. /// Return true if the instruction is a variety of EH-block.
  568. bool isEHPad() const {
  569. switch (getOpcode()) {
  570. case Instruction::CatchSwitch:
  571. case Instruction::CatchPad:
  572. case Instruction::CleanupPad:
  573. case Instruction::LandingPad:
  574. return true;
  575. default:
  576. return false;
  577. }
  578. }
  579. /// Return true if the instruction is a llvm.lifetime.start or
  580. /// llvm.lifetime.end marker.
  581. bool isLifetimeStartOrEnd() const LLVM_READONLY;
  582. /// Return true if the instruction is a llvm.launder.invariant.group or
  583. /// llvm.strip.invariant.group.
  584. bool isLaunderOrStripInvariantGroup() const LLVM_READONLY;
  585. /// Return true if the instruction is a DbgInfoIntrinsic or PseudoProbeInst.
  586. bool isDebugOrPseudoInst() const LLVM_READONLY;
  587. /// Return a pointer to the next non-debug instruction in the same basic
  588. /// block as 'this', or nullptr if no such instruction exists. Skip any pseudo
  589. /// operations if \c SkipPseudoOp is true.
  590. const Instruction *
  591. getNextNonDebugInstruction(bool SkipPseudoOp = false) const;
  592. Instruction *getNextNonDebugInstruction(bool SkipPseudoOp = false) {
  593. return const_cast<Instruction *>(
  594. static_cast<const Instruction *>(this)->getNextNonDebugInstruction(
  595. SkipPseudoOp));
  596. }
  597. /// Return a pointer to the previous non-debug instruction in the same basic
  598. /// block as 'this', or nullptr if no such instruction exists. Skip any pseudo
  599. /// operations if \c SkipPseudoOp is true.
  600. const Instruction *
  601. getPrevNonDebugInstruction(bool SkipPseudoOp = false) const;
  602. Instruction *getPrevNonDebugInstruction(bool SkipPseudoOp = false) {
  603. return const_cast<Instruction *>(
  604. static_cast<const Instruction *>(this)->getPrevNonDebugInstruction(
  605. SkipPseudoOp));
  606. }
  607. /// Create a copy of 'this' instruction that is identical in all ways except
  608. /// the following:
  609. /// * The instruction has no parent
  610. /// * The instruction has no name
  611. ///
  612. Instruction *clone() const;
  613. /// Return true if the specified instruction is exactly identical to the
  614. /// current one. This means that all operands match and any extra information
  615. /// (e.g. load is volatile) agree.
  616. bool isIdenticalTo(const Instruction *I) const LLVM_READONLY;
  617. /// This is like isIdenticalTo, except that it ignores the
  618. /// SubclassOptionalData flags, which may specify conditions under which the
  619. /// instruction's result is undefined.
  620. bool isIdenticalToWhenDefined(const Instruction *I) const LLVM_READONLY;
  621. /// When checking for operation equivalence (using isSameOperationAs) it is
  622. /// sometimes useful to ignore certain attributes.
  623. enum OperationEquivalenceFlags {
  624. /// Check for equivalence ignoring load/store alignment.
  625. CompareIgnoringAlignment = 1<<0,
  626. /// Check for equivalence treating a type and a vector of that type
  627. /// as equivalent.
  628. CompareUsingScalarTypes = 1<<1
  629. };
  630. /// This function determines if the specified instruction executes the same
  631. /// operation as the current one. This means that the opcodes, type, operand
  632. /// types and any other factors affecting the operation must be the same. This
  633. /// is similar to isIdenticalTo except the operands themselves don't have to
  634. /// be identical.
  635. /// @returns true if the specified instruction is the same operation as
  636. /// the current one.
  637. /// Determine if one instruction is the same operation as another.
  638. bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const LLVM_READONLY;
  639. /// Return true if there are any uses of this instruction in blocks other than
  640. /// the specified block. Note that PHI nodes are considered to evaluate their
  641. /// operands in the corresponding predecessor block.
  642. bool isUsedOutsideOfBlock(const BasicBlock *BB) const LLVM_READONLY;
  643. /// Return the number of successors that this instruction has. The instruction
  644. /// must be a terminator.
  645. unsigned getNumSuccessors() const LLVM_READONLY;
  646. /// Return the specified successor. This instruction must be a terminator.
  647. BasicBlock *getSuccessor(unsigned Idx) const LLVM_READONLY;
  648. /// Update the specified successor to point at the provided block. This
  649. /// instruction must be a terminator.
  650. void setSuccessor(unsigned Idx, BasicBlock *BB);
  651. /// Replace specified successor OldBB to point at the provided block.
  652. /// This instruction must be a terminator.
  653. void replaceSuccessorWith(BasicBlock *OldBB, BasicBlock *NewBB);
  654. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  655. static bool classof(const Value *V) {
  656. return V->getValueID() >= Value::InstructionVal;
  657. }
  658. //----------------------------------------------------------------------
  659. // Exported enumerations.
  660. //
  661. enum TermOps { // These terminate basic blocks
  662. #define FIRST_TERM_INST(N) TermOpsBegin = N,
  663. #define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N,
  664. #define LAST_TERM_INST(N) TermOpsEnd = N+1
  665. #include "llvm/IR/Instruction.def"
  666. };
  667. enum UnaryOps {
  668. #define FIRST_UNARY_INST(N) UnaryOpsBegin = N,
  669. #define HANDLE_UNARY_INST(N, OPC, CLASS) OPC = N,
  670. #define LAST_UNARY_INST(N) UnaryOpsEnd = N+1
  671. #include "llvm/IR/Instruction.def"
  672. };
  673. enum BinaryOps {
  674. #define FIRST_BINARY_INST(N) BinaryOpsBegin = N,
  675. #define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N,
  676. #define LAST_BINARY_INST(N) BinaryOpsEnd = N+1
  677. #include "llvm/IR/Instruction.def"
  678. };
  679. enum MemoryOps {
  680. #define FIRST_MEMORY_INST(N) MemoryOpsBegin = N,
  681. #define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N,
  682. #define LAST_MEMORY_INST(N) MemoryOpsEnd = N+1
  683. #include "llvm/IR/Instruction.def"
  684. };
  685. enum CastOps {
  686. #define FIRST_CAST_INST(N) CastOpsBegin = N,
  687. #define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N,
  688. #define LAST_CAST_INST(N) CastOpsEnd = N+1
  689. #include "llvm/IR/Instruction.def"
  690. };
  691. enum FuncletPadOps {
  692. #define FIRST_FUNCLETPAD_INST(N) FuncletPadOpsBegin = N,
  693. #define HANDLE_FUNCLETPAD_INST(N, OPC, CLASS) OPC = N,
  694. #define LAST_FUNCLETPAD_INST(N) FuncletPadOpsEnd = N+1
  695. #include "llvm/IR/Instruction.def"
  696. };
  697. enum OtherOps {
  698. #define FIRST_OTHER_INST(N) OtherOpsBegin = N,
  699. #define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N,
  700. #define LAST_OTHER_INST(N) OtherOpsEnd = N+1
  701. #include "llvm/IR/Instruction.def"
  702. };
  703. private:
  704. friend class SymbolTableListTraits<Instruction>;
  705. friend class BasicBlock; // For renumbering.
  706. // Shadow Value::setValueSubclassData with a private forwarding method so that
  707. // subclasses cannot accidentally use it.
  708. void setValueSubclassData(unsigned short D) {
  709. Value::setValueSubclassData(D);
  710. }
  711. unsigned short getSubclassDataFromValue() const {
  712. return Value::getSubclassDataFromValue();
  713. }
  714. void setParent(BasicBlock *P);
  715. protected:
  716. // Instruction subclasses can stick up to 15 bits of stuff into the
  717. // SubclassData field of instruction with these members.
  718. template <typename BitfieldElement>
  719. typename BitfieldElement::Type getSubclassData() const {
  720. static_assert(
  721. std::is_same<BitfieldElement, HasMetadataField>::value ||
  722. !Bitfield::isOverlapping<BitfieldElement, HasMetadataField>(),
  723. "Must not overlap with the metadata bit");
  724. return Bitfield::get<BitfieldElement>(getSubclassDataFromValue());
  725. }
  726. template <typename BitfieldElement>
  727. void setSubclassData(typename BitfieldElement::Type Value) {
  728. static_assert(
  729. std::is_same<BitfieldElement, HasMetadataField>::value ||
  730. !Bitfield::isOverlapping<BitfieldElement, HasMetadataField>(),
  731. "Must not overlap with the metadata bit");
  732. auto Storage = getSubclassDataFromValue();
  733. Bitfield::set<BitfieldElement>(Storage, Value);
  734. setValueSubclassData(Storage);
  735. }
  736. Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
  737. Instruction *InsertBefore = nullptr);
  738. Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
  739. BasicBlock *InsertAtEnd);
  740. private:
  741. /// Create a copy of this instruction.
  742. Instruction *cloneImpl() const;
  743. };
  744. inline void ilist_alloc_traits<Instruction>::deleteNode(Instruction *V) {
  745. V->deleteValue();
  746. }
  747. } // end namespace llvm
  748. #endif // LLVM_IR_INSTRUCTION_H
  749. #ifdef __GNUC__
  750. #pragma GCC diagnostic pop
  751. #endif