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 MDNode *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 MDNode *getMetadata(StringRef Kind) const {
152 if (!hasMetadata()) return nullptr;
153 return getMetadataImpl(Kind);
156 /// getAllMetadata - Get all metadata attached to this Instruction. The first
157 /// element of each pair returned is the KindID, the second element is the
158 /// metadata value. This list is returned sorted by the KindID.
159 void getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode*> > &MDs)const{
161 getAllMetadataImpl(MDs);
164 /// getAllMetadataOtherThanDebugLoc - This does the same thing as
165 /// getAllMetadata, except that it filters out the debug location.
166 void getAllMetadataOtherThanDebugLoc(SmallVectorImpl<std::pair<unsigned,
167 MDNode*> > &MDs) const {
168 if (hasMetadataOtherThanDebugLoc())
169 getAllMetadataOtherThanDebugLocImpl(MDs);
172 /// getAAMetadata - Fills the AAMDNodes structure with AA metadata from
173 /// this instruction. When Merge is true, the existing AA metadata is
174 /// merged with that from this instruction providing the most-general result.
175 void getAAMetadata(AAMDNodes &N, bool Merge = false) const;
177 /// setMetadata - Set the metadata of the specified kind to the specified
178 /// node. This updates/replaces metadata if already present, or removes it if
180 void setMetadata(unsigned KindID, MDNode *Node);
181 void setMetadata(StringRef Kind, MDNode *Node);
183 /// \brief Drop unknown metadata.
184 /// Passes are required to drop metadata they don't understand. This is a
185 /// convenience method for passes to do so.
186 void dropUnknownMetadata(ArrayRef<unsigned> KnownIDs);
187 void dropUnknownMetadata() {
188 return dropUnknownMetadata(None);
190 void dropUnknownMetadata(unsigned ID1) {
191 return dropUnknownMetadata(makeArrayRef(ID1));
193 void dropUnknownMetadata(unsigned ID1, unsigned ID2) {
194 unsigned IDs[] = {ID1, ID2};
195 return dropUnknownMetadata(IDs);
198 /// setAAMetadata - Sets the metadata on this instruction from the
199 /// AAMDNodes structure.
200 void setAAMetadata(const AAMDNodes &N);
202 /// setDebugLoc - Set the debug location information for this instruction.
203 void setDebugLoc(const DebugLoc &Loc) { DbgLoc = Loc; }
205 /// getDebugLoc - Return the debug location for this node as a DebugLoc.
206 const DebugLoc &getDebugLoc() const { return DbgLoc; }
208 /// Set or clear the unsafe-algebra flag on this instruction, which must be an
209 /// operator which supports this flag. See LangRef.html for the meaning of
211 void setHasUnsafeAlgebra(bool B);
213 /// Set or clear the no-nans flag on this instruction, which must be an
214 /// operator which supports this flag. See LangRef.html for the meaning of
216 void setHasNoNaNs(bool B);
218 /// Set or clear the no-infs flag on this instruction, which must be an
219 /// operator which supports this flag. See LangRef.html for the meaning of
221 void setHasNoInfs(bool B);
223 /// Set or clear the no-signed-zeros flag on this instruction, which must be
224 /// an operator which supports this flag. See LangRef.html for the meaning of
226 void setHasNoSignedZeros(bool B);
228 /// Set or clear the allow-reciprocal flag on this instruction, which must be
229 /// an operator which supports this flag. See LangRef.html for the meaning of
231 void setHasAllowReciprocal(bool B);
233 /// Convenience function for setting multiple fast-math flags on this
234 /// instruction, which must be an operator which supports these flags. See
235 /// LangRef.html for the meaning of these flags.
236 void setFastMathFlags(FastMathFlags FMF);
238 /// Convenience function for transferring all fast-math flag values to this
239 /// instruction, which must be an operator which supports these flags. See
240 /// LangRef.html for the meaning of these flags.
241 void copyFastMathFlags(FastMathFlags FMF);
243 /// Determine whether the unsafe-algebra flag is set.
244 bool hasUnsafeAlgebra() const;
246 /// Determine whether the no-NaNs flag is set.
247 bool hasNoNaNs() const;
249 /// Determine whether the no-infs flag is set.
250 bool hasNoInfs() const;
252 /// Determine whether the no-signed-zeros flag is set.
253 bool hasNoSignedZeros() const;
255 /// Determine whether the allow-reciprocal flag is set.
256 bool hasAllowReciprocal() const;
258 /// Convenience function for getting all the fast-math flags, which must be an
259 /// operator which supports these flags. See LangRef.html for the meaning of
261 FastMathFlags getFastMathFlags() const;
263 /// Copy I's fast-math flags
264 void copyFastMathFlags(const Instruction *I);
267 /// hasMetadataHashEntry - Return true if we have an entry in the on-the-side
269 bool hasMetadataHashEntry() const {
270 return (getSubclassDataFromValue() & HasMetadataBit) != 0;
273 // These are all implemented in Metadata.cpp.
274 MDNode *getMetadataImpl(unsigned KindID) const;
275 MDNode *getMetadataImpl(StringRef Kind) const;
276 void getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned,MDNode*> > &)const;
277 void getAllMetadataOtherThanDebugLocImpl(SmallVectorImpl<std::pair<unsigned,
279 void clearMetadataHashEntries();
281 //===--------------------------------------------------------------------===//
282 // Predicates and helper methods.
283 //===--------------------------------------------------------------------===//
286 /// isAssociative - Return true if the instruction is associative:
288 /// Associative operators satisfy: x op (y op z) === (x op y) op z
290 /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
292 bool isAssociative() const;
293 static bool isAssociative(unsigned op);
295 /// isCommutative - Return true if the instruction is commutative:
297 /// Commutative operators satisfy: (x op y) === (y op x)
299 /// In LLVM, these are the associative operators, plus SetEQ and SetNE, when
300 /// applied to any type.
302 bool isCommutative() const { return isCommutative(getOpcode()); }
303 static bool isCommutative(unsigned op);
305 /// isIdempotent - Return true if the instruction is idempotent:
307 /// Idempotent operators satisfy: x op x === x
309 /// In LLVM, the And and Or operators are idempotent.
311 bool isIdempotent() const { return isIdempotent(getOpcode()); }
312 static bool isIdempotent(unsigned op);
314 /// isNilpotent - Return true if the instruction is nilpotent:
316 /// Nilpotent operators satisfy: x op x === Id,
318 /// where Id is the identity for the operator, i.e. a constant such that
319 /// x op Id === x and Id op x === x for all x.
321 /// In LLVM, the Xor operator is nilpotent.
323 bool isNilpotent() const { return isNilpotent(getOpcode()); }
324 static bool isNilpotent(unsigned op);
326 /// mayWriteToMemory - Return true if this instruction may modify memory.
328 bool mayWriteToMemory() const;
330 /// mayReadFromMemory - Return true if this instruction may read memory.
332 bool mayReadFromMemory() const;
334 /// mayReadOrWriteMemory - Return true if this instruction may read or
337 bool mayReadOrWriteMemory() const {
338 return mayReadFromMemory() || mayWriteToMemory();
341 /// isAtomic - Return true if this instruction has an
342 /// AtomicOrdering of unordered or higher.
344 bool isAtomic() const;
346 /// mayThrow - Return true if this instruction may throw an exception.
348 bool mayThrow() const;
350 /// mayReturn - Return true if this is a function that may return.
351 /// this is true for all normal instructions. The only exception
352 /// is functions that are marked with the 'noreturn' attribute.
354 bool mayReturn() const;
356 /// mayHaveSideEffects - Return true if the instruction may have side effects.
358 /// Note that this does not consider malloc and alloca to have side
359 /// effects because the newly allocated memory is completely invisible to
360 /// instructions which don't used the returned value. For cases where this
361 /// matters, isSafeToSpeculativelyExecute may be more appropriate.
362 bool mayHaveSideEffects() const {
363 return mayWriteToMemory() || mayThrow() || !mayReturn();
366 /// clone() - Create a copy of 'this' instruction that is identical in all
367 /// ways except the following:
368 /// * The instruction has no parent
369 /// * The instruction has no name
371 Instruction *clone() const;
373 /// isIdenticalTo - Return true if the specified instruction is exactly
374 /// identical to the current one. This means that all operands match and any
375 /// extra information (e.g. load is volatile) agree.
376 bool isIdenticalTo(const Instruction *I) const;
378 /// isIdenticalToWhenDefined - This is like isIdenticalTo, except that it
379 /// ignores the SubclassOptionalData flags, which specify conditions
380 /// under which the instruction's result is undefined.
381 bool isIdenticalToWhenDefined(const Instruction *I) const;
383 /// When checking for operation equivalence (using isSameOperationAs) it is
384 /// sometimes useful to ignore certain attributes.
385 enum OperationEquivalenceFlags {
386 /// Check for equivalence ignoring load/store alignment.
387 CompareIgnoringAlignment = 1<<0,
388 /// Check for equivalence treating a type and a vector of that type
390 CompareUsingScalarTypes = 1<<1
393 /// This function determines if the specified instruction executes the same
394 /// operation as the current one. This means that the opcodes, type, operand
395 /// types and any other factors affecting the operation must be the same. This
396 /// is similar to isIdenticalTo except the operands themselves don't have to
398 /// @returns true if the specified instruction is the same operation as
400 /// @brief Determine if one instruction is the same operation as another.
401 bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const;
403 /// isUsedOutsideOfBlock - Return true if there are any uses of this
404 /// instruction in blocks other than the specified block. Note that PHI nodes
405 /// are considered to evaluate their operands in the corresponding predecessor
407 bool isUsedOutsideOfBlock(const BasicBlock *BB) const;
410 /// Methods for support type inquiry through isa, cast, and dyn_cast:
411 static inline bool classof(const Value *V) {
412 return V->getValueID() >= Value::InstructionVal;
415 //----------------------------------------------------------------------
416 // Exported enumerations.
418 enum TermOps { // These terminate basic blocks
419 #define FIRST_TERM_INST(N) TermOpsBegin = N,
420 #define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N,
421 #define LAST_TERM_INST(N) TermOpsEnd = N+1
422 #include "llvm/IR/Instruction.def"
426 #define FIRST_BINARY_INST(N) BinaryOpsBegin = N,
427 #define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N,
428 #define LAST_BINARY_INST(N) BinaryOpsEnd = N+1
429 #include "llvm/IR/Instruction.def"
433 #define FIRST_MEMORY_INST(N) MemoryOpsBegin = N,
434 #define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N,
435 #define LAST_MEMORY_INST(N) MemoryOpsEnd = N+1
436 #include "llvm/IR/Instruction.def"
440 #define FIRST_CAST_INST(N) CastOpsBegin = N,
441 #define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N,
442 #define LAST_CAST_INST(N) CastOpsEnd = N+1
443 #include "llvm/IR/Instruction.def"
447 #define FIRST_OTHER_INST(N) OtherOpsBegin = N,
448 #define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N,
449 #define LAST_OTHER_INST(N) OtherOpsEnd = N+1
450 #include "llvm/IR/Instruction.def"
453 // Shadow Value::setValueSubclassData with a private forwarding method so that
454 // subclasses cannot accidentally use it.
455 void setValueSubclassData(unsigned short D) {
456 Value::setValueSubclassData(D);
458 unsigned short getSubclassDataFromValue() const {
459 return Value::getSubclassDataFromValue();
462 void setHasMetadataHashEntry(bool V) {
463 setValueSubclassData((getSubclassDataFromValue() & ~HasMetadataBit) |
464 (V ? HasMetadataBit : 0));
467 friend class SymbolTableListTraits<Instruction, BasicBlock>;
468 void setParent(BasicBlock *P);
470 // Instruction subclasses can stick up to 15 bits of stuff into the
471 // SubclassData field of instruction with these members.
473 // Verify that only the low 15 bits are used.
474 void setInstructionSubclassData(unsigned short D) {
475 assert((D & HasMetadataBit) == 0 && "Out of range value put into field");
476 setValueSubclassData((getSubclassDataFromValue() & HasMetadataBit) | D);
479 unsigned getSubclassDataFromInstruction() const {
480 return getSubclassDataFromValue() & ~HasMetadataBit;
483 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
484 Instruction *InsertBefore = nullptr);
485 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
486 BasicBlock *InsertAtEnd);
487 virtual Instruction *clone_impl() const = 0;
491 // Instruction* is only 4-byte aligned.
493 class PointerLikeTypeTraits<Instruction*> {
494 typedef Instruction* PT;
496 static inline void *getAsVoidPointer(PT P) { return P; }
497 static inline PT getFromVoidPointer(void *P) {
498 return static_cast<PT>(P);
500 enum { NumLowBitsAvailable = 2 };
503 } // End llvm namespace