1 //! A pass that simplifies branches when their condition is known.
3 use rustc::ty::{TyCtxt, ParamEnv};
5 use crate::transform::{MirPass, MirSource};
9 pub struct SimplifyBranches { label: String }
11 impl SimplifyBranches {
12 pub fn new(label: &str) -> Self {
13 SimplifyBranches { label: format!("SimplifyBranches-{}", label) }
17 impl MirPass for SimplifyBranches {
18 fn name<'a>(&'a self) -> Cow<'a, str> {
19 Cow::Borrowed(&self.label)
24 tcx: TyCtxt<'tcx, 'tcx>,
25 _src: MirSource<'tcx>,
26 body: &mut Body<'tcx>,
28 for block in body.basic_blocks_mut() {
29 let terminator = block.terminator_mut();
30 terminator.kind = match terminator.kind {
31 TerminatorKind::SwitchInt {
32 discr: Operand::Constant(ref c), switch_ty, ref values, ref targets, ..
34 let switch_ty = ParamEnv::empty().and(switch_ty);
35 let constant = c.literal.assert_bits(tcx, switch_ty);
36 if let Some(constant) = constant {
37 let (otherwise, targets) = targets.split_last().unwrap();
38 let mut ret = TerminatorKind::Goto { target: *otherwise };
39 for (&v, t) in values.iter().zip(targets.iter()) {
41 ret = TerminatorKind::Goto { target: *t };
50 TerminatorKind::Assert {
51 target, cond: Operand::Constant(ref c), expected, ..
52 } if (c.literal.assert_bool(tcx) == Some(true)) == expected =>
53 TerminatorKind::Goto { target },
54 TerminatorKind::FalseEdges { real_target, .. } => {
55 TerminatorKind::Goto { target: real_target }
57 TerminatorKind::FalseUnwind { real_target, .. } => {
58 TerminatorKind::Goto { target: real_target }