DeclBase.cpp revision 251662
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>
34using 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
44void Decl::updateOutOfDate(IdentifierInfo &II) const {
45  getASTContext().getExternalSource()->updateOutOfDateIdentifier(II);
46}
47
48void *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
67Module *Decl::getOwningModuleSlow() const {
68  assert(isFromASTFile() && "Not from AST file?");
69  return getASTContext().getExternalSource()->getModule(getOwningModuleID());
70}
71
72const 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
81void 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
91const 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
100bool Decl::StatisticsEnabled = false;
101void Decl::EnableStatistics() {
102  StatisticsEnabled = true;
103}
104
105void 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
129void 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
137bool 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
149bool Decl::isParameterPack() const {
150  if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this))
151    return Parm->isParameterPack();
152
153  return isTemplateParameterPack();
154}
155
156bool 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
163bool Decl::isTemplateDecl() const {
164  return isa<TemplateDecl>(this);
165}
166
167const 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
182void 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.
207Decl::~Decl() { }
208
209void Decl::setDeclContext(DeclContext *DC) {
210  DeclCtx = DC;
211}
212
213void 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
224void 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
236bool 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
247TranslationUnitDecl *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
262ASTContext &Decl::getASTContext() const {
263  return getTranslationUnitDecl()->getASTContext();
264}
265
266ASTMutationListener *Decl::getASTMutationListener() const {
267  return getASTContext().getASTMutationListener();
268}
269
270unsigned 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
283bool 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
294bool 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.
315static 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
390AvailabilityResult 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
433bool 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
463bool 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
482unsigned 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    case MSProperty:
497      return IDNS_Ordinary;
498    case Label:
499      return IDNS_Label;
500    case IndirectField:
501      return IDNS_Ordinary | IDNS_Member;
502
503    case ObjCCompatibleAlias:
504    case ObjCInterface:
505      return IDNS_Ordinary | IDNS_Type;
506
507    case Typedef:
508    case TypeAlias:
509    case TypeAliasTemplate:
510    case UnresolvedUsingTypename:
511    case TemplateTypeParm:
512      return IDNS_Ordinary | IDNS_Type;
513
514    case UsingShadow:
515      return 0; // we'll actually overwrite this later
516
517    case UnresolvedUsingValue:
518      return IDNS_Ordinary | IDNS_Using;
519
520    case Using:
521      return IDNS_Using;
522
523    case ObjCProtocol:
524      return IDNS_ObjCProtocol;
525
526    case Field:
527    case ObjCAtDefsField:
528    case ObjCIvar:
529      return IDNS_Member;
530
531    case Record:
532    case CXXRecord:
533    case Enum:
534      return IDNS_Tag | IDNS_Type;
535
536    case Namespace:
537    case NamespaceAlias:
538      return IDNS_Namespace;
539
540    case FunctionTemplate:
541      return IDNS_Ordinary;
542
543    case ClassTemplate:
544    case TemplateTemplateParm:
545      return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
546
547    // Never have names.
548    case Friend:
549    case FriendTemplate:
550    case AccessSpec:
551    case LinkageSpec:
552    case FileScopeAsm:
553    case StaticAssert:
554    case ObjCPropertyImpl:
555    case Block:
556    case Captured:
557    case TranslationUnit:
558
559    case UsingDirective:
560    case ClassTemplateSpecialization:
561    case ClassTemplatePartialSpecialization:
562    case ClassScopeFunctionSpecialization:
563    case ObjCImplementation:
564    case ObjCCategory:
565    case ObjCCategoryImpl:
566    case Import:
567    case OMPThreadPrivate:
568    case Empty:
569      // Never looked up by name.
570      return 0;
571  }
572
573  llvm_unreachable("Invalid DeclKind!");
574}
575
576void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
577  assert(!HasAttrs && "Decl already contains attrs.");
578
579  AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
580  assert(AttrBlank.empty() && "HasAttrs was wrong?");
581
582  AttrBlank = attrs;
583  HasAttrs = true;
584}
585
586void Decl::dropAttrs() {
587  if (!HasAttrs) return;
588
589  HasAttrs = false;
590  getASTContext().eraseDeclAttrs(this);
591}
592
593const AttrVec &Decl::getAttrs() const {
594  assert(HasAttrs && "No attrs to get!");
595  return getASTContext().getDeclAttrs(this);
596}
597
598void Decl::swapAttrs(Decl *RHS) {
599  bool HasLHSAttr = this->HasAttrs;
600  bool HasRHSAttr = RHS->HasAttrs;
601
602  // Usually, neither decl has attrs, nothing to do.
603  if (!HasLHSAttr && !HasRHSAttr) return;
604
605  // If 'this' has no attrs, swap the other way.
606  if (!HasLHSAttr)
607    return RHS->swapAttrs(this);
608
609  ASTContext &Context = getASTContext();
610
611  // Handle the case when both decls have attrs.
612  if (HasRHSAttr) {
613    std::swap(Context.getDeclAttrs(this), Context.getDeclAttrs(RHS));
614    return;
615  }
616
617  // Otherwise, LHS has an attr and RHS doesn't.
618  Context.getDeclAttrs(RHS) = Context.getDeclAttrs(this);
619  Context.eraseDeclAttrs(this);
620  this->HasAttrs = false;
621  RHS->HasAttrs = true;
622}
623
624Decl *Decl::castFromDeclContext (const DeclContext *D) {
625  Decl::Kind DK = D->getDeclKind();
626  switch(DK) {
627#define DECL(NAME, BASE)
628#define DECL_CONTEXT(NAME) \
629    case Decl::NAME:       \
630      return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
631#define DECL_CONTEXT_BASE(NAME)
632#include "clang/AST/DeclNodes.inc"
633    default:
634#define DECL(NAME, BASE)
635#define DECL_CONTEXT_BASE(NAME)                  \
636      if (DK >= first##NAME && DK <= last##NAME) \
637        return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
638#include "clang/AST/DeclNodes.inc"
639      llvm_unreachable("a decl that inherits DeclContext isn't handled");
640  }
641}
642
643DeclContext *Decl::castToDeclContext(const Decl *D) {
644  Decl::Kind DK = D->getKind();
645  switch(DK) {
646#define DECL(NAME, BASE)
647#define DECL_CONTEXT(NAME) \
648    case Decl::NAME:       \
649      return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
650#define DECL_CONTEXT_BASE(NAME)
651#include "clang/AST/DeclNodes.inc"
652    default:
653#define DECL(NAME, BASE)
654#define DECL_CONTEXT_BASE(NAME)                                   \
655      if (DK >= first##NAME && DK <= last##NAME)                  \
656        return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
657#include "clang/AST/DeclNodes.inc"
658      llvm_unreachable("a decl that inherits DeclContext isn't handled");
659  }
660}
661
662SourceLocation Decl::getBodyRBrace() const {
663  // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
664  // FunctionDecl stores EndRangeLoc for this purpose.
665  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
666    const FunctionDecl *Definition;
667    if (FD->hasBody(Definition))
668      return Definition->getSourceRange().getEnd();
669    return SourceLocation();
670  }
671
672  if (Stmt *Body = getBody())
673    return Body->getSourceRange().getEnd();
674
675  return SourceLocation();
676}
677
678void Decl::CheckAccessDeclContext() const {
679#ifndef NDEBUG
680  // Suppress this check if any of the following hold:
681  // 1. this is the translation unit (and thus has no parent)
682  // 2. this is a template parameter (and thus doesn't belong to its context)
683  // 3. this is a non-type template parameter
684  // 4. the context is not a record
685  // 5. it's invalid
686  // 6. it's a C++0x static_assert.
687  if (isa<TranslationUnitDecl>(this) ||
688      isa<TemplateTypeParmDecl>(this) ||
689      isa<NonTypeTemplateParmDecl>(this) ||
690      !isa<CXXRecordDecl>(getDeclContext()) ||
691      isInvalidDecl() ||
692      isa<StaticAssertDecl>(this) ||
693      // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
694      // as DeclContext (?).
695      isa<ParmVarDecl>(this) ||
696      // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
697      // AS_none as access specifier.
698      isa<CXXRecordDecl>(this) ||
699      isa<ClassScopeFunctionSpecializationDecl>(this))
700    return;
701
702  assert(Access != AS_none &&
703         "Access specifier is AS_none inside a record decl");
704#endif
705}
706
707static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
708static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
709
710/// Starting at a given context (a Decl or DeclContext), look for a
711/// code context that is not a closure (a lambda, block, etc.).
712template <class T> static Decl *getNonClosureContext(T *D) {
713  if (getKind(D) == Decl::CXXMethod) {
714    CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
715    if (MD->getOverloadedOperator() == OO_Call &&
716        MD->getParent()->isLambda())
717      return getNonClosureContext(MD->getParent()->getParent());
718    return MD;
719  } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
720    return FD;
721  } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
722    return MD;
723  } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
724    return getNonClosureContext(BD->getParent());
725  } else if (CapturedDecl *CD = dyn_cast<CapturedDecl>(D)) {
726    return getNonClosureContext(CD->getParent());
727  } else {
728    return 0;
729  }
730}
731
732Decl *Decl::getNonClosureContext() {
733  return ::getNonClosureContext(this);
734}
735
736Decl *DeclContext::getNonClosureAncestor() {
737  return ::getNonClosureContext(this);
738}
739
740//===----------------------------------------------------------------------===//
741// DeclContext Implementation
742//===----------------------------------------------------------------------===//
743
744bool DeclContext::classof(const Decl *D) {
745  switch (D->getKind()) {
746#define DECL(NAME, BASE)
747#define DECL_CONTEXT(NAME) case Decl::NAME:
748#define DECL_CONTEXT_BASE(NAME)
749#include "clang/AST/DeclNodes.inc"
750      return true;
751    default:
752#define DECL(NAME, BASE)
753#define DECL_CONTEXT_BASE(NAME)                 \
754      if (D->getKind() >= Decl::first##NAME &&  \
755          D->getKind() <= Decl::last##NAME)     \
756        return true;
757#include "clang/AST/DeclNodes.inc"
758      return false;
759  }
760}
761
762DeclContext::~DeclContext() { }
763
764/// \brief Find the parent context of this context that will be
765/// used for unqualified name lookup.
766///
767/// Generally, the parent lookup context is the semantic context. However, for
768/// a friend function the parent lookup context is the lexical context, which
769/// is the class in which the friend is declared.
770DeclContext *DeclContext::getLookupParent() {
771  // FIXME: Find a better way to identify friends
772  if (isa<FunctionDecl>(this))
773    if (getParent()->getRedeclContext()->isFileContext() &&
774        getLexicalParent()->getRedeclContext()->isRecord())
775      return getLexicalParent();
776
777  return getParent();
778}
779
780bool DeclContext::isInlineNamespace() const {
781  return isNamespace() &&
782         cast<NamespaceDecl>(this)->isInline();
783}
784
785bool DeclContext::isDependentContext() const {
786  if (isFileContext())
787    return false;
788
789  if (isa<ClassTemplatePartialSpecializationDecl>(this))
790    return true;
791
792  if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
793    if (Record->getDescribedClassTemplate())
794      return true;
795
796    if (Record->isDependentLambda())
797      return true;
798  }
799
800  if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
801    if (Function->getDescribedFunctionTemplate())
802      return true;
803
804    // Friend function declarations are dependent if their *lexical*
805    // context is dependent.
806    if (cast<Decl>(this)->getFriendObjectKind())
807      return getLexicalParent()->isDependentContext();
808  }
809
810  return getParent() && getParent()->isDependentContext();
811}
812
813bool DeclContext::isTransparentContext() const {
814  if (DeclKind == Decl::Enum)
815    return !cast<EnumDecl>(this)->isScoped();
816  else if (DeclKind == Decl::LinkageSpec)
817    return true;
818
819  return false;
820}
821
822bool DeclContext::Encloses(const DeclContext *DC) const {
823  if (getPrimaryContext() != this)
824    return getPrimaryContext()->Encloses(DC);
825
826  for (; DC; DC = DC->getParent())
827    if (DC->getPrimaryContext() == this)
828      return true;
829  return false;
830}
831
832DeclContext *DeclContext::getPrimaryContext() {
833  switch (DeclKind) {
834  case Decl::TranslationUnit:
835  case Decl::LinkageSpec:
836  case Decl::Block:
837  case Decl::Captured:
838    // There is only one DeclContext for these entities.
839    return this;
840
841  case Decl::Namespace:
842    // The original namespace is our primary context.
843    return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
844
845  case Decl::ObjCMethod:
846    return this;
847
848  case Decl::ObjCInterface:
849    if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
850      return Def;
851
852    return this;
853
854  case Decl::ObjCProtocol:
855    if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
856      return Def;
857
858    return this;
859
860  case Decl::ObjCCategory:
861    return this;
862
863  case Decl::ObjCImplementation:
864  case Decl::ObjCCategoryImpl:
865    return this;
866
867  default:
868    if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
869      // If this is a tag type that has a definition or is currently
870      // being defined, that definition is our primary context.
871      TagDecl *Tag = cast<TagDecl>(this);
872      assert(isa<TagType>(Tag->TypeForDecl) ||
873             isa<InjectedClassNameType>(Tag->TypeForDecl));
874
875      if (TagDecl *Def = Tag->getDefinition())
876        return Def;
877
878      if (!isa<InjectedClassNameType>(Tag->TypeForDecl)) {
879        const TagType *TagTy = cast<TagType>(Tag->TypeForDecl);
880        if (TagTy->isBeingDefined())
881          // FIXME: is it necessarily being defined in the decl
882          // that owns the type?
883          return TagTy->getDecl();
884      }
885
886      return Tag;
887    }
888
889    assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
890          "Unknown DeclContext kind");
891    return this;
892  }
893}
894
895void
896DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
897  Contexts.clear();
898
899  if (DeclKind != Decl::Namespace) {
900    Contexts.push_back(this);
901    return;
902  }
903
904  NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
905  for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
906       N = N->getPreviousDecl())
907    Contexts.push_back(N);
908
909  std::reverse(Contexts.begin(), Contexts.end());
910}
911
912std::pair<Decl *, Decl *>
913DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
914                            bool FieldsAlreadyLoaded) {
915  // Build up a chain of declarations via the Decl::NextInContextAndBits field.
916  Decl *FirstNewDecl = 0;
917  Decl *PrevDecl = 0;
918  for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
919    if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
920      continue;
921
922    Decl *D = Decls[I];
923    if (PrevDecl)
924      PrevDecl->NextInContextAndBits.setPointer(D);
925    else
926      FirstNewDecl = D;
927
928    PrevDecl = D;
929  }
930
931  return std::make_pair(FirstNewDecl, PrevDecl);
932}
933
934/// \brief We have just acquired external visible storage, and we already have
935/// built a lookup map. For every name in the map, pull in the new names from
936/// the external storage.
937void DeclContext::reconcileExternalVisibleStorage() {
938  assert(NeedToReconcileExternalVisibleStorage && LookupPtr.getPointer());
939  NeedToReconcileExternalVisibleStorage = false;
940
941  StoredDeclsMap &Map = *LookupPtr.getPointer();
942  ExternalASTSource *Source = getParentASTContext().getExternalSource();
943  for (StoredDeclsMap::iterator I = Map.begin(); I != Map.end(); ++I) {
944    I->second.removeExternalDecls();
945    Source->FindExternalVisibleDeclsByName(this, I->first);
946  }
947}
948
949/// \brief Load the declarations within this lexical storage from an
950/// external source.
951void
952DeclContext::LoadLexicalDeclsFromExternalStorage() const {
953  ExternalASTSource *Source = getParentASTContext().getExternalSource();
954  assert(hasExternalLexicalStorage() && Source && "No external storage?");
955
956  // Notify that we have a DeclContext that is initializing.
957  ExternalASTSource::Deserializing ADeclContext(Source);
958
959  // Load the external declarations, if any.
960  SmallVector<Decl*, 64> Decls;
961  ExternalLexicalStorage = false;
962  switch (Source->FindExternalLexicalDecls(this, Decls)) {
963  case ELR_Success:
964    break;
965
966  case ELR_Failure:
967  case ELR_AlreadyLoaded:
968    return;
969  }
970
971  if (Decls.empty())
972    return;
973
974  // We may have already loaded just the fields of this record, in which case
975  // we need to ignore them.
976  bool FieldsAlreadyLoaded = false;
977  if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
978    FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
979
980  // Splice the newly-read declarations into the beginning of the list
981  // of declarations.
982  Decl *ExternalFirst, *ExternalLast;
983  llvm::tie(ExternalFirst, ExternalLast) = BuildDeclChain(Decls,
984                                                          FieldsAlreadyLoaded);
985  ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
986  FirstDecl = ExternalFirst;
987  if (!LastDecl)
988    LastDecl = ExternalLast;
989}
990
991DeclContext::lookup_result
992ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
993                                                    DeclarationName Name) {
994  ASTContext &Context = DC->getParentASTContext();
995  StoredDeclsMap *Map;
996  if (!(Map = DC->LookupPtr.getPointer()))
997    Map = DC->CreateStoredDeclsMap(Context);
998
999  // Add an entry to the map for this name, if it's not already present.
1000  (*Map)[Name];
1001
1002  return DeclContext::lookup_result();
1003}
1004
1005DeclContext::lookup_result
1006ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
1007                                                  DeclarationName Name,
1008                                                  ArrayRef<NamedDecl*> Decls) {
1009  ASTContext &Context = DC->getParentASTContext();
1010  StoredDeclsMap *Map;
1011  if (!(Map = DC->LookupPtr.getPointer()))
1012    Map = DC->CreateStoredDeclsMap(Context);
1013
1014  StoredDeclsList &List = (*Map)[Name];
1015  for (ArrayRef<NamedDecl*>::iterator
1016         I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1017    if (List.isNull())
1018      List.setOnlyValue(*I);
1019    else
1020      // FIXME: Need declarationReplaces handling for redeclarations in modules.
1021      List.AddSubsequentDecl(*I);
1022  }
1023
1024  return List.getLookupResult();
1025}
1026
1027DeclContext::decl_iterator DeclContext::noload_decls_begin() const {
1028  return decl_iterator(FirstDecl);
1029}
1030
1031DeclContext::decl_iterator DeclContext::decls_begin() const {
1032  if (hasExternalLexicalStorage())
1033    LoadLexicalDeclsFromExternalStorage();
1034
1035  return decl_iterator(FirstDecl);
1036}
1037
1038bool DeclContext::decls_empty() const {
1039  if (hasExternalLexicalStorage())
1040    LoadLexicalDeclsFromExternalStorage();
1041
1042  return !FirstDecl;
1043}
1044
1045bool DeclContext::containsDecl(Decl *D) const {
1046  return (D->getLexicalDeclContext() == this &&
1047          (D->NextInContextAndBits.getPointer() || D == LastDecl));
1048}
1049
1050void DeclContext::removeDecl(Decl *D) {
1051  assert(D->getLexicalDeclContext() == this &&
1052         "decl being removed from non-lexical context");
1053  assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
1054         "decl is not in decls list");
1055
1056  // Remove D from the decl chain.  This is O(n) but hopefully rare.
1057  if (D == FirstDecl) {
1058    if (D == LastDecl)
1059      FirstDecl = LastDecl = 0;
1060    else
1061      FirstDecl = D->NextInContextAndBits.getPointer();
1062  } else {
1063    for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
1064      assert(I && "decl not found in linked list");
1065      if (I->NextInContextAndBits.getPointer() == D) {
1066        I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
1067        if (D == LastDecl) LastDecl = I;
1068        break;
1069      }
1070    }
1071  }
1072
1073  // Mark that D is no longer in the decl chain.
1074  D->NextInContextAndBits.setPointer(0);
1075
1076  // Remove D from the lookup table if necessary.
1077  if (isa<NamedDecl>(D)) {
1078    NamedDecl *ND = cast<NamedDecl>(D);
1079
1080    // Remove only decls that have a name
1081    if (!ND->getDeclName()) return;
1082
1083    StoredDeclsMap *Map = getPrimaryContext()->LookupPtr.getPointer();
1084    if (!Map) return;
1085
1086    StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1087    assert(Pos != Map->end() && "no lookup entry for decl");
1088    if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
1089      Pos->second.remove(ND);
1090  }
1091}
1092
1093void DeclContext::addHiddenDecl(Decl *D) {
1094  assert(D->getLexicalDeclContext() == this &&
1095         "Decl inserted into wrong lexical context");
1096  assert(!D->getNextDeclInContext() && D != LastDecl &&
1097         "Decl already inserted into a DeclContext");
1098
1099  if (FirstDecl) {
1100    LastDecl->NextInContextAndBits.setPointer(D);
1101    LastDecl = D;
1102  } else {
1103    FirstDecl = LastDecl = D;
1104  }
1105
1106  // Notify a C++ record declaration that we've added a member, so it can
1107  // update it's class-specific state.
1108  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1109    Record->addedMember(D);
1110
1111  // If this is a newly-created (not de-serialized) import declaration, wire
1112  // it in to the list of local import declarations.
1113  if (!D->isFromASTFile()) {
1114    if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
1115      D->getASTContext().addedLocalImportDecl(Import);
1116  }
1117}
1118
1119void DeclContext::addDecl(Decl *D) {
1120  addHiddenDecl(D);
1121
1122  if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1123    ND->getDeclContext()->getPrimaryContext()->
1124        makeDeclVisibleInContextWithFlags(ND, false, true);
1125}
1126
1127void DeclContext::addDeclInternal(Decl *D) {
1128  addHiddenDecl(D);
1129
1130  if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1131    ND->getDeclContext()->getPrimaryContext()->
1132        makeDeclVisibleInContextWithFlags(ND, true, true);
1133}
1134
1135/// shouldBeHidden - Determine whether a declaration which was declared
1136/// within its semantic context should be invisible to qualified name lookup.
1137static bool shouldBeHidden(NamedDecl *D) {
1138  // Skip unnamed declarations.
1139  if (!D->getDeclName())
1140    return true;
1141
1142  // Skip entities that can't be found by name lookup into a particular
1143  // context.
1144  if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1145      D->isTemplateParameter())
1146    return true;
1147
1148  // Skip template specializations.
1149  // FIXME: This feels like a hack. Should DeclarationName support
1150  // template-ids, or is there a better way to keep specializations
1151  // from being visible?
1152  if (isa<ClassTemplateSpecializationDecl>(D))
1153    return true;
1154  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1155    if (FD->isFunctionTemplateSpecialization())
1156      return true;
1157
1158  return false;
1159}
1160
1161/// buildLookup - Build the lookup data structure with all of the
1162/// declarations in this DeclContext (and any other contexts linked
1163/// to it or transparent contexts nested within it) and return it.
1164StoredDeclsMap *DeclContext::buildLookup() {
1165  assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1166
1167  // FIXME: Should we keep going if hasExternalVisibleStorage?
1168  if (!LookupPtr.getInt())
1169    return LookupPtr.getPointer();
1170
1171  SmallVector<DeclContext *, 2> Contexts;
1172  collectAllContexts(Contexts);
1173  for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
1174    buildLookupImpl(Contexts[I]);
1175
1176  // We no longer have any lazy decls.
1177  LookupPtr.setInt(false);
1178  NeedToReconcileExternalVisibleStorage = false;
1179  return LookupPtr.getPointer();
1180}
1181
1182/// buildLookupImpl - Build part of the lookup data structure for the
1183/// declarations contained within DCtx, which will either be this
1184/// DeclContext, a DeclContext linked to it, or a transparent context
1185/// nested within it.
1186void DeclContext::buildLookupImpl(DeclContext *DCtx) {
1187  for (decl_iterator I = DCtx->decls_begin(), E = DCtx->decls_end();
1188       I != E; ++I) {
1189    Decl *D = *I;
1190
1191    // Insert this declaration into the lookup structure, but only if
1192    // it's semantically within its decl context. Any other decls which
1193    // should be found in this context are added eagerly.
1194    if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1195      if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND))
1196        makeDeclVisibleInContextImpl(ND, false);
1197
1198    // If this declaration is itself a transparent declaration context
1199    // or inline namespace, add the members of this declaration of that
1200    // context (recursively).
1201    if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
1202      if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1203        buildLookupImpl(InnerCtx);
1204  }
1205}
1206
1207DeclContext::lookup_result
1208DeclContext::lookup(DeclarationName Name) {
1209  assert(DeclKind != Decl::LinkageSpec &&
1210         "Should not perform lookups into linkage specs!");
1211
1212  DeclContext *PrimaryContext = getPrimaryContext();
1213  if (PrimaryContext != this)
1214    return PrimaryContext->lookup(Name);
1215
1216  if (hasExternalVisibleStorage()) {
1217    StoredDeclsMap *Map = LookupPtr.getPointer();
1218    if (LookupPtr.getInt())
1219      Map = buildLookup();
1220    else if (NeedToReconcileExternalVisibleStorage)
1221      reconcileExternalVisibleStorage();
1222
1223    if (!Map)
1224      Map = CreateStoredDeclsMap(getParentASTContext());
1225
1226    // If a PCH/module has a result for this name, and we have a local
1227    // declaration, we will have imported the PCH/module result when adding the
1228    // local declaration or when reconciling the module.
1229    std::pair<StoredDeclsMap::iterator, bool> R =
1230        Map->insert(std::make_pair(Name, StoredDeclsList()));
1231    if (!R.second)
1232      return R.first->second.getLookupResult();
1233
1234    ExternalASTSource *Source = getParentASTContext().getExternalSource();
1235    if (Source->FindExternalVisibleDeclsByName(this, Name)) {
1236      if (StoredDeclsMap *Map = LookupPtr.getPointer()) {
1237        StoredDeclsMap::iterator I = Map->find(Name);
1238        if (I != Map->end())
1239          return I->second.getLookupResult();
1240      }
1241    }
1242
1243    return lookup_result(lookup_iterator(0), lookup_iterator(0));
1244  }
1245
1246  StoredDeclsMap *Map = LookupPtr.getPointer();
1247  if (LookupPtr.getInt())
1248    Map = buildLookup();
1249
1250  if (!Map)
1251    return lookup_result(lookup_iterator(0), lookup_iterator(0));
1252
1253  StoredDeclsMap::iterator I = Map->find(Name);
1254  if (I == Map->end())
1255    return lookup_result(lookup_iterator(0), lookup_iterator(0));
1256
1257  return I->second.getLookupResult();
1258}
1259
1260void DeclContext::localUncachedLookup(DeclarationName Name,
1261                                      SmallVectorImpl<NamedDecl *> &Results) {
1262  Results.clear();
1263
1264  // If there's no external storage, just perform a normal lookup and copy
1265  // the results.
1266  if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
1267    lookup_result LookupResults = lookup(Name);
1268    Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
1269    return;
1270  }
1271
1272  // If we have a lookup table, check there first. Maybe we'll get lucky.
1273  if (Name && !LookupPtr.getInt()) {
1274    if (StoredDeclsMap *Map = LookupPtr.getPointer()) {
1275      StoredDeclsMap::iterator Pos = Map->find(Name);
1276      if (Pos != Map->end()) {
1277        Results.insert(Results.end(),
1278                       Pos->second.getLookupResult().begin(),
1279                       Pos->second.getLookupResult().end());
1280        return;
1281      }
1282    }
1283  }
1284
1285  // Slow case: grovel through the declarations in our chain looking for
1286  // matches.
1287  for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1288    if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1289      if (ND->getDeclName() == Name)
1290        Results.push_back(ND);
1291  }
1292}
1293
1294DeclContext *DeclContext::getRedeclContext() {
1295  DeclContext *Ctx = this;
1296  // Skip through transparent contexts.
1297  while (Ctx->isTransparentContext())
1298    Ctx = Ctx->getParent();
1299  return Ctx;
1300}
1301
1302DeclContext *DeclContext::getEnclosingNamespaceContext() {
1303  DeclContext *Ctx = this;
1304  // Skip through non-namespace, non-translation-unit contexts.
1305  while (!Ctx->isFileContext())
1306    Ctx = Ctx->getParent();
1307  return Ctx->getPrimaryContext();
1308}
1309
1310bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1311  // For non-file contexts, this is equivalent to Equals.
1312  if (!isFileContext())
1313    return O->Equals(this);
1314
1315  do {
1316    if (O->Equals(this))
1317      return true;
1318
1319    const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1320    if (!NS || !NS->isInline())
1321      break;
1322    O = NS->getParent();
1323  } while (O);
1324
1325  return false;
1326}
1327
1328void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1329  DeclContext *PrimaryDC = this->getPrimaryContext();
1330  DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1331  // If the decl is being added outside of its semantic decl context, we
1332  // need to ensure that we eagerly build the lookup information for it.
1333  PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
1334}
1335
1336void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1337                                                    bool Recoverable) {
1338  assert(this == getPrimaryContext() && "expected a primary DC");
1339
1340  // Skip declarations within functions.
1341  // FIXME: We shouldn't need to build lookup tables for function declarations
1342  // ever, and we can't do so correctly because we can't model the nesting of
1343  // scopes which occurs within functions. We use "qualified" lookup into
1344  // function declarations when handling friend declarations inside nested
1345  // classes, and consequently accept the following invalid code:
1346  //
1347  //   void f() { void g(); { int g; struct S { friend void g(); }; } }
1348  if (isFunctionOrMethod() && !isa<FunctionDecl>(D))
1349    return;
1350
1351  // Skip declarations which should be invisible to name lookup.
1352  if (shouldBeHidden(D))
1353    return;
1354
1355  // If we already have a lookup data structure, perform the insertion into
1356  // it. If we might have externally-stored decls with this name, look them
1357  // up and perform the insertion. If this decl was declared outside its
1358  // semantic context, buildLookup won't add it, so add it now.
1359  //
1360  // FIXME: As a performance hack, don't add such decls into the translation
1361  // unit unless we're in C++, since qualified lookup into the TU is never
1362  // performed.
1363  if (LookupPtr.getPointer() || hasExternalVisibleStorage() ||
1364      ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1365       (getParentASTContext().getLangOpts().CPlusPlus ||
1366        !isTranslationUnit()))) {
1367    // If we have lazily omitted any decls, they might have the same name as
1368    // the decl which we are adding, so build a full lookup table before adding
1369    // this decl.
1370    buildLookup();
1371    makeDeclVisibleInContextImpl(D, Internal);
1372  } else {
1373    LookupPtr.setInt(true);
1374  }
1375
1376  // If we are a transparent context or inline namespace, insert into our
1377  // parent context, too. This operation is recursive.
1378  if (isTransparentContext() || isInlineNamespace())
1379    getParent()->getPrimaryContext()->
1380        makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1381
1382  Decl *DCAsDecl = cast<Decl>(this);
1383  // Notify that a decl was made visible unless we are a Tag being defined.
1384  if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1385    if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1386      L->AddedVisibleDecl(this, D);
1387}
1388
1389void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1390  // Find or create the stored declaration map.
1391  StoredDeclsMap *Map = LookupPtr.getPointer();
1392  if (!Map) {
1393    ASTContext *C = &getParentASTContext();
1394    Map = CreateStoredDeclsMap(*C);
1395  }
1396
1397  // If there is an external AST source, load any declarations it knows about
1398  // with this declaration's name.
1399  // If the lookup table contains an entry about this name it means that we
1400  // have already checked the external source.
1401  if (!Internal)
1402    if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1403      if (hasExternalVisibleStorage() &&
1404          Map->find(D->getDeclName()) == Map->end())
1405        Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1406
1407  // Insert this declaration into the map.
1408  StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
1409  if (DeclNameEntries.isNull()) {
1410    DeclNameEntries.setOnlyValue(D);
1411    return;
1412  }
1413
1414  if (DeclNameEntries.HandleRedeclaration(D)) {
1415    // This declaration has replaced an existing one for which
1416    // declarationReplaces returns true.
1417    return;
1418  }
1419
1420  // Put this declaration into the appropriate slot.
1421  DeclNameEntries.AddSubsequentDecl(D);
1422}
1423
1424/// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1425/// this context.
1426DeclContext::udir_iterator_range
1427DeclContext::getUsingDirectives() const {
1428  // FIXME: Use something more efficient than normal lookup for using
1429  // directives. In C++, using directives are looked up more than anything else.
1430  lookup_const_result Result = lookup(UsingDirectiveDecl::getName());
1431  return udir_iterator_range(reinterpret_cast<udir_iterator>(Result.begin()),
1432                             reinterpret_cast<udir_iterator>(Result.end()));
1433}
1434
1435//===----------------------------------------------------------------------===//
1436// Creation and Destruction of StoredDeclsMaps.                               //
1437//===----------------------------------------------------------------------===//
1438
1439StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1440  assert(!LookupPtr.getPointer() && "context already has a decls map");
1441  assert(getPrimaryContext() == this &&
1442         "creating decls map on non-primary context");
1443
1444  StoredDeclsMap *M;
1445  bool Dependent = isDependentContext();
1446  if (Dependent)
1447    M = new DependentStoredDeclsMap();
1448  else
1449    M = new StoredDeclsMap();
1450  M->Previous = C.LastSDM;
1451  C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1452  LookupPtr.setPointer(M);
1453  return M;
1454}
1455
1456void ASTContext::ReleaseDeclContextMaps() {
1457  // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1458  // pointer because the subclass doesn't add anything that needs to
1459  // be deleted.
1460  StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1461}
1462
1463void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1464  while (Map) {
1465    // Advance the iteration before we invalidate memory.
1466    llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1467
1468    if (Dependent)
1469      delete static_cast<DependentStoredDeclsMap*>(Map);
1470    else
1471      delete Map;
1472
1473    Map = Next.getPointer();
1474    Dependent = Next.getInt();
1475  }
1476}
1477
1478DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1479                                                 DeclContext *Parent,
1480                                           const PartialDiagnostic &PDiag) {
1481  assert(Parent->isDependentContext()
1482         && "cannot iterate dependent diagnostics of non-dependent context");
1483  Parent = Parent->getPrimaryContext();
1484  if (!Parent->LookupPtr.getPointer())
1485    Parent->CreateStoredDeclsMap(C);
1486
1487  DependentStoredDeclsMap *Map
1488    = static_cast<DependentStoredDeclsMap*>(Parent->LookupPtr.getPointer());
1489
1490  // Allocate the copy of the PartialDiagnostic via the ASTContext's
1491  // BumpPtrAllocator, rather than the ASTContext itself.
1492  PartialDiagnostic::Storage *DiagStorage = 0;
1493  if (PDiag.hasStorage())
1494    DiagStorage = new (C) PartialDiagnostic::Storage;
1495
1496  DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
1497
1498  // TODO: Maybe we shouldn't reverse the order during insertion.
1499  DD->NextDiagnostic = Map->FirstDiagnostic;
1500  Map->FirstDiagnostic = DD;
1501
1502  return DD;
1503}
1504