DeclBase.cpp revision 770877fa855d1de462392e503ef08252614b0994
1//===--- DeclBase.cpp - Declaration AST Node Implementation ---------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements the Decl and DeclContext classes. 11// 12//===----------------------------------------------------------------------===// 13 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 "llvm/ADT/DenseMap.h" 29#include "llvm/Support/raw_ostream.h" 30#include <algorithm> 31#include <cstdio> 32#include <vector> 33using namespace clang; 34 35//===----------------------------------------------------------------------===// 36// Statistics 37//===----------------------------------------------------------------------===// 38 39#define DECL(DERIVED, BASE) static int n##DERIVED##s = 0; 40#define ABSTRACT_DECL(DECL) 41#include "clang/AST/DeclNodes.inc" 42 43static bool StatSwitch = false; 44 45namespace { 46 template<typename Class> 47 inline SourceRange getSourceRangeImpl(const Decl *D, 48 SourceRange (Class::*)() const) { 49 return static_cast<const Class *>(D)->getSourceRange(); 50 } 51 52 inline SourceRange getSourceRangeImpl(const Decl *D, 53 SourceRange (Decl::*)() const) { 54 return D->getLocation(); 55 } 56} 57 58SourceRange Decl::getSourceRange() const { 59 switch (getKind()) { 60#define ABSTRACT_DECL(Type) 61#define DECL(Type, Base) \ 62 case Type: return getSourceRangeImpl(this, &Type##Decl::getSourceRange); 63#include "clang/AST/DeclNodes.inc" 64 } 65 66 return getLocation(); 67} 68 69const char *Decl::getDeclKindName() const { 70 switch (DeclKind) { 71 default: assert(0 && "Declaration not in DeclNodes.inc!"); 72#define DECL(DERIVED, BASE) case DERIVED: return #DERIVED; 73#define ABSTRACT_DECL(DECL) 74#include "clang/AST/DeclNodes.inc" 75 } 76} 77 78void Decl::setInvalidDecl(bool Invalid) { 79 InvalidDecl = Invalid; 80 if (Invalid) { 81 // Defensive maneuver for ill-formed code: we're likely not to make it to 82 // a point where we set the access specifier, so default it to "public" 83 // to avoid triggering asserts elsewhere in the front end. 84 setAccess(AS_public); 85 } 86} 87 88const char *DeclContext::getDeclKindName() const { 89 switch (DeclKind) { 90 default: assert(0 && "Declaration context not in DeclNodes.inc!"); 91#define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED; 92#define ABSTRACT_DECL(DECL) 93#include "clang/AST/DeclNodes.inc" 94 } 95} 96 97bool Decl::CollectingStats(bool Enable) { 98 if (Enable) StatSwitch = true; 99 return StatSwitch; 100} 101 102void Decl::PrintStats() { 103 fprintf(stderr, "*** Decl Stats:\n"); 104 105 int totalDecls = 0; 106#define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s; 107#define ABSTRACT_DECL(DECL) 108#include "clang/AST/DeclNodes.inc" 109 fprintf(stderr, " %d decls total.\n", totalDecls); 110 111 int totalBytes = 0; 112#define DECL(DERIVED, BASE) \ 113 if (n##DERIVED##s > 0) { \ 114 totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \ 115 fprintf(stderr, " %d " #DERIVED " decls, %d each (%d bytes)\n", \ 116 n##DERIVED##s, (int)sizeof(DERIVED##Decl), \ 117 (int)(n##DERIVED##s * sizeof(DERIVED##Decl))); \ 118 } 119#define ABSTRACT_DECL(DECL) 120#include "clang/AST/DeclNodes.inc" 121 122 fprintf(stderr, "Total bytes = %d\n", totalBytes); 123} 124 125void Decl::add(Kind k) { 126 switch (k) { 127 default: assert(0 && "Declaration not in DeclNodes.inc!"); 128#define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break; 129#define ABSTRACT_DECL(DECL) 130#include "clang/AST/DeclNodes.inc" 131 } 132} 133 134bool Decl::isTemplateParameterPack() const { 135 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this)) 136 return TTP->isParameterPack(); 137 if (const NonTypeTemplateParmDecl *NTTP 138 = dyn_cast<NonTypeTemplateParmDecl>(this)) 139 return NTTP->isParameterPack(); 140 if (const TemplateTemplateParmDecl *TTP 141 = dyn_cast<TemplateTemplateParmDecl>(this)) 142 return TTP->isParameterPack(); 143 return false; 144} 145 146bool Decl::isParameterPack() const { 147 if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this)) 148 return Parm->isParameterPack(); 149 150 return isTemplateParameterPack(); 151} 152 153bool Decl::isFunctionOrFunctionTemplate() const { 154 if (const UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(this)) 155 return UD->getTargetDecl()->isFunctionOrFunctionTemplate(); 156 157 return isa<FunctionDecl>(this) || isa<FunctionTemplateDecl>(this); 158} 159 160bool Decl::isDefinedOutsideFunctionOrMethod() const { 161 for (const DeclContext *DC = getDeclContext(); 162 DC && !DC->isTranslationUnit(); 163 DC = DC->getParent()) 164 if (DC->isFunctionOrMethod()) 165 return false; 166 167 return true; 168} 169 170namespace { 171 template<typename Class, typename Result> 172 inline Result *getSpecificCanonicalDecl(Decl *D, Result *(Class::*Get)()) { 173 return (llvm::cast<Class>(D)->*Get)(); 174 } 175 176 inline Decl *getSpecificCanonicalDecl(Decl *D, Decl *(Decl::*)()) { 177 // No specific implementation. 178 return D; 179 } 180} 181 182Decl *Decl::getCanonicalDecl() { 183 switch (getKind()) { 184#define ABSTRACT_DECL(Type) 185#define DECL(Type, Base) \ 186 case Type: \ 187 return getSpecificCanonicalDecl(this, &Type##Decl::getCanonicalDecl); 188#include "clang/AST/DeclNodes.inc" 189 } 190 191 return this; 192} 193 194//===----------------------------------------------------------------------===// 195// PrettyStackTraceDecl Implementation 196//===----------------------------------------------------------------------===// 197 198void PrettyStackTraceDecl::print(llvm::raw_ostream &OS) const { 199 SourceLocation TheLoc = Loc; 200 if (TheLoc.isInvalid() && TheDecl) 201 TheLoc = TheDecl->getLocation(); 202 203 if (TheLoc.isValid()) { 204 TheLoc.print(OS, SM); 205 OS << ": "; 206 } 207 208 OS << Message; 209 210 if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) 211 OS << " '" << DN->getQualifiedNameAsString() << '\''; 212 OS << '\n'; 213} 214 215//===----------------------------------------------------------------------===// 216// Decl Implementation 217//===----------------------------------------------------------------------===// 218 219// Out-of-line virtual method providing a home for Decl. 220Decl::~Decl() { } 221 222bool Decl::isOutOfLine() const { 223 if (const VarDecl *VD = dyn_cast<VarDecl>(this)) 224 return VD->isOutOfLine(); 225 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) 226 return FD->isOutOfLine(); 227 228 return getLexicalDeclContext() != getDeclContext(); 229} 230 231void Decl::setDeclContext(DeclContext *DC) { 232 if (isOutOfSemaDC()) 233 delete getMultipleDC(); 234 235 DeclCtx = DC; 236} 237 238void Decl::setLexicalDeclContext(DeclContext *DC) { 239 if (DC == getLexicalDeclContext()) 240 return; 241 242 if (isInSemaDC()) { 243 MultipleDC *MDC = new (getASTContext()) MultipleDC(); 244 MDC->SemanticDC = getDeclContext(); 245 MDC->LexicalDC = DC; 246 DeclCtx = MDC; 247 } else { 248 getMultipleDC()->LexicalDC = DC; 249 } 250} 251 252bool Decl::isInAnonymousNamespace() const { 253 const DeclContext *DC = getDeclContext(); 254 do { 255 if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC)) 256 if (ND->isAnonymousNamespace()) 257 return true; 258 } while ((DC = DC->getParent())); 259 260 return false; 261} 262 263TranslationUnitDecl *Decl::getTranslationUnitDecl() { 264 if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this)) 265 return TUD; 266 267 DeclContext *DC = getDeclContext(); 268 assert(DC && "This decl is not contained in a translation unit!"); 269 270 while (!DC->isTranslationUnit()) { 271 DC = DC->getParent(); 272 assert(DC && "This decl is not contained in a translation unit!"); 273 } 274 275 return cast<TranslationUnitDecl>(DC); 276} 277 278ASTContext &Decl::getASTContext() const { 279 return getTranslationUnitDecl()->getASTContext(); 280} 281 282ASTMutationListener *Decl::getASTMutationListener() const { 283 return getASTContext().getASTMutationListener(); 284} 285 286bool Decl::isUsed(bool CheckUsedAttr) const { 287 if (Used) 288 return true; 289 290 // Check for used attribute. 291 if (CheckUsedAttr && hasAttr<UsedAttr>()) 292 return true; 293 294 // Check redeclarations for used attribute. 295 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) { 296 if ((CheckUsedAttr && I->hasAttr<UsedAttr>()) || I->Used) 297 return true; 298 } 299 300 return false; 301} 302 303 304unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) { 305 switch (DeclKind) { 306 case Function: 307 case CXXMethod: 308 case CXXConstructor: 309 case CXXDestructor: 310 case CXXConversion: 311 case EnumConstant: 312 case Var: 313 case ImplicitParam: 314 case ParmVar: 315 case NonTypeTemplateParm: 316 case ObjCMethod: 317 case ObjCProperty: 318 return IDNS_Ordinary; 319 case Label: 320 return IDNS_Label; 321 case IndirectField: 322 return IDNS_Ordinary | IDNS_Member; 323 324 case ObjCCompatibleAlias: 325 case ObjCInterface: 326 return IDNS_Ordinary | IDNS_Type; 327 328 case Typedef: 329 case UnresolvedUsingTypename: 330 case TemplateTypeParm: 331 return IDNS_Ordinary | IDNS_Type; 332 333 case UsingShadow: 334 return 0; // we'll actually overwrite this later 335 336 case UnresolvedUsingValue: 337 return IDNS_Ordinary | IDNS_Using; 338 339 case Using: 340 return IDNS_Using; 341 342 case ObjCProtocol: 343 return IDNS_ObjCProtocol; 344 345 case Field: 346 case ObjCAtDefsField: 347 case ObjCIvar: 348 return IDNS_Member; 349 350 case Record: 351 case CXXRecord: 352 case Enum: 353 return IDNS_Tag | IDNS_Type; 354 355 case Namespace: 356 case NamespaceAlias: 357 return IDNS_Namespace; 358 359 case FunctionTemplate: 360 return IDNS_Ordinary; 361 362 case ClassTemplate: 363 case TemplateTemplateParm: 364 return IDNS_Ordinary | IDNS_Tag | IDNS_Type; 365 366 // Never have names. 367 case Friend: 368 case FriendTemplate: 369 case AccessSpec: 370 case LinkageSpec: 371 case FileScopeAsm: 372 case StaticAssert: 373 case ObjCClass: 374 case ObjCPropertyImpl: 375 case ObjCForwardProtocol: 376 case Block: 377 case TranslationUnit: 378 379 case UsingDirective: 380 case ClassTemplateSpecialization: 381 case ClassTemplatePartialSpecialization: 382 case ObjCImplementation: 383 case ObjCCategory: 384 case ObjCCategoryImpl: 385 // Never looked up by name. 386 return 0; 387 } 388 389 return 0; 390} 391 392void Decl::setAttrs(const AttrVec &attrs) { 393 assert(!HasAttrs && "Decl already contains attrs."); 394 395 AttrVec &AttrBlank = getASTContext().getDeclAttrs(this); 396 assert(AttrBlank.empty() && "HasAttrs was wrong?"); 397 398 AttrBlank = attrs; 399 HasAttrs = true; 400} 401 402void Decl::dropAttrs() { 403 if (!HasAttrs) return; 404 405 HasAttrs = false; 406 getASTContext().eraseDeclAttrs(this); 407} 408 409const AttrVec &Decl::getAttrs() const { 410 assert(HasAttrs && "No attrs to get!"); 411 return getASTContext().getDeclAttrs(this); 412} 413 414void Decl::swapAttrs(Decl *RHS) { 415 bool HasLHSAttr = this->HasAttrs; 416 bool HasRHSAttr = RHS->HasAttrs; 417 418 // Usually, neither decl has attrs, nothing to do. 419 if (!HasLHSAttr && !HasRHSAttr) return; 420 421 // If 'this' has no attrs, swap the other way. 422 if (!HasLHSAttr) 423 return RHS->swapAttrs(this); 424 425 ASTContext &Context = getASTContext(); 426 427 // Handle the case when both decls have attrs. 428 if (HasRHSAttr) { 429 std::swap(Context.getDeclAttrs(this), Context.getDeclAttrs(RHS)); 430 return; 431 } 432 433 // Otherwise, LHS has an attr and RHS doesn't. 434 Context.getDeclAttrs(RHS) = Context.getDeclAttrs(this); 435 Context.eraseDeclAttrs(this); 436 this->HasAttrs = false; 437 RHS->HasAttrs = true; 438} 439 440Decl *Decl::castFromDeclContext (const DeclContext *D) { 441 Decl::Kind DK = D->getDeclKind(); 442 switch(DK) { 443#define DECL(NAME, BASE) 444#define DECL_CONTEXT(NAME) \ 445 case Decl::NAME: \ 446 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D)); 447#define DECL_CONTEXT_BASE(NAME) 448#include "clang/AST/DeclNodes.inc" 449 default: 450#define DECL(NAME, BASE) 451#define DECL_CONTEXT_BASE(NAME) \ 452 if (DK >= first##NAME && DK <= last##NAME) \ 453 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D)); 454#include "clang/AST/DeclNodes.inc" 455 assert(false && "a decl that inherits DeclContext isn't handled"); 456 return 0; 457 } 458} 459 460DeclContext *Decl::castToDeclContext(const Decl *D) { 461 Decl::Kind DK = D->getKind(); 462 switch(DK) { 463#define DECL(NAME, BASE) 464#define DECL_CONTEXT(NAME) \ 465 case Decl::NAME: \ 466 return static_cast<NAME##Decl*>(const_cast<Decl*>(D)); 467#define DECL_CONTEXT_BASE(NAME) 468#include "clang/AST/DeclNodes.inc" 469 default: 470#define DECL(NAME, BASE) 471#define DECL_CONTEXT_BASE(NAME) \ 472 if (DK >= first##NAME && DK <= last##NAME) \ 473 return static_cast<NAME##Decl*>(const_cast<Decl*>(D)); 474#include "clang/AST/DeclNodes.inc" 475 assert(false && "a decl that inherits DeclContext isn't handled"); 476 return 0; 477 } 478} 479 480Stmt *Decl::getBody() const { 481 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) 482 return FD->getBody(); 483 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(this)) 484 return MD->getBody(); 485 if (const BlockDecl *BD = dyn_cast<BlockDecl>(this)) 486 return BD->getBody(); 487 488 return 0; 489} 490 491bool Decl::hasBody() const { 492 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) 493 return FD->hasBody(); 494 495 return getBody() != 0; 496} 497 498SourceLocation Decl::getBodyRBrace() const { 499 // Special handling of FunctionDecl to avoid de-serializing the body from PCH. 500 // FunctionDecl stores EndRangeLoc for this purpose. 501 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) { 502 const FunctionDecl *Definition; 503 if (FD->hasBody(Definition)) 504 return Definition->getSourceRange().getEnd(); 505 return SourceLocation(); 506 } 507 508 if (Stmt *Body = getBody()) 509 return Body->getSourceRange().getEnd(); 510 511 return SourceLocation(); 512} 513 514void Decl::CheckAccessDeclContext() const { 515#ifndef NDEBUG 516 // Suppress this check if any of the following hold: 517 // 1. this is the translation unit (and thus has no parent) 518 // 2. this is a template parameter (and thus doesn't belong to its context) 519 // 3. this is a non-type template parameter 520 // 4. the context is not a record 521 // 5. it's invalid 522 // 6. it's a C++0x static_assert. 523 if (isa<TranslationUnitDecl>(this) || 524 isa<TemplateTypeParmDecl>(this) || 525 isa<NonTypeTemplateParmDecl>(this) || 526 !isa<CXXRecordDecl>(getDeclContext()) || 527 isInvalidDecl() || 528 isa<StaticAssertDecl>(this) || 529 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization 530 // as DeclContext (?). 531 isa<ParmVarDecl>(this) || 532 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have 533 // AS_none as access specifier. 534 isa<CXXRecordDecl>(this)) 535 return; 536 537 assert(Access != AS_none && 538 "Access specifier is AS_none inside a record decl"); 539#endif 540} 541 542 543//===----------------------------------------------------------------------===// 544// DeclContext Implementation 545//===----------------------------------------------------------------------===// 546 547bool DeclContext::classof(const Decl *D) { 548 switch (D->getKind()) { 549#define DECL(NAME, BASE) 550#define DECL_CONTEXT(NAME) case Decl::NAME: 551#define DECL_CONTEXT_BASE(NAME) 552#include "clang/AST/DeclNodes.inc" 553 return true; 554 default: 555#define DECL(NAME, BASE) 556#define DECL_CONTEXT_BASE(NAME) \ 557 if (D->getKind() >= Decl::first##NAME && \ 558 D->getKind() <= Decl::last##NAME) \ 559 return true; 560#include "clang/AST/DeclNodes.inc" 561 return false; 562 } 563} 564 565DeclContext::~DeclContext() { } 566 567/// \brief Find the parent context of this context that will be 568/// used for unqualified name lookup. 569/// 570/// Generally, the parent lookup context is the semantic context. However, for 571/// a friend function the parent lookup context is the lexical context, which 572/// is the class in which the friend is declared. 573DeclContext *DeclContext::getLookupParent() { 574 // FIXME: Find a better way to identify friends 575 if (isa<FunctionDecl>(this)) 576 if (getParent()->getRedeclContext()->isFileContext() && 577 getLexicalParent()->getRedeclContext()->isRecord()) 578 return getLexicalParent(); 579 580 return getParent(); 581} 582 583bool DeclContext::isInlineNamespace() const { 584 return isNamespace() && 585 cast<NamespaceDecl>(this)->isInline(); 586} 587 588bool DeclContext::isDependentContext() const { 589 if (isFileContext()) 590 return false; 591 592 if (isa<ClassTemplatePartialSpecializationDecl>(this)) 593 return true; 594 595 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) 596 if (Record->getDescribedClassTemplate()) 597 return true; 598 599 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) { 600 if (Function->getDescribedFunctionTemplate()) 601 return true; 602 603 // Friend function declarations are dependent if their *lexical* 604 // context is dependent. 605 if (cast<Decl>(this)->getFriendObjectKind()) 606 return getLexicalParent()->isDependentContext(); 607 } 608 609 return getParent() && getParent()->isDependentContext(); 610} 611 612bool DeclContext::isTransparentContext() const { 613 if (DeclKind == Decl::Enum) 614 return !cast<EnumDecl>(this)->isScoped(); 615 else if (DeclKind == Decl::LinkageSpec) 616 return true; 617 618 return false; 619} 620 621bool DeclContext::isExternCContext() const { 622 const DeclContext *DC = this; 623 while (DC->DeclKind != Decl::TranslationUnit) { 624 if (DC->DeclKind == Decl::LinkageSpec) 625 return cast<LinkageSpecDecl>(DC)->getLanguage() 626 == LinkageSpecDecl::lang_c; 627 DC = DC->getParent(); 628 } 629 return false; 630} 631 632bool DeclContext::Encloses(const DeclContext *DC) const { 633 if (getPrimaryContext() != this) 634 return getPrimaryContext()->Encloses(DC); 635 636 for (; DC; DC = DC->getParent()) 637 if (DC->getPrimaryContext() == this) 638 return true; 639 return false; 640} 641 642DeclContext *DeclContext::getPrimaryContext() { 643 switch (DeclKind) { 644 case Decl::TranslationUnit: 645 case Decl::LinkageSpec: 646 case Decl::Block: 647 // There is only one DeclContext for these entities. 648 return this; 649 650 case Decl::Namespace: 651 // The original namespace is our primary context. 652 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace(); 653 654 case Decl::ObjCMethod: 655 return this; 656 657 case Decl::ObjCInterface: 658 case Decl::ObjCProtocol: 659 case Decl::ObjCCategory: 660 // FIXME: Can Objective-C interfaces be forward-declared? 661 return this; 662 663 case Decl::ObjCImplementation: 664 case Decl::ObjCCategoryImpl: 665 return this; 666 667 default: 668 if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) { 669 // If this is a tag type that has a definition or is currently 670 // being defined, that definition is our primary context. 671 TagDecl *Tag = cast<TagDecl>(this); 672 assert(isa<TagType>(Tag->TypeForDecl) || 673 isa<InjectedClassNameType>(Tag->TypeForDecl)); 674 675 if (TagDecl *Def = Tag->getDefinition()) 676 return Def; 677 678 if (!isa<InjectedClassNameType>(Tag->TypeForDecl)) { 679 const TagType *TagTy = cast<TagType>(Tag->TypeForDecl); 680 if (TagTy->isBeingDefined()) 681 // FIXME: is it necessarily being defined in the decl 682 // that owns the type? 683 return TagTy->getDecl(); 684 } 685 686 return Tag; 687 } 688 689 assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction && 690 "Unknown DeclContext kind"); 691 return this; 692 } 693} 694 695DeclContext *DeclContext::getNextContext() { 696 switch (DeclKind) { 697 case Decl::Namespace: 698 // Return the next namespace 699 return static_cast<NamespaceDecl*>(this)->getNextNamespace(); 700 701 default: 702 return 0; 703 } 704} 705 706std::pair<Decl *, Decl *> 707DeclContext::BuildDeclChain(const llvm::SmallVectorImpl<Decl*> &Decls) { 708 // Build up a chain of declarations via the Decl::NextDeclInContext field. 709 Decl *FirstNewDecl = 0; 710 Decl *PrevDecl = 0; 711 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 712 Decl *D = Decls[I]; 713 if (PrevDecl) 714 PrevDecl->NextDeclInContext = D; 715 else 716 FirstNewDecl = D; 717 718 PrevDecl = D; 719 } 720 721 return std::make_pair(FirstNewDecl, PrevDecl); 722} 723 724/// \brief Load the declarations within this lexical storage from an 725/// external source. 726void 727DeclContext::LoadLexicalDeclsFromExternalStorage() const { 728 ExternalASTSource *Source = getParentASTContext().getExternalSource(); 729 assert(hasExternalLexicalStorage() && Source && "No external storage?"); 730 731 // Notify that we have a DeclContext that is initializing. 732 ExternalASTSource::Deserializing ADeclContext(Source); 733 734 llvm::SmallVector<Decl*, 64> Decls; 735 if (Source->FindExternalLexicalDecls(this, Decls)) 736 return; 737 738 // There is no longer any lexical storage in this context 739 ExternalLexicalStorage = false; 740 741 if (Decls.empty()) 742 return; 743 744 // We may have already loaded just the fields of this record, in which case 745 // don't add the decls, just replace the FirstDecl/LastDecl chain. 746 if (const RecordDecl *RD = dyn_cast<RecordDecl>(this)) 747 if (RD->LoadedFieldsFromExternalStorage) { 748 llvm::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls); 749 return; 750 } 751 752 // Splice the newly-read declarations into the beginning of the list 753 // of declarations. 754 Decl *ExternalFirst, *ExternalLast; 755 llvm::tie(ExternalFirst, ExternalLast) = BuildDeclChain(Decls); 756 ExternalLast->NextDeclInContext = FirstDecl; 757 FirstDecl = ExternalFirst; 758 if (!LastDecl) 759 LastDecl = ExternalLast; 760} 761 762DeclContext::lookup_result 763ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC, 764 DeclarationName Name) { 765 ASTContext &Context = DC->getParentASTContext(); 766 StoredDeclsMap *Map; 767 if (!(Map = DC->LookupPtr)) 768 Map = DC->CreateStoredDeclsMap(Context); 769 770 StoredDeclsList &List = (*Map)[Name]; 771 assert(List.isNull()); 772 (void) List; 773 774 return DeclContext::lookup_result(); 775} 776 777DeclContext::lookup_result 778ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC, 779 DeclarationName Name, 780 llvm::SmallVectorImpl<NamedDecl*> &Decls) { 781 ASTContext &Context = DC->getParentASTContext();; 782 783 StoredDeclsMap *Map; 784 if (!(Map = DC->LookupPtr)) 785 Map = DC->CreateStoredDeclsMap(Context); 786 787 StoredDeclsList &List = (*Map)[Name]; 788 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 789 if (List.isNull()) 790 List.setOnlyValue(Decls[I]); 791 else 792 List.AddSubsequentDecl(Decls[I]); 793 } 794 795 return List.getLookupResult(); 796} 797 798void ExternalASTSource::MaterializeVisibleDeclsForName(const DeclContext *DC, 799 DeclarationName Name, 800 llvm::SmallVectorImpl<NamedDecl*> &Decls) { 801 assert(DC->LookupPtr); 802 StoredDeclsMap &Map = *DC->LookupPtr; 803 804 // If there's an entry in the table the visible decls for this name have 805 // already been deserialized. 806 if (Map.find(Name) == Map.end()) { 807 StoredDeclsList &List = Map[Name]; 808 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 809 if (List.isNull()) 810 List.setOnlyValue(Decls[I]); 811 else 812 List.AddSubsequentDecl(Decls[I]); 813 } 814 } 815} 816 817DeclContext::decl_iterator DeclContext::noload_decls_begin() const { 818 return decl_iterator(FirstDecl); 819} 820 821DeclContext::decl_iterator DeclContext::noload_decls_end() const { 822 return decl_iterator(); 823} 824 825DeclContext::decl_iterator DeclContext::decls_begin() const { 826 if (hasExternalLexicalStorage()) 827 LoadLexicalDeclsFromExternalStorage(); 828 829 // FIXME: Check whether we need to load some declarations from 830 // external storage. 831 return decl_iterator(FirstDecl); 832} 833 834DeclContext::decl_iterator DeclContext::decls_end() const { 835 if (hasExternalLexicalStorage()) 836 LoadLexicalDeclsFromExternalStorage(); 837 838 return decl_iterator(); 839} 840 841bool DeclContext::decls_empty() const { 842 if (hasExternalLexicalStorage()) 843 LoadLexicalDeclsFromExternalStorage(); 844 845 return !FirstDecl; 846} 847 848void DeclContext::removeDecl(Decl *D) { 849 assert(D->getLexicalDeclContext() == this && 850 "decl being removed from non-lexical context"); 851 assert((D->NextDeclInContext || D == LastDecl) && 852 "decl is not in decls list"); 853 854 // Remove D from the decl chain. This is O(n) but hopefully rare. 855 if (D == FirstDecl) { 856 if (D == LastDecl) 857 FirstDecl = LastDecl = 0; 858 else 859 FirstDecl = D->NextDeclInContext; 860 } else { 861 for (Decl *I = FirstDecl; true; I = I->NextDeclInContext) { 862 assert(I && "decl not found in linked list"); 863 if (I->NextDeclInContext == D) { 864 I->NextDeclInContext = D->NextDeclInContext; 865 if (D == LastDecl) LastDecl = I; 866 break; 867 } 868 } 869 } 870 871 // Mark that D is no longer in the decl chain. 872 D->NextDeclInContext = 0; 873 874 // Remove D from the lookup table if necessary. 875 if (isa<NamedDecl>(D)) { 876 NamedDecl *ND = cast<NamedDecl>(D); 877 878 StoredDeclsMap *Map = getPrimaryContext()->LookupPtr; 879 if (!Map) return; 880 881 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName()); 882 assert(Pos != Map->end() && "no lookup entry for decl"); 883 Pos->second.remove(ND); 884 } 885} 886 887void DeclContext::addHiddenDecl(Decl *D) { 888 assert(D->getLexicalDeclContext() == this && 889 "Decl inserted into wrong lexical context"); 890 assert(!D->getNextDeclInContext() && D != LastDecl && 891 "Decl already inserted into a DeclContext"); 892 893 if (FirstDecl) { 894 LastDecl->NextDeclInContext = D; 895 LastDecl = D; 896 } else { 897 FirstDecl = LastDecl = D; 898 } 899 900 // Notify a C++ record declaration that we've added a member, so it can 901 // update it's class-specific state. 902 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) 903 Record->addedMember(D); 904} 905 906void DeclContext::addDecl(Decl *D) { 907 addHiddenDecl(D); 908 909 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) 910 ND->getDeclContext()->makeDeclVisibleInContext(ND); 911} 912 913/// buildLookup - Build the lookup data structure with all of the 914/// declarations in DCtx (and any other contexts linked to it or 915/// transparent contexts nested within it). 916void DeclContext::buildLookup(DeclContext *DCtx) { 917 for (; DCtx; DCtx = DCtx->getNextContext()) { 918 for (decl_iterator D = DCtx->decls_begin(), 919 DEnd = DCtx->decls_end(); 920 D != DEnd; ++D) { 921 // Insert this declaration into the lookup structure, but only 922 // if it's semantically in its decl context. During non-lazy 923 // lookup building, this is implicitly enforced by addDecl. 924 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D)) 925 if (D->getDeclContext() == DCtx) 926 makeDeclVisibleInContextImpl(ND); 927 928 // Insert any forward-declared Objective-C interfaces into the lookup 929 // data structure. 930 if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(*D)) 931 for (ObjCClassDecl::iterator I = Class->begin(), IEnd = Class->end(); 932 I != IEnd; ++I) 933 makeDeclVisibleInContextImpl(I->getInterface()); 934 935 // If this declaration is itself a transparent declaration context or 936 // inline namespace, add its members (recursively). 937 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) 938 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace()) 939 buildLookup(InnerCtx->getPrimaryContext()); 940 } 941 } 942} 943 944DeclContext::lookup_result 945DeclContext::lookup(DeclarationName Name) { 946 DeclContext *PrimaryContext = getPrimaryContext(); 947 if (PrimaryContext != this) 948 return PrimaryContext->lookup(Name); 949 950 if (hasExternalVisibleStorage()) { 951 // Check to see if we've already cached the lookup results. 952 if (LookupPtr) { 953 StoredDeclsMap::iterator I = LookupPtr->find(Name); 954 if (I != LookupPtr->end()) 955 return I->second.getLookupResult(); 956 } 957 958 ExternalASTSource *Source = getParentASTContext().getExternalSource(); 959 return Source->FindExternalVisibleDeclsByName(this, Name); 960 } 961 962 /// If there is no lookup data structure, build one now by walking 963 /// all of the linked DeclContexts (in declaration order!) and 964 /// inserting their values. 965 if (!LookupPtr) { 966 buildLookup(this); 967 968 if (!LookupPtr) 969 return lookup_result(lookup_iterator(0), lookup_iterator(0)); 970 } 971 972 StoredDeclsMap::iterator Pos = LookupPtr->find(Name); 973 if (Pos == LookupPtr->end()) 974 return lookup_result(lookup_iterator(0), lookup_iterator(0)); 975 return Pos->second.getLookupResult(); 976} 977 978DeclContext::lookup_const_result 979DeclContext::lookup(DeclarationName Name) const { 980 return const_cast<DeclContext*>(this)->lookup(Name); 981} 982 983DeclContext *DeclContext::getRedeclContext() { 984 DeclContext *Ctx = this; 985 // Skip through transparent contexts. 986 while (Ctx->isTransparentContext()) 987 Ctx = Ctx->getParent(); 988 return Ctx; 989} 990 991DeclContext *DeclContext::getEnclosingNamespaceContext() { 992 DeclContext *Ctx = this; 993 // Skip through non-namespace, non-translation-unit contexts. 994 while (!Ctx->isFileContext()) 995 Ctx = Ctx->getParent(); 996 return Ctx->getPrimaryContext(); 997} 998 999bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const { 1000 // For non-file contexts, this is equivalent to Equals. 1001 if (!isFileContext()) 1002 return O->Equals(this); 1003 1004 do { 1005 if (O->Equals(this)) 1006 return true; 1007 1008 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O); 1009 if (!NS || !NS->isInline()) 1010 break; 1011 O = NS->getParent(); 1012 } while (O); 1013 1014 return false; 1015} 1016 1017void DeclContext::makeDeclVisibleInContext(NamedDecl *D, bool Recoverable) { 1018 // FIXME: This feels like a hack. Should DeclarationName support 1019 // template-ids, or is there a better way to keep specializations 1020 // from being visible? 1021 if (isa<ClassTemplateSpecializationDecl>(D)) 1022 return; 1023 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 1024 if (FD->isFunctionTemplateSpecialization()) 1025 return; 1026 1027 DeclContext *PrimaryContext = getPrimaryContext(); 1028 if (PrimaryContext != this) { 1029 PrimaryContext->makeDeclVisibleInContext(D, Recoverable); 1030 return; 1031 } 1032 1033 // If we already have a lookup data structure, perform the insertion 1034 // into it. If we haven't deserialized externally stored decls, deserialize 1035 // them so we can add the decl. Otherwise, be lazy and don't build that 1036 // structure until someone asks for it. 1037 if (LookupPtr || !Recoverable || hasExternalVisibleStorage()) 1038 makeDeclVisibleInContextImpl(D); 1039 1040 // If we are a transparent context or inline namespace, insert into our 1041 // parent context, too. This operation is recursive. 1042 if (isTransparentContext() || isInlineNamespace()) 1043 getParent()->makeDeclVisibleInContext(D, Recoverable); 1044 1045 Decl *DCAsDecl = cast<Decl>(this); 1046 // Notify that a decl was made visible unless it's a Tag being defined. 1047 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined())) 1048 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener()) 1049 L->AddedVisibleDecl(this, D); 1050} 1051 1052void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D) { 1053 // Skip unnamed declarations. 1054 if (!D->getDeclName()) 1055 return; 1056 1057 // FIXME: This feels like a hack. Should DeclarationName support 1058 // template-ids, or is there a better way to keep specializations 1059 // from being visible? 1060 if (isa<ClassTemplateSpecializationDecl>(D)) 1061 return; 1062 1063 ASTContext *C = 0; 1064 if (!LookupPtr) { 1065 C = &getParentASTContext(); 1066 CreateStoredDeclsMap(*C); 1067 } 1068 1069 // If there is an external AST source, load any declarations it knows about 1070 // with this declaration's name. 1071 // If the lookup table contains an entry about this name it means that we 1072 // have already checked the external source. 1073 if (ExternalASTSource *Source = getParentASTContext().getExternalSource()) 1074 if (hasExternalVisibleStorage() && 1075 LookupPtr->find(D->getDeclName()) == LookupPtr->end()) 1076 Source->FindExternalVisibleDeclsByName(this, D->getDeclName()); 1077 1078 // Insert this declaration into the map. 1079 StoredDeclsList &DeclNameEntries = (*LookupPtr)[D->getDeclName()]; 1080 if (DeclNameEntries.isNull()) { 1081 DeclNameEntries.setOnlyValue(D); 1082 return; 1083 } 1084 1085 // If it is possible that this is a redeclaration, check to see if there is 1086 // already a decl for which declarationReplaces returns true. If there is 1087 // one, just replace it and return. 1088 if (DeclNameEntries.HandleRedeclaration(D)) 1089 return; 1090 1091 // Put this declaration into the appropriate slot. 1092 DeclNameEntries.AddSubsequentDecl(D); 1093} 1094 1095void DeclContext::MaterializeVisibleDeclsFromExternalStorage() { 1096 ExternalASTSource *Source = getParentASTContext().getExternalSource(); 1097 assert(hasExternalVisibleStorage() && Source && "No external storage?"); 1098 1099 if (!LookupPtr) 1100 CreateStoredDeclsMap(getParentASTContext()); 1101 Source->MaterializeVisibleDecls(this); 1102} 1103 1104/// Returns iterator range [First, Last) of UsingDirectiveDecls stored within 1105/// this context. 1106DeclContext::udir_iterator_range 1107DeclContext::getUsingDirectives() const { 1108 lookup_const_result Result = lookup(UsingDirectiveDecl::getName()); 1109 return udir_iterator_range(reinterpret_cast<udir_iterator>(Result.first), 1110 reinterpret_cast<udir_iterator>(Result.second)); 1111} 1112 1113//===----------------------------------------------------------------------===// 1114// Creation and Destruction of StoredDeclsMaps. // 1115//===----------------------------------------------------------------------===// 1116 1117StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const { 1118 assert(!LookupPtr && "context already has a decls map"); 1119 assert(getPrimaryContext() == this && 1120 "creating decls map on non-primary context"); 1121 1122 StoredDeclsMap *M; 1123 bool Dependent = isDependentContext(); 1124 if (Dependent) 1125 M = new DependentStoredDeclsMap(); 1126 else 1127 M = new StoredDeclsMap(); 1128 M->Previous = C.LastSDM; 1129 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent); 1130 LookupPtr = M; 1131 return M; 1132} 1133 1134void ASTContext::ReleaseDeclContextMaps() { 1135 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap 1136 // pointer because the subclass doesn't add anything that needs to 1137 // be deleted. 1138 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt()); 1139} 1140 1141void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) { 1142 while (Map) { 1143 // Advance the iteration before we invalidate memory. 1144 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous; 1145 1146 if (Dependent) 1147 delete static_cast<DependentStoredDeclsMap*>(Map); 1148 else 1149 delete Map; 1150 1151 Map = Next.getPointer(); 1152 Dependent = Next.getInt(); 1153 } 1154} 1155 1156DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C, 1157 DeclContext *Parent, 1158 const PartialDiagnostic &PDiag) { 1159 assert(Parent->isDependentContext() 1160 && "cannot iterate dependent diagnostics of non-dependent context"); 1161 Parent = Parent->getPrimaryContext(); 1162 if (!Parent->LookupPtr) 1163 Parent->CreateStoredDeclsMap(C); 1164 1165 DependentStoredDeclsMap *Map 1166 = static_cast<DependentStoredDeclsMap*>(Parent->LookupPtr); 1167 1168 // Allocate the copy of the PartialDiagnostic via the ASTContext's 1169 // BumpPtrAllocator, rather than the ASTContext itself. 1170 PartialDiagnostic::Storage *DiagStorage = 0; 1171 if (PDiag.hasStorage()) 1172 DiagStorage = new (C) PartialDiagnostic::Storage; 1173 1174 DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage); 1175 1176 // TODO: Maybe we shouldn't reverse the order during insertion. 1177 DD->NextDiagnostic = Map->FirstDiagnostic; 1178 Map->FirstDiagnostic = DD; 1179 1180 return DD; 1181} 1182