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