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