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