Fix pr14893.
[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/ArrayRef.h"
19 #include "llvm/ADT/ilist_node.h"
20 #include "llvm/IR/User.h"
21 #include "llvm/Support/DebugLoc.h"
22
23 namespace llvm {
24
25 class FastMathFlags;
26 class LLVMContext;
27 class MDNode;
28
29 template<typename ValueSubClass, typename ItemParentClass>
30   class SymbolTableListTraits;
31
32 class Instruction : public User, public ilist_node<Instruction> {
33   void operator=(const Instruction &) LLVM_DELETED_FUNCTION;
34   Instruction(const Instruction &) LLVM_DELETED_FUNCTION;
35
36   BasicBlock *Parent;
37   DebugLoc DbgLoc;                         // 'dbg' Metadata cache.
38
39   enum {
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
43   };
44 public:
45   // Out of line virtual method, so the vtable, etc has a home.
46   ~Instruction();
47
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());}
52
53   inline const BasicBlock *getParent() const { return Parent; }
54   inline       BasicBlock *getParent()       { return Parent; }
55
56   /// removeFromParent - This method unlinks 'this' from the containing basic
57   /// block, but does not delete it.
58   ///
59   void removeFromParent();
60
61   /// eraseFromParent - This method unlinks 'this' from the containing basic
62   /// block and deletes it.
63   ///
64   void eraseFromParent();
65
66   /// insertBefore - Insert an unlinked instructions into a basic block
67   /// immediately before the specified instruction.
68   void insertBefore(Instruction *InsertPos);
69
70   /// insertAfter - Insert an unlinked instructions into a basic block
71   /// immediately after the specified instruction.
72   void insertAfter(Instruction *InsertPos);
73
74   /// moveBefore - Unlink this instruction from its current basic block and
75   /// insert it into the basic block that MovePos lives in, right before
76   /// MovePos.
77   void moveBefore(Instruction *MovePos);
78
79   //===--------------------------------------------------------------------===//
80   // Subclass classification.
81   //===--------------------------------------------------------------------===//
82
83   /// getOpcode() returns a member of one of the enums like Instruction::Add.
84   unsigned getOpcode() const { return getValueID() - InstructionVal; }
85
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()); }
91
92   static const char* getOpcodeName(unsigned OpCode);
93
94   static inline bool isTerminator(unsigned OpCode) {
95     return OpCode >= TermOpsBegin && OpCode < TermOpsEnd;
96   }
97
98   static inline bool isBinaryOp(unsigned Opcode) {
99     return Opcode >= BinaryOpsBegin && Opcode < BinaryOpsEnd;
100   }
101
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;
105   }
106
107   /// isLogicalShift - Return true if this is a logical shift left or a logical
108   /// shift right.
109   inline bool isLogicalShift() const {
110     return getOpcode() == Shl || getOpcode() == LShr;
111   }
112
113   /// isArithmeticShift - Return true if this is an arithmetic shift right.
114   inline bool isArithmeticShift() const {
115     return getOpcode() == AShr;
116   }
117
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;
121   }
122
123   //===--------------------------------------------------------------------===//
124   // Metadata manipulation.
125   //===--------------------------------------------------------------------===//
126
127   /// hasMetadata() - Return true if this instruction has any metadata attached
128   /// to it.
129   bool hasMetadata() const {
130     return !DbgLoc.isUnknown() || hasMetadataHashEntry();
131   }
132
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();
137   }
138
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);
144   }
145
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);
151   }
152
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{
157     if (hasMetadata())
158       getAllMetadataImpl(MDs);
159   }
160
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);
167   }
168
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
171   /// Node is null.
172   void setMetadata(unsigned KindID, MDNode *Node);
173   void setMetadata(StringRef Kind, MDNode *Node);
174
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>());
181   }
182   void dropUnknownMetadata(unsigned ID1) {
183     return dropUnknownMetadata(makeArrayRef(ID1));
184   }
185   void dropUnknownMetadata(unsigned ID1, unsigned ID2) {
186     unsigned IDs[] = {ID1, ID2};
187     return dropUnknownMetadata(IDs);
188   }
189
190   /// setDebugLoc - Set the debug location information for this instruction.
191   void setDebugLoc(const DebugLoc &Loc) { DbgLoc = Loc; }
192
193   /// getDebugLoc - Return the debug location for this node as a DebugLoc.
194   const DebugLoc &getDebugLoc() const { return DbgLoc; }
195
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
198   /// this flag.
199   void setHasUnsafeAlgebra(bool B);
200
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
203   /// this flag.
204   void setHasNoNaNs(bool B);
205
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
208   /// this flag.
209   void setHasNoInfs(bool B);
210
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
213   /// this flag.
214   void setHasNoSignedZeros(bool B);
215
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
218   /// this flag.
219   void setHasAllowReciprocal(bool B);
220
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);
225
226   /// Determine whether the unsafe-algebra flag is set.
227   bool hasUnsafeAlgebra() const;
228
229   /// Determine whether the no-NaNs flag is set.
230   bool hasNoNaNs() const;
231
232   /// Determine whether the no-infs flag is set.
233   bool hasNoInfs() const;
234
235   /// Determine whether the no-signed-zeros flag is set.
236   bool hasNoSignedZeros() const;
237
238   /// Determine whether the allow-reciprocal flag is set.
239   bool hasAllowReciprocal() const;
240
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
243   /// these flats.
244   FastMathFlags getFastMathFlags() const;
245
246   /// Copy I's fast-math flags
247   void copyFastMathFlags(const Instruction *I);
248
249 private:
250   /// hasMetadataHashEntry - Return true if we have an entry in the on-the-side
251   /// metadata hash.
252   bool hasMetadataHashEntry() const {
253     return (getSubclassDataFromValue() & HasMetadataBit) != 0;
254   }
255
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,
261                                            MDNode*> > &) const;
262   void clearMetadataHashEntries();
263 public:
264   //===--------------------------------------------------------------------===//
265   // Predicates and helper methods.
266   //===--------------------------------------------------------------------===//
267
268
269   /// isAssociative - Return true if the instruction is associative:
270   ///
271   ///   Associative operators satisfy:  x op (y op z) === (x op y) op z
272   ///
273   /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
274   ///
275   bool isAssociative() const;
276   static bool isAssociative(unsigned op);
277
278   /// isCommutative - Return true if the instruction is commutative:
279   ///
280   ///   Commutative operators satisfy: (x op y) === (y op x)
281   ///
282   /// In LLVM, these are the associative operators, plus SetEQ and SetNE, when
283   /// applied to any type.
284   ///
285   bool isCommutative() const { return isCommutative(getOpcode()); }
286   static bool isCommutative(unsigned op);
287
288   /// isIdempotent - Return true if the instruction is idempotent:
289   ///
290   ///   Idempotent operators satisfy:  x op x === x
291   ///
292   /// In LLVM, the And and Or operators are idempotent.
293   ///
294   bool isIdempotent() const { return isIdempotent(getOpcode()); }
295   static bool isIdempotent(unsigned op);
296
297   /// isNilpotent - Return true if the instruction is nilpotent:
298   ///
299   ///   Nilpotent operators satisfy:  x op x === Id,
300   ///
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.
303   ///
304   /// In LLVM, the Xor operator is nilpotent.
305   ///
306   bool isNilpotent() const { return isNilpotent(getOpcode()); }
307   static bool isNilpotent(unsigned op);
308
309   /// mayWriteToMemory - Return true if this instruction may modify memory.
310   ///
311   bool mayWriteToMemory() const;
312
313   /// mayReadFromMemory - Return true if this instruction may read memory.
314   ///
315   bool mayReadFromMemory() const;
316
317   /// mayReadOrWriteMemory - Return true if this instruction may read or
318   /// write memory.
319   ///
320   bool mayReadOrWriteMemory() const {
321     return mayReadFromMemory() || mayWriteToMemory();
322   }
323
324   /// mayThrow - Return true if this instruction may throw an exception.
325   ///
326   bool mayThrow() const;
327
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.
331   ///
332   bool mayReturn() const;
333
334   /// mayHaveSideEffects - Return true if the instruction may have side effects.
335   ///
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();
342   }
343
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
348   ///
349   Instruction *clone() const;
350
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;
355
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;
360
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
367     /// as equivalent.
368     CompareUsingScalarTypes = 1<<1
369   };
370
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
375   /// be identical.
376   /// @returns true if the specified instruction is the same operation as
377   /// the current one.
378   /// @brief Determine if one instruction is the same operation as another.
379   bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const;
380
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
384   /// block.
385   bool isUsedOutsideOfBlock(const BasicBlock *BB) const;
386
387
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;
391   }
392
393   //----------------------------------------------------------------------
394   // Exported enumerations.
395   //
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"
401   };
402
403   enum BinaryOps {
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"
408   };
409
410   enum MemoryOps {
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"
415   };
416
417   enum CastOps {
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"
422   };
423
424   enum OtherOps {
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"
429   };
430 private:
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);
435   }
436   unsigned short getSubclassDataFromValue() const {
437     return Value::getSubclassDataFromValue();
438   }
439
440   void setHasMetadataHashEntry(bool V) {
441     setValueSubclassData((getSubclassDataFromValue() & ~HasMetadataBit) |
442                          (V ? HasMetadataBit : 0));
443   }
444
445   friend class SymbolTableListTraits<Instruction, BasicBlock>;
446   void setParent(BasicBlock *P);
447 protected:
448   // Instruction subclasses can stick up to 15 bits of stuff into the
449   // SubclassData field of instruction with these members.
450
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);
455   }
456
457   unsigned getSubclassDataFromInstruction() const {
458     return getSubclassDataFromValue() & ~HasMetadataBit;
459   }
460
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;
466
467 };
468
469 // Instruction* is only 4-byte aligned.
470 template<>
471 class PointerLikeTypeTraits<Instruction*> {
472   typedef Instruction* PT;
473 public:
474   static inline void *getAsVoidPointer(PT P) { return P; }
475   static inline PT getFromVoidPointer(void *P) {
476     return static_cast<PT>(P);
477   }
478   enum { NumLowBitsAvailable = 2 };
479 };
480
481 } // End llvm namespace
482
483 #endif