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
73 friend class ValueSymbolTable; // Allow ValueSymbolTable to directly mod Name.
74 friend class ValueHandleBase;
77 const unsigned char SubclassID; // Subclass identifier (for isa/dyn_cast)
78 unsigned char HasValueHandle : 1; // Has a ValueHandle pointing to this?
80 /// SubclassOptionalData - This member is similar to SubclassData, however it
81 /// is for holding information which may be used to aid optimization, but
82 /// which may be cleared to zero without affecting conservative
84 unsigned char SubclassOptionalData : 7;
87 /// SubclassData - This member is defined by this class, but is not used for
88 /// anything. Subclasses can use it to hold whatever state they find useful.
89 /// This field is initialized to zero by the ctor.
90 unsigned short SubclassData;
92 template <typename UseT> // UseT == 'Use' or 'const Use'
93 class use_iterator_impl
94 : public std::iterator<std::forward_iterator_tag, UseT *, ptrdiff_t> {
95 typedef std::iterator<std::forward_iterator_tag, UseT *, ptrdiff_t> super;
98 explicit use_iterator_impl(UseT *u) : U(u) {}
102 typedef typename super::reference reference;
103 typedef typename super::pointer pointer;
105 use_iterator_impl() : U() {}
107 bool operator==(const use_iterator_impl &x) const { return U == x.U; }
108 bool operator!=(const use_iterator_impl &x) const { return !operator==(x); }
110 use_iterator_impl &operator++() { // Preincrement
111 assert(U && "Cannot increment end iterator!");
115 use_iterator_impl operator++(int) { // Postincrement
121 UseT &operator*() const {
122 assert(U && "Cannot dereference end iterator!");
126 UseT *operator->() const { return &operator*(); }
128 operator use_iterator_impl<const UseT>() const {
129 return use_iterator_impl<const UseT>(U);
133 template <typename UserTy> // UserTy == 'User' or 'const User'
134 class user_iterator_impl
135 : public std::iterator<std::forward_iterator_tag, UserTy *, ptrdiff_t> {
136 typedef std::iterator<std::forward_iterator_tag, UserTy *, ptrdiff_t> super;
138 use_iterator_impl<Use> UI;
139 explicit user_iterator_impl(Use *U) : UI(U) {}
143 typedef typename super::reference reference;
144 typedef typename super::pointer pointer;
146 user_iterator_impl() {}
148 bool operator==(const user_iterator_impl &x) const { return UI == x.UI; }
149 bool operator!=(const user_iterator_impl &x) const { return !operator==(x); }
151 /// \brief Returns true if this iterator is equal to user_end() on the value.
152 bool atEnd() const { return *this == user_iterator_impl(); }
154 user_iterator_impl &operator++() { // Preincrement
158 user_iterator_impl operator++(int) { // Postincrement
164 // Retrieve a pointer to the current User.
165 UserTy *operator*() const {
166 return UI->getUser();
169 UserTy *operator->() const { return operator*(); }
171 operator user_iterator_impl<const UserTy>() const {
172 return user_iterator_impl<const UserTy>(*UI);
175 Use &getUse() const { return *UI; }
177 /// \brief Return the operand # of this use in its User.
178 /// FIXME: Replace all callers with a direct call to Use::getOperandNo.
179 unsigned getOperandNo() const { return UI->getOperandNo(); }
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 DataLayout *DL = nullptr) 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) {
459 /// \brief Sort the use-list.
461 /// Sorts the Value's use-list by Cmp using a stable mergesort. Cmp is
462 /// expected to compare two \a Use references.
463 template <class Compare> void sortUseList(Compare Cmp);
466 /// \brief Merge two lists together.
468 /// Merges \c L and \c R using \c Cmp. To enable stable sorts, always pushes
469 /// "equal" items from L before items from R.
471 /// \return the first element in the list.
473 /// \note Completely ignores \a Prev (doesn't read, doesn't update).
474 template <class Compare>
475 static Use *mergeUseLists(Use *L, Use *R, Compare Cmp) {
477 mergeUseListsImpl(L, R, &Merged, Cmp);
481 /// \brief Tail-recursive helper for \a mergeUseLists().
483 /// \param[out] Next the first element in the list.
484 template <class Compare>
485 static void mergeUseListsImpl(Use *L, Use *R, Use **Next, Compare Cmp);
488 unsigned short getSubclassDataFromValue() const { return SubclassData; }
489 void setValueSubclassData(unsigned short D) { SubclassData = D; }
492 inline raw_ostream &operator<<(raw_ostream &OS, const Value &V) {
497 void Use::set(Value *V) {
498 if (Val) removeFromList();
500 if (V) V->addUse(*this);
503 template <class Compare> void Value::sortUseList(Compare Cmp) {
504 if (!UseList || !UseList->Next)
505 // No need to sort 0 or 1 uses.
508 // Note: this function completely ignores Prev pointers until the end when
509 // they're fixed en masse.
511 // Create a binomial vector of sorted lists, visiting uses one at a time and
512 // merging lists as necessary.
513 const unsigned MaxSlots = 32;
514 Use *Slots[MaxSlots];
516 // Collect the first use, turning it into a single-item list.
517 Use *Next = UseList->Next;
518 UseList->Next = nullptr;
519 unsigned NumSlots = 1;
522 // Collect all but the last use.
525 Next = Current->Next;
527 // Turn Current into a single-item list.
528 Current->Next = nullptr;
530 // Save Current in the first available slot, merging on collisions.
532 for (I = 0; I < NumSlots; ++I) {
536 // Merge two lists, doubling the size of Current and emptying slot I.
538 // Since the uses in Slots[I] originally preceded those in Current, send
539 // Slots[I] in as the left parameter to maintain a stable sort.
540 Current = mergeUseLists(Slots[I], Current, Cmp);
543 // Check if this is a new slot.
546 assert(NumSlots <= MaxSlots && "Use list bigger than 2^32");
549 // Found an open slot.
553 // Merge all the lists together.
554 assert(Next && "Expected one more Use");
555 assert(!Next->Next && "Expected only one Use");
557 for (unsigned I = 0; I < NumSlots; ++I)
559 // Since the uses in Slots[I] originally preceded those in UseList, send
560 // Slots[I] in as the left parameter to maintain a stable sort.
561 UseList = mergeUseLists(Slots[I], UseList, Cmp);
563 // Fix the Prev pointers.
564 for (Use *I = UseList, **Prev = &UseList; I; I = I->Next) {
570 template <class Compare>
571 void Value::mergeUseListsImpl(Use *L, Use *R, Use **Next, Compare Cmp) {
582 mergeUseListsImpl(L, R->Next, &R->Next, Cmp);
586 mergeUseListsImpl(L->Next, R, &L->Next, Cmp);
589 // isa - Provide some specializations of isa so that we don't have to include
590 // the subtype header files to test to see if the value is a subclass...
592 template <> struct isa_impl<Constant, Value> {
593 static inline bool doit(const Value &Val) {
594 return Val.getValueID() >= Value::ConstantFirstVal &&
595 Val.getValueID() <= Value::ConstantLastVal;
599 template <> struct isa_impl<Argument, Value> {
600 static inline bool doit (const Value &Val) {
601 return Val.getValueID() == Value::ArgumentVal;
605 template <> struct isa_impl<InlineAsm, Value> {
606 static inline bool doit(const Value &Val) {
607 return Val.getValueID() == Value::InlineAsmVal;
611 template <> struct isa_impl<Instruction, Value> {
612 static inline bool doit(const Value &Val) {
613 return Val.getValueID() >= Value::InstructionVal;
617 template <> struct isa_impl<BasicBlock, Value> {
618 static inline bool doit(const Value &Val) {
619 return Val.getValueID() == Value::BasicBlockVal;
623 template <> struct isa_impl<Function, Value> {
624 static inline bool doit(const Value &Val) {
625 return Val.getValueID() == Value::FunctionVal;
629 template <> struct isa_impl<GlobalVariable, Value> {
630 static inline bool doit(const Value &Val) {
631 return Val.getValueID() == Value::GlobalVariableVal;
635 template <> struct isa_impl<GlobalAlias, Value> {
636 static inline bool doit(const Value &Val) {
637 return Val.getValueID() == Value::GlobalAliasVal;
641 template <> struct isa_impl<GlobalValue, Value> {
642 static inline bool doit(const Value &Val) {
643 return isa<GlobalObject>(Val) || isa<GlobalAlias>(Val);
647 template <> struct isa_impl<GlobalObject, Value> {
648 static inline bool doit(const Value &Val) {
649 return isa<GlobalVariable>(Val) || isa<Function>(Val);
653 template <> struct isa_impl<MDNode, Value> {
654 static inline bool doit(const Value &Val) {
655 return Val.getValueID() == Value::MDNodeVal;
659 // Value* is only 4-byte aligned.
661 class PointerLikeTypeTraits<Value*> {
664 static inline void *getAsVoidPointer(PT P) { return P; }
665 static inline PT getFromVoidPointer(void *P) {
666 return static_cast<PT>(P);
668 enum { NumLowBitsAvailable = 2 };
671 // Create wrappers for C Binding types (see CBindingWrapping.h).
672 DEFINE_ISA_CONVERSION_FUNCTIONS(Value, LLVMValueRef)
674 /* Specialized opaque value conversions.
676 inline Value **unwrap(LLVMValueRef *Vals) {
677 return reinterpret_cast<Value**>(Vals);
681 inline T **unwrap(LLVMValueRef *Vals, unsigned Length) {
683 for (LLVMValueRef *I = Vals, *E = Vals + Length; I != E; ++I)
687 return reinterpret_cast<T**>(Vals);
690 inline LLVMValueRef *wrap(const Value **Vals) {
691 return reinterpret_cast<LLVMValueRef*>(const_cast<Value**>(Vals));
694 } // End llvm namespace