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