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