Skip to content

Commit 7e76003

Browse files
authored
Merge pull request #1541 from Nadrieril/reconstruct-copy-for-deref
Remove noretag pointer copies in elaborated MIR
2 parents 44ffb20 + 5a00c26 commit 7e76003

83 files changed

Lines changed: 646 additions & 385 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎charon-ml/src/PrintFmt.ml‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1617,7 +1617,8 @@ and pp_aggregate (env : fmt_env) (agg : aggregate_kind) (fmt : Format.formatter)
16171617

16181618
and pp_rvalue (env : fmt_env) (fmt : Format.formatter) (rv : rvalue) : unit =
16191619
match rv with
1620-
| Use (op, _) -> pp_operand env fmt op
1620+
| Use (op, NoRetag) -> Format.fprintf fmt "noretag %a" (pp_operand env) op
1621+
| Use (op, YesRetag) -> pp_operand env fmt op
16211622
| RvRef (p, bk, op) -> begin
16221623
let p = place_to_string env p in
16231624
let borrow_kind =

‎charon/src/pretty/fmt_with_ctx.rs‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2218,7 +2218,12 @@ impl_display_via_ctx!(Rvalue);
22182218
impl<C: AstFormatter> FmtWithCtx<C> for Rvalue {
22192219
fn fmt_with_ctx(&self, ctx: &C, f: &mut fmt::Formatter<'_>) -> fmt::Result {
22202220
match self {
2221-
Rvalue::Use(x, _) => write!(f, "{}", x.with_ctx(ctx)),
2221+
Rvalue::Use(x, retag) => {
2222+
if let WithRetag::No = retag {
2223+
write!(f, "noretag ")?;
2224+
}
2225+
write!(f, "{}", x.with_ctx(ctx))
2226+
}
22222227
Rvalue::Ref {
22232228
place,
22242229
kind: borrow_kind,

‎charon/src/transform/mod.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ pub mod resugar {
3939
pub mod move_asserts_to_statements;
4040
pub mod reconstruct_asserts;
4141
pub mod reconstruct_box_derefs;
42+
pub mod reconstruct_copy_for_deref;
4243
pub mod reconstruct_fallible_operations;
4344
pub mod reconstruct_intrinsics;
4445
pub mod reconstruct_matches;
@@ -165,6 +166,8 @@ pub fn run_transformation_passes(options: &CliOpts, ctx: &mut TransformCtx) {
165166
// of the CFG.
166167
// This must be done early as some resugaring passes depend on it.
167168
CowBox::Borrowed(&control_flow::merge_goto_chains::Transform),
169+
// Undo the splitting of places at derefs done in elaborated MIR.
170+
CowBox::Borrowed(&resugar::reconstruct_copy_for_deref::Transform),
168171
// Remove overflow/div-by-zero/bounds checks since they are already part of the
169172
// arithmetic/array operation in the semantics of (U)LLBC.
170173
// **WARNING**: this pass uses the fact that the dynamic checks introduced by Rustc use a
Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
//! Reconstruct places that rustc split with `CopyForDeref` in elaborated MIR.
2+
//!
3+
//! A statement like `*tuple.1 = x` can become `_tmp = noretag copy tuple.1; *_tmp = x`.
4+
//! The copy only reads the pointer; we put the dereference back on `tuple.1`. This also
5+
//! applies to shared references and boxes, and to reads of pointer metadata.
6+
use std::ops::ControlFlow;
7+
8+
use crate::ids::IndexVec;
9+
use crate::transform::TransformCtx;
10+
use crate::transform::ctx::UllbcPass;
11+
use crate::ullbc_ast::*;
12+
13+
#[derive(Default)]
14+
struct CopyInfo {
15+
assignment: Option<(StmtLoc, Place)>,
16+
use_loc: Option<StmtLoc>,
17+
/// Whether this local is used in any way that doesn't allow the merging we want.
18+
invalid: bool,
19+
}
20+
21+
#[derive(Visitor)]
22+
struct UseCollector<'a> {
23+
body: &'a ExprBody,
24+
copies: &'a mut IndexVec<LocalId, CopyInfo>,
25+
has_candidate: bool,
26+
current_st: Option<StmtLoc>,
27+
}
28+
29+
impl VisitBody for UseCollector<'_> {
30+
fn visit_place(&mut self, place: &Place) -> ControlFlow<Self::Break> {
31+
if let Some((subplace, ProjectionElem::Deref | ProjectionElem::PtrMetadata)) =
32+
place.as_projection()
33+
&& let Some(local) = subplace.as_local()
34+
{
35+
let info = &mut self.copies[local];
36+
if let Some(loc) = self.current_st
37+
&& (info.use_loc.is_none() || info.use_loc == self.current_st)
38+
{
39+
info.use_loc = self.current_st;
40+
// We conservatively skip replacing into a statement that has by-move operands, to
41+
// avoid cases like:
42+
// tmp = noretag copy pair._0
43+
// out = (move pair._0, copy (*tmp))
44+
self.body[loc].dyn_visit_in_body(|operand: &Operand| {
45+
info.invalid |= matches!(operand, Operand::Move(_));
46+
});
47+
} else {
48+
info.invalid = true;
49+
}
50+
// Don't visit the local.
51+
return ControlFlow::Continue(());
52+
}
53+
54+
if let Some(local) = place.as_local() {
55+
// If we get to here then this is an invalid use.
56+
self.copies[local].invalid = true;
57+
}
58+
self.visit_inner(place)
59+
}
60+
61+
fn visit_ullbc_statement(&mut self, st: &Statement) -> ControlFlow<Self::Break> {
62+
if let StatementKind::Assign(dest, rvalue) = &st.kind
63+
&& let Some(local) = dest.as_local()
64+
&& let Some(loc) = self.current_st
65+
{
66+
let info = &mut self.copies[local];
67+
if info.assignment.is_some() {
68+
info.invalid = true;
69+
} else if let Rvalue::Use(Operand::Copy(source), WithRetag::No) = rvalue
70+
&& (matches!(source.ty().kind(), TyKind::Ref(..)) || source.ty().is_box())
71+
&& !info.invalid
72+
{
73+
info.assignment = Some((loc, source.clone()));
74+
self.has_candidate = true;
75+
} else {
76+
info.invalid = true;
77+
}
78+
self.visit(rvalue)
79+
} else {
80+
self.visit_inner(st)
81+
}
82+
}
83+
}
84+
85+
pub struct Transform;
86+
87+
impl UllbcPass for Transform {
88+
fn transform_body(&self, _ctx: &mut TransformCtx, body: &mut ExprBody) {
89+
let mut copies: IndexVec<LocalId, CopyInfo> =
90+
body.locals.locals.map_ref(|_| CopyInfo::default());
91+
92+
// Look for locals that are assigned exactly once with a non-retagging copy. A local is
93+
// eligible only if every use is beneath a dereference or a metadata projection.
94+
let mut collector = UseCollector {
95+
body,
96+
copies: &mut copies,
97+
has_candidate: false,
98+
current_st: None,
99+
};
100+
for (block, data) in body.body.iter_enumerated() {
101+
for (statement, st) in data.statements.iter().enumerate() {
102+
collector.current_st = Some(StmtLoc::new(block, statement));
103+
collector.visit(st);
104+
}
105+
collector.current_st = None;
106+
collector.visit(&data.terminator);
107+
}
108+
if !collector.has_candidate {
109+
return;
110+
}
111+
112+
// Inlining the source is safe only if nothing can change it between the
113+
// pointer read and its use. Nops do not affect that ordering.
114+
let uninterrupted = |body: &ExprBody, before: StmtLoc, after: StmtLoc| {
115+
before.block == after.block
116+
&& before.statement < after.statement
117+
&& body.body[before.block].statements[before.statement + 1..after.statement]
118+
.iter()
119+
.all(|st| st.kind.is_nop())
120+
};
121+
let mut replacements: IndexMap<LocalId, Place> = IndexMap::new();
122+
for (local, info) in copies.iter_enumerated() {
123+
if !info.invalid
124+
&& let Some((assignment, source)) = &info.assignment
125+
&& let Some(use_loc) = info.use_loc
126+
&& uninterrupted(body, *assignment, use_loc)
127+
{
128+
replacements.insert(local, source.clone());
129+
body[*assignment].kind = StatementKind::Nop;
130+
}
131+
}
132+
if replacements.is_empty() {
133+
return;
134+
}
135+
136+
body.body.dyn_visit_in_body_mut(|place: &mut Place| {
137+
// Keep the projection and replace only its base; the visitor reaches
138+
// inner projections on its own.
139+
if let PlaceKind::Projection(
140+
subplace,
141+
ProjectionElem::Deref | ProjectionElem::PtrMetadata,
142+
) = &mut place.kind
143+
&& let Some(local) = subplace.as_local()
144+
&& let Some(source) = replacements.get(local)
145+
{
146+
**subplace = source.clone();
147+
}
148+
});
149+
}
150+
}

‎charon/tests/cargo/dependencies.out‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,7 @@ fn call_once(_1: {closure}, tupled_args: (u32,)) -> u32
167167
storage_live(_0)
168168
storage_live(y)
169169
storage_live(_5)
170-
y = move tupled_args._0
170+
y = noretag move tupled_args._0
171171
storage_live(_4)
172172
_4 = copy y
173173
_5 = copy _4 checked.+ const 1u32

‎charon/tests/ui/arrays.out‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -385,7 +385,7 @@ where
385385
storage_live(_6)
386386
storage_live(_7)
387387
_0 = ()
388-
_2 = copy _1.metadata
388+
_2 = noretag copy _1.metadata
389389
_3 = const 0usize
390390
loop {
391391
_7 = copy _3 == copy _2
@@ -2969,7 +2969,7 @@ fn slice_pattern_4<'_0>(x: &'_0 [()])
29692969
storage_live(_4)
29702970
storage_live(_5)
29712971
_0 = ()
2972-
_3 = copy x.metadata
2972+
_3 = noretag copy x.metadata
29732973
_2 = move _3
29742974
_4 = const 1usize
29752975
_5 = move _2 == move _4

‎charon/tests/ui/associated_types/closure-inside-impl-with-bound-with-assoc-ty.out‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ where
7777
storage_live(_0)
7878
storage_live(_x)
7979
_0 = ()
80-
_x = move tupled_args._0
80+
_x = noretag move tupled_args._0
8181
_0 = ()
8282
storage_dead(_x)
8383
storage_dead(tupled_args)

‎charon/tests/ui/closures.out‎

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -576,7 +576,7 @@ fn {impl Fn<(u32,), u32> for test_crate::test_closure_u32::{closure}}::call<'_0>
576576

577577
storage_live(_0)
578578
storage_live(x)
579-
x = move tupled_args._0
579+
x = noretag move tupled_args._0
580580
_0 = copy x
581581
storage_dead(x)
582582
storage_dead(tupled_args)
@@ -701,8 +701,8 @@ fn {impl Fn<(u32, u32), u32> for test_crate::test_closure_u32s::{closure}}::call
701701
storage_live(x)
702702
storage_live(y)
703703
storage_live(_7)
704-
x = move tupled_args._0
705-
y = move tupled_args._1
704+
x = noretag move tupled_args._0
705+
y = noretag move tupled_args._1
706706
storage_live(_5)
707707
_5 = copy x
708708
storage_live(_6)
@@ -837,7 +837,7 @@ fn {impl Fn<(&'_0 u32,), &'_0 u32> for test_crate::test_closure_ref_u32::{closur
837837

838838
storage_live(_0)
839839
storage_live(y)
840-
y = move tupled_args._0
840+
y = noretag move tupled_args._0
841841
_0 = copy y
842842
storage_dead(y)
843843
storage_dead(tupled_args)
@@ -968,7 +968,7 @@ where
968968

969969
storage_live(_0)
970970
storage_live(x)
971-
x = move tupled_args._0
971+
x = noretag move tupled_args._0
972972
_0 = copy x
973973
storage_dead(x)
974974
storage_dead(tupled_args)
@@ -1121,7 +1121,7 @@ where
11211121

11221122
storage_live(_0)
11231123
storage_live(y)
1124-
y = move tupled_args._0
1124+
y = noretag move tupled_args._0
11251125
_0 = copy y
11261126
storage_dead(y)
11271127
storage_dead(tupled_args)
@@ -1265,7 +1265,7 @@ fn {impl Fn<(u32,), u32> for test_crate::test_map_option2::{closure}}::call<'_0>
12651265
storage_live(_0)
12661266
storage_live(x)
12671267
storage_live(_5)
1268-
x = move tupled_args._0
1268+
x = noretag move tupled_args._0
12691269
storage_live(_4)
12701270
_4 = copy x
12711271
_5 = copy _4 panic.+ const 1u32
@@ -1773,7 +1773,7 @@ fn {impl Fn<(u32,), u32> for test_crate::test_map_option3::{closure}}::call<'_0>
17731773
storage_live(_0)
17741774
storage_live(x)
17751775
storage_live(_5)
1776-
x = move tupled_args._0
1776+
x = noretag move tupled_args._0
17771777
storage_live(_4)
17781778
_4 = copy x
17791779
_5 = copy _4 panic.+ const 1u32
@@ -1896,7 +1896,7 @@ where
18961896

18971897
storage_live(_0)
18981898
storage_live(x)
1899-
x = move tupled_args._0
1899+
x = noretag move tupled_args._0
19001900
_0 = copy (*(*x))
19011901
storage_dead(x)
19021902
storage_dead(tupled_args)
@@ -1953,7 +1953,7 @@ where
19531953

19541954
storage_live(_0)
19551955
storage_live(x)
1956-
x = move tupled_args._0
1956+
x = noretag move tupled_args._0
19571957
_0 = copy (*(*x))
19581958
storage_dead(x)
19591959
storage_dead(tupled_args)
@@ -2096,7 +2096,7 @@ where
20962096
storage_live(z)
20972097
storage_live(_7)
20982098
storage_live(_9)
2099-
z = move tupled_args._0
2099+
z = noretag move tupled_args._0
21002100
storage_live(_4)
21012101
storage_live(_5)
21022102
_5 = copy (*(*_1)._0)
@@ -2183,7 +2183,7 @@ where
21832183

21842184
storage_live(_0)
21852185
storage_live(x)
2186-
x = move tupled_args._0
2186+
x = noretag move tupled_args._0
21872187
storage_live(_4)
21882188
_4 = &x
21892189
_0 = TraitClause1::clone<'4>(move _4)
@@ -2276,7 +2276,7 @@ fn {impl FnMut<(i32,), i32> for test_crate::test_array_map::{closure}}::call_mut
22762276

22772277
storage_live(_0)
22782278
storage_live(v)
2279-
v = move tupled_args._0
2279+
v = noretag move tupled_args._0
22802280
_0 = copy v
22812281
storage_dead(v)
22822282
storage_dead(tupled_args)
@@ -2368,7 +2368,7 @@ where
23682368
storage_live(x)
23692369
storage_live(_5)
23702370
_0 = ()
2371-
x = move tupled_args._0
2371+
x = noretag move tupled_args._0
23722372
storage_live(_4)
23732373
_4 = copy (*x)
23742374
_5 = copy (*(*_1)._0) panic.+ copy _4

‎charon/tests/ui/closures_with_where.out‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ where
105105

106106
storage_live(_0)
107107
storage_live(i)
108-
i = move tupled_args._0
108+
i = noretag move tupled_args._0
109109
storage_live(_4)
110110
_4 = copy i
111111
_0 = TraitClause1::of_usize(move _4)

‎charon/tests/ui/consts/evaluate-consts-inline.out‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,7 @@ pub fn inline_ref_scalar() -> &'static i32
132132

133133
storage_live(_0)
134134
storage_live(_1)
135-
_1 = const 42i32
135+
_1 = noretag const 42i32
136136
storage_live(_2)
137137
_2 = &_1
138138
_0 = move _2

0 commit comments

Comments
 (0)