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