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