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