1 //===-- llvm/Value.h - Definition of the Value class ------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file declares the Value class.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_IR_VALUE_H
15 #define LLVM_IR_VALUE_H
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"
27 class AssemblyAnnotationWriter;
43 class ValueHandleBase;
44 class ValueSymbolTable;
47 template<typename ValueTy> class StringMapEntry;
48 typedef StringMapEntry<Value*> ValueName;
50 //===----------------------------------------------------------------------===//
52 //===----------------------------------------------------------------------===//
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.
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/IR/ValueHandle.h for details.
66 /// @brief LLVM Value Representation
68 const unsigned char SubclassID; // Subclass identifier (for isa/dyn_cast)
69 unsigned char HasValueHandle : 1; // Has a ValueHandle pointing to this?
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
75 unsigned char SubclassOptionalData : 7;
78 template <typename UserTy> // UserTy == 'User' or 'const User'
79 class user_iterator_impl
80 : public std::iterator<std::forward_iterator_tag, UserTy *, ptrdiff_t> {
81 typedef std::iterator<std::forward_iterator_tag, UserTy *, ptrdiff_t> super;
84 explicit user_iterator_impl(Use *u) : U(u) {}
88 typedef typename super::reference reference;
89 typedef typename super::pointer pointer;
91 user_iterator_impl() {}
93 bool operator==(const user_iterator_impl &x) const { return U == x.U; }
94 bool operator!=(const user_iterator_impl &x) const { return !operator==(x); }
96 /// \brief Returns true if this iterator is equal to use_end() on the value.
97 bool atEnd() const { return U == 0; }
99 // Iterator traversal: forward iteration only
100 user_iterator_impl &operator++() { // Preincrement
101 assert(U && "Cannot increment end iterator!");
105 user_iterator_impl operator++(int) { // Postincrement
111 // Retrieve a pointer to the current User.
112 UserTy *operator*() const {
113 assert(U && "Cannot dereference end iterator!");
117 UserTy *operator->() const { return operator*(); }
119 operator user_iterator_impl<const UserTy>() const {
120 return user_iterator_impl<const UserTy>(U);
123 Use &getUse() const { return *U; }
125 /// \brief Return the operand # of this use in its User.
126 /// FIXME: Replace all callers with a direct call to Use::getOperandNo.
127 unsigned getOperandNo() const { return U->getOperandNo(); }
130 /// SubclassData - This member is defined by this class, but is not used for
131 /// anything. Subclasses can use it to hold whatever state they find useful.
132 /// This field is initialized to zero by the ctor.
133 unsigned short SubclassData;
138 friend class ValueSymbolTable; // Allow ValueSymbolTable to directly mod Name.
139 friend class ValueHandleBase;
142 void operator=(const Value &) LLVM_DELETED_FUNCTION;
143 Value(const Value &) LLVM_DELETED_FUNCTION;
146 /// printCustom - Value subclasses can override this to implement custom
147 /// printing behavior.
148 virtual void printCustom(raw_ostream &O) const;
150 Value(Type *Ty, unsigned scid);
154 /// dump - Support for debugging, callable in GDB: V->dump()
158 /// print - Implement operator<< on Value.
160 void print(raw_ostream &O, AssemblyAnnotationWriter *AAW = 0) const;
162 /// \brief Print the name of this Value out to the specified raw_ostream.
163 /// This is useful when you just want to print 'int %reg126', not the
164 /// instruction that generated it. If you specify a Module for context, then
165 /// even constanst get pretty-printed; for example, the type of a null
166 /// pointer is printed symbolically.
167 void printAsOperand(raw_ostream &O, bool PrintType = true, const Module *M = 0) const;
169 /// All values are typed, get the type of this value.
171 Type *getType() const { return VTy; }
173 /// All values hold a context through their type.
174 LLVMContext &getContext() const;
176 // All values can potentially be named.
177 bool hasName() const { return Name != 0 && SubclassID != MDStringVal; }
178 ValueName *getValueName() const { return Name; }
179 void setValueName(ValueName *VN) { Name = VN; }
181 /// getName() - Return a constant reference to the value's name. This is cheap
182 /// and guaranteed to return the same reference as long as the value is not
184 StringRef getName() const;
186 /// setName() - Change the name of the value, choosing a new unique name if
187 /// the provided name is taken.
189 /// \param Name The new name; or "" if the value's name should be removed.
190 void setName(const Twine &Name);
193 /// takeName - transfer the name from V to this value, setting V's name to
194 /// empty. It is an error to call V->takeName(V).
195 void takeName(Value *V);
197 /// replaceAllUsesWith - Go through the uses list for this definition and make
198 /// each use point to "V" instead of "this". After this completes, 'this's
199 /// use list is guaranteed to be empty.
201 void replaceAllUsesWith(Value *V);
203 //----------------------------------------------------------------------
204 // Methods for handling the chain of uses of this Value.
206 bool use_empty() const { return UseList == 0; }
208 typedef user_iterator_impl<User> use_iterator;
209 typedef user_iterator_impl<const User> const_use_iterator;
210 use_iterator use_begin() { return use_iterator(UseList); }
211 const_use_iterator use_begin() const { return const_use_iterator(UseList); }
212 use_iterator use_end() { return use_iterator(0); }
213 const_use_iterator use_end() const { return const_use_iterator(0); }
214 User *use_back() { return *use_begin(); }
215 const User *use_back() const { return *use_begin(); }
217 /// hasOneUse - Return true if there is exactly one user of this value. This
218 /// is specialized because it is a common request and does not require
219 /// traversing the whole use list.
221 bool hasOneUse() const {
222 const_use_iterator I = use_begin(), E = use_end();
223 if (I == E) return false;
227 /// hasNUses - Return true if this Value has exactly N users.
229 bool hasNUses(unsigned N) const;
231 /// hasNUsesOrMore - Return true if this value has N users or more. This is
232 /// logically equivalent to getNumUses() >= N.
234 bool hasNUsesOrMore(unsigned N) const;
236 bool isUsedInBasicBlock(const BasicBlock *BB) const;
238 /// getNumUses - This method computes the number of uses of this Value. This
239 /// is a linear time operation. Use hasOneUse, hasNUses, or hasNUsesOrMore
240 /// to check for specific values.
241 unsigned getNumUses() const;
243 /// addUse - This method should only be used by the Use class.
245 void addUse(Use &U) { U.addToList(&UseList); }
247 /// An enumeration for keeping track of the concrete subclass of Value that
248 /// is actually instantiated. Values of this enumeration are kept in the
249 /// Value classes SubclassID field. They are used for concrete type
252 ArgumentVal, // This is an instance of Argument
253 BasicBlockVal, // This is an instance of BasicBlock
254 FunctionVal, // This is an instance of Function
255 GlobalAliasVal, // This is an instance of GlobalAlias
256 GlobalVariableVal, // This is an instance of GlobalVariable
257 UndefValueVal, // This is an instance of UndefValue
258 BlockAddressVal, // This is an instance of BlockAddress
259 ConstantExprVal, // This is an instance of ConstantExpr
260 ConstantAggregateZeroVal, // This is an instance of ConstantAggregateZero
261 ConstantDataArrayVal, // This is an instance of ConstantDataArray
262 ConstantDataVectorVal, // This is an instance of ConstantDataVector
263 ConstantIntVal, // This is an instance of ConstantInt
264 ConstantFPVal, // This is an instance of ConstantFP
265 ConstantArrayVal, // This is an instance of ConstantArray
266 ConstantStructVal, // This is an instance of ConstantStruct
267 ConstantVectorVal, // This is an instance of ConstantVector
268 ConstantPointerNullVal, // This is an instance of ConstantPointerNull
269 MDNodeVal, // This is an instance of MDNode
270 MDStringVal, // This is an instance of MDString
271 InlineAsmVal, // This is an instance of InlineAsm
272 PseudoSourceValueVal, // This is an instance of PseudoSourceValue
273 FixedStackPseudoSourceValueVal, // This is an instance of
274 // FixedStackPseudoSourceValue
275 InstructionVal, // This is an instance of Instruction
276 // Enum values starting at InstructionVal are used for Instructions;
277 // don't add new values here!
280 ConstantFirstVal = FunctionVal,
281 ConstantLastVal = ConstantPointerNullVal
284 /// getValueID - Return an ID for the concrete type of this object. This is
285 /// used to implement the classof checks. This should not be used for any
286 /// other purpose, as the values may change as LLVM evolves. Also, note that
287 /// for instructions, the Instruction's opcode is added to InstructionVal. So
288 /// this means three things:
289 /// # there is no value with code InstructionVal (no opcode==0).
290 /// # there are more possible values for the value type than in ValueTy enum.
291 /// # the InstructionVal enumerator must be the highest valued enumerator in
292 /// the ValueTy enum.
293 unsigned getValueID() const {
297 /// getRawSubclassOptionalData - Return the raw optional flags value
298 /// contained in this value. This should only be used when testing two
299 /// Values for equivalence.
300 unsigned getRawSubclassOptionalData() const {
301 return SubclassOptionalData;
304 /// clearSubclassOptionalData - Clear the optional flags contained in
306 void clearSubclassOptionalData() {
307 SubclassOptionalData = 0;
310 /// hasSameSubclassOptionalData - Test whether the optional flags contained
311 /// in this value are equal to the optional flags in the given value.
312 bool hasSameSubclassOptionalData(const Value *V) const {
313 return SubclassOptionalData == V->SubclassOptionalData;
316 /// intersectOptionalDataWith - Clear any optional flags in this value
317 /// that are not also set in the given value.
318 void intersectOptionalDataWith(const Value *V) {
319 SubclassOptionalData &= V->SubclassOptionalData;
322 /// hasValueHandle - Return true if there is a value handle associated with
324 bool hasValueHandle() const { return HasValueHandle; }
326 /// \brief Strips off any unneeded pointer casts, all-zero GEPs and aliases
327 /// from the specified value, returning the original uncasted value.
329 /// If this is called on a non-pointer value, it returns 'this'.
330 Value *stripPointerCasts();
331 const Value *stripPointerCasts() const {
332 return const_cast<Value*>(this)->stripPointerCasts();
335 /// \brief Strips off any unneeded pointer casts and all-zero GEPs from the
336 /// specified value, returning the original uncasted value.
338 /// If this is called on a non-pointer value, it returns 'this'.
339 Value *stripPointerCastsNoFollowAliases();
340 const Value *stripPointerCastsNoFollowAliases() const {
341 return const_cast<Value*>(this)->stripPointerCastsNoFollowAliases();
344 /// \brief Strips off unneeded pointer casts and all-constant GEPs from the
345 /// specified value, returning the original pointer value.
347 /// If this is called on a non-pointer value, it returns 'this'.
348 Value *stripInBoundsConstantOffsets();
349 const Value *stripInBoundsConstantOffsets() const {
350 return const_cast<Value*>(this)->stripInBoundsConstantOffsets();
353 /// \brief Strips like \c stripInBoundsConstantOffsets but also accumulates
354 /// the constant offset stripped.
356 /// Stores the resulting constant offset stripped into the APInt provided.
357 /// The provided APInt will be extended or truncated as needed to be the
358 /// correct bitwidth for an offset of this pointer type.
360 /// If this is called on a non-pointer value, it returns 'this'.
361 Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
363 const Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
364 APInt &Offset) const {
365 return const_cast<Value *>(this)
366 ->stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
369 /// \brief Strips off unneeded pointer casts and any in-bounds offsets from
370 /// the specified value, returning the original pointer value.
372 /// If this is called on a non-pointer value, it returns 'this'.
373 Value *stripInBoundsOffsets();
374 const Value *stripInBoundsOffsets() const {
375 return const_cast<Value*>(this)->stripInBoundsOffsets();
378 /// isDereferenceablePointer - Test if this value is always a pointer to
379 /// allocated and suitably aligned memory for a simple load or store.
380 bool isDereferenceablePointer() const;
382 /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
383 /// return the value in the PHI node corresponding to PredBB. If not, return
384 /// ourself. This is useful if you want to know the value something has in a
385 /// predecessor block.
386 Value *DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB);
388 const Value *DoPHITranslation(const BasicBlock *CurBB,
389 const BasicBlock *PredBB) const{
390 return const_cast<Value*>(this)->DoPHITranslation(CurBB, PredBB);
393 /// MaximumAlignment - This is the greatest alignment value supported by
394 /// load, store, and alloca instructions, and global values.
395 static const unsigned MaximumAlignment = 1u << 29;
397 /// mutateType - Mutate the type of this Value to be of the specified type.
398 /// Note that this is an extremely dangerous operation which can create
399 /// completely invalid IR very easily. It is strongly recommended that you
400 /// recreate IR objects with the right types instead of mutating them in
402 void mutateType(Type *Ty) {
407 unsigned short getSubclassDataFromValue() const { return SubclassData; }
408 void setValueSubclassData(unsigned short D) { SubclassData = D; }
411 inline raw_ostream &operator<<(raw_ostream &OS, const Value &V) {
416 void Use::set(Value *V) {
417 if (Val) removeFromList();
419 if (V) V->addUse(*this);
423 // isa - Provide some specializations of isa so that we don't have to include
424 // the subtype header files to test to see if the value is a subclass...
426 template <> struct isa_impl<Constant, Value> {
427 static inline bool doit(const Value &Val) {
428 return Val.getValueID() >= Value::ConstantFirstVal &&
429 Val.getValueID() <= Value::ConstantLastVal;
433 template <> struct isa_impl<Argument, Value> {
434 static inline bool doit (const Value &Val) {
435 return Val.getValueID() == Value::ArgumentVal;
439 template <> struct isa_impl<InlineAsm, Value> {
440 static inline bool doit(const Value &Val) {
441 return Val.getValueID() == Value::InlineAsmVal;
445 template <> struct isa_impl<Instruction, Value> {
446 static inline bool doit(const Value &Val) {
447 return Val.getValueID() >= Value::InstructionVal;
451 template <> struct isa_impl<BasicBlock, Value> {
452 static inline bool doit(const Value &Val) {
453 return Val.getValueID() == Value::BasicBlockVal;
457 template <> struct isa_impl<Function, Value> {
458 static inline bool doit(const Value &Val) {
459 return Val.getValueID() == Value::FunctionVal;
463 template <> struct isa_impl<GlobalVariable, Value> {
464 static inline bool doit(const Value &Val) {
465 return Val.getValueID() == Value::GlobalVariableVal;
469 template <> struct isa_impl<GlobalAlias, Value> {
470 static inline bool doit(const Value &Val) {
471 return Val.getValueID() == Value::GlobalAliasVal;
475 template <> struct isa_impl<GlobalValue, Value> {
476 static inline bool doit(const Value &Val) {
477 return isa<GlobalVariable>(Val) || isa<Function>(Val) ||
478 isa<GlobalAlias>(Val);
482 template <> struct isa_impl<MDNode, Value> {
483 static inline bool doit(const Value &Val) {
484 return Val.getValueID() == Value::MDNodeVal;
488 // Value* is only 4-byte aligned.
490 class PointerLikeTypeTraits<Value*> {
493 static inline void *getAsVoidPointer(PT P) { return P; }
494 static inline PT getFromVoidPointer(void *P) {
495 return static_cast<PT>(P);
497 enum { NumLowBitsAvailable = 2 };
500 // Create wrappers for C Binding types (see CBindingWrapping.h).
501 DEFINE_ISA_CONVERSION_FUNCTIONS(Value, LLVMValueRef)
503 /* Specialized opaque value conversions.
505 inline Value **unwrap(LLVMValueRef *Vals) {
506 return reinterpret_cast<Value**>(Vals);
510 inline T **unwrap(LLVMValueRef *Vals, unsigned Length) {
512 for (LLVMValueRef *I = Vals, *E = Vals + Length; I != E; ++I)
516 return reinterpret_cast<T**>(Vals);
519 inline LLVMValueRef *wrap(const Value **Vals) {
520 return reinterpret_cast<LLVMValueRef*>(const_cast<Value**>(Vals));
523 } // End llvm namespace