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 // This is non-deterministic because LLVM can treat SNaN as QNaN, and because
276 // implementation behavior differs between glibc and musl.
277 let return_nan = exp.is_signaling() && this.machine.float_nondet && rng.random();
278 if return_nan { this.generate_nan(args) } else { one }
279 }
280
281 // x^(±0) = 1 for any x, even a NaN
282 ("pow", [base, exp]) if exp.is_zero() => {
283 let rng = this.machine.rng.get_mut();
284 // SNaN bases get special treatment: they might return 1, or a NaN.
285 // This is non-deterministic because LLVM can treat SNaN as QNaN, and because
286 // implementation behavior differs between glibc and musl.
287 let return_nan = base.is_signaling() && this.machine.float_nondet && rng.random();
288 if return_nan { this.generate_nan(args) } else { one }
289 }
290
291 // There are a lot of cases for fixed outputs according to the C Standard, but these are
292 // mainly INF or zero which are not affected by the applied error.
293 _ => return None,
294 })
295}
296
297/// Returns `Some(output)` if `powi` (called `pown` in C) results in a fixed value specified in the
298/// C standard (specifically, C23 annex F.10.4.6) when doing `base^exp`. Otherwise, returns `None`.
299pub(crate) fn fixed_powi_value<S: Semantics>(
300 ecx: &mut MiriInterpCx<'_>,
301 base: IeeeFloat<S>,
302 exp: i32,
303) -> Option<IeeeFloat<S>>
304where
305 IeeeFloat<S>: IeeeExt,
306{
307 match exp {
308 0 => {
309 let one = IeeeFloat::<S>::one();
310 let rng = ecx.machine.rng.get_mut();
311 // SNaN bases get special treatment: they might return 1, or a NaN.
312 // This is non-deterministic because LLVM can treat SNaN as QNaN.
313 let return_nan = base.is_signaling() && ecx.machine.float_nondet && rng.random();
314 Some(if return_nan { ecx.generate_nan(&[base]) } else { one })
315 }
316
317 _ => None,
318 }
319}
320
321pub(crate) fn sqrt<F: Float>(x: F) -> F {
322 match x.category() {
323 // preserve zero sign
324 rustc_apfloat::Category::Zero => x,
325 // propagate NaN
326 rustc_apfloat::Category::NaN => x,
327 // sqrt of negative number is NaN
328 _ if x.is_negative() => F::NAN,
329 // sqrt(∞) = ∞
330 rustc_apfloat::Category::Infinity => F::INFINITY,
331 rustc_apfloat::Category::Normal => {
332 // Floating point precision, excluding the integer bit
333 let prec = i32::try_from(F::PRECISION).unwrap() - 1;
334
335 // x = 2^(exp - prec) * mant
336 // where mant is an integer with prec+1 bits
337 // mant is a u128, which should be large enough for the largest prec (112 for f128)
338 let mut exp = x.ilogb();
339 let mut mant = x.scalbn(prec - exp).to_u128(128).value;
340
341 if exp % 2 != 0 {
342 // Make exponent even, so it can be divided by 2
343 exp -= 1;
344 mant <<= 1;
345 }
346
347 // Bit-by-bit (base-2 digit-by-digit) sqrt of mant.
348 // mant is treated here as a fixed point number with prec fractional bits.
349 // mant will be shifted left by one bit to have an extra fractional bit, which
350 // will be used to determine the rounding direction.
351
352 // res is the truncated sqrt of mant, where one bit is added at each iteration.
353 let mut res = 0u128;
354 // rem is the remainder with the current res
355 // rem_i = 2^i * ((mant<<1) - res_i^2)
356 // starting with res = 0, rem = mant<<1
357 let mut rem = mant << 1;
358 // s_i = 2*res_i
359 let mut s = 0u128;
360 // d is used to iterate over bits, from high to low (d_i = 2^(-i))
361 let mut d = 1u128 << (prec + 1);
362
363 // For iteration j=i+1, we need to find largest b_j = 0 or 1 such that
364 // (res_i + b_j * 2^(-j))^2 <= mant<<1
365 // Expanding (a + b)^2 = a^2 + b^2 + 2*a*b:
366 // res_i^2 + (b_j * 2^(-j))^2 + 2 * res_i * b_j * 2^(-j) <= mant<<1
367 // And rearranging the terms:
368 // b_j^2 * 2^(-j) + 2 * res_i * b_j <= 2^j * (mant<<1 - res_i^2)
369 // b_j^2 * 2^(-j) + 2 * res_i * b_j <= rem_i
370
371 while d != 0 {
372 // Probe b_j^2 * 2^(-j) + 2 * res_i * b_j <= rem_i with b_j = 1:
373 // t = 2*res_i + 2^(-j)
374 let t = s + d;
375 if rem >= t {
376 // b_j should be 1, so make res_j = res_i + 2^(-j) and adjust rem
377 res += d;
378 s += d + d;
379 rem -= t;
380 }
381 // Adjust rem for next iteration
382 rem <<= 1;
383 // Shift iterator
384 d >>= 1;
385 }
386
387 // Remove extra fractional bit from result, rounding to nearest.
388 // If the last bit is 0, then the nearest neighbor is definitely the lower one.
389 // If the last bit is 1, it sounds like this may either be a tie (if there's
390 // infinitely many 0s after this 1), or the nearest neighbor is the upper one.
391 // However, since square roots are either exact or irrational, and an exact root
392 // would lead to the last "extra" bit being 0, we can exclude a tie in this case.
393 // We therefore always round up if the last bit is 1. When the last bit is 0,
394 // adding 1 will not do anything since the shift will discard it.
395 res = (res + 1) >> 1;
396
397 // Build resulting value with res as mantissa and exp/2 as exponent
398 F::from_u128(res).value.scalbn(exp / 2 - prec)
399 }
400 }
401}
402
403/// Extend functionality of `rustc_apfloat` softfloats for IEEE float types.
404pub trait IeeeExt: rustc_apfloat::Float {
405 // Some values we use:
406
407 #[inline]
408 fn one() -> Self {
409 Self::from_u128(1).value
410 }
411
412 #[inline]
413 fn two() -> Self {
414 Self::from_u128(2).value
415 }
416
417 #[inline]
418 fn three() -> Self {
419 Self::from_u128(3).value
420 }
421
422 fn pi() -> Self;
423
424 #[inline]
425 fn clamp(self, min: Self, max: Self) -> Self {
426 self.maximum(min).minimum(max)
427 }
428}
429
430macro_rules! impl_ieee_pi {
431 ($float_ty:ident, $semantic:ty) => {
432 impl IeeeExt for IeeeFloat<$semantic> {
433 #[inline]
434 fn pi() -> Self {
435 // We take the value from the standard library as the most reasonable source for an exact π here.
436 Self::from_bits($float_ty::consts::PI.to_bits().into())
437 }
438 }
439 };
440}
441
442impl_ieee_pi!(f32, SingleS);
443impl_ieee_pi!(f64, DoubleS);
444
445#[cfg(test)]
446mod tests {
447 use rustc_apfloat::ieee::{DoubleS, HalfS, IeeeFloat, QuadS, SingleS};
448
449 use super::sqrt;
450
451 #[test]
452 fn test_sqrt() {
453 #[track_caller]
454 fn test<S: rustc_apfloat::ieee::Semantics>(x: &str, expected: &str) {
455 let x: IeeeFloat<S> = x.parse().unwrap();
456 let expected: IeeeFloat<S> = expected.parse().unwrap();
457 let result = sqrt(x);
458 assert_eq!(result, expected);
459 }
460
461 fn exact_tests<S: rustc_apfloat::ieee::Semantics>() {
462 test::<S>("0", "0");
463 test::<S>("1", "1");
464 test::<S>("1.5625", "1.25");
465 test::<S>("2.25", "1.5");
466 test::<S>("4", "2");
467 test::<S>("5.0625", "2.25");
468 test::<S>("9", "3");
469 test::<S>("16", "4");
470 test::<S>("25", "5");
471 test::<S>("36", "6");
472 test::<S>("49", "7");
473 test::<S>("64", "8");
474 test::<S>("81", "9");
475 test::<S>("100", "10");
476
477 test::<S>("0.5625", "0.75");
478 test::<S>("0.25", "0.5");
479 test::<S>("0.0625", "0.25");
480 test::<S>("0.00390625", "0.0625");
481 }
482
483 exact_tests::<HalfS>();
484 exact_tests::<SingleS>();
485 exact_tests::<DoubleS>();
486 exact_tests::<QuadS>();
487
488 test::<SingleS>("2", "1.4142135");
489 test::<DoubleS>("2", "1.4142135623730951");
490
491 test::<SingleS>("1.1", "1.0488088");
492 test::<DoubleS>("1.1", "1.0488088481701516");
493
494 test::<SingleS>("2.2", "1.4832398");
495 test::<DoubleS>("2.2", "1.4832396974191326");
496
497 test::<SingleS>("1.22101e-40", "1.10499205e-20");
498 test::<DoubleS>("1.22101e-310", "1.1049932126488395e-155");
499
500 test::<SingleS>("3.4028235e38", "1.8446743e19");
501 test::<DoubleS>("1.7976931348623157e308", "1.3407807929942596e154");
502 }
503}