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