miri/math.rs
1use std::ops::Neg;
2use std::{f32, f64};
3
4use rand::Rng as _;
5use rustc_apfloat::Float;
6use rustc_apfloat::ieee::{DoubleS, IeeeFloat, Semantics, SingleS};
7use rustc_middle::ty::{self, FloatTy, ScalarInt};
8
9use crate::*;
10
11/// Disturbes a floating-point result by a relative error in the range (-2^scale, 2^scale).
12pub(crate) fn apply_random_float_error<F: rustc_apfloat::Float>(
13 ecx: &mut crate::MiriInterpCx<'_>,
14 val: F,
15 err_scale: i32,
16) -> F {
17 if !ecx.machine.float_nondet
18 || matches!(ecx.machine.float_rounding_error, FloatRoundingErrorMode::None)
19 // relative errors don't do anything to zeros... avoid messing up the sign
20 || val.is_zero()
21 // The logic below makes no sense if the input is already non-finite.
22 || !val.is_finite()
23 {
24 return val;
25 }
26 let rng = ecx.machine.rng.get_mut();
27
28 // Generate a random integer in the range [0, 2^PREC).
29 // (When read as binary, the position of the first `1` determines the exponent,
30 // and the remaining bits fill the mantissa. `PREC` is one plus the size of the mantissa,
31 // so this all works out.)
32 let r = F::from_u128(match ecx.machine.float_rounding_error {
33 FloatRoundingErrorMode::Random => rng.random_range(0..(1 << F::PRECISION)),
34 FloatRoundingErrorMode::Max => (1 << F::PRECISION) - 1, // force max error
35 FloatRoundingErrorMode::None => unreachable!(),
36 })
37 .value;
38 // Multiply this with 2^(scale - PREC). The result is between 0 and
39 // 2^PREC * 2^(scale - PREC) = 2^scale.
40 let err = r.scalbn(err_scale.strict_sub(F::PRECISION.try_into().unwrap()));
41 // give it a random sign
42 let err = if rng.random() { -err } else { err };
43 // Compute `val*(1+err)`, distributed out as `val + val*err` to avoid the imprecise addition
44 // error being amplified by multiplication.
45 (val + (val * err).value).value
46}
47
48/// Applies an error of `[-N, +N]` ULP to the given value.
49pub(crate) fn apply_random_float_error_ulp<F: rustc_apfloat::Float>(
50 ecx: &mut crate::MiriInterpCx<'_>,
51 val: F,
52 max_error: u32,
53) -> F {
54 // We could try to be clever and reuse `apply_random_float_error`, but that is hard to get right
55 // (see <https://github.com/rust-lang/miri/pull/4558#discussion_r2316838085> for why) so we
56 // implement the logic directly instead.
57 if !ecx.machine.float_nondet
58 || matches!(ecx.machine.float_rounding_error, FloatRoundingErrorMode::None)
59 // FIXME: also disturb zeros? That requires a lot more cases in `fixed_float_value`
60 // and might make the std test suite quite unhappy.
61 || val.is_zero()
62 // The logic below makes no sense if the input is already non-finite.
63 || !val.is_finite()
64 {
65 return val;
66 }
67 let rng = ecx.machine.rng.get_mut();
68
69 let max_error = i64::from(max_error);
70 let error = match ecx.machine.float_rounding_error {
71 FloatRoundingErrorMode::Random => rng.random_range(-max_error..=max_error),
72 FloatRoundingErrorMode::Max =>
73 if rng.random() {
74 max_error
75 } else {
76 -max_error
77 },
78 FloatRoundingErrorMode::None => unreachable!(),
79 };
80 // If upwards ULP and downwards ULP differ, we take the average.
81 let ulp = (((val.next_up().value - val).value + (val - val.next_down().value).value).value
82 / F::from_u128(2).value)
83 .value;
84 // Shift the value by N times the ULP
85 (val + (ulp * F::from_i128(error.into()).value).value).value
86}
87
88/// Applies an error of `[-N, +N]` ULP to the given value.
89/// Will fail if `val` is not a floating point number.
90pub(crate) fn apply_random_float_error_to_imm<'tcx>(
91 ecx: &mut MiriInterpCx<'tcx>,
92 val: ImmTy<'tcx>,
93 max_error: u32,
94) -> InterpResult<'tcx, ImmTy<'tcx>> {
95 let scalar = val.to_scalar_int()?;
96 let res: ScalarInt = match val.layout.ty.kind() {
97 ty::Float(FloatTy::F16) =>
98 apply_random_float_error_ulp(ecx, scalar.to_f16(), max_error).into(),
99 ty::Float(FloatTy::F32) =>
100 apply_random_float_error_ulp(ecx, scalar.to_f32(), max_error).into(),
101 ty::Float(FloatTy::F64) =>
102 apply_random_float_error_ulp(ecx, scalar.to_f64(), max_error).into(),
103 ty::Float(FloatTy::F128) =>
104 apply_random_float_error_ulp(ecx, scalar.to_f128(), max_error).into(),
105 _ => bug!("intrinsic called with non-float input type"),
106 };
107
108 interp_ok(ImmTy::from_scalar_int(res, val.layout))
109}
110
111/// Given a floating-point operation and a floating-point value, clamps the result to the output
112/// range of the given operation according to the C standard, if any.
113pub(crate) fn clamp_float_value<S: Semantics>(
114 intrinsic_name: &str,
115 val: IeeeFloat<S>,
116) -> IeeeFloat<S>
117where
118 IeeeFloat<S>: IeeeExt,
119{
120 let zero = IeeeFloat::<S>::ZERO;
121 let one = IeeeFloat::<S>::one();
122 let two = IeeeFloat::<S>::two();
123 let pi = IeeeFloat::<S>::pi();
124 let pi_over_2 = (pi / two).value;
125
126 match intrinsic_name {
127 // sin, cos, tanh: [-1, 1]
128 #[rustfmt::skip]
129 | "sinf32"
130 | "sinf64"
131 | "cosf32"
132 | "cosf64"
133 | "tanhf"
134 | "tanh"
135 => val.clamp(one.neg(), one),
136
137 // exp: [0, +INF)
138 "expf32" | "exp2f32" | "expf64" | "exp2f64" => val.maximum(zero),
139
140 // cosh: [1, +INF)
141 "coshf" | "cosh" => val.maximum(one),
142
143 // acos: [0, π]
144 "acosf" | "acos" => val.clamp(zero, pi),
145
146 // asin: [-π, +π]
147 "asinf" | "asin" => val.clamp(pi.neg(), pi),
148
149 // atan: (-π/2, +π/2)
150 "atanf" | "atan" => val.clamp(pi_over_2.neg(), pi_over_2),
151
152 // erfc: (-1, 1)
153 "erff" | "erf" => val.clamp(one.neg(), one),
154
155 // erfc: (0, 2)
156 "erfcf" | "erfc" => val.clamp(zero, two),
157
158 // atan2(y, x): arctan(y/x) in [−π, +π]
159 "atan2f" | "atan2" => val.clamp(pi.neg(), pi),
160
161 _ => val,
162 }
163}
164
165/// For the intrinsics:
166/// - sinf32, sinf64, sinhf, sinh
167/// - cosf32, cosf64, coshf, cosh
168/// - tanhf, tanh, atanf, atan, atan2f, atan2
169/// - expf32, expf64, exp2f32, exp2f64
170/// - logf32, logf64, log2f32, log2f64, log10f32, log10f64
171/// - powf32, powf64
172/// - erff, erf, erfcf, erfc
173/// - hypotf, hypot
174///
175/// # Return
176///
177/// Returns `Some(output)` if the `intrinsic` results in a defined fixed `output` specified in the C standard
178/// (specifically, C23 annex F.10) when given `args` as arguments. Outputs that are unaffected by a relative error
179/// (such as INF and zero) are not handled here, they are assumed to be handled by the underlying
180/// implementation. Returns `None` if no specific value is guaranteed.
181///
182/// # Note
183///
184/// For `powf*` operations of the form:
185///
186/// - `(SNaN)^(±0)`
187/// - `1^(SNaN)`
188///
189/// The result is implementation-defined:
190/// - musl returns for both `1.0`
191/// - glibc returns for both `NaN`
192///
193/// This discrepancy exists because SNaN handling is not consistently defined across platforms,
194/// and the C standard leaves behavior for SNaNs unspecified.
195///
196/// Miri chooses to adhere to both implementations and returns either one of them non-deterministically.
197pub(crate) fn fixed_float_value<S: Semantics>(
198 ecx: &mut MiriInterpCx<'_>,
199 intrinsic_name: &str,
200 args: &[IeeeFloat<S>],
201) -> Option<IeeeFloat<S>>
202where
203 IeeeFloat<S>: IeeeExt,
204{
205 let this = ecx.eval_context_mut();
206 let one = IeeeFloat::<S>::one();
207 let two = IeeeFloat::<S>::two();
208 let three = IeeeFloat::<S>::three();
209 let pi = IeeeFloat::<S>::pi();
210 let pi_over_2 = (pi / two).value;
211 let pi_over_4 = (pi_over_2 / two).value;
212
213 // Remove `f32`/`f64` suffix, if any.
214 let name = intrinsic_name
215 .strip_suffix("f32")
216 .or_else(|| intrinsic_name.strip_suffix("f64"))
217 .unwrap_or(intrinsic_name);
218 // Also strip trailing `f` (indicates "float"), with an exception for "erf" to avoid
219 // removing that `f`.
220 let name = if name == "erf" { name } else { name.strip_suffix("f").unwrap_or(name) };
221 Some(match (name, args) {
222 // cos(±0) and cosh(±0)= 1
223 ("cos" | "cosh", [input]) if input.is_zero() => one,
224
225 // e^0 = 1
226 ("exp" | "exp2", [input]) if input.is_zero() => one,
227
228 // tanh(±INF) = ±1
229 ("tanh", [input]) if input.is_infinite() => one.copy_sign(*input),
230
231 // atan(±INF) = ±π/2
232 ("atan", [input]) if input.is_infinite() => pi_over_2.copy_sign(*input),
233
234 // erf(±INF) = ±1
235 ("erf", [input]) if input.is_infinite() => one.copy_sign(*input),
236
237 // erfc(-INF) = 2
238 ("erfc", [input]) if input.is_neg_infinity() => (one + one).value,
239
240 // hypot(x, ±0) = abs(x), if x is not a NaN.
241 // `_hypot` is the Windows name for this.
242 ("_hypot" | "hypot", [x, y]) if !x.is_nan() && y.is_zero() => x.abs(),
243
244 // atan2(±0,−0) = ±π.
245 // atan2(±0, y) = ±π for y < 0.
246 // Must check for non NaN because `y.is_negative()` also applies to NaN.
247 ("atan2", [x, y]) if (x.is_zero() && (y.is_negative() && !y.is_nan())) => pi.copy_sign(*x),
248
249 // atan2(±x,−∞) = ±π for finite x > 0.
250 ("atan2", [x, y]) if (!x.is_zero() && !x.is_infinite()) && y.is_neg_infinity() =>
251 pi.copy_sign(*x),
252
253 // atan2(x, ±0) = −π/2 for x < 0.
254 // atan2(x, ±0) = π/2 for x > 0.
255 ("atan2", [x, y]) if !x.is_zero() && y.is_zero() => pi_over_2.copy_sign(*x),
256
257 //atan2(±∞, −∞) = ±3π/4
258 ("atan2", [x, y]) if x.is_infinite() && y.is_neg_infinity() =>
259 (pi_over_4 * three).value.copy_sign(*x),
260
261 //atan2(±∞, +∞) = ±π/4
262 ("atan2", [x, y]) if x.is_infinite() && y.is_pos_infinity() => pi_over_4.copy_sign(*x),
263
264 // atan2(±∞, y) returns ±π/2 for finite y.
265 ("atan2", [x, y]) if x.is_infinite() && (!y.is_infinite() && !y.is_nan()) =>
266 pi_over_2.copy_sign(*x),
267
268 // (-1)^(±INF) = 1
269 ("pow", [base, exp]) if *base == -one && exp.is_infinite() => one,
270
271 // 1^y = 1 for any y, even a NaN
272 ("pow", [base, exp]) if *base == one => {
273 let rng = this.machine.rng.get_mut();
274 // SNaN exponents get special treatment: they might return 1, or a NaN.
275 let return_nan = exp.is_signaling() && this.machine.float_nondet && rng.random();
276 // Handle both the musl and glibc cases non-deterministically.
277 if return_nan { this.generate_nan(args) } else { one }
278 }
279
280 // x^(±0) = 1 for any x, even a NaN
281 ("pow", [base, exp]) if exp.is_zero() => {
282 let rng = this.machine.rng.get_mut();
283 // SNaN bases get special treatment: they might return 1, or a NaN.
284 let return_nan = base.is_signaling() && this.machine.float_nondet && rng.random();
285 // Handle both the musl and glibc cases non-deterministically.
286 if return_nan { this.generate_nan(args) } else { one }
287 }
288
289 // There are a lot of cases for fixed outputs according to the C Standard, but these are
290 // mainly INF or zero which are not affected by the applied error.
291 _ => return None,
292 })
293}
294
295/// Returns `Some(output)` if `powi` (called `pown` in C) results in a fixed value specified in the
296/// C standard (specifically, C23 annex F.10.4.6) when doing `base^exp`. Otherwise, returns `None`.
297pub(crate) fn fixed_powi_value<S: Semantics>(
298 ecx: &mut MiriInterpCx<'_>,
299 base: IeeeFloat<S>,
300 exp: i32,
301) -> Option<IeeeFloat<S>>
302where
303 IeeeFloat<S>: IeeeExt,
304{
305 match exp {
306 0 => {
307 let one = IeeeFloat::<S>::one();
308 let rng = ecx.machine.rng.get_mut();
309 let return_nan = ecx.machine.float_nondet && rng.random() && base.is_signaling();
310 // For SNaN treatment, we are consistent with `powf`above.
311 // (We wouldn't have two, unlike powf all implementations seem to agree for powi,
312 // but for now we are maximally conservative.)
313 Some(if return_nan { ecx.generate_nan(&[base]) } else { one })
314 }
315
316 _ => None,
317 }
318}
319
320pub(crate) fn sqrt<F: Float>(x: F) -> F {
321 match x.category() {
322 // preserve zero sign
323 rustc_apfloat::Category::Zero => x,
324 // propagate NaN
325 rustc_apfloat::Category::NaN => x,
326 // sqrt of negative number is NaN
327 _ if x.is_negative() => F::NAN,
328 // sqrt(∞) = ∞
329 rustc_apfloat::Category::Infinity => F::INFINITY,
330 rustc_apfloat::Category::Normal => {
331 // Floating point precision, excluding the integer bit
332 let prec = i32::try_from(F::PRECISION).unwrap() - 1;
333
334 // x = 2^(exp - prec) * mant
335 // where mant is an integer with prec+1 bits
336 // mant is a u128, which should be large enough for the largest prec (112 for f128)
337 let mut exp = x.ilogb();
338 let mut mant = x.scalbn(prec - exp).to_u128(128).value;
339
340 if exp % 2 != 0 {
341 // Make exponent even, so it can be divided by 2
342 exp -= 1;
343 mant <<= 1;
344 }
345
346 // Bit-by-bit (base-2 digit-by-digit) sqrt of mant.
347 // mant is treated here as a fixed point number with prec fractional bits.
348 // mant will be shifted left by one bit to have an extra fractional bit, which
349 // will be used to determine the rounding direction.
350
351 // res is the truncated sqrt of mant, where one bit is added at each iteration.
352 let mut res = 0u128;
353 // rem is the remainder with the current res
354 // rem_i = 2^i * ((mant<<1) - res_i^2)
355 // starting with res = 0, rem = mant<<1
356 let mut rem = mant << 1;
357 // s_i = 2*res_i
358 let mut s = 0u128;
359 // d is used to iterate over bits, from high to low (d_i = 2^(-i))
360 let mut d = 1u128 << (prec + 1);
361
362 // For iteration j=i+1, we need to find largest b_j = 0 or 1 such that
363 // (res_i + b_j * 2^(-j))^2 <= mant<<1
364 // Expanding (a + b)^2 = a^2 + b^2 + 2*a*b:
365 // res_i^2 + (b_j * 2^(-j))^2 + 2 * res_i * b_j * 2^(-j) <= mant<<1
366 // And rearranging the terms:
367 // b_j^2 * 2^(-j) + 2 * res_i * b_j <= 2^j * (mant<<1 - res_i^2)
368 // b_j^2 * 2^(-j) + 2 * res_i * b_j <= rem_i
369
370 while d != 0 {
371 // Probe b_j^2 * 2^(-j) + 2 * res_i * b_j <= rem_i with b_j = 1:
372 // t = 2*res_i + 2^(-j)
373 let t = s + d;
374 if rem >= t {
375 // b_j should be 1, so make res_j = res_i + 2^(-j) and adjust rem
376 res += d;
377 s += d + d;
378 rem -= t;
379 }
380 // Adjust rem for next iteration
381 rem <<= 1;
382 // Shift iterator
383 d >>= 1;
384 }
385
386 // Remove extra fractional bit from result, rounding to nearest.
387 // If the last bit is 0, then the nearest neighbor is definitely the lower one.
388 // If the last bit is 1, it sounds like this may either be a tie (if there's
389 // infinitely many 0s after this 1), or the nearest neighbor is the upper one.
390 // However, since square roots are either exact or irrational, and an exact root
391 // would lead to the last "extra" bit being 0, we can exclude a tie in this case.
392 // We therefore always round up if the last bit is 1. When the last bit is 0,
393 // adding 1 will not do anything since the shift will discard it.
394 res = (res + 1) >> 1;
395
396 // Build resulting value with res as mantissa and exp/2 as exponent
397 F::from_u128(res).value.scalbn(exp / 2 - prec)
398 }
399 }
400}
401
402/// Extend functionality of `rustc_apfloat` softfloats for IEEE float types.
403pub trait IeeeExt: rustc_apfloat::Float {
404 // Some values we use:
405
406 #[inline]
407 fn one() -> Self {
408 Self::from_u128(1).value
409 }
410
411 #[inline]
412 fn two() -> Self {
413 Self::from_u128(2).value
414 }
415
416 #[inline]
417 fn three() -> Self {
418 Self::from_u128(3).value
419 }
420
421 fn pi() -> Self;
422
423 #[inline]
424 fn clamp(self, min: Self, max: Self) -> Self {
425 self.maximum(min).minimum(max)
426 }
427}
428
429macro_rules! impl_ieee_pi {
430 ($float_ty:ident, $semantic:ty) => {
431 impl IeeeExt for IeeeFloat<$semantic> {
432 #[inline]
433 fn pi() -> Self {
434 // We take the value from the standard library as the most reasonable source for an exact π here.
435 Self::from_bits($float_ty::consts::PI.to_bits().into())
436 }
437 }
438 };
439}
440
441impl_ieee_pi!(f32, SingleS);
442impl_ieee_pi!(f64, DoubleS);
443
444#[cfg(test)]
445mod tests {
446 use rustc_apfloat::ieee::{DoubleS, HalfS, IeeeFloat, QuadS, SingleS};
447
448 use super::sqrt;
449
450 #[test]
451 fn test_sqrt() {
452 #[track_caller]
453 fn test<S: rustc_apfloat::ieee::Semantics>(x: &str, expected: &str) {
454 let x: IeeeFloat<S> = x.parse().unwrap();
455 let expected: IeeeFloat<S> = expected.parse().unwrap();
456 let result = sqrt(x);
457 assert_eq!(result, expected);
458 }
459
460 fn exact_tests<S: rustc_apfloat::ieee::Semantics>() {
461 test::<S>("0", "0");
462 test::<S>("1", "1");
463 test::<S>("1.5625", "1.25");
464 test::<S>("2.25", "1.5");
465 test::<S>("4", "2");
466 test::<S>("5.0625", "2.25");
467 test::<S>("9", "3");
468 test::<S>("16", "4");
469 test::<S>("25", "5");
470 test::<S>("36", "6");
471 test::<S>("49", "7");
472 test::<S>("64", "8");
473 test::<S>("81", "9");
474 test::<S>("100", "10");
475
476 test::<S>("0.5625", "0.75");
477 test::<S>("0.25", "0.5");
478 test::<S>("0.0625", "0.25");
479 test::<S>("0.00390625", "0.0625");
480 }
481
482 exact_tests::<HalfS>();
483 exact_tests::<SingleS>();
484 exact_tests::<DoubleS>();
485 exact_tests::<QuadS>();
486
487 test::<SingleS>("2", "1.4142135");
488 test::<DoubleS>("2", "1.4142135623730951");
489
490 test::<SingleS>("1.1", "1.0488088");
491 test::<DoubleS>("1.1", "1.0488088481701516");
492
493 test::<SingleS>("2.2", "1.4832398");
494 test::<DoubleS>("2.2", "1.4832396974191326");
495
496 test::<SingleS>("1.22101e-40", "1.10499205e-20");
497 test::<DoubleS>("1.22101e-310", "1.1049932126488395e-155");
498
499 test::<SingleS>("3.4028235e38", "1.8446743e19");
500 test::<DoubleS>("1.7976931348623157e308", "1.3407807929942596e154");
501 }
502}