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