1 //===--- DeclBase.cpp - Declaration AST Node Implementation ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Decl and DeclContext classes.
12 //===----------------------------------------------------------------------===//
14 #include "clang/AST/DeclBase.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclContextInternals.h"
21 #include "clang/AST/DeclFriend.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclOpenMP.h"
24 #include "clang/AST/DeclTemplate.h"
25 #include "clang/AST/DependentDiagnostic.h"
26 #include "clang/AST/ExternalASTSource.h"
27 #include "clang/AST/Stmt.h"
28 #include "clang/AST/StmtCXX.h"
29 #include "clang/AST/Type.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "llvm/Support/raw_ostream.h"
33 using namespace clang;
35 //===----------------------------------------------------------------------===//
37 //===----------------------------------------------------------------------===//
39 #define DECL(DERIVED, BASE) static int n##DERIVED##s = 0;
40 #define ABSTRACT_DECL(DECL)
41 #include "clang/AST/DeclNodes.inc"
43 void Decl::updateOutOfDate(IdentifierInfo &II) const {
44 getASTContext().getExternalSource()->updateOutOfDateIdentifier(II);
47 #define DECL(DERIVED, BASE) \
48 static_assert(alignof(Decl) >= alignof(DERIVED##Decl), \
49 "Alignment sufficient after objects prepended to " #DERIVED);
50 #define ABSTRACT_DECL(DECL)
51 #include "clang/AST/DeclNodes.inc"
53 void *Decl::operator new(std::size_t Size, const ASTContext &Context,
54 unsigned ID, std::size_t Extra) {
55 // Allocate an extra 8 bytes worth of storage, which ensures that the
56 // resulting pointer will still be 8-byte aligned.
57 static_assert(sizeof(unsigned) * 2 >= alignof(Decl),
58 "Decl won't be misaligned");
59 void *Start = Context.Allocate(Size + Extra + 8);
60 void *Result = (char*)Start + 8;
62 unsigned *PrefixPtr = (unsigned *)Result - 2;
64 // Zero out the first 4 bytes; this is used to store the owning module ID.
67 // Store the global declaration ID in the second 4 bytes.
73 void *Decl::operator new(std::size_t Size, const ASTContext &Ctx,
74 DeclContext *Parent, std::size_t Extra) {
75 assert(!Parent || &Parent->getParentASTContext() == &Ctx);
76 // With local visibility enabled, we track the owning module even for local
78 if (Ctx.getLangOpts().trackLocalOwningModule()) {
79 // Ensure required alignment of the resulting object by adding extra
80 // padding at the start if required.
82 llvm::OffsetToAlignment(sizeof(Module *), alignof(Decl));
83 char *Buffer = reinterpret_cast<char *>(
84 ::operator new(ExtraAlign + sizeof(Module *) + Size + Extra, Ctx));
87 Parent ? cast<Decl>(Parent)->getOwningModule() : nullptr;
88 return new (Buffer) Module*(ParentModule) + 1;
90 return ::operator new(Size + Extra, Ctx);
93 Module *Decl::getOwningModuleSlow() const {
94 assert(isFromASTFile() && "Not from AST file?");
95 return getASTContext().getExternalSource()->getModule(getOwningModuleID());
98 bool Decl::hasLocalOwningModuleStorage() const {
99 return getASTContext().getLangOpts().trackLocalOwningModule();
102 const char *Decl::getDeclKindName() const {
104 default: llvm_unreachable("Declaration not in DeclNodes.inc!");
105 #define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
106 #define ABSTRACT_DECL(DECL)
107 #include "clang/AST/DeclNodes.inc"
111 void Decl::setInvalidDecl(bool Invalid) {
112 InvalidDecl = Invalid;
113 assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition());
118 if (!isa<ParmVarDecl>(this)) {
119 // Defensive maneuver for ill-formed code: we're likely not to make it to
120 // a point where we set the access specifier, so default it to "public"
121 // to avoid triggering asserts elsewhere in the front end.
122 setAccess(AS_public);
125 // Marking a DecompositionDecl as invalid implies all the child BindingDecl's
127 if (DecompositionDecl *DD = dyn_cast<DecompositionDecl>(this)) {
128 for (BindingDecl *Binding : DD->bindings()) {
129 Binding->setInvalidDecl();
134 const char *DeclContext::getDeclKindName() const {
136 default: llvm_unreachable("Declaration context not in DeclNodes.inc!");
137 #define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
138 #define ABSTRACT_DECL(DECL)
139 #include "clang/AST/DeclNodes.inc"
143 bool Decl::StatisticsEnabled = false;
144 void Decl::EnableStatistics() {
145 StatisticsEnabled = true;
148 void Decl::PrintStats() {
149 llvm::errs() << "\n*** Decl Stats:\n";
152 #define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
153 #define ABSTRACT_DECL(DECL)
154 #include "clang/AST/DeclNodes.inc"
155 llvm::errs() << " " << totalDecls << " decls total.\n";
158 #define DECL(DERIVED, BASE) \
159 if (n##DERIVED##s > 0) { \
160 totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \
161 llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \
162 << sizeof(DERIVED##Decl) << " each (" \
163 << n##DERIVED##s * sizeof(DERIVED##Decl) \
166 #define ABSTRACT_DECL(DECL)
167 #include "clang/AST/DeclNodes.inc"
169 llvm::errs() << "Total bytes = " << totalBytes << "\n";
172 void Decl::add(Kind k) {
174 #define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
175 #define ABSTRACT_DECL(DECL)
176 #include "clang/AST/DeclNodes.inc"
180 bool Decl::isTemplateParameterPack() const {
181 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
182 return TTP->isParameterPack();
183 if (const NonTypeTemplateParmDecl *NTTP
184 = dyn_cast<NonTypeTemplateParmDecl>(this))
185 return NTTP->isParameterPack();
186 if (const TemplateTemplateParmDecl *TTP
187 = dyn_cast<TemplateTemplateParmDecl>(this))
188 return TTP->isParameterPack();
192 bool Decl::isParameterPack() const {
193 if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this))
194 return Parm->isParameterPack();
196 return isTemplateParameterPack();
199 FunctionDecl *Decl::getAsFunction() {
200 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
202 if (const FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(this))
203 return FTD->getTemplatedDecl();
207 bool Decl::isTemplateDecl() const {
208 return isa<TemplateDecl>(this);
211 TemplateDecl *Decl::getDescribedTemplate() const {
212 if (auto *FD = dyn_cast<FunctionDecl>(this))
213 return FD->getDescribedFunctionTemplate();
214 else if (auto *RD = dyn_cast<CXXRecordDecl>(this))
215 return RD->getDescribedClassTemplate();
216 else if (auto *VD = dyn_cast<VarDecl>(this))
217 return VD->getDescribedVarTemplate();
222 const DeclContext *Decl::getParentFunctionOrMethod() const {
223 for (const DeclContext *DC = getDeclContext();
224 DC && !DC->isTranslationUnit() && !DC->isNamespace();
225 DC = DC->getParent())
226 if (DC->isFunctionOrMethod())
233 //===----------------------------------------------------------------------===//
234 // PrettyStackTraceDecl Implementation
235 //===----------------------------------------------------------------------===//
237 void PrettyStackTraceDecl::print(raw_ostream &OS) const {
238 SourceLocation TheLoc = Loc;
239 if (TheLoc.isInvalid() && TheDecl)
240 TheLoc = TheDecl->getLocation();
242 if (TheLoc.isValid()) {
243 TheLoc.print(OS, SM);
249 if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
251 DN->printQualifiedName(OS);
257 //===----------------------------------------------------------------------===//
258 // Decl Implementation
259 //===----------------------------------------------------------------------===//
261 // Out-of-line virtual method providing a home for Decl.
264 void Decl::setDeclContext(DeclContext *DC) {
268 void Decl::setLexicalDeclContext(DeclContext *DC) {
269 if (DC == getLexicalDeclContext())
273 setDeclContextsImpl(getDeclContext(), DC, getASTContext());
275 getMultipleDC()->LexicalDC = DC;
278 // FIXME: We shouldn't be changing the lexical context of declarations
279 // imported from AST files.
280 if (!isFromASTFile()) {
281 Hidden = cast<Decl>(DC)->Hidden && hasLocalOwningModuleStorage();
283 setLocalOwningModule(cast<Decl>(DC)->getOwningModule());
286 assert((!Hidden || getOwningModule()) &&
287 "hidden declaration has no owning module");
290 void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
292 if (SemaDC == LexicalDC) {
295 Decl::MultipleDC *MDC = new (Ctx) Decl::MultipleDC();
296 MDC->SemanticDC = SemaDC;
297 MDC->LexicalDC = LexicalDC;
302 bool Decl::isLexicallyWithinFunctionOrMethod() const {
303 const DeclContext *LDC = getLexicalDeclContext();
305 if (LDC->isFunctionOrMethod())
307 if (!isa<TagDecl>(LDC))
309 LDC = LDC->getLexicalParent();
314 bool Decl::isInAnonymousNamespace() const {
315 const DeclContext *DC = getDeclContext();
317 if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
318 if (ND->isAnonymousNamespace())
320 } while ((DC = DC->getParent()));
325 bool Decl::isInStdNamespace() const {
326 return getDeclContext()->isStdNamespace();
329 TranslationUnitDecl *Decl::getTranslationUnitDecl() {
330 if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
333 DeclContext *DC = getDeclContext();
334 assert(DC && "This decl is not contained in a translation unit!");
336 while (!DC->isTranslationUnit()) {
337 DC = DC->getParent();
338 assert(DC && "This decl is not contained in a translation unit!");
341 return cast<TranslationUnitDecl>(DC);
344 ASTContext &Decl::getASTContext() const {
345 return getTranslationUnitDecl()->getASTContext();
348 ASTMutationListener *Decl::getASTMutationListener() const {
349 return getASTContext().getASTMutationListener();
352 unsigned Decl::getMaxAlignment() const {
357 const AttrVec &V = getAttrs();
358 ASTContext &Ctx = getASTContext();
359 specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
361 Align = std::max(Align, I->getAlignment(Ctx));
365 bool Decl::isUsed(bool CheckUsedAttr) const {
366 const Decl *CanonD = getCanonicalDecl();
370 // Check for used attribute.
371 // Ask the most recent decl, since attributes accumulate in the redecl chain.
372 if (CheckUsedAttr && getMostRecentDecl()->hasAttr<UsedAttr>())
375 // The information may have not been deserialized yet. Force deserialization
376 // to complete the needed information.
377 return getMostRecentDecl()->getCanonicalDecl()->Used;
380 void Decl::markUsed(ASTContext &C) {
384 if (C.getASTMutationListener())
385 C.getASTMutationListener()->DeclarationMarkedUsed(this);
390 bool Decl::isReferenced() const {
394 // Check redeclarations.
395 for (auto I : redecls())
402 bool Decl::isExported() const {
403 if (isModulePrivate())
405 // Namespaces are always exported.
406 if (isa<TranslationUnitDecl>(this) || isa<NamespaceDecl>(this))
408 // Otherwise, this is a strictly lexical check.
409 for (auto *DC = getLexicalDeclContext(); DC; DC = DC->getLexicalParent()) {
410 if (cast<Decl>(DC)->isModulePrivate())
412 if (isa<ExportDecl>(DC))
418 ExternalSourceSymbolAttr *Decl::getExternalSourceSymbolAttr() const {
419 const Decl *Definition = nullptr;
420 if (auto ID = dyn_cast<ObjCInterfaceDecl>(this)) {
421 Definition = ID->getDefinition();
422 } else if (auto PD = dyn_cast<ObjCProtocolDecl>(this)) {
423 Definition = PD->getDefinition();
424 } else if (auto TD = dyn_cast<TagDecl>(this)) {
425 Definition = TD->getDefinition();
430 if (auto *attr = Definition->getAttr<ExternalSourceSymbolAttr>())
432 if (auto *dcd = dyn_cast<Decl>(getDeclContext())) {
433 return dcd->getAttr<ExternalSourceSymbolAttr>();
439 bool Decl::hasDefiningAttr() const {
440 return hasAttr<AliasAttr>() || hasAttr<IFuncAttr>();
443 const Attr *Decl::getDefiningAttr() const {
444 if (AliasAttr *AA = getAttr<AliasAttr>())
446 if (IFuncAttr *IFA = getAttr<IFuncAttr>())
451 static StringRef getRealizedPlatform(const AvailabilityAttr *A,
452 const ASTContext &Context) {
453 // Check if this is an App Extension "platform", and if so chop off
454 // the suffix for matching with the actual platform.
455 StringRef RealizedPlatform = A->getPlatform()->getName();
456 if (!Context.getLangOpts().AppExt)
457 return RealizedPlatform;
458 size_t suffix = RealizedPlatform.rfind("_app_extension");
459 if (suffix != StringRef::npos)
460 return RealizedPlatform.slice(0, suffix);
461 return RealizedPlatform;
464 /// \brief Determine the availability of the given declaration based on
465 /// the target platform.
467 /// When it returns an availability result other than \c AR_Available,
468 /// if the \p Message parameter is non-NULL, it will be set to a
469 /// string describing why the entity is unavailable.
471 /// FIXME: Make these strings localizable, since they end up in
473 static AvailabilityResult CheckAvailability(ASTContext &Context,
474 const AvailabilityAttr *A,
475 std::string *Message,
476 VersionTuple EnclosingVersion) {
477 if (EnclosingVersion.empty())
478 EnclosingVersion = Context.getTargetInfo().getPlatformMinVersion();
480 if (EnclosingVersion.empty())
483 StringRef ActualPlatform = A->getPlatform()->getName();
484 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
486 // Match the platform name.
487 if (getRealizedPlatform(A, Context) != TargetPlatform)
490 StringRef PrettyPlatformName
491 = AvailabilityAttr::getPrettyPlatformName(ActualPlatform);
493 if (PrettyPlatformName.empty())
494 PrettyPlatformName = ActualPlatform;
496 std::string HintMessage;
497 if (!A->getMessage().empty()) {
499 HintMessage += A->getMessage();
502 // Make sure that this declaration has not been marked 'unavailable'.
503 if (A->getUnavailable()) {
506 llvm::raw_string_ostream Out(*Message);
507 Out << "not available on " << PrettyPlatformName
511 return AR_Unavailable;
514 // Make sure that this declaration has already been introduced.
515 if (!A->getIntroduced().empty() &&
516 EnclosingVersion < A->getIntroduced()) {
519 llvm::raw_string_ostream Out(*Message);
520 VersionTuple VTI(A->getIntroduced());
521 VTI.UseDotAsSeparator();
522 Out << "introduced in " << PrettyPlatformName << ' '
523 << VTI << HintMessage;
526 return A->getStrict() ? AR_Unavailable : AR_NotYetIntroduced;
529 // Make sure that this declaration hasn't been obsoleted.
530 if (!A->getObsoleted().empty() && EnclosingVersion >= A->getObsoleted()) {
533 llvm::raw_string_ostream Out(*Message);
534 VersionTuple VTO(A->getObsoleted());
535 VTO.UseDotAsSeparator();
536 Out << "obsoleted in " << PrettyPlatformName << ' '
537 << VTO << HintMessage;
540 return AR_Unavailable;
543 // Make sure that this declaration hasn't been deprecated.
544 if (!A->getDeprecated().empty() && EnclosingVersion >= A->getDeprecated()) {
547 llvm::raw_string_ostream Out(*Message);
548 VersionTuple VTD(A->getDeprecated());
549 VTD.UseDotAsSeparator();
550 Out << "first deprecated in " << PrettyPlatformName << ' '
551 << VTD << HintMessage;
554 return AR_Deprecated;
560 AvailabilityResult Decl::getAvailability(std::string *Message,
561 VersionTuple EnclosingVersion) const {
562 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(this))
563 return FTD->getTemplatedDecl()->getAvailability(Message, EnclosingVersion);
565 AvailabilityResult Result = AR_Available;
566 std::string ResultMessage;
568 for (const auto *A : attrs()) {
569 if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
570 if (Result >= AR_Deprecated)
574 ResultMessage = Deprecated->getMessage();
576 Result = AR_Deprecated;
580 if (const auto *Unavailable = dyn_cast<UnavailableAttr>(A)) {
582 *Message = Unavailable->getMessage();
583 return AR_Unavailable;
586 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
587 AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
588 Message, EnclosingVersion);
590 if (AR == AR_Unavailable)
591 return AR_Unavailable;
596 ResultMessage.swap(*Message);
603 Message->swap(ResultMessage);
607 VersionTuple Decl::getVersionIntroduced() const {
608 const ASTContext &Context = getASTContext();
609 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
610 for (const auto *A : attrs()) {
611 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
612 if (getRealizedPlatform(Availability, Context) != TargetPlatform)
614 if (!Availability->getIntroduced().empty())
615 return Availability->getIntroduced();
618 return VersionTuple();
621 bool Decl::canBeWeakImported(bool &IsDefinition) const {
622 IsDefinition = false;
624 // Variables, if they aren't definitions.
625 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
626 if (Var->isThisDeclarationADefinition()) {
632 // Functions, if they aren't definitions.
633 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
640 // Objective-C classes, if this is the non-fragile runtime.
641 } else if (isa<ObjCInterfaceDecl>(this) &&
642 getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
651 bool Decl::isWeakImported() const {
653 if (!canBeWeakImported(IsDefinition))
656 for (const auto *A : attrs()) {
657 if (isa<WeakImportAttr>(A))
660 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
661 if (CheckAvailability(getASTContext(), Availability, nullptr,
662 VersionTuple()) == AR_NotYetIntroduced)
670 unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
673 case CXXDeductionGuide:
676 case ConstructorUsingShadow:
687 return IDNS_Ordinary;
691 return IDNS_Ordinary | IDNS_Member;
693 case NonTypeTemplateParm:
694 // Non-type template parameters are not found by lookups that ignore
695 // non-types, but they are found by redeclaration lookups for tag types,
696 // so we include them in the tag namespace.
697 return IDNS_Ordinary | IDNS_Tag;
699 case ObjCCompatibleAlias:
701 return IDNS_Ordinary | IDNS_Type;
705 case TypeAliasTemplate:
706 case TemplateTypeParm:
708 return IDNS_Ordinary | IDNS_Type;
710 case UnresolvedUsingTypename:
711 return IDNS_Ordinary | IDNS_Type | IDNS_Using;
714 return 0; // we'll actually overwrite this later
716 case UnresolvedUsingValue:
717 return IDNS_Ordinary | IDNS_Using;
724 return IDNS_ObjCProtocol;
727 case ObjCAtDefsField:
734 return IDNS_Tag | IDNS_Type;
738 return IDNS_Namespace;
740 case FunctionTemplate:
742 return IDNS_Ordinary;
745 case TemplateTemplateParm:
746 return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
748 case OMPDeclareReduction:
749 return IDNS_OMPReduction;
759 case ObjCPropertyImpl:
761 case PragmaDetectMismatch:
764 case TranslationUnit:
769 case BuiltinTemplate:
770 case ClassTemplateSpecialization:
771 case ClassTemplatePartialSpecialization:
772 case ClassScopeFunctionSpecialization:
773 case VarTemplateSpecialization:
774 case VarTemplatePartialSpecialization:
775 case ObjCImplementation:
777 case ObjCCategoryImpl:
779 case OMPThreadPrivate:
780 case OMPCapturedExpr:
782 // Never looked up by name.
786 llvm_unreachable("Invalid DeclKind!");
789 void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
790 assert(!HasAttrs && "Decl already contains attrs.");
792 AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
793 assert(AttrBlank.empty() && "HasAttrs was wrong?");
799 void Decl::dropAttrs() {
800 if (!HasAttrs) return;
803 getASTContext().eraseDeclAttrs(this);
806 const AttrVec &Decl::getAttrs() const {
807 assert(HasAttrs && "No attrs to get!");
808 return getASTContext().getDeclAttrs(this);
811 Decl *Decl::castFromDeclContext (const DeclContext *D) {
812 Decl::Kind DK = D->getDeclKind();
814 #define DECL(NAME, BASE)
815 #define DECL_CONTEXT(NAME) \
817 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
818 #define DECL_CONTEXT_BASE(NAME)
819 #include "clang/AST/DeclNodes.inc"
821 #define DECL(NAME, BASE)
822 #define DECL_CONTEXT_BASE(NAME) \
823 if (DK >= first##NAME && DK <= last##NAME) \
824 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
825 #include "clang/AST/DeclNodes.inc"
826 llvm_unreachable("a decl that inherits DeclContext isn't handled");
830 DeclContext *Decl::castToDeclContext(const Decl *D) {
831 Decl::Kind DK = D->getKind();
833 #define DECL(NAME, BASE)
834 #define DECL_CONTEXT(NAME) \
836 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
837 #define DECL_CONTEXT_BASE(NAME)
838 #include "clang/AST/DeclNodes.inc"
840 #define DECL(NAME, BASE)
841 #define DECL_CONTEXT_BASE(NAME) \
842 if (DK >= first##NAME && DK <= last##NAME) \
843 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
844 #include "clang/AST/DeclNodes.inc"
845 llvm_unreachable("a decl that inherits DeclContext isn't handled");
849 SourceLocation Decl::getBodyRBrace() const {
850 // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
851 // FunctionDecl stores EndRangeLoc for this purpose.
852 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
853 const FunctionDecl *Definition;
854 if (FD->hasBody(Definition))
855 return Definition->getSourceRange().getEnd();
856 return SourceLocation();
859 if (Stmt *Body = getBody())
860 return Body->getSourceRange().getEnd();
862 return SourceLocation();
865 bool Decl::AccessDeclContextSanity() const {
867 // Suppress this check if any of the following hold:
868 // 1. this is the translation unit (and thus has no parent)
869 // 2. this is a template parameter (and thus doesn't belong to its context)
870 // 3. this is a non-type template parameter
871 // 4. the context is not a record
873 // 6. it's a C++0x static_assert.
874 if (isa<TranslationUnitDecl>(this) ||
875 isa<TemplateTypeParmDecl>(this) ||
876 isa<NonTypeTemplateParmDecl>(this) ||
877 !isa<CXXRecordDecl>(getDeclContext()) ||
879 isa<StaticAssertDecl>(this) ||
880 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
881 // as DeclContext (?).
882 isa<ParmVarDecl>(this) ||
883 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
884 // AS_none as access specifier.
885 isa<CXXRecordDecl>(this) ||
886 isa<ClassScopeFunctionSpecializationDecl>(this))
889 assert(Access != AS_none &&
890 "Access specifier is AS_none inside a record decl");
895 static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
896 static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
898 const FunctionType *Decl::getFunctionType(bool BlocksToo) const {
900 if (const ValueDecl *D = dyn_cast<ValueDecl>(this))
902 else if (const TypedefNameDecl *D = dyn_cast<TypedefNameDecl>(this))
903 Ty = D->getUnderlyingType();
907 if (Ty->isFunctionPointerType())
908 Ty = Ty->getAs<PointerType>()->getPointeeType();
909 else if (BlocksToo && Ty->isBlockPointerType())
910 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
912 return Ty->getAs<FunctionType>();
916 /// Starting at a given context (a Decl or DeclContext), look for a
917 /// code context that is not a closure (a lambda, block, etc.).
918 template <class T> static Decl *getNonClosureContext(T *D) {
919 if (getKind(D) == Decl::CXXMethod) {
920 CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
921 if (MD->getOverloadedOperator() == OO_Call &&
922 MD->getParent()->isLambda())
923 return getNonClosureContext(MD->getParent()->getParent());
925 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
927 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
929 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
930 return getNonClosureContext(BD->getParent());
931 } else if (CapturedDecl *CD = dyn_cast<CapturedDecl>(D)) {
932 return getNonClosureContext(CD->getParent());
938 Decl *Decl::getNonClosureContext() {
939 return ::getNonClosureContext(this);
942 Decl *DeclContext::getNonClosureAncestor() {
943 return ::getNonClosureContext(this);
946 //===----------------------------------------------------------------------===//
947 // DeclContext Implementation
948 //===----------------------------------------------------------------------===//
950 bool DeclContext::classof(const Decl *D) {
951 switch (D->getKind()) {
952 #define DECL(NAME, BASE)
953 #define DECL_CONTEXT(NAME) case Decl::NAME:
954 #define DECL_CONTEXT_BASE(NAME)
955 #include "clang/AST/DeclNodes.inc"
958 #define DECL(NAME, BASE)
959 #define DECL_CONTEXT_BASE(NAME) \
960 if (D->getKind() >= Decl::first##NAME && \
961 D->getKind() <= Decl::last##NAME) \
963 #include "clang/AST/DeclNodes.inc"
968 DeclContext::~DeclContext() { }
970 /// \brief Find the parent context of this context that will be
971 /// used for unqualified name lookup.
973 /// Generally, the parent lookup context is the semantic context. However, for
974 /// a friend function the parent lookup context is the lexical context, which
975 /// is the class in which the friend is declared.
976 DeclContext *DeclContext::getLookupParent() {
977 // FIXME: Find a better way to identify friends
978 if (isa<FunctionDecl>(this))
979 if (getParent()->getRedeclContext()->isFileContext() &&
980 getLexicalParent()->getRedeclContext()->isRecord())
981 return getLexicalParent();
986 bool DeclContext::isInlineNamespace() const {
987 return isNamespace() &&
988 cast<NamespaceDecl>(this)->isInline();
991 bool DeclContext::isStdNamespace() const {
995 const NamespaceDecl *ND = cast<NamespaceDecl>(this);
996 if (ND->isInline()) {
997 return ND->getParent()->isStdNamespace();
1000 if (!getParent()->getRedeclContext()->isTranslationUnit())
1003 const IdentifierInfo *II = ND->getIdentifier();
1004 return II && II->isStr("std");
1007 bool DeclContext::isDependentContext() const {
1008 if (isFileContext())
1011 if (isa<ClassTemplatePartialSpecializationDecl>(this))
1014 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
1015 if (Record->getDescribedClassTemplate())
1018 if (Record->isDependentLambda())
1022 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
1023 if (Function->getDescribedFunctionTemplate())
1026 // Friend function declarations are dependent if their *lexical*
1027 // context is dependent.
1028 if (cast<Decl>(this)->getFriendObjectKind())
1029 return getLexicalParent()->isDependentContext();
1032 // FIXME: A variable template is a dependent context, but is not a
1033 // DeclContext. A context within it (such as a lambda-expression)
1034 // should be considered dependent.
1036 return getParent() && getParent()->isDependentContext();
1039 bool DeclContext::isTransparentContext() const {
1040 if (DeclKind == Decl::Enum)
1041 return !cast<EnumDecl>(this)->isScoped();
1042 else if (DeclKind == Decl::LinkageSpec || DeclKind == Decl::Export)
1048 static bool isLinkageSpecContext(const DeclContext *DC,
1049 LinkageSpecDecl::LanguageIDs ID) {
1050 while (DC->getDeclKind() != Decl::TranslationUnit) {
1051 if (DC->getDeclKind() == Decl::LinkageSpec)
1052 return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
1053 DC = DC->getLexicalParent();
1058 bool DeclContext::isExternCContext() const {
1059 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_c);
1062 const LinkageSpecDecl *DeclContext::getExternCContext() const {
1063 const DeclContext *DC = this;
1064 while (DC->getDeclKind() != Decl::TranslationUnit) {
1065 if (DC->getDeclKind() == Decl::LinkageSpec &&
1066 cast<LinkageSpecDecl>(DC)->getLanguage() ==
1067 clang::LinkageSpecDecl::lang_c)
1068 return cast<LinkageSpecDecl>(DC);
1069 DC = DC->getLexicalParent();
1074 bool DeclContext::isExternCXXContext() const {
1075 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_cxx);
1078 bool DeclContext::Encloses(const DeclContext *DC) const {
1079 if (getPrimaryContext() != this)
1080 return getPrimaryContext()->Encloses(DC);
1082 for (; DC; DC = DC->getParent())
1083 if (DC->getPrimaryContext() == this)
1088 DeclContext *DeclContext::getPrimaryContext() {
1090 case Decl::TranslationUnit:
1091 case Decl::ExternCContext:
1092 case Decl::LinkageSpec:
1095 case Decl::Captured:
1096 case Decl::OMPDeclareReduction:
1097 // There is only one DeclContext for these entities.
1100 case Decl::Namespace:
1101 // The original namespace is our primary context.
1102 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
1104 case Decl::ObjCMethod:
1107 case Decl::ObjCInterface:
1108 if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
1113 case Decl::ObjCProtocol:
1114 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
1119 case Decl::ObjCCategory:
1122 case Decl::ObjCImplementation:
1123 case Decl::ObjCCategoryImpl:
1127 if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
1128 // If this is a tag type that has a definition or is currently
1129 // being defined, that definition is our primary context.
1130 TagDecl *Tag = cast<TagDecl>(this);
1132 if (TagDecl *Def = Tag->getDefinition())
1135 if (const TagType *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) {
1136 // Note, TagType::getDecl returns the (partial) definition one exists.
1137 TagDecl *PossiblePartialDef = TagTy->getDecl();
1138 if (PossiblePartialDef->isBeingDefined())
1139 return PossiblePartialDef;
1141 assert(isa<InjectedClassNameType>(Tag->getTypeForDecl()));
1147 assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
1148 "Unknown DeclContext kind");
1154 DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
1157 if (DeclKind != Decl::Namespace) {
1158 Contexts.push_back(this);
1162 NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
1163 for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
1164 N = N->getPreviousDecl())
1165 Contexts.push_back(N);
1167 std::reverse(Contexts.begin(), Contexts.end());
1170 std::pair<Decl *, Decl *>
1171 DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
1172 bool FieldsAlreadyLoaded) {
1173 // Build up a chain of declarations via the Decl::NextInContextAndBits field.
1174 Decl *FirstNewDecl = nullptr;
1175 Decl *PrevDecl = nullptr;
1176 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1177 if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
1182 PrevDecl->NextInContextAndBits.setPointer(D);
1189 return std::make_pair(FirstNewDecl, PrevDecl);
1192 /// \brief We have just acquired external visible storage, and we already have
1193 /// built a lookup map. For every name in the map, pull in the new names from
1194 /// the external storage.
1195 void DeclContext::reconcileExternalVisibleStorage() const {
1196 assert(NeedToReconcileExternalVisibleStorage && LookupPtr);
1197 NeedToReconcileExternalVisibleStorage = false;
1199 for (auto &Lookup : *LookupPtr)
1200 Lookup.second.setHasExternalDecls();
1203 /// \brief Load the declarations within this lexical storage from an
1204 /// external source.
1205 /// \return \c true if any declarations were added.
1207 DeclContext::LoadLexicalDeclsFromExternalStorage() const {
1208 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1209 assert(hasExternalLexicalStorage() && Source && "No external storage?");
1211 // Notify that we have a DeclContext that is initializing.
1212 ExternalASTSource::Deserializing ADeclContext(Source);
1214 // Load the external declarations, if any.
1215 SmallVector<Decl*, 64> Decls;
1216 ExternalLexicalStorage = false;
1217 Source->FindExternalLexicalDecls(this, Decls);
1222 // We may have already loaded just the fields of this record, in which case
1223 // we need to ignore them.
1224 bool FieldsAlreadyLoaded = false;
1225 if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
1226 FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
1228 // Splice the newly-read declarations into the beginning of the list
1230 Decl *ExternalFirst, *ExternalLast;
1231 std::tie(ExternalFirst, ExternalLast) =
1232 BuildDeclChain(Decls, FieldsAlreadyLoaded);
1233 ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
1234 FirstDecl = ExternalFirst;
1236 LastDecl = ExternalLast;
1240 DeclContext::lookup_result
1241 ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
1242 DeclarationName Name) {
1243 ASTContext &Context = DC->getParentASTContext();
1244 StoredDeclsMap *Map;
1245 if (!(Map = DC->LookupPtr))
1246 Map = DC->CreateStoredDeclsMap(Context);
1247 if (DC->NeedToReconcileExternalVisibleStorage)
1248 DC->reconcileExternalVisibleStorage();
1250 (*Map)[Name].removeExternalDecls();
1252 return DeclContext::lookup_result();
1255 DeclContext::lookup_result
1256 ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
1257 DeclarationName Name,
1258 ArrayRef<NamedDecl*> Decls) {
1259 ASTContext &Context = DC->getParentASTContext();
1260 StoredDeclsMap *Map;
1261 if (!(Map = DC->LookupPtr))
1262 Map = DC->CreateStoredDeclsMap(Context);
1263 if (DC->NeedToReconcileExternalVisibleStorage)
1264 DC->reconcileExternalVisibleStorage();
1266 StoredDeclsList &List = (*Map)[Name];
1268 // Clear out any old external visible declarations, to avoid quadratic
1269 // performance in the redeclaration checks below.
1270 List.removeExternalDecls();
1272 if (!List.isNull()) {
1273 // We have both existing declarations and new declarations for this name.
1274 // Some of the declarations may simply replace existing ones. Handle those
1276 llvm::SmallVector<unsigned, 8> Skip;
1277 for (unsigned I = 0, N = Decls.size(); I != N; ++I)
1278 if (List.HandleRedeclaration(Decls[I], /*IsKnownNewer*/false))
1280 Skip.push_back(Decls.size());
1282 // Add in any new declarations.
1283 unsigned SkipPos = 0;
1284 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1285 if (I == Skip[SkipPos])
1288 List.AddSubsequentDecl(Decls[I]);
1291 // Convert the array to a StoredDeclsList.
1292 for (ArrayRef<NamedDecl*>::iterator
1293 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1295 List.setOnlyValue(*I);
1297 List.AddSubsequentDecl(*I);
1301 return List.getLookupResult();
1304 DeclContext::decl_iterator DeclContext::decls_begin() const {
1305 if (hasExternalLexicalStorage())
1306 LoadLexicalDeclsFromExternalStorage();
1307 return decl_iterator(FirstDecl);
1310 bool DeclContext::decls_empty() const {
1311 if (hasExternalLexicalStorage())
1312 LoadLexicalDeclsFromExternalStorage();
1317 bool DeclContext::containsDecl(Decl *D) const {
1318 return (D->getLexicalDeclContext() == this &&
1319 (D->NextInContextAndBits.getPointer() || D == LastDecl));
1322 void DeclContext::removeDecl(Decl *D) {
1323 assert(D->getLexicalDeclContext() == this &&
1324 "decl being removed from non-lexical context");
1325 assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
1326 "decl is not in decls list");
1328 // Remove D from the decl chain. This is O(n) but hopefully rare.
1329 if (D == FirstDecl) {
1331 FirstDecl = LastDecl = nullptr;
1333 FirstDecl = D->NextInContextAndBits.getPointer();
1335 for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
1336 assert(I && "decl not found in linked list");
1337 if (I->NextInContextAndBits.getPointer() == D) {
1338 I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
1339 if (D == LastDecl) LastDecl = I;
1345 // Mark that D is no longer in the decl chain.
1346 D->NextInContextAndBits.setPointer(nullptr);
1348 // Remove D from the lookup table if necessary.
1349 if (isa<NamedDecl>(D)) {
1350 NamedDecl *ND = cast<NamedDecl>(D);
1352 // Remove only decls that have a name
1353 if (!ND->getDeclName()) return;
1357 StoredDeclsMap *Map = DC->getPrimaryContext()->LookupPtr;
1359 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1360 assert(Pos != Map->end() && "no lookup entry for decl");
1361 if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
1362 Pos->second.remove(ND);
1364 } while (DC->isTransparentContext() && (DC = DC->getParent()));
1368 void DeclContext::addHiddenDecl(Decl *D) {
1369 assert(D->getLexicalDeclContext() == this &&
1370 "Decl inserted into wrong lexical context");
1371 assert(!D->getNextDeclInContext() && D != LastDecl &&
1372 "Decl already inserted into a DeclContext");
1375 LastDecl->NextInContextAndBits.setPointer(D);
1378 FirstDecl = LastDecl = D;
1381 // Notify a C++ record declaration that we've added a member, so it can
1382 // update its class-specific state.
1383 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1384 Record->addedMember(D);
1386 // If this is a newly-created (not de-serialized) import declaration, wire
1387 // it in to the list of local import declarations.
1388 if (!D->isFromASTFile()) {
1389 if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
1390 D->getASTContext().addedLocalImportDecl(Import);
1394 void DeclContext::addDecl(Decl *D) {
1397 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1398 ND->getDeclContext()->getPrimaryContext()->
1399 makeDeclVisibleInContextWithFlags(ND, false, true);
1402 void DeclContext::addDeclInternal(Decl *D) {
1405 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1406 ND->getDeclContext()->getPrimaryContext()->
1407 makeDeclVisibleInContextWithFlags(ND, true, true);
1410 /// shouldBeHidden - Determine whether a declaration which was declared
1411 /// within its semantic context should be invisible to qualified name lookup.
1412 static bool shouldBeHidden(NamedDecl *D) {
1413 // Skip unnamed declarations.
1414 if (!D->getDeclName())
1417 // Skip entities that can't be found by name lookup into a particular
1419 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1420 D->isTemplateParameter())
1423 // Skip template specializations.
1424 // FIXME: This feels like a hack. Should DeclarationName support
1425 // template-ids, or is there a better way to keep specializations
1426 // from being visible?
1427 if (isa<ClassTemplateSpecializationDecl>(D))
1429 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1430 if (FD->isFunctionTemplateSpecialization())
1436 /// buildLookup - Build the lookup data structure with all of the
1437 /// declarations in this DeclContext (and any other contexts linked
1438 /// to it or transparent contexts nested within it) and return it.
1440 /// Note that the produced map may miss out declarations from an
1441 /// external source. If it does, those entries will be marked with
1442 /// the 'hasExternalDecls' flag.
1443 StoredDeclsMap *DeclContext::buildLookup() {
1444 assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1446 if (!HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups)
1449 SmallVector<DeclContext *, 2> Contexts;
1450 collectAllContexts(Contexts);
1452 if (HasLazyExternalLexicalLookups) {
1453 HasLazyExternalLexicalLookups = false;
1454 for (auto *DC : Contexts) {
1455 if (DC->hasExternalLexicalStorage())
1456 HasLazyLocalLexicalLookups |=
1457 DC->LoadLexicalDeclsFromExternalStorage();
1460 if (!HasLazyLocalLexicalLookups)
1464 for (auto *DC : Contexts)
1465 buildLookupImpl(DC, hasExternalVisibleStorage());
1467 // We no longer have any lazy decls.
1468 HasLazyLocalLexicalLookups = false;
1472 /// buildLookupImpl - Build part of the lookup data structure for the
1473 /// declarations contained within DCtx, which will either be this
1474 /// DeclContext, a DeclContext linked to it, or a transparent context
1475 /// nested within it.
1476 void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {
1477 for (Decl *D : DCtx->noload_decls()) {
1478 // Insert this declaration into the lookup structure, but only if
1479 // it's semantically within its decl context. Any other decls which
1480 // should be found in this context are added eagerly.
1482 // If it's from an AST file, don't add it now. It'll get handled by
1483 // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1484 // in C++, we do not track external visible decls for the TU, so in
1485 // that case we need to collect them all here.
1486 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1487 if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1488 (!ND->isFromASTFile() ||
1489 (isTranslationUnit() &&
1490 !getParentASTContext().getLangOpts().CPlusPlus)))
1491 makeDeclVisibleInContextImpl(ND, Internal);
1493 // If this declaration is itself a transparent declaration context
1494 // or inline namespace, add the members of this declaration of that
1495 // context (recursively).
1496 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
1497 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1498 buildLookupImpl(InnerCtx, Internal);
1502 NamedDecl *const DeclContextLookupResult::SingleElementDummyList = nullptr;
1504 DeclContext::lookup_result
1505 DeclContext::lookup(DeclarationName Name) const {
1506 assert(DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export &&
1507 "should not perform lookups into transparent contexts");
1509 const DeclContext *PrimaryContext = getPrimaryContext();
1510 if (PrimaryContext != this)
1511 return PrimaryContext->lookup(Name);
1513 // If we have an external source, ensure that any later redeclarations of this
1514 // context have been loaded, since they may add names to the result of this
1515 // lookup (or add external visible storage).
1516 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1518 (void)cast<Decl>(this)->getMostRecentDecl();
1520 if (hasExternalVisibleStorage()) {
1521 assert(Source && "external visible storage but no external source?");
1523 if (NeedToReconcileExternalVisibleStorage)
1524 reconcileExternalVisibleStorage();
1526 StoredDeclsMap *Map = LookupPtr;
1528 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
1529 // FIXME: Make buildLookup const?
1530 Map = const_cast<DeclContext*>(this)->buildLookup();
1533 Map = CreateStoredDeclsMap(getParentASTContext());
1535 // If we have a lookup result with no external decls, we are done.
1536 std::pair<StoredDeclsMap::iterator, bool> R =
1537 Map->insert(std::make_pair(Name, StoredDeclsList()));
1538 if (!R.second && !R.first->second.hasExternalDecls())
1539 return R.first->second.getLookupResult();
1541 if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) {
1542 if (StoredDeclsMap *Map = LookupPtr) {
1543 StoredDeclsMap::iterator I = Map->find(Name);
1544 if (I != Map->end())
1545 return I->second.getLookupResult();
1549 return lookup_result();
1552 StoredDeclsMap *Map = LookupPtr;
1553 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
1554 Map = const_cast<DeclContext*>(this)->buildLookup();
1557 return lookup_result();
1559 StoredDeclsMap::iterator I = Map->find(Name);
1560 if (I == Map->end())
1561 return lookup_result();
1563 return I->second.getLookupResult();
1566 DeclContext::lookup_result
1567 DeclContext::noload_lookup(DeclarationName Name) {
1568 assert(DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export &&
1569 "should not perform lookups into transparent contexts");
1571 DeclContext *PrimaryContext = getPrimaryContext();
1572 if (PrimaryContext != this)
1573 return PrimaryContext->noload_lookup(Name);
1575 // If we have any lazy lexical declarations not in our lookup map, add them
1576 // now. Don't import any external declarations, not even if we know we have
1577 // some missing from the external visible lookups.
1578 if (HasLazyLocalLexicalLookups) {
1579 SmallVector<DeclContext *, 2> Contexts;
1580 collectAllContexts(Contexts);
1581 for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
1582 buildLookupImpl(Contexts[I], hasExternalVisibleStorage());
1583 HasLazyLocalLexicalLookups = false;
1586 StoredDeclsMap *Map = LookupPtr;
1588 return lookup_result();
1590 StoredDeclsMap::iterator I = Map->find(Name);
1591 return I != Map->end() ? I->second.getLookupResult()
1595 void DeclContext::localUncachedLookup(DeclarationName Name,
1596 SmallVectorImpl<NamedDecl *> &Results) {
1599 // If there's no external storage, just perform a normal lookup and copy
1601 if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
1602 lookup_result LookupResults = lookup(Name);
1603 Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
1607 // If we have a lookup table, check there first. Maybe we'll get lucky.
1608 // FIXME: Should we be checking these flags on the primary context?
1609 if (Name && !HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups) {
1610 if (StoredDeclsMap *Map = LookupPtr) {
1611 StoredDeclsMap::iterator Pos = Map->find(Name);
1612 if (Pos != Map->end()) {
1613 Results.insert(Results.end(),
1614 Pos->second.getLookupResult().begin(),
1615 Pos->second.getLookupResult().end());
1621 // Slow case: grovel through the declarations in our chain looking for
1623 // FIXME: If we have lazy external declarations, this will not find them!
1624 // FIXME: Should we CollectAllContexts and walk them all here?
1625 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1626 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1627 if (ND->getDeclName() == Name)
1628 Results.push_back(ND);
1632 DeclContext *DeclContext::getRedeclContext() {
1633 DeclContext *Ctx = this;
1634 // Skip through transparent contexts.
1635 while (Ctx->isTransparentContext())
1636 Ctx = Ctx->getParent();
1640 DeclContext *DeclContext::getEnclosingNamespaceContext() {
1641 DeclContext *Ctx = this;
1642 // Skip through non-namespace, non-translation-unit contexts.
1643 while (!Ctx->isFileContext())
1644 Ctx = Ctx->getParent();
1645 return Ctx->getPrimaryContext();
1648 RecordDecl *DeclContext::getOuterLexicalRecordContext() {
1649 // Loop until we find a non-record context.
1650 RecordDecl *OutermostRD = nullptr;
1651 DeclContext *DC = this;
1652 while (DC->isRecord()) {
1653 OutermostRD = cast<RecordDecl>(DC);
1654 DC = DC->getLexicalParent();
1659 bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1660 // For non-file contexts, this is equivalent to Equals.
1661 if (!isFileContext())
1662 return O->Equals(this);
1665 if (O->Equals(this))
1668 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1669 if (!NS || !NS->isInline())
1671 O = NS->getParent();
1677 void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1678 DeclContext *PrimaryDC = this->getPrimaryContext();
1679 DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1680 // If the decl is being added outside of its semantic decl context, we
1681 // need to ensure that we eagerly build the lookup information for it.
1682 PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
1685 void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1687 assert(this == getPrimaryContext() && "expected a primary DC");
1689 if (!isLookupContext()) {
1690 if (isTransparentContext())
1691 getParent()->getPrimaryContext()
1692 ->makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1696 // Skip declarations which should be invisible to name lookup.
1697 if (shouldBeHidden(D))
1700 // If we already have a lookup data structure, perform the insertion into
1701 // it. If we might have externally-stored decls with this name, look them
1702 // up and perform the insertion. If this decl was declared outside its
1703 // semantic context, buildLookup won't add it, so add it now.
1705 // FIXME: As a performance hack, don't add such decls into the translation
1706 // unit unless we're in C++, since qualified lookup into the TU is never
1708 if (LookupPtr || hasExternalVisibleStorage() ||
1709 ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1710 (getParentASTContext().getLangOpts().CPlusPlus ||
1711 !isTranslationUnit()))) {
1712 // If we have lazily omitted any decls, they might have the same name as
1713 // the decl which we are adding, so build a full lookup table before adding
1716 makeDeclVisibleInContextImpl(D, Internal);
1718 HasLazyLocalLexicalLookups = true;
1721 // If we are a transparent context or inline namespace, insert into our
1722 // parent context, too. This operation is recursive.
1723 if (isTransparentContext() || isInlineNamespace())
1724 getParent()->getPrimaryContext()->
1725 makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1727 Decl *DCAsDecl = cast<Decl>(this);
1728 // Notify that a decl was made visible unless we are a Tag being defined.
1729 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1730 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1731 L->AddedVisibleDecl(this, D);
1734 void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1735 // Find or create the stored declaration map.
1736 StoredDeclsMap *Map = LookupPtr;
1738 ASTContext *C = &getParentASTContext();
1739 Map = CreateStoredDeclsMap(*C);
1742 // If there is an external AST source, load any declarations it knows about
1743 // with this declaration's name.
1744 // If the lookup table contains an entry about this name it means that we
1745 // have already checked the external source.
1747 if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1748 if (hasExternalVisibleStorage() &&
1749 Map->find(D->getDeclName()) == Map->end())
1750 Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1752 // Insert this declaration into the map.
1753 StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
1756 // If this is being added as part of loading an external declaration,
1757 // this may not be the only external declaration with this name.
1758 // In this case, we never try to replace an existing declaration; we'll
1759 // handle that when we finalize the list of declarations for this name.
1760 DeclNameEntries.setHasExternalDecls();
1761 DeclNameEntries.AddSubsequentDecl(D);
1765 if (DeclNameEntries.isNull()) {
1766 DeclNameEntries.setOnlyValue(D);
1770 if (DeclNameEntries.HandleRedeclaration(D, /*IsKnownNewer*/!Internal)) {
1771 // This declaration has replaced an existing one for which
1772 // declarationReplaces returns true.
1776 // Put this declaration into the appropriate slot.
1777 DeclNameEntries.AddSubsequentDecl(D);
1780 UsingDirectiveDecl *DeclContext::udir_iterator::operator*() const {
1781 return cast<UsingDirectiveDecl>(*I);
1784 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1786 DeclContext::udir_range DeclContext::using_directives() const {
1787 // FIXME: Use something more efficient than normal lookup for using
1788 // directives. In C++, using directives are looked up more than anything else.
1789 lookup_result Result = lookup(UsingDirectiveDecl::getName());
1790 return udir_range(Result.begin(), Result.end());
1793 //===----------------------------------------------------------------------===//
1794 // Creation and Destruction of StoredDeclsMaps. //
1795 //===----------------------------------------------------------------------===//
1797 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1798 assert(!LookupPtr && "context already has a decls map");
1799 assert(getPrimaryContext() == this &&
1800 "creating decls map on non-primary context");
1803 bool Dependent = isDependentContext();
1805 M = new DependentStoredDeclsMap();
1807 M = new StoredDeclsMap();
1808 M->Previous = C.LastSDM;
1809 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1814 void ASTContext::ReleaseDeclContextMaps() {
1815 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1816 // pointer because the subclass doesn't add anything that needs to
1818 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1821 void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1823 // Advance the iteration before we invalidate memory.
1824 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1827 delete static_cast<DependentStoredDeclsMap*>(Map);
1831 Map = Next.getPointer();
1832 Dependent = Next.getInt();
1836 DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1837 DeclContext *Parent,
1838 const PartialDiagnostic &PDiag) {
1839 assert(Parent->isDependentContext()
1840 && "cannot iterate dependent diagnostics of non-dependent context");
1841 Parent = Parent->getPrimaryContext();
1842 if (!Parent->LookupPtr)
1843 Parent->CreateStoredDeclsMap(C);
1845 DependentStoredDeclsMap *Map =
1846 static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr);
1848 // Allocate the copy of the PartialDiagnostic via the ASTContext's
1849 // BumpPtrAllocator, rather than the ASTContext itself.
1850 PartialDiagnostic::Storage *DiagStorage = nullptr;
1851 if (PDiag.hasStorage())
1852 DiagStorage = new (C) PartialDiagnostic::Storage;
1854 DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
1856 // TODO: Maybe we shouldn't reverse the order during insertion.
1857 DD->NextDiagnostic = Map->FirstDiagnostic;
1858 Map->FirstDiagnostic = DD;