1 //===- ASTReaderDecl.cpp - Decl Deserialization ---------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the ASTReader::ReadDeclRecord method, which is the
11 // entrypoint for loading a decl.
13 //===----------------------------------------------------------------------===//
15 #include "ASTCommon.h"
16 #include "ASTReaderInternals.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/Attr.h"
19 #include "clang/AST/AttrIterator.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclBase.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclFriend.h"
24 #include "clang/AST/DeclObjC.h"
25 #include "clang/AST/DeclOpenMP.h"
26 #include "clang/AST/DeclTemplate.h"
27 #include "clang/AST/DeclVisitor.h"
28 #include "clang/AST/DeclarationName.h"
29 #include "clang/AST/Expr.h"
30 #include "clang/AST/ExternalASTSource.h"
31 #include "clang/AST/LambdaCapture.h"
32 #include "clang/AST/NestedNameSpecifier.h"
33 #include "clang/AST/OpenMPClause.h"
34 #include "clang/AST/Redeclarable.h"
35 #include "clang/AST/Stmt.h"
36 #include "clang/AST/TemplateBase.h"
37 #include "clang/AST/Type.h"
38 #include "clang/AST/UnresolvedSet.h"
39 #include "clang/Basic/AttrKinds.h"
40 #include "clang/Basic/ExceptionSpecificationType.h"
41 #include "clang/Basic/IdentifierTable.h"
42 #include "clang/Basic/LLVM.h"
43 #include "clang/Basic/Lambda.h"
44 #include "clang/Basic/LangOptions.h"
45 #include "clang/Basic/Linkage.h"
46 #include "clang/Basic/Module.h"
47 #include "clang/Basic/PragmaKinds.h"
48 #include "clang/Basic/SourceLocation.h"
49 #include "clang/Basic/Specifiers.h"
50 #include "clang/Sema/IdentifierResolver.h"
51 #include "clang/Serialization/ASTBitCodes.h"
52 #include "clang/Serialization/ASTReader.h"
53 #include "clang/Serialization/ContinuousRangeMap.h"
54 #include "clang/Serialization/Module.h"
55 #include "llvm/ADT/DenseMap.h"
56 #include "llvm/ADT/FoldingSet.h"
57 #include "llvm/ADT/STLExtras.h"
58 #include "llvm/ADT/SmallPtrSet.h"
59 #include "llvm/ADT/SmallVector.h"
60 #include "llvm/ADT/iterator_range.h"
61 #include "llvm/Bitcode/BitstreamReader.h"
62 #include "llvm/Support/Casting.h"
63 #include "llvm/Support/ErrorHandling.h"
64 #include "llvm/Support/SaveAndRestore.h"
72 using namespace clang;
73 using namespace serialization;
75 //===----------------------------------------------------------------------===//
76 // Declaration deserialization
77 //===----------------------------------------------------------------------===//
81 class ASTDeclReader : public DeclVisitor<ASTDeclReader, void> {
83 ASTRecordReader &Record;
84 ASTReader::RecordLocation Loc;
85 const DeclID ThisDeclID;
86 const SourceLocation ThisDeclLoc;
88 using RecordData = ASTReader::RecordData;
90 TypeID DeferredTypeID = 0;
91 unsigned AnonymousDeclNumber;
92 GlobalDeclID NamedDeclForTagDecl = 0;
93 IdentifierInfo *TypedefNameForLinkage = nullptr;
95 bool HasPendingBody = false;
97 ///A flag to carry the information for a decl from the entity is
98 /// used. We use it to delay the marking of the canonical decl as used until
99 /// the entire declaration is deserialized and merged.
100 bool IsDeclMarkedUsed = false;
102 uint64_t GetCurrentCursorOffset();
104 uint64_t ReadLocalOffset() {
105 uint64_t LocalOffset = Record.readInt();
106 assert(LocalOffset < Loc.Offset && "offset point after current record");
107 return LocalOffset ? Loc.Offset - LocalOffset : 0;
110 uint64_t ReadGlobalOffset() {
111 uint64_t Local = ReadLocalOffset();
112 return Local ? Record.getGlobalBitOffset(Local) : 0;
115 SourceLocation ReadSourceLocation() {
116 return Record.readSourceLocation();
119 SourceRange ReadSourceRange() {
120 return Record.readSourceRange();
123 TypeSourceInfo *GetTypeSourceInfo() {
124 return Record.getTypeSourceInfo();
127 serialization::DeclID ReadDeclID() {
128 return Record.readDeclID();
131 std::string ReadString() {
132 return Record.readString();
135 void ReadDeclIDList(SmallVectorImpl<DeclID> &IDs) {
136 for (unsigned I = 0, Size = Record.readInt(); I != Size; ++I)
137 IDs.push_back(ReadDeclID());
141 return Record.readDecl();
146 return Record.readDeclAs<T>();
149 void ReadQualifierInfo(QualifierInfo &Info) {
150 Record.readQualifierInfo(Info);
153 void ReadDeclarationNameLoc(DeclarationNameLoc &DNLoc, DeclarationName Name) {
154 Record.readDeclarationNameLoc(DNLoc, Name);
157 serialization::SubmoduleID readSubmoduleID() {
158 if (Record.getIdx() == Record.size())
161 return Record.getGlobalSubmoduleID(Record.readInt());
164 Module *readModule() {
165 return Record.getSubmodule(readSubmoduleID());
168 void ReadCXXRecordDefinition(CXXRecordDecl *D, bool Update);
169 void ReadCXXDefinitionData(struct CXXRecordDecl::DefinitionData &Data,
170 const CXXRecordDecl *D);
171 void MergeDefinitionData(CXXRecordDecl *D,
172 struct CXXRecordDecl::DefinitionData &&NewDD);
173 void ReadObjCDefinitionData(struct ObjCInterfaceDecl::DefinitionData &Data);
174 void MergeDefinitionData(ObjCInterfaceDecl *D,
175 struct ObjCInterfaceDecl::DefinitionData &&NewDD);
176 void ReadObjCDefinitionData(struct ObjCProtocolDecl::DefinitionData &Data);
177 void MergeDefinitionData(ObjCProtocolDecl *D,
178 struct ObjCProtocolDecl::DefinitionData &&NewDD);
180 static DeclContext *getPrimaryDCForAnonymousDecl(DeclContext *LexicalDC);
182 static NamedDecl *getAnonymousDeclForMerging(ASTReader &Reader,
185 static void setAnonymousDeclForMerging(ASTReader &Reader, DeclContext *DC,
186 unsigned Index, NamedDecl *D);
188 /// Results from loading a RedeclarableDecl.
189 class RedeclarableResult {
191 GlobalDeclID FirstID;
195 RedeclarableResult(Decl *MergeWith, GlobalDeclID FirstID, bool IsKeyDecl)
196 : MergeWith(MergeWith), FirstID(FirstID), IsKeyDecl(IsKeyDecl) {}
198 /// Retrieve the first ID.
199 GlobalDeclID getFirstID() const { return FirstID; }
201 /// Is this declaration a key declaration?
202 bool isKeyDecl() const { return IsKeyDecl; }
204 /// Get a known declaration that this should be merged with, if
206 Decl *getKnownMergeTarget() const { return MergeWith; }
209 /// Class used to capture the result of searching for an existing
210 /// declaration of a specific kind and name, along with the ability
211 /// to update the place where this result was found (the declaration
212 /// chain hanging off an identifier or the DeclContext we searched in)
214 class FindExistingResult {
216 NamedDecl *New = nullptr;
217 NamedDecl *Existing = nullptr;
218 bool AddResult = false;
219 unsigned AnonymousDeclNumber = 0;
220 IdentifierInfo *TypedefNameForLinkage = nullptr;
223 FindExistingResult(ASTReader &Reader) : Reader(Reader) {}
225 FindExistingResult(ASTReader &Reader, NamedDecl *New, NamedDecl *Existing,
226 unsigned AnonymousDeclNumber,
227 IdentifierInfo *TypedefNameForLinkage)
228 : Reader(Reader), New(New), Existing(Existing), AddResult(true),
229 AnonymousDeclNumber(AnonymousDeclNumber),
230 TypedefNameForLinkage(TypedefNameForLinkage) {}
232 FindExistingResult(FindExistingResult &&Other)
233 : Reader(Other.Reader), New(Other.New), Existing(Other.Existing),
234 AddResult(Other.AddResult),
235 AnonymousDeclNumber(Other.AnonymousDeclNumber),
236 TypedefNameForLinkage(Other.TypedefNameForLinkage) {
237 Other.AddResult = false;
240 FindExistingResult &operator=(FindExistingResult &&) = delete;
241 ~FindExistingResult();
243 /// Suppress the addition of this result into the known set of
245 void suppress() { AddResult = false; }
247 operator NamedDecl*() const { return Existing; }
250 operator T*() const { return dyn_cast_or_null<T>(Existing); }
253 static DeclContext *getPrimaryContextForMerging(ASTReader &Reader,
255 FindExistingResult findExisting(NamedDecl *D);
258 ASTDeclReader(ASTReader &Reader, ASTRecordReader &Record,
259 ASTReader::RecordLocation Loc,
260 DeclID thisDeclID, SourceLocation ThisDeclLoc)
261 : Reader(Reader), Record(Record), Loc(Loc), ThisDeclID(thisDeclID),
262 ThisDeclLoc(ThisDeclLoc) {}
264 template <typename T> static
265 void AddLazySpecializations(T *D,
266 SmallVectorImpl<serialization::DeclID>& IDs) {
270 // FIXME: We should avoid this pattern of getting the ASTContext.
271 ASTContext &C = D->getASTContext();
273 auto *&LazySpecializations = D->getCommonPtr()->LazySpecializations;
275 if (auto &Old = LazySpecializations) {
276 IDs.insert(IDs.end(), Old + 1, Old + 1 + Old[0]);
278 IDs.erase(std::unique(IDs.begin(), IDs.end()), IDs.end());
281 auto *Result = new (C) serialization::DeclID[1 + IDs.size()];
282 *Result = IDs.size();
283 std::copy(IDs.begin(), IDs.end(), Result + 1);
285 LazySpecializations = Result;
288 template <typename DeclT>
289 static Decl *getMostRecentDeclImpl(Redeclarable<DeclT> *D);
290 static Decl *getMostRecentDeclImpl(...);
291 static Decl *getMostRecentDecl(Decl *D);
293 template <typename DeclT>
294 static void attachPreviousDeclImpl(ASTReader &Reader,
295 Redeclarable<DeclT> *D, Decl *Previous,
297 static void attachPreviousDeclImpl(ASTReader &Reader, ...);
298 static void attachPreviousDecl(ASTReader &Reader, Decl *D, Decl *Previous,
301 template <typename DeclT>
302 static void attachLatestDeclImpl(Redeclarable<DeclT> *D, Decl *Latest);
303 static void attachLatestDeclImpl(...);
304 static void attachLatestDecl(Decl *D, Decl *latest);
306 template <typename DeclT>
307 static void markIncompleteDeclChainImpl(Redeclarable<DeclT> *D);
308 static void markIncompleteDeclChainImpl(...);
310 /// Determine whether this declaration has a pending body.
311 bool hasPendingBody() const { return HasPendingBody; }
313 void ReadFunctionDefinition(FunctionDecl *FD);
316 void UpdateDecl(Decl *D, SmallVectorImpl<serialization::DeclID> &);
318 static void setNextObjCCategory(ObjCCategoryDecl *Cat,
319 ObjCCategoryDecl *Next) {
320 Cat->NextClassCategory = Next;
323 void VisitDecl(Decl *D);
324 void VisitPragmaCommentDecl(PragmaCommentDecl *D);
325 void VisitPragmaDetectMismatchDecl(PragmaDetectMismatchDecl *D);
326 void VisitTranslationUnitDecl(TranslationUnitDecl *TU);
327 void VisitNamedDecl(NamedDecl *ND);
328 void VisitLabelDecl(LabelDecl *LD);
329 void VisitNamespaceDecl(NamespaceDecl *D);
330 void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
331 void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
332 void VisitTypeDecl(TypeDecl *TD);
333 RedeclarableResult VisitTypedefNameDecl(TypedefNameDecl *TD);
334 void VisitTypedefDecl(TypedefDecl *TD);
335 void VisitTypeAliasDecl(TypeAliasDecl *TD);
336 void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
337 RedeclarableResult VisitTagDecl(TagDecl *TD);
338 void VisitEnumDecl(EnumDecl *ED);
339 RedeclarableResult VisitRecordDeclImpl(RecordDecl *RD);
340 void VisitRecordDecl(RecordDecl *RD) { VisitRecordDeclImpl(RD); }
341 RedeclarableResult VisitCXXRecordDeclImpl(CXXRecordDecl *D);
342 void VisitCXXRecordDecl(CXXRecordDecl *D) { VisitCXXRecordDeclImpl(D); }
343 RedeclarableResult VisitClassTemplateSpecializationDeclImpl(
344 ClassTemplateSpecializationDecl *D);
346 void VisitClassTemplateSpecializationDecl(
347 ClassTemplateSpecializationDecl *D) {
348 VisitClassTemplateSpecializationDeclImpl(D);
351 void VisitClassTemplatePartialSpecializationDecl(
352 ClassTemplatePartialSpecializationDecl *D);
353 void VisitClassScopeFunctionSpecializationDecl(
354 ClassScopeFunctionSpecializationDecl *D);
356 VisitVarTemplateSpecializationDeclImpl(VarTemplateSpecializationDecl *D);
358 void VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D) {
359 VisitVarTemplateSpecializationDeclImpl(D);
362 void VisitVarTemplatePartialSpecializationDecl(
363 VarTemplatePartialSpecializationDecl *D);
364 void VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
365 void VisitValueDecl(ValueDecl *VD);
366 void VisitEnumConstantDecl(EnumConstantDecl *ECD);
367 void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
368 void VisitDeclaratorDecl(DeclaratorDecl *DD);
369 void VisitFunctionDecl(FunctionDecl *FD);
370 void VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *GD);
371 void VisitCXXMethodDecl(CXXMethodDecl *D);
372 void VisitCXXConstructorDecl(CXXConstructorDecl *D);
373 void VisitCXXDestructorDecl(CXXDestructorDecl *D);
374 void VisitCXXConversionDecl(CXXConversionDecl *D);
375 void VisitFieldDecl(FieldDecl *FD);
376 void VisitMSPropertyDecl(MSPropertyDecl *FD);
377 void VisitIndirectFieldDecl(IndirectFieldDecl *FD);
378 RedeclarableResult VisitVarDeclImpl(VarDecl *D);
379 void VisitVarDecl(VarDecl *VD) { VisitVarDeclImpl(VD); }
380 void VisitImplicitParamDecl(ImplicitParamDecl *PD);
381 void VisitParmVarDecl(ParmVarDecl *PD);
382 void VisitDecompositionDecl(DecompositionDecl *DD);
383 void VisitBindingDecl(BindingDecl *BD);
384 void VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
385 DeclID VisitTemplateDecl(TemplateDecl *D);
386 RedeclarableResult VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D);
387 void VisitClassTemplateDecl(ClassTemplateDecl *D);
388 void VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D);
389 void VisitVarTemplateDecl(VarTemplateDecl *D);
390 void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
391 void VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
392 void VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
393 void VisitUsingDecl(UsingDecl *D);
394 void VisitUsingPackDecl(UsingPackDecl *D);
395 void VisitUsingShadowDecl(UsingShadowDecl *D);
396 void VisitConstructorUsingShadowDecl(ConstructorUsingShadowDecl *D);
397 void VisitLinkageSpecDecl(LinkageSpecDecl *D);
398 void VisitExportDecl(ExportDecl *D);
399 void VisitFileScopeAsmDecl(FileScopeAsmDecl *AD);
400 void VisitImportDecl(ImportDecl *D);
401 void VisitAccessSpecDecl(AccessSpecDecl *D);
402 void VisitFriendDecl(FriendDecl *D);
403 void VisitFriendTemplateDecl(FriendTemplateDecl *D);
404 void VisitStaticAssertDecl(StaticAssertDecl *D);
405 void VisitBlockDecl(BlockDecl *BD);
406 void VisitCapturedDecl(CapturedDecl *CD);
407 void VisitEmptyDecl(EmptyDecl *D);
409 std::pair<uint64_t, uint64_t> VisitDeclContext(DeclContext *DC);
412 RedeclarableResult VisitRedeclarable(Redeclarable<T> *D);
415 void mergeRedeclarable(Redeclarable<T> *D, RedeclarableResult &Redecl,
416 DeclID TemplatePatternID = 0);
419 void mergeRedeclarable(Redeclarable<T> *D, T *Existing,
420 RedeclarableResult &Redecl,
421 DeclID TemplatePatternID = 0);
424 void mergeMergeable(Mergeable<T> *D);
426 void mergeTemplatePattern(RedeclarableTemplateDecl *D,
427 RedeclarableTemplateDecl *Existing,
428 DeclID DsID, bool IsKeyDecl);
430 ObjCTypeParamList *ReadObjCTypeParamList();
432 // FIXME: Reorder according to DeclNodes.td?
433 void VisitObjCMethodDecl(ObjCMethodDecl *D);
434 void VisitObjCTypeParamDecl(ObjCTypeParamDecl *D);
435 void VisitObjCContainerDecl(ObjCContainerDecl *D);
436 void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
437 void VisitObjCIvarDecl(ObjCIvarDecl *D);
438 void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
439 void VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D);
440 void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
441 void VisitObjCImplDecl(ObjCImplDecl *D);
442 void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
443 void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
444 void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D);
445 void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
446 void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
447 void VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D);
448 void VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D);
449 void VisitOMPRequiresDecl(OMPRequiresDecl *D);
450 void VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D);
457 /// Iterator over the redeclarations of a declaration that have already
458 /// been merged into the same redeclaration chain.
459 template<typename DeclT>
460 class MergedRedeclIterator {
462 DeclT *Canonical = nullptr;
463 DeclT *Current = nullptr;
466 MergedRedeclIterator() = default;
467 MergedRedeclIterator(DeclT *Start) : Start(Start), Current(Start) {}
469 DeclT *operator*() { return Current; }
471 MergedRedeclIterator &operator++() {
472 if (Current->isFirstDecl()) {
474 Current = Current->getMostRecentDecl();
476 Current = Current->getPreviousDecl();
478 // If we started in the merged portion, we'll reach our start position
479 // eventually. Otherwise, we'll never reach it, but the second declaration
480 // we reached was the canonical declaration, so stop when we see that one
482 if (Current == Start || Current == Canonical)
487 friend bool operator!=(const MergedRedeclIterator &A,
488 const MergedRedeclIterator &B) {
489 return A.Current != B.Current;
495 template <typename DeclT>
496 static llvm::iterator_range<MergedRedeclIterator<DeclT>>
497 merged_redecls(DeclT *D) {
498 return llvm::make_range(MergedRedeclIterator<DeclT>(D),
499 MergedRedeclIterator<DeclT>());
502 uint64_t ASTDeclReader::GetCurrentCursorOffset() {
503 return Loc.F->DeclsCursor.GetCurrentBitNo() + Loc.F->GlobalBitOffset;
506 void ASTDeclReader::ReadFunctionDefinition(FunctionDecl *FD) {
507 if (Record.readInt())
508 Reader.DefinitionSource[FD] = Loc.F->Kind == ModuleKind::MK_MainFile;
509 if (auto *CD = dyn_cast<CXXConstructorDecl>(FD)) {
510 CD->setNumCtorInitializers(Record.readInt());
511 if (CD->getNumCtorInitializers())
512 CD->CtorInitializers = ReadGlobalOffset();
514 // Store the offset of the body so we can lazily load it later.
515 Reader.PendingBodies[FD] = GetCurrentCursorOffset();
516 HasPendingBody = true;
519 void ASTDeclReader::Visit(Decl *D) {
520 DeclVisitor<ASTDeclReader, void>::Visit(D);
522 // At this point we have deserialized and merged the decl and it is safe to
523 // update its canonical decl to signal that the entire entity is used.
524 D->getCanonicalDecl()->Used |= IsDeclMarkedUsed;
525 IsDeclMarkedUsed = false;
527 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
528 if (auto *TInfo = DD->getTypeSourceInfo())
529 Record.readTypeLoc(TInfo->getTypeLoc());
532 if (auto *TD = dyn_cast<TypeDecl>(D)) {
533 // We have a fully initialized TypeDecl. Read its type now.
534 TD->setTypeForDecl(Reader.GetType(DeferredTypeID).getTypePtrOrNull());
536 // If this is a tag declaration with a typedef name for linkage, it's safe
537 // to load that typedef now.
538 if (NamedDeclForTagDecl)
539 cast<TagDecl>(D)->TypedefNameDeclOrQualifier =
540 cast<TypedefNameDecl>(Reader.GetDecl(NamedDeclForTagDecl));
541 } else if (auto *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
542 // if we have a fully initialized TypeDecl, we can safely read its type now.
543 ID->TypeForDecl = Reader.GetType(DeferredTypeID).getTypePtrOrNull();
544 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
545 // FunctionDecl's body was written last after all other Stmts/Exprs.
546 // We only read it if FD doesn't already have a body (e.g., from another
548 // FIXME: Can we diagnose ODR violations somehow?
549 if (Record.readInt())
550 ReadFunctionDefinition(FD);
554 void ASTDeclReader::VisitDecl(Decl *D) {
555 if (D->isTemplateParameter() || D->isTemplateParameterPack() ||
556 isa<ParmVarDecl>(D)) {
557 // We don't want to deserialize the DeclContext of a template
558 // parameter or of a parameter of a function template immediately. These
559 // entities might be used in the formulation of its DeclContext (for
560 // example, a function parameter can be used in decltype() in trailing
561 // return type of the function). Use the translation unit DeclContext as a
563 GlobalDeclID SemaDCIDForTemplateParmDecl = ReadDeclID();
564 GlobalDeclID LexicalDCIDForTemplateParmDecl = ReadDeclID();
565 if (!LexicalDCIDForTemplateParmDecl)
566 LexicalDCIDForTemplateParmDecl = SemaDCIDForTemplateParmDecl;
567 Reader.addPendingDeclContextInfo(D,
568 SemaDCIDForTemplateParmDecl,
569 LexicalDCIDForTemplateParmDecl);
570 D->setDeclContext(Reader.getContext().getTranslationUnitDecl());
572 auto *SemaDC = ReadDeclAs<DeclContext>();
573 auto *LexicalDC = ReadDeclAs<DeclContext>();
576 DeclContext *MergedSemaDC = Reader.MergedDeclContexts.lookup(SemaDC);
577 // Avoid calling setLexicalDeclContext() directly because it uses
578 // Decl::getASTContext() internally which is unsafe during derialization.
579 D->setDeclContextsImpl(MergedSemaDC ? MergedSemaDC : SemaDC, LexicalDC,
580 Reader.getContext());
582 D->setLocation(ThisDeclLoc);
583 D->setInvalidDecl(Record.readInt());
584 if (Record.readInt()) { // hasAttrs
586 Record.readAttributes(Attrs);
587 // Avoid calling setAttrs() directly because it uses Decl::getASTContext()
588 // internally which is unsafe during derialization.
589 D->setAttrsImpl(Attrs, Reader.getContext());
591 D->setImplicit(Record.readInt());
592 D->Used = Record.readInt();
593 IsDeclMarkedUsed |= D->Used;
594 D->setReferenced(Record.readInt());
595 D->setTopLevelDeclInObjCContainer(Record.readInt());
596 D->setAccess((AccessSpecifier)Record.readInt());
597 D->FromASTFile = true;
598 bool ModulePrivate = Record.readInt();
600 // Determine whether this declaration is part of a (sub)module. If so, it
601 // may not yet be visible.
602 if (unsigned SubmoduleID = readSubmoduleID()) {
603 // Store the owning submodule ID in the declaration.
604 D->setModuleOwnershipKind(
605 ModulePrivate ? Decl::ModuleOwnershipKind::ModulePrivate
606 : Decl::ModuleOwnershipKind::VisibleWhenImported);
607 D->setOwningModuleID(SubmoduleID);
610 // Module-private declarations are never visible, so there is no work to
612 } else if (Reader.getContext().getLangOpts().ModulesLocalVisibility) {
613 // If local visibility is being tracked, this declaration will become
614 // hidden and visible as the owning module does.
615 } else if (Module *Owner = Reader.getSubmodule(SubmoduleID)) {
616 // Mark the declaration as visible when its owning module becomes visible.
617 if (Owner->NameVisibility == Module::AllVisible)
618 D->setVisibleDespiteOwningModule();
620 Reader.HiddenNamesMap[Owner].push_back(D);
622 } else if (ModulePrivate) {
623 D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
627 void ASTDeclReader::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
629 D->setLocation(ReadSourceLocation());
630 D->CommentKind = (PragmaMSCommentKind)Record.readInt();
631 std::string Arg = ReadString();
632 memcpy(D->getTrailingObjects<char>(), Arg.data(), Arg.size());
633 D->getTrailingObjects<char>()[Arg.size()] = '\0';
636 void ASTDeclReader::VisitPragmaDetectMismatchDecl(PragmaDetectMismatchDecl *D) {
638 D->setLocation(ReadSourceLocation());
639 std::string Name = ReadString();
640 memcpy(D->getTrailingObjects<char>(), Name.data(), Name.size());
641 D->getTrailingObjects<char>()[Name.size()] = '\0';
643 D->ValueStart = Name.size() + 1;
644 std::string Value = ReadString();
645 memcpy(D->getTrailingObjects<char>() + D->ValueStart, Value.data(),
647 D->getTrailingObjects<char>()[D->ValueStart + Value.size()] = '\0';
650 void ASTDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) {
651 llvm_unreachable("Translation units are not serialized");
654 void ASTDeclReader::VisitNamedDecl(NamedDecl *ND) {
656 ND->setDeclName(Record.readDeclarationName());
657 AnonymousDeclNumber = Record.readInt();
660 void ASTDeclReader::VisitTypeDecl(TypeDecl *TD) {
662 TD->setLocStart(ReadSourceLocation());
663 // Delay type reading until after we have fully initialized the decl.
664 DeferredTypeID = Record.getGlobalTypeID(Record.readInt());
667 ASTDeclReader::RedeclarableResult
668 ASTDeclReader::VisitTypedefNameDecl(TypedefNameDecl *TD) {
669 RedeclarableResult Redecl = VisitRedeclarable(TD);
671 TypeSourceInfo *TInfo = GetTypeSourceInfo();
672 if (Record.readInt()) { // isModed
673 QualType modedT = Record.readType();
674 TD->setModedTypeSourceInfo(TInfo, modedT);
676 TD->setTypeSourceInfo(TInfo);
677 // Read and discard the declaration for which this is a typedef name for
678 // linkage, if it exists. We cannot rely on our type to pull in this decl,
679 // because it might have been merged with a type from another module and
680 // thus might not refer to our version of the declaration.
685 void ASTDeclReader::VisitTypedefDecl(TypedefDecl *TD) {
686 RedeclarableResult Redecl = VisitTypedefNameDecl(TD);
687 mergeRedeclarable(TD, Redecl);
690 void ASTDeclReader::VisitTypeAliasDecl(TypeAliasDecl *TD) {
691 RedeclarableResult Redecl = VisitTypedefNameDecl(TD);
692 if (auto *Template = ReadDeclAs<TypeAliasTemplateDecl>())
693 // Merged when we merge the template.
694 TD->setDescribedAliasTemplate(Template);
696 mergeRedeclarable(TD, Redecl);
699 ASTDeclReader::RedeclarableResult ASTDeclReader::VisitTagDecl(TagDecl *TD) {
700 RedeclarableResult Redecl = VisitRedeclarable(TD);
703 TD->IdentifierNamespace = Record.readInt();
704 TD->setTagKind((TagDecl::TagKind)Record.readInt());
705 if (!isa<CXXRecordDecl>(TD))
706 TD->setCompleteDefinition(Record.readInt());
707 TD->setEmbeddedInDeclarator(Record.readInt());
708 TD->setFreeStanding(Record.readInt());
709 TD->setCompleteDefinitionRequired(Record.readInt());
710 TD->setBraceRange(ReadSourceRange());
712 switch (Record.readInt()) {
716 auto *Info = new (Reader.getContext()) TagDecl::ExtInfo();
717 ReadQualifierInfo(*Info);
718 TD->TypedefNameDeclOrQualifier = Info;
721 case 2: // TypedefNameForAnonDecl
722 NamedDeclForTagDecl = ReadDeclID();
723 TypedefNameForLinkage = Record.getIdentifierInfo();
726 llvm_unreachable("unexpected tag info kind");
729 if (!isa<CXXRecordDecl>(TD))
730 mergeRedeclarable(TD, Redecl);
734 void ASTDeclReader::VisitEnumDecl(EnumDecl *ED) {
736 if (TypeSourceInfo *TI = GetTypeSourceInfo())
737 ED->setIntegerTypeSourceInfo(TI);
739 ED->setIntegerType(Record.readType());
740 ED->setPromotionType(Record.readType());
741 ED->setNumPositiveBits(Record.readInt());
742 ED->setNumNegativeBits(Record.readInt());
743 ED->setScoped(Record.readInt());
744 ED->setScopedUsingClassTag(Record.readInt());
745 ED->setFixed(Record.readInt());
747 ED->setHasODRHash(true);
748 ED->ODRHash = Record.readInt();
750 // If this is a definition subject to the ODR, and we already have a
751 // definition, merge this one into it.
752 if (ED->isCompleteDefinition() &&
753 Reader.getContext().getLangOpts().Modules &&
754 Reader.getContext().getLangOpts().CPlusPlus) {
755 EnumDecl *&OldDef = Reader.EnumDefinitions[ED->getCanonicalDecl()];
757 // This is the first time we've seen an imported definition. Look for a
758 // local definition before deciding that we are the first definition.
759 for (auto *D : merged_redecls(ED->getCanonicalDecl())) {
760 if (!D->isFromASTFile() && D->isCompleteDefinition()) {
767 Reader.MergedDeclContexts.insert(std::make_pair(ED, OldDef));
768 ED->setCompleteDefinition(false);
769 Reader.mergeDefinitionVisibility(OldDef, ED);
770 if (OldDef->getODRHash() != ED->getODRHash())
771 Reader.PendingEnumOdrMergeFailures[OldDef].push_back(ED);
777 if (auto *InstED = ReadDeclAs<EnumDecl>()) {
778 auto TSK = (TemplateSpecializationKind)Record.readInt();
779 SourceLocation POI = ReadSourceLocation();
780 ED->setInstantiationOfMemberEnum(Reader.getContext(), InstED, TSK);
781 ED->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
785 ASTDeclReader::RedeclarableResult
786 ASTDeclReader::VisitRecordDeclImpl(RecordDecl *RD) {
787 RedeclarableResult Redecl = VisitTagDecl(RD);
788 RD->setHasFlexibleArrayMember(Record.readInt());
789 RD->setAnonymousStructOrUnion(Record.readInt());
790 RD->setHasObjectMember(Record.readInt());
791 RD->setHasVolatileMember(Record.readInt());
792 RD->setNonTrivialToPrimitiveDefaultInitialize(Record.readInt());
793 RD->setNonTrivialToPrimitiveCopy(Record.readInt());
794 RD->setNonTrivialToPrimitiveDestroy(Record.readInt());
795 RD->setParamDestroyedInCallee(Record.readInt());
796 RD->setArgPassingRestrictions((RecordDecl::ArgPassingKind)Record.readInt());
800 void ASTDeclReader::VisitValueDecl(ValueDecl *VD) {
802 // For function declarations, defer reading the type in case the function has
803 // a deduced return type that references an entity declared within the
805 if (isa<FunctionDecl>(VD))
806 DeferredTypeID = Record.getGlobalTypeID(Record.readInt());
808 VD->setType(Record.readType());
811 void ASTDeclReader::VisitEnumConstantDecl(EnumConstantDecl *ECD) {
813 if (Record.readInt())
814 ECD->setInitExpr(Record.readExpr());
815 ECD->setInitVal(Record.readAPSInt());
819 void ASTDeclReader::VisitDeclaratorDecl(DeclaratorDecl *DD) {
821 DD->setInnerLocStart(ReadSourceLocation());
822 if (Record.readInt()) { // hasExtInfo
823 auto *Info = new (Reader.getContext()) DeclaratorDecl::ExtInfo();
824 ReadQualifierInfo(*Info);
827 QualType TSIType = Record.readType();
828 DD->setTypeSourceInfo(
829 TSIType.isNull() ? nullptr
830 : Reader.getContext().CreateTypeSourceInfo(TSIType));
833 void ASTDeclReader::VisitFunctionDecl(FunctionDecl *FD) {
834 RedeclarableResult Redecl = VisitRedeclarable(FD);
835 VisitDeclaratorDecl(FD);
837 // Attach a type to this function. Use the real type if possible, but fall
838 // back to the type as written if it involves a deduced return type.
839 if (FD->getTypeSourceInfo() &&
840 FD->getTypeSourceInfo()->getType()->castAs<FunctionType>()
841 ->getReturnType()->getContainedAutoType()) {
842 // We'll set up the real type in Visit, once we've finished loading the
844 FD->setType(FD->getTypeSourceInfo()->getType());
845 Reader.PendingFunctionTypes.push_back({FD, DeferredTypeID});
847 FD->setType(Reader.GetType(DeferredTypeID));
851 ReadDeclarationNameLoc(FD->DNLoc, FD->getDeclName());
852 FD->IdentifierNamespace = Record.readInt();
854 // FunctionDecl's body is handled last at ASTDeclReader::Visit,
855 // after everything else is read.
857 FD->setStorageClass(static_cast<StorageClass>(Record.readInt()));
858 FD->setInlineSpecified(Record.readInt());
859 FD->setImplicitlyInline(Record.readInt());
860 FD->setExplicitSpecified(Record.readInt());
861 FD->setVirtualAsWritten(Record.readInt());
862 FD->setPure(Record.readInt());
863 FD->setHasInheritedPrototype(Record.readInt());
864 FD->setHasWrittenPrototype(Record.readInt());
865 FD->setDeletedAsWritten(Record.readInt());
866 FD->setTrivial(Record.readInt());
867 FD->setTrivialForCall(Record.readInt());
868 FD->setDefaulted(Record.readInt());
869 FD->setExplicitlyDefaulted(Record.readInt());
870 FD->setHasImplicitReturnZero(Record.readInt());
871 FD->setConstexpr(Record.readInt());
872 FD->setUsesSEHTry(Record.readInt());
873 FD->setHasSkippedBody(Record.readInt());
874 FD->setIsMultiVersion(Record.readInt());
875 FD->setLateTemplateParsed(Record.readInt());
877 FD->setCachedLinkage(static_cast<Linkage>(Record.readInt()));
878 FD->EndRangeLoc = ReadSourceLocation();
880 FD->ODRHash = Record.readInt();
881 FD->setHasODRHash(true);
883 switch ((FunctionDecl::TemplatedKind)Record.readInt()) {
884 case FunctionDecl::TK_NonTemplate:
885 mergeRedeclarable(FD, Redecl);
887 case FunctionDecl::TK_FunctionTemplate:
888 // Merged when we merge the template.
889 FD->setDescribedFunctionTemplate(ReadDeclAs<FunctionTemplateDecl>());
891 case FunctionDecl::TK_MemberSpecialization: {
892 auto *InstFD = ReadDeclAs<FunctionDecl>();
893 auto TSK = (TemplateSpecializationKind)Record.readInt();
894 SourceLocation POI = ReadSourceLocation();
895 FD->setInstantiationOfMemberFunction(Reader.getContext(), InstFD, TSK);
896 FD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
897 mergeRedeclarable(FD, Redecl);
900 case FunctionDecl::TK_FunctionTemplateSpecialization: {
901 auto *Template = ReadDeclAs<FunctionTemplateDecl>();
902 auto TSK = (TemplateSpecializationKind)Record.readInt();
904 // Template arguments.
905 SmallVector<TemplateArgument, 8> TemplArgs;
906 Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
908 // Template args as written.
909 SmallVector<TemplateArgumentLoc, 8> TemplArgLocs;
910 SourceLocation LAngleLoc, RAngleLoc;
911 bool HasTemplateArgumentsAsWritten = Record.readInt();
912 if (HasTemplateArgumentsAsWritten) {
913 unsigned NumTemplateArgLocs = Record.readInt();
914 TemplArgLocs.reserve(NumTemplateArgLocs);
915 for (unsigned i = 0; i != NumTemplateArgLocs; ++i)
916 TemplArgLocs.push_back(Record.readTemplateArgumentLoc());
918 LAngleLoc = ReadSourceLocation();
919 RAngleLoc = ReadSourceLocation();
922 SourceLocation POI = ReadSourceLocation();
924 ASTContext &C = Reader.getContext();
925 TemplateArgumentList *TemplArgList
926 = TemplateArgumentList::CreateCopy(C, TemplArgs);
927 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
928 for (unsigned i = 0, e = TemplArgLocs.size(); i != e; ++i)
929 TemplArgsInfo.addArgument(TemplArgLocs[i]);
930 FunctionTemplateSpecializationInfo *FTInfo
931 = FunctionTemplateSpecializationInfo::Create(C, FD, Template, TSK,
933 HasTemplateArgumentsAsWritten ? &TemplArgsInfo
936 FD->TemplateOrSpecialization = FTInfo;
938 if (FD->isCanonicalDecl()) { // if canonical add to template's set.
939 // The template that contains the specializations set. It's not safe to
940 // use getCanonicalDecl on Template since it may still be initializing.
941 auto *CanonTemplate = ReadDeclAs<FunctionTemplateDecl>();
942 // Get the InsertPos by FindNodeOrInsertPos() instead of calling
943 // InsertNode(FTInfo) directly to avoid the getASTContext() call in
944 // FunctionTemplateSpecializationInfo's Profile().
945 // We avoid getASTContext because a decl in the parent hierarchy may
947 llvm::FoldingSetNodeID ID;
948 FunctionTemplateSpecializationInfo::Profile(ID, TemplArgs, C);
949 void *InsertPos = nullptr;
950 FunctionTemplateDecl::Common *CommonPtr = CanonTemplate->getCommonPtr();
951 FunctionTemplateSpecializationInfo *ExistingInfo =
952 CommonPtr->Specializations.FindNodeOrInsertPos(ID, InsertPos);
954 CommonPtr->Specializations.InsertNode(FTInfo, InsertPos);
956 assert(Reader.getContext().getLangOpts().Modules &&
957 "already deserialized this template specialization");
958 mergeRedeclarable(FD, ExistingInfo->Function, Redecl);
963 case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
965 UnresolvedSet<8> TemplDecls;
966 unsigned NumTemplates = Record.readInt();
967 while (NumTemplates--)
968 TemplDecls.addDecl(ReadDeclAs<NamedDecl>());
971 TemplateArgumentListInfo TemplArgs;
972 unsigned NumArgs = Record.readInt();
974 TemplArgs.addArgument(Record.readTemplateArgumentLoc());
975 TemplArgs.setLAngleLoc(ReadSourceLocation());
976 TemplArgs.setRAngleLoc(ReadSourceLocation());
978 FD->setDependentTemplateSpecialization(Reader.getContext(),
979 TemplDecls, TemplArgs);
980 // These are not merged; we don't need to merge redeclarations of dependent
986 // Read in the parameters.
987 unsigned NumParams = Record.readInt();
988 SmallVector<ParmVarDecl *, 16> Params;
989 Params.reserve(NumParams);
990 for (unsigned I = 0; I != NumParams; ++I)
991 Params.push_back(ReadDeclAs<ParmVarDecl>());
992 FD->setParams(Reader.getContext(), Params);
995 void ASTDeclReader::VisitObjCMethodDecl(ObjCMethodDecl *MD) {
997 if (Record.readInt()) {
998 // Load the body on-demand. Most clients won't care, because method
999 // definitions rarely show up in headers.
1000 Reader.PendingBodies[MD] = GetCurrentCursorOffset();
1001 HasPendingBody = true;
1002 MD->setSelfDecl(ReadDeclAs<ImplicitParamDecl>());
1003 MD->setCmdDecl(ReadDeclAs<ImplicitParamDecl>());
1005 MD->setInstanceMethod(Record.readInt());
1006 MD->setVariadic(Record.readInt());
1007 MD->setPropertyAccessor(Record.readInt());
1008 MD->setDefined(Record.readInt());
1009 MD->setOverriding(Record.readInt());
1010 MD->setHasSkippedBody(Record.readInt());
1012 MD->setIsRedeclaration(Record.readInt());
1013 MD->setHasRedeclaration(Record.readInt());
1014 if (MD->hasRedeclaration())
1015 Reader.getContext().setObjCMethodRedeclaration(MD,
1016 ReadDeclAs<ObjCMethodDecl>());
1018 MD->setDeclImplementation((ObjCMethodDecl::ImplementationControl)Record.readInt());
1019 MD->setObjCDeclQualifier((Decl::ObjCDeclQualifier)Record.readInt());
1020 MD->setRelatedResultType(Record.readInt());
1021 MD->setReturnType(Record.readType());
1022 MD->setReturnTypeSourceInfo(GetTypeSourceInfo());
1023 MD->DeclEndLoc = ReadSourceLocation();
1024 unsigned NumParams = Record.readInt();
1025 SmallVector<ParmVarDecl *, 16> Params;
1026 Params.reserve(NumParams);
1027 for (unsigned I = 0; I != NumParams; ++I)
1028 Params.push_back(ReadDeclAs<ParmVarDecl>());
1030 MD->setSelLocsKind((SelectorLocationsKind)Record.readInt());
1031 unsigned NumStoredSelLocs = Record.readInt();
1032 SmallVector<SourceLocation, 16> SelLocs;
1033 SelLocs.reserve(NumStoredSelLocs);
1034 for (unsigned i = 0; i != NumStoredSelLocs; ++i)
1035 SelLocs.push_back(ReadSourceLocation());
1037 MD->setParamsAndSelLocs(Reader.getContext(), Params, SelLocs);
1040 void ASTDeclReader::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
1041 VisitTypedefNameDecl(D);
1043 D->Variance = Record.readInt();
1044 D->Index = Record.readInt();
1045 D->VarianceLoc = ReadSourceLocation();
1046 D->ColonLoc = ReadSourceLocation();
1049 void ASTDeclReader::VisitObjCContainerDecl(ObjCContainerDecl *CD) {
1051 CD->setAtStartLoc(ReadSourceLocation());
1052 CD->setAtEndRange(ReadSourceRange());
1055 ObjCTypeParamList *ASTDeclReader::ReadObjCTypeParamList() {
1056 unsigned numParams = Record.readInt();
1060 SmallVector<ObjCTypeParamDecl *, 4> typeParams;
1061 typeParams.reserve(numParams);
1062 for (unsigned i = 0; i != numParams; ++i) {
1063 auto *typeParam = ReadDeclAs<ObjCTypeParamDecl>();
1067 typeParams.push_back(typeParam);
1070 SourceLocation lAngleLoc = ReadSourceLocation();
1071 SourceLocation rAngleLoc = ReadSourceLocation();
1073 return ObjCTypeParamList::create(Reader.getContext(), lAngleLoc,
1074 typeParams, rAngleLoc);
1077 void ASTDeclReader::ReadObjCDefinitionData(
1078 struct ObjCInterfaceDecl::DefinitionData &Data) {
1079 // Read the superclass.
1080 Data.SuperClassTInfo = GetTypeSourceInfo();
1082 Data.EndLoc = ReadSourceLocation();
1083 Data.HasDesignatedInitializers = Record.readInt();
1085 // Read the directly referenced protocols and their SourceLocations.
1086 unsigned NumProtocols = Record.readInt();
1087 SmallVector<ObjCProtocolDecl *, 16> Protocols;
1088 Protocols.reserve(NumProtocols);
1089 for (unsigned I = 0; I != NumProtocols; ++I)
1090 Protocols.push_back(ReadDeclAs<ObjCProtocolDecl>());
1091 SmallVector<SourceLocation, 16> ProtoLocs;
1092 ProtoLocs.reserve(NumProtocols);
1093 for (unsigned I = 0; I != NumProtocols; ++I)
1094 ProtoLocs.push_back(ReadSourceLocation());
1095 Data.ReferencedProtocols.set(Protocols.data(), NumProtocols, ProtoLocs.data(),
1096 Reader.getContext());
1098 // Read the transitive closure of protocols referenced by this class.
1099 NumProtocols = Record.readInt();
1101 Protocols.reserve(NumProtocols);
1102 for (unsigned I = 0; I != NumProtocols; ++I)
1103 Protocols.push_back(ReadDeclAs<ObjCProtocolDecl>());
1104 Data.AllReferencedProtocols.set(Protocols.data(), NumProtocols,
1105 Reader.getContext());
1108 void ASTDeclReader::MergeDefinitionData(ObjCInterfaceDecl *D,
1109 struct ObjCInterfaceDecl::DefinitionData &&NewDD) {
1110 // FIXME: odr checking?
1113 void ASTDeclReader::VisitObjCInterfaceDecl(ObjCInterfaceDecl *ID) {
1114 RedeclarableResult Redecl = VisitRedeclarable(ID);
1115 VisitObjCContainerDecl(ID);
1116 DeferredTypeID = Record.getGlobalTypeID(Record.readInt());
1117 mergeRedeclarable(ID, Redecl);
1119 ID->TypeParamList = ReadObjCTypeParamList();
1120 if (Record.readInt()) {
1121 // Read the definition.
1122 ID->allocateDefinitionData();
1124 ReadObjCDefinitionData(ID->data());
1125 ObjCInterfaceDecl *Canon = ID->getCanonicalDecl();
1126 if (Canon->Data.getPointer()) {
1127 // If we already have a definition, keep the definition invariant and
1129 MergeDefinitionData(Canon, std::move(ID->data()));
1130 ID->Data = Canon->Data;
1132 // Set the definition data of the canonical declaration, so other
1133 // redeclarations will see it.
1134 ID->getCanonicalDecl()->Data = ID->Data;
1136 // We will rebuild this list lazily.
1137 ID->setIvarList(nullptr);
1140 // Note that we have deserialized a definition.
1141 Reader.PendingDefinitions.insert(ID);
1143 // Note that we've loaded this Objective-C class.
1144 Reader.ObjCClassesLoaded.push_back(ID);
1146 ID->Data = ID->getCanonicalDecl()->Data;
1150 void ASTDeclReader::VisitObjCIvarDecl(ObjCIvarDecl *IVD) {
1151 VisitFieldDecl(IVD);
1152 IVD->setAccessControl((ObjCIvarDecl::AccessControl)Record.readInt());
1153 // This field will be built lazily.
1154 IVD->setNextIvar(nullptr);
1155 bool synth = Record.readInt();
1156 IVD->setSynthesize(synth);
1159 void ASTDeclReader::ReadObjCDefinitionData(
1160 struct ObjCProtocolDecl::DefinitionData &Data) {
1161 unsigned NumProtoRefs = Record.readInt();
1162 SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
1163 ProtoRefs.reserve(NumProtoRefs);
1164 for (unsigned I = 0; I != NumProtoRefs; ++I)
1165 ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>());
1166 SmallVector<SourceLocation, 16> ProtoLocs;
1167 ProtoLocs.reserve(NumProtoRefs);
1168 for (unsigned I = 0; I != NumProtoRefs; ++I)
1169 ProtoLocs.push_back(ReadSourceLocation());
1170 Data.ReferencedProtocols.set(ProtoRefs.data(), NumProtoRefs,
1171 ProtoLocs.data(), Reader.getContext());
1174 void ASTDeclReader::MergeDefinitionData(ObjCProtocolDecl *D,
1175 struct ObjCProtocolDecl::DefinitionData &&NewDD) {
1176 // FIXME: odr checking?
1179 void ASTDeclReader::VisitObjCProtocolDecl(ObjCProtocolDecl *PD) {
1180 RedeclarableResult Redecl = VisitRedeclarable(PD);
1181 VisitObjCContainerDecl(PD);
1182 mergeRedeclarable(PD, Redecl);
1184 if (Record.readInt()) {
1185 // Read the definition.
1186 PD->allocateDefinitionData();
1188 ReadObjCDefinitionData(PD->data());
1190 ObjCProtocolDecl *Canon = PD->getCanonicalDecl();
1191 if (Canon->Data.getPointer()) {
1192 // If we already have a definition, keep the definition invariant and
1194 MergeDefinitionData(Canon, std::move(PD->data()));
1195 PD->Data = Canon->Data;
1197 // Set the definition data of the canonical declaration, so other
1198 // redeclarations will see it.
1199 PD->getCanonicalDecl()->Data = PD->Data;
1201 // Note that we have deserialized a definition.
1202 Reader.PendingDefinitions.insert(PD);
1204 PD->Data = PD->getCanonicalDecl()->Data;
1208 void ASTDeclReader::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *FD) {
1212 void ASTDeclReader::VisitObjCCategoryDecl(ObjCCategoryDecl *CD) {
1213 VisitObjCContainerDecl(CD);
1214 CD->setCategoryNameLoc(ReadSourceLocation());
1215 CD->setIvarLBraceLoc(ReadSourceLocation());
1216 CD->setIvarRBraceLoc(ReadSourceLocation());
1218 // Note that this category has been deserialized. We do this before
1219 // deserializing the interface declaration, so that it will consider this
1221 Reader.CategoriesDeserialized.insert(CD);
1223 CD->ClassInterface = ReadDeclAs<ObjCInterfaceDecl>();
1224 CD->TypeParamList = ReadObjCTypeParamList();
1225 unsigned NumProtoRefs = Record.readInt();
1226 SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
1227 ProtoRefs.reserve(NumProtoRefs);
1228 for (unsigned I = 0; I != NumProtoRefs; ++I)
1229 ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>());
1230 SmallVector<SourceLocation, 16> ProtoLocs;
1231 ProtoLocs.reserve(NumProtoRefs);
1232 for (unsigned I = 0; I != NumProtoRefs; ++I)
1233 ProtoLocs.push_back(ReadSourceLocation());
1234 CD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
1235 Reader.getContext());
1237 // Protocols in the class extension belong to the class.
1238 if (NumProtoRefs > 0 && CD->ClassInterface && CD->IsClassExtension())
1239 CD->ClassInterface->mergeClassExtensionProtocolList(
1240 (ObjCProtocolDecl *const *)ProtoRefs.data(), NumProtoRefs,
1241 Reader.getContext());
1244 void ASTDeclReader::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *CAD) {
1245 VisitNamedDecl(CAD);
1246 CAD->setClassInterface(ReadDeclAs<ObjCInterfaceDecl>());
1249 void ASTDeclReader::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
1251 D->setAtLoc(ReadSourceLocation());
1252 D->setLParenLoc(ReadSourceLocation());
1253 QualType T = Record.readType();
1254 TypeSourceInfo *TSI = GetTypeSourceInfo();
1256 D->setPropertyAttributes(
1257 (ObjCPropertyDecl::PropertyAttributeKind)Record.readInt());
1258 D->setPropertyAttributesAsWritten(
1259 (ObjCPropertyDecl::PropertyAttributeKind)Record.readInt());
1260 D->setPropertyImplementation(
1261 (ObjCPropertyDecl::PropertyControl)Record.readInt());
1262 DeclarationName GetterName = Record.readDeclarationName();
1263 SourceLocation GetterLoc = ReadSourceLocation();
1264 D->setGetterName(GetterName.getObjCSelector(), GetterLoc);
1265 DeclarationName SetterName = Record.readDeclarationName();
1266 SourceLocation SetterLoc = ReadSourceLocation();
1267 D->setSetterName(SetterName.getObjCSelector(), SetterLoc);
1268 D->setGetterMethodDecl(ReadDeclAs<ObjCMethodDecl>());
1269 D->setSetterMethodDecl(ReadDeclAs<ObjCMethodDecl>());
1270 D->setPropertyIvarDecl(ReadDeclAs<ObjCIvarDecl>());
1273 void ASTDeclReader::VisitObjCImplDecl(ObjCImplDecl *D) {
1274 VisitObjCContainerDecl(D);
1275 D->setClassInterface(ReadDeclAs<ObjCInterfaceDecl>());
1278 void ASTDeclReader::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1279 VisitObjCImplDecl(D);
1280 D->CategoryNameLoc = ReadSourceLocation();
1283 void ASTDeclReader::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1284 VisitObjCImplDecl(D);
1285 D->setSuperClass(ReadDeclAs<ObjCInterfaceDecl>());
1286 D->SuperLoc = ReadSourceLocation();
1287 D->setIvarLBraceLoc(ReadSourceLocation());
1288 D->setIvarRBraceLoc(ReadSourceLocation());
1289 D->setHasNonZeroConstructors(Record.readInt());
1290 D->setHasDestructors(Record.readInt());
1291 D->NumIvarInitializers = Record.readInt();
1292 if (D->NumIvarInitializers)
1293 D->IvarInitializers = ReadGlobalOffset();
1296 void ASTDeclReader::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
1298 D->setAtLoc(ReadSourceLocation());
1299 D->setPropertyDecl(ReadDeclAs<ObjCPropertyDecl>());
1300 D->PropertyIvarDecl = ReadDeclAs<ObjCIvarDecl>();
1301 D->IvarLoc = ReadSourceLocation();
1302 D->setGetterCXXConstructor(Record.readExpr());
1303 D->setSetterCXXAssignment(Record.readExpr());
1306 void ASTDeclReader::VisitFieldDecl(FieldDecl *FD) {
1307 VisitDeclaratorDecl(FD);
1308 FD->Mutable = Record.readInt();
1310 if (auto ISK = static_cast<FieldDecl::InitStorageKind>(Record.readInt())) {
1311 FD->InitStorage.setInt(ISK);
1312 FD->InitStorage.setPointer(ISK == FieldDecl::ISK_CapturedVLAType
1313 ? Record.readType().getAsOpaquePtr()
1314 : Record.readExpr());
1317 if (auto *BW = Record.readExpr())
1318 FD->setBitWidth(BW);
1320 if (!FD->getDeclName()) {
1321 if (auto *Tmpl = ReadDeclAs<FieldDecl>())
1322 Reader.getContext().setInstantiatedFromUnnamedFieldDecl(FD, Tmpl);
1327 void ASTDeclReader::VisitMSPropertyDecl(MSPropertyDecl *PD) {
1328 VisitDeclaratorDecl(PD);
1329 PD->GetterId = Record.getIdentifierInfo();
1330 PD->SetterId = Record.getIdentifierInfo();
1333 void ASTDeclReader::VisitIndirectFieldDecl(IndirectFieldDecl *FD) {
1336 FD->ChainingSize = Record.readInt();
1337 assert(FD->ChainingSize >= 2 && "Anonymous chaining must be >= 2");
1338 FD->Chaining = new (Reader.getContext())NamedDecl*[FD->ChainingSize];
1340 for (unsigned I = 0; I != FD->ChainingSize; ++I)
1341 FD->Chaining[I] = ReadDeclAs<NamedDecl>();
1346 ASTDeclReader::RedeclarableResult ASTDeclReader::VisitVarDeclImpl(VarDecl *VD) {
1347 RedeclarableResult Redecl = VisitRedeclarable(VD);
1348 VisitDeclaratorDecl(VD);
1350 VD->VarDeclBits.SClass = (StorageClass)Record.readInt();
1351 VD->VarDeclBits.TSCSpec = Record.readInt();
1352 VD->VarDeclBits.InitStyle = Record.readInt();
1353 VD->VarDeclBits.ARCPseudoStrong = Record.readInt();
1354 if (!isa<ParmVarDecl>(VD)) {
1355 VD->NonParmVarDeclBits.IsThisDeclarationADemotedDefinition =
1357 VD->NonParmVarDeclBits.ExceptionVar = Record.readInt();
1358 VD->NonParmVarDeclBits.NRVOVariable = Record.readInt();
1359 VD->NonParmVarDeclBits.CXXForRangeDecl = Record.readInt();
1360 VD->NonParmVarDeclBits.ObjCForDecl = Record.readInt();
1361 VD->NonParmVarDeclBits.IsInline = Record.readInt();
1362 VD->NonParmVarDeclBits.IsInlineSpecified = Record.readInt();
1363 VD->NonParmVarDeclBits.IsConstexpr = Record.readInt();
1364 VD->NonParmVarDeclBits.IsInitCapture = Record.readInt();
1365 VD->NonParmVarDeclBits.PreviousDeclInSameBlockScope = Record.readInt();
1366 VD->NonParmVarDeclBits.ImplicitParamKind = Record.readInt();
1367 VD->NonParmVarDeclBits.EscapingByref = Record.readInt();
1369 auto VarLinkage = Linkage(Record.readInt());
1370 VD->setCachedLinkage(VarLinkage);
1372 // Reconstruct the one piece of the IdentifierNamespace that we need.
1373 if (VD->getStorageClass() == SC_Extern && VarLinkage != NoLinkage &&
1374 VD->getLexicalDeclContext()->isFunctionOrMethod())
1375 VD->setLocalExternDecl();
1377 if (uint64_t Val = Record.readInt()) {
1378 VD->setInit(Record.readExpr());
1379 if (Val > 1) { // IsInitKnownICE = 1, IsInitNotICE = 2, IsInitICE = 3
1380 EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
1381 Eval->CheckedICE = true;
1382 Eval->IsICE = Val == 3;
1386 if (VD->hasAttr<BlocksAttr>() && VD->getType()->getAsCXXRecordDecl()) {
1387 Expr *CopyExpr = Record.readExpr();
1389 Reader.getContext().setBlockVarCopyInit(VD, CopyExpr, Record.readInt());
1392 if (VD->getStorageDuration() == SD_Static && Record.readInt())
1393 Reader.DefinitionSource[VD] = Loc.F->Kind == ModuleKind::MK_MainFile;
1396 VarNotTemplate = 0, VarTemplate, StaticDataMemberSpecialization
1398 switch ((VarKind)Record.readInt()) {
1399 case VarNotTemplate:
1400 // Only true variables (not parameters or implicit parameters) can be
1401 // merged; the other kinds are not really redeclarable at all.
1402 if (!isa<ParmVarDecl>(VD) && !isa<ImplicitParamDecl>(VD) &&
1403 !isa<VarTemplateSpecializationDecl>(VD))
1404 mergeRedeclarable(VD, Redecl);
1407 // Merged when we merge the template.
1408 VD->setDescribedVarTemplate(ReadDeclAs<VarTemplateDecl>());
1410 case StaticDataMemberSpecialization: { // HasMemberSpecializationInfo.
1411 auto *Tmpl = ReadDeclAs<VarDecl>();
1412 auto TSK = (TemplateSpecializationKind)Record.readInt();
1413 SourceLocation POI = ReadSourceLocation();
1414 Reader.getContext().setInstantiatedFromStaticDataMember(VD, Tmpl, TSK,POI);
1415 mergeRedeclarable(VD, Redecl);
1423 void ASTDeclReader::VisitImplicitParamDecl(ImplicitParamDecl *PD) {
1427 void ASTDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
1429 unsigned isObjCMethodParam = Record.readInt();
1430 unsigned scopeDepth = Record.readInt();
1431 unsigned scopeIndex = Record.readInt();
1432 unsigned declQualifier = Record.readInt();
1433 if (isObjCMethodParam) {
1434 assert(scopeDepth == 0);
1435 PD->setObjCMethodScopeInfo(scopeIndex);
1436 PD->ParmVarDeclBits.ScopeDepthOrObjCQuals = declQualifier;
1438 PD->setScopeInfo(scopeDepth, scopeIndex);
1440 PD->ParmVarDeclBits.IsKNRPromoted = Record.readInt();
1441 PD->ParmVarDeclBits.HasInheritedDefaultArg = Record.readInt();
1442 if (Record.readInt()) // hasUninstantiatedDefaultArg.
1443 PD->setUninstantiatedDefaultArg(Record.readExpr());
1445 // FIXME: If this is a redeclaration of a function from another module, handle
1446 // inheritance of default arguments.
1449 void ASTDeclReader::VisitDecompositionDecl(DecompositionDecl *DD) {
1451 auto **BDs = DD->getTrailingObjects<BindingDecl *>();
1452 for (unsigned I = 0; I != DD->NumBindings; ++I)
1453 BDs[I] = ReadDeclAs<BindingDecl>();
1456 void ASTDeclReader::VisitBindingDecl(BindingDecl *BD) {
1458 BD->Binding = Record.readExpr();
1461 void ASTDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {
1463 AD->setAsmString(cast<StringLiteral>(Record.readExpr()));
1464 AD->setRParenLoc(ReadSourceLocation());
1467 void ASTDeclReader::VisitBlockDecl(BlockDecl *BD) {
1469 BD->setBody(cast_or_null<CompoundStmt>(Record.readStmt()));
1470 BD->setSignatureAsWritten(GetTypeSourceInfo());
1471 unsigned NumParams = Record.readInt();
1472 SmallVector<ParmVarDecl *, 16> Params;
1473 Params.reserve(NumParams);
1474 for (unsigned I = 0; I != NumParams; ++I)
1475 Params.push_back(ReadDeclAs<ParmVarDecl>());
1476 BD->setParams(Params);
1478 BD->setIsVariadic(Record.readInt());
1479 BD->setBlockMissingReturnType(Record.readInt());
1480 BD->setIsConversionFromLambda(Record.readInt());
1481 BD->setDoesNotEscape(Record.readInt());
1483 bool capturesCXXThis = Record.readInt();
1484 unsigned numCaptures = Record.readInt();
1485 SmallVector<BlockDecl::Capture, 16> captures;
1486 captures.reserve(numCaptures);
1487 for (unsigned i = 0; i != numCaptures; ++i) {
1488 auto *decl = ReadDeclAs<VarDecl>();
1489 unsigned flags = Record.readInt();
1490 bool byRef = (flags & 1);
1491 bool nested = (flags & 2);
1492 Expr *copyExpr = ((flags & 4) ? Record.readExpr() : nullptr);
1494 captures.push_back(BlockDecl::Capture(decl, byRef, nested, copyExpr));
1496 BD->setCaptures(Reader.getContext(), captures, capturesCXXThis);
1499 void ASTDeclReader::VisitCapturedDecl(CapturedDecl *CD) {
1501 unsigned ContextParamPos = Record.readInt();
1502 CD->setNothrow(Record.readInt() != 0);
1503 // Body is set by VisitCapturedStmt.
1504 for (unsigned I = 0; I < CD->NumParams; ++I) {
1505 if (I != ContextParamPos)
1506 CD->setParam(I, ReadDeclAs<ImplicitParamDecl>());
1508 CD->setContextParam(I, ReadDeclAs<ImplicitParamDecl>());
1512 void ASTDeclReader::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1514 D->setLanguage((LinkageSpecDecl::LanguageIDs)Record.readInt());
1515 D->setExternLoc(ReadSourceLocation());
1516 D->setRBraceLoc(ReadSourceLocation());
1519 void ASTDeclReader::VisitExportDecl(ExportDecl *D) {
1521 D->RBraceLoc = ReadSourceLocation();
1524 void ASTDeclReader::VisitLabelDecl(LabelDecl *D) {
1526 D->setLocStart(ReadSourceLocation());
1529 void ASTDeclReader::VisitNamespaceDecl(NamespaceDecl *D) {
1530 RedeclarableResult Redecl = VisitRedeclarable(D);
1532 D->setInline(Record.readInt());
1533 D->LocStart = ReadSourceLocation();
1534 D->RBraceLoc = ReadSourceLocation();
1536 // Defer loading the anonymous namespace until we've finished merging
1537 // this namespace; loading it might load a later declaration of the
1538 // same namespace, and we have an invariant that older declarations
1539 // get merged before newer ones try to merge.
1540 GlobalDeclID AnonNamespace = 0;
1541 if (Redecl.getFirstID() == ThisDeclID) {
1542 AnonNamespace = ReadDeclID();
1544 // Link this namespace back to the first declaration, which has already
1545 // been deserialized.
1546 D->AnonOrFirstNamespaceAndInline.setPointer(D->getFirstDecl());
1549 mergeRedeclarable(D, Redecl);
1551 if (AnonNamespace) {
1552 // Each module has its own anonymous namespace, which is disjoint from
1553 // any other module's anonymous namespaces, so don't attach the anonymous
1554 // namespace at all.
1555 auto *Anon = cast<NamespaceDecl>(Reader.GetDecl(AnonNamespace));
1556 if (!Record.isModule())
1557 D->setAnonymousNamespace(Anon);
1561 void ASTDeclReader::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1562 RedeclarableResult Redecl = VisitRedeclarable(D);
1564 D->NamespaceLoc = ReadSourceLocation();
1565 D->IdentLoc = ReadSourceLocation();
1566 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1567 D->Namespace = ReadDeclAs<NamedDecl>();
1568 mergeRedeclarable(D, Redecl);
1571 void ASTDeclReader::VisitUsingDecl(UsingDecl *D) {
1573 D->setUsingLoc(ReadSourceLocation());
1574 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1575 ReadDeclarationNameLoc(D->DNLoc, D->getDeclName());
1576 D->FirstUsingShadow.setPointer(ReadDeclAs<UsingShadowDecl>());
1577 D->setTypename(Record.readInt());
1578 if (auto *Pattern = ReadDeclAs<NamedDecl>())
1579 Reader.getContext().setInstantiatedFromUsingDecl(D, Pattern);
1583 void ASTDeclReader::VisitUsingPackDecl(UsingPackDecl *D) {
1585 D->InstantiatedFrom = ReadDeclAs<NamedDecl>();
1586 auto **Expansions = D->getTrailingObjects<NamedDecl *>();
1587 for (unsigned I = 0; I != D->NumExpansions; ++I)
1588 Expansions[I] = ReadDeclAs<NamedDecl>();
1592 void ASTDeclReader::VisitUsingShadowDecl(UsingShadowDecl *D) {
1593 RedeclarableResult Redecl = VisitRedeclarable(D);
1595 D->Underlying = ReadDeclAs<NamedDecl>();
1596 D->IdentifierNamespace = Record.readInt();
1597 D->UsingOrNextShadow = ReadDeclAs<NamedDecl>();
1598 auto *Pattern = ReadDeclAs<UsingShadowDecl>();
1600 Reader.getContext().setInstantiatedFromUsingShadowDecl(D, Pattern);
1601 mergeRedeclarable(D, Redecl);
1604 void ASTDeclReader::VisitConstructorUsingShadowDecl(
1605 ConstructorUsingShadowDecl *D) {
1606 VisitUsingShadowDecl(D);
1607 D->NominatedBaseClassShadowDecl = ReadDeclAs<ConstructorUsingShadowDecl>();
1608 D->ConstructedBaseClassShadowDecl = ReadDeclAs<ConstructorUsingShadowDecl>();
1609 D->IsVirtual = Record.readInt();
1612 void ASTDeclReader::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1614 D->UsingLoc = ReadSourceLocation();
1615 D->NamespaceLoc = ReadSourceLocation();
1616 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1617 D->NominatedNamespace = ReadDeclAs<NamedDecl>();
1618 D->CommonAncestor = ReadDeclAs<DeclContext>();
1621 void ASTDeclReader::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1623 D->setUsingLoc(ReadSourceLocation());
1624 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1625 ReadDeclarationNameLoc(D->DNLoc, D->getDeclName());
1626 D->EllipsisLoc = ReadSourceLocation();
1630 void ASTDeclReader::VisitUnresolvedUsingTypenameDecl(
1631 UnresolvedUsingTypenameDecl *D) {
1633 D->TypenameLocation = ReadSourceLocation();
1634 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1635 D->EllipsisLoc = ReadSourceLocation();
1639 void ASTDeclReader::ReadCXXDefinitionData(
1640 struct CXXRecordDecl::DefinitionData &Data, const CXXRecordDecl *D) {
1641 // Note: the caller has deserialized the IsLambda bit already.
1642 Data.UserDeclaredConstructor = Record.readInt();
1643 Data.UserDeclaredSpecialMembers = Record.readInt();
1644 Data.Aggregate = Record.readInt();
1645 Data.PlainOldData = Record.readInt();
1646 Data.Empty = Record.readInt();
1647 Data.Polymorphic = Record.readInt();
1648 Data.Abstract = Record.readInt();
1649 Data.IsStandardLayout = Record.readInt();
1650 Data.IsCXX11StandardLayout = Record.readInt();
1651 Data.HasBasesWithFields = Record.readInt();
1652 Data.HasBasesWithNonStaticDataMembers = Record.readInt();
1653 Data.HasPrivateFields = Record.readInt();
1654 Data.HasProtectedFields = Record.readInt();
1655 Data.HasPublicFields = Record.readInt();
1656 Data.HasMutableFields = Record.readInt();
1657 Data.HasVariantMembers = Record.readInt();
1658 Data.HasOnlyCMembers = Record.readInt();
1659 Data.HasInClassInitializer = Record.readInt();
1660 Data.HasUninitializedReferenceMember = Record.readInt();
1661 Data.HasUninitializedFields = Record.readInt();
1662 Data.HasInheritedConstructor = Record.readInt();
1663 Data.HasInheritedAssignment = Record.readInt();
1664 Data.NeedOverloadResolutionForCopyConstructor = Record.readInt();
1665 Data.NeedOverloadResolutionForMoveConstructor = Record.readInt();
1666 Data.NeedOverloadResolutionForMoveAssignment = Record.readInt();
1667 Data.NeedOverloadResolutionForDestructor = Record.readInt();
1668 Data.DefaultedCopyConstructorIsDeleted = Record.readInt();
1669 Data.DefaultedMoveConstructorIsDeleted = Record.readInt();
1670 Data.DefaultedMoveAssignmentIsDeleted = Record.readInt();
1671 Data.DefaultedDestructorIsDeleted = Record.readInt();
1672 Data.HasTrivialSpecialMembers = Record.readInt();
1673 Data.HasTrivialSpecialMembersForCall = Record.readInt();
1674 Data.DeclaredNonTrivialSpecialMembers = Record.readInt();
1675 Data.DeclaredNonTrivialSpecialMembersForCall = Record.readInt();
1676 Data.HasIrrelevantDestructor = Record.readInt();
1677 Data.HasConstexprNonCopyMoveConstructor = Record.readInt();
1678 Data.HasDefaultedDefaultConstructor = Record.readInt();
1679 Data.DefaultedDefaultConstructorIsConstexpr = Record.readInt();
1680 Data.HasConstexprDefaultConstructor = Record.readInt();
1681 Data.HasNonLiteralTypeFieldsOrBases = Record.readInt();
1682 Data.ComputedVisibleConversions = Record.readInt();
1683 Data.UserProvidedDefaultConstructor = Record.readInt();
1684 Data.DeclaredSpecialMembers = Record.readInt();
1685 Data.ImplicitCopyConstructorCanHaveConstParamForVBase = Record.readInt();
1686 Data.ImplicitCopyConstructorCanHaveConstParamForNonVBase = Record.readInt();
1687 Data.ImplicitCopyAssignmentHasConstParam = Record.readInt();
1688 Data.HasDeclaredCopyConstructorWithConstParam = Record.readInt();
1689 Data.HasDeclaredCopyAssignmentWithConstParam = Record.readInt();
1690 Data.ODRHash = Record.readInt();
1691 Data.HasODRHash = true;
1693 if (Record.readInt())
1694 Reader.DefinitionSource[D] = Loc.F->Kind == ModuleKind::MK_MainFile;
1696 Data.NumBases = Record.readInt();
1698 Data.Bases = ReadGlobalOffset();
1699 Data.NumVBases = Record.readInt();
1701 Data.VBases = ReadGlobalOffset();
1703 Record.readUnresolvedSet(Data.Conversions);
1704 Record.readUnresolvedSet(Data.VisibleConversions);
1705 assert(Data.Definition && "Data.Definition should be already set!");
1706 Data.FirstFriend = ReadDeclID();
1708 if (Data.IsLambda) {
1709 using Capture = LambdaCapture;
1711 auto &Lambda = static_cast<CXXRecordDecl::LambdaDefinitionData &>(Data);
1712 Lambda.Dependent = Record.readInt();
1713 Lambda.IsGenericLambda = Record.readInt();
1714 Lambda.CaptureDefault = Record.readInt();
1715 Lambda.NumCaptures = Record.readInt();
1716 Lambda.NumExplicitCaptures = Record.readInt();
1717 Lambda.ManglingNumber = Record.readInt();
1718 Lambda.ContextDecl = ReadDeclID();
1719 Lambda.Captures = (Capture *)Reader.getContext().Allocate(
1720 sizeof(Capture) * Lambda.NumCaptures);
1721 Capture *ToCapture = Lambda.Captures;
1722 Lambda.MethodTyInfo = GetTypeSourceInfo();
1723 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
1724 SourceLocation Loc = ReadSourceLocation();
1725 bool IsImplicit = Record.readInt();
1726 auto Kind = static_cast<LambdaCaptureKind>(Record.readInt());
1731 *ToCapture++ = Capture(Loc, IsImplicit, Kind, nullptr,SourceLocation());
1735 auto *Var = ReadDeclAs<VarDecl>();
1736 SourceLocation EllipsisLoc = ReadSourceLocation();
1737 *ToCapture++ = Capture(Loc, IsImplicit, Kind, Var, EllipsisLoc);
1744 void ASTDeclReader::MergeDefinitionData(
1745 CXXRecordDecl *D, struct CXXRecordDecl::DefinitionData &&MergeDD) {
1746 assert(D->DefinitionData &&
1747 "merging class definition into non-definition");
1748 auto &DD = *D->DefinitionData;
1750 if (DD.Definition != MergeDD.Definition) {
1751 // Track that we merged the definitions.
1752 Reader.MergedDeclContexts.insert(std::make_pair(MergeDD.Definition,
1754 Reader.PendingDefinitions.erase(MergeDD.Definition);
1755 MergeDD.Definition->setCompleteDefinition(false);
1756 Reader.mergeDefinitionVisibility(DD.Definition, MergeDD.Definition);
1757 assert(Reader.Lookups.find(MergeDD.Definition) == Reader.Lookups.end() &&
1758 "already loaded pending lookups for merged definition");
1761 auto PFDI = Reader.PendingFakeDefinitionData.find(&DD);
1762 if (PFDI != Reader.PendingFakeDefinitionData.end() &&
1763 PFDI->second == ASTReader::PendingFakeDefinitionKind::Fake) {
1764 // We faked up this definition data because we found a class for which we'd
1765 // not yet loaded the definition. Replace it with the real thing now.
1766 assert(!DD.IsLambda && !MergeDD.IsLambda && "faked up lambda definition?");
1767 PFDI->second = ASTReader::PendingFakeDefinitionKind::FakeLoaded;
1769 // Don't change which declaration is the definition; that is required
1770 // to be invariant once we select it.
1771 auto *Def = DD.Definition;
1772 DD = std::move(MergeDD);
1773 DD.Definition = Def;
1777 // FIXME: Move this out into a .def file?
1778 bool DetectedOdrViolation = false;
1779 #define OR_FIELD(Field) DD.Field |= MergeDD.Field;
1780 #define MATCH_FIELD(Field) \
1781 DetectedOdrViolation |= DD.Field != MergeDD.Field; \
1783 MATCH_FIELD(UserDeclaredConstructor)
1784 MATCH_FIELD(UserDeclaredSpecialMembers)
1785 MATCH_FIELD(Aggregate)
1786 MATCH_FIELD(PlainOldData)
1788 MATCH_FIELD(Polymorphic)
1789 MATCH_FIELD(Abstract)
1790 MATCH_FIELD(IsStandardLayout)
1791 MATCH_FIELD(IsCXX11StandardLayout)
1792 MATCH_FIELD(HasBasesWithFields)
1793 MATCH_FIELD(HasBasesWithNonStaticDataMembers)
1794 MATCH_FIELD(HasPrivateFields)
1795 MATCH_FIELD(HasProtectedFields)
1796 MATCH_FIELD(HasPublicFields)
1797 MATCH_FIELD(HasMutableFields)
1798 MATCH_FIELD(HasVariantMembers)
1799 MATCH_FIELD(HasOnlyCMembers)
1800 MATCH_FIELD(HasInClassInitializer)
1801 MATCH_FIELD(HasUninitializedReferenceMember)
1802 MATCH_FIELD(HasUninitializedFields)
1803 MATCH_FIELD(HasInheritedConstructor)
1804 MATCH_FIELD(HasInheritedAssignment)
1805 MATCH_FIELD(NeedOverloadResolutionForCopyConstructor)
1806 MATCH_FIELD(NeedOverloadResolutionForMoveConstructor)
1807 MATCH_FIELD(NeedOverloadResolutionForMoveAssignment)
1808 MATCH_FIELD(NeedOverloadResolutionForDestructor)
1809 MATCH_FIELD(DefaultedCopyConstructorIsDeleted)
1810 MATCH_FIELD(DefaultedMoveConstructorIsDeleted)
1811 MATCH_FIELD(DefaultedMoveAssignmentIsDeleted)
1812 MATCH_FIELD(DefaultedDestructorIsDeleted)
1813 OR_FIELD(HasTrivialSpecialMembers)
1814 OR_FIELD(HasTrivialSpecialMembersForCall)
1815 OR_FIELD(DeclaredNonTrivialSpecialMembers)
1816 OR_FIELD(DeclaredNonTrivialSpecialMembersForCall)
1817 MATCH_FIELD(HasIrrelevantDestructor)
1818 OR_FIELD(HasConstexprNonCopyMoveConstructor)
1819 OR_FIELD(HasDefaultedDefaultConstructor)
1820 MATCH_FIELD(DefaultedDefaultConstructorIsConstexpr)
1821 OR_FIELD(HasConstexprDefaultConstructor)
1822 MATCH_FIELD(HasNonLiteralTypeFieldsOrBases)
1823 // ComputedVisibleConversions is handled below.
1824 MATCH_FIELD(UserProvidedDefaultConstructor)
1825 OR_FIELD(DeclaredSpecialMembers)
1826 MATCH_FIELD(ImplicitCopyConstructorCanHaveConstParamForVBase)
1827 MATCH_FIELD(ImplicitCopyConstructorCanHaveConstParamForNonVBase)
1828 MATCH_FIELD(ImplicitCopyAssignmentHasConstParam)
1829 OR_FIELD(HasDeclaredCopyConstructorWithConstParam)
1830 OR_FIELD(HasDeclaredCopyAssignmentWithConstParam)
1831 MATCH_FIELD(IsLambda)
1835 if (DD.NumBases != MergeDD.NumBases || DD.NumVBases != MergeDD.NumVBases)
1836 DetectedOdrViolation = true;
1837 // FIXME: Issue a diagnostic if the base classes don't match when we come
1838 // to lazily load them.
1840 // FIXME: Issue a diagnostic if the list of conversion functions doesn't
1841 // match when we come to lazily load them.
1842 if (MergeDD.ComputedVisibleConversions && !DD.ComputedVisibleConversions) {
1843 DD.VisibleConversions = std::move(MergeDD.VisibleConversions);
1844 DD.ComputedVisibleConversions = true;
1847 // FIXME: Issue a diagnostic if FirstFriend doesn't match when we come to
1851 // FIXME: ODR-checking for merging lambdas (this happens, for instance,
1852 // when they occur within the body of a function template specialization).
1855 if (D->getODRHash() != MergeDD.ODRHash) {
1856 DetectedOdrViolation = true;
1859 if (DetectedOdrViolation)
1860 Reader.PendingOdrMergeFailures[DD.Definition].push_back(
1861 {MergeDD.Definition, &MergeDD});
1864 void ASTDeclReader::ReadCXXRecordDefinition(CXXRecordDecl *D, bool Update) {
1865 struct CXXRecordDecl::DefinitionData *DD;
1866 ASTContext &C = Reader.getContext();
1868 // Determine whether this is a lambda closure type, so that we can
1869 // allocate the appropriate DefinitionData structure.
1870 bool IsLambda = Record.readInt();
1872 DD = new (C) CXXRecordDecl::LambdaDefinitionData(D, nullptr, false, false,
1875 DD = new (C) struct CXXRecordDecl::DefinitionData(D);
1877 CXXRecordDecl *Canon = D->getCanonicalDecl();
1878 // Set decl definition data before reading it, so that during deserialization
1879 // when we read CXXRecordDecl, it already has definition data and we don't
1881 if (!Canon->DefinitionData)
1882 Canon->DefinitionData = DD;
1883 D->DefinitionData = Canon->DefinitionData;
1884 ReadCXXDefinitionData(*DD, D);
1886 // We might already have a different definition for this record. This can
1887 // happen either because we're reading an update record, or because we've
1888 // already done some merging. Either way, just merge into it.
1889 if (Canon->DefinitionData != DD) {
1890 MergeDefinitionData(Canon, std::move(*DD));
1894 // Mark this declaration as being a definition.
1895 D->setCompleteDefinition(true);
1897 // If this is not the first declaration or is an update record, we can have
1898 // other redeclarations already. Make a note that we need to propagate the
1899 // DefinitionData pointer onto them.
1900 if (Update || Canon != D)
1901 Reader.PendingDefinitions.insert(D);
1904 ASTDeclReader::RedeclarableResult
1905 ASTDeclReader::VisitCXXRecordDeclImpl(CXXRecordDecl *D) {
1906 RedeclarableResult Redecl = VisitRecordDeclImpl(D);
1908 ASTContext &C = Reader.getContext();
1911 CXXRecNotTemplate = 0, CXXRecTemplate, CXXRecMemberSpecialization
1913 switch ((CXXRecKind)Record.readInt()) {
1914 case CXXRecNotTemplate:
1915 // Merged when we merge the folding set entry in the primary template.
1916 if (!isa<ClassTemplateSpecializationDecl>(D))
1917 mergeRedeclarable(D, Redecl);
1919 case CXXRecTemplate: {
1920 // Merged when we merge the template.
1921 auto *Template = ReadDeclAs<ClassTemplateDecl>();
1922 D->TemplateOrInstantiation = Template;
1923 if (!Template->getTemplatedDecl()) {
1924 // We've not actually loaded the ClassTemplateDecl yet, because we're
1925 // currently being loaded as its pattern. Rely on it to set up our
1926 // TypeForDecl (see VisitClassTemplateDecl).
1928 // Beware: we do not yet know our canonical declaration, and may still
1929 // get merged once the surrounding class template has got off the ground.
1934 case CXXRecMemberSpecialization: {
1935 auto *RD = ReadDeclAs<CXXRecordDecl>();
1936 auto TSK = (TemplateSpecializationKind)Record.readInt();
1937 SourceLocation POI = ReadSourceLocation();
1938 MemberSpecializationInfo *MSI = new (C) MemberSpecializationInfo(RD, TSK);
1939 MSI->setPointOfInstantiation(POI);
1940 D->TemplateOrInstantiation = MSI;
1941 mergeRedeclarable(D, Redecl);
1946 bool WasDefinition = Record.readInt();
1948 ReadCXXRecordDefinition(D, /*Update*/false);
1950 // Propagate DefinitionData pointer from the canonical declaration.
1951 D->DefinitionData = D->getCanonicalDecl()->DefinitionData;
1953 // Lazily load the key function to avoid deserializing every method so we can
1955 if (WasDefinition) {
1956 DeclID KeyFn = ReadDeclID();
1957 if (KeyFn && D->isCompleteDefinition())
1958 // FIXME: This is wrong for the ARM ABI, where some other module may have
1959 // made this function no longer be a key function. We need an update
1960 // record or similar for that case.
1961 C.KeyFunctions[D] = KeyFn;
1967 void ASTDeclReader::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
1968 VisitFunctionDecl(D);
1969 D->setIsCopyDeductionCandidate(Record.readInt());
1972 void ASTDeclReader::VisitCXXMethodDecl(CXXMethodDecl *D) {
1973 VisitFunctionDecl(D);
1975 unsigned NumOverridenMethods = Record.readInt();
1976 if (D->isCanonicalDecl()) {
1977 while (NumOverridenMethods--) {
1978 // Avoid invariant checking of CXXMethodDecl::addOverriddenMethod,
1979 // MD may be initializing.
1980 if (auto *MD = ReadDeclAs<CXXMethodDecl>())
1981 Reader.getContext().addOverriddenMethod(D, MD->getCanonicalDecl());
1984 // We don't care about which declarations this used to override; we get
1985 // the relevant information from the canonical declaration.
1986 Record.skipInts(NumOverridenMethods);
1990 void ASTDeclReader::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1991 // We need the inherited constructor information to merge the declaration,
1992 // so we have to read it before we call VisitCXXMethodDecl.
1993 if (D->isInheritingConstructor()) {
1994 auto *Shadow = ReadDeclAs<ConstructorUsingShadowDecl>();
1995 auto *Ctor = ReadDeclAs<CXXConstructorDecl>();
1996 *D->getTrailingObjects<InheritedConstructor>() =
1997 InheritedConstructor(Shadow, Ctor);
2000 VisitCXXMethodDecl(D);
2003 void ASTDeclReader::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
2004 VisitCXXMethodDecl(D);
2006 if (auto *OperatorDelete = ReadDeclAs<FunctionDecl>()) {
2007 CXXDestructorDecl *Canon = D->getCanonicalDecl();
2008 auto *ThisArg = Record.readExpr();
2009 // FIXME: Check consistency if we have an old and new operator delete.
2010 if (!Canon->OperatorDelete) {
2011 Canon->OperatorDelete = OperatorDelete;
2012 Canon->OperatorDeleteThisArg = ThisArg;
2017 void ASTDeclReader::VisitCXXConversionDecl(CXXConversionDecl *D) {
2018 VisitCXXMethodDecl(D);
2021 void ASTDeclReader::VisitImportDecl(ImportDecl *D) {
2023 D->ImportedAndComplete.setPointer(readModule());
2024 D->ImportedAndComplete.setInt(Record.readInt());
2025 auto *StoredLocs = D->getTrailingObjects<SourceLocation>();
2026 for (unsigned I = 0, N = Record.back(); I != N; ++I)
2027 StoredLocs[I] = ReadSourceLocation();
2028 Record.skipInts(1); // The number of stored source locations.
2031 void ASTDeclReader::VisitAccessSpecDecl(AccessSpecDecl *D) {
2033 D->setColonLoc(ReadSourceLocation());
2036 void ASTDeclReader::VisitFriendDecl(FriendDecl *D) {
2038 if (Record.readInt()) // hasFriendDecl
2039 D->Friend = ReadDeclAs<NamedDecl>();
2041 D->Friend = GetTypeSourceInfo();
2042 for (unsigned i = 0; i != D->NumTPLists; ++i)
2043 D->getTrailingObjects<TemplateParameterList *>()[i] =
2044 Record.readTemplateParameterList();
2045 D->NextFriend = ReadDeclID();
2046 D->UnsupportedFriend = (Record.readInt() != 0);
2047 D->FriendLoc = ReadSourceLocation();
2050 void ASTDeclReader::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
2052 unsigned NumParams = Record.readInt();
2053 D->NumParams = NumParams;
2054 D->Params = new TemplateParameterList*[NumParams];
2055 for (unsigned i = 0; i != NumParams; ++i)
2056 D->Params[i] = Record.readTemplateParameterList();
2057 if (Record.readInt()) // HasFriendDecl
2058 D->Friend = ReadDeclAs<NamedDecl>();
2060 D->Friend = GetTypeSourceInfo();
2061 D->FriendLoc = ReadSourceLocation();
2064 DeclID ASTDeclReader::VisitTemplateDecl(TemplateDecl *D) {
2067 DeclID PatternID = ReadDeclID();
2068 auto *TemplatedDecl = cast_or_null<NamedDecl>(Reader.GetDecl(PatternID));
2069 TemplateParameterList *TemplateParams = Record.readTemplateParameterList();
2070 // FIXME handle associated constraints
2071 D->init(TemplatedDecl, TemplateParams);
2076 ASTDeclReader::RedeclarableResult
2077 ASTDeclReader::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
2078 RedeclarableResult Redecl = VisitRedeclarable(D);
2080 // Make sure we've allocated the Common pointer first. We do this before
2081 // VisitTemplateDecl so that getCommonPtr() can be used during initialization.
2082 RedeclarableTemplateDecl *CanonD = D->getCanonicalDecl();
2083 if (!CanonD->Common) {
2084 CanonD->Common = CanonD->newCommon(Reader.getContext());
2085 Reader.PendingDefinitions.insert(CanonD);
2087 D->Common = CanonD->Common;
2089 // If this is the first declaration of the template, fill in the information
2090 // for the 'common' pointer.
2091 if (ThisDeclID == Redecl.getFirstID()) {
2092 if (auto *RTD = ReadDeclAs<RedeclarableTemplateDecl>()) {
2093 assert(RTD->getKind() == D->getKind() &&
2094 "InstantiatedFromMemberTemplate kind mismatch");
2095 D->setInstantiatedFromMemberTemplate(RTD);
2096 if (Record.readInt())
2097 D->setMemberSpecialization();
2101 DeclID PatternID = VisitTemplateDecl(D);
2102 D->IdentifierNamespace = Record.readInt();
2104 mergeRedeclarable(D, Redecl, PatternID);
2106 // If we merged the template with a prior declaration chain, merge the common
2108 // FIXME: Actually merge here, don't just overwrite.
2109 D->Common = D->getCanonicalDecl()->Common;
2114 void ASTDeclReader::VisitClassTemplateDecl(ClassTemplateDecl *D) {
2115 RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
2117 if (ThisDeclID == Redecl.getFirstID()) {
2118 // This ClassTemplateDecl owns a CommonPtr; read it to keep track of all of
2119 // the specializations.
2120 SmallVector<serialization::DeclID, 32> SpecIDs;
2121 ReadDeclIDList(SpecIDs);
2122 ASTDeclReader::AddLazySpecializations(D, SpecIDs);
2125 if (D->getTemplatedDecl()->TemplateOrInstantiation) {
2126 // We were loaded before our templated declaration was. We've not set up
2127 // its corresponding type yet (see VisitCXXRecordDeclImpl), so reconstruct
2129 Reader.getContext().getInjectedClassNameType(
2130 D->getTemplatedDecl(), D->getInjectedClassNameSpecialization());
2134 void ASTDeclReader::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
2135 llvm_unreachable("BuiltinTemplates are not serialized");
2138 /// TODO: Unify with ClassTemplateDecl version?
2139 /// May require unifying ClassTemplateDecl and
2140 /// VarTemplateDecl beyond TemplateDecl...
2141 void ASTDeclReader::VisitVarTemplateDecl(VarTemplateDecl *D) {
2142 RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
2144 if (ThisDeclID == Redecl.getFirstID()) {
2145 // This VarTemplateDecl owns a CommonPtr; read it to keep track of all of
2146 // the specializations.
2147 SmallVector<serialization::DeclID, 32> SpecIDs;
2148 ReadDeclIDList(SpecIDs);
2149 ASTDeclReader::AddLazySpecializations(D, SpecIDs);
2153 ASTDeclReader::RedeclarableResult
2154 ASTDeclReader::VisitClassTemplateSpecializationDeclImpl(
2155 ClassTemplateSpecializationDecl *D) {
2156 RedeclarableResult Redecl = VisitCXXRecordDeclImpl(D);
2158 ASTContext &C = Reader.getContext();
2159 if (Decl *InstD = ReadDecl()) {
2160 if (auto *CTD = dyn_cast<ClassTemplateDecl>(InstD)) {
2161 D->SpecializedTemplate = CTD;
2163 SmallVector<TemplateArgument, 8> TemplArgs;
2164 Record.readTemplateArgumentList(TemplArgs);
2165 TemplateArgumentList *ArgList
2166 = TemplateArgumentList::CreateCopy(C, TemplArgs);
2168 new (C) ClassTemplateSpecializationDecl::
2169 SpecializedPartialSpecialization();
2170 PS->PartialSpecialization
2171 = cast<ClassTemplatePartialSpecializationDecl>(InstD);
2172 PS->TemplateArgs = ArgList;
2173 D->SpecializedTemplate = PS;
2177 SmallVector<TemplateArgument, 8> TemplArgs;
2178 Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
2179 D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs);
2180 D->PointOfInstantiation = ReadSourceLocation();
2181 D->SpecializationKind = (TemplateSpecializationKind)Record.readInt();
2183 bool writtenAsCanonicalDecl = Record.readInt();
2184 if (writtenAsCanonicalDecl) {
2185 auto *CanonPattern = ReadDeclAs<ClassTemplateDecl>();
2186 if (D->isCanonicalDecl()) { // It's kept in the folding set.
2187 // Set this as, or find, the canonical declaration for this specialization
2188 ClassTemplateSpecializationDecl *CanonSpec;
2189 if (auto *Partial = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) {
2190 CanonSpec = CanonPattern->getCommonPtr()->PartialSpecializations
2191 .GetOrInsertNode(Partial);
2194 CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
2196 // If there was already a canonical specialization, merge into it.
2197 if (CanonSpec != D) {
2198 mergeRedeclarable<TagDecl>(D, CanonSpec, Redecl);
2200 // This declaration might be a definition. Merge with any existing
2202 if (auto *DDD = D->DefinitionData) {
2203 if (CanonSpec->DefinitionData)
2204 MergeDefinitionData(CanonSpec, std::move(*DDD));
2206 CanonSpec->DefinitionData = D->DefinitionData;
2208 D->DefinitionData = CanonSpec->DefinitionData;
2214 if (TypeSourceInfo *TyInfo = GetTypeSourceInfo()) {
2215 auto *ExplicitInfo =
2216 new (C) ClassTemplateSpecializationDecl::ExplicitSpecializationInfo;
2217 ExplicitInfo->TypeAsWritten = TyInfo;
2218 ExplicitInfo->ExternLoc = ReadSourceLocation();
2219 ExplicitInfo->TemplateKeywordLoc = ReadSourceLocation();
2220 D->ExplicitInfo = ExplicitInfo;
2226 void ASTDeclReader::VisitClassTemplatePartialSpecializationDecl(
2227 ClassTemplatePartialSpecializationDecl *D) {
2228 RedeclarableResult Redecl = VisitClassTemplateSpecializationDeclImpl(D);
2230 D->TemplateParams = Record.readTemplateParameterList();
2231 D->ArgsAsWritten = Record.readASTTemplateArgumentListInfo();
2233 // These are read/set from/to the first declaration.
2234 if (ThisDeclID == Redecl.getFirstID()) {
2235 D->InstantiatedFromMember.setPointer(
2236 ReadDeclAs<ClassTemplatePartialSpecializationDecl>());
2237 D->InstantiatedFromMember.setInt(Record.readInt());
2241 void ASTDeclReader::VisitClassScopeFunctionSpecializationDecl(
2242 ClassScopeFunctionSpecializationDecl *D) {
2244 D->Specialization = ReadDeclAs<CXXMethodDecl>();
2247 void ASTDeclReader::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
2248 RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
2250 if (ThisDeclID == Redecl.getFirstID()) {
2251 // This FunctionTemplateDecl owns a CommonPtr; read it.
2252 SmallVector<serialization::DeclID, 32> SpecIDs;
2253 ReadDeclIDList(SpecIDs);
2254 ASTDeclReader::AddLazySpecializations(D, SpecIDs);
2258 /// TODO: Unify with ClassTemplateSpecializationDecl version?
2259 /// May require unifying ClassTemplate(Partial)SpecializationDecl and
2260 /// VarTemplate(Partial)SpecializationDecl with a new data
2261 /// structure Template(Partial)SpecializationDecl, and
2262 /// using Template(Partial)SpecializationDecl as input type.
2263 ASTDeclReader::RedeclarableResult
2264 ASTDeclReader::VisitVarTemplateSpecializationDeclImpl(
2265 VarTemplateSpecializationDecl *D) {
2266 RedeclarableResult Redecl = VisitVarDeclImpl(D);
2268 ASTContext &C = Reader.getContext();
2269 if (Decl *InstD = ReadDecl()) {
2270 if (auto *VTD = dyn_cast<VarTemplateDecl>(InstD)) {
2271 D->SpecializedTemplate = VTD;
2273 SmallVector<TemplateArgument, 8> TemplArgs;
2274 Record.readTemplateArgumentList(TemplArgs);
2275 TemplateArgumentList *ArgList = TemplateArgumentList::CreateCopy(
2279 VarTemplateSpecializationDecl::SpecializedPartialSpecialization();
2280 PS->PartialSpecialization =
2281 cast<VarTemplatePartialSpecializationDecl>(InstD);
2282 PS->TemplateArgs = ArgList;
2283 D->SpecializedTemplate = PS;
2288 if (TypeSourceInfo *TyInfo = GetTypeSourceInfo()) {
2289 auto *ExplicitInfo =
2290 new (C) VarTemplateSpecializationDecl::ExplicitSpecializationInfo;
2291 ExplicitInfo->TypeAsWritten = TyInfo;
2292 ExplicitInfo->ExternLoc = ReadSourceLocation();
2293 ExplicitInfo->TemplateKeywordLoc = ReadSourceLocation();
2294 D->ExplicitInfo = ExplicitInfo;
2297 SmallVector<TemplateArgument, 8> TemplArgs;
2298 Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
2299 D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs);
2300 D->PointOfInstantiation = ReadSourceLocation();
2301 D->SpecializationKind = (TemplateSpecializationKind)Record.readInt();
2302 D->IsCompleteDefinition = Record.readInt();
2304 bool writtenAsCanonicalDecl = Record.readInt();
2305 if (writtenAsCanonicalDecl) {
2306 auto *CanonPattern = ReadDeclAs<VarTemplateDecl>();
2307 if (D->isCanonicalDecl()) { // It's kept in the folding set.
2308 // FIXME: If it's already present, merge it.
2309 if (auto *Partial = dyn_cast<VarTemplatePartialSpecializationDecl>(D)) {
2310 CanonPattern->getCommonPtr()->PartialSpecializations
2311 .GetOrInsertNode(Partial);
2313 CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
2321 /// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2322 /// May require unifying ClassTemplate(Partial)SpecializationDecl and
2323 /// VarTemplate(Partial)SpecializationDecl with a new data
2324 /// structure Template(Partial)SpecializationDecl, and
2325 /// using Template(Partial)SpecializationDecl as input type.
2326 void ASTDeclReader::VisitVarTemplatePartialSpecializationDecl(
2327 VarTemplatePartialSpecializationDecl *D) {
2328 RedeclarableResult Redecl = VisitVarTemplateSpecializationDeclImpl(D);
2330 D->TemplateParams = Record.readTemplateParameterList();
2331 D->ArgsAsWritten = Record.readASTTemplateArgumentListInfo();
2333 // These are read/set from/to the first declaration.
2334 if (ThisDeclID == Redecl.getFirstID()) {
2335 D->InstantiatedFromMember.setPointer(
2336 ReadDeclAs<VarTemplatePartialSpecializationDecl>());
2337 D->InstantiatedFromMember.setInt(Record.readInt());
2341 void ASTDeclReader::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
2344 D->setDeclaredWithTypename(Record.readInt());
2346 if (Record.readInt())
2347 D->setDefaultArgument(GetTypeSourceInfo());
2350 void ASTDeclReader::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
2351 VisitDeclaratorDecl(D);
2352 // TemplateParmPosition.
2353 D->setDepth(Record.readInt());
2354 D->setPosition(Record.readInt());
2355 if (D->isExpandedParameterPack()) {
2356 auto TypesAndInfos =
2357 D->getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>();
2358 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
2359 new (&TypesAndInfos[I].first) QualType(Record.readType());
2360 TypesAndInfos[I].second = GetTypeSourceInfo();
2363 // Rest of NonTypeTemplateParmDecl.
2364 D->ParameterPack = Record.readInt();
2365 if (Record.readInt())
2366 D->setDefaultArgument(Record.readExpr());
2370 void ASTDeclReader::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
2371 VisitTemplateDecl(D);
2372 // TemplateParmPosition.
2373 D->setDepth(Record.readInt());
2374 D->setPosition(Record.readInt());
2375 if (D->isExpandedParameterPack()) {
2376 auto **Data = D->getTrailingObjects<TemplateParameterList *>();
2377 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
2379 Data[I] = Record.readTemplateParameterList();
2381 // Rest of TemplateTemplateParmDecl.
2382 D->ParameterPack = Record.readInt();
2383 if (Record.readInt())
2384 D->setDefaultArgument(Reader.getContext(),
2385 Record.readTemplateArgumentLoc());
2389 void ASTDeclReader::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
2390 VisitRedeclarableTemplateDecl(D);
2393 void ASTDeclReader::VisitStaticAssertDecl(StaticAssertDecl *D) {
2395 D->AssertExprAndFailed.setPointer(Record.readExpr());
2396 D->AssertExprAndFailed.setInt(Record.readInt());
2397 D->Message = cast_or_null<StringLiteral>(Record.readExpr());
2398 D->RParenLoc = ReadSourceLocation();
2401 void ASTDeclReader::VisitEmptyDecl(EmptyDecl *D) {
2405 std::pair<uint64_t, uint64_t>
2406 ASTDeclReader::VisitDeclContext(DeclContext *DC) {
2407 uint64_t LexicalOffset = ReadLocalOffset();
2408 uint64_t VisibleOffset = ReadLocalOffset();
2409 return std::make_pair(LexicalOffset, VisibleOffset);
2412 template <typename T>
2413 ASTDeclReader::RedeclarableResult
2414 ASTDeclReader::VisitRedeclarable(Redeclarable<T> *D) {
2415 DeclID FirstDeclID = ReadDeclID();
2416 Decl *MergeWith = nullptr;
2418 bool IsKeyDecl = ThisDeclID == FirstDeclID;
2419 bool IsFirstLocalDecl = false;
2421 uint64_t RedeclOffset = 0;
2423 // 0 indicates that this declaration was the only declaration of its entity,
2424 // and is used for space optimization.
2425 if (FirstDeclID == 0) {
2426 FirstDeclID = ThisDeclID;
2428 IsFirstLocalDecl = true;
2429 } else if (unsigned N = Record.readInt()) {
2430 // This declaration was the first local declaration, but may have imported
2431 // other declarations.
2433 IsFirstLocalDecl = true;
2435 // We have some declarations that must be before us in our redeclaration
2436 // chain. Read them now, and remember that we ought to merge with one of
2438 // FIXME: Provide a known merge target to the second and subsequent such
2440 for (unsigned I = 0; I != N - 1; ++I)
2441 MergeWith = ReadDecl();
2443 RedeclOffset = ReadLocalOffset();
2445 // This declaration was not the first local declaration. Read the first
2446 // local declaration now, to trigger the import of other redeclarations.
2450 auto *FirstDecl = cast_or_null<T>(Reader.GetDecl(FirstDeclID));
2451 if (FirstDecl != D) {
2452 // We delay loading of the redeclaration chain to avoid deeply nested calls.
2453 // We temporarily set the first (canonical) declaration as the previous one
2454 // which is the one that matters and mark the real previous DeclID to be
2455 // loaded & attached later on.
2456 D->RedeclLink = Redeclarable<T>::PreviousDeclLink(FirstDecl);
2457 D->First = FirstDecl->getCanonicalDecl();
2460 auto *DAsT = static_cast<T *>(D);
2462 // Note that we need to load local redeclarations of this decl and build a
2463 // decl chain for them. This must happen *after* we perform the preloading
2464 // above; this ensures that the redeclaration chain is built in the correct
2466 if (IsFirstLocalDecl)
2467 Reader.PendingDeclChains.push_back(std::make_pair(DAsT, RedeclOffset));
2469 return RedeclarableResult(MergeWith, FirstDeclID, IsKeyDecl);
2472 /// Attempts to merge the given declaration (D) with another declaration
2473 /// of the same entity.
2474 template<typename T>
2475 void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *DBase,
2476 RedeclarableResult &Redecl,
2477 DeclID TemplatePatternID) {
2478 // If modules are not available, there is no reason to perform this merge.
2479 if (!Reader.getContext().getLangOpts().Modules)
2482 // If we're not the canonical declaration, we don't need to merge.
2483 if (!DBase->isFirstDecl())
2486 auto *D = static_cast<T *>(DBase);
2488 if (auto *Existing = Redecl.getKnownMergeTarget())
2489 // We already know of an existing declaration we should merge with.
2490 mergeRedeclarable(D, cast<T>(Existing), Redecl, TemplatePatternID);
2491 else if (FindExistingResult ExistingRes = findExisting(D))
2492 if (T *Existing = ExistingRes)
2493 mergeRedeclarable(D, Existing, Redecl, TemplatePatternID);
2496 /// "Cast" to type T, asserting if we don't have an implicit conversion.
2497 /// We use this to put code in a template that will only be valid for certain
2499 template<typename T> static T assert_cast(T t) { return t; }
2500 template<typename T> static T assert_cast(...) {
2501 llvm_unreachable("bad assert_cast");
2504 /// Merge together the pattern declarations from two template
2506 void ASTDeclReader::mergeTemplatePattern(RedeclarableTemplateDecl *D,
2507 RedeclarableTemplateDecl *Existing,
2508 DeclID DsID, bool IsKeyDecl) {
2509 auto *DPattern = D->getTemplatedDecl();
2510 auto *ExistingPattern = Existing->getTemplatedDecl();
2511 RedeclarableResult Result(/*MergeWith*/ ExistingPattern,
2512 DPattern->getCanonicalDecl()->getGlobalID(),
2515 if (auto *DClass = dyn_cast<CXXRecordDecl>(DPattern)) {
2516 // Merge with any existing definition.
2517 // FIXME: This is duplicated in several places. Refactor.
2518 auto *ExistingClass =
2519 cast<CXXRecordDecl>(ExistingPattern)->getCanonicalDecl();
2520 if (auto *DDD = DClass->DefinitionData) {
2521 if (ExistingClass->DefinitionData) {
2522 MergeDefinitionData(ExistingClass, std::move(*DDD));
2524 ExistingClass->DefinitionData = DClass->DefinitionData;
2525 // We may have skipped this before because we thought that DClass
2526 // was the canonical declaration.
2527 Reader.PendingDefinitions.insert(DClass);
2530 DClass->DefinitionData = ExistingClass->DefinitionData;
2532 return mergeRedeclarable(DClass, cast<TagDecl>(ExistingPattern),
2535 if (auto *DFunction = dyn_cast<FunctionDecl>(DPattern))
2536 return mergeRedeclarable(DFunction, cast<FunctionDecl>(ExistingPattern),
2538 if (auto *DVar = dyn_cast<VarDecl>(DPattern))
2539 return mergeRedeclarable(DVar, cast<VarDecl>(ExistingPattern), Result);
2540 if (auto *DAlias = dyn_cast<TypeAliasDecl>(DPattern))
2541 return mergeRedeclarable(DAlias, cast<TypedefNameDecl>(ExistingPattern),
2543 llvm_unreachable("merged an unknown kind of redeclarable template");
2546 /// Attempts to merge the given declaration (D) with another declaration
2547 /// of the same entity.
2548 template<typename T>
2549 void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *DBase, T *Existing,
2550 RedeclarableResult &Redecl,
2551 DeclID TemplatePatternID) {
2552 auto *D = static_cast<T *>(DBase);
2553 T *ExistingCanon = Existing->getCanonicalDecl();
2554 T *DCanon = D->getCanonicalDecl();
2555 if (ExistingCanon != DCanon) {
2556 assert(DCanon->getGlobalID() == Redecl.getFirstID() &&
2557 "already merged this declaration");
2559 // Have our redeclaration link point back at the canonical declaration
2560 // of the existing declaration, so that this declaration has the
2561 // appropriate canonical declaration.
2562 D->RedeclLink = Redeclarable<T>::PreviousDeclLink(ExistingCanon);
2563 D->First = ExistingCanon;
2564 ExistingCanon->Used |= D->Used;
2567 // When we merge a namespace, update its pointer to the first namespace.
2568 // We cannot have loaded any redeclarations of this declaration yet, so
2569 // there's nothing else that needs to be updated.
2570 if (auto *Namespace = dyn_cast<NamespaceDecl>(D))
2571 Namespace->AnonOrFirstNamespaceAndInline.setPointer(
2572 assert_cast<NamespaceDecl*>(ExistingCanon));
2574 // When we merge a template, merge its pattern.
2575 if (auto *DTemplate = dyn_cast<RedeclarableTemplateDecl>(D))
2576 mergeTemplatePattern(
2577 DTemplate, assert_cast<RedeclarableTemplateDecl*>(ExistingCanon),
2578 TemplatePatternID, Redecl.isKeyDecl());
2580 // If this declaration is a key declaration, make a note of that.
2581 if (Redecl.isKeyDecl())
2582 Reader.KeyDecls[ExistingCanon].push_back(Redecl.getFirstID());
2586 /// ODR-like semantics for C/ObjC allow us to merge tag types and a structural
2587 /// check in Sema guarantees the types can be merged (see C11 6.2.7/1 or C89
2588 /// 6.1.2.6/1). Although most merging is done in Sema, we need to guarantee
2589 /// that some types are mergeable during deserialization, otherwise name
2590 /// lookup fails. This is the case for EnumConstantDecl.
2591 static bool allowODRLikeMergeInC(NamedDecl *ND) {
2594 // TODO: implement merge for other necessary decls.
2595 if (isa<EnumConstantDecl>(ND))
2600 /// Attempts to merge the given declaration (D) with another declaration
2601 /// of the same entity, for the case where the entity is not actually
2602 /// redeclarable. This happens, for instance, when merging the fields of
2603 /// identical class definitions from two different modules.
2604 template<typename T>
2605 void ASTDeclReader::mergeMergeable(Mergeable<T> *D) {
2606 // If modules are not available, there is no reason to perform this merge.
2607 if (!Reader.getContext().getLangOpts().Modules)
2610 // ODR-based merging is performed in C++ and in some cases (tag types) in C.
2611 // Note that C identically-named things in different translation units are
2612 // not redeclarations, but may still have compatible types, where ODR-like
2613 // semantics may apply.
2614 if (!Reader.getContext().getLangOpts().CPlusPlus &&
2615 !allowODRLikeMergeInC(dyn_cast<NamedDecl>(static_cast<T*>(D))))
2618 if (FindExistingResult ExistingRes = findExisting(static_cast<T*>(D)))
2619 if (T *Existing = ExistingRes)
2620 Reader.getContext().setPrimaryMergedDecl(static_cast<T *>(D),
2621 Existing->getCanonicalDecl());
2624 void ASTDeclReader::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {
2626 unsigned NumVars = D->varlist_size();
2627 SmallVector<Expr *, 16> Vars;
2628 Vars.reserve(NumVars);
2629 for (unsigned i = 0; i != NumVars; ++i) {
2630 Vars.push_back(Record.readExpr());
2635 void ASTDeclReader::VisitOMPRequiresDecl(OMPRequiresDecl * D) {
2637 unsigned NumClauses = D->clauselist_size();
2638 SmallVector<OMPClause *, 8> Clauses;
2639 Clauses.reserve(NumClauses);
2640 OMPClauseReader ClauseReader(Record);
2641 for (unsigned I = 0; I != NumClauses; ++I)
2642 Clauses.push_back(ClauseReader.readClause());
2643 D->setClauses(Clauses);
2646 void ASTDeclReader::VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D) {
2648 D->setLocation(ReadSourceLocation());
2649 Expr *In = Record.readExpr();
2650 Expr *Out = Record.readExpr();
2651 D->setCombinerData(In, Out);
2652 Expr *Combiner = Record.readExpr();
2653 D->setCombiner(Combiner);
2654 Expr *Orig = Record.readExpr();
2655 Expr *Priv = Record.readExpr();
2656 D->setInitializerData(Orig, Priv);
2657 Expr *Init = Record.readExpr();
2658 auto IK = static_cast<OMPDeclareReductionDecl::InitKind>(Record.readInt());
2659 D->setInitializer(Init, IK);
2660 D->PrevDeclInScope = ReadDeclID();
2663 void ASTDeclReader::VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D) {
2667 //===----------------------------------------------------------------------===//
2668 // Attribute Reading
2669 //===----------------------------------------------------------------------===//
2675 const ASTReader::RecordData &Record;
2679 AttrReader(ModuleFile &F, ASTReader &Reader,
2680 const ASTReader::RecordData &Record, unsigned &Idx)
2681 : F(&F), Reader(&Reader), Record(Record), Idx(Idx) {}
2683 const uint64_t &readInt() { return Record[Idx++]; }
2685 SourceRange readSourceRange() {
2686 return Reader->ReadSourceRange(*F, Record, Idx);
2689 Expr *readExpr() { return Reader->ReadExpr(*F); }
2691 std::string readString() {
2692 return Reader->ReadString(Record, Idx);
2695 TypeSourceInfo *getTypeSourceInfo() {
2696 return Reader->GetTypeSourceInfo(*F, Record, Idx);
2699 IdentifierInfo *getIdentifierInfo() {
2700 return Reader->GetIdentifierInfo(*F, Record, Idx);
2703 VersionTuple readVersionTuple() {
2704 return ASTReader::ReadVersionTuple(Record, Idx);
2707 template <typename T> T *GetLocalDeclAs(uint32_t LocalID) {
2708 return cast_or_null<T>(Reader->GetLocalDecl(*F, LocalID));
2713 Attr *ASTReader::ReadAttr(ModuleFile &M, const RecordData &Rec,
2715 AttrReader Record(M, *this, Rec, Idx);
2716 auto V = Record.readInt();
2720 Attr *New = nullptr;
2721 // Kind is stored as a 1-based integer because 0 is used to indicate a null
2723 auto Kind = static_cast<attr::Kind>(V - 1);
2724 SourceRange Range = Record.readSourceRange();
2725 ASTContext &Context = getContext();
2727 #include "clang/Serialization/AttrPCHRead.inc"
2729 assert(New && "Unable to decode attribute?");
2733 /// Reads attributes from the current stream position.
2734 void ASTReader::ReadAttributes(ASTRecordReader &Record, AttrVec &Attrs) {
2735 for (unsigned I = 0, E = Record.readInt(); I != E; ++I)
2736 Attrs.push_back(Record.readAttr());
2739 //===----------------------------------------------------------------------===//
2740 // ASTReader Implementation
2741 //===----------------------------------------------------------------------===//
2743 /// Note that we have loaded the declaration with the given
2746 /// This routine notes that this declaration has already been loaded,
2747 /// so that future GetDecl calls will return this declaration rather
2748 /// than trying to load a new declaration.
2749 inline void ASTReader::LoadedDecl(unsigned Index, Decl *D) {
2750 assert(!DeclsLoaded[Index] && "Decl loaded twice?");
2751 DeclsLoaded[Index] = D;
2754 /// Determine whether the consumer will be interested in seeing
2755 /// this declaration (via HandleTopLevelDecl).
2757 /// This routine should return true for anything that might affect
2758 /// code generation, e.g., inline function definitions, Objective-C
2759 /// declarations with metadata, etc.
2760 static bool isConsumerInterestedIn(ASTContext &Ctx, Decl *D, bool HasBody) {
2761 // An ObjCMethodDecl is never considered as "interesting" because its
2762 // implementation container always is.
2764 // An ImportDecl or VarDecl imported from a module map module will get
2765 // emitted when we import the relevant module.
2766 if (isa<ImportDecl>(D) || isa<VarDecl>(D)) {
2767 auto *M = D->getImportedOwningModule();
2768 if (M && M->Kind == Module::ModuleMapModule &&
2769 Ctx.DeclMustBeEmitted(D))
2773 if (isa<FileScopeAsmDecl>(D) ||
2774 isa<ObjCProtocolDecl>(D) ||
2775 isa<ObjCImplDecl>(D) ||
2776 isa<ImportDecl>(D) ||
2777 isa<PragmaCommentDecl>(D) ||
2778 isa<PragmaDetectMismatchDecl>(D))
2780 if (isa<OMPThreadPrivateDecl>(D) || isa<OMPDeclareReductionDecl>(D))
2781 return !D->getDeclContext()->isFunctionOrMethod();
2782 if (const auto *Var = dyn_cast<VarDecl>(D))
2783 return Var->isFileVarDecl() &&
2784 (Var->isThisDeclarationADefinition() == VarDecl::Definition ||
2785 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Var));
2786 if (const auto *Func = dyn_cast<FunctionDecl>(D))
2787 return Func->doesThisDeclarationHaveABody() || HasBody;
2789 if (auto *ES = D->getASTContext().getExternalSource())
2790 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
2796 /// Get the correct cursor and offset for loading a declaration.
2797 ASTReader::RecordLocation
2798 ASTReader::DeclCursorForID(DeclID ID, SourceLocation &Loc) {
2799 GlobalDeclMapType::iterator I = GlobalDeclMap.find(ID);
2800 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
2801 ModuleFile *M = I->second;
2802 const DeclOffset &DOffs =
2803 M->DeclOffsets[ID - M->BaseDeclID - NUM_PREDEF_DECL_IDS];
2804 Loc = TranslateSourceLocation(*M, DOffs.getLocation());
2805 return RecordLocation(M, DOffs.BitOffset);
2808 ASTReader::RecordLocation ASTReader::getLocalBitOffset(uint64_t GlobalOffset) {
2809 auto I = GlobalBitOffsetsMap.find(GlobalOffset);
2811 assert(I != GlobalBitOffsetsMap.end() && "Corrupted global bit offsets map");
2812 return RecordLocation(I->second, GlobalOffset - I->second->GlobalBitOffset);
2815 uint64_t ASTReader::getGlobalBitOffset(ModuleFile &M, uint32_t LocalOffset) {
2816 return LocalOffset + M.GlobalBitOffset;
2819 static bool isSameTemplateParameterList(const TemplateParameterList *X,
2820 const TemplateParameterList *Y);
2822 /// Determine whether two template parameters are similar enough
2823 /// that they may be used in declarations of the same template.
2824 static bool isSameTemplateParameter(const NamedDecl *X,
2825 const NamedDecl *Y) {
2826 if (X->getKind() != Y->getKind())
2829 if (const auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
2830 const auto *TY = cast<TemplateTypeParmDecl>(Y);
2831 return TX->isParameterPack() == TY->isParameterPack();
2834 if (const auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
2835 const auto *TY = cast<NonTypeTemplateParmDecl>(Y);
2836 return TX->isParameterPack() == TY->isParameterPack() &&
2837 TX->getASTContext().hasSameType(TX->getType(), TY->getType());
2840 const auto *TX = cast<TemplateTemplateParmDecl>(X);
2841 const auto *TY = cast<TemplateTemplateParmDecl>(Y);
2842 return TX->isParameterPack() == TY->isParameterPack() &&
2843 isSameTemplateParameterList(TX->getTemplateParameters(),
2844 TY->getTemplateParameters());
2847 static NamespaceDecl *getNamespace(const NestedNameSpecifier *X) {
2848 if (auto *NS = X->getAsNamespace())
2850 if (auto *NAS = X->getAsNamespaceAlias())
2851 return NAS->getNamespace();
2855 static bool isSameQualifier(const NestedNameSpecifier *X,
2856 const NestedNameSpecifier *Y) {
2857 if (auto *NSX = getNamespace(X)) {
2858 auto *NSY = getNamespace(Y);
2859 if (!NSY || NSX->getCanonicalDecl() != NSY->getCanonicalDecl())
2861 } else if (X->getKind() != Y->getKind())
2864 // FIXME: For namespaces and types, we're permitted to check that the entity
2865 // is named via the same tokens. We should probably do so.
2866 switch (X->getKind()) {
2867 case NestedNameSpecifier::Identifier:
2868 if (X->getAsIdentifier() != Y->getAsIdentifier())
2871 case NestedNameSpecifier::Namespace:
2872 case NestedNameSpecifier::NamespaceAlias:
2873 // We've already checked that we named the same namespace.
2875 case NestedNameSpecifier::TypeSpec:
2876 case NestedNameSpecifier::TypeSpecWithTemplate:
2877 if (X->getAsType()->getCanonicalTypeInternal() !=
2878 Y->getAsType()->getCanonicalTypeInternal())
2881 case NestedNameSpecifier::Global:
2882 case NestedNameSpecifier::Super:
2886 // Recurse into earlier portion of NNS, if any.
2887 auto *PX = X->getPrefix();
2888 auto *PY = Y->getPrefix();
2890 return isSameQualifier(PX, PY);
2894 /// Determine whether two template parameter lists are similar enough
2895 /// that they may be used in declarations of the same template.
2896 static bool isSameTemplateParameterList(const TemplateParameterList *X,
2897 const TemplateParameterList *Y) {
2898 if (X->size() != Y->size())
2901 for (unsigned I = 0, N = X->size(); I != N; ++I)
2902 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
2908 /// Determine whether the attributes we can overload on are identical for A and
2909 /// B. Will ignore any overloadable attrs represented in the type of A and B.
2910 static bool hasSameOverloadableAttrs(const FunctionDecl *A,
2911 const FunctionDecl *B) {
2912 // Note that pass_object_size attributes are represented in the function's
2913 // ExtParameterInfo, so we don't need to check them here.
2915 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
2916 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
2917 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
2919 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
2920 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
2921 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
2923 // Return false if the number of enable_if attributes is different.
2924 if (!Cand1A || !Cand2A)
2930 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
2931 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
2933 // Return false if any of the enable_if expressions of A and B are
2935 if (Cand1ID != Cand2ID)
2941 /// Determine whether the two declarations refer to the same entity.
2942 static bool isSameEntity(NamedDecl *X, NamedDecl *Y) {
2943 assert(X->getDeclName() == Y->getDeclName() && "Declaration name mismatch!");
2948 // Must be in the same context.
2950 // Note that we can't use DeclContext::Equals here, because the DeclContexts
2951 // could be two different declarations of the same function. (We will fix the
2952 // semantic DC to refer to the primary definition after merging.)
2953 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
2954 cast<Decl>(Y->getDeclContext()->getRedeclContext())))
2957 // Two typedefs refer to the same entity if they have the same underlying
2959 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
2960 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
2961 return X->getASTContext().hasSameType(TypedefX->getUnderlyingType(),
2962 TypedefY->getUnderlyingType());
2964 // Must have the same kind.
2965 if (X->getKind() != Y->getKind())
2968 // Objective-C classes and protocols with the same name always match.
2969 if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
2972 if (isa<ClassTemplateSpecializationDecl>(X)) {
2973 // No need to handle these here: we merge them when adding them to the
2978 // Compatible tags match.
2979 if (const auto *TagX = dyn_cast<TagDecl>(X)) {
2980 const auto *TagY = cast<TagDecl>(Y);
2981 return (TagX->getTagKind() == TagY->getTagKind()) ||
2982 ((TagX->getTagKind() == TTK_Struct || TagX->getTagKind() == TTK_Class ||
2983 TagX->getTagKind() == TTK_Interface) &&
2984 (TagY->getTagKind() == TTK_Struct || TagY->getTagKind() == TTK_Class ||
2985 TagY->getTagKind() == TTK_Interface));
2988 // Functions with the same type and linkage match.
2989 // FIXME: This needs to cope with merging of prototyped/non-prototyped
2991 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
2992 const auto *FuncY = cast<FunctionDecl>(Y);
2993 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
2994 const auto *CtorY = cast<CXXConstructorDecl>(Y);
2995 if (CtorX->getInheritedConstructor() &&
2996 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
2997 CtorY->getInheritedConstructor().getConstructor()))
3001 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
3004 // Multiversioned functions with different feature strings are represented
3005 // as separate declarations.
3006 if (FuncX->isMultiVersion()) {
3007 const auto *TAX = FuncX->getAttr<TargetAttr>();
3008 const auto *TAY = FuncY->getAttr<TargetAttr>();
3009 assert(TAX && TAY && "Multiversion Function without target attribute");
3011 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
3015 ASTContext &C = FuncX->getASTContext();
3016 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
3017 // Map to the first declaration that we've already merged into this one.
3018 // The TSI of redeclarations might not match (due to calling conventions
3019 // being inherited onto the type but not the TSI), but the TSI type of
3020 // the first declaration of the function should match across modules.
3021 FD = FD->getCanonicalDecl();
3022 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
3025 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
3026 if (!C.hasSameType(XT, YT)) {
3027 // We can get functions with different types on the redecl chain in C++17
3028 // if they have differing exception specifications and at least one of
3029 // the excpetion specs is unresolved.
3030 auto *XFPT = XT->getAs<FunctionProtoType>();
3031 auto *YFPT = YT->getAs<FunctionProtoType>();
3032 if (C.getLangOpts().CPlusPlus17 && XFPT && YFPT &&
3033 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
3034 isUnresolvedExceptionSpec(YFPT->getExceptionSpecType())) &&
3035 C.hasSameFunctionTypeIgnoringExceptionSpec(XT, YT))
3039 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
3040 hasSameOverloadableAttrs(FuncX, FuncY);
3043 // Variables with the same type and linkage match.
3044 if (const auto *VarX = dyn_cast<VarDecl>(X)) {
3045 const auto *VarY = cast<VarDecl>(Y);
3046 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
3047 ASTContext &C = VarX->getASTContext();
3048 if (C.hasSameType(VarX->getType(), VarY->getType()))
3051 // We can get decls with different types on the redecl chain. Eg.
3052 // template <typename T> struct S { static T Var[]; }; // #1
3053 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
3054 // Only? happens when completing an incomplete array type. In this case
3055 // when comparing #1 and #2 we should go through their element type.
3056 const ArrayType *VarXTy = C.getAsArrayType(VarX->getType());
3057 const ArrayType *VarYTy = C.getAsArrayType(VarY->getType());
3058 if (!VarXTy || !VarYTy)
3060 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
3061 return C.hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
3066 // Namespaces with the same name and inlinedness match.
3067 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
3068 const auto *NamespaceY = cast<NamespaceDecl>(Y);
3069 return NamespaceX->isInline() == NamespaceY->isInline();
3072 // Identical template names and kinds match if their template parameter lists
3073 // and patterns match.
3074 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
3075 const auto *TemplateY = cast<TemplateDecl>(Y);
3076 return isSameEntity(TemplateX->getTemplatedDecl(),
3077 TemplateY->getTemplatedDecl()) &&
3078 isSameTemplateParameterList(TemplateX->getTemplateParameters(),
3079 TemplateY->getTemplateParameters());
3082 // Fields with the same name and the same type match.
3083 if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
3084 const auto *FDY = cast<FieldDecl>(Y);
3085 // FIXME: Also check the bitwidth is odr-equivalent, if any.
3086 return X->getASTContext().hasSameType(FDX->getType(), FDY->getType());
3089 // Indirect fields with the same target field match.
3090 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
3091 const auto *IFDY = cast<IndirectFieldDecl>(Y);
3092 return IFDX->getAnonField()->getCanonicalDecl() ==
3093 IFDY->getAnonField()->getCanonicalDecl();
3096 // Enumerators with the same name match.
3097 if (isa<EnumConstantDecl>(X))
3098 // FIXME: Also check the value is odr-equivalent.
3101 // Using shadow declarations with the same target match.
3102 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
3103 const auto *USY = cast<UsingShadowDecl>(Y);
3104 return USX->getTargetDecl() == USY->getTargetDecl();
3107 // Using declarations with the same qualifier match. (We already know that
3108 // the name matches.)
3109 if (const auto *UX = dyn_cast<UsingDecl>(X)) {
3110 const auto *UY = cast<UsingDecl>(Y);
3111 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
3112 UX->hasTypename() == UY->hasTypename() &&
3113 UX->isAccessDeclaration() == UY->isAccessDeclaration();
3115 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
3116 const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
3117 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
3118 UX->isAccessDeclaration() == UY->isAccessDeclaration();
3120 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X))
3121 return isSameQualifier(
3123 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
3125 // Namespace alias definitions with the same target match.
3126 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
3127 const auto *NAY = cast<NamespaceAliasDecl>(Y);
3128 return NAX->getNamespace()->Equals(NAY->getNamespace());
3134 /// Find the context in which we should search for previous declarations when
3135 /// looking for declarations to merge.
3136 DeclContext *ASTDeclReader::getPrimaryContextForMerging(ASTReader &Reader,
3138 if (auto *ND = dyn_cast<NamespaceDecl>(DC))
3139 return ND->getOriginalNamespace();
3141 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
3142 // Try to dig out the definition.
3143 auto *DD = RD->DefinitionData;
3145 DD = RD->getCanonicalDecl()->DefinitionData;
3147 // If there's no definition yet, then DC's definition is added by an update
3148 // record, but we've not yet loaded that update record. In this case, we
3149 // commit to DC being the canonical definition now, and will fix this when
3150 // we load the update record.
3152 DD = new (Reader.getContext()) struct CXXRecordDecl::DefinitionData(RD);
3153 RD->setCompleteDefinition(true);
3154 RD->DefinitionData = DD;
3155 RD->getCanonicalDecl()->DefinitionData = DD;
3157 // Track that we did this horrible thing so that we can fix it later.
3158 Reader.PendingFakeDefinitionData.insert(
3159 std::make_pair(DD, ASTReader::PendingFakeDefinitionKind::Fake));
3162 return DD->Definition;
3165 if (auto *ED = dyn_cast<EnumDecl>(DC))
3166 return ED->getASTContext().getLangOpts().CPlusPlus? ED->getDefinition()
3169 // We can see the TU here only if we have no Sema object. In that case,
3170 // there's no TU scope to look in, so using the DC alone is sufficient.
3171 if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
3177 ASTDeclReader::FindExistingResult::~FindExistingResult() {
3178 // Record that we had a typedef name for linkage whether or not we merge
3179 // with that declaration.
3180 if (TypedefNameForLinkage) {
3181 DeclContext *DC = New->getDeclContext()->getRedeclContext();
3182 Reader.ImportedTypedefNamesForLinkage.insert(
3183 std::make_pair(std::make_pair(DC, TypedefNameForLinkage), New));
3187 if (!AddResult || Existing)
3190 DeclarationName Name = New->getDeclName();
3191 DeclContext *DC = New->getDeclContext()->getRedeclContext();
3192 if (needsAnonymousDeclarationNumber(New)) {
3193 setAnonymousDeclForMerging(Reader, New->getLexicalDeclContext(),
3194 AnonymousDeclNumber, New);
3195 } else if (DC->isTranslationUnit() &&
3196 !Reader.getContext().getLangOpts().CPlusPlus) {
3197 if (Reader.getIdResolver().tryAddTopLevelDecl(New, Name))
3198 Reader.PendingFakeLookupResults[Name.getAsIdentifierInfo()]
3200 } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
3201 // Add the declaration to its redeclaration context so later merging
3202 // lookups will find it.
3203 MergeDC->makeDeclVisibleInContextImpl(New, /*Internal*/true);
3207 /// Find the declaration that should be merged into, given the declaration found
3208 /// by name lookup. If we're merging an anonymous declaration within a typedef,
3209 /// we need a matching typedef, and we merge with the type inside it.
3210 static NamedDecl *getDeclForMerging(NamedDecl *Found,
3211 bool IsTypedefNameForLinkage) {
3212 if (!IsTypedefNameForLinkage)
3215 // If we found a typedef declaration that gives a name to some other
3216 // declaration, then we want that inner declaration. Declarations from
3217 // AST files are handled via ImportedTypedefNamesForLinkage.
3218 if (Found->isFromASTFile())
3221 if (auto *TND = dyn_cast<TypedefNameDecl>(Found))
3222 return TND->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
3227 /// Find the declaration to use to populate the anonymous declaration table
3228 /// for the given lexical DeclContext. We only care about finding local
3229 /// definitions of the context; we'll merge imported ones as we go.
3231 ASTDeclReader::getPrimaryDCForAnonymousDecl(DeclContext *LexicalDC) {
3232 // For classes, we track the definition as we merge.
3233 if (auto *RD = dyn_cast<CXXRecordDecl>(LexicalDC)) {
3234 auto *DD = RD->getCanonicalDecl()->DefinitionData;
3235 return DD ? DD->Definition : nullptr;
3238 // For anything else, walk its merged redeclarations looking for a definition.
3239 // Note that we can't just call getDefinition here because the redeclaration
3240 // chain isn't wired up.
3241 for (auto *D : merged_redecls(cast<Decl>(LexicalDC))) {
3242 if (auto *FD = dyn_cast<FunctionDecl>(D))
3243 if (FD->isThisDeclarationADefinition())
3245 if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
3246 if (MD->isThisDeclarationADefinition())
3250 // No merged definition yet.
3254 NamedDecl *ASTDeclReader::getAnonymousDeclForMerging(ASTReader &Reader,
3257 // If the lexical context has been merged, look into the now-canonical
3259 auto *CanonDC = cast<Decl>(DC)->getCanonicalDecl();
3261 // If we've seen this before, return the canonical declaration.
3262 auto &Previous = Reader.AnonymousDeclarationsForMerging[CanonDC];
3263 if (Index < Previous.size() && Previous[Index])
3264 return Previous[Index];
3266 // If this is the first time, but we have parsed a declaration of the context,
3267 // build the anonymous declaration list from the parsed declaration.
3268 auto *PrimaryDC = getPrimaryDCForAnonymousDecl(DC);
3269 if (PrimaryDC && !cast<Decl>(PrimaryDC)->isFromASTFile()) {
3270 numberAnonymousDeclsWithin(PrimaryDC, [&](NamedDecl *ND, unsigned Number) {
3271 if (Previous.size() == Number)
3272 Previous.push_back(cast<NamedDecl>(ND->getCanonicalDecl()));
3274 Previous[Number] = cast<NamedDecl>(ND->getCanonicalDecl());
3278 return Index < Previous.size() ? Previous[Index] : nullptr;
3281 void ASTDeclReader::setAnonymousDeclForMerging(ASTReader &Reader,
3282 DeclContext *DC, unsigned Index,
3284 auto *CanonDC = cast<Decl>(DC)->getCanonicalDecl();
3286 auto &Previous = Reader.AnonymousDeclarationsForMerging[CanonDC];
3287 if (Index >= Previous.size())
3288 Previous.resize(Index + 1);
3289 if (!Previous[Index])
3290 Previous[Index] = D;
3293 ASTDeclReader::FindExistingResult ASTDeclReader::findExisting(NamedDecl *D) {
3294 DeclarationName Name = TypedefNameForLinkage ? TypedefNameForLinkage
3297 if (!Name && !needsAnonymousDeclarationNumber(D)) {
3298 // Don't bother trying to find unnamed declarations that are in
3299 // unmergeable contexts.
3300 FindExistingResult Result(Reader, D, /*Existing=*/nullptr,
3301 AnonymousDeclNumber, TypedefNameForLinkage);
3306 DeclContext *DC = D->getDeclContext()->getRedeclContext();
3307 if (TypedefNameForLinkage) {
3308 auto It = Reader.ImportedTypedefNamesForLinkage.find(
3309 std::make_pair(DC, TypedefNameForLinkage));
3310 if (It != Reader.ImportedTypedefNamesForLinkage.end())
3311 if (isSameEntity(It->second, D))
3312 return FindExistingResult(Reader, D, It->second, AnonymousDeclNumber,
3313 TypedefNameForLinkage);
3314 // Go on to check in other places in case an existing typedef name
3315 // was not imported.
3318 if (needsAnonymousDeclarationNumber(D)) {
3319 // This is an anonymous declaration that we may need to merge. Look it up
3320 // in its context by number.
3321 if (auto *Existing = getAnonymousDeclForMerging(
3322 Reader, D->getLexicalDeclContext(), AnonymousDeclNumber))
3323 if (isSameEntity(Existing, D))
3324 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3325 TypedefNameForLinkage);
3326 } else if (DC->isTranslationUnit() &&
3327 !Reader.getContext().getLangOpts().CPlusPlus) {
3328 IdentifierResolver &IdResolver = Reader.getIdResolver();
3330 // Temporarily consider the identifier to be up-to-date. We don't want to
3331 // cause additional lookups here.
3332 class UpToDateIdentifierRAII {
3334 bool WasOutToDate = false;
3337 explicit UpToDateIdentifierRAII(IdentifierInfo *II) : II(II) {
3339 WasOutToDate = II->isOutOfDate();
3341 II->setOutOfDate(false);
3345 ~UpToDateIdentifierRAII() {
3347 II->setOutOfDate(true);
3349 } UpToDate(Name.getAsIdentifierInfo());
3351 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
3352 IEnd = IdResolver.end();
3354 if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage))
3355 if (isSameEntity(Existing, D))
3356 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3357 TypedefNameForLinkage);
3359 } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
3360 DeclContext::lookup_result R = MergeDC->noload_lookup(Name);
3361 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
3362 if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage))
3363 if (isSameEntity(Existing, D))
3364 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3365 TypedefNameForLinkage);
3368 // Not in a mergeable context.
3369 return FindExistingResult(Reader);
3372 // If this declaration is from a merged context, make a note that we need to
3373 // check that the canonical definition of that context contains the decl.
3375 // FIXME: We should do something similar if we merge two definitions of the
3376 // same template specialization into the same CXXRecordDecl.
3377 auto MergedDCIt = Reader.MergedDeclContexts.find(D->getLexicalDeclContext());
3378 if (MergedDCIt != Reader.MergedDeclContexts.end() &&
3379 MergedDCIt->second == D->getDeclContext())
3380 Reader.PendingOdrMergeChecks.push_back(D);
3382 return FindExistingResult(Reader, D, /*Existing=*/nullptr,
3383 AnonymousDeclNumber, TypedefNameForLinkage);
3386 template<typename DeclT>
3387 Decl *ASTDeclReader::getMostRecentDeclImpl(Redeclarable<DeclT> *D) {
3388 return D->RedeclLink.getLatestNotUpdated();
3391 Decl *ASTDeclReader::getMostRecentDeclImpl(...) {
3392 llvm_unreachable("getMostRecentDecl on non-redeclarable declaration");
3395 Decl *ASTDeclReader::getMostRecentDecl(Decl *D) {
3398 switch (D->getKind()) {
3399 #define ABSTRACT_DECL(TYPE)
3400 #define DECL(TYPE, BASE) \
3402 return getMostRecentDeclImpl(cast<TYPE##Decl>(D));
3403 #include "clang/AST/DeclNodes.inc"
3405 llvm_unreachable("unknown decl kind");
3408 Decl *ASTReader::getMostRecentExistingDecl(Decl *D) {
3409 return ASTDeclReader::getMostRecentDecl(D->getCanonicalDecl());
3412 template<typename DeclT>
3413 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3414 Redeclarable<DeclT> *D,
3415 Decl *Previous, Decl *Canon) {
3416 D->RedeclLink.setPrevious(cast<DeclT>(Previous));
3417 D->First = cast<DeclT>(Previous)->First;
3423 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3424 Redeclarable<VarDecl> *D,
3425 Decl *Previous, Decl *Canon) {
3426 auto *VD = static_cast<VarDecl *>(D);
3427 auto *PrevVD = cast<VarDecl>(Previous);
3428 D->RedeclLink.setPrevious(PrevVD);
3429 D->First = PrevVD->First;
3431 // We should keep at most one definition on the chain.
3432 // FIXME: Cache the definition once we've found it. Building a chain with
3433 // N definitions currently takes O(N^2) time here.
3434 if (VD->isThisDeclarationADefinition() == VarDecl::Definition) {
3435 for (VarDecl *CurD = PrevVD; CurD; CurD = CurD->getPreviousDecl()) {
3436 if (CurD->isThisDeclarationADefinition() == VarDecl::Definition) {
3437 Reader.mergeDefinitionVisibility(CurD, VD);
3438 VD->demoteThisDefinitionToDeclaration();
3445 static bool isUndeducedReturnType(QualType T) {
3446 auto *DT = T->getContainedDeducedType();
3447 return DT && !DT->isDeduced();
3451 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3452 Redeclarable<FunctionDecl> *D,
3453 Decl *Previous, Decl *Canon) {
3454 auto *FD = static_cast<FunctionDecl *>(D);
3455 auto *PrevFD = cast<FunctionDecl>(Previous);
3457 FD->RedeclLink.setPrevious(PrevFD);
3458 FD->First = PrevFD->First;
3460 // If the previous declaration is an inline function declaration, then this
3461 // declaration is too.
3462 if (PrevFD->isInlined() != FD->isInlined()) {
3463 // FIXME: [dcl.fct.spec]p4:
3464 // If a function with external linkage is declared inline in one
3465 // translation unit, it shall be declared inline in all translation
3466 // units in which it appears.
3468 // Be careful of this case:
3471 // template<typename T> struct X { void f(); };
3472 // template<typename T> inline void X<T>::f() {}
3474 // module B instantiates the declaration of X<int>::f
3475 // module C instantiates the definition of X<int>::f
3477 // If module B and C are merged, we do not have a violation of this rule.
3478 FD->setImplicitlyInline(true);
3481 auto *FPT = FD->getType()->getAs<FunctionProtoType>();
3482 auto *PrevFPT = PrevFD->getType()->getAs<FunctionProtoType>();
3483 if (FPT && PrevFPT) {
3484 // If we need to propagate an exception specification along the redecl
3485 // chain, make a note of that so that we can do so later.
3486 bool IsUnresolved = isUnresolvedExceptionSpec(FPT->getExceptionSpecType());
3487 bool WasUnresolved =
3488 isUnresolvedExceptionSpec(PrevFPT->getExceptionSpecType());
3489 if (IsUnresolved != WasUnresolved)
3490 Reader.PendingExceptionSpecUpdates.insert(
3491 {Canon, IsUnresolved ? PrevFD : FD});
3493 // If we need to propagate a deduced return type along the redecl chain,
3494 // make a note of that so that we can do it later.
3495 bool IsUndeduced = isUndeducedReturnType(FPT->getReturnType());
3496 bool WasUndeduced = isUndeducedReturnType(PrevFPT->getReturnType());
3497 if (IsUndeduced != WasUndeduced)
3498 Reader.PendingDeducedTypeUpdates.insert(
3499 {cast<FunctionDecl>(Canon),
3500 (IsUndeduced ? PrevFPT : FPT)->getReturnType()});
3504 } // namespace clang
3506 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader, ...) {
3507 llvm_unreachable("attachPreviousDecl on non-redeclarable declaration");
3510 /// Inherit the default template argument from \p From to \p To. Returns
3511 /// \c false if there is no default template for \p From.
3512 template <typename ParmDecl>
3513 static bool inheritDefaultTemplateArgument(ASTContext &Context, ParmDecl *From,
3515 auto *To = cast<ParmDecl>(ToD);
3516 if (!From->hasDefaultArgument())
3518 To->setInheritedDefaultArgument(Context, From);
3522 static void inheritDefaultTemplateArguments(ASTContext &Context,
3525 auto *FromTP = From->getTemplateParameters();
3526 auto *ToTP = To->getTemplateParameters();
3527 assert(FromTP->size() == ToTP->size() && "merged mismatched templates?");
3529 for (unsigned I = 0, N = FromTP->size(); I != N; ++I) {
3530 NamedDecl *FromParam = FromTP->getParam(I);
3531 NamedDecl *ToParam = ToTP->getParam(I);
3533 if (auto *FTTP = dyn_cast<TemplateTypeParmDecl>(FromParam))
3534 inheritDefaultTemplateArgument(Context, FTTP, ToParam);
3535 else if (auto *FNTTP = dyn_cast<NonTypeTemplateParmDecl>(FromParam))
3536 inheritDefaultTemplateArgument(Context, FNTTP, ToParam);
3538 inheritDefaultTemplateArgument(
3539 Context, cast<TemplateTemplateParmDecl>(FromParam), ToParam);
3543 void ASTDeclReader::attachPreviousDecl(ASTReader &Reader, Decl *D,
3544 Decl *Previous, Decl *Canon) {
3545 assert(D && Previous);
3547 switch (D->getKind()) {
3548 #define ABSTRACT_DECL(TYPE)
3549 #define DECL(TYPE, BASE) \
3551 attachPreviousDeclImpl(Reader, cast<TYPE##Decl>(D), Previous, Canon); \
3553 #include "clang/AST/DeclNodes.inc"
3556 // If the declaration was visible in one module, a redeclaration of it in
3557 // another module remains visible even if it wouldn't be visible by itself.
3559 // FIXME: In this case, the declaration should only be visible if a module
3560 // that makes it visible has been imported.
3561 D->IdentifierNamespace |=
3562 Previous->IdentifierNamespace &
3563 (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
3565 // If the declaration declares a template, it may inherit default arguments
3566 // from the previous declaration.
3567 if (auto *TD = dyn_cast<TemplateDecl>(D))
3568 inheritDefaultTemplateArguments(Reader.getContext(),
3569 cast<TemplateDecl>(Previous), TD);
3572 template<typename DeclT>
3573 void ASTDeclReader::attachLatestDeclImpl(Redeclarable<DeclT> *D, Decl *Latest) {
3574 D->RedeclLink.setLatest(cast<DeclT>(Latest));
3577 void ASTDeclReader::attachLatestDeclImpl(...) {
3578 llvm_unreachable("attachLatestDecl on non-redeclarable declaration");
3581 void ASTDeclReader::attachLatestDecl(Decl *D, Decl *Latest) {
3582 assert(D && Latest);
3584 switch (D->getKind()) {
3585 #define ABSTRACT_DECL(TYPE)
3586 #define DECL(TYPE, BASE) \
3588 attachLatestDeclImpl(cast<TYPE##Decl>(D), Latest); \
3590 #include "clang/AST/DeclNodes.inc"
3594 template<typename DeclT>
3595 void ASTDeclReader::markIncompleteDeclChainImpl(Redeclarable<DeclT> *D) {
3596 D->RedeclLink.markIncomplete();
3599 void ASTDeclReader::markIncompleteDeclChainImpl(...) {
3600 llvm_unreachable("markIncompleteDeclChain on non-redeclarable declaration");
3603 void ASTReader::markIncompleteDeclChain(Decl *D) {
3604 switch (D->getKind()) {
3605 #define ABSTRACT_DECL(TYPE)
3606 #define DECL(TYPE, BASE) \
3608 ASTDeclReader::markIncompleteDeclChainImpl(cast<TYPE##Decl>(D)); \
3610 #include "clang/AST/DeclNodes.inc"
3614 /// Read the declaration at the given offset from the AST file.
3615 Decl *ASTReader::ReadDeclRecord(DeclID ID) {
3616 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
3617 SourceLocation DeclLoc;
3618 RecordLocation Loc = DeclCursorForID(ID, DeclLoc);
3619 llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
3620 // Keep track of where we are in the stream, then jump back there
3621 // after reading this declaration.
3622 SavedStreamPosition SavedPosition(DeclsCursor);
3624 ReadingKindTracker ReadingKind(Read_Decl, *this);
3626 // Note that we are loading a declaration record.
3627 Deserializing ADecl(this);
3629 DeclsCursor.JumpToBit(Loc.Offset);
3630 ASTRecordReader Record(*this, *Loc.F);
3631 ASTDeclReader Reader(*this, Record, Loc, ID, DeclLoc);
3632 unsigned Code = DeclsCursor.ReadCode();
3634 ASTContext &Context = getContext();
3636 switch ((DeclCode)Record.readRecord(DeclsCursor, Code)) {
3637 case DECL_CONTEXT_LEXICAL:
3638 case DECL_CONTEXT_VISIBLE:
3639 llvm_unreachable("Record cannot be de-serialized with ReadDeclRecord");
3641 D = TypedefDecl::CreateDeserialized(Context, ID);
3643 case DECL_TYPEALIAS:
3644 D = TypeAliasDecl::CreateDeserialized(Context, ID);
3647 D = EnumDecl::CreateDeserialized(Context, ID);
3650 D = RecordDecl::CreateDeserialized(Context, ID);
3652 case DECL_ENUM_CONSTANT:
3653 D = EnumConstantDecl::CreateDeserialized(Context, ID);
3656 D = FunctionDecl::CreateDeserialized(Context, ID);
3658 case DECL_LINKAGE_SPEC:
3659 D = LinkageSpecDecl::CreateDeserialized(Context, ID);
3662 D = ExportDecl::CreateDeserialized(Context, ID);
3665 D = LabelDecl::CreateDeserialized(Context, ID);
3667 case DECL_NAMESPACE:
3668 D = NamespaceDecl::CreateDeserialized(Context, ID);
3670 case DECL_NAMESPACE_ALIAS:
3671 D = NamespaceAliasDecl::CreateDeserialized(Context, ID);
3674 D = UsingDecl::CreateDeserialized(Context, ID);
3676 case DECL_USING_PACK:
3677 D = UsingPackDecl::CreateDeserialized(Context, ID, Record.readInt());
3679 case DECL_USING_SHADOW:
3680 D = UsingShadowDecl::CreateDeserialized(Context, ID);
3682 case DECL_CONSTRUCTOR_USING_SHADOW:
3683 D = ConstructorUsingShadowDecl::CreateDeserialized(Context, ID);
3685 case DECL_USING_DIRECTIVE:
3686 D = UsingDirectiveDecl::CreateDeserialized(Context, ID);
3688 case DECL_UNRESOLVED_USING_VALUE:
3689 D = UnresolvedUsingValueDecl::CreateDeserialized(Context, ID);
3691 case DECL_UNRESOLVED_USING_TYPENAME:
3692 D = UnresolvedUsingTypenameDecl::CreateDeserialized(Context, ID);
3694 case DECL_CXX_RECORD:
3695 D = CXXRecordDecl::CreateDeserialized(Context, ID);
3697 case DECL_CXX_DEDUCTION_GUIDE:
3698 D = CXXDeductionGuideDecl::CreateDeserialized(Context, ID);
3700 case DECL_CXX_METHOD:
3701 D = CXXMethodDecl::CreateDeserialized(Context, ID);
3703 case DECL_CXX_CONSTRUCTOR:
3704 D = CXXConstructorDecl::CreateDeserialized(Context, ID, false);
3706 case DECL_CXX_INHERITED_CONSTRUCTOR:
3707 D = CXXConstructorDecl::CreateDeserialized(Context, ID, true);
3709 case DECL_CXX_DESTRUCTOR:
3710 D = CXXDestructorDecl::CreateDeserialized(Context, ID);
3712 case DECL_CXX_CONVERSION:
3713 D = CXXConversionDecl::CreateDeserialized(Context, ID);
3715 case DECL_ACCESS_SPEC:
3716 D = AccessSpecDecl::CreateDeserialized(Context, ID);
3719 D = FriendDecl::CreateDeserialized(Context, ID, Record.readInt());
3721 case DECL_FRIEND_TEMPLATE:
3722 D = FriendTemplateDecl::CreateDeserialized(Context, ID);
3724 case DECL_CLASS_TEMPLATE:
3725 D = ClassTemplateDecl::CreateDeserialized(Context, ID);
3727 case DECL_CLASS_TEMPLATE_SPECIALIZATION:
3728 D = ClassTemplateSpecializationDecl::CreateDeserialized(Context, ID);
3730 case DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION:
3731 D = ClassTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
3733 case DECL_VAR_TEMPLATE:
3734 D = VarTemplateDecl::CreateDeserialized(Context, ID);
3736 case DECL_VAR_TEMPLATE_SPECIALIZATION:
3737 D = VarTemplateSpecializationDecl::CreateDeserialized(Context, ID);
3739 case DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION:
3740 D = VarTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
3742 case DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION:
3743 D = ClassScopeFunctionSpecializationDecl::CreateDeserialized(Context, ID);
3745 case DECL_FUNCTION_TEMPLATE:
3746 D = FunctionTemplateDecl::CreateDeserialized(Context, ID);
3748 case DECL_TEMPLATE_TYPE_PARM:
3749 D = TemplateTypeParmDecl::CreateDeserialized(Context, ID);
3751 case DECL_NON_TYPE_TEMPLATE_PARM:
3752 D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID);
3754 case DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK:
3755 D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID,
3758 case DECL_TEMPLATE_TEMPLATE_PARM:
3759 D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID);
3761 case DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK:
3762 D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID,
3765 case DECL_TYPE_ALIAS_TEMPLATE:
3766 D = TypeAliasTemplateDecl::CreateDeserialized(Context, ID);
3768 case DECL_STATIC_ASSERT:
3769 D = StaticAssertDecl::CreateDeserialized(Context, ID);
3771 case DECL_OBJC_METHOD:
3772 D = ObjCMethodDecl::CreateDeserialized(Context, ID);
3774 case DECL_OBJC_INTERFACE:
3775 D = ObjCInterfaceDecl::CreateDeserialized(Context, ID);
3777 case DECL_OBJC_IVAR:
3778 D = ObjCIvarDecl::CreateDeserialized(Context, ID);
3780 case DECL_OBJC_PROTOCOL:
3781 D = ObjCProtocolDecl::CreateDeserialized(Context, ID);
3783 case DECL_OBJC_AT_DEFS_FIELD:
3784 D = ObjCAtDefsFieldDecl::CreateDeserialized(Context, ID);
3786 case DECL_OBJC_CATEGORY:
3787 D = ObjCCategoryDecl::CreateDeserialized(Context, ID);
3789 case DECL_OBJC_CATEGORY_IMPL:
3790 D = ObjCCategoryImplDecl::CreateDeserialized(Context, ID);
3792 case DECL_OBJC_IMPLEMENTATION:
3793 D = ObjCImplementationDecl::CreateDeserialized(Context, ID);
3795 case DECL_OBJC_COMPATIBLE_ALIAS:
3796 D = ObjCCompatibleAliasDecl::CreateDeserialized(Context, ID);
3798 case DECL_OBJC_PROPERTY:
3799 D = ObjCPropertyDecl::CreateDeserialized(Context, ID);
3801 case DECL_OBJC_PROPERTY_IMPL:
3802 D = ObjCPropertyImplDecl::CreateDeserialized(Context, ID);
3805 D = FieldDecl::CreateDeserialized(Context, ID);
3807 case DECL_INDIRECTFIELD:
3808 D = IndirectFieldDecl::CreateDeserialized(Context, ID);
3811 D = VarDecl::CreateDeserialized(Context, ID);
3813 case DECL_IMPLICIT_PARAM:
3814 D = ImplicitParamDecl::CreateDeserialized(Context, ID);
3817 D = ParmVarDecl::CreateDeserialized(Context, ID);
3819 case DECL_DECOMPOSITION:
3820 D = DecompositionDecl::CreateDeserialized(Context, ID, Record.readInt());
3823 D = BindingDecl::CreateDeserialized(Context, ID);
3825 case DECL_FILE_SCOPE_ASM:
3826 D = FileScopeAsmDecl::CreateDeserialized(Context, ID);
3829 D = BlockDecl::CreateDeserialized(Context, ID);
3831 case DECL_MS_PROPERTY:
3832 D = MSPropertyDecl::CreateDeserialized(Context, ID);
3835 D = CapturedDecl::CreateDeserialized(Context, ID, Record.readInt());
3837 case DECL_CXX_BASE_SPECIFIERS:
3838 Error("attempt to read a C++ base-specifier record as a declaration");
3840 case DECL_CXX_CTOR_INITIALIZERS:
3841 Error("attempt to read a C++ ctor initializer record as a declaration");
3844 // Note: last entry of the ImportDecl record is the number of stored source
3846 D = ImportDecl::CreateDeserialized(Context, ID, Record.back());
3848 case DECL_OMP_THREADPRIVATE:
3849 D = OMPThreadPrivateDecl::CreateDeserialized(Context, ID, Record.readInt());
3851 case DECL_OMP_REQUIRES:
3852 D = OMPRequiresDecl::CreateDeserialized(Context, ID, Record.readInt());
3854 case DECL_OMP_DECLARE_REDUCTION:
3855 D = OMPDeclareReductionDecl::CreateDeserialized(Context, ID);
3857 case DECL_OMP_CAPTUREDEXPR:
3858 D = OMPCapturedExprDecl::CreateDeserialized(Context, ID);
3860 case DECL_PRAGMA_COMMENT:
3861 D = PragmaCommentDecl::CreateDeserialized(Context, ID, Record.readInt());
3863 case DECL_PRAGMA_DETECT_MISMATCH:
3864 D = PragmaDetectMismatchDecl::CreateDeserialized(Context, ID,
3868 D = EmptyDecl::CreateDeserialized(Context, ID);
3870 case DECL_OBJC_TYPE_PARAM:
3871 D = ObjCTypeParamDecl::CreateDeserialized(Context, ID);
3875 assert(D && "Unknown declaration reading AST file");
3876 LoadedDecl(Index, D);
3877 // Set the DeclContext before doing any deserialization, to make sure internal
3878 // calls to Decl::getASTContext() by Decl's methods will find the
3879 // TranslationUnitDecl without crashing.
3880 D->setDeclContext(Context.getTranslationUnitDecl());
3883 // If this declaration is also a declaration context, get the
3884 // offsets for its tables of lexical and visible declarations.
3885 if (auto *DC = dyn_cast<DeclContext>(D)) {
3886 std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
3887 if (Offsets.first &&
3888 ReadLexicalDeclContextStorage(*Loc.F, DeclsCursor, Offsets.first, DC))
3890 if (Offsets.second &&
3891 ReadVisibleDeclContextStorage(*Loc.F, DeclsCursor, Offsets.second, ID))
3894 assert(Record.getIdx() == Record.size());
3896 // Load any relevant update records.
3897 PendingUpdateRecords.push_back(
3898 PendingUpdateRecord(ID, D, /*JustLoaded=*/true));
3900 // Load the categories after recursive loading is finished.
3901 if (auto *Class = dyn_cast<ObjCInterfaceDecl>(D))
3902 // If we already have a definition when deserializing the ObjCInterfaceDecl,
3903 // we put the Decl in PendingDefinitions so we can pull the categories here.
3904 if (Class->isThisDeclarationADefinition() ||
3905 PendingDefinitions.count(Class))
3906 loadObjCCategories(ID, Class);
3908 // If we have deserialized a declaration that has a definition the
3909 // AST consumer might need to know about, queue it.
3910 // We don't pass it to the consumer immediately because we may be in recursive
3911 // loading, and some declarations may still be initializing.
3912 PotentiallyInterestingDecls.push_back(
3913 InterestingDecl(D, Reader.hasPendingBody()));
3918 void ASTReader::PassInterestingDeclsToConsumer() {
3921 if (PassingDeclsToConsumer)
3924 // Guard variable to avoid recursively redoing the process of passing
3925 // decls to consumer.
3926 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
3929 // Ensure that we've loaded all potentially-interesting declarations
3930 // that need to be eagerly loaded.
3931 for (auto ID : EagerlyDeserializedDecls)
3933 EagerlyDeserializedDecls.clear();
3935 while (!PotentiallyInterestingDecls.empty()) {
3936 InterestingDecl D = PotentiallyInterestingDecls.front();
3937 PotentiallyInterestingDecls.pop_front();
3938 if (isConsumerInterestedIn(getContext(), D.getDecl(), D.hasPendingBody()))
3939 PassInterestingDeclToConsumer(D.getDecl());
3943 void ASTReader::loadDeclUpdateRecords(PendingUpdateRecord &Record) {
3944 // The declaration may have been modified by files later in the chain.
3945 // If this is the case, read the record containing the updates from each file
3946 // and pass it to ASTDeclReader to make the modifications.
3947 serialization::GlobalDeclID ID = Record.ID;
3949 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
3950 DeclUpdateOffsetsMap::iterator UpdI = DeclUpdateOffsets.find(ID);
3952 SmallVector<serialization::DeclID, 8> PendingLazySpecializationIDs;
3954 if (UpdI != DeclUpdateOffsets.end()) {
3955 auto UpdateOffsets = std::move(UpdI->second);
3956 DeclUpdateOffsets.erase(UpdI);
3958 // Check if this decl was interesting to the consumer. If we just loaded
3959 // the declaration, then we know it was interesting and we skip the call
3960 // to isConsumerInterestedIn because it is unsafe to call in the
3961 // current ASTReader state.
3962 bool WasInteresting =
3963 Record.JustLoaded || isConsumerInterestedIn(getContext(), D, false);
3964 for (auto &FileAndOffset : UpdateOffsets) {
3965 ModuleFile *F = FileAndOffset.first;
3966 uint64_t Offset = FileAndOffset.second;
3967 llvm::BitstreamCursor &Cursor = F->DeclsCursor;
3968 SavedStreamPosition SavedPosition(Cursor);
3969 Cursor.JumpToBit(Offset);
3970 unsigned Code = Cursor.ReadCode();
3971 ASTRecordReader Record(*this, *F);
3972 unsigned RecCode = Record.readRecord(Cursor, Code);
3974 assert(RecCode == DECL_UPDATES && "Expected DECL_UPDATES record!");
3976 ASTDeclReader Reader(*this, Record, RecordLocation(F, Offset), ID,
3978 Reader.UpdateDecl(D, PendingLazySpecializationIDs);
3980 // We might have made this declaration interesting. If so, remember that
3981 // we need to hand it off to the consumer.
3982 if (!WasInteresting &&
3983 isConsumerInterestedIn(getContext(), D, Reader.hasPendingBody())) {
3984 PotentiallyInterestingDecls.push_back(
3985 InterestingDecl(D, Reader.hasPendingBody()));
3986 WasInteresting = true;
3990 // Add the lazy specializations to the template.
3991 assert((PendingLazySpecializationIDs.empty() || isa<ClassTemplateDecl>(D) ||
3992 isa<FunctionTemplateDecl>(D) || isa<VarTemplateDecl>(D)) &&
3993 "Must not have pending specializations");
3994 if (auto *CTD = dyn_cast<ClassTemplateDecl>(D))
3995 ASTDeclReader::AddLazySpecializations(CTD, PendingLazySpecializationIDs);
3996 else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
3997 ASTDeclReader::AddLazySpecializations(FTD, PendingLazySpecializationIDs);
3998 else if (auto *VTD = dyn_cast<VarTemplateDecl>(D))
3999 ASTDeclReader::AddLazySpecializations(VTD, PendingLazySpecializationIDs);
4000 PendingLazySpecializationIDs.clear();
4002 // Load the pending visible updates for this decl context, if it has any.
4003 auto I = PendingVisibleUpdates.find(ID);
4004 if (I != PendingVisibleUpdates.end()) {
4005 auto VisibleUpdates = std::move(I->second);
4006 PendingVisibleUpdates.erase(I);
4008 auto *DC = cast<DeclContext>(D)->getPrimaryContext();
4009 for (const auto &Update : VisibleUpdates)
4010 Lookups[DC].Table.add(
4011 Update.Mod, Update.Data,
4012 reader::ASTDeclContextNameLookupTrait(*this, *Update.Mod));
4013 DC->setHasExternalVisibleStorage(true);
4017 void ASTReader::loadPendingDeclChain(Decl *FirstLocal, uint64_t LocalOffset) {
4018 // Attach FirstLocal to the end of the decl chain.
4019 Decl *CanonDecl = FirstLocal->getCanonicalDecl();
4020 if (FirstLocal != CanonDecl) {
4021 Decl *PrevMostRecent = ASTDeclReader::getMostRecentDecl(CanonDecl);
4022 ASTDeclReader::attachPreviousDecl(
4023 *this, FirstLocal, PrevMostRecent ? PrevMostRecent : CanonDecl,
4028 ASTDeclReader::attachLatestDecl(CanonDecl, FirstLocal);
4032 // Load the list of other redeclarations from this module file.
4033 ModuleFile *M = getOwningModuleFile(FirstLocal);
4034 assert(M && "imported decl from no module file");
4036 llvm::BitstreamCursor &Cursor = M->DeclsCursor;
4037 SavedStreamPosition SavedPosition(Cursor);
4038 Cursor.JumpToBit(LocalOffset);
4041 unsigned Code = Cursor.ReadCode();
4042 unsigned RecCode = Cursor.readRecord(Code, Record);
4044 assert(RecCode == LOCAL_REDECLARATIONS && "expected LOCAL_REDECLARATIONS record!");
4046 // FIXME: We have several different dispatches on decl kind here; maybe
4047 // we should instead generate one loop per kind and dispatch up-front?
4048 Decl *MostRecent = FirstLocal;
4049 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
4050 auto *D = GetLocalDecl(*M, Record[N - I - 1]);
4051 ASTDeclReader::attachPreviousDecl(*this, D, MostRecent, CanonDecl);
4054 ASTDeclReader::attachLatestDecl(CanonDecl, MostRecent);
4059 /// Given an ObjC interface, goes through the modules and links to the
4060 /// interface all the categories for it.
4061 class ObjCCategoriesVisitor {
4063 ObjCInterfaceDecl *Interface;
4064 llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized;
4065 ObjCCategoryDecl *Tail = nullptr;
4066 llvm::DenseMap<DeclarationName, ObjCCategoryDecl *> NameCategoryMap;
4067 serialization::GlobalDeclID InterfaceID;
4068 unsigned PreviousGeneration;
4070 void add(ObjCCategoryDecl *Cat) {
4071 // Only process each category once.
4072 if (!Deserialized.erase(Cat))
4075 // Check for duplicate categories.
4076 if (Cat->getDeclName()) {
4077 ObjCCategoryDecl *&Existing = NameCategoryMap[Cat->getDeclName()];
4079 Reader.getOwningModuleFile(Existing)
4080 != Reader.getOwningModuleFile(Cat)) {
4081 // FIXME: We should not warn for duplicates in diamond:
4089 // If there are duplicates in ML/MR, there will be warning when
4090 // creating MB *and* when importing MB. We should not warn when
4092 Reader.Diag(Cat->getLocation(), diag::warn_dup_category_def)
4093 << Interface->getDeclName() << Cat->getDeclName();
4094 Reader.Diag(Existing->getLocation(), diag::note_previous_definition);
4095 } else if (!Existing) {
4096 // Record this category.
4101 // Add this category to the end of the chain.
4103 ASTDeclReader::setNextObjCCategory(Tail, Cat);
4105 Interface->setCategoryListRaw(Cat);
4110 ObjCCategoriesVisitor(ASTReader &Reader,
4111 ObjCInterfaceDecl *Interface,
4112 llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized,
4113 serialization::GlobalDeclID InterfaceID,
4114 unsigned PreviousGeneration)
4115 : Reader(Reader), Interface(Interface), Deserialized(Deserialized),
4116 InterfaceID(InterfaceID), PreviousGeneration(PreviousGeneration) {
4117 // Populate the name -> category map with the set of known categories.
4118 for (auto *Cat : Interface->known_categories()) {
4119 if (Cat->getDeclName())
4120 NameCategoryMap[Cat->getDeclName()] = Cat;
4122 // Keep track of the tail of the category list.
4127 bool operator()(ModuleFile &M) {
4128 // If we've loaded all of the category information we care about from
4129 // this module file, we're done.
4130 if (M.Generation <= PreviousGeneration)
4133 // Map global ID of the definition down to the local ID used in this
4134 // module file. If there is no such mapping, we'll find nothing here
4135 // (or in any module it imports).
4136 DeclID LocalID = Reader.mapGlobalIDToModuleFileGlobalID(M, InterfaceID);
4140 // Perform a binary search to find the local redeclarations for this
4141 // declaration (if any).
4142 const ObjCCategoriesInfo Compare = { LocalID, 0 };
4143 const ObjCCategoriesInfo *Result
4144 = std::lower_bound(M.ObjCCategoriesMap,
4145 M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap,
4147 if (Result == M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap ||
4148 Result->DefinitionID != LocalID) {
4149 // We didn't find anything. If the class definition is in this module
4150 // file, then the module files it depends on cannot have any categories,
4151 // so suppress further lookup.
4152 return Reader.isDeclIDFromModule(InterfaceID, M);
4155 // We found something. Dig out all of the categories.
4156 unsigned Offset = Result->Offset;
4157 unsigned N = M.ObjCCategories[Offset];
4158 M.ObjCCategories[Offset++] = 0; // Don't try to deserialize again
4159 for (unsigned I = 0; I != N; ++I)
4160 add(cast_or_null<ObjCCategoryDecl>(
4161 Reader.GetLocalDecl(M, M.ObjCCategories[Offset++])));
4168 void ASTReader::loadObjCCategories(serialization::GlobalDeclID ID,
4169 ObjCInterfaceDecl *D,
4170 unsigned PreviousGeneration) {
4171 ObjCCategoriesVisitor Visitor(*this, D, CategoriesDeserialized, ID,
4172 PreviousGeneration);
4173 ModuleMgr.visit(Visitor);
4176 template<typename DeclT, typename Fn>
4177 static void forAllLaterRedecls(DeclT *D, Fn F) {
4180 // Check whether we've already merged D into its redeclaration chain.
4181 // MostRecent may or may not be nullptr if D has not been merged. If
4182 // not, walk the merged redecl chain and see if it's there.
4183 auto *MostRecent = D->getMostRecentDecl();
4185 for (auto *Redecl = MostRecent; Redecl && !Found;
4186 Redecl = Redecl->getPreviousDecl())
4187 Found = (Redecl == D);
4189 // If this declaration is merged, apply the functor to all later decls.
4191 for (auto *Redecl = MostRecent; Redecl != D;
4192 Redecl = Redecl->getPreviousDecl())
4197 void ASTDeclReader::UpdateDecl(Decl *D,
4198 llvm::SmallVectorImpl<serialization::DeclID> &PendingLazySpecializationIDs) {
4199 while (Record.getIdx() < Record.size()) {
4200 switch ((DeclUpdateKind)Record.readInt()) {
4201 case UPD_CXX_ADDED_IMPLICIT_MEMBER: {
4202 auto *RD = cast<CXXRecordDecl>(D);
4203 // FIXME: If we also have an update record for instantiating the
4204 // definition of D, we need that to happen before we get here.
4205 Decl *MD = Record.readDecl();
4206 assert(MD && "couldn't read decl from update record");
4207 // FIXME: We should call addHiddenDecl instead, to add the member
4208 // to its DeclContext.
4209 RD->addedMember(MD);
4213 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
4214 // It will be added to the template's lazy specialization set.
4215 PendingLazySpecializationIDs.push_back(ReadDeclID());
4218 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: {
4219 auto *Anon = ReadDeclAs<NamespaceDecl>();
4221 // Each module has its own anonymous namespace, which is disjoint from
4222 // any other module's anonymous namespaces, so don't attach the anonymous
4223 // namespace at all.
4224 if (!Record.isModule()) {
4225 if (auto *TU = dyn_cast<TranslationUnitDecl>(D))
4226 TU->setAnonymousNamespace(Anon);
4228 cast<NamespaceDecl>(D)->setAnonymousNamespace(Anon);
4233 case UPD_CXX_ADDED_VAR_DEFINITION: {
4234 auto *VD = cast<VarDecl>(D);
4235 VD->NonParmVarDeclBits.IsInline = Record.readInt();
4236 VD->NonParmVarDeclBits.IsInlineSpecified = Record.readInt();
4237 uint64_t Val = Record.readInt();
4238 if (Val && !VD->getInit()) {
4239 VD->setInit(Record.readExpr());
4240 if (Val > 1) { // IsInitKnownICE = 1, IsInitNotICE = 2, IsInitICE = 3
4241 EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
4242 Eval->CheckedICE = true;
4243 Eval->IsICE = Val == 3;
4249 case UPD_CXX_POINT_OF_INSTANTIATION: {
4250 SourceLocation POI = Record.readSourceLocation();
4251 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) {
4252 VTSD->setPointOfInstantiation(POI);
4253 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
4254 VD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
4256 auto *FD = cast<FunctionDecl>(D);
4257 if (auto *FTSInfo = FD->TemplateOrSpecialization
4258 .dyn_cast<FunctionTemplateSpecializationInfo *>())
4259 FTSInfo->setPointOfInstantiation(POI);
4261 FD->TemplateOrSpecialization.get<MemberSpecializationInfo *>()
4262 ->setPointOfInstantiation(POI);
4267 case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT: {
4268 auto *Param = cast<ParmVarDecl>(D);
4270 // We have to read the default argument regardless of whether we use it
4271 // so that hypothetical further update records aren't messed up.
4272 // TODO: Add a function to skip over the next expr record.
4273 auto *DefaultArg = Record.readExpr();
4275 // Only apply the update if the parameter still has an uninstantiated
4276 // default argument.
4277 if (Param->hasUninstantiatedDefaultArg())
4278 Param->setDefaultArg(DefaultArg);
4282 case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER: {
4283 auto *FD = cast<FieldDecl>(D);
4284 auto *DefaultInit = Record.readExpr();
4286 // Only apply the update if the field still has an uninstantiated
4287 // default member initializer.
4288 if (FD->hasInClassInitializer() && !FD->getInClassInitializer()) {
4290 FD->setInClassInitializer(DefaultInit);
4292 // Instantiation failed. We can get here if we serialized an AST for
4293 // an invalid program.
4294 FD->removeInClassInitializer();
4299 case UPD_CXX_ADDED_FUNCTION_DEFINITION: {
4300 auto *FD = cast<FunctionDecl>(D);
4301 if (Reader.PendingBodies[FD]) {
4302 // FIXME: Maybe check for ODR violations.
4303 // It's safe to stop now because this update record is always last.
4307 if (Record.readInt()) {
4308 // Maintain AST consistency: any later redeclarations of this function
4309 // are inline if this one is. (We might have merged another declaration
4311 forAllLaterRedecls(FD, [](FunctionDecl *FD) {
4312 FD->setImplicitlyInline();
4315 FD->setInnerLocStart(ReadSourceLocation());
4316 ReadFunctionDefinition(FD);
4317 assert(Record.getIdx() == Record.size() && "lazy body must be last");
4321 case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
4322 auto *RD = cast<CXXRecordDecl>(D);
4323 auto *OldDD = RD->getCanonicalDecl()->DefinitionData;
4324 bool HadRealDefinition =
4325 OldDD && (OldDD->Definition != RD ||
4326 !Reader.PendingFakeDefinitionData.count(OldDD));
4327 RD->setParamDestroyedInCallee(Record.readInt());
4328 RD->setArgPassingRestrictions(
4329 (RecordDecl::ArgPassingKind)Record.readInt());
4330 ReadCXXRecordDefinition(RD, /*Update*/true);
4332 // Visible update is handled separately.
4333 uint64_t LexicalOffset = ReadLocalOffset();
4334 if (!HadRealDefinition && LexicalOffset) {
4335 Record.readLexicalDeclContextStorage(LexicalOffset, RD);
4336 Reader.PendingFakeDefinitionData.erase(OldDD);
4339 auto TSK = (TemplateSpecializationKind)Record.readInt();
4340 SourceLocation POI = ReadSourceLocation();
4341 if (MemberSpecializationInfo *MSInfo =
4342 RD->getMemberSpecializationInfo()) {
4343 MSInfo->setTemplateSpecializationKind(TSK);
4344 MSInfo->setPointOfInstantiation(POI);
4346 auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
4347 Spec->setTemplateSpecializationKind(TSK);
4348 Spec->setPointOfInstantiation(POI);
4350 if (Record.readInt()) {
4352 ReadDeclAs<ClassTemplatePartialSpecializationDecl>();
4353 SmallVector<TemplateArgument, 8> TemplArgs;
4354 Record.readTemplateArgumentList(TemplArgs);
4355 auto *TemplArgList = TemplateArgumentList::CreateCopy(
4356 Reader.getContext(), TemplArgs);
4358 // FIXME: If we already have a partial specialization set,
4359 // check that it matches.
4360 if (!Spec->getSpecializedTemplateOrPartial()
4361 .is<ClassTemplatePartialSpecializationDecl *>())
4362 Spec->setInstantiationOf(PartialSpec, TemplArgList);
4366 RD->setTagKind((TagTypeKind)Record.readInt());
4367 RD->setLocation(ReadSourceLocation());
4368 RD->setLocStart(ReadSourceLocation());
4369 RD->setBraceRange(ReadSourceRange());
4371 if (Record.readInt()) {
4373 Record.readAttributes(Attrs);
4374 // If the declaration already has attributes, we assume that some other
4375 // AST file already loaded them.
4377 D->setAttrsImpl(Attrs, Reader.getContext());
4382 case UPD_CXX_RESOLVED_DTOR_DELETE: {
4383 // Set the 'operator delete' directly to avoid emitting another update
4385 auto *Del = ReadDeclAs<FunctionDecl>();
4386 auto *First = cast<CXXDestructorDecl>(D->getCanonicalDecl());
4387 auto *ThisArg = Record.readExpr();
4388 // FIXME: Check consistency if we have an old and new operator delete.
4389 if (!First->OperatorDelete) {
4390 First->OperatorDelete = Del;
4391 First->OperatorDeleteThisArg = ThisArg;
4396 case UPD_CXX_RESOLVED_EXCEPTION_SPEC: {
4397 FunctionProtoType::ExceptionSpecInfo ESI;
4398 SmallVector<QualType, 8> ExceptionStorage;
4399 Record.readExceptionSpec(ExceptionStorage, ESI);
4401 // Update this declaration's exception specification, if needed.
4402 auto *FD = cast<FunctionDecl>(D);
4403 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
4404 // FIXME: If the exception specification is already present, check that it
4406 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
4407 FD->setType(Reader.getContext().getFunctionType(
4408 FPT->getReturnType(), FPT->getParamTypes(),
4409 FPT->getExtProtoInfo().withExceptionSpec(ESI)));
4411 // When we get to the end of deserializing, see if there are other decls
4412 // that we need to propagate this exception specification onto.
4413 Reader.PendingExceptionSpecUpdates.insert(
4414 std::make_pair(FD->getCanonicalDecl(), FD));
4419 case UPD_CXX_DEDUCED_RETURN_TYPE: {
4420 auto *FD = cast<FunctionDecl>(D);
4421 QualType DeducedResultType = Record.readType();
4422 Reader.PendingDeducedTypeUpdates.insert(
4423 {FD->getCanonicalDecl(), DeducedResultType});
4427 case UPD_DECL_MARKED_USED:
4428 // Maintain AST consistency: any later redeclarations are used too.
4429 D->markUsed(Reader.getContext());
4432 case UPD_MANGLING_NUMBER:
4433 Reader.getContext().setManglingNumber(cast<NamedDecl>(D),
4437 case UPD_STATIC_LOCAL_NUMBER:
4438 Reader.getContext().setStaticLocalNumber(cast<VarDecl>(D),
4442 case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
4443 D->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(Reader.getContext(),
4444 ReadSourceRange()));
4447 case UPD_DECL_EXPORTED: {
4448 unsigned SubmoduleID = readSubmoduleID();
4449 auto *Exported = cast<NamedDecl>(D);
4450 Module *Owner = SubmoduleID ? Reader.getSubmodule(SubmoduleID) : nullptr;
4451 Reader.getContext().mergeDefinitionIntoModule(Exported, Owner);
4452 Reader.PendingMergedDefinitionsToDeduplicate.insert(Exported);
4456 case UPD_DECL_MARKED_OPENMP_DECLARETARGET:
4457 D->addAttr(OMPDeclareTargetDeclAttr::CreateImplicit(
4458 Reader.getContext(),
4459 static_cast<OMPDeclareTargetDeclAttr::MapTypeTy>(Record.readInt()),
4460 ReadSourceRange()));
4463 case UPD_ADDED_ATTR_TO_RECORD:
4465 Record.readAttributes(Attrs);
4466 assert(Attrs.size() == 1);
4467 D->addAttr(Attrs[0]);