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 is_enabled(&self, sess: &rustc_session::Session) -> bool {
30 sess.mir_opt_level() > 0
33 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
34 trace!("Running SimplifyComparisonIntegral on {:?}", body.source);
36 let helper = OptimizationFinder { body };
37 let opts = helper.find_optimizations();
38 let mut storage_deads_to_insert = vec![];
39 let mut storage_deads_to_remove: Vec<(usize, BasicBlock)> = vec![];
40 let param_env = tcx.param_env(body.source.def_id());
42 trace!("SUCCESS: Applying {:?}", opt);
43 // replace terminator with a switchInt that switches on the integer directly
44 let bbs = &mut body.basic_blocks_mut();
45 let bb = &mut bbs[opt.bb_idx];
46 let new_value = match opt.branch_value_scalar {
49 .layout_of(param_env.and(opt.branch_value_ty))
50 .expect("if we have an evaluated constant we must know the layout");
51 int.assert_bits(layout.size)
53 Scalar::Ptr(..) => continue,
55 const FALSE: u128 = 0;
57 let mut new_targets = opt.targets;
58 let first_value = new_targets.iter().next().unwrap().0;
59 let first_is_false_target = first_value == FALSE;
62 // if the assignment was Eq we want the true case to be first
63 if first_is_false_target {
64 new_targets.all_targets_mut().swap(0, 1);
68 // if the assignment was Ne we want the false case to be first
69 if !first_is_false_target {
70 new_targets.all_targets_mut().swap(0, 1);
76 // delete comparison statement if it the value being switched on was moved, which means it can not be user later on
77 if opt.can_remove_bin_op_stmt {
78 bb.statements[opt.bin_op_stmt_idx].make_nop();
80 // if the integer being compared to a const integral is being moved into the comparison,
81 // e.g `_2 = Eq(move _3, const 'x');`
82 // we want to avoid making a double move later on in the switchInt on _3.
83 // So to avoid `switchInt(move _3) -> ['x': bb2, otherwise: bb1];`,
84 // we convert the move in the comparison statement to a copy.
86 // unwrap is safe as we know this statement is an assign
87 let (_, rhs) = bb.statements[opt.bin_op_stmt_idx].kind.as_assign_mut().unwrap();
91 Rvalue::BinaryOp(_, box (ref mut left @ Move(_), Constant(_))) => {
92 *left = Copy(opt.to_switch_on);
94 Rvalue::BinaryOp(_, box (Constant(_), ref mut right @ Move(_))) => {
95 *right = Copy(opt.to_switch_on);
101 let terminator = bb.terminator();
103 // remove StorageDead (if it exists) being used in the assign of the comparison
104 for (stmt_idx, stmt) in bb.statements.iter().enumerate() {
105 if !matches!(stmt.kind, StatementKind::StorageDead(local) if local == opt.to_switch_on.local)
109 storage_deads_to_remove.push((stmt_idx, opt.bb_idx));
110 // if we have StorageDeads to remove then make sure to insert them at the top of each target
111 for bb_idx in new_targets.all_targets() {
112 storage_deads_to_insert.push((
115 source_info: terminator.source_info,
116 kind: StatementKind::StorageDead(opt.to_switch_on.local),
122 let [bb_cond, bb_otherwise] = match new_targets.all_targets() {
124 e => bug!("expected 2 switch targets, got: {:?}", e),
127 let targets = SwitchTargets::new(iter::once((new_value, bb_cond)), bb_otherwise);
129 let terminator = bb.terminator_mut();
130 terminator.kind = TerminatorKind::SwitchInt {
131 discr: Operand::Move(opt.to_switch_on),
132 switch_ty: opt.branch_value_ty,
137 for (idx, bb_idx) in storage_deads_to_remove {
138 body.basic_blocks_mut()[bb_idx].statements[idx].make_nop();
141 for (idx, stmt) in storage_deads_to_insert {
142 body.basic_blocks_mut()[idx].statements.insert(0, stmt);
147 struct OptimizationFinder<'a, 'tcx> {
148 body: &'a Body<'tcx>,
151 impl<'tcx> OptimizationFinder<'_, 'tcx> {
152 fn find_optimizations(&self) -> Vec<OptimizationInfo<'tcx>> {
156 .filter_map(|(bb_idx, bb)| {
158 let (place_switched_on, targets, place_switched_on_moved) =
159 match &bb.terminator().kind {
160 rustc_middle::mir::TerminatorKind::SwitchInt { discr, targets, .. } => {
161 Some((discr.place()?, targets, discr.is_move()))
166 // find the statement that assigns the place being switched on
167 bb.statements.iter().enumerate().rev().find_map(|(stmt_idx, stmt)| {
169 rustc_middle::mir::StatementKind::Assign(box (lhs, rhs))
170 if *lhs == place_switched_on =>
174 op @ (BinOp::Eq | BinOp::Ne),
177 let (branch_value_scalar, branch_value_ty, to_switch_on) =
178 find_branch_value_info(left, right)?;
180 Some(OptimizationInfo {
181 bin_op_stmt_idx: stmt_idx,
183 can_remove_bin_op_stmt: place_switched_on_moved,
188 targets: targets.clone(),
202 fn find_branch_value_info<'tcx>(
203 left: &Operand<'tcx>,
204 right: &Operand<'tcx>,
205 ) -> Option<(Scalar, Ty<'tcx>, Place<'tcx>)> {
206 // check that either left or right is a constant.
207 // if any are, we can use the other to switch on, and the constant as a value in a switch
209 match (left, right) {
210 (Constant(branch_value), Copy(to_switch_on) | Move(to_switch_on))
211 | (Copy(to_switch_on) | Move(to_switch_on), Constant(branch_value)) => {
212 let branch_value_ty = branch_value.literal.ty();
213 // we only want to apply this optimization if we are matching on integrals (and chars), as it is not possible to switch on floats
214 if !branch_value_ty.is_integral() && !branch_value_ty.is_char() {
217 let branch_value_scalar = branch_value.literal.try_to_scalar()?;
218 Some((branch_value_scalar, branch_value_ty, *to_switch_on))
225 struct OptimizationInfo<'tcx> {
226 /// Basic block to apply the optimization
228 /// 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
229 bin_op_stmt_idx: usize,
230 /// Can remove Eq/Ne assignment
231 can_remove_bin_op_stmt: bool,
232 /// Place that needs to be switched on. This place is of type integral
233 to_switch_on: Place<'tcx>,
234 /// Constant to use in switch target value
235 branch_value_scalar: Scalar,
236 /// Type of the constant value
237 branch_value_ty: Ty<'tcx>,
240 /// Current targets used in the switch
241 targets: SwitchTargets,