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