• 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/Decl.h"
16 #include "clang/AST/DeclContextInternals.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclFriend.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/DependentDiagnostic.h"
22 #include "clang/AST/ExternalASTSource.h"
23 #include "clang/AST/ASTContext.h"
24 #include "clang/AST/Type.h"
25 #include "clang/AST/Stmt.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/AST/ASTMutationListener.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include <algorithm>
32 using namespace clang;
33 
34 //===----------------------------------------------------------------------===//
35 //  Statistics
36 //===----------------------------------------------------------------------===//
37 
38 #define DECL(DERIVED, BASE) static int n##DERIVED##s = 0;
39 #define ABSTRACT_DECL(DECL)
40 #include "clang/AST/DeclNodes.inc"
41 
42 static bool StatSwitch = false;
43 
getDeclKindName() const44 const char *Decl::getDeclKindName() const {
45   switch (DeclKind) {
46   default: assert(0 && "Declaration not in DeclNodes.inc!");
47 #define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
48 #define ABSTRACT_DECL(DECL)
49 #include "clang/AST/DeclNodes.inc"
50   }
51 }
52 
setInvalidDecl(bool Invalid)53 void Decl::setInvalidDecl(bool Invalid) {
54   InvalidDecl = Invalid;
55   if (Invalid) {
56     // Defensive maneuver for ill-formed code: we're likely not to make it to
57     // a point where we set the access specifier, so default it to "public"
58     // to avoid triggering asserts elsewhere in the front end.
59     setAccess(AS_public);
60   }
61 }
62 
getDeclKindName() const63 const char *DeclContext::getDeclKindName() const {
64   switch (DeclKind) {
65   default: assert(0 && "Declaration context not in DeclNodes.inc!");
66 #define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
67 #define ABSTRACT_DECL(DECL)
68 #include "clang/AST/DeclNodes.inc"
69   }
70 }
71 
CollectingStats(bool Enable)72 bool Decl::CollectingStats(bool Enable) {
73   if (Enable) StatSwitch = true;
74   return StatSwitch;
75 }
76 
PrintStats()77 void Decl::PrintStats() {
78   llvm::errs() << "\n*** Decl Stats:\n";
79 
80   int totalDecls = 0;
81 #define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
82 #define ABSTRACT_DECL(DECL)
83 #include "clang/AST/DeclNodes.inc"
84   llvm::errs() << "  " << totalDecls << " decls total.\n";
85 
86   int totalBytes = 0;
87 #define DECL(DERIVED, BASE)                                             \
88   if (n##DERIVED##s > 0) {                                              \
89     totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl));         \
90     llvm::errs() << "    " << n##DERIVED##s << " " #DERIVED " decls, "  \
91                  << sizeof(DERIVED##Decl) << " each ("                  \
92                  << n##DERIVED##s * sizeof(DERIVED##Decl)               \
93                  << " bytes)\n";                                        \
94   }
95 #define ABSTRACT_DECL(DECL)
96 #include "clang/AST/DeclNodes.inc"
97 
98   llvm::errs() << "Total bytes = " << totalBytes << "\n";
99 }
100 
add(Kind k)101 void Decl::add(Kind k) {
102   switch (k) {
103   default: assert(0 && "Declaration not in DeclNodes.inc!");
104 #define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
105 #define ABSTRACT_DECL(DECL)
106 #include "clang/AST/DeclNodes.inc"
107   }
108 }
109 
isTemplateParameterPack() const110 bool Decl::isTemplateParameterPack() const {
111   if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
112     return TTP->isParameterPack();
113   if (const NonTypeTemplateParmDecl *NTTP
114                                 = dyn_cast<NonTypeTemplateParmDecl>(this))
115     return NTTP->isParameterPack();
116   if (const TemplateTemplateParmDecl *TTP
117                                     = dyn_cast<TemplateTemplateParmDecl>(this))
118     return TTP->isParameterPack();
119   return false;
120 }
121 
isParameterPack() const122 bool Decl::isParameterPack() const {
123   if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this))
124     return Parm->isParameterPack();
125 
126   return isTemplateParameterPack();
127 }
128 
isFunctionOrFunctionTemplate() const129 bool Decl::isFunctionOrFunctionTemplate() const {
130   if (const UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(this))
131     return UD->getTargetDecl()->isFunctionOrFunctionTemplate();
132 
133   return isa<FunctionDecl>(this) || isa<FunctionTemplateDecl>(this);
134 }
135 
isDefinedOutsideFunctionOrMethod() const136 bool Decl::isDefinedOutsideFunctionOrMethod() const {
137   for (const DeclContext *DC = getDeclContext();
138        DC && !DC->isTranslationUnit();
139        DC = DC->getParent())
140     if (DC->isFunctionOrMethod())
141       return false;
142 
143   return true;
144 }
145 
146 
147 //===----------------------------------------------------------------------===//
148 // PrettyStackTraceDecl Implementation
149 //===----------------------------------------------------------------------===//
150 
print(llvm::raw_ostream & OS) const151 void PrettyStackTraceDecl::print(llvm::raw_ostream &OS) const {
152   SourceLocation TheLoc = Loc;
153   if (TheLoc.isInvalid() && TheDecl)
154     TheLoc = TheDecl->getLocation();
155 
156   if (TheLoc.isValid()) {
157     TheLoc.print(OS, SM);
158     OS << ": ";
159   }
160 
161   OS << Message;
162 
163   if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl))
164     OS << " '" << DN->getQualifiedNameAsString() << '\'';
165   OS << '\n';
166 }
167 
168 //===----------------------------------------------------------------------===//
169 // Decl Implementation
170 //===----------------------------------------------------------------------===//
171 
172 // Out-of-line virtual method providing a home for Decl.
~Decl()173 Decl::~Decl() { }
174 
setDeclContext(DeclContext * DC)175 void Decl::setDeclContext(DeclContext *DC) {
176   DeclCtx = DC;
177 }
178 
setLexicalDeclContext(DeclContext * DC)179 void Decl::setLexicalDeclContext(DeclContext *DC) {
180   if (DC == getLexicalDeclContext())
181     return;
182 
183   if (isInSemaDC()) {
184     MultipleDC *MDC = new (getASTContext()) MultipleDC();
185     MDC->SemanticDC = getDeclContext();
186     MDC->LexicalDC = DC;
187     DeclCtx = MDC;
188   } else {
189     getMultipleDC()->LexicalDC = DC;
190   }
191 }
192 
isInAnonymousNamespace() const193 bool Decl::isInAnonymousNamespace() const {
194   const DeclContext *DC = getDeclContext();
195   do {
196     if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
197       if (ND->isAnonymousNamespace())
198         return true;
199   } while ((DC = DC->getParent()));
200 
201   return false;
202 }
203 
getTranslationUnitDecl()204 TranslationUnitDecl *Decl::getTranslationUnitDecl() {
205   if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
206     return TUD;
207 
208   DeclContext *DC = getDeclContext();
209   assert(DC && "This decl is not contained in a translation unit!");
210 
211   while (!DC->isTranslationUnit()) {
212     DC = DC->getParent();
213     assert(DC && "This decl is not contained in a translation unit!");
214   }
215 
216   return cast<TranslationUnitDecl>(DC);
217 }
218 
getASTContext() const219 ASTContext &Decl::getASTContext() const {
220   return getTranslationUnitDecl()->getASTContext();
221 }
222 
getASTMutationListener() const223 ASTMutationListener *Decl::getASTMutationListener() const {
224   return getASTContext().getASTMutationListener();
225 }
226 
isUsed(bool CheckUsedAttr) const227 bool Decl::isUsed(bool CheckUsedAttr) const {
228   if (Used)
229     return true;
230 
231   // Check for used attribute.
232   if (CheckUsedAttr && hasAttr<UsedAttr>())
233     return true;
234 
235   // Check redeclarations for used attribute.
236   for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
237     if ((CheckUsedAttr && I->hasAttr<UsedAttr>()) || I->Used)
238       return true;
239   }
240 
241   return false;
242 }
243 
isReferenced() const244 bool Decl::isReferenced() const {
245   if (Referenced)
246     return true;
247 
248   // Check redeclarations.
249   for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
250     if (I->Referenced)
251       return true;
252 
253   return false;
254 }
255 
256 /// \brief Determine the availability of the given declaration based on
257 /// the target platform.
258 ///
259 /// When it returns an availability result other than \c AR_Available,
260 /// if the \p Message parameter is non-NULL, it will be set to a
261 /// string describing why the entity is unavailable.
262 ///
263 /// FIXME: Make these strings localizable, since they end up in
264 /// diagnostics.
CheckAvailability(ASTContext & Context,const AvailabilityAttr * A,std::string * Message)265 static AvailabilityResult CheckAvailability(ASTContext &Context,
266                                             const AvailabilityAttr *A,
267                                             std::string *Message) {
268   llvm::StringRef TargetPlatform = Context.Target.getPlatformName();
269   llvm::StringRef PrettyPlatformName
270     = AvailabilityAttr::getPrettyPlatformName(TargetPlatform);
271   if (PrettyPlatformName.empty())
272     PrettyPlatformName = TargetPlatform;
273 
274   VersionTuple TargetMinVersion = Context.Target.getPlatformMinVersion();
275   if (TargetMinVersion.empty())
276     return AR_Available;
277 
278   // Match the platform name.
279   if (A->getPlatform()->getName() != TargetPlatform)
280     return AR_Available;
281 
282   // Make sure that this declaration has not been marked 'unavailable'.
283   if (A->getUnavailable()) {
284     if (Message) {
285       Message->clear();
286       llvm::raw_string_ostream Out(*Message);
287       Out << "not available on " << PrettyPlatformName;
288     }
289 
290     return AR_Unavailable;
291   }
292 
293   // Make sure that this declaration has already been introduced.
294   if (!A->getIntroduced().empty() &&
295       TargetMinVersion < A->getIntroduced()) {
296     if (Message) {
297       Message->clear();
298       llvm::raw_string_ostream Out(*Message);
299       Out << "introduced in " << PrettyPlatformName << ' '
300           << A->getIntroduced();
301     }
302 
303     return AR_NotYetIntroduced;
304   }
305 
306   // Make sure that this declaration hasn't been obsoleted.
307   if (!A->getObsoleted().empty() && TargetMinVersion >= A->getObsoleted()) {
308     if (Message) {
309       Message->clear();
310       llvm::raw_string_ostream Out(*Message);
311       Out << "obsoleted in " << PrettyPlatformName << ' '
312           << A->getObsoleted();
313     }
314 
315     return AR_Unavailable;
316   }
317 
318   // Make sure that this declaration hasn't been deprecated.
319   if (!A->getDeprecated().empty() && TargetMinVersion >= A->getDeprecated()) {
320     if (Message) {
321       Message->clear();
322       llvm::raw_string_ostream Out(*Message);
323       Out << "first deprecated in " << PrettyPlatformName << ' '
324           << A->getDeprecated();
325     }
326 
327     return AR_Deprecated;
328   }
329 
330   return AR_Available;
331 }
332 
getAvailability(std::string * Message) const333 AvailabilityResult Decl::getAvailability(std::string *Message) const {
334   AvailabilityResult Result = AR_Available;
335   std::string ResultMessage;
336 
337   for (attr_iterator A = attr_begin(), AEnd = attr_end(); A != AEnd; ++A) {
338     if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(*A)) {
339       if (Result >= AR_Deprecated)
340         continue;
341 
342       if (Message)
343         ResultMessage = Deprecated->getMessage();
344 
345       Result = AR_Deprecated;
346       continue;
347     }
348 
349     if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(*A)) {
350       if (Message)
351         *Message = Unavailable->getMessage();
352       return AR_Unavailable;
353     }
354 
355     if (AvailabilityAttr *Availability = dyn_cast<AvailabilityAttr>(*A)) {
356       AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
357                                                 Message);
358 
359       if (AR == AR_Unavailable)
360         return AR_Unavailable;
361 
362       if (AR > Result) {
363         Result = AR;
364         if (Message)
365           ResultMessage.swap(*Message);
366       }
367       continue;
368     }
369   }
370 
371   if (Message)
372     Message->swap(ResultMessage);
373   return Result;
374 }
375 
canBeWeakImported(bool & IsDefinition) const376 bool Decl::canBeWeakImported(bool &IsDefinition) const {
377   IsDefinition = false;
378   if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
379     if (!Var->hasExternalStorage() || Var->getInit()) {
380       IsDefinition = true;
381       return false;
382     }
383   } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
384     if (FD->hasBody()) {
385       IsDefinition = true;
386       return false;
387     }
388   } else if (isa<ObjCPropertyDecl>(this) || isa<ObjCMethodDecl>(this))
389     return false;
390   else if (!(getASTContext().getLangOptions().ObjCNonFragileABI &&
391              isa<ObjCInterfaceDecl>(this)))
392     return false;
393 
394   return true;
395 }
396 
isWeakImported() const397 bool Decl::isWeakImported() const {
398   bool IsDefinition;
399   if (!canBeWeakImported(IsDefinition))
400     return false;
401 
402   for (attr_iterator A = attr_begin(), AEnd = attr_end(); A != AEnd; ++A) {
403     if (isa<WeakImportAttr>(*A))
404       return true;
405 
406     if (AvailabilityAttr *Availability = dyn_cast<AvailabilityAttr>(*A)) {
407       if (CheckAvailability(getASTContext(), Availability, 0)
408                                                          == AR_NotYetIntroduced)
409         return true;
410     }
411   }
412 
413   return false;
414 }
415 
getIdentifierNamespaceForKind(Kind DeclKind)416 unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
417   switch (DeclKind) {
418     case Function:
419     case CXXMethod:
420     case CXXConstructor:
421     case CXXDestructor:
422     case CXXConversion:
423     case EnumConstant:
424     case Var:
425     case ImplicitParam:
426     case ParmVar:
427     case NonTypeTemplateParm:
428     case ObjCMethod:
429     case ObjCProperty:
430       return IDNS_Ordinary;
431     case Label:
432       return IDNS_Label;
433     case IndirectField:
434       return IDNS_Ordinary | IDNS_Member;
435 
436     case ObjCCompatibleAlias:
437     case ObjCInterface:
438       return IDNS_Ordinary | IDNS_Type;
439 
440     case Typedef:
441     case TypeAlias:
442     case TypeAliasTemplate:
443     case UnresolvedUsingTypename:
444     case TemplateTypeParm:
445       return IDNS_Ordinary | IDNS_Type;
446 
447     case UsingShadow:
448       return 0; // we'll actually overwrite this later
449 
450     case UnresolvedUsingValue:
451       return IDNS_Ordinary | IDNS_Using;
452 
453     case Using:
454       return IDNS_Using;
455 
456     case ObjCProtocol:
457       return IDNS_ObjCProtocol;
458 
459     case Field:
460     case ObjCAtDefsField:
461     case ObjCIvar:
462       return IDNS_Member;
463 
464     case Record:
465     case CXXRecord:
466     case Enum:
467       return IDNS_Tag | IDNS_Type;
468 
469     case Namespace:
470     case NamespaceAlias:
471       return IDNS_Namespace;
472 
473     case FunctionTemplate:
474       return IDNS_Ordinary;
475 
476     case ClassTemplate:
477     case TemplateTemplateParm:
478       return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
479 
480     // Never have names.
481     case Friend:
482     case FriendTemplate:
483     case AccessSpec:
484     case LinkageSpec:
485     case FileScopeAsm:
486     case StaticAssert:
487     case ObjCClass:
488     case ObjCPropertyImpl:
489     case ObjCForwardProtocol:
490     case Block:
491     case TranslationUnit:
492 
493     case UsingDirective:
494     case ClassTemplateSpecialization:
495     case ClassTemplatePartialSpecialization:
496     case ObjCImplementation:
497     case ObjCCategory:
498     case ObjCCategoryImpl:
499       // Never looked up by name.
500       return 0;
501   }
502 
503   return 0;
504 }
505 
setAttrs(const AttrVec & attrs)506 void Decl::setAttrs(const AttrVec &attrs) {
507   assert(!HasAttrs && "Decl already contains attrs.");
508 
509   AttrVec &AttrBlank = getASTContext().getDeclAttrs(this);
510   assert(AttrBlank.empty() && "HasAttrs was wrong?");
511 
512   AttrBlank = attrs;
513   HasAttrs = true;
514 }
515 
dropAttrs()516 void Decl::dropAttrs() {
517   if (!HasAttrs) return;
518 
519   HasAttrs = false;
520   getASTContext().eraseDeclAttrs(this);
521 }
522 
getAttrs() const523 const AttrVec &Decl::getAttrs() const {
524   assert(HasAttrs && "No attrs to get!");
525   return getASTContext().getDeclAttrs(this);
526 }
527 
swapAttrs(Decl * RHS)528 void Decl::swapAttrs(Decl *RHS) {
529   bool HasLHSAttr = this->HasAttrs;
530   bool HasRHSAttr = RHS->HasAttrs;
531 
532   // Usually, neither decl has attrs, nothing to do.
533   if (!HasLHSAttr && !HasRHSAttr) return;
534 
535   // If 'this' has no attrs, swap the other way.
536   if (!HasLHSAttr)
537     return RHS->swapAttrs(this);
538 
539   ASTContext &Context = getASTContext();
540 
541   // Handle the case when both decls have attrs.
542   if (HasRHSAttr) {
543     std::swap(Context.getDeclAttrs(this), Context.getDeclAttrs(RHS));
544     return;
545   }
546 
547   // Otherwise, LHS has an attr and RHS doesn't.
548   Context.getDeclAttrs(RHS) = Context.getDeclAttrs(this);
549   Context.eraseDeclAttrs(this);
550   this->HasAttrs = false;
551   RHS->HasAttrs = true;
552 }
553 
castFromDeclContext(const DeclContext * D)554 Decl *Decl::castFromDeclContext (const DeclContext *D) {
555   Decl::Kind DK = D->getDeclKind();
556   switch(DK) {
557 #define DECL(NAME, BASE)
558 #define DECL_CONTEXT(NAME) \
559     case Decl::NAME:       \
560       return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
561 #define DECL_CONTEXT_BASE(NAME)
562 #include "clang/AST/DeclNodes.inc"
563     default:
564 #define DECL(NAME, BASE)
565 #define DECL_CONTEXT_BASE(NAME)                  \
566       if (DK >= first##NAME && DK <= last##NAME) \
567         return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
568 #include "clang/AST/DeclNodes.inc"
569       assert(false && "a decl that inherits DeclContext isn't handled");
570       return 0;
571   }
572 }
573 
castToDeclContext(const Decl * D)574 DeclContext *Decl::castToDeclContext(const Decl *D) {
575   Decl::Kind DK = D->getKind();
576   switch(DK) {
577 #define DECL(NAME, BASE)
578 #define DECL_CONTEXT(NAME) \
579     case Decl::NAME:       \
580       return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
581 #define DECL_CONTEXT_BASE(NAME)
582 #include "clang/AST/DeclNodes.inc"
583     default:
584 #define DECL(NAME, BASE)
585 #define DECL_CONTEXT_BASE(NAME)                                   \
586       if (DK >= first##NAME && DK <= last##NAME)                  \
587         return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
588 #include "clang/AST/DeclNodes.inc"
589       assert(false && "a decl that inherits DeclContext isn't handled");
590       return 0;
591   }
592 }
593 
getBodyRBrace() const594 SourceLocation Decl::getBodyRBrace() const {
595   // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
596   // FunctionDecl stores EndRangeLoc for this purpose.
597   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
598     const FunctionDecl *Definition;
599     if (FD->hasBody(Definition))
600       return Definition->getSourceRange().getEnd();
601     return SourceLocation();
602   }
603 
604   if (Stmt *Body = getBody())
605     return Body->getSourceRange().getEnd();
606 
607   return SourceLocation();
608 }
609 
CheckAccessDeclContext() const610 void Decl::CheckAccessDeclContext() const {
611 #ifndef NDEBUG
612   // Suppress this check if any of the following hold:
613   // 1. this is the translation unit (and thus has no parent)
614   // 2. this is a template parameter (and thus doesn't belong to its context)
615   // 3. this is a non-type template parameter
616   // 4. the context is not a record
617   // 5. it's invalid
618   // 6. it's a C++0x static_assert.
619   if (isa<TranslationUnitDecl>(this) ||
620       isa<TemplateTypeParmDecl>(this) ||
621       isa<NonTypeTemplateParmDecl>(this) ||
622       !isa<CXXRecordDecl>(getDeclContext()) ||
623       isInvalidDecl() ||
624       isa<StaticAssertDecl>(this) ||
625       // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
626       // as DeclContext (?).
627       isa<ParmVarDecl>(this) ||
628       // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
629       // AS_none as access specifier.
630       isa<CXXRecordDecl>(this))
631     return;
632 
633   assert(Access != AS_none &&
634          "Access specifier is AS_none inside a record decl");
635 #endif
636 }
637 
getNonClosureContext()638 DeclContext *Decl::getNonClosureContext() {
639   DeclContext *DC = getDeclContext();
640 
641   // This is basically "while (DC->isClosure()) DC = DC->getParent();"
642   // except that it's significantly more efficient to cast to a known
643   // decl type and call getDeclContext() than to call getParent().
644   while (isa<BlockDecl>(DC))
645     DC = cast<BlockDecl>(DC)->getDeclContext();
646 
647   assert(!DC->isClosure());
648   return DC;
649 }
650 
651 //===----------------------------------------------------------------------===//
652 // DeclContext Implementation
653 //===----------------------------------------------------------------------===//
654 
classof(const Decl * D)655 bool DeclContext::classof(const Decl *D) {
656   switch (D->getKind()) {
657 #define DECL(NAME, BASE)
658 #define DECL_CONTEXT(NAME) case Decl::NAME:
659 #define DECL_CONTEXT_BASE(NAME)
660 #include "clang/AST/DeclNodes.inc"
661       return true;
662     default:
663 #define DECL(NAME, BASE)
664 #define DECL_CONTEXT_BASE(NAME)                 \
665       if (D->getKind() >= Decl::first##NAME &&  \
666           D->getKind() <= Decl::last##NAME)     \
667         return true;
668 #include "clang/AST/DeclNodes.inc"
669       return false;
670   }
671 }
672 
~DeclContext()673 DeclContext::~DeclContext() { }
674 
675 /// \brief Find the parent context of this context that will be
676 /// used for unqualified name lookup.
677 ///
678 /// Generally, the parent lookup context is the semantic context. However, for
679 /// a friend function the parent lookup context is the lexical context, which
680 /// is the class in which the friend is declared.
getLookupParent()681 DeclContext *DeclContext::getLookupParent() {
682   // FIXME: Find a better way to identify friends
683   if (isa<FunctionDecl>(this))
684     if (getParent()->getRedeclContext()->isFileContext() &&
685         getLexicalParent()->getRedeclContext()->isRecord())
686       return getLexicalParent();
687 
688   return getParent();
689 }
690 
isInlineNamespace() const691 bool DeclContext::isInlineNamespace() const {
692   return isNamespace() &&
693          cast<NamespaceDecl>(this)->isInline();
694 }
695 
isDependentContext() const696 bool DeclContext::isDependentContext() const {
697   if (isFileContext())
698     return false;
699 
700   if (isa<ClassTemplatePartialSpecializationDecl>(this))
701     return true;
702 
703   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
704     if (Record->getDescribedClassTemplate())
705       return true;
706 
707   if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
708     if (Function->getDescribedFunctionTemplate())
709       return true;
710 
711     // Friend function declarations are dependent if their *lexical*
712     // context is dependent.
713     if (cast<Decl>(this)->getFriendObjectKind())
714       return getLexicalParent()->isDependentContext();
715   }
716 
717   return getParent() && getParent()->isDependentContext();
718 }
719 
isTransparentContext() const720 bool DeclContext::isTransparentContext() const {
721   if (DeclKind == Decl::Enum)
722     return !cast<EnumDecl>(this)->isScoped();
723   else if (DeclKind == Decl::LinkageSpec)
724     return true;
725 
726   return false;
727 }
728 
isExternCContext() const729 bool DeclContext::isExternCContext() const {
730   const DeclContext *DC = this;
731   while (DC->DeclKind != Decl::TranslationUnit) {
732     if (DC->DeclKind == Decl::LinkageSpec)
733       return cast<LinkageSpecDecl>(DC)->getLanguage()
734         == LinkageSpecDecl::lang_c;
735     DC = DC->getParent();
736   }
737   return false;
738 }
739 
Encloses(const DeclContext * DC) const740 bool DeclContext::Encloses(const DeclContext *DC) const {
741   if (getPrimaryContext() != this)
742     return getPrimaryContext()->Encloses(DC);
743 
744   for (; DC; DC = DC->getParent())
745     if (DC->getPrimaryContext() == this)
746       return true;
747   return false;
748 }
749 
getPrimaryContext()750 DeclContext *DeclContext::getPrimaryContext() {
751   switch (DeclKind) {
752   case Decl::TranslationUnit:
753   case Decl::LinkageSpec:
754   case Decl::Block:
755     // There is only one DeclContext for these entities.
756     return this;
757 
758   case Decl::Namespace:
759     // The original namespace is our primary context.
760     return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
761 
762   case Decl::ObjCMethod:
763     return this;
764 
765   case Decl::ObjCInterface:
766   case Decl::ObjCProtocol:
767   case Decl::ObjCCategory:
768     // FIXME: Can Objective-C interfaces be forward-declared?
769     return this;
770 
771   case Decl::ObjCImplementation:
772   case Decl::ObjCCategoryImpl:
773     return this;
774 
775   default:
776     if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
777       // If this is a tag type that has a definition or is currently
778       // being defined, that definition is our primary context.
779       TagDecl *Tag = cast<TagDecl>(this);
780       assert(isa<TagType>(Tag->TypeForDecl) ||
781              isa<InjectedClassNameType>(Tag->TypeForDecl));
782 
783       if (TagDecl *Def = Tag->getDefinition())
784         return Def;
785 
786       if (!isa<InjectedClassNameType>(Tag->TypeForDecl)) {
787         const TagType *TagTy = cast<TagType>(Tag->TypeForDecl);
788         if (TagTy->isBeingDefined())
789           // FIXME: is it necessarily being defined in the decl
790           // that owns the type?
791           return TagTy->getDecl();
792       }
793 
794       return Tag;
795     }
796 
797     assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
798           "Unknown DeclContext kind");
799     return this;
800   }
801 }
802 
getNextContext()803 DeclContext *DeclContext::getNextContext() {
804   switch (DeclKind) {
805   case Decl::Namespace:
806     // Return the next namespace
807     return static_cast<NamespaceDecl*>(this)->getNextNamespace();
808 
809   default:
810     return 0;
811   }
812 }
813 
814 std::pair<Decl *, Decl *>
BuildDeclChain(const llvm::SmallVectorImpl<Decl * > & Decls)815 DeclContext::BuildDeclChain(const llvm::SmallVectorImpl<Decl*> &Decls) {
816   // Build up a chain of declarations via the Decl::NextDeclInContext field.
817   Decl *FirstNewDecl = 0;
818   Decl *PrevDecl = 0;
819   for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
820     Decl *D = Decls[I];
821     if (PrevDecl)
822       PrevDecl->NextDeclInContext = D;
823     else
824       FirstNewDecl = D;
825 
826     PrevDecl = D;
827   }
828 
829   return std::make_pair(FirstNewDecl, PrevDecl);
830 }
831 
832 /// \brief Load the declarations within this lexical storage from an
833 /// external source.
834 void
LoadLexicalDeclsFromExternalStorage() const835 DeclContext::LoadLexicalDeclsFromExternalStorage() const {
836   ExternalASTSource *Source = getParentASTContext().getExternalSource();
837   assert(hasExternalLexicalStorage() && Source && "No external storage?");
838 
839   // Notify that we have a DeclContext that is initializing.
840   ExternalASTSource::Deserializing ADeclContext(Source);
841 
842   // Load the external declarations, if any.
843   llvm::SmallVector<Decl*, 64> Decls;
844   ExternalLexicalStorage = false;
845   switch (Source->FindExternalLexicalDecls(this, Decls)) {
846   case ELR_Success:
847     break;
848 
849   case ELR_Failure:
850   case ELR_AlreadyLoaded:
851     return;
852   }
853 
854   if (Decls.empty())
855     return;
856 
857   // We may have already loaded just the fields of this record, in which case
858   // don't add the decls, just replace the FirstDecl/LastDecl chain.
859   if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
860     if (RD->LoadedFieldsFromExternalStorage) {
861       llvm::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls);
862       return;
863     }
864 
865   // Splice the newly-read declarations into the beginning of the list
866   // of declarations.
867   Decl *ExternalFirst, *ExternalLast;
868   llvm::tie(ExternalFirst, ExternalLast) = BuildDeclChain(Decls);
869   ExternalLast->NextDeclInContext = FirstDecl;
870   FirstDecl = ExternalFirst;
871   if (!LastDecl)
872     LastDecl = ExternalLast;
873 }
874 
875 DeclContext::lookup_result
SetNoExternalVisibleDeclsForName(const DeclContext * DC,DeclarationName Name)876 ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
877                                                     DeclarationName Name) {
878   ASTContext &Context = DC->getParentASTContext();
879   StoredDeclsMap *Map;
880   if (!(Map = DC->LookupPtr))
881     Map = DC->CreateStoredDeclsMap(Context);
882 
883   StoredDeclsList &List = (*Map)[Name];
884   assert(List.isNull());
885   (void) List;
886 
887   return DeclContext::lookup_result();
888 }
889 
890 DeclContext::lookup_result
SetExternalVisibleDeclsForName(const DeclContext * DC,DeclarationName Name,llvm::SmallVectorImpl<NamedDecl * > & Decls)891 ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
892                                                   DeclarationName Name,
893                                     llvm::SmallVectorImpl<NamedDecl*> &Decls) {
894   ASTContext &Context = DC->getParentASTContext();;
895 
896   StoredDeclsMap *Map;
897   if (!(Map = DC->LookupPtr))
898     Map = DC->CreateStoredDeclsMap(Context);
899 
900   StoredDeclsList &List = (*Map)[Name];
901   for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
902     if (List.isNull())
903       List.setOnlyValue(Decls[I]);
904     else
905       List.AddSubsequentDecl(Decls[I]);
906   }
907 
908   return List.getLookupResult();
909 }
910 
MaterializeVisibleDeclsForName(const DeclContext * DC,DeclarationName Name,llvm::SmallVectorImpl<NamedDecl * > & Decls)911 void ExternalASTSource::MaterializeVisibleDeclsForName(const DeclContext *DC,
912                                                        DeclarationName Name,
913                                      llvm::SmallVectorImpl<NamedDecl*> &Decls) {
914   assert(DC->LookupPtr);
915   StoredDeclsMap &Map = *DC->LookupPtr;
916 
917   // If there's an entry in the table the visible decls for this name have
918   // already been deserialized.
919   if (Map.find(Name) == Map.end()) {
920     StoredDeclsList &List = Map[Name];
921     for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
922       if (List.isNull())
923         List.setOnlyValue(Decls[I]);
924       else
925         List.AddSubsequentDecl(Decls[I]);
926     }
927   }
928 }
929 
noload_decls_begin() const930 DeclContext::decl_iterator DeclContext::noload_decls_begin() const {
931   return decl_iterator(FirstDecl);
932 }
933 
noload_decls_end() const934 DeclContext::decl_iterator DeclContext::noload_decls_end() const {
935   return decl_iterator();
936 }
937 
decls_begin() const938 DeclContext::decl_iterator DeclContext::decls_begin() const {
939   if (hasExternalLexicalStorage())
940     LoadLexicalDeclsFromExternalStorage();
941 
942   // FIXME: Check whether we need to load some declarations from
943   // external storage.
944   return decl_iterator(FirstDecl);
945 }
946 
decls_end() const947 DeclContext::decl_iterator DeclContext::decls_end() const {
948   if (hasExternalLexicalStorage())
949     LoadLexicalDeclsFromExternalStorage();
950 
951   return decl_iterator();
952 }
953 
decls_empty() const954 bool DeclContext::decls_empty() const {
955   if (hasExternalLexicalStorage())
956     LoadLexicalDeclsFromExternalStorage();
957 
958   return !FirstDecl;
959 }
960 
removeDecl(Decl * D)961 void DeclContext::removeDecl(Decl *D) {
962   assert(D->getLexicalDeclContext() == this &&
963          "decl being removed from non-lexical context");
964   assert((D->NextDeclInContext || D == LastDecl) &&
965          "decl is not in decls list");
966 
967   // Remove D from the decl chain.  This is O(n) but hopefully rare.
968   if (D == FirstDecl) {
969     if (D == LastDecl)
970       FirstDecl = LastDecl = 0;
971     else
972       FirstDecl = D->NextDeclInContext;
973   } else {
974     for (Decl *I = FirstDecl; true; I = I->NextDeclInContext) {
975       assert(I && "decl not found in linked list");
976       if (I->NextDeclInContext == D) {
977         I->NextDeclInContext = D->NextDeclInContext;
978         if (D == LastDecl) LastDecl = I;
979         break;
980       }
981     }
982   }
983 
984   // Mark that D is no longer in the decl chain.
985   D->NextDeclInContext = 0;
986 
987   // Remove D from the lookup table if necessary.
988   if (isa<NamedDecl>(D)) {
989     NamedDecl *ND = cast<NamedDecl>(D);
990 
991     StoredDeclsMap *Map = getPrimaryContext()->LookupPtr;
992     if (!Map) return;
993 
994     StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
995     assert(Pos != Map->end() && "no lookup entry for decl");
996     Pos->second.remove(ND);
997   }
998 }
999 
addHiddenDecl(Decl * D)1000 void DeclContext::addHiddenDecl(Decl *D) {
1001   assert(D->getLexicalDeclContext() == this &&
1002          "Decl inserted into wrong lexical context");
1003   assert(!D->getNextDeclInContext() && D != LastDecl &&
1004          "Decl already inserted into a DeclContext");
1005 
1006   if (FirstDecl) {
1007     LastDecl->NextDeclInContext = D;
1008     LastDecl = D;
1009   } else {
1010     FirstDecl = LastDecl = D;
1011   }
1012 
1013   // Notify a C++ record declaration that we've added a member, so it can
1014   // update it's class-specific state.
1015   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1016     Record->addedMember(D);
1017 }
1018 
addDecl(Decl * D)1019 void DeclContext::addDecl(Decl *D) {
1020   addHiddenDecl(D);
1021 
1022   if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1023     ND->getDeclContext()->makeDeclVisibleInContext(ND);
1024 }
1025 
1026 /// buildLookup - Build the lookup data structure with all of the
1027 /// declarations in DCtx (and any other contexts linked to it or
1028 /// transparent contexts nested within it).
buildLookup(DeclContext * DCtx)1029 void DeclContext::buildLookup(DeclContext *DCtx) {
1030   for (; DCtx; DCtx = DCtx->getNextContext()) {
1031     for (decl_iterator D = DCtx->decls_begin(),
1032                     DEnd = DCtx->decls_end();
1033          D != DEnd; ++D) {
1034       // Insert this declaration into the lookup structure, but only
1035       // if it's semantically in its decl context.  During non-lazy
1036       // lookup building, this is implicitly enforced by addDecl.
1037       if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
1038         if (D->getDeclContext() == DCtx)
1039           makeDeclVisibleInContextImpl(ND);
1040 
1041       // Insert any forward-declared Objective-C interfaces into the lookup
1042       // data structure.
1043       if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(*D))
1044         for (ObjCClassDecl::iterator I = Class->begin(), IEnd = Class->end();
1045              I != IEnd; ++I)
1046           makeDeclVisibleInContextImpl(I->getInterface());
1047 
1048       // If this declaration is itself a transparent declaration context or
1049       // inline namespace, add its members (recursively).
1050       if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D))
1051         if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1052           buildLookup(InnerCtx->getPrimaryContext());
1053     }
1054   }
1055 }
1056 
1057 DeclContext::lookup_result
lookup(DeclarationName Name)1058 DeclContext::lookup(DeclarationName Name) {
1059   DeclContext *PrimaryContext = getPrimaryContext();
1060   if (PrimaryContext != this)
1061     return PrimaryContext->lookup(Name);
1062 
1063   if (hasExternalVisibleStorage()) {
1064     // Check to see if we've already cached the lookup results.
1065     if (LookupPtr) {
1066       StoredDeclsMap::iterator I = LookupPtr->find(Name);
1067       if (I != LookupPtr->end())
1068         return I->second.getLookupResult();
1069     }
1070 
1071     ExternalASTSource *Source = getParentASTContext().getExternalSource();
1072     return Source->FindExternalVisibleDeclsByName(this, Name);
1073   }
1074 
1075   /// If there is no lookup data structure, build one now by walking
1076   /// all of the linked DeclContexts (in declaration order!) and
1077   /// inserting their values.
1078   if (!LookupPtr) {
1079     buildLookup(this);
1080 
1081     if (!LookupPtr)
1082       return lookup_result(lookup_iterator(0), lookup_iterator(0));
1083   }
1084 
1085   StoredDeclsMap::iterator Pos = LookupPtr->find(Name);
1086   if (Pos == LookupPtr->end())
1087     return lookup_result(lookup_iterator(0), lookup_iterator(0));
1088   return Pos->second.getLookupResult();
1089 }
1090 
1091 DeclContext::lookup_const_result
lookup(DeclarationName Name) const1092 DeclContext::lookup(DeclarationName Name) const {
1093   return const_cast<DeclContext*>(this)->lookup(Name);
1094 }
1095 
getRedeclContext()1096 DeclContext *DeclContext::getRedeclContext() {
1097   DeclContext *Ctx = this;
1098   // Skip through transparent contexts.
1099   while (Ctx->isTransparentContext())
1100     Ctx = Ctx->getParent();
1101   return Ctx;
1102 }
1103 
getEnclosingNamespaceContext()1104 DeclContext *DeclContext::getEnclosingNamespaceContext() {
1105   DeclContext *Ctx = this;
1106   // Skip through non-namespace, non-translation-unit contexts.
1107   while (!Ctx->isFileContext())
1108     Ctx = Ctx->getParent();
1109   return Ctx->getPrimaryContext();
1110 }
1111 
InEnclosingNamespaceSetOf(const DeclContext * O) const1112 bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1113   // For non-file contexts, this is equivalent to Equals.
1114   if (!isFileContext())
1115     return O->Equals(this);
1116 
1117   do {
1118     if (O->Equals(this))
1119       return true;
1120 
1121     const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1122     if (!NS || !NS->isInline())
1123       break;
1124     O = NS->getParent();
1125   } while (O);
1126 
1127   return false;
1128 }
1129 
makeDeclVisibleInContext(NamedDecl * D,bool Recoverable)1130 void DeclContext::makeDeclVisibleInContext(NamedDecl *D, bool Recoverable) {
1131   // FIXME: This feels like a hack. Should DeclarationName support
1132   // template-ids, or is there a better way to keep specializations
1133   // from being visible?
1134   if (isa<ClassTemplateSpecializationDecl>(D) || D->isTemplateParameter())
1135     return;
1136   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1137     if (FD->isFunctionTemplateSpecialization())
1138       return;
1139 
1140   DeclContext *PrimaryContext = getPrimaryContext();
1141   if (PrimaryContext != this) {
1142     PrimaryContext->makeDeclVisibleInContext(D, Recoverable);
1143     return;
1144   }
1145 
1146   // If we already have a lookup data structure, perform the insertion
1147   // into it. If we haven't deserialized externally stored decls, deserialize
1148   // them so we can add the decl. Otherwise, be lazy and don't build that
1149   // structure until someone asks for it.
1150   if (LookupPtr || !Recoverable || hasExternalVisibleStorage())
1151     makeDeclVisibleInContextImpl(D);
1152 
1153   // If we are a transparent context or inline namespace, insert into our
1154   // parent context, too. This operation is recursive.
1155   if (isTransparentContext() || isInlineNamespace())
1156     getParent()->makeDeclVisibleInContext(D, Recoverable);
1157 
1158   Decl *DCAsDecl = cast<Decl>(this);
1159   // Notify that a decl was made visible unless it's a Tag being defined.
1160   if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1161     if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1162       L->AddedVisibleDecl(this, D);
1163 }
1164 
makeDeclVisibleInContextImpl(NamedDecl * D)1165 void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D) {
1166   // Skip unnamed declarations.
1167   if (!D->getDeclName())
1168     return;
1169 
1170   // Skip entities that can't be found by name lookup into a particular
1171   // context.
1172   if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1173       D->isTemplateParameter())
1174     return;
1175 
1176   ASTContext *C = 0;
1177   if (!LookupPtr) {
1178     C = &getParentASTContext();
1179     CreateStoredDeclsMap(*C);
1180   }
1181 
1182   // If there is an external AST source, load any declarations it knows about
1183   // with this declaration's name.
1184   // If the lookup table contains an entry about this name it means that we
1185   // have already checked the external source.
1186   if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1187     if (hasExternalVisibleStorage() &&
1188         LookupPtr->find(D->getDeclName()) == LookupPtr->end())
1189       Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1190 
1191   // Insert this declaration into the map.
1192   StoredDeclsList &DeclNameEntries = (*LookupPtr)[D->getDeclName()];
1193   if (DeclNameEntries.isNull()) {
1194     DeclNameEntries.setOnlyValue(D);
1195     return;
1196   }
1197 
1198   // If it is possible that this is a redeclaration, check to see if there is
1199   // already a decl for which declarationReplaces returns true.  If there is
1200   // one, just replace it and return.
1201   if (DeclNameEntries.HandleRedeclaration(D))
1202     return;
1203 
1204   // Put this declaration into the appropriate slot.
1205   DeclNameEntries.AddSubsequentDecl(D);
1206 }
1207 
MaterializeVisibleDeclsFromExternalStorage()1208 void DeclContext::MaterializeVisibleDeclsFromExternalStorage() {
1209   ExternalASTSource *Source = getParentASTContext().getExternalSource();
1210   assert(hasExternalVisibleStorage() && Source && "No external storage?");
1211 
1212   if (!LookupPtr)
1213     CreateStoredDeclsMap(getParentASTContext());
1214   Source->MaterializeVisibleDecls(this);
1215 }
1216 
1217 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1218 /// this context.
1219 DeclContext::udir_iterator_range
getUsingDirectives() const1220 DeclContext::getUsingDirectives() const {
1221   lookup_const_result Result = lookup(UsingDirectiveDecl::getName());
1222   return udir_iterator_range(reinterpret_cast<udir_iterator>(Result.first),
1223                              reinterpret_cast<udir_iterator>(Result.second));
1224 }
1225 
1226 //===----------------------------------------------------------------------===//
1227 // Creation and Destruction of StoredDeclsMaps.                               //
1228 //===----------------------------------------------------------------------===//
1229 
CreateStoredDeclsMap(ASTContext & C) const1230 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1231   assert(!LookupPtr && "context already has a decls map");
1232   assert(getPrimaryContext() == this &&
1233          "creating decls map on non-primary context");
1234 
1235   StoredDeclsMap *M;
1236   bool Dependent = isDependentContext();
1237   if (Dependent)
1238     M = new DependentStoredDeclsMap();
1239   else
1240     M = new StoredDeclsMap();
1241   M->Previous = C.LastSDM;
1242   C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1243   LookupPtr = M;
1244   return M;
1245 }
1246 
ReleaseDeclContextMaps()1247 void ASTContext::ReleaseDeclContextMaps() {
1248   // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1249   // pointer because the subclass doesn't add anything that needs to
1250   // be deleted.
1251   StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1252 }
1253 
DestroyAll(StoredDeclsMap * Map,bool Dependent)1254 void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1255   while (Map) {
1256     // Advance the iteration before we invalidate memory.
1257     llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1258 
1259     if (Dependent)
1260       delete static_cast<DependentStoredDeclsMap*>(Map);
1261     else
1262       delete Map;
1263 
1264     Map = Next.getPointer();
1265     Dependent = Next.getInt();
1266   }
1267 }
1268 
Create(ASTContext & C,DeclContext * Parent,const PartialDiagnostic & PDiag)1269 DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1270                                                  DeclContext *Parent,
1271                                            const PartialDiagnostic &PDiag) {
1272   assert(Parent->isDependentContext()
1273          && "cannot iterate dependent diagnostics of non-dependent context");
1274   Parent = Parent->getPrimaryContext();
1275   if (!Parent->LookupPtr)
1276     Parent->CreateStoredDeclsMap(C);
1277 
1278   DependentStoredDeclsMap *Map
1279     = static_cast<DependentStoredDeclsMap*>(Parent->LookupPtr);
1280 
1281   // Allocate the copy of the PartialDiagnostic via the ASTContext's
1282   // BumpPtrAllocator, rather than the ASTContext itself.
1283   PartialDiagnostic::Storage *DiagStorage = 0;
1284   if (PDiag.hasStorage())
1285     DiagStorage = new (C) PartialDiagnostic::Storage;
1286 
1287   DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
1288 
1289   // TODO: Maybe we shouldn't reverse the order during insertion.
1290   DD->NextDiagnostic = Map->FirstDiagnostic;
1291   Map->FirstDiagnostic = DD;
1292 
1293   return DD;
1294 }
1295