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