1 //===--- ASTReaderDecl.cpp - Decl Deserialization ---------------*- C++ -*-===//
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 ASTReader::ReadDeclRecord method, which is the
11 // entrypoint for loading a decl.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/Serialization/ASTReader.h"
16 #include "ASTCommon.h"
17 #include "ASTReaderInternals.h"
18 #include "clang/AST/ASTConsumer.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclGroup.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/DeclVisitor.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/Sema/IdentifierResolver.h"
26 #include "clang/Sema/Sema.h"
27 #include "clang/Sema/SemaDiagnostic.h"
28 #include "llvm/Support/SaveAndRestore.h"
29 using namespace clang;
30 using namespace clang::serialization;
31 
32 //===----------------------------------------------------------------------===//
33 // Declaration deserialization
34 //===----------------------------------------------------------------------===//
35 
36 namespace clang {
37   class ASTDeclReader : public DeclVisitor<ASTDeclReader, void> {
38     ASTReader &Reader;
39     ModuleFile &F;
40     const DeclID ThisDeclID;
41     const unsigned RawLocation;
42     typedef ASTReader::RecordData RecordData;
43     const RecordData &Record;
44     unsigned &Idx;
45     TypeID TypeIDForTypeDecl;
46 
47     bool HasPendingBody;
48 
49     uint64_t GetCurrentCursorOffset();
50 
51     SourceLocation ReadSourceLocation(const RecordData &R, unsigned &I) {
52       return Reader.ReadSourceLocation(F, R, I);
53     }
54 
55     SourceRange ReadSourceRange(const RecordData &R, unsigned &I) {
56       return Reader.ReadSourceRange(F, R, I);
57     }
58 
59     TypeSourceInfo *GetTypeSourceInfo(const RecordData &R, unsigned &I) {
60       return Reader.GetTypeSourceInfo(F, R, I);
61     }
62 
63     serialization::DeclID ReadDeclID(const RecordData &R, unsigned &I) {
64       return Reader.ReadDeclID(F, R, I);
65     }
66 
67     Decl *ReadDecl(const RecordData &R, unsigned &I) {
68       return Reader.ReadDecl(F, R, I);
69     }
70 
71     template<typename T>
72     T *ReadDeclAs(const RecordData &R, unsigned &I) {
73       return Reader.ReadDeclAs<T>(F, R, I);
74     }
75 
76     void ReadQualifierInfo(QualifierInfo &Info,
77                            const RecordData &R, unsigned &I) {
78       Reader.ReadQualifierInfo(F, Info, R, I);
79     }
80 
81     void ReadDeclarationNameLoc(DeclarationNameLoc &DNLoc, DeclarationName Name,
82                                 const RecordData &R, unsigned &I) {
83       Reader.ReadDeclarationNameLoc(F, DNLoc, Name, R, I);
84     }
85 
86     void ReadDeclarationNameInfo(DeclarationNameInfo &NameInfo,
87                                 const RecordData &R, unsigned &I) {
88       Reader.ReadDeclarationNameInfo(F, NameInfo, R, I);
89     }
90 
91     serialization::SubmoduleID readSubmoduleID(const RecordData &R,
92                                                unsigned &I) {
93       if (I >= R.size())
94         return 0;
95 
96       return Reader.getGlobalSubmoduleID(F, R[I++]);
97     }
98 
99     Module *readModule(const RecordData &R, unsigned &I) {
100       return Reader.getSubmodule(readSubmoduleID(R, I));
101     }
102 
103     void ReadCXXDefinitionData(struct CXXRecordDecl::DefinitionData &Data,
104                                const RecordData &R, unsigned &I);
105 
106     /// \brief RAII class used to capture the first ID within a redeclaration
107     /// chain and to introduce it into the list of pending redeclaration chains
108     /// on destruction.
109     ///
110     /// The caller can choose not to introduce this ID into the redeclaration
111     /// chain by calling \c suppress().
112     class RedeclarableResult {
113       ASTReader &Reader;
114       GlobalDeclID FirstID;
115       mutable bool Owning;
116       Decl::Kind DeclKind;
117 
118       void operator=(RedeclarableResult &) LLVM_DELETED_FUNCTION;
119 
120     public:
121       RedeclarableResult(ASTReader &Reader, GlobalDeclID FirstID,
122                          Decl::Kind DeclKind)
123         : Reader(Reader), FirstID(FirstID), Owning(true), DeclKind(DeclKind) { }
124 
125       RedeclarableResult(const RedeclarableResult &Other)
126         : Reader(Other.Reader), FirstID(Other.FirstID), Owning(Other.Owning) ,
127           DeclKind(Other.DeclKind)
128       {
129         Other.Owning = false;
130       }
131 
132       ~RedeclarableResult() {
133         if (FirstID && Owning && isRedeclarableDeclKind(DeclKind) &&
134             Reader.PendingDeclChainsKnown.insert(FirstID))
135           Reader.PendingDeclChains.push_back(FirstID);
136       }
137 
138       /// \brief Retrieve the first ID.
139       GlobalDeclID getFirstID() const { return FirstID; }
140 
141       /// \brief Do not introduce this declaration ID into the set of pending
142       /// declaration chains.
143       void suppress() {
144         Owning = false;
145       }
146     };
147 
148     /// \brief Class used to capture the result of searching for an existing
149     /// declaration of a specific kind and name, along with the ability
150     /// to update the place where this result was found (the declaration
151     /// chain hanging off an identifier or the DeclContext we searched in)
152     /// if requested.
153     class FindExistingResult {
154       ASTReader &Reader;
155       NamedDecl *New;
156       NamedDecl *Existing;
157       mutable bool AddResult;
158 
159       void operator=(FindExistingResult&) LLVM_DELETED_FUNCTION;
160 
161     public:
162       FindExistingResult(ASTReader &Reader)
163         : Reader(Reader), New(0), Existing(0), AddResult(false) { }
164 
165       FindExistingResult(ASTReader &Reader, NamedDecl *New, NamedDecl *Existing)
166         : Reader(Reader), New(New), Existing(Existing), AddResult(true) { }
167 
168       FindExistingResult(const FindExistingResult &Other)
169         : Reader(Other.Reader), New(Other.New), Existing(Other.Existing),
170           AddResult(Other.AddResult)
171       {
172         Other.AddResult = false;
173       }
174 
175       ~FindExistingResult();
176 
177       /// \brief Suppress the addition of this result into the known set of
178       /// names.
179       void suppress() { AddResult = false; }
180 
181       operator NamedDecl*() const { return Existing; }
182 
183       template<typename T>
184       operator T*() const { return dyn_cast_or_null<T>(Existing); }
185     };
186 
187     FindExistingResult findExisting(NamedDecl *D);
188 
189   public:
190     ASTDeclReader(ASTReader &Reader, ModuleFile &F,
191                   DeclID thisDeclID,
192                   unsigned RawLocation,
193                   const RecordData &Record, unsigned &Idx)
194       : Reader(Reader), F(F), ThisDeclID(thisDeclID),
195         RawLocation(RawLocation), Record(Record), Idx(Idx),
196         TypeIDForTypeDecl(0), HasPendingBody(false) { }
197 
198     static void attachPreviousDecl(Decl *D, Decl *previous);
199     static void attachLatestDecl(Decl *D, Decl *latest);
200 
201     /// \brief Determine whether this declaration has a pending body.
202     bool hasPendingBody() const { return HasPendingBody; }
203 
204     void Visit(Decl *D);
205 
206     void UpdateDecl(Decl *D, ModuleFile &ModuleFile,
207                     const RecordData &Record);
208 
209     static void setNextObjCCategory(ObjCCategoryDecl *Cat,
210                                     ObjCCategoryDecl *Next) {
211       Cat->NextClassCategory = Next;
212     }
213 
214     void VisitDecl(Decl *D);
215     void VisitTranslationUnitDecl(TranslationUnitDecl *TU);
216     void VisitNamedDecl(NamedDecl *ND);
217     void VisitLabelDecl(LabelDecl *LD);
218     void VisitNamespaceDecl(NamespaceDecl *D);
219     void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
220     void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
221     void VisitTypeDecl(TypeDecl *TD);
222     void VisitTypedefNameDecl(TypedefNameDecl *TD);
223     void VisitTypedefDecl(TypedefDecl *TD);
224     void VisitTypeAliasDecl(TypeAliasDecl *TD);
225     void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
226     RedeclarableResult VisitTagDecl(TagDecl *TD);
227     void VisitEnumDecl(EnumDecl *ED);
228     RedeclarableResult VisitRecordDeclImpl(RecordDecl *RD);
229     void VisitRecordDecl(RecordDecl *RD) { VisitRecordDeclImpl(RD); }
230     RedeclarableResult VisitCXXRecordDeclImpl(CXXRecordDecl *D);
231     void VisitCXXRecordDecl(CXXRecordDecl *D) { VisitCXXRecordDeclImpl(D); }
232     RedeclarableResult VisitClassTemplateSpecializationDeclImpl(
233                                             ClassTemplateSpecializationDecl *D);
234     void VisitClassTemplateSpecializationDecl(
235         ClassTemplateSpecializationDecl *D) {
236       VisitClassTemplateSpecializationDeclImpl(D);
237     }
238     void VisitClassTemplatePartialSpecializationDecl(
239                                      ClassTemplatePartialSpecializationDecl *D);
240     void VisitClassScopeFunctionSpecializationDecl(
241                                        ClassScopeFunctionSpecializationDecl *D);
242     RedeclarableResult
243     VisitVarTemplateSpecializationDeclImpl(VarTemplateSpecializationDecl *D);
244     void VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D) {
245       VisitVarTemplateSpecializationDeclImpl(D);
246     }
247     void VisitVarTemplatePartialSpecializationDecl(
248         VarTemplatePartialSpecializationDecl *D);
249     void VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
250     void VisitValueDecl(ValueDecl *VD);
251     void VisitEnumConstantDecl(EnumConstantDecl *ECD);
252     void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
253     void VisitDeclaratorDecl(DeclaratorDecl *DD);
254     void VisitFunctionDecl(FunctionDecl *FD);
255     void VisitCXXMethodDecl(CXXMethodDecl *D);
256     void VisitCXXConstructorDecl(CXXConstructorDecl *D);
257     void VisitCXXDestructorDecl(CXXDestructorDecl *D);
258     void VisitCXXConversionDecl(CXXConversionDecl *D);
259     void VisitFieldDecl(FieldDecl *FD);
260     void VisitMSPropertyDecl(MSPropertyDecl *FD);
261     void VisitIndirectFieldDecl(IndirectFieldDecl *FD);
262     RedeclarableResult VisitVarDeclImpl(VarDecl *D);
263     void VisitVarDecl(VarDecl *VD) { VisitVarDeclImpl(VD); }
264     void VisitImplicitParamDecl(ImplicitParamDecl *PD);
265     void VisitParmVarDecl(ParmVarDecl *PD);
266     void VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
267     void VisitTemplateDecl(TemplateDecl *D);
268     RedeclarableResult VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D);
269     void VisitClassTemplateDecl(ClassTemplateDecl *D);
270     void VisitVarTemplateDecl(VarTemplateDecl *D);
271     void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
272     void VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
273     void VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
274     void VisitUsingDecl(UsingDecl *D);
275     void VisitUsingShadowDecl(UsingShadowDecl *D);
276     void VisitLinkageSpecDecl(LinkageSpecDecl *D);
277     void VisitFileScopeAsmDecl(FileScopeAsmDecl *AD);
278     void VisitImportDecl(ImportDecl *D);
279     void VisitAccessSpecDecl(AccessSpecDecl *D);
280     void VisitFriendDecl(FriendDecl *D);
281     void VisitFriendTemplateDecl(FriendTemplateDecl *D);
282     void VisitStaticAssertDecl(StaticAssertDecl *D);
283     void VisitBlockDecl(BlockDecl *BD);
284     void VisitCapturedDecl(CapturedDecl *CD);
285     void VisitEmptyDecl(EmptyDecl *D);
286 
287     std::pair<uint64_t, uint64_t> VisitDeclContext(DeclContext *DC);
288 
289     template<typename T>
290     RedeclarableResult VisitRedeclarable(Redeclarable<T> *D);
291 
292     template<typename T>
293     void mergeRedeclarable(Redeclarable<T> *D, RedeclarableResult &Redecl);
294 
295     template<typename T>
296     void mergeRedeclarable(Redeclarable<T> *D, T *Existing,
297                            RedeclarableResult &Redecl);
298 
299     template<typename T>
300     void mergeMergeable(Mergeable<T> *D);
301 
302     // FIXME: Reorder according to DeclNodes.td?
303     void VisitObjCMethodDecl(ObjCMethodDecl *D);
304     void VisitObjCContainerDecl(ObjCContainerDecl *D);
305     void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
306     void VisitObjCIvarDecl(ObjCIvarDecl *D);
307     void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
308     void VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D);
309     void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
310     void VisitObjCImplDecl(ObjCImplDecl *D);
311     void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
312     void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
313     void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D);
314     void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
315     void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
316     void VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D);
317   };
318 }
319 
320 uint64_t ASTDeclReader::GetCurrentCursorOffset() {
321   return F.DeclsCursor.GetCurrentBitNo() + F.GlobalBitOffset;
322 }
323 
324 void ASTDeclReader::Visit(Decl *D) {
325   DeclVisitor<ASTDeclReader, void>::Visit(D);
326 
327   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
328     if (DD->DeclInfo) {
329       DeclaratorDecl::ExtInfo *Info =
330           DD->DeclInfo.get<DeclaratorDecl::ExtInfo *>();
331       Info->TInfo =
332           GetTypeSourceInfo(Record, Idx);
333     }
334     else {
335       DD->DeclInfo = GetTypeSourceInfo(Record, Idx);
336     }
337   }
338 
339   if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
340     // if we have a fully initialized TypeDecl, we can safely read its type now.
341     TD->setTypeForDecl(Reader.GetType(TypeIDForTypeDecl).getTypePtrOrNull());
342   } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
343     // if we have a fully initialized TypeDecl, we can safely read its type now.
344     ID->TypeForDecl = Reader.GetType(TypeIDForTypeDecl).getTypePtrOrNull();
345   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
346     // FunctionDecl's body was written last after all other Stmts/Exprs.
347     // We only read it if FD doesn't already have a body (e.g., from another
348     // module).
349     // FIXME: Also consider = default and = delete.
350     // FIXME: Can we diagnose ODR violations somehow?
351     if (Record[Idx++]) {
352       Reader.PendingBodies[FD] = GetCurrentCursorOffset();
353       HasPendingBody = true;
354     }
355   }
356 }
357 
358 void ASTDeclReader::VisitDecl(Decl *D) {
359   if (D->isTemplateParameter()) {
360     // We don't want to deserialize the DeclContext of a template
361     // parameter immediately, because the template parameter might be
362     // used in the formulation of its DeclContext. Use the translation
363     // unit DeclContext as a placeholder.
364     GlobalDeclID SemaDCIDForTemplateParmDecl = ReadDeclID(Record, Idx);
365     GlobalDeclID LexicalDCIDForTemplateParmDecl = ReadDeclID(Record, Idx);
366     Reader.addPendingDeclContextInfo(D,
367                                      SemaDCIDForTemplateParmDecl,
368                                      LexicalDCIDForTemplateParmDecl);
369     D->setDeclContext(Reader.getContext().getTranslationUnitDecl());
370   } else {
371     DeclContext *SemaDC = ReadDeclAs<DeclContext>(Record, Idx);
372     DeclContext *LexicalDC = ReadDeclAs<DeclContext>(Record, Idx);
373     DeclContext *MergedSemaDC = Reader.MergedDeclContexts.lookup(SemaDC);
374     // Avoid calling setLexicalDeclContext() directly because it uses
375     // Decl::getASTContext() internally which is unsafe during derialization.
376     D->setDeclContextsImpl(MergedSemaDC ? MergedSemaDC : SemaDC, LexicalDC,
377                            Reader.getContext());
378   }
379   D->setLocation(Reader.ReadSourceLocation(F, RawLocation));
380   D->setInvalidDecl(Record[Idx++]);
381   if (Record[Idx++]) { // hasAttrs
382     AttrVec Attrs;
383     Reader.ReadAttributes(F, Attrs, Record, Idx);
384     // Avoid calling setAttrs() directly because it uses Decl::getASTContext()
385     // internally which is unsafe during derialization.
386     D->setAttrsImpl(Attrs, Reader.getContext());
387   }
388   D->setImplicit(Record[Idx++]);
389   D->setIsUsed(Record[Idx++]);
390   D->setReferenced(Record[Idx++]);
391   D->setTopLevelDeclInObjCContainer(Record[Idx++]);
392   D->setAccess((AccessSpecifier)Record[Idx++]);
393   D->FromASTFile = true;
394   D->setModulePrivate(Record[Idx++]);
395   D->Hidden = D->isModulePrivate();
396 
397   // Determine whether this declaration is part of a (sub)module. If so, it
398   // may not yet be visible.
399   if (unsigned SubmoduleID = readSubmoduleID(Record, Idx)) {
400     // Store the owning submodule ID in the declaration.
401     D->setOwningModuleID(SubmoduleID);
402 
403     // Module-private declarations are never visible, so there is no work to do.
404     if (!D->isModulePrivate()) {
405       if (Module *Owner = Reader.getSubmodule(SubmoduleID)) {
406         if (Owner->NameVisibility != Module::AllVisible) {
407           // The owning module is not visible. Mark this declaration as hidden.
408           D->Hidden = true;
409 
410           // Note that this declaration was hidden because its owning module is
411           // not yet visible.
412           Reader.HiddenNamesMap[Owner].push_back(D);
413         }
414       }
415     }
416   }
417 }
418 
419 void ASTDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) {
420   llvm_unreachable("Translation units are not serialized");
421 }
422 
423 void ASTDeclReader::VisitNamedDecl(NamedDecl *ND) {
424   VisitDecl(ND);
425   ND->setDeclName(Reader.ReadDeclarationName(F, Record, Idx));
426 }
427 
428 void ASTDeclReader::VisitTypeDecl(TypeDecl *TD) {
429   VisitNamedDecl(TD);
430   TD->setLocStart(ReadSourceLocation(Record, Idx));
431   // Delay type reading until after we have fully initialized the decl.
432   TypeIDForTypeDecl = Reader.getGlobalTypeID(F, Record[Idx++]);
433 }
434 
435 void ASTDeclReader::VisitTypedefNameDecl(TypedefNameDecl *TD) {
436   RedeclarableResult Redecl = VisitRedeclarable(TD);
437   VisitTypeDecl(TD);
438   TypeSourceInfo *TInfo = GetTypeSourceInfo(Record, Idx);
439   if (Record[Idx++]) { // isModed
440     QualType modedT = Reader.readType(F, Record, Idx);
441     TD->setModedTypeSourceInfo(TInfo, modedT);
442   } else
443     TD->setTypeSourceInfo(TInfo);
444   mergeRedeclarable(TD, Redecl);
445 }
446 
447 void ASTDeclReader::VisitTypedefDecl(TypedefDecl *TD) {
448   VisitTypedefNameDecl(TD);
449 }
450 
451 void ASTDeclReader::VisitTypeAliasDecl(TypeAliasDecl *TD) {
452   VisitTypedefNameDecl(TD);
453 }
454 
455 ASTDeclReader::RedeclarableResult ASTDeclReader::VisitTagDecl(TagDecl *TD) {
456   RedeclarableResult Redecl = VisitRedeclarable(TD);
457   VisitTypeDecl(TD);
458 
459   TD->IdentifierNamespace = Record[Idx++];
460   TD->setTagKind((TagDecl::TagKind)Record[Idx++]);
461   TD->setCompleteDefinition(Record[Idx++]);
462   TD->setEmbeddedInDeclarator(Record[Idx++]);
463   TD->setFreeStanding(Record[Idx++]);
464   TD->setCompleteDefinitionRequired(Record[Idx++]);
465   TD->setRBraceLoc(ReadSourceLocation(Record, Idx));
466 
467   if (Record[Idx++]) { // hasExtInfo
468     TagDecl::ExtInfo *Info = new (Reader.getContext()) TagDecl::ExtInfo();
469     ReadQualifierInfo(*Info, Record, Idx);
470     TD->NamedDeclOrQualifier = Info;
471   } else
472     TD->NamedDeclOrQualifier = ReadDeclAs<NamedDecl>(Record, Idx);
473 
474   mergeRedeclarable(TD, Redecl);
475   return Redecl;
476 }
477 
478 void ASTDeclReader::VisitEnumDecl(EnumDecl *ED) {
479   VisitTagDecl(ED);
480   if (TypeSourceInfo *TI = Reader.GetTypeSourceInfo(F, Record, Idx))
481     ED->setIntegerTypeSourceInfo(TI);
482   else
483     ED->setIntegerType(Reader.readType(F, Record, Idx));
484   ED->setPromotionType(Reader.readType(F, Record, Idx));
485   ED->setNumPositiveBits(Record[Idx++]);
486   ED->setNumNegativeBits(Record[Idx++]);
487   ED->IsScoped = Record[Idx++];
488   ED->IsScopedUsingClassTag = Record[Idx++];
489   ED->IsFixed = Record[Idx++];
490 
491   // If this is a definition subject to the ODR, and we already have a
492   // definition, merge this one into it.
493   if (ED->IsCompleteDefinition &&
494       Reader.getContext().getLangOpts().Modules &&
495       Reader.getContext().getLangOpts().CPlusPlus) {
496     if (EnumDecl *&OldDef = Reader.EnumDefinitions[ED->getCanonicalDecl()]) {
497       Reader.MergedDeclContexts.insert(std::make_pair(ED, OldDef));
498       ED->IsCompleteDefinition = false;
499     } else {
500       OldDef = ED;
501     }
502   }
503 
504   if (EnumDecl *InstED = ReadDeclAs<EnumDecl>(Record, Idx)) {
505     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
506     SourceLocation POI = ReadSourceLocation(Record, Idx);
507     ED->setInstantiationOfMemberEnum(Reader.getContext(), InstED, TSK);
508     ED->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
509   }
510 }
511 
512 ASTDeclReader::RedeclarableResult
513 ASTDeclReader::VisitRecordDeclImpl(RecordDecl *RD) {
514   RedeclarableResult Redecl = VisitTagDecl(RD);
515   RD->setHasFlexibleArrayMember(Record[Idx++]);
516   RD->setAnonymousStructOrUnion(Record[Idx++]);
517   RD->setHasObjectMember(Record[Idx++]);
518   RD->setHasVolatileMember(Record[Idx++]);
519   return Redecl;
520 }
521 
522 void ASTDeclReader::VisitValueDecl(ValueDecl *VD) {
523   VisitNamedDecl(VD);
524   VD->setType(Reader.readType(F, Record, Idx));
525 }
526 
527 void ASTDeclReader::VisitEnumConstantDecl(EnumConstantDecl *ECD) {
528   VisitValueDecl(ECD);
529   if (Record[Idx++])
530     ECD->setInitExpr(Reader.ReadExpr(F));
531   ECD->setInitVal(Reader.ReadAPSInt(Record, Idx));
532   mergeMergeable(ECD);
533 }
534 
535 void ASTDeclReader::VisitDeclaratorDecl(DeclaratorDecl *DD) {
536   VisitValueDecl(DD);
537   DD->setInnerLocStart(ReadSourceLocation(Record, Idx));
538   if (Record[Idx++]) { // hasExtInfo
539     DeclaratorDecl::ExtInfo *Info
540         = new (Reader.getContext()) DeclaratorDecl::ExtInfo();
541     ReadQualifierInfo(*Info, Record, Idx);
542     DD->DeclInfo = Info;
543   }
544 }
545 
546 void ASTDeclReader::VisitFunctionDecl(FunctionDecl *FD) {
547   RedeclarableResult Redecl = VisitRedeclarable(FD);
548   VisitDeclaratorDecl(FD);
549 
550   ReadDeclarationNameLoc(FD->DNLoc, FD->getDeclName(), Record, Idx);
551   FD->IdentifierNamespace = Record[Idx++];
552 
553   // FunctionDecl's body is handled last at ASTDeclReader::Visit,
554   // after everything else is read.
555 
556   FD->SClass = (StorageClass)Record[Idx++];
557   FD->IsInline = Record[Idx++];
558   FD->IsInlineSpecified = Record[Idx++];
559   FD->IsVirtualAsWritten = Record[Idx++];
560   FD->IsPure = Record[Idx++];
561   FD->HasInheritedPrototype = Record[Idx++];
562   FD->HasWrittenPrototype = Record[Idx++];
563   FD->IsDeleted = Record[Idx++];
564   FD->IsTrivial = Record[Idx++];
565   FD->IsDefaulted = Record[Idx++];
566   FD->IsExplicitlyDefaulted = Record[Idx++];
567   FD->HasImplicitReturnZero = Record[Idx++];
568   FD->IsConstexpr = Record[Idx++];
569   FD->HasSkippedBody = Record[Idx++];
570   FD->IsLateTemplateParsed = Record[Idx++];
571   FD->setCachedLinkage(Linkage(Record[Idx++]));
572   FD->EndRangeLoc = ReadSourceLocation(Record, Idx);
573 
574   switch ((FunctionDecl::TemplatedKind)Record[Idx++]) {
575   case FunctionDecl::TK_NonTemplate:
576     mergeRedeclarable(FD, Redecl);
577     break;
578   case FunctionDecl::TK_FunctionTemplate:
579     FD->setDescribedFunctionTemplate(ReadDeclAs<FunctionTemplateDecl>(Record,
580                                                                       Idx));
581     break;
582   case FunctionDecl::TK_MemberSpecialization: {
583     FunctionDecl *InstFD = ReadDeclAs<FunctionDecl>(Record, Idx);
584     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
585     SourceLocation POI = ReadSourceLocation(Record, Idx);
586     FD->setInstantiationOfMemberFunction(Reader.getContext(), InstFD, TSK);
587     FD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
588     break;
589   }
590   case FunctionDecl::TK_FunctionTemplateSpecialization: {
591     FunctionTemplateDecl *Template = ReadDeclAs<FunctionTemplateDecl>(Record,
592                                                                       Idx);
593     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
594 
595     // Template arguments.
596     SmallVector<TemplateArgument, 8> TemplArgs;
597     Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
598 
599     // Template args as written.
600     SmallVector<TemplateArgumentLoc, 8> TemplArgLocs;
601     SourceLocation LAngleLoc, RAngleLoc;
602     bool HasTemplateArgumentsAsWritten = Record[Idx++];
603     if (HasTemplateArgumentsAsWritten) {
604       unsigned NumTemplateArgLocs = Record[Idx++];
605       TemplArgLocs.reserve(NumTemplateArgLocs);
606       for (unsigned i=0; i != NumTemplateArgLocs; ++i)
607         TemplArgLocs.push_back(
608             Reader.ReadTemplateArgumentLoc(F, Record, Idx));
609 
610       LAngleLoc = ReadSourceLocation(Record, Idx);
611       RAngleLoc = ReadSourceLocation(Record, Idx);
612     }
613 
614     SourceLocation POI = ReadSourceLocation(Record, Idx);
615 
616     ASTContext &C = Reader.getContext();
617     TemplateArgumentList *TemplArgList
618       = TemplateArgumentList::CreateCopy(C, TemplArgs.data(), TemplArgs.size());
619     TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
620     for (unsigned i=0, e = TemplArgLocs.size(); i != e; ++i)
621       TemplArgsInfo.addArgument(TemplArgLocs[i]);
622     FunctionTemplateSpecializationInfo *FTInfo
623         = FunctionTemplateSpecializationInfo::Create(C, FD, Template, TSK,
624                                                      TemplArgList,
625                              HasTemplateArgumentsAsWritten ? &TemplArgsInfo : 0,
626                                                      POI);
627     FD->TemplateOrSpecialization = FTInfo;
628 
629     if (FD->isCanonicalDecl()) { // if canonical add to template's set.
630       // The template that contains the specializations set. It's not safe to
631       // use getCanonicalDecl on Template since it may still be initializing.
632       FunctionTemplateDecl *CanonTemplate
633         = ReadDeclAs<FunctionTemplateDecl>(Record, Idx);
634       // Get the InsertPos by FindNodeOrInsertPos() instead of calling
635       // InsertNode(FTInfo) directly to avoid the getASTContext() call in
636       // FunctionTemplateSpecializationInfo's Profile().
637       // We avoid getASTContext because a decl in the parent hierarchy may
638       // be initializing.
639       llvm::FoldingSetNodeID ID;
640       FunctionTemplateSpecializationInfo::Profile(ID, TemplArgs.data(),
641                                                   TemplArgs.size(), C);
642       void *InsertPos = 0;
643       FunctionTemplateDecl::Common *CommonPtr = CanonTemplate->getCommonPtr();
644       CommonPtr->Specializations.FindNodeOrInsertPos(ID, InsertPos);
645       if (InsertPos)
646         CommonPtr->Specializations.InsertNode(FTInfo, InsertPos);
647       else {
648         assert(Reader.getContext().getLangOpts().Modules &&
649                "already deserialized this template specialization");
650         // FIXME: This specialization is a redeclaration of one from another
651         // module. Merge it.
652       }
653     }
654     break;
655   }
656   case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
657     // Templates.
658     UnresolvedSet<8> TemplDecls;
659     unsigned NumTemplates = Record[Idx++];
660     while (NumTemplates--)
661       TemplDecls.addDecl(ReadDeclAs<NamedDecl>(Record, Idx));
662 
663     // Templates args.
664     TemplateArgumentListInfo TemplArgs;
665     unsigned NumArgs = Record[Idx++];
666     while (NumArgs--)
667       TemplArgs.addArgument(Reader.ReadTemplateArgumentLoc(F, Record, Idx));
668     TemplArgs.setLAngleLoc(ReadSourceLocation(Record, Idx));
669     TemplArgs.setRAngleLoc(ReadSourceLocation(Record, Idx));
670 
671     FD->setDependentTemplateSpecialization(Reader.getContext(),
672                                            TemplDecls, TemplArgs);
673     break;
674   }
675   }
676 
677   // Read in the parameters.
678   unsigned NumParams = Record[Idx++];
679   SmallVector<ParmVarDecl *, 16> Params;
680   Params.reserve(NumParams);
681   for (unsigned I = 0; I != NumParams; ++I)
682     Params.push_back(ReadDeclAs<ParmVarDecl>(Record, Idx));
683   FD->setParams(Reader.getContext(), Params);
684 }
685 
686 void ASTDeclReader::VisitObjCMethodDecl(ObjCMethodDecl *MD) {
687   VisitNamedDecl(MD);
688   if (Record[Idx++]) {
689     // Load the body on-demand. Most clients won't care, because method
690     // definitions rarely show up in headers.
691     Reader.PendingBodies[MD] = GetCurrentCursorOffset();
692     HasPendingBody = true;
693     MD->setSelfDecl(ReadDeclAs<ImplicitParamDecl>(Record, Idx));
694     MD->setCmdDecl(ReadDeclAs<ImplicitParamDecl>(Record, Idx));
695   }
696   MD->setInstanceMethod(Record[Idx++]);
697   MD->setVariadic(Record[Idx++]);
698   MD->setPropertyAccessor(Record[Idx++]);
699   MD->setDefined(Record[Idx++]);
700   MD->IsOverriding = Record[Idx++];
701   MD->HasSkippedBody = Record[Idx++];
702 
703   MD->IsRedeclaration = Record[Idx++];
704   MD->HasRedeclaration = Record[Idx++];
705   if (MD->HasRedeclaration)
706     Reader.getContext().setObjCMethodRedeclaration(MD,
707                                        ReadDeclAs<ObjCMethodDecl>(Record, Idx));
708 
709   MD->setDeclImplementation((ObjCMethodDecl::ImplementationControl)Record[Idx++]);
710   MD->setObjCDeclQualifier((Decl::ObjCDeclQualifier)Record[Idx++]);
711   MD->SetRelatedResultType(Record[Idx++]);
712   MD->setResultType(Reader.readType(F, Record, Idx));
713   MD->setResultTypeSourceInfo(GetTypeSourceInfo(Record, Idx));
714   MD->DeclEndLoc = ReadSourceLocation(Record, Idx);
715   unsigned NumParams = Record[Idx++];
716   SmallVector<ParmVarDecl *, 16> Params;
717   Params.reserve(NumParams);
718   for (unsigned I = 0; I != NumParams; ++I)
719     Params.push_back(ReadDeclAs<ParmVarDecl>(Record, Idx));
720 
721   MD->SelLocsKind = Record[Idx++];
722   unsigned NumStoredSelLocs = Record[Idx++];
723   SmallVector<SourceLocation, 16> SelLocs;
724   SelLocs.reserve(NumStoredSelLocs);
725   for (unsigned i = 0; i != NumStoredSelLocs; ++i)
726     SelLocs.push_back(ReadSourceLocation(Record, Idx));
727 
728   MD->setParamsAndSelLocs(Reader.getContext(), Params, SelLocs);
729 }
730 
731 void ASTDeclReader::VisitObjCContainerDecl(ObjCContainerDecl *CD) {
732   VisitNamedDecl(CD);
733   CD->setAtStartLoc(ReadSourceLocation(Record, Idx));
734   CD->setAtEndRange(ReadSourceRange(Record, Idx));
735 }
736 
737 void ASTDeclReader::VisitObjCInterfaceDecl(ObjCInterfaceDecl *ID) {
738   RedeclarableResult Redecl = VisitRedeclarable(ID);
739   VisitObjCContainerDecl(ID);
740   TypeIDForTypeDecl = Reader.getGlobalTypeID(F, Record[Idx++]);
741   mergeRedeclarable(ID, Redecl);
742 
743   if (Record[Idx++]) {
744     // Read the definition.
745     ID->allocateDefinitionData();
746 
747     // Set the definition data of the canonical declaration, so other
748     // redeclarations will see it.
749     ID->getCanonicalDecl()->Data = ID->Data;
750 
751     ObjCInterfaceDecl::DefinitionData &Data = ID->data();
752 
753     // Read the superclass.
754     Data.SuperClass = ReadDeclAs<ObjCInterfaceDecl>(Record, Idx);
755     Data.SuperClassLoc = ReadSourceLocation(Record, Idx);
756 
757     Data.EndLoc = ReadSourceLocation(Record, Idx);
758 
759     // Read the directly referenced protocols and their SourceLocations.
760     unsigned NumProtocols = Record[Idx++];
761     SmallVector<ObjCProtocolDecl *, 16> Protocols;
762     Protocols.reserve(NumProtocols);
763     for (unsigned I = 0; I != NumProtocols; ++I)
764       Protocols.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
765     SmallVector<SourceLocation, 16> ProtoLocs;
766     ProtoLocs.reserve(NumProtocols);
767     for (unsigned I = 0; I != NumProtocols; ++I)
768       ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
769     ID->setProtocolList(Protocols.data(), NumProtocols, ProtoLocs.data(),
770                         Reader.getContext());
771 
772     // Read the transitive closure of protocols referenced by this class.
773     NumProtocols = Record[Idx++];
774     Protocols.clear();
775     Protocols.reserve(NumProtocols);
776     for (unsigned I = 0; I != NumProtocols; ++I)
777       Protocols.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
778     ID->data().AllReferencedProtocols.set(Protocols.data(), NumProtocols,
779                                           Reader.getContext());
780 
781     // We will rebuild this list lazily.
782     ID->setIvarList(0);
783 
784     // Note that we have deserialized a definition.
785     Reader.PendingDefinitions.insert(ID);
786 
787     // Note that we've loaded this Objective-C class.
788     Reader.ObjCClassesLoaded.push_back(ID);
789   } else {
790     ID->Data = ID->getCanonicalDecl()->Data;
791   }
792 }
793 
794 void ASTDeclReader::VisitObjCIvarDecl(ObjCIvarDecl *IVD) {
795   VisitFieldDecl(IVD);
796   IVD->setAccessControl((ObjCIvarDecl::AccessControl)Record[Idx++]);
797   // This field will be built lazily.
798   IVD->setNextIvar(0);
799   bool synth = Record[Idx++];
800   IVD->setSynthesize(synth);
801 }
802 
803 void ASTDeclReader::VisitObjCProtocolDecl(ObjCProtocolDecl *PD) {
804   RedeclarableResult Redecl = VisitRedeclarable(PD);
805   VisitObjCContainerDecl(PD);
806   mergeRedeclarable(PD, Redecl);
807 
808   if (Record[Idx++]) {
809     // Read the definition.
810     PD->allocateDefinitionData();
811 
812     // Set the definition data of the canonical declaration, so other
813     // redeclarations will see it.
814     PD->getCanonicalDecl()->Data = PD->Data;
815 
816     unsigned NumProtoRefs = Record[Idx++];
817     SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
818     ProtoRefs.reserve(NumProtoRefs);
819     for (unsigned I = 0; I != NumProtoRefs; ++I)
820       ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
821     SmallVector<SourceLocation, 16> ProtoLocs;
822     ProtoLocs.reserve(NumProtoRefs);
823     for (unsigned I = 0; I != NumProtoRefs; ++I)
824       ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
825     PD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
826                         Reader.getContext());
827 
828     // Note that we have deserialized a definition.
829     Reader.PendingDefinitions.insert(PD);
830   } else {
831     PD->Data = PD->getCanonicalDecl()->Data;
832   }
833 }
834 
835 void ASTDeclReader::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *FD) {
836   VisitFieldDecl(FD);
837 }
838 
839 void ASTDeclReader::VisitObjCCategoryDecl(ObjCCategoryDecl *CD) {
840   VisitObjCContainerDecl(CD);
841   CD->setCategoryNameLoc(ReadSourceLocation(Record, Idx));
842   CD->setIvarLBraceLoc(ReadSourceLocation(Record, Idx));
843   CD->setIvarRBraceLoc(ReadSourceLocation(Record, Idx));
844 
845   // Note that this category has been deserialized. We do this before
846   // deserializing the interface declaration, so that it will consider this
847   /// category.
848   Reader.CategoriesDeserialized.insert(CD);
849 
850   CD->ClassInterface = ReadDeclAs<ObjCInterfaceDecl>(Record, Idx);
851   unsigned NumProtoRefs = Record[Idx++];
852   SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
853   ProtoRefs.reserve(NumProtoRefs);
854   for (unsigned I = 0; I != NumProtoRefs; ++I)
855     ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
856   SmallVector<SourceLocation, 16> ProtoLocs;
857   ProtoLocs.reserve(NumProtoRefs);
858   for (unsigned I = 0; I != NumProtoRefs; ++I)
859     ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
860   CD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
861                       Reader.getContext());
862 }
863 
864 void ASTDeclReader::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *CAD) {
865   VisitNamedDecl(CAD);
866   CAD->setClassInterface(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
867 }
868 
869 void ASTDeclReader::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
870   VisitNamedDecl(D);
871   D->setAtLoc(ReadSourceLocation(Record, Idx));
872   D->setLParenLoc(ReadSourceLocation(Record, Idx));
873   D->setType(GetTypeSourceInfo(Record, Idx));
874   // FIXME: stable encoding
875   D->setPropertyAttributes(
876                       (ObjCPropertyDecl::PropertyAttributeKind)Record[Idx++]);
877   D->setPropertyAttributesAsWritten(
878                       (ObjCPropertyDecl::PropertyAttributeKind)Record[Idx++]);
879   // FIXME: stable encoding
880   D->setPropertyImplementation(
881                             (ObjCPropertyDecl::PropertyControl)Record[Idx++]);
882   D->setGetterName(Reader.ReadDeclarationName(F,Record, Idx).getObjCSelector());
883   D->setSetterName(Reader.ReadDeclarationName(F,Record, Idx).getObjCSelector());
884   D->setGetterMethodDecl(ReadDeclAs<ObjCMethodDecl>(Record, Idx));
885   D->setSetterMethodDecl(ReadDeclAs<ObjCMethodDecl>(Record, Idx));
886   D->setPropertyIvarDecl(ReadDeclAs<ObjCIvarDecl>(Record, Idx));
887 }
888 
889 void ASTDeclReader::VisitObjCImplDecl(ObjCImplDecl *D) {
890   VisitObjCContainerDecl(D);
891   D->setClassInterface(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
892 }
893 
894 void ASTDeclReader::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
895   VisitObjCImplDecl(D);
896   D->setIdentifier(Reader.GetIdentifierInfo(F, Record, Idx));
897   D->CategoryNameLoc = ReadSourceLocation(Record, Idx);
898 }
899 
900 void ASTDeclReader::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
901   VisitObjCImplDecl(D);
902   D->setSuperClass(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
903   D->SuperLoc = ReadSourceLocation(Record, Idx);
904   D->setIvarLBraceLoc(ReadSourceLocation(Record, Idx));
905   D->setIvarRBraceLoc(ReadSourceLocation(Record, Idx));
906   D->setHasNonZeroConstructors(Record[Idx++]);
907   D->setHasDestructors(Record[Idx++]);
908   llvm::tie(D->IvarInitializers, D->NumIvarInitializers)
909       = Reader.ReadCXXCtorInitializers(F, Record, Idx);
910 }
911 
912 
913 void ASTDeclReader::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
914   VisitDecl(D);
915   D->setAtLoc(ReadSourceLocation(Record, Idx));
916   D->setPropertyDecl(ReadDeclAs<ObjCPropertyDecl>(Record, Idx));
917   D->PropertyIvarDecl = ReadDeclAs<ObjCIvarDecl>(Record, Idx);
918   D->IvarLoc = ReadSourceLocation(Record, Idx);
919   D->setGetterCXXConstructor(Reader.ReadExpr(F));
920   D->setSetterCXXAssignment(Reader.ReadExpr(F));
921 }
922 
923 void ASTDeclReader::VisitFieldDecl(FieldDecl *FD) {
924   VisitDeclaratorDecl(FD);
925   FD->Mutable = Record[Idx++];
926   if (int BitWidthOrInitializer = Record[Idx++]) {
927     FD->InitializerOrBitWidth.setInt(BitWidthOrInitializer - 1);
928     FD->InitializerOrBitWidth.setPointer(Reader.ReadExpr(F));
929   }
930   if (!FD->getDeclName()) {
931     if (FieldDecl *Tmpl = ReadDeclAs<FieldDecl>(Record, Idx))
932       Reader.getContext().setInstantiatedFromUnnamedFieldDecl(FD, Tmpl);
933   }
934   mergeMergeable(FD);
935 }
936 
937 void ASTDeclReader::VisitMSPropertyDecl(MSPropertyDecl *PD) {
938   VisitDeclaratorDecl(PD);
939   PD->GetterId = Reader.GetIdentifierInfo(F, Record, Idx);
940   PD->SetterId = Reader.GetIdentifierInfo(F, Record, Idx);
941 }
942 
943 void ASTDeclReader::VisitIndirectFieldDecl(IndirectFieldDecl *FD) {
944   VisitValueDecl(FD);
945 
946   FD->ChainingSize = Record[Idx++];
947   assert(FD->ChainingSize >= 2 && "Anonymous chaining must be >= 2");
948   FD->Chaining = new (Reader.getContext())NamedDecl*[FD->ChainingSize];
949 
950   for (unsigned I = 0; I != FD->ChainingSize; ++I)
951     FD->Chaining[I] = ReadDeclAs<NamedDecl>(Record, Idx);
952 }
953 
954 ASTDeclReader::RedeclarableResult ASTDeclReader::VisitVarDeclImpl(VarDecl *VD) {
955   RedeclarableResult Redecl = VisitRedeclarable(VD);
956   VisitDeclaratorDecl(VD);
957 
958   VD->VarDeclBits.SClass = (StorageClass)Record[Idx++];
959   VD->VarDeclBits.TSCSpec = Record[Idx++];
960   VD->VarDeclBits.InitStyle = Record[Idx++];
961   VD->VarDeclBits.ExceptionVar = Record[Idx++];
962   VD->VarDeclBits.NRVOVariable = Record[Idx++];
963   VD->VarDeclBits.CXXForRangeDecl = Record[Idx++];
964   VD->VarDeclBits.ARCPseudoStrong = Record[Idx++];
965   VD->VarDeclBits.IsConstexpr = Record[Idx++];
966   VD->VarDeclBits.IsInitCapture = Record[Idx++];
967   VD->VarDeclBits.PreviousDeclInSameBlockScope = Record[Idx++];
968   Linkage VarLinkage = Linkage(Record[Idx++]);
969   VD->setCachedLinkage(VarLinkage);
970 
971   // Reconstruct the one piece of the IdentifierNamespace that we need.
972   if (VarLinkage != NoLinkage &&
973       VD->getLexicalDeclContext()->isFunctionOrMethod())
974     VD->setLocalExternDecl();
975 
976   // Only true variables (not parameters or implicit parameters) can be merged.
977   if (VD->getKind() != Decl::ParmVar && VD->getKind() != Decl::ImplicitParam)
978     mergeRedeclarable(VD, Redecl);
979 
980   if (uint64_t Val = Record[Idx++]) {
981     VD->setInit(Reader.ReadExpr(F));
982     if (Val > 1) {
983       EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
984       Eval->CheckedICE = true;
985       Eval->IsICE = Val == 3;
986     }
987   }
988 
989   enum VarKind {
990     VarNotTemplate = 0, VarTemplate, StaticDataMemberSpecialization
991   };
992   switch ((VarKind)Record[Idx++]) {
993   case VarNotTemplate:
994     break;
995   case VarTemplate:
996     VD->setDescribedVarTemplate(ReadDeclAs<VarTemplateDecl>(Record, Idx));
997     break;
998   case StaticDataMemberSpecialization: { // HasMemberSpecializationInfo.
999     VarDecl *Tmpl = ReadDeclAs<VarDecl>(Record, Idx);
1000     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
1001     SourceLocation POI = ReadSourceLocation(Record, Idx);
1002     Reader.getContext().setInstantiatedFromStaticDataMember(VD, Tmpl, TSK,POI);
1003     break;
1004   }
1005   }
1006 
1007   return Redecl;
1008 }
1009 
1010 void ASTDeclReader::VisitImplicitParamDecl(ImplicitParamDecl *PD) {
1011   VisitVarDecl(PD);
1012 }
1013 
1014 void ASTDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
1015   VisitVarDecl(PD);
1016   unsigned isObjCMethodParam = Record[Idx++];
1017   unsigned scopeDepth = Record[Idx++];
1018   unsigned scopeIndex = Record[Idx++];
1019   unsigned declQualifier = Record[Idx++];
1020   if (isObjCMethodParam) {
1021     assert(scopeDepth == 0);
1022     PD->setObjCMethodScopeInfo(scopeIndex);
1023     PD->ParmVarDeclBits.ScopeDepthOrObjCQuals = declQualifier;
1024   } else {
1025     PD->setScopeInfo(scopeDepth, scopeIndex);
1026   }
1027   PD->ParmVarDeclBits.IsKNRPromoted = Record[Idx++];
1028   PD->ParmVarDeclBits.HasInheritedDefaultArg = Record[Idx++];
1029   if (Record[Idx++]) // hasUninstantiatedDefaultArg.
1030     PD->setUninstantiatedDefaultArg(Reader.ReadExpr(F));
1031 
1032   // FIXME: If this is a redeclaration of a function from another module, handle
1033   // inheritance of default arguments.
1034 }
1035 
1036 void ASTDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {
1037   VisitDecl(AD);
1038   AD->setAsmString(cast<StringLiteral>(Reader.ReadExpr(F)));
1039   AD->setRParenLoc(ReadSourceLocation(Record, Idx));
1040 }
1041 
1042 void ASTDeclReader::VisitBlockDecl(BlockDecl *BD) {
1043   VisitDecl(BD);
1044   BD->setBody(cast_or_null<CompoundStmt>(Reader.ReadStmt(F)));
1045   BD->setSignatureAsWritten(GetTypeSourceInfo(Record, Idx));
1046   unsigned NumParams = Record[Idx++];
1047   SmallVector<ParmVarDecl *, 16> Params;
1048   Params.reserve(NumParams);
1049   for (unsigned I = 0; I != NumParams; ++I)
1050     Params.push_back(ReadDeclAs<ParmVarDecl>(Record, Idx));
1051   BD->setParams(Params);
1052 
1053   BD->setIsVariadic(Record[Idx++]);
1054   BD->setBlockMissingReturnType(Record[Idx++]);
1055   BD->setIsConversionFromLambda(Record[Idx++]);
1056 
1057   bool capturesCXXThis = Record[Idx++];
1058   unsigned numCaptures = Record[Idx++];
1059   SmallVector<BlockDecl::Capture, 16> captures;
1060   captures.reserve(numCaptures);
1061   for (unsigned i = 0; i != numCaptures; ++i) {
1062     VarDecl *decl = ReadDeclAs<VarDecl>(Record, Idx);
1063     unsigned flags = Record[Idx++];
1064     bool byRef = (flags & 1);
1065     bool nested = (flags & 2);
1066     Expr *copyExpr = ((flags & 4) ? Reader.ReadExpr(F) : 0);
1067 
1068     captures.push_back(BlockDecl::Capture(decl, byRef, nested, copyExpr));
1069   }
1070   BD->setCaptures(Reader.getContext(), captures.begin(),
1071                   captures.end(), capturesCXXThis);
1072 }
1073 
1074 void ASTDeclReader::VisitCapturedDecl(CapturedDecl *CD) {
1075   VisitDecl(CD);
1076   // Body is set by VisitCapturedStmt.
1077   for (unsigned i = 0; i < CD->NumParams; ++i)
1078     CD->setParam(i, ReadDeclAs<ImplicitParamDecl>(Record, Idx));
1079 }
1080 
1081 void ASTDeclReader::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1082   VisitDecl(D);
1083   D->setLanguage((LinkageSpecDecl::LanguageIDs)Record[Idx++]);
1084   D->setExternLoc(ReadSourceLocation(Record, Idx));
1085   D->setRBraceLoc(ReadSourceLocation(Record, Idx));
1086 }
1087 
1088 void ASTDeclReader::VisitLabelDecl(LabelDecl *D) {
1089   VisitNamedDecl(D);
1090   D->setLocStart(ReadSourceLocation(Record, Idx));
1091 }
1092 
1093 
1094 void ASTDeclReader::VisitNamespaceDecl(NamespaceDecl *D) {
1095   RedeclarableResult Redecl = VisitRedeclarable(D);
1096   VisitNamedDecl(D);
1097   D->setInline(Record[Idx++]);
1098   D->LocStart = ReadSourceLocation(Record, Idx);
1099   D->RBraceLoc = ReadSourceLocation(Record, Idx);
1100   // FIXME: At the point of this call, D->getCanonicalDecl() returns 0.
1101   mergeRedeclarable(D, Redecl);
1102 
1103   if (Redecl.getFirstID() == ThisDeclID) {
1104     // Each module has its own anonymous namespace, which is disjoint from
1105     // any other module's anonymous namespaces, so don't attach the anonymous
1106     // namespace at all.
1107     NamespaceDecl *Anon = ReadDeclAs<NamespaceDecl>(Record, Idx);
1108     if (F.Kind != MK_Module)
1109       D->setAnonymousNamespace(Anon);
1110   } else {
1111     // Link this namespace back to the first declaration, which has already
1112     // been deserialized.
1113     D->AnonOrFirstNamespaceAndInline.setPointer(D->getFirstDecl());
1114   }
1115 }
1116 
1117 void ASTDeclReader::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1118   VisitNamedDecl(D);
1119   D->NamespaceLoc = ReadSourceLocation(Record, Idx);
1120   D->IdentLoc = ReadSourceLocation(Record, Idx);
1121   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1122   D->Namespace = ReadDeclAs<NamedDecl>(Record, Idx);
1123 }
1124 
1125 void ASTDeclReader::VisitUsingDecl(UsingDecl *D) {
1126   VisitNamedDecl(D);
1127   D->setUsingLoc(ReadSourceLocation(Record, Idx));
1128   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1129   ReadDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record, Idx);
1130   D->FirstUsingShadow.setPointer(ReadDeclAs<UsingShadowDecl>(Record, Idx));
1131   D->setTypename(Record[Idx++]);
1132   if (NamedDecl *Pattern = ReadDeclAs<NamedDecl>(Record, Idx))
1133     Reader.getContext().setInstantiatedFromUsingDecl(D, Pattern);
1134 }
1135 
1136 void ASTDeclReader::VisitUsingShadowDecl(UsingShadowDecl *D) {
1137   VisitNamedDecl(D);
1138   D->setTargetDecl(ReadDeclAs<NamedDecl>(Record, Idx));
1139   D->UsingOrNextShadow = ReadDeclAs<NamedDecl>(Record, Idx);
1140   UsingShadowDecl *Pattern = ReadDeclAs<UsingShadowDecl>(Record, Idx);
1141   if (Pattern)
1142     Reader.getContext().setInstantiatedFromUsingShadowDecl(D, Pattern);
1143 }
1144 
1145 void ASTDeclReader::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1146   VisitNamedDecl(D);
1147   D->UsingLoc = ReadSourceLocation(Record, Idx);
1148   D->NamespaceLoc = ReadSourceLocation(Record, Idx);
1149   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1150   D->NominatedNamespace = ReadDeclAs<NamedDecl>(Record, Idx);
1151   D->CommonAncestor = ReadDeclAs<DeclContext>(Record, Idx);
1152 }
1153 
1154 void ASTDeclReader::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1155   VisitValueDecl(D);
1156   D->setUsingLoc(ReadSourceLocation(Record, Idx));
1157   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1158   ReadDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record, Idx);
1159 }
1160 
1161 void ASTDeclReader::VisitUnresolvedUsingTypenameDecl(
1162                                                UnresolvedUsingTypenameDecl *D) {
1163   VisitTypeDecl(D);
1164   D->TypenameLocation = ReadSourceLocation(Record, Idx);
1165   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1166 }
1167 
1168 void ASTDeclReader::ReadCXXDefinitionData(
1169                                    struct CXXRecordDecl::DefinitionData &Data,
1170                                    const RecordData &Record, unsigned &Idx) {
1171   // Note: the caller has deserialized the IsLambda bit already.
1172   Data.UserDeclaredConstructor = Record[Idx++];
1173   Data.UserDeclaredSpecialMembers = Record[Idx++];
1174   Data.Aggregate = Record[Idx++];
1175   Data.PlainOldData = Record[Idx++];
1176   Data.Empty = Record[Idx++];
1177   Data.Polymorphic = Record[Idx++];
1178   Data.Abstract = Record[Idx++];
1179   Data.IsStandardLayout = Record[Idx++];
1180   Data.HasNoNonEmptyBases = Record[Idx++];
1181   Data.HasPrivateFields = Record[Idx++];
1182   Data.HasProtectedFields = Record[Idx++];
1183   Data.HasPublicFields = Record[Idx++];
1184   Data.HasMutableFields = Record[Idx++];
1185   Data.HasOnlyCMembers = Record[Idx++];
1186   Data.HasInClassInitializer = Record[Idx++];
1187   Data.HasUninitializedReferenceMember = Record[Idx++];
1188   Data.NeedOverloadResolutionForMoveConstructor = Record[Idx++];
1189   Data.NeedOverloadResolutionForMoveAssignment = Record[Idx++];
1190   Data.NeedOverloadResolutionForDestructor = Record[Idx++];
1191   Data.DefaultedMoveConstructorIsDeleted = Record[Idx++];
1192   Data.DefaultedMoveAssignmentIsDeleted = Record[Idx++];
1193   Data.DefaultedDestructorIsDeleted = Record[Idx++];
1194   Data.HasTrivialSpecialMembers = Record[Idx++];
1195   Data.HasIrrelevantDestructor = Record[Idx++];
1196   Data.HasConstexprNonCopyMoveConstructor = Record[Idx++];
1197   Data.DefaultedDefaultConstructorIsConstexpr = Record[Idx++];
1198   Data.HasConstexprDefaultConstructor = Record[Idx++];
1199   Data.HasNonLiteralTypeFieldsOrBases = Record[Idx++];
1200   Data.ComputedVisibleConversions = Record[Idx++];
1201   Data.UserProvidedDefaultConstructor = Record[Idx++];
1202   Data.DeclaredSpecialMembers = Record[Idx++];
1203   Data.ImplicitCopyConstructorHasConstParam = Record[Idx++];
1204   Data.ImplicitCopyAssignmentHasConstParam = Record[Idx++];
1205   Data.HasDeclaredCopyConstructorWithConstParam = Record[Idx++];
1206   Data.HasDeclaredCopyAssignmentWithConstParam = Record[Idx++];
1207   Data.FailedImplicitMoveConstructor = Record[Idx++];
1208   Data.FailedImplicitMoveAssignment = Record[Idx++];
1209 
1210   Data.NumBases = Record[Idx++];
1211   if (Data.NumBases)
1212     Data.Bases = Reader.readCXXBaseSpecifiers(F, Record, Idx);
1213   Data.NumVBases = Record[Idx++];
1214   if (Data.NumVBases)
1215     Data.VBases = Reader.readCXXBaseSpecifiers(F, Record, Idx);
1216 
1217   Reader.ReadUnresolvedSet(F, Data.Conversions, Record, Idx);
1218   Reader.ReadUnresolvedSet(F, Data.VisibleConversions, Record, Idx);
1219   assert(Data.Definition && "Data.Definition should be already set!");
1220   Data.FirstFriend = ReadDeclID(Record, Idx);
1221 
1222   if (Data.IsLambda) {
1223     typedef LambdaExpr::Capture Capture;
1224     CXXRecordDecl::LambdaDefinitionData &Lambda
1225       = static_cast<CXXRecordDecl::LambdaDefinitionData &>(Data);
1226     Lambda.Dependent = Record[Idx++];
1227     Lambda.NumCaptures = Record[Idx++];
1228     Lambda.NumExplicitCaptures = Record[Idx++];
1229     Lambda.ManglingNumber = Record[Idx++];
1230     Lambda.ContextDecl = ReadDecl(Record, Idx);
1231     Lambda.Captures
1232       = (Capture*)Reader.Context.Allocate(sizeof(Capture)*Lambda.NumCaptures);
1233     Capture *ToCapture = Lambda.Captures;
1234     Lambda.MethodTyInfo = GetTypeSourceInfo(Record, Idx);
1235     Lambda.TheLambdaExpr = cast<LambdaExpr>(Reader.ReadExpr(F));
1236     for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
1237       SourceLocation Loc = ReadSourceLocation(Record, Idx);
1238       bool IsImplicit = Record[Idx++];
1239       LambdaCaptureKind Kind = static_cast<LambdaCaptureKind>(Record[Idx++]);
1240       switch (Kind) {
1241       case LCK_This:
1242         *ToCapture++ = Capture(Loc, IsImplicit, Kind, 0, SourceLocation());
1243         break;
1244       case LCK_ByCopy:
1245       case LCK_ByRef:
1246         VarDecl *Var = ReadDeclAs<VarDecl>(Record, Idx);
1247         SourceLocation EllipsisLoc = ReadSourceLocation(Record, Idx);
1248         *ToCapture++ = Capture(Loc, IsImplicit, Kind, Var, EllipsisLoc);
1249         break;
1250       }
1251     }
1252   }
1253 }
1254 
1255 ASTDeclReader::RedeclarableResult
1256 ASTDeclReader::VisitCXXRecordDeclImpl(CXXRecordDecl *D) {
1257   RedeclarableResult Redecl = VisitRecordDeclImpl(D);
1258 
1259   ASTContext &C = Reader.getContext();
1260   bool WasDefinition = Record[Idx++];
1261   if (WasDefinition) {
1262     // Determine whether this is a lambda closure type, so that we can
1263     // allocate the appropriate DefinitionData structure.
1264     bool IsLambda = Record[Idx++];
1265     if (IsLambda)
1266       D->DefinitionData = new (C) CXXRecordDecl::LambdaDefinitionData(D, 0,
1267                                                                       false);
1268     else
1269       D->DefinitionData = new (C) struct CXXRecordDecl::DefinitionData(D);
1270 
1271     ReadCXXDefinitionData(*D->DefinitionData, Record, Idx);
1272 
1273     // Propagate the DefinitionData pointer to the canonical declaration, so
1274     // that all other deserialized declarations will see it.
1275     CXXRecordDecl *Canon = D->getCanonicalDecl();
1276     if (Canon == D) {
1277       // Nothing to do.
1278     } else if (!Canon->DefinitionData) {
1279       Canon->DefinitionData = D->DefinitionData;
1280 
1281       // Note that we have deserialized a definition. Any declarations
1282       // deserialized before this one will be be given the DefinitionData
1283       // pointer at the end.
1284       Reader.PendingDefinitions.insert(D);
1285     } else {
1286       // We have already deserialized a definition of this record. This
1287       // definition is no longer really a definition. Note that the pre-existing
1288       // definition is the *real* definition.
1289       // FIXME: Check DefinitionData for consistency with prior definition.
1290       Reader.MergedDeclContexts.insert(
1291           std::make_pair(D, D->getCanonicalDecl()->DefinitionData->Definition));
1292       D->IsCompleteDefinition = false;
1293       D->DefinitionData = D->getCanonicalDecl()->DefinitionData;
1294     }
1295   } else {
1296     // Propagate DefinitionData pointer from the canonical declaration.
1297     D->DefinitionData = D->getCanonicalDecl()->DefinitionData;
1298   }
1299 
1300   enum CXXRecKind {
1301     CXXRecNotTemplate = 0, CXXRecTemplate, CXXRecMemberSpecialization
1302   };
1303   switch ((CXXRecKind)Record[Idx++]) {
1304   case CXXRecNotTemplate:
1305     break;
1306   case CXXRecTemplate:
1307     D->TemplateOrInstantiation = ReadDeclAs<ClassTemplateDecl>(Record, Idx);
1308     break;
1309   case CXXRecMemberSpecialization: {
1310     CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(Record, Idx);
1311     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
1312     SourceLocation POI = ReadSourceLocation(Record, Idx);
1313     MemberSpecializationInfo *MSI = new (C) MemberSpecializationInfo(RD, TSK);
1314     MSI->setPointOfInstantiation(POI);
1315     D->TemplateOrInstantiation = MSI;
1316     break;
1317   }
1318   }
1319 
1320   // Lazily load the key function to avoid deserializing every method so we can
1321   // compute it.
1322   if (WasDefinition) {
1323     DeclID KeyFn = ReadDeclID(Record, Idx);
1324     if (KeyFn && D->IsCompleteDefinition)
1325       C.KeyFunctions[D] = KeyFn;
1326   }
1327 
1328   return Redecl;
1329 }
1330 
1331 void ASTDeclReader::VisitCXXMethodDecl(CXXMethodDecl *D) {
1332   VisitFunctionDecl(D);
1333   unsigned NumOverridenMethods = Record[Idx++];
1334   while (NumOverridenMethods--) {
1335     // Avoid invariant checking of CXXMethodDecl::addOverriddenMethod,
1336     // MD may be initializing.
1337     if (CXXMethodDecl *MD = ReadDeclAs<CXXMethodDecl>(Record, Idx))
1338       Reader.getContext().addOverriddenMethod(D, MD);
1339   }
1340 }
1341 
1342 void ASTDeclReader::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1343   VisitCXXMethodDecl(D);
1344 
1345   D->IsExplicitSpecified = Record[Idx++];
1346   llvm::tie(D->CtorInitializers, D->NumCtorInitializers)
1347       = Reader.ReadCXXCtorInitializers(F, Record, Idx);
1348 }
1349 
1350 void ASTDeclReader::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1351   VisitCXXMethodDecl(D);
1352 
1353   D->OperatorDelete = ReadDeclAs<FunctionDecl>(Record, Idx);
1354 }
1355 
1356 void ASTDeclReader::VisitCXXConversionDecl(CXXConversionDecl *D) {
1357   VisitCXXMethodDecl(D);
1358   D->IsExplicitSpecified = Record[Idx++];
1359 }
1360 
1361 void ASTDeclReader::VisitImportDecl(ImportDecl *D) {
1362   VisitDecl(D);
1363   D->ImportedAndComplete.setPointer(readModule(Record, Idx));
1364   D->ImportedAndComplete.setInt(Record[Idx++]);
1365   SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(D + 1);
1366   for (unsigned I = 0, N = Record.back(); I != N; ++I)
1367     StoredLocs[I] = ReadSourceLocation(Record, Idx);
1368   ++Idx; // The number of stored source locations.
1369 }
1370 
1371 void ASTDeclReader::VisitAccessSpecDecl(AccessSpecDecl *D) {
1372   VisitDecl(D);
1373   D->setColonLoc(ReadSourceLocation(Record, Idx));
1374 }
1375 
1376 void ASTDeclReader::VisitFriendDecl(FriendDecl *D) {
1377   VisitDecl(D);
1378   if (Record[Idx++]) // hasFriendDecl
1379     D->Friend = ReadDeclAs<NamedDecl>(Record, Idx);
1380   else
1381     D->Friend = GetTypeSourceInfo(Record, Idx);
1382   for (unsigned i = 0; i != D->NumTPLists; ++i)
1383     D->getTPLists()[i] = Reader.ReadTemplateParameterList(F, Record, Idx);
1384   D->NextFriend = ReadDeclID(Record, Idx);
1385   D->UnsupportedFriend = (Record[Idx++] != 0);
1386   D->FriendLoc = ReadSourceLocation(Record, Idx);
1387 }
1388 
1389 void ASTDeclReader::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
1390   VisitDecl(D);
1391   unsigned NumParams = Record[Idx++];
1392   D->NumParams = NumParams;
1393   D->Params = new TemplateParameterList*[NumParams];
1394   for (unsigned i = 0; i != NumParams; ++i)
1395     D->Params[i] = Reader.ReadTemplateParameterList(F, Record, Idx);
1396   if (Record[Idx++]) // HasFriendDecl
1397     D->Friend = ReadDeclAs<NamedDecl>(Record, Idx);
1398   else
1399     D->Friend = GetTypeSourceInfo(Record, Idx);
1400   D->FriendLoc = ReadSourceLocation(Record, Idx);
1401 }
1402 
1403 void ASTDeclReader::VisitTemplateDecl(TemplateDecl *D) {
1404   VisitNamedDecl(D);
1405 
1406   NamedDecl *TemplatedDecl = ReadDeclAs<NamedDecl>(Record, Idx);
1407   TemplateParameterList* TemplateParams
1408       = Reader.ReadTemplateParameterList(F, Record, Idx);
1409   D->init(TemplatedDecl, TemplateParams);
1410 
1411   // FIXME: If this is a redeclaration of a template from another module, handle
1412   // inheritance of default template arguments.
1413 }
1414 
1415 ASTDeclReader::RedeclarableResult
1416 ASTDeclReader::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
1417   RedeclarableResult Redecl = VisitRedeclarable(D);
1418 
1419   // Make sure we've allocated the Common pointer first. We do this before
1420   // VisitTemplateDecl so that getCommonPtr() can be used during initialization.
1421   RedeclarableTemplateDecl *CanonD = D->getCanonicalDecl();
1422   if (!CanonD->Common) {
1423     CanonD->Common = CanonD->newCommon(Reader.getContext());
1424     Reader.PendingDefinitions.insert(CanonD);
1425   }
1426   D->Common = CanonD->Common;
1427 
1428   // If this is the first declaration of the template, fill in the information
1429   // for the 'common' pointer.
1430   if (ThisDeclID == Redecl.getFirstID()) {
1431     if (RedeclarableTemplateDecl *RTD
1432           = ReadDeclAs<RedeclarableTemplateDecl>(Record, Idx)) {
1433       assert(RTD->getKind() == D->getKind() &&
1434              "InstantiatedFromMemberTemplate kind mismatch");
1435       D->setInstantiatedFromMemberTemplate(RTD);
1436       if (Record[Idx++])
1437         D->setMemberSpecialization();
1438     }
1439   }
1440 
1441   VisitTemplateDecl(D);
1442   D->IdentifierNamespace = Record[Idx++];
1443 
1444   mergeRedeclarable(D, Redecl);
1445 
1446   // If we merged the template with a prior declaration chain, merge the common
1447   // pointer.
1448   // FIXME: Actually merge here, don't just overwrite.
1449   D->Common = D->getCanonicalDecl()->Common;
1450 
1451   return Redecl;
1452 }
1453 
1454 void ASTDeclReader::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1455   RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
1456 
1457   if (ThisDeclID == Redecl.getFirstID()) {
1458     // This ClassTemplateDecl owns a CommonPtr; read it to keep track of all of
1459     // the specializations.
1460     SmallVector<serialization::DeclID, 2> SpecIDs;
1461     SpecIDs.push_back(0);
1462 
1463     // Specializations.
1464     unsigned Size = Record[Idx++];
1465     SpecIDs[0] += Size;
1466     for (unsigned I = 0; I != Size; ++I)
1467       SpecIDs.push_back(ReadDeclID(Record, Idx));
1468 
1469     // Partial specializations.
1470     Size = Record[Idx++];
1471     SpecIDs[0] += Size;
1472     for (unsigned I = 0; I != Size; ++I)
1473       SpecIDs.push_back(ReadDeclID(Record, Idx));
1474 
1475     ClassTemplateDecl::Common *CommonPtr = D->getCommonPtr();
1476     if (SpecIDs[0]) {
1477       typedef serialization::DeclID DeclID;
1478 
1479       // FIXME: Append specializations!
1480       CommonPtr->LazySpecializations
1481         = new (Reader.getContext()) DeclID [SpecIDs.size()];
1482       memcpy(CommonPtr->LazySpecializations, SpecIDs.data(),
1483              SpecIDs.size() * sizeof(DeclID));
1484     }
1485 
1486     CommonPtr->InjectedClassNameType = Reader.readType(F, Record, Idx);
1487   }
1488 }
1489 
1490 /// TODO: Unify with ClassTemplateDecl version?
1491 ///       May require unifying ClassTemplateDecl and
1492 ///        VarTemplateDecl beyond TemplateDecl...
1493 void ASTDeclReader::VisitVarTemplateDecl(VarTemplateDecl *D) {
1494   RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
1495 
1496   if (ThisDeclID == Redecl.getFirstID()) {
1497     // This VarTemplateDecl owns a CommonPtr; read it to keep track of all of
1498     // the specializations.
1499     SmallVector<serialization::DeclID, 2> SpecIDs;
1500     SpecIDs.push_back(0);
1501 
1502     // Specializations.
1503     unsigned Size = Record[Idx++];
1504     SpecIDs[0] += Size;
1505     for (unsigned I = 0; I != Size; ++I)
1506       SpecIDs.push_back(ReadDeclID(Record, Idx));
1507 
1508     // Partial specializations.
1509     Size = Record[Idx++];
1510     SpecIDs[0] += Size;
1511     for (unsigned I = 0; I != Size; ++I)
1512       SpecIDs.push_back(ReadDeclID(Record, Idx));
1513 
1514     VarTemplateDecl::Common *CommonPtr = D->getCommonPtr();
1515     if (SpecIDs[0]) {
1516       typedef serialization::DeclID DeclID;
1517 
1518       // FIXME: Append specializations!
1519       CommonPtr->LazySpecializations =
1520           new (Reader.getContext()) DeclID[SpecIDs.size()];
1521       memcpy(CommonPtr->LazySpecializations, SpecIDs.data(),
1522              SpecIDs.size() * sizeof(DeclID));
1523     }
1524   }
1525 }
1526 
1527 ASTDeclReader::RedeclarableResult
1528 ASTDeclReader::VisitClassTemplateSpecializationDeclImpl(
1529     ClassTemplateSpecializationDecl *D) {
1530   RedeclarableResult Redecl = VisitCXXRecordDeclImpl(D);
1531 
1532   ASTContext &C = Reader.getContext();
1533   if (Decl *InstD = ReadDecl(Record, Idx)) {
1534     if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(InstD)) {
1535       D->SpecializedTemplate = CTD;
1536     } else {
1537       SmallVector<TemplateArgument, 8> TemplArgs;
1538       Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1539       TemplateArgumentList *ArgList
1540         = TemplateArgumentList::CreateCopy(C, TemplArgs.data(),
1541                                            TemplArgs.size());
1542       ClassTemplateSpecializationDecl::SpecializedPartialSpecialization *PS
1543           = new (C) ClassTemplateSpecializationDecl::
1544                                              SpecializedPartialSpecialization();
1545       PS->PartialSpecialization
1546           = cast<ClassTemplatePartialSpecializationDecl>(InstD);
1547       PS->TemplateArgs = ArgList;
1548       D->SpecializedTemplate = PS;
1549     }
1550   }
1551 
1552   SmallVector<TemplateArgument, 8> TemplArgs;
1553   Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1554   D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs.data(),
1555                                                      TemplArgs.size());
1556   D->PointOfInstantiation = ReadSourceLocation(Record, Idx);
1557   D->SpecializationKind = (TemplateSpecializationKind)Record[Idx++];
1558 
1559   bool writtenAsCanonicalDecl = Record[Idx++];
1560   if (writtenAsCanonicalDecl) {
1561     ClassTemplateDecl *CanonPattern = ReadDeclAs<ClassTemplateDecl>(Record,Idx);
1562     if (D->isCanonicalDecl()) { // It's kept in the folding set.
1563       // Set this as, or find, the canonical declaration for this specialization
1564       ClassTemplateSpecializationDecl *CanonSpec;
1565       if (ClassTemplatePartialSpecializationDecl *Partial =
1566               dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) {
1567         CanonSpec = CanonPattern->getCommonPtr()->PartialSpecializations
1568             .GetOrInsertNode(Partial);
1569       } else {
1570         CanonSpec =
1571             CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
1572       }
1573       // If there was already a canonical specialization, merge into it.
1574       if (CanonSpec != D) {
1575         mergeRedeclarable<TagDecl>(D, CanonSpec, Redecl);
1576 
1577         // This declaration might be a definition. Merge with any existing
1578         // definition.
1579         if (D->DefinitionData) {
1580           if (!CanonSpec->DefinitionData) {
1581             CanonSpec->DefinitionData = D->DefinitionData;
1582           } else {
1583             // FIXME: Check DefinitionData for consistency with prior definition
1584             Reader.PendingDefinitions.erase(D);
1585             Reader.MergedDeclContexts.insert(
1586                 std::make_pair(D, CanonSpec->DefinitionData->Definition));
1587             D->IsCompleteDefinition = false;
1588             D->DefinitionData = CanonSpec->DefinitionData;
1589           }
1590         }
1591       }
1592     }
1593   }
1594 
1595   // Explicit info.
1596   if (TypeSourceInfo *TyInfo = GetTypeSourceInfo(Record, Idx)) {
1597     ClassTemplateSpecializationDecl::ExplicitSpecializationInfo *ExplicitInfo
1598         = new (C) ClassTemplateSpecializationDecl::ExplicitSpecializationInfo;
1599     ExplicitInfo->TypeAsWritten = TyInfo;
1600     ExplicitInfo->ExternLoc = ReadSourceLocation(Record, Idx);
1601     ExplicitInfo->TemplateKeywordLoc = ReadSourceLocation(Record, Idx);
1602     D->ExplicitInfo = ExplicitInfo;
1603   }
1604 
1605   return Redecl;
1606 }
1607 
1608 void ASTDeclReader::VisitClassTemplatePartialSpecializationDecl(
1609                                     ClassTemplatePartialSpecializationDecl *D) {
1610   RedeclarableResult Redecl = VisitClassTemplateSpecializationDeclImpl(D);
1611 
1612   D->TemplateParams = Reader.ReadTemplateParameterList(F, Record, Idx);
1613   D->ArgsAsWritten = Reader.ReadASTTemplateArgumentListInfo(F, Record, Idx);
1614 
1615   // These are read/set from/to the first declaration.
1616   if (ThisDeclID == Redecl.getFirstID()) {
1617     D->InstantiatedFromMember.setPointer(
1618       ReadDeclAs<ClassTemplatePartialSpecializationDecl>(Record, Idx));
1619     D->InstantiatedFromMember.setInt(Record[Idx++]);
1620   }
1621 }
1622 
1623 void ASTDeclReader::VisitClassScopeFunctionSpecializationDecl(
1624                                     ClassScopeFunctionSpecializationDecl *D) {
1625   VisitDecl(D);
1626   D->Specialization = ReadDeclAs<CXXMethodDecl>(Record, Idx);
1627 }
1628 
1629 void ASTDeclReader::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1630   RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
1631 
1632   if (ThisDeclID == Redecl.getFirstID()) {
1633     // This FunctionTemplateDecl owns a CommonPtr; read it.
1634 
1635     // Read the function specialization declaration IDs. The specializations
1636     // themselves will be loaded if they're needed.
1637     if (unsigned NumSpecs = Record[Idx++]) {
1638       // FIXME: Append specializations!
1639       FunctionTemplateDecl::Common *CommonPtr = D->getCommonPtr();
1640       CommonPtr->LazySpecializations = new (Reader.getContext())
1641           serialization::DeclID[NumSpecs + 1];
1642       CommonPtr->LazySpecializations[0] = NumSpecs;
1643       for (unsigned I = 0; I != NumSpecs; ++I)
1644         CommonPtr->LazySpecializations[I + 1] = ReadDeclID(Record, Idx);
1645     }
1646   }
1647 }
1648 
1649 /// TODO: Unify with ClassTemplateSpecializationDecl version?
1650 ///       May require unifying ClassTemplate(Partial)SpecializationDecl and
1651 ///        VarTemplate(Partial)SpecializationDecl with a new data
1652 ///        structure Template(Partial)SpecializationDecl, and
1653 ///        using Template(Partial)SpecializationDecl as input type.
1654 ASTDeclReader::RedeclarableResult
1655 ASTDeclReader::VisitVarTemplateSpecializationDeclImpl(
1656     VarTemplateSpecializationDecl *D) {
1657   RedeclarableResult Redecl = VisitVarDeclImpl(D);
1658 
1659   ASTContext &C = Reader.getContext();
1660   if (Decl *InstD = ReadDecl(Record, Idx)) {
1661     if (VarTemplateDecl *VTD = dyn_cast<VarTemplateDecl>(InstD)) {
1662       D->SpecializedTemplate = VTD;
1663     } else {
1664       SmallVector<TemplateArgument, 8> TemplArgs;
1665       Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1666       TemplateArgumentList *ArgList = TemplateArgumentList::CreateCopy(
1667           C, TemplArgs.data(), TemplArgs.size());
1668       VarTemplateSpecializationDecl::SpecializedPartialSpecialization *PS =
1669           new (C)
1670           VarTemplateSpecializationDecl::SpecializedPartialSpecialization();
1671       PS->PartialSpecialization =
1672           cast<VarTemplatePartialSpecializationDecl>(InstD);
1673       PS->TemplateArgs = ArgList;
1674       D->SpecializedTemplate = PS;
1675     }
1676   }
1677 
1678   // Explicit info.
1679   if (TypeSourceInfo *TyInfo = GetTypeSourceInfo(Record, Idx)) {
1680     VarTemplateSpecializationDecl::ExplicitSpecializationInfo *ExplicitInfo =
1681         new (C) VarTemplateSpecializationDecl::ExplicitSpecializationInfo;
1682     ExplicitInfo->TypeAsWritten = TyInfo;
1683     ExplicitInfo->ExternLoc = ReadSourceLocation(Record, Idx);
1684     ExplicitInfo->TemplateKeywordLoc = ReadSourceLocation(Record, Idx);
1685     D->ExplicitInfo = ExplicitInfo;
1686   }
1687 
1688   SmallVector<TemplateArgument, 8> TemplArgs;
1689   Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1690   D->TemplateArgs =
1691       TemplateArgumentList::CreateCopy(C, TemplArgs.data(), TemplArgs.size());
1692   D->PointOfInstantiation = ReadSourceLocation(Record, Idx);
1693   D->SpecializationKind = (TemplateSpecializationKind)Record[Idx++];
1694 
1695   bool writtenAsCanonicalDecl = Record[Idx++];
1696   if (writtenAsCanonicalDecl) {
1697     VarTemplateDecl *CanonPattern = ReadDeclAs<VarTemplateDecl>(Record, Idx);
1698     if (D->isCanonicalDecl()) { // It's kept in the folding set.
1699       if (VarTemplatePartialSpecializationDecl *Partial =
1700               dyn_cast<VarTemplatePartialSpecializationDecl>(D)) {
1701         CanonPattern->getCommonPtr()->PartialSpecializations
1702             .GetOrInsertNode(Partial);
1703       } else {
1704         CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
1705       }
1706     }
1707   }
1708 
1709   return Redecl;
1710 }
1711 
1712 /// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
1713 ///       May require unifying ClassTemplate(Partial)SpecializationDecl and
1714 ///        VarTemplate(Partial)SpecializationDecl with a new data
1715 ///        structure Template(Partial)SpecializationDecl, and
1716 ///        using Template(Partial)SpecializationDecl as input type.
1717 void ASTDeclReader::VisitVarTemplatePartialSpecializationDecl(
1718     VarTemplatePartialSpecializationDecl *D) {
1719   RedeclarableResult Redecl = VisitVarTemplateSpecializationDeclImpl(D);
1720 
1721   D->TemplateParams = Reader.ReadTemplateParameterList(F, Record, Idx);
1722   D->ArgsAsWritten = Reader.ReadASTTemplateArgumentListInfo(F, Record, Idx);
1723 
1724   // These are read/set from/to the first declaration.
1725   if (ThisDeclID == Redecl.getFirstID()) {
1726     D->InstantiatedFromMember.setPointer(
1727         ReadDeclAs<VarTemplatePartialSpecializationDecl>(Record, Idx));
1728     D->InstantiatedFromMember.setInt(Record[Idx++]);
1729   }
1730 }
1731 
1732 void ASTDeclReader::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
1733   VisitTypeDecl(D);
1734 
1735   D->setDeclaredWithTypename(Record[Idx++]);
1736 
1737   bool Inherited = Record[Idx++];
1738   TypeSourceInfo *DefArg = GetTypeSourceInfo(Record, Idx);
1739   D->setDefaultArgument(DefArg, Inherited);
1740 }
1741 
1742 void ASTDeclReader::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1743   VisitDeclaratorDecl(D);
1744   // TemplateParmPosition.
1745   D->setDepth(Record[Idx++]);
1746   D->setPosition(Record[Idx++]);
1747   if (D->isExpandedParameterPack()) {
1748     void **Data = reinterpret_cast<void **>(D + 1);
1749     for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1750       Data[2*I] = Reader.readType(F, Record, Idx).getAsOpaquePtr();
1751       Data[2*I + 1] = GetTypeSourceInfo(Record, Idx);
1752     }
1753   } else {
1754     // Rest of NonTypeTemplateParmDecl.
1755     D->ParameterPack = Record[Idx++];
1756     if (Record[Idx++]) {
1757       Expr *DefArg = Reader.ReadExpr(F);
1758       bool Inherited = Record[Idx++];
1759       D->setDefaultArgument(DefArg, Inherited);
1760    }
1761   }
1762 }
1763 
1764 void ASTDeclReader::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
1765   VisitTemplateDecl(D);
1766   // TemplateParmPosition.
1767   D->setDepth(Record[Idx++]);
1768   D->setPosition(Record[Idx++]);
1769   if (D->isExpandedParameterPack()) {
1770     void **Data = reinterpret_cast<void **>(D + 1);
1771     for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
1772          I != N; ++I)
1773       Data[I] = Reader.ReadTemplateParameterList(F, Record, Idx);
1774   } else {
1775     // Rest of TemplateTemplateParmDecl.
1776     TemplateArgumentLoc Arg = Reader.ReadTemplateArgumentLoc(F, Record, Idx);
1777     bool IsInherited = Record[Idx++];
1778     D->setDefaultArgument(Arg, IsInherited);
1779     D->ParameterPack = Record[Idx++];
1780   }
1781 }
1782 
1783 void ASTDeclReader::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
1784   VisitRedeclarableTemplateDecl(D);
1785 }
1786 
1787 void ASTDeclReader::VisitStaticAssertDecl(StaticAssertDecl *D) {
1788   VisitDecl(D);
1789   D->AssertExprAndFailed.setPointer(Reader.ReadExpr(F));
1790   D->AssertExprAndFailed.setInt(Record[Idx++]);
1791   D->Message = cast<StringLiteral>(Reader.ReadExpr(F));
1792   D->RParenLoc = ReadSourceLocation(Record, Idx);
1793 }
1794 
1795 void ASTDeclReader::VisitEmptyDecl(EmptyDecl *D) {
1796   VisitDecl(D);
1797 }
1798 
1799 std::pair<uint64_t, uint64_t>
1800 ASTDeclReader::VisitDeclContext(DeclContext *DC) {
1801   uint64_t LexicalOffset = Record[Idx++];
1802   uint64_t VisibleOffset = Record[Idx++];
1803   return std::make_pair(LexicalOffset, VisibleOffset);
1804 }
1805 
1806 template <typename T>
1807 ASTDeclReader::RedeclarableResult
1808 ASTDeclReader::VisitRedeclarable(Redeclarable<T> *D) {
1809   DeclID FirstDeclID = ReadDeclID(Record, Idx);
1810 
1811   // 0 indicates that this declaration was the only declaration of its entity,
1812   // and is used for space optimization.
1813   if (FirstDeclID == 0)
1814     FirstDeclID = ThisDeclID;
1815 
1816   T *FirstDecl = cast_or_null<T>(Reader.GetDecl(FirstDeclID));
1817   if (FirstDecl != D) {
1818     // We delay loading of the redeclaration chain to avoid deeply nested calls.
1819     // We temporarily set the first (canonical) declaration as the previous one
1820     // which is the one that matters and mark the real previous DeclID to be
1821     // loaded & attached later on.
1822     D->RedeclLink = Redeclarable<T>::PreviousDeclLink(FirstDecl);
1823   }
1824 
1825   // Note that this declaration has been deserialized.
1826   Reader.RedeclsDeserialized.insert(static_cast<T *>(D));
1827 
1828   // The result structure takes care to note that we need to load the
1829   // other declaration chains for this ID.
1830   return RedeclarableResult(Reader, FirstDeclID,
1831                             static_cast<T *>(D)->getKind());
1832 }
1833 
1834 /// \brief Attempts to merge the given declaration (D) with another declaration
1835 /// of the same entity.
1836 template<typename T>
1837 void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *D,
1838                                       RedeclarableResult &Redecl) {
1839   // If modules are not available, there is no reason to perform this merge.
1840   if (!Reader.getContext().getLangOpts().Modules)
1841     return;
1842 
1843   if (FindExistingResult ExistingRes = findExisting(static_cast<T*>(D)))
1844     if (T *Existing = ExistingRes)
1845       mergeRedeclarable(D, Existing, Redecl);
1846 }
1847 
1848 /// \brief Attempts to merge the given declaration (D) with another declaration
1849 /// of the same entity.
1850 template<typename T>
1851 void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *D, T *Existing,
1852                                       RedeclarableResult &Redecl) {
1853   T *ExistingCanon = Existing->getCanonicalDecl();
1854   T *DCanon = static_cast<T*>(D)->getCanonicalDecl();
1855   if (ExistingCanon != DCanon) {
1856     // Have our redeclaration link point back at the canonical declaration
1857     // of the existing declaration, so that this declaration has the
1858     // appropriate canonical declaration.
1859     D->RedeclLink = Redeclarable<T>::PreviousDeclLink(ExistingCanon);
1860 
1861     // When we merge a namespace, update its pointer to the first namespace.
1862     if (NamespaceDecl *Namespace
1863           = dyn_cast<NamespaceDecl>(static_cast<T*>(D))) {
1864       Namespace->AnonOrFirstNamespaceAndInline.setPointer(
1865         static_cast<NamespaceDecl *>(static_cast<void*>(ExistingCanon)));
1866     }
1867 
1868     // Don't introduce DCanon into the set of pending declaration chains.
1869     Redecl.suppress();
1870 
1871     // Introduce ExistingCanon into the set of pending declaration chains,
1872     // if in fact it came from a module file.
1873     if (ExistingCanon->isFromASTFile()) {
1874       GlobalDeclID ExistingCanonID = ExistingCanon->getGlobalID();
1875       assert(ExistingCanonID && "Unrecorded canonical declaration ID?");
1876       if (Reader.PendingDeclChainsKnown.insert(ExistingCanonID))
1877         Reader.PendingDeclChains.push_back(ExistingCanonID);
1878     }
1879 
1880     // If this declaration was the canonical declaration, make a note of
1881     // that. We accept the linear algorithm here because the number of
1882     // unique canonical declarations of an entity should always be tiny.
1883     if (DCanon == static_cast<T*>(D)) {
1884       SmallVectorImpl<DeclID> &Merged = Reader.MergedDecls[ExistingCanon];
1885       if (std::find(Merged.begin(), Merged.end(), Redecl.getFirstID())
1886             == Merged.end())
1887         Merged.push_back(Redecl.getFirstID());
1888 
1889       // If ExistingCanon did not come from a module file, introduce the
1890       // first declaration that *does* come from a module file to the
1891       // set of pending declaration chains, so that we merge this
1892       // declaration.
1893       if (!ExistingCanon->isFromASTFile() &&
1894           Reader.PendingDeclChainsKnown.insert(Redecl.getFirstID()))
1895         Reader.PendingDeclChains.push_back(Merged[0]);
1896     }
1897   }
1898 }
1899 
1900 /// \brief Attempts to merge the given declaration (D) with another declaration
1901 /// of the same entity, for the case where the entity is not actually
1902 /// redeclarable. This happens, for instance, when merging the fields of
1903 /// identical class definitions from two different modules.
1904 template<typename T>
1905 void ASTDeclReader::mergeMergeable(Mergeable<T> *D) {
1906   // If modules are not available, there is no reason to perform this merge.
1907   if (!Reader.getContext().getLangOpts().Modules)
1908     return;
1909 
1910   // ODR-based merging is only performed in C++. In C, identically-named things
1911   // in different translation units are not redeclarations (but may still have
1912   // compatible types).
1913   if (!Reader.getContext().getLangOpts().CPlusPlus)
1914     return;
1915 
1916   if (FindExistingResult ExistingRes = findExisting(static_cast<T*>(D)))
1917     if (T *Existing = ExistingRes)
1918       Reader.Context.setPrimaryMergedDecl(static_cast<T*>(D),
1919                                           Existing->getCanonicalDecl());
1920 }
1921 
1922 void ASTDeclReader::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {
1923   VisitDecl(D);
1924   unsigned NumVars = D->varlist_size();
1925   SmallVector<Expr *, 16> Vars;
1926   Vars.reserve(NumVars);
1927   for (unsigned i = 0; i != NumVars; ++i) {
1928     Vars.push_back(Reader.ReadExpr(F));
1929   }
1930   D->setVars(Vars);
1931 }
1932 
1933 //===----------------------------------------------------------------------===//
1934 // Attribute Reading
1935 //===----------------------------------------------------------------------===//
1936 
1937 /// \brief Reads attributes from the current stream position.
1938 void ASTReader::ReadAttributes(ModuleFile &F, AttrVec &Attrs,
1939                                const RecordData &Record, unsigned &Idx) {
1940   for (unsigned i = 0, e = Record[Idx++]; i != e; ++i) {
1941     Attr *New = 0;
1942     attr::Kind Kind = (attr::Kind)Record[Idx++];
1943     SourceRange Range = ReadSourceRange(F, Record, Idx);
1944 
1945 #include "clang/Serialization/AttrPCHRead.inc"
1946 
1947     assert(New && "Unable to decode attribute?");
1948     Attrs.push_back(New);
1949   }
1950 }
1951 
1952 //===----------------------------------------------------------------------===//
1953 // ASTReader Implementation
1954 //===----------------------------------------------------------------------===//
1955 
1956 /// \brief Note that we have loaded the declaration with the given
1957 /// Index.
1958 ///
1959 /// This routine notes that this declaration has already been loaded,
1960 /// so that future GetDecl calls will return this declaration rather
1961 /// than trying to load a new declaration.
1962 inline void ASTReader::LoadedDecl(unsigned Index, Decl *D) {
1963   assert(!DeclsLoaded[Index] && "Decl loaded twice?");
1964   DeclsLoaded[Index] = D;
1965 }
1966 
1967 
1968 /// \brief Determine whether the consumer will be interested in seeing
1969 /// this declaration (via HandleTopLevelDecl).
1970 ///
1971 /// This routine should return true for anything that might affect
1972 /// code generation, e.g., inline function definitions, Objective-C
1973 /// declarations with metadata, etc.
1974 static bool isConsumerInterestedIn(Decl *D, bool HasBody) {
1975   // An ObjCMethodDecl is never considered as "interesting" because its
1976   // implementation container always is.
1977 
1978   if (isa<FileScopeAsmDecl>(D) ||
1979       isa<ObjCProtocolDecl>(D) ||
1980       isa<ObjCImplDecl>(D))
1981     return true;
1982   if (VarDecl *Var = dyn_cast<VarDecl>(D))
1983     return Var->isFileVarDecl() &&
1984            Var->isThisDeclarationADefinition() == VarDecl::Definition;
1985   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D))
1986     return Func->doesThisDeclarationHaveABody() || HasBody;
1987 
1988   return false;
1989 }
1990 
1991 /// \brief Get the correct cursor and offset for loading a declaration.
1992 ASTReader::RecordLocation
1993 ASTReader::DeclCursorForID(DeclID ID, unsigned &RawLocation) {
1994   // See if there's an override.
1995   DeclReplacementMap::iterator It = ReplacedDecls.find(ID);
1996   if (It != ReplacedDecls.end()) {
1997     RawLocation = It->second.RawLoc;
1998     return RecordLocation(It->second.Mod, It->second.Offset);
1999   }
2000 
2001   GlobalDeclMapType::iterator I = GlobalDeclMap.find(ID);
2002   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
2003   ModuleFile *M = I->second;
2004   const DeclOffset &
2005     DOffs =  M->DeclOffsets[ID - M->BaseDeclID - NUM_PREDEF_DECL_IDS];
2006   RawLocation = DOffs.Loc;
2007   return RecordLocation(M, DOffs.BitOffset);
2008 }
2009 
2010 ASTReader::RecordLocation ASTReader::getLocalBitOffset(uint64_t GlobalOffset) {
2011   ContinuousRangeMap<uint64_t, ModuleFile*, 4>::iterator I
2012     = GlobalBitOffsetsMap.find(GlobalOffset);
2013 
2014   assert(I != GlobalBitOffsetsMap.end() && "Corrupted global bit offsets map");
2015   return RecordLocation(I->second, GlobalOffset - I->second->GlobalBitOffset);
2016 }
2017 
2018 uint64_t ASTReader::getGlobalBitOffset(ModuleFile &M, uint32_t LocalOffset) {
2019   return LocalOffset + M.GlobalBitOffset;
2020 }
2021 
2022 static bool isSameTemplateParameterList(const TemplateParameterList *X,
2023                                         const TemplateParameterList *Y);
2024 
2025 /// \brief Determine whether two template parameters are similar enough
2026 /// that they may be used in declarations of the same template.
2027 static bool isSameTemplateParameter(const NamedDecl *X,
2028                                     const NamedDecl *Y) {
2029   if (X->getKind() != Y->getKind())
2030     return false;
2031 
2032   if (const TemplateTypeParmDecl *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
2033     const TemplateTypeParmDecl *TY = cast<TemplateTypeParmDecl>(Y);
2034     return TX->isParameterPack() == TY->isParameterPack();
2035   }
2036 
2037   if (const NonTypeTemplateParmDecl *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
2038     const NonTypeTemplateParmDecl *TY = cast<NonTypeTemplateParmDecl>(Y);
2039     return TX->isParameterPack() == TY->isParameterPack() &&
2040            TX->getASTContext().hasSameType(TX->getType(), TY->getType());
2041   }
2042 
2043   const TemplateTemplateParmDecl *TX = cast<TemplateTemplateParmDecl>(X);
2044   const TemplateTemplateParmDecl *TY = cast<TemplateTemplateParmDecl>(Y);
2045   return TX->isParameterPack() == TY->isParameterPack() &&
2046          isSameTemplateParameterList(TX->getTemplateParameters(),
2047                                      TY->getTemplateParameters());
2048 }
2049 
2050 /// \brief Determine whether two template parameter lists are similar enough
2051 /// that they may be used in declarations of the same template.
2052 static bool isSameTemplateParameterList(const TemplateParameterList *X,
2053                                         const TemplateParameterList *Y) {
2054   if (X->size() != Y->size())
2055     return false;
2056 
2057   for (unsigned I = 0, N = X->size(); I != N; ++I)
2058     if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
2059       return false;
2060 
2061   return true;
2062 }
2063 
2064 /// \brief Determine whether the two declarations refer to the same entity.
2065 static bool isSameEntity(NamedDecl *X, NamedDecl *Y) {
2066   assert(X->getDeclName() == Y->getDeclName() && "Declaration name mismatch!");
2067 
2068   if (X == Y)
2069     return true;
2070 
2071   // Must be in the same context.
2072   if (!X->getDeclContext()->getRedeclContext()->Equals(
2073          Y->getDeclContext()->getRedeclContext()))
2074     return false;
2075 
2076   // Two typedefs refer to the same entity if they have the same underlying
2077   // type.
2078   if (TypedefNameDecl *TypedefX = dyn_cast<TypedefNameDecl>(X))
2079     if (TypedefNameDecl *TypedefY = dyn_cast<TypedefNameDecl>(Y))
2080       return X->getASTContext().hasSameType(TypedefX->getUnderlyingType(),
2081                                             TypedefY->getUnderlyingType());
2082 
2083   // Must have the same kind.
2084   if (X->getKind() != Y->getKind())
2085     return false;
2086 
2087   // Objective-C classes and protocols with the same name always match.
2088   if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
2089     return true;
2090 
2091   if (isa<ClassTemplateSpecializationDecl>(X)) {
2092     // No need to handle these here: we merge them when adding them to the
2093     // template.
2094     return false;
2095   }
2096 
2097   // Compatible tags match.
2098   if (TagDecl *TagX = dyn_cast<TagDecl>(X)) {
2099     TagDecl *TagY = cast<TagDecl>(Y);
2100     return (TagX->getTagKind() == TagY->getTagKind()) ||
2101       ((TagX->getTagKind() == TTK_Struct || TagX->getTagKind() == TTK_Class ||
2102         TagX->getTagKind() == TTK_Interface) &&
2103        (TagY->getTagKind() == TTK_Struct || TagY->getTagKind() == TTK_Class ||
2104         TagY->getTagKind() == TTK_Interface));
2105   }
2106 
2107   // Functions with the same type and linkage match.
2108   // FIXME: This needs to cope with function template specializations,
2109   // merging of prototyped/non-prototyped functions, etc.
2110   if (FunctionDecl *FuncX = dyn_cast<FunctionDecl>(X)) {
2111     FunctionDecl *FuncY = cast<FunctionDecl>(Y);
2112     return (FuncX->getLinkageInternal() == FuncY->getLinkageInternal()) &&
2113       FuncX->getASTContext().hasSameType(FuncX->getType(), FuncY->getType());
2114   }
2115 
2116   // Variables with the same type and linkage match.
2117   if (VarDecl *VarX = dyn_cast<VarDecl>(X)) {
2118     VarDecl *VarY = cast<VarDecl>(Y);
2119     return (VarX->getLinkageInternal() == VarY->getLinkageInternal()) &&
2120       VarX->getASTContext().hasSameType(VarX->getType(), VarY->getType());
2121   }
2122 
2123   // Namespaces with the same name and inlinedness match.
2124   if (NamespaceDecl *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
2125     NamespaceDecl *NamespaceY = cast<NamespaceDecl>(Y);
2126     return NamespaceX->isInline() == NamespaceY->isInline();
2127   }
2128 
2129   // Identical template names and kinds match if their template parameter lists
2130   // and patterns match.
2131   if (TemplateDecl *TemplateX = dyn_cast<TemplateDecl>(X)) {
2132     TemplateDecl *TemplateY = cast<TemplateDecl>(Y);
2133     return isSameEntity(TemplateX->getTemplatedDecl(),
2134                         TemplateY->getTemplatedDecl()) &&
2135            isSameTemplateParameterList(TemplateX->getTemplateParameters(),
2136                                        TemplateY->getTemplateParameters());
2137   }
2138 
2139   // Fields with the same name and the same type match.
2140   if (FieldDecl *FDX = dyn_cast<FieldDecl>(X)) {
2141     FieldDecl *FDY = cast<FieldDecl>(Y);
2142     // FIXME: Diagnose if the types don't match. More generally, diagnose if we
2143     // get a declaration in a class definition that isn't in the canonical class
2144     // definition.
2145     // FIXME: Also check the bitwidth is odr-equivalent, if any.
2146     return X->getASTContext().hasSameType(FDX->getType(), FDY->getType());
2147   }
2148 
2149   // Enumerators with the same name match.
2150   if (isa<EnumConstantDecl>(X))
2151     // FIXME: Also check the value is odr-equivalent.
2152     return true;
2153 
2154   // FIXME: Many other cases to implement.
2155   return false;
2156 }
2157 
2158 /// Find the context in which we should search for previous declarations when
2159 /// looking for declarations to merge.
2160 static DeclContext *getPrimaryContextForMerging(DeclContext *DC) {
2161   if (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
2162     return ND->getOriginalNamespace();
2163 
2164   if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
2165     return RD->getDefinition();
2166 
2167   if (EnumDecl *ED = dyn_cast<EnumDecl>(DC))
2168     return ED->getASTContext().getLangOpts().CPlusPlus? ED->getDefinition() : 0;
2169 
2170   return 0;
2171 }
2172 
2173 ASTDeclReader::FindExistingResult::~FindExistingResult() {
2174   if (!AddResult || Existing)
2175     return;
2176 
2177   DeclContext *DC = New->getDeclContext()->getRedeclContext();
2178   if (DC->isTranslationUnit() && Reader.SemaObj) {
2179     Reader.SemaObj->IdResolver.tryAddTopLevelDecl(New, New->getDeclName());
2180   } else if (DeclContext *MergeDC = getPrimaryContextForMerging(DC)) {
2181     // Add the declaration to its redeclaration context so later merging
2182     // lookups will find it.
2183     MergeDC->makeDeclVisibleInContextImpl(New, /*Internal*/true);
2184   }
2185 }
2186 
2187 ASTDeclReader::FindExistingResult ASTDeclReader::findExisting(NamedDecl *D) {
2188   DeclarationName Name = D->getDeclName();
2189   if (!Name) {
2190     // Don't bother trying to find unnamed declarations.
2191     FindExistingResult Result(Reader, D, /*Existing=*/0);
2192     Result.suppress();
2193     return Result;
2194   }
2195 
2196   // FIXME: Bail out for non-canonical declarations. We will have performed any
2197   // necessary merging already.
2198 
2199   DeclContext *DC = D->getDeclContext()->getRedeclContext();
2200   if (DC->isTranslationUnit() && Reader.SemaObj) {
2201     IdentifierResolver &IdResolver = Reader.SemaObj->IdResolver;
2202 
2203     // Temporarily consider the identifier to be up-to-date. We don't want to
2204     // cause additional lookups here.
2205     class UpToDateIdentifierRAII {
2206       IdentifierInfo *II;
2207       bool WasOutToDate;
2208 
2209     public:
2210       explicit UpToDateIdentifierRAII(IdentifierInfo *II)
2211         : II(II), WasOutToDate(false)
2212       {
2213         if (II) {
2214           WasOutToDate = II->isOutOfDate();
2215           if (WasOutToDate)
2216             II->setOutOfDate(false);
2217         }
2218       }
2219 
2220       ~UpToDateIdentifierRAII() {
2221         if (WasOutToDate)
2222           II->setOutOfDate(true);
2223       }
2224     } UpToDate(Name.getAsIdentifierInfo());
2225 
2226     for (IdentifierResolver::iterator I = IdResolver.begin(Name),
2227                                    IEnd = IdResolver.end();
2228          I != IEnd; ++I) {
2229       if (isSameEntity(*I, D))
2230         return FindExistingResult(Reader, D, *I);
2231     }
2232   } else if (DeclContext *MergeDC = getPrimaryContextForMerging(DC)) {
2233     DeclContext::lookup_result R = MergeDC->noload_lookup(Name);
2234     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
2235       if (isSameEntity(*I, D))
2236         return FindExistingResult(Reader, D, *I);
2237     }
2238   } else {
2239     // Not in a mergeable context.
2240     return FindExistingResult(Reader);
2241   }
2242 
2243   // If this declaration is from a merged context, make a note that we need to
2244   // check that the canonical definition of that context contains the decl.
2245   if (Reader.MergedDeclContexts.count(D->getLexicalDeclContext()))
2246     Reader.PendingOdrMergeChecks.push_back(D);
2247 
2248   return FindExistingResult(Reader, D, /*Existing=*/0);
2249 }
2250 
2251 void ASTDeclReader::attachPreviousDecl(Decl *D, Decl *previous) {
2252   assert(D && previous);
2253   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2254     TD->RedeclLink.setNext(cast<TagDecl>(previous));
2255   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2256     FD->RedeclLink.setNext(cast<FunctionDecl>(previous));
2257   } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2258     VD->RedeclLink.setNext(cast<VarDecl>(previous));
2259   } else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2260     TD->RedeclLink.setNext(cast<TypedefNameDecl>(previous));
2261   } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
2262     ID->RedeclLink.setNext(cast<ObjCInterfaceDecl>(previous));
2263   } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
2264     PD->RedeclLink.setNext(cast<ObjCProtocolDecl>(previous));
2265   } else if (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(D)) {
2266     ND->RedeclLink.setNext(cast<NamespaceDecl>(previous));
2267   } else {
2268     RedeclarableTemplateDecl *TD = cast<RedeclarableTemplateDecl>(D);
2269     TD->RedeclLink.setNext(cast<RedeclarableTemplateDecl>(previous));
2270   }
2271 
2272   // If the declaration was visible in one module, a redeclaration of it in
2273   // another module remains visible even if it wouldn't be visible by itself.
2274   //
2275   // FIXME: In this case, the declaration should only be visible if a module
2276   //        that makes it visible has been imported.
2277   D->IdentifierNamespace |=
2278       previous->IdentifierNamespace &
2279       (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
2280 }
2281 
2282 void ASTDeclReader::attachLatestDecl(Decl *D, Decl *Latest) {
2283   assert(D && Latest);
2284   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2285     TD->RedeclLink
2286       = Redeclarable<TagDecl>::LatestDeclLink(cast<TagDecl>(Latest));
2287   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2288     FD->RedeclLink
2289       = Redeclarable<FunctionDecl>::LatestDeclLink(cast<FunctionDecl>(Latest));
2290   } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2291     VD->RedeclLink
2292       = Redeclarable<VarDecl>::LatestDeclLink(cast<VarDecl>(Latest));
2293   } else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2294     TD->RedeclLink
2295       = Redeclarable<TypedefNameDecl>::LatestDeclLink(
2296                                                 cast<TypedefNameDecl>(Latest));
2297   } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
2298     ID->RedeclLink
2299       = Redeclarable<ObjCInterfaceDecl>::LatestDeclLink(
2300                                               cast<ObjCInterfaceDecl>(Latest));
2301   } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
2302     PD->RedeclLink
2303       = Redeclarable<ObjCProtocolDecl>::LatestDeclLink(
2304                                                 cast<ObjCProtocolDecl>(Latest));
2305   } else if (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(D)) {
2306     ND->RedeclLink
2307       = Redeclarable<NamespaceDecl>::LatestDeclLink(
2308                                                    cast<NamespaceDecl>(Latest));
2309   } else {
2310     RedeclarableTemplateDecl *TD = cast<RedeclarableTemplateDecl>(D);
2311     TD->RedeclLink
2312       = Redeclarable<RedeclarableTemplateDecl>::LatestDeclLink(
2313                                         cast<RedeclarableTemplateDecl>(Latest));
2314   }
2315 }
2316 
2317 ASTReader::MergedDeclsMap::iterator
2318 ASTReader::combineStoredMergedDecls(Decl *Canon, GlobalDeclID CanonID) {
2319   // If we don't have any stored merged declarations, just look in the
2320   // merged declarations set.
2321   StoredMergedDeclsMap::iterator StoredPos = StoredMergedDecls.find(CanonID);
2322   if (StoredPos == StoredMergedDecls.end())
2323     return MergedDecls.find(Canon);
2324 
2325   // Append the stored merged declarations to the merged declarations set.
2326   MergedDeclsMap::iterator Pos = MergedDecls.find(Canon);
2327   if (Pos == MergedDecls.end())
2328     Pos = MergedDecls.insert(std::make_pair(Canon,
2329                                             SmallVector<DeclID, 2>())).first;
2330   Pos->second.append(StoredPos->second.begin(), StoredPos->second.end());
2331   StoredMergedDecls.erase(StoredPos);
2332 
2333   // Sort and uniquify the set of merged declarations.
2334   llvm::array_pod_sort(Pos->second.begin(), Pos->second.end());
2335   Pos->second.erase(std::unique(Pos->second.begin(), Pos->second.end()),
2336                     Pos->second.end());
2337   return Pos;
2338 }
2339 
2340 /// \brief Read the declaration at the given offset from the AST file.
2341 Decl *ASTReader::ReadDeclRecord(DeclID ID) {
2342   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
2343   unsigned RawLocation = 0;
2344   RecordLocation Loc = DeclCursorForID(ID, RawLocation);
2345   llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
2346   // Keep track of where we are in the stream, then jump back there
2347   // after reading this declaration.
2348   SavedStreamPosition SavedPosition(DeclsCursor);
2349 
2350   ReadingKindTracker ReadingKind(Read_Decl, *this);
2351 
2352   // Note that we are loading a declaration record.
2353   Deserializing ADecl(this);
2354 
2355   DeclsCursor.JumpToBit(Loc.Offset);
2356   RecordData Record;
2357   unsigned Code = DeclsCursor.ReadCode();
2358   unsigned Idx = 0;
2359   ASTDeclReader Reader(*this, *Loc.F, ID, RawLocation, Record,Idx);
2360 
2361   Decl *D = 0;
2362   switch ((DeclCode)DeclsCursor.readRecord(Code, Record)) {
2363   case DECL_CONTEXT_LEXICAL:
2364   case DECL_CONTEXT_VISIBLE:
2365     llvm_unreachable("Record cannot be de-serialized with ReadDeclRecord");
2366   case DECL_TYPEDEF:
2367     D = TypedefDecl::CreateDeserialized(Context, ID);
2368     break;
2369   case DECL_TYPEALIAS:
2370     D = TypeAliasDecl::CreateDeserialized(Context, ID);
2371     break;
2372   case DECL_ENUM:
2373     D = EnumDecl::CreateDeserialized(Context, ID);
2374     break;
2375   case DECL_RECORD:
2376     D = RecordDecl::CreateDeserialized(Context, ID);
2377     break;
2378   case DECL_ENUM_CONSTANT:
2379     D = EnumConstantDecl::CreateDeserialized(Context, ID);
2380     break;
2381   case DECL_FUNCTION:
2382     D = FunctionDecl::CreateDeserialized(Context, ID);
2383     break;
2384   case DECL_LINKAGE_SPEC:
2385     D = LinkageSpecDecl::CreateDeserialized(Context, ID);
2386     break;
2387   case DECL_LABEL:
2388     D = LabelDecl::CreateDeserialized(Context, ID);
2389     break;
2390   case DECL_NAMESPACE:
2391     D = NamespaceDecl::CreateDeserialized(Context, ID);
2392     break;
2393   case DECL_NAMESPACE_ALIAS:
2394     D = NamespaceAliasDecl::CreateDeserialized(Context, ID);
2395     break;
2396   case DECL_USING:
2397     D = UsingDecl::CreateDeserialized(Context, ID);
2398     break;
2399   case DECL_USING_SHADOW:
2400     D = UsingShadowDecl::CreateDeserialized(Context, ID);
2401     break;
2402   case DECL_USING_DIRECTIVE:
2403     D = UsingDirectiveDecl::CreateDeserialized(Context, ID);
2404     break;
2405   case DECL_UNRESOLVED_USING_VALUE:
2406     D = UnresolvedUsingValueDecl::CreateDeserialized(Context, ID);
2407     break;
2408   case DECL_UNRESOLVED_USING_TYPENAME:
2409     D = UnresolvedUsingTypenameDecl::CreateDeserialized(Context, ID);
2410     break;
2411   case DECL_CXX_RECORD:
2412     D = CXXRecordDecl::CreateDeserialized(Context, ID);
2413     break;
2414   case DECL_CXX_METHOD:
2415     D = CXXMethodDecl::CreateDeserialized(Context, ID);
2416     break;
2417   case DECL_CXX_CONSTRUCTOR:
2418     D = CXXConstructorDecl::CreateDeserialized(Context, ID);
2419     break;
2420   case DECL_CXX_DESTRUCTOR:
2421     D = CXXDestructorDecl::CreateDeserialized(Context, ID);
2422     break;
2423   case DECL_CXX_CONVERSION:
2424     D = CXXConversionDecl::CreateDeserialized(Context, ID);
2425     break;
2426   case DECL_ACCESS_SPEC:
2427     D = AccessSpecDecl::CreateDeserialized(Context, ID);
2428     break;
2429   case DECL_FRIEND:
2430     D = FriendDecl::CreateDeserialized(Context, ID, Record[Idx++]);
2431     break;
2432   case DECL_FRIEND_TEMPLATE:
2433     D = FriendTemplateDecl::CreateDeserialized(Context, ID);
2434     break;
2435   case DECL_CLASS_TEMPLATE:
2436     D = ClassTemplateDecl::CreateDeserialized(Context, ID);
2437     break;
2438   case DECL_CLASS_TEMPLATE_SPECIALIZATION:
2439     D = ClassTemplateSpecializationDecl::CreateDeserialized(Context, ID);
2440     break;
2441   case DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION:
2442     D = ClassTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
2443     break;
2444   case DECL_VAR_TEMPLATE:
2445     D = VarTemplateDecl::CreateDeserialized(Context, ID);
2446     break;
2447   case DECL_VAR_TEMPLATE_SPECIALIZATION:
2448     D = VarTemplateSpecializationDecl::CreateDeserialized(Context, ID);
2449     break;
2450   case DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION:
2451     D = VarTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
2452     break;
2453   case DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION:
2454     D = ClassScopeFunctionSpecializationDecl::CreateDeserialized(Context, ID);
2455     break;
2456   case DECL_FUNCTION_TEMPLATE:
2457     D = FunctionTemplateDecl::CreateDeserialized(Context, ID);
2458     break;
2459   case DECL_TEMPLATE_TYPE_PARM:
2460     D = TemplateTypeParmDecl::CreateDeserialized(Context, ID);
2461     break;
2462   case DECL_NON_TYPE_TEMPLATE_PARM:
2463     D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID);
2464     break;
2465   case DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK:
2466     D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID, Record[Idx++]);
2467     break;
2468   case DECL_TEMPLATE_TEMPLATE_PARM:
2469     D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID);
2470     break;
2471   case DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK:
2472     D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID,
2473                                                      Record[Idx++]);
2474     break;
2475   case DECL_TYPE_ALIAS_TEMPLATE:
2476     D = TypeAliasTemplateDecl::CreateDeserialized(Context, ID);
2477     break;
2478   case DECL_STATIC_ASSERT:
2479     D = StaticAssertDecl::CreateDeserialized(Context, ID);
2480     break;
2481   case DECL_OBJC_METHOD:
2482     D = ObjCMethodDecl::CreateDeserialized(Context, ID);
2483     break;
2484   case DECL_OBJC_INTERFACE:
2485     D = ObjCInterfaceDecl::CreateDeserialized(Context, ID);
2486     break;
2487   case DECL_OBJC_IVAR:
2488     D = ObjCIvarDecl::CreateDeserialized(Context, ID);
2489     break;
2490   case DECL_OBJC_PROTOCOL:
2491     D = ObjCProtocolDecl::CreateDeserialized(Context, ID);
2492     break;
2493   case DECL_OBJC_AT_DEFS_FIELD:
2494     D = ObjCAtDefsFieldDecl::CreateDeserialized(Context, ID);
2495     break;
2496   case DECL_OBJC_CATEGORY:
2497     D = ObjCCategoryDecl::CreateDeserialized(Context, ID);
2498     break;
2499   case DECL_OBJC_CATEGORY_IMPL:
2500     D = ObjCCategoryImplDecl::CreateDeserialized(Context, ID);
2501     break;
2502   case DECL_OBJC_IMPLEMENTATION:
2503     D = ObjCImplementationDecl::CreateDeserialized(Context, ID);
2504     break;
2505   case DECL_OBJC_COMPATIBLE_ALIAS:
2506     D = ObjCCompatibleAliasDecl::CreateDeserialized(Context, ID);
2507     break;
2508   case DECL_OBJC_PROPERTY:
2509     D = ObjCPropertyDecl::CreateDeserialized(Context, ID);
2510     break;
2511   case DECL_OBJC_PROPERTY_IMPL:
2512     D = ObjCPropertyImplDecl::CreateDeserialized(Context, ID);
2513     break;
2514   case DECL_FIELD:
2515     D = FieldDecl::CreateDeserialized(Context, ID);
2516     break;
2517   case DECL_INDIRECTFIELD:
2518     D = IndirectFieldDecl::CreateDeserialized(Context, ID);
2519     break;
2520   case DECL_VAR:
2521     D = VarDecl::CreateDeserialized(Context, ID);
2522     break;
2523   case DECL_IMPLICIT_PARAM:
2524     D = ImplicitParamDecl::CreateDeserialized(Context, ID);
2525     break;
2526   case DECL_PARM_VAR:
2527     D = ParmVarDecl::CreateDeserialized(Context, ID);
2528     break;
2529   case DECL_FILE_SCOPE_ASM:
2530     D = FileScopeAsmDecl::CreateDeserialized(Context, ID);
2531     break;
2532   case DECL_BLOCK:
2533     D = BlockDecl::CreateDeserialized(Context, ID);
2534     break;
2535   case DECL_MS_PROPERTY:
2536     D = MSPropertyDecl::CreateDeserialized(Context, ID);
2537     break;
2538   case DECL_CAPTURED:
2539     D = CapturedDecl::CreateDeserialized(Context, ID, Record[Idx++]);
2540     break;
2541   case DECL_CXX_BASE_SPECIFIERS:
2542     Error("attempt to read a C++ base-specifier record as a declaration");
2543     return 0;
2544   case DECL_IMPORT:
2545     // Note: last entry of the ImportDecl record is the number of stored source
2546     // locations.
2547     D = ImportDecl::CreateDeserialized(Context, ID, Record.back());
2548     break;
2549   case DECL_OMP_THREADPRIVATE:
2550     D = OMPThreadPrivateDecl::CreateDeserialized(Context, ID, Record[Idx++]);
2551     break;
2552   case DECL_EMPTY:
2553     D = EmptyDecl::CreateDeserialized(Context, ID);
2554     break;
2555   }
2556 
2557   assert(D && "Unknown declaration reading AST file");
2558   LoadedDecl(Index, D);
2559   // Set the DeclContext before doing any deserialization, to make sure internal
2560   // calls to Decl::getASTContext() by Decl's methods will find the
2561   // TranslationUnitDecl without crashing.
2562   D->setDeclContext(Context.getTranslationUnitDecl());
2563   Reader.Visit(D);
2564 
2565   // If this declaration is also a declaration context, get the
2566   // offsets for its tables of lexical and visible declarations.
2567   if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
2568     // FIXME: This should really be
2569     //     DeclContext *LookupDC = DC->getPrimaryContext();
2570     // but that can walk the redeclaration chain, which might not work yet.
2571     DeclContext *LookupDC = DC;
2572     if (isa<NamespaceDecl>(DC))
2573       LookupDC = DC->getPrimaryContext();
2574     std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
2575     if (Offsets.first || Offsets.second) {
2576       if (Offsets.first != 0)
2577         DC->setHasExternalLexicalStorage(true);
2578       if (Offsets.second != 0)
2579         LookupDC->setHasExternalVisibleStorage(true);
2580       if (ReadDeclContextStorage(*Loc.F, DeclsCursor, Offsets,
2581                                  Loc.F->DeclContextInfos[DC]))
2582         return 0;
2583     }
2584 
2585     // Now add the pending visible updates for this decl context, if it has any.
2586     DeclContextVisibleUpdatesPending::iterator I =
2587         PendingVisibleUpdates.find(ID);
2588     if (I != PendingVisibleUpdates.end()) {
2589       // There are updates. This means the context has external visible
2590       // storage, even if the original stored version didn't.
2591       LookupDC->setHasExternalVisibleStorage(true);
2592       DeclContextVisibleUpdates &U = I->second;
2593       for (DeclContextVisibleUpdates::iterator UI = U.begin(), UE = U.end();
2594            UI != UE; ++UI) {
2595         DeclContextInfo &Info = UI->second->DeclContextInfos[DC];
2596         delete Info.NameLookupTableData;
2597         Info.NameLookupTableData = UI->first;
2598       }
2599       PendingVisibleUpdates.erase(I);
2600     }
2601   }
2602   assert(Idx == Record.size());
2603 
2604   // Load any relevant update records.
2605   loadDeclUpdateRecords(ID, D);
2606 
2607   // Load the categories after recursive loading is finished.
2608   if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
2609     if (Class->isThisDeclarationADefinition())
2610       loadObjCCategories(ID, Class);
2611 
2612   // If we have deserialized a declaration that has a definition the
2613   // AST consumer might need to know about, queue it.
2614   // We don't pass it to the consumer immediately because we may be in recursive
2615   // loading, and some declarations may still be initializing.
2616   if (isConsumerInterestedIn(D, Reader.hasPendingBody()))
2617     InterestingDecls.push_back(D);
2618 
2619   return D;
2620 }
2621 
2622 void ASTReader::loadDeclUpdateRecords(serialization::DeclID ID, Decl *D) {
2623   // The declaration may have been modified by files later in the chain.
2624   // If this is the case, read the record containing the updates from each file
2625   // and pass it to ASTDeclReader to make the modifications.
2626   DeclUpdateOffsetsMap::iterator UpdI = DeclUpdateOffsets.find(ID);
2627   if (UpdI != DeclUpdateOffsets.end()) {
2628     FileOffsetsTy &UpdateOffsets = UpdI->second;
2629     for (FileOffsetsTy::iterator
2630          I = UpdateOffsets.begin(), E = UpdateOffsets.end(); I != E; ++I) {
2631       ModuleFile *F = I->first;
2632       uint64_t Offset = I->second;
2633       llvm::BitstreamCursor &Cursor = F->DeclsCursor;
2634       SavedStreamPosition SavedPosition(Cursor);
2635       Cursor.JumpToBit(Offset);
2636       RecordData Record;
2637       unsigned Code = Cursor.ReadCode();
2638       unsigned RecCode = Cursor.readRecord(Code, Record);
2639       (void)RecCode;
2640       assert(RecCode == DECL_UPDATES && "Expected DECL_UPDATES record!");
2641 
2642       unsigned Idx = 0;
2643       ASTDeclReader Reader(*this, *F, ID, 0, Record, Idx);
2644       Reader.UpdateDecl(D, *F, Record);
2645     }
2646   }
2647 }
2648 
2649 namespace {
2650   struct CompareLocalRedeclarationsInfoToID {
2651     bool operator()(const LocalRedeclarationsInfo &X, DeclID Y) {
2652       return X.FirstID < Y;
2653     }
2654 
2655     bool operator()(DeclID X, const LocalRedeclarationsInfo &Y) {
2656       return X < Y.FirstID;
2657     }
2658 
2659     bool operator()(const LocalRedeclarationsInfo &X,
2660                     const LocalRedeclarationsInfo &Y) {
2661       return X.FirstID < Y.FirstID;
2662     }
2663     bool operator()(DeclID X, DeclID Y) {
2664       return X < Y;
2665     }
2666   };
2667 
2668   /// \brief Module visitor class that finds all of the redeclarations of a
2669   ///
2670   class RedeclChainVisitor {
2671     ASTReader &Reader;
2672     SmallVectorImpl<DeclID> &SearchDecls;
2673     llvm::SmallPtrSet<Decl *, 16> &Deserialized;
2674     GlobalDeclID CanonID;
2675     SmallVector<Decl *, 4> Chain;
2676 
2677   public:
2678     RedeclChainVisitor(ASTReader &Reader, SmallVectorImpl<DeclID> &SearchDecls,
2679                        llvm::SmallPtrSet<Decl *, 16> &Deserialized,
2680                        GlobalDeclID CanonID)
2681       : Reader(Reader), SearchDecls(SearchDecls), Deserialized(Deserialized),
2682         CanonID(CanonID) {
2683       for (unsigned I = 0, N = SearchDecls.size(); I != N; ++I)
2684         addToChain(Reader.GetDecl(SearchDecls[I]));
2685     }
2686 
2687     static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
2688       if (Preorder)
2689         return false;
2690 
2691       return static_cast<RedeclChainVisitor *>(UserData)->visit(M);
2692     }
2693 
2694     void addToChain(Decl *D) {
2695       if (!D)
2696         return;
2697 
2698       if (Deserialized.erase(D))
2699         Chain.push_back(D);
2700     }
2701 
2702     void searchForID(ModuleFile &M, GlobalDeclID GlobalID) {
2703       // Map global ID of the first declaration down to the local ID
2704       // used in this module file.
2705       DeclID ID = Reader.mapGlobalIDToModuleFileGlobalID(M, GlobalID);
2706       if (!ID)
2707         return;
2708 
2709       // Perform a binary search to find the local redeclarations for this
2710       // declaration (if any).
2711       const LocalRedeclarationsInfo *Result
2712         = std::lower_bound(M.RedeclarationsMap,
2713                            M.RedeclarationsMap + M.LocalNumRedeclarationsInMap,
2714                            ID, CompareLocalRedeclarationsInfoToID());
2715       if (Result == M.RedeclarationsMap + M.LocalNumRedeclarationsInMap ||
2716           Result->FirstID != ID) {
2717         // If we have a previously-canonical singleton declaration that was
2718         // merged into another redeclaration chain, create a trivial chain
2719         // for this single declaration so that it will get wired into the
2720         // complete redeclaration chain.
2721         if (GlobalID != CanonID &&
2722             GlobalID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
2723             GlobalID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls) {
2724           addToChain(Reader.GetDecl(GlobalID));
2725         }
2726 
2727         return;
2728       }
2729 
2730       // Dig out all of the redeclarations.
2731       unsigned Offset = Result->Offset;
2732       unsigned N = M.RedeclarationChains[Offset];
2733       M.RedeclarationChains[Offset++] = 0; // Don't try to deserialize again
2734       for (unsigned I = 0; I != N; ++I)
2735         addToChain(Reader.GetLocalDecl(M, M.RedeclarationChains[Offset++]));
2736     }
2737 
2738     bool visit(ModuleFile &M) {
2739       // Visit each of the declarations.
2740       for (unsigned I = 0, N = SearchDecls.size(); I != N; ++I)
2741         searchForID(M, SearchDecls[I]);
2742       return false;
2743     }
2744 
2745     ArrayRef<Decl *> getChain() const {
2746       return Chain;
2747     }
2748   };
2749 }
2750 
2751 void ASTReader::loadPendingDeclChain(serialization::GlobalDeclID ID) {
2752   Decl *D = GetDecl(ID);
2753   Decl *CanonDecl = D->getCanonicalDecl();
2754 
2755   // Determine the set of declaration IDs we'll be searching for.
2756   SmallVector<DeclID, 1> SearchDecls;
2757   GlobalDeclID CanonID = 0;
2758   if (D == CanonDecl) {
2759     SearchDecls.push_back(ID); // Always first.
2760     CanonID = ID;
2761   }
2762   MergedDeclsMap::iterator MergedPos = combineStoredMergedDecls(CanonDecl, ID);
2763   if (MergedPos != MergedDecls.end())
2764     SearchDecls.append(MergedPos->second.begin(), MergedPos->second.end());
2765 
2766   // Build up the list of redeclarations.
2767   RedeclChainVisitor Visitor(*this, SearchDecls, RedeclsDeserialized, CanonID);
2768   ModuleMgr.visitDepthFirst(&RedeclChainVisitor::visit, &Visitor);
2769 
2770   // Retrieve the chains.
2771   ArrayRef<Decl *> Chain = Visitor.getChain();
2772   if (Chain.empty())
2773     return;
2774 
2775   // Hook up the chains.
2776   Decl *MostRecent = CanonDecl->getMostRecentDecl();
2777   for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2778     if (Chain[I] == CanonDecl)
2779       continue;
2780 
2781     ASTDeclReader::attachPreviousDecl(Chain[I], MostRecent);
2782     MostRecent = Chain[I];
2783   }
2784 
2785   ASTDeclReader::attachLatestDecl(CanonDecl, MostRecent);
2786 }
2787 
2788 namespace {
2789   struct CompareObjCCategoriesInfo {
2790     bool operator()(const ObjCCategoriesInfo &X, DeclID Y) {
2791       return X.DefinitionID < Y;
2792     }
2793 
2794     bool operator()(DeclID X, const ObjCCategoriesInfo &Y) {
2795       return X < Y.DefinitionID;
2796     }
2797 
2798     bool operator()(const ObjCCategoriesInfo &X,
2799                     const ObjCCategoriesInfo &Y) {
2800       return X.DefinitionID < Y.DefinitionID;
2801     }
2802     bool operator()(DeclID X, DeclID Y) {
2803       return X < Y;
2804     }
2805   };
2806 
2807   /// \brief Given an ObjC interface, goes through the modules and links to the
2808   /// interface all the categories for it.
2809   class ObjCCategoriesVisitor {
2810     ASTReader &Reader;
2811     serialization::GlobalDeclID InterfaceID;
2812     ObjCInterfaceDecl *Interface;
2813     llvm::SmallPtrSet<ObjCCategoryDecl *, 16> &Deserialized;
2814     unsigned PreviousGeneration;
2815     ObjCCategoryDecl *Tail;
2816     llvm::DenseMap<DeclarationName, ObjCCategoryDecl *> NameCategoryMap;
2817 
2818     void add(ObjCCategoryDecl *Cat) {
2819       // Only process each category once.
2820       if (!Deserialized.erase(Cat))
2821         return;
2822 
2823       // Check for duplicate categories.
2824       if (Cat->getDeclName()) {
2825         ObjCCategoryDecl *&Existing = NameCategoryMap[Cat->getDeclName()];
2826         if (Existing &&
2827             Reader.getOwningModuleFile(Existing)
2828                                           != Reader.getOwningModuleFile(Cat)) {
2829           // FIXME: We should not warn for duplicates in diamond:
2830           //
2831           //   MT     //
2832           //  /  \    //
2833           // ML  MR   //
2834           //  \  /    //
2835           //   MB     //
2836           //
2837           // If there are duplicates in ML/MR, there will be warning when
2838           // creating MB *and* when importing MB. We should not warn when
2839           // importing.
2840           Reader.Diag(Cat->getLocation(), diag::warn_dup_category_def)
2841             << Interface->getDeclName() << Cat->getDeclName();
2842           Reader.Diag(Existing->getLocation(), diag::note_previous_definition);
2843         } else if (!Existing) {
2844           // Record this category.
2845           Existing = Cat;
2846         }
2847       }
2848 
2849       // Add this category to the end of the chain.
2850       if (Tail)
2851         ASTDeclReader::setNextObjCCategory(Tail, Cat);
2852       else
2853         Interface->setCategoryListRaw(Cat);
2854       Tail = Cat;
2855     }
2856 
2857   public:
2858     ObjCCategoriesVisitor(ASTReader &Reader,
2859                           serialization::GlobalDeclID InterfaceID,
2860                           ObjCInterfaceDecl *Interface,
2861                         llvm::SmallPtrSet<ObjCCategoryDecl *, 16> &Deserialized,
2862                           unsigned PreviousGeneration)
2863       : Reader(Reader), InterfaceID(InterfaceID), Interface(Interface),
2864         Deserialized(Deserialized), PreviousGeneration(PreviousGeneration),
2865         Tail(0)
2866     {
2867       // Populate the name -> category map with the set of known categories.
2868       for (ObjCInterfaceDecl::known_categories_iterator
2869              Cat = Interface->known_categories_begin(),
2870              CatEnd = Interface->known_categories_end();
2871            Cat != CatEnd; ++Cat) {
2872         if (Cat->getDeclName())
2873           NameCategoryMap[Cat->getDeclName()] = *Cat;
2874 
2875         // Keep track of the tail of the category list.
2876         Tail = *Cat;
2877       }
2878     }
2879 
2880     static bool visit(ModuleFile &M, void *UserData) {
2881       return static_cast<ObjCCategoriesVisitor *>(UserData)->visit(M);
2882     }
2883 
2884     bool visit(ModuleFile &M) {
2885       // If we've loaded all of the category information we care about from
2886       // this module file, we're done.
2887       if (M.Generation <= PreviousGeneration)
2888         return true;
2889 
2890       // Map global ID of the definition down to the local ID used in this
2891       // module file. If there is no such mapping, we'll find nothing here
2892       // (or in any module it imports).
2893       DeclID LocalID = Reader.mapGlobalIDToModuleFileGlobalID(M, InterfaceID);
2894       if (!LocalID)
2895         return true;
2896 
2897       // Perform a binary search to find the local redeclarations for this
2898       // declaration (if any).
2899       const ObjCCategoriesInfo *Result
2900         = std::lower_bound(M.ObjCCategoriesMap,
2901                            M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap,
2902                            LocalID, CompareObjCCategoriesInfo());
2903       if (Result == M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap ||
2904           Result->DefinitionID != LocalID) {
2905         // We didn't find anything. If the class definition is in this module
2906         // file, then the module files it depends on cannot have any categories,
2907         // so suppress further lookup.
2908         return Reader.isDeclIDFromModule(InterfaceID, M);
2909       }
2910 
2911       // We found something. Dig out all of the categories.
2912       unsigned Offset = Result->Offset;
2913       unsigned N = M.ObjCCategories[Offset];
2914       M.ObjCCategories[Offset++] = 0; // Don't try to deserialize again
2915       for (unsigned I = 0; I != N; ++I)
2916         add(cast_or_null<ObjCCategoryDecl>(
2917               Reader.GetLocalDecl(M, M.ObjCCategories[Offset++])));
2918       return true;
2919     }
2920   };
2921 }
2922 
2923 void ASTReader::loadObjCCategories(serialization::GlobalDeclID ID,
2924                                    ObjCInterfaceDecl *D,
2925                                    unsigned PreviousGeneration) {
2926   ObjCCategoriesVisitor Visitor(*this, ID, D, CategoriesDeserialized,
2927                                 PreviousGeneration);
2928   ModuleMgr.visit(ObjCCategoriesVisitor::visit, &Visitor);
2929 }
2930 
2931 void ASTDeclReader::UpdateDecl(Decl *D, ModuleFile &ModuleFile,
2932                                const RecordData &Record) {
2933   unsigned Idx = 0;
2934   while (Idx < Record.size()) {
2935     switch ((DeclUpdateKind)Record[Idx++]) {
2936     case UPD_CXX_ADDED_IMPLICIT_MEMBER:
2937       cast<CXXRecordDecl>(D)->addedMember(Reader.ReadDecl(ModuleFile, Record, Idx));
2938       break;
2939 
2940     case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
2941       // It will be added to the template's specializations set when loaded.
2942       (void)Reader.ReadDecl(ModuleFile, Record, Idx);
2943       break;
2944 
2945     case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: {
2946       NamespaceDecl *Anon
2947         = Reader.ReadDeclAs<NamespaceDecl>(ModuleFile, Record, Idx);
2948 
2949       // Each module has its own anonymous namespace, which is disjoint from
2950       // any other module's anonymous namespaces, so don't attach the anonymous
2951       // namespace at all.
2952       if (ModuleFile.Kind != MK_Module) {
2953         if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(D))
2954           TU->setAnonymousNamespace(Anon);
2955         else
2956           cast<NamespaceDecl>(D)->setAnonymousNamespace(Anon);
2957       }
2958       break;
2959     }
2960 
2961     case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER:
2962       cast<VarDecl>(D)->getMemberSpecializationInfo()->setPointOfInstantiation(
2963           Reader.ReadSourceLocation(ModuleFile, Record, Idx));
2964       break;
2965 
2966     case UPD_CXX_DEDUCED_RETURN_TYPE: {
2967       FunctionDecl *FD = cast<FunctionDecl>(D);
2968       Reader.Context.adjustDeducedFunctionResultType(
2969           FD, Reader.readType(ModuleFile, Record, Idx));
2970       break;
2971     }
2972 
2973     case UPD_DECL_MARKED_USED: {
2974       // FIXME: This doesn't send the right notifications if there are
2975       // ASTMutationListeners other than an ASTWriter.
2976       D->setIsUsed(true);
2977       break;
2978     }
2979     }
2980   }
2981 }
2982