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