Debian Codegraph @

llvm-project/llvm/projects/llvm-spirv/lib/SPIRV/Mangler/Refcount.h

raw
1 //===--------------------------- Refcount.h ------------------------------===//
2 //
3 // SPIR Tools
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===---------------------------------------------------------------------===//
9 /*
10 * Contributed by: Intel Corporation
11 */
12
13 #ifndef SPIRV_MANGLER_REFCOUNT_H
14 #define SPIRV_MANGLER_REFCOUNT_H
15
16 #include <assert.h>
17
18 namespace SPIR {
19
20 template <typename T> class RefCount {
21 public:
22 RefCount() : Count(0), Ptr(0) {}
23
24 RefCount(T *Ptr) : Ptr(Ptr) { Count = new int(1); }
25
26 RefCount(const RefCount<T> &Other) { cpy(Other); }
27
28 ~RefCount() {
29 if (Count)
30 dispose();
31 }
32
33 RefCount &operator=(const RefCount<T> &Other) {
34 if (this == &Other)
35 return *this;
36 if (Count)
37 dispose();
38 cpy(Other);
39 return *this;
40 }
41
42 void init(T *Ptr) {
43 assert(!Ptr && "overrunning non NULL pointer");
44 assert(!Count && "overrunning non NULL pointer");
45 Count = new int(1);
46 this->Ptr = Ptr;
47 }
48
49 bool isNull() const { return (!Ptr); }
50
51 // Pointer access
52 const T &operator*() const {
53 sanity();
54 return *Ptr;
55 }
56
57 T &operator*() {
58 sanity();
59 return *Ptr;
60 }
61
62 operator T *() { return Ptr; }
63
64 operator const T *() const { return Ptr; }
65
66 T *operator->() { return Ptr; }
67
68 const T *operator->() const { return Ptr; }
69
70 private:
71 void sanity() const {
72 assert(Ptr && "NULL pointer");
73 assert(Count && "NULL ref counter");
74 assert(*Count && "zero ref counter");
75 }
76
77 void cpy(const RefCount<T> &Other) {
78 Count = Other.Count;
79 Ptr = Other.Ptr;
80 if (Count)
81 ++*Count;
82 }
83
84 void dispose() {
85 sanity();
86 if (0 == --*Count) {
87 delete Count;
88 delete Ptr;
89 Ptr = 0;
90 Count = 0;
91 }
92 }
93
94 int *Count;
95 T *Ptr;
96 }; // End RefCount
97
98 } // namespace SPIR
99
100 #endif // SPIRV_MANGLER_REFCOUNT_H