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