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->Used = 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   bool backingIvarReferencedInAccessor = Record[Idx++];
802   IVD->setBackingIvarReferencedInAccessor(backingIvarReferencedInAccessor);
803 }
804 
805 void ASTDeclReader::VisitObjCProtocolDecl(ObjCProtocolDecl *PD) {
806   RedeclarableResult Redecl = VisitRedeclarable(PD);
807   VisitObjCContainerDecl(PD);
808   mergeRedeclarable(PD, Redecl);
809 
810   if (Record[Idx++]) {
811     // Read the definition.
812     PD->allocateDefinitionData();
813 
814     // Set the definition data of the canonical declaration, so other
815     // redeclarations will see it.
816     PD->getCanonicalDecl()->Data = PD->Data;
817 
818     unsigned NumProtoRefs = Record[Idx++];
819     SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
820     ProtoRefs.reserve(NumProtoRefs);
821     for (unsigned I = 0; I != NumProtoRefs; ++I)
822       ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
823     SmallVector<SourceLocation, 16> ProtoLocs;
824     ProtoLocs.reserve(NumProtoRefs);
825     for (unsigned I = 0; I != NumProtoRefs; ++I)
826       ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
827     PD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
828                         Reader.getContext());
829 
830     // Note that we have deserialized a definition.
831     Reader.PendingDefinitions.insert(PD);
832   } else {
833     PD->Data = PD->getCanonicalDecl()->Data;
834   }
835 }
836 
837 void ASTDeclReader::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *FD) {
838   VisitFieldDecl(FD);
839 }
840 
841 void ASTDeclReader::VisitObjCCategoryDecl(ObjCCategoryDecl *CD) {
842   VisitObjCContainerDecl(CD);
843   CD->setCategoryNameLoc(ReadSourceLocation(Record, Idx));
844   CD->setIvarLBraceLoc(ReadSourceLocation(Record, Idx));
845   CD->setIvarRBraceLoc(ReadSourceLocation(Record, Idx));
846 
847   // Note that this category has been deserialized. We do this before
848   // deserializing the interface declaration, so that it will consider this
849   /// category.
850   Reader.CategoriesDeserialized.insert(CD);
851 
852   CD->ClassInterface = ReadDeclAs<ObjCInterfaceDecl>(Record, Idx);
853   unsigned NumProtoRefs = Record[Idx++];
854   SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
855   ProtoRefs.reserve(NumProtoRefs);
856   for (unsigned I = 0; I != NumProtoRefs; ++I)
857     ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
858   SmallVector<SourceLocation, 16> ProtoLocs;
859   ProtoLocs.reserve(NumProtoRefs);
860   for (unsigned I = 0; I != NumProtoRefs; ++I)
861     ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
862   CD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
863                       Reader.getContext());
864 }
865 
866 void ASTDeclReader::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *CAD) {
867   VisitNamedDecl(CAD);
868   CAD->setClassInterface(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
869 }
870 
871 void ASTDeclReader::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
872   VisitNamedDecl(D);
873   D->setAtLoc(ReadSourceLocation(Record, Idx));
874   D->setLParenLoc(ReadSourceLocation(Record, Idx));
875   D->setType(GetTypeSourceInfo(Record, Idx));
876   // FIXME: stable encoding
877   D->setPropertyAttributes(
878                       (ObjCPropertyDecl::PropertyAttributeKind)Record[Idx++]);
879   D->setPropertyAttributesAsWritten(
880                       (ObjCPropertyDecl::PropertyAttributeKind)Record[Idx++]);
881   // FIXME: stable encoding
882   D->setPropertyImplementation(
883                             (ObjCPropertyDecl::PropertyControl)Record[Idx++]);
884   D->setGetterName(Reader.ReadDeclarationName(F,Record, Idx).getObjCSelector());
885   D->setSetterName(Reader.ReadDeclarationName(F,Record, Idx).getObjCSelector());
886   D->setGetterMethodDecl(ReadDeclAs<ObjCMethodDecl>(Record, Idx));
887   D->setSetterMethodDecl(ReadDeclAs<ObjCMethodDecl>(Record, Idx));
888   D->setPropertyIvarDecl(ReadDeclAs<ObjCIvarDecl>(Record, Idx));
889 }
890 
891 void ASTDeclReader::VisitObjCImplDecl(ObjCImplDecl *D) {
892   VisitObjCContainerDecl(D);
893   D->setClassInterface(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
894 }
895 
896 void ASTDeclReader::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
897   VisitObjCImplDecl(D);
898   D->setIdentifier(Reader.GetIdentifierInfo(F, Record, Idx));
899   D->CategoryNameLoc = ReadSourceLocation(Record, Idx);
900 }
901 
902 void ASTDeclReader::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
903   VisitObjCImplDecl(D);
904   D->setSuperClass(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
905   D->SuperLoc = ReadSourceLocation(Record, Idx);
906   D->setIvarLBraceLoc(ReadSourceLocation(Record, Idx));
907   D->setIvarRBraceLoc(ReadSourceLocation(Record, Idx));
908   D->setHasNonZeroConstructors(Record[Idx++]);
909   D->setHasDestructors(Record[Idx++]);
910   llvm::tie(D->IvarInitializers, D->NumIvarInitializers)
911       = Reader.ReadCXXCtorInitializers(F, Record, Idx);
912 }
913 
914 
915 void ASTDeclReader::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
916   VisitDecl(D);
917   D->setAtLoc(ReadSourceLocation(Record, Idx));
918   D->setPropertyDecl(ReadDeclAs<ObjCPropertyDecl>(Record, Idx));
919   D->PropertyIvarDecl = ReadDeclAs<ObjCIvarDecl>(Record, Idx);
920   D->IvarLoc = ReadSourceLocation(Record, Idx);
921   D->setGetterCXXConstructor(Reader.ReadExpr(F));
922   D->setSetterCXXAssignment(Reader.ReadExpr(F));
923 }
924 
925 void ASTDeclReader::VisitFieldDecl(FieldDecl *FD) {
926   VisitDeclaratorDecl(FD);
927   FD->Mutable = Record[Idx++];
928   if (int BitWidthOrInitializer = Record[Idx++]) {
929     FD->InitializerOrBitWidth.setInt(BitWidthOrInitializer - 1);
930     FD->InitializerOrBitWidth.setPointer(Reader.ReadExpr(F));
931   }
932   if (!FD->getDeclName()) {
933     if (FieldDecl *Tmpl = ReadDeclAs<FieldDecl>(Record, Idx))
934       Reader.getContext().setInstantiatedFromUnnamedFieldDecl(FD, Tmpl);
935   }
936   mergeMergeable(FD);
937 }
938 
939 void ASTDeclReader::VisitMSPropertyDecl(MSPropertyDecl *PD) {
940   VisitDeclaratorDecl(PD);
941   PD->GetterId = Reader.GetIdentifierInfo(F, Record, Idx);
942   PD->SetterId = Reader.GetIdentifierInfo(F, Record, Idx);
943 }
944 
945 void ASTDeclReader::VisitIndirectFieldDecl(IndirectFieldDecl *FD) {
946   VisitValueDecl(FD);
947 
948   FD->ChainingSize = Record[Idx++];
949   assert(FD->ChainingSize >= 2 && "Anonymous chaining must be >= 2");
950   FD->Chaining = new (Reader.getContext())NamedDecl*[FD->ChainingSize];
951 
952   for (unsigned I = 0; I != FD->ChainingSize; ++I)
953     FD->Chaining[I] = ReadDeclAs<NamedDecl>(Record, Idx);
954 }
955 
956 ASTDeclReader::RedeclarableResult ASTDeclReader::VisitVarDeclImpl(VarDecl *VD) {
957   RedeclarableResult Redecl = VisitRedeclarable(VD);
958   VisitDeclaratorDecl(VD);
959 
960   VD->VarDeclBits.SClass = (StorageClass)Record[Idx++];
961   VD->VarDeclBits.TSCSpec = Record[Idx++];
962   VD->VarDeclBits.InitStyle = Record[Idx++];
963   VD->VarDeclBits.ExceptionVar = Record[Idx++];
964   VD->VarDeclBits.NRVOVariable = Record[Idx++];
965   VD->VarDeclBits.CXXForRangeDecl = Record[Idx++];
966   VD->VarDeclBits.ARCPseudoStrong = Record[Idx++];
967   VD->VarDeclBits.IsConstexpr = Record[Idx++];
968   VD->VarDeclBits.IsInitCapture = Record[Idx++];
969   VD->VarDeclBits.PreviousDeclInSameBlockScope = Record[Idx++];
970   Linkage VarLinkage = Linkage(Record[Idx++]);
971   VD->setCachedLinkage(VarLinkage);
972 
973   // Reconstruct the one piece of the IdentifierNamespace that we need.
974   if (VarLinkage != NoLinkage &&
975       VD->getLexicalDeclContext()->isFunctionOrMethod())
976     VD->setLocalExternDecl();
977 
978   // Only true variables (not parameters or implicit parameters) can be merged.
979   if (VD->getKind() != Decl::ParmVar && VD->getKind() != Decl::ImplicitParam)
980     mergeRedeclarable(VD, Redecl);
981 
982   if (uint64_t Val = Record[Idx++]) {
983     VD->setInit(Reader.ReadExpr(F));
984     if (Val > 1) {
985       EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
986       Eval->CheckedICE = true;
987       Eval->IsICE = Val == 3;
988     }
989   }
990 
991   enum VarKind {
992     VarNotTemplate = 0, VarTemplate, StaticDataMemberSpecialization
993   };
994   switch ((VarKind)Record[Idx++]) {
995   case VarNotTemplate:
996     break;
997   case VarTemplate:
998     VD->setDescribedVarTemplate(ReadDeclAs<VarTemplateDecl>(Record, Idx));
999     break;
1000   case StaticDataMemberSpecialization: { // HasMemberSpecializationInfo.
1001     VarDecl *Tmpl = ReadDeclAs<VarDecl>(Record, Idx);
1002     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
1003     SourceLocation POI = ReadSourceLocation(Record, Idx);
1004     Reader.getContext().setInstantiatedFromStaticDataMember(VD, Tmpl, TSK,POI);
1005     break;
1006   }
1007   }
1008 
1009   return Redecl;
1010 }
1011 
1012 void ASTDeclReader::VisitImplicitParamDecl(ImplicitParamDecl *PD) {
1013   VisitVarDecl(PD);
1014 }
1015 
1016 void ASTDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
1017   VisitVarDecl(PD);
1018   unsigned isObjCMethodParam = Record[Idx++];
1019   unsigned scopeDepth = Record[Idx++];
1020   unsigned scopeIndex = Record[Idx++];
1021   unsigned declQualifier = Record[Idx++];
1022   if (isObjCMethodParam) {
1023     assert(scopeDepth == 0);
1024     PD->setObjCMethodScopeInfo(scopeIndex);
1025     PD->ParmVarDeclBits.ScopeDepthOrObjCQuals = declQualifier;
1026   } else {
1027     PD->setScopeInfo(scopeDepth, scopeIndex);
1028   }
1029   PD->ParmVarDeclBits.IsKNRPromoted = Record[Idx++];
1030   PD->ParmVarDeclBits.HasInheritedDefaultArg = Record[Idx++];
1031   if (Record[Idx++]) // hasUninstantiatedDefaultArg.
1032     PD->setUninstantiatedDefaultArg(Reader.ReadExpr(F));
1033 
1034   // FIXME: If this is a redeclaration of a function from another module, handle
1035   // inheritance of default arguments.
1036 }
1037 
1038 void ASTDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {
1039   VisitDecl(AD);
1040   AD->setAsmString(cast<StringLiteral>(Reader.ReadExpr(F)));
1041   AD->setRParenLoc(ReadSourceLocation(Record, Idx));
1042 }
1043 
1044 void ASTDeclReader::VisitBlockDecl(BlockDecl *BD) {
1045   VisitDecl(BD);
1046   BD->setBody(cast_or_null<CompoundStmt>(Reader.ReadStmt(F)));
1047   BD->setSignatureAsWritten(GetTypeSourceInfo(Record, Idx));
1048   unsigned NumParams = Record[Idx++];
1049   SmallVector<ParmVarDecl *, 16> Params;
1050   Params.reserve(NumParams);
1051   for (unsigned I = 0; I != NumParams; ++I)
1052     Params.push_back(ReadDeclAs<ParmVarDecl>(Record, Idx));
1053   BD->setParams(Params);
1054 
1055   BD->setIsVariadic(Record[Idx++]);
1056   BD->setBlockMissingReturnType(Record[Idx++]);
1057   BD->setIsConversionFromLambda(Record[Idx++]);
1058 
1059   bool capturesCXXThis = Record[Idx++];
1060   unsigned numCaptures = Record[Idx++];
1061   SmallVector<BlockDecl::Capture, 16> captures;
1062   captures.reserve(numCaptures);
1063   for (unsigned i = 0; i != numCaptures; ++i) {
1064     VarDecl *decl = ReadDeclAs<VarDecl>(Record, Idx);
1065     unsigned flags = Record[Idx++];
1066     bool byRef = (flags & 1);
1067     bool nested = (flags & 2);
1068     Expr *copyExpr = ((flags & 4) ? Reader.ReadExpr(F) : 0);
1069 
1070     captures.push_back(BlockDecl::Capture(decl, byRef, nested, copyExpr));
1071   }
1072   BD->setCaptures(Reader.getContext(), captures.begin(),
1073                   captures.end(), capturesCXXThis);
1074 }
1075 
1076 void ASTDeclReader::VisitCapturedDecl(CapturedDecl *CD) {
1077   VisitDecl(CD);
1078   // Body is set by VisitCapturedStmt.
1079   for (unsigned i = 0; i < CD->NumParams; ++i)
1080     CD->setParam(i, ReadDeclAs<ImplicitParamDecl>(Record, Idx));
1081 }
1082 
1083 void ASTDeclReader::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1084   VisitDecl(D);
1085   D->setLanguage((LinkageSpecDecl::LanguageIDs)Record[Idx++]);
1086   D->setExternLoc(ReadSourceLocation(Record, Idx));
1087   D->setRBraceLoc(ReadSourceLocation(Record, Idx));
1088 }
1089 
1090 void ASTDeclReader::VisitLabelDecl(LabelDecl *D) {
1091   VisitNamedDecl(D);
1092   D->setLocStart(ReadSourceLocation(Record, Idx));
1093 }
1094 
1095 
1096 void ASTDeclReader::VisitNamespaceDecl(NamespaceDecl *D) {
1097   RedeclarableResult Redecl = VisitRedeclarable(D);
1098   VisitNamedDecl(D);
1099   D->setInline(Record[Idx++]);
1100   D->LocStart = ReadSourceLocation(Record, Idx);
1101   D->RBraceLoc = ReadSourceLocation(Record, Idx);
1102   // FIXME: At the point of this call, D->getCanonicalDecl() returns 0.
1103   mergeRedeclarable(D, Redecl);
1104 
1105   if (Redecl.getFirstID() == ThisDeclID) {
1106     // Each module has its own anonymous namespace, which is disjoint from
1107     // any other module's anonymous namespaces, so don't attach the anonymous
1108     // namespace at all.
1109     NamespaceDecl *Anon = ReadDeclAs<NamespaceDecl>(Record, Idx);
1110     if (F.Kind != MK_Module)
1111       D->setAnonymousNamespace(Anon);
1112   } else {
1113     // Link this namespace back to the first declaration, which has already
1114     // been deserialized.
1115     D->AnonOrFirstNamespaceAndInline.setPointer(D->getFirstDecl());
1116   }
1117 }
1118 
1119 void ASTDeclReader::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1120   VisitNamedDecl(D);
1121   D->NamespaceLoc = ReadSourceLocation(Record, Idx);
1122   D->IdentLoc = ReadSourceLocation(Record, Idx);
1123   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1124   D->Namespace = ReadDeclAs<NamedDecl>(Record, Idx);
1125 }
1126 
1127 void ASTDeclReader::VisitUsingDecl(UsingDecl *D) {
1128   VisitNamedDecl(D);
1129   D->setUsingLoc(ReadSourceLocation(Record, Idx));
1130   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1131   ReadDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record, Idx);
1132   D->FirstUsingShadow.setPointer(ReadDeclAs<UsingShadowDecl>(Record, Idx));
1133   D->setTypename(Record[Idx++]);
1134   if (NamedDecl *Pattern = ReadDeclAs<NamedDecl>(Record, Idx))
1135     Reader.getContext().setInstantiatedFromUsingDecl(D, Pattern);
1136 }
1137 
1138 void ASTDeclReader::VisitUsingShadowDecl(UsingShadowDecl *D) {
1139   RedeclarableResult Redecl = VisitRedeclarable(D);
1140   VisitNamedDecl(D);
1141   D->setTargetDecl(ReadDeclAs<NamedDecl>(Record, Idx));
1142   D->UsingOrNextShadow = ReadDeclAs<NamedDecl>(Record, Idx);
1143   UsingShadowDecl *Pattern = ReadDeclAs<UsingShadowDecl>(Record, Idx);
1144   if (Pattern)
1145     Reader.getContext().setInstantiatedFromUsingShadowDecl(D, Pattern);
1146   mergeRedeclarable(D, Redecl);
1147 }
1148 
1149 void ASTDeclReader::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1150   VisitNamedDecl(D);
1151   D->UsingLoc = ReadSourceLocation(Record, Idx);
1152   D->NamespaceLoc = ReadSourceLocation(Record, Idx);
1153   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1154   D->NominatedNamespace = ReadDeclAs<NamedDecl>(Record, Idx);
1155   D->CommonAncestor = ReadDeclAs<DeclContext>(Record, Idx);
1156 }
1157 
1158 void ASTDeclReader::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1159   VisitValueDecl(D);
1160   D->setUsingLoc(ReadSourceLocation(Record, Idx));
1161   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1162   ReadDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record, Idx);
1163 }
1164 
1165 void ASTDeclReader::VisitUnresolvedUsingTypenameDecl(
1166                                                UnresolvedUsingTypenameDecl *D) {
1167   VisitTypeDecl(D);
1168   D->TypenameLocation = ReadSourceLocation(Record, Idx);
1169   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1170 }
1171 
1172 void ASTDeclReader::ReadCXXDefinitionData(
1173                                    struct CXXRecordDecl::DefinitionData &Data,
1174                                    const RecordData &Record, unsigned &Idx) {
1175   // Note: the caller has deserialized the IsLambda bit already.
1176   Data.UserDeclaredConstructor = Record[Idx++];
1177   Data.UserDeclaredSpecialMembers = Record[Idx++];
1178   Data.Aggregate = Record[Idx++];
1179   Data.PlainOldData = Record[Idx++];
1180   Data.Empty = Record[Idx++];
1181   Data.Polymorphic = Record[Idx++];
1182   Data.Abstract = Record[Idx++];
1183   Data.IsStandardLayout = Record[Idx++];
1184   Data.HasNoNonEmptyBases = Record[Idx++];
1185   Data.HasPrivateFields = Record[Idx++];
1186   Data.HasProtectedFields = Record[Idx++];
1187   Data.HasPublicFields = Record[Idx++];
1188   Data.HasMutableFields = Record[Idx++];
1189   Data.HasOnlyCMembers = Record[Idx++];
1190   Data.HasInClassInitializer = Record[Idx++];
1191   Data.HasUninitializedReferenceMember = Record[Idx++];
1192   Data.NeedOverloadResolutionForMoveConstructor = Record[Idx++];
1193   Data.NeedOverloadResolutionForMoveAssignment = Record[Idx++];
1194   Data.NeedOverloadResolutionForDestructor = Record[Idx++];
1195   Data.DefaultedMoveConstructorIsDeleted = Record[Idx++];
1196   Data.DefaultedMoveAssignmentIsDeleted = Record[Idx++];
1197   Data.DefaultedDestructorIsDeleted = Record[Idx++];
1198   Data.HasTrivialSpecialMembers = Record[Idx++];
1199   Data.HasIrrelevantDestructor = Record[Idx++];
1200   Data.HasConstexprNonCopyMoveConstructor = Record[Idx++];
1201   Data.DefaultedDefaultConstructorIsConstexpr = Record[Idx++];
1202   Data.HasConstexprDefaultConstructor = Record[Idx++];
1203   Data.HasNonLiteralTypeFieldsOrBases = Record[Idx++];
1204   Data.ComputedVisibleConversions = Record[Idx++];
1205   Data.UserProvidedDefaultConstructor = Record[Idx++];
1206   Data.DeclaredSpecialMembers = Record[Idx++];
1207   Data.ImplicitCopyConstructorHasConstParam = Record[Idx++];
1208   Data.ImplicitCopyAssignmentHasConstParam = Record[Idx++];
1209   Data.HasDeclaredCopyConstructorWithConstParam = Record[Idx++];
1210   Data.HasDeclaredCopyAssignmentWithConstParam = Record[Idx++];
1211   Data.FailedImplicitMoveConstructor = Record[Idx++];
1212   Data.FailedImplicitMoveAssignment = Record[Idx++];
1213 
1214   Data.NumBases = Record[Idx++];
1215   if (Data.NumBases)
1216     Data.Bases = Reader.readCXXBaseSpecifiers(F, Record, Idx);
1217   Data.NumVBases = Record[Idx++];
1218   if (Data.NumVBases)
1219     Data.VBases = Reader.readCXXBaseSpecifiers(F, Record, Idx);
1220 
1221   Reader.ReadUnresolvedSet(F, Data.Conversions, Record, Idx);
1222   Reader.ReadUnresolvedSet(F, Data.VisibleConversions, Record, Idx);
1223   assert(Data.Definition && "Data.Definition should be already set!");
1224   Data.FirstFriend = ReadDeclID(Record, Idx);
1225 
1226   if (Data.IsLambda) {
1227     typedef LambdaExpr::Capture Capture;
1228     CXXRecordDecl::LambdaDefinitionData &Lambda
1229       = static_cast<CXXRecordDecl::LambdaDefinitionData &>(Data);
1230     Lambda.Dependent = Record[Idx++];
1231     Lambda.IsGenericLambda = Record[Idx++];
1232     Lambda.CaptureDefault = Record[Idx++];
1233     Lambda.NumCaptures = Record[Idx++];
1234     Lambda.NumExplicitCaptures = Record[Idx++];
1235     Lambda.ManglingNumber = Record[Idx++];
1236     Lambda.ContextDecl = ReadDecl(Record, Idx);
1237     Lambda.Captures
1238       = (Capture*)Reader.Context.Allocate(sizeof(Capture)*Lambda.NumCaptures);
1239     Capture *ToCapture = Lambda.Captures;
1240     Lambda.MethodTyInfo = GetTypeSourceInfo(Record, Idx);
1241     for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
1242       SourceLocation Loc = ReadSourceLocation(Record, Idx);
1243       bool IsImplicit = Record[Idx++];
1244       LambdaCaptureKind Kind = static_cast<LambdaCaptureKind>(Record[Idx++]);
1245       switch (Kind) {
1246       case LCK_This:
1247         *ToCapture++ = Capture(Loc, IsImplicit, Kind, 0, SourceLocation());
1248         break;
1249       case LCK_ByCopy:
1250       case LCK_ByRef:
1251         VarDecl *Var = ReadDeclAs<VarDecl>(Record, Idx);
1252         SourceLocation EllipsisLoc = ReadSourceLocation(Record, Idx);
1253         *ToCapture++ = Capture(Loc, IsImplicit, Kind, Var, EllipsisLoc);
1254         break;
1255       }
1256     }
1257   }
1258 }
1259 
1260 ASTDeclReader::RedeclarableResult
1261 ASTDeclReader::VisitCXXRecordDeclImpl(CXXRecordDecl *D) {
1262   RedeclarableResult Redecl = VisitRecordDeclImpl(D);
1263 
1264   ASTContext &C = Reader.getContext();
1265   bool WasDefinition = Record[Idx++];
1266   if (WasDefinition) {
1267     // Determine whether this is a lambda closure type, so that we can
1268     // allocate the appropriate DefinitionData structure.
1269     bool IsLambda = Record[Idx++];
1270     if (IsLambda)
1271       D->DefinitionData = new (C) CXXRecordDecl::LambdaDefinitionData(D, 0,
1272                                                                       false,
1273                                                                       false, LCD_None);
1274     else
1275       D->DefinitionData = new (C) struct CXXRecordDecl::DefinitionData(D);
1276 
1277     ReadCXXDefinitionData(*D->DefinitionData, Record, Idx);
1278 
1279     // Propagate the DefinitionData pointer to the canonical declaration, so
1280     // that all other deserialized declarations will see it.
1281     CXXRecordDecl *Canon = D->getCanonicalDecl();
1282     if (Canon == D) {
1283       // Nothing to do.
1284     } else if (!Canon->DefinitionData) {
1285       Canon->DefinitionData = D->DefinitionData;
1286 
1287       // Note that we have deserialized a definition. Any declarations
1288       // deserialized before this one will be be given the DefinitionData
1289       // pointer at the end.
1290       Reader.PendingDefinitions.insert(D);
1291     } else {
1292       // We have already deserialized a definition of this record. This
1293       // definition is no longer really a definition. Note that the pre-existing
1294       // definition is the *real* definition.
1295       // FIXME: Check DefinitionData for consistency with prior definition.
1296       Reader.MergedDeclContexts.insert(
1297           std::make_pair(D, D->getCanonicalDecl()->DefinitionData->Definition));
1298       D->IsCompleteDefinition = false;
1299       D->DefinitionData = D->getCanonicalDecl()->DefinitionData;
1300     }
1301   } else {
1302     // Propagate DefinitionData pointer from the canonical declaration.
1303     D->DefinitionData = D->getCanonicalDecl()->DefinitionData;
1304   }
1305 
1306   enum CXXRecKind {
1307     CXXRecNotTemplate = 0, CXXRecTemplate, CXXRecMemberSpecialization
1308   };
1309   switch ((CXXRecKind)Record[Idx++]) {
1310   case CXXRecNotTemplate:
1311     break;
1312   case CXXRecTemplate:
1313     D->TemplateOrInstantiation = ReadDeclAs<ClassTemplateDecl>(Record, Idx);
1314     break;
1315   case CXXRecMemberSpecialization: {
1316     CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(Record, Idx);
1317     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
1318     SourceLocation POI = ReadSourceLocation(Record, Idx);
1319     MemberSpecializationInfo *MSI = new (C) MemberSpecializationInfo(RD, TSK);
1320     MSI->setPointOfInstantiation(POI);
1321     D->TemplateOrInstantiation = MSI;
1322     break;
1323   }
1324   }
1325 
1326   // Lazily load the key function to avoid deserializing every method so we can
1327   // compute it.
1328   if (WasDefinition) {
1329     DeclID KeyFn = ReadDeclID(Record, Idx);
1330     if (KeyFn && D->IsCompleteDefinition)
1331       C.KeyFunctions[D] = KeyFn;
1332   }
1333 
1334   return Redecl;
1335 }
1336 
1337 void ASTDeclReader::VisitCXXMethodDecl(CXXMethodDecl *D) {
1338   VisitFunctionDecl(D);
1339   unsigned NumOverridenMethods = Record[Idx++];
1340   while (NumOverridenMethods--) {
1341     // Avoid invariant checking of CXXMethodDecl::addOverriddenMethod,
1342     // MD may be initializing.
1343     if (CXXMethodDecl *MD = ReadDeclAs<CXXMethodDecl>(Record, Idx))
1344       Reader.getContext().addOverriddenMethod(D, MD);
1345   }
1346 }
1347 
1348 void ASTDeclReader::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1349   VisitCXXMethodDecl(D);
1350 
1351   D->IsExplicitSpecified = Record[Idx++];
1352   llvm::tie(D->CtorInitializers, D->NumCtorInitializers)
1353       = Reader.ReadCXXCtorInitializers(F, Record, Idx);
1354 }
1355 
1356 void ASTDeclReader::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1357   VisitCXXMethodDecl(D);
1358 
1359   D->OperatorDelete = ReadDeclAs<FunctionDecl>(Record, Idx);
1360 }
1361 
1362 void ASTDeclReader::VisitCXXConversionDecl(CXXConversionDecl *D) {
1363   VisitCXXMethodDecl(D);
1364   D->IsExplicitSpecified = Record[Idx++];
1365 }
1366 
1367 void ASTDeclReader::VisitImportDecl(ImportDecl *D) {
1368   VisitDecl(D);
1369   D->ImportedAndComplete.setPointer(readModule(Record, Idx));
1370   D->ImportedAndComplete.setInt(Record[Idx++]);
1371   SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(D + 1);
1372   for (unsigned I = 0, N = Record.back(); I != N; ++I)
1373     StoredLocs[I] = ReadSourceLocation(Record, Idx);
1374   ++Idx; // The number of stored source locations.
1375 }
1376 
1377 void ASTDeclReader::VisitAccessSpecDecl(AccessSpecDecl *D) {
1378   VisitDecl(D);
1379   D->setColonLoc(ReadSourceLocation(Record, Idx));
1380 }
1381 
1382 void ASTDeclReader::VisitFriendDecl(FriendDecl *D) {
1383   VisitDecl(D);
1384   if (Record[Idx++]) // hasFriendDecl
1385     D->Friend = ReadDeclAs<NamedDecl>(Record, Idx);
1386   else
1387     D->Friend = GetTypeSourceInfo(Record, Idx);
1388   for (unsigned i = 0; i != D->NumTPLists; ++i)
1389     D->getTPLists()[i] = Reader.ReadTemplateParameterList(F, Record, Idx);
1390   D->NextFriend = ReadDeclID(Record, Idx);
1391   D->UnsupportedFriend = (Record[Idx++] != 0);
1392   D->FriendLoc = ReadSourceLocation(Record, Idx);
1393 }
1394 
1395 void ASTDeclReader::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
1396   VisitDecl(D);
1397   unsigned NumParams = Record[Idx++];
1398   D->NumParams = NumParams;
1399   D->Params = new TemplateParameterList*[NumParams];
1400   for (unsigned i = 0; i != NumParams; ++i)
1401     D->Params[i] = Reader.ReadTemplateParameterList(F, Record, Idx);
1402   if (Record[Idx++]) // HasFriendDecl
1403     D->Friend = ReadDeclAs<NamedDecl>(Record, Idx);
1404   else
1405     D->Friend = GetTypeSourceInfo(Record, Idx);
1406   D->FriendLoc = ReadSourceLocation(Record, Idx);
1407 }
1408 
1409 void ASTDeclReader::VisitTemplateDecl(TemplateDecl *D) {
1410   VisitNamedDecl(D);
1411 
1412   NamedDecl *TemplatedDecl = ReadDeclAs<NamedDecl>(Record, Idx);
1413   TemplateParameterList* TemplateParams
1414       = Reader.ReadTemplateParameterList(F, Record, Idx);
1415   D->init(TemplatedDecl, TemplateParams);
1416 
1417   // FIXME: If this is a redeclaration of a template from another module, handle
1418   // inheritance of default template arguments.
1419 }
1420 
1421 ASTDeclReader::RedeclarableResult
1422 ASTDeclReader::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
1423   RedeclarableResult Redecl = VisitRedeclarable(D);
1424 
1425   // Make sure we've allocated the Common pointer first. We do this before
1426   // VisitTemplateDecl so that getCommonPtr() can be used during initialization.
1427   RedeclarableTemplateDecl *CanonD = D->getCanonicalDecl();
1428   if (!CanonD->Common) {
1429     CanonD->Common = CanonD->newCommon(Reader.getContext());
1430     Reader.PendingDefinitions.insert(CanonD);
1431   }
1432   D->Common = CanonD->Common;
1433 
1434   // If this is the first declaration of the template, fill in the information
1435   // for the 'common' pointer.
1436   if (ThisDeclID == Redecl.getFirstID()) {
1437     if (RedeclarableTemplateDecl *RTD
1438           = ReadDeclAs<RedeclarableTemplateDecl>(Record, Idx)) {
1439       assert(RTD->getKind() == D->getKind() &&
1440              "InstantiatedFromMemberTemplate kind mismatch");
1441       D->setInstantiatedFromMemberTemplate(RTD);
1442       if (Record[Idx++])
1443         D->setMemberSpecialization();
1444     }
1445   }
1446 
1447   VisitTemplateDecl(D);
1448   D->IdentifierNamespace = Record[Idx++];
1449 
1450   mergeRedeclarable(D, Redecl);
1451 
1452   // If we merged the template with a prior declaration chain, merge the common
1453   // pointer.
1454   // FIXME: Actually merge here, don't just overwrite.
1455   D->Common = D->getCanonicalDecl()->Common;
1456 
1457   return Redecl;
1458 }
1459 
1460 void ASTDeclReader::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1461   RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
1462 
1463   if (ThisDeclID == Redecl.getFirstID()) {
1464     // This ClassTemplateDecl owns a CommonPtr; read it to keep track of all of
1465     // the specializations.
1466     SmallVector<serialization::DeclID, 2> SpecIDs;
1467     SpecIDs.push_back(0);
1468 
1469     // Specializations.
1470     unsigned Size = Record[Idx++];
1471     SpecIDs[0] += Size;
1472     for (unsigned I = 0; I != Size; ++I)
1473       SpecIDs.push_back(ReadDeclID(Record, Idx));
1474 
1475     // Partial specializations.
1476     Size = Record[Idx++];
1477     SpecIDs[0] += Size;
1478     for (unsigned I = 0; I != Size; ++I)
1479       SpecIDs.push_back(ReadDeclID(Record, Idx));
1480 
1481     ClassTemplateDecl::Common *CommonPtr = D->getCommonPtr();
1482     if (SpecIDs[0]) {
1483       typedef serialization::DeclID DeclID;
1484 
1485       // FIXME: Append specializations!
1486       CommonPtr->LazySpecializations
1487         = new (Reader.getContext()) DeclID [SpecIDs.size()];
1488       memcpy(CommonPtr->LazySpecializations, SpecIDs.data(),
1489              SpecIDs.size() * sizeof(DeclID));
1490     }
1491 
1492     CommonPtr->InjectedClassNameType = Reader.readType(F, Record, Idx);
1493   }
1494 }
1495 
1496 /// TODO: Unify with ClassTemplateDecl version?
1497 ///       May require unifying ClassTemplateDecl and
1498 ///        VarTemplateDecl beyond TemplateDecl...
1499 void ASTDeclReader::VisitVarTemplateDecl(VarTemplateDecl *D) {
1500   RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
1501 
1502   if (ThisDeclID == Redecl.getFirstID()) {
1503     // This VarTemplateDecl owns a CommonPtr; read it to keep track of all of
1504     // the specializations.
1505     SmallVector<serialization::DeclID, 2> SpecIDs;
1506     SpecIDs.push_back(0);
1507 
1508     // Specializations.
1509     unsigned Size = Record[Idx++];
1510     SpecIDs[0] += Size;
1511     for (unsigned I = 0; I != Size; ++I)
1512       SpecIDs.push_back(ReadDeclID(Record, Idx));
1513 
1514     // Partial specializations.
1515     Size = Record[Idx++];
1516     SpecIDs[0] += Size;
1517     for (unsigned I = 0; I != Size; ++I)
1518       SpecIDs.push_back(ReadDeclID(Record, Idx));
1519 
1520     VarTemplateDecl::Common *CommonPtr = D->getCommonPtr();
1521     if (SpecIDs[0]) {
1522       typedef serialization::DeclID DeclID;
1523 
1524       // FIXME: Append specializations!
1525       CommonPtr->LazySpecializations =
1526           new (Reader.getContext()) DeclID[SpecIDs.size()];
1527       memcpy(CommonPtr->LazySpecializations, SpecIDs.data(),
1528              SpecIDs.size() * sizeof(DeclID));
1529     }
1530   }
1531 }
1532 
1533 ASTDeclReader::RedeclarableResult
1534 ASTDeclReader::VisitClassTemplateSpecializationDeclImpl(
1535     ClassTemplateSpecializationDecl *D) {
1536   RedeclarableResult Redecl = VisitCXXRecordDeclImpl(D);
1537 
1538   ASTContext &C = Reader.getContext();
1539   if (Decl *InstD = ReadDecl(Record, Idx)) {
1540     if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(InstD)) {
1541       D->SpecializedTemplate = CTD;
1542     } else {
1543       SmallVector<TemplateArgument, 8> TemplArgs;
1544       Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1545       TemplateArgumentList *ArgList
1546         = TemplateArgumentList::CreateCopy(C, TemplArgs.data(),
1547                                            TemplArgs.size());
1548       ClassTemplateSpecializationDecl::SpecializedPartialSpecialization *PS
1549           = new (C) ClassTemplateSpecializationDecl::
1550                                              SpecializedPartialSpecialization();
1551       PS->PartialSpecialization
1552           = cast<ClassTemplatePartialSpecializationDecl>(InstD);
1553       PS->TemplateArgs = ArgList;
1554       D->SpecializedTemplate = PS;
1555     }
1556   }
1557 
1558   SmallVector<TemplateArgument, 8> TemplArgs;
1559   Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1560   D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs.data(),
1561                                                      TemplArgs.size());
1562   D->PointOfInstantiation = ReadSourceLocation(Record, Idx);
1563   D->SpecializationKind = (TemplateSpecializationKind)Record[Idx++];
1564 
1565   bool writtenAsCanonicalDecl = Record[Idx++];
1566   if (writtenAsCanonicalDecl) {
1567     ClassTemplateDecl *CanonPattern = ReadDeclAs<ClassTemplateDecl>(Record,Idx);
1568     if (D->isCanonicalDecl()) { // It's kept in the folding set.
1569       // Set this as, or find, the canonical declaration for this specialization
1570       ClassTemplateSpecializationDecl *CanonSpec;
1571       if (ClassTemplatePartialSpecializationDecl *Partial =
1572               dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) {
1573         CanonSpec = CanonPattern->getCommonPtr()->PartialSpecializations
1574             .GetOrInsertNode(Partial);
1575       } else {
1576         CanonSpec =
1577             CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
1578       }
1579       // If there was already a canonical specialization, merge into it.
1580       if (CanonSpec != D) {
1581         mergeRedeclarable<TagDecl>(D, CanonSpec, Redecl);
1582 
1583         // This declaration might be a definition. Merge with any existing
1584         // definition.
1585         if (D->DefinitionData) {
1586           if (!CanonSpec->DefinitionData) {
1587             CanonSpec->DefinitionData = D->DefinitionData;
1588           } else {
1589             // FIXME: Check DefinitionData for consistency with prior definition
1590             Reader.PendingDefinitions.erase(D);
1591             Reader.MergedDeclContexts.insert(
1592                 std::make_pair(D, CanonSpec->DefinitionData->Definition));
1593             D->IsCompleteDefinition = false;
1594             D->DefinitionData = CanonSpec->DefinitionData;
1595           }
1596         }
1597       }
1598     }
1599   }
1600 
1601   // Explicit info.
1602   if (TypeSourceInfo *TyInfo = GetTypeSourceInfo(Record, Idx)) {
1603     ClassTemplateSpecializationDecl::ExplicitSpecializationInfo *ExplicitInfo
1604         = new (C) ClassTemplateSpecializationDecl::ExplicitSpecializationInfo;
1605     ExplicitInfo->TypeAsWritten = TyInfo;
1606     ExplicitInfo->ExternLoc = ReadSourceLocation(Record, Idx);
1607     ExplicitInfo->TemplateKeywordLoc = ReadSourceLocation(Record, Idx);
1608     D->ExplicitInfo = ExplicitInfo;
1609   }
1610 
1611   return Redecl;
1612 }
1613 
1614 void ASTDeclReader::VisitClassTemplatePartialSpecializationDecl(
1615                                     ClassTemplatePartialSpecializationDecl *D) {
1616   RedeclarableResult Redecl = VisitClassTemplateSpecializationDeclImpl(D);
1617 
1618   D->TemplateParams = Reader.ReadTemplateParameterList(F, Record, Idx);
1619   D->ArgsAsWritten = Reader.ReadASTTemplateArgumentListInfo(F, Record, Idx);
1620 
1621   // These are read/set from/to the first declaration.
1622   if (ThisDeclID == Redecl.getFirstID()) {
1623     D->InstantiatedFromMember.setPointer(
1624       ReadDeclAs<ClassTemplatePartialSpecializationDecl>(Record, Idx));
1625     D->InstantiatedFromMember.setInt(Record[Idx++]);
1626   }
1627 }
1628 
1629 void ASTDeclReader::VisitClassScopeFunctionSpecializationDecl(
1630                                     ClassScopeFunctionSpecializationDecl *D) {
1631   VisitDecl(D);
1632   D->Specialization = ReadDeclAs<CXXMethodDecl>(Record, Idx);
1633 }
1634 
1635 void ASTDeclReader::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1636   RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
1637 
1638   if (ThisDeclID == Redecl.getFirstID()) {
1639     // This FunctionTemplateDecl owns a CommonPtr; read it.
1640 
1641     // Read the function specialization declaration IDs. The specializations
1642     // themselves will be loaded if they're needed.
1643     if (unsigned NumSpecs = Record[Idx++]) {
1644       // FIXME: Append specializations!
1645       FunctionTemplateDecl::Common *CommonPtr = D->getCommonPtr();
1646       CommonPtr->LazySpecializations = new (Reader.getContext())
1647           serialization::DeclID[NumSpecs + 1];
1648       CommonPtr->LazySpecializations[0] = NumSpecs;
1649       for (unsigned I = 0; I != NumSpecs; ++I)
1650         CommonPtr->LazySpecializations[I + 1] = ReadDeclID(Record, Idx);
1651     }
1652   }
1653 }
1654 
1655 /// TODO: Unify with ClassTemplateSpecializationDecl version?
1656 ///       May require unifying ClassTemplate(Partial)SpecializationDecl and
1657 ///        VarTemplate(Partial)SpecializationDecl with a new data
1658 ///        structure Template(Partial)SpecializationDecl, and
1659 ///        using Template(Partial)SpecializationDecl as input type.
1660 ASTDeclReader::RedeclarableResult
1661 ASTDeclReader::VisitVarTemplateSpecializationDeclImpl(
1662     VarTemplateSpecializationDecl *D) {
1663   RedeclarableResult Redecl = VisitVarDeclImpl(D);
1664 
1665   ASTContext &C = Reader.getContext();
1666   if (Decl *InstD = ReadDecl(Record, Idx)) {
1667     if (VarTemplateDecl *VTD = dyn_cast<VarTemplateDecl>(InstD)) {
1668       D->SpecializedTemplate = VTD;
1669     } else {
1670       SmallVector<TemplateArgument, 8> TemplArgs;
1671       Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1672       TemplateArgumentList *ArgList = TemplateArgumentList::CreateCopy(
1673           C, TemplArgs.data(), TemplArgs.size());
1674       VarTemplateSpecializationDecl::SpecializedPartialSpecialization *PS =
1675           new (C)
1676           VarTemplateSpecializationDecl::SpecializedPartialSpecialization();
1677       PS->PartialSpecialization =
1678           cast<VarTemplatePartialSpecializationDecl>(InstD);
1679       PS->TemplateArgs = ArgList;
1680       D->SpecializedTemplate = PS;
1681     }
1682   }
1683 
1684   // Explicit info.
1685   if (TypeSourceInfo *TyInfo = GetTypeSourceInfo(Record, Idx)) {
1686     VarTemplateSpecializationDecl::ExplicitSpecializationInfo *ExplicitInfo =
1687         new (C) VarTemplateSpecializationDecl::ExplicitSpecializationInfo;
1688     ExplicitInfo->TypeAsWritten = TyInfo;
1689     ExplicitInfo->ExternLoc = ReadSourceLocation(Record, Idx);
1690     ExplicitInfo->TemplateKeywordLoc = ReadSourceLocation(Record, Idx);
1691     D->ExplicitInfo = ExplicitInfo;
1692   }
1693 
1694   SmallVector<TemplateArgument, 8> TemplArgs;
1695   Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1696   D->TemplateArgs =
1697       TemplateArgumentList::CreateCopy(C, TemplArgs.data(), TemplArgs.size());
1698   D->PointOfInstantiation = ReadSourceLocation(Record, Idx);
1699   D->SpecializationKind = (TemplateSpecializationKind)Record[Idx++];
1700 
1701   bool writtenAsCanonicalDecl = Record[Idx++];
1702   if (writtenAsCanonicalDecl) {
1703     VarTemplateDecl *CanonPattern = ReadDeclAs<VarTemplateDecl>(Record, Idx);
1704     if (D->isCanonicalDecl()) { // It's kept in the folding set.
1705       if (VarTemplatePartialSpecializationDecl *Partial =
1706               dyn_cast<VarTemplatePartialSpecializationDecl>(D)) {
1707         CanonPattern->getCommonPtr()->PartialSpecializations
1708             .GetOrInsertNode(Partial);
1709       } else {
1710         CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
1711       }
1712     }
1713   }
1714 
1715   return Redecl;
1716 }
1717 
1718 /// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
1719 ///       May require unifying ClassTemplate(Partial)SpecializationDecl and
1720 ///        VarTemplate(Partial)SpecializationDecl with a new data
1721 ///        structure Template(Partial)SpecializationDecl, and
1722 ///        using Template(Partial)SpecializationDecl as input type.
1723 void ASTDeclReader::VisitVarTemplatePartialSpecializationDecl(
1724     VarTemplatePartialSpecializationDecl *D) {
1725   RedeclarableResult Redecl = VisitVarTemplateSpecializationDeclImpl(D);
1726 
1727   D->TemplateParams = Reader.ReadTemplateParameterList(F, Record, Idx);
1728   D->ArgsAsWritten = Reader.ReadASTTemplateArgumentListInfo(F, Record, Idx);
1729 
1730   // These are read/set from/to the first declaration.
1731   if (ThisDeclID == Redecl.getFirstID()) {
1732     D->InstantiatedFromMember.setPointer(
1733         ReadDeclAs<VarTemplatePartialSpecializationDecl>(Record, Idx));
1734     D->InstantiatedFromMember.setInt(Record[Idx++]);
1735   }
1736 }
1737 
1738 void ASTDeclReader::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
1739   VisitTypeDecl(D);
1740 
1741   D->setDeclaredWithTypename(Record[Idx++]);
1742 
1743   bool Inherited = Record[Idx++];
1744   TypeSourceInfo *DefArg = GetTypeSourceInfo(Record, Idx);
1745   D->setDefaultArgument(DefArg, Inherited);
1746 }
1747 
1748 void ASTDeclReader::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1749   VisitDeclaratorDecl(D);
1750   // TemplateParmPosition.
1751   D->setDepth(Record[Idx++]);
1752   D->setPosition(Record[Idx++]);
1753   if (D->isExpandedParameterPack()) {
1754     void **Data = reinterpret_cast<void **>(D + 1);
1755     for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1756       Data[2*I] = Reader.readType(F, Record, Idx).getAsOpaquePtr();
1757       Data[2*I + 1] = GetTypeSourceInfo(Record, Idx);
1758     }
1759   } else {
1760     // Rest of NonTypeTemplateParmDecl.
1761     D->ParameterPack = Record[Idx++];
1762     if (Record[Idx++]) {
1763       Expr *DefArg = Reader.ReadExpr(F);
1764       bool Inherited = Record[Idx++];
1765       D->setDefaultArgument(DefArg, Inherited);
1766    }
1767   }
1768 }
1769 
1770 void ASTDeclReader::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
1771   VisitTemplateDecl(D);
1772   // TemplateParmPosition.
1773   D->setDepth(Record[Idx++]);
1774   D->setPosition(Record[Idx++]);
1775   if (D->isExpandedParameterPack()) {
1776     void **Data = reinterpret_cast<void **>(D + 1);
1777     for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
1778          I != N; ++I)
1779       Data[I] = Reader.ReadTemplateParameterList(F, Record, Idx);
1780   } else {
1781     // Rest of TemplateTemplateParmDecl.
1782     TemplateArgumentLoc Arg = Reader.ReadTemplateArgumentLoc(F, Record, Idx);
1783     bool IsInherited = Record[Idx++];
1784     D->setDefaultArgument(Arg, IsInherited);
1785     D->ParameterPack = Record[Idx++];
1786   }
1787 }
1788 
1789 void ASTDeclReader::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
1790   VisitRedeclarableTemplateDecl(D);
1791 }
1792 
1793 void ASTDeclReader::VisitStaticAssertDecl(StaticAssertDecl *D) {
1794   VisitDecl(D);
1795   D->AssertExprAndFailed.setPointer(Reader.ReadExpr(F));
1796   D->AssertExprAndFailed.setInt(Record[Idx++]);
1797   D->Message = cast<StringLiteral>(Reader.ReadExpr(F));
1798   D->RParenLoc = ReadSourceLocation(Record, Idx);
1799 }
1800 
1801 void ASTDeclReader::VisitEmptyDecl(EmptyDecl *D) {
1802   VisitDecl(D);
1803 }
1804 
1805 std::pair<uint64_t, uint64_t>
1806 ASTDeclReader::VisitDeclContext(DeclContext *DC) {
1807   uint64_t LexicalOffset = Record[Idx++];
1808   uint64_t VisibleOffset = Record[Idx++];
1809   return std::make_pair(LexicalOffset, VisibleOffset);
1810 }
1811 
1812 template <typename T>
1813 ASTDeclReader::RedeclarableResult
1814 ASTDeclReader::VisitRedeclarable(Redeclarable<T> *D) {
1815   DeclID FirstDeclID = ReadDeclID(Record, Idx);
1816 
1817   // 0 indicates that this declaration was the only declaration of its entity,
1818   // and is used for space optimization.
1819   if (FirstDeclID == 0)
1820     FirstDeclID = ThisDeclID;
1821 
1822   T *FirstDecl = cast_or_null<T>(Reader.GetDecl(FirstDeclID));
1823   if (FirstDecl != D) {
1824     // We delay loading of the redeclaration chain to avoid deeply nested calls.
1825     // We temporarily set the first (canonical) declaration as the previous one
1826     // which is the one that matters and mark the real previous DeclID to be
1827     // loaded & attached later on.
1828     D->RedeclLink = Redeclarable<T>::PreviousDeclLink(FirstDecl);
1829   }
1830 
1831   // Note that this declaration has been deserialized.
1832   Reader.RedeclsDeserialized.insert(static_cast<T *>(D));
1833 
1834   // The result structure takes care to note that we need to load the
1835   // other declaration chains for this ID.
1836   return RedeclarableResult(Reader, FirstDeclID,
1837                             static_cast<T *>(D)->getKind());
1838 }
1839 
1840 /// \brief Attempts to merge the given declaration (D) with another declaration
1841 /// of the same entity.
1842 template<typename T>
1843 void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *D,
1844                                       RedeclarableResult &Redecl) {
1845   // If modules are not available, there is no reason to perform this merge.
1846   if (!Reader.getContext().getLangOpts().Modules)
1847     return;
1848 
1849   if (FindExistingResult ExistingRes = findExisting(static_cast<T*>(D)))
1850     if (T *Existing = ExistingRes)
1851       mergeRedeclarable(D, Existing, Redecl);
1852 }
1853 
1854 /// \brief Attempts to merge the given declaration (D) with another declaration
1855 /// of the same entity.
1856 template<typename T>
1857 void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *D, T *Existing,
1858                                       RedeclarableResult &Redecl) {
1859   T *ExistingCanon = Existing->getCanonicalDecl();
1860   T *DCanon = static_cast<T*>(D)->getCanonicalDecl();
1861   if (ExistingCanon != DCanon) {
1862     // Have our redeclaration link point back at the canonical declaration
1863     // of the existing declaration, so that this declaration has the
1864     // appropriate canonical declaration.
1865     D->RedeclLink = Redeclarable<T>::PreviousDeclLink(ExistingCanon);
1866 
1867     // When we merge a namespace, update its pointer to the first namespace.
1868     if (NamespaceDecl *Namespace
1869           = dyn_cast<NamespaceDecl>(static_cast<T*>(D))) {
1870       Namespace->AnonOrFirstNamespaceAndInline.setPointer(
1871         static_cast<NamespaceDecl *>(static_cast<void*>(ExistingCanon)));
1872     }
1873 
1874     // Don't introduce DCanon into the set of pending declaration chains.
1875     Redecl.suppress();
1876 
1877     // Introduce ExistingCanon into the set of pending declaration chains,
1878     // if in fact it came from a module file.
1879     if (ExistingCanon->isFromASTFile()) {
1880       GlobalDeclID ExistingCanonID = ExistingCanon->getGlobalID();
1881       assert(ExistingCanonID && "Unrecorded canonical declaration ID?");
1882       if (Reader.PendingDeclChainsKnown.insert(ExistingCanonID))
1883         Reader.PendingDeclChains.push_back(ExistingCanonID);
1884     }
1885 
1886     // If this declaration was the canonical declaration, make a note of
1887     // that. We accept the linear algorithm here because the number of
1888     // unique canonical declarations of an entity should always be tiny.
1889     if (DCanon == static_cast<T*>(D)) {
1890       SmallVectorImpl<DeclID> &Merged = Reader.MergedDecls[ExistingCanon];
1891       if (std::find(Merged.begin(), Merged.end(), Redecl.getFirstID())
1892             == Merged.end())
1893         Merged.push_back(Redecl.getFirstID());
1894 
1895       // If ExistingCanon did not come from a module file, introduce the
1896       // first declaration that *does* come from a module file to the
1897       // set of pending declaration chains, so that we merge this
1898       // declaration.
1899       if (!ExistingCanon->isFromASTFile() &&
1900           Reader.PendingDeclChainsKnown.insert(Redecl.getFirstID()))
1901         Reader.PendingDeclChains.push_back(Merged[0]);
1902     }
1903   }
1904 }
1905 
1906 /// \brief Attempts to merge the given declaration (D) with another declaration
1907 /// of the same entity, for the case where the entity is not actually
1908 /// redeclarable. This happens, for instance, when merging the fields of
1909 /// identical class definitions from two different modules.
1910 template<typename T>
1911 void ASTDeclReader::mergeMergeable(Mergeable<T> *D) {
1912   // If modules are not available, there is no reason to perform this merge.
1913   if (!Reader.getContext().getLangOpts().Modules)
1914     return;
1915 
1916   // ODR-based merging is only performed in C++. In C, identically-named things
1917   // in different translation units are not redeclarations (but may still have
1918   // compatible types).
1919   if (!Reader.getContext().getLangOpts().CPlusPlus)
1920     return;
1921 
1922   if (FindExistingResult ExistingRes = findExisting(static_cast<T*>(D)))
1923     if (T *Existing = ExistingRes)
1924       Reader.Context.setPrimaryMergedDecl(static_cast<T*>(D),
1925                                           Existing->getCanonicalDecl());
1926 }
1927 
1928 void ASTDeclReader::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {
1929   VisitDecl(D);
1930   unsigned NumVars = D->varlist_size();
1931   SmallVector<Expr *, 16> Vars;
1932   Vars.reserve(NumVars);
1933   for (unsigned i = 0; i != NumVars; ++i) {
1934     Vars.push_back(Reader.ReadExpr(F));
1935   }
1936   D->setVars(Vars);
1937 }
1938 
1939 //===----------------------------------------------------------------------===//
1940 // Attribute Reading
1941 //===----------------------------------------------------------------------===//
1942 
1943 /// \brief Reads attributes from the current stream position.
1944 void ASTReader::ReadAttributes(ModuleFile &F, AttrVec &Attrs,
1945                                const RecordData &Record, unsigned &Idx) {
1946   for (unsigned i = 0, e = Record[Idx++]; i != e; ++i) {
1947     Attr *New = 0;
1948     attr::Kind Kind = (attr::Kind)Record[Idx++];
1949     SourceRange Range = ReadSourceRange(F, Record, Idx);
1950 
1951 #include "clang/Serialization/AttrPCHRead.inc"
1952 
1953     assert(New && "Unable to decode attribute?");
1954     Attrs.push_back(New);
1955   }
1956 }
1957 
1958 //===----------------------------------------------------------------------===//
1959 // ASTReader Implementation
1960 //===----------------------------------------------------------------------===//
1961 
1962 /// \brief Note that we have loaded the declaration with the given
1963 /// Index.
1964 ///
1965 /// This routine notes that this declaration has already been loaded,
1966 /// so that future GetDecl calls will return this declaration rather
1967 /// than trying to load a new declaration.
1968 inline void ASTReader::LoadedDecl(unsigned Index, Decl *D) {
1969   assert(!DeclsLoaded[Index] && "Decl loaded twice?");
1970   DeclsLoaded[Index] = D;
1971 }
1972 
1973 
1974 /// \brief Determine whether the consumer will be interested in seeing
1975 /// this declaration (via HandleTopLevelDecl).
1976 ///
1977 /// This routine should return true for anything that might affect
1978 /// code generation, e.g., inline function definitions, Objective-C
1979 /// declarations with metadata, etc.
1980 static bool isConsumerInterestedIn(Decl *D, bool HasBody) {
1981   // An ObjCMethodDecl is never considered as "interesting" because its
1982   // implementation container always is.
1983 
1984   if (isa<FileScopeAsmDecl>(D) ||
1985       isa<ObjCProtocolDecl>(D) ||
1986       isa<ObjCImplDecl>(D))
1987     return true;
1988   if (VarDecl *Var = dyn_cast<VarDecl>(D))
1989     return Var->isFileVarDecl() &&
1990            Var->isThisDeclarationADefinition() == VarDecl::Definition;
1991   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D))
1992     return Func->doesThisDeclarationHaveABody() || HasBody;
1993 
1994   return false;
1995 }
1996 
1997 /// \brief Get the correct cursor and offset for loading a declaration.
1998 ASTReader::RecordLocation
1999 ASTReader::DeclCursorForID(DeclID ID, unsigned &RawLocation) {
2000   // See if there's an override.
2001   DeclReplacementMap::iterator It = ReplacedDecls.find(ID);
2002   if (It != ReplacedDecls.end()) {
2003     RawLocation = It->second.RawLoc;
2004     return RecordLocation(It->second.Mod, It->second.Offset);
2005   }
2006 
2007   GlobalDeclMapType::iterator I = GlobalDeclMap.find(ID);
2008   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
2009   ModuleFile *M = I->second;
2010   const DeclOffset &
2011     DOffs =  M->DeclOffsets[ID - M->BaseDeclID - NUM_PREDEF_DECL_IDS];
2012   RawLocation = DOffs.Loc;
2013   return RecordLocation(M, DOffs.BitOffset);
2014 }
2015 
2016 ASTReader::RecordLocation ASTReader::getLocalBitOffset(uint64_t GlobalOffset) {
2017   ContinuousRangeMap<uint64_t, ModuleFile*, 4>::iterator I
2018     = GlobalBitOffsetsMap.find(GlobalOffset);
2019 
2020   assert(I != GlobalBitOffsetsMap.end() && "Corrupted global bit offsets map");
2021   return RecordLocation(I->second, GlobalOffset - I->second->GlobalBitOffset);
2022 }
2023 
2024 uint64_t ASTReader::getGlobalBitOffset(ModuleFile &M, uint32_t LocalOffset) {
2025   return LocalOffset + M.GlobalBitOffset;
2026 }
2027 
2028 static bool isSameTemplateParameterList(const TemplateParameterList *X,
2029                                         const TemplateParameterList *Y);
2030 
2031 /// \brief Determine whether two template parameters are similar enough
2032 /// that they may be used in declarations of the same template.
2033 static bool isSameTemplateParameter(const NamedDecl *X,
2034                                     const NamedDecl *Y) {
2035   if (X->getKind() != Y->getKind())
2036     return false;
2037 
2038   if (const TemplateTypeParmDecl *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
2039     const TemplateTypeParmDecl *TY = cast<TemplateTypeParmDecl>(Y);
2040     return TX->isParameterPack() == TY->isParameterPack();
2041   }
2042 
2043   if (const NonTypeTemplateParmDecl *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
2044     const NonTypeTemplateParmDecl *TY = cast<NonTypeTemplateParmDecl>(Y);
2045     return TX->isParameterPack() == TY->isParameterPack() &&
2046            TX->getASTContext().hasSameType(TX->getType(), TY->getType());
2047   }
2048 
2049   const TemplateTemplateParmDecl *TX = cast<TemplateTemplateParmDecl>(X);
2050   const TemplateTemplateParmDecl *TY = cast<TemplateTemplateParmDecl>(Y);
2051   return TX->isParameterPack() == TY->isParameterPack() &&
2052          isSameTemplateParameterList(TX->getTemplateParameters(),
2053                                      TY->getTemplateParameters());
2054 }
2055 
2056 /// \brief Determine whether two template parameter lists are similar enough
2057 /// that they may be used in declarations of the same template.
2058 static bool isSameTemplateParameterList(const TemplateParameterList *X,
2059                                         const TemplateParameterList *Y) {
2060   if (X->size() != Y->size())
2061     return false;
2062 
2063   for (unsigned I = 0, N = X->size(); I != N; ++I)
2064     if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
2065       return false;
2066 
2067   return true;
2068 }
2069 
2070 /// \brief Determine whether the two declarations refer to the same entity.
2071 static bool isSameEntity(NamedDecl *X, NamedDecl *Y) {
2072   assert(X->getDeclName() == Y->getDeclName() && "Declaration name mismatch!");
2073 
2074   if (X == Y)
2075     return true;
2076 
2077   // Must be in the same context.
2078   if (!X->getDeclContext()->getRedeclContext()->Equals(
2079          Y->getDeclContext()->getRedeclContext()))
2080     return false;
2081 
2082   // Two typedefs refer to the same entity if they have the same underlying
2083   // type.
2084   if (TypedefNameDecl *TypedefX = dyn_cast<TypedefNameDecl>(X))
2085     if (TypedefNameDecl *TypedefY = dyn_cast<TypedefNameDecl>(Y))
2086       return X->getASTContext().hasSameType(TypedefX->getUnderlyingType(),
2087                                             TypedefY->getUnderlyingType());
2088 
2089   // Must have the same kind.
2090   if (X->getKind() != Y->getKind())
2091     return false;
2092 
2093   // Objective-C classes and protocols with the same name always match.
2094   if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
2095     return true;
2096 
2097   if (isa<ClassTemplateSpecializationDecl>(X)) {
2098     // No need to handle these here: we merge them when adding them to the
2099     // template.
2100     return false;
2101   }
2102 
2103   // Compatible tags match.
2104   if (TagDecl *TagX = dyn_cast<TagDecl>(X)) {
2105     TagDecl *TagY = cast<TagDecl>(Y);
2106     return (TagX->getTagKind() == TagY->getTagKind()) ||
2107       ((TagX->getTagKind() == TTK_Struct || TagX->getTagKind() == TTK_Class ||
2108         TagX->getTagKind() == TTK_Interface) &&
2109        (TagY->getTagKind() == TTK_Struct || TagY->getTagKind() == TTK_Class ||
2110         TagY->getTagKind() == TTK_Interface));
2111   }
2112 
2113   // Functions with the same type and linkage match.
2114   // FIXME: This needs to cope with function template specializations,
2115   // merging of prototyped/non-prototyped functions, etc.
2116   if (FunctionDecl *FuncX = dyn_cast<FunctionDecl>(X)) {
2117     FunctionDecl *FuncY = cast<FunctionDecl>(Y);
2118     return (FuncX->getLinkageInternal() == FuncY->getLinkageInternal()) &&
2119       FuncX->getASTContext().hasSameType(FuncX->getType(), FuncY->getType());
2120   }
2121 
2122   // Variables with the same type and linkage match.
2123   if (VarDecl *VarX = dyn_cast<VarDecl>(X)) {
2124     VarDecl *VarY = cast<VarDecl>(Y);
2125     return (VarX->getLinkageInternal() == VarY->getLinkageInternal()) &&
2126       VarX->getASTContext().hasSameType(VarX->getType(), VarY->getType());
2127   }
2128 
2129   // Namespaces with the same name and inlinedness match.
2130   if (NamespaceDecl *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
2131     NamespaceDecl *NamespaceY = cast<NamespaceDecl>(Y);
2132     return NamespaceX->isInline() == NamespaceY->isInline();
2133   }
2134 
2135   // Identical template names and kinds match if their template parameter lists
2136   // and patterns match.
2137   if (TemplateDecl *TemplateX = dyn_cast<TemplateDecl>(X)) {
2138     TemplateDecl *TemplateY = cast<TemplateDecl>(Y);
2139     return isSameEntity(TemplateX->getTemplatedDecl(),
2140                         TemplateY->getTemplatedDecl()) &&
2141            isSameTemplateParameterList(TemplateX->getTemplateParameters(),
2142                                        TemplateY->getTemplateParameters());
2143   }
2144 
2145   // Fields with the same name and the same type match.
2146   if (FieldDecl *FDX = dyn_cast<FieldDecl>(X)) {
2147     FieldDecl *FDY = cast<FieldDecl>(Y);
2148     // FIXME: Diagnose if the types don't match. More generally, diagnose if we
2149     // get a declaration in a class definition that isn't in the canonical class
2150     // definition.
2151     // FIXME: Also check the bitwidth is odr-equivalent, if any.
2152     return X->getASTContext().hasSameType(FDX->getType(), FDY->getType());
2153   }
2154 
2155   // Enumerators with the same name match.
2156   if (isa<EnumConstantDecl>(X))
2157     // FIXME: Also check the value is odr-equivalent.
2158     return true;
2159 
2160   // Using shadow declarations with the same target match.
2161   if (UsingShadowDecl *USX = dyn_cast<UsingShadowDecl>(X)) {
2162     UsingShadowDecl *USY = cast<UsingShadowDecl>(Y);
2163     return USX->getTargetDecl() == USY->getTargetDecl();
2164   }
2165 
2166   // FIXME: Many other cases to implement.
2167   return false;
2168 }
2169 
2170 /// Find the context in which we should search for previous declarations when
2171 /// looking for declarations to merge.
2172 static DeclContext *getPrimaryContextForMerging(DeclContext *DC) {
2173   if (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
2174     return ND->getOriginalNamespace();
2175 
2176   if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
2177     return RD->getDefinition();
2178 
2179   if (EnumDecl *ED = dyn_cast<EnumDecl>(DC))
2180     return ED->getASTContext().getLangOpts().CPlusPlus? ED->getDefinition() : 0;
2181 
2182   return 0;
2183 }
2184 
2185 ASTDeclReader::FindExistingResult::~FindExistingResult() {
2186   if (!AddResult || Existing)
2187     return;
2188 
2189   DeclContext *DC = New->getDeclContext()->getRedeclContext();
2190   if (DC->isTranslationUnit() && Reader.SemaObj) {
2191     Reader.SemaObj->IdResolver.tryAddTopLevelDecl(New, New->getDeclName());
2192   } else if (DeclContext *MergeDC = getPrimaryContextForMerging(DC)) {
2193     // Add the declaration to its redeclaration context so later merging
2194     // lookups will find it.
2195     MergeDC->makeDeclVisibleInContextImpl(New, /*Internal*/true);
2196   }
2197 }
2198 
2199 ASTDeclReader::FindExistingResult ASTDeclReader::findExisting(NamedDecl *D) {
2200   DeclarationName Name = D->getDeclName();
2201   if (!Name) {
2202     // Don't bother trying to find unnamed declarations.
2203     FindExistingResult Result(Reader, D, /*Existing=*/0);
2204     Result.suppress();
2205     return Result;
2206   }
2207 
2208   // FIXME: Bail out for non-canonical declarations. We will have performed any
2209   // necessary merging already.
2210 
2211   DeclContext *DC = D->getDeclContext()->getRedeclContext();
2212   if (DC->isTranslationUnit() && Reader.SemaObj) {
2213     IdentifierResolver &IdResolver = Reader.SemaObj->IdResolver;
2214 
2215     // Temporarily consider the identifier to be up-to-date. We don't want to
2216     // cause additional lookups here.
2217     class UpToDateIdentifierRAII {
2218       IdentifierInfo *II;
2219       bool WasOutToDate;
2220 
2221     public:
2222       explicit UpToDateIdentifierRAII(IdentifierInfo *II)
2223         : II(II), WasOutToDate(false)
2224       {
2225         if (II) {
2226           WasOutToDate = II->isOutOfDate();
2227           if (WasOutToDate)
2228             II->setOutOfDate(false);
2229         }
2230       }
2231 
2232       ~UpToDateIdentifierRAII() {
2233         if (WasOutToDate)
2234           II->setOutOfDate(true);
2235       }
2236     } UpToDate(Name.getAsIdentifierInfo());
2237 
2238     for (IdentifierResolver::iterator I = IdResolver.begin(Name),
2239                                    IEnd = IdResolver.end();
2240          I != IEnd; ++I) {
2241       if (isSameEntity(*I, D))
2242         return FindExistingResult(Reader, D, *I);
2243     }
2244   } else if (DeclContext *MergeDC = getPrimaryContextForMerging(DC)) {
2245     DeclContext::lookup_result R = MergeDC->noload_lookup(Name);
2246     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
2247       if (isSameEntity(*I, D))
2248         return FindExistingResult(Reader, D, *I);
2249     }
2250   } else {
2251     // Not in a mergeable context.
2252     return FindExistingResult(Reader);
2253   }
2254 
2255   // If this declaration is from a merged context, make a note that we need to
2256   // check that the canonical definition of that context contains the decl.
2257   if (Reader.MergedDeclContexts.count(D->getLexicalDeclContext()))
2258     Reader.PendingOdrMergeChecks.push_back(D);
2259 
2260   return FindExistingResult(Reader, D, /*Existing=*/0);
2261 }
2262 
2263 void ASTDeclReader::attachPreviousDecl(Decl *D, Decl *previous) {
2264   assert(D && previous);
2265   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2266     TD->RedeclLink.setNext(cast<TagDecl>(previous));
2267   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2268     FD->RedeclLink.setNext(cast<FunctionDecl>(previous));
2269   } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2270     VD->RedeclLink.setNext(cast<VarDecl>(previous));
2271   } else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2272     TD->RedeclLink.setNext(cast<TypedefNameDecl>(previous));
2273   } else if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D)) {
2274     USD->RedeclLink.setNext(cast<UsingShadowDecl>(previous));
2275   } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
2276     ID->RedeclLink.setNext(cast<ObjCInterfaceDecl>(previous));
2277   } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
2278     PD->RedeclLink.setNext(cast<ObjCProtocolDecl>(previous));
2279   } else if (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(D)) {
2280     ND->RedeclLink.setNext(cast<NamespaceDecl>(previous));
2281   } else {
2282     RedeclarableTemplateDecl *TD = cast<RedeclarableTemplateDecl>(D);
2283     TD->RedeclLink.setNext(cast<RedeclarableTemplateDecl>(previous));
2284   }
2285 
2286   // If the declaration was visible in one module, a redeclaration of it in
2287   // another module remains visible even if it wouldn't be visible by itself.
2288   //
2289   // FIXME: In this case, the declaration should only be visible if a module
2290   //        that makes it visible has been imported.
2291   D->IdentifierNamespace |=
2292       previous->IdentifierNamespace &
2293       (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
2294 }
2295 
2296 void ASTDeclReader::attachLatestDecl(Decl *D, Decl *Latest) {
2297   assert(D && Latest);
2298   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2299     TD->RedeclLink
2300       = Redeclarable<TagDecl>::LatestDeclLink(cast<TagDecl>(Latest));
2301   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2302     FD->RedeclLink
2303       = Redeclarable<FunctionDecl>::LatestDeclLink(cast<FunctionDecl>(Latest));
2304   } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2305     VD->RedeclLink
2306       = Redeclarable<VarDecl>::LatestDeclLink(cast<VarDecl>(Latest));
2307   } else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2308     TD->RedeclLink
2309       = Redeclarable<TypedefNameDecl>::LatestDeclLink(
2310                                                 cast<TypedefNameDecl>(Latest));
2311   } else if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D)) {
2312     USD->RedeclLink
2313       = Redeclarable<UsingShadowDecl>::LatestDeclLink(
2314                                              cast<UsingShadowDecl>(Latest));
2315   } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
2316     ID->RedeclLink
2317       = Redeclarable<ObjCInterfaceDecl>::LatestDeclLink(
2318                                               cast<ObjCInterfaceDecl>(Latest));
2319   } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
2320     PD->RedeclLink
2321       = Redeclarable<ObjCProtocolDecl>::LatestDeclLink(
2322                                                 cast<ObjCProtocolDecl>(Latest));
2323   } else if (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(D)) {
2324     ND->RedeclLink
2325       = Redeclarable<NamespaceDecl>::LatestDeclLink(
2326                                                    cast<NamespaceDecl>(Latest));
2327   } else {
2328     RedeclarableTemplateDecl *TD = cast<RedeclarableTemplateDecl>(D);
2329     TD->RedeclLink
2330       = Redeclarable<RedeclarableTemplateDecl>::LatestDeclLink(
2331                                         cast<RedeclarableTemplateDecl>(Latest));
2332   }
2333 }
2334 
2335 ASTReader::MergedDeclsMap::iterator
2336 ASTReader::combineStoredMergedDecls(Decl *Canon, GlobalDeclID CanonID) {
2337   // If we don't have any stored merged declarations, just look in the
2338   // merged declarations set.
2339   StoredMergedDeclsMap::iterator StoredPos = StoredMergedDecls.find(CanonID);
2340   if (StoredPos == StoredMergedDecls.end())
2341     return MergedDecls.find(Canon);
2342 
2343   // Append the stored merged declarations to the merged declarations set.
2344   MergedDeclsMap::iterator Pos = MergedDecls.find(Canon);
2345   if (Pos == MergedDecls.end())
2346     Pos = MergedDecls.insert(std::make_pair(Canon,
2347                                             SmallVector<DeclID, 2>())).first;
2348   Pos->second.append(StoredPos->second.begin(), StoredPos->second.end());
2349   StoredMergedDecls.erase(StoredPos);
2350 
2351   // Sort and uniquify the set of merged declarations.
2352   llvm::array_pod_sort(Pos->second.begin(), Pos->second.end());
2353   Pos->second.erase(std::unique(Pos->second.begin(), Pos->second.end()),
2354                     Pos->second.end());
2355   return Pos;
2356 }
2357 
2358 /// \brief Read the declaration at the given offset from the AST file.
2359 Decl *ASTReader::ReadDeclRecord(DeclID ID) {
2360   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
2361   unsigned RawLocation = 0;
2362   RecordLocation Loc = DeclCursorForID(ID, RawLocation);
2363   llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
2364   // Keep track of where we are in the stream, then jump back there
2365   // after reading this declaration.
2366   SavedStreamPosition SavedPosition(DeclsCursor);
2367 
2368   ReadingKindTracker ReadingKind(Read_Decl, *this);
2369 
2370   // Note that we are loading a declaration record.
2371   Deserializing ADecl(this);
2372 
2373   DeclsCursor.JumpToBit(Loc.Offset);
2374   RecordData Record;
2375   unsigned Code = DeclsCursor.ReadCode();
2376   unsigned Idx = 0;
2377   ASTDeclReader Reader(*this, *Loc.F, ID, RawLocation, Record,Idx);
2378 
2379   Decl *D = 0;
2380   switch ((DeclCode)DeclsCursor.readRecord(Code, Record)) {
2381   case DECL_CONTEXT_LEXICAL:
2382   case DECL_CONTEXT_VISIBLE:
2383     llvm_unreachable("Record cannot be de-serialized with ReadDeclRecord");
2384   case DECL_TYPEDEF:
2385     D = TypedefDecl::CreateDeserialized(Context, ID);
2386     break;
2387   case DECL_TYPEALIAS:
2388     D = TypeAliasDecl::CreateDeserialized(Context, ID);
2389     break;
2390   case DECL_ENUM:
2391     D = EnumDecl::CreateDeserialized(Context, ID);
2392     break;
2393   case DECL_RECORD:
2394     D = RecordDecl::CreateDeserialized(Context, ID);
2395     break;
2396   case DECL_ENUM_CONSTANT:
2397     D = EnumConstantDecl::CreateDeserialized(Context, ID);
2398     break;
2399   case DECL_FUNCTION:
2400     D = FunctionDecl::CreateDeserialized(Context, ID);
2401     break;
2402   case DECL_LINKAGE_SPEC:
2403     D = LinkageSpecDecl::CreateDeserialized(Context, ID);
2404     break;
2405   case DECL_LABEL:
2406     D = LabelDecl::CreateDeserialized(Context, ID);
2407     break;
2408   case DECL_NAMESPACE:
2409     D = NamespaceDecl::CreateDeserialized(Context, ID);
2410     break;
2411   case DECL_NAMESPACE_ALIAS:
2412     D = NamespaceAliasDecl::CreateDeserialized(Context, ID);
2413     break;
2414   case DECL_USING:
2415     D = UsingDecl::CreateDeserialized(Context, ID);
2416     break;
2417   case DECL_USING_SHADOW:
2418     D = UsingShadowDecl::CreateDeserialized(Context, ID);
2419     break;
2420   case DECL_USING_DIRECTIVE:
2421     D = UsingDirectiveDecl::CreateDeserialized(Context, ID);
2422     break;
2423   case DECL_UNRESOLVED_USING_VALUE:
2424     D = UnresolvedUsingValueDecl::CreateDeserialized(Context, ID);
2425     break;
2426   case DECL_UNRESOLVED_USING_TYPENAME:
2427     D = UnresolvedUsingTypenameDecl::CreateDeserialized(Context, ID);
2428     break;
2429   case DECL_CXX_RECORD:
2430     D = CXXRecordDecl::CreateDeserialized(Context, ID);
2431     break;
2432   case DECL_CXX_METHOD:
2433     D = CXXMethodDecl::CreateDeserialized(Context, ID);
2434     break;
2435   case DECL_CXX_CONSTRUCTOR:
2436     D = CXXConstructorDecl::CreateDeserialized(Context, ID);
2437     break;
2438   case DECL_CXX_DESTRUCTOR:
2439     D = CXXDestructorDecl::CreateDeserialized(Context, ID);
2440     break;
2441   case DECL_CXX_CONVERSION:
2442     D = CXXConversionDecl::CreateDeserialized(Context, ID);
2443     break;
2444   case DECL_ACCESS_SPEC:
2445     D = AccessSpecDecl::CreateDeserialized(Context, ID);
2446     break;
2447   case DECL_FRIEND:
2448     D = FriendDecl::CreateDeserialized(Context, ID, Record[Idx++]);
2449     break;
2450   case DECL_FRIEND_TEMPLATE:
2451     D = FriendTemplateDecl::CreateDeserialized(Context, ID);
2452     break;
2453   case DECL_CLASS_TEMPLATE:
2454     D = ClassTemplateDecl::CreateDeserialized(Context, ID);
2455     break;
2456   case DECL_CLASS_TEMPLATE_SPECIALIZATION:
2457     D = ClassTemplateSpecializationDecl::CreateDeserialized(Context, ID);
2458     break;
2459   case DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION:
2460     D = ClassTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
2461     break;
2462   case DECL_VAR_TEMPLATE:
2463     D = VarTemplateDecl::CreateDeserialized(Context, ID);
2464     break;
2465   case DECL_VAR_TEMPLATE_SPECIALIZATION:
2466     D = VarTemplateSpecializationDecl::CreateDeserialized(Context, ID);
2467     break;
2468   case DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION:
2469     D = VarTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
2470     break;
2471   case DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION:
2472     D = ClassScopeFunctionSpecializationDecl::CreateDeserialized(Context, ID);
2473     break;
2474   case DECL_FUNCTION_TEMPLATE:
2475     D = FunctionTemplateDecl::CreateDeserialized(Context, ID);
2476     break;
2477   case DECL_TEMPLATE_TYPE_PARM:
2478     D = TemplateTypeParmDecl::CreateDeserialized(Context, ID);
2479     break;
2480   case DECL_NON_TYPE_TEMPLATE_PARM:
2481     D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID);
2482     break;
2483   case DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK:
2484     D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID, Record[Idx++]);
2485     break;
2486   case DECL_TEMPLATE_TEMPLATE_PARM:
2487     D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID);
2488     break;
2489   case DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK:
2490     D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID,
2491                                                      Record[Idx++]);
2492     break;
2493   case DECL_TYPE_ALIAS_TEMPLATE:
2494     D = TypeAliasTemplateDecl::CreateDeserialized(Context, ID);
2495     break;
2496   case DECL_STATIC_ASSERT:
2497     D = StaticAssertDecl::CreateDeserialized(Context, ID);
2498     break;
2499   case DECL_OBJC_METHOD:
2500     D = ObjCMethodDecl::CreateDeserialized(Context, ID);
2501     break;
2502   case DECL_OBJC_INTERFACE:
2503     D = ObjCInterfaceDecl::CreateDeserialized(Context, ID);
2504     break;
2505   case DECL_OBJC_IVAR:
2506     D = ObjCIvarDecl::CreateDeserialized(Context, ID);
2507     break;
2508   case DECL_OBJC_PROTOCOL:
2509     D = ObjCProtocolDecl::CreateDeserialized(Context, ID);
2510     break;
2511   case DECL_OBJC_AT_DEFS_FIELD:
2512     D = ObjCAtDefsFieldDecl::CreateDeserialized(Context, ID);
2513     break;
2514   case DECL_OBJC_CATEGORY:
2515     D = ObjCCategoryDecl::CreateDeserialized(Context, ID);
2516     break;
2517   case DECL_OBJC_CATEGORY_IMPL:
2518     D = ObjCCategoryImplDecl::CreateDeserialized(Context, ID);
2519     break;
2520   case DECL_OBJC_IMPLEMENTATION:
2521     D = ObjCImplementationDecl::CreateDeserialized(Context, ID);
2522     break;
2523   case DECL_OBJC_COMPATIBLE_ALIAS:
2524     D = ObjCCompatibleAliasDecl::CreateDeserialized(Context, ID);
2525     break;
2526   case DECL_OBJC_PROPERTY:
2527     D = ObjCPropertyDecl::CreateDeserialized(Context, ID);
2528     break;
2529   case DECL_OBJC_PROPERTY_IMPL:
2530     D = ObjCPropertyImplDecl::CreateDeserialized(Context, ID);
2531     break;
2532   case DECL_FIELD:
2533     D = FieldDecl::CreateDeserialized(Context, ID);
2534     break;
2535   case DECL_INDIRECTFIELD:
2536     D = IndirectFieldDecl::CreateDeserialized(Context, ID);
2537     break;
2538   case DECL_VAR:
2539     D = VarDecl::CreateDeserialized(Context, ID);
2540     break;
2541   case DECL_IMPLICIT_PARAM:
2542     D = ImplicitParamDecl::CreateDeserialized(Context, ID);
2543     break;
2544   case DECL_PARM_VAR:
2545     D = ParmVarDecl::CreateDeserialized(Context, ID);
2546     break;
2547   case DECL_FILE_SCOPE_ASM:
2548     D = FileScopeAsmDecl::CreateDeserialized(Context, ID);
2549     break;
2550   case DECL_BLOCK:
2551     D = BlockDecl::CreateDeserialized(Context, ID);
2552     break;
2553   case DECL_MS_PROPERTY:
2554     D = MSPropertyDecl::CreateDeserialized(Context, ID);
2555     break;
2556   case DECL_CAPTURED:
2557     D = CapturedDecl::CreateDeserialized(Context, ID, Record[Idx++]);
2558     break;
2559   case DECL_CXX_BASE_SPECIFIERS:
2560     Error("attempt to read a C++ base-specifier record as a declaration");
2561     return 0;
2562   case DECL_IMPORT:
2563     // Note: last entry of the ImportDecl record is the number of stored source
2564     // locations.
2565     D = ImportDecl::CreateDeserialized(Context, ID, Record.back());
2566     break;
2567   case DECL_OMP_THREADPRIVATE:
2568     D = OMPThreadPrivateDecl::CreateDeserialized(Context, ID, Record[Idx++]);
2569     break;
2570   case DECL_EMPTY:
2571     D = EmptyDecl::CreateDeserialized(Context, ID);
2572     break;
2573   }
2574 
2575   assert(D && "Unknown declaration reading AST file");
2576   LoadedDecl(Index, D);
2577   // Set the DeclContext before doing any deserialization, to make sure internal
2578   // calls to Decl::getASTContext() by Decl's methods will find the
2579   // TranslationUnitDecl without crashing.
2580   D->setDeclContext(Context.getTranslationUnitDecl());
2581   Reader.Visit(D);
2582 
2583   // If this declaration is also a declaration context, get the
2584   // offsets for its tables of lexical and visible declarations.
2585   if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
2586     // FIXME: This should really be
2587     //     DeclContext *LookupDC = DC->getPrimaryContext();
2588     // but that can walk the redeclaration chain, which might not work yet.
2589     DeclContext *LookupDC = DC;
2590     if (isa<NamespaceDecl>(DC))
2591       LookupDC = DC->getPrimaryContext();
2592     std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
2593     if (Offsets.first || Offsets.second) {
2594       if (Offsets.first != 0)
2595         DC->setHasExternalLexicalStorage(true);
2596       if (Offsets.second != 0)
2597         LookupDC->setHasExternalVisibleStorage(true);
2598       if (ReadDeclContextStorage(*Loc.F, DeclsCursor, Offsets,
2599                                  Loc.F->DeclContextInfos[DC]))
2600         return 0;
2601     }
2602 
2603     // Now add the pending visible updates for this decl context, if it has any.
2604     DeclContextVisibleUpdatesPending::iterator I =
2605         PendingVisibleUpdates.find(ID);
2606     if (I != PendingVisibleUpdates.end()) {
2607       // There are updates. This means the context has external visible
2608       // storage, even if the original stored version didn't.
2609       LookupDC->setHasExternalVisibleStorage(true);
2610       DeclContextVisibleUpdates &U = I->second;
2611       for (DeclContextVisibleUpdates::iterator UI = U.begin(), UE = U.end();
2612            UI != UE; ++UI) {
2613         DeclContextInfo &Info = UI->second->DeclContextInfos[DC];
2614         delete Info.NameLookupTableData;
2615         Info.NameLookupTableData = UI->first;
2616       }
2617       PendingVisibleUpdates.erase(I);
2618     }
2619   }
2620   assert(Idx == Record.size());
2621 
2622   // Load any relevant update records.
2623   loadDeclUpdateRecords(ID, D);
2624 
2625   // Load the categories after recursive loading is finished.
2626   if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
2627     if (Class->isThisDeclarationADefinition())
2628       loadObjCCategories(ID, Class);
2629 
2630   // If we have deserialized a declaration that has a definition the
2631   // AST consumer might need to know about, queue it.
2632   // We don't pass it to the consumer immediately because we may be in recursive
2633   // loading, and some declarations may still be initializing.
2634   if (isConsumerInterestedIn(D, Reader.hasPendingBody()))
2635     InterestingDecls.push_back(D);
2636 
2637   return D;
2638 }
2639 
2640 void ASTReader::loadDeclUpdateRecords(serialization::DeclID ID, Decl *D) {
2641   // The declaration may have been modified by files later in the chain.
2642   // If this is the case, read the record containing the updates from each file
2643   // and pass it to ASTDeclReader to make the modifications.
2644   DeclUpdateOffsetsMap::iterator UpdI = DeclUpdateOffsets.find(ID);
2645   if (UpdI != DeclUpdateOffsets.end()) {
2646     FileOffsetsTy &UpdateOffsets = UpdI->second;
2647     for (FileOffsetsTy::iterator
2648          I = UpdateOffsets.begin(), E = UpdateOffsets.end(); I != E; ++I) {
2649       ModuleFile *F = I->first;
2650       uint64_t Offset = I->second;
2651       llvm::BitstreamCursor &Cursor = F->DeclsCursor;
2652       SavedStreamPosition SavedPosition(Cursor);
2653       Cursor.JumpToBit(Offset);
2654       RecordData Record;
2655       unsigned Code = Cursor.ReadCode();
2656       unsigned RecCode = Cursor.readRecord(Code, Record);
2657       (void)RecCode;
2658       assert(RecCode == DECL_UPDATES && "Expected DECL_UPDATES record!");
2659 
2660       unsigned Idx = 0;
2661       ASTDeclReader Reader(*this, *F, ID, 0, Record, Idx);
2662       Reader.UpdateDecl(D, *F, Record);
2663     }
2664   }
2665 }
2666 
2667 namespace {
2668   struct CompareLocalRedeclarationsInfoToID {
2669     bool operator()(const LocalRedeclarationsInfo &X, DeclID Y) {
2670       return X.FirstID < Y;
2671     }
2672 
2673     bool operator()(DeclID X, const LocalRedeclarationsInfo &Y) {
2674       return X < Y.FirstID;
2675     }
2676 
2677     bool operator()(const LocalRedeclarationsInfo &X,
2678                     const LocalRedeclarationsInfo &Y) {
2679       return X.FirstID < Y.FirstID;
2680     }
2681     bool operator()(DeclID X, DeclID Y) {
2682       return X < Y;
2683     }
2684   };
2685 
2686   /// \brief Module visitor class that finds all of the redeclarations of a
2687   ///
2688   class RedeclChainVisitor {
2689     ASTReader &Reader;
2690     SmallVectorImpl<DeclID> &SearchDecls;
2691     llvm::SmallPtrSet<Decl *, 16> &Deserialized;
2692     GlobalDeclID CanonID;
2693     SmallVector<Decl *, 4> Chain;
2694 
2695   public:
2696     RedeclChainVisitor(ASTReader &Reader, SmallVectorImpl<DeclID> &SearchDecls,
2697                        llvm::SmallPtrSet<Decl *, 16> &Deserialized,
2698                        GlobalDeclID CanonID)
2699       : Reader(Reader), SearchDecls(SearchDecls), Deserialized(Deserialized),
2700         CanonID(CanonID) {
2701       for (unsigned I = 0, N = SearchDecls.size(); I != N; ++I)
2702         addToChain(Reader.GetDecl(SearchDecls[I]));
2703     }
2704 
2705     static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
2706       if (Preorder)
2707         return false;
2708 
2709       return static_cast<RedeclChainVisitor *>(UserData)->visit(M);
2710     }
2711 
2712     void addToChain(Decl *D) {
2713       if (!D)
2714         return;
2715 
2716       if (Deserialized.erase(D))
2717         Chain.push_back(D);
2718     }
2719 
2720     void searchForID(ModuleFile &M, GlobalDeclID GlobalID) {
2721       // Map global ID of the first declaration down to the local ID
2722       // used in this module file.
2723       DeclID ID = Reader.mapGlobalIDToModuleFileGlobalID(M, GlobalID);
2724       if (!ID)
2725         return;
2726 
2727       // Perform a binary search to find the local redeclarations for this
2728       // declaration (if any).
2729       const LocalRedeclarationsInfo *Result
2730         = std::lower_bound(M.RedeclarationsMap,
2731                            M.RedeclarationsMap + M.LocalNumRedeclarationsInMap,
2732                            ID, CompareLocalRedeclarationsInfoToID());
2733       if (Result == M.RedeclarationsMap + M.LocalNumRedeclarationsInMap ||
2734           Result->FirstID != ID) {
2735         // If we have a previously-canonical singleton declaration that was
2736         // merged into another redeclaration chain, create a trivial chain
2737         // for this single declaration so that it will get wired into the
2738         // complete redeclaration chain.
2739         if (GlobalID != CanonID &&
2740             GlobalID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
2741             GlobalID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls) {
2742           addToChain(Reader.GetDecl(GlobalID));
2743         }
2744 
2745         return;
2746       }
2747 
2748       // Dig out all of the redeclarations.
2749       unsigned Offset = Result->Offset;
2750       unsigned N = M.RedeclarationChains[Offset];
2751       M.RedeclarationChains[Offset++] = 0; // Don't try to deserialize again
2752       for (unsigned I = 0; I != N; ++I)
2753         addToChain(Reader.GetLocalDecl(M, M.RedeclarationChains[Offset++]));
2754     }
2755 
2756     bool visit(ModuleFile &M) {
2757       // Visit each of the declarations.
2758       for (unsigned I = 0, N = SearchDecls.size(); I != N; ++I)
2759         searchForID(M, SearchDecls[I]);
2760       return false;
2761     }
2762 
2763     ArrayRef<Decl *> getChain() const {
2764       return Chain;
2765     }
2766   };
2767 }
2768 
2769 void ASTReader::loadPendingDeclChain(serialization::GlobalDeclID ID) {
2770   Decl *D = GetDecl(ID);
2771   Decl *CanonDecl = D->getCanonicalDecl();
2772 
2773   // Determine the set of declaration IDs we'll be searching for.
2774   SmallVector<DeclID, 1> SearchDecls;
2775   GlobalDeclID CanonID = 0;
2776   if (D == CanonDecl) {
2777     SearchDecls.push_back(ID); // Always first.
2778     CanonID = ID;
2779   }
2780   MergedDeclsMap::iterator MergedPos = combineStoredMergedDecls(CanonDecl, ID);
2781   if (MergedPos != MergedDecls.end())
2782     SearchDecls.append(MergedPos->second.begin(), MergedPos->second.end());
2783 
2784   // Build up the list of redeclarations.
2785   RedeclChainVisitor Visitor(*this, SearchDecls, RedeclsDeserialized, CanonID);
2786   ModuleMgr.visitDepthFirst(&RedeclChainVisitor::visit, &Visitor);
2787 
2788   // Retrieve the chains.
2789   ArrayRef<Decl *> Chain = Visitor.getChain();
2790   if (Chain.empty())
2791     return;
2792 
2793   // Hook up the chains.
2794   Decl *MostRecent = CanonDecl->getMostRecentDecl();
2795   for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2796     if (Chain[I] == CanonDecl)
2797       continue;
2798 
2799     ASTDeclReader::attachPreviousDecl(Chain[I], MostRecent);
2800     MostRecent = Chain[I];
2801   }
2802 
2803   ASTDeclReader::attachLatestDecl(CanonDecl, MostRecent);
2804 }
2805 
2806 namespace {
2807   struct CompareObjCCategoriesInfo {
2808     bool operator()(const ObjCCategoriesInfo &X, DeclID Y) {
2809       return X.DefinitionID < Y;
2810     }
2811 
2812     bool operator()(DeclID X, const ObjCCategoriesInfo &Y) {
2813       return X < Y.DefinitionID;
2814     }
2815 
2816     bool operator()(const ObjCCategoriesInfo &X,
2817                     const ObjCCategoriesInfo &Y) {
2818       return X.DefinitionID < Y.DefinitionID;
2819     }
2820     bool operator()(DeclID X, DeclID Y) {
2821       return X < Y;
2822     }
2823   };
2824 
2825   /// \brief Given an ObjC interface, goes through the modules and links to the
2826   /// interface all the categories for it.
2827   class ObjCCategoriesVisitor {
2828     ASTReader &Reader;
2829     serialization::GlobalDeclID InterfaceID;
2830     ObjCInterfaceDecl *Interface;
2831     llvm::SmallPtrSet<ObjCCategoryDecl *, 16> &Deserialized;
2832     unsigned PreviousGeneration;
2833     ObjCCategoryDecl *Tail;
2834     llvm::DenseMap<DeclarationName, ObjCCategoryDecl *> NameCategoryMap;
2835 
2836     void add(ObjCCategoryDecl *Cat) {
2837       // Only process each category once.
2838       if (!Deserialized.erase(Cat))
2839         return;
2840 
2841       // Check for duplicate categories.
2842       if (Cat->getDeclName()) {
2843         ObjCCategoryDecl *&Existing = NameCategoryMap[Cat->getDeclName()];
2844         if (Existing &&
2845             Reader.getOwningModuleFile(Existing)
2846                                           != Reader.getOwningModuleFile(Cat)) {
2847           // FIXME: We should not warn for duplicates in diamond:
2848           //
2849           //   MT     //
2850           //  /  \    //
2851           // ML  MR   //
2852           //  \  /    //
2853           //   MB     //
2854           //
2855           // If there are duplicates in ML/MR, there will be warning when
2856           // creating MB *and* when importing MB. We should not warn when
2857           // importing.
2858           Reader.Diag(Cat->getLocation(), diag::warn_dup_category_def)
2859             << Interface->getDeclName() << Cat->getDeclName();
2860           Reader.Diag(Existing->getLocation(), diag::note_previous_definition);
2861         } else if (!Existing) {
2862           // Record this category.
2863           Existing = Cat;
2864         }
2865       }
2866 
2867       // Add this category to the end of the chain.
2868       if (Tail)
2869         ASTDeclReader::setNextObjCCategory(Tail, Cat);
2870       else
2871         Interface->setCategoryListRaw(Cat);
2872       Tail = Cat;
2873     }
2874 
2875   public:
2876     ObjCCategoriesVisitor(ASTReader &Reader,
2877                           serialization::GlobalDeclID InterfaceID,
2878                           ObjCInterfaceDecl *Interface,
2879                         llvm::SmallPtrSet<ObjCCategoryDecl *, 16> &Deserialized,
2880                           unsigned PreviousGeneration)
2881       : Reader(Reader), InterfaceID(InterfaceID), Interface(Interface),
2882         Deserialized(Deserialized), PreviousGeneration(PreviousGeneration),
2883         Tail(0)
2884     {
2885       // Populate the name -> category map with the set of known categories.
2886       for (ObjCInterfaceDecl::known_categories_iterator
2887              Cat = Interface->known_categories_begin(),
2888              CatEnd = Interface->known_categories_end();
2889            Cat != CatEnd; ++Cat) {
2890         if (Cat->getDeclName())
2891           NameCategoryMap[Cat->getDeclName()] = *Cat;
2892 
2893         // Keep track of the tail of the category list.
2894         Tail = *Cat;
2895       }
2896     }
2897 
2898     static bool visit(ModuleFile &M, void *UserData) {
2899       return static_cast<ObjCCategoriesVisitor *>(UserData)->visit(M);
2900     }
2901 
2902     bool visit(ModuleFile &M) {
2903       // If we've loaded all of the category information we care about from
2904       // this module file, we're done.
2905       if (M.Generation <= PreviousGeneration)
2906         return true;
2907 
2908       // Map global ID of the definition down to the local ID used in this
2909       // module file. If there is no such mapping, we'll find nothing here
2910       // (or in any module it imports).
2911       DeclID LocalID = Reader.mapGlobalIDToModuleFileGlobalID(M, InterfaceID);
2912       if (!LocalID)
2913         return true;
2914 
2915       // Perform a binary search to find the local redeclarations for this
2916       // declaration (if any).
2917       const ObjCCategoriesInfo *Result
2918         = std::lower_bound(M.ObjCCategoriesMap,
2919                            M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap,
2920                            LocalID, CompareObjCCategoriesInfo());
2921       if (Result == M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap ||
2922           Result->DefinitionID != LocalID) {
2923         // We didn't find anything. If the class definition is in this module
2924         // file, then the module files it depends on cannot have any categories,
2925         // so suppress further lookup.
2926         return Reader.isDeclIDFromModule(InterfaceID, M);
2927       }
2928 
2929       // We found something. Dig out all of the categories.
2930       unsigned Offset = Result->Offset;
2931       unsigned N = M.ObjCCategories[Offset];
2932       M.ObjCCategories[Offset++] = 0; // Don't try to deserialize again
2933       for (unsigned I = 0; I != N; ++I)
2934         add(cast_or_null<ObjCCategoryDecl>(
2935               Reader.GetLocalDecl(M, M.ObjCCategories[Offset++])));
2936       return true;
2937     }
2938   };
2939 }
2940 
2941 void ASTReader::loadObjCCategories(serialization::GlobalDeclID ID,
2942                                    ObjCInterfaceDecl *D,
2943                                    unsigned PreviousGeneration) {
2944   ObjCCategoriesVisitor Visitor(*this, ID, D, CategoriesDeserialized,
2945                                 PreviousGeneration);
2946   ModuleMgr.visit(ObjCCategoriesVisitor::visit, &Visitor);
2947 }
2948 
2949 void ASTDeclReader::UpdateDecl(Decl *D, ModuleFile &ModuleFile,
2950                                const RecordData &Record) {
2951   unsigned Idx = 0;
2952   while (Idx < Record.size()) {
2953     switch ((DeclUpdateKind)Record[Idx++]) {
2954     case UPD_CXX_ADDED_IMPLICIT_MEMBER:
2955       cast<CXXRecordDecl>(D)->addedMember(Reader.ReadDecl(ModuleFile, Record, Idx));
2956       break;
2957 
2958     case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
2959       // It will be added to the template's specializations set when loaded.
2960       (void)Reader.ReadDecl(ModuleFile, Record, Idx);
2961       break;
2962 
2963     case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: {
2964       NamespaceDecl *Anon
2965         = Reader.ReadDeclAs<NamespaceDecl>(ModuleFile, Record, Idx);
2966 
2967       // Each module has its own anonymous namespace, which is disjoint from
2968       // any other module's anonymous namespaces, so don't attach the anonymous
2969       // namespace at all.
2970       if (ModuleFile.Kind != MK_Module) {
2971         if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(D))
2972           TU->setAnonymousNamespace(Anon);
2973         else
2974           cast<NamespaceDecl>(D)->setAnonymousNamespace(Anon);
2975       }
2976       break;
2977     }
2978 
2979     case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER:
2980       cast<VarDecl>(D)->getMemberSpecializationInfo()->setPointOfInstantiation(
2981           Reader.ReadSourceLocation(ModuleFile, Record, Idx));
2982       break;
2983 
2984     case UPD_CXX_DEDUCED_RETURN_TYPE: {
2985       FunctionDecl *FD = cast<FunctionDecl>(D);
2986       Reader.Context.adjustDeducedFunctionResultType(
2987           FD, Reader.readType(ModuleFile, Record, Idx));
2988       break;
2989     }
2990 
2991     case UPD_DECL_MARKED_USED: {
2992       // FIXME: This doesn't send the right notifications if there are
2993       // ASTMutationListeners other than an ASTWriter.
2994       D->Used = true;
2995       break;
2996     }
2997     }
2998   }
2999 }
3000