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