DeclBase.cpp revision f5ebf9bf1df10ac15ba32a4b24dfe171b7848c58
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->getParent()->isLambda() &&
716        MD->getOverloadedOperator() == OO_Call)
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::isExternCContext() const {
823  const DeclContext *DC = this;
824  while (DC->DeclKind != Decl::TranslationUnit) {
825    if (DC->DeclKind == Decl::LinkageSpec)
826      return cast<LinkageSpecDecl>(DC)->getLanguage()
827        == LinkageSpecDecl::lang_c;
828    DC = DC->getParent();
829  }
830  return false;
831}
832
833bool DeclContext::isExternCXXContext() const {
834  const DeclContext *DC = this;
835  while (DC->DeclKind != Decl::TranslationUnit) {
836    if (DC->DeclKind == Decl::LinkageSpec)
837      return cast<LinkageSpecDecl>(DC)->getLanguage()
838        == LinkageSpecDecl::lang_cxx;
839    DC = DC->getParent();
840  }
841  return false;
842}
843
844bool DeclContext::Encloses(const DeclContext *DC) const {
845  if (getPrimaryContext() != this)
846    return getPrimaryContext()->Encloses(DC);
847
848  for (; DC; DC = DC->getParent())
849    if (DC->getPrimaryContext() == this)
850      return true;
851  return false;
852}
853
854DeclContext *DeclContext::getPrimaryContext() {
855  switch (DeclKind) {
856  case Decl::TranslationUnit:
857  case Decl::LinkageSpec:
858  case Decl::Block:
859  case Decl::Captured:
860    // There is only one DeclContext for these entities.
861    return this;
862
863  case Decl::Namespace:
864    // The original namespace is our primary context.
865    return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
866
867  case Decl::ObjCMethod:
868    return this;
869
870  case Decl::ObjCInterface:
871    if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
872      return Def;
873
874    return this;
875
876  case Decl::ObjCProtocol:
877    if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
878      return Def;
879
880    return this;
881
882  case Decl::ObjCCategory:
883    return this;
884
885  case Decl::ObjCImplementation:
886  case Decl::ObjCCategoryImpl:
887    return this;
888
889  default:
890    if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
891      // If this is a tag type that has a definition or is currently
892      // being defined, that definition is our primary context.
893      TagDecl *Tag = cast<TagDecl>(this);
894      assert(isa<TagType>(Tag->TypeForDecl) ||
895             isa<InjectedClassNameType>(Tag->TypeForDecl));
896
897      if (TagDecl *Def = Tag->getDefinition())
898        return Def;
899
900      if (!isa<InjectedClassNameType>(Tag->TypeForDecl)) {
901        const TagType *TagTy = cast<TagType>(Tag->TypeForDecl);
902        if (TagTy->isBeingDefined())
903          // FIXME: is it necessarily being defined in the decl
904          // that owns the type?
905          return TagTy->getDecl();
906      }
907
908      return Tag;
909    }
910
911    assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
912          "Unknown DeclContext kind");
913    return this;
914  }
915}
916
917void
918DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
919  Contexts.clear();
920
921  if (DeclKind != Decl::Namespace) {
922    Contexts.push_back(this);
923    return;
924  }
925
926  NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
927  for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
928       N = N->getPreviousDecl())
929    Contexts.push_back(N);
930
931  std::reverse(Contexts.begin(), Contexts.end());
932}
933
934std::pair<Decl *, Decl *>
935DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
936                            bool FieldsAlreadyLoaded) {
937  // Build up a chain of declarations via the Decl::NextInContextAndBits field.
938  Decl *FirstNewDecl = 0;
939  Decl *PrevDecl = 0;
940  for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
941    if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
942      continue;
943
944    Decl *D = Decls[I];
945    if (PrevDecl)
946      PrevDecl->NextInContextAndBits.setPointer(D);
947    else
948      FirstNewDecl = D;
949
950    PrevDecl = D;
951  }
952
953  return std::make_pair(FirstNewDecl, PrevDecl);
954}
955
956/// \brief We have just acquired external visible storage, and we already have
957/// built a lookup map. For every name in the map, pull in the new names from
958/// the external storage.
959void DeclContext::reconcileExternalVisibleStorage() {
960  assert(NeedToReconcileExternalVisibleStorage && LookupPtr.getPointer());
961  NeedToReconcileExternalVisibleStorage = false;
962
963  StoredDeclsMap &Map = *LookupPtr.getPointer();
964  ExternalASTSource *Source = getParentASTContext().getExternalSource();
965  for (StoredDeclsMap::iterator I = Map.begin(); I != Map.end(); ++I) {
966    I->second.removeExternalDecls();
967    Source->FindExternalVisibleDeclsByName(this, I->first);
968  }
969}
970
971/// \brief Load the declarations within this lexical storage from an
972/// external source.
973void
974DeclContext::LoadLexicalDeclsFromExternalStorage() const {
975  ExternalASTSource *Source = getParentASTContext().getExternalSource();
976  assert(hasExternalLexicalStorage() && Source && "No external storage?");
977
978  // Notify that we have a DeclContext that is initializing.
979  ExternalASTSource::Deserializing ADeclContext(Source);
980
981  // Load the external declarations, if any.
982  SmallVector<Decl*, 64> Decls;
983  ExternalLexicalStorage = false;
984  switch (Source->FindExternalLexicalDecls(this, Decls)) {
985  case ELR_Success:
986    break;
987
988  case ELR_Failure:
989  case ELR_AlreadyLoaded:
990    return;
991  }
992
993  if (Decls.empty())
994    return;
995
996  // We may have already loaded just the fields of this record, in which case
997  // we need to ignore them.
998  bool FieldsAlreadyLoaded = false;
999  if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
1000    FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
1001
1002  // Splice the newly-read declarations into the beginning of the list
1003  // of declarations.
1004  Decl *ExternalFirst, *ExternalLast;
1005  llvm::tie(ExternalFirst, ExternalLast) = BuildDeclChain(Decls,
1006                                                          FieldsAlreadyLoaded);
1007  ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
1008  FirstDecl = ExternalFirst;
1009  if (!LastDecl)
1010    LastDecl = ExternalLast;
1011}
1012
1013DeclContext::lookup_result
1014ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
1015                                                    DeclarationName Name) {
1016  ASTContext &Context = DC->getParentASTContext();
1017  StoredDeclsMap *Map;
1018  if (!(Map = DC->LookupPtr.getPointer()))
1019    Map = DC->CreateStoredDeclsMap(Context);
1020
1021  // Add an entry to the map for this name, if it's not already present.
1022  (*Map)[Name];
1023
1024  return DeclContext::lookup_result();
1025}
1026
1027DeclContext::lookup_result
1028ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
1029                                                  DeclarationName Name,
1030                                                  ArrayRef<NamedDecl*> Decls) {
1031  ASTContext &Context = DC->getParentASTContext();
1032  StoredDeclsMap *Map;
1033  if (!(Map = DC->LookupPtr.getPointer()))
1034    Map = DC->CreateStoredDeclsMap(Context);
1035
1036  StoredDeclsList &List = (*Map)[Name];
1037  for (ArrayRef<NamedDecl*>::iterator
1038         I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1039    if (List.isNull())
1040      List.setOnlyValue(*I);
1041    else
1042      // FIXME: Need declarationReplaces handling for redeclarations in modules.
1043      List.AddSubsequentDecl(*I);
1044  }
1045
1046  return List.getLookupResult();
1047}
1048
1049DeclContext::decl_iterator DeclContext::noload_decls_begin() const {
1050  return decl_iterator(FirstDecl);
1051}
1052
1053DeclContext::decl_iterator DeclContext::decls_begin() const {
1054  if (hasExternalLexicalStorage())
1055    LoadLexicalDeclsFromExternalStorage();
1056
1057  return decl_iterator(FirstDecl);
1058}
1059
1060bool DeclContext::decls_empty() const {
1061  if (hasExternalLexicalStorage())
1062    LoadLexicalDeclsFromExternalStorage();
1063
1064  return !FirstDecl;
1065}
1066
1067void DeclContext::removeDecl(Decl *D) {
1068  assert(D->getLexicalDeclContext() == this &&
1069         "decl being removed from non-lexical context");
1070  assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
1071         "decl is not in decls list");
1072
1073  // Remove D from the decl chain.  This is O(n) but hopefully rare.
1074  if (D == FirstDecl) {
1075    if (D == LastDecl)
1076      FirstDecl = LastDecl = 0;
1077    else
1078      FirstDecl = D->NextInContextAndBits.getPointer();
1079  } else {
1080    for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
1081      assert(I && "decl not found in linked list");
1082      if (I->NextInContextAndBits.getPointer() == D) {
1083        I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
1084        if (D == LastDecl) LastDecl = I;
1085        break;
1086      }
1087    }
1088  }
1089
1090  // Mark that D is no longer in the decl chain.
1091  D->NextInContextAndBits.setPointer(0);
1092
1093  // Remove D from the lookup table if necessary.
1094  if (isa<NamedDecl>(D)) {
1095    NamedDecl *ND = cast<NamedDecl>(D);
1096
1097    // Remove only decls that have a name
1098    if (!ND->getDeclName()) return;
1099
1100    StoredDeclsMap *Map = getPrimaryContext()->LookupPtr.getPointer();
1101    if (!Map) return;
1102
1103    StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1104    assert(Pos != Map->end() && "no lookup entry for decl");
1105    if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
1106      Pos->second.remove(ND);
1107  }
1108}
1109
1110void DeclContext::addHiddenDecl(Decl *D) {
1111  assert(D->getLexicalDeclContext() == this &&
1112         "Decl inserted into wrong lexical context");
1113  assert(!D->getNextDeclInContext() && D != LastDecl &&
1114         "Decl already inserted into a DeclContext");
1115
1116  if (FirstDecl) {
1117    LastDecl->NextInContextAndBits.setPointer(D);
1118    LastDecl = D;
1119  } else {
1120    FirstDecl = LastDecl = D;
1121  }
1122
1123  // Notify a C++ record declaration that we've added a member, so it can
1124  // update it's class-specific state.
1125  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1126    Record->addedMember(D);
1127
1128  // If this is a newly-created (not de-serialized) import declaration, wire
1129  // it in to the list of local import declarations.
1130  if (!D->isFromASTFile()) {
1131    if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
1132      D->getASTContext().addedLocalImportDecl(Import);
1133  }
1134}
1135
1136void DeclContext::addDecl(Decl *D) {
1137  addHiddenDecl(D);
1138
1139  if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1140    ND->getDeclContext()->getPrimaryContext()->
1141        makeDeclVisibleInContextWithFlags(ND, false, true);
1142}
1143
1144void DeclContext::addDeclInternal(Decl *D) {
1145  addHiddenDecl(D);
1146
1147  if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1148    ND->getDeclContext()->getPrimaryContext()->
1149        makeDeclVisibleInContextWithFlags(ND, true, true);
1150}
1151
1152/// shouldBeHidden - Determine whether a declaration which was declared
1153/// within its semantic context should be invisible to qualified name lookup.
1154static bool shouldBeHidden(NamedDecl *D) {
1155  // Skip unnamed declarations.
1156  if (!D->getDeclName())
1157    return true;
1158
1159  // Skip entities that can't be found by name lookup into a particular
1160  // context.
1161  if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1162      D->isTemplateParameter())
1163    return true;
1164
1165  // Skip template specializations.
1166  // FIXME: This feels like a hack. Should DeclarationName support
1167  // template-ids, or is there a better way to keep specializations
1168  // from being visible?
1169  if (isa<ClassTemplateSpecializationDecl>(D))
1170    return true;
1171  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1172    if (FD->isFunctionTemplateSpecialization())
1173      return true;
1174
1175  return false;
1176}
1177
1178/// buildLookup - Build the lookup data structure with all of the
1179/// declarations in this DeclContext (and any other contexts linked
1180/// to it or transparent contexts nested within it) and return it.
1181StoredDeclsMap *DeclContext::buildLookup() {
1182  assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1183
1184  // FIXME: Should we keep going if hasExternalVisibleStorage?
1185  if (!LookupPtr.getInt())
1186    return LookupPtr.getPointer();
1187
1188  SmallVector<DeclContext *, 2> Contexts;
1189  collectAllContexts(Contexts);
1190  for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
1191    buildLookupImpl(Contexts[I]);
1192
1193  // We no longer have any lazy decls.
1194  LookupPtr.setInt(false);
1195  NeedToReconcileExternalVisibleStorage = false;
1196  return LookupPtr.getPointer();
1197}
1198
1199/// buildLookupImpl - Build part of the lookup data structure for the
1200/// declarations contained within DCtx, which will either be this
1201/// DeclContext, a DeclContext linked to it, or a transparent context
1202/// nested within it.
1203void DeclContext::buildLookupImpl(DeclContext *DCtx) {
1204  for (decl_iterator I = DCtx->decls_begin(), E = DCtx->decls_end();
1205       I != E; ++I) {
1206    Decl *D = *I;
1207
1208    // Insert this declaration into the lookup structure, but only if
1209    // it's semantically within its decl context. Any other decls which
1210    // should be found in this context are added eagerly.
1211    if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1212      if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND))
1213        makeDeclVisibleInContextImpl(ND, false);
1214
1215    // If this declaration is itself a transparent declaration context
1216    // or inline namespace, add the members of this declaration of that
1217    // context (recursively).
1218    if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
1219      if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1220        buildLookupImpl(InnerCtx);
1221  }
1222}
1223
1224DeclContext::lookup_result
1225DeclContext::lookup(DeclarationName Name) {
1226  assert(DeclKind != Decl::LinkageSpec &&
1227         "Should not perform lookups into linkage specs!");
1228
1229  DeclContext *PrimaryContext = getPrimaryContext();
1230  if (PrimaryContext != this)
1231    return PrimaryContext->lookup(Name);
1232
1233  if (hasExternalVisibleStorage()) {
1234    StoredDeclsMap *Map = LookupPtr.getPointer();
1235    if (LookupPtr.getInt())
1236      Map = buildLookup();
1237    else if (NeedToReconcileExternalVisibleStorage)
1238      reconcileExternalVisibleStorage();
1239
1240    if (!Map)
1241      Map = CreateStoredDeclsMap(getParentASTContext());
1242
1243    // If a PCH/module has a result for this name, and we have a local
1244    // declaration, we will have imported the PCH/module result when adding the
1245    // local declaration or when reconciling the module.
1246    std::pair<StoredDeclsMap::iterator, bool> R =
1247        Map->insert(std::make_pair(Name, StoredDeclsList()));
1248    if (!R.second)
1249      return R.first->second.getLookupResult();
1250
1251    ExternalASTSource *Source = getParentASTContext().getExternalSource();
1252    if (Source->FindExternalVisibleDeclsByName(this, Name)) {
1253      if (StoredDeclsMap *Map = LookupPtr.getPointer()) {
1254        StoredDeclsMap::iterator I = Map->find(Name);
1255        if (I != Map->end())
1256          return I->second.getLookupResult();
1257      }
1258    }
1259
1260    return lookup_result(lookup_iterator(0), lookup_iterator(0));
1261  }
1262
1263  StoredDeclsMap *Map = LookupPtr.getPointer();
1264  if (LookupPtr.getInt())
1265    Map = buildLookup();
1266
1267  if (!Map)
1268    return lookup_result(lookup_iterator(0), lookup_iterator(0));
1269
1270  StoredDeclsMap::iterator I = Map->find(Name);
1271  if (I == Map->end())
1272    return lookup_result(lookup_iterator(0), lookup_iterator(0));
1273
1274  return I->second.getLookupResult();
1275}
1276
1277void DeclContext::localUncachedLookup(DeclarationName Name,
1278                                      SmallVectorImpl<NamedDecl *> &Results) {
1279  Results.clear();
1280
1281  // If there's no external storage, just perform a normal lookup and copy
1282  // the results.
1283  if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
1284    lookup_result LookupResults = lookup(Name);
1285    Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
1286    return;
1287  }
1288
1289  // If we have a lookup table, check there first. Maybe we'll get lucky.
1290  if (Name && !LookupPtr.getInt()) {
1291    if (StoredDeclsMap *Map = LookupPtr.getPointer()) {
1292      StoredDeclsMap::iterator Pos = Map->find(Name);
1293      if (Pos != Map->end()) {
1294        Results.insert(Results.end(),
1295                       Pos->second.getLookupResult().begin(),
1296                       Pos->second.getLookupResult().end());
1297        return;
1298      }
1299    }
1300  }
1301
1302  // Slow case: grovel through the declarations in our chain looking for
1303  // matches.
1304  for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1305    if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1306      if (ND->getDeclName() == Name)
1307        Results.push_back(ND);
1308  }
1309}
1310
1311DeclContext *DeclContext::getRedeclContext() {
1312  DeclContext *Ctx = this;
1313  // Skip through transparent contexts.
1314  while (Ctx->isTransparentContext())
1315    Ctx = Ctx->getParent();
1316  return Ctx;
1317}
1318
1319DeclContext *DeclContext::getEnclosingNamespaceContext() {
1320  DeclContext *Ctx = this;
1321  // Skip through non-namespace, non-translation-unit contexts.
1322  while (!Ctx->isFileContext())
1323    Ctx = Ctx->getParent();
1324  return Ctx->getPrimaryContext();
1325}
1326
1327bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1328  // For non-file contexts, this is equivalent to Equals.
1329  if (!isFileContext())
1330    return O->Equals(this);
1331
1332  do {
1333    if (O->Equals(this))
1334      return true;
1335
1336    const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1337    if (!NS || !NS->isInline())
1338      break;
1339    O = NS->getParent();
1340  } while (O);
1341
1342  return false;
1343}
1344
1345void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1346  DeclContext *PrimaryDC = this->getPrimaryContext();
1347  DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1348  // If the decl is being added outside of its semantic decl context, we
1349  // need to ensure that we eagerly build the lookup information for it.
1350  PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
1351}
1352
1353void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1354                                                    bool Recoverable) {
1355  assert(this == getPrimaryContext() && "expected a primary DC");
1356
1357  // Skip declarations within functions.
1358  // FIXME: We shouldn't need to build lookup tables for function declarations
1359  // ever, and we can't do so correctly because we can't model the nesting of
1360  // scopes which occurs within functions. We use "qualified" lookup into
1361  // function declarations when handling friend declarations inside nested
1362  // classes, and consequently accept the following invalid code:
1363  //
1364  //   void f() { void g(); { int g; struct S { friend void g(); }; } }
1365  if (isFunctionOrMethod() && !isa<FunctionDecl>(D))
1366    return;
1367
1368  // Skip declarations which should be invisible to name lookup.
1369  if (shouldBeHidden(D))
1370    return;
1371
1372  // If we already have a lookup data structure, perform the insertion into
1373  // it. If we might have externally-stored decls with this name, look them
1374  // up and perform the insertion. If this decl was declared outside its
1375  // semantic context, buildLookup won't add it, so add it now.
1376  //
1377  // FIXME: As a performance hack, don't add such decls into the translation
1378  // unit unless we're in C++, since qualified lookup into the TU is never
1379  // performed.
1380  if (LookupPtr.getPointer() || hasExternalVisibleStorage() ||
1381      ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1382       (getParentASTContext().getLangOpts().CPlusPlus ||
1383        !isTranslationUnit()))) {
1384    // If we have lazily omitted any decls, they might have the same name as
1385    // the decl which we are adding, so build a full lookup table before adding
1386    // this decl.
1387    buildLookup();
1388    makeDeclVisibleInContextImpl(D, Internal);
1389  } else {
1390    LookupPtr.setInt(true);
1391  }
1392
1393  // If we are a transparent context or inline namespace, insert into our
1394  // parent context, too. This operation is recursive.
1395  if (isTransparentContext() || isInlineNamespace())
1396    getParent()->getPrimaryContext()->
1397        makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1398
1399  Decl *DCAsDecl = cast<Decl>(this);
1400  // Notify that a decl was made visible unless we are a Tag being defined.
1401  if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1402    if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1403      L->AddedVisibleDecl(this, D);
1404}
1405
1406void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1407  // Find or create the stored declaration map.
1408  StoredDeclsMap *Map = LookupPtr.getPointer();
1409  if (!Map) {
1410    ASTContext *C = &getParentASTContext();
1411    Map = CreateStoredDeclsMap(*C);
1412  }
1413
1414  // If there is an external AST source, load any declarations it knows about
1415  // with this declaration's name.
1416  // If the lookup table contains an entry about this name it means that we
1417  // have already checked the external source.
1418  if (!Internal)
1419    if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1420      if (hasExternalVisibleStorage() &&
1421          Map->find(D->getDeclName()) == Map->end())
1422        Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1423
1424  // Insert this declaration into the map.
1425  StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
1426  if (DeclNameEntries.isNull()) {
1427    DeclNameEntries.setOnlyValue(D);
1428    return;
1429  }
1430
1431  if (DeclNameEntries.HandleRedeclaration(D)) {
1432    // This declaration has replaced an existing one for which
1433    // declarationReplaces returns true.
1434    return;
1435  }
1436
1437  // Put this declaration into the appropriate slot.
1438  DeclNameEntries.AddSubsequentDecl(D);
1439}
1440
1441/// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1442/// this context.
1443DeclContext::udir_iterator_range
1444DeclContext::getUsingDirectives() const {
1445  // FIXME: Use something more efficient than normal lookup for using
1446  // directives. In C++, using directives are looked up more than anything else.
1447  lookup_const_result Result = lookup(UsingDirectiveDecl::getName());
1448  return udir_iterator_range(reinterpret_cast<udir_iterator>(Result.begin()),
1449                             reinterpret_cast<udir_iterator>(Result.end()));
1450}
1451
1452//===----------------------------------------------------------------------===//
1453// Creation and Destruction of StoredDeclsMaps.                               //
1454//===----------------------------------------------------------------------===//
1455
1456StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1457  assert(!LookupPtr.getPointer() && "context already has a decls map");
1458  assert(getPrimaryContext() == this &&
1459         "creating decls map on non-primary context");
1460
1461  StoredDeclsMap *M;
1462  bool Dependent = isDependentContext();
1463  if (Dependent)
1464    M = new DependentStoredDeclsMap();
1465  else
1466    M = new StoredDeclsMap();
1467  M->Previous = C.LastSDM;
1468  C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1469  LookupPtr.setPointer(M);
1470  return M;
1471}
1472
1473void ASTContext::ReleaseDeclContextMaps() {
1474  // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1475  // pointer because the subclass doesn't add anything that needs to
1476  // be deleted.
1477  StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1478}
1479
1480void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1481  while (Map) {
1482    // Advance the iteration before we invalidate memory.
1483    llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1484
1485    if (Dependent)
1486      delete static_cast<DependentStoredDeclsMap*>(Map);
1487    else
1488      delete Map;
1489
1490    Map = Next.getPointer();
1491    Dependent = Next.getInt();
1492  }
1493}
1494
1495DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1496                                                 DeclContext *Parent,
1497                                           const PartialDiagnostic &PDiag) {
1498  assert(Parent->isDependentContext()
1499         && "cannot iterate dependent diagnostics of non-dependent context");
1500  Parent = Parent->getPrimaryContext();
1501  if (!Parent->LookupPtr.getPointer())
1502    Parent->CreateStoredDeclsMap(C);
1503
1504  DependentStoredDeclsMap *Map
1505    = static_cast<DependentStoredDeclsMap*>(Parent->LookupPtr.getPointer());
1506
1507  // Allocate the copy of the PartialDiagnostic via the ASTContext's
1508  // BumpPtrAllocator, rather than the ASTContext itself.
1509  PartialDiagnostic::Storage *DiagStorage = 0;
1510  if (PDiag.hasStorage())
1511    DiagStorage = new (C) PartialDiagnostic::Storage;
1512
1513  DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
1514
1515  // TODO: Maybe we shouldn't reverse the order during insertion.
1516  DD->NextDiagnostic = Map->FirstDiagnostic;
1517  Map->FirstDiagnostic = DD;
1518
1519  return DD;
1520}
1521