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 GlobalDeclID 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.get(); 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->getNonTransparentContext()->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 IdentifierInfo *IIEnv = A->getEnvironment(); 670 StringRef TargetEnv = 671 Context.getTargetInfo().getTriple().getEnvironmentName(); 672 StringRef EnvName = AvailabilityAttr::getPrettyEnviromentName( 673 Context.getTargetInfo().getTriple().getEnvironment()); 674 // Matching environment or no environment on attribute 675 if (!IIEnv || (!TargetEnv.empty() && IIEnv->getName() == TargetEnv)) { 676 if (Message) { 677 Message->clear(); 678 llvm::raw_string_ostream Out(*Message); 679 VersionTuple VTI(A->getIntroduced()); 680 Out << "introduced in " << PrettyPlatformName << " " << VTI << " " 681 << EnvName << HintMessage; 682 } 683 } 684 // Non-matching environment or no environment on target 685 else { 686 if (Message) { 687 Message->clear(); 688 llvm::raw_string_ostream Out(*Message); 689 Out << "not available on " << PrettyPlatformName << " " << EnvName 690 << HintMessage; 691 } 692 } 693 694 return A->getStrict() ? AR_Unavailable : AR_NotYetIntroduced; 695 } 696 697 // Make sure that this declaration hasn't been obsoleted. 698 if (!A->getObsoleted().empty() && EnclosingVersion >= A->getObsoleted()) { 699 if (Message) { 700 Message->clear(); 701 llvm::raw_string_ostream Out(*Message); 702 VersionTuple VTO(A->getObsoleted()); 703 Out << "obsoleted in " << PrettyPlatformName << ' ' 704 << VTO << HintMessage; 705 } 706 707 return AR_Unavailable; 708 } 709 710 // Make sure that this declaration hasn't been deprecated. 711 if (!A->getDeprecated().empty() && EnclosingVersion >= A->getDeprecated()) { 712 if (Message) { 713 Message->clear(); 714 llvm::raw_string_ostream Out(*Message); 715 VersionTuple VTD(A->getDeprecated()); 716 Out << "first deprecated in " << PrettyPlatformName << ' ' 717 << VTD << HintMessage; 718 } 719 720 return AR_Deprecated; 721 } 722 723 return AR_Available; 724 } 725 726 AvailabilityResult Decl::getAvailability(std::string *Message, 727 VersionTuple EnclosingVersion, 728 StringRef *RealizedPlatform) const { 729 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(this)) 730 return FTD->getTemplatedDecl()->getAvailability(Message, EnclosingVersion, 731 RealizedPlatform); 732 733 AvailabilityResult Result = AR_Available; 734 std::string ResultMessage; 735 736 for (const auto *A : attrs()) { 737 if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(A)) { 738 if (Result >= AR_Deprecated) 739 continue; 740 741 if (Message) 742 ResultMessage = std::string(Deprecated->getMessage()); 743 744 Result = AR_Deprecated; 745 continue; 746 } 747 748 if (const auto *Unavailable = dyn_cast<UnavailableAttr>(A)) { 749 if (Message) 750 *Message = std::string(Unavailable->getMessage()); 751 return AR_Unavailable; 752 } 753 754 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) { 755 AvailabilityResult AR = CheckAvailability(getASTContext(), Availability, 756 Message, EnclosingVersion); 757 758 if (AR == AR_Unavailable) { 759 if (RealizedPlatform) 760 *RealizedPlatform = Availability->getPlatform()->getName(); 761 return AR_Unavailable; 762 } 763 764 if (AR > Result) { 765 Result = AR; 766 if (Message) 767 ResultMessage.swap(*Message); 768 } 769 continue; 770 } 771 } 772 773 if (Message) 774 Message->swap(ResultMessage); 775 return Result; 776 } 777 778 VersionTuple Decl::getVersionIntroduced() const { 779 const ASTContext &Context = getASTContext(); 780 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName(); 781 for (const auto *A : attrs()) { 782 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) { 783 if (getRealizedPlatform(Availability, Context) != TargetPlatform) 784 continue; 785 if (!Availability->getIntroduced().empty()) 786 return Availability->getIntroduced(); 787 } 788 } 789 return {}; 790 } 791 792 bool Decl::canBeWeakImported(bool &IsDefinition) const { 793 IsDefinition = false; 794 795 // Variables, if they aren't definitions. 796 if (const auto *Var = dyn_cast<VarDecl>(this)) { 797 if (Var->isThisDeclarationADefinition()) { 798 IsDefinition = true; 799 return false; 800 } 801 return true; 802 } 803 // Functions, if they aren't definitions. 804 if (const auto *FD = dyn_cast<FunctionDecl>(this)) { 805 if (FD->hasBody()) { 806 IsDefinition = true; 807 return false; 808 } 809 return true; 810 811 } 812 // Objective-C classes, if this is the non-fragile runtime. 813 if (isa<ObjCInterfaceDecl>(this) && 814 getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) { 815 return true; 816 } 817 // Nothing else. 818 return false; 819 } 820 821 bool Decl::isWeakImported() const { 822 bool IsDefinition; 823 if (!canBeWeakImported(IsDefinition)) 824 return false; 825 826 for (const auto *A : getMostRecentDecl()->attrs()) { 827 if (isa<WeakImportAttr>(A)) 828 return true; 829 830 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) { 831 if (CheckAvailability(getASTContext(), Availability, nullptr, 832 VersionTuple()) == AR_NotYetIntroduced) 833 return true; 834 } 835 } 836 837 return false; 838 } 839 840 unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) { 841 switch (DeclKind) { 842 case Function: 843 case CXXDeductionGuide: 844 case CXXMethod: 845 case CXXConstructor: 846 case ConstructorUsingShadow: 847 case CXXDestructor: 848 case CXXConversion: 849 case EnumConstant: 850 case Var: 851 case ImplicitParam: 852 case ParmVar: 853 case ObjCMethod: 854 case ObjCProperty: 855 case MSProperty: 856 case HLSLBuffer: 857 return IDNS_Ordinary; 858 case Label: 859 return IDNS_Label; 860 case IndirectField: 861 return IDNS_Ordinary | IDNS_Member; 862 863 case Binding: 864 case NonTypeTemplateParm: 865 case VarTemplate: 866 case Concept: 867 // These (C++-only) declarations are found by redeclaration lookup for 868 // tag types, so we include them in the tag namespace. 869 return IDNS_Ordinary | IDNS_Tag; 870 871 case ObjCCompatibleAlias: 872 case ObjCInterface: 873 return IDNS_Ordinary | IDNS_Type; 874 875 case Typedef: 876 case TypeAlias: 877 case TemplateTypeParm: 878 case ObjCTypeParam: 879 return IDNS_Ordinary | IDNS_Type; 880 881 case UnresolvedUsingTypename: 882 return IDNS_Ordinary | IDNS_Type | IDNS_Using; 883 884 case UsingShadow: 885 return 0; // we'll actually overwrite this later 886 887 case UnresolvedUsingValue: 888 return IDNS_Ordinary | IDNS_Using; 889 890 case Using: 891 case UsingPack: 892 case UsingEnum: 893 return IDNS_Using; 894 895 case ObjCProtocol: 896 return IDNS_ObjCProtocol; 897 898 case Field: 899 case ObjCAtDefsField: 900 case ObjCIvar: 901 return IDNS_Member; 902 903 case Record: 904 case CXXRecord: 905 case Enum: 906 return IDNS_Tag | IDNS_Type; 907 908 case Namespace: 909 case NamespaceAlias: 910 return IDNS_Namespace; 911 912 case FunctionTemplate: 913 return IDNS_Ordinary; 914 915 case ClassTemplate: 916 case TemplateTemplateParm: 917 case TypeAliasTemplate: 918 return IDNS_Ordinary | IDNS_Tag | IDNS_Type; 919 920 case UnresolvedUsingIfExists: 921 return IDNS_Type | IDNS_Ordinary; 922 923 case OMPDeclareReduction: 924 return IDNS_OMPReduction; 925 926 case OMPDeclareMapper: 927 return IDNS_OMPMapper; 928 929 // Never have names. 930 case Friend: 931 case FriendTemplate: 932 case AccessSpec: 933 case LinkageSpec: 934 case Export: 935 case FileScopeAsm: 936 case TopLevelStmt: 937 case StaticAssert: 938 case ObjCPropertyImpl: 939 case PragmaComment: 940 case PragmaDetectMismatch: 941 case Block: 942 case Captured: 943 case TranslationUnit: 944 case ExternCContext: 945 case Decomposition: 946 case MSGuid: 947 case UnnamedGlobalConstant: 948 case TemplateParamObject: 949 950 case UsingDirective: 951 case BuiltinTemplate: 952 case ClassTemplateSpecialization: 953 case ClassTemplatePartialSpecialization: 954 case VarTemplateSpecialization: 955 case VarTemplatePartialSpecialization: 956 case ObjCImplementation: 957 case ObjCCategory: 958 case ObjCCategoryImpl: 959 case Import: 960 case OMPThreadPrivate: 961 case OMPAllocate: 962 case OMPRequires: 963 case OMPCapturedExpr: 964 case Empty: 965 case LifetimeExtendedTemporary: 966 case RequiresExprBody: 967 case ImplicitConceptSpecialization: 968 // Never looked up by name. 969 return 0; 970 } 971 972 llvm_unreachable("Invalid DeclKind!"); 973 } 974 975 void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) { 976 assert(!HasAttrs && "Decl already contains attrs."); 977 978 AttrVec &AttrBlank = Ctx.getDeclAttrs(this); 979 assert(AttrBlank.empty() && "HasAttrs was wrong?"); 980 981 AttrBlank = attrs; 982 HasAttrs = true; 983 } 984 985 void Decl::dropAttrs() { 986 if (!HasAttrs) return; 987 988 HasAttrs = false; 989 getASTContext().eraseDeclAttrs(this); 990 } 991 992 void Decl::addAttr(Attr *A) { 993 if (!hasAttrs()) { 994 setAttrs(AttrVec(1, A)); 995 return; 996 } 997 998 AttrVec &Attrs = getAttrs(); 999 if (!A->isInherited()) { 1000 Attrs.push_back(A); 1001 return; 1002 } 1003 1004 // Attribute inheritance is processed after attribute parsing. To keep the 1005 // order as in the source code, add inherited attributes before non-inherited 1006 // ones. 1007 auto I = Attrs.begin(), E = Attrs.end(); 1008 for (; I != E; ++I) { 1009 if (!(*I)->isInherited()) 1010 break; 1011 } 1012 Attrs.insert(I, A); 1013 } 1014 1015 const AttrVec &Decl::getAttrs() const { 1016 assert(HasAttrs && "No attrs to get!"); 1017 return getASTContext().getDeclAttrs(this); 1018 } 1019 1020 Decl *Decl::castFromDeclContext (const DeclContext *D) { 1021 Decl::Kind DK = D->getDeclKind(); 1022 switch (DK) { 1023 #define DECL(NAME, BASE) 1024 #define DECL_CONTEXT(NAME) \ 1025 case Decl::NAME: \ 1026 return static_cast<NAME##Decl *>(const_cast<DeclContext *>(D)); 1027 #include "clang/AST/DeclNodes.inc" 1028 default: 1029 llvm_unreachable("a decl that inherits DeclContext isn't handled"); 1030 } 1031 } 1032 1033 DeclContext *Decl::castToDeclContext(const Decl *D) { 1034 Decl::Kind DK = D->getKind(); 1035 switch(DK) { 1036 #define DECL(NAME, BASE) 1037 #define DECL_CONTEXT(NAME) \ 1038 case Decl::NAME: \ 1039 return static_cast<NAME##Decl *>(const_cast<Decl *>(D)); 1040 #include "clang/AST/DeclNodes.inc" 1041 default: 1042 llvm_unreachable("a decl that inherits DeclContext isn't handled"); 1043 } 1044 } 1045 1046 SourceLocation Decl::getBodyRBrace() const { 1047 // Special handling of FunctionDecl to avoid de-serializing the body from PCH. 1048 // FunctionDecl stores EndRangeLoc for this purpose. 1049 if (const auto *FD = dyn_cast<FunctionDecl>(this)) { 1050 const FunctionDecl *Definition; 1051 if (FD->hasBody(Definition)) 1052 return Definition->getSourceRange().getEnd(); 1053 return {}; 1054 } 1055 1056 if (Stmt *Body = getBody()) 1057 return Body->getSourceRange().getEnd(); 1058 1059 return {}; 1060 } 1061 1062 bool Decl::AccessDeclContextCheck() const { 1063 #ifndef NDEBUG 1064 // Suppress this check if any of the following hold: 1065 // 1. this is the translation unit (and thus has no parent) 1066 // 2. this is a template parameter (and thus doesn't belong to its context) 1067 // 3. this is a non-type template parameter 1068 // 4. the context is not a record 1069 // 5. it's invalid 1070 // 6. it's a C++0x static_assert. 1071 // 7. it's a block literal declaration 1072 // 8. it's a temporary with lifetime extended due to being default value. 1073 if (isa<TranslationUnitDecl>(this) || isa<TemplateTypeParmDecl>(this) || 1074 isa<NonTypeTemplateParmDecl>(this) || !getDeclContext() || 1075 !isa<CXXRecordDecl>(getDeclContext()) || isInvalidDecl() || 1076 isa<StaticAssertDecl>(this) || isa<BlockDecl>(this) || 1077 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization 1078 // as DeclContext (?). 1079 isa<ParmVarDecl>(this) || 1080 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have 1081 // AS_none as access specifier. 1082 isa<CXXRecordDecl>(this) || isa<LifetimeExtendedTemporaryDecl>(this)) 1083 return true; 1084 1085 assert(Access != AS_none && 1086 "Access specifier is AS_none inside a record decl"); 1087 #endif 1088 return true; 1089 } 1090 1091 bool Decl::isInExportDeclContext() const { 1092 const DeclContext *DC = getLexicalDeclContext(); 1093 1094 while (DC && !isa<ExportDecl>(DC)) 1095 DC = DC->getLexicalParent(); 1096 1097 return DC && isa<ExportDecl>(DC); 1098 } 1099 1100 bool Decl::isInAnotherModuleUnit() const { 1101 auto *M = getOwningModule(); 1102 1103 if (!M || !M->isNamedModule()) 1104 return false; 1105 1106 return M != getASTContext().getCurrentNamedModule(); 1107 } 1108 1109 bool Decl::shouldEmitInExternalSource() const { 1110 ExternalASTSource *Source = getASTContext().getExternalSource(); 1111 if (!Source) 1112 return false; 1113 1114 return Source->hasExternalDefinitions(this) == ExternalASTSource::EK_Always; 1115 } 1116 1117 bool Decl::isInNamedModule() const { 1118 return getOwningModule() && getOwningModule()->isNamedModule(); 1119 } 1120 1121 bool Decl::isFromExplicitGlobalModule() const { 1122 return getOwningModule() && getOwningModule()->isExplicitGlobalModule(); 1123 } 1124 1125 static Decl::Kind getKind(const Decl *D) { return D->getKind(); } 1126 static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); } 1127 1128 int64_t Decl::getID() const { 1129 return getASTContext().getAllocator().identifyKnownAlignedObject<Decl>(this); 1130 } 1131 1132 const FunctionType *Decl::getFunctionType(bool BlocksToo) const { 1133 QualType Ty; 1134 if (isa<BindingDecl>(this)) 1135 return nullptr; 1136 else if (const auto *D = dyn_cast<ValueDecl>(this)) 1137 Ty = D->getType(); 1138 else if (const auto *D = dyn_cast<TypedefNameDecl>(this)) 1139 Ty = D->getUnderlyingType(); 1140 else 1141 return nullptr; 1142 1143 if (Ty->isFunctionPointerType()) 1144 Ty = Ty->castAs<PointerType>()->getPointeeType(); 1145 else if (Ty->isFunctionReferenceType()) 1146 Ty = Ty->castAs<ReferenceType>()->getPointeeType(); 1147 else if (BlocksToo && Ty->isBlockPointerType()) 1148 Ty = Ty->castAs<BlockPointerType>()->getPointeeType(); 1149 1150 return Ty->getAs<FunctionType>(); 1151 } 1152 1153 bool Decl::isFunctionPointerType() const { 1154 QualType Ty; 1155 if (const auto *D = dyn_cast<ValueDecl>(this)) 1156 Ty = D->getType(); 1157 else if (const auto *D = dyn_cast<TypedefNameDecl>(this)) 1158 Ty = D->getUnderlyingType(); 1159 else 1160 return false; 1161 1162 return Ty.getCanonicalType()->isFunctionPointerType(); 1163 } 1164 1165 DeclContext *Decl::getNonTransparentDeclContext() { 1166 assert(getDeclContext()); 1167 return getDeclContext()->getNonTransparentContext(); 1168 } 1169 1170 /// Starting at a given context (a Decl or DeclContext), look for a 1171 /// code context that is not a closure (a lambda, block, etc.). 1172 template <class T> static Decl *getNonClosureContext(T *D) { 1173 if (getKind(D) == Decl::CXXMethod) { 1174 auto *MD = cast<CXXMethodDecl>(D); 1175 if (MD->getOverloadedOperator() == OO_Call && 1176 MD->getParent()->isLambda()) 1177 return getNonClosureContext(MD->getParent()->getParent()); 1178 return MD; 1179 } 1180 if (auto *FD = dyn_cast<FunctionDecl>(D)) 1181 return FD; 1182 if (auto *MD = dyn_cast<ObjCMethodDecl>(D)) 1183 return MD; 1184 if (auto *BD = dyn_cast<BlockDecl>(D)) 1185 return getNonClosureContext(BD->getParent()); 1186 if (auto *CD = dyn_cast<CapturedDecl>(D)) 1187 return getNonClosureContext(CD->getParent()); 1188 return nullptr; 1189 } 1190 1191 Decl *Decl::getNonClosureContext() { 1192 return ::getNonClosureContext(this); 1193 } 1194 1195 Decl *DeclContext::getNonClosureAncestor() { 1196 return ::getNonClosureContext(this); 1197 } 1198 1199 //===----------------------------------------------------------------------===// 1200 // DeclContext Implementation 1201 //===----------------------------------------------------------------------===// 1202 1203 DeclContext::DeclContext(Decl::Kind K) { 1204 DeclContextBits.DeclKind = K; 1205 setHasExternalLexicalStorage(false); 1206 setHasExternalVisibleStorage(false); 1207 setNeedToReconcileExternalVisibleStorage(false); 1208 setHasLazyLocalLexicalLookups(false); 1209 setHasLazyExternalLexicalLookups(false); 1210 setUseQualifiedLookup(false); 1211 } 1212 1213 bool DeclContext::classof(const Decl *D) { 1214 Decl::Kind DK = D->getKind(); 1215 switch (DK) { 1216 #define DECL(NAME, BASE) 1217 #define DECL_CONTEXT(NAME) case Decl::NAME: 1218 #include "clang/AST/DeclNodes.inc" 1219 return true; 1220 default: 1221 return false; 1222 } 1223 } 1224 1225 DeclContext::~DeclContext() = default; 1226 1227 /// Find the parent context of this context that will be 1228 /// used for unqualified name lookup. 1229 /// 1230 /// Generally, the parent lookup context is the semantic context. However, for 1231 /// a friend function the parent lookup context is the lexical context, which 1232 /// is the class in which the friend is declared. 1233 DeclContext *DeclContext::getLookupParent() { 1234 // FIXME: Find a better way to identify friends. 1235 if (isa<FunctionDecl>(this)) 1236 if (getParent()->getRedeclContext()->isFileContext() && 1237 getLexicalParent()->getRedeclContext()->isRecord()) 1238 return getLexicalParent(); 1239 1240 // A lookup within the call operator of a lambda never looks in the lambda 1241 // class; instead, skip to the context in which that closure type is 1242 // declared. 1243 if (isLambdaCallOperator(this)) 1244 return getParent()->getParent(); 1245 1246 return getParent(); 1247 } 1248 1249 const BlockDecl *DeclContext::getInnermostBlockDecl() const { 1250 const DeclContext *Ctx = this; 1251 1252 do { 1253 if (Ctx->isClosure()) 1254 return cast<BlockDecl>(Ctx); 1255 Ctx = Ctx->getParent(); 1256 } while (Ctx); 1257 1258 return nullptr; 1259 } 1260 1261 bool DeclContext::isInlineNamespace() const { 1262 return isNamespace() && 1263 cast<NamespaceDecl>(this)->isInline(); 1264 } 1265 1266 bool DeclContext::isStdNamespace() const { 1267 if (!isNamespace()) 1268 return false; 1269 1270 const auto *ND = cast<NamespaceDecl>(this); 1271 if (ND->isInline()) { 1272 return ND->getParent()->isStdNamespace(); 1273 } 1274 1275 if (!getParent()->getRedeclContext()->isTranslationUnit()) 1276 return false; 1277 1278 const IdentifierInfo *II = ND->getIdentifier(); 1279 return II && II->isStr("std"); 1280 } 1281 1282 bool DeclContext::isDependentContext() const { 1283 if (isFileContext()) 1284 return false; 1285 1286 if (isa<ClassTemplatePartialSpecializationDecl>(this)) 1287 return true; 1288 1289 if (const auto *Record = dyn_cast<CXXRecordDecl>(this)) { 1290 if (Record->getDescribedClassTemplate()) 1291 return true; 1292 1293 if (Record->isDependentLambda()) 1294 return true; 1295 if (Record->isNeverDependentLambda()) 1296 return false; 1297 } 1298 1299 if (const auto *Function = dyn_cast<FunctionDecl>(this)) { 1300 if (Function->getDescribedFunctionTemplate()) 1301 return true; 1302 1303 // Friend function declarations are dependent if their *lexical* 1304 // context is dependent. 1305 if (cast<Decl>(this)->getFriendObjectKind()) 1306 return getLexicalParent()->isDependentContext(); 1307 } 1308 1309 // FIXME: A variable template is a dependent context, but is not a 1310 // DeclContext. A context within it (such as a lambda-expression) 1311 // should be considered dependent. 1312 1313 return getParent() && getParent()->isDependentContext(); 1314 } 1315 1316 bool DeclContext::isTransparentContext() const { 1317 if (getDeclKind() == Decl::Enum) 1318 return !cast<EnumDecl>(this)->isScoped(); 1319 1320 return isa<LinkageSpecDecl, ExportDecl, HLSLBufferDecl>(this); 1321 } 1322 1323 static bool isLinkageSpecContext(const DeclContext *DC, 1324 LinkageSpecLanguageIDs ID) { 1325 while (DC->getDeclKind() != Decl::TranslationUnit) { 1326 if (DC->getDeclKind() == Decl::LinkageSpec) 1327 return cast<LinkageSpecDecl>(DC)->getLanguage() == ID; 1328 DC = DC->getLexicalParent(); 1329 } 1330 return false; 1331 } 1332 1333 bool DeclContext::isExternCContext() const { 1334 return isLinkageSpecContext(this, LinkageSpecLanguageIDs::C); 1335 } 1336 1337 const LinkageSpecDecl *DeclContext::getExternCContext() const { 1338 const DeclContext *DC = this; 1339 while (DC->getDeclKind() != Decl::TranslationUnit) { 1340 if (DC->getDeclKind() == Decl::LinkageSpec && 1341 cast<LinkageSpecDecl>(DC)->getLanguage() == LinkageSpecLanguageIDs::C) 1342 return cast<LinkageSpecDecl>(DC); 1343 DC = DC->getLexicalParent(); 1344 } 1345 return nullptr; 1346 } 1347 1348 bool DeclContext::isExternCXXContext() const { 1349 return isLinkageSpecContext(this, LinkageSpecLanguageIDs::CXX); 1350 } 1351 1352 bool DeclContext::Encloses(const DeclContext *DC) const { 1353 if (getPrimaryContext() != this) 1354 return getPrimaryContext()->Encloses(DC); 1355 1356 for (; DC; DC = DC->getParent()) 1357 if (!isa<LinkageSpecDecl>(DC) && !isa<ExportDecl>(DC) && 1358 DC->getPrimaryContext() == this) 1359 return true; 1360 return false; 1361 } 1362 1363 DeclContext *DeclContext::getNonTransparentContext() { 1364 DeclContext *DC = this; 1365 while (DC->isTransparentContext()) { 1366 DC = DC->getParent(); 1367 assert(DC && "All transparent contexts should have a parent!"); 1368 } 1369 return DC; 1370 } 1371 1372 DeclContext *DeclContext::getPrimaryContext() { 1373 switch (getDeclKind()) { 1374 case Decl::ExternCContext: 1375 case Decl::LinkageSpec: 1376 case Decl::Export: 1377 case Decl::TopLevelStmt: 1378 case Decl::Block: 1379 case Decl::Captured: 1380 case Decl::OMPDeclareReduction: 1381 case Decl::OMPDeclareMapper: 1382 case Decl::RequiresExprBody: 1383 // There is only one DeclContext for these entities. 1384 return this; 1385 1386 case Decl::HLSLBuffer: 1387 // Each buffer, even with the same name, is a distinct construct. 1388 // Multiple buffers with the same name are allowed for backward 1389 // compatibility. 1390 // As long as buffers have unique resource bindings the names don't matter. 1391 // The names get exposed via the CPU-side reflection API which 1392 // supports querying bindings, so we cannot remove them. 1393 return this; 1394 1395 case Decl::TranslationUnit: 1396 return static_cast<TranslationUnitDecl *>(this)->getFirstDecl(); 1397 case Decl::Namespace: 1398 // The original namespace is our primary context. 1399 return static_cast<NamespaceDecl *>(this)->getOriginalNamespace(); 1400 1401 case Decl::ObjCMethod: 1402 return this; 1403 1404 case Decl::ObjCInterface: 1405 if (auto *OID = dyn_cast<ObjCInterfaceDecl>(this)) 1406 if (auto *Def = OID->getDefinition()) 1407 return Def; 1408 return this; 1409 1410 case Decl::ObjCProtocol: 1411 if (auto *OPD = dyn_cast<ObjCProtocolDecl>(this)) 1412 if (auto *Def = OPD->getDefinition()) 1413 return Def; 1414 return this; 1415 1416 case Decl::ObjCCategory: 1417 return this; 1418 1419 case Decl::ObjCImplementation: 1420 case Decl::ObjCCategoryImpl: 1421 return this; 1422 1423 default: 1424 if (getDeclKind() >= Decl::firstTag && getDeclKind() <= Decl::lastTag) { 1425 // If this is a tag type that has a definition or is currently 1426 // being defined, that definition is our primary context. 1427 auto *Tag = cast<TagDecl>(this); 1428 1429 if (TagDecl *Def = Tag->getDefinition()) 1430 return Def; 1431 1432 if (const auto *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) { 1433 // Note, TagType::getDecl returns the (partial) definition one exists. 1434 TagDecl *PossiblePartialDef = TagTy->getDecl(); 1435 if (PossiblePartialDef->isBeingDefined()) 1436 return PossiblePartialDef; 1437 } else { 1438 assert(isa<InjectedClassNameType>(Tag->getTypeForDecl())); 1439 } 1440 1441 return Tag; 1442 } 1443 1444 assert(getDeclKind() >= Decl::firstFunction && 1445 getDeclKind() <= Decl::lastFunction && 1446 "Unknown DeclContext kind"); 1447 return this; 1448 } 1449 } 1450 1451 template <typename T> 1452 void collectAllContextsImpl(T *Self, SmallVectorImpl<DeclContext *> &Contexts) { 1453 for (T *D = Self->getMostRecentDecl(); D; D = D->getPreviousDecl()) 1454 Contexts.push_back(D); 1455 1456 std::reverse(Contexts.begin(), Contexts.end()); 1457 } 1458 1459 void DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts) { 1460 Contexts.clear(); 1461 1462 Decl::Kind Kind = getDeclKind(); 1463 1464 if (Kind == Decl::TranslationUnit) 1465 collectAllContextsImpl(static_cast<TranslationUnitDecl *>(this), Contexts); 1466 else if (Kind == Decl::Namespace) 1467 collectAllContextsImpl(static_cast<NamespaceDecl *>(this), Contexts); 1468 else 1469 Contexts.push_back(this); 1470 } 1471 1472 std::pair<Decl *, Decl *> 1473 DeclContext::BuildDeclChain(ArrayRef<Decl *> Decls, 1474 bool FieldsAlreadyLoaded) { 1475 // Build up a chain of declarations via the Decl::NextInContextAndBits field. 1476 Decl *FirstNewDecl = nullptr; 1477 Decl *PrevDecl = nullptr; 1478 for (auto *D : Decls) { 1479 if (FieldsAlreadyLoaded && isa<FieldDecl>(D)) 1480 continue; 1481 1482 if (PrevDecl) 1483 PrevDecl->NextInContextAndBits.setPointer(D); 1484 else 1485 FirstNewDecl = D; 1486 1487 PrevDecl = D; 1488 } 1489 1490 return std::make_pair(FirstNewDecl, PrevDecl); 1491 } 1492 1493 /// We have just acquired external visible storage, and we already have 1494 /// built a lookup map. For every name in the map, pull in the new names from 1495 /// the external storage. 1496 void DeclContext::reconcileExternalVisibleStorage() const { 1497 assert(hasNeedToReconcileExternalVisibleStorage() && LookupPtr); 1498 setNeedToReconcileExternalVisibleStorage(false); 1499 1500 for (auto &Lookup : *LookupPtr) 1501 Lookup.second.setHasExternalDecls(); 1502 } 1503 1504 /// Load the declarations within this lexical storage from an 1505 /// external source. 1506 /// \return \c true if any declarations were added. 1507 bool 1508 DeclContext::LoadLexicalDeclsFromExternalStorage() const { 1509 ExternalASTSource *Source = getParentASTContext().getExternalSource(); 1510 assert(hasExternalLexicalStorage() && Source && "No external storage?"); 1511 1512 // Notify that we have a DeclContext that is initializing. 1513 ExternalASTSource::Deserializing ADeclContext(Source); 1514 1515 // Load the external declarations, if any. 1516 SmallVector<Decl*, 64> Decls; 1517 setHasExternalLexicalStorage(false); 1518 Source->FindExternalLexicalDecls(this, Decls); 1519 1520 if (Decls.empty()) 1521 return false; 1522 1523 // We may have already loaded just the fields of this record, in which case 1524 // we need to ignore them. 1525 bool FieldsAlreadyLoaded = false; 1526 if (const auto *RD = dyn_cast<RecordDecl>(this)) 1527 FieldsAlreadyLoaded = RD->hasLoadedFieldsFromExternalStorage(); 1528 1529 // Splice the newly-read declarations into the beginning of the list 1530 // of declarations. 1531 Decl *ExternalFirst, *ExternalLast; 1532 std::tie(ExternalFirst, ExternalLast) = 1533 BuildDeclChain(Decls, FieldsAlreadyLoaded); 1534 ExternalLast->NextInContextAndBits.setPointer(FirstDecl); 1535 FirstDecl = ExternalFirst; 1536 if (!LastDecl) 1537 LastDecl = ExternalLast; 1538 return true; 1539 } 1540 1541 DeclContext::lookup_result 1542 ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC, 1543 DeclarationName Name) { 1544 ASTContext &Context = DC->getParentASTContext(); 1545 StoredDeclsMap *Map; 1546 if (!(Map = DC->LookupPtr)) 1547 Map = DC->CreateStoredDeclsMap(Context); 1548 if (DC->hasNeedToReconcileExternalVisibleStorage()) 1549 DC->reconcileExternalVisibleStorage(); 1550 1551 (*Map)[Name].removeExternalDecls(); 1552 1553 return DeclContext::lookup_result(); 1554 } 1555 1556 DeclContext::lookup_result 1557 ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC, 1558 DeclarationName Name, 1559 ArrayRef<NamedDecl*> Decls) { 1560 ASTContext &Context = DC->getParentASTContext(); 1561 StoredDeclsMap *Map; 1562 if (!(Map = DC->LookupPtr)) 1563 Map = DC->CreateStoredDeclsMap(Context); 1564 if (DC->hasNeedToReconcileExternalVisibleStorage()) 1565 DC->reconcileExternalVisibleStorage(); 1566 1567 StoredDeclsList &List = (*Map)[Name]; 1568 List.replaceExternalDecls(Decls); 1569 return List.getLookupResult(); 1570 } 1571 1572 DeclContext::decl_iterator DeclContext::decls_begin() const { 1573 if (hasExternalLexicalStorage()) 1574 LoadLexicalDeclsFromExternalStorage(); 1575 return decl_iterator(FirstDecl); 1576 } 1577 1578 bool DeclContext::decls_empty() const { 1579 if (hasExternalLexicalStorage()) 1580 LoadLexicalDeclsFromExternalStorage(); 1581 1582 return !FirstDecl; 1583 } 1584 1585 bool DeclContext::containsDecl(Decl *D) const { 1586 return (D->getLexicalDeclContext() == this && 1587 (D->NextInContextAndBits.getPointer() || D == LastDecl)); 1588 } 1589 1590 bool DeclContext::containsDeclAndLoad(Decl *D) const { 1591 if (hasExternalLexicalStorage()) 1592 LoadLexicalDeclsFromExternalStorage(); 1593 return containsDecl(D); 1594 } 1595 1596 /// shouldBeHidden - Determine whether a declaration which was declared 1597 /// within its semantic context should be invisible to qualified name lookup. 1598 static bool shouldBeHidden(NamedDecl *D) { 1599 // Skip unnamed declarations. 1600 if (!D->getDeclName()) 1601 return true; 1602 1603 // Skip entities that can't be found by name lookup into a particular 1604 // context. 1605 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) || 1606 D->isTemplateParameter()) 1607 return true; 1608 1609 // Skip friends and local extern declarations unless they're the first 1610 // declaration of the entity. 1611 if ((D->isLocalExternDecl() || D->getFriendObjectKind()) && 1612 D != D->getCanonicalDecl()) 1613 return true; 1614 1615 // Skip template specializations. 1616 // FIXME: This feels like a hack. Should DeclarationName support 1617 // template-ids, or is there a better way to keep specializations 1618 // from being visible? 1619 if (isa<ClassTemplateSpecializationDecl>(D)) 1620 return true; 1621 if (auto *FD = dyn_cast<FunctionDecl>(D)) 1622 if (FD->isFunctionTemplateSpecialization()) 1623 return true; 1624 1625 // Hide destructors that are invalid. There should always be one destructor, 1626 // but if it is an invalid decl, another one is created. We need to hide the 1627 // invalid one from places that expect exactly one destructor, like the 1628 // serialization code. 1629 if (isa<CXXDestructorDecl>(D) && D->isInvalidDecl()) 1630 return true; 1631 1632 return false; 1633 } 1634 1635 void DeclContext::removeDecl(Decl *D) { 1636 assert(D->getLexicalDeclContext() == this && 1637 "decl being removed from non-lexical context"); 1638 assert((D->NextInContextAndBits.getPointer() || D == LastDecl) && 1639 "decl is not in decls list"); 1640 1641 // Remove D from the decl chain. This is O(n) but hopefully rare. 1642 if (D == FirstDecl) { 1643 if (D == LastDecl) 1644 FirstDecl = LastDecl = nullptr; 1645 else 1646 FirstDecl = D->NextInContextAndBits.getPointer(); 1647 } else { 1648 for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) { 1649 assert(I && "decl not found in linked list"); 1650 if (I->NextInContextAndBits.getPointer() == D) { 1651 I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer()); 1652 if (D == LastDecl) LastDecl = I; 1653 break; 1654 } 1655 } 1656 } 1657 1658 // Mark that D is no longer in the decl chain. 1659 D->NextInContextAndBits.setPointer(nullptr); 1660 1661 // Remove D from the lookup table if necessary. 1662 if (isa<NamedDecl>(D)) { 1663 auto *ND = cast<NamedDecl>(D); 1664 1665 // Do not try to remove the declaration if that is invisible to qualified 1666 // lookup. E.g. template specializations are skipped. 1667 if (shouldBeHidden(ND)) 1668 return; 1669 1670 // Remove only decls that have a name 1671 if (!ND->getDeclName()) 1672 return; 1673 1674 auto *DC = D->getDeclContext(); 1675 do { 1676 StoredDeclsMap *Map = DC->getPrimaryContext()->LookupPtr; 1677 if (Map) { 1678 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName()); 1679 assert(Pos != Map->end() && "no lookup entry for decl"); 1680 StoredDeclsList &List = Pos->second; 1681 List.remove(ND); 1682 // Clean up the entry if there are no more decls. 1683 if (List.isNull()) 1684 Map->erase(Pos); 1685 } 1686 } while (DC->isTransparentContext() && (DC = DC->getParent())); 1687 } 1688 } 1689 1690 void DeclContext::addHiddenDecl(Decl *D) { 1691 assert(D->getLexicalDeclContext() == this && 1692 "Decl inserted into wrong lexical context"); 1693 assert(!D->getNextDeclInContext() && D != LastDecl && 1694 "Decl already inserted into a DeclContext"); 1695 1696 if (FirstDecl) { 1697 LastDecl->NextInContextAndBits.setPointer(D); 1698 LastDecl = D; 1699 } else { 1700 FirstDecl = LastDecl = D; 1701 } 1702 1703 // Notify a C++ record declaration that we've added a member, so it can 1704 // update its class-specific state. 1705 if (auto *Record = dyn_cast<CXXRecordDecl>(this)) 1706 Record->addedMember(D); 1707 1708 // If this is a newly-created (not de-serialized) import declaration, wire 1709 // it in to the list of local import declarations. 1710 if (!D->isFromASTFile()) { 1711 if (auto *Import = dyn_cast<ImportDecl>(D)) 1712 D->getASTContext().addedLocalImportDecl(Import); 1713 } 1714 } 1715 1716 void DeclContext::addDecl(Decl *D) { 1717 addHiddenDecl(D); 1718 1719 if (auto *ND = dyn_cast<NamedDecl>(D)) 1720 ND->getDeclContext()->getPrimaryContext()-> 1721 makeDeclVisibleInContextWithFlags(ND, false, true); 1722 } 1723 1724 void DeclContext::addDeclInternal(Decl *D) { 1725 addHiddenDecl(D); 1726 1727 if (auto *ND = dyn_cast<NamedDecl>(D)) 1728 ND->getDeclContext()->getPrimaryContext()-> 1729 makeDeclVisibleInContextWithFlags(ND, true, true); 1730 } 1731 1732 /// buildLookup - Build the lookup data structure with all of the 1733 /// declarations in this DeclContext (and any other contexts linked 1734 /// to it or transparent contexts nested within it) and return it. 1735 /// 1736 /// Note that the produced map may miss out declarations from an 1737 /// external source. If it does, those entries will be marked with 1738 /// the 'hasExternalDecls' flag. 1739 StoredDeclsMap *DeclContext::buildLookup() { 1740 assert(this == getPrimaryContext() && "buildLookup called on non-primary DC"); 1741 1742 if (!hasLazyLocalLexicalLookups() && 1743 !hasLazyExternalLexicalLookups()) 1744 return LookupPtr; 1745 1746 SmallVector<DeclContext *, 2> Contexts; 1747 collectAllContexts(Contexts); 1748 1749 if (hasLazyExternalLexicalLookups()) { 1750 setHasLazyExternalLexicalLookups(false); 1751 for (auto *DC : Contexts) { 1752 if (DC->hasExternalLexicalStorage()) { 1753 bool LoadedDecls = DC->LoadLexicalDeclsFromExternalStorage(); 1754 setHasLazyLocalLexicalLookups( 1755 hasLazyLocalLexicalLookups() | LoadedDecls ); 1756 } 1757 } 1758 1759 if (!hasLazyLocalLexicalLookups()) 1760 return LookupPtr; 1761 } 1762 1763 for (auto *DC : Contexts) 1764 buildLookupImpl(DC, hasExternalVisibleStorage()); 1765 1766 // We no longer have any lazy decls. 1767 setHasLazyLocalLexicalLookups(false); 1768 return LookupPtr; 1769 } 1770 1771 /// buildLookupImpl - Build part of the lookup data structure for the 1772 /// declarations contained within DCtx, which will either be this 1773 /// DeclContext, a DeclContext linked to it, or a transparent context 1774 /// nested within it. 1775 void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) { 1776 for (auto *D : DCtx->noload_decls()) { 1777 // Insert this declaration into the lookup structure, but only if 1778 // it's semantically within its decl context. Any other decls which 1779 // should be found in this context are added eagerly. 1780 // 1781 // If it's from an AST file, don't add it now. It'll get handled by 1782 // FindExternalVisibleDeclsByName if needed. Exception: if we're not 1783 // in C++, we do not track external visible decls for the TU, so in 1784 // that case we need to collect them all here. 1785 if (auto *ND = dyn_cast<NamedDecl>(D)) 1786 if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) && 1787 (!ND->isFromASTFile() || 1788 (isTranslationUnit() && 1789 !getParentASTContext().getLangOpts().CPlusPlus))) 1790 makeDeclVisibleInContextImpl(ND, Internal); 1791 1792 // If this declaration is itself a transparent declaration context 1793 // or inline namespace, add the members of this declaration of that 1794 // context (recursively). 1795 if (auto *InnerCtx = dyn_cast<DeclContext>(D)) 1796 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace()) 1797 buildLookupImpl(InnerCtx, Internal); 1798 } 1799 } 1800 1801 DeclContext::lookup_result 1802 DeclContext::lookup(DeclarationName Name) const { 1803 // For transparent DeclContext, we should lookup in their enclosing context. 1804 if (getDeclKind() == Decl::LinkageSpec || getDeclKind() == Decl::Export) 1805 return getParent()->lookup(Name); 1806 1807 const DeclContext *PrimaryContext = getPrimaryContext(); 1808 if (PrimaryContext != this) 1809 return PrimaryContext->lookup(Name); 1810 1811 // If we have an external source, ensure that any later redeclarations of this 1812 // context have been loaded, since they may add names to the result of this 1813 // lookup (or add external visible storage). 1814 ExternalASTSource *Source = getParentASTContext().getExternalSource(); 1815 if (Source) 1816 (void)cast<Decl>(this)->getMostRecentDecl(); 1817 1818 if (hasExternalVisibleStorage()) { 1819 assert(Source && "external visible storage but no external source?"); 1820 1821 if (hasNeedToReconcileExternalVisibleStorage()) 1822 reconcileExternalVisibleStorage(); 1823 1824 StoredDeclsMap *Map = LookupPtr; 1825 1826 if (hasLazyLocalLexicalLookups() || 1827 hasLazyExternalLexicalLookups()) 1828 // FIXME: Make buildLookup const? 1829 Map = const_cast<DeclContext*>(this)->buildLookup(); 1830 1831 if (!Map) 1832 Map = CreateStoredDeclsMap(getParentASTContext()); 1833 1834 // If we have a lookup result with no external decls, we are done. 1835 std::pair<StoredDeclsMap::iterator, bool> R = 1836 Map->insert(std::make_pair(Name, StoredDeclsList())); 1837 if (!R.second && !R.first->second.hasExternalDecls()) 1838 return R.first->second.getLookupResult(); 1839 1840 if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) { 1841 if (StoredDeclsMap *Map = LookupPtr) { 1842 StoredDeclsMap::iterator I = Map->find(Name); 1843 if (I != Map->end()) 1844 return I->second.getLookupResult(); 1845 } 1846 } 1847 1848 return {}; 1849 } 1850 1851 StoredDeclsMap *Map = LookupPtr; 1852 if (hasLazyLocalLexicalLookups() || 1853 hasLazyExternalLexicalLookups()) 1854 Map = const_cast<DeclContext*>(this)->buildLookup(); 1855 1856 if (!Map) 1857 return {}; 1858 1859 StoredDeclsMap::iterator I = Map->find(Name); 1860 if (I == Map->end()) 1861 return {}; 1862 1863 return I->second.getLookupResult(); 1864 } 1865 1866 DeclContext::lookup_result 1867 DeclContext::noload_lookup(DeclarationName Name) { 1868 // For transparent DeclContext, we should lookup in their enclosing context. 1869 if (getDeclKind() == Decl::LinkageSpec || getDeclKind() == Decl::Export) 1870 return getParent()->noload_lookup(Name); 1871 1872 DeclContext *PrimaryContext = getPrimaryContext(); 1873 if (PrimaryContext != this) 1874 return PrimaryContext->noload_lookup(Name); 1875 1876 loadLazyLocalLexicalLookups(); 1877 StoredDeclsMap *Map = LookupPtr; 1878 if (!Map) 1879 return {}; 1880 1881 StoredDeclsMap::iterator I = Map->find(Name); 1882 return I != Map->end() ? I->second.getLookupResult() 1883 : lookup_result(); 1884 } 1885 1886 // If we have any lazy lexical declarations not in our lookup map, add them 1887 // now. Don't import any external declarations, not even if we know we have 1888 // some missing from the external visible lookups. 1889 void DeclContext::loadLazyLocalLexicalLookups() { 1890 if (hasLazyLocalLexicalLookups()) { 1891 SmallVector<DeclContext *, 2> Contexts; 1892 collectAllContexts(Contexts); 1893 for (auto *Context : Contexts) 1894 buildLookupImpl(Context, hasExternalVisibleStorage()); 1895 setHasLazyLocalLexicalLookups(false); 1896 } 1897 } 1898 1899 void DeclContext::localUncachedLookup(DeclarationName Name, 1900 SmallVectorImpl<NamedDecl *> &Results) { 1901 Results.clear(); 1902 1903 // If there's no external storage, just perform a normal lookup and copy 1904 // the results. 1905 if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) { 1906 lookup_result LookupResults = lookup(Name); 1907 Results.insert(Results.end(), LookupResults.begin(), LookupResults.end()); 1908 if (!Results.empty()) 1909 return; 1910 } 1911 1912 // If we have a lookup table, check there first. Maybe we'll get lucky. 1913 // FIXME: Should we be checking these flags on the primary context? 1914 if (Name && !hasLazyLocalLexicalLookups() && 1915 !hasLazyExternalLexicalLookups()) { 1916 if (StoredDeclsMap *Map = LookupPtr) { 1917 StoredDeclsMap::iterator Pos = Map->find(Name); 1918 if (Pos != Map->end()) { 1919 Results.insert(Results.end(), 1920 Pos->second.getLookupResult().begin(), 1921 Pos->second.getLookupResult().end()); 1922 return; 1923 } 1924 } 1925 } 1926 1927 // Slow case: grovel through the declarations in our chain looking for 1928 // matches. 1929 // FIXME: If we have lazy external declarations, this will not find them! 1930 // FIXME: Should we CollectAllContexts and walk them all here? 1931 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) { 1932 if (auto *ND = dyn_cast<NamedDecl>(D)) 1933 if (ND->getDeclName() == Name) 1934 Results.push_back(ND); 1935 } 1936 } 1937 1938 DeclContext *DeclContext::getRedeclContext() { 1939 DeclContext *Ctx = this; 1940 1941 // In C, a record type is the redeclaration context for its fields only. If 1942 // we arrive at a record context after skipping anything else, we should skip 1943 // the record as well. Currently, this means skipping enumerations because 1944 // they're the only transparent context that can exist within a struct or 1945 // union. 1946 bool SkipRecords = getDeclKind() == Decl::Kind::Enum && 1947 !getParentASTContext().getLangOpts().CPlusPlus; 1948 1949 // Skip through contexts to get to the redeclaration context. Transparent 1950 // contexts are always skipped. 1951 while ((SkipRecords && Ctx->isRecord()) || Ctx->isTransparentContext()) 1952 Ctx = Ctx->getParent(); 1953 return Ctx; 1954 } 1955 1956 DeclContext *DeclContext::getEnclosingNamespaceContext() { 1957 DeclContext *Ctx = this; 1958 // Skip through non-namespace, non-translation-unit contexts. 1959 while (!Ctx->isFileContext()) 1960 Ctx = Ctx->getParent(); 1961 return Ctx->getPrimaryContext(); 1962 } 1963 1964 RecordDecl *DeclContext::getOuterLexicalRecordContext() { 1965 // Loop until we find a non-record context. 1966 RecordDecl *OutermostRD = nullptr; 1967 DeclContext *DC = this; 1968 while (DC->isRecord()) { 1969 OutermostRD = cast<RecordDecl>(DC); 1970 DC = DC->getLexicalParent(); 1971 } 1972 return OutermostRD; 1973 } 1974 1975 bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const { 1976 // For non-file contexts, this is equivalent to Equals. 1977 if (!isFileContext()) 1978 return O->Equals(this); 1979 1980 do { 1981 if (O->Equals(this)) 1982 return true; 1983 1984 const auto *NS = dyn_cast<NamespaceDecl>(O); 1985 if (!NS || !NS->isInline()) 1986 break; 1987 O = NS->getParent(); 1988 } while (O); 1989 1990 return false; 1991 } 1992 1993 void DeclContext::makeDeclVisibleInContext(NamedDecl *D) { 1994 DeclContext *PrimaryDC = this->getPrimaryContext(); 1995 DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext(); 1996 // If the decl is being added outside of its semantic decl context, we 1997 // need to ensure that we eagerly build the lookup information for it. 1998 PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC); 1999 } 2000 2001 void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal, 2002 bool Recoverable) { 2003 assert(this == getPrimaryContext() && "expected a primary DC"); 2004 2005 if (!isLookupContext()) { 2006 if (isTransparentContext()) 2007 getParent()->getPrimaryContext() 2008 ->makeDeclVisibleInContextWithFlags(D, Internal, Recoverable); 2009 return; 2010 } 2011 2012 // Skip declarations which should be invisible to name lookup. 2013 if (shouldBeHidden(D)) 2014 return; 2015 2016 // If we already have a lookup data structure, perform the insertion into 2017 // it. If we might have externally-stored decls with this name, look them 2018 // up and perform the insertion. If this decl was declared outside its 2019 // semantic context, buildLookup won't add it, so add it now. 2020 // 2021 // FIXME: As a performance hack, don't add such decls into the translation 2022 // unit unless we're in C++, since qualified lookup into the TU is never 2023 // performed. 2024 if (LookupPtr || hasExternalVisibleStorage() || 2025 ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) && 2026 (getParentASTContext().getLangOpts().CPlusPlus || 2027 !isTranslationUnit()))) { 2028 // If we have lazily omitted any decls, they might have the same name as 2029 // the decl which we are adding, so build a full lookup table before adding 2030 // this decl. 2031 buildLookup(); 2032 makeDeclVisibleInContextImpl(D, Internal); 2033 } else { 2034 setHasLazyLocalLexicalLookups(true); 2035 } 2036 2037 // If we are a transparent context or inline namespace, insert into our 2038 // parent context, too. This operation is recursive. 2039 if (isTransparentContext() || isInlineNamespace()) 2040 getParent()->getPrimaryContext()-> 2041 makeDeclVisibleInContextWithFlags(D, Internal, Recoverable); 2042 2043 auto *DCAsDecl = cast<Decl>(this); 2044 // Notify that a decl was made visible unless we are a Tag being defined. 2045 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined())) 2046 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener()) 2047 L->AddedVisibleDecl(this, D); 2048 } 2049 2050 void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) { 2051 // Find or create the stored declaration map. 2052 StoredDeclsMap *Map = LookupPtr; 2053 if (!Map) { 2054 ASTContext *C = &getParentASTContext(); 2055 Map = CreateStoredDeclsMap(*C); 2056 } 2057 2058 // If there is an external AST source, load any declarations it knows about 2059 // with this declaration's name. 2060 // If the lookup table contains an entry about this name it means that we 2061 // have already checked the external source. 2062 if (!Internal) 2063 if (ExternalASTSource *Source = getParentASTContext().getExternalSource()) 2064 if (hasExternalVisibleStorage() && 2065 Map->find(D->getDeclName()) == Map->end()) 2066 Source->FindExternalVisibleDeclsByName(this, D->getDeclName()); 2067 2068 // Insert this declaration into the map. 2069 StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()]; 2070 2071 if (Internal) { 2072 // If this is being added as part of loading an external declaration, 2073 // this may not be the only external declaration with this name. 2074 // In this case, we never try to replace an existing declaration; we'll 2075 // handle that when we finalize the list of declarations for this name. 2076 DeclNameEntries.setHasExternalDecls(); 2077 DeclNameEntries.prependDeclNoReplace(D); 2078 return; 2079 } 2080 2081 DeclNameEntries.addOrReplaceDecl(D); 2082 } 2083 2084 UsingDirectiveDecl *DeclContext::udir_iterator::operator*() const { 2085 return cast<UsingDirectiveDecl>(*I); 2086 } 2087 2088 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within 2089 /// this context. 2090 DeclContext::udir_range DeclContext::using_directives() const { 2091 // FIXME: Use something more efficient than normal lookup for using 2092 // directives. In C++, using directives are looked up more than anything else. 2093 lookup_result Result = lookup(UsingDirectiveDecl::getName()); 2094 return udir_range(Result.begin(), Result.end()); 2095 } 2096 2097 //===----------------------------------------------------------------------===// 2098 // Creation and Destruction of StoredDeclsMaps. // 2099 //===----------------------------------------------------------------------===// 2100 2101 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const { 2102 assert(!LookupPtr && "context already has a decls map"); 2103 assert(getPrimaryContext() == this && 2104 "creating decls map on non-primary context"); 2105 2106 StoredDeclsMap *M; 2107 bool Dependent = isDependentContext(); 2108 if (Dependent) 2109 M = new DependentStoredDeclsMap(); 2110 else 2111 M = new StoredDeclsMap(); 2112 M->Previous = C.LastSDM; 2113 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent); 2114 LookupPtr = M; 2115 return M; 2116 } 2117 2118 void ASTContext::ReleaseDeclContextMaps() { 2119 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap 2120 // pointer because the subclass doesn't add anything that needs to 2121 // be deleted. 2122 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt()); 2123 LastSDM.setPointer(nullptr); 2124 } 2125 2126 void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) { 2127 while (Map) { 2128 // Advance the iteration before we invalidate memory. 2129 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous; 2130 2131 if (Dependent) 2132 delete static_cast<DependentStoredDeclsMap*>(Map); 2133 else 2134 delete Map; 2135 2136 Map = Next.getPointer(); 2137 Dependent = Next.getInt(); 2138 } 2139 } 2140 2141 DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C, 2142 DeclContext *Parent, 2143 const PartialDiagnostic &PDiag) { 2144 assert(Parent->isDependentContext() 2145 && "cannot iterate dependent diagnostics of non-dependent context"); 2146 Parent = Parent->getPrimaryContext(); 2147 if (!Parent->LookupPtr) 2148 Parent->CreateStoredDeclsMap(C); 2149 2150 auto *Map = static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr); 2151 2152 // Allocate the copy of the PartialDiagnostic via the ASTContext's 2153 // BumpPtrAllocator, rather than the ASTContext itself. 2154 DiagnosticStorage *DiagStorage = nullptr; 2155 if (PDiag.hasStorage()) 2156 DiagStorage = new (C) DiagnosticStorage; 2157 2158 auto *DD = new (C) DependentDiagnostic(PDiag, DiagStorage); 2159 2160 // TODO: Maybe we shouldn't reverse the order during insertion. 2161 DD->NextDiagnostic = Map->FirstDiagnostic; 2162 Map->FirstDiagnostic = DD; 2163 2164 return DD; 2165 } 2166