Skip to content

Commit c902b60

Browse files
Evaluate fixed-operand effects before hoisted emplacement construction (#675)
Since a495c8d ("don't require rules to worry about run-time borrow errors"), `GetMappedAsString` may construct an emplaced element (`init`) before the rule body runs. The receiver and the `emplace_hint` hint (the operands before the forwarded pack) are still evaluated later, inside the body. In C++ they are evaluated before the element is constructed. So the translation can copy stale data in both models, and in the refcount model an aliased receiver can panic with "RefCell already mutably borrowed". When a rule always constructs `init` and is called on a receiver, `GetMappedAsString` now marks the receiver and any other non-pack operands that have side effects for binding, before it checks whether `init` must be constructed first. If construction is hoisted, those operands are evaluated once, in C++ order, before construction and before the container is borrowed mutably. Evaluation uses the existing binding code. If construction is not hoisted, the original analysis and output are unchanged. Binding only after the hoisting decision fixes the wrong values but not the aliased-receiver panic, because there the binding is what allows construction to be hoisted. `HasSideEffects` treats library calls as effectful, so hints such as `m.end()` or `m.find(k)` are now also bound first. This keeps their meaning. It adds one iterator binding (and a no-op clone) to the refcount output, which is why `tests/unit/out/refcount/map.rs` changes, with renumbered temporaries. --- Made by [Perfloop](https://app.perfloop.ai). Human sponsor: [Tomás Senart](https://github.com/tsenart). Signed-off-by: Perfloop Agent <agent@perfloop.ai>
1 parent ba04beb commit c902b60

11 files changed

Lines changed: 598 additions & 29 deletions

‎cpp2rust/converter/converter.cpp‎

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5795,17 +5795,30 @@ std::string Converter::GetMappedAsString(clang::Expr *expr, clang::Expr **args,
57955795
ReturnsPointerToArg(all_args[base->n])) {
57965796
bind[base->n] = true;
57975797
}
5798-
5799-
auto first = ArgsToEvaluateFirst(expr, *tgt_ir, all_args, bind);
5798+
// Construction happens inside the C++ call, after its fixed operands.
5799+
// Plan fixed-operand bindings before checking for conflicting init borrows.
5800+
auto num_params = std::min(tgt_ir->params.size(), all_args.size());
5801+
bool always_constructs_init = tgt_ir->alwaysConstructsInit();
5802+
auto init_bind = bind;
5803+
if (always_constructs_init && HasReceiver(expr)) {
5804+
for (size_t i = 0; i < num_params; ++i) {
5805+
init_bind[i] = init_bind[i] || all_args[i]->HasSideEffects(ctx_);
5806+
}
5807+
}
5808+
auto first = ArgsToEvaluateFirst(expr, *tgt_ir, all_args, init_bind);
58005809
// The object that init constructs is constructed first, rather than its
58015810
// arguments evaluated first one by one, and once if the body uses it more
58025811
// than once.
5803-
auto num_params = std::min(tgt_ir->params.size(), all_args.size());
58045812
bool init_first =
5805-
tgt_ir->alwaysConstructsInit() &&
5813+
always_constructs_init &&
58065814
(tgt_ir->initCopies() > 1 ||
58075815
std::find(first.begin() + num_params, first.end(), true) != first.end());
5808-
5816+
if (init_first) {
5817+
bind = std::move(init_bind);
5818+
} else if (init_bind != bind) {
5819+
// A declined plan must not hide bindings needed by the original borrows.
5820+
first = ArgsToEvaluateFirst(expr, *tgt_ir, all_args, bind);
5821+
}
58095822
std::vector<std::string> values, names;
58105823
bool all_by_value = true;
58115824

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// ADDITIONAL_COMPILE_FLAGS: -std=c++17
2+
3+
#include <cstdio>
4+
#include <map>
5+
#include <vector>
6+
using Map = std::map<int, std::vector<int>>;
7+
Map *receiver(Map *m, std::vector<int> *v, int *calls) {
8+
++*calls;
9+
(*v)[2] = 9;
10+
return m;
11+
}
12+
Map::iterator hint(Map *m, std::vector<int> *v, int *calls) {
13+
++*calls;
14+
(*v)[2] = 7;
15+
return m->end();
16+
}
17+
int main() {
18+
for (int select_receiver = 1; select_receiver >= 0; --select_receiver) {
19+
Map m;
20+
std::vector<int> v{1, 2, 3};
21+
int a = 0, b = 0;
22+
if (select_receiver)
23+
receiver(&m, &v, &a)->emplace_hint(hint(&m, &v, &b), 1, v);
24+
else
25+
m.emplace_hint(hint(&m, &v, &b), 1, v);
26+
const std::vector<int> &inserted = m.at(1);
27+
std::printf("receiver=%d hint=%d source=%d inserted=%d\n", a, b, v[2],
28+
inserted[2]);
29+
}
30+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// ADDITIONAL_COMPILE_FLAGS: -std=c++14
2+
3+
#include <cstdio>
4+
#include <vector>
5+
6+
using Rows = std::vector<std::vector<int>>;
7+
8+
Rows *select_rows(Rows *rows, int *calls) {
9+
++*calls;
10+
return rows;
11+
}
12+
13+
int main() {
14+
Rows rows{{1, 2, 3}};
15+
rows.reserve(2);
16+
int calls = 0;
17+
Rows *alias = &rows;
18+
select_rows(alias, &calls)
19+
->emplace_back((*alias)[0].data(), (*alias)[0].data() + 3);
20+
std::printf("calls=%d size=%zu last=%d\n", calls, rows.size(), rows[1][2]);
21+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// ADDITIONAL_COMPILE_FLAGS: -std=c++14
2+
3+
#include <cstdio>
4+
#include <vector>
5+
6+
using Rows = std::vector<std::vector<int>>;
7+
8+
Rows *select_rows(Rows *rows, int *calls) {
9+
++*calls;
10+
(*rows)[0][2] = 9;
11+
return rows;
12+
}
13+
14+
int main() {
15+
for (int bound = 0; bound < 2; ++bound) {
16+
Rows rows{{1, 2, 3}};
17+
rows.reserve(2);
18+
int calls = 0;
19+
if (bound) {
20+
Rows *receiver = select_rows(&rows, &calls);
21+
receiver->emplace_back(rows[0].data(), rows[0].data() + 3);
22+
} else {
23+
select_rows(&rows, &calls)
24+
->emplace_back(rows[0].data(), rows[0].data() + 3);
25+
}
26+
std::printf("source=%d inserted=%d calls=%d\n", rows[0][2], rows[1][2],
27+
calls);
28+
}
29+
}
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
extern crate libcc2rs;
2+
use libcc2rs::*;
3+
use std::cell::RefCell;
4+
use std::collections::BTreeMap;
5+
use std::io::prelude::*;
6+
use std::io::{Read, Seek, Write};
7+
use std::os::fd::AsFd;
8+
use std::rc::{Rc, Weak};
9+
pub fn receiver_0(
10+
mut m: Ptr<Map<i32, (Value<i32>, Value<Vec<i32>>)>>,
11+
mut v: Ptr<Vec<i32>>,
12+
mut calls: Ptr<i32>,
13+
) -> Ptr<Map<i32, (Value<i32>, Value<Vec<i32>>)>> {
14+
calls.with_mut(|__v| {
15+
__v.prefix_inc();
16+
});
17+
index!(v, 2_usize).write(9);
18+
return m;
19+
}
20+
pub fn hint_1(
21+
mut m: Ptr<Map<i32, (Value<i32>, Value<Vec<i32>>)>>,
22+
mut v: Ptr<Vec<i32>>,
23+
mut calls: Ptr<i32>,
24+
) -> BidirectionalIterator<(Value<i32>, Value<Vec<i32>>)> {
25+
calls.with_mut(|__v| {
26+
__v.prefix_inc();
27+
});
28+
index!(v, 2_usize).write(7);
29+
return m.with(|__m: &Map<i32, (Value<i32>, Value<Vec<i32>>)>| __m.end());
30+
}
31+
pub fn main() {
32+
__cpp2rust_init_globals();
33+
libcc2rs::cpp2rust_exit(main_0());
34+
}
35+
fn main_0() -> i32 {
36+
{
37+
let mut select_receiver: i32 = 1;
38+
'loop_: while (select_receiver >= 0) {
39+
let m: Value<Map<i32, (Value<i32>, Value<Vec<i32>>)>> =
40+
Rc::new(RefCell::new(Map::new()));
41+
let v: Value<Vec<i32>> = Rc::new(RefCell::new(Vec::from([1, 2, 3])));
42+
let a: Value<i32> = Rc::new(RefCell::new(0));
43+
let b: Value<i32> = Rc::new(RefCell::new(0));
44+
if (select_receiver != 0) {
45+
{
46+
let mut __tmp_0 =
47+
{ ({ receiver_0((m.as_pointer()), (v.as_pointer()), (a.as_pointer())) }) };
48+
let mut __tmp_1 = {
49+
<BidirectionalIterator<(Value<i32>, Value<Vec<i32>>)>>::from(
50+
({ hint_1((m.as_pointer()), (v.as_pointer()), (b.as_pointer())) }),
51+
)
52+
};
53+
let mut __tmp_2 = {
54+
(
55+
Rc::new(RefCell::new(1)),
56+
Rc::new(RefCell::new(({ (*v.borrow()).clone() }))),
57+
)
58+
};
59+
let _ = (__tmp_1).clone();
60+
Map::emplace((__tmp_0).clone(), &__tmp_2.0.as_pointer(), || __tmp_2).0
61+
};
62+
} else {
63+
{
64+
let mut __tmp_3 = {
65+
<BidirectionalIterator<(Value<i32>, Value<Vec<i32>>)>>::from(
66+
({ hint_1((m.as_pointer()), (v.as_pointer()), (b.as_pointer())) }),
67+
)
68+
};
69+
let mut __tmp_4 = {
70+
(
71+
Rc::new(RefCell::new(1)),
72+
Rc::new(RefCell::new(({ (*v.borrow()).clone() }))),
73+
)
74+
};
75+
let _ = (__tmp_3).clone();
76+
Map::emplace(m.as_pointer(), &__tmp_4.0.as_pointer(), || __tmp_4).0
77+
};
78+
}
79+
let inserted: Ptr<Vec<i32>> = ({
80+
let __tmp_5: Value<i32> = Rc::new(RefCell::new(1));
81+
(*m.borrow())
82+
.get(&__tmp_5.as_pointer())
83+
.expect("out of range!")
84+
.borrow()
85+
.1
86+
.as_pointer()
87+
});
88+
printf!(
89+
b"receiver=%d hint=%d source=%d inserted=%d\n",
90+
(*a.borrow()),
91+
(*b.borrow()),
92+
{ (*v.borrow())[2_usize] },
93+
(index!(inserted, 2_usize).read())
94+
);
95+
select_receiver.prefix_dec();
96+
}
97+
}
98+
0
99+
}
100+
pub fn __cpp2rust_init_globals() {}
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
extern crate libcc2rs;
2+
use libcc2rs::*;
3+
use std::cell::RefCell;
4+
use std::collections::BTreeMap;
5+
use std::io::prelude::*;
6+
use std::io::{Read, Seek, Write};
7+
use std::os::fd::AsFd;
8+
use std::rc::{Rc, Weak};
9+
pub fn select_rows_0(mut rows: Ptr<Vec<Vec<i32>>>, mut calls: Ptr<i32>) -> Ptr<Vec<Vec<i32>>> {
10+
calls.with_mut(|__v| {
11+
__v.prefix_inc();
12+
});
13+
return rows;
14+
}
15+
pub fn main() {
16+
__cpp2rust_init_globals();
17+
libcc2rs::cpp2rust_exit(main_0());
18+
}
19+
fn main_0() -> i32 {
20+
let rows: Value<Vec<Vec<i32>>> = Rc::new(RefCell::new(Vec::from([Vec::from([1, 2, 3])])));
21+
rows.with_mut(|__b0| {
22+
if 2_usize > (*__b0).capacity() as usize {
23+
let len_0 = (*__b0).len();
24+
(*__b0).reserve_exact(2_usize - len_0 as usize);
25+
}
26+
});
27+
let calls: Value<i32> = Rc::new(RefCell::new(0));
28+
let mut alias: Ptr<Vec<Vec<i32>>> = (rows.as_pointer());
29+
{
30+
let mut __tmp_0 = { ({ select_rows_0((alias).clone(), (calls.as_pointer())) }) };
31+
let mut __tmp_3 = {
32+
{
33+
let mut __tmp_1 = { (alias).decay().offset(0_usize).decay() };
34+
let mut __tmp_2 = { (alias).decay().offset(0_usize).decay().offset((3) as isize) };
35+
let mut __v = Vec::new();
36+
let mut __it = (__tmp_1).clone();
37+
while __it != __tmp_2 {
38+
__v.push((__it.iter_deref().read()));
39+
__it.iter_inc();
40+
}
41+
__v
42+
}
43+
};
44+
__tmp_0.with_mut(|__v: &mut Vec<Vec<i32>>| __v.push(__tmp_3))
45+
};
46+
printf!(
47+
b"calls=%d size=%zu last=%d\n",
48+
(*calls.borrow()),
49+
(*rows.borrow()).len(),
50+
(index!(elem!(rows.decay(), 1_usize), 2_usize).read())
51+
);
52+
0
53+
}
54+
pub fn __cpp2rust_init_globals() {}
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
extern crate libcc2rs;
2+
use libcc2rs::*;
3+
use std::cell::RefCell;
4+
use std::collections::BTreeMap;
5+
use std::io::prelude::*;
6+
use std::io::{Read, Seek, Write};
7+
use std::os::fd::AsFd;
8+
use std::rc::{Rc, Weak};
9+
pub fn select_rows_0(mut rows: Ptr<Vec<Vec<i32>>>, mut calls: Ptr<i32>) -> Ptr<Vec<Vec<i32>>> {
10+
calls.with_mut(|__v| {
11+
__v.prefix_inc();
12+
});
13+
index!(index!(rows, 0_usize), 2_usize).write(9);
14+
return rows;
15+
}
16+
pub fn main() {
17+
__cpp2rust_init_globals();
18+
libcc2rs::cpp2rust_exit(main_0());
19+
}
20+
fn main_0() -> i32 {
21+
{
22+
let mut bound: i32 = 0;
23+
'loop_: while (bound < 2) {
24+
let rows: Value<Vec<Vec<i32>>> =
25+
Rc::new(RefCell::new(Vec::from([Vec::from([1, 2, 3])])));
26+
rows.with_mut(|__b0| {
27+
if 2_usize > (*__b0).capacity() as usize {
28+
let len_0 = (*__b0).len();
29+
(*__b0).reserve_exact(2_usize - len_0 as usize);
30+
}
31+
});
32+
let calls: Value<i32> = Rc::new(RefCell::new(0));
33+
if (bound != 0) {
34+
let mut receiver: Ptr<Vec<Vec<i32>>> =
35+
({ select_rows_0((rows.as_pointer()), (calls.as_pointer())) });
36+
{
37+
let mut __tmp_2 = {
38+
{
39+
let mut __tmp_0 = { rows.decay().offset(0_usize).decay() };
40+
let mut __tmp_1 =
41+
{ rows.decay().offset(0_usize).decay().offset((3) as isize) };
42+
let mut __v = Vec::new();
43+
let mut __it = (__tmp_0).clone();
44+
while __it != __tmp_1 {
45+
__v.push((__it.iter_deref().read()));
46+
__it.iter_inc();
47+
}
48+
__v
49+
}
50+
};
51+
receiver.with_mut(|__v: &mut Vec<Vec<i32>>| __v.push(__tmp_2))
52+
};
53+
} else {
54+
{
55+
let mut __tmp_3 =
56+
{ ({ select_rows_0((rows.as_pointer()), (calls.as_pointer())) }) };
57+
let mut __tmp_6 = {
58+
{
59+
let mut __tmp_4 = { rows.decay().offset(0_usize).decay() };
60+
let mut __tmp_5 =
61+
{ rows.decay().offset(0_usize).decay().offset((3) as isize) };
62+
let mut __v = Vec::new();
63+
let mut __it = (__tmp_4).clone();
64+
while __it != __tmp_5 {
65+
__v.push((__it.iter_deref().read()));
66+
__it.iter_inc();
67+
}
68+
__v
69+
}
70+
};
71+
__tmp_3.with_mut(|__v: &mut Vec<Vec<i32>>| __v.push(__tmp_6))
72+
};
73+
}
74+
printf!(
75+
b"source=%d inserted=%d calls=%d\n",
76+
(index!(elem!(rows.decay(), 0_usize), 2_usize).read()),
77+
(index!(elem!(rows.decay(), 1_usize), 2_usize).read()),
78+
(*calls.borrow())
79+
);
80+
bound.prefix_inc();
81+
}
82+
}
83+
0
84+
}
85+
pub fn __cpp2rust_init_globals() {}

0 commit comments

Comments
 (0)