Skip to content

[interop][SwiftToCxx] add support for generic methods #60835

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 2 commits into from
Aug 30, 2022
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
57 changes: 32 additions & 25 deletions lib/PrintAsClang/DeclAndTypePrinter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -753,9 +753,9 @@ class DeclAndTypePrinter::Implementation
typeDeclContext, accessor, funcABI->getSymbolName(), resultTy,
/*isDefinition=*/false);
} else {
declPrinter.printCxxMethod(typeDeclContext, AFD,
funcABI->getSymbolName(), resultTy,
/*isDefinition=*/false);
declPrinter.printCxxMethod(
typeDeclContext, AFD, funcABI->getSymbolName(), resultTy,
/*isDefinition=*/false, funcABI->additionalParams);
}

DeclAndTypeClangFunctionPrinter defPrinter(
Expand All @@ -769,9 +769,9 @@ class DeclAndTypePrinter::Implementation
typeDeclContext, accessor, funcABI->getSymbolName(), resultTy,
/*isDefinition=*/true);
} else {
defPrinter.printCxxMethod(typeDeclContext, AFD,
funcABI->getSymbolName(), resultTy,
/*isDefinition=*/true);
defPrinter.printCxxMethod(
typeDeclContext, AFD, funcABI->getSymbolName(), resultTy,
/*isDefinition=*/true, funcABI->additionalParams);
}

// FIXME: SWIFT_WARN_UNUSED_RESULT
Expand Down Expand Up @@ -1068,6 +1068,9 @@ class DeclAndTypePrinter::Implementation

bool useMangledSymbolName() const { return !isCDecl; }

SmallVector<DeclAndTypeClangFunctionPrinter::AdditionalParam, 2>
additionalParams;

private:
bool isCDecl;
StringRef symbolName;
Expand All @@ -1078,7 +1081,8 @@ class DeclAndTypePrinter::Implementation
AbstractFunctionDecl *FD, Type resultTy,
llvm::SmallVector<IRABIDetailsProvider::ABIAdditionalParam, 1> ABIparams,
llvm::SmallVector<DeclAndTypeClangFunctionPrinter::AdditionalParam, 2>
&params) {
&params,
Optional<NominalTypeDecl *> selfTypeDeclContext = None) {
for (auto param : ABIparams) {
if (param.role == IRABIDetailsProvider::ABIAdditionalParam::
ABIParameterRole::GenericRequirementRole)
Expand All @@ -1090,7 +1094,9 @@ class DeclAndTypePrinter::Implementation
IRABIDetailsProvider::ABIAdditionalParam::ABIParameterRole::Self)
params.push_back(
{DeclAndTypeClangFunctionPrinter::AdditionalParam::Role::Self,
resultTy->getASTContext().getOpaquePointerType(),
selfTypeDeclContext
? (*selfTypeDeclContext)->getDeclaredType()
: resultTy->getASTContext().getOpaquePointerType(),
/*isIndirect=*/
isa<FuncDecl>(FD) ? cast<FuncDecl>(FD)->isMutating() : false});
else if (param.role == IRABIDetailsProvider::ABIAdditionalParam::
Expand Down Expand Up @@ -1135,23 +1141,29 @@ class DeclAndTypePrinter::Implementation
owningPrinter.interopContext, owningPrinter);
auto ABIparams = owningPrinter.interopContext.getIrABIDetails()
.getFunctionABIAdditionalParams(FD);
llvm::SmallVector<DeclAndTypeClangFunctionPrinter::AdditionalParam, 2>
additionalParams;
if (selfTypeDeclContext && !isa<ConstructorDecl>(FD)) {
additionalParams.push_back(
// FIXME: Ideally direct 'self' would come from IR provider too.
if (selfTypeDeclContext && !isa<ConstructorDecl>(FD) &&
llvm::find_if(
ABIparams,
[](const IRABIDetailsProvider::ABIAdditionalParam &Param) {
return Param.role == IRABIDetailsProvider::ABIAdditionalParam::
ABIParameterRole::Self;
}) == ABIparams.end()) {
funcABI.additionalParams.push_back(
{DeclAndTypeClangFunctionPrinter::AdditionalParam::Role::Self,
(*selfTypeDeclContext)->getDeclaredType(),
/*isIndirect=*/
isa<FuncDecl>(FD) ? cast<FuncDecl>(FD)->isMutating() : false});
}
// FIXME: Fix the method 'self' parameter.
if (!selfTypeDeclContext && !ABIparams.empty())
convertABIAdditionalParams(FD, resultTy, ABIparams, additionalParams);
if (!ABIparams.empty())
convertABIAdditionalParams(FD, resultTy, ABIparams,
funcABI.additionalParams,
/*selfContext=*/selfTypeDeclContext);

auto representation = funcPrinter.printFunctionSignature(
FD, funcABI.getSymbolName(), resultTy,
DeclAndTypeClangFunctionPrinter::FunctionSignatureKind::CFunctionProto,
additionalParams);
funcABI.additionalParams);
if (representation.isUnsupported()) {
// FIXME: Emit remark about unemitted declaration.
return None;
Expand Down Expand Up @@ -1195,12 +1207,6 @@ class DeclAndTypePrinter::Implementation
DeclAndTypeClangFunctionPrinter funcPrinter(
os, owningPrinter.prologueOS, owningPrinter.typeMapping,
owningPrinter.interopContext, owningPrinter);
llvm::SmallVector<DeclAndTypeClangFunctionPrinter::AdditionalParam, 2>
additionalParams;
auto ABIparams = owningPrinter.interopContext.getIrABIDetails()
.getFunctionABIAdditionalParams(FD);
if (!ABIparams.empty())
convertABIAdditionalParams(FD, resultTy, ABIparams, additionalParams);
DeclAndTypeClangFunctionPrinter::FunctionSignatureModifiers modifiers;
modifiers.isInline = true;
auto result = funcPrinter.printFunctionSignature(
Expand All @@ -1215,9 +1221,10 @@ class DeclAndTypePrinter::Implementation
printFunctionClangAttributes(FD, funcTy);
printAvailability(FD);
os << " {\n";
funcPrinter.printCxxThunkBody(
funcABI.getSymbolName(), FD->getModuleContext(), resultTy,
FD->getParameters(), additionalParams, funcTy->isThrowing(), funcTy);
funcPrinter.printCxxThunkBody(funcABI.getSymbolName(),
FD->getModuleContext(), resultTy,
FD->getParameters(), funcABI.additionalParams,
funcTy->isThrowing(), funcTy);
os << "}\n";
}

Expand Down
57 changes: 30 additions & 27 deletions lib/PrintAsClang/PrintClangFunction.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -318,24 +318,32 @@ ClangRepresentation DeclAndTypeClangFunctionPrinter::printFunctionSignature(
const AbstractFunctionDecl *FD, StringRef name, Type resultTy,
FunctionSignatureKind kind, ArrayRef<AdditionalParam> additionalParams,
FunctionSignatureModifiers modifiers) {
if (kind == FunctionSignatureKind::CxxInlineThunk && FD->isGeneric()) {
os << "template<";
llvm::interleaveComma(FD->getGenericParams()->getParams(), os,
[&](const GenericTypeParamDecl *genericParam) {
os << "class ";
ClangSyntaxPrinter(os).printBaseName(genericParam);
});
os << ">\n";
os << "requires ";
llvm::interleave(
FD->getGenericParams()->getParams(), os,
[&](const GenericTypeParamDecl *genericParam) {
os << "swift::isUsableInGenericContext<";
ClangSyntaxPrinter(os).printBaseName(genericParam);
os << ">";
},
" && ");
os << "\n";
if (FD->isGeneric()) {
auto Signature = FD->getGenericSignature();
auto Requirements = Signature.getRequirements();
// FIXME: Support generic requirements.
if (!Requirements.empty())
return ClangRepresentation::unsupported;
if (kind == FunctionSignatureKind::CxxInlineThunk) {
os << "template<";
llvm::interleaveComma(FD->getGenericParams()->getParams(), os,
[&](const GenericTypeParamDecl *genericParam) {
os << "class ";
ClangSyntaxPrinter(os).printBaseName(
genericParam);
});
os << ">\n";
os << "requires ";
llvm::interleave(
FD->getGenericParams()->getParams(), os,
[&](const GenericTypeParamDecl *genericParam) {
os << "swift::isUsableInGenericContext<";
ClangSyntaxPrinter(os).printBaseName(genericParam);
os << ">";
},
" && ");
os << "\n";
}
}
auto emittedModule = FD->getModuleContext();
OutputLanguageMode outputLang = kind == FunctionSignatureKind::CFunctionProto
Expand Down Expand Up @@ -709,7 +717,8 @@ static StringRef getConstructorName(const AbstractFunctionDecl *FD) {

void DeclAndTypeClangFunctionPrinter::printCxxMethod(
const NominalTypeDecl *typeDeclContext, const AbstractFunctionDecl *FD,
StringRef swiftSymbolName, Type resultTy, bool isDefinition) {
StringRef swiftSymbolName, Type resultTy, bool isDefinition,
ArrayRef<AdditionalParam> additionalParams) {
bool isConstructor = isa<ConstructorDecl>(FD);
os << " ";

Expand All @@ -736,15 +745,9 @@ void DeclAndTypeClangFunctionPrinter::printCxxMethod(

os << " {\n";
// FIXME: should it be objTy for resultTy?
SmallVector<AdditionalParam, 2> additionalParams;
if (!isConstructor)
additionalParams.push_back(AdditionalParam{
AdditionalParam::Role::Self,
typeDeclContext->getDeclaredType(),
/*isIndirect=*/isMutating,
});
printCxxThunkBody(swiftSymbolName, FD->getModuleContext(), resultTy,
FD->getParameters(), additionalParams, FD->hasThrows());
FD->getParameters(), additionalParams, FD->hasThrows(),
FD->getInterfaceType()->castTo<AnyFunctionType>());
os << " }\n";
}

Expand Down
3 changes: 2 additions & 1 deletion lib/PrintAsClang/PrintClangFunction.h
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,8 @@ class DeclAndTypeClangFunctionPrinter {
/// constructors.
void printCxxMethod(const NominalTypeDecl *typeDeclContext,
const AbstractFunctionDecl *FD, StringRef swiftSymbolName,
Type resultTy, bool isDefinition);
Type resultTy, bool isDefinition,
ArrayRef<AdditionalParam> additionalParams);

/// Print the C++ getter/setter method signature.
void printCxxPropertyAccessorMethod(const NominalTypeDecl *typeDeclContext,
Expand Down
18 changes: 18 additions & 0 deletions test/Interop/SwiftToCxx/generics/generic-function-execution.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -206,5 +206,23 @@ int main() {
// CHECK-NEXT: TestSmallStruct value=TestSmallStruct(x1: 65233)
// CHECK-NEXT: TestSmallStruct value=TestSmallStruct(x1: 4294902062)
// CHECK-NEXT: TestSmallStruct value=TestSmallStruct(x1: 65233)
{
auto x = createTestSmallStruct(42);
int passThru = x.genericMethodPassThrough((int)555);
assert(passThru == 555);
auto xprime = x.genericMethodPassThrough(x);
genericPrintFunction(xprime);
x.genericMethodMutTake((uint32_t)16);
genericPrintFunction(xprime);
genericPrintFunction(x);
x.genericMethodMutTake(xprime);
genericPrintFunction(xprime);
genericPrintFunction(x);
}
// CHECK-NEXT: TestSmallStruct value=TestSmallStruct(x1: 42)
// CHECK-NEXT: TestSmallStruct value=TestSmallStruct(x1: 42)
// CHECK-NEXT: TestSmallStruct value=TestSmallStruct(x1: 58)
// CHECK-NEXT: TestSmallStruct value=TestSmallStruct(x1: 42)
// CHECK-NEXT: TestSmallStruct value=TestSmallStruct(x1: 57)
return 0;
}
54 changes: 54 additions & 0 deletions test/Interop/SwiftToCxx/generics/generic-function-in-cxx.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,12 @@ public func genericRet<T>(_ x: T) -> T {
return x
}

public func genericRequirementProtocol<T: Hashable>(_ x: T) {
}

public func genericRequirementClass<T>(_ x: T) where T: TestClass {
}

public class TestClass {
let field: Int

Expand Down Expand Up @@ -66,27 +72,52 @@ public func createTestLargeStruct(_ x: Int) -> TestLargeStruct {
return TestLargeStruct(x)
}

@frozen
public struct TestSmallStruct {
var x1: UInt32

public mutating func mut() {
x1 = ~x1
}

public func genericMethodPassThrough<T>(_ x: T) -> T {
return x
}

public mutating func genericMethodMutTake<T>(_ x: T) {
if let y = x as? UInt32 {
x1 += y
} else {
x1 -= 1
}
}
}

public func createTestSmallStruct(_ x: UInt32) -> TestSmallStruct {
return TestSmallStruct(x1: x)
}

// CHECK: SWIFT_EXTERN void $s9Functions15TestSmallStructV24genericMethodPassThroughyxxlF(SWIFT_INDIRECT_RESULT void * _Nonnull, const void * _Nonnull x, struct swift_interop_stub_Functions_TestSmallStruct _self, void * _Nonnull ) SWIFT_NOEXCEPT SWIFT_CALL; // genericMethodPassThrough(_:)
// CHECK-NEXT: SWIFT_EXTERN void $s9Functions15TestSmallStructV20genericMethodMutTakeyyxlF(const void * _Nonnull x, void * _Nonnull , SWIFT_CONTEXT void * _Nonnull _self) SWIFT_NOEXCEPT SWIFT_CALL; // genericMethodMutTake(_:)

// CHECK: SWIFT_EXTERN void $s9Functions20genericPrintFunctionyyxlF(const void * _Nonnull x, void * _Nonnull ) SWIFT_NOEXCEPT SWIFT_CALL; // genericPrintFunction(_:)
// CHECK-NEXT: SWIFT_EXTERN void $s9Functions32genericPrintFunctionMultiGenericyySi_xxSiq_tr0_lF(ptrdiff_t x, const void * _Nonnull t1, const void * _Nonnull t1p, ptrdiff_t y, const void * _Nonnull t2, void * _Nonnull , void * _Nonnull ) SWIFT_NOEXCEPT SWIFT_CALL; // genericPrintFunctionMultiGeneric(_:_:_:_:_:)
// CHECK-NEXT: SWIFT_EXTERN void $s9Functions26genericPrintFunctionTwoArgyyx_SitlF(const void * _Nonnull x, ptrdiff_t y, void * _Nonnull ) SWIFT_NOEXCEPT SWIFT_CALL; // genericPrintFunctionTwoArg(_:_:)
// CHECK-NEXT: SWIFT_EXTERN void $s9Functions10genericRetyxxlF(SWIFT_INDIRECT_RESULT void * _Nonnull, const void * _Nonnull x, void * _Nonnull ) SWIFT_NOEXCEPT SWIFT_CALL; // genericRet(_:)
// CHECK-NEXT: SWIFT_EXTERN void $s9Functions11genericSwapyyxz_xztlF(void * _Nonnull x, void * _Nonnull y, void * _Nonnull ) SWIFT_NOEXCEPT SWIFT_CALL; // genericSwap(_:_:)

// CHECK-NOT: genericRequirement

// Skip templates in impl classes.
// CHECK: _impl_TestSmallStruct
// CHECK: template<class T>
// CHECK-NEXT: requires swift::isUsableInGenericContext<T>
// CHECK-NEXT: inline T genericMethodPassThrough(const T & x) const;
// CHECK-NEXT: template<class T>
// CHECK-NEXT: requires swift::isUsableInGenericContext<T>
// CHECK-NEXT: inline void genericMethodMutTake(const T & x);
// CHECK: template<class T>
// CHECK-NEXT: returnNewValue

// CHECK: template<class T>
// CHECK-NEXT: requires swift::isUsableInGenericContext<T>
Expand Down Expand Up @@ -131,3 +162,26 @@ public func createTestSmallStruct(_ x: UInt32) -> TestSmallStruct {
// CHECK-NEXT: inline void genericSwap(T & x, T & y) noexcept {
// CHECK-NEXT: return _impl::$s9Functions11genericSwapyyxz_xztlF(swift::_impl::getOpaquePointer(x), swift::_impl::getOpaquePointer(y), swift::getTypeMetadata<T>());
// CHECK-NEXT: }

// CHECK: template<class T>
// CHECK-NEXT: requires swift::isUsableInGenericContext<T>
// CHECK-NEXT: inline T TestSmallStruct::genericMethodPassThrough(const T & x) const {
// CHECK-NEXT: if constexpr (std::is_base_of<::swift::_impl::RefCountedClass, T>::value) {
// CHECK-NEXT: void *returnValue;
// CHECK-NEXT: _impl::$s9Functions15TestSmallStructV24genericMethodPassThroughyxxlF(reinterpret_cast<void *>(&returnValue), swift::_impl::getOpaquePointer(x), _impl::swift_interop_passDirect_Functions_TestSmallStruct(_getOpaquePointer()), swift::getTypeMetadata<T>());
// CHECK-NEXT: return ::swift::_impl::implClassFor<T>::type::makeRetained(returnValue);
// CHECK-NEXT: } else if constexpr (::swift::_impl::isValueType<T>) {
// CHECK-NEXT: return ::swift::_impl::implClassFor<T>::type::returnNewValue([&](void * _Nonnull returnValue) {
// CHECK-NEXT: _impl::$s9Functions15TestSmallStructV24genericMethodPassThroughyxxlF(returnValue, swift::_impl::getOpaquePointer(x), _impl::swift_interop_passDirect_Functions_TestSmallStruct(_getOpaquePointer()), swift::getTypeMetadata<T>());
// CHECK-NEXT: });
// CHECK-NEXT: } else {
// CHECK-NEXT: T returnValue;
// CHECK-NEXT: _impl::$s9Functions15TestSmallStructV24genericMethodPassThroughyxxlF(reinterpret_cast<void *>(&returnValue), swift::_impl::getOpaquePointer(x), _impl::swift_interop_passDirect_Functions_TestSmallStruct(_getOpaquePointer()), swift::getTypeMetadata<T>());
// CHECK-NEXT: return returnValue;
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: template<class T>
// CHECK-NEXT: requires swift::isUsableInGenericContext<T>
// CHECK-NEXT: inline void TestSmallStruct::genericMethodMutTake(const T & x) {
// CHECK-NEXT: return _impl::$s9Functions15TestSmallStructV20genericMethodMutTakeyyxlF(swift::_impl::getOpaquePointer(x), swift::getTypeMetadata<T>(), _getOpaquePointer());
// CHECK-NEXT: }