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