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