Skip to content

Commit ef695de

Browse files
committed
Auto merge of rust-lang#127324 - DianQK:match-br, r=<try>
[WIP] Simplify match based on the cast result of `IntToInt` Even though the current method has become simpler and clearer, I should still add more comprehensive tests. r? ghost
2 parents 4892331 + 5bbd1f2 commit ef695de

10 files changed

+321
-220
lines changed

compiler/rustc_mir_transform/src/match_branches.rs

+67-64
Original file line numberDiff line numberDiff line change
@@ -41,10 +41,7 @@ impl<'tcx> MirPass<'tcx> for MatchBranchSimplification {
4141
should_cleanup = true;
4242
continue;
4343
}
44-
// unsound: https://github.com/rust-lang/rust/issues/124150
45-
if tcx.sess.opts.unstable_opts.unsound_mir_opts
46-
&& SimplifyToExp::default().simplify(tcx, body, bb_idx, param_env).is_some()
47-
{
44+
if SimplifyToExp::default().simplify(tcx, body, bb_idx, param_env).is_some() {
4845
should_cleanup = true;
4946
continue;
5047
}
@@ -263,33 +260,49 @@ impl<'tcx> SimplifyMatch<'tcx> for SimplifyToIf {
263260
}
264261
}
265262

263+
/// Check if the cast constant using `IntToInt` is equal to the target constant.
264+
fn can_cast(
265+
from_val: impl Into<u128>,
266+
from_size: Size,
267+
target_scalar: ScalarInt,
268+
target_is_signed: bool,
269+
) -> bool {
270+
let from_scalar = ScalarInt::try_from_uint(from_val.into(), from_size).unwrap();
271+
let to_size = target_scalar.size();
272+
let cast_scalar = if target_is_signed {
273+
ScalarInt::try_from_int(from_scalar.to_int(from_size), to_size).unwrap()
274+
} else {
275+
ScalarInt::try_from_uint(from_scalar.to_uint(from_size), to_size).unwrap()
276+
};
277+
cast_scalar == target_scalar
278+
}
279+
266280
#[derive(Default)]
267281
struct SimplifyToExp {
268-
transfrom_types: Vec<TransfromType>,
282+
transfrom_kinds: Vec<TransfromKind>,
269283
}
270284

271285
#[derive(Clone, Copy)]
272-
enum CompareType<'tcx, 'a> {
286+
enum ExpectedTransformKind<'tcx, 'a> {
273287
/// Identical statements.
274288
Same(&'a StatementKind<'tcx>),
275289
/// Assignment statements have the same value.
276-
Eq(&'a Place<'tcx>, Ty<'tcx>, ScalarInt),
290+
SameByEq { place: &'a Place<'tcx>, ty: Ty<'tcx>, scalar: ScalarInt },
277291
/// Enum variant comparison type.
278-
Discr { place: &'a Place<'tcx>, ty: Ty<'tcx>, is_signed: bool },
292+
Cast { place: &'a Place<'tcx>, ty: Ty<'tcx> },
279293
}
280294

281-
enum TransfromType {
295+
enum TransfromKind {
282296
Same,
283-
Eq,
284-
Discr,
297+
Cast,
285298
}
286299

287-
impl From<CompareType<'_, '_>> for TransfromType {
288-
fn from(compare_type: CompareType<'_, '_>) -> Self {
300+
impl From<ExpectedTransformKind<'_, '_>> for TransfromKind {
301+
fn from(compare_type: ExpectedTransformKind<'_, '_>) -> Self {
289302
match compare_type {
290-
CompareType::Same(_) => TransfromType::Same,
291-
CompareType::Eq(_, _, _) => TransfromType::Eq,
292-
CompareType::Discr { .. } => TransfromType::Discr,
303+
ExpectedTransformKind::Same(_) => TransfromKind::Same,
304+
ExpectedTransformKind::SameByEq { .. } => TransfromKind::Same,
305+
ExpectedTransformKind::Cast { .. } => TransfromKind::Cast,
293306
}
294307
}
295308
}
@@ -353,7 +366,7 @@ impl<'tcx> SimplifyMatch<'tcx> for SimplifyToExp {
353366
return None;
354367
}
355368
let mut target_iter = targets.iter();
356-
let (first_val, first_target) = target_iter.next().unwrap();
369+
let (first_case_val, first_target) = target_iter.next().unwrap();
357370
let first_terminator_kind = &bbs[first_target].terminator().kind;
358371
// Check that destinations are identical, and if not, then don't optimize this block
359372
if !targets
@@ -365,22 +378,18 @@ impl<'tcx> SimplifyMatch<'tcx> for SimplifyToExp {
365378

366379
let discr_size = tcx.layout_of(param_env.and(discr_ty)).unwrap().size;
367380
let first_stmts = &bbs[first_target].statements;
368-
let (second_val, second_target) = target_iter.next().unwrap();
381+
let (second_case_val, second_target) = target_iter.next().unwrap();
369382
let second_stmts = &bbs[second_target].statements;
370383
if first_stmts.len() != second_stmts.len() {
371384
return None;
372385
}
373386

374-
fn int_equal(l: ScalarInt, r: impl Into<u128>, size: Size) -> bool {
375-
l.to_bits_unchecked() == ScalarInt::try_from_uint(r, size).unwrap().to_bits_unchecked()
376-
}
377-
378387
// We first compare the two branches, and then the other branches need to fulfill the same conditions.
379-
let mut compare_types = Vec::new();
388+
let mut expected_transform_kinds = Vec::new();
380389
for (f, s) in iter::zip(first_stmts, second_stmts) {
381390
let compare_type = match (&f.kind, &s.kind) {
382391
// If two statements are exactly the same, we can optimize.
383-
(f_s, s_s) if f_s == s_s => CompareType::Same(f_s),
392+
(f_s, s_s) if f_s == s_s => ExpectedTransformKind::Same(f_s),
384393

385394
// If two statements are assignments with the match values to the same place, we can optimize.
386395
(
@@ -394,22 +403,27 @@ impl<'tcx> SimplifyMatch<'tcx> for SimplifyToExp {
394403
f_c.const_.try_eval_scalar_int(tcx, param_env),
395404
s_c.const_.try_eval_scalar_int(tcx, param_env),
396405
) {
397-
(Some(f), Some(s)) if f == s => CompareType::Eq(lhs_f, f_c.const_.ty(), f),
398-
// Enum variants can also be simplified to an assignment statement if their values are equal.
399-
// We need to consider both unsigned and signed scenarios here.
406+
(Some(f), Some(s)) if f == s => ExpectedTransformKind::SameByEq {
407+
place: lhs_f,
408+
ty: f_c.const_.ty(),
409+
scalar: f,
410+
},
411+
// Enum variants can also be simplified to an assignment statement,
412+
// if we can use `IntToInt` cast to get an equal value.
400413
(Some(f), Some(s))
401-
if ((f_c.const_.ty().is_signed() || discr_ty.is_signed())
402-
&& int_equal(f, first_val, discr_size)
403-
&& int_equal(s, second_val, discr_size))
404-
|| (Some(f) == ScalarInt::try_from_uint(first_val, f.size())
405-
&& Some(s)
406-
== ScalarInt::try_from_uint(second_val, s.size())) =>
414+
if (can_cast(
415+
first_case_val,
416+
discr_size,
417+
f,
418+
f_c.const_.ty().is_signed(),
419+
) && can_cast(
420+
second_case_val,
421+
discr_size,
422+
s,
423+
s_c.const_.ty().is_signed(),
424+
)) =>
407425
{
408-
CompareType::Discr {
409-
place: lhs_f,
410-
ty: f_c.const_.ty(),
411-
is_signed: f_c.const_.ty().is_signed() || discr_ty.is_signed(),
412-
}
426+
ExpectedTransformKind::Cast { place: lhs_f, ty: f_c.const_.ty() }
413427
}
414428
_ => {
415429
return None;
@@ -420,47 +434,36 @@ impl<'tcx> SimplifyMatch<'tcx> for SimplifyToExp {
420434
// Otherwise we cannot optimize. Try another block.
421435
_ => return None,
422436
};
423-
compare_types.push(compare_type);
437+
expected_transform_kinds.push(compare_type);
424438
}
425439

426440
// All remaining BBs need to fulfill the same pattern as the two BBs from the previous step.
427441
for (other_val, other_target) in target_iter {
428442
let other_stmts = &bbs[other_target].statements;
429-
if compare_types.len() != other_stmts.len() {
443+
if expected_transform_kinds.len() != other_stmts.len() {
430444
return None;
431445
}
432-
for (f, s) in iter::zip(&compare_types, other_stmts) {
446+
for (f, s) in iter::zip(&expected_transform_kinds, other_stmts) {
433447
match (*f, &s.kind) {
434-
(CompareType::Same(f_s), s_s) if f_s == s_s => {}
448+
(ExpectedTransformKind::Same(f_s), s_s) if f_s == s_s => {}
435449
(
436-
CompareType::Eq(lhs_f, f_ty, val),
450+
ExpectedTransformKind::SameByEq { place: lhs_f, ty: f_ty, scalar },
437451
StatementKind::Assign(box (lhs_s, Rvalue::Use(Operand::Constant(s_c)))),
438452
) if lhs_f == lhs_s
439453
&& s_c.const_.ty() == f_ty
440-
&& s_c.const_.try_eval_scalar_int(tcx, param_env) == Some(val) => {}
454+
&& s_c.const_.try_eval_scalar_int(tcx, param_env) == Some(scalar) => {}
441455
(
442-
CompareType::Discr { place: lhs_f, ty: f_ty, is_signed },
456+
ExpectedTransformKind::Cast { place: lhs_f, ty: f_ty },
443457
StatementKind::Assign(box (lhs_s, Rvalue::Use(Operand::Constant(s_c)))),
444-
) if lhs_f == lhs_s && s_c.const_.ty() == f_ty => {
445-
let Some(f) = s_c.const_.try_eval_scalar_int(tcx, param_env) else {
446-
return None;
447-
};
448-
if is_signed
449-
&& s_c.const_.ty().is_signed()
450-
&& int_equal(f, other_val, discr_size)
451-
{
452-
continue;
453-
}
454-
if Some(f) == ScalarInt::try_from_uint(other_val, f.size()) {
455-
continue;
456-
}
457-
return None;
458-
}
458+
) if let Some(f) = s_c.const_.try_eval_scalar_int(tcx, param_env)
459+
&& lhs_f == lhs_s
460+
&& s_c.const_.ty() == f_ty
461+
&& can_cast(other_val, discr_size, f, f_ty.is_signed()) => {}
459462
_ => return None,
460463
}
461464
}
462465
}
463-
self.transfrom_types = compare_types.into_iter().map(|c| c.into()).collect();
466+
self.transfrom_kinds = expected_transform_kinds.into_iter().map(|c| c.into()).collect();
464467
Some(())
465468
}
466469

@@ -478,13 +481,13 @@ impl<'tcx> SimplifyMatch<'tcx> for SimplifyToExp {
478481
let (_, first) = targets.iter().next().unwrap();
479482
let first = &bbs[first];
480483

481-
for (t, s) in iter::zip(&self.transfrom_types, &first.statements) {
484+
for (t, s) in iter::zip(&self.transfrom_kinds, &first.statements) {
482485
match (t, &s.kind) {
483-
(TransfromType::Same, _) | (TransfromType::Eq, _) => {
486+
(TransfromKind::Same, _) => {
484487
patch.add_statement(parent_end, s.kind.clone());
485488
}
486489
(
487-
TransfromType::Discr,
490+
TransfromKind::Cast,
488491
StatementKind::Assign(box (lhs, Rvalue::Use(Operand::Constant(f_c)))),
489492
) => {
490493
let operand = Operand::Copy(Place::from(discr_local));

tests/mir-opt/matches_reduce_branches.match_i128_u128.MatchBranchSimplification.diff

+33-28
Original file line numberDiff line numberDiff line change
@@ -5,37 +5,42 @@
55
debug i => _1;
66
let mut _0: u128;
77
let mut _2: i128;
8+
+ let mut _3: i128;
89

910
bb0: {
1011
_2 = discriminant(_1);
11-
switchInt(move _2) -> [1: bb3, 2: bb4, 3: bb5, 340282366920938463463374607431768211455: bb2, otherwise: bb1];
12-
}
13-
14-
bb1: {
15-
unreachable;
16-
}
17-
18-
bb2: {
19-
_0 = const core::num::<impl u128>::MAX;
20-
goto -> bb6;
21-
}
22-
23-
bb3: {
24-
_0 = const 1_u128;
25-
goto -> bb6;
26-
}
27-
28-
bb4: {
29-
_0 = const 2_u128;
30-
goto -> bb6;
31-
}
32-
33-
bb5: {
34-
_0 = const 3_u128;
35-
goto -> bb6;
36-
}
37-
38-
bb6: {
12+
- switchInt(move _2) -> [1: bb3, 2: bb4, 3: bb5, 340282366920938463463374607431768211455: bb2, otherwise: bb1];
13+
- }
14+
-
15+
- bb1: {
16+
- unreachable;
17+
- }
18+
-
19+
- bb2: {
20+
- _0 = const core::num::<impl u128>::MAX;
21+
- goto -> bb6;
22+
- }
23+
-
24+
- bb3: {
25+
- _0 = const 1_u128;
26+
- goto -> bb6;
27+
- }
28+
-
29+
- bb4: {
30+
- _0 = const 2_u128;
31+
- goto -> bb6;
32+
- }
33+
-
34+
- bb5: {
35+
- _0 = const 3_u128;
36+
- goto -> bb6;
37+
- }
38+
-
39+
- bb6: {
40+
+ StorageLive(_3);
41+
+ _3 = move _2;
42+
+ _0 = _3 as u128 (IntToInt);
43+
+ StorageDead(_3);
3944
return;
4045
}
4146
}

tests/mir-opt/matches_reduce_branches.match_i16_i8.MatchBranchSimplification.diff

+28-23
Original file line numberDiff line numberDiff line change
@@ -5,32 +5,37 @@
55
debug i => _1;
66
let mut _0: i8;
77
let mut _2: i16;
8+
+ let mut _3: i16;
89

910
bb0: {
1011
_2 = discriminant(_1);
11-
switchInt(move _2) -> [65535: bb3, 2: bb4, 65533: bb2, otherwise: bb1];
12-
}
13-
14-
bb1: {
15-
unreachable;
16-
}
17-
18-
bb2: {
19-
_0 = const -3_i8;
20-
goto -> bb5;
21-
}
22-
23-
bb3: {
24-
_0 = const -1_i8;
25-
goto -> bb5;
26-
}
27-
28-
bb4: {
29-
_0 = const 2_i8;
30-
goto -> bb5;
31-
}
32-
33-
bb5: {
12+
- switchInt(move _2) -> [65535: bb3, 2: bb4, 65533: bb2, otherwise: bb1];
13+
- }
14+
-
15+
- bb1: {
16+
- unreachable;
17+
- }
18+
-
19+
- bb2: {
20+
- _0 = const -3_i8;
21+
- goto -> bb5;
22+
- }
23+
-
24+
- bb3: {
25+
- _0 = const -1_i8;
26+
- goto -> bb5;
27+
- }
28+
-
29+
- bb4: {
30+
- _0 = const 2_i8;
31+
- goto -> bb5;
32+
- }
33+
-
34+
- bb5: {
35+
+ StorageLive(_3);
36+
+ _3 = move _2;
37+
+ _0 = _3 as i8 (IntToInt);
38+
+ StorageDead(_3);
3439
return;
3540
}
3641
}

0 commit comments

Comments
 (0)