1 //! A pass that simplifies branches when their condition is known.
3 use crate::transform::MirPass;
4 use rustc_middle::mir::*;
5 use rustc_middle::ty::TyCtxt;
9 pub struct SimplifyBranches {
13 impl SimplifyBranches {
14 pub fn new(label: &str) -> Self {
15 SimplifyBranches { label: format!("SimplifyBranches-{}", label) }
19 impl<'tcx> MirPass<'tcx> for SimplifyBranches {
20 fn name(&self) -> Cow<'_, str> {
21 Cow::Borrowed(&self.label)
24 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
25 let param_env = tcx.param_env(body.source.def_id());
26 for block in body.basic_blocks_mut() {
27 let terminator = block.terminator_mut();
28 terminator.kind = match terminator.kind {
29 TerminatorKind::SwitchInt {
30 discr: Operand::Constant(ref c),
36 let constant = c.literal.try_eval_bits(tcx, param_env, switch_ty);
37 if let Some(constant) = constant {
38 let (otherwise, targets) = targets.split_last().unwrap();
39 let mut ret = TerminatorKind::Goto { target: *otherwise };
40 for (&v, t) in values.iter().zip(targets.iter()) {
42 ret = TerminatorKind::Goto { target: *t };
51 TerminatorKind::Assert {
52 target, cond: Operand::Constant(ref c), expected, ..
53 } if (c.literal.try_eval_bool(tcx, param_env) == Some(true)) == expected => {
54 TerminatorKind::Goto { target }
56 TerminatorKind::FalseEdge { real_target, .. } => {
57 TerminatorKind::Goto { target: real_target }
59 TerminatorKind::FalseUnwind { real_target, .. } => {
60 TerminatorKind::Goto { target: real_target }