blob: 1135d796f7ed7def28191f78d224c03a9a3e2c13 [file] [log] [blame]
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001//===- ValueHandle.h - Value Smart Pointer classes --------------*- C++ -*-===//
2//
Andrew Walbran16937d02019-10-22 13:54:20 +01003// 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
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01006//
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
22namespace llvm {
23
Andrew Scullcdfcccc2018-10-05 20:58:37 +010024/// This is the common base class of value handles.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010025///
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.
29class ValueHandleBase {
30 friend class Value;
31
32protected:
Andrew Scullcdfcccc2018-10-05 20:58:37 +010033 /// This indicates what sub class the handle actually is.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010034 ///
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
48private:
49 PointerIntPair<ValueHandleBase**, 2, HandleBaseKind> PrevPair;
50 ValueHandleBase *Next = nullptr;
51 Value *Val = nullptr;
52
53 void setValPtr(Value *V) { Val = V; }
54
55public:
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
94protected:
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
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100103 /// Remove this ValueHandle from its current use list.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100104 void RemoveFromUseList();
105
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100106 /// Clear the underlying pointer without clearing the use list.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100107 ///
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
112public:
113 // Callbacks made from Value.
114 static void ValueIsDeleted(Value *V);
115 static void ValueIsRAUWd(Value *Old, Value *New);
116
117private:
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
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100123 /// Add this ValueHandle to the use list for V.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100124 ///
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
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100129 /// Add this ValueHandle to the use list after Node.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100130 void AddToExistingUseListAfter(ValueHandleBase *Node);
131
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100132 /// Add this ValueHandle to the use list for V.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100133 void AddToUseList();
134};
135
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100136/// A nullable Value handle that is nullable.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100137///
138/// This is a value handle that points to a value, and nulls itself
139/// out if that value is deleted.
140class WeakVH : public ValueHandleBase {
141public:
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.
163template <> struct simplify_type<WeakVH> {
164 using SimpleType = Value *;
165
166 static SimpleType getSimplifiedValue(WeakVH &WVH) { return WVH; }
167};
168template <> struct simplify_type<const WeakVH> {
169 using SimpleType = Value *;
170
171 static SimpleType getSimplifiedValue(const WeakVH &WVH) { return WVH; }
172};
173
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100174/// Value handle that is nullable, but tries to track the Value.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100175///
176/// This is a value handle that tries hard to point to a Value, even across
177/// RAUW operations, but will null itself out if the value is destroyed. this
178/// is useful for advisory sorts of information, but should not be used as the
179/// key of a map (since the map would have to rearrange itself when the pointer
180/// changes).
181class WeakTrackingVH : public ValueHandleBase {
182public:
183 WeakTrackingVH() : ValueHandleBase(WeakTracking) {}
184 WeakTrackingVH(Value *P) : ValueHandleBase(WeakTracking, P) {}
185 WeakTrackingVH(const WeakTrackingVH &RHS)
186 : ValueHandleBase(WeakTracking, RHS) {}
187
188 WeakTrackingVH &operator=(const WeakTrackingVH &RHS) = default;
189
190 Value *operator=(Value *RHS) {
191 return ValueHandleBase::operator=(RHS);
192 }
193 Value *operator=(const ValueHandleBase &RHS) {
194 return ValueHandleBase::operator=(RHS);
195 }
196
197 operator Value*() const {
198 return getValPtr();
199 }
200
201 bool pointsToAliveValue() const {
202 return ValueHandleBase::isValid(getValPtr());
203 }
204};
205
206// Specialize simplify_type to allow WeakTrackingVH to participate in
207// dyn_cast, isa, etc.
208template <> struct simplify_type<WeakTrackingVH> {
209 using SimpleType = Value *;
210
211 static SimpleType getSimplifiedValue(WeakTrackingVH &WVH) { return WVH; }
212};
213template <> struct simplify_type<const WeakTrackingVH> {
214 using SimpleType = Value *;
215
216 static SimpleType getSimplifiedValue(const WeakTrackingVH &WVH) {
217 return WVH;
218 }
219};
220
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100221/// Value handle that asserts if the Value is deleted.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100222///
223/// This is a Value Handle that points to a value and asserts out if the value
224/// is destroyed while the handle is still live. This is very useful for
225/// catching dangling pointer bugs and other things which can be non-obvious.
226/// One particularly useful place to use this is as the Key of a map. Dangling
227/// pointer bugs often lead to really subtle bugs that only occur if another
228/// object happens to get allocated to the same address as the old one. Using
229/// an AssertingVH ensures that an assert is triggered as soon as the bad
230/// delete occurs.
231///
232/// Note that an AssertingVH handle does *not* follow values across RAUW
233/// operations. This means that RAUW's need to explicitly update the
234/// AssertingVH's as it moves. This is required because in non-assert mode this
235/// class turns into a trivial wrapper around a pointer.
236template <typename ValueTy>
237class AssertingVH
238#ifndef NDEBUG
239 : public ValueHandleBase
240#endif
241 {
242 friend struct DenseMapInfo<AssertingVH<ValueTy>>;
243
244#ifndef NDEBUG
245 Value *getRawValPtr() const { return ValueHandleBase::getValPtr(); }
246 void setRawValPtr(Value *P) { ValueHandleBase::operator=(P); }
247#else
248 Value *ThePtr;
249 Value *getRawValPtr() const { return ThePtr; }
250 void setRawValPtr(Value *P) { ThePtr = P; }
251#endif
252 // Convert a ValueTy*, which may be const, to the raw Value*.
253 static Value *GetAsValue(Value *V) { return V; }
254 static Value *GetAsValue(const Value *V) { return const_cast<Value*>(V); }
255
256 ValueTy *getValPtr() const { return static_cast<ValueTy *>(getRawValPtr()); }
257 void setValPtr(ValueTy *P) { setRawValPtr(GetAsValue(P)); }
258
259public:
260#ifndef NDEBUG
261 AssertingVH() : ValueHandleBase(Assert) {}
262 AssertingVH(ValueTy *P) : ValueHandleBase(Assert, GetAsValue(P)) {}
263 AssertingVH(const AssertingVH &RHS) : ValueHandleBase(Assert, RHS) {}
264#else
265 AssertingVH() : ThePtr(nullptr) {}
266 AssertingVH(ValueTy *P) : ThePtr(GetAsValue(P)) {}
267#endif
268
269 operator ValueTy*() const {
270 return getValPtr();
271 }
272
273 ValueTy *operator=(ValueTy *RHS) {
274 setValPtr(RHS);
275 return getValPtr();
276 }
277 ValueTy *operator=(const AssertingVH<ValueTy> &RHS) {
278 setValPtr(RHS.getValPtr());
279 return getValPtr();
280 }
281
282 ValueTy *operator->() const { return getValPtr(); }
283 ValueTy &operator*() const { return *getValPtr(); }
284};
285
286// Specialize DenseMapInfo to allow AssertingVH to participate in DenseMap.
287template<typename T>
288struct DenseMapInfo<AssertingVH<T>> {
289 static inline AssertingVH<T> getEmptyKey() {
290 AssertingVH<T> Res;
291 Res.setRawValPtr(DenseMapInfo<Value *>::getEmptyKey());
292 return Res;
293 }
294
295 static inline AssertingVH<T> getTombstoneKey() {
296 AssertingVH<T> Res;
297 Res.setRawValPtr(DenseMapInfo<Value *>::getTombstoneKey());
298 return Res;
299 }
300
301 static unsigned getHashValue(const AssertingVH<T> &Val) {
302 return DenseMapInfo<Value *>::getHashValue(Val.getRawValPtr());
303 }
304
305 static bool isEqual(const AssertingVH<T> &LHS, const AssertingVH<T> &RHS) {
306 return DenseMapInfo<Value *>::isEqual(LHS.getRawValPtr(),
307 RHS.getRawValPtr());
308 }
309};
310
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100311/// Value handle that tracks a Value across RAUW.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100312///
313/// TrackingVH is designed for situations where a client needs to hold a handle
314/// to a Value (or subclass) across some operations which may move that value,
315/// but should never destroy it or replace it with some unacceptable type.
316///
317/// It is an error to attempt to replace a value with one of a type which is
318/// incompatible with any of its outstanding TrackingVHs.
319///
320/// It is an error to read from a TrackingVH that does not point to a valid
321/// value. A TrackingVH is said to not point to a valid value if either it
322/// hasn't yet been assigned a value yet or because the value it was tracking
323/// has since been deleted.
324///
325/// Assigning a value to a TrackingVH is always allowed, even if said TrackingVH
326/// no longer points to a valid value.
327template <typename ValueTy> class TrackingVH {
328 WeakTrackingVH InnerHandle;
329
330public:
331 ValueTy *getValPtr() const {
332 assert(InnerHandle.pointsToAliveValue() &&
333 "TrackingVH must be non-null and valid on dereference!");
334
335 // Check that the value is a member of the correct subclass. We would like
336 // to check this property on assignment for better debugging, but we don't
337 // want to require a virtual interface on this VH. Instead we allow RAUW to
338 // replace this value with a value of an invalid type, and check it here.
339 assert(isa<ValueTy>(InnerHandle) &&
340 "Tracked Value was replaced by one with an invalid type!");
341 return cast<ValueTy>(InnerHandle);
342 }
343
344 void setValPtr(ValueTy *P) {
345 // Assigning to non-valid TrackingVH's are fine so we just unconditionally
346 // assign here.
347 InnerHandle = GetAsValue(P);
348 }
349
350 // Convert a ValueTy*, which may be const, to the type the base
351 // class expects.
352 static Value *GetAsValue(Value *V) { return V; }
353 static Value *GetAsValue(const Value *V) { return const_cast<Value*>(V); }
354
355public:
356 TrackingVH() = default;
357 TrackingVH(ValueTy *P) { setValPtr(P); }
358
359 operator ValueTy*() const {
360 return getValPtr();
361 }
362
363 ValueTy *operator=(ValueTy *RHS) {
364 setValPtr(RHS);
365 return getValPtr();
366 }
367
368 ValueTy *operator->() const { return getValPtr(); }
369 ValueTy &operator*() const { return *getValPtr(); }
370};
371
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100372/// Value handle with callbacks on RAUW and destruction.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100373///
374/// This is a value handle that allows subclasses to define callbacks that run
375/// when the underlying Value has RAUW called on it or is destroyed. This
376/// class can be used as the key of a map, as long as the user takes it out of
377/// the map before calling setValPtr() (since the map has to rearrange itself
378/// when the pointer changes). Unlike ValueHandleBase, this class has a vtable.
379class CallbackVH : public ValueHandleBase {
380 virtual void anchor();
381protected:
382 ~CallbackVH() = default;
383 CallbackVH(const CallbackVH &) = default;
384 CallbackVH &operator=(const CallbackVH &) = default;
385
386 void setValPtr(Value *P) {
387 ValueHandleBase::operator=(P);
388 }
389
390public:
391 CallbackVH() : ValueHandleBase(Callback) {}
392 CallbackVH(Value *P) : ValueHandleBase(Callback, P) {}
393
394 operator Value*() const {
395 return getValPtr();
396 }
397
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100398 /// Callback for Value destruction.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100399 ///
400 /// Called when this->getValPtr() is destroyed, inside ~Value(), so you
401 /// may call any non-virtual Value method on getValPtr(), but no subclass
402 /// methods. If WeakTrackingVH were implemented as a CallbackVH, it would use
403 /// this
404 /// method to call setValPtr(NULL). AssertingVH would use this method to
405 /// cause an assertion failure.
406 ///
407 /// All implementations must remove the reference from this object to the
408 /// Value that's being destroyed.
409 virtual void deleted() { setValPtr(nullptr); }
410
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100411 /// Callback for Value RAUW.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100412 ///
413 /// Called when this->getValPtr()->replaceAllUsesWith(new_value) is called,
414 /// _before_ any of the uses have actually been replaced. If WeakTrackingVH
415 /// were
416 /// implemented as a CallbackVH, it would use this method to call
417 /// setValPtr(new_value). AssertingVH would do nothing in this method.
418 virtual void allUsesReplacedWith(Value *) {}
419};
420
421/// Value handle that poisons itself if the Value is deleted.
422///
423/// This is a Value Handle that points to a value and poisons itself if the
424/// value is destroyed while the handle is still live. This is very useful for
425/// catching dangling pointer bugs where an \c AssertingVH cannot be used
426/// because the dangling handle needs to outlive the value without ever being
427/// used.
428///
429/// One particularly useful place to use this is as the Key of a map. Dangling
430/// pointer bugs often lead to really subtle bugs that only occur if another
431/// object happens to get allocated to the same address as the old one. Using
432/// a PoisoningVH ensures that an assert is triggered if looking up a new value
433/// in the map finds a handle from the old value.
434///
435/// Note that a PoisoningVH handle does *not* follow values across RAUW
436/// operations. This means that RAUW's need to explicitly update the
437/// PoisoningVH's as it moves. This is required because in non-assert mode this
438/// class turns into a trivial wrapper around a pointer.
439template <typename ValueTy>
440class PoisoningVH
441#ifndef NDEBUG
442 final : public CallbackVH
443#endif
444{
445 friend struct DenseMapInfo<PoisoningVH<ValueTy>>;
446
447 // Convert a ValueTy*, which may be const, to the raw Value*.
448 static Value *GetAsValue(Value *V) { return V; }
449 static Value *GetAsValue(const Value *V) { return const_cast<Value *>(V); }
450
451#ifndef NDEBUG
452 /// A flag tracking whether this value has been poisoned.
453 ///
454 /// On delete and RAUW, we leave the value pointer alone so that as a raw
455 /// pointer it produces the same value (and we fit into the same key of
456 /// a hash table, etc), but we poison the handle so that any top-level usage
457 /// will fail.
458 bool Poisoned = false;
459
460 Value *getRawValPtr() const { return ValueHandleBase::getValPtr(); }
461 void setRawValPtr(Value *P) { ValueHandleBase::operator=(P); }
462
463 /// Handle deletion by poisoning the handle.
464 void deleted() override {
465 assert(!Poisoned && "Tried to delete an already poisoned handle!");
466 Poisoned = true;
467 RemoveFromUseList();
468 }
469
470 /// Handle RAUW by poisoning the handle.
471 void allUsesReplacedWith(Value *) override {
472 assert(!Poisoned && "Tried to RAUW an already poisoned handle!");
473 Poisoned = true;
474 RemoveFromUseList();
475 }
476#else // NDEBUG
477 Value *ThePtr = nullptr;
478
479 Value *getRawValPtr() const { return ThePtr; }
480 void setRawValPtr(Value *P) { ThePtr = P; }
481#endif
482
483 ValueTy *getValPtr() const {
484 assert(!Poisoned && "Accessed a poisoned value handle!");
485 return static_cast<ValueTy *>(getRawValPtr());
486 }
487 void setValPtr(ValueTy *P) { setRawValPtr(GetAsValue(P)); }
488
489public:
490 PoisoningVH() = default;
491#ifndef NDEBUG
492 PoisoningVH(ValueTy *P) : CallbackVH(GetAsValue(P)) {}
493 PoisoningVH(const PoisoningVH &RHS)
494 : CallbackVH(RHS), Poisoned(RHS.Poisoned) {}
495
496 ~PoisoningVH() {
497 if (Poisoned)
498 clearValPtr();
499 }
500
501 PoisoningVH &operator=(const PoisoningVH &RHS) {
502 if (Poisoned)
503 clearValPtr();
504 CallbackVH::operator=(RHS);
505 Poisoned = RHS.Poisoned;
506 return *this;
507 }
508#else
509 PoisoningVH(ValueTy *P) : ThePtr(GetAsValue(P)) {}
510#endif
511
512 operator ValueTy *() const { return getValPtr(); }
513
514 ValueTy *operator->() const { return getValPtr(); }
515 ValueTy &operator*() const { return *getValPtr(); }
516};
517
518// Specialize DenseMapInfo to allow PoisoningVH to participate in DenseMap.
519template <typename T> struct DenseMapInfo<PoisoningVH<T>> {
520 static inline PoisoningVH<T> getEmptyKey() {
521 PoisoningVH<T> Res;
522 Res.setRawValPtr(DenseMapInfo<Value *>::getEmptyKey());
523 return Res;
524 }
525
526 static inline PoisoningVH<T> getTombstoneKey() {
527 PoisoningVH<T> Res;
528 Res.setRawValPtr(DenseMapInfo<Value *>::getTombstoneKey());
529 return Res;
530 }
531
532 static unsigned getHashValue(const PoisoningVH<T> &Val) {
533 return DenseMapInfo<Value *>::getHashValue(Val.getRawValPtr());
534 }
535
536 static bool isEqual(const PoisoningVH<T> &LHS, const PoisoningVH<T> &RHS) {
537 return DenseMapInfo<Value *>::isEqual(LHS.getRawValPtr(),
538 RHS.getRawValPtr());
539 }
540};
541
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100542} // end namespace llvm
543
544#endif // LLVM_IR_VALUEHANDLE_H