mirror of
https://github.com/carbon-language/carbon-lang.git
synced 2026-10-04 10:51:05 +01:00
Support pass-by-move when calling a C++ function taking by value. (#7135)
Previously, we picked a single Carbon parameter pattern for each C++ parameter pattern. This doesn't work well in cases where the Carbon semantics and the C++ semantics are not perfectly aligned. In particular, when a parameter is passed by value in C++, that might mean either pass-by-move (which in Carbon would best be modeled by a `var` pattern, as no other form of parameter would perform a move) or pass-by-copy (which in Carbon would best be modeled by a value parameter, as a `var` parameter would force an extra copy). After this change, we compute a passing mode for each parameter based on the implicit conversion sequence from the argument to the parameter as determined by C++ overload resolution, and use that to determine the Carbon pattern corresponding to each C++ parameter. This results in potentially generating multiple different thunks for the same C++ function if it's called in different ways, but we already did that to handle default arguments and list-initialization. The passing modes are included in the thunk mangling. Add a new value store for clang decl signatures, which capture the information about parameter passing mode as well as the other existing information about different ways that a C++ function might be imported to Carbon. Most of the rules for computing passing modes are the same as before: const references use pass by value, non-const lvalue references use pass-by-ref, non-const rvalue references use pass-by-var. But for C++ non-reference parameters, pick between pass-by-value and pass-by-var based on whether the implicit conversion sequence was effectively performing a copy. Prefer pass-by-value if either would work and they'd do the same thing. We still use pass-by-value for const references, even when the argument is an lvalue and we could pass a reference; we may want to change this in future. For virtual functions, we try to pick a worst-case passing mode, as we can only pick a single signature for what goes in the vtable. Calls to virtual functions will still use a thunk to C++, allowing variance in the calling convention at call sites. We don't allow variance in the overriders as we don't implement support for thunks for virtual functions yet. We currently use pass-by-value for const reference parameters here, but that should probably change at some point. Assisted-by: Gemini via Antigravity
This commit is contained in:
@@ -4,6 +4,7 @@
|
||||
|
||||
#include "toolchain/check/cpp/overload_resolution.h"
|
||||
|
||||
#include "clang/AST/DeclCXX.h"
|
||||
#include "clang/Basic/DiagnosticSema.h"
|
||||
#include "clang/Sema/Overload.h"
|
||||
#include "clang/Sema/Sema.h"
|
||||
@@ -68,9 +69,8 @@ static auto AddOverloadCandidates(
|
||||
|
||||
auto* fn_decl = template_decl ? template_decl->getTemplatedDecl()
|
||||
: cast<clang::FunctionDecl>(decl);
|
||||
auto* method_decl = dyn_cast<clang::CXXMethodDecl>(fn_decl);
|
||||
if (method_decl && !method_decl->isStatic() &&
|
||||
!isa<clang::CXXConstructorDecl>(fn_decl)) {
|
||||
if (IsObjectMemberFunction(*fn_decl)) {
|
||||
auto* method_decl = cast<clang::CXXMethodDecl>(fn_decl);
|
||||
clang::QualType self_type;
|
||||
clang::Expr::Classification self_classification;
|
||||
if (self_arg) {
|
||||
@@ -130,6 +130,139 @@ auto CheckCppOverloadAccess(
|
||||
.highest_allowed_access = allowed_access_kind});
|
||||
}
|
||||
|
||||
// Computes the passing mode for a C++ function parameter that is a reference.
|
||||
static auto ComputePassingModeForReferenceBinding(
|
||||
const clang::StandardConversionSequence& scs)
|
||||
-> SemIR::ClangDeclSignature::PassingMode {
|
||||
CARBON_CHECK(scs.ReferenceBinding);
|
||||
auto pointee_type = scs.getToType(2);
|
||||
if (pointee_type.isConstQualified() ||
|
||||
(scs.IsLvalueReference && scs.BindsToRvalue)) {
|
||||
// Reference to const is always mapped to Carbon pass by value. A non-const
|
||||
// lvalue reference bound to an rvalue only happens when initializing an
|
||||
// object parameter with no ref-qualifier from an rvalue, which we also
|
||||
// model as pass-by-value.
|
||||
return SemIR::ClangDeclSignature::PassingMode::ByValue;
|
||||
}
|
||||
// Rvalue reference to non-const is passed as a `var` to force a copy or move
|
||||
// in the caller. Lvalue reference to non-const is passed by reference.
|
||||
return scs.IsLvalueReference ? SemIR::ClangDeclSignature::PassingMode::ByRef
|
||||
: SemIR::ClangDeclSignature::PassingMode::ByVar;
|
||||
}
|
||||
|
||||
// Returns whether move-construction of type `type` is known to be equivalent to
|
||||
// a copy. If so, it's safe to map C++ pass-by-value into Carbon pass-by-value
|
||||
// instead of pass-by-var.
|
||||
static auto IsMoveEquivalentToCopy(clang::QualType type) {
|
||||
// We can pass by copy instead of by move if:
|
||||
// - The type is not a class type.
|
||||
auto* record_decl = type->getAsCXXRecordDecl();
|
||||
if (!record_decl) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// - The move constructor is defaulted and deleted or non-existent, in
|
||||
// which case overload resolution for a move will call the copy
|
||||
// constructor.
|
||||
if (!record_decl->hasMoveConstructor() ||
|
||||
(!record_decl->hasUserDeclaredMoveConstructor() &&
|
||||
record_decl->defaultedMoveConstructorIsDeleted())) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// - Both move and copy are trivial and not deleted, in which case they
|
||||
// are equivalent.
|
||||
if (record_decl->hasTrivialMoveConstructor() &&
|
||||
!record_decl->defaultedMoveConstructorIsDeleted() &&
|
||||
record_decl->hasTrivialCopyConstructor() &&
|
||||
!record_decl->defaultedCopyConstructorIsDeleted()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Otherwise we need a move, so we pass by var.
|
||||
return false;
|
||||
}
|
||||
|
||||
auto GetPassingModeForCppParameter(const clang::ImplicitConversionSequence& ics,
|
||||
const clang::Expr* arg_expr)
|
||||
-> SemIR::ClangDeclSignature::PassingMode {
|
||||
if (ics.isStandard()) {
|
||||
const auto& scs = ics.Standard;
|
||||
if (scs.ReferenceBinding) {
|
||||
return ComputePassingModeForReferenceBinding(scs);
|
||||
}
|
||||
|
||||
// Most standard conversions can be mapped to Carbon pass by value. The
|
||||
// exception is where the source is an initializing expression of record
|
||||
// type, which we map to pass by var, unless a copy would do the same thing.
|
||||
if (arg_expr->isXValue() && !IsMoveEquivalentToCopy(arg_expr->getType())) {
|
||||
return SemIR::ClangDeclSignature::PassingMode::ByVar;
|
||||
}
|
||||
|
||||
return SemIR::ClangDeclSignature::PassingMode::ByValue;
|
||||
}
|
||||
|
||||
if (ics.isUserDefined()) {
|
||||
const auto& ucs = ics.UserDefined;
|
||||
if (ucs.After.ReferenceBinding) {
|
||||
return ComputePassingModeForReferenceBinding(ucs.After);
|
||||
}
|
||||
|
||||
const auto* ctor =
|
||||
dyn_cast_or_null<clang::CXXConstructorDecl>(ucs.ConversionFunction);
|
||||
if (ctor && ctor->isCopyConstructor()) {
|
||||
// Overload resolution wanted to call a copy constructor to initialize
|
||||
// this parameter. Pass by value instead; we'll copy in the thunk.
|
||||
return SemIR::ClangDeclSignature::PassingMode::ByValue;
|
||||
}
|
||||
|
||||
// We're calling a user-defined conversion, so we're performing
|
||||
// initialization. Pass by move unless the type being initialized doesn't
|
||||
// distinguish moves and copies.
|
||||
return IsMoveEquivalentToCopy(ucs.After.getToType(2))
|
||||
? SemIR::ClangDeclSignature::PassingMode::ByValue
|
||||
: SemIR::ClangDeclSignature::PassingMode::ByVar;
|
||||
}
|
||||
|
||||
// TODO: Support ellipsis conversion sequences.
|
||||
CARBON_FATAL("Unexpected kind of implicit conversion sequence");
|
||||
}
|
||||
|
||||
// Computes the signature for a C++ function candidate based on the conversions
|
||||
// performed on the arguments.
|
||||
auto ComputeClangDeclSignatureFromBestViableFunction(
|
||||
Context& context, clang::OverloadCandidateSet::iterator candidate,
|
||||
clang::Expr* self_expr, llvm::ArrayRef<clang::Expr*> arg_exprs,
|
||||
SemIR::ClangDeclSignature::Kind kind) -> SemIR::ClangDeclSignatureId {
|
||||
SemIR::ClangDeclSignature signature;
|
||||
signature.kind = kind;
|
||||
signature.num_params = static_cast<int32_t>(arg_exprs.size());
|
||||
signature.passing_modes.reserve(signature.num_params);
|
||||
|
||||
for (auto [i, arg_expr] : llvm::enumerate(arg_exprs)) {
|
||||
// Compute which conversion sequence corresponds to this argument.
|
||||
// TODO: Clang should expose a way to compute this.
|
||||
int conversion_index = i;
|
||||
if (auto* method = dyn_cast<clang::CXXMethodDecl>(candidate->Function)) {
|
||||
if (method->isStatic()) {
|
||||
// Static methods get an object parameter conversion at index 0, even
|
||||
// though there's no argument.
|
||||
++conversion_index;
|
||||
}
|
||||
}
|
||||
|
||||
signature.passing_modes.push_back(GetPassingModeForCppParameter(
|
||||
candidate->Conversions[conversion_index], arg_expr));
|
||||
}
|
||||
|
||||
if (IsObjectMemberFunction(*candidate->Function)) {
|
||||
signature.self_passing_mode =
|
||||
GetPassingModeForCppParameter(candidate->Conversions[0], self_expr);
|
||||
}
|
||||
|
||||
return context.clang_decl_signatures().Add(std::move(signature));
|
||||
}
|
||||
|
||||
auto PerformCppOverloadResolution(
|
||||
Context& context, SemIR::LocId loc_id,
|
||||
const SemIR::CppOverloadSet& overload_set,
|
||||
@@ -179,9 +312,12 @@ auto PerformCppOverloadResolution(
|
||||
case clang::OverloadingResult::OR_Success: {
|
||||
CARBON_CHECK(best_viable_fn->Function);
|
||||
CARBON_CHECK(!best_viable_fn->RewriteKind);
|
||||
SemIR::ClangDeclSignatureId signature_id =
|
||||
ComputeClangDeclSignatureFromBestViableFunction(
|
||||
context, best_viable_fn, self_expr, arg_exprs);
|
||||
|
||||
SemIR::InstId result_id = ImportCppFunctionDecl(
|
||||
context, loc_id, best_viable_fn->Function,
|
||||
{.num_params = static_cast<int32_t>(arg_exprs.size())});
|
||||
context, loc_id, best_viable_fn->Function, signature_id);
|
||||
if (result_id != SemIR::ErrorInst::InstId) {
|
||||
CheckCppOverloadAccess(
|
||||
context, loc_id, best_viable_fn->FoundDecl,
|
||||
|
||||
Reference in New Issue
Block a user