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