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