Skip to content

[interop][SwiftToCxx] dispatch virtual calls via thunks for resilient… #63572

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
Feb 11, 2023
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
17 changes: 14 additions & 3 deletions include/swift/IRGen/IRABIDetailsProvider.h
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,9 @@ class IRABIDetailsProvider {
/// A direct call can be made to the underlying function.
Direct,
/// An indirect call that can be made via a static offset in a vtable.
IndirectVTableStaticOffset
IndirectVTableStaticOffset,
/// The call should be made via the provided thunk function.
Thunk
};

static MethodDispatchInfo direct() {
Expand All @@ -265,18 +267,27 @@ class IRABIDetailsProvider {
return MethodDispatchInfo(Kind::IndirectVTableStaticOffset, bitOffset);
}

static MethodDispatchInfo thunk(std::string thunkName) {
return MethodDispatchInfo(Kind::Thunk, 0, thunkName);
}

Kind getKind() const { return kind; }
size_t getStaticBitOffset() const {
assert(kind == Kind::IndirectVTableStaticOffset);
return bitOffset;
}
StringRef getThunkSymbolName() const {
assert(kind == Kind::Thunk);
return thunkName;
}

private:
constexpr MethodDispatchInfo(Kind kind, size_t bitOffset)
: kind(kind), bitOffset(bitOffset) {}
MethodDispatchInfo(Kind kind, size_t bitOffset, std::string thunkName = "")
: kind(kind), bitOffset(bitOffset), thunkName(thunkName) {}

Kind kind;
size_t bitOffset;
std::string thunkName;
};

Optional<MethodDispatchInfo>
Expand Down
7 changes: 7 additions & 0 deletions lib/IRGen/IRABIDetailsProvider.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
#include "swift/AST/IRGenOptions.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/Types.h"
#include "swift/IRGen/Linking.h"
#include "swift/SIL/SILFunctionBuilder.h"
#include "swift/SIL/SILModule.h"
#include "swift/Subsystems.h"
Expand Down Expand Up @@ -216,6 +217,12 @@ class IRABIDetailsProviderImpl {
auto *parentClass = dyn_cast<ClassDecl>(funcDecl->getDeclContext());
if (!parentClass)
return MethodDispatchInfo::direct();
// Resilient indirect calls should go through a thunk.
if (parentClass->hasResilientMetadata())
return MethodDispatchInfo::thunk(
LinkEntity::forDispatchThunk(
SILDeclRef(const_cast<AbstractFunctionDecl *>(funcDecl)))
.mangleAsString());
auto &layout = IGM.getMetadataLayout(parentClass);
if (!isa<ClassMetadataLayout>(layout))
return {};
Expand Down
87 changes: 57 additions & 30 deletions lib/PrintAsClang/DeclAndTypePrinter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1356,6 +1356,47 @@ class DeclAndTypePrinter::Implementation
LoweredFunctionSignature signature;
};

/// Print the C function declaration that represents the given native Swift
/// function, or its dispatch thunk.
ClangRepresentation printCFunctionWithLoweredSignature(
AbstractFunctionDecl *FD, const FunctionSwiftABIInformation &funcABI,
Type resultTy, AnyFunctionType *funcTy, StringRef symbolName,
StringRef comment = "") {
std::string cRepresentationString;
llvm::raw_string_ostream cRepresentationOS(cRepresentationString);
cRepresentationOS << "SWIFT_EXTERN ";

DeclAndTypeClangFunctionPrinter funcPrinter(
cRepresentationOS, owningPrinter.prologueOS, owningPrinter.typeMapping,
owningPrinter.interopContext, owningPrinter);

auto representation = funcPrinter.printFunctionSignature(
FD, funcABI.getSignature(), symbolName, resultTy,
DeclAndTypeClangFunctionPrinter::FunctionSignatureKind::CFunctionProto);
if (representation.isUnsupported())
return representation;

os << cRepresentationOS.str();
// Swift functions can't throw exceptions, we can only
// throw them from C++ when emitting C++ inline thunks for the Swift
// functions.
if (!funcTy->isThrowing())
os << " SWIFT_NOEXCEPT";
if (!funcABI.useCCallingConvention())
os << " SWIFT_CALL";
printAvailability(FD);
os << ';';
if (funcABI.useMangledSymbolName()) {
// add a comment with a demangled function name.
os << " // ";
if (!comment.empty())
os << comment << ' ';
FD->getName().print(os);
}
os << "\n";
return representation;
}

// Print out the extern C Swift ABI function signature.
Optional<FunctionSwiftABIInformation>
printSwiftABIFunctionSignatureAsCxxFunction(
Expand All @@ -1378,47 +1419,33 @@ class DeclAndTypePrinter::Implementation
auto resultTy =
getForeignResultType(FD, funcTy, asyncConvention, errorConvention);

std::string cRepresentationString;
llvm::raw_string_ostream cRepresentationOS(cRepresentationString);

auto signature = owningPrinter.interopContext.getIrABIDetails()
.getFunctionLoweredSignature(FD);
// FIXME: Add a note saying that this func is unsupported.
if (!signature)
return None;
FunctionSwiftABIInformation funcABI(FD, *signature);

cRepresentationOS << "SWIFT_EXTERN ";

DeclAndTypeClangFunctionPrinter funcPrinter(
cRepresentationOS, owningPrinter.prologueOS, owningPrinter.typeMapping,
owningPrinter.interopContext, owningPrinter);

auto representation = funcPrinter.printFunctionSignature(
FD, funcABI.getSignature(), funcABI.getSymbolName(), resultTy,
DeclAndTypeClangFunctionPrinter::FunctionSignatureKind::CFunctionProto);
if (representation.isUnsupported()) {
auto representation = printCFunctionWithLoweredSignature(
FD, funcABI, resultTy, funcTy, funcABI.getSymbolName());
if (representation.isUnsupported())
// FIXME: Emit remark about unemitted declaration.
return None;
}

os << cRepresentationOS.str();
// Swift functions can't throw exceptions, we can only
// throw them from C++ when emitting C++ inline thunks for the Swift
// functions.
// FIXME: Support throwing exceptions for Swift errors.
if (!funcTy->isThrowing())
os << " SWIFT_NOEXCEPT";
if (!funcABI.useCCallingConvention())
os << " SWIFT_CALL";
printAvailability(FD);
os << ';';
if (funcABI.useMangledSymbolName()) {
// add a comment with a demangled function name.
os << " // ";
FD->getName().print(os);
if (selfTypeDeclContext && !isa<ConstructorDecl>(FD)) {
if (auto dispatchInfo = owningPrinter.interopContext.getIrABIDetails()
.getMethodDispatchInfo(FD)) {
// Emit the C signature for the dispatch thunk.
if (dispatchInfo->getKind() ==
IRABIDetailsProvider::MethodDispatchInfo::Kind::Thunk) {
auto thunkRepresentation = printCFunctionWithLoweredSignature(
FD, funcABI, resultTy, funcTy, dispatchInfo->getThunkSymbolName(),
"dispatch thunk for");
assert(!thunkRepresentation.isUnsupported());
}
}
}
os << "\n";

return funcABI;
}

Expand Down
36 changes: 21 additions & 15 deletions lib/PrintAsClang/PrintClangFunction.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1098,21 +1098,27 @@ void DeclAndTypeClangFunctionPrinter::printCxxThunkBody(
os << " void* _ctx = nullptr;\n";
}
Optional<StringRef> indirectFunctionVar;
if (dispatchInfo &&
dispatchInfo->getKind() !=
IRABIDetailsProvider::MethodDispatchInfo::Kind::Direct) {
assert(dispatchInfo->getKind() == IRABIDetailsProvider::MethodDispatchInfo::
Kind::IndirectVTableStaticOffset);
auto vtableBitOffset = dispatchInfo->getStaticBitOffset();

os << "void ***selfPtr_ = reinterpret_cast<void ***>( "
"::swift::_impl::_impl_RefCountedClass::getOpaquePointer(*this));\n";
os << "void **vtable_ = *selfPtr_;\n";
os << "using FType = decltype(" << cxx_synthesis::getCxxImplNamespaceName()
<< "::" << swiftSymbolName << ");\n";
os << "FType *fptr_ = reinterpret_cast<FType *>(*(vtable_ + "
<< (vtableBitOffset / 8) << "));\n"; // FIXME: not 8
indirectFunctionVar = StringRef("fptr_");
using DispatchKindTy = IRABIDetailsProvider::MethodDispatchInfo::Kind;
if (dispatchInfo) {
switch (dispatchInfo->getKind()) {
case DispatchKindTy::Direct:
break;
case DispatchKindTy::IndirectVTableStaticOffset:
os << "void ***selfPtr_ = reinterpret_cast<void ***>( "
"::swift::_impl::_impl_RefCountedClass::getOpaquePointer(*this));"
"\n";
os << "void **vtable_ = *selfPtr_;\n";
os << "using FType = decltype("
<< cxx_synthesis::getCxxImplNamespaceName() << "::" << swiftSymbolName
<< ");\n";
os << "FType *fptr_ = reinterpret_cast<FType *>(*(vtable_ + "
<< (dispatchInfo->getStaticBitOffset() / 8) << "));\n";
indirectFunctionVar = StringRef("fptr_");
break;
case DispatchKindTy::Thunk:
swiftSymbolName = dispatchInfo->getThunkSymbolName();
break;
}
}
auto printCallToCFunc = [&](Optional<StringRef> additionalParam) {
if (indirectFunctionVar)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// RUN: %empty-directory(%t)

// RUN: %target-swift-frontend %S/swift-class-virtual-method-dispatch.swift -typecheck -module-name Class -clang-header-expose-decls=all-public -emit-clang-header-path %t/class.h -enable-library-evolution

// RUN: %target-interop-build-clangxx -c %s -I %t -o %t/swift-class-execution.o
// RUN: %target-interop-build-swift %S/swift-class-virtual-method-dispatch.swift -o %t/swift-class-execution -Xlinker %t/swift-class-execution.o -module-name Class -Xfrontend -entry-point-function-name -Xfrontend swiftMain -enable-library-evolution

// RUN: %target-codesign %t/swift-class-execution
// RUN: %target-run %t/swift-class-execution | %FileCheck %S/swift-class-virtual-method-dispatch-execution.cpp

// FIXME: pointer signing support.
// UNSUPPORTED: CPU=arm64e

// REQUIRES: executable_test

#include "swift-class-virtual-method-dispatch-execution.cpp"
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend %S/swift-class-virtual-method-dispatch.swift -typecheck -module-name Class -clang-header-expose-decls=all-public -emit-clang-header-path %t/class.h -enable-library-evolution
// RUN: %FileCheck %s < %t/class.h

// RUN: %check-interop-cxx-header-in-clang(%t/class.h)

// note: implemented in swift-class-virtual-method-dispatch.swift

// CHECK: void BaseClass::virtualMethod() {
// CHECK-NEXT: return _impl::$s5Class04BaseA0C13virtualMethodyyFTj(::swift::_impl::_impl_RefCountedClass::getOpaquePointer(*this));
// CHECK-NEXT: }

// CHECK: swift::Int BaseClass::virtualMethodIntInt(swift::Int x) {
// CHECK-NEXT: return _impl::$s5Class04BaseA0C016virtualMethodIntE0yS2iFTj(x, ::swift::_impl::_impl_RefCountedClass::getOpaquePointer(*this));
// CHECK-NEXT: }

// CHECK: swift::Int BaseClass::finalMethodInBase(swift::Int x) {
// CHECK-NEXT: return _impl::$s5Class04BaseA0C013finalMethodInB0yS2iF(x, ::swift::_impl::_impl_RefCountedClass::getOpaquePointer(*this));
// CHECK-NEXT: }

// CHECK: void DerivedClass::virtualMethod() {
// CHECK-NEXT: return _impl::$s5Class04BaseA0C13virtualMethodyyFTj(::swift::_impl::_impl_RefCountedClass::getOpaquePointer(*this));
// CHECK-NEXT: }

// CHECK: swift::Int DerivedClass::virtualMethodIntInt(swift::Int x) {
// CHECK-NEXT: return _impl::$s5Class04BaseA0C016virtualMethodIntE0yS2iFTj(x, ::swift::_impl::_impl_RefCountedClass::getOpaquePointer(*this));
// CHECK-NEXT: }

// CHECK: BaseClass DerivedClass::virtualMethodInDerived(const BaseClass& x) {
// CHECK-NEXT: return _impl::_impl_BaseClass::makeRetained(_impl::$s5Class07DerivedA0C015virtualMethodInB0yAA04BaseA0CAFFTj(::swift::_impl::_impl_RefCountedClass::getOpaquePointer(x), ::swift::_impl::_impl_RefCountedClass::getOpaquePointer(*this)));
// CHECK-NEXT: }

// CHECK: void DerivedDerivedClass::virtualMethod() {
// CHECK-NEXT: return _impl::$s5Class07DerivedbA0C13virtualMethodyyF(::swift::_impl::_impl_RefCountedClass::getOpaquePointer(*this));
// CHECK-NEXT: }

// CHECK: BaseClass DerivedDerivedClass::virtualMethodInDerived(const BaseClass& x) {
// CHECK-NEXT: return _impl::_impl_BaseClass::makeRetained(_impl::$s5Class07DerivedbA0C015virtualMethodInB0yAA04BaseA0CAFF(::swift::_impl::_impl_RefCountedClass::getOpaquePointer(x), ::swift::_impl::_impl_RefCountedClass::getOpaquePointer(*this)));
// CHECK-NEXT: }

// CHECK: void DerivedDerivedClass::methodInDerivedDerived() {
// CHECK-NEXT: return _impl::$s5Class07DerivedbA0C08methodInbB0yyF(::swift::_impl::_impl_RefCountedClass::getOpaquePointer(*this));
// CHECK-NEXT: }