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