IntrusiveRefCntPtr.h 9.3 KB

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