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