1//===- DeclBase.cpp - Declaration AST Node Implementation -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Decl and DeclContext classes.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/DeclBase.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/ASTLambda.h"
16#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/Attr.h"
18#include "clang/AST/AttrIterator.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclContextInternals.h"
22#include "clang/AST/DeclFriend.h"
23#include "clang/AST/DeclObjC.h"
24#include "clang/AST/DeclOpenMP.h"
25#include "clang/AST/DeclTemplate.h"
26#include "clang/AST/DependentDiagnostic.h"
27#include "clang/AST/ExternalASTSource.h"
28#include "clang/AST/Stmt.h"
29#include "clang/AST/Type.h"
30#include "clang/Basic/IdentifierTable.h"
31#include "clang/Basic/LLVM.h"
32#include "clang/Basic/LangOptions.h"
33#include "clang/Basic/ObjCRuntime.h"
34#include "clang/Basic/PartialDiagnostic.h"
35#include "clang/Basic/SourceLocation.h"
36#include "clang/Basic/TargetInfo.h"
37#include "llvm/ADT/ArrayRef.h"
38#include "llvm/ADT/PointerIntPair.h"
39#include "llvm/ADT/SmallVector.h"
40#include "llvm/ADT/StringRef.h"
41#include "llvm/Support/Casting.h"
42#include "llvm/Support/ErrorHandling.h"
43#include "llvm/Support/MathExtras.h"
44#include "llvm/Support/VersionTuple.h"
45#include "llvm/Support/raw_ostream.h"
46#include <algorithm>
47#include <cassert>
48#include <cstddef>
49#include <string>
50#include <tuple>
51#include <utility>
52
53using namespace clang;
54
55//===----------------------------------------------------------------------===//
56//  Statistics
57//===----------------------------------------------------------------------===//
58
59#define DECL(DERIVED, BASE) static int n##DERIVED##s = 0;
60#define ABSTRACT_DECL(DECL)
61#include "clang/AST/DeclNodes.inc"
62
63void Decl::updateOutOfDate(IdentifierInfo &II) const {
64  getASTContext().getExternalSource()->updateOutOfDateIdentifier(II);
65}
66
67#define DECL(DERIVED, BASE)                                                    \
68  static_assert(alignof(Decl) >= alignof(DERIVED##Decl),                       \
69                "Alignment sufficient after objects prepended to " #DERIVED);
70#define ABSTRACT_DECL(DECL)
71#include "clang/AST/DeclNodes.inc"
72
73void *Decl::operator new(std::size_t Size, const ASTContext &Context,
74                         unsigned ID, std::size_t Extra) {
75  // Allocate an extra 8 bytes worth of storage, which ensures that the
76  // resulting pointer will still be 8-byte aligned.
77  static_assert(sizeof(unsigned) * 2 >= alignof(Decl),
78                "Decl won't be misaligned");
79  void *Start = Context.Allocate(Size + Extra + 8);
80  void *Result = (char*)Start + 8;
81
82  unsigned *PrefixPtr = (unsigned *)Result - 2;
83
84  // Zero out the first 4 bytes; this is used to store the owning module ID.
85  PrefixPtr[0] = 0;
86
87  // Store the global declaration ID in the second 4 bytes.
88  PrefixPtr[1] = ID;
89
90  return Result;
91}
92
93void *Decl::operator new(std::size_t Size, const ASTContext &Ctx,
94                         DeclContext *Parent, std::size_t Extra) {
95  assert(!Parent || &Parent->getParentASTContext() == &Ctx);
96  // With local visibility enabled, we track the owning module even for local
97  // declarations. We create the TU decl early and may not yet know what the
98  // LangOpts are, so conservatively allocate the storage.
99  if (Ctx.getLangOpts().trackLocalOwningModule() || !Parent) {
100    // Ensure required alignment of the resulting object by adding extra
101    // padding at the start if required.
102    size_t ExtraAlign =
103        llvm::offsetToAlignment(sizeof(Module *), llvm::Align(alignof(Decl)));
104    auto *Buffer = reinterpret_cast<char *>(
105        ::operator new(ExtraAlign + sizeof(Module *) + Size + Extra, Ctx));
106    Buffer += ExtraAlign;
107    auto *ParentModule =
108        Parent ? cast<Decl>(Parent)->getOwningModule() : nullptr;
109    return new (Buffer) Module*(ParentModule) + 1;
110  }
111  return ::operator new(Size + Extra, Ctx);
112}
113
114Module *Decl::getOwningModuleSlow() const {
115  assert(isFromASTFile() && "Not from AST file?");
116  return getASTContext().getExternalSource()->getModule(getOwningModuleID());
117}
118
119bool Decl::hasLocalOwningModuleStorage() const {
120  return getASTContext().getLangOpts().trackLocalOwningModule();
121}
122
123const char *Decl::getDeclKindName() const {
124  switch (DeclKind) {
125  default: llvm_unreachable("Declaration not in DeclNodes.inc!");
126#define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
127#define ABSTRACT_DECL(DECL)
128#include "clang/AST/DeclNodes.inc"
129  }
130}
131
132void Decl::setInvalidDecl(bool Invalid) {
133  InvalidDecl = Invalid;
134  assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition());
135  if (!Invalid) {
136    return;
137  }
138
139  if (!isa<ParmVarDecl>(this)) {
140    // Defensive maneuver for ill-formed code: we're likely not to make it to
141    // a point where we set the access specifier, so default it to "public"
142    // to avoid triggering asserts elsewhere in the front end.
143    setAccess(AS_public);
144  }
145
146  // Marking a DecompositionDecl as invalid implies all the child BindingDecl's
147  // are invalid too.
148  if (auto *DD = dyn_cast<DecompositionDecl>(this)) {
149    for (auto *Binding : DD->bindings()) {
150      Binding->setInvalidDecl();
151    }
152  }
153}
154
155const char *DeclContext::getDeclKindName() const {
156  switch (getDeclKind()) {
157#define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
158#define ABSTRACT_DECL(DECL)
159#include "clang/AST/DeclNodes.inc"
160  }
161  llvm_unreachable("Declaration context not in DeclNodes.inc!");
162}
163
164bool Decl::StatisticsEnabled = false;
165void Decl::EnableStatistics() {
166  StatisticsEnabled = true;
167}
168
169void Decl::PrintStats() {
170  llvm::errs() << "\n*** Decl Stats:\n";
171
172  int totalDecls = 0;
173#define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
174#define ABSTRACT_DECL(DECL)
175#include "clang/AST/DeclNodes.inc"
176  llvm::errs() << "  " << totalDecls << " decls total.\n";
177
178  int totalBytes = 0;
179#define DECL(DERIVED, BASE)                                             \
180  if (n##DERIVED##s > 0) {                                              \
181    totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl));         \
182    llvm::errs() << "    " << n##DERIVED##s << " " #DERIVED " decls, "  \
183                 << sizeof(DERIVED##Decl) << " each ("                  \
184                 << n##DERIVED##s * sizeof(DERIVED##Decl)               \
185                 << " bytes)\n";                                        \
186  }
187#define ABSTRACT_DECL(DECL)
188#include "clang/AST/DeclNodes.inc"
189
190  llvm::errs() << "Total bytes = " << totalBytes << "\n";
191}
192
193void Decl::add(Kind k) {
194  switch (k) {
195#define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
196#define ABSTRACT_DECL(DECL)
197#include "clang/AST/DeclNodes.inc"
198  }
199}
200
201bool Decl::isTemplateParameterPack() const {
202  if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(this))
203    return TTP->isParameterPack();
204  if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(this))
205    return NTTP->isParameterPack();
206  if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(this))
207    return TTP->isParameterPack();
208  return false;
209}
210
211bool Decl::isParameterPack() const {
212  if (const auto *Var = dyn_cast<VarDecl>(this))
213    return Var->isParameterPack();
214
215  return isTemplateParameterPack();
216}
217
218FunctionDecl *Decl::getAsFunction() {
219  if (auto *FD = dyn_cast<FunctionDecl>(this))
220    return FD;
221  if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(this))
222    return FTD->getTemplatedDecl();
223  return nullptr;
224}
225
226bool Decl::isTemplateDecl() const {
227  return isa<TemplateDecl>(this);
228}
229
230TemplateDecl *Decl::getDescribedTemplate() const {
231  if (auto *FD = dyn_cast<FunctionDecl>(this))
232    return FD->getDescribedFunctionTemplate();
233  if (auto *RD = dyn_cast<CXXRecordDecl>(this))
234    return RD->getDescribedClassTemplate();
235  if (auto *VD = dyn_cast<VarDecl>(this))
236    return VD->getDescribedVarTemplate();
237  if (auto *AD = dyn_cast<TypeAliasDecl>(this))
238    return AD->getDescribedAliasTemplate();
239
240  return nullptr;
241}
242
243const TemplateParameterList *Decl::getDescribedTemplateParams() const {
244  if (auto *TD = getDescribedTemplate())
245    return TD->getTemplateParameters();
246  if (auto *CTPSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(this))
247    return CTPSD->getTemplateParameters();
248  if (auto *VTPSD = dyn_cast<VarTemplatePartialSpecializationDecl>(this))
249    return VTPSD->getTemplateParameters();
250  return nullptr;
251}
252
253bool Decl::isTemplated() const {
254  // A declaration is templated if it is a template or a template pattern, or
255  // is within (lexcially for a friend, semantically otherwise) a dependent
256  // context.
257  // FIXME: Should local extern declarations be treated like friends?
258  if (auto *AsDC = dyn_cast<DeclContext>(this))
259    return AsDC->isDependentContext();
260  auto *DC = getFriendObjectKind() ? getLexicalDeclContext() : getDeclContext();
261  return DC->isDependentContext() || isTemplateDecl() ||
262         getDescribedTemplateParams();
263}
264
265unsigned Decl::getTemplateDepth() const {
266  if (auto *DC = dyn_cast<DeclContext>(this))
267    if (DC->isFileContext())
268      return 0;
269
270  if (auto *TPL = getDescribedTemplateParams())
271    return TPL->getDepth() + 1;
272
273  // If this is a dependent lambda, there might be an enclosing variable
274  // template. In this case, the next step is not the parent DeclContext (or
275  // even a DeclContext at all).
276  auto *RD = dyn_cast<CXXRecordDecl>(this);
277  if (RD && RD->isDependentLambda())
278    if (Decl *Context = RD->getLambdaContextDecl())
279      return Context->getTemplateDepth();
280
281  const DeclContext *DC =
282      getFriendObjectKind() ? getLexicalDeclContext() : getDeclContext();
283  return cast<Decl>(DC)->getTemplateDepth();
284}
285
286const DeclContext *Decl::getParentFunctionOrMethod() const {
287  for (const DeclContext *DC = getDeclContext();
288       DC && !DC->isTranslationUnit() && !DC->isNamespace();
289       DC = DC->getParent())
290    if (DC->isFunctionOrMethod())
291      return DC;
292
293  return nullptr;
294}
295
296//===----------------------------------------------------------------------===//
297// PrettyStackTraceDecl Implementation
298//===----------------------------------------------------------------------===//
299
300void PrettyStackTraceDecl::print(raw_ostream &OS) const {
301  SourceLocation TheLoc = Loc;
302  if (TheLoc.isInvalid() && TheDecl)
303    TheLoc = TheDecl->getLocation();
304
305  if (TheLoc.isValid()) {
306    TheLoc.print(OS, SM);
307    OS << ": ";
308  }
309
310  OS << Message;
311
312  if (const auto *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
313    OS << " '";
314    DN->printQualifiedName(OS);
315    OS << '\'';
316  }
317  OS << '\n';
318}
319
320//===----------------------------------------------------------------------===//
321// Decl Implementation
322//===----------------------------------------------------------------------===//
323
324// Out-of-line virtual method providing a home for Decl.
325Decl::~Decl() = default;
326
327void Decl::setDeclContext(DeclContext *DC) {
328  DeclCtx = DC;
329}
330
331void Decl::setLexicalDeclContext(DeclContext *DC) {
332  if (DC == getLexicalDeclContext())
333    return;
334
335  if (isInSemaDC()) {
336    setDeclContextsImpl(getDeclContext(), DC, getASTContext());
337  } else {
338    getMultipleDC()->LexicalDC = DC;
339  }
340
341  // FIXME: We shouldn't be changing the lexical context of declarations
342  // imported from AST files.
343  if (!isFromASTFile()) {
344    setModuleOwnershipKind(getModuleOwnershipKindForChildOf(DC));
345    if (hasOwningModule())
346      setLocalOwningModule(cast<Decl>(DC)->getOwningModule());
347  }
348
349  assert(
350      (getModuleOwnershipKind() != ModuleOwnershipKind::VisibleWhenImported ||
351       getOwningModule()) &&
352      "hidden declaration has no owning module");
353}
354
355void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
356                               ASTContext &Ctx) {
357  if (SemaDC == LexicalDC) {
358    DeclCtx = SemaDC;
359  } else {
360    auto *MDC = new (Ctx) Decl::MultipleDC();
361    MDC->SemanticDC = SemaDC;
362    MDC->LexicalDC = LexicalDC;
363    DeclCtx = MDC;
364  }
365}
366
367bool Decl::isInLocalScopeForInstantiation() const {
368  const DeclContext *LDC = getLexicalDeclContext();
369  if (!LDC->isDependentContext())
370    return false;
371  while (true) {
372    if (LDC->isFunctionOrMethod())
373      return true;
374    if (!isa<TagDecl>(LDC))
375      return false;
376    if (const auto *CRD = dyn_cast<CXXRecordDecl>(LDC))
377      if (CRD->isLambda())
378        return true;
379    LDC = LDC->getLexicalParent();
380  }
381  return false;
382}
383
384bool Decl::isInAnonymousNamespace() const {
385  for (const DeclContext *DC = getDeclContext(); DC; DC = DC->getParent()) {
386    if (const auto *ND = dyn_cast<NamespaceDecl>(DC))
387      if (ND->isAnonymousNamespace())
388        return true;
389  }
390
391  return false;
392}
393
394bool Decl::isInStdNamespace() const {
395  const DeclContext *DC = getDeclContext();
396  return DC && DC->isStdNamespace();
397}
398
399TranslationUnitDecl *Decl::getTranslationUnitDecl() {
400  if (auto *TUD = dyn_cast<TranslationUnitDecl>(this))
401    return TUD;
402
403  DeclContext *DC = getDeclContext();
404  assert(DC && "This decl is not contained in a translation unit!");
405
406  while (!DC->isTranslationUnit()) {
407    DC = DC->getParent();
408    assert(DC && "This decl is not contained in a translation unit!");
409  }
410
411  return cast<TranslationUnitDecl>(DC);
412}
413
414ASTContext &Decl::getASTContext() const {
415  return getTranslationUnitDecl()->getASTContext();
416}
417
418/// Helper to get the language options from the ASTContext.
419/// Defined out of line to avoid depending on ASTContext.h.
420const LangOptions &Decl::getLangOpts() const {
421  return getASTContext().getLangOpts();
422}
423
424ASTMutationListener *Decl::getASTMutationListener() const {
425  return getASTContext().getASTMutationListener();
426}
427
428unsigned Decl::getMaxAlignment() const {
429  if (!hasAttrs())
430    return 0;
431
432  unsigned Align = 0;
433  const AttrVec &V = getAttrs();
434  ASTContext &Ctx = getASTContext();
435  specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
436  for (; I != E; ++I) {
437    if (!I->isAlignmentErrorDependent())
438      Align = std::max(Align, I->getAlignment(Ctx));
439  }
440  return Align;
441}
442
443bool Decl::isUsed(bool CheckUsedAttr) const {
444  const Decl *CanonD = getCanonicalDecl();
445  if (CanonD->Used)
446    return true;
447
448  // Check for used attribute.
449  // Ask the most recent decl, since attributes accumulate in the redecl chain.
450  if (CheckUsedAttr && getMostRecentDecl()->hasAttr<UsedAttr>())
451    return true;
452
453  // The information may have not been deserialized yet. Force deserialization
454  // to complete the needed information.
455  return getMostRecentDecl()->getCanonicalDecl()->Used;
456}
457
458void Decl::markUsed(ASTContext &C) {
459  if (isUsed(false))
460    return;
461
462  if (C.getASTMutationListener())
463    C.getASTMutationListener()->DeclarationMarkedUsed(this);
464
465  setIsUsed();
466}
467
468bool Decl::isReferenced() const {
469  if (Referenced)
470    return true;
471
472  // Check redeclarations.
473  for (const auto *I : redecls())
474    if (I->Referenced)
475      return true;
476
477  return false;
478}
479
480ExternalSourceSymbolAttr *Decl::getExternalSourceSymbolAttr() const {
481  const Decl *Definition = nullptr;
482  if (auto *ID = dyn_cast<ObjCInterfaceDecl>(this)) {
483    Definition = ID->getDefinition();
484  } else if (auto *PD = dyn_cast<ObjCProtocolDecl>(this)) {
485    Definition = PD->getDefinition();
486  } else if (auto *TD = dyn_cast<TagDecl>(this)) {
487    Definition = TD->getDefinition();
488  }
489  if (!Definition)
490    Definition = this;
491
492  if (auto *attr = Definition->getAttr<ExternalSourceSymbolAttr>())
493    return attr;
494  if (auto *dcd = dyn_cast<Decl>(getDeclContext())) {
495    return dcd->getAttr<ExternalSourceSymbolAttr>();
496  }
497
498  return nullptr;
499}
500
501bool Decl::hasDefiningAttr() const {
502  return hasAttr<AliasAttr>() || hasAttr<IFuncAttr>() ||
503         hasAttr<LoaderUninitializedAttr>();
504}
505
506const Attr *Decl::getDefiningAttr() const {
507  if (auto *AA = getAttr<AliasAttr>())
508    return AA;
509  if (auto *IFA = getAttr<IFuncAttr>())
510    return IFA;
511  if (auto *NZA = getAttr<LoaderUninitializedAttr>())
512    return NZA;
513  return nullptr;
514}
515
516static StringRef getRealizedPlatform(const AvailabilityAttr *A,
517                                     const ASTContext &Context) {
518  // Check if this is an App Extension "platform", and if so chop off
519  // the suffix for matching with the actual platform.
520  StringRef RealizedPlatform = A->getPlatform()->getName();
521  if (!Context.getLangOpts().AppExt)
522    return RealizedPlatform;
523  size_t suffix = RealizedPlatform.rfind("_app_extension");
524  if (suffix != StringRef::npos)
525    return RealizedPlatform.slice(0, suffix);
526  return RealizedPlatform;
527}
528
529/// Determine the availability of the given declaration based on
530/// the target platform.
531///
532/// When it returns an availability result other than \c AR_Available,
533/// if the \p Message parameter is non-NULL, it will be set to a
534/// string describing why the entity is unavailable.
535///
536/// FIXME: Make these strings localizable, since they end up in
537/// diagnostics.
538static AvailabilityResult CheckAvailability(ASTContext &Context,
539                                            const AvailabilityAttr *A,
540                                            std::string *Message,
541                                            VersionTuple EnclosingVersion) {
542  if (EnclosingVersion.empty())
543    EnclosingVersion = Context.getTargetInfo().getPlatformMinVersion();
544
545  if (EnclosingVersion.empty())
546    return AR_Available;
547
548  StringRef ActualPlatform = A->getPlatform()->getName();
549  StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
550
551  // Match the platform name.
552  if (getRealizedPlatform(A, Context) != TargetPlatform)
553    return AR_Available;
554
555  StringRef PrettyPlatformName
556    = AvailabilityAttr::getPrettyPlatformName(ActualPlatform);
557
558  if (PrettyPlatformName.empty())
559    PrettyPlatformName = ActualPlatform;
560
561  std::string HintMessage;
562  if (!A->getMessage().empty()) {
563    HintMessage = " - ";
564    HintMessage += A->getMessage();
565  }
566
567  // Make sure that this declaration has not been marked 'unavailable'.
568  if (A->getUnavailable()) {
569    if (Message) {
570      Message->clear();
571      llvm::raw_string_ostream Out(*Message);
572      Out << "not available on " << PrettyPlatformName
573          << HintMessage;
574    }
575
576    return AR_Unavailable;
577  }
578
579  // Make sure that this declaration has already been introduced.
580  if (!A->getIntroduced().empty() &&
581      EnclosingVersion < A->getIntroduced()) {
582    if (Message) {
583      Message->clear();
584      llvm::raw_string_ostream Out(*Message);
585      VersionTuple VTI(A->getIntroduced());
586      Out << "introduced in " << PrettyPlatformName << ' '
587          << VTI << HintMessage;
588    }
589
590    return A->getStrict() ? AR_Unavailable : AR_NotYetIntroduced;
591  }
592
593  // Make sure that this declaration hasn't been obsoleted.
594  if (!A->getObsoleted().empty() && EnclosingVersion >= A->getObsoleted()) {
595    if (Message) {
596      Message->clear();
597      llvm::raw_string_ostream Out(*Message);
598      VersionTuple VTO(A->getObsoleted());
599      Out << "obsoleted in " << PrettyPlatformName << ' '
600          << VTO << HintMessage;
601    }
602
603    return AR_Unavailable;
604  }
605
606  // Make sure that this declaration hasn't been deprecated.
607  if (!A->getDeprecated().empty() && EnclosingVersion >= A->getDeprecated()) {
608    if (Message) {
609      Message->clear();
610      llvm::raw_string_ostream Out(*Message);
611      VersionTuple VTD(A->getDeprecated());
612      Out << "first deprecated in " << PrettyPlatformName << ' '
613          << VTD << HintMessage;
614    }
615
616    return AR_Deprecated;
617  }
618
619  return AR_Available;
620}
621
622AvailabilityResult Decl::getAvailability(std::string *Message,
623                                         VersionTuple EnclosingVersion,
624                                         StringRef *RealizedPlatform) const {
625  if (auto *FTD = dyn_cast<FunctionTemplateDecl>(this))
626    return FTD->getTemplatedDecl()->getAvailability(Message, EnclosingVersion,
627                                                    RealizedPlatform);
628
629  AvailabilityResult Result = AR_Available;
630  std::string ResultMessage;
631
632  for (const auto *A : attrs()) {
633    if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
634      if (Result >= AR_Deprecated)
635        continue;
636
637      if (Message)
638        ResultMessage = std::string(Deprecated->getMessage());
639
640      Result = AR_Deprecated;
641      continue;
642    }
643
644    if (const auto *Unavailable = dyn_cast<UnavailableAttr>(A)) {
645      if (Message)
646        *Message = std::string(Unavailable->getMessage());
647      return AR_Unavailable;
648    }
649
650    if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
651      AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
652                                                Message, EnclosingVersion);
653
654      if (AR == AR_Unavailable) {
655        if (RealizedPlatform)
656          *RealizedPlatform = Availability->getPlatform()->getName();
657        return AR_Unavailable;
658      }
659
660      if (AR > Result) {
661        Result = AR;
662        if (Message)
663          ResultMessage.swap(*Message);
664      }
665      continue;
666    }
667  }
668
669  if (Message)
670    Message->swap(ResultMessage);
671  return Result;
672}
673
674VersionTuple Decl::getVersionIntroduced() const {
675  const ASTContext &Context = getASTContext();
676  StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
677  for (const auto *A : attrs()) {
678    if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
679      if (getRealizedPlatform(Availability, Context) != TargetPlatform)
680        continue;
681      if (!Availability->getIntroduced().empty())
682        return Availability->getIntroduced();
683    }
684  }
685  return {};
686}
687
688bool Decl::canBeWeakImported(bool &IsDefinition) const {
689  IsDefinition = false;
690
691  // Variables, if they aren't definitions.
692  if (const auto *Var = dyn_cast<VarDecl>(this)) {
693    if (Var->isThisDeclarationADefinition()) {
694      IsDefinition = true;
695      return false;
696    }
697    return true;
698  }
699  // Functions, if they aren't definitions.
700  if (const auto *FD = dyn_cast<FunctionDecl>(this)) {
701    if (FD->hasBody()) {
702      IsDefinition = true;
703      return false;
704    }
705    return true;
706
707  }
708  // Objective-C classes, if this is the non-fragile runtime.
709  if (isa<ObjCInterfaceDecl>(this) &&
710             getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
711    return true;
712  }
713  // Nothing else.
714  return false;
715}
716
717bool Decl::isWeakImported() const {
718  bool IsDefinition;
719  if (!canBeWeakImported(IsDefinition))
720    return false;
721
722  for (const auto *A : getMostRecentDecl()->attrs()) {
723    if (isa<WeakImportAttr>(A))
724      return true;
725
726    if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
727      if (CheckAvailability(getASTContext(), Availability, nullptr,
728                            VersionTuple()) == AR_NotYetIntroduced)
729        return true;
730    }
731  }
732
733  return false;
734}
735
736unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
737  switch (DeclKind) {
738    case Function:
739    case CXXDeductionGuide:
740    case CXXMethod:
741    case CXXConstructor:
742    case ConstructorUsingShadow:
743    case CXXDestructor:
744    case CXXConversion:
745    case EnumConstant:
746    case Var:
747    case ImplicitParam:
748    case ParmVar:
749    case ObjCMethod:
750    case ObjCProperty:
751    case MSProperty:
752      return IDNS_Ordinary;
753    case Label:
754      return IDNS_Label;
755    case IndirectField:
756      return IDNS_Ordinary | IDNS_Member;
757
758    case Binding:
759    case NonTypeTemplateParm:
760    case VarTemplate:
761    case Concept:
762      // These (C++-only) declarations are found by redeclaration lookup for
763      // tag types, so we include them in the tag namespace.
764      return IDNS_Ordinary | IDNS_Tag;
765
766    case ObjCCompatibleAlias:
767    case ObjCInterface:
768      return IDNS_Ordinary | IDNS_Type;
769
770    case Typedef:
771    case TypeAlias:
772    case TemplateTypeParm:
773    case ObjCTypeParam:
774      return IDNS_Ordinary | IDNS_Type;
775
776    case UnresolvedUsingTypename:
777      return IDNS_Ordinary | IDNS_Type | IDNS_Using;
778
779    case UsingShadow:
780      return 0; // we'll actually overwrite this later
781
782    case UnresolvedUsingValue:
783      return IDNS_Ordinary | IDNS_Using;
784
785    case Using:
786    case UsingPack:
787      return IDNS_Using;
788
789    case ObjCProtocol:
790      return IDNS_ObjCProtocol;
791
792    case Field:
793    case ObjCAtDefsField:
794    case ObjCIvar:
795      return IDNS_Member;
796
797    case Record:
798    case CXXRecord:
799    case Enum:
800      return IDNS_Tag | IDNS_Type;
801
802    case Namespace:
803    case NamespaceAlias:
804      return IDNS_Namespace;
805
806    case FunctionTemplate:
807      return IDNS_Ordinary;
808
809    case ClassTemplate:
810    case TemplateTemplateParm:
811    case TypeAliasTemplate:
812      return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
813
814    case OMPDeclareReduction:
815      return IDNS_OMPReduction;
816
817    case OMPDeclareMapper:
818      return IDNS_OMPMapper;
819
820    // Never have names.
821    case Friend:
822    case FriendTemplate:
823    case AccessSpec:
824    case LinkageSpec:
825    case Export:
826    case FileScopeAsm:
827    case StaticAssert:
828    case ObjCPropertyImpl:
829    case PragmaComment:
830    case PragmaDetectMismatch:
831    case Block:
832    case Captured:
833    case TranslationUnit:
834    case ExternCContext:
835    case Decomposition:
836    case MSGuid:
837    case TemplateParamObject:
838
839    case UsingDirective:
840    case BuiltinTemplate:
841    case ClassTemplateSpecialization:
842    case ClassTemplatePartialSpecialization:
843    case ClassScopeFunctionSpecialization:
844    case VarTemplateSpecialization:
845    case VarTemplatePartialSpecialization:
846    case ObjCImplementation:
847    case ObjCCategory:
848    case ObjCCategoryImpl:
849    case Import:
850    case OMPThreadPrivate:
851    case OMPAllocate:
852    case OMPRequires:
853    case OMPCapturedExpr:
854    case Empty:
855    case LifetimeExtendedTemporary:
856    case RequiresExprBody:
857      // Never looked up by name.
858      return 0;
859  }
860
861  llvm_unreachable("Invalid DeclKind!");
862}
863
864void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
865  assert(!HasAttrs && "Decl already contains attrs.");
866
867  AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
868  assert(AttrBlank.empty() && "HasAttrs was wrong?");
869
870  AttrBlank = attrs;
871  HasAttrs = true;
872}
873
874void Decl::dropAttrs() {
875  if (!HasAttrs) return;
876
877  HasAttrs = false;
878  getASTContext().eraseDeclAttrs(this);
879}
880
881void Decl::addAttr(Attr *A) {
882  if (!hasAttrs()) {
883    setAttrs(AttrVec(1, A));
884    return;
885  }
886
887  AttrVec &Attrs = getAttrs();
888  if (!A->isInherited()) {
889    Attrs.push_back(A);
890    return;
891  }
892
893  // Attribute inheritance is processed after attribute parsing. To keep the
894  // order as in the source code, add inherited attributes before non-inherited
895  // ones.
896  auto I = Attrs.begin(), E = Attrs.end();
897  for (; I != E; ++I) {
898    if (!(*I)->isInherited())
899      break;
900  }
901  Attrs.insert(I, A);
902}
903
904const AttrVec &Decl::getAttrs() const {
905  assert(HasAttrs && "No attrs to get!");
906  return getASTContext().getDeclAttrs(this);
907}
908
909Decl *Decl::castFromDeclContext (const DeclContext *D) {
910  Decl::Kind DK = D->getDeclKind();
911  switch(DK) {
912#define DECL(NAME, BASE)
913#define DECL_CONTEXT(NAME) \
914    case Decl::NAME:       \
915      return static_cast<NAME##Decl *>(const_cast<DeclContext *>(D));
916#define DECL_CONTEXT_BASE(NAME)
917#include "clang/AST/DeclNodes.inc"
918    default:
919#define DECL(NAME, BASE)
920#define DECL_CONTEXT_BASE(NAME)                  \
921      if (DK >= first##NAME && DK <= last##NAME) \
922        return static_cast<NAME##Decl *>(const_cast<DeclContext *>(D));
923#include "clang/AST/DeclNodes.inc"
924      llvm_unreachable("a decl that inherits DeclContext isn't handled");
925  }
926}
927
928DeclContext *Decl::castToDeclContext(const Decl *D) {
929  Decl::Kind DK = D->getKind();
930  switch(DK) {
931#define DECL(NAME, BASE)
932#define DECL_CONTEXT(NAME) \
933    case Decl::NAME:       \
934      return static_cast<NAME##Decl *>(const_cast<Decl *>(D));
935#define DECL_CONTEXT_BASE(NAME)
936#include "clang/AST/DeclNodes.inc"
937    default:
938#define DECL(NAME, BASE)
939#define DECL_CONTEXT_BASE(NAME)                                   \
940      if (DK >= first##NAME && DK <= last##NAME)                  \
941        return static_cast<NAME##Decl *>(const_cast<Decl *>(D));
942#include "clang/AST/DeclNodes.inc"
943      llvm_unreachable("a decl that inherits DeclContext isn't handled");
944  }
945}
946
947SourceLocation Decl::getBodyRBrace() const {
948  // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
949  // FunctionDecl stores EndRangeLoc for this purpose.
950  if (const auto *FD = dyn_cast<FunctionDecl>(this)) {
951    const FunctionDecl *Definition;
952    if (FD->hasBody(Definition))
953      return Definition->getSourceRange().getEnd();
954    return {};
955  }
956
957  if (Stmt *Body = getBody())
958    return Body->getSourceRange().getEnd();
959
960  return {};
961}
962
963bool Decl::AccessDeclContextSanity() const {
964#ifndef NDEBUG
965  // Suppress this check if any of the following hold:
966  // 1. this is the translation unit (and thus has no parent)
967  // 2. this is a template parameter (and thus doesn't belong to its context)
968  // 3. this is a non-type template parameter
969  // 4. the context is not a record
970  // 5. it's invalid
971  // 6. it's a C++0x static_assert.
972  // 7. it's a block literal declaration
973  // 8. it's a temporary with lifetime extended due to being default value.
974  if (isa<TranslationUnitDecl>(this) || isa<TemplateTypeParmDecl>(this) ||
975      isa<NonTypeTemplateParmDecl>(this) || !getDeclContext() ||
976      !isa<CXXRecordDecl>(getDeclContext()) || isInvalidDecl() ||
977      isa<StaticAssertDecl>(this) || isa<BlockDecl>(this) ||
978      // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
979      // as DeclContext (?).
980      isa<ParmVarDecl>(this) ||
981      // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
982      // AS_none as access specifier.
983      isa<CXXRecordDecl>(this) ||
984      isa<ClassScopeFunctionSpecializationDecl>(this) ||
985      isa<LifetimeExtendedTemporaryDecl>(this))
986    return true;
987
988  assert(Access != AS_none &&
989         "Access specifier is AS_none inside a record decl");
990#endif
991  return true;
992}
993
994static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
995static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
996
997int64_t Decl::getID() const {
998  return getASTContext().getAllocator().identifyKnownAlignedObject<Decl>(this);
999}
1000
1001const FunctionType *Decl::getFunctionType(bool BlocksToo) const {
1002  QualType Ty;
1003  if (const auto *D = dyn_cast<ValueDecl>(this))
1004    Ty = D->getType();
1005  else if (const auto *D = dyn_cast<TypedefNameDecl>(this))
1006    Ty = D->getUnderlyingType();
1007  else
1008    return nullptr;
1009
1010  if (Ty->isFunctionPointerType())
1011    Ty = Ty->castAs<PointerType>()->getPointeeType();
1012  else if (Ty->isFunctionReferenceType())
1013    Ty = Ty->castAs<ReferenceType>()->getPointeeType();
1014  else if (BlocksToo && Ty->isBlockPointerType())
1015    Ty = Ty->castAs<BlockPointerType>()->getPointeeType();
1016
1017  return Ty->getAs<FunctionType>();
1018}
1019
1020/// Starting at a given context (a Decl or DeclContext), look for a
1021/// code context that is not a closure (a lambda, block, etc.).
1022template <class T> static Decl *getNonClosureContext(T *D) {
1023  if (getKind(D) == Decl::CXXMethod) {
1024    auto *MD = cast<CXXMethodDecl>(D);
1025    if (MD->getOverloadedOperator() == OO_Call &&
1026        MD->getParent()->isLambda())
1027      return getNonClosureContext(MD->getParent()->getParent());
1028    return MD;
1029  }
1030  if (auto *FD = dyn_cast<FunctionDecl>(D))
1031    return FD;
1032  if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
1033    return MD;
1034  if (auto *BD = dyn_cast<BlockDecl>(D))
1035    return getNonClosureContext(BD->getParent());
1036  if (auto *CD = dyn_cast<CapturedDecl>(D))
1037    return getNonClosureContext(CD->getParent());
1038  return nullptr;
1039}
1040
1041Decl *Decl::getNonClosureContext() {
1042  return ::getNonClosureContext(this);
1043}
1044
1045Decl *DeclContext::getNonClosureAncestor() {
1046  return ::getNonClosureContext(this);
1047}
1048
1049//===----------------------------------------------------------------------===//
1050// DeclContext Implementation
1051//===----------------------------------------------------------------------===//
1052
1053DeclContext::DeclContext(Decl::Kind K) {
1054  DeclContextBits.DeclKind = K;
1055  setHasExternalLexicalStorage(false);
1056  setHasExternalVisibleStorage(false);
1057  setNeedToReconcileExternalVisibleStorage(false);
1058  setHasLazyLocalLexicalLookups(false);
1059  setHasLazyExternalLexicalLookups(false);
1060  setUseQualifiedLookup(false);
1061}
1062
1063bool DeclContext::classof(const Decl *D) {
1064  switch (D->getKind()) {
1065#define DECL(NAME, BASE)
1066#define DECL_CONTEXT(NAME) case Decl::NAME:
1067#define DECL_CONTEXT_BASE(NAME)
1068#include "clang/AST/DeclNodes.inc"
1069      return true;
1070    default:
1071#define DECL(NAME, BASE)
1072#define DECL_CONTEXT_BASE(NAME)                 \
1073      if (D->getKind() >= Decl::first##NAME &&  \
1074          D->getKind() <= Decl::last##NAME)     \
1075        return true;
1076#include "clang/AST/DeclNodes.inc"
1077      return false;
1078  }
1079}
1080
1081DeclContext::~DeclContext() = default;
1082
1083/// Find the parent context of this context that will be
1084/// used for unqualified name lookup.
1085///
1086/// Generally, the parent lookup context is the semantic context. However, for
1087/// a friend function the parent lookup context is the lexical context, which
1088/// is the class in which the friend is declared.
1089DeclContext *DeclContext::getLookupParent() {
1090  // FIXME: Find a better way to identify friends.
1091  if (isa<FunctionDecl>(this))
1092    if (getParent()->getRedeclContext()->isFileContext() &&
1093        getLexicalParent()->getRedeclContext()->isRecord())
1094      return getLexicalParent();
1095
1096  // A lookup within the call operator of a lambda never looks in the lambda
1097  // class; instead, skip to the context in which that closure type is
1098  // declared.
1099  if (isLambdaCallOperator(this))
1100    return getParent()->getParent();
1101
1102  return getParent();
1103}
1104
1105const BlockDecl *DeclContext::getInnermostBlockDecl() const {
1106  const DeclContext *Ctx = this;
1107
1108  do {
1109    if (Ctx->isClosure())
1110      return cast<BlockDecl>(Ctx);
1111    Ctx = Ctx->getParent();
1112  } while (Ctx);
1113
1114  return nullptr;
1115}
1116
1117bool DeclContext::isInlineNamespace() const {
1118  return isNamespace() &&
1119         cast<NamespaceDecl>(this)->isInline();
1120}
1121
1122bool DeclContext::isStdNamespace() const {
1123  if (!isNamespace())
1124    return false;
1125
1126  const auto *ND = cast<NamespaceDecl>(this);
1127  if (ND->isInline()) {
1128    return ND->getParent()->isStdNamespace();
1129  }
1130
1131  if (!getParent()->getRedeclContext()->isTranslationUnit())
1132    return false;
1133
1134  const IdentifierInfo *II = ND->getIdentifier();
1135  return II && II->isStr("std");
1136}
1137
1138bool DeclContext::isDependentContext() const {
1139  if (isFileContext())
1140    return false;
1141
1142  if (isa<ClassTemplatePartialSpecializationDecl>(this))
1143    return true;
1144
1145  if (const auto *Record = dyn_cast<CXXRecordDecl>(this)) {
1146    if (Record->getDescribedClassTemplate())
1147      return true;
1148
1149    if (Record->isDependentLambda())
1150      return true;
1151  }
1152
1153  if (const auto *Function = dyn_cast<FunctionDecl>(this)) {
1154    if (Function->getDescribedFunctionTemplate())
1155      return true;
1156
1157    // Friend function declarations are dependent if their *lexical*
1158    // context is dependent.
1159    if (cast<Decl>(this)->getFriendObjectKind())
1160      return getLexicalParent()->isDependentContext();
1161  }
1162
1163  // FIXME: A variable template is a dependent context, but is not a
1164  // DeclContext. A context within it (such as a lambda-expression)
1165  // should be considered dependent.
1166
1167  return getParent() && getParent()->isDependentContext();
1168}
1169
1170bool DeclContext::isTransparentContext() const {
1171  if (getDeclKind() == Decl::Enum)
1172    return !cast<EnumDecl>(this)->isScoped();
1173
1174  return getDeclKind() == Decl::LinkageSpec || getDeclKind() == Decl::Export;
1175}
1176
1177static bool isLinkageSpecContext(const DeclContext *DC,
1178                                 LinkageSpecDecl::LanguageIDs ID) {
1179  while (DC->getDeclKind() != Decl::TranslationUnit) {
1180    if (DC->getDeclKind() == Decl::LinkageSpec)
1181      return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
1182    DC = DC->getLexicalParent();
1183  }
1184  return false;
1185}
1186
1187bool DeclContext::isExternCContext() const {
1188  return isLinkageSpecContext(this, LinkageSpecDecl::lang_c);
1189}
1190
1191const LinkageSpecDecl *DeclContext::getExternCContext() const {
1192  const DeclContext *DC = this;
1193  while (DC->getDeclKind() != Decl::TranslationUnit) {
1194    if (DC->getDeclKind() == Decl::LinkageSpec &&
1195        cast<LinkageSpecDecl>(DC)->getLanguage() == LinkageSpecDecl::lang_c)
1196      return cast<LinkageSpecDecl>(DC);
1197    DC = DC->getLexicalParent();
1198  }
1199  return nullptr;
1200}
1201
1202bool DeclContext::isExternCXXContext() const {
1203  return isLinkageSpecContext(this, LinkageSpecDecl::lang_cxx);
1204}
1205
1206bool DeclContext::Encloses(const DeclContext *DC) const {
1207  if (getPrimaryContext() != this)
1208    return getPrimaryContext()->Encloses(DC);
1209
1210  for (; DC; DC = DC->getParent())
1211    if (DC->getPrimaryContext() == this)
1212      return true;
1213  return false;
1214}
1215
1216DeclContext *DeclContext::getPrimaryContext() {
1217  switch (getDeclKind()) {
1218  case Decl::TranslationUnit:
1219  case Decl::ExternCContext:
1220  case Decl::LinkageSpec:
1221  case Decl::Export:
1222  case Decl::Block:
1223  case Decl::Captured:
1224  case Decl::OMPDeclareReduction:
1225  case Decl::OMPDeclareMapper:
1226  case Decl::RequiresExprBody:
1227    // There is only one DeclContext for these entities.
1228    return this;
1229
1230  case Decl::Namespace:
1231    // The original namespace is our primary context.
1232    return static_cast<NamespaceDecl *>(this)->getOriginalNamespace();
1233
1234  case Decl::ObjCMethod:
1235    return this;
1236
1237  case Decl::ObjCInterface:
1238    if (auto *OID = dyn_cast<ObjCInterfaceDecl>(this))
1239      if (auto *Def = OID->getDefinition())
1240        return Def;
1241    return this;
1242
1243  case Decl::ObjCProtocol:
1244    if (auto *OPD = dyn_cast<ObjCProtocolDecl>(this))
1245      if (auto *Def = OPD->getDefinition())
1246        return Def;
1247    return this;
1248
1249  case Decl::ObjCCategory:
1250    return this;
1251
1252  case Decl::ObjCImplementation:
1253  case Decl::ObjCCategoryImpl:
1254    return this;
1255
1256  default:
1257    if (getDeclKind() >= Decl::firstTag && getDeclKind() <= Decl::lastTag) {
1258      // If this is a tag type that has a definition or is currently
1259      // being defined, that definition is our primary context.
1260      auto *Tag = cast<TagDecl>(this);
1261
1262      if (TagDecl *Def = Tag->getDefinition())
1263        return Def;
1264
1265      if (const auto *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) {
1266        // Note, TagType::getDecl returns the (partial) definition one exists.
1267        TagDecl *PossiblePartialDef = TagTy->getDecl();
1268        if (PossiblePartialDef->isBeingDefined())
1269          return PossiblePartialDef;
1270      } else {
1271        assert(isa<InjectedClassNameType>(Tag->getTypeForDecl()));
1272      }
1273
1274      return Tag;
1275    }
1276
1277    assert(getDeclKind() >= Decl::firstFunction &&
1278           getDeclKind() <= Decl::lastFunction &&
1279          "Unknown DeclContext kind");
1280    return this;
1281  }
1282}
1283
1284void
1285DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
1286  Contexts.clear();
1287
1288  if (getDeclKind() != Decl::Namespace) {
1289    Contexts.push_back(this);
1290    return;
1291  }
1292
1293  auto *Self = static_cast<NamespaceDecl *>(this);
1294  for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
1295       N = N->getPreviousDecl())
1296    Contexts.push_back(N);
1297
1298  std::reverse(Contexts.begin(), Contexts.end());
1299}
1300
1301std::pair<Decl *, Decl *>
1302DeclContext::BuildDeclChain(ArrayRef<Decl *> Decls,
1303                            bool FieldsAlreadyLoaded) {
1304  // Build up a chain of declarations via the Decl::NextInContextAndBits field.
1305  Decl *FirstNewDecl = nullptr;
1306  Decl *PrevDecl = nullptr;
1307  for (auto *D : Decls) {
1308    if (FieldsAlreadyLoaded && isa<FieldDecl>(D))
1309      continue;
1310
1311    if (PrevDecl)
1312      PrevDecl->NextInContextAndBits.setPointer(D);
1313    else
1314      FirstNewDecl = D;
1315
1316    PrevDecl = D;
1317  }
1318
1319  return std::make_pair(FirstNewDecl, PrevDecl);
1320}
1321
1322/// We have just acquired external visible storage, and we already have
1323/// built a lookup map. For every name in the map, pull in the new names from
1324/// the external storage.
1325void DeclContext::reconcileExternalVisibleStorage() const {
1326  assert(hasNeedToReconcileExternalVisibleStorage() && LookupPtr);
1327  setNeedToReconcileExternalVisibleStorage(false);
1328
1329  for (auto &Lookup : *LookupPtr)
1330    Lookup.second.setHasExternalDecls();
1331}
1332
1333/// Load the declarations within this lexical storage from an
1334/// external source.
1335/// \return \c true if any declarations were added.
1336bool
1337DeclContext::LoadLexicalDeclsFromExternalStorage() const {
1338  ExternalASTSource *Source = getParentASTContext().getExternalSource();
1339  assert(hasExternalLexicalStorage() && Source && "No external storage?");
1340
1341  // Notify that we have a DeclContext that is initializing.
1342  ExternalASTSource::Deserializing ADeclContext(Source);
1343
1344  // Load the external declarations, if any.
1345  SmallVector<Decl*, 64> Decls;
1346  setHasExternalLexicalStorage(false);
1347  Source->FindExternalLexicalDecls(this, Decls);
1348
1349  if (Decls.empty())
1350    return false;
1351
1352  // We may have already loaded just the fields of this record, in which case
1353  // we need to ignore them.
1354  bool FieldsAlreadyLoaded = false;
1355  if (const auto *RD = dyn_cast<RecordDecl>(this))
1356    FieldsAlreadyLoaded = RD->hasLoadedFieldsFromExternalStorage();
1357
1358  // Splice the newly-read declarations into the beginning of the list
1359  // of declarations.
1360  Decl *ExternalFirst, *ExternalLast;
1361  std::tie(ExternalFirst, ExternalLast) =
1362      BuildDeclChain(Decls, FieldsAlreadyLoaded);
1363  ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
1364  FirstDecl = ExternalFirst;
1365  if (!LastDecl)
1366    LastDecl = ExternalLast;
1367  return true;
1368}
1369
1370DeclContext::lookup_result
1371ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
1372                                                    DeclarationName Name) {
1373  ASTContext &Context = DC->getParentASTContext();
1374  StoredDeclsMap *Map;
1375  if (!(Map = DC->LookupPtr))
1376    Map = DC->CreateStoredDeclsMap(Context);
1377  if (DC->hasNeedToReconcileExternalVisibleStorage())
1378    DC->reconcileExternalVisibleStorage();
1379
1380  (*Map)[Name].removeExternalDecls();
1381
1382  return DeclContext::lookup_result();
1383}
1384
1385DeclContext::lookup_result
1386ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
1387                                                  DeclarationName Name,
1388                                                  ArrayRef<NamedDecl*> Decls) {
1389  ASTContext &Context = DC->getParentASTContext();
1390  StoredDeclsMap *Map;
1391  if (!(Map = DC->LookupPtr))
1392    Map = DC->CreateStoredDeclsMap(Context);
1393  if (DC->hasNeedToReconcileExternalVisibleStorage())
1394    DC->reconcileExternalVisibleStorage();
1395
1396  StoredDeclsList &List = (*Map)[Name];
1397  List.replaceExternalDecls(Decls);
1398  return List.getLookupResult();
1399}
1400
1401DeclContext::decl_iterator DeclContext::decls_begin() const {
1402  if (hasExternalLexicalStorage())
1403    LoadLexicalDeclsFromExternalStorage();
1404  return decl_iterator(FirstDecl);
1405}
1406
1407bool DeclContext::decls_empty() const {
1408  if (hasExternalLexicalStorage())
1409    LoadLexicalDeclsFromExternalStorage();
1410
1411  return !FirstDecl;
1412}
1413
1414bool DeclContext::containsDecl(Decl *D) const {
1415  return (D->getLexicalDeclContext() == this &&
1416          (D->NextInContextAndBits.getPointer() || D == LastDecl));
1417}
1418
1419bool DeclContext::containsDeclAndLoad(Decl *D) const {
1420  if (hasExternalLexicalStorage())
1421    LoadLexicalDeclsFromExternalStorage();
1422  return containsDecl(D);
1423}
1424
1425/// shouldBeHidden - Determine whether a declaration which was declared
1426/// within its semantic context should be invisible to qualified name lookup.
1427static bool shouldBeHidden(NamedDecl *D) {
1428  // Skip unnamed declarations.
1429  if (!D->getDeclName())
1430    return true;
1431
1432  // Skip entities that can't be found by name lookup into a particular
1433  // context.
1434  if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1435      D->isTemplateParameter())
1436    return true;
1437
1438  // Skip friends and local extern declarations unless they're the first
1439  // declaration of the entity.
1440  if ((D->isLocalExternDecl() || D->getFriendObjectKind()) &&
1441      D != D->getCanonicalDecl())
1442    return true;
1443
1444  // Skip template specializations.
1445  // FIXME: This feels like a hack. Should DeclarationName support
1446  // template-ids, or is there a better way to keep specializations
1447  // from being visible?
1448  if (isa<ClassTemplateSpecializationDecl>(D))
1449    return true;
1450  if (auto *FD = dyn_cast<FunctionDecl>(D))
1451    if (FD->isFunctionTemplateSpecialization())
1452      return true;
1453
1454  // Hide destructors that are invalid. There should always be one destructor,
1455  // but if it is an invalid decl, another one is created. We need to hide the
1456  // invalid one from places that expect exactly one destructor, like the
1457  // serialization code.
1458  if (isa<CXXDestructorDecl>(D) && D->isInvalidDecl())
1459    return true;
1460
1461  return false;
1462}
1463
1464void DeclContext::removeDecl(Decl *D) {
1465  assert(D->getLexicalDeclContext() == this &&
1466         "decl being removed from non-lexical context");
1467  assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
1468         "decl is not in decls list");
1469
1470  // Remove D from the decl chain.  This is O(n) but hopefully rare.
1471  if (D == FirstDecl) {
1472    if (D == LastDecl)
1473      FirstDecl = LastDecl = nullptr;
1474    else
1475      FirstDecl = D->NextInContextAndBits.getPointer();
1476  } else {
1477    for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
1478      assert(I && "decl not found in linked list");
1479      if (I->NextInContextAndBits.getPointer() == D) {
1480        I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
1481        if (D == LastDecl) LastDecl = I;
1482        break;
1483      }
1484    }
1485  }
1486
1487  // Mark that D is no longer in the decl chain.
1488  D->NextInContextAndBits.setPointer(nullptr);
1489
1490  // Remove D from the lookup table if necessary.
1491  if (isa<NamedDecl>(D)) {
1492    auto *ND = cast<NamedDecl>(D);
1493
1494    // Do not try to remove the declaration if that is invisible to qualified
1495    // lookup.  E.g. template specializations are skipped.
1496    if (shouldBeHidden(ND))
1497      return;
1498
1499    // Remove only decls that have a name
1500    if (!ND->getDeclName())
1501      return;
1502
1503    auto *DC = D->getDeclContext();
1504    do {
1505      StoredDeclsMap *Map = DC->getPrimaryContext()->LookupPtr;
1506      if (Map) {
1507        StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1508        assert(Pos != Map->end() && "no lookup entry for decl");
1509        Pos->second.remove(ND);
1510      }
1511    } while (DC->isTransparentContext() && (DC = DC->getParent()));
1512  }
1513}
1514
1515void DeclContext::addHiddenDecl(Decl *D) {
1516  assert(D->getLexicalDeclContext() == this &&
1517         "Decl inserted into wrong lexical context");
1518  assert(!D->getNextDeclInContext() && D != LastDecl &&
1519         "Decl already inserted into a DeclContext");
1520
1521  if (FirstDecl) {
1522    LastDecl->NextInContextAndBits.setPointer(D);
1523    LastDecl = D;
1524  } else {
1525    FirstDecl = LastDecl = D;
1526  }
1527
1528  // Notify a C++ record declaration that we've added a member, so it can
1529  // update its class-specific state.
1530  if (auto *Record = dyn_cast<CXXRecordDecl>(this))
1531    Record->addedMember(D);
1532
1533  // If this is a newly-created (not de-serialized) import declaration, wire
1534  // it in to the list of local import declarations.
1535  if (!D->isFromASTFile()) {
1536    if (auto *Import = dyn_cast<ImportDecl>(D))
1537      D->getASTContext().addedLocalImportDecl(Import);
1538  }
1539}
1540
1541void DeclContext::addDecl(Decl *D) {
1542  addHiddenDecl(D);
1543
1544  if (auto *ND = dyn_cast<NamedDecl>(D))
1545    ND->getDeclContext()->getPrimaryContext()->
1546        makeDeclVisibleInContextWithFlags(ND, false, true);
1547}
1548
1549void DeclContext::addDeclInternal(Decl *D) {
1550  addHiddenDecl(D);
1551
1552  if (auto *ND = dyn_cast<NamedDecl>(D))
1553    ND->getDeclContext()->getPrimaryContext()->
1554        makeDeclVisibleInContextWithFlags(ND, true, true);
1555}
1556
1557/// buildLookup - Build the lookup data structure with all of the
1558/// declarations in this DeclContext (and any other contexts linked
1559/// to it or transparent contexts nested within it) and return it.
1560///
1561/// Note that the produced map may miss out declarations from an
1562/// external source. If it does, those entries will be marked with
1563/// the 'hasExternalDecls' flag.
1564StoredDeclsMap *DeclContext::buildLookup() {
1565  assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1566
1567  if (!hasLazyLocalLexicalLookups() &&
1568      !hasLazyExternalLexicalLookups())
1569    return LookupPtr;
1570
1571  SmallVector<DeclContext *, 2> Contexts;
1572  collectAllContexts(Contexts);
1573
1574  if (hasLazyExternalLexicalLookups()) {
1575    setHasLazyExternalLexicalLookups(false);
1576    for (auto *DC : Contexts) {
1577      if (DC->hasExternalLexicalStorage()) {
1578        bool LoadedDecls = DC->LoadLexicalDeclsFromExternalStorage();
1579        setHasLazyLocalLexicalLookups(
1580            hasLazyLocalLexicalLookups() | LoadedDecls );
1581      }
1582    }
1583
1584    if (!hasLazyLocalLexicalLookups())
1585      return LookupPtr;
1586  }
1587
1588  for (auto *DC : Contexts)
1589    buildLookupImpl(DC, hasExternalVisibleStorage());
1590
1591  // We no longer have any lazy decls.
1592  setHasLazyLocalLexicalLookups(false);
1593  return LookupPtr;
1594}
1595
1596/// buildLookupImpl - Build part of the lookup data structure for the
1597/// declarations contained within DCtx, which will either be this
1598/// DeclContext, a DeclContext linked to it, or a transparent context
1599/// nested within it.
1600void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {
1601  for (auto *D : DCtx->noload_decls()) {
1602    // Insert this declaration into the lookup structure, but only if
1603    // it's semantically within its decl context. Any other decls which
1604    // should be found in this context are added eagerly.
1605    //
1606    // If it's from an AST file, don't add it now. It'll get handled by
1607    // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1608    // in C++, we do not track external visible decls for the TU, so in
1609    // that case we need to collect them all here.
1610    if (auto *ND = dyn_cast<NamedDecl>(D))
1611      if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1612          (!ND->isFromASTFile() ||
1613           (isTranslationUnit() &&
1614            !getParentASTContext().getLangOpts().CPlusPlus)))
1615        makeDeclVisibleInContextImpl(ND, Internal);
1616
1617    // If this declaration is itself a transparent declaration context
1618    // or inline namespace, add the members of this declaration of that
1619    // context (recursively).
1620    if (auto *InnerCtx = dyn_cast<DeclContext>(D))
1621      if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1622        buildLookupImpl(InnerCtx, Internal);
1623  }
1624}
1625
1626DeclContext::lookup_result
1627DeclContext::lookup(DeclarationName Name) const {
1628  assert(getDeclKind() != Decl::LinkageSpec &&
1629         getDeclKind() != Decl::Export &&
1630         "should not perform lookups into transparent contexts");
1631
1632  const DeclContext *PrimaryContext = getPrimaryContext();
1633  if (PrimaryContext != this)
1634    return PrimaryContext->lookup(Name);
1635
1636  // If we have an external source, ensure that any later redeclarations of this
1637  // context have been loaded, since they may add names to the result of this
1638  // lookup (or add external visible storage).
1639  ExternalASTSource *Source = getParentASTContext().getExternalSource();
1640  if (Source)
1641    (void)cast<Decl>(this)->getMostRecentDecl();
1642
1643  if (hasExternalVisibleStorage()) {
1644    assert(Source && "external visible storage but no external source?");
1645
1646    if (hasNeedToReconcileExternalVisibleStorage())
1647      reconcileExternalVisibleStorage();
1648
1649    StoredDeclsMap *Map = LookupPtr;
1650
1651    if (hasLazyLocalLexicalLookups() ||
1652        hasLazyExternalLexicalLookups())
1653      // FIXME: Make buildLookup const?
1654      Map = const_cast<DeclContext*>(this)->buildLookup();
1655
1656    if (!Map)
1657      Map = CreateStoredDeclsMap(getParentASTContext());
1658
1659    // If we have a lookup result with no external decls, we are done.
1660    std::pair<StoredDeclsMap::iterator, bool> R =
1661        Map->insert(std::make_pair(Name, StoredDeclsList()));
1662    if (!R.second && !R.first->second.hasExternalDecls())
1663      return R.first->second.getLookupResult();
1664
1665    if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) {
1666      if (StoredDeclsMap *Map = LookupPtr) {
1667        StoredDeclsMap::iterator I = Map->find(Name);
1668        if (I != Map->end())
1669          return I->second.getLookupResult();
1670      }
1671    }
1672
1673    return {};
1674  }
1675
1676  StoredDeclsMap *Map = LookupPtr;
1677  if (hasLazyLocalLexicalLookups() ||
1678      hasLazyExternalLexicalLookups())
1679    Map = const_cast<DeclContext*>(this)->buildLookup();
1680
1681  if (!Map)
1682    return {};
1683
1684  StoredDeclsMap::iterator I = Map->find(Name);
1685  if (I == Map->end())
1686    return {};
1687
1688  return I->second.getLookupResult();
1689}
1690
1691DeclContext::lookup_result
1692DeclContext::noload_lookup(DeclarationName Name) {
1693  assert(getDeclKind() != Decl::LinkageSpec &&
1694         getDeclKind() != Decl::Export &&
1695         "should not perform lookups into transparent contexts");
1696
1697  DeclContext *PrimaryContext = getPrimaryContext();
1698  if (PrimaryContext != this)
1699    return PrimaryContext->noload_lookup(Name);
1700
1701  loadLazyLocalLexicalLookups();
1702  StoredDeclsMap *Map = LookupPtr;
1703  if (!Map)
1704    return {};
1705
1706  StoredDeclsMap::iterator I = Map->find(Name);
1707  return I != Map->end() ? I->second.getLookupResult()
1708                         : lookup_result();
1709}
1710
1711// If we have any lazy lexical declarations not in our lookup map, add them
1712// now. Don't import any external declarations, not even if we know we have
1713// some missing from the external visible lookups.
1714void DeclContext::loadLazyLocalLexicalLookups() {
1715  if (hasLazyLocalLexicalLookups()) {
1716    SmallVector<DeclContext *, 2> Contexts;
1717    collectAllContexts(Contexts);
1718    for (auto *Context : Contexts)
1719      buildLookupImpl(Context, hasExternalVisibleStorage());
1720    setHasLazyLocalLexicalLookups(false);
1721  }
1722}
1723
1724void DeclContext::localUncachedLookup(DeclarationName Name,
1725                                      SmallVectorImpl<NamedDecl *> &Results) {
1726  Results.clear();
1727
1728  // If there's no external storage, just perform a normal lookup and copy
1729  // the results.
1730  if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
1731    lookup_result LookupResults = lookup(Name);
1732    Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
1733    return;
1734  }
1735
1736  // If we have a lookup table, check there first. Maybe we'll get lucky.
1737  // FIXME: Should we be checking these flags on the primary context?
1738  if (Name && !hasLazyLocalLexicalLookups() &&
1739      !hasLazyExternalLexicalLookups()) {
1740    if (StoredDeclsMap *Map = LookupPtr) {
1741      StoredDeclsMap::iterator Pos = Map->find(Name);
1742      if (Pos != Map->end()) {
1743        Results.insert(Results.end(),
1744                       Pos->second.getLookupResult().begin(),
1745                       Pos->second.getLookupResult().end());
1746        return;
1747      }
1748    }
1749  }
1750
1751  // Slow case: grovel through the declarations in our chain looking for
1752  // matches.
1753  // FIXME: If we have lazy external declarations, this will not find them!
1754  // FIXME: Should we CollectAllContexts and walk them all here?
1755  for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1756    if (auto *ND = dyn_cast<NamedDecl>(D))
1757      if (ND->getDeclName() == Name)
1758        Results.push_back(ND);
1759  }
1760}
1761
1762DeclContext *DeclContext::getRedeclContext() {
1763  DeclContext *Ctx = this;
1764
1765  // In C, a record type is the redeclaration context for its fields only. If
1766  // we arrive at a record context after skipping anything else, we should skip
1767  // the record as well. Currently, this means skipping enumerations because
1768  // they're the only transparent context that can exist within a struct or
1769  // union.
1770  bool SkipRecords = getDeclKind() == Decl::Kind::Enum &&
1771                     !getParentASTContext().getLangOpts().CPlusPlus;
1772
1773  // Skip through contexts to get to the redeclaration context. Transparent
1774  // contexts are always skipped.
1775  while ((SkipRecords && Ctx->isRecord()) || Ctx->isTransparentContext())
1776    Ctx = Ctx->getParent();
1777  return Ctx;
1778}
1779
1780DeclContext *DeclContext::getEnclosingNamespaceContext() {
1781  DeclContext *Ctx = this;
1782  // Skip through non-namespace, non-translation-unit contexts.
1783  while (!Ctx->isFileContext())
1784    Ctx = Ctx->getParent();
1785  return Ctx->getPrimaryContext();
1786}
1787
1788RecordDecl *DeclContext::getOuterLexicalRecordContext() {
1789  // Loop until we find a non-record context.
1790  RecordDecl *OutermostRD = nullptr;
1791  DeclContext *DC = this;
1792  while (DC->isRecord()) {
1793    OutermostRD = cast<RecordDecl>(DC);
1794    DC = DC->getLexicalParent();
1795  }
1796  return OutermostRD;
1797}
1798
1799bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1800  // For non-file contexts, this is equivalent to Equals.
1801  if (!isFileContext())
1802    return O->Equals(this);
1803
1804  do {
1805    if (O->Equals(this))
1806      return true;
1807
1808    const auto *NS = dyn_cast<NamespaceDecl>(O);
1809    if (!NS || !NS->isInline())
1810      break;
1811    O = NS->getParent();
1812  } while (O);
1813
1814  return false;
1815}
1816
1817void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1818  DeclContext *PrimaryDC = this->getPrimaryContext();
1819  DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1820  // If the decl is being added outside of its semantic decl context, we
1821  // need to ensure that we eagerly build the lookup information for it.
1822  PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
1823}
1824
1825void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1826                                                    bool Recoverable) {
1827  assert(this == getPrimaryContext() && "expected a primary DC");
1828
1829  if (!isLookupContext()) {
1830    if (isTransparentContext())
1831      getParent()->getPrimaryContext()
1832        ->makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1833    return;
1834  }
1835
1836  // Skip declarations which should be invisible to name lookup.
1837  if (shouldBeHidden(D))
1838    return;
1839
1840  // If we already have a lookup data structure, perform the insertion into
1841  // it. If we might have externally-stored decls with this name, look them
1842  // up and perform the insertion. If this decl was declared outside its
1843  // semantic context, buildLookup won't add it, so add it now.
1844  //
1845  // FIXME: As a performance hack, don't add such decls into the translation
1846  // unit unless we're in C++, since qualified lookup into the TU is never
1847  // performed.
1848  if (LookupPtr || hasExternalVisibleStorage() ||
1849      ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1850       (getParentASTContext().getLangOpts().CPlusPlus ||
1851        !isTranslationUnit()))) {
1852    // If we have lazily omitted any decls, they might have the same name as
1853    // the decl which we are adding, so build a full lookup table before adding
1854    // this decl.
1855    buildLookup();
1856    makeDeclVisibleInContextImpl(D, Internal);
1857  } else {
1858    setHasLazyLocalLexicalLookups(true);
1859  }
1860
1861  // If we are a transparent context or inline namespace, insert into our
1862  // parent context, too. This operation is recursive.
1863  if (isTransparentContext() || isInlineNamespace())
1864    getParent()->getPrimaryContext()->
1865        makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1866
1867  auto *DCAsDecl = cast<Decl>(this);
1868  // Notify that a decl was made visible unless we are a Tag being defined.
1869  if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1870    if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1871      L->AddedVisibleDecl(this, D);
1872}
1873
1874void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1875  // Find or create the stored declaration map.
1876  StoredDeclsMap *Map = LookupPtr;
1877  if (!Map) {
1878    ASTContext *C = &getParentASTContext();
1879    Map = CreateStoredDeclsMap(*C);
1880  }
1881
1882  // If there is an external AST source, load any declarations it knows about
1883  // with this declaration's name.
1884  // If the lookup table contains an entry about this name it means that we
1885  // have already checked the external source.
1886  if (!Internal)
1887    if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1888      if (hasExternalVisibleStorage() &&
1889          Map->find(D->getDeclName()) == Map->end())
1890        Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1891
1892  // Insert this declaration into the map.
1893  StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
1894
1895  if (Internal) {
1896    // If this is being added as part of loading an external declaration,
1897    // this may not be the only external declaration with this name.
1898    // In this case, we never try to replace an existing declaration; we'll
1899    // handle that when we finalize the list of declarations for this name.
1900    DeclNameEntries.setHasExternalDecls();
1901    DeclNameEntries.prependDeclNoReplace(D);
1902    return;
1903  }
1904
1905  DeclNameEntries.addOrReplaceDecl(D);
1906}
1907
1908UsingDirectiveDecl *DeclContext::udir_iterator::operator*() const {
1909  return cast<UsingDirectiveDecl>(*I);
1910}
1911
1912/// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1913/// this context.
1914DeclContext::udir_range DeclContext::using_directives() const {
1915  // FIXME: Use something more efficient than normal lookup for using
1916  // directives. In C++, using directives are looked up more than anything else.
1917  lookup_result Result = lookup(UsingDirectiveDecl::getName());
1918  return udir_range(Result.begin(), Result.end());
1919}
1920
1921//===----------------------------------------------------------------------===//
1922// Creation and Destruction of StoredDeclsMaps.                               //
1923//===----------------------------------------------------------------------===//
1924
1925StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1926  assert(!LookupPtr && "context already has a decls map");
1927  assert(getPrimaryContext() == this &&
1928         "creating decls map on non-primary context");
1929
1930  StoredDeclsMap *M;
1931  bool Dependent = isDependentContext();
1932  if (Dependent)
1933    M = new DependentStoredDeclsMap();
1934  else
1935    M = new StoredDeclsMap();
1936  M->Previous = C.LastSDM;
1937  C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1938  LookupPtr = M;
1939  return M;
1940}
1941
1942void ASTContext::ReleaseDeclContextMaps() {
1943  // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1944  // pointer because the subclass doesn't add anything that needs to
1945  // be deleted.
1946  StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1947}
1948
1949void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1950  while (Map) {
1951    // Advance the iteration before we invalidate memory.
1952    llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1953
1954    if (Dependent)
1955      delete static_cast<DependentStoredDeclsMap*>(Map);
1956    else
1957      delete Map;
1958
1959    Map = Next.getPointer();
1960    Dependent = Next.getInt();
1961  }
1962}
1963
1964DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1965                                                 DeclContext *Parent,
1966                                           const PartialDiagnostic &PDiag) {
1967  assert(Parent->isDependentContext()
1968         && "cannot iterate dependent diagnostics of non-dependent context");
1969  Parent = Parent->getPrimaryContext();
1970  if (!Parent->LookupPtr)
1971    Parent->CreateStoredDeclsMap(C);
1972
1973  auto *Map = static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr);
1974
1975  // Allocate the copy of the PartialDiagnostic via the ASTContext's
1976  // BumpPtrAllocator, rather than the ASTContext itself.
1977  DiagnosticStorage *DiagStorage = nullptr;
1978  if (PDiag.hasStorage())
1979    DiagStorage = new (C) DiagnosticStorage;
1980
1981  auto *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
1982
1983  // TODO: Maybe we shouldn't reverse the order during insertion.
1984  DD->NextDiagnostic = Map->FirstDiagnostic;
1985  Map->FirstDiagnostic = DD;
1986
1987  return DD;
1988}
1989