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

source code of clang/lib/Serialization/ASTReaderDecl.cpp