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