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/User.h"
21 #include "llvm/Support/DebugLoc.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 /// use_back - Specialize the methods defined in Value, as we know that an
49 /// instruction can only be used by other instructions.
50 Instruction *use_back() { return cast<Instruction>(*use_begin());}
51 const Instruction *use_back() const { return cast<Instruction>(*use_begin());}
53 inline const BasicBlock *getParent() const { return Parent; }
54 inline BasicBlock *getParent() { return Parent; }
56 /// removeFromParent - This method unlinks 'this' from the containing basic
57 /// block, but does not delete it.
59 void removeFromParent();
61 /// eraseFromParent - This method unlinks 'this' from the containing basic
62 /// block and deletes it.
64 void eraseFromParent();
66 /// insertBefore - Insert an unlinked instructions into a basic block
67 /// immediately before the specified instruction.
68 void insertBefore(Instruction *InsertPos);
70 /// insertAfter - Insert an unlinked instructions into a basic block
71 /// immediately after the specified instruction.
72 void insertAfter(Instruction *InsertPos);
74 /// moveBefore - Unlink this instruction from its current basic block and
75 /// insert it into the basic block that MovePos lives in, right before
77 void moveBefore(Instruction *MovePos);
79 //===--------------------------------------------------------------------===//
80 // Subclass classification.
81 //===--------------------------------------------------------------------===//
83 /// getOpcode() returns a member of one of the enums like Instruction::Add.
84 unsigned getOpcode() const { return getValueID() - InstructionVal; }
86 const char *getOpcodeName() const { return getOpcodeName(getOpcode()); }
87 bool isTerminator() const { return isTerminator(getOpcode()); }
88 bool isBinaryOp() const { return isBinaryOp(getOpcode()); }
89 bool isShift() { return isShift(getOpcode()); }
90 bool isCast() const { return isCast(getOpcode()); }
92 static const char* getOpcodeName(unsigned OpCode);
94 static inline bool isTerminator(unsigned OpCode) {
95 return OpCode >= TermOpsBegin && OpCode < TermOpsEnd;
98 static inline bool isBinaryOp(unsigned Opcode) {
99 return Opcode >= BinaryOpsBegin && Opcode < BinaryOpsEnd;
102 /// @brief Determine if the Opcode is one of the shift instructions.
103 static inline bool isShift(unsigned Opcode) {
104 return Opcode >= Shl && Opcode <= AShr;
107 /// isLogicalShift - Return true if this is a logical shift left or a logical
109 inline bool isLogicalShift() const {
110 return getOpcode() == Shl || getOpcode() == LShr;
113 /// isArithmeticShift - Return true if this is an arithmetic shift right.
114 inline bool isArithmeticShift() const {
115 return getOpcode() == AShr;
118 /// @brief Determine if the OpCode is one of the CastInst instructions.
119 static inline bool isCast(unsigned OpCode) {
120 return OpCode >= CastOpsBegin && OpCode < CastOpsEnd;
123 //===--------------------------------------------------------------------===//
124 // Metadata manipulation.
125 //===--------------------------------------------------------------------===//
127 /// hasMetadata() - Return true if this instruction has any metadata attached
129 bool hasMetadata() const {
130 return !DbgLoc.isUnknown() || hasMetadataHashEntry();
133 /// hasMetadataOtherThanDebugLoc - Return true if this instruction has
134 /// metadata attached to it other than a debug location.
135 bool hasMetadataOtherThanDebugLoc() const {
136 return hasMetadataHashEntry();
139 /// getMetadata - Get the metadata of given kind attached to this Instruction.
140 /// If the metadata is not found then return null.
141 MDNode *getMetadata(unsigned KindID) const {
142 if (!hasMetadata()) return 0;
143 return getMetadataImpl(KindID);
146 /// getMetadata - Get the metadata of given kind attached to this Instruction.
147 /// If the metadata is not found then return null.
148 MDNode *getMetadata(StringRef Kind) const {
149 if (!hasMetadata()) return 0;
150 return getMetadataImpl(Kind);
153 /// getAllMetadata - Get all metadata attached to this Instruction. The first
154 /// element of each pair returned is the KindID, the second element is the
155 /// metadata value. This list is returned sorted by the KindID.
156 void getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode*> > &MDs)const{
158 getAllMetadataImpl(MDs);
161 /// getAllMetadataOtherThanDebugLoc - This does the same thing as
162 /// getAllMetadata, except that it filters out the debug location.
163 void getAllMetadataOtherThanDebugLoc(SmallVectorImpl<std::pair<unsigned,
164 MDNode*> > &MDs) const {
165 if (hasMetadataOtherThanDebugLoc())
166 getAllMetadataOtherThanDebugLocImpl(MDs);
169 /// setMetadata - Set the metadata of the specified kind to the specified
170 /// node. This updates/replaces metadata if already present, or removes it if
172 void setMetadata(unsigned KindID, MDNode *Node);
173 void setMetadata(StringRef Kind, MDNode *Node);
175 /// \brief Drop unknown metadata.
176 /// Passes are required to drop metadata they don't understand. This is a
177 /// convenience method for passes to do so.
178 void dropUnknownMetadata(ArrayRef<unsigned> KnownIDs);
179 void dropUnknownMetadata() {
180 return dropUnknownMetadata(ArrayRef<unsigned>());
182 void dropUnknownMetadata(unsigned ID1) {
183 return dropUnknownMetadata(makeArrayRef(ID1));
185 void dropUnknownMetadata(unsigned ID1, unsigned ID2) {
186 unsigned IDs[] = {ID1, ID2};
187 return dropUnknownMetadata(IDs);
190 /// setDebugLoc - Set the debug location information for this instruction.
191 void setDebugLoc(const DebugLoc &Loc) { DbgLoc = Loc; }
193 /// getDebugLoc - Return the debug location for this node as a DebugLoc.
194 const DebugLoc &getDebugLoc() const { return DbgLoc; }
196 /// Set or clear the unsafe-algebra flag on this instruction, which must be an
197 /// operator which supports this flag. See LangRef.html for the meaning of
199 void setHasUnsafeAlgebra(bool B);
201 /// Set or clear the no-nans flag on this instruction, which must be an
202 /// operator which supports this flag. See LangRef.html for the meaning of
204 void setHasNoNaNs(bool B);
206 /// Set or clear the no-infs flag on this instruction, which must be an
207 /// operator which supports this flag. See LangRef.html for the meaning of
209 void setHasNoInfs(bool B);
211 /// Set or clear the no-signed-zeros flag on this instruction, which must be
212 /// an operator which supports this flag. See LangRef.html for the meaning of
214 void setHasNoSignedZeros(bool B);
216 /// Set or clear the allow-reciprocal flag on this instruction, which must be
217 /// an operator which supports this flag. See LangRef.html for the meaning of
219 void setHasAllowReciprocal(bool B);
221 /// Convenience function for setting all the fast-math flags on this
222 /// instruction, which must be an operator which supports these flags. See
223 /// LangRef.html for the meaning of these flats.
224 void setFastMathFlags(FastMathFlags FMF);
226 /// Determine whether the unsafe-algebra flag is set.
227 bool hasUnsafeAlgebra() const;
229 /// Determine whether the no-NaNs flag is set.
230 bool hasNoNaNs() const;
232 /// Determine whether the no-infs flag is set.
233 bool hasNoInfs() const;
235 /// Determine whether the no-signed-zeros flag is set.
236 bool hasNoSignedZeros() const;
238 /// Determine whether the allow-reciprocal flag is set.
239 bool hasAllowReciprocal() const;
241 /// Convenience function for getting all the fast-math flags, which must be an
242 /// operator which supports these flags. See LangRef.html for the meaning of
244 FastMathFlags getFastMathFlags() const;
246 /// Copy I's fast-math flags
247 void copyFastMathFlags(const Instruction *I);
250 /// hasMetadataHashEntry - Return true if we have an entry in the on-the-side
252 bool hasMetadataHashEntry() const {
253 return (getSubclassDataFromValue() & HasMetadataBit) != 0;
256 // These are all implemented in Metadata.cpp.
257 MDNode *getMetadataImpl(unsigned KindID) const;
258 MDNode *getMetadataImpl(StringRef Kind) const;
259 void getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned,MDNode*> > &)const;
260 void getAllMetadataOtherThanDebugLocImpl(SmallVectorImpl<std::pair<unsigned,
262 void clearMetadataHashEntries();
264 //===--------------------------------------------------------------------===//
265 // Predicates and helper methods.
266 //===--------------------------------------------------------------------===//
269 /// isAssociative - Return true if the instruction is associative:
271 /// Associative operators satisfy: x op (y op z) === (x op y) op z
273 /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
275 bool isAssociative() const;
276 static bool isAssociative(unsigned op);
278 /// isCommutative - Return true if the instruction is commutative:
280 /// Commutative operators satisfy: (x op y) === (y op x)
282 /// In LLVM, these are the associative operators, plus SetEQ and SetNE, when
283 /// applied to any type.
285 bool isCommutative() const { return isCommutative(getOpcode()); }
286 static bool isCommutative(unsigned op);
288 /// isIdempotent - Return true if the instruction is idempotent:
290 /// Idempotent operators satisfy: x op x === x
292 /// In LLVM, the And and Or operators are idempotent.
294 bool isIdempotent() const { return isIdempotent(getOpcode()); }
295 static bool isIdempotent(unsigned op);
297 /// isNilpotent - Return true if the instruction is nilpotent:
299 /// Nilpotent operators satisfy: x op x === Id,
301 /// where Id is the identity for the operator, i.e. a constant such that
302 /// x op Id === x and Id op x === x for all x.
304 /// In LLVM, the Xor operator is nilpotent.
306 bool isNilpotent() const { return isNilpotent(getOpcode()); }
307 static bool isNilpotent(unsigned op);
309 /// mayWriteToMemory - Return true if this instruction may modify memory.
311 bool mayWriteToMemory() const;
313 /// mayReadFromMemory - Return true if this instruction may read memory.
315 bool mayReadFromMemory() const;
317 /// mayReadOrWriteMemory - Return true if this instruction may read or
320 bool mayReadOrWriteMemory() const {
321 return mayReadFromMemory() || mayWriteToMemory();
324 /// mayThrow - Return true if this instruction may throw an exception.
326 bool mayThrow() const;
328 /// mayReturn - Return true if this is a function that may return.
329 /// this is true for all normal instructions. The only exception
330 /// is functions that are marked with the 'noreturn' attribute.
332 bool mayReturn() const;
334 /// mayHaveSideEffects - Return true if the instruction may have side effects.
336 /// Note that this does not consider malloc and alloca to have side
337 /// effects because the newly allocated memory is completely invisible to
338 /// instructions which don't used the returned value. For cases where this
339 /// matters, isSafeToSpeculativelyExecute may be more appropriate.
340 bool mayHaveSideEffects() const {
341 return mayWriteToMemory() || mayThrow() || !mayReturn();
344 /// clone() - Create a copy of 'this' instruction that is identical in all
345 /// ways except the following:
346 /// * The instruction has no parent
347 /// * The instruction has no name
349 Instruction *clone() const;
351 /// isIdenticalTo - Return true if the specified instruction is exactly
352 /// identical to the current one. This means that all operands match and any
353 /// extra information (e.g. load is volatile) agree.
354 bool isIdenticalTo(const Instruction *I) const;
356 /// isIdenticalToWhenDefined - This is like isIdenticalTo, except that it
357 /// ignores the SubclassOptionalData flags, which specify conditions
358 /// under which the instruction's result is undefined.
359 bool isIdenticalToWhenDefined(const Instruction *I) const;
361 /// When checking for operation equivalence (using isSameOperationAs) it is
362 /// sometimes useful to ignore certain attributes.
363 enum OperationEquivalenceFlags {
364 /// Check for equivalence ignoring load/store alignment.
365 CompareIgnoringAlignment = 1<<0,
366 /// Check for equivalence treating a type and a vector of that type
368 CompareUsingScalarTypes = 1<<1
371 /// This function determines if the specified instruction executes the same
372 /// operation as the current one. This means that the opcodes, type, operand
373 /// types and any other factors affecting the operation must be the same. This
374 /// is similar to isIdenticalTo except the operands themselves don't have to
376 /// @returns true if the specified instruction is the same operation as
378 /// @brief Determine if one instruction is the same operation as another.
379 bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const;
381 /// isUsedOutsideOfBlock - Return true if there are any uses of this
382 /// instruction in blocks other than the specified block. Note that PHI nodes
383 /// are considered to evaluate their operands in the corresponding predecessor
385 bool isUsedOutsideOfBlock(const BasicBlock *BB) const;
388 /// Methods for support type inquiry through isa, cast, and dyn_cast:
389 static inline bool classof(const Value *V) {
390 return V->getValueID() >= Value::InstructionVal;
393 //----------------------------------------------------------------------
394 // Exported enumerations.
396 enum TermOps { // These terminate basic blocks
397 #define FIRST_TERM_INST(N) TermOpsBegin = N,
398 #define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N,
399 #define LAST_TERM_INST(N) TermOpsEnd = N+1
400 #include "llvm/IR/Instruction.def"
404 #define FIRST_BINARY_INST(N) BinaryOpsBegin = N,
405 #define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N,
406 #define LAST_BINARY_INST(N) BinaryOpsEnd = N+1
407 #include "llvm/IR/Instruction.def"
411 #define FIRST_MEMORY_INST(N) MemoryOpsBegin = N,
412 #define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N,
413 #define LAST_MEMORY_INST(N) MemoryOpsEnd = N+1
414 #include "llvm/IR/Instruction.def"
418 #define FIRST_CAST_INST(N) CastOpsBegin = N,
419 #define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N,
420 #define LAST_CAST_INST(N) CastOpsEnd = N+1
421 #include "llvm/IR/Instruction.def"
425 #define FIRST_OTHER_INST(N) OtherOpsBegin = N,
426 #define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N,
427 #define LAST_OTHER_INST(N) OtherOpsEnd = N+1
428 #include "llvm/IR/Instruction.def"
431 // Shadow Value::setValueSubclassData with a private forwarding method so that
432 // subclasses cannot accidentally use it.
433 void setValueSubclassData(unsigned short D) {
434 Value::setValueSubclassData(D);
436 unsigned short getSubclassDataFromValue() const {
437 return Value::getSubclassDataFromValue();
440 void setHasMetadataHashEntry(bool V) {
441 setValueSubclassData((getSubclassDataFromValue() & ~HasMetadataBit) |
442 (V ? HasMetadataBit : 0));
445 friend class SymbolTableListTraits<Instruction, BasicBlock>;
446 void setParent(BasicBlock *P);
448 // Instruction subclasses can stick up to 15 bits of stuff into the
449 // SubclassData field of instruction with these members.
451 // Verify that only the low 15 bits are used.
452 void setInstructionSubclassData(unsigned short D) {
453 assert((D & HasMetadataBit) == 0 && "Out of range value put into field");
454 setValueSubclassData((getSubclassDataFromValue() & HasMetadataBit) | D);
457 unsigned getSubclassDataFromInstruction() const {
458 return getSubclassDataFromValue() & ~HasMetadataBit;
461 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
462 Instruction *InsertBefore = 0);
463 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
464 BasicBlock *InsertAtEnd);
465 virtual Instruction *clone_impl() const = 0;
469 // Instruction* is only 4-byte aligned.
471 class PointerLikeTypeTraits<Instruction*> {
472 typedef Instruction* PT;
474 static inline void *getAsVoidPointer(PT P) { return P; }
475 static inline PT getFromVoidPointer(void *P) {
476 return static_cast<PT>(P);
478 enum { NumLowBitsAvailable = 2 };
481 } // End llvm namespace