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