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