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