]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/AST/DeclBase.cpp
Update tcpdump to 4.9.2
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / AST / DeclBase.cpp
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.
78   if (Ctx.getLangOpts().trackLocalOwningModule()) {
79     // Ensure required alignment of the resulting object by adding extra
80     // padding at the start if required.
81     size_t ExtraAlign =
82         llvm::OffsetToAlignment(sizeof(Module *), alignof(Decl));
83     char *Buffer = reinterpret_cast<char *>(
84         ::operator new(ExtraAlign + sizeof(Module *) + Size + Extra, Ctx));
85     Buffer += ExtraAlign;
86     auto *ParentModule =
87         Parent ? cast<Decl>(Parent)->getOwningModule() : nullptr;
88     return new (Buffer) Module*(ParentModule) + 1;
89   }
90   return ::operator new(Size + Extra, Ctx);
91 }
92
93 Module *Decl::getOwningModuleSlow() const {
94   assert(isFromASTFile() && "Not from AST file?");
95   return getASTContext().getExternalSource()->getModule(getOwningModuleID());
96 }
97
98 bool Decl::hasLocalOwningModuleStorage() const {
99   return getASTContext().getLangOpts().trackLocalOwningModule();
100 }
101
102 const char *Decl::getDeclKindName() const {
103   switch (DeclKind) {
104   default: llvm_unreachable("Declaration not in DeclNodes.inc!");
105 #define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
106 #define ABSTRACT_DECL(DECL)
107 #include "clang/AST/DeclNodes.inc"
108   }
109 }
110
111 void Decl::setInvalidDecl(bool Invalid) {
112   InvalidDecl = Invalid;
113   assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition());
114   if (!Invalid) {
115     return;
116   }
117
118   if (!isa<ParmVarDecl>(this)) {
119     // Defensive maneuver for ill-formed code: we're likely not to make it to
120     // a point where we set the access specifier, so default it to "public"
121     // to avoid triggering asserts elsewhere in the front end. 
122     setAccess(AS_public);
123   }
124
125   // Marking a DecompositionDecl as invalid implies all the child BindingDecl's
126   // are invalid too.
127   if (DecompositionDecl *DD = dyn_cast<DecompositionDecl>(this)) {
128     for (BindingDecl *Binding : DD->bindings()) {
129       Binding->setInvalidDecl();
130     }
131   }
132 }
133
134 const char *DeclContext::getDeclKindName() const {
135   switch (DeclKind) {
136   default: llvm_unreachable("Declaration context not in DeclNodes.inc!");
137 #define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
138 #define ABSTRACT_DECL(DECL)
139 #include "clang/AST/DeclNodes.inc"
140   }
141 }
142
143 bool Decl::StatisticsEnabled = false;
144 void Decl::EnableStatistics() {
145   StatisticsEnabled = true;
146 }
147
148 void Decl::PrintStats() {
149   llvm::errs() << "\n*** Decl Stats:\n";
150
151   int totalDecls = 0;
152 #define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
153 #define ABSTRACT_DECL(DECL)
154 #include "clang/AST/DeclNodes.inc"
155   llvm::errs() << "  " << totalDecls << " decls total.\n";
156
157   int totalBytes = 0;
158 #define DECL(DERIVED, BASE)                                             \
159   if (n##DERIVED##s > 0) {                                              \
160     totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl));         \
161     llvm::errs() << "    " << n##DERIVED##s << " " #DERIVED " decls, "  \
162                  << sizeof(DERIVED##Decl) << " each ("                  \
163                  << n##DERIVED##s * sizeof(DERIVED##Decl)               \
164                  << " bytes)\n";                                        \
165   }
166 #define ABSTRACT_DECL(DECL)
167 #include "clang/AST/DeclNodes.inc"
168
169   llvm::errs() << "Total bytes = " << totalBytes << "\n";
170 }
171
172 void Decl::add(Kind k) {
173   switch (k) {
174 #define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
175 #define ABSTRACT_DECL(DECL)
176 #include "clang/AST/DeclNodes.inc"
177   }
178 }
179
180 bool Decl::isTemplateParameterPack() const {
181   if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
182     return TTP->isParameterPack();
183   if (const NonTypeTemplateParmDecl *NTTP
184                                 = dyn_cast<NonTypeTemplateParmDecl>(this))
185     return NTTP->isParameterPack();
186   if (const TemplateTemplateParmDecl *TTP
187                                     = dyn_cast<TemplateTemplateParmDecl>(this))
188     return TTP->isParameterPack();
189   return false;
190 }
191
192 bool Decl::isParameterPack() const {
193   if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this))
194     return Parm->isParameterPack();
195   
196   return isTemplateParameterPack();
197 }
198
199 FunctionDecl *Decl::getAsFunction() {
200   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
201     return FD;
202   if (const FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(this))
203     return FTD->getTemplatedDecl();
204   return nullptr;
205 }
206
207 bool Decl::isTemplateDecl() const {
208   return isa<TemplateDecl>(this);
209 }
210
211 TemplateDecl *Decl::getDescribedTemplate() const {
212   if (auto *FD = dyn_cast<FunctionDecl>(this))
213     return FD->getDescribedFunctionTemplate();
214   else if (auto *RD = dyn_cast<CXXRecordDecl>(this))
215     return RD->getDescribedClassTemplate();
216   else if (auto *VD = dyn_cast<VarDecl>(this))
217     return VD->getDescribedVarTemplate();
218
219   return nullptr;
220 }
221
222 const DeclContext *Decl::getParentFunctionOrMethod() const {
223   for (const DeclContext *DC = getDeclContext();
224        DC && !DC->isTranslationUnit() && !DC->isNamespace(); 
225        DC = DC->getParent())
226     if (DC->isFunctionOrMethod())
227       return DC;
228
229   return nullptr;
230 }
231
232
233 //===----------------------------------------------------------------------===//
234 // PrettyStackTraceDecl Implementation
235 //===----------------------------------------------------------------------===//
236
237 void PrettyStackTraceDecl::print(raw_ostream &OS) const {
238   SourceLocation TheLoc = Loc;
239   if (TheLoc.isInvalid() && TheDecl)
240     TheLoc = TheDecl->getLocation();
241
242   if (TheLoc.isValid()) {
243     TheLoc.print(OS, SM);
244     OS << ": ";
245   }
246
247   OS << Message;
248
249   if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
250     OS << " '";
251     DN->printQualifiedName(OS);
252     OS << '\'';
253   }
254   OS << '\n';
255 }
256
257 //===----------------------------------------------------------------------===//
258 // Decl Implementation
259 //===----------------------------------------------------------------------===//
260
261 // Out-of-line virtual method providing a home for Decl.
262 Decl::~Decl() { }
263
264 void Decl::setDeclContext(DeclContext *DC) {
265   DeclCtx = DC;
266 }
267
268 void Decl::setLexicalDeclContext(DeclContext *DC) {
269   if (DC == getLexicalDeclContext())
270     return;
271
272   if (isInSemaDC()) {
273     setDeclContextsImpl(getDeclContext(), DC, getASTContext());
274   } else {
275     getMultipleDC()->LexicalDC = DC;
276   }
277
278   // FIXME: We shouldn't be changing the lexical context of declarations
279   // imported from AST files.
280   if (!isFromASTFile()) {
281     setModuleOwnershipKind(getModuleOwnershipKindForChildOf(DC));
282     if (hasOwningModule())
283       setLocalOwningModule(cast<Decl>(DC)->getOwningModule());
284   }
285
286   assert(
287       (getModuleOwnershipKind() != ModuleOwnershipKind::VisibleWhenImported ||
288        getOwningModule()) &&
289       "hidden declaration has no owning module");
290 }
291
292 void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
293                                ASTContext &Ctx) {
294   if (SemaDC == LexicalDC) {
295     DeclCtx = SemaDC;
296   } else {
297     Decl::MultipleDC *MDC = new (Ctx) Decl::MultipleDC();
298     MDC->SemanticDC = SemaDC;
299     MDC->LexicalDC = LexicalDC;
300     DeclCtx = MDC;
301   }
302 }
303
304 bool Decl::isLexicallyWithinFunctionOrMethod() const {
305   const DeclContext *LDC = getLexicalDeclContext();
306   while (true) {
307     if (LDC->isFunctionOrMethod())
308       return true;
309     if (!isa<TagDecl>(LDC))
310       return false;
311     LDC = LDC->getLexicalParent();
312   }
313   return false;
314 }
315
316 bool Decl::isInAnonymousNamespace() const {
317   const DeclContext *DC = getDeclContext();
318   do {
319     if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
320       if (ND->isAnonymousNamespace())
321         return true;
322   } while ((DC = DC->getParent()));
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 Binding:
684     case ImplicitParam:
685     case ParmVar:
686     case ObjCMethod:
687     case ObjCProperty:
688     case MSProperty:
689       return IDNS_Ordinary;
690     case Label:
691       return IDNS_Label;
692     case IndirectField:
693       return IDNS_Ordinary | IDNS_Member;
694
695     case NonTypeTemplateParm:
696       // Non-type template parameters are not found by lookups that ignore
697       // non-types, but they are found by redeclaration lookups for tag types,
698       // 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 TypeAliasTemplate:
708     case TemplateTypeParm:
709     case ObjCTypeParam:
710       return IDNS_Ordinary | IDNS_Type;
711
712     case UnresolvedUsingTypename:
713       return IDNS_Ordinary | IDNS_Type | IDNS_Using;
714
715     case UsingShadow:
716       return 0; // we'll actually overwrite this later
717
718     case UnresolvedUsingValue:
719       return IDNS_Ordinary | IDNS_Using;
720
721     case Using:
722     case UsingPack:
723       return IDNS_Using;
724
725     case ObjCProtocol:
726       return IDNS_ObjCProtocol;
727
728     case Field:
729     case ObjCAtDefsField:
730     case ObjCIvar:
731       return IDNS_Member;
732
733     case Record:
734     case CXXRecord:
735     case Enum:
736       return IDNS_Tag | IDNS_Type;
737
738     case Namespace:
739     case NamespaceAlias:
740       return IDNS_Namespace;
741
742     case FunctionTemplate:
743     case VarTemplate:
744       return IDNS_Ordinary;
745
746     case ClassTemplate:
747     case TemplateTemplateParm:
748       return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
749
750     case OMPDeclareReduction:
751       return IDNS_OMPReduction;
752
753     // Never have names.
754     case Friend:
755     case FriendTemplate:
756     case AccessSpec:
757     case LinkageSpec:
758     case Export:
759     case FileScopeAsm:
760     case StaticAssert:
761     case ObjCPropertyImpl:
762     case PragmaComment:
763     case PragmaDetectMismatch:
764     case Block:
765     case Captured:
766     case TranslationUnit:
767     case ExternCContext:
768     case Decomposition:
769
770     case UsingDirective:
771     case BuiltinTemplate:
772     case ClassTemplateSpecialization:
773     case ClassTemplatePartialSpecialization:
774     case ClassScopeFunctionSpecialization:
775     case VarTemplateSpecialization:
776     case VarTemplatePartialSpecialization:
777     case ObjCImplementation:
778     case ObjCCategory:
779     case ObjCCategoryImpl:
780     case Import:
781     case OMPThreadPrivate:
782     case OMPCapturedExpr:
783     case Empty:
784       // Never looked up by name.
785       return 0;
786   }
787
788   llvm_unreachable("Invalid DeclKind!");
789 }
790
791 void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
792   assert(!HasAttrs && "Decl already contains attrs.");
793
794   AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
795   assert(AttrBlank.empty() && "HasAttrs was wrong?");
796
797   AttrBlank = attrs;
798   HasAttrs = true;
799 }
800
801 void Decl::dropAttrs() {
802   if (!HasAttrs) return;
803
804   HasAttrs = false;
805   getASTContext().eraseDeclAttrs(this);
806 }
807
808 const AttrVec &Decl::getAttrs() const {
809   assert(HasAttrs && "No attrs to get!");
810   return getASTContext().getDeclAttrs(this);
811 }
812
813 Decl *Decl::castFromDeclContext (const DeclContext *D) {
814   Decl::Kind DK = D->getDeclKind();
815   switch(DK) {
816 #define DECL(NAME, BASE)
817 #define DECL_CONTEXT(NAME) \
818     case Decl::NAME:       \
819       return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
820 #define DECL_CONTEXT_BASE(NAME)
821 #include "clang/AST/DeclNodes.inc"
822     default:
823 #define DECL(NAME, BASE)
824 #define DECL_CONTEXT_BASE(NAME)                  \
825       if (DK >= first##NAME && DK <= last##NAME) \
826         return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
827 #include "clang/AST/DeclNodes.inc"
828       llvm_unreachable("a decl that inherits DeclContext isn't handled");
829   }
830 }
831
832 DeclContext *Decl::castToDeclContext(const Decl *D) {
833   Decl::Kind DK = D->getKind();
834   switch(DK) {
835 #define DECL(NAME, BASE)
836 #define DECL_CONTEXT(NAME) \
837     case Decl::NAME:       \
838       return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
839 #define DECL_CONTEXT_BASE(NAME)
840 #include "clang/AST/DeclNodes.inc"
841     default:
842 #define DECL(NAME, BASE)
843 #define DECL_CONTEXT_BASE(NAME)                                   \
844       if (DK >= first##NAME && DK <= last##NAME)                  \
845         return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
846 #include "clang/AST/DeclNodes.inc"
847       llvm_unreachable("a decl that inherits DeclContext isn't handled");
848   }
849 }
850
851 SourceLocation Decl::getBodyRBrace() const {
852   // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
853   // FunctionDecl stores EndRangeLoc for this purpose.
854   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
855     const FunctionDecl *Definition;
856     if (FD->hasBody(Definition))
857       return Definition->getSourceRange().getEnd();
858     return SourceLocation();
859   }
860
861   if (Stmt *Body = getBody())
862     return Body->getSourceRange().getEnd();
863
864   return SourceLocation();
865 }
866
867 bool Decl::AccessDeclContextSanity() const {
868 #ifndef NDEBUG
869   // Suppress this check if any of the following hold:
870   // 1. this is the translation unit (and thus has no parent)
871   // 2. this is a template parameter (and thus doesn't belong to its context)
872   // 3. this is a non-type template parameter
873   // 4. the context is not a record
874   // 5. it's invalid
875   // 6. it's a C++0x static_assert.
876   if (isa<TranslationUnitDecl>(this) ||
877       isa<TemplateTypeParmDecl>(this) ||
878       isa<NonTypeTemplateParmDecl>(this) ||
879       !isa<CXXRecordDecl>(getDeclContext()) ||
880       isInvalidDecl() ||
881       isa<StaticAssertDecl>(this) ||
882       // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
883       // as DeclContext (?).
884       isa<ParmVarDecl>(this) ||
885       // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
886       // AS_none as access specifier.
887       isa<CXXRecordDecl>(this) ||
888       isa<ClassScopeFunctionSpecializationDecl>(this))
889     return true;
890
891   assert(Access != AS_none &&
892          "Access specifier is AS_none inside a record decl");
893 #endif
894   return true;
895 }
896
897 static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
898 static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
899
900 const FunctionType *Decl::getFunctionType(bool BlocksToo) const {
901   QualType Ty;
902   if (const ValueDecl *D = dyn_cast<ValueDecl>(this))
903     Ty = D->getType();
904   else if (const TypedefNameDecl *D = dyn_cast<TypedefNameDecl>(this))
905     Ty = D->getUnderlyingType();
906   else
907     return nullptr;
908
909   if (Ty->isFunctionPointerType())
910     Ty = Ty->getAs<PointerType>()->getPointeeType();
911   else if (BlocksToo && Ty->isBlockPointerType())
912     Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
913
914   return Ty->getAs<FunctionType>();
915 }
916
917
918 /// Starting at a given context (a Decl or DeclContext), look for a
919 /// code context that is not a closure (a lambda, block, etc.).
920 template <class T> static Decl *getNonClosureContext(T *D) {
921   if (getKind(D) == Decl::CXXMethod) {
922     CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
923     if (MD->getOverloadedOperator() == OO_Call &&
924         MD->getParent()->isLambda())
925       return getNonClosureContext(MD->getParent()->getParent());
926     return MD;
927   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
928     return FD;
929   } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
930     return MD;
931   } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
932     return getNonClosureContext(BD->getParent());
933   } else if (CapturedDecl *CD = dyn_cast<CapturedDecl>(D)) {
934     return getNonClosureContext(CD->getParent());
935   } else {
936     return nullptr;
937   }
938 }
939
940 Decl *Decl::getNonClosureContext() {
941   return ::getNonClosureContext(this);
942 }
943
944 Decl *DeclContext::getNonClosureAncestor() {
945   return ::getNonClosureContext(this);
946 }
947
948 //===----------------------------------------------------------------------===//
949 // DeclContext Implementation
950 //===----------------------------------------------------------------------===//
951
952 bool DeclContext::classof(const Decl *D) {
953   switch (D->getKind()) {
954 #define DECL(NAME, BASE)
955 #define DECL_CONTEXT(NAME) case Decl::NAME:
956 #define DECL_CONTEXT_BASE(NAME)
957 #include "clang/AST/DeclNodes.inc"
958       return true;
959     default:
960 #define DECL(NAME, BASE)
961 #define DECL_CONTEXT_BASE(NAME)                 \
962       if (D->getKind() >= Decl::first##NAME &&  \
963           D->getKind() <= Decl::last##NAME)     \
964         return true;
965 #include "clang/AST/DeclNodes.inc"
966       return false;
967   }
968 }
969
970 DeclContext::~DeclContext() { }
971
972 /// \brief Find the parent context of this context that will be
973 /// used for unqualified name lookup.
974 ///
975 /// Generally, the parent lookup context is the semantic context. However, for
976 /// a friend function the parent lookup context is the lexical context, which
977 /// is the class in which the friend is declared.
978 DeclContext *DeclContext::getLookupParent() {
979   // FIXME: Find a better way to identify friends
980   if (isa<FunctionDecl>(this))
981     if (getParent()->getRedeclContext()->isFileContext() &&
982         getLexicalParent()->getRedeclContext()->isRecord())
983       return getLexicalParent();
984   
985   return getParent();
986 }
987
988 bool DeclContext::isInlineNamespace() const {
989   return isNamespace() &&
990          cast<NamespaceDecl>(this)->isInline();
991 }
992
993 bool DeclContext::isStdNamespace() const {
994   if (!isNamespace())
995     return false;
996
997   const NamespaceDecl *ND = cast<NamespaceDecl>(this);
998   if (ND->isInline()) {
999     return ND->getParent()->isStdNamespace();
1000   }
1001
1002   if (!getParent()->getRedeclContext()->isTranslationUnit())
1003     return false;
1004
1005   const IdentifierInfo *II = ND->getIdentifier();
1006   return II && II->isStr("std");
1007 }
1008
1009 bool DeclContext::isDependentContext() const {
1010   if (isFileContext())
1011     return false;
1012
1013   if (isa<ClassTemplatePartialSpecializationDecl>(this))
1014     return true;
1015
1016   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
1017     if (Record->getDescribedClassTemplate())
1018       return true;
1019     
1020     if (Record->isDependentLambda())
1021       return true;
1022   }
1023   
1024   if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
1025     if (Function->getDescribedFunctionTemplate())
1026       return true;
1027
1028     // Friend function declarations are dependent if their *lexical*
1029     // context is dependent.
1030     if (cast<Decl>(this)->getFriendObjectKind())
1031       return getLexicalParent()->isDependentContext();
1032   }
1033
1034   // FIXME: A variable template is a dependent context, but is not a
1035   // DeclContext. A context within it (such as a lambda-expression)
1036   // should be considered dependent.
1037
1038   return getParent() && getParent()->isDependentContext();
1039 }
1040
1041 bool DeclContext::isTransparentContext() const {
1042   if (DeclKind == Decl::Enum)
1043     return !cast<EnumDecl>(this)->isScoped();
1044   else if (DeclKind == Decl::LinkageSpec || DeclKind == Decl::Export)
1045     return true;
1046
1047   return false;
1048 }
1049
1050 static bool isLinkageSpecContext(const DeclContext *DC,
1051                                  LinkageSpecDecl::LanguageIDs ID) {
1052   while (DC->getDeclKind() != Decl::TranslationUnit) {
1053     if (DC->getDeclKind() == Decl::LinkageSpec)
1054       return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
1055     DC = DC->getLexicalParent();
1056   }
1057   return false;
1058 }
1059
1060 bool DeclContext::isExternCContext() const {
1061   return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_c);
1062 }
1063
1064 const LinkageSpecDecl *DeclContext::getExternCContext() const {
1065   const DeclContext *DC = this;
1066   while (DC->getDeclKind() != Decl::TranslationUnit) {
1067     if (DC->getDeclKind() == Decl::LinkageSpec &&
1068         cast<LinkageSpecDecl>(DC)->getLanguage() ==
1069             clang::LinkageSpecDecl::lang_c)
1070       return cast<LinkageSpecDecl>(DC);
1071     DC = DC->getLexicalParent();
1072   }
1073   return nullptr;
1074 }
1075
1076 bool DeclContext::isExternCXXContext() const {
1077   return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_cxx);
1078 }
1079
1080 bool DeclContext::Encloses(const DeclContext *DC) const {
1081   if (getPrimaryContext() != this)
1082     return getPrimaryContext()->Encloses(DC);
1083
1084   for (; DC; DC = DC->getParent())
1085     if (DC->getPrimaryContext() == this)
1086       return true;
1087   return false;
1088 }
1089
1090 DeclContext *DeclContext::getPrimaryContext() {
1091   switch (DeclKind) {
1092   case Decl::TranslationUnit:
1093   case Decl::ExternCContext:
1094   case Decl::LinkageSpec:
1095   case Decl::Export:
1096   case Decl::Block:
1097   case Decl::Captured:
1098   case Decl::OMPDeclareReduction:
1099     // There is only one DeclContext for these entities.
1100     return this;
1101
1102   case Decl::Namespace:
1103     // The original namespace is our primary context.
1104     return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
1105
1106   case Decl::ObjCMethod:
1107     return this;
1108
1109   case Decl::ObjCInterface:
1110     if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
1111       return Def;
1112       
1113     return this;
1114       
1115   case Decl::ObjCProtocol:
1116     if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
1117       return Def;
1118     
1119     return this;
1120       
1121   case Decl::ObjCCategory:
1122     return this;
1123
1124   case Decl::ObjCImplementation:
1125   case Decl::ObjCCategoryImpl:
1126     return this;
1127
1128   default:
1129     if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
1130       // If this is a tag type that has a definition or is currently
1131       // being defined, that definition is our primary context.
1132       TagDecl *Tag = cast<TagDecl>(this);
1133
1134       if (TagDecl *Def = Tag->getDefinition())
1135         return Def;
1136
1137       if (const TagType *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) {
1138         // Note, TagType::getDecl returns the (partial) definition one exists.
1139         TagDecl *PossiblePartialDef = TagTy->getDecl();
1140         if (PossiblePartialDef->isBeingDefined())
1141           return PossiblePartialDef;
1142       } else {
1143         assert(isa<InjectedClassNameType>(Tag->getTypeForDecl()));
1144       }
1145
1146       return Tag;
1147     }
1148
1149     assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
1150           "Unknown DeclContext kind");
1151     return this;
1152   }
1153 }
1154
1155 void 
1156 DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
1157   Contexts.clear();
1158   
1159   if (DeclKind != Decl::Namespace) {
1160     Contexts.push_back(this);
1161     return;
1162   }
1163   
1164   NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
1165   for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
1166        N = N->getPreviousDecl())
1167     Contexts.push_back(N);
1168   
1169   std::reverse(Contexts.begin(), Contexts.end());
1170 }
1171
1172 std::pair<Decl *, Decl *>
1173 DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
1174                             bool FieldsAlreadyLoaded) {
1175   // Build up a chain of declarations via the Decl::NextInContextAndBits field.
1176   Decl *FirstNewDecl = nullptr;
1177   Decl *PrevDecl = nullptr;
1178   for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1179     if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
1180       continue;
1181
1182     Decl *D = Decls[I];
1183     if (PrevDecl)
1184       PrevDecl->NextInContextAndBits.setPointer(D);
1185     else
1186       FirstNewDecl = D;
1187
1188     PrevDecl = D;
1189   }
1190
1191   return std::make_pair(FirstNewDecl, PrevDecl);
1192 }
1193
1194 /// \brief We have just acquired external visible storage, and we already have
1195 /// built a lookup map. For every name in the map, pull in the new names from
1196 /// the external storage.
1197 void DeclContext::reconcileExternalVisibleStorage() const {
1198   assert(NeedToReconcileExternalVisibleStorage && LookupPtr);
1199   NeedToReconcileExternalVisibleStorage = false;
1200
1201   for (auto &Lookup : *LookupPtr)
1202     Lookup.second.setHasExternalDecls();
1203 }
1204
1205 /// \brief Load the declarations within this lexical storage from an
1206 /// external source.
1207 /// \return \c true if any declarations were added.
1208 bool
1209 DeclContext::LoadLexicalDeclsFromExternalStorage() const {
1210   ExternalASTSource *Source = getParentASTContext().getExternalSource();
1211   assert(hasExternalLexicalStorage() && Source && "No external storage?");
1212
1213   // Notify that we have a DeclContext that is initializing.
1214   ExternalASTSource::Deserializing ADeclContext(Source);
1215
1216   // Load the external declarations, if any.
1217   SmallVector<Decl*, 64> Decls;
1218   ExternalLexicalStorage = false;
1219   Source->FindExternalLexicalDecls(this, Decls);
1220
1221   if (Decls.empty())
1222     return false;
1223
1224   // We may have already loaded just the fields of this record, in which case
1225   // we need to ignore them.
1226   bool FieldsAlreadyLoaded = false;
1227   if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
1228     FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
1229   
1230   // Splice the newly-read declarations into the beginning of the list
1231   // of declarations.
1232   Decl *ExternalFirst, *ExternalLast;
1233   std::tie(ExternalFirst, ExternalLast) =
1234       BuildDeclChain(Decls, FieldsAlreadyLoaded);
1235   ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
1236   FirstDecl = ExternalFirst;
1237   if (!LastDecl)
1238     LastDecl = ExternalLast;
1239   return true;
1240 }
1241
1242 DeclContext::lookup_result
1243 ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
1244                                                     DeclarationName Name) {
1245   ASTContext &Context = DC->getParentASTContext();
1246   StoredDeclsMap *Map;
1247   if (!(Map = DC->LookupPtr))
1248     Map = DC->CreateStoredDeclsMap(Context);
1249   if (DC->NeedToReconcileExternalVisibleStorage)
1250     DC->reconcileExternalVisibleStorage();
1251
1252   (*Map)[Name].removeExternalDecls();
1253
1254   return DeclContext::lookup_result();
1255 }
1256
1257 DeclContext::lookup_result
1258 ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
1259                                                   DeclarationName Name,
1260                                                   ArrayRef<NamedDecl*> Decls) {
1261   ASTContext &Context = DC->getParentASTContext();
1262   StoredDeclsMap *Map;
1263   if (!(Map = DC->LookupPtr))
1264     Map = DC->CreateStoredDeclsMap(Context);
1265   if (DC->NeedToReconcileExternalVisibleStorage)
1266     DC->reconcileExternalVisibleStorage();
1267
1268   StoredDeclsList &List = (*Map)[Name];
1269
1270   // Clear out any old external visible declarations, to avoid quadratic
1271   // performance in the redeclaration checks below.
1272   List.removeExternalDecls();
1273
1274   if (!List.isNull()) {
1275     // We have both existing declarations and new declarations for this name.
1276     // Some of the declarations may simply replace existing ones. Handle those
1277     // first.
1278     llvm::SmallVector<unsigned, 8> Skip;
1279     for (unsigned I = 0, N = Decls.size(); I != N; ++I)
1280       if (List.HandleRedeclaration(Decls[I], /*IsKnownNewer*/false))
1281         Skip.push_back(I);
1282     Skip.push_back(Decls.size());
1283
1284     // Add in any new declarations.
1285     unsigned SkipPos = 0;
1286     for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1287       if (I == Skip[SkipPos])
1288         ++SkipPos;
1289       else
1290         List.AddSubsequentDecl(Decls[I]);
1291     }
1292   } else {
1293     // Convert the array to a StoredDeclsList.
1294     for (ArrayRef<NamedDecl*>::iterator
1295            I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1296       if (List.isNull())
1297         List.setOnlyValue(*I);
1298       else
1299         List.AddSubsequentDecl(*I);
1300     }
1301   }
1302
1303   return List.getLookupResult();
1304 }
1305
1306 DeclContext::decl_iterator DeclContext::decls_begin() const {
1307   if (hasExternalLexicalStorage())
1308     LoadLexicalDeclsFromExternalStorage();
1309   return decl_iterator(FirstDecl);
1310 }
1311
1312 bool DeclContext::decls_empty() const {
1313   if (hasExternalLexicalStorage())
1314     LoadLexicalDeclsFromExternalStorage();
1315
1316   return !FirstDecl;
1317 }
1318
1319 bool DeclContext::containsDecl(Decl *D) const {
1320   return (D->getLexicalDeclContext() == this &&
1321           (D->NextInContextAndBits.getPointer() || D == LastDecl));
1322 }
1323
1324 void DeclContext::removeDecl(Decl *D) {
1325   assert(D->getLexicalDeclContext() == this &&
1326          "decl being removed from non-lexical context");
1327   assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
1328          "decl is not in decls list");
1329
1330   // Remove D from the decl chain.  This is O(n) but hopefully rare.
1331   if (D == FirstDecl) {
1332     if (D == LastDecl)
1333       FirstDecl = LastDecl = nullptr;
1334     else
1335       FirstDecl = D->NextInContextAndBits.getPointer();
1336   } else {
1337     for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
1338       assert(I && "decl not found in linked list");
1339       if (I->NextInContextAndBits.getPointer() == D) {
1340         I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
1341         if (D == LastDecl) LastDecl = I;
1342         break;
1343       }
1344     }
1345   }
1346   
1347   // Mark that D is no longer in the decl chain.
1348   D->NextInContextAndBits.setPointer(nullptr);
1349
1350   // Remove D from the lookup table if necessary.
1351   if (isa<NamedDecl>(D)) {
1352     NamedDecl *ND = cast<NamedDecl>(D);
1353
1354     // Remove only decls that have a name
1355     if (!ND->getDeclName()) return;
1356
1357     auto *DC = D->getDeclContext();
1358     do {
1359       StoredDeclsMap *Map = DC->getPrimaryContext()->LookupPtr;
1360       if (Map) {
1361         StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1362         assert(Pos != Map->end() && "no lookup entry for decl");
1363         if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
1364           Pos->second.remove(ND);
1365       }
1366     } while (DC->isTransparentContext() && (DC = DC->getParent()));
1367   }
1368 }
1369
1370 void DeclContext::addHiddenDecl(Decl *D) {
1371   assert(D->getLexicalDeclContext() == this &&
1372          "Decl inserted into wrong lexical context");
1373   assert(!D->getNextDeclInContext() && D != LastDecl &&
1374          "Decl already inserted into a DeclContext");
1375
1376   if (FirstDecl) {
1377     LastDecl->NextInContextAndBits.setPointer(D);
1378     LastDecl = D;
1379   } else {
1380     FirstDecl = LastDecl = D;
1381   }
1382
1383   // Notify a C++ record declaration that we've added a member, so it can
1384   // update its class-specific state.
1385   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1386     Record->addedMember(D);
1387
1388   // If this is a newly-created (not de-serialized) import declaration, wire
1389   // it in to the list of local import declarations.
1390   if (!D->isFromASTFile()) {
1391     if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
1392       D->getASTContext().addedLocalImportDecl(Import);
1393   }
1394 }
1395
1396 void DeclContext::addDecl(Decl *D) {
1397   addHiddenDecl(D);
1398
1399   if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1400     ND->getDeclContext()->getPrimaryContext()->
1401         makeDeclVisibleInContextWithFlags(ND, false, true);
1402 }
1403
1404 void DeclContext::addDeclInternal(Decl *D) {
1405   addHiddenDecl(D);
1406
1407   if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1408     ND->getDeclContext()->getPrimaryContext()->
1409         makeDeclVisibleInContextWithFlags(ND, true, true);
1410 }
1411
1412 /// shouldBeHidden - Determine whether a declaration which was declared
1413 /// within its semantic context should be invisible to qualified name lookup.
1414 static bool shouldBeHidden(NamedDecl *D) {
1415   // Skip unnamed declarations.
1416   if (!D->getDeclName())
1417     return true;
1418
1419   // Skip entities that can't be found by name lookup into a particular
1420   // context.
1421   if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1422       D->isTemplateParameter())
1423     return true;
1424
1425   // Skip template specializations.
1426   // FIXME: This feels like a hack. Should DeclarationName support
1427   // template-ids, or is there a better way to keep specializations
1428   // from being visible?
1429   if (isa<ClassTemplateSpecializationDecl>(D))
1430     return true;
1431   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1432     if (FD->isFunctionTemplateSpecialization())
1433       return true;
1434
1435   return false;
1436 }
1437
1438 /// buildLookup - Build the lookup data structure with all of the
1439 /// declarations in this DeclContext (and any other contexts linked
1440 /// to it or transparent contexts nested within it) and return it.
1441 ///
1442 /// Note that the produced map may miss out declarations from an
1443 /// external source. If it does, those entries will be marked with
1444 /// the 'hasExternalDecls' flag.
1445 StoredDeclsMap *DeclContext::buildLookup() {
1446   assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1447
1448   if (!HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups)
1449     return LookupPtr;
1450
1451   SmallVector<DeclContext *, 2> Contexts;
1452   collectAllContexts(Contexts);
1453
1454   if (HasLazyExternalLexicalLookups) {
1455     HasLazyExternalLexicalLookups = false;
1456     for (auto *DC : Contexts) {
1457       if (DC->hasExternalLexicalStorage())
1458         HasLazyLocalLexicalLookups |=
1459             DC->LoadLexicalDeclsFromExternalStorage();
1460     }
1461
1462     if (!HasLazyLocalLexicalLookups)
1463       return LookupPtr;
1464   }
1465
1466   for (auto *DC : Contexts)
1467     buildLookupImpl(DC, hasExternalVisibleStorage());
1468
1469   // We no longer have any lazy decls.
1470   HasLazyLocalLexicalLookups = false;
1471   return LookupPtr;
1472 }
1473
1474 /// buildLookupImpl - Build part of the lookup data structure for the
1475 /// declarations contained within DCtx, which will either be this
1476 /// DeclContext, a DeclContext linked to it, or a transparent context
1477 /// nested within it.
1478 void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {
1479   for (Decl *D : DCtx->noload_decls()) {
1480     // Insert this declaration into the lookup structure, but only if
1481     // it's semantically within its decl context. Any other decls which
1482     // should be found in this context are added eagerly.
1483     //
1484     // If it's from an AST file, don't add it now. It'll get handled by
1485     // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1486     // in C++, we do not track external visible decls for the TU, so in
1487     // that case we need to collect them all here.
1488     if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1489       if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1490           (!ND->isFromASTFile() ||
1491            (isTranslationUnit() &&
1492             !getParentASTContext().getLangOpts().CPlusPlus)))
1493         makeDeclVisibleInContextImpl(ND, Internal);
1494
1495     // If this declaration is itself a transparent declaration context
1496     // or inline namespace, add the members of this declaration of that
1497     // context (recursively).
1498     if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
1499       if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1500         buildLookupImpl(InnerCtx, Internal);
1501   }
1502 }
1503
1504 NamedDecl *const DeclContextLookupResult::SingleElementDummyList = nullptr;
1505
1506 DeclContext::lookup_result
1507 DeclContext::lookup(DeclarationName Name) const {
1508   assert(DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export &&
1509          "should not perform lookups into transparent contexts");
1510
1511   const DeclContext *PrimaryContext = getPrimaryContext();
1512   if (PrimaryContext != this)
1513     return PrimaryContext->lookup(Name);
1514
1515   // If we have an external source, ensure that any later redeclarations of this
1516   // context have been loaded, since they may add names to the result of this
1517   // lookup (or add external visible storage).
1518   ExternalASTSource *Source = getParentASTContext().getExternalSource();
1519   if (Source)
1520     (void)cast<Decl>(this)->getMostRecentDecl();
1521
1522   if (hasExternalVisibleStorage()) {
1523     assert(Source && "external visible storage but no external source?");
1524
1525     if (NeedToReconcileExternalVisibleStorage)
1526       reconcileExternalVisibleStorage();
1527
1528     StoredDeclsMap *Map = LookupPtr;
1529
1530     if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
1531       // FIXME: Make buildLookup const?
1532       Map = const_cast<DeclContext*>(this)->buildLookup();
1533
1534     if (!Map)
1535       Map = CreateStoredDeclsMap(getParentASTContext());
1536
1537     // If we have a lookup result with no external decls, we are done.
1538     std::pair<StoredDeclsMap::iterator, bool> R =
1539         Map->insert(std::make_pair(Name, StoredDeclsList()));
1540     if (!R.second && !R.first->second.hasExternalDecls())
1541       return R.first->second.getLookupResult();
1542
1543     if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) {
1544       if (StoredDeclsMap *Map = LookupPtr) {
1545         StoredDeclsMap::iterator I = Map->find(Name);
1546         if (I != Map->end())
1547           return I->second.getLookupResult();
1548       }
1549     }
1550
1551     return lookup_result();
1552   }
1553
1554   StoredDeclsMap *Map = LookupPtr;
1555   if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
1556     Map = const_cast<DeclContext*>(this)->buildLookup();
1557
1558   if (!Map)
1559     return lookup_result();
1560
1561   StoredDeclsMap::iterator I = Map->find(Name);
1562   if (I == Map->end())
1563     return lookup_result();
1564
1565   return I->second.getLookupResult();
1566 }
1567
1568 DeclContext::lookup_result
1569 DeclContext::noload_lookup(DeclarationName Name) {
1570   assert(DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export &&
1571          "should not perform lookups into transparent contexts");
1572
1573   DeclContext *PrimaryContext = getPrimaryContext();
1574   if (PrimaryContext != this)
1575     return PrimaryContext->noload_lookup(Name);
1576
1577   // If we have any lazy lexical declarations not in our lookup map, add them
1578   // now. Don't import any external declarations, not even if we know we have
1579   // some missing from the external visible lookups.
1580   if (HasLazyLocalLexicalLookups) {
1581     SmallVector<DeclContext *, 2> Contexts;
1582     collectAllContexts(Contexts);
1583     for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
1584       buildLookupImpl(Contexts[I], hasExternalVisibleStorage());
1585     HasLazyLocalLexicalLookups = false;
1586   }
1587
1588   StoredDeclsMap *Map = LookupPtr;
1589   if (!Map)
1590     return lookup_result();
1591
1592   StoredDeclsMap::iterator I = Map->find(Name);
1593   return I != Map->end() ? I->second.getLookupResult()
1594                          : lookup_result();
1595 }
1596
1597 void DeclContext::localUncachedLookup(DeclarationName Name,
1598                                       SmallVectorImpl<NamedDecl *> &Results) {
1599   Results.clear();
1600   
1601   // If there's no external storage, just perform a normal lookup and copy
1602   // the results.
1603   if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
1604     lookup_result LookupResults = lookup(Name);
1605     Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
1606     return;
1607   }
1608
1609   // If we have a lookup table, check there first. Maybe we'll get lucky.
1610   // FIXME: Should we be checking these flags on the primary context?
1611   if (Name && !HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups) {
1612     if (StoredDeclsMap *Map = LookupPtr) {
1613       StoredDeclsMap::iterator Pos = Map->find(Name);
1614       if (Pos != Map->end()) {
1615         Results.insert(Results.end(),
1616                        Pos->second.getLookupResult().begin(),
1617                        Pos->second.getLookupResult().end());
1618         return;
1619       }
1620     }
1621   }
1622
1623   // Slow case: grovel through the declarations in our chain looking for 
1624   // matches.
1625   // FIXME: If we have lazy external declarations, this will not find them!
1626   // FIXME: Should we CollectAllContexts and walk them all here?
1627   for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1628     if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1629       if (ND->getDeclName() == Name)
1630         Results.push_back(ND);
1631   }
1632 }
1633
1634 DeclContext *DeclContext::getRedeclContext() {
1635   DeclContext *Ctx = this;
1636   // Skip through transparent contexts.
1637   while (Ctx->isTransparentContext())
1638     Ctx = Ctx->getParent();
1639   return Ctx;
1640 }
1641
1642 DeclContext *DeclContext::getEnclosingNamespaceContext() {
1643   DeclContext *Ctx = this;
1644   // Skip through non-namespace, non-translation-unit contexts.
1645   while (!Ctx->isFileContext())
1646     Ctx = Ctx->getParent();
1647   return Ctx->getPrimaryContext();
1648 }
1649
1650 RecordDecl *DeclContext::getOuterLexicalRecordContext() {
1651   // Loop until we find a non-record context.
1652   RecordDecl *OutermostRD = nullptr;
1653   DeclContext *DC = this;
1654   while (DC->isRecord()) {
1655     OutermostRD = cast<RecordDecl>(DC);
1656     DC = DC->getLexicalParent();
1657   }
1658   return OutermostRD;
1659 }
1660
1661 bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1662   // For non-file contexts, this is equivalent to Equals.
1663   if (!isFileContext())
1664     return O->Equals(this);
1665
1666   do {
1667     if (O->Equals(this))
1668       return true;
1669
1670     const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1671     if (!NS || !NS->isInline())
1672       break;
1673     O = NS->getParent();
1674   } while (O);
1675
1676   return false;
1677 }
1678
1679 void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1680   DeclContext *PrimaryDC = this->getPrimaryContext();
1681   DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1682   // If the decl is being added outside of its semantic decl context, we
1683   // need to ensure that we eagerly build the lookup information for it.
1684   PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
1685 }
1686
1687 void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1688                                                     bool Recoverable) {
1689   assert(this == getPrimaryContext() && "expected a primary DC");
1690
1691   if (!isLookupContext()) {
1692     if (isTransparentContext())
1693       getParent()->getPrimaryContext()
1694         ->makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1695     return;
1696   }
1697
1698   // Skip declarations which should be invisible to name lookup.
1699   if (shouldBeHidden(D))
1700     return;
1701
1702   // If we already have a lookup data structure, perform the insertion into
1703   // it. If we might have externally-stored decls with this name, look them
1704   // up and perform the insertion. If this decl was declared outside its
1705   // semantic context, buildLookup won't add it, so add it now.
1706   //
1707   // FIXME: As a performance hack, don't add such decls into the translation
1708   // unit unless we're in C++, since qualified lookup into the TU is never
1709   // performed.
1710   if (LookupPtr || hasExternalVisibleStorage() ||
1711       ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1712        (getParentASTContext().getLangOpts().CPlusPlus ||
1713         !isTranslationUnit()))) {
1714     // If we have lazily omitted any decls, they might have the same name as
1715     // the decl which we are adding, so build a full lookup table before adding
1716     // this decl.
1717     buildLookup();
1718     makeDeclVisibleInContextImpl(D, Internal);
1719   } else {
1720     HasLazyLocalLexicalLookups = true;
1721   }
1722
1723   // If we are a transparent context or inline namespace, insert into our
1724   // parent context, too. This operation is recursive.
1725   if (isTransparentContext() || isInlineNamespace())
1726     getParent()->getPrimaryContext()->
1727         makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1728
1729   Decl *DCAsDecl = cast<Decl>(this);
1730   // Notify that a decl was made visible unless we are a Tag being defined.
1731   if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1732     if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1733       L->AddedVisibleDecl(this, D);
1734 }
1735
1736 void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1737   // Find or create the stored declaration map.
1738   StoredDeclsMap *Map = LookupPtr;
1739   if (!Map) {
1740     ASTContext *C = &getParentASTContext();
1741     Map = CreateStoredDeclsMap(*C);
1742   }
1743
1744   // If there is an external AST source, load any declarations it knows about
1745   // with this declaration's name.
1746   // If the lookup table contains an entry about this name it means that we
1747   // have already checked the external source.
1748   if (!Internal)
1749     if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1750       if (hasExternalVisibleStorage() &&
1751           Map->find(D->getDeclName()) == Map->end())
1752         Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1753
1754   // Insert this declaration into the map.
1755   StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
1756
1757   if (Internal) {
1758     // If this is being added as part of loading an external declaration,
1759     // this may not be the only external declaration with this name.
1760     // In this case, we never try to replace an existing declaration; we'll
1761     // handle that when we finalize the list of declarations for this name.
1762     DeclNameEntries.setHasExternalDecls();
1763     DeclNameEntries.AddSubsequentDecl(D);
1764     return;
1765   }
1766
1767   if (DeclNameEntries.isNull()) {
1768     DeclNameEntries.setOnlyValue(D);
1769     return;
1770   }
1771
1772   if (DeclNameEntries.HandleRedeclaration(D, /*IsKnownNewer*/!Internal)) {
1773     // This declaration has replaced an existing one for which
1774     // declarationReplaces returns true.
1775     return;
1776   }
1777
1778   // Put this declaration into the appropriate slot.
1779   DeclNameEntries.AddSubsequentDecl(D);
1780 }
1781
1782 UsingDirectiveDecl *DeclContext::udir_iterator::operator*() const {
1783   return cast<UsingDirectiveDecl>(*I);
1784 }
1785
1786 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1787 /// this context.
1788 DeclContext::udir_range DeclContext::using_directives() const {
1789   // FIXME: Use something more efficient than normal lookup for using
1790   // directives. In C++, using directives are looked up more than anything else.
1791   lookup_result Result = lookup(UsingDirectiveDecl::getName());
1792   return udir_range(Result.begin(), Result.end());
1793 }
1794
1795 //===----------------------------------------------------------------------===//
1796 // Creation and Destruction of StoredDeclsMaps.                               //
1797 //===----------------------------------------------------------------------===//
1798
1799 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1800   assert(!LookupPtr && "context already has a decls map");
1801   assert(getPrimaryContext() == this &&
1802          "creating decls map on non-primary context");
1803
1804   StoredDeclsMap *M;
1805   bool Dependent = isDependentContext();
1806   if (Dependent)
1807     M = new DependentStoredDeclsMap();
1808   else
1809     M = new StoredDeclsMap();
1810   M->Previous = C.LastSDM;
1811   C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1812   LookupPtr = M;
1813   return M;
1814 }
1815
1816 void ASTContext::ReleaseDeclContextMaps() {
1817   // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1818   // pointer because the subclass doesn't add anything that needs to
1819   // be deleted.
1820   StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1821 }
1822
1823 void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1824   while (Map) {
1825     // Advance the iteration before we invalidate memory.
1826     llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1827
1828     if (Dependent)
1829       delete static_cast<DependentStoredDeclsMap*>(Map);
1830     else
1831       delete Map;
1832
1833     Map = Next.getPointer();
1834     Dependent = Next.getInt();
1835   }
1836 }
1837
1838 DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1839                                                  DeclContext *Parent,
1840                                            const PartialDiagnostic &PDiag) {
1841   assert(Parent->isDependentContext()
1842          && "cannot iterate dependent diagnostics of non-dependent context");
1843   Parent = Parent->getPrimaryContext();
1844   if (!Parent->LookupPtr)
1845     Parent->CreateStoredDeclsMap(C);
1846
1847   DependentStoredDeclsMap *Map =
1848       static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr);
1849
1850   // Allocate the copy of the PartialDiagnostic via the ASTContext's
1851   // BumpPtrAllocator, rather than the ASTContext itself.
1852   PartialDiagnostic::Storage *DiagStorage = nullptr;
1853   if (PDiag.hasStorage())
1854     DiagStorage = new (C) PartialDiagnostic::Storage;
1855   
1856   DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
1857
1858   // TODO: Maybe we shouldn't reverse the order during insertion.
1859   DD->NextDiagnostic = Map->FirstDiagnostic;
1860   Map->FirstDiagnostic = DD;
1861
1862   return DD;
1863 }