1 //===- ValueHandle.h - Value Smart Pointer classes --------------*- 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 ValueHandle class and its sub-classes.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_IR_VALUEHANDLE_H
14 #define LLVM_IR_VALUEHANDLE_H
15 
16 #include "llvm/ADT/DenseMapInfo.h"
17 #include "llvm/ADT/PointerIntPair.h"
18 #include "llvm/IR/Value.h"
19 #include "llvm/Support/Casting.h"
20 #include <cassert>
21 
22 namespace llvm {
23 
24 /// This is the common base class of value handles.
25 ///
26 /// ValueHandle's are smart pointers to Value's that have special behavior when
27 /// the value is deleted or ReplaceAllUsesWith'd.  See the specific handles
28 /// below for details.
29 class ValueHandleBase {
30   friend class Value;
31 
32 protected:
33   /// This indicates what sub class the handle actually is.
34   ///
35   /// This is to avoid having a vtable for the light-weight handle pointers. The
36   /// fully general Callback version does have a vtable.
37   enum HandleBaseKind { Assert, Callback, Weak, WeakTracking };
38 
39   ValueHandleBase(const ValueHandleBase &RHS)
40       : ValueHandleBase(RHS.PrevPair.getInt(), RHS) {}
41 
42   ValueHandleBase(HandleBaseKind Kind, const ValueHandleBase &RHS)
43       : PrevPair(nullptr, Kind), Val(RHS.getValPtr()) {
44     if (isValid(getValPtr()))
45       AddToExistingUseList(RHS.getPrevPtr());
46   }
47 
48 private:
49   PointerIntPair<ValueHandleBase**, 2, HandleBaseKind> PrevPair;
50   ValueHandleBase *Next = nullptr;
51   Value *Val = nullptr;
52 
53   void setValPtr(Value *V) { Val = V; }
54 
55 public:
56   explicit ValueHandleBase(HandleBaseKind Kind)
57       : PrevPair(nullptr, Kind) {}
58   ValueHandleBase(HandleBaseKind Kind, Value *V)
59       : PrevPair(nullptr, Kind), Val(V) {
60     if (isValid(getValPtr()))
61       AddToUseList();
62   }
63 
64   ~ValueHandleBase() {
65     if (isValid(getValPtr()))
66       RemoveFromUseList();
67   }
68 
69   Value *operator=(Value *RHS) {
70     if (getValPtr() == RHS)
71       return RHS;
72     if (isValid(getValPtr()))
73       RemoveFromUseList();
74     setValPtr(RHS);
75     if (isValid(getValPtr()))
76       AddToUseList();
77     return RHS;
78   }
79 
80   Value *operator=(const ValueHandleBase &RHS) {
81     if (getValPtr() == RHS.getValPtr())
82       return RHS.getValPtr();
83     if (isValid(getValPtr()))
84       RemoveFromUseList();
85     setValPtr(RHS.getValPtr());
86     if (isValid(getValPtr()))
87       AddToExistingUseList(RHS.getPrevPtr());
88     return getValPtr();
89   }
90 
91   Value *operator->() const { return getValPtr(); }
92   Value &operator*() const { return *getValPtr(); }
93 
94 protected:
95   Value *getValPtr() const { return Val; }
96 
97   static bool isValid(Value *V) {
98     return V &&
99            V != DenseMapInfo<Value *>::getEmptyKey() &&
100            V != DenseMapInfo<Value *>::getTombstoneKey();
101   }
102 
103   /// Remove this ValueHandle from its current use list.
104   void RemoveFromUseList();
105 
106   /// Clear the underlying pointer without clearing the use list.
107   ///
108   /// This should only be used if a derived class has manually removed the
109   /// handle from the use list.
110   void clearValPtr() { setValPtr(nullptr); }
111 
112 public:
113   // Callbacks made from Value.
114   static void ValueIsDeleted(Value *V);
115   static void ValueIsRAUWd(Value *Old, Value *New);
116 
117 private:
118   // Internal implementation details.
119   ValueHandleBase **getPrevPtr() const { return PrevPair.getPointer(); }
120   HandleBaseKind getKind() const { return PrevPair.getInt(); }
121   void setPrevPtr(ValueHandleBase **Ptr) { PrevPair.setPointer(Ptr); }
122 
123   /// Add this ValueHandle to the use list for V.
124   ///
125   /// List is the address of either the head of the list or a Next node within
126   /// the existing use list.
127   void AddToExistingUseList(ValueHandleBase **List);
128 
129   /// Add this ValueHandle to the use list after Node.
130   void AddToExistingUseListAfter(ValueHandleBase *Node);
131 
132   /// Add this ValueHandle to the use list for V.
133   void AddToUseList();
134 };
135 
136 /// A nullable Value handle that is nullable.
137 ///
138 /// This is a value handle that points to a value, and nulls itself
139 /// out if that value is deleted.
140 class WeakVH : public ValueHandleBase {
141 public:
142   WeakVH() : ValueHandleBase(Weak) {}
143   WeakVH(Value *P) : ValueHandleBase(Weak, P) {}
144   WeakVH(const WeakVH &RHS)
145       : ValueHandleBase(Weak, RHS) {}
146 
147   WeakVH &operator=(const WeakVH &RHS) = default;
148 
149   Value *operator=(Value *RHS) {
150     return ValueHandleBase::operator=(RHS);
151   }
152   Value *operator=(const ValueHandleBase &RHS) {
153     return ValueHandleBase::operator=(RHS);
154   }
155 
156   operator Value*() const {
157     return getValPtr();
158   }
159 };
160 
161 // Specialize simplify_type to allow WeakVH to participate in
162 // dyn_cast, isa, etc.
163 template <> struct simplify_type<WeakVH> {
164   using SimpleType = Value *;
165 
166   static SimpleType getSimplifiedValue(WeakVH &WVH) { return WVH; }
167 };
168 template <> struct simplify_type<const WeakVH> {
169   using SimpleType = Value *;
170 
171   static SimpleType getSimplifiedValue(const WeakVH &WVH) { return WVH; }
172 };
173 
174 // Specialize DenseMapInfo to allow WeakVH to participate in DenseMap.
175 template <> struct DenseMapInfo<WeakVH> {
176   static inline WeakVH getEmptyKey() {
177     return WeakVH(DenseMapInfo<Value *>::getEmptyKey());
178   }
179 
180   static inline WeakVH getTombstoneKey() {
181     return WeakVH(DenseMapInfo<Value *>::getTombstoneKey());
182   }
183 
184   static unsigned getHashValue(const WeakVH &Val) {
185     return DenseMapInfo<Value *>::getHashValue(Val);
186   }
187 
188   static bool isEqual(const WeakVH &LHS, const WeakVH &RHS) {
189     return DenseMapInfo<Value *>::isEqual(LHS, RHS);
190   }
191 };
192 
193 /// Value handle that is nullable, but tries to track the Value.
194 ///
195 /// This is a value handle that tries hard to point to a Value, even across
196 /// RAUW operations, but will null itself out if the value is destroyed.  this
197 /// is useful for advisory sorts of information, but should not be used as the
198 /// key of a map (since the map would have to rearrange itself when the pointer
199 /// changes).
200 class WeakTrackingVH : public ValueHandleBase {
201 public:
202   WeakTrackingVH() : ValueHandleBase(WeakTracking) {}
203   WeakTrackingVH(Value *P) : ValueHandleBase(WeakTracking, P) {}
204   WeakTrackingVH(const WeakTrackingVH &RHS)
205       : ValueHandleBase(WeakTracking, RHS) {}
206 
207   WeakTrackingVH &operator=(const WeakTrackingVH &RHS) = default;
208 
209   Value *operator=(Value *RHS) {
210     return ValueHandleBase::operator=(RHS);
211   }
212   Value *operator=(const ValueHandleBase &RHS) {
213     return ValueHandleBase::operator=(RHS);
214   }
215 
216   operator Value*() const {
217     return getValPtr();
218   }
219 
220   bool pointsToAliveValue() const {
221     return ValueHandleBase::isValid(getValPtr());
222   }
223 };
224 
225 // Specialize simplify_type to allow WeakTrackingVH to participate in
226 // dyn_cast, isa, etc.
227 template <> struct simplify_type<WeakTrackingVH> {
228   using SimpleType = Value *;
229 
230   static SimpleType getSimplifiedValue(WeakTrackingVH &WVH) { return WVH; }
231 };
232 template <> struct simplify_type<const WeakTrackingVH> {
233   using SimpleType = Value *;
234 
235   static SimpleType getSimplifiedValue(const WeakTrackingVH &WVH) {
236     return WVH;
237   }
238 };
239 
240 /// Value handle that asserts if the Value is deleted.
241 ///
242 /// This is a Value Handle that points to a value and asserts out if the value
243 /// is destroyed while the handle is still live.  This is very useful for
244 /// catching dangling pointer bugs and other things which can be non-obvious.
245 /// One particularly useful place to use this is as the Key of a map.  Dangling
246 /// pointer bugs often lead to really subtle bugs that only occur if another
247 /// object happens to get allocated to the same address as the old one.  Using
248 /// an AssertingVH ensures that an assert is triggered as soon as the bad
249 /// delete occurs.
250 ///
251 /// Note that an AssertingVH handle does *not* follow values across RAUW
252 /// operations.  This means that RAUW's need to explicitly update the
253 /// AssertingVH's as it moves.  This is required because in non-assert mode this
254 /// class turns into a trivial wrapper around a pointer.
255 template <typename ValueTy>
256 class AssertingVH
257 #ifndef NDEBUG
258   : public ValueHandleBase
259 #endif
260   {
261   friend struct DenseMapInfo<AssertingVH<ValueTy>>;
262 
263 #ifndef NDEBUG
264   Value *getRawValPtr() const { return ValueHandleBase::getValPtr(); }
265   void setRawValPtr(Value *P) { ValueHandleBase::operator=(P); }
266 #else
267   Value *ThePtr;
268   Value *getRawValPtr() const { return ThePtr; }
269   void setRawValPtr(Value *P) { ThePtr = P; }
270 #endif
271   // Convert a ValueTy*, which may be const, to the raw Value*.
272   static Value *GetAsValue(Value *V) { return V; }
273   static Value *GetAsValue(const Value *V) { return const_cast<Value*>(V); }
274 
275   ValueTy *getValPtr() const { return static_cast<ValueTy *>(getRawValPtr()); }
276   void setValPtr(ValueTy *P) { setRawValPtr(GetAsValue(P)); }
277 
278 public:
279 #ifndef NDEBUG
280   AssertingVH() : ValueHandleBase(Assert) {}
281   AssertingVH(ValueTy *P) : ValueHandleBase(Assert, GetAsValue(P)) {}
282   AssertingVH(const AssertingVH &RHS) : ValueHandleBase(Assert, RHS) {}
283 #else
284   AssertingVH() : ThePtr(nullptr) {}
285   AssertingVH(ValueTy *P) : ThePtr(GetAsValue(P)) {}
286   AssertingVH(const AssertingVH<ValueTy> &) = default;
287 #endif
288 
289   operator ValueTy*() const {
290     return getValPtr();
291   }
292 
293   ValueTy *operator=(ValueTy *RHS) {
294     setValPtr(RHS);
295     return getValPtr();
296   }
297   ValueTy *operator=(const AssertingVH<ValueTy> &RHS) {
298     setValPtr(RHS.getValPtr());
299     return getValPtr();
300   }
301 
302   ValueTy *operator->() const { return getValPtr(); }
303   ValueTy &operator*() const { return *getValPtr(); }
304 };
305 
306 // Specialize DenseMapInfo to allow AssertingVH to participate in DenseMap.
307 template<typename T>
308 struct DenseMapInfo<AssertingVH<T>> {
309   static inline AssertingVH<T> getEmptyKey() {
310     AssertingVH<T> Res;
311     Res.setRawValPtr(DenseMapInfo<Value *>::getEmptyKey());
312     return Res;
313   }
314 
315   static inline AssertingVH<T> getTombstoneKey() {
316     AssertingVH<T> Res;
317     Res.setRawValPtr(DenseMapInfo<Value *>::getTombstoneKey());
318     return Res;
319   }
320 
321   static unsigned getHashValue(const AssertingVH<T> &Val) {
322     return DenseMapInfo<Value *>::getHashValue(Val.getRawValPtr());
323   }
324 
325   static bool isEqual(const AssertingVH<T> &LHS, const AssertingVH<T> &RHS) {
326     return DenseMapInfo<Value *>::isEqual(LHS.getRawValPtr(),
327                                           RHS.getRawValPtr());
328   }
329 };
330 
331 /// Value handle that tracks a Value across RAUW.
332 ///
333 /// TrackingVH is designed for situations where a client needs to hold a handle
334 /// to a Value (or subclass) across some operations which may move that value,
335 /// but should never destroy it or replace it with some unacceptable type.
336 ///
337 /// It is an error to attempt to replace a value with one of a type which is
338 /// incompatible with any of its outstanding TrackingVHs.
339 ///
340 /// It is an error to read from a TrackingVH that does not point to a valid
341 /// value.  A TrackingVH is said to not point to a valid value if either it
342 /// hasn't yet been assigned a value yet or because the value it was tracking
343 /// has since been deleted.
344 ///
345 /// Assigning a value to a TrackingVH is always allowed, even if said TrackingVH
346 /// no longer points to a valid value.
347 template <typename ValueTy> class TrackingVH {
348   WeakTrackingVH InnerHandle;
349 
350 public:
351   ValueTy *getValPtr() const {
352     assert(InnerHandle.pointsToAliveValue() &&
353            "TrackingVH must be non-null and valid on dereference!");
354 
355     // Check that the value is a member of the correct subclass. We would like
356     // to check this property on assignment for better debugging, but we don't
357     // want to require a virtual interface on this VH. Instead we allow RAUW to
358     // replace this value with a value of an invalid type, and check it here.
359     assert(isa<ValueTy>(InnerHandle) &&
360            "Tracked Value was replaced by one with an invalid type!");
361     return cast<ValueTy>(InnerHandle);
362   }
363 
364   void setValPtr(ValueTy *P) {
365     // Assigning to non-valid TrackingVH's are fine so we just unconditionally
366     // assign here.
367     InnerHandle = GetAsValue(P);
368   }
369 
370   // Convert a ValueTy*, which may be const, to the type the base
371   // class expects.
372   static Value *GetAsValue(Value *V) { return V; }
373   static Value *GetAsValue(const Value *V) { return const_cast<Value*>(V); }
374 
375 public:
376   TrackingVH() = default;
377   TrackingVH(ValueTy *P) { setValPtr(P); }
378 
379   operator ValueTy*() const {
380     return getValPtr();
381   }
382 
383   ValueTy *operator=(ValueTy *RHS) {
384     setValPtr(RHS);
385     return getValPtr();
386   }
387 
388   ValueTy *operator->() const { return getValPtr(); }
389   ValueTy &operator*() const { return *getValPtr(); }
390 };
391 
392 /// Value handle with callbacks on RAUW and destruction.
393 ///
394 /// This is a value handle that allows subclasses to define callbacks that run
395 /// when the underlying Value has RAUW called on it or is destroyed.  This
396 /// class can be used as the key of a map, as long as the user takes it out of
397 /// the map before calling setValPtr() (since the map has to rearrange itself
398 /// when the pointer changes).  Unlike ValueHandleBase, this class has a vtable.
399 class CallbackVH : public ValueHandleBase {
400   virtual void anchor();
401 protected:
402   ~CallbackVH() = default;
403   CallbackVH(const CallbackVH &) = default;
404   CallbackVH &operator=(const CallbackVH &) = default;
405 
406   void setValPtr(Value *P) {
407     ValueHandleBase::operator=(P);
408   }
409 
410 public:
411   CallbackVH() : ValueHandleBase(Callback) {}
412   CallbackVH(Value *P) : ValueHandleBase(Callback, P) {}
413 
414   operator Value*() const {
415     return getValPtr();
416   }
417 
418   /// Callback for Value destruction.
419   ///
420   /// Called when this->getValPtr() is destroyed, inside ~Value(), so you
421   /// may call any non-virtual Value method on getValPtr(), but no subclass
422   /// methods.  If WeakTrackingVH were implemented as a CallbackVH, it would use
423   /// this
424   /// method to call setValPtr(NULL).  AssertingVH would use this method to
425   /// cause an assertion failure.
426   ///
427   /// All implementations must remove the reference from this object to the
428   /// Value that's being destroyed.
429   virtual void deleted() { setValPtr(nullptr); }
430 
431   /// Callback for Value RAUW.
432   ///
433   /// Called when this->getValPtr()->replaceAllUsesWith(new_value) is called,
434   /// _before_ any of the uses have actually been replaced.  If WeakTrackingVH
435   /// were
436   /// implemented as a CallbackVH, it would use this method to call
437   /// setValPtr(new_value).  AssertingVH would do nothing in this method.
438   virtual void allUsesReplacedWith(Value *) {}
439 };
440 
441 /// Value handle that poisons itself if the Value is deleted.
442 ///
443 /// This is a Value Handle that points to a value and poisons itself if the
444 /// value is destroyed while the handle is still live.  This is very useful for
445 /// catching dangling pointer bugs where an \c AssertingVH cannot be used
446 /// because the dangling handle needs to outlive the value without ever being
447 /// used.
448 ///
449 /// One particularly useful place to use this is as the Key of a map. Dangling
450 /// pointer bugs often lead to really subtle bugs that only occur if another
451 /// object happens to get allocated to the same address as the old one. Using
452 /// a PoisoningVH ensures that an assert is triggered if looking up a new value
453 /// in the map finds a handle from the old value.
454 ///
455 /// Note that a PoisoningVH handle does *not* follow values across RAUW
456 /// operations. This means that RAUW's need to explicitly update the
457 /// PoisoningVH's as it moves. This is required because in non-assert mode this
458 /// class turns into a trivial wrapper around a pointer.
459 template <typename ValueTy>
460 class PoisoningVH
461 #ifndef NDEBUG
462     final : public CallbackVH
463 #endif
464 {
465   friend struct DenseMapInfo<PoisoningVH<ValueTy>>;
466 
467   // Convert a ValueTy*, which may be const, to the raw Value*.
468   static Value *GetAsValue(Value *V) { return V; }
469   static Value *GetAsValue(const Value *V) { return const_cast<Value *>(V); }
470 
471 #ifndef NDEBUG
472   /// A flag tracking whether this value has been poisoned.
473   ///
474   /// On delete and RAUW, we leave the value pointer alone so that as a raw
475   /// pointer it produces the same value (and we fit into the same key of
476   /// a hash table, etc), but we poison the handle so that any top-level usage
477   /// will fail.
478   bool Poisoned = false;
479 
480   Value *getRawValPtr() const { return ValueHandleBase::getValPtr(); }
481   void setRawValPtr(Value *P) { ValueHandleBase::operator=(P); }
482 
483   /// Handle deletion by poisoning the handle.
484   void deleted() override {
485     assert(!Poisoned && "Tried to delete an already poisoned handle!");
486     Poisoned = true;
487     RemoveFromUseList();
488   }
489 
490   /// Handle RAUW by poisoning the handle.
491   void allUsesReplacedWith(Value *) override {
492     assert(!Poisoned && "Tried to RAUW an already poisoned handle!");
493     Poisoned = true;
494     RemoveFromUseList();
495   }
496 #else // NDEBUG
497   Value *ThePtr = nullptr;
498 
499   Value *getRawValPtr() const { return ThePtr; }
500   void setRawValPtr(Value *P) { ThePtr = P; }
501 #endif
502 
503   ValueTy *getValPtr() const {
504     assert(!Poisoned && "Accessed a poisoned value handle!");
505     return static_cast<ValueTy *>(getRawValPtr());
506   }
507   void setValPtr(ValueTy *P) { setRawValPtr(GetAsValue(P)); }
508 
509 public:
510   PoisoningVH() = default;
511 #ifndef NDEBUG
512   PoisoningVH(ValueTy *P) : CallbackVH(GetAsValue(P)) {}
513   PoisoningVH(const PoisoningVH &RHS)
514       : CallbackVH(RHS), Poisoned(RHS.Poisoned) {}
515 
516   ~PoisoningVH() {
517     if (Poisoned)
518       clearValPtr();
519   }
520 
521   PoisoningVH &operator=(const PoisoningVH &RHS) {
522     if (Poisoned)
523       clearValPtr();
524     CallbackVH::operator=(RHS);
525     Poisoned = RHS.Poisoned;
526     return *this;
527   }
528 #else
529   PoisoningVH(ValueTy *P) : ThePtr(GetAsValue(P)) {}
530 #endif
531 
532   operator ValueTy *() const { return getValPtr(); }
533 
534   ValueTy *operator->() const { return getValPtr(); }
535   ValueTy &operator*() const { return *getValPtr(); }
536 };
537 
538 // Specialize DenseMapInfo to allow PoisoningVH to participate in DenseMap.
539 template <typename T> struct DenseMapInfo<PoisoningVH<T>> {
540   static inline PoisoningVH<T> getEmptyKey() {
541     PoisoningVH<T> Res;
542     Res.setRawValPtr(DenseMapInfo<Value *>::getEmptyKey());
543     return Res;
544   }
545 
546   static inline PoisoningVH<T> getTombstoneKey() {
547     PoisoningVH<T> Res;
548     Res.setRawValPtr(DenseMapInfo<Value *>::getTombstoneKey());
549     return Res;
550   }
551 
552   static unsigned getHashValue(const PoisoningVH<T> &Val) {
553     return DenseMapInfo<Value *>::getHashValue(Val.getRawValPtr());
554   }
555 
556   static bool isEqual(const PoisoningVH<T> &LHS, const PoisoningVH<T> &RHS) {
557     return DenseMapInfo<Value *>::isEqual(LHS.getRawValPtr(),
558                                           RHS.getRawValPtr());
559   }
560 };
561 
562 } // end namespace llvm
563 
564 #endif // LLVM_IR_VALUEHANDLE_H
565