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