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