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