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