Skip to content

Commit a554a35

Browse files
authored
Create storage in caller for by-value non-trivial arguments (#694)
For non-trivial by-value arguments, create the storage in the caller and pass a `Ptr<T>` insted of `T` to the function. Trivial by-value arguments continue to pass `T`. Pass a `Ptr<T>` instead of `Value<T>` to the callee so that the caller continues having ownership. This is important later when we fix the destructor calls.
1 parent e426aed commit a554a35

19 files changed

Lines changed: 184 additions & 153 deletions

‎cpp2rust/converter/converter.cpp‎

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -334,8 +334,9 @@ Converter::MaterializeTemp(const std::string &binding_name,
334334
std::string value;
335335
{
336336
ScopedPush init_type(curr_init_type_, pointee);
337-
value = retain_bound_temporaries_ ? ConvertFreshRValue(expr, pointee)
338-
: ConvertRValue(expr, pointee);
337+
value = retain_bound_temporaries_ || !param_type->isReferenceType()
338+
? ConvertFreshRValue(expr, pointee)
339+
: ConvertRValue(expr, pointee);
339340
}
340341
auto type_str = ToStringBase(pointee);
341342
bool is_static = in_const_initializer_ && !declarations;
@@ -405,7 +406,7 @@ Converter::ConvertFunctionPointerType(const clang::FunctionProtoType *proto) {
405406
result += ',';
406407
}
407408
for (auto p_ty : proto->param_types()) {
408-
result += ToString(p_ty);
409+
result += ToString(GetPassedParamType(ctx_, p_ty));
409410
result += ',';
410411
}
411412
if (proto->isVariadic()) {
@@ -616,7 +617,7 @@ bool Converter::NeedsMut(const clang::VarDecl *decl, clang::QualType type,
616617
}
617618

618619
bool Converter::ConvertVarDeclSkipInit(clang::VarDecl *decl) {
619-
auto qual_type = decl->getType();
620+
auto qual_type = GetConvertedVarType(decl);
620621
if (IsVaListType(qual_type) && decl->isLocalVarDecl()) {
621622
StrCat(keyword::kLet, keyword_mut_, GetNamedDeclAsString(decl),
622623
token::kColon);
@@ -2461,7 +2462,9 @@ Converter::CallInfo Converter::CollectCallInfo(clang::CallExpr *expr) {
24612462
: Kind::Hoisted,
24622463
};
24632464
bool is_materialize = clang::isa<clang::MaterializeTemporaryExpr>(arg);
2464-
if (is_materialize && ca.param_type->isReferenceType()) {
2465+
if (UsesReturnSlot(ca.param_type)) {
2466+
ca.kind = Kind::Materialized;
2467+
} else if (is_materialize && ca.param_type->isReferenceType()) {
24652468
ca.kind = Kind::Materialized;
24662469
} else if (is_materialize) {
24672470
ca.kind = Kind::Inline;
@@ -4660,7 +4663,12 @@ void Converter::ConvertCXXConstructExprArgs(clang::CXXConstructExpr *expr) {
46604663
}
46614664
{
46624665
PushBrace brace(*this);
4663-
ConvertVarInit(ctor->getParamDecl(i)->getType(), arg);
4666+
auto type = ctor->getParamDecl(i)->getType();
4667+
if (UsesReturnSlot(type)) {
4668+
StrCat(EmitMaterializedTempBinding(type, arg));
4669+
} else {
4670+
ConvertVarInit(type, arg);
4671+
}
46644672
}
46654673
StrCat(token::kComma);
46664674
}

‎cpp2rust/converter/converter_lib.cpp‎

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -848,7 +848,7 @@ static bool HasFieldWithMoveAssign(const clang::RecordDecl *decl) {
848848

849849
// Whether a defaulted move assignment of decl isn't a copy assignment.
850850
static bool NeedsDefaultedMoveAssignment(const clang::CXXRecordDecl *decl) {
851-
return !decl->isTriviallyCopyable() || !HasDefaultedCopyAssignment(decl) ||
851+
return !decl->canPassInRegisters() || !HasDefaultedCopyAssignment(decl) ||
852852
HasFieldWithMoveAssign(decl);
853853
}
854854

@@ -902,7 +902,7 @@ bool HasMoveAssignOperator(const clang::RecordDecl *decl) {
902902
// fields: when the record has a copy constructor, or a field (or element of
903903
// an array field) has a copy assignment operator.
904904
static bool NeedsDefaultedCopyAssignment(const clang::CXXRecordDecl *decl) {
905-
return !decl->isTriviallyCopyable() || GetUserDefinedCopyConstructor(decl) ||
905+
return !decl->canPassInRegisters() || GetUserDefinedCopyConstructor(decl) ||
906906
llvm::any_of(decl->fields(), [](const clang::FieldDecl *field) {
907907
auto *record =
908908
field->getType()->getBaseElementTypeUnsafe()->getAsRecordDecl();
@@ -1063,7 +1063,7 @@ static const clang::Expr *IgnorePlacementWrappers(const clang::Expr *init) {
10631063
bool UsesReturnSlot(clang::QualType type) {
10641064
auto *record = type->getAsCXXRecordDecl();
10651065
return record && record->hasDefinition() && IsUserDefinedDecl(record) &&
1066-
!record->isLambda() && !record->isTriviallyCopyable();
1066+
!record->isLambda() && !record->canPassInRegisters();
10671067
}
10681068

10691069
bool IsReturnSlotCall(const clang::Expr *expr) {
@@ -1889,11 +1889,23 @@ const clang::FieldDecl *AsLambdaCaptureThis(const clang::FunctionDecl *fn) {
18891889
return nullptr;
18901890
}
18911891

1892+
clang::QualType GetPassedParamType(const clang::ASTContext &ctx,
1893+
clang::QualType type) {
1894+
return UsesReturnSlot(type) ? ctx.getLValueReferenceType(type) : type;
1895+
}
1896+
1897+
clang::QualType GetConvertedVarType(const clang::ValueDecl *decl) {
1898+
if (clang::isa<clang::ParmVarDecl>(decl)) {
1899+
return GetPassedParamType(decl->getASTContext(), decl->getType());
1900+
}
1901+
return decl->getType();
1902+
}
1903+
18921904
clang::QualType GetDeclRefType(const clang::FunctionDecl *fn,
18931905
const clang::Expr *expr,
18941906
const clang::ValueDecl *decl) {
18951907
auto field = AsLambdaCaptureField(fn, expr);
1896-
return field ? field->getType() : decl->getType();
1908+
return field ? field->getType() : GetConvertedVarType(decl);
18971909
}
18981910

18991911
bool IsUserOperatorCall(const clang::CXXOperatorCallExpr *expr) {

‎cpp2rust/converter/converter_lib.h‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -383,6 +383,11 @@ clang::Expr *AsLambdaUncapturedConstant(const clang::FunctionDecl *fn,
383383

384384
const clang::FieldDecl *AsLambdaCaptureThis(const clang::FunctionDecl *fn);
385385

386+
clang::QualType GetPassedParamType(const clang::ASTContext &ctx,
387+
clang::QualType type);
388+
389+
clang::QualType GetConvertedVarType(const clang::ValueDecl *decl);
390+
386391
clang::QualType GetDeclRefType(const clang::FunctionDecl *fn,
387392
const clang::Expr *expr,
388393
const clang::ValueDecl *decl);

‎cpp2rust/converter/models/boxed_vars.cpp‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ bool IsFlatVec(clang::QualType type) {
3838
// and iterators translated to pointers, unless they have a destructor, which
3939
// is called with a pointer to them.
4040
bool CanUnbox(clang::ASTContext &ctx, const clang::VarDecl *decl) {
41-
auto type = decl->getType();
41+
auto type = GetConvertedVarType(decl);
4242
if (IsFlatVec(type)) {
4343
// Vectors are flat Vecs.
4444
} else if (type->isConstantArrayType()) {

‎cpp2rust/converter/models/converter_refcount.cpp‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -930,7 +930,7 @@ void ConverterRefCount::EmitFunctionPreamble(clang::FunctionDecl *decl) {
930930
}
931931
for (auto *param : DefinitionParameters(decl)) {
932932
// Unboxed parameters are used in place.
933-
if (param->getType()->isReferenceType() || IsUnboxedVar(param)) {
933+
if (GetConvertedVarType(param)->isReferenceType() || IsUnboxedVar(param)) {
934934
continue;
935935
}
936936
auto name = GetNamedDeclAsString(param);

‎tests/std/basic/out/refcount/basic.def.odr.rs‎

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -778,13 +778,9 @@ impl Default for p9_unused_implicit_assignment_HasUndefinedCopyAssignment {
778778
VaArg,
779779
FnPtrArg,
780780
Destructible,
781-
Memberwise,
782-
CopyConstructible,
783-
MoveConstructible,
784-
Swappable,
781+
Copyable,
785782
Default,
786783
)]
787-
#[memberwise(copy_assign, move_assign)]
788784
#[byte_size(1)]
789785
pub struct p9_unused_implicit_assignment_HasMemberWithUndefinedCopyAssignment {
790786
#[offset(0)]

‎tests/std/basic/out/unsafe/basic.def.odr.rs‎

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -720,13 +720,9 @@ impl Default for p9_unused_implicit_assignment_HasUndefinedCopyAssignment {
720720
FnPtrArg,
721721
ZeroInitializationUnsafe,
722722
DestructibleUnsafe,
723-
MemberwiseUnsafe,
724-
CopyConstructibleUnsafe,
725-
MoveConstructibleUnsafe,
726-
SwappableUnsafe,
723+
CopyableUnsafe,
727724
Default,
728725
)]
729-
#[memberwise(copy_assign, move_assign)]
730726
pub struct p9_unused_implicit_assignment_HasMemberWithUndefinedCopyAssignment {
731727
pub m: p9_unused_implicit_assignment_HasUndefinedCopyAssignment,
732728
}

‎tests/unit/out/refcount/copy_ctor.rs‎

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -290,8 +290,8 @@ pub fn touch_1(mut t: Ptr<Tracked>) {
290290
__v.prefix_inc();
291291
});
292292
}
293-
pub fn by_value_2(mut c: Counted) -> i32 {
294-
return c.v;
293+
pub fn by_value_2(c: Ptr<Counted>) -> i32 {
294+
return c.with(|__s| __s.v);
295295
}
296296
pub fn make_3(this: Ptr<Counted>, mut v: i32) {
297297
let c: Value<Counted> = Rc::new(RefCell::new(<Counted>::zero_init()));
@@ -318,11 +318,9 @@ fn main_0() -> i32 {
318318
);
319319
assert!(
320320
(({
321-
by_value_2({
322-
let __v: Value<Counted> = Rc::new(RefCell::new(<Counted>::zero_init()));
323-
CopyConstructible::copy_constructor(&__v.as_pointer(), { a.as_pointer() });
324-
Rc::try_unwrap(__v).ok().unwrap().into_inner()
325-
})
321+
let _c: Value<Counted> = Rc::new(RefCell::new(<Counted>::zero_init()));
322+
CopyConstructible::copy_constructor(&_c.as_pointer(), { a.as_pointer() });
323+
by_value_2(_c.as_pointer())
326324
}) == 1)
327325
);
328326
assert!((copies_0.with(|rc| *rc.borrow()) == 4));

‎tests/unit/out/refcount/destructor_params.rs‎

Lines changed: 40 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -37,14 +37,12 @@ impl Destructible for S {
3737
last_1.with(|rc| *rc.borrow_mut() = (*this).with(|__s| __s.v));
3838
}
3939
}
40-
pub fn by_value_2(s: S) -> i32 {
41-
let s: Value<S> = Rc::new(RefCell::new(s));
40+
pub fn by_value_2(s: Ptr<S>) -> i32 {
4241
assert!((destroyed_0.with(|rc| *rc.borrow()) == 0));
43-
return { (*s.borrow()).v };
42+
return s.with(|__s| __s.v);
4443
}
45-
pub fn with_default_3(s: S) -> i32 {
46-
let s: Value<S> = Rc::new(RefCell::new(s));
47-
return { (*s.borrow()).v };
44+
pub fn with_default_3(s: Ptr<S>) -> i32 {
45+
return s.with(|__s| __s.v);
4846
}
4947
#[derive(
5048
Copy,
@@ -72,26 +70,51 @@ fn main_0() -> i32 {
7270
let s: Value<S> = Rc::new(RefCell::new(S { v: 1 }));
7371
let _dtor_s =
7472
std::mem::DropGuard::new(s.clone(), |__p| Destructible::destroy(&__p.as_pointer()));
75-
assert!((({ by_value_2({ (*s.borrow()).clone() },) }) == 1));
73+
assert!(
74+
({
75+
(({
76+
let _s: Value<S> = Rc::new(RefCell::new((*s.borrow()).clone()));
77+
by_value_2(_s.as_pointer())
78+
}) == 1)
79+
})
80+
);
7681
assert!(
7782
(destroyed_0.with(|rc| *rc.borrow()) == 1) && (last_1.with(|rc| *rc.borrow()) == 1)
7883
);
7984
}
8085
assert!((destroyed_0.with(|rc| *rc.borrow()) == 2));
8186
destroyed_0.with(|rc| *rc.borrow_mut() = 0);
82-
assert!((({ by_value_2(S { v: 2 },) }) == 2));
87+
assert!(
88+
(({
89+
let _s: Value<S> = Rc::new(RefCell::new(S { v: 2 }));
90+
by_value_2(_s.as_pointer())
91+
}) == 2)
92+
);
8393
assert!((destroyed_0.with(|rc| *rc.borrow()) == 1) && (last_1.with(|rc| *rc.borrow()) == 2));
8494
destroyed_0.with(|rc| *rc.borrow_mut() = 0);
85-
assert!((({ with_default_3(S { v: 5 },) }) == 5));
95+
assert!(
96+
(({
97+
let _s: Value<S> = Rc::new(RefCell::new(S { v: 5 }));
98+
with_default_3(_s.as_pointer())
99+
}) == 5)
100+
);
86101
assert!((destroyed_0.with(|rc| *rc.borrow()) == 1) && (last_1.with(|rc| *rc.borrow()) == 5));
87102
destroyed_0.with(|rc| *rc.borrow_mut() = 0);
88103
{
89104
let h: Value<Holder> = Rc::new(RefCell::new(<Holder>::zero_init()));
90-
HolderImpl::construct(&h.as_pointer(), { S { v: 3 } });
105+
{
106+
let __tmp_0: Value<S> = Rc::new(RefCell::new(S { v: 3 }));
107+
HolderImpl::construct(&h.as_pointer(), { __tmp_0.as_pointer() })
108+
};
91109
assert!(
92110
(destroyed_0.with(|rc| *rc.borrow()) == 1) && (last_1.with(|rc| *rc.borrow()) == 3)
93111
);
94-
assert!((({ HolderImpl::add(&h.as_pointer(), S { v: 4 },) }) == 7));
112+
assert!(
113+
(({
114+
let _s: Value<S> = Rc::new(RefCell::new(S { v: 4 }));
115+
HolderImpl::add(&h.as_pointer(), _s.as_pointer())
116+
}) == 7)
117+
);
95118
assert!(
96119
(destroyed_0.with(|rc| *rc.borrow()) == 2) && (last_1.with(|rc| *rc.borrow()) == 4)
97120
);
@@ -100,17 +123,15 @@ fn main_0() -> i32 {
100123
return 0;
101124
}
102125
pub trait HolderImpl {
103-
fn construct(&self, s: S);
104-
fn add(&self, s: S) -> i32;
126+
fn construct(&self, s: Ptr<S>);
127+
fn add(&self, s: Ptr<S>) -> i32;
105128
}
106129
impl HolderImpl for Ptr<Holder> {
107-
fn construct(&self, s: S) {
108-
let s: Value<S> = Rc::new(RefCell::new(s));
109-
field!((*self), v).write({ (*s.borrow()).v });
130+
fn construct(&self, s: Ptr<S>) {
131+
field!((*self), v).write(s.with(|__s| __s.v));
110132
}
111-
fn add(&self, s: S) -> i32 {
112-
let s: Value<S> = Rc::new(RefCell::new(s));
113-
return ((*self).with(|__s| __s.v) + { (*s.borrow()).v });
133+
fn add(&self, s: Ptr<S>) -> i32 {
134+
return ((*self).with(|__s| __s.v) + s.with(|__s| __s.v));
114135
}
115136
}
116137
pub fn __cpp2rust_init_globals() {

‎tests/unit/out/refcount/fn_ptr_struct.rs‎

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -75,9 +75,8 @@ pub fn make_move_only_2(this: Ptr<MoveOnly>) {
7575
MoveOnlyImpl::construct(&this, { 4 });
7676
return;
7777
}
78-
pub fn scale_move_only_3(this: Ptr<MoveOnly>, x: MoveOnly) {
79-
let x: Value<MoveOnly> = Rc::new(RefCell::new(x));
80-
MoveOnlyImpl::construct(&this, { (({ MoveOnlyImpl::get(&x.as_pointer()) }) * 10) });
78+
pub fn scale_move_only_3(this: Ptr<MoveOnly>, x: Ptr<MoveOnly>) {
79+
MoveOnlyImpl::construct(&this, { (({ MoveOnlyImpl::get(&x) }) * 10) });
8180
return;
8281
}
8382
pub fn main() {
@@ -113,15 +112,13 @@ fn main_0() -> i32 {
113112
let m: Value<MoveOnly> = Rc::new(RefCell::new(<MoveOnly>::zero_init()));
114113
({ mk.call(Ptr::clone(&m.as_pointer())) });
115114
assert!((({ MoveOnlyImpl::get(&m.as_pointer(),) }) == 4));
116-
let mut sc: FnPtr<fn(Ptr<MoveOnly>, MoveOnly)> =
117-
FnPtr::<fn(Ptr<MoveOnly>, MoveOnly)>::new(scale_move_only_3);
115+
let mut sc: FnPtr<fn(Ptr<MoveOnly>, Ptr<MoveOnly>)> =
116+
FnPtr::<fn(Ptr<MoveOnly>, Ptr<MoveOnly>)>::new(scale_move_only_3);
118117
let n: Value<MoveOnly> = Rc::new(RefCell::new(<MoveOnly>::zero_init()));
119118
({
120-
sc.call(Ptr::clone(&n.as_pointer()), {
121-
let __v: Value<MoveOnly> = Rc::new(RefCell::new(<MoveOnly>::zero_init()));
122-
MoveConstructible::move_constructor(&__v.as_pointer(), { m.as_pointer() });
123-
Rc::try_unwrap(__v).ok().unwrap().into_inner()
124-
})
119+
let _arg0: Value<MoveOnly> = Rc::new(RefCell::new(<MoveOnly>::zero_init()));
120+
MoveConstructible::move_constructor(&_arg0.as_pointer(), { m.as_pointer() });
121+
sc.call(Ptr::clone(&n.as_pointer()), _arg0.as_pointer())
125122
});
126123
assert!((({ MoveOnlyImpl::get(&n.as_pointer(),) }) == 40));
127124
assert!((({ MoveOnlyImpl::get(&m.as_pointer(),) }) == 0));

0 commit comments

Comments
 (0)