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/Decl.h"
16 #include "clang/AST/DeclContextInternals.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclFriend.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/DependentDiagnostic.h"
22 #include "clang/AST/ExternalASTSource.h"
23 #include "clang/AST/ASTContext.h"
24 #include "clang/AST/Type.h"
25 #include "clang/AST/Stmt.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/AST/ASTMutationListener.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/Support/raw_ostream.h"
32 using namespace clang;
34 //===----------------------------------------------------------------------===//
36 //===----------------------------------------------------------------------===//
38 #define DECL(DERIVED, BASE) static int n##DERIVED##s = 0;
39 #define ABSTRACT_DECL(DECL)
40 #include "clang/AST/DeclNodes.inc"
42 static bool StatSwitch = false;
44 const char *Decl::getDeclKindName() const {
46 default: assert(0 && "Declaration not in DeclNodes.inc!");
47 #define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
48 #define ABSTRACT_DECL(DECL)
49 #include "clang/AST/DeclNodes.inc"
53 void Decl::setInvalidDecl(bool Invalid) {
54 InvalidDecl = Invalid;
56 // Defensive maneuver for ill-formed code: we're likely not to make it to
57 // a point where we set the access specifier, so default it to "public"
58 // to avoid triggering asserts elsewhere in the front end.
63 const char *DeclContext::getDeclKindName() const {
65 default: assert(0 && "Declaration context not in DeclNodes.inc!");
66 #define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
67 #define ABSTRACT_DECL(DECL)
68 #include "clang/AST/DeclNodes.inc"
72 bool Decl::CollectingStats(bool Enable) {
73 if (Enable) StatSwitch = true;
77 void Decl::PrintStats() {
78 llvm::errs() << "\n*** Decl Stats:\n";
81 #define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
82 #define ABSTRACT_DECL(DECL)
83 #include "clang/AST/DeclNodes.inc"
84 llvm::errs() << " " << totalDecls << " decls total.\n";
87 #define DECL(DERIVED, BASE) \
88 if (n##DERIVED##s > 0) { \
89 totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \
90 llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \
91 << sizeof(DERIVED##Decl) << " each (" \
92 << n##DERIVED##s * sizeof(DERIVED##Decl) \
95 #define ABSTRACT_DECL(DECL)
96 #include "clang/AST/DeclNodes.inc"
98 llvm::errs() << "Total bytes = " << totalBytes << "\n";
101 void Decl::add(Kind k) {
103 default: assert(0 && "Declaration not in DeclNodes.inc!");
104 #define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
105 #define ABSTRACT_DECL(DECL)
106 #include "clang/AST/DeclNodes.inc"
110 bool Decl::isTemplateParameterPack() const {
111 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
112 return TTP->isParameterPack();
113 if (const NonTypeTemplateParmDecl *NTTP
114 = dyn_cast<NonTypeTemplateParmDecl>(this))
115 return NTTP->isParameterPack();
116 if (const TemplateTemplateParmDecl *TTP
117 = dyn_cast<TemplateTemplateParmDecl>(this))
118 return TTP->isParameterPack();
122 bool Decl::isParameterPack() const {
123 if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this))
124 return Parm->isParameterPack();
126 return isTemplateParameterPack();
129 bool Decl::isFunctionOrFunctionTemplate() const {
130 if (const UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(this))
131 return UD->getTargetDecl()->isFunctionOrFunctionTemplate();
133 return isa<FunctionDecl>(this) || isa<FunctionTemplateDecl>(this);
136 bool Decl::isDefinedOutsideFunctionOrMethod() const {
137 for (const DeclContext *DC = getDeclContext();
138 DC && !DC->isTranslationUnit();
139 DC = DC->getParent())
140 if (DC->isFunctionOrMethod())
147 //===----------------------------------------------------------------------===//
148 // PrettyStackTraceDecl Implementation
149 //===----------------------------------------------------------------------===//
151 void PrettyStackTraceDecl::print(llvm::raw_ostream &OS) const {
152 SourceLocation TheLoc = Loc;
153 if (TheLoc.isInvalid() && TheDecl)
154 TheLoc = TheDecl->getLocation();
156 if (TheLoc.isValid()) {
157 TheLoc.print(OS, SM);
163 if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl))
164 OS << " '" << DN->getQualifiedNameAsString() << '\'';
168 //===----------------------------------------------------------------------===//
169 // Decl Implementation
170 //===----------------------------------------------------------------------===//
172 // Out-of-line virtual method providing a home for Decl.
175 void Decl::setDeclContext(DeclContext *DC) {
179 void Decl::setLexicalDeclContext(DeclContext *DC) {
180 if (DC == getLexicalDeclContext())
184 MultipleDC *MDC = new (getASTContext()) MultipleDC();
185 MDC->SemanticDC = getDeclContext();
189 getMultipleDC()->LexicalDC = DC;
193 bool Decl::isInAnonymousNamespace() const {
194 const DeclContext *DC = getDeclContext();
196 if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
197 if (ND->isAnonymousNamespace())
199 } while ((DC = DC->getParent()));
204 TranslationUnitDecl *Decl::getTranslationUnitDecl() {
205 if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
208 DeclContext *DC = getDeclContext();
209 assert(DC && "This decl is not contained in a translation unit!");
211 while (!DC->isTranslationUnit()) {
212 DC = DC->getParent();
213 assert(DC && "This decl is not contained in a translation unit!");
216 return cast<TranslationUnitDecl>(DC);
219 ASTContext &Decl::getASTContext() const {
220 return getTranslationUnitDecl()->getASTContext();
223 ASTMutationListener *Decl::getASTMutationListener() const {
224 return getASTContext().getASTMutationListener();
227 bool Decl::isUsed(bool CheckUsedAttr) const {
231 // Check for used attribute.
232 if (CheckUsedAttr && hasAttr<UsedAttr>())
235 // Check redeclarations for used attribute.
236 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
237 if ((CheckUsedAttr && I->hasAttr<UsedAttr>()) || I->Used)
244 bool Decl::isReferenced() const {
248 // Check redeclarations.
249 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
256 /// \brief Determine the availability of the given declaration based on
257 /// the target platform.
259 /// When it returns an availability result other than \c AR_Available,
260 /// if the \p Message parameter is non-NULL, it will be set to a
261 /// string describing why the entity is unavailable.
263 /// FIXME: Make these strings localizable, since they end up in
265 static AvailabilityResult CheckAvailability(ASTContext &Context,
266 const AvailabilityAttr *A,
267 std::string *Message) {
268 llvm::StringRef TargetPlatform = Context.Target.getPlatformName();
269 llvm::StringRef PrettyPlatformName
270 = AvailabilityAttr::getPrettyPlatformName(TargetPlatform);
271 if (PrettyPlatformName.empty())
272 PrettyPlatformName = TargetPlatform;
274 VersionTuple TargetMinVersion = Context.Target.getPlatformMinVersion();
275 if (TargetMinVersion.empty())
278 // Match the platform name.
279 if (A->getPlatform()->getName() != TargetPlatform)
282 // Make sure that this declaration has not been marked 'unavailable'.
283 if (A->getUnavailable()) {
286 llvm::raw_string_ostream Out(*Message);
287 Out << "not available on " << PrettyPlatformName;
290 return AR_Unavailable;
293 // Make sure that this declaration has already been introduced.
294 if (!A->getIntroduced().empty() &&
295 TargetMinVersion < A->getIntroduced()) {
298 llvm::raw_string_ostream Out(*Message);
299 Out << "introduced in " << PrettyPlatformName << ' '
300 << A->getIntroduced();
303 return AR_NotYetIntroduced;
306 // Make sure that this declaration hasn't been obsoleted.
307 if (!A->getObsoleted().empty() && TargetMinVersion >= A->getObsoleted()) {
310 llvm::raw_string_ostream Out(*Message);
311 Out << "obsoleted in " << PrettyPlatformName << ' '
312 << A->getObsoleted();
315 return AR_Unavailable;
318 // Make sure that this declaration hasn't been deprecated.
319 if (!A->getDeprecated().empty() && TargetMinVersion >= A->getDeprecated()) {
322 llvm::raw_string_ostream Out(*Message);
323 Out << "first deprecated in " << PrettyPlatformName << ' '
324 << A->getDeprecated();
327 return AR_Deprecated;
333 AvailabilityResult Decl::getAvailability(std::string *Message) const {
334 AvailabilityResult Result = AR_Available;
335 std::string ResultMessage;
337 for (attr_iterator A = attr_begin(), AEnd = attr_end(); A != AEnd; ++A) {
338 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(*A)) {
339 if (Result >= AR_Deprecated)
343 ResultMessage = Deprecated->getMessage();
345 Result = AR_Deprecated;
349 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(*A)) {
351 *Message = Unavailable->getMessage();
352 return AR_Unavailable;
355 if (AvailabilityAttr *Availability = dyn_cast<AvailabilityAttr>(*A)) {
356 AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
359 if (AR == AR_Unavailable)
360 return AR_Unavailable;
365 ResultMessage.swap(*Message);
372 Message->swap(ResultMessage);
376 bool Decl::canBeWeakImported(bool &IsDefinition) const {
377 IsDefinition = false;
378 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
379 if (!Var->hasExternalStorage() || Var->getInit()) {
383 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
388 } else if (isa<ObjCPropertyDecl>(this) || isa<ObjCMethodDecl>(this))
390 else if (!(getASTContext().getLangOptions().ObjCNonFragileABI &&
391 isa<ObjCInterfaceDecl>(this)))
397 bool Decl::isWeakImported() const {
399 if (!canBeWeakImported(IsDefinition))
402 for (attr_iterator A = attr_begin(), AEnd = attr_end(); A != AEnd; ++A) {
403 if (isa<WeakImportAttr>(*A))
406 if (AvailabilityAttr *Availability = dyn_cast<AvailabilityAttr>(*A)) {
407 if (CheckAvailability(getASTContext(), Availability, 0)
408 == AR_NotYetIntroduced)
416 unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
427 case NonTypeTemplateParm:
430 return IDNS_Ordinary;
434 return IDNS_Ordinary | IDNS_Member;
436 case ObjCCompatibleAlias:
438 return IDNS_Ordinary | IDNS_Type;
442 case TypeAliasTemplate:
443 case UnresolvedUsingTypename:
444 case TemplateTypeParm:
445 return IDNS_Ordinary | IDNS_Type;
448 return 0; // we'll actually overwrite this later
450 case UnresolvedUsingValue:
451 return IDNS_Ordinary | IDNS_Using;
457 return IDNS_ObjCProtocol;
460 case ObjCAtDefsField:
467 return IDNS_Tag | IDNS_Type;
471 return IDNS_Namespace;
473 case FunctionTemplate:
474 return IDNS_Ordinary;
477 case TemplateTemplateParm:
478 return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
488 case ObjCPropertyImpl:
489 case ObjCForwardProtocol:
491 case TranslationUnit:
494 case ClassTemplateSpecialization:
495 case ClassTemplatePartialSpecialization:
496 case ObjCImplementation:
498 case ObjCCategoryImpl:
499 // Never looked up by name.
506 void Decl::setAttrs(const AttrVec &attrs) {
507 assert(!HasAttrs && "Decl already contains attrs.");
509 AttrVec &AttrBlank = getASTContext().getDeclAttrs(this);
510 assert(AttrBlank.empty() && "HasAttrs was wrong?");
516 void Decl::dropAttrs() {
517 if (!HasAttrs) return;
520 getASTContext().eraseDeclAttrs(this);
523 const AttrVec &Decl::getAttrs() const {
524 assert(HasAttrs && "No attrs to get!");
525 return getASTContext().getDeclAttrs(this);
528 void Decl::swapAttrs(Decl *RHS) {
529 bool HasLHSAttr = this->HasAttrs;
530 bool HasRHSAttr = RHS->HasAttrs;
532 // Usually, neither decl has attrs, nothing to do.
533 if (!HasLHSAttr && !HasRHSAttr) return;
535 // If 'this' has no attrs, swap the other way.
537 return RHS->swapAttrs(this);
539 ASTContext &Context = getASTContext();
541 // Handle the case when both decls have attrs.
543 std::swap(Context.getDeclAttrs(this), Context.getDeclAttrs(RHS));
547 // Otherwise, LHS has an attr and RHS doesn't.
548 Context.getDeclAttrs(RHS) = Context.getDeclAttrs(this);
549 Context.eraseDeclAttrs(this);
550 this->HasAttrs = false;
551 RHS->HasAttrs = true;
554 Decl *Decl::castFromDeclContext (const DeclContext *D) {
555 Decl::Kind DK = D->getDeclKind();
557 #define DECL(NAME, BASE)
558 #define DECL_CONTEXT(NAME) \
560 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
561 #define DECL_CONTEXT_BASE(NAME)
562 #include "clang/AST/DeclNodes.inc"
564 #define DECL(NAME, BASE)
565 #define DECL_CONTEXT_BASE(NAME) \
566 if (DK >= first##NAME && DK <= last##NAME) \
567 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
568 #include "clang/AST/DeclNodes.inc"
569 assert(false && "a decl that inherits DeclContext isn't handled");
574 DeclContext *Decl::castToDeclContext(const Decl *D) {
575 Decl::Kind DK = D->getKind();
577 #define DECL(NAME, BASE)
578 #define DECL_CONTEXT(NAME) \
580 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
581 #define DECL_CONTEXT_BASE(NAME)
582 #include "clang/AST/DeclNodes.inc"
584 #define DECL(NAME, BASE)
585 #define DECL_CONTEXT_BASE(NAME) \
586 if (DK >= first##NAME && DK <= last##NAME) \
587 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
588 #include "clang/AST/DeclNodes.inc"
589 assert(false && "a decl that inherits DeclContext isn't handled");
594 SourceLocation Decl::getBodyRBrace() const {
595 // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
596 // FunctionDecl stores EndRangeLoc for this purpose.
597 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
598 const FunctionDecl *Definition;
599 if (FD->hasBody(Definition))
600 return Definition->getSourceRange().getEnd();
601 return SourceLocation();
604 if (Stmt *Body = getBody())
605 return Body->getSourceRange().getEnd();
607 return SourceLocation();
610 void Decl::CheckAccessDeclContext() const {
612 // Suppress this check if any of the following hold:
613 // 1. this is the translation unit (and thus has no parent)
614 // 2. this is a template parameter (and thus doesn't belong to its context)
615 // 3. this is a non-type template parameter
616 // 4. the context is not a record
618 // 6. it's a C++0x static_assert.
619 if (isa<TranslationUnitDecl>(this) ||
620 isa<TemplateTypeParmDecl>(this) ||
621 isa<NonTypeTemplateParmDecl>(this) ||
622 !isa<CXXRecordDecl>(getDeclContext()) ||
624 isa<StaticAssertDecl>(this) ||
625 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
626 // as DeclContext (?).
627 isa<ParmVarDecl>(this) ||
628 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
629 // AS_none as access specifier.
630 isa<CXXRecordDecl>(this))
633 assert(Access != AS_none &&
634 "Access specifier is AS_none inside a record decl");
638 DeclContext *Decl::getNonClosureContext() {
639 DeclContext *DC = getDeclContext();
641 // This is basically "while (DC->isClosure()) DC = DC->getParent();"
642 // except that it's significantly more efficient to cast to a known
643 // decl type and call getDeclContext() than to call getParent().
644 while (isa<BlockDecl>(DC))
645 DC = cast<BlockDecl>(DC)->getDeclContext();
647 assert(!DC->isClosure());
651 //===----------------------------------------------------------------------===//
652 // DeclContext Implementation
653 //===----------------------------------------------------------------------===//
655 bool DeclContext::classof(const Decl *D) {
656 switch (D->getKind()) {
657 #define DECL(NAME, BASE)
658 #define DECL_CONTEXT(NAME) case Decl::NAME:
659 #define DECL_CONTEXT_BASE(NAME)
660 #include "clang/AST/DeclNodes.inc"
663 #define DECL(NAME, BASE)
664 #define DECL_CONTEXT_BASE(NAME) \
665 if (D->getKind() >= Decl::first##NAME && \
666 D->getKind() <= Decl::last##NAME) \
668 #include "clang/AST/DeclNodes.inc"
673 DeclContext::~DeclContext() { }
675 /// \brief Find the parent context of this context that will be
676 /// used for unqualified name lookup.
678 /// Generally, the parent lookup context is the semantic context. However, for
679 /// a friend function the parent lookup context is the lexical context, which
680 /// is the class in which the friend is declared.
681 DeclContext *DeclContext::getLookupParent() {
682 // FIXME: Find a better way to identify friends
683 if (isa<FunctionDecl>(this))
684 if (getParent()->getRedeclContext()->isFileContext() &&
685 getLexicalParent()->getRedeclContext()->isRecord())
686 return getLexicalParent();
691 bool DeclContext::isInlineNamespace() const {
692 return isNamespace() &&
693 cast<NamespaceDecl>(this)->isInline();
696 bool DeclContext::isDependentContext() const {
700 if (isa<ClassTemplatePartialSpecializationDecl>(this))
703 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
704 if (Record->getDescribedClassTemplate())
707 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
708 if (Function->getDescribedFunctionTemplate())
711 // Friend function declarations are dependent if their *lexical*
712 // context is dependent.
713 if (cast<Decl>(this)->getFriendObjectKind())
714 return getLexicalParent()->isDependentContext();
717 return getParent() && getParent()->isDependentContext();
720 bool DeclContext::isTransparentContext() const {
721 if (DeclKind == Decl::Enum)
722 return !cast<EnumDecl>(this)->isScoped();
723 else if (DeclKind == Decl::LinkageSpec)
729 bool DeclContext::isExternCContext() const {
730 const DeclContext *DC = this;
731 while (DC->DeclKind != Decl::TranslationUnit) {
732 if (DC->DeclKind == Decl::LinkageSpec)
733 return cast<LinkageSpecDecl>(DC)->getLanguage()
734 == LinkageSpecDecl::lang_c;
735 DC = DC->getParent();
740 bool DeclContext::Encloses(const DeclContext *DC) const {
741 if (getPrimaryContext() != this)
742 return getPrimaryContext()->Encloses(DC);
744 for (; DC; DC = DC->getParent())
745 if (DC->getPrimaryContext() == this)
750 DeclContext *DeclContext::getPrimaryContext() {
752 case Decl::TranslationUnit:
753 case Decl::LinkageSpec:
755 // There is only one DeclContext for these entities.
758 case Decl::Namespace:
759 // The original namespace is our primary context.
760 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
762 case Decl::ObjCMethod:
765 case Decl::ObjCInterface:
766 case Decl::ObjCProtocol:
767 case Decl::ObjCCategory:
768 // FIXME: Can Objective-C interfaces be forward-declared?
771 case Decl::ObjCImplementation:
772 case Decl::ObjCCategoryImpl:
776 if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
777 // If this is a tag type that has a definition or is currently
778 // being defined, that definition is our primary context.
779 TagDecl *Tag = cast<TagDecl>(this);
780 assert(isa<TagType>(Tag->TypeForDecl) ||
781 isa<InjectedClassNameType>(Tag->TypeForDecl));
783 if (TagDecl *Def = Tag->getDefinition())
786 if (!isa<InjectedClassNameType>(Tag->TypeForDecl)) {
787 const TagType *TagTy = cast<TagType>(Tag->TypeForDecl);
788 if (TagTy->isBeingDefined())
789 // FIXME: is it necessarily being defined in the decl
790 // that owns the type?
791 return TagTy->getDecl();
797 assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
798 "Unknown DeclContext kind");
803 DeclContext *DeclContext::getNextContext() {
805 case Decl::Namespace:
806 // Return the next namespace
807 return static_cast<NamespaceDecl*>(this)->getNextNamespace();
814 std::pair<Decl *, Decl *>
815 DeclContext::BuildDeclChain(const llvm::SmallVectorImpl<Decl*> &Decls) {
816 // Build up a chain of declarations via the Decl::NextDeclInContext field.
817 Decl *FirstNewDecl = 0;
819 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
822 PrevDecl->NextDeclInContext = D;
829 return std::make_pair(FirstNewDecl, PrevDecl);
832 /// \brief Load the declarations within this lexical storage from an
835 DeclContext::LoadLexicalDeclsFromExternalStorage() const {
836 ExternalASTSource *Source = getParentASTContext().getExternalSource();
837 assert(hasExternalLexicalStorage() && Source && "No external storage?");
839 // Notify that we have a DeclContext that is initializing.
840 ExternalASTSource::Deserializing ADeclContext(Source);
842 // Load the external declarations, if any.
843 llvm::SmallVector<Decl*, 64> Decls;
844 ExternalLexicalStorage = false;
845 switch (Source->FindExternalLexicalDecls(this, Decls)) {
850 case ELR_AlreadyLoaded:
857 // We may have already loaded just the fields of this record, in which case
858 // don't add the decls, just replace the FirstDecl/LastDecl chain.
859 if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
860 if (RD->LoadedFieldsFromExternalStorage) {
861 llvm::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls);
865 // Splice the newly-read declarations into the beginning of the list
867 Decl *ExternalFirst, *ExternalLast;
868 llvm::tie(ExternalFirst, ExternalLast) = BuildDeclChain(Decls);
869 ExternalLast->NextDeclInContext = FirstDecl;
870 FirstDecl = ExternalFirst;
872 LastDecl = ExternalLast;
875 DeclContext::lookup_result
876 ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
877 DeclarationName Name) {
878 ASTContext &Context = DC->getParentASTContext();
880 if (!(Map = DC->LookupPtr))
881 Map = DC->CreateStoredDeclsMap(Context);
883 StoredDeclsList &List = (*Map)[Name];
884 assert(List.isNull());
887 return DeclContext::lookup_result();
890 DeclContext::lookup_result
891 ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
892 DeclarationName Name,
893 llvm::SmallVectorImpl<NamedDecl*> &Decls) {
894 ASTContext &Context = DC->getParentASTContext();;
897 if (!(Map = DC->LookupPtr))
898 Map = DC->CreateStoredDeclsMap(Context);
900 StoredDeclsList &List = (*Map)[Name];
901 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
903 List.setOnlyValue(Decls[I]);
905 List.AddSubsequentDecl(Decls[I]);
908 return List.getLookupResult();
911 void ExternalASTSource::MaterializeVisibleDeclsForName(const DeclContext *DC,
912 DeclarationName Name,
913 llvm::SmallVectorImpl<NamedDecl*> &Decls) {
914 assert(DC->LookupPtr);
915 StoredDeclsMap &Map = *DC->LookupPtr;
917 // If there's an entry in the table the visible decls for this name have
918 // already been deserialized.
919 if (Map.find(Name) == Map.end()) {
920 StoredDeclsList &List = Map[Name];
921 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
923 List.setOnlyValue(Decls[I]);
925 List.AddSubsequentDecl(Decls[I]);
930 DeclContext::decl_iterator DeclContext::noload_decls_begin() const {
931 return decl_iterator(FirstDecl);
934 DeclContext::decl_iterator DeclContext::noload_decls_end() const {
935 return decl_iterator();
938 DeclContext::decl_iterator DeclContext::decls_begin() const {
939 if (hasExternalLexicalStorage())
940 LoadLexicalDeclsFromExternalStorage();
942 // FIXME: Check whether we need to load some declarations from
944 return decl_iterator(FirstDecl);
947 DeclContext::decl_iterator DeclContext::decls_end() const {
948 if (hasExternalLexicalStorage())
949 LoadLexicalDeclsFromExternalStorage();
951 return decl_iterator();
954 bool DeclContext::decls_empty() const {
955 if (hasExternalLexicalStorage())
956 LoadLexicalDeclsFromExternalStorage();
961 void DeclContext::removeDecl(Decl *D) {
962 assert(D->getLexicalDeclContext() == this &&
963 "decl being removed from non-lexical context");
964 assert((D->NextDeclInContext || D == LastDecl) &&
965 "decl is not in decls list");
967 // Remove D from the decl chain. This is O(n) but hopefully rare.
968 if (D == FirstDecl) {
970 FirstDecl = LastDecl = 0;
972 FirstDecl = D->NextDeclInContext;
974 for (Decl *I = FirstDecl; true; I = I->NextDeclInContext) {
975 assert(I && "decl not found in linked list");
976 if (I->NextDeclInContext == D) {
977 I->NextDeclInContext = D->NextDeclInContext;
978 if (D == LastDecl) LastDecl = I;
984 // Mark that D is no longer in the decl chain.
985 D->NextDeclInContext = 0;
987 // Remove D from the lookup table if necessary.
988 if (isa<NamedDecl>(D)) {
989 NamedDecl *ND = cast<NamedDecl>(D);
991 StoredDeclsMap *Map = getPrimaryContext()->LookupPtr;
994 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
995 assert(Pos != Map->end() && "no lookup entry for decl");
996 Pos->second.remove(ND);
1000 void DeclContext::addHiddenDecl(Decl *D) {
1001 assert(D->getLexicalDeclContext() == this &&
1002 "Decl inserted into wrong lexical context");
1003 assert(!D->getNextDeclInContext() && D != LastDecl &&
1004 "Decl already inserted into a DeclContext");
1007 LastDecl->NextDeclInContext = D;
1010 FirstDecl = LastDecl = D;
1013 // Notify a C++ record declaration that we've added a member, so it can
1014 // update it's class-specific state.
1015 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1016 Record->addedMember(D);
1019 void DeclContext::addDecl(Decl *D) {
1022 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1023 ND->getDeclContext()->makeDeclVisibleInContext(ND);
1026 /// buildLookup - Build the lookup data structure with all of the
1027 /// declarations in DCtx (and any other contexts linked to it or
1028 /// transparent contexts nested within it).
1029 void DeclContext::buildLookup(DeclContext *DCtx) {
1030 for (; DCtx; DCtx = DCtx->getNextContext()) {
1031 for (decl_iterator D = DCtx->decls_begin(),
1032 DEnd = DCtx->decls_end();
1034 // Insert this declaration into the lookup structure, but only
1035 // if it's semantically in its decl context. During non-lazy
1036 // lookup building, this is implicitly enforced by addDecl.
1037 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
1038 if (D->getDeclContext() == DCtx)
1039 makeDeclVisibleInContextImpl(ND);
1041 // Insert any forward-declared Objective-C interfaces into the lookup
1043 if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(*D))
1044 for (ObjCClassDecl::iterator I = Class->begin(), IEnd = Class->end();
1046 makeDeclVisibleInContextImpl(I->getInterface());
1048 // If this declaration is itself a transparent declaration context or
1049 // inline namespace, add its members (recursively).
1050 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D))
1051 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1052 buildLookup(InnerCtx->getPrimaryContext());
1057 DeclContext::lookup_result
1058 DeclContext::lookup(DeclarationName Name) {
1059 DeclContext *PrimaryContext = getPrimaryContext();
1060 if (PrimaryContext != this)
1061 return PrimaryContext->lookup(Name);
1063 if (hasExternalVisibleStorage()) {
1064 // Check to see if we've already cached the lookup results.
1066 StoredDeclsMap::iterator I = LookupPtr->find(Name);
1067 if (I != LookupPtr->end())
1068 return I->second.getLookupResult();
1071 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1072 return Source->FindExternalVisibleDeclsByName(this, Name);
1075 /// If there is no lookup data structure, build one now by walking
1076 /// all of the linked DeclContexts (in declaration order!) and
1077 /// inserting their values.
1082 return lookup_result(lookup_iterator(0), lookup_iterator(0));
1085 StoredDeclsMap::iterator Pos = LookupPtr->find(Name);
1086 if (Pos == LookupPtr->end())
1087 return lookup_result(lookup_iterator(0), lookup_iterator(0));
1088 return Pos->second.getLookupResult();
1091 DeclContext::lookup_const_result
1092 DeclContext::lookup(DeclarationName Name) const {
1093 return const_cast<DeclContext*>(this)->lookup(Name);
1096 DeclContext *DeclContext::getRedeclContext() {
1097 DeclContext *Ctx = this;
1098 // Skip through transparent contexts.
1099 while (Ctx->isTransparentContext())
1100 Ctx = Ctx->getParent();
1104 DeclContext *DeclContext::getEnclosingNamespaceContext() {
1105 DeclContext *Ctx = this;
1106 // Skip through non-namespace, non-translation-unit contexts.
1107 while (!Ctx->isFileContext())
1108 Ctx = Ctx->getParent();
1109 return Ctx->getPrimaryContext();
1112 bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1113 // For non-file contexts, this is equivalent to Equals.
1114 if (!isFileContext())
1115 return O->Equals(this);
1118 if (O->Equals(this))
1121 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1122 if (!NS || !NS->isInline())
1124 O = NS->getParent();
1130 void DeclContext::makeDeclVisibleInContext(NamedDecl *D, bool Recoverable) {
1131 // FIXME: This feels like a hack. Should DeclarationName support
1132 // template-ids, or is there a better way to keep specializations
1133 // from being visible?
1134 if (isa<ClassTemplateSpecializationDecl>(D) || D->isTemplateParameter())
1136 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1137 if (FD->isFunctionTemplateSpecialization())
1140 DeclContext *PrimaryContext = getPrimaryContext();
1141 if (PrimaryContext != this) {
1142 PrimaryContext->makeDeclVisibleInContext(D, Recoverable);
1146 // If we already have a lookup data structure, perform the insertion
1147 // into it. If we haven't deserialized externally stored decls, deserialize
1148 // them so we can add the decl. Otherwise, be lazy and don't build that
1149 // structure until someone asks for it.
1150 if (LookupPtr || !Recoverable || hasExternalVisibleStorage())
1151 makeDeclVisibleInContextImpl(D);
1153 // If we are a transparent context or inline namespace, insert into our
1154 // parent context, too. This operation is recursive.
1155 if (isTransparentContext() || isInlineNamespace())
1156 getParent()->makeDeclVisibleInContext(D, Recoverable);
1158 Decl *DCAsDecl = cast<Decl>(this);
1159 // Notify that a decl was made visible unless it's a Tag being defined.
1160 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1161 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1162 L->AddedVisibleDecl(this, D);
1165 void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D) {
1166 // Skip unnamed declarations.
1167 if (!D->getDeclName())
1170 // Skip entities that can't be found by name lookup into a particular
1172 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1173 D->isTemplateParameter())
1178 C = &getParentASTContext();
1179 CreateStoredDeclsMap(*C);
1182 // If there is an external AST source, load any declarations it knows about
1183 // with this declaration's name.
1184 // If the lookup table contains an entry about this name it means that we
1185 // have already checked the external source.
1186 if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1187 if (hasExternalVisibleStorage() &&
1188 LookupPtr->find(D->getDeclName()) == LookupPtr->end())
1189 Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1191 // Insert this declaration into the map.
1192 StoredDeclsList &DeclNameEntries = (*LookupPtr)[D->getDeclName()];
1193 if (DeclNameEntries.isNull()) {
1194 DeclNameEntries.setOnlyValue(D);
1198 // If it is possible that this is a redeclaration, check to see if there is
1199 // already a decl for which declarationReplaces returns true. If there is
1200 // one, just replace it and return.
1201 if (DeclNameEntries.HandleRedeclaration(D))
1204 // Put this declaration into the appropriate slot.
1205 DeclNameEntries.AddSubsequentDecl(D);
1208 void DeclContext::MaterializeVisibleDeclsFromExternalStorage() {
1209 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1210 assert(hasExternalVisibleStorage() && Source && "No external storage?");
1213 CreateStoredDeclsMap(getParentASTContext());
1214 Source->MaterializeVisibleDecls(this);
1217 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1219 DeclContext::udir_iterator_range
1220 DeclContext::getUsingDirectives() const {
1221 lookup_const_result Result = lookup(UsingDirectiveDecl::getName());
1222 return udir_iterator_range(reinterpret_cast<udir_iterator>(Result.first),
1223 reinterpret_cast<udir_iterator>(Result.second));
1226 //===----------------------------------------------------------------------===//
1227 // Creation and Destruction of StoredDeclsMaps. //
1228 //===----------------------------------------------------------------------===//
1230 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1231 assert(!LookupPtr && "context already has a decls map");
1232 assert(getPrimaryContext() == this &&
1233 "creating decls map on non-primary context");
1236 bool Dependent = isDependentContext();
1238 M = new DependentStoredDeclsMap();
1240 M = new StoredDeclsMap();
1241 M->Previous = C.LastSDM;
1242 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1247 void ASTContext::ReleaseDeclContextMaps() {
1248 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1249 // pointer because the subclass doesn't add anything that needs to
1251 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1254 void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1256 // Advance the iteration before we invalidate memory.
1257 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1260 delete static_cast<DependentStoredDeclsMap*>(Map);
1264 Map = Next.getPointer();
1265 Dependent = Next.getInt();
1269 DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1270 DeclContext *Parent,
1271 const PartialDiagnostic &PDiag) {
1272 assert(Parent->isDependentContext()
1273 && "cannot iterate dependent diagnostics of non-dependent context");
1274 Parent = Parent->getPrimaryContext();
1275 if (!Parent->LookupPtr)
1276 Parent->CreateStoredDeclsMap(C);
1278 DependentStoredDeclsMap *Map
1279 = static_cast<DependentStoredDeclsMap*>(Parent->LookupPtr);
1281 // Allocate the copy of the PartialDiagnostic via the ASTContext's
1282 // BumpPtrAllocator, rather than the ASTContext itself.
1283 PartialDiagnostic::Storage *DiagStorage = 0;
1284 if (PDiag.hasStorage())
1285 DiagStorage = new (C) PartialDiagnostic::Storage;
1287 DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
1289 // TODO: Maybe we shouldn't reverse the order during insertion.
1290 DD->NextDiagnostic = Map->FirstDiagnostic;
1291 Map->FirstDiagnostic = DD;