Final step in the metadata API restructuring: move the
[oota-llvm.git] / include / llvm / 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_VALUE_H
15 #define LLVM_VALUE_H
16
17 #include "llvm/AbstractTypeUser.h"
18 #include "llvm/Use.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/Support/Casting.h"
21 #include <string>
22
23 namespace llvm {
24
25 class Constant;
26 class Argument;
27 class Instruction;
28 class BasicBlock;
29 class GlobalValue;
30 class Function;
31 class GlobalVariable;
32 class GlobalAlias;
33 class InlineAsm;
34 class ValueSymbolTable;
35 class TypeSymbolTable;
36 template<typename ValueTy> class StringMapEntry;
37 template <typename ValueTy = Value>
38 class AssertingVH;
39 typedef StringMapEntry<Value*> ValueName;
40 class raw_ostream;
41 class AssemblyAnnotationWriter;
42 class ValueHandleBase;
43 class LLVMContext;
44 class Twine;
45
46 //===----------------------------------------------------------------------===//
47 //                                 Value Class
48 //===----------------------------------------------------------------------===//
49
50 /// This is a very important LLVM class. It is the base class of all values 
51 /// computed by a program that may be used as operands to other values. Value is
52 /// the super class of other important classes such as Instruction and Function.
53 /// All Values have a Type. Type is not a subclass of Value. All types can have
54 /// a name and they should belong to some Module. Setting the name on the Value
55 /// automatically updates the module's symbol table.
56 ///
57 /// Every value has a "use list" that keeps track of which other Values are
58 /// using this Value.  A Value can also have an arbitrary number of ValueHandle
59 /// objects that watch it and listen to RAUW and Destroy events.  See
60 /// llvm/Support/ValueHandle.h for details.
61 ///
62 /// @brief LLVM Value Representation
63 class Value {
64   const unsigned char SubclassID;   // Subclass identifier (for isa/dyn_cast)
65   unsigned char HasValueHandle : 1; // Has a ValueHandle pointing to this?
66 protected:
67   /// SubclassOptionalData - This member is similar to SubclassData, however it
68   /// is for holding information which may be used to aid optimization, but
69   /// which may be cleared to zero without affecting conservative
70   /// interpretation.
71   unsigned char SubclassOptionalData : 7;
72
73 private:
74   /// SubclassData - This member is defined by this class, but is not used for
75   /// anything.  Subclasses can use it to hold whatever state they find useful.
76   /// This field is initialized to zero by the ctor.
77   unsigned short SubclassData;
78
79   PATypeHolder VTy;
80   Use *UseList;
81
82   friend class ValueSymbolTable; // Allow ValueSymbolTable to directly mod Name.
83   friend class ValueHandleBase;
84   friend class AbstractTypeUser;
85   ValueName *Name;
86
87   void operator=(const Value &);     // Do not implement
88   Value(const Value &);              // Do not implement
89
90 protected:
91   /// printCustom - Value subclasses can override this to implement custom
92   /// printing behavior.
93   virtual void printCustom(raw_ostream &O) const;
94
95 public:
96   Value(const Type *Ty, unsigned scid);
97   virtual ~Value();
98
99   /// dump - Support for debugging, callable in GDB: V->dump()
100   //
101   void dump() const;
102
103   /// print - Implement operator<< on Value.
104   ///
105   void print(raw_ostream &O, AssemblyAnnotationWriter *AAW = 0) const;
106
107   /// All values are typed, get the type of this value.
108   ///
109   inline const Type *getType() const { return VTy; }
110
111   /// All values hold a context through their type.
112   LLVMContext &getContext() const;
113
114   // All values can potentially be named...
115   inline bool hasName() const { return Name != 0; }
116   ValueName *getValueName() const { return Name; }
117   
118   /// getName() - Return a constant reference to the value's name. This is cheap
119   /// and guaranteed to return the same reference as long as the value is not
120   /// modified.
121   ///
122   /// This is currently guaranteed to return a StringRef for which data() points
123   /// to a valid null terminated string. The use of StringRef.data() is 
124   /// deprecated here, however, and clients should not rely on it. If such 
125   /// behavior is needed, clients should use expensive getNameStr(), or switch 
126   /// to an interface that does not depend on null termination.
127   StringRef getName() const;
128
129   /// getNameStr() - Return the name of the specified value, *constructing a
130   /// string* to hold it.  This is guaranteed to construct a string and is very
131   /// expensive, clients should use getName() unless necessary.
132   std::string getNameStr() const;
133
134   /// setName() - Change the name of the value, choosing a new unique name if
135   /// the provided name is taken.
136   ///
137   /// \arg 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   // uncheckedReplaceAllUsesWith - Just like replaceAllUsesWith but dangerous.
152   // Only use when in type resolution situations!
153   void uncheckedReplaceAllUsesWith(Value *V);
154
155   //----------------------------------------------------------------------
156   // Methods for handling the chain of uses of this Value.
157   //
158   typedef value_use_iterator<User>       use_iterator;
159   typedef value_use_iterator<const User> use_const_iterator;
160
161   bool               use_empty() const { return UseList == 0; }
162   use_iterator       use_begin()       { return use_iterator(UseList); }
163   use_const_iterator use_begin() const { return use_const_iterator(UseList); }
164   use_iterator       use_end()         { return use_iterator(0);   }
165   use_const_iterator use_end()   const { return use_const_iterator(0);   }
166   User              *use_back()        { return *use_begin(); }
167   const User        *use_back()  const { return *use_begin(); }
168
169   /// hasOneUse - Return true if there is exactly one user of this value.  This
170   /// is specialized because it is a common request and does not require
171   /// traversing the whole use list.
172   ///
173   bool hasOneUse() const {
174     use_const_iterator I = use_begin(), E = use_end();
175     if (I == E) return false;
176     return ++I == E;
177   }
178
179   /// hasNUses - Return true if this Value has exactly N users.
180   ///
181   bool hasNUses(unsigned N) const;
182
183   /// hasNUsesOrMore - Return true if this value has N users or more.  This is
184   /// logically equivalent to getNumUses() >= N.
185   ///
186   bool hasNUsesOrMore(unsigned N) const;
187
188   bool isUsedInBasicBlock(const BasicBlock *BB) const;
189
190   /// getNumUses - This method computes the number of uses of this Value.  This
191   /// is a linear time operation.  Use hasOneUse, hasNUses, or hasMoreThanNUses
192   /// to check for specific values.
193   unsigned getNumUses() const;
194
195   /// addUse - This method should only be used by the Use class.
196   ///
197   void addUse(Use &U) { U.addToList(&UseList); }
198
199   /// An enumeration for keeping track of the concrete subclass of Value that
200   /// is actually instantiated. Values of this enumeration are kept in the 
201   /// Value classes SubclassID field. They are used for concrete type
202   /// identification.
203   enum ValueTy {
204     ArgumentVal,              // This is an instance of Argument
205     BasicBlockVal,            // This is an instance of BasicBlock
206     FunctionVal,              // This is an instance of Function
207     GlobalAliasVal,           // This is an instance of GlobalAlias
208     GlobalVariableVal,        // This is an instance of GlobalVariable
209     UndefValueVal,            // This is an instance of UndefValue
210     BlockAddressVal,          // This is an instance of BlockAddress
211     ConstantExprVal,          // This is an instance of ConstantExpr
212     ConstantAggregateZeroVal, // This is an instance of ConstantAggregateNull
213     ConstantIntVal,           // This is an instance of ConstantInt
214     ConstantFPVal,            // This is an instance of ConstantFP
215     ConstantArrayVal,         // This is an instance of ConstantArray
216     ConstantStructVal,        // This is an instance of ConstantStruct
217     ConstantVectorVal,        // This is an instance of ConstantVector
218     ConstantPointerNullVal,   // This is an instance of ConstantPointerNull
219     MDNodeVal,                // This is an instance of MDNode
220     MDStringVal,              // This is an instance of MDString
221     NamedMDNodeVal,           // This is an instance of NamedMDNode
222     InlineAsmVal,             // This is an instance of InlineAsm
223     PseudoSourceValueVal,     // This is an instance of PseudoSourceValue
224     FixedStackPseudoSourceValueVal, // This is an instance of 
225                                     // FixedStackPseudoSourceValue
226     InstructionVal,           // This is an instance of Instruction
227     // Enum values starting at InstructionVal are used for Instructions;
228     // don't add new values here!
229
230     // Markers:
231     ConstantFirstVal = FunctionVal,
232     ConstantLastVal  = ConstantPointerNullVal
233   };
234
235   /// getValueID - Return an ID for the concrete type of this object.  This is
236   /// used to implement the classof checks.  This should not be used for any
237   /// other purpose, as the values may change as LLVM evolves.  Also, note that
238   /// for instructions, the Instruction's opcode is added to InstructionVal. So
239   /// this means three things:
240   /// # there is no value with code InstructionVal (no opcode==0).
241   /// # there are more possible values for the value type than in ValueTy enum.
242   /// # the InstructionVal enumerator must be the highest valued enumerator in
243   ///   the ValueTy enum.
244   unsigned getValueID() const {
245     return SubclassID;
246   }
247
248   /// getRawSubclassOptionalData - Return the raw optional flags value
249   /// contained in this value. This should only be used when testing two
250   /// Values for equivalence.
251   unsigned getRawSubclassOptionalData() const {
252     return SubclassOptionalData;
253   }
254
255   /// hasSameSubclassOptionalData - Test whether the optional flags contained
256   /// in this value are equal to the optional flags in the given value.
257   bool hasSameSubclassOptionalData(const Value *V) const {
258     return SubclassOptionalData == V->SubclassOptionalData;
259   }
260
261   /// intersectOptionalDataWith - Clear any optional flags in this value
262   /// that are not also set in the given value.
263   void intersectOptionalDataWith(const Value *V) {
264     SubclassOptionalData &= V->SubclassOptionalData;
265   }
266
267   // Methods for support type inquiry through isa, cast, and dyn_cast:
268   static inline bool classof(const Value *) {
269     return true; // Values are always values.
270   }
271
272   /// getRawType - This should only be used to implement the vmcore library.
273   ///
274   const Type *getRawType() const { return VTy.getRawType(); }
275
276   /// stripPointerCasts - This method strips off any unneeded pointer
277   /// casts from the specified value, returning the original uncasted value.
278   /// Note that the returned value has pointer type if the specified value does.
279   Value *stripPointerCasts();
280   const Value *stripPointerCasts() const {
281     return const_cast<Value*>(this)->stripPointerCasts();
282   }
283
284   /// getUnderlyingObject - This method strips off any GEP address adjustments
285   /// and pointer casts from the specified value, returning the original object
286   /// being addressed.  Note that the returned value has pointer type if the
287   /// specified value does.
288   Value *getUnderlyingObject();
289   const Value *getUnderlyingObject() const {
290     return const_cast<Value*>(this)->getUnderlyingObject();
291   }
292   
293   /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
294   /// return the value in the PHI node corresponding to PredBB.  If not, return
295   /// ourself.  This is useful if you want to know the value something has in a
296   /// predecessor block.
297   Value *DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB);
298
299   const Value *DoPHITranslation(const BasicBlock *CurBB,
300                                 const BasicBlock *PredBB) const{
301     return const_cast<Value*>(this)->DoPHITranslation(CurBB, PredBB);
302   }
303   
304 protected:
305   unsigned short getSubclassDataFromValue() const { return SubclassData; }
306   void setValueSubclassData(unsigned short D) { SubclassData = D; }
307 };
308
309 inline raw_ostream &operator<<(raw_ostream &OS, const Value &V) {
310   V.print(OS);
311   return OS;
312 }
313   
314 void Use::set(Value *V) {
315   if (Val) removeFromList();
316   Val = V;
317   if (V) V->addUse(*this);
318 }
319
320
321 // isa - Provide some specializations of isa so that we don't have to include
322 // the subtype header files to test to see if the value is a subclass...
323 //
324 template <> inline bool isa_impl<Constant, Value>(const Value &Val) {
325   return Val.getValueID() >= Value::ConstantFirstVal &&
326          Val.getValueID() <= Value::ConstantLastVal;
327 }
328 template <> inline bool isa_impl<Argument, Value>(const Value &Val) {
329   return Val.getValueID() == Value::ArgumentVal;
330 }
331 template <> inline bool isa_impl<InlineAsm, Value>(const Value &Val) {
332   return Val.getValueID() == Value::InlineAsmVal;
333 }
334 template <> inline bool isa_impl<Instruction, Value>(const Value &Val) {
335   return Val.getValueID() >= Value::InstructionVal;
336 }
337 template <> inline bool isa_impl<BasicBlock, Value>(const Value &Val) {
338   return Val.getValueID() == Value::BasicBlockVal;
339 }
340 template <> inline bool isa_impl<Function, Value>(const Value &Val) {
341   return Val.getValueID() == Value::FunctionVal;
342 }
343 template <> inline bool isa_impl<GlobalVariable, Value>(const Value &Val) {
344   return Val.getValueID() == Value::GlobalVariableVal;
345 }
346 template <> inline bool isa_impl<GlobalAlias, Value>(const Value &Val) {
347   return Val.getValueID() == Value::GlobalAliasVal;
348 }
349 template <> inline bool isa_impl<GlobalValue, Value>(const Value &Val) {
350   return isa<GlobalVariable>(Val) || isa<Function>(Val) ||
351          isa<GlobalAlias>(Val);
352 }
353   
354   
355 // Value* is only 4-byte aligned.
356 template<>
357 class PointerLikeTypeTraits<Value*> {
358   typedef Value* PT;
359 public:
360   static inline void *getAsVoidPointer(PT P) { return P; }
361   static inline PT getFromVoidPointer(void *P) {
362     return static_cast<PT>(P);
363   }
364   enum { NumLowBitsAvailable = 2 };
365 };
366
367 } // End llvm namespace
368
369 #endif