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"
29 template<typename ValueSubClass, typename ItemParentClass>
30 class SymbolTableListTraits;
32 class Instruction : public User, public ilist_node<Instruction> {
33 void operator=(const Instruction &) LLVM_DELETED_FUNCTION;
34 Instruction(const Instruction &) LLVM_DELETED_FUNCTION;
37 DebugLoc DbgLoc; // 'dbg' Metadata cache.
40 /// HasMetadataBit - This is a bit stored in the SubClassData field which
41 /// indicates whether this instruction has metadata attached to it or not.
42 HasMetadataBit = 1 << 15
45 // Out of line virtual method, so the vtable, etc has a home.
48 /// user_back - Specialize the methods defined in Value, as we know that an
49 /// instruction can only be used by other instructions.
50 Instruction *user_back() { return cast<Instruction>(*user_begin());}
51 const Instruction *user_back() const { return cast<Instruction>(*user_begin());}
53 inline const BasicBlock *getParent() const { return Parent; }
54 inline BasicBlock *getParent() { return Parent; }
56 const DataLayout *getDataLayout() const;
58 /// removeFromParent - This method unlinks 'this' from the containing basic
59 /// block, but does not delete it.
61 void removeFromParent();
63 /// eraseFromParent - This method unlinks 'this' from the containing basic
64 /// block and deletes it.
66 void eraseFromParent();
68 /// insertBefore - Insert an unlinked instructions into a basic block
69 /// immediately before the specified instruction.
70 void insertBefore(Instruction *InsertPos);
72 /// insertAfter - Insert an unlinked instructions into a basic block
73 /// immediately after the specified instruction.
74 void insertAfter(Instruction *InsertPos);
76 /// moveBefore - Unlink this instruction from its current basic block and
77 /// insert it into the basic block that MovePos lives in, right before
79 void moveBefore(Instruction *MovePos);
81 //===--------------------------------------------------------------------===//
82 // Subclass classification.
83 //===--------------------------------------------------------------------===//
85 /// getOpcode() returns a member of one of the enums like Instruction::Add.
86 unsigned getOpcode() const { return getValueID() - InstructionVal; }
88 const char *getOpcodeName() const { return getOpcodeName(getOpcode()); }
89 bool isTerminator() const { return isTerminator(getOpcode()); }
90 bool isBinaryOp() const { return isBinaryOp(getOpcode()); }
91 bool isShift() { return isShift(getOpcode()); }
92 bool isCast() const { return isCast(getOpcode()); }
94 static const char* getOpcodeName(unsigned OpCode);
96 static inline bool isTerminator(unsigned OpCode) {
97 return OpCode >= TermOpsBegin && OpCode < TermOpsEnd;
100 static inline bool isBinaryOp(unsigned Opcode) {
101 return Opcode >= BinaryOpsBegin && Opcode < BinaryOpsEnd;
104 /// @brief Determine if the Opcode is one of the shift instructions.
105 static inline bool isShift(unsigned Opcode) {
106 return Opcode >= Shl && Opcode <= AShr;
109 /// isLogicalShift - Return true if this is a logical shift left or a logical
111 inline bool isLogicalShift() const {
112 return getOpcode() == Shl || getOpcode() == LShr;
115 /// isArithmeticShift - Return true if this is an arithmetic shift right.
116 inline bool isArithmeticShift() const {
117 return getOpcode() == AShr;
120 /// @brief Determine if the OpCode is one of the CastInst instructions.
121 static inline bool isCast(unsigned OpCode) {
122 return OpCode >= CastOpsBegin && OpCode < CastOpsEnd;
125 //===--------------------------------------------------------------------===//
126 // Metadata manipulation.
127 //===--------------------------------------------------------------------===//
129 /// hasMetadata() - Return true if this instruction has any metadata attached
131 bool hasMetadata() const {
132 return !DbgLoc.isUnknown() || hasMetadataHashEntry();
135 /// hasMetadataOtherThanDebugLoc - Return true if this instruction has
136 /// metadata attached to it other than a debug location.
137 bool hasMetadataOtherThanDebugLoc() const {
138 return hasMetadataHashEntry();
141 /// getMetadata - Get the metadata of given kind attached to this Instruction.
142 /// If the metadata is not found then return null.
143 MDNode *getMetadata(unsigned KindID) const {
144 if (!hasMetadata()) return 0;
145 return getMetadataImpl(KindID);
148 /// getMetadata - Get the metadata of given kind attached to this Instruction.
149 /// If the metadata is not found then return null.
150 MDNode *getMetadata(StringRef Kind) const {
151 if (!hasMetadata()) return 0;
152 return getMetadataImpl(Kind);
155 /// getAllMetadata - Get all metadata attached to this Instruction. The first
156 /// element of each pair returned is the KindID, the second element is the
157 /// metadata value. This list is returned sorted by the KindID.
158 void getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode*> > &MDs)const{
160 getAllMetadataImpl(MDs);
163 /// getAllMetadataOtherThanDebugLoc - This does the same thing as
164 /// getAllMetadata, except that it filters out the debug location.
165 void getAllMetadataOtherThanDebugLoc(SmallVectorImpl<std::pair<unsigned,
166 MDNode*> > &MDs) const {
167 if (hasMetadataOtherThanDebugLoc())
168 getAllMetadataOtherThanDebugLocImpl(MDs);
171 /// setMetadata - Set the metadata of the specified kind to the specified
172 /// node. This updates/replaces metadata if already present, or removes it if
174 void setMetadata(unsigned KindID, MDNode *Node);
175 void setMetadata(StringRef Kind, MDNode *Node);
177 /// \brief Drop unknown metadata.
178 /// Passes are required to drop metadata they don't understand. This is a
179 /// convenience method for passes to do so.
180 void dropUnknownMetadata(ArrayRef<unsigned> KnownIDs);
181 void dropUnknownMetadata() {
182 return dropUnknownMetadata(ArrayRef<unsigned>());
184 void dropUnknownMetadata(unsigned ID1) {
185 return dropUnknownMetadata(makeArrayRef(ID1));
187 void dropUnknownMetadata(unsigned ID1, unsigned ID2) {
188 unsigned IDs[] = {ID1, ID2};
189 return dropUnknownMetadata(IDs);
192 /// setDebugLoc - Set the debug location information for this instruction.
193 void setDebugLoc(const DebugLoc &Loc) { DbgLoc = Loc; }
195 /// getDebugLoc - Return the debug location for this node as a DebugLoc.
196 const DebugLoc &getDebugLoc() const { return DbgLoc; }
198 /// Set or clear the unsafe-algebra flag on this instruction, which must be an
199 /// operator which supports this flag. See LangRef.html for the meaning of
201 void setHasUnsafeAlgebra(bool B);
203 /// Set or clear the no-nans flag on this instruction, which must be an
204 /// operator which supports this flag. See LangRef.html for the meaning of
206 void setHasNoNaNs(bool B);
208 /// Set or clear the no-infs flag on this instruction, which must be an
209 /// operator which supports this flag. See LangRef.html for the meaning of
211 void setHasNoInfs(bool B);
213 /// Set or clear the no-signed-zeros flag on this instruction, which must be
214 /// an operator which supports this flag. See LangRef.html for the meaning of
216 void setHasNoSignedZeros(bool B);
218 /// Set or clear the allow-reciprocal flag on this instruction, which must be
219 /// an operator which supports this flag. See LangRef.html for the meaning of
221 void setHasAllowReciprocal(bool B);
223 /// Convenience function for setting all the fast-math flags on this
224 /// instruction, which must be an operator which supports these flags. See
225 /// LangRef.html for the meaning of these flats.
226 void setFastMathFlags(FastMathFlags FMF);
228 /// Determine whether the unsafe-algebra flag is set.
229 bool hasUnsafeAlgebra() const;
231 /// Determine whether the no-NaNs flag is set.
232 bool hasNoNaNs() const;
234 /// Determine whether the no-infs flag is set.
235 bool hasNoInfs() const;
237 /// Determine whether the no-signed-zeros flag is set.
238 bool hasNoSignedZeros() const;
240 /// Determine whether the allow-reciprocal flag is set.
241 bool hasAllowReciprocal() const;
243 /// Convenience function for getting all the fast-math flags, which must be an
244 /// operator which supports these flags. See LangRef.html for the meaning of
246 FastMathFlags getFastMathFlags() const;
248 /// Copy I's fast-math flags
249 void copyFastMathFlags(const Instruction *I);
252 /// hasMetadataHashEntry - Return true if we have an entry in the on-the-side
254 bool hasMetadataHashEntry() const {
255 return (getSubclassDataFromValue() & HasMetadataBit) != 0;
258 // These are all implemented in Metadata.cpp.
259 MDNode *getMetadataImpl(unsigned KindID) const;
260 MDNode *getMetadataImpl(StringRef Kind) const;
261 void getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned,MDNode*> > &)const;
262 void getAllMetadataOtherThanDebugLocImpl(SmallVectorImpl<std::pair<unsigned,
264 void clearMetadataHashEntries();
266 //===--------------------------------------------------------------------===//
267 // Predicates and helper methods.
268 //===--------------------------------------------------------------------===//
271 /// isAssociative - Return true if the instruction is associative:
273 /// Associative operators satisfy: x op (y op z) === (x op y) op z
275 /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
277 bool isAssociative() const;
278 static bool isAssociative(unsigned op);
280 /// isCommutative - Return true if the instruction is commutative:
282 /// Commutative operators satisfy: (x op y) === (y op x)
284 /// In LLVM, these are the associative operators, plus SetEQ and SetNE, when
285 /// applied to any type.
287 bool isCommutative() const { return isCommutative(getOpcode()); }
288 static bool isCommutative(unsigned op);
290 /// isIdempotent - Return true if the instruction is idempotent:
292 /// Idempotent operators satisfy: x op x === x
294 /// In LLVM, the And and Or operators are idempotent.
296 bool isIdempotent() const { return isIdempotent(getOpcode()); }
297 static bool isIdempotent(unsigned op);
299 /// isNilpotent - Return true if the instruction is nilpotent:
301 /// Nilpotent operators satisfy: x op x === Id,
303 /// where Id is the identity for the operator, i.e. a constant such that
304 /// x op Id === x and Id op x === x for all x.
306 /// In LLVM, the Xor operator is nilpotent.
308 bool isNilpotent() const { return isNilpotent(getOpcode()); }
309 static bool isNilpotent(unsigned op);
311 /// mayWriteToMemory - Return true if this instruction may modify memory.
313 bool mayWriteToMemory() const;
315 /// mayReadFromMemory - Return true if this instruction may read memory.
317 bool mayReadFromMemory() const;
319 /// mayReadOrWriteMemory - Return true if this instruction may read or
322 bool mayReadOrWriteMemory() const {
323 return mayReadFromMemory() || mayWriteToMemory();
326 /// mayThrow - Return true if this instruction may throw an exception.
328 bool mayThrow() const;
330 /// mayReturn - Return true if this is a function that may return.
331 /// this is true for all normal instructions. The only exception
332 /// is functions that are marked with the 'noreturn' attribute.
334 bool mayReturn() const;
336 /// mayHaveSideEffects - Return true if the instruction may have side effects.
338 /// Note that this does not consider malloc and alloca to have side
339 /// effects because the newly allocated memory is completely invisible to
340 /// instructions which don't used the returned value. For cases where this
341 /// matters, isSafeToSpeculativelyExecute may be more appropriate.
342 bool mayHaveSideEffects() const {
343 return mayWriteToMemory() || mayThrow() || !mayReturn();
346 /// clone() - Create a copy of 'this' instruction that is identical in all
347 /// ways except the following:
348 /// * The instruction has no parent
349 /// * The instruction has no name
351 Instruction *clone() const;
353 /// isIdenticalTo - Return true if the specified instruction is exactly
354 /// identical to the current one. This means that all operands match and any
355 /// extra information (e.g. load is volatile) agree.
356 bool isIdenticalTo(const Instruction *I) const;
358 /// isIdenticalToWhenDefined - This is like isIdenticalTo, except that it
359 /// ignores the SubclassOptionalData flags, which specify conditions
360 /// under which the instruction's result is undefined.
361 bool isIdenticalToWhenDefined(const Instruction *I) const;
363 /// When checking for operation equivalence (using isSameOperationAs) it is
364 /// sometimes useful to ignore certain attributes.
365 enum OperationEquivalenceFlags {
366 /// Check for equivalence ignoring load/store alignment.
367 CompareIgnoringAlignment = 1<<0,
368 /// Check for equivalence treating a type and a vector of that type
370 CompareUsingScalarTypes = 1<<1
373 /// This function determines if the specified instruction executes the same
374 /// operation as the current one. This means that the opcodes, type, operand
375 /// types and any other factors affecting the operation must be the same. This
376 /// is similar to isIdenticalTo except the operands themselves don't have to
378 /// @returns true if the specified instruction is the same operation as
380 /// @brief Determine if one instruction is the same operation as another.
381 bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const;
383 /// isUsedOutsideOfBlock - Return true if there are any uses of this
384 /// instruction in blocks other than the specified block. Note that PHI nodes
385 /// are considered to evaluate their operands in the corresponding predecessor
387 bool isUsedOutsideOfBlock(const BasicBlock *BB) const;
390 /// Methods for support type inquiry through isa, cast, and dyn_cast:
391 static inline bool classof(const Value *V) {
392 return V->getValueID() >= Value::InstructionVal;
395 //----------------------------------------------------------------------
396 // Exported enumerations.
398 enum TermOps { // These terminate basic blocks
399 #define FIRST_TERM_INST(N) TermOpsBegin = N,
400 #define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N,
401 #define LAST_TERM_INST(N) TermOpsEnd = N+1
402 #include "llvm/IR/Instruction.def"
406 #define FIRST_BINARY_INST(N) BinaryOpsBegin = N,
407 #define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N,
408 #define LAST_BINARY_INST(N) BinaryOpsEnd = N+1
409 #include "llvm/IR/Instruction.def"
413 #define FIRST_MEMORY_INST(N) MemoryOpsBegin = N,
414 #define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N,
415 #define LAST_MEMORY_INST(N) MemoryOpsEnd = N+1
416 #include "llvm/IR/Instruction.def"
420 #define FIRST_CAST_INST(N) CastOpsBegin = N,
421 #define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N,
422 #define LAST_CAST_INST(N) CastOpsEnd = N+1
423 #include "llvm/IR/Instruction.def"
427 #define FIRST_OTHER_INST(N) OtherOpsBegin = N,
428 #define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N,
429 #define LAST_OTHER_INST(N) OtherOpsEnd = N+1
430 #include "llvm/IR/Instruction.def"
433 // Shadow Value::setValueSubclassData with a private forwarding method so that
434 // subclasses cannot accidentally use it.
435 void setValueSubclassData(unsigned short D) {
436 Value::setValueSubclassData(D);
438 unsigned short getSubclassDataFromValue() const {
439 return Value::getSubclassDataFromValue();
442 void setHasMetadataHashEntry(bool V) {
443 setValueSubclassData((getSubclassDataFromValue() & ~HasMetadataBit) |
444 (V ? HasMetadataBit : 0));
447 friend class SymbolTableListTraits<Instruction, BasicBlock>;
448 void setParent(BasicBlock *P);
450 // Instruction subclasses can stick up to 15 bits of stuff into the
451 // SubclassData field of instruction with these members.
453 // Verify that only the low 15 bits are used.
454 void setInstructionSubclassData(unsigned short D) {
455 assert((D & HasMetadataBit) == 0 && "Out of range value put into field");
456 setValueSubclassData((getSubclassDataFromValue() & HasMetadataBit) | D);
459 unsigned getSubclassDataFromInstruction() const {
460 return getSubclassDataFromValue() & ~HasMetadataBit;
463 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
464 Instruction *InsertBefore = 0);
465 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
466 BasicBlock *InsertAtEnd);
467 virtual Instruction *clone_impl() const = 0;
471 // Instruction* is only 4-byte aligned.
473 class PointerLikeTypeTraits<Instruction*> {
474 typedef Instruction* PT;
476 static inline void *getAsVoidPointer(PT P) { return P; }
477 static inline PT getFromVoidPointer(void *P) {
478 return static_cast<PT>(P);
480 enum { NumLowBitsAvailable = 2 };
483 } // End llvm namespace