1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! A pass that simplifies branches when their condition is known.
13 use rustc::ty::{self, TyCtxt};
14 use rustc::middle::const_val::ConstVal;
16 use transform::{MirPass, MirSource};
20 pub struct SimplifyBranches { label: String }
22 impl SimplifyBranches {
23 pub fn new(label: &str) -> Self {
24 SimplifyBranches { label: format!("SimplifyBranches-{}", label) }
28 impl MirPass for SimplifyBranches {
29 fn name<'a>(&'a self) -> Cow<'a, str> {
30 Cow::Borrowed(&self.label)
33 fn run_pass<'a, 'tcx>(&self,
34 _tcx: TyCtxt<'a, 'tcx, 'tcx>,
36 mir: &mut Mir<'tcx>) {
37 for block in mir.basic_blocks_mut() {
38 let terminator = block.terminator_mut();
39 terminator.kind = match terminator.kind {
40 TerminatorKind::SwitchInt { discr: Operand::Constant(box Constant {
41 literal: Literal::Value { ref value }, ..
42 }), ref values, ref targets, .. } => {
43 if let Some(ref constint) = value.val.to_const_int() {
44 let (otherwise, targets) = targets.split_last().unwrap();
45 let mut ret = TerminatorKind::Goto { target: *otherwise };
46 for (v, t) in values.iter().zip(targets.iter()) {
48 ret = TerminatorKind::Goto { target: *t };
57 TerminatorKind::Assert { target, cond: Operand::Constant(box Constant {
58 literal: Literal::Value {
59 value: &ty::Const { val: ConstVal::Bool(cond), .. }
61 }), expected, .. } if cond == expected => {
62 TerminatorKind::Goto { target: target }
64 TerminatorKind::FalseEdges { real_target, .. } => {
65 TerminatorKind::Goto { target: real_target }