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