1 //===- llvm/Value.h - Definition of the Value class -------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file declares the Value class.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #ifndef LLVM_IR_VALUE_H
14 #define LLVM_IR_VALUE_H
15
16 #include "llvm-c/Types.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/iterator_range.h"
19 #include "llvm/IR/Use.h"
20 #include "llvm/Support/Alignment.h"
21 #include "llvm/Support/CBindingWrapping.h"
22 #include "llvm/Support/Casting.h"
23 #include <cassert>
24 #include <iterator>
25 #include <memory>
26
27 namespace llvm {
28
29 class APInt;
30 class Argument;
31 class BasicBlock;
32 class Constant;
33 class ConstantData;
34 class ConstantAggregate;
35 class DataLayout;
36 class Function;
37 class GlobalAlias;
38 class GlobalIFunc;
39 class GlobalIndirectSymbol;
40 class GlobalObject;
41 class GlobalValue;
42 class GlobalVariable;
43 class InlineAsm;
44 class Instruction;
45 class LLVMContext;
46 class Module;
47 class ModuleSlotTracker;
48 class raw_ostream;
49 template<typename ValueTy> class StringMapEntry;
50 class StringRef;
51 class Twine;
52 class Type;
53 class User;
54
55 using ValueName = StringMapEntry<Value *>;
56
57 //===----------------------------------------------------------------------===//
58 // Value Class
59 //===----------------------------------------------------------------------===//
60
61 /// LLVM Value Representation
62 ///
63 /// This is a very important LLVM class. It is the base class of all values
64 /// computed by a program that may be used as operands to other values. Value is
65 /// the super class of other important classes such as Instruction and Function.
66 /// All Values have a Type. Type is not a subclass of Value. Some values can
67 /// have a name and they belong to some Module. Setting the name on the Value
68 /// automatically updates the module's symbol table.
69 ///
70 /// Every value has a "use list" that keeps track of which other Values are
71 /// using this Value. A Value can also have an arbitrary number of ValueHandle
72 /// objects that watch it and listen to RAUW and Destroy events. See
73 /// llvm/IR/ValueHandle.h for details.
74 class Value {
75 // The least-significant bit of the first word of Value *must* be zero:
76 // http://www.llvm.org/docs/ProgrammersManual.html#the-waymarking-algorithm
77 Type *VTy;
78 Use *UseList;
79
80 friend class ValueAsMetadata; // Allow access to IsUsedByMD.
81 friend class ValueHandleBase;
82
83 const unsigned char SubclassID; // Subclass identifier (for isa/dyn_cast)
84 unsigned char HasValueHandle : 1; // Has a ValueHandle pointing to this?
85
86 protected:
87 /// Hold subclass data that can be dropped.
88 ///
89 /// This member is similar to SubclassData, however it is for holding
90 /// information which may be used to aid optimization, but which may be
91 /// cleared to zero without affecting conservative interpretation.
92 unsigned char SubclassOptionalData : 7;
93
94 private:
95 /// Hold arbitrary subclass data.
96 ///
97 /// This member is defined by this class, but is not used for anything.
98 /// Subclasses can use it to hold whatever state they find useful. This
99 /// field is initialized to zero by the ctor.
100 unsigned short SubclassData;
101
102 protected:
103 /// The number of operands in the subclass.
104 ///
105 /// This member is defined by this class, but not used for anything.
106 /// Subclasses can use it to store their number of operands, if they have
107 /// any.
108 ///
109 /// This is stored here to save space in User on 64-bit hosts. Since most
110 /// instances of Value have operands, 32-bit hosts aren't significantly
111 /// affected.
112 ///
113 /// Note, this should *NOT* be used directly by any class other than User.
114 /// User uses this value to find the Use list.
115 enum : unsigned { NumUserOperandsBits = 28 };
116 unsigned NumUserOperands : NumUserOperandsBits;
117
118 // Use the same type as the bitfield above so that MSVC will pack them.
119 unsigned IsUsedByMD : 1;
120 unsigned HasName : 1;
121 unsigned HasHungOffUses : 1;
122 unsigned HasDescriptor : 1;
123
124 private:
125 template <typename UseT> // UseT == 'Use' or 'const Use'
126 class use_iterator_impl {
127 friend class Value;
128
129 UseT *U;
130
use_iterator_impl(UseT * u)131 explicit use_iterator_impl(UseT *u) : U(u) {}
132
133 public:
134 using iterator_category = std::forward_iterator_tag;
135 using value_type = UseT *;
136 using difference_type = std::ptrdiff_t;
137 using pointer = UseT **;
138 using reference = UseT *&;
139
use_iterator_impl()140 use_iterator_impl() : U() {}
141
142 bool operator==(const use_iterator_impl &x) const { return U == x.U; }
143 bool operator!=(const use_iterator_impl &x) const { return !operator==(x); }
144
145 use_iterator_impl &operator++() { // Preincrement
146 assert(U && "Cannot increment end iterator!");
147 U = U->getNext();
148 return *this;
149 }
150
151 use_iterator_impl operator++(int) { // Postincrement
152 auto tmp = *this;
153 ++*this;
154 return tmp;
155 }
156
157 UseT &operator*() const {
158 assert(U && "Cannot dereference end iterator!");
159 return *U;
160 }
161
162 UseT *operator->() const { return &operator*(); }
163
164 operator use_iterator_impl<const UseT>() const {
165 return use_iterator_impl<const UseT>(U);
166 }
167 };
168
169 template <typename UserTy> // UserTy == 'User' or 'const User'
170 class user_iterator_impl {
171 use_iterator_impl<Use> UI;
user_iterator_impl(Use * U)172 explicit user_iterator_impl(Use *U) : UI(U) {}
173 friend class Value;
174
175 public:
176 using iterator_category = std::forward_iterator_tag;
177 using value_type = UserTy *;
178 using difference_type = std::ptrdiff_t;
179 using pointer = UserTy **;
180 using reference = UserTy *&;
181
182 user_iterator_impl() = default;
183
184 bool operator==(const user_iterator_impl &x) const { return UI == x.UI; }
185 bool operator!=(const user_iterator_impl &x) const { return !operator==(x); }
186
187 /// Returns true if this iterator is equal to user_end() on the value.
atEnd()188 bool atEnd() const { return *this == user_iterator_impl(); }
189
190 user_iterator_impl &operator++() { // Preincrement
191 ++UI;
192 return *this;
193 }
194
195 user_iterator_impl operator++(int) { // Postincrement
196 auto tmp = *this;
197 ++*this;
198 return tmp;
199 }
200
201 // Retrieve a pointer to the current User.
202 UserTy *operator*() const {
203 return UI->getUser();
204 }
205
206 UserTy *operator->() const { return operator*(); }
207
208 operator user_iterator_impl<const UserTy>() const {
209 return user_iterator_impl<const UserTy>(*UI);
210 }
211
getUse()212 Use &getUse() const { return *UI; }
213 };
214
215 protected:
216 Value(Type *Ty, unsigned scid);
217
218 /// Value's destructor should be virtual by design, but that would require
219 /// that Value and all of its subclasses have a vtable that effectively
220 /// duplicates the information in the value ID. As a size optimization, the
221 /// destructor has been protected, and the caller should manually call
222 /// deleteValue.
223 ~Value(); // Use deleteValue() to delete a generic Value.
224
225 public:
226 Value(const Value &) = delete;
227 Value &operator=(const Value &) = delete;
228
229 /// Delete a pointer to a generic Value.
230 void deleteValue();
231
232 /// Support for debugging, callable in GDB: V->dump()
233 void dump() const;
234
235 /// Implement operator<< on Value.
236 /// @{
237 void print(raw_ostream &O, bool IsForDebug = false) const;
238 void print(raw_ostream &O, ModuleSlotTracker &MST,
239 bool IsForDebug = false) const;
240 /// @}
241
242 /// Print the name of this Value out to the specified raw_ostream.
243 ///
244 /// This is useful when you just want to print 'int %reg126', not the
245 /// instruction that generated it. If you specify a Module for context, then
246 /// even constanst get pretty-printed; for example, the type of a null
247 /// pointer is printed symbolically.
248 /// @{
249 void printAsOperand(raw_ostream &O, bool PrintType = true,
250 const Module *M = nullptr) const;
251 void printAsOperand(raw_ostream &O, bool PrintType,
252 ModuleSlotTracker &MST) const;
253 /// @}
254
255 /// All values are typed, get the type of this value.
getType()256 Type *getType() const { return VTy; }
257
258 /// All values hold a context through their type.
259 LLVMContext &getContext() const;
260
261 // All values can potentially be named.
hasName()262 bool hasName() const { return HasName; }
263 ValueName *getValueName() const;
264 void setValueName(ValueName *VN);
265
266 private:
267 void destroyValueName();
268 enum class ReplaceMetadataUses { No, Yes };
269 void doRAUW(Value *New, ReplaceMetadataUses);
270 void setNameImpl(const Twine &Name);
271
272 public:
273 /// Return a constant reference to the value's name.
274 ///
275 /// This guaranteed to return the same reference as long as the value is not
276 /// modified. If the value has a name, this does a hashtable lookup, so it's
277 /// not free.
278 StringRef getName() const;
279
280 /// Change the name of the value.
281 ///
282 /// Choose a new unique name if the provided name is taken.
283 ///
284 /// \param Name The new name; or "" if the value's name should be removed.
285 void setName(const Twine &Name);
286
287 /// Transfer the name from V to this value.
288 ///
289 /// After taking V's name, sets V's name to empty.
290 ///
291 /// \note It is an error to call V->takeName(V).
292 void takeName(Value *V);
293
294 /// Change all uses of this to point to a new Value.
295 ///
296 /// Go through the uses list for this definition and make each use point to
297 /// "V" instead of "this". After this completes, 'this's use list is
298 /// guaranteed to be empty.
299 void replaceAllUsesWith(Value *V);
300
301 /// Change non-metadata uses of this to point to a new Value.
302 ///
303 /// Go through the uses list for this definition and make each use point to
304 /// "V" instead of "this". This function skips metadata entries in the list.
305 void replaceNonMetadataUsesWith(Value *V);
306
307 /// Go through the uses list for this definition and make each use point
308 /// to "V" if the callback ShouldReplace returns true for the given Use.
309 /// Unlike replaceAllUsesWith() this function does not support basic block
310 /// values or constant users.
replaceUsesWithIf(Value * New,llvm::function_ref<bool (Use & U)> ShouldReplace)311 void replaceUsesWithIf(Value *New,
312 llvm::function_ref<bool(Use &U)> ShouldReplace) {
313 assert(New && "Value::replaceUsesWithIf(<null>) is invalid!");
314 assert(New->getType() == getType() &&
315 "replaceUses of value with new value of different type!");
316
317 for (use_iterator UI = use_begin(), E = use_end(); UI != E;) {
318 Use &U = *UI;
319 ++UI;
320 if (!ShouldReplace(U))
321 continue;
322 U.set(New);
323 }
324 }
325
326 /// replaceUsesOutsideBlock - Go through the uses list for this definition and
327 /// make each use point to "V" instead of "this" when the use is outside the
328 /// block. 'This's use list is expected to have at least one element.
329 /// Unlike replaceAllUsesWith() this function does not support basic block
330 /// values or constant users.
331 void replaceUsesOutsideBlock(Value *V, BasicBlock *BB);
332
333 //----------------------------------------------------------------------
334 // Methods for handling the chain of uses of this Value.
335 //
336 // Materializing a function can introduce new uses, so these methods come in
337 // two variants:
338 // The methods that start with materialized_ check the uses that are
339 // currently known given which functions are materialized. Be very careful
340 // when using them since you might not get all uses.
341 // The methods that don't start with materialized_ assert that modules is
342 // fully materialized.
343 void assertModuleIsMaterializedImpl() const;
344 // This indirection exists so we can keep assertModuleIsMaterializedImpl()
345 // around in release builds of Value.cpp to be linked with other code built
346 // in debug mode. But this avoids calling it in any of the release built code.
assertModuleIsMaterialized()347 void assertModuleIsMaterialized() const {
348 #ifndef NDEBUG
349 assertModuleIsMaterializedImpl();
350 #endif
351 }
352
use_empty()353 bool use_empty() const {
354 assertModuleIsMaterialized();
355 return UseList == nullptr;
356 }
357
materialized_use_empty()358 bool materialized_use_empty() const {
359 return UseList == nullptr;
360 }
361
362 using use_iterator = use_iterator_impl<Use>;
363 using const_use_iterator = use_iterator_impl<const Use>;
364
materialized_use_begin()365 use_iterator materialized_use_begin() { return use_iterator(UseList); }
materialized_use_begin()366 const_use_iterator materialized_use_begin() const {
367 return const_use_iterator(UseList);
368 }
use_begin()369 use_iterator use_begin() {
370 assertModuleIsMaterialized();
371 return materialized_use_begin();
372 }
use_begin()373 const_use_iterator use_begin() const {
374 assertModuleIsMaterialized();
375 return materialized_use_begin();
376 }
use_end()377 use_iterator use_end() { return use_iterator(); }
use_end()378 const_use_iterator use_end() const { return const_use_iterator(); }
materialized_uses()379 iterator_range<use_iterator> materialized_uses() {
380 return make_range(materialized_use_begin(), use_end());
381 }
materialized_uses()382 iterator_range<const_use_iterator> materialized_uses() const {
383 return make_range(materialized_use_begin(), use_end());
384 }
uses()385 iterator_range<use_iterator> uses() {
386 assertModuleIsMaterialized();
387 return materialized_uses();
388 }
uses()389 iterator_range<const_use_iterator> uses() const {
390 assertModuleIsMaterialized();
391 return materialized_uses();
392 }
393
user_empty()394 bool user_empty() const {
395 assertModuleIsMaterialized();
396 return UseList == nullptr;
397 }
398
399 using user_iterator = user_iterator_impl<User>;
400 using const_user_iterator = user_iterator_impl<const User>;
401
materialized_user_begin()402 user_iterator materialized_user_begin() { return user_iterator(UseList); }
materialized_user_begin()403 const_user_iterator materialized_user_begin() const {
404 return const_user_iterator(UseList);
405 }
user_begin()406 user_iterator user_begin() {
407 assertModuleIsMaterialized();
408 return materialized_user_begin();
409 }
user_begin()410 const_user_iterator user_begin() const {
411 assertModuleIsMaterialized();
412 return materialized_user_begin();
413 }
user_end()414 user_iterator user_end() { return user_iterator(); }
user_end()415 const_user_iterator user_end() const { return const_user_iterator(); }
user_back()416 User *user_back() {
417 assertModuleIsMaterialized();
418 return *materialized_user_begin();
419 }
user_back()420 const User *user_back() const {
421 assertModuleIsMaterialized();
422 return *materialized_user_begin();
423 }
materialized_users()424 iterator_range<user_iterator> materialized_users() {
425 return make_range(materialized_user_begin(), user_end());
426 }
materialized_users()427 iterator_range<const_user_iterator> materialized_users() const {
428 return make_range(materialized_user_begin(), user_end());
429 }
users()430 iterator_range<user_iterator> users() {
431 assertModuleIsMaterialized();
432 return materialized_users();
433 }
users()434 iterator_range<const_user_iterator> users() const {
435 assertModuleIsMaterialized();
436 return materialized_users();
437 }
438
439 /// Return true if there is exactly one user of this value.
440 ///
441 /// This is specialized because it is a common request and does not require
442 /// traversing the whole use list.
hasOneUse()443 bool hasOneUse() const {
444 const_use_iterator I = use_begin(), E = use_end();
445 if (I == E) return false;
446 return ++I == E;
447 }
448
449 /// Return true if this Value has exactly N users.
450 bool hasNUses(unsigned N) const;
451
452 /// Return true if this value has N users or more.
453 ///
454 /// This is logically equivalent to getNumUses() >= N.
455 bool hasNUsesOrMore(unsigned N) const;
456
457 /// Check if this value is used in the specified basic block.
458 bool isUsedInBasicBlock(const BasicBlock *BB) const;
459
460 /// This method computes the number of uses of this Value.
461 ///
462 /// This is a linear time operation. Use hasOneUse, hasNUses, or
463 /// hasNUsesOrMore to check for specific values.
464 unsigned getNumUses() const;
465
466 /// This method should only be used by the Use class.
addUse(Use & U)467 void addUse(Use &U) { U.addToList(&UseList); }
468
469 /// Concrete subclass of this.
470 ///
471 /// An enumeration for keeping track of the concrete subclass of Value that
472 /// is actually instantiated. Values of this enumeration are kept in the
473 /// Value classes SubclassID field. They are used for concrete type
474 /// identification.
475 enum ValueTy {
476 #define HANDLE_VALUE(Name) Name##Val,
477 #include "llvm/IR/Value.def"
478
479 // Markers:
480 #define HANDLE_CONSTANT_MARKER(Marker, Constant) Marker = Constant##Val,
481 #include "llvm/IR/Value.def"
482 };
483
484 /// Return an ID for the concrete type of this object.
485 ///
486 /// This is used to implement the classof checks. This should not be used
487 /// for any other purpose, as the values may change as LLVM evolves. Also,
488 /// note that for instructions, the Instruction's opcode is added to
489 /// InstructionVal. So this means three things:
490 /// # there is no value with code InstructionVal (no opcode==0).
491 /// # there are more possible values for the value type than in ValueTy enum.
492 /// # the InstructionVal enumerator must be the highest valued enumerator in
493 /// the ValueTy enum.
getValueID()494 unsigned getValueID() const {
495 return SubclassID;
496 }
497
498 /// Return the raw optional flags value contained in this value.
499 ///
500 /// This should only be used when testing two Values for equivalence.
getRawSubclassOptionalData()501 unsigned getRawSubclassOptionalData() const {
502 return SubclassOptionalData;
503 }
504
505 /// Clear the optional flags contained in this value.
clearSubclassOptionalData()506 void clearSubclassOptionalData() {
507 SubclassOptionalData = 0;
508 }
509
510 /// Check the optional flags for equality.
hasSameSubclassOptionalData(const Value * V)511 bool hasSameSubclassOptionalData(const Value *V) const {
512 return SubclassOptionalData == V->SubclassOptionalData;
513 }
514
515 /// Return true if there is a value handle associated with this value.
hasValueHandle()516 bool hasValueHandle() const { return HasValueHandle; }
517
518 /// Return true if there is metadata referencing this value.
isUsedByMetadata()519 bool isUsedByMetadata() const { return IsUsedByMD; }
520
521 /// Return true if this value is a swifterror value.
522 ///
523 /// swifterror values can be either a function argument or an alloca with a
524 /// swifterror attribute.
525 bool isSwiftError() const;
526
527 /// Strip off pointer casts, all-zero GEPs and address space casts.
528 ///
529 /// Returns the original uncasted value. If this is called on a non-pointer
530 /// value, it returns 'this'.
531 const Value *stripPointerCasts() const;
stripPointerCasts()532 Value *stripPointerCasts() {
533 return const_cast<Value *>(
534 static_cast<const Value *>(this)->stripPointerCasts());
535 }
536
537 /// Strip off pointer casts, all-zero GEPs, address space casts, and aliases.
538 ///
539 /// Returns the original uncasted value. If this is called on a non-pointer
540 /// value, it returns 'this'.
541 const Value *stripPointerCastsAndAliases() const;
stripPointerCastsAndAliases()542 Value *stripPointerCastsAndAliases() {
543 return const_cast<Value *>(
544 static_cast<const Value *>(this)->stripPointerCastsAndAliases());
545 }
546
547 /// Strip off pointer casts, all-zero GEPs and address space casts
548 /// but ensures the representation of the result stays the same.
549 ///
550 /// Returns the original uncasted value with the same representation. If this
551 /// is called on a non-pointer value, it returns 'this'.
552 const Value *stripPointerCastsSameRepresentation() const;
stripPointerCastsSameRepresentation()553 Value *stripPointerCastsSameRepresentation() {
554 return const_cast<Value *>(static_cast<const Value *>(this)
555 ->stripPointerCastsSameRepresentation());
556 }
557
558 /// Strip off pointer casts, all-zero GEPs and invariant group info.
559 ///
560 /// Returns the original uncasted value. If this is called on a non-pointer
561 /// value, it returns 'this'. This function should be used only in
562 /// Alias analysis.
563 const Value *stripPointerCastsAndInvariantGroups() const;
stripPointerCastsAndInvariantGroups()564 Value *stripPointerCastsAndInvariantGroups() {
565 return const_cast<Value *>(static_cast<const Value *>(this)
566 ->stripPointerCastsAndInvariantGroups());
567 }
568
569 /// Strip off pointer casts and all-constant inbounds GEPs.
570 ///
571 /// Returns the original pointer value. If this is called on a non-pointer
572 /// value, it returns 'this'.
573 const Value *stripInBoundsConstantOffsets() const;
stripInBoundsConstantOffsets()574 Value *stripInBoundsConstantOffsets() {
575 return const_cast<Value *>(
576 static_cast<const Value *>(this)->stripInBoundsConstantOffsets());
577 }
578
579 /// Accumulate the constant offset this value has compared to a base pointer.
580 /// Only 'getelementptr' instructions (GEPs) with constant indices are
581 /// accumulated but other instructions, e.g., casts, are stripped away as
582 /// well. The accumulated constant offset is added to \p Offset and the base
583 /// pointer is returned.
584 ///
585 /// The APInt \p Offset has to have a bit-width equal to the IntPtr type for
586 /// the address space of 'this' pointer value, e.g., use
587 /// DataLayout::getIndexTypeSizeInBits(Ty).
588 ///
589 /// If \p AllowNonInbounds is true, constant offsets in GEPs are stripped and
590 /// accumulated even if the GEP is not "inbounds".
591 ///
592 /// If this is called on a non-pointer value, it returns 'this' and the
593 /// \p Offset is not modified.
594 ///
595 /// Note that this function will never return a nullptr. It will also never
596 /// manipulate the \p Offset in a way that would not match the difference
597 /// between the underlying value and the returned one. Thus, if no constant
598 /// offset was found, the returned value is the underlying one and \p Offset
599 /// is unchanged.
600 const Value *stripAndAccumulateConstantOffsets(const DataLayout &DL,
601 APInt &Offset,
602 bool AllowNonInbounds) const;
stripAndAccumulateConstantOffsets(const DataLayout & DL,APInt & Offset,bool AllowNonInbounds)603 Value *stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset,
604 bool AllowNonInbounds) {
605 return const_cast<Value *>(
606 static_cast<const Value *>(this)->stripAndAccumulateConstantOffsets(
607 DL, Offset, AllowNonInbounds));
608 }
609
610 /// This is a wrapper around stripAndAccumulateConstantOffsets with the
611 /// in-bounds requirement set to false.
stripAndAccumulateInBoundsConstantOffsets(const DataLayout & DL,APInt & Offset)612 const Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
613 APInt &Offset) const {
614 return stripAndAccumulateConstantOffsets(DL, Offset,
615 /* AllowNonInbounds */ false);
616 }
stripAndAccumulateInBoundsConstantOffsets(const DataLayout & DL,APInt & Offset)617 Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
618 APInt &Offset) {
619 return stripAndAccumulateConstantOffsets(DL, Offset,
620 /* AllowNonInbounds */ false);
621 }
622
623 /// Strip off pointer casts and inbounds GEPs.
624 ///
625 /// Returns the original pointer value. If this is called on a non-pointer
626 /// value, it returns 'this'.
627 const Value *stripInBoundsOffsets() const;
stripInBoundsOffsets()628 Value *stripInBoundsOffsets() {
629 return const_cast<Value *>(
630 static_cast<const Value *>(this)->stripInBoundsOffsets());
631 }
632
633 /// Returns the number of bytes known to be dereferenceable for the
634 /// pointer value.
635 ///
636 /// If CanBeNull is set by this function the pointer can either be null or be
637 /// dereferenceable up to the returned number of bytes.
638 uint64_t getPointerDereferenceableBytes(const DataLayout &DL,
639 bool &CanBeNull) const;
640
641 /// Returns an alignment of the pointer value.
642 ///
643 /// Returns an alignment which is either specified explicitly, e.g. via
644 /// align attribute of a function argument, or guaranteed by DataLayout.
645 MaybeAlign getPointerAlignment(const DataLayout &DL) const;
646
647 /// Translate PHI node to its predecessor from the given basic block.
648 ///
649 /// If this value is a PHI node with CurBB as its parent, return the value in
650 /// the PHI node corresponding to PredBB. If not, return ourself. This is
651 /// useful if you want to know the value something has in a predecessor
652 /// block.
653 const Value *DoPHITranslation(const BasicBlock *CurBB,
654 const BasicBlock *PredBB) const;
DoPHITranslation(const BasicBlock * CurBB,const BasicBlock * PredBB)655 Value *DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB) {
656 return const_cast<Value *>(
657 static_cast<const Value *>(this)->DoPHITranslation(CurBB, PredBB));
658 }
659
660 /// The maximum alignment for instructions.
661 ///
662 /// This is the greatest alignment value supported by load, store, and alloca
663 /// instructions, and global values.
664 static const unsigned MaxAlignmentExponent = 29;
665 static const unsigned MaximumAlignment = 1u << MaxAlignmentExponent;
666
667 /// Mutate the type of this Value to be of the specified type.
668 ///
669 /// Note that this is an extremely dangerous operation which can create
670 /// completely invalid IR very easily. It is strongly recommended that you
671 /// recreate IR objects with the right types instead of mutating them in
672 /// place.
mutateType(Type * Ty)673 void mutateType(Type *Ty) {
674 VTy = Ty;
675 }
676
677 /// Sort the use-list.
678 ///
679 /// Sorts the Value's use-list by Cmp using a stable mergesort. Cmp is
680 /// expected to compare two \a Use references.
681 template <class Compare> void sortUseList(Compare Cmp);
682
683 /// Reverse the use-list.
684 void reverseUseList();
685
686 private:
687 /// Merge two lists together.
688 ///
689 /// Merges \c L and \c R using \c Cmp. To enable stable sorts, always pushes
690 /// "equal" items from L before items from R.
691 ///
692 /// \return the first element in the list.
693 ///
694 /// \note Completely ignores \a Use::Prev (doesn't read, doesn't update).
695 template <class Compare>
mergeUseLists(Use * L,Use * R,Compare Cmp)696 static Use *mergeUseLists(Use *L, Use *R, Compare Cmp) {
697 Use *Merged;
698 Use **Next = &Merged;
699
700 while (true) {
701 if (!L) {
702 *Next = R;
703 break;
704 }
705 if (!R) {
706 *Next = L;
707 break;
708 }
709 if (Cmp(*R, *L)) {
710 *Next = R;
711 Next = &R->Next;
712 R = R->Next;
713 } else {
714 *Next = L;
715 Next = &L->Next;
716 L = L->Next;
717 }
718 }
719
720 return Merged;
721 }
722
723 protected:
getSubclassDataFromValue()724 unsigned short getSubclassDataFromValue() const { return SubclassData; }
setValueSubclassData(unsigned short D)725 void setValueSubclassData(unsigned short D) { SubclassData = D; }
726 };
727
operatorValueDeleter728 struct ValueDeleter { void operator()(Value *V) { V->deleteValue(); } };
729
730 /// Use this instead of std::unique_ptr<Value> or std::unique_ptr<Instruction>.
731 /// Those don't work because Value and Instruction's destructors are protected,
732 /// aren't virtual, and won't destroy the complete object.
733 using unique_value = std::unique_ptr<Value, ValueDeleter>;
734
735 inline raw_ostream &operator<<(raw_ostream &OS, const Value &V) {
736 V.print(OS);
737 return OS;
738 }
739
set(Value * V)740 void Use::set(Value *V) {
741 if (Val) removeFromList();
742 Val = V;
743 if (V) V->addUse(*this);
744 }
745
746 Value *Use::operator=(Value *RHS) {
747 set(RHS);
748 return RHS;
749 }
750
751 const Use &Use::operator=(const Use &RHS) {
752 set(RHS.Val);
753 return *this;
754 }
755
sortUseList(Compare Cmp)756 template <class Compare> void Value::sortUseList(Compare Cmp) {
757 if (!UseList || !UseList->Next)
758 // No need to sort 0 or 1 uses.
759 return;
760
761 // Note: this function completely ignores Prev pointers until the end when
762 // they're fixed en masse.
763
764 // Create a binomial vector of sorted lists, visiting uses one at a time and
765 // merging lists as necessary.
766 const unsigned MaxSlots = 32;
767 Use *Slots[MaxSlots];
768
769 // Collect the first use, turning it into a single-item list.
770 Use *Next = UseList->Next;
771 UseList->Next = nullptr;
772 unsigned NumSlots = 1;
773 Slots[0] = UseList;
774
775 // Collect all but the last use.
776 while (Next->Next) {
777 Use *Current = Next;
778 Next = Current->Next;
779
780 // Turn Current into a single-item list.
781 Current->Next = nullptr;
782
783 // Save Current in the first available slot, merging on collisions.
784 unsigned I;
785 for (I = 0; I < NumSlots; ++I) {
786 if (!Slots[I])
787 break;
788
789 // Merge two lists, doubling the size of Current and emptying slot I.
790 //
791 // Since the uses in Slots[I] originally preceded those in Current, send
792 // Slots[I] in as the left parameter to maintain a stable sort.
793 Current = mergeUseLists(Slots[I], Current, Cmp);
794 Slots[I] = nullptr;
795 }
796 // Check if this is a new slot.
797 if (I == NumSlots) {
798 ++NumSlots;
799 assert(NumSlots <= MaxSlots && "Use list bigger than 2^32");
800 }
801
802 // Found an open slot.
803 Slots[I] = Current;
804 }
805
806 // Merge all the lists together.
807 assert(Next && "Expected one more Use");
808 assert(!Next->Next && "Expected only one Use");
809 UseList = Next;
810 for (unsigned I = 0; I < NumSlots; ++I)
811 if (Slots[I])
812 // Since the uses in Slots[I] originally preceded those in UseList, send
813 // Slots[I] in as the left parameter to maintain a stable sort.
814 UseList = mergeUseLists(Slots[I], UseList, Cmp);
815
816 // Fix the Prev pointers.
817 for (Use *I = UseList, **Prev = &UseList; I; I = I->Next) {
818 I->setPrev(Prev);
819 Prev = &I->Next;
820 }
821 }
822
823 // isa - Provide some specializations of isa so that we don't have to include
824 // the subtype header files to test to see if the value is a subclass...
825 //
826 template <> struct isa_impl<Constant, Value> {
827 static inline bool doit(const Value &Val) {
828 static_assert(Value::ConstantFirstVal == 0, "Val.getValueID() >= Value::ConstantFirstVal");
829 return Val.getValueID() <= Value::ConstantLastVal;
830 }
831 };
832
833 template <> struct isa_impl<ConstantData, Value> {
834 static inline bool doit(const Value &Val) {
835 return Val.getValueID() >= Value::ConstantDataFirstVal &&
836 Val.getValueID() <= Value::ConstantDataLastVal;
837 }
838 };
839
840 template <> struct isa_impl<ConstantAggregate, Value> {
841 static inline bool doit(const Value &Val) {
842 return Val.getValueID() >= Value::ConstantAggregateFirstVal &&
843 Val.getValueID() <= Value::ConstantAggregateLastVal;
844 }
845 };
846
847 template <> struct isa_impl<Argument, Value> {
848 static inline bool doit (const Value &Val) {
849 return Val.getValueID() == Value::ArgumentVal;
850 }
851 };
852
853 template <> struct isa_impl<InlineAsm, Value> {
854 static inline bool doit(const Value &Val) {
855 return Val.getValueID() == Value::InlineAsmVal;
856 }
857 };
858
859 template <> struct isa_impl<Instruction, Value> {
860 static inline bool doit(const Value &Val) {
861 return Val.getValueID() >= Value::InstructionVal;
862 }
863 };
864
865 template <> struct isa_impl<BasicBlock, Value> {
866 static inline bool doit(const Value &Val) {
867 return Val.getValueID() == Value::BasicBlockVal;
868 }
869 };
870
871 template <> struct isa_impl<Function, Value> {
872 static inline bool doit(const Value &Val) {
873 return Val.getValueID() == Value::FunctionVal;
874 }
875 };
876
877 template <> struct isa_impl<GlobalVariable, Value> {
878 static inline bool doit(const Value &Val) {
879 return Val.getValueID() == Value::GlobalVariableVal;
880 }
881 };
882
883 template <> struct isa_impl<GlobalAlias, Value> {
884 static inline bool doit(const Value &Val) {
885 return Val.getValueID() == Value::GlobalAliasVal;
886 }
887 };
888
889 template <> struct isa_impl<GlobalIFunc, Value> {
890 static inline bool doit(const Value &Val) {
891 return Val.getValueID() == Value::GlobalIFuncVal;
892 }
893 };
894
895 template <> struct isa_impl<GlobalIndirectSymbol, Value> {
896 static inline bool doit(const Value &Val) {
897 return isa<GlobalAlias>(Val) || isa<GlobalIFunc>(Val);
898 }
899 };
900
901 template <> struct isa_impl<GlobalValue, Value> {
902 static inline bool doit(const Value &Val) {
903 return isa<GlobalObject>(Val) || isa<GlobalIndirectSymbol>(Val);
904 }
905 };
906
907 template <> struct isa_impl<GlobalObject, Value> {
908 static inline bool doit(const Value &Val) {
909 return isa<GlobalVariable>(Val) || isa<Function>(Val);
910 }
911 };
912
913 // Create wrappers for C Binding types (see CBindingWrapping.h).
914 DEFINE_ISA_CONVERSION_FUNCTIONS(Value, LLVMValueRef)
915
916 // Specialized opaque value conversions.
917 inline Value **unwrap(LLVMValueRef *Vals) {
918 return reinterpret_cast<Value**>(Vals);
919 }
920
921 template<typename T>
922 inline T **unwrap(LLVMValueRef *Vals, unsigned Length) {
923 #ifndef NDEBUG
924 for (LLVMValueRef *I = Vals, *E = Vals + Length; I != E; ++I)
925 unwrap<T>(*I); // For side effect of calling assert on invalid usage.
926 #endif
927 (void)Length;
928 return reinterpret_cast<T**>(Vals);
929 }
930
931 inline LLVMValueRef *wrap(const Value **Vals) {
932 return reinterpret_cast<LLVMValueRef*>(const_cast<Value**>(Vals));
933 }
934
935 } // end namespace llvm
936
937 #endif // LLVM_IR_VALUE_H
938