Skip to content

Commit fa1681c

Browse files
committed
Auto merge of rust-lang#125910 - scottmcm:single-use-consts, r=saethlin
Add `SingleUseConsts` mir-opt pass The goal here is to make a pass that can be run in debug builds to simplify the common case of constants that are used just once -- that doesn't need SSA handling and avoids any potential downside of multi-use constants. In particular, to simplify the `if T::IS_ZST` pattern that's common in the standard library. By also handling the case of constants that are *never* actually used this fully replaces the `ConstDebugInfo` pass, since it has all the information needed to do that naturally from the traversal it needs to do anyway. This is roughly a wash on instructions on its own (a couple regressions, a few improvements rust-lang#125910 (comment)), with a bunch of size improvements. So I'd like to land it as its own PR, then do follow-ups to take more advantage of it (in the inliner, cg_ssa, etc). r? `@saethlin`
2 parents b5b1356 + 8fbab18 commit fa1681c

File tree

35 files changed

+1042
-467
lines changed

35 files changed

+1042
-467
lines changed

Diff for: compiler/rustc_mir_transform/src/const_debuginfo.rs

-102
This file was deleted.

Diff for: compiler/rustc_mir_transform/src/lib.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,6 @@ mod remove_place_mention;
5555
// This pass is public to allow external drivers to perform MIR cleanup
5656
mod add_subtyping_projections;
5757
pub mod cleanup_post_borrowck;
58-
mod const_debuginfo;
5958
mod copy_prop;
6059
mod coroutine;
6160
mod cost_checker;
@@ -106,6 +105,7 @@ mod check_alignment;
106105
pub mod simplify;
107106
mod simplify_branches;
108107
mod simplify_comparison_integral;
108+
mod single_use_consts;
109109
mod sroa;
110110
mod unreachable_enum_branching;
111111
mod unreachable_prop;
@@ -593,7 +593,7 @@ fn run_optimization_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
593593
&gvn::GVN,
594594
&simplify::SimplifyLocals::AfterGVN,
595595
&dataflow_const_prop::DataflowConstProp,
596-
&const_debuginfo::ConstDebugInfo,
596+
&single_use_consts::SingleUseConsts,
597597
&o1(simplify_branches::SimplifyConstCondition::AfterConstProp),
598598
&jump_threading::JumpThreading,
599599
&early_otherwise_branch::EarlyOtherwiseBranch,
+199
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+
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+
}

Diff for: tests/mir-opt/building/match/sort_candidates.rs

+3-3
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,

0 commit comments

Comments
 (0)