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