2021-01-01 00:53:25 +00:00
|
|
|
use crate::MirPass;
|
2020-03-29 14:41:09 +00:00
|
|
|
use rustc_middle::mir::*;
|
|
|
|
use rustc_middle::ty::TyCtxt;
|
2016-06-08 21:10:15 +00:00
|
|
|
|
2023-04-21 21:45:25 +00:00
|
|
|
pub enum SimplifyConstCondition {
|
2023-04-18 02:17:01 +00:00
|
|
|
AfterConstProp,
|
|
|
|
Final,
|
2016-06-08 21:10:15 +00:00
|
|
|
}
|
2023-04-18 02:17:01 +00:00
|
|
|
/// A pass that replaces a branch with a goto when its condition is known.
|
2023-04-21 21:45:25 +00:00
|
|
|
impl<'tcx> MirPass<'tcx> for SimplifyConstCondition {
|
2023-04-18 02:17:01 +00:00
|
|
|
fn name(&self) -> &'static str {
|
|
|
|
match self {
|
2023-04-21 21:45:25 +00:00
|
|
|
SimplifyConstCondition::AfterConstProp => "SimplifyConstCondition-after-const-prop",
|
|
|
|
SimplifyConstCondition::Final => "SimplifyConstCondition-final",
|
2023-04-18 02:17:01 +00:00
|
|
|
}
|
2017-04-25 22:23:33 +00:00
|
|
|
}
|
|
|
|
|
2020-10-04 18:01:38 +00:00
|
|
|
fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
|
|
|
|
let param_env = tcx.param_env(body.source.def_id());
|
2019-11-06 17:00:46 +00:00
|
|
|
for block in body.basic_blocks_mut() {
|
2019-10-04 04:55:28 +00:00
|
|
|
let terminator = block.terminator_mut();
|
2016-06-08 21:10:15 +00:00
|
|
|
terminator.kind = match terminator.kind {
|
2018-07-21 23:01:07 +00:00
|
|
|
TerminatorKind::SwitchInt {
|
2022-12-04 00:03:27 +00:00
|
|
|
discr: Operand::Constant(ref c), ref targets, ..
|
2018-07-21 23:01:07 +00:00
|
|
|
} => {
|
2022-12-04 00:03:27 +00:00
|
|
|
let constant = c.literal.try_eval_bits(tcx, param_env, c.ty());
|
2018-12-13 10:15:18 +00:00
|
|
|
if let Some(constant) = constant {
|
2021-11-27 02:18:14 +00:00
|
|
|
let target = targets.target_for_value(constant);
|
|
|
|
TerminatorKind::Goto { target }
|
2017-02-02 06:41:01 +00:00
|
|
|
} else {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
}
|
2018-07-21 23:01:07 +00:00
|
|
|
TerminatorKind::Assert {
|
|
|
|
target, cond: Operand::Constant(ref c), expected, ..
|
2020-10-21 00:00:00 +00:00
|
|
|
} => match c.literal.try_eval_bool(tcx, param_env) {
|
|
|
|
Some(v) if v == expected => TerminatorKind::Goto { target },
|
|
|
|
_ => continue,
|
|
|
|
},
|
2016-06-08 21:10:15 +00:00
|
|
|
_ => continue,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|