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