clang API Documentation

DeclBase.cpp
Go to the documentation of this file.
00001 //===--- DeclBase.cpp - Declaration AST Node Implementation ---------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the Decl and DeclContext classes.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "clang/AST/DeclBase.h"
00015 #include "clang/AST/ASTContext.h"
00016 #include "clang/AST/ASTMutationListener.h"
00017 #include "clang/AST/Attr.h"
00018 #include "clang/AST/Decl.h"
00019 #include "clang/AST/DeclCXX.h"
00020 #include "clang/AST/DeclContextInternals.h"
00021 #include "clang/AST/DeclFriend.h"
00022 #include "clang/AST/DeclObjC.h"
00023 #include "clang/AST/DeclOpenMP.h"
00024 #include "clang/AST/DeclTemplate.h"
00025 #include "clang/AST/DependentDiagnostic.h"
00026 #include "clang/AST/ExternalASTSource.h"
00027 #include "clang/AST/Stmt.h"
00028 #include "clang/AST/StmtCXX.h"
00029 #include "clang/AST/Type.h"
00030 #include "clang/Basic/TargetInfo.h"
00031 #include "llvm/ADT/DenseMap.h"
00032 #include "llvm/Support/raw_ostream.h"
00033 #include <algorithm>
00034 using namespace clang;
00035 
00036 //===----------------------------------------------------------------------===//
00037 //  Statistics
00038 //===----------------------------------------------------------------------===//
00039 
00040 #define DECL(DERIVED, BASE) static int n##DERIVED##s = 0;
00041 #define ABSTRACT_DECL(DECL)
00042 #include "clang/AST/DeclNodes.inc"
00043 
00044 void Decl::updateOutOfDate(IdentifierInfo &II) const {
00045   getASTContext().getExternalSource()->updateOutOfDateIdentifier(II);
00046 }
00047 
00048 void *Decl::operator new(std::size_t Size, const ASTContext &Context,
00049                          unsigned ID, std::size_t Extra) {
00050   // Allocate an extra 8 bytes worth of storage, which ensures that the
00051   // resulting pointer will still be 8-byte aligned. 
00052   void *Start = Context.Allocate(Size + Extra + 8);
00053   void *Result = (char*)Start + 8;
00054 
00055   unsigned *PrefixPtr = (unsigned *)Result - 2;
00056 
00057   // Zero out the first 4 bytes; this is used to store the owning module ID.
00058   PrefixPtr[0] = 0;
00059 
00060   // Store the global declaration ID in the second 4 bytes.
00061   PrefixPtr[1] = ID;
00062 
00063   return Result;
00064 }
00065 
00066 void *Decl::operator new(std::size_t Size, const ASTContext &Ctx,
00067                          DeclContext *Parent, std::size_t Extra) {
00068   assert(!Parent || &Parent->getParentASTContext() == &Ctx);
00069   return ::operator new(Size + Extra, Ctx);
00070 }
00071 
00072 Module *Decl::getOwningModuleSlow() const {
00073   assert(isFromASTFile() && "Not from AST file?");
00074   return getASTContext().getExternalSource()->getModule(getOwningModuleID());
00075 }
00076 
00077 const char *Decl::getDeclKindName() const {
00078   switch (DeclKind) {
00079   default: llvm_unreachable("Declaration not in DeclNodes.inc!");
00080 #define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
00081 #define ABSTRACT_DECL(DECL)
00082 #include "clang/AST/DeclNodes.inc"
00083   }
00084 }
00085 
00086 void Decl::setInvalidDecl(bool Invalid) {
00087   InvalidDecl = Invalid;
00088   assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition());
00089   if (Invalid && !isa<ParmVarDecl>(this)) {
00090     // Defensive maneuver for ill-formed code: we're likely not to make it to
00091     // a point where we set the access specifier, so default it to "public"
00092     // to avoid triggering asserts elsewhere in the front end. 
00093     setAccess(AS_public);
00094   }
00095 }
00096 
00097 const char *DeclContext::getDeclKindName() const {
00098   switch (DeclKind) {
00099   default: llvm_unreachable("Declaration context not in DeclNodes.inc!");
00100 #define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
00101 #define ABSTRACT_DECL(DECL)
00102 #include "clang/AST/DeclNodes.inc"
00103   }
00104 }
00105 
00106 bool Decl::StatisticsEnabled = false;
00107 void Decl::EnableStatistics() {
00108   StatisticsEnabled = true;
00109 }
00110 
00111 void Decl::PrintStats() {
00112   llvm::errs() << "\n*** Decl Stats:\n";
00113 
00114   int totalDecls = 0;
00115 #define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
00116 #define ABSTRACT_DECL(DECL)
00117 #include "clang/AST/DeclNodes.inc"
00118   llvm::errs() << "  " << totalDecls << " decls total.\n";
00119 
00120   int totalBytes = 0;
00121 #define DECL(DERIVED, BASE)                                             \
00122   if (n##DERIVED##s > 0) {                                              \
00123     totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl));         \
00124     llvm::errs() << "    " << n##DERIVED##s << " " #DERIVED " decls, "  \
00125                  << sizeof(DERIVED##Decl) << " each ("                  \
00126                  << n##DERIVED##s * sizeof(DERIVED##Decl)               \
00127                  << " bytes)\n";                                        \
00128   }
00129 #define ABSTRACT_DECL(DECL)
00130 #include "clang/AST/DeclNodes.inc"
00131 
00132   llvm::errs() << "Total bytes = " << totalBytes << "\n";
00133 }
00134 
00135 void Decl::add(Kind k) {
00136   switch (k) {
00137 #define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
00138 #define ABSTRACT_DECL(DECL)
00139 #include "clang/AST/DeclNodes.inc"
00140   }
00141 }
00142 
00143 bool Decl::isTemplateParameterPack() const {
00144   if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
00145     return TTP->isParameterPack();
00146   if (const NonTypeTemplateParmDecl *NTTP
00147                                 = dyn_cast<NonTypeTemplateParmDecl>(this))
00148     return NTTP->isParameterPack();
00149   if (const TemplateTemplateParmDecl *TTP
00150                                     = dyn_cast<TemplateTemplateParmDecl>(this))
00151     return TTP->isParameterPack();
00152   return false;
00153 }
00154 
00155 bool Decl::isParameterPack() const {
00156   if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this))
00157     return Parm->isParameterPack();
00158   
00159   return isTemplateParameterPack();
00160 }
00161 
00162 FunctionDecl *Decl::getAsFunction() {
00163   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
00164     return FD;
00165   if (const FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(this))
00166     return FTD->getTemplatedDecl();
00167   return nullptr;
00168 }
00169 
00170 bool Decl::isTemplateDecl() const {
00171   return isa<TemplateDecl>(this);
00172 }
00173 
00174 const DeclContext *Decl::getParentFunctionOrMethod() const {
00175   for (const DeclContext *DC = getDeclContext();
00176        DC && !DC->isTranslationUnit() && !DC->isNamespace(); 
00177        DC = DC->getParent())
00178     if (DC->isFunctionOrMethod())
00179       return DC;
00180 
00181   return nullptr;
00182 }
00183 
00184 
00185 //===----------------------------------------------------------------------===//
00186 // PrettyStackTraceDecl Implementation
00187 //===----------------------------------------------------------------------===//
00188 
00189 void PrettyStackTraceDecl::print(raw_ostream &OS) const {
00190   SourceLocation TheLoc = Loc;
00191   if (TheLoc.isInvalid() && TheDecl)
00192     TheLoc = TheDecl->getLocation();
00193 
00194   if (TheLoc.isValid()) {
00195     TheLoc.print(OS, SM);
00196     OS << ": ";
00197   }
00198 
00199   OS << Message;
00200 
00201   if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
00202     OS << " '";
00203     DN->printQualifiedName(OS);
00204     OS << '\'';
00205   }
00206   OS << '\n';
00207 }
00208 
00209 //===----------------------------------------------------------------------===//
00210 // Decl Implementation
00211 //===----------------------------------------------------------------------===//
00212 
00213 // Out-of-line virtual method providing a home for Decl.
00214 Decl::~Decl() { }
00215 
00216 void Decl::setDeclContext(DeclContext *DC) {
00217   DeclCtx = DC;
00218 }
00219 
00220 void Decl::setLexicalDeclContext(DeclContext *DC) {
00221   if (DC == getLexicalDeclContext())
00222     return;
00223 
00224   if (isInSemaDC()) {
00225     setDeclContextsImpl(getDeclContext(), DC, getASTContext());
00226   } else {
00227     getMultipleDC()->LexicalDC = DC;
00228   }
00229 }
00230 
00231 void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
00232                                ASTContext &Ctx) {
00233   if (SemaDC == LexicalDC) {
00234     DeclCtx = SemaDC;
00235   } else {
00236     Decl::MultipleDC *MDC = new (Ctx) Decl::MultipleDC();
00237     MDC->SemanticDC = SemaDC;
00238     MDC->LexicalDC = LexicalDC;
00239     DeclCtx = MDC;
00240   }
00241 }
00242 
00243 bool Decl::isInAnonymousNamespace() const {
00244   const DeclContext *DC = getDeclContext();
00245   do {
00246     if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
00247       if (ND->isAnonymousNamespace())
00248         return true;
00249   } while ((DC = DC->getParent()));
00250 
00251   return false;
00252 }
00253 
00254 bool Decl::isInStdNamespace() const {
00255   return getDeclContext()->isStdNamespace();
00256 }
00257 
00258 TranslationUnitDecl *Decl::getTranslationUnitDecl() {
00259   if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
00260     return TUD;
00261 
00262   DeclContext *DC = getDeclContext();
00263   assert(DC && "This decl is not contained in a translation unit!");
00264 
00265   while (!DC->isTranslationUnit()) {
00266     DC = DC->getParent();
00267     assert(DC && "This decl is not contained in a translation unit!");
00268   }
00269 
00270   return cast<TranslationUnitDecl>(DC);
00271 }
00272 
00273 ASTContext &Decl::getASTContext() const {
00274   return getTranslationUnitDecl()->getASTContext();
00275 }
00276 
00277 ASTMutationListener *Decl::getASTMutationListener() const {
00278   return getASTContext().getASTMutationListener();
00279 }
00280 
00281 unsigned Decl::getMaxAlignment() const {
00282   if (!hasAttrs())
00283     return 0;
00284 
00285   unsigned Align = 0;
00286   const AttrVec &V = getAttrs();
00287   ASTContext &Ctx = getASTContext();
00288   specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
00289   for (; I != E; ++I)
00290     Align = std::max(Align, I->getAlignment(Ctx));
00291   return Align;
00292 }
00293 
00294 bool Decl::isUsed(bool CheckUsedAttr) const { 
00295   if (Used)
00296     return true;
00297   
00298   // Check for used attribute.
00299   if (CheckUsedAttr && hasAttr<UsedAttr>())
00300     return true;
00301 
00302   return false; 
00303 }
00304 
00305 void Decl::markUsed(ASTContext &C) {
00306   if (Used)
00307     return;
00308 
00309   if (C.getASTMutationListener())
00310     C.getASTMutationListener()->DeclarationMarkedUsed(this);
00311 
00312   Used = true;
00313 }
00314 
00315 bool Decl::isReferenced() const { 
00316   if (Referenced)
00317     return true;
00318 
00319   // Check redeclarations.
00320   for (auto I : redecls())
00321     if (I->Referenced)
00322       return true;
00323 
00324   return false; 
00325 }
00326 
00327 /// \brief Determine the availability of the given declaration based on
00328 /// the target platform.
00329 ///
00330 /// When it returns an availability result other than \c AR_Available,
00331 /// if the \p Message parameter is non-NULL, it will be set to a
00332 /// string describing why the entity is unavailable.
00333 ///
00334 /// FIXME: Make these strings localizable, since they end up in
00335 /// diagnostics.
00336 static AvailabilityResult CheckAvailability(ASTContext &Context,
00337                                             const AvailabilityAttr *A,
00338                                             std::string *Message) {
00339   StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
00340   StringRef PrettyPlatformName
00341     = AvailabilityAttr::getPrettyPlatformName(TargetPlatform);
00342   if (PrettyPlatformName.empty())
00343     PrettyPlatformName = TargetPlatform;
00344 
00345   VersionTuple TargetMinVersion = Context.getTargetInfo().getPlatformMinVersion();
00346   if (TargetMinVersion.empty())
00347     return AR_Available;
00348 
00349   // Match the platform name.
00350   if (A->getPlatform()->getName() != TargetPlatform)
00351     return AR_Available;
00352   
00353   std::string HintMessage;
00354   if (!A->getMessage().empty()) {
00355     HintMessage = " - ";
00356     HintMessage += A->getMessage();
00357   }
00358   
00359   // Make sure that this declaration has not been marked 'unavailable'.
00360   if (A->getUnavailable()) {
00361     if (Message) {
00362       Message->clear();
00363       llvm::raw_string_ostream Out(*Message);
00364       Out << "not available on " << PrettyPlatformName 
00365           << HintMessage;
00366     }
00367 
00368     return AR_Unavailable;
00369   }
00370 
00371   // Make sure that this declaration has already been introduced.
00372   if (!A->getIntroduced().empty() && 
00373       TargetMinVersion < A->getIntroduced()) {
00374     if (Message) {
00375       Message->clear();
00376       llvm::raw_string_ostream Out(*Message);
00377       VersionTuple VTI(A->getIntroduced());
00378       VTI.UseDotAsSeparator();
00379       Out << "introduced in " << PrettyPlatformName << ' ' 
00380           << VTI << HintMessage;
00381     }
00382 
00383     return AR_NotYetIntroduced;
00384   }
00385 
00386   // Make sure that this declaration hasn't been obsoleted.
00387   if (!A->getObsoleted().empty() && TargetMinVersion >= A->getObsoleted()) {
00388     if (Message) {
00389       Message->clear();
00390       llvm::raw_string_ostream Out(*Message);
00391       VersionTuple VTO(A->getObsoleted());
00392       VTO.UseDotAsSeparator();
00393       Out << "obsoleted in " << PrettyPlatformName << ' ' 
00394           << VTO << HintMessage;
00395     }
00396     
00397     return AR_Unavailable;
00398   }
00399 
00400   // Make sure that this declaration hasn't been deprecated.
00401   if (!A->getDeprecated().empty() && TargetMinVersion >= A->getDeprecated()) {
00402     if (Message) {
00403       Message->clear();
00404       llvm::raw_string_ostream Out(*Message);
00405       VersionTuple VTD(A->getDeprecated());
00406       VTD.UseDotAsSeparator();
00407       Out << "first deprecated in " << PrettyPlatformName << ' '
00408           << VTD << HintMessage;
00409     }
00410     
00411     return AR_Deprecated;
00412   }
00413 
00414   return AR_Available;
00415 }
00416 
00417 AvailabilityResult Decl::getAvailability(std::string *Message) const {
00418   AvailabilityResult Result = AR_Available;
00419   std::string ResultMessage;
00420 
00421   for (const auto *A : attrs()) {
00422     if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
00423       if (Result >= AR_Deprecated)
00424         continue;
00425 
00426       if (Message)
00427         ResultMessage = Deprecated->getMessage();
00428 
00429       Result = AR_Deprecated;
00430       continue;
00431     }
00432 
00433     if (const auto *Unavailable = dyn_cast<UnavailableAttr>(A)) {
00434       if (Message)
00435         *Message = Unavailable->getMessage();
00436       return AR_Unavailable;
00437     }
00438 
00439     if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
00440       AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
00441                                                 Message);
00442 
00443       if (AR == AR_Unavailable)
00444         return AR_Unavailable;
00445 
00446       if (AR > Result) {
00447         Result = AR;
00448         if (Message)
00449           ResultMessage.swap(*Message);
00450       }
00451       continue;
00452     }
00453   }
00454 
00455   if (Message)
00456     Message->swap(ResultMessage);
00457   return Result;
00458 }
00459 
00460 bool Decl::canBeWeakImported(bool &IsDefinition) const {
00461   IsDefinition = false;
00462 
00463   // Variables, if they aren't definitions.
00464   if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
00465     if (Var->isThisDeclarationADefinition()) {
00466       IsDefinition = true;
00467       return false;
00468     }
00469     return true;
00470 
00471   // Functions, if they aren't definitions.
00472   } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
00473     if (FD->hasBody()) {
00474       IsDefinition = true;
00475       return false;
00476     }
00477     return true;
00478 
00479   // Objective-C classes, if this is the non-fragile runtime.
00480   } else if (isa<ObjCInterfaceDecl>(this) &&
00481              getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
00482     return true;
00483 
00484   // Nothing else.
00485   } else {
00486     return false;
00487   }
00488 }
00489 
00490 bool Decl::isWeakImported() const {
00491   bool IsDefinition;
00492   if (!canBeWeakImported(IsDefinition))
00493     return false;
00494 
00495   for (const auto *A : attrs()) {
00496     if (isa<WeakImportAttr>(A))
00497       return true;
00498 
00499     if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
00500       if (CheckAvailability(getASTContext(), Availability,
00501                             nullptr) == AR_NotYetIntroduced)
00502         return true;
00503     }
00504   }
00505 
00506   return false;
00507 }
00508 
00509 unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
00510   switch (DeclKind) {
00511     case Function:
00512     case CXXMethod:
00513     case CXXConstructor:
00514     case CXXDestructor:
00515     case CXXConversion:
00516     case EnumConstant:
00517     case Var:
00518     case ImplicitParam:
00519     case ParmVar:
00520     case NonTypeTemplateParm:
00521     case ObjCMethod:
00522     case ObjCProperty:
00523     case MSProperty:
00524       return IDNS_Ordinary;
00525     case Label:
00526       return IDNS_Label;
00527     case IndirectField:
00528       return IDNS_Ordinary | IDNS_Member;
00529 
00530     case ObjCCompatibleAlias:
00531     case ObjCInterface:
00532       return IDNS_Ordinary | IDNS_Type;
00533 
00534     case Typedef:
00535     case TypeAlias:
00536     case TypeAliasTemplate:
00537     case UnresolvedUsingTypename:
00538     case TemplateTypeParm:
00539       return IDNS_Ordinary | IDNS_Type;
00540 
00541     case UsingShadow:
00542       return 0; // we'll actually overwrite this later
00543 
00544     case UnresolvedUsingValue:
00545       return IDNS_Ordinary | IDNS_Using;
00546 
00547     case Using:
00548       return IDNS_Using;
00549 
00550     case ObjCProtocol:
00551       return IDNS_ObjCProtocol;
00552 
00553     case Field:
00554     case ObjCAtDefsField:
00555     case ObjCIvar:
00556       return IDNS_Member;
00557 
00558     case Record:
00559     case CXXRecord:
00560     case Enum:
00561       return IDNS_Tag | IDNS_Type;
00562 
00563     case Namespace:
00564     case NamespaceAlias:
00565       return IDNS_Namespace;
00566 
00567     case FunctionTemplate:
00568     case VarTemplate:
00569       return IDNS_Ordinary;
00570 
00571     case ClassTemplate:
00572     case TemplateTemplateParm:
00573       return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
00574 
00575     // Never have names.
00576     case Friend:
00577     case FriendTemplate:
00578     case AccessSpec:
00579     case LinkageSpec:
00580     case FileScopeAsm:
00581     case StaticAssert:
00582     case ObjCPropertyImpl:
00583     case Block:
00584     case Captured:
00585     case TranslationUnit:
00586 
00587     case UsingDirective:
00588     case ClassTemplateSpecialization:
00589     case ClassTemplatePartialSpecialization:
00590     case ClassScopeFunctionSpecialization:
00591     case VarTemplateSpecialization:
00592     case VarTemplatePartialSpecialization:
00593     case ObjCImplementation:
00594     case ObjCCategory:
00595     case ObjCCategoryImpl:
00596     case Import:
00597     case OMPThreadPrivate:
00598     case Empty:
00599       // Never looked up by name.
00600       return 0;
00601   }
00602 
00603   llvm_unreachable("Invalid DeclKind!");
00604 }
00605 
00606 void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
00607   assert(!HasAttrs && "Decl already contains attrs.");
00608 
00609   AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
00610   assert(AttrBlank.empty() && "HasAttrs was wrong?");
00611 
00612   AttrBlank = attrs;
00613   HasAttrs = true;
00614 }
00615 
00616 void Decl::dropAttrs() {
00617   if (!HasAttrs) return;
00618 
00619   HasAttrs = false;
00620   getASTContext().eraseDeclAttrs(this);
00621 }
00622 
00623 const AttrVec &Decl::getAttrs() const {
00624   assert(HasAttrs && "No attrs to get!");
00625   return getASTContext().getDeclAttrs(this);
00626 }
00627 
00628 Decl *Decl::castFromDeclContext (const DeclContext *D) {
00629   Decl::Kind DK = D->getDeclKind();
00630   switch(DK) {
00631 #define DECL(NAME, BASE)
00632 #define DECL_CONTEXT(NAME) \
00633     case Decl::NAME:       \
00634       return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
00635 #define DECL_CONTEXT_BASE(NAME)
00636 #include "clang/AST/DeclNodes.inc"
00637     default:
00638 #define DECL(NAME, BASE)
00639 #define DECL_CONTEXT_BASE(NAME)                  \
00640       if (DK >= first##NAME && DK <= last##NAME) \
00641         return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
00642 #include "clang/AST/DeclNodes.inc"
00643       llvm_unreachable("a decl that inherits DeclContext isn't handled");
00644   }
00645 }
00646 
00647 DeclContext *Decl::castToDeclContext(const Decl *D) {
00648   Decl::Kind DK = D->getKind();
00649   switch(DK) {
00650 #define DECL(NAME, BASE)
00651 #define DECL_CONTEXT(NAME) \
00652     case Decl::NAME:       \
00653       return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
00654 #define DECL_CONTEXT_BASE(NAME)
00655 #include "clang/AST/DeclNodes.inc"
00656     default:
00657 #define DECL(NAME, BASE)
00658 #define DECL_CONTEXT_BASE(NAME)                                   \
00659       if (DK >= first##NAME && DK <= last##NAME)                  \
00660         return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
00661 #include "clang/AST/DeclNodes.inc"
00662       llvm_unreachable("a decl that inherits DeclContext isn't handled");
00663   }
00664 }
00665 
00666 SourceLocation Decl::getBodyRBrace() const {
00667   // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
00668   // FunctionDecl stores EndRangeLoc for this purpose.
00669   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
00670     const FunctionDecl *Definition;
00671     if (FD->hasBody(Definition))
00672       return Definition->getSourceRange().getEnd();
00673     return SourceLocation();
00674   }
00675 
00676   if (Stmt *Body = getBody())
00677     return Body->getSourceRange().getEnd();
00678 
00679   return SourceLocation();
00680 }
00681 
00682 bool Decl::AccessDeclContextSanity() const {
00683 #ifndef NDEBUG
00684   // Suppress this check if any of the following hold:
00685   // 1. this is the translation unit (and thus has no parent)
00686   // 2. this is a template parameter (and thus doesn't belong to its context)
00687   // 3. this is a non-type template parameter
00688   // 4. the context is not a record
00689   // 5. it's invalid
00690   // 6. it's a C++0x static_assert.
00691   if (isa<TranslationUnitDecl>(this) ||
00692       isa<TemplateTypeParmDecl>(this) ||
00693       isa<NonTypeTemplateParmDecl>(this) ||
00694       !isa<CXXRecordDecl>(getDeclContext()) ||
00695       isInvalidDecl() ||
00696       isa<StaticAssertDecl>(this) ||
00697       // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
00698       // as DeclContext (?).
00699       isa<ParmVarDecl>(this) ||
00700       // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
00701       // AS_none as access specifier.
00702       isa<CXXRecordDecl>(this) ||
00703       isa<ClassScopeFunctionSpecializationDecl>(this))
00704     return true;
00705 
00706   assert(Access != AS_none &&
00707          "Access specifier is AS_none inside a record decl");
00708 #endif
00709   return true;
00710 }
00711 
00712 static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
00713 static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
00714 
00715 const FunctionType *Decl::getFunctionType(bool BlocksToo) const {
00716   QualType Ty;
00717   if (const ValueDecl *D = dyn_cast<ValueDecl>(this))
00718     Ty = D->getType();
00719   else if (const TypedefNameDecl *D = dyn_cast<TypedefNameDecl>(this))
00720     Ty = D->getUnderlyingType();
00721   else
00722     return nullptr;
00723 
00724   if (Ty->isFunctionPointerType())
00725     Ty = Ty->getAs<PointerType>()->getPointeeType();
00726   else if (BlocksToo && Ty->isBlockPointerType())
00727     Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
00728 
00729   return Ty->getAs<FunctionType>();
00730 }
00731 
00732 
00733 /// Starting at a given context (a Decl or DeclContext), look for a
00734 /// code context that is not a closure (a lambda, block, etc.).
00735 template <class T> static Decl *getNonClosureContext(T *D) {
00736   if (getKind(D) == Decl::CXXMethod) {
00737     CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
00738     if (MD->getOverloadedOperator() == OO_Call &&
00739         MD->getParent()->isLambda())
00740       return getNonClosureContext(MD->getParent()->getParent());
00741     return MD;
00742   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
00743     return FD;
00744   } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
00745     return MD;
00746   } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
00747     return getNonClosureContext(BD->getParent());
00748   } else if (CapturedDecl *CD = dyn_cast<CapturedDecl>(D)) {
00749     return getNonClosureContext(CD->getParent());
00750   } else {
00751     return nullptr;
00752   }
00753 }
00754 
00755 Decl *Decl::getNonClosureContext() {
00756   return ::getNonClosureContext(this);
00757 }
00758 
00759 Decl *DeclContext::getNonClosureAncestor() {
00760   return ::getNonClosureContext(this);
00761 }
00762 
00763 //===----------------------------------------------------------------------===//
00764 // DeclContext Implementation
00765 //===----------------------------------------------------------------------===//
00766 
00767 bool DeclContext::classof(const Decl *D) {
00768   switch (D->getKind()) {
00769 #define DECL(NAME, BASE)
00770 #define DECL_CONTEXT(NAME) case Decl::NAME:
00771 #define DECL_CONTEXT_BASE(NAME)
00772 #include "clang/AST/DeclNodes.inc"
00773       return true;
00774     default:
00775 #define DECL(NAME, BASE)
00776 #define DECL_CONTEXT_BASE(NAME)                 \
00777       if (D->getKind() >= Decl::first##NAME &&  \
00778           D->getKind() <= Decl::last##NAME)     \
00779         return true;
00780 #include "clang/AST/DeclNodes.inc"
00781       return false;
00782   }
00783 }
00784 
00785 DeclContext::~DeclContext() { }
00786 
00787 /// \brief Find the parent context of this context that will be
00788 /// used for unqualified name lookup.
00789 ///
00790 /// Generally, the parent lookup context is the semantic context. However, for
00791 /// a friend function the parent lookup context is the lexical context, which
00792 /// is the class in which the friend is declared.
00793 DeclContext *DeclContext::getLookupParent() {
00794   // FIXME: Find a better way to identify friends
00795   if (isa<FunctionDecl>(this))
00796     if (getParent()->getRedeclContext()->isFileContext() &&
00797         getLexicalParent()->getRedeclContext()->isRecord())
00798       return getLexicalParent();
00799   
00800   return getParent();
00801 }
00802 
00803 bool DeclContext::isInlineNamespace() const {
00804   return isNamespace() &&
00805          cast<NamespaceDecl>(this)->isInline();
00806 }
00807 
00808 bool DeclContext::isStdNamespace() const {
00809   if (!isNamespace())
00810     return false;
00811 
00812   const NamespaceDecl *ND = cast<NamespaceDecl>(this);
00813   if (ND->isInline()) {
00814     return ND->getParent()->isStdNamespace();
00815   }
00816 
00817   if (!getParent()->getRedeclContext()->isTranslationUnit())
00818     return false;
00819 
00820   const IdentifierInfo *II = ND->getIdentifier();
00821   return II && II->isStr("std");
00822 }
00823 
00824 bool DeclContext::isDependentContext() const {
00825   if (isFileContext())
00826     return false;
00827 
00828   if (isa<ClassTemplatePartialSpecializationDecl>(this))
00829     return true;
00830 
00831   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
00832     if (Record->getDescribedClassTemplate())
00833       return true;
00834     
00835     if (Record->isDependentLambda())
00836       return true;
00837   }
00838   
00839   if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
00840     if (Function->getDescribedFunctionTemplate())
00841       return true;
00842 
00843     // Friend function declarations are dependent if their *lexical*
00844     // context is dependent.
00845     if (cast<Decl>(this)->getFriendObjectKind())
00846       return getLexicalParent()->isDependentContext();
00847   }
00848 
00849   return getParent() && getParent()->isDependentContext();
00850 }
00851 
00852 bool DeclContext::isTransparentContext() const {
00853   if (DeclKind == Decl::Enum)
00854     return !cast<EnumDecl>(this)->isScoped();
00855   else if (DeclKind == Decl::LinkageSpec)
00856     return true;
00857 
00858   return false;
00859 }
00860 
00861 static bool isLinkageSpecContext(const DeclContext *DC,
00862                                  LinkageSpecDecl::LanguageIDs ID) {
00863   while (DC->getDeclKind() != Decl::TranslationUnit) {
00864     if (DC->getDeclKind() == Decl::LinkageSpec)
00865       return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
00866     DC = DC->getLexicalParent();
00867   }
00868   return false;
00869 }
00870 
00871 bool DeclContext::isExternCContext() const {
00872   return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_c);
00873 }
00874 
00875 bool DeclContext::isExternCXXContext() const {
00876   return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_cxx);
00877 }
00878 
00879 bool DeclContext::Encloses(const DeclContext *DC) const {
00880   if (getPrimaryContext() != this)
00881     return getPrimaryContext()->Encloses(DC);
00882 
00883   for (; DC; DC = DC->getParent())
00884     if (DC->getPrimaryContext() == this)
00885       return true;
00886   return false;
00887 }
00888 
00889 DeclContext *DeclContext::getPrimaryContext() {
00890   switch (DeclKind) {
00891   case Decl::TranslationUnit:
00892   case Decl::LinkageSpec:
00893   case Decl::Block:
00894   case Decl::Captured:
00895     // There is only one DeclContext for these entities.
00896     return this;
00897 
00898   case Decl::Namespace:
00899     // The original namespace is our primary context.
00900     return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
00901 
00902   case Decl::ObjCMethod:
00903     return this;
00904 
00905   case Decl::ObjCInterface:
00906     if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
00907       return Def;
00908       
00909     return this;
00910       
00911   case Decl::ObjCProtocol:
00912     if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
00913       return Def;
00914     
00915     return this;
00916       
00917   case Decl::ObjCCategory:
00918     return this;
00919 
00920   case Decl::ObjCImplementation:
00921   case Decl::ObjCCategoryImpl:
00922     return this;
00923 
00924   default:
00925     if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
00926       // If this is a tag type that has a definition or is currently
00927       // being defined, that definition is our primary context.
00928       TagDecl *Tag = cast<TagDecl>(this);
00929 
00930       if (TagDecl *Def = Tag->getDefinition())
00931         return Def;
00932 
00933       if (const TagType *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) {
00934         // Note, TagType::getDecl returns the (partial) definition one exists.
00935         TagDecl *PossiblePartialDef = TagTy->getDecl();
00936         if (PossiblePartialDef->isBeingDefined())
00937           return PossiblePartialDef;
00938       } else {
00939         assert(isa<InjectedClassNameType>(Tag->getTypeForDecl()));
00940       }
00941 
00942       return Tag;
00943     }
00944 
00945     assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
00946           "Unknown DeclContext kind");
00947     return this;
00948   }
00949 }
00950 
00951 void 
00952 DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
00953   Contexts.clear();
00954   
00955   if (DeclKind != Decl::Namespace) {
00956     Contexts.push_back(this);
00957     return;
00958   }
00959   
00960   NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
00961   for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
00962        N = N->getPreviousDecl())
00963     Contexts.push_back(N);
00964   
00965   std::reverse(Contexts.begin(), Contexts.end());
00966 }
00967 
00968 std::pair<Decl *, Decl *>
00969 DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
00970                             bool FieldsAlreadyLoaded) {
00971   // Build up a chain of declarations via the Decl::NextInContextAndBits field.
00972   Decl *FirstNewDecl = nullptr;
00973   Decl *PrevDecl = nullptr;
00974   for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
00975     if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
00976       continue;
00977 
00978     Decl *D = Decls[I];
00979     if (PrevDecl)
00980       PrevDecl->NextInContextAndBits.setPointer(D);
00981     else
00982       FirstNewDecl = D;
00983 
00984     PrevDecl = D;
00985   }
00986 
00987   return std::make_pair(FirstNewDecl, PrevDecl);
00988 }
00989 
00990 /// \brief We have just acquired external visible storage, and we already have
00991 /// built a lookup map. For every name in the map, pull in the new names from
00992 /// the external storage.
00993 void DeclContext::reconcileExternalVisibleStorage() const {
00994   assert(NeedToReconcileExternalVisibleStorage && LookupPtr.getPointer());
00995   NeedToReconcileExternalVisibleStorage = false;
00996 
00997   for (auto &Lookup : *LookupPtr.getPointer())
00998     Lookup.second.setHasExternalDecls();
00999 }
01000 
01001 /// \brief Load the declarations within this lexical storage from an
01002 /// external source.
01003 void
01004 DeclContext::LoadLexicalDeclsFromExternalStorage() const {
01005   ExternalASTSource *Source = getParentASTContext().getExternalSource();
01006   assert(hasExternalLexicalStorage() && Source && "No external storage?");
01007 
01008   // Notify that we have a DeclContext that is initializing.
01009   ExternalASTSource::Deserializing ADeclContext(Source);
01010   
01011   // Load the external declarations, if any.
01012   SmallVector<Decl*, 64> Decls;
01013   ExternalLexicalStorage = false;
01014   switch (Source->FindExternalLexicalDecls(this, Decls)) {
01015   case ELR_Success:
01016     break;
01017     
01018   case ELR_Failure:
01019   case ELR_AlreadyLoaded:
01020     return;
01021   }
01022 
01023   if (Decls.empty())
01024     return;
01025 
01026   // We may have already loaded just the fields of this record, in which case
01027   // we need to ignore them.
01028   bool FieldsAlreadyLoaded = false;
01029   if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
01030     FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
01031   
01032   // Splice the newly-read declarations into the beginning of the list
01033   // of declarations.
01034   Decl *ExternalFirst, *ExternalLast;
01035   std::tie(ExternalFirst, ExternalLast) =
01036       BuildDeclChain(Decls, FieldsAlreadyLoaded);
01037   ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
01038   FirstDecl = ExternalFirst;
01039   if (!LastDecl)
01040     LastDecl = ExternalLast;
01041 }
01042 
01043 DeclContext::lookup_result
01044 ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
01045                                                     DeclarationName Name) {
01046   ASTContext &Context = DC->getParentASTContext();
01047   StoredDeclsMap *Map;
01048   if (!(Map = DC->LookupPtr.getPointer()))
01049     Map = DC->CreateStoredDeclsMap(Context);
01050   if (DC->NeedToReconcileExternalVisibleStorage)
01051     DC->reconcileExternalVisibleStorage();
01052 
01053   (*Map)[Name].removeExternalDecls();
01054 
01055   return DeclContext::lookup_result();
01056 }
01057 
01058 DeclContext::lookup_result
01059 ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
01060                                                   DeclarationName Name,
01061                                                   ArrayRef<NamedDecl*> Decls) {
01062   ASTContext &Context = DC->getParentASTContext();
01063   StoredDeclsMap *Map;
01064   if (!(Map = DC->LookupPtr.getPointer()))
01065     Map = DC->CreateStoredDeclsMap(Context);
01066   if (DC->NeedToReconcileExternalVisibleStorage)
01067     DC->reconcileExternalVisibleStorage();
01068 
01069   StoredDeclsList &List = (*Map)[Name];
01070 
01071   // Clear out any old external visible declarations, to avoid quadratic
01072   // performance in the redeclaration checks below.
01073   List.removeExternalDecls();
01074 
01075   if (!List.isNull()) {
01076     // We have both existing declarations and new declarations for this name.
01077     // Some of the declarations may simply replace existing ones. Handle those
01078     // first.
01079     llvm::SmallVector<unsigned, 8> Skip;
01080     for (unsigned I = 0, N = Decls.size(); I != N; ++I)
01081       if (List.HandleRedeclaration(Decls[I]))
01082         Skip.push_back(I);
01083     Skip.push_back(Decls.size());
01084 
01085     // Add in any new declarations.
01086     unsigned SkipPos = 0;
01087     for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
01088       if (I == Skip[SkipPos])
01089         ++SkipPos;
01090       else
01091         List.AddSubsequentDecl(Decls[I]);
01092     }
01093   } else {
01094     // Convert the array to a StoredDeclsList.
01095     for (ArrayRef<NamedDecl*>::iterator
01096            I = Decls.begin(), E = Decls.end(); I != E; ++I) {
01097       if (List.isNull())
01098         List.setOnlyValue(*I);
01099       else
01100         List.AddSubsequentDecl(*I);
01101     }
01102   }
01103 
01104   return List.getLookupResult();
01105 }
01106 
01107 DeclContext::decl_iterator DeclContext::decls_begin() const {
01108   if (hasExternalLexicalStorage())
01109     LoadLexicalDeclsFromExternalStorage();
01110   return decl_iterator(FirstDecl);
01111 }
01112 
01113 bool DeclContext::decls_empty() const {
01114   if (hasExternalLexicalStorage())
01115     LoadLexicalDeclsFromExternalStorage();
01116 
01117   return !FirstDecl;
01118 }
01119 
01120 bool DeclContext::containsDecl(Decl *D) const {
01121   return (D->getLexicalDeclContext() == this &&
01122           (D->NextInContextAndBits.getPointer() || D == LastDecl));
01123 }
01124 
01125 void DeclContext::removeDecl(Decl *D) {
01126   assert(D->getLexicalDeclContext() == this &&
01127          "decl being removed from non-lexical context");
01128   assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
01129          "decl is not in decls list");
01130 
01131   // Remove D from the decl chain.  This is O(n) but hopefully rare.
01132   if (D == FirstDecl) {
01133     if (D == LastDecl)
01134       FirstDecl = LastDecl = nullptr;
01135     else
01136       FirstDecl = D->NextInContextAndBits.getPointer();
01137   } else {
01138     for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
01139       assert(I && "decl not found in linked list");
01140       if (I->NextInContextAndBits.getPointer() == D) {
01141         I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
01142         if (D == LastDecl) LastDecl = I;
01143         break;
01144       }
01145     }
01146   }
01147   
01148   // Mark that D is no longer in the decl chain.
01149   D->NextInContextAndBits.setPointer(nullptr);
01150 
01151   // Remove D from the lookup table if necessary.
01152   if (isa<NamedDecl>(D)) {
01153     NamedDecl *ND = cast<NamedDecl>(D);
01154 
01155     // Remove only decls that have a name
01156     if (!ND->getDeclName()) return;
01157 
01158     StoredDeclsMap *Map = getPrimaryContext()->LookupPtr.getPointer();
01159     if (!Map) return;
01160 
01161     StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
01162     assert(Pos != Map->end() && "no lookup entry for decl");
01163     if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
01164       Pos->second.remove(ND);
01165   }
01166 }
01167 
01168 void DeclContext::addHiddenDecl(Decl *D) {
01169   assert(D->getLexicalDeclContext() == this &&
01170          "Decl inserted into wrong lexical context");
01171   assert(!D->getNextDeclInContext() && D != LastDecl &&
01172          "Decl already inserted into a DeclContext");
01173 
01174   if (FirstDecl) {
01175     LastDecl->NextInContextAndBits.setPointer(D);
01176     LastDecl = D;
01177   } else {
01178     FirstDecl = LastDecl = D;
01179   }
01180 
01181   // Notify a C++ record declaration that we've added a member, so it can
01182   // update it's class-specific state.
01183   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
01184     Record->addedMember(D);
01185 
01186   // If this is a newly-created (not de-serialized) import declaration, wire
01187   // it in to the list of local import declarations.
01188   if (!D->isFromASTFile()) {
01189     if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
01190       D->getASTContext().addedLocalImportDecl(Import);
01191   }
01192 }
01193 
01194 void DeclContext::addDecl(Decl *D) {
01195   addHiddenDecl(D);
01196 
01197   if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
01198     ND->getDeclContext()->getPrimaryContext()->
01199         makeDeclVisibleInContextWithFlags(ND, false, true);
01200 }
01201 
01202 void DeclContext::addDeclInternal(Decl *D) {
01203   addHiddenDecl(D);
01204 
01205   if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
01206     ND->getDeclContext()->getPrimaryContext()->
01207         makeDeclVisibleInContextWithFlags(ND, true, true);
01208 }
01209 
01210 /// shouldBeHidden - Determine whether a declaration which was declared
01211 /// within its semantic context should be invisible to qualified name lookup.
01212 static bool shouldBeHidden(NamedDecl *D) {
01213   // Skip unnamed declarations.
01214   if (!D->getDeclName())
01215     return true;
01216 
01217   // Skip entities that can't be found by name lookup into a particular
01218   // context.
01219   if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
01220       D->isTemplateParameter())
01221     return true;
01222 
01223   // Skip template specializations.
01224   // FIXME: This feels like a hack. Should DeclarationName support
01225   // template-ids, or is there a better way to keep specializations
01226   // from being visible?
01227   if (isa<ClassTemplateSpecializationDecl>(D))
01228     return true;
01229   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
01230     if (FD->isFunctionTemplateSpecialization())
01231       return true;
01232 
01233   return false;
01234 }
01235 
01236 /// buildLookup - Build the lookup data structure with all of the
01237 /// declarations in this DeclContext (and any other contexts linked
01238 /// to it or transparent contexts nested within it) and return it.
01239 ///
01240 /// Note that the produced map may miss out declarations from an
01241 /// external source. If it does, those entries will be marked with
01242 /// the 'hasExternalDecls' flag.
01243 StoredDeclsMap *DeclContext::buildLookup() {
01244   assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
01245 
01246   // FIXME: Should we keep going if hasExternalVisibleStorage?
01247   if (!LookupPtr.getInt())
01248     return LookupPtr.getPointer();
01249 
01250   SmallVector<DeclContext *, 2> Contexts;
01251   collectAllContexts(Contexts);
01252   for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
01253     buildLookupImpl<&DeclContext::decls_begin,
01254                     &DeclContext::decls_end>(Contexts[I]);
01255 
01256   // We no longer have any lazy decls.
01257   LookupPtr.setInt(false);
01258   return LookupPtr.getPointer();
01259 }
01260 
01261 /// buildLookupImpl - Build part of the lookup data structure for the
01262 /// declarations contained within DCtx, which will either be this
01263 /// DeclContext, a DeclContext linked to it, or a transparent context
01264 /// nested within it.
01265 template<DeclContext::decl_iterator (DeclContext::*Begin)() const,
01266          DeclContext::decl_iterator (DeclContext::*End)() const>
01267 void DeclContext::buildLookupImpl(DeclContext *DCtx) {
01268   for (decl_iterator I = (DCtx->*Begin)(), E = (DCtx->*End)();
01269        I != E; ++I) {
01270     Decl *D = *I;
01271 
01272     // Insert this declaration into the lookup structure, but only if
01273     // it's semantically within its decl context. Any other decls which
01274     // should be found in this context are added eagerly.
01275     //
01276     // If it's from an AST file, don't add it now. It'll get handled by
01277     // FindExternalVisibleDeclsByName if needed. Exception: if we're not
01278     // in C++, we do not track external visible decls for the TU, so in
01279     // that case we need to collect them all here.
01280     if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
01281       if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
01282           (!ND->isFromASTFile() ||
01283            (isTranslationUnit() &&
01284             !getParentASTContext().getLangOpts().CPlusPlus)))
01285         makeDeclVisibleInContextImpl(ND, false);
01286 
01287     // If this declaration is itself a transparent declaration context
01288     // or inline namespace, add the members of this declaration of that
01289     // context (recursively).
01290     if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
01291       if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
01292         buildLookupImpl<Begin, End>(InnerCtx);
01293   }
01294 }
01295 
01296 DeclContext::lookup_result
01297 DeclContext::lookup(DeclarationName Name) {
01298   assert(DeclKind != Decl::LinkageSpec &&
01299          "Should not perform lookups into linkage specs!");
01300 
01301   DeclContext *PrimaryContext = getPrimaryContext();
01302   if (PrimaryContext != this)
01303     return PrimaryContext->lookup(Name);
01304 
01305   // If this is a namespace, ensure that any later redeclarations of it have
01306   // been loaded, since they may add names to the result of this lookup.
01307   if (auto *ND = dyn_cast<NamespaceDecl>(this))
01308     (void)ND->getMostRecentDecl();
01309 
01310   if (hasExternalVisibleStorage()) {
01311     if (NeedToReconcileExternalVisibleStorage)
01312       reconcileExternalVisibleStorage();
01313 
01314     StoredDeclsMap *Map = LookupPtr.getPointer();
01315 
01316     if (LookupPtr.getInt())
01317       Map = buildLookup();
01318 
01319     if (!Map)
01320       Map = CreateStoredDeclsMap(getParentASTContext());
01321 
01322     // If we have a lookup result with no external decls, we are done.
01323     std::pair<StoredDeclsMap::iterator, bool> R =
01324         Map->insert(std::make_pair(Name, StoredDeclsList()));
01325     if (!R.second && !R.first->second.hasExternalDecls())
01326       return R.first->second.getLookupResult();
01327 
01328     ExternalASTSource *Source = getParentASTContext().getExternalSource();
01329     if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) {
01330       if (StoredDeclsMap *Map = LookupPtr.getPointer()) {
01331         StoredDeclsMap::iterator I = Map->find(Name);
01332         if (I != Map->end())
01333           return I->second.getLookupResult();
01334       }
01335     }
01336 
01337     return lookup_result(lookup_iterator(nullptr), lookup_iterator(nullptr));
01338   }
01339 
01340   StoredDeclsMap *Map = LookupPtr.getPointer();
01341   if (LookupPtr.getInt())
01342     Map = buildLookup();
01343 
01344   if (!Map)
01345     return lookup_result(lookup_iterator(nullptr), lookup_iterator(nullptr));
01346 
01347   StoredDeclsMap::iterator I = Map->find(Name);
01348   if (I == Map->end())
01349     return lookup_result(lookup_iterator(nullptr), lookup_iterator(nullptr));
01350 
01351   return I->second.getLookupResult();
01352 }
01353 
01354 DeclContext::lookup_result
01355 DeclContext::noload_lookup(DeclarationName Name) {
01356   assert(DeclKind != Decl::LinkageSpec &&
01357          "Should not perform lookups into linkage specs!");
01358   if (!hasExternalVisibleStorage())
01359     return lookup(Name);
01360 
01361   DeclContext *PrimaryContext = getPrimaryContext();
01362   if (PrimaryContext != this)
01363     return PrimaryContext->noload_lookup(Name);
01364 
01365   StoredDeclsMap *Map = LookupPtr.getPointer();
01366   if (LookupPtr.getInt()) {
01367     // Carefully build the lookup map, without deserializing anything.
01368     SmallVector<DeclContext *, 2> Contexts;
01369     collectAllContexts(Contexts);
01370     for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
01371       buildLookupImpl<&DeclContext::noload_decls_begin,
01372                       &DeclContext::noload_decls_end>(Contexts[I]);
01373 
01374     // We no longer have any lazy decls.
01375     LookupPtr.setInt(false);
01376 
01377     // There may now be names for which we have local decls but are
01378     // missing the external decls. FIXME: Just set the hasExternalDecls
01379     // flag on those names that have external decls.
01380     NeedToReconcileExternalVisibleStorage = true;
01381 
01382     Map = LookupPtr.getPointer();
01383   }
01384 
01385   if (!Map)
01386     return lookup_result(lookup_iterator(nullptr), lookup_iterator(nullptr));
01387 
01388   StoredDeclsMap::iterator I = Map->find(Name);
01389   return I != Map->end() ? I->second.getLookupResult()
01390                          : lookup_result(lookup_iterator(nullptr),
01391                                          lookup_iterator(nullptr));
01392 }
01393 
01394 void DeclContext::localUncachedLookup(DeclarationName Name,
01395                                       SmallVectorImpl<NamedDecl *> &Results) {
01396   Results.clear();
01397   
01398   // If there's no external storage, just perform a normal lookup and copy
01399   // the results.
01400   if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
01401     lookup_result LookupResults = lookup(Name);
01402     Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
01403     return;
01404   }
01405 
01406   // If we have a lookup table, check there first. Maybe we'll get lucky.
01407   if (Name && !LookupPtr.getInt()) {
01408     if (StoredDeclsMap *Map = LookupPtr.getPointer()) {
01409       StoredDeclsMap::iterator Pos = Map->find(Name);
01410       if (Pos != Map->end()) {
01411         Results.insert(Results.end(),
01412                        Pos->second.getLookupResult().begin(),
01413                        Pos->second.getLookupResult().end());
01414         return;
01415       }
01416     }
01417   }
01418 
01419   // Slow case: grovel through the declarations in our chain looking for 
01420   // matches.
01421   for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
01422     if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
01423       if (ND->getDeclName() == Name)
01424         Results.push_back(ND);
01425   }
01426 }
01427 
01428 DeclContext *DeclContext::getRedeclContext() {
01429   DeclContext *Ctx = this;
01430   // Skip through transparent contexts.
01431   while (Ctx->isTransparentContext())
01432     Ctx = Ctx->getParent();
01433   return Ctx;
01434 }
01435 
01436 DeclContext *DeclContext::getEnclosingNamespaceContext() {
01437   DeclContext *Ctx = this;
01438   // Skip through non-namespace, non-translation-unit contexts.
01439   while (!Ctx->isFileContext())
01440     Ctx = Ctx->getParent();
01441   return Ctx->getPrimaryContext();
01442 }
01443 
01444 RecordDecl *DeclContext::getOuterLexicalRecordContext() {
01445   // Loop until we find a non-record context.
01446   RecordDecl *OutermostRD = nullptr;
01447   DeclContext *DC = this;
01448   while (DC->isRecord()) {
01449     OutermostRD = cast<RecordDecl>(DC);
01450     DC = DC->getLexicalParent();
01451   }
01452   return OutermostRD;
01453 }
01454 
01455 bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
01456   // For non-file contexts, this is equivalent to Equals.
01457   if (!isFileContext())
01458     return O->Equals(this);
01459 
01460   do {
01461     if (O->Equals(this))
01462       return true;
01463 
01464     const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
01465     if (!NS || !NS->isInline())
01466       break;
01467     O = NS->getParent();
01468   } while (O);
01469 
01470   return false;
01471 }
01472 
01473 void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
01474   DeclContext *PrimaryDC = this->getPrimaryContext();
01475   DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
01476   // If the decl is being added outside of its semantic decl context, we
01477   // need to ensure that we eagerly build the lookup information for it.
01478   PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
01479 }
01480 
01481 void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
01482                                                     bool Recoverable) {
01483   assert(this == getPrimaryContext() && "expected a primary DC");
01484 
01485   // Skip declarations within functions.
01486   if (isFunctionOrMethod())
01487     return;
01488 
01489   // Skip declarations which should be invisible to name lookup.
01490   if (shouldBeHidden(D))
01491     return;
01492 
01493   // If we already have a lookup data structure, perform the insertion into
01494   // it. If we might have externally-stored decls with this name, look them
01495   // up and perform the insertion. If this decl was declared outside its
01496   // semantic context, buildLookup won't add it, so add it now.
01497   //
01498   // FIXME: As a performance hack, don't add such decls into the translation
01499   // unit unless we're in C++, since qualified lookup into the TU is never
01500   // performed.
01501   if (LookupPtr.getPointer() || hasExternalVisibleStorage() ||
01502       ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
01503        (getParentASTContext().getLangOpts().CPlusPlus ||
01504         !isTranslationUnit()))) {
01505     // If we have lazily omitted any decls, they might have the same name as
01506     // the decl which we are adding, so build a full lookup table before adding
01507     // this decl.
01508     buildLookup();
01509     makeDeclVisibleInContextImpl(D, Internal);
01510   } else {
01511     LookupPtr.setInt(true);
01512   }
01513 
01514   // If we are a transparent context or inline namespace, insert into our
01515   // parent context, too. This operation is recursive.
01516   if (isTransparentContext() || isInlineNamespace())
01517     getParent()->getPrimaryContext()->
01518         makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
01519 
01520   Decl *DCAsDecl = cast<Decl>(this);
01521   // Notify that a decl was made visible unless we are a Tag being defined.
01522   if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
01523     if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
01524       L->AddedVisibleDecl(this, D);
01525 }
01526 
01527 void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
01528   // Find or create the stored declaration map.
01529   StoredDeclsMap *Map = LookupPtr.getPointer();
01530   if (!Map) {
01531     ASTContext *C = &getParentASTContext();
01532     Map = CreateStoredDeclsMap(*C);
01533   }
01534 
01535   // If there is an external AST source, load any declarations it knows about
01536   // with this declaration's name.
01537   // If the lookup table contains an entry about this name it means that we
01538   // have already checked the external source.
01539   if (!Internal)
01540     if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
01541       if (hasExternalVisibleStorage() &&
01542           Map->find(D->getDeclName()) == Map->end())
01543         Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
01544 
01545   // Insert this declaration into the map.
01546   StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
01547 
01548   if (Internal) {
01549     // If this is being added as part of loading an external declaration,
01550     // this may not be the only external declaration with this name.
01551     // In this case, we never try to replace an existing declaration; we'll
01552     // handle that when we finalize the list of declarations for this name.
01553     DeclNameEntries.setHasExternalDecls();
01554     DeclNameEntries.AddSubsequentDecl(D);
01555     return;
01556   }
01557 
01558   else if (DeclNameEntries.isNull()) {
01559     DeclNameEntries.setOnlyValue(D);
01560     return;
01561   }
01562 
01563   if (DeclNameEntries.HandleRedeclaration(D)) {
01564     // This declaration has replaced an existing one for which
01565     // declarationReplaces returns true.
01566     return;
01567   }
01568 
01569   // Put this declaration into the appropriate slot.
01570   DeclNameEntries.AddSubsequentDecl(D);
01571 }
01572 
01573 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
01574 /// this context.
01575 DeclContext::udir_range DeclContext::using_directives() const {
01576   // FIXME: Use something more efficient than normal lookup for using
01577   // directives. In C++, using directives are looked up more than anything else.
01578   lookup_const_result Result = lookup(UsingDirectiveDecl::getName());
01579   return udir_range(
01580       reinterpret_cast<UsingDirectiveDecl *const *>(Result.begin()),
01581       reinterpret_cast<UsingDirectiveDecl *const *>(Result.end()));
01582 }
01583 
01584 //===----------------------------------------------------------------------===//
01585 // Creation and Destruction of StoredDeclsMaps.                               //
01586 //===----------------------------------------------------------------------===//
01587 
01588 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
01589   assert(!LookupPtr.getPointer() && "context already has a decls map");
01590   assert(getPrimaryContext() == this &&
01591          "creating decls map on non-primary context");
01592 
01593   StoredDeclsMap *M;
01594   bool Dependent = isDependentContext();
01595   if (Dependent)
01596     M = new DependentStoredDeclsMap();
01597   else
01598     M = new StoredDeclsMap();
01599   M->Previous = C.LastSDM;
01600   C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
01601   LookupPtr.setPointer(M);
01602   return M;
01603 }
01604 
01605 void ASTContext::ReleaseDeclContextMaps() {
01606   // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
01607   // pointer because the subclass doesn't add anything that needs to
01608   // be deleted.
01609   StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
01610 }
01611 
01612 void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
01613   while (Map) {
01614     // Advance the iteration before we invalidate memory.
01615     llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
01616 
01617     if (Dependent)
01618       delete static_cast<DependentStoredDeclsMap*>(Map);
01619     else
01620       delete Map;
01621 
01622     Map = Next.getPointer();
01623     Dependent = Next.getInt();
01624   }
01625 }
01626 
01627 DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
01628                                                  DeclContext *Parent,
01629                                            const PartialDiagnostic &PDiag) {
01630   assert(Parent->isDependentContext()
01631          && "cannot iterate dependent diagnostics of non-dependent context");
01632   Parent = Parent->getPrimaryContext();
01633   if (!Parent->LookupPtr.getPointer())
01634     Parent->CreateStoredDeclsMap(C);
01635 
01636   DependentStoredDeclsMap *Map
01637     = static_cast<DependentStoredDeclsMap*>(Parent->LookupPtr.getPointer());
01638 
01639   // Allocate the copy of the PartialDiagnostic via the ASTContext's
01640   // BumpPtrAllocator, rather than the ASTContext itself.
01641   PartialDiagnostic::Storage *DiagStorage = nullptr;
01642   if (PDiag.hasStorage())
01643     DiagStorage = new (C) PartialDiagnostic::Storage;
01644   
01645   DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
01646 
01647   // TODO: Maybe we shouldn't reverse the order during insertion.
01648   DD->NextDiagnostic = Map->FirstDiagnostic;
01649   Map->FirstDiagnostic = DD;
01650 
01651   return DD;
01652 }