Subversion Repositories QNX 8.QNX8 LLVM/Clang compiler suite

Rev

Blame | Last modification | View Log | Download | RSS feed

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