Skip to content

Commit 620bf99

Browse files
committed
Auto merge of rust-lang#125910 - scottmcm:single-use-consts, r=<try>
Add `SingleUseConsts` mir-opt pass r? ghost
2 parents 621e957 + d543a8e commit 620bf99

File tree

31 files changed

+1016
-344
lines changed

31 files changed

+1016
-344
lines changed

compiler/rustc_mir_transform/src/const_debuginfo.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,8 @@ pub struct ConstDebugInfo;
1616

1717
impl<'tcx> MirPass<'tcx> for ConstDebugInfo {
1818
fn is_enabled(&self, sess: &rustc_session::Session) -> bool {
19-
sess.mir_opt_level() > 0
19+
// Disabled in favour of `SingleUseConsts`
20+
sess.mir_opt_level() > 2
2021
}
2122

2223
fn run_pass(&self, _tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {

compiler/rustc_mir_transform/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@ mod check_alignment;
106106
pub mod simplify;
107107
mod simplify_branches;
108108
mod simplify_comparison_integral;
109+
mod single_use_consts;
109110
mod sroa;
110111
mod unreachable_enum_branching;
111112
mod unreachable_prop;
@@ -603,6 +604,7 @@ fn run_optimization_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
603604
&gvn::GVN,
604605
&simplify::SimplifyLocals::AfterGVN,
605606
&dataflow_const_prop::DataflowConstProp,
607+
&single_use_consts::SingleUseConsts,
606608
&const_debuginfo::ConstDebugInfo,
607609
&o1(simplify_branches::SimplifyConstCondition::AfterConstProp),
608610
&jump_threading::JumpThreading,
Lines changed: 199 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,199 @@
1+
use rustc_index::{bit_set::BitSet, IndexVec};
2+
use rustc_middle::bug;
3+
use rustc_middle::mir::visit::{MutVisitor, PlaceContext, Visitor};
4+
use rustc_middle::mir::*;
5+
use rustc_middle::ty::TyCtxt;
6+
7+
/// Various parts of MIR building introduce temporaries that are commonly not needed.
8+
///
9+
/// Notably, `if CONST` and `match CONST` end up being used-once temporaries, which
10+
/// obfuscates the structure for other passes and codegen, which would like to always
11+
/// be able to just see the constant directly.
12+
///
13+
/// At higher optimization levels fancier passes like GVN will take care of this
14+
/// in a more general fashion, but this handles the easy cases so can run in debug.
15+
///
16+
/// This only removes constants with a single-use because re-evaluating constants
17+
/// isn't always an improvement, especially for large ones.
18+
///
19+
/// It also removes *never*-used constants, since it had all the information
20+
/// needed to do that too, including updating the debug info.
21+
pub struct SingleUseConsts;
22+
23+
impl<'tcx> MirPass<'tcx> for SingleUseConsts {
24+
fn is_enabled(&self, sess: &rustc_session::Session) -> bool {
25+
sess.mir_opt_level() > 0
26+
}
27+
28+
fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
29+
let mut finder = SingleUseConstsFinder {
30+
ineligible_locals: BitSet::new_empty(body.local_decls.len()),
31+
locations: IndexVec::from_elem(LocationPair::new(), &body.local_decls),
32+
locals_in_debug_info: BitSet::new_empty(body.local_decls.len()),
33+
};
34+
35+
finder.ineligible_locals.insert_range(..=Local::from_usize(body.arg_count));
36+
37+
finder.visit_body(body);
38+
39+
for (local, locations) in finder.locations.iter_enumerated() {
40+
if finder.ineligible_locals.contains(local) {
41+
continue;
42+
}
43+
44+
let Some(init_loc) = locations.init_loc else {
45+
continue;
46+
};
47+
48+
// We're only changing an operand, not the terminator kinds or successors
49+
let basic_blocks = body.basic_blocks.as_mut_preserves_cfg();
50+
let init_statement =
51+
basic_blocks[init_loc.block].statements[init_loc.statement_index].replace_nop();
52+
let StatementKind::Assign(place_and_rvalue) = init_statement.kind else {
53+
bug!("No longer an assign?");
54+
};
55+
let (place, rvalue) = *place_and_rvalue;
56+
debug_assert_eq!(place.as_local(), Some(local));
57+
let Rvalue::Use(operand) = rvalue else { bug!("No longer a use?") };
58+
59+
let mut replacer = LocalReplacer { tcx, local, operand: Some(operand) };
60+
61+
if finder.locals_in_debug_info.contains(local) {
62+
for var_debug_info in &mut body.var_debug_info {
63+
replacer.visit_var_debug_info(var_debug_info);
64+
}
65+
}
66+
67+
let Some(use_loc) = locations.use_loc else { continue };
68+
69+
let use_block = &mut basic_blocks[use_loc.block];
70+
if let Some(use_statement) = use_block.statements.get_mut(use_loc.statement_index) {
71+
replacer.visit_statement(use_statement, use_loc);
72+
} else {
73+
replacer.visit_terminator(use_block.terminator_mut(), use_loc);
74+
}
75+
76+
if replacer.operand.is_some() {
77+
bug!(
78+
"operand wasn't used replacing local {local:?} with locations {locations:?} in body {body:#?}"
79+
);
80+
}
81+
}
82+
}
83+
}
84+
85+
#[derive(Copy, Clone, Debug)]
86+
struct LocationPair {
87+
init_loc: Option<Location>,
88+
use_loc: Option<Location>,
89+
}
90+
91+
impl LocationPair {
92+
fn new() -> Self {
93+
Self { init_loc: None, use_loc: None }
94+
}
95+
}
96+
97+
struct SingleUseConstsFinder {
98+
ineligible_locals: BitSet<Local>,
99+
locations: IndexVec<Local, LocationPair>,
100+
locals_in_debug_info: BitSet<Local>,
101+
}
102+
103+
impl<'tcx> Visitor<'tcx> for SingleUseConstsFinder {
104+
fn visit_assign(&mut self, place: &Place<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
105+
if let Some(local) = place.as_local()
106+
&& let Rvalue::Use(operand) = rvalue
107+
&& let Operand::Constant(_) = operand
108+
{
109+
let locations = &mut self.locations[local];
110+
if locations.init_loc.is_some() {
111+
self.ineligible_locals.insert(local);
112+
} else {
113+
locations.init_loc = Some(location);
114+
}
115+
} else {
116+
self.super_assign(place, rvalue, location);
117+
}
118+
}
119+
120+
fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) {
121+
if let Some(place) = operand.place()
122+
&& let Some(local) = place.as_local()
123+
{
124+
let locations = &mut self.locations[local];
125+
if locations.use_loc.is_some() {
126+
self.ineligible_locals.insert(local);
127+
} else {
128+
locations.use_loc = Some(location);
129+
}
130+
} else {
131+
self.super_operand(operand, location);
132+
}
133+
}
134+
135+
fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
136+
match &statement.kind {
137+
// Storage markers are irrelevant to this.
138+
StatementKind::StorageLive(_) | StatementKind::StorageDead(_) => {}
139+
_ => self.super_statement(statement, location),
140+
}
141+
}
142+
143+
fn visit_var_debug_info(&mut self, var_debug_info: &VarDebugInfo<'tcx>) {
144+
if let VarDebugInfoContents::Place(place) = &var_debug_info.value
145+
&& let Some(local) = place.as_local()
146+
{
147+
self.locals_in_debug_info.insert(local);
148+
} else {
149+
self.super_var_debug_info(var_debug_info);
150+
}
151+
}
152+
153+
fn visit_local(&mut self, local: Local, _context: PlaceContext, _location: Location) {
154+
// If there's any path that gets here, rather than being understood elsewhere,
155+
// then we'd better not do anything with this local.
156+
self.ineligible_locals.insert(local);
157+
}
158+
}
159+
160+
struct LocalReplacer<'tcx> {
161+
tcx: TyCtxt<'tcx>,
162+
local: Local,
163+
operand: Option<Operand<'tcx>>,
164+
}
165+
166+
impl<'tcx> MutVisitor<'tcx> for LocalReplacer<'tcx> {
167+
fn tcx(&self) -> TyCtxt<'tcx> {
168+
self.tcx
169+
}
170+
171+
fn visit_operand(&mut self, operand: &mut Operand<'tcx>, _location: Location) {
172+
if let Operand::Copy(place) | Operand::Move(place) = operand
173+
&& let Some(local) = place.as_local()
174+
&& local == self.local
175+
{
176+
*operand = self.operand.take().unwrap_or_else(|| {
177+
bug!("there was a second use of the operand");
178+
});
179+
}
180+
}
181+
182+
fn visit_var_debug_info(&mut self, var_debug_info: &mut VarDebugInfo<'tcx>) {
183+
if let VarDebugInfoContents::Place(place) = &var_debug_info.value
184+
&& let Some(local) = place.as_local()
185+
&& local == self.local
186+
{
187+
let const_op = self
188+
.operand
189+
.as_ref()
190+
.unwrap_or_else(|| {
191+
bug!("the operand was already stolen");
192+
})
193+
.constant()
194+
.unwrap()
195+
.clone();
196+
var_debug_info.value = VarDebugInfoContents::Const(const_op);
197+
}
198+
}
199+
}

tests/mir-opt/building/match/sort_candidates.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@ fn constant_eq(s: &str, b: bool) -> u32 {
55
// Check that we only test "a" once
66

77
// CHECK-LABEL: fn constant_eq(
8-
// CHECK: bb0: {
9-
// CHECK: [[a:_.*]] = const "a";
10-
// CHECK-NOT: {{_.*}} = const "a";
8+
// CHECK-NOT: const "a"
9+
// CHECK: {{_[0-9]+}} = const "a" as &[u8] (Transmute);
10+
// CHECK-NOT: const "a"
1111
match (s, b) {
1212
("a", _) if true => 1,
1313
("b", true) => 2,

tests/mir-opt/dest-prop/union.main.DestinationPropagation.panic-abort.diff

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
bb0: {
1919
StorageLive(_1);
2020
StorageLive(_2);
21-
_2 = const 1_u32;
21+
nop;
2222
_1 = Un { us: const 1_u32 };
2323
StorageDead(_2);
2424
StorageLive(_3);

tests/mir-opt/dest-prop/union.main.DestinationPropagation.panic-unwind.diff

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
bb0: {
1919
StorageLive(_1);
2020
StorageLive(_2);
21-
_2 = const 1_u32;
21+
nop;
2222
_1 = Un { us: const 1_u32 };
2323
StorageDead(_2);
2424
StorageLive(_3);

tests/mir-opt/issue_76432.test.SimplifyComparisonIntegral.panic-abort.diff

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,8 @@
2929
_3 = &_4;
3030
_2 = move _3 as &[T] (PointerCoercion(Unsize));
3131
StorageDead(_3);
32-
_5 = const 3_usize;
33-
_6 = const true;
32+
nop;
33+
nop;
3434
goto -> bb2;
3535
}
3636

tests/mir-opt/issue_76432.test.SimplifyComparisonIntegral.panic-unwind.diff

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,8 @@
2929
_3 = &_4;
3030
_2 = move _3 as &[T] (PointerCoercion(Unsize));
3131
StorageDead(_3);
32-
_5 = const 3_usize;
33-
_6 = const true;
32+
nop;
33+
nop;
3434
goto -> bb2;
3535
}
3636

tests/mir-opt/pre-codegen/issue_117368_print_invalid_constant.main.GVN.32bit.panic-abort.diff

Lines changed: 14 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -23,16 +23,15 @@
2323
let mut _12: isize;
2424
let _13: std::alloc::AllocError;
2525
let mut _14: !;
26-
let _15: &str;
27-
let mut _16: &dyn std::fmt::Debug;
28-
let mut _17: &std::alloc::AllocError;
26+
let mut _15: &dyn std::fmt::Debug;
27+
let mut _16: &std::alloc::AllocError;
2928
scope 7 {
3029
}
3130
scope 8 {
3231
}
3332
}
3433
scope 9 (inlined NonNull::<[u8]>::as_ptr) {
35-
let mut _18: *const [u8];
34+
let mut _17: *const [u8];
3635
}
3736
}
3837
scope 3 (inlined #[track_caller] Option::<Layout>::unwrap) {
@@ -87,36 +86,33 @@
8786
StorageDead(_8);
8887
StorageDead(_7);
8988
StorageLive(_12);
90-
StorageLive(_15);
9189
_12 = discriminant(_6);
9290
switchInt(move _12) -> [0: bb6, 1: bb5, otherwise: bb1];
9391
}
9492

9593
bb5: {
96-
_15 = const "called `Result::unwrap()` on an `Err` value";
94+
StorageLive(_15);
9795
StorageLive(_16);
98-
StorageLive(_17);
99-
_17 = &_13;
100-
_16 = move _17 as &dyn std::fmt::Debug (PointerCoercion(Unsize));
101-
StorageDead(_17);
102-
_14 = result::unwrap_failed(move _15, move _16) -> unwind unreachable;
96+
_16 = &_13;
97+
_15 = move _16 as &dyn std::fmt::Debug (PointerCoercion(Unsize));
98+
StorageDead(_16);
99+
_14 = result::unwrap_failed(const "called `Result::unwrap()` on an `Err` value", move _15) -> unwind unreachable;
103100
}
104101

105102
bb6: {
106103
_5 = move ((_6 as Ok).0: std::ptr::NonNull<[u8]>);
107-
StorageDead(_15);
108104
StorageDead(_12);
109105
StorageDead(_6);
110-
- StorageLive(_18);
106+
- StorageLive(_17);
111107
+ nop;
112-
_18 = (_5.0: *const [u8]);
113-
- _4 = move _18 as *mut [u8] (PtrToPtr);
114-
- StorageDead(_18);
115-
+ _4 = _18 as *mut [u8] (PtrToPtr);
108+
_17 = (_5.0: *const [u8]);
109+
- _4 = move _17 as *mut [u8] (PtrToPtr);
110+
- StorageDead(_17);
111+
+ _4 = _17 as *mut [u8] (PtrToPtr);
116112
+ nop;
117113
StorageDead(_5);
118114
- _3 = move _4 as *mut u8 (PtrToPtr);
119-
+ _3 = _18 as *mut u8 (PtrToPtr);
115+
+ _3 = _17 as *mut u8 (PtrToPtr);
120116
StorageDead(_4);
121117
StorageDead(_3);
122118
- StorageDead(_1);

0 commit comments

Comments
 (0)