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