1 //===--- DeclBase.cpp - Declaration AST Node Implementation ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Decl and DeclContext classes.
12 //===----------------------------------------------------------------------===//
14 #include "clang/AST/DeclBase.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclContextInternals.h"
21 #include "clang/AST/DeclFriend.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclOpenMP.h"
24 #include "clang/AST/DeclTemplate.h"
25 #include "clang/AST/DependentDiagnostic.h"
26 #include "clang/AST/ExternalASTSource.h"
27 #include "clang/AST/Stmt.h"
28 #include "clang/AST/StmtCXX.h"
29 #include "clang/AST/Type.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "llvm/Support/raw_ostream.h"
33 using namespace clang;
35 //===----------------------------------------------------------------------===//
37 //===----------------------------------------------------------------------===//
39 #define DECL(DERIVED, BASE) static int n##DERIVED##s = 0;
40 #define ABSTRACT_DECL(DECL)
41 #include "clang/AST/DeclNodes.inc"
43 void Decl::updateOutOfDate(IdentifierInfo &II) const {
44 getASTContext().getExternalSource()->updateOutOfDateIdentifier(II);
47 #define DECL(DERIVED, BASE) \
48 static_assert(alignof(Decl) >= alignof(DERIVED##Decl), \
49 "Alignment sufficient after objects prepended to " #DERIVED);
50 #define ABSTRACT_DECL(DECL)
51 #include "clang/AST/DeclNodes.inc"
53 void *Decl::operator new(std::size_t Size, const ASTContext &Context,
54 unsigned ID, std::size_t Extra) {
55 // Allocate an extra 8 bytes worth of storage, which ensures that the
56 // resulting pointer will still be 8-byte aligned.
57 static_assert(sizeof(unsigned) * 2 >= alignof(Decl),
58 "Decl won't be misaligned");
59 void *Start = Context.Allocate(Size + Extra + 8);
60 void *Result = (char*)Start + 8;
62 unsigned *PrefixPtr = (unsigned *)Result - 2;
64 // Zero out the first 4 bytes; this is used to store the owning module ID.
67 // Store the global declaration ID in the second 4 bytes.
73 void *Decl::operator new(std::size_t Size, const ASTContext &Ctx,
74 DeclContext *Parent, std::size_t Extra) {
75 assert(!Parent || &Parent->getParentASTContext() == &Ctx);
76 // With local visibility enabled, we track the owning module even for local
78 if (Ctx.getLangOpts().ModulesLocalVisibility) {
79 // Ensure required alignment of the resulting object by adding extra
80 // padding at the start if required.
82 llvm::OffsetToAlignment(sizeof(Module *), alignof(Decl));
83 char *Buffer = reinterpret_cast<char *>(
84 ::operator new(ExtraAlign + sizeof(Module *) + Size + Extra, Ctx));
86 return new (Buffer) Module*(nullptr) + 1;
88 return ::operator new(Size + Extra, Ctx);
91 Module *Decl::getOwningModuleSlow() const {
92 assert(isFromASTFile() && "Not from AST file?");
93 return getASTContext().getExternalSource()->getModule(getOwningModuleID());
96 bool Decl::hasLocalOwningModuleStorage() const {
97 return getASTContext().getLangOpts().ModulesLocalVisibility;
100 const char *Decl::getDeclKindName() const {
102 default: llvm_unreachable("Declaration not in DeclNodes.inc!");
103 #define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
104 #define ABSTRACT_DECL(DECL)
105 #include "clang/AST/DeclNodes.inc"
109 void Decl::setInvalidDecl(bool Invalid) {
110 InvalidDecl = Invalid;
111 assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition());
116 if (!isa<ParmVarDecl>(this)) {
117 // Defensive maneuver for ill-formed code: we're likely not to make it to
118 // a point where we set the access specifier, so default it to "public"
119 // to avoid triggering asserts elsewhere in the front end.
120 setAccess(AS_public);
123 // Marking a DecompositionDecl as invalid implies all the child BindingDecl's
125 if (DecompositionDecl *DD = dyn_cast<DecompositionDecl>(this)) {
126 for (BindingDecl *Binding : DD->bindings()) {
127 Binding->setInvalidDecl();
132 const char *DeclContext::getDeclKindName() const {
134 default: llvm_unreachable("Declaration context not in DeclNodes.inc!");
135 #define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
136 #define ABSTRACT_DECL(DECL)
137 #include "clang/AST/DeclNodes.inc"
141 bool Decl::StatisticsEnabled = false;
142 void Decl::EnableStatistics() {
143 StatisticsEnabled = true;
146 void Decl::PrintStats() {
147 llvm::errs() << "\n*** Decl Stats:\n";
150 #define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
151 #define ABSTRACT_DECL(DECL)
152 #include "clang/AST/DeclNodes.inc"
153 llvm::errs() << " " << totalDecls << " decls total.\n";
156 #define DECL(DERIVED, BASE) \
157 if (n##DERIVED##s > 0) { \
158 totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \
159 llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \
160 << sizeof(DERIVED##Decl) << " each (" \
161 << n##DERIVED##s * sizeof(DERIVED##Decl) \
164 #define ABSTRACT_DECL(DECL)
165 #include "clang/AST/DeclNodes.inc"
167 llvm::errs() << "Total bytes = " << totalBytes << "\n";
170 void Decl::add(Kind k) {
172 #define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
173 #define ABSTRACT_DECL(DECL)
174 #include "clang/AST/DeclNodes.inc"
178 bool Decl::isTemplateParameterPack() const {
179 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
180 return TTP->isParameterPack();
181 if (const NonTypeTemplateParmDecl *NTTP
182 = dyn_cast<NonTypeTemplateParmDecl>(this))
183 return NTTP->isParameterPack();
184 if (const TemplateTemplateParmDecl *TTP
185 = dyn_cast<TemplateTemplateParmDecl>(this))
186 return TTP->isParameterPack();
190 bool Decl::isParameterPack() const {
191 if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this))
192 return Parm->isParameterPack();
194 return isTemplateParameterPack();
197 FunctionDecl *Decl::getAsFunction() {
198 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
200 if (const FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(this))
201 return FTD->getTemplatedDecl();
205 bool Decl::isTemplateDecl() const {
206 return isa<TemplateDecl>(this);
209 TemplateDecl *Decl::getDescribedTemplate() const {
210 if (auto *FD = dyn_cast<FunctionDecl>(this))
211 return FD->getDescribedFunctionTemplate();
212 else if (auto *RD = dyn_cast<CXXRecordDecl>(this))
213 return RD->getDescribedClassTemplate();
214 else if (auto *VD = dyn_cast<VarDecl>(this))
215 return VD->getDescribedVarTemplate();
220 const DeclContext *Decl::getParentFunctionOrMethod() const {
221 for (const DeclContext *DC = getDeclContext();
222 DC && !DC->isTranslationUnit() && !DC->isNamespace();
223 DC = DC->getParent())
224 if (DC->isFunctionOrMethod())
231 //===----------------------------------------------------------------------===//
232 // PrettyStackTraceDecl Implementation
233 //===----------------------------------------------------------------------===//
235 void PrettyStackTraceDecl::print(raw_ostream &OS) const {
236 SourceLocation TheLoc = Loc;
237 if (TheLoc.isInvalid() && TheDecl)
238 TheLoc = TheDecl->getLocation();
240 if (TheLoc.isValid()) {
241 TheLoc.print(OS, SM);
247 if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
249 DN->printQualifiedName(OS);
255 //===----------------------------------------------------------------------===//
256 // Decl Implementation
257 //===----------------------------------------------------------------------===//
259 // Out-of-line virtual method providing a home for Decl.
262 void Decl::setDeclContext(DeclContext *DC) {
266 void Decl::setLexicalDeclContext(DeclContext *DC) {
267 if (DC == getLexicalDeclContext())
271 setDeclContextsImpl(getDeclContext(), DC, getASTContext());
273 getMultipleDC()->LexicalDC = DC;
275 Hidden = cast<Decl>(DC)->Hidden;
278 void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
280 if (SemaDC == LexicalDC) {
283 Decl::MultipleDC *MDC = new (Ctx) Decl::MultipleDC();
284 MDC->SemanticDC = SemaDC;
285 MDC->LexicalDC = LexicalDC;
290 bool Decl::isLexicallyWithinFunctionOrMethod() const {
291 const DeclContext *LDC = getLexicalDeclContext();
293 if (LDC->isFunctionOrMethod())
295 if (!isa<TagDecl>(LDC))
297 LDC = LDC->getLexicalParent();
302 bool Decl::isInAnonymousNamespace() const {
303 const DeclContext *DC = getDeclContext();
305 if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
306 if (ND->isAnonymousNamespace())
308 } while ((DC = DC->getParent()));
313 bool Decl::isInStdNamespace() const {
314 return getDeclContext()->isStdNamespace();
317 TranslationUnitDecl *Decl::getTranslationUnitDecl() {
318 if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
321 DeclContext *DC = getDeclContext();
322 assert(DC && "This decl is not contained in a translation unit!");
324 while (!DC->isTranslationUnit()) {
325 DC = DC->getParent();
326 assert(DC && "This decl is not contained in a translation unit!");
329 return cast<TranslationUnitDecl>(DC);
332 ASTContext &Decl::getASTContext() const {
333 return getTranslationUnitDecl()->getASTContext();
336 ASTMutationListener *Decl::getASTMutationListener() const {
337 return getASTContext().getASTMutationListener();
340 unsigned Decl::getMaxAlignment() const {
345 const AttrVec &V = getAttrs();
346 ASTContext &Ctx = getASTContext();
347 specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
349 Align = std::max(Align, I->getAlignment(Ctx));
353 bool Decl::isUsed(bool CheckUsedAttr) const {
354 const Decl *CanonD = getCanonicalDecl();
358 // Check for used attribute.
359 // Ask the most recent decl, since attributes accumulate in the redecl chain.
360 if (CheckUsedAttr && getMostRecentDecl()->hasAttr<UsedAttr>())
363 // The information may have not been deserialized yet. Force deserialization
364 // to complete the needed information.
365 return getMostRecentDecl()->getCanonicalDecl()->Used;
368 void Decl::markUsed(ASTContext &C) {
372 if (C.getASTMutationListener())
373 C.getASTMutationListener()->DeclarationMarkedUsed(this);
378 bool Decl::isReferenced() const {
382 // Check redeclarations.
383 for (auto I : redecls())
390 bool Decl::isExported() const {
391 if (isModulePrivate())
393 // Namespaces are always exported.
394 if (isa<TranslationUnitDecl>(this) || isa<NamespaceDecl>(this))
396 // Otherwise, this is a strictly lexical check.
397 for (auto *DC = getLexicalDeclContext(); DC; DC = DC->getLexicalParent()) {
398 if (cast<Decl>(DC)->isModulePrivate())
400 if (isa<ExportDecl>(DC))
406 bool Decl::hasDefiningAttr() const {
407 return hasAttr<AliasAttr>() || hasAttr<IFuncAttr>();
410 const Attr *Decl::getDefiningAttr() const {
411 if (AliasAttr *AA = getAttr<AliasAttr>())
413 if (IFuncAttr *IFA = getAttr<IFuncAttr>())
418 /// \brief Determine the availability of the given declaration based on
419 /// the target platform.
421 /// When it returns an availability result other than \c AR_Available,
422 /// if the \p Message parameter is non-NULL, it will be set to a
423 /// string describing why the entity is unavailable.
425 /// FIXME: Make these strings localizable, since they end up in
427 static AvailabilityResult CheckAvailability(ASTContext &Context,
428 const AvailabilityAttr *A,
429 std::string *Message,
430 VersionTuple EnclosingVersion) {
431 if (EnclosingVersion.empty())
432 EnclosingVersion = Context.getTargetInfo().getPlatformMinVersion();
434 if (EnclosingVersion.empty())
437 // Check if this is an App Extension "platform", and if so chop off
438 // the suffix for matching with the actual platform.
439 StringRef ActualPlatform = A->getPlatform()->getName();
440 StringRef RealizedPlatform = ActualPlatform;
441 if (Context.getLangOpts().AppExt) {
442 size_t suffix = RealizedPlatform.rfind("_app_extension");
443 if (suffix != StringRef::npos)
444 RealizedPlatform = RealizedPlatform.slice(0, suffix);
447 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
449 // Match the platform name.
450 if (RealizedPlatform != TargetPlatform)
453 StringRef PrettyPlatformName
454 = AvailabilityAttr::getPrettyPlatformName(ActualPlatform);
456 if (PrettyPlatformName.empty())
457 PrettyPlatformName = ActualPlatform;
459 std::string HintMessage;
460 if (!A->getMessage().empty()) {
462 HintMessage += A->getMessage();
465 // Make sure that this declaration has not been marked 'unavailable'.
466 if (A->getUnavailable()) {
469 llvm::raw_string_ostream Out(*Message);
470 Out << "not available on " << PrettyPlatformName
474 return AR_Unavailable;
477 // Make sure that this declaration has already been introduced.
478 if (!A->getIntroduced().empty() &&
479 EnclosingVersion < A->getIntroduced()) {
482 llvm::raw_string_ostream Out(*Message);
483 VersionTuple VTI(A->getIntroduced());
484 VTI.UseDotAsSeparator();
485 Out << "introduced in " << PrettyPlatformName << ' '
486 << VTI << HintMessage;
489 return A->getStrict() ? AR_Unavailable : AR_NotYetIntroduced;
492 // Make sure that this declaration hasn't been obsoleted.
493 if (!A->getObsoleted().empty() && EnclosingVersion >= A->getObsoleted()) {
496 llvm::raw_string_ostream Out(*Message);
497 VersionTuple VTO(A->getObsoleted());
498 VTO.UseDotAsSeparator();
499 Out << "obsoleted in " << PrettyPlatformName << ' '
500 << VTO << HintMessage;
503 return AR_Unavailable;
506 // Make sure that this declaration hasn't been deprecated.
507 if (!A->getDeprecated().empty() && EnclosingVersion >= A->getDeprecated()) {
510 llvm::raw_string_ostream Out(*Message);
511 VersionTuple VTD(A->getDeprecated());
512 VTD.UseDotAsSeparator();
513 Out << "first deprecated in " << PrettyPlatformName << ' '
514 << VTD << HintMessage;
517 return AR_Deprecated;
523 AvailabilityResult Decl::getAvailability(std::string *Message,
524 VersionTuple EnclosingVersion) const {
525 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(this))
526 return FTD->getTemplatedDecl()->getAvailability(Message, EnclosingVersion);
528 AvailabilityResult Result = AR_Available;
529 std::string ResultMessage;
531 for (const auto *A : attrs()) {
532 if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
533 if (Result >= AR_Deprecated)
537 ResultMessage = Deprecated->getMessage();
539 Result = AR_Deprecated;
543 if (const auto *Unavailable = dyn_cast<UnavailableAttr>(A)) {
545 *Message = Unavailable->getMessage();
546 return AR_Unavailable;
549 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
550 AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
551 Message, EnclosingVersion);
553 if (AR == AR_Unavailable)
554 return AR_Unavailable;
559 ResultMessage.swap(*Message);
566 Message->swap(ResultMessage);
570 bool Decl::canBeWeakImported(bool &IsDefinition) const {
571 IsDefinition = false;
573 // Variables, if they aren't definitions.
574 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
575 if (Var->isThisDeclarationADefinition()) {
581 // Functions, if they aren't definitions.
582 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
589 // Objective-C classes, if this is the non-fragile runtime.
590 } else if (isa<ObjCInterfaceDecl>(this) &&
591 getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
600 bool Decl::isWeakImported() const {
602 if (!canBeWeakImported(IsDefinition))
605 for (const auto *A : attrs()) {
606 if (isa<WeakImportAttr>(A))
609 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
610 if (CheckAvailability(getASTContext(), Availability, nullptr,
611 VersionTuple()) == AR_NotYetIntroduced)
619 unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
622 case CXXDeductionGuide:
625 case ConstructorUsingShadow:
636 return IDNS_Ordinary;
640 return IDNS_Ordinary | IDNS_Member;
642 case NonTypeTemplateParm:
643 // Non-type template parameters are not found by lookups that ignore
644 // non-types, but they are found by redeclaration lookups for tag types,
645 // so we include them in the tag namespace.
646 return IDNS_Ordinary | IDNS_Tag;
648 case ObjCCompatibleAlias:
650 return IDNS_Ordinary | IDNS_Type;
654 case TypeAliasTemplate:
655 case TemplateTypeParm:
657 return IDNS_Ordinary | IDNS_Type;
659 case UnresolvedUsingTypename:
660 return IDNS_Ordinary | IDNS_Type | IDNS_Using;
663 return 0; // we'll actually overwrite this later
665 case UnresolvedUsingValue:
666 return IDNS_Ordinary | IDNS_Using;
673 return IDNS_ObjCProtocol;
676 case ObjCAtDefsField:
683 return IDNS_Tag | IDNS_Type;
687 return IDNS_Namespace;
689 case FunctionTemplate:
691 return IDNS_Ordinary;
694 case TemplateTemplateParm:
695 return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
697 case OMPDeclareReduction:
698 return IDNS_OMPReduction;
708 case ObjCPropertyImpl:
710 case PragmaDetectMismatch:
713 case TranslationUnit:
718 case BuiltinTemplate:
719 case ClassTemplateSpecialization:
720 case ClassTemplatePartialSpecialization:
721 case ClassScopeFunctionSpecialization:
722 case VarTemplateSpecialization:
723 case VarTemplatePartialSpecialization:
724 case ObjCImplementation:
726 case ObjCCategoryImpl:
728 case OMPThreadPrivate:
729 case OMPCapturedExpr:
731 // Never looked up by name.
735 llvm_unreachable("Invalid DeclKind!");
738 void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
739 assert(!HasAttrs && "Decl already contains attrs.");
741 AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
742 assert(AttrBlank.empty() && "HasAttrs was wrong?");
748 void Decl::dropAttrs() {
749 if (!HasAttrs) return;
752 getASTContext().eraseDeclAttrs(this);
755 const AttrVec &Decl::getAttrs() const {
756 assert(HasAttrs && "No attrs to get!");
757 return getASTContext().getDeclAttrs(this);
760 Decl *Decl::castFromDeclContext (const DeclContext *D) {
761 Decl::Kind DK = D->getDeclKind();
763 #define DECL(NAME, BASE)
764 #define DECL_CONTEXT(NAME) \
766 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
767 #define DECL_CONTEXT_BASE(NAME)
768 #include "clang/AST/DeclNodes.inc"
770 #define DECL(NAME, BASE)
771 #define DECL_CONTEXT_BASE(NAME) \
772 if (DK >= first##NAME && DK <= last##NAME) \
773 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
774 #include "clang/AST/DeclNodes.inc"
775 llvm_unreachable("a decl that inherits DeclContext isn't handled");
779 DeclContext *Decl::castToDeclContext(const Decl *D) {
780 Decl::Kind DK = D->getKind();
782 #define DECL(NAME, BASE)
783 #define DECL_CONTEXT(NAME) \
785 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
786 #define DECL_CONTEXT_BASE(NAME)
787 #include "clang/AST/DeclNodes.inc"
789 #define DECL(NAME, BASE)
790 #define DECL_CONTEXT_BASE(NAME) \
791 if (DK >= first##NAME && DK <= last##NAME) \
792 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
793 #include "clang/AST/DeclNodes.inc"
794 llvm_unreachable("a decl that inherits DeclContext isn't handled");
798 SourceLocation Decl::getBodyRBrace() const {
799 // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
800 // FunctionDecl stores EndRangeLoc for this purpose.
801 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
802 const FunctionDecl *Definition;
803 if (FD->hasBody(Definition))
804 return Definition->getSourceRange().getEnd();
805 return SourceLocation();
808 if (Stmt *Body = getBody())
809 return Body->getSourceRange().getEnd();
811 return SourceLocation();
814 bool Decl::AccessDeclContextSanity() const {
816 // Suppress this check if any of the following hold:
817 // 1. this is the translation unit (and thus has no parent)
818 // 2. this is a template parameter (and thus doesn't belong to its context)
819 // 3. this is a non-type template parameter
820 // 4. the context is not a record
822 // 6. it's a C++0x static_assert.
823 if (isa<TranslationUnitDecl>(this) ||
824 isa<TemplateTypeParmDecl>(this) ||
825 isa<NonTypeTemplateParmDecl>(this) ||
826 !isa<CXXRecordDecl>(getDeclContext()) ||
828 isa<StaticAssertDecl>(this) ||
829 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
830 // as DeclContext (?).
831 isa<ParmVarDecl>(this) ||
832 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
833 // AS_none as access specifier.
834 isa<CXXRecordDecl>(this) ||
835 isa<ClassScopeFunctionSpecializationDecl>(this))
838 assert(Access != AS_none &&
839 "Access specifier is AS_none inside a record decl");
844 static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
845 static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
847 const FunctionType *Decl::getFunctionType(bool BlocksToo) const {
849 if (const ValueDecl *D = dyn_cast<ValueDecl>(this))
851 else if (const TypedefNameDecl *D = dyn_cast<TypedefNameDecl>(this))
852 Ty = D->getUnderlyingType();
856 if (Ty->isFunctionPointerType())
857 Ty = Ty->getAs<PointerType>()->getPointeeType();
858 else if (BlocksToo && Ty->isBlockPointerType())
859 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
861 return Ty->getAs<FunctionType>();
865 /// Starting at a given context (a Decl or DeclContext), look for a
866 /// code context that is not a closure (a lambda, block, etc.).
867 template <class T> static Decl *getNonClosureContext(T *D) {
868 if (getKind(D) == Decl::CXXMethod) {
869 CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
870 if (MD->getOverloadedOperator() == OO_Call &&
871 MD->getParent()->isLambda())
872 return getNonClosureContext(MD->getParent()->getParent());
874 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
876 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
878 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
879 return getNonClosureContext(BD->getParent());
880 } else if (CapturedDecl *CD = dyn_cast<CapturedDecl>(D)) {
881 return getNonClosureContext(CD->getParent());
887 Decl *Decl::getNonClosureContext() {
888 return ::getNonClosureContext(this);
891 Decl *DeclContext::getNonClosureAncestor() {
892 return ::getNonClosureContext(this);
895 //===----------------------------------------------------------------------===//
896 // DeclContext Implementation
897 //===----------------------------------------------------------------------===//
899 bool DeclContext::classof(const Decl *D) {
900 switch (D->getKind()) {
901 #define DECL(NAME, BASE)
902 #define DECL_CONTEXT(NAME) case Decl::NAME:
903 #define DECL_CONTEXT_BASE(NAME)
904 #include "clang/AST/DeclNodes.inc"
907 #define DECL(NAME, BASE)
908 #define DECL_CONTEXT_BASE(NAME) \
909 if (D->getKind() >= Decl::first##NAME && \
910 D->getKind() <= Decl::last##NAME) \
912 #include "clang/AST/DeclNodes.inc"
917 DeclContext::~DeclContext() { }
919 /// \brief Find the parent context of this context that will be
920 /// used for unqualified name lookup.
922 /// Generally, the parent lookup context is the semantic context. However, for
923 /// a friend function the parent lookup context is the lexical context, which
924 /// is the class in which the friend is declared.
925 DeclContext *DeclContext::getLookupParent() {
926 // FIXME: Find a better way to identify friends
927 if (isa<FunctionDecl>(this))
928 if (getParent()->getRedeclContext()->isFileContext() &&
929 getLexicalParent()->getRedeclContext()->isRecord())
930 return getLexicalParent();
935 bool DeclContext::isInlineNamespace() const {
936 return isNamespace() &&
937 cast<NamespaceDecl>(this)->isInline();
940 bool DeclContext::isStdNamespace() const {
944 const NamespaceDecl *ND = cast<NamespaceDecl>(this);
945 if (ND->isInline()) {
946 return ND->getParent()->isStdNamespace();
949 if (!getParent()->getRedeclContext()->isTranslationUnit())
952 const IdentifierInfo *II = ND->getIdentifier();
953 return II && II->isStr("std");
956 bool DeclContext::isDependentContext() const {
960 if (isa<ClassTemplatePartialSpecializationDecl>(this))
963 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
964 if (Record->getDescribedClassTemplate())
967 if (Record->isDependentLambda())
971 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
972 if (Function->getDescribedFunctionTemplate())
975 // Friend function declarations are dependent if their *lexical*
976 // context is dependent.
977 if (cast<Decl>(this)->getFriendObjectKind())
978 return getLexicalParent()->isDependentContext();
981 // FIXME: A variable template is a dependent context, but is not a
982 // DeclContext. A context within it (such as a lambda-expression)
983 // should be considered dependent.
985 return getParent() && getParent()->isDependentContext();
988 bool DeclContext::isTransparentContext() const {
989 if (DeclKind == Decl::Enum)
990 return !cast<EnumDecl>(this)->isScoped();
991 else if (DeclKind == Decl::LinkageSpec || DeclKind == Decl::Export)
997 static bool isLinkageSpecContext(const DeclContext *DC,
998 LinkageSpecDecl::LanguageIDs ID) {
999 while (DC->getDeclKind() != Decl::TranslationUnit) {
1000 if (DC->getDeclKind() == Decl::LinkageSpec)
1001 return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
1002 DC = DC->getLexicalParent();
1007 bool DeclContext::isExternCContext() const {
1008 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_c);
1011 const LinkageSpecDecl *DeclContext::getExternCContext() const {
1012 const DeclContext *DC = this;
1013 while (DC->getDeclKind() != Decl::TranslationUnit) {
1014 if (DC->getDeclKind() == Decl::LinkageSpec &&
1015 cast<LinkageSpecDecl>(DC)->getLanguage() ==
1016 clang::LinkageSpecDecl::lang_c)
1017 return cast<LinkageSpecDecl>(DC);
1018 DC = DC->getLexicalParent();
1023 bool DeclContext::isExternCXXContext() const {
1024 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_cxx);
1027 bool DeclContext::Encloses(const DeclContext *DC) const {
1028 if (getPrimaryContext() != this)
1029 return getPrimaryContext()->Encloses(DC);
1031 for (; DC; DC = DC->getParent())
1032 if (DC->getPrimaryContext() == this)
1037 DeclContext *DeclContext::getPrimaryContext() {
1039 case Decl::TranslationUnit:
1040 case Decl::ExternCContext:
1041 case Decl::LinkageSpec:
1044 case Decl::Captured:
1045 case Decl::OMPDeclareReduction:
1046 // There is only one DeclContext for these entities.
1049 case Decl::Namespace:
1050 // The original namespace is our primary context.
1051 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
1053 case Decl::ObjCMethod:
1056 case Decl::ObjCInterface:
1057 if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
1062 case Decl::ObjCProtocol:
1063 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
1068 case Decl::ObjCCategory:
1071 case Decl::ObjCImplementation:
1072 case Decl::ObjCCategoryImpl:
1076 if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
1077 // If this is a tag type that has a definition or is currently
1078 // being defined, that definition is our primary context.
1079 TagDecl *Tag = cast<TagDecl>(this);
1081 if (TagDecl *Def = Tag->getDefinition())
1084 if (const TagType *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) {
1085 // Note, TagType::getDecl returns the (partial) definition one exists.
1086 TagDecl *PossiblePartialDef = TagTy->getDecl();
1087 if (PossiblePartialDef->isBeingDefined())
1088 return PossiblePartialDef;
1090 assert(isa<InjectedClassNameType>(Tag->getTypeForDecl()));
1096 assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
1097 "Unknown DeclContext kind");
1103 DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
1106 if (DeclKind != Decl::Namespace) {
1107 Contexts.push_back(this);
1111 NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
1112 for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
1113 N = N->getPreviousDecl())
1114 Contexts.push_back(N);
1116 std::reverse(Contexts.begin(), Contexts.end());
1119 std::pair<Decl *, Decl *>
1120 DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
1121 bool FieldsAlreadyLoaded) {
1122 // Build up a chain of declarations via the Decl::NextInContextAndBits field.
1123 Decl *FirstNewDecl = nullptr;
1124 Decl *PrevDecl = nullptr;
1125 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1126 if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
1131 PrevDecl->NextInContextAndBits.setPointer(D);
1138 return std::make_pair(FirstNewDecl, PrevDecl);
1141 /// \brief We have just acquired external visible storage, and we already have
1142 /// built a lookup map. For every name in the map, pull in the new names from
1143 /// the external storage.
1144 void DeclContext::reconcileExternalVisibleStorage() const {
1145 assert(NeedToReconcileExternalVisibleStorage && LookupPtr);
1146 NeedToReconcileExternalVisibleStorage = false;
1148 for (auto &Lookup : *LookupPtr)
1149 Lookup.second.setHasExternalDecls();
1152 /// \brief Load the declarations within this lexical storage from an
1153 /// external source.
1154 /// \return \c true if any declarations were added.
1156 DeclContext::LoadLexicalDeclsFromExternalStorage() const {
1157 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1158 assert(hasExternalLexicalStorage() && Source && "No external storage?");
1160 // Notify that we have a DeclContext that is initializing.
1161 ExternalASTSource::Deserializing ADeclContext(Source);
1163 // Load the external declarations, if any.
1164 SmallVector<Decl*, 64> Decls;
1165 ExternalLexicalStorage = false;
1166 Source->FindExternalLexicalDecls(this, Decls);
1171 // We may have already loaded just the fields of this record, in which case
1172 // we need to ignore them.
1173 bool FieldsAlreadyLoaded = false;
1174 if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
1175 FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
1177 // Splice the newly-read declarations into the beginning of the list
1179 Decl *ExternalFirst, *ExternalLast;
1180 std::tie(ExternalFirst, ExternalLast) =
1181 BuildDeclChain(Decls, FieldsAlreadyLoaded);
1182 ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
1183 FirstDecl = ExternalFirst;
1185 LastDecl = ExternalLast;
1189 DeclContext::lookup_result
1190 ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
1191 DeclarationName Name) {
1192 ASTContext &Context = DC->getParentASTContext();
1193 StoredDeclsMap *Map;
1194 if (!(Map = DC->LookupPtr))
1195 Map = DC->CreateStoredDeclsMap(Context);
1196 if (DC->NeedToReconcileExternalVisibleStorage)
1197 DC->reconcileExternalVisibleStorage();
1199 (*Map)[Name].removeExternalDecls();
1201 return DeclContext::lookup_result();
1204 DeclContext::lookup_result
1205 ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
1206 DeclarationName Name,
1207 ArrayRef<NamedDecl*> Decls) {
1208 ASTContext &Context = DC->getParentASTContext();
1209 StoredDeclsMap *Map;
1210 if (!(Map = DC->LookupPtr))
1211 Map = DC->CreateStoredDeclsMap(Context);
1212 if (DC->NeedToReconcileExternalVisibleStorage)
1213 DC->reconcileExternalVisibleStorage();
1215 StoredDeclsList &List = (*Map)[Name];
1217 // Clear out any old external visible declarations, to avoid quadratic
1218 // performance in the redeclaration checks below.
1219 List.removeExternalDecls();
1221 if (!List.isNull()) {
1222 // We have both existing declarations and new declarations for this name.
1223 // Some of the declarations may simply replace existing ones. Handle those
1225 llvm::SmallVector<unsigned, 8> Skip;
1226 for (unsigned I = 0, N = Decls.size(); I != N; ++I)
1227 if (List.HandleRedeclaration(Decls[I], /*IsKnownNewer*/false))
1229 Skip.push_back(Decls.size());
1231 // Add in any new declarations.
1232 unsigned SkipPos = 0;
1233 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1234 if (I == Skip[SkipPos])
1237 List.AddSubsequentDecl(Decls[I]);
1240 // Convert the array to a StoredDeclsList.
1241 for (ArrayRef<NamedDecl*>::iterator
1242 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1244 List.setOnlyValue(*I);
1246 List.AddSubsequentDecl(*I);
1250 return List.getLookupResult();
1253 DeclContext::decl_iterator DeclContext::decls_begin() const {
1254 if (hasExternalLexicalStorage())
1255 LoadLexicalDeclsFromExternalStorage();
1256 return decl_iterator(FirstDecl);
1259 bool DeclContext::decls_empty() const {
1260 if (hasExternalLexicalStorage())
1261 LoadLexicalDeclsFromExternalStorage();
1266 bool DeclContext::containsDecl(Decl *D) const {
1267 return (D->getLexicalDeclContext() == this &&
1268 (D->NextInContextAndBits.getPointer() || D == LastDecl));
1271 void DeclContext::removeDecl(Decl *D) {
1272 assert(D->getLexicalDeclContext() == this &&
1273 "decl being removed from non-lexical context");
1274 assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
1275 "decl is not in decls list");
1277 // Remove D from the decl chain. This is O(n) but hopefully rare.
1278 if (D == FirstDecl) {
1280 FirstDecl = LastDecl = nullptr;
1282 FirstDecl = D->NextInContextAndBits.getPointer();
1284 for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
1285 assert(I && "decl not found in linked list");
1286 if (I->NextInContextAndBits.getPointer() == D) {
1287 I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
1288 if (D == LastDecl) LastDecl = I;
1294 // Mark that D is no longer in the decl chain.
1295 D->NextInContextAndBits.setPointer(nullptr);
1297 // Remove D from the lookup table if necessary.
1298 if (isa<NamedDecl>(D)) {
1299 NamedDecl *ND = cast<NamedDecl>(D);
1301 // Remove only decls that have a name
1302 if (!ND->getDeclName()) return;
1306 StoredDeclsMap *Map = DC->getPrimaryContext()->LookupPtr;
1308 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1309 assert(Pos != Map->end() && "no lookup entry for decl");
1310 if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
1311 Pos->second.remove(ND);
1313 } while (DC->isTransparentContext() && (DC = DC->getParent()));
1317 void DeclContext::addHiddenDecl(Decl *D) {
1318 assert(D->getLexicalDeclContext() == this &&
1319 "Decl inserted into wrong lexical context");
1320 assert(!D->getNextDeclInContext() && D != LastDecl &&
1321 "Decl already inserted into a DeclContext");
1324 LastDecl->NextInContextAndBits.setPointer(D);
1327 FirstDecl = LastDecl = D;
1330 // Notify a C++ record declaration that we've added a member, so it can
1331 // update its class-specific state.
1332 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1333 Record->addedMember(D);
1335 // If this is a newly-created (not de-serialized) import declaration, wire
1336 // it in to the list of local import declarations.
1337 if (!D->isFromASTFile()) {
1338 if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
1339 D->getASTContext().addedLocalImportDecl(Import);
1343 void DeclContext::addDecl(Decl *D) {
1346 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1347 ND->getDeclContext()->getPrimaryContext()->
1348 makeDeclVisibleInContextWithFlags(ND, false, true);
1351 void DeclContext::addDeclInternal(Decl *D) {
1354 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1355 ND->getDeclContext()->getPrimaryContext()->
1356 makeDeclVisibleInContextWithFlags(ND, true, true);
1359 /// shouldBeHidden - Determine whether a declaration which was declared
1360 /// within its semantic context should be invisible to qualified name lookup.
1361 static bool shouldBeHidden(NamedDecl *D) {
1362 // Skip unnamed declarations.
1363 if (!D->getDeclName())
1366 // Skip entities that can't be found by name lookup into a particular
1368 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1369 D->isTemplateParameter())
1372 // Skip template specializations.
1373 // FIXME: This feels like a hack. Should DeclarationName support
1374 // template-ids, or is there a better way to keep specializations
1375 // from being visible?
1376 if (isa<ClassTemplateSpecializationDecl>(D))
1378 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1379 if (FD->isFunctionTemplateSpecialization())
1385 /// buildLookup - Build the lookup data structure with all of the
1386 /// declarations in this DeclContext (and any other contexts linked
1387 /// to it or transparent contexts nested within it) and return it.
1389 /// Note that the produced map may miss out declarations from an
1390 /// external source. If it does, those entries will be marked with
1391 /// the 'hasExternalDecls' flag.
1392 StoredDeclsMap *DeclContext::buildLookup() {
1393 assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1395 if (!HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups)
1398 SmallVector<DeclContext *, 2> Contexts;
1399 collectAllContexts(Contexts);
1401 if (HasLazyExternalLexicalLookups) {
1402 HasLazyExternalLexicalLookups = false;
1403 for (auto *DC : Contexts) {
1404 if (DC->hasExternalLexicalStorage())
1405 HasLazyLocalLexicalLookups |=
1406 DC->LoadLexicalDeclsFromExternalStorage();
1409 if (!HasLazyLocalLexicalLookups)
1413 for (auto *DC : Contexts)
1414 buildLookupImpl(DC, hasExternalVisibleStorage());
1416 // We no longer have any lazy decls.
1417 HasLazyLocalLexicalLookups = false;
1421 /// buildLookupImpl - Build part of the lookup data structure for the
1422 /// declarations contained within DCtx, which will either be this
1423 /// DeclContext, a DeclContext linked to it, or a transparent context
1424 /// nested within it.
1425 void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {
1426 for (Decl *D : DCtx->noload_decls()) {
1427 // Insert this declaration into the lookup structure, but only if
1428 // it's semantically within its decl context. Any other decls which
1429 // should be found in this context are added eagerly.
1431 // If it's from an AST file, don't add it now. It'll get handled by
1432 // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1433 // in C++, we do not track external visible decls for the TU, so in
1434 // that case we need to collect them all here.
1435 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1436 if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1437 (!ND->isFromASTFile() ||
1438 (isTranslationUnit() &&
1439 !getParentASTContext().getLangOpts().CPlusPlus)))
1440 makeDeclVisibleInContextImpl(ND, Internal);
1442 // If this declaration is itself a transparent declaration context
1443 // or inline namespace, add the members of this declaration of that
1444 // context (recursively).
1445 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
1446 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1447 buildLookupImpl(InnerCtx, Internal);
1451 NamedDecl *const DeclContextLookupResult::SingleElementDummyList = nullptr;
1453 DeclContext::lookup_result
1454 DeclContext::lookup(DeclarationName Name) const {
1455 assert(DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export &&
1456 "should not perform lookups into transparent contexts");
1458 const DeclContext *PrimaryContext = getPrimaryContext();
1459 if (PrimaryContext != this)
1460 return PrimaryContext->lookup(Name);
1462 // If we have an external source, ensure that any later redeclarations of this
1463 // context have been loaded, since they may add names to the result of this
1464 // lookup (or add external visible storage).
1465 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1467 (void)cast<Decl>(this)->getMostRecentDecl();
1469 if (hasExternalVisibleStorage()) {
1470 assert(Source && "external visible storage but no external source?");
1472 if (NeedToReconcileExternalVisibleStorage)
1473 reconcileExternalVisibleStorage();
1475 StoredDeclsMap *Map = LookupPtr;
1477 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
1478 // FIXME: Make buildLookup const?
1479 Map = const_cast<DeclContext*>(this)->buildLookup();
1482 Map = CreateStoredDeclsMap(getParentASTContext());
1484 // If we have a lookup result with no external decls, we are done.
1485 std::pair<StoredDeclsMap::iterator, bool> R =
1486 Map->insert(std::make_pair(Name, StoredDeclsList()));
1487 if (!R.second && !R.first->second.hasExternalDecls())
1488 return R.first->second.getLookupResult();
1490 if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) {
1491 if (StoredDeclsMap *Map = LookupPtr) {
1492 StoredDeclsMap::iterator I = Map->find(Name);
1493 if (I != Map->end())
1494 return I->second.getLookupResult();
1498 return lookup_result();
1501 StoredDeclsMap *Map = LookupPtr;
1502 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
1503 Map = const_cast<DeclContext*>(this)->buildLookup();
1506 return lookup_result();
1508 StoredDeclsMap::iterator I = Map->find(Name);
1509 if (I == Map->end())
1510 return lookup_result();
1512 return I->second.getLookupResult();
1515 DeclContext::lookup_result
1516 DeclContext::noload_lookup(DeclarationName Name) {
1517 assert(DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export &&
1518 "should not perform lookups into transparent contexts");
1520 DeclContext *PrimaryContext = getPrimaryContext();
1521 if (PrimaryContext != this)
1522 return PrimaryContext->noload_lookup(Name);
1524 // If we have any lazy lexical declarations not in our lookup map, add them
1525 // now. Don't import any external declarations, not even if we know we have
1526 // some missing from the external visible lookups.
1527 if (HasLazyLocalLexicalLookups) {
1528 SmallVector<DeclContext *, 2> Contexts;
1529 collectAllContexts(Contexts);
1530 for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
1531 buildLookupImpl(Contexts[I], hasExternalVisibleStorage());
1532 HasLazyLocalLexicalLookups = false;
1535 StoredDeclsMap *Map = LookupPtr;
1537 return lookup_result();
1539 StoredDeclsMap::iterator I = Map->find(Name);
1540 return I != Map->end() ? I->second.getLookupResult()
1544 void DeclContext::localUncachedLookup(DeclarationName Name,
1545 SmallVectorImpl<NamedDecl *> &Results) {
1548 // If there's no external storage, just perform a normal lookup and copy
1550 if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
1551 lookup_result LookupResults = lookup(Name);
1552 Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
1556 // If we have a lookup table, check there first. Maybe we'll get lucky.
1557 // FIXME: Should we be checking these flags on the primary context?
1558 if (Name && !HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups) {
1559 if (StoredDeclsMap *Map = LookupPtr) {
1560 StoredDeclsMap::iterator Pos = Map->find(Name);
1561 if (Pos != Map->end()) {
1562 Results.insert(Results.end(),
1563 Pos->second.getLookupResult().begin(),
1564 Pos->second.getLookupResult().end());
1570 // Slow case: grovel through the declarations in our chain looking for
1572 // FIXME: If we have lazy external declarations, this will not find them!
1573 // FIXME: Should we CollectAllContexts and walk them all here?
1574 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1575 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1576 if (ND->getDeclName() == Name)
1577 Results.push_back(ND);
1581 DeclContext *DeclContext::getRedeclContext() {
1582 DeclContext *Ctx = this;
1583 // Skip through transparent contexts.
1584 while (Ctx->isTransparentContext())
1585 Ctx = Ctx->getParent();
1589 DeclContext *DeclContext::getEnclosingNamespaceContext() {
1590 DeclContext *Ctx = this;
1591 // Skip through non-namespace, non-translation-unit contexts.
1592 while (!Ctx->isFileContext())
1593 Ctx = Ctx->getParent();
1594 return Ctx->getPrimaryContext();
1597 RecordDecl *DeclContext::getOuterLexicalRecordContext() {
1598 // Loop until we find a non-record context.
1599 RecordDecl *OutermostRD = nullptr;
1600 DeclContext *DC = this;
1601 while (DC->isRecord()) {
1602 OutermostRD = cast<RecordDecl>(DC);
1603 DC = DC->getLexicalParent();
1608 bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1609 // For non-file contexts, this is equivalent to Equals.
1610 if (!isFileContext())
1611 return O->Equals(this);
1614 if (O->Equals(this))
1617 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1618 if (!NS || !NS->isInline())
1620 O = NS->getParent();
1626 void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1627 DeclContext *PrimaryDC = this->getPrimaryContext();
1628 DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1629 // If the decl is being added outside of its semantic decl context, we
1630 // need to ensure that we eagerly build the lookup information for it.
1631 PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
1634 void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1636 assert(this == getPrimaryContext() && "expected a primary DC");
1638 if (!isLookupContext()) {
1639 if (isTransparentContext())
1640 getParent()->getPrimaryContext()
1641 ->makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1645 // Skip declarations which should be invisible to name lookup.
1646 if (shouldBeHidden(D))
1649 // If we already have a lookup data structure, perform the insertion into
1650 // it. If we might have externally-stored decls with this name, look them
1651 // up and perform the insertion. If this decl was declared outside its
1652 // semantic context, buildLookup won't add it, so add it now.
1654 // FIXME: As a performance hack, don't add such decls into the translation
1655 // unit unless we're in C++, since qualified lookup into the TU is never
1657 if (LookupPtr || hasExternalVisibleStorage() ||
1658 ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1659 (getParentASTContext().getLangOpts().CPlusPlus ||
1660 !isTranslationUnit()))) {
1661 // If we have lazily omitted any decls, they might have the same name as
1662 // the decl which we are adding, so build a full lookup table before adding
1665 makeDeclVisibleInContextImpl(D, Internal);
1667 HasLazyLocalLexicalLookups = true;
1670 // If we are a transparent context or inline namespace, insert into our
1671 // parent context, too. This operation is recursive.
1672 if (isTransparentContext() || isInlineNamespace())
1673 getParent()->getPrimaryContext()->
1674 makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1676 Decl *DCAsDecl = cast<Decl>(this);
1677 // Notify that a decl was made visible unless we are a Tag being defined.
1678 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1679 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1680 L->AddedVisibleDecl(this, D);
1683 void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1684 // Find or create the stored declaration map.
1685 StoredDeclsMap *Map = LookupPtr;
1687 ASTContext *C = &getParentASTContext();
1688 Map = CreateStoredDeclsMap(*C);
1691 // If there is an external AST source, load any declarations it knows about
1692 // with this declaration's name.
1693 // If the lookup table contains an entry about this name it means that we
1694 // have already checked the external source.
1696 if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1697 if (hasExternalVisibleStorage() &&
1698 Map->find(D->getDeclName()) == Map->end())
1699 Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1701 // Insert this declaration into the map.
1702 StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
1705 // If this is being added as part of loading an external declaration,
1706 // this may not be the only external declaration with this name.
1707 // In this case, we never try to replace an existing declaration; we'll
1708 // handle that when we finalize the list of declarations for this name.
1709 DeclNameEntries.setHasExternalDecls();
1710 DeclNameEntries.AddSubsequentDecl(D);
1714 if (DeclNameEntries.isNull()) {
1715 DeclNameEntries.setOnlyValue(D);
1719 if (DeclNameEntries.HandleRedeclaration(D, /*IsKnownNewer*/!Internal)) {
1720 // This declaration has replaced an existing one for which
1721 // declarationReplaces returns true.
1725 // Put this declaration into the appropriate slot.
1726 DeclNameEntries.AddSubsequentDecl(D);
1729 UsingDirectiveDecl *DeclContext::udir_iterator::operator*() const {
1730 return cast<UsingDirectiveDecl>(*I);
1733 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1735 DeclContext::udir_range DeclContext::using_directives() const {
1736 // FIXME: Use something more efficient than normal lookup for using
1737 // directives. In C++, using directives are looked up more than anything else.
1738 lookup_result Result = lookup(UsingDirectiveDecl::getName());
1739 return udir_range(Result.begin(), Result.end());
1742 //===----------------------------------------------------------------------===//
1743 // Creation and Destruction of StoredDeclsMaps. //
1744 //===----------------------------------------------------------------------===//
1746 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1747 assert(!LookupPtr && "context already has a decls map");
1748 assert(getPrimaryContext() == this &&
1749 "creating decls map on non-primary context");
1752 bool Dependent = isDependentContext();
1754 M = new DependentStoredDeclsMap();
1756 M = new StoredDeclsMap();
1757 M->Previous = C.LastSDM;
1758 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1763 void ASTContext::ReleaseDeclContextMaps() {
1764 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1765 // pointer because the subclass doesn't add anything that needs to
1767 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1770 void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1772 // Advance the iteration before we invalidate memory.
1773 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1776 delete static_cast<DependentStoredDeclsMap*>(Map);
1780 Map = Next.getPointer();
1781 Dependent = Next.getInt();
1785 DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1786 DeclContext *Parent,
1787 const PartialDiagnostic &PDiag) {
1788 assert(Parent->isDependentContext()
1789 && "cannot iterate dependent diagnostics of non-dependent context");
1790 Parent = Parent->getPrimaryContext();
1791 if (!Parent->LookupPtr)
1792 Parent->CreateStoredDeclsMap(C);
1794 DependentStoredDeclsMap *Map =
1795 static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr);
1797 // Allocate the copy of the PartialDiagnostic via the ASTContext's
1798 // BumpPtrAllocator, rather than the ASTContext itself.
1799 PartialDiagnostic::Storage *DiagStorage = nullptr;
1800 if (PDiag.hasStorage())
1801 DiagStorage = new (C) PartialDiagnostic::Storage;
1803 DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
1805 // TODO: Maybe we shouldn't reverse the order during insertion.
1806 DD->NextDiagnostic = Map->FirstDiagnostic;
1807 Map->FirstDiagnostic = DD;