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