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 return ::operator new(Size + Extra, Ctx);
72 Module *Decl::getOwningModuleSlow() const {
73 assert(isFromASTFile() && "Not from AST file?");
74 return getASTContext().getExternalSource()->getModule(getOwningModuleID());
77 const char *Decl::getDeclKindName() const {
79 default: llvm_unreachable("Declaration not in DeclNodes.inc!");
80 #define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
81 #define ABSTRACT_DECL(DECL)
82 #include "clang/AST/DeclNodes.inc"
86 void Decl::setInvalidDecl(bool Invalid) {
87 InvalidDecl = Invalid;
88 assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition());
89 if (Invalid && !isa<ParmVarDecl>(this)) {
90 // Defensive maneuver for ill-formed code: we're likely not to make it to
91 // a point where we set the access specifier, so default it to "public"
92 // to avoid triggering asserts elsewhere in the front end.
97 const char *DeclContext::getDeclKindName() const {
99 default: llvm_unreachable("Declaration context not in DeclNodes.inc!");
100 #define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
101 #define ABSTRACT_DECL(DECL)
102 #include "clang/AST/DeclNodes.inc"
106 bool Decl::StatisticsEnabled = false;
107 void Decl::EnableStatistics() {
108 StatisticsEnabled = true;
111 void Decl::PrintStats() {
112 llvm::errs() << "\n*** Decl Stats:\n";
115 #define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
116 #define ABSTRACT_DECL(DECL)
117 #include "clang/AST/DeclNodes.inc"
118 llvm::errs() << " " << totalDecls << " decls total.\n";
121 #define DECL(DERIVED, BASE) \
122 if (n##DERIVED##s > 0) { \
123 totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \
124 llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \
125 << sizeof(DERIVED##Decl) << " each (" \
126 << n##DERIVED##s * sizeof(DERIVED##Decl) \
129 #define ABSTRACT_DECL(DECL)
130 #include "clang/AST/DeclNodes.inc"
132 llvm::errs() << "Total bytes = " << totalBytes << "\n";
135 void Decl::add(Kind k) {
137 #define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
138 #define ABSTRACT_DECL(DECL)
139 #include "clang/AST/DeclNodes.inc"
143 bool Decl::isTemplateParameterPack() const {
144 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
145 return TTP->isParameterPack();
146 if (const NonTypeTemplateParmDecl *NTTP
147 = dyn_cast<NonTypeTemplateParmDecl>(this))
148 return NTTP->isParameterPack();
149 if (const TemplateTemplateParmDecl *TTP
150 = dyn_cast<TemplateTemplateParmDecl>(this))
151 return TTP->isParameterPack();
155 bool Decl::isParameterPack() const {
156 if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this))
157 return Parm->isParameterPack();
159 return isTemplateParameterPack();
162 FunctionDecl *Decl::getAsFunction() {
163 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
165 if (const FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(this))
166 return FTD->getTemplatedDecl();
170 bool Decl::isTemplateDecl() const {
171 return isa<TemplateDecl>(this);
174 const DeclContext *Decl::getParentFunctionOrMethod() const {
175 for (const DeclContext *DC = getDeclContext();
176 DC && !DC->isTranslationUnit() && !DC->isNamespace();
177 DC = DC->getParent())
178 if (DC->isFunctionOrMethod())
185 //===----------------------------------------------------------------------===//
186 // PrettyStackTraceDecl Implementation
187 //===----------------------------------------------------------------------===//
189 void PrettyStackTraceDecl::print(raw_ostream &OS) const {
190 SourceLocation TheLoc = Loc;
191 if (TheLoc.isInvalid() && TheDecl)
192 TheLoc = TheDecl->getLocation();
194 if (TheLoc.isValid()) {
195 TheLoc.print(OS, SM);
201 if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
203 DN->printQualifiedName(OS);
209 //===----------------------------------------------------------------------===//
210 // Decl Implementation
211 //===----------------------------------------------------------------------===//
213 // Out-of-line virtual method providing a home for Decl.
216 void Decl::setDeclContext(DeclContext *DC) {
220 void Decl::setLexicalDeclContext(DeclContext *DC) {
221 if (DC == getLexicalDeclContext())
225 setDeclContextsImpl(getDeclContext(), DC, getASTContext());
227 getMultipleDC()->LexicalDC = DC;
231 void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
233 if (SemaDC == LexicalDC) {
236 Decl::MultipleDC *MDC = new (Ctx) Decl::MultipleDC();
237 MDC->SemanticDC = SemaDC;
238 MDC->LexicalDC = LexicalDC;
243 bool Decl::isInAnonymousNamespace() const {
244 const DeclContext *DC = getDeclContext();
246 if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
247 if (ND->isAnonymousNamespace())
249 } while ((DC = DC->getParent()));
254 bool Decl::isInStdNamespace() const {
255 return getDeclContext()->isStdNamespace();
258 TranslationUnitDecl *Decl::getTranslationUnitDecl() {
259 if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
262 DeclContext *DC = getDeclContext();
263 assert(DC && "This decl is not contained in a translation unit!");
265 while (!DC->isTranslationUnit()) {
266 DC = DC->getParent();
267 assert(DC && "This decl is not contained in a translation unit!");
270 return cast<TranslationUnitDecl>(DC);
273 ASTContext &Decl::getASTContext() const {
274 return getTranslationUnitDecl()->getASTContext();
277 ASTMutationListener *Decl::getASTMutationListener() const {
278 return getASTContext().getASTMutationListener();
281 unsigned Decl::getMaxAlignment() const {
286 const AttrVec &V = getAttrs();
287 ASTContext &Ctx = getASTContext();
288 specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
290 Align = std::max(Align, I->getAlignment(Ctx));
294 bool Decl::isUsed(bool CheckUsedAttr) const {
298 // Check for used attribute.
299 if (CheckUsedAttr && hasAttr<UsedAttr>())
305 void Decl::markUsed(ASTContext &C) {
309 if (C.getASTMutationListener())
310 C.getASTMutationListener()->DeclarationMarkedUsed(this);
315 bool Decl::isReferenced() const {
319 // Check redeclarations.
320 for (auto I : redecls())
327 /// \brief Determine the availability of the given declaration based on
328 /// the target platform.
330 /// When it returns an availability result other than \c AR_Available,
331 /// if the \p Message parameter is non-NULL, it will be set to a
332 /// string describing why the entity is unavailable.
334 /// FIXME: Make these strings localizable, since they end up in
336 static AvailabilityResult CheckAvailability(ASTContext &Context,
337 const AvailabilityAttr *A,
338 std::string *Message) {
339 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
340 StringRef PrettyPlatformName
341 = AvailabilityAttr::getPrettyPlatformName(TargetPlatform);
342 if (PrettyPlatformName.empty())
343 PrettyPlatformName = TargetPlatform;
345 VersionTuple TargetMinVersion = Context.getTargetInfo().getPlatformMinVersion();
346 if (TargetMinVersion.empty())
349 // Match the platform name.
350 if (A->getPlatform()->getName() != TargetPlatform)
353 std::string HintMessage;
354 if (!A->getMessage().empty()) {
356 HintMessage += A->getMessage();
359 // Make sure that this declaration has not been marked 'unavailable'.
360 if (A->getUnavailable()) {
363 llvm::raw_string_ostream Out(*Message);
364 Out << "not available on " << PrettyPlatformName
368 return AR_Unavailable;
371 // Make sure that this declaration has already been introduced.
372 if (!A->getIntroduced().empty() &&
373 TargetMinVersion < A->getIntroduced()) {
376 llvm::raw_string_ostream Out(*Message);
377 Out << "introduced in " << PrettyPlatformName << ' '
378 << A->getIntroduced() << HintMessage;
381 return AR_NotYetIntroduced;
384 // Make sure that this declaration hasn't been obsoleted.
385 if (!A->getObsoleted().empty() && TargetMinVersion >= A->getObsoleted()) {
388 llvm::raw_string_ostream Out(*Message);
389 Out << "obsoleted in " << PrettyPlatformName << ' '
390 << A->getObsoleted() << HintMessage;
393 return AR_Unavailable;
396 // Make sure that this declaration hasn't been deprecated.
397 if (!A->getDeprecated().empty() && TargetMinVersion >= A->getDeprecated()) {
400 llvm::raw_string_ostream Out(*Message);
401 Out << "first deprecated in " << PrettyPlatformName << ' '
402 << A->getDeprecated() << HintMessage;
405 return AR_Deprecated;
411 AvailabilityResult Decl::getAvailability(std::string *Message) const {
412 AvailabilityResult Result = AR_Available;
413 std::string ResultMessage;
415 for (const auto *A : attrs()) {
416 if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
417 if (Result >= AR_Deprecated)
421 ResultMessage = Deprecated->getMessage();
423 Result = AR_Deprecated;
427 if (const auto *Unavailable = dyn_cast<UnavailableAttr>(A)) {
429 *Message = Unavailable->getMessage();
430 return AR_Unavailable;
433 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
434 AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
437 if (AR == AR_Unavailable)
438 return AR_Unavailable;
443 ResultMessage.swap(*Message);
450 Message->swap(ResultMessage);
454 bool Decl::canBeWeakImported(bool &IsDefinition) const {
455 IsDefinition = false;
457 // Variables, if they aren't definitions.
458 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
459 if (Var->isThisDeclarationADefinition()) {
465 // Functions, if they aren't definitions.
466 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
473 // Objective-C classes, if this is the non-fragile runtime.
474 } else if (isa<ObjCInterfaceDecl>(this) &&
475 getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
484 bool Decl::isWeakImported() const {
486 if (!canBeWeakImported(IsDefinition))
489 for (const auto *A : attrs()) {
490 if (isa<WeakImportAttr>(A))
493 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
494 if (CheckAvailability(getASTContext(), Availability,
495 nullptr) == AR_NotYetIntroduced)
503 unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
514 case NonTypeTemplateParm:
518 return IDNS_Ordinary;
522 return IDNS_Ordinary | IDNS_Member;
524 case ObjCCompatibleAlias:
526 return IDNS_Ordinary | IDNS_Type;
530 case TypeAliasTemplate:
531 case UnresolvedUsingTypename:
532 case TemplateTypeParm:
533 return IDNS_Ordinary | IDNS_Type;
536 return 0; // we'll actually overwrite this later
538 case UnresolvedUsingValue:
539 return IDNS_Ordinary | IDNS_Using;
545 return IDNS_ObjCProtocol;
548 case ObjCAtDefsField:
555 return IDNS_Tag | IDNS_Type;
559 return IDNS_Namespace;
561 case FunctionTemplate:
563 return IDNS_Ordinary;
566 case TemplateTemplateParm:
567 return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
576 case ObjCPropertyImpl:
579 case TranslationUnit:
582 case ClassTemplateSpecialization:
583 case ClassTemplatePartialSpecialization:
584 case ClassScopeFunctionSpecialization:
585 case VarTemplateSpecialization:
586 case VarTemplatePartialSpecialization:
587 case ObjCImplementation:
589 case ObjCCategoryImpl:
591 case OMPThreadPrivate:
593 // Never looked up by name.
597 llvm_unreachable("Invalid DeclKind!");
600 void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
601 assert(!HasAttrs && "Decl already contains attrs.");
603 AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
604 assert(AttrBlank.empty() && "HasAttrs was wrong?");
610 void Decl::dropAttrs() {
611 if (!HasAttrs) return;
614 getASTContext().eraseDeclAttrs(this);
617 const AttrVec &Decl::getAttrs() const {
618 assert(HasAttrs && "No attrs to get!");
619 return getASTContext().getDeclAttrs(this);
622 Decl *Decl::castFromDeclContext (const DeclContext *D) {
623 Decl::Kind DK = D->getDeclKind();
625 #define DECL(NAME, BASE)
626 #define DECL_CONTEXT(NAME) \
628 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
629 #define DECL_CONTEXT_BASE(NAME)
630 #include "clang/AST/DeclNodes.inc"
632 #define DECL(NAME, BASE)
633 #define DECL_CONTEXT_BASE(NAME) \
634 if (DK >= first##NAME && DK <= last##NAME) \
635 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
636 #include "clang/AST/DeclNodes.inc"
637 llvm_unreachable("a decl that inherits DeclContext isn't handled");
641 DeclContext *Decl::castToDeclContext(const Decl *D) {
642 Decl::Kind DK = D->getKind();
644 #define DECL(NAME, BASE)
645 #define DECL_CONTEXT(NAME) \
647 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
648 #define DECL_CONTEXT_BASE(NAME)
649 #include "clang/AST/DeclNodes.inc"
651 #define DECL(NAME, BASE)
652 #define DECL_CONTEXT_BASE(NAME) \
653 if (DK >= first##NAME && DK <= last##NAME) \
654 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
655 #include "clang/AST/DeclNodes.inc"
656 llvm_unreachable("a decl that inherits DeclContext isn't handled");
660 SourceLocation Decl::getBodyRBrace() const {
661 // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
662 // FunctionDecl stores EndRangeLoc for this purpose.
663 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
664 const FunctionDecl *Definition;
665 if (FD->hasBody(Definition))
666 return Definition->getSourceRange().getEnd();
667 return SourceLocation();
670 if (Stmt *Body = getBody())
671 return Body->getSourceRange().getEnd();
673 return SourceLocation();
676 bool Decl::AccessDeclContextSanity() const {
678 // Suppress this check if any of the following hold:
679 // 1. this is the translation unit (and thus has no parent)
680 // 2. this is a template parameter (and thus doesn't belong to its context)
681 // 3. this is a non-type template parameter
682 // 4. the context is not a record
684 // 6. it's a C++0x static_assert.
685 if (isa<TranslationUnitDecl>(this) ||
686 isa<TemplateTypeParmDecl>(this) ||
687 isa<NonTypeTemplateParmDecl>(this) ||
688 !isa<CXXRecordDecl>(getDeclContext()) ||
690 isa<StaticAssertDecl>(this) ||
691 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
692 // as DeclContext (?).
693 isa<ParmVarDecl>(this) ||
694 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
695 // AS_none as access specifier.
696 isa<CXXRecordDecl>(this) ||
697 isa<ClassScopeFunctionSpecializationDecl>(this))
700 assert(Access != AS_none &&
701 "Access specifier is AS_none inside a record decl");
706 static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
707 static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
709 const FunctionType *Decl::getFunctionType(bool BlocksToo) const {
711 if (const ValueDecl *D = dyn_cast<ValueDecl>(this))
713 else if (const TypedefNameDecl *D = dyn_cast<TypedefNameDecl>(this))
714 Ty = D->getUnderlyingType();
718 if (Ty->isFunctionPointerType())
719 Ty = Ty->getAs<PointerType>()->getPointeeType();
720 else if (BlocksToo && Ty->isBlockPointerType())
721 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
723 return Ty->getAs<FunctionType>();
727 /// Starting at a given context (a Decl or DeclContext), look for a
728 /// code context that is not a closure (a lambda, block, etc.).
729 template <class T> static Decl *getNonClosureContext(T *D) {
730 if (getKind(D) == Decl::CXXMethod) {
731 CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
732 if (MD->getOverloadedOperator() == OO_Call &&
733 MD->getParent()->isLambda())
734 return getNonClosureContext(MD->getParent()->getParent());
736 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
738 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
740 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
741 return getNonClosureContext(BD->getParent());
742 } else if (CapturedDecl *CD = dyn_cast<CapturedDecl>(D)) {
743 return getNonClosureContext(CD->getParent());
749 Decl *Decl::getNonClosureContext() {
750 return ::getNonClosureContext(this);
753 Decl *DeclContext::getNonClosureAncestor() {
754 return ::getNonClosureContext(this);
757 //===----------------------------------------------------------------------===//
758 // DeclContext Implementation
759 //===----------------------------------------------------------------------===//
761 bool DeclContext::classof(const Decl *D) {
762 switch (D->getKind()) {
763 #define DECL(NAME, BASE)
764 #define DECL_CONTEXT(NAME) case Decl::NAME:
765 #define DECL_CONTEXT_BASE(NAME)
766 #include "clang/AST/DeclNodes.inc"
769 #define DECL(NAME, BASE)
770 #define DECL_CONTEXT_BASE(NAME) \
771 if (D->getKind() >= Decl::first##NAME && \
772 D->getKind() <= Decl::last##NAME) \
774 #include "clang/AST/DeclNodes.inc"
779 DeclContext::~DeclContext() { }
781 /// \brief Find the parent context of this context that will be
782 /// used for unqualified name lookup.
784 /// Generally, the parent lookup context is the semantic context. However, for
785 /// a friend function the parent lookup context is the lexical context, which
786 /// is the class in which the friend is declared.
787 DeclContext *DeclContext::getLookupParent() {
788 // FIXME: Find a better way to identify friends
789 if (isa<FunctionDecl>(this))
790 if (getParent()->getRedeclContext()->isFileContext() &&
791 getLexicalParent()->getRedeclContext()->isRecord())
792 return getLexicalParent();
797 bool DeclContext::isInlineNamespace() const {
798 return isNamespace() &&
799 cast<NamespaceDecl>(this)->isInline();
802 bool DeclContext::isStdNamespace() const {
806 const NamespaceDecl *ND = cast<NamespaceDecl>(this);
807 if (ND->isInline()) {
808 return ND->getParent()->isStdNamespace();
811 if (!getParent()->getRedeclContext()->isTranslationUnit())
814 const IdentifierInfo *II = ND->getIdentifier();
815 return II && II->isStr("std");
818 bool DeclContext::isDependentContext() const {
822 if (isa<ClassTemplatePartialSpecializationDecl>(this))
825 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
826 if (Record->getDescribedClassTemplate())
829 if (Record->isDependentLambda())
833 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
834 if (Function->getDescribedFunctionTemplate())
837 // Friend function declarations are dependent if their *lexical*
838 // context is dependent.
839 if (cast<Decl>(this)->getFriendObjectKind())
840 return getLexicalParent()->isDependentContext();
843 return getParent() && getParent()->isDependentContext();
846 bool DeclContext::isTransparentContext() const {
847 if (DeclKind == Decl::Enum)
848 return !cast<EnumDecl>(this)->isScoped();
849 else if (DeclKind == Decl::LinkageSpec)
855 static bool isLinkageSpecContext(const DeclContext *DC,
856 LinkageSpecDecl::LanguageIDs ID) {
857 while (DC->getDeclKind() != Decl::TranslationUnit) {
858 if (DC->getDeclKind() == Decl::LinkageSpec)
859 return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
860 DC = DC->getLexicalParent();
865 bool DeclContext::isExternCContext() const {
866 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_c);
869 bool DeclContext::isExternCXXContext() const {
870 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_cxx);
873 bool DeclContext::Encloses(const DeclContext *DC) const {
874 if (getPrimaryContext() != this)
875 return getPrimaryContext()->Encloses(DC);
877 for (; DC; DC = DC->getParent())
878 if (DC->getPrimaryContext() == this)
883 DeclContext *DeclContext::getPrimaryContext() {
885 case Decl::TranslationUnit:
886 case Decl::LinkageSpec:
889 // There is only one DeclContext for these entities.
892 case Decl::Namespace:
893 // The original namespace is our primary context.
894 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
896 case Decl::ObjCMethod:
899 case Decl::ObjCInterface:
900 if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
905 case Decl::ObjCProtocol:
906 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
911 case Decl::ObjCCategory:
914 case Decl::ObjCImplementation:
915 case Decl::ObjCCategoryImpl:
919 if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
920 // If this is a tag type that has a definition or is currently
921 // being defined, that definition is our primary context.
922 TagDecl *Tag = cast<TagDecl>(this);
924 if (TagDecl *Def = Tag->getDefinition())
927 if (const TagType *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) {
928 // Note, TagType::getDecl returns the (partial) definition one exists.
929 TagDecl *PossiblePartialDef = TagTy->getDecl();
930 if (PossiblePartialDef->isBeingDefined())
931 return PossiblePartialDef;
933 assert(isa<InjectedClassNameType>(Tag->getTypeForDecl()));
939 assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
940 "Unknown DeclContext kind");
946 DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
949 if (DeclKind != Decl::Namespace) {
950 Contexts.push_back(this);
954 NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
955 for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
956 N = N->getPreviousDecl())
957 Contexts.push_back(N);
959 std::reverse(Contexts.begin(), Contexts.end());
962 std::pair<Decl *, Decl *>
963 DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
964 bool FieldsAlreadyLoaded) {
965 // Build up a chain of declarations via the Decl::NextInContextAndBits field.
966 Decl *FirstNewDecl = nullptr;
967 Decl *PrevDecl = nullptr;
968 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
969 if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
974 PrevDecl->NextInContextAndBits.setPointer(D);
981 return std::make_pair(FirstNewDecl, PrevDecl);
984 /// \brief We have just acquired external visible storage, and we already have
985 /// built a lookup map. For every name in the map, pull in the new names from
986 /// the external storage.
987 void DeclContext::reconcileExternalVisibleStorage() const {
988 assert(NeedToReconcileExternalVisibleStorage && LookupPtr.getPointer());
989 NeedToReconcileExternalVisibleStorage = false;
991 for (auto &Lookup : *LookupPtr.getPointer())
992 Lookup.second.setHasExternalDecls();
995 /// \brief Load the declarations within this lexical storage from an
998 DeclContext::LoadLexicalDeclsFromExternalStorage() const {
999 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1000 assert(hasExternalLexicalStorage() && Source && "No external storage?");
1002 // Notify that we have a DeclContext that is initializing.
1003 ExternalASTSource::Deserializing ADeclContext(Source);
1005 // Load the external declarations, if any.
1006 SmallVector<Decl*, 64> Decls;
1007 ExternalLexicalStorage = false;
1008 switch (Source->FindExternalLexicalDecls(this, Decls)) {
1013 case ELR_AlreadyLoaded:
1020 // We may have already loaded just the fields of this record, in which case
1021 // we need to ignore them.
1022 bool FieldsAlreadyLoaded = false;
1023 if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
1024 FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
1026 // Splice the newly-read declarations into the beginning of the list
1028 Decl *ExternalFirst, *ExternalLast;
1029 std::tie(ExternalFirst, ExternalLast) =
1030 BuildDeclChain(Decls, FieldsAlreadyLoaded);
1031 ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
1032 FirstDecl = ExternalFirst;
1034 LastDecl = ExternalLast;
1037 DeclContext::lookup_result
1038 ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
1039 DeclarationName Name) {
1040 ASTContext &Context = DC->getParentASTContext();
1041 StoredDeclsMap *Map;
1042 if (!(Map = DC->LookupPtr.getPointer()))
1043 Map = DC->CreateStoredDeclsMap(Context);
1044 if (DC->NeedToReconcileExternalVisibleStorage)
1045 DC->reconcileExternalVisibleStorage();
1047 (*Map)[Name].removeExternalDecls();
1049 return DeclContext::lookup_result();
1052 DeclContext::lookup_result
1053 ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
1054 DeclarationName Name,
1055 ArrayRef<NamedDecl*> Decls) {
1056 ASTContext &Context = DC->getParentASTContext();
1057 StoredDeclsMap *Map;
1058 if (!(Map = DC->LookupPtr.getPointer()))
1059 Map = DC->CreateStoredDeclsMap(Context);
1060 if (DC->NeedToReconcileExternalVisibleStorage)
1061 DC->reconcileExternalVisibleStorage();
1063 StoredDeclsList &List = (*Map)[Name];
1065 // Clear out any old external visible declarations, to avoid quadratic
1066 // performance in the redeclaration checks below.
1067 List.removeExternalDecls();
1069 if (!List.isNull()) {
1070 // We have both existing declarations and new declarations for this name.
1071 // Some of the declarations may simply replace existing ones. Handle those
1073 llvm::SmallVector<unsigned, 8> Skip;
1074 for (unsigned I = 0, N = Decls.size(); I != N; ++I)
1075 if (List.HandleRedeclaration(Decls[I]))
1077 Skip.push_back(Decls.size());
1079 // Add in any new declarations.
1080 unsigned SkipPos = 0;
1081 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1082 if (I == Skip[SkipPos])
1085 List.AddSubsequentDecl(Decls[I]);
1088 // Convert the array to a StoredDeclsList.
1089 for (ArrayRef<NamedDecl*>::iterator
1090 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1092 List.setOnlyValue(*I);
1094 List.AddSubsequentDecl(*I);
1098 return List.getLookupResult();
1101 DeclContext::decl_iterator DeclContext::decls_begin() const {
1102 if (hasExternalLexicalStorage())
1103 LoadLexicalDeclsFromExternalStorage();
1104 return decl_iterator(FirstDecl);
1107 bool DeclContext::decls_empty() const {
1108 if (hasExternalLexicalStorage())
1109 LoadLexicalDeclsFromExternalStorage();
1114 bool DeclContext::containsDecl(Decl *D) const {
1115 return (D->getLexicalDeclContext() == this &&
1116 (D->NextInContextAndBits.getPointer() || D == LastDecl));
1119 void DeclContext::removeDecl(Decl *D) {
1120 assert(D->getLexicalDeclContext() == this &&
1121 "decl being removed from non-lexical context");
1122 assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
1123 "decl is not in decls list");
1125 // Remove D from the decl chain. This is O(n) but hopefully rare.
1126 if (D == FirstDecl) {
1128 FirstDecl = LastDecl = nullptr;
1130 FirstDecl = D->NextInContextAndBits.getPointer();
1132 for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
1133 assert(I && "decl not found in linked list");
1134 if (I->NextInContextAndBits.getPointer() == D) {
1135 I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
1136 if (D == LastDecl) LastDecl = I;
1142 // Mark that D is no longer in the decl chain.
1143 D->NextInContextAndBits.setPointer(nullptr);
1145 // Remove D from the lookup table if necessary.
1146 if (isa<NamedDecl>(D)) {
1147 NamedDecl *ND = cast<NamedDecl>(D);
1149 // Remove only decls that have a name
1150 if (!ND->getDeclName()) return;
1152 StoredDeclsMap *Map = getPrimaryContext()->LookupPtr.getPointer();
1155 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1156 assert(Pos != Map->end() && "no lookup entry for decl");
1157 if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
1158 Pos->second.remove(ND);
1162 void DeclContext::addHiddenDecl(Decl *D) {
1163 assert(D->getLexicalDeclContext() == this &&
1164 "Decl inserted into wrong lexical context");
1165 assert(!D->getNextDeclInContext() && D != LastDecl &&
1166 "Decl already inserted into a DeclContext");
1169 LastDecl->NextInContextAndBits.setPointer(D);
1172 FirstDecl = LastDecl = D;
1175 // Notify a C++ record declaration that we've added a member, so it can
1176 // update it's class-specific state.
1177 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1178 Record->addedMember(D);
1180 // If this is a newly-created (not de-serialized) import declaration, wire
1181 // it in to the list of local import declarations.
1182 if (!D->isFromASTFile()) {
1183 if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
1184 D->getASTContext().addedLocalImportDecl(Import);
1188 void DeclContext::addDecl(Decl *D) {
1191 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1192 ND->getDeclContext()->getPrimaryContext()->
1193 makeDeclVisibleInContextWithFlags(ND, false, true);
1196 void DeclContext::addDeclInternal(Decl *D) {
1199 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1200 ND->getDeclContext()->getPrimaryContext()->
1201 makeDeclVisibleInContextWithFlags(ND, true, true);
1204 /// shouldBeHidden - Determine whether a declaration which was declared
1205 /// within its semantic context should be invisible to qualified name lookup.
1206 static bool shouldBeHidden(NamedDecl *D) {
1207 // Skip unnamed declarations.
1208 if (!D->getDeclName())
1211 // Skip entities that can't be found by name lookup into a particular
1213 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1214 D->isTemplateParameter())
1217 // Skip template specializations.
1218 // FIXME: This feels like a hack. Should DeclarationName support
1219 // template-ids, or is there a better way to keep specializations
1220 // from being visible?
1221 if (isa<ClassTemplateSpecializationDecl>(D))
1223 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1224 if (FD->isFunctionTemplateSpecialization())
1230 /// buildLookup - Build the lookup data structure with all of the
1231 /// declarations in this DeclContext (and any other contexts linked
1232 /// to it or transparent contexts nested within it) and return it.
1234 /// Note that the produced map may miss out declarations from an
1235 /// external source. If it does, those entries will be marked with
1236 /// the 'hasExternalDecls' flag.
1237 StoredDeclsMap *DeclContext::buildLookup() {
1238 assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1240 // FIXME: Should we keep going if hasExternalVisibleStorage?
1241 if (!LookupPtr.getInt())
1242 return LookupPtr.getPointer();
1244 SmallVector<DeclContext *, 2> Contexts;
1245 collectAllContexts(Contexts);
1246 for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
1247 buildLookupImpl<&DeclContext::decls_begin,
1248 &DeclContext::decls_end>(Contexts[I]);
1250 // We no longer have any lazy decls.
1251 LookupPtr.setInt(false);
1252 return LookupPtr.getPointer();
1255 /// buildLookupImpl - Build part of the lookup data structure for the
1256 /// declarations contained within DCtx, which will either be this
1257 /// DeclContext, a DeclContext linked to it, or a transparent context
1258 /// nested within it.
1259 template<DeclContext::decl_iterator (DeclContext::*Begin)() const,
1260 DeclContext::decl_iterator (DeclContext::*End)() const>
1261 void DeclContext::buildLookupImpl(DeclContext *DCtx) {
1262 for (decl_iterator I = (DCtx->*Begin)(), E = (DCtx->*End)();
1266 // Insert this declaration into the lookup structure, but only if
1267 // it's semantically within its decl context. Any other decls which
1268 // should be found in this context are added eagerly.
1270 // If it's from an AST file, don't add it now. It'll get handled by
1271 // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1272 // in C++, we do not track external visible decls for the TU, so in
1273 // that case we need to collect them all here.
1274 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1275 if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1276 (!ND->isFromASTFile() ||
1277 (isTranslationUnit() &&
1278 !getParentASTContext().getLangOpts().CPlusPlus)))
1279 makeDeclVisibleInContextImpl(ND, false);
1281 // If this declaration is itself a transparent declaration context
1282 // or inline namespace, add the members of this declaration of that
1283 // context (recursively).
1284 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
1285 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1286 buildLookupImpl<Begin, End>(InnerCtx);
1290 DeclContext::lookup_result
1291 DeclContext::lookup(DeclarationName Name) {
1292 assert(DeclKind != Decl::LinkageSpec &&
1293 "Should not perform lookups into linkage specs!");
1295 DeclContext *PrimaryContext = getPrimaryContext();
1296 if (PrimaryContext != this)
1297 return PrimaryContext->lookup(Name);
1299 if (hasExternalVisibleStorage()) {
1300 if (NeedToReconcileExternalVisibleStorage)
1301 reconcileExternalVisibleStorage();
1303 StoredDeclsMap *Map = LookupPtr.getPointer();
1305 if (LookupPtr.getInt())
1306 Map = buildLookup();
1309 Map = CreateStoredDeclsMap(getParentASTContext());
1311 // If we have a lookup result with no external decls, we are done.
1312 std::pair<StoredDeclsMap::iterator, bool> R =
1313 Map->insert(std::make_pair(Name, StoredDeclsList()));
1314 if (!R.second && !R.first->second.hasExternalDecls())
1315 return R.first->second.getLookupResult();
1317 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1318 if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) {
1319 if (StoredDeclsMap *Map = LookupPtr.getPointer()) {
1320 StoredDeclsMap::iterator I = Map->find(Name);
1321 if (I != Map->end())
1322 return I->second.getLookupResult();
1326 return lookup_result(lookup_iterator(nullptr), lookup_iterator(nullptr));
1329 StoredDeclsMap *Map = LookupPtr.getPointer();
1330 if (LookupPtr.getInt())
1331 Map = buildLookup();
1334 return lookup_result(lookup_iterator(nullptr), lookup_iterator(nullptr));
1336 StoredDeclsMap::iterator I = Map->find(Name);
1337 if (I == Map->end())
1338 return lookup_result(lookup_iterator(nullptr), lookup_iterator(nullptr));
1340 return I->second.getLookupResult();
1343 DeclContext::lookup_result
1344 DeclContext::noload_lookup(DeclarationName Name) {
1345 assert(DeclKind != Decl::LinkageSpec &&
1346 "Should not perform lookups into linkage specs!");
1347 if (!hasExternalVisibleStorage())
1348 return lookup(Name);
1350 DeclContext *PrimaryContext = getPrimaryContext();
1351 if (PrimaryContext != this)
1352 return PrimaryContext->noload_lookup(Name);
1354 StoredDeclsMap *Map = LookupPtr.getPointer();
1355 if (LookupPtr.getInt()) {
1356 // Carefully build the lookup map, without deserializing anything.
1357 SmallVector<DeclContext *, 2> Contexts;
1358 collectAllContexts(Contexts);
1359 for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
1360 buildLookupImpl<&DeclContext::noload_decls_begin,
1361 &DeclContext::noload_decls_end>(Contexts[I]);
1363 // We no longer have any lazy decls.
1364 LookupPtr.setInt(false);
1366 // There may now be names for which we have local decls but are
1367 // missing the external decls. FIXME: Just set the hasExternalDecls
1368 // flag on those names that have external decls.
1369 NeedToReconcileExternalVisibleStorage = true;
1371 Map = LookupPtr.getPointer();
1375 return lookup_result(lookup_iterator(nullptr), lookup_iterator(nullptr));
1377 StoredDeclsMap::iterator I = Map->find(Name);
1378 return I != Map->end() ? I->second.getLookupResult()
1379 : lookup_result(lookup_iterator(nullptr),
1380 lookup_iterator(nullptr));
1383 void DeclContext::localUncachedLookup(DeclarationName Name,
1384 SmallVectorImpl<NamedDecl *> &Results) {
1387 // If there's no external storage, just perform a normal lookup and copy
1389 if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
1390 lookup_result LookupResults = lookup(Name);
1391 Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
1395 // If we have a lookup table, check there first. Maybe we'll get lucky.
1396 if (Name && !LookupPtr.getInt()) {
1397 if (StoredDeclsMap *Map = LookupPtr.getPointer()) {
1398 StoredDeclsMap::iterator Pos = Map->find(Name);
1399 if (Pos != Map->end()) {
1400 Results.insert(Results.end(),
1401 Pos->second.getLookupResult().begin(),
1402 Pos->second.getLookupResult().end());
1408 // Slow case: grovel through the declarations in our chain looking for
1410 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1411 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1412 if (ND->getDeclName() == Name)
1413 Results.push_back(ND);
1417 DeclContext *DeclContext::getRedeclContext() {
1418 DeclContext *Ctx = this;
1419 // Skip through transparent contexts.
1420 while (Ctx->isTransparentContext())
1421 Ctx = Ctx->getParent();
1425 DeclContext *DeclContext::getEnclosingNamespaceContext() {
1426 DeclContext *Ctx = this;
1427 // Skip through non-namespace, non-translation-unit contexts.
1428 while (!Ctx->isFileContext())
1429 Ctx = Ctx->getParent();
1430 return Ctx->getPrimaryContext();
1433 bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1434 // For non-file contexts, this is equivalent to Equals.
1435 if (!isFileContext())
1436 return O->Equals(this);
1439 if (O->Equals(this))
1442 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1443 if (!NS || !NS->isInline())
1445 O = NS->getParent();
1451 void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1452 DeclContext *PrimaryDC = this->getPrimaryContext();
1453 DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1454 // If the decl is being added outside of its semantic decl context, we
1455 // need to ensure that we eagerly build the lookup information for it.
1456 PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
1459 void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1461 assert(this == getPrimaryContext() && "expected a primary DC");
1463 // Skip declarations within functions.
1464 if (isFunctionOrMethod())
1467 // Skip declarations which should be invisible to name lookup.
1468 if (shouldBeHidden(D))
1471 // If we already have a lookup data structure, perform the insertion into
1472 // it. If we might have externally-stored decls with this name, look them
1473 // up and perform the insertion. If this decl was declared outside its
1474 // semantic context, buildLookup won't add it, so add it now.
1476 // FIXME: As a performance hack, don't add such decls into the translation
1477 // unit unless we're in C++, since qualified lookup into the TU is never
1479 if (LookupPtr.getPointer() || hasExternalVisibleStorage() ||
1480 ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1481 (getParentASTContext().getLangOpts().CPlusPlus ||
1482 !isTranslationUnit()))) {
1483 // If we have lazily omitted any decls, they might have the same name as
1484 // the decl which we are adding, so build a full lookup table before adding
1487 makeDeclVisibleInContextImpl(D, Internal);
1489 LookupPtr.setInt(true);
1492 // If we are a transparent context or inline namespace, insert into our
1493 // parent context, too. This operation is recursive.
1494 if (isTransparentContext() || isInlineNamespace())
1495 getParent()->getPrimaryContext()->
1496 makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1498 Decl *DCAsDecl = cast<Decl>(this);
1499 // Notify that a decl was made visible unless we are a Tag being defined.
1500 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1501 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1502 L->AddedVisibleDecl(this, D);
1505 void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1506 // Find or create the stored declaration map.
1507 StoredDeclsMap *Map = LookupPtr.getPointer();
1509 ASTContext *C = &getParentASTContext();
1510 Map = CreateStoredDeclsMap(*C);
1513 // If there is an external AST source, load any declarations it knows about
1514 // with this declaration's name.
1515 // If the lookup table contains an entry about this name it means that we
1516 // have already checked the external source.
1518 if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1519 if (hasExternalVisibleStorage() &&
1520 Map->find(D->getDeclName()) == Map->end())
1521 Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1523 // Insert this declaration into the map.
1524 StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
1527 // If this is being added as part of loading an external declaration,
1528 // this may not be the only external declaration with this name.
1529 // In this case, we never try to replace an existing declaration; we'll
1530 // handle that when we finalize the list of declarations for this name.
1531 DeclNameEntries.setHasExternalDecls();
1532 DeclNameEntries.AddSubsequentDecl(D);
1536 else if (DeclNameEntries.isNull()) {
1537 DeclNameEntries.setOnlyValue(D);
1541 if (DeclNameEntries.HandleRedeclaration(D)) {
1542 // This declaration has replaced an existing one for which
1543 // declarationReplaces returns true.
1547 // Put this declaration into the appropriate slot.
1548 DeclNameEntries.AddSubsequentDecl(D);
1551 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1553 DeclContext::udir_range DeclContext::using_directives() const {
1554 // FIXME: Use something more efficient than normal lookup for using
1555 // directives. In C++, using directives are looked up more than anything else.
1556 lookup_const_result Result = lookup(UsingDirectiveDecl::getName());
1558 reinterpret_cast<UsingDirectiveDecl *const *>(Result.begin()),
1559 reinterpret_cast<UsingDirectiveDecl *const *>(Result.end()));
1562 //===----------------------------------------------------------------------===//
1563 // Creation and Destruction of StoredDeclsMaps. //
1564 //===----------------------------------------------------------------------===//
1566 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1567 assert(!LookupPtr.getPointer() && "context already has a decls map");
1568 assert(getPrimaryContext() == this &&
1569 "creating decls map on non-primary context");
1572 bool Dependent = isDependentContext();
1574 M = new DependentStoredDeclsMap();
1576 M = new StoredDeclsMap();
1577 M->Previous = C.LastSDM;
1578 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1579 LookupPtr.setPointer(M);
1583 void ASTContext::ReleaseDeclContextMaps() {
1584 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1585 // pointer because the subclass doesn't add anything that needs to
1587 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1590 void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1592 // Advance the iteration before we invalidate memory.
1593 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1596 delete static_cast<DependentStoredDeclsMap*>(Map);
1600 Map = Next.getPointer();
1601 Dependent = Next.getInt();
1605 DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1606 DeclContext *Parent,
1607 const PartialDiagnostic &PDiag) {
1608 assert(Parent->isDependentContext()
1609 && "cannot iterate dependent diagnostics of non-dependent context");
1610 Parent = Parent->getPrimaryContext();
1611 if (!Parent->LookupPtr.getPointer())
1612 Parent->CreateStoredDeclsMap(C);
1614 DependentStoredDeclsMap *Map
1615 = static_cast<DependentStoredDeclsMap*>(Parent->LookupPtr.getPointer());
1617 // Allocate the copy of the PartialDiagnostic via the ASTContext's
1618 // BumpPtrAllocator, rather than the ASTContext itself.
1619 PartialDiagnostic::Storage *DiagStorage = nullptr;
1620 if (PDiag.hasStorage())
1621 DiagStorage = new (C) PartialDiagnostic::Storage;
1623 DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
1625 // TODO: Maybe we shouldn't reverse the order during insertion.
1626 DD->NextDiagnostic = Map->FirstDiagnostic;
1627 Map->FirstDiagnostic = DD;