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