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/ADT/iterator_range.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;
40 class ModuleSlotTracker;
44 class ValueHandleBase;
45 class ValueSymbolTable;
48 template<typename ValueTy> class StringMapEntry;
49 typedef StringMapEntry<Value*> ValueName;
51 //===----------------------------------------------------------------------===//
53 //===----------------------------------------------------------------------===//
55 /// \brief LLVM Value Representation
57 /// This is a very important LLVM class. It is the base class of all values
58 /// computed by a program that may be used as operands to other values. Value is
59 /// the super class of other important classes such as Instruction and Function.
60 /// All Values have a Type. Type is not a subclass of Value. Some values can
61 /// have a name and they belong to some Module. Setting the name on the Value
62 /// automatically updates the module's symbol table.
64 /// Every value has a "use list" that keeps track of which other Values are
65 /// using this Value. A Value can also have an arbitrary number of ValueHandle
66 /// objects that watch it and listen to RAUW and Destroy events. See
67 /// llvm/IR/ValueHandle.h for details.
72 friend class ValueAsMetadata; // Allow access to IsUsedByMD.
73 friend class ValueHandleBase;
75 const unsigned char SubclassID; // Subclass identifier (for isa/dyn_cast)
76 unsigned char HasValueHandle : 1; // Has a ValueHandle pointing to this?
78 /// \brief Hold subclass data that can be dropped.
80 /// This member is similar to SubclassData, however it is for holding
81 /// information which may be used to aid optimization, but which may be
82 /// cleared to zero without affecting conservative interpretation.
83 unsigned char SubclassOptionalData : 7;
86 /// \brief Hold arbitrary subclass data.
88 /// This member is defined by this class, but is not used for anything.
89 /// Subclasses can use it to hold whatever state they find useful. This
90 /// field is initialized to zero by the ctor.
91 unsigned short SubclassData;
94 /// \brief The number of operands in the subclass.
96 /// This member is defined by this class, but not used for anything.
97 /// Subclasses can use it to store their number of operands, if they have
100 /// This is stored here to save space in User on 64-bit hosts. Since most
101 /// instances of Value have operands, 32-bit hosts aren't significantly
104 /// Note, this should *NOT* be used directly by any class other than User.
105 /// User uses this value to find the Use list.
106 enum : unsigned { NumUserOperandsBits = 28 };
107 unsigned NumUserOperands : NumUserOperandsBits;
111 bool HasHungOffUses : 1;
112 bool HasDescriptor : 1;
115 template <typename UseT> // UseT == 'Use' or 'const Use'
116 class use_iterator_impl
117 : public std::iterator<std::forward_iterator_tag, UseT *> {
119 explicit use_iterator_impl(UseT *u) : U(u) {}
123 use_iterator_impl() : U() {}
125 bool operator==(const use_iterator_impl &x) const { return U == x.U; }
126 bool operator!=(const use_iterator_impl &x) const { return !operator==(x); }
128 use_iterator_impl &operator++() { // Preincrement
129 assert(U && "Cannot increment end iterator!");
133 use_iterator_impl operator++(int) { // Postincrement
139 UseT &operator*() const {
140 assert(U && "Cannot dereference end iterator!");
144 UseT *operator->() const { return &operator*(); }
146 operator use_iterator_impl<const UseT>() const {
147 return use_iterator_impl<const UseT>(U);
151 template <typename UserTy> // UserTy == 'User' or 'const User'
152 class user_iterator_impl
153 : public std::iterator<std::forward_iterator_tag, UserTy *> {
154 use_iterator_impl<Use> UI;
155 explicit user_iterator_impl(Use *U) : UI(U) {}
159 user_iterator_impl() {}
161 bool operator==(const user_iterator_impl &x) const { return UI == x.UI; }
162 bool operator!=(const user_iterator_impl &x) const { return !operator==(x); }
164 /// \brief Returns true if this iterator is equal to user_end() on the value.
165 bool atEnd() const { return *this == user_iterator_impl(); }
167 user_iterator_impl &operator++() { // Preincrement
171 user_iterator_impl operator++(int) { // Postincrement
177 // Retrieve a pointer to the current User.
178 UserTy *operator*() const {
179 return UI->getUser();
182 UserTy *operator->() const { return operator*(); }
184 operator user_iterator_impl<const UserTy>() const {
185 return user_iterator_impl<const UserTy>(*UI);
188 Use &getUse() const { return *UI; }
191 void operator=(const Value &) = delete;
192 Value(const Value &) = delete;
195 Value(Type *Ty, unsigned scid);
199 /// \brief Support for debugging, callable in GDB: V->dump()
202 /// \brief Implement operator<< on Value.
204 void print(raw_ostream &O, bool IsForDebug = false) const;
205 void print(raw_ostream &O, ModuleSlotTracker &MST,
206 bool IsForDebug = false) const;
209 /// \brief Print the name of this Value out to the specified raw_ostream.
211 /// This is useful when you just want to print 'int %reg126', not the
212 /// instruction that generated it. If you specify a Module for context, then
213 /// even constanst get pretty-printed; for example, the type of a null
214 /// pointer is printed symbolically.
216 void printAsOperand(raw_ostream &O, bool PrintType = true,
217 const Module *M = nullptr) const;
218 void printAsOperand(raw_ostream &O, bool PrintType,
219 ModuleSlotTracker &MST) const;
222 /// \brief All values are typed, get the type of this value.
223 Type *getType() const { return VTy; }
225 /// \brief All values hold a context through their type.
226 LLVMContext &getContext() const;
228 // \brief All values can potentially be named.
229 bool hasName() const { return HasName; }
230 ValueName *getValueName() const;
231 void setValueName(ValueName *VN);
234 void destroyValueName();
235 void setNameImpl(const Twine &Name);
238 /// \brief Return a constant reference to the value's name.
240 /// This is cheap and guaranteed to return the same reference as long as the
241 /// value is not modified.
242 StringRef getName() const;
244 /// \brief Change the name of the value.
246 /// Choose a new unique name if the provided name is taken.
248 /// \param Name The new name; or "" if the value's name should be removed.
249 void setName(const Twine &Name);
252 /// \brief Transfer the name from V to this value.
254 /// After taking V's name, sets V's name to empty.
256 /// \note It is an error to call V->takeName(V).
257 void takeName(Value *V);
259 /// \brief Change all uses of this to point to a new Value.
261 /// Go through the uses list for this definition and make each use point to
262 /// "V" instead of "this". After this completes, 'this's use list is
263 /// guaranteed to be empty.
264 void replaceAllUsesWith(Value *V);
266 /// replaceUsesOutsideBlock - Go through the uses list for this definition and
267 /// make each use point to "V" instead of "this" when the use is outside the
268 /// block. 'This's use list is expected to have at least one element.
269 /// Unlike replaceAllUsesWith this function does not support basic block
270 /// values or constant users.
271 void replaceUsesOutsideBlock(Value *V, BasicBlock *BB);
273 //----------------------------------------------------------------------
274 // Methods for handling the chain of uses of this Value.
276 // Materializing a function can introduce new uses, so these methods come in
278 // The methods that start with materialized_ check the uses that are
279 // currently known given which functions are materialized. Be very careful
280 // when using them since you might not get all uses.
281 // The methods that don't start with materialized_ assert that modules is
282 // fully materialized.
284 void assertModuleIsMaterialized() const {}
286 void assertModuleIsMaterialized() const;
289 bool use_empty() const {
290 assertModuleIsMaterialized();
291 return UseList == nullptr;
294 typedef use_iterator_impl<Use> use_iterator;
295 typedef use_iterator_impl<const Use> const_use_iterator;
296 use_iterator materialized_use_begin() { return use_iterator(UseList); }
297 const_use_iterator materialized_use_begin() const {
298 return const_use_iterator(UseList);
300 use_iterator use_begin() {
301 assertModuleIsMaterialized();
302 return materialized_use_begin();
304 const_use_iterator use_begin() const {
305 assertModuleIsMaterialized();
306 return materialized_use_begin();
308 use_iterator use_end() { return use_iterator(); }
309 const_use_iterator use_end() const { return const_use_iterator(); }
310 iterator_range<use_iterator> materialized_uses() {
311 return make_range(materialized_use_begin(), use_end());
313 iterator_range<const_use_iterator> materialized_uses() const {
314 return make_range(materialized_use_begin(), use_end());
316 iterator_range<use_iterator> uses() {
317 assertModuleIsMaterialized();
318 return materialized_uses();
320 iterator_range<const_use_iterator> uses() const {
321 assertModuleIsMaterialized();
322 return materialized_uses();
325 bool user_empty() const {
326 assertModuleIsMaterialized();
327 return UseList == nullptr;
330 typedef user_iterator_impl<User> user_iterator;
331 typedef user_iterator_impl<const User> const_user_iterator;
332 user_iterator materialized_user_begin() { return user_iterator(UseList); }
333 const_user_iterator materialized_user_begin() const {
334 return const_user_iterator(UseList);
336 user_iterator user_begin() {
337 assertModuleIsMaterialized();
338 return materialized_user_begin();
340 const_user_iterator user_begin() const {
341 assertModuleIsMaterialized();
342 return materialized_user_begin();
344 user_iterator user_end() { return user_iterator(); }
345 const_user_iterator user_end() const { return const_user_iterator(); }
347 assertModuleIsMaterialized();
348 return *materialized_user_begin();
350 const User *user_back() const {
351 assertModuleIsMaterialized();
352 return *materialized_user_begin();
354 iterator_range<user_iterator> users() {
355 assertModuleIsMaterialized();
356 return make_range(materialized_user_begin(), user_end());
358 iterator_range<const_user_iterator> users() const {
359 assertModuleIsMaterialized();
360 return make_range(materialized_user_begin(), user_end());
363 /// \brief Return true if there is exactly one user of this value.
365 /// This is specialized because it is a common request and does not require
366 /// traversing the whole use list.
367 bool hasOneUse() const {
368 const_use_iterator I = use_begin(), E = use_end();
369 if (I == E) return false;
373 /// \brief Return true if this Value has exactly N users.
374 bool hasNUses(unsigned N) const;
376 /// \brief Return true if this value has N users or more.
378 /// This is logically equivalent to getNumUses() >= N.
379 bool hasNUsesOrMore(unsigned N) const;
381 /// \brief Check if this value is used in the specified basic block.
382 bool isUsedInBasicBlock(const BasicBlock *BB) const;
384 /// \brief This method computes the number of uses of this Value.
386 /// This is a linear time operation. Use hasOneUse, hasNUses, or
387 /// hasNUsesOrMore to check for specific values.
388 unsigned getNumUses() const;
390 /// \brief This method should only be used by the Use class.
391 void addUse(Use &U) { U.addToList(&UseList); }
393 /// \brief Concrete subclass of this.
395 /// An enumeration for keeping track of the concrete subclass of Value that
396 /// is actually instantiated. Values of this enumeration are kept in the
397 /// Value classes SubclassID field. They are used for concrete type
400 #define HANDLE_VALUE(Name) Name##Val,
401 #include "llvm/IR/Value.def"
404 #define HANDLE_CONSTANT_MARKER(Marker, Constant) Marker = Constant##Val,
405 #include "llvm/IR/Value.def"
408 /// \brief Return an ID for the concrete type of this object.
410 /// This is used to implement the classof checks. This should not be used
411 /// for any other purpose, as the values may change as LLVM evolves. Also,
412 /// note that for instructions, the Instruction's opcode is added to
413 /// InstructionVal. So this means three things:
414 /// # there is no value with code InstructionVal (no opcode==0).
415 /// # there are more possible values for the value type than in ValueTy enum.
416 /// # the InstructionVal enumerator must be the highest valued enumerator in
417 /// the ValueTy enum.
418 unsigned getValueID() const {
422 /// \brief Return the raw optional flags value contained in this value.
424 /// This should only be used when testing two Values for equivalence.
425 unsigned getRawSubclassOptionalData() const {
426 return SubclassOptionalData;
429 /// \brief Clear the optional flags contained in this value.
430 void clearSubclassOptionalData() {
431 SubclassOptionalData = 0;
434 /// \brief Check the optional flags for equality.
435 bool hasSameSubclassOptionalData(const Value *V) const {
436 return SubclassOptionalData == V->SubclassOptionalData;
439 /// \brief Clear any optional flags not set in the given Value.
440 void intersectOptionalDataWith(const Value *V) {
441 SubclassOptionalData &= V->SubclassOptionalData;
444 /// \brief Return true if there is a value handle associated with this value.
445 bool hasValueHandle() const { return HasValueHandle; }
447 /// \brief Return true if there is metadata referencing this value.
448 bool isUsedByMetadata() const { return IsUsedByMD; }
450 /// \brief Strip off pointer casts, all-zero GEPs, and aliases.
452 /// Returns the original uncasted value. If this is called on a non-pointer
453 /// value, it returns 'this'.
454 Value *stripPointerCasts();
455 const Value *stripPointerCasts() const {
456 return const_cast<Value*>(this)->stripPointerCasts();
459 /// \brief Strip off pointer casts and all-zero GEPs.
461 /// Returns the original uncasted value. If this is called on a non-pointer
462 /// value, it returns 'this'.
463 Value *stripPointerCastsNoFollowAliases();
464 const Value *stripPointerCastsNoFollowAliases() const {
465 return const_cast<Value*>(this)->stripPointerCastsNoFollowAliases();
468 /// \brief Strip off pointer casts and all-constant inbounds GEPs.
470 /// Returns the original pointer value. If this is called on a non-pointer
471 /// value, it returns 'this'.
472 Value *stripInBoundsConstantOffsets();
473 const Value *stripInBoundsConstantOffsets() const {
474 return const_cast<Value*>(this)->stripInBoundsConstantOffsets();
477 /// \brief Accumulate offsets from \a stripInBoundsConstantOffsets().
479 /// Stores the resulting constant offset stripped into the APInt provided.
480 /// The provided APInt will be extended or truncated as needed to be the
481 /// correct bitwidth for an offset of this pointer type.
483 /// If this is called on a non-pointer value, it returns 'this'.
484 Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
486 const Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
487 APInt &Offset) const {
488 return const_cast<Value *>(this)
489 ->stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
492 /// \brief Strip off pointer casts and inbounds GEPs.
494 /// Returns the original pointer value. If this is called on a non-pointer
495 /// value, it returns 'this'.
496 Value *stripInBoundsOffsets();
497 const Value *stripInBoundsOffsets() const {
498 return const_cast<Value*>(this)->stripInBoundsOffsets();
501 /// \brief Translate PHI node to its predecessor from the given basic block.
503 /// If this value is a PHI node with CurBB as its parent, return the value in
504 /// the PHI node corresponding to PredBB. If not, return ourself. This is
505 /// useful if you want to know the value something has in a predecessor
507 Value *DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB);
509 const Value *DoPHITranslation(const BasicBlock *CurBB,
510 const BasicBlock *PredBB) const{
511 return const_cast<Value*>(this)->DoPHITranslation(CurBB, PredBB);
514 /// \brief The maximum alignment for instructions.
516 /// This is the greatest alignment value supported by load, store, and alloca
517 /// instructions, and global values.
518 static const unsigned MaxAlignmentExponent = 29;
519 static const unsigned MaximumAlignment = 1u << MaxAlignmentExponent;
521 /// \brief Mutate the type of this Value to be of the specified type.
523 /// Note that this is an extremely dangerous operation which can create
524 /// completely invalid IR very easily. It is strongly recommended that you
525 /// recreate IR objects with the right types instead of mutating them in
527 void mutateType(Type *Ty) {
531 /// \brief Sort the use-list.
533 /// Sorts the Value's use-list by Cmp using a stable mergesort. Cmp is
534 /// expected to compare two \a Use references.
535 template <class Compare> void sortUseList(Compare Cmp);
537 /// \brief Reverse the use-list.
538 void reverseUseList();
541 /// \brief Merge two lists together.
543 /// Merges \c L and \c R using \c Cmp. To enable stable sorts, always pushes
544 /// "equal" items from L before items from R.
546 /// \return the first element in the list.
548 /// \note Completely ignores \a Use::Prev (doesn't read, doesn't update).
549 template <class Compare>
550 static Use *mergeUseLists(Use *L, Use *R, Compare Cmp) {
552 Use **Next = &Merged;
577 /// \brief Tail-recursive helper for \a mergeUseLists().
579 /// \param[out] Next the first element in the list.
580 template <class Compare>
581 static void mergeUseListsImpl(Use *L, Use *R, Use **Next, Compare Cmp);
584 unsigned short getSubclassDataFromValue() const { return SubclassData; }
585 void setValueSubclassData(unsigned short D) { SubclassData = D; }
588 inline raw_ostream &operator<<(raw_ostream &OS, const Value &V) {
593 void Use::set(Value *V) {
594 if (Val) removeFromList();
596 if (V) V->addUse(*this);
599 template <class Compare> void Value::sortUseList(Compare Cmp) {
600 if (!UseList || !UseList->Next)
601 // No need to sort 0 or 1 uses.
604 // Note: this function completely ignores Prev pointers until the end when
605 // they're fixed en masse.
607 // Create a binomial vector of sorted lists, visiting uses one at a time and
608 // merging lists as necessary.
609 const unsigned MaxSlots = 32;
610 Use *Slots[MaxSlots];
612 // Collect the first use, turning it into a single-item list.
613 Use *Next = UseList->Next;
614 UseList->Next = nullptr;
615 unsigned NumSlots = 1;
618 // Collect all but the last use.
621 Next = Current->Next;
623 // Turn Current into a single-item list.
624 Current->Next = nullptr;
626 // Save Current in the first available slot, merging on collisions.
628 for (I = 0; I < NumSlots; ++I) {
632 // Merge two lists, doubling the size of Current and emptying slot I.
634 // Since the uses in Slots[I] originally preceded those in Current, send
635 // Slots[I] in as the left parameter to maintain a stable sort.
636 Current = mergeUseLists(Slots[I], Current, Cmp);
639 // Check if this is a new slot.
642 assert(NumSlots <= MaxSlots && "Use list bigger than 2^32");
645 // Found an open slot.
649 // Merge all the lists together.
650 assert(Next && "Expected one more Use");
651 assert(!Next->Next && "Expected only one Use");
653 for (unsigned I = 0; I < NumSlots; ++I)
655 // Since the uses in Slots[I] originally preceded those in UseList, send
656 // Slots[I] in as the left parameter to maintain a stable sort.
657 UseList = mergeUseLists(Slots[I], UseList, Cmp);
659 // Fix the Prev pointers.
660 for (Use *I = UseList, **Prev = &UseList; I; I = I->Next) {
666 // isa - Provide some specializations of isa so that we don't have to include
667 // the subtype header files to test to see if the value is a subclass...
669 template <> struct isa_impl<Constant, Value> {
670 static inline bool doit(const Value &Val) {
671 return Val.getValueID() >= Value::ConstantFirstVal &&
672 Val.getValueID() <= Value::ConstantLastVal;
676 template <> struct isa_impl<Argument, Value> {
677 static inline bool doit (const Value &Val) {
678 return Val.getValueID() == Value::ArgumentVal;
682 template <> struct isa_impl<InlineAsm, Value> {
683 static inline bool doit(const Value &Val) {
684 return Val.getValueID() == Value::InlineAsmVal;
688 template <> struct isa_impl<Instruction, Value> {
689 static inline bool doit(const Value &Val) {
690 return Val.getValueID() >= Value::InstructionVal;
694 template <> struct isa_impl<BasicBlock, Value> {
695 static inline bool doit(const Value &Val) {
696 return Val.getValueID() == Value::BasicBlockVal;
700 template <> struct isa_impl<Function, Value> {
701 static inline bool doit(const Value &Val) {
702 return Val.getValueID() == Value::FunctionVal;
706 template <> struct isa_impl<GlobalVariable, Value> {
707 static inline bool doit(const Value &Val) {
708 return Val.getValueID() == Value::GlobalVariableVal;
712 template <> struct isa_impl<GlobalAlias, Value> {
713 static inline bool doit(const Value &Val) {
714 return Val.getValueID() == Value::GlobalAliasVal;
718 template <> struct isa_impl<GlobalValue, Value> {
719 static inline bool doit(const Value &Val) {
720 return isa<GlobalObject>(Val) || isa<GlobalAlias>(Val);
724 template <> struct isa_impl<GlobalObject, Value> {
725 static inline bool doit(const Value &Val) {
726 return isa<GlobalVariable>(Val) || isa<Function>(Val);
730 // Value* is only 4-byte aligned.
732 class PointerLikeTypeTraits<Value*> {
735 static inline void *getAsVoidPointer(PT P) { return P; }
736 static inline PT getFromVoidPointer(void *P) {
737 return static_cast<PT>(P);
739 enum { NumLowBitsAvailable = 2 };
742 // Create wrappers for C Binding types (see CBindingWrapping.h).
743 DEFINE_ISA_CONVERSION_FUNCTIONS(Value, LLVMValueRef)
745 /* Specialized opaque value conversions.
747 inline Value **unwrap(LLVMValueRef *Vals) {
748 return reinterpret_cast<Value**>(Vals);
752 inline T **unwrap(LLVMValueRef *Vals, unsigned Length) {
754 for (LLVMValueRef *I = Vals, *E = Vals + Length; I != E; ++I)
758 return reinterpret_cast<T**>(Vals);
761 inline LLVMValueRef *wrap(const Value **Vals) {
762 return reinterpret_cast<LLVMValueRef*>(const_cast<Value**>(Vals));
765 } // End llvm namespace