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