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