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 // 7. it's a block literal declaration 895 if (isa<TranslationUnitDecl>(this) || 896 isa<TemplateTypeParmDecl>(this) || 897 isa<NonTypeTemplateParmDecl>(this) || 898 !isa<CXXRecordDecl>(getDeclContext()) || 899 isInvalidDecl() || 900 isa<StaticAssertDecl>(this) || 901 isa<BlockDecl>(this) || 902 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization 903 // as DeclContext (?). 904 isa<ParmVarDecl>(this) || 905 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have 906 // AS_none as access specifier. 907 isa<CXXRecordDecl>(this) || 908 isa<ClassScopeFunctionSpecializationDecl>(this)) 909 return true; 910 911 assert(Access != AS_none && 912 "Access specifier is AS_none inside a record decl"); 913 #endif 914 return true; 915 } 916 917 static Decl::Kind getKind(const Decl *D) { return D->getKind(); } 918 static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); } 919 920 const FunctionType *Decl::getFunctionType(bool BlocksToo) const { 921 QualType Ty; 922 if (const ValueDecl *D = dyn_cast<ValueDecl>(this)) 923 Ty = D->getType(); 924 else if (const TypedefNameDecl *D = dyn_cast<TypedefNameDecl>(this)) 925 Ty = D->getUnderlyingType(); 926 else 927 return nullptr; 928 929 if (Ty->isFunctionPointerType()) 930 Ty = Ty->getAs<PointerType>()->getPointeeType(); 931 else if (BlocksToo && Ty->isBlockPointerType()) 932 Ty = Ty->getAs<BlockPointerType>()->getPointeeType(); 933 934 return Ty->getAs<FunctionType>(); 935 } 936 937 /// Starting at a given context (a Decl or DeclContext), look for a 938 /// code context that is not a closure (a lambda, block, etc.). 939 template <class T> static Decl *getNonClosureContext(T *D) { 940 if (getKind(D) == Decl::CXXMethod) { 941 CXXMethodDecl *MD = cast<CXXMethodDecl>(D); 942 if (MD->getOverloadedOperator() == OO_Call && 943 MD->getParent()->isLambda()) 944 return getNonClosureContext(MD->getParent()->getParent()); 945 return MD; 946 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 947 return FD; 948 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 949 return MD; 950 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) { 951 return getNonClosureContext(BD->getParent()); 952 } else if (CapturedDecl *CD = dyn_cast<CapturedDecl>(D)) { 953 return getNonClosureContext(CD->getParent()); 954 } else { 955 return nullptr; 956 } 957 } 958 959 Decl *Decl::getNonClosureContext() { 960 return ::getNonClosureContext(this); 961 } 962 963 Decl *DeclContext::getNonClosureAncestor() { 964 return ::getNonClosureContext(this); 965 } 966 967 //===----------------------------------------------------------------------===// 968 // DeclContext Implementation 969 //===----------------------------------------------------------------------===// 970 971 bool DeclContext::classof(const Decl *D) { 972 switch (D->getKind()) { 973 #define DECL(NAME, BASE) 974 #define DECL_CONTEXT(NAME) case Decl::NAME: 975 #define DECL_CONTEXT_BASE(NAME) 976 #include "clang/AST/DeclNodes.inc" 977 return true; 978 default: 979 #define DECL(NAME, BASE) 980 #define DECL_CONTEXT_BASE(NAME) \ 981 if (D->getKind() >= Decl::first##NAME && \ 982 D->getKind() <= Decl::last##NAME) \ 983 return true; 984 #include "clang/AST/DeclNodes.inc" 985 return false; 986 } 987 } 988 989 DeclContext::~DeclContext() = default; 990 991 /// \brief Find the parent context of this context that will be 992 /// used for unqualified name lookup. 993 /// 994 /// Generally, the parent lookup context is the semantic context. However, for 995 /// a friend function the parent lookup context is the lexical context, which 996 /// is the class in which the friend is declared. 997 DeclContext *DeclContext::getLookupParent() { 998 // FIXME: Find a better way to identify friends 999 if (isa<FunctionDecl>(this)) 1000 if (getParent()->getRedeclContext()->isFileContext() && 1001 getLexicalParent()->getRedeclContext()->isRecord()) 1002 return getLexicalParent(); 1003 1004 return getParent(); 1005 } 1006 1007 bool DeclContext::isInlineNamespace() const { 1008 return isNamespace() && 1009 cast<NamespaceDecl>(this)->isInline(); 1010 } 1011 1012 bool DeclContext::isStdNamespace() const { 1013 if (!isNamespace()) 1014 return false; 1015 1016 const NamespaceDecl *ND = cast<NamespaceDecl>(this); 1017 if (ND->isInline()) { 1018 return ND->getParent()->isStdNamespace(); 1019 } 1020 1021 if (!getParent()->getRedeclContext()->isTranslationUnit()) 1022 return false; 1023 1024 const IdentifierInfo *II = ND->getIdentifier(); 1025 return II && II->isStr("std"); 1026 } 1027 1028 bool DeclContext::isDependentContext() const { 1029 if (isFileContext()) 1030 return false; 1031 1032 if (isa<ClassTemplatePartialSpecializationDecl>(this)) 1033 return true; 1034 1035 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) { 1036 if (Record->getDescribedClassTemplate()) 1037 return true; 1038 1039 if (Record->isDependentLambda()) 1040 return true; 1041 } 1042 1043 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) { 1044 if (Function->getDescribedFunctionTemplate()) 1045 return true; 1046 1047 // Friend function declarations are dependent if their *lexical* 1048 // context is dependent. 1049 if (cast<Decl>(this)->getFriendObjectKind()) 1050 return getLexicalParent()->isDependentContext(); 1051 } 1052 1053 // FIXME: A variable template is a dependent context, but is not a 1054 // DeclContext. A context within it (such as a lambda-expression) 1055 // should be considered dependent. 1056 1057 return getParent() && getParent()->isDependentContext(); 1058 } 1059 1060 bool DeclContext::isTransparentContext() const { 1061 if (DeclKind == Decl::Enum) 1062 return !cast<EnumDecl>(this)->isScoped(); 1063 else if (DeclKind == Decl::LinkageSpec || DeclKind == Decl::Export) 1064 return true; 1065 1066 return false; 1067 } 1068 1069 static bool isLinkageSpecContext(const DeclContext *DC, 1070 LinkageSpecDecl::LanguageIDs ID) { 1071 while (DC->getDeclKind() != Decl::TranslationUnit) { 1072 if (DC->getDeclKind() == Decl::LinkageSpec) 1073 return cast<LinkageSpecDecl>(DC)->getLanguage() == ID; 1074 DC = DC->getLexicalParent(); 1075 } 1076 return false; 1077 } 1078 1079 bool DeclContext::isExternCContext() const { 1080 return isLinkageSpecContext(this, LinkageSpecDecl::lang_c); 1081 } 1082 1083 const LinkageSpecDecl *DeclContext::getExternCContext() const { 1084 const DeclContext *DC = this; 1085 while (DC->getDeclKind() != Decl::TranslationUnit) { 1086 if (DC->getDeclKind() == Decl::LinkageSpec && 1087 cast<LinkageSpecDecl>(DC)->getLanguage() == LinkageSpecDecl::lang_c) 1088 return cast<LinkageSpecDecl>(DC); 1089 DC = DC->getLexicalParent(); 1090 } 1091 return nullptr; 1092 } 1093 1094 bool DeclContext::isExternCXXContext() const { 1095 return isLinkageSpecContext(this, LinkageSpecDecl::lang_cxx); 1096 } 1097 1098 bool DeclContext::Encloses(const DeclContext *DC) const { 1099 if (getPrimaryContext() != this) 1100 return getPrimaryContext()->Encloses(DC); 1101 1102 for (; DC; DC = DC->getParent()) 1103 if (DC->getPrimaryContext() == this) 1104 return true; 1105 return false; 1106 } 1107 1108 DeclContext *DeclContext::getPrimaryContext() { 1109 switch (DeclKind) { 1110 case Decl::TranslationUnit: 1111 case Decl::ExternCContext: 1112 case Decl::LinkageSpec: 1113 case Decl::Export: 1114 case Decl::Block: 1115 case Decl::Captured: 1116 case Decl::OMPDeclareReduction: 1117 // There is only one DeclContext for these entities. 1118 return this; 1119 1120 case Decl::Namespace: 1121 // The original namespace is our primary context. 1122 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace(); 1123 1124 case Decl::ObjCMethod: 1125 return this; 1126 1127 case Decl::ObjCInterface: 1128 if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition()) 1129 return Def; 1130 return this; 1131 1132 case Decl::ObjCProtocol: 1133 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition()) 1134 return Def; 1135 return this; 1136 1137 case Decl::ObjCCategory: 1138 return this; 1139 1140 case Decl::ObjCImplementation: 1141 case Decl::ObjCCategoryImpl: 1142 return this; 1143 1144 default: 1145 if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) { 1146 // If this is a tag type that has a definition or is currently 1147 // being defined, that definition is our primary context. 1148 TagDecl *Tag = cast<TagDecl>(this); 1149 1150 if (TagDecl *Def = Tag->getDefinition()) 1151 return Def; 1152 1153 if (const TagType *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) { 1154 // Note, TagType::getDecl returns the (partial) definition one exists. 1155 TagDecl *PossiblePartialDef = TagTy->getDecl(); 1156 if (PossiblePartialDef->isBeingDefined()) 1157 return PossiblePartialDef; 1158 } else { 1159 assert(isa<InjectedClassNameType>(Tag->getTypeForDecl())); 1160 } 1161 1162 return Tag; 1163 } 1164 1165 assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction && 1166 "Unknown DeclContext kind"); 1167 return this; 1168 } 1169 } 1170 1171 void 1172 DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){ 1173 Contexts.clear(); 1174 1175 if (DeclKind != Decl::Namespace) { 1176 Contexts.push_back(this); 1177 return; 1178 } 1179 1180 NamespaceDecl *Self = static_cast<NamespaceDecl *>(this); 1181 for (NamespaceDecl *N = Self->getMostRecentDecl(); N; 1182 N = N->getPreviousDecl()) 1183 Contexts.push_back(N); 1184 1185 std::reverse(Contexts.begin(), Contexts.end()); 1186 } 1187 1188 std::pair<Decl *, Decl *> 1189 DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls, 1190 bool FieldsAlreadyLoaded) { 1191 // Build up a chain of declarations via the Decl::NextInContextAndBits field. 1192 Decl *FirstNewDecl = nullptr; 1193 Decl *PrevDecl = nullptr; 1194 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 1195 if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I])) 1196 continue; 1197 1198 Decl *D = Decls[I]; 1199 if (PrevDecl) 1200 PrevDecl->NextInContextAndBits.setPointer(D); 1201 else 1202 FirstNewDecl = D; 1203 1204 PrevDecl = D; 1205 } 1206 1207 return std::make_pair(FirstNewDecl, PrevDecl); 1208 } 1209 1210 /// \brief We have just acquired external visible storage, and we already have 1211 /// built a lookup map. For every name in the map, pull in the new names from 1212 /// the external storage. 1213 void DeclContext::reconcileExternalVisibleStorage() const { 1214 assert(NeedToReconcileExternalVisibleStorage && LookupPtr); 1215 NeedToReconcileExternalVisibleStorage = false; 1216 1217 for (auto &Lookup : *LookupPtr) 1218 Lookup.second.setHasExternalDecls(); 1219 } 1220 1221 /// \brief Load the declarations within this lexical storage from an 1222 /// external source. 1223 /// \return \c true if any declarations were added. 1224 bool 1225 DeclContext::LoadLexicalDeclsFromExternalStorage() const { 1226 ExternalASTSource *Source = getParentASTContext().getExternalSource(); 1227 assert(hasExternalLexicalStorage() && Source && "No external storage?"); 1228 1229 // Notify that we have a DeclContext that is initializing. 1230 ExternalASTSource::Deserializing ADeclContext(Source); 1231 1232 // Load the external declarations, if any. 1233 SmallVector<Decl*, 64> Decls; 1234 ExternalLexicalStorage = false; 1235 Source->FindExternalLexicalDecls(this, Decls); 1236 1237 if (Decls.empty()) 1238 return false; 1239 1240 // We may have already loaded just the fields of this record, in which case 1241 // we need to ignore them. 1242 bool FieldsAlreadyLoaded = false; 1243 if (const RecordDecl *RD = dyn_cast<RecordDecl>(this)) 1244 FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage; 1245 1246 // Splice the newly-read declarations into the beginning of the list 1247 // of declarations. 1248 Decl *ExternalFirst, *ExternalLast; 1249 std::tie(ExternalFirst, ExternalLast) = 1250 BuildDeclChain(Decls, FieldsAlreadyLoaded); 1251 ExternalLast->NextInContextAndBits.setPointer(FirstDecl); 1252 FirstDecl = ExternalFirst; 1253 if (!LastDecl) 1254 LastDecl = ExternalLast; 1255 return true; 1256 } 1257 1258 DeclContext::lookup_result 1259 ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC, 1260 DeclarationName Name) { 1261 ASTContext &Context = DC->getParentASTContext(); 1262 StoredDeclsMap *Map; 1263 if (!(Map = DC->LookupPtr)) 1264 Map = DC->CreateStoredDeclsMap(Context); 1265 if (DC->NeedToReconcileExternalVisibleStorage) 1266 DC->reconcileExternalVisibleStorage(); 1267 1268 (*Map)[Name].removeExternalDecls(); 1269 1270 return DeclContext::lookup_result(); 1271 } 1272 1273 DeclContext::lookup_result 1274 ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC, 1275 DeclarationName Name, 1276 ArrayRef<NamedDecl*> Decls) { 1277 ASTContext &Context = DC->getParentASTContext(); 1278 StoredDeclsMap *Map; 1279 if (!(Map = DC->LookupPtr)) 1280 Map = DC->CreateStoredDeclsMap(Context); 1281 if (DC->NeedToReconcileExternalVisibleStorage) 1282 DC->reconcileExternalVisibleStorage(); 1283 1284 StoredDeclsList &List = (*Map)[Name]; 1285 1286 // Clear out any old external visible declarations, to avoid quadratic 1287 // performance in the redeclaration checks below. 1288 List.removeExternalDecls(); 1289 1290 if (!List.isNull()) { 1291 // We have both existing declarations and new declarations for this name. 1292 // Some of the declarations may simply replace existing ones. Handle those 1293 // first. 1294 llvm::SmallVector<unsigned, 8> Skip; 1295 for (unsigned I = 0, N = Decls.size(); I != N; ++I) 1296 if (List.HandleRedeclaration(Decls[I], /*IsKnownNewer*/false)) 1297 Skip.push_back(I); 1298 Skip.push_back(Decls.size()); 1299 1300 // Add in any new declarations. 1301 unsigned SkipPos = 0; 1302 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 1303 if (I == Skip[SkipPos]) 1304 ++SkipPos; 1305 else 1306 List.AddSubsequentDecl(Decls[I]); 1307 } 1308 } else { 1309 // Convert the array to a StoredDeclsList. 1310 for (ArrayRef<NamedDecl*>::iterator 1311 I = Decls.begin(), E = Decls.end(); I != E; ++I) { 1312 if (List.isNull()) 1313 List.setOnlyValue(*I); 1314 else 1315 List.AddSubsequentDecl(*I); 1316 } 1317 } 1318 1319 return List.getLookupResult(); 1320 } 1321 1322 DeclContext::decl_iterator DeclContext::decls_begin() const { 1323 if (hasExternalLexicalStorage()) 1324 LoadLexicalDeclsFromExternalStorage(); 1325 return decl_iterator(FirstDecl); 1326 } 1327 1328 bool DeclContext::decls_empty() const { 1329 if (hasExternalLexicalStorage()) 1330 LoadLexicalDeclsFromExternalStorage(); 1331 1332 return !FirstDecl; 1333 } 1334 1335 bool DeclContext::containsDecl(Decl *D) const { 1336 return (D->getLexicalDeclContext() == this && 1337 (D->NextInContextAndBits.getPointer() || D == LastDecl)); 1338 } 1339 1340 void DeclContext::removeDecl(Decl *D) { 1341 assert(D->getLexicalDeclContext() == this && 1342 "decl being removed from non-lexical context"); 1343 assert((D->NextInContextAndBits.getPointer() || D == LastDecl) && 1344 "decl is not in decls list"); 1345 1346 // Remove D from the decl chain. This is O(n) but hopefully rare. 1347 if (D == FirstDecl) { 1348 if (D == LastDecl) 1349 FirstDecl = LastDecl = nullptr; 1350 else 1351 FirstDecl = D->NextInContextAndBits.getPointer(); 1352 } else { 1353 for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) { 1354 assert(I && "decl not found in linked list"); 1355 if (I->NextInContextAndBits.getPointer() == D) { 1356 I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer()); 1357 if (D == LastDecl) LastDecl = I; 1358 break; 1359 } 1360 } 1361 } 1362 1363 // Mark that D is no longer in the decl chain. 1364 D->NextInContextAndBits.setPointer(nullptr); 1365 1366 // Remove D from the lookup table if necessary. 1367 if (isa<NamedDecl>(D)) { 1368 NamedDecl *ND = cast<NamedDecl>(D); 1369 1370 // Remove only decls that have a name 1371 if (!ND->getDeclName()) return; 1372 1373 auto *DC = D->getDeclContext(); 1374 do { 1375 StoredDeclsMap *Map = DC->getPrimaryContext()->LookupPtr; 1376 if (Map) { 1377 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName()); 1378 assert(Pos != Map->end() && "no lookup entry for decl"); 1379 if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND) 1380 Pos->second.remove(ND); 1381 } 1382 } while (DC->isTransparentContext() && (DC = DC->getParent())); 1383 } 1384 } 1385 1386 void DeclContext::addHiddenDecl(Decl *D) { 1387 assert(D->getLexicalDeclContext() == this && 1388 "Decl inserted into wrong lexical context"); 1389 assert(!D->getNextDeclInContext() && D != LastDecl && 1390 "Decl already inserted into a DeclContext"); 1391 1392 if (FirstDecl) { 1393 LastDecl->NextInContextAndBits.setPointer(D); 1394 LastDecl = D; 1395 } else { 1396 FirstDecl = LastDecl = D; 1397 } 1398 1399 // Notify a C++ record declaration that we've added a member, so it can 1400 // update its class-specific state. 1401 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) 1402 Record->addedMember(D); 1403 1404 // If this is a newly-created (not de-serialized) import declaration, wire 1405 // it in to the list of local import declarations. 1406 if (!D->isFromASTFile()) { 1407 if (ImportDecl *Import = dyn_cast<ImportDecl>(D)) 1408 D->getASTContext().addedLocalImportDecl(Import); 1409 } 1410 } 1411 1412 void DeclContext::addDecl(Decl *D) { 1413 addHiddenDecl(D); 1414 1415 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) 1416 ND->getDeclContext()->getPrimaryContext()-> 1417 makeDeclVisibleInContextWithFlags(ND, false, true); 1418 } 1419 1420 void DeclContext::addDeclInternal(Decl *D) { 1421 addHiddenDecl(D); 1422 1423 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) 1424 ND->getDeclContext()->getPrimaryContext()-> 1425 makeDeclVisibleInContextWithFlags(ND, true, true); 1426 } 1427 1428 /// shouldBeHidden - Determine whether a declaration which was declared 1429 /// within its semantic context should be invisible to qualified name lookup. 1430 static bool shouldBeHidden(NamedDecl *D) { 1431 // Skip unnamed declarations. 1432 if (!D->getDeclName()) 1433 return true; 1434 1435 // Skip entities that can't be found by name lookup into a particular 1436 // context. 1437 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) || 1438 D->isTemplateParameter()) 1439 return true; 1440 1441 // Skip template specializations. 1442 // FIXME: This feels like a hack. Should DeclarationName support 1443 // template-ids, or is there a better way to keep specializations 1444 // from being visible? 1445 if (isa<ClassTemplateSpecializationDecl>(D)) 1446 return true; 1447 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 1448 if (FD->isFunctionTemplateSpecialization()) 1449 return true; 1450 1451 return false; 1452 } 1453 1454 /// buildLookup - Build the lookup data structure with all of the 1455 /// declarations in this DeclContext (and any other contexts linked 1456 /// to it or transparent contexts nested within it) and return it. 1457 /// 1458 /// Note that the produced map may miss out declarations from an 1459 /// external source. If it does, those entries will be marked with 1460 /// the 'hasExternalDecls' flag. 1461 StoredDeclsMap *DeclContext::buildLookup() { 1462 assert(this == getPrimaryContext() && "buildLookup called on non-primary DC"); 1463 1464 if (!HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups) 1465 return LookupPtr; 1466 1467 SmallVector<DeclContext *, 2> Contexts; 1468 collectAllContexts(Contexts); 1469 1470 if (HasLazyExternalLexicalLookups) { 1471 HasLazyExternalLexicalLookups = false; 1472 for (auto *DC : Contexts) { 1473 if (DC->hasExternalLexicalStorage()) 1474 HasLazyLocalLexicalLookups |= 1475 DC->LoadLexicalDeclsFromExternalStorage(); 1476 } 1477 1478 if (!HasLazyLocalLexicalLookups) 1479 return LookupPtr; 1480 } 1481 1482 for (auto *DC : Contexts) 1483 buildLookupImpl(DC, hasExternalVisibleStorage()); 1484 1485 // We no longer have any lazy decls. 1486 HasLazyLocalLexicalLookups = false; 1487 return LookupPtr; 1488 } 1489 1490 /// buildLookupImpl - Build part of the lookup data structure for the 1491 /// declarations contained within DCtx, which will either be this 1492 /// DeclContext, a DeclContext linked to it, or a transparent context 1493 /// nested within it. 1494 void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) { 1495 for (Decl *D : DCtx->noload_decls()) { 1496 // Insert this declaration into the lookup structure, but only if 1497 // it's semantically within its decl context. Any other decls which 1498 // should be found in this context are added eagerly. 1499 // 1500 // If it's from an AST file, don't add it now. It'll get handled by 1501 // FindExternalVisibleDeclsByName if needed. Exception: if we're not 1502 // in C++, we do not track external visible decls for the TU, so in 1503 // that case we need to collect them all here. 1504 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) 1505 if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) && 1506 (!ND->isFromASTFile() || 1507 (isTranslationUnit() && 1508 !getParentASTContext().getLangOpts().CPlusPlus))) 1509 makeDeclVisibleInContextImpl(ND, Internal); 1510 1511 // If this declaration is itself a transparent declaration context 1512 // or inline namespace, add the members of this declaration of that 1513 // context (recursively). 1514 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D)) 1515 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace()) 1516 buildLookupImpl(InnerCtx, Internal); 1517 } 1518 } 1519 1520 NamedDecl *const DeclContextLookupResult::SingleElementDummyList = nullptr; 1521 1522 DeclContext::lookup_result 1523 DeclContext::lookup(DeclarationName Name) const { 1524 assert(DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export && 1525 "should not perform lookups into transparent contexts"); 1526 1527 const DeclContext *PrimaryContext = getPrimaryContext(); 1528 if (PrimaryContext != this) 1529 return PrimaryContext->lookup(Name); 1530 1531 // If we have an external source, ensure that any later redeclarations of this 1532 // context have been loaded, since they may add names to the result of this 1533 // lookup (or add external visible storage). 1534 ExternalASTSource *Source = getParentASTContext().getExternalSource(); 1535 if (Source) 1536 (void)cast<Decl>(this)->getMostRecentDecl(); 1537 1538 if (hasExternalVisibleStorage()) { 1539 assert(Source && "external visible storage but no external source?"); 1540 1541 if (NeedToReconcileExternalVisibleStorage) 1542 reconcileExternalVisibleStorage(); 1543 1544 StoredDeclsMap *Map = LookupPtr; 1545 1546 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups) 1547 // FIXME: Make buildLookup const? 1548 Map = const_cast<DeclContext*>(this)->buildLookup(); 1549 1550 if (!Map) 1551 Map = CreateStoredDeclsMap(getParentASTContext()); 1552 1553 // If we have a lookup result with no external decls, we are done. 1554 std::pair<StoredDeclsMap::iterator, bool> R = 1555 Map->insert(std::make_pair(Name, StoredDeclsList())); 1556 if (!R.second && !R.first->second.hasExternalDecls()) 1557 return R.first->second.getLookupResult(); 1558 1559 if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) { 1560 if (StoredDeclsMap *Map = LookupPtr) { 1561 StoredDeclsMap::iterator I = Map->find(Name); 1562 if (I != Map->end()) 1563 return I->second.getLookupResult(); 1564 } 1565 } 1566 1567 return lookup_result(); 1568 } 1569 1570 StoredDeclsMap *Map = LookupPtr; 1571 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups) 1572 Map = const_cast<DeclContext*>(this)->buildLookup(); 1573 1574 if (!Map) 1575 return lookup_result(); 1576 1577 StoredDeclsMap::iterator I = Map->find(Name); 1578 if (I == Map->end()) 1579 return lookup_result(); 1580 1581 return I->second.getLookupResult(); 1582 } 1583 1584 DeclContext::lookup_result 1585 DeclContext::noload_lookup(DeclarationName Name) { 1586 assert(DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export && 1587 "should not perform lookups into transparent contexts"); 1588 1589 DeclContext *PrimaryContext = getPrimaryContext(); 1590 if (PrimaryContext != this) 1591 return PrimaryContext->noload_lookup(Name); 1592 1593 loadLazyLocalLexicalLookups(); 1594 StoredDeclsMap *Map = LookupPtr; 1595 if (!Map) 1596 return lookup_result(); 1597 1598 StoredDeclsMap::iterator I = Map->find(Name); 1599 return I != Map->end() ? I->second.getLookupResult() 1600 : lookup_result(); 1601 } 1602 1603 // If we have any lazy lexical declarations not in our lookup map, add them 1604 // now. Don't import any external declarations, not even if we know we have 1605 // some missing from the external visible lookups. 1606 void DeclContext::loadLazyLocalLexicalLookups() { 1607 if (HasLazyLocalLexicalLookups) { 1608 SmallVector<DeclContext *, 2> Contexts; 1609 collectAllContexts(Contexts); 1610 for (unsigned I = 0, N = Contexts.size(); I != N; ++I) 1611 buildLookupImpl(Contexts[I], hasExternalVisibleStorage()); 1612 HasLazyLocalLexicalLookups = false; 1613 } 1614 } 1615 1616 void DeclContext::localUncachedLookup(DeclarationName Name, 1617 SmallVectorImpl<NamedDecl *> &Results) { 1618 Results.clear(); 1619 1620 // If there's no external storage, just perform a normal lookup and copy 1621 // the results. 1622 if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) { 1623 lookup_result LookupResults = lookup(Name); 1624 Results.insert(Results.end(), LookupResults.begin(), LookupResults.end()); 1625 return; 1626 } 1627 1628 // If we have a lookup table, check there first. Maybe we'll get lucky. 1629 // FIXME: Should we be checking these flags on the primary context? 1630 if (Name && !HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups) { 1631 if (StoredDeclsMap *Map = LookupPtr) { 1632 StoredDeclsMap::iterator Pos = Map->find(Name); 1633 if (Pos != Map->end()) { 1634 Results.insert(Results.end(), 1635 Pos->second.getLookupResult().begin(), 1636 Pos->second.getLookupResult().end()); 1637 return; 1638 } 1639 } 1640 } 1641 1642 // Slow case: grovel through the declarations in our chain looking for 1643 // matches. 1644 // FIXME: If we have lazy external declarations, this will not find them! 1645 // FIXME: Should we CollectAllContexts and walk them all here? 1646 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) { 1647 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) 1648 if (ND->getDeclName() == Name) 1649 Results.push_back(ND); 1650 } 1651 } 1652 1653 DeclContext *DeclContext::getRedeclContext() { 1654 DeclContext *Ctx = this; 1655 // Skip through transparent contexts. 1656 while (Ctx->isTransparentContext()) 1657 Ctx = Ctx->getParent(); 1658 return Ctx; 1659 } 1660 1661 DeclContext *DeclContext::getEnclosingNamespaceContext() { 1662 DeclContext *Ctx = this; 1663 // Skip through non-namespace, non-translation-unit contexts. 1664 while (!Ctx->isFileContext()) 1665 Ctx = Ctx->getParent(); 1666 return Ctx->getPrimaryContext(); 1667 } 1668 1669 RecordDecl *DeclContext::getOuterLexicalRecordContext() { 1670 // Loop until we find a non-record context. 1671 RecordDecl *OutermostRD = nullptr; 1672 DeclContext *DC = this; 1673 while (DC->isRecord()) { 1674 OutermostRD = cast<RecordDecl>(DC); 1675 DC = DC->getLexicalParent(); 1676 } 1677 return OutermostRD; 1678 } 1679 1680 bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const { 1681 // For non-file contexts, this is equivalent to Equals. 1682 if (!isFileContext()) 1683 return O->Equals(this); 1684 1685 do { 1686 if (O->Equals(this)) 1687 return true; 1688 1689 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O); 1690 if (!NS || !NS->isInline()) 1691 break; 1692 O = NS->getParent(); 1693 } while (O); 1694 1695 return false; 1696 } 1697 1698 void DeclContext::makeDeclVisibleInContext(NamedDecl *D) { 1699 DeclContext *PrimaryDC = this->getPrimaryContext(); 1700 DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext(); 1701 // If the decl is being added outside of its semantic decl context, we 1702 // need to ensure that we eagerly build the lookup information for it. 1703 PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC); 1704 } 1705 1706 void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal, 1707 bool Recoverable) { 1708 assert(this == getPrimaryContext() && "expected a primary DC"); 1709 1710 if (!isLookupContext()) { 1711 if (isTransparentContext()) 1712 getParent()->getPrimaryContext() 1713 ->makeDeclVisibleInContextWithFlags(D, Internal, Recoverable); 1714 return; 1715 } 1716 1717 // Skip declarations which should be invisible to name lookup. 1718 if (shouldBeHidden(D)) 1719 return; 1720 1721 // If we already have a lookup data structure, perform the insertion into 1722 // it. If we might have externally-stored decls with this name, look them 1723 // up and perform the insertion. If this decl was declared outside its 1724 // semantic context, buildLookup won't add it, so add it now. 1725 // 1726 // FIXME: As a performance hack, don't add such decls into the translation 1727 // unit unless we're in C++, since qualified lookup into the TU is never 1728 // performed. 1729 if (LookupPtr || hasExternalVisibleStorage() || 1730 ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) && 1731 (getParentASTContext().getLangOpts().CPlusPlus || 1732 !isTranslationUnit()))) { 1733 // If we have lazily omitted any decls, they might have the same name as 1734 // the decl which we are adding, so build a full lookup table before adding 1735 // this decl. 1736 buildLookup(); 1737 makeDeclVisibleInContextImpl(D, Internal); 1738 } else { 1739 HasLazyLocalLexicalLookups = true; 1740 } 1741 1742 // If we are a transparent context or inline namespace, insert into our 1743 // parent context, too. This operation is recursive. 1744 if (isTransparentContext() || isInlineNamespace()) 1745 getParent()->getPrimaryContext()-> 1746 makeDeclVisibleInContextWithFlags(D, Internal, Recoverable); 1747 1748 Decl *DCAsDecl = cast<Decl>(this); 1749 // Notify that a decl was made visible unless we are a Tag being defined. 1750 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined())) 1751 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener()) 1752 L->AddedVisibleDecl(this, D); 1753 } 1754 1755 void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) { 1756 // Find or create the stored declaration map. 1757 StoredDeclsMap *Map = LookupPtr; 1758 if (!Map) { 1759 ASTContext *C = &getParentASTContext(); 1760 Map = CreateStoredDeclsMap(*C); 1761 } 1762 1763 // If there is an external AST source, load any declarations it knows about 1764 // with this declaration's name. 1765 // If the lookup table contains an entry about this name it means that we 1766 // have already checked the external source. 1767 if (!Internal) 1768 if (ExternalASTSource *Source = getParentASTContext().getExternalSource()) 1769 if (hasExternalVisibleStorage() && 1770 Map->find(D->getDeclName()) == Map->end()) 1771 Source->FindExternalVisibleDeclsByName(this, D->getDeclName()); 1772 1773 // Insert this declaration into the map. 1774 StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()]; 1775 1776 if (Internal) { 1777 // If this is being added as part of loading an external declaration, 1778 // this may not be the only external declaration with this name. 1779 // In this case, we never try to replace an existing declaration; we'll 1780 // handle that when we finalize the list of declarations for this name. 1781 DeclNameEntries.setHasExternalDecls(); 1782 DeclNameEntries.AddSubsequentDecl(D); 1783 return; 1784 } 1785 1786 if (DeclNameEntries.isNull()) { 1787 DeclNameEntries.setOnlyValue(D); 1788 return; 1789 } 1790 1791 if (DeclNameEntries.HandleRedeclaration(D, /*IsKnownNewer*/!Internal)) { 1792 // This declaration has replaced an existing one for which 1793 // declarationReplaces returns true. 1794 return; 1795 } 1796 1797 // Put this declaration into the appropriate slot. 1798 DeclNameEntries.AddSubsequentDecl(D); 1799 } 1800 1801 UsingDirectiveDecl *DeclContext::udir_iterator::operator*() const { 1802 return cast<UsingDirectiveDecl>(*I); 1803 } 1804 1805 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within 1806 /// this context. 1807 DeclContext::udir_range DeclContext::using_directives() const { 1808 // FIXME: Use something more efficient than normal lookup for using 1809 // directives. In C++, using directives are looked up more than anything else. 1810 lookup_result Result = lookup(UsingDirectiveDecl::getName()); 1811 return udir_range(Result.begin(), Result.end()); 1812 } 1813 1814 //===----------------------------------------------------------------------===// 1815 // Creation and Destruction of StoredDeclsMaps. // 1816 //===----------------------------------------------------------------------===// 1817 1818 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const { 1819 assert(!LookupPtr && "context already has a decls map"); 1820 assert(getPrimaryContext() == this && 1821 "creating decls map on non-primary context"); 1822 1823 StoredDeclsMap *M; 1824 bool Dependent = isDependentContext(); 1825 if (Dependent) 1826 M = new DependentStoredDeclsMap(); 1827 else 1828 M = new StoredDeclsMap(); 1829 M->Previous = C.LastSDM; 1830 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent); 1831 LookupPtr = M; 1832 return M; 1833 } 1834 1835 void ASTContext::ReleaseDeclContextMaps() { 1836 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap 1837 // pointer because the subclass doesn't add anything that needs to 1838 // be deleted. 1839 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt()); 1840 } 1841 1842 void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) { 1843 while (Map) { 1844 // Advance the iteration before we invalidate memory. 1845 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous; 1846 1847 if (Dependent) 1848 delete static_cast<DependentStoredDeclsMap*>(Map); 1849 else 1850 delete Map; 1851 1852 Map = Next.getPointer(); 1853 Dependent = Next.getInt(); 1854 } 1855 } 1856 1857 DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C, 1858 DeclContext *Parent, 1859 const PartialDiagnostic &PDiag) { 1860 assert(Parent->isDependentContext() 1861 && "cannot iterate dependent diagnostics of non-dependent context"); 1862 Parent = Parent->getPrimaryContext(); 1863 if (!Parent->LookupPtr) 1864 Parent->CreateStoredDeclsMap(C); 1865 1866 DependentStoredDeclsMap *Map = 1867 static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr); 1868 1869 // Allocate the copy of the PartialDiagnostic via the ASTContext's 1870 // BumpPtrAllocator, rather than the ASTContext itself. 1871 PartialDiagnostic::Storage *DiagStorage = nullptr; 1872 if (PDiag.hasStorage()) 1873 DiagStorage = new (C) PartialDiagnostic::Storage; 1874 1875 DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage); 1876 1877 // TODO: Maybe we shouldn't reverse the order during insertion. 1878 DD->NextDiagnostic = Map->FirstDiagnostic; 1879 Map->FirstDiagnostic = DD; 1880 1881 return DD; 1882 } 1883