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:
497 return IDNS_Ordinary;
501 return IDNS_Ordinary | IDNS_Member;
503 case ObjCCompatibleAlias:
505 return IDNS_Ordinary | IDNS_Type;
509 case TypeAliasTemplate:
510 case UnresolvedUsingTypename:
511 case TemplateTypeParm:
512 return IDNS_Ordinary | IDNS_Type;
515 return 0; // we'll actually overwrite this later
517 case UnresolvedUsingValue:
518 return IDNS_Ordinary | IDNS_Using;
524 return IDNS_ObjCProtocol;
527 case ObjCAtDefsField:
534 return IDNS_Tag | IDNS_Type;
538 return IDNS_Namespace;
540 case FunctionTemplate:
541 return IDNS_Ordinary;
544 case TemplateTemplateParm:
545 return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
554 case ObjCPropertyImpl:
557 case TranslationUnit:
560 case ClassTemplateSpecialization:
561 case ClassTemplatePartialSpecialization:
562 case ClassScopeFunctionSpecialization:
563 case ObjCImplementation:
565 case ObjCCategoryImpl:
567 case OMPThreadPrivate:
569 // Never looked up by name.
573 llvm_unreachable("Invalid DeclKind!");
576 void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
577 assert(!HasAttrs && "Decl already contains attrs.");
579 AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
580 assert(AttrBlank.empty() && "HasAttrs was wrong?");
586 void Decl::dropAttrs() {
587 if (!HasAttrs) return;
590 getASTContext().eraseDeclAttrs(this);
593 const AttrVec &Decl::getAttrs() const {
594 assert(HasAttrs && "No attrs to get!");
595 return getASTContext().getDeclAttrs(this);
598 void Decl::swapAttrs(Decl *RHS) {
599 bool HasLHSAttr = this->HasAttrs;
600 bool HasRHSAttr = RHS->HasAttrs;
602 // Usually, neither decl has attrs, nothing to do.
603 if (!HasLHSAttr && !HasRHSAttr) return;
605 // If 'this' has no attrs, swap the other way.
607 return RHS->swapAttrs(this);
609 ASTContext &Context = getASTContext();
611 // Handle the case when both decls have attrs.
613 std::swap(Context.getDeclAttrs(this), Context.getDeclAttrs(RHS));
617 // Otherwise, LHS has an attr and RHS doesn't.
618 Context.getDeclAttrs(RHS) = Context.getDeclAttrs(this);
619 Context.eraseDeclAttrs(this);
620 this->HasAttrs = false;
621 RHS->HasAttrs = true;
624 Decl *Decl::castFromDeclContext (const DeclContext *D) {
625 Decl::Kind DK = D->getDeclKind();
627 #define DECL(NAME, BASE)
628 #define DECL_CONTEXT(NAME) \
630 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
631 #define DECL_CONTEXT_BASE(NAME)
632 #include "clang/AST/DeclNodes.inc"
634 #define DECL(NAME, BASE)
635 #define DECL_CONTEXT_BASE(NAME) \
636 if (DK >= first##NAME && DK <= last##NAME) \
637 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
638 #include "clang/AST/DeclNodes.inc"
639 llvm_unreachable("a decl that inherits DeclContext isn't handled");
643 DeclContext *Decl::castToDeclContext(const Decl *D) {
644 Decl::Kind DK = D->getKind();
646 #define DECL(NAME, BASE)
647 #define DECL_CONTEXT(NAME) \
649 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
650 #define DECL_CONTEXT_BASE(NAME)
651 #include "clang/AST/DeclNodes.inc"
653 #define DECL(NAME, BASE)
654 #define DECL_CONTEXT_BASE(NAME) \
655 if (DK >= first##NAME && DK <= last##NAME) \
656 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
657 #include "clang/AST/DeclNodes.inc"
658 llvm_unreachable("a decl that inherits DeclContext isn't handled");
662 SourceLocation Decl::getBodyRBrace() const {
663 // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
664 // FunctionDecl stores EndRangeLoc for this purpose.
665 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
666 const FunctionDecl *Definition;
667 if (FD->hasBody(Definition))
668 return Definition->getSourceRange().getEnd();
669 return SourceLocation();
672 if (Stmt *Body = getBody())
673 return Body->getSourceRange().getEnd();
675 return SourceLocation();
678 void Decl::CheckAccessDeclContext() const {
680 // Suppress this check if any of the following hold:
681 // 1. this is the translation unit (and thus has no parent)
682 // 2. this is a template parameter (and thus doesn't belong to its context)
683 // 3. this is a non-type template parameter
684 // 4. the context is not a record
686 // 6. it's a C++0x static_assert.
687 if (isa<TranslationUnitDecl>(this) ||
688 isa<TemplateTypeParmDecl>(this) ||
689 isa<NonTypeTemplateParmDecl>(this) ||
690 !isa<CXXRecordDecl>(getDeclContext()) ||
692 isa<StaticAssertDecl>(this) ||
693 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
694 // as DeclContext (?).
695 isa<ParmVarDecl>(this) ||
696 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
697 // AS_none as access specifier.
698 isa<CXXRecordDecl>(this) ||
699 isa<ClassScopeFunctionSpecializationDecl>(this))
702 assert(Access != AS_none &&
703 "Access specifier is AS_none inside a record decl");
707 static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
708 static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
710 /// Starting at a given context (a Decl or DeclContext), look for a
711 /// code context that is not a closure (a lambda, block, etc.).
712 template <class T> static Decl *getNonClosureContext(T *D) {
713 if (getKind(D) == Decl::CXXMethod) {
714 CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
715 if (MD->getOverloadedOperator() == OO_Call &&
716 MD->getParent()->isLambda())
717 return getNonClosureContext(MD->getParent()->getParent());
719 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
721 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
723 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
724 return getNonClosureContext(BD->getParent());
725 } else if (CapturedDecl *CD = dyn_cast<CapturedDecl>(D)) {
726 return getNonClosureContext(CD->getParent());
732 Decl *Decl::getNonClosureContext() {
733 return ::getNonClosureContext(this);
736 Decl *DeclContext::getNonClosureAncestor() {
737 return ::getNonClosureContext(this);
740 //===----------------------------------------------------------------------===//
741 // DeclContext Implementation
742 //===----------------------------------------------------------------------===//
744 bool DeclContext::classof(const Decl *D) {
745 switch (D->getKind()) {
746 #define DECL(NAME, BASE)
747 #define DECL_CONTEXT(NAME) case Decl::NAME:
748 #define DECL_CONTEXT_BASE(NAME)
749 #include "clang/AST/DeclNodes.inc"
752 #define DECL(NAME, BASE)
753 #define DECL_CONTEXT_BASE(NAME) \
754 if (D->getKind() >= Decl::first##NAME && \
755 D->getKind() <= Decl::last##NAME) \
757 #include "clang/AST/DeclNodes.inc"
762 DeclContext::~DeclContext() { }
764 /// \brief Find the parent context of this context that will be
765 /// used for unqualified name lookup.
767 /// Generally, the parent lookup context is the semantic context. However, for
768 /// a friend function the parent lookup context is the lexical context, which
769 /// is the class in which the friend is declared.
770 DeclContext *DeclContext::getLookupParent() {
771 // FIXME: Find a better way to identify friends
772 if (isa<FunctionDecl>(this))
773 if (getParent()->getRedeclContext()->isFileContext() &&
774 getLexicalParent()->getRedeclContext()->isRecord())
775 return getLexicalParent();
780 bool DeclContext::isInlineNamespace() const {
781 return isNamespace() &&
782 cast<NamespaceDecl>(this)->isInline();
785 bool DeclContext::isDependentContext() const {
789 if (isa<ClassTemplatePartialSpecializationDecl>(this))
792 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
793 if (Record->getDescribedClassTemplate())
796 if (Record->isDependentLambda())
800 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
801 if (Function->getDescribedFunctionTemplate())
804 // Friend function declarations are dependent if their *lexical*
805 // context is dependent.
806 if (cast<Decl>(this)->getFriendObjectKind())
807 return getLexicalParent()->isDependentContext();
810 return getParent() && getParent()->isDependentContext();
813 bool DeclContext::isTransparentContext() const {
814 if (DeclKind == Decl::Enum)
815 return !cast<EnumDecl>(this)->isScoped();
816 else if (DeclKind == Decl::LinkageSpec)
822 bool DeclContext::Encloses(const DeclContext *DC) const {
823 if (getPrimaryContext() != this)
824 return getPrimaryContext()->Encloses(DC);
826 for (; DC; DC = DC->getParent())
827 if (DC->getPrimaryContext() == this)
832 DeclContext *DeclContext::getPrimaryContext() {
834 case Decl::TranslationUnit:
835 case Decl::LinkageSpec:
838 // There is only one DeclContext for these entities.
841 case Decl::Namespace:
842 // The original namespace is our primary context.
843 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
845 case Decl::ObjCMethod:
848 case Decl::ObjCInterface:
849 if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
854 case Decl::ObjCProtocol:
855 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
860 case Decl::ObjCCategory:
863 case Decl::ObjCImplementation:
864 case Decl::ObjCCategoryImpl:
868 if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
869 // If this is a tag type that has a definition or is currently
870 // being defined, that definition is our primary context.
871 TagDecl *Tag = cast<TagDecl>(this);
872 assert(isa<TagType>(Tag->TypeForDecl) ||
873 isa<InjectedClassNameType>(Tag->TypeForDecl));
875 if (TagDecl *Def = Tag->getDefinition())
878 if (!isa<InjectedClassNameType>(Tag->TypeForDecl)) {
879 const TagType *TagTy = cast<TagType>(Tag->TypeForDecl);
880 if (TagTy->isBeingDefined())
881 // FIXME: is it necessarily being defined in the decl
882 // that owns the type?
883 return TagTy->getDecl();
889 assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
890 "Unknown DeclContext kind");
896 DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
899 if (DeclKind != Decl::Namespace) {
900 Contexts.push_back(this);
904 NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
905 for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
906 N = N->getPreviousDecl())
907 Contexts.push_back(N);
909 std::reverse(Contexts.begin(), Contexts.end());
912 std::pair<Decl *, Decl *>
913 DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
914 bool FieldsAlreadyLoaded) {
915 // Build up a chain of declarations via the Decl::NextInContextAndBits field.
916 Decl *FirstNewDecl = 0;
918 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
919 if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
924 PrevDecl->NextInContextAndBits.setPointer(D);
931 return std::make_pair(FirstNewDecl, PrevDecl);
934 /// \brief We have just acquired external visible storage, and we already have
935 /// built a lookup map. For every name in the map, pull in the new names from
936 /// the external storage.
937 void DeclContext::reconcileExternalVisibleStorage() {
938 assert(NeedToReconcileExternalVisibleStorage && LookupPtr.getPointer());
939 NeedToReconcileExternalVisibleStorage = false;
941 StoredDeclsMap &Map = *LookupPtr.getPointer();
942 ExternalASTSource *Source = getParentASTContext().getExternalSource();
943 for (StoredDeclsMap::iterator I = Map.begin(); I != Map.end(); ++I) {
944 I->second.removeExternalDecls();
945 Source->FindExternalVisibleDeclsByName(this, I->first);
949 /// \brief Load the declarations within this lexical storage from an
952 DeclContext::LoadLexicalDeclsFromExternalStorage() const {
953 ExternalASTSource *Source = getParentASTContext().getExternalSource();
954 assert(hasExternalLexicalStorage() && Source && "No external storage?");
956 // Notify that we have a DeclContext that is initializing.
957 ExternalASTSource::Deserializing ADeclContext(Source);
959 // Load the external declarations, if any.
960 SmallVector<Decl*, 64> Decls;
961 ExternalLexicalStorage = false;
962 switch (Source->FindExternalLexicalDecls(this, Decls)) {
967 case ELR_AlreadyLoaded:
974 // We may have already loaded just the fields of this record, in which case
975 // we need to ignore them.
976 bool FieldsAlreadyLoaded = false;
977 if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
978 FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
980 // Splice the newly-read declarations into the beginning of the list
982 Decl *ExternalFirst, *ExternalLast;
983 llvm::tie(ExternalFirst, ExternalLast) = BuildDeclChain(Decls,
984 FieldsAlreadyLoaded);
985 ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
986 FirstDecl = ExternalFirst;
988 LastDecl = ExternalLast;
991 DeclContext::lookup_result
992 ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
993 DeclarationName Name) {
994 ASTContext &Context = DC->getParentASTContext();
996 if (!(Map = DC->LookupPtr.getPointer()))
997 Map = DC->CreateStoredDeclsMap(Context);
999 // Add an entry to the map for this name, if it's not already present.
1002 return DeclContext::lookup_result();
1005 DeclContext::lookup_result
1006 ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
1007 DeclarationName Name,
1008 ArrayRef<NamedDecl*> Decls) {
1009 ASTContext &Context = DC->getParentASTContext();
1010 StoredDeclsMap *Map;
1011 if (!(Map = DC->LookupPtr.getPointer()))
1012 Map = DC->CreateStoredDeclsMap(Context);
1014 StoredDeclsList &List = (*Map)[Name];
1015 for (ArrayRef<NamedDecl*>::iterator
1016 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1018 List.setOnlyValue(*I);
1020 // FIXME: Need declarationReplaces handling for redeclarations in modules.
1021 List.AddSubsequentDecl(*I);
1024 return List.getLookupResult();
1027 DeclContext::decl_iterator DeclContext::noload_decls_begin() const {
1028 return decl_iterator(FirstDecl);
1031 DeclContext::decl_iterator DeclContext::decls_begin() const {
1032 if (hasExternalLexicalStorage())
1033 LoadLexicalDeclsFromExternalStorage();
1035 return decl_iterator(FirstDecl);
1038 bool DeclContext::decls_empty() const {
1039 if (hasExternalLexicalStorage())
1040 LoadLexicalDeclsFromExternalStorage();
1045 bool DeclContext::containsDecl(Decl *D) const {
1046 return (D->getLexicalDeclContext() == this &&
1047 (D->NextInContextAndBits.getPointer() || D == LastDecl));
1050 void DeclContext::removeDecl(Decl *D) {
1051 assert(D->getLexicalDeclContext() == this &&
1052 "decl being removed from non-lexical context");
1053 assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
1054 "decl is not in decls list");
1056 // Remove D from the decl chain. This is O(n) but hopefully rare.
1057 if (D == FirstDecl) {
1059 FirstDecl = LastDecl = 0;
1061 FirstDecl = D->NextInContextAndBits.getPointer();
1063 for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
1064 assert(I && "decl not found in linked list");
1065 if (I->NextInContextAndBits.getPointer() == D) {
1066 I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
1067 if (D == LastDecl) LastDecl = I;
1073 // Mark that D is no longer in the decl chain.
1074 D->NextInContextAndBits.setPointer(0);
1076 // Remove D from the lookup table if necessary.
1077 if (isa<NamedDecl>(D)) {
1078 NamedDecl *ND = cast<NamedDecl>(D);
1080 // Remove only decls that have a name
1081 if (!ND->getDeclName()) return;
1083 StoredDeclsMap *Map = getPrimaryContext()->LookupPtr.getPointer();
1086 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1087 assert(Pos != Map->end() && "no lookup entry for decl");
1088 if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
1089 Pos->second.remove(ND);
1093 void DeclContext::addHiddenDecl(Decl *D) {
1094 assert(D->getLexicalDeclContext() == this &&
1095 "Decl inserted into wrong lexical context");
1096 assert(!D->getNextDeclInContext() && D != LastDecl &&
1097 "Decl already inserted into a DeclContext");
1100 LastDecl->NextInContextAndBits.setPointer(D);
1103 FirstDecl = LastDecl = D;
1106 // Notify a C++ record declaration that we've added a member, so it can
1107 // update it's class-specific state.
1108 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1109 Record->addedMember(D);
1111 // If this is a newly-created (not de-serialized) import declaration, wire
1112 // it in to the list of local import declarations.
1113 if (!D->isFromASTFile()) {
1114 if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
1115 D->getASTContext().addedLocalImportDecl(Import);
1119 void DeclContext::addDecl(Decl *D) {
1122 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1123 ND->getDeclContext()->getPrimaryContext()->
1124 makeDeclVisibleInContextWithFlags(ND, false, true);
1127 void DeclContext::addDeclInternal(Decl *D) {
1130 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1131 ND->getDeclContext()->getPrimaryContext()->
1132 makeDeclVisibleInContextWithFlags(ND, true, true);
1135 /// shouldBeHidden - Determine whether a declaration which was declared
1136 /// within its semantic context should be invisible to qualified name lookup.
1137 static bool shouldBeHidden(NamedDecl *D) {
1138 // Skip unnamed declarations.
1139 if (!D->getDeclName())
1142 // Skip entities that can't be found by name lookup into a particular
1144 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1145 D->isTemplateParameter())
1148 // Skip template specializations.
1149 // FIXME: This feels like a hack. Should DeclarationName support
1150 // template-ids, or is there a better way to keep specializations
1151 // from being visible?
1152 if (isa<ClassTemplateSpecializationDecl>(D))
1154 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1155 if (FD->isFunctionTemplateSpecialization())
1161 /// buildLookup - Build the lookup data structure with all of the
1162 /// declarations in this DeclContext (and any other contexts linked
1163 /// to it or transparent contexts nested within it) and return it.
1164 StoredDeclsMap *DeclContext::buildLookup() {
1165 assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1167 // FIXME: Should we keep going if hasExternalVisibleStorage?
1168 if (!LookupPtr.getInt())
1169 return LookupPtr.getPointer();
1171 SmallVector<DeclContext *, 2> Contexts;
1172 collectAllContexts(Contexts);
1173 for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
1174 buildLookupImpl(Contexts[I]);
1176 // We no longer have any lazy decls.
1177 LookupPtr.setInt(false);
1178 NeedToReconcileExternalVisibleStorage = false;
1179 return LookupPtr.getPointer();
1182 /// buildLookupImpl - Build part of the lookup data structure for the
1183 /// declarations contained within DCtx, which will either be this
1184 /// DeclContext, a DeclContext linked to it, or a transparent context
1185 /// nested within it.
1186 void DeclContext::buildLookupImpl(DeclContext *DCtx) {
1187 for (decl_iterator I = DCtx->decls_begin(), E = DCtx->decls_end();
1191 // Insert this declaration into the lookup structure, but only if
1192 // it's semantically within its decl context. Any other decls which
1193 // should be found in this context are added eagerly.
1194 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1195 if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND))
1196 makeDeclVisibleInContextImpl(ND, false);
1198 // If this declaration is itself a transparent declaration context
1199 // or inline namespace, add the members of this declaration of that
1200 // context (recursively).
1201 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
1202 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1203 buildLookupImpl(InnerCtx);
1207 DeclContext::lookup_result
1208 DeclContext::lookup(DeclarationName Name) {
1209 assert(DeclKind != Decl::LinkageSpec &&
1210 "Should not perform lookups into linkage specs!");
1212 DeclContext *PrimaryContext = getPrimaryContext();
1213 if (PrimaryContext != this)
1214 return PrimaryContext->lookup(Name);
1216 if (hasExternalVisibleStorage()) {
1217 StoredDeclsMap *Map = LookupPtr.getPointer();
1218 if (LookupPtr.getInt())
1219 Map = buildLookup();
1220 else if (NeedToReconcileExternalVisibleStorage)
1221 reconcileExternalVisibleStorage();
1224 Map = CreateStoredDeclsMap(getParentASTContext());
1226 // If a PCH/module has a result for this name, and we have a local
1227 // declaration, we will have imported the PCH/module result when adding the
1228 // local declaration or when reconciling the module.
1229 std::pair<StoredDeclsMap::iterator, bool> R =
1230 Map->insert(std::make_pair(Name, StoredDeclsList()));
1232 return R.first->second.getLookupResult();
1234 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1235 if (Source->FindExternalVisibleDeclsByName(this, Name)) {
1236 if (StoredDeclsMap *Map = LookupPtr.getPointer()) {
1237 StoredDeclsMap::iterator I = Map->find(Name);
1238 if (I != Map->end())
1239 return I->second.getLookupResult();
1243 return lookup_result(lookup_iterator(0), lookup_iterator(0));
1246 StoredDeclsMap *Map = LookupPtr.getPointer();
1247 if (LookupPtr.getInt())
1248 Map = buildLookup();
1251 return lookup_result(lookup_iterator(0), lookup_iterator(0));
1253 StoredDeclsMap::iterator I = Map->find(Name);
1254 if (I == Map->end())
1255 return lookup_result(lookup_iterator(0), lookup_iterator(0));
1257 return I->second.getLookupResult();
1260 void DeclContext::localUncachedLookup(DeclarationName Name,
1261 SmallVectorImpl<NamedDecl *> &Results) {
1264 // If there's no external storage, just perform a normal lookup and copy
1266 if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
1267 lookup_result LookupResults = lookup(Name);
1268 Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
1272 // If we have a lookup table, check there first. Maybe we'll get lucky.
1273 if (Name && !LookupPtr.getInt()) {
1274 if (StoredDeclsMap *Map = LookupPtr.getPointer()) {
1275 StoredDeclsMap::iterator Pos = Map->find(Name);
1276 if (Pos != Map->end()) {
1277 Results.insert(Results.end(),
1278 Pos->second.getLookupResult().begin(),
1279 Pos->second.getLookupResult().end());
1285 // Slow case: grovel through the declarations in our chain looking for
1287 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1288 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1289 if (ND->getDeclName() == Name)
1290 Results.push_back(ND);
1294 DeclContext *DeclContext::getRedeclContext() {
1295 DeclContext *Ctx = this;
1296 // Skip through transparent contexts.
1297 while (Ctx->isTransparentContext())
1298 Ctx = Ctx->getParent();
1302 DeclContext *DeclContext::getEnclosingNamespaceContext() {
1303 DeclContext *Ctx = this;
1304 // Skip through non-namespace, non-translation-unit contexts.
1305 while (!Ctx->isFileContext())
1306 Ctx = Ctx->getParent();
1307 return Ctx->getPrimaryContext();
1310 bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1311 // For non-file contexts, this is equivalent to Equals.
1312 if (!isFileContext())
1313 return O->Equals(this);
1316 if (O->Equals(this))
1319 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1320 if (!NS || !NS->isInline())
1322 O = NS->getParent();
1328 void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1329 DeclContext *PrimaryDC = this->getPrimaryContext();
1330 DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1331 // If the decl is being added outside of its semantic decl context, we
1332 // need to ensure that we eagerly build the lookup information for it.
1333 PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
1336 void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1338 assert(this == getPrimaryContext() && "expected a primary DC");
1340 // Skip declarations within functions.
1341 // FIXME: We shouldn't need to build lookup tables for function declarations
1342 // ever, and we can't do so correctly because we can't model the nesting of
1343 // scopes which occurs within functions. We use "qualified" lookup into
1344 // function declarations when handling friend declarations inside nested
1345 // classes, and consequently accept the following invalid code:
1347 // void f() { void g(); { int g; struct S { friend void g(); }; } }
1348 if (isFunctionOrMethod() && !isa<FunctionDecl>(D))
1351 // Skip declarations which should be invisible to name lookup.
1352 if (shouldBeHidden(D))
1355 // If we already have a lookup data structure, perform the insertion into
1356 // it. If we might have externally-stored decls with this name, look them
1357 // up and perform the insertion. If this decl was declared outside its
1358 // semantic context, buildLookup won't add it, so add it now.
1360 // FIXME: As a performance hack, don't add such decls into the translation
1361 // unit unless we're in C++, since qualified lookup into the TU is never
1363 if (LookupPtr.getPointer() || hasExternalVisibleStorage() ||
1364 ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1365 (getParentASTContext().getLangOpts().CPlusPlus ||
1366 !isTranslationUnit()))) {
1367 // If we have lazily omitted any decls, they might have the same name as
1368 // the decl which we are adding, so build a full lookup table before adding
1371 makeDeclVisibleInContextImpl(D, Internal);
1373 LookupPtr.setInt(true);
1376 // If we are a transparent context or inline namespace, insert into our
1377 // parent context, too. This operation is recursive.
1378 if (isTransparentContext() || isInlineNamespace())
1379 getParent()->getPrimaryContext()->
1380 makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1382 Decl *DCAsDecl = cast<Decl>(this);
1383 // Notify that a decl was made visible unless we are a Tag being defined.
1384 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1385 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1386 L->AddedVisibleDecl(this, D);
1389 void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1390 // Find or create the stored declaration map.
1391 StoredDeclsMap *Map = LookupPtr.getPointer();
1393 ASTContext *C = &getParentASTContext();
1394 Map = CreateStoredDeclsMap(*C);
1397 // If there is an external AST source, load any declarations it knows about
1398 // with this declaration's name.
1399 // If the lookup table contains an entry about this name it means that we
1400 // have already checked the external source.
1402 if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1403 if (hasExternalVisibleStorage() &&
1404 Map->find(D->getDeclName()) == Map->end())
1405 Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1407 // Insert this declaration into the map.
1408 StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
1409 if (DeclNameEntries.isNull()) {
1410 DeclNameEntries.setOnlyValue(D);
1414 if (DeclNameEntries.HandleRedeclaration(D)) {
1415 // This declaration has replaced an existing one for which
1416 // declarationReplaces returns true.
1420 // Put this declaration into the appropriate slot.
1421 DeclNameEntries.AddSubsequentDecl(D);
1424 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1426 DeclContext::udir_iterator_range
1427 DeclContext::getUsingDirectives() const {
1428 // FIXME: Use something more efficient than normal lookup for using
1429 // directives. In C++, using directives are looked up more than anything else.
1430 lookup_const_result Result = lookup(UsingDirectiveDecl::getName());
1431 return udir_iterator_range(reinterpret_cast<udir_iterator>(Result.begin()),
1432 reinterpret_cast<udir_iterator>(Result.end()));
1435 //===----------------------------------------------------------------------===//
1436 // Creation and Destruction of StoredDeclsMaps. //
1437 //===----------------------------------------------------------------------===//
1439 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1440 assert(!LookupPtr.getPointer() && "context already has a decls map");
1441 assert(getPrimaryContext() == this &&
1442 "creating decls map on non-primary context");
1445 bool Dependent = isDependentContext();
1447 M = new DependentStoredDeclsMap();
1449 M = new StoredDeclsMap();
1450 M->Previous = C.LastSDM;
1451 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1452 LookupPtr.setPointer(M);
1456 void ASTContext::ReleaseDeclContextMaps() {
1457 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1458 // pointer because the subclass doesn't add anything that needs to
1460 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1463 void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1465 // Advance the iteration before we invalidate memory.
1466 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1469 delete static_cast<DependentStoredDeclsMap*>(Map);
1473 Map = Next.getPointer();
1474 Dependent = Next.getInt();
1478 DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1479 DeclContext *Parent,
1480 const PartialDiagnostic &PDiag) {
1481 assert(Parent->isDependentContext()
1482 && "cannot iterate dependent diagnostics of non-dependent context");
1483 Parent = Parent->getPrimaryContext();
1484 if (!Parent->LookupPtr.getPointer())
1485 Parent->CreateStoredDeclsMap(C);
1487 DependentStoredDeclsMap *Map
1488 = static_cast<DependentStoredDeclsMap*>(Parent->LookupPtr.getPointer());
1490 // Allocate the copy of the PartialDiagnostic via the ASTContext's
1491 // BumpPtrAllocator, rather than the ASTContext itself.
1492 PartialDiagnostic::Storage *DiagStorage = 0;
1493 if (PDiag.hasStorage())
1494 DiagStorage = new (C) PartialDiagnostic::Storage;
1496 DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
1498 // TODO: Maybe we shouldn't reverse the order during insertion.
1499 DD->NextDiagnostic = Map->FirstDiagnostic;
1500 Map->FirstDiagnostic = DD;