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