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