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