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 const char *Decl::getDeclKindName() const {
85 default: llvm_unreachable("Declaration not in DeclNodes.inc!");
86 #define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
87 #define ABSTRACT_DECL(DECL)
88 #include "clang/AST/DeclNodes.inc"
92 void Decl::setInvalidDecl(bool Invalid) {
93 InvalidDecl = Invalid;
94 assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition());
95 if (Invalid && !isa<ParmVarDecl>(this)) {
96 // Defensive maneuver for ill-formed code: we're likely not to make it to
97 // a point where we set the access specifier, so default it to "public"
98 // to avoid triggering asserts elsewhere in the front end.
103 const char *DeclContext::getDeclKindName() const {
105 default: llvm_unreachable("Declaration context not in DeclNodes.inc!");
106 #define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
107 #define ABSTRACT_DECL(DECL)
108 #include "clang/AST/DeclNodes.inc"
112 bool Decl::StatisticsEnabled = false;
113 void Decl::EnableStatistics() {
114 StatisticsEnabled = true;
117 void Decl::PrintStats() {
118 llvm::errs() << "\n*** Decl Stats:\n";
121 #define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
122 #define ABSTRACT_DECL(DECL)
123 #include "clang/AST/DeclNodes.inc"
124 llvm::errs() << " " << totalDecls << " decls total.\n";
127 #define DECL(DERIVED, BASE) \
128 if (n##DERIVED##s > 0) { \
129 totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \
130 llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \
131 << sizeof(DERIVED##Decl) << " each (" \
132 << n##DERIVED##s * sizeof(DERIVED##Decl) \
135 #define ABSTRACT_DECL(DECL)
136 #include "clang/AST/DeclNodes.inc"
138 llvm::errs() << "Total bytes = " << totalBytes << "\n";
141 void Decl::add(Kind k) {
143 #define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
144 #define ABSTRACT_DECL(DECL)
145 #include "clang/AST/DeclNodes.inc"
149 bool Decl::isTemplateParameterPack() const {
150 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
151 return TTP->isParameterPack();
152 if (const NonTypeTemplateParmDecl *NTTP
153 = dyn_cast<NonTypeTemplateParmDecl>(this))
154 return NTTP->isParameterPack();
155 if (const TemplateTemplateParmDecl *TTP
156 = dyn_cast<TemplateTemplateParmDecl>(this))
157 return TTP->isParameterPack();
161 bool Decl::isParameterPack() const {
162 if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this))
163 return Parm->isParameterPack();
165 return isTemplateParameterPack();
168 FunctionDecl *Decl::getAsFunction() {
169 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
171 if (const FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(this))
172 return FTD->getTemplatedDecl();
176 bool Decl::isTemplateDecl() const {
177 return isa<TemplateDecl>(this);
180 const DeclContext *Decl::getParentFunctionOrMethod() const {
181 for (const DeclContext *DC = getDeclContext();
182 DC && !DC->isTranslationUnit() && !DC->isNamespace();
183 DC = DC->getParent())
184 if (DC->isFunctionOrMethod())
191 //===----------------------------------------------------------------------===//
192 // PrettyStackTraceDecl Implementation
193 //===----------------------------------------------------------------------===//
195 void PrettyStackTraceDecl::print(raw_ostream &OS) const {
196 SourceLocation TheLoc = Loc;
197 if (TheLoc.isInvalid() && TheDecl)
198 TheLoc = TheDecl->getLocation();
200 if (TheLoc.isValid()) {
201 TheLoc.print(OS, SM);
207 if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
209 DN->printQualifiedName(OS);
215 //===----------------------------------------------------------------------===//
216 // Decl Implementation
217 //===----------------------------------------------------------------------===//
219 // Out-of-line virtual method providing a home for Decl.
222 void Decl::setDeclContext(DeclContext *DC) {
226 void Decl::setLexicalDeclContext(DeclContext *DC) {
227 if (DC == getLexicalDeclContext())
231 setDeclContextsImpl(getDeclContext(), DC, getASTContext());
233 getMultipleDC()->LexicalDC = DC;
237 void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
239 if (SemaDC == LexicalDC) {
242 Decl::MultipleDC *MDC = new (Ctx) Decl::MultipleDC();
243 MDC->SemanticDC = SemaDC;
244 MDC->LexicalDC = LexicalDC;
249 bool Decl::isInAnonymousNamespace() const {
250 const DeclContext *DC = getDeclContext();
252 if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
253 if (ND->isAnonymousNamespace())
255 } while ((DC = DC->getParent()));
260 bool Decl::isInStdNamespace() const {
261 return getDeclContext()->isStdNamespace();
264 TranslationUnitDecl *Decl::getTranslationUnitDecl() {
265 if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
268 DeclContext *DC = getDeclContext();
269 assert(DC && "This decl is not contained in a translation unit!");
271 while (!DC->isTranslationUnit()) {
272 DC = DC->getParent();
273 assert(DC && "This decl is not contained in a translation unit!");
276 return cast<TranslationUnitDecl>(DC);
279 ASTContext &Decl::getASTContext() const {
280 return getTranslationUnitDecl()->getASTContext();
283 ASTMutationListener *Decl::getASTMutationListener() const {
284 return getASTContext().getASTMutationListener();
287 unsigned Decl::getMaxAlignment() const {
292 const AttrVec &V = getAttrs();
293 ASTContext &Ctx = getASTContext();
294 specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
296 Align = std::max(Align, I->getAlignment(Ctx));
300 bool Decl::isUsed(bool CheckUsedAttr) const {
304 // Check for used attribute.
305 if (CheckUsedAttr && hasAttr<UsedAttr>())
311 void Decl::markUsed(ASTContext &C) {
315 if (C.getASTMutationListener())
316 C.getASTMutationListener()->DeclarationMarkedUsed(this);
321 bool Decl::isReferenced() const {
325 // Check redeclarations.
326 for (auto I : redecls())
333 /// \brief Determine the availability of the given declaration based on
334 /// the target platform.
336 /// When it returns an availability result other than \c AR_Available,
337 /// if the \p Message parameter is non-NULL, it will be set to a
338 /// string describing why the entity is unavailable.
340 /// FIXME: Make these strings localizable, since they end up in
342 static AvailabilityResult CheckAvailability(ASTContext &Context,
343 const AvailabilityAttr *A,
344 std::string *Message) {
345 VersionTuple TargetMinVersion =
346 Context.getTargetInfo().getPlatformMinVersion();
348 if (TargetMinVersion.empty())
351 // Check if this is an App Extension "platform", and if so chop off
352 // the suffix for matching with the actual platform.
353 StringRef ActualPlatform = A->getPlatform()->getName();
354 StringRef RealizedPlatform = ActualPlatform;
355 if (Context.getLangOpts().AppExt) {
356 size_t suffix = RealizedPlatform.rfind("_app_extension");
357 if (suffix != StringRef::npos)
358 RealizedPlatform = RealizedPlatform.slice(0, suffix);
361 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
363 // Match the platform name.
364 if (RealizedPlatform != TargetPlatform)
367 StringRef PrettyPlatformName
368 = AvailabilityAttr::getPrettyPlatformName(ActualPlatform);
370 if (PrettyPlatformName.empty())
371 PrettyPlatformName = ActualPlatform;
373 std::string HintMessage;
374 if (!A->getMessage().empty()) {
376 HintMessage += A->getMessage();
379 // Make sure that this declaration has not been marked 'unavailable'.
380 if (A->getUnavailable()) {
383 llvm::raw_string_ostream Out(*Message);
384 Out << "not available on " << PrettyPlatformName
388 return AR_Unavailable;
391 // Make sure that this declaration has already been introduced.
392 if (!A->getIntroduced().empty() &&
393 TargetMinVersion < A->getIntroduced()) {
396 llvm::raw_string_ostream Out(*Message);
397 VersionTuple VTI(A->getIntroduced());
398 VTI.UseDotAsSeparator();
399 Out << "introduced in " << PrettyPlatformName << ' '
400 << VTI << HintMessage;
403 return AR_NotYetIntroduced;
406 // Make sure that this declaration hasn't been obsoleted.
407 if (!A->getObsoleted().empty() && TargetMinVersion >= A->getObsoleted()) {
410 llvm::raw_string_ostream Out(*Message);
411 VersionTuple VTO(A->getObsoleted());
412 VTO.UseDotAsSeparator();
413 Out << "obsoleted in " << PrettyPlatformName << ' '
414 << VTO << HintMessage;
417 return AR_Unavailable;
420 // Make sure that this declaration hasn't been deprecated.
421 if (!A->getDeprecated().empty() && TargetMinVersion >= A->getDeprecated()) {
424 llvm::raw_string_ostream Out(*Message);
425 VersionTuple VTD(A->getDeprecated());
426 VTD.UseDotAsSeparator();
427 Out << "first deprecated in " << PrettyPlatformName << ' '
428 << VTD << HintMessage;
431 return AR_Deprecated;
437 AvailabilityResult Decl::getAvailability(std::string *Message) const {
438 AvailabilityResult Result = AR_Available;
439 std::string ResultMessage;
441 for (const auto *A : attrs()) {
442 if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
443 if (Result >= AR_Deprecated)
447 ResultMessage = Deprecated->getMessage();
449 Result = AR_Deprecated;
453 if (const auto *Unavailable = dyn_cast<UnavailableAttr>(A)) {
455 *Message = Unavailable->getMessage();
456 return AR_Unavailable;
459 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
460 AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
463 if (AR == AR_Unavailable)
464 return AR_Unavailable;
469 ResultMessage.swap(*Message);
476 Message->swap(ResultMessage);
480 bool Decl::canBeWeakImported(bool &IsDefinition) const {
481 IsDefinition = false;
483 // Variables, if they aren't definitions.
484 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
485 if (Var->isThisDeclarationADefinition()) {
491 // Functions, if they aren't definitions.
492 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
499 // Objective-C classes, if this is the non-fragile runtime.
500 } else if (isa<ObjCInterfaceDecl>(this) &&
501 getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
510 bool Decl::isWeakImported() const {
512 if (!canBeWeakImported(IsDefinition))
515 for (const auto *A : attrs()) {
516 if (isa<WeakImportAttr>(A))
519 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
520 if (CheckAvailability(getASTContext(), Availability,
521 nullptr) == AR_NotYetIntroduced)
529 unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
540 case NonTypeTemplateParm:
544 return IDNS_Ordinary;
548 return IDNS_Ordinary | IDNS_Member;
550 case ObjCCompatibleAlias:
552 return IDNS_Ordinary | IDNS_Type;
556 case TypeAliasTemplate:
557 case UnresolvedUsingTypename:
558 case TemplateTypeParm:
559 return IDNS_Ordinary | IDNS_Type;
562 return 0; // we'll actually overwrite this later
564 case UnresolvedUsingValue:
565 return IDNS_Ordinary | IDNS_Using;
571 return IDNS_ObjCProtocol;
574 case ObjCAtDefsField:
581 return IDNS_Tag | IDNS_Type;
585 return IDNS_Namespace;
587 case FunctionTemplate:
589 return IDNS_Ordinary;
592 case TemplateTemplateParm:
593 return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
602 case ObjCPropertyImpl:
605 case TranslationUnit:
609 case ClassTemplateSpecialization:
610 case ClassTemplatePartialSpecialization:
611 case ClassScopeFunctionSpecialization:
612 case VarTemplateSpecialization:
613 case VarTemplatePartialSpecialization:
614 case ObjCImplementation:
616 case ObjCCategoryImpl:
618 case OMPThreadPrivate:
620 // Never looked up by name.
624 llvm_unreachable("Invalid DeclKind!");
627 void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
628 assert(!HasAttrs && "Decl already contains attrs.");
630 AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
631 assert(AttrBlank.empty() && "HasAttrs was wrong?");
637 void Decl::dropAttrs() {
638 if (!HasAttrs) return;
641 getASTContext().eraseDeclAttrs(this);
644 const AttrVec &Decl::getAttrs() const {
645 assert(HasAttrs && "No attrs to get!");
646 return getASTContext().getDeclAttrs(this);
649 Decl *Decl::castFromDeclContext (const DeclContext *D) {
650 Decl::Kind DK = D->getDeclKind();
652 #define DECL(NAME, BASE)
653 #define DECL_CONTEXT(NAME) \
655 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
656 #define DECL_CONTEXT_BASE(NAME)
657 #include "clang/AST/DeclNodes.inc"
659 #define DECL(NAME, BASE)
660 #define DECL_CONTEXT_BASE(NAME) \
661 if (DK >= first##NAME && DK <= last##NAME) \
662 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
663 #include "clang/AST/DeclNodes.inc"
664 llvm_unreachable("a decl that inherits DeclContext isn't handled");
668 DeclContext *Decl::castToDeclContext(const Decl *D) {
669 Decl::Kind DK = D->getKind();
671 #define DECL(NAME, BASE)
672 #define DECL_CONTEXT(NAME) \
674 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
675 #define DECL_CONTEXT_BASE(NAME)
676 #include "clang/AST/DeclNodes.inc"
678 #define DECL(NAME, BASE)
679 #define DECL_CONTEXT_BASE(NAME) \
680 if (DK >= first##NAME && DK <= last##NAME) \
681 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
682 #include "clang/AST/DeclNodes.inc"
683 llvm_unreachable("a decl that inherits DeclContext isn't handled");
687 SourceLocation Decl::getBodyRBrace() const {
688 // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
689 // FunctionDecl stores EndRangeLoc for this purpose.
690 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
691 const FunctionDecl *Definition;
692 if (FD->hasBody(Definition))
693 return Definition->getSourceRange().getEnd();
694 return SourceLocation();
697 if (Stmt *Body = getBody())
698 return Body->getSourceRange().getEnd();
700 return SourceLocation();
703 bool Decl::AccessDeclContextSanity() const {
705 // Suppress this check if any of the following hold:
706 // 1. this is the translation unit (and thus has no parent)
707 // 2. this is a template parameter (and thus doesn't belong to its context)
708 // 3. this is a non-type template parameter
709 // 4. the context is not a record
711 // 6. it's a C++0x static_assert.
712 if (isa<TranslationUnitDecl>(this) ||
713 isa<TemplateTypeParmDecl>(this) ||
714 isa<NonTypeTemplateParmDecl>(this) ||
715 !isa<CXXRecordDecl>(getDeclContext()) ||
717 isa<StaticAssertDecl>(this) ||
718 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
719 // as DeclContext (?).
720 isa<ParmVarDecl>(this) ||
721 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
722 // AS_none as access specifier.
723 isa<CXXRecordDecl>(this) ||
724 isa<ClassScopeFunctionSpecializationDecl>(this))
727 assert(Access != AS_none &&
728 "Access specifier is AS_none inside a record decl");
733 static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
734 static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
736 const FunctionType *Decl::getFunctionType(bool BlocksToo) const {
738 if (const ValueDecl *D = dyn_cast<ValueDecl>(this))
740 else if (const TypedefNameDecl *D = dyn_cast<TypedefNameDecl>(this))
741 Ty = D->getUnderlyingType();
745 if (Ty->isFunctionPointerType())
746 Ty = Ty->getAs<PointerType>()->getPointeeType();
747 else if (BlocksToo && Ty->isBlockPointerType())
748 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
750 return Ty->getAs<FunctionType>();
754 /// Starting at a given context (a Decl or DeclContext), look for a
755 /// code context that is not a closure (a lambda, block, etc.).
756 template <class T> static Decl *getNonClosureContext(T *D) {
757 if (getKind(D) == Decl::CXXMethod) {
758 CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
759 if (MD->getOverloadedOperator() == OO_Call &&
760 MD->getParent()->isLambda())
761 return getNonClosureContext(MD->getParent()->getParent());
763 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
765 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
767 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
768 return getNonClosureContext(BD->getParent());
769 } else if (CapturedDecl *CD = dyn_cast<CapturedDecl>(D)) {
770 return getNonClosureContext(CD->getParent());
776 Decl *Decl::getNonClosureContext() {
777 return ::getNonClosureContext(this);
780 Decl *DeclContext::getNonClosureAncestor() {
781 return ::getNonClosureContext(this);
784 //===----------------------------------------------------------------------===//
785 // DeclContext Implementation
786 //===----------------------------------------------------------------------===//
788 bool DeclContext::classof(const Decl *D) {
789 switch (D->getKind()) {
790 #define DECL(NAME, BASE)
791 #define DECL_CONTEXT(NAME) case Decl::NAME:
792 #define DECL_CONTEXT_BASE(NAME)
793 #include "clang/AST/DeclNodes.inc"
796 #define DECL(NAME, BASE)
797 #define DECL_CONTEXT_BASE(NAME) \
798 if (D->getKind() >= Decl::first##NAME && \
799 D->getKind() <= Decl::last##NAME) \
801 #include "clang/AST/DeclNodes.inc"
806 DeclContext::~DeclContext() { }
808 /// \brief Find the parent context of this context that will be
809 /// used for unqualified name lookup.
811 /// Generally, the parent lookup context is the semantic context. However, for
812 /// a friend function the parent lookup context is the lexical context, which
813 /// is the class in which the friend is declared.
814 DeclContext *DeclContext::getLookupParent() {
815 // FIXME: Find a better way to identify friends
816 if (isa<FunctionDecl>(this))
817 if (getParent()->getRedeclContext()->isFileContext() &&
818 getLexicalParent()->getRedeclContext()->isRecord())
819 return getLexicalParent();
824 bool DeclContext::isInlineNamespace() const {
825 return isNamespace() &&
826 cast<NamespaceDecl>(this)->isInline();
829 bool DeclContext::isStdNamespace() const {
833 const NamespaceDecl *ND = cast<NamespaceDecl>(this);
834 if (ND->isInline()) {
835 return ND->getParent()->isStdNamespace();
838 if (!getParent()->getRedeclContext()->isTranslationUnit())
841 const IdentifierInfo *II = ND->getIdentifier();
842 return II && II->isStr("std");
845 bool DeclContext::isDependentContext() const {
849 if (isa<ClassTemplatePartialSpecializationDecl>(this))
852 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
853 if (Record->getDescribedClassTemplate())
856 if (Record->isDependentLambda())
860 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
861 if (Function->getDescribedFunctionTemplate())
864 // Friend function declarations are dependent if their *lexical*
865 // context is dependent.
866 if (cast<Decl>(this)->getFriendObjectKind())
867 return getLexicalParent()->isDependentContext();
870 // FIXME: A variable template is a dependent context, but is not a
871 // DeclContext. A context within it (such as a lambda-expression)
872 // should be considered dependent.
874 return getParent() && getParent()->isDependentContext();
877 bool DeclContext::isTransparentContext() const {
878 if (DeclKind == Decl::Enum)
879 return !cast<EnumDecl>(this)->isScoped();
880 else if (DeclKind == Decl::LinkageSpec)
886 static bool isLinkageSpecContext(const DeclContext *DC,
887 LinkageSpecDecl::LanguageIDs ID) {
888 while (DC->getDeclKind() != Decl::TranslationUnit) {
889 if (DC->getDeclKind() == Decl::LinkageSpec)
890 return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
891 DC = DC->getLexicalParent();
896 bool DeclContext::isExternCContext() const {
897 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_c);
900 bool DeclContext::isExternCXXContext() const {
901 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_cxx);
904 bool DeclContext::Encloses(const DeclContext *DC) const {
905 if (getPrimaryContext() != this)
906 return getPrimaryContext()->Encloses(DC);
908 for (; DC; DC = DC->getParent())
909 if (DC->getPrimaryContext() == this)
914 DeclContext *DeclContext::getPrimaryContext() {
916 case Decl::TranslationUnit:
917 case Decl::ExternCContext:
918 case Decl::LinkageSpec:
921 // There is only one DeclContext for these entities.
924 case Decl::Namespace:
925 // The original namespace is our primary context.
926 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
928 case Decl::ObjCMethod:
931 case Decl::ObjCInterface:
932 if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
937 case Decl::ObjCProtocol:
938 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
943 case Decl::ObjCCategory:
946 case Decl::ObjCImplementation:
947 case Decl::ObjCCategoryImpl:
951 if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
952 // If this is a tag type that has a definition or is currently
953 // being defined, that definition is our primary context.
954 TagDecl *Tag = cast<TagDecl>(this);
956 if (TagDecl *Def = Tag->getDefinition())
959 if (const TagType *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) {
960 // Note, TagType::getDecl returns the (partial) definition one exists.
961 TagDecl *PossiblePartialDef = TagTy->getDecl();
962 if (PossiblePartialDef->isBeingDefined())
963 return PossiblePartialDef;
965 assert(isa<InjectedClassNameType>(Tag->getTypeForDecl()));
971 assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
972 "Unknown DeclContext kind");
978 DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
981 if (DeclKind != Decl::Namespace) {
982 Contexts.push_back(this);
986 NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
987 for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
988 N = N->getPreviousDecl())
989 Contexts.push_back(N);
991 std::reverse(Contexts.begin(), Contexts.end());
994 std::pair<Decl *, Decl *>
995 DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
996 bool FieldsAlreadyLoaded) {
997 // Build up a chain of declarations via the Decl::NextInContextAndBits field.
998 Decl *FirstNewDecl = nullptr;
999 Decl *PrevDecl = nullptr;
1000 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1001 if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
1006 PrevDecl->NextInContextAndBits.setPointer(D);
1013 return std::make_pair(FirstNewDecl, PrevDecl);
1016 /// \brief We have just acquired external visible storage, and we already have
1017 /// built a lookup map. For every name in the map, pull in the new names from
1018 /// the external storage.
1019 void DeclContext::reconcileExternalVisibleStorage() const {
1020 assert(NeedToReconcileExternalVisibleStorage && LookupPtr);
1021 NeedToReconcileExternalVisibleStorage = false;
1023 for (auto &Lookup : *LookupPtr)
1024 Lookup.second.setHasExternalDecls();
1027 /// \brief Load the declarations within this lexical storage from an
1028 /// external source.
1029 /// \return \c true if any declarations were added.
1031 DeclContext::LoadLexicalDeclsFromExternalStorage() const {
1032 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1033 assert(hasExternalLexicalStorage() && Source && "No external storage?");
1035 // Notify that we have a DeclContext that is initializing.
1036 ExternalASTSource::Deserializing ADeclContext(Source);
1038 // Load the external declarations, if any.
1039 SmallVector<Decl*, 64> Decls;
1040 ExternalLexicalStorage = false;
1041 switch (Source->FindExternalLexicalDecls(this, Decls)) {
1046 case ELR_AlreadyLoaded:
1053 // We may have already loaded just the fields of this record, in which case
1054 // we need to ignore them.
1055 bool FieldsAlreadyLoaded = false;
1056 if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
1057 FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
1059 // Splice the newly-read declarations into the beginning of the list
1061 Decl *ExternalFirst, *ExternalLast;
1062 std::tie(ExternalFirst, ExternalLast) =
1063 BuildDeclChain(Decls, FieldsAlreadyLoaded);
1064 ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
1065 FirstDecl = ExternalFirst;
1067 LastDecl = ExternalLast;
1071 DeclContext::lookup_result
1072 ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
1073 DeclarationName Name) {
1074 ASTContext &Context = DC->getParentASTContext();
1075 StoredDeclsMap *Map;
1076 if (!(Map = DC->LookupPtr))
1077 Map = DC->CreateStoredDeclsMap(Context);
1078 if (DC->NeedToReconcileExternalVisibleStorage)
1079 DC->reconcileExternalVisibleStorage();
1081 (*Map)[Name].removeExternalDecls();
1083 return DeclContext::lookup_result();
1086 DeclContext::lookup_result
1087 ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
1088 DeclarationName Name,
1089 ArrayRef<NamedDecl*> Decls) {
1090 ASTContext &Context = DC->getParentASTContext();
1091 StoredDeclsMap *Map;
1092 if (!(Map = DC->LookupPtr))
1093 Map = DC->CreateStoredDeclsMap(Context);
1094 if (DC->NeedToReconcileExternalVisibleStorage)
1095 DC->reconcileExternalVisibleStorage();
1097 StoredDeclsList &List = (*Map)[Name];
1099 // Clear out any old external visible declarations, to avoid quadratic
1100 // performance in the redeclaration checks below.
1101 List.removeExternalDecls();
1103 if (!List.isNull()) {
1104 // We have both existing declarations and new declarations for this name.
1105 // Some of the declarations may simply replace existing ones. Handle those
1107 llvm::SmallVector<unsigned, 8> Skip;
1108 for (unsigned I = 0, N = Decls.size(); I != N; ++I)
1109 if (List.HandleRedeclaration(Decls[I], /*IsKnownNewer*/false))
1111 Skip.push_back(Decls.size());
1113 // Add in any new declarations.
1114 unsigned SkipPos = 0;
1115 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1116 if (I == Skip[SkipPos])
1119 List.AddSubsequentDecl(Decls[I]);
1122 // Convert the array to a StoredDeclsList.
1123 for (ArrayRef<NamedDecl*>::iterator
1124 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1126 List.setOnlyValue(*I);
1128 List.AddSubsequentDecl(*I);
1132 return List.getLookupResult();
1135 DeclContext::decl_iterator DeclContext::decls_begin() const {
1136 if (hasExternalLexicalStorage())
1137 LoadLexicalDeclsFromExternalStorage();
1138 return decl_iterator(FirstDecl);
1141 bool DeclContext::decls_empty() const {
1142 if (hasExternalLexicalStorage())
1143 LoadLexicalDeclsFromExternalStorage();
1148 bool DeclContext::containsDecl(Decl *D) const {
1149 return (D->getLexicalDeclContext() == this &&
1150 (D->NextInContextAndBits.getPointer() || D == LastDecl));
1153 void DeclContext::removeDecl(Decl *D) {
1154 assert(D->getLexicalDeclContext() == this &&
1155 "decl being removed from non-lexical context");
1156 assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
1157 "decl is not in decls list");
1159 // Remove D from the decl chain. This is O(n) but hopefully rare.
1160 if (D == FirstDecl) {
1162 FirstDecl = LastDecl = nullptr;
1164 FirstDecl = D->NextInContextAndBits.getPointer();
1166 for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
1167 assert(I && "decl not found in linked list");
1168 if (I->NextInContextAndBits.getPointer() == D) {
1169 I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
1170 if (D == LastDecl) LastDecl = I;
1176 // Mark that D is no longer in the decl chain.
1177 D->NextInContextAndBits.setPointer(nullptr);
1179 // Remove D from the lookup table if necessary.
1180 if (isa<NamedDecl>(D)) {
1181 NamedDecl *ND = cast<NamedDecl>(D);
1183 // Remove only decls that have a name
1184 if (!ND->getDeclName()) return;
1186 StoredDeclsMap *Map = getPrimaryContext()->LookupPtr;
1189 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1190 assert(Pos != Map->end() && "no lookup entry for decl");
1191 if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
1192 Pos->second.remove(ND);
1196 void DeclContext::addHiddenDecl(Decl *D) {
1197 assert(D->getLexicalDeclContext() == this &&
1198 "Decl inserted into wrong lexical context");
1199 assert(!D->getNextDeclInContext() && D != LastDecl &&
1200 "Decl already inserted into a DeclContext");
1203 LastDecl->NextInContextAndBits.setPointer(D);
1206 FirstDecl = LastDecl = D;
1209 // Notify a C++ record declaration that we've added a member, so it can
1210 // update it's class-specific state.
1211 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1212 Record->addedMember(D);
1214 // If this is a newly-created (not de-serialized) import declaration, wire
1215 // it in to the list of local import declarations.
1216 if (!D->isFromASTFile()) {
1217 if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
1218 D->getASTContext().addedLocalImportDecl(Import);
1222 void DeclContext::addDecl(Decl *D) {
1225 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1226 ND->getDeclContext()->getPrimaryContext()->
1227 makeDeclVisibleInContextWithFlags(ND, false, true);
1230 void DeclContext::addDeclInternal(Decl *D) {
1233 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1234 ND->getDeclContext()->getPrimaryContext()->
1235 makeDeclVisibleInContextWithFlags(ND, true, true);
1238 /// shouldBeHidden - Determine whether a declaration which was declared
1239 /// within its semantic context should be invisible to qualified name lookup.
1240 static bool shouldBeHidden(NamedDecl *D) {
1241 // Skip unnamed declarations.
1242 if (!D->getDeclName())
1245 // Skip entities that can't be found by name lookup into a particular
1247 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1248 D->isTemplateParameter())
1251 // Skip template specializations.
1252 // FIXME: This feels like a hack. Should DeclarationName support
1253 // template-ids, or is there a better way to keep specializations
1254 // from being visible?
1255 if (isa<ClassTemplateSpecializationDecl>(D))
1257 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1258 if (FD->isFunctionTemplateSpecialization())
1264 /// buildLookup - Build the lookup data structure with all of the
1265 /// declarations in this DeclContext (and any other contexts linked
1266 /// to it or transparent contexts nested within it) and return it.
1268 /// Note that the produced map may miss out declarations from an
1269 /// external source. If it does, those entries will be marked with
1270 /// the 'hasExternalDecls' flag.
1271 StoredDeclsMap *DeclContext::buildLookup() {
1272 assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1274 if (!HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups)
1277 SmallVector<DeclContext *, 2> Contexts;
1278 collectAllContexts(Contexts);
1280 if (HasLazyExternalLexicalLookups) {
1281 HasLazyExternalLexicalLookups = false;
1282 for (auto *DC : Contexts) {
1283 if (DC->hasExternalLexicalStorage())
1284 HasLazyLocalLexicalLookups |=
1285 DC->LoadLexicalDeclsFromExternalStorage();
1288 if (!HasLazyLocalLexicalLookups)
1292 for (auto *DC : Contexts)
1293 buildLookupImpl(DC, hasExternalVisibleStorage());
1295 // We no longer have any lazy decls.
1296 HasLazyLocalLexicalLookups = false;
1300 /// buildLookupImpl - Build part of the lookup data structure for the
1301 /// declarations contained within DCtx, which will either be this
1302 /// DeclContext, a DeclContext linked to it, or a transparent context
1303 /// nested within it.
1304 void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {
1305 for (Decl *D : DCtx->noload_decls()) {
1306 // Insert this declaration into the lookup structure, but only if
1307 // it's semantically within its decl context. Any other decls which
1308 // should be found in this context are added eagerly.
1310 // If it's from an AST file, don't add it now. It'll get handled by
1311 // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1312 // in C++, we do not track external visible decls for the TU, so in
1313 // that case we need to collect them all here.
1314 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1315 if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1316 (!ND->isFromASTFile() ||
1317 (isTranslationUnit() &&
1318 !getParentASTContext().getLangOpts().CPlusPlus)))
1319 makeDeclVisibleInContextImpl(ND, Internal);
1321 // If this declaration is itself a transparent declaration context
1322 // or inline namespace, add the members of this declaration of that
1323 // context (recursively).
1324 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
1325 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1326 buildLookupImpl(InnerCtx, Internal);
1330 NamedDecl *const DeclContextLookupResult::SingleElementDummyList = nullptr;
1332 DeclContext::lookup_result
1333 DeclContext::lookup(DeclarationName Name) const {
1334 assert(DeclKind != Decl::LinkageSpec &&
1335 "Should not perform lookups into linkage specs!");
1337 const DeclContext *PrimaryContext = getPrimaryContext();
1338 if (PrimaryContext != this)
1339 return PrimaryContext->lookup(Name);
1341 // If we have an external source, ensure that any later redeclarations of this
1342 // context have been loaded, since they may add names to the result of this
1343 // lookup (or add external visible storage).
1344 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1346 (void)cast<Decl>(this)->getMostRecentDecl();
1348 if (hasExternalVisibleStorage()) {
1349 assert(Source && "external visible storage but no external source?");
1351 if (NeedToReconcileExternalVisibleStorage)
1352 reconcileExternalVisibleStorage();
1354 StoredDeclsMap *Map = LookupPtr;
1356 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
1357 // FIXME: Make buildLookup const?
1358 Map = const_cast<DeclContext*>(this)->buildLookup();
1361 Map = CreateStoredDeclsMap(getParentASTContext());
1363 // If we have a lookup result with no external decls, we are done.
1364 std::pair<StoredDeclsMap::iterator, bool> R =
1365 Map->insert(std::make_pair(Name, StoredDeclsList()));
1366 if (!R.second && !R.first->second.hasExternalDecls())
1367 return R.first->second.getLookupResult();
1369 if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) {
1370 if (StoredDeclsMap *Map = LookupPtr) {
1371 StoredDeclsMap::iterator I = Map->find(Name);
1372 if (I != Map->end())
1373 return I->second.getLookupResult();
1377 return lookup_result();
1380 StoredDeclsMap *Map = LookupPtr;
1381 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
1382 Map = const_cast<DeclContext*>(this)->buildLookup();
1385 return lookup_result();
1387 StoredDeclsMap::iterator I = Map->find(Name);
1388 if (I == Map->end())
1389 return lookup_result();
1391 return I->second.getLookupResult();
1394 DeclContext::lookup_result
1395 DeclContext::noload_lookup(DeclarationName Name) {
1396 assert(DeclKind != Decl::LinkageSpec &&
1397 "Should not perform lookups into linkage specs!");
1399 DeclContext *PrimaryContext = getPrimaryContext();
1400 if (PrimaryContext != this)
1401 return PrimaryContext->noload_lookup(Name);
1403 // If we have any lazy lexical declarations not in our lookup map, add them
1404 // now. Don't import any external declarations, not even if we know we have
1405 // some missing from the external visible lookups.
1406 if (HasLazyLocalLexicalLookups) {
1407 SmallVector<DeclContext *, 2> Contexts;
1408 collectAllContexts(Contexts);
1409 for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
1410 buildLookupImpl(Contexts[I], hasExternalVisibleStorage());
1411 HasLazyLocalLexicalLookups = false;
1414 StoredDeclsMap *Map = LookupPtr;
1416 return lookup_result();
1418 StoredDeclsMap::iterator I = Map->find(Name);
1419 return I != Map->end() ? I->second.getLookupResult()
1423 void DeclContext::localUncachedLookup(DeclarationName Name,
1424 SmallVectorImpl<NamedDecl *> &Results) {
1427 // If there's no external storage, just perform a normal lookup and copy
1429 if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
1430 lookup_result LookupResults = lookup(Name);
1431 Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
1435 // If we have a lookup table, check there first. Maybe we'll get lucky.
1436 // FIXME: Should we be checking these flags on the primary context?
1437 if (Name && !HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups) {
1438 if (StoredDeclsMap *Map = LookupPtr) {
1439 StoredDeclsMap::iterator Pos = Map->find(Name);
1440 if (Pos != Map->end()) {
1441 Results.insert(Results.end(),
1442 Pos->second.getLookupResult().begin(),
1443 Pos->second.getLookupResult().end());
1449 // Slow case: grovel through the declarations in our chain looking for
1451 // FIXME: If we have lazy external declarations, this will not find them!
1452 // FIXME: Should we CollectAllContexts and walk them all here?
1453 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1454 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1455 if (ND->getDeclName() == Name)
1456 Results.push_back(ND);
1460 DeclContext *DeclContext::getRedeclContext() {
1461 DeclContext *Ctx = this;
1462 // Skip through transparent contexts.
1463 while (Ctx->isTransparentContext())
1464 Ctx = Ctx->getParent();
1468 DeclContext *DeclContext::getEnclosingNamespaceContext() {
1469 DeclContext *Ctx = this;
1470 // Skip through non-namespace, non-translation-unit contexts.
1471 while (!Ctx->isFileContext())
1472 Ctx = Ctx->getParent();
1473 return Ctx->getPrimaryContext();
1476 RecordDecl *DeclContext::getOuterLexicalRecordContext() {
1477 // Loop until we find a non-record context.
1478 RecordDecl *OutermostRD = nullptr;
1479 DeclContext *DC = this;
1480 while (DC->isRecord()) {
1481 OutermostRD = cast<RecordDecl>(DC);
1482 DC = DC->getLexicalParent();
1487 bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1488 // For non-file contexts, this is equivalent to Equals.
1489 if (!isFileContext())
1490 return O->Equals(this);
1493 if (O->Equals(this))
1496 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1497 if (!NS || !NS->isInline())
1499 O = NS->getParent();
1505 void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1506 DeclContext *PrimaryDC = this->getPrimaryContext();
1507 DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1508 // If the decl is being added outside of its semantic decl context, we
1509 // need to ensure that we eagerly build the lookup information for it.
1510 PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
1513 void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1515 assert(this == getPrimaryContext() && "expected a primary DC");
1517 // Skip declarations within functions.
1518 if (isFunctionOrMethod())
1521 // Skip declarations which should be invisible to name lookup.
1522 if (shouldBeHidden(D))
1525 // If we already have a lookup data structure, perform the insertion into
1526 // it. If we might have externally-stored decls with this name, look them
1527 // up and perform the insertion. If this decl was declared outside its
1528 // semantic context, buildLookup won't add it, so add it now.
1530 // FIXME: As a performance hack, don't add such decls into the translation
1531 // unit unless we're in C++, since qualified lookup into the TU is never
1533 if (LookupPtr || hasExternalVisibleStorage() ||
1534 ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1535 (getParentASTContext().getLangOpts().CPlusPlus ||
1536 !isTranslationUnit()))) {
1537 // If we have lazily omitted any decls, they might have the same name as
1538 // the decl which we are adding, so build a full lookup table before adding
1541 makeDeclVisibleInContextImpl(D, Internal);
1543 HasLazyLocalLexicalLookups = true;
1546 // If we are a transparent context or inline namespace, insert into our
1547 // parent context, too. This operation is recursive.
1548 if (isTransparentContext() || isInlineNamespace())
1549 getParent()->getPrimaryContext()->
1550 makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1552 Decl *DCAsDecl = cast<Decl>(this);
1553 // Notify that a decl was made visible unless we are a Tag being defined.
1554 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1555 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1556 L->AddedVisibleDecl(this, D);
1559 void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1560 // Find or create the stored declaration map.
1561 StoredDeclsMap *Map = LookupPtr;
1563 ASTContext *C = &getParentASTContext();
1564 Map = CreateStoredDeclsMap(*C);
1567 // If there is an external AST source, load any declarations it knows about
1568 // with this declaration's name.
1569 // If the lookup table contains an entry about this name it means that we
1570 // have already checked the external source.
1572 if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1573 if (hasExternalVisibleStorage() &&
1574 Map->find(D->getDeclName()) == Map->end())
1575 Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1577 // Insert this declaration into the map.
1578 StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
1581 // If this is being added as part of loading an external declaration,
1582 // this may not be the only external declaration with this name.
1583 // In this case, we never try to replace an existing declaration; we'll
1584 // handle that when we finalize the list of declarations for this name.
1585 DeclNameEntries.setHasExternalDecls();
1586 DeclNameEntries.AddSubsequentDecl(D);
1590 if (DeclNameEntries.isNull()) {
1591 DeclNameEntries.setOnlyValue(D);
1595 if (DeclNameEntries.HandleRedeclaration(D, /*IsKnownNewer*/!Internal)) {
1596 // This declaration has replaced an existing one for which
1597 // declarationReplaces returns true.
1601 // Put this declaration into the appropriate slot.
1602 DeclNameEntries.AddSubsequentDecl(D);
1605 UsingDirectiveDecl *DeclContext::udir_iterator::operator*() const {
1606 return cast<UsingDirectiveDecl>(*I);
1609 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1611 DeclContext::udir_range DeclContext::using_directives() const {
1612 // FIXME: Use something more efficient than normal lookup for using
1613 // directives. In C++, using directives are looked up more than anything else.
1614 lookup_result Result = lookup(UsingDirectiveDecl::getName());
1615 return udir_range(Result.begin(), Result.end());
1618 //===----------------------------------------------------------------------===//
1619 // Creation and Destruction of StoredDeclsMaps. //
1620 //===----------------------------------------------------------------------===//
1622 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1623 assert(!LookupPtr && "context already has a decls map");
1624 assert(getPrimaryContext() == this &&
1625 "creating decls map on non-primary context");
1628 bool Dependent = isDependentContext();
1630 M = new DependentStoredDeclsMap();
1632 M = new StoredDeclsMap();
1633 M->Previous = C.LastSDM;
1634 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1639 void ASTContext::ReleaseDeclContextMaps() {
1640 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1641 // pointer because the subclass doesn't add anything that needs to
1643 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1646 void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1648 // Advance the iteration before we invalidate memory.
1649 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1652 delete static_cast<DependentStoredDeclsMap*>(Map);
1656 Map = Next.getPointer();
1657 Dependent = Next.getInt();
1661 DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1662 DeclContext *Parent,
1663 const PartialDiagnostic &PDiag) {
1664 assert(Parent->isDependentContext()
1665 && "cannot iterate dependent diagnostics of non-dependent context");
1666 Parent = Parent->getPrimaryContext();
1667 if (!Parent->LookupPtr)
1668 Parent->CreateStoredDeclsMap(C);
1670 DependentStoredDeclsMap *Map =
1671 static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr);
1673 // Allocate the copy of the PartialDiagnostic via the ASTContext's
1674 // BumpPtrAllocator, rather than the ASTContext itself.
1675 PartialDiagnostic::Storage *DiagStorage = nullptr;
1676 if (PDiag.hasStorage())
1677 DiagStorage = new (C) PartialDiagnostic::Storage;
1679 DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
1681 // TODO: Maybe we shouldn't reverse the order during insertion.
1682 DD->NextDiagnostic = Map->FirstDiagnostic;
1683 Map->FirstDiagnostic = DD;