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/ilist_node.h"
20 #include "llvm/ADT/None.h"
21 #include "llvm/ADT/StringRef.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 class Instruction : public User,
40 public ilist_node_with_parent<Instruction, BasicBlock> {
42 DebugLoc DbgLoc; // 'dbg' Metadata cache.
45 /// This is a bit stored in the SubClassData field which indicates whether
46 /// this instruction has metadata attached to it or not.
47 HasMetadataBit = 1 << 15
51 Instruction(const Instruction &) = delete;
52 Instruction &operator=(const Instruction &) = delete;
54 // Out of line virtual method, so the vtable, etc has a home.
55 ~Instruction() override;
57 /// Specialize the methods defined in Value, as we know that an instruction
58 /// can only be used by other instructions.
59 Instruction *user_back() { return cast<Instruction>(*user_begin());}
60 const Instruction *user_back() const { return cast<Instruction>(*user_begin());}
62 inline const BasicBlock *getParent() const { return Parent; }
63 inline BasicBlock *getParent() { return Parent; }
65 /// Return the module owning the function this instruction belongs to
66 /// or nullptr it the function does not have a module.
68 /// Note: this is undefined behavior if the instruction does not have a
69 /// parent, or the parent basic block does not have a parent function.
70 const Module *getModule() const;
73 /// Return the function this instruction belongs to.
75 /// Note: it is undefined behavior to call this on an instruction not
76 /// currently inserted into a function.
77 const Function *getFunction() const;
78 Function *getFunction();
80 /// This method unlinks 'this' from the containing basic block, but does not
82 void removeFromParent();
84 /// This method unlinks 'this' from the containing basic block and deletes it.
86 /// \returns an iterator pointing to the element after the erased one
87 SymbolTableList<Instruction>::iterator eraseFromParent();
89 /// Insert an unlinked instruction into a basic block immediately before
90 /// the specified instruction.
91 void insertBefore(Instruction *InsertPos);
93 /// Insert an unlinked instruction into a basic block immediately after the
94 /// specified instruction.
95 void insertAfter(Instruction *InsertPos);
97 /// Unlink this instruction from its current basic block and insert it into
98 /// the basic block that MovePos lives in, right before MovePos.
99 void moveBefore(Instruction *MovePos);
101 /// Unlink this instruction and insert into BB before I.
103 /// \pre I is a valid iterator into BB.
104 void moveBefore(BasicBlock &BB, SymbolTableList<Instruction>::iterator I);
106 //===--------------------------------------------------------------------===//
107 // Subclass classification.
108 //===--------------------------------------------------------------------===//
110 /// Returns a member of one of the enums like Instruction::Add.
111 unsigned getOpcode() const { return getValueID() - InstructionVal; }
113 const char *getOpcodeName() const { return getOpcodeName(getOpcode()); }
114 bool isTerminator() const { return isTerminator(getOpcode()); }
115 bool isBinaryOp() const { return isBinaryOp(getOpcode()); }
116 bool isShift() { return isShift(getOpcode()); }
117 bool isCast() const { return isCast(getOpcode()); }
118 bool isFuncletPad() const { return isFuncletPad(getOpcode()); }
120 static const char* getOpcodeName(unsigned OpCode);
122 static inline bool isTerminator(unsigned OpCode) {
123 return OpCode >= TermOpsBegin && OpCode < TermOpsEnd;
126 static inline bool isBinaryOp(unsigned Opcode) {
127 return Opcode >= BinaryOpsBegin && Opcode < BinaryOpsEnd;
130 /// Determine if the Opcode is one of the shift instructions.
131 static inline bool isShift(unsigned Opcode) {
132 return Opcode >= Shl && Opcode <= AShr;
135 /// Return true if this is a logical shift left or a logical shift right.
136 inline bool isLogicalShift() const {
137 return getOpcode() == Shl || getOpcode() == LShr;
140 /// Return true if this is an arithmetic shift right.
141 inline bool isArithmeticShift() const {
142 return getOpcode() == AShr;
145 /// Return true if this is and/or/xor.
146 inline bool isBitwiseLogicOp() const {
147 return getOpcode() == And || getOpcode() == Or || getOpcode() == Xor;
150 /// Determine if the OpCode is one of the CastInst instructions.
151 static inline bool isCast(unsigned OpCode) {
152 return OpCode >= CastOpsBegin && OpCode < CastOpsEnd;
155 /// Determine if the OpCode is one of the FuncletPadInst instructions.
156 static inline bool isFuncletPad(unsigned OpCode) {
157 return OpCode >= FuncletPadOpsBegin && OpCode < FuncletPadOpsEnd;
160 //===--------------------------------------------------------------------===//
161 // Metadata manipulation.
162 //===--------------------------------------------------------------------===//
164 /// Return true if this instruction has any metadata attached to it.
165 bool hasMetadata() const { return DbgLoc || hasMetadataHashEntry(); }
167 /// Return true if this instruction has metadata attached to it other than a
169 bool hasMetadataOtherThanDebugLoc() const {
170 return hasMetadataHashEntry();
173 /// Get the metadata of given kind attached to this Instruction.
174 /// If the metadata is not found then return null.
175 MDNode *getMetadata(unsigned KindID) const {
176 if (!hasMetadata()) return nullptr;
177 return getMetadataImpl(KindID);
180 /// Get the metadata of given kind attached to this Instruction.
181 /// If the metadata is not found then return null.
182 MDNode *getMetadata(StringRef Kind) const {
183 if (!hasMetadata()) return nullptr;
184 return getMetadataImpl(Kind);
187 /// Get all metadata attached to this Instruction. The first element of each
188 /// pair returned is the KindID, the second element is the metadata value.
189 /// This list is returned sorted by the KindID.
191 getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
193 getAllMetadataImpl(MDs);
196 /// This does the same thing as getAllMetadata, except that it filters out the
198 void getAllMetadataOtherThanDebugLoc(
199 SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
200 if (hasMetadataOtherThanDebugLoc())
201 getAllMetadataOtherThanDebugLocImpl(MDs);
204 /// Fills the AAMDNodes structure with AA metadata from this instruction.
205 /// When Merge is true, the existing AA metadata is merged with that from this
206 /// instruction providing the most-general result.
207 void getAAMetadata(AAMDNodes &N, bool Merge = false) const;
209 /// Set the metadata of the specified kind to the specified node. This updates
210 /// or replaces metadata if already present, or removes it if Node is null.
211 void setMetadata(unsigned KindID, MDNode *Node);
212 void setMetadata(StringRef Kind, MDNode *Node);
214 /// Copy metadata from \p SrcInst to this instruction. \p WL, if not empty,
215 /// specifies the list of meta data that needs to be copied. If \p WL is
216 /// empty, all meta data will be copied.
217 void copyMetadata(const Instruction &SrcInst,
218 ArrayRef<unsigned> WL = ArrayRef<unsigned>());
220 /// If the instruction has "branch_weights" MD_prof metadata and the MDNode
221 /// has three operands (including name string), swap the order of the
223 void swapProfMetadata();
225 /// Drop all unknown metadata except for debug locations.
227 /// Passes are required to drop metadata they don't understand. This is a
228 /// convenience method for passes to do so.
229 void dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs);
230 void dropUnknownNonDebugMetadata() {
231 return dropUnknownNonDebugMetadata(None);
233 void dropUnknownNonDebugMetadata(unsigned ID1) {
234 return dropUnknownNonDebugMetadata(makeArrayRef(ID1));
236 void dropUnknownNonDebugMetadata(unsigned ID1, unsigned ID2) {
237 unsigned IDs[] = {ID1, ID2};
238 return dropUnknownNonDebugMetadata(IDs);
242 /// Sets the metadata on this instruction from the AAMDNodes structure.
243 void setAAMetadata(const AAMDNodes &N);
245 /// Retrieve the raw weight values of a conditional branch or select.
246 /// Returns true on success with profile weights filled in.
247 /// Returns false if no metadata or invalid metadata was found.
248 bool extractProfMetadata(uint64_t &TrueVal, uint64_t &FalseVal) const;
250 /// Retrieve total raw weight values of a branch.
251 /// Returns true on success with profile total weights filled in.
252 /// Returns false if no metadata was found.
253 bool extractProfTotalWeight(uint64_t &TotalVal) const;
255 /// Set the debug location information for this instruction.
256 void setDebugLoc(DebugLoc Loc) { DbgLoc = std::move(Loc); }
258 /// Return the debug location for this node as a DebugLoc.
259 const DebugLoc &getDebugLoc() const { return DbgLoc; }
261 /// Set or clear the nsw flag on this instruction, which must be an operator
262 /// which supports this flag. See LangRef.html for the meaning of this flag.
263 void setHasNoUnsignedWrap(bool b = true);
265 /// Set or clear the nsw flag on this instruction, which must be an operator
266 /// which supports this flag. See LangRef.html for the meaning of this flag.
267 void setHasNoSignedWrap(bool b = true);
269 /// Set or clear the exact flag on this instruction, which must be an operator
270 /// which supports this flag. See LangRef.html for the meaning of this flag.
271 void setIsExact(bool b = true);
273 /// Determine whether the no unsigned wrap flag is set.
274 bool hasNoUnsignedWrap() const;
276 /// Determine whether the no signed wrap flag is set.
277 bool hasNoSignedWrap() const;
279 /// Determine whether the exact flag is set.
280 bool isExact() const;
282 /// Set or clear the unsafe-algebra flag on this instruction, which must be an
283 /// operator which supports this flag. See LangRef.html for the meaning of
285 void setHasUnsafeAlgebra(bool B);
287 /// Set or clear the no-nans flag on this instruction, which must be an
288 /// operator which supports this flag. See LangRef.html for the meaning of
290 void setHasNoNaNs(bool B);
292 /// Set or clear the no-infs flag on this instruction, which must be an
293 /// operator which supports this flag. See LangRef.html for the meaning of
295 void setHasNoInfs(bool B);
297 /// Set or clear the no-signed-zeros flag on this instruction, which must be
298 /// an operator which supports this flag. See LangRef.html for the meaning of
300 void setHasNoSignedZeros(bool B);
302 /// Set or clear the allow-reciprocal flag on this instruction, which must be
303 /// an operator which supports this flag. See LangRef.html for the meaning of
305 void setHasAllowReciprocal(bool B);
307 /// Convenience function for setting multiple fast-math flags on this
308 /// instruction, which must be an operator which supports these flags. See
309 /// LangRef.html for the meaning of these flags.
310 void setFastMathFlags(FastMathFlags FMF);
312 /// Convenience function for transferring all fast-math flag values to this
313 /// instruction, which must be an operator which supports these flags. See
314 /// LangRef.html for the meaning of these flags.
315 void copyFastMathFlags(FastMathFlags FMF);
317 /// Determine whether the unsafe-algebra flag is set.
318 bool hasUnsafeAlgebra() const;
320 /// Determine whether the no-NaNs flag is set.
321 bool hasNoNaNs() const;
323 /// Determine whether the no-infs flag is set.
324 bool hasNoInfs() const;
326 /// Determine whether the no-signed-zeros flag is set.
327 bool hasNoSignedZeros() const;
329 /// Determine whether the allow-reciprocal flag is set.
330 bool hasAllowReciprocal() const;
332 /// Convenience function for getting all the fast-math flags, which must be an
333 /// operator which supports these flags. See LangRef.html for the meaning of
335 FastMathFlags getFastMathFlags() const;
337 /// Copy I's fast-math flags
338 void copyFastMathFlags(const Instruction *I);
340 /// Convenience method to copy supported wrapping, exact, and fast-math flags
341 /// from V to this instruction.
342 void copyIRFlags(const Value *V);
344 /// Logical 'and' of any supported wrapping, exact, and fast-math flags of
345 /// V and this instruction.
346 void andIRFlags(const Value *V);
349 /// Return true if we have an entry in the on-the-side metadata hash.
350 bool hasMetadataHashEntry() const {
351 return (getSubclassDataFromValue() & HasMetadataBit) != 0;
354 // These are all implemented in Metadata.cpp.
355 MDNode *getMetadataImpl(unsigned KindID) const;
356 MDNode *getMetadataImpl(StringRef Kind) const;
358 getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
359 void getAllMetadataOtherThanDebugLocImpl(
360 SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
361 /// Clear all hashtable-based metadata from this instruction.
362 void clearMetadataHashEntries();
365 //===--------------------------------------------------------------------===//
366 // Predicates and helper methods.
367 //===--------------------------------------------------------------------===//
369 /// Return true if the instruction is associative:
371 /// Associative operators satisfy: x op (y op z) === (x op y) op z
373 /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
375 bool isAssociative() const;
376 static bool isAssociative(unsigned op);
378 /// Return true if the instruction is commutative:
380 /// Commutative operators satisfy: (x op y) === (y op x)
382 /// In LLVM, these are the associative operators, plus SetEQ and SetNE, when
383 /// applied to any type.
385 bool isCommutative() const { return isCommutative(getOpcode()); }
386 static bool isCommutative(unsigned op);
388 /// Return true if the instruction is idempotent:
390 /// Idempotent operators satisfy: x op x === x
392 /// In LLVM, the And and Or operators are idempotent.
394 bool isIdempotent() const { return isIdempotent(getOpcode()); }
395 static bool isIdempotent(unsigned op);
397 /// Return true if the instruction is nilpotent:
399 /// Nilpotent operators satisfy: x op x === Id,
401 /// where Id is the identity for the operator, i.e. a constant such that
402 /// x op Id === x and Id op x === x for all x.
404 /// In LLVM, the Xor operator is nilpotent.
406 bool isNilpotent() const { return isNilpotent(getOpcode()); }
407 static bool isNilpotent(unsigned op);
409 /// Return true if this instruction may modify memory.
410 bool mayWriteToMemory() const;
412 /// Return true if this instruction may read memory.
413 bool mayReadFromMemory() const;
415 /// Return true if this instruction may read or write memory.
416 bool mayReadOrWriteMemory() const {
417 return mayReadFromMemory() || mayWriteToMemory();
420 /// Return true if this instruction has an AtomicOrdering of unordered or
422 bool isAtomic() const;
424 /// Return true if this instruction may throw an exception.
425 bool mayThrow() const;
427 /// Return true if this instruction behaves like a memory fence: it can load
428 /// or store to memory location without being given a memory location.
429 bool isFenceLike() const {
430 switch (getOpcode()) {
433 // This list should be kept in sync with the list in mayWriteToMemory for
434 // all opcodes which don't have a memory location.
435 case Instruction::Fence:
436 case Instruction::CatchPad:
437 case Instruction::CatchRet:
438 case Instruction::Call:
439 case Instruction::Invoke:
444 /// Return true if the instruction may have side effects.
446 /// Note that this does not consider malloc and alloca to have side
447 /// effects because the newly allocated memory is completely invisible to
448 /// instructions which don't use the returned value. For cases where this
449 /// matters, isSafeToSpeculativelyExecute may be more appropriate.
450 bool mayHaveSideEffects() const { return mayWriteToMemory() || mayThrow(); }
452 /// Return true if the instruction is a variety of EH-block.
453 bool isEHPad() const {
454 switch (getOpcode()) {
455 case Instruction::CatchSwitch:
456 case Instruction::CatchPad:
457 case Instruction::CleanupPad:
458 case Instruction::LandingPad:
465 /// Create a copy of 'this' instruction that is identical in all ways except
467 /// * The instruction has no parent
468 /// * The instruction has no name
470 Instruction *clone() const;
472 /// Return true if the specified instruction is exactly identical to the
473 /// current one. This means that all operands match and any extra information
474 /// (e.g. load is volatile) agree.
475 bool isIdenticalTo(const Instruction *I) const;
477 /// This is like isIdenticalTo, except that it ignores the
478 /// SubclassOptionalData flags, which may specify conditions under which the
479 /// instruction's result is undefined.
480 bool isIdenticalToWhenDefined(const Instruction *I) const;
482 /// When checking for operation equivalence (using isSameOperationAs) it is
483 /// sometimes useful to ignore certain attributes.
484 enum OperationEquivalenceFlags {
485 /// Check for equivalence ignoring load/store alignment.
486 CompareIgnoringAlignment = 1<<0,
487 /// Check for equivalence treating a type and a vector of that type
489 CompareUsingScalarTypes = 1<<1
492 /// This function determines if the specified instruction executes the same
493 /// operation as the current one. This means that the opcodes, type, operand
494 /// types and any other factors affecting the operation must be the same. This
495 /// is similar to isIdenticalTo except the operands themselves don't have to
497 /// @returns true if the specified instruction is the same operation as
499 /// @brief Determine if one instruction is the same operation as another.
500 bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const;
502 /// Return true if there are any uses of this instruction in blocks other than
503 /// the specified block. Note that PHI nodes are considered to evaluate their
504 /// operands in the corresponding predecessor block.
505 bool isUsedOutsideOfBlock(const BasicBlock *BB) const;
508 /// Methods for support type inquiry through isa, cast, and dyn_cast:
509 static inline bool classof(const Value *V) {
510 return V->getValueID() >= Value::InstructionVal;
513 //----------------------------------------------------------------------
514 // Exported enumerations.
516 enum TermOps { // These terminate basic blocks
517 #define FIRST_TERM_INST(N) TermOpsBegin = N,
518 #define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N,
519 #define LAST_TERM_INST(N) TermOpsEnd = N+1
520 #include "llvm/IR/Instruction.def"
524 #define FIRST_BINARY_INST(N) BinaryOpsBegin = N,
525 #define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N,
526 #define LAST_BINARY_INST(N) BinaryOpsEnd = N+1
527 #include "llvm/IR/Instruction.def"
531 #define FIRST_MEMORY_INST(N) MemoryOpsBegin = N,
532 #define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N,
533 #define LAST_MEMORY_INST(N) MemoryOpsEnd = N+1
534 #include "llvm/IR/Instruction.def"
538 #define FIRST_CAST_INST(N) CastOpsBegin = N,
539 #define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N,
540 #define LAST_CAST_INST(N) CastOpsEnd = N+1
541 #include "llvm/IR/Instruction.def"
545 #define FIRST_FUNCLETPAD_INST(N) FuncletPadOpsBegin = N,
546 #define HANDLE_FUNCLETPAD_INST(N, OPC, CLASS) OPC = N,
547 #define LAST_FUNCLETPAD_INST(N) FuncletPadOpsEnd = N+1
548 #include "llvm/IR/Instruction.def"
552 #define FIRST_OTHER_INST(N) OtherOpsBegin = N,
553 #define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N,
554 #define LAST_OTHER_INST(N) OtherOpsEnd = N+1
555 #include "llvm/IR/Instruction.def"
559 friend class SymbolTableListTraits<Instruction>;
561 // Shadow Value::setValueSubclassData with a private forwarding method so that
562 // subclasses cannot accidentally use it.
563 void setValueSubclassData(unsigned short D) {
564 Value::setValueSubclassData(D);
567 unsigned short getSubclassDataFromValue() const {
568 return Value::getSubclassDataFromValue();
571 void setHasMetadataHashEntry(bool V) {
572 setValueSubclassData((getSubclassDataFromValue() & ~HasMetadataBit) |
573 (V ? HasMetadataBit : 0));
576 void setParent(BasicBlock *P);
579 // Instruction subclasses can stick up to 15 bits of stuff into the
580 // SubclassData field of instruction with these members.
582 // Verify that only the low 15 bits are used.
583 void setInstructionSubclassData(unsigned short D) {
584 assert((D & HasMetadataBit) == 0 && "Out of range value put into field");
585 setValueSubclassData((getSubclassDataFromValue() & HasMetadataBit) | D);
588 unsigned getSubclassDataFromInstruction() const {
589 return getSubclassDataFromValue() & ~HasMetadataBit;
592 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
593 Instruction *InsertBefore = nullptr);
594 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
595 BasicBlock *InsertAtEnd);
598 /// Create a copy of this instruction.
599 Instruction *cloneImpl() const;
602 } // end namespace llvm
604 #endif // LLVM_IR_INSTRUCTION_H