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().trackLocalOwningModule()) {
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));
87 Parent ? cast<Decl>(Parent)->getOwningModule() : nullptr;
88 return new (Buffer) Module*(ParentModule) + 1;
90 return ::operator new(Size + Extra, Ctx);
93 Module *Decl::getOwningModuleSlow() const {
94 assert(isFromASTFile() && "Not from AST file?");
95 return getASTContext().getExternalSource()->getModule(getOwningModuleID());
98 bool Decl::hasLocalOwningModuleStorage() const {
99 return getASTContext().getLangOpts().trackLocalOwningModule();
102 const char *Decl::getDeclKindName() const {
104 default: llvm_unreachable("Declaration not in DeclNodes.inc!");
105 #define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
106 #define ABSTRACT_DECL(DECL)
107 #include "clang/AST/DeclNodes.inc"
111 void Decl::setInvalidDecl(bool Invalid) {
112 InvalidDecl = Invalid;
113 assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition());
118 if (!isa<ParmVarDecl>(this)) {
119 // Defensive maneuver for ill-formed code: we're likely not to make it to
120 // a point where we set the access specifier, so default it to "public"
121 // to avoid triggering asserts elsewhere in the front end.
122 setAccess(AS_public);
125 // Marking a DecompositionDecl as invalid implies all the child BindingDecl's
127 if (DecompositionDecl *DD = dyn_cast<DecompositionDecl>(this)) {
128 for (BindingDecl *Binding : DD->bindings()) {
129 Binding->setInvalidDecl();
134 const char *DeclContext::getDeclKindName() const {
136 default: llvm_unreachable("Declaration context not in DeclNodes.inc!");
137 #define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
138 #define ABSTRACT_DECL(DECL)
139 #include "clang/AST/DeclNodes.inc"
143 bool Decl::StatisticsEnabled = false;
144 void Decl::EnableStatistics() {
145 StatisticsEnabled = true;
148 void Decl::PrintStats() {
149 llvm::errs() << "\n*** Decl Stats:\n";
152 #define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
153 #define ABSTRACT_DECL(DECL)
154 #include "clang/AST/DeclNodes.inc"
155 llvm::errs() << " " << totalDecls << " decls total.\n";
158 #define DECL(DERIVED, BASE) \
159 if (n##DERIVED##s > 0) { \
160 totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \
161 llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \
162 << sizeof(DERIVED##Decl) << " each (" \
163 << n##DERIVED##s * sizeof(DERIVED##Decl) \
166 #define ABSTRACT_DECL(DECL)
167 #include "clang/AST/DeclNodes.inc"
169 llvm::errs() << "Total bytes = " << totalBytes << "\n";
172 void Decl::add(Kind k) {
174 #define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
175 #define ABSTRACT_DECL(DECL)
176 #include "clang/AST/DeclNodes.inc"
180 bool Decl::isTemplateParameterPack() const {
181 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
182 return TTP->isParameterPack();
183 if (const NonTypeTemplateParmDecl *NTTP
184 = dyn_cast<NonTypeTemplateParmDecl>(this))
185 return NTTP->isParameterPack();
186 if (const TemplateTemplateParmDecl *TTP
187 = dyn_cast<TemplateTemplateParmDecl>(this))
188 return TTP->isParameterPack();
192 bool Decl::isParameterPack() const {
193 if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this))
194 return Parm->isParameterPack();
196 return isTemplateParameterPack();
199 FunctionDecl *Decl::getAsFunction() {
200 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
202 if (const FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(this))
203 return FTD->getTemplatedDecl();
207 bool Decl::isTemplateDecl() const {
208 return isa<TemplateDecl>(this);
211 TemplateDecl *Decl::getDescribedTemplate() const {
212 if (auto *FD = dyn_cast<FunctionDecl>(this))
213 return FD->getDescribedFunctionTemplate();
214 else if (auto *RD = dyn_cast<CXXRecordDecl>(this))
215 return RD->getDescribedClassTemplate();
216 else if (auto *VD = dyn_cast<VarDecl>(this))
217 return VD->getDescribedVarTemplate();
222 const DeclContext *Decl::getParentFunctionOrMethod() const {
223 for (const DeclContext *DC = getDeclContext();
224 DC && !DC->isTranslationUnit() && !DC->isNamespace();
225 DC = DC->getParent())
226 if (DC->isFunctionOrMethod())
233 //===----------------------------------------------------------------------===//
234 // PrettyStackTraceDecl Implementation
235 //===----------------------------------------------------------------------===//
237 void PrettyStackTraceDecl::print(raw_ostream &OS) const {
238 SourceLocation TheLoc = Loc;
239 if (TheLoc.isInvalid() && TheDecl)
240 TheLoc = TheDecl->getLocation();
242 if (TheLoc.isValid()) {
243 TheLoc.print(OS, SM);
249 if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
251 DN->printQualifiedName(OS);
257 //===----------------------------------------------------------------------===//
258 // Decl Implementation
259 //===----------------------------------------------------------------------===//
261 // Out-of-line virtual method providing a home for Decl.
264 void Decl::setDeclContext(DeclContext *DC) {
268 void Decl::setLexicalDeclContext(DeclContext *DC) {
269 if (DC == getLexicalDeclContext())
273 setDeclContextsImpl(getDeclContext(), DC, getASTContext());
275 getMultipleDC()->LexicalDC = DC;
278 // FIXME: We shouldn't be changing the lexical context of declarations
279 // imported from AST files.
280 if (!isFromASTFile()) {
281 setModuleOwnershipKind(getModuleOwnershipKindForChildOf(DC));
282 if (hasOwningModule())
283 setLocalOwningModule(cast<Decl>(DC)->getOwningModule());
287 (getModuleOwnershipKind() != ModuleOwnershipKind::VisibleWhenImported ||
288 getOwningModule()) &&
289 "hidden declaration has no owning module");
292 void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
294 if (SemaDC == LexicalDC) {
297 Decl::MultipleDC *MDC = new (Ctx) Decl::MultipleDC();
298 MDC->SemanticDC = SemaDC;
299 MDC->LexicalDC = LexicalDC;
304 bool Decl::isLexicallyWithinFunctionOrMethod() const {
305 const DeclContext *LDC = getLexicalDeclContext();
307 if (LDC->isFunctionOrMethod())
309 if (!isa<TagDecl>(LDC))
311 LDC = LDC->getLexicalParent();
316 bool Decl::isInAnonymousNamespace() const {
317 const DeclContext *DC = getDeclContext();
319 if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
320 if (ND->isAnonymousNamespace())
322 } while ((DC = DC->getParent()));
327 bool Decl::isInStdNamespace() const {
328 return getDeclContext()->isStdNamespace();
331 TranslationUnitDecl *Decl::getTranslationUnitDecl() {
332 if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
335 DeclContext *DC = getDeclContext();
336 assert(DC && "This decl is not contained in a translation unit!");
338 while (!DC->isTranslationUnit()) {
339 DC = DC->getParent();
340 assert(DC && "This decl is not contained in a translation unit!");
343 return cast<TranslationUnitDecl>(DC);
346 ASTContext &Decl::getASTContext() const {
347 return getTranslationUnitDecl()->getASTContext();
350 ASTMutationListener *Decl::getASTMutationListener() const {
351 return getASTContext().getASTMutationListener();
354 unsigned Decl::getMaxAlignment() const {
359 const AttrVec &V = getAttrs();
360 ASTContext &Ctx = getASTContext();
361 specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
363 Align = std::max(Align, I->getAlignment(Ctx));
367 bool Decl::isUsed(bool CheckUsedAttr) const {
368 const Decl *CanonD = getCanonicalDecl();
372 // Check for used attribute.
373 // Ask the most recent decl, since attributes accumulate in the redecl chain.
374 if (CheckUsedAttr && getMostRecentDecl()->hasAttr<UsedAttr>())
377 // The information may have not been deserialized yet. Force deserialization
378 // to complete the needed information.
379 return getMostRecentDecl()->getCanonicalDecl()->Used;
382 void Decl::markUsed(ASTContext &C) {
386 if (C.getASTMutationListener())
387 C.getASTMutationListener()->DeclarationMarkedUsed(this);
392 bool Decl::isReferenced() const {
396 // Check redeclarations.
397 for (auto I : redecls())
404 bool Decl::isExported() const {
405 if (isModulePrivate())
407 // Namespaces are always exported.
408 if (isa<TranslationUnitDecl>(this) || isa<NamespaceDecl>(this))
410 // Otherwise, this is a strictly lexical check.
411 for (auto *DC = getLexicalDeclContext(); DC; DC = DC->getLexicalParent()) {
412 if (cast<Decl>(DC)->isModulePrivate())
414 if (isa<ExportDecl>(DC))
420 ExternalSourceSymbolAttr *Decl::getExternalSourceSymbolAttr() const {
421 const Decl *Definition = nullptr;
422 if (auto ID = dyn_cast<ObjCInterfaceDecl>(this)) {
423 Definition = ID->getDefinition();
424 } else if (auto PD = dyn_cast<ObjCProtocolDecl>(this)) {
425 Definition = PD->getDefinition();
426 } else if (auto TD = dyn_cast<TagDecl>(this)) {
427 Definition = TD->getDefinition();
432 if (auto *attr = Definition->getAttr<ExternalSourceSymbolAttr>())
434 if (auto *dcd = dyn_cast<Decl>(getDeclContext())) {
435 return dcd->getAttr<ExternalSourceSymbolAttr>();
441 bool Decl::hasDefiningAttr() const {
442 return hasAttr<AliasAttr>() || hasAttr<IFuncAttr>();
445 const Attr *Decl::getDefiningAttr() const {
446 if (AliasAttr *AA = getAttr<AliasAttr>())
448 if (IFuncAttr *IFA = getAttr<IFuncAttr>())
453 static StringRef getRealizedPlatform(const AvailabilityAttr *A,
454 const ASTContext &Context) {
455 // Check if this is an App Extension "platform", and if so chop off
456 // the suffix for matching with the actual platform.
457 StringRef RealizedPlatform = A->getPlatform()->getName();
458 if (!Context.getLangOpts().AppExt)
459 return RealizedPlatform;
460 size_t suffix = RealizedPlatform.rfind("_app_extension");
461 if (suffix != StringRef::npos)
462 return RealizedPlatform.slice(0, suffix);
463 return RealizedPlatform;
466 /// \brief Determine the availability of the given declaration based on
467 /// the target platform.
469 /// When it returns an availability result other than \c AR_Available,
470 /// if the \p Message parameter is non-NULL, it will be set to a
471 /// string describing why the entity is unavailable.
473 /// FIXME: Make these strings localizable, since they end up in
475 static AvailabilityResult CheckAvailability(ASTContext &Context,
476 const AvailabilityAttr *A,
477 std::string *Message,
478 VersionTuple EnclosingVersion) {
479 if (EnclosingVersion.empty())
480 EnclosingVersion = Context.getTargetInfo().getPlatformMinVersion();
482 if (EnclosingVersion.empty())
485 StringRef ActualPlatform = A->getPlatform()->getName();
486 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
488 // Match the platform name.
489 if (getRealizedPlatform(A, Context) != TargetPlatform)
492 StringRef PrettyPlatformName
493 = AvailabilityAttr::getPrettyPlatformName(ActualPlatform);
495 if (PrettyPlatformName.empty())
496 PrettyPlatformName = ActualPlatform;
498 std::string HintMessage;
499 if (!A->getMessage().empty()) {
501 HintMessage += A->getMessage();
504 // Make sure that this declaration has not been marked 'unavailable'.
505 if (A->getUnavailable()) {
508 llvm::raw_string_ostream Out(*Message);
509 Out << "not available on " << PrettyPlatformName
513 return AR_Unavailable;
516 // Make sure that this declaration has already been introduced.
517 if (!A->getIntroduced().empty() &&
518 EnclosingVersion < A->getIntroduced()) {
521 llvm::raw_string_ostream Out(*Message);
522 VersionTuple VTI(A->getIntroduced());
523 VTI.UseDotAsSeparator();
524 Out << "introduced in " << PrettyPlatformName << ' '
525 << VTI << HintMessage;
528 return A->getStrict() ? AR_Unavailable : AR_NotYetIntroduced;
531 // Make sure that this declaration hasn't been obsoleted.
532 if (!A->getObsoleted().empty() && EnclosingVersion >= A->getObsoleted()) {
535 llvm::raw_string_ostream Out(*Message);
536 VersionTuple VTO(A->getObsoleted());
537 VTO.UseDotAsSeparator();
538 Out << "obsoleted in " << PrettyPlatformName << ' '
539 << VTO << HintMessage;
542 return AR_Unavailable;
545 // Make sure that this declaration hasn't been deprecated.
546 if (!A->getDeprecated().empty() && EnclosingVersion >= A->getDeprecated()) {
549 llvm::raw_string_ostream Out(*Message);
550 VersionTuple VTD(A->getDeprecated());
551 VTD.UseDotAsSeparator();
552 Out << "first deprecated in " << PrettyPlatformName << ' '
553 << VTD << HintMessage;
556 return AR_Deprecated;
562 AvailabilityResult Decl::getAvailability(std::string *Message,
563 VersionTuple EnclosingVersion) const {
564 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(this))
565 return FTD->getTemplatedDecl()->getAvailability(Message, EnclosingVersion);
567 AvailabilityResult Result = AR_Available;
568 std::string ResultMessage;
570 for (const auto *A : attrs()) {
571 if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
572 if (Result >= AR_Deprecated)
576 ResultMessage = Deprecated->getMessage();
578 Result = AR_Deprecated;
582 if (const auto *Unavailable = dyn_cast<UnavailableAttr>(A)) {
584 *Message = Unavailable->getMessage();
585 return AR_Unavailable;
588 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
589 AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
590 Message, EnclosingVersion);
592 if (AR == AR_Unavailable)
593 return AR_Unavailable;
598 ResultMessage.swap(*Message);
605 Message->swap(ResultMessage);
609 VersionTuple Decl::getVersionIntroduced() const {
610 const ASTContext &Context = getASTContext();
611 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
612 for (const auto *A : attrs()) {
613 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
614 if (getRealizedPlatform(Availability, Context) != TargetPlatform)
616 if (!Availability->getIntroduced().empty())
617 return Availability->getIntroduced();
620 return VersionTuple();
623 bool Decl::canBeWeakImported(bool &IsDefinition) const {
624 IsDefinition = false;
626 // Variables, if they aren't definitions.
627 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
628 if (Var->isThisDeclarationADefinition()) {
634 // Functions, if they aren't definitions.
635 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
642 // Objective-C classes, if this is the non-fragile runtime.
643 } else if (isa<ObjCInterfaceDecl>(this) &&
644 getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
653 bool Decl::isWeakImported() const {
655 if (!canBeWeakImported(IsDefinition))
658 for (const auto *A : attrs()) {
659 if (isa<WeakImportAttr>(A))
662 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
663 if (CheckAvailability(getASTContext(), Availability, nullptr,
664 VersionTuple()) == AR_NotYetIntroduced)
672 unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
675 case CXXDeductionGuide:
678 case ConstructorUsingShadow:
689 return IDNS_Ordinary;
693 return IDNS_Ordinary | IDNS_Member;
695 case NonTypeTemplateParm:
696 // Non-type template parameters are not found by lookups that ignore
697 // non-types, but they are found by redeclaration lookups for tag types,
698 // so we include them in the tag namespace.
699 return IDNS_Ordinary | IDNS_Tag;
701 case ObjCCompatibleAlias:
703 return IDNS_Ordinary | IDNS_Type;
707 case TypeAliasTemplate:
708 case TemplateTypeParm:
710 return IDNS_Ordinary | IDNS_Type;
712 case UnresolvedUsingTypename:
713 return IDNS_Ordinary | IDNS_Type | IDNS_Using;
716 return 0; // we'll actually overwrite this later
718 case UnresolvedUsingValue:
719 return IDNS_Ordinary | IDNS_Using;
726 return IDNS_ObjCProtocol;
729 case ObjCAtDefsField:
736 return IDNS_Tag | IDNS_Type;
740 return IDNS_Namespace;
742 case FunctionTemplate:
744 return IDNS_Ordinary;
747 case TemplateTemplateParm:
748 return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
750 case OMPDeclareReduction:
751 return IDNS_OMPReduction;
761 case ObjCPropertyImpl:
763 case PragmaDetectMismatch:
766 case TranslationUnit:
771 case BuiltinTemplate:
772 case ClassTemplateSpecialization:
773 case ClassTemplatePartialSpecialization:
774 case ClassScopeFunctionSpecialization:
775 case VarTemplateSpecialization:
776 case VarTemplatePartialSpecialization:
777 case ObjCImplementation:
779 case ObjCCategoryImpl:
781 case OMPThreadPrivate:
782 case OMPCapturedExpr:
784 // Never looked up by name.
788 llvm_unreachable("Invalid DeclKind!");
791 void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
792 assert(!HasAttrs && "Decl already contains attrs.");
794 AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
795 assert(AttrBlank.empty() && "HasAttrs was wrong?");
801 void Decl::dropAttrs() {
802 if (!HasAttrs) return;
805 getASTContext().eraseDeclAttrs(this);
808 const AttrVec &Decl::getAttrs() const {
809 assert(HasAttrs && "No attrs to get!");
810 return getASTContext().getDeclAttrs(this);
813 Decl *Decl::castFromDeclContext (const DeclContext *D) {
814 Decl::Kind DK = D->getDeclKind();
816 #define DECL(NAME, BASE)
817 #define DECL_CONTEXT(NAME) \
819 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
820 #define DECL_CONTEXT_BASE(NAME)
821 #include "clang/AST/DeclNodes.inc"
823 #define DECL(NAME, BASE)
824 #define DECL_CONTEXT_BASE(NAME) \
825 if (DK >= first##NAME && DK <= last##NAME) \
826 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
827 #include "clang/AST/DeclNodes.inc"
828 llvm_unreachable("a decl that inherits DeclContext isn't handled");
832 DeclContext *Decl::castToDeclContext(const Decl *D) {
833 Decl::Kind DK = D->getKind();
835 #define DECL(NAME, BASE)
836 #define DECL_CONTEXT(NAME) \
838 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
839 #define DECL_CONTEXT_BASE(NAME)
840 #include "clang/AST/DeclNodes.inc"
842 #define DECL(NAME, BASE)
843 #define DECL_CONTEXT_BASE(NAME) \
844 if (DK >= first##NAME && DK <= last##NAME) \
845 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
846 #include "clang/AST/DeclNodes.inc"
847 llvm_unreachable("a decl that inherits DeclContext isn't handled");
851 SourceLocation Decl::getBodyRBrace() const {
852 // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
853 // FunctionDecl stores EndRangeLoc for this purpose.
854 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
855 const FunctionDecl *Definition;
856 if (FD->hasBody(Definition))
857 return Definition->getSourceRange().getEnd();
858 return SourceLocation();
861 if (Stmt *Body = getBody())
862 return Body->getSourceRange().getEnd();
864 return SourceLocation();
867 bool Decl::AccessDeclContextSanity() const {
869 // Suppress this check if any of the following hold:
870 // 1. this is the translation unit (and thus has no parent)
871 // 2. this is a template parameter (and thus doesn't belong to its context)
872 // 3. this is a non-type template parameter
873 // 4. the context is not a record
875 // 6. it's a C++0x static_assert.
876 if (isa<TranslationUnitDecl>(this) ||
877 isa<TemplateTypeParmDecl>(this) ||
878 isa<NonTypeTemplateParmDecl>(this) ||
879 !isa<CXXRecordDecl>(getDeclContext()) ||
881 isa<StaticAssertDecl>(this) ||
882 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
883 // as DeclContext (?).
884 isa<ParmVarDecl>(this) ||
885 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
886 // AS_none as access specifier.
887 isa<CXXRecordDecl>(this) ||
888 isa<ClassScopeFunctionSpecializationDecl>(this))
891 assert(Access != AS_none &&
892 "Access specifier is AS_none inside a record decl");
897 static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
898 static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
900 const FunctionType *Decl::getFunctionType(bool BlocksToo) const {
902 if (const ValueDecl *D = dyn_cast<ValueDecl>(this))
904 else if (const TypedefNameDecl *D = dyn_cast<TypedefNameDecl>(this))
905 Ty = D->getUnderlyingType();
909 if (Ty->isFunctionPointerType())
910 Ty = Ty->getAs<PointerType>()->getPointeeType();
911 else if (BlocksToo && Ty->isBlockPointerType())
912 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
914 return Ty->getAs<FunctionType>();
918 /// Starting at a given context (a Decl or DeclContext), look for a
919 /// code context that is not a closure (a lambda, block, etc.).
920 template <class T> static Decl *getNonClosureContext(T *D) {
921 if (getKind(D) == Decl::CXXMethod) {
922 CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
923 if (MD->getOverloadedOperator() == OO_Call &&
924 MD->getParent()->isLambda())
925 return getNonClosureContext(MD->getParent()->getParent());
927 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
929 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
931 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
932 return getNonClosureContext(BD->getParent());
933 } else if (CapturedDecl *CD = dyn_cast<CapturedDecl>(D)) {
934 return getNonClosureContext(CD->getParent());
940 Decl *Decl::getNonClosureContext() {
941 return ::getNonClosureContext(this);
944 Decl *DeclContext::getNonClosureAncestor() {
945 return ::getNonClosureContext(this);
948 //===----------------------------------------------------------------------===//
949 // DeclContext Implementation
950 //===----------------------------------------------------------------------===//
952 bool DeclContext::classof(const Decl *D) {
953 switch (D->getKind()) {
954 #define DECL(NAME, BASE)
955 #define DECL_CONTEXT(NAME) case Decl::NAME:
956 #define DECL_CONTEXT_BASE(NAME)
957 #include "clang/AST/DeclNodes.inc"
960 #define DECL(NAME, BASE)
961 #define DECL_CONTEXT_BASE(NAME) \
962 if (D->getKind() >= Decl::first##NAME && \
963 D->getKind() <= Decl::last##NAME) \
965 #include "clang/AST/DeclNodes.inc"
970 DeclContext::~DeclContext() { }
972 /// \brief Find the parent context of this context that will be
973 /// used for unqualified name lookup.
975 /// Generally, the parent lookup context is the semantic context. However, for
976 /// a friend function the parent lookup context is the lexical context, which
977 /// is the class in which the friend is declared.
978 DeclContext *DeclContext::getLookupParent() {
979 // FIXME: Find a better way to identify friends
980 if (isa<FunctionDecl>(this))
981 if (getParent()->getRedeclContext()->isFileContext() &&
982 getLexicalParent()->getRedeclContext()->isRecord())
983 return getLexicalParent();
988 bool DeclContext::isInlineNamespace() const {
989 return isNamespace() &&
990 cast<NamespaceDecl>(this)->isInline();
993 bool DeclContext::isStdNamespace() const {
997 const NamespaceDecl *ND = cast<NamespaceDecl>(this);
998 if (ND->isInline()) {
999 return ND->getParent()->isStdNamespace();
1002 if (!getParent()->getRedeclContext()->isTranslationUnit())
1005 const IdentifierInfo *II = ND->getIdentifier();
1006 return II && II->isStr("std");
1009 bool DeclContext::isDependentContext() const {
1010 if (isFileContext())
1013 if (isa<ClassTemplatePartialSpecializationDecl>(this))
1016 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
1017 if (Record->getDescribedClassTemplate())
1020 if (Record->isDependentLambda())
1024 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
1025 if (Function->getDescribedFunctionTemplate())
1028 // Friend function declarations are dependent if their *lexical*
1029 // context is dependent.
1030 if (cast<Decl>(this)->getFriendObjectKind())
1031 return getLexicalParent()->isDependentContext();
1034 // FIXME: A variable template is a dependent context, but is not a
1035 // DeclContext. A context within it (such as a lambda-expression)
1036 // should be considered dependent.
1038 return getParent() && getParent()->isDependentContext();
1041 bool DeclContext::isTransparentContext() const {
1042 if (DeclKind == Decl::Enum)
1043 return !cast<EnumDecl>(this)->isScoped();
1044 else if (DeclKind == Decl::LinkageSpec || DeclKind == Decl::Export)
1050 static bool isLinkageSpecContext(const DeclContext *DC,
1051 LinkageSpecDecl::LanguageIDs ID) {
1052 while (DC->getDeclKind() != Decl::TranslationUnit) {
1053 if (DC->getDeclKind() == Decl::LinkageSpec)
1054 return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
1055 DC = DC->getLexicalParent();
1060 bool DeclContext::isExternCContext() const {
1061 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_c);
1064 const LinkageSpecDecl *DeclContext::getExternCContext() const {
1065 const DeclContext *DC = this;
1066 while (DC->getDeclKind() != Decl::TranslationUnit) {
1067 if (DC->getDeclKind() == Decl::LinkageSpec &&
1068 cast<LinkageSpecDecl>(DC)->getLanguage() ==
1069 clang::LinkageSpecDecl::lang_c)
1070 return cast<LinkageSpecDecl>(DC);
1071 DC = DC->getLexicalParent();
1076 bool DeclContext::isExternCXXContext() const {
1077 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_cxx);
1080 bool DeclContext::Encloses(const DeclContext *DC) const {
1081 if (getPrimaryContext() != this)
1082 return getPrimaryContext()->Encloses(DC);
1084 for (; DC; DC = DC->getParent())
1085 if (DC->getPrimaryContext() == this)
1090 DeclContext *DeclContext::getPrimaryContext() {
1092 case Decl::TranslationUnit:
1093 case Decl::ExternCContext:
1094 case Decl::LinkageSpec:
1097 case Decl::Captured:
1098 case Decl::OMPDeclareReduction:
1099 // There is only one DeclContext for these entities.
1102 case Decl::Namespace:
1103 // The original namespace is our primary context.
1104 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
1106 case Decl::ObjCMethod:
1109 case Decl::ObjCInterface:
1110 if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
1115 case Decl::ObjCProtocol:
1116 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
1121 case Decl::ObjCCategory:
1124 case Decl::ObjCImplementation:
1125 case Decl::ObjCCategoryImpl:
1129 if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
1130 // If this is a tag type that has a definition or is currently
1131 // being defined, that definition is our primary context.
1132 TagDecl *Tag = cast<TagDecl>(this);
1134 if (TagDecl *Def = Tag->getDefinition())
1137 if (const TagType *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) {
1138 // Note, TagType::getDecl returns the (partial) definition one exists.
1139 TagDecl *PossiblePartialDef = TagTy->getDecl();
1140 if (PossiblePartialDef->isBeingDefined())
1141 return PossiblePartialDef;
1143 assert(isa<InjectedClassNameType>(Tag->getTypeForDecl()));
1149 assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
1150 "Unknown DeclContext kind");
1156 DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
1159 if (DeclKind != Decl::Namespace) {
1160 Contexts.push_back(this);
1164 NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
1165 for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
1166 N = N->getPreviousDecl())
1167 Contexts.push_back(N);
1169 std::reverse(Contexts.begin(), Contexts.end());
1172 std::pair<Decl *, Decl *>
1173 DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
1174 bool FieldsAlreadyLoaded) {
1175 // Build up a chain of declarations via the Decl::NextInContextAndBits field.
1176 Decl *FirstNewDecl = nullptr;
1177 Decl *PrevDecl = nullptr;
1178 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1179 if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
1184 PrevDecl->NextInContextAndBits.setPointer(D);
1191 return std::make_pair(FirstNewDecl, PrevDecl);
1194 /// \brief We have just acquired external visible storage, and we already have
1195 /// built a lookup map. For every name in the map, pull in the new names from
1196 /// the external storage.
1197 void DeclContext::reconcileExternalVisibleStorage() const {
1198 assert(NeedToReconcileExternalVisibleStorage && LookupPtr);
1199 NeedToReconcileExternalVisibleStorage = false;
1201 for (auto &Lookup : *LookupPtr)
1202 Lookup.second.setHasExternalDecls();
1205 /// \brief Load the declarations within this lexical storage from an
1206 /// external source.
1207 /// \return \c true if any declarations were added.
1209 DeclContext::LoadLexicalDeclsFromExternalStorage() const {
1210 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1211 assert(hasExternalLexicalStorage() && Source && "No external storage?");
1213 // Notify that we have a DeclContext that is initializing.
1214 ExternalASTSource::Deserializing ADeclContext(Source);
1216 // Load the external declarations, if any.
1217 SmallVector<Decl*, 64> Decls;
1218 ExternalLexicalStorage = false;
1219 Source->FindExternalLexicalDecls(this, Decls);
1224 // We may have already loaded just the fields of this record, in which case
1225 // we need to ignore them.
1226 bool FieldsAlreadyLoaded = false;
1227 if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
1228 FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
1230 // Splice the newly-read declarations into the beginning of the list
1232 Decl *ExternalFirst, *ExternalLast;
1233 std::tie(ExternalFirst, ExternalLast) =
1234 BuildDeclChain(Decls, FieldsAlreadyLoaded);
1235 ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
1236 FirstDecl = ExternalFirst;
1238 LastDecl = ExternalLast;
1242 DeclContext::lookup_result
1243 ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
1244 DeclarationName Name) {
1245 ASTContext &Context = DC->getParentASTContext();
1246 StoredDeclsMap *Map;
1247 if (!(Map = DC->LookupPtr))
1248 Map = DC->CreateStoredDeclsMap(Context);
1249 if (DC->NeedToReconcileExternalVisibleStorage)
1250 DC->reconcileExternalVisibleStorage();
1252 (*Map)[Name].removeExternalDecls();
1254 return DeclContext::lookup_result();
1257 DeclContext::lookup_result
1258 ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
1259 DeclarationName Name,
1260 ArrayRef<NamedDecl*> Decls) {
1261 ASTContext &Context = DC->getParentASTContext();
1262 StoredDeclsMap *Map;
1263 if (!(Map = DC->LookupPtr))
1264 Map = DC->CreateStoredDeclsMap(Context);
1265 if (DC->NeedToReconcileExternalVisibleStorage)
1266 DC->reconcileExternalVisibleStorage();
1268 StoredDeclsList &List = (*Map)[Name];
1270 // Clear out any old external visible declarations, to avoid quadratic
1271 // performance in the redeclaration checks below.
1272 List.removeExternalDecls();
1274 if (!List.isNull()) {
1275 // We have both existing declarations and new declarations for this name.
1276 // Some of the declarations may simply replace existing ones. Handle those
1278 llvm::SmallVector<unsigned, 8> Skip;
1279 for (unsigned I = 0, N = Decls.size(); I != N; ++I)
1280 if (List.HandleRedeclaration(Decls[I], /*IsKnownNewer*/false))
1282 Skip.push_back(Decls.size());
1284 // Add in any new declarations.
1285 unsigned SkipPos = 0;
1286 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1287 if (I == Skip[SkipPos])
1290 List.AddSubsequentDecl(Decls[I]);
1293 // Convert the array to a StoredDeclsList.
1294 for (ArrayRef<NamedDecl*>::iterator
1295 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1297 List.setOnlyValue(*I);
1299 List.AddSubsequentDecl(*I);
1303 return List.getLookupResult();
1306 DeclContext::decl_iterator DeclContext::decls_begin() const {
1307 if (hasExternalLexicalStorage())
1308 LoadLexicalDeclsFromExternalStorage();
1309 return decl_iterator(FirstDecl);
1312 bool DeclContext::decls_empty() const {
1313 if (hasExternalLexicalStorage())
1314 LoadLexicalDeclsFromExternalStorage();
1319 bool DeclContext::containsDecl(Decl *D) const {
1320 return (D->getLexicalDeclContext() == this &&
1321 (D->NextInContextAndBits.getPointer() || D == LastDecl));
1324 void DeclContext::removeDecl(Decl *D) {
1325 assert(D->getLexicalDeclContext() == this &&
1326 "decl being removed from non-lexical context");
1327 assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
1328 "decl is not in decls list");
1330 // Remove D from the decl chain. This is O(n) but hopefully rare.
1331 if (D == FirstDecl) {
1333 FirstDecl = LastDecl = nullptr;
1335 FirstDecl = D->NextInContextAndBits.getPointer();
1337 for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
1338 assert(I && "decl not found in linked list");
1339 if (I->NextInContextAndBits.getPointer() == D) {
1340 I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
1341 if (D == LastDecl) LastDecl = I;
1347 // Mark that D is no longer in the decl chain.
1348 D->NextInContextAndBits.setPointer(nullptr);
1350 // Remove D from the lookup table if necessary.
1351 if (isa<NamedDecl>(D)) {
1352 NamedDecl *ND = cast<NamedDecl>(D);
1354 // Remove only decls that have a name
1355 if (!ND->getDeclName()) return;
1357 auto *DC = D->getDeclContext();
1359 StoredDeclsMap *Map = DC->getPrimaryContext()->LookupPtr;
1361 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1362 assert(Pos != Map->end() && "no lookup entry for decl");
1363 if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
1364 Pos->second.remove(ND);
1366 } while (DC->isTransparentContext() && (DC = DC->getParent()));
1370 void DeclContext::addHiddenDecl(Decl *D) {
1371 assert(D->getLexicalDeclContext() == this &&
1372 "Decl inserted into wrong lexical context");
1373 assert(!D->getNextDeclInContext() && D != LastDecl &&
1374 "Decl already inserted into a DeclContext");
1377 LastDecl->NextInContextAndBits.setPointer(D);
1380 FirstDecl = LastDecl = D;
1383 // Notify a C++ record declaration that we've added a member, so it can
1384 // update its class-specific state.
1385 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1386 Record->addedMember(D);
1388 // If this is a newly-created (not de-serialized) import declaration, wire
1389 // it in to the list of local import declarations.
1390 if (!D->isFromASTFile()) {
1391 if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
1392 D->getASTContext().addedLocalImportDecl(Import);
1396 void DeclContext::addDecl(Decl *D) {
1399 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1400 ND->getDeclContext()->getPrimaryContext()->
1401 makeDeclVisibleInContextWithFlags(ND, false, true);
1404 void DeclContext::addDeclInternal(Decl *D) {
1407 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1408 ND->getDeclContext()->getPrimaryContext()->
1409 makeDeclVisibleInContextWithFlags(ND, true, true);
1412 /// shouldBeHidden - Determine whether a declaration which was declared
1413 /// within its semantic context should be invisible to qualified name lookup.
1414 static bool shouldBeHidden(NamedDecl *D) {
1415 // Skip unnamed declarations.
1416 if (!D->getDeclName())
1419 // Skip entities that can't be found by name lookup into a particular
1421 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1422 D->isTemplateParameter())
1425 // Skip template specializations.
1426 // FIXME: This feels like a hack. Should DeclarationName support
1427 // template-ids, or is there a better way to keep specializations
1428 // from being visible?
1429 if (isa<ClassTemplateSpecializationDecl>(D))
1431 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1432 if (FD->isFunctionTemplateSpecialization())
1438 /// buildLookup - Build the lookup data structure with all of the
1439 /// declarations in this DeclContext (and any other contexts linked
1440 /// to it or transparent contexts nested within it) and return it.
1442 /// Note that the produced map may miss out declarations from an
1443 /// external source. If it does, those entries will be marked with
1444 /// the 'hasExternalDecls' flag.
1445 StoredDeclsMap *DeclContext::buildLookup() {
1446 assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1448 if (!HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups)
1451 SmallVector<DeclContext *, 2> Contexts;
1452 collectAllContexts(Contexts);
1454 if (HasLazyExternalLexicalLookups) {
1455 HasLazyExternalLexicalLookups = false;
1456 for (auto *DC : Contexts) {
1457 if (DC->hasExternalLexicalStorage())
1458 HasLazyLocalLexicalLookups |=
1459 DC->LoadLexicalDeclsFromExternalStorage();
1462 if (!HasLazyLocalLexicalLookups)
1466 for (auto *DC : Contexts)
1467 buildLookupImpl(DC, hasExternalVisibleStorage());
1469 // We no longer have any lazy decls.
1470 HasLazyLocalLexicalLookups = false;
1474 /// buildLookupImpl - Build part of the lookup data structure for the
1475 /// declarations contained within DCtx, which will either be this
1476 /// DeclContext, a DeclContext linked to it, or a transparent context
1477 /// nested within it.
1478 void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {
1479 for (Decl *D : DCtx->noload_decls()) {
1480 // Insert this declaration into the lookup structure, but only if
1481 // it's semantically within its decl context. Any other decls which
1482 // should be found in this context are added eagerly.
1484 // If it's from an AST file, don't add it now. It'll get handled by
1485 // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1486 // in C++, we do not track external visible decls for the TU, so in
1487 // that case we need to collect them all here.
1488 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1489 if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1490 (!ND->isFromASTFile() ||
1491 (isTranslationUnit() &&
1492 !getParentASTContext().getLangOpts().CPlusPlus)))
1493 makeDeclVisibleInContextImpl(ND, Internal);
1495 // If this declaration is itself a transparent declaration context
1496 // or inline namespace, add the members of this declaration of that
1497 // context (recursively).
1498 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
1499 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1500 buildLookupImpl(InnerCtx, Internal);
1504 NamedDecl *const DeclContextLookupResult::SingleElementDummyList = nullptr;
1506 DeclContext::lookup_result
1507 DeclContext::lookup(DeclarationName Name) const {
1508 assert(DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export &&
1509 "should not perform lookups into transparent contexts");
1511 const DeclContext *PrimaryContext = getPrimaryContext();
1512 if (PrimaryContext != this)
1513 return PrimaryContext->lookup(Name);
1515 // If we have an external source, ensure that any later redeclarations of this
1516 // context have been loaded, since they may add names to the result of this
1517 // lookup (or add external visible storage).
1518 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1520 (void)cast<Decl>(this)->getMostRecentDecl();
1522 if (hasExternalVisibleStorage()) {
1523 assert(Source && "external visible storage but no external source?");
1525 if (NeedToReconcileExternalVisibleStorage)
1526 reconcileExternalVisibleStorage();
1528 StoredDeclsMap *Map = LookupPtr;
1530 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
1531 // FIXME: Make buildLookup const?
1532 Map = const_cast<DeclContext*>(this)->buildLookup();
1535 Map = CreateStoredDeclsMap(getParentASTContext());
1537 // If we have a lookup result with no external decls, we are done.
1538 std::pair<StoredDeclsMap::iterator, bool> R =
1539 Map->insert(std::make_pair(Name, StoredDeclsList()));
1540 if (!R.second && !R.first->second.hasExternalDecls())
1541 return R.first->second.getLookupResult();
1543 if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) {
1544 if (StoredDeclsMap *Map = LookupPtr) {
1545 StoredDeclsMap::iterator I = Map->find(Name);
1546 if (I != Map->end())
1547 return I->second.getLookupResult();
1551 return lookup_result();
1554 StoredDeclsMap *Map = LookupPtr;
1555 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
1556 Map = const_cast<DeclContext*>(this)->buildLookup();
1559 return lookup_result();
1561 StoredDeclsMap::iterator I = Map->find(Name);
1562 if (I == Map->end())
1563 return lookup_result();
1565 return I->second.getLookupResult();
1568 DeclContext::lookup_result
1569 DeclContext::noload_lookup(DeclarationName Name) {
1570 assert(DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export &&
1571 "should not perform lookups into transparent contexts");
1573 DeclContext *PrimaryContext = getPrimaryContext();
1574 if (PrimaryContext != this)
1575 return PrimaryContext->noload_lookup(Name);
1577 // If we have any lazy lexical declarations not in our lookup map, add them
1578 // now. Don't import any external declarations, not even if we know we have
1579 // some missing from the external visible lookups.
1580 if (HasLazyLocalLexicalLookups) {
1581 SmallVector<DeclContext *, 2> Contexts;
1582 collectAllContexts(Contexts);
1583 for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
1584 buildLookupImpl(Contexts[I], hasExternalVisibleStorage());
1585 HasLazyLocalLexicalLookups = false;
1588 StoredDeclsMap *Map = LookupPtr;
1590 return lookup_result();
1592 StoredDeclsMap::iterator I = Map->find(Name);
1593 return I != Map->end() ? I->second.getLookupResult()
1597 void DeclContext::localUncachedLookup(DeclarationName Name,
1598 SmallVectorImpl<NamedDecl *> &Results) {
1601 // If there's no external storage, just perform a normal lookup and copy
1603 if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
1604 lookup_result LookupResults = lookup(Name);
1605 Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
1609 // If we have a lookup table, check there first. Maybe we'll get lucky.
1610 // FIXME: Should we be checking these flags on the primary context?
1611 if (Name && !HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups) {
1612 if (StoredDeclsMap *Map = LookupPtr) {
1613 StoredDeclsMap::iterator Pos = Map->find(Name);
1614 if (Pos != Map->end()) {
1615 Results.insert(Results.end(),
1616 Pos->second.getLookupResult().begin(),
1617 Pos->second.getLookupResult().end());
1623 // Slow case: grovel through the declarations in our chain looking for
1625 // FIXME: If we have lazy external declarations, this will not find them!
1626 // FIXME: Should we CollectAllContexts and walk them all here?
1627 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1628 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1629 if (ND->getDeclName() == Name)
1630 Results.push_back(ND);
1634 DeclContext *DeclContext::getRedeclContext() {
1635 DeclContext *Ctx = this;
1636 // Skip through transparent contexts.
1637 while (Ctx->isTransparentContext())
1638 Ctx = Ctx->getParent();
1642 DeclContext *DeclContext::getEnclosingNamespaceContext() {
1643 DeclContext *Ctx = this;
1644 // Skip through non-namespace, non-translation-unit contexts.
1645 while (!Ctx->isFileContext())
1646 Ctx = Ctx->getParent();
1647 return Ctx->getPrimaryContext();
1650 RecordDecl *DeclContext::getOuterLexicalRecordContext() {
1651 // Loop until we find a non-record context.
1652 RecordDecl *OutermostRD = nullptr;
1653 DeclContext *DC = this;
1654 while (DC->isRecord()) {
1655 OutermostRD = cast<RecordDecl>(DC);
1656 DC = DC->getLexicalParent();
1661 bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1662 // For non-file contexts, this is equivalent to Equals.
1663 if (!isFileContext())
1664 return O->Equals(this);
1667 if (O->Equals(this))
1670 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1671 if (!NS || !NS->isInline())
1673 O = NS->getParent();
1679 void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1680 DeclContext *PrimaryDC = this->getPrimaryContext();
1681 DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1682 // If the decl is being added outside of its semantic decl context, we
1683 // need to ensure that we eagerly build the lookup information for it.
1684 PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
1687 void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1689 assert(this == getPrimaryContext() && "expected a primary DC");
1691 if (!isLookupContext()) {
1692 if (isTransparentContext())
1693 getParent()->getPrimaryContext()
1694 ->makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1698 // Skip declarations which should be invisible to name lookup.
1699 if (shouldBeHidden(D))
1702 // If we already have a lookup data structure, perform the insertion into
1703 // it. If we might have externally-stored decls with this name, look them
1704 // up and perform the insertion. If this decl was declared outside its
1705 // semantic context, buildLookup won't add it, so add it now.
1707 // FIXME: As a performance hack, don't add such decls into the translation
1708 // unit unless we're in C++, since qualified lookup into the TU is never
1710 if (LookupPtr || hasExternalVisibleStorage() ||
1711 ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1712 (getParentASTContext().getLangOpts().CPlusPlus ||
1713 !isTranslationUnit()))) {
1714 // If we have lazily omitted any decls, they might have the same name as
1715 // the decl which we are adding, so build a full lookup table before adding
1718 makeDeclVisibleInContextImpl(D, Internal);
1720 HasLazyLocalLexicalLookups = true;
1723 // If we are a transparent context or inline namespace, insert into our
1724 // parent context, too. This operation is recursive.
1725 if (isTransparentContext() || isInlineNamespace())
1726 getParent()->getPrimaryContext()->
1727 makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1729 Decl *DCAsDecl = cast<Decl>(this);
1730 // Notify that a decl was made visible unless we are a Tag being defined.
1731 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1732 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1733 L->AddedVisibleDecl(this, D);
1736 void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1737 // Find or create the stored declaration map.
1738 StoredDeclsMap *Map = LookupPtr;
1740 ASTContext *C = &getParentASTContext();
1741 Map = CreateStoredDeclsMap(*C);
1744 // If there is an external AST source, load any declarations it knows about
1745 // with this declaration's name.
1746 // If the lookup table contains an entry about this name it means that we
1747 // have already checked the external source.
1749 if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1750 if (hasExternalVisibleStorage() &&
1751 Map->find(D->getDeclName()) == Map->end())
1752 Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1754 // Insert this declaration into the map.
1755 StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
1758 // If this is being added as part of loading an external declaration,
1759 // this may not be the only external declaration with this name.
1760 // In this case, we never try to replace an existing declaration; we'll
1761 // handle that when we finalize the list of declarations for this name.
1762 DeclNameEntries.setHasExternalDecls();
1763 DeclNameEntries.AddSubsequentDecl(D);
1767 if (DeclNameEntries.isNull()) {
1768 DeclNameEntries.setOnlyValue(D);
1772 if (DeclNameEntries.HandleRedeclaration(D, /*IsKnownNewer*/!Internal)) {
1773 // This declaration has replaced an existing one for which
1774 // declarationReplaces returns true.
1778 // Put this declaration into the appropriate slot.
1779 DeclNameEntries.AddSubsequentDecl(D);
1782 UsingDirectiveDecl *DeclContext::udir_iterator::operator*() const {
1783 return cast<UsingDirectiveDecl>(*I);
1786 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1788 DeclContext::udir_range DeclContext::using_directives() const {
1789 // FIXME: Use something more efficient than normal lookup for using
1790 // directives. In C++, using directives are looked up more than anything else.
1791 lookup_result Result = lookup(UsingDirectiveDecl::getName());
1792 return udir_range(Result.begin(), Result.end());
1795 //===----------------------------------------------------------------------===//
1796 // Creation and Destruction of StoredDeclsMaps. //
1797 //===----------------------------------------------------------------------===//
1799 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1800 assert(!LookupPtr && "context already has a decls map");
1801 assert(getPrimaryContext() == this &&
1802 "creating decls map on non-primary context");
1805 bool Dependent = isDependentContext();
1807 M = new DependentStoredDeclsMap();
1809 M = new StoredDeclsMap();
1810 M->Previous = C.LastSDM;
1811 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1816 void ASTContext::ReleaseDeclContextMaps() {
1817 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1818 // pointer because the subclass doesn't add anything that needs to
1820 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1823 void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1825 // Advance the iteration before we invalidate memory.
1826 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1829 delete static_cast<DependentStoredDeclsMap*>(Map);
1833 Map = Next.getPointer();
1834 Dependent = Next.getInt();
1838 DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1839 DeclContext *Parent,
1840 const PartialDiagnostic &PDiag) {
1841 assert(Parent->isDependentContext()
1842 && "cannot iterate dependent diagnostics of non-dependent context");
1843 Parent = Parent->getPrimaryContext();
1844 if (!Parent->LookupPtr)
1845 Parent->CreateStoredDeclsMap(C);
1847 DependentStoredDeclsMap *Map =
1848 static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr);
1850 // Allocate the copy of the PartialDiagnostic via the ASTContext's
1851 // BumpPtrAllocator, rather than the ASTContext itself.
1852 PartialDiagnostic::Storage *DiagStorage = nullptr;
1853 if (PDiag.hasStorage())
1854 DiagStorage = new (C) PartialDiagnostic::Storage;
1856 DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
1858 // TODO: Maybe we shouldn't reverse the order during insertion.
1859 DD->NextDiagnostic = Map->FirstDiagnostic;
1860 Map->FirstDiagnostic = DD;