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