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