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