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