blob: ca4c40db48b999a857a65dcc5f05e996b25da524 [file] [log] [blame]
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001//==- llvm/ADT/IntrusiveRefCntPtr.h - Smart Refcounting Pointer --*- C++ -*-==//
2//
Andrew Walbran16937d02019-10-22 13:54:20 +01003// 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
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01006//
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
55#ifndef LLVM_ADT_INTRUSIVEREFCNTPTR_H
56#define LLVM_ADT_INTRUSIVEREFCNTPTR_H
57
58#include <atomic>
59#include <cassert>
60#include <cstddef>
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020061#include <memory>
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010062
63namespace 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.
71template <class Derived> class RefCountedBase {
72 mutable unsigned RefCount = 0;
73
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020074protected:
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010075 RefCountedBase() = default;
76 RefCountedBase(const RefCountedBase &) {}
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020077 RefCountedBase &operator=(const RefCountedBase &) = delete;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010078
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020079#ifndef NDEBUG
80 ~RefCountedBase() {
81 assert(RefCount == 0 &&
82 "Destruction occured when there are still references to this.");
83 }
84#else
85 // Default the destructor in release builds, A trivial destructor may enable
86 // better codegen.
87 ~RefCountedBase() = default;
88#endif
89
90public:
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010091 void Retain() const { ++RefCount; }
92
93 void Release() const {
94 assert(RefCount > 0 && "Reference count is already zero.");
95 if (--RefCount == 0)
96 delete static_cast<const Derived *>(this);
97 }
98};
99
100/// A thread-safe version of \c RefCountedBase.
101template <class Derived> class ThreadSafeRefCountedBase {
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200102 mutable std::atomic<int> RefCount{0};
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100103
104protected:
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200105 ThreadSafeRefCountedBase() = default;
106 ThreadSafeRefCountedBase(const ThreadSafeRefCountedBase &) {}
107 ThreadSafeRefCountedBase &
108 operator=(const ThreadSafeRefCountedBase &) = delete;
109
110#ifndef NDEBUG
111 ~ThreadSafeRefCountedBase() {
112 assert(RefCount == 0 &&
113 "Destruction occured when there are still references to this.");
114 }
115#else
116 // Default the destructor in release builds, A trivial destructor may enable
117 // better codegen.
118 ~ThreadSafeRefCountedBase() = default;
119#endif
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100120
121public:
122 void Retain() const { RefCount.fetch_add(1, std::memory_order_relaxed); }
123
124 void Release() const {
125 int NewRefCount = RefCount.fetch_sub(1, std::memory_order_acq_rel) - 1;
126 assert(NewRefCount >= 0 && "Reference count was already zero.");
127 if (NewRefCount == 0)
128 delete static_cast<const Derived *>(this);
129 }
130};
131
132/// Class you can specialize to provide custom retain/release functionality for
133/// a type.
134///
135/// Usually specializing this class is not necessary, as IntrusiveRefCntPtr
136/// works with any type which defines Retain() and Release() functions -- you
137/// can define those functions yourself if RefCountedBase doesn't work for you.
138///
139/// One case when you might want to specialize this type is if you have
140/// - Foo.h defines type Foo and includes Bar.h, and
141/// - Bar.h uses IntrusiveRefCntPtr<Foo> in inline functions.
142///
143/// Because Foo.h includes Bar.h, Bar.h can't include Foo.h in order to pull in
144/// the declaration of Foo. Without the declaration of Foo, normally Bar.h
145/// wouldn't be able to use IntrusiveRefCntPtr<Foo>, which wants to call
146/// T::Retain and T::Release.
147///
148/// To resolve this, Bar.h could include a third header, FooFwd.h, which
149/// forward-declares Foo and specializes IntrusiveRefCntPtrInfo<Foo>. Then
150/// Bar.h could use IntrusiveRefCntPtr<Foo>, although it still couldn't call any
151/// functions on Foo itself, because Foo would be an incomplete type.
152template <typename T> struct IntrusiveRefCntPtrInfo {
153 static void retain(T *obj) { obj->Retain(); }
154 static void release(T *obj) { obj->Release(); }
155};
156
157/// A smart pointer to a reference-counted object that inherits from
158/// RefCountedBase or ThreadSafeRefCountedBase.
159///
160/// This class increments its pointee's reference count when it is created, and
161/// decrements its refcount when it's destroyed (or is changed to point to a
162/// different object).
163template <typename T> class IntrusiveRefCntPtr {
164 T *Obj = nullptr;
165
166public:
167 using element_type = T;
168
169 explicit IntrusiveRefCntPtr() = default;
170 IntrusiveRefCntPtr(T *obj) : Obj(obj) { retain(); }
171 IntrusiveRefCntPtr(const IntrusiveRefCntPtr &S) : Obj(S.Obj) { retain(); }
172 IntrusiveRefCntPtr(IntrusiveRefCntPtr &&S) : Obj(S.Obj) { S.Obj = nullptr; }
173
174 template <class X>
175 IntrusiveRefCntPtr(IntrusiveRefCntPtr<X> &&S) : Obj(S.get()) {
176 S.Obj = nullptr;
177 }
178
179 template <class X>
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200180 IntrusiveRefCntPtr(std::unique_ptr<X> S) : Obj(S.release()) {
181 retain();
182 }
183
184 template <class X>
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100185 IntrusiveRefCntPtr(const IntrusiveRefCntPtr<X> &S) : Obj(S.get()) {
186 retain();
187 }
188
189 ~IntrusiveRefCntPtr() { release(); }
190
191 IntrusiveRefCntPtr &operator=(IntrusiveRefCntPtr S) {
192 swap(S);
193 return *this;
194 }
195
196 T &operator*() const { return *Obj; }
197 T *operator->() const { return Obj; }
198 T *get() const { return Obj; }
199 explicit operator bool() const { return Obj; }
200
201 void swap(IntrusiveRefCntPtr &other) {
202 T *tmp = other.Obj;
203 other.Obj = Obj;
204 Obj = tmp;
205 }
206
207 void reset() {
208 release();
209 Obj = nullptr;
210 }
211
212 void resetWithoutRelease() { Obj = nullptr; }
213
214private:
215 void retain() {
216 if (Obj)
217 IntrusiveRefCntPtrInfo<T>::retain(Obj);
218 }
219
220 void release() {
221 if (Obj)
222 IntrusiveRefCntPtrInfo<T>::release(Obj);
223 }
224
225 template <typename X> friend class IntrusiveRefCntPtr;
226};
227
228template <class T, class U>
229inline bool operator==(const IntrusiveRefCntPtr<T> &A,
230 const IntrusiveRefCntPtr<U> &B) {
231 return A.get() == B.get();
232}
233
234template <class T, class U>
235inline bool operator!=(const IntrusiveRefCntPtr<T> &A,
236 const IntrusiveRefCntPtr<U> &B) {
237 return A.get() != B.get();
238}
239
240template <class T, class U>
241inline bool operator==(const IntrusiveRefCntPtr<T> &A, U *B) {
242 return A.get() == B;
243}
244
245template <class T, class U>
246inline bool operator!=(const IntrusiveRefCntPtr<T> &A, U *B) {
247 return A.get() != B;
248}
249
250template <class T, class U>
251inline bool operator==(T *A, const IntrusiveRefCntPtr<U> &B) {
252 return A == B.get();
253}
254
255template <class T, class U>
256inline bool operator!=(T *A, const IntrusiveRefCntPtr<U> &B) {
257 return A != B.get();
258}
259
260template <class T>
261bool operator==(std::nullptr_t A, const IntrusiveRefCntPtr<T> &B) {
262 return !B;
263}
264
265template <class T>
266bool operator==(const IntrusiveRefCntPtr<T> &A, std::nullptr_t B) {
267 return B == A;
268}
269
270template <class T>
271bool operator!=(std::nullptr_t A, const IntrusiveRefCntPtr<T> &B) {
272 return !(A == B);
273}
274
275template <class T>
276bool operator!=(const IntrusiveRefCntPtr<T> &A, std::nullptr_t B) {
277 return !(A == B);
278}
279
280// Make IntrusiveRefCntPtr work with dyn_cast, isa, and the other idioms from
281// Casting.h.
282template <typename From> struct simplify_type;
283
284template <class T> struct simplify_type<IntrusiveRefCntPtr<T>> {
285 using SimpleType = T *;
286
287 static SimpleType getSimplifiedValue(IntrusiveRefCntPtr<T> &Val) {
288 return Val.get();
289 }
290};
291
292template <class T> struct simplify_type<const IntrusiveRefCntPtr<T>> {
293 using SimpleType = /*const*/ T *;
294
295 static SimpleType getSimplifiedValue(const IntrusiveRefCntPtr<T> &Val) {
296 return Val.get();
297 }
298};
299
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200300/// Factory function for creating intrusive ref counted pointers.
301template <typename T, typename... Args>
302IntrusiveRefCntPtr<T> makeIntrusiveRefCnt(Args &&...A) {
303 return IntrusiveRefCntPtr<T>(new T(std::forward<Args>(A)...));
304}
305
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100306} // end namespace llvm
307
308#endif // LLVM_ADT_INTRUSIVEREFCNTPTR_H