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::operator new(std::size_t Size, const ASTContext &Context,
49                         unsigned ID, std::size_t Extra) {
50  // Allocate an extra 8 bytes worth of storage, which ensures that the
51  // resulting pointer will still be 8-byte aligned.
52  void *Start = Context.Allocate(Size + Extra + 8);
53  void *Result = (char*)Start + 8;
54
55  unsigned *PrefixPtr = (unsigned *)Result - 2;
56
57  // Zero out the first 4 bytes; this is used to store the owning module ID.
58  PrefixPtr[0] = 0;
59
60  // Store the global declaration ID in the second 4 bytes.
61  PrefixPtr[1] = ID;
62
63  return Result;
64}
65
66void *Decl::operator new(std::size_t Size, const ASTContext &Ctx,
67                         DeclContext *Parent, std::size_t Extra) {
68  assert(!Parent || &Parent->getParentASTContext() == &Ctx);
69  return ::operator new(Size + Extra, Ctx);
70}
71
72Module *Decl::getOwningModuleSlow() const {
73  assert(isFromASTFile() && "Not from AST file?");
74  return getASTContext().getExternalSource()->getModule(getOwningModuleID());
75}
76
77const char *Decl::getDeclKindName() const {
78  switch (DeclKind) {
79  default: llvm_unreachable("Declaration not in DeclNodes.inc!");
80#define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
81#define ABSTRACT_DECL(DECL)
82#include "clang/AST/DeclNodes.inc"
83  }
84}
85
86void Decl::setInvalidDecl(bool Invalid) {
87  InvalidDecl = Invalid;
88  assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition());
89  if (Invalid && !isa<ParmVarDecl>(this)) {
90    // Defensive maneuver for ill-formed code: we're likely not to make it to
91    // a point where we set the access specifier, so default it to "public"
92    // to avoid triggering asserts elsewhere in the front end.
93    setAccess(AS_public);
94  }
95}
96
97const char *DeclContext::getDeclKindName() const {
98  switch (DeclKind) {
99  default: llvm_unreachable("Declaration context not in DeclNodes.inc!");
100#define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
101#define ABSTRACT_DECL(DECL)
102#include "clang/AST/DeclNodes.inc"
103  }
104}
105
106bool Decl::StatisticsEnabled = false;
107void Decl::EnableStatistics() {
108  StatisticsEnabled = true;
109}
110
111void Decl::PrintStats() {
112  llvm::errs() << "\n*** Decl Stats:\n";
113
114  int totalDecls = 0;
115#define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
116#define ABSTRACT_DECL(DECL)
117#include "clang/AST/DeclNodes.inc"
118  llvm::errs() << "  " << totalDecls << " decls total.\n";
119
120  int totalBytes = 0;
121#define DECL(DERIVED, BASE)                                             \
122  if (n##DERIVED##s > 0) {                                              \
123    totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl));         \
124    llvm::errs() << "    " << n##DERIVED##s << " " #DERIVED " decls, "  \
125                 << sizeof(DERIVED##Decl) << " each ("                  \
126                 << n##DERIVED##s * sizeof(DERIVED##Decl)               \
127                 << " bytes)\n";                                        \
128  }
129#define ABSTRACT_DECL(DECL)
130#include "clang/AST/DeclNodes.inc"
131
132  llvm::errs() << "Total bytes = " << totalBytes << "\n";
133}
134
135void Decl::add(Kind k) {
136  switch (k) {
137#define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
138#define ABSTRACT_DECL(DECL)
139#include "clang/AST/DeclNodes.inc"
140  }
141}
142
143bool Decl::isTemplateParameterPack() const {
144  if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
145    return TTP->isParameterPack();
146  if (const NonTypeTemplateParmDecl *NTTP
147                                = dyn_cast<NonTypeTemplateParmDecl>(this))
148    return NTTP->isParameterPack();
149  if (const TemplateTemplateParmDecl *TTP
150                                    = dyn_cast<TemplateTemplateParmDecl>(this))
151    return TTP->isParameterPack();
152  return false;
153}
154
155bool Decl::isParameterPack() const {
156  if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this))
157    return Parm->isParameterPack();
158
159  return isTemplateParameterPack();
160}
161
162FunctionDecl *Decl::getAsFunction() {
163  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
164    return FD;
165  if (const FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(this))
166    return FTD->getTemplatedDecl();
167  return nullptr;
168}
169
170bool Decl::isTemplateDecl() const {
171  return isa<TemplateDecl>(this);
172}
173
174const DeclContext *Decl::getParentFunctionOrMethod() const {
175  for (const DeclContext *DC = getDeclContext();
176       DC && !DC->isTranslationUnit() && !DC->isNamespace();
177       DC = DC->getParent())
178    if (DC->isFunctionOrMethod())
179      return DC;
180
181  return nullptr;
182}
183
184
185//===----------------------------------------------------------------------===//
186// PrettyStackTraceDecl Implementation
187//===----------------------------------------------------------------------===//
188
189void PrettyStackTraceDecl::print(raw_ostream &OS) const {
190  SourceLocation TheLoc = Loc;
191  if (TheLoc.isInvalid() && TheDecl)
192    TheLoc = TheDecl->getLocation();
193
194  if (TheLoc.isValid()) {
195    TheLoc.print(OS, SM);
196    OS << ": ";
197  }
198
199  OS << Message;
200
201  if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
202    OS << " '";
203    DN->printQualifiedName(OS);
204    OS << '\'';
205  }
206  OS << '\n';
207}
208
209//===----------------------------------------------------------------------===//
210// Decl Implementation
211//===----------------------------------------------------------------------===//
212
213// Out-of-line virtual method providing a home for Decl.
214Decl::~Decl() { }
215
216void Decl::setDeclContext(DeclContext *DC) {
217  DeclCtx = DC;
218}
219
220void Decl::setLexicalDeclContext(DeclContext *DC) {
221  if (DC == getLexicalDeclContext())
222    return;
223
224  if (isInSemaDC()) {
225    setDeclContextsImpl(getDeclContext(), DC, getASTContext());
226  } else {
227    getMultipleDC()->LexicalDC = DC;
228  }
229}
230
231void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
232                               ASTContext &Ctx) {
233  if (SemaDC == LexicalDC) {
234    DeclCtx = SemaDC;
235  } else {
236    Decl::MultipleDC *MDC = new (Ctx) Decl::MultipleDC();
237    MDC->SemanticDC = SemaDC;
238    MDC->LexicalDC = LexicalDC;
239    DeclCtx = MDC;
240  }
241}
242
243bool Decl::isInAnonymousNamespace() const {
244  const DeclContext *DC = getDeclContext();
245  do {
246    if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
247      if (ND->isAnonymousNamespace())
248        return true;
249  } while ((DC = DC->getParent()));
250
251  return false;
252}
253
254bool Decl::isInStdNamespace() const {
255  return getDeclContext()->isStdNamespace();
256}
257
258TranslationUnitDecl *Decl::getTranslationUnitDecl() {
259  if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
260    return TUD;
261
262  DeclContext *DC = getDeclContext();
263  assert(DC && "This decl is not contained in a translation unit!");
264
265  while (!DC->isTranslationUnit()) {
266    DC = DC->getParent();
267    assert(DC && "This decl is not contained in a translation unit!");
268  }
269
270  return cast<TranslationUnitDecl>(DC);
271}
272
273ASTContext &Decl::getASTContext() const {
274  return getTranslationUnitDecl()->getASTContext();
275}
276
277ASTMutationListener *Decl::getASTMutationListener() const {
278  return getASTContext().getASTMutationListener();
279}
280
281unsigned Decl::getMaxAlignment() const {
282  if (!hasAttrs())
283    return 0;
284
285  unsigned Align = 0;
286  const AttrVec &V = getAttrs();
287  ASTContext &Ctx = getASTContext();
288  specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
289  for (; I != E; ++I)
290    Align = std::max(Align, I->getAlignment(Ctx));
291  return Align;
292}
293
294bool Decl::isUsed(bool CheckUsedAttr) const {
295  if (Used)
296    return true;
297
298  // Check for used attribute.
299  if (CheckUsedAttr && hasAttr<UsedAttr>())
300    return true;
301
302  return false;
303}
304
305void Decl::markUsed(ASTContext &C) {
306  if (Used)
307    return;
308
309  if (C.getASTMutationListener())
310    C.getASTMutationListener()->DeclarationMarkedUsed(this);
311
312  Used = true;
313}
314
315bool Decl::isReferenced() const {
316  if (Referenced)
317    return true;
318
319  // Check redeclarations.
320  for (auto I : redecls())
321    if (I->Referenced)
322      return true;
323
324  return false;
325}
326
327/// \brief Determine the availability of the given declaration based on
328/// the target platform.
329///
330/// When it returns an availability result other than \c AR_Available,
331/// if the \p Message parameter is non-NULL, it will be set to a
332/// string describing why the entity is unavailable.
333///
334/// FIXME: Make these strings localizable, since they end up in
335/// diagnostics.
336static AvailabilityResult CheckAvailability(ASTContext &Context,
337                                            const AvailabilityAttr *A,
338                                            std::string *Message) {
339  StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
340  StringRef PrettyPlatformName
341    = AvailabilityAttr::getPrettyPlatformName(TargetPlatform);
342  if (PrettyPlatformName.empty())
343    PrettyPlatformName = TargetPlatform;
344
345  VersionTuple TargetMinVersion = Context.getTargetInfo().getPlatformMinVersion();
346  if (TargetMinVersion.empty())
347    return AR_Available;
348
349  // Match the platform name.
350  if (A->getPlatform()->getName() != TargetPlatform)
351    return AR_Available;
352
353  std::string HintMessage;
354  if (!A->getMessage().empty()) {
355    HintMessage = " - ";
356    HintMessage += A->getMessage();
357  }
358
359  // Make sure that this declaration has not been marked 'unavailable'.
360  if (A->getUnavailable()) {
361    if (Message) {
362      Message->clear();
363      llvm::raw_string_ostream Out(*Message);
364      Out << "not available on " << PrettyPlatformName
365          << HintMessage;
366    }
367
368    return AR_Unavailable;
369  }
370
371  // Make sure that this declaration has already been introduced.
372  if (!A->getIntroduced().empty() &&
373      TargetMinVersion < A->getIntroduced()) {
374    if (Message) {
375      Message->clear();
376      llvm::raw_string_ostream Out(*Message);
377      Out << "introduced in " << PrettyPlatformName << ' '
378          << A->getIntroduced() << HintMessage;
379    }
380
381    return AR_NotYetIntroduced;
382  }
383
384  // Make sure that this declaration hasn't been obsoleted.
385  if (!A->getObsoleted().empty() && TargetMinVersion >= A->getObsoleted()) {
386    if (Message) {
387      Message->clear();
388      llvm::raw_string_ostream Out(*Message);
389      Out << "obsoleted in " << PrettyPlatformName << ' '
390          << A->getObsoleted() << HintMessage;
391    }
392
393    return AR_Unavailable;
394  }
395
396  // Make sure that this declaration hasn't been deprecated.
397  if (!A->getDeprecated().empty() && TargetMinVersion >= A->getDeprecated()) {
398    if (Message) {
399      Message->clear();
400      llvm::raw_string_ostream Out(*Message);
401      Out << "first deprecated in " << PrettyPlatformName << ' '
402          << A->getDeprecated() << HintMessage;
403    }
404
405    return AR_Deprecated;
406  }
407
408  return AR_Available;
409}
410
411AvailabilityResult Decl::getAvailability(std::string *Message) const {
412  AvailabilityResult Result = AR_Available;
413  std::string ResultMessage;
414
415  for (const auto *A : attrs()) {
416    if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
417      if (Result >= AR_Deprecated)
418        continue;
419
420      if (Message)
421        ResultMessage = Deprecated->getMessage();
422
423      Result = AR_Deprecated;
424      continue;
425    }
426
427    if (const auto *Unavailable = dyn_cast<UnavailableAttr>(A)) {
428      if (Message)
429        *Message = Unavailable->getMessage();
430      return AR_Unavailable;
431    }
432
433    if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
434      AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
435                                                Message);
436
437      if (AR == AR_Unavailable)
438        return AR_Unavailable;
439
440      if (AR > Result) {
441        Result = AR;
442        if (Message)
443          ResultMessage.swap(*Message);
444      }
445      continue;
446    }
447  }
448
449  if (Message)
450    Message->swap(ResultMessage);
451  return Result;
452}
453
454bool Decl::canBeWeakImported(bool &IsDefinition) const {
455  IsDefinition = false;
456
457  // Variables, if they aren't definitions.
458  if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
459    if (Var->isThisDeclarationADefinition()) {
460      IsDefinition = true;
461      return false;
462    }
463    return true;
464
465  // Functions, if they aren't definitions.
466  } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
467    if (FD->hasBody()) {
468      IsDefinition = true;
469      return false;
470    }
471    return true;
472
473  // Objective-C classes, if this is the non-fragile runtime.
474  } else if (isa<ObjCInterfaceDecl>(this) &&
475             getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
476    return true;
477
478  // Nothing else.
479  } else {
480    return false;
481  }
482}
483
484bool Decl::isWeakImported() const {
485  bool IsDefinition;
486  if (!canBeWeakImported(IsDefinition))
487    return false;
488
489  for (const auto *A : attrs()) {
490    if (isa<WeakImportAttr>(A))
491      return true;
492
493    if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
494      if (CheckAvailability(getASTContext(), Availability,
495                            nullptr) == AR_NotYetIntroduced)
496        return true;
497    }
498  }
499
500  return false;
501}
502
503unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
504  switch (DeclKind) {
505    case Function:
506    case CXXMethod:
507    case CXXConstructor:
508    case CXXDestructor:
509    case CXXConversion:
510    case EnumConstant:
511    case Var:
512    case ImplicitParam:
513    case ParmVar:
514    case NonTypeTemplateParm:
515    case ObjCMethod:
516    case ObjCProperty:
517    case MSProperty:
518      return IDNS_Ordinary;
519    case Label:
520      return IDNS_Label;
521    case IndirectField:
522      return IDNS_Ordinary | IDNS_Member;
523
524    case ObjCCompatibleAlias:
525    case ObjCInterface:
526      return IDNS_Ordinary | IDNS_Type;
527
528    case Typedef:
529    case TypeAlias:
530    case TypeAliasTemplate:
531    case UnresolvedUsingTypename:
532    case TemplateTypeParm:
533      return IDNS_Ordinary | IDNS_Type;
534
535    case UsingShadow:
536      return 0; // we'll actually overwrite this later
537
538    case UnresolvedUsingValue:
539      return IDNS_Ordinary | IDNS_Using;
540
541    case Using:
542      return IDNS_Using;
543
544    case ObjCProtocol:
545      return IDNS_ObjCProtocol;
546
547    case Field:
548    case ObjCAtDefsField:
549    case ObjCIvar:
550      return IDNS_Member;
551
552    case Record:
553    case CXXRecord:
554    case Enum:
555      return IDNS_Tag | IDNS_Type;
556
557    case Namespace:
558    case NamespaceAlias:
559      return IDNS_Namespace;
560
561    case FunctionTemplate:
562    case VarTemplate:
563      return IDNS_Ordinary;
564
565    case ClassTemplate:
566    case TemplateTemplateParm:
567      return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
568
569    // Never have names.
570    case Friend:
571    case FriendTemplate:
572    case AccessSpec:
573    case LinkageSpec:
574    case FileScopeAsm:
575    case StaticAssert:
576    case ObjCPropertyImpl:
577    case Block:
578    case Captured:
579    case TranslationUnit:
580
581    case UsingDirective:
582    case ClassTemplateSpecialization:
583    case ClassTemplatePartialSpecialization:
584    case ClassScopeFunctionSpecialization:
585    case VarTemplateSpecialization:
586    case VarTemplatePartialSpecialization:
587    case ObjCImplementation:
588    case ObjCCategory:
589    case ObjCCategoryImpl:
590    case Import:
591    case OMPThreadPrivate:
592    case Empty:
593      // Never looked up by name.
594      return 0;
595  }
596
597  llvm_unreachable("Invalid DeclKind!");
598}
599
600void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
601  assert(!HasAttrs && "Decl already contains attrs.");
602
603  AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
604  assert(AttrBlank.empty() && "HasAttrs was wrong?");
605
606  AttrBlank = attrs;
607  HasAttrs = true;
608}
609
610void Decl::dropAttrs() {
611  if (!HasAttrs) return;
612
613  HasAttrs = false;
614  getASTContext().eraseDeclAttrs(this);
615}
616
617const AttrVec &Decl::getAttrs() const {
618  assert(HasAttrs && "No attrs to get!");
619  return getASTContext().getDeclAttrs(this);
620}
621
622Decl *Decl::castFromDeclContext (const DeclContext *D) {
623  Decl::Kind DK = D->getDeclKind();
624  switch(DK) {
625#define DECL(NAME, BASE)
626#define DECL_CONTEXT(NAME) \
627    case Decl::NAME:       \
628      return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
629#define DECL_CONTEXT_BASE(NAME)
630#include "clang/AST/DeclNodes.inc"
631    default:
632#define DECL(NAME, BASE)
633#define DECL_CONTEXT_BASE(NAME)                  \
634      if (DK >= first##NAME && DK <= last##NAME) \
635        return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
636#include "clang/AST/DeclNodes.inc"
637      llvm_unreachable("a decl that inherits DeclContext isn't handled");
638  }
639}
640
641DeclContext *Decl::castToDeclContext(const Decl *D) {
642  Decl::Kind DK = D->getKind();
643  switch(DK) {
644#define DECL(NAME, BASE)
645#define DECL_CONTEXT(NAME) \
646    case Decl::NAME:       \
647      return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
648#define DECL_CONTEXT_BASE(NAME)
649#include "clang/AST/DeclNodes.inc"
650    default:
651#define DECL(NAME, BASE)
652#define DECL_CONTEXT_BASE(NAME)                                   \
653      if (DK >= first##NAME && DK <= last##NAME)                  \
654        return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
655#include "clang/AST/DeclNodes.inc"
656      llvm_unreachable("a decl that inherits DeclContext isn't handled");
657  }
658}
659
660SourceLocation Decl::getBodyRBrace() const {
661  // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
662  // FunctionDecl stores EndRangeLoc for this purpose.
663  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
664    const FunctionDecl *Definition;
665    if (FD->hasBody(Definition))
666      return Definition->getSourceRange().getEnd();
667    return SourceLocation();
668  }
669
670  if (Stmt *Body = getBody())
671    return Body->getSourceRange().getEnd();
672
673  return SourceLocation();
674}
675
676bool Decl::AccessDeclContextSanity() const {
677#ifndef NDEBUG
678  // Suppress this check if any of the following hold:
679  // 1. this is the translation unit (and thus has no parent)
680  // 2. this is a template parameter (and thus doesn't belong to its context)
681  // 3. this is a non-type template parameter
682  // 4. the context is not a record
683  // 5. it's invalid
684  // 6. it's a C++0x static_assert.
685  if (isa<TranslationUnitDecl>(this) ||
686      isa<TemplateTypeParmDecl>(this) ||
687      isa<NonTypeTemplateParmDecl>(this) ||
688      !isa<CXXRecordDecl>(getDeclContext()) ||
689      isInvalidDecl() ||
690      isa<StaticAssertDecl>(this) ||
691      // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
692      // as DeclContext (?).
693      isa<ParmVarDecl>(this) ||
694      // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
695      // AS_none as access specifier.
696      isa<CXXRecordDecl>(this) ||
697      isa<ClassScopeFunctionSpecializationDecl>(this))
698    return true;
699
700  assert(Access != AS_none &&
701         "Access specifier is AS_none inside a record decl");
702#endif
703  return true;
704}
705
706static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
707static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
708
709const FunctionType *Decl::getFunctionType(bool BlocksToo) const {
710  QualType Ty;
711  if (const ValueDecl *D = dyn_cast<ValueDecl>(this))
712    Ty = D->getType();
713  else if (const TypedefNameDecl *D = dyn_cast<TypedefNameDecl>(this))
714    Ty = D->getUnderlyingType();
715  else
716    return nullptr;
717
718  if (Ty->isFunctionPointerType())
719    Ty = Ty->getAs<PointerType>()->getPointeeType();
720  else if (BlocksToo && Ty->isBlockPointerType())
721    Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
722
723  return Ty->getAs<FunctionType>();
724}
725
726
727/// Starting at a given context (a Decl or DeclContext), look for a
728/// code context that is not a closure (a lambda, block, etc.).
729template <class T> static Decl *getNonClosureContext(T *D) {
730  if (getKind(D) == Decl::CXXMethod) {
731    CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
732    if (MD->getOverloadedOperator() == OO_Call &&
733        MD->getParent()->isLambda())
734      return getNonClosureContext(MD->getParent()->getParent());
735    return MD;
736  } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
737    return FD;
738  } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
739    return MD;
740  } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
741    return getNonClosureContext(BD->getParent());
742  } else if (CapturedDecl *CD = dyn_cast<CapturedDecl>(D)) {
743    return getNonClosureContext(CD->getParent());
744  } else {
745    return nullptr;
746  }
747}
748
749Decl *Decl::getNonClosureContext() {
750  return ::getNonClosureContext(this);
751}
752
753Decl *DeclContext::getNonClosureAncestor() {
754  return ::getNonClosureContext(this);
755}
756
757//===----------------------------------------------------------------------===//
758// DeclContext Implementation
759//===----------------------------------------------------------------------===//
760
761bool DeclContext::classof(const Decl *D) {
762  switch (D->getKind()) {
763#define DECL(NAME, BASE)
764#define DECL_CONTEXT(NAME) case Decl::NAME:
765#define DECL_CONTEXT_BASE(NAME)
766#include "clang/AST/DeclNodes.inc"
767      return true;
768    default:
769#define DECL(NAME, BASE)
770#define DECL_CONTEXT_BASE(NAME)                 \
771      if (D->getKind() >= Decl::first##NAME &&  \
772          D->getKind() <= Decl::last##NAME)     \
773        return true;
774#include "clang/AST/DeclNodes.inc"
775      return false;
776  }
777}
778
779DeclContext::~DeclContext() { }
780
781/// \brief Find the parent context of this context that will be
782/// used for unqualified name lookup.
783///
784/// Generally, the parent lookup context is the semantic context. However, for
785/// a friend function the parent lookup context is the lexical context, which
786/// is the class in which the friend is declared.
787DeclContext *DeclContext::getLookupParent() {
788  // FIXME: Find a better way to identify friends
789  if (isa<FunctionDecl>(this))
790    if (getParent()->getRedeclContext()->isFileContext() &&
791        getLexicalParent()->getRedeclContext()->isRecord())
792      return getLexicalParent();
793
794  return getParent();
795}
796
797bool DeclContext::isInlineNamespace() const {
798  return isNamespace() &&
799         cast<NamespaceDecl>(this)->isInline();
800}
801
802bool DeclContext::isStdNamespace() const {
803  if (!isNamespace())
804    return false;
805
806  const NamespaceDecl *ND = cast<NamespaceDecl>(this);
807  if (ND->isInline()) {
808    return ND->getParent()->isStdNamespace();
809  }
810
811  if (!getParent()->getRedeclContext()->isTranslationUnit())
812    return false;
813
814  const IdentifierInfo *II = ND->getIdentifier();
815  return II && II->isStr("std");
816}
817
818bool DeclContext::isDependentContext() const {
819  if (isFileContext())
820    return false;
821
822  if (isa<ClassTemplatePartialSpecializationDecl>(this))
823    return true;
824
825  if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
826    if (Record->getDescribedClassTemplate())
827      return true;
828
829    if (Record->isDependentLambda())
830      return true;
831  }
832
833  if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
834    if (Function->getDescribedFunctionTemplate())
835      return true;
836
837    // Friend function declarations are dependent if their *lexical*
838    // context is dependent.
839    if (cast<Decl>(this)->getFriendObjectKind())
840      return getLexicalParent()->isDependentContext();
841  }
842
843  return getParent() && getParent()->isDependentContext();
844}
845
846bool DeclContext::isTransparentContext() const {
847  if (DeclKind == Decl::Enum)
848    return !cast<EnumDecl>(this)->isScoped();
849  else if (DeclKind == Decl::LinkageSpec)
850    return true;
851
852  return false;
853}
854
855static bool isLinkageSpecContext(const DeclContext *DC,
856                                 LinkageSpecDecl::LanguageIDs ID) {
857  while (DC->getDeclKind() != Decl::TranslationUnit) {
858    if (DC->getDeclKind() == Decl::LinkageSpec)
859      return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
860    DC = DC->getLexicalParent();
861  }
862  return false;
863}
864
865bool DeclContext::isExternCContext() const {
866  return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_c);
867}
868
869bool DeclContext::isExternCXXContext() const {
870  return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_cxx);
871}
872
873bool DeclContext::Encloses(const DeclContext *DC) const {
874  if (getPrimaryContext() != this)
875    return getPrimaryContext()->Encloses(DC);
876
877  for (; DC; DC = DC->getParent())
878    if (DC->getPrimaryContext() == this)
879      return true;
880  return false;
881}
882
883DeclContext *DeclContext::getPrimaryContext() {
884  switch (DeclKind) {
885  case Decl::TranslationUnit:
886  case Decl::LinkageSpec:
887  case Decl::Block:
888  case Decl::Captured:
889    // There is only one DeclContext for these entities.
890    return this;
891
892  case Decl::Namespace:
893    // The original namespace is our primary context.
894    return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
895
896  case Decl::ObjCMethod:
897    return this;
898
899  case Decl::ObjCInterface:
900    if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
901      return Def;
902
903    return this;
904
905  case Decl::ObjCProtocol:
906    if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
907      return Def;
908
909    return this;
910
911  case Decl::ObjCCategory:
912    return this;
913
914  case Decl::ObjCImplementation:
915  case Decl::ObjCCategoryImpl:
916    return this;
917
918  default:
919    if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
920      // If this is a tag type that has a definition or is currently
921      // being defined, that definition is our primary context.
922      TagDecl *Tag = cast<TagDecl>(this);
923
924      if (TagDecl *Def = Tag->getDefinition())
925        return Def;
926
927      if (const TagType *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) {
928        // Note, TagType::getDecl returns the (partial) definition one exists.
929        TagDecl *PossiblePartialDef = TagTy->getDecl();
930        if (PossiblePartialDef->isBeingDefined())
931          return PossiblePartialDef;
932      } else {
933        assert(isa<InjectedClassNameType>(Tag->getTypeForDecl()));
934      }
935
936      return Tag;
937    }
938
939    assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
940          "Unknown DeclContext kind");
941    return this;
942  }
943}
944
945void
946DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
947  Contexts.clear();
948
949  if (DeclKind != Decl::Namespace) {
950    Contexts.push_back(this);
951    return;
952  }
953
954  NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
955  for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
956       N = N->getPreviousDecl())
957    Contexts.push_back(N);
958
959  std::reverse(Contexts.begin(), Contexts.end());
960}
961
962std::pair<Decl *, Decl *>
963DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
964                            bool FieldsAlreadyLoaded) {
965  // Build up a chain of declarations via the Decl::NextInContextAndBits field.
966  Decl *FirstNewDecl = nullptr;
967  Decl *PrevDecl = nullptr;
968  for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
969    if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
970      continue;
971
972    Decl *D = Decls[I];
973    if (PrevDecl)
974      PrevDecl->NextInContextAndBits.setPointer(D);
975    else
976      FirstNewDecl = D;
977
978    PrevDecl = D;
979  }
980
981  return std::make_pair(FirstNewDecl, PrevDecl);
982}
983
984/// \brief We have just acquired external visible storage, and we already have
985/// built a lookup map. For every name in the map, pull in the new names from
986/// the external storage.
987void DeclContext::reconcileExternalVisibleStorage() const {
988  assert(NeedToReconcileExternalVisibleStorage && LookupPtr.getPointer());
989  NeedToReconcileExternalVisibleStorage = false;
990
991  for (auto &Lookup : *LookupPtr.getPointer())
992    Lookup.second.setHasExternalDecls();
993}
994
995/// \brief Load the declarations within this lexical storage from an
996/// external source.
997void
998DeclContext::LoadLexicalDeclsFromExternalStorage() const {
999  ExternalASTSource *Source = getParentASTContext().getExternalSource();
1000  assert(hasExternalLexicalStorage() && Source && "No external storage?");
1001
1002  // Notify that we have a DeclContext that is initializing.
1003  ExternalASTSource::Deserializing ADeclContext(Source);
1004
1005  // Load the external declarations, if any.
1006  SmallVector<Decl*, 64> Decls;
1007  ExternalLexicalStorage = false;
1008  switch (Source->FindExternalLexicalDecls(this, Decls)) {
1009  case ELR_Success:
1010    break;
1011
1012  case ELR_Failure:
1013  case ELR_AlreadyLoaded:
1014    return;
1015  }
1016
1017  if (Decls.empty())
1018    return;
1019
1020  // We may have already loaded just the fields of this record, in which case
1021  // we need to ignore them.
1022  bool FieldsAlreadyLoaded = false;
1023  if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
1024    FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
1025
1026  // Splice the newly-read declarations into the beginning of the list
1027  // of declarations.
1028  Decl *ExternalFirst, *ExternalLast;
1029  std::tie(ExternalFirst, ExternalLast) =
1030      BuildDeclChain(Decls, FieldsAlreadyLoaded);
1031  ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
1032  FirstDecl = ExternalFirst;
1033  if (!LastDecl)
1034    LastDecl = ExternalLast;
1035}
1036
1037DeclContext::lookup_result
1038ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
1039                                                    DeclarationName Name) {
1040  ASTContext &Context = DC->getParentASTContext();
1041  StoredDeclsMap *Map;
1042  if (!(Map = DC->LookupPtr.getPointer()))
1043    Map = DC->CreateStoredDeclsMap(Context);
1044  if (DC->NeedToReconcileExternalVisibleStorage)
1045    DC->reconcileExternalVisibleStorage();
1046
1047  (*Map)[Name].removeExternalDecls();
1048
1049  return DeclContext::lookup_result();
1050}
1051
1052DeclContext::lookup_result
1053ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
1054                                                  DeclarationName Name,
1055                                                  ArrayRef<NamedDecl*> Decls) {
1056  ASTContext &Context = DC->getParentASTContext();
1057  StoredDeclsMap *Map;
1058  if (!(Map = DC->LookupPtr.getPointer()))
1059    Map = DC->CreateStoredDeclsMap(Context);
1060  if (DC->NeedToReconcileExternalVisibleStorage)
1061    DC->reconcileExternalVisibleStorage();
1062
1063  StoredDeclsList &List = (*Map)[Name];
1064
1065  // Clear out any old external visible declarations, to avoid quadratic
1066  // performance in the redeclaration checks below.
1067  List.removeExternalDecls();
1068
1069  if (!List.isNull()) {
1070    // We have both existing declarations and new declarations for this name.
1071    // Some of the declarations may simply replace existing ones. Handle those
1072    // first.
1073    llvm::SmallVector<unsigned, 8> Skip;
1074    for (unsigned I = 0, N = Decls.size(); I != N; ++I)
1075      if (List.HandleRedeclaration(Decls[I]))
1076        Skip.push_back(I);
1077    Skip.push_back(Decls.size());
1078
1079    // Add in any new declarations.
1080    unsigned SkipPos = 0;
1081    for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1082      if (I == Skip[SkipPos])
1083        ++SkipPos;
1084      else
1085        List.AddSubsequentDecl(Decls[I]);
1086    }
1087  } else {
1088    // Convert the array to a StoredDeclsList.
1089    for (ArrayRef<NamedDecl*>::iterator
1090           I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1091      if (List.isNull())
1092        List.setOnlyValue(*I);
1093      else
1094        List.AddSubsequentDecl(*I);
1095    }
1096  }
1097
1098  return List.getLookupResult();
1099}
1100
1101DeclContext::decl_iterator DeclContext::decls_begin() const {
1102  if (hasExternalLexicalStorage())
1103    LoadLexicalDeclsFromExternalStorage();
1104  return decl_iterator(FirstDecl);
1105}
1106
1107bool DeclContext::decls_empty() const {
1108  if (hasExternalLexicalStorage())
1109    LoadLexicalDeclsFromExternalStorage();
1110
1111  return !FirstDecl;
1112}
1113
1114bool DeclContext::containsDecl(Decl *D) const {
1115  return (D->getLexicalDeclContext() == this &&
1116          (D->NextInContextAndBits.getPointer() || D == LastDecl));
1117}
1118
1119void DeclContext::removeDecl(Decl *D) {
1120  assert(D->getLexicalDeclContext() == this &&
1121         "decl being removed from non-lexical context");
1122  assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
1123         "decl is not in decls list");
1124
1125  // Remove D from the decl chain.  This is O(n) but hopefully rare.
1126  if (D == FirstDecl) {
1127    if (D == LastDecl)
1128      FirstDecl = LastDecl = nullptr;
1129    else
1130      FirstDecl = D->NextInContextAndBits.getPointer();
1131  } else {
1132    for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
1133      assert(I && "decl not found in linked list");
1134      if (I->NextInContextAndBits.getPointer() == D) {
1135        I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
1136        if (D == LastDecl) LastDecl = I;
1137        break;
1138      }
1139    }
1140  }
1141
1142  // Mark that D is no longer in the decl chain.
1143  D->NextInContextAndBits.setPointer(nullptr);
1144
1145  // Remove D from the lookup table if necessary.
1146  if (isa<NamedDecl>(D)) {
1147    NamedDecl *ND = cast<NamedDecl>(D);
1148
1149    // Remove only decls that have a name
1150    if (!ND->getDeclName()) return;
1151
1152    StoredDeclsMap *Map = getPrimaryContext()->LookupPtr.getPointer();
1153    if (!Map) return;
1154
1155    StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1156    assert(Pos != Map->end() && "no lookup entry for decl");
1157    if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
1158      Pos->second.remove(ND);
1159  }
1160}
1161
1162void DeclContext::addHiddenDecl(Decl *D) {
1163  assert(D->getLexicalDeclContext() == this &&
1164         "Decl inserted into wrong lexical context");
1165  assert(!D->getNextDeclInContext() && D != LastDecl &&
1166         "Decl already inserted into a DeclContext");
1167
1168  if (FirstDecl) {
1169    LastDecl->NextInContextAndBits.setPointer(D);
1170    LastDecl = D;
1171  } else {
1172    FirstDecl = LastDecl = D;
1173  }
1174
1175  // Notify a C++ record declaration that we've added a member, so it can
1176  // update it's class-specific state.
1177  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1178    Record->addedMember(D);
1179
1180  // If this is a newly-created (not de-serialized) import declaration, wire
1181  // it in to the list of local import declarations.
1182  if (!D->isFromASTFile()) {
1183    if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
1184      D->getASTContext().addedLocalImportDecl(Import);
1185  }
1186}
1187
1188void DeclContext::addDecl(Decl *D) {
1189  addHiddenDecl(D);
1190
1191  if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1192    ND->getDeclContext()->getPrimaryContext()->
1193        makeDeclVisibleInContextWithFlags(ND, false, true);
1194}
1195
1196void DeclContext::addDeclInternal(Decl *D) {
1197  addHiddenDecl(D);
1198
1199  if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1200    ND->getDeclContext()->getPrimaryContext()->
1201        makeDeclVisibleInContextWithFlags(ND, true, true);
1202}
1203
1204/// shouldBeHidden - Determine whether a declaration which was declared
1205/// within its semantic context should be invisible to qualified name lookup.
1206static bool shouldBeHidden(NamedDecl *D) {
1207  // Skip unnamed declarations.
1208  if (!D->getDeclName())
1209    return true;
1210
1211  // Skip entities that can't be found by name lookup into a particular
1212  // context.
1213  if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1214      D->isTemplateParameter())
1215    return true;
1216
1217  // Skip template specializations.
1218  // FIXME: This feels like a hack. Should DeclarationName support
1219  // template-ids, or is there a better way to keep specializations
1220  // from being visible?
1221  if (isa<ClassTemplateSpecializationDecl>(D))
1222    return true;
1223  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1224    if (FD->isFunctionTemplateSpecialization())
1225      return true;
1226
1227  return false;
1228}
1229
1230/// buildLookup - Build the lookup data structure with all of the
1231/// declarations in this DeclContext (and any other contexts linked
1232/// to it or transparent contexts nested within it) and return it.
1233///
1234/// Note that the produced map may miss out declarations from an
1235/// external source. If it does, those entries will be marked with
1236/// the 'hasExternalDecls' flag.
1237StoredDeclsMap *DeclContext::buildLookup() {
1238  assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1239
1240  // FIXME: Should we keep going if hasExternalVisibleStorage?
1241  if (!LookupPtr.getInt())
1242    return LookupPtr.getPointer();
1243
1244  SmallVector<DeclContext *, 2> Contexts;
1245  collectAllContexts(Contexts);
1246  for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
1247    buildLookupImpl<&DeclContext::decls_begin,
1248                    &DeclContext::decls_end>(Contexts[I]);
1249
1250  // We no longer have any lazy decls.
1251  LookupPtr.setInt(false);
1252  return LookupPtr.getPointer();
1253}
1254
1255/// buildLookupImpl - Build part of the lookup data structure for the
1256/// declarations contained within DCtx, which will either be this
1257/// DeclContext, a DeclContext linked to it, or a transparent context
1258/// nested within it.
1259template<DeclContext::decl_iterator (DeclContext::*Begin)() const,
1260         DeclContext::decl_iterator (DeclContext::*End)() const>
1261void DeclContext::buildLookupImpl(DeclContext *DCtx) {
1262  for (decl_iterator I = (DCtx->*Begin)(), E = (DCtx->*End)();
1263       I != E; ++I) {
1264    Decl *D = *I;
1265
1266    // Insert this declaration into the lookup structure, but only if
1267    // it's semantically within its decl context. Any other decls which
1268    // should be found in this context are added eagerly.
1269    //
1270    // If it's from an AST file, don't add it now. It'll get handled by
1271    // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1272    // in C++, we do not track external visible decls for the TU, so in
1273    // that case we need to collect them all here.
1274    if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1275      if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1276          (!ND->isFromASTFile() ||
1277           (isTranslationUnit() &&
1278            !getParentASTContext().getLangOpts().CPlusPlus)))
1279        makeDeclVisibleInContextImpl(ND, false);
1280
1281    // If this declaration is itself a transparent declaration context
1282    // or inline namespace, add the members of this declaration of that
1283    // context (recursively).
1284    if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
1285      if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1286        buildLookupImpl<Begin, End>(InnerCtx);
1287  }
1288}
1289
1290DeclContext::lookup_result
1291DeclContext::lookup(DeclarationName Name) {
1292  assert(DeclKind != Decl::LinkageSpec &&
1293         "Should not perform lookups into linkage specs!");
1294
1295  DeclContext *PrimaryContext = getPrimaryContext();
1296  if (PrimaryContext != this)
1297    return PrimaryContext->lookup(Name);
1298
1299  if (hasExternalVisibleStorage()) {
1300    if (NeedToReconcileExternalVisibleStorage)
1301      reconcileExternalVisibleStorage();
1302
1303    StoredDeclsMap *Map = LookupPtr.getPointer();
1304
1305    if (LookupPtr.getInt())
1306      Map = buildLookup();
1307
1308    if (!Map)
1309      Map = CreateStoredDeclsMap(getParentASTContext());
1310
1311    // If we have a lookup result with no external decls, we are done.
1312    std::pair<StoredDeclsMap::iterator, bool> R =
1313        Map->insert(std::make_pair(Name, StoredDeclsList()));
1314    if (!R.second && !R.first->second.hasExternalDecls())
1315      return R.first->second.getLookupResult();
1316
1317    ExternalASTSource *Source = getParentASTContext().getExternalSource();
1318    if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) {
1319      if (StoredDeclsMap *Map = LookupPtr.getPointer()) {
1320        StoredDeclsMap::iterator I = Map->find(Name);
1321        if (I != Map->end())
1322          return I->second.getLookupResult();
1323      }
1324    }
1325
1326    return lookup_result(lookup_iterator(nullptr), lookup_iterator(nullptr));
1327  }
1328
1329  StoredDeclsMap *Map = LookupPtr.getPointer();
1330  if (LookupPtr.getInt())
1331    Map = buildLookup();
1332
1333  if (!Map)
1334    return lookup_result(lookup_iterator(nullptr), lookup_iterator(nullptr));
1335
1336  StoredDeclsMap::iterator I = Map->find(Name);
1337  if (I == Map->end())
1338    return lookup_result(lookup_iterator(nullptr), lookup_iterator(nullptr));
1339
1340  return I->second.getLookupResult();
1341}
1342
1343DeclContext::lookup_result
1344DeclContext::noload_lookup(DeclarationName Name) {
1345  assert(DeclKind != Decl::LinkageSpec &&
1346         "Should not perform lookups into linkage specs!");
1347  if (!hasExternalVisibleStorage())
1348    return lookup(Name);
1349
1350  DeclContext *PrimaryContext = getPrimaryContext();
1351  if (PrimaryContext != this)
1352    return PrimaryContext->noload_lookup(Name);
1353
1354  StoredDeclsMap *Map = LookupPtr.getPointer();
1355  if (LookupPtr.getInt()) {
1356    // Carefully build the lookup map, without deserializing anything.
1357    SmallVector<DeclContext *, 2> Contexts;
1358    collectAllContexts(Contexts);
1359    for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
1360      buildLookupImpl<&DeclContext::noload_decls_begin,
1361                      &DeclContext::noload_decls_end>(Contexts[I]);
1362
1363    // We no longer have any lazy decls.
1364    LookupPtr.setInt(false);
1365
1366    // There may now be names for which we have local decls but are
1367    // missing the external decls. FIXME: Just set the hasExternalDecls
1368    // flag on those names that have external decls.
1369    NeedToReconcileExternalVisibleStorage = true;
1370
1371    Map = LookupPtr.getPointer();
1372  }
1373
1374  if (!Map)
1375    return lookup_result(lookup_iterator(nullptr), lookup_iterator(nullptr));
1376
1377  StoredDeclsMap::iterator I = Map->find(Name);
1378  return I != Map->end() ? I->second.getLookupResult()
1379                         : lookup_result(lookup_iterator(nullptr),
1380                                         lookup_iterator(nullptr));
1381}
1382
1383void DeclContext::localUncachedLookup(DeclarationName Name,
1384                                      SmallVectorImpl<NamedDecl *> &Results) {
1385  Results.clear();
1386
1387  // If there's no external storage, just perform a normal lookup and copy
1388  // the results.
1389  if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
1390    lookup_result LookupResults = lookup(Name);
1391    Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
1392    return;
1393  }
1394
1395  // If we have a lookup table, check there first. Maybe we'll get lucky.
1396  if (Name && !LookupPtr.getInt()) {
1397    if (StoredDeclsMap *Map = LookupPtr.getPointer()) {
1398      StoredDeclsMap::iterator Pos = Map->find(Name);
1399      if (Pos != Map->end()) {
1400        Results.insert(Results.end(),
1401                       Pos->second.getLookupResult().begin(),
1402                       Pos->second.getLookupResult().end());
1403        return;
1404      }
1405    }
1406  }
1407
1408  // Slow case: grovel through the declarations in our chain looking for
1409  // matches.
1410  for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1411    if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1412      if (ND->getDeclName() == Name)
1413        Results.push_back(ND);
1414  }
1415}
1416
1417DeclContext *DeclContext::getRedeclContext() {
1418  DeclContext *Ctx = this;
1419  // Skip through transparent contexts.
1420  while (Ctx->isTransparentContext())
1421    Ctx = Ctx->getParent();
1422  return Ctx;
1423}
1424
1425DeclContext *DeclContext::getEnclosingNamespaceContext() {
1426  DeclContext *Ctx = this;
1427  // Skip through non-namespace, non-translation-unit contexts.
1428  while (!Ctx->isFileContext())
1429    Ctx = Ctx->getParent();
1430  return Ctx->getPrimaryContext();
1431}
1432
1433bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1434  // For non-file contexts, this is equivalent to Equals.
1435  if (!isFileContext())
1436    return O->Equals(this);
1437
1438  do {
1439    if (O->Equals(this))
1440      return true;
1441
1442    const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1443    if (!NS || !NS->isInline())
1444      break;
1445    O = NS->getParent();
1446  } while (O);
1447
1448  return false;
1449}
1450
1451void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1452  DeclContext *PrimaryDC = this->getPrimaryContext();
1453  DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1454  // If the decl is being added outside of its semantic decl context, we
1455  // need to ensure that we eagerly build the lookup information for it.
1456  PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
1457}
1458
1459void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1460                                                    bool Recoverable) {
1461  assert(this == getPrimaryContext() && "expected a primary DC");
1462
1463  // Skip declarations within functions.
1464  if (isFunctionOrMethod())
1465    return;
1466
1467  // Skip declarations which should be invisible to name lookup.
1468  if (shouldBeHidden(D))
1469    return;
1470
1471  // If we already have a lookup data structure, perform the insertion into
1472  // it. If we might have externally-stored decls with this name, look them
1473  // up and perform the insertion. If this decl was declared outside its
1474  // semantic context, buildLookup won't add it, so add it now.
1475  //
1476  // FIXME: As a performance hack, don't add such decls into the translation
1477  // unit unless we're in C++, since qualified lookup into the TU is never
1478  // performed.
1479  if (LookupPtr.getPointer() || hasExternalVisibleStorage() ||
1480      ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1481       (getParentASTContext().getLangOpts().CPlusPlus ||
1482        !isTranslationUnit()))) {
1483    // If we have lazily omitted any decls, they might have the same name as
1484    // the decl which we are adding, so build a full lookup table before adding
1485    // this decl.
1486    buildLookup();
1487    makeDeclVisibleInContextImpl(D, Internal);
1488  } else {
1489    LookupPtr.setInt(true);
1490  }
1491
1492  // If we are a transparent context or inline namespace, insert into our
1493  // parent context, too. This operation is recursive.
1494  if (isTransparentContext() || isInlineNamespace())
1495    getParent()->getPrimaryContext()->
1496        makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1497
1498  Decl *DCAsDecl = cast<Decl>(this);
1499  // Notify that a decl was made visible unless we are a Tag being defined.
1500  if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1501    if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1502      L->AddedVisibleDecl(this, D);
1503}
1504
1505void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1506  // Find or create the stored declaration map.
1507  StoredDeclsMap *Map = LookupPtr.getPointer();
1508  if (!Map) {
1509    ASTContext *C = &getParentASTContext();
1510    Map = CreateStoredDeclsMap(*C);
1511  }
1512
1513  // If there is an external AST source, load any declarations it knows about
1514  // with this declaration's name.
1515  // If the lookup table contains an entry about this name it means that we
1516  // have already checked the external source.
1517  if (!Internal)
1518    if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1519      if (hasExternalVisibleStorage() &&
1520          Map->find(D->getDeclName()) == Map->end())
1521        Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1522
1523  // Insert this declaration into the map.
1524  StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
1525
1526  if (Internal) {
1527    // If this is being added as part of loading an external declaration,
1528    // this may not be the only external declaration with this name.
1529    // In this case, we never try to replace an existing declaration; we'll
1530    // handle that when we finalize the list of declarations for this name.
1531    DeclNameEntries.setHasExternalDecls();
1532    DeclNameEntries.AddSubsequentDecl(D);
1533    return;
1534  }
1535
1536  else if (DeclNameEntries.isNull()) {
1537    DeclNameEntries.setOnlyValue(D);
1538    return;
1539  }
1540
1541  if (DeclNameEntries.HandleRedeclaration(D)) {
1542    // This declaration has replaced an existing one for which
1543    // declarationReplaces returns true.
1544    return;
1545  }
1546
1547  // Put this declaration into the appropriate slot.
1548  DeclNameEntries.AddSubsequentDecl(D);
1549}
1550
1551/// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1552/// this context.
1553DeclContext::udir_range DeclContext::using_directives() const {
1554  // FIXME: Use something more efficient than normal lookup for using
1555  // directives. In C++, using directives are looked up more than anything else.
1556  lookup_const_result Result = lookup(UsingDirectiveDecl::getName());
1557  return udir_range(
1558      reinterpret_cast<UsingDirectiveDecl *const *>(Result.begin()),
1559      reinterpret_cast<UsingDirectiveDecl *const *>(Result.end()));
1560}
1561
1562//===----------------------------------------------------------------------===//
1563// Creation and Destruction of StoredDeclsMaps.                               //
1564//===----------------------------------------------------------------------===//
1565
1566StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1567  assert(!LookupPtr.getPointer() && "context already has a decls map");
1568  assert(getPrimaryContext() == this &&
1569         "creating decls map on non-primary context");
1570
1571  StoredDeclsMap *M;
1572  bool Dependent = isDependentContext();
1573  if (Dependent)
1574    M = new DependentStoredDeclsMap();
1575  else
1576    M = new StoredDeclsMap();
1577  M->Previous = C.LastSDM;
1578  C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1579  LookupPtr.setPointer(M);
1580  return M;
1581}
1582
1583void ASTContext::ReleaseDeclContextMaps() {
1584  // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1585  // pointer because the subclass doesn't add anything that needs to
1586  // be deleted.
1587  StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1588}
1589
1590void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1591  while (Map) {
1592    // Advance the iteration before we invalidate memory.
1593    llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1594
1595    if (Dependent)
1596      delete static_cast<DependentStoredDeclsMap*>(Map);
1597    else
1598      delete Map;
1599
1600    Map = Next.getPointer();
1601    Dependent = Next.getInt();
1602  }
1603}
1604
1605DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1606                                                 DeclContext *Parent,
1607                                           const PartialDiagnostic &PDiag) {
1608  assert(Parent->isDependentContext()
1609         && "cannot iterate dependent diagnostics of non-dependent context");
1610  Parent = Parent->getPrimaryContext();
1611  if (!Parent->LookupPtr.getPointer())
1612    Parent->CreateStoredDeclsMap(C);
1613
1614  DependentStoredDeclsMap *Map
1615    = static_cast<DependentStoredDeclsMap*>(Parent->LookupPtr.getPointer());
1616
1617  // Allocate the copy of the PartialDiagnostic via the ASTContext's
1618  // BumpPtrAllocator, rather than the ASTContext itself.
1619  PartialDiagnostic::Storage *DiagStorage = nullptr;
1620  if (PDiag.hasStorage())
1621    DiagStorage = new (C) PartialDiagnostic::Storage;
1622
1623  DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
1624
1625  // TODO: Maybe we shouldn't reverse the order during insertion.
1626  DD->NextDiagnostic = Map->FirstDiagnostic;
1627  Map->FirstDiagnostic = DD;
1628
1629  return DD;
1630}
1631