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