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 /// \brief LLVM Value Representation
58 /// This is a very important LLVM class. It is the base class of all values
59 /// computed by a program that may be used as operands to other values. Value is
60 /// the super class of other important classes such as Instruction and Function.
61 /// All Values have a Type. Type is not a subclass of Value. Some values can
62 /// have a name and they belong to some Module. Setting the name on the Value
63 /// automatically updates the module's symbol table.
65 /// Every value has a "use list" that keeps track of which other Values are
66 /// using this Value. A Value can also have an arbitrary number of ValueHandle
67 /// objects that watch it and listen to RAUW and Destroy events. See
68 /// llvm/IR/ValueHandle.h for details.
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 /// \brief Hold subclass data that can be dropped.
82 /// This member is similar to SubclassData, however it is for holding
83 /// information which may be used to aid optimization, but which may be
84 /// cleared to zero without affecting conservative interpretation.
85 unsigned char SubclassOptionalData : 7;
88 /// \brief Hold arbitrary subclass data.
90 /// This member is defined by this class, but is not used for anything.
91 /// Subclasses can use it to hold whatever state they find useful. This
92 /// field is initialized to zero by the ctor.
93 unsigned short SubclassData;
96 /// \brief The number of operands in the subclass.
98 /// This member is defined by this class, but not used for anything.
99 /// Subclasses can use it to store their number of operands, if they have
102 /// This is stored here to save space in User on 64-bit hosts. Since most
103 /// instances of Value have operands, 32-bit hosts aren't significantly
105 unsigned NumOperands;
108 template <typename UseT> // UseT == 'Use' or 'const Use'
109 class use_iterator_impl
110 : public std::iterator<std::forward_iterator_tag, UseT *, ptrdiff_t> {
111 typedef std::iterator<std::forward_iterator_tag, UseT *, ptrdiff_t> super;
114 explicit use_iterator_impl(UseT *u) : U(u) {}
118 typedef typename super::reference reference;
119 typedef typename super::pointer pointer;
121 use_iterator_impl() : U() {}
123 bool operator==(const use_iterator_impl &x) const { return U == x.U; }
124 bool operator!=(const use_iterator_impl &x) const { return !operator==(x); }
126 use_iterator_impl &operator++() { // Preincrement
127 assert(U && "Cannot increment end iterator!");
131 use_iterator_impl operator++(int) { // Postincrement
137 UseT &operator*() const {
138 assert(U && "Cannot dereference end iterator!");
142 UseT *operator->() const { return &operator*(); }
144 operator use_iterator_impl<const UseT>() const {
145 return use_iterator_impl<const UseT>(U);
149 template <typename UserTy> // UserTy == 'User' or 'const User'
150 class user_iterator_impl
151 : public std::iterator<std::forward_iterator_tag, UserTy *, ptrdiff_t> {
152 typedef std::iterator<std::forward_iterator_tag, UserTy *, ptrdiff_t> super;
154 use_iterator_impl<Use> UI;
155 explicit user_iterator_impl(Use *U) : UI(U) {}
159 typedef typename super::reference reference;
160 typedef typename super::pointer pointer;
162 user_iterator_impl() {}
164 bool operator==(const user_iterator_impl &x) const { return UI == x.UI; }
165 bool operator!=(const user_iterator_impl &x) const { return !operator==(x); }
167 /// \brief Returns true if this iterator is equal to user_end() on the value.
168 bool atEnd() const { return *this == user_iterator_impl(); }
170 user_iterator_impl &operator++() { // Preincrement
174 user_iterator_impl operator++(int) { // Postincrement
180 // Retrieve a pointer to the current User.
181 UserTy *operator*() const {
182 return UI->getUser();
185 UserTy *operator->() const { return operator*(); }
187 operator user_iterator_impl<const UserTy>() const {
188 return user_iterator_impl<const UserTy>(*UI);
191 Use &getUse() const { return *UI; }
193 /// \brief Return the operand # of this use in its User.
195 /// FIXME: Replace all callers with a direct call to Use::getOperandNo.
196 unsigned getOperandNo() const { return UI->getOperandNo(); }
199 void operator=(const Value &) LLVM_DELETED_FUNCTION;
200 Value(const Value &) LLVM_DELETED_FUNCTION;
203 Value(Type *Ty, unsigned scid);
207 /// \brief Support for debugging, callable in GDB: V->dump()
210 /// \brief Implement operator<< on Value.
211 void print(raw_ostream &O) const;
213 /// \brief Print the name of this Value out to the specified raw_ostream.
215 /// This is useful when you just want to print 'int %reg126', not the
216 /// instruction that generated it. If you specify a Module for context, then
217 /// even constanst get pretty-printed; for example, the type of a null
218 /// pointer is printed symbolically.
219 void printAsOperand(raw_ostream &O, bool PrintType = true,
220 const Module *M = nullptr) 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 Name != nullptr; }
230 ValueName *getValueName() const { return Name; }
231 void setValueName(ValueName *VN) { Name = VN; }
233 /// \brief Return a constant reference to the value's name.
235 /// This is cheap and guaranteed to return the same reference as long as the
236 /// value is not modified.
237 StringRef getName() const;
239 /// \brief Change the name of the value.
241 /// Choose a new unique name if the provided name is taken.
243 /// \param Name The new name; or "" if the value's name should be removed.
244 void setName(const Twine &Name);
247 /// \brief Transfer the name from V to this value.
249 /// After taking V's name, sets V's name to empty.
251 /// \note It is an error to call V->takeName(V).
252 void takeName(Value *V);
254 /// \brief Change all uses of this to point to a new Value.
256 /// Go through the uses list for this definition and make each use point to
257 /// "V" instead of "this". After this completes, 'this's use list is
258 /// guaranteed to be empty.
259 void replaceAllUsesWith(Value *V);
261 /// replaceUsesOutsideBlock - Go through the uses list for this definition and
262 /// make each use point to "V" instead of "this" when the use is outside the
263 /// block. 'This's use list is expected to have at least one element.
264 /// Unlike replaceAllUsesWith this function does not support basic block
265 /// values or constant users.
266 void replaceUsesOutsideBlock(Value *V, BasicBlock *BB);
268 //----------------------------------------------------------------------
269 // Methods for handling the chain of uses of this Value.
271 bool use_empty() const { return UseList == nullptr; }
273 typedef use_iterator_impl<Use> use_iterator;
274 typedef use_iterator_impl<const Use> const_use_iterator;
275 use_iterator use_begin() { return use_iterator(UseList); }
276 const_use_iterator use_begin() const { return const_use_iterator(UseList); }
277 use_iterator use_end() { return use_iterator(); }
278 const_use_iterator use_end() const { return const_use_iterator(); }
279 iterator_range<use_iterator> uses() {
280 return iterator_range<use_iterator>(use_begin(), use_end());
282 iterator_range<const_use_iterator> uses() const {
283 return iterator_range<const_use_iterator>(use_begin(), use_end());
286 typedef user_iterator_impl<User> user_iterator;
287 typedef user_iterator_impl<const User> const_user_iterator;
288 user_iterator user_begin() { return user_iterator(UseList); }
289 const_user_iterator user_begin() const { return const_user_iterator(UseList); }
290 user_iterator user_end() { return user_iterator(); }
291 const_user_iterator user_end() const { return const_user_iterator(); }
292 User *user_back() { return *user_begin(); }
293 const User *user_back() const { return *user_begin(); }
294 iterator_range<user_iterator> users() {
295 return iterator_range<user_iterator>(user_begin(), user_end());
297 iterator_range<const_user_iterator> users() const {
298 return iterator_range<const_user_iterator>(user_begin(), user_end());
301 /// \brief Return true if there is exactly one user of this value.
303 /// This is specialized because it is a common request and does not require
304 /// traversing the whole use list.
305 bool hasOneUse() const {
306 const_use_iterator I = use_begin(), E = use_end();
307 if (I == E) return false;
311 /// \brief Return true if this Value has exactly N users.
312 bool hasNUses(unsigned N) const;
314 /// \brief Return true if this value has N users or more.
316 /// This is logically equivalent to getNumUses() >= N.
317 bool hasNUsesOrMore(unsigned N) const;
319 /// \brief Check if this value is used in the specified basic block.
320 bool isUsedInBasicBlock(const BasicBlock *BB) const;
322 /// \brief This method computes the number of uses of this Value.
324 /// This is a linear time operation. Use hasOneUse, hasNUses, or
325 /// hasNUsesOrMore to check for specific values.
326 unsigned getNumUses() const;
328 /// \brief This method should only be used by the Use class.
329 void addUse(Use &U) { U.addToList(&UseList); }
331 /// \brief Concrete subclass of this.
333 /// An enumeration for keeping track of the concrete subclass of Value that
334 /// is actually instantiated. Values of this enumeration are kept in the
335 /// Value classes SubclassID field. They are used for concrete type
338 ArgumentVal, // This is an instance of Argument
339 BasicBlockVal, // This is an instance of BasicBlock
340 FunctionVal, // This is an instance of Function
341 GlobalAliasVal, // This is an instance of GlobalAlias
342 GlobalVariableVal, // This is an instance of GlobalVariable
343 UndefValueVal, // This is an instance of UndefValue
344 BlockAddressVal, // This is an instance of BlockAddress
345 ConstantExprVal, // This is an instance of ConstantExpr
346 ConstantAggregateZeroVal, // This is an instance of ConstantAggregateZero
347 ConstantDataArrayVal, // This is an instance of ConstantDataArray
348 ConstantDataVectorVal, // This is an instance of ConstantDataVector
349 ConstantIntVal, // This is an instance of ConstantInt
350 ConstantFPVal, // This is an instance of ConstantFP
351 ConstantArrayVal, // This is an instance of ConstantArray
352 ConstantStructVal, // This is an instance of ConstantStruct
353 ConstantVectorVal, // This is an instance of ConstantVector
354 ConstantPointerNullVal, // This is an instance of ConstantPointerNull
355 GenericMDNodeVal, // This is an instance of GenericMDNode
356 MDNodeFwdDeclVal, // This is an instance of MDNodeFwdDecl
357 MDStringVal, // This is an instance of MDString
358 InlineAsmVal, // This is an instance of InlineAsm
359 InstructionVal, // This is an instance of Instruction
360 // Enum values starting at InstructionVal are used for Instructions;
361 // don't add new values here!
364 ConstantFirstVal = FunctionVal,
365 ConstantLastVal = ConstantPointerNullVal
368 /// \brief Return an ID for the concrete type of this object.
370 /// This is used to implement the classof checks. This should not be used
371 /// for any other purpose, as the values may change as LLVM evolves. Also,
372 /// note that for instructions, the Instruction's opcode is added to
373 /// InstructionVal. So this means three things:
374 /// # there is no value with code InstructionVal (no opcode==0).
375 /// # there are more possible values for the value type than in ValueTy enum.
376 /// # the InstructionVal enumerator must be the highest valued enumerator in
377 /// the ValueTy enum.
378 unsigned getValueID() const {
382 /// \brief Return the raw optional flags value contained in this value.
384 /// This should only be used when testing two Values for equivalence.
385 unsigned getRawSubclassOptionalData() const {
386 return SubclassOptionalData;
389 /// \brief Clear the optional flags contained in this value.
390 void clearSubclassOptionalData() {
391 SubclassOptionalData = 0;
394 /// \brief Check the optional flags for equality.
395 bool hasSameSubclassOptionalData(const Value *V) const {
396 return SubclassOptionalData == V->SubclassOptionalData;
399 /// \brief Clear any optional flags not set in the given Value.
400 void intersectOptionalDataWith(const Value *V) {
401 SubclassOptionalData &= V->SubclassOptionalData;
404 /// \brief Return true if there is a value handle associated with this value.
405 bool hasValueHandle() const { return HasValueHandle; }
407 /// \brief Strip off pointer casts, all-zero GEPs, and aliases.
409 /// Returns the original uncasted value. If this is called on a non-pointer
410 /// value, it returns 'this'.
411 Value *stripPointerCasts();
412 const Value *stripPointerCasts() const {
413 return const_cast<Value*>(this)->stripPointerCasts();
416 /// \brief Strip off pointer casts and all-zero GEPs.
418 /// Returns the original uncasted value. If this is called on a non-pointer
419 /// value, it returns 'this'.
420 Value *stripPointerCastsNoFollowAliases();
421 const Value *stripPointerCastsNoFollowAliases() const {
422 return const_cast<Value*>(this)->stripPointerCastsNoFollowAliases();
425 /// \brief Strip off pointer casts and all-constant inbounds GEPs.
427 /// Returns the original pointer value. If this is called on a non-pointer
428 /// value, it returns 'this'.
429 Value *stripInBoundsConstantOffsets();
430 const Value *stripInBoundsConstantOffsets() const {
431 return const_cast<Value*>(this)->stripInBoundsConstantOffsets();
434 /// \brief Accumulate offsets from \a stripInBoundsConstantOffsets().
436 /// Stores the resulting constant offset stripped into the APInt provided.
437 /// The provided APInt will be extended or truncated as needed to be the
438 /// correct bitwidth for an offset of this pointer type.
440 /// If this is called on a non-pointer value, it returns 'this'.
441 Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
443 const Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
444 APInt &Offset) const {
445 return const_cast<Value *>(this)
446 ->stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
449 /// \brief Strip off pointer casts and inbounds GEPs.
451 /// Returns the original pointer value. If this is called on a non-pointer
452 /// value, it returns 'this'.
453 Value *stripInBoundsOffsets();
454 const Value *stripInBoundsOffsets() const {
455 return const_cast<Value*>(this)->stripInBoundsOffsets();
458 /// \brief Check if this is always a dereferenceable pointer.
460 /// Test if this value is always a pointer to allocated and suitably aligned
461 /// memory for a simple load or store.
462 bool isDereferenceablePointer(const DataLayout *DL = nullptr) const;
464 /// \brief Translate PHI node to its predecessor from the given basic block.
466 /// If this value is a PHI node with CurBB as its parent, return the value in
467 /// the PHI node corresponding to PredBB. If not, return ourself. This is
468 /// useful if you want to know the value something has in a predecessor
470 Value *DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB);
472 const Value *DoPHITranslation(const BasicBlock *CurBB,
473 const BasicBlock *PredBB) const{
474 return const_cast<Value*>(this)->DoPHITranslation(CurBB, PredBB);
477 /// \brief The maximum alignment for instructions.
479 /// This is the greatest alignment value supported by load, store, and alloca
480 /// instructions, and global values.
481 static const unsigned MaximumAlignment = 1u << 29;
483 /// \brief Mutate the type of this Value to be of the specified type.
485 /// Note that this is an extremely dangerous operation which can create
486 /// completely invalid IR very easily. It is strongly recommended that you
487 /// recreate IR objects with the right types instead of mutating them in
489 void mutateType(Type *Ty) {
493 /// \brief Sort the use-list.
495 /// Sorts the Value's use-list by Cmp using a stable mergesort. Cmp is
496 /// expected to compare two \a Use references.
497 template <class Compare> void sortUseList(Compare Cmp);
499 /// \brief Reverse the use-list.
500 void reverseUseList();
503 /// \brief Merge two lists together.
505 /// Merges \c L and \c R using \c Cmp. To enable stable sorts, always pushes
506 /// "equal" items from L before items from R.
508 /// \return the first element in the list.
510 /// \note Completely ignores \a Use::Prev (doesn't read, doesn't update).
511 template <class Compare>
512 static Use *mergeUseLists(Use *L, Use *R, Compare Cmp) {
514 mergeUseListsImpl(L, R, &Merged, Cmp);
518 /// \brief Tail-recursive helper for \a mergeUseLists().
520 /// \param[out] Next the first element in the list.
521 template <class Compare>
522 static void mergeUseListsImpl(Use *L, Use *R, Use **Next, Compare Cmp);
525 unsigned short getSubclassDataFromValue() const { return SubclassData; }
526 void setValueSubclassData(unsigned short D) { SubclassData = D; }
529 inline raw_ostream &operator<<(raw_ostream &OS, const Value &V) {
534 void Use::set(Value *V) {
535 if (Val) removeFromList();
537 if (V) V->addUse(*this);
540 template <class Compare> void Value::sortUseList(Compare Cmp) {
541 if (!UseList || !UseList->Next)
542 // No need to sort 0 or 1 uses.
545 // Note: this function completely ignores Prev pointers until the end when
546 // they're fixed en masse.
548 // Create a binomial vector of sorted lists, visiting uses one at a time and
549 // merging lists as necessary.
550 const unsigned MaxSlots = 32;
551 Use *Slots[MaxSlots];
553 // Collect the first use, turning it into a single-item list.
554 Use *Next = UseList->Next;
555 UseList->Next = nullptr;
556 unsigned NumSlots = 1;
559 // Collect all but the last use.
562 Next = Current->Next;
564 // Turn Current into a single-item list.
565 Current->Next = nullptr;
567 // Save Current in the first available slot, merging on collisions.
569 for (I = 0; I < NumSlots; ++I) {
573 // Merge two lists, doubling the size of Current and emptying slot I.
575 // Since the uses in Slots[I] originally preceded those in Current, send
576 // Slots[I] in as the left parameter to maintain a stable sort.
577 Current = mergeUseLists(Slots[I], Current, Cmp);
580 // Check if this is a new slot.
583 assert(NumSlots <= MaxSlots && "Use list bigger than 2^32");
586 // Found an open slot.
590 // Merge all the lists together.
591 assert(Next && "Expected one more Use");
592 assert(!Next->Next && "Expected only one Use");
594 for (unsigned I = 0; I < NumSlots; ++I)
596 // Since the uses in Slots[I] originally preceded those in UseList, send
597 // Slots[I] in as the left parameter to maintain a stable sort.
598 UseList = mergeUseLists(Slots[I], UseList, Cmp);
600 // Fix the Prev pointers.
601 for (Use *I = UseList, **Prev = &UseList; I; I = I->Next) {
607 template <class Compare>
608 void Value::mergeUseListsImpl(Use *L, Use *R, Use **Next, Compare Cmp) {
619 mergeUseListsImpl(L, R->Next, &R->Next, Cmp);
623 mergeUseListsImpl(L->Next, R, &L->Next, Cmp);
626 // isa - Provide some specializations of isa so that we don't have to include
627 // the subtype header files to test to see if the value is a subclass...
629 template <> struct isa_impl<Constant, Value> {
630 static inline bool doit(const Value &Val) {
631 return Val.getValueID() >= Value::ConstantFirstVal &&
632 Val.getValueID() <= Value::ConstantLastVal;
636 template <> struct isa_impl<Argument, Value> {
637 static inline bool doit (const Value &Val) {
638 return Val.getValueID() == Value::ArgumentVal;
642 template <> struct isa_impl<InlineAsm, Value> {
643 static inline bool doit(const Value &Val) {
644 return Val.getValueID() == Value::InlineAsmVal;
648 template <> struct isa_impl<Instruction, Value> {
649 static inline bool doit(const Value &Val) {
650 return Val.getValueID() >= Value::InstructionVal;
654 template <> struct isa_impl<BasicBlock, Value> {
655 static inline bool doit(const Value &Val) {
656 return Val.getValueID() == Value::BasicBlockVal;
660 template <> struct isa_impl<Function, Value> {
661 static inline bool doit(const Value &Val) {
662 return Val.getValueID() == Value::FunctionVal;
666 template <> struct isa_impl<GlobalVariable, Value> {
667 static inline bool doit(const Value &Val) {
668 return Val.getValueID() == Value::GlobalVariableVal;
672 template <> struct isa_impl<GlobalAlias, Value> {
673 static inline bool doit(const Value &Val) {
674 return Val.getValueID() == Value::GlobalAliasVal;
678 template <> struct isa_impl<GlobalValue, Value> {
679 static inline bool doit(const Value &Val) {
680 return isa<GlobalObject>(Val) || isa<GlobalAlias>(Val);
684 template <> struct isa_impl<GlobalObject, Value> {
685 static inline bool doit(const Value &Val) {
686 return isa<GlobalVariable>(Val) || isa<Function>(Val);
690 template <> struct isa_impl<MDNode, Value> {
691 static inline bool doit(const Value &Val) {
692 return Val.getValueID() == Value::GenericMDNodeVal ||
693 Val.getValueID() == Value::MDNodeFwdDeclVal;
697 // Value* is only 4-byte aligned.
699 class PointerLikeTypeTraits<Value*> {
702 static inline void *getAsVoidPointer(PT P) { return P; }
703 static inline PT getFromVoidPointer(void *P) {
704 return static_cast<PT>(P);
706 enum { NumLowBitsAvailable = 2 };
709 // Create wrappers for C Binding types (see CBindingWrapping.h).
710 DEFINE_ISA_CONVERSION_FUNCTIONS(Value, LLVMValueRef)
712 /* Specialized opaque value conversions.
714 inline Value **unwrap(LLVMValueRef *Vals) {
715 return reinterpret_cast<Value**>(Vals);
719 inline T **unwrap(LLVMValueRef *Vals, unsigned Length) {
721 for (LLVMValueRef *I = Vals, *E = Vals + Length; I != E; ++I)
725 return reinterpret_cast<T**>(Vals);
728 inline LLVMValueRef *wrap(const Value **Vals) {
729 return reinterpret_cast<LLVMValueRef*>(const_cast<Value**>(Vals));
732 } // End llvm namespace