Instruction::isAssociative() returns true for fmul/fadd if they are tagged "unsafe...
[oota-llvm.git] / include / llvm / 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_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 struct 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 private:
231   /// hasMetadataHashEntry - Return true if we have an entry in the on-the-side
232   /// metadata hash.
233   bool hasMetadataHashEntry() const {
234     return (getSubclassDataFromValue() & HasMetadataBit) != 0;
235   }
236
237   // These are all implemented in Metadata.cpp.
238   MDNode *getMetadataImpl(unsigned KindID) const;
239   MDNode *getMetadataImpl(StringRef Kind) const;
240   void getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned,MDNode*> > &)const;
241   void getAllMetadataOtherThanDebugLocImpl(SmallVectorImpl<std::pair<unsigned,
242                                            MDNode*> > &) const;
243   void clearMetadataHashEntries();
244 public:
245   //===--------------------------------------------------------------------===//
246   // Predicates and helper methods.
247   //===--------------------------------------------------------------------===//
248
249
250   /// isAssociative - Return true if the instruction is associative:
251   ///
252   ///   Associative operators satisfy:  x op (y op z) === (x op y) op z
253   ///
254   /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
255   ///
256   bool isAssociative() const;
257   static bool isAssociative(unsigned op);
258
259   /// isCommutative - Return true if the instruction is commutative:
260   ///
261   ///   Commutative operators satisfy: (x op y) === (y op x)
262   ///
263   /// In LLVM, these are the associative operators, plus SetEQ and SetNE, when
264   /// applied to any type.
265   ///
266   bool isCommutative() const { return isCommutative(getOpcode()); }
267   static bool isCommutative(unsigned op);
268
269   /// isIdempotent - Return true if the instruction is idempotent:
270   ///
271   ///   Idempotent operators satisfy:  x op x === x
272   ///
273   /// In LLVM, the And and Or operators are idempotent.
274   ///
275   bool isIdempotent() const { return isIdempotent(getOpcode()); }
276   static bool isIdempotent(unsigned op);
277
278   /// isNilpotent - Return true if the instruction is nilpotent:
279   ///
280   ///   Nilpotent operators satisfy:  x op x === Id,
281   ///
282   ///   where Id is the identity for the operator, i.e. a constant such that
283   ///     x op Id === x and Id op x === x for all x.
284   ///
285   /// In LLVM, the Xor operator is nilpotent.
286   ///
287   bool isNilpotent() const { return isNilpotent(getOpcode()); }
288   static bool isNilpotent(unsigned op);
289
290   /// mayWriteToMemory - Return true if this instruction may modify memory.
291   ///
292   bool mayWriteToMemory() const;
293
294   /// mayReadFromMemory - Return true if this instruction may read memory.
295   ///
296   bool mayReadFromMemory() const;
297
298   /// mayReadOrWriteMemory - Return true if this instruction may read or
299   /// write memory.
300   ///
301   bool mayReadOrWriteMemory() const {
302     return mayReadFromMemory() || mayWriteToMemory();
303   }
304
305   /// mayThrow - Return true if this instruction may throw an exception.
306   ///
307   bool mayThrow() const;
308
309   /// mayHaveSideEffects - Return true if the instruction may have side effects.
310   ///
311   /// Note that this does not consider malloc and alloca to have side
312   /// effects because the newly allocated memory is completely invisible to
313   /// instructions which don't used the returned value.  For cases where this
314   /// matters, isSafeToSpeculativelyExecute may be more appropriate.
315   bool mayHaveSideEffects() const {
316     return mayWriteToMemory() || mayThrow();
317   }
318
319   /// clone() - Create a copy of 'this' instruction that is identical in all
320   /// ways except the following:
321   ///   * The instruction has no parent
322   ///   * The instruction has no name
323   ///
324   Instruction *clone() const;
325
326   /// isIdenticalTo - Return true if the specified instruction is exactly
327   /// identical to the current one.  This means that all operands match and any
328   /// extra information (e.g. load is volatile) agree.
329   bool isIdenticalTo(const Instruction *I) const;
330
331   /// isIdenticalToWhenDefined - This is like isIdenticalTo, except that it
332   /// ignores the SubclassOptionalData flags, which specify conditions
333   /// under which the instruction's result is undefined.
334   bool isIdenticalToWhenDefined(const Instruction *I) const;
335
336   /// When checking for operation equivalence (using isSameOperationAs) it is
337   /// sometimes useful to ignore certain attributes.
338   enum OperationEquivalenceFlags {
339     /// Check for equivalence ignoring load/store alignment.
340     CompareIgnoringAlignment = 1<<0,
341     /// Check for equivalence treating a type and a vector of that type
342     /// as equivalent.
343     CompareUsingScalarTypes = 1<<1
344   };
345
346   /// This function determines if the specified instruction executes the same
347   /// operation as the current one. This means that the opcodes, type, operand
348   /// types and any other factors affecting the operation must be the same. This
349   /// is similar to isIdenticalTo except the operands themselves don't have to
350   /// be identical.
351   /// @returns true if the specified instruction is the same operation as
352   /// the current one.
353   /// @brief Determine if one instruction is the same operation as another.
354   bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const;
355
356   /// isUsedOutsideOfBlock - Return true if there are any uses of this
357   /// instruction in blocks other than the specified block.  Note that PHI nodes
358   /// are considered to evaluate their operands in the corresponding predecessor
359   /// block.
360   bool isUsedOutsideOfBlock(const BasicBlock *BB) const;
361
362
363   /// Methods for support type inquiry through isa, cast, and dyn_cast:
364   static inline bool classof(const Value *V) {
365     return V->getValueID() >= Value::InstructionVal;
366   }
367
368   //----------------------------------------------------------------------
369   // Exported enumerations.
370   //
371   enum TermOps {       // These terminate basic blocks
372 #define  FIRST_TERM_INST(N)             TermOpsBegin = N,
373 #define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N,
374 #define   LAST_TERM_INST(N)             TermOpsEnd = N+1
375 #include "llvm/Instruction.def"
376   };
377
378   enum BinaryOps {
379 #define  FIRST_BINARY_INST(N)             BinaryOpsBegin = N,
380 #define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N,
381 #define   LAST_BINARY_INST(N)             BinaryOpsEnd = N+1
382 #include "llvm/Instruction.def"
383   };
384
385   enum MemoryOps {
386 #define  FIRST_MEMORY_INST(N)             MemoryOpsBegin = N,
387 #define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N,
388 #define   LAST_MEMORY_INST(N)             MemoryOpsEnd = N+1
389 #include "llvm/Instruction.def"
390   };
391
392   enum CastOps {
393 #define  FIRST_CAST_INST(N)             CastOpsBegin = N,
394 #define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N,
395 #define   LAST_CAST_INST(N)             CastOpsEnd = N+1
396 #include "llvm/Instruction.def"
397   };
398
399   enum OtherOps {
400 #define  FIRST_OTHER_INST(N)             OtherOpsBegin = N,
401 #define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N,
402 #define   LAST_OTHER_INST(N)             OtherOpsEnd = N+1
403 #include "llvm/Instruction.def"
404   };
405 private:
406   // Shadow Value::setValueSubclassData with a private forwarding method so that
407   // subclasses cannot accidentally use it.
408   void setValueSubclassData(unsigned short D) {
409     Value::setValueSubclassData(D);
410   }
411   unsigned short getSubclassDataFromValue() const {
412     return Value::getSubclassDataFromValue();
413   }
414
415   void setHasMetadataHashEntry(bool V) {
416     setValueSubclassData((getSubclassDataFromValue() & ~HasMetadataBit) |
417                          (V ? HasMetadataBit : 0));
418   }
419
420   friend class SymbolTableListTraits<Instruction, BasicBlock>;
421   void setParent(BasicBlock *P);
422 protected:
423   // Instruction subclasses can stick up to 15 bits of stuff into the
424   // SubclassData field of instruction with these members.
425
426   // Verify that only the low 15 bits are used.
427   void setInstructionSubclassData(unsigned short D) {
428     assert((D & HasMetadataBit) == 0 && "Out of range value put into field");
429     setValueSubclassData((getSubclassDataFromValue() & HasMetadataBit) | D);
430   }
431
432   unsigned getSubclassDataFromInstruction() const {
433     return getSubclassDataFromValue() & ~HasMetadataBit;
434   }
435
436   Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
437               Instruction *InsertBefore = 0);
438   Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
439               BasicBlock *InsertAtEnd);
440   virtual Instruction *clone_impl() const = 0;
441
442 };
443
444 // Instruction* is only 4-byte aligned.
445 template<>
446 class PointerLikeTypeTraits<Instruction*> {
447   typedef Instruction* PT;
448 public:
449   static inline void *getAsVoidPointer(PT P) { return P; }
450   static inline PT getFromVoidPointer(void *P) {
451     return static_cast<PT>(P);
452   }
453   enum { NumLowBitsAvailable = 2 };
454 };
455
456 } // End llvm namespace
457
458 #endif