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   // FIXME: odr checking?
1181 }
1182 
1183 void ASTDeclReader::VisitObjCInterfaceDecl(ObjCInterfaceDecl *ID) {
1184   RedeclarableResult Redecl = VisitRedeclarable(ID);
1185   VisitObjCContainerDecl(ID);
1186   DeferredTypeID = Record.getGlobalTypeID(Record.readInt());
1187   mergeRedeclarable(ID, Redecl);
1188 
1189   ID->TypeParamList = ReadObjCTypeParamList();
1190   if (Record.readInt()) {
1191     // Read the definition.
1192     ID->allocateDefinitionData();
1193 
1194     ReadObjCDefinitionData(ID->data());
1195     ObjCInterfaceDecl *Canon = ID->getCanonicalDecl();
1196     if (Canon->Data.getPointer()) {
1197       // If we already have a definition, keep the definition invariant and
1198       // merge the data.
1199       MergeDefinitionData(Canon, std::move(ID->data()));
1200       ID->Data = Canon->Data;
1201     } else {
1202       // Set the definition data of the canonical declaration, so other
1203       // redeclarations will see it.
1204       ID->getCanonicalDecl()->Data = ID->Data;
1205 
1206       // We will rebuild this list lazily.
1207       ID->setIvarList(nullptr);
1208     }
1209 
1210     // Note that we have deserialized a definition.
1211     Reader.PendingDefinitions.insert(ID);
1212 
1213     // Note that we've loaded this Objective-C class.
1214     Reader.ObjCClassesLoaded.push_back(ID);
1215   } else {
1216     ID->Data = ID->getCanonicalDecl()->Data;
1217   }
1218 }
1219 
1220 void ASTDeclReader::VisitObjCIvarDecl(ObjCIvarDecl *IVD) {
1221   VisitFieldDecl(IVD);
1222   IVD->setAccessControl((ObjCIvarDecl::AccessControl)Record.readInt());
1223   // This field will be built lazily.
1224   IVD->setNextIvar(nullptr);
1225   bool synth = Record.readInt();
1226   IVD->setSynthesize(synth);
1227 }
1228 
1229 void ASTDeclReader::ReadObjCDefinitionData(
1230          struct ObjCProtocolDecl::DefinitionData &Data) {
1231     unsigned NumProtoRefs = Record.readInt();
1232     SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
1233     ProtoRefs.reserve(NumProtoRefs);
1234     for (unsigned I = 0; I != NumProtoRefs; ++I)
1235       ProtoRefs.push_back(readDeclAs<ObjCProtocolDecl>());
1236     SmallVector<SourceLocation, 16> ProtoLocs;
1237     ProtoLocs.reserve(NumProtoRefs);
1238     for (unsigned I = 0; I != NumProtoRefs; ++I)
1239       ProtoLocs.push_back(readSourceLocation());
1240     Data.ReferencedProtocols.set(ProtoRefs.data(), NumProtoRefs,
1241                                  ProtoLocs.data(), Reader.getContext());
1242 }
1243 
1244 void ASTDeclReader::MergeDefinitionData(ObjCProtocolDecl *D,
1245          struct ObjCProtocolDecl::DefinitionData &&NewDD) {
1246   // FIXME: odr checking?
1247 }
1248 
1249 void ASTDeclReader::VisitObjCProtocolDecl(ObjCProtocolDecl *PD) {
1250   RedeclarableResult Redecl = VisitRedeclarable(PD);
1251   VisitObjCContainerDecl(PD);
1252   mergeRedeclarable(PD, Redecl);
1253 
1254   if (Record.readInt()) {
1255     // Read the definition.
1256     PD->allocateDefinitionData();
1257 
1258     ReadObjCDefinitionData(PD->data());
1259 
1260     ObjCProtocolDecl *Canon = PD->getCanonicalDecl();
1261     if (Canon->Data.getPointer()) {
1262       // If we already have a definition, keep the definition invariant and
1263       // merge the data.
1264       MergeDefinitionData(Canon, std::move(PD->data()));
1265       PD->Data = Canon->Data;
1266     } else {
1267       // Set the definition data of the canonical declaration, so other
1268       // redeclarations will see it.
1269       PD->getCanonicalDecl()->Data = PD->Data;
1270     }
1271     // Note that we have deserialized a definition.
1272     Reader.PendingDefinitions.insert(PD);
1273   } else {
1274     PD->Data = PD->getCanonicalDecl()->Data;
1275   }
1276 }
1277 
1278 void ASTDeclReader::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *FD) {
1279   VisitFieldDecl(FD);
1280 }
1281 
1282 void ASTDeclReader::VisitObjCCategoryDecl(ObjCCategoryDecl *CD) {
1283   VisitObjCContainerDecl(CD);
1284   CD->setCategoryNameLoc(readSourceLocation());
1285   CD->setIvarLBraceLoc(readSourceLocation());
1286   CD->setIvarRBraceLoc(readSourceLocation());
1287 
1288   // Note that this category has been deserialized. We do this before
1289   // deserializing the interface declaration, so that it will consider this
1290   /// category.
1291   Reader.CategoriesDeserialized.insert(CD);
1292 
1293   CD->ClassInterface = readDeclAs<ObjCInterfaceDecl>();
1294   CD->TypeParamList = ReadObjCTypeParamList();
1295   unsigned NumProtoRefs = Record.readInt();
1296   SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
1297   ProtoRefs.reserve(NumProtoRefs);
1298   for (unsigned I = 0; I != NumProtoRefs; ++I)
1299     ProtoRefs.push_back(readDeclAs<ObjCProtocolDecl>());
1300   SmallVector<SourceLocation, 16> ProtoLocs;
1301   ProtoLocs.reserve(NumProtoRefs);
1302   for (unsigned I = 0; I != NumProtoRefs; ++I)
1303     ProtoLocs.push_back(readSourceLocation());
1304   CD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
1305                       Reader.getContext());
1306 
1307   // Protocols in the class extension belong to the class.
1308   if (NumProtoRefs > 0 && CD->ClassInterface && CD->IsClassExtension())
1309     CD->ClassInterface->mergeClassExtensionProtocolList(
1310         (ObjCProtocolDecl *const *)ProtoRefs.data(), NumProtoRefs,
1311         Reader.getContext());
1312 }
1313 
1314 void ASTDeclReader::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *CAD) {
1315   VisitNamedDecl(CAD);
1316   CAD->setClassInterface(readDeclAs<ObjCInterfaceDecl>());
1317 }
1318 
1319 void ASTDeclReader::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
1320   VisitNamedDecl(D);
1321   D->setAtLoc(readSourceLocation());
1322   D->setLParenLoc(readSourceLocation());
1323   QualType T = Record.readType();
1324   TypeSourceInfo *TSI = readTypeSourceInfo();
1325   D->setType(T, TSI);
1326   D->setPropertyAttributes((ObjCPropertyAttribute::Kind)Record.readInt());
1327   D->setPropertyAttributesAsWritten(
1328       (ObjCPropertyAttribute::Kind)Record.readInt());
1329   D->setPropertyImplementation(
1330       (ObjCPropertyDecl::PropertyControl)Record.readInt());
1331   DeclarationName GetterName = Record.readDeclarationName();
1332   SourceLocation GetterLoc = readSourceLocation();
1333   D->setGetterName(GetterName.getObjCSelector(), GetterLoc);
1334   DeclarationName SetterName = Record.readDeclarationName();
1335   SourceLocation SetterLoc = readSourceLocation();
1336   D->setSetterName(SetterName.getObjCSelector(), SetterLoc);
1337   D->setGetterMethodDecl(readDeclAs<ObjCMethodDecl>());
1338   D->setSetterMethodDecl(readDeclAs<ObjCMethodDecl>());
1339   D->setPropertyIvarDecl(readDeclAs<ObjCIvarDecl>());
1340 }
1341 
1342 void ASTDeclReader::VisitObjCImplDecl(ObjCImplDecl *D) {
1343   VisitObjCContainerDecl(D);
1344   D->setClassInterface(readDeclAs<ObjCInterfaceDecl>());
1345 }
1346 
1347 void ASTDeclReader::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1348   VisitObjCImplDecl(D);
1349   D->CategoryNameLoc = readSourceLocation();
1350 }
1351 
1352 void ASTDeclReader::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1353   VisitObjCImplDecl(D);
1354   D->setSuperClass(readDeclAs<ObjCInterfaceDecl>());
1355   D->SuperLoc = readSourceLocation();
1356   D->setIvarLBraceLoc(readSourceLocation());
1357   D->setIvarRBraceLoc(readSourceLocation());
1358   D->setHasNonZeroConstructors(Record.readInt());
1359   D->setHasDestructors(Record.readInt());
1360   D->NumIvarInitializers = Record.readInt();
1361   if (D->NumIvarInitializers)
1362     D->IvarInitializers = ReadGlobalOffset();
1363 }
1364 
1365 void ASTDeclReader::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
1366   VisitDecl(D);
1367   D->setAtLoc(readSourceLocation());
1368   D->setPropertyDecl(readDeclAs<ObjCPropertyDecl>());
1369   D->PropertyIvarDecl = readDeclAs<ObjCIvarDecl>();
1370   D->IvarLoc = readSourceLocation();
1371   D->setGetterMethodDecl(readDeclAs<ObjCMethodDecl>());
1372   D->setSetterMethodDecl(readDeclAs<ObjCMethodDecl>());
1373   D->setGetterCXXConstructor(Record.readExpr());
1374   D->setSetterCXXAssignment(Record.readExpr());
1375 }
1376 
1377 void ASTDeclReader::VisitFieldDecl(FieldDecl *FD) {
1378   VisitDeclaratorDecl(FD);
1379   FD->Mutable = Record.readInt();
1380 
1381   if (auto ISK = static_cast<FieldDecl::InitStorageKind>(Record.readInt())) {
1382     FD->InitStorage.setInt(ISK);
1383     FD->InitStorage.setPointer(ISK == FieldDecl::ISK_CapturedVLAType
1384                                    ? Record.readType().getAsOpaquePtr()
1385                                    : Record.readExpr());
1386   }
1387 
1388   if (auto *BW = Record.readExpr())
1389     FD->setBitWidth(BW);
1390 
1391   if (!FD->getDeclName()) {
1392     if (auto *Tmpl = readDeclAs<FieldDecl>())
1393       Reader.getContext().setInstantiatedFromUnnamedFieldDecl(FD, Tmpl);
1394   }
1395   mergeMergeable(FD);
1396 }
1397 
1398 void ASTDeclReader::VisitMSPropertyDecl(MSPropertyDecl *PD) {
1399   VisitDeclaratorDecl(PD);
1400   PD->GetterId = Record.readIdentifier();
1401   PD->SetterId = Record.readIdentifier();
1402 }
1403 
1404 void ASTDeclReader::VisitMSGuidDecl(MSGuidDecl *D) {
1405   VisitValueDecl(D);
1406   D->PartVal.Part1 = Record.readInt();
1407   D->PartVal.Part2 = Record.readInt();
1408   D->PartVal.Part3 = Record.readInt();
1409   for (auto &C : D->PartVal.Part4And5)
1410     C = Record.readInt();
1411 
1412   // Add this GUID to the AST context's lookup structure, and merge if needed.
1413   if (MSGuidDecl *Existing = Reader.getContext().MSGuidDecls.GetOrInsertNode(D))
1414     Reader.getContext().setPrimaryMergedDecl(D, Existing->getCanonicalDecl());
1415 }
1416 
1417 void ASTDeclReader::VisitTemplateParamObjectDecl(TemplateParamObjectDecl *D) {
1418   VisitValueDecl(D);
1419   D->Value = Record.readAPValue();
1420 
1421   // Add this template parameter object to the AST context's lookup structure,
1422   // and merge if needed.
1423   if (TemplateParamObjectDecl *Existing =
1424           Reader.getContext().TemplateParamObjectDecls.GetOrInsertNode(D))
1425     Reader.getContext().setPrimaryMergedDecl(D, Existing->getCanonicalDecl());
1426 }
1427 
1428 void ASTDeclReader::VisitIndirectFieldDecl(IndirectFieldDecl *FD) {
1429   VisitValueDecl(FD);
1430 
1431   FD->ChainingSize = Record.readInt();
1432   assert(FD->ChainingSize >= 2 && "Anonymous chaining must be >= 2");
1433   FD->Chaining = new (Reader.getContext())NamedDecl*[FD->ChainingSize];
1434 
1435   for (unsigned I = 0; I != FD->ChainingSize; ++I)
1436     FD->Chaining[I] = readDeclAs<NamedDecl>();
1437 
1438   mergeMergeable(FD);
1439 }
1440 
1441 ASTDeclReader::RedeclarableResult ASTDeclReader::VisitVarDeclImpl(VarDecl *VD) {
1442   RedeclarableResult Redecl = VisitRedeclarable(VD);
1443   VisitDeclaratorDecl(VD);
1444 
1445   VD->VarDeclBits.SClass = (StorageClass)Record.readInt();
1446   VD->VarDeclBits.TSCSpec = Record.readInt();
1447   VD->VarDeclBits.InitStyle = Record.readInt();
1448   VD->VarDeclBits.ARCPseudoStrong = Record.readInt();
1449   if (!isa<ParmVarDecl>(VD)) {
1450     VD->NonParmVarDeclBits.IsThisDeclarationADemotedDefinition =
1451         Record.readInt();
1452     VD->NonParmVarDeclBits.ExceptionVar = Record.readInt();
1453     VD->NonParmVarDeclBits.NRVOVariable = Record.readInt();
1454     VD->NonParmVarDeclBits.CXXForRangeDecl = Record.readInt();
1455     VD->NonParmVarDeclBits.ObjCForDecl = Record.readInt();
1456     VD->NonParmVarDeclBits.IsInline = Record.readInt();
1457     VD->NonParmVarDeclBits.IsInlineSpecified = Record.readInt();
1458     VD->NonParmVarDeclBits.IsConstexpr = Record.readInt();
1459     VD->NonParmVarDeclBits.IsInitCapture = Record.readInt();
1460     VD->NonParmVarDeclBits.PreviousDeclInSameBlockScope = Record.readInt();
1461     VD->NonParmVarDeclBits.ImplicitParamKind = Record.readInt();
1462     VD->NonParmVarDeclBits.EscapingByref = Record.readInt();
1463   }
1464   auto VarLinkage = Linkage(Record.readInt());
1465   VD->setCachedLinkage(VarLinkage);
1466 
1467   // Reconstruct the one piece of the IdentifierNamespace that we need.
1468   if (VD->getStorageClass() == SC_Extern && VarLinkage != NoLinkage &&
1469       VD->getLexicalDeclContext()->isFunctionOrMethod())
1470     VD->setLocalExternDecl();
1471 
1472   if (uint64_t Val = Record.readInt()) {
1473     VD->setInit(Record.readExpr());
1474     if (Val != 1) {
1475       EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
1476       Eval->HasConstantInitialization = (Val & 2) != 0;
1477       Eval->HasConstantDestruction = (Val & 4) != 0;
1478     }
1479   }
1480 
1481   if (VD->hasAttr<BlocksAttr>() && VD->getType()->getAsCXXRecordDecl()) {
1482     Expr *CopyExpr = Record.readExpr();
1483     if (CopyExpr)
1484       Reader.getContext().setBlockVarCopyInit(VD, CopyExpr, Record.readInt());
1485   }
1486 
1487   if (VD->getStorageDuration() == SD_Static && Record.readInt()) {
1488     Reader.DefinitionSource[VD] =
1489         Loc.F->Kind == ModuleKind::MK_MainFile ||
1490         Reader.getContext().getLangOpts().BuildingPCHWithObjectFile;
1491   }
1492 
1493   enum VarKind {
1494     VarNotTemplate = 0, VarTemplate, StaticDataMemberSpecialization
1495   };
1496   switch ((VarKind)Record.readInt()) {
1497   case VarNotTemplate:
1498     // Only true variables (not parameters or implicit parameters) can be
1499     // merged; the other kinds are not really redeclarable at all.
1500     if (!isa<ParmVarDecl>(VD) && !isa<ImplicitParamDecl>(VD) &&
1501         !isa<VarTemplateSpecializationDecl>(VD))
1502       mergeRedeclarable(VD, Redecl);
1503     break;
1504   case VarTemplate:
1505     // Merged when we merge the template.
1506     VD->setDescribedVarTemplate(readDeclAs<VarTemplateDecl>());
1507     break;
1508   case StaticDataMemberSpecialization: { // HasMemberSpecializationInfo.
1509     auto *Tmpl = readDeclAs<VarDecl>();
1510     auto TSK = (TemplateSpecializationKind)Record.readInt();
1511     SourceLocation POI = readSourceLocation();
1512     Reader.getContext().setInstantiatedFromStaticDataMember(VD, Tmpl, TSK,POI);
1513     mergeRedeclarable(VD, Redecl);
1514     break;
1515   }
1516   }
1517 
1518   return Redecl;
1519 }
1520 
1521 void ASTDeclReader::VisitImplicitParamDecl(ImplicitParamDecl *PD) {
1522   VisitVarDecl(PD);
1523 }
1524 
1525 void ASTDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
1526   VisitVarDecl(PD);
1527   unsigned isObjCMethodParam = Record.readInt();
1528   unsigned scopeDepth = Record.readInt();
1529   unsigned scopeIndex = Record.readInt();
1530   unsigned declQualifier = Record.readInt();
1531   if (isObjCMethodParam) {
1532     assert(scopeDepth == 0);
1533     PD->setObjCMethodScopeInfo(scopeIndex);
1534     PD->ParmVarDeclBits.ScopeDepthOrObjCQuals = declQualifier;
1535   } else {
1536     PD->setScopeInfo(scopeDepth, scopeIndex);
1537   }
1538   PD->ParmVarDeclBits.IsKNRPromoted = Record.readInt();
1539   PD->ParmVarDeclBits.HasInheritedDefaultArg = Record.readInt();
1540   if (Record.readInt()) // hasUninstantiatedDefaultArg.
1541     PD->setUninstantiatedDefaultArg(Record.readExpr());
1542 
1543   // FIXME: If this is a redeclaration of a function from another module, handle
1544   // inheritance of default arguments.
1545 }
1546 
1547 void ASTDeclReader::VisitDecompositionDecl(DecompositionDecl *DD) {
1548   VisitVarDecl(DD);
1549   auto **BDs = DD->getTrailingObjects<BindingDecl *>();
1550   for (unsigned I = 0; I != DD->NumBindings; ++I) {
1551     BDs[I] = readDeclAs<BindingDecl>();
1552     BDs[I]->setDecomposedDecl(DD);
1553   }
1554 }
1555 
1556 void ASTDeclReader::VisitBindingDecl(BindingDecl *BD) {
1557   VisitValueDecl(BD);
1558   BD->Binding = Record.readExpr();
1559 }
1560 
1561 void ASTDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {
1562   VisitDecl(AD);
1563   AD->setAsmString(cast<StringLiteral>(Record.readExpr()));
1564   AD->setRParenLoc(readSourceLocation());
1565 }
1566 
1567 void ASTDeclReader::VisitBlockDecl(BlockDecl *BD) {
1568   VisitDecl(BD);
1569   BD->setBody(cast_or_null<CompoundStmt>(Record.readStmt()));
1570   BD->setSignatureAsWritten(readTypeSourceInfo());
1571   unsigned NumParams = Record.readInt();
1572   SmallVector<ParmVarDecl *, 16> Params;
1573   Params.reserve(NumParams);
1574   for (unsigned I = 0; I != NumParams; ++I)
1575     Params.push_back(readDeclAs<ParmVarDecl>());
1576   BD->setParams(Params);
1577 
1578   BD->setIsVariadic(Record.readInt());
1579   BD->setBlockMissingReturnType(Record.readInt());
1580   BD->setIsConversionFromLambda(Record.readInt());
1581   BD->setDoesNotEscape(Record.readInt());
1582   BD->setCanAvoidCopyToHeap(Record.readInt());
1583 
1584   bool capturesCXXThis = Record.readInt();
1585   unsigned numCaptures = Record.readInt();
1586   SmallVector<BlockDecl::Capture, 16> captures;
1587   captures.reserve(numCaptures);
1588   for (unsigned i = 0; i != numCaptures; ++i) {
1589     auto *decl = readDeclAs<VarDecl>();
1590     unsigned flags = Record.readInt();
1591     bool byRef = (flags & 1);
1592     bool nested = (flags & 2);
1593     Expr *copyExpr = ((flags & 4) ? Record.readExpr() : nullptr);
1594 
1595     captures.push_back(BlockDecl::Capture(decl, byRef, nested, copyExpr));
1596   }
1597   BD->setCaptures(Reader.getContext(), captures, capturesCXXThis);
1598 }
1599 
1600 void ASTDeclReader::VisitCapturedDecl(CapturedDecl *CD) {
1601   VisitDecl(CD);
1602   unsigned ContextParamPos = Record.readInt();
1603   CD->setNothrow(Record.readInt() != 0);
1604   // Body is set by VisitCapturedStmt.
1605   for (unsigned I = 0; I < CD->NumParams; ++I) {
1606     if (I != ContextParamPos)
1607       CD->setParam(I, readDeclAs<ImplicitParamDecl>());
1608     else
1609       CD->setContextParam(I, readDeclAs<ImplicitParamDecl>());
1610   }
1611 }
1612 
1613 void ASTDeclReader::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1614   VisitDecl(D);
1615   D->setLanguage((LinkageSpecDecl::LanguageIDs)Record.readInt());
1616   D->setExternLoc(readSourceLocation());
1617   D->setRBraceLoc(readSourceLocation());
1618 }
1619 
1620 void ASTDeclReader::VisitExportDecl(ExportDecl *D) {
1621   VisitDecl(D);
1622   D->RBraceLoc = readSourceLocation();
1623 }
1624 
1625 void ASTDeclReader::VisitLabelDecl(LabelDecl *D) {
1626   VisitNamedDecl(D);
1627   D->setLocStart(readSourceLocation());
1628 }
1629 
1630 void ASTDeclReader::VisitNamespaceDecl(NamespaceDecl *D) {
1631   RedeclarableResult Redecl = VisitRedeclarable(D);
1632   VisitNamedDecl(D);
1633   D->setInline(Record.readInt());
1634   D->LocStart = readSourceLocation();
1635   D->RBraceLoc = readSourceLocation();
1636 
1637   // Defer loading the anonymous namespace until we've finished merging
1638   // this namespace; loading it might load a later declaration of the
1639   // same namespace, and we have an invariant that older declarations
1640   // get merged before newer ones try to merge.
1641   GlobalDeclID AnonNamespace = 0;
1642   if (Redecl.getFirstID() == ThisDeclID) {
1643     AnonNamespace = readDeclID();
1644   } else {
1645     // Link this namespace back to the first declaration, which has already
1646     // been deserialized.
1647     D->AnonOrFirstNamespaceAndInline.setPointer(D->getFirstDecl());
1648   }
1649 
1650   mergeRedeclarable(D, Redecl);
1651 
1652   if (AnonNamespace) {
1653     // Each module has its own anonymous namespace, which is disjoint from
1654     // any other module's anonymous namespaces, so don't attach the anonymous
1655     // namespace at all.
1656     auto *Anon = cast<NamespaceDecl>(Reader.GetDecl(AnonNamespace));
1657     if (!Record.isModule())
1658       D->setAnonymousNamespace(Anon);
1659   }
1660 }
1661 
1662 void ASTDeclReader::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1663   RedeclarableResult Redecl = VisitRedeclarable(D);
1664   VisitNamedDecl(D);
1665   D->NamespaceLoc = readSourceLocation();
1666   D->IdentLoc = readSourceLocation();
1667   D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1668   D->Namespace = readDeclAs<NamedDecl>();
1669   mergeRedeclarable(D, Redecl);
1670 }
1671 
1672 void ASTDeclReader::VisitUsingDecl(UsingDecl *D) {
1673   VisitNamedDecl(D);
1674   D->setUsingLoc(readSourceLocation());
1675   D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1676   D->DNLoc = Record.readDeclarationNameLoc(D->getDeclName());
1677   D->FirstUsingShadow.setPointer(readDeclAs<UsingShadowDecl>());
1678   D->setTypename(Record.readInt());
1679   if (auto *Pattern = readDeclAs<NamedDecl>())
1680     Reader.getContext().setInstantiatedFromUsingDecl(D, Pattern);
1681   mergeMergeable(D);
1682 }
1683 
1684 void ASTDeclReader::VisitUsingEnumDecl(UsingEnumDecl *D) {
1685   VisitNamedDecl(D);
1686   D->setUsingLoc(readSourceLocation());
1687   D->setEnumLoc(readSourceLocation());
1688   D->Enum = readDeclAs<EnumDecl>();
1689   D->FirstUsingShadow.setPointer(readDeclAs<UsingShadowDecl>());
1690   if (auto *Pattern = readDeclAs<UsingEnumDecl>())
1691     Reader.getContext().setInstantiatedFromUsingEnumDecl(D, Pattern);
1692   mergeMergeable(D);
1693 }
1694 
1695 void ASTDeclReader::VisitUsingPackDecl(UsingPackDecl *D) {
1696   VisitNamedDecl(D);
1697   D->InstantiatedFrom = readDeclAs<NamedDecl>();
1698   auto **Expansions = D->getTrailingObjects<NamedDecl *>();
1699   for (unsigned I = 0; I != D->NumExpansions; ++I)
1700     Expansions[I] = readDeclAs<NamedDecl>();
1701   mergeMergeable(D);
1702 }
1703 
1704 void ASTDeclReader::VisitUsingShadowDecl(UsingShadowDecl *D) {
1705   RedeclarableResult Redecl = VisitRedeclarable(D);
1706   VisitNamedDecl(D);
1707   D->Underlying = readDeclAs<NamedDecl>();
1708   D->IdentifierNamespace = Record.readInt();
1709   D->UsingOrNextShadow = readDeclAs<NamedDecl>();
1710   auto *Pattern = readDeclAs<UsingShadowDecl>();
1711   if (Pattern)
1712     Reader.getContext().setInstantiatedFromUsingShadowDecl(D, Pattern);
1713   mergeRedeclarable(D, Redecl);
1714 }
1715 
1716 void ASTDeclReader::VisitConstructorUsingShadowDecl(
1717     ConstructorUsingShadowDecl *D) {
1718   VisitUsingShadowDecl(D);
1719   D->NominatedBaseClassShadowDecl = readDeclAs<ConstructorUsingShadowDecl>();
1720   D->ConstructedBaseClassShadowDecl = readDeclAs<ConstructorUsingShadowDecl>();
1721   D->IsVirtual = Record.readInt();
1722 }
1723 
1724 void ASTDeclReader::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1725   VisitNamedDecl(D);
1726   D->UsingLoc = readSourceLocation();
1727   D->NamespaceLoc = readSourceLocation();
1728   D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1729   D->NominatedNamespace = readDeclAs<NamedDecl>();
1730   D->CommonAncestor = readDeclAs<DeclContext>();
1731 }
1732 
1733 void ASTDeclReader::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1734   VisitValueDecl(D);
1735   D->setUsingLoc(readSourceLocation());
1736   D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1737   D->DNLoc = Record.readDeclarationNameLoc(D->getDeclName());
1738   D->EllipsisLoc = readSourceLocation();
1739   mergeMergeable(D);
1740 }
1741 
1742 void ASTDeclReader::VisitUnresolvedUsingTypenameDecl(
1743                                                UnresolvedUsingTypenameDecl *D) {
1744   VisitTypeDecl(D);
1745   D->TypenameLocation = readSourceLocation();
1746   D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1747   D->EllipsisLoc = readSourceLocation();
1748   mergeMergeable(D);
1749 }
1750 
1751 void ASTDeclReader::VisitUnresolvedUsingIfExistsDecl(
1752     UnresolvedUsingIfExistsDecl *D) {
1753   VisitNamedDecl(D);
1754 }
1755 
1756 void ASTDeclReader::ReadCXXDefinitionData(
1757     struct CXXRecordDecl::DefinitionData &Data, const CXXRecordDecl *D) {
1758   #define FIELD(Name, Width, Merge) \
1759   Data.Name = Record.readInt();
1760   #include "clang/AST/CXXRecordDeclDefinitionBits.def"
1761 
1762   // Note: the caller has deserialized the IsLambda bit already.
1763   Data.ODRHash = Record.readInt();
1764   Data.HasODRHash = true;
1765 
1766   if (Record.readInt()) {
1767     Reader.DefinitionSource[D] =
1768         Loc.F->Kind == ModuleKind::MK_MainFile ||
1769         Reader.getContext().getLangOpts().BuildingPCHWithObjectFile;
1770   }
1771 
1772   Data.NumBases = Record.readInt();
1773   if (Data.NumBases)
1774     Data.Bases = ReadGlobalOffset();
1775   Data.NumVBases = Record.readInt();
1776   if (Data.NumVBases)
1777     Data.VBases = ReadGlobalOffset();
1778 
1779   Record.readUnresolvedSet(Data.Conversions);
1780   Data.ComputedVisibleConversions = Record.readInt();
1781   if (Data.ComputedVisibleConversions)
1782     Record.readUnresolvedSet(Data.VisibleConversions);
1783   assert(Data.Definition && "Data.Definition should be already set!");
1784   Data.FirstFriend = readDeclID();
1785 
1786   if (Data.IsLambda) {
1787     using Capture = LambdaCapture;
1788 
1789     auto &Lambda = static_cast<CXXRecordDecl::LambdaDefinitionData &>(Data);
1790     Lambda.Dependent = Record.readInt();
1791     Lambda.IsGenericLambda = Record.readInt();
1792     Lambda.CaptureDefault = Record.readInt();
1793     Lambda.NumCaptures = Record.readInt();
1794     Lambda.NumExplicitCaptures = Record.readInt();
1795     Lambda.HasKnownInternalLinkage = Record.readInt();
1796     Lambda.ManglingNumber = Record.readInt();
1797     D->setDeviceLambdaManglingNumber(Record.readInt());
1798     Lambda.ContextDecl = readDeclID();
1799     Lambda.Captures = (Capture *)Reader.getContext().Allocate(
1800         sizeof(Capture) * Lambda.NumCaptures);
1801     Capture *ToCapture = Lambda.Captures;
1802     Lambda.MethodTyInfo = readTypeSourceInfo();
1803     for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
1804       SourceLocation Loc = readSourceLocation();
1805       bool IsImplicit = Record.readInt();
1806       auto Kind = static_cast<LambdaCaptureKind>(Record.readInt());
1807       switch (Kind) {
1808       case LCK_StarThis:
1809       case LCK_This:
1810       case LCK_VLAType:
1811         *ToCapture++ = Capture(Loc, IsImplicit, Kind, nullptr,SourceLocation());
1812         break;
1813       case LCK_ByCopy:
1814       case LCK_ByRef:
1815         auto *Var = readDeclAs<VarDecl>();
1816         SourceLocation EllipsisLoc = readSourceLocation();
1817         *ToCapture++ = Capture(Loc, IsImplicit, Kind, Var, EllipsisLoc);
1818         break;
1819       }
1820     }
1821   }
1822 }
1823 
1824 void ASTDeclReader::MergeDefinitionData(
1825     CXXRecordDecl *D, struct CXXRecordDecl::DefinitionData &&MergeDD) {
1826   assert(D->DefinitionData &&
1827          "merging class definition into non-definition");
1828   auto &DD = *D->DefinitionData;
1829 
1830   if (DD.Definition != MergeDD.Definition) {
1831     // Track that we merged the definitions.
1832     Reader.MergedDeclContexts.insert(std::make_pair(MergeDD.Definition,
1833                                                     DD.Definition));
1834     Reader.PendingDefinitions.erase(MergeDD.Definition);
1835     MergeDD.Definition->setCompleteDefinition(false);
1836     Reader.mergeDefinitionVisibility(DD.Definition, MergeDD.Definition);
1837     assert(Reader.Lookups.find(MergeDD.Definition) == Reader.Lookups.end() &&
1838            "already loaded pending lookups for merged definition");
1839   }
1840 
1841   auto PFDI = Reader.PendingFakeDefinitionData.find(&DD);
1842   if (PFDI != Reader.PendingFakeDefinitionData.end() &&
1843       PFDI->second == ASTReader::PendingFakeDefinitionKind::Fake) {
1844     // We faked up this definition data because we found a class for which we'd
1845     // not yet loaded the definition. Replace it with the real thing now.
1846     assert(!DD.IsLambda && !MergeDD.IsLambda && "faked up lambda definition?");
1847     PFDI->second = ASTReader::PendingFakeDefinitionKind::FakeLoaded;
1848 
1849     // Don't change which declaration is the definition; that is required
1850     // to be invariant once we select it.
1851     auto *Def = DD.Definition;
1852     DD = std::move(MergeDD);
1853     DD.Definition = Def;
1854     return;
1855   }
1856 
1857   bool DetectedOdrViolation = false;
1858 
1859   #define FIELD(Name, Width, Merge) Merge(Name)
1860   #define MERGE_OR(Field) DD.Field |= MergeDD.Field;
1861   #define NO_MERGE(Field) \
1862     DetectedOdrViolation |= DD.Field != MergeDD.Field; \
1863     MERGE_OR(Field)
1864   #include "clang/AST/CXXRecordDeclDefinitionBits.def"
1865   NO_MERGE(IsLambda)
1866   #undef NO_MERGE
1867   #undef MERGE_OR
1868 
1869   if (DD.NumBases != MergeDD.NumBases || DD.NumVBases != MergeDD.NumVBases)
1870     DetectedOdrViolation = true;
1871   // FIXME: Issue a diagnostic if the base classes don't match when we come
1872   // to lazily load them.
1873 
1874   // FIXME: Issue a diagnostic if the list of conversion functions doesn't
1875   // match when we come to lazily load them.
1876   if (MergeDD.ComputedVisibleConversions && !DD.ComputedVisibleConversions) {
1877     DD.VisibleConversions = std::move(MergeDD.VisibleConversions);
1878     DD.ComputedVisibleConversions = true;
1879   }
1880 
1881   // FIXME: Issue a diagnostic if FirstFriend doesn't match when we come to
1882   // lazily load it.
1883 
1884   if (DD.IsLambda) {
1885     // FIXME: ODR-checking for merging lambdas (this happens, for instance,
1886     // when they occur within the body of a function template specialization).
1887   }
1888 
1889   if (D->getODRHash() != MergeDD.ODRHash) {
1890     DetectedOdrViolation = true;
1891   }
1892 
1893   if (DetectedOdrViolation)
1894     Reader.PendingOdrMergeFailures[DD.Definition].push_back(
1895         {MergeDD.Definition, &MergeDD});
1896 }
1897 
1898 void ASTDeclReader::ReadCXXRecordDefinition(CXXRecordDecl *D, bool Update) {
1899   struct CXXRecordDecl::DefinitionData *DD;
1900   ASTContext &C = Reader.getContext();
1901 
1902   // Determine whether this is a lambda closure type, so that we can
1903   // allocate the appropriate DefinitionData structure.
1904   bool IsLambda = Record.readInt();
1905   if (IsLambda)
1906     DD = new (C) CXXRecordDecl::LambdaDefinitionData(D, nullptr, false, false,
1907                                                      LCD_None);
1908   else
1909     DD = new (C) struct CXXRecordDecl::DefinitionData(D);
1910 
1911   CXXRecordDecl *Canon = D->getCanonicalDecl();
1912   // Set decl definition data before reading it, so that during deserialization
1913   // when we read CXXRecordDecl, it already has definition data and we don't
1914   // set fake one.
1915   if (!Canon->DefinitionData)
1916     Canon->DefinitionData = DD;
1917   D->DefinitionData = Canon->DefinitionData;
1918   ReadCXXDefinitionData(*DD, D);
1919 
1920   // We might already have a different definition for this record. This can
1921   // happen either because we're reading an update record, or because we've
1922   // already done some merging. Either way, just merge into it.
1923   if (Canon->DefinitionData != DD) {
1924     MergeDefinitionData(Canon, std::move(*DD));
1925     return;
1926   }
1927 
1928   // Mark this declaration as being a definition.
1929   D->setCompleteDefinition(true);
1930 
1931   // If this is not the first declaration or is an update record, we can have
1932   // other redeclarations already. Make a note that we need to propagate the
1933   // DefinitionData pointer onto them.
1934   if (Update || Canon != D)
1935     Reader.PendingDefinitions.insert(D);
1936 }
1937 
1938 ASTDeclReader::RedeclarableResult
1939 ASTDeclReader::VisitCXXRecordDeclImpl(CXXRecordDecl *D) {
1940   RedeclarableResult Redecl = VisitRecordDeclImpl(D);
1941 
1942   ASTContext &C = Reader.getContext();
1943 
1944   enum CXXRecKind {
1945     CXXRecNotTemplate = 0, CXXRecTemplate, CXXRecMemberSpecialization
1946   };
1947   switch ((CXXRecKind)Record.readInt()) {
1948   case CXXRecNotTemplate:
1949     // Merged when we merge the folding set entry in the primary template.
1950     if (!isa<ClassTemplateSpecializationDecl>(D))
1951       mergeRedeclarable(D, Redecl);
1952     break;
1953   case CXXRecTemplate: {
1954     // Merged when we merge the template.
1955     auto *Template = readDeclAs<ClassTemplateDecl>();
1956     D->TemplateOrInstantiation = Template;
1957     if (!Template->getTemplatedDecl()) {
1958       // We've not actually loaded the ClassTemplateDecl yet, because we're
1959       // currently being loaded as its pattern. Rely on it to set up our
1960       // TypeForDecl (see VisitClassTemplateDecl).
1961       //
1962       // Beware: we do not yet know our canonical declaration, and may still
1963       // get merged once the surrounding class template has got off the ground.
1964       DeferredTypeID = 0;
1965     }
1966     break;
1967   }
1968   case CXXRecMemberSpecialization: {
1969     auto *RD = readDeclAs<CXXRecordDecl>();
1970     auto TSK = (TemplateSpecializationKind)Record.readInt();
1971     SourceLocation POI = readSourceLocation();
1972     MemberSpecializationInfo *MSI = new (C) MemberSpecializationInfo(RD, TSK);
1973     MSI->setPointOfInstantiation(POI);
1974     D->TemplateOrInstantiation = MSI;
1975     mergeRedeclarable(D, Redecl);
1976     break;
1977   }
1978   }
1979 
1980   bool WasDefinition = Record.readInt();
1981   if (WasDefinition)
1982     ReadCXXRecordDefinition(D, /*Update*/false);
1983   else
1984     // Propagate DefinitionData pointer from the canonical declaration.
1985     D->DefinitionData = D->getCanonicalDecl()->DefinitionData;
1986 
1987   // Lazily load the key function to avoid deserializing every method so we can
1988   // compute it.
1989   if (WasDefinition) {
1990     DeclID KeyFn = readDeclID();
1991     if (KeyFn && D->isCompleteDefinition())
1992       // FIXME: This is wrong for the ARM ABI, where some other module may have
1993       // made this function no longer be a key function. We need an update
1994       // record or similar for that case.
1995       C.KeyFunctions[D] = KeyFn;
1996   }
1997 
1998   return Redecl;
1999 }
2000 
2001 void ASTDeclReader::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
2002   D->setExplicitSpecifier(Record.readExplicitSpec());
2003   D->Ctor = readDeclAs<CXXConstructorDecl>();
2004   VisitFunctionDecl(D);
2005   D->setIsCopyDeductionCandidate(Record.readInt());
2006 }
2007 
2008 void ASTDeclReader::VisitCXXMethodDecl(CXXMethodDecl *D) {
2009   VisitFunctionDecl(D);
2010 
2011   unsigned NumOverridenMethods = Record.readInt();
2012   if (D->isCanonicalDecl()) {
2013     while (NumOverridenMethods--) {
2014       // Avoid invariant checking of CXXMethodDecl::addOverriddenMethod,
2015       // MD may be initializing.
2016       if (auto *MD = readDeclAs<CXXMethodDecl>())
2017         Reader.getContext().addOverriddenMethod(D, MD->getCanonicalDecl());
2018     }
2019   } else {
2020     // We don't care about which declarations this used to override; we get
2021     // the relevant information from the canonical declaration.
2022     Record.skipInts(NumOverridenMethods);
2023   }
2024 }
2025 
2026 void ASTDeclReader::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
2027   // We need the inherited constructor information to merge the declaration,
2028   // so we have to read it before we call VisitCXXMethodDecl.
2029   D->setExplicitSpecifier(Record.readExplicitSpec());
2030   if (D->isInheritingConstructor()) {
2031     auto *Shadow = readDeclAs<ConstructorUsingShadowDecl>();
2032     auto *Ctor = readDeclAs<CXXConstructorDecl>();
2033     *D->getTrailingObjects<InheritedConstructor>() =
2034         InheritedConstructor(Shadow, Ctor);
2035   }
2036 
2037   VisitCXXMethodDecl(D);
2038 }
2039 
2040 void ASTDeclReader::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
2041   VisitCXXMethodDecl(D);
2042 
2043   if (auto *OperatorDelete = readDeclAs<FunctionDecl>()) {
2044     CXXDestructorDecl *Canon = D->getCanonicalDecl();
2045     auto *ThisArg = Record.readExpr();
2046     // FIXME: Check consistency if we have an old and new operator delete.
2047     if (!Canon->OperatorDelete) {
2048       Canon->OperatorDelete = OperatorDelete;
2049       Canon->OperatorDeleteThisArg = ThisArg;
2050     }
2051   }
2052 }
2053 
2054 void ASTDeclReader::VisitCXXConversionDecl(CXXConversionDecl *D) {
2055   D->setExplicitSpecifier(Record.readExplicitSpec());
2056   VisitCXXMethodDecl(D);
2057 }
2058 
2059 void ASTDeclReader::VisitImportDecl(ImportDecl *D) {
2060   VisitDecl(D);
2061   D->ImportedModule = readModule();
2062   D->setImportComplete(Record.readInt());
2063   auto *StoredLocs = D->getTrailingObjects<SourceLocation>();
2064   for (unsigned I = 0, N = Record.back(); I != N; ++I)
2065     StoredLocs[I] = readSourceLocation();
2066   Record.skipInts(1); // The number of stored source locations.
2067 }
2068 
2069 void ASTDeclReader::VisitAccessSpecDecl(AccessSpecDecl *D) {
2070   VisitDecl(D);
2071   D->setColonLoc(readSourceLocation());
2072 }
2073 
2074 void ASTDeclReader::VisitFriendDecl(FriendDecl *D) {
2075   VisitDecl(D);
2076   if (Record.readInt()) // hasFriendDecl
2077     D->Friend = readDeclAs<NamedDecl>();
2078   else
2079     D->Friend = readTypeSourceInfo();
2080   for (unsigned i = 0; i != D->NumTPLists; ++i)
2081     D->getTrailingObjects<TemplateParameterList *>()[i] =
2082         Record.readTemplateParameterList();
2083   D->NextFriend = readDeclID();
2084   D->UnsupportedFriend = (Record.readInt() != 0);
2085   D->FriendLoc = readSourceLocation();
2086 }
2087 
2088 void ASTDeclReader::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
2089   VisitDecl(D);
2090   unsigned NumParams = Record.readInt();
2091   D->NumParams = NumParams;
2092   D->Params = new TemplateParameterList*[NumParams];
2093   for (unsigned i = 0; i != NumParams; ++i)
2094     D->Params[i] = Record.readTemplateParameterList();
2095   if (Record.readInt()) // HasFriendDecl
2096     D->Friend = readDeclAs<NamedDecl>();
2097   else
2098     D->Friend = readTypeSourceInfo();
2099   D->FriendLoc = readSourceLocation();
2100 }
2101 
2102 DeclID ASTDeclReader::VisitTemplateDecl(TemplateDecl *D) {
2103   VisitNamedDecl(D);
2104 
2105   DeclID PatternID = readDeclID();
2106   auto *TemplatedDecl = cast_or_null<NamedDecl>(Reader.GetDecl(PatternID));
2107   TemplateParameterList *TemplateParams = Record.readTemplateParameterList();
2108   D->init(TemplatedDecl, TemplateParams);
2109 
2110   return PatternID;
2111 }
2112 
2113 void ASTDeclReader::VisitConceptDecl(ConceptDecl *D) {
2114   VisitTemplateDecl(D);
2115   D->ConstraintExpr = Record.readExpr();
2116   mergeMergeable(D);
2117 }
2118 
2119 void ASTDeclReader::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) {
2120 }
2121 
2122 ASTDeclReader::RedeclarableResult
2123 ASTDeclReader::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
2124   RedeclarableResult Redecl = VisitRedeclarable(D);
2125 
2126   // Make sure we've allocated the Common pointer first. We do this before
2127   // VisitTemplateDecl so that getCommonPtr() can be used during initialization.
2128   RedeclarableTemplateDecl *CanonD = D->getCanonicalDecl();
2129   if (!CanonD->Common) {
2130     CanonD->Common = CanonD->newCommon(Reader.getContext());
2131     Reader.PendingDefinitions.insert(CanonD);
2132   }
2133   D->Common = CanonD->Common;
2134 
2135   // If this is the first declaration of the template, fill in the information
2136   // for the 'common' pointer.
2137   if (ThisDeclID == Redecl.getFirstID()) {
2138     if (auto *RTD = readDeclAs<RedeclarableTemplateDecl>()) {
2139       assert(RTD->getKind() == D->getKind() &&
2140              "InstantiatedFromMemberTemplate kind mismatch");
2141       D->setInstantiatedFromMemberTemplate(RTD);
2142       if (Record.readInt())
2143         D->setMemberSpecialization();
2144     }
2145   }
2146 
2147   DeclID PatternID = VisitTemplateDecl(D);
2148   D->IdentifierNamespace = Record.readInt();
2149 
2150   mergeRedeclarable(D, Redecl, PatternID);
2151 
2152   // If we merged the template with a prior declaration chain, merge the common
2153   // pointer.
2154   // FIXME: Actually merge here, don't just overwrite.
2155   D->Common = D->getCanonicalDecl()->Common;
2156 
2157   return Redecl;
2158 }
2159 
2160 void ASTDeclReader::VisitClassTemplateDecl(ClassTemplateDecl *D) {
2161   RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
2162 
2163   if (ThisDeclID == Redecl.getFirstID()) {
2164     // This ClassTemplateDecl owns a CommonPtr; read it to keep track of all of
2165     // the specializations.
2166     SmallVector<serialization::DeclID, 32> SpecIDs;
2167     readDeclIDList(SpecIDs);
2168     ASTDeclReader::AddLazySpecializations(D, SpecIDs);
2169   }
2170 
2171   if (D->getTemplatedDecl()->TemplateOrInstantiation) {
2172     // We were loaded before our templated declaration was. We've not set up
2173     // its corresponding type yet (see VisitCXXRecordDeclImpl), so reconstruct
2174     // it now.
2175     Reader.getContext().getInjectedClassNameType(
2176         D->getTemplatedDecl(), D->getInjectedClassNameSpecialization());
2177   }
2178 }
2179 
2180 void ASTDeclReader::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
2181   llvm_unreachable("BuiltinTemplates are not serialized");
2182 }
2183 
2184 /// TODO: Unify with ClassTemplateDecl version?
2185 ///       May require unifying ClassTemplateDecl and
2186 ///        VarTemplateDecl beyond TemplateDecl...
2187 void ASTDeclReader::VisitVarTemplateDecl(VarTemplateDecl *D) {
2188   RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
2189 
2190   if (ThisDeclID == Redecl.getFirstID()) {
2191     // This VarTemplateDecl owns a CommonPtr; read it to keep track of all of
2192     // the specializations.
2193     SmallVector<serialization::DeclID, 32> SpecIDs;
2194     readDeclIDList(SpecIDs);
2195     ASTDeclReader::AddLazySpecializations(D, SpecIDs);
2196   }
2197 }
2198 
2199 ASTDeclReader::RedeclarableResult
2200 ASTDeclReader::VisitClassTemplateSpecializationDeclImpl(
2201     ClassTemplateSpecializationDecl *D) {
2202   RedeclarableResult Redecl = VisitCXXRecordDeclImpl(D);
2203 
2204   ASTContext &C = Reader.getContext();
2205   if (Decl *InstD = readDecl()) {
2206     if (auto *CTD = dyn_cast<ClassTemplateDecl>(InstD)) {
2207       D->SpecializedTemplate = CTD;
2208     } else {
2209       SmallVector<TemplateArgument, 8> TemplArgs;
2210       Record.readTemplateArgumentList(TemplArgs);
2211       TemplateArgumentList *ArgList
2212         = TemplateArgumentList::CreateCopy(C, TemplArgs);
2213       auto *PS =
2214           new (C) ClassTemplateSpecializationDecl::
2215                                              SpecializedPartialSpecialization();
2216       PS->PartialSpecialization
2217           = cast<ClassTemplatePartialSpecializationDecl>(InstD);
2218       PS->TemplateArgs = ArgList;
2219       D->SpecializedTemplate = PS;
2220     }
2221   }
2222 
2223   SmallVector<TemplateArgument, 8> TemplArgs;
2224   Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
2225   D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs);
2226   D->PointOfInstantiation = readSourceLocation();
2227   D->SpecializationKind = (TemplateSpecializationKind)Record.readInt();
2228 
2229   bool writtenAsCanonicalDecl = Record.readInt();
2230   if (writtenAsCanonicalDecl) {
2231     auto *CanonPattern = readDeclAs<ClassTemplateDecl>();
2232     if (D->isCanonicalDecl()) { // It's kept in the folding set.
2233       // Set this as, or find, the canonical declaration for this specialization
2234       ClassTemplateSpecializationDecl *CanonSpec;
2235       if (auto *Partial = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) {
2236         CanonSpec = CanonPattern->getCommonPtr()->PartialSpecializations
2237             .GetOrInsertNode(Partial);
2238       } else {
2239         CanonSpec =
2240             CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
2241       }
2242       // If there was already a canonical specialization, merge into it.
2243       if (CanonSpec != D) {
2244         mergeRedeclarable<TagDecl>(D, CanonSpec, Redecl);
2245 
2246         // This declaration might be a definition. Merge with any existing
2247         // definition.
2248         if (auto *DDD = D->DefinitionData) {
2249           if (CanonSpec->DefinitionData)
2250             MergeDefinitionData(CanonSpec, std::move(*DDD));
2251           else
2252             CanonSpec->DefinitionData = D->DefinitionData;
2253         }
2254         D->DefinitionData = CanonSpec->DefinitionData;
2255       }
2256     }
2257   }
2258 
2259   // Explicit info.
2260   if (TypeSourceInfo *TyInfo = readTypeSourceInfo()) {
2261     auto *ExplicitInfo =
2262         new (C) ClassTemplateSpecializationDecl::ExplicitSpecializationInfo;
2263     ExplicitInfo->TypeAsWritten = TyInfo;
2264     ExplicitInfo->ExternLoc = readSourceLocation();
2265     ExplicitInfo->TemplateKeywordLoc = readSourceLocation();
2266     D->ExplicitInfo = ExplicitInfo;
2267   }
2268 
2269   return Redecl;
2270 }
2271 
2272 void ASTDeclReader::VisitClassTemplatePartialSpecializationDecl(
2273                                     ClassTemplatePartialSpecializationDecl *D) {
2274   // We need to read the template params first because redeclarable is going to
2275   // need them for profiling
2276   TemplateParameterList *Params = Record.readTemplateParameterList();
2277   D->TemplateParams = Params;
2278   D->ArgsAsWritten = Record.readASTTemplateArgumentListInfo();
2279 
2280   RedeclarableResult Redecl = VisitClassTemplateSpecializationDeclImpl(D);
2281 
2282   // These are read/set from/to the first declaration.
2283   if (ThisDeclID == Redecl.getFirstID()) {
2284     D->InstantiatedFromMember.setPointer(
2285       readDeclAs<ClassTemplatePartialSpecializationDecl>());
2286     D->InstantiatedFromMember.setInt(Record.readInt());
2287   }
2288 }
2289 
2290 void ASTDeclReader::VisitClassScopeFunctionSpecializationDecl(
2291                                     ClassScopeFunctionSpecializationDecl *D) {
2292   VisitDecl(D);
2293   D->Specialization = readDeclAs<CXXMethodDecl>();
2294   if (Record.readInt())
2295     D->TemplateArgs = Record.readASTTemplateArgumentListInfo();
2296 }
2297 
2298 void ASTDeclReader::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
2299   RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
2300 
2301   if (ThisDeclID == Redecl.getFirstID()) {
2302     // This FunctionTemplateDecl owns a CommonPtr; read it.
2303     SmallVector<serialization::DeclID, 32> SpecIDs;
2304     readDeclIDList(SpecIDs);
2305     ASTDeclReader::AddLazySpecializations(D, SpecIDs);
2306   }
2307 }
2308 
2309 /// TODO: Unify with ClassTemplateSpecializationDecl version?
2310 ///       May require unifying ClassTemplate(Partial)SpecializationDecl and
2311 ///        VarTemplate(Partial)SpecializationDecl with a new data
2312 ///        structure Template(Partial)SpecializationDecl, and
2313 ///        using Template(Partial)SpecializationDecl as input type.
2314 ASTDeclReader::RedeclarableResult
2315 ASTDeclReader::VisitVarTemplateSpecializationDeclImpl(
2316     VarTemplateSpecializationDecl *D) {
2317   RedeclarableResult Redecl = VisitVarDeclImpl(D);
2318 
2319   ASTContext &C = Reader.getContext();
2320   if (Decl *InstD = readDecl()) {
2321     if (auto *VTD = dyn_cast<VarTemplateDecl>(InstD)) {
2322       D->SpecializedTemplate = VTD;
2323     } else {
2324       SmallVector<TemplateArgument, 8> TemplArgs;
2325       Record.readTemplateArgumentList(TemplArgs);
2326       TemplateArgumentList *ArgList = TemplateArgumentList::CreateCopy(
2327           C, TemplArgs);
2328       auto *PS =
2329           new (C)
2330           VarTemplateSpecializationDecl::SpecializedPartialSpecialization();
2331       PS->PartialSpecialization =
2332           cast<VarTemplatePartialSpecializationDecl>(InstD);
2333       PS->TemplateArgs = ArgList;
2334       D->SpecializedTemplate = PS;
2335     }
2336   }
2337 
2338   // Explicit info.
2339   if (TypeSourceInfo *TyInfo = readTypeSourceInfo()) {
2340     auto *ExplicitInfo =
2341         new (C) VarTemplateSpecializationDecl::ExplicitSpecializationInfo;
2342     ExplicitInfo->TypeAsWritten = TyInfo;
2343     ExplicitInfo->ExternLoc = readSourceLocation();
2344     ExplicitInfo->TemplateKeywordLoc = readSourceLocation();
2345     D->ExplicitInfo = ExplicitInfo;
2346   }
2347 
2348   SmallVector<TemplateArgument, 8> TemplArgs;
2349   Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
2350   D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs);
2351   D->PointOfInstantiation = readSourceLocation();
2352   D->SpecializationKind = (TemplateSpecializationKind)Record.readInt();
2353   D->IsCompleteDefinition = Record.readInt();
2354 
2355   bool writtenAsCanonicalDecl = Record.readInt();
2356   if (writtenAsCanonicalDecl) {
2357     auto *CanonPattern = readDeclAs<VarTemplateDecl>();
2358     if (D->isCanonicalDecl()) { // It's kept in the folding set.
2359       // FIXME: If it's already present, merge it.
2360       if (auto *Partial = dyn_cast<VarTemplatePartialSpecializationDecl>(D)) {
2361         CanonPattern->getCommonPtr()->PartialSpecializations
2362             .GetOrInsertNode(Partial);
2363       } else {
2364         CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
2365       }
2366     }
2367   }
2368 
2369   return Redecl;
2370 }
2371 
2372 /// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2373 ///       May require unifying ClassTemplate(Partial)SpecializationDecl and
2374 ///        VarTemplate(Partial)SpecializationDecl with a new data
2375 ///        structure Template(Partial)SpecializationDecl, and
2376 ///        using Template(Partial)SpecializationDecl as input type.
2377 void ASTDeclReader::VisitVarTemplatePartialSpecializationDecl(
2378     VarTemplatePartialSpecializationDecl *D) {
2379   TemplateParameterList *Params = Record.readTemplateParameterList();
2380   D->TemplateParams = Params;
2381   D->ArgsAsWritten = Record.readASTTemplateArgumentListInfo();
2382 
2383   RedeclarableResult Redecl = VisitVarTemplateSpecializationDeclImpl(D);
2384 
2385   // These are read/set from/to the first declaration.
2386   if (ThisDeclID == Redecl.getFirstID()) {
2387     D->InstantiatedFromMember.setPointer(
2388         readDeclAs<VarTemplatePartialSpecializationDecl>());
2389     D->InstantiatedFromMember.setInt(Record.readInt());
2390   }
2391 }
2392 
2393 void ASTDeclReader::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
2394   VisitTypeDecl(D);
2395 
2396   D->setDeclaredWithTypename(Record.readInt());
2397 
2398   if (Record.readBool()) {
2399     NestedNameSpecifierLoc NNS = Record.readNestedNameSpecifierLoc();
2400     DeclarationNameInfo DN = Record.readDeclarationNameInfo();
2401     ConceptDecl *NamedConcept = Record.readDeclAs<ConceptDecl>();
2402     const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
2403     if (Record.readBool())
2404         ArgsAsWritten = Record.readASTTemplateArgumentListInfo();
2405     Expr *ImmediatelyDeclaredConstraint = Record.readExpr();
2406     D->setTypeConstraint(NNS, DN, /*FoundDecl=*/nullptr, NamedConcept,
2407                          ArgsAsWritten, ImmediatelyDeclaredConstraint);
2408     if ((D->ExpandedParameterPack = Record.readInt()))
2409       D->NumExpanded = Record.readInt();
2410   }
2411 
2412   if (Record.readInt())
2413     D->setDefaultArgument(readTypeSourceInfo());
2414 }
2415 
2416 void ASTDeclReader::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
2417   VisitDeclaratorDecl(D);
2418   // TemplateParmPosition.
2419   D->setDepth(Record.readInt());
2420   D->setPosition(Record.readInt());
2421   if (D->hasPlaceholderTypeConstraint())
2422     D->setPlaceholderTypeConstraint(Record.readExpr());
2423   if (D->isExpandedParameterPack()) {
2424     auto TypesAndInfos =
2425         D->getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>();
2426     for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
2427       new (&TypesAndInfos[I].first) QualType(Record.readType());
2428       TypesAndInfos[I].second = readTypeSourceInfo();
2429     }
2430   } else {
2431     // Rest of NonTypeTemplateParmDecl.
2432     D->ParameterPack = Record.readInt();
2433     if (Record.readInt())
2434       D->setDefaultArgument(Record.readExpr());
2435   }
2436 }
2437 
2438 void ASTDeclReader::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
2439   VisitTemplateDecl(D);
2440   // TemplateParmPosition.
2441   D->setDepth(Record.readInt());
2442   D->setPosition(Record.readInt());
2443   if (D->isExpandedParameterPack()) {
2444     auto **Data = D->getTrailingObjects<TemplateParameterList *>();
2445     for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
2446          I != N; ++I)
2447       Data[I] = Record.readTemplateParameterList();
2448   } else {
2449     // Rest of TemplateTemplateParmDecl.
2450     D->ParameterPack = Record.readInt();
2451     if (Record.readInt())
2452       D->setDefaultArgument(Reader.getContext(),
2453                             Record.readTemplateArgumentLoc());
2454   }
2455 }
2456 
2457 void ASTDeclReader::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
2458   VisitRedeclarableTemplateDecl(D);
2459 }
2460 
2461 void ASTDeclReader::VisitStaticAssertDecl(StaticAssertDecl *D) {
2462   VisitDecl(D);
2463   D->AssertExprAndFailed.setPointer(Record.readExpr());
2464   D->AssertExprAndFailed.setInt(Record.readInt());
2465   D->Message = cast_or_null<StringLiteral>(Record.readExpr());
2466   D->RParenLoc = readSourceLocation();
2467 }
2468 
2469 void ASTDeclReader::VisitEmptyDecl(EmptyDecl *D) {
2470   VisitDecl(D);
2471 }
2472 
2473 void ASTDeclReader::VisitLifetimeExtendedTemporaryDecl(
2474     LifetimeExtendedTemporaryDecl *D) {
2475   VisitDecl(D);
2476   D->ExtendingDecl = readDeclAs<ValueDecl>();
2477   D->ExprWithTemporary = Record.readStmt();
2478   if (Record.readInt()) {
2479     D->Value = new (D->getASTContext()) APValue(Record.readAPValue());
2480     D->getASTContext().addDestruction(D->Value);
2481   }
2482   D->ManglingNumber = Record.readInt();
2483   mergeMergeable(D);
2484 }
2485 
2486 std::pair<uint64_t, uint64_t>
2487 ASTDeclReader::VisitDeclContext(DeclContext *DC) {
2488   uint64_t LexicalOffset = ReadLocalOffset();
2489   uint64_t VisibleOffset = ReadLocalOffset();
2490   return std::make_pair(LexicalOffset, VisibleOffset);
2491 }
2492 
2493 template <typename T>
2494 ASTDeclReader::RedeclarableResult
2495 ASTDeclReader::VisitRedeclarable(Redeclarable<T> *D) {
2496   DeclID FirstDeclID = readDeclID();
2497   Decl *MergeWith = nullptr;
2498 
2499   bool IsKeyDecl = ThisDeclID == FirstDeclID;
2500   bool IsFirstLocalDecl = false;
2501 
2502   uint64_t RedeclOffset = 0;
2503 
2504   // 0 indicates that this declaration was the only declaration of its entity,
2505   // and is used for space optimization.
2506   if (FirstDeclID == 0) {
2507     FirstDeclID = ThisDeclID;
2508     IsKeyDecl = true;
2509     IsFirstLocalDecl = true;
2510   } else if (unsigned N = Record.readInt()) {
2511     // This declaration was the first local declaration, but may have imported
2512     // other declarations.
2513     IsKeyDecl = N == 1;
2514     IsFirstLocalDecl = true;
2515 
2516     // We have some declarations that must be before us in our redeclaration
2517     // chain. Read them now, and remember that we ought to merge with one of
2518     // them.
2519     // FIXME: Provide a known merge target to the second and subsequent such
2520     // declaration.
2521     for (unsigned I = 0; I != N - 1; ++I)
2522       MergeWith = readDecl();
2523 
2524     RedeclOffset = ReadLocalOffset();
2525   } else {
2526     // This declaration was not the first local declaration. Read the first
2527     // local declaration now, to trigger the import of other redeclarations.
2528     (void)readDecl();
2529   }
2530 
2531   auto *FirstDecl = cast_or_null<T>(Reader.GetDecl(FirstDeclID));
2532   if (FirstDecl != D) {
2533     // We delay loading of the redeclaration chain to avoid deeply nested calls.
2534     // We temporarily set the first (canonical) declaration as the previous one
2535     // which is the one that matters and mark the real previous DeclID to be
2536     // loaded & attached later on.
2537     D->RedeclLink = Redeclarable<T>::PreviousDeclLink(FirstDecl);
2538     D->First = FirstDecl->getCanonicalDecl();
2539   }
2540 
2541   auto *DAsT = static_cast<T *>(D);
2542 
2543   // Note that we need to load local redeclarations of this decl and build a
2544   // decl chain for them. This must happen *after* we perform the preloading
2545   // above; this ensures that the redeclaration chain is built in the correct
2546   // order.
2547   if (IsFirstLocalDecl)
2548     Reader.PendingDeclChains.push_back(std::make_pair(DAsT, RedeclOffset));
2549 
2550   return RedeclarableResult(MergeWith, FirstDeclID, IsKeyDecl);
2551 }
2552 
2553 /// Attempts to merge the given declaration (D) with another declaration
2554 /// of the same entity.
2555 template<typename T>
2556 void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *DBase,
2557                                       RedeclarableResult &Redecl,
2558                                       DeclID TemplatePatternID) {
2559   // If modules are not available, there is no reason to perform this merge.
2560   if (!Reader.getContext().getLangOpts().Modules)
2561     return;
2562 
2563   // If we're not the canonical declaration, we don't need to merge.
2564   if (!DBase->isFirstDecl())
2565     return;
2566 
2567   auto *D = static_cast<T *>(DBase);
2568 
2569   if (auto *Existing = Redecl.getKnownMergeTarget())
2570     // We already know of an existing declaration we should merge with.
2571     mergeRedeclarable(D, cast<T>(Existing), Redecl, TemplatePatternID);
2572   else if (FindExistingResult ExistingRes = findExisting(D))
2573     if (T *Existing = ExistingRes)
2574       mergeRedeclarable(D, Existing, Redecl, TemplatePatternID);
2575 }
2576 
2577 /// "Cast" to type T, asserting if we don't have an implicit conversion.
2578 /// We use this to put code in a template that will only be valid for certain
2579 /// instantiations.
2580 template<typename T> static T assert_cast(T t) { return t; }
2581 template<typename T> static T assert_cast(...) {
2582   llvm_unreachable("bad assert_cast");
2583 }
2584 
2585 /// Merge together the pattern declarations from two template
2586 /// declarations.
2587 void ASTDeclReader::mergeTemplatePattern(RedeclarableTemplateDecl *D,
2588                                          RedeclarableTemplateDecl *Existing,
2589                                          DeclID DsID, bool IsKeyDecl) {
2590   auto *DPattern = D->getTemplatedDecl();
2591   auto *ExistingPattern = Existing->getTemplatedDecl();
2592   RedeclarableResult Result(/*MergeWith*/ ExistingPattern,
2593                             DPattern->getCanonicalDecl()->getGlobalID(),
2594                             IsKeyDecl);
2595 
2596   if (auto *DClass = dyn_cast<CXXRecordDecl>(DPattern)) {
2597     // Merge with any existing definition.
2598     // FIXME: This is duplicated in several places. Refactor.
2599     auto *ExistingClass =
2600         cast<CXXRecordDecl>(ExistingPattern)->getCanonicalDecl();
2601     if (auto *DDD = DClass->DefinitionData) {
2602       if (ExistingClass->DefinitionData) {
2603         MergeDefinitionData(ExistingClass, std::move(*DDD));
2604       } else {
2605         ExistingClass->DefinitionData = DClass->DefinitionData;
2606         // We may have skipped this before because we thought that DClass
2607         // was the canonical declaration.
2608         Reader.PendingDefinitions.insert(DClass);
2609       }
2610     }
2611     DClass->DefinitionData = ExistingClass->DefinitionData;
2612 
2613     return mergeRedeclarable(DClass, cast<TagDecl>(ExistingPattern),
2614                              Result);
2615   }
2616   if (auto *DFunction = dyn_cast<FunctionDecl>(DPattern))
2617     return mergeRedeclarable(DFunction, cast<FunctionDecl>(ExistingPattern),
2618                              Result);
2619   if (auto *DVar = dyn_cast<VarDecl>(DPattern))
2620     return mergeRedeclarable(DVar, cast<VarDecl>(ExistingPattern), Result);
2621   if (auto *DAlias = dyn_cast<TypeAliasDecl>(DPattern))
2622     return mergeRedeclarable(DAlias, cast<TypedefNameDecl>(ExistingPattern),
2623                              Result);
2624   llvm_unreachable("merged an unknown kind of redeclarable template");
2625 }
2626 
2627 /// Attempts to merge the given declaration (D) with another declaration
2628 /// of the same entity.
2629 template<typename T>
2630 void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *DBase, T *Existing,
2631                                       RedeclarableResult &Redecl,
2632                                       DeclID TemplatePatternID) {
2633   auto *D = static_cast<T *>(DBase);
2634   T *ExistingCanon = Existing->getCanonicalDecl();
2635   T *DCanon = D->getCanonicalDecl();
2636   if (ExistingCanon != DCanon) {
2637     assert(DCanon->getGlobalID() == Redecl.getFirstID() &&
2638            "already merged this declaration");
2639 
2640     // Have our redeclaration link point back at the canonical declaration
2641     // of the existing declaration, so that this declaration has the
2642     // appropriate canonical declaration.
2643     D->RedeclLink = Redeclarable<T>::PreviousDeclLink(ExistingCanon);
2644     D->First = ExistingCanon;
2645     ExistingCanon->Used |= D->Used;
2646     D->Used = false;
2647 
2648     // When we merge a namespace, update its pointer to the first namespace.
2649     // We cannot have loaded any redeclarations of this declaration yet, so
2650     // there's nothing else that needs to be updated.
2651     if (auto *Namespace = dyn_cast<NamespaceDecl>(D))
2652       Namespace->AnonOrFirstNamespaceAndInline.setPointer(
2653           assert_cast<NamespaceDecl*>(ExistingCanon));
2654 
2655     // When we merge a template, merge its pattern.
2656     if (auto *DTemplate = dyn_cast<RedeclarableTemplateDecl>(D))
2657       mergeTemplatePattern(
2658           DTemplate, assert_cast<RedeclarableTemplateDecl*>(ExistingCanon),
2659           TemplatePatternID, Redecl.isKeyDecl());
2660 
2661     // If this declaration is a key declaration, make a note of that.
2662     if (Redecl.isKeyDecl())
2663       Reader.KeyDecls[ExistingCanon].push_back(Redecl.getFirstID());
2664   }
2665 }
2666 
2667 /// ODR-like semantics for C/ObjC allow us to merge tag types and a structural
2668 /// check in Sema guarantees the types can be merged (see C11 6.2.7/1 or C89
2669 /// 6.1.2.6/1). Although most merging is done in Sema, we need to guarantee
2670 /// that some types are mergeable during deserialization, otherwise name
2671 /// lookup fails. This is the case for EnumConstantDecl.
2672 static bool allowODRLikeMergeInC(NamedDecl *ND) {
2673   if (!ND)
2674     return false;
2675   // TODO: implement merge for other necessary decls.
2676   if (isa<EnumConstantDecl, FieldDecl, IndirectFieldDecl>(ND))
2677     return true;
2678   return false;
2679 }
2680 
2681 /// Attempts to merge LifetimeExtendedTemporaryDecl with
2682 /// identical class definitions from two different modules.
2683 void ASTDeclReader::mergeMergeable(LifetimeExtendedTemporaryDecl *D) {
2684   // If modules are not available, there is no reason to perform this merge.
2685   if (!Reader.getContext().getLangOpts().Modules)
2686     return;
2687 
2688   LifetimeExtendedTemporaryDecl *LETDecl = D;
2689 
2690   LifetimeExtendedTemporaryDecl *&LookupResult =
2691       Reader.LETemporaryForMerging[std::make_pair(
2692           LETDecl->getExtendingDecl(), LETDecl->getManglingNumber())];
2693   if (LookupResult)
2694     Reader.getContext().setPrimaryMergedDecl(LETDecl,
2695                                              LookupResult->getCanonicalDecl());
2696   else
2697     LookupResult = LETDecl;
2698 }
2699 
2700 /// Attempts to merge the given declaration (D) with another declaration
2701 /// of the same entity, for the case where the entity is not actually
2702 /// redeclarable. This happens, for instance, when merging the fields of
2703 /// identical class definitions from two different modules.
2704 template<typename T>
2705 void ASTDeclReader::mergeMergeable(Mergeable<T> *D) {
2706   // If modules are not available, there is no reason to perform this merge.
2707   if (!Reader.getContext().getLangOpts().Modules)
2708     return;
2709 
2710   // ODR-based merging is performed in C++ and in some cases (tag types) in C.
2711   // Note that C identically-named things in different translation units are
2712   // not redeclarations, but may still have compatible types, where ODR-like
2713   // semantics may apply.
2714   if (!Reader.getContext().getLangOpts().CPlusPlus &&
2715       !allowODRLikeMergeInC(dyn_cast<NamedDecl>(static_cast<T*>(D))))
2716     return;
2717 
2718   if (FindExistingResult ExistingRes = findExisting(static_cast<T*>(D)))
2719     if (T *Existing = ExistingRes)
2720       Reader.getContext().setPrimaryMergedDecl(static_cast<T *>(D),
2721                                                Existing->getCanonicalDecl());
2722 }
2723 
2724 void ASTDeclReader::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {
2725   Record.readOMPChildren(D->Data);
2726   VisitDecl(D);
2727 }
2728 
2729 void ASTDeclReader::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
2730   Record.readOMPChildren(D->Data);
2731   VisitDecl(D);
2732 }
2733 
2734 void ASTDeclReader::VisitOMPRequiresDecl(OMPRequiresDecl * D) {
2735   Record.readOMPChildren(D->Data);
2736   VisitDecl(D);
2737 }
2738 
2739 void ASTDeclReader::VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D) {
2740   VisitValueDecl(D);
2741   D->setLocation(readSourceLocation());
2742   Expr *In = Record.readExpr();
2743   Expr *Out = Record.readExpr();
2744   D->setCombinerData(In, Out);
2745   Expr *Combiner = Record.readExpr();
2746   D->setCombiner(Combiner);
2747   Expr *Orig = Record.readExpr();
2748   Expr *Priv = Record.readExpr();
2749   D->setInitializerData(Orig, Priv);
2750   Expr *Init = Record.readExpr();
2751   auto IK = static_cast<OMPDeclareReductionDecl::InitKind>(Record.readInt());
2752   D->setInitializer(Init, IK);
2753   D->PrevDeclInScope = readDeclID();
2754 }
2755 
2756 void ASTDeclReader::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
2757   Record.readOMPChildren(D->Data);
2758   VisitValueDecl(D);
2759   D->VarName = Record.readDeclarationName();
2760   D->PrevDeclInScope = readDeclID();
2761 }
2762 
2763 void ASTDeclReader::VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D) {
2764   VisitVarDecl(D);
2765 }
2766 
2767 //===----------------------------------------------------------------------===//
2768 // Attribute Reading
2769 //===----------------------------------------------------------------------===//
2770 
2771 namespace {
2772 class AttrReader {
2773   ASTRecordReader &Reader;
2774 
2775 public:
2776   AttrReader(ASTRecordReader &Reader) : Reader(Reader) {}
2777 
2778   uint64_t readInt() {
2779     return Reader.readInt();
2780   }
2781 
2782   SourceRange readSourceRange() {
2783     return Reader.readSourceRange();
2784   }
2785 
2786   SourceLocation readSourceLocation() {
2787     return Reader.readSourceLocation();
2788   }
2789 
2790   Expr *readExpr() { return Reader.readExpr(); }
2791 
2792   std::string readString() {
2793     return Reader.readString();
2794   }
2795 
2796   TypeSourceInfo *readTypeSourceInfo() {
2797     return Reader.readTypeSourceInfo();
2798   }
2799 
2800   IdentifierInfo *readIdentifier() {
2801     return Reader.readIdentifier();
2802   }
2803 
2804   VersionTuple readVersionTuple() {
2805     return Reader.readVersionTuple();
2806   }
2807 
2808   OMPTraitInfo *readOMPTraitInfo() { return Reader.readOMPTraitInfo(); }
2809 
2810   template <typename T> T *GetLocalDeclAs(uint32_t LocalID) {
2811     return Reader.GetLocalDeclAs<T>(LocalID);
2812   }
2813 };
2814 }
2815 
2816 Attr *ASTRecordReader::readAttr() {
2817   AttrReader Record(*this);
2818   auto V = Record.readInt();
2819   if (!V)
2820     return nullptr;
2821 
2822   Attr *New = nullptr;
2823   // Kind is stored as a 1-based integer because 0 is used to indicate a null
2824   // Attr pointer.
2825   auto Kind = static_cast<attr::Kind>(V - 1);
2826   ASTContext &Context = getContext();
2827 
2828   IdentifierInfo *AttrName = Record.readIdentifier();
2829   IdentifierInfo *ScopeName = Record.readIdentifier();
2830   SourceRange AttrRange = Record.readSourceRange();
2831   SourceLocation ScopeLoc = Record.readSourceLocation();
2832   unsigned ParsedKind = Record.readInt();
2833   unsigned Syntax = Record.readInt();
2834   unsigned SpellingIndex = Record.readInt();
2835 
2836   AttributeCommonInfo Info(AttrName, ScopeName, AttrRange, ScopeLoc,
2837                            AttributeCommonInfo::Kind(ParsedKind),
2838                            AttributeCommonInfo::Syntax(Syntax), SpellingIndex);
2839 
2840 #include "clang/Serialization/AttrPCHRead.inc"
2841 
2842   assert(New && "Unable to decode attribute?");
2843   return New;
2844 }
2845 
2846 /// Reads attributes from the current stream position.
2847 void ASTRecordReader::readAttributes(AttrVec &Attrs) {
2848   for (unsigned I = 0, E = readInt(); I != E; ++I)
2849     Attrs.push_back(readAttr());
2850 }
2851 
2852 //===----------------------------------------------------------------------===//
2853 // ASTReader Implementation
2854 //===----------------------------------------------------------------------===//
2855 
2856 /// Note that we have loaded the declaration with the given
2857 /// Index.
2858 ///
2859 /// This routine notes that this declaration has already been loaded,
2860 /// so that future GetDecl calls will return this declaration rather
2861 /// than trying to load a new declaration.
2862 inline void ASTReader::LoadedDecl(unsigned Index, Decl *D) {
2863   assert(!DeclsLoaded[Index] && "Decl loaded twice?");
2864   DeclsLoaded[Index] = D;
2865 }
2866 
2867 /// Determine whether the consumer will be interested in seeing
2868 /// this declaration (via HandleTopLevelDecl).
2869 ///
2870 /// This routine should return true for anything that might affect
2871 /// code generation, e.g., inline function definitions, Objective-C
2872 /// declarations with metadata, etc.
2873 static bool isConsumerInterestedIn(ASTContext &Ctx, Decl *D, bool HasBody) {
2874   // An ObjCMethodDecl is never considered as "interesting" because its
2875   // implementation container always is.
2876 
2877   // An ImportDecl or VarDecl imported from a module map module will get
2878   // emitted when we import the relevant module.
2879   if (isPartOfPerModuleInitializer(D)) {
2880     auto *M = D->getImportedOwningModule();
2881     if (M && M->Kind == Module::ModuleMapModule &&
2882         Ctx.DeclMustBeEmitted(D))
2883       return false;
2884   }
2885 
2886   if (isa<FileScopeAsmDecl>(D) ||
2887       isa<ObjCProtocolDecl>(D) ||
2888       isa<ObjCImplDecl>(D) ||
2889       isa<ImportDecl>(D) ||
2890       isa<PragmaCommentDecl>(D) ||
2891       isa<PragmaDetectMismatchDecl>(D))
2892     return true;
2893   if (isa<OMPThreadPrivateDecl>(D) || isa<OMPDeclareReductionDecl>(D) ||
2894       isa<OMPDeclareMapperDecl>(D) || isa<OMPAllocateDecl>(D) ||
2895       isa<OMPRequiresDecl>(D))
2896     return !D->getDeclContext()->isFunctionOrMethod();
2897   if (const auto *Var = dyn_cast<VarDecl>(D))
2898     return Var->isFileVarDecl() &&
2899            (Var->isThisDeclarationADefinition() == VarDecl::Definition ||
2900             OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Var));
2901   if (const auto *Func = dyn_cast<FunctionDecl>(D))
2902     return Func->doesThisDeclarationHaveABody() || HasBody;
2903 
2904   if (auto *ES = D->getASTContext().getExternalSource())
2905     if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
2906       return true;
2907 
2908   return false;
2909 }
2910 
2911 /// Get the correct cursor and offset for loading a declaration.
2912 ASTReader::RecordLocation
2913 ASTReader::DeclCursorForID(DeclID ID, SourceLocation &Loc) {
2914   GlobalDeclMapType::iterator I = GlobalDeclMap.find(ID);
2915   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
2916   ModuleFile *M = I->second;
2917   const DeclOffset &DOffs =
2918       M->DeclOffsets[ID - M->BaseDeclID - NUM_PREDEF_DECL_IDS];
2919   Loc = TranslateSourceLocation(*M, DOffs.getLocation());
2920   return RecordLocation(M, DOffs.getBitOffset(M->DeclsBlockStartOffset));
2921 }
2922 
2923 ASTReader::RecordLocation ASTReader::getLocalBitOffset(uint64_t GlobalOffset) {
2924   auto I = GlobalBitOffsetsMap.find(GlobalOffset);
2925 
2926   assert(I != GlobalBitOffsetsMap.end() && "Corrupted global bit offsets map");
2927   return RecordLocation(I->second, GlobalOffset - I->second->GlobalBitOffset);
2928 }
2929 
2930 uint64_t ASTReader::getGlobalBitOffset(ModuleFile &M, uint64_t LocalOffset) {
2931   return LocalOffset + M.GlobalBitOffset;
2932 }
2933 
2934 static bool isSameTemplateParameterList(const ASTContext &C,
2935                                         const TemplateParameterList *X,
2936                                         const TemplateParameterList *Y);
2937 
2938 /// Determine whether two template parameters are similar enough
2939 /// that they may be used in declarations of the same template.
2940 static bool isSameTemplateParameter(const NamedDecl *X,
2941                                     const NamedDecl *Y) {
2942   if (X->getKind() != Y->getKind())
2943     return false;
2944 
2945   if (const auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
2946     const auto *TY = cast<TemplateTypeParmDecl>(Y);
2947     if (TX->isParameterPack() != TY->isParameterPack())
2948       return false;
2949     if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
2950       return false;
2951     const TypeConstraint *TXTC = TX->getTypeConstraint();
2952     const TypeConstraint *TYTC = TY->getTypeConstraint();
2953     if (!TXTC != !TYTC)
2954       return false;
2955     if (TXTC && TYTC) {
2956       if (TXTC->getNamedConcept() != TYTC->getNamedConcept())
2957         return false;
2958       if (TXTC->hasExplicitTemplateArgs() != TYTC->hasExplicitTemplateArgs())
2959         return false;
2960       if (TXTC->hasExplicitTemplateArgs()) {
2961         const auto *TXTCArgs = TXTC->getTemplateArgsAsWritten();
2962         const auto *TYTCArgs = TYTC->getTemplateArgsAsWritten();
2963         if (TXTCArgs->NumTemplateArgs != TYTCArgs->NumTemplateArgs)
2964           return false;
2965         llvm::FoldingSetNodeID XID, YID;
2966         for (const auto &ArgLoc : TXTCArgs->arguments())
2967           ArgLoc.getArgument().Profile(XID, X->getASTContext());
2968         for (const auto &ArgLoc : TYTCArgs->arguments())
2969           ArgLoc.getArgument().Profile(YID, Y->getASTContext());
2970         if (XID != YID)
2971           return false;
2972       }
2973     }
2974     return true;
2975   }
2976 
2977   if (const auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
2978     const auto *TY = cast<NonTypeTemplateParmDecl>(Y);
2979     return TX->isParameterPack() == TY->isParameterPack() &&
2980            TX->getASTContext().hasSameType(TX->getType(), TY->getType());
2981   }
2982 
2983   const auto *TX = cast<TemplateTemplateParmDecl>(X);
2984   const auto *TY = cast<TemplateTemplateParmDecl>(Y);
2985   return TX->isParameterPack() == TY->isParameterPack() &&
2986          isSameTemplateParameterList(TX->getASTContext(),
2987                                      TX->getTemplateParameters(),
2988                                      TY->getTemplateParameters());
2989 }
2990 
2991 static NamespaceDecl *getNamespace(const NestedNameSpecifier *X) {
2992   if (auto *NS = X->getAsNamespace())
2993     return NS;
2994   if (auto *NAS = X->getAsNamespaceAlias())
2995     return NAS->getNamespace();
2996   return nullptr;
2997 }
2998 
2999 static bool isSameQualifier(const NestedNameSpecifier *X,
3000                             const NestedNameSpecifier *Y) {
3001   if (auto *NSX = getNamespace(X)) {
3002     auto *NSY = getNamespace(Y);
3003     if (!NSY || NSX->getCanonicalDecl() != NSY->getCanonicalDecl())
3004       return false;
3005   } else if (X->getKind() != Y->getKind())
3006     return false;
3007 
3008   // FIXME: For namespaces and types, we're permitted to check that the entity
3009   // is named via the same tokens. We should probably do so.
3010   switch (X->getKind()) {
3011   case NestedNameSpecifier::Identifier:
3012     if (X->getAsIdentifier() != Y->getAsIdentifier())
3013       return false;
3014     break;
3015   case NestedNameSpecifier::Namespace:
3016   case NestedNameSpecifier::NamespaceAlias:
3017     // We've already checked that we named the same namespace.
3018     break;
3019   case NestedNameSpecifier::TypeSpec:
3020   case NestedNameSpecifier::TypeSpecWithTemplate:
3021     if (X->getAsType()->getCanonicalTypeInternal() !=
3022         Y->getAsType()->getCanonicalTypeInternal())
3023       return false;
3024     break;
3025   case NestedNameSpecifier::Global:
3026   case NestedNameSpecifier::Super:
3027     return true;
3028   }
3029 
3030   // Recurse into earlier portion of NNS, if any.
3031   auto *PX = X->getPrefix();
3032   auto *PY = Y->getPrefix();
3033   if (PX && PY)
3034     return isSameQualifier(PX, PY);
3035   return !PX && !PY;
3036 }
3037 
3038 /// Determine whether two template parameter lists are similar enough
3039 /// that they may be used in declarations of the same template.
3040 static bool isSameTemplateParameterList(const ASTContext &C,
3041                                         const TemplateParameterList *X,
3042                                         const TemplateParameterList *Y) {
3043   if (X->size() != Y->size())
3044     return false;
3045 
3046   for (unsigned I = 0, N = X->size(); I != N; ++I)
3047     if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
3048       return false;
3049 
3050   const Expr *XRC = X->getRequiresClause();
3051   const Expr *YRC = Y->getRequiresClause();
3052   if (!XRC != !YRC)
3053     return false;
3054   if (XRC) {
3055     llvm::FoldingSetNodeID XRCID, YRCID;
3056     XRC->Profile(XRCID, C, /*Canonical=*/true);
3057     YRC->Profile(YRCID, C, /*Canonical=*/true);
3058     if (XRCID != YRCID)
3059       return false;
3060   }
3061 
3062   return true;
3063 }
3064 
3065 /// Determine whether the attributes we can overload on are identical for A and
3066 /// B. Will ignore any overloadable attrs represented in the type of A and B.
3067 static bool hasSameOverloadableAttrs(const FunctionDecl *A,
3068                                      const FunctionDecl *B) {
3069   // Note that pass_object_size attributes are represented in the function's
3070   // ExtParameterInfo, so we don't need to check them here.
3071 
3072   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
3073   auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
3074   auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
3075 
3076   for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
3077     Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
3078     Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
3079 
3080     // Return false if the number of enable_if attributes is different.
3081     if (!Cand1A || !Cand2A)
3082       return false;
3083 
3084     Cand1ID.clear();
3085     Cand2ID.clear();
3086 
3087     (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
3088     (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
3089 
3090     // Return false if any of the enable_if expressions of A and B are
3091     // different.
3092     if (Cand1ID != Cand2ID)
3093       return false;
3094   }
3095   return true;
3096 }
3097 
3098 /// Determine whether the two declarations refer to the same entity.
3099 static bool isSameEntity(NamedDecl *X, NamedDecl *Y) {
3100   assert(X->getDeclName() == Y->getDeclName() && "Declaration name mismatch!");
3101 
3102   if (X == Y)
3103     return true;
3104 
3105   // Must be in the same context.
3106   //
3107   // Note that we can't use DeclContext::Equals here, because the DeclContexts
3108   // could be two different declarations of the same function. (We will fix the
3109   // semantic DC to refer to the primary definition after merging.)
3110   if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
3111                           cast<Decl>(Y->getDeclContext()->getRedeclContext())))
3112     return false;
3113 
3114   // Two typedefs refer to the same entity if they have the same underlying
3115   // type.
3116   if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
3117     if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
3118       return X->getASTContext().hasSameType(TypedefX->getUnderlyingType(),
3119                                             TypedefY->getUnderlyingType());
3120 
3121   // Must have the same kind.
3122   if (X->getKind() != Y->getKind())
3123     return false;
3124 
3125   // Objective-C classes and protocols with the same name always match.
3126   if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
3127     return true;
3128 
3129   if (isa<ClassTemplateSpecializationDecl>(X)) {
3130     // No need to handle these here: we merge them when adding them to the
3131     // template.
3132     return false;
3133   }
3134 
3135   // Compatible tags match.
3136   if (const auto *TagX = dyn_cast<TagDecl>(X)) {
3137     const auto *TagY = cast<TagDecl>(Y);
3138     return (TagX->getTagKind() == TagY->getTagKind()) ||
3139       ((TagX->getTagKind() == TTK_Struct || TagX->getTagKind() == TTK_Class ||
3140         TagX->getTagKind() == TTK_Interface) &&
3141        (TagY->getTagKind() == TTK_Struct || TagY->getTagKind() == TTK_Class ||
3142         TagY->getTagKind() == TTK_Interface));
3143   }
3144 
3145   // Functions with the same type and linkage match.
3146   // FIXME: This needs to cope with merging of prototyped/non-prototyped
3147   // functions, etc.
3148   if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
3149     const auto *FuncY = cast<FunctionDecl>(Y);
3150     if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
3151       const auto *CtorY = cast<CXXConstructorDecl>(Y);
3152       if (CtorX->getInheritedConstructor() &&
3153           !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
3154                         CtorY->getInheritedConstructor().getConstructor()))
3155         return false;
3156     }
3157 
3158     if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
3159       return false;
3160 
3161     // Multiversioned functions with different feature strings are represented
3162     // as separate declarations.
3163     if (FuncX->isMultiVersion()) {
3164       const auto *TAX = FuncX->getAttr<TargetAttr>();
3165       const auto *TAY = FuncY->getAttr<TargetAttr>();
3166       assert(TAX && TAY && "Multiversion Function without target attribute");
3167 
3168       if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
3169         return false;
3170     }
3171 
3172     ASTContext &C = FuncX->getASTContext();
3173 
3174     const Expr *XRC = FuncX->getTrailingRequiresClause();
3175     const Expr *YRC = FuncY->getTrailingRequiresClause();
3176     if (!XRC != !YRC)
3177       return false;
3178     if (XRC) {
3179       llvm::FoldingSetNodeID XRCID, YRCID;
3180       XRC->Profile(XRCID, C, /*Canonical=*/true);
3181       YRC->Profile(YRCID, C, /*Canonical=*/true);
3182       if (XRCID != YRCID)
3183         return false;
3184     }
3185 
3186     auto GetTypeAsWritten = [](const FunctionDecl *FD) {
3187       // Map to the first declaration that we've already merged into this one.
3188       // The TSI of redeclarations might not match (due to calling conventions
3189       // being inherited onto the type but not the TSI), but the TSI type of
3190       // the first declaration of the function should match across modules.
3191       FD = FD->getCanonicalDecl();
3192       return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
3193                                      : FD->getType();
3194     };
3195     QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
3196     if (!C.hasSameType(XT, YT)) {
3197       // We can get functions with different types on the redecl chain in C++17
3198       // if they have differing exception specifications and at least one of
3199       // the excpetion specs is unresolved.
3200       auto *XFPT = XT->getAs<FunctionProtoType>();
3201       auto *YFPT = YT->getAs<FunctionProtoType>();
3202       if (C.getLangOpts().CPlusPlus17 && XFPT && YFPT &&
3203           (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
3204            isUnresolvedExceptionSpec(YFPT->getExceptionSpecType())) &&
3205           C.hasSameFunctionTypeIgnoringExceptionSpec(XT, YT))
3206         return true;
3207       return false;
3208     }
3209 
3210     return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
3211            hasSameOverloadableAttrs(FuncX, FuncY);
3212   }
3213 
3214   // Variables with the same type and linkage match.
3215   if (const auto *VarX = dyn_cast<VarDecl>(X)) {
3216     const auto *VarY = cast<VarDecl>(Y);
3217     if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
3218       ASTContext &C = VarX->getASTContext();
3219       if (C.hasSameType(VarX->getType(), VarY->getType()))
3220         return true;
3221 
3222       // We can get decls with different types on the redecl chain. Eg.
3223       // template <typename T> struct S { static T Var[]; }; // #1
3224       // template <typename T> T S<T>::Var[sizeof(T)]; // #2
3225       // Only? happens when completing an incomplete array type. In this case
3226       // when comparing #1 and #2 we should go through their element type.
3227       const ArrayType *VarXTy = C.getAsArrayType(VarX->getType());
3228       const ArrayType *VarYTy = C.getAsArrayType(VarY->getType());
3229       if (!VarXTy || !VarYTy)
3230         return false;
3231       if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
3232         return C.hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
3233     }
3234     return false;
3235   }
3236 
3237   // Namespaces with the same name and inlinedness match.
3238   if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
3239     const auto *NamespaceY = cast<NamespaceDecl>(Y);
3240     return NamespaceX->isInline() == NamespaceY->isInline();
3241   }
3242 
3243   // Identical template names and kinds match if their template parameter lists
3244   // and patterns match.
3245   if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
3246     const auto *TemplateY = cast<TemplateDecl>(Y);
3247     return isSameEntity(TemplateX->getTemplatedDecl(),
3248                         TemplateY->getTemplatedDecl()) &&
3249            isSameTemplateParameterList(TemplateX->getASTContext(),
3250                                        TemplateX->getTemplateParameters(),
3251                                        TemplateY->getTemplateParameters());
3252   }
3253 
3254   // Fields with the same name and the same type match.
3255   if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
3256     const auto *FDY = cast<FieldDecl>(Y);
3257     // FIXME: Also check the bitwidth is odr-equivalent, if any.
3258     return X->getASTContext().hasSameType(FDX->getType(), FDY->getType());
3259   }
3260 
3261   // Indirect fields with the same target field match.
3262   if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
3263     const auto *IFDY = cast<IndirectFieldDecl>(Y);
3264     return IFDX->getAnonField()->getCanonicalDecl() ==
3265            IFDY->getAnonField()->getCanonicalDecl();
3266   }
3267 
3268   // Enumerators with the same name match.
3269   if (isa<EnumConstantDecl>(X))
3270     // FIXME: Also check the value is odr-equivalent.
3271     return true;
3272 
3273   // Using shadow declarations with the same target match.
3274   if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
3275     const auto *USY = cast<UsingShadowDecl>(Y);
3276     return USX->getTargetDecl() == USY->getTargetDecl();
3277   }
3278 
3279   // Using declarations with the same qualifier match. (We already know that
3280   // the name matches.)
3281   if (const auto *UX = dyn_cast<UsingDecl>(X)) {
3282     const auto *UY = cast<UsingDecl>(Y);
3283     return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
3284            UX->hasTypename() == UY->hasTypename() &&
3285            UX->isAccessDeclaration() == UY->isAccessDeclaration();
3286   }
3287   if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
3288     const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
3289     return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
3290            UX->isAccessDeclaration() == UY->isAccessDeclaration();
3291   }
3292   if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
3293     return isSameQualifier(
3294         UX->getQualifier(),
3295         cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
3296   }
3297 
3298   // Using-pack declarations are only created by instantiation, and match if
3299   // they're instantiated from matching UnresolvedUsing...Decls.
3300   if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
3301     return declaresSameEntity(
3302         UX->getInstantiatedFromUsingDecl(),
3303         cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
3304   }
3305 
3306   // Namespace alias definitions with the same target match.
3307   if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
3308     const auto *NAY = cast<NamespaceAliasDecl>(Y);
3309     return NAX->getNamespace()->Equals(NAY->getNamespace());
3310   }
3311 
3312   return false;
3313 }
3314 
3315 /// Find the context in which we should search for previous declarations when
3316 /// looking for declarations to merge.
3317 DeclContext *ASTDeclReader::getPrimaryContextForMerging(ASTReader &Reader,
3318                                                         DeclContext *DC) {
3319   if (auto *ND = dyn_cast<NamespaceDecl>(DC))
3320     return ND->getOriginalNamespace();
3321 
3322   if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
3323     // Try to dig out the definition.
3324     auto *DD = RD->DefinitionData;
3325     if (!DD)
3326       DD = RD->getCanonicalDecl()->DefinitionData;
3327 
3328     // If there's no definition yet, then DC's definition is added by an update
3329     // record, but we've not yet loaded that update record. In this case, we
3330     // commit to DC being the canonical definition now, and will fix this when
3331     // we load the update record.
3332     if (!DD) {
3333       DD = new (Reader.getContext()) struct CXXRecordDecl::DefinitionData(RD);
3334       RD->setCompleteDefinition(true);
3335       RD->DefinitionData = DD;
3336       RD->getCanonicalDecl()->DefinitionData = DD;
3337 
3338       // Track that we did this horrible thing so that we can fix it later.
3339       Reader.PendingFakeDefinitionData.insert(
3340           std::make_pair(DD, ASTReader::PendingFakeDefinitionKind::Fake));
3341     }
3342 
3343     return DD->Definition;
3344   }
3345 
3346   if (auto *RD = dyn_cast<RecordDecl>(DC))
3347     return RD->getDefinition();
3348 
3349   if (auto *ED = dyn_cast<EnumDecl>(DC))
3350     return ED->getASTContext().getLangOpts().CPlusPlus? ED->getDefinition()
3351                                                       : nullptr;
3352 
3353   // We can see the TU here only if we have no Sema object. In that case,
3354   // there's no TU scope to look in, so using the DC alone is sufficient.
3355   if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
3356     return TU;
3357 
3358   return nullptr;
3359 }
3360 
3361 ASTDeclReader::FindExistingResult::~FindExistingResult() {
3362   // Record that we had a typedef name for linkage whether or not we merge
3363   // with that declaration.
3364   if (TypedefNameForLinkage) {
3365     DeclContext *DC = New->getDeclContext()->getRedeclContext();
3366     Reader.ImportedTypedefNamesForLinkage.insert(
3367         std::make_pair(std::make_pair(DC, TypedefNameForLinkage), New));
3368     return;
3369   }
3370 
3371   if (!AddResult || Existing)
3372     return;
3373 
3374   DeclarationName Name = New->getDeclName();
3375   DeclContext *DC = New->getDeclContext()->getRedeclContext();
3376   if (needsAnonymousDeclarationNumber(New)) {
3377     setAnonymousDeclForMerging(Reader, New->getLexicalDeclContext(),
3378                                AnonymousDeclNumber, New);
3379   } else if (DC->isTranslationUnit() &&
3380              !Reader.getContext().getLangOpts().CPlusPlus) {
3381     if (Reader.getIdResolver().tryAddTopLevelDecl(New, Name))
3382       Reader.PendingFakeLookupResults[Name.getAsIdentifierInfo()]
3383             .push_back(New);
3384   } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
3385     // Add the declaration to its redeclaration context so later merging
3386     // lookups will find it.
3387     MergeDC->makeDeclVisibleInContextImpl(New, /*Internal*/true);
3388   }
3389 }
3390 
3391 /// Find the declaration that should be merged into, given the declaration found
3392 /// by name lookup. If we're merging an anonymous declaration within a typedef,
3393 /// we need a matching typedef, and we merge with the type inside it.
3394 static NamedDecl *getDeclForMerging(NamedDecl *Found,
3395                                     bool IsTypedefNameForLinkage) {
3396   if (!IsTypedefNameForLinkage)
3397     return Found;
3398 
3399   // If we found a typedef declaration that gives a name to some other
3400   // declaration, then we want that inner declaration. Declarations from
3401   // AST files are handled via ImportedTypedefNamesForLinkage.
3402   if (Found->isFromASTFile())
3403     return nullptr;
3404 
3405   if (auto *TND = dyn_cast<TypedefNameDecl>(Found))
3406     return TND->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
3407 
3408   return nullptr;
3409 }
3410 
3411 /// Find the declaration to use to populate the anonymous declaration table
3412 /// for the given lexical DeclContext. We only care about finding local
3413 /// definitions of the context; we'll merge imported ones as we go.
3414 DeclContext *
3415 ASTDeclReader::getPrimaryDCForAnonymousDecl(DeclContext *LexicalDC) {
3416   // For classes, we track the definition as we merge.
3417   if (auto *RD = dyn_cast<CXXRecordDecl>(LexicalDC)) {
3418     auto *DD = RD->getCanonicalDecl()->DefinitionData;
3419     return DD ? DD->Definition : nullptr;
3420   }
3421 
3422   // For anything else, walk its merged redeclarations looking for a definition.
3423   // Note that we can't just call getDefinition here because the redeclaration
3424   // chain isn't wired up.
3425   for (auto *D : merged_redecls(cast<Decl>(LexicalDC))) {
3426     if (auto *FD = dyn_cast<FunctionDecl>(D))
3427       if (FD->isThisDeclarationADefinition())
3428         return FD;
3429     if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
3430       if (MD->isThisDeclarationADefinition())
3431         return MD;
3432     if (auto *RD = dyn_cast<RecordDecl>(D))
3433       if (RD->isThisDeclarationADefinition())
3434         return RD;
3435   }
3436 
3437   // No merged definition yet.
3438   return nullptr;
3439 }
3440 
3441 NamedDecl *ASTDeclReader::getAnonymousDeclForMerging(ASTReader &Reader,
3442                                                      DeclContext *DC,
3443                                                      unsigned Index) {
3444   // If the lexical context has been merged, look into the now-canonical
3445   // definition.
3446   auto *CanonDC = cast<Decl>(DC)->getCanonicalDecl();
3447 
3448   // If we've seen this before, return the canonical declaration.
3449   auto &Previous = Reader.AnonymousDeclarationsForMerging[CanonDC];
3450   if (Index < Previous.size() && Previous[Index])
3451     return Previous[Index];
3452 
3453   // If this is the first time, but we have parsed a declaration of the context,
3454   // build the anonymous declaration list from the parsed declaration.
3455   auto *PrimaryDC = getPrimaryDCForAnonymousDecl(DC);
3456   if (PrimaryDC && !cast<Decl>(PrimaryDC)->isFromASTFile()) {
3457     numberAnonymousDeclsWithin(PrimaryDC, [&](NamedDecl *ND, unsigned Number) {
3458       if (Previous.size() == Number)
3459         Previous.push_back(cast<NamedDecl>(ND->getCanonicalDecl()));
3460       else
3461         Previous[Number] = cast<NamedDecl>(ND->getCanonicalDecl());
3462     });
3463   }
3464 
3465   return Index < Previous.size() ? Previous[Index] : nullptr;
3466 }
3467 
3468 void ASTDeclReader::setAnonymousDeclForMerging(ASTReader &Reader,
3469                                                DeclContext *DC, unsigned Index,
3470                                                NamedDecl *D) {
3471   auto *CanonDC = cast<Decl>(DC)->getCanonicalDecl();
3472 
3473   auto &Previous = Reader.AnonymousDeclarationsForMerging[CanonDC];
3474   if (Index >= Previous.size())
3475     Previous.resize(Index + 1);
3476   if (!Previous[Index])
3477     Previous[Index] = D;
3478 }
3479 
3480 ASTDeclReader::FindExistingResult ASTDeclReader::findExisting(NamedDecl *D) {
3481   DeclarationName Name = TypedefNameForLinkage ? TypedefNameForLinkage
3482                                                : D->getDeclName();
3483 
3484   if (!Name && !needsAnonymousDeclarationNumber(D)) {
3485     // Don't bother trying to find unnamed declarations that are in
3486     // unmergeable contexts.
3487     FindExistingResult Result(Reader, D, /*Existing=*/nullptr,
3488                               AnonymousDeclNumber, TypedefNameForLinkage);
3489     Result.suppress();
3490     return Result;
3491   }
3492 
3493   DeclContext *DC = D->getDeclContext()->getRedeclContext();
3494   if (TypedefNameForLinkage) {
3495     auto It = Reader.ImportedTypedefNamesForLinkage.find(
3496         std::make_pair(DC, TypedefNameForLinkage));
3497     if (It != Reader.ImportedTypedefNamesForLinkage.end())
3498       if (isSameEntity(It->second, D))
3499         return FindExistingResult(Reader, D, It->second, AnonymousDeclNumber,
3500                                   TypedefNameForLinkage);
3501     // Go on to check in other places in case an existing typedef name
3502     // was not imported.
3503   }
3504 
3505   if (needsAnonymousDeclarationNumber(D)) {
3506     // This is an anonymous declaration that we may need to merge. Look it up
3507     // in its context by number.
3508     if (auto *Existing = getAnonymousDeclForMerging(
3509             Reader, D->getLexicalDeclContext(), AnonymousDeclNumber))
3510       if (isSameEntity(Existing, D))
3511         return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3512                                   TypedefNameForLinkage);
3513   } else if (DC->isTranslationUnit() &&
3514              !Reader.getContext().getLangOpts().CPlusPlus) {
3515     IdentifierResolver &IdResolver = Reader.getIdResolver();
3516 
3517     // Temporarily consider the identifier to be up-to-date. We don't want to
3518     // cause additional lookups here.
3519     class UpToDateIdentifierRAII {
3520       IdentifierInfo *II;
3521       bool WasOutToDate = false;
3522 
3523     public:
3524       explicit UpToDateIdentifierRAII(IdentifierInfo *II) : II(II) {
3525         if (II) {
3526           WasOutToDate = II->isOutOfDate();
3527           if (WasOutToDate)
3528             II->setOutOfDate(false);
3529         }
3530       }
3531 
3532       ~UpToDateIdentifierRAII() {
3533         if (WasOutToDate)
3534           II->setOutOfDate(true);
3535       }
3536     } UpToDate(Name.getAsIdentifierInfo());
3537 
3538     for (IdentifierResolver::iterator I = IdResolver.begin(Name),
3539                                    IEnd = IdResolver.end();
3540          I != IEnd; ++I) {
3541       if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage))
3542         if (isSameEntity(Existing, D))
3543           return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3544                                     TypedefNameForLinkage);
3545     }
3546   } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
3547     DeclContext::lookup_result R = MergeDC->noload_lookup(Name);
3548     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
3549       if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage))
3550         if (isSameEntity(Existing, D))
3551           return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3552                                     TypedefNameForLinkage);
3553     }
3554   } else {
3555     // Not in a mergeable context.
3556     return FindExistingResult(Reader);
3557   }
3558 
3559   // If this declaration is from a merged context, make a note that we need to
3560   // check that the canonical definition of that context contains the decl.
3561   //
3562   // FIXME: We should do something similar if we merge two definitions of the
3563   // same template specialization into the same CXXRecordDecl.
3564   auto MergedDCIt = Reader.MergedDeclContexts.find(D->getLexicalDeclContext());
3565   if (MergedDCIt != Reader.MergedDeclContexts.end() &&
3566       MergedDCIt->second == D->getDeclContext())
3567     Reader.PendingOdrMergeChecks.push_back(D);
3568 
3569   return FindExistingResult(Reader, D, /*Existing=*/nullptr,
3570                             AnonymousDeclNumber, TypedefNameForLinkage);
3571 }
3572 
3573 template<typename DeclT>
3574 Decl *ASTDeclReader::getMostRecentDeclImpl(Redeclarable<DeclT> *D) {
3575   return D->RedeclLink.getLatestNotUpdated();
3576 }
3577 
3578 Decl *ASTDeclReader::getMostRecentDeclImpl(...) {
3579   llvm_unreachable("getMostRecentDecl on non-redeclarable declaration");
3580 }
3581 
3582 Decl *ASTDeclReader::getMostRecentDecl(Decl *D) {
3583   assert(D);
3584 
3585   switch (D->getKind()) {
3586 #define ABSTRACT_DECL(TYPE)
3587 #define DECL(TYPE, BASE)                               \
3588   case Decl::TYPE:                                     \
3589     return getMostRecentDeclImpl(cast<TYPE##Decl>(D));
3590 #include "clang/AST/DeclNodes.inc"
3591   }
3592   llvm_unreachable("unknown decl kind");
3593 }
3594 
3595 Decl *ASTReader::getMostRecentExistingDecl(Decl *D) {
3596   return ASTDeclReader::getMostRecentDecl(D->getCanonicalDecl());
3597 }
3598 
3599 void ASTDeclReader::mergeInheritableAttributes(ASTReader &Reader, Decl *D,
3600                                                Decl *Previous) {
3601   InheritableAttr *NewAttr = nullptr;
3602   ASTContext &Context = Reader.getContext();
3603   const auto *IA = Previous->getAttr<MSInheritanceAttr>();
3604 
3605   if (IA && !D->hasAttr<MSInheritanceAttr>()) {
3606     NewAttr = cast<InheritableAttr>(IA->clone(Context));
3607     NewAttr->setInherited(true);
3608     D->addAttr(NewAttr);
3609   }
3610 }
3611 
3612 template<typename DeclT>
3613 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3614                                            Redeclarable<DeclT> *D,
3615                                            Decl *Previous, Decl *Canon) {
3616   D->RedeclLink.setPrevious(cast<DeclT>(Previous));
3617   D->First = cast<DeclT>(Previous)->First;
3618 }
3619 
3620 namespace clang {
3621 
3622 template<>
3623 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3624                                            Redeclarable<VarDecl> *D,
3625                                            Decl *Previous, Decl *Canon) {
3626   auto *VD = static_cast<VarDecl *>(D);
3627   auto *PrevVD = cast<VarDecl>(Previous);
3628   D->RedeclLink.setPrevious(PrevVD);
3629   D->First = PrevVD->First;
3630 
3631   // We should keep at most one definition on the chain.
3632   // FIXME: Cache the definition once we've found it. Building a chain with
3633   // N definitions currently takes O(N^2) time here.
3634   if (VD->isThisDeclarationADefinition() == VarDecl::Definition) {
3635     for (VarDecl *CurD = PrevVD; CurD; CurD = CurD->getPreviousDecl()) {
3636       if (CurD->isThisDeclarationADefinition() == VarDecl::Definition) {
3637         Reader.mergeDefinitionVisibility(CurD, VD);
3638         VD->demoteThisDefinitionToDeclaration();
3639         break;
3640       }
3641     }
3642   }
3643 }
3644 
3645 static bool isUndeducedReturnType(QualType T) {
3646   auto *DT = T->getContainedDeducedType();
3647   return DT && !DT->isDeduced();
3648 }
3649 
3650 template<>
3651 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3652                                            Redeclarable<FunctionDecl> *D,
3653                                            Decl *Previous, Decl *Canon) {
3654   auto *FD = static_cast<FunctionDecl *>(D);
3655   auto *PrevFD = cast<FunctionDecl>(Previous);
3656 
3657   FD->RedeclLink.setPrevious(PrevFD);
3658   FD->First = PrevFD->First;
3659 
3660   // If the previous declaration is an inline function declaration, then this
3661   // declaration is too.
3662   if (PrevFD->isInlined() != FD->isInlined()) {
3663     // FIXME: [dcl.fct.spec]p4:
3664     //   If a function with external linkage is declared inline in one
3665     //   translation unit, it shall be declared inline in all translation
3666     //   units in which it appears.
3667     //
3668     // Be careful of this case:
3669     //
3670     // module A:
3671     //   template<typename T> struct X { void f(); };
3672     //   template<typename T> inline void X<T>::f() {}
3673     //
3674     // module B instantiates the declaration of X<int>::f
3675     // module C instantiates the definition of X<int>::f
3676     //
3677     // If module B and C are merged, we do not have a violation of this rule.
3678     FD->setImplicitlyInline(true);
3679   }
3680 
3681   auto *FPT = FD->getType()->getAs<FunctionProtoType>();
3682   auto *PrevFPT = PrevFD->getType()->getAs<FunctionProtoType>();
3683   if (FPT && PrevFPT) {
3684     // If we need to propagate an exception specification along the redecl
3685     // chain, make a note of that so that we can do so later.
3686     bool IsUnresolved = isUnresolvedExceptionSpec(FPT->getExceptionSpecType());
3687     bool WasUnresolved =
3688         isUnresolvedExceptionSpec(PrevFPT->getExceptionSpecType());
3689     if (IsUnresolved != WasUnresolved)
3690       Reader.PendingExceptionSpecUpdates.insert(
3691           {Canon, IsUnresolved ? PrevFD : FD});
3692 
3693     // If we need to propagate a deduced return type along the redecl chain,
3694     // make a note of that so that we can do it later.
3695     bool IsUndeduced = isUndeducedReturnType(FPT->getReturnType());
3696     bool WasUndeduced = isUndeducedReturnType(PrevFPT->getReturnType());
3697     if (IsUndeduced != WasUndeduced)
3698       Reader.PendingDeducedTypeUpdates.insert(
3699           {cast<FunctionDecl>(Canon),
3700            (IsUndeduced ? PrevFPT : FPT)->getReturnType()});
3701   }
3702 }
3703 
3704 } // namespace clang
3705 
3706 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader, ...) {
3707   llvm_unreachable("attachPreviousDecl on non-redeclarable declaration");
3708 }
3709 
3710 /// Inherit the default template argument from \p From to \p To. Returns
3711 /// \c false if there is no default template for \p From.
3712 template <typename ParmDecl>
3713 static bool inheritDefaultTemplateArgument(ASTContext &Context, ParmDecl *From,
3714                                            Decl *ToD) {
3715   auto *To = cast<ParmDecl>(ToD);
3716   if (!From->hasDefaultArgument())
3717     return false;
3718   To->setInheritedDefaultArgument(Context, From);
3719   return true;
3720 }
3721 
3722 static void inheritDefaultTemplateArguments(ASTContext &Context,
3723                                             TemplateDecl *From,
3724                                             TemplateDecl *To) {
3725   auto *FromTP = From->getTemplateParameters();
3726   auto *ToTP = To->getTemplateParameters();
3727   assert(FromTP->size() == ToTP->size() && "merged mismatched templates?");
3728 
3729   for (unsigned I = 0, N = FromTP->size(); I != N; ++I) {
3730     NamedDecl *FromParam = FromTP->getParam(I);
3731     NamedDecl *ToParam = ToTP->getParam(I);
3732 
3733     if (auto *FTTP = dyn_cast<TemplateTypeParmDecl>(FromParam))
3734       inheritDefaultTemplateArgument(Context, FTTP, ToParam);
3735     else if (auto *FNTTP = dyn_cast<NonTypeTemplateParmDecl>(FromParam))
3736       inheritDefaultTemplateArgument(Context, FNTTP, ToParam);
3737     else
3738       inheritDefaultTemplateArgument(
3739               Context, cast<TemplateTemplateParmDecl>(FromParam), ToParam);
3740   }
3741 }
3742 
3743 void ASTDeclReader::attachPreviousDecl(ASTReader &Reader, Decl *D,
3744                                        Decl *Previous, Decl *Canon) {
3745   assert(D && Previous);
3746 
3747   switch (D->getKind()) {
3748 #define ABSTRACT_DECL(TYPE)
3749 #define DECL(TYPE, BASE)                                                  \
3750   case Decl::TYPE:                                                        \
3751     attachPreviousDeclImpl(Reader, cast<TYPE##Decl>(D), Previous, Canon); \
3752     break;
3753 #include "clang/AST/DeclNodes.inc"
3754   }
3755 
3756   // If the declaration was visible in one module, a redeclaration of it in
3757   // another module remains visible even if it wouldn't be visible by itself.
3758   //
3759   // FIXME: In this case, the declaration should only be visible if a module
3760   //        that makes it visible has been imported.
3761   D->IdentifierNamespace |=
3762       Previous->IdentifierNamespace &
3763       (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
3764 
3765   // If the declaration declares a template, it may inherit default arguments
3766   // from the previous declaration.
3767   if (auto *TD = dyn_cast<TemplateDecl>(D))
3768     inheritDefaultTemplateArguments(Reader.getContext(),
3769                                     cast<TemplateDecl>(Previous), TD);
3770 
3771   // If any of the declaration in the chain contains an Inheritable attribute,
3772   // it needs to be added to all the declarations in the redeclarable chain.
3773   // FIXME: Only the logic of merging MSInheritableAttr is present, it should
3774   // be extended for all inheritable attributes.
3775   mergeInheritableAttributes(Reader, D, Previous);
3776 }
3777 
3778 template<typename DeclT>
3779 void ASTDeclReader::attachLatestDeclImpl(Redeclarable<DeclT> *D, Decl *Latest) {
3780   D->RedeclLink.setLatest(cast<DeclT>(Latest));
3781 }
3782 
3783 void ASTDeclReader::attachLatestDeclImpl(...) {
3784   llvm_unreachable("attachLatestDecl on non-redeclarable declaration");
3785 }
3786 
3787 void ASTDeclReader::attachLatestDecl(Decl *D, Decl *Latest) {
3788   assert(D && Latest);
3789 
3790   switch (D->getKind()) {
3791 #define ABSTRACT_DECL(TYPE)
3792 #define DECL(TYPE, BASE)                                  \
3793   case Decl::TYPE:                                        \
3794     attachLatestDeclImpl(cast<TYPE##Decl>(D), Latest); \
3795     break;
3796 #include "clang/AST/DeclNodes.inc"
3797   }
3798 }
3799 
3800 template<typename DeclT>
3801 void ASTDeclReader::markIncompleteDeclChainImpl(Redeclarable<DeclT> *D) {
3802   D->RedeclLink.markIncomplete();
3803 }
3804 
3805 void ASTDeclReader::markIncompleteDeclChainImpl(...) {
3806   llvm_unreachable("markIncompleteDeclChain on non-redeclarable declaration");
3807 }
3808 
3809 void ASTReader::markIncompleteDeclChain(Decl *D) {
3810   switch (D->getKind()) {
3811 #define ABSTRACT_DECL(TYPE)
3812 #define DECL(TYPE, BASE)                                             \
3813   case Decl::TYPE:                                                   \
3814     ASTDeclReader::markIncompleteDeclChainImpl(cast<TYPE##Decl>(D)); \
3815     break;
3816 #include "clang/AST/DeclNodes.inc"
3817   }
3818 }
3819 
3820 /// Read the declaration at the given offset from the AST file.
3821 Decl *ASTReader::ReadDeclRecord(DeclID ID) {
3822   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
3823   SourceLocation DeclLoc;
3824   RecordLocation Loc = DeclCursorForID(ID, DeclLoc);
3825   llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
3826   // Keep track of where we are in the stream, then jump back there
3827   // after reading this declaration.
3828   SavedStreamPosition SavedPosition(DeclsCursor);
3829 
3830   ReadingKindTracker ReadingKind(Read_Decl, *this);
3831 
3832   // Note that we are loading a declaration record.
3833   Deserializing ADecl(this);
3834 
3835   auto Fail = [](const char *what, llvm::Error &&Err) {
3836     llvm::report_fatal_error(Twine("ASTReader::readDeclRecord failed ") + what +
3837                              ": " + toString(std::move(Err)));
3838   };
3839 
3840   if (llvm::Error JumpFailed = DeclsCursor.JumpToBit(Loc.Offset))
3841     Fail("jumping", std::move(JumpFailed));
3842   ASTRecordReader Record(*this, *Loc.F);
3843   ASTDeclReader Reader(*this, Record, Loc, ID, DeclLoc);
3844   Expected<unsigned> MaybeCode = DeclsCursor.ReadCode();
3845   if (!MaybeCode)
3846     Fail("reading code", MaybeCode.takeError());
3847   unsigned Code = MaybeCode.get();
3848 
3849   ASTContext &Context = getContext();
3850   Decl *D = nullptr;
3851   Expected<unsigned> MaybeDeclCode = Record.readRecord(DeclsCursor, Code);
3852   if (!MaybeDeclCode)
3853     llvm::report_fatal_error(
3854         "ASTReader::readDeclRecord failed reading decl code: " +
3855         toString(MaybeDeclCode.takeError()));
3856   switch ((DeclCode)MaybeDeclCode.get()) {
3857   case DECL_CONTEXT_LEXICAL:
3858   case DECL_CONTEXT_VISIBLE:
3859     llvm_unreachable("Record cannot be de-serialized with readDeclRecord");
3860   case DECL_TYPEDEF:
3861     D = TypedefDecl::CreateDeserialized(Context, ID);
3862     break;
3863   case DECL_TYPEALIAS:
3864     D = TypeAliasDecl::CreateDeserialized(Context, ID);
3865     break;
3866   case DECL_ENUM:
3867     D = EnumDecl::CreateDeserialized(Context, ID);
3868     break;
3869   case DECL_RECORD:
3870     D = RecordDecl::CreateDeserialized(Context, ID);
3871     break;
3872   case DECL_ENUM_CONSTANT:
3873     D = EnumConstantDecl::CreateDeserialized(Context, ID);
3874     break;
3875   case DECL_FUNCTION:
3876     D = FunctionDecl::CreateDeserialized(Context, ID);
3877     break;
3878   case DECL_LINKAGE_SPEC:
3879     D = LinkageSpecDecl::CreateDeserialized(Context, ID);
3880     break;
3881   case DECL_EXPORT:
3882     D = ExportDecl::CreateDeserialized(Context, ID);
3883     break;
3884   case DECL_LABEL:
3885     D = LabelDecl::CreateDeserialized(Context, ID);
3886     break;
3887   case DECL_NAMESPACE:
3888     D = NamespaceDecl::CreateDeserialized(Context, ID);
3889     break;
3890   case DECL_NAMESPACE_ALIAS:
3891     D = NamespaceAliasDecl::CreateDeserialized(Context, ID);
3892     break;
3893   case DECL_USING:
3894     D = UsingDecl::CreateDeserialized(Context, ID);
3895     break;
3896   case DECL_USING_PACK:
3897     D = UsingPackDecl::CreateDeserialized(Context, ID, Record.readInt());
3898     break;
3899   case DECL_USING_SHADOW:
3900     D = UsingShadowDecl::CreateDeserialized(Context, ID);
3901     break;
3902   case DECL_USING_ENUM:
3903     D = UsingEnumDecl::CreateDeserialized(Context, ID);
3904     break;
3905   case DECL_CONSTRUCTOR_USING_SHADOW:
3906     D = ConstructorUsingShadowDecl::CreateDeserialized(Context, ID);
3907     break;
3908   case DECL_USING_DIRECTIVE:
3909     D = UsingDirectiveDecl::CreateDeserialized(Context, ID);
3910     break;
3911   case DECL_UNRESOLVED_USING_VALUE:
3912     D = UnresolvedUsingValueDecl::CreateDeserialized(Context, ID);
3913     break;
3914   case DECL_UNRESOLVED_USING_TYPENAME:
3915     D = UnresolvedUsingTypenameDecl::CreateDeserialized(Context, ID);
3916     break;
3917   case DECL_UNRESOLVED_USING_IF_EXISTS:
3918     D = UnresolvedUsingIfExistsDecl::CreateDeserialized(Context, ID);
3919     break;
3920   case DECL_CXX_RECORD:
3921     D = CXXRecordDecl::CreateDeserialized(Context, ID);
3922     break;
3923   case DECL_CXX_DEDUCTION_GUIDE:
3924     D = CXXDeductionGuideDecl::CreateDeserialized(Context, ID);
3925     break;
3926   case DECL_CXX_METHOD:
3927     D = CXXMethodDecl::CreateDeserialized(Context, ID);
3928     break;
3929   case DECL_CXX_CONSTRUCTOR:
3930     D = CXXConstructorDecl::CreateDeserialized(Context, ID, Record.readInt());
3931     break;
3932   case DECL_CXX_DESTRUCTOR:
3933     D = CXXDestructorDecl::CreateDeserialized(Context, ID);
3934     break;
3935   case DECL_CXX_CONVERSION:
3936     D = CXXConversionDecl::CreateDeserialized(Context, ID);
3937     break;
3938   case DECL_ACCESS_SPEC:
3939     D = AccessSpecDecl::CreateDeserialized(Context, ID);
3940     break;
3941   case DECL_FRIEND:
3942     D = FriendDecl::CreateDeserialized(Context, ID, Record.readInt());
3943     break;
3944   case DECL_FRIEND_TEMPLATE:
3945     D = FriendTemplateDecl::CreateDeserialized(Context, ID);
3946     break;
3947   case DECL_CLASS_TEMPLATE:
3948     D = ClassTemplateDecl::CreateDeserialized(Context, ID);
3949     break;
3950   case DECL_CLASS_TEMPLATE_SPECIALIZATION:
3951     D = ClassTemplateSpecializationDecl::CreateDeserialized(Context, ID);
3952     break;
3953   case DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION:
3954     D = ClassTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
3955     break;
3956   case DECL_VAR_TEMPLATE:
3957     D = VarTemplateDecl::CreateDeserialized(Context, ID);
3958     break;
3959   case DECL_VAR_TEMPLATE_SPECIALIZATION:
3960     D = VarTemplateSpecializationDecl::CreateDeserialized(Context, ID);
3961     break;
3962   case DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION:
3963     D = VarTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
3964     break;
3965   case DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION:
3966     D = ClassScopeFunctionSpecializationDecl::CreateDeserialized(Context, ID);
3967     break;
3968   case DECL_FUNCTION_TEMPLATE:
3969     D = FunctionTemplateDecl::CreateDeserialized(Context, ID);
3970     break;
3971   case DECL_TEMPLATE_TYPE_PARM: {
3972     bool HasTypeConstraint = Record.readInt();
3973     D = TemplateTypeParmDecl::CreateDeserialized(Context, ID,
3974                                                  HasTypeConstraint);
3975     break;
3976   }
3977   case DECL_NON_TYPE_TEMPLATE_PARM: {
3978     bool HasTypeConstraint = Record.readInt();
3979     D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID,
3980                                                     HasTypeConstraint);
3981     break;
3982   }
3983   case DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK: {
3984     bool HasTypeConstraint = Record.readInt();
3985     D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID,
3986                                                     Record.readInt(),
3987                                                     HasTypeConstraint);
3988     break;
3989   }
3990   case DECL_TEMPLATE_TEMPLATE_PARM:
3991     D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID);
3992     break;
3993   case DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK:
3994     D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID,
3995                                                      Record.readInt());
3996     break;
3997   case DECL_TYPE_ALIAS_TEMPLATE:
3998     D = TypeAliasTemplateDecl::CreateDeserialized(Context, ID);
3999     break;
4000   case DECL_CONCEPT:
4001     D = ConceptDecl::CreateDeserialized(Context, ID);
4002     break;
4003   case DECL_REQUIRES_EXPR_BODY:
4004     D = RequiresExprBodyDecl::CreateDeserialized(Context, ID);
4005     break;
4006   case DECL_STATIC_ASSERT:
4007     D = StaticAssertDecl::CreateDeserialized(Context, ID);
4008     break;
4009   case DECL_OBJC_METHOD:
4010     D = ObjCMethodDecl::CreateDeserialized(Context, ID);
4011     break;
4012   case DECL_OBJC_INTERFACE:
4013     D = ObjCInterfaceDecl::CreateDeserialized(Context, ID);
4014     break;
4015   case DECL_OBJC_IVAR:
4016     D = ObjCIvarDecl::CreateDeserialized(Context, ID);
4017     break;
4018   case DECL_OBJC_PROTOCOL:
4019     D = ObjCProtocolDecl::CreateDeserialized(Context, ID);
4020     break;
4021   case DECL_OBJC_AT_DEFS_FIELD:
4022     D = ObjCAtDefsFieldDecl::CreateDeserialized(Context, ID);
4023     break;
4024   case DECL_OBJC_CATEGORY:
4025     D = ObjCCategoryDecl::CreateDeserialized(Context, ID);
4026     break;
4027   case DECL_OBJC_CATEGORY_IMPL:
4028     D = ObjCCategoryImplDecl::CreateDeserialized(Context, ID);
4029     break;
4030   case DECL_OBJC_IMPLEMENTATION:
4031     D = ObjCImplementationDecl::CreateDeserialized(Context, ID);
4032     break;
4033   case DECL_OBJC_COMPATIBLE_ALIAS:
4034     D = ObjCCompatibleAliasDecl::CreateDeserialized(Context, ID);
4035     break;
4036   case DECL_OBJC_PROPERTY:
4037     D = ObjCPropertyDecl::CreateDeserialized(Context, ID);
4038     break;
4039   case DECL_OBJC_PROPERTY_IMPL:
4040     D = ObjCPropertyImplDecl::CreateDeserialized(Context, ID);
4041     break;
4042   case DECL_FIELD:
4043     D = FieldDecl::CreateDeserialized(Context, ID);
4044     break;
4045   case DECL_INDIRECTFIELD:
4046     D = IndirectFieldDecl::CreateDeserialized(Context, ID);
4047     break;
4048   case DECL_VAR:
4049     D = VarDecl::CreateDeserialized(Context, ID);
4050     break;
4051   case DECL_IMPLICIT_PARAM:
4052     D = ImplicitParamDecl::CreateDeserialized(Context, ID);
4053     break;
4054   case DECL_PARM_VAR:
4055     D = ParmVarDecl::CreateDeserialized(Context, ID);
4056     break;
4057   case DECL_DECOMPOSITION:
4058     D = DecompositionDecl::CreateDeserialized(Context, ID, Record.readInt());
4059     break;
4060   case DECL_BINDING:
4061     D = BindingDecl::CreateDeserialized(Context, ID);
4062     break;
4063   case DECL_FILE_SCOPE_ASM:
4064     D = FileScopeAsmDecl::CreateDeserialized(Context, ID);
4065     break;
4066   case DECL_BLOCK:
4067     D = BlockDecl::CreateDeserialized(Context, ID);
4068     break;
4069   case DECL_MS_PROPERTY:
4070     D = MSPropertyDecl::CreateDeserialized(Context, ID);
4071     break;
4072   case DECL_MS_GUID:
4073     D = MSGuidDecl::CreateDeserialized(Context, ID);
4074     break;
4075   case DECL_TEMPLATE_PARAM_OBJECT:
4076     D = TemplateParamObjectDecl::CreateDeserialized(Context, ID);
4077     break;
4078   case DECL_CAPTURED:
4079     D = CapturedDecl::CreateDeserialized(Context, ID, Record.readInt());
4080     break;
4081   case DECL_CXX_BASE_SPECIFIERS:
4082     Error("attempt to read a C++ base-specifier record as a declaration");
4083     return nullptr;
4084   case DECL_CXX_CTOR_INITIALIZERS:
4085     Error("attempt to read a C++ ctor initializer record as a declaration");
4086     return nullptr;
4087   case DECL_IMPORT:
4088     // Note: last entry of the ImportDecl record is the number of stored source
4089     // locations.
4090     D = ImportDecl::CreateDeserialized(Context, ID, Record.back());
4091     break;
4092   case DECL_OMP_THREADPRIVATE: {
4093     Record.skipInts(1);
4094     unsigned NumChildren = Record.readInt();
4095     Record.skipInts(1);
4096     D = OMPThreadPrivateDecl::CreateDeserialized(Context, ID, NumChildren);
4097     break;
4098   }
4099   case DECL_OMP_ALLOCATE: {
4100     unsigned NumClauses = Record.readInt();
4101     unsigned NumVars = Record.readInt();
4102     Record.skipInts(1);
4103     D = OMPAllocateDecl::CreateDeserialized(Context, ID, NumVars, NumClauses);
4104     break;
4105   }
4106   case DECL_OMP_REQUIRES: {
4107     unsigned NumClauses = Record.readInt();
4108     Record.skipInts(2);
4109     D = OMPRequiresDecl::CreateDeserialized(Context, ID, NumClauses);
4110     break;
4111   }
4112   case DECL_OMP_DECLARE_REDUCTION:
4113     D = OMPDeclareReductionDecl::CreateDeserialized(Context, ID);
4114     break;
4115   case DECL_OMP_DECLARE_MAPPER: {
4116     unsigned NumClauses = Record.readInt();
4117     Record.skipInts(2);
4118     D = OMPDeclareMapperDecl::CreateDeserialized(Context, ID, NumClauses);
4119     break;
4120   }
4121   case DECL_OMP_CAPTUREDEXPR:
4122     D = OMPCapturedExprDecl::CreateDeserialized(Context, ID);
4123     break;
4124   case DECL_PRAGMA_COMMENT:
4125     D = PragmaCommentDecl::CreateDeserialized(Context, ID, Record.readInt());
4126     break;
4127   case DECL_PRAGMA_DETECT_MISMATCH:
4128     D = PragmaDetectMismatchDecl::CreateDeserialized(Context, ID,
4129                                                      Record.readInt());
4130     break;
4131   case DECL_EMPTY:
4132     D = EmptyDecl::CreateDeserialized(Context, ID);
4133     break;
4134   case DECL_LIFETIME_EXTENDED_TEMPORARY:
4135     D = LifetimeExtendedTemporaryDecl::CreateDeserialized(Context, ID);
4136     break;
4137   case DECL_OBJC_TYPE_PARAM:
4138     D = ObjCTypeParamDecl::CreateDeserialized(Context, ID);
4139     break;
4140   }
4141 
4142   assert(D && "Unknown declaration reading AST file");
4143   LoadedDecl(Index, D);
4144   // Set the DeclContext before doing any deserialization, to make sure internal
4145   // calls to Decl::getASTContext() by Decl's methods will find the
4146   // TranslationUnitDecl without crashing.
4147   D->setDeclContext(Context.getTranslationUnitDecl());
4148   Reader.Visit(D);
4149 
4150   // If this declaration is also a declaration context, get the
4151   // offsets for its tables of lexical and visible declarations.
4152   if (auto *DC = dyn_cast<DeclContext>(D)) {
4153     std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
4154     if (Offsets.first &&
4155         ReadLexicalDeclContextStorage(*Loc.F, DeclsCursor, Offsets.first, DC))
4156       return nullptr;
4157     if (Offsets.second &&
4158         ReadVisibleDeclContextStorage(*Loc.F, DeclsCursor, Offsets.second, ID))
4159       return nullptr;
4160   }
4161   assert(Record.getIdx() == Record.size());
4162 
4163   // Load any relevant update records.
4164   PendingUpdateRecords.push_back(
4165       PendingUpdateRecord(ID, D, /*JustLoaded=*/true));
4166 
4167   // Load the categories after recursive loading is finished.
4168   if (auto *Class = dyn_cast<ObjCInterfaceDecl>(D))
4169     // If we already have a definition when deserializing the ObjCInterfaceDecl,
4170     // we put the Decl in PendingDefinitions so we can pull the categories here.
4171     if (Class->isThisDeclarationADefinition() ||
4172         PendingDefinitions.count(Class))
4173       loadObjCCategories(ID, Class);
4174 
4175   // If we have deserialized a declaration that has a definition the
4176   // AST consumer might need to know about, queue it.
4177   // We don't pass it to the consumer immediately because we may be in recursive
4178   // loading, and some declarations may still be initializing.
4179   PotentiallyInterestingDecls.push_back(
4180       InterestingDecl(D, Reader.hasPendingBody()));
4181 
4182   return D;
4183 }
4184 
4185 void ASTReader::PassInterestingDeclsToConsumer() {
4186   assert(Consumer);
4187 
4188   if (PassingDeclsToConsumer)
4189     return;
4190 
4191   // Guard variable to avoid recursively redoing the process of passing
4192   // decls to consumer.
4193   SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
4194                                                    true);
4195 
4196   // Ensure that we've loaded all potentially-interesting declarations
4197   // that need to be eagerly loaded.
4198   for (auto ID : EagerlyDeserializedDecls)
4199     GetDecl(ID);
4200   EagerlyDeserializedDecls.clear();
4201 
4202   while (!PotentiallyInterestingDecls.empty()) {
4203     InterestingDecl D = PotentiallyInterestingDecls.front();
4204     PotentiallyInterestingDecls.pop_front();
4205     if (isConsumerInterestedIn(getContext(), D.getDecl(), D.hasPendingBody()))
4206       PassInterestingDeclToConsumer(D.getDecl());
4207   }
4208 }
4209 
4210 void ASTReader::loadDeclUpdateRecords(PendingUpdateRecord &Record) {
4211   // The declaration may have been modified by files later in the chain.
4212   // If this is the case, read the record containing the updates from each file
4213   // and pass it to ASTDeclReader to make the modifications.
4214   serialization::GlobalDeclID ID = Record.ID;
4215   Decl *D = Record.D;
4216   ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
4217   DeclUpdateOffsetsMap::iterator UpdI = DeclUpdateOffsets.find(ID);
4218 
4219   SmallVector<serialization::DeclID, 8> PendingLazySpecializationIDs;
4220 
4221   if (UpdI != DeclUpdateOffsets.end()) {
4222     auto UpdateOffsets = std::move(UpdI->second);
4223     DeclUpdateOffsets.erase(UpdI);
4224 
4225     // Check if this decl was interesting to the consumer. If we just loaded
4226     // the declaration, then we know it was interesting and we skip the call
4227     // to isConsumerInterestedIn because it is unsafe to call in the
4228     // current ASTReader state.
4229     bool WasInteresting =
4230         Record.JustLoaded || isConsumerInterestedIn(getContext(), D, false);
4231     for (auto &FileAndOffset : UpdateOffsets) {
4232       ModuleFile *F = FileAndOffset.first;
4233       uint64_t Offset = FileAndOffset.second;
4234       llvm::BitstreamCursor &Cursor = F->DeclsCursor;
4235       SavedStreamPosition SavedPosition(Cursor);
4236       if (llvm::Error JumpFailed = Cursor.JumpToBit(Offset))
4237         // FIXME don't do a fatal error.
4238         llvm::report_fatal_error(
4239             "ASTReader::loadDeclUpdateRecords failed jumping: " +
4240             toString(std::move(JumpFailed)));
4241       Expected<unsigned> MaybeCode = Cursor.ReadCode();
4242       if (!MaybeCode)
4243         llvm::report_fatal_error(
4244             "ASTReader::loadDeclUpdateRecords failed reading code: " +
4245             toString(MaybeCode.takeError()));
4246       unsigned Code = MaybeCode.get();
4247       ASTRecordReader Record(*this, *F);
4248       if (Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code))
4249         assert(MaybeRecCode.get() == DECL_UPDATES &&
4250                "Expected DECL_UPDATES record!");
4251       else
4252         llvm::report_fatal_error(
4253             "ASTReader::loadDeclUpdateRecords failed reading rec code: " +
4254             toString(MaybeCode.takeError()));
4255 
4256       ASTDeclReader Reader(*this, Record, RecordLocation(F, Offset), ID,
4257                            SourceLocation());
4258       Reader.UpdateDecl(D, PendingLazySpecializationIDs);
4259 
4260       // We might have made this declaration interesting. If so, remember that
4261       // we need to hand it off to the consumer.
4262       if (!WasInteresting &&
4263           isConsumerInterestedIn(getContext(), D, Reader.hasPendingBody())) {
4264         PotentiallyInterestingDecls.push_back(
4265             InterestingDecl(D, Reader.hasPendingBody()));
4266         WasInteresting = true;
4267       }
4268     }
4269   }
4270   // Add the lazy specializations to the template.
4271   assert((PendingLazySpecializationIDs.empty() || isa<ClassTemplateDecl>(D) ||
4272           isa<FunctionTemplateDecl>(D) || isa<VarTemplateDecl>(D)) &&
4273          "Must not have pending specializations");
4274   if (auto *CTD = dyn_cast<ClassTemplateDecl>(D))
4275     ASTDeclReader::AddLazySpecializations(CTD, PendingLazySpecializationIDs);
4276   else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
4277     ASTDeclReader::AddLazySpecializations(FTD, PendingLazySpecializationIDs);
4278   else if (auto *VTD = dyn_cast<VarTemplateDecl>(D))
4279     ASTDeclReader::AddLazySpecializations(VTD, PendingLazySpecializationIDs);
4280   PendingLazySpecializationIDs.clear();
4281 
4282   // Load the pending visible updates for this decl context, if it has any.
4283   auto I = PendingVisibleUpdates.find(ID);
4284   if (I != PendingVisibleUpdates.end()) {
4285     auto VisibleUpdates = std::move(I->second);
4286     PendingVisibleUpdates.erase(I);
4287 
4288     auto *DC = cast<DeclContext>(D)->getPrimaryContext();
4289     for (const auto &Update : VisibleUpdates)
4290       Lookups[DC].Table.add(
4291           Update.Mod, Update.Data,
4292           reader::ASTDeclContextNameLookupTrait(*this, *Update.Mod));
4293     DC->setHasExternalVisibleStorage(true);
4294   }
4295 }
4296 
4297 void ASTReader::loadPendingDeclChain(Decl *FirstLocal, uint64_t LocalOffset) {
4298   // Attach FirstLocal to the end of the decl chain.
4299   Decl *CanonDecl = FirstLocal->getCanonicalDecl();
4300   if (FirstLocal != CanonDecl) {
4301     Decl *PrevMostRecent = ASTDeclReader::getMostRecentDecl(CanonDecl);
4302     ASTDeclReader::attachPreviousDecl(
4303         *this, FirstLocal, PrevMostRecent ? PrevMostRecent : CanonDecl,
4304         CanonDecl);
4305   }
4306 
4307   if (!LocalOffset) {
4308     ASTDeclReader::attachLatestDecl(CanonDecl, FirstLocal);
4309     return;
4310   }
4311 
4312   // Load the list of other redeclarations from this module file.
4313   ModuleFile *M = getOwningModuleFile(FirstLocal);
4314   assert(M && "imported decl from no module file");
4315 
4316   llvm::BitstreamCursor &Cursor = M->DeclsCursor;
4317   SavedStreamPosition SavedPosition(Cursor);
4318   if (llvm::Error JumpFailed = Cursor.JumpToBit(LocalOffset))
4319     llvm::report_fatal_error(
4320         "ASTReader::loadPendingDeclChain failed jumping: " +
4321         toString(std::move(JumpFailed)));
4322 
4323   RecordData Record;
4324   Expected<unsigned> MaybeCode = Cursor.ReadCode();
4325   if (!MaybeCode)
4326     llvm::report_fatal_error(
4327         "ASTReader::loadPendingDeclChain failed reading code: " +
4328         toString(MaybeCode.takeError()));
4329   unsigned Code = MaybeCode.get();
4330   if (Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record))
4331     assert(MaybeRecCode.get() == LOCAL_REDECLARATIONS &&
4332            "expected LOCAL_REDECLARATIONS record!");
4333   else
4334     llvm::report_fatal_error(
4335         "ASTReader::loadPendingDeclChain failed reading rec code: " +
4336         toString(MaybeCode.takeError()));
4337 
4338   // FIXME: We have several different dispatches on decl kind here; maybe
4339   // we should instead generate one loop per kind and dispatch up-front?
4340   Decl *MostRecent = FirstLocal;
4341   for (unsigned I = 0, N = Record.size(); I != N; ++I) {
4342     auto *D = GetLocalDecl(*M, Record[N - I - 1]);
4343     ASTDeclReader::attachPreviousDecl(*this, D, MostRecent, CanonDecl);
4344     MostRecent = D;
4345   }
4346   ASTDeclReader::attachLatestDecl(CanonDecl, MostRecent);
4347 }
4348 
4349 namespace {
4350 
4351   /// Given an ObjC interface, goes through the modules and links to the
4352   /// interface all the categories for it.
4353   class ObjCCategoriesVisitor {
4354     ASTReader &Reader;
4355     ObjCInterfaceDecl *Interface;
4356     llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized;
4357     ObjCCategoryDecl *Tail = nullptr;
4358     llvm::DenseMap<DeclarationName, ObjCCategoryDecl *> NameCategoryMap;
4359     serialization::GlobalDeclID InterfaceID;
4360     unsigned PreviousGeneration;
4361 
4362     void add(ObjCCategoryDecl *Cat) {
4363       // Only process each category once.
4364       if (!Deserialized.erase(Cat))
4365         return;
4366 
4367       // Check for duplicate categories.
4368       if (Cat->getDeclName()) {
4369         ObjCCategoryDecl *&Existing = NameCategoryMap[Cat->getDeclName()];
4370         if (Existing &&
4371             Reader.getOwningModuleFile(Existing)
4372                                           != Reader.getOwningModuleFile(Cat)) {
4373           // FIXME: We should not warn for duplicates in diamond:
4374           //
4375           //   MT     //
4376           //  /  \    //
4377           // ML  MR   //
4378           //  \  /    //
4379           //   MB     //
4380           //
4381           // If there are duplicates in ML/MR, there will be warning when
4382           // creating MB *and* when importing MB. We should not warn when
4383           // importing.
4384           Reader.Diag(Cat->getLocation(), diag::warn_dup_category_def)
4385             << Interface->getDeclName() << Cat->getDeclName();
4386           Reader.Diag(Existing->getLocation(), diag::note_previous_definition);
4387         } else if (!Existing) {
4388           // Record this category.
4389           Existing = Cat;
4390         }
4391       }
4392 
4393       // Add this category to the end of the chain.
4394       if (Tail)
4395         ASTDeclReader::setNextObjCCategory(Tail, Cat);
4396       else
4397         Interface->setCategoryListRaw(Cat);
4398       Tail = Cat;
4399     }
4400 
4401   public:
4402     ObjCCategoriesVisitor(ASTReader &Reader,
4403                           ObjCInterfaceDecl *Interface,
4404                           llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized,
4405                           serialization::GlobalDeclID InterfaceID,
4406                           unsigned PreviousGeneration)
4407         : Reader(Reader), Interface(Interface), Deserialized(Deserialized),
4408           InterfaceID(InterfaceID), PreviousGeneration(PreviousGeneration) {
4409       // Populate the name -> category map with the set of known categories.
4410       for (auto *Cat : Interface->known_categories()) {
4411         if (Cat->getDeclName())
4412           NameCategoryMap[Cat->getDeclName()] = Cat;
4413 
4414         // Keep track of the tail of the category list.
4415         Tail = Cat;
4416       }
4417     }
4418 
4419     bool operator()(ModuleFile &M) {
4420       // If we've loaded all of the category information we care about from
4421       // this module file, we're done.
4422       if (M.Generation <= PreviousGeneration)
4423         return true;
4424 
4425       // Map global ID of the definition down to the local ID used in this
4426       // module file. If there is no such mapping, we'll find nothing here
4427       // (or in any module it imports).
4428       DeclID LocalID = Reader.mapGlobalIDToModuleFileGlobalID(M, InterfaceID);
4429       if (!LocalID)
4430         return true;
4431 
4432       // Perform a binary search to find the local redeclarations for this
4433       // declaration (if any).
4434       const ObjCCategoriesInfo Compare = { LocalID, 0 };
4435       const ObjCCategoriesInfo *Result
4436         = std::lower_bound(M.ObjCCategoriesMap,
4437                            M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap,
4438                            Compare);
4439       if (Result == M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap ||
4440           Result->DefinitionID != LocalID) {
4441         // We didn't find anything. If the class definition is in this module
4442         // file, then the module files it depends on cannot have any categories,
4443         // so suppress further lookup.
4444         return Reader.isDeclIDFromModule(InterfaceID, M);
4445       }
4446 
4447       // We found something. Dig out all of the categories.
4448       unsigned Offset = Result->Offset;
4449       unsigned N = M.ObjCCategories[Offset];
4450       M.ObjCCategories[Offset++] = 0; // Don't try to deserialize again
4451       for (unsigned I = 0; I != N; ++I)
4452         add(cast_or_null<ObjCCategoryDecl>(
4453               Reader.GetLocalDecl(M, M.ObjCCategories[Offset++])));
4454       return true;
4455     }
4456   };
4457 
4458 } // namespace
4459 
4460 void ASTReader::loadObjCCategories(serialization::GlobalDeclID ID,
4461                                    ObjCInterfaceDecl *D,
4462                                    unsigned PreviousGeneration) {
4463   ObjCCategoriesVisitor Visitor(*this, D, CategoriesDeserialized, ID,
4464                                 PreviousGeneration);
4465   ModuleMgr.visit(Visitor);
4466 }
4467 
4468 template<typename DeclT, typename Fn>
4469 static void forAllLaterRedecls(DeclT *D, Fn F) {
4470   F(D);
4471 
4472   // Check whether we've already merged D into its redeclaration chain.
4473   // MostRecent may or may not be nullptr if D has not been merged. If
4474   // not, walk the merged redecl chain and see if it's there.
4475   auto *MostRecent = D->getMostRecentDecl();
4476   bool Found = false;
4477   for (auto *Redecl = MostRecent; Redecl && !Found;
4478        Redecl = Redecl->getPreviousDecl())
4479     Found = (Redecl == D);
4480 
4481   // If this declaration is merged, apply the functor to all later decls.
4482   if (Found) {
4483     for (auto *Redecl = MostRecent; Redecl != D;
4484          Redecl = Redecl->getPreviousDecl())
4485       F(Redecl);
4486   }
4487 }
4488 
4489 void ASTDeclReader::UpdateDecl(Decl *D,
4490    llvm::SmallVectorImpl<serialization::DeclID> &PendingLazySpecializationIDs) {
4491   while (Record.getIdx() < Record.size()) {
4492     switch ((DeclUpdateKind)Record.readInt()) {
4493     case UPD_CXX_ADDED_IMPLICIT_MEMBER: {
4494       auto *RD = cast<CXXRecordDecl>(D);
4495       // FIXME: If we also have an update record for instantiating the
4496       // definition of D, we need that to happen before we get here.
4497       Decl *MD = Record.readDecl();
4498       assert(MD && "couldn't read decl from update record");
4499       // FIXME: We should call addHiddenDecl instead, to add the member
4500       // to its DeclContext.
4501       RD->addedMember(MD);
4502       break;
4503     }
4504 
4505     case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
4506       // It will be added to the template's lazy specialization set.
4507       PendingLazySpecializationIDs.push_back(readDeclID());
4508       break;
4509 
4510     case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: {
4511       auto *Anon = readDeclAs<NamespaceDecl>();
4512 
4513       // Each module has its own anonymous namespace, which is disjoint from
4514       // any other module's anonymous namespaces, so don't attach the anonymous
4515       // namespace at all.
4516       if (!Record.isModule()) {
4517         if (auto *TU = dyn_cast<TranslationUnitDecl>(D))
4518           TU->setAnonymousNamespace(Anon);
4519         else
4520           cast<NamespaceDecl>(D)->setAnonymousNamespace(Anon);
4521       }
4522       break;
4523     }
4524 
4525     case UPD_CXX_ADDED_VAR_DEFINITION: {
4526       auto *VD = cast<VarDecl>(D);
4527       VD->NonParmVarDeclBits.IsInline = Record.readInt();
4528       VD->NonParmVarDeclBits.IsInlineSpecified = Record.readInt();
4529       uint64_t Val = Record.readInt();
4530       if (Val && !VD->getInit()) {
4531         VD->setInit(Record.readExpr());
4532         if (Val != 1) {
4533           EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
4534           Eval->HasConstantInitialization = (Val & 2) != 0;
4535           Eval->HasConstantDestruction = (Val & 4) != 0;
4536         }
4537       }
4538       break;
4539     }
4540 
4541     case UPD_CXX_POINT_OF_INSTANTIATION: {
4542       SourceLocation POI = Record.readSourceLocation();
4543       if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) {
4544         VTSD->setPointOfInstantiation(POI);
4545       } else if (auto *VD = dyn_cast<VarDecl>(D)) {
4546         VD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
4547       } else {
4548         auto *FD = cast<FunctionDecl>(D);
4549         if (auto *FTSInfo = FD->TemplateOrSpecialization
4550                     .dyn_cast<FunctionTemplateSpecializationInfo *>())
4551           FTSInfo->setPointOfInstantiation(POI);
4552         else
4553           FD->TemplateOrSpecialization.get<MemberSpecializationInfo *>()
4554               ->setPointOfInstantiation(POI);
4555       }
4556       break;
4557     }
4558 
4559     case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT: {
4560       auto *Param = cast<ParmVarDecl>(D);
4561 
4562       // We have to read the default argument regardless of whether we use it
4563       // so that hypothetical further update records aren't messed up.
4564       // TODO: Add a function to skip over the next expr record.
4565       auto *DefaultArg = Record.readExpr();
4566 
4567       // Only apply the update if the parameter still has an uninstantiated
4568       // default argument.
4569       if (Param->hasUninstantiatedDefaultArg())
4570         Param->setDefaultArg(DefaultArg);
4571       break;
4572     }
4573 
4574     case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER: {
4575       auto *FD = cast<FieldDecl>(D);
4576       auto *DefaultInit = Record.readExpr();
4577 
4578       // Only apply the update if the field still has an uninstantiated
4579       // default member initializer.
4580       if (FD->hasInClassInitializer() && !FD->getInClassInitializer()) {
4581         if (DefaultInit)
4582           FD->setInClassInitializer(DefaultInit);
4583         else
4584           // Instantiation failed. We can get here if we serialized an AST for
4585           // an invalid program.
4586           FD->removeInClassInitializer();
4587       }
4588       break;
4589     }
4590 
4591     case UPD_CXX_ADDED_FUNCTION_DEFINITION: {
4592       auto *FD = cast<FunctionDecl>(D);
4593       if (Reader.PendingBodies[FD]) {
4594         // FIXME: Maybe check for ODR violations.
4595         // It's safe to stop now because this update record is always last.
4596         return;
4597       }
4598 
4599       if (Record.readInt()) {
4600         // Maintain AST consistency: any later redeclarations of this function
4601         // are inline if this one is. (We might have merged another declaration
4602         // into this one.)
4603         forAllLaterRedecls(FD, [](FunctionDecl *FD) {
4604           FD->setImplicitlyInline();
4605         });
4606       }
4607       FD->setInnerLocStart(readSourceLocation());
4608       ReadFunctionDefinition(FD);
4609       assert(Record.getIdx() == Record.size() && "lazy body must be last");
4610       break;
4611     }
4612 
4613     case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
4614       auto *RD = cast<CXXRecordDecl>(D);
4615       auto *OldDD = RD->getCanonicalDecl()->DefinitionData;
4616       bool HadRealDefinition =
4617           OldDD && (OldDD->Definition != RD ||
4618                     !Reader.PendingFakeDefinitionData.count(OldDD));
4619       RD->setParamDestroyedInCallee(Record.readInt());
4620       RD->setArgPassingRestrictions(
4621           (RecordDecl::ArgPassingKind)Record.readInt());
4622       ReadCXXRecordDefinition(RD, /*Update*/true);
4623 
4624       // Visible update is handled separately.
4625       uint64_t LexicalOffset = ReadLocalOffset();
4626       if (!HadRealDefinition && LexicalOffset) {
4627         Record.readLexicalDeclContextStorage(LexicalOffset, RD);
4628         Reader.PendingFakeDefinitionData.erase(OldDD);
4629       }
4630 
4631       auto TSK = (TemplateSpecializationKind)Record.readInt();
4632       SourceLocation POI = readSourceLocation();
4633       if (MemberSpecializationInfo *MSInfo =
4634               RD->getMemberSpecializationInfo()) {
4635         MSInfo->setTemplateSpecializationKind(TSK);
4636         MSInfo->setPointOfInstantiation(POI);
4637       } else {
4638         auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
4639         Spec->setTemplateSpecializationKind(TSK);
4640         Spec->setPointOfInstantiation(POI);
4641 
4642         if (Record.readInt()) {
4643           auto *PartialSpec =
4644               readDeclAs<ClassTemplatePartialSpecializationDecl>();
4645           SmallVector<TemplateArgument, 8> TemplArgs;
4646           Record.readTemplateArgumentList(TemplArgs);
4647           auto *TemplArgList = TemplateArgumentList::CreateCopy(
4648               Reader.getContext(), TemplArgs);
4649 
4650           // FIXME: If we already have a partial specialization set,
4651           // check that it matches.
4652           if (!Spec->getSpecializedTemplateOrPartial()
4653                    .is<ClassTemplatePartialSpecializationDecl *>())
4654             Spec->setInstantiationOf(PartialSpec, TemplArgList);
4655         }
4656       }
4657 
4658       RD->setTagKind((TagTypeKind)Record.readInt());
4659       RD->setLocation(readSourceLocation());
4660       RD->setLocStart(readSourceLocation());
4661       RD->setBraceRange(readSourceRange());
4662 
4663       if (Record.readInt()) {
4664         AttrVec Attrs;
4665         Record.readAttributes(Attrs);
4666         // If the declaration already has attributes, we assume that some other
4667         // AST file already loaded them.
4668         if (!D->hasAttrs())
4669           D->setAttrsImpl(Attrs, Reader.getContext());
4670       }
4671       break;
4672     }
4673 
4674     case UPD_CXX_RESOLVED_DTOR_DELETE: {
4675       // Set the 'operator delete' directly to avoid emitting another update
4676       // record.
4677       auto *Del = readDeclAs<FunctionDecl>();
4678       auto *First = cast<CXXDestructorDecl>(D->getCanonicalDecl());
4679       auto *ThisArg = Record.readExpr();
4680       // FIXME: Check consistency if we have an old and new operator delete.
4681       if (!First->OperatorDelete) {
4682         First->OperatorDelete = Del;
4683         First->OperatorDeleteThisArg = ThisArg;
4684       }
4685       break;
4686     }
4687 
4688     case UPD_CXX_RESOLVED_EXCEPTION_SPEC: {
4689       SmallVector<QualType, 8> ExceptionStorage;
4690       auto ESI = Record.readExceptionSpecInfo(ExceptionStorage);
4691 
4692       // Update this declaration's exception specification, if needed.
4693       auto *FD = cast<FunctionDecl>(D);
4694       auto *FPT = FD->getType()->castAs<FunctionProtoType>();
4695       // FIXME: If the exception specification is already present, check that it
4696       // matches.
4697       if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
4698         FD->setType(Reader.getContext().getFunctionType(
4699             FPT->getReturnType(), FPT->getParamTypes(),
4700             FPT->getExtProtoInfo().withExceptionSpec(ESI)));
4701 
4702         // When we get to the end of deserializing, see if there are other decls
4703         // that we need to propagate this exception specification onto.
4704         Reader.PendingExceptionSpecUpdates.insert(
4705             std::make_pair(FD->getCanonicalDecl(), FD));
4706       }
4707       break;
4708     }
4709 
4710     case UPD_CXX_DEDUCED_RETURN_TYPE: {
4711       auto *FD = cast<FunctionDecl>(D);
4712       QualType DeducedResultType = Record.readType();
4713       Reader.PendingDeducedTypeUpdates.insert(
4714           {FD->getCanonicalDecl(), DeducedResultType});
4715       break;
4716     }
4717 
4718     case UPD_DECL_MARKED_USED:
4719       // Maintain AST consistency: any later redeclarations are used too.
4720       D->markUsed(Reader.getContext());
4721       break;
4722 
4723     case UPD_MANGLING_NUMBER:
4724       Reader.getContext().setManglingNumber(cast<NamedDecl>(D),
4725                                             Record.readInt());
4726       break;
4727 
4728     case UPD_STATIC_LOCAL_NUMBER:
4729       Reader.getContext().setStaticLocalNumber(cast<VarDecl>(D),
4730                                                Record.readInt());
4731       break;
4732 
4733     case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
4734       D->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
4735           Reader.getContext(), readSourceRange(),
4736           AttributeCommonInfo::AS_Pragma));
4737       break;
4738 
4739     case UPD_DECL_MARKED_OPENMP_ALLOCATE: {
4740       auto AllocatorKind =
4741           static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(Record.readInt());
4742       Expr *Allocator = Record.readExpr();
4743       SourceRange SR = readSourceRange();
4744       D->addAttr(OMPAllocateDeclAttr::CreateImplicit(
4745           Reader.getContext(), AllocatorKind, Allocator, SR,
4746           AttributeCommonInfo::AS_Pragma));
4747       break;
4748     }
4749 
4750     case UPD_DECL_EXPORTED: {
4751       unsigned SubmoduleID = readSubmoduleID();
4752       auto *Exported = cast<NamedDecl>(D);
4753       Module *Owner = SubmoduleID ? Reader.getSubmodule(SubmoduleID) : nullptr;
4754       Reader.getContext().mergeDefinitionIntoModule(Exported, Owner);
4755       Reader.PendingMergedDefinitionsToDeduplicate.insert(Exported);
4756       break;
4757     }
4758 
4759     case UPD_DECL_MARKED_OPENMP_DECLARETARGET: {
4760       auto MapType = Record.readEnum<OMPDeclareTargetDeclAttr::MapTypeTy>();
4761       auto DevType = Record.readEnum<OMPDeclareTargetDeclAttr::DevTypeTy>();
4762       unsigned Level = Record.readInt();
4763       D->addAttr(OMPDeclareTargetDeclAttr::CreateImplicit(
4764           Reader.getContext(), MapType, DevType, Level, readSourceRange(),
4765           AttributeCommonInfo::AS_Pragma));
4766       break;
4767     }
4768 
4769     case UPD_ADDED_ATTR_TO_RECORD:
4770       AttrVec Attrs;
4771       Record.readAttributes(Attrs);
4772       assert(Attrs.size() == 1);
4773       D->addAttr(Attrs[0]);
4774       break;
4775     }
4776   }
4777 }
4778