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"
39 template <> struct ilist_alloc_traits<Instruction> {
40 static inline void deleteNode(Instruction *V);
43 class Instruction : public User,
44 public ilist_node_with_parent<Instruction, BasicBlock> {
46 DebugLoc DbgLoc; // 'dbg' Metadata cache.
49 /// This is a bit stored in the SubClassData field which indicates whether
50 /// this instruction has metadata attached to it or not.
51 HasMetadataBit = 1 << 15
55 ~Instruction(); // Use deleteValue() to delete a generic Instruction.
58 Instruction(const Instruction &) = delete;
59 Instruction &operator=(const Instruction &) = delete;
61 /// Specialize the methods defined in Value, as we know that an instruction
62 /// can only be used by other instructions.
63 Instruction *user_back() { return cast<Instruction>(*user_begin());}
64 const Instruction *user_back() const { return cast<Instruction>(*user_begin());}
66 inline const BasicBlock *getParent() const { return Parent; }
67 inline BasicBlock *getParent() { return Parent; }
69 /// Return the module owning the function this instruction belongs to
70 /// or nullptr it the function does not have a module.
72 /// Note: this is undefined behavior if the instruction does not have a
73 /// parent, or the parent basic block does not have a parent function.
74 const Module *getModule() const;
76 return const_cast<Module *>(
77 static_cast<const Instruction *>(this)->getModule());
80 /// Return the function this instruction belongs to.
82 /// Note: it is undefined behavior to call this on an instruction not
83 /// currently inserted into a function.
84 const Function *getFunction() const;
85 Function *getFunction() {
86 return const_cast<Function *>(
87 static_cast<const Instruction *>(this)->getFunction());
90 /// This method unlinks 'this' from the containing basic block, but does not
92 void removeFromParent();
94 /// This method unlinks 'this' from the containing basic block and deletes it.
96 /// \returns an iterator pointing to the element after the erased one
97 SymbolTableList<Instruction>::iterator eraseFromParent();
99 /// Insert an unlinked instruction into a basic block immediately before
100 /// the specified instruction.
101 void insertBefore(Instruction *InsertPos);
103 /// Insert an unlinked instruction into a basic block immediately after the
104 /// specified instruction.
105 void insertAfter(Instruction *InsertPos);
107 /// Unlink this instruction from its current basic block and insert it into
108 /// the basic block that MovePos lives in, right before MovePos.
109 void moveBefore(Instruction *MovePos);
111 /// Unlink this instruction and insert into BB before I.
113 /// \pre I is a valid iterator into BB.
114 void moveBefore(BasicBlock &BB, SymbolTableList<Instruction>::iterator I);
116 //===--------------------------------------------------------------------===//
117 // Subclass classification.
118 //===--------------------------------------------------------------------===//
120 /// Returns a member of one of the enums like Instruction::Add.
121 unsigned getOpcode() const { return getValueID() - InstructionVal; }
123 const char *getOpcodeName() const { return getOpcodeName(getOpcode()); }
124 bool isTerminator() const { return isTerminator(getOpcode()); }
125 bool isBinaryOp() const { return isBinaryOp(getOpcode()); }
126 bool isShift() { return isShift(getOpcode()); }
127 bool isCast() const { return isCast(getOpcode()); }
128 bool isFuncletPad() const { return isFuncletPad(getOpcode()); }
130 static const char* getOpcodeName(unsigned OpCode);
132 static inline bool isTerminator(unsigned OpCode) {
133 return OpCode >= TermOpsBegin && OpCode < TermOpsEnd;
136 static inline bool isBinaryOp(unsigned Opcode) {
137 return Opcode >= BinaryOpsBegin && Opcode < BinaryOpsEnd;
140 /// Determine if the Opcode is one of the shift instructions.
141 static inline bool isShift(unsigned Opcode) {
142 return Opcode >= Shl && Opcode <= AShr;
145 /// Return true if this is a logical shift left or a logical shift right.
146 inline bool isLogicalShift() const {
147 return getOpcode() == Shl || getOpcode() == LShr;
150 /// Return true if this is an arithmetic shift right.
151 inline bool isArithmeticShift() const {
152 return getOpcode() == AShr;
155 /// Determine if the Opcode is and/or/xor.
156 static inline bool isBitwiseLogicOp(unsigned Opcode) {
157 return Opcode == And || Opcode == Or || Opcode == Xor;
160 /// Return true if this is and/or/xor.
161 inline bool isBitwiseLogicOp() const {
162 return isBitwiseLogicOp(getOpcode());
165 /// Determine if the OpCode is one of the CastInst instructions.
166 static inline bool isCast(unsigned OpCode) {
167 return OpCode >= CastOpsBegin && OpCode < CastOpsEnd;
170 /// Determine if the OpCode is one of the FuncletPadInst instructions.
171 static inline bool isFuncletPad(unsigned OpCode) {
172 return OpCode >= FuncletPadOpsBegin && OpCode < FuncletPadOpsEnd;
175 //===--------------------------------------------------------------------===//
176 // Metadata manipulation.
177 //===--------------------------------------------------------------------===//
179 /// Return true if this instruction has any metadata attached to it.
180 bool hasMetadata() const { return DbgLoc || hasMetadataHashEntry(); }
182 /// Return true if this instruction has metadata attached to it other than a
184 bool hasMetadataOtherThanDebugLoc() const {
185 return hasMetadataHashEntry();
188 /// Get the metadata of given kind attached to this Instruction.
189 /// If the metadata is not found then return null.
190 MDNode *getMetadata(unsigned KindID) const {
191 if (!hasMetadata()) return nullptr;
192 return getMetadataImpl(KindID);
195 /// Get the metadata of given kind attached to this Instruction.
196 /// If the metadata is not found then return null.
197 MDNode *getMetadata(StringRef Kind) const {
198 if (!hasMetadata()) return nullptr;
199 return getMetadataImpl(Kind);
202 /// Get all metadata attached to this Instruction. The first element of each
203 /// pair returned is the KindID, the second element is the metadata value.
204 /// This list is returned sorted by the KindID.
206 getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
208 getAllMetadataImpl(MDs);
211 /// This does the same thing as getAllMetadata, except that it filters out the
213 void getAllMetadataOtherThanDebugLoc(
214 SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
215 if (hasMetadataOtherThanDebugLoc())
216 getAllMetadataOtherThanDebugLocImpl(MDs);
219 /// Fills the AAMDNodes structure with AA metadata from this instruction.
220 /// When Merge is true, the existing AA metadata is merged with that from this
221 /// instruction providing the most-general result.
222 void getAAMetadata(AAMDNodes &N, bool Merge = false) const;
224 /// Set the metadata of the specified kind to the specified node. This updates
225 /// or replaces metadata if already present, or removes it if Node is null.
226 void setMetadata(unsigned KindID, MDNode *Node);
227 void setMetadata(StringRef Kind, MDNode *Node);
229 /// Copy metadata from \p SrcInst to this instruction. \p WL, if not empty,
230 /// specifies the list of meta data that needs to be copied. If \p WL is
231 /// empty, all meta data will be copied.
232 void copyMetadata(const Instruction &SrcInst,
233 ArrayRef<unsigned> WL = ArrayRef<unsigned>());
235 /// If the instruction has "branch_weights" MD_prof metadata and the MDNode
236 /// has three operands (including name string), swap the order of the
238 void swapProfMetadata();
240 /// Drop all unknown metadata except for debug locations.
242 /// Passes are required to drop metadata they don't understand. This is a
243 /// convenience method for passes to do so.
244 void dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs);
245 void dropUnknownNonDebugMetadata() {
246 return dropUnknownNonDebugMetadata(None);
248 void dropUnknownNonDebugMetadata(unsigned ID1) {
249 return dropUnknownNonDebugMetadata(makeArrayRef(ID1));
251 void dropUnknownNonDebugMetadata(unsigned ID1, unsigned ID2) {
252 unsigned IDs[] = {ID1, ID2};
253 return dropUnknownNonDebugMetadata(IDs);
257 /// Sets the metadata on this instruction from the AAMDNodes structure.
258 void setAAMetadata(const AAMDNodes &N);
260 /// Retrieve the raw weight values of a conditional branch or select.
261 /// Returns true on success with profile weights filled in.
262 /// Returns false if no metadata or invalid metadata was found.
263 bool extractProfMetadata(uint64_t &TrueVal, uint64_t &FalseVal) const;
265 /// Retrieve total raw weight values of a branch.
266 /// Returns true on success with profile total weights filled in.
267 /// Returns false if no metadata was found.
268 bool extractProfTotalWeight(uint64_t &TotalVal) const;
270 /// Updates branch_weights metadata by scaling it by \p S / \p T.
271 void updateProfWeight(uint64_t S, uint64_t T);
273 /// Sets the branch_weights metadata to \p W for CallInst.
274 void setProfWeight(uint64_t W);
276 /// Set the debug location information for this instruction.
277 void setDebugLoc(DebugLoc Loc) { DbgLoc = std::move(Loc); }
279 /// Return the debug location for this node as a DebugLoc.
280 const DebugLoc &getDebugLoc() const { return DbgLoc; }
282 /// Set or clear the nsw flag on this instruction, which must be an operator
283 /// which supports this flag. See LangRef.html for the meaning of this flag.
284 void setHasNoUnsignedWrap(bool b = true);
286 /// Set or clear the nsw flag on this instruction, which must be an operator
287 /// which supports this flag. See LangRef.html for the meaning of this flag.
288 void setHasNoSignedWrap(bool b = true);
290 /// Set or clear the exact flag on this instruction, which must be an operator
291 /// which supports this flag. See LangRef.html for the meaning of this flag.
292 void setIsExact(bool b = true);
294 /// Determine whether the no unsigned wrap flag is set.
295 bool hasNoUnsignedWrap() const;
297 /// Determine whether the no signed wrap flag is set.
298 bool hasNoSignedWrap() const;
300 /// Drops flags that may cause this instruction to evaluate to poison despite
301 /// having non-poison inputs.
302 void dropPoisonGeneratingFlags();
304 /// Determine whether the exact flag is set.
305 bool isExact() const;
307 /// Set or clear the unsafe-algebra flag on this instruction, which must be an
308 /// operator which supports this flag. See LangRef.html for the meaning of
310 void setHasUnsafeAlgebra(bool B);
312 /// Set or clear the no-nans flag on this instruction, which must be an
313 /// operator which supports this flag. See LangRef.html for the meaning of
315 void setHasNoNaNs(bool B);
317 /// Set or clear the no-infs flag on this instruction, which must be an
318 /// operator which supports this flag. See LangRef.html for the meaning of
320 void setHasNoInfs(bool B);
322 /// Set or clear the no-signed-zeros flag on this instruction, which must be
323 /// an operator which supports this flag. See LangRef.html for the meaning of
325 void setHasNoSignedZeros(bool B);
327 /// Set or clear the allow-reciprocal flag on this instruction, which must be
328 /// an operator which supports this flag. See LangRef.html for the meaning of
330 void setHasAllowReciprocal(bool B);
332 /// Convenience function for setting multiple fast-math flags on this
333 /// instruction, which must be an operator which supports these flags. See
334 /// LangRef.html for the meaning of these flags.
335 void setFastMathFlags(FastMathFlags FMF);
337 /// Convenience function for transferring all fast-math flag values to this
338 /// instruction, which must be an operator which supports these flags. See
339 /// LangRef.html for the meaning of these flags.
340 void copyFastMathFlags(FastMathFlags FMF);
342 /// Determine whether the unsafe-algebra flag is set.
343 bool hasUnsafeAlgebra() const;
345 /// Determine whether the no-NaNs flag is set.
346 bool hasNoNaNs() const;
348 /// Determine whether the no-infs flag is set.
349 bool hasNoInfs() const;
351 /// Determine whether the no-signed-zeros flag is set.
352 bool hasNoSignedZeros() const;
354 /// Determine whether the allow-reciprocal flag is set.
355 bool hasAllowReciprocal() const;
357 /// Determine whether the allow-contract flag is set.
358 bool hasAllowContract() const;
360 /// Convenience function for getting all the fast-math flags, which must be an
361 /// operator which supports these flags. See LangRef.html for the meaning of
363 FastMathFlags getFastMathFlags() const;
365 /// Copy I's fast-math flags
366 void copyFastMathFlags(const Instruction *I);
368 /// Convenience method to copy supported exact, fast-math, and (optionally)
369 /// wrapping flags from V to this instruction.
370 void copyIRFlags(const Value *V, bool IncludeWrapFlags = true);
372 /// Logical 'and' of any supported wrapping, exact, and fast-math flags of
373 /// V and this instruction.
374 void andIRFlags(const Value *V);
377 /// Return true if we have an entry in the on-the-side metadata hash.
378 bool hasMetadataHashEntry() const {
379 return (getSubclassDataFromValue() & HasMetadataBit) != 0;
382 // These are all implemented in Metadata.cpp.
383 MDNode *getMetadataImpl(unsigned KindID) const;
384 MDNode *getMetadataImpl(StringRef Kind) const;
386 getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
387 void getAllMetadataOtherThanDebugLocImpl(
388 SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
389 /// Clear all hashtable-based metadata from this instruction.
390 void clearMetadataHashEntries();
393 //===--------------------------------------------------------------------===//
394 // Predicates and helper methods.
395 //===--------------------------------------------------------------------===//
397 /// Return true if the instruction is associative:
399 /// Associative operators satisfy: x op (y op z) === (x op y) op z
401 /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
403 bool isAssociative() const LLVM_READONLY;
404 static bool isAssociative(unsigned Opcode) {
405 return Opcode == And || Opcode == Or || Opcode == Xor ||
406 Opcode == Add || Opcode == Mul;
409 /// Return true if the instruction is commutative:
411 /// Commutative operators satisfy: (x op y) === (y op x)
413 /// In LLVM, these are the commutative operators, plus SetEQ and SetNE, when
414 /// applied to any type.
416 bool isCommutative() const { return isCommutative(getOpcode()); }
417 static bool isCommutative(unsigned Opcode) {
421 case And: case Or: case Xor:
428 /// Return true if the instruction is idempotent:
430 /// Idempotent operators satisfy: x op x === x
432 /// In LLVM, the And and Or operators are idempotent.
434 bool isIdempotent() const { return isIdempotent(getOpcode()); }
435 static bool isIdempotent(unsigned Opcode) {
436 return Opcode == And || Opcode == Or;
439 /// Return true if the instruction is nilpotent:
441 /// Nilpotent operators satisfy: x op x === Id,
443 /// where Id is the identity for the operator, i.e. a constant such that
444 /// x op Id === x and Id op x === x for all x.
446 /// In LLVM, the Xor operator is nilpotent.
448 bool isNilpotent() const { return isNilpotent(getOpcode()); }
449 static bool isNilpotent(unsigned Opcode) {
450 return Opcode == Xor;
453 /// Return true if this instruction may modify memory.
454 bool mayWriteToMemory() const;
456 /// Return true if this instruction may read memory.
457 bool mayReadFromMemory() const;
459 /// Return true if this instruction may read or write memory.
460 bool mayReadOrWriteMemory() const {
461 return mayReadFromMemory() || mayWriteToMemory();
464 /// Return true if this instruction has an AtomicOrdering of unordered or
466 bool isAtomic() const;
468 /// Return true if this atomic instruction loads from memory.
469 bool hasAtomicLoad() const;
471 /// Return true if this atomic instruction stores to memory.
472 bool hasAtomicStore() const;
474 /// Return true if this instruction may throw an exception.
475 bool mayThrow() const;
477 /// Return true if this instruction behaves like a memory fence: it can load
478 /// or store to memory location without being given a memory location.
479 bool isFenceLike() const {
480 switch (getOpcode()) {
483 // This list should be kept in sync with the list in mayWriteToMemory for
484 // all opcodes which don't have a memory location.
485 case Instruction::Fence:
486 case Instruction::CatchPad:
487 case Instruction::CatchRet:
488 case Instruction::Call:
489 case Instruction::Invoke:
494 /// Return true if the instruction may have side effects.
496 /// Note that this does not consider malloc and alloca to have side
497 /// effects because the newly allocated memory is completely invisible to
498 /// instructions which don't use the returned value. For cases where this
499 /// matters, isSafeToSpeculativelyExecute may be more appropriate.
500 bool mayHaveSideEffects() const { return mayWriteToMemory() || mayThrow(); }
502 /// Return true if the instruction is a variety of EH-block.
503 bool isEHPad() const {
504 switch (getOpcode()) {
505 case Instruction::CatchSwitch:
506 case Instruction::CatchPad:
507 case Instruction::CleanupPad:
508 case Instruction::LandingPad:
515 /// Create a copy of 'this' instruction that is identical in all ways except
517 /// * The instruction has no parent
518 /// * The instruction has no name
520 Instruction *clone() const;
522 /// Return true if the specified instruction is exactly identical to the
523 /// current one. This means that all operands match and any extra information
524 /// (e.g. load is volatile) agree.
525 bool isIdenticalTo(const Instruction *I) const;
527 /// This is like isIdenticalTo, except that it ignores the
528 /// SubclassOptionalData flags, which may specify conditions under which the
529 /// instruction's result is undefined.
530 bool isIdenticalToWhenDefined(const Instruction *I) const;
532 /// When checking for operation equivalence (using isSameOperationAs) it is
533 /// sometimes useful to ignore certain attributes.
534 enum OperationEquivalenceFlags {
535 /// Check for equivalence ignoring load/store alignment.
536 CompareIgnoringAlignment = 1<<0,
537 /// Check for equivalence treating a type and a vector of that type
539 CompareUsingScalarTypes = 1<<1
542 /// This function determines if the specified instruction executes the same
543 /// operation as the current one. This means that the opcodes, type, operand
544 /// types and any other factors affecting the operation must be the same. This
545 /// is similar to isIdenticalTo except the operands themselves don't have to
547 /// @returns true if the specified instruction is the same operation as
549 /// @brief Determine if one instruction is the same operation as another.
550 bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const;
552 /// Return true if there are any uses of this instruction in blocks other than
553 /// the specified block. Note that PHI nodes are considered to evaluate their
554 /// operands in the corresponding predecessor block.
555 bool isUsedOutsideOfBlock(const BasicBlock *BB) const;
558 /// Methods for support type inquiry through isa, cast, and dyn_cast:
559 static bool classof(const Value *V) {
560 return V->getValueID() >= Value::InstructionVal;
563 //----------------------------------------------------------------------
564 // Exported enumerations.
566 enum TermOps { // These terminate basic blocks
567 #define FIRST_TERM_INST(N) TermOpsBegin = N,
568 #define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N,
569 #define LAST_TERM_INST(N) TermOpsEnd = N+1
570 #include "llvm/IR/Instruction.def"
574 #define FIRST_BINARY_INST(N) BinaryOpsBegin = N,
575 #define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N,
576 #define LAST_BINARY_INST(N) BinaryOpsEnd = N+1
577 #include "llvm/IR/Instruction.def"
581 #define FIRST_MEMORY_INST(N) MemoryOpsBegin = N,
582 #define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N,
583 #define LAST_MEMORY_INST(N) MemoryOpsEnd = N+1
584 #include "llvm/IR/Instruction.def"
588 #define FIRST_CAST_INST(N) CastOpsBegin = N,
589 #define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N,
590 #define LAST_CAST_INST(N) CastOpsEnd = N+1
591 #include "llvm/IR/Instruction.def"
595 #define FIRST_FUNCLETPAD_INST(N) FuncletPadOpsBegin = N,
596 #define HANDLE_FUNCLETPAD_INST(N, OPC, CLASS) OPC = N,
597 #define LAST_FUNCLETPAD_INST(N) FuncletPadOpsEnd = N+1
598 #include "llvm/IR/Instruction.def"
602 #define FIRST_OTHER_INST(N) OtherOpsBegin = N,
603 #define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N,
604 #define LAST_OTHER_INST(N) OtherOpsEnd = N+1
605 #include "llvm/IR/Instruction.def"
609 friend class SymbolTableListTraits<Instruction>;
611 // Shadow Value::setValueSubclassData with a private forwarding method so that
612 // subclasses cannot accidentally use it.
613 void setValueSubclassData(unsigned short D) {
614 Value::setValueSubclassData(D);
617 unsigned short getSubclassDataFromValue() const {
618 return Value::getSubclassDataFromValue();
621 void setHasMetadataHashEntry(bool V) {
622 setValueSubclassData((getSubclassDataFromValue() & ~HasMetadataBit) |
623 (V ? HasMetadataBit : 0));
626 void setParent(BasicBlock *P);
629 // Instruction subclasses can stick up to 15 bits of stuff into the
630 // SubclassData field of instruction with these members.
632 // Verify that only the low 15 bits are used.
633 void setInstructionSubclassData(unsigned short D) {
634 assert((D & HasMetadataBit) == 0 && "Out of range value put into field");
635 setValueSubclassData((getSubclassDataFromValue() & HasMetadataBit) | D);
638 unsigned getSubclassDataFromInstruction() const {
639 return getSubclassDataFromValue() & ~HasMetadataBit;
642 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
643 Instruction *InsertBefore = nullptr);
644 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
645 BasicBlock *InsertAtEnd);
648 /// Create a copy of this instruction.
649 Instruction *cloneImpl() const;
652 inline void ilist_alloc_traits<Instruction>::deleteNode(Instruction *V) {
656 } // end namespace llvm
658 #endif // LLVM_IR_INSTRUCTION_H