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