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