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