Skip to content

[cxx-interop] Prevent usage in Swift of C++ move constructor with default args #79542

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 7, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions include/swift/AST/DiagnosticsClangImporter.def
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,10 @@ NOTE(record_not_automatically_importable, none, "record '%0' is not "
"does this type have reference "
"semantics?",
(StringRef, StringRef))
NOTE(record_unsupported_default_args, none,
"copy constructors and move constructors with more than one parameter are "
"unavailable in Swift",
())

NOTE(projection_value_not_imported, none, "C++ method '%0' that returns a value "
"of type '%1' is unavailable",
Expand Down
4 changes: 3 additions & 1 deletion include/swift/ClangImporter/ClangImporterRequests.h
Original file line number Diff line number Diff line change
Expand Up @@ -347,8 +347,10 @@ enum class CxxRecordSemanticsKind {
MoveOnly,
Reference,
Iterator,
// A record that is either not copyable or not destructible.
// A record that is either not copyable/movable or not destructible.
MissingLifetimeOperation,
// A record that has no copy and no move operations
UnavailableConstructors,
// A C++ record that represents a Swift class type exposed to C++ from Swift.
SwiftClassType
};
Expand Down
27 changes: 17 additions & 10 deletions lib/ClangImporter/ClangImporter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8010,14 +8010,6 @@ static bool isSufficientlyTrivial(const clang::CXXRecordDecl *decl) {
return true;
}

static bool hasNonFirstDefaultArg(const clang::CXXConstructorDecl *ctor) {
if (ctor->getNumParams() < 2)
return false;

auto lastParam = ctor->parameters().back();
return lastParam->hasDefaultArg();
}

/// Checks if a record provides the required value type lifetime operations
/// (copy and destroy).
static bool hasCopyTypeOperations(const clang::CXXRecordDecl *decl) {
Expand All @@ -8034,7 +8026,8 @@ static bool hasCopyTypeOperations(const clang::CXXRecordDecl *decl) {
// struct.
return llvm::any_of(decl->ctors(), [](clang::CXXConstructorDecl *ctor) {
return ctor->isCopyConstructor() && !ctor->isDeleted() &&
!hasNonFirstDefaultArg(ctor) &&
// FIXME: Support default arguments (rdar://142414553)
ctor->getNumParams() == 1 &&
ctor->getAccess() == clang::AccessSpecifier::AS_public;
});
}
Expand All @@ -8050,7 +8043,9 @@ static bool hasMoveTypeOperations(const clang::CXXRecordDecl *decl) {
return false;

return llvm::any_of(decl->ctors(), [](clang::CXXConstructorDecl *ctor) {
return ctor->isMoveConstructor();
return ctor->isMoveConstructor() &&
// FIXME: Support default arguments (rdar://142414553)
ctor->getNumParams() == 1;
});
}

Expand All @@ -8069,6 +8064,15 @@ static bool hasCustomCopyOrMoveConstructor(const clang::CXXRecordDecl *decl) {
decl->hasUserDeclaredMoveConstructor();
}

static bool
hasConstructorWithUnsupportedDefaultArgs(const clang::CXXRecordDecl *decl) {
return llvm::any_of(decl->ctors(), [](clang::CXXConstructorDecl *ctor) {
return (ctor->isCopyConstructor() || ctor->isMoveConstructor()) &&
// FIXME: Support default arguments (rdar://142414553)
ctor->getNumParams() != 1;
});
}

static bool isSwiftClassType(const clang::CXXRecordDecl *decl) {
// Swift type must be annotated with external_source_symbol attribute.
auto essAttr = decl->getAttr<clang::ExternalSourceSymbolAttr>();
Expand Down Expand Up @@ -8124,6 +8128,9 @@ CxxRecordSemantics::evaluate(Evaluator &evaluator,
"import_iterator", decl->getNameAsString());
}

if (hasConstructorWithUnsupportedDefaultArgs(cxxDecl))
return CxxRecordSemanticsKind::UnavailableConstructors;

return CxxRecordSemanticsKind::MissingLifetimeOperation;
}

Expand Down
14 changes: 11 additions & 3 deletions lib/ClangImporter/ImportDecl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2966,15 +2966,23 @@ namespace {
auto semanticsKind = evaluateOrDefault(
Impl.SwiftContext.evaluator,
CxxRecordSemantics({decl, Impl.SwiftContext, &Impl}), {});
if (semanticsKind == CxxRecordSemanticsKind::MissingLifetimeOperation &&
if ((semanticsKind == CxxRecordSemanticsKind::MissingLifetimeOperation ||
semanticsKind == CxxRecordSemanticsKind::UnavailableConstructors) &&
// Let un-specialized class templates through. We'll sort out their
// members once they're instranciated.
// members once they're instantiated.
!Impl.importSymbolicCXXDecls) {

if (semanticsKind == CxxRecordSemanticsKind::UnavailableConstructors) {
Impl.addImportDiagnostic(
decl, Diagnostic(diag::record_unsupported_default_args),
decl->getLocation());
}

Impl.addImportDiagnostic(
decl,
Diagnostic(diag::record_not_automatically_importable,
Impl.SwiftContext.AllocateCopy(decl->getNameAsString()),
"does not have a copy constructor or destructor"),
"it must have a copy/move constructor and a destructor"),
decl->getLocation());
return nullptr;
}
Expand Down
14 changes: 5 additions & 9 deletions lib/IRGen/GenStruct.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -541,20 +541,14 @@ namespace {
FixedTypeInfo, ClangFieldInfo> {
const clang::RecordDecl *ClangDecl;

bool hasNonFirstDefaultArg(const clang::CXXConstructorDecl *ctor) const {
if (ctor->getNumParams() < 2)
return false;

auto lastParam = ctor->parameters().back();
return lastParam->hasDefaultArg();
}

const clang::CXXConstructorDecl *findCopyConstructor() const {
const auto *cxxRecordDecl = dyn_cast<clang::CXXRecordDecl>(ClangDecl);
if (!cxxRecordDecl)
return nullptr;
for (auto ctor : cxxRecordDecl->ctors()) {
if (ctor->isCopyConstructor() && !hasNonFirstDefaultArg(ctor) &&
if (ctor->isCopyConstructor() &&
// FIXME: Support default arguments (rdar://142414553)
ctor->getNumParams() == 1 &&
ctor->getAccess() == clang::AS_public && !ctor->isDeleted())
return ctor;
}
Expand All @@ -567,6 +561,8 @@ namespace {
return nullptr;
for (auto ctor : cxxRecordDecl->ctors()) {
if (ctor->isMoveConstructor() &&
// FIXME: Support default arguments (rdar://142414553)
ctor->getNumParams() == 1 &&
ctor->getAccess() == clang::AS_public && !ctor->isDeleted())
return ctor;
}
Expand Down
14 changes: 14 additions & 0 deletions test/Interop/Cxx/class/Inputs/constructors.h
Original file line number Diff line number Diff line change
Expand Up @@ -108,4 +108,18 @@ struct HasPtrAuthMember {
};
#endif

struct MoveConstructorWithOneParameterWithDefaultArg {
int value;

MoveConstructorWithOneParameterWithDefaultArg(int value) : value(value) {}

MoveConstructorWithOneParameterWithDefaultArg(
const MoveConstructorWithOneParameterWithDefaultArg &) = delete;

MoveConstructorWithOneParameterWithDefaultArg(
MoveConstructorWithOneParameterWithDefaultArg &&other =
MoveConstructorWithOneParameterWithDefaultArg{0})
: value(other.value + 1) {}
};

#endif // TEST_INTEROP_CXX_CLASS_INPUTS_CONSTRUCTORS_H
22 changes: 22 additions & 0 deletions test/Interop/Cxx/class/Inputs/type-classification.h
Original file line number Diff line number Diff line change
Expand Up @@ -274,4 +274,26 @@ struct HasCopyConstructorWithDefaultArgs {
default;
};

struct HasMoveConstructorWithDefaultArgs {
int value;
HasMoveConstructorWithDefaultArgs(int value) : value(value) {}

HasMoveConstructorWithDefaultArgs(HasMoveConstructorWithDefaultArgs &&other,
int value = 1)
: value(other.value + value) {}
};

struct HasCopyAndMoveConstructorWithDefaultArgs {
int value;
HasCopyAndMoveConstructorWithDefaultArgs(int value) : value(value) {}

HasCopyAndMoveConstructorWithDefaultArgs(
const HasCopyAndMoveConstructorWithDefaultArgs &other, int value = 1)
: value(other.value + value) {}

HasCopyAndMoveConstructorWithDefaultArgs(
HasCopyAndMoveConstructorWithDefaultArgs &&other, int value = 1)
: value(other.value + value) {}
};

#endif // TEST_INTEROP_CXX_CLASS_INPUTS_TYPE_CLASSIFICATION_H
7 changes: 7 additions & 0 deletions test/Interop/Cxx/class/constructors-executable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -63,4 +63,11 @@ CxxConstructorTestSuite.test("implicit default ctor") {
expectNil(instance3.ptr)
}

CxxConstructorTestSuite.test("MoveConstructorWithOneParamWithDefaultArg") {
let instance1 = MoveConstructorWithOneParameterWithDefaultArg(5)
let instance2 = instance1
let instance3 = MoveConstructorWithOneParameterWithDefaultArg(5)
expectTrue(instance2.value + instance3.value >= 10)
}

runAllTests()
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ CxxCopyMoveAssignTestSuite.test("NonTrivialCopyAssign") {
expectEqual(0, instance.copyAssignCounter)
takeValue(instance2)
}
// The number of construcors and destructors called for `NonTrivialCopyAssign` must be balanced.
// The number of constructors and destructors called for `NonTrivialCopyAssign` must be balanced.
expectEqual(0, InstanceBalanceCounter.getCounterValue())
}

Expand All @@ -37,7 +37,7 @@ CxxCopyMoveAssignTestSuite.test("NonTrivialMoveAssign") {
// `operator=` isn't called.
expectEqual(0, instance.moveAssignCounter)
}
// The number of construcors and destructors called for `NonTrivialCopyAssign` must be balanced.
// The number of constructors and destructors called for `NonTrivialCopyAssign` must be balanced.
expectEqual(0, InstanceBalanceCounter.getCounterValue())
}

Expand All @@ -51,7 +51,7 @@ CxxCopyMoveAssignTestSuite.test("NonTrivialCopyAndCopyMoveAssign") {
expectEqual(0, instance.assignCounter)
takeValue(instance2)
}
// The number of construcors and destructors called for `NonTrivialCopyAndCopyMoveAssign` must be balanced.
// The number of constructors and destructors called for `NonTrivialCopyAndCopyMoveAssign` must be balanced.
expectEqual(0, InstanceBalanceCounter.getCounterValue())
}

Expand Down
6 changes: 3 additions & 3 deletions test/Interop/Cxx/class/invalid-class-errors.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,17 +27,17 @@ struct Nested {

import Test

// CHECK: note: record 'A' is not automatically available: does not have a copy constructor or destructor; does this type have reference semantics?
// CHECK: note: record 'A' is not automatically available: it must have a copy/move constructor and a destructor; does this type have reference semantics?
// CHECK: struct A {
// CHECK: ^
// CHECK: SWIFT_SHARED_REFERENCE(<#retain#>, <#release#>)
public func test(x: A) { }
// CHECK: note: record 'B' is not automatically available: does not have a copy constructor or destructor; does this type have reference semantics?
// CHECK: note: record 'B' is not automatically available: it must have a copy/move constructor and a destructor; does this type have reference semantics?
// CHECK: struct {{.*}}B {
// CHECK: ^
// CHECK: SWIFT_SHARED_REFERENCE(<#retain#>, <#release#>)
public func test(x: B) { }
// CHECK: note: record 'Nested' is not automatically available: does not have a copy constructor or destructor; does this type have reference semantics?
// CHECK: note: record 'Nested' is not automatically available: it must have a copy/move constructor and a destructor; does this type have reference semantics?
// CHECK: struct Nested {
// CHECK: ^
// CHECK: SWIFT_SHARED_REFERENCE(<#retain#>, <#release#>)
Expand Down
26 changes: 24 additions & 2 deletions test/Interop/Cxx/class/type-classification-typechecker.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,35 @@ func testAnnotated() {
_ = v
}

func testNonCopyable() {
func testHasCopyTypeOperations() {
let x = HasCopyConstructorWithDefaultArgs(5)
let v = copy x // expected-error {{'copy' cannot be applied to noncopyable types}}
_ = v
}

func testFuncCallNoncopyable() {
func aux(input: HasCopyConstructorWithDefaultArgs) {}
let x = HasCopyConstructorWithDefaultArgs(5)
aux(input: x)
// expected-error@-3 {{parameter of noncopyable type 'HasCopyConstructorWithDefaultArgs' must specify ownership}}
// expected-note@-4 {{add 'borrowing' for an immutable reference}}
// expected-note@-5 {{add 'consuming' to take the value from the caller}}
// expected-note@-6 {{add 'inout' for a mutable reference}}
}

func testHasMoveTypeOperations() {
let x = HasMoveConstructorWithDefaultArgs(5) // expected-error {{cannot find 'HasMoveConstructorWithDefaultArgs' in scope}}
}

func testHasCopyOrMoveTypeOperations() {
let x = HasCopyAndMoveConstructorWithDefaultArgs(5)
// expected-error@-1 {{cannot find 'HasCopyAndMoveConstructorWithDefaultArgs' in scope}}
}

test()
testField()
testAnnotated()
testNonCopyable()
testHasCopyTypeOperations()
testFuncCallNoncopyable()
testHasMoveTypeOperations()
testHasCopyOrMoveTypeOperations()