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