Bug Summary

File:clang/lib/StaticAnalyzer/Core/MemRegion.cpp
Warning:line 931, column 36
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name MemRegion.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 -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/build-llvm/tools/clang/lib/StaticAnalyzer/Core -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-12/lib/clang/12.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/build-llvm/tools/clang/lib/StaticAnalyzer/Core -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-09-17-195756-12974-1 -x c++ /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp

/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp

1//===- MemRegion.cpp - Abstract memory regions for static analysis --------===//
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 MemRegion and its subclasses. MemRegion defines a
10// partially-typed abstraction of memory useful for path-sensitive dataflow
11// analyses.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/Attr.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/PrettyPrinter.h"
24#include "clang/AST/RecordLayout.h"
25#include "clang/AST/Type.h"
26#include "clang/Analysis/AnalysisDeclContext.h"
27#include "clang/Analysis/Support/BumpVector.h"
28#include "clang/Basic/IdentifierTable.h"
29#include "clang/Basic/LLVM.h"
30#include "clang/Basic/SourceManager.h"
31#include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
32#include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
33#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
34#include "llvm/ADT/APInt.h"
35#include "llvm/ADT/FoldingSet.h"
36#include "llvm/ADT/Optional.h"
37#include "llvm/ADT/PointerUnion.h"
38#include "llvm/ADT/SmallString.h"
39#include "llvm/ADT/StringRef.h"
40#include "llvm/ADT/Twine.h"
41#include "llvm/Support/Allocator.h"
42#include "llvm/Support/Casting.h"
43#include "llvm/Support/CheckedArithmetic.h"
44#include "llvm/Support/Compiler.h"
45#include "llvm/Support/Debug.h"
46#include "llvm/Support/ErrorHandling.h"
47#include "llvm/Support/raw_ostream.h"
48#include <cassert>
49#include <cstdint>
50#include <functional>
51#include <iterator>
52#include <string>
53#include <tuple>
54#include <utility>
55
56using namespace clang;
57using namespace ento;
58
59#define DEBUG_TYPE"MemRegion" "MemRegion"
60
61//===----------------------------------------------------------------------===//
62// MemRegion Construction.
63//===----------------------------------------------------------------------===//
64
65template <typename RegionTy, typename SuperTy, typename Arg1Ty>
66RegionTy* MemRegionManager::getSubRegion(const Arg1Ty arg1,
67 const SuperTy *superRegion) {
68 llvm::FoldingSetNodeID ID;
69 RegionTy::ProfileRegion(ID, arg1, superRegion);
70 void *InsertPos;
71 auto *R = cast_or_null<RegionTy>(Regions.FindNodeOrInsertPos(ID, InsertPos));
72
73 if (!R) {
74 R = A.Allocate<RegionTy>();
75 new (R) RegionTy(arg1, superRegion);
76 Regions.InsertNode(R, InsertPos);
77 }
78
79 return R;
80}
81
82template <typename RegionTy, typename SuperTy, typename Arg1Ty, typename Arg2Ty>
83RegionTy* MemRegionManager::getSubRegion(const Arg1Ty arg1, const Arg2Ty arg2,
84 const SuperTy *superRegion) {
85 llvm::FoldingSetNodeID ID;
86 RegionTy::ProfileRegion(ID, arg1, arg2, superRegion);
87 void *InsertPos;
88 auto *R = cast_or_null<RegionTy>(Regions.FindNodeOrInsertPos(ID, InsertPos));
89
90 if (!R) {
91 R = A.Allocate<RegionTy>();
92 new (R) RegionTy(arg1, arg2, superRegion);
93 Regions.InsertNode(R, InsertPos);
94 }
95
96 return R;
97}
98
99template <typename RegionTy, typename SuperTy,
100 typename Arg1Ty, typename Arg2Ty, typename Arg3Ty>
101RegionTy* MemRegionManager::getSubRegion(const Arg1Ty arg1, const Arg2Ty arg2,
102 const Arg3Ty arg3,
103 const SuperTy *superRegion) {
104 llvm::FoldingSetNodeID ID;
105 RegionTy::ProfileRegion(ID, arg1, arg2, arg3, superRegion);
106 void *InsertPos;
107 auto *R = cast_or_null<RegionTy>(Regions.FindNodeOrInsertPos(ID, InsertPos));
108
109 if (!R) {
110 R = A.Allocate<RegionTy>();
111 new (R) RegionTy(arg1, arg2, arg3, superRegion);
112 Regions.InsertNode(R, InsertPos);
113 }
114
115 return R;
116}
117
118//===----------------------------------------------------------------------===//
119// Object destruction.
120//===----------------------------------------------------------------------===//
121
122MemRegion::~MemRegion() = default;
123
124// All regions and their data are BumpPtrAllocated. No need to call their
125// destructors.
126MemRegionManager::~MemRegionManager() = default;
127
128//===----------------------------------------------------------------------===//
129// Basic methods.
130//===----------------------------------------------------------------------===//
131
132bool SubRegion::isSubRegionOf(const MemRegion* R) const {
133 const MemRegion* r = this;
134 do {
135 if (r == R)
136 return true;
137 if (const auto *sr = dyn_cast<SubRegion>(r))
138 r = sr->getSuperRegion();
139 else
140 break;
141 } while (r != nullptr);
142 return false;
143}
144
145MemRegionManager &SubRegion::getMemRegionManager() const {
146 const SubRegion* r = this;
147 do {
148 const MemRegion *superRegion = r->getSuperRegion();
149 if (const auto *sr = dyn_cast<SubRegion>(superRegion)) {
150 r = sr;
151 continue;
152 }
153 return superRegion->getMemRegionManager();
154 } while (true);
155}
156
157const StackFrameContext *VarRegion::getStackFrame() const {
158 const auto *SSR = dyn_cast<StackSpaceRegion>(getMemorySpace());
159 return SSR ? SSR->getStackFrame() : nullptr;
160}
161
162ObjCIvarRegion::ObjCIvarRegion(const ObjCIvarDecl *ivd, const SubRegion *sReg)
163 : DeclRegion(sReg, ObjCIvarRegionKind), IVD(ivd) {}
164
165const ObjCIvarDecl *ObjCIvarRegion::getDecl() const { return IVD; }
166
167QualType ObjCIvarRegion::getValueType() const {
168 return getDecl()->getType();
169}
170
171QualType CXXBaseObjectRegion::getValueType() const {
172 return QualType(getDecl()->getTypeForDecl(), 0);
173}
174
175QualType CXXDerivedObjectRegion::getValueType() const {
176 return QualType(getDecl()->getTypeForDecl(), 0);
177}
178
179QualType ParamVarRegion::getValueType() const {
180 assert(getDecl() &&((getDecl() && "`ParamVarRegion` support functions without `Decl` not implemented"
" yet.") ? static_cast<void> (0) : __assert_fail ("getDecl() && \"`ParamVarRegion` support functions without `Decl` not implemented\" \" yet.\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 182, __PRETTY_FUNCTION__))
181 "`ParamVarRegion` support functions without `Decl` not implemented"((getDecl() && "`ParamVarRegion` support functions without `Decl` not implemented"
" yet.") ? static_cast<void> (0) : __assert_fail ("getDecl() && \"`ParamVarRegion` support functions without `Decl` not implemented\" \" yet.\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 182, __PRETTY_FUNCTION__))
182 " yet.")((getDecl() && "`ParamVarRegion` support functions without `Decl` not implemented"
" yet.") ? static_cast<void> (0) : __assert_fail ("getDecl() && \"`ParamVarRegion` support functions without `Decl` not implemented\" \" yet.\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 182, __PRETTY_FUNCTION__))
;
183 return getDecl()->getType();
184}
185
186const ParmVarDecl *ParamVarRegion::getDecl() const {
187 const Decl *D = getStackFrame()->getDecl();
188
189 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
190 assert(Index < FD->param_size())((Index < FD->param_size()) ? static_cast<void> (
0) : __assert_fail ("Index < FD->param_size()", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 190, __PRETTY_FUNCTION__))
;
191 return FD->parameters()[Index];
192 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
193 assert(Index < BD->param_size())((Index < BD->param_size()) ? static_cast<void> (
0) : __assert_fail ("Index < BD->param_size()", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 193, __PRETTY_FUNCTION__))
;
194 return BD->parameters()[Index];
195 } else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
196 assert(Index < MD->param_size())((Index < MD->param_size()) ? static_cast<void> (
0) : __assert_fail ("Index < MD->param_size()", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 196, __PRETTY_FUNCTION__))
;
197 return MD->parameters()[Index];
198 } else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D)) {
199 assert(Index < CD->param_size())((Index < CD->param_size()) ? static_cast<void> (
0) : __assert_fail ("Index < CD->param_size()", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 199, __PRETTY_FUNCTION__))
;
200 return CD->parameters()[Index];
201 } else {
202 llvm_unreachable("Unexpected Decl kind!")::llvm::llvm_unreachable_internal("Unexpected Decl kind!", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 202)
;
203 }
204}
205
206//===----------------------------------------------------------------------===//
207// FoldingSet profiling.
208//===----------------------------------------------------------------------===//
209
210void MemSpaceRegion::Profile(llvm::FoldingSetNodeID &ID) const {
211 ID.AddInteger(static_cast<unsigned>(getKind()));
212}
213
214void StackSpaceRegion::Profile(llvm::FoldingSetNodeID &ID) const {
215 ID.AddInteger(static_cast<unsigned>(getKind()));
216 ID.AddPointer(getStackFrame());
217}
218
219void StaticGlobalSpaceRegion::Profile(llvm::FoldingSetNodeID &ID) const {
220 ID.AddInteger(static_cast<unsigned>(getKind()));
221 ID.AddPointer(getCodeRegion());
222}
223
224void StringRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
225 const StringLiteral *Str,
226 const MemRegion *superRegion) {
227 ID.AddInteger(static_cast<unsigned>(StringRegionKind));
228 ID.AddPointer(Str);
229 ID.AddPointer(superRegion);
230}
231
232void ObjCStringRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
233 const ObjCStringLiteral *Str,
234 const MemRegion *superRegion) {
235 ID.AddInteger(static_cast<unsigned>(ObjCStringRegionKind));
236 ID.AddPointer(Str);
237 ID.AddPointer(superRegion);
238}
239
240void AllocaRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
241 const Expr *Ex, unsigned cnt,
242 const MemRegion *superRegion) {
243 ID.AddInteger(static_cast<unsigned>(AllocaRegionKind));
244 ID.AddPointer(Ex);
245 ID.AddInteger(cnt);
246 ID.AddPointer(superRegion);
247}
248
249void AllocaRegion::Profile(llvm::FoldingSetNodeID& ID) const {
250 ProfileRegion(ID, Ex, Cnt, superRegion);
251}
252
253void CompoundLiteralRegion::Profile(llvm::FoldingSetNodeID& ID) const {
254 CompoundLiteralRegion::ProfileRegion(ID, CL, superRegion);
255}
256
257void CompoundLiteralRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
258 const CompoundLiteralExpr *CL,
259 const MemRegion* superRegion) {
260 ID.AddInteger(static_cast<unsigned>(CompoundLiteralRegionKind));
261 ID.AddPointer(CL);
262 ID.AddPointer(superRegion);
263}
264
265void CXXThisRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
266 const PointerType *PT,
267 const MemRegion *sRegion) {
268 ID.AddInteger(static_cast<unsigned>(CXXThisRegionKind));
269 ID.AddPointer(PT);
270 ID.AddPointer(sRegion);
271}
272
273void CXXThisRegion::Profile(llvm::FoldingSetNodeID &ID) const {
274 CXXThisRegion::ProfileRegion(ID, ThisPointerTy, superRegion);
275}
276
277void FieldRegion::Profile(llvm::FoldingSetNodeID &ID) const {
278 ProfileRegion(ID, getDecl(), superRegion);
279}
280
281void ObjCIvarRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
282 const ObjCIvarDecl *ivd,
283 const MemRegion* superRegion) {
284 ID.AddInteger(static_cast<unsigned>(ObjCIvarRegionKind));
285 ID.AddPointer(ivd);
286 ID.AddPointer(superRegion);
287}
288
289void ObjCIvarRegion::Profile(llvm::FoldingSetNodeID &ID) const {
290 ProfileRegion(ID, getDecl(), superRegion);
291}
292
293void NonParamVarRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
294 const VarDecl *VD,
295 const MemRegion *superRegion) {
296 ID.AddInteger(static_cast<unsigned>(NonParamVarRegionKind));
297 ID.AddPointer(VD);
298 ID.AddPointer(superRegion);
299}
300
301void NonParamVarRegion::Profile(llvm::FoldingSetNodeID &ID) const {
302 ProfileRegion(ID, getDecl(), superRegion);
303}
304
305void ParamVarRegion::ProfileRegion(llvm::FoldingSetNodeID &ID, const Expr *OE,
306 unsigned Idx, const MemRegion *SReg) {
307 ID.AddInteger(static_cast<unsigned>(ParamVarRegionKind));
308 ID.AddPointer(OE);
309 ID.AddInteger(Idx);
310 ID.AddPointer(SReg);
311}
312
313void ParamVarRegion::Profile(llvm::FoldingSetNodeID &ID) const {
314 ProfileRegion(ID, getOriginExpr(), getIndex(), superRegion);
315}
316
317void SymbolicRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, SymbolRef sym,
318 const MemRegion *sreg) {
319 ID.AddInteger(static_cast<unsigned>(MemRegion::SymbolicRegionKind));
320 ID.Add(sym);
321 ID.AddPointer(sreg);
322}
323
324void SymbolicRegion::Profile(llvm::FoldingSetNodeID& ID) const {
325 SymbolicRegion::ProfileRegion(ID, sym, getSuperRegion());
326}
327
328void ElementRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
329 QualType ElementType, SVal Idx,
330 const MemRegion* superRegion) {
331 ID.AddInteger(MemRegion::ElementRegionKind);
332 ID.Add(ElementType);
333 ID.AddPointer(superRegion);
334 Idx.Profile(ID);
335}
336
337void ElementRegion::Profile(llvm::FoldingSetNodeID& ID) const {
338 ElementRegion::ProfileRegion(ID, ElementType, Index, superRegion);
339}
340
341void FunctionCodeRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
342 const NamedDecl *FD,
343 const MemRegion*) {
344 ID.AddInteger(MemRegion::FunctionCodeRegionKind);
345 ID.AddPointer(FD);
346}
347
348void FunctionCodeRegion::Profile(llvm::FoldingSetNodeID& ID) const {
349 FunctionCodeRegion::ProfileRegion(ID, FD, superRegion);
350}
351
352void BlockCodeRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
353 const BlockDecl *BD, CanQualType,
354 const AnalysisDeclContext *AC,
355 const MemRegion*) {
356 ID.AddInteger(MemRegion::BlockCodeRegionKind);
357 ID.AddPointer(BD);
358}
359
360void BlockCodeRegion::Profile(llvm::FoldingSetNodeID& ID) const {
361 BlockCodeRegion::ProfileRegion(ID, BD, locTy, AC, superRegion);
362}
363
364void BlockDataRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
365 const BlockCodeRegion *BC,
366 const LocationContext *LC,
367 unsigned BlkCount,
368 const MemRegion *sReg) {
369 ID.AddInteger(MemRegion::BlockDataRegionKind);
370 ID.AddPointer(BC);
371 ID.AddPointer(LC);
372 ID.AddInteger(BlkCount);
373 ID.AddPointer(sReg);
374}
375
376void BlockDataRegion::Profile(llvm::FoldingSetNodeID& ID) const {
377 BlockDataRegion::ProfileRegion(ID, BC, LC, BlockCount, getSuperRegion());
378}
379
380void CXXTempObjectRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
381 Expr const *Ex,
382 const MemRegion *sReg) {
383 ID.AddPointer(Ex);
384 ID.AddPointer(sReg);
385}
386
387void CXXTempObjectRegion::Profile(llvm::FoldingSetNodeID &ID) const {
388 ProfileRegion(ID, Ex, getSuperRegion());
389}
390
391void CXXBaseObjectRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
392 const CXXRecordDecl *RD,
393 bool IsVirtual,
394 const MemRegion *SReg) {
395 ID.AddPointer(RD);
396 ID.AddBoolean(IsVirtual);
397 ID.AddPointer(SReg);
398}
399
400void CXXBaseObjectRegion::Profile(llvm::FoldingSetNodeID &ID) const {
401 ProfileRegion(ID, getDecl(), isVirtual(), superRegion);
402}
403
404void CXXDerivedObjectRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
405 const CXXRecordDecl *RD,
406 const MemRegion *SReg) {
407 ID.AddPointer(RD);
408 ID.AddPointer(SReg);
409}
410
411void CXXDerivedObjectRegion::Profile(llvm::FoldingSetNodeID &ID) const {
412 ProfileRegion(ID, getDecl(), superRegion);
413}
414
415//===----------------------------------------------------------------------===//
416// Region anchors.
417//===----------------------------------------------------------------------===//
418
419void GlobalsSpaceRegion::anchor() {}
420
421void NonStaticGlobalSpaceRegion::anchor() {}
422
423void StackSpaceRegion::anchor() {}
424
425void TypedRegion::anchor() {}
426
427void TypedValueRegion::anchor() {}
428
429void CodeTextRegion::anchor() {}
430
431void SubRegion::anchor() {}
432
433//===----------------------------------------------------------------------===//
434// Region pretty-printing.
435//===----------------------------------------------------------------------===//
436
437LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void MemRegion::dump() const {
438 dumpToStream(llvm::errs());
439}
440
441std::string MemRegion::getString() const {
442 std::string s;
443 llvm::raw_string_ostream os(s);
444 dumpToStream(os);
445 return os.str();
446}
447
448void MemRegion::dumpToStream(raw_ostream &os) const {
449 os << "<Unknown Region>";
450}
451
452void AllocaRegion::dumpToStream(raw_ostream &os) const {
453 os << "alloca{S" << Ex->getID(getContext()) << ',' << Cnt << '}';
454}
455
456void FunctionCodeRegion::dumpToStream(raw_ostream &os) const {
457 os << "code{" << getDecl()->getDeclName().getAsString() << '}';
458}
459
460void BlockCodeRegion::dumpToStream(raw_ostream &os) const {
461 os << "block_code{" << static_cast<const void *>(this) << '}';
462}
463
464void BlockDataRegion::dumpToStream(raw_ostream &os) const {
465 os << "block_data{" << BC;
466 os << "; ";
467 for (BlockDataRegion::referenced_vars_iterator
468 I = referenced_vars_begin(),
469 E = referenced_vars_end(); I != E; ++I)
470 os << "(" << I.getCapturedRegion() << "<-" <<
471 I.getOriginalRegion() << ") ";
472 os << '}';
473}
474
475void CompoundLiteralRegion::dumpToStream(raw_ostream &os) const {
476 // FIXME: More elaborate pretty-printing.
477 os << "{ S" << CL->getID(getContext()) << " }";
478}
479
480void CXXTempObjectRegion::dumpToStream(raw_ostream &os) const {
481 os << "temp_object{" << getValueType().getAsString() << ", "
482 << "S" << Ex->getID(getContext()) << '}';
483}
484
485void CXXBaseObjectRegion::dumpToStream(raw_ostream &os) const {
486 os << "Base{" << superRegion << ',' << getDecl()->getName() << '}';
487}
488
489void CXXDerivedObjectRegion::dumpToStream(raw_ostream &os) const {
490 os << "Derived{" << superRegion << ',' << getDecl()->getName() << '}';
491}
492
493void CXXThisRegion::dumpToStream(raw_ostream &os) const {
494 os << "this";
495}
496
497void ElementRegion::dumpToStream(raw_ostream &os) const {
498 os << "Element{" << superRegion << ','
499 << Index << ',' << getElementType().getAsString() << '}';
500}
501
502void FieldRegion::dumpToStream(raw_ostream &os) const {
503 os << superRegion << "." << *getDecl();
504}
505
506void ObjCIvarRegion::dumpToStream(raw_ostream &os) const {
507 os << "Ivar{" << superRegion << ',' << *getDecl() << '}';
508}
509
510void StringRegion::dumpToStream(raw_ostream &os) const {
511 assert(Str != nullptr && "Expecting non-null StringLiteral")((Str != nullptr && "Expecting non-null StringLiteral"
) ? static_cast<void> (0) : __assert_fail ("Str != nullptr && \"Expecting non-null StringLiteral\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 511, __PRETTY_FUNCTION__))
;
512 Str->printPretty(os, nullptr, PrintingPolicy(getContext().getLangOpts()));
513}
514
515void ObjCStringRegion::dumpToStream(raw_ostream &os) const {
516 assert(Str != nullptr && "Expecting non-null ObjCStringLiteral")((Str != nullptr && "Expecting non-null ObjCStringLiteral"
) ? static_cast<void> (0) : __assert_fail ("Str != nullptr && \"Expecting non-null ObjCStringLiteral\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 516, __PRETTY_FUNCTION__))
;
517 Str->printPretty(os, nullptr, PrintingPolicy(getContext().getLangOpts()));
518}
519
520void SymbolicRegion::dumpToStream(raw_ostream &os) const {
521 if (isa<HeapSpaceRegion>(getSuperRegion()))
522 os << "Heap";
523 os << "SymRegion{" << sym << '}';
524}
525
526void NonParamVarRegion::dumpToStream(raw_ostream &os) const {
527 if (const IdentifierInfo *ID = VD->getIdentifier())
528 os << ID->getName();
529 else
530 os << "NonParamVarRegion{D" << VD->getID() << '}';
531}
532
533LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void RegionRawOffset::dump() const {
534 dumpToStream(llvm::errs());
535}
536
537void RegionRawOffset::dumpToStream(raw_ostream &os) const {
538 os << "raw_offset{" << getRegion() << ',' << getOffset().getQuantity() << '}';
539}
540
541void CodeSpaceRegion::dumpToStream(raw_ostream &os) const {
542 os << "CodeSpaceRegion";
543}
544
545void StaticGlobalSpaceRegion::dumpToStream(raw_ostream &os) const {
546 os << "StaticGlobalsMemSpace{" << CR << '}';
547}
548
549void GlobalInternalSpaceRegion::dumpToStream(raw_ostream &os) const {
550 os << "GlobalInternalSpaceRegion";
551}
552
553void GlobalSystemSpaceRegion::dumpToStream(raw_ostream &os) const {
554 os << "GlobalSystemSpaceRegion";
555}
556
557void GlobalImmutableSpaceRegion::dumpToStream(raw_ostream &os) const {
558 os << "GlobalImmutableSpaceRegion";
559}
560
561void HeapSpaceRegion::dumpToStream(raw_ostream &os) const {
562 os << "HeapSpaceRegion";
563}
564
565void UnknownSpaceRegion::dumpToStream(raw_ostream &os) const {
566 os << "UnknownSpaceRegion";
567}
568
569void StackArgumentsSpaceRegion::dumpToStream(raw_ostream &os) const {
570 os << "StackArgumentsSpaceRegion";
571}
572
573void StackLocalsSpaceRegion::dumpToStream(raw_ostream &os) const {
574 os << "StackLocalsSpaceRegion";
575}
576
577void ParamVarRegion::dumpToStream(raw_ostream &os) const {
578 const ParmVarDecl *PVD = getDecl();
579 assert(PVD &&((PVD && "`ParamVarRegion` support functions without `Decl` not implemented"
" yet.") ? static_cast<void> (0) : __assert_fail ("PVD && \"`ParamVarRegion` support functions without `Decl` not implemented\" \" yet.\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 581, __PRETTY_FUNCTION__))
580 "`ParamVarRegion` support functions without `Decl` not implemented"((PVD && "`ParamVarRegion` support functions without `Decl` not implemented"
" yet.") ? static_cast<void> (0) : __assert_fail ("PVD && \"`ParamVarRegion` support functions without `Decl` not implemented\" \" yet.\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 581, __PRETTY_FUNCTION__))
581 " yet.")((PVD && "`ParamVarRegion` support functions without `Decl` not implemented"
" yet.") ? static_cast<void> (0) : __assert_fail ("PVD && \"`ParamVarRegion` support functions without `Decl` not implemented\" \" yet.\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 581, __PRETTY_FUNCTION__))
;
582 if (const IdentifierInfo *ID = PVD->getIdentifier()) {
583 os << ID->getName();
584 } else {
585 os << "ParamVarRegion{P" << PVD->getID() << '}';
586 }
587}
588
589bool MemRegion::canPrintPretty() const {
590 return canPrintPrettyAsExpr();
591}
592
593bool MemRegion::canPrintPrettyAsExpr() const {
594 return false;
595}
596
597void MemRegion::printPretty(raw_ostream &os) const {
598 assert(canPrintPretty() && "This region cannot be printed pretty.")((canPrintPretty() && "This region cannot be printed pretty."
) ? static_cast<void> (0) : __assert_fail ("canPrintPretty() && \"This region cannot be printed pretty.\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 598, __PRETTY_FUNCTION__))
;
599 os << "'";
600 printPrettyAsExpr(os);
601 os << "'";
602}
603
604void MemRegion::printPrettyAsExpr(raw_ostream &) const {
605 llvm_unreachable("This region cannot be printed pretty.")::llvm::llvm_unreachable_internal("This region cannot be printed pretty."
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 605)
;
606}
607
608bool NonParamVarRegion::canPrintPrettyAsExpr() const { return true; }
609
610void NonParamVarRegion::printPrettyAsExpr(raw_ostream &os) const {
611 os << getDecl()->getName();
612}
613
614bool ParamVarRegion::canPrintPrettyAsExpr() const { return true; }
615
616void ParamVarRegion::printPrettyAsExpr(raw_ostream &os) const {
617 assert(getDecl() &&((getDecl() && "`ParamVarRegion` support functions without `Decl` not implemented"
" yet.") ? static_cast<void> (0) : __assert_fail ("getDecl() && \"`ParamVarRegion` support functions without `Decl` not implemented\" \" yet.\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 619, __PRETTY_FUNCTION__))
618 "`ParamVarRegion` support functions without `Decl` not implemented"((getDecl() && "`ParamVarRegion` support functions without `Decl` not implemented"
" yet.") ? static_cast<void> (0) : __assert_fail ("getDecl() && \"`ParamVarRegion` support functions without `Decl` not implemented\" \" yet.\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 619, __PRETTY_FUNCTION__))
619 " yet.")((getDecl() && "`ParamVarRegion` support functions without `Decl` not implemented"
" yet.") ? static_cast<void> (0) : __assert_fail ("getDecl() && \"`ParamVarRegion` support functions without `Decl` not implemented\" \" yet.\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 619, __PRETTY_FUNCTION__))
;
620 os << getDecl()->getName();
621}
622
623bool ObjCIvarRegion::canPrintPrettyAsExpr() const {
624 return true;
625}
626
627void ObjCIvarRegion::printPrettyAsExpr(raw_ostream &os) const {
628 os << getDecl()->getName();
629}
630
631bool FieldRegion::canPrintPretty() const {
632 return true;
633}
634
635bool FieldRegion::canPrintPrettyAsExpr() const {
636 return superRegion->canPrintPrettyAsExpr();
637}
638
639void FieldRegion::printPrettyAsExpr(raw_ostream &os) const {
640 assert(canPrintPrettyAsExpr())((canPrintPrettyAsExpr()) ? static_cast<void> (0) : __assert_fail
("canPrintPrettyAsExpr()", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 640, __PRETTY_FUNCTION__))
;
641 superRegion->printPrettyAsExpr(os);
642 os << "." << getDecl()->getName();
643}
644
645void FieldRegion::printPretty(raw_ostream &os) const {
646 if (canPrintPrettyAsExpr()) {
647 os << "\'";
648 printPrettyAsExpr(os);
649 os << "'";
650 } else {
651 os << "field " << "\'" << getDecl()->getName() << "'";
652 }
653}
654
655bool CXXBaseObjectRegion::canPrintPrettyAsExpr() const {
656 return superRegion->canPrintPrettyAsExpr();
657}
658
659void CXXBaseObjectRegion::printPrettyAsExpr(raw_ostream &os) const {
660 superRegion->printPrettyAsExpr(os);
661}
662
663bool CXXDerivedObjectRegion::canPrintPrettyAsExpr() const {
664 return superRegion->canPrintPrettyAsExpr();
665}
666
667void CXXDerivedObjectRegion::printPrettyAsExpr(raw_ostream &os) const {
668 superRegion->printPrettyAsExpr(os);
669}
670
671std::string MemRegion::getDescriptiveName(bool UseQuotes) const {
672 std::string VariableName;
673 std::string ArrayIndices;
674 const MemRegion *R = this;
675 SmallString<50> buf;
676 llvm::raw_svector_ostream os(buf);
677
678 // Obtain array indices to add them to the variable name.
679 const ElementRegion *ER = nullptr;
680 while ((ER = R->getAs<ElementRegion>())) {
681 // Index is a ConcreteInt.
682 if (auto CI = ER->getIndex().getAs<nonloc::ConcreteInt>()) {
683 llvm::SmallString<2> Idx;
684 CI->getValue().toString(Idx);
685 ArrayIndices = (llvm::Twine("[") + Idx.str() + "]" + ArrayIndices).str();
686 }
687 // If not a ConcreteInt, try to obtain the variable
688 // name by calling 'getDescriptiveName' recursively.
689 else {
690 std::string Idx = ER->getDescriptiveName(false);
691 if (!Idx.empty()) {
692 ArrayIndices = (llvm::Twine("[") + Idx + "]" + ArrayIndices).str();
693 }
694 }
695 R = ER->getSuperRegion();
696 }
697
698 // Get variable name.
699 if (R && R->canPrintPrettyAsExpr()) {
700 R->printPrettyAsExpr(os);
701 if (UseQuotes)
702 return (llvm::Twine("'") + os.str() + ArrayIndices + "'").str();
703 else
704 return (llvm::Twine(os.str()) + ArrayIndices).str();
705 }
706
707 return VariableName;
708}
709
710SourceRange MemRegion::sourceRange() const {
711 const auto *const VR = dyn_cast<VarRegion>(this->getBaseRegion());
712 const auto *const FR = dyn_cast<FieldRegion>(this);
713
714 // Check for more specific regions first.
715 // FieldRegion
716 if (FR) {
717 return FR->getDecl()->getSourceRange();
718 }
719 // VarRegion
720 else if (VR) {
721 return VR->getDecl()->getSourceRange();
722 }
723 // Return invalid source range (can be checked by client).
724 else
725 return {};
726}
727
728//===----------------------------------------------------------------------===//
729// MemRegionManager methods.
730//===----------------------------------------------------------------------===//
731
732static DefinedOrUnknownSVal getTypeSize(QualType Ty, ASTContext &Ctx,
733 SValBuilder &SVB) {
734 CharUnits Size = Ctx.getTypeSizeInChars(Ty);
735 QualType SizeTy = SVB.getArrayIndexType();
736 return SVB.makeIntVal(Size.getQuantity(), SizeTy);
737}
738
739DefinedOrUnknownSVal MemRegionManager::getStaticSize(const MemRegion *MR,
740 SValBuilder &SVB) const {
741 const auto *SR = cast<SubRegion>(MR);
742 SymbolManager &SymMgr = SVB.getSymbolManager();
743
744 switch (SR->getKind()) {
745 case MemRegion::AllocaRegionKind:
746 case MemRegion::SymbolicRegionKind:
747 return nonloc::SymbolVal(SymMgr.getExtentSymbol(SR));
748 case MemRegion::StringRegionKind:
749 return SVB.makeIntVal(
750 cast<StringRegion>(SR)->getStringLiteral()->getByteLength() + 1,
751 SVB.getArrayIndexType());
752 case MemRegion::CompoundLiteralRegionKind:
753 case MemRegion::CXXBaseObjectRegionKind:
754 case MemRegion::CXXDerivedObjectRegionKind:
755 case MemRegion::CXXTempObjectRegionKind:
756 case MemRegion::CXXThisRegionKind:
757 case MemRegion::ObjCIvarRegionKind:
758 case MemRegion::NonParamVarRegionKind:
759 case MemRegion::ParamVarRegionKind:
760 case MemRegion::ElementRegionKind:
761 case MemRegion::ObjCStringRegionKind: {
762 QualType Ty = cast<TypedValueRegion>(SR)->getDesugaredValueType(Ctx);
763 if (isa<VariableArrayType>(Ty))
764 return nonloc::SymbolVal(SymMgr.getExtentSymbol(SR));
765
766 if (Ty->isIncompleteType())
767 return UnknownVal();
768
769 return getTypeSize(Ty, Ctx, SVB);
770 }
771 case MemRegion::FieldRegionKind: {
772 // Force callers to deal with bitfields explicitly.
773 if (cast<FieldRegion>(SR)->getDecl()->isBitField())
774 return UnknownVal();
775
776 QualType Ty = cast<TypedValueRegion>(SR)->getDesugaredValueType(Ctx);
777 DefinedOrUnknownSVal Size = getTypeSize(Ty, Ctx, SVB);
778
779 // A zero-length array at the end of a struct often stands for dynamically
780 // allocated extra memory.
781 if (Size.isZeroConstant()) {
782 if (isa<ConstantArrayType>(Ty))
783 return UnknownVal();
784 }
785
786 return Size;
787 }
788 // FIXME: The following are being used in 'SimpleSValBuilder' and in
789 // 'ArrayBoundChecker::checkLocation' because there is no symbol to
790 // represent the regions more appropriately.
791 case MemRegion::BlockDataRegionKind:
792 case MemRegion::BlockCodeRegionKind:
793 case MemRegion::FunctionCodeRegionKind:
794 return nonloc::SymbolVal(SymMgr.getExtentSymbol(SR));
795 default:
796 llvm_unreachable("Unhandled region")::llvm::llvm_unreachable_internal("Unhandled region", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 796)
;
797 }
798}
799
800template <typename REG>
801const REG *MemRegionManager::LazyAllocate(REG*& region) {
802 if (!region) {
803 region = A.Allocate<REG>();
804 new (region) REG(*this);
805 }
806
807 return region;
808}
809
810template <typename REG, typename ARG>
811const REG *MemRegionManager::LazyAllocate(REG*& region, ARG a) {
812 if (!region) {
813 region = A.Allocate<REG>();
814 new (region) REG(this, a);
815 }
816
817 return region;
818}
819
820const StackLocalsSpaceRegion*
821MemRegionManager::getStackLocalsRegion(const StackFrameContext *STC) {
822 assert(STC)((STC) ? static_cast<void> (0) : __assert_fail ("STC", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 822, __PRETTY_FUNCTION__))
;
823 StackLocalsSpaceRegion *&R = StackLocalsSpaceRegions[STC];
824
825 if (R)
826 return R;
827
828 R = A.Allocate<StackLocalsSpaceRegion>();
829 new (R) StackLocalsSpaceRegion(*this, STC);
830 return R;
831}
832
833const StackArgumentsSpaceRegion *
834MemRegionManager::getStackArgumentsRegion(const StackFrameContext *STC) {
835 assert(STC)((STC) ? static_cast<void> (0) : __assert_fail ("STC", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 835, __PRETTY_FUNCTION__))
;
836 StackArgumentsSpaceRegion *&R = StackArgumentsSpaceRegions[STC];
837
838 if (R)
839 return R;
840
841 R = A.Allocate<StackArgumentsSpaceRegion>();
842 new (R) StackArgumentsSpaceRegion(*this, STC);
843 return R;
844}
845
846const GlobalsSpaceRegion
847*MemRegionManager::getGlobalsRegion(MemRegion::Kind K,
848 const CodeTextRegion *CR) {
849 if (!CR) {
850 if (K == MemRegion::GlobalSystemSpaceRegionKind)
851 return LazyAllocate(SystemGlobals);
852 if (K == MemRegion::GlobalImmutableSpaceRegionKind)
853 return LazyAllocate(ImmutableGlobals);
854 assert(K == MemRegion::GlobalInternalSpaceRegionKind)((K == MemRegion::GlobalInternalSpaceRegionKind) ? static_cast
<void> (0) : __assert_fail ("K == MemRegion::GlobalInternalSpaceRegionKind"
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 854, __PRETTY_FUNCTION__))
;
855 return LazyAllocate(InternalGlobals);
856 }
857
858 assert(K == MemRegion::StaticGlobalSpaceRegionKind)((K == MemRegion::StaticGlobalSpaceRegionKind) ? static_cast<
void> (0) : __assert_fail ("K == MemRegion::StaticGlobalSpaceRegionKind"
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 858, __PRETTY_FUNCTION__))
;
859 StaticGlobalSpaceRegion *&R = StaticsGlobalSpaceRegions[CR];
860 if (R)
861 return R;
862
863 R = A.Allocate<StaticGlobalSpaceRegion>();
864 new (R) StaticGlobalSpaceRegion(*this, CR);
865 return R;
866}
867
868const HeapSpaceRegion *MemRegionManager::getHeapRegion() {
869 return LazyAllocate(heap);
870}
871
872const UnknownSpaceRegion *MemRegionManager::getUnknownRegion() {
873 return LazyAllocate(unknown);
874}
875
876const CodeSpaceRegion *MemRegionManager::getCodeRegion() {
877 return LazyAllocate(code);
878}
879
880//===----------------------------------------------------------------------===//
881// Constructing regions.
882//===----------------------------------------------------------------------===//
883
884const StringRegion *MemRegionManager::getStringRegion(const StringLiteral *Str){
885 return getSubRegion<StringRegion>(
886 Str, cast<GlobalInternalSpaceRegion>(getGlobalsRegion()));
887}
888
889const ObjCStringRegion *
890MemRegionManager::getObjCStringRegion(const ObjCStringLiteral *Str){
891 return getSubRegion<ObjCStringRegion>(
892 Str, cast<GlobalInternalSpaceRegion>(getGlobalsRegion()));
893}
894
895/// Look through a chain of LocationContexts to either find the
896/// StackFrameContext that matches a DeclContext, or find a VarRegion
897/// for a variable captured by a block.
898static llvm::PointerUnion<const StackFrameContext *, const VarRegion *>
899getStackOrCaptureRegionForDeclContext(const LocationContext *LC,
900 const DeclContext *DC,
901 const VarDecl *VD) {
902 while (LC) {
903 if (const auto *SFC = dyn_cast<StackFrameContext>(LC)) {
904 if (cast<DeclContext>(SFC->getDecl()) == DC)
905 return SFC;
906 }
907 if (const auto *BC = dyn_cast<BlockInvocationContext>(LC)) {
908 const auto *BR = static_cast<const BlockDataRegion *>(BC->getData());
909 // FIXME: This can be made more efficient.
910 for (BlockDataRegion::referenced_vars_iterator
911 I = BR->referenced_vars_begin(),
912 E = BR->referenced_vars_end(); I != E; ++I) {
913 const TypedValueRegion *OrigR = I.getOriginalRegion();
914 if (const auto *VR = dyn_cast<VarRegion>(OrigR)) {
915 if (VR->getDecl() == VD)
916 return cast<VarRegion>(I.getCapturedRegion());
917 }
918 }
919 }
920
921 LC = LC->getParent();
922 }
923 return (const StackFrameContext *)nullptr;
924}
925
926const VarRegion *MemRegionManager::getVarRegion(const VarDecl *D,
927 const LocationContext *LC) {
928 const auto *PVD = dyn_cast<ParmVarDecl>(D);
27
Assuming 'D' is a 'ParmVarDecl'
929 if (PVD
27.1
'PVD' is non-null
27.1
'PVD' is non-null
27.1
'PVD' is non-null
) {
28
Taking true branch
930 unsigned Index = PVD->getFunctionScopeIndex();
931 const StackFrameContext *SFC = LC->getStackFrame();
29
Called C++ object pointer is null
932 const Stmt *CallSite = SFC->getCallSite();
933 if (CallSite) {
934 const Decl *D = SFC->getDecl();
935 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
936 if (Index < FD->param_size() && FD->parameters()[Index] == PVD)
937 return getSubRegion<ParamVarRegion>(cast<Expr>(CallSite), Index,
938 getStackArgumentsRegion(SFC));
939 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
940 if (Index < BD->param_size() && BD->parameters()[Index] == PVD)
941 return getSubRegion<ParamVarRegion>(cast<Expr>(CallSite), Index,
942 getStackArgumentsRegion(SFC));
943 } else {
944 return getSubRegion<ParamVarRegion>(cast<Expr>(CallSite), Index,
945 getStackArgumentsRegion(SFC));
946 }
947 }
948 }
949
950 D = D->getCanonicalDecl();
951 const MemRegion *sReg = nullptr;
952
953 if (D->hasGlobalStorage() && !D->isStaticLocal()) {
954
955 // First handle the globals defined in system headers.
956 if (Ctx.getSourceManager().isInSystemHeader(D->getLocation())) {
957 // Whitelist the system globals which often DO GET modified, assume the
958 // rest are immutable.
959 if (D->getName().find("errno") != StringRef::npos)
960 sReg = getGlobalsRegion(MemRegion::GlobalSystemSpaceRegionKind);
961 else
962 sReg = getGlobalsRegion(MemRegion::GlobalImmutableSpaceRegionKind);
963
964 // Treat other globals as GlobalInternal unless they are constants.
965 } else {
966 QualType GQT = D->getType();
967 const Type *GT = GQT.getTypePtrOrNull();
968 // TODO: We could walk the complex types here and see if everything is
969 // constified.
970 if (GT && GQT.isConstQualified() && GT->isArithmeticType())
971 sReg = getGlobalsRegion(MemRegion::GlobalImmutableSpaceRegionKind);
972 else
973 sReg = getGlobalsRegion();
974 }
975
976 // Finally handle static locals.
977 } else {
978 // FIXME: Once we implement scope handling, we will need to properly lookup
979 // 'D' to the proper LocationContext.
980 const DeclContext *DC = D->getDeclContext();
981 llvm::PointerUnion<const StackFrameContext *, const VarRegion *> V =
982 getStackOrCaptureRegionForDeclContext(LC, DC, D);
983
984 if (V.is<const VarRegion*>())
985 return V.get<const VarRegion*>();
986
987 const auto *STC = V.get<const StackFrameContext *>();
988
989 if (!STC) {
990 // FIXME: Assign a more sensible memory space to static locals
991 // we see from within blocks that we analyze as top-level declarations.
992 sReg = getUnknownRegion();
993 } else {
994 if (D->hasLocalStorage()) {
995 sReg = isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)
996 ? static_cast<const MemRegion*>(getStackArgumentsRegion(STC))
997 : static_cast<const MemRegion*>(getStackLocalsRegion(STC));
998 }
999 else {
1000 assert(D->isStaticLocal())((D->isStaticLocal()) ? static_cast<void> (0) : __assert_fail
("D->isStaticLocal()", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1000, __PRETTY_FUNCTION__))
;
1001 const Decl *STCD = STC->getDecl();
1002 if (isa<FunctionDecl>(STCD) || isa<ObjCMethodDecl>(STCD))
1003 sReg = getGlobalsRegion(MemRegion::StaticGlobalSpaceRegionKind,
1004 getFunctionCodeRegion(cast<NamedDecl>(STCD)));
1005 else if (const auto *BD = dyn_cast<BlockDecl>(STCD)) {
1006 // FIXME: The fallback type here is totally bogus -- though it should
1007 // never be queried, it will prevent uniquing with the real
1008 // BlockCodeRegion. Ideally we'd fix the AST so that we always had a
1009 // signature.
1010 QualType T;
1011 if (const TypeSourceInfo *TSI = BD->getSignatureAsWritten())
1012 T = TSI->getType();
1013 if (T.isNull())
1014 T = getContext().VoidTy;
1015 if (!T->getAs<FunctionType>())
1016 T = getContext().getFunctionNoProtoType(T);
1017 T = getContext().getBlockPointerType(T);
1018
1019 const BlockCodeRegion *BTR =
1020 getBlockCodeRegion(BD, Ctx.getCanonicalType(T),
1021 STC->getAnalysisDeclContext());
1022 sReg = getGlobalsRegion(MemRegion::StaticGlobalSpaceRegionKind,
1023 BTR);
1024 }
1025 else {
1026 sReg = getGlobalsRegion();
1027 }
1028 }
1029 }
1030 }
1031
1032 return getSubRegion<NonParamVarRegion>(D, sReg);
1033}
1034
1035const NonParamVarRegion *
1036MemRegionManager::getNonParamVarRegion(const VarDecl *D,
1037 const MemRegion *superR) {
1038 D = D->getCanonicalDecl();
1039 return getSubRegion<NonParamVarRegion>(D, superR);
1040}
1041
1042const ParamVarRegion *
1043MemRegionManager::getParamVarRegion(const Expr *OriginExpr, unsigned Index,
1044 const LocationContext *LC) {
1045 const StackFrameContext *SFC = LC->getStackFrame();
1046 assert(SFC)((SFC) ? static_cast<void> (0) : __assert_fail ("SFC", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1046, __PRETTY_FUNCTION__))
;
1047 return getSubRegion<ParamVarRegion>(OriginExpr, Index,
1048 getStackArgumentsRegion(SFC));
1049}
1050
1051const BlockDataRegion *
1052MemRegionManager::getBlockDataRegion(const BlockCodeRegion *BC,
1053 const LocationContext *LC,
1054 unsigned blockCount) {
1055 const MemSpaceRegion *sReg = nullptr;
1056 const BlockDecl *BD = BC->getDecl();
1057 if (!BD->hasCaptures()) {
1058 // This handles 'static' blocks.
1059 sReg = getGlobalsRegion(MemRegion::GlobalImmutableSpaceRegionKind);
1060 }
1061 else {
1062 if (LC) {
1063 // FIXME: Once we implement scope handling, we want the parent region
1064 // to be the scope.
1065 const StackFrameContext *STC = LC->getStackFrame();
1066 assert(STC)((STC) ? static_cast<void> (0) : __assert_fail ("STC", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1066, __PRETTY_FUNCTION__))
;
1067 sReg = getStackLocalsRegion(STC);
1068 }
1069 else {
1070 // We allow 'LC' to be NULL for cases where want BlockDataRegions
1071 // without context-sensitivity.
1072 sReg = getUnknownRegion();
1073 }
1074 }
1075
1076 return getSubRegion<BlockDataRegion>(BC, LC, blockCount, sReg);
1077}
1078
1079const CXXTempObjectRegion *
1080MemRegionManager::getCXXStaticTempObjectRegion(const Expr *Ex) {
1081 return getSubRegion<CXXTempObjectRegion>(
1082 Ex, getGlobalsRegion(MemRegion::GlobalInternalSpaceRegionKind, nullptr));
1083}
1084
1085const CompoundLiteralRegion*
1086MemRegionManager::getCompoundLiteralRegion(const CompoundLiteralExpr *CL,
1087 const LocationContext *LC) {
1088 const MemSpaceRegion *sReg = nullptr;
1089
1090 if (CL->isFileScope())
1091 sReg = getGlobalsRegion();
1092 else {
1093 const StackFrameContext *STC = LC->getStackFrame();
1094 assert(STC)((STC) ? static_cast<void> (0) : __assert_fail ("STC", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1094, __PRETTY_FUNCTION__))
;
1095 sReg = getStackLocalsRegion(STC);
1096 }
1097
1098 return getSubRegion<CompoundLiteralRegion>(CL, sReg);
1099}
1100
1101const ElementRegion*
1102MemRegionManager::getElementRegion(QualType elementType, NonLoc Idx,
1103 const SubRegion* superRegion,
1104 ASTContext &Ctx){
1105 QualType T = Ctx.getCanonicalType(elementType).getUnqualifiedType();
1106
1107 llvm::FoldingSetNodeID ID;
1108 ElementRegion::ProfileRegion(ID, T, Idx, superRegion);
1109
1110 void *InsertPos;
1111 MemRegion* data = Regions.FindNodeOrInsertPos(ID, InsertPos);
1112 auto *R = cast_or_null<ElementRegion>(data);
1113
1114 if (!R) {
1115 R = A.Allocate<ElementRegion>();
1116 new (R) ElementRegion(T, Idx, superRegion);
1117 Regions.InsertNode(R, InsertPos);
1118 }
1119
1120 return R;
1121}
1122
1123const FunctionCodeRegion *
1124MemRegionManager::getFunctionCodeRegion(const NamedDecl *FD) {
1125 // To think: should we canonicalize the declaration here?
1126 return getSubRegion<FunctionCodeRegion>(FD, getCodeRegion());
1127}
1128
1129const BlockCodeRegion *
1130MemRegionManager::getBlockCodeRegion(const BlockDecl *BD, CanQualType locTy,
1131 AnalysisDeclContext *AC) {
1132 return getSubRegion<BlockCodeRegion>(BD, locTy, AC, getCodeRegion());
1133}
1134
1135/// getSymbolicRegion - Retrieve or create a "symbolic" memory region.
1136const SymbolicRegion *MemRegionManager::getSymbolicRegion(SymbolRef sym) {
1137 return getSubRegion<SymbolicRegion>(sym, getUnknownRegion());
1138}
1139
1140const SymbolicRegion *MemRegionManager::getSymbolicHeapRegion(SymbolRef Sym) {
1141 return getSubRegion<SymbolicRegion>(Sym, getHeapRegion());
1142}
1143
1144const FieldRegion*
1145MemRegionManager::getFieldRegion(const FieldDecl *d,
1146 const SubRegion* superRegion){
1147 return getSubRegion<FieldRegion>(d, superRegion);
1148}
1149
1150const ObjCIvarRegion*
1151MemRegionManager::getObjCIvarRegion(const ObjCIvarDecl *d,
1152 const SubRegion* superRegion) {
1153 return getSubRegion<ObjCIvarRegion>(d, superRegion);
1154}
1155
1156const CXXTempObjectRegion*
1157MemRegionManager::getCXXTempObjectRegion(Expr const *E,
1158 LocationContext const *LC) {
1159 const StackFrameContext *SFC = LC->getStackFrame();
1160 assert(SFC)((SFC) ? static_cast<void> (0) : __assert_fail ("SFC", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1160, __PRETTY_FUNCTION__))
;
1161 return getSubRegion<CXXTempObjectRegion>(E, getStackLocalsRegion(SFC));
1162}
1163
1164/// Checks whether \p BaseClass is a valid virtual or direct non-virtual base
1165/// class of the type of \p Super.
1166static bool isValidBaseClass(const CXXRecordDecl *BaseClass,
1167 const TypedValueRegion *Super,
1168 bool IsVirtual) {
1169 BaseClass = BaseClass->getCanonicalDecl();
1170
1171 const CXXRecordDecl *Class = Super->getValueType()->getAsCXXRecordDecl();
1172 if (!Class)
1173 return true;
1174
1175 if (IsVirtual)
1176 return Class->isVirtuallyDerivedFrom(BaseClass);
1177
1178 for (const auto &I : Class->bases()) {
1179 if (I.getType()->getAsCXXRecordDecl()->getCanonicalDecl() == BaseClass)
1180 return true;
1181 }
1182
1183 return false;
1184}
1185
1186const CXXBaseObjectRegion *
1187MemRegionManager::getCXXBaseObjectRegion(const CXXRecordDecl *RD,
1188 const SubRegion *Super,
1189 bool IsVirtual) {
1190 if (isa<TypedValueRegion>(Super)) {
1191 assert(isValidBaseClass(RD, cast<TypedValueRegion>(Super), IsVirtual))((isValidBaseClass(RD, cast<TypedValueRegion>(Super), IsVirtual
)) ? static_cast<void> (0) : __assert_fail ("isValidBaseClass(RD, cast<TypedValueRegion>(Super), IsVirtual)"
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1191, __PRETTY_FUNCTION__))
;
1192 (void)&isValidBaseClass;
1193
1194 if (IsVirtual) {
1195 // Virtual base regions should not be layered, since the layout rules
1196 // are different.
1197 while (const auto *Base = dyn_cast<CXXBaseObjectRegion>(Super))
1198 Super = cast<SubRegion>(Base->getSuperRegion());
1199 assert(Super && !isa<MemSpaceRegion>(Super))((Super && !isa<MemSpaceRegion>(Super)) ? static_cast
<void> (0) : __assert_fail ("Super && !isa<MemSpaceRegion>(Super)"
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1199, __PRETTY_FUNCTION__))
;
1200 }
1201 }
1202
1203 return getSubRegion<CXXBaseObjectRegion>(RD, IsVirtual, Super);
1204}
1205
1206const CXXDerivedObjectRegion *
1207MemRegionManager::getCXXDerivedObjectRegion(const CXXRecordDecl *RD,
1208 const SubRegion *Super) {
1209 return getSubRegion<CXXDerivedObjectRegion>(RD, Super);
1210}
1211
1212const CXXThisRegion*
1213MemRegionManager::getCXXThisRegion(QualType thisPointerTy,
1214 const LocationContext *LC) {
1215 const auto *PT = thisPointerTy->getAs<PointerType>();
1216 assert(PT)((PT) ? static_cast<void> (0) : __assert_fail ("PT", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1216, __PRETTY_FUNCTION__))
;
1217 // Inside the body of the operator() of a lambda a this expr might refer to an
1218 // object in one of the parent location contexts.
1219 const auto *D = dyn_cast<CXXMethodDecl>(LC->getDecl());
1220 // FIXME: when operator() of lambda is analyzed as a top level function and
1221 // 'this' refers to a this to the enclosing scope, there is no right region to
1222 // return.
1223 while (!LC->inTopFrame() && (!D || D->isStatic() ||
1224 PT != D->getThisType()->getAs<PointerType>())) {
1225 LC = LC->getParent();
1226 D = dyn_cast<CXXMethodDecl>(LC->getDecl());
1227 }
1228 const StackFrameContext *STC = LC->getStackFrame();
1229 assert(STC)((STC) ? static_cast<void> (0) : __assert_fail ("STC", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1229, __PRETTY_FUNCTION__))
;
1230 return getSubRegion<CXXThisRegion>(PT, getStackArgumentsRegion(STC));
1231}
1232
1233const AllocaRegion*
1234MemRegionManager::getAllocaRegion(const Expr *E, unsigned cnt,
1235 const LocationContext *LC) {
1236 const StackFrameContext *STC = LC->getStackFrame();
1237 assert(STC)((STC) ? static_cast<void> (0) : __assert_fail ("STC", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1237, __PRETTY_FUNCTION__))
;
1238 return getSubRegion<AllocaRegion>(E, cnt, getStackLocalsRegion(STC));
1239}
1240
1241const MemSpaceRegion *MemRegion::getMemorySpace() const {
1242 const MemRegion *R = this;
1243 const auto *SR = dyn_cast<SubRegion>(this);
1244
1245 while (SR) {
1246 R = SR->getSuperRegion();
1247 SR = dyn_cast<SubRegion>(R);
1248 }
1249
1250 return dyn_cast<MemSpaceRegion>(R);
1251}
1252
1253bool MemRegion::hasStackStorage() const {
1254 return isa<StackSpaceRegion>(getMemorySpace());
1255}
1256
1257bool MemRegion::hasStackNonParametersStorage() const {
1258 return isa<StackLocalsSpaceRegion>(getMemorySpace());
1259}
1260
1261bool MemRegion::hasStackParametersStorage() const {
1262 return isa<StackArgumentsSpaceRegion>(getMemorySpace());
1263}
1264
1265bool MemRegion::hasGlobalsOrParametersStorage() const {
1266 const MemSpaceRegion *MS = getMemorySpace();
1267 return isa<StackArgumentsSpaceRegion>(MS) ||
1268 isa<GlobalsSpaceRegion>(MS);
1269}
1270
1271// getBaseRegion strips away all elements and fields, and get the base region
1272// of them.
1273const MemRegion *MemRegion::getBaseRegion() const {
1274 const MemRegion *R = this;
1275 while (true) {
1276 switch (R->getKind()) {
1277 case MemRegion::ElementRegionKind:
1278 case MemRegion::FieldRegionKind:
1279 case MemRegion::ObjCIvarRegionKind:
1280 case MemRegion::CXXBaseObjectRegionKind:
1281 case MemRegion::CXXDerivedObjectRegionKind:
1282 R = cast<SubRegion>(R)->getSuperRegion();
1283 continue;
1284 default:
1285 break;
1286 }
1287 break;
1288 }
1289 return R;
1290}
1291
1292// getgetMostDerivedObjectRegion gets the region of the root class of a C++
1293// class hierarchy.
1294const MemRegion *MemRegion::getMostDerivedObjectRegion() const {
1295 const MemRegion *R = this;
1296 while (const auto *BR = dyn_cast<CXXBaseObjectRegion>(R))
1297 R = BR->getSuperRegion();
1298 return R;
1299}
1300
1301bool MemRegion::isSubRegionOf(const MemRegion *) const {
1302 return false;
1303}
1304
1305//===----------------------------------------------------------------------===//
1306// View handling.
1307//===----------------------------------------------------------------------===//
1308
1309const MemRegion *MemRegion::StripCasts(bool StripBaseAndDerivedCasts) const {
1310 const MemRegion *R = this;
1311 while (true) {
1312 switch (R->getKind()) {
1313 case ElementRegionKind: {
1314 const auto *ER = cast<ElementRegion>(R);
1315 if (!ER->getIndex().isZeroConstant())
1316 return R;
1317 R = ER->getSuperRegion();
1318 break;
1319 }
1320 case CXXBaseObjectRegionKind:
1321 case CXXDerivedObjectRegionKind:
1322 if (!StripBaseAndDerivedCasts)
1323 return R;
1324 R = cast<TypedValueRegion>(R)->getSuperRegion();
1325 break;
1326 default:
1327 return R;
1328 }
1329 }
1330}
1331
1332const SymbolicRegion *MemRegion::getSymbolicBase() const {
1333 const auto *SubR = dyn_cast<SubRegion>(this);
1334
1335 while (SubR) {
1336 if (const auto *SymR = dyn_cast<SymbolicRegion>(SubR))
1337 return SymR;
1338 SubR = dyn_cast<SubRegion>(SubR->getSuperRegion());
1339 }
1340 return nullptr;
1341}
1342
1343RegionRawOffset ElementRegion::getAsArrayOffset() const {
1344 int64_t offset = 0;
1345 const ElementRegion *ER = this;
1346 const MemRegion *superR = nullptr;
1347 ASTContext &C = getContext();
1348
1349 // FIXME: Handle multi-dimensional arrays.
1350
1351 while (ER) {
1352 superR = ER->getSuperRegion();
1353
1354 // FIXME: generalize to symbolic offsets.
1355 SVal index = ER->getIndex();
1356 if (auto CI = index.getAs<nonloc::ConcreteInt>()) {
1357 // Update the offset.
1358 int64_t i = CI->getValue().getSExtValue();
1359
1360 if (i != 0) {
1361 QualType elemType = ER->getElementType();
1362
1363 // If we are pointing to an incomplete type, go no further.
1364 if (elemType->isIncompleteType()) {
1365 superR = ER;
1366 break;
1367 }
1368
1369 int64_t size = C.getTypeSizeInChars(elemType).getQuantity();
1370 if (auto NewOffset = llvm::checkedMulAdd(i, size, offset)) {
1371 offset = *NewOffset;
1372 } else {
1373 LLVM_DEBUG(llvm::dbgs() << "MemRegion::getAsArrayOffset: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("MemRegion")) { llvm::dbgs() << "MemRegion::getAsArrayOffset: "
<< "offset overflowing, returning unknown\n"; } } while
(false)
1374 << "offset overflowing, returning unknown\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("MemRegion")) { llvm::dbgs() << "MemRegion::getAsArrayOffset: "
<< "offset overflowing, returning unknown\n"; } } while
(false)
;
1375
1376 return nullptr;
1377 }
1378 }
1379
1380 // Go to the next ElementRegion (if any).
1381 ER = dyn_cast<ElementRegion>(superR);
1382 continue;
1383 }
1384
1385 return nullptr;
1386 }
1387
1388 assert(superR && "super region cannot be NULL")((superR && "super region cannot be NULL") ? static_cast
<void> (0) : __assert_fail ("superR && \"super region cannot be NULL\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1388, __PRETTY_FUNCTION__))
;
1389 return RegionRawOffset(superR, CharUnits::fromQuantity(offset));
1390}
1391
1392/// Returns true if \p Base is an immediate base class of \p Child
1393static bool isImmediateBase(const CXXRecordDecl *Child,
1394 const CXXRecordDecl *Base) {
1395 assert(Child && "Child must not be null")((Child && "Child must not be null") ? static_cast<
void> (0) : __assert_fail ("Child && \"Child must not be null\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1395, __PRETTY_FUNCTION__))
;
1396 // Note that we do NOT canonicalize the base class here, because
1397 // ASTRecordLayout doesn't either. If that leads us down the wrong path,
1398 // so be it; at least we won't crash.
1399 for (const auto &I : Child->bases()) {
1400 if (I.getType()->getAsCXXRecordDecl() == Base)
1401 return true;
1402 }
1403
1404 return false;
1405}
1406
1407static RegionOffset calculateOffset(const MemRegion *R) {
1408 const MemRegion *SymbolicOffsetBase = nullptr;
1409 int64_t Offset = 0;
1410
1411 while (true) {
1412 switch (R->getKind()) {
1413 case MemRegion::CodeSpaceRegionKind:
1414 case MemRegion::StackLocalsSpaceRegionKind:
1415 case MemRegion::StackArgumentsSpaceRegionKind:
1416 case MemRegion::HeapSpaceRegionKind:
1417 case MemRegion::UnknownSpaceRegionKind:
1418 case MemRegion::StaticGlobalSpaceRegionKind:
1419 case MemRegion::GlobalInternalSpaceRegionKind:
1420 case MemRegion::GlobalSystemSpaceRegionKind:
1421 case MemRegion::GlobalImmutableSpaceRegionKind:
1422 // Stores can bind directly to a region space to set a default value.
1423 assert(Offset == 0 && !SymbolicOffsetBase)((Offset == 0 && !SymbolicOffsetBase) ? static_cast<
void> (0) : __assert_fail ("Offset == 0 && !SymbolicOffsetBase"
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1423, __PRETTY_FUNCTION__))
;
1424 goto Finish;
1425
1426 case MemRegion::FunctionCodeRegionKind:
1427 case MemRegion::BlockCodeRegionKind:
1428 case MemRegion::BlockDataRegionKind:
1429 // These will never have bindings, but may end up having values requested
1430 // if the user does some strange casting.
1431 if (Offset != 0)
1432 SymbolicOffsetBase = R;
1433 goto Finish;
1434
1435 case MemRegion::SymbolicRegionKind:
1436 case MemRegion::AllocaRegionKind:
1437 case MemRegion::CompoundLiteralRegionKind:
1438 case MemRegion::CXXThisRegionKind:
1439 case MemRegion::StringRegionKind:
1440 case MemRegion::ObjCStringRegionKind:
1441 case MemRegion::NonParamVarRegionKind:
1442 case MemRegion::ParamVarRegionKind:
1443 case MemRegion::CXXTempObjectRegionKind:
1444 // Usual base regions.
1445 goto Finish;
1446
1447 case MemRegion::ObjCIvarRegionKind:
1448 // This is a little strange, but it's a compromise between
1449 // ObjCIvarRegions having unknown compile-time offsets (when using the
1450 // non-fragile runtime) and yet still being distinct, non-overlapping
1451 // regions. Thus we treat them as "like" base regions for the purposes
1452 // of computing offsets.
1453 goto Finish;
1454
1455 case MemRegion::CXXBaseObjectRegionKind: {
1456 const auto *BOR = cast<CXXBaseObjectRegion>(R);
1457 R = BOR->getSuperRegion();
1458
1459 QualType Ty;
1460 bool RootIsSymbolic = false;
1461 if (const auto *TVR = dyn_cast<TypedValueRegion>(R)) {
1462 Ty = TVR->getDesugaredValueType(R->getContext());
1463 } else if (const auto *SR = dyn_cast<SymbolicRegion>(R)) {
1464 // If our base region is symbolic, we don't know what type it really is.
1465 // Pretend the type of the symbol is the true dynamic type.
1466 // (This will at least be self-consistent for the life of the symbol.)
1467 Ty = SR->getSymbol()->getType()->getPointeeType();
1468 RootIsSymbolic = true;
1469 }
1470
1471 const CXXRecordDecl *Child = Ty->getAsCXXRecordDecl();
1472 if (!Child) {
1473 // We cannot compute the offset of the base class.
1474 SymbolicOffsetBase = R;
1475 } else {
1476 if (RootIsSymbolic) {
1477 // Base layers on symbolic regions may not be type-correct.
1478 // Double-check the inheritance here, and revert to a symbolic offset
1479 // if it's invalid (e.g. due to a reinterpret_cast).
1480 if (BOR->isVirtual()) {
1481 if (!Child->isVirtuallyDerivedFrom(BOR->getDecl()))
1482 SymbolicOffsetBase = R;
1483 } else {
1484 if (!isImmediateBase(Child, BOR->getDecl()))
1485 SymbolicOffsetBase = R;
1486 }
1487 }
1488 }
1489
1490 // Don't bother calculating precise offsets if we already have a
1491 // symbolic offset somewhere in the chain.
1492 if (SymbolicOffsetBase)
1493 continue;
1494
1495 CharUnits BaseOffset;
1496 const ASTRecordLayout &Layout = R->getContext().getASTRecordLayout(Child);
1497 if (BOR->isVirtual())
1498 BaseOffset = Layout.getVBaseClassOffset(BOR->getDecl());
1499 else
1500 BaseOffset = Layout.getBaseClassOffset(BOR->getDecl());
1501
1502 // The base offset is in chars, not in bits.
1503 Offset += BaseOffset.getQuantity() * R->getContext().getCharWidth();
1504 break;
1505 }
1506
1507 case MemRegion::CXXDerivedObjectRegionKind: {
1508 // TODO: Store the base type in the CXXDerivedObjectRegion and use it.
1509 goto Finish;
1510 }
1511
1512 case MemRegion::ElementRegionKind: {
1513 const auto *ER = cast<ElementRegion>(R);
1514 R = ER->getSuperRegion();
1515
1516 QualType EleTy = ER->getValueType();
1517 if (EleTy->isIncompleteType()) {
1518 // We cannot compute the offset of the base class.
1519 SymbolicOffsetBase = R;
1520 continue;
1521 }
1522
1523 SVal Index = ER->getIndex();
1524 if (Optional<nonloc::ConcreteInt> CI =
1525 Index.getAs<nonloc::ConcreteInt>()) {
1526 // Don't bother calculating precise offsets if we already have a
1527 // symbolic offset somewhere in the chain.
1528 if (SymbolicOffsetBase)
1529 continue;
1530
1531 int64_t i = CI->getValue().getSExtValue();
1532 // This type size is in bits.
1533 Offset += i * R->getContext().getTypeSize(EleTy);
1534 } else {
1535 // We cannot compute offset for non-concrete index.
1536 SymbolicOffsetBase = R;
1537 }
1538 break;
1539 }
1540 case MemRegion::FieldRegionKind: {
1541 const auto *FR = cast<FieldRegion>(R);
1542 R = FR->getSuperRegion();
1543 assert(R)((R) ? static_cast<void> (0) : __assert_fail ("R", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1543, __PRETTY_FUNCTION__))
;
1544
1545 const RecordDecl *RD = FR->getDecl()->getParent();
1546 if (RD->isUnion() || !RD->isCompleteDefinition()) {
1547 // We cannot compute offset for incomplete type.
1548 // For unions, we could treat everything as offset 0, but we'd rather
1549 // treat each field as a symbolic offset so they aren't stored on top
1550 // of each other, since we depend on things in typed regions actually
1551 // matching their types.
1552 SymbolicOffsetBase = R;
1553 }
1554
1555 // Don't bother calculating precise offsets if we already have a
1556 // symbolic offset somewhere in the chain.
1557 if (SymbolicOffsetBase)
1558 continue;
1559
1560 // Get the field number.
1561 unsigned idx = 0;
1562 for (RecordDecl::field_iterator FI = RD->field_begin(),
1563 FE = RD->field_end(); FI != FE; ++FI, ++idx) {
1564 if (FR->getDecl() == *FI)
1565 break;
1566 }
1567 const ASTRecordLayout &Layout = R->getContext().getASTRecordLayout(RD);
1568 // This is offset in bits.
1569 Offset += Layout.getFieldOffset(idx);
1570 break;
1571 }
1572 }
1573 }
1574
1575 Finish:
1576 if (SymbolicOffsetBase)
1577 return RegionOffset(SymbolicOffsetBase, RegionOffset::Symbolic);
1578 return RegionOffset(R, Offset);
1579}
1580
1581RegionOffset MemRegion::getAsOffset() const {
1582 if (!cachedOffset)
1583 cachedOffset = calculateOffset(this);
1584 return *cachedOffset;
1585}
1586
1587//===----------------------------------------------------------------------===//
1588// BlockDataRegion
1589//===----------------------------------------------------------------------===//
1590
1591std::pair<const VarRegion *, const VarRegion *>
1592BlockDataRegion::getCaptureRegions(const VarDecl *VD) {
1593 MemRegionManager &MemMgr = getMemRegionManager();
9
Value assigned to field 'LC'
1594 const VarRegion *VR = nullptr;
1595 const VarRegion *OriginalVR = nullptr;
1596
1597 if (!VD->hasAttr<BlocksAttr>() && VD->hasLocalStorage()) {
10
Calling 'Decl::hasAttr'
13
Returning from 'Decl::hasAttr'
14
Calling 'VarDecl::hasLocalStorage'
20
Returning from 'VarDecl::hasLocalStorage'
21
Taking false branch
1598 VR = MemMgr.getNonParamVarRegion(VD, this);
1599 OriginalVR = MemMgr.getVarRegion(VD, LC);
1600 }
1601 else {
1602 if (LC) {
22
Assuming pointer value is null
23
Assuming field 'LC' is null
24
Taking false branch
1603 VR = MemMgr.getVarRegion(VD, LC);
1604 OriginalVR = VR;
1605 }
1606 else {
1607 VR = MemMgr.getNonParamVarRegion(VD, MemMgr.getUnknownRegion());
1608 OriginalVR = MemMgr.getVarRegion(VD, LC);
25
Passing null pointer value via 2nd parameter 'LC'
26
Calling 'MemRegionManager::getVarRegion'
1609 }
1610 }
1611 return std::make_pair(VR, OriginalVR);
1612}
1613
1614void BlockDataRegion::LazyInitializeReferencedVars() {
1615 if (ReferencedVars)
3
Assuming field 'ReferencedVars' is null
4
Taking false branch
1616 return;
1617
1618 AnalysisDeclContext *AC = getCodeRegion()->getAnalysisDeclContext();
1619 const auto &ReferencedBlockVars = AC->getReferencedBlockVars(BC->getDecl());
1620 auto NumBlockVars =
1621 std::distance(ReferencedBlockVars.begin(), ReferencedBlockVars.end());
1622
1623 if (NumBlockVars == 0) {
5
Assuming 'NumBlockVars' is not equal to 0
6
Taking false branch
1624 ReferencedVars = (void*) 0x1;
1625 return;
1626 }
1627
1628 MemRegionManager &MemMgr = getMemRegionManager();
1629 llvm::BumpPtrAllocator &A = MemMgr.getAllocator();
1630 BumpVectorContext BC(A);
1631
1632 using VarVec = BumpVector<const MemRegion *>;
1633
1634 auto *BV = A.Allocate<VarVec>();
1635 new (BV) VarVec(BC, NumBlockVars);
1636 auto *BVOriginal = A.Allocate<VarVec>();
1637 new (BVOriginal) VarVec(BC, NumBlockVars);
1638
1639 for (const auto *VD : ReferencedBlockVars) {
7
Assuming '__begin1' is not equal to '__end1'
1640 const VarRegion *VR = nullptr;
1641 const VarRegion *OriginalVR = nullptr;
1642 std::tie(VR, OriginalVR) = getCaptureRegions(VD);
8
Calling 'BlockDataRegion::getCaptureRegions'
1643 assert(VR)((VR) ? static_cast<void> (0) : __assert_fail ("VR", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1643, __PRETTY_FUNCTION__))
;
1644 assert(OriginalVR)((OriginalVR) ? static_cast<void> (0) : __assert_fail (
"OriginalVR", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1644, __PRETTY_FUNCTION__))
;
1645 BV->push_back(VR, BC);
1646 BVOriginal->push_back(OriginalVR, BC);
1647 }
1648
1649 ReferencedVars = BV;
1650 OriginalVars = BVOriginal;
1651}
1652
1653BlockDataRegion::referenced_vars_iterator
1654BlockDataRegion::referenced_vars_begin() const {
1655 const_cast<BlockDataRegion*>(this)->LazyInitializeReferencedVars();
2
Calling 'BlockDataRegion::LazyInitializeReferencedVars'
1656
1657 auto *Vec = static_cast<BumpVector<const MemRegion *> *>(ReferencedVars);
1658
1659 if (Vec == (void*) 0x1)
1660 return BlockDataRegion::referenced_vars_iterator(nullptr, nullptr);
1661
1662 auto *VecOriginal =
1663 static_cast<BumpVector<const MemRegion *> *>(OriginalVars);
1664
1665 return BlockDataRegion::referenced_vars_iterator(Vec->begin(),
1666 VecOriginal->begin());
1667}
1668
1669BlockDataRegion::referenced_vars_iterator
1670BlockDataRegion::referenced_vars_end() const {
1671 const_cast<BlockDataRegion*>(this)->LazyInitializeReferencedVars();
1672
1673 auto *Vec = static_cast<BumpVector<const MemRegion *> *>(ReferencedVars);
1674
1675 if (Vec == (void*) 0x1)
1676 return BlockDataRegion::referenced_vars_iterator(nullptr, nullptr);
1677
1678 auto *VecOriginal =
1679 static_cast<BumpVector<const MemRegion *> *>(OriginalVars);
1680
1681 return BlockDataRegion::referenced_vars_iterator(Vec->end(),
1682 VecOriginal->end());
1683}
1684
1685const VarRegion *BlockDataRegion::getOriginalRegion(const VarRegion *R) const {
1686 for (referenced_vars_iterator I = referenced_vars_begin(),
1
Calling 'BlockDataRegion::referenced_vars_begin'
1687 E = referenced_vars_end();
1688 I != E; ++I) {
1689 if (I.getCapturedRegion() == R)
1690 return I.getOriginalRegion();
1691 }
1692 return nullptr;
1693}
1694
1695//===----------------------------------------------------------------------===//
1696// RegionAndSymbolInvalidationTraits
1697//===----------------------------------------------------------------------===//
1698
1699void RegionAndSymbolInvalidationTraits::setTrait(SymbolRef Sym,
1700 InvalidationKinds IK) {
1701 SymTraitsMap[Sym] |= IK;
1702}
1703
1704void RegionAndSymbolInvalidationTraits::setTrait(const MemRegion *MR,
1705 InvalidationKinds IK) {
1706 assert(MR)((MR) ? static_cast<void> (0) : __assert_fail ("MR", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1706, __PRETTY_FUNCTION__))
;
1707 if (const auto *SR = dyn_cast<SymbolicRegion>(MR))
1708 setTrait(SR->getSymbol(), IK);
1709 else
1710 MRTraitsMap[MR] |= IK;
1711}
1712
1713bool RegionAndSymbolInvalidationTraits::hasTrait(SymbolRef Sym,
1714 InvalidationKinds IK) const {
1715 const_symbol_iterator I = SymTraitsMap.find(Sym);
1716 if (I != SymTraitsMap.end())
1717 return I->second & IK;
1718
1719 return false;
1720}
1721
1722bool RegionAndSymbolInvalidationTraits::hasTrait(const MemRegion *MR,
1723 InvalidationKinds IK) const {
1724 if (!MR)
1725 return false;
1726
1727 if (const auto *SR = dyn_cast<SymbolicRegion>(MR))
1728 return hasTrait(SR->getSymbol(), IK);
1729
1730 const_region_iterator I = MRTraitsMap.find(MR);
1731 if (I != MRTraitsMap.end())
1732 return I->second & IK;
1733
1734 return false;
1735}

/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h

1//===- DeclBase.h - Base Classes for representing declarations --*- 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 Decl and DeclContext interfaces.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_AST_DECLBASE_H
14#define LLVM_CLANG_AST_DECLBASE_H
15
16#include "clang/AST/ASTDumperUtils.h"
17#include "clang/AST/AttrIterator.h"
18#include "clang/AST/DeclarationName.h"
19#include "clang/Basic/IdentifierTable.h"
20#include "clang/Basic/LLVM.h"
21#include "clang/Basic/SourceLocation.h"
22#include "clang/Basic/Specifiers.h"
23#include "llvm/ADT/ArrayRef.h"
24#include "llvm/ADT/PointerIntPair.h"
25#include "llvm/ADT/PointerUnion.h"
26#include "llvm/ADT/iterator.h"
27#include "llvm/ADT/iterator_range.h"
28#include "llvm/Support/Casting.h"
29#include "llvm/Support/Compiler.h"
30#include "llvm/Support/PrettyStackTrace.h"
31#include "llvm/Support/VersionTuple.h"
32#include <algorithm>
33#include <cassert>
34#include <cstddef>
35#include <iterator>
36#include <string>
37#include <type_traits>
38#include <utility>
39
40namespace clang {
41
42class ASTContext;
43class ASTMutationListener;
44class Attr;
45class BlockDecl;
46class DeclContext;
47class ExternalSourceSymbolAttr;
48class FunctionDecl;
49class FunctionType;
50class IdentifierInfo;
51enum Linkage : unsigned char;
52class LinkageSpecDecl;
53class Module;
54class NamedDecl;
55class ObjCCategoryDecl;
56class ObjCCategoryImplDecl;
57class ObjCContainerDecl;
58class ObjCImplDecl;
59class ObjCImplementationDecl;
60class ObjCInterfaceDecl;
61class ObjCMethodDecl;
62class ObjCProtocolDecl;
63struct PrintingPolicy;
64class RecordDecl;
65class SourceManager;
66class Stmt;
67class StoredDeclsMap;
68class TemplateDecl;
69class TemplateParameterList;
70class TranslationUnitDecl;
71class UsingDirectiveDecl;
72
73/// Captures the result of checking the availability of a
74/// declaration.
75enum AvailabilityResult {
76 AR_Available = 0,
77 AR_NotYetIntroduced,
78 AR_Deprecated,
79 AR_Unavailable
80};
81
82/// Decl - This represents one declaration (or definition), e.g. a variable,
83/// typedef, function, struct, etc.
84///
85/// Note: There are objects tacked on before the *beginning* of Decl
86/// (and its subclasses) in its Decl::operator new(). Proper alignment
87/// of all subclasses (not requiring more than the alignment of Decl) is
88/// asserted in DeclBase.cpp.
89class alignas(8) Decl {
90public:
91 /// Lists the kind of concrete classes of Decl.
92 enum Kind {
93#define DECL(DERIVED, BASE) DERIVED,
94#define ABSTRACT_DECL(DECL)
95#define DECL_RANGE(BASE, START, END) \
96 first##BASE = START, last##BASE = END,
97#define LAST_DECL_RANGE(BASE, START, END) \
98 first##BASE = START, last##BASE = END
99#include "clang/AST/DeclNodes.inc"
100 };
101
102 /// A placeholder type used to construct an empty shell of a
103 /// decl-derived type that will be filled in later (e.g., by some
104 /// deserialization method).
105 struct EmptyShell {};
106
107 /// IdentifierNamespace - The different namespaces in which
108 /// declarations may appear. According to C99 6.2.3, there are
109 /// four namespaces, labels, tags, members and ordinary
110 /// identifiers. C++ describes lookup completely differently:
111 /// certain lookups merely "ignore" certain kinds of declarations,
112 /// usually based on whether the declaration is of a type, etc.
113 ///
114 /// These are meant as bitmasks, so that searches in
115 /// C++ can look into the "tag" namespace during ordinary lookup.
116 ///
117 /// Decl currently provides 15 bits of IDNS bits.
118 enum IdentifierNamespace {
119 /// Labels, declared with 'x:' and referenced with 'goto x'.
120 IDNS_Label = 0x0001,
121
122 /// Tags, declared with 'struct foo;' and referenced with
123 /// 'struct foo'. All tags are also types. This is what
124 /// elaborated-type-specifiers look for in C.
125 /// This also contains names that conflict with tags in the
126 /// same scope but that are otherwise ordinary names (non-type
127 /// template parameters and indirect field declarations).
128 IDNS_Tag = 0x0002,
129
130 /// Types, declared with 'struct foo', typedefs, etc.
131 /// This is what elaborated-type-specifiers look for in C++,
132 /// but note that it's ill-formed to find a non-tag.
133 IDNS_Type = 0x0004,
134
135 /// Members, declared with object declarations within tag
136 /// definitions. In C, these can only be found by "qualified"
137 /// lookup in member expressions. In C++, they're found by
138 /// normal lookup.
139 IDNS_Member = 0x0008,
140
141 /// Namespaces, declared with 'namespace foo {}'.
142 /// Lookup for nested-name-specifiers find these.
143 IDNS_Namespace = 0x0010,
144
145 /// Ordinary names. In C, everything that's not a label, tag,
146 /// member, or function-local extern ends up here.
147 IDNS_Ordinary = 0x0020,
148
149 /// Objective C \@protocol.
150 IDNS_ObjCProtocol = 0x0040,
151
152 /// This declaration is a friend function. A friend function
153 /// declaration is always in this namespace but may also be in
154 /// IDNS_Ordinary if it was previously declared.
155 IDNS_OrdinaryFriend = 0x0080,
156
157 /// This declaration is a friend class. A friend class
158 /// declaration is always in this namespace but may also be in
159 /// IDNS_Tag|IDNS_Type if it was previously declared.
160 IDNS_TagFriend = 0x0100,
161
162 /// This declaration is a using declaration. A using declaration
163 /// *introduces* a number of other declarations into the current
164 /// scope, and those declarations use the IDNS of their targets,
165 /// but the actual using declarations go in this namespace.
166 IDNS_Using = 0x0200,
167
168 /// This declaration is a C++ operator declared in a non-class
169 /// context. All such operators are also in IDNS_Ordinary.
170 /// C++ lexical operator lookup looks for these.
171 IDNS_NonMemberOperator = 0x0400,
172
173 /// This declaration is a function-local extern declaration of a
174 /// variable or function. This may also be IDNS_Ordinary if it
175 /// has been declared outside any function. These act mostly like
176 /// invisible friend declarations, but are also visible to unqualified
177 /// lookup within the scope of the declaring function.
178 IDNS_LocalExtern = 0x0800,
179
180 /// This declaration is an OpenMP user defined reduction construction.
181 IDNS_OMPReduction = 0x1000,
182
183 /// This declaration is an OpenMP user defined mapper.
184 IDNS_OMPMapper = 0x2000,
185 };
186
187 /// ObjCDeclQualifier - 'Qualifiers' written next to the return and
188 /// parameter types in method declarations. Other than remembering
189 /// them and mangling them into the method's signature string, these
190 /// are ignored by the compiler; they are consumed by certain
191 /// remote-messaging frameworks.
192 ///
193 /// in, inout, and out are mutually exclusive and apply only to
194 /// method parameters. bycopy and byref are mutually exclusive and
195 /// apply only to method parameters (?). oneway applies only to
196 /// results. All of these expect their corresponding parameter to
197 /// have a particular type. None of this is currently enforced by
198 /// clang.
199 ///
200 /// This should be kept in sync with ObjCDeclSpec::ObjCDeclQualifier.
201 enum ObjCDeclQualifier {
202 OBJC_TQ_None = 0x0,
203 OBJC_TQ_In = 0x1,
204 OBJC_TQ_Inout = 0x2,
205 OBJC_TQ_Out = 0x4,
206 OBJC_TQ_Bycopy = 0x8,
207 OBJC_TQ_Byref = 0x10,
208 OBJC_TQ_Oneway = 0x20,
209
210 /// The nullability qualifier is set when the nullability of the
211 /// result or parameter was expressed via a context-sensitive
212 /// keyword.
213 OBJC_TQ_CSNullability = 0x40
214 };
215
216 /// The kind of ownership a declaration has, for visibility purposes.
217 /// This enumeration is designed such that higher values represent higher
218 /// levels of name hiding.
219 enum class ModuleOwnershipKind : unsigned {
220 /// This declaration is not owned by a module.
221 Unowned,
222
223 /// This declaration has an owning module, but is globally visible
224 /// (typically because its owning module is visible and we know that
225 /// modules cannot later become hidden in this compilation).
226 /// After serialization and deserialization, this will be converted
227 /// to VisibleWhenImported.
228 Visible,
229
230 /// This declaration has an owning module, and is visible when that
231 /// module is imported.
232 VisibleWhenImported,
233
234 /// This declaration has an owning module, but is only visible to
235 /// lookups that occur within that module.
236 ModulePrivate
237 };
238
239protected:
240 /// The next declaration within the same lexical
241 /// DeclContext. These pointers form the linked list that is
242 /// traversed via DeclContext's decls_begin()/decls_end().
243 ///
244 /// The extra two bits are used for the ModuleOwnershipKind.
245 llvm::PointerIntPair<Decl *, 2, ModuleOwnershipKind> NextInContextAndBits;
246
247private:
248 friend class DeclContext;
249
250 struct MultipleDC {
251 DeclContext *SemanticDC;
252 DeclContext *LexicalDC;
253 };
254
255 /// DeclCtx - Holds either a DeclContext* or a MultipleDC*.
256 /// For declarations that don't contain C++ scope specifiers, it contains
257 /// the DeclContext where the Decl was declared.
258 /// For declarations with C++ scope specifiers, it contains a MultipleDC*
259 /// with the context where it semantically belongs (SemanticDC) and the
260 /// context where it was lexically declared (LexicalDC).
261 /// e.g.:
262 ///
263 /// namespace A {
264 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
265 /// }
266 /// void A::f(); // SemanticDC == namespace 'A'
267 /// // LexicalDC == global namespace
268 llvm::PointerUnion<DeclContext*, MultipleDC*> DeclCtx;
269
270 bool isInSemaDC() const { return DeclCtx.is<DeclContext*>(); }
271 bool isOutOfSemaDC() const { return DeclCtx.is<MultipleDC*>(); }
272
273 MultipleDC *getMultipleDC() const {
274 return DeclCtx.get<MultipleDC*>();
275 }
276
277 DeclContext *getSemanticDC() const {
278 return DeclCtx.get<DeclContext*>();
279 }
280
281 /// Loc - The location of this decl.
282 SourceLocation Loc;
283
284 /// DeclKind - This indicates which class this is.
285 unsigned DeclKind : 7;
286
287 /// InvalidDecl - This indicates a semantic error occurred.
288 unsigned InvalidDecl : 1;
289
290 /// HasAttrs - This indicates whether the decl has attributes or not.
291 unsigned HasAttrs : 1;
292
293 /// Implicit - Whether this declaration was implicitly generated by
294 /// the implementation rather than explicitly written by the user.
295 unsigned Implicit : 1;
296
297 /// Whether this declaration was "used", meaning that a definition is
298 /// required.
299 unsigned Used : 1;
300
301 /// Whether this declaration was "referenced".
302 /// The difference with 'Used' is whether the reference appears in a
303 /// evaluated context or not, e.g. functions used in uninstantiated templates
304 /// are regarded as "referenced" but not "used".
305 unsigned Referenced : 1;
306
307 /// Whether this declaration is a top-level declaration (function,
308 /// global variable, etc.) that is lexically inside an objc container
309 /// definition.
310 unsigned TopLevelDeclInObjCContainer : 1;
311
312 /// Whether statistic collection is enabled.
313 static bool StatisticsEnabled;
314
315protected:
316 friend class ASTDeclReader;
317 friend class ASTDeclWriter;
318 friend class ASTNodeImporter;
319 friend class ASTReader;
320 friend class CXXClassMemberWrapper;
321 friend class LinkageComputer;
322 template<typename decl_type> friend class Redeclarable;
323
324 /// Access - Used by C++ decls for the access specifier.
325 // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum
326 unsigned Access : 2;
327
328 /// Whether this declaration was loaded from an AST file.
329 unsigned FromASTFile : 1;
330
331 /// IdentifierNamespace - This specifies what IDNS_* namespace this lives in.
332 unsigned IdentifierNamespace : 14;
333
334 /// If 0, we have not computed the linkage of this declaration.
335 /// Otherwise, it is the linkage + 1.
336 mutable unsigned CacheValidAndLinkage : 3;
337
338 /// Allocate memory for a deserialized declaration.
339 ///
340 /// This routine must be used to allocate memory for any declaration that is
341 /// deserialized from a module file.
342 ///
343 /// \param Size The size of the allocated object.
344 /// \param Ctx The context in which we will allocate memory.
345 /// \param ID The global ID of the deserialized declaration.
346 /// \param Extra The amount of extra space to allocate after the object.
347 void *operator new(std::size_t Size, const ASTContext &Ctx, unsigned ID,
348 std::size_t Extra = 0);
349
350 /// Allocate memory for a non-deserialized declaration.
351 void *operator new(std::size_t Size, const ASTContext &Ctx,
352 DeclContext *Parent, std::size_t Extra = 0);
353
354private:
355 bool AccessDeclContextSanity() const;
356
357 /// Get the module ownership kind to use for a local lexical child of \p DC,
358 /// which may be either a local or (rarely) an imported declaration.
359 static ModuleOwnershipKind getModuleOwnershipKindForChildOf(DeclContext *DC) {
360 if (DC) {
361 auto *D = cast<Decl>(DC);
362 auto MOK = D->getModuleOwnershipKind();
363 if (MOK != ModuleOwnershipKind::Unowned &&
364 (!D->isFromASTFile() || D->hasLocalOwningModuleStorage()))
365 return MOK;
366 // If D is not local and we have no local module storage, then we don't
367 // need to track module ownership at all.
368 }
369 return ModuleOwnershipKind::Unowned;
370 }
371
372public:
373 Decl() = delete;
374 Decl(const Decl&) = delete;
375 Decl(Decl &&) = delete;
376 Decl &operator=(const Decl&) = delete;
377 Decl &operator=(Decl&&) = delete;
378
379protected:
380 Decl(Kind DK, DeclContext *DC, SourceLocation L)
381 : NextInContextAndBits(nullptr, getModuleOwnershipKindForChildOf(DC)),
382 DeclCtx(DC), Loc(L), DeclKind(DK), InvalidDecl(false), HasAttrs(false),
383 Implicit(false), Used(false), Referenced(false),
384 TopLevelDeclInObjCContainer(false), Access(AS_none), FromASTFile(0),
385 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
386 CacheValidAndLinkage(0) {
387 if (StatisticsEnabled) add(DK);
388 }
389
390 Decl(Kind DK, EmptyShell Empty)
391 : DeclKind(DK), InvalidDecl(false), HasAttrs(false), Implicit(false),
392 Used(false), Referenced(false), TopLevelDeclInObjCContainer(false),
393 Access(AS_none), FromASTFile(0),
394 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
395 CacheValidAndLinkage(0) {
396 if (StatisticsEnabled) add(DK);
397 }
398
399 virtual ~Decl();
400
401 /// Update a potentially out-of-date declaration.
402 void updateOutOfDate(IdentifierInfo &II) const;
403
404 Linkage getCachedLinkage() const {
405 return Linkage(CacheValidAndLinkage - 1);
406 }
407
408 void setCachedLinkage(Linkage L) const {
409 CacheValidAndLinkage = L + 1;
410 }
411
412 bool hasCachedLinkage() const {
413 return CacheValidAndLinkage;
414 }
415
416public:
417 /// Source range that this declaration covers.
418 virtual SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) {
419 return SourceRange(getLocation(), getLocation());
420 }
421
422 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
423 return getSourceRange().getBegin();
424 }
425
426 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
427 return getSourceRange().getEnd();
428 }
429
430 SourceLocation getLocation() const { return Loc; }
431 void setLocation(SourceLocation L) { Loc = L; }
432
433 Kind getKind() const { return static_cast<Kind>(DeclKind); }
434 const char *getDeclKindName() const;
435
436 Decl *getNextDeclInContext() { return NextInContextAndBits.getPointer(); }
437 const Decl *getNextDeclInContext() const {return NextInContextAndBits.getPointer();}
438
439 DeclContext *getDeclContext() {
440 if (isInSemaDC())
441 return getSemanticDC();
442 return getMultipleDC()->SemanticDC;
443 }
444 const DeclContext *getDeclContext() const {
445 return const_cast<Decl*>(this)->getDeclContext();
446 }
447
448 /// Find the innermost non-closure ancestor of this declaration,
449 /// walking up through blocks, lambdas, etc. If that ancestor is
450 /// not a code context (!isFunctionOrMethod()), returns null.
451 ///
452 /// A declaration may be its own non-closure context.
453 Decl *getNonClosureContext();
454 const Decl *getNonClosureContext() const {
455 return const_cast<Decl*>(this)->getNonClosureContext();
456 }
457
458 TranslationUnitDecl *getTranslationUnitDecl();
459 const TranslationUnitDecl *getTranslationUnitDecl() const {
460 return const_cast<Decl*>(this)->getTranslationUnitDecl();
461 }
462
463 bool isInAnonymousNamespace() const;
464
465 bool isInStdNamespace() const;
466
467 ASTContext &getASTContext() const LLVM_READONLY__attribute__((__pure__));
468
469 /// Helper to get the language options from the ASTContext.
470 /// Defined out of line to avoid depending on ASTContext.h.
471 const LangOptions &getLangOpts() const LLVM_READONLY__attribute__((__pure__));
472
473 void setAccess(AccessSpecifier AS) {
474 Access = AS;
475 assert(AccessDeclContextSanity())((AccessDeclContextSanity()) ? static_cast<void> (0) : __assert_fail
("AccessDeclContextSanity()", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 475, __PRETTY_FUNCTION__))
;
476 }
477
478 AccessSpecifier getAccess() const {
479 assert(AccessDeclContextSanity())((AccessDeclContextSanity()) ? static_cast<void> (0) : __assert_fail
("AccessDeclContextSanity()", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 479, __PRETTY_FUNCTION__))
;
480 return AccessSpecifier(Access);
481 }
482
483 /// Retrieve the access specifier for this declaration, even though
484 /// it may not yet have been properly set.
485 AccessSpecifier getAccessUnsafe() const {
486 return AccessSpecifier(Access);
487 }
488
489 bool hasAttrs() const { return HasAttrs; }
490
491 void setAttrs(const AttrVec& Attrs) {
492 return setAttrsImpl(Attrs, getASTContext());
493 }
494
495 AttrVec &getAttrs() {
496 return const_cast<AttrVec&>(const_cast<const Decl*>(this)->getAttrs());
497 }
498
499 const AttrVec &getAttrs() const;
500 void dropAttrs();
501 void addAttr(Attr *A);
502
503 using attr_iterator = AttrVec::const_iterator;
504 using attr_range = llvm::iterator_range<attr_iterator>;
505
506 attr_range attrs() const {
507 return attr_range(attr_begin(), attr_end());
508 }
509
510 attr_iterator attr_begin() const {
511 return hasAttrs() ? getAttrs().begin() : nullptr;
512 }
513 attr_iterator attr_end() const {
514 return hasAttrs() ? getAttrs().end() : nullptr;
515 }
516
517 template <typename T>
518 void dropAttr() {
519 if (!HasAttrs) return;
520
521 AttrVec &Vec = getAttrs();
522 llvm::erase_if(Vec, [](Attr *A) { return isa<T>(A); });
523
524 if (Vec.empty())
525 HasAttrs = false;
526 }
527
528 template <typename T>
529 llvm::iterator_range<specific_attr_iterator<T>> specific_attrs() const {
530 return llvm::make_range(specific_attr_begin<T>(), specific_attr_end<T>());
531 }
532
533 template <typename T>
534 specific_attr_iterator<T> specific_attr_begin() const {
535 return specific_attr_iterator<T>(attr_begin());
536 }
537
538 template <typename T>
539 specific_attr_iterator<T> specific_attr_end() const {
540 return specific_attr_iterator<T>(attr_end());
541 }
542
543 template<typename T> T *getAttr() const {
544 return hasAttrs() ? getSpecificAttr<T>(getAttrs()) : nullptr;
545 }
546
547 template<typename T> bool hasAttr() const {
548 return hasAttrs() && hasSpecificAttr<T>(getAttrs());
11
Assuming the condition is false
12
Returning zero, which participates in a condition later
549 }
550
551 /// getMaxAlignment - return the maximum alignment specified by attributes
552 /// on this decl, 0 if there are none.
553 unsigned getMaxAlignment() const;
554
555 /// setInvalidDecl - Indicates the Decl had a semantic error. This
556 /// allows for graceful error recovery.
557 void setInvalidDecl(bool Invalid = true);
558 bool isInvalidDecl() const { return (bool) InvalidDecl; }
559
560 /// isImplicit - Indicates whether the declaration was implicitly
561 /// generated by the implementation. If false, this declaration
562 /// was written explicitly in the source code.
563 bool isImplicit() const { return Implicit; }
564 void setImplicit(bool I = true) { Implicit = I; }
565
566 /// Whether *any* (re-)declaration of the entity was used, meaning that
567 /// a definition is required.
568 ///
569 /// \param CheckUsedAttr When true, also consider the "used" attribute
570 /// (in addition to the "used" bit set by \c setUsed()) when determining
571 /// whether the function is used.
572 bool isUsed(bool CheckUsedAttr = true) const;
573
574 /// Set whether the declaration is used, in the sense of odr-use.
575 ///
576 /// This should only be used immediately after creating a declaration.
577 /// It intentionally doesn't notify any listeners.
578 void setIsUsed() { getCanonicalDecl()->Used = true; }
579
580 /// Mark the declaration used, in the sense of odr-use.
581 ///
582 /// This notifies any mutation listeners in addition to setting a bit
583 /// indicating the declaration is used.
584 void markUsed(ASTContext &C);
585
586 /// Whether any declaration of this entity was referenced.
587 bool isReferenced() const;
588
589 /// Whether this declaration was referenced. This should not be relied
590 /// upon for anything other than debugging.
591 bool isThisDeclarationReferenced() const { return Referenced; }
592
593 void setReferenced(bool R = true) { Referenced = R; }
594
595 /// Whether this declaration is a top-level declaration (function,
596 /// global variable, etc.) that is lexically inside an objc container
597 /// definition.
598 bool isTopLevelDeclInObjCContainer() const {
599 return TopLevelDeclInObjCContainer;
600 }
601
602 void setTopLevelDeclInObjCContainer(bool V = true) {
603 TopLevelDeclInObjCContainer = V;
604 }
605
606 /// Looks on this and related declarations for an applicable
607 /// external source symbol attribute.
608 ExternalSourceSymbolAttr *getExternalSourceSymbolAttr() const;
609
610 /// Whether this declaration was marked as being private to the
611 /// module in which it was defined.
612 bool isModulePrivate() const {
613 return getModuleOwnershipKind() == ModuleOwnershipKind::ModulePrivate;
614 }
615
616 /// Return true if this declaration has an attribute which acts as
617 /// definition of the entity, such as 'alias' or 'ifunc'.
618 bool hasDefiningAttr() const;
619
620 /// Return this declaration's defining attribute if it has one.
621 const Attr *getDefiningAttr() const;
622
623protected:
624 /// Specify that this declaration was marked as being private
625 /// to the module in which it was defined.
626 void setModulePrivate() {
627 // The module-private specifier has no effect on unowned declarations.
628 // FIXME: We should track this in some way for source fidelity.
629 if (getModuleOwnershipKind() == ModuleOwnershipKind::Unowned)
630 return;
631 setModuleOwnershipKind(ModuleOwnershipKind::ModulePrivate);
632 }
633
634public:
635 /// Set the FromASTFile flag. This indicates that this declaration
636 /// was deserialized and not parsed from source code and enables
637 /// features such as module ownership information.
638 void setFromASTFile() {
639 FromASTFile = true;
640 }
641
642 /// Set the owning module ID. This may only be called for
643 /// deserialized Decls.
644 void setOwningModuleID(unsigned ID) {
645 assert(isFromASTFile() && "Only works on a deserialized declaration")((isFromASTFile() && "Only works on a deserialized declaration"
) ? static_cast<void> (0) : __assert_fail ("isFromASTFile() && \"Only works on a deserialized declaration\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 645, __PRETTY_FUNCTION__))
;
646 *((unsigned*)this - 2) = ID;
647 }
648
649public:
650 /// Determine the availability of the given declaration.
651 ///
652 /// This routine will determine the most restrictive availability of
653 /// the given declaration (e.g., preferring 'unavailable' to
654 /// 'deprecated').
655 ///
656 /// \param Message If non-NULL and the result is not \c
657 /// AR_Available, will be set to a (possibly empty) message
658 /// describing why the declaration has not been introduced, is
659 /// deprecated, or is unavailable.
660 ///
661 /// \param EnclosingVersion The version to compare with. If empty, assume the
662 /// deployment target version.
663 ///
664 /// \param RealizedPlatform If non-NULL and the availability result is found
665 /// in an available attribute it will set to the platform which is written in
666 /// the available attribute.
667 AvailabilityResult
668 getAvailability(std::string *Message = nullptr,
669 VersionTuple EnclosingVersion = VersionTuple(),
670 StringRef *RealizedPlatform = nullptr) const;
671
672 /// Retrieve the version of the target platform in which this
673 /// declaration was introduced.
674 ///
675 /// \returns An empty version tuple if this declaration has no 'introduced'
676 /// availability attributes, or the version tuple that's specified in the
677 /// attribute otherwise.
678 VersionTuple getVersionIntroduced() const;
679
680 /// Determine whether this declaration is marked 'deprecated'.
681 ///
682 /// \param Message If non-NULL and the declaration is deprecated,
683 /// this will be set to the message describing why the declaration
684 /// was deprecated (which may be empty).
685 bool isDeprecated(std::string *Message = nullptr) const {
686 return getAvailability(Message) == AR_Deprecated;
687 }
688
689 /// Determine whether this declaration is marked 'unavailable'.
690 ///
691 /// \param Message If non-NULL and the declaration is unavailable,
692 /// this will be set to the message describing why the declaration
693 /// was made unavailable (which may be empty).
694 bool isUnavailable(std::string *Message = nullptr) const {
695 return getAvailability(Message) == AR_Unavailable;
696 }
697
698 /// Determine whether this is a weak-imported symbol.
699 ///
700 /// Weak-imported symbols are typically marked with the
701 /// 'weak_import' attribute, but may also be marked with an
702 /// 'availability' attribute where we're targing a platform prior to
703 /// the introduction of this feature.
704 bool isWeakImported() const;
705
706 /// Determines whether this symbol can be weak-imported,
707 /// e.g., whether it would be well-formed to add the weak_import
708 /// attribute.
709 ///
710 /// \param IsDefinition Set to \c true to indicate that this
711 /// declaration cannot be weak-imported because it has a definition.
712 bool canBeWeakImported(bool &IsDefinition) const;
713
714 /// Determine whether this declaration came from an AST file (such as
715 /// a precompiled header or module) rather than having been parsed.
716 bool isFromASTFile() const { return FromASTFile; }
717
718 /// Retrieve the global declaration ID associated with this
719 /// declaration, which specifies where this Decl was loaded from.
720 unsigned getGlobalID() const {
721 if (isFromASTFile())
722 return *((const unsigned*)this - 1);
723 return 0;
724 }
725
726 /// Retrieve the global ID of the module that owns this particular
727 /// declaration.
728 unsigned getOwningModuleID() const {
729 if (isFromASTFile())
730 return *((const unsigned*)this - 2);
731 return 0;
732 }
733
734private:
735 Module *getOwningModuleSlow() const;
736
737protected:
738 bool hasLocalOwningModuleStorage() const;
739
740public:
741 /// Get the imported owning module, if this decl is from an imported
742 /// (non-local) module.
743 Module *getImportedOwningModule() const {
744 if (!isFromASTFile() || !hasOwningModule())
745 return nullptr;
746
747 return getOwningModuleSlow();
748 }
749
750 /// Get the local owning module, if known. Returns nullptr if owner is
751 /// not yet known or declaration is not from a module.
752 Module *getLocalOwningModule() const {
753 if (isFromASTFile() || !hasOwningModule())
754 return nullptr;
755
756 assert(hasLocalOwningModuleStorage() &&((hasLocalOwningModuleStorage() && "owned local decl but no local module storage"
) ? static_cast<void> (0) : __assert_fail ("hasLocalOwningModuleStorage() && \"owned local decl but no local module storage\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 757, __PRETTY_FUNCTION__))
757 "owned local decl but no local module storage")((hasLocalOwningModuleStorage() && "owned local decl but no local module storage"
) ? static_cast<void> (0) : __assert_fail ("hasLocalOwningModuleStorage() && \"owned local decl but no local module storage\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 757, __PRETTY_FUNCTION__))
;
758 return reinterpret_cast<Module *const *>(this)[-1];
759 }
760 void setLocalOwningModule(Module *M) {
761 assert(!isFromASTFile() && hasOwningModule() &&((!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage
() && "should not have a cached owning module") ? static_cast
<void> (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 763, __PRETTY_FUNCTION__))
762 hasLocalOwningModuleStorage() &&((!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage
() && "should not have a cached owning module") ? static_cast
<void> (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 763, __PRETTY_FUNCTION__))
763 "should not have a cached owning module")((!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage
() && "should not have a cached owning module") ? static_cast
<void> (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 763, __PRETTY_FUNCTION__))
;
764 reinterpret_cast<Module **>(this)[-1] = M;
765 }
766
767 /// Is this declaration owned by some module?
768 bool hasOwningModule() const {
769 return getModuleOwnershipKind() != ModuleOwnershipKind::Unowned;
770 }
771
772 /// Get the module that owns this declaration (for visibility purposes).
773 Module *getOwningModule() const {
774 return isFromASTFile() ? getImportedOwningModule() : getLocalOwningModule();
775 }
776
777 /// Get the module that owns this declaration for linkage purposes.
778 /// There only ever is such a module under the C++ Modules TS.
779 ///
780 /// \param IgnoreLinkage Ignore the linkage of the entity; assume that
781 /// all declarations in a global module fragment are unowned.
782 Module *getOwningModuleForLinkage(bool IgnoreLinkage = false) const;
783
784 /// Determine whether this declaration is definitely visible to name lookup,
785 /// independent of whether the owning module is visible.
786 /// Note: The declaration may be visible even if this returns \c false if the
787 /// owning module is visible within the query context. This is a low-level
788 /// helper function; most code should be calling Sema::isVisible() instead.
789 bool isUnconditionallyVisible() const {
790 return (int)getModuleOwnershipKind() <= (int)ModuleOwnershipKind::Visible;
791 }
792
793 /// Set that this declaration is globally visible, even if it came from a
794 /// module that is not visible.
795 void setVisibleDespiteOwningModule() {
796 if (!isUnconditionallyVisible())
797 setModuleOwnershipKind(ModuleOwnershipKind::Visible);
798 }
799
800 /// Get the kind of module ownership for this declaration.
801 ModuleOwnershipKind getModuleOwnershipKind() const {
802 return NextInContextAndBits.getInt();
803 }
804
805 /// Set whether this declaration is hidden from name lookup.
806 void setModuleOwnershipKind(ModuleOwnershipKind MOK) {
807 assert(!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&((!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&
MOK != ModuleOwnershipKind::Unowned && !isFromASTFile
() && !hasLocalOwningModuleStorage()) && "no storage available for owning module for this declaration"
) ? static_cast<void> (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 810, __PRETTY_FUNCTION__))
808 MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() &&((!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&
MOK != ModuleOwnershipKind::Unowned && !isFromASTFile
() && !hasLocalOwningModuleStorage()) && "no storage available for owning module for this declaration"
) ? static_cast<void> (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 810, __PRETTY_FUNCTION__))
809 !hasLocalOwningModuleStorage()) &&((!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&
MOK != ModuleOwnershipKind::Unowned && !isFromASTFile
() && !hasLocalOwningModuleStorage()) && "no storage available for owning module for this declaration"
) ? static_cast<void> (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 810, __PRETTY_FUNCTION__))
810 "no storage available for owning module for this declaration")((!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&
MOK != ModuleOwnershipKind::Unowned && !isFromASTFile
() && !hasLocalOwningModuleStorage()) && "no storage available for owning module for this declaration"
) ? static_cast<void> (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 810, __PRETTY_FUNCTION__))
;
811 NextInContextAndBits.setInt(MOK);
812 }
813
814 unsigned getIdentifierNamespace() const {
815 return IdentifierNamespace;
816 }
817
818 bool isInIdentifierNamespace(unsigned NS) const {
819 return getIdentifierNamespace() & NS;
820 }
821
822 static unsigned getIdentifierNamespaceForKind(Kind DK);
823
824 bool hasTagIdentifierNamespace() const {
825 return isTagIdentifierNamespace(getIdentifierNamespace());
826 }
827
828 static bool isTagIdentifierNamespace(unsigned NS) {
829 // TagDecls have Tag and Type set and may also have TagFriend.
830 return (NS & ~IDNS_TagFriend) == (IDNS_Tag | IDNS_Type);
831 }
832
833 /// getLexicalDeclContext - The declaration context where this Decl was
834 /// lexically declared (LexicalDC). May be different from
835 /// getDeclContext() (SemanticDC).
836 /// e.g.:
837 ///
838 /// namespace A {
839 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
840 /// }
841 /// void A::f(); // SemanticDC == namespace 'A'
842 /// // LexicalDC == global namespace
843 DeclContext *getLexicalDeclContext() {
844 if (isInSemaDC())
845 return getSemanticDC();
846 return getMultipleDC()->LexicalDC;
847 }
848 const DeclContext *getLexicalDeclContext() const {
849 return const_cast<Decl*>(this)->getLexicalDeclContext();
850 }
851
852 /// Determine whether this declaration is declared out of line (outside its
853 /// semantic context).
854 virtual bool isOutOfLine() const;
855
856 /// setDeclContext - Set both the semantic and lexical DeclContext
857 /// to DC.
858 void setDeclContext(DeclContext *DC);
859
860 void setLexicalDeclContext(DeclContext *DC);
861
862 /// Determine whether this declaration is a templated entity (whether it is
863 // within the scope of a template parameter).
864 bool isTemplated() const;
865
866 /// Determine the number of levels of template parameter surrounding this
867 /// declaration.
868 unsigned getTemplateDepth() const;
869
870 /// isDefinedOutsideFunctionOrMethod - This predicate returns true if this
871 /// scoped decl is defined outside the current function or method. This is
872 /// roughly global variables and functions, but also handles enums (which
873 /// could be defined inside or outside a function etc).
874 bool isDefinedOutsideFunctionOrMethod() const {
875 return getParentFunctionOrMethod() == nullptr;
876 }
877
878 /// Determine whether a substitution into this declaration would occur as
879 /// part of a substitution into a dependent local scope. Such a substitution
880 /// transitively substitutes into all constructs nested within this
881 /// declaration.
882 ///
883 /// This recognizes non-defining declarations as well as members of local
884 /// classes and lambdas:
885 /// \code
886 /// template<typename T> void foo() { void bar(); }
887 /// template<typename T> void foo2() { class ABC { void bar(); }; }
888 /// template<typename T> inline int x = [](){ return 0; }();
889 /// \endcode
890 bool isInLocalScopeForInstantiation() const;
891
892 /// If this decl is defined inside a function/method/block it returns
893 /// the corresponding DeclContext, otherwise it returns null.
894 const DeclContext *getParentFunctionOrMethod() const;
895 DeclContext *getParentFunctionOrMethod() {
896 return const_cast<DeclContext*>(
897 const_cast<const Decl*>(this)->getParentFunctionOrMethod());
898 }
899
900 /// Retrieves the "canonical" declaration of the given declaration.
901 virtual Decl *getCanonicalDecl() { return this; }
902 const Decl *getCanonicalDecl() const {
903 return const_cast<Decl*>(this)->getCanonicalDecl();
904 }
905
906 /// Whether this particular Decl is a canonical one.
907 bool isCanonicalDecl() const { return getCanonicalDecl() == this; }
908
909protected:
910 /// Returns the next redeclaration or itself if this is the only decl.
911 ///
912 /// Decl subclasses that can be redeclared should override this method so that
913 /// Decl::redecl_iterator can iterate over them.
914 virtual Decl *getNextRedeclarationImpl() { return this; }
915
916 /// Implementation of getPreviousDecl(), to be overridden by any
917 /// subclass that has a redeclaration chain.
918 virtual Decl *getPreviousDeclImpl() { return nullptr; }
919
920 /// Implementation of getMostRecentDecl(), to be overridden by any
921 /// subclass that has a redeclaration chain.
922 virtual Decl *getMostRecentDeclImpl() { return this; }
923
924public:
925 /// Iterates through all the redeclarations of the same decl.
926 class redecl_iterator {
927 /// Current - The current declaration.
928 Decl *Current = nullptr;
929 Decl *Starter;
930
931 public:
932 using value_type = Decl *;
933 using reference = const value_type &;
934 using pointer = const value_type *;
935 using iterator_category = std::forward_iterator_tag;
936 using difference_type = std::ptrdiff_t;
937
938 redecl_iterator() = default;
939 explicit redecl_iterator(Decl *C) : Current(C), Starter(C) {}
940
941 reference operator*() const { return Current; }
942 value_type operator->() const { return Current; }
943
944 redecl_iterator& operator++() {
945 assert(Current && "Advancing while iterator has reached end")((Current && "Advancing while iterator has reached end"
) ? static_cast<void> (0) : __assert_fail ("Current && \"Advancing while iterator has reached end\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 945, __PRETTY_FUNCTION__))
;
946 // Get either previous decl or latest decl.
947 Decl *Next = Current->getNextRedeclarationImpl();
948 assert(Next && "Should return next redeclaration or itself, never null!")((Next && "Should return next redeclaration or itself, never null!"
) ? static_cast<void> (0) : __assert_fail ("Next && \"Should return next redeclaration or itself, never null!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 948, __PRETTY_FUNCTION__))
;
949 Current = (Next != Starter) ? Next : nullptr;
950 return *this;
951 }
952
953 redecl_iterator operator++(int) {
954 redecl_iterator tmp(*this);
955 ++(*this);
956 return tmp;
957 }
958
959 friend bool operator==(redecl_iterator x, redecl_iterator y) {
960 return x.Current == y.Current;
961 }
962
963 friend bool operator!=(redecl_iterator x, redecl_iterator y) {
964 return x.Current != y.Current;
965 }
966 };
967
968 using redecl_range = llvm::iterator_range<redecl_iterator>;
969
970 /// Returns an iterator range for all the redeclarations of the same
971 /// decl. It will iterate at least once (when this decl is the only one).
972 redecl_range redecls() const {
973 return redecl_range(redecls_begin(), redecls_end());
974 }
975
976 redecl_iterator redecls_begin() const {
977 return redecl_iterator(const_cast<Decl *>(this));
978 }
979
980 redecl_iterator redecls_end() const { return redecl_iterator(); }
981
982 /// Retrieve the previous declaration that declares the same entity
983 /// as this declaration, or NULL if there is no previous declaration.
984 Decl *getPreviousDecl() { return getPreviousDeclImpl(); }
985
986 /// Retrieve the previous declaration that declares the same entity
987 /// as this declaration, or NULL if there is no previous declaration.
988 const Decl *getPreviousDecl() const {
989 return const_cast<Decl *>(this)->getPreviousDeclImpl();
990 }
991
992 /// True if this is the first declaration in its redeclaration chain.
993 bool isFirstDecl() const {
994 return getPreviousDecl() == nullptr;
995 }
996
997 /// Retrieve the most recent declaration that declares the same entity
998 /// as this declaration (which may be this declaration).
999 Decl *getMostRecentDecl() { return getMostRecentDeclImpl(); }
1000
1001 /// Retrieve the most recent declaration that declares the same entity
1002 /// as this declaration (which may be this declaration).
1003 const Decl *getMostRecentDecl() const {
1004 return const_cast<Decl *>(this)->getMostRecentDeclImpl();
1005 }
1006
1007 /// getBody - If this Decl represents a declaration for a body of code,
1008 /// such as a function or method definition, this method returns the
1009 /// top-level Stmt* of that body. Otherwise this method returns null.
1010 virtual Stmt* getBody() const { return nullptr; }
1011
1012 /// Returns true if this \c Decl represents a declaration for a body of
1013 /// code, such as a function or method definition.
1014 /// Note that \c hasBody can also return true if any redeclaration of this
1015 /// \c Decl represents a declaration for a body of code.
1016 virtual bool hasBody() const { return getBody() != nullptr; }
1017
1018 /// getBodyRBrace - Gets the right brace of the body, if a body exists.
1019 /// This works whether the body is a CompoundStmt or a CXXTryStmt.
1020 SourceLocation getBodyRBrace() const;
1021
1022 // global temp stats (until we have a per-module visitor)
1023 static void add(Kind k);
1024 static void EnableStatistics();
1025 static void PrintStats();
1026
1027 /// isTemplateParameter - Determines whether this declaration is a
1028 /// template parameter.
1029 bool isTemplateParameter() const;
1030
1031 /// isTemplateParameter - Determines whether this declaration is a
1032 /// template parameter pack.
1033 bool isTemplateParameterPack() const;
1034
1035 /// Whether this declaration is a parameter pack.
1036 bool isParameterPack() const;
1037
1038 /// returns true if this declaration is a template
1039 bool isTemplateDecl() const;
1040
1041 /// Whether this declaration is a function or function template.
1042 bool isFunctionOrFunctionTemplate() const {
1043 return (DeclKind >= Decl::firstFunction &&
1044 DeclKind <= Decl::lastFunction) ||
1045 DeclKind == FunctionTemplate;
1046 }
1047
1048 /// If this is a declaration that describes some template, this
1049 /// method returns that template declaration.
1050 ///
1051 /// Note that this returns nullptr for partial specializations, because they
1052 /// are not modeled as TemplateDecls. Use getDescribedTemplateParams to handle
1053 /// those cases.
1054 TemplateDecl *getDescribedTemplate() const;
1055
1056 /// If this is a declaration that describes some template or partial
1057 /// specialization, this returns the corresponding template parameter list.
1058 const TemplateParameterList *getDescribedTemplateParams() const;
1059
1060 /// Returns the function itself, or the templated function if this is a
1061 /// function template.
1062 FunctionDecl *getAsFunction() LLVM_READONLY__attribute__((__pure__));
1063
1064 const FunctionDecl *getAsFunction() const {
1065 return const_cast<Decl *>(this)->getAsFunction();
1066 }
1067
1068 /// Changes the namespace of this declaration to reflect that it's
1069 /// a function-local extern declaration.
1070 ///
1071 /// These declarations appear in the lexical context of the extern
1072 /// declaration, but in the semantic context of the enclosing namespace
1073 /// scope.
1074 void setLocalExternDecl() {
1075 Decl *Prev = getPreviousDecl();
1076 IdentifierNamespace &= ~IDNS_Ordinary;
1077
1078 // It's OK for the declaration to still have the "invisible friend" flag or
1079 // the "conflicts with tag declarations in this scope" flag for the outer
1080 // scope.
1081 assert((IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 &&(((IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag
)) == 0 && "namespace is not ordinary") ? static_cast
<void> (0) : __assert_fail ("(IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 && \"namespace is not ordinary\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 1082, __PRETTY_FUNCTION__))
1082 "namespace is not ordinary")(((IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag
)) == 0 && "namespace is not ordinary") ? static_cast
<void> (0) : __assert_fail ("(IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 && \"namespace is not ordinary\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 1082, __PRETTY_FUNCTION__))
;
1083
1084 IdentifierNamespace |= IDNS_LocalExtern;
1085 if (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary)
1086 IdentifierNamespace |= IDNS_Ordinary;
1087 }
1088
1089 /// Determine whether this is a block-scope declaration with linkage.
1090 /// This will either be a local variable declaration declared 'extern', or a
1091 /// local function declaration.
1092 bool isLocalExternDecl() {
1093 return IdentifierNamespace & IDNS_LocalExtern;
1094 }
1095
1096 /// Changes the namespace of this declaration to reflect that it's
1097 /// the object of a friend declaration.
1098 ///
1099 /// These declarations appear in the lexical context of the friending
1100 /// class, but in the semantic context of the actual entity. This property
1101 /// applies only to a specific decl object; other redeclarations of the
1102 /// same entity may not (and probably don't) share this property.
1103 void setObjectOfFriendDecl(bool PerformFriendInjection = false) {
1104 unsigned OldNS = IdentifierNamespace;
1105 assert((OldNS & (IDNS_Tag | IDNS_Ordinary |(((OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend
| IDNS_LocalExtern | IDNS_NonMemberOperator)) && "namespace includes neither ordinary nor tag"
) ? static_cast<void> (0) : __assert_fail ("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes neither ordinary nor tag\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 1108, __PRETTY_FUNCTION__))
1106 IDNS_TagFriend | IDNS_OrdinaryFriend |(((OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend
| IDNS_LocalExtern | IDNS_NonMemberOperator)) && "namespace includes neither ordinary nor tag"
) ? static_cast<void> (0) : __assert_fail ("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes neither ordinary nor tag\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 1108, __PRETTY_FUNCTION__))
1107 IDNS_LocalExtern | IDNS_NonMemberOperator)) &&(((OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend
| IDNS_LocalExtern | IDNS_NonMemberOperator)) && "namespace includes neither ordinary nor tag"
) ? static_cast<void> (0) : __assert_fail ("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes neither ordinary nor tag\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 1108, __PRETTY_FUNCTION__))
1108 "namespace includes neither ordinary nor tag")(((OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend
| IDNS_LocalExtern | IDNS_NonMemberOperator)) && "namespace includes neither ordinary nor tag"
) ? static_cast<void> (0) : __assert_fail ("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes neither ordinary nor tag\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 1108, __PRETTY_FUNCTION__))
;
1109 assert(!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type |((!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend
| IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator
)) && "namespace includes other than ordinary or tag"
) ? static_cast<void> (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes other than ordinary or tag\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 1112, __PRETTY_FUNCTION__))
1110 IDNS_TagFriend | IDNS_OrdinaryFriend |((!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend
| IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator
)) && "namespace includes other than ordinary or tag"
) ? static_cast<void> (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes other than ordinary or tag\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 1112, __PRETTY_FUNCTION__))
1111 IDNS_LocalExtern | IDNS_NonMemberOperator)) &&((!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend
| IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator
)) && "namespace includes other than ordinary or tag"
) ? static_cast<void> (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes other than ordinary or tag\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 1112, __PRETTY_FUNCTION__))
1112 "namespace includes other than ordinary or tag")((!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend
| IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator
)) && "namespace includes other than ordinary or tag"
) ? static_cast<void> (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes other than ordinary or tag\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 1112, __PRETTY_FUNCTION__))
;
1113
1114 Decl *Prev = getPreviousDecl();
1115 IdentifierNamespace &= ~(IDNS_Ordinary | IDNS_Tag | IDNS_Type);
1116
1117 if (OldNS & (IDNS_Tag | IDNS_TagFriend)) {
1118 IdentifierNamespace |= IDNS_TagFriend;
1119 if (PerformFriendInjection ||
1120 (Prev && Prev->getIdentifierNamespace() & IDNS_Tag))
1121 IdentifierNamespace |= IDNS_Tag | IDNS_Type;
1122 }
1123
1124 if (OldNS & (IDNS_Ordinary | IDNS_OrdinaryFriend |
1125 IDNS_LocalExtern | IDNS_NonMemberOperator)) {
1126 IdentifierNamespace |= IDNS_OrdinaryFriend;
1127 if (PerformFriendInjection ||
1128 (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary))
1129 IdentifierNamespace |= IDNS_Ordinary;
1130 }
1131 }
1132
1133 enum FriendObjectKind {
1134 FOK_None, ///< Not a friend object.
1135 FOK_Declared, ///< A friend of a previously-declared entity.
1136 FOK_Undeclared ///< A friend of a previously-undeclared entity.
1137 };
1138
1139 /// Determines whether this declaration is the object of a
1140 /// friend declaration and, if so, what kind.
1141 ///
1142 /// There is currently no direct way to find the associated FriendDecl.
1143 FriendObjectKind getFriendObjectKind() const {
1144 unsigned mask =
1145 (IdentifierNamespace & (IDNS_TagFriend | IDNS_OrdinaryFriend));
1146 if (!mask) return FOK_None;
1147 return (IdentifierNamespace & (IDNS_Tag | IDNS_Ordinary) ? FOK_Declared
1148 : FOK_Undeclared);
1149 }
1150
1151 /// Specifies that this declaration is a C++ overloaded non-member.
1152 void setNonMemberOperator() {
1153 assert(getKind() == Function || getKind() == FunctionTemplate)((getKind() == Function || getKind() == FunctionTemplate) ? static_cast
<void> (0) : __assert_fail ("getKind() == Function || getKind() == FunctionTemplate"
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 1153, __PRETTY_FUNCTION__))
;
1154 assert((IdentifierNamespace & IDNS_Ordinary) &&(((IdentifierNamespace & IDNS_Ordinary) && "visible non-member operators should be in ordinary namespace"
) ? static_cast<void> (0) : __assert_fail ("(IdentifierNamespace & IDNS_Ordinary) && \"visible non-member operators should be in ordinary namespace\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 1155, __PRETTY_FUNCTION__))
1155 "visible non-member operators should be in ordinary namespace")(((IdentifierNamespace & IDNS_Ordinary) && "visible non-member operators should be in ordinary namespace"
) ? static_cast<void> (0) : __assert_fail ("(IdentifierNamespace & IDNS_Ordinary) && \"visible non-member operators should be in ordinary namespace\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 1155, __PRETTY_FUNCTION__))
;
1156 IdentifierNamespace |= IDNS_NonMemberOperator;
1157 }
1158
1159 static bool classofKind(Kind K) { return true; }
1160 static DeclContext *castToDeclContext(const Decl *);
1161 static Decl *castFromDeclContext(const DeclContext *);
1162
1163 void print(raw_ostream &Out, unsigned Indentation = 0,
1164 bool PrintInstantiation = false) const;
1165 void print(raw_ostream &Out, const PrintingPolicy &Policy,
1166 unsigned Indentation = 0, bool PrintInstantiation = false) const;
1167 static void printGroup(Decl** Begin, unsigned NumDecls,
1168 raw_ostream &Out, const PrintingPolicy &Policy,
1169 unsigned Indentation = 0);
1170
1171 // Debuggers don't usually respect default arguments.
1172 void dump() const;
1173
1174 // Same as dump(), but forces color printing.
1175 void dumpColor() const;
1176
1177 void dump(raw_ostream &Out, bool Deserialize = false,
1178 ASTDumpOutputFormat OutputFormat = ADOF_Default) const;
1179
1180 /// \return Unique reproducible object identifier
1181 int64_t getID() const;
1182
1183 /// Looks through the Decl's underlying type to extract a FunctionType
1184 /// when possible. Will return null if the type underlying the Decl does not
1185 /// have a FunctionType.
1186 const FunctionType *getFunctionType(bool BlocksToo = true) const;
1187
1188private:
1189 void setAttrsImpl(const AttrVec& Attrs, ASTContext &Ctx);
1190 void setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
1191 ASTContext &Ctx);
1192
1193protected:
1194 ASTMutationListener *getASTMutationListener() const;
1195};
1196
1197/// Determine whether two declarations declare the same entity.
1198inline bool declaresSameEntity(const Decl *D1, const Decl *D2) {
1199 if (!D1 || !D2)
1200 return false;
1201
1202 if (D1 == D2)
1203 return true;
1204
1205 return D1->getCanonicalDecl() == D2->getCanonicalDecl();
1206}
1207
1208/// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when
1209/// doing something to a specific decl.
1210class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry {
1211 const Decl *TheDecl;
1212 SourceLocation Loc;
1213 SourceManager &SM;
1214 const char *Message;
1215
1216public:
1217 PrettyStackTraceDecl(const Decl *theDecl, SourceLocation L,
1218 SourceManager &sm, const char *Msg)
1219 : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {}
1220
1221 void print(raw_ostream &OS) const override;
1222};
1223
1224/// The results of name lookup within a DeclContext. This is either a
1225/// single result (with no stable storage) or a collection of results (with
1226/// stable storage provided by the lookup table).
1227class DeclContextLookupResult {
1228 using ResultTy = ArrayRef<NamedDecl *>;
1229
1230 ResultTy Result;
1231
1232 // If there is only one lookup result, it would be invalidated by
1233 // reallocations of the name table, so store it separately.
1234 NamedDecl *Single = nullptr;
1235
1236 static NamedDecl *const SingleElementDummyList;
1237
1238public:
1239 DeclContextLookupResult() = default;
1240 DeclContextLookupResult(ArrayRef<NamedDecl *> Result)
1241 : Result(Result) {}
1242 DeclContextLookupResult(NamedDecl *Single)
1243 : Result(SingleElementDummyList), Single(Single) {}
1244
1245 class iterator;
1246
1247 using IteratorBase =
1248 llvm::iterator_adaptor_base<iterator, ResultTy::iterator,
1249 std::random_access_iterator_tag,
1250 NamedDecl *const>;
1251
1252 class iterator : public IteratorBase {
1253 value_type SingleElement;
1254
1255 public:
1256 explicit iterator(pointer Pos, value_type Single = nullptr)
1257 : IteratorBase(Pos), SingleElement(Single) {}
1258
1259 reference operator*() const {
1260 return SingleElement ? SingleElement : IteratorBase::operator*();
1261 }
1262 };
1263
1264 using const_iterator = iterator;
1265 using pointer = iterator::pointer;
1266 using reference = iterator::reference;
1267
1268 iterator begin() const { return iterator(Result.begin(), Single); }
1269 iterator end() const { return iterator(Result.end(), Single); }
1270
1271 bool empty() const { return Result.empty(); }
1272 pointer data() const { return Single ? &Single : Result.data(); }
1273 size_t size() const { return Single ? 1 : Result.size(); }
1274 reference front() const { return Single ? Single : Result.front(); }
1275 reference back() const { return Single ? Single : Result.back(); }
1276 reference operator[](size_t N) const { return Single ? Single : Result[N]; }
1277
1278 // FIXME: Remove this from the interface
1279 DeclContextLookupResult slice(size_t N) const {
1280 DeclContextLookupResult Sliced = Result.slice(N);
1281 Sliced.Single = Single;
1282 return Sliced;
1283 }
1284};
1285
1286/// DeclContext - This is used only as base class of specific decl types that
1287/// can act as declaration contexts. These decls are (only the top classes
1288/// that directly derive from DeclContext are mentioned, not their subclasses):
1289///
1290/// TranslationUnitDecl
1291/// ExternCContext
1292/// NamespaceDecl
1293/// TagDecl
1294/// OMPDeclareReductionDecl
1295/// OMPDeclareMapperDecl
1296/// FunctionDecl
1297/// ObjCMethodDecl
1298/// ObjCContainerDecl
1299/// LinkageSpecDecl
1300/// ExportDecl
1301/// BlockDecl
1302/// CapturedDecl
1303class DeclContext {
1304 /// For makeDeclVisibleInContextImpl
1305 friend class ASTDeclReader;
1306 /// For reconcileExternalVisibleStorage, CreateStoredDeclsMap,
1307 /// hasNeedToReconcileExternalVisibleStorage
1308 friend class ExternalASTSource;
1309 /// For CreateStoredDeclsMap
1310 friend class DependentDiagnostic;
1311 /// For hasNeedToReconcileExternalVisibleStorage,
1312 /// hasLazyLocalLexicalLookups, hasLazyExternalLexicalLookups
1313 friend class ASTWriter;
1314
1315 // We use uint64_t in the bit-fields below since some bit-fields
1316 // cross the unsigned boundary and this breaks the packing.
1317
1318 /// Stores the bits used by DeclContext.
1319 /// If modified NumDeclContextBit, the ctor of DeclContext and the accessor
1320 /// methods in DeclContext should be updated appropriately.
1321 class DeclContextBitfields {
1322 friend class DeclContext;
1323 /// DeclKind - This indicates which class this is.
1324 uint64_t DeclKind : 7;
1325
1326 /// Whether this declaration context also has some external
1327 /// storage that contains additional declarations that are lexically
1328 /// part of this context.
1329 mutable uint64_t ExternalLexicalStorage : 1;
1330
1331 /// Whether this declaration context also has some external
1332 /// storage that contains additional declarations that are visible
1333 /// in this context.
1334 mutable uint64_t ExternalVisibleStorage : 1;
1335
1336 /// Whether this declaration context has had externally visible
1337 /// storage added since the last lookup. In this case, \c LookupPtr's
1338 /// invariant may not hold and needs to be fixed before we perform
1339 /// another lookup.
1340 mutable uint64_t NeedToReconcileExternalVisibleStorage : 1;
1341
1342 /// If \c true, this context may have local lexical declarations
1343 /// that are missing from the lookup table.
1344 mutable uint64_t HasLazyLocalLexicalLookups : 1;
1345
1346 /// If \c true, the external source may have lexical declarations
1347 /// that are missing from the lookup table.
1348 mutable uint64_t HasLazyExternalLexicalLookups : 1;
1349
1350 /// If \c true, lookups should only return identifier from
1351 /// DeclContext scope (for example TranslationUnit). Used in
1352 /// LookupQualifiedName()
1353 mutable uint64_t UseQualifiedLookup : 1;
1354 };
1355
1356 /// Number of bits in DeclContextBitfields.
1357 enum { NumDeclContextBits = 13 };
1358
1359 /// Stores the bits used by TagDecl.
1360 /// If modified NumTagDeclBits and the accessor
1361 /// methods in TagDecl should be updated appropriately.
1362 class TagDeclBitfields {
1363 friend class TagDecl;
1364 /// For the bits in DeclContextBitfields
1365 uint64_t : NumDeclContextBits;
1366
1367 /// The TagKind enum.
1368 uint64_t TagDeclKind : 3;
1369
1370 /// True if this is a definition ("struct foo {};"), false if it is a
1371 /// declaration ("struct foo;"). It is not considered a definition
1372 /// until the definition has been fully processed.
1373 uint64_t IsCompleteDefinition : 1;
1374
1375 /// True if this is currently being defined.
1376 uint64_t IsBeingDefined : 1;
1377
1378 /// True if this tag declaration is "embedded" (i.e., defined or declared
1379 /// for the very first time) in the syntax of a declarator.
1380 uint64_t IsEmbeddedInDeclarator : 1;
1381
1382 /// True if this tag is free standing, e.g. "struct foo;".
1383 uint64_t IsFreeStanding : 1;
1384
1385 /// Indicates whether it is possible for declarations of this kind
1386 /// to have an out-of-date definition.
1387 ///
1388 /// This option is only enabled when modules are enabled.
1389 uint64_t MayHaveOutOfDateDef : 1;
1390
1391 /// Has the full definition of this type been required by a use somewhere in
1392 /// the TU.
1393 uint64_t IsCompleteDefinitionRequired : 1;
1394 };
1395
1396 /// Number of non-inherited bits in TagDeclBitfields.
1397 enum { NumTagDeclBits = 9 };
1398
1399 /// Stores the bits used by EnumDecl.
1400 /// If modified NumEnumDeclBit and the accessor
1401 /// methods in EnumDecl should be updated appropriately.
1402 class EnumDeclBitfields {
1403 friend class EnumDecl;
1404 /// For the bits in DeclContextBitfields.
1405 uint64_t : NumDeclContextBits;
1406 /// For the bits in TagDeclBitfields.
1407 uint64_t : NumTagDeclBits;
1408
1409 /// Width in bits required to store all the non-negative
1410 /// enumerators of this enum.
1411 uint64_t NumPositiveBits : 8;
1412
1413 /// Width in bits required to store all the negative
1414 /// enumerators of this enum.
1415 uint64_t NumNegativeBits : 8;
1416
1417 /// True if this tag declaration is a scoped enumeration. Only
1418 /// possible in C++11 mode.
1419 uint64_t IsScoped : 1;
1420
1421 /// If this tag declaration is a scoped enum,
1422 /// then this is true if the scoped enum was declared using the class
1423 /// tag, false if it was declared with the struct tag. No meaning is
1424 /// associated if this tag declaration is not a scoped enum.
1425 uint64_t IsScopedUsingClassTag : 1;
1426
1427 /// True if this is an enumeration with fixed underlying type. Only
1428 /// possible in C++11, Microsoft extensions, or Objective C mode.
1429 uint64_t IsFixed : 1;
1430
1431 /// True if a valid hash is stored in ODRHash.
1432 uint64_t HasODRHash : 1;
1433 };
1434
1435 /// Number of non-inherited bits in EnumDeclBitfields.
1436 enum { NumEnumDeclBits = 20 };
1437
1438 /// Stores the bits used by RecordDecl.
1439 /// If modified NumRecordDeclBits and the accessor
1440 /// methods in RecordDecl should be updated appropriately.
1441 class RecordDeclBitfields {
1442 friend class RecordDecl;
1443 /// For the bits in DeclContextBitfields.
1444 uint64_t : NumDeclContextBits;
1445 /// For the bits in TagDeclBitfields.
1446 uint64_t : NumTagDeclBits;
1447
1448 /// This is true if this struct ends with a flexible
1449 /// array member (e.g. int X[]) or if this union contains a struct that does.
1450 /// If so, this cannot be contained in arrays or other structs as a member.
1451 uint64_t HasFlexibleArrayMember : 1;
1452
1453 /// Whether this is the type of an anonymous struct or union.
1454 uint64_t AnonymousStructOrUnion : 1;
1455
1456 /// This is true if this struct has at least one member
1457 /// containing an Objective-C object pointer type.
1458 uint64_t HasObjectMember : 1;
1459
1460 /// This is true if struct has at least one member of
1461 /// 'volatile' type.
1462 uint64_t HasVolatileMember : 1;
1463
1464 /// Whether the field declarations of this record have been loaded
1465 /// from external storage. To avoid unnecessary deserialization of
1466 /// methods/nested types we allow deserialization of just the fields
1467 /// when needed.
1468 mutable uint64_t LoadedFieldsFromExternalStorage : 1;
1469
1470 /// Basic properties of non-trivial C structs.
1471 uint64_t NonTrivialToPrimitiveDefaultInitialize : 1;
1472 uint64_t NonTrivialToPrimitiveCopy : 1;
1473 uint64_t NonTrivialToPrimitiveDestroy : 1;
1474
1475 /// The following bits indicate whether this is or contains a C union that
1476 /// is non-trivial to default-initialize, destruct, or copy. These bits
1477 /// imply the associated basic non-triviality predicates declared above.
1478 uint64_t HasNonTrivialToPrimitiveDefaultInitializeCUnion : 1;
1479 uint64_t HasNonTrivialToPrimitiveDestructCUnion : 1;
1480 uint64_t HasNonTrivialToPrimitiveCopyCUnion : 1;
1481
1482 /// Indicates whether this struct is destroyed in the callee.
1483 uint64_t ParamDestroyedInCallee : 1;
1484
1485 /// Represents the way this type is passed to a function.
1486 uint64_t ArgPassingRestrictions : 2;
1487 };
1488
1489 /// Number of non-inherited bits in RecordDeclBitfields.
1490 enum { NumRecordDeclBits = 14 };
1491
1492 /// Stores the bits used by OMPDeclareReductionDecl.
1493 /// If modified NumOMPDeclareReductionDeclBits and the accessor
1494 /// methods in OMPDeclareReductionDecl should be updated appropriately.
1495 class OMPDeclareReductionDeclBitfields {
1496 friend class OMPDeclareReductionDecl;
1497 /// For the bits in DeclContextBitfields
1498 uint64_t : NumDeclContextBits;
1499
1500 /// Kind of initializer,
1501 /// function call or omp_priv<init_expr> initializtion.
1502 uint64_t InitializerKind : 2;
1503 };
1504
1505 /// Number of non-inherited bits in OMPDeclareReductionDeclBitfields.
1506 enum { NumOMPDeclareReductionDeclBits = 2 };
1507
1508 /// Stores the bits used by FunctionDecl.
1509 /// If modified NumFunctionDeclBits and the accessor
1510 /// methods in FunctionDecl and CXXDeductionGuideDecl
1511 /// (for IsCopyDeductionCandidate) should be updated appropriately.
1512 class FunctionDeclBitfields {
1513 friend class FunctionDecl;
1514 /// For IsCopyDeductionCandidate
1515 friend class CXXDeductionGuideDecl;
1516 /// For the bits in DeclContextBitfields.
1517 uint64_t : NumDeclContextBits;
1518
1519 uint64_t SClass : 3;
1520 uint64_t IsInline : 1;
1521 uint64_t IsInlineSpecified : 1;
1522
1523 uint64_t IsVirtualAsWritten : 1;
1524 uint64_t IsPure : 1;
1525 uint64_t HasInheritedPrototype : 1;
1526 uint64_t HasWrittenPrototype : 1;
1527 uint64_t IsDeleted : 1;
1528 /// Used by CXXMethodDecl
1529 uint64_t IsTrivial : 1;
1530
1531 /// This flag indicates whether this function is trivial for the purpose of
1532 /// calls. This is meaningful only when this function is a copy/move
1533 /// constructor or a destructor.
1534 uint64_t IsTrivialForCall : 1;
1535
1536 uint64_t IsDefaulted : 1;
1537 uint64_t IsExplicitlyDefaulted : 1;
1538 uint64_t HasDefaultedFunctionInfo : 1;
1539 uint64_t HasImplicitReturnZero : 1;
1540 uint64_t IsLateTemplateParsed : 1;
1541
1542 /// Kind of contexpr specifier as defined by ConstexprSpecKind.
1543 uint64_t ConstexprKind : 2;
1544 uint64_t InstantiationIsPending : 1;
1545
1546 /// Indicates if the function uses __try.
1547 uint64_t UsesSEHTry : 1;
1548
1549 /// Indicates if the function was a definition
1550 /// but its body was skipped.
1551 uint64_t HasSkippedBody : 1;
1552
1553 /// Indicates if the function declaration will
1554 /// have a body, once we're done parsing it.
1555 uint64_t WillHaveBody : 1;
1556
1557 /// Indicates that this function is a multiversioned
1558 /// function using attribute 'target'.
1559 uint64_t IsMultiVersion : 1;
1560
1561 /// [C++17] Only used by CXXDeductionGuideDecl. Indicates that
1562 /// the Deduction Guide is the implicitly generated 'copy
1563 /// deduction candidate' (is used during overload resolution).
1564 uint64_t IsCopyDeductionCandidate : 1;
1565
1566 /// Store the ODRHash after first calculation.
1567 uint64_t HasODRHash : 1;
1568
1569 /// Indicates if the function uses Floating Point Constrained Intrinsics
1570 uint64_t UsesFPIntrin : 1;
1571 };
1572
1573 /// Number of non-inherited bits in FunctionDeclBitfields.
1574 enum { NumFunctionDeclBits = 27 };
1575
1576 /// Stores the bits used by CXXConstructorDecl. If modified
1577 /// NumCXXConstructorDeclBits and the accessor
1578 /// methods in CXXConstructorDecl should be updated appropriately.
1579 class CXXConstructorDeclBitfields {
1580 friend class CXXConstructorDecl;
1581 /// For the bits in DeclContextBitfields.
1582 uint64_t : NumDeclContextBits;
1583 /// For the bits in FunctionDeclBitfields.
1584 uint64_t : NumFunctionDeclBits;
1585
1586 /// 24 bits to fit in the remaining available space.
1587 /// Note that this makes CXXConstructorDeclBitfields take
1588 /// exactly 64 bits and thus the width of NumCtorInitializers
1589 /// will need to be shrunk if some bit is added to NumDeclContextBitfields,
1590 /// NumFunctionDeclBitfields or CXXConstructorDeclBitfields.
1591 uint64_t NumCtorInitializers : 21;
1592 uint64_t IsInheritingConstructor : 1;
1593
1594 /// Whether this constructor has a trail-allocated explicit specifier.
1595 uint64_t HasTrailingExplicitSpecifier : 1;
1596 /// If this constructor does't have a trail-allocated explicit specifier.
1597 /// Whether this constructor is explicit specified.
1598 uint64_t IsSimpleExplicit : 1;
1599 };
1600
1601 /// Number of non-inherited bits in CXXConstructorDeclBitfields.
1602 enum {
1603 NumCXXConstructorDeclBits = 64 - NumDeclContextBits - NumFunctionDeclBits
1604 };
1605
1606 /// Stores the bits used by ObjCMethodDecl.
1607 /// If modified NumObjCMethodDeclBits and the accessor
1608 /// methods in ObjCMethodDecl should be updated appropriately.
1609 class ObjCMethodDeclBitfields {
1610 friend class ObjCMethodDecl;
1611
1612 /// For the bits in DeclContextBitfields.
1613 uint64_t : NumDeclContextBits;
1614
1615 /// The conventional meaning of this method; an ObjCMethodFamily.
1616 /// This is not serialized; instead, it is computed on demand and
1617 /// cached.
1618 mutable uint64_t Family : ObjCMethodFamilyBitWidth;
1619
1620 /// instance (true) or class (false) method.
1621 uint64_t IsInstance : 1;
1622 uint64_t IsVariadic : 1;
1623
1624 /// True if this method is the getter or setter for an explicit property.
1625 uint64_t IsPropertyAccessor : 1;
1626
1627 /// True if this method is a synthesized property accessor stub.
1628 uint64_t IsSynthesizedAccessorStub : 1;
1629
1630 /// Method has a definition.
1631 uint64_t IsDefined : 1;
1632
1633 /// Method redeclaration in the same interface.
1634 uint64_t IsRedeclaration : 1;
1635
1636 /// Is redeclared in the same interface.
1637 mutable uint64_t HasRedeclaration : 1;
1638
1639 /// \@required/\@optional
1640 uint64_t DeclImplementation : 2;
1641
1642 /// in, inout, etc.
1643 uint64_t objcDeclQualifier : 7;
1644
1645 /// Indicates whether this method has a related result type.
1646 uint64_t RelatedResultType : 1;
1647
1648 /// Whether the locations of the selector identifiers are in a
1649 /// "standard" position, a enum SelectorLocationsKind.
1650 uint64_t SelLocsKind : 2;
1651
1652 /// Whether this method overrides any other in the class hierarchy.
1653 ///
1654 /// A method is said to override any method in the class's
1655 /// base classes, its protocols, or its categories' protocols, that has
1656 /// the same selector and is of the same kind (class or instance).
1657 /// A method in an implementation is not considered as overriding the same
1658 /// method in the interface or its categories.
1659 uint64_t IsOverriding : 1;
1660
1661 /// Indicates if the method was a definition but its body was skipped.
1662 uint64_t HasSkippedBody : 1;
1663 };
1664
1665 /// Number of non-inherited bits in ObjCMethodDeclBitfields.
1666 enum { NumObjCMethodDeclBits = 24 };
1667
1668 /// Stores the bits used by ObjCContainerDecl.
1669 /// If modified NumObjCContainerDeclBits and the accessor
1670 /// methods in ObjCContainerDecl should be updated appropriately.
1671 class ObjCContainerDeclBitfields {
1672 friend class ObjCContainerDecl;
1673 /// For the bits in DeclContextBitfields
1674 uint32_t : NumDeclContextBits;
1675
1676 // Not a bitfield but this saves space.
1677 // Note that ObjCContainerDeclBitfields is full.
1678 SourceLocation AtStart;
1679 };
1680
1681 /// Number of non-inherited bits in ObjCContainerDeclBitfields.
1682 /// Note that here we rely on the fact that SourceLocation is 32 bits
1683 /// wide. We check this with the static_assert in the ctor of DeclContext.
1684 enum { NumObjCContainerDeclBits = 64 - NumDeclContextBits };
1685
1686 /// Stores the bits used by LinkageSpecDecl.
1687 /// If modified NumLinkageSpecDeclBits and the accessor
1688 /// methods in LinkageSpecDecl should be updated appropriately.
1689 class LinkageSpecDeclBitfields {
1690 friend class LinkageSpecDecl;
1691 /// For the bits in DeclContextBitfields.
1692 uint64_t : NumDeclContextBits;
1693
1694 /// The language for this linkage specification with values
1695 /// in the enum LinkageSpecDecl::LanguageIDs.
1696 uint64_t Language : 3;
1697
1698 /// True if this linkage spec has braces.
1699 /// This is needed so that hasBraces() returns the correct result while the
1700 /// linkage spec body is being parsed. Once RBraceLoc has been set this is
1701 /// not used, so it doesn't need to be serialized.
1702 uint64_t HasBraces : 1;
1703 };
1704
1705 /// Number of non-inherited bits in LinkageSpecDeclBitfields.
1706 enum { NumLinkageSpecDeclBits = 4 };
1707
1708 /// Stores the bits used by BlockDecl.
1709 /// If modified NumBlockDeclBits and the accessor
1710 /// methods in BlockDecl should be updated appropriately.
1711 class BlockDeclBitfields {
1712 friend class BlockDecl;
1713 /// For the bits in DeclContextBitfields.
1714 uint64_t : NumDeclContextBits;
1715
1716 uint64_t IsVariadic : 1;
1717 uint64_t CapturesCXXThis : 1;
1718 uint64_t BlockMissingReturnType : 1;
1719 uint64_t IsConversionFromLambda : 1;
1720
1721 /// A bit that indicates this block is passed directly to a function as a
1722 /// non-escaping parameter.
1723 uint64_t DoesNotEscape : 1;
1724
1725 /// A bit that indicates whether it's possible to avoid coying this block to
1726 /// the heap when it initializes or is assigned to a local variable with
1727 /// automatic storage.
1728 uint64_t CanAvoidCopyToHeap : 1;
1729 };
1730
1731 /// Number of non-inherited bits in BlockDeclBitfields.
1732 enum { NumBlockDeclBits = 5 };
1733
1734 /// Pointer to the data structure used to lookup declarations
1735 /// within this context (or a DependentStoredDeclsMap if this is a
1736 /// dependent context). We maintain the invariant that, if the map
1737 /// contains an entry for a DeclarationName (and we haven't lazily
1738 /// omitted anything), then it contains all relevant entries for that
1739 /// name (modulo the hasExternalDecls() flag).
1740 mutable StoredDeclsMap *LookupPtr = nullptr;
1741
1742protected:
1743 /// This anonymous union stores the bits belonging to DeclContext and classes
1744 /// deriving from it. The goal is to use otherwise wasted
1745 /// space in DeclContext to store data belonging to derived classes.
1746 /// The space saved is especially significient when pointers are aligned
1747 /// to 8 bytes. In this case due to alignment requirements we have a
1748 /// little less than 8 bytes free in DeclContext which we can use.
1749 /// We check that none of the classes in this union is larger than
1750 /// 8 bytes with static_asserts in the ctor of DeclContext.
1751 union {
1752 DeclContextBitfields DeclContextBits;
1753 TagDeclBitfields TagDeclBits;
1754 EnumDeclBitfields EnumDeclBits;
1755 RecordDeclBitfields RecordDeclBits;
1756 OMPDeclareReductionDeclBitfields OMPDeclareReductionDeclBits;
1757 FunctionDeclBitfields FunctionDeclBits;
1758 CXXConstructorDeclBitfields CXXConstructorDeclBits;
1759 ObjCMethodDeclBitfields ObjCMethodDeclBits;
1760 ObjCContainerDeclBitfields ObjCContainerDeclBits;
1761 LinkageSpecDeclBitfields LinkageSpecDeclBits;
1762 BlockDeclBitfields BlockDeclBits;
1763
1764 static_assert(sizeof(DeclContextBitfields) <= 8,
1765 "DeclContextBitfields is larger than 8 bytes!");
1766 static_assert(sizeof(TagDeclBitfields) <= 8,
1767 "TagDeclBitfields is larger than 8 bytes!");
1768 static_assert(sizeof(EnumDeclBitfields) <= 8,
1769 "EnumDeclBitfields is larger than 8 bytes!");
1770 static_assert(sizeof(RecordDeclBitfields) <= 8,
1771 "RecordDeclBitfields is larger than 8 bytes!");
1772 static_assert(sizeof(OMPDeclareReductionDeclBitfields) <= 8,
1773 "OMPDeclareReductionDeclBitfields is larger than 8 bytes!");
1774 static_assert(sizeof(FunctionDeclBitfields) <= 8,
1775 "FunctionDeclBitfields is larger than 8 bytes!");
1776 static_assert(sizeof(CXXConstructorDeclBitfields) <= 8,
1777 "CXXConstructorDeclBitfields is larger than 8 bytes!");
1778 static_assert(sizeof(ObjCMethodDeclBitfields) <= 8,
1779 "ObjCMethodDeclBitfields is larger than 8 bytes!");
1780 static_assert(sizeof(ObjCContainerDeclBitfields) <= 8,
1781 "ObjCContainerDeclBitfields is larger than 8 bytes!");
1782 static_assert(sizeof(LinkageSpecDeclBitfields) <= 8,
1783 "LinkageSpecDeclBitfields is larger than 8 bytes!");
1784 static_assert(sizeof(BlockDeclBitfields) <= 8,
1785 "BlockDeclBitfields is larger than 8 bytes!");
1786 };
1787
1788 /// FirstDecl - The first declaration stored within this declaration
1789 /// context.
1790 mutable Decl *FirstDecl = nullptr;
1791
1792 /// LastDecl - The last declaration stored within this declaration
1793 /// context. FIXME: We could probably cache this value somewhere
1794 /// outside of the DeclContext, to reduce the size of DeclContext by
1795 /// another pointer.
1796 mutable Decl *LastDecl = nullptr;
1797
1798 /// Build up a chain of declarations.
1799 ///
1800 /// \returns the first/last pair of declarations.
1801 static std::pair<Decl *, Decl *>
1802 BuildDeclChain(ArrayRef<Decl*> Decls, bool FieldsAlreadyLoaded);
1803
1804 DeclContext(Decl::Kind K);
1805
1806public:
1807 ~DeclContext();
1808
1809 Decl::Kind getDeclKind() const {
1810 return static_cast<Decl::Kind>(DeclContextBits.DeclKind);
1811 }
1812
1813 const char *getDeclKindName() const;
1814
1815 /// getParent - Returns the containing DeclContext.
1816 DeclContext *getParent() {
1817 return cast<Decl>(this)->getDeclContext();
1818 }
1819 const DeclContext *getParent() const {
1820 return const_cast<DeclContext*>(this)->getParent();
1821 }
1822
1823 /// getLexicalParent - Returns the containing lexical DeclContext. May be
1824 /// different from getParent, e.g.:
1825 ///
1826 /// namespace A {
1827 /// struct S;
1828 /// }
1829 /// struct A::S {}; // getParent() == namespace 'A'
1830 /// // getLexicalParent() == translation unit
1831 ///
1832 DeclContext *getLexicalParent() {
1833 return cast<Decl>(this)->getLexicalDeclContext();
1834 }
1835 const DeclContext *getLexicalParent() const {
1836 return const_cast<DeclContext*>(this)->getLexicalParent();
1837 }
1838
1839 DeclContext *getLookupParent();
1840
1841 const DeclContext *getLookupParent() const {
1842 return const_cast<DeclContext*>(this)->getLookupParent();
1843 }
1844
1845 ASTContext &getParentASTContext() const {
1846 return cast<Decl>(this)->getASTContext();
1847 }
1848
1849 bool isClosure() const { return getDeclKind() == Decl::Block; }
1850
1851 /// Return this DeclContext if it is a BlockDecl. Otherwise, return the
1852 /// innermost enclosing BlockDecl or null if there are no enclosing blocks.
1853 const BlockDecl *getInnermostBlockDecl() const;
1854
1855 bool isObjCContainer() const {
1856 switch (getDeclKind()) {
1857 case Decl::ObjCCategory:
1858 case Decl::ObjCCategoryImpl:
1859 case Decl::ObjCImplementation:
1860 case Decl::ObjCInterface:
1861 case Decl::ObjCProtocol:
1862 return true;
1863 default:
1864 return false;
1865 }
1866 }
1867
1868 bool isFunctionOrMethod() const {
1869 switch (getDeclKind()) {
1870 case Decl::Block:
1871 case Decl::Captured:
1872 case Decl::ObjCMethod:
1873 return true;
1874 default:
1875 return getDeclKind() >= Decl::firstFunction &&
1876 getDeclKind() <= Decl::lastFunction;
1877 }
1878 }
1879
1880 /// Test whether the context supports looking up names.
1881 bool isLookupContext() const {
1882 return !isFunctionOrMethod() && getDeclKind() != Decl::LinkageSpec &&
1883 getDeclKind() != Decl::Export;
1884 }
1885
1886 bool isFileContext() const {
1887 return getDeclKind() == Decl::TranslationUnit ||
1888 getDeclKind() == Decl::Namespace;
1889 }
1890
1891 bool isTranslationUnit() const {
1892 return getDeclKind() == Decl::TranslationUnit;
1893 }
1894
1895 bool isRecord() const {
1896 return getDeclKind() >= Decl::firstRecord &&
1897 getDeclKind() <= Decl::lastRecord;
1898 }
1899
1900 bool isNamespace() const { return getDeclKind() == Decl::Namespace; }
1901
1902 bool isStdNamespace() const;
1903
1904 bool isInlineNamespace() const;
1905
1906 /// Determines whether this context is dependent on a
1907 /// template parameter.
1908 bool isDependentContext() const;
1909
1910 /// isTransparentContext - Determines whether this context is a
1911 /// "transparent" context, meaning that the members declared in this
1912 /// context are semantically declared in the nearest enclosing
1913 /// non-transparent (opaque) context but are lexically declared in
1914 /// this context. For example, consider the enumerators of an
1915 /// enumeration type:
1916 /// @code
1917 /// enum E {
1918 /// Val1
1919 /// };
1920 /// @endcode
1921 /// Here, E is a transparent context, so its enumerator (Val1) will
1922 /// appear (semantically) that it is in the same context of E.
1923 /// Examples of transparent contexts include: enumerations (except for
1924 /// C++0x scoped enums), and C++ linkage specifications.
1925 bool isTransparentContext() const;
1926
1927 /// Determines whether this context or some of its ancestors is a
1928 /// linkage specification context that specifies C linkage.
1929 bool isExternCContext() const;
1930
1931 /// Retrieve the nearest enclosing C linkage specification context.
1932 const LinkageSpecDecl *getExternCContext() const;
1933
1934 /// Determines whether this context or some of its ancestors is a
1935 /// linkage specification context that specifies C++ linkage.
1936 bool isExternCXXContext() const;
1937
1938 /// Determine whether this declaration context is equivalent
1939 /// to the declaration context DC.
1940 bool Equals(const DeclContext *DC) const {
1941 return DC && this->getPrimaryContext() == DC->getPrimaryContext();
1942 }
1943
1944 /// Determine whether this declaration context encloses the
1945 /// declaration context DC.
1946 bool Encloses(const DeclContext *DC) const;
1947
1948 /// Find the nearest non-closure ancestor of this context,
1949 /// i.e. the innermost semantic parent of this context which is not
1950 /// a closure. A context may be its own non-closure ancestor.
1951 Decl *getNonClosureAncestor();
1952 const Decl *getNonClosureAncestor() const {
1953 return const_cast<DeclContext*>(this)->getNonClosureAncestor();
1954 }
1955
1956 /// getPrimaryContext - There may be many different
1957 /// declarations of the same entity (including forward declarations
1958 /// of classes, multiple definitions of namespaces, etc.), each with
1959 /// a different set of declarations. This routine returns the
1960 /// "primary" DeclContext structure, which will contain the
1961 /// information needed to perform name lookup into this context.
1962 DeclContext *getPrimaryContext();
1963 const DeclContext *getPrimaryContext() const {
1964 return const_cast<DeclContext*>(this)->getPrimaryContext();
1965 }
1966
1967 /// getRedeclContext - Retrieve the context in which an entity conflicts with
1968 /// other entities of the same name, or where it is a redeclaration if the
1969 /// two entities are compatible. This skips through transparent contexts.
1970 DeclContext *getRedeclContext();
1971 const DeclContext *getRedeclContext() const {
1972 return const_cast<DeclContext *>(this)->getRedeclContext();
1973 }
1974
1975 /// Retrieve the nearest enclosing namespace context.
1976 DeclContext *getEnclosingNamespaceContext();
1977 const DeclContext *getEnclosingNamespaceContext() const {
1978 return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext();
1979 }
1980
1981 /// Retrieve the outermost lexically enclosing record context.
1982 RecordDecl *getOuterLexicalRecordContext();
1983 const RecordDecl *getOuterLexicalRecordContext() const {
1984 return const_cast<DeclContext *>(this)->getOuterLexicalRecordContext();
1985 }
1986
1987 /// Test if this context is part of the enclosing namespace set of
1988 /// the context NS, as defined in C++0x [namespace.def]p9. If either context
1989 /// isn't a namespace, this is equivalent to Equals().
1990 ///
1991 /// The enclosing namespace set of a namespace is the namespace and, if it is
1992 /// inline, its enclosing namespace, recursively.
1993 bool InEnclosingNamespaceSetOf(const DeclContext *NS) const;
1994
1995 /// Collects all of the declaration contexts that are semantically
1996 /// connected to this declaration context.
1997 ///
1998 /// For declaration contexts that have multiple semantically connected but
1999 /// syntactically distinct contexts, such as C++ namespaces, this routine
2000 /// retrieves the complete set of such declaration contexts in source order.
2001 /// For example, given:
2002 ///
2003 /// \code
2004 /// namespace N {
2005 /// int x;
2006 /// }
2007 /// namespace N {
2008 /// int y;
2009 /// }
2010 /// \endcode
2011 ///
2012 /// The \c Contexts parameter will contain both definitions of N.
2013 ///
2014 /// \param Contexts Will be cleared and set to the set of declaration
2015 /// contexts that are semanticaly connected to this declaration context,
2016 /// in source order, including this context (which may be the only result,
2017 /// for non-namespace contexts).
2018 void collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts);
2019
2020 /// decl_iterator - Iterates through the declarations stored
2021 /// within this context.
2022 class decl_iterator {
2023 /// Current - The current declaration.
2024 Decl *Current = nullptr;
2025
2026 public:
2027 using value_type = Decl *;
2028 using reference = const value_type &;
2029 using pointer = const value_type *;
2030 using iterator_category = std::forward_iterator_tag;
2031 using difference_type = std::ptrdiff_t;
2032
2033 decl_iterator() = default;
2034 explicit decl_iterator(Decl *C) : Current(C) {}
2035
2036 reference operator*() const { return Current; }
2037
2038 // This doesn't meet the iterator requirements, but it's convenient
2039 value_type operator->() const { return Current; }
2040
2041 decl_iterator& operator++() {
2042 Current = Current->getNextDeclInContext();
2043 return *this;
2044 }
2045
2046 decl_iterator operator++(int) {
2047 decl_iterator tmp(*this);
2048 ++(*this);
2049 return tmp;
2050 }
2051
2052 friend bool operator==(decl_iterator x, decl_iterator y) {
2053 return x.Current == y.Current;
2054 }
2055
2056 friend bool operator!=(decl_iterator x, decl_iterator y) {
2057 return x.Current != y.Current;
2058 }
2059 };
2060
2061 using decl_range = llvm::iterator_range<decl_iterator>;
2062
2063 /// decls_begin/decls_end - Iterate over the declarations stored in
2064 /// this context.
2065 decl_range decls() const { return decl_range(decls_begin(), decls_end()); }
2066 decl_iterator decls_begin() const;
2067 decl_iterator decls_end() const { return decl_iterator(); }
2068 bool decls_empty() const;
2069
2070 /// noload_decls_begin/end - Iterate over the declarations stored in this
2071 /// context that are currently loaded; don't attempt to retrieve anything
2072 /// from an external source.
2073 decl_range noload_decls() const {
2074 return decl_range(noload_decls_begin(), noload_decls_end());
2075 }
2076 decl_iterator noload_decls_begin() const { return decl_iterator(FirstDecl); }
2077 decl_iterator noload_decls_end() const { return decl_iterator(); }
2078
2079 /// specific_decl_iterator - Iterates over a subrange of
2080 /// declarations stored in a DeclContext, providing only those that
2081 /// are of type SpecificDecl (or a class derived from it). This
2082 /// iterator is used, for example, to provide iteration over just
2083 /// the fields within a RecordDecl (with SpecificDecl = FieldDecl).
2084 template<typename SpecificDecl>
2085 class specific_decl_iterator {
2086 /// Current - The current, underlying declaration iterator, which
2087 /// will either be NULL or will point to a declaration of
2088 /// type SpecificDecl.
2089 DeclContext::decl_iterator Current;
2090
2091 /// SkipToNextDecl - Advances the current position up to the next
2092 /// declaration of type SpecificDecl that also meets the criteria
2093 /// required by Acceptable.
2094 void SkipToNextDecl() {
2095 while (*Current && !isa<SpecificDecl>(*Current))
2096 ++Current;
2097 }
2098
2099 public:
2100 using value_type = SpecificDecl *;
2101 // TODO: Add reference and pointer types (with some appropriate proxy type)
2102 // if we ever have a need for them.
2103 using reference = void;
2104 using pointer = void;
2105 using difference_type =
2106 std::iterator_traits<DeclContext::decl_iterator>::difference_type;
2107 using iterator_category = std::forward_iterator_tag;
2108
2109 specific_decl_iterator() = default;
2110
2111 /// specific_decl_iterator - Construct a new iterator over a
2112 /// subset of the declarations the range [C,
2113 /// end-of-declarations). If A is non-NULL, it is a pointer to a
2114 /// member function of SpecificDecl that should return true for
2115 /// all of the SpecificDecl instances that will be in the subset
2116 /// of iterators. For example, if you want Objective-C instance
2117 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
2118 /// &ObjCMethodDecl::isInstanceMethod.
2119 explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
2120 SkipToNextDecl();
2121 }
2122
2123 value_type operator*() const { return cast<SpecificDecl>(*Current); }
2124
2125 // This doesn't meet the iterator requirements, but it's convenient
2126 value_type operator->() const { return **this; }
2127
2128 specific_decl_iterator& operator++() {
2129 ++Current;
2130 SkipToNextDecl();
2131 return *this;
2132 }
2133
2134 specific_decl_iterator operator++(int) {
2135 specific_decl_iterator tmp(*this);
2136 ++(*this);
2137 return tmp;
2138 }
2139
2140 friend bool operator==(const specific_decl_iterator& x,
2141 const specific_decl_iterator& y) {
2142 return x.Current == y.Current;
2143 }
2144
2145 friend bool operator!=(const specific_decl_iterator& x,
2146 const specific_decl_iterator& y) {
2147 return x.Current != y.Current;
2148 }
2149 };
2150
2151 /// Iterates over a filtered subrange of declarations stored
2152 /// in a DeclContext.
2153 ///
2154 /// This iterator visits only those declarations that are of type
2155 /// SpecificDecl (or a class derived from it) and that meet some
2156 /// additional run-time criteria. This iterator is used, for
2157 /// example, to provide access to the instance methods within an
2158 /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and
2159 /// Acceptable = ObjCMethodDecl::isInstanceMethod).
2160 template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const>
2161 class filtered_decl_iterator {
2162 /// Current - The current, underlying declaration iterator, which
2163 /// will either be NULL or will point to a declaration of
2164 /// type SpecificDecl.
2165 DeclContext::decl_iterator Current;
2166
2167 /// SkipToNextDecl - Advances the current position up to the next
2168 /// declaration of type SpecificDecl that also meets the criteria
2169 /// required by Acceptable.
2170 void SkipToNextDecl() {
2171 while (*Current &&
2172 (!isa<SpecificDecl>(*Current) ||
2173 (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)())))
2174 ++Current;
2175 }
2176
2177 public:
2178 using value_type = SpecificDecl *;
2179 // TODO: Add reference and pointer types (with some appropriate proxy type)
2180 // if we ever have a need for them.
2181 using reference = void;
2182 using pointer = void;
2183 using difference_type =
2184 std::iterator_traits<DeclContext::decl_iterator>::difference_type;
2185 using iterator_category = std::forward_iterator_tag;
2186
2187 filtered_decl_iterator() = default;
2188
2189 /// filtered_decl_iterator - Construct a new iterator over a
2190 /// subset of the declarations the range [C,
2191 /// end-of-declarations). If A is non-NULL, it is a pointer to a
2192 /// member function of SpecificDecl that should return true for
2193 /// all of the SpecificDecl instances that will be in the subset
2194 /// of iterators. For example, if you want Objective-C instance
2195 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
2196 /// &ObjCMethodDecl::isInstanceMethod.
2197 explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
2198 SkipToNextDecl();
2199 }
2200
2201 value_type operator*() const { return cast<SpecificDecl>(*Current); }
2202 value_type operator->() const { return cast<SpecificDecl>(*Current); }
2203
2204 filtered_decl_iterator& operator++() {
2205 ++Current;
2206 SkipToNextDecl();
2207 return *this;
2208 }
2209
2210 filtered_decl_iterator operator++(int) {
2211 filtered_decl_iterator tmp(*this);
2212 ++(*this);
2213 return tmp;
2214 }
2215
2216 friend bool operator==(const filtered_decl_iterator& x,
2217 const filtered_decl_iterator& y) {
2218 return x.Current == y.Current;
2219 }
2220
2221 friend bool operator!=(const filtered_decl_iterator& x,
2222 const filtered_decl_iterator& y) {
2223 return x.Current != y.Current;
2224 }
2225 };
2226
2227 /// Add the declaration D into this context.
2228 ///
2229 /// This routine should be invoked when the declaration D has first
2230 /// been declared, to place D into the context where it was
2231 /// (lexically) defined. Every declaration must be added to one
2232 /// (and only one!) context, where it can be visited via
2233 /// [decls_begin(), decls_end()). Once a declaration has been added
2234 /// to its lexical context, the corresponding DeclContext owns the
2235 /// declaration.
2236 ///
2237 /// If D is also a NamedDecl, it will be made visible within its
2238 /// semantic context via makeDeclVisibleInContext.
2239 void addDecl(Decl *D);
2240
2241 /// Add the declaration D into this context, but suppress
2242 /// searches for external declarations with the same name.
2243 ///
2244 /// Although analogous in function to addDecl, this removes an
2245 /// important check. This is only useful if the Decl is being
2246 /// added in response to an external search; in all other cases,
2247 /// addDecl() is the right function to use.
2248 /// See the ASTImporter for use cases.
2249 void addDeclInternal(Decl *D);
2250
2251 /// Add the declaration D to this context without modifying
2252 /// any lookup tables.
2253 ///
2254 /// This is useful for some operations in dependent contexts where
2255 /// the semantic context might not be dependent; this basically
2256 /// only happens with friends.
2257 void addHiddenDecl(Decl *D);
2258
2259 /// Removes a declaration from this context.
2260 void removeDecl(Decl *D);
2261
2262 /// Checks whether a declaration is in this context.
2263 bool containsDecl(Decl *D) const;
2264
2265 /// Checks whether a declaration is in this context.
2266 /// This also loads the Decls from the external source before the check.
2267 bool containsDeclAndLoad(Decl *D) const;
2268
2269 using lookup_result = DeclContextLookupResult;
2270 using lookup_iterator = lookup_result::iterator;
2271
2272 /// lookup - Find the declarations (if any) with the given Name in
2273 /// this context. Returns a range of iterators that contains all of
2274 /// the declarations with this name, with object, function, member,
2275 /// and enumerator names preceding any tag name. Note that this
2276 /// routine will not look into parent contexts.
2277 lookup_result lookup(DeclarationName Name) const;
2278
2279 /// Find the declarations with the given name that are visible
2280 /// within this context; don't attempt to retrieve anything from an
2281 /// external source.
2282 lookup_result noload_lookup(DeclarationName Name);
2283
2284 /// A simplistic name lookup mechanism that performs name lookup
2285 /// into this declaration context without consulting the external source.
2286 ///
2287 /// This function should almost never be used, because it subverts the
2288 /// usual relationship between a DeclContext and the external source.
2289 /// See the ASTImporter for the (few, but important) use cases.
2290 ///
2291 /// FIXME: This is very inefficient; replace uses of it with uses of
2292 /// noload_lookup.
2293 void localUncachedLookup(DeclarationName Name,
2294 SmallVectorImpl<NamedDecl *> &Results);
2295
2296 /// Makes a declaration visible within this context.
2297 ///
2298 /// This routine makes the declaration D visible to name lookup
2299 /// within this context and, if this is a transparent context,
2300 /// within its parent contexts up to the first enclosing
2301 /// non-transparent context. Making a declaration visible within a
2302 /// context does not transfer ownership of a declaration, and a
2303 /// declaration can be visible in many contexts that aren't its
2304 /// lexical context.
2305 ///
2306 /// If D is a redeclaration of an existing declaration that is
2307 /// visible from this context, as determined by
2308 /// NamedDecl::declarationReplaces, the previous declaration will be
2309 /// replaced with D.
2310 void makeDeclVisibleInContext(NamedDecl *D);
2311
2312 /// all_lookups_iterator - An iterator that provides a view over the results
2313 /// of looking up every possible name.
2314 class all_lookups_iterator;
2315
2316 using lookups_range = llvm::iterator_range<all_lookups_iterator>;
2317
2318 lookups_range lookups() const;
2319 // Like lookups(), but avoids loading external declarations.
2320 // If PreserveInternalState, avoids building lookup data structures too.
2321 lookups_range noload_lookups(bool PreserveInternalState) const;
2322
2323 /// Iterators over all possible lookups within this context.
2324 all_lookups_iterator lookups_begin() const;
2325 all_lookups_iterator lookups_end() const;
2326
2327 /// Iterators over all possible lookups within this context that are
2328 /// currently loaded; don't attempt to retrieve anything from an external
2329 /// source.
2330 all_lookups_iterator noload_lookups_begin() const;
2331 all_lookups_iterator noload_lookups_end() const;
2332
2333 struct udir_iterator;
2334
2335 using udir_iterator_base =
2336 llvm::iterator_adaptor_base<udir_iterator, lookup_iterator,
2337 std::random_access_iterator_tag,
2338 UsingDirectiveDecl *>;
2339
2340 struct udir_iterator : udir_iterator_base {
2341 udir_iterator(lookup_iterator I) : udir_iterator_base(I) {}
2342
2343 UsingDirectiveDecl *operator*() const;
2344 };
2345
2346 using udir_range = llvm::iterator_range<udir_iterator>;
2347
2348 udir_range using_directives() const;
2349
2350 // These are all defined in DependentDiagnostic.h.
2351 class ddiag_iterator;
2352
2353 using ddiag_range = llvm::iterator_range<DeclContext::ddiag_iterator>;
2354
2355 inline ddiag_range ddiags() const;
2356
2357 // Low-level accessors
2358
2359 /// Mark that there are external lexical declarations that we need
2360 /// to include in our lookup table (and that are not available as external
2361 /// visible lookups). These extra lookup results will be found by walking
2362 /// the lexical declarations of this context. This should be used only if
2363 /// setHasExternalLexicalStorage() has been called on any decl context for
2364 /// which this is the primary context.
2365 void setMustBuildLookupTable() {
2366 assert(this == getPrimaryContext() &&((this == getPrimaryContext() && "should only be called on primary context"
) ? static_cast<void> (0) : __assert_fail ("this == getPrimaryContext() && \"should only be called on primary context\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 2367, __PRETTY_FUNCTION__))
2367 "should only be called on primary context")((this == getPrimaryContext() && "should only be called on primary context"
) ? static_cast<void> (0) : __assert_fail ("this == getPrimaryContext() && \"should only be called on primary context\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 2367, __PRETTY_FUNCTION__))
;
2368 DeclContextBits.HasLazyExternalLexicalLookups = true;
2369 }
2370
2371 /// Retrieve the internal representation of the lookup structure.
2372 /// This may omit some names if we are lazily building the structure.
2373 StoredDeclsMap *getLookupPtr() const { return LookupPtr; }
2374
2375 /// Ensure the lookup structure is fully-built and return it.
2376 StoredDeclsMap *buildLookup();
2377
2378 /// Whether this DeclContext has external storage containing
2379 /// additional declarations that are lexically in this context.
2380 bool hasExternalLexicalStorage() const {
2381 return DeclContextBits.ExternalLexicalStorage;
2382 }
2383
2384 /// State whether this DeclContext has external storage for
2385 /// declarations lexically in this context.
2386 void setHasExternalLexicalStorage(bool ES = true) const {
2387 DeclContextBits.ExternalLexicalStorage = ES;
2388 }
2389
2390 /// Whether this DeclContext has external storage containing
2391 /// additional declarations that are visible in this context.
2392 bool hasExternalVisibleStorage() const {
2393 return DeclContextBits.ExternalVisibleStorage;
2394 }
2395
2396 /// State whether this DeclContext has external storage for
2397 /// declarations visible in this context.
2398 void setHasExternalVisibleStorage(bool ES = true) const {
2399 DeclContextBits.ExternalVisibleStorage = ES;
2400 if (ES && LookupPtr)
2401 DeclContextBits.NeedToReconcileExternalVisibleStorage = true;
2402 }
2403
2404 /// Determine whether the given declaration is stored in the list of
2405 /// declarations lexically within this context.
2406 bool isDeclInLexicalTraversal(const Decl *D) const {
2407 return D && (D->NextInContextAndBits.getPointer() || D == FirstDecl ||
2408 D == LastDecl);
2409 }
2410
2411 bool setUseQualifiedLookup(bool use = true) const {
2412 bool old_value = DeclContextBits.UseQualifiedLookup;
2413 DeclContextBits.UseQualifiedLookup = use;
2414 return old_value;
2415 }
2416
2417 bool shouldUseQualifiedLookup() const {
2418 return DeclContextBits.UseQualifiedLookup;
2419 }
2420
2421 static bool classof(const Decl *D);
2422 static bool classof(const DeclContext *D) { return true; }
2423
2424 void dumpDeclContext() const;
2425 void dumpLookups() const;
2426 void dumpLookups(llvm::raw_ostream &OS, bool DumpDecls = false,
2427 bool Deserialize = false) const;
2428
2429private:
2430 /// Whether this declaration context has had externally visible
2431 /// storage added since the last lookup. In this case, \c LookupPtr's
2432 /// invariant may not hold and needs to be fixed before we perform
2433 /// another lookup.
2434 bool hasNeedToReconcileExternalVisibleStorage() const {
2435 return DeclContextBits.NeedToReconcileExternalVisibleStorage;
2436 }
2437
2438 /// State that this declaration context has had externally visible
2439 /// storage added since the last lookup. In this case, \c LookupPtr's
2440 /// invariant may not hold and needs to be fixed before we perform
2441 /// another lookup.
2442 void setNeedToReconcileExternalVisibleStorage(bool Need = true) const {
2443 DeclContextBits.NeedToReconcileExternalVisibleStorage = Need;
2444 }
2445
2446 /// If \c true, this context may have local lexical declarations
2447 /// that are missing from the lookup table.
2448 bool hasLazyLocalLexicalLookups() const {
2449 return DeclContextBits.HasLazyLocalLexicalLookups;
2450 }
2451
2452 /// If \c true, this context may have local lexical declarations
2453 /// that are missing from the lookup table.
2454 void setHasLazyLocalLexicalLookups(bool HasLLLL = true) const {
2455 DeclContextBits.HasLazyLocalLexicalLookups = HasLLLL;
2456 }
2457
2458 /// If \c true, the external source may have lexical declarations
2459 /// that are missing from the lookup table.
2460 bool hasLazyExternalLexicalLookups() const {
2461 return DeclContextBits.HasLazyExternalLexicalLookups;
2462 }
2463
2464 /// If \c true, the external source may have lexical declarations
2465 /// that are missing from the lookup table.
2466 void setHasLazyExternalLexicalLookups(bool HasLELL = true) const {
2467 DeclContextBits.HasLazyExternalLexicalLookups = HasLELL;
2468 }
2469
2470 void reconcileExternalVisibleStorage() const;
2471 bool LoadLexicalDeclsFromExternalStorage() const;
2472
2473 /// Makes a declaration visible within this context, but
2474 /// suppresses searches for external declarations with the same
2475 /// name.
2476 ///
2477 /// Analogous to makeDeclVisibleInContext, but for the exclusive
2478 /// use of addDeclInternal().
2479 void makeDeclVisibleInContextInternal(NamedDecl *D);
2480
2481 StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const;
2482
2483 void loadLazyLocalLexicalLookups();
2484 void buildLookupImpl(DeclContext *DCtx, bool Internal);
2485 void makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
2486 bool Rediscoverable);
2487 void makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal);
2488};
2489
2490inline bool Decl::isTemplateParameter() const {
2491 return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm ||
2492 getKind() == TemplateTemplateParm;
2493}
2494
2495// Specialization selected when ToTy is not a known subclass of DeclContext.
2496template <class ToTy,
2497 bool IsKnownSubtype = ::std::is_base_of<DeclContext, ToTy>::value>
2498struct cast_convert_decl_context {
2499 static const ToTy *doit(const DeclContext *Val) {
2500 return static_cast<const ToTy*>(Decl::castFromDeclContext(Val));
2501 }
2502
2503 static ToTy *doit(DeclContext *Val) {
2504 return static_cast<ToTy*>(Decl::castFromDeclContext(Val));
2505 }
2506};
2507
2508// Specialization selected when ToTy is a known subclass of DeclContext.
2509template <class ToTy>
2510struct cast_convert_decl_context<ToTy, true> {
2511 static const ToTy *doit(const DeclContext *Val) {
2512 return static_cast<const ToTy*>(Val);
2513 }
2514
2515 static ToTy *doit(DeclContext *Val) {
2516 return static_cast<ToTy*>(Val);
2517 }
2518};
2519
2520} // namespace clang
2521
2522namespace llvm {
2523
2524/// isa<T>(DeclContext*)
2525template <typename To>
2526struct isa_impl<To, ::clang::DeclContext> {
2527 static bool doit(const ::clang::DeclContext &Val) {
2528 return To::classofKind(Val.getDeclKind());
2529 }
2530};
2531
2532/// cast<T>(DeclContext*)
2533template<class ToTy>
2534struct cast_convert_val<ToTy,
2535 const ::clang::DeclContext,const ::clang::DeclContext> {
2536 static const ToTy &doit(const ::clang::DeclContext &Val) {
2537 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
2538 }
2539};
2540
2541template<class ToTy>
2542struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext> {
2543 static ToTy &doit(::clang::DeclContext &Val) {
2544 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
2545 }
2546};
2547
2548template<class ToTy>
2549struct cast_convert_val<ToTy,
2550 const ::clang::DeclContext*, const ::clang::DeclContext*> {
2551 static const ToTy *doit(const ::clang::DeclContext *Val) {
2552 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
2553 }
2554};
2555
2556template<class ToTy>
2557struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*> {
2558 static ToTy *doit(::clang::DeclContext *Val) {
2559 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
2560 }
2561};
2562
2563/// Implement cast_convert_val for Decl -> DeclContext conversions.
2564template<class FromTy>
2565struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> {
2566 static ::clang::DeclContext &doit(const FromTy &Val) {
2567 return *FromTy::castToDeclContext(&Val);
2568 }
2569};
2570
2571template<class FromTy>
2572struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> {
2573 static ::clang::DeclContext *doit(const FromTy *Val) {
2574 return FromTy::castToDeclContext(Val);
2575 }
2576};
2577
2578template<class FromTy>
2579struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> {
2580 static const ::clang::DeclContext &doit(const FromTy &Val) {
2581 return *FromTy::castToDeclContext(&Val);
2582 }
2583};
2584
2585template<class FromTy>
2586struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> {
2587 static const ::clang::DeclContext *doit(const FromTy *Val) {
2588 return FromTy::castToDeclContext(Val);
2589 }
2590};
2591
2592} // namespace llvm
2593
2594#endif // LLVM_CLANG_AST_DECLBASE_H

/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/Decl.h

1//===- Decl.h - Classes for representing declarations -----------*- 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 Decl subclasses.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_AST_DECL_H
14#define LLVM_CLANG_AST_DECL_H
15
16#include "clang/AST/APValue.h"
17#include "clang/AST/ASTContextAllocate.h"
18#include "clang/AST/DeclAccessPair.h"
19#include "clang/AST/DeclBase.h"
20#include "clang/AST/DeclarationName.h"
21#include "clang/AST/ExternalASTSource.h"
22#include "clang/AST/NestedNameSpecifier.h"
23#include "clang/AST/Redeclarable.h"
24#include "clang/AST/Type.h"
25#include "clang/Basic/AddressSpaces.h"
26#include "clang/Basic/Diagnostic.h"
27#include "clang/Basic/IdentifierTable.h"
28#include "clang/Basic/LLVM.h"
29#include "clang/Basic/Linkage.h"
30#include "clang/Basic/OperatorKinds.h"
31#include "clang/Basic/PartialDiagnostic.h"
32#include "clang/Basic/PragmaKinds.h"
33#include "clang/Basic/SourceLocation.h"
34#include "clang/Basic/Specifiers.h"
35#include "clang/Basic/Visibility.h"
36#include "llvm/ADT/APSInt.h"
37#include "llvm/ADT/ArrayRef.h"
38#include "llvm/ADT/Optional.h"
39#include "llvm/ADT/PointerIntPair.h"
40#include "llvm/ADT/PointerUnion.h"
41#include "llvm/ADT/StringRef.h"
42#include "llvm/ADT/iterator_range.h"
43#include "llvm/Support/Casting.h"
44#include "llvm/Support/Compiler.h"
45#include "llvm/Support/TrailingObjects.h"
46#include <cassert>
47#include <cstddef>
48#include <cstdint>
49#include <string>
50#include <utility>
51
52namespace clang {
53
54class ASTContext;
55struct ASTTemplateArgumentListInfo;
56class Attr;
57class CompoundStmt;
58class DependentFunctionTemplateSpecializationInfo;
59class EnumDecl;
60class Expr;
61class FunctionTemplateDecl;
62class FunctionTemplateSpecializationInfo;
63class FunctionTypeLoc;
64class LabelStmt;
65class MemberSpecializationInfo;
66class Module;
67class NamespaceDecl;
68class ParmVarDecl;
69class RecordDecl;
70class Stmt;
71class StringLiteral;
72class TagDecl;
73class TemplateArgumentList;
74class TemplateArgumentListInfo;
75class TemplateParameterList;
76class TypeAliasTemplateDecl;
77class TypeLoc;
78class UnresolvedSetImpl;
79class VarTemplateDecl;
80
81/// The top declaration context.
82class TranslationUnitDecl : public Decl, public DeclContext {
83 ASTContext &Ctx;
84
85 /// The (most recently entered) anonymous namespace for this
86 /// translation unit, if one has been created.
87 NamespaceDecl *AnonymousNamespace = nullptr;
88
89 explicit TranslationUnitDecl(ASTContext &ctx);
90
91 virtual void anchor();
92
93public:
94 ASTContext &getASTContext() const { return Ctx; }
95
96 NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; }
97 void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; }
98
99 static TranslationUnitDecl *Create(ASTContext &C);
100
101 // Implement isa/cast/dyncast/etc.
102 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
103 static bool classofKind(Kind K) { return K == TranslationUnit; }
104 static DeclContext *castToDeclContext(const TranslationUnitDecl *D) {
105 return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D));
106 }
107 static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) {
108 return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC));
109 }
110};
111
112/// Represents a `#pragma comment` line. Always a child of
113/// TranslationUnitDecl.
114class PragmaCommentDecl final
115 : public Decl,
116 private llvm::TrailingObjects<PragmaCommentDecl, char> {
117 friend class ASTDeclReader;
118 friend class ASTDeclWriter;
119 friend TrailingObjects;
120
121 PragmaMSCommentKind CommentKind;
122
123 PragmaCommentDecl(TranslationUnitDecl *TU, SourceLocation CommentLoc,
124 PragmaMSCommentKind CommentKind)
125 : Decl(PragmaComment, TU, CommentLoc), CommentKind(CommentKind) {}
126
127 virtual void anchor();
128
129public:
130 static PragmaCommentDecl *Create(const ASTContext &C, TranslationUnitDecl *DC,
131 SourceLocation CommentLoc,
132 PragmaMSCommentKind CommentKind,
133 StringRef Arg);
134 static PragmaCommentDecl *CreateDeserialized(ASTContext &C, unsigned ID,
135 unsigned ArgSize);
136
137 PragmaMSCommentKind getCommentKind() const { return CommentKind; }
138
139 StringRef getArg() const { return getTrailingObjects<char>(); }
140
141 // Implement isa/cast/dyncast/etc.
142 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
143 static bool classofKind(Kind K) { return K == PragmaComment; }
144};
145
146/// Represents a `#pragma detect_mismatch` line. Always a child of
147/// TranslationUnitDecl.
148class PragmaDetectMismatchDecl final
149 : public Decl,
150 private llvm::TrailingObjects<PragmaDetectMismatchDecl, char> {
151 friend class ASTDeclReader;
152 friend class ASTDeclWriter;
153 friend TrailingObjects;
154
155 size_t ValueStart;
156
157 PragmaDetectMismatchDecl(TranslationUnitDecl *TU, SourceLocation Loc,
158 size_t ValueStart)
159 : Decl(PragmaDetectMismatch, TU, Loc), ValueStart(ValueStart) {}
160
161 virtual void anchor();
162
163public:
164 static PragmaDetectMismatchDecl *Create(const ASTContext &C,
165 TranslationUnitDecl *DC,
166 SourceLocation Loc, StringRef Name,
167 StringRef Value);
168 static PragmaDetectMismatchDecl *
169 CreateDeserialized(ASTContext &C, unsigned ID, unsigned NameValueSize);
170
171 StringRef getName() const { return getTrailingObjects<char>(); }
172 StringRef getValue() const { return getTrailingObjects<char>() + ValueStart; }
173
174 // Implement isa/cast/dyncast/etc.
175 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
176 static bool classofKind(Kind K) { return K == PragmaDetectMismatch; }
177};
178
179/// Declaration context for names declared as extern "C" in C++. This
180/// is neither the semantic nor lexical context for such declarations, but is
181/// used to check for conflicts with other extern "C" declarations. Example:
182///
183/// \code
184/// namespace N { extern "C" void f(); } // #1
185/// void N::f() {} // #2
186/// namespace M { extern "C" void f(); } // #3
187/// \endcode
188///
189/// The semantic context of #1 is namespace N and its lexical context is the
190/// LinkageSpecDecl; the semantic context of #2 is namespace N and its lexical
191/// context is the TU. However, both declarations are also visible in the
192/// extern "C" context.
193///
194/// The declaration at #3 finds it is a redeclaration of \c N::f through
195/// lookup in the extern "C" context.
196class ExternCContextDecl : public Decl, public DeclContext {
197 explicit ExternCContextDecl(TranslationUnitDecl *TU)
198 : Decl(ExternCContext, TU, SourceLocation()),
199 DeclContext(ExternCContext) {}
200
201 virtual void anchor();
202
203public:
204 static ExternCContextDecl *Create(const ASTContext &C,
205 TranslationUnitDecl *TU);
206
207 // Implement isa/cast/dyncast/etc.
208 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
209 static bool classofKind(Kind K) { return K == ExternCContext; }
210 static DeclContext *castToDeclContext(const ExternCContextDecl *D) {
211 return static_cast<DeclContext *>(const_cast<ExternCContextDecl*>(D));
212 }
213 static ExternCContextDecl *castFromDeclContext(const DeclContext *DC) {
214 return static_cast<ExternCContextDecl *>(const_cast<DeclContext*>(DC));
215 }
216};
217
218/// This represents a decl that may have a name. Many decls have names such
219/// as ObjCMethodDecl, but not \@class, etc.
220///
221/// Note that not every NamedDecl is actually named (e.g., a struct might
222/// be anonymous), and not every name is an identifier.
223class NamedDecl : public Decl {
224 /// The name of this declaration, which is typically a normal
225 /// identifier but may also be a special kind of name (C++
226 /// constructor, Objective-C selector, etc.)
227 DeclarationName Name;
228
229 virtual void anchor();
230
231private:
232 NamedDecl *getUnderlyingDeclImpl() LLVM_READONLY__attribute__((__pure__));
233
234protected:
235 NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
236 : Decl(DK, DC, L), Name(N) {}
237
238public:
239 /// Get the identifier that names this declaration, if there is one.
240 ///
241 /// This will return NULL if this declaration has no name (e.g., for
242 /// an unnamed class) or if the name is a special name (C++ constructor,
243 /// Objective-C selector, etc.).
244 IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); }
245
246 /// Get the name of identifier for this declaration as a StringRef.
247 ///
248 /// This requires that the declaration have a name and that it be a simple
249 /// identifier.
250 StringRef getName() const {
251 assert(Name.isIdentifier() && "Name is not a simple identifier")((Name.isIdentifier() && "Name is not a simple identifier"
) ? static_cast<void> (0) : __assert_fail ("Name.isIdentifier() && \"Name is not a simple identifier\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/Decl.h"
, 251, __PRETTY_FUNCTION__))
;
252 return getIdentifier() ? getIdentifier()->getName() : "";
253 }
254
255 /// Get a human-readable name for the declaration, even if it is one of the
256 /// special kinds of names (C++ constructor, Objective-C selector, etc).
257 ///
258 /// Creating this name requires expensive string manipulation, so it should
259 /// be called only when performance doesn't matter. For simple declarations,
260 /// getNameAsCString() should suffice.
261 //
262 // FIXME: This function should be renamed to indicate that it is not just an
263 // alternate form of getName(), and clients should move as appropriate.
264 //
265 // FIXME: Deprecated, move clients to getName().
266 std::string getNameAsString() const { return Name.getAsString(); }
267
268 /// Pretty-print the unqualified name of this declaration. Can be overloaded
269 /// by derived classes to provide a more user-friendly name when appropriate.
270 virtual void printName(raw_ostream &os) const;
271
272 /// Get the actual, stored name of the declaration, which may be a special
273 /// name.
274 ///
275 /// Note that generally in diagnostics, the non-null \p NamedDecl* itself
276 /// should be sent into the diagnostic instead of using the result of
277 /// \p getDeclName().
278 ///
279 /// A \p DeclarationName in a diagnostic will just be streamed to the output,
280 /// which will directly result in a call to \p DeclarationName::print.
281 ///
282 /// A \p NamedDecl* in a diagnostic will also ultimately result in a call to
283 /// \p DeclarationName::print, but with two customisation points along the
284 /// way (\p getNameForDiagnostic and \p printName). These are used to print
285 /// the template arguments if any, and to provide a user-friendly name for
286 /// some entities (such as unnamed variables and anonymous records).
287 DeclarationName getDeclName() const { return Name; }
288
289 /// Set the name of this declaration.
290 void setDeclName(DeclarationName N) { Name = N; }
291
292 /// Returns a human-readable qualified name for this declaration, like
293 /// A::B::i, for i being member of namespace A::B.
294 ///
295 /// If the declaration is not a member of context which can be named (record,
296 /// namespace), it will return the same result as printName().
297 ///
298 /// Creating this name is expensive, so it should be called only when
299 /// performance doesn't matter.
300 void printQualifiedName(raw_ostream &OS) const;
301 void printQualifiedName(raw_ostream &OS, const PrintingPolicy &Policy) const;
302
303 /// Print only the nested name specifier part of a fully-qualified name,
304 /// including the '::' at the end. E.g.
305 /// when `printQualifiedName(D)` prints "A::B::i",
306 /// this function prints "A::B::".
307 void printNestedNameSpecifier(raw_ostream &OS) const;
308 void printNestedNameSpecifier(raw_ostream &OS,
309 const PrintingPolicy &Policy) const;
310
311 // FIXME: Remove string version.
312 std::string getQualifiedNameAsString() const;
313
314 /// Appends a human-readable name for this declaration into the given stream.
315 ///
316 /// This is the method invoked by Sema when displaying a NamedDecl
317 /// in a diagnostic. It does not necessarily produce the same
318 /// result as printName(); for example, class template
319 /// specializations are printed with their template arguments.
320 virtual void getNameForDiagnostic(raw_ostream &OS,
321 const PrintingPolicy &Policy,
322 bool Qualified) const;
323
324 /// Determine whether this declaration, if known to be well-formed within
325 /// its context, will replace the declaration OldD if introduced into scope.
326 ///
327 /// A declaration will replace another declaration if, for example, it is
328 /// a redeclaration of the same variable or function, but not if it is a
329 /// declaration of a different kind (function vs. class) or an overloaded
330 /// function.
331 ///
332 /// \param IsKnownNewer \c true if this declaration is known to be newer
333 /// than \p OldD (for instance, if this declaration is newly-created).
334 bool declarationReplaces(NamedDecl *OldD, bool IsKnownNewer = true) const;
335
336 /// Determine whether this declaration has linkage.
337 bool hasLinkage() const;
338
339 using Decl::isModulePrivate;
340 using Decl::setModulePrivate;
341
342 /// Determine whether this declaration is a C++ class member.
343 bool isCXXClassMember() const {
344 const DeclContext *DC = getDeclContext();
345
346 // C++0x [class.mem]p1:
347 // The enumerators of an unscoped enumeration defined in
348 // the class are members of the class.
349 if (isa<EnumDecl>(DC))
350 DC = DC->getRedeclContext();
351
352 return DC->isRecord();
353 }
354
355 /// Determine whether the given declaration is an instance member of
356 /// a C++ class.
357 bool isCXXInstanceMember() const;
358
359 /// Determine what kind of linkage this entity has.
360 ///
361 /// This is not the linkage as defined by the standard or the codegen notion
362 /// of linkage. It is just an implementation detail that is used to compute
363 /// those.
364 Linkage getLinkageInternal() const;
365
366 /// Get the linkage from a semantic point of view. Entities in
367 /// anonymous namespaces are external (in c++98).
368 Linkage getFormalLinkage() const {
369 return clang::getFormalLinkage(getLinkageInternal());
370 }
371
372 /// True if this decl has external linkage.
373 bool hasExternalFormalLinkage() const {
374 return isExternalFormalLinkage(getLinkageInternal());
375 }
376
377 bool isExternallyVisible() const {
378 return clang::isExternallyVisible(getLinkageInternal());
379 }
380
381 /// Determine whether this declaration can be redeclared in a
382 /// different translation unit.
383 bool isExternallyDeclarable() const {
384 return isExternallyVisible() && !getOwningModuleForLinkage();
385 }
386
387 /// Determines the visibility of this entity.
388 Visibility getVisibility() const {
389 return getLinkageAndVisibility().getVisibility();
390 }
391
392 /// Determines the linkage and visibility of this entity.
393 LinkageInfo getLinkageAndVisibility() const;
394
395 /// Kinds of explicit visibility.
396 enum ExplicitVisibilityKind {
397 /// Do an LV computation for, ultimately, a type.
398 /// Visibility may be restricted by type visibility settings and
399 /// the visibility of template arguments.
400 VisibilityForType,
401
402 /// Do an LV computation for, ultimately, a non-type declaration.
403 /// Visibility may be restricted by value visibility settings and
404 /// the visibility of template arguments.
405 VisibilityForValue
406 };
407
408 /// If visibility was explicitly specified for this
409 /// declaration, return that visibility.
410 Optional<Visibility>
411 getExplicitVisibility(ExplicitVisibilityKind kind) const;
412
413 /// True if the computed linkage is valid. Used for consistency
414 /// checking. Should always return true.
415 bool isLinkageValid() const;
416
417 /// True if something has required us to compute the linkage
418 /// of this declaration.
419 ///
420 /// Language features which can retroactively change linkage (like a
421 /// typedef name for linkage purposes) may need to consider this,
422 /// but hopefully only in transitory ways during parsing.
423 bool hasLinkageBeenComputed() const {
424 return hasCachedLinkage();
425 }
426
427 /// Looks through UsingDecls and ObjCCompatibleAliasDecls for
428 /// the underlying named decl.
429 NamedDecl *getUnderlyingDecl() {
430 // Fast-path the common case.
431 if (this->getKind() != UsingShadow &&
432 this->getKind() != ConstructorUsingShadow &&
433 this->getKind() != ObjCCompatibleAlias &&
434 this->getKind() != NamespaceAlias)
435 return this;
436
437 return getUnderlyingDeclImpl();
438 }
439 const NamedDecl *getUnderlyingDecl() const {
440 return const_cast<NamedDecl*>(this)->getUnderlyingDecl();
441 }
442
443 NamedDecl *getMostRecentDecl() {
444 return cast<NamedDecl>(static_cast<Decl *>(this)->getMostRecentDecl());
445 }
446 const NamedDecl *getMostRecentDecl() const {
447 return const_cast<NamedDecl*>(this)->getMostRecentDecl();
448 }
449
450 ObjCStringFormatFamily getObjCFStringFormattingFamily() const;
451
452 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
453 static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; }
454};
455
456inline raw_ostream &operator<<(raw_ostream &OS, const NamedDecl &ND) {
457 ND.printName(OS);
458 return OS;
459}
460
461/// Represents the declaration of a label. Labels also have a
462/// corresponding LabelStmt, which indicates the position that the label was
463/// defined at. For normal labels, the location of the decl is the same as the
464/// location of the statement. For GNU local labels (__label__), the decl
465/// location is where the __label__ is.
466class LabelDecl : public NamedDecl {
467 LabelStmt *TheStmt;
468 StringRef MSAsmName;
469 bool MSAsmNameResolved = false;
470
471 /// For normal labels, this is the same as the main declaration
472 /// label, i.e., the location of the identifier; for GNU local labels,
473 /// this is the location of the __label__ keyword.
474 SourceLocation LocStart;
475
476 LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II,
477 LabelStmt *S, SourceLocation StartL)
478 : NamedDecl(Label, DC, IdentL, II), TheStmt(S), LocStart(StartL) {}
479
480 void anchor() override;
481
482public:
483 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
484 SourceLocation IdentL, IdentifierInfo *II);
485 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
486 SourceLocation IdentL, IdentifierInfo *II,
487 SourceLocation GnuLabelL);
488 static LabelDecl *CreateDeserialized(ASTContext &C, unsigned ID);
489
490 LabelStmt *getStmt() const { return TheStmt; }
491 void setStmt(LabelStmt *T) { TheStmt = T; }
492
493 bool isGnuLocal() const { return LocStart != getLocation(); }
494 void setLocStart(SourceLocation L) { LocStart = L; }
495
496 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
497 return SourceRange(LocStart, getLocation());
498 }
499
500 bool isMSAsmLabel() const { return !MSAsmName.empty(); }
501 bool isResolvedMSAsmLabel() const { return isMSAsmLabel() && MSAsmNameResolved; }
502 void setMSAsmLabel(StringRef Name);
503 StringRef getMSAsmLabel() const { return MSAsmName; }
504 void setMSAsmLabelResolved() { MSAsmNameResolved = true; }
505
506 // Implement isa/cast/dyncast/etc.
507 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
508 static bool classofKind(Kind K) { return K == Label; }
509};
510
511/// Represent a C++ namespace.
512class NamespaceDecl : public NamedDecl, public DeclContext,
513 public Redeclarable<NamespaceDecl>
514{
515 /// The starting location of the source range, pointing
516 /// to either the namespace or the inline keyword.
517 SourceLocation LocStart;
518
519 /// The ending location of the source range.
520 SourceLocation RBraceLoc;
521
522 /// A pointer to either the anonymous namespace that lives just inside
523 /// this namespace or to the first namespace in the chain (the latter case
524 /// only when this is not the first in the chain), along with a
525 /// boolean value indicating whether this is an inline namespace.
526 llvm::PointerIntPair<NamespaceDecl *, 1, bool> AnonOrFirstNamespaceAndInline;
527
528 NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline,
529 SourceLocation StartLoc, SourceLocation IdLoc,
530 IdentifierInfo *Id, NamespaceDecl *PrevDecl);
531
532 using redeclarable_base = Redeclarable<NamespaceDecl>;
533
534 NamespaceDecl *getNextRedeclarationImpl() override;
535 NamespaceDecl *getPreviousDeclImpl() override;
536 NamespaceDecl *getMostRecentDeclImpl() override;
537
538public:
539 friend class ASTDeclReader;
540 friend class ASTDeclWriter;
541
542 static NamespaceDecl *Create(ASTContext &C, DeclContext *DC,
543 bool Inline, SourceLocation StartLoc,
544 SourceLocation IdLoc, IdentifierInfo *Id,
545 NamespaceDecl *PrevDecl);
546
547 static NamespaceDecl *CreateDeserialized(ASTContext &C, unsigned ID);
548
549 using redecl_range = redeclarable_base::redecl_range;
550 using redecl_iterator = redeclarable_base::redecl_iterator;
551
552 using redeclarable_base::redecls_begin;
553 using redeclarable_base::redecls_end;
554 using redeclarable_base::redecls;
555 using redeclarable_base::getPreviousDecl;
556 using redeclarable_base::getMostRecentDecl;
557 using redeclarable_base::isFirstDecl;
558
559 /// Returns true if this is an anonymous namespace declaration.
560 ///
561 /// For example:
562 /// \code
563 /// namespace {
564 /// ...
565 /// };
566 /// \endcode
567 /// q.v. C++ [namespace.unnamed]
568 bool isAnonymousNamespace() const {
569 return !getIdentifier();
570 }
571
572 /// Returns true if this is an inline namespace declaration.
573 bool isInline() const {
574 return AnonOrFirstNamespaceAndInline.getInt();
575 }
576
577 /// Set whether this is an inline namespace declaration.
578 void setInline(bool Inline) {
579 AnonOrFirstNamespaceAndInline.setInt(Inline);
580 }
581
582 /// Get the original (first) namespace declaration.
583 NamespaceDecl *getOriginalNamespace();
584
585 /// Get the original (first) namespace declaration.
586 const NamespaceDecl *getOriginalNamespace() const;
587
588 /// Return true if this declaration is an original (first) declaration
589 /// of the namespace. This is false for non-original (subsequent) namespace
590 /// declarations and anonymous namespaces.
591 bool isOriginalNamespace() const;
592
593 /// Retrieve the anonymous namespace nested inside this namespace,
594 /// if any.
595 NamespaceDecl *getAnonymousNamespace() const {
596 return getOriginalNamespace()->AnonOrFirstNamespaceAndInline.getPointer();
597 }
598
599 void setAnonymousNamespace(NamespaceDecl *D) {
600 getOriginalNamespace()->AnonOrFirstNamespaceAndInline.setPointer(D);
601 }
602
603 /// Retrieves the canonical declaration of this namespace.
604 NamespaceDecl *getCanonicalDecl() override {
605 return getOriginalNamespace();
606 }
607 const NamespaceDecl *getCanonicalDecl() const {
608 return getOriginalNamespace();
609 }
610
611 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
612 return SourceRange(LocStart, RBraceLoc);
613 }
614
615 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return LocStart; }
616 SourceLocation getRBraceLoc() const { return RBraceLoc; }
617 void setLocStart(SourceLocation L) { LocStart = L; }
618 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
619
620 // Implement isa/cast/dyncast/etc.
621 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
622 static bool classofKind(Kind K) { return K == Namespace; }
623 static DeclContext *castToDeclContext(const NamespaceDecl *D) {
624 return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D));
625 }
626 static NamespaceDecl *castFromDeclContext(const DeclContext *DC) {
627 return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC));
628 }
629};
630
631/// Represent the declaration of a variable (in which case it is
632/// an lvalue) a function (in which case it is a function designator) or
633/// an enum constant.
634class ValueDecl : public NamedDecl {
635 QualType DeclType;
636
637 void anchor() override;
638
639protected:
640 ValueDecl(Kind DK, DeclContext *DC, SourceLocation L,
641 DeclarationName N, QualType T)
642 : NamedDecl(DK, DC, L, N), DeclType(T) {}
643
644public:
645 QualType getType() const { return DeclType; }
646 void setType(QualType newType) { DeclType = newType; }
647
648 /// Determine whether this symbol is weakly-imported,
649 /// or declared with the weak or weak-ref attr.
650 bool isWeak() const;
651
652 // Implement isa/cast/dyncast/etc.
653 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
654 static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; }
655};
656
657/// A struct with extended info about a syntactic
658/// name qualifier, to be used for the case of out-of-line declarations.
659struct QualifierInfo {
660 NestedNameSpecifierLoc QualifierLoc;
661
662 /// The number of "outer" template parameter lists.
663 /// The count includes all of the template parameter lists that were matched
664 /// against the template-ids occurring into the NNS and possibly (in the
665 /// case of an explicit specialization) a final "template <>".
666 unsigned NumTemplParamLists = 0;
667
668 /// A new-allocated array of size NumTemplParamLists,
669 /// containing pointers to the "outer" template parameter lists.
670 /// It includes all of the template parameter lists that were matched
671 /// against the template-ids occurring into the NNS and possibly (in the
672 /// case of an explicit specialization) a final "template <>".
673 TemplateParameterList** TemplParamLists = nullptr;
674
675 QualifierInfo() = default;
676 QualifierInfo(const QualifierInfo &) = delete;
677 QualifierInfo& operator=(const QualifierInfo &) = delete;
678
679 /// Sets info about "outer" template parameter lists.
680 void setTemplateParameterListsInfo(ASTContext &Context,
681 ArrayRef<TemplateParameterList *> TPLists);
682};
683
684/// Represents a ValueDecl that came out of a declarator.
685/// Contains type source information through TypeSourceInfo.
686class DeclaratorDecl : public ValueDecl {
687 // A struct representing a TInfo, a trailing requires-clause and a syntactic
688 // qualifier, to be used for the (uncommon) case of out-of-line declarations
689 // and constrained function decls.
690 struct ExtInfo : public QualifierInfo {
691 TypeSourceInfo *TInfo;
692 Expr *TrailingRequiresClause = nullptr;
693 };
694
695 llvm::PointerUnion<TypeSourceInfo *, ExtInfo *> DeclInfo;
696
697 /// The start of the source range for this declaration,
698 /// ignoring outer template declarations.
699 SourceLocation InnerLocStart;
700
701 bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); }
702 ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); }
703 const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); }
704
705protected:
706 DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L,
707 DeclarationName N, QualType T, TypeSourceInfo *TInfo,
708 SourceLocation StartL)
709 : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) {}
710
711public:
712 friend class ASTDeclReader;
713 friend class ASTDeclWriter;
714
715 TypeSourceInfo *getTypeSourceInfo() const {
716 return hasExtInfo()
717 ? getExtInfo()->TInfo
718 : DeclInfo.get<TypeSourceInfo*>();
719 }
720
721 void setTypeSourceInfo(TypeSourceInfo *TI) {
722 if (hasExtInfo())
723 getExtInfo()->TInfo = TI;
724 else
725 DeclInfo = TI;
726 }
727
728 /// Return start of source range ignoring outer template declarations.
729 SourceLocation getInnerLocStart() const { return InnerLocStart; }
730 void setInnerLocStart(SourceLocation L) { InnerLocStart = L; }
731
732 /// Return start of source range taking into account any outer template
733 /// declarations.
734 SourceLocation getOuterLocStart() const;
735
736 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
737
738 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
739 return getOuterLocStart();
740 }
741
742 /// Retrieve the nested-name-specifier that qualifies the name of this
743 /// declaration, if it was present in the source.
744 NestedNameSpecifier *getQualifier() const {
745 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
746 : nullptr;
747 }
748
749 /// Retrieve the nested-name-specifier (with source-location
750 /// information) that qualifies the name of this declaration, if it was
751 /// present in the source.
752 NestedNameSpecifierLoc getQualifierLoc() const {
753 return hasExtInfo() ? getExtInfo()->QualifierLoc
754 : NestedNameSpecifierLoc();
755 }
756
757 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
758
759 /// \brief Get the constraint-expression introduced by the trailing
760 /// requires-clause in the function/member declaration, or null if no
761 /// requires-clause was provided.
762 Expr *getTrailingRequiresClause() {
763 return hasExtInfo() ? getExtInfo()->TrailingRequiresClause
764 : nullptr;
765 }
766
767 const Expr *getTrailingRequiresClause() const {
768 return hasExtInfo() ? getExtInfo()->TrailingRequiresClause
769 : nullptr;
770 }
771
772 void setTrailingRequiresClause(Expr *TrailingRequiresClause);
773
774 unsigned getNumTemplateParameterLists() const {
775 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
776 }
777
778 TemplateParameterList *getTemplateParameterList(unsigned index) const {
779 assert(index < getNumTemplateParameterLists())((index < getNumTemplateParameterLists()) ? static_cast<
void> (0) : __assert_fail ("index < getNumTemplateParameterLists()"
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/Decl.h"
, 779, __PRETTY_FUNCTION__))
;
780 return getExtInfo()->TemplParamLists[index];
781 }
782
783 void setTemplateParameterListsInfo(ASTContext &Context,
784 ArrayRef<TemplateParameterList *> TPLists);
785
786 SourceLocation getTypeSpecStartLoc() const;
787 SourceLocation getTypeSpecEndLoc() const;
788
789 // Implement isa/cast/dyncast/etc.
790 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
791 static bool classofKind(Kind K) {
792 return K >= firstDeclarator && K <= lastDeclarator;
793 }
794};
795
796/// Structure used to store a statement, the constant value to
797/// which it was evaluated (if any), and whether or not the statement
798/// is an integral constant expression (if known).
799struct EvaluatedStmt {
800 /// Whether this statement was already evaluated.
801 bool WasEvaluated : 1;
802
803 /// Whether this statement is being evaluated.
804 bool IsEvaluating : 1;
805
806 /// Whether we already checked whether this statement was an
807 /// integral constant expression.
808 bool CheckedICE : 1;
809
810 /// Whether we are checking whether this statement is an
811 /// integral constant expression.
812 bool CheckingICE : 1;
813
814 /// Whether this statement is an integral constant expression,
815 /// or in C++11, whether the statement is a constant expression. Only
816 /// valid if CheckedICE is true.
817 bool IsICE : 1;
818
819 /// Whether this variable is known to have constant destruction. That is,
820 /// whether running the destructor on the initial value is a side-effect
821 /// (and doesn't inspect any state that might have changed during program
822 /// execution). This is currently only computed if the destructor is
823 /// non-trivial.
824 bool HasConstantDestruction : 1;
825
826 Stmt *Value;
827 APValue Evaluated;
828
829 EvaluatedStmt()
830 : WasEvaluated(false), IsEvaluating(false), CheckedICE(false),
831 CheckingICE(false), IsICE(false), HasConstantDestruction(false) {}
832};
833
834/// Represents a variable declaration or definition.
835class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> {
836public:
837 /// Initialization styles.
838 enum InitializationStyle {
839 /// C-style initialization with assignment
840 CInit,
841
842 /// Call-style initialization (C++98)
843 CallInit,
844
845 /// Direct list-initialization (C++11)
846 ListInit
847 };
848
849 /// Kinds of thread-local storage.
850 enum TLSKind {
851 /// Not a TLS variable.
852 TLS_None,
853
854 /// TLS with a known-constant initializer.
855 TLS_Static,
856
857 /// TLS with a dynamic initializer.
858 TLS_Dynamic
859 };
860
861 /// Return the string used to specify the storage class \p SC.
862 ///
863 /// It is illegal to call this function with SC == None.
864 static const char *getStorageClassSpecifierString(StorageClass SC);
865
866protected:
867 // A pointer union of Stmt * and EvaluatedStmt *. When an EvaluatedStmt, we
868 // have allocated the auxiliary struct of information there.
869 //
870 // TODO: It is a bit unfortunate to use a PointerUnion inside the VarDecl for
871 // this as *many* VarDecls are ParmVarDecls that don't have default
872 // arguments. We could save some space by moving this pointer union to be
873 // allocated in trailing space when necessary.
874 using InitType = llvm::PointerUnion<Stmt *, EvaluatedStmt *>;
875
876 /// The initializer for this variable or, for a ParmVarDecl, the
877 /// C++ default argument.
878 mutable InitType Init;
879
880private:
881 friend class ASTDeclReader;
882 friend class ASTNodeImporter;
883 friend class StmtIteratorBase;
884
885 class VarDeclBitfields {
886 friend class ASTDeclReader;
887 friend class VarDecl;
888
889 unsigned SClass : 3;
890 unsigned TSCSpec : 2;
891 unsigned InitStyle : 2;
892
893 /// Whether this variable is an ARC pseudo-__strong variable; see
894 /// isARCPseudoStrong() for details.
895 unsigned ARCPseudoStrong : 1;
896 };
897 enum { NumVarDeclBits = 8 };
898
899protected:
900 enum { NumParameterIndexBits = 8 };
901
902 enum DefaultArgKind {
903 DAK_None,
904 DAK_Unparsed,
905 DAK_Uninstantiated,
906 DAK_Normal
907 };
908
909 enum { NumScopeDepthOrObjCQualsBits = 7 };
910
911 class ParmVarDeclBitfields {
912 friend class ASTDeclReader;
913 friend class ParmVarDecl;
914
915 unsigned : NumVarDeclBits;
916
917 /// Whether this parameter inherits a default argument from a
918 /// prior declaration.
919 unsigned HasInheritedDefaultArg : 1;
920
921 /// Describes the kind of default argument for this parameter. By default
922 /// this is none. If this is normal, then the default argument is stored in
923 /// the \c VarDecl initializer expression unless we were unable to parse
924 /// (even an invalid) expression for the default argument.
925 unsigned DefaultArgKind : 2;
926
927 /// Whether this parameter undergoes K&R argument promotion.
928 unsigned IsKNRPromoted : 1;
929
930 /// Whether this parameter is an ObjC method parameter or not.
931 unsigned IsObjCMethodParam : 1;
932
933 /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier.
934 /// Otherwise, the number of function parameter scopes enclosing
935 /// the function parameter scope in which this parameter was
936 /// declared.
937 unsigned ScopeDepthOrObjCQuals : NumScopeDepthOrObjCQualsBits;
938
939 /// The number of parameters preceding this parameter in the
940 /// function parameter scope in which it was declared.
941 unsigned ParameterIndex : NumParameterIndexBits;
942 };
943
944 class NonParmVarDeclBitfields {
945 friend class ASTDeclReader;
946 friend class ImplicitParamDecl;
947 friend class VarDecl;
948
949 unsigned : NumVarDeclBits;
950
951 // FIXME: We need something similar to CXXRecordDecl::DefinitionData.
952 /// Whether this variable is a definition which was demoted due to
953 /// module merge.
954 unsigned IsThisDeclarationADemotedDefinition : 1;
955
956 /// Whether this variable is the exception variable in a C++ catch
957 /// or an Objective-C @catch statement.
958 unsigned ExceptionVar : 1;
959
960 /// Whether this local variable could be allocated in the return
961 /// slot of its function, enabling the named return value optimization
962 /// (NRVO).
963 unsigned NRVOVariable : 1;
964
965 /// Whether this variable is the for-range-declaration in a C++0x
966 /// for-range statement.
967 unsigned CXXForRangeDecl : 1;
968
969 /// Whether this variable is the for-in loop declaration in Objective-C.
970 unsigned ObjCForDecl : 1;
971
972 /// Whether this variable is (C++1z) inline.
973 unsigned IsInline : 1;
974
975 /// Whether this variable has (C++1z) inline explicitly specified.
976 unsigned IsInlineSpecified : 1;
977
978 /// Whether this variable is (C++0x) constexpr.
979 unsigned IsConstexpr : 1;
980
981 /// Whether this variable is the implicit variable for a lambda
982 /// init-capture.
983 unsigned IsInitCapture : 1;
984
985 /// Whether this local extern variable's previous declaration was
986 /// declared in the same block scope. This controls whether we should merge
987 /// the type of this declaration with its previous declaration.
988 unsigned PreviousDeclInSameBlockScope : 1;
989
990 /// Defines kind of the ImplicitParamDecl: 'this', 'self', 'vtt', '_cmd' or
991 /// something else.
992 unsigned ImplicitParamKind : 3;
993
994 unsigned EscapingByref : 1;
995 };
996
997 union {
998 unsigned AllBits;
999 VarDeclBitfields VarDeclBits;
1000 ParmVarDeclBitfields ParmVarDeclBits;
1001 NonParmVarDeclBitfields NonParmVarDeclBits;
1002 };
1003
1004 VarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1005 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
1006 TypeSourceInfo *TInfo, StorageClass SC);
1007
1008 using redeclarable_base = Redeclarable<VarDecl>;
1009
1010 VarDecl *getNextRedeclarationImpl() override {
1011 return getNextRedeclaration();
1012 }
1013
1014 VarDecl *getPreviousDeclImpl() override {
1015 return getPreviousDecl();
1016 }
1017
1018 VarDecl *getMostRecentDeclImpl() override {
1019 return getMostRecentDecl();
1020 }
1021
1022public:
1023 using redecl_range = redeclarable_base::redecl_range;
1024 using redecl_iterator = redeclarable_base::redecl_iterator;
1025
1026 using redeclarable_base::redecls_begin;
1027 using redeclarable_base::redecls_end;
1028 using redeclarable_base::redecls;
1029 using redeclarable_base::getPreviousDecl;
1030 using redeclarable_base::getMostRecentDecl;
1031 using redeclarable_base::isFirstDecl;
1032
1033 static VarDecl *Create(ASTContext &C, DeclContext *DC,
1034 SourceLocation StartLoc, SourceLocation IdLoc,
1035 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1036 StorageClass S);
1037
1038 static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1039
1040 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1041
1042 /// Returns the storage class as written in the source. For the
1043 /// computed linkage of symbol, see getLinkage.
1044 StorageClass getStorageClass() const {
1045 return (StorageClass) VarDeclBits.SClass;
1046 }
1047 void setStorageClass(StorageClass SC);
1048
1049 void setTSCSpec(ThreadStorageClassSpecifier TSC) {
1050 VarDeclBits.TSCSpec = TSC;
1051 assert(VarDeclBits.TSCSpec == TSC && "truncation")((VarDeclBits.TSCSpec == TSC && "truncation") ? static_cast
<void> (0) : __assert_fail ("VarDeclBits.TSCSpec == TSC && \"truncation\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/Decl.h"
, 1051, __PRETTY_FUNCTION__))
;
1052 }
1053 ThreadStorageClassSpecifier getTSCSpec() const {
1054 return static_cast<ThreadStorageClassSpecifier>(VarDeclBits.TSCSpec);
1055 }
1056 TLSKind getTLSKind() const;
1057
1058 /// Returns true if a variable with function scope is a non-static local
1059 /// variable.
1060 bool hasLocalStorage() const {
1061 if (getStorageClass() == SC_None) {
15
Assuming the condition is false
16
Taking false branch
1062 // OpenCL v1.2 s6.5.3: The __constant or constant address space name is
1063 // used to describe variables allocated in global memory and which are
1064 // accessed inside a kernel(s) as read-only variables. As such, variables
1065 // in constant address space cannot have local storage.
1066 if (getType().getAddressSpace() == LangAS::opencl_constant)
1067 return false;
1068 // Second check is for C++11 [dcl.stc]p4.
1069 return !isFileVarDecl() && getTSCSpec() == TSCS_unspecified;
1070 }
1071
1072 // Global Named Register (GNU extension)
1073 if (getStorageClass() == SC_Register && !isLocalVarDeclOrParm())
17
Assuming the condition is false
1074 return false;
1075
1076 // Return true for: Auto, Register.
1077 // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal.
1078
1079 return getStorageClass() >= SC_Auto;
18
Assuming the condition is false
19
Returning zero, which participates in a condition later
1080 }
1081
1082 /// Returns true if a variable with function scope is a static local
1083 /// variable.
1084 bool isStaticLocal() const {
1085 return (getStorageClass() == SC_Static ||
1086 // C++11 [dcl.stc]p4
1087 (getStorageClass() == SC_None && getTSCSpec() == TSCS_thread_local))
1088 && !isFileVarDecl();
1089 }
1090
1091 /// Returns true if a variable has extern or __private_extern__
1092 /// storage.
1093 bool hasExternalStorage() const {
1094 return getStorageClass() == SC_Extern ||
1095 getStorageClass() == SC_PrivateExtern;
1096 }
1097
1098 /// Returns true for all variables that do not have local storage.
1099 ///
1100 /// This includes all global variables as well as static variables declared
1101 /// within a function.
1102 bool hasGlobalStorage() const { return !hasLocalStorage(); }
1103
1104 /// Get the storage duration of this variable, per C++ [basic.stc].
1105 StorageDuration getStorageDuration() const {
1106 return hasLocalStorage() ? SD_Automatic :
1107 getTSCSpec() ? SD_Thread : SD_Static;
1108 }
1109
1110 /// Compute the language linkage.
1111 LanguageLinkage getLanguageLinkage() const;
1112
1113 /// Determines whether this variable is a variable with external, C linkage.
1114 bool isExternC() const;
1115
1116 /// Determines whether this variable's context is, or is nested within,
1117 /// a C++ extern "C" linkage spec.
1118 bool isInExternCContext() const;
1119
1120 /// Determines whether this variable's context is, or is nested within,
1121 /// a C++ extern "C++" linkage spec.
1122 bool isInExternCXXContext() const;
1123
1124 /// Returns true for local variable declarations other than parameters.
1125 /// Note that this includes static variables inside of functions. It also
1126 /// includes variables inside blocks.
1127 ///
1128 /// void foo() { int x; static int y; extern int z; }
1129 bool isLocalVarDecl() const {
1130 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1131 return false;
1132 if (const DeclContext *DC = getLexicalDeclContext())
1133 return DC->getRedeclContext()->isFunctionOrMethod();
1134 return false;
1135 }
1136
1137 /// Similar to isLocalVarDecl but also includes parameters.
1138 bool isLocalVarDeclOrParm() const {
1139 return isLocalVarDecl() || getKind() == Decl::ParmVar;
1140 }
1141
1142 /// Similar to isLocalVarDecl, but excludes variables declared in blocks.
1143 bool isFunctionOrMethodVarDecl() const {
1144 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1145 return false;
1146 const DeclContext *DC = getLexicalDeclContext()->getRedeclContext();
1147 return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block;
1148 }
1149
1150 /// Determines whether this is a static data member.
1151 ///
1152 /// This will only be true in C++, and applies to, e.g., the
1153 /// variable 'x' in:
1154 /// \code
1155 /// struct S {
1156 /// static int x;
1157 /// };
1158 /// \endcode
1159 bool isStaticDataMember() const {
1160 // If it wasn't static, it would be a FieldDecl.
1161 return getKind() != Decl::ParmVar && getDeclContext()->isRecord();
1162 }
1163
1164 VarDecl *getCanonicalDecl() override;
1165 const VarDecl *getCanonicalDecl() const {
1166 return const_cast<VarDecl*>(this)->getCanonicalDecl();
1167 }
1168
1169 enum DefinitionKind {
1170 /// This declaration is only a declaration.
1171 DeclarationOnly,
1172
1173 /// This declaration is a tentative definition.
1174 TentativeDefinition,
1175
1176 /// This declaration is definitely a definition.
1177 Definition
1178 };
1179
1180 /// Check whether this declaration is a definition. If this could be
1181 /// a tentative definition (in C), don't check whether there's an overriding
1182 /// definition.
1183 DefinitionKind isThisDeclarationADefinition(ASTContext &) const;
1184 DefinitionKind isThisDeclarationADefinition() const {
1185 return isThisDeclarationADefinition(getASTContext());
1186 }
1187
1188 /// Check whether this variable is defined in this translation unit.
1189 DefinitionKind hasDefinition(ASTContext &) const;
1190 DefinitionKind hasDefinition() const {
1191 return hasDefinition(getASTContext());
1192 }
1193
1194 /// Get the tentative definition that acts as the real definition in a TU.
1195 /// Returns null if there is a proper definition available.
1196 VarDecl *getActingDefinition();
1197 const VarDecl *getActingDefinition() const {
1198 return const_cast<VarDecl*>(this)->getActingDefinition();
1199 }
1200
1201 /// Get the real (not just tentative) definition for this declaration.
1202 VarDecl *getDefinition(ASTContext &);
1203 const VarDecl *getDefinition(ASTContext &C) const {
1204 return const_cast<VarDecl*>(this)->getDefinition(C);
1205 }
1206 VarDecl *getDefinition() {
1207 return getDefinition(getASTContext());
1208 }
1209 const VarDecl *getDefinition() const {
1210 return const_cast<VarDecl*>(this)->getDefinition();
1211 }
1212
1213 /// Determine whether this is or was instantiated from an out-of-line
1214 /// definition of a static data member.
1215 bool isOutOfLine() const override;
1216
1217 /// Returns true for file scoped variable declaration.
1218 bool isFileVarDecl() const {
1219 Kind K = getKind();
1220 if (K == ParmVar || K == ImplicitParam)
1221 return false;
1222
1223 if (getLexicalDeclContext()->getRedeclContext()->isFileContext())
1224 return true;
1225
1226 if (isStaticDataMember())
1227 return true;
1228
1229 return false;
1230 }
1231
1232 /// Get the initializer for this variable, no matter which
1233 /// declaration it is attached to.
1234 const Expr *getAnyInitializer() const {
1235 const VarDecl *D;
1236 return getAnyInitializer(D);
1237 }
1238
1239 /// Get the initializer for this variable, no matter which
1240 /// declaration it is attached to. Also get that declaration.
1241 const Expr *getAnyInitializer(const VarDecl *&D) const;
1242
1243 bool hasInit() const;
1244 const Expr *getInit() const {
1245 return const_cast<VarDecl *>(this)->getInit();
1246 }
1247 Expr *getInit();
1248
1249 /// Retrieve the address of the initializer expression.
1250 Stmt **getInitAddress();
1251
1252 void setInit(Expr *I);
1253
1254 /// Get the initializing declaration of this variable, if any. This is
1255 /// usually the definition, except that for a static data member it can be
1256 /// the in-class declaration.
1257 VarDecl *getInitializingDeclaration();
1258 const VarDecl *getInitializingDeclaration() const {
1259 return const_cast<VarDecl *>(this)->getInitializingDeclaration();
1260 }
1261
1262 /// Determine whether this variable's value might be usable in a
1263 /// constant expression, according to the relevant language standard.
1264 /// This only checks properties of the declaration, and does not check
1265 /// whether the initializer is in fact a constant expression.
1266 bool mightBeUsableInConstantExpressions(ASTContext &C) const;
1267
1268 /// Determine whether this variable's value can be used in a
1269 /// constant expression, according to the relevant language standard,
1270 /// including checking whether it was initialized by a constant expression.
1271 bool isUsableInConstantExpressions(ASTContext &C) const;
1272
1273 EvaluatedStmt *ensureEvaluatedStmt() const;
1274
1275 /// Attempt to evaluate the value of the initializer attached to this
1276 /// declaration, and produce notes explaining why it cannot be evaluated or is
1277 /// not a constant expression. Returns a pointer to the value if evaluation
1278 /// succeeded, 0 otherwise.
1279 APValue *evaluateValue() const;
1280 APValue *evaluateValue(SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
1281
1282 /// Return the already-evaluated value of this variable's
1283 /// initializer, or NULL if the value is not yet known. Returns pointer
1284 /// to untyped APValue if the value could not be evaluated.
1285 APValue *getEvaluatedValue() const;
1286
1287 /// Evaluate the destruction of this variable to determine if it constitutes
1288 /// constant destruction.
1289 ///
1290 /// \pre isInitICE()
1291 /// \return \c true if this variable has constant destruction, \c false if
1292 /// not.
1293 bool evaluateDestruction(SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
1294
1295 /// Determines whether it is already known whether the
1296 /// initializer is an integral constant expression or not.
1297 bool isInitKnownICE() const;
1298
1299 /// Determines whether the initializer is an integral constant
1300 /// expression, or in C++11, whether the initializer is a constant
1301 /// expression.
1302 ///
1303 /// \pre isInitKnownICE()
1304 bool isInitICE() const;
1305
1306 /// Determine whether the value of the initializer attached to this
1307 /// declaration is an integral constant expression.
1308 bool checkInitIsICE() const;
1309
1310 void setInitStyle(InitializationStyle Style) {
1311 VarDeclBits.InitStyle = Style;
1312 }
1313
1314 /// The style of initialization for this declaration.
1315 ///
1316 /// C-style initialization is "int x = 1;". Call-style initialization is
1317 /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be
1318 /// the expression inside the parens or a "ClassType(a,b,c)" class constructor
1319 /// expression for class types. List-style initialization is C++11 syntax,
1320 /// e.g. "int x{1};". Clients can distinguish between different forms of
1321 /// initialization by checking this value. In particular, "int x = {1};" is
1322 /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the
1323 /// Init expression in all three cases is an InitListExpr.
1324 InitializationStyle getInitStyle() const {
1325 return static_cast<InitializationStyle>(VarDeclBits.InitStyle);
1326 }
1327
1328 /// Whether the initializer is a direct-initializer (list or call).
1329 bool isDirectInit() const {
1330 return getInitStyle() != CInit;
1331 }
1332
1333 /// If this definition should pretend to be a declaration.
1334 bool isThisDeclarationADemotedDefinition() const {
1335 return isa<ParmVarDecl>(this) ? false :
1336 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition;
1337 }
1338
1339 /// This is a definition which should be demoted to a declaration.
1340 ///
1341 /// In some cases (mostly module merging) we can end up with two visible
1342 /// definitions one of which needs to be demoted to a declaration to keep
1343 /// the AST invariants.
1344 void demoteThisDefinitionToDeclaration() {
1345 assert(isThisDeclarationADefinition() && "Not a definition!")((isThisDeclarationADefinition() && "Not a definition!"
) ? static_cast<void> (0) : __assert_fail ("isThisDeclarationADefinition() && \"Not a definition!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/Decl.h"
, 1345, __PRETTY_FUNCTION__))
;
1346 assert(!isa<ParmVarDecl>(this) && "Cannot demote ParmVarDecls!")((!isa<ParmVarDecl>(this) && "Cannot demote ParmVarDecls!"
) ? static_cast<void> (0) : __assert_fail ("!isa<ParmVarDecl>(this) && \"Cannot demote ParmVarDecls!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/Decl.h"
, 1346, __PRETTY_FUNCTION__))
;
1347 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition = 1;
1348 }
1349
1350 /// Determine whether this variable is the exception variable in a
1351 /// C++ catch statememt or an Objective-C \@catch statement.
1352 bool isExceptionVariable() const {
1353 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ExceptionVar;
1354 }
1355 void setExceptionVariable(bool EV) {
1356 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/Decl.h"
, 1356, __PRETTY_FUNCTION__))
;
1357 NonParmVarDeclBits.ExceptionVar = EV;
1358 }
1359
1360 /// Determine whether this local variable can be used with the named
1361 /// return value optimization (NRVO).
1362 ///
1363 /// The named return value optimization (NRVO) works by marking certain
1364 /// non-volatile local variables of class type as NRVO objects. These
1365 /// locals can be allocated within the return slot of their containing
1366 /// function, in which case there is no need to copy the object to the
1367 /// return slot when returning from the function. Within the function body,
1368 /// each return that returns the NRVO object will have this variable as its
1369 /// NRVO candidate.
1370 bool isNRVOVariable() const {
1371 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.NRVOVariable;
1372 }
1373 void setNRVOVariable(bool NRVO) {
1374 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/Decl.h"
, 1374, __PRETTY_FUNCTION__))
;
1375 NonParmVarDeclBits.NRVOVariable = NRVO;
1376 }
1377
1378 /// Determine whether this variable is the for-range-declaration in
1379 /// a C++0x for-range statement.
1380 bool isCXXForRangeDecl() const {
1381 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.CXXForRangeDecl;
1382 }
1383 void setCXXForRangeDecl(bool FRD) {
1384 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/Decl.h"
, 1384, __PRETTY_FUNCTION__))
;
1385 NonParmVarDeclBits.CXXForRangeDecl = FRD;
1386 }
1387
1388 /// Determine whether this variable is a for-loop declaration for a
1389 /// for-in statement in Objective-C.
1390 bool isObjCForDecl() const {
1391 return NonParmVarDeclBits.ObjCForDecl;
1392 }
1393
1394 void setObjCForDecl(bool FRD) {
1395 NonParmVarDeclBits.ObjCForDecl = FRD;
1396 }
1397
1398 /// Determine whether this variable is an ARC pseudo-__strong variable. A
1399 /// pseudo-__strong variable has a __strong-qualified type but does not
1400 /// actually retain the object written into it. Generally such variables are
1401 /// also 'const' for safety. There are 3 cases where this will be set, 1) if
1402 /// the variable is annotated with the objc_externally_retained attribute, 2)
1403 /// if its 'self' in a non-init method, or 3) if its the variable in an for-in
1404 /// loop.
1405 bool isARCPseudoStrong() const { return VarDeclBits.ARCPseudoStrong; }
1406 void setARCPseudoStrong(bool PS) { VarDeclBits.ARCPseudoStrong = PS; }
1407
1408 /// Whether this variable is (C++1z) inline.
1409 bool isInline() const {
1410 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInline;
1411 }
1412 bool isInlineSpecified() const {
1413 return isa<ParmVarDecl>(this) ? false
1414 : NonParmVarDeclBits.IsInlineSpecified;
1415 }
1416 void setInlineSpecified() {
1417 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/Decl.h"
, 1417, __PRETTY_FUNCTION__))
;
1418 NonParmVarDeclBits.IsInline = true;
1419 NonParmVarDeclBits.IsInlineSpecified = true;
1420 }
1421 void setImplicitlyInline() {
1422 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/Decl.h"
, 1422, __PRETTY_FUNCTION__))
;
1423 NonParmVarDeclBits.IsInline = true;
1424 }
1425
1426 /// Whether this variable is (C++11) constexpr.
1427 bool isConstexpr() const {
1428 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsConstexpr;
1429 }
1430 void setConstexpr(bool IC) {
1431 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/Decl.h"
, 1431, __PRETTY_FUNCTION__))
;
1432 NonParmVarDeclBits.IsConstexpr = IC;
1433 }
1434
1435 /// Whether this variable is the implicit variable for a lambda init-capture.
1436 bool isInitCapture() const {
1437 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInitCapture;
1438 }
1439 void setInitCapture(bool IC) {
1440 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/Decl.h"
, 1440, __PRETTY_FUNCTION__))
;
1441 NonParmVarDeclBits.IsInitCapture = IC;
1442 }
1443
1444 /// Determine whether this variable is actually a function parameter pack or
1445 /// init-capture pack.
1446 bool isParameterPack() const;
1447
1448 /// Whether this local extern variable declaration's previous declaration
1449 /// was declared in the same block scope. Only correct in C++.
1450 bool isPreviousDeclInSameBlockScope() const {
1451 return isa<ParmVarDecl>(this)
1452 ? false
1453 : NonParmVarDeclBits.PreviousDeclInSameBlockScope;
1454 }
1455 void setPreviousDeclInSameBlockScope(bool Same) {
1456 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/Decl.h"
, 1456, __PRETTY_FUNCTION__))
;
1457 NonParmVarDeclBits.PreviousDeclInSameBlockScope = Same;
1458 }
1459
1460 /// Indicates the capture is a __block variable that is captured by a block
1461 /// that can potentially escape (a block for which BlockDecl::doesNotEscape
1462 /// returns false).
1463 bool isEscapingByref() const;
1464
1465 /// Indicates the capture is a __block variable that is never captured by an
1466 /// escaping block.
1467 bool isNonEscapingByref() const;
1468
1469 void setEscapingByref() {
1470 NonParmVarDeclBits.EscapingByref = true;
1471 }
1472
1473 /// Retrieve the variable declaration from which this variable could
1474 /// be instantiated, if it is an instantiation (rather than a non-template).
1475 VarDecl *getTemplateInstantiationPattern() const;
1476
1477 /// If this variable is an instantiated static data member of a
1478 /// class template specialization, returns the templated static data member
1479 /// from which it was instantiated.
1480 VarDecl *getInstantiatedFromStaticDataMember() const;
1481
1482 /// If this variable is an instantiation of a variable template or a
1483 /// static data member of a class template, determine what kind of
1484 /// template specialization or instantiation this is.
1485 TemplateSpecializationKind getTemplateSpecializationKind() const;
1486
1487 /// Get the template specialization kind of this variable for the purposes of
1488 /// template instantiation. This differs from getTemplateSpecializationKind()
1489 /// for an instantiation of a class-scope explicit specialization.
1490 TemplateSpecializationKind
1491 getTemplateSpecializationKindForInstantiation() const;
1492
1493 /// If this variable is an instantiation of a variable template or a
1494 /// static data member of a class template, determine its point of
1495 /// instantiation.
1496 SourceLocation getPointOfInstantiation() const;
1497
1498 /// If this variable is an instantiation of a static data member of a
1499 /// class template specialization, retrieves the member specialization
1500 /// information.
1501 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1502
1503 /// For a static data member that was instantiated from a static
1504 /// data member of a class template, set the template specialiation kind.
1505 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1506 SourceLocation PointOfInstantiation = SourceLocation());
1507
1508 /// Specify that this variable is an instantiation of the
1509 /// static data member VD.
1510 void setInstantiationOfStaticDataMember(VarDecl *VD,
1511 TemplateSpecializationKind TSK);
1512
1513 /// Retrieves the variable template that is described by this
1514 /// variable declaration.
1515 ///
1516 /// Every variable template is represented as a VarTemplateDecl and a
1517 /// VarDecl. The former contains template properties (such as
1518 /// the template parameter lists) while the latter contains the
1519 /// actual description of the template's
1520 /// contents. VarTemplateDecl::getTemplatedDecl() retrieves the
1521 /// VarDecl that from a VarTemplateDecl, while
1522 /// getDescribedVarTemplate() retrieves the VarTemplateDecl from
1523 /// a VarDecl.
1524 VarTemplateDecl *getDescribedVarTemplate() const;
1525
1526 void setDescribedVarTemplate(VarTemplateDecl *Template);
1527
1528 // Is this variable known to have a definition somewhere in the complete
1529 // program? This may be true even if the declaration has internal linkage and
1530 // has no definition within this source file.
1531 bool isKnownToBeDefined() const;
1532
1533 /// Is destruction of this variable entirely suppressed? If so, the variable
1534 /// need not have a usable destructor at all.
1535 bool isNoDestroy(const ASTContext &) const;
1536
1537 /// Would the destruction of this variable have any effect, and if so, what
1538 /// kind?
1539 QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const;
1540
1541 // Implement isa/cast/dyncast/etc.
1542 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1543 static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; }
1544};
1545
1546class ImplicitParamDecl : public VarDecl {
1547 void anchor() override;
1548
1549public:
1550 /// Defines the kind of the implicit parameter: is this an implicit parameter
1551 /// with pointer to 'this', 'self', '_cmd', virtual table pointers, captured
1552 /// context or something else.
1553 enum ImplicitParamKind : unsigned {
1554 /// Parameter for Objective-C 'self' argument
1555 ObjCSelf,
1556
1557 /// Parameter for Objective-C '_cmd' argument
1558 ObjCCmd,
1559
1560 /// Parameter for C++ 'this' argument
1561 CXXThis,
1562
1563 /// Parameter for C++ virtual table pointers
1564 CXXVTT,
1565
1566 /// Parameter for captured context
1567 CapturedContext,
1568
1569