]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/simplify_branches.rs
Rollup merge of #61135 - czipperz:rc-make_mut-weak-doc, r=Mark-Simulacrum
[rust.git] / src / librustc_mir / transform / simplify_branches.rs
1 //! A pass that simplifies branches when their condition is known.
2
3 use rustc::ty::{TyCtxt, ParamEnv};
4 use rustc::mir::*;
5 use crate::transform::{MirPass, MirSource};
6
7 use std::borrow::Cow;
8
9 pub struct SimplifyBranches { label: String }
10
11 impl SimplifyBranches {
12     pub fn new(label: &str) -> Self {
13         SimplifyBranches { label: format!("SimplifyBranches-{}", label) }
14     }
15 }
16
17 impl MirPass for SimplifyBranches {
18     fn name<'a>(&'a self) -> Cow<'a, str> {
19         Cow::Borrowed(&self.label)
20     }
21
22     fn run_pass<'a, 'tcx>(&self,
23                           tcx: TyCtxt<'a, 'tcx, 'tcx>,
24                           _src: MirSource<'tcx>,
25                           mir: &mut Body<'tcx>) {
26         for block in mir.basic_blocks_mut() {
27             let terminator = block.terminator_mut();
28             terminator.kind = match terminator.kind {
29                 TerminatorKind::SwitchInt {
30                     discr: Operand::Constant(ref c), switch_ty, ref values, ref targets, ..
31                 } => {
32                     let switch_ty = ParamEnv::empty().and(switch_ty);
33                     let constant = c.literal.assert_bits(tcx, switch_ty);
34                     if let Some(constant) = constant {
35                         let (otherwise, targets) = targets.split_last().unwrap();
36                         let mut ret = TerminatorKind::Goto { target: *otherwise };
37                         for (&v, t) in values.iter().zip(targets.iter()) {
38                             if v == constant {
39                                 ret = TerminatorKind::Goto { target: *t };
40                                 break;
41                             }
42                         }
43                         ret
44                     } else {
45                         continue
46                     }
47                 },
48                 TerminatorKind::Assert {
49                     target, cond: Operand::Constant(ref c), expected, ..
50                 } if (c.literal.assert_bool(tcx) == Some(true)) == expected =>
51                     TerminatorKind::Goto { target },
52                 TerminatorKind::FalseEdges { real_target, .. } => {
53                     TerminatorKind::Goto { target: real_target }
54                 },
55                 TerminatorKind::FalseUnwind { real_target, .. } => {
56                     TerminatorKind::Goto { target: real_target }
57                 },
58                 _ => continue
59             };
60         }
61     }
62 }