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