Allow isDereferenceablePointer to look through some bitcasts
[oota-llvm.git] / include / llvm / IR / Value.h
1 //===-- llvm/Value.h - Definition of the Value class ------------*- 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 declares the Value class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_IR_VALUE_H
15 #define LLVM_IR_VALUE_H
16
17 #include "llvm-c/Core.h"
18 #include "llvm/ADT/iterator_range.h"
19 #include "llvm/IR/Use.h"
20 #include "llvm/Support/CBindingWrapping.h"
21 #include "llvm/Support/Casting.h"
22 #include "llvm/Support/Compiler.h"
23
24 namespace llvm {
25
26 class APInt;
27 class Argument;
28 class AssemblyAnnotationWriter;
29 class BasicBlock;
30 class Constant;
31 class DataLayout;
32 class Function;
33 class GlobalAlias;
34 class GlobalObject;
35 class GlobalValue;
36 class GlobalVariable;
37 class InlineAsm;
38 class Instruction;
39 class LLVMContext;
40 class MDNode;
41 class Module;
42 class StringRef;
43 class Twine;
44 class Type;
45 class ValueHandleBase;
46 class ValueSymbolTable;
47 class raw_ostream;
48
49 template<typename ValueTy> class StringMapEntry;
50 typedef StringMapEntry<Value*> ValueName;
51
52 //===----------------------------------------------------------------------===//
53 //                                 Value Class
54 //===----------------------------------------------------------------------===//
55
56 /// This is a very important LLVM class. It is the base class of all values
57 /// computed by a program that may be used as operands to other values. Value is
58 /// the super class of other important classes such as Instruction and Function.
59 /// All Values have a Type. Type is not a subclass of Value. Some values can
60 /// have a name and they belong to some Module.  Setting the name on the Value
61 /// automatically updates the module's symbol table.
62 ///
63 /// Every value has a "use list" that keeps track of which other Values are
64 /// using this Value.  A Value can also have an arbitrary number of ValueHandle
65 /// objects that watch it and listen to RAUW and Destroy events.  See
66 /// llvm/IR/ValueHandle.h for details.
67 ///
68 /// @brief LLVM Value Representation
69 class Value {
70   Type *VTy;
71   Use *UseList;
72
73   friend class ValueSymbolTable; // Allow ValueSymbolTable to directly mod Name.
74   friend class ValueHandleBase;
75   ValueName *Name;
76
77   const unsigned char SubclassID;   // Subclass identifier (for isa/dyn_cast)
78   unsigned char HasValueHandle : 1; // Has a ValueHandle pointing to this?
79 protected:
80   /// SubclassOptionalData - This member is similar to SubclassData, however it
81   /// is for holding information which may be used to aid optimization, but
82   /// which may be cleared to zero without affecting conservative
83   /// interpretation.
84   unsigned char SubclassOptionalData : 7;
85
86 private:
87   /// SubclassData - This member is defined by this class, but is not used for
88   /// anything.  Subclasses can use it to hold whatever state they find useful.
89   /// This field is initialized to zero by the ctor.
90   unsigned short SubclassData;
91
92   template <typename UseT> // UseT == 'Use' or 'const Use'
93   class use_iterator_impl
94       : public std::iterator<std::forward_iterator_tag, UseT *, ptrdiff_t> {
95     typedef std::iterator<std::forward_iterator_tag, UseT *, ptrdiff_t> super;
96
97     UseT *U;
98     explicit use_iterator_impl(UseT *u) : U(u) {}
99     friend class Value;
100
101   public:
102     typedef typename super::reference reference;
103     typedef typename super::pointer pointer;
104
105     use_iterator_impl() : U() {}
106
107     bool operator==(const use_iterator_impl &x) const { return U == x.U; }
108     bool operator!=(const use_iterator_impl &x) const { return !operator==(x); }
109
110     use_iterator_impl &operator++() { // Preincrement
111       assert(U && "Cannot increment end iterator!");
112       U = U->getNext();
113       return *this;
114     }
115     use_iterator_impl operator++(int) { // Postincrement
116       auto tmp = *this;
117       ++*this;
118       return tmp;
119     }
120
121     UseT &operator*() const {
122       assert(U && "Cannot dereference end iterator!");
123       return *U;
124     }
125
126     UseT *operator->() const { return &operator*(); }
127
128     operator use_iterator_impl<const UseT>() const {
129       return use_iterator_impl<const UseT>(U);
130     }
131   };
132
133   template <typename UserTy> // UserTy == 'User' or 'const User'
134   class user_iterator_impl
135       : public std::iterator<std::forward_iterator_tag, UserTy *, ptrdiff_t> {
136     typedef std::iterator<std::forward_iterator_tag, UserTy *, ptrdiff_t> super;
137
138     use_iterator_impl<Use> UI;
139     explicit user_iterator_impl(Use *U) : UI(U) {}
140     friend class Value;
141
142   public:
143     typedef typename super::reference reference;
144     typedef typename super::pointer pointer;
145
146     user_iterator_impl() {}
147
148     bool operator==(const user_iterator_impl &x) const { return UI == x.UI; }
149     bool operator!=(const user_iterator_impl &x) const { return !operator==(x); }
150
151     /// \brief Returns true if this iterator is equal to user_end() on the value.
152     bool atEnd() const { return *this == user_iterator_impl(); }
153
154     user_iterator_impl &operator++() { // Preincrement
155       ++UI;
156       return *this;
157     }
158     user_iterator_impl operator++(int) { // Postincrement
159       auto tmp = *this;
160       ++*this;
161       return tmp;
162     }
163
164     // Retrieve a pointer to the current User.
165     UserTy *operator*() const {
166       return UI->getUser();
167     }
168
169     UserTy *operator->() const { return operator*(); }
170
171     operator user_iterator_impl<const UserTy>() const {
172       return user_iterator_impl<const UserTy>(*UI);
173     }
174
175     Use &getUse() const { return *UI; }
176
177     /// \brief Return the operand # of this use in its User.
178     /// FIXME: Replace all callers with a direct call to Use::getOperandNo.
179     unsigned getOperandNo() const { return UI->getOperandNo(); }
180   };
181
182   void operator=(const Value &) LLVM_DELETED_FUNCTION;
183   Value(const Value &) LLVM_DELETED_FUNCTION;
184
185 protected:
186   Value(Type *Ty, unsigned scid);
187 public:
188   virtual ~Value();
189
190   /// dump - Support for debugging, callable in GDB: V->dump()
191   //
192   void dump() const;
193
194   /// print - Implement operator<< on Value.
195   ///
196   void print(raw_ostream &O) const;
197
198   /// \brief Print the name of this Value out to the specified raw_ostream.
199   /// This is useful when you just want to print 'int %reg126', not the
200   /// instruction that generated it. If you specify a Module for context, then
201   /// even constanst get pretty-printed; for example, the type of a null
202   /// pointer is printed symbolically.
203   void printAsOperand(raw_ostream &O, bool PrintType = true,
204                       const Module *M = nullptr) const;
205
206   /// All values are typed, get the type of this value.
207   ///
208   Type *getType() const { return VTy; }
209
210   /// All values hold a context through their type.
211   LLVMContext &getContext() const;
212
213   // All values can potentially be named.
214   bool hasName() const { return Name != nullptr && SubclassID != MDStringVal; }
215   ValueName *getValueName() const { return Name; }
216   void setValueName(ValueName *VN) { Name = VN; }
217
218   /// getName() - Return a constant reference to the value's name. This is cheap
219   /// and guaranteed to return the same reference as long as the value is not
220   /// modified.
221   StringRef getName() const;
222
223   /// setName() - Change the name of the value, choosing a new unique name if
224   /// the provided name is taken.
225   ///
226   /// \param Name The new name; or "" if the value's name should be removed.
227   void setName(const Twine &Name);
228
229
230   /// takeName - transfer the name from V to this value, setting V's name to
231   /// empty.  It is an error to call V->takeName(V).
232   void takeName(Value *V);
233
234   /// replaceAllUsesWith - Go through the uses list for this definition and make
235   /// each use point to "V" instead of "this".  After this completes, 'this's
236   /// use list is guaranteed to be empty.
237   ///
238   void replaceAllUsesWith(Value *V);
239
240   //----------------------------------------------------------------------
241   // Methods for handling the chain of uses of this Value.
242   //
243   bool               use_empty() const { return UseList == nullptr; }
244
245   typedef use_iterator_impl<Use>       use_iterator;
246   typedef use_iterator_impl<const Use> const_use_iterator;
247   use_iterator       use_begin()       { return use_iterator(UseList); }
248   const_use_iterator use_begin() const { return const_use_iterator(UseList); }
249   use_iterator       use_end()         { return use_iterator();   }
250   const_use_iterator use_end()   const { return const_use_iterator();   }
251   iterator_range<use_iterator> uses() {
252     return iterator_range<use_iterator>(use_begin(), use_end());
253   }
254   iterator_range<const_use_iterator> uses() const {
255     return iterator_range<const_use_iterator>(use_begin(), use_end());
256   }
257
258   typedef user_iterator_impl<User>       user_iterator;
259   typedef user_iterator_impl<const User> const_user_iterator;
260   user_iterator       user_begin()       { return user_iterator(UseList); }
261   const_user_iterator user_begin() const { return const_user_iterator(UseList); }
262   user_iterator       user_end()         { return user_iterator();   }
263   const_user_iterator user_end()   const { return const_user_iterator();   }
264   User               *user_back()        { return *user_begin(); }
265   const User         *user_back()  const { return *user_begin(); }
266   iterator_range<user_iterator> users() {
267     return iterator_range<user_iterator>(user_begin(), user_end());
268   }
269   iterator_range<const_user_iterator> users() const {
270     return iterator_range<const_user_iterator>(user_begin(), user_end());
271   }
272
273   /// hasOneUse - Return true if there is exactly one user of this value.  This
274   /// is specialized because it is a common request and does not require
275   /// traversing the whole use list.
276   ///
277   bool hasOneUse() const {
278     const_use_iterator I = use_begin(), E = use_end();
279     if (I == E) return false;
280     return ++I == E;
281   }
282
283   /// hasNUses - Return true if this Value has exactly N users.
284   ///
285   bool hasNUses(unsigned N) const;
286
287   /// hasNUsesOrMore - Return true if this value has N users or more.  This is
288   /// logically equivalent to getNumUses() >= N.
289   ///
290   bool hasNUsesOrMore(unsigned N) const;
291
292   bool isUsedInBasicBlock(const BasicBlock *BB) const;
293
294   /// getNumUses - This method computes the number of uses of this Value.  This
295   /// is a linear time operation.  Use hasOneUse, hasNUses, or hasNUsesOrMore
296   /// to check for specific values.
297   unsigned getNumUses() const;
298
299   /// addUse - This method should only be used by the Use class.
300   ///
301   void addUse(Use &U) { U.addToList(&UseList); }
302
303   /// An enumeration for keeping track of the concrete subclass of Value that
304   /// is actually instantiated. Values of this enumeration are kept in the
305   /// Value classes SubclassID field. They are used for concrete type
306   /// identification.
307   enum ValueTy {
308     ArgumentVal,              // This is an instance of Argument
309     BasicBlockVal,            // This is an instance of BasicBlock
310     FunctionVal,              // This is an instance of Function
311     GlobalAliasVal,           // This is an instance of GlobalAlias
312     GlobalVariableVal,        // This is an instance of GlobalVariable
313     UndefValueVal,            // This is an instance of UndefValue
314     BlockAddressVal,          // This is an instance of BlockAddress
315     ConstantExprVal,          // This is an instance of ConstantExpr
316     ConstantAggregateZeroVal, // This is an instance of ConstantAggregateZero
317     ConstantDataArrayVal,     // This is an instance of ConstantDataArray
318     ConstantDataVectorVal,    // This is an instance of ConstantDataVector
319     ConstantIntVal,           // This is an instance of ConstantInt
320     ConstantFPVal,            // This is an instance of ConstantFP
321     ConstantArrayVal,         // This is an instance of ConstantArray
322     ConstantStructVal,        // This is an instance of ConstantStruct
323     ConstantVectorVal,        // This is an instance of ConstantVector
324     ConstantPointerNullVal,   // This is an instance of ConstantPointerNull
325     MDNodeVal,                // This is an instance of MDNode
326     MDStringVal,              // This is an instance of MDString
327     InlineAsmVal,             // This is an instance of InlineAsm
328     InstructionVal,           // This is an instance of Instruction
329     // Enum values starting at InstructionVal are used for Instructions;
330     // don't add new values here!
331
332     // Markers:
333     ConstantFirstVal = FunctionVal,
334     ConstantLastVal  = ConstantPointerNullVal
335   };
336
337   /// getValueID - Return an ID for the concrete type of this object.  This is
338   /// used to implement the classof checks.  This should not be used for any
339   /// other purpose, as the values may change as LLVM evolves.  Also, note that
340   /// for instructions, the Instruction's opcode is added to InstructionVal. So
341   /// this means three things:
342   /// # there is no value with code InstructionVal (no opcode==0).
343   /// # there are more possible values for the value type than in ValueTy enum.
344   /// # the InstructionVal enumerator must be the highest valued enumerator in
345   ///   the ValueTy enum.
346   unsigned getValueID() const {
347     return SubclassID;
348   }
349
350   /// getRawSubclassOptionalData - Return the raw optional flags value
351   /// contained in this value. This should only be used when testing two
352   /// Values for equivalence.
353   unsigned getRawSubclassOptionalData() const {
354     return SubclassOptionalData;
355   }
356
357   /// clearSubclassOptionalData - Clear the optional flags contained in
358   /// this value.
359   void clearSubclassOptionalData() {
360     SubclassOptionalData = 0;
361   }
362
363   /// hasSameSubclassOptionalData - Test whether the optional flags contained
364   /// in this value are equal to the optional flags in the given value.
365   bool hasSameSubclassOptionalData(const Value *V) const {
366     return SubclassOptionalData == V->SubclassOptionalData;
367   }
368
369   /// intersectOptionalDataWith - Clear any optional flags in this value
370   /// that are not also set in the given value.
371   void intersectOptionalDataWith(const Value *V) {
372     SubclassOptionalData &= V->SubclassOptionalData;
373   }
374
375   /// hasValueHandle - Return true if there is a value handle associated with
376   /// this value.
377   bool hasValueHandle() const { return HasValueHandle; }
378
379   /// \brief Strips off any unneeded pointer casts, all-zero GEPs and aliases
380   /// from the specified value, returning the original uncasted value.
381   ///
382   /// If this is called on a non-pointer value, it returns 'this'.
383   Value *stripPointerCasts();
384   const Value *stripPointerCasts() const {
385     return const_cast<Value*>(this)->stripPointerCasts();
386   }
387
388   /// \brief Strips off any unneeded pointer casts and all-zero GEPs from the
389   /// specified value, returning the original uncasted value.
390   ///
391   /// If this is called on a non-pointer value, it returns 'this'.
392   Value *stripPointerCastsNoFollowAliases();
393   const Value *stripPointerCastsNoFollowAliases() const {
394     return const_cast<Value*>(this)->stripPointerCastsNoFollowAliases();
395   }
396
397   /// \brief Strips off unneeded pointer casts and all-constant GEPs from the
398   /// specified value, returning the original pointer value.
399   ///
400   /// If this is called on a non-pointer value, it returns 'this'.
401   Value *stripInBoundsConstantOffsets();
402   const Value *stripInBoundsConstantOffsets() const {
403     return const_cast<Value*>(this)->stripInBoundsConstantOffsets();
404   }
405
406   /// \brief Strips like \c stripInBoundsConstantOffsets but also accumulates
407   /// the constant offset stripped.
408   ///
409   /// Stores the resulting constant offset stripped into the APInt provided.
410   /// The provided APInt will be extended or truncated as needed to be the
411   /// correct bitwidth for an offset of this pointer type.
412   ///
413   /// If this is called on a non-pointer value, it returns 'this'.
414   Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
415                                                    APInt &Offset);
416   const Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
417                                                          APInt &Offset) const {
418     return const_cast<Value *>(this)
419         ->stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
420   }
421
422   /// \brief Strips off unneeded pointer casts and any in-bounds offsets from
423   /// the specified value, returning the original pointer value.
424   ///
425   /// If this is called on a non-pointer value, it returns 'this'.
426   Value *stripInBoundsOffsets();
427   const Value *stripInBoundsOffsets() const {
428     return const_cast<Value*>(this)->stripInBoundsOffsets();
429   }
430
431   /// isDereferenceablePointer - Test if this value is always a pointer to
432   /// allocated and suitably aligned memory for a simple load or store.
433   bool isDereferenceablePointer(const DataLayout *DL = nullptr) const;
434
435   /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
436   /// return the value in the PHI node corresponding to PredBB.  If not, return
437   /// ourself.  This is useful if you want to know the value something has in a
438   /// predecessor block.
439   Value *DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB);
440
441   const Value *DoPHITranslation(const BasicBlock *CurBB,
442                                 const BasicBlock *PredBB) const{
443     return const_cast<Value*>(this)->DoPHITranslation(CurBB, PredBB);
444   }
445
446   /// MaximumAlignment - This is the greatest alignment value supported by
447   /// load, store, and alloca instructions, and global values.
448   static const unsigned MaximumAlignment = 1u << 29;
449
450   /// mutateType - Mutate the type of this Value to be of the specified type.
451   /// Note that this is an extremely dangerous operation which can create
452   /// completely invalid IR very easily.  It is strongly recommended that you
453   /// recreate IR objects with the right types instead of mutating them in
454   /// place.
455   void mutateType(Type *Ty) {
456     VTy = Ty;
457   }
458
459 protected:
460   unsigned short getSubclassDataFromValue() const { return SubclassData; }
461   void setValueSubclassData(unsigned short D) { SubclassData = D; }
462 };
463
464 inline raw_ostream &operator<<(raw_ostream &OS, const Value &V) {
465   V.print(OS);
466   return OS;
467 }
468
469 void Use::set(Value *V) {
470   if (Val) removeFromList();
471   Val = V;
472   if (V) V->addUse(*this);
473 }
474
475
476 // isa - Provide some specializations of isa so that we don't have to include
477 // the subtype header files to test to see if the value is a subclass...
478 //
479 template <> struct isa_impl<Constant, Value> {
480   static inline bool doit(const Value &Val) {
481     return Val.getValueID() >= Value::ConstantFirstVal &&
482       Val.getValueID() <= Value::ConstantLastVal;
483   }
484 };
485
486 template <> struct isa_impl<Argument, Value> {
487   static inline bool doit (const Value &Val) {
488     return Val.getValueID() == Value::ArgumentVal;
489   }
490 };
491
492 template <> struct isa_impl<InlineAsm, Value> {
493   static inline bool doit(const Value &Val) {
494     return Val.getValueID() == Value::InlineAsmVal;
495   }
496 };
497
498 template <> struct isa_impl<Instruction, Value> {
499   static inline bool doit(const Value &Val) {
500     return Val.getValueID() >= Value::InstructionVal;
501   }
502 };
503
504 template <> struct isa_impl<BasicBlock, Value> {
505   static inline bool doit(const Value &Val) {
506     return Val.getValueID() == Value::BasicBlockVal;
507   }
508 };
509
510 template <> struct isa_impl<Function, Value> {
511   static inline bool doit(const Value &Val) {
512     return Val.getValueID() == Value::FunctionVal;
513   }
514 };
515
516 template <> struct isa_impl<GlobalVariable, Value> {
517   static inline bool doit(const Value &Val) {
518     return Val.getValueID() == Value::GlobalVariableVal;
519   }
520 };
521
522 template <> struct isa_impl<GlobalAlias, Value> {
523   static inline bool doit(const Value &Val) {
524     return Val.getValueID() == Value::GlobalAliasVal;
525   }
526 };
527
528 template <> struct isa_impl<GlobalValue, Value> {
529   static inline bool doit(const Value &Val) {
530     return isa<GlobalObject>(Val) || isa<GlobalAlias>(Val);
531   }
532 };
533
534 template <> struct isa_impl<GlobalObject, Value> {
535   static inline bool doit(const Value &Val) {
536     return isa<GlobalVariable>(Val) || isa<Function>(Val);
537   }
538 };
539
540 template <> struct isa_impl<MDNode, Value> {
541   static inline bool doit(const Value &Val) {
542     return Val.getValueID() == Value::MDNodeVal;
543   }
544 };
545
546 // Value* is only 4-byte aligned.
547 template<>
548 class PointerLikeTypeTraits<Value*> {
549   typedef Value* PT;
550 public:
551   static inline void *getAsVoidPointer(PT P) { return P; }
552   static inline PT getFromVoidPointer(void *P) {
553     return static_cast<PT>(P);
554   }
555   enum { NumLowBitsAvailable = 2 };
556 };
557
558 // Create wrappers for C Binding types (see CBindingWrapping.h).
559 DEFINE_ISA_CONVERSION_FUNCTIONS(Value, LLVMValueRef)
560
561 /* Specialized opaque value conversions.
562  */
563 inline Value **unwrap(LLVMValueRef *Vals) {
564   return reinterpret_cast<Value**>(Vals);
565 }
566
567 template<typename T>
568 inline T **unwrap(LLVMValueRef *Vals, unsigned Length) {
569 #ifdef DEBUG
570   for (LLVMValueRef *I = Vals, *E = Vals + Length; I != E; ++I)
571     cast<T>(*I);
572 #endif
573   (void)Length;
574   return reinterpret_cast<T**>(Vals);
575 }
576
577 inline LLVMValueRef *wrap(const Value **Vals) {
578   return reinterpret_cast<LLVMValueRef*>(const_cast<Value**>(Vals));
579 }
580
581 } // End llvm namespace
582
583 #endif