DeclBase.cpp revision 006e42f0c8b65b783d565ef10b938a9e82fc02e3
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  std::string HintMessage;
287  if (!A->getMessage().empty()) {
288    HintMessage = " - ";
289    HintMessage += A->getMessage();
290  }
291
292  // Make sure that this declaration has not been marked 'unavailable'.
293  if (A->getUnavailable()) {
294    if (Message) {
295      Message->clear();
296      llvm::raw_string_ostream Out(*Message);
297      Out << "not available on " << PrettyPlatformName
298          << HintMessage;
299    }
300
301    return AR_Unavailable;
302  }
303
304  // Make sure that this declaration has already been introduced.
305  if (!A->getIntroduced().empty() &&
306      TargetMinVersion < A->getIntroduced()) {
307    if (Message) {
308      Message->clear();
309      llvm::raw_string_ostream Out(*Message);
310      Out << "introduced in " << PrettyPlatformName << ' '
311          << A->getIntroduced() << HintMessage;
312    }
313
314    return AR_NotYetIntroduced;
315  }
316
317  // Make sure that this declaration hasn't been obsoleted.
318  if (!A->getObsoleted().empty() && TargetMinVersion >= A->getObsoleted()) {
319    if (Message) {
320      Message->clear();
321      llvm::raw_string_ostream Out(*Message);
322      Out << "obsoleted in " << PrettyPlatformName << ' '
323          << A->getObsoleted() << HintMessage;
324    }
325
326    return AR_Unavailable;
327  }
328
329  // Make sure that this declaration hasn't been deprecated.
330  if (!A->getDeprecated().empty() && TargetMinVersion >= A->getDeprecated()) {
331    if (Message) {
332      Message->clear();
333      llvm::raw_string_ostream Out(*Message);
334      Out << "first deprecated in " << PrettyPlatformName << ' '
335          << A->getDeprecated() << HintMessage;
336    }
337
338    return AR_Deprecated;
339  }
340
341  return AR_Available;
342}
343
344AvailabilityResult Decl::getAvailability(std::string *Message) const {
345  AvailabilityResult Result = AR_Available;
346  std::string ResultMessage;
347
348  for (attr_iterator A = attr_begin(), AEnd = attr_end(); A != AEnd; ++A) {
349    if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(*A)) {
350      if (Result >= AR_Deprecated)
351        continue;
352
353      if (Message)
354        ResultMessage = Deprecated->getMessage();
355
356      Result = AR_Deprecated;
357      continue;
358    }
359
360    if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(*A)) {
361      if (Message)
362        *Message = Unavailable->getMessage();
363      return AR_Unavailable;
364    }
365
366    if (AvailabilityAttr *Availability = dyn_cast<AvailabilityAttr>(*A)) {
367      AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
368                                                Message);
369
370      if (AR == AR_Unavailable)
371        return AR_Unavailable;
372
373      if (AR > Result) {
374        Result = AR;
375        if (Message)
376          ResultMessage.swap(*Message);
377      }
378      continue;
379    }
380  }
381
382  if (Message)
383    Message->swap(ResultMessage);
384  return Result;
385}
386
387bool Decl::canBeWeakImported(bool &IsDefinition) const {
388  IsDefinition = false;
389  if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
390    if (!Var->hasExternalStorage() || Var->getInit()) {
391      IsDefinition = true;
392      return false;
393    }
394  } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
395    if (FD->hasBody()) {
396      IsDefinition = true;
397      return false;
398    }
399  } else if (isa<ObjCPropertyDecl>(this) || isa<ObjCMethodDecl>(this))
400    return false;
401  else if (!(getASTContext().getLangOptions().ObjCNonFragileABI &&
402             isa<ObjCInterfaceDecl>(this)))
403    return false;
404
405  return true;
406}
407
408bool Decl::isWeakImported() const {
409  bool IsDefinition;
410  if (!canBeWeakImported(IsDefinition))
411    return false;
412
413  for (attr_iterator A = attr_begin(), AEnd = attr_end(); A != AEnd; ++A) {
414    if (isa<WeakImportAttr>(*A))
415      return true;
416
417    if (AvailabilityAttr *Availability = dyn_cast<AvailabilityAttr>(*A)) {
418      if (CheckAvailability(getASTContext(), Availability, 0)
419                                                         == AR_NotYetIntroduced)
420        return true;
421    }
422  }
423
424  return false;
425}
426
427unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
428  switch (DeclKind) {
429    case Function:
430    case CXXMethod:
431    case CXXConstructor:
432    case CXXDestructor:
433    case CXXConversion:
434    case EnumConstant:
435    case Var:
436    case ImplicitParam:
437    case ParmVar:
438    case NonTypeTemplateParm:
439    case ObjCMethod:
440    case ObjCProperty:
441      return IDNS_Ordinary;
442    case Label:
443      return IDNS_Label;
444    case IndirectField:
445      return IDNS_Ordinary | IDNS_Member;
446
447    case ObjCCompatibleAlias:
448    case ObjCInterface:
449      return IDNS_Ordinary | IDNS_Type;
450
451    case Typedef:
452    case TypeAlias:
453    case TypeAliasTemplate:
454    case UnresolvedUsingTypename:
455    case TemplateTypeParm:
456      return IDNS_Ordinary | IDNS_Type;
457
458    case UsingShadow:
459      return 0; // we'll actually overwrite this later
460
461    case UnresolvedUsingValue:
462      return IDNS_Ordinary | IDNS_Using;
463
464    case Using:
465      return IDNS_Using;
466
467    case ObjCProtocol:
468      return IDNS_ObjCProtocol;
469
470    case Field:
471    case ObjCAtDefsField:
472    case ObjCIvar:
473      return IDNS_Member;
474
475    case Record:
476    case CXXRecord:
477    case Enum:
478      return IDNS_Tag | IDNS_Type;
479
480    case Namespace:
481    case NamespaceAlias:
482      return IDNS_Namespace;
483
484    case FunctionTemplate:
485      return IDNS_Ordinary;
486
487    case ClassTemplate:
488    case TemplateTemplateParm:
489      return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
490
491    // Never have names.
492    case Friend:
493    case FriendTemplate:
494    case AccessSpec:
495    case LinkageSpec:
496    case FileScopeAsm:
497    case StaticAssert:
498    case ObjCClass:
499    case ObjCPropertyImpl:
500    case ObjCForwardProtocol:
501    case Block:
502    case TranslationUnit:
503
504    case UsingDirective:
505    case ClassTemplateSpecialization:
506    case ClassTemplatePartialSpecialization:
507    case ClassScopeFunctionSpecialization:
508    case ObjCImplementation:
509    case ObjCCategory:
510    case ObjCCategoryImpl:
511    case Import:
512      // Never looked up by name.
513      return 0;
514  }
515
516  return 0;
517}
518
519void Decl::setAttrs(const AttrVec &attrs) {
520  assert(!HasAttrs && "Decl already contains attrs.");
521
522  AttrVec &AttrBlank = getASTContext().getDeclAttrs(this);
523  assert(AttrBlank.empty() && "HasAttrs was wrong?");
524
525  AttrBlank = attrs;
526  HasAttrs = true;
527}
528
529void Decl::dropAttrs() {
530  if (!HasAttrs) return;
531
532  HasAttrs = false;
533  getASTContext().eraseDeclAttrs(this);
534}
535
536const AttrVec &Decl::getAttrs() const {
537  assert(HasAttrs && "No attrs to get!");
538  return getASTContext().getDeclAttrs(this);
539}
540
541void Decl::swapAttrs(Decl *RHS) {
542  bool HasLHSAttr = this->HasAttrs;
543  bool HasRHSAttr = RHS->HasAttrs;
544
545  // Usually, neither decl has attrs, nothing to do.
546  if (!HasLHSAttr && !HasRHSAttr) return;
547
548  // If 'this' has no attrs, swap the other way.
549  if (!HasLHSAttr)
550    return RHS->swapAttrs(this);
551
552  ASTContext &Context = getASTContext();
553
554  // Handle the case when both decls have attrs.
555  if (HasRHSAttr) {
556    std::swap(Context.getDeclAttrs(this), Context.getDeclAttrs(RHS));
557    return;
558  }
559
560  // Otherwise, LHS has an attr and RHS doesn't.
561  Context.getDeclAttrs(RHS) = Context.getDeclAttrs(this);
562  Context.eraseDeclAttrs(this);
563  this->HasAttrs = false;
564  RHS->HasAttrs = true;
565}
566
567Decl *Decl::castFromDeclContext (const DeclContext *D) {
568  Decl::Kind DK = D->getDeclKind();
569  switch(DK) {
570#define DECL(NAME, BASE)
571#define DECL_CONTEXT(NAME) \
572    case Decl::NAME:       \
573      return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
574#define DECL_CONTEXT_BASE(NAME)
575#include "clang/AST/DeclNodes.inc"
576    default:
577#define DECL(NAME, BASE)
578#define DECL_CONTEXT_BASE(NAME)                  \
579      if (DK >= first##NAME && DK <= last##NAME) \
580        return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
581#include "clang/AST/DeclNodes.inc"
582      llvm_unreachable("a decl that inherits DeclContext isn't handled");
583  }
584}
585
586DeclContext *Decl::castToDeclContext(const Decl *D) {
587  Decl::Kind DK = D->getKind();
588  switch(DK) {
589#define DECL(NAME, BASE)
590#define DECL_CONTEXT(NAME) \
591    case Decl::NAME:       \
592      return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
593#define DECL_CONTEXT_BASE(NAME)
594#include "clang/AST/DeclNodes.inc"
595    default:
596#define DECL(NAME, BASE)
597#define DECL_CONTEXT_BASE(NAME)                                   \
598      if (DK >= first##NAME && DK <= last##NAME)                  \
599        return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
600#include "clang/AST/DeclNodes.inc"
601      llvm_unreachable("a decl that inherits DeclContext isn't handled");
602  }
603}
604
605SourceLocation Decl::getBodyRBrace() const {
606  // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
607  // FunctionDecl stores EndRangeLoc for this purpose.
608  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
609    const FunctionDecl *Definition;
610    if (FD->hasBody(Definition))
611      return Definition->getSourceRange().getEnd();
612    return SourceLocation();
613  }
614
615  if (Stmt *Body = getBody())
616    return Body->getSourceRange().getEnd();
617
618  return SourceLocation();
619}
620
621void Decl::CheckAccessDeclContext() const {
622#ifndef NDEBUG
623  // Suppress this check if any of the following hold:
624  // 1. this is the translation unit (and thus has no parent)
625  // 2. this is a template parameter (and thus doesn't belong to its context)
626  // 3. this is a non-type template parameter
627  // 4. the context is not a record
628  // 5. it's invalid
629  // 6. it's a C++0x static_assert.
630  if (isa<TranslationUnitDecl>(this) ||
631      isa<TemplateTypeParmDecl>(this) ||
632      isa<NonTypeTemplateParmDecl>(this) ||
633      !isa<CXXRecordDecl>(getDeclContext()) ||
634      isInvalidDecl() ||
635      isa<StaticAssertDecl>(this) ||
636      // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
637      // as DeclContext (?).
638      isa<ParmVarDecl>(this) ||
639      // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
640      // AS_none as access specifier.
641      isa<CXXRecordDecl>(this) ||
642      isa<ClassScopeFunctionSpecializationDecl>(this))
643    return;
644
645  assert(Access != AS_none &&
646         "Access specifier is AS_none inside a record decl");
647#endif
648}
649
650DeclContext *Decl::getNonClosureContext() {
651  return getDeclContext()->getNonClosureAncestor();
652}
653
654DeclContext *DeclContext::getNonClosureAncestor() {
655  DeclContext *DC = this;
656
657  // This is basically "while (DC->isClosure()) DC = DC->getParent();"
658  // except that it's significantly more efficient to cast to a known
659  // decl type and call getDeclContext() than to call getParent().
660  while (isa<BlockDecl>(DC))
661    DC = cast<BlockDecl>(DC)->getDeclContext();
662
663  assert(!DC->isClosure());
664  return DC;
665}
666
667//===----------------------------------------------------------------------===//
668// DeclContext Implementation
669//===----------------------------------------------------------------------===//
670
671bool DeclContext::classof(const Decl *D) {
672  switch (D->getKind()) {
673#define DECL(NAME, BASE)
674#define DECL_CONTEXT(NAME) case Decl::NAME:
675#define DECL_CONTEXT_BASE(NAME)
676#include "clang/AST/DeclNodes.inc"
677      return true;
678    default:
679#define DECL(NAME, BASE)
680#define DECL_CONTEXT_BASE(NAME)                 \
681      if (D->getKind() >= Decl::first##NAME &&  \
682          D->getKind() <= Decl::last##NAME)     \
683        return true;
684#include "clang/AST/DeclNodes.inc"
685      return false;
686  }
687}
688
689DeclContext::~DeclContext() { }
690
691/// \brief Find the parent context of this context that will be
692/// used for unqualified name lookup.
693///
694/// Generally, the parent lookup context is the semantic context. However, for
695/// a friend function the parent lookup context is the lexical context, which
696/// is the class in which the friend is declared.
697DeclContext *DeclContext::getLookupParent() {
698  // FIXME: Find a better way to identify friends
699  if (isa<FunctionDecl>(this))
700    if (getParent()->getRedeclContext()->isFileContext() &&
701        getLexicalParent()->getRedeclContext()->isRecord())
702      return getLexicalParent();
703
704  return getParent();
705}
706
707bool DeclContext::isInlineNamespace() const {
708  return isNamespace() &&
709         cast<NamespaceDecl>(this)->isInline();
710}
711
712bool DeclContext::isDependentContext() const {
713  if (isFileContext())
714    return false;
715
716  if (isa<ClassTemplatePartialSpecializationDecl>(this))
717    return true;
718
719  if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
720    if (Record->getDescribedClassTemplate())
721      return true;
722
723  if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
724    if (Function->getDescribedFunctionTemplate())
725      return true;
726
727    // Friend function declarations are dependent if their *lexical*
728    // context is dependent.
729    if (cast<Decl>(this)->getFriendObjectKind())
730      return getLexicalParent()->isDependentContext();
731  }
732
733  return getParent() && getParent()->isDependentContext();
734}
735
736bool DeclContext::isTransparentContext() const {
737  if (DeclKind == Decl::Enum)
738    return !cast<EnumDecl>(this)->isScoped();
739  else if (DeclKind == Decl::LinkageSpec)
740    return true;
741
742  return false;
743}
744
745bool DeclContext::isExternCContext() const {
746  const DeclContext *DC = this;
747  while (DC->DeclKind != Decl::TranslationUnit) {
748    if (DC->DeclKind == Decl::LinkageSpec)
749      return cast<LinkageSpecDecl>(DC)->getLanguage()
750        == LinkageSpecDecl::lang_c;
751    DC = DC->getParent();
752  }
753  return false;
754}
755
756bool DeclContext::Encloses(const DeclContext *DC) const {
757  if (getPrimaryContext() != this)
758    return getPrimaryContext()->Encloses(DC);
759
760  for (; DC; DC = DC->getParent())
761    if (DC->getPrimaryContext() == this)
762      return true;
763  return false;
764}
765
766DeclContext *DeclContext::getPrimaryContext() {
767  switch (DeclKind) {
768  case Decl::TranslationUnit:
769  case Decl::LinkageSpec:
770  case Decl::Block:
771    // There is only one DeclContext for these entities.
772    return this;
773
774  case Decl::Namespace:
775    // The original namespace is our primary context.
776    return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
777
778  case Decl::ObjCMethod:
779    return this;
780
781  case Decl::ObjCInterface:
782  case Decl::ObjCProtocol:
783  case Decl::ObjCCategory:
784    // FIXME: Can Objective-C interfaces be forward-declared?
785    return this;
786
787  case Decl::ObjCImplementation:
788  case Decl::ObjCCategoryImpl:
789    return this;
790
791  default:
792    if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
793      // If this is a tag type that has a definition or is currently
794      // being defined, that definition is our primary context.
795      TagDecl *Tag = cast<TagDecl>(this);
796      assert(isa<TagType>(Tag->TypeForDecl) ||
797             isa<InjectedClassNameType>(Tag->TypeForDecl));
798
799      if (TagDecl *Def = Tag->getDefinition())
800        return Def;
801
802      if (!isa<InjectedClassNameType>(Tag->TypeForDecl)) {
803        const TagType *TagTy = cast<TagType>(Tag->TypeForDecl);
804        if (TagTy->isBeingDefined())
805          // FIXME: is it necessarily being defined in the decl
806          // that owns the type?
807          return TagTy->getDecl();
808      }
809
810      return Tag;
811    }
812
813    assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
814          "Unknown DeclContext kind");
815    return this;
816  }
817}
818
819DeclContext *DeclContext::getNextContext() {
820  switch (DeclKind) {
821  case Decl::Namespace:
822    // Return the next namespace
823    return static_cast<NamespaceDecl*>(this)->getNextNamespace();
824
825  default:
826    return 0;
827  }
828}
829
830std::pair<Decl *, Decl *>
831DeclContext::BuildDeclChain(const SmallVectorImpl<Decl*> &Decls,
832                            bool FieldsAlreadyLoaded) {
833  // Build up a chain of declarations via the Decl::NextDeclInContext field.
834  Decl *FirstNewDecl = 0;
835  Decl *PrevDecl = 0;
836  for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
837    if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
838      continue;
839
840    Decl *D = Decls[I];
841    if (PrevDecl)
842      PrevDecl->NextDeclInContext = D;
843    else
844      FirstNewDecl = D;
845
846    PrevDecl = D;
847  }
848
849  return std::make_pair(FirstNewDecl, PrevDecl);
850}
851
852/// \brief Load the declarations within this lexical storage from an
853/// external source.
854void
855DeclContext::LoadLexicalDeclsFromExternalStorage() const {
856  ExternalASTSource *Source = getParentASTContext().getExternalSource();
857  assert(hasExternalLexicalStorage() && Source && "No external storage?");
858
859  // Notify that we have a DeclContext that is initializing.
860  ExternalASTSource::Deserializing ADeclContext(Source);
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  // We may have already loaded just the fields of this record, in which case
878  // we need to ignore them.
879  bool FieldsAlreadyLoaded = false;
880  if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
881    FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
882
883  // Splice the newly-read declarations into the beginning of the list
884  // of declarations.
885  Decl *ExternalFirst, *ExternalLast;
886  llvm::tie(ExternalFirst, ExternalLast) = BuildDeclChain(Decls,
887                                                          FieldsAlreadyLoaded);
888  ExternalLast->NextDeclInContext = FirstDecl;
889  FirstDecl = ExternalFirst;
890  if (!LastDecl)
891    LastDecl = ExternalLast;
892}
893
894DeclContext::lookup_result
895ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
896                                                    DeclarationName Name) {
897  ASTContext &Context = DC->getParentASTContext();
898  StoredDeclsMap *Map;
899  if (!(Map = DC->LookupPtr))
900    Map = DC->CreateStoredDeclsMap(Context);
901
902  StoredDeclsList &List = (*Map)[Name];
903  assert(List.isNull());
904  (void) List;
905
906  return DeclContext::lookup_result();
907}
908
909DeclContext::lookup_result
910ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
911                                                  DeclarationName Name,
912                                                  ArrayRef<NamedDecl*> Decls) {
913  ASTContext &Context = DC->getParentASTContext();;
914
915  StoredDeclsMap *Map;
916  if (!(Map = DC->LookupPtr))
917    Map = DC->CreateStoredDeclsMap(Context);
918
919  StoredDeclsList &List = (*Map)[Name];
920  for (ArrayRef<NamedDecl*>::iterator
921         I = Decls.begin(), E = Decls.end(); I != E; ++I) {
922    if (List.isNull())
923      List.setOnlyValue(*I);
924    else
925      List.AddSubsequentDecl(*I);
926  }
927
928  return List.getLookupResult();
929}
930
931DeclContext::decl_iterator DeclContext::noload_decls_begin() const {
932  return decl_iterator(FirstDecl);
933}
934
935DeclContext::decl_iterator DeclContext::noload_decls_end() const {
936  return decl_iterator();
937}
938
939DeclContext::decl_iterator DeclContext::decls_begin() const {
940  if (hasExternalLexicalStorage())
941    LoadLexicalDeclsFromExternalStorage();
942
943  return decl_iterator(FirstDecl);
944}
945
946DeclContext::decl_iterator DeclContext::decls_end() const {
947  if (hasExternalLexicalStorage())
948    LoadLexicalDeclsFromExternalStorage();
949
950  return decl_iterator();
951}
952
953bool DeclContext::decls_empty() const {
954  if (hasExternalLexicalStorage())
955    LoadLexicalDeclsFromExternalStorage();
956
957  return !FirstDecl;
958}
959
960void DeclContext::removeDecl(Decl *D) {
961  assert(D->getLexicalDeclContext() == this &&
962         "decl being removed from non-lexical context");
963  assert((D->NextDeclInContext || D == LastDecl) &&
964         "decl is not in decls list");
965
966  // Remove D from the decl chain.  This is O(n) but hopefully rare.
967  if (D == FirstDecl) {
968    if (D == LastDecl)
969      FirstDecl = LastDecl = 0;
970    else
971      FirstDecl = D->NextDeclInContext;
972  } else {
973    for (Decl *I = FirstDecl; true; I = I->NextDeclInContext) {
974      assert(I && "decl not found in linked list");
975      if (I->NextDeclInContext == D) {
976        I->NextDeclInContext = D->NextDeclInContext;
977        if (D == LastDecl) LastDecl = I;
978        break;
979      }
980    }
981  }
982
983  // Mark that D is no longer in the decl chain.
984  D->NextDeclInContext = 0;
985
986  // Remove D from the lookup table if necessary.
987  if (isa<NamedDecl>(D)) {
988    NamedDecl *ND = cast<NamedDecl>(D);
989
990    // Remove only decls that have a name
991    if (!ND->getDeclName()) return;
992
993    StoredDeclsMap *Map = getPrimaryContext()->LookupPtr;
994    if (!Map) return;
995
996    StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
997    assert(Pos != Map->end() && "no lookup entry for decl");
998    if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
999      Pos->second.remove(ND);
1000  }
1001}
1002
1003void DeclContext::addHiddenDecl(Decl *D) {
1004  assert(D->getLexicalDeclContext() == this &&
1005         "Decl inserted into wrong lexical context");
1006  assert(!D->getNextDeclInContext() && D != LastDecl &&
1007         "Decl already inserted into a DeclContext");
1008
1009  if (FirstDecl) {
1010    LastDecl->NextDeclInContext = D;
1011    LastDecl = D;
1012  } else {
1013    FirstDecl = LastDecl = D;
1014  }
1015
1016  // Notify a C++ record declaration that we've added a member, so it can
1017  // update it's class-specific state.
1018  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1019    Record->addedMember(D);
1020
1021  // If this is a newly-created (not de-serialized) import declaration, wire
1022  // it in to the list of local import declarations.
1023  if (!D->isFromASTFile()) {
1024    if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
1025      D->getASTContext().addedLocalImportDecl(Import);
1026  }
1027}
1028
1029void DeclContext::addDecl(Decl *D) {
1030  addHiddenDecl(D);
1031
1032  if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1033    ND->getDeclContext()->makeDeclVisibleInContext(ND);
1034}
1035
1036void DeclContext::addDeclInternal(Decl *D) {
1037  addHiddenDecl(D);
1038
1039  if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1040    ND->getDeclContext()->makeDeclVisibleInContextInternal(ND);
1041}
1042
1043/// buildLookup - Build the lookup data structure with all of the
1044/// declarations in DCtx (and any other contexts linked to it or
1045/// transparent contexts nested within it).
1046void DeclContext::buildLookup(DeclContext *DCtx) {
1047  for (; DCtx; DCtx = DCtx->getNextContext()) {
1048    for (decl_iterator D = DCtx->decls_begin(),
1049                    DEnd = DCtx->decls_end();
1050         D != DEnd; ++D) {
1051      // Insert this declaration into the lookup structure, but only
1052      // if it's semantically in its decl context.  During non-lazy
1053      // lookup building, this is implicitly enforced by addDecl.
1054      if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
1055        if (D->getDeclContext() == DCtx)
1056          makeDeclVisibleInContextImpl(ND, false);
1057
1058      // Insert any forward-declared Objective-C interface into the lookup
1059      // data structure.
1060      if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(*D))
1061        makeDeclVisibleInContextImpl(Class->getForwardInterfaceDecl(), false);
1062
1063      // If this declaration is itself a transparent declaration context or
1064      // inline namespace, add its members (recursively).
1065      if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D))
1066        if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1067          buildLookup(InnerCtx->getPrimaryContext());
1068    }
1069  }
1070}
1071
1072DeclContext::lookup_result
1073DeclContext::lookup(DeclarationName Name) {
1074  DeclContext *PrimaryContext = getPrimaryContext();
1075  if (PrimaryContext != this)
1076    return PrimaryContext->lookup(Name);
1077
1078  if (hasExternalVisibleStorage()) {
1079    // Check to see if we've already cached the lookup results.
1080    if (LookupPtr) {
1081      StoredDeclsMap::iterator I = LookupPtr->find(Name);
1082      if (I != LookupPtr->end())
1083        return I->second.getLookupResult();
1084    }
1085
1086    ExternalASTSource *Source = getParentASTContext().getExternalSource();
1087    return Source->FindExternalVisibleDeclsByName(this, Name);
1088  }
1089
1090  /// If there is no lookup data structure, build one now by walking
1091  /// all of the linked DeclContexts (in declaration order!) and
1092  /// inserting their values.
1093  if (!LookupPtr) {
1094    buildLookup(this);
1095
1096    if (!LookupPtr)
1097      return lookup_result(lookup_iterator(0), lookup_iterator(0));
1098  }
1099
1100  StoredDeclsMap::iterator Pos = LookupPtr->find(Name);
1101  if (Pos == LookupPtr->end())
1102    return lookup_result(lookup_iterator(0), lookup_iterator(0));
1103  return Pos->second.getLookupResult();
1104}
1105
1106DeclContext::lookup_const_result
1107DeclContext::lookup(DeclarationName Name) const {
1108  return const_cast<DeclContext*>(this)->lookup(Name);
1109}
1110
1111void DeclContext::localUncachedLookup(DeclarationName Name,
1112                                  llvm::SmallVectorImpl<NamedDecl *> &Results) {
1113  Results.clear();
1114
1115  // If there's no external storage, just perform a normal lookup and copy
1116  // the results.
1117  if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage()) {
1118    lookup_result LookupResults = lookup(Name);
1119    Results.insert(Results.end(), LookupResults.first, LookupResults.second);
1120    return;
1121  }
1122
1123  // If we have a lookup table, check there first. Maybe we'll get lucky.
1124  if (LookupPtr) {
1125    StoredDeclsMap::iterator Pos = LookupPtr->find(Name);
1126    if (Pos != LookupPtr->end()) {
1127      Results.insert(Results.end(),
1128                     Pos->second.getLookupResult().first,
1129                     Pos->second.getLookupResult().second);
1130      return;
1131    }
1132  }
1133
1134  // Slow case: grovel through the declarations in our chain looking for
1135  // matches.
1136  for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1137    if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1138      if (ND->getDeclName() == Name)
1139        Results.push_back(ND);
1140  }
1141}
1142
1143DeclContext *DeclContext::getRedeclContext() {
1144  DeclContext *Ctx = this;
1145  // Skip through transparent contexts.
1146  while (Ctx->isTransparentContext())
1147    Ctx = Ctx->getParent();
1148  return Ctx;
1149}
1150
1151DeclContext *DeclContext::getEnclosingNamespaceContext() {
1152  DeclContext *Ctx = this;
1153  // Skip through non-namespace, non-translation-unit contexts.
1154  while (!Ctx->isFileContext())
1155    Ctx = Ctx->getParent();
1156  return Ctx->getPrimaryContext();
1157}
1158
1159bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1160  // For non-file contexts, this is equivalent to Equals.
1161  if (!isFileContext())
1162    return O->Equals(this);
1163
1164  do {
1165    if (O->Equals(this))
1166      return true;
1167
1168    const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1169    if (!NS || !NS->isInline())
1170      break;
1171    O = NS->getParent();
1172  } while (O);
1173
1174  return false;
1175}
1176
1177void DeclContext::makeDeclVisibleInContext(NamedDecl *D, bool Recoverable)
1178{
1179    makeDeclVisibleInContextWithFlags(D, false, Recoverable);
1180}
1181
1182void DeclContext::makeDeclVisibleInContextInternal(NamedDecl *D, bool Recoverable)
1183{
1184    makeDeclVisibleInContextWithFlags(D, true, Recoverable);
1185}
1186
1187void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal, bool Recoverable) {
1188  // FIXME: This feels like a hack. Should DeclarationName support
1189  // template-ids, or is there a better way to keep specializations
1190  // from being visible?
1191  if (isa<ClassTemplateSpecializationDecl>(D) || D->isTemplateParameter())
1192    return;
1193  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1194    if (FD->isFunctionTemplateSpecialization())
1195      return;
1196
1197  DeclContext *PrimaryContext = getPrimaryContext();
1198  if (PrimaryContext != this) {
1199    PrimaryContext->makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1200    return;
1201  }
1202
1203  // If we already have a lookup data structure, perform the insertion
1204  // into it. If we haven't deserialized externally stored decls, deserialize
1205  // them so we can add the decl. Otherwise, be lazy and don't build that
1206  // structure until someone asks for it.
1207  if (LookupPtr || !Recoverable || hasExternalVisibleStorage())
1208    makeDeclVisibleInContextImpl(D, Internal);
1209
1210  // If we are a transparent context or inline namespace, insert into our
1211  // parent context, too. This operation is recursive.
1212  if (isTransparentContext() || isInlineNamespace())
1213    getParent()->makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1214
1215  Decl *DCAsDecl = cast<Decl>(this);
1216  // Notify that a decl was made visible unless it's a Tag being defined.
1217  if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1218    if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1219      L->AddedVisibleDecl(this, D);
1220}
1221
1222void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1223  // Skip unnamed declarations.
1224  if (!D->getDeclName())
1225    return;
1226
1227  // Skip entities that can't be found by name lookup into a particular
1228  // context.
1229  if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1230      D->isTemplateParameter())
1231    return;
1232
1233  ASTContext *C = 0;
1234  if (!LookupPtr) {
1235    C = &getParentASTContext();
1236    CreateStoredDeclsMap(*C);
1237  }
1238
1239  // If there is an external AST source, load any declarations it knows about
1240  // with this declaration's name.
1241  // If the lookup table contains an entry about this name it means that we
1242  // have already checked the external source.
1243  if (!Internal)
1244    if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1245      if (hasExternalVisibleStorage() &&
1246          LookupPtr->find(D->getDeclName()) == LookupPtr->end())
1247        Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1248
1249  // Insert this declaration into the map.
1250  StoredDeclsList &DeclNameEntries = (*LookupPtr)[D->getDeclName()];
1251  if (DeclNameEntries.isNull()) {
1252    DeclNameEntries.setOnlyValue(D);
1253    return;
1254  }
1255
1256  // If it is possible that this is a redeclaration, check to see if there is
1257  // already a decl for which declarationReplaces returns true.  If there is
1258  // one, just replace it and return.
1259  if (DeclNameEntries.HandleRedeclaration(D))
1260    return;
1261
1262  // Put this declaration into the appropriate slot.
1263  DeclNameEntries.AddSubsequentDecl(D);
1264}
1265
1266/// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1267/// this context.
1268DeclContext::udir_iterator_range
1269DeclContext::getUsingDirectives() const {
1270  lookup_const_result Result = lookup(UsingDirectiveDecl::getName());
1271  return udir_iterator_range(reinterpret_cast<udir_iterator>(Result.first),
1272                             reinterpret_cast<udir_iterator>(Result.second));
1273}
1274
1275//===----------------------------------------------------------------------===//
1276// Creation and Destruction of StoredDeclsMaps.                               //
1277//===----------------------------------------------------------------------===//
1278
1279StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1280  assert(!LookupPtr && "context already has a decls map");
1281  assert(getPrimaryContext() == this &&
1282         "creating decls map on non-primary context");
1283
1284  StoredDeclsMap *M;
1285  bool Dependent = isDependentContext();
1286  if (Dependent)
1287    M = new DependentStoredDeclsMap();
1288  else
1289    M = new StoredDeclsMap();
1290  M->Previous = C.LastSDM;
1291  C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1292  LookupPtr = M;
1293  return M;
1294}
1295
1296void ASTContext::ReleaseDeclContextMaps() {
1297  // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1298  // pointer because the subclass doesn't add anything that needs to
1299  // be deleted.
1300  StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1301}
1302
1303void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1304  while (Map) {
1305    // Advance the iteration before we invalidate memory.
1306    llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1307
1308    if (Dependent)
1309      delete static_cast<DependentStoredDeclsMap*>(Map);
1310    else
1311      delete Map;
1312
1313    Map = Next.getPointer();
1314    Dependent = Next.getInt();
1315  }
1316}
1317
1318DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1319                                                 DeclContext *Parent,
1320                                           const PartialDiagnostic &PDiag) {
1321  assert(Parent->isDependentContext()
1322         && "cannot iterate dependent diagnostics of non-dependent context");
1323  Parent = Parent->getPrimaryContext();
1324  if (!Parent->LookupPtr)
1325    Parent->CreateStoredDeclsMap(C);
1326
1327  DependentStoredDeclsMap *Map
1328    = static_cast<DependentStoredDeclsMap*>(Parent->LookupPtr);
1329
1330  // Allocate the copy of the PartialDiagnostic via the ASTContext's
1331  // BumpPtrAllocator, rather than the ASTContext itself.
1332  PartialDiagnostic::Storage *DiagStorage = 0;
1333  if (PDiag.hasStorage())
1334    DiagStorage = new (C) PartialDiagnostic::Storage;
1335
1336  DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
1337
1338  // TODO: Maybe we shouldn't reverse the order during insertion.
1339  DD->NextDiagnostic = Map->FirstDiagnostic;
1340  Map->FirstDiagnostic = DD;
1341
1342  return DD;
1343}
1344