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