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