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