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