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