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