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/StringRef.h"
19 #include "llvm/ADT/iterator_range.h"
20 #include "llvm/IR/Use.h"
21 #include "llvm/Support/Alignment.h"
22 #include "llvm/Support/CBindingWrapping.h"
23 #include "llvm/Support/Casting.h"
24 #include <cassert>
25 #include <iterator>
26 #include <memory>
27 
28 namespace llvm {
29 
30 class APInt;
31 class Argument;
32 class BasicBlock;
33 class Constant;
34 class ConstantData;
35 class ConstantAggregate;
36 class DataLayout;
37 class Function;
38 class GlobalAlias;
39 class GlobalIFunc;
40 class GlobalIndirectSymbol;
41 class GlobalObject;
42 class GlobalValue;
43 class GlobalVariable;
44 class InlineAsm;
45 class Instruction;
46 class LLVMContext;
47 class MDNode;
48 class Module;
49 class ModuleSlotTracker;
50 class raw_ostream;
51 template<typename ValueTy> class StringMapEntry;
52 class Twine;
53 class Type;
54 class User;
55 
56 using ValueName = StringMapEntry<Value *>;
57 
58 //===----------------------------------------------------------------------===//
59 //                                 Value Class
60 //===----------------------------------------------------------------------===//
61 
62 /// LLVM Value Representation
63 ///
64 /// This is a very important LLVM class. It is the base class of all values
65 /// computed by a program that may be used as operands to other values. Value is
66 /// the super class of other important classes such as Instruction and Function.
67 /// All Values have a Type. Type is not a subclass of Value. Some values can
68 /// have a name and they belong to some Module.  Setting the name on the Value
69 /// automatically updates the module's symbol table.
70 ///
71 /// Every value has a "use list" that keeps track of which other Values are
72 /// using this Value.  A Value can also have an arbitrary number of ValueHandle
73 /// objects that watch it and listen to RAUW and Destroy events.  See
74 /// llvm/IR/ValueHandle.h for details.
75 class Value {
76   Type *VTy;
77   Use *UseList;
78 
79   friend class ValueAsMetadata; // Allow access to IsUsedByMD.
80   friend class ValueHandleBase;
81 
82   const unsigned char SubclassID;   // Subclass identifier (for isa/dyn_cast)
83   unsigned char HasValueHandle : 1; // Has a ValueHandle pointing to this?
84 
85 protected:
86   /// Hold subclass data that can be dropped.
87   ///
88   /// This member is similar to SubclassData, however it is for holding
89   /// information which may be used to aid optimization, but which may be
90   /// cleared to zero without affecting conservative interpretation.
91   unsigned char SubclassOptionalData : 7;
92 
93 private:
94   /// Hold arbitrary subclass data.
95   ///
96   /// This member is defined by this class, but is not used for anything.
97   /// Subclasses can use it to hold whatever state they find useful.  This
98   /// field is initialized to zero by the ctor.
99   unsigned short SubclassData;
100 
101 protected:
102   /// The number of operands in the subclass.
103   ///
104   /// This member is defined by this class, but not used for anything.
105   /// Subclasses can use it to store their number of operands, if they have
106   /// any.
107   ///
108   /// This is stored here to save space in User on 64-bit hosts.  Since most
109   /// instances of Value have operands, 32-bit hosts aren't significantly
110   /// affected.
111   ///
112   /// Note, this should *NOT* be used directly by any class other than User.
113   /// User uses this value to find the Use list.
114   enum : unsigned { NumUserOperandsBits = 27 };
115   unsigned NumUserOperands : NumUserOperandsBits;
116 
117   // Use the same type as the bitfield above so that MSVC will pack them.
118   unsigned IsUsedByMD : 1;
119   unsigned HasName : 1;
120   unsigned HasMetadata : 1; // Has metadata attached to this?
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 = value_type *;
138     using reference = value_type &;
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 = value_type *;
180     using reference = value_type &;
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 #ifndef NDEBUG
295   std::string getNameOrAsOperand() const;
296 #endif
297 
298   /// Change all uses of this to point to a new Value.
299   ///
300   /// Go through the uses list for this definition and make each use point to
301   /// "V" instead of "this".  After this completes, 'this's use list is
302   /// guaranteed to be empty.
303   void replaceAllUsesWith(Value *V);
304 
305   /// Change non-metadata uses of this to point to a new Value.
306   ///
307   /// Go through the uses list for this definition and make each use point to
308   /// "V" instead of "this". This function skips metadata entries in the list.
309   void replaceNonMetadataUsesWith(Value *V);
310 
311   /// Go through the uses list for this definition and make each use point
312   /// to "V" if the callback ShouldReplace returns true for the given Use.
313   /// Unlike replaceAllUsesWith() this function does not support basic block
314   /// values.
315   void replaceUsesWithIf(Value *New,
316                          llvm::function_ref<bool(Use &U)> ShouldReplace);
317 
318   /// replaceUsesOutsideBlock - Go through the uses list for this definition and
319   /// make each use point to "V" instead of "this" when the use is outside the
320   /// block. 'This's use list is expected to have at least one element.
321   /// Unlike replaceAllUsesWith() this function does not support basic block
322   /// values.
323   void replaceUsesOutsideBlock(Value *V, BasicBlock *BB);
324 
325   //----------------------------------------------------------------------
326   // Methods for handling the chain of uses of this Value.
327   //
328   // Materializing a function can introduce new uses, so these methods come in
329   // two variants:
330   // The methods that start with materialized_ check the uses that are
331   // currently known given which functions are materialized. Be very careful
332   // when using them since you might not get all uses.
333   // The methods that don't start with materialized_ assert that modules is
334   // fully materialized.
335   void assertModuleIsMaterializedImpl() const;
336   // This indirection exists so we can keep assertModuleIsMaterializedImpl()
337   // around in release builds of Value.cpp to be linked with other code built
338   // in debug mode. But this avoids calling it in any of the release built code.
assertModuleIsMaterialized()339   void assertModuleIsMaterialized() const {
340 #ifndef NDEBUG
341     assertModuleIsMaterializedImpl();
342 #endif
343   }
344 
use_empty()345   bool use_empty() const {
346     assertModuleIsMaterialized();
347     return UseList == nullptr;
348   }
349 
materialized_use_empty()350   bool materialized_use_empty() const {
351     return UseList == nullptr;
352   }
353 
354   using use_iterator = use_iterator_impl<Use>;
355   using const_use_iterator = use_iterator_impl<const Use>;
356 
materialized_use_begin()357   use_iterator materialized_use_begin() { return use_iterator(UseList); }
materialized_use_begin()358   const_use_iterator materialized_use_begin() const {
359     return const_use_iterator(UseList);
360   }
use_begin()361   use_iterator use_begin() {
362     assertModuleIsMaterialized();
363     return materialized_use_begin();
364   }
use_begin()365   const_use_iterator use_begin() const {
366     assertModuleIsMaterialized();
367     return materialized_use_begin();
368   }
use_end()369   use_iterator use_end() { return use_iterator(); }
use_end()370   const_use_iterator use_end() const { return const_use_iterator(); }
materialized_uses()371   iterator_range<use_iterator> materialized_uses() {
372     return make_range(materialized_use_begin(), use_end());
373   }
materialized_uses()374   iterator_range<const_use_iterator> materialized_uses() const {
375     return make_range(materialized_use_begin(), use_end());
376   }
uses()377   iterator_range<use_iterator> uses() {
378     assertModuleIsMaterialized();
379     return materialized_uses();
380   }
uses()381   iterator_range<const_use_iterator> uses() const {
382     assertModuleIsMaterialized();
383     return materialized_uses();
384   }
385 
user_empty()386   bool user_empty() const {
387     assertModuleIsMaterialized();
388     return UseList == nullptr;
389   }
390 
391   using user_iterator = user_iterator_impl<User>;
392   using const_user_iterator = user_iterator_impl<const User>;
393 
materialized_user_begin()394   user_iterator materialized_user_begin() { return user_iterator(UseList); }
materialized_user_begin()395   const_user_iterator materialized_user_begin() const {
396     return const_user_iterator(UseList);
397   }
user_begin()398   user_iterator user_begin() {
399     assertModuleIsMaterialized();
400     return materialized_user_begin();
401   }
user_begin()402   const_user_iterator user_begin() const {
403     assertModuleIsMaterialized();
404     return materialized_user_begin();
405   }
user_end()406   user_iterator user_end() { return user_iterator(); }
user_end()407   const_user_iterator user_end() const { return const_user_iterator(); }
user_back()408   User *user_back() {
409     assertModuleIsMaterialized();
410     return *materialized_user_begin();
411   }
user_back()412   const User *user_back() const {
413     assertModuleIsMaterialized();
414     return *materialized_user_begin();
415   }
materialized_users()416   iterator_range<user_iterator> materialized_users() {
417     return make_range(materialized_user_begin(), user_end());
418   }
materialized_users()419   iterator_range<const_user_iterator> materialized_users() const {
420     return make_range(materialized_user_begin(), user_end());
421   }
users()422   iterator_range<user_iterator> users() {
423     assertModuleIsMaterialized();
424     return materialized_users();
425   }
users()426   iterator_range<const_user_iterator> users() const {
427     assertModuleIsMaterialized();
428     return materialized_users();
429   }
430 
431   /// Return true if there is exactly one use of this value.
432   ///
433   /// This is specialized because it is a common request and does not require
434   /// traversing the whole use list.
hasOneUse()435   bool hasOneUse() const { return hasSingleElement(uses()); }
436 
437   /// Return true if this Value has exactly N uses.
438   bool hasNUses(unsigned N) const;
439 
440   /// Return true if this value has N uses or more.
441   ///
442   /// This is logically equivalent to getNumUses() >= N.
443   bool hasNUsesOrMore(unsigned N) const;
444 
445   /// Return true if there is exactly one user of this value.
446   ///
447   /// Note that this is not the same as "has one use". If a value has one use,
448   /// then there certainly is a single user. But if value has several uses,
449   /// it is possible that all uses are in a single user, or not.
450   ///
451   /// This check is potentially costly, since it requires traversing,
452   /// in the worst case, the whole use list of a value.
453   bool hasOneUser() const;
454 
455   /// Return true if there is exactly one use of this value that cannot be
456   /// dropped.
457   ///
458   /// This is specialized because it is a common request and does not require
459   /// traversing the whole use list.
460   Use *getSingleUndroppableUse();
getSingleUndroppableUse()461   const Use *getSingleUndroppableUse() const {
462     return const_cast<Value *>(this)->getSingleUndroppableUse();
463   }
464 
465   /// Return true if there this value.
466   ///
467   /// This is specialized because it is a common request and does not require
468   /// traversing the whole use list.
469   bool hasNUndroppableUses(unsigned N) const;
470 
471   /// Return true if this value has N uses or more.
472   ///
473   /// This is logically equivalent to getNumUses() >= N.
474   bool hasNUndroppableUsesOrMore(unsigned N) const;
475 
476   /// Remove every uses that can safely be removed.
477   ///
478   /// This will remove for example uses in llvm.assume.
479   /// This should be used when performing want to perform a tranformation but
480   /// some Droppable uses pervent it.
481   /// This function optionally takes a filter to only remove some droppable
482   /// uses.
483   void dropDroppableUses(llvm::function_ref<bool(const Use *)> ShouldDrop =
484                              [](const Use *) { return true; });
485 
486   /// Remove every use of this value in \p User that can safely be removed.
487   void dropDroppableUsesIn(User &Usr);
488 
489   /// Remove the droppable use \p U.
490   static void dropDroppableUse(Use &U);
491 
492   /// Check if this value is used in the specified basic block.
493   bool isUsedInBasicBlock(const BasicBlock *BB) const;
494 
495   /// This method computes the number of uses of this Value.
496   ///
497   /// This is a linear time operation.  Use hasOneUse, hasNUses, or
498   /// hasNUsesOrMore to check for specific values.
499   unsigned getNumUses() const;
500 
501   /// This method should only be used by the Use class.
addUse(Use & U)502   void addUse(Use &U) { U.addToList(&UseList); }
503 
504   /// Concrete subclass of this.
505   ///
506   /// An enumeration for keeping track of the concrete subclass of Value that
507   /// is actually instantiated. Values of this enumeration are kept in the
508   /// Value classes SubclassID field. They are used for concrete type
509   /// identification.
510   enum ValueTy {
511 #define HANDLE_VALUE(Name) Name##Val,
512 #include "llvm/IR/Value.def"
513 
514     // Markers:
515 #define HANDLE_CONSTANT_MARKER(Marker, Constant) Marker = Constant##Val,
516 #include "llvm/IR/Value.def"
517   };
518 
519   /// Return an ID for the concrete type of this object.
520   ///
521   /// This is used to implement the classof checks.  This should not be used
522   /// for any other purpose, as the values may change as LLVM evolves.  Also,
523   /// note that for instructions, the Instruction's opcode is added to
524   /// InstructionVal. So this means three things:
525   /// # there is no value with code InstructionVal (no opcode==0).
526   /// # there are more possible values for the value type than in ValueTy enum.
527   /// # the InstructionVal enumerator must be the highest valued enumerator in
528   ///   the ValueTy enum.
getValueID()529   unsigned getValueID() const {
530     return SubclassID;
531   }
532 
533   /// Return the raw optional flags value contained in this value.
534   ///
535   /// This should only be used when testing two Values for equivalence.
getRawSubclassOptionalData()536   unsigned getRawSubclassOptionalData() const {
537     return SubclassOptionalData;
538   }
539 
540   /// Clear the optional flags contained in this value.
clearSubclassOptionalData()541   void clearSubclassOptionalData() {
542     SubclassOptionalData = 0;
543   }
544 
545   /// Check the optional flags for equality.
hasSameSubclassOptionalData(const Value * V)546   bool hasSameSubclassOptionalData(const Value *V) const {
547     return SubclassOptionalData == V->SubclassOptionalData;
548   }
549 
550   /// Return true if there is a value handle associated with this value.
hasValueHandle()551   bool hasValueHandle() const { return HasValueHandle; }
552 
553   /// Return true if there is metadata referencing this value.
isUsedByMetadata()554   bool isUsedByMetadata() const { return IsUsedByMD; }
555 
556   // Return true if this value is only transitively referenced by metadata.
557   bool isTransitiveUsedByMetadataOnly() const;
558 
559 protected:
560   /// Get the current metadata attachments for the given kind, if any.
561   ///
562   /// These functions require that the value have at most a single attachment
563   /// of the given kind, and return \c nullptr if such an attachment is missing.
564   /// @{
565   MDNode *getMetadata(unsigned KindID) const;
566   MDNode *getMetadata(StringRef Kind) const;
567   /// @}
568 
569   /// Appends all attachments with the given ID to \c MDs in insertion order.
570   /// If the Value has no attachments with the given ID, or if ID is invalid,
571   /// leaves MDs unchanged.
572   /// @{
573   void getMetadata(unsigned KindID, SmallVectorImpl<MDNode *> &MDs) const;
574   void getMetadata(StringRef Kind, SmallVectorImpl<MDNode *> &MDs) const;
575   /// @}
576 
577   /// Appends all metadata attached to this value to \c MDs, sorting by
578   /// KindID. The first element of each pair returned is the KindID, the second
579   /// element is the metadata value. Attachments with the same ID appear in
580   /// insertion order.
581   void
582   getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const;
583 
584   /// Return true if this value has any metadata attached to it.
hasMetadata()585   bool hasMetadata() const { return (bool)HasMetadata; }
586 
587   /// Return true if this value has the given type of metadata attached.
588   /// @{
hasMetadata(unsigned KindID)589   bool hasMetadata(unsigned KindID) const {
590     return getMetadata(KindID) != nullptr;
591   }
hasMetadata(StringRef Kind)592   bool hasMetadata(StringRef Kind) const {
593     return getMetadata(Kind) != nullptr;
594   }
595   /// @}
596 
597   /// Set a particular kind of metadata attachment.
598   ///
599   /// Sets the given attachment to \c MD, erasing it if \c MD is \c nullptr or
600   /// replacing it if it already exists.
601   /// @{
602   void setMetadata(unsigned KindID, MDNode *Node);
603   void setMetadata(StringRef Kind, MDNode *Node);
604   /// @}
605 
606   /// Add a metadata attachment.
607   /// @{
608   void addMetadata(unsigned KindID, MDNode &MD);
609   void addMetadata(StringRef Kind, MDNode &MD);
610   /// @}
611 
612   /// Erase all metadata attachments with the given kind.
613   ///
614   /// \returns true if any metadata was removed.
615   bool eraseMetadata(unsigned KindID);
616 
617   /// Erase all metadata attached to this Value.
618   void clearMetadata();
619 
620 public:
621   /// Return true if this value is a swifterror value.
622   ///
623   /// swifterror values can be either a function argument or an alloca with a
624   /// swifterror attribute.
625   bool isSwiftError() const;
626 
627   /// Strip off pointer casts, all-zero GEPs and address space casts.
628   ///
629   /// Returns the original uncasted value.  If this is called on a non-pointer
630   /// value, it returns 'this'.
631   const Value *stripPointerCasts() const;
stripPointerCasts()632   Value *stripPointerCasts() {
633     return const_cast<Value *>(
634         static_cast<const Value *>(this)->stripPointerCasts());
635   }
636 
637   /// Strip off pointer casts, all-zero GEPs, address space casts, and aliases.
638   ///
639   /// Returns the original uncasted value.  If this is called on a non-pointer
640   /// value, it returns 'this'.
641   const Value *stripPointerCastsAndAliases() const;
stripPointerCastsAndAliases()642   Value *stripPointerCastsAndAliases() {
643     return const_cast<Value *>(
644         static_cast<const Value *>(this)->stripPointerCastsAndAliases());
645   }
646 
647   /// Strip off pointer casts, all-zero GEPs and address space casts
648   /// but ensures the representation of the result stays the same.
649   ///
650   /// Returns the original uncasted value with the same representation. If this
651   /// is called on a non-pointer value, it returns 'this'.
652   const Value *stripPointerCastsSameRepresentation() const;
stripPointerCastsSameRepresentation()653   Value *stripPointerCastsSameRepresentation() {
654     return const_cast<Value *>(static_cast<const Value *>(this)
655                                    ->stripPointerCastsSameRepresentation());
656   }
657 
658   /// Strip off pointer casts, all-zero GEPs, single-argument phi nodes and
659   /// invariant group info.
660   ///
661   /// Returns the original uncasted value.  If this is called on a non-pointer
662   /// value, it returns 'this'. This function should be used only in
663   /// Alias analysis.
664   const Value *stripPointerCastsForAliasAnalysis() const;
stripPointerCastsForAliasAnalysis()665   Value *stripPointerCastsForAliasAnalysis() {
666     return const_cast<Value *>(static_cast<const Value *>(this)
667                                    ->stripPointerCastsForAliasAnalysis());
668   }
669 
670   /// Strip off pointer casts and all-constant inbounds GEPs.
671   ///
672   /// Returns the original pointer value.  If this is called on a non-pointer
673   /// value, it returns 'this'.
674   const Value *stripInBoundsConstantOffsets() const;
stripInBoundsConstantOffsets()675   Value *stripInBoundsConstantOffsets() {
676     return const_cast<Value *>(
677               static_cast<const Value *>(this)->stripInBoundsConstantOffsets());
678   }
679 
680   /// Accumulate the constant offset this value has compared to a base pointer.
681   /// Only 'getelementptr' instructions (GEPs) are accumulated but other
682   /// instructions, e.g., casts, are stripped away as well.
683   /// The accumulated constant offset is added to \p Offset and the base
684   /// pointer is returned.
685   ///
686   /// The APInt \p Offset has to have a bit-width equal to the IntPtr type for
687   /// the address space of 'this' pointer value, e.g., use
688   /// DataLayout::getIndexTypeSizeInBits(Ty).
689   ///
690   /// If \p AllowNonInbounds is true, offsets in GEPs are stripped and
691   /// accumulated even if the GEP is not "inbounds".
692   ///
693   /// If \p ExternalAnalysis is provided it will be used to calculate a offset
694   /// when a operand of GEP is not constant.
695   /// For example, for a value \p ExternalAnalysis might try to calculate a
696   /// lower bound. If \p ExternalAnalysis is successful, it should return true.
697   ///
698   /// If this is called on a non-pointer value, it returns 'this' and the
699   /// \p Offset is not modified.
700   ///
701   /// Note that this function will never return a nullptr. It will also never
702   /// manipulate the \p Offset in a way that would not match the difference
703   /// between the underlying value and the returned one. Thus, if no constant
704   /// offset was found, the returned value is the underlying one and \p Offset
705   /// is unchanged.
706   const Value *stripAndAccumulateConstantOffsets(
707       const DataLayout &DL, APInt &Offset, bool AllowNonInbounds,
708       function_ref<bool(Value &Value, APInt &Offset)> ExternalAnalysis =
709           nullptr) const;
stripAndAccumulateConstantOffsets(const DataLayout & DL,APInt & Offset,bool AllowNonInbounds)710   Value *stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset,
711                                            bool AllowNonInbounds) {
712     return const_cast<Value *>(
713         static_cast<const Value *>(this)->stripAndAccumulateConstantOffsets(
714             DL, Offset, AllowNonInbounds));
715   }
716 
717   /// This is a wrapper around stripAndAccumulateConstantOffsets with the
718   /// in-bounds requirement set to false.
stripAndAccumulateInBoundsConstantOffsets(const DataLayout & DL,APInt & Offset)719   const Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
720                                                          APInt &Offset) const {
721     return stripAndAccumulateConstantOffsets(DL, Offset,
722                                              /* AllowNonInbounds */ false);
723   }
stripAndAccumulateInBoundsConstantOffsets(const DataLayout & DL,APInt & Offset)724   Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
725                                                    APInt &Offset) {
726     return stripAndAccumulateConstantOffsets(DL, Offset,
727                                              /* AllowNonInbounds */ false);
728   }
729 
730   /// Strip off pointer casts and inbounds GEPs.
731   ///
732   /// Returns the original pointer value.  If this is called on a non-pointer
733   /// value, it returns 'this'.
734   const Value *stripInBoundsOffsets(function_ref<void(const Value *)> Func =
735                                         [](const Value *) {}) const;
736   inline Value *stripInBoundsOffsets(function_ref<void(const Value *)> Func =
737                                   [](const Value *) {}) {
738     return const_cast<Value *>(
739         static_cast<const Value *>(this)->stripInBoundsOffsets(Func));
740   }
741 
742   /// Return true if the memory object referred to by V can by freed in the
743   /// scope for which the SSA value defining the allocation is statically
744   /// defined.  E.g.  deallocation after the static scope of a value does not
745   /// count, but a deallocation before that does.
746   bool canBeFreed() const;
747 
748   /// Returns the number of bytes known to be dereferenceable for the
749   /// pointer value.
750   ///
751   /// If CanBeNull is set by this function the pointer can either be null or be
752   /// dereferenceable up to the returned number of bytes.
753   ///
754   /// IF CanBeFreed is true, the pointer is known to be dereferenceable at
755   /// point of definition only.  Caller must prove that allocation is not
756   /// deallocated between point of definition and use.
757   uint64_t getPointerDereferenceableBytes(const DataLayout &DL,
758                                           bool &CanBeNull,
759                                           bool &CanBeFreed) const;
760 
761   /// Returns an alignment of the pointer value.
762   ///
763   /// Returns an alignment which is either specified explicitly, e.g. via
764   /// align attribute of a function argument, or guaranteed by DataLayout.
765   Align getPointerAlignment(const DataLayout &DL) const;
766 
767   /// Translate PHI node to its predecessor from the given basic block.
768   ///
769   /// If this value is a PHI node with CurBB as its parent, return the value in
770   /// the PHI node corresponding to PredBB.  If not, return ourself.  This is
771   /// useful if you want to know the value something has in a predecessor
772   /// block.
773   const Value *DoPHITranslation(const BasicBlock *CurBB,
774                                 const BasicBlock *PredBB) const;
DoPHITranslation(const BasicBlock * CurBB,const BasicBlock * PredBB)775   Value *DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB) {
776     return const_cast<Value *>(
777              static_cast<const Value *>(this)->DoPHITranslation(CurBB, PredBB));
778   }
779 
780   /// The maximum alignment for instructions.
781   ///
782   /// This is the greatest alignment value supported by load, store, and alloca
783   /// instructions, and global values.
784   static const unsigned MaxAlignmentExponent = 29;
785   static const unsigned MaximumAlignment = 1u << MaxAlignmentExponent;
786 
787   /// Mutate the type of this Value to be of the specified type.
788   ///
789   /// Note that this is an extremely dangerous operation which can create
790   /// completely invalid IR very easily.  It is strongly recommended that you
791   /// recreate IR objects with the right types instead of mutating them in
792   /// place.
mutateType(Type * Ty)793   void mutateType(Type *Ty) {
794     VTy = Ty;
795   }
796 
797   /// Sort the use-list.
798   ///
799   /// Sorts the Value's use-list by Cmp using a stable mergesort.  Cmp is
800   /// expected to compare two \a Use references.
801   template <class Compare> void sortUseList(Compare Cmp);
802 
803   /// Reverse the use-list.
804   void reverseUseList();
805 
806 private:
807   /// Merge two lists together.
808   ///
809   /// Merges \c L and \c R using \c Cmp.  To enable stable sorts, always pushes
810   /// "equal" items from L before items from R.
811   ///
812   /// \return the first element in the list.
813   ///
814   /// \note Completely ignores \a Use::Prev (doesn't read, doesn't update).
815   template <class Compare>
mergeUseLists(Use * L,Use * R,Compare Cmp)816   static Use *mergeUseLists(Use *L, Use *R, Compare Cmp) {
817     Use *Merged;
818     Use **Next = &Merged;
819 
820     while (true) {
821       if (!L) {
822         *Next = R;
823         break;
824       }
825       if (!R) {
826         *Next = L;
827         break;
828       }
829       if (Cmp(*R, *L)) {
830         *Next = R;
831         Next = &R->Next;
832         R = R->Next;
833       } else {
834         *Next = L;
835         Next = &L->Next;
836         L = L->Next;
837       }
838     }
839 
840     return Merged;
841   }
842 
843 protected:
getSubclassDataFromValue()844   unsigned short getSubclassDataFromValue() const { return SubclassData; }
setValueSubclassData(unsigned short D)845   void setValueSubclassData(unsigned short D) { SubclassData = D; }
846 };
847 
operatorValueDeleter848 struct ValueDeleter { void operator()(Value *V) { V->deleteValue(); } };
849 
850 /// Use this instead of std::unique_ptr<Value> or std::unique_ptr<Instruction>.
851 /// Those don't work because Value and Instruction's destructors are protected,
852 /// aren't virtual, and won't destroy the complete object.
853 using unique_value = std::unique_ptr<Value, ValueDeleter>;
854 
855 inline raw_ostream &operator<<(raw_ostream &OS, const Value &V) {
856   V.print(OS);
857   return OS;
858 }
859 
set(Value * V)860 void Use::set(Value *V) {
861   if (Val) removeFromList();
862   Val = V;
863   if (V) V->addUse(*this);
864 }
865 
866 Value *Use::operator=(Value *RHS) {
867   set(RHS);
868   return RHS;
869 }
870 
871 const Use &Use::operator=(const Use &RHS) {
872   set(RHS.Val);
873   return *this;
874 }
875 
sortUseList(Compare Cmp)876 template <class Compare> void Value::sortUseList(Compare Cmp) {
877   if (!UseList || !UseList->Next)
878     // No need to sort 0 or 1 uses.
879     return;
880 
881   // Note: this function completely ignores Prev pointers until the end when
882   // they're fixed en masse.
883 
884   // Create a binomial vector of sorted lists, visiting uses one at a time and
885   // merging lists as necessary.
886   const unsigned MaxSlots = 32;
887   Use *Slots[MaxSlots];
888 
889   // Collect the first use, turning it into a single-item list.
890   Use *Next = UseList->Next;
891   UseList->Next = nullptr;
892   unsigned NumSlots = 1;
893   Slots[0] = UseList;
894 
895   // Collect all but the last use.
896   while (Next->Next) {
897     Use *Current = Next;
898     Next = Current->Next;
899 
900     // Turn Current into a single-item list.
901     Current->Next = nullptr;
902 
903     // Save Current in the first available slot, merging on collisions.
904     unsigned I;
905     for (I = 0; I < NumSlots; ++I) {
906       if (!Slots[I])
907         break;
908 
909       // Merge two lists, doubling the size of Current and emptying slot I.
910       //
911       // Since the uses in Slots[I] originally preceded those in Current, send
912       // Slots[I] in as the left parameter to maintain a stable sort.
913       Current = mergeUseLists(Slots[I], Current, Cmp);
914       Slots[I] = nullptr;
915     }
916     // Check if this is a new slot.
917     if (I == NumSlots) {
918       ++NumSlots;
919       assert(NumSlots <= MaxSlots && "Use list bigger than 2^32");
920     }
921 
922     // Found an open slot.
923     Slots[I] = Current;
924   }
925 
926   // Merge all the lists together.
927   assert(Next && "Expected one more Use");
928   assert(!Next->Next && "Expected only one Use");
929   UseList = Next;
930   for (unsigned I = 0; I < NumSlots; ++I)
931     if (Slots[I])
932       // Since the uses in Slots[I] originally preceded those in UseList, send
933       // Slots[I] in as the left parameter to maintain a stable sort.
934       UseList = mergeUseLists(Slots[I], UseList, Cmp);
935 
936   // Fix the Prev pointers.
937   for (Use *I = UseList, **Prev = &UseList; I; I = I->Next) {
938     I->Prev = Prev;
939     Prev = &I->Next;
940   }
941 }
942 
943 // isa - Provide some specializations of isa so that we don't have to include
944 // the subtype header files to test to see if the value is a subclass...
945 //
946 template <> struct isa_impl<Constant, Value> {
947   static inline bool doit(const Value &Val) {
948     static_assert(Value::ConstantFirstVal == 0, "Val.getValueID() >= Value::ConstantFirstVal");
949     return Val.getValueID() <= Value::ConstantLastVal;
950   }
951 };
952 
953 template <> struct isa_impl<ConstantData, Value> {
954   static inline bool doit(const Value &Val) {
955     return Val.getValueID() >= Value::ConstantDataFirstVal &&
956            Val.getValueID() <= Value::ConstantDataLastVal;
957   }
958 };
959 
960 template <> struct isa_impl<ConstantAggregate, Value> {
961   static inline bool doit(const Value &Val) {
962     return Val.getValueID() >= Value::ConstantAggregateFirstVal &&
963            Val.getValueID() <= Value::ConstantAggregateLastVal;
964   }
965 };
966 
967 template <> struct isa_impl<Argument, Value> {
968   static inline bool doit (const Value &Val) {
969     return Val.getValueID() == Value::ArgumentVal;
970   }
971 };
972 
973 template <> struct isa_impl<InlineAsm, Value> {
974   static inline bool doit(const Value &Val) {
975     return Val.getValueID() == Value::InlineAsmVal;
976   }
977 };
978 
979 template <> struct isa_impl<Instruction, Value> {
980   static inline bool doit(const Value &Val) {
981     return Val.getValueID() >= Value::InstructionVal;
982   }
983 };
984 
985 template <> struct isa_impl<BasicBlock, Value> {
986   static inline bool doit(const Value &Val) {
987     return Val.getValueID() == Value::BasicBlockVal;
988   }
989 };
990 
991 template <> struct isa_impl<Function, Value> {
992   static inline bool doit(const Value &Val) {
993     return Val.getValueID() == Value::FunctionVal;
994   }
995 };
996 
997 template <> struct isa_impl<GlobalVariable, Value> {
998   static inline bool doit(const Value &Val) {
999     return Val.getValueID() == Value::GlobalVariableVal;
1000   }
1001 };
1002 
1003 template <> struct isa_impl<GlobalAlias, Value> {
1004   static inline bool doit(const Value &Val) {
1005     return Val.getValueID() == Value::GlobalAliasVal;
1006   }
1007 };
1008 
1009 template <> struct isa_impl<GlobalIFunc, Value> {
1010   static inline bool doit(const Value &Val) {
1011     return Val.getValueID() == Value::GlobalIFuncVal;
1012   }
1013 };
1014 
1015 template <> struct isa_impl<GlobalIndirectSymbol, Value> {
1016   static inline bool doit(const Value &Val) {
1017     return isa<GlobalAlias>(Val) || isa<GlobalIFunc>(Val);
1018   }
1019 };
1020 
1021 template <> struct isa_impl<GlobalValue, Value> {
1022   static inline bool doit(const Value &Val) {
1023     return isa<GlobalObject>(Val) || isa<GlobalIndirectSymbol>(Val);
1024   }
1025 };
1026 
1027 template <> struct isa_impl<GlobalObject, Value> {
1028   static inline bool doit(const Value &Val) {
1029     return isa<GlobalVariable>(Val) || isa<Function>(Val);
1030   }
1031 };
1032 
1033 // Create wrappers for C Binding types (see CBindingWrapping.h).
1034 DEFINE_ISA_CONVERSION_FUNCTIONS(Value, LLVMValueRef)
1035 
1036 // Specialized opaque value conversions.
1037 inline Value **unwrap(LLVMValueRef *Vals) {
1038   return reinterpret_cast<Value**>(Vals);
1039 }
1040 
1041 template<typename T>
1042 inline T **unwrap(LLVMValueRef *Vals, unsigned Length) {
1043 #ifndef NDEBUG
1044   for (LLVMValueRef *I = Vals, *E = Vals + Length; I != E; ++I)
1045     unwrap<T>(*I); // For side effect of calling assert on invalid usage.
1046 #endif
1047   (void)Length;
1048   return reinterpret_cast<T**>(Vals);
1049 }
1050 
1051 inline LLVMValueRef *wrap(const Value **Vals) {
1052   return reinterpret_cast<LLVMValueRef*>(const_cast<Value**>(Vals));
1053 }
1054 
1055 } // end namespace llvm
1056 
1057 #endif // LLVM_IR_VALUE_H
1058