1 //===--- DeclBase.cpp - Declaration AST Node Implementation ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Decl and DeclContext classes.
12 //===----------------------------------------------------------------------===//
14 #include "clang/AST/DeclBase.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclContextInternals.h"
21 #include "clang/AST/DeclFriend.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclOpenMP.h"
24 #include "clang/AST/DeclTemplate.h"
25 #include "clang/AST/DependentDiagnostic.h"
26 #include "clang/AST/ExternalASTSource.h"
27 #include "clang/AST/Stmt.h"
28 #include "clang/AST/StmtCXX.h"
29 #include "clang/AST/Type.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include "llvm/Support/raw_ostream.h"
34 using namespace clang;
36 //===----------------------------------------------------------------------===//
38 //===----------------------------------------------------------------------===//
40 #define DECL(DERIVED, BASE) static int n##DERIVED##s = 0;
41 #define ABSTRACT_DECL(DECL)
42 #include "clang/AST/DeclNodes.inc"
44 void Decl::updateOutOfDate(IdentifierInfo &II) const {
45 getASTContext().getExternalSource()->updateOutOfDateIdentifier(II);
48 void *Decl::AllocateDeserializedDecl(const ASTContext &Context,
51 // Allocate an extra 8 bytes worth of storage, which ensures that the
52 // resulting pointer will still be 8-byte aligned.
53 void *Start = Context.Allocate(Size + 8);
54 void *Result = (char*)Start + 8;
56 unsigned *PrefixPtr = (unsigned *)Result - 2;
58 // Zero out the first 4 bytes; this is used to store the owning module ID.
61 // Store the global declaration ID in the second 4 bytes.
67 Module *Decl::getOwningModuleSlow() const {
68 assert(isFromASTFile() && "Not from AST file?");
69 return getASTContext().getExternalSource()->getModule(getOwningModuleID());
72 const char *Decl::getDeclKindName() const {
74 default: llvm_unreachable("Declaration not in DeclNodes.inc!");
75 #define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
76 #define ABSTRACT_DECL(DECL)
77 #include "clang/AST/DeclNodes.inc"
81 void Decl::setInvalidDecl(bool Invalid) {
82 InvalidDecl = Invalid;
83 if (Invalid && !isa<ParmVarDecl>(this)) {
84 // Defensive maneuver for ill-formed code: we're likely not to make it to
85 // a point where we set the access specifier, so default it to "public"
86 // to avoid triggering asserts elsewhere in the front end.
91 const char *DeclContext::getDeclKindName() const {
93 default: llvm_unreachable("Declaration context not in DeclNodes.inc!");
94 #define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
95 #define ABSTRACT_DECL(DECL)
96 #include "clang/AST/DeclNodes.inc"
100 bool Decl::StatisticsEnabled = false;
101 void Decl::EnableStatistics() {
102 StatisticsEnabled = true;
105 void Decl::PrintStats() {
106 llvm::errs() << "\n*** Decl Stats:\n";
109 #define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
110 #define ABSTRACT_DECL(DECL)
111 #include "clang/AST/DeclNodes.inc"
112 llvm::errs() << " " << totalDecls << " decls total.\n";
115 #define DECL(DERIVED, BASE) \
116 if (n##DERIVED##s > 0) { \
117 totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \
118 llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \
119 << sizeof(DERIVED##Decl) << " each (" \
120 << n##DERIVED##s * sizeof(DERIVED##Decl) \
123 #define ABSTRACT_DECL(DECL)
124 #include "clang/AST/DeclNodes.inc"
126 llvm::errs() << "Total bytes = " << totalBytes << "\n";
129 void Decl::add(Kind k) {
131 #define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
132 #define ABSTRACT_DECL(DECL)
133 #include "clang/AST/DeclNodes.inc"
137 bool Decl::isTemplateParameterPack() const {
138 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
139 return TTP->isParameterPack();
140 if (const NonTypeTemplateParmDecl *NTTP
141 = dyn_cast<NonTypeTemplateParmDecl>(this))
142 return NTTP->isParameterPack();
143 if (const TemplateTemplateParmDecl *TTP
144 = dyn_cast<TemplateTemplateParmDecl>(this))
145 return TTP->isParameterPack();
149 bool Decl::isParameterPack() const {
150 if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this))
151 return Parm->isParameterPack();
153 return isTemplateParameterPack();
156 bool Decl::isFunctionOrFunctionTemplate() const {
157 if (const UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(this))
158 return UD->getTargetDecl()->isFunctionOrFunctionTemplate();
160 return isa<FunctionDecl>(this) || isa<FunctionTemplateDecl>(this);
163 bool Decl::isTemplateDecl() const {
164 return isa<TemplateDecl>(this);
167 const DeclContext *Decl::getParentFunctionOrMethod() const {
168 for (const DeclContext *DC = getDeclContext();
169 DC && !DC->isTranslationUnit() && !DC->isNamespace();
170 DC = DC->getParent())
171 if (DC->isFunctionOrMethod())
178 //===----------------------------------------------------------------------===//
179 // PrettyStackTraceDecl Implementation
180 //===----------------------------------------------------------------------===//
182 void PrettyStackTraceDecl::print(raw_ostream &OS) const {
183 SourceLocation TheLoc = Loc;
184 if (TheLoc.isInvalid() && TheDecl)
185 TheLoc = TheDecl->getLocation();
187 if (TheLoc.isValid()) {
188 TheLoc.print(OS, SM);
194 if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
196 DN->printQualifiedName(OS);
202 //===----------------------------------------------------------------------===//
203 // Decl Implementation
204 //===----------------------------------------------------------------------===//
206 // Out-of-line virtual method providing a home for Decl.
209 void Decl::setDeclContext(DeclContext *DC) {
213 void Decl::setLexicalDeclContext(DeclContext *DC) {
214 if (DC == getLexicalDeclContext())
218 setDeclContextsImpl(getDeclContext(), DC, getASTContext());
220 getMultipleDC()->LexicalDC = DC;
224 void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
226 if (SemaDC == LexicalDC) {
229 Decl::MultipleDC *MDC = new (Ctx) Decl::MultipleDC();
230 MDC->SemanticDC = SemaDC;
231 MDC->LexicalDC = LexicalDC;
236 bool Decl::isInAnonymousNamespace() const {
237 const DeclContext *DC = getDeclContext();
239 if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
240 if (ND->isAnonymousNamespace())
242 } while ((DC = DC->getParent()));
247 TranslationUnitDecl *Decl::getTranslationUnitDecl() {
248 if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
251 DeclContext *DC = getDeclContext();
252 assert(DC && "This decl is not contained in a translation unit!");
254 while (!DC->isTranslationUnit()) {
255 DC = DC->getParent();
256 assert(DC && "This decl is not contained in a translation unit!");
259 return cast<TranslationUnitDecl>(DC);
262 ASTContext &Decl::getASTContext() const {
263 return getTranslationUnitDecl()->getASTContext();
266 ASTMutationListener *Decl::getASTMutationListener() const {
267 return getASTContext().getASTMutationListener();
270 unsigned Decl::getMaxAlignment() const {
275 const AttrVec &V = getAttrs();
276 ASTContext &Ctx = getASTContext();
277 specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
279 Align = std::max(Align, I->getAlignment(Ctx));
283 bool Decl::isUsed(bool CheckUsedAttr) const {
287 // Check for used attribute.
288 if (CheckUsedAttr && hasAttr<UsedAttr>())
294 bool Decl::isReferenced() const {
298 // Check redeclarations.
299 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
306 /// \brief Determine the availability of the given declaration based on
307 /// the target platform.
309 /// When it returns an availability result other than \c AR_Available,
310 /// if the \p Message parameter is non-NULL, it will be set to a
311 /// string describing why the entity is unavailable.
313 /// FIXME: Make these strings localizable, since they end up in
315 static AvailabilityResult CheckAvailability(ASTContext &Context,
316 const AvailabilityAttr *A,
317 std::string *Message) {
318 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
319 StringRef PrettyPlatformName
320 = AvailabilityAttr::getPrettyPlatformName(TargetPlatform);
321 if (PrettyPlatformName.empty())
322 PrettyPlatformName = TargetPlatform;
324 VersionTuple TargetMinVersion = Context.getTargetInfo().getPlatformMinVersion();
325 if (TargetMinVersion.empty())
328 // Match the platform name.
329 if (A->getPlatform()->getName() != TargetPlatform)
332 std::string HintMessage;
333 if (!A->getMessage().empty()) {
335 HintMessage += A->getMessage();
338 // Make sure that this declaration has not been marked 'unavailable'.
339 if (A->getUnavailable()) {
342 llvm::raw_string_ostream Out(*Message);
343 Out << "not available on " << PrettyPlatformName
347 return AR_Unavailable;
350 // Make sure that this declaration has already been introduced.
351 if (!A->getIntroduced().empty() &&
352 TargetMinVersion < A->getIntroduced()) {
355 llvm::raw_string_ostream Out(*Message);
356 Out << "introduced in " << PrettyPlatformName << ' '
357 << A->getIntroduced() << HintMessage;
360 return AR_NotYetIntroduced;
363 // Make sure that this declaration hasn't been obsoleted.
364 if (!A->getObsoleted().empty() && TargetMinVersion >= A->getObsoleted()) {
367 llvm::raw_string_ostream Out(*Message);
368 Out << "obsoleted in " << PrettyPlatformName << ' '
369 << A->getObsoleted() << HintMessage;
372 return AR_Unavailable;
375 // Make sure that this declaration hasn't been deprecated.
376 if (!A->getDeprecated().empty() && TargetMinVersion >= A->getDeprecated()) {
379 llvm::raw_string_ostream Out(*Message);
380 Out << "first deprecated in " << PrettyPlatformName << ' '
381 << A->getDeprecated() << HintMessage;
384 return AR_Deprecated;
390 AvailabilityResult Decl::getAvailability(std::string *Message) const {
391 AvailabilityResult Result = AR_Available;
392 std::string ResultMessage;
394 for (attr_iterator A = attr_begin(), AEnd = attr_end(); A != AEnd; ++A) {
395 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(*A)) {
396 if (Result >= AR_Deprecated)
400 ResultMessage = Deprecated->getMessage();
402 Result = AR_Deprecated;
406 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(*A)) {
408 *Message = Unavailable->getMessage();
409 return AR_Unavailable;
412 if (AvailabilityAttr *Availability = dyn_cast<AvailabilityAttr>(*A)) {
413 AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
416 if (AR == AR_Unavailable)
417 return AR_Unavailable;
422 ResultMessage.swap(*Message);
429 Message->swap(ResultMessage);
433 bool Decl::canBeWeakImported(bool &IsDefinition) const {
434 IsDefinition = false;
436 // Variables, if they aren't definitions.
437 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
438 if (Var->isThisDeclarationADefinition()) {
444 // Functions, if they aren't definitions.
445 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
452 // Objective-C classes, if this is the non-fragile runtime.
453 } else if (isa<ObjCInterfaceDecl>(this) &&
454 getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
463 bool Decl::isWeakImported() const {
465 if (!canBeWeakImported(IsDefinition))
468 for (attr_iterator A = attr_begin(), AEnd = attr_end(); A != AEnd; ++A) {
469 if (isa<WeakImportAttr>(*A))
472 if (AvailabilityAttr *Availability = dyn_cast<AvailabilityAttr>(*A)) {
473 if (CheckAvailability(getASTContext(), Availability, 0)
474 == AR_NotYetIntroduced)
482 unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
493 case NonTypeTemplateParm:
496 return IDNS_Ordinary;
500 return IDNS_Ordinary | IDNS_Member;
502 case ObjCCompatibleAlias:
504 return IDNS_Ordinary | IDNS_Type;
508 case TypeAliasTemplate:
509 case UnresolvedUsingTypename:
510 case TemplateTypeParm:
511 return IDNS_Ordinary | IDNS_Type;
514 return 0; // we'll actually overwrite this later
516 case UnresolvedUsingValue:
517 return IDNS_Ordinary | IDNS_Using;
523 return IDNS_ObjCProtocol;
526 case ObjCAtDefsField:
533 return IDNS_Tag | IDNS_Type;
537 return IDNS_Namespace;
539 case FunctionTemplate:
540 return IDNS_Ordinary;
543 case TemplateTemplateParm:
544 return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
553 case ObjCPropertyImpl:
555 case TranslationUnit:
558 case ClassTemplateSpecialization:
559 case ClassTemplatePartialSpecialization:
560 case ClassScopeFunctionSpecialization:
561 case ObjCImplementation:
563 case ObjCCategoryImpl:
565 case OMPThreadPrivate:
567 // Never looked up by name.
571 llvm_unreachable("Invalid DeclKind!");
574 void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
575 assert(!HasAttrs && "Decl already contains attrs.");
577 AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
578 assert(AttrBlank.empty() && "HasAttrs was wrong?");
584 void Decl::dropAttrs() {
585 if (!HasAttrs) return;
588 getASTContext().eraseDeclAttrs(this);
591 const AttrVec &Decl::getAttrs() const {
592 assert(HasAttrs && "No attrs to get!");
593 return getASTContext().getDeclAttrs(this);
596 void Decl::swapAttrs(Decl *RHS) {
597 bool HasLHSAttr = this->HasAttrs;
598 bool HasRHSAttr = RHS->HasAttrs;
600 // Usually, neither decl has attrs, nothing to do.
601 if (!HasLHSAttr && !HasRHSAttr) return;
603 // If 'this' has no attrs, swap the other way.
605 return RHS->swapAttrs(this);
607 ASTContext &Context = getASTContext();
609 // Handle the case when both decls have attrs.
611 std::swap(Context.getDeclAttrs(this), Context.getDeclAttrs(RHS));
615 // Otherwise, LHS has an attr and RHS doesn't.
616 Context.getDeclAttrs(RHS) = Context.getDeclAttrs(this);
617 Context.eraseDeclAttrs(this);
618 this->HasAttrs = false;
619 RHS->HasAttrs = true;
622 Decl *Decl::castFromDeclContext (const DeclContext *D) {
623 Decl::Kind DK = D->getDeclKind();
625 #define DECL(NAME, BASE)
626 #define DECL_CONTEXT(NAME) \
628 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
629 #define DECL_CONTEXT_BASE(NAME)
630 #include "clang/AST/DeclNodes.inc"
632 #define DECL(NAME, BASE)
633 #define DECL_CONTEXT_BASE(NAME) \
634 if (DK >= first##NAME && DK <= last##NAME) \
635 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
636 #include "clang/AST/DeclNodes.inc"
637 llvm_unreachable("a decl that inherits DeclContext isn't handled");
641 DeclContext *Decl::castToDeclContext(const Decl *D) {
642 Decl::Kind DK = D->getKind();
644 #define DECL(NAME, BASE)
645 #define DECL_CONTEXT(NAME) \
647 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
648 #define DECL_CONTEXT_BASE(NAME)
649 #include "clang/AST/DeclNodes.inc"
651 #define DECL(NAME, BASE)
652 #define DECL_CONTEXT_BASE(NAME) \
653 if (DK >= first##NAME && DK <= last##NAME) \
654 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
655 #include "clang/AST/DeclNodes.inc"
656 llvm_unreachable("a decl that inherits DeclContext isn't handled");
660 SourceLocation Decl::getBodyRBrace() const {
661 // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
662 // FunctionDecl stores EndRangeLoc for this purpose.
663 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
664 const FunctionDecl *Definition;
665 if (FD->hasBody(Definition))
666 return Definition->getSourceRange().getEnd();
667 return SourceLocation();
670 if (Stmt *Body = getBody())
671 return Body->getSourceRange().getEnd();
673 return SourceLocation();
676 void Decl::CheckAccessDeclContext() const {
678 // Suppress this check if any of the following hold:
679 // 1. this is the translation unit (and thus has no parent)
680 // 2. this is a template parameter (and thus doesn't belong to its context)
681 // 3. this is a non-type template parameter
682 // 4. the context is not a record
684 // 6. it's a C++0x static_assert.
685 if (isa<TranslationUnitDecl>(this) ||
686 isa<TemplateTypeParmDecl>(this) ||
687 isa<NonTypeTemplateParmDecl>(this) ||
688 !isa<CXXRecordDecl>(getDeclContext()) ||
690 isa<StaticAssertDecl>(this) ||
691 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
692 // as DeclContext (?).
693 isa<ParmVarDecl>(this) ||
694 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
695 // AS_none as access specifier.
696 isa<CXXRecordDecl>(this) ||
697 isa<ClassScopeFunctionSpecializationDecl>(this))
700 assert(Access != AS_none &&
701 "Access specifier is AS_none inside a record decl");
705 DeclContext *Decl::getNonClosureContext() {
706 return getDeclContext()->getNonClosureAncestor();
709 DeclContext *DeclContext::getNonClosureAncestor() {
710 DeclContext *DC = this;
712 // This is basically "while (DC->isClosure()) DC = DC->getParent();"
713 // except that it's significantly more efficient to cast to a known
714 // decl type and call getDeclContext() than to call getParent().
715 while (isa<BlockDecl>(DC))
716 DC = cast<BlockDecl>(DC)->getDeclContext();
718 assert(!DC->isClosure());
722 //===----------------------------------------------------------------------===//
723 // DeclContext Implementation
724 //===----------------------------------------------------------------------===//
726 bool DeclContext::classof(const Decl *D) {
727 switch (D->getKind()) {
728 #define DECL(NAME, BASE)
729 #define DECL_CONTEXT(NAME) case Decl::NAME:
730 #define DECL_CONTEXT_BASE(NAME)
731 #include "clang/AST/DeclNodes.inc"
734 #define DECL(NAME, BASE)
735 #define DECL_CONTEXT_BASE(NAME) \
736 if (D->getKind() >= Decl::first##NAME && \
737 D->getKind() <= Decl::last##NAME) \
739 #include "clang/AST/DeclNodes.inc"
744 DeclContext::~DeclContext() { }
746 /// \brief Find the parent context of this context that will be
747 /// used for unqualified name lookup.
749 /// Generally, the parent lookup context is the semantic context. However, for
750 /// a friend function the parent lookup context is the lexical context, which
751 /// is the class in which the friend is declared.
752 DeclContext *DeclContext::getLookupParent() {
753 // FIXME: Find a better way to identify friends
754 if (isa<FunctionDecl>(this))
755 if (getParent()->getRedeclContext()->isFileContext() &&
756 getLexicalParent()->getRedeclContext()->isRecord())
757 return getLexicalParent();
762 bool DeclContext::isInlineNamespace() const {
763 return isNamespace() &&
764 cast<NamespaceDecl>(this)->isInline();
767 bool DeclContext::isDependentContext() const {
771 if (isa<ClassTemplatePartialSpecializationDecl>(this))
774 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
775 if (Record->getDescribedClassTemplate())
778 if (Record->isDependentLambda())
782 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
783 if (Function->getDescribedFunctionTemplate())
786 // Friend function declarations are dependent if their *lexical*
787 // context is dependent.
788 if (cast<Decl>(this)->getFriendObjectKind())
789 return getLexicalParent()->isDependentContext();
792 return getParent() && getParent()->isDependentContext();
795 bool DeclContext::isTransparentContext() const {
796 if (DeclKind == Decl::Enum)
797 return !cast<EnumDecl>(this)->isScoped();
798 else if (DeclKind == Decl::LinkageSpec)
804 bool DeclContext::isExternCContext() const {
805 const DeclContext *DC = this;
806 while (DC->DeclKind != Decl::TranslationUnit) {
807 if (DC->DeclKind == Decl::LinkageSpec)
808 return cast<LinkageSpecDecl>(DC)->getLanguage()
809 == LinkageSpecDecl::lang_c;
810 DC = DC->getParent();
815 bool DeclContext::isExternCXXContext() const {
816 const DeclContext *DC = this;
817 while (DC->DeclKind != Decl::TranslationUnit) {
818 if (DC->DeclKind == Decl::LinkageSpec)
819 return cast<LinkageSpecDecl>(DC)->getLanguage()
820 == LinkageSpecDecl::lang_cxx;
821 DC = DC->getParent();
826 bool DeclContext::Encloses(const DeclContext *DC) const {
827 if (getPrimaryContext() != this)
828 return getPrimaryContext()->Encloses(DC);
830 for (; DC; DC = DC->getParent())
831 if (DC->getPrimaryContext() == this)
836 DeclContext *DeclContext::getPrimaryContext() {
838 case Decl::TranslationUnit:
839 case Decl::LinkageSpec:
841 // There is only one DeclContext for these entities.
844 case Decl::Namespace:
845 // The original namespace is our primary context.
846 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
848 case Decl::ObjCMethod:
851 case Decl::ObjCInterface:
852 if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
857 case Decl::ObjCProtocol:
858 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
863 case Decl::ObjCCategory:
866 case Decl::ObjCImplementation:
867 case Decl::ObjCCategoryImpl:
871 if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
872 // If this is a tag type that has a definition or is currently
873 // being defined, that definition is our primary context.
874 TagDecl *Tag = cast<TagDecl>(this);
875 assert(isa<TagType>(Tag->TypeForDecl) ||
876 isa<InjectedClassNameType>(Tag->TypeForDecl));
878 if (TagDecl *Def = Tag->getDefinition())
881 if (!isa<InjectedClassNameType>(Tag->TypeForDecl)) {
882 const TagType *TagTy = cast<TagType>(Tag->TypeForDecl);
883 if (TagTy->isBeingDefined())
884 // FIXME: is it necessarily being defined in the decl
885 // that owns the type?
886 return TagTy->getDecl();
892 assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
893 "Unknown DeclContext kind");
899 DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
902 if (DeclKind != Decl::Namespace) {
903 Contexts.push_back(this);
907 NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
908 for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
909 N = N->getPreviousDecl())
910 Contexts.push_back(N);
912 std::reverse(Contexts.begin(), Contexts.end());
915 std::pair<Decl *, Decl *>
916 DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
917 bool FieldsAlreadyLoaded) {
918 // Build up a chain of declarations via the Decl::NextInContextAndBits field.
919 Decl *FirstNewDecl = 0;
921 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
922 if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
927 PrevDecl->NextInContextAndBits.setPointer(D);
934 return std::make_pair(FirstNewDecl, PrevDecl);
937 /// \brief We have just acquired external visible storage, and we already have
938 /// built a lookup map. For every name in the map, pull in the new names from
939 /// the external storage.
940 void DeclContext::reconcileExternalVisibleStorage() {
941 assert(NeedToReconcileExternalVisibleStorage && LookupPtr.getPointer());
942 NeedToReconcileExternalVisibleStorage = false;
944 StoredDeclsMap &Map = *LookupPtr.getPointer();
945 ExternalASTSource *Source = getParentASTContext().getExternalSource();
946 for (StoredDeclsMap::iterator I = Map.begin(); I != Map.end(); ++I) {
947 I->second.removeExternalDecls();
948 Source->FindExternalVisibleDeclsByName(this, I->first);
952 /// \brief Load the declarations within this lexical storage from an
955 DeclContext::LoadLexicalDeclsFromExternalStorage() const {
956 ExternalASTSource *Source = getParentASTContext().getExternalSource();
957 assert(hasExternalLexicalStorage() && Source && "No external storage?");
959 // Notify that we have a DeclContext that is initializing.
960 ExternalASTSource::Deserializing ADeclContext(Source);
962 // Load the external declarations, if any.
963 SmallVector<Decl*, 64> Decls;
964 ExternalLexicalStorage = false;
965 switch (Source->FindExternalLexicalDecls(this, Decls)) {
970 case ELR_AlreadyLoaded:
977 // We may have already loaded just the fields of this record, in which case
978 // we need to ignore them.
979 bool FieldsAlreadyLoaded = false;
980 if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
981 FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
983 // Splice the newly-read declarations into the beginning of the list
985 Decl *ExternalFirst, *ExternalLast;
986 llvm::tie(ExternalFirst, ExternalLast) = BuildDeclChain(Decls,
987 FieldsAlreadyLoaded);
988 ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
989 FirstDecl = ExternalFirst;
991 LastDecl = ExternalLast;
994 DeclContext::lookup_result
995 ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
996 DeclarationName Name) {
997 ASTContext &Context = DC->getParentASTContext();
999 if (!(Map = DC->LookupPtr.getPointer()))
1000 Map = DC->CreateStoredDeclsMap(Context);
1002 // Add an entry to the map for this name, if it's not already present.
1005 return DeclContext::lookup_result();
1008 DeclContext::lookup_result
1009 ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
1010 DeclarationName Name,
1011 ArrayRef<NamedDecl*> Decls) {
1012 ASTContext &Context = DC->getParentASTContext();
1013 StoredDeclsMap *Map;
1014 if (!(Map = DC->LookupPtr.getPointer()))
1015 Map = DC->CreateStoredDeclsMap(Context);
1017 StoredDeclsList &List = (*Map)[Name];
1018 for (ArrayRef<NamedDecl*>::iterator
1019 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1021 List.setOnlyValue(*I);
1023 // FIXME: Need declarationReplaces handling for redeclarations in modules.
1024 List.AddSubsequentDecl(*I);
1027 return List.getLookupResult();
1030 DeclContext::decl_iterator DeclContext::noload_decls_begin() const {
1031 return decl_iterator(FirstDecl);
1034 DeclContext::decl_iterator DeclContext::decls_begin() const {
1035 if (hasExternalLexicalStorage())
1036 LoadLexicalDeclsFromExternalStorage();
1038 return decl_iterator(FirstDecl);
1041 bool DeclContext::decls_empty() const {
1042 if (hasExternalLexicalStorage())
1043 LoadLexicalDeclsFromExternalStorage();
1048 void DeclContext::removeDecl(Decl *D) {
1049 assert(D->getLexicalDeclContext() == this &&
1050 "decl being removed from non-lexical context");
1051 assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
1052 "decl is not in decls list");
1054 // Remove D from the decl chain. This is O(n) but hopefully rare.
1055 if (D == FirstDecl) {
1057 FirstDecl = LastDecl = 0;
1059 FirstDecl = D->NextInContextAndBits.getPointer();
1061 for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
1062 assert(I && "decl not found in linked list");
1063 if (I->NextInContextAndBits.getPointer() == D) {
1064 I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
1065 if (D == LastDecl) LastDecl = I;
1071 // Mark that D is no longer in the decl chain.
1072 D->NextInContextAndBits.setPointer(0);
1074 // Remove D from the lookup table if necessary.
1075 if (isa<NamedDecl>(D)) {
1076 NamedDecl *ND = cast<NamedDecl>(D);
1078 // Remove only decls that have a name
1079 if (!ND->getDeclName()) return;
1081 StoredDeclsMap *Map = getPrimaryContext()->LookupPtr.getPointer();
1084 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1085 assert(Pos != Map->end() && "no lookup entry for decl");
1086 if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
1087 Pos->second.remove(ND);
1091 void DeclContext::addHiddenDecl(Decl *D) {
1092 assert(D->getLexicalDeclContext() == this &&
1093 "Decl inserted into wrong lexical context");
1094 assert(!D->getNextDeclInContext() && D != LastDecl &&
1095 "Decl already inserted into a DeclContext");
1098 LastDecl->NextInContextAndBits.setPointer(D);
1101 FirstDecl = LastDecl = D;
1104 // Notify a C++ record declaration that we've added a member, so it can
1105 // update it's class-specific state.
1106 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1107 Record->addedMember(D);
1109 // If this is a newly-created (not de-serialized) import declaration, wire
1110 // it in to the list of local import declarations.
1111 if (!D->isFromASTFile()) {
1112 if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
1113 D->getASTContext().addedLocalImportDecl(Import);
1117 void DeclContext::addDecl(Decl *D) {
1120 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1121 ND->getDeclContext()->getPrimaryContext()->
1122 makeDeclVisibleInContextWithFlags(ND, false, true);
1125 void DeclContext::addDeclInternal(Decl *D) {
1128 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1129 ND->getDeclContext()->getPrimaryContext()->
1130 makeDeclVisibleInContextWithFlags(ND, true, true);
1133 /// shouldBeHidden - Determine whether a declaration which was declared
1134 /// within its semantic context should be invisible to qualified name lookup.
1135 static bool shouldBeHidden(NamedDecl *D) {
1136 // Skip unnamed declarations.
1137 if (!D->getDeclName())
1140 // Skip entities that can't be found by name lookup into a particular
1142 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1143 D->isTemplateParameter())
1146 // Skip template specializations.
1147 // FIXME: This feels like a hack. Should DeclarationName support
1148 // template-ids, or is there a better way to keep specializations
1149 // from being visible?
1150 if (isa<ClassTemplateSpecializationDecl>(D))
1152 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1153 if (FD->isFunctionTemplateSpecialization())
1159 /// buildLookup - Build the lookup data structure with all of the
1160 /// declarations in this DeclContext (and any other contexts linked
1161 /// to it or transparent contexts nested within it) and return it.
1162 StoredDeclsMap *DeclContext::buildLookup() {
1163 assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1165 // FIXME: Should we keep going if hasExternalVisibleStorage?
1166 if (!LookupPtr.getInt())
1167 return LookupPtr.getPointer();
1169 SmallVector<DeclContext *, 2> Contexts;
1170 collectAllContexts(Contexts);
1171 for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
1172 buildLookupImpl(Contexts[I]);
1174 // We no longer have any lazy decls.
1175 LookupPtr.setInt(false);
1176 NeedToReconcileExternalVisibleStorage = false;
1177 return LookupPtr.getPointer();
1180 /// buildLookupImpl - Build part of the lookup data structure for the
1181 /// declarations contained within DCtx, which will either be this
1182 /// DeclContext, a DeclContext linked to it, or a transparent context
1183 /// nested within it.
1184 void DeclContext::buildLookupImpl(DeclContext *DCtx) {
1185 for (decl_iterator I = DCtx->decls_begin(), E = DCtx->decls_end();
1189 // Insert this declaration into the lookup structure, but only if
1190 // it's semantically within its decl context. Any other decls which
1191 // should be found in this context are added eagerly.
1192 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1193 if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND))
1194 makeDeclVisibleInContextImpl(ND, false);
1196 // If this declaration is itself a transparent declaration context
1197 // or inline namespace, add the members of this declaration of that
1198 // context (recursively).
1199 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
1200 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1201 buildLookupImpl(InnerCtx);
1205 DeclContext::lookup_result
1206 DeclContext::lookup(DeclarationName Name) {
1207 assert(DeclKind != Decl::LinkageSpec &&
1208 "Should not perform lookups into linkage specs!");
1210 DeclContext *PrimaryContext = getPrimaryContext();
1211 if (PrimaryContext != this)
1212 return PrimaryContext->lookup(Name);
1214 if (hasExternalVisibleStorage()) {
1215 StoredDeclsMap *Map = LookupPtr.getPointer();
1216 if (LookupPtr.getInt())
1217 Map = buildLookup();
1218 else if (NeedToReconcileExternalVisibleStorage)
1219 reconcileExternalVisibleStorage();
1222 Map = CreateStoredDeclsMap(getParentASTContext());
1224 // If a PCH/module has a result for this name, and we have a local
1225 // declaration, we will have imported the PCH/module result when adding the
1226 // local declaration or when reconciling the module.
1227 std::pair<StoredDeclsMap::iterator, bool> R =
1228 Map->insert(std::make_pair(Name, StoredDeclsList()));
1230 return R.first->second.getLookupResult();
1232 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1233 if (Source->FindExternalVisibleDeclsByName(this, Name)) {
1234 if (StoredDeclsMap *Map = LookupPtr.getPointer()) {
1235 StoredDeclsMap::iterator I = Map->find(Name);
1236 if (I != Map->end())
1237 return I->second.getLookupResult();
1241 return lookup_result(lookup_iterator(0), lookup_iterator(0));
1244 StoredDeclsMap *Map = LookupPtr.getPointer();
1245 if (LookupPtr.getInt())
1246 Map = buildLookup();
1249 return lookup_result(lookup_iterator(0), lookup_iterator(0));
1251 StoredDeclsMap::iterator I = Map->find(Name);
1252 if (I == Map->end())
1253 return lookup_result(lookup_iterator(0), lookup_iterator(0));
1255 return I->second.getLookupResult();
1258 void DeclContext::localUncachedLookup(DeclarationName Name,
1259 SmallVectorImpl<NamedDecl *> &Results) {
1262 // If there's no external storage, just perform a normal lookup and copy
1264 if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
1265 lookup_result LookupResults = lookup(Name);
1266 Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
1270 // If we have a lookup table, check there first. Maybe we'll get lucky.
1271 if (Name && !LookupPtr.getInt()) {
1272 if (StoredDeclsMap *Map = LookupPtr.getPointer()) {
1273 StoredDeclsMap::iterator Pos = Map->find(Name);
1274 if (Pos != Map->end()) {
1275 Results.insert(Results.end(),
1276 Pos->second.getLookupResult().begin(),
1277 Pos->second.getLookupResult().end());
1283 // Slow case: grovel through the declarations in our chain looking for
1285 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1286 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1287 if (ND->getDeclName() == Name)
1288 Results.push_back(ND);
1292 DeclContext *DeclContext::getRedeclContext() {
1293 DeclContext *Ctx = this;
1294 // Skip through transparent contexts.
1295 while (Ctx->isTransparentContext())
1296 Ctx = Ctx->getParent();
1300 DeclContext *DeclContext::getEnclosingNamespaceContext() {
1301 DeclContext *Ctx = this;
1302 // Skip through non-namespace, non-translation-unit contexts.
1303 while (!Ctx->isFileContext())
1304 Ctx = Ctx->getParent();
1305 return Ctx->getPrimaryContext();
1308 bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1309 // For non-file contexts, this is equivalent to Equals.
1310 if (!isFileContext())
1311 return O->Equals(this);
1314 if (O->Equals(this))
1317 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1318 if (!NS || !NS->isInline())
1320 O = NS->getParent();
1326 void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1327 DeclContext *PrimaryDC = this->getPrimaryContext();
1328 DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1329 // If the decl is being added outside of its semantic decl context, we
1330 // need to ensure that we eagerly build the lookup information for it.
1331 PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
1334 void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1336 assert(this == getPrimaryContext() && "expected a primary DC");
1338 // Skip declarations within functions.
1339 // FIXME: We shouldn't need to build lookup tables for function declarations
1340 // ever, and we can't do so correctly because we can't model the nesting of
1341 // scopes which occurs within functions. We use "qualified" lookup into
1342 // function declarations when handling friend declarations inside nested
1343 // classes, and consequently accept the following invalid code:
1345 // void f() { void g(); { int g; struct S { friend void g(); }; } }
1346 if (isFunctionOrMethod() && !isa<FunctionDecl>(D))
1349 // Skip declarations which should be invisible to name lookup.
1350 if (shouldBeHidden(D))
1353 // If we already have a lookup data structure, perform the insertion into
1354 // it. If we might have externally-stored decls with this name, look them
1355 // up and perform the insertion. If this decl was declared outside its
1356 // semantic context, buildLookup won't add it, so add it now.
1358 // FIXME: As a performance hack, don't add such decls into the translation
1359 // unit unless we're in C++, since qualified lookup into the TU is never
1361 if (LookupPtr.getPointer() || hasExternalVisibleStorage() ||
1362 ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1363 (getParentASTContext().getLangOpts().CPlusPlus ||
1364 !isTranslationUnit()))) {
1365 // If we have lazily omitted any decls, they might have the same name as
1366 // the decl which we are adding, so build a full lookup table before adding
1369 makeDeclVisibleInContextImpl(D, Internal);
1371 LookupPtr.setInt(true);
1374 // If we are a transparent context or inline namespace, insert into our
1375 // parent context, too. This operation is recursive.
1376 if (isTransparentContext() || isInlineNamespace())
1377 getParent()->getPrimaryContext()->
1378 makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1380 Decl *DCAsDecl = cast<Decl>(this);
1381 // Notify that a decl was made visible unless we are a Tag being defined.
1382 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1383 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1384 L->AddedVisibleDecl(this, D);
1387 void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1388 // Find or create the stored declaration map.
1389 StoredDeclsMap *Map = LookupPtr.getPointer();
1391 ASTContext *C = &getParentASTContext();
1392 Map = CreateStoredDeclsMap(*C);
1395 // If there is an external AST source, load any declarations it knows about
1396 // with this declaration's name.
1397 // If the lookup table contains an entry about this name it means that we
1398 // have already checked the external source.
1400 if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1401 if (hasExternalVisibleStorage() &&
1402 Map->find(D->getDeclName()) == Map->end())
1403 Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1405 // Insert this declaration into the map.
1406 StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
1407 if (DeclNameEntries.isNull()) {
1408 DeclNameEntries.setOnlyValue(D);
1412 if (DeclNameEntries.HandleRedeclaration(D)) {
1413 // This declaration has replaced an existing one for which
1414 // declarationReplaces returns true.
1418 // Put this declaration into the appropriate slot.
1419 DeclNameEntries.AddSubsequentDecl(D);
1422 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1424 DeclContext::udir_iterator_range
1425 DeclContext::getUsingDirectives() const {
1426 // FIXME: Use something more efficient than normal lookup for using
1427 // directives. In C++, using directives are looked up more than anything else.
1428 lookup_const_result Result = lookup(UsingDirectiveDecl::getName());
1429 return udir_iterator_range(reinterpret_cast<udir_iterator>(Result.begin()),
1430 reinterpret_cast<udir_iterator>(Result.end()));
1433 //===----------------------------------------------------------------------===//
1434 // Creation and Destruction of StoredDeclsMaps. //
1435 //===----------------------------------------------------------------------===//
1437 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1438 assert(!LookupPtr.getPointer() && "context already has a decls map");
1439 assert(getPrimaryContext() == this &&
1440 "creating decls map on non-primary context");
1443 bool Dependent = isDependentContext();
1445 M = new DependentStoredDeclsMap();
1447 M = new StoredDeclsMap();
1448 M->Previous = C.LastSDM;
1449 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1450 LookupPtr.setPointer(M);
1454 void ASTContext::ReleaseDeclContextMaps() {
1455 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1456 // pointer because the subclass doesn't add anything that needs to
1458 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1461 void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1463 // Advance the iteration before we invalidate memory.
1464 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1467 delete static_cast<DependentStoredDeclsMap*>(Map);
1471 Map = Next.getPointer();
1472 Dependent = Next.getInt();
1476 DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1477 DeclContext *Parent,
1478 const PartialDiagnostic &PDiag) {
1479 assert(Parent->isDependentContext()
1480 && "cannot iterate dependent diagnostics of non-dependent context");
1481 Parent = Parent->getPrimaryContext();
1482 if (!Parent->LookupPtr.getPointer())
1483 Parent->CreateStoredDeclsMap(C);
1485 DependentStoredDeclsMap *Map
1486 = static_cast<DependentStoredDeclsMap*>(Parent->LookupPtr.getPointer());
1488 // Allocate the copy of the PartialDiagnostic via the ASTContext's
1489 // BumpPtrAllocator, rather than the ASTContext itself.
1490 PartialDiagnostic::Storage *DiagStorage = 0;
1491 if (PDiag.hasStorage())
1492 DiagStorage = new (C) PartialDiagnostic::Storage;
1494 DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
1496 // TODO: Maybe we shouldn't reverse the order during insertion.
1497 DD->NextDiagnostic = Map->FirstDiagnostic;
1498 Map->FirstDiagnostic = DD;