• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===-- llvm/Instruction.h - Instruction class definition -------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the declaration of the Instruction class, which is the
11 // base class for all of the LLVM instructions.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #ifndef LLVM_INSTRUCTION_H
16 #define LLVM_INSTRUCTION_H
17 
18 #include "llvm/User.h"
19 #include "llvm/ADT/ilist_node.h"
20 #include "llvm/Support/DebugLoc.h"
21 
22 namespace llvm {
23 
24 class LLVMContext;
25 class MDNode;
26 
27 template<typename ValueSubClass, typename ItemParentClass>
28   class SymbolTableListTraits;
29 
30 class Instruction : public User, public ilist_node<Instruction> {
31   void operator=(const Instruction &);     // Do not implement
32   Instruction(const Instruction &);        // Do not implement
33 
34   BasicBlock *Parent;
35   DebugLoc DbgLoc;                         // 'dbg' Metadata cache.
36 
37   enum {
38     /// HasMetadataBit - This is a bit stored in the SubClassData field which
39     /// indicates whether this instruction has metadata attached to it or not.
40     HasMetadataBit = 1 << 15
41   };
42 public:
43   // Out of line virtual method, so the vtable, etc has a home.
44   ~Instruction();
45 
46   /// use_back - Specialize the methods defined in Value, as we know that an
47   /// instruction can only be used by other instructions.
use_back()48   Instruction       *use_back()       { return cast<Instruction>(*use_begin());}
use_back()49   const Instruction *use_back() const { return cast<Instruction>(*use_begin());}
50 
getParent()51   inline const BasicBlock *getParent() const { return Parent; }
getParent()52   inline       BasicBlock *getParent()       { return Parent; }
53 
54   /// removeFromParent - This method unlinks 'this' from the containing basic
55   /// block, but does not delete it.
56   ///
57   void removeFromParent();
58 
59   /// eraseFromParent - This method unlinks 'this' from the containing basic
60   /// block and deletes it.
61   ///
62   void eraseFromParent();
63 
64   /// insertBefore - Insert an unlinked instructions into a basic block
65   /// immediately before the specified instruction.
66   void insertBefore(Instruction *InsertPos);
67 
68   /// insertAfter - Insert an unlinked instructions into a basic block
69   /// immediately after the specified instruction.
70   void insertAfter(Instruction *InsertPos);
71 
72   /// moveBefore - Unlink this instruction from its current basic block and
73   /// insert it into the basic block that MovePos lives in, right before
74   /// MovePos.
75   void moveBefore(Instruction *MovePos);
76 
77   //===--------------------------------------------------------------------===//
78   // Subclass classification.
79   //===--------------------------------------------------------------------===//
80 
81   /// getOpcode() returns a member of one of the enums like Instruction::Add.
getOpcode()82   unsigned getOpcode() const { return getValueID() - InstructionVal; }
83 
getOpcodeName()84   const char *getOpcodeName() const { return getOpcodeName(getOpcode()); }
isTerminator()85   bool isTerminator() const { return isTerminator(getOpcode()); }
isBinaryOp()86   bool isBinaryOp() const { return isBinaryOp(getOpcode()); }
isShift()87   bool isShift() { return isShift(getOpcode()); }
isCast()88   bool isCast() const { return isCast(getOpcode()); }
89 
90   static const char* getOpcodeName(unsigned OpCode);
91 
isTerminator(unsigned OpCode)92   static inline bool isTerminator(unsigned OpCode) {
93     return OpCode >= TermOpsBegin && OpCode < TermOpsEnd;
94   }
95 
isBinaryOp(unsigned Opcode)96   static inline bool isBinaryOp(unsigned Opcode) {
97     return Opcode >= BinaryOpsBegin && Opcode < BinaryOpsEnd;
98   }
99 
100   /// @brief Determine if the Opcode is one of the shift instructions.
isShift(unsigned Opcode)101   static inline bool isShift(unsigned Opcode) {
102     return Opcode >= Shl && Opcode <= AShr;
103   }
104 
105   /// isLogicalShift - Return true if this is a logical shift left or a logical
106   /// shift right.
isLogicalShift()107   inline bool isLogicalShift() const {
108     return getOpcode() == Shl || getOpcode() == LShr;
109   }
110 
111   /// isArithmeticShift - Return true if this is an arithmetic shift right.
isArithmeticShift()112   inline bool isArithmeticShift() const {
113     return getOpcode() == AShr;
114   }
115 
116   /// @brief Determine if the OpCode is one of the CastInst instructions.
isCast(unsigned OpCode)117   static inline bool isCast(unsigned OpCode) {
118     return OpCode >= CastOpsBegin && OpCode < CastOpsEnd;
119   }
120 
121   //===--------------------------------------------------------------------===//
122   // Metadata manipulation.
123   //===--------------------------------------------------------------------===//
124 
125   /// hasMetadata() - Return true if this instruction has any metadata attached
126   /// to it.
hasMetadata()127   bool hasMetadata() const {
128     return !DbgLoc.isUnknown() || hasMetadataHashEntry();
129   }
130 
131   /// hasMetadataOtherThanDebugLoc - Return true if this instruction has
132   /// metadata attached to it other than a debug location.
hasMetadataOtherThanDebugLoc()133   bool hasMetadataOtherThanDebugLoc() const {
134     return hasMetadataHashEntry();
135   }
136 
137   /// getMetadata - Get the metadata of given kind attached to this Instruction.
138   /// If the metadata is not found then return null.
getMetadata(unsigned KindID)139   MDNode *getMetadata(unsigned KindID) const {
140     if (!hasMetadata()) return 0;
141     return getMetadataImpl(KindID);
142   }
143 
144   /// getMetadata - Get the metadata of given kind attached to this Instruction.
145   /// If the metadata is not found then return null.
getMetadata(StringRef Kind)146   MDNode *getMetadata(StringRef Kind) const {
147     if (!hasMetadata()) return 0;
148     return getMetadataImpl(Kind);
149   }
150 
151   /// getAllMetadata - Get all metadata attached to this Instruction.  The first
152   /// element of each pair returned is the KindID, the second element is the
153   /// metadata value.  This list is returned sorted by the KindID.
getAllMetadata(SmallVectorImpl<std::pair<unsigned,MDNode * >> & MDs)154   void getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode*> > &MDs)const{
155     if (hasMetadata())
156       getAllMetadataImpl(MDs);
157   }
158 
159   /// getAllMetadataOtherThanDebugLoc - This does the same thing as
160   /// getAllMetadata, except that it filters out the debug location.
getAllMetadataOtherThanDebugLoc(SmallVectorImpl<std::pair<unsigned,MDNode * >> & MDs)161   void getAllMetadataOtherThanDebugLoc(SmallVectorImpl<std::pair<unsigned,
162                                        MDNode*> > &MDs) const {
163     if (hasMetadataOtherThanDebugLoc())
164       getAllMetadataOtherThanDebugLocImpl(MDs);
165   }
166 
167   /// setMetadata - Set the metadata of the specified kind to the specified
168   /// node.  This updates/replaces metadata if already present, or removes it if
169   /// Node is null.
170   void setMetadata(unsigned KindID, MDNode *Node);
171   void setMetadata(StringRef Kind, MDNode *Node);
172 
173   /// setDebugLoc - Set the debug location information for this instruction.
setDebugLoc(const DebugLoc & Loc)174   void setDebugLoc(const DebugLoc &Loc) { DbgLoc = Loc; }
175 
176   /// getDebugLoc - Return the debug location for this node as a DebugLoc.
getDebugLoc()177   const DebugLoc &getDebugLoc() const { return DbgLoc; }
178 
179 private:
180   /// hasMetadataHashEntry - Return true if we have an entry in the on-the-side
181   /// metadata hash.
hasMetadataHashEntry()182   bool hasMetadataHashEntry() const {
183     return (getSubclassDataFromValue() & HasMetadataBit) != 0;
184   }
185 
186   // These are all implemented in Metadata.cpp.
187   MDNode *getMetadataImpl(unsigned KindID) const;
188   MDNode *getMetadataImpl(StringRef Kind) const;
189   void getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned,MDNode*> > &)const;
190   void getAllMetadataOtherThanDebugLocImpl(SmallVectorImpl<std::pair<unsigned,
191                                            MDNode*> > &) const;
192   void clearMetadataHashEntries();
193 public:
194   //===--------------------------------------------------------------------===//
195   // Predicates and helper methods.
196   //===--------------------------------------------------------------------===//
197 
198 
199   /// isAssociative - Return true if the instruction is associative:
200   ///
201   ///   Associative operators satisfy:  x op (y op z) === (x op y) op z
202   ///
203   /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
204   ///
isAssociative()205   bool isAssociative() const { return isAssociative(getOpcode()); }
206   static bool isAssociative(unsigned op);
207 
208   /// isCommutative - Return true if the instruction is commutative:
209   ///
210   ///   Commutative operators satisfy: (x op y) === (y op x)
211   ///
212   /// In LLVM, these are the associative operators, plus SetEQ and SetNE, when
213   /// applied to any type.
214   ///
isCommutative()215   bool isCommutative() const { return isCommutative(getOpcode()); }
216   static bool isCommutative(unsigned op);
217 
218   /// mayWriteToMemory - Return true if this instruction may modify memory.
219   ///
220   bool mayWriteToMemory() const;
221 
222   /// mayReadFromMemory - Return true if this instruction may read memory.
223   ///
224   bool mayReadFromMemory() const;
225 
226   /// mayReadOrWriteMemory - Return true if this instruction may read or
227   /// write memory.
228   ///
mayReadOrWriteMemory()229   bool mayReadOrWriteMemory() const {
230     return mayReadFromMemory() || mayWriteToMemory();
231   }
232 
233   /// mayThrow - Return true if this instruction may throw an exception.
234   ///
235   bool mayThrow() const;
236 
237   /// mayHaveSideEffects - Return true if the instruction may have side effects.
238   ///
239   /// Note that this does not consider malloc and alloca to have side
240   /// effects because the newly allocated memory is completely invisible to
241   /// instructions which don't used the returned value.  For cases where this
242   /// matters, isSafeToSpeculativelyExecute may be more appropriate.
mayHaveSideEffects()243   bool mayHaveSideEffects() const {
244     return mayWriteToMemory() || mayThrow();
245   }
246 
247   /// clone() - Create a copy of 'this' instruction that is identical in all
248   /// ways except the following:
249   ///   * The instruction has no parent
250   ///   * The instruction has no name
251   ///
252   Instruction *clone() const;
253 
254   /// isIdenticalTo - Return true if the specified instruction is exactly
255   /// identical to the current one.  This means that all operands match and any
256   /// extra information (e.g. load is volatile) agree.
257   bool isIdenticalTo(const Instruction *I) const;
258 
259   /// isIdenticalToWhenDefined - This is like isIdenticalTo, except that it
260   /// ignores the SubclassOptionalData flags, which specify conditions
261   /// under which the instruction's result is undefined.
262   bool isIdenticalToWhenDefined(const Instruction *I) const;
263 
264   /// This function determines if the specified instruction executes the same
265   /// operation as the current one. This means that the opcodes, type, operand
266   /// types and any other factors affecting the operation must be the same. This
267   /// is similar to isIdenticalTo except the operands themselves don't have to
268   /// be identical.
269   /// @returns true if the specified instruction is the same operation as
270   /// the current one.
271   /// @brief Determine if one instruction is the same operation as another.
272   bool isSameOperationAs(const Instruction *I) const;
273 
274   /// isUsedOutsideOfBlock - Return true if there are any uses of this
275   /// instruction in blocks other than the specified block.  Note that PHI nodes
276   /// are considered to evaluate their operands in the corresponding predecessor
277   /// block.
278   bool isUsedOutsideOfBlock(const BasicBlock *BB) const;
279 
280 
281   /// Methods for support type inquiry through isa, cast, and dyn_cast:
classof(const Instruction *)282   static inline bool classof(const Instruction *) { return true; }
classof(const Value * V)283   static inline bool classof(const Value *V) {
284     return V->getValueID() >= Value::InstructionVal;
285   }
286 
287   //----------------------------------------------------------------------
288   // Exported enumerations.
289   //
290   enum TermOps {       // These terminate basic blocks
291 #define  FIRST_TERM_INST(N)             TermOpsBegin = N,
292 #define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N,
293 #define   LAST_TERM_INST(N)             TermOpsEnd = N+1
294 #include "llvm/Instruction.def"
295   };
296 
297   enum BinaryOps {
298 #define  FIRST_BINARY_INST(N)             BinaryOpsBegin = N,
299 #define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N,
300 #define   LAST_BINARY_INST(N)             BinaryOpsEnd = N+1
301 #include "llvm/Instruction.def"
302   };
303 
304   enum MemoryOps {
305 #define  FIRST_MEMORY_INST(N)             MemoryOpsBegin = N,
306 #define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N,
307 #define   LAST_MEMORY_INST(N)             MemoryOpsEnd = N+1
308 #include "llvm/Instruction.def"
309   };
310 
311   enum CastOps {
312 #define  FIRST_CAST_INST(N)             CastOpsBegin = N,
313 #define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N,
314 #define   LAST_CAST_INST(N)             CastOpsEnd = N+1
315 #include "llvm/Instruction.def"
316   };
317 
318   enum OtherOps {
319 #define  FIRST_OTHER_INST(N)             OtherOpsBegin = N,
320 #define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N,
321 #define   LAST_OTHER_INST(N)             OtherOpsEnd = N+1
322 #include "llvm/Instruction.def"
323   };
324 private:
325   // Shadow Value::setValueSubclassData with a private forwarding method so that
326   // subclasses cannot accidentally use it.
setValueSubclassData(unsigned short D)327   void setValueSubclassData(unsigned short D) {
328     Value::setValueSubclassData(D);
329   }
getSubclassDataFromValue()330   unsigned short getSubclassDataFromValue() const {
331     return Value::getSubclassDataFromValue();
332   }
333 
setHasMetadataHashEntry(bool V)334   void setHasMetadataHashEntry(bool V) {
335     setValueSubclassData((getSubclassDataFromValue() & ~HasMetadataBit) |
336                          (V ? HasMetadataBit : 0));
337   }
338 
339   friend class SymbolTableListTraits<Instruction, BasicBlock>;
340   void setParent(BasicBlock *P);
341 protected:
342   // Instruction subclasses can stick up to 15 bits of stuff into the
343   // SubclassData field of instruction with these members.
344 
345   // Verify that only the low 15 bits are used.
setInstructionSubclassData(unsigned short D)346   void setInstructionSubclassData(unsigned short D) {
347     assert((D & HasMetadataBit) == 0 && "Out of range value put into field");
348     setValueSubclassData((getSubclassDataFromValue() & HasMetadataBit) | D);
349   }
350 
getSubclassDataFromInstruction()351   unsigned getSubclassDataFromInstruction() const {
352     return getSubclassDataFromValue() & ~HasMetadataBit;
353   }
354 
355   Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
356               Instruction *InsertBefore = 0);
357   Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
358               BasicBlock *InsertAtEnd);
359   virtual Instruction *clone_impl() const = 0;
360 
361 };
362 
363 // Instruction* is only 4-byte aligned.
364 template<>
365 class PointerLikeTypeTraits<Instruction*> {
366   typedef Instruction* PT;
367 public:
getAsVoidPointer(PT P)368   static inline void *getAsVoidPointer(PT P) { return P; }
getFromVoidPointer(void * P)369   static inline PT getFromVoidPointer(void *P) {
370     return static_cast<PT>(P);
371   }
372   enum { NumLowBitsAvailable = 2 };
373 };
374 
375 } // End llvm namespace
376 
377 #endif
378