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