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