Skip to content

Commit 7854067

Browse files
committed
Saturating add/sub intrinsic emulation refactor/comments #58030
1 parent da13fbd commit 7854067

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed

src/librustc_mir/interpret/intrinsics.rs

+12-5
Original file line numberDiff line numberDiff line change
@@ -132,15 +132,22 @@ impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> EvalContext<'a, 'mir, 'tcx, M>
132132
BinOp::Sub
133133
}, l, r)?;
134134
let val = if overflowed {
135-
// For signed ints the saturated value depends on the
136-
// sign of the first term
137-
let first_term: u128 = l.to_scalar()?.to_bits(l.layout.size)?;
138135
let num_bits = l.layout.size.bits();
139136
if l.layout.abi.is_signed() {
140-
if first_term & (1 << (num_bits-1)) == 0 { // first term is positive
137+
// For signed ints the saturated value depends on the sign of the first
138+
// term since the sign of the second term can be inferred from this and
139+
// the fact that the operation has overflowed (if either is 0 no
140+
// overflow can occur)
141+
let first_term: u128 = l.to_scalar()?.to_bits(l.layout.size)?;
142+
let first_term_pos = first_term & (1 << (num_bits-1)) == 0;
143+
if first_term_pos {
144+
// Negative overflow not possible since the positive first term
145+
// can only increase an (in range) negative term for addition
146+
// or corresponding negated positive term for subtraction
141147
Scalar::from_uint((1u128 << (num_bits - 1)) - 1, // max positive
142148
Size::from_bits(num_bits))
143-
} else { // first term is negative
149+
} else {
150+
// Positive overflow not possible for similar reason
144151
// max negative
145152
Scalar::from_uint(1u128 << (num_bits - 1), Size::from_bits(num_bits))
146153
}

0 commit comments

Comments
 (0)