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