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