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