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