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"
33 struct SymbolTableListSentinelTraits<Instruction>
34 : public ilist_half_embedded_sentinel_traits<Instruction> {};
36 class Instruction : public User,
37 public ilist_node_with_parent<Instruction, BasicBlock> {
38 void operator=(const Instruction &) = delete;
39 Instruction(const Instruction &) = delete;
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
50 // Out of line virtual method, so the vtable, etc has a home.
51 ~Instruction() override;
53 /// Specialize the methods defined in Value, as we know that an instruction
54 /// can only be used by other instructions.
55 Instruction *user_back() { return cast<Instruction>(*user_begin());}
56 const Instruction *user_back() const { return cast<Instruction>(*user_begin());}
58 inline const BasicBlock *getParent() const { return Parent; }
59 inline BasicBlock *getParent() { return Parent; }
61 /// Return the module owning the function this instruction belongs to
62 /// or nullptr it the function does not have a module.
64 /// Note: this is undefined behavior if the instruction does not have a
65 /// parent, or the parent basic block does not have a parent function.
66 const Module *getModule() const;
69 /// Return the function this instruction belongs to.
71 /// Note: it is undefined behavior to call this on an instruction not
72 /// currently inserted into a function.
73 const Function *getFunction() const;
74 Function *getFunction();
76 /// This method unlinks 'this' from the containing basic block, but does not
78 void removeFromParent();
80 /// This method unlinks 'this' from the containing basic block and deletes it.
82 /// \returns an iterator pointing to the element after the erased one
83 SymbolTableList<Instruction>::iterator eraseFromParent();
85 /// Insert an unlinked instruction into a basic block immediately before
86 /// the specified instruction.
87 void insertBefore(Instruction *InsertPos);
89 /// Insert an unlinked instruction into a basic block immediately after the
90 /// specified instruction.
91 void insertAfter(Instruction *InsertPos);
93 /// Unlink this instruction from its current basic block and insert it into
94 /// the basic block that MovePos lives in, right before MovePos.
95 void moveBefore(Instruction *MovePos);
97 //===--------------------------------------------------------------------===//
98 // Subclass classification.
99 //===--------------------------------------------------------------------===//
101 /// Returns a member of one of the enums like Instruction::Add.
102 unsigned getOpcode() const { return getValueID() - InstructionVal; }
104 const char *getOpcodeName() const { return getOpcodeName(getOpcode()); }
105 bool isTerminator() const { return isTerminator(getOpcode()); }
106 bool isBinaryOp() const { return isBinaryOp(getOpcode()); }
107 bool isShift() { return isShift(getOpcode()); }
108 bool isCast() const { return isCast(getOpcode()); }
109 bool isFuncletPad() const { return isFuncletPad(getOpcode()); }
111 static const char* getOpcodeName(unsigned OpCode);
113 static inline bool isTerminator(unsigned OpCode) {
114 return OpCode >= TermOpsBegin && OpCode < TermOpsEnd;
117 static inline bool isBinaryOp(unsigned Opcode) {
118 return Opcode >= BinaryOpsBegin && Opcode < BinaryOpsEnd;
121 /// Determine if the Opcode is one of the shift instructions.
122 static inline bool isShift(unsigned Opcode) {
123 return Opcode >= Shl && Opcode <= AShr;
126 /// Return true if this is a logical shift left or a logical shift right.
127 inline bool isLogicalShift() const {
128 return getOpcode() == Shl || getOpcode() == LShr;
131 /// Return true if this is an arithmetic shift right.
132 inline bool isArithmeticShift() const {
133 return getOpcode() == AShr;
136 /// Determine if the OpCode is one of the CastInst instructions.
137 static inline bool isCast(unsigned OpCode) {
138 return OpCode >= CastOpsBegin && OpCode < CastOpsEnd;
141 /// Determine if the OpCode is one of the FuncletPadInst instructions.
142 static inline bool isFuncletPad(unsigned OpCode) {
143 return OpCode >= FuncletPadOpsBegin && OpCode < FuncletPadOpsEnd;
146 //===--------------------------------------------------------------------===//
147 // Metadata manipulation.
148 //===--------------------------------------------------------------------===//
150 /// Return true if this instruction has any metadata attached to it.
151 bool hasMetadata() const { return DbgLoc || hasMetadataHashEntry(); }
153 /// Return true if this instruction has metadata attached to it other than a
155 bool hasMetadataOtherThanDebugLoc() const {
156 return hasMetadataHashEntry();
159 /// Get the metadata of given kind attached to this Instruction.
160 /// If the metadata is not found then return null.
161 MDNode *getMetadata(unsigned KindID) const {
162 if (!hasMetadata()) return nullptr;
163 return getMetadataImpl(KindID);
166 /// Get the metadata of given kind attached to this Instruction.
167 /// If the metadata is not found then return null.
168 MDNode *getMetadata(StringRef Kind) const {
169 if (!hasMetadata()) return nullptr;
170 return getMetadataImpl(Kind);
173 /// Get all metadata attached to this Instruction. The first element of each
174 /// pair returned is the KindID, the second element is the metadata value.
175 /// This list is returned sorted by the KindID.
177 getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
179 getAllMetadataImpl(MDs);
182 /// This does the same thing as getAllMetadata, except that it filters out the
184 void getAllMetadataOtherThanDebugLoc(
185 SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
186 if (hasMetadataOtherThanDebugLoc())
187 getAllMetadataOtherThanDebugLocImpl(MDs);
190 /// Fills the AAMDNodes structure with AA metadata from this instruction.
191 /// When Merge is true, the existing AA metadata is merged with that from this
192 /// instruction providing the most-general result.
193 void getAAMetadata(AAMDNodes &N, bool Merge = false) const;
195 /// Set the metadata of the specified kind to the specified node. This updates
196 /// or replaces metadata if already present, or removes it if Node is null.
197 void setMetadata(unsigned KindID, MDNode *Node);
198 void setMetadata(StringRef Kind, MDNode *Node);
200 /// Drop all unknown metadata except for debug locations.
202 /// Passes are required to drop metadata they don't understand. This is a
203 /// convenience method for passes to do so.
204 void dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs);
205 void dropUnknownNonDebugMetadata() {
206 return dropUnknownNonDebugMetadata(None);
208 void dropUnknownNonDebugMetadata(unsigned ID1) {
209 return dropUnknownNonDebugMetadata(makeArrayRef(ID1));
211 void dropUnknownNonDebugMetadata(unsigned ID1, unsigned ID2) {
212 unsigned IDs[] = {ID1, ID2};
213 return dropUnknownNonDebugMetadata(IDs);
217 /// Sets the metadata on this instruction from the AAMDNodes structure.
218 void setAAMetadata(const AAMDNodes &N);
220 /// Retrieve the raw weight values of a conditional branch or select.
221 /// Returns true on success with profile weights filled in.
222 /// Returns false if no metadata or invalid metadata was found.
223 bool extractProfMetadata(uint64_t &TrueVal, uint64_t &FalseVal);
225 /// Retrieve total raw weight values of a branch.
226 /// Returns true on success with profile total weights filled in.
227 /// Returns false if no metadata was found.
228 bool extractProfTotalWeight(uint64_t &TotalVal);
230 /// Set the debug location information for this instruction.
231 void setDebugLoc(DebugLoc Loc) { DbgLoc = std::move(Loc); }
233 /// Return the debug location for this node as a DebugLoc.
234 const DebugLoc &getDebugLoc() const { return DbgLoc; }
236 /// Set or clear the nsw flag on this instruction, which must be an operator
237 /// which supports this flag. See LangRef.html for the meaning of this flag.
238 void setHasNoUnsignedWrap(bool b = true);
240 /// Set or clear the nsw flag on this instruction, which must be an operator
241 /// which supports this flag. See LangRef.html for the meaning of this flag.
242 void setHasNoSignedWrap(bool b = true);
244 /// Set or clear the exact flag on this instruction, which must be an operator
245 /// which supports this flag. See LangRef.html for the meaning of this flag.
246 void setIsExact(bool b = true);
248 /// Determine whether the no unsigned wrap flag is set.
249 bool hasNoUnsignedWrap() const;
251 /// Determine whether the no signed wrap flag is set.
252 bool hasNoSignedWrap() const;
254 /// Determine whether the exact flag is set.
255 bool isExact() const;
257 /// Set or clear the unsafe-algebra flag on this instruction, which must be an
258 /// operator which supports this flag. See LangRef.html for the meaning of
260 void setHasUnsafeAlgebra(bool B);
262 /// Set or clear the no-nans flag on this instruction, which must be an
263 /// operator which supports this flag. See LangRef.html for the meaning of
265 void setHasNoNaNs(bool B);
267 /// Set or clear the no-infs flag on this instruction, which must be an
268 /// operator which supports this flag. See LangRef.html for the meaning of
270 void setHasNoInfs(bool B);
272 /// Set or clear the no-signed-zeros flag on this instruction, which must be
273 /// an operator which supports this flag. See LangRef.html for the meaning of
275 void setHasNoSignedZeros(bool B);
277 /// Set or clear the allow-reciprocal flag on this instruction, which must be
278 /// an operator which supports this flag. See LangRef.html for the meaning of
280 void setHasAllowReciprocal(bool B);
282 /// Convenience function for setting multiple fast-math flags on this
283 /// instruction, which must be an operator which supports these flags. See
284 /// LangRef.html for the meaning of these flags.
285 void setFastMathFlags(FastMathFlags FMF);
287 /// Convenience function for transferring all fast-math flag values to this
288 /// instruction, which must be an operator which supports these flags. See
289 /// LangRef.html for the meaning of these flags.
290 void copyFastMathFlags(FastMathFlags FMF);
292 /// Determine whether the unsafe-algebra flag is set.
293 bool hasUnsafeAlgebra() const;
295 /// Determine whether the no-NaNs flag is set.
296 bool hasNoNaNs() const;
298 /// Determine whether the no-infs flag is set.
299 bool hasNoInfs() const;
301 /// Determine whether the no-signed-zeros flag is set.
302 bool hasNoSignedZeros() const;
304 /// Determine whether the allow-reciprocal flag is set.
305 bool hasAllowReciprocal() const;
307 /// Convenience function for getting all the fast-math flags, which must be an
308 /// operator which supports these flags. See LangRef.html for the meaning of
310 FastMathFlags getFastMathFlags() const;
312 /// Copy I's fast-math flags
313 void copyFastMathFlags(const Instruction *I);
315 /// Convenience method to copy supported wrapping, exact, and fast-math flags
316 /// from V to this instruction.
317 void copyIRFlags(const Value *V);
319 /// Logical 'and' of any supported wrapping, exact, and fast-math flags of
320 /// V and this instruction.
321 void andIRFlags(const Value *V);
324 /// Return true if we have an entry in the on-the-side metadata hash.
325 bool hasMetadataHashEntry() const {
326 return (getSubclassDataFromValue() & HasMetadataBit) != 0;
329 // These are all implemented in Metadata.cpp.
330 MDNode *getMetadataImpl(unsigned KindID) const;
331 MDNode *getMetadataImpl(StringRef Kind) const;
333 getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
334 void getAllMetadataOtherThanDebugLocImpl(
335 SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
336 /// Clear all hashtable-based metadata from this instruction.
337 void clearMetadataHashEntries();
339 //===--------------------------------------------------------------------===//
340 // Predicates and helper methods.
341 //===--------------------------------------------------------------------===//
344 /// Return true if the instruction is associative:
346 /// Associative operators satisfy: x op (y op z) === (x op y) op z
348 /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
350 bool isAssociative() const;
351 static bool isAssociative(unsigned op);
353 /// Return true if the instruction is commutative:
355 /// Commutative operators satisfy: (x op y) === (y op x)
357 /// In LLVM, these are the associative operators, plus SetEQ and SetNE, when
358 /// applied to any type.
360 bool isCommutative() const { return isCommutative(getOpcode()); }
361 static bool isCommutative(unsigned op);
363 /// Return true if the instruction is idempotent:
365 /// Idempotent operators satisfy: x op x === x
367 /// In LLVM, the And and Or operators are idempotent.
369 bool isIdempotent() const { return isIdempotent(getOpcode()); }
370 static bool isIdempotent(unsigned op);
372 /// Return true if the instruction is nilpotent:
374 /// Nilpotent operators satisfy: x op x === Id,
376 /// where Id is the identity for the operator, i.e. a constant such that
377 /// x op Id === x and Id op x === x for all x.
379 /// In LLVM, the Xor operator is nilpotent.
381 bool isNilpotent() const { return isNilpotent(getOpcode()); }
382 static bool isNilpotent(unsigned op);
384 /// Return true if this instruction may modify memory.
385 bool mayWriteToMemory() const;
387 /// Return true if this instruction may read memory.
388 bool mayReadFromMemory() const;
390 /// Return true if this instruction may read or write memory.
391 bool mayReadOrWriteMemory() const {
392 return mayReadFromMemory() || mayWriteToMemory();
395 /// Return true if this instruction has an AtomicOrdering of unordered or
397 bool isAtomic() const;
399 /// Return true if this instruction may throw an exception.
400 bool mayThrow() const;
402 /// Return true if this instruction behaves like a memory fence: it can load
403 /// or store to memory location without being given a memory location.
404 bool isFenceLike() const {
405 switch (getOpcode()) {
408 // This list should be kept in sync with the list in mayWriteToMemory for
409 // all opcodes which don't have a memory location.
410 case Instruction::Fence:
411 case Instruction::CatchPad:
412 case Instruction::CatchRet:
413 case Instruction::Call:
414 case Instruction::Invoke:
419 /// Return true if the instruction may have side effects.
421 /// Note that this does not consider malloc and alloca to have side
422 /// effects because the newly allocated memory is completely invisible to
423 /// instructions which don't use the returned value. For cases where this
424 /// matters, isSafeToSpeculativelyExecute may be more appropriate.
425 bool mayHaveSideEffects() const { return mayWriteToMemory() || mayThrow(); }
427 /// Return true if the instruction is a variety of EH-block.
428 bool isEHPad() const {
429 switch (getOpcode()) {
430 case Instruction::CatchSwitch:
431 case Instruction::CatchPad:
432 case Instruction::CleanupPad:
433 case Instruction::LandingPad:
440 /// Create a copy of 'this' instruction that is identical in all ways except
442 /// * The instruction has no parent
443 /// * The instruction has no name
445 Instruction *clone() const;
447 /// Return true if the specified instruction is exactly identical to the
448 /// current one. This means that all operands match and any extra information
449 /// (e.g. load is volatile) agree.
450 bool isIdenticalTo(const Instruction *I) const;
452 /// This is like isIdenticalTo, except that it ignores the
453 /// SubclassOptionalData flags, which specify conditions under which the
454 /// instruction's result is undefined.
455 bool isIdenticalToWhenDefined(const Instruction *I) const;
457 /// When checking for operation equivalence (using isSameOperationAs) it is
458 /// sometimes useful to ignore certain attributes.
459 enum OperationEquivalenceFlags {
460 /// Check for equivalence ignoring load/store alignment.
461 CompareIgnoringAlignment = 1<<0,
462 /// Check for equivalence treating a type and a vector of that type
464 CompareUsingScalarTypes = 1<<1
467 /// This function determines if the specified instruction executes the same
468 /// operation as the current one. This means that the opcodes, type, operand
469 /// types and any other factors affecting the operation must be the same. This
470 /// is similar to isIdenticalTo except the operands themselves don't have to
472 /// @returns true if the specified instruction is the same operation as
474 /// @brief Determine if one instruction is the same operation as another.
475 bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const;
477 /// Return true if there are any uses of this instruction in blocks other than
478 /// the specified block. Note that PHI nodes are considered to evaluate their
479 /// operands in the corresponding predecessor block.
480 bool isUsedOutsideOfBlock(const BasicBlock *BB) const;
483 /// Methods for support type inquiry through isa, cast, and dyn_cast:
484 static inline bool classof(const Value *V) {
485 return V->getValueID() >= Value::InstructionVal;
488 //----------------------------------------------------------------------
489 // Exported enumerations.
491 enum TermOps { // These terminate basic blocks
492 #define FIRST_TERM_INST(N) TermOpsBegin = N,
493 #define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N,
494 #define LAST_TERM_INST(N) TermOpsEnd = N+1
495 #include "llvm/IR/Instruction.def"
499 #define FIRST_BINARY_INST(N) BinaryOpsBegin = N,
500 #define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N,
501 #define LAST_BINARY_INST(N) BinaryOpsEnd = N+1
502 #include "llvm/IR/Instruction.def"
506 #define FIRST_MEMORY_INST(N) MemoryOpsBegin = N,
507 #define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N,
508 #define LAST_MEMORY_INST(N) MemoryOpsEnd = N+1
509 #include "llvm/IR/Instruction.def"
513 #define FIRST_CAST_INST(N) CastOpsBegin = N,
514 #define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N,
515 #define LAST_CAST_INST(N) CastOpsEnd = N+1
516 #include "llvm/IR/Instruction.def"
520 #define FIRST_FUNCLETPAD_INST(N) FuncletPadOpsBegin = N,
521 #define HANDLE_FUNCLETPAD_INST(N, OPC, CLASS) OPC = N,
522 #define LAST_FUNCLETPAD_INST(N) FuncletPadOpsEnd = N+1
523 #include "llvm/IR/Instruction.def"
527 #define FIRST_OTHER_INST(N) OtherOpsBegin = N,
528 #define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N,
529 #define LAST_OTHER_INST(N) OtherOpsEnd = N+1
530 #include "llvm/IR/Instruction.def"
533 // Shadow Value::setValueSubclassData with a private forwarding method so that
534 // subclasses cannot accidentally use it.
535 void setValueSubclassData(unsigned short D) {
536 Value::setValueSubclassData(D);
538 unsigned short getSubclassDataFromValue() const {
539 return Value::getSubclassDataFromValue();
542 void setHasMetadataHashEntry(bool V) {
543 setValueSubclassData((getSubclassDataFromValue() & ~HasMetadataBit) |
544 (V ? HasMetadataBit : 0));
547 friend class SymbolTableListTraits<Instruction>;
548 void setParent(BasicBlock *P);
550 // Instruction subclasses can stick up to 15 bits of stuff into the
551 // SubclassData field of instruction with these members.
553 // Verify that only the low 15 bits are used.
554 void setInstructionSubclassData(unsigned short D) {
555 assert((D & HasMetadataBit) == 0 && "Out of range value put into field");
556 setValueSubclassData((getSubclassDataFromValue() & HasMetadataBit) | D);
559 unsigned getSubclassDataFromInstruction() const {
560 return getSubclassDataFromValue() & ~HasMetadataBit;
563 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
564 Instruction *InsertBefore = nullptr);
565 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
566 BasicBlock *InsertAtEnd);
569 /// Create a copy of this instruction.
570 Instruction *cloneImpl() const;
573 // Instruction* is only 4-byte aligned.
575 class PointerLikeTypeTraits<Instruction*> {
576 typedef Instruction* PT;
578 static inline void *getAsVoidPointer(PT P) { return P; }
579 static inline PT getFromVoidPointer(void *P) {
580 return static_cast<PT>(P);
582 enum { NumLowBitsAvailable = 2 };
585 } // End llvm namespace