Skip to content

Iteratively simplify const conditions #107702

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 35 additions & 21 deletions compiler/rustc_mir_transform/src/simplify_branches.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::dataflow_const_prop::DataflowConstProp;
use crate::MirPass;
use rustc_middle::mir::*;
use rustc_middle::ty::TyCtxt;
Expand All @@ -19,29 +20,42 @@ impl<'tcx> MirPass<'tcx> for SimplifyConstCondition {
}

fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
let param_env = tcx.param_env(body.source.def_id());
for block in body.basic_blocks_mut() {
let terminator = block.terminator_mut();
terminator.kind = match terminator.kind {
TerminatorKind::SwitchInt {
discr: Operand::Constant(ref c), ref targets, ..
} => {
let constant = c.literal.try_eval_bits(tcx, param_env, c.ty());
if let Some(constant) = constant {
let target = targets.target_for_value(constant);
TerminatorKind::Goto { target }
} else {
continue;
loop {
let mut changed = false;
let param_env = tcx.param_env(body.source.def_id());
for block in body.basic_blocks_mut() {
let terminator = block.terminator_mut();
terminator.kind = match terminator.kind {
TerminatorKind::SwitchInt {
discr: Operand::Constant(ref c),
ref targets,
..
} => {
let constant = c.literal.try_eval_bits(tcx, param_env, c.ty());
if let Some(constant) = constant {
changed = true;
let target = targets.target_for_value(constant);
TerminatorKind::Goto { target }
} else {
continue;
}
}
}
TerminatorKind::Assert {
target, cond: Operand::Constant(ref c), expected, ..
} => match c.literal.try_eval_bool(tcx, param_env) {
Some(v) if v == expected => TerminatorKind::Goto { target },
TerminatorKind::Assert {
target,
cond: Operand::Constant(ref c),
expected,
..
} => match c.literal.try_eval_bool(tcx, param_env) {
Some(v) if v == expected => {
changed = true;
TerminatorKind::Goto { target }
}
_ => continue,
},
_ => continue,
},
_ => continue,
};
};
}
if !changed { break } else { DataflowConstProp.run_pass(tcx, body) }
}
}
}