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