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