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