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