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