1 //===-- llvm/Instruction.h - Instruction class definition -------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the declaration of the Instruction class, which is the
11 // base class for all of the LLVM instructions.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_IR_INSTRUCTION_H
16 #define LLVM_IR_INSTRUCTION_H
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/None.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/ilist_node.h"
22 #include "llvm/IR/DebugLoc.h"
23 #include "llvm/IR/SymbolTableListTraits.h"
24 #include "llvm/IR/User.h"
25 #include "llvm/IR/Value.h"
26 #include "llvm/Support/Casting.h"
40 template <> struct ilist_alloc_traits<Instruction> {
41 static inline void deleteNode(Instruction *V);
44 class Instruction : public User,
45 public ilist_node_with_parent<Instruction, BasicBlock> {
47 DebugLoc DbgLoc; // 'dbg' Metadata cache.
50 /// This is a bit stored in the SubClassData field which indicates whether
51 /// this instruction has metadata attached to it or not.
52 HasMetadataBit = 1 << 15
56 ~Instruction(); // Use deleteValue() to delete a generic Instruction.
59 Instruction(const Instruction &) = delete;
60 Instruction &operator=(const Instruction &) = delete;
62 /// Specialize the methods defined in Value, as we know that an instruction
63 /// can only be used by other instructions.
64 Instruction *user_back() { return cast<Instruction>(*user_begin());}
65 const Instruction *user_back() const { return cast<Instruction>(*user_begin());}
67 inline const BasicBlock *getParent() const { return Parent; }
68 inline BasicBlock *getParent() { return Parent; }
70 /// Return the module owning the function this instruction belongs to
71 /// or nullptr it the function does not have a module.
73 /// Note: this is undefined behavior if the instruction does not have a
74 /// parent, or the parent basic block does not have a parent function.
75 const Module *getModule() const;
77 return const_cast<Module *>(
78 static_cast<const Instruction *>(this)->getModule());
81 /// Return the function this instruction belongs to.
83 /// Note: it is undefined behavior to call this on an instruction not
84 /// currently inserted into a function.
85 const Function *getFunction() const;
86 Function *getFunction() {
87 return const_cast<Function *>(
88 static_cast<const Instruction *>(this)->getFunction());
91 /// This method unlinks 'this' from the containing basic block, but does not
93 void removeFromParent();
95 /// This method unlinks 'this' from the containing basic block and deletes it.
97 /// \returns an iterator pointing to the element after the erased one
98 SymbolTableList<Instruction>::iterator eraseFromParent();
100 /// Insert an unlinked instruction into a basic block immediately before
101 /// the specified instruction.
102 void insertBefore(Instruction *InsertPos);
104 /// Insert an unlinked instruction into a basic block immediately after the
105 /// specified instruction.
106 void insertAfter(Instruction *InsertPos);
108 /// Unlink this instruction from its current basic block and insert it into
109 /// the basic block that MovePos lives in, right before MovePos.
110 void moveBefore(Instruction *MovePos);
112 /// Unlink this instruction and insert into BB before I.
114 /// \pre I is a valid iterator into BB.
115 void moveBefore(BasicBlock &BB, SymbolTableList<Instruction>::iterator I);
117 /// Unlink this instruction from its current basic block and insert it into
118 /// the basic block that MovePos lives in, right after MovePos.
119 void moveAfter(Instruction *MovePos);
121 //===--------------------------------------------------------------------===//
122 // Subclass classification.
123 //===--------------------------------------------------------------------===//
125 /// Returns a member of one of the enums like Instruction::Add.
126 unsigned getOpcode() const { return getValueID() - InstructionVal; }
128 const char *getOpcodeName() const { return getOpcodeName(getOpcode()); }
129 bool isTerminator() const { return isTerminator(getOpcode()); }
130 bool isBinaryOp() const { return isBinaryOp(getOpcode()); }
131 bool isShift() { return isShift(getOpcode()); }
132 bool isCast() const { return isCast(getOpcode()); }
133 bool isFuncletPad() const { return isFuncletPad(getOpcode()); }
135 static const char* getOpcodeName(unsigned OpCode);
137 static inline bool isTerminator(unsigned OpCode) {
138 return OpCode >= TermOpsBegin && OpCode < TermOpsEnd;
141 static inline bool isBinaryOp(unsigned Opcode) {
142 return Opcode >= BinaryOpsBegin && Opcode < BinaryOpsEnd;
145 /// Determine if the Opcode is one of the shift instructions.
146 static inline bool isShift(unsigned Opcode) {
147 return Opcode >= Shl && Opcode <= AShr;
150 /// Return true if this is a logical shift left or a logical shift right.
151 inline bool isLogicalShift() const {
152 return getOpcode() == Shl || getOpcode() == LShr;
155 /// Return true if this is an arithmetic shift right.
156 inline bool isArithmeticShift() const {
157 return getOpcode() == AShr;
160 /// Determine if the Opcode is and/or/xor.
161 static inline bool isBitwiseLogicOp(unsigned Opcode) {
162 return Opcode == And || Opcode == Or || Opcode == Xor;
165 /// Return true if this is and/or/xor.
166 inline bool isBitwiseLogicOp() const {
167 return isBitwiseLogicOp(getOpcode());
170 /// Determine if the OpCode is one of the CastInst instructions.
171 static inline bool isCast(unsigned OpCode) {
172 return OpCode >= CastOpsBegin && OpCode < CastOpsEnd;
175 /// Determine if the OpCode is one of the FuncletPadInst instructions.
176 static inline bool isFuncletPad(unsigned OpCode) {
177 return OpCode >= FuncletPadOpsBegin && OpCode < FuncletPadOpsEnd;
180 //===--------------------------------------------------------------------===//
181 // Metadata manipulation.
182 //===--------------------------------------------------------------------===//
184 /// Return true if this instruction has any metadata attached to it.
185 bool hasMetadata() const { return DbgLoc || hasMetadataHashEntry(); }
187 /// Return true if this instruction has metadata attached to it other than a
189 bool hasMetadataOtherThanDebugLoc() const {
190 return hasMetadataHashEntry();
193 /// Get the metadata of given kind attached to this Instruction.
194 /// If the metadata is not found then return null.
195 MDNode *getMetadata(unsigned KindID) const {
196 if (!hasMetadata()) return nullptr;
197 return getMetadataImpl(KindID);
200 /// Get the metadata of given kind attached to this Instruction.
201 /// If the metadata is not found then return null.
202 MDNode *getMetadata(StringRef Kind) const {
203 if (!hasMetadata()) return nullptr;
204 return getMetadataImpl(Kind);
207 /// Get all metadata attached to this Instruction. The first element of each
208 /// pair returned is the KindID, the second element is the metadata value.
209 /// This list is returned sorted by the KindID.
211 getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
213 getAllMetadataImpl(MDs);
216 /// This does the same thing as getAllMetadata, except that it filters out the
218 void getAllMetadataOtherThanDebugLoc(
219 SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
220 if (hasMetadataOtherThanDebugLoc())
221 getAllMetadataOtherThanDebugLocImpl(MDs);
224 /// Fills the AAMDNodes structure with AA metadata from this instruction.
225 /// When Merge is true, the existing AA metadata is merged with that from this
226 /// instruction providing the most-general result.
227 void getAAMetadata(AAMDNodes &N, bool Merge = false) const;
229 /// Set the metadata of the specified kind to the specified node. This updates
230 /// or replaces metadata if already present, or removes it if Node is null.
231 void setMetadata(unsigned KindID, MDNode *Node);
232 void setMetadata(StringRef Kind, MDNode *Node);
234 /// Copy metadata from \p SrcInst to this instruction. \p WL, if not empty,
235 /// specifies the list of meta data that needs to be copied. If \p WL is
236 /// empty, all meta data will be copied.
237 void copyMetadata(const Instruction &SrcInst,
238 ArrayRef<unsigned> WL = ArrayRef<unsigned>());
240 /// If the instruction has "branch_weights" MD_prof metadata and the MDNode
241 /// has three operands (including name string), swap the order of the
243 void swapProfMetadata();
245 /// Drop all unknown metadata except for debug locations.
247 /// Passes are required to drop metadata they don't understand. This is a
248 /// convenience method for passes to do so.
249 void dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs);
250 void dropUnknownNonDebugMetadata() {
251 return dropUnknownNonDebugMetadata(None);
253 void dropUnknownNonDebugMetadata(unsigned ID1) {
254 return dropUnknownNonDebugMetadata(makeArrayRef(ID1));
256 void dropUnknownNonDebugMetadata(unsigned ID1, unsigned ID2) {
257 unsigned IDs[] = {ID1, ID2};
258 return dropUnknownNonDebugMetadata(IDs);
262 /// Sets the metadata on this instruction from the AAMDNodes structure.
263 void setAAMetadata(const AAMDNodes &N);
265 /// Retrieve the raw weight values of a conditional branch or select.
266 /// Returns true on success with profile weights filled in.
267 /// Returns false if no metadata or invalid metadata was found.
268 bool extractProfMetadata(uint64_t &TrueVal, uint64_t &FalseVal) const;
270 /// Retrieve total raw weight values of a branch.
271 /// Returns true on success with profile total weights filled in.
272 /// Returns false if no metadata was found.
273 bool extractProfTotalWeight(uint64_t &TotalVal) const;
275 /// Updates branch_weights metadata by scaling it by \p S / \p T.
276 void updateProfWeight(uint64_t S, uint64_t T);
278 /// Sets the branch_weights metadata to \p W for CallInst.
279 void setProfWeight(uint64_t W);
281 /// Set the debug location information for this instruction.
282 void setDebugLoc(DebugLoc Loc) { DbgLoc = std::move(Loc); }
284 /// Return the debug location for this node as a DebugLoc.
285 const DebugLoc &getDebugLoc() const { return DbgLoc; }
287 /// Set or clear the nsw flag on this instruction, which must be an operator
288 /// which supports this flag. See LangRef.html for the meaning of this flag.
289 void setHasNoUnsignedWrap(bool b = true);
291 /// Set or clear the nsw flag on this instruction, which must be an operator
292 /// which supports this flag. See LangRef.html for the meaning of this flag.
293 void setHasNoSignedWrap(bool b = true);
295 /// Set or clear the exact flag on this instruction, which must be an operator
296 /// which supports this flag. See LangRef.html for the meaning of this flag.
297 void setIsExact(bool b = true);
299 /// Determine whether the no unsigned wrap flag is set.
300 bool hasNoUnsignedWrap() const;
302 /// Determine whether the no signed wrap flag is set.
303 bool hasNoSignedWrap() const;
305 /// Drops flags that may cause this instruction to evaluate to poison despite
306 /// having non-poison inputs.
307 void dropPoisonGeneratingFlags();
309 /// Determine whether the exact flag is set.
310 bool isExact() const;
312 /// Set or clear all fast-math-flags on this instruction, which must be an
313 /// operator which supports this flag. See LangRef.html for the meaning of
315 void setFast(bool B);
317 /// Set or clear the reassociation flag on this instruction, which must be
318 /// an operator which supports this flag. See LangRef.html for the meaning of
320 void setHasAllowReassoc(bool B);
322 /// Set or clear the no-nans flag on this instruction, which must be an
323 /// operator which supports this flag. See LangRef.html for the meaning of
325 void setHasNoNaNs(bool B);
327 /// Set or clear the no-infs flag on this instruction, which must be an
328 /// operator which supports this flag. See LangRef.html for the meaning of
330 void setHasNoInfs(bool B);
332 /// Set or clear the no-signed-zeros flag on this instruction, which must be
333 /// an operator which supports this flag. See LangRef.html for the meaning of
335 void setHasNoSignedZeros(bool B);
337 /// Set or clear the allow-reciprocal flag on this instruction, which must be
338 /// an operator which supports this flag. See LangRef.html for the meaning of
340 void setHasAllowReciprocal(bool B);
342 /// Set or clear the approximate-math-functions flag on this instruction,
343 /// which must be an operator which supports this flag. See LangRef.html for
344 /// the meaning of this flag.
345 void setHasApproxFunc(bool B);
347 /// Convenience function for setting multiple fast-math flags on this
348 /// instruction, which must be an operator which supports these flags. See
349 /// LangRef.html for the meaning of these flags.
350 void setFastMathFlags(FastMathFlags FMF);
352 /// Convenience function for transferring all fast-math flag values to this
353 /// instruction, which must be an operator which supports these flags. See
354 /// LangRef.html for the meaning of these flags.
355 void copyFastMathFlags(FastMathFlags FMF);
357 /// Determine whether all fast-math-flags are set.
360 /// Determine whether the allow-reassociation flag is set.
361 bool hasAllowReassoc() const;
363 /// Determine whether the no-NaNs flag is set.
364 bool hasNoNaNs() const;
366 /// Determine whether the no-infs flag is set.
367 bool hasNoInfs() const;
369 /// Determine whether the no-signed-zeros flag is set.
370 bool hasNoSignedZeros() const;
372 /// Determine whether the allow-reciprocal flag is set.
373 bool hasAllowReciprocal() const;
375 /// Determine whether the allow-contract flag is set.
376 bool hasAllowContract() const;
378 /// Determine whether the approximate-math-functions flag is set.
379 bool hasApproxFunc() const;
381 /// Convenience function for getting all the fast-math flags, which must be an
382 /// operator which supports these flags. See LangRef.html for the meaning of
384 FastMathFlags getFastMathFlags() const;
386 /// Copy I's fast-math flags
387 void copyFastMathFlags(const Instruction *I);
389 /// Convenience method to copy supported exact, fast-math, and (optionally)
390 /// wrapping flags from V to this instruction.
391 void copyIRFlags(const Value *V, bool IncludeWrapFlags = true);
393 /// Logical 'and' of any supported wrapping, exact, and fast-math flags of
394 /// V and this instruction.
395 void andIRFlags(const Value *V);
397 /// Merge 2 debug locations and apply it to the Instruction. If the
398 /// instruction is a CallIns, we need to traverse the inline chain to find
399 /// the common scope. This is not efficient for N-way merging as each time
400 /// you merge 2 iterations, you need to rebuild the hashmap to find the
401 /// common scope. However, we still choose this API because:
402 /// 1) Simplicity: it takes 2 locations instead of a list of locations.
403 /// 2) In worst case, it increases the complexity from O(N*I) to
404 /// O(2*N*I), where N is # of Instructions to merge, and I is the
405 /// maximum level of inline stack. So it is still linear.
406 /// 3) Merging of call instructions should be extremely rare in real
407 /// applications, thus the N-way merging should be in code path.
408 /// The DebugLoc attached to this instruction will be overwritten by the
410 void applyMergedLocation(const DILocation *LocA, const DILocation *LocB);
413 /// Return true if we have an entry in the on-the-side metadata hash.
414 bool hasMetadataHashEntry() const {
415 return (getSubclassDataFromValue() & HasMetadataBit) != 0;
418 // These are all implemented in Metadata.cpp.
419 MDNode *getMetadataImpl(unsigned KindID) const;
420 MDNode *getMetadataImpl(StringRef Kind) const;
422 getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
423 void getAllMetadataOtherThanDebugLocImpl(
424 SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
425 /// Clear all hashtable-based metadata from this instruction.
426 void clearMetadataHashEntries();
429 //===--------------------------------------------------------------------===//
430 // Predicates and helper methods.
431 //===--------------------------------------------------------------------===//
433 /// Return true if the instruction is associative:
435 /// Associative operators satisfy: x op (y op z) === (x op y) op z
437 /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
439 bool isAssociative() const LLVM_READONLY;
440 static bool isAssociative(unsigned Opcode) {
441 return Opcode == And || Opcode == Or || Opcode == Xor ||
442 Opcode == Add || Opcode == Mul;
445 /// Return true if the instruction is commutative:
447 /// Commutative operators satisfy: (x op y) === (y op x)
449 /// In LLVM, these are the commutative operators, plus SetEQ and SetNE, when
450 /// applied to any type.
452 bool isCommutative() const { return isCommutative(getOpcode()); }
453 static bool isCommutative(unsigned Opcode) {
457 case And: case Or: case Xor:
464 /// Return true if the instruction is idempotent:
466 /// Idempotent operators satisfy: x op x === x
468 /// In LLVM, the And and Or operators are idempotent.
470 bool isIdempotent() const { return isIdempotent(getOpcode()); }
471 static bool isIdempotent(unsigned Opcode) {
472 return Opcode == And || Opcode == Or;
475 /// Return true if the instruction is nilpotent:
477 /// Nilpotent operators satisfy: x op x === Id,
479 /// where Id is the identity for the operator, i.e. a constant such that
480 /// x op Id === x and Id op x === x for all x.
482 /// In LLVM, the Xor operator is nilpotent.
484 bool isNilpotent() const { return isNilpotent(getOpcode()); }
485 static bool isNilpotent(unsigned Opcode) {
486 return Opcode == Xor;
489 /// Return true if this instruction may modify memory.
490 bool mayWriteToMemory() const;
492 /// Return true if this instruction may read memory.
493 bool mayReadFromMemory() const;
495 /// Return true if this instruction may read or write memory.
496 bool mayReadOrWriteMemory() const {
497 return mayReadFromMemory() || mayWriteToMemory();
500 /// Return true if this instruction has an AtomicOrdering of unordered or
502 bool isAtomic() const;
504 /// Return true if this atomic instruction loads from memory.
505 bool hasAtomicLoad() const;
507 /// Return true if this atomic instruction stores to memory.
508 bool hasAtomicStore() const;
510 /// Return true if this instruction may throw an exception.
511 bool mayThrow() const;
513 /// Return true if this instruction behaves like a memory fence: it can load
514 /// or store to memory location without being given a memory location.
515 bool isFenceLike() const {
516 switch (getOpcode()) {
519 // This list should be kept in sync with the list in mayWriteToMemory for
520 // all opcodes which don't have a memory location.
521 case Instruction::Fence:
522 case Instruction::CatchPad:
523 case Instruction::CatchRet:
524 case Instruction::Call:
525 case Instruction::Invoke:
530 /// Return true if the instruction may have side effects.
532 /// Note that this does not consider malloc and alloca to have side
533 /// effects because the newly allocated memory is completely invisible to
534 /// instructions which don't use the returned value. For cases where this
535 /// matters, isSafeToSpeculativelyExecute may be more appropriate.
536 bool mayHaveSideEffects() const { return mayWriteToMemory() || mayThrow(); }
538 /// Return true if the instruction is a variety of EH-block.
539 bool isEHPad() const {
540 switch (getOpcode()) {
541 case Instruction::CatchSwitch:
542 case Instruction::CatchPad:
543 case Instruction::CleanupPad:
544 case Instruction::LandingPad:
551 /// Create a copy of 'this' instruction that is identical in all ways except
553 /// * The instruction has no parent
554 /// * The instruction has no name
556 Instruction *clone() const;
558 /// Return true if the specified instruction is exactly identical to the
559 /// current one. This means that all operands match and any extra information
560 /// (e.g. load is volatile) agree.
561 bool isIdenticalTo(const Instruction *I) const;
563 /// This is like isIdenticalTo, except that it ignores the
564 /// SubclassOptionalData flags, which may specify conditions under which the
565 /// instruction's result is undefined.
566 bool isIdenticalToWhenDefined(const Instruction *I) const;
568 /// When checking for operation equivalence (using isSameOperationAs) it is
569 /// sometimes useful to ignore certain attributes.
570 enum OperationEquivalenceFlags {
571 /// Check for equivalence ignoring load/store alignment.
572 CompareIgnoringAlignment = 1<<0,
573 /// Check for equivalence treating a type and a vector of that type
575 CompareUsingScalarTypes = 1<<1
578 /// This function determines if the specified instruction executes the same
579 /// operation as the current one. This means that the opcodes, type, operand
580 /// types and any other factors affecting the operation must be the same. This
581 /// is similar to isIdenticalTo except the operands themselves don't have to
583 /// @returns true if the specified instruction is the same operation as
585 /// @brief Determine if one instruction is the same operation as another.
586 bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const;
588 /// Return true if there are any uses of this instruction in blocks other than
589 /// the specified block. Note that PHI nodes are considered to evaluate their
590 /// operands in the corresponding predecessor block.
591 bool isUsedOutsideOfBlock(const BasicBlock *BB) const;
594 /// Methods for support type inquiry through isa, cast, and dyn_cast:
595 static bool classof(const Value *V) {
596 return V->getValueID() >= Value::InstructionVal;
599 //----------------------------------------------------------------------
600 // Exported enumerations.
602 enum TermOps { // These terminate basic blocks
603 #define FIRST_TERM_INST(N) TermOpsBegin = N,
604 #define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N,
605 #define LAST_TERM_INST(N) TermOpsEnd = N+1
606 #include "llvm/IR/Instruction.def"
610 #define FIRST_BINARY_INST(N) BinaryOpsBegin = N,
611 #define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N,
612 #define LAST_BINARY_INST(N) BinaryOpsEnd = N+1
613 #include "llvm/IR/Instruction.def"
617 #define FIRST_MEMORY_INST(N) MemoryOpsBegin = N,
618 #define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N,
619 #define LAST_MEMORY_INST(N) MemoryOpsEnd = N+1
620 #include "llvm/IR/Instruction.def"
624 #define FIRST_CAST_INST(N) CastOpsBegin = N,
625 #define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N,
626 #define LAST_CAST_INST(N) CastOpsEnd = N+1
627 #include "llvm/IR/Instruction.def"
631 #define FIRST_FUNCLETPAD_INST(N) FuncletPadOpsBegin = N,
632 #define HANDLE_FUNCLETPAD_INST(N, OPC, CLASS) OPC = N,
633 #define LAST_FUNCLETPAD_INST(N) FuncletPadOpsEnd = N+1
634 #include "llvm/IR/Instruction.def"
638 #define FIRST_OTHER_INST(N) OtherOpsBegin = N,
639 #define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N,
640 #define LAST_OTHER_INST(N) OtherOpsEnd = N+1
641 #include "llvm/IR/Instruction.def"
645 friend class SymbolTableListTraits<Instruction>;
647 // Shadow Value::setValueSubclassData with a private forwarding method so that
648 // subclasses cannot accidentally use it.
649 void setValueSubclassData(unsigned short D) {
650 Value::setValueSubclassData(D);
653 unsigned short getSubclassDataFromValue() const {
654 return Value::getSubclassDataFromValue();
657 void setHasMetadataHashEntry(bool V) {
658 setValueSubclassData((getSubclassDataFromValue() & ~HasMetadataBit) |
659 (V ? HasMetadataBit : 0));
662 void setParent(BasicBlock *P);
665 // Instruction subclasses can stick up to 15 bits of stuff into the
666 // SubclassData field of instruction with these members.
668 // Verify that only the low 15 bits are used.
669 void setInstructionSubclassData(unsigned short D) {
670 assert((D & HasMetadataBit) == 0 && "Out of range value put into field");
671 setValueSubclassData((getSubclassDataFromValue() & HasMetadataBit) | D);
674 unsigned getSubclassDataFromInstruction() const {
675 return getSubclassDataFromValue() & ~HasMetadataBit;
678 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
679 Instruction *InsertBefore = nullptr);
680 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
681 BasicBlock *InsertAtEnd);
684 /// Create a copy of this instruction.
685 Instruction *cloneImpl() const;
688 inline void ilist_alloc_traits<Instruction>::deleteNode(Instruction *V) {
692 } // end namespace llvm
694 #endif // LLVM_IR_INSTRUCTION_H