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