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