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