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/ADT/DenseMap.h"
32 #include "llvm/Support/raw_ostream.h"
34 using namespace clang;
36 //===----------------------------------------------------------------------===//
38 //===----------------------------------------------------------------------===//
40 #define DECL(DERIVED, BASE) static int n##DERIVED##s = 0;
41 #define ABSTRACT_DECL(DECL)
42 #include "clang/AST/DeclNodes.inc"
44 void Decl::updateOutOfDate(IdentifierInfo &II) const {
45 getASTContext().getExternalSource()->updateOutOfDateIdentifier(II);
48 void *Decl::operator new(std::size_t Size, const ASTContext &Context,
49 unsigned ID, std::size_t Extra) {
50 // Allocate an extra 8 bytes worth of storage, which ensures that the
51 // resulting pointer will still be 8-byte aligned.
52 void *Start = Context.Allocate(Size + Extra + 8);
53 void *Result = (char*)Start + 8;
55 unsigned *PrefixPtr = (unsigned *)Result - 2;
57 // Zero out the first 4 bytes; this is used to store the owning module ID.
60 // Store the global declaration ID in the second 4 bytes.
66 void *Decl::operator new(std::size_t Size, const ASTContext &Ctx,
67 DeclContext *Parent, std::size_t Extra) {
68 assert(!Parent || &Parent->getParentASTContext() == &Ctx);
69 // With local visibility enabled, we track the owning module even for local
71 if (Ctx.getLangOpts().ModulesLocalVisibility) {
72 void *Buffer = ::operator new(sizeof(Module *) + Size + Extra, Ctx);
73 return new (Buffer) Module*(nullptr) + 1;
75 return ::operator new(Size + Extra, Ctx);
78 Module *Decl::getOwningModuleSlow() const {
79 assert(isFromASTFile() && "Not from AST file?");
80 return getASTContext().getExternalSource()->getModule(getOwningModuleID());
83 bool Decl::hasLocalOwningModuleStorage() const {
84 return getASTContext().getLangOpts().ModulesLocalVisibility;
87 const char *Decl::getDeclKindName() const {
89 default: llvm_unreachable("Declaration not in DeclNodes.inc!");
90 #define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
91 #define ABSTRACT_DECL(DECL)
92 #include "clang/AST/DeclNodes.inc"
96 void Decl::setInvalidDecl(bool Invalid) {
97 InvalidDecl = Invalid;
98 assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition());
99 if (Invalid && !isa<ParmVarDecl>(this)) {
100 // Defensive maneuver for ill-formed code: we're likely not to make it to
101 // a point where we set the access specifier, so default it to "public"
102 // to avoid triggering asserts elsewhere in the front end.
103 setAccess(AS_public);
107 const char *DeclContext::getDeclKindName() const {
109 default: llvm_unreachable("Declaration context not in DeclNodes.inc!");
110 #define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
111 #define ABSTRACT_DECL(DECL)
112 #include "clang/AST/DeclNodes.inc"
116 bool Decl::StatisticsEnabled = false;
117 void Decl::EnableStatistics() {
118 StatisticsEnabled = true;
121 void Decl::PrintStats() {
122 llvm::errs() << "\n*** Decl Stats:\n";
125 #define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
126 #define ABSTRACT_DECL(DECL)
127 #include "clang/AST/DeclNodes.inc"
128 llvm::errs() << " " << totalDecls << " decls total.\n";
131 #define DECL(DERIVED, BASE) \
132 if (n##DERIVED##s > 0) { \
133 totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \
134 llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \
135 << sizeof(DERIVED##Decl) << " each (" \
136 << n##DERIVED##s * sizeof(DERIVED##Decl) \
139 #define ABSTRACT_DECL(DECL)
140 #include "clang/AST/DeclNodes.inc"
142 llvm::errs() << "Total bytes = " << totalBytes << "\n";
145 void Decl::add(Kind k) {
147 #define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
148 #define ABSTRACT_DECL(DECL)
149 #include "clang/AST/DeclNodes.inc"
153 bool Decl::isTemplateParameterPack() const {
154 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
155 return TTP->isParameterPack();
156 if (const NonTypeTemplateParmDecl *NTTP
157 = dyn_cast<NonTypeTemplateParmDecl>(this))
158 return NTTP->isParameterPack();
159 if (const TemplateTemplateParmDecl *TTP
160 = dyn_cast<TemplateTemplateParmDecl>(this))
161 return TTP->isParameterPack();
165 bool Decl::isParameterPack() const {
166 if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this))
167 return Parm->isParameterPack();
169 return isTemplateParameterPack();
172 FunctionDecl *Decl::getAsFunction() {
173 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
175 if (const FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(this))
176 return FTD->getTemplatedDecl();
180 bool Decl::isTemplateDecl() const {
181 return isa<TemplateDecl>(this);
184 const DeclContext *Decl::getParentFunctionOrMethod() const {
185 for (const DeclContext *DC = getDeclContext();
186 DC && !DC->isTranslationUnit() && !DC->isNamespace();
187 DC = DC->getParent())
188 if (DC->isFunctionOrMethod())
195 //===----------------------------------------------------------------------===//
196 // PrettyStackTraceDecl Implementation
197 //===----------------------------------------------------------------------===//
199 void PrettyStackTraceDecl::print(raw_ostream &OS) const {
200 SourceLocation TheLoc = Loc;
201 if (TheLoc.isInvalid() && TheDecl)
202 TheLoc = TheDecl->getLocation();
204 if (TheLoc.isValid()) {
205 TheLoc.print(OS, SM);
211 if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
213 DN->printQualifiedName(OS);
219 //===----------------------------------------------------------------------===//
220 // Decl Implementation
221 //===----------------------------------------------------------------------===//
223 // Out-of-line virtual method providing a home for Decl.
226 void Decl::setDeclContext(DeclContext *DC) {
230 void Decl::setLexicalDeclContext(DeclContext *DC) {
231 if (DC == getLexicalDeclContext())
235 setDeclContextsImpl(getDeclContext(), DC, getASTContext());
237 getMultipleDC()->LexicalDC = DC;
239 Hidden = cast<Decl>(DC)->Hidden;
242 void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
244 if (SemaDC == LexicalDC) {
247 Decl::MultipleDC *MDC = new (Ctx) Decl::MultipleDC();
248 MDC->SemanticDC = SemaDC;
249 MDC->LexicalDC = LexicalDC;
254 bool Decl::isInAnonymousNamespace() const {
255 const DeclContext *DC = getDeclContext();
257 if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
258 if (ND->isAnonymousNamespace())
260 } while ((DC = DC->getParent()));
265 bool Decl::isInStdNamespace() const {
266 return getDeclContext()->isStdNamespace();
269 TranslationUnitDecl *Decl::getTranslationUnitDecl() {
270 if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
273 DeclContext *DC = getDeclContext();
274 assert(DC && "This decl is not contained in a translation unit!");
276 while (!DC->isTranslationUnit()) {
277 DC = DC->getParent();
278 assert(DC && "This decl is not contained in a translation unit!");
281 return cast<TranslationUnitDecl>(DC);
284 ASTContext &Decl::getASTContext() const {
285 return getTranslationUnitDecl()->getASTContext();
288 ASTMutationListener *Decl::getASTMutationListener() const {
289 return getASTContext().getASTMutationListener();
292 unsigned Decl::getMaxAlignment() const {
297 const AttrVec &V = getAttrs();
298 ASTContext &Ctx = getASTContext();
299 specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
301 Align = std::max(Align, I->getAlignment(Ctx));
305 bool Decl::isUsed(bool CheckUsedAttr) const {
309 // Check for used attribute.
310 if (CheckUsedAttr && hasAttr<UsedAttr>())
316 void Decl::markUsed(ASTContext &C) {
320 if (C.getASTMutationListener())
321 C.getASTMutationListener()->DeclarationMarkedUsed(this);
326 bool Decl::isReferenced() const {
330 // Check redeclarations.
331 for (auto I : redecls())
338 /// \brief Determine the availability of the given declaration based on
339 /// the target platform.
341 /// When it returns an availability result other than \c AR_Available,
342 /// if the \p Message parameter is non-NULL, it will be set to a
343 /// string describing why the entity is unavailable.
345 /// FIXME: Make these strings localizable, since they end up in
347 static AvailabilityResult CheckAvailability(ASTContext &Context,
348 const AvailabilityAttr *A,
349 std::string *Message) {
350 VersionTuple TargetMinVersion =
351 Context.getTargetInfo().getPlatformMinVersion();
353 if (TargetMinVersion.empty())
356 // Check if this is an App Extension "platform", and if so chop off
357 // the suffix for matching with the actual platform.
358 StringRef ActualPlatform = A->getPlatform()->getName();
359 StringRef RealizedPlatform = ActualPlatform;
360 if (Context.getLangOpts().AppExt) {
361 size_t suffix = RealizedPlatform.rfind("_app_extension");
362 if (suffix != StringRef::npos)
363 RealizedPlatform = RealizedPlatform.slice(0, suffix);
366 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
368 // Match the platform name.
369 if (RealizedPlatform != TargetPlatform)
372 StringRef PrettyPlatformName
373 = AvailabilityAttr::getPrettyPlatformName(ActualPlatform);
375 if (PrettyPlatformName.empty())
376 PrettyPlatformName = ActualPlatform;
378 std::string HintMessage;
379 if (!A->getMessage().empty()) {
381 HintMessage += A->getMessage();
384 // Make sure that this declaration has not been marked 'unavailable'.
385 if (A->getUnavailable()) {
388 llvm::raw_string_ostream Out(*Message);
389 Out << "not available on " << PrettyPlatformName
393 return AR_Unavailable;
396 // Make sure that this declaration has already been introduced.
397 if (!A->getIntroduced().empty() &&
398 TargetMinVersion < A->getIntroduced()) {
401 llvm::raw_string_ostream Out(*Message);
402 VersionTuple VTI(A->getIntroduced());
403 VTI.UseDotAsSeparator();
404 Out << "introduced in " << PrettyPlatformName << ' '
405 << VTI << HintMessage;
408 return AR_NotYetIntroduced;
411 // Make sure that this declaration hasn't been obsoleted.
412 if (!A->getObsoleted().empty() && TargetMinVersion >= A->getObsoleted()) {
415 llvm::raw_string_ostream Out(*Message);
416 VersionTuple VTO(A->getObsoleted());
417 VTO.UseDotAsSeparator();
418 Out << "obsoleted in " << PrettyPlatformName << ' '
419 << VTO << HintMessage;
422 return AR_Unavailable;
425 // Make sure that this declaration hasn't been deprecated.
426 if (!A->getDeprecated().empty() && TargetMinVersion >= A->getDeprecated()) {
429 llvm::raw_string_ostream Out(*Message);
430 VersionTuple VTD(A->getDeprecated());
431 VTD.UseDotAsSeparator();
432 Out << "first deprecated in " << PrettyPlatformName << ' '
433 << VTD << HintMessage;
436 return AR_Deprecated;
442 AvailabilityResult Decl::getAvailability(std::string *Message) const {
443 AvailabilityResult Result = AR_Available;
444 std::string ResultMessage;
446 for (const auto *A : attrs()) {
447 if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
448 if (Result >= AR_Deprecated)
452 ResultMessage = Deprecated->getMessage();
454 Result = AR_Deprecated;
458 if (const auto *Unavailable = dyn_cast<UnavailableAttr>(A)) {
460 *Message = Unavailable->getMessage();
461 return AR_Unavailable;
464 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
465 AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
468 if (AR == AR_Unavailable)
469 return AR_Unavailable;
474 ResultMessage.swap(*Message);
481 Message->swap(ResultMessage);
485 bool Decl::canBeWeakImported(bool &IsDefinition) const {
486 IsDefinition = false;
488 // Variables, if they aren't definitions.
489 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
490 if (Var->isThisDeclarationADefinition()) {
496 // Functions, if they aren't definitions.
497 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
504 // Objective-C classes, if this is the non-fragile runtime.
505 } else if (isa<ObjCInterfaceDecl>(this) &&
506 getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
515 bool Decl::isWeakImported() const {
517 if (!canBeWeakImported(IsDefinition))
520 for (const auto *A : attrs()) {
521 if (isa<WeakImportAttr>(A))
524 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
525 if (CheckAvailability(getASTContext(), Availability,
526 nullptr) == AR_NotYetIntroduced)
534 unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
545 case NonTypeTemplateParm:
549 return IDNS_Ordinary;
553 return IDNS_Ordinary | IDNS_Member;
555 case ObjCCompatibleAlias:
557 return IDNS_Ordinary | IDNS_Type;
561 case TypeAliasTemplate:
562 case UnresolvedUsingTypename:
563 case TemplateTypeParm:
564 return IDNS_Ordinary | IDNS_Type;
567 return 0; // we'll actually overwrite this later
569 case UnresolvedUsingValue:
570 return IDNS_Ordinary | IDNS_Using;
576 return IDNS_ObjCProtocol;
579 case ObjCAtDefsField:
586 return IDNS_Tag | IDNS_Type;
590 return IDNS_Namespace;
592 case FunctionTemplate:
594 return IDNS_Ordinary;
597 case TemplateTemplateParm:
598 return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
607 case ObjCPropertyImpl:
610 case TranslationUnit:
614 case ClassTemplateSpecialization:
615 case ClassTemplatePartialSpecialization:
616 case ClassScopeFunctionSpecialization:
617 case VarTemplateSpecialization:
618 case VarTemplatePartialSpecialization:
619 case ObjCImplementation:
621 case ObjCCategoryImpl:
623 case OMPThreadPrivate:
625 // Never looked up by name.
629 llvm_unreachable("Invalid DeclKind!");
632 void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
633 assert(!HasAttrs && "Decl already contains attrs.");
635 AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
636 assert(AttrBlank.empty() && "HasAttrs was wrong?");
642 void Decl::dropAttrs() {
643 if (!HasAttrs) return;
646 getASTContext().eraseDeclAttrs(this);
649 const AttrVec &Decl::getAttrs() const {
650 assert(HasAttrs && "No attrs to get!");
651 return getASTContext().getDeclAttrs(this);
654 Decl *Decl::castFromDeclContext (const DeclContext *D) {
655 Decl::Kind DK = D->getDeclKind();
657 #define DECL(NAME, BASE)
658 #define DECL_CONTEXT(NAME) \
660 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
661 #define DECL_CONTEXT_BASE(NAME)
662 #include "clang/AST/DeclNodes.inc"
664 #define DECL(NAME, BASE)
665 #define DECL_CONTEXT_BASE(NAME) \
666 if (DK >= first##NAME && DK <= last##NAME) \
667 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
668 #include "clang/AST/DeclNodes.inc"
669 llvm_unreachable("a decl that inherits DeclContext isn't handled");
673 DeclContext *Decl::castToDeclContext(const Decl *D) {
674 Decl::Kind DK = D->getKind();
676 #define DECL(NAME, BASE)
677 #define DECL_CONTEXT(NAME) \
679 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
680 #define DECL_CONTEXT_BASE(NAME)
681 #include "clang/AST/DeclNodes.inc"
683 #define DECL(NAME, BASE)
684 #define DECL_CONTEXT_BASE(NAME) \
685 if (DK >= first##NAME && DK <= last##NAME) \
686 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
687 #include "clang/AST/DeclNodes.inc"
688 llvm_unreachable("a decl that inherits DeclContext isn't handled");
692 SourceLocation Decl::getBodyRBrace() const {
693 // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
694 // FunctionDecl stores EndRangeLoc for this purpose.
695 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
696 const FunctionDecl *Definition;
697 if (FD->hasBody(Definition))
698 return Definition->getSourceRange().getEnd();
699 return SourceLocation();
702 if (Stmt *Body = getBody())
703 return Body->getSourceRange().getEnd();
705 return SourceLocation();
708 bool Decl::AccessDeclContextSanity() const {
710 // Suppress this check if any of the following hold:
711 // 1. this is the translation unit (and thus has no parent)
712 // 2. this is a template parameter (and thus doesn't belong to its context)
713 // 3. this is a non-type template parameter
714 // 4. the context is not a record
716 // 6. it's a C++0x static_assert.
717 if (isa<TranslationUnitDecl>(this) ||
718 isa<TemplateTypeParmDecl>(this) ||
719 isa<NonTypeTemplateParmDecl>(this) ||
720 !isa<CXXRecordDecl>(getDeclContext()) ||
722 isa<StaticAssertDecl>(this) ||
723 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
724 // as DeclContext (?).
725 isa<ParmVarDecl>(this) ||
726 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
727 // AS_none as access specifier.
728 isa<CXXRecordDecl>(this) ||
729 isa<ClassScopeFunctionSpecializationDecl>(this))
732 assert(Access != AS_none &&
733 "Access specifier is AS_none inside a record decl");
738 static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
739 static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
741 const FunctionType *Decl::getFunctionType(bool BlocksToo) const {
743 if (const ValueDecl *D = dyn_cast<ValueDecl>(this))
745 else if (const TypedefNameDecl *D = dyn_cast<TypedefNameDecl>(this))
746 Ty = D->getUnderlyingType();
750 if (Ty->isFunctionPointerType())
751 Ty = Ty->getAs<PointerType>()->getPointeeType();
752 else if (BlocksToo && Ty->isBlockPointerType())
753 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
755 return Ty->getAs<FunctionType>();
759 /// Starting at a given context (a Decl or DeclContext), look for a
760 /// code context that is not a closure (a lambda, block, etc.).
761 template <class T> static Decl *getNonClosureContext(T *D) {
762 if (getKind(D) == Decl::CXXMethod) {
763 CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
764 if (MD->getOverloadedOperator() == OO_Call &&
765 MD->getParent()->isLambda())
766 return getNonClosureContext(MD->getParent()->getParent());
768 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
770 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
772 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
773 return getNonClosureContext(BD->getParent());
774 } else if (CapturedDecl *CD = dyn_cast<CapturedDecl>(D)) {
775 return getNonClosureContext(CD->getParent());
781 Decl *Decl::getNonClosureContext() {
782 return ::getNonClosureContext(this);
785 Decl *DeclContext::getNonClosureAncestor() {
786 return ::getNonClosureContext(this);
789 //===----------------------------------------------------------------------===//
790 // DeclContext Implementation
791 //===----------------------------------------------------------------------===//
793 bool DeclContext::classof(const Decl *D) {
794 switch (D->getKind()) {
795 #define DECL(NAME, BASE)
796 #define DECL_CONTEXT(NAME) case Decl::NAME:
797 #define DECL_CONTEXT_BASE(NAME)
798 #include "clang/AST/DeclNodes.inc"
801 #define DECL(NAME, BASE)
802 #define DECL_CONTEXT_BASE(NAME) \
803 if (D->getKind() >= Decl::first##NAME && \
804 D->getKind() <= Decl::last##NAME) \
806 #include "clang/AST/DeclNodes.inc"
811 DeclContext::~DeclContext() { }
813 /// \brief Find the parent context of this context that will be
814 /// used for unqualified name lookup.
816 /// Generally, the parent lookup context is the semantic context. However, for
817 /// a friend function the parent lookup context is the lexical context, which
818 /// is the class in which the friend is declared.
819 DeclContext *DeclContext::getLookupParent() {
820 // FIXME: Find a better way to identify friends
821 if (isa<FunctionDecl>(this))
822 if (getParent()->getRedeclContext()->isFileContext() &&
823 getLexicalParent()->getRedeclContext()->isRecord())
824 return getLexicalParent();
829 bool DeclContext::isInlineNamespace() const {
830 return isNamespace() &&
831 cast<NamespaceDecl>(this)->isInline();
834 bool DeclContext::isStdNamespace() const {
838 const NamespaceDecl *ND = cast<NamespaceDecl>(this);
839 if (ND->isInline()) {
840 return ND->getParent()->isStdNamespace();
843 if (!getParent()->getRedeclContext()->isTranslationUnit())
846 const IdentifierInfo *II = ND->getIdentifier();
847 return II && II->isStr("std");
850 bool DeclContext::isDependentContext() const {
854 if (isa<ClassTemplatePartialSpecializationDecl>(this))
857 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
858 if (Record->getDescribedClassTemplate())
861 if (Record->isDependentLambda())
865 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
866 if (Function->getDescribedFunctionTemplate())
869 // Friend function declarations are dependent if their *lexical*
870 // context is dependent.
871 if (cast<Decl>(this)->getFriendObjectKind())
872 return getLexicalParent()->isDependentContext();
875 // FIXME: A variable template is a dependent context, but is not a
876 // DeclContext. A context within it (such as a lambda-expression)
877 // should be considered dependent.
879 return getParent() && getParent()->isDependentContext();
882 bool DeclContext::isTransparentContext() const {
883 if (DeclKind == Decl::Enum)
884 return !cast<EnumDecl>(this)->isScoped();
885 else if (DeclKind == Decl::LinkageSpec)
891 static bool isLinkageSpecContext(const DeclContext *DC,
892 LinkageSpecDecl::LanguageIDs ID) {
893 while (DC->getDeclKind() != Decl::TranslationUnit) {
894 if (DC->getDeclKind() == Decl::LinkageSpec)
895 return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
896 DC = DC->getLexicalParent();
901 bool DeclContext::isExternCContext() const {
902 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_c);
905 bool DeclContext::isExternCXXContext() const {
906 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_cxx);
909 bool DeclContext::Encloses(const DeclContext *DC) const {
910 if (getPrimaryContext() != this)
911 return getPrimaryContext()->Encloses(DC);
913 for (; DC; DC = DC->getParent())
914 if (DC->getPrimaryContext() == this)
919 DeclContext *DeclContext::getPrimaryContext() {
921 case Decl::TranslationUnit:
922 case Decl::ExternCContext:
923 case Decl::LinkageSpec:
926 // There is only one DeclContext for these entities.
929 case Decl::Namespace:
930 // The original namespace is our primary context.
931 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
933 case Decl::ObjCMethod:
936 case Decl::ObjCInterface:
937 if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
942 case Decl::ObjCProtocol:
943 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
948 case Decl::ObjCCategory:
951 case Decl::ObjCImplementation:
952 case Decl::ObjCCategoryImpl:
956 if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
957 // If this is a tag type that has a definition or is currently
958 // being defined, that definition is our primary context.
959 TagDecl *Tag = cast<TagDecl>(this);
961 if (TagDecl *Def = Tag->getDefinition())
964 if (const TagType *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) {
965 // Note, TagType::getDecl returns the (partial) definition one exists.
966 TagDecl *PossiblePartialDef = TagTy->getDecl();
967 if (PossiblePartialDef->isBeingDefined())
968 return PossiblePartialDef;
970 assert(isa<InjectedClassNameType>(Tag->getTypeForDecl()));
976 assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
977 "Unknown DeclContext kind");
983 DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
986 if (DeclKind != Decl::Namespace) {
987 Contexts.push_back(this);
991 NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
992 for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
993 N = N->getPreviousDecl())
994 Contexts.push_back(N);
996 std::reverse(Contexts.begin(), Contexts.end());
999 std::pair<Decl *, Decl *>
1000 DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
1001 bool FieldsAlreadyLoaded) {
1002 // Build up a chain of declarations via the Decl::NextInContextAndBits field.
1003 Decl *FirstNewDecl = nullptr;
1004 Decl *PrevDecl = nullptr;
1005 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1006 if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
1011 PrevDecl->NextInContextAndBits.setPointer(D);
1018 return std::make_pair(FirstNewDecl, PrevDecl);
1021 /// \brief We have just acquired external visible storage, and we already have
1022 /// built a lookup map. For every name in the map, pull in the new names from
1023 /// the external storage.
1024 void DeclContext::reconcileExternalVisibleStorage() const {
1025 assert(NeedToReconcileExternalVisibleStorage && LookupPtr);
1026 NeedToReconcileExternalVisibleStorage = false;
1028 for (auto &Lookup : *LookupPtr)
1029 Lookup.second.setHasExternalDecls();
1032 /// \brief Load the declarations within this lexical storage from an
1033 /// external source.
1034 /// \return \c true if any declarations were added.
1036 DeclContext::LoadLexicalDeclsFromExternalStorage() const {
1037 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1038 assert(hasExternalLexicalStorage() && Source && "No external storage?");
1040 // Notify that we have a DeclContext that is initializing.
1041 ExternalASTSource::Deserializing ADeclContext(Source);
1043 // Load the external declarations, if any.
1044 SmallVector<Decl*, 64> Decls;
1045 ExternalLexicalStorage = false;
1046 switch (Source->FindExternalLexicalDecls(this, Decls)) {
1051 case ELR_AlreadyLoaded:
1058 // We may have already loaded just the fields of this record, in which case
1059 // we need to ignore them.
1060 bool FieldsAlreadyLoaded = false;
1061 if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
1062 FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
1064 // Splice the newly-read declarations into the beginning of the list
1066 Decl *ExternalFirst, *ExternalLast;
1067 std::tie(ExternalFirst, ExternalLast) =
1068 BuildDeclChain(Decls, FieldsAlreadyLoaded);
1069 ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
1070 FirstDecl = ExternalFirst;
1072 LastDecl = ExternalLast;
1076 DeclContext::lookup_result
1077 ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
1078 DeclarationName Name) {
1079 ASTContext &Context = DC->getParentASTContext();
1080 StoredDeclsMap *Map;
1081 if (!(Map = DC->LookupPtr))
1082 Map = DC->CreateStoredDeclsMap(Context);
1083 if (DC->NeedToReconcileExternalVisibleStorage)
1084 DC->reconcileExternalVisibleStorage();
1086 (*Map)[Name].removeExternalDecls();
1088 return DeclContext::lookup_result();
1091 DeclContext::lookup_result
1092 ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
1093 DeclarationName Name,
1094 ArrayRef<NamedDecl*> Decls) {
1095 ASTContext &Context = DC->getParentASTContext();
1096 StoredDeclsMap *Map;
1097 if (!(Map = DC->LookupPtr))
1098 Map = DC->CreateStoredDeclsMap(Context);
1099 if (DC->NeedToReconcileExternalVisibleStorage)
1100 DC->reconcileExternalVisibleStorage();
1102 StoredDeclsList &List = (*Map)[Name];
1104 // Clear out any old external visible declarations, to avoid quadratic
1105 // performance in the redeclaration checks below.
1106 List.removeExternalDecls();
1108 if (!List.isNull()) {
1109 // We have both existing declarations and new declarations for this name.
1110 // Some of the declarations may simply replace existing ones. Handle those
1112 llvm::SmallVector<unsigned, 8> Skip;
1113 for (unsigned I = 0, N = Decls.size(); I != N; ++I)
1114 if (List.HandleRedeclaration(Decls[I], /*IsKnownNewer*/false))
1116 Skip.push_back(Decls.size());
1118 // Add in any new declarations.
1119 unsigned SkipPos = 0;
1120 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1121 if (I == Skip[SkipPos])
1124 List.AddSubsequentDecl(Decls[I]);
1127 // Convert the array to a StoredDeclsList.
1128 for (ArrayRef<NamedDecl*>::iterator
1129 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1131 List.setOnlyValue(*I);
1133 List.AddSubsequentDecl(*I);
1137 return List.getLookupResult();
1140 DeclContext::decl_iterator DeclContext::decls_begin() const {
1141 if (hasExternalLexicalStorage())
1142 LoadLexicalDeclsFromExternalStorage();
1143 return decl_iterator(FirstDecl);
1146 bool DeclContext::decls_empty() const {
1147 if (hasExternalLexicalStorage())
1148 LoadLexicalDeclsFromExternalStorage();
1153 bool DeclContext::containsDecl(Decl *D) const {
1154 return (D->getLexicalDeclContext() == this &&
1155 (D->NextInContextAndBits.getPointer() || D == LastDecl));
1158 void DeclContext::removeDecl(Decl *D) {
1159 assert(D->getLexicalDeclContext() == this &&
1160 "decl being removed from non-lexical context");
1161 assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
1162 "decl is not in decls list");
1164 // Remove D from the decl chain. This is O(n) but hopefully rare.
1165 if (D == FirstDecl) {
1167 FirstDecl = LastDecl = nullptr;
1169 FirstDecl = D->NextInContextAndBits.getPointer();
1171 for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
1172 assert(I && "decl not found in linked list");
1173 if (I->NextInContextAndBits.getPointer() == D) {
1174 I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
1175 if (D == LastDecl) LastDecl = I;
1181 // Mark that D is no longer in the decl chain.
1182 D->NextInContextAndBits.setPointer(nullptr);
1184 // Remove D from the lookup table if necessary.
1185 if (isa<NamedDecl>(D)) {
1186 NamedDecl *ND = cast<NamedDecl>(D);
1188 // Remove only decls that have a name
1189 if (!ND->getDeclName()) return;
1191 StoredDeclsMap *Map = getPrimaryContext()->LookupPtr;
1194 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1195 assert(Pos != Map->end() && "no lookup entry for decl");
1196 if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
1197 Pos->second.remove(ND);
1201 void DeclContext::addHiddenDecl(Decl *D) {
1202 assert(D->getLexicalDeclContext() == this &&
1203 "Decl inserted into wrong lexical context");
1204 assert(!D->getNextDeclInContext() && D != LastDecl &&
1205 "Decl already inserted into a DeclContext");
1208 LastDecl->NextInContextAndBits.setPointer(D);
1211 FirstDecl = LastDecl = D;
1214 // Notify a C++ record declaration that we've added a member, so it can
1215 // update it's class-specific state.
1216 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1217 Record->addedMember(D);
1219 // If this is a newly-created (not de-serialized) import declaration, wire
1220 // it in to the list of local import declarations.
1221 if (!D->isFromASTFile()) {
1222 if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
1223 D->getASTContext().addedLocalImportDecl(Import);
1227 void DeclContext::addDecl(Decl *D) {
1230 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1231 ND->getDeclContext()->getPrimaryContext()->
1232 makeDeclVisibleInContextWithFlags(ND, false, true);
1235 void DeclContext::addDeclInternal(Decl *D) {
1238 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1239 ND->getDeclContext()->getPrimaryContext()->
1240 makeDeclVisibleInContextWithFlags(ND, true, true);
1243 /// shouldBeHidden - Determine whether a declaration which was declared
1244 /// within its semantic context should be invisible to qualified name lookup.
1245 static bool shouldBeHidden(NamedDecl *D) {
1246 // Skip unnamed declarations.
1247 if (!D->getDeclName())
1250 // Skip entities that can't be found by name lookup into a particular
1252 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1253 D->isTemplateParameter())
1256 // Skip template specializations.
1257 // FIXME: This feels like a hack. Should DeclarationName support
1258 // template-ids, or is there a better way to keep specializations
1259 // from being visible?
1260 if (isa<ClassTemplateSpecializationDecl>(D))
1262 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1263 if (FD->isFunctionTemplateSpecialization())
1269 /// buildLookup - Build the lookup data structure with all of the
1270 /// declarations in this DeclContext (and any other contexts linked
1271 /// to it or transparent contexts nested within it) and return it.
1273 /// Note that the produced map may miss out declarations from an
1274 /// external source. If it does, those entries will be marked with
1275 /// the 'hasExternalDecls' flag.
1276 StoredDeclsMap *DeclContext::buildLookup() {
1277 assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1279 if (!HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups)
1282 SmallVector<DeclContext *, 2> Contexts;
1283 collectAllContexts(Contexts);
1285 if (HasLazyExternalLexicalLookups) {
1286 HasLazyExternalLexicalLookups = false;
1287 for (auto *DC : Contexts) {
1288 if (DC->hasExternalLexicalStorage())
1289 HasLazyLocalLexicalLookups |=
1290 DC->LoadLexicalDeclsFromExternalStorage();
1293 if (!HasLazyLocalLexicalLookups)
1297 for (auto *DC : Contexts)
1298 buildLookupImpl(DC, hasExternalVisibleStorage());
1300 // We no longer have any lazy decls.
1301 HasLazyLocalLexicalLookups = false;
1305 /// buildLookupImpl - Build part of the lookup data structure for the
1306 /// declarations contained within DCtx, which will either be this
1307 /// DeclContext, a DeclContext linked to it, or a transparent context
1308 /// nested within it.
1309 void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {
1310 for (Decl *D : DCtx->noload_decls()) {
1311 // Insert this declaration into the lookup structure, but only if
1312 // it's semantically within its decl context. Any other decls which
1313 // should be found in this context are added eagerly.
1315 // If it's from an AST file, don't add it now. It'll get handled by
1316 // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1317 // in C++, we do not track external visible decls for the TU, so in
1318 // that case we need to collect them all here.
1319 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1320 if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1321 (!ND->isFromASTFile() ||
1322 (isTranslationUnit() &&
1323 !getParentASTContext().getLangOpts().CPlusPlus)))
1324 makeDeclVisibleInContextImpl(ND, Internal);
1326 // If this declaration is itself a transparent declaration context
1327 // or inline namespace, add the members of this declaration of that
1328 // context (recursively).
1329 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
1330 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1331 buildLookupImpl(InnerCtx, Internal);
1335 NamedDecl *const DeclContextLookupResult::SingleElementDummyList = nullptr;
1337 DeclContext::lookup_result
1338 DeclContext::lookup(DeclarationName Name) const {
1339 assert(DeclKind != Decl::LinkageSpec &&
1340 "Should not perform lookups into linkage specs!");
1342 const DeclContext *PrimaryContext = getPrimaryContext();
1343 if (PrimaryContext != this)
1344 return PrimaryContext->lookup(Name);
1346 // If we have an external source, ensure that any later redeclarations of this
1347 // context have been loaded, since they may add names to the result of this
1348 // lookup (or add external visible storage).
1349 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1351 (void)cast<Decl>(this)->getMostRecentDecl();
1353 if (hasExternalVisibleStorage()) {
1354 assert(Source && "external visible storage but no external source?");
1356 if (NeedToReconcileExternalVisibleStorage)
1357 reconcileExternalVisibleStorage();
1359 StoredDeclsMap *Map = LookupPtr;
1361 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
1362 // FIXME: Make buildLookup const?
1363 Map = const_cast<DeclContext*>(this)->buildLookup();
1366 Map = CreateStoredDeclsMap(getParentASTContext());
1368 // If we have a lookup result with no external decls, we are done.
1369 std::pair<StoredDeclsMap::iterator, bool> R =
1370 Map->insert(std::make_pair(Name, StoredDeclsList()));
1371 if (!R.second && !R.first->second.hasExternalDecls())
1372 return R.first->second.getLookupResult();
1374 if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) {
1375 if (StoredDeclsMap *Map = LookupPtr) {
1376 StoredDeclsMap::iterator I = Map->find(Name);
1377 if (I != Map->end())
1378 return I->second.getLookupResult();
1382 return lookup_result();
1385 StoredDeclsMap *Map = LookupPtr;
1386 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
1387 Map = const_cast<DeclContext*>(this)->buildLookup();
1390 return lookup_result();
1392 StoredDeclsMap::iterator I = Map->find(Name);
1393 if (I == Map->end())
1394 return lookup_result();
1396 return I->second.getLookupResult();
1399 DeclContext::lookup_result
1400 DeclContext::noload_lookup(DeclarationName Name) {
1401 assert(DeclKind != Decl::LinkageSpec &&
1402 "Should not perform lookups into linkage specs!");
1404 DeclContext *PrimaryContext = getPrimaryContext();
1405 if (PrimaryContext != this)
1406 return PrimaryContext->noload_lookup(Name);
1408 // If we have any lazy lexical declarations not in our lookup map, add them
1409 // now. Don't import any external declarations, not even if we know we have
1410 // some missing from the external visible lookups.
1411 if (HasLazyLocalLexicalLookups) {
1412 SmallVector<DeclContext *, 2> Contexts;
1413 collectAllContexts(Contexts);
1414 for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
1415 buildLookupImpl(Contexts[I], hasExternalVisibleStorage());
1416 HasLazyLocalLexicalLookups = false;
1419 StoredDeclsMap *Map = LookupPtr;
1421 return lookup_result();
1423 StoredDeclsMap::iterator I = Map->find(Name);
1424 return I != Map->end() ? I->second.getLookupResult()
1428 void DeclContext::localUncachedLookup(DeclarationName Name,
1429 SmallVectorImpl<NamedDecl *> &Results) {
1432 // If there's no external storage, just perform a normal lookup and copy
1434 if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
1435 lookup_result LookupResults = lookup(Name);
1436 Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
1440 // If we have a lookup table, check there first. Maybe we'll get lucky.
1441 // FIXME: Should we be checking these flags on the primary context?
1442 if (Name && !HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups) {
1443 if (StoredDeclsMap *Map = LookupPtr) {
1444 StoredDeclsMap::iterator Pos = Map->find(Name);
1445 if (Pos != Map->end()) {
1446 Results.insert(Results.end(),
1447 Pos->second.getLookupResult().begin(),
1448 Pos->second.getLookupResult().end());
1454 // Slow case: grovel through the declarations in our chain looking for
1456 // FIXME: If we have lazy external declarations, this will not find them!
1457 // FIXME: Should we CollectAllContexts and walk them all here?
1458 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1459 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1460 if (ND->getDeclName() == Name)
1461 Results.push_back(ND);
1465 DeclContext *DeclContext::getRedeclContext() {
1466 DeclContext *Ctx = this;
1467 // Skip through transparent contexts.
1468 while (Ctx->isTransparentContext())
1469 Ctx = Ctx->getParent();
1473 DeclContext *DeclContext::getEnclosingNamespaceContext() {
1474 DeclContext *Ctx = this;
1475 // Skip through non-namespace, non-translation-unit contexts.
1476 while (!Ctx->isFileContext())
1477 Ctx = Ctx->getParent();
1478 return Ctx->getPrimaryContext();
1481 RecordDecl *DeclContext::getOuterLexicalRecordContext() {
1482 // Loop until we find a non-record context.
1483 RecordDecl *OutermostRD = nullptr;
1484 DeclContext *DC = this;
1485 while (DC->isRecord()) {
1486 OutermostRD = cast<RecordDecl>(DC);
1487 DC = DC->getLexicalParent();
1492 bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1493 // For non-file contexts, this is equivalent to Equals.
1494 if (!isFileContext())
1495 return O->Equals(this);
1498 if (O->Equals(this))
1501 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1502 if (!NS || !NS->isInline())
1504 O = NS->getParent();
1510 void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1511 DeclContext *PrimaryDC = this->getPrimaryContext();
1512 DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1513 // If the decl is being added outside of its semantic decl context, we
1514 // need to ensure that we eagerly build the lookup information for it.
1515 PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
1518 void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1520 assert(this == getPrimaryContext() && "expected a primary DC");
1522 // Skip declarations within functions.
1523 if (isFunctionOrMethod())
1526 // Skip declarations which should be invisible to name lookup.
1527 if (shouldBeHidden(D))
1530 // If we already have a lookup data structure, perform the insertion into
1531 // it. If we might have externally-stored decls with this name, look them
1532 // up and perform the insertion. If this decl was declared outside its
1533 // semantic context, buildLookup won't add it, so add it now.
1535 // FIXME: As a performance hack, don't add such decls into the translation
1536 // unit unless we're in C++, since qualified lookup into the TU is never
1538 if (LookupPtr || hasExternalVisibleStorage() ||
1539 ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1540 (getParentASTContext().getLangOpts().CPlusPlus ||
1541 !isTranslationUnit()))) {
1542 // If we have lazily omitted any decls, they might have the same name as
1543 // the decl which we are adding, so build a full lookup table before adding
1546 makeDeclVisibleInContextImpl(D, Internal);
1548 HasLazyLocalLexicalLookups = true;
1551 // If we are a transparent context or inline namespace, insert into our
1552 // parent context, too. This operation is recursive.
1553 if (isTransparentContext() || isInlineNamespace())
1554 getParent()->getPrimaryContext()->
1555 makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1557 Decl *DCAsDecl = cast<Decl>(this);
1558 // Notify that a decl was made visible unless we are a Tag being defined.
1559 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1560 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1561 L->AddedVisibleDecl(this, D);
1564 void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1565 // Find or create the stored declaration map.
1566 StoredDeclsMap *Map = LookupPtr;
1568 ASTContext *C = &getParentASTContext();
1569 Map = CreateStoredDeclsMap(*C);
1572 // If there is an external AST source, load any declarations it knows about
1573 // with this declaration's name.
1574 // If the lookup table contains an entry about this name it means that we
1575 // have already checked the external source.
1577 if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1578 if (hasExternalVisibleStorage() &&
1579 Map->find(D->getDeclName()) == Map->end())
1580 Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1582 // Insert this declaration into the map.
1583 StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
1586 // If this is being added as part of loading an external declaration,
1587 // this may not be the only external declaration with this name.
1588 // In this case, we never try to replace an existing declaration; we'll
1589 // handle that when we finalize the list of declarations for this name.
1590 DeclNameEntries.setHasExternalDecls();
1591 DeclNameEntries.AddSubsequentDecl(D);
1595 if (DeclNameEntries.isNull()) {
1596 DeclNameEntries.setOnlyValue(D);
1600 if (DeclNameEntries.HandleRedeclaration(D, /*IsKnownNewer*/!Internal)) {
1601 // This declaration has replaced an existing one for which
1602 // declarationReplaces returns true.
1606 // Put this declaration into the appropriate slot.
1607 DeclNameEntries.AddSubsequentDecl(D);
1610 UsingDirectiveDecl *DeclContext::udir_iterator::operator*() const {
1611 return cast<UsingDirectiveDecl>(*I);
1614 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1616 DeclContext::udir_range DeclContext::using_directives() const {
1617 // FIXME: Use something more efficient than normal lookup for using
1618 // directives. In C++, using directives are looked up more than anything else.
1619 lookup_result Result = lookup(UsingDirectiveDecl::getName());
1620 return udir_range(Result.begin(), Result.end());
1623 //===----------------------------------------------------------------------===//
1624 // Creation and Destruction of StoredDeclsMaps. //
1625 //===----------------------------------------------------------------------===//
1627 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1628 assert(!LookupPtr && "context already has a decls map");
1629 assert(getPrimaryContext() == this &&
1630 "creating decls map on non-primary context");
1633 bool Dependent = isDependentContext();
1635 M = new DependentStoredDeclsMap();
1637 M = new StoredDeclsMap();
1638 M->Previous = C.LastSDM;
1639 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1644 void ASTContext::ReleaseDeclContextMaps() {
1645 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1646 // pointer because the subclass doesn't add anything that needs to
1648 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1651 void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1653 // Advance the iteration before we invalidate memory.
1654 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1657 delete static_cast<DependentStoredDeclsMap*>(Map);
1661 Map = Next.getPointer();
1662 Dependent = Next.getInt();
1666 DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1667 DeclContext *Parent,
1668 const PartialDiagnostic &PDiag) {
1669 assert(Parent->isDependentContext()
1670 && "cannot iterate dependent diagnostics of non-dependent context");
1671 Parent = Parent->getPrimaryContext();
1672 if (!Parent->LookupPtr)
1673 Parent->CreateStoredDeclsMap(C);
1675 DependentStoredDeclsMap *Map =
1676 static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr);
1678 // Allocate the copy of the PartialDiagnostic via the ASTContext's
1679 // BumpPtrAllocator, rather than the ASTContext itself.
1680 PartialDiagnostic::Storage *DiagStorage = nullptr;
1681 if (PDiag.hasStorage())
1682 DiagStorage = new (C) PartialDiagnostic::Storage;
1684 DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
1686 // TODO: Maybe we shouldn't reverse the order during insertion.
1687 DD->NextDiagnostic = Map->FirstDiagnostic;
1688 Map->FirstDiagnostic = DD;