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