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