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/ADT/iterator_range.h"
19 #include "llvm/IR/Use.h"
20 #include "llvm/Support/CBindingWrapping.h"
21 #include "llvm/Support/Casting.h"
22 #include "llvm/Support/Compiler.h"
28 class AssemblyAnnotationWriter;
45 class ValueHandleBase;
46 class ValueSymbolTable;
49 template<typename ValueTy> class StringMapEntry;
50 typedef StringMapEntry<Value*> ValueName;
52 //===----------------------------------------------------------------------===//
54 //===----------------------------------------------------------------------===//
56 /// This is a very important LLVM class. It is the base class of all values
57 /// computed by a program that may be used as operands to other values. Value is
58 /// the super class of other important classes such as Instruction and Function.
59 /// All Values have a Type. Type is not a subclass of Value. Some values can
60 /// have a name and they belong to some Module. Setting the name on the Value
61 /// automatically updates the module's symbol table.
63 /// Every value has a "use list" that keeps track of which other Values are
64 /// using this Value. A Value can also have an arbitrary number of ValueHandle
65 /// objects that watch it and listen to RAUW and Destroy events. See
66 /// llvm/IR/ValueHandle.h for details.
68 /// @brief LLVM Value Representation
70 const unsigned char SubclassID; // Subclass identifier (for isa/dyn_cast)
71 unsigned char HasValueHandle : 1; // Has a ValueHandle pointing to this?
73 /// SubclassOptionalData - This member is similar to SubclassData, however it
74 /// is for holding information which may be used to aid optimization, but
75 /// which may be cleared to zero without affecting conservative
77 unsigned char SubclassOptionalData : 7;
80 template <typename UseT> // UseT == 'Use' or 'const Use'
81 class use_iterator_impl
82 : public std::iterator<std::forward_iterator_tag, UseT *, ptrdiff_t> {
83 typedef std::iterator<std::forward_iterator_tag, UseT *, ptrdiff_t> super;
86 explicit use_iterator_impl(UseT *u) : U(u) {}
90 typedef typename super::reference reference;
91 typedef typename super::pointer pointer;
93 use_iterator_impl() : U() {}
95 bool operator==(const use_iterator_impl &x) const { return U == x.U; }
96 bool operator!=(const use_iterator_impl &x) const { return !operator==(x); }
98 use_iterator_impl &operator++() { // Preincrement
99 assert(U && "Cannot increment end iterator!");
103 use_iterator_impl operator++(int) { // Postincrement
109 UseT &operator*() const {
110 assert(U && "Cannot dereference end iterator!");
114 UseT *operator->() const { return &operator*(); }
116 operator use_iterator_impl<const UseT>() const {
117 return use_iterator_impl<const UseT>(U);
121 template <typename UserTy> // UserTy == 'User' or 'const User'
122 class user_iterator_impl
123 : public std::iterator<std::forward_iterator_tag, UserTy *, ptrdiff_t> {
124 typedef std::iterator<std::forward_iterator_tag, UserTy *, ptrdiff_t> super;
126 use_iterator_impl<Use> UI;
127 explicit user_iterator_impl(Use *U) : UI(U) {}
131 typedef typename super::reference reference;
132 typedef typename super::pointer pointer;
134 user_iterator_impl() {}
136 bool operator==(const user_iterator_impl &x) const { return UI == x.UI; }
137 bool operator!=(const user_iterator_impl &x) const { return !operator==(x); }
139 /// \brief Returns true if this iterator is equal to user_end() on the value.
140 bool atEnd() const { return *this == user_iterator_impl(); }
142 user_iterator_impl &operator++() { // Preincrement
146 user_iterator_impl operator++(int) { // Postincrement
152 // Retrieve a pointer to the current User.
153 UserTy *operator*() const {
154 return UI->getUser();
157 UserTy *operator->() const { return operator*(); }
159 operator user_iterator_impl<const UserTy>() const {
160 return user_iterator_impl<const UserTy>(*UI);
163 Use &getUse() const { return *UI; }
165 /// \brief Return the operand # of this use in its User.
166 /// FIXME: Replace all callers with a direct call to Use::getOperandNo.
167 unsigned getOperandNo() const { return UI->getOperandNo(); }
170 /// SubclassData - This member is defined by this class, but is not used for
171 /// anything. Subclasses can use it to hold whatever state they find useful.
172 /// This field is initialized to zero by the ctor.
173 unsigned short SubclassData;
178 friend class ValueSymbolTable; // Allow ValueSymbolTable to directly mod Name.
179 friend class ValueHandleBase;
182 void operator=(const Value &) LLVM_DELETED_FUNCTION;
183 Value(const Value &) LLVM_DELETED_FUNCTION;
186 Value(Type *Ty, unsigned scid);
190 /// dump - Support for debugging, callable in GDB: V->dump()
194 /// print - Implement operator<< on Value.
196 void print(raw_ostream &O) const;
198 /// \brief Print the name of this Value out to the specified raw_ostream.
199 /// This is useful when you just want to print 'int %reg126', not the
200 /// instruction that generated it. If you specify a Module for context, then
201 /// even constanst get pretty-printed; for example, the type of a null
202 /// pointer is printed symbolically.
203 void printAsOperand(raw_ostream &O, bool PrintType = true,
204 const Module *M = nullptr) const;
206 /// All values are typed, get the type of this value.
208 Type *getType() const { return VTy; }
210 /// All values hold a context through their type.
211 LLVMContext &getContext() const;
213 // All values can potentially be named.
214 bool hasName() const { return Name != nullptr && SubclassID != MDStringVal; }
215 ValueName *getValueName() const { return Name; }
216 void setValueName(ValueName *VN) { Name = VN; }
218 /// getName() - Return a constant reference to the value's name. This is cheap
219 /// and guaranteed to return the same reference as long as the value is not
221 StringRef getName() const;
223 /// setName() - Change the name of the value, choosing a new unique name if
224 /// the provided name is taken.
226 /// \param Name The new name; or "" if the value's name should be removed.
227 void setName(const Twine &Name);
230 /// takeName - transfer the name from V to this value, setting V's name to
231 /// empty. It is an error to call V->takeName(V).
232 void takeName(Value *V);
234 /// replaceAllUsesWith - Go through the uses list for this definition and make
235 /// each use point to "V" instead of "this". After this completes, 'this's
236 /// use list is guaranteed to be empty.
238 void replaceAllUsesWith(Value *V);
240 //----------------------------------------------------------------------
241 // Methods for handling the chain of uses of this Value.
243 bool use_empty() const { return UseList == nullptr; }
245 typedef use_iterator_impl<Use> use_iterator;
246 typedef use_iterator_impl<const Use> const_use_iterator;
247 use_iterator use_begin() { return use_iterator(UseList); }
248 const_use_iterator use_begin() const { return const_use_iterator(UseList); }
249 use_iterator use_end() { return use_iterator(); }
250 const_use_iterator use_end() const { return const_use_iterator(); }
251 iterator_range<use_iterator> uses() {
252 return iterator_range<use_iterator>(use_begin(), use_end());
254 iterator_range<const_use_iterator> uses() const {
255 return iterator_range<const_use_iterator>(use_begin(), use_end());
258 typedef user_iterator_impl<User> user_iterator;
259 typedef user_iterator_impl<const User> const_user_iterator;
260 user_iterator user_begin() { return user_iterator(UseList); }
261 const_user_iterator user_begin() const { return const_user_iterator(UseList); }
262 user_iterator user_end() { return user_iterator(); }
263 const_user_iterator user_end() const { return const_user_iterator(); }
264 User *user_back() { return *user_begin(); }
265 const User *user_back() const { return *user_begin(); }
266 iterator_range<user_iterator> users() {
267 return iterator_range<user_iterator>(user_begin(), user_end());
269 iterator_range<const_user_iterator> users() const {
270 return iterator_range<const_user_iterator>(user_begin(), user_end());
273 /// hasOneUse - Return true if there is exactly one user of this value. This
274 /// is specialized because it is a common request and does not require
275 /// traversing the whole use list.
277 bool hasOneUse() const {
278 const_use_iterator I = use_begin(), E = use_end();
279 if (I == E) return false;
283 /// hasNUses - Return true if this Value has exactly N users.
285 bool hasNUses(unsigned N) const;
287 /// hasNUsesOrMore - Return true if this value has N users or more. This is
288 /// logically equivalent to getNumUses() >= N.
290 bool hasNUsesOrMore(unsigned N) const;
292 bool isUsedInBasicBlock(const BasicBlock *BB) const;
294 /// getNumUses - This method computes the number of uses of this Value. This
295 /// is a linear time operation. Use hasOneUse, hasNUses, or hasNUsesOrMore
296 /// to check for specific values.
297 unsigned getNumUses() const;
299 /// addUse - This method should only be used by the Use class.
301 void addUse(Use &U) { U.addToList(&UseList); }
303 /// An enumeration for keeping track of the concrete subclass of Value that
304 /// is actually instantiated. Values of this enumeration are kept in the
305 /// Value classes SubclassID field. They are used for concrete type
308 ArgumentVal, // This is an instance of Argument
309 BasicBlockVal, // This is an instance of BasicBlock
310 FunctionVal, // This is an instance of Function
311 GlobalAliasVal, // This is an instance of GlobalAlias
312 GlobalVariableVal, // This is an instance of GlobalVariable
313 UndefValueVal, // This is an instance of UndefValue
314 BlockAddressVal, // This is an instance of BlockAddress
315 ConstantExprVal, // This is an instance of ConstantExpr
316 ConstantAggregateZeroVal, // This is an instance of ConstantAggregateZero
317 ConstantDataArrayVal, // This is an instance of ConstantDataArray
318 ConstantDataVectorVal, // This is an instance of ConstantDataVector
319 ConstantIntVal, // This is an instance of ConstantInt
320 ConstantFPVal, // This is an instance of ConstantFP
321 ConstantArrayVal, // This is an instance of ConstantArray
322 ConstantStructVal, // This is an instance of ConstantStruct
323 ConstantVectorVal, // This is an instance of ConstantVector
324 ConstantPointerNullVal, // This is an instance of ConstantPointerNull
325 MDNodeVal, // This is an instance of MDNode
326 MDStringVal, // This is an instance of MDString
327 InlineAsmVal, // This is an instance of InlineAsm
328 InstructionVal, // This is an instance of Instruction
329 // Enum values starting at InstructionVal are used for Instructions;
330 // don't add new values here!
333 ConstantFirstVal = FunctionVal,
334 ConstantLastVal = ConstantPointerNullVal
337 /// getValueID - Return an ID for the concrete type of this object. This is
338 /// used to implement the classof checks. This should not be used for any
339 /// other purpose, as the values may change as LLVM evolves. Also, note that
340 /// for instructions, the Instruction's opcode is added to InstructionVal. So
341 /// this means three things:
342 /// # there is no value with code InstructionVal (no opcode==0).
343 /// # there are more possible values for the value type than in ValueTy enum.
344 /// # the InstructionVal enumerator must be the highest valued enumerator in
345 /// the ValueTy enum.
346 unsigned getValueID() const {
350 /// getRawSubclassOptionalData - Return the raw optional flags value
351 /// contained in this value. This should only be used when testing two
352 /// Values for equivalence.
353 unsigned getRawSubclassOptionalData() const {
354 return SubclassOptionalData;
357 /// clearSubclassOptionalData - Clear the optional flags contained in
359 void clearSubclassOptionalData() {
360 SubclassOptionalData = 0;
363 /// hasSameSubclassOptionalData - Test whether the optional flags contained
364 /// in this value are equal to the optional flags in the given value.
365 bool hasSameSubclassOptionalData(const Value *V) const {
366 return SubclassOptionalData == V->SubclassOptionalData;
369 /// intersectOptionalDataWith - Clear any optional flags in this value
370 /// that are not also set in the given value.
371 void intersectOptionalDataWith(const Value *V) {
372 SubclassOptionalData &= V->SubclassOptionalData;
375 /// hasValueHandle - Return true if there is a value handle associated with
377 bool hasValueHandle() const { return HasValueHandle; }
379 /// \brief Strips off any unneeded pointer casts, all-zero GEPs and aliases
380 /// from the specified value, returning the original uncasted value.
382 /// If this is called on a non-pointer value, it returns 'this'.
383 Value *stripPointerCasts();
384 const Value *stripPointerCasts() const {
385 return const_cast<Value*>(this)->stripPointerCasts();
388 /// \brief Strips off any unneeded pointer casts and all-zero GEPs from the
389 /// specified value, returning the original uncasted value.
391 /// If this is called on a non-pointer value, it returns 'this'.
392 Value *stripPointerCastsNoFollowAliases();
393 const Value *stripPointerCastsNoFollowAliases() const {
394 return const_cast<Value*>(this)->stripPointerCastsNoFollowAliases();
397 /// \brief Strips off unneeded pointer casts and all-constant GEPs from the
398 /// specified value, returning the original pointer value.
400 /// If this is called on a non-pointer value, it returns 'this'.
401 Value *stripInBoundsConstantOffsets();
402 const Value *stripInBoundsConstantOffsets() const {
403 return const_cast<Value*>(this)->stripInBoundsConstantOffsets();
406 /// \brief Strips like \c stripInBoundsConstantOffsets but also accumulates
407 /// the constant offset stripped.
409 /// Stores the resulting constant offset stripped into the APInt provided.
410 /// The provided APInt will be extended or truncated as needed to be the
411 /// correct bitwidth for an offset of this pointer type.
413 /// If this is called on a non-pointer value, it returns 'this'.
414 Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
416 const Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
417 APInt &Offset) const {
418 return const_cast<Value *>(this)
419 ->stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
422 /// \brief Strips off unneeded pointer casts and any in-bounds offsets from
423 /// the specified value, returning the original pointer value.
425 /// If this is called on a non-pointer value, it returns 'this'.
426 Value *stripInBoundsOffsets();
427 const Value *stripInBoundsOffsets() const {
428 return const_cast<Value*>(this)->stripInBoundsOffsets();
431 /// isDereferenceablePointer - Test if this value is always a pointer to
432 /// allocated and suitably aligned memory for a simple load or store.
433 bool isDereferenceablePointer() const;
435 /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
436 /// return the value in the PHI node corresponding to PredBB. If not, return
437 /// ourself. This is useful if you want to know the value something has in a
438 /// predecessor block.
439 Value *DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB);
441 const Value *DoPHITranslation(const BasicBlock *CurBB,
442 const BasicBlock *PredBB) const{
443 return const_cast<Value*>(this)->DoPHITranslation(CurBB, PredBB);
446 /// MaximumAlignment - This is the greatest alignment value supported by
447 /// load, store, and alloca instructions, and global values.
448 static const unsigned MaximumAlignment = 1u << 29;
450 /// mutateType - Mutate the type of this Value to be of the specified type.
451 /// Note that this is an extremely dangerous operation which can create
452 /// completely invalid IR very easily. It is strongly recommended that you
453 /// recreate IR objects with the right types instead of mutating them in
455 void mutateType(Type *Ty) {
460 unsigned short getSubclassDataFromValue() const { return SubclassData; }
461 void setValueSubclassData(unsigned short D) { SubclassData = D; }
464 inline raw_ostream &operator<<(raw_ostream &OS, const Value &V) {
469 void Use::set(Value *V) {
470 if (Val) removeFromList();
472 if (V) V->addUse(*this);
476 // isa - Provide some specializations of isa so that we don't have to include
477 // the subtype header files to test to see if the value is a subclass...
479 template <> struct isa_impl<Constant, Value> {
480 static inline bool doit(const Value &Val) {
481 return Val.getValueID() >= Value::ConstantFirstVal &&
482 Val.getValueID() <= Value::ConstantLastVal;
486 template <> struct isa_impl<Argument, Value> {
487 static inline bool doit (const Value &Val) {
488 return Val.getValueID() == Value::ArgumentVal;
492 template <> struct isa_impl<InlineAsm, Value> {
493 static inline bool doit(const Value &Val) {
494 return Val.getValueID() == Value::InlineAsmVal;
498 template <> struct isa_impl<Instruction, Value> {
499 static inline bool doit(const Value &Val) {
500 return Val.getValueID() >= Value::InstructionVal;
504 template <> struct isa_impl<BasicBlock, Value> {
505 static inline bool doit(const Value &Val) {
506 return Val.getValueID() == Value::BasicBlockVal;
510 template <> struct isa_impl<Function, Value> {
511 static inline bool doit(const Value &Val) {
512 return Val.getValueID() == Value::FunctionVal;
516 template <> struct isa_impl<GlobalVariable, Value> {
517 static inline bool doit(const Value &Val) {
518 return Val.getValueID() == Value::GlobalVariableVal;
522 template <> struct isa_impl<GlobalAlias, Value> {
523 static inline bool doit(const Value &Val) {
524 return Val.getValueID() == Value::GlobalAliasVal;
528 template <> struct isa_impl<GlobalValue, Value> {
529 static inline bool doit(const Value &Val) {
530 return isa<GlobalObject>(Val) || isa<GlobalAlias>(Val);
534 template <> struct isa_impl<GlobalObject, Value> {
535 static inline bool doit(const Value &Val) {
536 return isa<GlobalVariable>(Val) || isa<Function>(Val);
540 template <> struct isa_impl<MDNode, Value> {
541 static inline bool doit(const Value &Val) {
542 return Val.getValueID() == Value::MDNodeVal;
546 // Value* is only 4-byte aligned.
548 class PointerLikeTypeTraits<Value*> {
551 static inline void *getAsVoidPointer(PT P) { return P; }
552 static inline PT getFromVoidPointer(void *P) {
553 return static_cast<PT>(P);
555 enum { NumLowBitsAvailable = 2 };
558 // Create wrappers for C Binding types (see CBindingWrapping.h).
559 DEFINE_ISA_CONVERSION_FUNCTIONS(Value, LLVMValueRef)
561 /* Specialized opaque value conversions.
563 inline Value **unwrap(LLVMValueRef *Vals) {
564 return reinterpret_cast<Value**>(Vals);
568 inline T **unwrap(LLVMValueRef *Vals, unsigned Length) {
570 for (LLVMValueRef *I = Vals, *E = Vals + Length; I != E; ++I)
574 return reinterpret_cast<T**>(Vals);
577 inline LLVMValueRef *wrap(const Value **Vals) {
578 return reinterpret_cast<LLVMValueRef*>(const_cast<Value**>(Vals));
581 } // End llvm namespace