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