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