Bug Summary

File:llvm/include/llvm/ADT/IntrusiveRefCntPtr.h
Warning:line 186, column 38
Potential leak of memory pointed to by field 'Obj'

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name QueryParser.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm/tools/clang/stage2-bins -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/tools/extra/clang-query -I /build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/clang-tools-extra/clang-query -I /build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-01-19-134126-35450-1 -x c++ /build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/clang-tools-extra/clang-query/QueryParser.cpp

/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/clang-tools-extra/clang-query/QueryParser.cpp

1//===---- QueryParser.cpp - clang-query command parser --------------------===//
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#include "QueryParser.h"
10#include "Query.h"
11#include "QuerySession.h"
12#include "clang/ASTMatchers/Dynamic/Parser.h"
13#include "clang/Basic/CharInfo.h"
14#include "clang/Tooling/NodeIntrospection.h"
15#include "llvm/ADT/StringRef.h"
16#include "llvm/ADT/StringSwitch.h"
17#include <set>
18
19using namespace llvm;
20using namespace clang::ast_matchers::dynamic;
21
22namespace clang {
23namespace query {
24
25// Lex any amount of whitespace followed by a "word" (any sequence of
26// non-whitespace characters) from the start of region [Begin,End). If no word
27// is found before End, return StringRef(). Begin is adjusted to exclude the
28// lexed region.
29StringRef QueryParser::lexWord() {
30 Line = Line.drop_while([](char c) {
31 // Don't trim newlines.
32 return StringRef(" \t\v\f\r").contains(c);
33 });
34
35 if (Line.empty())
36 // Even though the Line is empty, it contains a pointer and
37 // a (zero) length. The pointer is used in the LexOrCompleteWord
38 // code completion.
39 return Line;
40
41 StringRef Word;
42 if (Line.front() == '#')
43 Word = Line.substr(0, 1);
44 else
45 Word = Line.take_until(isWhitespace);
46
47 Line = Line.drop_front(Word.size());
48 return Word;
49}
50
51// This is the StringSwitch-alike used by lexOrCompleteWord below. See that
52// function for details.
53template <typename T> struct QueryParser::LexOrCompleteWord {
54 StringRef Word;
55 StringSwitch<T> Switch;
56
57 QueryParser *P;
58 // Set to the completion point offset in Word, or StringRef::npos if
59 // completion point not in Word.
60 size_t WordCompletionPos;
61
62 // Lexes a word and stores it in Word. Returns a LexOrCompleteWord<T> object
63 // that can be used like a llvm::StringSwitch<T>, but adds cases as possible
64 // completions if the lexed word contains the completion point.
65 LexOrCompleteWord(QueryParser *P, StringRef &OutWord)
66 : Word(P->lexWord()), Switch(Word), P(P),
67 WordCompletionPos(StringRef::npos) {
68 OutWord = Word;
69 if (P->CompletionPos && P->CompletionPos <= Word.data() + Word.size()) {
70 if (P->CompletionPos < Word.data())
71 WordCompletionPos = 0;
72 else
73 WordCompletionPos = P->CompletionPos - Word.data();
74 }
75 }
76
77 LexOrCompleteWord &Case(llvm::StringLiteral CaseStr, const T &Value,
78 bool IsCompletion = true) {
79
80 if (WordCompletionPos == StringRef::npos)
81 Switch.Case(CaseStr, Value);
82 else if (CaseStr.size() != 0 && IsCompletion && WordCompletionPos <= CaseStr.size() &&
83 CaseStr.substr(0, WordCompletionPos) ==
84 Word.substr(0, WordCompletionPos))
85 P->Completions.push_back(LineEditor::Completion(
86 (CaseStr.substr(WordCompletionPos) + " ").str(),
87 std::string(CaseStr)));
88 return *this;
89 }
90
91 T Default(T Value) { return Switch.Default(Value); }
92};
93
94QueryRef QueryParser::parseSetBool(bool QuerySession::*Var) {
95 StringRef ValStr;
96 unsigned Value = LexOrCompleteWord<unsigned>(this, ValStr)
97 .Case("false", 0)
98 .Case("true", 1)
99 .Default(~0u);
100 if (Value == ~0u) {
101 return new InvalidQuery("expected 'true' or 'false', got '" + ValStr + "'");
102 }
103 return new SetQuery<bool>(Var, Value);
104}
105
106template <typename QueryType> QueryRef QueryParser::parseSetOutputKind() {
107 StringRef ValStr;
108 bool HasIntrospection = tooling::NodeIntrospection::hasIntrospectionSupport();
109 unsigned OutKind =
110 LexOrCompleteWord<unsigned>(this, ValStr)
111 .Case("diag", OK_Diag)
112 .Case("print", OK_Print)
113 .Case("detailed-ast", OK_DetailedAST)
114 .Case("srcloc", OK_SrcLoc, /*IsCompletion=*/HasIntrospection)
115 .Case("dump", OK_DetailedAST)
116 .Default(~0u);
117 if (OutKind == ~0u) {
118 return new InvalidQuery("expected 'diag', 'print', 'detailed-ast'" +
119 StringRef(HasIntrospection ? ", 'srcloc'" : "") +
120 " or 'dump', got '" + ValStr + "'");
121 }
122
123 switch (OutKind) {
124 case OK_DetailedAST:
125 return new QueryType(&QuerySession::DetailedASTOutput);
126 case OK_Diag:
127 return new QueryType(&QuerySession::DiagOutput);
128 case OK_Print:
129 return new QueryType(&QuerySession::PrintOutput);
130 case OK_SrcLoc:
131 if (HasIntrospection)
132 return new QueryType(&QuerySession::SrcLocOutput);
133 return new InvalidQuery("'srcloc' output support is not available.");
134 }
135
136 llvm_unreachable("Invalid output kind")::llvm::llvm_unreachable_internal("Invalid output kind", "clang-tools-extra/clang-query/QueryParser.cpp"
, 136)
;
137}
138
139QueryRef QueryParser::parseSetTraversalKind(TraversalKind QuerySession::*Var) {
140 StringRef ValStr;
141 unsigned Value =
142 LexOrCompleteWord<unsigned>(this, ValStr)
143 .Case("AsIs", TK_AsIs)
144 .Case("IgnoreUnlessSpelledInSource", TK_IgnoreUnlessSpelledInSource)
145 .Default(~0u);
146 if (Value == ~0u) {
147 return new InvalidQuery("expected traversal kind, got '" + ValStr + "'");
148 }
149 return new SetQuery<TraversalKind>(Var, static_cast<TraversalKind>(Value));
150}
151
152QueryRef QueryParser::endQuery(QueryRef Q) {
153 StringRef Extra = Line;
154 StringRef ExtraTrimmed = Extra.drop_while(
155 [](char c) { return StringRef(" \t\v\f\r").contains(c); });
156
157 if ((!ExtraTrimmed.empty() && ExtraTrimmed[0] == '\n') ||
158 (ExtraTrimmed.size() >= 2 && ExtraTrimmed[0] == '\r' &&
159 ExtraTrimmed[1] == '\n'))
160 Q->RemainingContent = Extra;
161 else {
162 StringRef TrailingWord = lexWord();
163 if (!TrailingWord.empty() && TrailingWord.front() == '#') {
164 Line = Line.drop_until([](char c) { return c == '\n'; });
165 Line = Line.drop_while([](char c) { return c == '\n'; });
166 return endQuery(Q);
167 }
168 if (!TrailingWord.empty()) {
169 return new InvalidQuery("unexpected extra input: '" + Extra + "'");
170 }
171 }
172 return Q;
173}
174
175namespace {
176
177enum ParsedQueryKind {
178 PQK_Invalid,
179 PQK_Comment,
180 PQK_NoOp,
181 PQK_Help,
182 PQK_Let,
183 PQK_Match,
184 PQK_Set,
185 PQK_Unlet,
186 PQK_Quit,
187 PQK_Enable,
188 PQK_Disable
189};
190
191enum ParsedQueryVariable {
192 PQV_Invalid,
193 PQV_Output,
194 PQV_BindRoot,
195 PQV_PrintMatcher,
196 PQV_Traversal
197};
198
199QueryRef makeInvalidQueryFromDiagnostics(const Diagnostics &Diag) {
200 std::string ErrStr;
201 llvm::raw_string_ostream OS(ErrStr);
202 Diag.printToStreamFull(OS);
203 return new InvalidQuery(OS.str());
204}
205
206} // namespace
207
208QueryRef QueryParser::completeMatcherExpression() {
209 std::vector<MatcherCompletion> Comps = Parser::completeExpression(
210 Line, CompletionPos - Line.begin(), nullptr, &QS.NamedValues);
211 for (auto I = Comps.begin(), E = Comps.end(); I != E; ++I) {
212 Completions.push_back(LineEditor::Completion(I->TypedText, I->MatcherDecl));
213 }
214 return QueryRef();
215}
216
217QueryRef QueryParser::doParse() {
218 StringRef CommandStr;
219 ParsedQueryKind QKind = LexOrCompleteWord<ParsedQueryKind>(this, CommandStr)
220 .Case("", PQK_NoOp)
221 .Case("#", PQK_Comment, /*IsCompletion=*/false)
222 .Case("help", PQK_Help)
223 .Case("l", PQK_Let, /*IsCompletion=*/false)
224 .Case("let", PQK_Let)
225 .Case("m", PQK_Match, /*IsCompletion=*/false)
226 .Case("match", PQK_Match)
227 .Case("q", PQK_Quit, /*IsCompletion=*/false)
228 .Case("quit", PQK_Quit)
229 .Case("set", PQK_Set)
230 .Case("enable", PQK_Enable)
231 .Case("disable", PQK_Disable)
232 .Case("unlet", PQK_Unlet)
233 .Default(PQK_Invalid);
234
235 switch (QKind) {
2
Control jumps to 'case PQK_Invalid:' at line 356
236 case PQK_Comment:
237 case PQK_NoOp:
238 Line = Line.drop_until([](char c) { return c == '\n'; });
239 Line = Line.drop_while([](char c) { return c == '\n'; });
240 if (Line.empty())
241 return new NoOpQuery;
242 return doParse();
243
244 case PQK_Help:
245 return endQuery(new HelpQuery);
246
247 case PQK_Quit:
248 return endQuery(new QuitQuery);
249
250 case PQK_Let: {
251 StringRef Name = lexWord();
252
253 if (Name.empty())
254 return new InvalidQuery("expected variable name");
255
256 if (CompletionPos)
257 return completeMatcherExpression();
258
259 Diagnostics Diag;
260 ast_matchers::dynamic::VariantValue Value;
261 if (!Parser::parseExpression(Line, nullptr, &QS.NamedValues, &Value,
262 &Diag)) {
263 return makeInvalidQueryFromDiagnostics(Diag);
264 }
265
266 auto *Q = new LetQuery(Name, Value);
267 Q->RemainingContent = Line;
268 return Q;
269 }
270
271 case PQK_Match: {
272 if (CompletionPos)
273 return completeMatcherExpression();
274
275 Diagnostics Diag;
276 auto MatcherSource = Line.ltrim();
277 auto OrigMatcherSource = MatcherSource;
278 Optional<DynTypedMatcher> Matcher = Parser::parseMatcherExpression(
279 MatcherSource, nullptr, &QS.NamedValues, &Diag);
280 if (!Matcher) {
281 return makeInvalidQueryFromDiagnostics(Diag);
282 }
283 auto ActualSource = OrigMatcherSource.slice(0, OrigMatcherSource.size() -
284 MatcherSource.size());
285 auto *Q = new MatchQuery(ActualSource, *Matcher);
286 Q->RemainingContent = MatcherSource;
287 return Q;
288 }
289
290 case PQK_Set: {
291 StringRef VarStr;
292 ParsedQueryVariable Var =
293 LexOrCompleteWord<ParsedQueryVariable>(this, VarStr)
294 .Case("output", PQV_Output)
295 .Case("bind-root", PQV_BindRoot)
296 .Case("print-matcher", PQV_PrintMatcher)
297 .Case("traversal", PQV_Traversal)
298 .Default(PQV_Invalid);
299 if (VarStr.empty())
300 return new InvalidQuery("expected variable name");
301 if (Var == PQV_Invalid)
302 return new InvalidQuery("unknown variable: '" + VarStr + "'");
303
304 QueryRef Q;
305 switch (Var) {
306 case PQV_Output:
307 Q = parseSetOutputKind<SetExclusiveOutputQuery>();
308 break;
309 case PQV_BindRoot:
310 Q = parseSetBool(&QuerySession::BindRoot);
311 break;
312 case PQV_PrintMatcher:
313 Q = parseSetBool(&QuerySession::PrintMatcher);
314 break;
315 case PQV_Traversal:
316 Q = parseSetTraversalKind(&QuerySession::TK);
317 break;
318 case PQV_Invalid:
319 llvm_unreachable("Invalid query kind")::llvm::llvm_unreachable_internal("Invalid query kind", "clang-tools-extra/clang-query/QueryParser.cpp"
, 319)
;
320 }
321
322 return endQuery(Q);
323 }
324 case PQK_Enable:
325 case PQK_Disable: {
326 StringRef VarStr;
327 ParsedQueryVariable Var =
328 LexOrCompleteWord<ParsedQueryVariable>(this, VarStr)
329 .Case("output", PQV_Output)
330 .Default(PQV_Invalid);
331 if (VarStr.empty())
332 return new InvalidQuery("expected variable name");
333 if (Var == PQV_Invalid)
334 return new InvalidQuery("unknown variable: '" + VarStr + "'");
335
336 QueryRef Q;
337
338 if (QKind == PQK_Enable)
339 Q = parseSetOutputKind<EnableOutputQuery>();
340 else if (QKind == PQK_Disable)
341 Q = parseSetOutputKind<DisableOutputQuery>();
342 else
343 llvm_unreachable("Invalid query kind")::llvm::llvm_unreachable_internal("Invalid query kind", "clang-tools-extra/clang-query/QueryParser.cpp"
, 343)
;
344 return endQuery(Q);
345 }
346
347 case PQK_Unlet: {
348 StringRef Name = lexWord();
349
350 if (Name.empty())
351 return new InvalidQuery("expected variable name");
352
353 return endQuery(new LetQuery(Name, VariantValue()));
354 }
355
356 case PQK_Invalid:
357 return new InvalidQuery("unknown command: " + CommandStr);
3
Memory is allocated
358 }
359
360 llvm_unreachable("Invalid query kind")::llvm::llvm_unreachable_internal("Invalid query kind", "clang-tools-extra/clang-query/QueryParser.cpp"
, 360)
;
361}
362
363QueryRef QueryParser::parse(StringRef Line, const QuerySession &QS) {
364 return QueryParser(Line, QS).doParse();
365}
366
367std::vector<LineEditor::Completion>
368QueryParser::complete(StringRef Line, size_t Pos, const QuerySession &QS) {
369 QueryParser P(Line, QS);
370 P.CompletionPos = Line.data() + Pos;
371
372 P.doParse();
1
Calling 'QueryParser::doParse'
4
Returned allocated memory
5
Calling '~IntrusiveRefCntPtr'
373 return P.Completions;
374}
375
376} // namespace query
377} // namespace clang

/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/llvm/include/llvm/ADT/IntrusiveRefCntPtr.h

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
55#ifndef LLVM_ADT_INTRUSIVEREFCNTPTR_H
56#define LLVM_ADT_INTRUSIVEREFCNTPTR_H
57
58#include <atomic>
59#include <cassert>
60#include <cstddef>
61#include <memory>
62
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
74protected:
75 RefCountedBase() = default;
76 RefCountedBase(const RefCountedBase &) {}
77 RefCountedBase &operator=(const RefCountedBase &) = delete;
78
79#ifndef NDEBUG
80 ~RefCountedBase() {
81 assert(RefCount == 0 &&(static_cast <bool> (RefCount == 0 && "Destruction occured when there are still references to this."
) ? void (0) : __assert_fail ("RefCount == 0 && \"Destruction occured when there are still references to this.\""
, "llvm/include/llvm/ADT/IntrusiveRefCntPtr.h", 82, __extension__
__PRETTY_FUNCTION__))
82 "Destruction occured when there are still references to this.")(static_cast <bool> (RefCount == 0 && "Destruction occured when there are still references to this."
) ? void (0) : __assert_fail ("RefCount == 0 && \"Destruction occured when there are still references to this.\""
, "llvm/include/llvm/ADT/IntrusiveRefCntPtr.h", 82, __extension__
__PRETTY_FUNCTION__))
;
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:
91 void Retain() const { ++RefCount; }
92
93 void Release() const {
94 assert(RefCount > 0 && "Reference count is already zero.")(static_cast <bool> (RefCount > 0 && "Reference count is already zero."
) ? void (0) : __assert_fail ("RefCount > 0 && \"Reference count is already zero.\""
, "llvm/include/llvm/ADT/IntrusiveRefCntPtr.h", 94, __extension__
__PRETTY_FUNCTION__))
;
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 {
102 mutable std::atomic<int> RefCount{0};
103
104protected:
105 ThreadSafeRefCountedBase() = default;
106 ThreadSafeRefCountedBase(const ThreadSafeRefCountedBase &) {}
107 ThreadSafeRefCountedBase &
108 operator=(const ThreadSafeRefCountedBase &) = delete;
109
110#ifndef NDEBUG
111 ~ThreadSafeRefCountedBase() {
112 assert(RefCount == 0 &&(static_cast <bool> (RefCount == 0 && "Destruction occured when there are still references to this."
) ? void (0) : __assert_fail ("RefCount == 0 && \"Destruction occured when there are still references to this.\""
, "llvm/include/llvm/ADT/IntrusiveRefCntPtr.h", 113, __extension__
__PRETTY_FUNCTION__))
113 "Destruction occured when there are still references to this.")(static_cast <bool> (RefCount == 0 && "Destruction occured when there are still references to this."
) ? void (0) : __assert_fail ("RefCount == 0 && \"Destruction occured when there are still references to this.\""
, "llvm/include/llvm/ADT/IntrusiveRefCntPtr.h", 113, __extension__
__PRETTY_FUNCTION__))
;
114 }
115#else
116 // Default the destructor in release builds, A trivial destructor may enable
117 // better codegen.
118 ~ThreadSafeRefCountedBase() = default;
119#endif
120
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.")(static_cast <bool> (NewRefCount >= 0 && "Reference count was already zero."
) ? void (0) : __assert_fail ("NewRefCount >= 0 && \"Reference count was already zero.\""
, "llvm/include/llvm/ADT/IntrusiveRefCntPtr.h", 126, __extension__
__PRETTY_FUNCTION__))
;
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 std::enable_if_t<std::is_convertible<X *, T *>::value, bool> = true>
176 IntrusiveRefCntPtr(IntrusiveRefCntPtr<X> S) : Obj(S.get()) {
177 S.Obj = nullptr;
178 }
179
180 template <class X,
181 std::enable_if_t<std::is_convertible<X *, T *>::value, bool> = true>
182 IntrusiveRefCntPtr(std::unique_ptr<X> S) : Obj(S.release()) {
183 retain();
184 }
185
186 ~IntrusiveRefCntPtr() { release(); }
6
Potential leak of memory pointed to by field 'Obj'
187
188 IntrusiveRefCntPtr &operator=(IntrusiveRefCntPtr S) {
189 swap(S);
190 return *this;
191 }
192
193 T &operator*() const { return *Obj; }
194 T *operator->() const { return Obj; }
195 T *get() const { return Obj; }
196 explicit operator bool() const { return Obj; }
197
198 void swap(IntrusiveRefCntPtr &other) {
199 T *tmp = other.Obj;
200 other.Obj = Obj;
201 Obj = tmp;
202 }
203
204 void reset() {
205 release();
206 Obj = nullptr;
207 }
208
209 void resetWithoutRelease() { Obj = nullptr; }
210
211private:
212 void retain() {
213 if (Obj)
214 IntrusiveRefCntPtrInfo<T>::retain(Obj);
215 }
216
217 void release() {
218 if (Obj)
219 IntrusiveRefCntPtrInfo<T>::release(Obj);
220 }
221
222 template <typename X> friend class IntrusiveRefCntPtr;
223};
224
225template <class T, class U>
226inline bool operator==(const IntrusiveRefCntPtr<T> &A,
227 const IntrusiveRefCntPtr<U> &B) {
228 return A.get() == B.get();
229}
230
231template <class T, class U>
232inline bool operator!=(const IntrusiveRefCntPtr<T> &A,
233 const IntrusiveRefCntPtr<U> &B) {
234 return A.get() != B.get();
235}
236
237template <class T, class U>
238inline bool operator==(const IntrusiveRefCntPtr<T> &A, U *B) {
239 return A.get() == B;
240}
241
242template <class T, class U>
243inline bool operator!=(const IntrusiveRefCntPtr<T> &A, U *B) {
244 return A.get() != B;
245}
246
247template <class T, class U>
248inline bool operator==(T *A, const IntrusiveRefCntPtr<U> &B) {
249 return A == B.get();
250}
251
252template <class T, class U>
253inline bool operator!=(T *A, const IntrusiveRefCntPtr<U> &B) {
254 return A != B.get();
255}
256
257template <class T>
258bool operator==(std::nullptr_t, const IntrusiveRefCntPtr<T> &B) {
259 return !B;
260}
261
262template <class T>
263bool operator==(const IntrusiveRefCntPtr<T> &A, std::nullptr_t B) {
264 return B == A;
265}
266
267template <class T>
268bool operator!=(std::nullptr_t A, const IntrusiveRefCntPtr<T> &B) {
269 return !(A == B);
270}
271
272template <class T>
273bool operator!=(const IntrusiveRefCntPtr<T> &A, std::nullptr_t B) {
274 return !(A == B);
275}
276
277// Make IntrusiveRefCntPtr work with dyn_cast, isa, and the other idioms from
278// Casting.h.
279template <typename From> struct simplify_type;
280
281template <class T> struct simplify_type<IntrusiveRefCntPtr<T>> {
282 using SimpleType = T *;
283
284 static SimpleType getSimplifiedValue(IntrusiveRefCntPtr<T> &Val) {
285 return Val.get();
286 }
287};
288
289template <class T> struct simplify_type<const IntrusiveRefCntPtr<T>> {
290 using SimpleType = /*const*/ T *;
291
292 static SimpleType getSimplifiedValue(const IntrusiveRefCntPtr<T> &Val) {
293 return Val.get();
294 }
295};
296
297/// Factory function for creating intrusive ref counted pointers.
298template <typename T, typename... Args>
299IntrusiveRefCntPtr<T> makeIntrusiveRefCnt(Args &&...A) {
300 return IntrusiveRefCntPtr<T>(new T(std::forward<Args>(A)...));
301}
302
303} // end namespace llvm
304
305#endif // LLVM_ADT_INTRUSIVEREFCNTPTR_H