Instruction.h 32 KB

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