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 OMPCapturedExpr:
659     case Empty:
660       // Never looked up by name.
661       return 0;
662   }
663 
664   llvm_unreachable("Invalid DeclKind!");
665 }
666 
667 void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
668   assert(!HasAttrs && "Decl already contains attrs.");
669 
670   AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
671   assert(AttrBlank.empty() && "HasAttrs was wrong?");
672 
673   AttrBlank = attrs;
674   HasAttrs = true;
675 }
676 
677 void Decl::dropAttrs() {
678   if (!HasAttrs) return;
679 
680   HasAttrs = false;
681   getASTContext().eraseDeclAttrs(this);
682 }
683 
684 const AttrVec &Decl::getAttrs() const {
685   assert(HasAttrs && "No attrs to get!");
686   return getASTContext().getDeclAttrs(this);
687 }
688 
689 Decl *Decl::castFromDeclContext (const DeclContext *D) {
690   Decl::Kind DK = D->getDeclKind();
691   switch(DK) {
692 #define DECL(NAME, BASE)
693 #define DECL_CONTEXT(NAME) \
694     case Decl::NAME:       \
695       return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
696 #define DECL_CONTEXT_BASE(NAME)
697 #include "clang/AST/DeclNodes.inc"
698     default:
699 #define DECL(NAME, BASE)
700 #define DECL_CONTEXT_BASE(NAME)                  \
701       if (DK >= first##NAME && DK <= last##NAME) \
702         return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
703 #include "clang/AST/DeclNodes.inc"
704       llvm_unreachable("a decl that inherits DeclContext isn't handled");
705   }
706 }
707 
708 DeclContext *Decl::castToDeclContext(const Decl *D) {
709   Decl::Kind DK = D->getKind();
710   switch(DK) {
711 #define DECL(NAME, BASE)
712 #define DECL_CONTEXT(NAME) \
713     case Decl::NAME:       \
714       return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
715 #define DECL_CONTEXT_BASE(NAME)
716 #include "clang/AST/DeclNodes.inc"
717     default:
718 #define DECL(NAME, BASE)
719 #define DECL_CONTEXT_BASE(NAME)                                   \
720       if (DK >= first##NAME && DK <= last##NAME)                  \
721         return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
722 #include "clang/AST/DeclNodes.inc"
723       llvm_unreachable("a decl that inherits DeclContext isn't handled");
724   }
725 }
726 
727 SourceLocation Decl::getBodyRBrace() const {
728   // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
729   // FunctionDecl stores EndRangeLoc for this purpose.
730   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
731     const FunctionDecl *Definition;
732     if (FD->hasBody(Definition))
733       return Definition->getSourceRange().getEnd();
734     return SourceLocation();
735   }
736 
737   if (Stmt *Body = getBody())
738     return Body->getSourceRange().getEnd();
739 
740   return SourceLocation();
741 }
742 
743 bool Decl::AccessDeclContextSanity() const {
744 #ifndef NDEBUG
745   // Suppress this check if any of the following hold:
746   // 1. this is the translation unit (and thus has no parent)
747   // 2. this is a template parameter (and thus doesn't belong to its context)
748   // 3. this is a non-type template parameter
749   // 4. the context is not a record
750   // 5. it's invalid
751   // 6. it's a C++0x static_assert.
752   if (isa<TranslationUnitDecl>(this) ||
753       isa<TemplateTypeParmDecl>(this) ||
754       isa<NonTypeTemplateParmDecl>(this) ||
755       !isa<CXXRecordDecl>(getDeclContext()) ||
756       isInvalidDecl() ||
757       isa<StaticAssertDecl>(this) ||
758       // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
759       // as DeclContext (?).
760       isa<ParmVarDecl>(this) ||
761       // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
762       // AS_none as access specifier.
763       isa<CXXRecordDecl>(this) ||
764       isa<ClassScopeFunctionSpecializationDecl>(this))
765     return true;
766 
767   assert(Access != AS_none &&
768          "Access specifier is AS_none inside a record decl");
769 #endif
770   return true;
771 }
772 
773 static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
774 static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
775 
776 const FunctionType *Decl::getFunctionType(bool BlocksToo) const {
777   QualType Ty;
778   if (const ValueDecl *D = dyn_cast<ValueDecl>(this))
779     Ty = D->getType();
780   else if (const TypedefNameDecl *D = dyn_cast<TypedefNameDecl>(this))
781     Ty = D->getUnderlyingType();
782   else
783     return nullptr;
784 
785   if (Ty->isFunctionPointerType())
786     Ty = Ty->getAs<PointerType>()->getPointeeType();
787   else if (BlocksToo && Ty->isBlockPointerType())
788     Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
789 
790   return Ty->getAs<FunctionType>();
791 }
792 
793 
794 /// Starting at a given context (a Decl or DeclContext), look for a
795 /// code context that is not a closure (a lambda, block, etc.).
796 template <class T> static Decl *getNonClosureContext(T *D) {
797   if (getKind(D) == Decl::CXXMethod) {
798     CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
799     if (MD->getOverloadedOperator() == OO_Call &&
800         MD->getParent()->isLambda())
801       return getNonClosureContext(MD->getParent()->getParent());
802     return MD;
803   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
804     return FD;
805   } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
806     return MD;
807   } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
808     return getNonClosureContext(BD->getParent());
809   } else if (CapturedDecl *CD = dyn_cast<CapturedDecl>(D)) {
810     return getNonClosureContext(CD->getParent());
811   } else {
812     return nullptr;
813   }
814 }
815 
816 Decl *Decl::getNonClosureContext() {
817   return ::getNonClosureContext(this);
818 }
819 
820 Decl *DeclContext::getNonClosureAncestor() {
821   return ::getNonClosureContext(this);
822 }
823 
824 //===----------------------------------------------------------------------===//
825 // DeclContext Implementation
826 //===----------------------------------------------------------------------===//
827 
828 bool DeclContext::classof(const Decl *D) {
829   switch (D->getKind()) {
830 #define DECL(NAME, BASE)
831 #define DECL_CONTEXT(NAME) case Decl::NAME:
832 #define DECL_CONTEXT_BASE(NAME)
833 #include "clang/AST/DeclNodes.inc"
834       return true;
835     default:
836 #define DECL(NAME, BASE)
837 #define DECL_CONTEXT_BASE(NAME)                 \
838       if (D->getKind() >= Decl::first##NAME &&  \
839           D->getKind() <= Decl::last##NAME)     \
840         return true;
841 #include "clang/AST/DeclNodes.inc"
842       return false;
843   }
844 }
845 
846 DeclContext::~DeclContext() { }
847 
848 /// \brief Find the parent context of this context that will be
849 /// used for unqualified name lookup.
850 ///
851 /// Generally, the parent lookup context is the semantic context. However, for
852 /// a friend function the parent lookup context is the lexical context, which
853 /// is the class in which the friend is declared.
854 DeclContext *DeclContext::getLookupParent() {
855   // FIXME: Find a better way to identify friends
856   if (isa<FunctionDecl>(this))
857     if (getParent()->getRedeclContext()->isFileContext() &&
858         getLexicalParent()->getRedeclContext()->isRecord())
859       return getLexicalParent();
860 
861   return getParent();
862 }
863 
864 bool DeclContext::isInlineNamespace() const {
865   return isNamespace() &&
866          cast<NamespaceDecl>(this)->isInline();
867 }
868 
869 bool DeclContext::isStdNamespace() const {
870   if (!isNamespace())
871     return false;
872 
873   const NamespaceDecl *ND = cast<NamespaceDecl>(this);
874   if (ND->isInline()) {
875     return ND->getParent()->isStdNamespace();
876   }
877 
878   if (!getParent()->getRedeclContext()->isTranslationUnit())
879     return false;
880 
881   const IdentifierInfo *II = ND->getIdentifier();
882   return II && II->isStr("std");
883 }
884 
885 bool DeclContext::isDependentContext() const {
886   if (isFileContext())
887     return false;
888 
889   if (isa<ClassTemplatePartialSpecializationDecl>(this))
890     return true;
891 
892   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
893     if (Record->getDescribedClassTemplate())
894       return true;
895 
896     if (Record->isDependentLambda())
897       return true;
898   }
899 
900   if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
901     if (Function->getDescribedFunctionTemplate())
902       return true;
903 
904     // Friend function declarations are dependent if their *lexical*
905     // context is dependent.
906     if (cast<Decl>(this)->getFriendObjectKind())
907       return getLexicalParent()->isDependentContext();
908   }
909 
910   // FIXME: A variable template is a dependent context, but is not a
911   // DeclContext. A context within it (such as a lambda-expression)
912   // should be considered dependent.
913 
914   return getParent() && getParent()->isDependentContext();
915 }
916 
917 bool DeclContext::isTransparentContext() const {
918   if (DeclKind == Decl::Enum)
919     return !cast<EnumDecl>(this)->isScoped();
920   else if (DeclKind == Decl::LinkageSpec)
921     return true;
922 
923   return false;
924 }
925 
926 static bool isLinkageSpecContext(const DeclContext *DC,
927                                  LinkageSpecDecl::LanguageIDs ID) {
928   while (DC->getDeclKind() != Decl::TranslationUnit) {
929     if (DC->getDeclKind() == Decl::LinkageSpec)
930       return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
931     DC = DC->getLexicalParent();
932   }
933   return false;
934 }
935 
936 bool DeclContext::isExternCContext() const {
937   return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_c);
938 }
939 
940 bool DeclContext::isExternCXXContext() const {
941   return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_cxx);
942 }
943 
944 bool DeclContext::Encloses(const DeclContext *DC) const {
945   if (getPrimaryContext() != this)
946     return getPrimaryContext()->Encloses(DC);
947 
948   for (; DC; DC = DC->getParent())
949     if (DC->getPrimaryContext() == this)
950       return true;
951   return false;
952 }
953 
954 DeclContext *DeclContext::getPrimaryContext() {
955   switch (DeclKind) {
956   case Decl::TranslationUnit:
957   case Decl::ExternCContext:
958   case Decl::LinkageSpec:
959   case Decl::Block:
960   case Decl::Captured:
961     // There is only one DeclContext for these entities.
962     return this;
963 
964   case Decl::Namespace:
965     // The original namespace is our primary context.
966     return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
967 
968   case Decl::ObjCMethod:
969     return this;
970 
971   case Decl::ObjCInterface:
972     if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
973       return Def;
974 
975     return this;
976 
977   case Decl::ObjCProtocol:
978     if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
979       return Def;
980 
981     return this;
982 
983   case Decl::ObjCCategory:
984     return this;
985 
986   case Decl::ObjCImplementation:
987   case Decl::ObjCCategoryImpl:
988     return this;
989 
990   default:
991     if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
992       // If this is a tag type that has a definition or is currently
993       // being defined, that definition is our primary context.
994       TagDecl *Tag = cast<TagDecl>(this);
995 
996       if (TagDecl *Def = Tag->getDefinition())
997         return Def;
998 
999       if (const TagType *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) {
1000         // Note, TagType::getDecl returns the (partial) definition one exists.
1001         TagDecl *PossiblePartialDef = TagTy->getDecl();
1002         if (PossiblePartialDef->isBeingDefined())
1003           return PossiblePartialDef;
1004       } else {
1005         assert(isa<InjectedClassNameType>(Tag->getTypeForDecl()));
1006       }
1007 
1008       return Tag;
1009     }
1010 
1011     assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
1012           "Unknown DeclContext kind");
1013     return this;
1014   }
1015 }
1016 
1017 void
1018 DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
1019   Contexts.clear();
1020 
1021   if (DeclKind != Decl::Namespace) {
1022     Contexts.push_back(this);
1023     return;
1024   }
1025 
1026   NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
1027   for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
1028        N = N->getPreviousDecl())
1029     Contexts.push_back(N);
1030 
1031   std::reverse(Contexts.begin(), Contexts.end());
1032 }
1033 
1034 std::pair<Decl *, Decl *>
1035 DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
1036                             bool FieldsAlreadyLoaded) {
1037   // Build up a chain of declarations via the Decl::NextInContextAndBits field.
1038   Decl *FirstNewDecl = nullptr;
1039   Decl *PrevDecl = nullptr;
1040   for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1041     if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
1042       continue;
1043 
1044     Decl *D = Decls[I];
1045     if (PrevDecl)
1046       PrevDecl->NextInContextAndBits.setPointer(D);
1047     else
1048       FirstNewDecl = D;
1049 
1050     PrevDecl = D;
1051   }
1052 
1053   return std::make_pair(FirstNewDecl, PrevDecl);
1054 }
1055 
1056 /// \brief We have just acquired external visible storage, and we already have
1057 /// built a lookup map. For every name in the map, pull in the new names from
1058 /// the external storage.
1059 void DeclContext::reconcileExternalVisibleStorage() const {
1060   assert(NeedToReconcileExternalVisibleStorage && LookupPtr);
1061   NeedToReconcileExternalVisibleStorage = false;
1062 
1063   for (auto &Lookup : *LookupPtr)
1064     Lookup.second.setHasExternalDecls();
1065 }
1066 
1067 /// \brief Load the declarations within this lexical storage from an
1068 /// external source.
1069 /// \return \c true if any declarations were added.
1070 bool
1071 DeclContext::LoadLexicalDeclsFromExternalStorage() const {
1072   ExternalASTSource *Source = getParentASTContext().getExternalSource();
1073   assert(hasExternalLexicalStorage() && Source && "No external storage?");
1074 
1075   // Notify that we have a DeclContext that is initializing.
1076   ExternalASTSource::Deserializing ADeclContext(Source);
1077 
1078   // Load the external declarations, if any.
1079   SmallVector<Decl*, 64> Decls;
1080   ExternalLexicalStorage = false;
1081   Source->FindExternalLexicalDecls(this, Decls);
1082 
1083   if (Decls.empty())
1084     return false;
1085 
1086   // We may have already loaded just the fields of this record, in which case
1087   // we need to ignore them.
1088   bool FieldsAlreadyLoaded = false;
1089   if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
1090     FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
1091 
1092   // Splice the newly-read declarations into the beginning of the list
1093   // of declarations.
1094   Decl *ExternalFirst, *ExternalLast;
1095   std::tie(ExternalFirst, ExternalLast) =
1096       BuildDeclChain(Decls, FieldsAlreadyLoaded);
1097   ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
1098   FirstDecl = ExternalFirst;
1099   if (!LastDecl)
1100     LastDecl = ExternalLast;
1101   return true;
1102 }
1103 
1104 DeclContext::lookup_result
1105 ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
1106                                                     DeclarationName Name) {
1107   ASTContext &Context = DC->getParentASTContext();
1108   StoredDeclsMap *Map;
1109   if (!(Map = DC->LookupPtr))
1110     Map = DC->CreateStoredDeclsMap(Context);
1111   if (DC->NeedToReconcileExternalVisibleStorage)
1112     DC->reconcileExternalVisibleStorage();
1113 
1114   (*Map)[Name].removeExternalDecls();
1115 
1116   return DeclContext::lookup_result();
1117 }
1118 
1119 DeclContext::lookup_result
1120 ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
1121                                                   DeclarationName Name,
1122                                                   ArrayRef<NamedDecl*> Decls) {
1123   ASTContext &Context = DC->getParentASTContext();
1124   StoredDeclsMap *Map;
1125   if (!(Map = DC->LookupPtr))
1126     Map = DC->CreateStoredDeclsMap(Context);
1127   if (DC->NeedToReconcileExternalVisibleStorage)
1128     DC->reconcileExternalVisibleStorage();
1129 
1130   StoredDeclsList &List = (*Map)[Name];
1131 
1132   // Clear out any old external visible declarations, to avoid quadratic
1133   // performance in the redeclaration checks below.
1134   List.removeExternalDecls();
1135 
1136   if (!List.isNull()) {
1137     // We have both existing declarations and new declarations for this name.
1138     // Some of the declarations may simply replace existing ones. Handle those
1139     // first.
1140     llvm::SmallVector<unsigned, 8> Skip;
1141     for (unsigned I = 0, N = Decls.size(); I != N; ++I)
1142       if (List.HandleRedeclaration(Decls[I], /*IsKnownNewer*/false))
1143         Skip.push_back(I);
1144     Skip.push_back(Decls.size());
1145 
1146     // Add in any new declarations.
1147     unsigned SkipPos = 0;
1148     for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1149       if (I == Skip[SkipPos])
1150         ++SkipPos;
1151       else
1152         List.AddSubsequentDecl(Decls[I]);
1153     }
1154   } else {
1155     // Convert the array to a StoredDeclsList.
1156     for (ArrayRef<NamedDecl*>::iterator
1157            I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1158       if (List.isNull())
1159         List.setOnlyValue(*I);
1160       else
1161         List.AddSubsequentDecl(*I);
1162     }
1163   }
1164 
1165   return List.getLookupResult();
1166 }
1167 
1168 DeclContext::decl_iterator DeclContext::decls_begin() const {
1169   if (hasExternalLexicalStorage())
1170     LoadLexicalDeclsFromExternalStorage();
1171   return decl_iterator(FirstDecl);
1172 }
1173 
1174 bool DeclContext::decls_empty() const {
1175   if (hasExternalLexicalStorage())
1176     LoadLexicalDeclsFromExternalStorage();
1177 
1178   return !FirstDecl;
1179 }
1180 
1181 bool DeclContext::containsDecl(Decl *D) const {
1182   return (D->getLexicalDeclContext() == this &&
1183           (D->NextInContextAndBits.getPointer() || D == LastDecl));
1184 }
1185 
1186 void DeclContext::removeDecl(Decl *D) {
1187   assert(D->getLexicalDeclContext() == this &&
1188          "decl being removed from non-lexical context");
1189   assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
1190          "decl is not in decls list");
1191 
1192   // Remove D from the decl chain.  This is O(n) but hopefully rare.
1193   if (D == FirstDecl) {
1194     if (D == LastDecl)
1195       FirstDecl = LastDecl = nullptr;
1196     else
1197       FirstDecl = D->NextInContextAndBits.getPointer();
1198   } else {
1199     for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
1200       assert(I && "decl not found in linked list");
1201       if (I->NextInContextAndBits.getPointer() == D) {
1202         I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
1203         if (D == LastDecl) LastDecl = I;
1204         break;
1205       }
1206     }
1207   }
1208 
1209   // Mark that D is no longer in the decl chain.
1210   D->NextInContextAndBits.setPointer(nullptr);
1211 
1212   // Remove D from the lookup table if necessary.
1213   if (isa<NamedDecl>(D)) {
1214     NamedDecl *ND = cast<NamedDecl>(D);
1215 
1216     // Remove only decls that have a name
1217     if (!ND->getDeclName()) return;
1218 
1219     auto *DC = this;
1220     do {
1221       StoredDeclsMap *Map = DC->getPrimaryContext()->LookupPtr;
1222       if (Map) {
1223         StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1224         assert(Pos != Map->end() && "no lookup entry for decl");
1225         if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
1226           Pos->second.remove(ND);
1227       }
1228     } while (DC->isTransparentContext() && (DC = DC->getParent()));
1229   }
1230 }
1231 
1232 void DeclContext::addHiddenDecl(Decl *D) {
1233   assert(D->getLexicalDeclContext() == this &&
1234          "Decl inserted into wrong lexical context");
1235   assert(!D->getNextDeclInContext() && D != LastDecl &&
1236          "Decl already inserted into a DeclContext");
1237 
1238   if (FirstDecl) {
1239     LastDecl->NextInContextAndBits.setPointer(D);
1240     LastDecl = D;
1241   } else {
1242     FirstDecl = LastDecl = D;
1243   }
1244 
1245   // Notify a C++ record declaration that we've added a member, so it can
1246   // update its class-specific state.
1247   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1248     Record->addedMember(D);
1249 
1250   // If this is a newly-created (not de-serialized) import declaration, wire
1251   // it in to the list of local import declarations.
1252   if (!D->isFromASTFile()) {
1253     if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
1254       D->getASTContext().addedLocalImportDecl(Import);
1255   }
1256 }
1257 
1258 void DeclContext::addDecl(Decl *D) {
1259   addHiddenDecl(D);
1260 
1261   if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1262     ND->getDeclContext()->getPrimaryContext()->
1263         makeDeclVisibleInContextWithFlags(ND, false, true);
1264 }
1265 
1266 void DeclContext::addDeclInternal(Decl *D) {
1267   addHiddenDecl(D);
1268 
1269   if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1270     ND->getDeclContext()->getPrimaryContext()->
1271         makeDeclVisibleInContextWithFlags(ND, true, true);
1272 }
1273 
1274 /// shouldBeHidden - Determine whether a declaration which was declared
1275 /// within its semantic context should be invisible to qualified name lookup.
1276 static bool shouldBeHidden(NamedDecl *D) {
1277   // Skip unnamed declarations.
1278   if (!D->getDeclName())
1279     return true;
1280 
1281   // Skip entities that can't be found by name lookup into a particular
1282   // context.
1283   if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1284       D->isTemplateParameter())
1285     return true;
1286 
1287   // Skip template specializations.
1288   // FIXME: This feels like a hack. Should DeclarationName support
1289   // template-ids, or is there a better way to keep specializations
1290   // from being visible?
1291   if (isa<ClassTemplateSpecializationDecl>(D))
1292     return true;
1293   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1294     if (FD->isFunctionTemplateSpecialization())
1295       return true;
1296 
1297   return false;
1298 }
1299 
1300 /// buildLookup - Build the lookup data structure with all of the
1301 /// declarations in this DeclContext (and any other contexts linked
1302 /// to it or transparent contexts nested within it) and return it.
1303 ///
1304 /// Note that the produced map may miss out declarations from an
1305 /// external source. If it does, those entries will be marked with
1306 /// the 'hasExternalDecls' flag.
1307 StoredDeclsMap *DeclContext::buildLookup() {
1308   assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1309 
1310   if (!HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups)
1311     return LookupPtr;
1312 
1313   SmallVector<DeclContext *, 2> Contexts;
1314   collectAllContexts(Contexts);
1315 
1316   if (HasLazyExternalLexicalLookups) {
1317     HasLazyExternalLexicalLookups = false;
1318     for (auto *DC : Contexts) {
1319       if (DC->hasExternalLexicalStorage())
1320         HasLazyLocalLexicalLookups |=
1321             DC->LoadLexicalDeclsFromExternalStorage();
1322     }
1323 
1324     if (!HasLazyLocalLexicalLookups)
1325       return LookupPtr;
1326   }
1327 
1328   for (auto *DC : Contexts)
1329     buildLookupImpl(DC, hasExternalVisibleStorage());
1330 
1331   // We no longer have any lazy decls.
1332   HasLazyLocalLexicalLookups = false;
1333   return LookupPtr;
1334 }
1335 
1336 /// buildLookupImpl - Build part of the lookup data structure for the
1337 /// declarations contained within DCtx, which will either be this
1338 /// DeclContext, a DeclContext linked to it, or a transparent context
1339 /// nested within it.
1340 void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {
1341   for (Decl *D : DCtx->noload_decls()) {
1342     // Insert this declaration into the lookup structure, but only if
1343     // it's semantically within its decl context. Any other decls which
1344     // should be found in this context are added eagerly.
1345     //
1346     // If it's from an AST file, don't add it now. It'll get handled by
1347     // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1348     // in C++, we do not track external visible decls for the TU, so in
1349     // that case we need to collect them all here.
1350     if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1351       if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1352           (!ND->isFromASTFile() ||
1353            (isTranslationUnit() &&
1354             !getParentASTContext().getLangOpts().CPlusPlus)))
1355         makeDeclVisibleInContextImpl(ND, Internal);
1356 
1357     // If this declaration is itself a transparent declaration context
1358     // or inline namespace, add the members of this declaration of that
1359     // context (recursively).
1360     if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
1361       if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1362         buildLookupImpl(InnerCtx, Internal);
1363   }
1364 }
1365 
1366 NamedDecl *const DeclContextLookupResult::SingleElementDummyList = nullptr;
1367 
1368 DeclContext::lookup_result
1369 DeclContext::lookup(DeclarationName Name) const {
1370   assert(DeclKind != Decl::LinkageSpec &&
1371          "Should not perform lookups into linkage specs!");
1372 
1373   const DeclContext *PrimaryContext = getPrimaryContext();
1374   if (PrimaryContext != this)
1375     return PrimaryContext->lookup(Name);
1376 
1377   // If we have an external source, ensure that any later redeclarations of this
1378   // context have been loaded, since they may add names to the result of this
1379   // lookup (or add external visible storage).
1380   ExternalASTSource *Source = getParentASTContext().getExternalSource();
1381   if (Source)
1382     (void)cast<Decl>(this)->getMostRecentDecl();
1383 
1384   if (hasExternalVisibleStorage()) {
1385     assert(Source && "external visible storage but no external source?");
1386 
1387     if (NeedToReconcileExternalVisibleStorage)
1388       reconcileExternalVisibleStorage();
1389 
1390     StoredDeclsMap *Map = LookupPtr;
1391 
1392     if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
1393       // FIXME: Make buildLookup const?
1394       Map = const_cast<DeclContext*>(this)->buildLookup();
1395 
1396     if (!Map)
1397       Map = CreateStoredDeclsMap(getParentASTContext());
1398 
1399     // If we have a lookup result with no external decls, we are done.
1400     std::pair<StoredDeclsMap::iterator, bool> R =
1401         Map->insert(std::make_pair(Name, StoredDeclsList()));
1402     if (!R.second && !R.first->second.hasExternalDecls())
1403       return R.first->second.getLookupResult();
1404 
1405     if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) {
1406       if (StoredDeclsMap *Map = LookupPtr) {
1407         StoredDeclsMap::iterator I = Map->find(Name);
1408         if (I != Map->end())
1409           return I->second.getLookupResult();
1410       }
1411     }
1412 
1413     return lookup_result();
1414   }
1415 
1416   StoredDeclsMap *Map = LookupPtr;
1417   if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
1418     Map = const_cast<DeclContext*>(this)->buildLookup();
1419 
1420   if (!Map)
1421     return lookup_result();
1422 
1423   StoredDeclsMap::iterator I = Map->find(Name);
1424   if (I == Map->end())
1425     return lookup_result();
1426 
1427   return I->second.getLookupResult();
1428 }
1429 
1430 DeclContext::lookup_result
1431 DeclContext::noload_lookup(DeclarationName Name) {
1432   assert(DeclKind != Decl::LinkageSpec &&
1433          "Should not perform lookups into linkage specs!");
1434 
1435   DeclContext *PrimaryContext = getPrimaryContext();
1436   if (PrimaryContext != this)
1437     return PrimaryContext->noload_lookup(Name);
1438 
1439   // If we have any lazy lexical declarations not in our lookup map, add them
1440   // now. Don't import any external declarations, not even if we know we have
1441   // some missing from the external visible lookups.
1442   if (HasLazyLocalLexicalLookups) {
1443     SmallVector<DeclContext *, 2> Contexts;
1444     collectAllContexts(Contexts);
1445     for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
1446       buildLookupImpl(Contexts[I], hasExternalVisibleStorage());
1447     HasLazyLocalLexicalLookups = false;
1448   }
1449 
1450   StoredDeclsMap *Map = LookupPtr;
1451   if (!Map)
1452     return lookup_result();
1453 
1454   StoredDeclsMap::iterator I = Map->find(Name);
1455   return I != Map->end() ? I->second.getLookupResult()
1456                          : lookup_result();
1457 }
1458 
1459 void DeclContext::localUncachedLookup(DeclarationName Name,
1460                                       SmallVectorImpl<NamedDecl *> &Results) {
1461   Results.clear();
1462 
1463   // If there's no external storage, just perform a normal lookup and copy
1464   // the results.
1465   if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
1466     lookup_result LookupResults = lookup(Name);
1467     Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
1468     return;
1469   }
1470 
1471   // If we have a lookup table, check there first. Maybe we'll get lucky.
1472   // FIXME: Should we be checking these flags on the primary context?
1473   if (Name && !HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups) {
1474     if (StoredDeclsMap *Map = LookupPtr) {
1475       StoredDeclsMap::iterator Pos = Map->find(Name);
1476       if (Pos != Map->end()) {
1477         Results.insert(Results.end(),
1478                        Pos->second.getLookupResult().begin(),
1479                        Pos->second.getLookupResult().end());
1480         return;
1481       }
1482     }
1483   }
1484 
1485   // Slow case: grovel through the declarations in our chain looking for
1486   // matches.
1487   // FIXME: If we have lazy external declarations, this will not find them!
1488   // FIXME: Should we CollectAllContexts and walk them all here?
1489   for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1490     if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1491       if (ND->getDeclName() == Name)
1492         Results.push_back(ND);
1493   }
1494 }
1495 
1496 DeclContext *DeclContext::getRedeclContext() {
1497   DeclContext *Ctx = this;
1498   // Skip through transparent contexts.
1499   while (Ctx->isTransparentContext())
1500     Ctx = Ctx->getParent();
1501   return Ctx;
1502 }
1503 
1504 DeclContext *DeclContext::getEnclosingNamespaceContext() {
1505   DeclContext *Ctx = this;
1506   // Skip through non-namespace, non-translation-unit contexts.
1507   while (!Ctx->isFileContext())
1508     Ctx = Ctx->getParent();
1509   return Ctx->getPrimaryContext();
1510 }
1511 
1512 RecordDecl *DeclContext::getOuterLexicalRecordContext() {
1513   // Loop until we find a non-record context.
1514   RecordDecl *OutermostRD = nullptr;
1515   DeclContext *DC = this;
1516   while (DC->isRecord()) {
1517     OutermostRD = cast<RecordDecl>(DC);
1518     DC = DC->getLexicalParent();
1519   }
1520   return OutermostRD;
1521 }
1522 
1523 bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1524   // For non-file contexts, this is equivalent to Equals.
1525   if (!isFileContext())
1526     return O->Equals(this);
1527 
1528   do {
1529     if (O->Equals(this))
1530       return true;
1531 
1532     const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1533     if (!NS || !NS->isInline())
1534       break;
1535     O = NS->getParent();
1536   } while (O);
1537 
1538   return false;
1539 }
1540 
1541 void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1542   DeclContext *PrimaryDC = this->getPrimaryContext();
1543   DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1544   // If the decl is being added outside of its semantic decl context, we
1545   // need to ensure that we eagerly build the lookup information for it.
1546   PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
1547 }
1548 
1549 void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1550                                                     bool Recoverable) {
1551   assert(this == getPrimaryContext() && "expected a primary DC");
1552 
1553   // Skip declarations within functions.
1554   if (isFunctionOrMethod())
1555     return;
1556 
1557   // Skip declarations which should be invisible to name lookup.
1558   if (shouldBeHidden(D))
1559     return;
1560 
1561   // If we already have a lookup data structure, perform the insertion into
1562   // it. If we might have externally-stored decls with this name, look them
1563   // up and perform the insertion. If this decl was declared outside its
1564   // semantic context, buildLookup won't add it, so add it now.
1565   //
1566   // FIXME: As a performance hack, don't add such decls into the translation
1567   // unit unless we're in C++, since qualified lookup into the TU is never
1568   // performed.
1569   if (LookupPtr || hasExternalVisibleStorage() ||
1570       ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1571        (getParentASTContext().getLangOpts().CPlusPlus ||
1572         !isTranslationUnit()))) {
1573     // If we have lazily omitted any decls, they might have the same name as
1574     // the decl which we are adding, so build a full lookup table before adding
1575     // this decl.
1576     buildLookup();
1577     makeDeclVisibleInContextImpl(D, Internal);
1578   } else {
1579     HasLazyLocalLexicalLookups = true;
1580   }
1581 
1582   // If we are a transparent context or inline namespace, insert into our
1583   // parent context, too. This operation is recursive.
1584   if (isTransparentContext() || isInlineNamespace())
1585     getParent()->getPrimaryContext()->
1586         makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1587 
1588   Decl *DCAsDecl = cast<Decl>(this);
1589   // Notify that a decl was made visible unless we are a Tag being defined.
1590   if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1591     if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1592       L->AddedVisibleDecl(this, D);
1593 }
1594 
1595 void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1596   // Find or create the stored declaration map.
1597   StoredDeclsMap *Map = LookupPtr;
1598   if (!Map) {
1599     ASTContext *C = &getParentASTContext();
1600     Map = CreateStoredDeclsMap(*C);
1601   }
1602 
1603   // If there is an external AST source, load any declarations it knows about
1604   // with this declaration's name.
1605   // If the lookup table contains an entry about this name it means that we
1606   // have already checked the external source.
1607   if (!Internal)
1608     if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1609       if (hasExternalVisibleStorage() &&
1610           Map->find(D->getDeclName()) == Map->end())
1611         Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1612 
1613   // Insert this declaration into the map.
1614   StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
1615 
1616   if (Internal) {
1617     // If this is being added as part of loading an external declaration,
1618     // this may not be the only external declaration with this name.
1619     // In this case, we never try to replace an existing declaration; we'll
1620     // handle that when we finalize the list of declarations for this name.
1621     DeclNameEntries.setHasExternalDecls();
1622     DeclNameEntries.AddSubsequentDecl(D);
1623     return;
1624   }
1625 
1626   if (DeclNameEntries.isNull()) {
1627     DeclNameEntries.setOnlyValue(D);
1628     return;
1629   }
1630 
1631   if (DeclNameEntries.HandleRedeclaration(D, /*IsKnownNewer*/!Internal)) {
1632     // This declaration has replaced an existing one for which
1633     // declarationReplaces returns true.
1634     return;
1635   }
1636 
1637   // Put this declaration into the appropriate slot.
1638   DeclNameEntries.AddSubsequentDecl(D);
1639 }
1640 
1641 UsingDirectiveDecl *DeclContext::udir_iterator::operator*() const {
1642   return cast<UsingDirectiveDecl>(*I);
1643 }
1644 
1645 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1646 /// this context.
1647 DeclContext::udir_range DeclContext::using_directives() const {
1648   // FIXME: Use something more efficient than normal lookup for using
1649   // directives. In C++, using directives are looked up more than anything else.
1650   lookup_result Result = lookup(UsingDirectiveDecl::getName());
1651   return udir_range(Result.begin(), Result.end());
1652 }
1653 
1654 //===----------------------------------------------------------------------===//
1655 // Creation and Destruction of StoredDeclsMaps.                               //
1656 //===----------------------------------------------------------------------===//
1657 
1658 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1659   assert(!LookupPtr && "context already has a decls map");
1660   assert(getPrimaryContext() == this &&
1661          "creating decls map on non-primary context");
1662 
1663   StoredDeclsMap *M;
1664   bool Dependent = isDependentContext();
1665   if (Dependent)
1666     M = new DependentStoredDeclsMap();
1667   else
1668     M = new StoredDeclsMap();
1669   M->Previous = C.LastSDM;
1670   C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1671   LookupPtr = M;
1672   return M;
1673 }
1674 
1675 void ASTContext::ReleaseDeclContextMaps() {
1676   // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1677   // pointer because the subclass doesn't add anything that needs to
1678   // be deleted.
1679   StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1680 }
1681 
1682 void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1683   while (Map) {
1684     // Advance the iteration before we invalidate memory.
1685     llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1686 
1687     if (Dependent)
1688       delete static_cast<DependentStoredDeclsMap*>(Map);
1689     else
1690       delete Map;
1691 
1692     Map = Next.getPointer();
1693     Dependent = Next.getInt();
1694   }
1695 }
1696 
1697 DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1698                                                  DeclContext *Parent,
1699                                            const PartialDiagnostic &PDiag) {
1700   assert(Parent->isDependentContext()
1701          && "cannot iterate dependent diagnostics of non-dependent context");
1702   Parent = Parent->getPrimaryContext();
1703   if (!Parent->LookupPtr)
1704     Parent->CreateStoredDeclsMap(C);
1705 
1706   DependentStoredDeclsMap *Map =
1707       static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr);
1708 
1709   // Allocate the copy of the PartialDiagnostic via the ASTContext's
1710   // BumpPtrAllocator, rather than the ASTContext itself.
1711   PartialDiagnostic::Storage *DiagStorage = nullptr;
1712   if (PDiag.hasStorage())
1713     DiagStorage = new (C) PartialDiagnostic::Storage;
1714 
1715   DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
1716 
1717   // TODO: Maybe we shouldn't reverse the order during insertion.
1718   DD->NextDiagnostic = Map->FirstDiagnostic;
1719   Map->FirstDiagnostic = DD;
1720 
1721   return DD;
1722 }
1723