1//===- ValueHandle.h - Value Smart Pointer classes --------------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file declares the ValueHandle class and its sub-classes.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_IR_VALUEHANDLE_H
15#define LLVM_IR_VALUEHANDLE_H
16
17#include "llvm/ADT/DenseMapInfo.h"
18#include "llvm/ADT/PointerIntPair.h"
19#include "llvm/IR/Value.h"
20
21namespace llvm {
22class ValueHandleBase;
23template<typename From> struct simplify_type;
24
25// ValueHandleBase** is only 4-byte aligned.
26template<>
27class PointerLikeTypeTraits<ValueHandleBase**> {
28public:
29  static inline void *getAsVoidPointer(ValueHandleBase** P) { return P; }
30  static inline ValueHandleBase **getFromVoidPointer(void *P) {
31    return static_cast<ValueHandleBase**>(P);
32  }
33  enum { NumLowBitsAvailable = 2 };
34};
35
36/// ValueHandleBase - This is the common base class of value handles.
37/// ValueHandle's are smart pointers to Value's that have special behavior when
38/// the value is deleted or ReplaceAllUsesWith'd.  See the specific handles
39/// below for details.
40///
41class ValueHandleBase {
42  friend class Value;
43protected:
44  /// HandleBaseKind - This indicates what sub class the handle actually is.
45  /// This is to avoid having a vtable for the light-weight handle pointers. The
46  /// fully general Callback version does have a vtable.
47  enum HandleBaseKind {
48    Assert,
49    Callback,
50    Tracking,
51    Weak
52  };
53
54private:
55  PointerIntPair<ValueHandleBase**, 2, HandleBaseKind> PrevPair;
56  ValueHandleBase *Next;
57
58  // A subclass may want to store some information along with the value
59  // pointer. Allow them to do this by making the value pointer a pointer-int
60  // pair. The 'setValPtrInt' and 'getValPtrInt' methods below give them this
61  // access.
62  PointerIntPair<Value*, 2> VP;
63
64  ValueHandleBase(const ValueHandleBase&) LLVM_DELETED_FUNCTION;
65public:
66  explicit ValueHandleBase(HandleBaseKind Kind)
67    : PrevPair(nullptr, Kind), Next(nullptr), VP(nullptr, 0) {}
68  ValueHandleBase(HandleBaseKind Kind, Value *V)
69    : PrevPair(nullptr, Kind), Next(nullptr), VP(V, 0) {
70    if (isValid(VP.getPointer()))
71      AddToUseList();
72  }
73  ValueHandleBase(HandleBaseKind Kind, const ValueHandleBase &RHS)
74    : PrevPair(nullptr, Kind), Next(nullptr), VP(RHS.VP) {
75    if (isValid(VP.getPointer()))
76      AddToExistingUseList(RHS.getPrevPtr());
77  }
78  ~ValueHandleBase() {
79    if (isValid(VP.getPointer()))
80      RemoveFromUseList();
81  }
82
83  Value *operator=(Value *RHS) {
84    if (VP.getPointer() == RHS) return RHS;
85    if (isValid(VP.getPointer())) RemoveFromUseList();
86    VP.setPointer(RHS);
87    if (isValid(VP.getPointer())) AddToUseList();
88    return RHS;
89  }
90
91  Value *operator=(const ValueHandleBase &RHS) {
92    if (VP.getPointer() == RHS.VP.getPointer()) return RHS.VP.getPointer();
93    if (isValid(VP.getPointer())) RemoveFromUseList();
94    VP.setPointer(RHS.VP.getPointer());
95    if (isValid(VP.getPointer())) AddToExistingUseList(RHS.getPrevPtr());
96    return VP.getPointer();
97  }
98
99  Value *operator->() const { return getValPtr(); }
100  Value &operator*() const { return *getValPtr(); }
101
102protected:
103  Value *getValPtr() const { return VP.getPointer(); }
104
105  void setValPtrInt(unsigned K) { VP.setInt(K); }
106  unsigned getValPtrInt() const { return VP.getInt(); }
107
108  static bool isValid(Value *V) {
109    return V &&
110           V != DenseMapInfo<Value *>::getEmptyKey() &&
111           V != DenseMapInfo<Value *>::getTombstoneKey();
112  }
113
114public:
115  // Callbacks made from Value.
116  static void ValueIsDeleted(Value *V);
117  static void ValueIsRAUWd(Value *Old, Value *New);
118
119private:
120  // Internal implementation details.
121  ValueHandleBase **getPrevPtr() const { return PrevPair.getPointer(); }
122  HandleBaseKind getKind() const { return PrevPair.getInt(); }
123  void setPrevPtr(ValueHandleBase **Ptr) { PrevPair.setPointer(Ptr); }
124
125  /// AddToExistingUseList - Add this ValueHandle to the use list for VP, where
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);
129
130  /// AddToExistingUseListAfter - Add this ValueHandle to the use list after
131  /// Node.
132  void AddToExistingUseListAfter(ValueHandleBase *Node);
133
134  /// AddToUseList - Add this ValueHandle to the use list for VP.
135  void AddToUseList();
136  /// RemoveFromUseList - Remove this ValueHandle from its current use list.
137  void RemoveFromUseList();
138};
139
140/// WeakVH - This is a value handle that tries hard to point to a Value, even
141/// across RAUW operations, but will null itself out if the value is destroyed.
142/// this is useful for advisory sorts of information, but should not be used as
143/// the key of a map (since the map would have to rearrange itself when the
144/// pointer changes).
145class WeakVH : public ValueHandleBase {
146public:
147  WeakVH() : ValueHandleBase(Weak) {}
148  WeakVH(Value *P) : ValueHandleBase(Weak, P) {}
149  WeakVH(const WeakVH &RHS)
150    : ValueHandleBase(Weak, RHS) {}
151
152  Value *operator=(Value *RHS) {
153    return ValueHandleBase::operator=(RHS);
154  }
155  Value *operator=(const ValueHandleBase &RHS) {
156    return ValueHandleBase::operator=(RHS);
157  }
158
159  operator Value*() const {
160    return getValPtr();
161  }
162};
163
164// Specialize simplify_type to allow WeakVH to participate in
165// dyn_cast, isa, etc.
166template<> struct simplify_type<WeakVH> {
167  typedef Value* SimpleType;
168  static SimpleType getSimplifiedValue(WeakVH &WVH) {
169    return WVH;
170  }
171};
172
173/// AssertingVH - This is a Value Handle that points to a value and asserts out
174/// if the value is destroyed while the handle is still live.  This is very
175/// useful for catching dangling pointer bugs and other things which can be
176/// non-obvious.  One particularly useful place to use this is as the Key of a
177/// map.  Dangling pointer bugs often lead to really subtle bugs that only occur
178/// if another object happens to get allocated to the same address as the old
179/// one.  Using an AssertingVH ensures that an assert is triggered as soon as
180/// the bad delete occurs.
181///
182/// Note that an AssertingVH handle does *not* follow values across RAUW
183/// operations.  This means that RAUW's need to explicitly update the
184/// AssertingVH's as it moves.  This is required because in non-assert mode this
185/// class turns into a trivial wrapper around a pointer.
186template <typename ValueTy>
187class AssertingVH
188#ifndef NDEBUG
189  : public ValueHandleBase
190#endif
191  {
192
193#ifndef NDEBUG
194  ValueTy *getValPtr() const {
195    return static_cast<ValueTy*>(ValueHandleBase::getValPtr());
196  }
197  void setValPtr(ValueTy *P) {
198    ValueHandleBase::operator=(GetAsValue(P));
199  }
200#else
201  ValueTy *ThePtr;
202  ValueTy *getValPtr() const { return ThePtr; }
203  void setValPtr(ValueTy *P) { ThePtr = P; }
204#endif
205
206  // Convert a ValueTy*, which may be const, to the type the base
207  // class expects.
208  static Value *GetAsValue(Value *V) { return V; }
209  static Value *GetAsValue(const Value *V) { return const_cast<Value*>(V); }
210
211public:
212#ifndef NDEBUG
213  AssertingVH() : ValueHandleBase(Assert) {}
214  AssertingVH(ValueTy *P) : ValueHandleBase(Assert, GetAsValue(P)) {}
215  AssertingVH(const AssertingVH &RHS) : ValueHandleBase(Assert, RHS) {}
216#else
217  AssertingVH() : ThePtr(nullptr) {}
218  AssertingVH(ValueTy *P) : ThePtr(P) {}
219#endif
220
221  operator ValueTy*() const {
222    return getValPtr();
223  }
224
225  ValueTy *operator=(ValueTy *RHS) {
226    setValPtr(RHS);
227    return getValPtr();
228  }
229  ValueTy *operator=(const AssertingVH<ValueTy> &RHS) {
230    setValPtr(RHS.getValPtr());
231    return getValPtr();
232  }
233
234  ValueTy *operator->() const { return getValPtr(); }
235  ValueTy &operator*() const { return *getValPtr(); }
236};
237
238// Specialize DenseMapInfo to allow AssertingVH to participate in DenseMap.
239template<typename T>
240struct DenseMapInfo<AssertingVH<T> > {
241  typedef DenseMapInfo<T*> PointerInfo;
242  static inline AssertingVH<T> getEmptyKey() {
243    return AssertingVH<T>(PointerInfo::getEmptyKey());
244  }
245  static inline T* getTombstoneKey() {
246    return AssertingVH<T>(PointerInfo::getTombstoneKey());
247  }
248  static unsigned getHashValue(const AssertingVH<T> &Val) {
249    return PointerInfo::getHashValue(Val);
250  }
251  static bool isEqual(const AssertingVH<T> &LHS, const AssertingVH<T> &RHS) {
252    return LHS == RHS;
253  }
254};
255
256template <typename T>
257struct isPodLike<AssertingVH<T> > {
258#ifdef NDEBUG
259  static const bool value = true;
260#else
261  static const bool value = false;
262#endif
263};
264
265
266/// TrackingVH - This is a value handle that tracks a Value (or Value subclass),
267/// even across RAUW operations.
268///
269/// TrackingVH is designed for situations where a client needs to hold a handle
270/// to a Value (or subclass) across some operations which may move that value,
271/// but should never destroy it or replace it with some unacceptable type.
272///
273/// It is an error to do anything with a TrackingVH whose value has been
274/// destroyed, except to destruct it.
275///
276/// It is an error to attempt to replace a value with one of a type which is
277/// incompatible with any of its outstanding TrackingVHs.
278template<typename ValueTy>
279class TrackingVH : public ValueHandleBase {
280  void CheckValidity() const {
281    Value *VP = ValueHandleBase::getValPtr();
282
283    // Null is always ok.
284    if (!VP) return;
285
286    // Check that this value is valid (i.e., it hasn't been deleted). We
287    // explicitly delay this check until access to avoid requiring clients to be
288    // unnecessarily careful w.r.t. destruction.
289    assert(ValueHandleBase::isValid(VP) && "Tracked Value was deleted!");
290
291    // Check that the value is a member of the correct subclass. We would like
292    // to check this property on assignment for better debugging, but we don't
293    // want to require a virtual interface on this VH. Instead we allow RAUW to
294    // replace this value with a value of an invalid type, and check it here.
295    assert(isa<ValueTy>(VP) &&
296           "Tracked Value was replaced by one with an invalid type!");
297  }
298
299  ValueTy *getValPtr() const {
300    CheckValidity();
301    return (ValueTy*)ValueHandleBase::getValPtr();
302  }
303  void setValPtr(ValueTy *P) {
304    CheckValidity();
305    ValueHandleBase::operator=(GetAsValue(P));
306  }
307
308  // Convert a ValueTy*, which may be const, to the type the base
309  // class expects.
310  static Value *GetAsValue(Value *V) { return V; }
311  static Value *GetAsValue(const Value *V) { return const_cast<Value*>(V); }
312
313public:
314  TrackingVH() : ValueHandleBase(Tracking) {}
315  TrackingVH(ValueTy *P) : ValueHandleBase(Tracking, GetAsValue(P)) {}
316  TrackingVH(const TrackingVH &RHS) : ValueHandleBase(Tracking, RHS) {}
317
318  operator ValueTy*() const {
319    return getValPtr();
320  }
321
322  ValueTy *operator=(ValueTy *RHS) {
323    setValPtr(RHS);
324    return getValPtr();
325  }
326  ValueTy *operator=(const TrackingVH<ValueTy> &RHS) {
327    setValPtr(RHS.getValPtr());
328    return getValPtr();
329  }
330
331  ValueTy *operator->() const { return getValPtr(); }
332  ValueTy &operator*() const { return *getValPtr(); }
333};
334
335/// CallbackVH - This is a value handle that allows subclasses to define
336/// callbacks that run when the underlying Value has RAUW called on it or is
337/// destroyed.  This class can be used as the key of a map, as long as the user
338/// takes it out of the map before calling setValPtr() (since the map has to
339/// rearrange itself when the pointer changes).  Unlike ValueHandleBase, this
340/// class has a vtable and a virtual destructor.
341class CallbackVH : public ValueHandleBase {
342  virtual void anchor();
343protected:
344  CallbackVH(const CallbackVH &RHS)
345    : ValueHandleBase(Callback, RHS) {}
346
347  virtual ~CallbackVH() {}
348
349  void setValPtr(Value *P) {
350    ValueHandleBase::operator=(P);
351  }
352
353public:
354  CallbackVH() : ValueHandleBase(Callback) {}
355  CallbackVH(Value *P) : ValueHandleBase(Callback, P) {}
356
357  operator Value*() const {
358    return getValPtr();
359  }
360
361  /// Called when this->getValPtr() is destroyed, inside ~Value(), so you may
362  /// call any non-virtual Value method on getValPtr(), but no subclass methods.
363  /// If WeakVH were implemented as a CallbackVH, it would use this method to
364  /// call setValPtr(NULL).  AssertingVH would use this method to cause an
365  /// assertion failure.
366  ///
367  /// All implementations must remove the reference from this object to the
368  /// Value that's being destroyed.
369  virtual void deleted() { setValPtr(nullptr); }
370
371  /// Called when this->getValPtr()->replaceAllUsesWith(new_value) is called,
372  /// _before_ any of the uses have actually been replaced.  If WeakVH were
373  /// implemented as a CallbackVH, it would use this method to call
374  /// setValPtr(new_value).  AssertingVH would do nothing in this method.
375  virtual void allUsesReplacedWith(Value *) {}
376};
377
378} // End llvm namespace
379
380#endif
381