Instruction.h 33 KB

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