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/IR/DebugLoc.h"
21 #include "llvm/IR/SymbolTableListTraits.h"
22 #include "llvm/IR/User.h"
32 class Instruction : public User,
33 public ilist_node_with_parent<Instruction, BasicBlock> {
34 void operator=(const Instruction &) = delete;
35 Instruction(const Instruction &) = delete;
38 DebugLoc DbgLoc; // 'dbg' Metadata cache.
41 /// This is a bit stored in the SubClassData field which indicates whether
42 /// this instruction has metadata attached to it or not.
43 HasMetadataBit = 1 << 15
46 // Out of line virtual method, so the vtable, etc has a home.
47 ~Instruction() override;
49 /// Specialize the methods defined in Value, as we know that an instruction
50 /// can only be used by other instructions.
51 Instruction *user_back() { return cast<Instruction>(*user_begin());}
52 const Instruction *user_back() const { return cast<Instruction>(*user_begin());}
54 inline const BasicBlock *getParent() const { return Parent; }
55 inline BasicBlock *getParent() { return Parent; }
57 /// Return the module owning the function this instruction belongs to
58 /// or nullptr it the function does not have a module.
60 /// Note: this is undefined behavior if the instruction does not have a
61 /// parent, or the parent basic block does not have a parent function.
62 const Module *getModule() const;
65 /// Return the function this instruction belongs to.
67 /// Note: it is undefined behavior to call this on an instruction not
68 /// currently inserted into a function.
69 const Function *getFunction() const;
70 Function *getFunction();
72 /// This method unlinks 'this' from the containing basic block, but does not
74 void removeFromParent();
76 /// This method unlinks 'this' from the containing basic block and deletes it.
78 /// \returns an iterator pointing to the element after the erased one
79 SymbolTableList<Instruction>::iterator eraseFromParent();
81 /// Insert an unlinked instruction into a basic block immediately before
82 /// the specified instruction.
83 void insertBefore(Instruction *InsertPos);
85 /// Insert an unlinked instruction into a basic block immediately after the
86 /// specified instruction.
87 void insertAfter(Instruction *InsertPos);
89 /// Unlink this instruction from its current basic block and insert it into
90 /// the basic block that MovePos lives in, right before MovePos.
91 void moveBefore(Instruction *MovePos);
93 /// Unlink this instruction and insert into BB before I.
95 /// \pre I is a valid iterator into BB.
96 void moveBefore(BasicBlock &BB, SymbolTableList<Instruction>::iterator I);
98 //===--------------------------------------------------------------------===//
99 // Subclass classification.
100 //===--------------------------------------------------------------------===//
102 /// Returns a member of one of the enums like Instruction::Add.
103 unsigned getOpcode() const { return getValueID() - InstructionVal; }
105 const char *getOpcodeName() const { return getOpcodeName(getOpcode()); }
106 bool isTerminator() const { return isTerminator(getOpcode()); }
107 bool isBinaryOp() const { return isBinaryOp(getOpcode()); }
108 bool isShift() { return isShift(getOpcode()); }
109 bool isCast() const { return isCast(getOpcode()); }
110 bool isFuncletPad() const { return isFuncletPad(getOpcode()); }
112 static const char* getOpcodeName(unsigned OpCode);
114 static inline bool isTerminator(unsigned OpCode) {
115 return OpCode >= TermOpsBegin && OpCode < TermOpsEnd;
118 static inline bool isBinaryOp(unsigned Opcode) {
119 return Opcode >= BinaryOpsBegin && Opcode < BinaryOpsEnd;
122 /// Determine if the Opcode is one of the shift instructions.
123 static inline bool isShift(unsigned Opcode) {
124 return Opcode >= Shl && Opcode <= AShr;
127 /// Return true if this is a logical shift left or a logical shift right.
128 inline bool isLogicalShift() const {
129 return getOpcode() == Shl || getOpcode() == LShr;
132 /// Return true if this is an arithmetic shift right.
133 inline bool isArithmeticShift() const {
134 return getOpcode() == AShr;
137 /// Determine if the OpCode is one of the CastInst instructions.
138 static inline bool isCast(unsigned OpCode) {
139 return OpCode >= CastOpsBegin && OpCode < CastOpsEnd;
142 /// Determine if the OpCode is one of the FuncletPadInst instructions.
143 static inline bool isFuncletPad(unsigned OpCode) {
144 return OpCode >= FuncletPadOpsBegin && OpCode < FuncletPadOpsEnd;
147 //===--------------------------------------------------------------------===//
148 // Metadata manipulation.
149 //===--------------------------------------------------------------------===//
151 /// Return true if this instruction has any metadata attached to it.
152 bool hasMetadata() const { return DbgLoc || hasMetadataHashEntry(); }
154 /// Return true if this instruction has metadata attached to it other than a
156 bool hasMetadataOtherThanDebugLoc() const {
157 return hasMetadataHashEntry();
160 /// Get the metadata of given kind attached to this Instruction.
161 /// If the metadata is not found then return null.
162 MDNode *getMetadata(unsigned KindID) const {
163 if (!hasMetadata()) return nullptr;
164 return getMetadataImpl(KindID);
167 /// Get the metadata of given kind attached to this Instruction.
168 /// If the metadata is not found then return null.
169 MDNode *getMetadata(StringRef Kind) const {
170 if (!hasMetadata()) return nullptr;
171 return getMetadataImpl(Kind);
174 /// Get all metadata attached to this Instruction. The first element of each
175 /// pair returned is the KindID, the second element is the metadata value.
176 /// This list is returned sorted by the KindID.
178 getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
180 getAllMetadataImpl(MDs);
183 /// This does the same thing as getAllMetadata, except that it filters out the
185 void getAllMetadataOtherThanDebugLoc(
186 SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
187 if (hasMetadataOtherThanDebugLoc())
188 getAllMetadataOtherThanDebugLocImpl(MDs);
191 /// Fills the AAMDNodes structure with AA metadata from this instruction.
192 /// When Merge is true, the existing AA metadata is merged with that from this
193 /// instruction providing the most-general result.
194 void getAAMetadata(AAMDNodes &N, bool Merge = false) const;
196 /// Set the metadata of the specified kind to the specified node. This updates
197 /// or replaces metadata if already present, or removes it if Node is null.
198 void setMetadata(unsigned KindID, MDNode *Node);
199 void setMetadata(StringRef Kind, MDNode *Node);
201 /// Copy metadata from \p SrcInst to this instruction. \p WL, if not empty,
202 /// specifies the list of meta data that needs to be copied. If \p WL is
203 /// empty, all meta data will be copied.
204 void copyMetadata(const Instruction &SrcInst,
205 ArrayRef<unsigned> WL = ArrayRef<unsigned>());
207 /// If the instruction has "branch_weights" MD_prof metadata and the MDNode
208 /// has three operands (including name string), swap the order of the
210 void swapProfMetadata();
212 /// Drop all unknown metadata except for debug locations.
214 /// Passes are required to drop metadata they don't understand. This is a
215 /// convenience method for passes to do so.
216 void dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs);
217 void dropUnknownNonDebugMetadata() {
218 return dropUnknownNonDebugMetadata(None);
220 void dropUnknownNonDebugMetadata(unsigned ID1) {
221 return dropUnknownNonDebugMetadata(makeArrayRef(ID1));
223 void dropUnknownNonDebugMetadata(unsigned ID1, unsigned ID2) {
224 unsigned IDs[] = {ID1, ID2};
225 return dropUnknownNonDebugMetadata(IDs);
229 /// Sets the metadata on this instruction from the AAMDNodes structure.
230 void setAAMetadata(const AAMDNodes &N);
232 /// Retrieve the raw weight values of a conditional branch or select.
233 /// Returns true on success with profile weights filled in.
234 /// Returns false if no metadata or invalid metadata was found.
235 bool extractProfMetadata(uint64_t &TrueVal, uint64_t &FalseVal) const;
237 /// Retrieve total raw weight values of a branch.
238 /// Returns true on success with profile total weights filled in.
239 /// Returns false if no metadata was found.
240 bool extractProfTotalWeight(uint64_t &TotalVal) const;
242 /// Set the debug location information for this instruction.
243 void setDebugLoc(DebugLoc Loc) { DbgLoc = std::move(Loc); }
245 /// Return the debug location for this node as a DebugLoc.
246 const DebugLoc &getDebugLoc() const { return DbgLoc; }
248 /// Set or clear the nsw flag on this instruction, which must be an operator
249 /// which supports this flag. See LangRef.html for the meaning of this flag.
250 void setHasNoUnsignedWrap(bool b = true);
252 /// Set or clear the nsw flag on this instruction, which must be an operator
253 /// which supports this flag. See LangRef.html for the meaning of this flag.
254 void setHasNoSignedWrap(bool b = true);
256 /// Set or clear the exact flag on this instruction, which must be an operator
257 /// which supports this flag. See LangRef.html for the meaning of this flag.
258 void setIsExact(bool b = true);
260 /// Determine whether the no unsigned wrap flag is set.
261 bool hasNoUnsignedWrap() const;
263 /// Determine whether the no signed wrap flag is set.
264 bool hasNoSignedWrap() const;
266 /// Determine whether the exact flag is set.
267 bool isExact() const;
269 /// Set or clear the unsafe-algebra flag on this instruction, which must be an
270 /// operator which supports this flag. See LangRef.html for the meaning of
272 void setHasUnsafeAlgebra(bool B);
274 /// Set or clear the no-nans flag on this instruction, which must be an
275 /// operator which supports this flag. See LangRef.html for the meaning of
277 void setHasNoNaNs(bool B);
279 /// Set or clear the no-infs flag on this instruction, which must be an
280 /// operator which supports this flag. See LangRef.html for the meaning of
282 void setHasNoInfs(bool B);
284 /// Set or clear the no-signed-zeros flag on this instruction, which must be
285 /// an operator which supports this flag. See LangRef.html for the meaning of
287 void setHasNoSignedZeros(bool B);
289 /// Set or clear the allow-reciprocal flag on this instruction, which must be
290 /// an operator which supports this flag. See LangRef.html for the meaning of
292 void setHasAllowReciprocal(bool B);
294 /// Convenience function for setting multiple fast-math flags on this
295 /// instruction, which must be an operator which supports these flags. See
296 /// LangRef.html for the meaning of these flags.
297 void setFastMathFlags(FastMathFlags FMF);
299 /// Convenience function for transferring all fast-math flag values to this
300 /// instruction, which must be an operator which supports these flags. See
301 /// LangRef.html for the meaning of these flags.
302 void copyFastMathFlags(FastMathFlags FMF);
304 /// Determine whether the unsafe-algebra flag is set.
305 bool hasUnsafeAlgebra() const;
307 /// Determine whether the no-NaNs flag is set.
308 bool hasNoNaNs() const;
310 /// Determine whether the no-infs flag is set.
311 bool hasNoInfs() const;
313 /// Determine whether the no-signed-zeros flag is set.
314 bool hasNoSignedZeros() const;
316 /// Determine whether the allow-reciprocal flag is set.
317 bool hasAllowReciprocal() const;
319 /// Convenience function for getting all the fast-math flags, which must be an
320 /// operator which supports these flags. See LangRef.html for the meaning of
322 FastMathFlags getFastMathFlags() const;
324 /// Copy I's fast-math flags
325 void copyFastMathFlags(const Instruction *I);
327 /// Convenience method to copy supported wrapping, exact, and fast-math flags
328 /// from V to this instruction.
329 void copyIRFlags(const Value *V);
331 /// Logical 'and' of any supported wrapping, exact, and fast-math flags of
332 /// V and this instruction.
333 void andIRFlags(const Value *V);
336 /// Return true if we have an entry in the on-the-side metadata hash.
337 bool hasMetadataHashEntry() const {
338 return (getSubclassDataFromValue() & HasMetadataBit) != 0;
341 // These are all implemented in Metadata.cpp.
342 MDNode *getMetadataImpl(unsigned KindID) const;
343 MDNode *getMetadataImpl(StringRef Kind) const;
345 getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
346 void getAllMetadataOtherThanDebugLocImpl(
347 SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
348 /// Clear all hashtable-based metadata from this instruction.
349 void clearMetadataHashEntries();
351 //===--------------------------------------------------------------------===//
352 // Predicates and helper methods.
353 //===--------------------------------------------------------------------===//
356 /// Return true if the instruction is associative:
358 /// Associative operators satisfy: x op (y op z) === (x op y) op z
360 /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
362 bool isAssociative() const;
363 static bool isAssociative(unsigned op);
365 /// Return true if the instruction is commutative:
367 /// Commutative operators satisfy: (x op y) === (y op x)
369 /// In LLVM, these are the associative operators, plus SetEQ and SetNE, when
370 /// applied to any type.
372 bool isCommutative() const { return isCommutative(getOpcode()); }
373 static bool isCommutative(unsigned op);
375 /// Return true if the instruction is idempotent:
377 /// Idempotent operators satisfy: x op x === x
379 /// In LLVM, the And and Or operators are idempotent.
381 bool isIdempotent() const { return isIdempotent(getOpcode()); }
382 static bool isIdempotent(unsigned op);
384 /// Return true if the instruction is nilpotent:
386 /// Nilpotent operators satisfy: x op x === Id,
388 /// where Id is the identity for the operator, i.e. a constant such that
389 /// x op Id === x and Id op x === x for all x.
391 /// In LLVM, the Xor operator is nilpotent.
393 bool isNilpotent() const { return isNilpotent(getOpcode()); }
394 static bool isNilpotent(unsigned op);
396 /// Return true if this instruction may modify memory.
397 bool mayWriteToMemory() const;
399 /// Return true if this instruction may read memory.
400 bool mayReadFromMemory() const;
402 /// Return true if this instruction may read or write memory.
403 bool mayReadOrWriteMemory() const {
404 return mayReadFromMemory() || mayWriteToMemory();
407 /// Return true if this instruction has an AtomicOrdering of unordered or
409 bool isAtomic() const;
411 /// Return true if this instruction may throw an exception.
412 bool mayThrow() const;
414 /// Return true if this instruction behaves like a memory fence: it can load
415 /// or store to memory location without being given a memory location.
416 bool isFenceLike() const {
417 switch (getOpcode()) {
420 // This list should be kept in sync with the list in mayWriteToMemory for
421 // all opcodes which don't have a memory location.
422 case Instruction::Fence:
423 case Instruction::CatchPad:
424 case Instruction::CatchRet:
425 case Instruction::Call:
426 case Instruction::Invoke:
431 /// Return true if the instruction may have side effects.
433 /// Note that this does not consider malloc and alloca to have side
434 /// effects because the newly allocated memory is completely invisible to
435 /// instructions which don't use the returned value. For cases where this
436 /// matters, isSafeToSpeculativelyExecute may be more appropriate.
437 bool mayHaveSideEffects() const { return mayWriteToMemory() || mayThrow(); }
439 /// Return true if the instruction is a variety of EH-block.
440 bool isEHPad() const {
441 switch (getOpcode()) {
442 case Instruction::CatchSwitch:
443 case Instruction::CatchPad:
444 case Instruction::CleanupPad:
445 case Instruction::LandingPad:
452 /// Create a copy of 'this' instruction that is identical in all ways except
454 /// * The instruction has no parent
455 /// * The instruction has no name
457 Instruction *clone() const;
459 /// Return true if the specified instruction is exactly identical to the
460 /// current one. This means that all operands match and any extra information
461 /// (e.g. load is volatile) agree.
462 bool isIdenticalTo(const Instruction *I) const;
464 /// This is like isIdenticalTo, except that it ignores the
465 /// SubclassOptionalData flags, which may specify conditions under which the
466 /// instruction's result is undefined.
467 bool isIdenticalToWhenDefined(const Instruction *I) const;
469 /// When checking for operation equivalence (using isSameOperationAs) it is
470 /// sometimes useful to ignore certain attributes.
471 enum OperationEquivalenceFlags {
472 /// Check for equivalence ignoring load/store alignment.
473 CompareIgnoringAlignment = 1<<0,
474 /// Check for equivalence treating a type and a vector of that type
476 CompareUsingScalarTypes = 1<<1
479 /// This function determines if the specified instruction executes the same
480 /// operation as the current one. This means that the opcodes, type, operand
481 /// types and any other factors affecting the operation must be the same. This
482 /// is similar to isIdenticalTo except the operands themselves don't have to
484 /// @returns true if the specified instruction is the same operation as
486 /// @brief Determine if one instruction is the same operation as another.
487 bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const;
489 /// Return true if there are any uses of this instruction in blocks other than
490 /// the specified block. Note that PHI nodes are considered to evaluate their
491 /// operands in the corresponding predecessor block.
492 bool isUsedOutsideOfBlock(const BasicBlock *BB) const;
495 /// Methods for support type inquiry through isa, cast, and dyn_cast:
496 static inline bool classof(const Value *V) {
497 return V->getValueID() >= Value::InstructionVal;
500 //----------------------------------------------------------------------
501 // Exported enumerations.
503 enum TermOps { // These terminate basic blocks
504 #define FIRST_TERM_INST(N) TermOpsBegin = N,
505 #define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N,
506 #define LAST_TERM_INST(N) TermOpsEnd = N+1
507 #include "llvm/IR/Instruction.def"
511 #define FIRST_BINARY_INST(N) BinaryOpsBegin = N,
512 #define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N,
513 #define LAST_BINARY_INST(N) BinaryOpsEnd = N+1
514 #include "llvm/IR/Instruction.def"
518 #define FIRST_MEMORY_INST(N) MemoryOpsBegin = N,
519 #define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N,
520 #define LAST_MEMORY_INST(N) MemoryOpsEnd = N+1
521 #include "llvm/IR/Instruction.def"
525 #define FIRST_CAST_INST(N) CastOpsBegin = N,
526 #define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N,
527 #define LAST_CAST_INST(N) CastOpsEnd = N+1
528 #include "llvm/IR/Instruction.def"
532 #define FIRST_FUNCLETPAD_INST(N) FuncletPadOpsBegin = N,
533 #define HANDLE_FUNCLETPAD_INST(N, OPC, CLASS) OPC = N,
534 #define LAST_FUNCLETPAD_INST(N) FuncletPadOpsEnd = N+1
535 #include "llvm/IR/Instruction.def"
539 #define FIRST_OTHER_INST(N) OtherOpsBegin = N,
540 #define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N,
541 #define LAST_OTHER_INST(N) OtherOpsEnd = N+1
542 #include "llvm/IR/Instruction.def"
545 // Shadow Value::setValueSubclassData with a private forwarding method so that
546 // subclasses cannot accidentally use it.
547 void setValueSubclassData(unsigned short D) {
548 Value::setValueSubclassData(D);
550 unsigned short getSubclassDataFromValue() const {
551 return Value::getSubclassDataFromValue();
554 void setHasMetadataHashEntry(bool V) {
555 setValueSubclassData((getSubclassDataFromValue() & ~HasMetadataBit) |
556 (V ? HasMetadataBit : 0));
559 friend class SymbolTableListTraits<Instruction>;
560 void setParent(BasicBlock *P);
562 // Instruction subclasses can stick up to 15 bits of stuff into the
563 // SubclassData field of instruction with these members.
565 // Verify that only the low 15 bits are used.
566 void setInstructionSubclassData(unsigned short D) {
567 assert((D & HasMetadataBit) == 0 && "Out of range value put into field");
568 setValueSubclassData((getSubclassDataFromValue() & HasMetadataBit) | D);
571 unsigned getSubclassDataFromInstruction() const {
572 return getSubclassDataFromValue() & ~HasMetadataBit;
575 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
576 Instruction *InsertBefore = nullptr);
577 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
578 BasicBlock *InsertAtEnd);
581 /// Create a copy of this instruction.
582 Instruction *cloneImpl() const;
585 // Instruction* is only 4-byte aligned.
587 class PointerLikeTypeTraits<Instruction*> {
588 typedef Instruction* PT;
590 static inline void *getAsVoidPointer(PT P) { return P; }
591 static inline PT getFromVoidPointer(void *P) {
592 return static_cast<PT>(P);
594 enum { NumLowBitsAvailable = 2 };
597 } // End llvm namespace