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