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