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