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 ilist_traits<Instruction>
34 : public SymbolTableListTraits<Instruction, BasicBlock> {
36 /// \brief Return a node that marks the end of a list.
38 /// The sentinel is relative to this instance, so we use a non-static
40 Instruction *createSentinel() const;
41 static void destroySentinel(Instruction *) {}
43 Instruction *provideInitialHead() const { return createSentinel(); }
44 Instruction *ensureHead(Instruction *) const { return createSentinel(); }
45 static void noteHead(Instruction *, Instruction *) {}
48 mutable ilist_half_node<Instruction> Sentinel;
51 class Instruction : public User, public ilist_node<Instruction> {
52 void operator=(const Instruction &) = delete;
53 Instruction(const Instruction &) = delete;
56 DebugLoc DbgLoc; // 'dbg' Metadata cache.
59 /// HasMetadataBit - This is a bit stored in the SubClassData field which
60 /// indicates whether this instruction has metadata attached to it or not.
61 HasMetadataBit = 1 << 15
64 // Out of line virtual method, so the vtable, etc has a home.
65 ~Instruction() override;
67 /// user_back - Specialize the methods defined in Value, as we know that an
68 /// instruction can only be used by other instructions.
69 Instruction *user_back() { return cast<Instruction>(*user_begin());}
70 const Instruction *user_back() const { return cast<Instruction>(*user_begin());}
72 inline const BasicBlock *getParent() const { return Parent; }
73 inline BasicBlock *getParent() { return Parent; }
75 /// \brief Return the module owning the function this instruction belongs to
76 /// or nullptr it the function does not have a module.
78 /// Note: this is undefined behavior if the instruction does not have a
79 /// parent, or the parent basic block does not have a parent function.
80 const Module *getModule() const;
82 /// removeFromParent - This method unlinks 'this' from the containing basic
83 /// block, but does not delete it.
85 void removeFromParent();
87 /// eraseFromParent - This method unlinks 'this' from the containing basic
88 /// block and deletes it.
90 /// \returns an iterator pointing to the element after the erased one
91 iplist<Instruction>::iterator eraseFromParent();
93 /// Insert an unlinked instruction into a basic block immediately before
94 /// the specified instruction.
95 void insertBefore(Instruction *InsertPos);
97 /// Insert an unlinked instruction into a basic block immediately after the
98 /// specified instruction.
99 void insertAfter(Instruction *InsertPos);
101 /// moveBefore - Unlink this instruction from its current basic block and
102 /// insert it into the basic block that MovePos lives in, right before
104 void moveBefore(Instruction *MovePos);
106 //===--------------------------------------------------------------------===//
107 // Subclass classification.
108 //===--------------------------------------------------------------------===//
110 /// getOpcode() 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()); }
119 static const char* getOpcodeName(unsigned OpCode);
121 static inline bool isTerminator(unsigned OpCode) {
122 return OpCode >= TermOpsBegin && OpCode < TermOpsEnd;
125 static inline bool isBinaryOp(unsigned Opcode) {
126 return Opcode >= BinaryOpsBegin && Opcode < BinaryOpsEnd;
129 /// @brief Determine if the Opcode is one of the shift instructions.
130 static inline bool isShift(unsigned Opcode) {
131 return Opcode >= Shl && Opcode <= AShr;
134 /// isLogicalShift - Return true if this is a logical shift left or a logical
136 inline bool isLogicalShift() const {
137 return getOpcode() == Shl || getOpcode() == LShr;
140 /// isArithmeticShift - Return true if this is an arithmetic shift right.
141 inline bool isArithmeticShift() const {
142 return getOpcode() == AShr;
145 /// @brief Determine if the OpCode is one of the CastInst instructions.
146 static inline bool isCast(unsigned OpCode) {
147 return OpCode >= CastOpsBegin && OpCode < CastOpsEnd;
150 //===--------------------------------------------------------------------===//
151 // Metadata manipulation.
152 //===--------------------------------------------------------------------===//
154 /// hasMetadata() - Return true if this instruction has any metadata attached
156 bool hasMetadata() const { return DbgLoc || hasMetadataHashEntry(); }
158 /// hasMetadataOtherThanDebugLoc - Return true if this instruction has
159 /// metadata attached to it other than a debug location.
160 bool hasMetadataOtherThanDebugLoc() const {
161 return hasMetadataHashEntry();
164 /// getMetadata - Get the metadata of given kind attached to this Instruction.
165 /// If the metadata is not found then return null.
166 MDNode *getMetadata(unsigned KindID) const {
167 if (!hasMetadata()) return nullptr;
168 return getMetadataImpl(KindID);
171 /// getMetadata - Get the metadata of given kind attached to this Instruction.
172 /// If the metadata is not found then return null.
173 MDNode *getMetadata(StringRef Kind) const {
174 if (!hasMetadata()) return nullptr;
175 return getMetadataImpl(Kind);
178 /// getAllMetadata - Get all metadata attached to this Instruction. The first
179 /// element of each pair returned is the KindID, the second element is the
180 /// metadata value. This list is returned sorted by the KindID.
182 getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
184 getAllMetadataImpl(MDs);
187 /// getAllMetadataOtherThanDebugLoc - This does the same thing as
188 /// getAllMetadata, except that it filters out the debug location.
189 void getAllMetadataOtherThanDebugLoc(
190 SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
191 if (hasMetadataOtherThanDebugLoc())
192 getAllMetadataOtherThanDebugLocImpl(MDs);
195 /// getAAMetadata - Fills the AAMDNodes structure with AA metadata from
196 /// this instruction. When Merge is true, the existing AA metadata is
197 /// merged with that from this instruction providing the most-general result.
198 void getAAMetadata(AAMDNodes &N, bool Merge = false) const;
200 /// setMetadata - Set the metadata of the specified kind to the specified
201 /// node. This updates/replaces metadata if already present, or removes it if
203 void setMetadata(unsigned KindID, MDNode *Node);
204 void setMetadata(StringRef Kind, MDNode *Node);
206 /// \brief Drop unknown metadata.
207 /// Passes are required to drop metadata they don't understand. This is a
208 /// convenience method for passes to do so.
209 void dropUnknownMetadata(ArrayRef<unsigned> KnownIDs);
210 void dropUnknownMetadata() {
211 return dropUnknownMetadata(None);
213 void dropUnknownMetadata(unsigned ID1) {
214 return dropUnknownMetadata(makeArrayRef(ID1));
216 void dropUnknownMetadata(unsigned ID1, unsigned ID2) {
217 unsigned IDs[] = {ID1, ID2};
218 return dropUnknownMetadata(IDs);
221 /// setAAMetadata - Sets the metadata on this instruction from the
222 /// AAMDNodes structure.
223 void setAAMetadata(const AAMDNodes &N);
225 /// setDebugLoc - Set the debug location information for this instruction.
226 void setDebugLoc(DebugLoc Loc) { DbgLoc = std::move(Loc); }
228 /// getDebugLoc - Return the debug location for this node as a DebugLoc.
229 const DebugLoc &getDebugLoc() const { return DbgLoc; }
231 /// Set or clear the unsafe-algebra flag on this instruction, which must be an
232 /// operator which supports this flag. See LangRef.html for the meaning of
234 void setHasUnsafeAlgebra(bool B);
236 /// Set or clear the no-nans flag on this instruction, which must be an
237 /// operator which supports this flag. See LangRef.html for the meaning of
239 void setHasNoNaNs(bool B);
241 /// Set or clear the no-infs flag on this instruction, which must be an
242 /// operator which supports this flag. See LangRef.html for the meaning of
244 void setHasNoInfs(bool B);
246 /// Set or clear the no-signed-zeros flag on this instruction, which must be
247 /// an operator which supports this flag. See LangRef.html for the meaning of
249 void setHasNoSignedZeros(bool B);
251 /// Set or clear the allow-reciprocal flag on this instruction, which must be
252 /// an operator which supports this flag. See LangRef.html for the meaning of
254 void setHasAllowReciprocal(bool B);
256 /// Convenience function for setting multiple fast-math flags on this
257 /// instruction, which must be an operator which supports these flags. See
258 /// LangRef.html for the meaning of these flags.
259 void setFastMathFlags(FastMathFlags FMF);
261 /// Convenience function for transferring all fast-math flag values to this
262 /// instruction, which must be an operator which supports these flags. See
263 /// LangRef.html for the meaning of these flags.
264 void copyFastMathFlags(FastMathFlags FMF);
266 /// Determine whether the unsafe-algebra flag is set.
267 bool hasUnsafeAlgebra() const;
269 /// Determine whether the no-NaNs flag is set.
270 bool hasNoNaNs() const;
272 /// Determine whether the no-infs flag is set.
273 bool hasNoInfs() const;
275 /// Determine whether the no-signed-zeros flag is set.
276 bool hasNoSignedZeros() const;
278 /// Determine whether the allow-reciprocal flag is set.
279 bool hasAllowReciprocal() const;
281 /// Convenience function for getting all the fast-math flags, which must be an
282 /// operator which supports these flags. See LangRef.html for the meaning of
284 FastMathFlags getFastMathFlags() const;
286 /// Copy I's fast-math flags
287 void copyFastMathFlags(const Instruction *I);
290 /// hasMetadataHashEntry - Return true if we have an entry in the on-the-side
292 bool hasMetadataHashEntry() const {
293 return (getSubclassDataFromValue() & HasMetadataBit) != 0;
296 // These are all implemented in Metadata.cpp.
297 MDNode *getMetadataImpl(unsigned KindID) const;
298 MDNode *getMetadataImpl(StringRef Kind) const;
300 getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
301 void getAllMetadataOtherThanDebugLocImpl(
302 SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
303 void clearMetadataHashEntries();
305 //===--------------------------------------------------------------------===//
306 // Predicates and helper methods.
307 //===--------------------------------------------------------------------===//
310 /// isAssociative - Return true if the instruction is associative:
312 /// Associative operators satisfy: x op (y op z) === (x op y) op z
314 /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
316 bool isAssociative() const;
317 static bool isAssociative(unsigned op);
319 /// isCommutative - Return true if the instruction is commutative:
321 /// Commutative operators satisfy: (x op y) === (y op x)
323 /// In LLVM, these are the associative operators, plus SetEQ and SetNE, when
324 /// applied to any type.
326 bool isCommutative() const { return isCommutative(getOpcode()); }
327 static bool isCommutative(unsigned op);
329 /// isIdempotent - Return true if the instruction is idempotent:
331 /// Idempotent operators satisfy: x op x === x
333 /// In LLVM, the And and Or operators are idempotent.
335 bool isIdempotent() const { return isIdempotent(getOpcode()); }
336 static bool isIdempotent(unsigned op);
338 /// isNilpotent - Return true if the instruction is nilpotent:
340 /// Nilpotent operators satisfy: x op x === Id,
342 /// where Id is the identity for the operator, i.e. a constant such that
343 /// x op Id === x and Id op x === x for all x.
345 /// In LLVM, the Xor operator is nilpotent.
347 bool isNilpotent() const { return isNilpotent(getOpcode()); }
348 static bool isNilpotent(unsigned op);
350 /// mayWriteToMemory - Return true if this instruction may modify memory.
352 bool mayWriteToMemory() const;
354 /// mayReadFromMemory - Return true if this instruction may read memory.
356 bool mayReadFromMemory() const;
358 /// mayReadOrWriteMemory - Return true if this instruction may read or
361 bool mayReadOrWriteMemory() const {
362 return mayReadFromMemory() || mayWriteToMemory();
365 /// isAtomic - Return true if this instruction has an
366 /// AtomicOrdering of unordered or higher.
368 bool isAtomic() const;
370 /// mayThrow - Return true if this instruction may throw an exception.
372 bool mayThrow() const;
374 /// mayReturn - Return true if this is a function that may return.
375 /// this is true for all normal instructions. The only exception
376 /// is functions that are marked with the 'noreturn' attribute.
378 bool mayReturn() const;
380 /// mayHaveSideEffects - Return true if the instruction may have side effects.
382 /// Note that this does not consider malloc and alloca to have side
383 /// effects because the newly allocated memory is completely invisible to
384 /// instructions which don't used the returned value. For cases where this
385 /// matters, isSafeToSpeculativelyExecute may be more appropriate.
386 bool mayHaveSideEffects() const {
387 return mayWriteToMemory() || mayThrow() || !mayReturn();
390 /// clone() - Create a copy of 'this' instruction that is identical in all
391 /// ways except the following:
392 /// * The instruction has no parent
393 /// * The instruction has no name
395 Instruction *clone() const;
397 /// isIdenticalTo - Return true if the specified instruction is exactly
398 /// identical to the current one. This means that all operands match and any
399 /// extra information (e.g. load is volatile) agree.
400 bool isIdenticalTo(const Instruction *I) const;
402 /// isIdenticalToWhenDefined - This is like isIdenticalTo, except that it
403 /// ignores the SubclassOptionalData flags, which specify conditions
404 /// under which the instruction's result is undefined.
405 bool isIdenticalToWhenDefined(const Instruction *I) const;
407 /// When checking for operation equivalence (using isSameOperationAs) it is
408 /// sometimes useful to ignore certain attributes.
409 enum OperationEquivalenceFlags {
410 /// Check for equivalence ignoring load/store alignment.
411 CompareIgnoringAlignment = 1<<0,
412 /// Check for equivalence treating a type and a vector of that type
414 CompareUsingScalarTypes = 1<<1
417 /// This function determines if the specified instruction executes the same
418 /// operation as the current one. This means that the opcodes, type, operand
419 /// types and any other factors affecting the operation must be the same. This
420 /// is similar to isIdenticalTo except the operands themselves don't have to
422 /// @returns true if the specified instruction is the same operation as
424 /// @brief Determine if one instruction is the same operation as another.
425 bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const;
427 /// isUsedOutsideOfBlock - Return true if there are any uses of this
428 /// instruction in blocks other than the specified block. Note that PHI nodes
429 /// are considered to evaluate their operands in the corresponding predecessor
431 bool isUsedOutsideOfBlock(const BasicBlock *BB) const;
434 /// Methods for support type inquiry through isa, cast, and dyn_cast:
435 static inline bool classof(const Value *V) {
436 return V->getValueID() >= Value::InstructionVal;
439 //----------------------------------------------------------------------
440 // Exported enumerations.
442 enum TermOps { // These terminate basic blocks
443 #define FIRST_TERM_INST(N) TermOpsBegin = N,
444 #define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N,
445 #define LAST_TERM_INST(N) TermOpsEnd = N+1
446 #include "llvm/IR/Instruction.def"
450 #define FIRST_BINARY_INST(N) BinaryOpsBegin = N,
451 #define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N,
452 #define LAST_BINARY_INST(N) BinaryOpsEnd = N+1
453 #include "llvm/IR/Instruction.def"
457 #define FIRST_MEMORY_INST(N) MemoryOpsBegin = N,
458 #define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N,
459 #define LAST_MEMORY_INST(N) MemoryOpsEnd = N+1
460 #include "llvm/IR/Instruction.def"
464 #define FIRST_CAST_INST(N) CastOpsBegin = N,
465 #define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N,
466 #define LAST_CAST_INST(N) CastOpsEnd = N+1
467 #include "llvm/IR/Instruction.def"
471 #define FIRST_OTHER_INST(N) OtherOpsBegin = N,
472 #define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N,
473 #define LAST_OTHER_INST(N) OtherOpsEnd = N+1
474 #include "llvm/IR/Instruction.def"
477 // Shadow Value::setValueSubclassData with a private forwarding method so that
478 // subclasses cannot accidentally use it.
479 void setValueSubclassData(unsigned short D) {
480 Value::setValueSubclassData(D);
482 unsigned short getSubclassDataFromValue() const {
483 return Value::getSubclassDataFromValue();
486 void setHasMetadataHashEntry(bool V) {
487 setValueSubclassData((getSubclassDataFromValue() & ~HasMetadataBit) |
488 (V ? HasMetadataBit : 0));
491 friend class SymbolTableListTraits<Instruction, BasicBlock>;
492 void setParent(BasicBlock *P);
494 // Instruction subclasses can stick up to 15 bits of stuff into the
495 // SubclassData field of instruction with these members.
497 // Verify that only the low 15 bits are used.
498 void setInstructionSubclassData(unsigned short D) {
499 assert((D & HasMetadataBit) == 0 && "Out of range value put into field");
500 setValueSubclassData((getSubclassDataFromValue() & HasMetadataBit) | D);
503 unsigned getSubclassDataFromInstruction() const {
504 return getSubclassDataFromValue() & ~HasMetadataBit;
507 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
508 Instruction *InsertBefore = nullptr);
509 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
510 BasicBlock *InsertAtEnd);
511 virtual Instruction *clone_impl() const = 0;
515 inline Instruction *ilist_traits<Instruction>::createSentinel() const {
516 // Since i(p)lists always publicly derive from their corresponding traits,
517 // placing a data member in this class will augment the i(p)list. But since
518 // the NodeTy is expected to be publicly derive from ilist_node<NodeTy>,
519 // there is a legal viable downcast from it to NodeTy. We use this trick to
520 // superimpose an i(p)list with a "ghostly" NodeTy, which becomes the
521 // sentinel. Dereferencing the sentinel is forbidden (save the
522 // ilist_node<NodeTy>), so no one will ever notice the superposition.
523 return static_cast<Instruction *>(&Sentinel);
526 // Instruction* is only 4-byte aligned.
528 class PointerLikeTypeTraits<Instruction*> {
529 typedef Instruction* PT;
531 static inline void *getAsVoidPointer(PT P) { return P; }
532 static inline PT getFromVoidPointer(void *P) {
533 return static_cast<PT>(P);
535 enum { NumLowBitsAvailable = 2 };
538 } // End llvm namespace