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