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 &) LLVM_DELETED_FUNCTION;
35 Instruction(const Instruction &) LLVM_DELETED_FUNCTION;
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 const DataLayout *getDataLayout() const;
59 /// removeFromParent - This method unlinks 'this' from the containing basic
60 /// block, but does not delete it.
62 void removeFromParent();
64 /// eraseFromParent - This method unlinks 'this' from the containing basic
65 /// block and deletes it.
67 void eraseFromParent();
69 /// insertBefore - Insert an unlinked instructions into a basic block
70 /// immediately before the specified instruction.
71 void insertBefore(Instruction *InsertPos);
73 /// insertAfter - Insert an unlinked instructions into a basic block
74 /// immediately after the specified instruction.
75 void insertAfter(Instruction *InsertPos);
77 /// moveBefore - Unlink this instruction from its current basic block and
78 /// insert it into the basic block that MovePos lives in, right before
80 void moveBefore(Instruction *MovePos);
82 //===--------------------------------------------------------------------===//
83 // Subclass classification.
84 //===--------------------------------------------------------------------===//
86 /// getOpcode() returns a member of one of the enums like Instruction::Add.
87 unsigned getOpcode() const { return getValueID() - InstructionVal; }
89 const char *getOpcodeName() const { return getOpcodeName(getOpcode()); }
90 bool isTerminator() const { return isTerminator(getOpcode()); }
91 bool isBinaryOp() const { return isBinaryOp(getOpcode()); }
92 bool isShift() { return isShift(getOpcode()); }
93 bool isCast() const { return isCast(getOpcode()); }
95 static const char* getOpcodeName(unsigned OpCode);
97 static inline bool isTerminator(unsigned OpCode) {
98 return OpCode >= TermOpsBegin && OpCode < TermOpsEnd;
101 static inline bool isBinaryOp(unsigned Opcode) {
102 return Opcode >= BinaryOpsBegin && Opcode < BinaryOpsEnd;
105 /// @brief Determine if the Opcode is one of the shift instructions.
106 static inline bool isShift(unsigned Opcode) {
107 return Opcode >= Shl && Opcode <= AShr;
110 /// isLogicalShift - Return true if this is a logical shift left or a logical
112 inline bool isLogicalShift() const {
113 return getOpcode() == Shl || getOpcode() == LShr;
116 /// isArithmeticShift - Return true if this is an arithmetic shift right.
117 inline bool isArithmeticShift() const {
118 return getOpcode() == AShr;
121 /// @brief Determine if the OpCode is one of the CastInst instructions.
122 static inline bool isCast(unsigned OpCode) {
123 return OpCode >= CastOpsBegin && OpCode < CastOpsEnd;
126 //===--------------------------------------------------------------------===//
127 // Metadata manipulation.
128 //===--------------------------------------------------------------------===//
130 /// hasMetadata() - Return true if this instruction has any metadata attached
132 bool hasMetadata() const {
133 return !DbgLoc.isUnknown() || hasMetadataHashEntry();
136 /// hasMetadataOtherThanDebugLoc - Return true if this instruction has
137 /// metadata attached to it other than a debug location.
138 bool hasMetadataOtherThanDebugLoc() const {
139 return hasMetadataHashEntry();
142 /// getMetadata - Get the metadata of given kind attached to this Instruction.
143 /// If the metadata is not found then return null.
144 Value *getMetadata(unsigned KindID) const {
145 if (!hasMetadata()) return nullptr;
146 return getMetadataImpl(KindID);
149 /// getMetadata - Get the metadata of given kind attached to this Instruction.
150 /// If the metadata is not found then return null.
151 Value *getMetadata(StringRef Kind) const {
152 if (!hasMetadata()) return nullptr;
153 return getMetadataImpl(Kind);
156 /// Get the the metadata as an MDNode.
158 /// \pre Any KindID metadata is implemented using \a MDNode.
159 MDNode *getMDNode(unsigned KindID) const {
162 return getMDNodeImpl(KindID);
165 /// Get the the metadata as an MDNode.
167 /// \pre Any KindID metadata is implemented using \a MDNode.
168 MDNode *getMDNode(StringRef Kind) const {
171 return getMDNodeImpl(Kind);
174 /// getAllMetadata - Get all metadata attached to this Instruction. The first
175 /// element of each pair returned is the KindID, the second element is the
176 /// metadata value. This list is returned sorted by the KindID.
177 void getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode*> > &MDs)const{
179 getAllMetadataImpl(MDs);
182 /// getAllMetadataOtherThanDebugLoc - This does the same thing as
183 /// getAllMetadata, except that it filters out the debug location.
184 void getAllMetadataOtherThanDebugLoc(SmallVectorImpl<std::pair<unsigned,
185 MDNode*> > &MDs) const {
186 if (hasMetadataOtherThanDebugLoc())
187 getAllMetadataOtherThanDebugLocImpl(MDs);
190 /// getAAMetadata - Fills the AAMDNodes structure with AA metadata from
191 /// this instruction. When Merge is true, the existing AA metadata is
192 /// merged with that from this instruction providing the most-general result.
193 void getAAMetadata(AAMDNodes &N, bool Merge = false) const;
195 /// setMetadata - Set the metadata of the specified kind to the specified
196 /// node. This updates/replaces metadata if already present, or removes it if
198 void setMetadata(unsigned KindID, Value *MD);
199 void setMetadata(StringRef Kind, Value *MD);
201 /// \brief Drop unknown metadata.
202 /// Passes are required to drop metadata they don't understand. This is a
203 /// convenience method for passes to do so.
204 void dropUnknownMetadata(ArrayRef<unsigned> KnownIDs);
205 void dropUnknownMetadata() {
206 return dropUnknownMetadata(None);
208 void dropUnknownMetadata(unsigned ID1) {
209 return dropUnknownMetadata(makeArrayRef(ID1));
211 void dropUnknownMetadata(unsigned ID1, unsigned ID2) {
212 unsigned IDs[] = {ID1, ID2};
213 return dropUnknownMetadata(IDs);
216 /// setAAMetadata - Sets the metadata on this instruction from the
217 /// AAMDNodes structure.
218 void setAAMetadata(const AAMDNodes &N);
220 /// setDebugLoc - Set the debug location information for this instruction.
221 void setDebugLoc(const DebugLoc &Loc) { DbgLoc = Loc; }
223 /// getDebugLoc - Return the debug location for this node as a DebugLoc.
224 const DebugLoc &getDebugLoc() const { return DbgLoc; }
226 /// Set or clear the unsafe-algebra flag on this instruction, which must be an
227 /// operator which supports this flag. See LangRef.html for the meaning of
229 void setHasUnsafeAlgebra(bool B);
231 /// Set or clear the no-nans flag on this instruction, which must be an
232 /// operator which supports this flag. See LangRef.html for the meaning of
234 void setHasNoNaNs(bool B);
236 /// Set or clear the no-infs flag on this instruction, which must be an
237 /// operator which supports this flag. See LangRef.html for the meaning of
239 void setHasNoInfs(bool B);
241 /// Set or clear the no-signed-zeros flag on this instruction, which must be
242 /// an operator which supports this flag. See LangRef.html for the meaning of
244 void setHasNoSignedZeros(bool B);
246 /// Set or clear the allow-reciprocal flag on this instruction, which must be
247 /// an operator which supports this flag. See LangRef.html for the meaning of
249 void setHasAllowReciprocal(bool B);
251 /// Convenience function for setting multiple fast-math flags on this
252 /// instruction, which must be an operator which supports these flags. See
253 /// LangRef.html for the meaning of these flags.
254 void setFastMathFlags(FastMathFlags FMF);
256 /// Convenience function for transferring all fast-math flag values to this
257 /// instruction, which must be an operator which supports these flags. See
258 /// LangRef.html for the meaning of these flags.
259 void copyFastMathFlags(FastMathFlags FMF);
261 /// Determine whether the unsafe-algebra flag is set.
262 bool hasUnsafeAlgebra() const;
264 /// Determine whether the no-NaNs flag is set.
265 bool hasNoNaNs() const;
267 /// Determine whether the no-infs flag is set.
268 bool hasNoInfs() const;
270 /// Determine whether the no-signed-zeros flag is set.
271 bool hasNoSignedZeros() const;
273 /// Determine whether the allow-reciprocal flag is set.
274 bool hasAllowReciprocal() const;
276 /// Convenience function for getting all the fast-math flags, which must be an
277 /// operator which supports these flags. See LangRef.html for the meaning of
279 FastMathFlags getFastMathFlags() const;
281 /// Copy I's fast-math flags
282 void copyFastMathFlags(const Instruction *I);
285 /// hasMetadataHashEntry - Return true if we have an entry in the on-the-side
287 bool hasMetadataHashEntry() const {
288 return (getSubclassDataFromValue() & HasMetadataBit) != 0;
291 // These are all implemented in Metadata.cpp.
292 Value *getMetadataImpl(unsigned KindID) const;
293 Value *getMetadataImpl(StringRef Kind) const;
294 MDNode *getMDNodeImpl(unsigned KindID) const;
295 MDNode *getMDNodeImpl(StringRef Kind) const;
296 void getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned,MDNode*> > &)const;
297 void getAllMetadataOtherThanDebugLocImpl(SmallVectorImpl<std::pair<unsigned,
299 void clearMetadataHashEntries();
301 //===--------------------------------------------------------------------===//
302 // Predicates and helper methods.
303 //===--------------------------------------------------------------------===//
306 /// isAssociative - Return true if the instruction is associative:
308 /// Associative operators satisfy: x op (y op z) === (x op y) op z
310 /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
312 bool isAssociative() const;
313 static bool isAssociative(unsigned op);
315 /// isCommutative - Return true if the instruction is commutative:
317 /// Commutative operators satisfy: (x op y) === (y op x)
319 /// In LLVM, these are the associative operators, plus SetEQ and SetNE, when
320 /// applied to any type.
322 bool isCommutative() const { return isCommutative(getOpcode()); }
323 static bool isCommutative(unsigned op);
325 /// isIdempotent - Return true if the instruction is idempotent:
327 /// Idempotent operators satisfy: x op x === x
329 /// In LLVM, the And and Or operators are idempotent.
331 bool isIdempotent() const { return isIdempotent(getOpcode()); }
332 static bool isIdempotent(unsigned op);
334 /// isNilpotent - Return true if the instruction is nilpotent:
336 /// Nilpotent operators satisfy: x op x === Id,
338 /// where Id is the identity for the operator, i.e. a constant such that
339 /// x op Id === x and Id op x === x for all x.
341 /// In LLVM, the Xor operator is nilpotent.
343 bool isNilpotent() const { return isNilpotent(getOpcode()); }
344 static bool isNilpotent(unsigned op);
346 /// mayWriteToMemory - Return true if this instruction may modify memory.
348 bool mayWriteToMemory() const;
350 /// mayReadFromMemory - Return true if this instruction may read memory.
352 bool mayReadFromMemory() const;
354 /// mayReadOrWriteMemory - Return true if this instruction may read or
357 bool mayReadOrWriteMemory() const {
358 return mayReadFromMemory() || mayWriteToMemory();
361 /// isAtomic - Return true if this instruction has an
362 /// AtomicOrdering of unordered or higher.
364 bool isAtomic() const;
366 /// mayThrow - Return true if this instruction may throw an exception.
368 bool mayThrow() const;
370 /// mayReturn - Return true if this is a function that may return.
371 /// this is true for all normal instructions. The only exception
372 /// is functions that are marked with the 'noreturn' attribute.
374 bool mayReturn() const;
376 /// mayHaveSideEffects - Return true if the instruction may have side effects.
378 /// Note that this does not consider malloc and alloca to have side
379 /// effects because the newly allocated memory is completely invisible to
380 /// instructions which don't used the returned value. For cases where this
381 /// matters, isSafeToSpeculativelyExecute may be more appropriate.
382 bool mayHaveSideEffects() const {
383 return mayWriteToMemory() || mayThrow() || !mayReturn();
386 /// clone() - Create a copy of 'this' instruction that is identical in all
387 /// ways except the following:
388 /// * The instruction has no parent
389 /// * The instruction has no name
391 Instruction *clone() const;
393 /// isIdenticalTo - Return true if the specified instruction is exactly
394 /// identical to the current one. This means that all operands match and any
395 /// extra information (e.g. load is volatile) agree.
396 bool isIdenticalTo(const Instruction *I) const;
398 /// isIdenticalToWhenDefined - This is like isIdenticalTo, except that it
399 /// ignores the SubclassOptionalData flags, which specify conditions
400 /// under which the instruction's result is undefined.
401 bool isIdenticalToWhenDefined(const Instruction *I) const;
403 /// When checking for operation equivalence (using isSameOperationAs) it is
404 /// sometimes useful to ignore certain attributes.
405 enum OperationEquivalenceFlags {
406 /// Check for equivalence ignoring load/store alignment.
407 CompareIgnoringAlignment = 1<<0,
408 /// Check for equivalence treating a type and a vector of that type
410 CompareUsingScalarTypes = 1<<1
413 /// This function determines if the specified instruction executes the same
414 /// operation as the current one. This means that the opcodes, type, operand
415 /// types and any other factors affecting the operation must be the same. This
416 /// is similar to isIdenticalTo except the operands themselves don't have to
418 /// @returns true if the specified instruction is the same operation as
420 /// @brief Determine if one instruction is the same operation as another.
421 bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const;
423 /// isUsedOutsideOfBlock - Return true if there are any uses of this
424 /// instruction in blocks other than the specified block. Note that PHI nodes
425 /// are considered to evaluate their operands in the corresponding predecessor
427 bool isUsedOutsideOfBlock(const BasicBlock *BB) const;
430 /// Methods for support type inquiry through isa, cast, and dyn_cast:
431 static inline bool classof(const Value *V) {
432 return V->getValueID() >= Value::InstructionVal;
435 //----------------------------------------------------------------------
436 // Exported enumerations.
438 enum TermOps { // These terminate basic blocks
439 #define FIRST_TERM_INST(N) TermOpsBegin = N,
440 #define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N,
441 #define LAST_TERM_INST(N) TermOpsEnd = N+1
442 #include "llvm/IR/Instruction.def"
446 #define FIRST_BINARY_INST(N) BinaryOpsBegin = N,
447 #define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N,
448 #define LAST_BINARY_INST(N) BinaryOpsEnd = N+1
449 #include "llvm/IR/Instruction.def"
453 #define FIRST_MEMORY_INST(N) MemoryOpsBegin = N,
454 #define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N,
455 #define LAST_MEMORY_INST(N) MemoryOpsEnd = N+1
456 #include "llvm/IR/Instruction.def"
460 #define FIRST_CAST_INST(N) CastOpsBegin = N,
461 #define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N,
462 #define LAST_CAST_INST(N) CastOpsEnd = N+1
463 #include "llvm/IR/Instruction.def"
467 #define FIRST_OTHER_INST(N) OtherOpsBegin = N,
468 #define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N,
469 #define LAST_OTHER_INST(N) OtherOpsEnd = N+1
470 #include "llvm/IR/Instruction.def"
473 // Shadow Value::setValueSubclassData with a private forwarding method so that
474 // subclasses cannot accidentally use it.
475 void setValueSubclassData(unsigned short D) {
476 Value::setValueSubclassData(D);
478 unsigned short getSubclassDataFromValue() const {
479 return Value::getSubclassDataFromValue();
482 void setHasMetadataHashEntry(bool V) {
483 setValueSubclassData((getSubclassDataFromValue() & ~HasMetadataBit) |
484 (V ? HasMetadataBit : 0));
487 friend class SymbolTableListTraits<Instruction, BasicBlock>;
488 void setParent(BasicBlock *P);
490 // Instruction subclasses can stick up to 15 bits of stuff into the
491 // SubclassData field of instruction with these members.
493 // Verify that only the low 15 bits are used.
494 void setInstructionSubclassData(unsigned short D) {
495 assert((D & HasMetadataBit) == 0 && "Out of range value put into field");
496 setValueSubclassData((getSubclassDataFromValue() & HasMetadataBit) | D);
499 unsigned getSubclassDataFromInstruction() const {
500 return getSubclassDataFromValue() & ~HasMetadataBit;
503 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
504 Instruction *InsertBefore = nullptr);
505 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
506 BasicBlock *InsertAtEnd);
507 virtual Instruction *clone_impl() const = 0;
511 // Instruction* is only 4-byte aligned.
513 class PointerLikeTypeTraits<Instruction*> {
514 typedef Instruction* PT;
516 static inline void *getAsVoidPointer(PT P) { return P; }
517 static inline PT getFromVoidPointer(void *P) {
518 return static_cast<PT>(P);
520 enum { NumLowBitsAvailable = 2 };
523 } // End llvm namespace