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

Provided by KDAB

Privacy Policy
Learn to use CMake with our Intro Training
Find out more

source code of clang/lib/AST/DeclBase.cpp