[PlaceSafepoints] Cleanup InsertSafepointPoll function
[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   /// \brief Drop unknown metadata.
208   /// Passes are required to drop metadata they don't understand. This is a
209   /// convenience method for passes to do so.
210   void dropUnknownMetadata(ArrayRef<unsigned> KnownIDs);
211   void dropUnknownMetadata() {
212     return dropUnknownMetadata(None);
213   }
214   void dropUnknownMetadata(unsigned ID1) {
215     return dropUnknownMetadata(makeArrayRef(ID1));
216   }
217   void dropUnknownMetadata(unsigned ID1, unsigned ID2) {
218     unsigned IDs[] = {ID1, ID2};
219     return dropUnknownMetadata(IDs);
220   }
221
222   /// setAAMetadata - Sets the metadata on this instruction from the
223   /// AAMDNodes structure.
224   void setAAMetadata(const AAMDNodes &N);
225
226   /// setDebugLoc - Set the debug location information for this instruction.
227   void setDebugLoc(DebugLoc Loc) { DbgLoc = std::move(Loc); }
228
229   /// getDebugLoc - Return the debug location for this node as a DebugLoc.
230   const DebugLoc &getDebugLoc() const { return DbgLoc; }
231
232   /// Set or clear the unsafe-algebra 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 setHasUnsafeAlgebra(bool B);
236
237   /// Set or clear the no-nans 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 setHasNoNaNs(bool B);
241
242   /// Set or clear the no-infs flag on this instruction, which must be an
243   /// operator which supports this flag. See LangRef.html for the meaning of
244   /// this flag.
245   void setHasNoInfs(bool B);
246
247   /// Set or clear the no-signed-zeros 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 setHasNoSignedZeros(bool B);
251
252   /// Set or clear the allow-reciprocal flag on this instruction, which must be
253   /// an operator which supports this flag. See LangRef.html for the meaning of
254   /// this flag.
255   void setHasAllowReciprocal(bool B);
256
257   /// Convenience function for setting multiple fast-math flags on this
258   /// instruction, which must be an operator which supports these flags. See
259   /// LangRef.html for the meaning of these flags.
260   void setFastMathFlags(FastMathFlags FMF);
261
262   /// Convenience function for transferring all fast-math flag values to this
263   /// instruction, which must be an operator which supports these flags. See
264   /// LangRef.html for the meaning of these flags.
265   void copyFastMathFlags(FastMathFlags FMF);
266
267   /// Determine whether the unsafe-algebra flag is set.
268   bool hasUnsafeAlgebra() const;
269
270   /// Determine whether the no-NaNs flag is set.
271   bool hasNoNaNs() const;
272
273   /// Determine whether the no-infs flag is set.
274   bool hasNoInfs() const;
275
276   /// Determine whether the no-signed-zeros flag is set.
277   bool hasNoSignedZeros() const;
278
279   /// Determine whether the allow-reciprocal flag is set.
280   bool hasAllowReciprocal() const;
281
282   /// Convenience function for getting all the fast-math flags, which must be an
283   /// operator which supports these flags. See LangRef.html for the meaning of
284   /// these flags.
285   FastMathFlags getFastMathFlags() const;
286
287   /// Copy I's fast-math flags
288   void copyFastMathFlags(const Instruction *I);
289
290 private:
291   /// hasMetadataHashEntry - Return true if we have an entry in the on-the-side
292   /// metadata hash.
293   bool hasMetadataHashEntry() const {
294     return (getSubclassDataFromValue() & HasMetadataBit) != 0;
295   }
296
297   // These are all implemented in Metadata.cpp.
298   MDNode *getMetadataImpl(unsigned KindID) const;
299   MDNode *getMetadataImpl(StringRef Kind) const;
300   void
301   getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
302   void getAllMetadataOtherThanDebugLocImpl(
303       SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
304   void clearMetadataHashEntries();
305 public:
306   //===--------------------------------------------------------------------===//
307   // Predicates and helper methods.
308   //===--------------------------------------------------------------------===//
309
310
311   /// isAssociative - Return true if the instruction is associative:
312   ///
313   ///   Associative operators satisfy:  x op (y op z) === (x op y) op z
314   ///
315   /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
316   ///
317   bool isAssociative() const;
318   static bool isAssociative(unsigned op);
319
320   /// isCommutative - Return true if the instruction is commutative:
321   ///
322   ///   Commutative operators satisfy: (x op y) === (y op x)
323   ///
324   /// In LLVM, these are the associative operators, plus SetEQ and SetNE, when
325   /// applied to any type.
326   ///
327   bool isCommutative() const { return isCommutative(getOpcode()); }
328   static bool isCommutative(unsigned op);
329
330   /// isIdempotent - Return true if the instruction is idempotent:
331   ///
332   ///   Idempotent operators satisfy:  x op x === x
333   ///
334   /// In LLVM, the And and Or operators are idempotent.
335   ///
336   bool isIdempotent() const { return isIdempotent(getOpcode()); }
337   static bool isIdempotent(unsigned op);
338
339   /// isNilpotent - Return true if the instruction is nilpotent:
340   ///
341   ///   Nilpotent operators satisfy:  x op x === Id,
342   ///
343   ///   where Id is the identity for the operator, i.e. a constant such that
344   ///     x op Id === x and Id op x === x for all x.
345   ///
346   /// In LLVM, the Xor operator is nilpotent.
347   ///
348   bool isNilpotent() const { return isNilpotent(getOpcode()); }
349   static bool isNilpotent(unsigned op);
350
351   /// mayWriteToMemory - Return true if this instruction may modify memory.
352   ///
353   bool mayWriteToMemory() const;
354
355   /// mayReadFromMemory - Return true if this instruction may read memory.
356   ///
357   bool mayReadFromMemory() const;
358
359   /// mayReadOrWriteMemory - Return true if this instruction may read or
360   /// write memory.
361   ///
362   bool mayReadOrWriteMemory() const {
363     return mayReadFromMemory() || mayWriteToMemory();
364   }
365
366   /// isAtomic - Return true if this instruction has an
367   /// AtomicOrdering of unordered or higher.
368   ///
369   bool isAtomic() const;
370
371   /// mayThrow - Return true if this instruction may throw an exception.
372   ///
373   bool mayThrow() const;
374
375   /// mayReturn - Return true if this is a function that may return.
376   /// this is true for all normal instructions. The only exception
377   /// is functions that are marked with the 'noreturn' attribute.
378   ///
379   bool mayReturn() const;
380
381   /// mayHaveSideEffects - Return true if the instruction may have side effects.
382   ///
383   /// Note that this does not consider malloc and alloca to have side
384   /// effects because the newly allocated memory is completely invisible to
385   /// instructions which don't used the returned value.  For cases where this
386   /// matters, isSafeToSpeculativelyExecute may be more appropriate.
387   bool mayHaveSideEffects() const {
388     return mayWriteToMemory() || mayThrow() || !mayReturn();
389   }
390
391   /// clone() - Create a copy of 'this' instruction that is identical in all
392   /// ways except the following:
393   ///   * The instruction has no parent
394   ///   * The instruction has no name
395   ///
396   Instruction *clone() const;
397
398   /// isIdenticalTo - Return true if the specified instruction is exactly
399   /// identical to the current one.  This means that all operands match and any
400   /// extra information (e.g. load is volatile) agree.
401   bool isIdenticalTo(const Instruction *I) const;
402
403   /// isIdenticalToWhenDefined - This is like isIdenticalTo, except that it
404   /// ignores the SubclassOptionalData flags, which specify conditions
405   /// under which the instruction's result is undefined.
406   bool isIdenticalToWhenDefined(const Instruction *I) const;
407
408   /// When checking for operation equivalence (using isSameOperationAs) it is
409   /// sometimes useful to ignore certain attributes.
410   enum OperationEquivalenceFlags {
411     /// Check for equivalence ignoring load/store alignment.
412     CompareIgnoringAlignment = 1<<0,
413     /// Check for equivalence treating a type and a vector of that type
414     /// as equivalent.
415     CompareUsingScalarTypes = 1<<1
416   };
417
418   /// This function determines if the specified instruction executes the same
419   /// operation as the current one. This means that the opcodes, type, operand
420   /// types and any other factors affecting the operation must be the same. This
421   /// is similar to isIdenticalTo except the operands themselves don't have to
422   /// be identical.
423   /// @returns true if the specified instruction is the same operation as
424   /// the current one.
425   /// @brief Determine if one instruction is the same operation as another.
426   bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const;
427
428   /// isUsedOutsideOfBlock - Return true if there are any uses of this
429   /// instruction in blocks other than the specified block.  Note that PHI nodes
430   /// are considered to evaluate their operands in the corresponding predecessor
431   /// block.
432   bool isUsedOutsideOfBlock(const BasicBlock *BB) const;
433
434
435   /// Methods for support type inquiry through isa, cast, and dyn_cast:
436   static inline bool classof(const Value *V) {
437     return V->getValueID() >= Value::InstructionVal;
438   }
439
440   //----------------------------------------------------------------------
441   // Exported enumerations.
442   //
443   enum TermOps {       // These terminate basic blocks
444 #define  FIRST_TERM_INST(N)             TermOpsBegin = N,
445 #define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N,
446 #define   LAST_TERM_INST(N)             TermOpsEnd = N+1
447 #include "llvm/IR/Instruction.def"
448   };
449
450   enum BinaryOps {
451 #define  FIRST_BINARY_INST(N)             BinaryOpsBegin = N,
452 #define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N,
453 #define   LAST_BINARY_INST(N)             BinaryOpsEnd = N+1
454 #include "llvm/IR/Instruction.def"
455   };
456
457   enum MemoryOps {
458 #define  FIRST_MEMORY_INST(N)             MemoryOpsBegin = N,
459 #define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N,
460 #define   LAST_MEMORY_INST(N)             MemoryOpsEnd = N+1
461 #include "llvm/IR/Instruction.def"
462   };
463
464   enum CastOps {
465 #define  FIRST_CAST_INST(N)             CastOpsBegin = N,
466 #define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N,
467 #define   LAST_CAST_INST(N)             CastOpsEnd = N+1
468 #include "llvm/IR/Instruction.def"
469   };
470
471   enum OtherOps {
472 #define  FIRST_OTHER_INST(N)             OtherOpsBegin = N,
473 #define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N,
474 #define   LAST_OTHER_INST(N)             OtherOpsEnd = N+1
475 #include "llvm/IR/Instruction.def"
476   };
477 private:
478   // Shadow Value::setValueSubclassData with a private forwarding method so that
479   // subclasses cannot accidentally use it.
480   void setValueSubclassData(unsigned short D) {
481     Value::setValueSubclassData(D);
482   }
483   unsigned short getSubclassDataFromValue() const {
484     return Value::getSubclassDataFromValue();
485   }
486
487   void setHasMetadataHashEntry(bool V) {
488     setValueSubclassData((getSubclassDataFromValue() & ~HasMetadataBit) |
489                          (V ? HasMetadataBit : 0));
490   }
491
492   friend class SymbolTableListTraits<Instruction, BasicBlock>;
493   void setParent(BasicBlock *P);
494 protected:
495   // Instruction subclasses can stick up to 15 bits of stuff into the
496   // SubclassData field of instruction with these members.
497
498   // Verify that only the low 15 bits are used.
499   void setInstructionSubclassData(unsigned short D) {
500     assert((D & HasMetadataBit) == 0 && "Out of range value put into field");
501     setValueSubclassData((getSubclassDataFromValue() & HasMetadataBit) | D);
502   }
503
504   unsigned getSubclassDataFromInstruction() const {
505     return getSubclassDataFromValue() & ~HasMetadataBit;
506   }
507
508   Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
509               Instruction *InsertBefore = nullptr);
510   Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
511               BasicBlock *InsertAtEnd);
512   virtual Instruction *clone_impl() const = 0;
513
514 };
515
516 inline Instruction *ilist_traits<Instruction>::createSentinel() const {
517   // Since i(p)lists always publicly derive from their corresponding traits,
518   // placing a data member in this class will augment the i(p)list.  But since
519   // the NodeTy is expected to be publicly derive from ilist_node<NodeTy>,
520   // there is a legal viable downcast from it to NodeTy. We use this trick to
521   // superimpose an i(p)list with a "ghostly" NodeTy, which becomes the
522   // sentinel. Dereferencing the sentinel is forbidden (save the
523   // ilist_node<NodeTy>), so no one will ever notice the superposition.
524   return static_cast<Instruction *>(&Sentinel);
525 }
526
527 // Instruction* is only 4-byte aligned.
528 template<>
529 class PointerLikeTypeTraits<Instruction*> {
530   typedef Instruction* PT;
531 public:
532   static inline void *getAsVoidPointer(PT P) { return P; }
533   static inline PT getFromVoidPointer(void *P) {
534     return static_cast<PT>(P);
535   }
536   enum { NumLowBitsAvailable = 2 };
537 };
538
539 } // End llvm namespace
540
541 #endif