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