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