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