]>
Commit | Line | Data |
---|---|---|
c295e0f8 | 1 | use crate::MirPass; |
ba9703b0 XL |
2 | use rustc_middle::mir::*; |
3 | use rustc_middle::ty::TyCtxt; | |
3157f602 | 4 | |
7cac9316 | 5 | use std::borrow::Cow; |
3157f602 | 6 | |
a2a8927a XL |
7 | /// A pass that replaces a branch with a goto when its condition is known. |
8 | pub struct SimplifyConstCondition { | |
dfeec247 XL |
9 | label: String, |
10 | } | |
3157f602 | 11 | |
a2a8927a | 12 | impl SimplifyConstCondition { |
7cac9316 | 13 | pub fn new(label: &str) -> Self { |
a2a8927a | 14 | SimplifyConstCondition { label: format!("SimplifyConstCondition-{}", label) } |
3157f602 XL |
15 | } |
16 | } | |
17 | ||
a2a8927a | 18 | impl<'tcx> MirPass<'tcx> for SimplifyConstCondition { |
416331ca | 19 | fn name(&self) -> Cow<'_, str> { |
7cac9316 XL |
20 | Cow::Borrowed(&self.label) |
21 | } | |
22 | ||
29967ef6 XL |
23 | fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { |
24 | let param_env = tcx.param_env(body.source.def_id()); | |
dc9dc135 | 25 | for block in body.basic_blocks_mut() { |
3157f602 XL |
26 | let terminator = block.terminator_mut(); |
27 | terminator.kind = match terminator.kind { | |
8faf50e0 | 28 | TerminatorKind::SwitchInt { |
dfeec247 XL |
29 | discr: Operand::Constant(ref c), |
30 | switch_ty, | |
dfeec247 XL |
31 | ref targets, |
32 | .. | |
8faf50e0 | 33 | } => { |
416331ca | 34 | let constant = c.literal.try_eval_bits(tcx, param_env, switch_ty); |
0731742a | 35 | if let Some(constant) = constant { |
a2a8927a XL |
36 | let target = targets.target_for_value(constant); |
37 | TerminatorKind::Goto { target } | |
3157f602 | 38 | } else { |
dfeec247 | 39 | continue; |
3157f602 | 40 | } |
dfeec247 | 41 | } |
8faf50e0 XL |
42 | TerminatorKind::Assert { |
43 | target, cond: Operand::Constant(ref c), expected, .. | |
29967ef6 XL |
44 | } => match c.literal.try_eval_bool(tcx, param_env) { |
45 | Some(v) if v == expected => TerminatorKind::Goto { target }, | |
46 | _ => continue, | |
47 | }, | |
dfeec247 | 48 | _ => continue, |
3157f602 XL |
49 | }; |
50 | } | |
51 | } | |
52 | } |