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 "llvm/ADT/DenseMap.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include <algorithm>
30 #include <cstdio>
31 #include <vector>
32 using namespace clang;
33 
34 //===----------------------------------------------------------------------===//
35 //  Statistics
36 //===----------------------------------------------------------------------===//
37 
38 #define DECL(Derived, Base) static int n##Derived##s = 0;
39 #include "clang/AST/DeclNodes.def"
40 
41 static bool StatSwitch = false;
42 
43 const char *Decl::getDeclKindName() const {
44   switch (DeclKind) {
45   default: assert(0 && "Declaration not in DeclNodes.def!");
46 #define DECL(Derived, Base) case Derived: return #Derived;
47 #include "clang/AST/DeclNodes.def"
48   }
49 }
50 
51 void Decl::setInvalidDecl(bool Invalid) {
52   InvalidDecl = Invalid;
53   if (Invalid) {
54     // Defensive maneuver for ill-formed code: we're likely not to make it to
55     // a point where we set the access specifier, so default it to "public"
56     // to avoid triggering asserts elsewhere in the front end.
57     setAccess(AS_public);
58   }
59 }
60 
61 const char *DeclContext::getDeclKindName() const {
62   switch (DeclKind) {
63   default: assert(0 && "Declaration context not in DeclNodes.def!");
64 #define DECL(Derived, Base) case Decl::Derived: return #Derived;
65 #include "clang/AST/DeclNodes.def"
66   }
67 }
68 
69 bool Decl::CollectingStats(bool Enable) {
70   if (Enable) StatSwitch = true;
71   return StatSwitch;
72 }
73 
74 void Decl::PrintStats() {
75   fprintf(stderr, "*** Decl Stats:\n");
76 
77   int totalDecls = 0;
78 #define DECL(Derived, Base) totalDecls += n##Derived##s;
79 #include "clang/AST/DeclNodes.def"
80   fprintf(stderr, "  %d decls total.\n", totalDecls);
81 
82   int totalBytes = 0;
83 #define DECL(Derived, Base)                                             \
84   if (n##Derived##s > 0) {                                              \
85     totalBytes += (int)(n##Derived##s * sizeof(Derived##Decl));         \
86     fprintf(stderr, "    %d " #Derived " decls, %d each (%d bytes)\n",  \
87             n##Derived##s, (int)sizeof(Derived##Decl),                  \
88             (int)(n##Derived##s * sizeof(Derived##Decl)));              \
89   }
90 #include "clang/AST/DeclNodes.def"
91 
92   fprintf(stderr, "Total bytes = %d\n", totalBytes);
93 }
94 
95 void Decl::addDeclKind(Kind k) {
96   switch (k) {
97   default: assert(0 && "Declaration not in DeclNodes.def!");
98 #define DECL(Derived, Base) case Derived: ++n##Derived##s; break;
99 #include "clang/AST/DeclNodes.def"
100   }
101 }
102 
103 bool Decl::isTemplateParameterPack() const {
104   if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
105     return TTP->isParameterPack();
106 
107   return false;
108 }
109 
110 bool Decl::isFunctionOrFunctionTemplate() const {
111   if (const UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(this))
112     return UD->getTargetDecl()->isFunctionOrFunctionTemplate();
113 
114   return isa<FunctionDecl>(this) || isa<FunctionTemplateDecl>(this);
115 }
116 
117 bool Decl::isDefinedOutsideFunctionOrMethod() const {
118   for (const DeclContext *DC = getDeclContext();
119        DC && !DC->isTranslationUnit();
120        DC = DC->getParent())
121     if (DC->isFunctionOrMethod())
122       return false;
123 
124   return true;
125 }
126 
127 
128 //===----------------------------------------------------------------------===//
129 // PrettyStackTraceDecl Implementation
130 //===----------------------------------------------------------------------===//
131 
132 void PrettyStackTraceDecl::print(llvm::raw_ostream &OS) const {
133   SourceLocation TheLoc = Loc;
134   if (TheLoc.isInvalid() && TheDecl)
135     TheLoc = TheDecl->getLocation();
136 
137   if (TheLoc.isValid()) {
138     TheLoc.print(OS, SM);
139     OS << ": ";
140   }
141 
142   OS << Message;
143 
144   if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl))
145     OS << " '" << DN->getQualifiedNameAsString() << '\'';
146   OS << '\n';
147 }
148 
149 //===----------------------------------------------------------------------===//
150 // Decl Implementation
151 //===----------------------------------------------------------------------===//
152 
153 // Out-of-line virtual method providing a home for Decl.
154 Decl::~Decl() {
155   assert(!HasAttrs && "attributes should have been freed by Destroy");
156 }
157 
158 void Decl::setDeclContext(DeclContext *DC) {
159   if (isOutOfSemaDC())
160     delete getMultipleDC();
161 
162   DeclCtx = DC;
163 }
164 
165 void Decl::setLexicalDeclContext(DeclContext *DC) {
166   if (DC == getLexicalDeclContext())
167     return;
168 
169   if (isInSemaDC()) {
170     MultipleDC *MDC = new (getASTContext()) MultipleDC();
171     MDC->SemanticDC = getDeclContext();
172     MDC->LexicalDC = DC;
173     DeclCtx = MDC;
174   } else {
175     getMultipleDC()->LexicalDC = DC;
176   }
177 }
178 
179 bool Decl::isInAnonymousNamespace() const {
180   const DeclContext *DC = getDeclContext();
181   do {
182     if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
183       if (ND->isAnonymousNamespace())
184         return true;
185   } while ((DC = DC->getParent()));
186 
187   return false;
188 }
189 
190 TranslationUnitDecl *Decl::getTranslationUnitDecl() {
191   if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
192     return TUD;
193 
194   DeclContext *DC = getDeclContext();
195   assert(DC && "This decl is not contained in a translation unit!");
196 
197   while (!DC->isTranslationUnit()) {
198     DC = DC->getParent();
199     assert(DC && "This decl is not contained in a translation unit!");
200   }
201 
202   return cast<TranslationUnitDecl>(DC);
203 }
204 
205 ASTContext &Decl::getASTContext() const {
206   return getTranslationUnitDecl()->getASTContext();
207 }
208 
209 bool Decl::isUsed() const {
210   if (Used)
211     return true;
212 
213   // Check for used attribute.
214   if (hasAttr<UsedAttr>())
215     return true;
216 
217   // Check redeclarations for used attribute.
218   for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
219     if (I->hasAttr<UsedAttr>() || I->Used)
220       return true;
221   }
222 
223   return false;
224 }
225 
226 
227 unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
228   switch (DeclKind) {
229     case Function:
230     case CXXMethod:
231     case CXXConstructor:
232     case CXXDestructor:
233     case CXXConversion:
234     case EnumConstant:
235     case Var:
236     case ImplicitParam:
237     case ParmVar:
238     case NonTypeTemplateParm:
239     case ObjCMethod:
240     case ObjCProperty:
241       return IDNS_Ordinary;
242 
243     case ObjCCompatibleAlias:
244     case ObjCInterface:
245       return IDNS_Ordinary | IDNS_Type;
246 
247     case Typedef:
248     case UnresolvedUsingTypename:
249     case TemplateTypeParm:
250       return IDNS_Ordinary | IDNS_Type;
251 
252     case UsingShadow:
253       return 0; // we'll actually overwrite this later
254 
255     case UnresolvedUsingValue:
256       return IDNS_Ordinary | IDNS_Using;
257 
258     case Using:
259       return IDNS_Using;
260 
261     case ObjCProtocol:
262       return IDNS_ObjCProtocol;
263 
264     case Field:
265     case ObjCAtDefsField:
266     case ObjCIvar:
267       return IDNS_Member;
268 
269     case Record:
270     case CXXRecord:
271     case Enum:
272       return IDNS_Tag | IDNS_Type;
273 
274     case Namespace:
275     case NamespaceAlias:
276       return IDNS_Namespace;
277 
278     case FunctionTemplate:
279       return IDNS_Ordinary;
280 
281     case ClassTemplate:
282     case TemplateTemplateParm:
283       return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
284 
285     // Never have names.
286     case Friend:
287     case FriendTemplate:
288     case LinkageSpec:
289     case FileScopeAsm:
290     case StaticAssert:
291     case ObjCClass:
292     case ObjCPropertyImpl:
293     case ObjCForwardProtocol:
294     case Block:
295     case TranslationUnit:
296 
297     case UsingDirective:
298     case ClassTemplateSpecialization:
299     case ClassTemplatePartialSpecialization:
300     case ObjCImplementation:
301     case ObjCCategory:
302     case ObjCCategoryImpl:
303       // Never looked up by name.
304       return 0;
305   }
306 
307   return 0;
308 }
309 
310 void Decl::addAttr(Attr *NewAttr) {
311   Attr *&ExistingAttr = getASTContext().getDeclAttrs(this);
312 
313   NewAttr->setNext(ExistingAttr);
314   ExistingAttr = NewAttr;
315 
316   HasAttrs = true;
317 }
318 
319 void Decl::invalidateAttrs() {
320   if (!HasAttrs) return;
321 
322   HasAttrs = false;
323   getASTContext().eraseDeclAttrs(this);
324 }
325 
326 const Attr *Decl::getAttrsImpl() const {
327   assert(HasAttrs && "getAttrs() should verify this!");
328   return getASTContext().getDeclAttrs(this);
329 }
330 
331 void Decl::swapAttrs(Decl *RHS) {
332   bool HasLHSAttr = this->HasAttrs;
333   bool HasRHSAttr = RHS->HasAttrs;
334 
335   // Usually, neither decl has attrs, nothing to do.
336   if (!HasLHSAttr && !HasRHSAttr) return;
337 
338   // If 'this' has no attrs, swap the other way.
339   if (!HasLHSAttr)
340     return RHS->swapAttrs(this);
341 
342   ASTContext &Context = getASTContext();
343 
344   // Handle the case when both decls have attrs.
345   if (HasRHSAttr) {
346     std::swap(Context.getDeclAttrs(this), Context.getDeclAttrs(RHS));
347     return;
348   }
349 
350   // Otherwise, LHS has an attr and RHS doesn't.
351   Context.getDeclAttrs(RHS) = Context.getDeclAttrs(this);
352   Context.eraseDeclAttrs(this);
353   this->HasAttrs = false;
354   RHS->HasAttrs = true;
355 }
356 
357 
358 void Decl::Destroy(ASTContext &C) {
359   // Free attributes for this decl.
360   if (HasAttrs) {
361     C.getDeclAttrs(this)->Destroy(C);
362     invalidateAttrs();
363     HasAttrs = false;
364   }
365 
366 #if 0
367   // FIXME: Once ownership is fully understood, we can enable this code
368   if (DeclContext *DC = dyn_cast<DeclContext>(this))
369     DC->decls_begin()->Destroy(C);
370 
371   // Observe the unrolled recursion.  By setting N->NextDeclInContext = 0x0
372   // within the loop, only the Destroy method for the first Decl
373   // will deallocate all of the Decls in a chain.
374 
375   Decl* N = getNextDeclInContext();
376 
377   while (N) {
378     Decl* Tmp = N->getNextDeclInContext();
379     N->NextDeclInContext = 0;
380     N->Destroy(C);
381     N = Tmp;
382   }
383 
384   if (isOutOfSemaDC())
385     delete (C) getMultipleDC();
386 
387   this->~Decl();
388   C.Deallocate((void *)this);
389 #endif
390 }
391 
392 Decl *Decl::castFromDeclContext (const DeclContext *D) {
393   Decl::Kind DK = D->getDeclKind();
394   switch(DK) {
395 #define DECL_CONTEXT(Name) \
396     case Decl::Name:     \
397       return static_cast<Name##Decl*>(const_cast<DeclContext*>(D));
398 #define DECL_CONTEXT_BASE(Name)
399 #include "clang/AST/DeclNodes.def"
400     default:
401 #define DECL_CONTEXT_BASE(Name)                                   \
402       if (DK >= Decl::Name##First && DK <= Decl::Name##Last)    \
403         return static_cast<Name##Decl*>(const_cast<DeclContext*>(D));
404 #include "clang/AST/DeclNodes.def"
405       assert(false && "a decl that inherits DeclContext isn't handled");
406       return 0;
407   }
408 }
409 
410 DeclContext *Decl::castToDeclContext(const Decl *D) {
411   Decl::Kind DK = D->getKind();
412   switch(DK) {
413 #define DECL_CONTEXT(Name) \
414     case Decl::Name:     \
415       return static_cast<Name##Decl*>(const_cast<Decl*>(D));
416 #define DECL_CONTEXT_BASE(Name)
417 #include "clang/AST/DeclNodes.def"
418     default:
419 #define DECL_CONTEXT_BASE(Name)                                   \
420       if (DK >= Decl::Name##First && DK <= Decl::Name##Last)    \
421         return static_cast<Name##Decl*>(const_cast<Decl*>(D));
422 #include "clang/AST/DeclNodes.def"
423       assert(false && "a decl that inherits DeclContext isn't handled");
424       return 0;
425   }
426 }
427 
428 CompoundStmt* Decl::getCompoundBody() const {
429   return dyn_cast_or_null<CompoundStmt>(getBody());
430 }
431 
432 SourceLocation Decl::getBodyRBrace() const {
433   Stmt *Body = getBody();
434   if (!Body)
435     return SourceLocation();
436   if (CompoundStmt *CS = dyn_cast<CompoundStmt>(Body))
437     return CS->getRBracLoc();
438   assert(isa<CXXTryStmt>(Body) &&
439          "Body can only be CompoundStmt or CXXTryStmt");
440   return cast<CXXTryStmt>(Body)->getSourceRange().getEnd();
441 }
442 
443 #ifndef NDEBUG
444 void Decl::CheckAccessDeclContext() const {
445   // Suppress this check if any of the following hold:
446   // 1. this is the translation unit (and thus has no parent)
447   // 2. this is a template parameter (and thus doesn't belong to its context)
448   // 3. this is a ParmVarDecl (which can be in a record context during
449   //    the brief period between its creation and the creation of the
450   //    FunctionDecl)
451   // 4. the context is not a record
452   if (isa<TranslationUnitDecl>(this) ||
453       !isa<CXXRecordDecl>(getDeclContext()) ||
454       isInvalidDecl())
455     return;
456 
457   assert(Access != AS_none &&
458          "Access specifier is AS_none inside a record decl");
459 }
460 
461 #endif
462 
463 //===----------------------------------------------------------------------===//
464 // DeclContext Implementation
465 //===----------------------------------------------------------------------===//
466 
467 bool DeclContext::classof(const Decl *D) {
468   switch (D->getKind()) {
469 #define DECL_CONTEXT(Name) case Decl::Name:
470 #define DECL_CONTEXT_BASE(Name)
471 #include "clang/AST/DeclNodes.def"
472       return true;
473     default:
474 #define DECL_CONTEXT_BASE(Name)                   \
475       if (D->getKind() >= Decl::Name##First &&  \
476           D->getKind() <= Decl::Name##Last)     \
477         return true;
478 #include "clang/AST/DeclNodes.def"
479       return false;
480   }
481 }
482 
483 DeclContext::~DeclContext() {
484   // FIXME: Currently ~ASTContext will delete the StoredDeclsMaps because
485   // ~DeclContext() is not guaranteed to be called when ASTContext uses
486   // a BumpPtrAllocator.
487   // delete LookupPtr;
488 }
489 
490 void DeclContext::DestroyDecls(ASTContext &C) {
491   for (decl_iterator D = decls_begin(); D != decls_end(); )
492     (*D++)->Destroy(C);
493 }
494 
495 /// \brief Find the parent context of this context that will be
496 /// used for unqualified name lookup.
497 ///
498 /// Generally, the parent lookup context is the semantic context. However, for
499 /// a friend function the parent lookup context is the lexical context, which
500 /// is the class in which the friend is declared.
501 DeclContext *DeclContext::getLookupParent() {
502   // FIXME: Find a better way to identify friends
503   if (isa<FunctionDecl>(this))
504     if (getParent()->getLookupContext()->isFileContext() &&
505         getLexicalParent()->getLookupContext()->isRecord())
506       return getLexicalParent();
507 
508   return getParent();
509 }
510 
511 bool DeclContext::isDependentContext() const {
512   if (isFileContext())
513     return false;
514 
515   if (isa<ClassTemplatePartialSpecializationDecl>(this))
516     return true;
517 
518   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
519     if (Record->getDescribedClassTemplate())
520       return true;
521 
522   if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
523     if (Function->getDescribedFunctionTemplate())
524       return true;
525 
526     // Friend function declarations are dependent if their *lexical*
527     // context is dependent.
528     if (cast<Decl>(this)->getFriendObjectKind())
529       return getLexicalParent()->isDependentContext();
530   }
531 
532   return getParent() && getParent()->isDependentContext();
533 }
534 
535 bool DeclContext::isTransparentContext() const {
536   if (DeclKind == Decl::Enum)
537     return true; // FIXME: Check for C++0x scoped enums
538   else if (DeclKind == Decl::LinkageSpec)
539     return true;
540   else if (DeclKind >= Decl::RecordFirst && DeclKind <= Decl::RecordLast)
541     return cast<RecordDecl>(this)->isAnonymousStructOrUnion();
542   else if (DeclKind == Decl::Namespace)
543     return false; // FIXME: Check for C++0x inline namespaces
544 
545   return false;
546 }
547 
548 bool DeclContext::Encloses(DeclContext *DC) {
549   if (getPrimaryContext() != this)
550     return getPrimaryContext()->Encloses(DC);
551 
552   for (; DC; DC = DC->getParent())
553     if (DC->getPrimaryContext() == this)
554       return true;
555   return false;
556 }
557 
558 DeclContext *DeclContext::getPrimaryContext() {
559   switch (DeclKind) {
560   case Decl::TranslationUnit:
561   case Decl::LinkageSpec:
562   case Decl::Block:
563     // There is only one DeclContext for these entities.
564     return this;
565 
566   case Decl::Namespace:
567     // The original namespace is our primary context.
568     return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
569 
570   case Decl::ObjCMethod:
571     return this;
572 
573   case Decl::ObjCInterface:
574   case Decl::ObjCProtocol:
575   case Decl::ObjCCategory:
576     // FIXME: Can Objective-C interfaces be forward-declared?
577     return this;
578 
579   case Decl::ObjCImplementation:
580   case Decl::ObjCCategoryImpl:
581     return this;
582 
583   default:
584     if (DeclKind >= Decl::TagFirst && DeclKind <= Decl::TagLast) {
585       // If this is a tag type that has a definition or is currently
586       // being defined, that definition is our primary context.
587       TagDecl *Tag = cast<TagDecl>(this);
588       assert(isa<TagType>(Tag->TypeForDecl) ||
589              isa<InjectedClassNameType>(Tag->TypeForDecl));
590 
591       if (TagDecl *Def = Tag->getDefinition())
592         return Def;
593 
594       if (!isa<InjectedClassNameType>(Tag->TypeForDecl)) {
595         const TagType *TagTy = cast<TagType>(Tag->TypeForDecl);
596         if (TagTy->isBeingDefined())
597           // FIXME: is it necessarily being defined in the decl
598           // that owns the type?
599           return TagTy->getDecl();
600       }
601 
602       return Tag;
603     }
604 
605     assert(DeclKind >= Decl::FunctionFirst && DeclKind <= Decl::FunctionLast &&
606           "Unknown DeclContext kind");
607     return this;
608   }
609 }
610 
611 DeclContext *DeclContext::getNextContext() {
612   switch (DeclKind) {
613   case Decl::Namespace:
614     // Return the next namespace
615     return static_cast<NamespaceDecl*>(this)->getNextNamespace();
616 
617   default:
618     return 0;
619   }
620 }
621 
622 /// \brief Load the declarations within this lexical storage from an
623 /// external source.
624 void
625 DeclContext::LoadLexicalDeclsFromExternalStorage() const {
626   ExternalASTSource *Source = getParentASTContext().getExternalSource();
627   assert(hasExternalLexicalStorage() && Source && "No external storage?");
628 
629   llvm::SmallVector<uint32_t, 64> Decls;
630   if (Source->ReadDeclsLexicallyInContext(const_cast<DeclContext *>(this),
631                                           Decls))
632     return;
633 
634   // There is no longer any lexical storage in this context
635   ExternalLexicalStorage = false;
636 
637   if (Decls.empty())
638     return;
639 
640   // Resolve all of the declaration IDs into declarations, building up
641   // a chain of declarations via the Decl::NextDeclInContext field.
642   Decl *FirstNewDecl = 0;
643   Decl *PrevDecl = 0;
644   for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
645     Decl *D = Source->GetDecl(Decls[I]);
646     if (PrevDecl)
647       PrevDecl->NextDeclInContext = D;
648     else
649       FirstNewDecl = D;
650 
651     PrevDecl = D;
652   }
653 
654   // Splice the newly-read declarations into the beginning of the list
655   // of declarations.
656   PrevDecl->NextDeclInContext = FirstDecl;
657   FirstDecl = FirstNewDecl;
658   if (!LastDecl)
659     LastDecl = PrevDecl;
660 }
661 
662 void
663 DeclContext::LoadVisibleDeclsFromExternalStorage() const {
664   DeclContext *This = const_cast<DeclContext *>(this);
665   ExternalASTSource *Source = getParentASTContext().getExternalSource();
666   assert(hasExternalVisibleStorage() && Source && "No external storage?");
667 
668   llvm::SmallVector<VisibleDeclaration, 64> Decls;
669   if (Source->ReadDeclsVisibleInContext(This, Decls))
670     return;
671 
672   // There is no longer any visible storage in this context
673   ExternalVisibleStorage = false;
674 
675   // Load the declaration IDs for all of the names visible in this
676   // context.
677   assert(!LookupPtr && "Have a lookup map before de-serialization?");
678   StoredDeclsMap *Map = CreateStoredDeclsMap(getParentASTContext());
679   for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
680     (*Map)[Decls[I].Name].setFromDeclIDs(Decls[I].Declarations);
681   }
682 }
683 
684 DeclContext::decl_iterator DeclContext::decls_begin() const {
685   if (hasExternalLexicalStorage())
686     LoadLexicalDeclsFromExternalStorage();
687 
688   // FIXME: Check whether we need to load some declarations from
689   // external storage.
690   return decl_iterator(FirstDecl);
691 }
692 
693 DeclContext::decl_iterator DeclContext::decls_end() const {
694   if (hasExternalLexicalStorage())
695     LoadLexicalDeclsFromExternalStorage();
696 
697   return decl_iterator();
698 }
699 
700 bool DeclContext::decls_empty() const {
701   if (hasExternalLexicalStorage())
702     LoadLexicalDeclsFromExternalStorage();
703 
704   return !FirstDecl;
705 }
706 
707 void DeclContext::removeDecl(Decl *D) {
708   assert(D->getLexicalDeclContext() == this &&
709          "decl being removed from non-lexical context");
710   assert((D->NextDeclInContext || D == LastDecl) &&
711          "decl is not in decls list");
712 
713   // Remove D from the decl chain.  This is O(n) but hopefully rare.
714   if (D == FirstDecl) {
715     if (D == LastDecl)
716       FirstDecl = LastDecl = 0;
717     else
718       FirstDecl = D->NextDeclInContext;
719   } else {
720     for (Decl *I = FirstDecl; true; I = I->NextDeclInContext) {
721       assert(I && "decl not found in linked list");
722       if (I->NextDeclInContext == D) {
723         I->NextDeclInContext = D->NextDeclInContext;
724         if (D == LastDecl) LastDecl = I;
725         break;
726       }
727     }
728   }
729 
730   // Mark that D is no longer in the decl chain.
731   D->NextDeclInContext = 0;
732 
733   // Remove D from the lookup table if necessary.
734   if (isa<NamedDecl>(D)) {
735     NamedDecl *ND = cast<NamedDecl>(D);
736 
737     StoredDeclsMap *Map = getPrimaryContext()->LookupPtr;
738     if (!Map) return;
739 
740     StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
741     assert(Pos != Map->end() && "no lookup entry for decl");
742     Pos->second.remove(ND);
743   }
744 }
745 
746 void DeclContext::addHiddenDecl(Decl *D) {
747   assert(D->getLexicalDeclContext() == this &&
748          "Decl inserted into wrong lexical context");
749   assert(!D->getNextDeclInContext() && D != LastDecl &&
750          "Decl already inserted into a DeclContext");
751 
752   if (FirstDecl) {
753     LastDecl->NextDeclInContext = D;
754     LastDecl = D;
755   } else {
756     FirstDecl = LastDecl = D;
757   }
758 }
759 
760 void DeclContext::addDecl(Decl *D) {
761   addHiddenDecl(D);
762 
763   if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
764     ND->getDeclContext()->makeDeclVisibleInContext(ND);
765 }
766 
767 /// buildLookup - Build the lookup data structure with all of the
768 /// declarations in DCtx (and any other contexts linked to it or
769 /// transparent contexts nested within it).
770 void DeclContext::buildLookup(DeclContext *DCtx) {
771   for (; DCtx; DCtx = DCtx->getNextContext()) {
772     for (decl_iterator D = DCtx->decls_begin(),
773                     DEnd = DCtx->decls_end();
774          D != DEnd; ++D) {
775       // Insert this declaration into the lookup structure, but only
776       // if it's semantically in its decl context.  During non-lazy
777       // lookup building, this is implicitly enforced by addDecl.
778       if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
779         if (D->getDeclContext() == DCtx)
780           makeDeclVisibleInContextImpl(ND);
781 
782       // Insert any forward-declared Objective-C interfaces into the lookup
783       // data structure.
784       if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(*D))
785         for (ObjCClassDecl::iterator I = Class->begin(), IEnd = Class->end();
786              I != IEnd; ++I)
787           makeDeclVisibleInContextImpl(I->getInterface());
788 
789       // If this declaration is itself a transparent declaration context,
790       // add its members (recursively).
791       if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D))
792         if (InnerCtx->isTransparentContext())
793           buildLookup(InnerCtx->getPrimaryContext());
794     }
795   }
796 }
797 
798 DeclContext::lookup_result
799 DeclContext::lookup(DeclarationName Name) {
800   DeclContext *PrimaryContext = getPrimaryContext();
801   if (PrimaryContext != this)
802     return PrimaryContext->lookup(Name);
803 
804   if (hasExternalVisibleStorage())
805     LoadVisibleDeclsFromExternalStorage();
806 
807   /// If there is no lookup data structure, build one now by walking
808   /// all of the linked DeclContexts (in declaration order!) and
809   /// inserting their values.
810   if (!LookupPtr) {
811     buildLookup(this);
812 
813     if (!LookupPtr)
814       return lookup_result(0, 0);
815   }
816 
817   StoredDeclsMap::iterator Pos = LookupPtr->find(Name);
818   if (Pos == LookupPtr->end())
819     return lookup_result(0, 0);
820   return Pos->second.getLookupResult(getParentASTContext());
821 }
822 
823 DeclContext::lookup_const_result
824 DeclContext::lookup(DeclarationName Name) const {
825   return const_cast<DeclContext*>(this)->lookup(Name);
826 }
827 
828 DeclContext *DeclContext::getLookupContext() {
829   DeclContext *Ctx = this;
830   // Skip through transparent contexts.
831   while (Ctx->isTransparentContext())
832     Ctx = Ctx->getParent();
833   return Ctx;
834 }
835 
836 DeclContext *DeclContext::getEnclosingNamespaceContext() {
837   DeclContext *Ctx = this;
838   // Skip through non-namespace, non-translation-unit contexts.
839   while (!Ctx->isFileContext() || Ctx->isTransparentContext())
840     Ctx = Ctx->getParent();
841   return Ctx->getPrimaryContext();
842 }
843 
844 void DeclContext::makeDeclVisibleInContext(NamedDecl *D, bool Recoverable) {
845   // FIXME: This feels like a hack. Should DeclarationName support
846   // template-ids, or is there a better way to keep specializations
847   // from being visible?
848   if (isa<ClassTemplateSpecializationDecl>(D))
849     return;
850   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
851     if (FD->isFunctionTemplateSpecialization())
852       return;
853 
854   DeclContext *PrimaryContext = getPrimaryContext();
855   if (PrimaryContext != this) {
856     PrimaryContext->makeDeclVisibleInContext(D, Recoverable);
857     return;
858   }
859 
860   // If we already have a lookup data structure, perform the insertion
861   // into it. Otherwise, be lazy and don't build that structure until
862   // someone asks for it.
863   if (LookupPtr || !Recoverable)
864     makeDeclVisibleInContextImpl(D);
865 
866   // If we are a transparent context, insert into our parent context,
867   // too. This operation is recursive.
868   if (isTransparentContext())
869     getParent()->makeDeclVisibleInContext(D, Recoverable);
870 }
871 
872 void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D) {
873   // Skip unnamed declarations.
874   if (!D->getDeclName())
875     return;
876 
877   // FIXME: This feels like a hack. Should DeclarationName support
878   // template-ids, or is there a better way to keep specializations
879   // from being visible?
880   if (isa<ClassTemplateSpecializationDecl>(D))
881     return;
882 
883   ASTContext *C = 0;
884   if (!LookupPtr) {
885     C = &getParentASTContext();
886     CreateStoredDeclsMap(*C);
887   }
888 
889   // Insert this declaration into the map.
890   StoredDeclsList &DeclNameEntries = (*LookupPtr)[D->getDeclName()];
891   if (DeclNameEntries.isNull()) {
892     DeclNameEntries.setOnlyValue(D);
893     return;
894   }
895 
896   // If it is possible that this is a redeclaration, check to see if there is
897   // already a decl for which declarationReplaces returns true.  If there is
898   // one, just replace it and return.
899   if (!C)
900     C = &getParentASTContext();
901 
902   if (DeclNameEntries.HandleRedeclaration(*C, D))
903     return;
904 
905   // Put this declaration into the appropriate slot.
906   DeclNameEntries.AddSubsequentDecl(D);
907 }
908 
909 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
910 /// this context.
911 DeclContext::udir_iterator_range
912 DeclContext::getUsingDirectives() const {
913   lookup_const_result Result = lookup(UsingDirectiveDecl::getName());
914   return udir_iterator_range(reinterpret_cast<udir_iterator>(Result.first),
915                              reinterpret_cast<udir_iterator>(Result.second));
916 }
917 
918 void StoredDeclsList::materializeDecls(ASTContext &Context) {
919   if (isNull())
920     return;
921 
922   switch ((DataKind)(Data & 0x03)) {
923   case DK_Decl:
924   case DK_Decl_Vector:
925     break;
926 
927   case DK_DeclID: {
928     // Resolve this declaration ID to an actual declaration by
929     // querying the external AST source.
930     unsigned DeclID = Data >> 2;
931 
932     ExternalASTSource *Source = Context.getExternalSource();
933     assert(Source && "No external AST source available!");
934 
935     Data = reinterpret_cast<uintptr_t>(Source->GetDecl(DeclID));
936     break;
937   }
938 
939   case DK_ID_Vector: {
940     // We have a vector of declaration IDs. Resolve all of them to
941     // actual declarations.
942     VectorTy &Vector = *getAsVector();
943     ExternalASTSource *Source = Context.getExternalSource();
944     assert(Source && "No external AST source available!");
945 
946     for (unsigned I = 0, N = Vector.size(); I != N; ++I)
947       Vector[I] = reinterpret_cast<uintptr_t>(Source->GetDecl(Vector[I]));
948 
949     Data = (Data & ~0x03) | DK_Decl_Vector;
950     break;
951   }
952   }
953 }
954 
955 //===----------------------------------------------------------------------===//
956 // Creation and Destruction of StoredDeclsMaps.                               //
957 //===----------------------------------------------------------------------===//
958 
959 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
960   assert(!LookupPtr && "context already has a decls map");
961   assert(getPrimaryContext() == this &&
962          "creating decls map on non-primary context");
963 
964   StoredDeclsMap *M;
965   bool Dependent = isDependentContext();
966   if (Dependent)
967     M = new DependentStoredDeclsMap();
968   else
969     M = new StoredDeclsMap();
970   M->Previous = C.LastSDM;
971   C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
972   LookupPtr = M;
973   return M;
974 }
975 
976 void ASTContext::ReleaseDeclContextMaps() {
977   // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
978   // pointer because the subclass doesn't add anything that needs to
979   // be deleted.
980 
981   StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
982 }
983 
984 void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
985   while (Map) {
986     // Advance the iteration before we invalidate memory.
987     llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
988 
989     if (Dependent)
990       delete static_cast<DependentStoredDeclsMap*>(Map);
991     else
992       delete Map;
993 
994     Map = Next.getPointer();
995     Dependent = Next.getInt();
996   }
997 }
998 
999 DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1000                                                  DeclContext *Parent,
1001                                            const PartialDiagnostic &PDiag) {
1002   assert(Parent->isDependentContext()
1003          && "cannot iterate dependent diagnostics of non-dependent context");
1004   Parent = Parent->getPrimaryContext();
1005   if (!Parent->LookupPtr)
1006     Parent->CreateStoredDeclsMap(C);
1007 
1008   DependentStoredDeclsMap *Map
1009     = static_cast<DependentStoredDeclsMap*>(Parent->LookupPtr);
1010 
1011   // Allocate the copy of the PartialDiagnostic via the ASTContext's
1012   // BumpPtrAllocator, rather than the ASTContext itself.
1013   PartialDiagnostic::Storage *DiagStorage = 0;
1014   if (PDiag.hasStorage())
1015     DiagStorage = new (C) PartialDiagnostic::Storage;
1016 
1017   DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
1018 
1019   // TODO: Maybe we shouldn't reverse the order during insertion.
1020   DD->NextDiagnostic = Map->FirstDiagnostic;
1021   Map->FirstDiagnostic = DD;
1022 
1023   return DD;
1024 }
1025