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

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