1//===- DeclBase.cpp - Declaration AST Node Implementation -----------------===//
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 implements the Decl and DeclContext classes.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/DeclBase.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/ASTLambda.h"
16#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/Attr.h"
18#include "clang/AST/AttrIterator.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclContextInternals.h"
22#include "clang/AST/DeclFriend.h"
23#include "clang/AST/DeclObjC.h"
24#include "clang/AST/DeclOpenACC.h"
25#include "clang/AST/DeclOpenMP.h"
26#include "clang/AST/DeclTemplate.h"
27#include "clang/AST/DependentDiagnostic.h"
28#include "clang/AST/ExternalASTSource.h"
29#include "clang/AST/Stmt.h"
30#include "clang/AST/Type.h"
31#include "clang/Basic/IdentifierTable.h"
32#include "clang/Basic/LLVM.h"
33#include "clang/Basic/Module.h"
34#include "clang/Basic/ObjCRuntime.h"
35#include "clang/Basic/PartialDiagnostic.h"
36#include "clang/Basic/SourceLocation.h"
37#include "clang/Basic/TargetInfo.h"
38#include "llvm/ADT/PointerIntPair.h"
39#include "llvm/ADT/StringRef.h"
40#include "llvm/Support/ErrorHandling.h"
41#include "llvm/Support/MathExtras.h"
42#include "llvm/Support/VersionTuple.h"
43#include "llvm/Support/raw_ostream.h"
44#include <algorithm>
45#include <cassert>
46#include <cstddef>
47#include <string>
48#include <tuple>
49#include <utility>
50
51using namespace clang;
52
53//===----------------------------------------------------------------------===//
54// Statistics
55//===----------------------------------------------------------------------===//
56
57#define DECL(DERIVED, BASE) static int n##DERIVED##s = 0;
58#define ABSTRACT_DECL(DECL)
59#include "clang/AST/DeclNodes.inc"
60
61#define DECL(DERIVED, BASE) \
62 static_assert(alignof(Decl) >= alignof(DERIVED##Decl), \
63 "Alignment sufficient after objects prepended to " #DERIVED);
64#define ABSTRACT_DECL(DECL)
65#include "clang/AST/DeclNodes.inc"
66
67void *Decl::operator new(std::size_t Size, const ASTContext &Context,
68 GlobalDeclID ID, std::size_t Extra) {
69 // Allocate an extra 8 bytes worth of storage, which ensures that the
70 // resulting pointer will still be 8-byte aligned.
71 static_assert(sizeof(uint64_t) >= alignof(Decl), "Decl won't be misaligned");
72 void *Start = Context.Allocate(Size: Size + Extra + 8);
73 void *Result = (char*)Start + 8;
74
75 uint64_t *PrefixPtr = (uint64_t *)Result - 1;
76
77 *PrefixPtr = ID.getRawValue();
78
79 // We leave the upper 16 bits to store the module IDs. 48 bits should be
80 // sufficient to store a declaration ID. See the comments in setOwningModuleID
81 // for details.
82 assert((*PrefixPtr < llvm::maskTrailingOnes<uint64_t>(48)) &&
83 "Current Implementation limits the number of module files to not "
84 "exceed 2^16. Contact Clang Developers to remove the limitation.");
85
86 return Result;
87}
88
89void *Decl::operator new(std::size_t Size, const ASTContext &Ctx,
90 DeclContext *Parent, std::size_t Extra) {
91 assert(!Parent || &Parent->getParentASTContext() == &Ctx);
92 // With local visibility enabled, we track the owning module even for local
93 // declarations. We create the TU decl early and may not yet know what the
94 // LangOpts are, so conservatively allocate the storage.
95 if (Ctx.getLangOpts().trackLocalOwningModule() || !Parent) {
96 // Ensure required alignment of the resulting object by adding extra
97 // padding at the start if required.
98 size_t ExtraAlign =
99 llvm::offsetToAlignment(Value: sizeof(Module *), Alignment: llvm::Align(alignof(Decl)));
100 auto *Buffer = reinterpret_cast<char *>(
101 ::operator new(Bytes: ExtraAlign + sizeof(Module *) + Size + Extra, C: Ctx));
102 Buffer += ExtraAlign;
103 auto *ParentModule =
104 Parent ? cast<Decl>(Val: Parent)->getOwningModule() : nullptr;
105 return new (Buffer) Module*(ParentModule) + 1;
106 }
107 return ::operator new(Bytes: Size + Extra, C: Ctx);
108}
109
110GlobalDeclID Decl::getGlobalID() const {
111 if (!isFromASTFile())
112 return GlobalDeclID();
113 // See the comments in `Decl::operator new` for details.
114 uint64_t ID = *((const uint64_t *)this - 1);
115 return GlobalDeclID(ID & llvm::maskTrailingOnes<uint64_t>(N: 48));
116}
117
118unsigned Decl::getOwningModuleID() const {
119 if (!isFromASTFile())
120 return 0;
121
122 uint64_t ID = *((const uint64_t *)this - 1);
123 return ID >> 48;
124}
125
126void Decl::setOwningModuleID(unsigned ID) {
127 assert(isFromASTFile() && "Only works on a deserialized declaration");
128 // Currently, we use 64 bits to store the GlobalDeclID and the module ID
129 // to save the space. See `Decl::operator new` for details. To make it,
130 // we split the higher 32 bits to 2 16bits for the module file index of
131 // GlobalDeclID and the module ID. This introduces a limitation that the
132 // number of modules can't exceed 2^16. (The number of module files should be
133 // less than the number of modules).
134 //
135 // It is counter-intuitive to store both the module file index and the
136 // module ID as it seems redundant. However, this is not true.
137 // The module ID may be different from the module file where it is serialized
138 // from for implicit template instantiations. See
139 // https://github.com/llvm/llvm-project/issues/101939
140 //
141 // If we reach the limitation, we have to remove the limitation by asking
142 // every deserialized declaration to pay for yet another 32 bits, or we have
143 // to review the above issue to decide what we should do for it.
144 assert((ID < llvm::maskTrailingOnes<unsigned>(16)) &&
145 "Current Implementation limits the number of modules to not exceed "
146 "2^16. Contact Clang Developers to remove the limitation.");
147 uint64_t *IDAddress = (uint64_t *)this - 1;
148 *IDAddress &= llvm::maskTrailingOnes<uint64_t>(N: 48);
149 *IDAddress |= (uint64_t)ID << 48;
150}
151
152Module *Decl::getTopLevelOwningNamedModule() const {
153 if (getOwningModule() &&
154 getOwningModule()->getTopLevelModule()->isNamedModule())
155 return getOwningModule()->getTopLevelModule();
156
157 return nullptr;
158}
159
160Module *Decl::getOwningModuleSlow() const {
161 assert(isFromASTFile() && "Not from AST file?");
162 return getASTContext().getExternalSource()->getModule(ID: getOwningModuleID());
163}
164
165bool Decl::hasLocalOwningModuleStorage() const {
166 return getASTContext().getLangOpts().trackLocalOwningModule();
167}
168
169const char *Decl::getDeclKindName() const {
170 switch (DeclKind) {
171 default: llvm_unreachable("Declaration not in DeclNodes.inc!");
172#define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
173#define ABSTRACT_DECL(DECL)
174#include "clang/AST/DeclNodes.inc"
175 }
176}
177
178void Decl::setInvalidDecl(bool Invalid) {
179 InvalidDecl = Invalid;
180 assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition());
181 if (!Invalid) {
182 return;
183 }
184
185 if (!isa<ParmVarDecl>(Val: this)) {
186 // Defensive maneuver for ill-formed code: we're likely not to make it to
187 // a point where we set the access specifier, so default it to "public"
188 // to avoid triggering asserts elsewhere in the front end.
189 setAccess(AS_public);
190 }
191
192 // Marking a DecompositionDecl as invalid implies all the child BindingDecl's
193 // are invalid too.
194 if (auto *DD = dyn_cast<DecompositionDecl>(Val: this)) {
195 for (auto *Binding : DD->bindings()) {
196 Binding->setInvalidDecl();
197 }
198 }
199}
200
201bool DeclContext::hasValidDeclKind() const {
202 switch (getDeclKind()) {
203#define DECL(DERIVED, BASE) case Decl::DERIVED: return true;
204#define ABSTRACT_DECL(DECL)
205#include "clang/AST/DeclNodes.inc"
206 }
207 return false;
208}
209
210const char *DeclContext::getDeclKindName() const {
211 switch (getDeclKind()) {
212#define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
213#define ABSTRACT_DECL(DECL)
214#include "clang/AST/DeclNodes.inc"
215 }
216 llvm_unreachable("Declaration context not in DeclNodes.inc!");
217}
218
219bool Decl::StatisticsEnabled = false;
220void Decl::EnableStatistics() {
221 StatisticsEnabled = true;
222}
223
224void Decl::PrintStats() {
225 llvm::errs() << "\n*** Decl Stats:\n";
226
227 int totalDecls = 0;
228#define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
229#define ABSTRACT_DECL(DECL)
230#include "clang/AST/DeclNodes.inc"
231 llvm::errs() << " " << totalDecls << " decls total.\n";
232
233 int totalBytes = 0;
234#define DECL(DERIVED, BASE) \
235 if (n##DERIVED##s > 0) { \
236 totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \
237 llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \
238 << sizeof(DERIVED##Decl) << " each (" \
239 << n##DERIVED##s * sizeof(DERIVED##Decl) \
240 << " bytes)\n"; \
241 }
242#define ABSTRACT_DECL(DECL)
243#include "clang/AST/DeclNodes.inc"
244
245 llvm::errs() << "Total bytes = " << totalBytes << "\n";
246}
247
248void Decl::add(Kind k) {
249 switch (k) {
250#define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
251#define ABSTRACT_DECL(DECL)
252#include "clang/AST/DeclNodes.inc"
253 }
254}
255
256bool Decl::isTemplateParameterPack() const {
257 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Val: this))
258 return TTP->isParameterPack();
259 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: this))
260 return NTTP->isParameterPack();
261 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Val: this))
262 return TTP->isParameterPack();
263 return false;
264}
265
266bool Decl::isParameterPack() const {
267 if (const auto *Var = dyn_cast<ValueDecl>(Val: this))
268 return Var->isParameterPack();
269
270 return isTemplateParameterPack();
271}
272
273FunctionDecl *Decl::getAsFunction() {
274 if (auto *FD = dyn_cast<FunctionDecl>(Val: this))
275 return FD;
276 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: this))
277 return FTD->getTemplatedDecl();
278 return nullptr;
279}
280
281bool Decl::isTemplateDecl() const {
282 return isa<TemplateDecl>(Val: this);
283}
284
285TemplateDecl *Decl::getDescribedTemplate() const {
286 if (auto *FD = dyn_cast<FunctionDecl>(Val: this))
287 return FD->getDescribedFunctionTemplate();
288 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: this))
289 return RD->getDescribedClassTemplate();
290 if (auto *VD = dyn_cast<VarDecl>(Val: this))
291 return VD->getDescribedVarTemplate();
292 if (auto *AD = dyn_cast<TypeAliasDecl>(Val: this))
293 return AD->getDescribedAliasTemplate();
294
295 return nullptr;
296}
297
298const TemplateParameterList *Decl::getDescribedTemplateParams() const {
299 if (auto *TD = getDescribedTemplate())
300 return TD->getTemplateParameters();
301 if (auto *CTPSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: this))
302 return CTPSD->getTemplateParameters();
303 if (auto *VTPSD = dyn_cast<VarTemplatePartialSpecializationDecl>(Val: this))
304 return VTPSD->getTemplateParameters();
305 return nullptr;
306}
307
308bool Decl::isTemplated() const {
309 // A declaration is templated if it is a template or a template pattern, or
310 // is within (lexcially for a friend or local function declaration,
311 // semantically otherwise) a dependent context.
312 if (auto *AsDC = dyn_cast<DeclContext>(Val: this))
313 return AsDC->isDependentContext();
314 auto *DC = getFriendObjectKind() || isLocalExternDecl()
315 ? getLexicalDeclContext() : getDeclContext();
316 return DC->isDependentContext() || isTemplateDecl() ||
317 getDescribedTemplateParams();
318}
319
320unsigned Decl::getTemplateDepth() const {
321 if (auto *DC = dyn_cast<DeclContext>(Val: this))
322 if (DC->isFileContext())
323 return 0;
324
325 if (auto *TPL = getDescribedTemplateParams())
326 return TPL->getDepth() + 1;
327
328 if (auto *ESD = dyn_cast<CXXExpansionStmtDecl>(Val: this))
329 return ESD->getIndexTemplateParm()->getDepth() + 1;
330
331 // If this is a dependent lambda, there might be an enclosing variable
332 // template. In this case, the next step is not the parent DeclContext (or
333 // even a DeclContext at all).
334 auto *RD = dyn_cast<CXXRecordDecl>(Val: this);
335 if (RD && RD->isDependentLambda())
336 if (Decl *Context = RD->getLambdaContextDecl())
337 return Context->getTemplateDepth();
338
339 const DeclContext *DC =
340 getFriendObjectKind() ? getLexicalDeclContext() : getDeclContext();
341 return cast<Decl>(Val: DC)->getTemplateDepth();
342}
343
344const DeclContext *Decl::getParentFunctionOrMethod(bool LexicalParent) const {
345 for (const DeclContext *DC = LexicalParent ? getLexicalDeclContext()
346 : getDeclContext();
347 DC && !DC->isFileContext(); DC = DC->getParent())
348 if (DC->isFunctionOrMethod())
349 return DC;
350
351 return nullptr;
352}
353
354//===----------------------------------------------------------------------===//
355// PrettyStackTraceDecl Implementation
356//===----------------------------------------------------------------------===//
357
358void PrettyStackTraceDecl::print(raw_ostream &OS) const {
359 SourceLocation TheLoc = Loc;
360 if (TheLoc.isInvalid() && TheDecl)
361 TheLoc = TheDecl->getLocation();
362
363 if (TheLoc.isValid()) {
364 TheLoc.print(OS, SM);
365 OS << ": ";
366 }
367
368 OS << Message;
369
370 if (const auto *DN = dyn_cast_or_null<NamedDecl>(Val: TheDecl)) {
371 OS << " '";
372 DN->printQualifiedName(OS);
373 OS << '\'';
374 }
375 OS << '\n';
376}
377
378//===----------------------------------------------------------------------===//
379// Decl Implementation
380//===----------------------------------------------------------------------===//
381
382// Out-of-line virtual method providing a home for Decl.
383Decl::~Decl() = default;
384
385void Decl::setDeclContext(DeclContext *DC) {
386 DeclCtx = DC;
387}
388
389void Decl::setLexicalDeclContext(DeclContext *DC) {
390 if (DC == getLexicalDeclContext())
391 return;
392
393 if (isInSemaDC()) {
394 setDeclContextsImpl(SemaDC: getDeclContext(), LexicalDC: DC, Ctx&: getASTContext());
395 } else {
396 getMultipleDC()->LexicalDC = DC;
397 }
398
399 // FIXME: We shouldn't be changing the lexical context of declarations
400 // imported from AST files.
401 if (!isFromASTFile()) {
402 setModuleOwnershipKind(getModuleOwnershipKindForChildOf(DC));
403 if (hasOwningModule())
404 setLocalOwningModule(cast<Decl>(Val: DC)->getOwningModule());
405 }
406
407 assert(
408 ((getModuleOwnershipKind() != ModuleOwnershipKind::VisibleWhenImported &&
409 getModuleOwnershipKind() != ModuleOwnershipKind::VisiblePromoted) ||
410 getOwningModule()) &&
411 "hidden declaration has no owning module");
412}
413
414void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
415 ASTContext &Ctx) {
416 if (SemaDC == LexicalDC) {
417 DeclCtx = SemaDC;
418 } else {
419 auto *MDC = new (Ctx) Decl::MultipleDC();
420 MDC->SemanticDC = SemaDC;
421 MDC->LexicalDC = LexicalDC;
422 DeclCtx = MDC;
423 }
424}
425
426bool Decl::isInLocalScopeForInstantiation() const {
427 const DeclContext *LDC = getLexicalDeclContext();
428 if (!LDC->isDependentContext())
429 return false;
430 while (true) {
431 if (LDC->isFunctionOrMethod())
432 return true;
433 if (!isa<TagDecl>(Val: LDC))
434 return false;
435 if (const auto *CRD = dyn_cast<CXXRecordDecl>(Val: LDC))
436 if (CRD->isLambda())
437 return true;
438 LDC = LDC->getLexicalParent();
439 }
440 return false;
441}
442
443bool Decl::isInAnonymousNamespace() const {
444 for (const DeclContext *DC = getDeclContext(); DC; DC = DC->getParent()) {
445 if (const auto *ND = dyn_cast<NamespaceDecl>(Val: DC))
446 if (ND->isAnonymousNamespace())
447 return true;
448 }
449
450 return false;
451}
452
453bool Decl::isInStdNamespace() const {
454 const DeclContext *DC = getDeclContext();
455 return DC && DC->getNonTransparentContext()->isStdNamespace();
456}
457
458bool Decl::isFileContextDecl() const {
459 const auto *DC = dyn_cast<DeclContext>(Val: this);
460 return DC && DC->isFileContext();
461}
462
463bool Decl::isFlexibleArrayMemberLike(
464 const ASTContext &Ctx, const Decl *D, QualType Ty,
465 LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel,
466 bool IgnoreTemplateOrMacroSubstitution) {
467 // For compatibility with existing code, we treat arrays of length 0 or
468 // 1 as flexible array members.
469 const auto *CAT = Ctx.getAsConstantArrayType(T: Ty);
470 if (CAT) {
471 using FAMKind = LangOptions::StrictFlexArraysLevelKind;
472
473 llvm::APInt Size = CAT->getSize();
474 if (StrictFlexArraysLevel == FAMKind::IncompleteOnly)
475 return false;
476
477 // GCC extension, only allowed to represent a FAM.
478 if (Size.isZero())
479 return true;
480
481 if (StrictFlexArraysLevel == FAMKind::ZeroOrIncomplete && Size.uge(RHS: 1))
482 return false;
483
484 if (StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete && Size.uge(RHS: 2))
485 return false;
486 } else if (!Ctx.getAsIncompleteArrayType(T: Ty)) {
487 return false;
488 }
489
490 if (const auto *OID = dyn_cast_if_present<ObjCIvarDecl>(Val: D))
491 return OID->getNextIvar() == nullptr;
492
493 const auto *FD = dyn_cast_if_present<FieldDecl>(Val: D);
494 if (!FD)
495 return false;
496
497 if (CAT) {
498 // GCC treats an array memeber of a union as an FAM if the size is one or
499 // zero.
500 llvm::APInt Size = CAT->getSize();
501 if (FD->getParent()->isUnion() && (Size.isZero() || Size.isOne()))
502 return true;
503 }
504
505 // Don't consider sizes resulting from macro expansions or template argument
506 // substitution to form C89 tail-padded arrays.
507 if (IgnoreTemplateOrMacroSubstitution) {
508 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
509 while (TInfo) {
510 TypeLoc TL = TInfo->getTypeLoc();
511
512 // Look through typedefs.
513 if (TypedefTypeLoc TTL = TL.getAsAdjusted<TypedefTypeLoc>()) {
514 TInfo = TTL.getDecl()->getTypeSourceInfo();
515 continue;
516 }
517
518 if (auto CTL = TL.getAs<ConstantArrayTypeLoc>()) {
519 if (const Expr *SizeExpr =
520 dyn_cast_if_present<IntegerLiteral>(Val: CTL.getSizeExpr());
521 !SizeExpr || SizeExpr->getExprLoc().isMacroID())
522 return false;
523 }
524
525 break;
526 }
527 }
528
529 // Test that the field is the last in the structure.
530 RecordDecl::field_iterator FI(
531 DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
532 return ++FI == FD->getParent()->field_end();
533}
534
535TranslationUnitDecl *Decl::getTranslationUnitDecl() {
536 if (auto *TUD = dyn_cast<TranslationUnitDecl>(Val: this))
537 return TUD;
538
539 DeclContext *DC = getDeclContext();
540 assert(DC && "This decl is not contained in a translation unit!");
541
542 while (!DC->isTranslationUnit()) {
543 DC = DC->getParent();
544 assert(DC && "This decl is not contained in a translation unit!");
545 }
546
547 return cast<TranslationUnitDecl>(Val: DC);
548}
549
550ASTContext &Decl::getASTContext() const {
551 return getTranslationUnitDecl()->getASTContext();
552}
553
554/// Helper to get the language options from the ASTContext.
555/// Defined out of line to avoid depending on ASTContext.h.
556const LangOptions &Decl::getLangOpts() const {
557 return getASTContext().getLangOpts();
558}
559
560ASTMutationListener *Decl::getASTMutationListener() const {
561 return getASTContext().getASTMutationListener();
562}
563
564unsigned Decl::getMaxAlignment() const {
565 if (!hasAttrs())
566 return 0;
567
568 unsigned Align = 0;
569 const AttrVec &V = getAttrs();
570 ASTContext &Ctx = getASTContext();
571 specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
572 for (; I != E; ++I) {
573 if (!I->isAlignmentErrorDependent())
574 Align = std::max(a: Align, b: I->getAlignment(Ctx));
575 }
576 return Align;
577}
578
579bool Decl::isUsed(bool CheckUsedAttr) const {
580 const Decl *CanonD = getCanonicalDecl();
581 if (CanonD->Used)
582 return true;
583
584 // Check for used attribute.
585 // Ask the most recent decl, since attributes accumulate in the redecl chain.
586 if (CheckUsedAttr && getMostRecentDecl()->hasAttr<UsedAttr>())
587 return true;
588
589 // The information may have not been deserialized yet. Force deserialization
590 // to complete the needed information.
591 return getMostRecentDecl()->getCanonicalDecl()->Used;
592}
593
594void Decl::markUsed(ASTContext &C) {
595 if (isUsed(CheckUsedAttr: false))
596 return;
597
598 if (C.getASTMutationListener())
599 C.getASTMutationListener()->DeclarationMarkedUsed(D: this);
600
601 setIsUsed();
602}
603
604bool Decl::isReferenced() const {
605 if (Referenced)
606 return true;
607
608 // Check redeclarations.
609 for (const auto *I : redecls())
610 if (I->Referenced)
611 return true;
612
613 return false;
614}
615
616ExternalSourceSymbolAttr *Decl::getExternalSourceSymbolAttr() const {
617 const Decl *Definition = nullptr;
618 if (auto *ID = dyn_cast<ObjCInterfaceDecl>(Val: this)) {
619 Definition = ID->getDefinition();
620 } else if (auto *PD = dyn_cast<ObjCProtocolDecl>(Val: this)) {
621 Definition = PD->getDefinition();
622 } else if (auto *TD = dyn_cast<TagDecl>(Val: this)) {
623 Definition = TD->getDefinition();
624 }
625 if (!Definition)
626 Definition = this;
627
628 if (auto *attr = Definition->getAttr<ExternalSourceSymbolAttr>())
629 return attr;
630 if (auto *dcd = dyn_cast<Decl>(Val: getDeclContext())) {
631 return dcd->getAttr<ExternalSourceSymbolAttr>();
632 }
633
634 return nullptr;
635}
636
637bool Decl::hasDefiningAttr() const {
638 return hasAttr<AliasAttr>() || hasAttr<IFuncAttr>() ||
639 hasAttr<LoaderUninitializedAttr>();
640}
641
642const Attr *Decl::getDefiningAttr() const {
643 if (auto *AA = getAttr<AliasAttr>())
644 return AA;
645 if (auto *IFA = getAttr<IFuncAttr>())
646 return IFA;
647 if (auto *NZA = getAttr<LoaderUninitializedAttr>())
648 return NZA;
649 return nullptr;
650}
651
652static StringRef getRealizedPlatform(const AvailabilityAttr *A,
653 const ASTContext &Context) {
654 // Check if this is an App Extension "platform", and if so chop off
655 // the suffix for matching with the actual platform.
656 StringRef RealizedPlatform = A->getPlatform()->getName();
657 if (!Context.getLangOpts().AppExt)
658 return RealizedPlatform;
659 size_t suffix = RealizedPlatform.rfind(Str: "_app_extension");
660 if (suffix != StringRef::npos)
661 return RealizedPlatform.slice(Start: 0, End: suffix);
662 return RealizedPlatform;
663}
664
665/// Determine the availability of the given declaration based on
666/// the target platform.
667///
668/// When it returns an availability result other than \c AR_Available,
669/// if the \p Message parameter is non-NULL, it will be set to a
670/// string describing why the entity is unavailable.
671///
672/// FIXME: Make these strings localizable, since they end up in
673/// diagnostics.
674static AvailabilityResult CheckAvailability(ASTContext &Context,
675 const AvailabilityAttr *A,
676 std::string *Message,
677 VersionTuple EnclosingVersion) {
678 if (EnclosingVersion.empty())
679 EnclosingVersion = Context.getTargetInfo().getPlatformMinVersion();
680
681 if (EnclosingVersion.empty())
682 return AR_Available;
683
684 StringRef ActualPlatform = A->getPlatform()->getName();
685 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
686
687 // Match the platform name.
688 if (getRealizedPlatform(A, Context) != TargetPlatform)
689 return AR_Available;
690
691 StringRef PrettyPlatformName
692 = AvailabilityAttr::getPrettyPlatformName(Platform: ActualPlatform);
693
694 if (PrettyPlatformName.empty())
695 PrettyPlatformName = ActualPlatform;
696
697 std::string HintMessage;
698 if (!A->getMessage().empty()) {
699 HintMessage = " - ";
700 HintMessage += A->getMessage();
701 }
702
703 // Make sure that this declaration has not been marked 'unavailable'.
704 if (A->getUnavailable()) {
705 if (Message) {
706 Message->clear();
707 llvm::raw_string_ostream Out(*Message);
708 Out << "not available on " << PrettyPlatformName
709 << HintMessage;
710 }
711
712 return AR_Unavailable;
713 }
714
715 // Make sure that this declaration has already been introduced.
716 if (!A->getIntroduced().empty() &&
717 EnclosingVersion < A->getIntroduced()) {
718 const IdentifierInfo *IIEnv = A->getEnvironment();
719 auto &Triple = Context.getTargetInfo().getTriple();
720 StringRef TargetEnv = Triple.getEnvironmentName();
721 StringRef EnvName =
722 llvm::Triple::getEnvironmentTypeName(Kind: Triple.getEnvironment());
723 // Matching environment or no environment on attribute.
724 if (!IIEnv || (Triple.hasEnvironment() && IIEnv->getName() == TargetEnv)) {
725 if (Message) {
726 Message->clear();
727 llvm::raw_string_ostream Out(*Message);
728 VersionTuple VTI(A->getIntroduced());
729 Out << "introduced in " << PrettyPlatformName << " " << VTI;
730 if (Triple.hasEnvironment())
731 Out << " " << EnvName;
732 Out << HintMessage;
733 }
734 }
735 // Non-matching environment or no environment on target.
736 else {
737 if (Message) {
738 Message->clear();
739 llvm::raw_string_ostream Out(*Message);
740 Out << "not available on " << PrettyPlatformName;
741 if (Triple.hasEnvironment())
742 Out << " " << EnvName;
743 Out << HintMessage;
744 }
745 }
746
747 return A->getStrict() ? AR_Unavailable : AR_NotYetIntroduced;
748 }
749
750 // Make sure that this declaration hasn't been obsoleted.
751 if (!A->getObsoleted().empty() && EnclosingVersion >= A->getObsoleted()) {
752 if (Message) {
753 Message->clear();
754 llvm::raw_string_ostream Out(*Message);
755 VersionTuple VTO(A->getObsoleted());
756 Out << "obsoleted in " << PrettyPlatformName << ' '
757 << VTO << HintMessage;
758 }
759
760 return AR_Unavailable;
761 }
762
763 // Make sure that this declaration hasn't been deprecated.
764 if (!A->getDeprecated().empty() && EnclosingVersion >= A->getDeprecated()) {
765 if (Message) {
766 Message->clear();
767 llvm::raw_string_ostream Out(*Message);
768 VersionTuple VTD(A->getDeprecated());
769 Out << "first deprecated in " << PrettyPlatformName << ' '
770 << VTD << HintMessage;
771 }
772
773 return AR_Deprecated;
774 }
775
776 return AR_Available;
777}
778
779AvailabilityResult Decl::getAvailability(std::string *Message,
780 VersionTuple EnclosingVersion,
781 StringRef *RealizedPlatform) const {
782 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: this))
783 return FTD->getTemplatedDecl()->getAvailability(Message, EnclosingVersion,
784 RealizedPlatform);
785
786 AvailabilityResult Result = AR_Available;
787 std::string ResultMessage;
788
789 for (const auto *A : attrs()) {
790 if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(Val: A)) {
791 if (Result >= AR_Deprecated)
792 continue;
793
794 if (Message)
795 ResultMessage = std::string(Deprecated->getMessage());
796
797 Result = AR_Deprecated;
798 continue;
799 }
800
801 if (const auto *Unavailable = dyn_cast<UnavailableAttr>(Val: A)) {
802 if (Message)
803 *Message = std::string(Unavailable->getMessage());
804 return AR_Unavailable;
805 }
806
807 if (const auto *Availability = dyn_cast<AvailabilityAttr>(Val: A)) {
808 Availability = Availability->getEffectiveAttr();
809 AvailabilityResult AR = CheckAvailability(Context&: getASTContext(), A: Availability,
810 Message, EnclosingVersion);
811
812 if (AR == AR_Unavailable) {
813 if (RealizedPlatform)
814 *RealizedPlatform = Availability->getPlatform()->getName();
815 return AR_Unavailable;
816 }
817
818 if (AR > Result) {
819 Result = AR;
820 if (Message)
821 ResultMessage.swap(s&: *Message);
822 }
823 continue;
824 }
825 }
826
827 if (Message)
828 Message->swap(s&: ResultMessage);
829 return Result;
830}
831
832VersionTuple Decl::getVersionIntroduced() const {
833 const ASTContext &Context = getASTContext();
834 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
835 for (const auto *A : attrs()) {
836 if (const auto *Availability = dyn_cast<AvailabilityAttr>(Val: A)) {
837 Availability = Availability->getEffectiveAttr();
838 if (getRealizedPlatform(A: Availability, Context) == TargetPlatform) {
839 if (!Availability->getIntroduced().empty())
840 return Availability->getIntroduced();
841 }
842 }
843 }
844 return {};
845}
846
847bool Decl::canBeWeakImported(bool &IsDefinition) const {
848 IsDefinition = false;
849
850 // Variables, if they aren't definitions.
851 if (const auto *Var = dyn_cast<VarDecl>(Val: this)) {
852 if (Var->isThisDeclarationADefinition()) {
853 IsDefinition = true;
854 return false;
855 }
856 return true;
857 }
858 // Functions, if they aren't definitions.
859 if (const auto *FD = dyn_cast<FunctionDecl>(Val: this)) {
860 if (FD->hasBody()) {
861 IsDefinition = true;
862 return false;
863 }
864 return true;
865
866 }
867 // Objective-C classes, if this is the non-fragile runtime.
868 if (isa<ObjCInterfaceDecl>(Val: this) &&
869 getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
870 return true;
871 }
872 // Nothing else.
873 return false;
874}
875
876bool Decl::isWeakImported() const {
877 const Decl *MostRecentDecl = getMostRecentDecl();
878 if (!MostRecentDecl->hasAttrs())
879 return false;
880
881 bool IsDefinition;
882 if (!canBeWeakImported(IsDefinition))
883 return false;
884
885 for (const auto *A : MostRecentDecl->attrs()) {
886 if (isa<WeakImportAttr>(Val: A))
887 return true;
888
889 if (const auto *Availability = dyn_cast<AvailabilityAttr>(Val: A)) {
890 Availability = Availability->getEffectiveAttr();
891 if (CheckAvailability(Context&: getASTContext(), A: Availability, Message: nullptr,
892 EnclosingVersion: VersionTuple()) == AR_NotYetIntroduced)
893 return true;
894 }
895 }
896
897 return false;
898}
899
900unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
901 switch (DeclKind) {
902 case Function:
903 case CXXDeductionGuide:
904 case CXXMethod:
905 case CXXConstructor:
906 case ConstructorUsingShadow:
907 case CXXDestructor:
908 case CXXConversion:
909 case EnumConstant:
910 case Var:
911 case ImplicitParam:
912 case ParmVar:
913 case ObjCMethod:
914 case ObjCProperty:
915 case MSProperty:
916 case HLSLBuffer:
917 case HLSLRootSignature:
918 return IDNS_Ordinary;
919 case Label:
920 return IDNS_Label;
921
922 case Binding:
923 case NonTypeTemplateParm:
924 case VarTemplate:
925 case Concept:
926 // These (C++-only) declarations are found by redeclaration lookup for
927 // tag types, so we include them in the tag namespace.
928 return IDNS_Ordinary | IDNS_Tag;
929
930 case ObjCCompatibleAlias:
931 case ObjCInterface:
932 return IDNS_Ordinary | IDNS_Type;
933
934 case Typedef:
935 case TypeAlias:
936 case TemplateTypeParm:
937 case ObjCTypeParam:
938 return IDNS_Ordinary | IDNS_Type;
939
940 case UnresolvedUsingTypename:
941 return IDNS_Ordinary | IDNS_Type | IDNS_Using;
942
943 case UsingShadow:
944 return 0; // we'll actually overwrite this later
945
946 case UnresolvedUsingValue:
947 return IDNS_Ordinary | IDNS_Using;
948
949 case Using:
950 case UsingPack:
951 case UsingEnum:
952 return IDNS_Using;
953
954 case ObjCProtocol:
955 return IDNS_ObjCProtocol;
956
957 case Field:
958 case IndirectField:
959 case ObjCAtDefsField:
960 case ObjCIvar:
961 return IDNS_Member;
962
963 case Record:
964 case CXXRecord:
965 case Enum:
966 return IDNS_Tag | IDNS_Type;
967
968 case Namespace:
969 case NamespaceAlias:
970 return IDNS_Namespace;
971
972 case FunctionTemplate:
973 return IDNS_Ordinary;
974
975 case ClassTemplate:
976 case TemplateTemplateParm:
977 case TypeAliasTemplate:
978 return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
979
980 case UnresolvedUsingIfExists:
981 return IDNS_Type | IDNS_Ordinary;
982
983 case OMPDeclareReduction:
984 return IDNS_OMPReduction;
985
986 case OMPDeclareMapper:
987 return IDNS_OMPMapper;
988
989 // Never have names.
990 case Friend:
991 case FriendTemplate:
992 case AccessSpec:
993 case LinkageSpec:
994 case Export:
995 case FileScopeAsm:
996 case TopLevelStmt:
997 case StaticAssert:
998 case ObjCPropertyImpl:
999 case PragmaComment:
1000 case PragmaDetectMismatch:
1001 case Block:
1002 case Captured:
1003 case OutlinedFunction:
1004 case TranslationUnit:
1005 case ExternCContext:
1006 case Decomposition:
1007 case MSGuid:
1008 case UnnamedGlobalConstant:
1009 case TemplateParamObject:
1010
1011 case UsingDirective:
1012 case BuiltinTemplate:
1013 case ClassTemplateSpecialization:
1014 case ClassTemplatePartialSpecialization:
1015 case VarTemplateSpecialization:
1016 case VarTemplatePartialSpecialization:
1017 case ObjCImplementation:
1018 case ObjCCategory:
1019 case ObjCCategoryImpl:
1020 case Import:
1021 case OMPThreadPrivate:
1022 case OMPGroupPrivate:
1023 case OMPAllocate:
1024 case OMPRequires:
1025 case OMPCapturedExpr:
1026 case Empty:
1027 case LifetimeExtendedTemporary:
1028 case RequiresExprBody:
1029 case ImplicitConceptSpecialization:
1030 case OpenACCDeclare:
1031 case OpenACCRoutine:
1032 case ExplicitInstantiation:
1033 case CXXExpansionStmt:
1034 // Never looked up by name.
1035 return 0;
1036 }
1037
1038 llvm_unreachable("Invalid DeclKind!");
1039}
1040
1041void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
1042 assert(!Attrs && "Decl already contains attrs.");
1043
1044 Attrs = Ctx.allocateAttrVec();
1045 *Attrs = attrs;
1046}
1047
1048void Decl::dropAttrs() {
1049 if (!Attrs)
1050 return;
1051
1052 // The vector itself belongs to the ASTContext's allocator and is destroyed
1053 // when the context dies; only the pointer is dropped here.
1054 Attrs->clear();
1055 Attrs = nullptr;
1056}
1057
1058void Decl::addAttr(Attr *A) {
1059 if (!hasAttrs()) {
1060 setAttrs(AttrVec(1, A));
1061 return;
1062 }
1063
1064 AttrVec &Attrs = getAttrs();
1065 if (!A->isInherited()) {
1066 Attrs.push_back(Elt: A);
1067 return;
1068 }
1069
1070 // Attribute inheritance is processed after attribute parsing. To keep the
1071 // order as in the source code, add inherited attributes before non-inherited
1072 // ones.
1073 auto I = Attrs.begin(), E = Attrs.end();
1074 for (; I != E; ++I) {
1075 if (!(*I)->isInherited())
1076 break;
1077 }
1078 Attrs.insert(I, Elt: A);
1079}
1080
1081const AttrVec &Decl::getAttrs() const {
1082 assert(Attrs && "No attrs to get!");
1083 return *Attrs;
1084}
1085
1086Decl *Decl::castFromDeclContext (const DeclContext *D) {
1087 Decl::Kind DK = D->getDeclKind();
1088 switch (DK) {
1089#define DECL(NAME, BASE)
1090#define DECL_CONTEXT(NAME) \
1091 case Decl::NAME: \
1092 return static_cast<NAME##Decl *>(const_cast<DeclContext *>(D));
1093#include "clang/AST/DeclNodes.inc"
1094 default:
1095 llvm_unreachable("a decl that inherits DeclContext isn't handled");
1096 }
1097}
1098
1099DeclContext *Decl::castToDeclContext(const Decl *D) {
1100 Decl::Kind DK = D->getKind();
1101 switch(DK) {
1102#define DECL(NAME, BASE)
1103#define DECL_CONTEXT(NAME) \
1104 case Decl::NAME: \
1105 return static_cast<NAME##Decl *>(const_cast<Decl *>(D));
1106#include "clang/AST/DeclNodes.inc"
1107 default:
1108 llvm_unreachable("a decl that inherits DeclContext isn't handled");
1109 }
1110}
1111
1112SourceLocation Decl::getBodyRBrace() const {
1113 // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
1114 // FunctionDecl stores EndRangeLoc for this purpose.
1115 if (const auto *FD = dyn_cast<FunctionDecl>(Val: this)) {
1116 const FunctionDecl *Definition;
1117 if (FD->hasBody(Definition))
1118 return Definition->getSourceRange().getEnd();
1119 return {};
1120 }
1121
1122 if (Stmt *Body = getBody())
1123 return Body->getSourceRange().getEnd();
1124
1125 return {};
1126}
1127
1128bool Decl::AccessDeclContextCheck() const {
1129#ifndef NDEBUG
1130 // Suppress this check if any of the following hold:
1131 // 1. this is the translation unit (and thus has no parent)
1132 // 2. this is a template parameter (and thus doesn't belong to its context)
1133 // 3. this is a non-type template parameter
1134 // 4. the context is not a record
1135 // 5. it's invalid
1136 // 6. it's a C++0x static_assert.
1137 // 7. it's a block literal declaration
1138 // 8. it's a temporary with lifetime extended due to being default value.
1139 if (isa<TranslationUnitDecl>(this) || isa<TemplateTypeParmDecl>(this) ||
1140 isa<NonTypeTemplateParmDecl>(this) || !getDeclContext() ||
1141 !isa<CXXRecordDecl>(getDeclContext()) || isInvalidDecl() ||
1142 isa<StaticAssertDecl>(this) || isa<BlockDecl>(this) ||
1143 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
1144 // as DeclContext (?).
1145 isa<ParmVarDecl>(this) ||
1146 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
1147 // AS_none as access specifier.
1148 isa<CXXRecordDecl>(this) || isa<LifetimeExtendedTemporaryDecl>(this))
1149 return true;
1150
1151 assert(Access != AS_none &&
1152 "Access specifier is AS_none inside a record decl");
1153#endif
1154 return true;
1155}
1156
1157bool Decl::isInExportDeclContext() const {
1158 const DeclContext *DC = getLexicalDeclContext();
1159
1160 while (DC && !isa<ExportDecl>(Val: DC))
1161 DC = DC->getLexicalParent();
1162
1163 return isa_and_nonnull<ExportDecl>(Val: DC);
1164}
1165
1166bool Decl::isModuleLocal() const {
1167 if (isa<NamespaceDecl, TranslationUnitDecl>(Val: this))
1168 return false;
1169 auto *M = getOwningModule();
1170 return M && M->isNamedModule() &&
1171 getModuleOwnershipKind() == ModuleOwnershipKind::ReachableWhenImported;
1172}
1173
1174bool Decl::isInAnotherModuleUnit() const {
1175 auto *M = getOwningModule();
1176
1177 if (!M)
1178 return false;
1179
1180 // FIXME or NOTE: maybe we need to be clear about the semantics
1181 // of clang header modules. e.g., if this lives in a clang header
1182 // module included by the current unit, should we return false
1183 // here?
1184 //
1185 // This is clear for header units as the specification says the
1186 // header units live in a synthesised translation unit. So we
1187 // can return false here.
1188 M = M->getTopLevelModule();
1189 if (!M->isNamedModule())
1190 return false;
1191
1192 return M != getASTContext().getCurrentNamedModule();
1193}
1194
1195bool Decl::isInCurrentModuleUnit() const {
1196 auto *M = getOwningModule();
1197
1198 if (!M || !M->isNamedModule())
1199 return false;
1200
1201 return M == getASTContext().getCurrentNamedModule();
1202}
1203
1204bool Decl::shouldEmitInExternalSource() const {
1205 ExternalASTSource *Source = getASTContext().getExternalSource();
1206 if (!Source)
1207 return false;
1208
1209 return Source->hasExternalDefinitions(D: this) == ExternalASTSource::EK_Always;
1210}
1211
1212bool Decl::isFromExplicitGlobalModule() const {
1213 return getOwningModule() && getOwningModule()->isExplicitGlobalModule();
1214}
1215
1216bool Decl::isFromGlobalModule() const {
1217 return getOwningModule() && getOwningModule()->isGlobalModule();
1218}
1219
1220bool Decl::isInNamedModule() const {
1221 return getOwningModule() && getOwningModule()->isNamedModule();
1222}
1223
1224bool Decl::isFromHeaderUnit() const {
1225 return getOwningModule() && getOwningModule()->isHeaderUnit();
1226}
1227
1228static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
1229static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
1230
1231int64_t Decl::getID() const {
1232 return getASTContext().getAllocator().identifyKnownAlignedObject<Decl>(Ptr: this);
1233}
1234
1235const FunctionType *Decl::getFunctionType(bool BlocksToo) const {
1236 QualType Ty;
1237 if (const auto *D = dyn_cast<ValueDecl>(Val: this))
1238 Ty = D->getType();
1239 else if (const auto *D = dyn_cast<TypedefNameDecl>(Val: this))
1240 Ty = D->getUnderlyingType();
1241 else
1242 return nullptr;
1243
1244 if (Ty.isNull()) {
1245 // BindingDecls do not have types during parsing, so return nullptr. This is
1246 // the only known case where `Ty` is null.
1247 assert(isa<BindingDecl>(this));
1248 return nullptr;
1249 }
1250
1251 if (Ty->isFunctionPointerType())
1252 Ty = Ty->castAs<PointerType>()->getPointeeType();
1253 else if (Ty->isMemberFunctionPointerType())
1254 Ty = Ty->castAs<MemberPointerType>()->getPointeeType();
1255 else if (Ty->isFunctionReferenceType())
1256 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
1257 else if (BlocksToo && Ty->isBlockPointerType())
1258 Ty = Ty->castAs<BlockPointerType>()->getPointeeType();
1259
1260 return Ty->getAs<FunctionType>();
1261}
1262
1263bool Decl::isFunctionPointerType() const {
1264 QualType Ty;
1265 if (const auto *D = dyn_cast<ValueDecl>(Val: this))
1266 Ty = D->getType();
1267 else if (const auto *D = dyn_cast<TypedefNameDecl>(Val: this))
1268 Ty = D->getUnderlyingType();
1269 else
1270 return false;
1271
1272 return Ty.getCanonicalType()->isFunctionPointerType();
1273}
1274
1275DeclContext *Decl::getNonTransparentDeclContext() {
1276 assert(getDeclContext());
1277 return getDeclContext()->getNonTransparentContext();
1278}
1279
1280/// Starting at a given context (a Decl or DeclContext), look for a
1281/// code context that is not a closure (a lambda, block, etc.).
1282template <class T> static Decl *getNonClosureContext(T *D) {
1283 if (getKind(D) == Decl::CXXMethod) {
1284 auto *MD = cast<CXXMethodDecl>(D);
1285 if (MD->getOverloadedOperator() == OO_Call &&
1286 MD->getParent()->isLambda())
1287 return getNonClosureContext(MD->getParent()->getParent());
1288 return MD;
1289 }
1290 if (auto *FD = dyn_cast<FunctionDecl>(D))
1291 return FD;
1292 if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
1293 return MD;
1294 if (auto *BD = dyn_cast<BlockDecl>(D))
1295 return getNonClosureContext(BD->getParent());
1296 if (auto *CD = dyn_cast<CapturedDecl>(D))
1297 return getNonClosureContext(CD->getParent());
1298 if (auto *OFD = dyn_cast<OutlinedFunctionDecl>(D))
1299 return getNonClosureContext(OFD->getParent());
1300 return nullptr;
1301}
1302
1303Decl *Decl::getNonClosureContext() {
1304 return ::getNonClosureContext(D: this);
1305}
1306
1307Decl *DeclContext::getNonClosureAncestor() {
1308 return ::getNonClosureContext(D: this);
1309}
1310
1311//===----------------------------------------------------------------------===//
1312// DeclContext Implementation
1313//===----------------------------------------------------------------------===//
1314
1315DeclContext::DeclContext(Decl::Kind K) {
1316 DeclContextBits.DeclKind = K;
1317 setHasExternalLexicalStorage(false);
1318 setHasExternalVisibleStorage(false);
1319 setNeedToReconcileExternalVisibleStorage(false);
1320 setHasLazyLocalLexicalLookups(false);
1321 setHasLazyExternalLexicalLookups(false);
1322}
1323
1324bool DeclContext::classof(const Decl *D) {
1325 Decl::Kind DK = D->getKind();
1326 switch (DK) {
1327#define DECL(NAME, BASE)
1328#define DECL_CONTEXT(NAME) case Decl::NAME:
1329#include "clang/AST/DeclNodes.inc"
1330 return true;
1331 default:
1332 return false;
1333 }
1334}
1335
1336DeclContext::~DeclContext() = default;
1337
1338/// Find the parent context of this context that will be
1339/// used for unqualified name lookup.
1340///
1341/// Generally, the parent lookup context is the semantic context. However, for
1342/// a friend function the parent lookup context is the lexical context, which
1343/// is the class in which the friend is declared.
1344DeclContext *DeclContext::getLookupParent() {
1345 // FIXME: Find a better way to identify friends.
1346 if (isa<FunctionDecl>(Val: this))
1347 if (getParent()->getRedeclContext()->isFileContext() &&
1348 getLexicalParent()->getRedeclContext()->isRecord())
1349 return getLexicalParent();
1350
1351 // A lookup within the call operator of a lambda never looks in the lambda
1352 // class; instead, skip to the context in which that closure type is
1353 // declared.
1354 if (isLambdaCallOperator(DC: this))
1355 return getParent()->getParent();
1356
1357 return getParent();
1358}
1359
1360const BlockDecl *DeclContext::getInnermostBlockDecl() const {
1361 const DeclContext *Ctx = this;
1362
1363 do {
1364 if (Ctx->isClosure())
1365 return cast<BlockDecl>(Val: Ctx);
1366 Ctx = Ctx->getParent();
1367 } while (Ctx);
1368
1369 return nullptr;
1370}
1371
1372bool DeclContext::isInlineNamespace() const {
1373 return isNamespace() &&
1374 cast<NamespaceDecl>(Val: this)->isInline();
1375}
1376
1377bool DeclContext::isStdNamespace() const {
1378 if (!isNamespace())
1379 return false;
1380
1381 const auto *ND = cast<NamespaceDecl>(Val: this);
1382 if (ND->isInline()) {
1383 return ND->getParent()->isStdNamespace();
1384 }
1385
1386 if (!getParent()->getRedeclContext()->isTranslationUnit())
1387 return false;
1388
1389 const IdentifierInfo *II = ND->getIdentifier();
1390 return II && II->isStr(Str: "std");
1391}
1392
1393bool DeclContext::isDependentContext() const {
1394 if (isFileContext())
1395 return false;
1396
1397 if (isa<ClassTemplatePartialSpecializationDecl, CXXExpansionStmtDecl>(Val: this))
1398 return true;
1399
1400 if (const auto *Record = dyn_cast<CXXRecordDecl>(Val: this)) {
1401 if (Record->getDescribedClassTemplate())
1402 return true;
1403
1404 if (Record->isDependentLambda())
1405 return true;
1406 if (Record->isNeverDependentLambda())
1407 return false;
1408 }
1409
1410 if (const auto *Function = dyn_cast<FunctionDecl>(Val: this)) {
1411 if (Function->getDescribedFunctionTemplate())
1412 return true;
1413
1414 // Friend function declarations are dependent if their *lexical*
1415 // context is dependent.
1416 if (cast<Decl>(Val: this)->getFriendObjectKind())
1417 return getLexicalParent()->isDependentContext();
1418 }
1419
1420 // FIXME: A variable template is a dependent context, but is not a
1421 // DeclContext. A context within it (such as a lambda-expression)
1422 // should be considered dependent.
1423
1424 return getParent() && getParent()->isDependentContext();
1425}
1426
1427bool DeclContext::isTransparentContext() const {
1428 if (getDeclKind() == Decl::Enum)
1429 return !cast<EnumDecl>(Val: this)->isScoped();
1430
1431 return isa<LinkageSpecDecl, ExportDecl, HLSLBufferDecl>(Val: this);
1432}
1433
1434static bool isLinkageSpecContext(const DeclContext *DC,
1435 LinkageSpecLanguageIDs ID) {
1436 while (DC->getDeclKind() != Decl::TranslationUnit) {
1437 if (DC->getDeclKind() == Decl::LinkageSpec)
1438 return cast<LinkageSpecDecl>(Val: DC)->getLanguage() == ID;
1439 DC = DC->getLexicalParent();
1440 }
1441 return false;
1442}
1443
1444bool DeclContext::isExternCContext() const {
1445 return isLinkageSpecContext(DC: this, ID: LinkageSpecLanguageIDs::C);
1446}
1447
1448const LinkageSpecDecl *DeclContext::getExternCContext() const {
1449 const DeclContext *DC = this;
1450 while (DC->getDeclKind() != Decl::TranslationUnit) {
1451 if (DC->getDeclKind() == Decl::LinkageSpec &&
1452 cast<LinkageSpecDecl>(Val: DC)->getLanguage() == LinkageSpecLanguageIDs::C)
1453 return cast<LinkageSpecDecl>(Val: DC);
1454 DC = DC->getLexicalParent();
1455 }
1456 return nullptr;
1457}
1458
1459bool DeclContext::isExternCXXContext() const {
1460 return isLinkageSpecContext(DC: this, ID: LinkageSpecLanguageIDs::CXX);
1461}
1462
1463bool DeclContext::Encloses(const DeclContext *DC) const {
1464 if (getPrimaryContext() != this)
1465 return getPrimaryContext()->Encloses(DC);
1466
1467 for (; DC; DC = DC->getParent())
1468 if (!isa<LinkageSpecDecl, ExportDecl>(Val: DC) &&
1469 DC->getPrimaryContext() == this)
1470 return true;
1471 return false;
1472}
1473
1474bool DeclContext::LexicallyEncloses(const DeclContext *DC) const {
1475 if (getPrimaryContext() != this)
1476 return getPrimaryContext()->LexicallyEncloses(DC);
1477
1478 for (; DC; DC = DC->getLexicalParent())
1479 if (!isa<LinkageSpecDecl, ExportDecl>(Val: DC) &&
1480 DC->getPrimaryContext() == this)
1481 return true;
1482 return false;
1483}
1484
1485DeclContext *DeclContext::getNonTransparentContext() {
1486 DeclContext *DC = this;
1487 while (DC->isTransparentContext()) {
1488 DC = DC->getParent();
1489 assert(DC && "All transparent contexts should have a parent!");
1490 }
1491 return DC;
1492}
1493
1494DeclContext *DeclContext::getPrimaryContext() {
1495 switch (getDeclKind()) {
1496 case Decl::ExternCContext:
1497 case Decl::LinkageSpec:
1498 case Decl::Export:
1499 case Decl::TopLevelStmt:
1500 case Decl::Block:
1501 case Decl::Captured:
1502 case Decl::OutlinedFunction:
1503 case Decl::OMPDeclareReduction:
1504 case Decl::OMPDeclareMapper:
1505 case Decl::RequiresExprBody:
1506 case Decl::CXXExpansionStmt:
1507 // There is only one DeclContext for these entities.
1508 return this;
1509
1510 case Decl::HLSLBuffer:
1511 // Each buffer, even with the same name, is a distinct construct.
1512 // Multiple buffers with the same name are allowed for backward
1513 // compatibility.
1514 // As long as buffers have unique resource bindings the names don't matter.
1515 // The names get exposed via the CPU-side reflection API which
1516 // supports querying bindings, so we cannot remove them.
1517 return this;
1518
1519 case Decl::TranslationUnit:
1520 return static_cast<TranslationUnitDecl *>(this)->getFirstDecl();
1521 case Decl::Namespace:
1522 return static_cast<NamespaceDecl *>(this)->getFirstDecl();
1523
1524 case Decl::ObjCMethod:
1525 return this;
1526
1527 case Decl::ObjCInterface:
1528 if (auto *OID = dyn_cast<ObjCInterfaceDecl>(Val: this))
1529 if (auto *Def = OID->getDefinition())
1530 return Def;
1531 return this;
1532
1533 case Decl::ObjCProtocol:
1534 if (auto *OPD = dyn_cast<ObjCProtocolDecl>(Val: this))
1535 if (auto *Def = OPD->getDefinition())
1536 return Def;
1537 return this;
1538
1539 case Decl::ObjCCategory:
1540 return this;
1541
1542 case Decl::ObjCImplementation:
1543 case Decl::ObjCCategoryImpl:
1544 return this;
1545
1546 // If this is a tag type that has a definition or is currently
1547 // being defined, that definition is our primary context.
1548 case Decl::ClassTemplatePartialSpecialization:
1549 case Decl::ClassTemplateSpecialization:
1550 case Decl::CXXRecord:
1551 return cast<CXXRecordDecl>(Val: this)->getDefinitionOrSelf();
1552 case Decl::Record:
1553 case Decl::Enum:
1554 return cast<TagDecl>(Val: this)->getDefinitionOrSelf();
1555
1556 default:
1557 assert(getDeclKind() >= Decl::firstFunction &&
1558 getDeclKind() <= Decl::lastFunction && "Unknown DeclContext kind");
1559 return this;
1560 }
1561}
1562
1563template <typename T>
1564static void collectAllContextsImpl(T *Self,
1565 SmallVectorImpl<DeclContext *> &Contexts) {
1566 for (T *D = Self->getMostRecentDecl(); D; D = D->getPreviousDecl())
1567 Contexts.push_back(Elt: D);
1568
1569 std::reverse(first: Contexts.begin(), last: Contexts.end());
1570}
1571
1572void DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts) {
1573 Contexts.clear();
1574
1575 Decl::Kind Kind = getDeclKind();
1576
1577 if (Kind == Decl::TranslationUnit)
1578 collectAllContextsImpl(Self: static_cast<TranslationUnitDecl *>(this), Contexts);
1579 else if (Kind == Decl::Namespace)
1580 collectAllContextsImpl(Self: static_cast<NamespaceDecl *>(this), Contexts);
1581 else
1582 Contexts.push_back(Elt: this);
1583}
1584
1585std::pair<Decl *, Decl *>
1586DeclContext::BuildDeclChain(ArrayRef<Decl *> Decls,
1587 bool FieldsAlreadyLoaded) {
1588 // Build up a chain of declarations via the Decl::NextInContextAndBits field.
1589 Decl *FirstNewDecl = nullptr;
1590 Decl *PrevDecl = nullptr;
1591 for (auto *D : Decls) {
1592 if (FieldsAlreadyLoaded && isa<FieldDecl>(Val: D))
1593 continue;
1594
1595 if (PrevDecl)
1596 PrevDecl->NextInContextAndBits.setPointer(D);
1597 else
1598 FirstNewDecl = D;
1599
1600 PrevDecl = D;
1601 }
1602
1603 return std::make_pair(x&: FirstNewDecl, y&: PrevDecl);
1604}
1605
1606/// We have just acquired external visible storage, and we already have
1607/// built a lookup map. For every name in the map, pull in the new names from
1608/// the external storage.
1609void DeclContext::reconcileExternalVisibleStorage() const {
1610 assert(hasNeedToReconcileExternalVisibleStorage() && LookupPtr);
1611 setNeedToReconcileExternalVisibleStorage(false);
1612
1613 for (auto &Lookup : *LookupPtr)
1614 Lookup.second.setHasExternalDecls();
1615}
1616
1617/// Load the declarations within this lexical storage from an
1618/// external source.
1619/// \return \c true if any declarations were added.
1620bool
1621DeclContext::LoadLexicalDeclsFromExternalStorage() const {
1622 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1623 assert(hasExternalLexicalStorage() && Source && "No external storage?");
1624
1625 // Notify that we have a DeclContext that is initializing.
1626 ExternalASTSource::Deserializing ADeclContext(Source);
1627
1628 // Load the external declarations, if any.
1629 SmallVector<Decl*, 64> Decls;
1630 setHasExternalLexicalStorage(false);
1631 Source->FindExternalLexicalDecls(DC: this, Result&: Decls);
1632
1633 if (Decls.empty())
1634 return false;
1635
1636 // We may have already loaded just the fields of this record, in which case
1637 // we need to ignore them.
1638 bool FieldsAlreadyLoaded = false;
1639 if (const auto *RD = dyn_cast<RecordDecl>(Val: this))
1640 FieldsAlreadyLoaded = RD->hasLoadedFieldsFromExternalStorage();
1641
1642 // Splice the newly-read declarations into the beginning of the list
1643 // of declarations.
1644 Decl *ExternalFirst, *ExternalLast;
1645 std::tie(args&: ExternalFirst, args&: ExternalLast) =
1646 BuildDeclChain(Decls, FieldsAlreadyLoaded);
1647 ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
1648 FirstDecl = ExternalFirst;
1649 if (!LastDecl)
1650 LastDecl = ExternalLast;
1651 return true;
1652}
1653
1654DeclContext::lookup_result
1655ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
1656 DeclarationName Name) {
1657 ASTContext &Context = DC->getParentASTContext();
1658 StoredDeclsMap *Map;
1659 if (!(Map = DC->LookupPtr))
1660 Map = DC->CreateStoredDeclsMap(C&: Context);
1661 if (DC->hasNeedToReconcileExternalVisibleStorage())
1662 DC->reconcileExternalVisibleStorage();
1663
1664 (*Map)[Name].removeExternalDecls();
1665
1666 return DeclContext::lookup_result();
1667}
1668
1669DeclContext::lookup_result
1670ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
1671 DeclarationName Name,
1672 ArrayRef<NamedDecl*> Decls) {
1673 ASTContext &Context = DC->getParentASTContext();
1674 StoredDeclsMap *Map;
1675 if (!(Map = DC->LookupPtr))
1676 Map = DC->CreateStoredDeclsMap(C&: Context);
1677 if (DC->hasNeedToReconcileExternalVisibleStorage())
1678 DC->reconcileExternalVisibleStorage();
1679
1680 StoredDeclsList &List = (*Map)[Name];
1681 List.replaceExternalDecls(Decls);
1682 return List.getLookupResult();
1683}
1684
1685DeclContext::decl_iterator DeclContext::decls_begin() const {
1686 if (hasExternalLexicalStorage())
1687 LoadLexicalDeclsFromExternalStorage();
1688 return decl_iterator(FirstDecl);
1689}
1690
1691bool DeclContext::decls_empty() const {
1692 if (hasExternalLexicalStorage())
1693 LoadLexicalDeclsFromExternalStorage();
1694
1695 return !FirstDecl;
1696}
1697
1698bool DeclContext::containsDecl(Decl *D) const {
1699 return (D->getLexicalDeclContext() == this &&
1700 (D->NextInContextAndBits.getPointer() || D == LastDecl));
1701}
1702
1703bool DeclContext::containsDeclAndLoad(Decl *D) const {
1704 if (hasExternalLexicalStorage())
1705 LoadLexicalDeclsFromExternalStorage();
1706 return containsDecl(D);
1707}
1708
1709/// shouldBeHidden - Determine whether a declaration which was declared
1710/// within its semantic context should be invisible to qualified name lookup.
1711static bool shouldBeHidden(NamedDecl *D) {
1712 // Skip unnamed declarations.
1713 if (!D->getDeclName())
1714 return true;
1715
1716 // Skip entities that can't be found by name lookup into a particular
1717 // context.
1718 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(Val: D)) ||
1719 D->isTemplateParameter())
1720 return true;
1721
1722 // Skip friends and local extern declarations unless they're the first
1723 // declaration of the entity.
1724 if ((D->isLocalExternDecl() || D->getFriendObjectKind()) &&
1725 D != D->getCanonicalDecl())
1726 return true;
1727
1728 // Skip template specializations.
1729 // FIXME: This feels like a hack. Should DeclarationName support
1730 // template-ids, or is there a better way to keep specializations
1731 // from being visible?
1732 if (isa<ClassTemplateSpecializationDecl>(Val: D))
1733 return true;
1734 if (auto *FD = dyn_cast<FunctionDecl>(Val: D))
1735 if (FD->isFunctionTemplateSpecialization())
1736 return true;
1737
1738 // Hide destructors that are invalid. There should always be one destructor,
1739 // but if it is an invalid decl, another one is created. We need to hide the
1740 // invalid one from places that expect exactly one destructor, like the
1741 // serialization code.
1742 if (isa<CXXDestructorDecl>(Val: D) && D->isInvalidDecl())
1743 return true;
1744
1745 return false;
1746}
1747
1748void DeclContext::removeDecl(Decl *D) {
1749 assert(D->getLexicalDeclContext() == this &&
1750 "decl being removed from non-lexical context");
1751 assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
1752 "decl is not in decls list");
1753
1754 // Remove D from the decl chain. This is O(n) but hopefully rare.
1755 if (D == FirstDecl) {
1756 if (D == LastDecl)
1757 FirstDecl = LastDecl = nullptr;
1758 else
1759 FirstDecl = D->NextInContextAndBits.getPointer();
1760 } else {
1761 for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
1762 assert(I && "decl not found in linked list");
1763 if (I->NextInContextAndBits.getPointer() == D) {
1764 I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
1765 if (D == LastDecl) LastDecl = I;
1766 break;
1767 }
1768 }
1769 }
1770
1771 // Mark that D is no longer in the decl chain.
1772 D->NextInContextAndBits.setPointer(nullptr);
1773
1774 // Remove D from the lookup table if necessary.
1775 if (isa<NamedDecl>(Val: D)) {
1776 auto *ND = cast<NamedDecl>(Val: D);
1777
1778 // Do not try to remove the declaration if that is invisible to qualified
1779 // lookup. E.g. template specializations are skipped.
1780 if (shouldBeHidden(D: ND))
1781 return;
1782
1783 // Remove only decls that have a name
1784 if (!ND->getDeclName())
1785 return;
1786
1787 auto *DC = D->getDeclContext();
1788 do {
1789 StoredDeclsMap *Map = DC->getPrimaryContext()->LookupPtr;
1790 if (Map) {
1791 StoredDeclsMap::iterator Pos = Map->find(Val: ND->getDeclName());
1792 // In C, the lookup table of the translation unit can miss a declaration
1793 // that was declared outside of it, like a structure declared in
1794 // another one (see makeDeclVisibleInContextWithFlags).
1795 assert((Pos != Map->end() ||
1796 (DC->isTranslationUnit() &&
1797 !getParentASTContext().getLangOpts().CPlusPlus)) &&
1798 "no lookup entry for decl");
1799 if (Pos != Map->end()) {
1800 StoredDeclsList &List = Pos->second;
1801 List.remove(D: ND);
1802 // Clean up the entry if there are no more decls.
1803 if (List.isNull())
1804 Map->erase(I: Pos);
1805 }
1806 }
1807 } while (DC->isTransparentContext() && (DC = DC->getParent()));
1808 }
1809}
1810
1811void DeclContext::addHiddenDecl(Decl *D) {
1812 assert(D->getLexicalDeclContext() == this &&
1813 "Decl inserted into wrong lexical context");
1814 assert(!D->getNextDeclInContext() && D != LastDecl &&
1815 "Decl already inserted into a DeclContext");
1816
1817 if (FirstDecl) {
1818 LastDecl->NextInContextAndBits.setPointer(D);
1819 LastDecl = D;
1820 } else {
1821 FirstDecl = LastDecl = D;
1822 }
1823
1824 // Notify a C++ record declaration that we've added a member, so it can
1825 // update its class-specific state.
1826 if (auto *Record = dyn_cast<CXXRecordDecl>(Val: this))
1827 Record->addedMember(D);
1828
1829 // If this is a newly-created (not de-serialized) import declaration, wire
1830 // it in to the list of local import declarations.
1831 if (!D->isFromASTFile()) {
1832 if (auto *Import = dyn_cast<ImportDecl>(Val: D))
1833 D->getASTContext().addedLocalImportDecl(Import);
1834 }
1835}
1836
1837void DeclContext::addDecl(Decl *D) {
1838 addHiddenDecl(D);
1839
1840 if (auto *ND = dyn_cast<NamedDecl>(Val: D))
1841 ND->getDeclContext()->getPrimaryContext()->
1842 makeDeclVisibleInContextWithFlags(D: ND, Internal: false, Rediscoverable: true);
1843}
1844
1845void DeclContext::addDeclInternal(Decl *D) {
1846 addHiddenDecl(D);
1847
1848 if (auto *ND = dyn_cast<NamedDecl>(Val: D))
1849 ND->getDeclContext()->getPrimaryContext()->
1850 makeDeclVisibleInContextWithFlags(D: ND, Internal: true, Rediscoverable: true);
1851}
1852
1853/// buildLookup - Build the lookup data structure with all of the
1854/// declarations in this DeclContext (and any other contexts linked
1855/// to it or transparent contexts nested within it) and return it.
1856///
1857/// Note that the produced map may miss out declarations from an
1858/// external source. If it does, those entries will be marked with
1859/// the 'hasExternalDecls' flag.
1860StoredDeclsMap *DeclContext::buildLookup() {
1861 assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1862
1863 if (!hasLazyLocalLexicalLookups() &&
1864 !hasLazyExternalLexicalLookups())
1865 return LookupPtr;
1866
1867 SmallVector<DeclContext *, 2> Contexts;
1868 collectAllContexts(Contexts);
1869
1870 if (hasLazyExternalLexicalLookups()) {
1871 setHasLazyExternalLexicalLookups(false);
1872 for (auto *DC : Contexts) {
1873 if (DC->hasExternalLexicalStorage()) {
1874 bool LoadedDecls = DC->LoadLexicalDeclsFromExternalStorage();
1875 setHasLazyLocalLexicalLookups(
1876 hasLazyLocalLexicalLookups() | LoadedDecls );
1877 }
1878 }
1879
1880 if (!hasLazyLocalLexicalLookups())
1881 return LookupPtr;
1882 }
1883
1884 for (auto *DC : Contexts)
1885 buildLookupImpl(DCtx: DC, Internal: hasExternalVisibleStorage());
1886
1887 // We no longer have any lazy decls.
1888 setHasLazyLocalLexicalLookups(false);
1889 return LookupPtr;
1890}
1891
1892/// buildLookupImpl - Build part of the lookup data structure for the
1893/// declarations contained within DCtx, which will either be this
1894/// DeclContext, a DeclContext linked to it, or a transparent context
1895/// nested within it.
1896void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {
1897 for (auto *D : DCtx->noload_decls()) {
1898 // Insert this declaration into the lookup structure, but only if
1899 // it's semantically within its decl context. Any other decls which
1900 // should be found in this context are added eagerly.
1901 //
1902 // If it's from an AST file, don't add it now. It'll get handled by
1903 // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1904 // in C++, we do not track external visible decls for the TU, so in
1905 // that case we need to collect them all here.
1906 if (auto *ND = dyn_cast<NamedDecl>(Val: D))
1907 if (ND->getDeclContext() == DCtx && !shouldBeHidden(D: ND) &&
1908 (!ND->isFromASTFile() ||
1909 (isTranslationUnit() &&
1910 !getParentASTContext().getLangOpts().CPlusPlus)))
1911 makeDeclVisibleInContextImpl(D: ND, Internal);
1912
1913 // If this declaration is itself a transparent declaration context
1914 // or inline namespace, add the members of this declaration of that
1915 // context (recursively).
1916 if (auto *InnerCtx = dyn_cast<DeclContext>(Val: D))
1917 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1918 buildLookupImpl(DCtx: InnerCtx, Internal);
1919 }
1920}
1921
1922DeclContext::lookup_result
1923DeclContext::lookup(DeclarationName Name) const {
1924 // For transparent DeclContext, we should lookup in their enclosing context.
1925 if (getDeclKind() == Decl::LinkageSpec || getDeclKind() == Decl::Export)
1926 return getParent()->lookup(Name);
1927
1928 return getPrimaryContext()->lookupImpl(Name, OriginalLookupDC: this);
1929}
1930
1931DeclContext::lookup_result
1932DeclContext::lookupImpl(DeclarationName Name,
1933 const DeclContext *OriginalLookupDC) const {
1934 assert(this == getPrimaryContext() &&
1935 "lookupImpl should only be called with primary DC!");
1936 assert(getDeclKind() != Decl::LinkageSpec && getDeclKind() != Decl::Export &&
1937 "We shouldn't lookup in transparent DC.");
1938
1939 // If we have an external source, ensure that any later redeclarations of this
1940 // context have been loaded, since they may add names to the result of this
1941 // lookup (or add external visible storage).
1942 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1943 if (Source)
1944 (void)cast<Decl>(Val: this)->getMostRecentDecl();
1945
1946 if (hasExternalVisibleStorage()) {
1947 assert(Source && "external visible storage but no external source?");
1948
1949 if (hasNeedToReconcileExternalVisibleStorage())
1950 reconcileExternalVisibleStorage();
1951
1952 StoredDeclsMap *Map = LookupPtr;
1953
1954 if (hasLazyLocalLexicalLookups() ||
1955 hasLazyExternalLexicalLookups())
1956 // FIXME: Make buildLookup const?
1957 Map = const_cast<DeclContext*>(this)->buildLookup();
1958
1959 if (!Map)
1960 Map = CreateStoredDeclsMap(C&: getParentASTContext());
1961
1962 // If we have a lookup result with no external decls, we are done.
1963 std::pair<StoredDeclsMap::iterator, bool> R = Map->try_emplace(Key: Name);
1964 if (!R.second && !R.first->second.hasExternalDecls())
1965 return R.first->second.getLookupResult();
1966
1967 if (Source->FindExternalVisibleDeclsByName(DC: this, Name, OriginalDC: OriginalLookupDC) ||
1968 !R.second) {
1969 if (StoredDeclsMap *Map = LookupPtr) {
1970 StoredDeclsMap::iterator I = Map->find(Val: Name);
1971 if (I != Map->end())
1972 return I->second.getLookupResult();
1973 }
1974 }
1975
1976 return {};
1977 }
1978
1979 StoredDeclsMap *Map = LookupPtr;
1980 if (hasLazyLocalLexicalLookups() ||
1981 hasLazyExternalLexicalLookups())
1982 Map = const_cast<DeclContext*>(this)->buildLookup();
1983
1984 if (!Map)
1985 return {};
1986
1987 StoredDeclsMap::iterator I = Map->find(Val: Name);
1988 if (I == Map->end())
1989 return {};
1990
1991 return I->second.getLookupResult();
1992}
1993
1994DeclContext::lookup_result
1995DeclContext::noload_lookup(DeclarationName Name) {
1996 // For transparent DeclContext, we should lookup in their enclosing context.
1997 if (getDeclKind() == Decl::LinkageSpec || getDeclKind() == Decl::Export)
1998 return getParent()->noload_lookup(Name);
1999
2000 DeclContext *PrimaryContext = getPrimaryContext();
2001 if (PrimaryContext != this)
2002 return PrimaryContext->noload_lookup(Name);
2003
2004 loadLazyLocalLexicalLookups();
2005 StoredDeclsMap *Map = LookupPtr;
2006 if (!Map)
2007 return {};
2008
2009 StoredDeclsMap::iterator I = Map->find(Val: Name);
2010 return I != Map->end() ? I->second.getLookupResult()
2011 : lookup_result();
2012}
2013
2014// If we have any lazy lexical declarations not in our lookup map, add them
2015// now. Don't import any external declarations, not even if we know we have
2016// some missing from the external visible lookups.
2017void DeclContext::loadLazyLocalLexicalLookups() {
2018 if (hasLazyLocalLexicalLookups()) {
2019 SmallVector<DeclContext *, 2> Contexts;
2020 collectAllContexts(Contexts);
2021 for (auto *Context : Contexts)
2022 buildLookupImpl(DCtx: Context, Internal: hasExternalVisibleStorage());
2023 setHasLazyLocalLexicalLookups(false);
2024 }
2025}
2026
2027void DeclContext::localUncachedLookup(DeclarationName Name,
2028 SmallVectorImpl<NamedDecl *> &Results) {
2029 Results.clear();
2030
2031 // If there's no external storage, just perform a normal lookup and copy
2032 // the results.
2033 if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
2034 lookup_result LookupResults = lookup(Name);
2035 llvm::append_range(C&: Results, R&: LookupResults);
2036 if (!Results.empty())
2037 return;
2038 }
2039
2040 // If we have a lookup table, check there first. Maybe we'll get lucky.
2041 // FIXME: Should we be checking these flags on the primary context?
2042 if (Name && !hasLazyLocalLexicalLookups() &&
2043 !hasLazyExternalLexicalLookups()) {
2044 if (StoredDeclsMap *Map = LookupPtr) {
2045 StoredDeclsMap::iterator Pos = Map->find(Val: Name);
2046 if (Pos != Map->end()) {
2047 Results.insert(I: Results.end(),
2048 From: Pos->second.getLookupResult().begin(),
2049 To: Pos->second.getLookupResult().end());
2050 return;
2051 }
2052 }
2053 }
2054
2055 // Slow case: grovel through the declarations in our chain looking for
2056 // matches.
2057 // FIXME: If we have lazy external declarations, this will not find them!
2058 // FIXME: Should we CollectAllContexts and walk them all here?
2059 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
2060 if (auto *ND = dyn_cast<NamedDecl>(Val: D))
2061 if (ND->getDeclName() == Name)
2062 Results.push_back(Elt: ND);
2063 }
2064}
2065
2066DeclContext *DeclContext::getRedeclContext() {
2067 DeclContext *Ctx = this;
2068
2069 // In C, a record type is the redeclaration context for its fields only. If
2070 // we arrive at a record context after skipping anything else, we should skip
2071 // the record as well. Currently, this means skipping enumerations because
2072 // they're the only transparent context that can exist within a struct or
2073 // union.
2074 bool SkipRecords = getDeclKind() == Decl::Kind::Enum &&
2075 !getParentASTContext().getLangOpts().CPlusPlus;
2076
2077 // Skip through contexts to get to the redeclaration context. Transparent
2078 // contexts are always skipped.
2079 while ((SkipRecords && Ctx->isRecord()) || Ctx->isTransparentContext())
2080 Ctx = Ctx->getParent();
2081 return Ctx;
2082}
2083
2084DeclContext *DeclContext::getEnclosingNamespaceContext() {
2085 DeclContext *Ctx = this;
2086 // Skip through non-namespace, non-translation-unit contexts.
2087 while (!Ctx->isFileContext())
2088 Ctx = Ctx->getParent();
2089 return Ctx->getPrimaryContext();
2090}
2091
2092RecordDecl *DeclContext::getOuterLexicalRecordContext() {
2093 // Loop until we find a non-record context.
2094 RecordDecl *OutermostRD = nullptr;
2095 DeclContext *DC = this;
2096 while (DC->isRecord()) {
2097 OutermostRD = cast<RecordDecl>(Val: DC);
2098 DC = DC->getLexicalParent();
2099 }
2100 return OutermostRD;
2101}
2102
2103DeclContext *DeclContext::getEnclosingNonExpansionStatementContext() {
2104 DeclContext *DC = this;
2105 while (isa<CXXExpansionStmtDecl>(Val: DC))
2106 DC = DC->getParent();
2107 return DC;
2108}
2109
2110FunctionDecl *DeclContext::getEnclosingFunction() {
2111 return dyn_cast<FunctionDecl>(Val: getEnclosingNonExpansionStatementContext());
2112}
2113
2114FunctionDecl *DeclContext::castEnclosingFunction() {
2115 return cast<FunctionDecl>(Val: getEnclosingNonExpansionStatementContext());
2116}
2117
2118bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
2119 // For non-file contexts, this is equivalent to Equals.
2120 if (!isFileContext())
2121 return O->Equals(DC: this);
2122
2123 do {
2124 if (O->Equals(DC: this))
2125 return true;
2126
2127 const auto *NS = dyn_cast<NamespaceDecl>(Val: O);
2128 if (!NS || !NS->isInline())
2129 break;
2130 O = NS->getParent();
2131 } while (O);
2132
2133 return false;
2134}
2135
2136void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
2137 DeclContext *PrimaryDC = this->getPrimaryContext();
2138 DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
2139 // If the decl is being added outside of its semantic decl context, we
2140 // need to ensure that we eagerly build the lookup information for it.
2141 PrimaryDC->makeDeclVisibleInContextWithFlags(D, Internal: false, Rediscoverable: PrimaryDC == DeclDC);
2142}
2143
2144void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
2145 bool Recoverable) {
2146 assert(this == getPrimaryContext() && "expected a primary DC");
2147
2148 if (!isLookupContext()) {
2149 if (isTransparentContext())
2150 getParent()->getPrimaryContext()
2151 ->makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
2152 return;
2153 }
2154
2155 // Skip declarations which should be invisible to name lookup.
2156 if (shouldBeHidden(D))
2157 return;
2158
2159 // If we already have a lookup data structure, perform the insertion into
2160 // it. If we might have externally-stored decls with this name, look them
2161 // up and perform the insertion. If this decl was declared outside its
2162 // semantic context, buildLookup won't add it, so add it now.
2163 //
2164 // FIXME: As a performance hack, don't add such decls into the translation
2165 // unit unless we're in C++, since qualified lookup into the TU is never
2166 // performed.
2167 if (LookupPtr || hasExternalVisibleStorage() ||
2168 ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
2169 (getParentASTContext().getLangOpts().CPlusPlus ||
2170 !isTranslationUnit()))) {
2171 // If we have lazily omitted any decls, they might have the same name as
2172 // the decl which we are adding, so build a full lookup table before adding
2173 // this decl.
2174 buildLookup();
2175 makeDeclVisibleInContextImpl(D, Internal);
2176 } else {
2177 setHasLazyLocalLexicalLookups(true);
2178 }
2179
2180 // If we are a transparent context or inline namespace, insert into our
2181 // parent context, too. This operation is recursive.
2182 if (isTransparentContext() || isInlineNamespace())
2183 getParent()->getPrimaryContext()->
2184 makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
2185
2186 auto *DCAsDecl = cast<Decl>(Val: this);
2187 // Notify that a decl was made visible unless we are a Tag being defined.
2188 if (!(isa<TagDecl>(Val: DCAsDecl) && cast<TagDecl>(Val: DCAsDecl)->isBeingDefined()))
2189 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
2190 L->AddedVisibleDecl(DC: this, D);
2191}
2192
2193void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
2194 // Find or create the stored declaration map.
2195 StoredDeclsMap *Map = LookupPtr;
2196 if (!Map) {
2197 ASTContext *C = &getParentASTContext();
2198 Map = CreateStoredDeclsMap(C&: *C);
2199 }
2200
2201 // If there is an external AST source, load any declarations it knows about
2202 // with this declaration's name.
2203 // If the lookup table contains an entry about this name it means that we
2204 // have already checked the external source.
2205 if (!Internal)
2206 if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
2207 if (hasExternalVisibleStorage() && !Map->contains(Val: D->getDeclName()))
2208 Source->FindExternalVisibleDeclsByName(DC: this, Name: D->getDeclName(),
2209 OriginalDC: D->getDeclContext());
2210
2211 // Insert this declaration into the map.
2212 StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
2213
2214 if (Internal) {
2215 // If this is being added as part of loading an external declaration,
2216 // this may not be the only external declaration with this name.
2217 // In this case, we never try to replace an existing declaration; we'll
2218 // handle that when we finalize the list of declarations for this name.
2219 DeclNameEntries.setHasExternalDecls();
2220 DeclNameEntries.prependDeclNoReplace(D);
2221 return;
2222 }
2223
2224 DeclNameEntries.addOrReplaceDecl(D);
2225}
2226
2227UsingDirectiveDecl *DeclContext::udir_iterator::operator*() const {
2228 return cast<UsingDirectiveDecl>(Val: *I);
2229}
2230
2231/// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
2232/// this context.
2233DeclContext::udir_range DeclContext::using_directives() const {
2234 // FIXME: Use something more efficient than normal lookup for using
2235 // directives. In C++, using directives are looked up more than anything else.
2236 lookup_result Result = lookup(Name: UsingDirectiveDecl::getName());
2237 return udir_range(Result.begin(), Result.end());
2238}
2239
2240//===----------------------------------------------------------------------===//
2241// Creation and Destruction of StoredDeclsMaps. //
2242//===----------------------------------------------------------------------===//
2243
2244StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
2245 assert(!LookupPtr && "context already has a decls map");
2246 assert(getPrimaryContext() == this &&
2247 "creating decls map on non-primary context");
2248
2249 StoredDeclsMap *M;
2250 bool Dependent = isDependentContext();
2251 if (Dependent)
2252 M = new DependentStoredDeclsMap();
2253 else
2254 M = new StoredDeclsMap();
2255 M->Previous = C.LastSDM;
2256 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
2257 LookupPtr = M;
2258 return M;
2259}
2260
2261void ASTContext::ReleaseDeclContextMaps() {
2262 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
2263 // pointer because the subclass doesn't add anything that needs to
2264 // be deleted.
2265 StoredDeclsMap::DestroyAll(Map: LastSDM.getPointer(), Dependent: LastSDM.getInt());
2266 LastSDM.setPointer(nullptr);
2267}
2268
2269void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
2270 while (Map) {
2271 // Advance the iteration before we invalidate memory.
2272 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
2273
2274 if (Dependent)
2275 delete static_cast<DependentStoredDeclsMap*>(Map);
2276 else
2277 delete Map;
2278
2279 Map = Next.getPointer();
2280 Dependent = Next.getInt();
2281 }
2282}
2283
2284DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
2285 DeclContext *Parent,
2286 const PartialDiagnostic &PDiag) {
2287 assert(Parent->isDependentContext()
2288 && "cannot iterate dependent diagnostics of non-dependent context");
2289 Parent = Parent->getPrimaryContext();
2290 if (!Parent->LookupPtr)
2291 Parent->CreateStoredDeclsMap(C);
2292
2293 auto *Map = static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr);
2294
2295 // Allocate the copy of the PartialDiagnostic via the ASTContext's
2296 // BumpPtrAllocator, rather than the ASTContext itself.
2297 DiagnosticStorage *DiagStorage = nullptr;
2298 if (PDiag.hasStorage())
2299 DiagStorage = new (C) DiagnosticStorage;
2300
2301 auto *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
2302
2303 // TODO: Maybe we shouldn't reverse the order during insertion.
2304 DD->NextDiagnostic = Map->FirstDiagnostic;
2305 Map->FirstDiagnostic = DD;
2306
2307 return DD;
2308}
2309
2310unsigned DeclIDBase::getLocalDeclIndex() const {
2311 return ID & llvm::maskTrailingOnes<DeclID>(N: 32);
2312}
2313