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/User.h"
30 template<typename ValueSubClass, typename ItemParentClass>
31 class SymbolTableListTraits;
33 class Instruction : public User, public ilist_node<Instruction> {
34 void operator=(const Instruction &) = delete;
35 Instruction(const Instruction &) = delete;
38 DebugLoc DbgLoc; // 'dbg' Metadata cache.
41 /// HasMetadataBit - This is a bit stored in the SubClassData field which
42 /// indicates whether 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.
49 /// user_back - Specialize the methods defined in Value, as we know that an
50 /// instruction 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 /// \brief 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;
64 /// removeFromParent - This method unlinks 'this' from the containing basic
65 /// block, but does not delete it.
67 void removeFromParent();
69 /// eraseFromParent - This method unlinks 'this' from the containing basic
70 /// block and deletes it.
72 void eraseFromParent();
74 /// insertBefore - Insert an unlinked instructions into a basic block
75 /// immediately before the specified instruction.
76 void insertBefore(Instruction *InsertPos);
78 /// insertAfter - Insert an unlinked instructions into a basic block
79 /// immediately after the specified instruction.
80 void insertAfter(Instruction *InsertPos);
82 /// moveBefore - Unlink this instruction from its current basic block and
83 /// insert it into the basic block that MovePos lives in, right before
85 void moveBefore(Instruction *MovePos);
87 //===--------------------------------------------------------------------===//
88 // Subclass classification.
89 //===--------------------------------------------------------------------===//
91 /// getOpcode() returns a member of one of the enums like Instruction::Add.
92 unsigned getOpcode() const { return getValueID() - InstructionVal; }
94 const char *getOpcodeName() const { return getOpcodeName(getOpcode()); }
95 bool isTerminator() const { return isTerminator(getOpcode()); }
96 bool isBinaryOp() const { return isBinaryOp(getOpcode()); }
97 bool isShift() { return isShift(getOpcode()); }
98 bool isCast() const { return isCast(getOpcode()); }
100 static const char* getOpcodeName(unsigned OpCode);
102 static inline bool isTerminator(unsigned OpCode) {
103 return OpCode >= TermOpsBegin && OpCode < TermOpsEnd;
106 static inline bool isBinaryOp(unsigned Opcode) {
107 return Opcode >= BinaryOpsBegin && Opcode < BinaryOpsEnd;
110 /// @brief Determine if the Opcode is one of the shift instructions.
111 static inline bool isShift(unsigned Opcode) {
112 return Opcode >= Shl && Opcode <= AShr;
115 /// isLogicalShift - Return true if this is a logical shift left or a logical
117 inline bool isLogicalShift() const {
118 return getOpcode() == Shl || getOpcode() == LShr;
121 /// isArithmeticShift - Return true if this is an arithmetic shift right.
122 inline bool isArithmeticShift() const {
123 return getOpcode() == AShr;
126 /// @brief Determine if the OpCode is one of the CastInst instructions.
127 static inline bool isCast(unsigned OpCode) {
128 return OpCode >= CastOpsBegin && OpCode < CastOpsEnd;
131 //===--------------------------------------------------------------------===//
132 // Metadata manipulation.
133 //===--------------------------------------------------------------------===//
135 /// hasMetadata() - Return true if this instruction has any metadata attached
137 bool hasMetadata() const { return DbgLoc || hasMetadataHashEntry(); }
139 /// hasMetadataOtherThanDebugLoc - Return true if this instruction has
140 /// metadata attached to it other than a debug location.
141 bool hasMetadataOtherThanDebugLoc() const {
142 return hasMetadataHashEntry();
145 /// getMetadata - Get the metadata of given kind attached to this Instruction.
146 /// If the metadata is not found then return null.
147 MDNode *getMetadata(unsigned KindID) const {
148 if (!hasMetadata()) return nullptr;
149 return getMetadataImpl(KindID);
152 /// getMetadata - Get the metadata of given kind attached to this Instruction.
153 /// If the metadata is not found then return null.
154 MDNode *getMetadata(StringRef Kind) const {
155 if (!hasMetadata()) return nullptr;
156 return getMetadataImpl(Kind);
159 /// getAllMetadata - Get all metadata attached to this Instruction. The first
160 /// element of each pair returned is the KindID, the second element is the
161 /// metadata value. This list is returned sorted by the KindID.
163 getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
165 getAllMetadataImpl(MDs);
168 /// getAllMetadataOtherThanDebugLoc - This does the same thing as
169 /// getAllMetadata, except that it filters out the debug location.
170 void getAllMetadataOtherThanDebugLoc(
171 SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
172 if (hasMetadataOtherThanDebugLoc())
173 getAllMetadataOtherThanDebugLocImpl(MDs);
176 /// getAAMetadata - Fills the AAMDNodes structure with AA metadata from
177 /// this instruction. When Merge is true, the existing AA metadata is
178 /// merged with that from this instruction providing the most-general result.
179 void getAAMetadata(AAMDNodes &N, bool Merge = false) const;
181 /// setMetadata - Set the metadata of the specified kind to the specified
182 /// node. This updates/replaces metadata if already present, or removes it if
184 void setMetadata(unsigned KindID, MDNode *Node);
185 void setMetadata(StringRef Kind, MDNode *Node);
187 /// \brief Drop unknown metadata.
188 /// Passes are required to drop metadata they don't understand. This is a
189 /// convenience method for passes to do so.
190 void dropUnknownMetadata(ArrayRef<unsigned> KnownIDs);
191 void dropUnknownMetadata() {
192 return dropUnknownMetadata(None);
194 void dropUnknownMetadata(unsigned ID1) {
195 return dropUnknownMetadata(makeArrayRef(ID1));
197 void dropUnknownMetadata(unsigned ID1, unsigned ID2) {
198 unsigned IDs[] = {ID1, ID2};
199 return dropUnknownMetadata(IDs);
202 /// setAAMetadata - Sets the metadata on this instruction from the
203 /// AAMDNodes structure.
204 void setAAMetadata(const AAMDNodes &N);
206 /// setDebugLoc - Set the debug location information for this instruction.
207 void setDebugLoc(DebugLoc Loc) { DbgLoc = std::move(Loc); }
209 /// getDebugLoc - Return the debug location for this node as a DebugLoc.
210 const DebugLoc &getDebugLoc() const { return DbgLoc; }
212 /// Set or clear the unsafe-algebra flag on this instruction, which must be an
213 /// operator which supports this flag. See LangRef.html for the meaning of
215 void setHasUnsafeAlgebra(bool B);
217 /// Set or clear the no-nans flag on this instruction, which must be an
218 /// operator which supports this flag. See LangRef.html for the meaning of
220 void setHasNoNaNs(bool B);
222 /// Set or clear the no-infs flag on this instruction, which must be an
223 /// operator which supports this flag. See LangRef.html for the meaning of
225 void setHasNoInfs(bool B);
227 /// Set or clear the no-signed-zeros flag on this instruction, which must be
228 /// an operator which supports this flag. See LangRef.html for the meaning of
230 void setHasNoSignedZeros(bool B);
232 /// Set or clear the allow-reciprocal flag on this instruction, which must be
233 /// an operator which supports this flag. See LangRef.html for the meaning of
235 void setHasAllowReciprocal(bool B);
237 /// Convenience function for setting multiple fast-math flags on this
238 /// instruction, which must be an operator which supports these flags. See
239 /// LangRef.html for the meaning of these flags.
240 void setFastMathFlags(FastMathFlags FMF);
242 /// Convenience function for transferring all fast-math flag values to this
243 /// instruction, which must be an operator which supports these flags. See
244 /// LangRef.html for the meaning of these flags.
245 void copyFastMathFlags(FastMathFlags FMF);
247 /// Determine whether the unsafe-algebra flag is set.
248 bool hasUnsafeAlgebra() const;
250 /// Determine whether the no-NaNs flag is set.
251 bool hasNoNaNs() const;
253 /// Determine whether the no-infs flag is set.
254 bool hasNoInfs() const;
256 /// Determine whether the no-signed-zeros flag is set.
257 bool hasNoSignedZeros() const;
259 /// Determine whether the allow-reciprocal flag is set.
260 bool hasAllowReciprocal() const;
262 /// Convenience function for getting all the fast-math flags, which must be an
263 /// operator which supports these flags. See LangRef.html for the meaning of
265 FastMathFlags getFastMathFlags() const;
267 /// Copy I's fast-math flags
268 void copyFastMathFlags(const Instruction *I);
271 /// hasMetadataHashEntry - Return true if we have an entry in the on-the-side
273 bool hasMetadataHashEntry() const {
274 return (getSubclassDataFromValue() & HasMetadataBit) != 0;
277 // These are all implemented in Metadata.cpp.
278 MDNode *getMetadataImpl(unsigned KindID) const;
279 MDNode *getMetadataImpl(StringRef Kind) const;
281 getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
282 void getAllMetadataOtherThanDebugLocImpl(
283 SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
284 void clearMetadataHashEntries();
286 //===--------------------------------------------------------------------===//
287 // Predicates and helper methods.
288 //===--------------------------------------------------------------------===//
291 /// isAssociative - Return true if the instruction is associative:
293 /// Associative operators satisfy: x op (y op z) === (x op y) op z
295 /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
297 bool isAssociative() const;
298 static bool isAssociative(unsigned op);
300 /// isCommutative - Return true if the instruction is commutative:
302 /// Commutative operators satisfy: (x op y) === (y op x)
304 /// In LLVM, these are the associative operators, plus SetEQ and SetNE, when
305 /// applied to any type.
307 bool isCommutative() const { return isCommutative(getOpcode()); }
308 static bool isCommutative(unsigned op);
310 /// isIdempotent - Return true if the instruction is idempotent:
312 /// Idempotent operators satisfy: x op x === x
314 /// In LLVM, the And and Or operators are idempotent.
316 bool isIdempotent() const { return isIdempotent(getOpcode()); }
317 static bool isIdempotent(unsigned op);
319 /// isNilpotent - Return true if the instruction is nilpotent:
321 /// Nilpotent operators satisfy: x op x === Id,
323 /// where Id is the identity for the operator, i.e. a constant such that
324 /// x op Id === x and Id op x === x for all x.
326 /// In LLVM, the Xor operator is nilpotent.
328 bool isNilpotent() const { return isNilpotent(getOpcode()); }
329 static bool isNilpotent(unsigned op);
331 /// mayWriteToMemory - Return true if this instruction may modify memory.
333 bool mayWriteToMemory() const;
335 /// mayReadFromMemory - Return true if this instruction may read memory.
337 bool mayReadFromMemory() const;
339 /// mayReadOrWriteMemory - Return true if this instruction may read or
342 bool mayReadOrWriteMemory() const {
343 return mayReadFromMemory() || mayWriteToMemory();
346 /// isAtomic - Return true if this instruction has an
347 /// AtomicOrdering of unordered or higher.
349 bool isAtomic() const;
351 /// mayThrow - Return true if this instruction may throw an exception.
353 bool mayThrow() const;
355 /// mayReturn - Return true if this is a function that may return.
356 /// this is true for all normal instructions. The only exception
357 /// is functions that are marked with the 'noreturn' attribute.
359 bool mayReturn() const;
361 /// mayHaveSideEffects - Return true if the instruction may have side effects.
363 /// Note that this does not consider malloc and alloca to have side
364 /// effects because the newly allocated memory is completely invisible to
365 /// instructions which don't used the returned value. For cases where this
366 /// matters, isSafeToSpeculativelyExecute may be more appropriate.
367 bool mayHaveSideEffects() const {
368 return mayWriteToMemory() || mayThrow() || !mayReturn();
371 /// clone() - Create a copy of 'this' instruction that is identical in all
372 /// ways except the following:
373 /// * The instruction has no parent
374 /// * The instruction has no name
376 Instruction *clone() const;
378 /// isIdenticalTo - Return true if the specified instruction is exactly
379 /// identical to the current one. This means that all operands match and any
380 /// extra information (e.g. load is volatile) agree.
381 bool isIdenticalTo(const Instruction *I) const;
383 /// isIdenticalToWhenDefined - This is like isIdenticalTo, except that it
384 /// ignores the SubclassOptionalData flags, which specify conditions
385 /// under which the instruction's result is undefined.
386 bool isIdenticalToWhenDefined(const Instruction *I) const;
388 /// When checking for operation equivalence (using isSameOperationAs) it is
389 /// sometimes useful to ignore certain attributes.
390 enum OperationEquivalenceFlags {
391 /// Check for equivalence ignoring load/store alignment.
392 CompareIgnoringAlignment = 1<<0,
393 /// Check for equivalence treating a type and a vector of that type
395 CompareUsingScalarTypes = 1<<1
398 /// This function determines if the specified instruction executes the same
399 /// operation as the current one. This means that the opcodes, type, operand
400 /// types and any other factors affecting the operation must be the same. This
401 /// is similar to isIdenticalTo except the operands themselves don't have to
403 /// @returns true if the specified instruction is the same operation as
405 /// @brief Determine if one instruction is the same operation as another.
406 bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const;
408 /// isUsedOutsideOfBlock - Return true if there are any uses of this
409 /// instruction in blocks other than the specified block. Note that PHI nodes
410 /// are considered to evaluate their operands in the corresponding predecessor
412 bool isUsedOutsideOfBlock(const BasicBlock *BB) const;
415 /// Methods for support type inquiry through isa, cast, and dyn_cast:
416 static inline bool classof(const Value *V) {
417 return V->getValueID() >= Value::InstructionVal;
420 //----------------------------------------------------------------------
421 // Exported enumerations.
423 enum TermOps { // These terminate basic blocks
424 #define FIRST_TERM_INST(N) TermOpsBegin = N,
425 #define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N,
426 #define LAST_TERM_INST(N) TermOpsEnd = N+1
427 #include "llvm/IR/Instruction.def"
431 #define FIRST_BINARY_INST(N) BinaryOpsBegin = N,
432 #define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N,
433 #define LAST_BINARY_INST(N) BinaryOpsEnd = N+1
434 #include "llvm/IR/Instruction.def"
438 #define FIRST_MEMORY_INST(N) MemoryOpsBegin = N,
439 #define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N,
440 #define LAST_MEMORY_INST(N) MemoryOpsEnd = N+1
441 #include "llvm/IR/Instruction.def"
445 #define FIRST_CAST_INST(N) CastOpsBegin = N,
446 #define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N,
447 #define LAST_CAST_INST(N) CastOpsEnd = N+1
448 #include "llvm/IR/Instruction.def"
452 #define FIRST_OTHER_INST(N) OtherOpsBegin = N,
453 #define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N,
454 #define LAST_OTHER_INST(N) OtherOpsEnd = N+1
455 #include "llvm/IR/Instruction.def"
458 // Shadow Value::setValueSubclassData with a private forwarding method so that
459 // subclasses cannot accidentally use it.
460 void setValueSubclassData(unsigned short D) {
461 Value::setValueSubclassData(D);
463 unsigned short getSubclassDataFromValue() const {
464 return Value::getSubclassDataFromValue();
467 void setHasMetadataHashEntry(bool V) {
468 setValueSubclassData((getSubclassDataFromValue() & ~HasMetadataBit) |
469 (V ? HasMetadataBit : 0));
472 friend class SymbolTableListTraits<Instruction, BasicBlock>;
473 void setParent(BasicBlock *P);
475 // Instruction subclasses can stick up to 15 bits of stuff into the
476 // SubclassData field of instruction with these members.
478 // Verify that only the low 15 bits are used.
479 void setInstructionSubclassData(unsigned short D) {
480 assert((D & HasMetadataBit) == 0 && "Out of range value put into field");
481 setValueSubclassData((getSubclassDataFromValue() & HasMetadataBit) | D);
484 unsigned getSubclassDataFromInstruction() const {
485 return getSubclassDataFromValue() & ~HasMetadataBit;
488 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
489 Instruction *InsertBefore = nullptr);
490 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
491 BasicBlock *InsertAtEnd);
492 virtual Instruction *clone_impl() const = 0;
496 // Instruction* is only 4-byte aligned.
498 class PointerLikeTypeTraits<Instruction*> {
499 typedef Instruction* PT;
501 static inline void *getAsVoidPointer(PT P) { return P; }
502 static inline PT getFromVoidPointer(void *P) {
503 return static_cast<PT>(P);
505 enum { NumLowBitsAvailable = 2 };
508 } // End llvm namespace