Bug Summary

File:clang/lib/StaticAnalyzer/Core/MemRegion.cpp
Warning:line 951, 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 -clear-ast-before-backend -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 -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/StaticAnalyzer/Core -I /build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/clang/lib/StaticAnalyzer/Core -I /build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-01-16-232930-107970-1 -x c++ /build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/clang/lib/StaticAnalyzer/Core/MemRegion.cpp

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

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

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