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