6 interpret::Scalar, BasicBlock, BinOp, Body, Operand, Place, Rvalue, Statement,
7 StatementKind, SwitchTargets, TerminatorKind,
12 /// Pass to convert `if` conditions on integrals into switches on the integral.
13 /// For an example, it turns something like
16 /// _3 = Eq(move _4, const 43i32);
18 /// switchInt(_3) -> [false: bb2, otherwise: bb3];
24 /// switchInt(_4) -> [43i32: bb3, otherwise: bb2];
26 pub struct SimplifyComparisonIntegral;
28 impl<'tcx> MirPass<'tcx> for SimplifyComparisonIntegral {
29 fn run_pass(&self, _: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
30 trace!("Running SimplifyComparisonIntegral on {:?}", body.source);
32 let helper = OptimizationFinder { body };
33 let opts = helper.find_optimizations();
34 let mut storage_deads_to_insert = vec![];
35 let mut storage_deads_to_remove: Vec<(usize, BasicBlock)> = vec![];
37 trace!("SUCCESS: Applying {:?}", opt);
38 // replace terminator with a switchInt that switches on the integer directly
39 let bbs = &mut body.basic_blocks_mut();
40 let bb = &mut bbs[opt.bb_idx];
41 // We only use the bits for the untyped, not length checked `values` field. Thus we are
42 // not using any of the convenience wrappers here and directly access the bits.
43 let new_value = match opt.branch_value_scalar {
44 Scalar::Raw { data, .. } => data,
45 Scalar::Ptr(_) => continue,
47 const FALSE: u128 = 0;
49 let mut new_targets = opt.targets;
50 let first_value = new_targets.iter().next().unwrap().0;
51 let first_is_false_target = first_value == FALSE;
54 // if the assignment was Eq we want the true case to be first
55 if first_is_false_target {
56 new_targets.all_targets_mut().swap(0, 1);
60 // if the assignment was Ne we want the false case to be first
61 if !first_is_false_target {
62 new_targets.all_targets_mut().swap(0, 1);
68 // delete comparison statement if it the value being switched on was moved, which means it can not be user later on
69 if opt.can_remove_bin_op_stmt {
70 bb.statements[opt.bin_op_stmt_idx].make_nop();
72 // if the integer being compared to a const integral is being moved into the comparison,
73 // e.g `_2 = Eq(move _3, const 'x');`
74 // we want to avoid making a double move later on in the switchInt on _3.
75 // So to avoid `switchInt(move _3) -> ['x': bb2, otherwise: bb1];`,
76 // we convert the move in the comparison statement to a copy.
78 // unwrap is safe as we know this statement is an assign
79 let box (_, rhs) = bb.statements[opt.bin_op_stmt_idx].kind.as_assign_mut().unwrap();
83 Rvalue::BinaryOp(_, ref mut left @ Move(_), Constant(_)) => {
84 *left = Copy(opt.to_switch_on);
86 Rvalue::BinaryOp(_, Constant(_), ref mut right @ Move(_)) => {
87 *right = Copy(opt.to_switch_on);
93 let terminator = bb.terminator();
95 // remove StorageDead (if it exists) being used in the assign of the comparison
96 for (stmt_idx, stmt) in bb.statements.iter().enumerate() {
97 if !matches!(stmt.kind, StatementKind::StorageDead(local) if local == opt.to_switch_on.local)
101 storage_deads_to_remove.push((stmt_idx, opt.bb_idx));
102 // if we have StorageDeads to remove then make sure to insert them at the top of each target
103 for bb_idx in new_targets.all_targets() {
104 storage_deads_to_insert.push((
107 source_info: terminator.source_info,
108 kind: StatementKind::StorageDead(opt.to_switch_on.local),
114 let [bb_cond, bb_otherwise] = match new_targets.all_targets() {
116 e => bug!("expected 2 switch targets, got: {:?}", e),
119 let targets = SwitchTargets::new(iter::once((new_value, bb_cond)), bb_otherwise);
121 let terminator = bb.terminator_mut();
122 terminator.kind = TerminatorKind::SwitchInt {
123 discr: Operand::Move(opt.to_switch_on),
124 switch_ty: opt.branch_value_ty,
129 for (idx, bb_idx) in storage_deads_to_remove {
130 body.basic_blocks_mut()[bb_idx].statements[idx].make_nop();
133 for (idx, stmt) in storage_deads_to_insert {
134 body.basic_blocks_mut()[idx].statements.insert(0, stmt);
139 struct OptimizationFinder<'a, 'tcx> {
140 body: &'a Body<'tcx>,
143 impl<'a, 'tcx> OptimizationFinder<'a, 'tcx> {
144 fn find_optimizations(&self) -> Vec<OptimizationInfo<'tcx>> {
148 .filter_map(|(bb_idx, bb)| {
150 let (place_switched_on, targets, place_switched_on_moved) =
151 match &bb.terminator().kind {
152 rustc_middle::mir::TerminatorKind::SwitchInt { discr, targets, .. } => {
153 Some((discr.place()?, targets, discr.is_move()))
158 // find the statement that assigns the place being switched on
159 bb.statements.iter().enumerate().rev().find_map(|(stmt_idx, stmt)| {
161 rustc_middle::mir::StatementKind::Assign(box (lhs, rhs))
162 if *lhs == place_switched_on =>
165 Rvalue::BinaryOp(op @ (BinOp::Eq | BinOp::Ne), left, right) => {
166 let (branch_value_scalar, branch_value_ty, to_switch_on) =
167 find_branch_value_info(left, right)?;
169 Some(OptimizationInfo {
170 bin_op_stmt_idx: stmt_idx,
172 can_remove_bin_op_stmt: place_switched_on_moved,
177 targets: targets.clone(),
191 fn find_branch_value_info<'tcx>(
192 left: &Operand<'tcx>,
193 right: &Operand<'tcx>,
194 ) -> Option<(Scalar, Ty<'tcx>, Place<'tcx>)> {
195 // check that either left or right is a constant.
196 // if any are, we can use the other to switch on, and the constant as a value in a switch
198 match (left, right) {
199 (Constant(branch_value), Copy(to_switch_on) | Move(to_switch_on))
200 | (Copy(to_switch_on) | Move(to_switch_on), Constant(branch_value)) => {
201 let branch_value_ty = branch_value.literal.ty;
202 // we only want to apply this optimization if we are matching on integrals (and chars), as it is not possible to switch on floats
203 if !branch_value_ty.is_integral() && !branch_value_ty.is_char() {
206 let branch_value_scalar = branch_value.literal.val.try_to_scalar()?;
207 Some((branch_value_scalar, branch_value_ty, *to_switch_on))
214 struct OptimizationInfo<'tcx> {
215 /// Basic block to apply the optimization
217 /// Statement index of Eq/Ne assignment that can be removed. None if the assignment can not be removed - i.e the statement is used later on
218 bin_op_stmt_idx: usize,
219 /// Can remove Eq/Ne assignment
220 can_remove_bin_op_stmt: bool,
221 /// Place that needs to be switched on. This place is of type integral
222 to_switch_on: Place<'tcx>,
223 /// Constant to use in switch target value
224 branch_value_scalar: Scalar,
225 /// Type of the constant value
226 branch_value_ty: Ty<'tcx>,
229 /// Current targets used in the switch
230 targets: SwitchTargets,