Skip to content

Commit 64b8514

Browse files
ChuanqiXu9tru
authored andcommitted
Reland [C++20] [Modules] [Itanium ABI] Generate the vtable in the mod… (#102287)
Reland #75912 The differences of this PR between #75912 are: - Fixed a regression in `Decl::isInAnotherModuleUnit()` in DeclBase.cpp pointed by @mizvekov and add the corresponding test. - Fixed the regression in windows #97447. The changes are in `CodeGenModule::getVTableLinkage` from `clang/lib/CodeGen/CGVTables.cpp`. According to the feedbacks from MSVC devs, the linkage of vtables won't affected by modules. So I simply skipped the case for MSVC. Given this is more or less fundamental to the use of modules. I hope we can backport this to 19.x. (cherry picked from commit 847f9cb)
1 parent 3ffa542 commit 64b8514

19 files changed

+374
-55
lines changed

clang/include/clang/AST/DeclBase.h

+7
Original file line numberDiff line numberDiff line change
@@ -670,6 +670,13 @@ class alignas(8) Decl {
670670
/// Whether this declaration comes from another module unit.
671671
bool isInAnotherModuleUnit() const;
672672

673+
/// Whether this declaration comes from the same module unit being compiled.
674+
bool isInCurrentModuleUnit() const;
675+
676+
/// Whether the definition of the declaration should be emitted in external
677+
/// sources.
678+
bool shouldEmitInExternalSource() const;
679+
673680
/// Whether this declaration comes from explicit global module.
674681
bool isFromExplicitGlobalModule() const;
675682

clang/include/clang/Serialization/ASTBitCodes.h

+3
Original file line numberDiff line numberDiff line change
@@ -721,6 +721,9 @@ enum ASTRecordTypes {
721721

722722
/// Record code for \#pragma clang unsafe_buffer_usage begin/end
723723
PP_UNSAFE_BUFFER_USAGE = 69,
724+
725+
/// Record code for vtables to emit.
726+
VTABLES_TO_EMIT = 70,
724727
};
725728

726729
/// Record types used within a source manager block.

clang/include/clang/Serialization/ASTReader.h

+6
Original file line numberDiff line numberDiff line change
@@ -790,6 +790,11 @@ class ASTReader
790790
/// the consumer eagerly.
791791
SmallVector<GlobalDeclID, 16> EagerlyDeserializedDecls;
792792

793+
/// The IDs of all vtables to emit. The referenced declarations are passed
794+
/// to the consumers' HandleVTable eagerly after passing
795+
/// EagerlyDeserializedDecls.
796+
SmallVector<GlobalDeclID, 16> VTablesToEmit;
797+
793798
/// The IDs of all tentative definitions stored in the chain.
794799
///
795800
/// Sema keeps track of all tentative definitions in a TU because it has to
@@ -1500,6 +1505,7 @@ class ASTReader
15001505
bool isConsumerInterestedIn(Decl *D);
15011506
void PassInterestingDeclsToConsumer();
15021507
void PassInterestingDeclToConsumer(Decl *D);
1508+
void PassVTableToConsumer(CXXRecordDecl *RD);
15031509

15041510
void finishPendingActions();
15051511
void diagnoseOdrViolations();

clang/include/clang/Serialization/ASTWriter.h

+7
Original file line numberDiff line numberDiff line change
@@ -500,6 +500,10 @@ class ASTWriter : public ASTDeserializationListener,
500500
std::vector<SourceRange> NonAffectingRanges;
501501
std::vector<SourceLocation::UIntTy> NonAffectingOffsetAdjustments;
502502

503+
/// A list of classes which need to emit the VTable in the corresponding
504+
/// object file.
505+
llvm::SmallVector<CXXRecordDecl *> PendingEmittingVTables;
506+
503507
/// Computes input files that didn't affect compilation of the current module,
504508
/// and initializes data structures necessary for leaving those files out
505509
/// during \c SourceManager serialization.
@@ -857,6 +861,8 @@ class ASTWriter : public ASTDeserializationListener,
857861
return PredefinedDecls.count(D);
858862
}
859863

864+
void handleVTable(CXXRecordDecl *RD);
865+
860866
private:
861867
// ASTDeserializationListener implementation
862868
void ReaderInitialized(ASTReader *Reader) override;
@@ -951,6 +957,7 @@ class PCHGenerator : public SemaConsumer {
951957

952958
void InitializeSema(Sema &S) override { SemaPtr = &S; }
953959
void HandleTranslationUnit(ASTContext &Ctx) override;
960+
void HandleVTable(CXXRecordDecl *RD) override { Writer.handleVTable(RD); }
954961
ASTMutationListener *GetASTMutationListener() override;
955962
ASTDeserializationListener *GetASTDeserializationListener() override;
956963
bool hasEmittedPCH() const { return Buffer->IsComplete; }

clang/lib/AST/ASTContext.cpp

+1-2
Original file line numberDiff line numberDiff line change
@@ -12405,8 +12405,7 @@ bool ASTContext::DeclMustBeEmitted(const Decl *D) {
1240512405
!isMSStaticDataMemberInlineDefinition(VD))
1240612406
return false;
1240712407

12408-
// Variables in other module units shouldn't be forced to be emitted.
12409-
if (VD->isInAnotherModuleUnit())
12408+
if (VD->shouldEmitInExternalSource())
1241012409
return false;
1241112410

1241212411
// Variables that can be needed in other TUs are required.

clang/lib/AST/DeclBase.cpp

+25-9
Original file line numberDiff line numberDiff line change
@@ -1125,20 +1125,36 @@ bool Decl::isInAnotherModuleUnit() const {
11251125
if (!M)
11261126
return false;
11271127

1128+
// FIXME or NOTE: maybe we need to be clear about the semantics
1129+
// of clang header modules. e.g., if this lives in a clang header
1130+
// module included by the current unit, should we return false
1131+
// here?
1132+
//
1133+
// This is clear for header units as the specification says the
1134+
// header units live in a synthesised translation unit. So we
1135+
// can return false here.
11281136
M = M->getTopLevelModule();
1129-
// FIXME: It is problematic if the header module lives in another module
1130-
// unit. Consider to fix this by techniques like
1131-
// ExternalASTSource::hasExternalDefinitions.
1132-
if (M->isHeaderLikeModule())
1137+
if (!M->isNamedModule())
11331138
return false;
11341139

1135-
// A global module without parent implies that we're parsing the global
1136-
// module. So it can't be in another module unit.
1137-
if (M->isGlobalModule())
1140+
return M != getASTContext().getCurrentNamedModule();
1141+
}
1142+
1143+
bool Decl::isInCurrentModuleUnit() const {
1144+
auto *M = getOwningModule();
1145+
1146+
if (!M || !M->isNamedModule())
11381147
return false;
11391148

1140-
assert(M->isNamedModule() && "New module kind?");
1141-
return M != getASTContext().getCurrentNamedModule();
1149+
return M == getASTContext().getCurrentNamedModule();
1150+
}
1151+
1152+
bool Decl::shouldEmitInExternalSource() const {
1153+
ExternalASTSource *Source = getASTContext().getExternalSource();
1154+
if (!Source)
1155+
return false;
1156+
1157+
return Source->hasExternalDefinitions(this) == ExternalASTSource::EK_Always;
11421158
}
11431159

11441160
bool Decl::isFromExplicitGlobalModule() const {

clang/lib/CodeGen/CGVTables.cpp

+33-23
Original file line numberDiff line numberDiff line change
@@ -1078,29 +1078,41 @@ llvm::GlobalVariable::LinkageTypes
10781078
CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
10791079
if (!RD->isExternallyVisible())
10801080
return llvm::GlobalVariable::InternalLinkage;
1081-
1082-
// We're at the end of the translation unit, so the current key
1083-
// function is fully correct.
1084-
const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD);
1085-
if (keyFunction && !RD->hasAttr<DLLImportAttr>()) {
1081+
1082+
// In windows, the linkage of vtable is not related to modules.
1083+
bool IsInNamedModule = !getTarget().getCXXABI().isMicrosoft() &&
1084+
RD->isInNamedModule();
1085+
// If the CXXRecordDecl is not in a module unit, we need to get
1086+
// its key function. We're at the end of the translation unit, so the current
1087+
// key function is fully correct.
1088+
const CXXMethodDecl *keyFunction =
1089+
IsInNamedModule ? nullptr : Context.getCurrentKeyFunction(RD);
1090+
if (IsInNamedModule || (keyFunction && !RD->hasAttr<DLLImportAttr>())) {
10861091
// If this class has a key function, use that to determine the
10871092
// linkage of the vtable.
10881093
const FunctionDecl *def = nullptr;
1089-
if (keyFunction->hasBody(def))
1094+
if (keyFunction && keyFunction->hasBody(def))
10901095
keyFunction = cast<CXXMethodDecl>(def);
10911096

1092-
switch (keyFunction->getTemplateSpecializationKind()) {
1093-
case TSK_Undeclared:
1094-
case TSK_ExplicitSpecialization:
1097+
bool IsExternalDefinition =
1098+
IsInNamedModule ? RD->shouldEmitInExternalSource() : !def;
1099+
1100+
TemplateSpecializationKind Kind =
1101+
IsInNamedModule ? RD->getTemplateSpecializationKind()
1102+
: keyFunction->getTemplateSpecializationKind();
1103+
1104+
switch (Kind) {
1105+
case TSK_Undeclared:
1106+
case TSK_ExplicitSpecialization:
10951107
assert(
1096-
(def || CodeGenOpts.OptimizationLevel > 0 ||
1108+
(IsInNamedModule || def || CodeGenOpts.OptimizationLevel > 0 ||
10971109
CodeGenOpts.getDebugInfo() != llvm::codegenoptions::NoDebugInfo) &&
1098-
"Shouldn't query vtable linkage without key function, "
1099-
"optimizations, or debug info");
1100-
if (!def && CodeGenOpts.OptimizationLevel > 0)
1110+
"Shouldn't query vtable linkage without the class in module units, "
1111+
"key function, optimizations, or debug info");
1112+
if (IsExternalDefinition && CodeGenOpts.OptimizationLevel > 0)
11011113
return llvm::GlobalVariable::AvailableExternallyLinkage;
11021114

1103-
if (keyFunction->isInlined())
1115+
if (keyFunction && keyFunction->isInlined())
11041116
return !Context.getLangOpts().AppleKext
11051117
? llvm::GlobalVariable::LinkOnceODRLinkage
11061118
: llvm::Function::InternalLinkage;
@@ -1119,7 +1131,7 @@ CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
11191131

11201132
case TSK_ExplicitInstantiationDeclaration:
11211133
llvm_unreachable("Should not have been asked to emit this");
1122-
}
1134+
}
11231135
}
11241136

11251137
// -fapple-kext mode does not support weak linkage, so we must use
@@ -1213,22 +1225,20 @@ bool CodeGenVTables::isVTableExternal(const CXXRecordDecl *RD) {
12131225
TSK == TSK_ExplicitInstantiationDefinition)
12141226
return false;
12151227

1228+
// Otherwise, if the class is attached to a module, the tables are uniquely
1229+
// emitted in the object for the module unit in which it is defined.
1230+
if (RD->isInNamedModule())
1231+
return RD->shouldEmitInExternalSource();
1232+
12161233
// Otherwise, if the class doesn't have a key function (possibly
12171234
// anymore), the vtable must be defined here.
12181235
const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
12191236
if (!keyFunction)
12201237
return false;
12211238

1222-
const FunctionDecl *Def;
12231239
// Otherwise, if we don't have a definition of the key function, the
12241240
// vtable must be defined somewhere else.
1225-
if (!keyFunction->hasBody(Def))
1226-
return true;
1227-
1228-
assert(Def && "The body of the key function is not assigned to Def?");
1229-
// If the non-inline key function comes from another module unit, the vtable
1230-
// must be defined there.
1231-
return Def->isInAnotherModuleUnit() && !Def->isInlineSpecified();
1241+
return !keyFunction->hasBody();
12321242
}
12331243

12341244
/// Given that we're currently at the end of the translation unit, and

clang/lib/CodeGen/ItaniumCXXABI.cpp

+3
Original file line numberDiff line numberDiff line change
@@ -2315,6 +2315,9 @@ bool ItaniumCXXABI::canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const {
23152315
if (!canSpeculativelyEmitVTableAsBaseClass(RD))
23162316
return false;
23172317

2318+
if (RD->shouldEmitInExternalSource())
2319+
return false;
2320+
23182321
// For a complete-object vtable (or more specifically, for the VTT), we need
23192322
// to be able to speculatively emit the vtables of all dynamic virtual bases.
23202323
for (const auto &B : RD->vbases()) {

clang/lib/Sema/SemaDecl.cpp

+9
Original file line numberDiff line numberDiff line change
@@ -18073,6 +18073,15 @@ void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
1807318073
if (NumInitMethods > 1 || !Def->hasInitMethod())
1807418074
Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
1807518075
}
18076+
18077+
// If we're defining a dynamic class in a module interface unit, we always
18078+
// need to produce the vtable for it, even if the vtable is not used in the
18079+
// current TU.
18080+
//
18081+
// The case where the current class is not dynamic is handled in
18082+
// MarkVTableUsed.
18083+
if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition())
18084+
MarkVTableUsed(RD->getLocation(), RD, /*DefinitionRequired=*/true);
1807618085
}
1807718086

1807818087
// Exit this scope of this tag's definition.

clang/lib/Sema/SemaDeclCXX.cpp

+9-5
Original file line numberDiff line numberDiff line change
@@ -18517,11 +18517,15 @@ bool Sema::DefineUsedVTables() {
1851718517

1851818518
bool DefineVTable = true;
1851918519

18520-
// If this class has a key function, but that key function is
18521-
// defined in another translation unit, we don't need to emit the
18522-
// vtable even though we're using it.
1852318520
const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
18524-
if (KeyFunction && !KeyFunction->hasBody()) {
18521+
// V-tables for non-template classes with an owning module are always
18522+
// uniquely emitted in that module.
18523+
if (Class->isInCurrentModuleUnit()) {
18524+
DefineVTable = true;
18525+
} else if (KeyFunction && !KeyFunction->hasBody()) {
18526+
// If this class has a key function, but that key function is
18527+
// defined in another translation unit, we don't need to emit the
18528+
// vtable even though we're using it.
1852518529
// The key function is in another translation unit.
1852618530
DefineVTable = false;
1852718531
TemplateSpecializationKind TSK =
@@ -18566,7 +18570,7 @@ bool Sema::DefineUsedVTables() {
1856618570
DefinedAnything = true;
1856718571
MarkVirtualMembersReferenced(Loc, Class);
1856818572
CXXRecordDecl *Canonical = Class->getCanonicalDecl();
18569-
if (VTablesUsed[Canonical])
18573+
if (VTablesUsed[Canonical] && !Class->shouldEmitInExternalSource())
1857018574
Consumer.HandleVTable(Class);
1857118575

1857218576
// Warn if we're emitting a weak vtable. The vtable will be weak if there is

clang/lib/Serialization/ASTReader.cpp

+11
Original file line numberDiff line numberDiff line change
@@ -3921,6 +3921,13 @@ llvm::Error ASTReader::ReadASTBlock(ModuleFile &F,
39213921
}
39223922
break;
39233923

3924+
case VTABLES_TO_EMIT:
3925+
if (F.Kind == MK_MainFile ||
3926+
getContext().getLangOpts().BuildingPCHWithObjectFile)
3927+
for (unsigned I = 0, N = Record.size(); I != N;)
3928+
VTablesToEmit.push_back(ReadDeclID(F, Record, I));
3929+
break;
3930+
39243931
case IMPORTED_MODULES:
39253932
if (!F.isModule()) {
39263933
// If we aren't loading a module (which has its own exports), make
@@ -8110,6 +8117,10 @@ void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
81108117
Consumer->HandleInterestingDecl(DeclGroupRef(D));
81118118
}
81128119

8120+
void ASTReader::PassVTableToConsumer(CXXRecordDecl *RD) {
8121+
Consumer->HandleVTable(RD);
8122+
}
8123+
81138124
void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
81148125
this->Consumer = Consumer;
81158126

clang/lib/Serialization/ASTReaderDecl.cpp

+7
Original file line numberDiff line numberDiff line change
@@ -4242,6 +4242,13 @@ void ASTReader::PassInterestingDeclsToConsumer() {
42424242

42434243
// If we add any new potential interesting decl in the last call, consume it.
42444244
ConsumingPotentialInterestingDecls();
4245+
4246+
for (GlobalDeclID ID : VTablesToEmit) {
4247+
auto *RD = cast<CXXRecordDecl>(GetDecl(ID));
4248+
assert(!RD->shouldEmitInExternalSource());
4249+
PassVTableToConsumer(RD);
4250+
}
4251+
VTablesToEmit.clear();
42454252
}
42464253

42474254
void ASTReader::loadDeclUpdateRecords(PendingUpdateRecord &Record) {

clang/lib/Serialization/ASTWriter.cpp

+29-4
Original file line numberDiff line numberDiff line change
@@ -927,6 +927,7 @@ void ASTWriter::WriteBlockInfoBlock() {
927927
RECORD(DECLS_TO_CHECK_FOR_DEFERRED_DIAGS);
928928
RECORD(PP_ASSUME_NONNULL_LOC);
929929
RECORD(PP_UNSAFE_BUFFER_USAGE);
930+
RECORD(VTABLES_TO_EMIT);
930931

931932
// SourceManager Block.
932933
BLOCK(SOURCE_MANAGER_BLOCK);
@@ -3961,6 +3962,10 @@ void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
39613962
Stream.EmitRecord(INTERESTING_IDENTIFIERS, InterestingIdents);
39623963
}
39633964

3965+
void ASTWriter::handleVTable(CXXRecordDecl *RD) {
3966+
PendingEmittingVTables.push_back(RD);
3967+
}
3968+
39643969
//===----------------------------------------------------------------------===//
39653970
// DeclContext's Name Lookup Table Serialization
39663971
//===----------------------------------------------------------------------===//
@@ -5163,6 +5168,13 @@ void ASTWriter::PrepareWritingSpecialDecls(Sema &SemaRef) {
51635168
// Write all of the DeclsToCheckForDeferredDiags.
51645169
for (auto *D : SemaRef.DeclsToCheckForDeferredDiags)
51655170
GetDeclRef(D);
5171+
5172+
// Write all classes that need to emit the vtable definitions if required.
5173+
if (isWritingStdCXXNamedModules())
5174+
for (CXXRecordDecl *RD : PendingEmittingVTables)
5175+
GetDeclRef(RD);
5176+
else
5177+
PendingEmittingVTables.clear();
51665178
}
51675179

51685180
void ASTWriter::WriteSpecialDeclRecords(Sema &SemaRef) {
@@ -5317,6 +5329,17 @@ void ASTWriter::WriteSpecialDeclRecords(Sema &SemaRef) {
53175329
}
53185330
if (!DeleteExprsToAnalyze.empty())
53195331
Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze);
5332+
5333+
RecordData VTablesToEmit;
5334+
for (CXXRecordDecl *RD : PendingEmittingVTables) {
5335+
if (!wasDeclEmitted(RD))
5336+
continue;
5337+
5338+
AddDeclRef(RD, VTablesToEmit);
5339+
}
5340+
5341+
if (!VTablesToEmit.empty())
5342+
Stream.EmitRecord(VTABLES_TO_EMIT, VTablesToEmit);
53205343
}
53215344

53225345
ASTFileSignature ASTWriter::WriteASTCore(Sema &SemaRef, StringRef isysroot,
@@ -6559,10 +6582,12 @@ void ASTRecordWriter::AddCXXDefinitionData(const CXXRecordDecl *D) {
65596582
// computed.
65606583
Record->push_back(D->getODRHash());
65616584

6562-
bool ModulesDebugInfo =
6563-
Writer->Context->getLangOpts().ModulesDebugInfo && !D->isDependentType();
6564-
Record->push_back(ModulesDebugInfo);
6565-
if (ModulesDebugInfo)
6585+
bool ModulesCodegen =
6586+
!D->isDependentType() &&
6587+
(Writer->Context->getLangOpts().ModulesDebugInfo ||
6588+
D->isInNamedModule());
6589+
Record->push_back(ModulesCodegen);
6590+
if (ModulesCodegen)
65666591
Writer->AddDeclRef(D, Writer->ModularCodegenDecls);
65676592

65686593
// IsLambda bit is already saved.

clang/lib/Serialization/ASTWriterDecl.cpp

+6
Original file line numberDiff line numberDiff line change
@@ -1529,8 +1529,14 @@ void ASTDeclWriter::VisitCXXRecordDecl(CXXRecordDecl *D) {
15291529
if (D->isThisDeclarationADefinition())
15301530
Record.AddCXXDefinitionData(D);
15311531

1532+
if (D->isCompleteDefinition() && D->isInNamedModule())
1533+
Writer.AddDeclRef(D, Writer.ModularCodegenDecls);
1534+
15321535
// Store (what we currently believe to be) the key function to avoid
15331536
// deserializing every method so we can compute it.
1537+
//
1538+
// FIXME: Avoid adding the key function if the class is defined in
1539+
// module purview since in that case the key function is meaningless.
15341540
if (D->isCompleteDefinition())
15351541
Record.AddDeclRef(Context.getCurrentKeyFunction(D));
15361542

0 commit comments

Comments
 (0)