ScalarInt: add methods to assert being a (u)int of given size

This commit is contained in:
Ralf Jung 2024-04-18 08:38:37 +02:00
parent 5e6184cdb7
commit 42220f0930
13 changed files with 78 additions and 72 deletions

View file

@ -796,7 +796,7 @@ impl<'tcx> Visitor<'tcx> for ConstPropagator<'_, 'tcx> {
if let Some(ref value) = self.eval_operand(discr)
&& let Some(value_const) = self.use_ecx(|this| this.ecx.read_scalar(value))
&& let Ok(constant) = value_const.try_to_int()
&& let Ok(constant) = constant.to_bits(constant.size())
&& let Ok(constant) = constant.try_to_bits(constant.size())
{
// We managed to evaluate the discriminant, so we know we only need to visit
// one target.

View file

@ -369,8 +369,7 @@ impl<'tcx> SimplifyMatch<'tcx> for SimplifyToExp {
}
fn int_equal(l: ScalarInt, r: impl Into<u128>, size: Size) -> bool {
l.try_to_int(l.size()).unwrap()
== ScalarInt::try_from_uint(r, size).unwrap().try_to_int(size).unwrap()
l.assert_int(l.size()) == ScalarInt::try_from_uint(r, size).unwrap().assert_int(size)
}
// We first compare the two branches, and then the other branches need to fulfill the same conditions.

View file

@ -490,14 +490,14 @@ impl<'tcx> Validator<'_, 'tcx> {
}
_ => None,
};
match rhs_val.map(|x| x.try_to_uint(sz).unwrap()) {
match rhs_val.map(|x| x.assert_uint(sz)) {
// for the zero test, int vs uint does not matter
Some(x) if x != 0 => {} // okay
_ => return Err(Unpromotable), // value not known or 0 -- not okay
}
// Furthermore, for signed divison, we also have to exclude `int::MIN / -1`.
if lhs_ty.is_signed() {
match rhs_val.map(|x| x.try_to_int(sz).unwrap()) {
match rhs_val.map(|x| x.assert_int(sz)) {
Some(-1) | None => {
// The RHS is -1 or unknown, so we have to be careful.
// But is the LHS int::MIN?
@ -508,7 +508,7 @@ impl<'tcx> Validator<'_, 'tcx> {
_ => None,
};
let lhs_min = sz.signed_int_min();
match lhs_val.map(|x| x.try_to_int(sz).unwrap()) {
match lhs_val.map(|x| x.assert_int(sz)) {
Some(x) if x != lhs_min => {} // okay
_ => return Err(Unpromotable), // value not known or int::MIN -- not okay
}