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 /// \brief This is the common base class of value handles.
     26 ///
     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 {
     31   friend class Value;
     32 protected:
     33   /// \brief This indicates what sub class the handle actually is.
     34   ///
     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 {
     38     Assert,
     39     Callback,
     40     Tracking,
     41     Weak
     42   };
     43 
     44   ValueHandleBase(const ValueHandleBase &RHS)
     45       : ValueHandleBase(RHS.PrevPair.getInt(), RHS) {}
     46 
     47   ValueHandleBase(HandleBaseKind Kind, const ValueHandleBase &RHS)
     48       : PrevPair(nullptr, Kind), Next(nullptr), V(RHS.V) {
     49     if (isValid(V))
     50       AddToExistingUseList(RHS.getPrevPtr());
     51   }
     52 
     53 private:
     54   PointerIntPair<ValueHandleBase**, 2, HandleBaseKind> PrevPair;
     55   ValueHandleBase *Next;
     56 
     57   Value* V;
     58 
     59 public:
     60   explicit ValueHandleBase(HandleBaseKind Kind)
     61     : PrevPair(nullptr, Kind), Next(nullptr), V(nullptr) {}
     62   ValueHandleBase(HandleBaseKind Kind, Value *V)
     63     : PrevPair(nullptr, Kind), Next(nullptr), V(V) {
     64     if (isValid(V))
     65       AddToUseList();
     66   }
     67 
     68   ~ValueHandleBase() {
     69     if (isValid(V))
     70       RemoveFromUseList();
     71   }
     72 
     73   Value *operator=(Value *RHS) {
     74     if (V == RHS) return RHS;
     75     if (isValid(V)) RemoveFromUseList();
     76     V = RHS;
     77     if (isValid(V)) AddToUseList();
     78     return RHS;
     79   }
     80 
     81   Value *operator=(const ValueHandleBase &RHS) {
     82     if (V == RHS.V) return RHS.V;
     83     if (isValid(V)) RemoveFromUseList();
     84     V = RHS.V;
     85     if (isValid(V)) AddToExistingUseList(RHS.getPrevPtr());
     86     return V;
     87   }
     88 
     89   Value *operator->() const { return V; }
     90   Value &operator*() const { return *V; }
     91 
     92 protected:
     93   Value *getValPtr() const { return V; }
     94 
     95   static bool isValid(Value *V) {
     96     return V &&
     97            V != DenseMapInfo<Value *>::getEmptyKey() &&
     98            V != DenseMapInfo<Value *>::getTombstoneKey();
     99   }
    100 
    101   /// \brief Remove this ValueHandle from its current use list.
    102   void RemoveFromUseList();
    103 
    104   /// \brief Clear the underlying pointer without clearing the use list.
    105   ///
    106   /// This should only be used if a derived class has manually removed the
    107   /// handle from the use list.
    108   void clearValPtr() { V = nullptr; }
    109 
    110 public:
    111   // Callbacks made from Value.
    112   static void ValueIsDeleted(Value *V);
    113   static void ValueIsRAUWd(Value *Old, Value *New);
    114 
    115 private:
    116   // Internal implementation details.
    117   ValueHandleBase **getPrevPtr() const { return PrevPair.getPointer(); }
    118   HandleBaseKind getKind() const { return PrevPair.getInt(); }
    119   void setPrevPtr(ValueHandleBase **Ptr) { PrevPair.setPointer(Ptr); }
    120 
    121   /// \brief Add this ValueHandle to the use list for V.
    122   ///
    123   /// List is the address of either the head of the list or a Next node within
    124   /// the existing use list.
    125   void AddToExistingUseList(ValueHandleBase **List);
    126 
    127   /// \brief Add this ValueHandle to the use list after Node.
    128   void AddToExistingUseListAfter(ValueHandleBase *Node);
    129 
    130   /// \brief Add this ValueHandle to the use list for V.
    131   void AddToUseList();
    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   WeakVH &operator=(const WeakVH &RHS) = default;
    149 
    150   Value *operator=(Value *RHS) {
    151     return ValueHandleBase::operator=(RHS);
    152   }
    153   Value *operator=(const ValueHandleBase &RHS) {
    154     return ValueHandleBase::operator=(RHS);
    155   }
    156 
    157   operator Value*() const {
    158     return getValPtr();
    159   }
    160 };
    161 
    162 // Specialize simplify_type to allow WeakVH to participate in
    163 // dyn_cast, isa, etc.
    164 template <> struct simplify_type<WeakVH> {
    165   typedef Value *SimpleType;
    166   static SimpleType getSimplifiedValue(WeakVH &WVH) { return WVH; }
    167 };
    168 template <> struct simplify_type<const WeakVH> {
    169   typedef Value *SimpleType;
    170   static SimpleType getSimplifiedValue(const WeakVH &WVH) { return WVH; }
    171 };
    172 
    173 /// \brief Value handle that asserts if the Value is deleted.
    174 ///
    175 /// This is a Value Handle that points to a value and asserts out if the value
    176 /// is destroyed while the handle is still live.  This is very useful for
    177 /// catching dangling pointer bugs and other things which can be non-obvious.
    178 /// One particularly useful place to use this is as the Key of a map.  Dangling
    179 /// pointer bugs often lead to really subtle bugs that only occur if another
    180 /// object happens to get allocated to the same address as the old one.  Using
    181 /// an AssertingVH ensures that an assert is triggered as soon as the bad
    182 /// delete occurs.
    183 ///
    184 /// Note that an AssertingVH handle does *not* follow values across RAUW
    185 /// operations.  This means that RAUW's need to explicitly update the
    186 /// AssertingVH's as it moves.  This is required because in non-assert mode this
    187 /// class turns into a trivial wrapper around a pointer.
    188 template <typename ValueTy>
    189 class AssertingVH
    190 #ifndef NDEBUG
    191   : public ValueHandleBase
    192 #endif
    193   {
    194   friend struct DenseMapInfo<AssertingVH<ValueTy> >;
    195 
    196 #ifndef NDEBUG
    197   Value *getRawValPtr() const { return ValueHandleBase::getValPtr(); }
    198   void setRawValPtr(Value *P) { ValueHandleBase::operator=(P); }
    199 #else
    200   Value *ThePtr;
    201   Value *getRawValPtr() const { return ThePtr; }
    202   void setRawValPtr(Value *P) { ThePtr = P; }
    203 #endif
    204   // Convert a ValueTy*, which may be const, to the raw Value*.
    205   static Value *GetAsValue(Value *V) { return V; }
    206   static Value *GetAsValue(const Value *V) { return const_cast<Value*>(V); }
    207 
    208   ValueTy *getValPtr() const { return static_cast<ValueTy *>(getRawValPtr()); }
    209   void setValPtr(ValueTy *P) { setRawValPtr(GetAsValue(P)); }
    210 
    211 public:
    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(GetAsValue(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.
    239 template<typename T>
    240 struct DenseMapInfo<AssertingVH<T> > {
    241   static inline AssertingVH<T> getEmptyKey() {
    242     AssertingVH<T> Res;
    243     Res.setRawValPtr(DenseMapInfo<Value *>::getEmptyKey());
    244     return Res;
    245   }
    246   static inline AssertingVH<T> getTombstoneKey() {
    247     AssertingVH<T> Res;
    248     Res.setRawValPtr(DenseMapInfo<Value *>::getTombstoneKey());
    249     return Res;
    250   }
    251   static unsigned getHashValue(const AssertingVH<T> &Val) {
    252     return DenseMapInfo<Value *>::getHashValue(Val.getRawValPtr());
    253   }
    254   static bool isEqual(const AssertingVH<T> &LHS, const AssertingVH<T> &RHS) {
    255     return DenseMapInfo<Value *>::isEqual(LHS.getRawValPtr(),
    256                                           RHS.getRawValPtr());
    257   }
    258 };
    259 
    260 template <typename T>
    261 struct isPodLike<AssertingVH<T> > {
    262 #ifdef NDEBUG
    263   static const bool value = true;
    264 #else
    265   static const bool value = false;
    266 #endif
    267 };
    268 
    269 /// \brief Value handle that tracks a Value across RAUW.
    270 ///
    271 /// TrackingVH is designed for situations where a client needs to hold a handle
    272 /// to a Value (or subclass) across some operations which may move that value,
    273 /// but should never destroy it or replace it with some unacceptable type.
    274 ///
    275 /// It is an error to do anything with a TrackingVH whose value has been
    276 /// destroyed, except to destruct it.
    277 ///
    278 /// It is an error to attempt to replace a value with one of a type which is
    279 /// incompatible with any of its outstanding TrackingVHs.
    280 template<typename ValueTy>
    281 class TrackingVH : public ValueHandleBase {
    282   void CheckValidity() const {
    283     Value *VP = ValueHandleBase::getValPtr();
    284 
    285     // Null is always ok.
    286     if (!VP) return;
    287 
    288     // Check that this value is valid (i.e., it hasn't been deleted). We
    289     // explicitly delay this check until access to avoid requiring clients to be
    290     // unnecessarily careful w.r.t. destruction.
    291     assert(ValueHandleBase::isValid(VP) && "Tracked Value was deleted!");
    292 
    293     // Check that the value is a member of the correct subclass. We would like
    294     // to check this property on assignment for better debugging, but we don't
    295     // want to require a virtual interface on this VH. Instead we allow RAUW to
    296     // replace this value with a value of an invalid type, and check it here.
    297     assert(isa<ValueTy>(VP) &&
    298            "Tracked Value was replaced by one with an invalid type!");
    299   }
    300 
    301   ValueTy *getValPtr() const {
    302     CheckValidity();
    303     return (ValueTy*)ValueHandleBase::getValPtr();
    304   }
    305   void setValPtr(ValueTy *P) {
    306     CheckValidity();
    307     ValueHandleBase::operator=(GetAsValue(P));
    308   }
    309 
    310   // Convert a ValueTy*, which may be const, to the type the base
    311   // class expects.
    312   static Value *GetAsValue(Value *V) { return V; }
    313   static Value *GetAsValue(const Value *V) { return const_cast<Value*>(V); }
    314 
    315 public:
    316   TrackingVH() : ValueHandleBase(Tracking) {}
    317   TrackingVH(ValueTy *P) : ValueHandleBase(Tracking, GetAsValue(P)) {}
    318 
    319   operator ValueTy*() const {
    320     return getValPtr();
    321   }
    322 
    323   ValueTy *operator=(ValueTy *RHS) {
    324     setValPtr(RHS);
    325     return getValPtr();
    326   }
    327 
    328   ValueTy *operator->() const { return getValPtr(); }
    329   ValueTy &operator*() const { return *getValPtr(); }
    330 };
    331 
    332 /// \brief Value handle with callbacks on RAUW and destruction.
    333 ///
    334 /// This is a value handle that allows subclasses to define callbacks that run
    335 /// when the underlying Value has RAUW called on it or is destroyed.  This
    336 /// class can be used as the key of a map, as long as the user takes it out of
    337 /// the map before calling setValPtr() (since the map has to rearrange itself
    338 /// when the pointer changes).  Unlike ValueHandleBase, this class has a vtable.
    339 class CallbackVH : public ValueHandleBase {
    340   virtual void anchor();
    341 protected:
    342   ~CallbackVH() = default;
    343   CallbackVH(const CallbackVH &) = default;
    344   CallbackVH &operator=(const CallbackVH &) = default;
    345 
    346   void setValPtr(Value *P) {
    347     ValueHandleBase::operator=(P);
    348   }
    349 
    350 public:
    351   CallbackVH() : ValueHandleBase(Callback) {}
    352   CallbackVH(Value *P) : ValueHandleBase(Callback, P) {}
    353 
    354   operator Value*() const {
    355     return getValPtr();
    356   }
    357 
    358   /// \brief Callback for Value destruction.
    359   ///
    360   /// Called when this->getValPtr() is destroyed, inside ~Value(), so you
    361   /// may call any non-virtual Value method on getValPtr(), but no subclass
    362   /// methods.  If WeakVH were implemented as a CallbackVH, it would use this
    363   /// method to call setValPtr(NULL).  AssertingVH would use this method to
    364   /// cause an assertion failure.
    365   ///
    366   /// All implementations must remove the reference from this object to the
    367   /// Value that's being destroyed.
    368   virtual void deleted() { setValPtr(nullptr); }
    369 
    370   /// \brief Callback for Value RAUW.
    371   ///
    372   /// Called when this->getValPtr()->replaceAllUsesWith(new_value) is called,
    373   /// _before_ any of the uses have actually been replaced.  If WeakVH were
    374   /// implemented as a CallbackVH, it would use this method to call
    375   /// setValPtr(new_value).  AssertingVH would do nothing in this method.
    376   virtual void allUsesReplacedWith(Value *) {}
    377 };
    378 
    379 /// Value handle that poisons itself if the Value is deleted.
    380 ///
    381 /// This is a Value Handle that points to a value and poisons itself if the
    382 /// value is destroyed while the handle is still live.  This is very useful for
    383 /// catching dangling pointer bugs where an \c AssertingVH cannot be used
    384 /// because the dangling handle needs to outlive the value without ever being
    385 /// used.
    386 ///
    387 /// One particularly useful place to use this is as the Key of a map. Dangling
    388 /// pointer bugs often lead to really subtle bugs that only occur if another
    389 /// object happens to get allocated to the same address as the old one. Using
    390 /// a PoisoningVH ensures that an assert is triggered if looking up a new value
    391 /// in the map finds a handle from the old value.
    392 ///
    393 /// Note that a PoisoningVH handle does *not* follow values across RAUW
    394 /// operations. This means that RAUW's need to explicitly update the
    395 /// PoisoningVH's as it moves. This is required because in non-assert mode this
    396 /// class turns into a trivial wrapper around a pointer.
    397 template <typename ValueTy>
    398 class PoisoningVH
    399 #ifndef NDEBUG
    400     final : public CallbackVH
    401 #endif
    402 {
    403   friend struct DenseMapInfo<PoisoningVH<ValueTy>>;
    404 
    405   // Convert a ValueTy*, which may be const, to the raw Value*.
    406   static Value *GetAsValue(Value *V) { return V; }
    407   static Value *GetAsValue(const Value *V) { return const_cast<Value *>(V); }
    408 
    409 #ifndef NDEBUG
    410   /// A flag tracking whether this value has been poisoned.
    411   ///
    412   /// On delete and RAUW, we leave the value pointer alone so that as a raw
    413   /// pointer it produces the same value (and we fit into the same key of
    414   /// a hash table, etc), but we poison the handle so that any top-level usage
    415   /// will fail.
    416   bool Poisoned = false;
    417 
    418   Value *getRawValPtr() const { return ValueHandleBase::getValPtr(); }
    419   void setRawValPtr(Value *P) { ValueHandleBase::operator=(P); }
    420 
    421   /// Handle deletion by poisoning the handle.
    422   void deleted() override {
    423     assert(!Poisoned && "Tried to delete an already poisoned handle!");
    424     Poisoned = true;
    425     RemoveFromUseList();
    426   }
    427 
    428   /// Handle RAUW by poisoning the handle.
    429   void allUsesReplacedWith(Value *) override {
    430     assert(!Poisoned && "Tried to RAUW an already poisoned handle!");
    431     Poisoned = true;
    432     RemoveFromUseList();
    433   }
    434 #else // NDEBUG
    435   Value *ThePtr = nullptr;
    436 
    437   Value *getRawValPtr() const { return ThePtr; }
    438   void setRawValPtr(Value *P) { ThePtr = P; }
    439 #endif
    440 
    441   ValueTy *getValPtr() const {
    442     assert(!Poisoned && "Accessed a poisoned value handle!");
    443     return static_cast<ValueTy *>(getRawValPtr());
    444   }
    445   void setValPtr(ValueTy *P) { setRawValPtr(GetAsValue(P)); }
    446 
    447 public:
    448   PoisoningVH() = default;
    449 #ifndef NDEBUG
    450   PoisoningVH(ValueTy *P) : CallbackVH(GetAsValue(P)) {}
    451   PoisoningVH(const PoisoningVH &RHS)
    452       : CallbackVH(RHS), Poisoned(RHS.Poisoned) {}
    453   ~PoisoningVH() {
    454     if (Poisoned)
    455       clearValPtr();
    456   }
    457   PoisoningVH &operator=(const PoisoningVH &RHS) {
    458     if (Poisoned)
    459       clearValPtr();
    460     CallbackVH::operator=(RHS);
    461     Poisoned = RHS.Poisoned;
    462     return *this;
    463   }
    464 #else
    465   PoisoningVH(ValueTy *P) : ThePtr(GetAsValue(P)) {}
    466 #endif
    467 
    468   operator ValueTy *() const { return getValPtr(); }
    469 
    470   ValueTy *operator->() const { return getValPtr(); }
    471   ValueTy &operator*() const { return *getValPtr(); }
    472 };
    473 
    474 // Specialize DenseMapInfo to allow PoisoningVH to participate in DenseMap.
    475 template <typename T> struct DenseMapInfo<PoisoningVH<T>> {
    476   static inline PoisoningVH<T> getEmptyKey() {
    477     PoisoningVH<T> Res;
    478     Res.setRawValPtr(DenseMapInfo<Value *>::getEmptyKey());
    479     return Res;
    480   }
    481   static inline PoisoningVH<T> getTombstoneKey() {
    482     PoisoningVH<T> Res;
    483     Res.setRawValPtr(DenseMapInfo<Value *>::getTombstoneKey());
    484     return Res;
    485   }
    486   static unsigned getHashValue(const PoisoningVH<T> &Val) {
    487     return DenseMapInfo<Value *>::getHashValue(Val.getRawValPtr());
    488   }
    489   static bool isEqual(const PoisoningVH<T> &LHS, const PoisoningVH<T> &RHS) {
    490     return DenseMapInfo<Value *>::isEqual(LHS.getRawValPtr(),
    491                                           RHS.getRawValPtr());
    492   }
    493 };
    494 
    495 template <typename T> struct isPodLike<PoisoningVH<T>> {
    496 #ifdef NDEBUG
    497   static const bool value = true;
    498 #else
    499   static const bool value = false;
    500 #endif
    501 };
    502 
    503 } // End llvm namespace
    504 
    505 #endif
    506