Home | History | Annotate | Download | only in ADT
      1 //== llvm/ADT/IntrusiveRefCntPtr.h - Smart Refcounting Pointer ---*- 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 defines the RefCountedBase, ThreadSafeRefCountedBase, and
     11 // IntrusiveRefCntPtr classes.
     12 //
     13 // IntrusiveRefCntPtr is a smart pointer to an object which maintains a
     14 // reference count.  (ThreadSafe)RefCountedBase is a mixin class that adds a
     15 // refcount member variable and methods for updating the refcount.  An object
     16 // that inherits from (ThreadSafe)RefCountedBase deletes itself when its
     17 // refcount hits zero.
     18 //
     19 // For example:
     20 //
     21 //   class MyClass : public RefCountedBase<MyClass> {};
     22 //
     23 //   void foo() {
     24 //     // Constructing an IntrusiveRefCntPtr increases the pointee's refcount by
     25 //     // 1 (from 0 in this case).
     26 //     IntrusiveRefCntPtr<MyClass> Ptr1(new MyClass());
     27 //
     28 //     // Copying an IntrusiveRefCntPtr increases the pointee's refcount by 1.
     29 //     IntrusiveRefCntPtr<MyClass> Ptr2(Ptr1);
     30 //
     31 //     // Constructing an IntrusiveRefCntPtr has no effect on the object's
     32 //     // refcount.  After a move, the moved-from pointer is null.
     33 //     IntrusiveRefCntPtr<MyClass> Ptr3(std::move(Ptr1));
     34 //     assert(Ptr1 == nullptr);
     35 //
     36 //     // Clearing an IntrusiveRefCntPtr decreases the pointee's refcount by 1.
     37 //     Ptr2.reset();
     38 //
     39 //     // The object deletes itself when we return from the function, because
     40 //     // Ptr3's destructor decrements its refcount to 0.
     41 //   }
     42 //
     43 // You can use IntrusiveRefCntPtr with isa<T>(), dyn_cast<T>(), etc.:
     44 //
     45 //   IntrusiveRefCntPtr<MyClass> Ptr(new MyClass());
     46 //   OtherClass *Other = dyn_cast<OtherClass>(Ptr);  // Ptr.get() not required
     47 //
     48 // IntrusiveRefCntPtr works with any class that
     49 //
     50 //  - inherits from (ThreadSafe)RefCountedBase,
     51 //  - has Retain() and Release() methods, or
     52 //  - specializes IntrusiveRefCntPtrInfo.
     53 //
     54 //===----------------------------------------------------------------------===//
     55 
     56 #ifndef LLVM_ADT_INTRUSIVEREFCNTPTR_H
     57 #define LLVM_ADT_INTRUSIVEREFCNTPTR_H
     58 
     59 #include <atomic>
     60 #include <cassert>
     61 #include <cstddef>
     62 
     63 namespace llvm {
     64 
     65 /// A CRTP mixin class that adds reference counting to a type.
     66 ///
     67 /// The lifetime of an object which inherits from RefCountedBase is managed by
     68 /// calls to Release() and Retain(), which increment and decrement the object's
     69 /// refcount, respectively.  When a Release() call decrements the refcount to 0,
     70 /// the object deletes itself.
     71 template <class Derived> class RefCountedBase {
     72   mutable unsigned RefCount = 0;
     73 
     74 public:
     75   RefCountedBase() = default;
     76   RefCountedBase(const RefCountedBase &) : RefCount(0) {}
     77 
     78   void Retain() const { ++RefCount; }
     79   void Release() const {
     80     assert(RefCount > 0 && "Reference count is already zero.");
     81     if (--RefCount == 0)
     82       delete static_cast<const Derived *>(this);
     83   }
     84 };
     85 
     86 /// A thread-safe version of \c RefCountedBase.
     87 template <class Derived> class ThreadSafeRefCountedBase {
     88   mutable std::atomic<int> RefCount;
     89 
     90 protected:
     91   ThreadSafeRefCountedBase() : RefCount(0) {}
     92 
     93 public:
     94   void Retain() const { RefCount.fetch_add(1, std::memory_order_relaxed); }
     95 
     96   void Release() const {
     97     int NewRefCount = RefCount.fetch_sub(1, std::memory_order_acq_rel) - 1;
     98     assert(NewRefCount >= 0 && "Reference count was already zero.");
     99     if (NewRefCount == 0)
    100       delete static_cast<const Derived *>(this);
    101   }
    102 };
    103 
    104 /// Class you can specialize to provide custom retain/release functionality for
    105 /// a type.
    106 ///
    107 /// Usually specializing this class is not necessary, as IntrusiveRefCntPtr
    108 /// works with any type which defines Retain() and Release() functions -- you
    109 /// can define those functions yourself if RefCountedBase doesn't work for you.
    110 ///
    111 /// One case when you might want to specialize this type is if you have
    112 ///  - Foo.h defines type Foo and includes Bar.h, and
    113 ///  - Bar.h uses IntrusiveRefCntPtr<Foo> in inline functions.
    114 ///
    115 /// Because Foo.h includes Bar.h, Bar.h can't include Foo.h in order to pull in
    116 /// the declaration of Foo.  Without the declaration of Foo, normally Bar.h
    117 /// wouldn't be able to use IntrusiveRefCntPtr<Foo>, which wants to call
    118 /// T::Retain and T::Release.
    119 ///
    120 /// To resolve this, Bar.h could include a third header, FooFwd.h, which
    121 /// forward-declares Foo and specializes IntrusiveRefCntPtrInfo<Foo>.  Then
    122 /// Bar.h could use IntrusiveRefCntPtr<Foo>, although it still couldn't call any
    123 /// functions on Foo itself, because Foo would be an incomplete type.
    124 template <typename T> struct IntrusiveRefCntPtrInfo {
    125   static void retain(T *obj) { obj->Retain(); }
    126   static void release(T *obj) { obj->Release(); }
    127 };
    128 
    129 /// A smart pointer to a reference-counted object that inherits from
    130 /// RefCountedBase or ThreadSafeRefCountedBase.
    131 ///
    132 /// This class increments its pointee's reference count when it is created, and
    133 /// decrements its refcount when it's destroyed (or is changed to point to a
    134 /// different object).
    135 template <typename T> class IntrusiveRefCntPtr {
    136   T *Obj = nullptr;
    137 
    138 public:
    139   typedef T element_type;
    140 
    141   explicit IntrusiveRefCntPtr() = default;
    142   IntrusiveRefCntPtr(T *obj) : Obj(obj) { retain(); }
    143   IntrusiveRefCntPtr(const IntrusiveRefCntPtr &S) : Obj(S.Obj) { retain(); }
    144   IntrusiveRefCntPtr(IntrusiveRefCntPtr &&S) : Obj(S.Obj) { S.Obj = nullptr; }
    145 
    146   template <class X>
    147   IntrusiveRefCntPtr(IntrusiveRefCntPtr<X> &&S) : Obj(S.get()) {
    148     S.Obj = nullptr;
    149   }
    150 
    151   template <class X>
    152   IntrusiveRefCntPtr(const IntrusiveRefCntPtr<X> &S) : Obj(S.get()) {
    153     retain();
    154   }
    155 
    156   IntrusiveRefCntPtr &operator=(IntrusiveRefCntPtr S) {
    157     swap(S);
    158     return *this;
    159   }
    160 
    161   ~IntrusiveRefCntPtr() { release(); }
    162 
    163   T &operator*() const { return *Obj; }
    164   T *operator->() const { return Obj; }
    165   T *get() const { return Obj; }
    166   explicit operator bool() const { return Obj; }
    167 
    168   void swap(IntrusiveRefCntPtr &other) {
    169     T *tmp = other.Obj;
    170     other.Obj = Obj;
    171     Obj = tmp;
    172   }
    173 
    174   void reset() {
    175     release();
    176     Obj = nullptr;
    177   }
    178 
    179   void resetWithoutRelease() { Obj = nullptr; }
    180 
    181 private:
    182   void retain() {
    183     if (Obj)
    184       IntrusiveRefCntPtrInfo<T>::retain(Obj);
    185   }
    186   void release() {
    187     if (Obj)
    188       IntrusiveRefCntPtrInfo<T>::release(Obj);
    189   }
    190 
    191   template <typename X> friend class IntrusiveRefCntPtr;
    192 };
    193 
    194 template <class T, class U>
    195 inline bool operator==(const IntrusiveRefCntPtr<T> &A,
    196                        const IntrusiveRefCntPtr<U> &B) {
    197   return A.get() == B.get();
    198 }
    199 
    200 template <class T, class U>
    201 inline bool operator!=(const IntrusiveRefCntPtr<T> &A,
    202                        const IntrusiveRefCntPtr<U> &B) {
    203   return A.get() != B.get();
    204 }
    205 
    206 template <class T, class U>
    207 inline bool operator==(const IntrusiveRefCntPtr<T> &A, U *B) {
    208   return A.get() == B;
    209 }
    210 
    211 template <class T, class U>
    212 inline bool operator!=(const IntrusiveRefCntPtr<T> &A, U *B) {
    213   return A.get() != B;
    214 }
    215 
    216 template <class T, class U>
    217 inline bool operator==(T *A, const IntrusiveRefCntPtr<U> &B) {
    218   return A == B.get();
    219 }
    220 
    221 template <class T, class U>
    222 inline bool operator!=(T *A, const IntrusiveRefCntPtr<U> &B) {
    223   return A != B.get();
    224 }
    225 
    226 template <class T>
    227 bool operator==(std::nullptr_t A, const IntrusiveRefCntPtr<T> &B) {
    228   return !B;
    229 }
    230 
    231 template <class T>
    232 bool operator==(const IntrusiveRefCntPtr<T> &A, std::nullptr_t B) {
    233   return B == A;
    234 }
    235 
    236 template <class T>
    237 bool operator!=(std::nullptr_t A, const IntrusiveRefCntPtr<T> &B) {
    238   return !(A == B);
    239 }
    240 
    241 template <class T>
    242 bool operator!=(const IntrusiveRefCntPtr<T> &A, std::nullptr_t B) {
    243   return !(A == B);
    244 }
    245 
    246 // Make IntrusiveRefCntPtr work with dyn_cast, isa, and the other idioms from
    247 // Casting.h.
    248 template <typename From> struct simplify_type;
    249 
    250 template <class T> struct simplify_type<IntrusiveRefCntPtr<T>> {
    251   typedef T *SimpleType;
    252   static SimpleType getSimplifiedValue(IntrusiveRefCntPtr<T> &Val) {
    253     return Val.get();
    254   }
    255 };
    256 
    257 template <class T> struct simplify_type<const IntrusiveRefCntPtr<T>> {
    258   typedef /*const*/ T *SimpleType;
    259   static SimpleType getSimplifiedValue(const IntrusiveRefCntPtr<T> &Val) {
    260     return Val.get();
    261   }
    262 };
    263 
    264 } // end namespace llvm
    265 
    266 #endif // LLVM_ADT_INTRUSIVEREFCNTPTR_H
    267