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