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