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