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/ASTContext.h" 16 #include "clang/AST/ASTMutationListener.h" 17 #include "clang/AST/Attr.h" 18 #include "clang/AST/Decl.h" 19 #include "clang/AST/DeclCXX.h" 20 #include "clang/AST/DeclContextInternals.h" 21 #include "clang/AST/DeclFriend.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclOpenMP.h" 24 #include "clang/AST/DeclTemplate.h" 25 #include "clang/AST/DependentDiagnostic.h" 26 #include "clang/AST/ExternalASTSource.h" 27 #include "clang/AST/Stmt.h" 28 #include "clang/AST/StmtCXX.h" 29 #include "clang/AST/Type.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "llvm/ADT/DenseMap.h" 32 #include "llvm/Support/raw_ostream.h" 33 #include <algorithm> 34 using namespace clang; 35 36 //===----------------------------------------------------------------------===// 37 // Statistics 38 //===----------------------------------------------------------------------===// 39 40 #define DECL(DERIVED, BASE) static int n##DERIVED##s = 0; 41 #define ABSTRACT_DECL(DECL) 42 #include "clang/AST/DeclNodes.inc" 43 44 void Decl::updateOutOfDate(IdentifierInfo &II) const { 45 getASTContext().getExternalSource()->updateOutOfDateIdentifier(II); 46 } 47 48 #define DECL(DERIVED, BASE) \ 49 static_assert(Decl::DeclObjAlignment >= \ 50 llvm::AlignOf<DERIVED##Decl>::Alignment, \ 51 "Alignment sufficient after objects prepended to " #DERIVED); 52 #define ABSTRACT_DECL(DECL) 53 #include "clang/AST/DeclNodes.inc" 54 55 void *Decl::operator new(std::size_t Size, const ASTContext &Context, 56 unsigned ID, std::size_t Extra) { 57 // Allocate an extra 8 bytes worth of storage, which ensures that the 58 // resulting pointer will still be 8-byte aligned. 59 static_assert(sizeof(unsigned) * 2 >= DeclObjAlignment, 60 "Decl won't be misaligned"); 61 void *Start = Context.Allocate(Size + Extra + 8); 62 void *Result = (char*)Start + 8; 63 64 unsigned *PrefixPtr = (unsigned *)Result - 2; 65 66 // Zero out the first 4 bytes; this is used to store the owning module ID. 67 PrefixPtr[0] = 0; 68 69 // Store the global declaration ID in the second 4 bytes. 70 PrefixPtr[1] = ID; 71 72 return Result; 73 } 74 75 void *Decl::operator new(std::size_t Size, const ASTContext &Ctx, 76 DeclContext *Parent, std::size_t Extra) { 77 assert(!Parent || &Parent->getParentASTContext() == &Ctx); 78 // With local visibility enabled, we track the owning module even for local 79 // declarations. 80 if (Ctx.getLangOpts().ModulesLocalVisibility) { 81 // Ensure required alignment of the resulting object by adding extra 82 // padding at the start if required. 83 size_t ExtraAlign = 84 llvm::OffsetToAlignment(sizeof(Module *), DeclObjAlignment); 85 char *Buffer = reinterpret_cast<char *>( 86 ::operator new(ExtraAlign + sizeof(Module *) + Size + Extra, Ctx)); 87 Buffer += ExtraAlign; 88 return new (Buffer) Module*(nullptr) + 1; 89 } 90 return ::operator new(Size + Extra, Ctx); 91 } 92 93 Module *Decl::getOwningModuleSlow() const { 94 assert(isFromASTFile() && "Not from AST file?"); 95 return getASTContext().getExternalSource()->getModule(getOwningModuleID()); 96 } 97 98 bool Decl::hasLocalOwningModuleStorage() const { 99 return getASTContext().getLangOpts().ModulesLocalVisibility; 100 } 101 102 const char *Decl::getDeclKindName() const { 103 switch (DeclKind) { 104 default: llvm_unreachable("Declaration not in DeclNodes.inc!"); 105 #define DECL(DERIVED, BASE) case DERIVED: return #DERIVED; 106 #define ABSTRACT_DECL(DECL) 107 #include "clang/AST/DeclNodes.inc" 108 } 109 } 110 111 void Decl::setInvalidDecl(bool Invalid) { 112 InvalidDecl = Invalid; 113 assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition()); 114 if (Invalid && !isa<ParmVarDecl>(this)) { 115 // Defensive maneuver for ill-formed code: we're likely not to make it to 116 // a point where we set the access specifier, so default it to "public" 117 // to avoid triggering asserts elsewhere in the front end. 118 setAccess(AS_public); 119 } 120 } 121 122 const char *DeclContext::getDeclKindName() const { 123 switch (DeclKind) { 124 default: llvm_unreachable("Declaration context not in DeclNodes.inc!"); 125 #define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED; 126 #define ABSTRACT_DECL(DECL) 127 #include "clang/AST/DeclNodes.inc" 128 } 129 } 130 131 bool Decl::StatisticsEnabled = false; 132 void Decl::EnableStatistics() { 133 StatisticsEnabled = true; 134 } 135 136 void Decl::PrintStats() { 137 llvm::errs() << "\n*** Decl Stats:\n"; 138 139 int totalDecls = 0; 140 #define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s; 141 #define ABSTRACT_DECL(DECL) 142 #include "clang/AST/DeclNodes.inc" 143 llvm::errs() << " " << totalDecls << " decls total.\n"; 144 145 int totalBytes = 0; 146 #define DECL(DERIVED, BASE) \ 147 if (n##DERIVED##s > 0) { \ 148 totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \ 149 llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \ 150 << sizeof(DERIVED##Decl) << " each (" \ 151 << n##DERIVED##s * sizeof(DERIVED##Decl) \ 152 << " bytes)\n"; \ 153 } 154 #define ABSTRACT_DECL(DECL) 155 #include "clang/AST/DeclNodes.inc" 156 157 llvm::errs() << "Total bytes = " << totalBytes << "\n"; 158 } 159 160 void Decl::add(Kind k) { 161 switch (k) { 162 #define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break; 163 #define ABSTRACT_DECL(DECL) 164 #include "clang/AST/DeclNodes.inc" 165 } 166 } 167 168 bool Decl::isTemplateParameterPack() const { 169 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this)) 170 return TTP->isParameterPack(); 171 if (const NonTypeTemplateParmDecl *NTTP 172 = dyn_cast<NonTypeTemplateParmDecl>(this)) 173 return NTTP->isParameterPack(); 174 if (const TemplateTemplateParmDecl *TTP 175 = dyn_cast<TemplateTemplateParmDecl>(this)) 176 return TTP->isParameterPack(); 177 return false; 178 } 179 180 bool Decl::isParameterPack() const { 181 if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this)) 182 return Parm->isParameterPack(); 183 184 return isTemplateParameterPack(); 185 } 186 187 FunctionDecl *Decl::getAsFunction() { 188 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) 189 return FD; 190 if (const FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(this)) 191 return FTD->getTemplatedDecl(); 192 return nullptr; 193 } 194 195 bool Decl::isTemplateDecl() const { 196 return isa<TemplateDecl>(this); 197 } 198 199 const DeclContext *Decl::getParentFunctionOrMethod() const { 200 for (const DeclContext *DC = getDeclContext(); 201 DC && !DC->isTranslationUnit() && !DC->isNamespace(); 202 DC = DC->getParent()) 203 if (DC->isFunctionOrMethod()) 204 return DC; 205 206 return nullptr; 207 } 208 209 210 //===----------------------------------------------------------------------===// 211 // PrettyStackTraceDecl Implementation 212 //===----------------------------------------------------------------------===// 213 214 void PrettyStackTraceDecl::print(raw_ostream &OS) const { 215 SourceLocation TheLoc = Loc; 216 if (TheLoc.isInvalid() && TheDecl) 217 TheLoc = TheDecl->getLocation(); 218 219 if (TheLoc.isValid()) { 220 TheLoc.print(OS, SM); 221 OS << ": "; 222 } 223 224 OS << Message; 225 226 if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) { 227 OS << " '"; 228 DN->printQualifiedName(OS); 229 OS << '\''; 230 } 231 OS << '\n'; 232 } 233 234 //===----------------------------------------------------------------------===// 235 // Decl Implementation 236 //===----------------------------------------------------------------------===// 237 238 // Out-of-line virtual method providing a home for Decl. 239 Decl::~Decl() { } 240 241 void Decl::setDeclContext(DeclContext *DC) { 242 DeclCtx = DC; 243 } 244 245 void Decl::setLexicalDeclContext(DeclContext *DC) { 246 if (DC == getLexicalDeclContext()) 247 return; 248 249 if (isInSemaDC()) { 250 setDeclContextsImpl(getDeclContext(), DC, getASTContext()); 251 } else { 252 getMultipleDC()->LexicalDC = DC; 253 } 254 Hidden = cast<Decl>(DC)->Hidden; 255 } 256 257 void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC, 258 ASTContext &Ctx) { 259 if (SemaDC == LexicalDC) { 260 DeclCtx = SemaDC; 261 } else { 262 Decl::MultipleDC *MDC = new (Ctx) Decl::MultipleDC(); 263 MDC->SemanticDC = SemaDC; 264 MDC->LexicalDC = LexicalDC; 265 DeclCtx = MDC; 266 } 267 } 268 269 bool Decl::isLexicallyWithinFunctionOrMethod() const { 270 const DeclContext *LDC = getLexicalDeclContext(); 271 while (true) { 272 if (LDC->isFunctionOrMethod()) 273 return true; 274 if (!isa<TagDecl>(LDC)) 275 return false; 276 LDC = LDC->getLexicalParent(); 277 } 278 return false; 279 } 280 281 bool Decl::isInAnonymousNamespace() const { 282 const DeclContext *DC = getDeclContext(); 283 do { 284 if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC)) 285 if (ND->isAnonymousNamespace()) 286 return true; 287 } while ((DC = DC->getParent())); 288 289 return false; 290 } 291 292 bool Decl::isInStdNamespace() const { 293 return getDeclContext()->isStdNamespace(); 294 } 295 296 TranslationUnitDecl *Decl::getTranslationUnitDecl() { 297 if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this)) 298 return TUD; 299 300 DeclContext *DC = getDeclContext(); 301 assert(DC && "This decl is not contained in a translation unit!"); 302 303 while (!DC->isTranslationUnit()) { 304 DC = DC->getParent(); 305 assert(DC && "This decl is not contained in a translation unit!"); 306 } 307 308 return cast<TranslationUnitDecl>(DC); 309 } 310 311 ASTContext &Decl::getASTContext() const { 312 return getTranslationUnitDecl()->getASTContext(); 313 } 314 315 ASTMutationListener *Decl::getASTMutationListener() const { 316 return getASTContext().getASTMutationListener(); 317 } 318 319 unsigned Decl::getMaxAlignment() const { 320 if (!hasAttrs()) 321 return 0; 322 323 unsigned Align = 0; 324 const AttrVec &V = getAttrs(); 325 ASTContext &Ctx = getASTContext(); 326 specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end()); 327 for (; I != E; ++I) 328 Align = std::max(Align, I->getAlignment(Ctx)); 329 return Align; 330 } 331 332 bool Decl::isUsed(bool CheckUsedAttr) const { 333 if (Used) 334 return true; 335 336 // Check for used attribute. 337 if (CheckUsedAttr && hasAttr<UsedAttr>()) 338 return true; 339 340 return false; 341 } 342 343 void Decl::markUsed(ASTContext &C) { 344 if (Used) 345 return; 346 347 if (C.getASTMutationListener()) 348 C.getASTMutationListener()->DeclarationMarkedUsed(this); 349 350 Used = true; 351 } 352 353 bool Decl::isReferenced() const { 354 if (Referenced) 355 return true; 356 357 // Check redeclarations. 358 for (auto I : redecls()) 359 if (I->Referenced) 360 return true; 361 362 return false; 363 } 364 365 /// \brief Determine the availability of the given declaration based on 366 /// the target platform. 367 /// 368 /// When it returns an availability result other than \c AR_Available, 369 /// if the \p Message parameter is non-NULL, it will be set to a 370 /// string describing why the entity is unavailable. 371 /// 372 /// FIXME: Make these strings localizable, since they end up in 373 /// diagnostics. 374 static AvailabilityResult CheckAvailability(ASTContext &Context, 375 const AvailabilityAttr *A, 376 std::string *Message) { 377 VersionTuple TargetMinVersion = 378 Context.getTargetInfo().getPlatformMinVersion(); 379 380 if (TargetMinVersion.empty()) 381 return AR_Available; 382 383 // Check if this is an App Extension "platform", and if so chop off 384 // the suffix for matching with the actual platform. 385 StringRef ActualPlatform = A->getPlatform()->getName(); 386 StringRef RealizedPlatform = ActualPlatform; 387 if (Context.getLangOpts().AppExt) { 388 size_t suffix = RealizedPlatform.rfind("_app_extension"); 389 if (suffix != StringRef::npos) 390 RealizedPlatform = RealizedPlatform.slice(0, suffix); 391 } 392 393 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName(); 394 395 // Match the platform name. 396 if (RealizedPlatform != TargetPlatform) 397 return AR_Available; 398 399 StringRef PrettyPlatformName 400 = AvailabilityAttr::getPrettyPlatformName(ActualPlatform); 401 402 if (PrettyPlatformName.empty()) 403 PrettyPlatformName = ActualPlatform; 404 405 std::string HintMessage; 406 if (!A->getMessage().empty()) { 407 HintMessage = " - "; 408 HintMessage += A->getMessage(); 409 } 410 411 // Make sure that this declaration has not been marked 'unavailable'. 412 if (A->getUnavailable()) { 413 if (Message) { 414 Message->clear(); 415 llvm::raw_string_ostream Out(*Message); 416 Out << "not available on " << PrettyPlatformName 417 << HintMessage; 418 } 419 420 return AR_Unavailable; 421 } 422 423 // Make sure that this declaration has already been introduced. 424 if (!A->getIntroduced().empty() && 425 TargetMinVersion < A->getIntroduced()) { 426 if (Message) { 427 Message->clear(); 428 llvm::raw_string_ostream Out(*Message); 429 VersionTuple VTI(A->getIntroduced()); 430 VTI.UseDotAsSeparator(); 431 Out << "introduced in " << PrettyPlatformName << ' ' 432 << VTI << HintMessage; 433 } 434 435 return A->getStrict() ? AR_Unavailable : AR_NotYetIntroduced; 436 } 437 438 // Make sure that this declaration hasn't been obsoleted. 439 if (!A->getObsoleted().empty() && TargetMinVersion >= A->getObsoleted()) { 440 if (Message) { 441 Message->clear(); 442 llvm::raw_string_ostream Out(*Message); 443 VersionTuple VTO(A->getObsoleted()); 444 VTO.UseDotAsSeparator(); 445 Out << "obsoleted in " << PrettyPlatformName << ' ' 446 << VTO << HintMessage; 447 } 448 449 return AR_Unavailable; 450 } 451 452 // Make sure that this declaration hasn't been deprecated. 453 if (!A->getDeprecated().empty() && TargetMinVersion >= A->getDeprecated()) { 454 if (Message) { 455 Message->clear(); 456 llvm::raw_string_ostream Out(*Message); 457 VersionTuple VTD(A->getDeprecated()); 458 VTD.UseDotAsSeparator(); 459 Out << "first deprecated in " << PrettyPlatformName << ' ' 460 << VTD << HintMessage; 461 } 462 463 return AR_Deprecated; 464 } 465 466 return AR_Available; 467 } 468 469 AvailabilityResult Decl::getAvailability(std::string *Message) const { 470 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(this)) 471 return FTD->getTemplatedDecl()->getAvailability(Message); 472 473 AvailabilityResult Result = AR_Available; 474 std::string ResultMessage; 475 476 for (const auto *A : attrs()) { 477 if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(A)) { 478 if (Result >= AR_Deprecated) 479 continue; 480 481 if (Message) 482 ResultMessage = Deprecated->getMessage(); 483 484 Result = AR_Deprecated; 485 continue; 486 } 487 488 if (const auto *Unavailable = dyn_cast<UnavailableAttr>(A)) { 489 if (Message) 490 *Message = Unavailable->getMessage(); 491 return AR_Unavailable; 492 } 493 494 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) { 495 AvailabilityResult AR = CheckAvailability(getASTContext(), Availability, 496 Message); 497 498 if (AR == AR_Unavailable) 499 return AR_Unavailable; 500 501 if (AR > Result) { 502 Result = AR; 503 if (Message) 504 ResultMessage.swap(*Message); 505 } 506 continue; 507 } 508 } 509 510 if (Message) 511 Message->swap(ResultMessage); 512 return Result; 513 } 514 515 bool Decl::canBeWeakImported(bool &IsDefinition) const { 516 IsDefinition = false; 517 518 // Variables, if they aren't definitions. 519 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) { 520 if (Var->isThisDeclarationADefinition()) { 521 IsDefinition = true; 522 return false; 523 } 524 return true; 525 526 // Functions, if they aren't definitions. 527 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) { 528 if (FD->hasBody()) { 529 IsDefinition = true; 530 return false; 531 } 532 return true; 533 534 // Objective-C classes, if this is the non-fragile runtime. 535 } else if (isa<ObjCInterfaceDecl>(this) && 536 getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) { 537 return true; 538 539 // Nothing else. 540 } else { 541 return false; 542 } 543 } 544 545 bool Decl::isWeakImported() const { 546 bool IsDefinition; 547 if (!canBeWeakImported(IsDefinition)) 548 return false; 549 550 for (const auto *A : attrs()) { 551 if (isa<WeakImportAttr>(A)) 552 return true; 553 554 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) { 555 if (CheckAvailability(getASTContext(), Availability, 556 nullptr) == AR_NotYetIntroduced) 557 return true; 558 } 559 } 560 561 return false; 562 } 563 564 unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) { 565 switch (DeclKind) { 566 case Function: 567 case CXXMethod: 568 case CXXConstructor: 569 case CXXDestructor: 570 case CXXConversion: 571 case EnumConstant: 572 case Var: 573 case ImplicitParam: 574 case ParmVar: 575 case ObjCMethod: 576 case ObjCProperty: 577 case MSProperty: 578 return IDNS_Ordinary; 579 case Label: 580 return IDNS_Label; 581 case IndirectField: 582 return IDNS_Ordinary | IDNS_Member; 583 584 case NonTypeTemplateParm: 585 // Non-type template parameters are not found by lookups that ignore 586 // non-types, but they are found by redeclaration lookups for tag types, 587 // so we include them in the tag namespace. 588 return IDNS_Ordinary | IDNS_Tag; 589 590 case ObjCCompatibleAlias: 591 case ObjCInterface: 592 return IDNS_Ordinary | IDNS_Type; 593 594 case Typedef: 595 case TypeAlias: 596 case TypeAliasTemplate: 597 case UnresolvedUsingTypename: 598 case TemplateTypeParm: 599 case ObjCTypeParam: 600 return IDNS_Ordinary | IDNS_Type; 601 602 case UsingShadow: 603 return 0; // we'll actually overwrite this later 604 605 case UnresolvedUsingValue: 606 return IDNS_Ordinary | IDNS_Using; 607 608 case Using: 609 return IDNS_Using; 610 611 case ObjCProtocol: 612 return IDNS_ObjCProtocol; 613 614 case Field: 615 case ObjCAtDefsField: 616 case ObjCIvar: 617 return IDNS_Member; 618 619 case Record: 620 case CXXRecord: 621 case Enum: 622 return IDNS_Tag | IDNS_Type; 623 624 case Namespace: 625 case NamespaceAlias: 626 return IDNS_Namespace; 627 628 case FunctionTemplate: 629 case VarTemplate: 630 return IDNS_Ordinary; 631 632 case ClassTemplate: 633 case TemplateTemplateParm: 634 return IDNS_Ordinary | IDNS_Tag | IDNS_Type; 635 636 case OMPDeclareReduction: 637 return IDNS_OMPReduction; 638 639 // Never have names. 640 case Friend: 641 case FriendTemplate: 642 case AccessSpec: 643 case LinkageSpec: 644 case FileScopeAsm: 645 case StaticAssert: 646 case ObjCPropertyImpl: 647 case PragmaComment: 648 case PragmaDetectMismatch: 649 case Block: 650 case Captured: 651 case TranslationUnit: 652 case ExternCContext: 653 654 case UsingDirective: 655 case BuiltinTemplate: 656 case ClassTemplateSpecialization: 657 case ClassTemplatePartialSpecialization: 658 case ClassScopeFunctionSpecialization: 659 case VarTemplateSpecialization: 660 case VarTemplatePartialSpecialization: 661 case ObjCImplementation: 662 case ObjCCategory: 663 case ObjCCategoryImpl: 664 case Import: 665 case OMPThreadPrivate: 666 case OMPCapturedExpr: 667 case Empty: 668 // Never looked up by name. 669 return 0; 670 } 671 672 llvm_unreachable("Invalid DeclKind!"); 673 } 674 675 void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) { 676 assert(!HasAttrs && "Decl already contains attrs."); 677 678 AttrVec &AttrBlank = Ctx.getDeclAttrs(this); 679 assert(AttrBlank.empty() && "HasAttrs was wrong?"); 680 681 AttrBlank = attrs; 682 HasAttrs = true; 683 } 684 685 void Decl::dropAttrs() { 686 if (!HasAttrs) return; 687 688 HasAttrs = false; 689 getASTContext().eraseDeclAttrs(this); 690 } 691 692 const AttrVec &Decl::getAttrs() const { 693 assert(HasAttrs && "No attrs to get!"); 694 return getASTContext().getDeclAttrs(this); 695 } 696 697 Decl *Decl::castFromDeclContext (const DeclContext *D) { 698 Decl::Kind DK = D->getDeclKind(); 699 switch(DK) { 700 #define DECL(NAME, BASE) 701 #define DECL_CONTEXT(NAME) \ 702 case Decl::NAME: \ 703 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D)); 704 #define DECL_CONTEXT_BASE(NAME) 705 #include "clang/AST/DeclNodes.inc" 706 default: 707 #define DECL(NAME, BASE) 708 #define DECL_CONTEXT_BASE(NAME) \ 709 if (DK >= first##NAME && DK <= last##NAME) \ 710 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D)); 711 #include "clang/AST/DeclNodes.inc" 712 llvm_unreachable("a decl that inherits DeclContext isn't handled"); 713 } 714 } 715 716 DeclContext *Decl::castToDeclContext(const Decl *D) { 717 Decl::Kind DK = D->getKind(); 718 switch(DK) { 719 #define DECL(NAME, BASE) 720 #define DECL_CONTEXT(NAME) \ 721 case Decl::NAME: \ 722 return static_cast<NAME##Decl*>(const_cast<Decl*>(D)); 723 #define DECL_CONTEXT_BASE(NAME) 724 #include "clang/AST/DeclNodes.inc" 725 default: 726 #define DECL(NAME, BASE) 727 #define DECL_CONTEXT_BASE(NAME) \ 728 if (DK >= first##NAME && DK <= last##NAME) \ 729 return static_cast<NAME##Decl*>(const_cast<Decl*>(D)); 730 #include "clang/AST/DeclNodes.inc" 731 llvm_unreachable("a decl that inherits DeclContext isn't handled"); 732 } 733 } 734 735 SourceLocation Decl::getBodyRBrace() const { 736 // Special handling of FunctionDecl to avoid de-serializing the body from PCH. 737 // FunctionDecl stores EndRangeLoc for this purpose. 738 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) { 739 const FunctionDecl *Definition; 740 if (FD->hasBody(Definition)) 741 return Definition->getSourceRange().getEnd(); 742 return SourceLocation(); 743 } 744 745 if (Stmt *Body = getBody()) 746 return Body->getSourceRange().getEnd(); 747 748 return SourceLocation(); 749 } 750 751 bool Decl::AccessDeclContextSanity() const { 752 #ifndef NDEBUG 753 // Suppress this check if any of the following hold: 754 // 1. this is the translation unit (and thus has no parent) 755 // 2. this is a template parameter (and thus doesn't belong to its context) 756 // 3. this is a non-type template parameter 757 // 4. the context is not a record 758 // 5. it's invalid 759 // 6. it's a C++0x static_assert. 760 if (isa<TranslationUnitDecl>(this) || 761 isa<TemplateTypeParmDecl>(this) || 762 isa<NonTypeTemplateParmDecl>(this) || 763 !isa<CXXRecordDecl>(getDeclContext()) || 764 isInvalidDecl() || 765 isa<StaticAssertDecl>(this) || 766 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization 767 // as DeclContext (?). 768 isa<ParmVarDecl>(this) || 769 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have 770 // AS_none as access specifier. 771 isa<CXXRecordDecl>(this) || 772 isa<ClassScopeFunctionSpecializationDecl>(this)) 773 return true; 774 775 assert(Access != AS_none && 776 "Access specifier is AS_none inside a record decl"); 777 #endif 778 return true; 779 } 780 781 static Decl::Kind getKind(const Decl *D) { return D->getKind(); } 782 static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); } 783 784 const FunctionType *Decl::getFunctionType(bool BlocksToo) const { 785 QualType Ty; 786 if (const ValueDecl *D = dyn_cast<ValueDecl>(this)) 787 Ty = D->getType(); 788 else if (const TypedefNameDecl *D = dyn_cast<TypedefNameDecl>(this)) 789 Ty = D->getUnderlyingType(); 790 else 791 return nullptr; 792 793 if (Ty->isFunctionPointerType()) 794 Ty = Ty->getAs<PointerType>()->getPointeeType(); 795 else if (BlocksToo && Ty->isBlockPointerType()) 796 Ty = Ty->getAs<BlockPointerType>()->getPointeeType(); 797 798 return Ty->getAs<FunctionType>(); 799 } 800 801 802 /// Starting at a given context (a Decl or DeclContext), look for a 803 /// code context that is not a closure (a lambda, block, etc.). 804 template <class T> static Decl *getNonClosureContext(T *D) { 805 if (getKind(D) == Decl::CXXMethod) { 806 CXXMethodDecl *MD = cast<CXXMethodDecl>(D); 807 if (MD->getOverloadedOperator() == OO_Call && 808 MD->getParent()->isLambda()) 809 return getNonClosureContext(MD->getParent()->getParent()); 810 return MD; 811 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 812 return FD; 813 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 814 return MD; 815 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) { 816 return getNonClosureContext(BD->getParent()); 817 } else if (CapturedDecl *CD = dyn_cast<CapturedDecl>(D)) { 818 return getNonClosureContext(CD->getParent()); 819 } else { 820 return nullptr; 821 } 822 } 823 824 Decl *Decl::getNonClosureContext() { 825 return ::getNonClosureContext(this); 826 } 827 828 Decl *DeclContext::getNonClosureAncestor() { 829 return ::getNonClosureContext(this); 830 } 831 832 //===----------------------------------------------------------------------===// 833 // DeclContext Implementation 834 //===----------------------------------------------------------------------===// 835 836 bool DeclContext::classof(const Decl *D) { 837 switch (D->getKind()) { 838 #define DECL(NAME, BASE) 839 #define DECL_CONTEXT(NAME) case Decl::NAME: 840 #define DECL_CONTEXT_BASE(NAME) 841 #include "clang/AST/DeclNodes.inc" 842 return true; 843 default: 844 #define DECL(NAME, BASE) 845 #define DECL_CONTEXT_BASE(NAME) \ 846 if (D->getKind() >= Decl::first##NAME && \ 847 D->getKind() <= Decl::last##NAME) \ 848 return true; 849 #include "clang/AST/DeclNodes.inc" 850 return false; 851 } 852 } 853 854 DeclContext::~DeclContext() { } 855 856 /// \brief Find the parent context of this context that will be 857 /// used for unqualified name lookup. 858 /// 859 /// Generally, the parent lookup context is the semantic context. However, for 860 /// a friend function the parent lookup context is the lexical context, which 861 /// is the class in which the friend is declared. 862 DeclContext *DeclContext::getLookupParent() { 863 // FIXME: Find a better way to identify friends 864 if (isa<FunctionDecl>(this)) 865 if (getParent()->getRedeclContext()->isFileContext() && 866 getLexicalParent()->getRedeclContext()->isRecord()) 867 return getLexicalParent(); 868 869 return getParent(); 870 } 871 872 bool DeclContext::isInlineNamespace() const { 873 return isNamespace() && 874 cast<NamespaceDecl>(this)->isInline(); 875 } 876 877 bool DeclContext::isStdNamespace() const { 878 if (!isNamespace()) 879 return false; 880 881 const NamespaceDecl *ND = cast<NamespaceDecl>(this); 882 if (ND->isInline()) { 883 return ND->getParent()->isStdNamespace(); 884 } 885 886 if (!getParent()->getRedeclContext()->isTranslationUnit()) 887 return false; 888 889 const IdentifierInfo *II = ND->getIdentifier(); 890 return II && II->isStr("std"); 891 } 892 893 bool DeclContext::isDependentContext() const { 894 if (isFileContext()) 895 return false; 896 897 if (isa<ClassTemplatePartialSpecializationDecl>(this)) 898 return true; 899 900 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) { 901 if (Record->getDescribedClassTemplate()) 902 return true; 903 904 if (Record->isDependentLambda()) 905 return true; 906 } 907 908 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) { 909 if (Function->getDescribedFunctionTemplate()) 910 return true; 911 912 // Friend function declarations are dependent if their *lexical* 913 // context is dependent. 914 if (cast<Decl>(this)->getFriendObjectKind()) 915 return getLexicalParent()->isDependentContext(); 916 } 917 918 // FIXME: A variable template is a dependent context, but is not a 919 // DeclContext. A context within it (such as a lambda-expression) 920 // should be considered dependent. 921 922 return getParent() && getParent()->isDependentContext(); 923 } 924 925 bool DeclContext::isTransparentContext() const { 926 if (DeclKind == Decl::Enum) 927 return !cast<EnumDecl>(this)->isScoped(); 928 else if (DeclKind == Decl::LinkageSpec) 929 return true; 930 931 return false; 932 } 933 934 static bool isLinkageSpecContext(const DeclContext *DC, 935 LinkageSpecDecl::LanguageIDs ID) { 936 while (DC->getDeclKind() != Decl::TranslationUnit) { 937 if (DC->getDeclKind() == Decl::LinkageSpec) 938 return cast<LinkageSpecDecl>(DC)->getLanguage() == ID; 939 DC = DC->getLexicalParent(); 940 } 941 return false; 942 } 943 944 bool DeclContext::isExternCContext() const { 945 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_c); 946 } 947 948 bool DeclContext::isExternCXXContext() const { 949 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_cxx); 950 } 951 952 bool DeclContext::Encloses(const DeclContext *DC) const { 953 if (getPrimaryContext() != this) 954 return getPrimaryContext()->Encloses(DC); 955 956 for (; DC; DC = DC->getParent()) 957 if (DC->getPrimaryContext() == this) 958 return true; 959 return false; 960 } 961 962 DeclContext *DeclContext::getPrimaryContext() { 963 switch (DeclKind) { 964 case Decl::TranslationUnit: 965 case Decl::ExternCContext: 966 case Decl::LinkageSpec: 967 case Decl::Block: 968 case Decl::Captured: 969 case Decl::OMPDeclareReduction: 970 // There is only one DeclContext for these entities. 971 return this; 972 973 case Decl::Namespace: 974 // The original namespace is our primary context. 975 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace(); 976 977 case Decl::ObjCMethod: 978 return this; 979 980 case Decl::ObjCInterface: 981 if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition()) 982 return Def; 983 984 return this; 985 986 case Decl::ObjCProtocol: 987 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition()) 988 return Def; 989 990 return this; 991 992 case Decl::ObjCCategory: 993 return this; 994 995 case Decl::ObjCImplementation: 996 case Decl::ObjCCategoryImpl: 997 return this; 998 999 default: 1000 if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) { 1001 // If this is a tag type that has a definition or is currently 1002 // being defined, that definition is our primary context. 1003 TagDecl *Tag = cast<TagDecl>(this); 1004 1005 if (TagDecl *Def = Tag->getDefinition()) 1006 return Def; 1007 1008 if (const TagType *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) { 1009 // Note, TagType::getDecl returns the (partial) definition one exists. 1010 TagDecl *PossiblePartialDef = TagTy->getDecl(); 1011 if (PossiblePartialDef->isBeingDefined()) 1012 return PossiblePartialDef; 1013 } else { 1014 assert(isa<InjectedClassNameType>(Tag->getTypeForDecl())); 1015 } 1016 1017 return Tag; 1018 } 1019 1020 assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction && 1021 "Unknown DeclContext kind"); 1022 return this; 1023 } 1024 } 1025 1026 void 1027 DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){ 1028 Contexts.clear(); 1029 1030 if (DeclKind != Decl::Namespace) { 1031 Contexts.push_back(this); 1032 return; 1033 } 1034 1035 NamespaceDecl *Self = static_cast<NamespaceDecl *>(this); 1036 for (NamespaceDecl *N = Self->getMostRecentDecl(); N; 1037 N = N->getPreviousDecl()) 1038 Contexts.push_back(N); 1039 1040 std::reverse(Contexts.begin(), Contexts.end()); 1041 } 1042 1043 std::pair<Decl *, Decl *> 1044 DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls, 1045 bool FieldsAlreadyLoaded) { 1046 // Build up a chain of declarations via the Decl::NextInContextAndBits field. 1047 Decl *FirstNewDecl = nullptr; 1048 Decl *PrevDecl = nullptr; 1049 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 1050 if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I])) 1051 continue; 1052 1053 Decl *D = Decls[I]; 1054 if (PrevDecl) 1055 PrevDecl->NextInContextAndBits.setPointer(D); 1056 else 1057 FirstNewDecl = D; 1058 1059 PrevDecl = D; 1060 } 1061 1062 return std::make_pair(FirstNewDecl, PrevDecl); 1063 } 1064 1065 /// \brief We have just acquired external visible storage, and we already have 1066 /// built a lookup map. For every name in the map, pull in the new names from 1067 /// the external storage. 1068 void DeclContext::reconcileExternalVisibleStorage() const { 1069 assert(NeedToReconcileExternalVisibleStorage && LookupPtr); 1070 NeedToReconcileExternalVisibleStorage = false; 1071 1072 for (auto &Lookup : *LookupPtr) 1073 Lookup.second.setHasExternalDecls(); 1074 } 1075 1076 /// \brief Load the declarations within this lexical storage from an 1077 /// external source. 1078 /// \return \c true if any declarations were added. 1079 bool 1080 DeclContext::LoadLexicalDeclsFromExternalStorage() const { 1081 ExternalASTSource *Source = getParentASTContext().getExternalSource(); 1082 assert(hasExternalLexicalStorage() && Source && "No external storage?"); 1083 1084 // Notify that we have a DeclContext that is initializing. 1085 ExternalASTSource::Deserializing ADeclContext(Source); 1086 1087 // Load the external declarations, if any. 1088 SmallVector<Decl*, 64> Decls; 1089 ExternalLexicalStorage = false; 1090 Source->FindExternalLexicalDecls(this, Decls); 1091 1092 if (Decls.empty()) 1093 return false; 1094 1095 // We may have already loaded just the fields of this record, in which case 1096 // we need to ignore them. 1097 bool FieldsAlreadyLoaded = false; 1098 if (const RecordDecl *RD = dyn_cast<RecordDecl>(this)) 1099 FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage; 1100 1101 // Splice the newly-read declarations into the beginning of the list 1102 // of declarations. 1103 Decl *ExternalFirst, *ExternalLast; 1104 std::tie(ExternalFirst, ExternalLast) = 1105 BuildDeclChain(Decls, FieldsAlreadyLoaded); 1106 ExternalLast->NextInContextAndBits.setPointer(FirstDecl); 1107 FirstDecl = ExternalFirst; 1108 if (!LastDecl) 1109 LastDecl = ExternalLast; 1110 return true; 1111 } 1112 1113 DeclContext::lookup_result 1114 ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC, 1115 DeclarationName Name) { 1116 ASTContext &Context = DC->getParentASTContext(); 1117 StoredDeclsMap *Map; 1118 if (!(Map = DC->LookupPtr)) 1119 Map = DC->CreateStoredDeclsMap(Context); 1120 if (DC->NeedToReconcileExternalVisibleStorage) 1121 DC->reconcileExternalVisibleStorage(); 1122 1123 (*Map)[Name].removeExternalDecls(); 1124 1125 return DeclContext::lookup_result(); 1126 } 1127 1128 DeclContext::lookup_result 1129 ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC, 1130 DeclarationName Name, 1131 ArrayRef<NamedDecl*> Decls) { 1132 ASTContext &Context = DC->getParentASTContext(); 1133 StoredDeclsMap *Map; 1134 if (!(Map = DC->LookupPtr)) 1135 Map = DC->CreateStoredDeclsMap(Context); 1136 if (DC->NeedToReconcileExternalVisibleStorage) 1137 DC->reconcileExternalVisibleStorage(); 1138 1139 StoredDeclsList &List = (*Map)[Name]; 1140 1141 // Clear out any old external visible declarations, to avoid quadratic 1142 // performance in the redeclaration checks below. 1143 List.removeExternalDecls(); 1144 1145 if (!List.isNull()) { 1146 // We have both existing declarations and new declarations for this name. 1147 // Some of the declarations may simply replace existing ones. Handle those 1148 // first. 1149 llvm::SmallVector<unsigned, 8> Skip; 1150 for (unsigned I = 0, N = Decls.size(); I != N; ++I) 1151 if (List.HandleRedeclaration(Decls[I], /*IsKnownNewer*/false)) 1152 Skip.push_back(I); 1153 Skip.push_back(Decls.size()); 1154 1155 // Add in any new declarations. 1156 unsigned SkipPos = 0; 1157 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 1158 if (I == Skip[SkipPos]) 1159 ++SkipPos; 1160 else 1161 List.AddSubsequentDecl(Decls[I]); 1162 } 1163 } else { 1164 // Convert the array to a StoredDeclsList. 1165 for (ArrayRef<NamedDecl*>::iterator 1166 I = Decls.begin(), E = Decls.end(); I != E; ++I) { 1167 if (List.isNull()) 1168 List.setOnlyValue(*I); 1169 else 1170 List.AddSubsequentDecl(*I); 1171 } 1172 } 1173 1174 return List.getLookupResult(); 1175 } 1176 1177 DeclContext::decl_iterator DeclContext::decls_begin() const { 1178 if (hasExternalLexicalStorage()) 1179 LoadLexicalDeclsFromExternalStorage(); 1180 return decl_iterator(FirstDecl); 1181 } 1182 1183 bool DeclContext::decls_empty() const { 1184 if (hasExternalLexicalStorage()) 1185 LoadLexicalDeclsFromExternalStorage(); 1186 1187 return !FirstDecl; 1188 } 1189 1190 bool DeclContext::containsDecl(Decl *D) const { 1191 return (D->getLexicalDeclContext() == this && 1192 (D->NextInContextAndBits.getPointer() || D == LastDecl)); 1193 } 1194 1195 void DeclContext::removeDecl(Decl *D) { 1196 assert(D->getLexicalDeclContext() == this && 1197 "decl being removed from non-lexical context"); 1198 assert((D->NextInContextAndBits.getPointer() || D == LastDecl) && 1199 "decl is not in decls list"); 1200 1201 // Remove D from the decl chain. This is O(n) but hopefully rare. 1202 if (D == FirstDecl) { 1203 if (D == LastDecl) 1204 FirstDecl = LastDecl = nullptr; 1205 else 1206 FirstDecl = D->NextInContextAndBits.getPointer(); 1207 } else { 1208 for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) { 1209 assert(I && "decl not found in linked list"); 1210 if (I->NextInContextAndBits.getPointer() == D) { 1211 I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer()); 1212 if (D == LastDecl) LastDecl = I; 1213 break; 1214 } 1215 } 1216 } 1217 1218 // Mark that D is no longer in the decl chain. 1219 D->NextInContextAndBits.setPointer(nullptr); 1220 1221 // Remove D from the lookup table if necessary. 1222 if (isa<NamedDecl>(D)) { 1223 NamedDecl *ND = cast<NamedDecl>(D); 1224 1225 // Remove only decls that have a name 1226 if (!ND->getDeclName()) return; 1227 1228 auto *DC = this; 1229 do { 1230 StoredDeclsMap *Map = DC->getPrimaryContext()->LookupPtr; 1231 if (Map) { 1232 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName()); 1233 assert(Pos != Map->end() && "no lookup entry for decl"); 1234 if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND) 1235 Pos->second.remove(ND); 1236 } 1237 } while (DC->isTransparentContext() && (DC = DC->getParent())); 1238 } 1239 } 1240 1241 void DeclContext::addHiddenDecl(Decl *D) { 1242 assert(D->getLexicalDeclContext() == this && 1243 "Decl inserted into wrong lexical context"); 1244 assert(!D->getNextDeclInContext() && D != LastDecl && 1245 "Decl already inserted into a DeclContext"); 1246 1247 if (FirstDecl) { 1248 LastDecl->NextInContextAndBits.setPointer(D); 1249 LastDecl = D; 1250 } else { 1251 FirstDecl = LastDecl = D; 1252 } 1253 1254 // Notify a C++ record declaration that we've added a member, so it can 1255 // update its class-specific state. 1256 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) 1257 Record->addedMember(D); 1258 1259 // If this is a newly-created (not de-serialized) import declaration, wire 1260 // it in to the list of local import declarations. 1261 if (!D->isFromASTFile()) { 1262 if (ImportDecl *Import = dyn_cast<ImportDecl>(D)) 1263 D->getASTContext().addedLocalImportDecl(Import); 1264 } 1265 } 1266 1267 void DeclContext::addDecl(Decl *D) { 1268 addHiddenDecl(D); 1269 1270 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) 1271 ND->getDeclContext()->getPrimaryContext()-> 1272 makeDeclVisibleInContextWithFlags(ND, false, true); 1273 } 1274 1275 void DeclContext::addDeclInternal(Decl *D) { 1276 addHiddenDecl(D); 1277 1278 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) 1279 ND->getDeclContext()->getPrimaryContext()-> 1280 makeDeclVisibleInContextWithFlags(ND, true, true); 1281 } 1282 1283 /// shouldBeHidden - Determine whether a declaration which was declared 1284 /// within its semantic context should be invisible to qualified name lookup. 1285 static bool shouldBeHidden(NamedDecl *D) { 1286 // Skip unnamed declarations. 1287 if (!D->getDeclName()) 1288 return true; 1289 1290 // Skip entities that can't be found by name lookup into a particular 1291 // context. 1292 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) || 1293 D->isTemplateParameter()) 1294 return true; 1295 1296 // Skip template specializations. 1297 // FIXME: This feels like a hack. Should DeclarationName support 1298 // template-ids, or is there a better way to keep specializations 1299 // from being visible? 1300 if (isa<ClassTemplateSpecializationDecl>(D)) 1301 return true; 1302 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 1303 if (FD->isFunctionTemplateSpecialization()) 1304 return true; 1305 1306 return false; 1307 } 1308 1309 /// buildLookup - Build the lookup data structure with all of the 1310 /// declarations in this DeclContext (and any other contexts linked 1311 /// to it or transparent contexts nested within it) and return it. 1312 /// 1313 /// Note that the produced map may miss out declarations from an 1314 /// external source. If it does, those entries will be marked with 1315 /// the 'hasExternalDecls' flag. 1316 StoredDeclsMap *DeclContext::buildLookup() { 1317 assert(this == getPrimaryContext() && "buildLookup called on non-primary DC"); 1318 1319 if (!HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups) 1320 return LookupPtr; 1321 1322 SmallVector<DeclContext *, 2> Contexts; 1323 collectAllContexts(Contexts); 1324 1325 if (HasLazyExternalLexicalLookups) { 1326 HasLazyExternalLexicalLookups = false; 1327 for (auto *DC : Contexts) { 1328 if (DC->hasExternalLexicalStorage()) 1329 HasLazyLocalLexicalLookups |= 1330 DC->LoadLexicalDeclsFromExternalStorage(); 1331 } 1332 1333 if (!HasLazyLocalLexicalLookups) 1334 return LookupPtr; 1335 } 1336 1337 for (auto *DC : Contexts) 1338 buildLookupImpl(DC, hasExternalVisibleStorage()); 1339 1340 // We no longer have any lazy decls. 1341 HasLazyLocalLexicalLookups = false; 1342 return LookupPtr; 1343 } 1344 1345 /// buildLookupImpl - Build part of the lookup data structure for the 1346 /// declarations contained within DCtx, which will either be this 1347 /// DeclContext, a DeclContext linked to it, or a transparent context 1348 /// nested within it. 1349 void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) { 1350 for (Decl *D : DCtx->noload_decls()) { 1351 // Insert this declaration into the lookup structure, but only if 1352 // it's semantically within its decl context. Any other decls which 1353 // should be found in this context are added eagerly. 1354 // 1355 // If it's from an AST file, don't add it now. It'll get handled by 1356 // FindExternalVisibleDeclsByName if needed. Exception: if we're not 1357 // in C++, we do not track external visible decls for the TU, so in 1358 // that case we need to collect them all here. 1359 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) 1360 if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) && 1361 (!ND->isFromASTFile() || 1362 (isTranslationUnit() && 1363 !getParentASTContext().getLangOpts().CPlusPlus))) 1364 makeDeclVisibleInContextImpl(ND, Internal); 1365 1366 // If this declaration is itself a transparent declaration context 1367 // or inline namespace, add the members of this declaration of that 1368 // context (recursively). 1369 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D)) 1370 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace()) 1371 buildLookupImpl(InnerCtx, Internal); 1372 } 1373 } 1374 1375 NamedDecl *const DeclContextLookupResult::SingleElementDummyList = nullptr; 1376 1377 DeclContext::lookup_result 1378 DeclContext::lookup(DeclarationName Name) const { 1379 assert(DeclKind != Decl::LinkageSpec && 1380 "Should not perform lookups into linkage specs!"); 1381 1382 const DeclContext *PrimaryContext = getPrimaryContext(); 1383 if (PrimaryContext != this) 1384 return PrimaryContext->lookup(Name); 1385 1386 // If we have an external source, ensure that any later redeclarations of this 1387 // context have been loaded, since they may add names to the result of this 1388 // lookup (or add external visible storage). 1389 ExternalASTSource *Source = getParentASTContext().getExternalSource(); 1390 if (Source) 1391 (void)cast<Decl>(this)->getMostRecentDecl(); 1392 1393 if (hasExternalVisibleStorage()) { 1394 assert(Source && "external visible storage but no external source?"); 1395 1396 if (NeedToReconcileExternalVisibleStorage) 1397 reconcileExternalVisibleStorage(); 1398 1399 StoredDeclsMap *Map = LookupPtr; 1400 1401 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups) 1402 // FIXME: Make buildLookup const? 1403 Map = const_cast<DeclContext*>(this)->buildLookup(); 1404 1405 if (!Map) 1406 Map = CreateStoredDeclsMap(getParentASTContext()); 1407 1408 // If we have a lookup result with no external decls, we are done. 1409 std::pair<StoredDeclsMap::iterator, bool> R = 1410 Map->insert(std::make_pair(Name, StoredDeclsList())); 1411 if (!R.second && !R.first->second.hasExternalDecls()) 1412 return R.first->second.getLookupResult(); 1413 1414 if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) { 1415 if (StoredDeclsMap *Map = LookupPtr) { 1416 StoredDeclsMap::iterator I = Map->find(Name); 1417 if (I != Map->end()) 1418 return I->second.getLookupResult(); 1419 } 1420 } 1421 1422 return lookup_result(); 1423 } 1424 1425 StoredDeclsMap *Map = LookupPtr; 1426 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups) 1427 Map = const_cast<DeclContext*>(this)->buildLookup(); 1428 1429 if (!Map) 1430 return lookup_result(); 1431 1432 StoredDeclsMap::iterator I = Map->find(Name); 1433 if (I == Map->end()) 1434 return lookup_result(); 1435 1436 return I->second.getLookupResult(); 1437 } 1438 1439 DeclContext::lookup_result 1440 DeclContext::noload_lookup(DeclarationName Name) { 1441 assert(DeclKind != Decl::LinkageSpec && 1442 "Should not perform lookups into linkage specs!"); 1443 1444 DeclContext *PrimaryContext = getPrimaryContext(); 1445 if (PrimaryContext != this) 1446 return PrimaryContext->noload_lookup(Name); 1447 1448 // If we have any lazy lexical declarations not in our lookup map, add them 1449 // now. Don't import any external declarations, not even if we know we have 1450 // some missing from the external visible lookups. 1451 if (HasLazyLocalLexicalLookups) { 1452 SmallVector<DeclContext *, 2> Contexts; 1453 collectAllContexts(Contexts); 1454 for (unsigned I = 0, N = Contexts.size(); I != N; ++I) 1455 buildLookupImpl(Contexts[I], hasExternalVisibleStorage()); 1456 HasLazyLocalLexicalLookups = false; 1457 } 1458 1459 StoredDeclsMap *Map = LookupPtr; 1460 if (!Map) 1461 return lookup_result(); 1462 1463 StoredDeclsMap::iterator I = Map->find(Name); 1464 return I != Map->end() ? I->second.getLookupResult() 1465 : lookup_result(); 1466 } 1467 1468 void DeclContext::localUncachedLookup(DeclarationName Name, 1469 SmallVectorImpl<NamedDecl *> &Results) { 1470 Results.clear(); 1471 1472 // If there's no external storage, just perform a normal lookup and copy 1473 // the results. 1474 if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) { 1475 lookup_result LookupResults = lookup(Name); 1476 Results.insert(Results.end(), LookupResults.begin(), LookupResults.end()); 1477 return; 1478 } 1479 1480 // If we have a lookup table, check there first. Maybe we'll get lucky. 1481 // FIXME: Should we be checking these flags on the primary context? 1482 if (Name && !HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups) { 1483 if (StoredDeclsMap *Map = LookupPtr) { 1484 StoredDeclsMap::iterator Pos = Map->find(Name); 1485 if (Pos != Map->end()) { 1486 Results.insert(Results.end(), 1487 Pos->second.getLookupResult().begin(), 1488 Pos->second.getLookupResult().end()); 1489 return; 1490 } 1491 } 1492 } 1493 1494 // Slow case: grovel through the declarations in our chain looking for 1495 // matches. 1496 // FIXME: If we have lazy external declarations, this will not find them! 1497 // FIXME: Should we CollectAllContexts and walk them all here? 1498 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) { 1499 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) 1500 if (ND->getDeclName() == Name) 1501 Results.push_back(ND); 1502 } 1503 } 1504 1505 DeclContext *DeclContext::getRedeclContext() { 1506 DeclContext *Ctx = this; 1507 // Skip through transparent contexts. 1508 while (Ctx->isTransparentContext()) 1509 Ctx = Ctx->getParent(); 1510 return Ctx; 1511 } 1512 1513 DeclContext *DeclContext::getEnclosingNamespaceContext() { 1514 DeclContext *Ctx = this; 1515 // Skip through non-namespace, non-translation-unit contexts. 1516 while (!Ctx->isFileContext()) 1517 Ctx = Ctx->getParent(); 1518 return Ctx->getPrimaryContext(); 1519 } 1520 1521 RecordDecl *DeclContext::getOuterLexicalRecordContext() { 1522 // Loop until we find a non-record context. 1523 RecordDecl *OutermostRD = nullptr; 1524 DeclContext *DC = this; 1525 while (DC->isRecord()) { 1526 OutermostRD = cast<RecordDecl>(DC); 1527 DC = DC->getLexicalParent(); 1528 } 1529 return OutermostRD; 1530 } 1531 1532 bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const { 1533 // For non-file contexts, this is equivalent to Equals. 1534 if (!isFileContext()) 1535 return O->Equals(this); 1536 1537 do { 1538 if (O->Equals(this)) 1539 return true; 1540 1541 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O); 1542 if (!NS || !NS->isInline()) 1543 break; 1544 O = NS->getParent(); 1545 } while (O); 1546 1547 return false; 1548 } 1549 1550 void DeclContext::makeDeclVisibleInContext(NamedDecl *D) { 1551 DeclContext *PrimaryDC = this->getPrimaryContext(); 1552 DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext(); 1553 // If the decl is being added outside of its semantic decl context, we 1554 // need to ensure that we eagerly build the lookup information for it. 1555 PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC); 1556 } 1557 1558 void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal, 1559 bool Recoverable) { 1560 assert(this == getPrimaryContext() && "expected a primary DC"); 1561 1562 // Skip declarations within functions. 1563 if (isFunctionOrMethod()) 1564 return; 1565 1566 // Skip declarations which should be invisible to name lookup. 1567 if (shouldBeHidden(D)) 1568 return; 1569 1570 // If we already have a lookup data structure, perform the insertion into 1571 // it. If we might have externally-stored decls with this name, look them 1572 // up and perform the insertion. If this decl was declared outside its 1573 // semantic context, buildLookup won't add it, so add it now. 1574 // 1575 // FIXME: As a performance hack, don't add such decls into the translation 1576 // unit unless we're in C++, since qualified lookup into the TU is never 1577 // performed. 1578 if (LookupPtr || hasExternalVisibleStorage() || 1579 ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) && 1580 (getParentASTContext().getLangOpts().CPlusPlus || 1581 !isTranslationUnit()))) { 1582 // If we have lazily omitted any decls, they might have the same name as 1583 // the decl which we are adding, so build a full lookup table before adding 1584 // this decl. 1585 buildLookup(); 1586 makeDeclVisibleInContextImpl(D, Internal); 1587 } else { 1588 HasLazyLocalLexicalLookups = true; 1589 } 1590 1591 // If we are a transparent context or inline namespace, insert into our 1592 // parent context, too. This operation is recursive. 1593 if (isTransparentContext() || isInlineNamespace()) 1594 getParent()->getPrimaryContext()-> 1595 makeDeclVisibleInContextWithFlags(D, Internal, Recoverable); 1596 1597 Decl *DCAsDecl = cast<Decl>(this); 1598 // Notify that a decl was made visible unless we are a Tag being defined. 1599 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined())) 1600 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener()) 1601 L->AddedVisibleDecl(this, D); 1602 } 1603 1604 void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) { 1605 // Find or create the stored declaration map. 1606 StoredDeclsMap *Map = LookupPtr; 1607 if (!Map) { 1608 ASTContext *C = &getParentASTContext(); 1609 Map = CreateStoredDeclsMap(*C); 1610 } 1611 1612 // If there is an external AST source, load any declarations it knows about 1613 // with this declaration's name. 1614 // If the lookup table contains an entry about this name it means that we 1615 // have already checked the external source. 1616 if (!Internal) 1617 if (ExternalASTSource *Source = getParentASTContext().getExternalSource()) 1618 if (hasExternalVisibleStorage() && 1619 Map->find(D->getDeclName()) == Map->end()) 1620 Source->FindExternalVisibleDeclsByName(this, D->getDeclName()); 1621 1622 // Insert this declaration into the map. 1623 StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()]; 1624 1625 if (Internal) { 1626 // If this is being added as part of loading an external declaration, 1627 // this may not be the only external declaration with this name. 1628 // In this case, we never try to replace an existing declaration; we'll 1629 // handle that when we finalize the list of declarations for this name. 1630 DeclNameEntries.setHasExternalDecls(); 1631 DeclNameEntries.AddSubsequentDecl(D); 1632 return; 1633 } 1634 1635 if (DeclNameEntries.isNull()) { 1636 DeclNameEntries.setOnlyValue(D); 1637 return; 1638 } 1639 1640 if (DeclNameEntries.HandleRedeclaration(D, /*IsKnownNewer*/!Internal)) { 1641 // This declaration has replaced an existing one for which 1642 // declarationReplaces returns true. 1643 return; 1644 } 1645 1646 // Put this declaration into the appropriate slot. 1647 DeclNameEntries.AddSubsequentDecl(D); 1648 } 1649 1650 UsingDirectiveDecl *DeclContext::udir_iterator::operator*() const { 1651 return cast<UsingDirectiveDecl>(*I); 1652 } 1653 1654 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within 1655 /// this context. 1656 DeclContext::udir_range DeclContext::using_directives() const { 1657 // FIXME: Use something more efficient than normal lookup for using 1658 // directives. In C++, using directives are looked up more than anything else. 1659 lookup_result Result = lookup(UsingDirectiveDecl::getName()); 1660 return udir_range(Result.begin(), Result.end()); 1661 } 1662 1663 //===----------------------------------------------------------------------===// 1664 // Creation and Destruction of StoredDeclsMaps. // 1665 //===----------------------------------------------------------------------===// 1666 1667 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const { 1668 assert(!LookupPtr && "context already has a decls map"); 1669 assert(getPrimaryContext() == this && 1670 "creating decls map on non-primary context"); 1671 1672 StoredDeclsMap *M; 1673 bool Dependent = isDependentContext(); 1674 if (Dependent) 1675 M = new DependentStoredDeclsMap(); 1676 else 1677 M = new StoredDeclsMap(); 1678 M->Previous = C.LastSDM; 1679 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent); 1680 LookupPtr = M; 1681 return M; 1682 } 1683 1684 void ASTContext::ReleaseDeclContextMaps() { 1685 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap 1686 // pointer because the subclass doesn't add anything that needs to 1687 // be deleted. 1688 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt()); 1689 } 1690 1691 void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) { 1692 while (Map) { 1693 // Advance the iteration before we invalidate memory. 1694 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous; 1695 1696 if (Dependent) 1697 delete static_cast<DependentStoredDeclsMap*>(Map); 1698 else 1699 delete Map; 1700 1701 Map = Next.getPointer(); 1702 Dependent = Next.getInt(); 1703 } 1704 } 1705 1706 DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C, 1707 DeclContext *Parent, 1708 const PartialDiagnostic &PDiag) { 1709 assert(Parent->isDependentContext() 1710 && "cannot iterate dependent diagnostics of non-dependent context"); 1711 Parent = Parent->getPrimaryContext(); 1712 if (!Parent->LookupPtr) 1713 Parent->CreateStoredDeclsMap(C); 1714 1715 DependentStoredDeclsMap *Map = 1716 static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr); 1717 1718 // Allocate the copy of the PartialDiagnostic via the ASTContext's 1719 // BumpPtrAllocator, rather than the ASTContext itself. 1720 PartialDiagnostic::Storage *DiagStorage = nullptr; 1721 if (PDiag.hasStorage()) 1722 DiagStorage = new (C) PartialDiagnostic::Storage; 1723 1724 DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage); 1725 1726 // TODO: Maybe we shouldn't reverse the order during insertion. 1727 DD->NextDiagnostic = Map->FirstDiagnostic; 1728 Map->FirstDiagnostic = DD; 1729 1730 return DD; 1731 } 1732