DeclBase.cpp revision 02368d0d1a778b73fd73600496fcde4557b2973f
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 isa<ClassScopeFunctionSpecializationDecl>(this)) 633 return; 634 635 assert(Access != AS_none && 636 "Access specifier is AS_none inside a record decl"); 637#endif 638} 639 640DeclContext *Decl::getNonClosureContext() { 641 DeclContext *DC = getDeclContext(); 642 643 // This is basically "while (DC->isClosure()) DC = DC->getParent();" 644 // except that it's significantly more efficient to cast to a known 645 // decl type and call getDeclContext() than to call getParent(). 646 while (isa<BlockDecl>(DC)) 647 DC = cast<BlockDecl>(DC)->getDeclContext(); 648 649 assert(!DC->isClosure()); 650 return DC; 651} 652 653//===----------------------------------------------------------------------===// 654// DeclContext Implementation 655//===----------------------------------------------------------------------===// 656 657bool DeclContext::classof(const Decl *D) { 658 switch (D->getKind()) { 659#define DECL(NAME, BASE) 660#define DECL_CONTEXT(NAME) case Decl::NAME: 661#define DECL_CONTEXT_BASE(NAME) 662#include "clang/AST/DeclNodes.inc" 663 return true; 664 default: 665#define DECL(NAME, BASE) 666#define DECL_CONTEXT_BASE(NAME) \ 667 if (D->getKind() >= Decl::first##NAME && \ 668 D->getKind() <= Decl::last##NAME) \ 669 return true; 670#include "clang/AST/DeclNodes.inc" 671 return false; 672 } 673} 674 675DeclContext::~DeclContext() { } 676 677/// \brief Find the parent context of this context that will be 678/// used for unqualified name lookup. 679/// 680/// Generally, the parent lookup context is the semantic context. However, for 681/// a friend function the parent lookup context is the lexical context, which 682/// is the class in which the friend is declared. 683DeclContext *DeclContext::getLookupParent() { 684 // FIXME: Find a better way to identify friends 685 if (isa<FunctionDecl>(this)) 686 if (getParent()->getRedeclContext()->isFileContext() && 687 getLexicalParent()->getRedeclContext()->isRecord()) 688 return getLexicalParent(); 689 690 return getParent(); 691} 692 693bool DeclContext::isInlineNamespace() const { 694 return isNamespace() && 695 cast<NamespaceDecl>(this)->isInline(); 696} 697 698bool DeclContext::isDependentContext() const { 699 if (isFileContext()) 700 return false; 701 702 if (isa<ClassTemplatePartialSpecializationDecl>(this)) 703 return true; 704 705 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) 706 if (Record->getDescribedClassTemplate()) 707 return true; 708 709 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) { 710 if (Function->getDescribedFunctionTemplate()) 711 return true; 712 713 // Friend function declarations are dependent if their *lexical* 714 // context is dependent. 715 if (cast<Decl>(this)->getFriendObjectKind()) 716 return getLexicalParent()->isDependentContext(); 717 } 718 719 return getParent() && getParent()->isDependentContext(); 720} 721 722bool DeclContext::isTransparentContext() const { 723 if (DeclKind == Decl::Enum) 724 return !cast<EnumDecl>(this)->isScoped(); 725 else if (DeclKind == Decl::LinkageSpec) 726 return true; 727 728 return false; 729} 730 731bool DeclContext::isExternCContext() const { 732 const DeclContext *DC = this; 733 while (DC->DeclKind != Decl::TranslationUnit) { 734 if (DC->DeclKind == Decl::LinkageSpec) 735 return cast<LinkageSpecDecl>(DC)->getLanguage() 736 == LinkageSpecDecl::lang_c; 737 DC = DC->getParent(); 738 } 739 return false; 740} 741 742bool DeclContext::Encloses(const DeclContext *DC) const { 743 if (getPrimaryContext() != this) 744 return getPrimaryContext()->Encloses(DC); 745 746 for (; DC; DC = DC->getParent()) 747 if (DC->getPrimaryContext() == this) 748 return true; 749 return false; 750} 751 752DeclContext *DeclContext::getPrimaryContext() { 753 switch (DeclKind) { 754 case Decl::TranslationUnit: 755 case Decl::LinkageSpec: 756 case Decl::Block: 757 // There is only one DeclContext for these entities. 758 return this; 759 760 case Decl::Namespace: 761 // The original namespace is our primary context. 762 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace(); 763 764 case Decl::ObjCMethod: 765 return this; 766 767 case Decl::ObjCInterface: 768 case Decl::ObjCProtocol: 769 case Decl::ObjCCategory: 770 // FIXME: Can Objective-C interfaces be forward-declared? 771 return this; 772 773 case Decl::ObjCImplementation: 774 case Decl::ObjCCategoryImpl: 775 return this; 776 777 default: 778 if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) { 779 // If this is a tag type that has a definition or is currently 780 // being defined, that definition is our primary context. 781 TagDecl *Tag = cast<TagDecl>(this); 782 assert(isa<TagType>(Tag->TypeForDecl) || 783 isa<InjectedClassNameType>(Tag->TypeForDecl)); 784 785 if (TagDecl *Def = Tag->getDefinition()) 786 return Def; 787 788 if (!isa<InjectedClassNameType>(Tag->TypeForDecl)) { 789 const TagType *TagTy = cast<TagType>(Tag->TypeForDecl); 790 if (TagTy->isBeingDefined()) 791 // FIXME: is it necessarily being defined in the decl 792 // that owns the type? 793 return TagTy->getDecl(); 794 } 795 796 return Tag; 797 } 798 799 assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction && 800 "Unknown DeclContext kind"); 801 return this; 802 } 803} 804 805DeclContext *DeclContext::getNextContext() { 806 switch (DeclKind) { 807 case Decl::Namespace: 808 // Return the next namespace 809 return static_cast<NamespaceDecl*>(this)->getNextNamespace(); 810 811 default: 812 return 0; 813 } 814} 815 816std::pair<Decl *, Decl *> 817DeclContext::BuildDeclChain(const SmallVectorImpl<Decl*> &Decls) { 818 // Build up a chain of declarations via the Decl::NextDeclInContext field. 819 Decl *FirstNewDecl = 0; 820 Decl *PrevDecl = 0; 821 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 822 Decl *D = Decls[I]; 823 if (PrevDecl) 824 PrevDecl->NextDeclInContext = D; 825 else 826 FirstNewDecl = D; 827 828 PrevDecl = D; 829 } 830 831 return std::make_pair(FirstNewDecl, PrevDecl); 832} 833 834/// \brief Load the declarations within this lexical storage from an 835/// external source. 836void 837DeclContext::LoadLexicalDeclsFromExternalStorage() const { 838 ExternalASTSource *Source = getParentASTContext().getExternalSource(); 839 assert(hasExternalLexicalStorage() && Source && "No external storage?"); 840 841 // Notify that we have a DeclContext that is initializing. 842 ExternalASTSource::Deserializing ADeclContext(Source); 843 844 // Load the external declarations, if any. 845 SmallVector<Decl*, 64> Decls; 846 ExternalLexicalStorage = false; 847 switch (Source->FindExternalLexicalDecls(this, Decls)) { 848 case ELR_Success: 849 break; 850 851 case ELR_Failure: 852 case ELR_AlreadyLoaded: 853 return; 854 } 855 856 if (Decls.empty()) 857 return; 858 859 // We may have already loaded just the fields of this record, in which case 860 // don't add the decls, just replace the FirstDecl/LastDecl chain. 861 if (const RecordDecl *RD = dyn_cast<RecordDecl>(this)) 862 if (RD->LoadedFieldsFromExternalStorage) { 863 llvm::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls); 864 return; 865 } 866 867 // Splice the newly-read declarations into the beginning of the list 868 // of declarations. 869 Decl *ExternalFirst, *ExternalLast; 870 llvm::tie(ExternalFirst, ExternalLast) = BuildDeclChain(Decls); 871 ExternalLast->NextDeclInContext = FirstDecl; 872 FirstDecl = ExternalFirst; 873 if (!LastDecl) 874 LastDecl = ExternalLast; 875} 876 877DeclContext::lookup_result 878ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC, 879 DeclarationName Name) { 880 ASTContext &Context = DC->getParentASTContext(); 881 StoredDeclsMap *Map; 882 if (!(Map = DC->LookupPtr)) 883 Map = DC->CreateStoredDeclsMap(Context); 884 885 StoredDeclsList &List = (*Map)[Name]; 886 assert(List.isNull()); 887 (void) List; 888 889 return DeclContext::lookup_result(); 890} 891 892DeclContext::lookup_result 893ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC, 894 DeclarationName Name, 895 SmallVectorImpl<NamedDecl*> &Decls) { 896 ASTContext &Context = DC->getParentASTContext();; 897 898 StoredDeclsMap *Map; 899 if (!(Map = DC->LookupPtr)) 900 Map = DC->CreateStoredDeclsMap(Context); 901 902 StoredDeclsList &List = (*Map)[Name]; 903 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 904 if (List.isNull()) 905 List.setOnlyValue(Decls[I]); 906 else 907 List.AddSubsequentDecl(Decls[I]); 908 } 909 910 return List.getLookupResult(); 911} 912 913DeclContext::decl_iterator DeclContext::noload_decls_begin() const { 914 return decl_iterator(FirstDecl); 915} 916 917DeclContext::decl_iterator DeclContext::noload_decls_end() const { 918 return decl_iterator(); 919} 920 921DeclContext::decl_iterator DeclContext::decls_begin() const { 922 if (hasExternalLexicalStorage()) 923 LoadLexicalDeclsFromExternalStorage(); 924 925 return decl_iterator(FirstDecl); 926} 927 928DeclContext::decl_iterator DeclContext::decls_end() const { 929 if (hasExternalLexicalStorage()) 930 LoadLexicalDeclsFromExternalStorage(); 931 932 return decl_iterator(); 933} 934 935bool DeclContext::decls_empty() const { 936 if (hasExternalLexicalStorage()) 937 LoadLexicalDeclsFromExternalStorage(); 938 939 return !FirstDecl; 940} 941 942void DeclContext::removeDecl(Decl *D) { 943 assert(D->getLexicalDeclContext() == this && 944 "decl being removed from non-lexical context"); 945 assert((D->NextDeclInContext || D == LastDecl) && 946 "decl is not in decls list"); 947 948 // Remove D from the decl chain. This is O(n) but hopefully rare. 949 if (D == FirstDecl) { 950 if (D == LastDecl) 951 FirstDecl = LastDecl = 0; 952 else 953 FirstDecl = D->NextDeclInContext; 954 } else { 955 for (Decl *I = FirstDecl; true; I = I->NextDeclInContext) { 956 assert(I && "decl not found in linked list"); 957 if (I->NextDeclInContext == D) { 958 I->NextDeclInContext = D->NextDeclInContext; 959 if (D == LastDecl) LastDecl = I; 960 break; 961 } 962 } 963 } 964 965 // Mark that D is no longer in the decl chain. 966 D->NextDeclInContext = 0; 967 968 // Remove D from the lookup table if necessary. 969 if (isa<NamedDecl>(D)) { 970 NamedDecl *ND = cast<NamedDecl>(D); 971 972 // Remove only decls that have a name 973 if (!ND->getDeclName()) return; 974 975 StoredDeclsMap *Map = getPrimaryContext()->LookupPtr; 976 if (!Map) return; 977 978 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName()); 979 assert(Pos != Map->end() && "no lookup entry for decl"); 980 Pos->second.remove(ND); 981 } 982} 983 984void DeclContext::addHiddenDecl(Decl *D) { 985 assert(D->getLexicalDeclContext() == this && 986 "Decl inserted into wrong lexical context"); 987 assert(!D->getNextDeclInContext() && D != LastDecl && 988 "Decl already inserted into a DeclContext"); 989 990 if (FirstDecl) { 991 LastDecl->NextDeclInContext = D; 992 LastDecl = D; 993 } else { 994 FirstDecl = LastDecl = D; 995 } 996 997 // Notify a C++ record declaration that we've added a member, so it can 998 // update it's class-specific state. 999 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) 1000 Record->addedMember(D); 1001} 1002 1003void DeclContext::addDecl(Decl *D) { 1004 addHiddenDecl(D); 1005 1006 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) 1007 ND->getDeclContext()->makeDeclVisibleInContext(ND); 1008} 1009 1010/// buildLookup - Build the lookup data structure with all of the 1011/// declarations in DCtx (and any other contexts linked to it or 1012/// transparent contexts nested within it). 1013void DeclContext::buildLookup(DeclContext *DCtx) { 1014 for (; DCtx; DCtx = DCtx->getNextContext()) { 1015 for (decl_iterator D = DCtx->decls_begin(), 1016 DEnd = DCtx->decls_end(); 1017 D != DEnd; ++D) { 1018 // Insert this declaration into the lookup structure, but only 1019 // if it's semantically in its decl context. During non-lazy 1020 // lookup building, this is implicitly enforced by addDecl. 1021 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D)) 1022 if (D->getDeclContext() == DCtx) 1023 makeDeclVisibleInContextImpl(ND); 1024 1025 // Insert any forward-declared Objective-C interfaces into the lookup 1026 // data structure. 1027 if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(*D)) 1028 for (ObjCClassDecl::iterator I = Class->begin(), IEnd = Class->end(); 1029 I != IEnd; ++I) 1030 makeDeclVisibleInContextImpl(I->getInterface()); 1031 1032 // If this declaration is itself a transparent declaration context or 1033 // inline namespace, add its members (recursively). 1034 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) 1035 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace()) 1036 buildLookup(InnerCtx->getPrimaryContext()); 1037 } 1038 } 1039} 1040 1041DeclContext::lookup_result 1042DeclContext::lookup(DeclarationName Name) { 1043 DeclContext *PrimaryContext = getPrimaryContext(); 1044 if (PrimaryContext != this) 1045 return PrimaryContext->lookup(Name); 1046 1047 if (hasExternalVisibleStorage()) { 1048 // Check to see if we've already cached the lookup results. 1049 if (LookupPtr) { 1050 StoredDeclsMap::iterator I = LookupPtr->find(Name); 1051 if (I != LookupPtr->end()) 1052 return I->second.getLookupResult(); 1053 } 1054 1055 ExternalASTSource *Source = getParentASTContext().getExternalSource(); 1056 return Source->FindExternalVisibleDeclsByName(this, Name); 1057 } 1058 1059 /// If there is no lookup data structure, build one now by walking 1060 /// all of the linked DeclContexts (in declaration order!) and 1061 /// inserting their values. 1062 if (!LookupPtr) { 1063 buildLookup(this); 1064 1065 if (!LookupPtr) 1066 return lookup_result(lookup_iterator(0), lookup_iterator(0)); 1067 } 1068 1069 StoredDeclsMap::iterator Pos = LookupPtr->find(Name); 1070 if (Pos == LookupPtr->end()) 1071 return lookup_result(lookup_iterator(0), lookup_iterator(0)); 1072 return Pos->second.getLookupResult(); 1073} 1074 1075DeclContext::lookup_const_result 1076DeclContext::lookup(DeclarationName Name) const { 1077 return const_cast<DeclContext*>(this)->lookup(Name); 1078} 1079 1080DeclContext *DeclContext::getRedeclContext() { 1081 DeclContext *Ctx = this; 1082 // Skip through transparent contexts. 1083 while (Ctx->isTransparentContext()) 1084 Ctx = Ctx->getParent(); 1085 return Ctx; 1086} 1087 1088DeclContext *DeclContext::getEnclosingNamespaceContext() { 1089 DeclContext *Ctx = this; 1090 // Skip through non-namespace, non-translation-unit contexts. 1091 while (!Ctx->isFileContext()) 1092 Ctx = Ctx->getParent(); 1093 return Ctx->getPrimaryContext(); 1094} 1095 1096bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const { 1097 // For non-file contexts, this is equivalent to Equals. 1098 if (!isFileContext()) 1099 return O->Equals(this); 1100 1101 do { 1102 if (O->Equals(this)) 1103 return true; 1104 1105 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O); 1106 if (!NS || !NS->isInline()) 1107 break; 1108 O = NS->getParent(); 1109 } while (O); 1110 1111 return false; 1112} 1113 1114void DeclContext::makeDeclVisibleInContext(NamedDecl *D, bool Recoverable) { 1115 // FIXME: This feels like a hack. Should DeclarationName support 1116 // template-ids, or is there a better way to keep specializations 1117 // from being visible? 1118 if (isa<ClassTemplateSpecializationDecl>(D) || D->isTemplateParameter()) 1119 return; 1120 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 1121 if (FD->isFunctionTemplateSpecialization()) 1122 return; 1123 1124 DeclContext *PrimaryContext = getPrimaryContext(); 1125 if (PrimaryContext != this) { 1126 PrimaryContext->makeDeclVisibleInContext(D, Recoverable); 1127 return; 1128 } 1129 1130 // If we already have a lookup data structure, perform the insertion 1131 // into it. If we haven't deserialized externally stored decls, deserialize 1132 // them so we can add the decl. Otherwise, be lazy and don't build that 1133 // structure until someone asks for it. 1134 if (LookupPtr || !Recoverable || hasExternalVisibleStorage()) 1135 makeDeclVisibleInContextImpl(D); 1136 1137 // If we are a transparent context or inline namespace, insert into our 1138 // parent context, too. This operation is recursive. 1139 if (isTransparentContext() || isInlineNamespace()) 1140 getParent()->makeDeclVisibleInContext(D, Recoverable); 1141 1142 Decl *DCAsDecl = cast<Decl>(this); 1143 // Notify that a decl was made visible unless it's a Tag being defined. 1144 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined())) 1145 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener()) 1146 L->AddedVisibleDecl(this, D); 1147} 1148 1149void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D) { 1150 // Skip unnamed declarations. 1151 if (!D->getDeclName()) 1152 return; 1153 1154 // Skip entities that can't be found by name lookup into a particular 1155 // context. 1156 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) || 1157 D->isTemplateParameter()) 1158 return; 1159 1160 ASTContext *C = 0; 1161 if (!LookupPtr) { 1162 C = &getParentASTContext(); 1163 CreateStoredDeclsMap(*C); 1164 } 1165 1166 // If there is an external AST source, load any declarations it knows about 1167 // with this declaration's name. 1168 // If the lookup table contains an entry about this name it means that we 1169 // have already checked the external source. 1170 if (ExternalASTSource *Source = getParentASTContext().getExternalSource()) 1171 if (hasExternalVisibleStorage() && 1172 LookupPtr->find(D->getDeclName()) == LookupPtr->end()) 1173 Source->FindExternalVisibleDeclsByName(this, D->getDeclName()); 1174 1175 // Insert this declaration into the map. 1176 StoredDeclsList &DeclNameEntries = (*LookupPtr)[D->getDeclName()]; 1177 if (DeclNameEntries.isNull()) { 1178 DeclNameEntries.setOnlyValue(D); 1179 return; 1180 } 1181 1182 // If it is possible that this is a redeclaration, check to see if there is 1183 // already a decl for which declarationReplaces returns true. If there is 1184 // one, just replace it and return. 1185 if (DeclNameEntries.HandleRedeclaration(D)) 1186 return; 1187 1188 // Put this declaration into the appropriate slot. 1189 DeclNameEntries.AddSubsequentDecl(D); 1190} 1191 1192/// Returns iterator range [First, Last) of UsingDirectiveDecls stored within 1193/// this context. 1194DeclContext::udir_iterator_range 1195DeclContext::getUsingDirectives() const { 1196 lookup_const_result Result = lookup(UsingDirectiveDecl::getName()); 1197 return udir_iterator_range(reinterpret_cast<udir_iterator>(Result.first), 1198 reinterpret_cast<udir_iterator>(Result.second)); 1199} 1200 1201//===----------------------------------------------------------------------===// 1202// Creation and Destruction of StoredDeclsMaps. // 1203//===----------------------------------------------------------------------===// 1204 1205StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const { 1206 assert(!LookupPtr && "context already has a decls map"); 1207 assert(getPrimaryContext() == this && 1208 "creating decls map on non-primary context"); 1209 1210 StoredDeclsMap *M; 1211 bool Dependent = isDependentContext(); 1212 if (Dependent) 1213 M = new DependentStoredDeclsMap(); 1214 else 1215 M = new StoredDeclsMap(); 1216 M->Previous = C.LastSDM; 1217 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent); 1218 LookupPtr = M; 1219 return M; 1220} 1221 1222void ASTContext::ReleaseDeclContextMaps() { 1223 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap 1224 // pointer because the subclass doesn't add anything that needs to 1225 // be deleted. 1226 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt()); 1227} 1228 1229void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) { 1230 while (Map) { 1231 // Advance the iteration before we invalidate memory. 1232 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous; 1233 1234 if (Dependent) 1235 delete static_cast<DependentStoredDeclsMap*>(Map); 1236 else 1237 delete Map; 1238 1239 Map = Next.getPointer(); 1240 Dependent = Next.getInt(); 1241 } 1242} 1243 1244DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C, 1245 DeclContext *Parent, 1246 const PartialDiagnostic &PDiag) { 1247 assert(Parent->isDependentContext() 1248 && "cannot iterate dependent diagnostics of non-dependent context"); 1249 Parent = Parent->getPrimaryContext(); 1250 if (!Parent->LookupPtr) 1251 Parent->CreateStoredDeclsMap(C); 1252 1253 DependentStoredDeclsMap *Map 1254 = static_cast<DependentStoredDeclsMap*>(Parent->LookupPtr); 1255 1256 // Allocate the copy of the PartialDiagnostic via the ASTContext's 1257 // BumpPtrAllocator, rather than the ASTContext itself. 1258 PartialDiagnostic::Storage *DiagStorage = 0; 1259 if (PDiag.hasStorage()) 1260 DiagStorage = new (C) PartialDiagnostic::Storage; 1261 1262 DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage); 1263 1264 // TODO: Maybe we shouldn't reverse the order during insertion. 1265 DD->NextDiagnostic = Map->FirstDiagnostic; 1266 Map->FirstDiagnostic = DD; 1267 1268 return DD; 1269} 1270