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