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