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