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