]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir/src/transform/simplify_comparison_integral.rs
Merge commit '03f01bbe901d60b71cf2c5ec766aef5e532ab79d' into update_cg_clif-2020...
[rust.git] / compiler / rustc_mir / src / transform / simplify_comparison_integral.rs
1 use std::iter;
2
3 use super::MirPass;
4 use rustc_middle::{
5     mir::{
6         interpret::Scalar, BasicBlock, BinOp, Body, Operand, Place, Rvalue, Statement,
7         StatementKind, SwitchTargets, TerminatorKind,
8     },
9     ty::{Ty, TyCtxt},
10 };
11
12 /// Pass to convert `if` conditions on integrals into switches on the integral.
13 /// For an example, it turns something like
14 ///
15 /// ```
16 /// _3 = Eq(move _4, const 43i32);
17 /// StorageDead(_4);
18 /// switchInt(_3) -> [false: bb2, otherwise: bb3];
19 /// ```
20 ///
21 /// into:
22 ///
23 /// ```
24 /// switchInt(_4) -> [43i32: bb3, otherwise: bb2];
25 /// ```
26 pub struct SimplifyComparisonIntegral;
27
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);
31
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![];
36         for opt in opts {
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,
46             };
47             const FALSE: u128 = 0;
48
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;
52             match opt.op {
53                 BinOp::Eq => {
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);
57                     }
58                 }
59                 BinOp::Ne => {
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);
63                     }
64                 }
65                 _ => unreachable!(),
66             }
67
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();
71             } else {
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.
77
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();
80
81                 use Operand::*;
82                 match rhs {
83                     Rvalue::BinaryOp(_, ref mut left @ Move(_), Constant(_)) => {
84                         *left = Copy(opt.to_switch_on);
85                     }
86                     Rvalue::BinaryOp(_, Constant(_), ref mut right @ Move(_)) => {
87                         *right = Copy(opt.to_switch_on);
88                     }
89                     _ => (),
90                 }
91             }
92
93             let terminator = bb.terminator();
94
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)
98                 {
99                     continue;
100                 }
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((
105                         *bb_idx,
106                         Statement {
107                             source_info: terminator.source_info,
108                             kind: StatementKind::StorageDead(opt.to_switch_on.local),
109                         },
110                     ));
111                 }
112             }
113
114             let [bb_cond, bb_otherwise] = match new_targets.all_targets() {
115                 [a, b] => [*a, *b],
116                 e => bug!("expected 2 switch targets, got: {:?}", e),
117             };
118
119             let targets = SwitchTargets::new(iter::once((new_value, bb_cond)), bb_otherwise);
120
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,
125                 targets,
126             };
127         }
128
129         for (idx, bb_idx) in storage_deads_to_remove {
130             body.basic_blocks_mut()[bb_idx].statements[idx].make_nop();
131         }
132
133         for (idx, stmt) in storage_deads_to_insert {
134             body.basic_blocks_mut()[idx].statements.insert(0, stmt);
135         }
136     }
137 }
138
139 struct OptimizationFinder<'a, 'tcx> {
140     body: &'a Body<'tcx>,
141 }
142
143 impl<'a, 'tcx> OptimizationFinder<'a, 'tcx> {
144     fn find_optimizations(&self) -> Vec<OptimizationInfo<'tcx>> {
145         self.body
146             .basic_blocks()
147             .iter_enumerated()
148             .filter_map(|(bb_idx, bb)| {
149                 // find switch
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()))
154                         }
155                         _ => None,
156                     }?;
157
158                 // find the statement that assigns the place being switched on
159                 bb.statements.iter().enumerate().rev().find_map(|(stmt_idx, stmt)| {
160                     match &stmt.kind {
161                         rustc_middle::mir::StatementKind::Assign(box (lhs, rhs))
162                             if *lhs == place_switched_on =>
163                         {
164                             match rhs {
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)?;
168
169                                     Some(OptimizationInfo {
170                                         bin_op_stmt_idx: stmt_idx,
171                                         bb_idx,
172                                         can_remove_bin_op_stmt: place_switched_on_moved,
173                                         to_switch_on,
174                                         branch_value_scalar,
175                                         branch_value_ty,
176                                         op: *op,
177                                         targets: targets.clone(),
178                                     })
179                                 }
180                                 _ => None,
181                             }
182                         }
183                         _ => None,
184                     }
185                 })
186             })
187             .collect()
188     }
189 }
190
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
197     use Operand::*;
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() {
204                 return None;
205             };
206             let branch_value_scalar = branch_value.literal.val.try_to_scalar()?;
207             Some((branch_value_scalar, branch_value_ty, *to_switch_on))
208         }
209         _ => None,
210     }
211 }
212
213 #[derive(Debug)]
214 struct OptimizationInfo<'tcx> {
215     /// Basic block to apply the optimization
216     bb_idx: BasicBlock,
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>,
227     /// Either Eq or Ne
228     op: BinOp,
229     /// Current targets used in the switch
230     targets: SwitchTargets,
231 }