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