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;
241 void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
243 if (SemaDC == LexicalDC) {
246 Decl::MultipleDC *MDC = new (Ctx) Decl::MultipleDC();
247 MDC->SemanticDC = SemaDC;
248 MDC->LexicalDC = LexicalDC;
253 bool Decl::isInAnonymousNamespace() const {
254 const DeclContext *DC = getDeclContext();
256 if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
257 if (ND->isAnonymousNamespace())
259 } while ((DC = DC->getParent()));
264 bool Decl::isInStdNamespace() const {
265 return getDeclContext()->isStdNamespace();
268 TranslationUnitDecl *Decl::getTranslationUnitDecl() {
269 if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
272 DeclContext *DC = getDeclContext();
273 assert(DC && "This decl is not contained in a translation unit!");
275 while (!DC->isTranslationUnit()) {
276 DC = DC->getParent();
277 assert(DC && "This decl is not contained in a translation unit!");
280 return cast<TranslationUnitDecl>(DC);
283 ASTContext &Decl::getASTContext() const {
284 return getTranslationUnitDecl()->getASTContext();
287 ASTMutationListener *Decl::getASTMutationListener() const {
288 return getASTContext().getASTMutationListener();
291 unsigned Decl::getMaxAlignment() const {
296 const AttrVec &V = getAttrs();
297 ASTContext &Ctx = getASTContext();
298 specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
300 Align = std::max(Align, I->getAlignment(Ctx));
304 bool Decl::isUsed(bool CheckUsedAttr) const {
308 // Check for used attribute.
309 if (CheckUsedAttr && hasAttr<UsedAttr>())
315 void Decl::markUsed(ASTContext &C) {
319 if (C.getASTMutationListener())
320 C.getASTMutationListener()->DeclarationMarkedUsed(this);
325 bool Decl::isReferenced() const {
329 // Check redeclarations.
330 for (auto I : redecls())
337 /// \brief Determine the availability of the given declaration based on
338 /// the target platform.
340 /// When it returns an availability result other than \c AR_Available,
341 /// if the \p Message parameter is non-NULL, it will be set to a
342 /// string describing why the entity is unavailable.
344 /// FIXME: Make these strings localizable, since they end up in
346 static AvailabilityResult CheckAvailability(ASTContext &Context,
347 const AvailabilityAttr *A,
348 std::string *Message) {
349 VersionTuple TargetMinVersion =
350 Context.getTargetInfo().getPlatformMinVersion();
352 if (TargetMinVersion.empty())
355 // Check if this is an App Extension "platform", and if so chop off
356 // the suffix for matching with the actual platform.
357 StringRef ActualPlatform = A->getPlatform()->getName();
358 StringRef RealizedPlatform = ActualPlatform;
359 if (Context.getLangOpts().AppExt) {
360 size_t suffix = RealizedPlatform.rfind("_app_extension");
361 if (suffix != StringRef::npos)
362 RealizedPlatform = RealizedPlatform.slice(0, suffix);
365 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
367 // Match the platform name.
368 if (RealizedPlatform != TargetPlatform)
371 StringRef PrettyPlatformName
372 = AvailabilityAttr::getPrettyPlatformName(ActualPlatform);
374 if (PrettyPlatformName.empty())
375 PrettyPlatformName = ActualPlatform;
377 std::string HintMessage;
378 if (!A->getMessage().empty()) {
380 HintMessage += A->getMessage();
383 // Make sure that this declaration has not been marked 'unavailable'.
384 if (A->getUnavailable()) {
387 llvm::raw_string_ostream Out(*Message);
388 Out << "not available on " << PrettyPlatformName
392 return AR_Unavailable;
395 // Make sure that this declaration has already been introduced.
396 if (!A->getIntroduced().empty() &&
397 TargetMinVersion < A->getIntroduced()) {
400 llvm::raw_string_ostream Out(*Message);
401 VersionTuple VTI(A->getIntroduced());
402 VTI.UseDotAsSeparator();
403 Out << "introduced in " << PrettyPlatformName << ' '
404 << VTI << HintMessage;
407 return AR_NotYetIntroduced;
410 // Make sure that this declaration hasn't been obsoleted.
411 if (!A->getObsoleted().empty() && TargetMinVersion >= A->getObsoleted()) {
414 llvm::raw_string_ostream Out(*Message);
415 VersionTuple VTO(A->getObsoleted());
416 VTO.UseDotAsSeparator();
417 Out << "obsoleted in " << PrettyPlatformName << ' '
418 << VTO << HintMessage;
421 return AR_Unavailable;
424 // Make sure that this declaration hasn't been deprecated.
425 if (!A->getDeprecated().empty() && TargetMinVersion >= A->getDeprecated()) {
428 llvm::raw_string_ostream Out(*Message);
429 VersionTuple VTD(A->getDeprecated());
430 VTD.UseDotAsSeparator();
431 Out << "first deprecated in " << PrettyPlatformName << ' '
432 << VTD << HintMessage;
435 return AR_Deprecated;
441 AvailabilityResult Decl::getAvailability(std::string *Message) const {
442 AvailabilityResult Result = AR_Available;
443 std::string ResultMessage;
445 for (const auto *A : attrs()) {
446 if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
447 if (Result >= AR_Deprecated)
451 ResultMessage = Deprecated->getMessage();
453 Result = AR_Deprecated;
457 if (const auto *Unavailable = dyn_cast<UnavailableAttr>(A)) {
459 *Message = Unavailable->getMessage();
460 return AR_Unavailable;
463 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
464 AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
467 if (AR == AR_Unavailable)
468 return AR_Unavailable;
473 ResultMessage.swap(*Message);
480 Message->swap(ResultMessage);
484 bool Decl::canBeWeakImported(bool &IsDefinition) const {
485 IsDefinition = false;
487 // Variables, if they aren't definitions.
488 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
489 if (Var->isThisDeclarationADefinition()) {
495 // Functions, if they aren't definitions.
496 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
503 // Objective-C classes, if this is the non-fragile runtime.
504 } else if (isa<ObjCInterfaceDecl>(this) &&
505 getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
514 bool Decl::isWeakImported() const {
516 if (!canBeWeakImported(IsDefinition))
519 for (const auto *A : attrs()) {
520 if (isa<WeakImportAttr>(A))
523 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
524 if (CheckAvailability(getASTContext(), Availability,
525 nullptr) == AR_NotYetIntroduced)
533 unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
544 case NonTypeTemplateParm:
548 return IDNS_Ordinary;
552 return IDNS_Ordinary | IDNS_Member;
554 case ObjCCompatibleAlias:
556 return IDNS_Ordinary | IDNS_Type;
560 case TypeAliasTemplate:
561 case UnresolvedUsingTypename:
562 case TemplateTypeParm:
563 return IDNS_Ordinary | IDNS_Type;
566 return 0; // we'll actually overwrite this later
568 case UnresolvedUsingValue:
569 return IDNS_Ordinary | IDNS_Using;
575 return IDNS_ObjCProtocol;
578 case ObjCAtDefsField:
585 return IDNS_Tag | IDNS_Type;
589 return IDNS_Namespace;
591 case FunctionTemplate:
593 return IDNS_Ordinary;
596 case TemplateTemplateParm:
597 return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
606 case ObjCPropertyImpl:
609 case TranslationUnit:
613 case ClassTemplateSpecialization:
614 case ClassTemplatePartialSpecialization:
615 case ClassScopeFunctionSpecialization:
616 case VarTemplateSpecialization:
617 case VarTemplatePartialSpecialization:
618 case ObjCImplementation:
620 case ObjCCategoryImpl:
622 case OMPThreadPrivate:
624 // Never looked up by name.
628 llvm_unreachable("Invalid DeclKind!");
631 void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
632 assert(!HasAttrs && "Decl already contains attrs.");
634 AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
635 assert(AttrBlank.empty() && "HasAttrs was wrong?");
641 void Decl::dropAttrs() {
642 if (!HasAttrs) return;
645 getASTContext().eraseDeclAttrs(this);
648 const AttrVec &Decl::getAttrs() const {
649 assert(HasAttrs && "No attrs to get!");
650 return getASTContext().getDeclAttrs(this);
653 Decl *Decl::castFromDeclContext (const DeclContext *D) {
654 Decl::Kind DK = D->getDeclKind();
656 #define DECL(NAME, BASE)
657 #define DECL_CONTEXT(NAME) \
659 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
660 #define DECL_CONTEXT_BASE(NAME)
661 #include "clang/AST/DeclNodes.inc"
663 #define DECL(NAME, BASE)
664 #define DECL_CONTEXT_BASE(NAME) \
665 if (DK >= first##NAME && DK <= last##NAME) \
666 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
667 #include "clang/AST/DeclNodes.inc"
668 llvm_unreachable("a decl that inherits DeclContext isn't handled");
672 DeclContext *Decl::castToDeclContext(const Decl *D) {
673 Decl::Kind DK = D->getKind();
675 #define DECL(NAME, BASE)
676 #define DECL_CONTEXT(NAME) \
678 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
679 #define DECL_CONTEXT_BASE(NAME)
680 #include "clang/AST/DeclNodes.inc"
682 #define DECL(NAME, BASE)
683 #define DECL_CONTEXT_BASE(NAME) \
684 if (DK >= first##NAME && DK <= last##NAME) \
685 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
686 #include "clang/AST/DeclNodes.inc"
687 llvm_unreachable("a decl that inherits DeclContext isn't handled");
691 SourceLocation Decl::getBodyRBrace() const {
692 // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
693 // FunctionDecl stores EndRangeLoc for this purpose.
694 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
695 const FunctionDecl *Definition;
696 if (FD->hasBody(Definition))
697 return Definition->getSourceRange().getEnd();
698 return SourceLocation();
701 if (Stmt *Body = getBody())
702 return Body->getSourceRange().getEnd();
704 return SourceLocation();
707 bool Decl::AccessDeclContextSanity() const {
709 // Suppress this check if any of the following hold:
710 // 1. this is the translation unit (and thus has no parent)
711 // 2. this is a template parameter (and thus doesn't belong to its context)
712 // 3. this is a non-type template parameter
713 // 4. the context is not a record
715 // 6. it's a C++0x static_assert.
716 if (isa<TranslationUnitDecl>(this) ||
717 isa<TemplateTypeParmDecl>(this) ||
718 isa<NonTypeTemplateParmDecl>(this) ||
719 !isa<CXXRecordDecl>(getDeclContext()) ||
721 isa<StaticAssertDecl>(this) ||
722 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
723 // as DeclContext (?).
724 isa<ParmVarDecl>(this) ||
725 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
726 // AS_none as access specifier.
727 isa<CXXRecordDecl>(this) ||
728 isa<ClassScopeFunctionSpecializationDecl>(this))
731 assert(Access != AS_none &&
732 "Access specifier is AS_none inside a record decl");
737 static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
738 static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
740 const FunctionType *Decl::getFunctionType(bool BlocksToo) const {
742 if (const ValueDecl *D = dyn_cast<ValueDecl>(this))
744 else if (const TypedefNameDecl *D = dyn_cast<TypedefNameDecl>(this))
745 Ty = D->getUnderlyingType();
749 if (Ty->isFunctionPointerType())
750 Ty = Ty->getAs<PointerType>()->getPointeeType();
751 else if (BlocksToo && Ty->isBlockPointerType())
752 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
754 return Ty->getAs<FunctionType>();
758 /// Starting at a given context (a Decl or DeclContext), look for a
759 /// code context that is not a closure (a lambda, block, etc.).
760 template <class T> static Decl *getNonClosureContext(T *D) {
761 if (getKind(D) == Decl::CXXMethod) {
762 CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
763 if (MD->getOverloadedOperator() == OO_Call &&
764 MD->getParent()->isLambda())
765 return getNonClosureContext(MD->getParent()->getParent());
767 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
769 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
771 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
772 return getNonClosureContext(BD->getParent());
773 } else if (CapturedDecl *CD = dyn_cast<CapturedDecl>(D)) {
774 return getNonClosureContext(CD->getParent());
780 Decl *Decl::getNonClosureContext() {
781 return ::getNonClosureContext(this);
784 Decl *DeclContext::getNonClosureAncestor() {
785 return ::getNonClosureContext(this);
788 //===----------------------------------------------------------------------===//
789 // DeclContext Implementation
790 //===----------------------------------------------------------------------===//
792 bool DeclContext::classof(const Decl *D) {
793 switch (D->getKind()) {
794 #define DECL(NAME, BASE)
795 #define DECL_CONTEXT(NAME) case Decl::NAME:
796 #define DECL_CONTEXT_BASE(NAME)
797 #include "clang/AST/DeclNodes.inc"
800 #define DECL(NAME, BASE)
801 #define DECL_CONTEXT_BASE(NAME) \
802 if (D->getKind() >= Decl::first##NAME && \
803 D->getKind() <= Decl::last##NAME) \
805 #include "clang/AST/DeclNodes.inc"
810 DeclContext::~DeclContext() { }
812 /// \brief Find the parent context of this context that will be
813 /// used for unqualified name lookup.
815 /// Generally, the parent lookup context is the semantic context. However, for
816 /// a friend function the parent lookup context is the lexical context, which
817 /// is the class in which the friend is declared.
818 DeclContext *DeclContext::getLookupParent() {
819 // FIXME: Find a better way to identify friends
820 if (isa<FunctionDecl>(this))
821 if (getParent()->getRedeclContext()->isFileContext() &&
822 getLexicalParent()->getRedeclContext()->isRecord())
823 return getLexicalParent();
828 bool DeclContext::isInlineNamespace() const {
829 return isNamespace() &&
830 cast<NamespaceDecl>(this)->isInline();
833 bool DeclContext::isStdNamespace() const {
837 const NamespaceDecl *ND = cast<NamespaceDecl>(this);
838 if (ND->isInline()) {
839 return ND->getParent()->isStdNamespace();
842 if (!getParent()->getRedeclContext()->isTranslationUnit())
845 const IdentifierInfo *II = ND->getIdentifier();
846 return II && II->isStr("std");
849 bool DeclContext::isDependentContext() const {
853 if (isa<ClassTemplatePartialSpecializationDecl>(this))
856 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
857 if (Record->getDescribedClassTemplate())
860 if (Record->isDependentLambda())
864 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
865 if (Function->getDescribedFunctionTemplate())
868 // Friend function declarations are dependent if their *lexical*
869 // context is dependent.
870 if (cast<Decl>(this)->getFriendObjectKind())
871 return getLexicalParent()->isDependentContext();
874 // FIXME: A variable template is a dependent context, but is not a
875 // DeclContext. A context within it (such as a lambda-expression)
876 // should be considered dependent.
878 return getParent() && getParent()->isDependentContext();
881 bool DeclContext::isTransparentContext() const {
882 if (DeclKind == Decl::Enum)
883 return !cast<EnumDecl>(this)->isScoped();
884 else if (DeclKind == Decl::LinkageSpec)
890 static bool isLinkageSpecContext(const DeclContext *DC,
891 LinkageSpecDecl::LanguageIDs ID) {
892 while (DC->getDeclKind() != Decl::TranslationUnit) {
893 if (DC->getDeclKind() == Decl::LinkageSpec)
894 return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
895 DC = DC->getLexicalParent();
900 bool DeclContext::isExternCContext() const {
901 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_c);
904 bool DeclContext::isExternCXXContext() const {
905 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_cxx);
908 bool DeclContext::Encloses(const DeclContext *DC) const {
909 if (getPrimaryContext() != this)
910 return getPrimaryContext()->Encloses(DC);
912 for (; DC; DC = DC->getParent())
913 if (DC->getPrimaryContext() == this)
918 DeclContext *DeclContext::getPrimaryContext() {
920 case Decl::TranslationUnit:
921 case Decl::ExternCContext:
922 case Decl::LinkageSpec:
925 // There is only one DeclContext for these entities.
928 case Decl::Namespace:
929 // The original namespace is our primary context.
930 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
932 case Decl::ObjCMethod:
935 case Decl::ObjCInterface:
936 if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
941 case Decl::ObjCProtocol:
942 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
947 case Decl::ObjCCategory:
950 case Decl::ObjCImplementation:
951 case Decl::ObjCCategoryImpl:
955 if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
956 // If this is a tag type that has a definition or is currently
957 // being defined, that definition is our primary context.
958 TagDecl *Tag = cast<TagDecl>(this);
960 if (TagDecl *Def = Tag->getDefinition())
963 if (const TagType *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) {
964 // Note, TagType::getDecl returns the (partial) definition one exists.
965 TagDecl *PossiblePartialDef = TagTy->getDecl();
966 if (PossiblePartialDef->isBeingDefined())
967 return PossiblePartialDef;
969 assert(isa<InjectedClassNameType>(Tag->getTypeForDecl()));
975 assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
976 "Unknown DeclContext kind");
982 DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
985 if (DeclKind != Decl::Namespace) {
986 Contexts.push_back(this);
990 NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
991 for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
992 N = N->getPreviousDecl())
993 Contexts.push_back(N);
995 std::reverse(Contexts.begin(), Contexts.end());
998 std::pair<Decl *, Decl *>
999 DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
1000 bool FieldsAlreadyLoaded) {
1001 // Build up a chain of declarations via the Decl::NextInContextAndBits field.
1002 Decl *FirstNewDecl = nullptr;
1003 Decl *PrevDecl = nullptr;
1004 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1005 if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
1010 PrevDecl->NextInContextAndBits.setPointer(D);
1017 return std::make_pair(FirstNewDecl, PrevDecl);
1020 /// \brief We have just acquired external visible storage, and we already have
1021 /// built a lookup map. For every name in the map, pull in the new names from
1022 /// the external storage.
1023 void DeclContext::reconcileExternalVisibleStorage() const {
1024 assert(NeedToReconcileExternalVisibleStorage && LookupPtr);
1025 NeedToReconcileExternalVisibleStorage = false;
1027 for (auto &Lookup : *LookupPtr)
1028 Lookup.second.setHasExternalDecls();
1031 /// \brief Load the declarations within this lexical storage from an
1032 /// external source.
1033 /// \return \c true if any declarations were added.
1035 DeclContext::LoadLexicalDeclsFromExternalStorage() const {
1036 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1037 assert(hasExternalLexicalStorage() && Source && "No external storage?");
1039 // Notify that we have a DeclContext that is initializing.
1040 ExternalASTSource::Deserializing ADeclContext(Source);
1042 // Load the external declarations, if any.
1043 SmallVector<Decl*, 64> Decls;
1044 ExternalLexicalStorage = false;
1045 switch (Source->FindExternalLexicalDecls(this, Decls)) {
1050 case ELR_AlreadyLoaded:
1057 // We may have already loaded just the fields of this record, in which case
1058 // we need to ignore them.
1059 bool FieldsAlreadyLoaded = false;
1060 if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
1061 FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
1063 // Splice the newly-read declarations into the beginning of the list
1065 Decl *ExternalFirst, *ExternalLast;
1066 std::tie(ExternalFirst, ExternalLast) =
1067 BuildDeclChain(Decls, FieldsAlreadyLoaded);
1068 ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
1069 FirstDecl = ExternalFirst;
1071 LastDecl = ExternalLast;
1075 DeclContext::lookup_result
1076 ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
1077 DeclarationName Name) {
1078 ASTContext &Context = DC->getParentASTContext();
1079 StoredDeclsMap *Map;
1080 if (!(Map = DC->LookupPtr))
1081 Map = DC->CreateStoredDeclsMap(Context);
1082 if (DC->NeedToReconcileExternalVisibleStorage)
1083 DC->reconcileExternalVisibleStorage();
1085 (*Map)[Name].removeExternalDecls();
1087 return DeclContext::lookup_result();
1090 DeclContext::lookup_result
1091 ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
1092 DeclarationName Name,
1093 ArrayRef<NamedDecl*> Decls) {
1094 ASTContext &Context = DC->getParentASTContext();
1095 StoredDeclsMap *Map;
1096 if (!(Map = DC->LookupPtr))
1097 Map = DC->CreateStoredDeclsMap(Context);
1098 if (DC->NeedToReconcileExternalVisibleStorage)
1099 DC->reconcileExternalVisibleStorage();
1101 StoredDeclsList &List = (*Map)[Name];
1103 // Clear out any old external visible declarations, to avoid quadratic
1104 // performance in the redeclaration checks below.
1105 List.removeExternalDecls();
1107 if (!List.isNull()) {
1108 // We have both existing declarations and new declarations for this name.
1109 // Some of the declarations may simply replace existing ones. Handle those
1111 llvm::SmallVector<unsigned, 8> Skip;
1112 for (unsigned I = 0, N = Decls.size(); I != N; ++I)
1113 if (List.HandleRedeclaration(Decls[I], /*IsKnownNewer*/false))
1115 Skip.push_back(Decls.size());
1117 // Add in any new declarations.
1118 unsigned SkipPos = 0;
1119 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1120 if (I == Skip[SkipPos])
1123 List.AddSubsequentDecl(Decls[I]);
1126 // Convert the array to a StoredDeclsList.
1127 for (ArrayRef<NamedDecl*>::iterator
1128 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1130 List.setOnlyValue(*I);
1132 List.AddSubsequentDecl(*I);
1136 return List.getLookupResult();
1139 DeclContext::decl_iterator DeclContext::decls_begin() const {
1140 if (hasExternalLexicalStorage())
1141 LoadLexicalDeclsFromExternalStorage();
1142 return decl_iterator(FirstDecl);
1145 bool DeclContext::decls_empty() const {
1146 if (hasExternalLexicalStorage())
1147 LoadLexicalDeclsFromExternalStorage();
1152 bool DeclContext::containsDecl(Decl *D) const {
1153 return (D->getLexicalDeclContext() == this &&
1154 (D->NextInContextAndBits.getPointer() || D == LastDecl));
1157 void DeclContext::removeDecl(Decl *D) {
1158 assert(D->getLexicalDeclContext() == this &&
1159 "decl being removed from non-lexical context");
1160 assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
1161 "decl is not in decls list");
1163 // Remove D from the decl chain. This is O(n) but hopefully rare.
1164 if (D == FirstDecl) {
1166 FirstDecl = LastDecl = nullptr;
1168 FirstDecl = D->NextInContextAndBits.getPointer();
1170 for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
1171 assert(I && "decl not found in linked list");
1172 if (I->NextInContextAndBits.getPointer() == D) {
1173 I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
1174 if (D == LastDecl) LastDecl = I;
1180 // Mark that D is no longer in the decl chain.
1181 D->NextInContextAndBits.setPointer(nullptr);
1183 // Remove D from the lookup table if necessary.
1184 if (isa<NamedDecl>(D)) {
1185 NamedDecl *ND = cast<NamedDecl>(D);
1187 // Remove only decls that have a name
1188 if (!ND->getDeclName()) return;
1190 StoredDeclsMap *Map = getPrimaryContext()->LookupPtr;
1193 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1194 assert(Pos != Map->end() && "no lookup entry for decl");
1195 if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
1196 Pos->second.remove(ND);
1200 void DeclContext::addHiddenDecl(Decl *D) {
1201 assert(D->getLexicalDeclContext() == this &&
1202 "Decl inserted into wrong lexical context");
1203 assert(!D->getNextDeclInContext() && D != LastDecl &&
1204 "Decl already inserted into a DeclContext");
1207 LastDecl->NextInContextAndBits.setPointer(D);
1210 FirstDecl = LastDecl = D;
1213 // Notify a C++ record declaration that we've added a member, so it can
1214 // update it's class-specific state.
1215 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1216 Record->addedMember(D);
1218 // If this is a newly-created (not de-serialized) import declaration, wire
1219 // it in to the list of local import declarations.
1220 if (!D->isFromASTFile()) {
1221 if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
1222 D->getASTContext().addedLocalImportDecl(Import);
1226 void DeclContext::addDecl(Decl *D) {
1229 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1230 ND->getDeclContext()->getPrimaryContext()->
1231 makeDeclVisibleInContextWithFlags(ND, false, true);
1234 void DeclContext::addDeclInternal(Decl *D) {
1237 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1238 ND->getDeclContext()->getPrimaryContext()->
1239 makeDeclVisibleInContextWithFlags(ND, true, true);
1242 /// shouldBeHidden - Determine whether a declaration which was declared
1243 /// within its semantic context should be invisible to qualified name lookup.
1244 static bool shouldBeHidden(NamedDecl *D) {
1245 // Skip unnamed declarations.
1246 if (!D->getDeclName())
1249 // Skip entities that can't be found by name lookup into a particular
1251 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1252 D->isTemplateParameter())
1255 // Skip template specializations.
1256 // FIXME: This feels like a hack. Should DeclarationName support
1257 // template-ids, or is there a better way to keep specializations
1258 // from being visible?
1259 if (isa<ClassTemplateSpecializationDecl>(D))
1261 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1262 if (FD->isFunctionTemplateSpecialization())
1268 /// buildLookup - Build the lookup data structure with all of the
1269 /// declarations in this DeclContext (and any other contexts linked
1270 /// to it or transparent contexts nested within it) and return it.
1272 /// Note that the produced map may miss out declarations from an
1273 /// external source. If it does, those entries will be marked with
1274 /// the 'hasExternalDecls' flag.
1275 StoredDeclsMap *DeclContext::buildLookup() {
1276 assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1278 if (!HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups)
1281 SmallVector<DeclContext *, 2> Contexts;
1282 collectAllContexts(Contexts);
1284 if (HasLazyExternalLexicalLookups) {
1285 HasLazyExternalLexicalLookups = false;
1286 for (auto *DC : Contexts) {
1287 if (DC->hasExternalLexicalStorage())
1288 HasLazyLocalLexicalLookups |=
1289 DC->LoadLexicalDeclsFromExternalStorage();
1292 if (!HasLazyLocalLexicalLookups)
1296 for (auto *DC : Contexts)
1297 buildLookupImpl(DC, hasExternalVisibleStorage());
1299 // We no longer have any lazy decls.
1300 HasLazyLocalLexicalLookups = false;
1304 /// buildLookupImpl - Build part of the lookup data structure for the
1305 /// declarations contained within DCtx, which will either be this
1306 /// DeclContext, a DeclContext linked to it, or a transparent context
1307 /// nested within it.
1308 void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {
1309 for (Decl *D : DCtx->noload_decls()) {
1310 // Insert this declaration into the lookup structure, but only if
1311 // it's semantically within its decl context. Any other decls which
1312 // should be found in this context are added eagerly.
1314 // If it's from an AST file, don't add it now. It'll get handled by
1315 // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1316 // in C++, we do not track external visible decls for the TU, so in
1317 // that case we need to collect them all here.
1318 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1319 if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1320 (!ND->isFromASTFile() ||
1321 (isTranslationUnit() &&
1322 !getParentASTContext().getLangOpts().CPlusPlus)))
1323 makeDeclVisibleInContextImpl(ND, Internal);
1325 // If this declaration is itself a transparent declaration context
1326 // or inline namespace, add the members of this declaration of that
1327 // context (recursively).
1328 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
1329 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1330 buildLookupImpl(InnerCtx, Internal);
1334 NamedDecl *const DeclContextLookupResult::SingleElementDummyList = nullptr;
1336 DeclContext::lookup_result
1337 DeclContext::lookup(DeclarationName Name) const {
1338 assert(DeclKind != Decl::LinkageSpec &&
1339 "Should not perform lookups into linkage specs!");
1341 const DeclContext *PrimaryContext = getPrimaryContext();
1342 if (PrimaryContext != this)
1343 return PrimaryContext->lookup(Name);
1345 // If we have an external source, ensure that any later redeclarations of this
1346 // context have been loaded, since they may add names to the result of this
1347 // lookup (or add external visible storage).
1348 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1350 (void)cast<Decl>(this)->getMostRecentDecl();
1352 if (hasExternalVisibleStorage()) {
1353 assert(Source && "external visible storage but no external source?");
1355 if (NeedToReconcileExternalVisibleStorage)
1356 reconcileExternalVisibleStorage();
1358 StoredDeclsMap *Map = LookupPtr;
1360 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
1361 // FIXME: Make buildLookup const?
1362 Map = const_cast<DeclContext*>(this)->buildLookup();
1365 Map = CreateStoredDeclsMap(getParentASTContext());
1367 // If we have a lookup result with no external decls, we are done.
1368 std::pair<StoredDeclsMap::iterator, bool> R =
1369 Map->insert(std::make_pair(Name, StoredDeclsList()));
1370 if (!R.second && !R.first->second.hasExternalDecls())
1371 return R.first->second.getLookupResult();
1373 if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) {
1374 if (StoredDeclsMap *Map = LookupPtr) {
1375 StoredDeclsMap::iterator I = Map->find(Name);
1376 if (I != Map->end())
1377 return I->second.getLookupResult();
1381 return lookup_result();
1384 StoredDeclsMap *Map = LookupPtr;
1385 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
1386 Map = const_cast<DeclContext*>(this)->buildLookup();
1389 return lookup_result();
1391 StoredDeclsMap::iterator I = Map->find(Name);
1392 if (I == Map->end())
1393 return lookup_result();
1395 return I->second.getLookupResult();
1398 DeclContext::lookup_result
1399 DeclContext::noload_lookup(DeclarationName Name) {
1400 assert(DeclKind != Decl::LinkageSpec &&
1401 "Should not perform lookups into linkage specs!");
1403 DeclContext *PrimaryContext = getPrimaryContext();
1404 if (PrimaryContext != this)
1405 return PrimaryContext->noload_lookup(Name);
1407 // If we have any lazy lexical declarations not in our lookup map, add them
1408 // now. Don't import any external declarations, not even if we know we have
1409 // some missing from the external visible lookups.
1410 if (HasLazyLocalLexicalLookups) {
1411 SmallVector<DeclContext *, 2> Contexts;
1412 collectAllContexts(Contexts);
1413 for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
1414 buildLookupImpl(Contexts[I], hasExternalVisibleStorage());
1415 HasLazyLocalLexicalLookups = false;
1418 StoredDeclsMap *Map = LookupPtr;
1420 return lookup_result();
1422 StoredDeclsMap::iterator I = Map->find(Name);
1423 return I != Map->end() ? I->second.getLookupResult()
1427 void DeclContext::localUncachedLookup(DeclarationName Name,
1428 SmallVectorImpl<NamedDecl *> &Results) {
1431 // If there's no external storage, just perform a normal lookup and copy
1433 if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
1434 lookup_result LookupResults = lookup(Name);
1435 Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
1439 // If we have a lookup table, check there first. Maybe we'll get lucky.
1440 // FIXME: Should we be checking these flags on the primary context?
1441 if (Name && !HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups) {
1442 if (StoredDeclsMap *Map = LookupPtr) {
1443 StoredDeclsMap::iterator Pos = Map->find(Name);
1444 if (Pos != Map->end()) {
1445 Results.insert(Results.end(),
1446 Pos->second.getLookupResult().begin(),
1447 Pos->second.getLookupResult().end());
1453 // Slow case: grovel through the declarations in our chain looking for
1455 // FIXME: If we have lazy external declarations, this will not find them!
1456 // FIXME: Should we CollectAllContexts and walk them all here?
1457 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1458 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1459 if (ND->getDeclName() == Name)
1460 Results.push_back(ND);
1464 DeclContext *DeclContext::getRedeclContext() {
1465 DeclContext *Ctx = this;
1466 // Skip through transparent contexts.
1467 while (Ctx->isTransparentContext())
1468 Ctx = Ctx->getParent();
1472 DeclContext *DeclContext::getEnclosingNamespaceContext() {
1473 DeclContext *Ctx = this;
1474 // Skip through non-namespace, non-translation-unit contexts.
1475 while (!Ctx->isFileContext())
1476 Ctx = Ctx->getParent();
1477 return Ctx->getPrimaryContext();
1480 RecordDecl *DeclContext::getOuterLexicalRecordContext() {
1481 // Loop until we find a non-record context.
1482 RecordDecl *OutermostRD = nullptr;
1483 DeclContext *DC = this;
1484 while (DC->isRecord()) {
1485 OutermostRD = cast<RecordDecl>(DC);
1486 DC = DC->getLexicalParent();
1491 bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1492 // For non-file contexts, this is equivalent to Equals.
1493 if (!isFileContext())
1494 return O->Equals(this);
1497 if (O->Equals(this))
1500 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1501 if (!NS || !NS->isInline())
1503 O = NS->getParent();
1509 void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1510 DeclContext *PrimaryDC = this->getPrimaryContext();
1511 DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1512 // If the decl is being added outside of its semantic decl context, we
1513 // need to ensure that we eagerly build the lookup information for it.
1514 PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
1517 void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1519 assert(this == getPrimaryContext() && "expected a primary DC");
1521 // Skip declarations within functions.
1522 if (isFunctionOrMethod())
1525 // Skip declarations which should be invisible to name lookup.
1526 if (shouldBeHidden(D))
1529 // If we already have a lookup data structure, perform the insertion into
1530 // it. If we might have externally-stored decls with this name, look them
1531 // up and perform the insertion. If this decl was declared outside its
1532 // semantic context, buildLookup won't add it, so add it now.
1534 // FIXME: As a performance hack, don't add such decls into the translation
1535 // unit unless we're in C++, since qualified lookup into the TU is never
1537 if (LookupPtr || hasExternalVisibleStorage() ||
1538 ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1539 (getParentASTContext().getLangOpts().CPlusPlus ||
1540 !isTranslationUnit()))) {
1541 // If we have lazily omitted any decls, they might have the same name as
1542 // the decl which we are adding, so build a full lookup table before adding
1545 makeDeclVisibleInContextImpl(D, Internal);
1547 HasLazyLocalLexicalLookups = true;
1550 // If we are a transparent context or inline namespace, insert into our
1551 // parent context, too. This operation is recursive.
1552 if (isTransparentContext() || isInlineNamespace())
1553 getParent()->getPrimaryContext()->
1554 makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1556 Decl *DCAsDecl = cast<Decl>(this);
1557 // Notify that a decl was made visible unless we are a Tag being defined.
1558 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1559 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1560 L->AddedVisibleDecl(this, D);
1563 void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1564 // Find or create the stored declaration map.
1565 StoredDeclsMap *Map = LookupPtr;
1567 ASTContext *C = &getParentASTContext();
1568 Map = CreateStoredDeclsMap(*C);
1571 // If there is an external AST source, load any declarations it knows about
1572 // with this declaration's name.
1573 // If the lookup table contains an entry about this name it means that we
1574 // have already checked the external source.
1576 if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1577 if (hasExternalVisibleStorage() &&
1578 Map->find(D->getDeclName()) == Map->end())
1579 Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1581 // Insert this declaration into the map.
1582 StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
1585 // If this is being added as part of loading an external declaration,
1586 // this may not be the only external declaration with this name.
1587 // In this case, we never try to replace an existing declaration; we'll
1588 // handle that when we finalize the list of declarations for this name.
1589 DeclNameEntries.setHasExternalDecls();
1590 DeclNameEntries.AddSubsequentDecl(D);
1594 if (DeclNameEntries.isNull()) {
1595 DeclNameEntries.setOnlyValue(D);
1599 if (DeclNameEntries.HandleRedeclaration(D, /*IsKnownNewer*/!Internal)) {
1600 // This declaration has replaced an existing one for which
1601 // declarationReplaces returns true.
1605 // Put this declaration into the appropriate slot.
1606 DeclNameEntries.AddSubsequentDecl(D);
1609 UsingDirectiveDecl *DeclContext::udir_iterator::operator*() const {
1610 return cast<UsingDirectiveDecl>(*I);
1613 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1615 DeclContext::udir_range DeclContext::using_directives() const {
1616 // FIXME: Use something more efficient than normal lookup for using
1617 // directives. In C++, using directives are looked up more than anything else.
1618 lookup_result Result = lookup(UsingDirectiveDecl::getName());
1619 return udir_range(Result.begin(), Result.end());
1622 //===----------------------------------------------------------------------===//
1623 // Creation and Destruction of StoredDeclsMaps. //
1624 //===----------------------------------------------------------------------===//
1626 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1627 assert(!LookupPtr && "context already has a decls map");
1628 assert(getPrimaryContext() == this &&
1629 "creating decls map on non-primary context");
1632 bool Dependent = isDependentContext();
1634 M = new DependentStoredDeclsMap();
1636 M = new StoredDeclsMap();
1637 M->Previous = C.LastSDM;
1638 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1643 void ASTContext::ReleaseDeclContextMaps() {
1644 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1645 // pointer because the subclass doesn't add anything that needs to
1647 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1650 void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1652 // Advance the iteration before we invalidate memory.
1653 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1656 delete static_cast<DependentStoredDeclsMap*>(Map);
1660 Map = Next.getPointer();
1661 Dependent = Next.getInt();
1665 DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1666 DeclContext *Parent,
1667 const PartialDiagnostic &PDiag) {
1668 assert(Parent->isDependentContext()
1669 && "cannot iterate dependent diagnostics of non-dependent context");
1670 Parent = Parent->getPrimaryContext();
1671 if (!Parent->LookupPtr)
1672 Parent->CreateStoredDeclsMap(C);
1674 DependentStoredDeclsMap *Map =
1675 static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr);
1677 // Allocate the copy of the PartialDiagnostic via the ASTContext's
1678 // BumpPtrAllocator, rather than the ASTContext itself.
1679 PartialDiagnostic::Storage *DiagStorage = nullptr;
1680 if (PDiag.hasStorage())
1681 DiagStorage = new (C) PartialDiagnostic::Storage;
1683 DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
1685 // TODO: Maybe we shouldn't reverse the order during insertion.
1686 DD->NextDiagnostic = Map->FirstDiagnostic;
1687 Map->FirstDiagnostic = DD;