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