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