1 //===- ValueHandle.h - Value Smart Pointer classes --------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file declares the ValueHandle class and its sub-classes.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_IR_VALUEHANDLE_H
15 #define LLVM_IR_VALUEHANDLE_H
17 #include "llvm/ADT/DenseMapInfo.h"
18 #include "llvm/ADT/PointerIntPair.h"
19 #include "llvm/IR/Value.h"
20 #include "llvm/Support/Casting.h"
25 /// \brief This is the common base class of value handles.
27 /// ValueHandle's are smart pointers to Value's that have special behavior when
28 /// the value is deleted or ReplaceAllUsesWith'd. See the specific handles
29 /// below for details.
30 class ValueHandleBase {
34 /// \brief This indicates what sub class the handle actually is.
36 /// This is to avoid having a vtable for the light-weight handle pointers. The
37 /// fully general Callback version does have a vtable.
38 enum HandleBaseKind { Assert, Callback, Weak, WeakTracking };
40 ValueHandleBase(const ValueHandleBase &RHS)
41 : ValueHandleBase(RHS.PrevPair.getInt(), RHS) {}
43 ValueHandleBase(HandleBaseKind Kind, const ValueHandleBase &RHS)
44 : PrevPair(nullptr, Kind), Val(RHS.getValPtr()) {
45 if (isValid(getValPtr()))
46 AddToExistingUseList(RHS.getPrevPtr());
50 PointerIntPair<ValueHandleBase**, 2, HandleBaseKind> PrevPair;
51 ValueHandleBase *Next = nullptr;
54 void setValPtr(Value *V) { Val = V; }
57 explicit ValueHandleBase(HandleBaseKind Kind)
58 : PrevPair(nullptr, Kind) {}
59 ValueHandleBase(HandleBaseKind Kind, Value *V)
60 : PrevPair(nullptr, Kind), Val(V) {
61 if (isValid(getValPtr()))
66 if (isValid(getValPtr()))
70 Value *operator=(Value *RHS) {
71 if (getValPtr() == RHS)
73 if (isValid(getValPtr()))
76 if (isValid(getValPtr()))
81 Value *operator=(const ValueHandleBase &RHS) {
82 if (getValPtr() == RHS.getValPtr())
83 return RHS.getValPtr();
84 if (isValid(getValPtr()))
86 setValPtr(RHS.getValPtr());
87 if (isValid(getValPtr()))
88 AddToExistingUseList(RHS.getPrevPtr());
92 Value *operator->() const { return getValPtr(); }
93 Value &operator*() const { return *getValPtr(); }
96 Value *getValPtr() const { return Val; }
98 static bool isValid(Value *V) {
100 V != DenseMapInfo<Value *>::getEmptyKey() &&
101 V != DenseMapInfo<Value *>::getTombstoneKey();
104 /// \brief Remove this ValueHandle from its current use list.
105 void RemoveFromUseList();
107 /// \brief Clear the underlying pointer without clearing the use list.
109 /// This should only be used if a derived class has manually removed the
110 /// handle from the use list.
111 void clearValPtr() { setValPtr(nullptr); }
114 // Callbacks made from Value.
115 static void ValueIsDeleted(Value *V);
116 static void ValueIsRAUWd(Value *Old, Value *New);
119 // Internal implementation details.
120 ValueHandleBase **getPrevPtr() const { return PrevPair.getPointer(); }
121 HandleBaseKind getKind() const { return PrevPair.getInt(); }
122 void setPrevPtr(ValueHandleBase **Ptr) { PrevPair.setPointer(Ptr); }
124 /// \brief Add this ValueHandle to the use list for V.
126 /// List is the address of either the head of the list or a Next node within
127 /// the existing use list.
128 void AddToExistingUseList(ValueHandleBase **List);
130 /// \brief Add this ValueHandle to the use list after Node.
131 void AddToExistingUseListAfter(ValueHandleBase *Node);
133 /// \brief Add this ValueHandle to the use list for V.
137 /// \brief A nullable Value handle that is nullable.
139 /// This is a value handle that points to a value, and nulls itself
140 /// out if that value is deleted.
141 class WeakVH : public ValueHandleBase {
143 WeakVH() : ValueHandleBase(Weak) {}
144 WeakVH(Value *P) : ValueHandleBase(Weak, P) {}
145 WeakVH(const WeakVH &RHS)
146 : ValueHandleBase(Weak, RHS) {}
148 WeakVH &operator=(const WeakVH &RHS) = default;
150 Value *operator=(Value *RHS) {
151 return ValueHandleBase::operator=(RHS);
153 Value *operator=(const ValueHandleBase &RHS) {
154 return ValueHandleBase::operator=(RHS);
157 operator Value*() const {
162 // Specialize simplify_type to allow WeakVH to participate in
163 // dyn_cast, isa, etc.
164 template <> struct simplify_type<WeakVH> {
165 using SimpleType = Value *;
167 static SimpleType getSimplifiedValue(WeakVH &WVH) { return WVH; }
169 template <> struct simplify_type<const WeakVH> {
170 using SimpleType = Value *;
172 static SimpleType getSimplifiedValue(const WeakVH &WVH) { return WVH; }
175 /// \brief Value handle that is nullable, but tries to track the Value.
177 /// This is a value handle that tries hard to point to a Value, even across
178 /// RAUW operations, but will null itself out if the value is destroyed. this
179 /// is useful for advisory sorts of information, but should not be used as the
180 /// key of a map (since the map would have to rearrange itself when the pointer
182 class WeakTrackingVH : public ValueHandleBase {
184 WeakTrackingVH() : ValueHandleBase(WeakTracking) {}
185 WeakTrackingVH(Value *P) : ValueHandleBase(WeakTracking, P) {}
186 WeakTrackingVH(const WeakTrackingVH &RHS)
187 : ValueHandleBase(WeakTracking, RHS) {}
189 WeakTrackingVH &operator=(const WeakTrackingVH &RHS) = default;
191 Value *operator=(Value *RHS) {
192 return ValueHandleBase::operator=(RHS);
194 Value *operator=(const ValueHandleBase &RHS) {
195 return ValueHandleBase::operator=(RHS);
198 operator Value*() const {
202 bool pointsToAliveValue() const {
203 return ValueHandleBase::isValid(getValPtr());
207 // Specialize simplify_type to allow WeakTrackingVH to participate in
208 // dyn_cast, isa, etc.
209 template <> struct simplify_type<WeakTrackingVH> {
210 using SimpleType = Value *;
212 static SimpleType getSimplifiedValue(WeakTrackingVH &WVH) { return WVH; }
214 template <> struct simplify_type<const WeakTrackingVH> {
215 using SimpleType = Value *;
217 static SimpleType getSimplifiedValue(const WeakTrackingVH &WVH) {
222 /// \brief Value handle that asserts if the Value is deleted.
224 /// This is a Value Handle that points to a value and asserts out if the value
225 /// is destroyed while the handle is still live. This is very useful for
226 /// catching dangling pointer bugs and other things which can be non-obvious.
227 /// One particularly useful place to use this is as the Key of a map. Dangling
228 /// pointer bugs often lead to really subtle bugs that only occur if another
229 /// object happens to get allocated to the same address as the old one. Using
230 /// an AssertingVH ensures that an assert is triggered as soon as the bad
233 /// Note that an AssertingVH handle does *not* follow values across RAUW
234 /// operations. This means that RAUW's need to explicitly update the
235 /// AssertingVH's as it moves. This is required because in non-assert mode this
236 /// class turns into a trivial wrapper around a pointer.
237 template <typename ValueTy>
240 : public ValueHandleBase
243 friend struct DenseMapInfo<AssertingVH<ValueTy>>;
246 Value *getRawValPtr() const { return ValueHandleBase::getValPtr(); }
247 void setRawValPtr(Value *P) { ValueHandleBase::operator=(P); }
250 Value *getRawValPtr() const { return ThePtr; }
251 void setRawValPtr(Value *P) { ThePtr = P; }
253 // Convert a ValueTy*, which may be const, to the raw Value*.
254 static Value *GetAsValue(Value *V) { return V; }
255 static Value *GetAsValue(const Value *V) { return const_cast<Value*>(V); }
257 ValueTy *getValPtr() const { return static_cast<ValueTy *>(getRawValPtr()); }
258 void setValPtr(ValueTy *P) { setRawValPtr(GetAsValue(P)); }
262 AssertingVH() : ValueHandleBase(Assert) {}
263 AssertingVH(ValueTy *P) : ValueHandleBase(Assert, GetAsValue(P)) {}
264 AssertingVH(const AssertingVH &RHS) : ValueHandleBase(Assert, RHS) {}
266 AssertingVH() : ThePtr(nullptr) {}
267 AssertingVH(ValueTy *P) : ThePtr(GetAsValue(P)) {}
270 operator ValueTy*() const {
274 ValueTy *operator=(ValueTy *RHS) {
278 ValueTy *operator=(const AssertingVH<ValueTy> &RHS) {
279 setValPtr(RHS.getValPtr());
283 ValueTy *operator->() const { return getValPtr(); }
284 ValueTy &operator*() const { return *getValPtr(); }
287 // Specialize DenseMapInfo to allow AssertingVH to participate in DenseMap.
289 struct DenseMapInfo<AssertingVH<T>> {
290 static inline AssertingVH<T> getEmptyKey() {
292 Res.setRawValPtr(DenseMapInfo<Value *>::getEmptyKey());
296 static inline AssertingVH<T> getTombstoneKey() {
298 Res.setRawValPtr(DenseMapInfo<Value *>::getTombstoneKey());
302 static unsigned getHashValue(const AssertingVH<T> &Val) {
303 return DenseMapInfo<Value *>::getHashValue(Val.getRawValPtr());
306 static bool isEqual(const AssertingVH<T> &LHS, const AssertingVH<T> &RHS) {
307 return DenseMapInfo<Value *>::isEqual(LHS.getRawValPtr(),
312 template <typename T>
313 struct isPodLike<AssertingVH<T>> {
315 static const bool value = true;
317 static const bool value = false;
321 /// \brief Value handle that tracks a Value across RAUW.
323 /// TrackingVH is designed for situations where a client needs to hold a handle
324 /// to a Value (or subclass) across some operations which may move that value,
325 /// but should never destroy it or replace it with some unacceptable type.
327 /// It is an error to attempt to replace a value with one of a type which is
328 /// incompatible with any of its outstanding TrackingVHs.
330 /// It is an error to read from a TrackingVH that does not point to a valid
331 /// value. A TrackingVH is said to not point to a valid value if either it
332 /// hasn't yet been assigned a value yet or because the value it was tracking
333 /// has since been deleted.
335 /// Assigning a value to a TrackingVH is always allowed, even if said TrackingVH
336 /// no longer points to a valid value.
337 template <typename ValueTy> class TrackingVH {
338 WeakTrackingVH InnerHandle;
341 ValueTy *getValPtr() const {
342 assert(InnerHandle.pointsToAliveValue() &&
343 "TrackingVH must be non-null and valid on dereference!");
345 // Check that the value is a member of the correct subclass. We would like
346 // to check this property on assignment for better debugging, but we don't
347 // want to require a virtual interface on this VH. Instead we allow RAUW to
348 // replace this value with a value of an invalid type, and check it here.
349 assert(isa<ValueTy>(InnerHandle) &&
350 "Tracked Value was replaced by one with an invalid type!");
351 return cast<ValueTy>(InnerHandle);
354 void setValPtr(ValueTy *P) {
355 // Assigning to non-valid TrackingVH's are fine so we just unconditionally
357 InnerHandle = GetAsValue(P);
360 // Convert a ValueTy*, which may be const, to the type the base
362 static Value *GetAsValue(Value *V) { return V; }
363 static Value *GetAsValue(const Value *V) { return const_cast<Value*>(V); }
366 TrackingVH() = default;
367 TrackingVH(ValueTy *P) { setValPtr(P); }
369 operator ValueTy*() const {
373 ValueTy *operator=(ValueTy *RHS) {
378 ValueTy *operator->() const { return getValPtr(); }
379 ValueTy &operator*() const { return *getValPtr(); }
382 /// \brief Value handle with callbacks on RAUW and destruction.
384 /// This is a value handle that allows subclasses to define callbacks that run
385 /// when the underlying Value has RAUW called on it or is destroyed. This
386 /// class can be used as the key of a map, as long as the user takes it out of
387 /// the map before calling setValPtr() (since the map has to rearrange itself
388 /// when the pointer changes). Unlike ValueHandleBase, this class has a vtable.
389 class CallbackVH : public ValueHandleBase {
390 virtual void anchor();
392 ~CallbackVH() = default;
393 CallbackVH(const CallbackVH &) = default;
394 CallbackVH &operator=(const CallbackVH &) = default;
396 void setValPtr(Value *P) {
397 ValueHandleBase::operator=(P);
401 CallbackVH() : ValueHandleBase(Callback) {}
402 CallbackVH(Value *P) : ValueHandleBase(Callback, P) {}
404 operator Value*() const {
408 /// \brief Callback for Value destruction.
410 /// Called when this->getValPtr() is destroyed, inside ~Value(), so you
411 /// may call any non-virtual Value method on getValPtr(), but no subclass
412 /// methods. If WeakTrackingVH were implemented as a CallbackVH, it would use
414 /// method to call setValPtr(NULL). AssertingVH would use this method to
415 /// cause an assertion failure.
417 /// All implementations must remove the reference from this object to the
418 /// Value that's being destroyed.
419 virtual void deleted() { setValPtr(nullptr); }
421 /// \brief Callback for Value RAUW.
423 /// Called when this->getValPtr()->replaceAllUsesWith(new_value) is called,
424 /// _before_ any of the uses have actually been replaced. If WeakTrackingVH
426 /// implemented as a CallbackVH, it would use this method to call
427 /// setValPtr(new_value). AssertingVH would do nothing in this method.
428 virtual void allUsesReplacedWith(Value *) {}
431 /// Value handle that poisons itself if the Value is deleted.
433 /// This is a Value Handle that points to a value and poisons itself if the
434 /// value is destroyed while the handle is still live. This is very useful for
435 /// catching dangling pointer bugs where an \c AssertingVH cannot be used
436 /// because the dangling handle needs to outlive the value without ever being
439 /// One particularly useful place to use this is as the Key of a map. Dangling
440 /// pointer bugs often lead to really subtle bugs that only occur if another
441 /// object happens to get allocated to the same address as the old one. Using
442 /// a PoisoningVH ensures that an assert is triggered if looking up a new value
443 /// in the map finds a handle from the old value.
445 /// Note that a PoisoningVH handle does *not* follow values across RAUW
446 /// operations. This means that RAUW's need to explicitly update the
447 /// PoisoningVH's as it moves. This is required because in non-assert mode this
448 /// class turns into a trivial wrapper around a pointer.
449 template <typename ValueTy>
452 final : public CallbackVH
455 friend struct DenseMapInfo<PoisoningVH<ValueTy>>;
457 // Convert a ValueTy*, which may be const, to the raw Value*.
458 static Value *GetAsValue(Value *V) { return V; }
459 static Value *GetAsValue(const Value *V) { return const_cast<Value *>(V); }
462 /// A flag tracking whether this value has been poisoned.
464 /// On delete and RAUW, we leave the value pointer alone so that as a raw
465 /// pointer it produces the same value (and we fit into the same key of
466 /// a hash table, etc), but we poison the handle so that any top-level usage
468 bool Poisoned = false;
470 Value *getRawValPtr() const { return ValueHandleBase::getValPtr(); }
471 void setRawValPtr(Value *P) { ValueHandleBase::operator=(P); }
473 /// Handle deletion by poisoning the handle.
474 void deleted() override {
475 assert(!Poisoned && "Tried to delete an already poisoned handle!");
480 /// Handle RAUW by poisoning the handle.
481 void allUsesReplacedWith(Value *) override {
482 assert(!Poisoned && "Tried to RAUW an already poisoned handle!");
487 Value *ThePtr = nullptr;
489 Value *getRawValPtr() const { return ThePtr; }
490 void setRawValPtr(Value *P) { ThePtr = P; }
493 ValueTy *getValPtr() const {
494 assert(!Poisoned && "Accessed a poisoned value handle!");
495 return static_cast<ValueTy *>(getRawValPtr());
497 void setValPtr(ValueTy *P) { setRawValPtr(GetAsValue(P)); }
500 PoisoningVH() = default;
502 PoisoningVH(ValueTy *P) : CallbackVH(GetAsValue(P)) {}
503 PoisoningVH(const PoisoningVH &RHS)
504 : CallbackVH(RHS), Poisoned(RHS.Poisoned) {}
511 PoisoningVH &operator=(const PoisoningVH &RHS) {
514 CallbackVH::operator=(RHS);
515 Poisoned = RHS.Poisoned;
519 PoisoningVH(ValueTy *P) : ThePtr(GetAsValue(P)) {}
522 operator ValueTy *() const { return getValPtr(); }
524 ValueTy *operator->() const { return getValPtr(); }
525 ValueTy &operator*() const { return *getValPtr(); }
528 // Specialize DenseMapInfo to allow PoisoningVH to participate in DenseMap.
529 template <typename T> struct DenseMapInfo<PoisoningVH<T>> {
530 static inline PoisoningVH<T> getEmptyKey() {
532 Res.setRawValPtr(DenseMapInfo<Value *>::getEmptyKey());
536 static inline PoisoningVH<T> getTombstoneKey() {
538 Res.setRawValPtr(DenseMapInfo<Value *>::getTombstoneKey());
542 static unsigned getHashValue(const PoisoningVH<T> &Val) {
543 return DenseMapInfo<Value *>::getHashValue(Val.getRawValPtr());
546 static bool isEqual(const PoisoningVH<T> &LHS, const PoisoningVH<T> &RHS) {
547 return DenseMapInfo<Value *>::isEqual(LHS.getRawValPtr(),
552 template <typename T> struct isPodLike<PoisoningVH<T>> {
554 static const bool value = true;
556 static const bool value = false;
560 } // end namespace llvm
562 #endif // LLVM_IR_VALUEHANDLE_H