Debian Codegraph @

mfbt/FloatingPoint.h

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 /* Various predicates and operations on IEEE-754 floating point types. */
8
9 #ifndef mozilla_FloatingPoint_h
10 #define mozilla_FloatingPoint_h
11
12 #include "mozilla/Assertions.h"
13 #include "mozilla/Attributes.h"
14 #include "mozilla/Casting.h"
15 #include "mozilla/MathAlgorithms.h"
16 #include "mozilla/MemoryChecking.h"
17 #include "mozilla/Types.h"
18
19 #include <algorithm>
20 #include <climits>
21 #include <limits>
22 #include <stdint.h>
23
24 namespace mozilla {
25
26 /*
27 * It's reasonable to ask why we have this header at all. Don't isnan,
28 * copysign, the built-in comparison operators, and the like solve these
29 * problems? Unfortunately, they don't. We've found that various compilers
30 * (MSVC, MSVC when compiling with PGO, and GCC on OS X, at least) miscompile
31 * the standard methods in various situations, so we can't use them. Some of
32 * these compilers even have problems compiling seemingly reasonable bitwise
33 * algorithms! But with some care we've found algorithms that seem to not
34 * trigger those compiler bugs.
35 *
36 * For the aforementioned reasons, be very wary of making changes to any of
37 * these algorithms. If you must make changes, keep a careful eye out for
38 * compiler bustage, particularly PGO-specific bustage.
39 */
40
41 namespace detail {
42
43 /*
44 * These implementations assume float/double are 32/64-bit single/double
45 * format number types compatible with the IEEE-754 standard. C++ doesn't
46 * require this, but we required it in implementations of these algorithms that
47 * preceded this header, so we shouldn't break anything to continue doing so.
48 */
49 template <typename T>
50 struct FloatingPointTrait;
51
52 template <>
53 struct FloatingPointTrait<float> {
54 protected:
55 using Bits = uint32_t;
56
57 static constexpr unsigned kExponentWidth = 8;
58 static constexpr unsigned kSignificandWidth = 23;
59 };
60
61 template <>
62 struct FloatingPointTrait<double> {
63 protected:
64 using Bits = uint64_t;
65
66 static constexpr unsigned kExponentWidth = 11;
67 static constexpr unsigned kSignificandWidth = 52;
68 };
69
70 } // namespace detail
71
72 /*
73 * This struct contains details regarding the encoding of floating-point
74 * numbers that can be useful for direct bit manipulation. As of now, the
75 * template parameter has to be float or double.
76 *
77 * The nested typedef |Bits| is the unsigned integral type with the same size
78 * as T: uint32_t for float and uint64_t for double (static assertions
79 * double-check these assumptions).
80 *
81 * kExponentBias is the offset that is subtracted from the exponent when
82 * computing the value, i.e. one plus the opposite of the mininum possible
83 * exponent.
84 * kExponentShift is the shift that one needs to apply to retrieve the
85 * exponent component of the value.
86 *
87 * kSignBit contains a bits mask. Bit-and-ing with this mask will result in
88 * obtaining the sign bit.
89 * kExponentBits contains the mask needed for obtaining the exponent bits and
90 * kSignificandBits contains the mask needed for obtaining the significand
91 * bits.
92 *
93 * Full details of how floating point number formats are encoded are beyond
94 * the scope of this comment. For more information, see
95 * http://en.wikipedia.org/wiki/IEEE_floating_point
96 * http://en.wikipedia.org/wiki/Floating_point#IEEE_754:_floating_point_in_modern_computers
97 */
98 template <typename T>
99 struct FloatingPoint final : private detail::FloatingPointTrait<T> {
100 private:
101 using Base = detail::FloatingPointTrait<T>;
102
103 public:
104 /**
105 * An unsigned integral type suitable for accessing the bitwise representation
106 * of T.
107 */
108 using Bits = typename Base::Bits;
109
110 static_assert(sizeof(T) == sizeof(Bits), "Bits must be same size as T");
111
112 /** The bit-width of the exponent component of T. */
113 using Base::kExponentWidth;
114
115 /** The bit-width of the significand component of T. */
116 using Base::kSignificandWidth;
117
118 static_assert(1 + kExponentWidth + kSignificandWidth == CHAR_BIT * sizeof(T),
119 "sign bit plus bit widths should sum to overall bit width");
120
121 /**
122 * The exponent field in an IEEE-754 floating point number consists of bits
123 * encoding an unsigned number. The *actual* represented exponent (for all
124 * values finite and not denormal) is that value, minus a bias |kExponentBias|
125 * so that a useful range of numbers is represented.
126 */
127 static constexpr unsigned kExponentBias = (1U << (kExponentWidth - 1)) - 1;
128
129 /**
130 * The amount by which the bits of the exponent-field in an IEEE-754 floating
131 * point number are shifted from the LSB of the floating point type.
132 */
133 static constexpr unsigned kExponentShift = kSignificandWidth;
134
135 /** The sign bit in the floating point representation. */
136 static constexpr Bits kSignBit = static_cast<Bits>(1)
137 << (CHAR_BIT * sizeof(Bits) - 1);
138
139 /** The exponent bits in the floating point representation. */
140 static constexpr Bits kExponentBits =
141 ((static_cast<Bits>(1) << kExponentWidth) - 1) << kSignificandWidth;
142
143 /** The significand bits in the floating point representation. */
144 static constexpr Bits kSignificandBits =
145 (static_cast<Bits>(1) << kSignificandWidth) - 1;
146
147 static_assert((kSignBit & kExponentBits) == 0,
148 "sign bit shouldn't overlap exponent bits");
149 static_assert((kSignBit & kSignificandBits) == 0,
150 "sign bit shouldn't overlap significand bits");
151 static_assert((kExponentBits & kSignificandBits) == 0,
152 "exponent bits shouldn't overlap significand bits");
153
154 static_assert((kSignBit | kExponentBits | kSignificandBits) == Bits(~0),
155 "all bits accounted for");
156 };
157
158 /**
159 * Determines whether a float/double is negative or -0. It is an error
160 * to call this method on a float/double which is NaN.
161 */
162 template <typename T>
163 static MOZ_ALWAYS_INLINE bool IsNegative(T aValue) {
164 MOZ_ASSERT(!std::isnan(aValue), "NaN does not have a sign");
165 return std::signbit(aValue);
166 }
167
168 /** Determines whether a float/double represents -0. */
169 template <typename T>
170 static MOZ_ALWAYS_INLINE bool IsNegativeZero(T aValue) {
171 /* Only the sign bit is set if the value is -0. */
172 typedef FloatingPoint<T> Traits;
173 typedef typename Traits::Bits Bits;
174 Bits bits = BitwiseCast<Bits>(aValue);
175 return bits == Traits::kSignBit;
176 }
177
178 /** Determines wether a float/double represents +0. */
179 template <typename T>
180 static MOZ_ALWAYS_INLINE bool IsPositiveZero(T aValue) {
181 /* All bits are zero if the value is +0. */
182 typedef FloatingPoint<T> Traits;
183 typedef typename Traits::Bits Bits;
184 Bits bits = BitwiseCast<Bits>(aValue);
185 return bits == 0;
186 }
187
188 /**
189 * Returns 0 if a float/double is NaN or infinite;
190 * otherwise, the float/double is returned.
191 */
192 template <typename T>
193 static MOZ_ALWAYS_INLINE T ToZeroIfNonfinite(T aValue) {
194 return std::isfinite(aValue) ? aValue : 0;
195 }
196
197 /**
198 * Returns the exponent portion of the float/double.
199 *
200 * Zero is not special-cased, so ExponentComponent(0.0) is
201 * -int_fast16_t(Traits::kExponentBias).
202 */
203 template <typename T>
204 static MOZ_ALWAYS_INLINE int_fast16_t ExponentComponent(T aValue) {
205 /*
206 * The exponent component of a float/double is an unsigned number, biased
207 * from its actual value. Subtract the bias to retrieve the actual exponent.
208 */
209 typedef FloatingPoint<T> Traits;
210 typedef typename Traits::Bits Bits;
211 Bits bits = BitwiseCast<Bits>(aValue);
212 return int_fast16_t((bits & Traits::kExponentBits) >>
213 Traits::kExponentShift) -
214 int_fast16_t(Traits::kExponentBias);
215 }
216
217 /** Returns +Infinity. */
218 template <typename T>
219 static constexpr MOZ_ALWAYS_INLINE T PositiveInfinity() {
220 return std::numeric_limits<T>::infinity();
221 }
222
223 /** Returns -Infinity. */
224 template <typename T>
225 static constexpr MOZ_ALWAYS_INLINE T NegativeInfinity() {
226 return -std::numeric_limits<T>::infinity();
227 }
228
229 /**
230 * Computes the bit pattern for an infinity with the specified sign bit.
231 */
232 template <typename T, int SignBit>
233 struct InfinityBits {
234 using Traits = FloatingPoint<T>;
235
236 static_assert(SignBit == 0 || SignBit == 1, "bad sign bit");
237 static constexpr typename Traits::Bits value =
238 (SignBit * Traits::kSignBit) | Traits::kExponentBits;
239 };
240
241 /**
242 * Computes the bit pattern for a NaN with the specified sign bit and
243 * significand bits.
244 */
245 template <typename T, int SignBit, typename FloatingPoint<T>::Bits Significand>
246 struct SpecificNaNBits {
247 using Traits = FloatingPoint<T>;
248
249 static_assert(SignBit == 0 || SignBit == 1, "bad sign bit");
250 static_assert((Significand & ~Traits::kSignificandBits) == 0,
251 "significand must only have significand bits set");
252 static_assert(Significand & Traits::kSignificandBits,
253 "significand must be nonzero");
254
255 static constexpr typename Traits::Bits value =
256 (SignBit * Traits::kSignBit) | Traits::kExponentBits | Significand;
257 };
258
259 /**
260 * Constructs a NaN value with the specified sign bit and significand bits.
261 *
262 * There is also a variant that returns the value directly. In most cases, the
263 * two variants should be identical. However, in the specific case of x86
264 * chips, the behavior differs: returning floating-point values directly is done
265 * through the x87 stack, and x87 loads and stores turn signaling NaNs into
266 * quiet NaNs... silently. Returning floating-point values via outparam,
267 * however, is done entirely within the SSE registers when SSE2 floating-point
268 * is enabled in the compiler, which has semantics-preserving behavior you would
269 * expect.
270 *
271 * If preserving the distinction between signaling NaNs and quiet NaNs is
272 * important to you, you should use the outparam version. In all other cases,
273 * you should use the direct return version.
274 */
275 template <typename T>
276 static MOZ_ALWAYS_INLINE void SpecificNaN(
277 int signbit, typename FloatingPoint<T>::Bits significand, T* result) {
278 typedef FloatingPoint<T> Traits;
279 MOZ_ASSERT(signbit == 0 || signbit == 1);
280 MOZ_ASSERT((significand & ~Traits::kSignificandBits) == 0);
281 MOZ_ASSERT(significand & Traits::kSignificandBits);
282
283 BitwiseCast<T>(
284 (signbit ? Traits::kSignBit : 0) | Traits::kExponentBits | significand,
285 result);
286 MOZ_ASSERT(std::isnan(*result));
287 }
288
289 template <typename T>
290 static MOZ_ALWAYS_INLINE T
291 SpecificNaN(int signbit, typename FloatingPoint<T>::Bits significand) {
292 T t;
293 SpecificNaN(signbit, significand, &t);
294 return t;
295 }
296
297 /** Computes the smallest non-zero positive float/double value. */
298 template <typename T>
299 static constexpr MOZ_ALWAYS_INLINE T MinNumberValue() {
300 return std::numeric_limits<T>::denorm_min();
301 }
302
303 /** Computes the largest positive float/double value. */
304 template <typename T>
305 static constexpr MOZ_ALWAYS_INLINE T MaxNumberValue() {
306 return std::numeric_limits<T>::max();
307 }
308
309 namespace detail {
310
311 template <typename Float, typename SignedInteger>
312 inline bool NumberEqualsSignedInteger(Float aValue, SignedInteger* aInteger) {
313 static_assert(std::is_same_v<Float, float> || std::is_same_v<Float, double>,
314 "Float must be an IEEE-754 floating point type");
315 static_assert(std::is_signed_v<SignedInteger>,
316 "this algorithm only works for signed types: a different one "
317 "will be required for unsigned types");
318 static_assert(sizeof(SignedInteger) >= sizeof(int),
319 "this function *might* require some finessing for signed types "
320 "subject to integral promotion before it can be used on them");
321
322 MOZ_MAKE_MEM_UNDEFINED(aInteger, sizeof(*aInteger));
323
324 // NaNs and infinities are not integers.
325 if (!std::isfinite(aValue)) {
326 return false;
327 }
328
329 // Otherwise do direct comparisons against the minimum/maximum |SignedInteger|
330 // values that can be encoded in |Float|.
331
332 constexpr SignedInteger MaxIntValue =
333 std::numeric_limits<SignedInteger>::max(); // e.g. INT32_MAX
334 constexpr SignedInteger MinValue =
335 std::numeric_limits<SignedInteger>::min(); // e.g. INT32_MIN
336
337 static_assert(IsPowerOfTwo(Abs(MinValue)),
338 "MinValue should be is a small power of two, thus exactly "
339 "representable in float/double both");
340
341 constexpr unsigned SignedIntegerWidth = CHAR_BIT * sizeof(SignedInteger);
342 constexpr unsigned ExponentShift = FloatingPoint<Float>::kExponentShift;
343
344 // Careful! |MaxIntValue| may not be the maximum |SignedInteger| value that
345 // can be encoded in |Float|. Its |SignedIntegerWidth - 1| bits of precision
346 // may exceed |Float|'s |ExponentShift + 1| bits of precision. If necessary,
347 // compute the maximum |SignedInteger| that fits in |Float| from IEEE-754
348 // first principles. (|MinValue| doesn't have this problem because as a
349 // [relatively] small power of two it's always representable in |Float|.)
350
351 // Per C++11 [expr.const]p2, unevaluated subexpressions of logical AND/OR and
352 // conditional expressions *may* contain non-constant expressions, without
353 // making the enclosing expression not constexpr. MSVC implements this -- but
354 // it sometimes warns about undefined behavior in unevaluated subexpressions.
355 // This bites us if we initialize |MaxValue| the obvious way including an
356 // |uint64_t(1) << (SignedIntegerWidth - 2 - ExponentShift)| subexpression.
357 // Pull that shift-amount out and give it a not-too-huge value when it's in an
358 // unevaluated subexpression. 🙄
359 constexpr unsigned PrecisionExceededShiftAmount =
360 ExponentShift > SignedIntegerWidth - 1
361 ? 0
362 : SignedIntegerWidth - 2 - ExponentShift;
363
364 constexpr SignedInteger MaxValue =
365 ExponentShift > SignedIntegerWidth - 1
366 ? MaxIntValue
367 : SignedInteger((uint64_t(1) << (SignedIntegerWidth - 1)) -
368 (uint64_t(1) << PrecisionExceededShiftAmount));
369
370 if (static_cast<Float>(MinValue) <= aValue &&
371 aValue <= static_cast<Float>(MaxValue)) {
372 auto possible = static_cast<SignedInteger>(aValue);
373 if (static_cast<Float>(possible) == aValue) {
374 *aInteger = possible;
375 return true;
376 }
377 }
378
379 return false;
380 }
381
382 template <typename Float, typename SignedInteger>
383 inline bool NumberIsSignedInteger(Float aValue, SignedInteger* aInteger) {
384 static_assert(std::is_same_v<Float, float> || std::is_same_v<Float, double>,
385 "Float must be an IEEE-754 floating point type");
386 static_assert(std::is_signed_v<SignedInteger>,
387 "this algorithm only works for signed types: a different one "
388 "will be required for unsigned types");
389 static_assert(sizeof(SignedInteger) >= sizeof(int),
390 "this function *might* require some finessing for signed types "
391 "subject to integral promotion before it can be used on them");
392
393 MOZ_MAKE_MEM_UNDEFINED(aInteger, sizeof(*aInteger));
394
395 if (IsNegativeZero(aValue)) {
396 return false;
397 }
398
399 return NumberEqualsSignedInteger(aValue, aInteger);
400 }
401
402 } // namespace detail
403
404 /**
405 * If |aValue| is identical to some |int32_t| value, set |*aInt32| to that value
406 * and return true. Otherwise return false, leaving |*aInt32| in an
407 * indeterminate state.
408 *
409 * This method returns false for negative zero. If you want to consider -0 to
410 * be 0, use NumberEqualsInt32 below.
411 */
412 template <typename T>
413 static MOZ_ALWAYS_INLINE bool NumberIsInt32(T aValue, int32_t* aInt32) {
414 return detail::NumberIsSignedInteger(aValue, aInt32);
415 }
416
417 /**
418 * If |aValue| is identical to some |int64_t| value, set |*aInt64| to that value
419 * and return true. Otherwise return false, leaving |*aInt64| in an
420 * indeterminate state.
421 *
422 * This method returns false for negative zero. If you want to consider -0 to
423 * be 0, use NumberEqualsInt64 below.
424 */
425 template <typename T>
426 static MOZ_ALWAYS_INLINE bool NumberIsInt64(T aValue, int64_t* aInt64) {
427 return detail::NumberIsSignedInteger(aValue, aInt64);
428 }
429
430 /**
431 * If |aValue| is equal to some int32_t value (where -0 and +0 are considered
432 * equal), set |*aInt32| to that value and return true. Otherwise return false,
433 * leaving |*aInt32| in an indeterminate state.
434 *
435 * |NumberEqualsInt32(-0.0, ...)| will return true. To test whether a value can
436 * be losslessly converted to |int32_t| and back, use NumberIsInt32 above.
437 */
438 template <typename T>
439 static MOZ_ALWAYS_INLINE bool NumberEqualsInt32(T aValue, int32_t* aInt32) {
440 return detail::NumberEqualsSignedInteger(aValue, aInt32);
441 }
442
443 /**
444 * If |aValue| is equal to some int64_t value (where -0 and +0 are considered
445 * equal), set |*aInt64| to that value and return true. Otherwise return false,
446 * leaving |*aInt64| in an indeterminate state.
447 *
448 * |NumberEqualsInt64(-0.0, ...)| will return true. To test whether a value can
449 * be losslessly converted to |int64_t| and back, use NumberIsInt64 above.
450 */
451 template <typename T>
452 static MOZ_ALWAYS_INLINE bool NumberEqualsInt64(T aValue, int64_t* aInt64) {
453 return detail::NumberEqualsSignedInteger(aValue, aInt64);
454 }
455
456 /**
457 * Computes a NaN value. Do not use this method if you depend upon a particular
458 * NaN value being returned.
459 */
460 template <typename T>
461 static MOZ_ALWAYS_INLINE T UnspecifiedNaN() {
462 /*
463 * If we can use any quiet NaN, we might as well use the all-ones NaN,
464 * since it's cheap to materialize on common platforms (such as x64, where
465 * this value can be represented in a 32-bit signed immediate field, allowing
466 * it to be stored to memory in a single instruction).
467 */
468 typedef FloatingPoint<T> Traits;
469 return SpecificNaN<T>(1, Traits::kSignificandBits);
470 }
471
472 /**
473 * Compare two doubles for equality, *without* equating -0 to +0, and equating
474 * any NaN value to any other NaN value. (The normal equality operators equate
475 * -0 with +0, and they equate NaN to no other value.)
476 */
477 template <typename T>
478 static inline bool NumbersAreIdentical(T aValue1, T aValue2) {
479 using Bits = typename FloatingPoint<T>::Bits;
480 if (std::isnan(aValue1)) {
481 return std::isnan(aValue2);
482 }
483 return BitwiseCast<Bits>(aValue1) == BitwiseCast<Bits>(aValue2);
484 }
485
486 /**
487 * Compare two floating point values for bit-wise equality.
488 */
489 template <typename T>
490 static inline bool NumbersAreBitwiseIdentical(T aValue1, T aValue2) {
491 using Bits = typename FloatingPoint<T>::Bits;
492 return BitwiseCast<Bits>(aValue1) == BitwiseCast<Bits>(aValue2);
493 }
494
495 /**
496 * Return true iff |aValue| and |aValue2| are equal (ignoring sign if both are
497 * zero) or both NaN.
498 */
499 template <typename T>
500 static inline bool EqualOrBothNaN(T aValue1, T aValue2) {
501 if (std::isnan(aValue1)) {
502 return std::isnan(aValue2);
503 }
504 return aValue1 == aValue2;
505 }
506
507 /**
508 * Return NaN if either |aValue1| or |aValue2| is NaN, or the minimum of
509 * |aValue1| and |aValue2| otherwise.
510 */
511 template <typename T>
512 static inline T NaNSafeMin(T aValue1, T aValue2) {
513 if (std::isnan(aValue1) || std::isnan(aValue2)) {
514 return UnspecifiedNaN<T>();
515 }
516 return std::min(aValue1, aValue2);
517 }
518
519 /**
520 * Return NaN if either |aValue1| or |aValue2| is NaN, or the maximum of
521 * |aValue1| and |aValue2| otherwise.
522 */
523 template <typename T>
524 static inline T NaNSafeMax(T aValue1, T aValue2) {
525 if (std::isnan(aValue1) || std::isnan(aValue2)) {
526 return UnspecifiedNaN<T>();
527 }
528 return std::max(aValue1, aValue2);
529 }
530
531 namespace detail {
532
533 template <typename T>
534 struct FuzzyEqualsEpsilon;
535
536 template <>
537 struct FuzzyEqualsEpsilon<float> {
538 // A number near 1e-5 that is exactly representable in a float.
539 static float value() { return 1.0f / (1 << 17); }
540 };
541
542 template <>
543 struct FuzzyEqualsEpsilon<double> {
544 // A number near 1e-12 that is exactly representable in a double.
545 static double value() { return 1.0 / (1LL << 40); }
546 };
547
548 } // namespace detail
549
550 /**
551 * Compare two floating point values for equality, modulo rounding error. That
552 * is, the two values are considered equal if they are both not NaN and if they
553 * are less than or equal to aEpsilon apart. The default value of aEpsilon is
554 * near 1e-5.
555 *
556 * For most scenarios you will want to use FuzzyEqualsMultiplicative instead,
557 * as it is more reasonable over the entire range of floating point numbers.
558 * This additive version should only be used if you know the range of the
559 * numbers you are dealing with is bounded and stays around the same order of
560 * magnitude.
561 */
562 template <typename T>
563 static MOZ_ALWAYS_INLINE bool FuzzyEqualsAdditive(
564 T aValue1, T aValue2, T aEpsilon = detail::FuzzyEqualsEpsilon<T>::value()) {
565 static_assert(std::is_floating_point_v<T>, "floating point type required");
566 return Abs(aValue1 - aValue2) <= aEpsilon;
567 }
568
569 /**
570 * Compare two floating point values for equality, allowing for rounding error
571 * relative to the magnitude of the values. That is, the two values are
572 * considered equal if they are both not NaN and they are less than or equal to
573 * some aEpsilon apart, where the aEpsilon is scaled by the smaller of the two
574 * argument values.
575 *
576 * In most cases you will want to use this rather than FuzzyEqualsAdditive, as
577 * this function effectively masks out differences in the bottom few bits of
578 * the floating point numbers being compared, regardless of what order of
579 * magnitude those numbers are at.
580 */
581 template <typename T>
582 static MOZ_ALWAYS_INLINE bool FuzzyEqualsMultiplicative(
583 T aValue1, T aValue2, T aEpsilon = detail::FuzzyEqualsEpsilon<T>::value()) {
584 static_assert(std::is_floating_point_v<T>, "floating point type required");
585 // can't use std::min because of bug 965340
586 T smaller = Abs(aValue1) < Abs(aValue2) ? Abs(aValue1) : Abs(aValue2);
587 return Abs(aValue1 - aValue2) <= aEpsilon * smaller;
588 }
589
590 /**
591 * Returns true if |aValue| can be losslessly represented as an IEEE-754 single
592 * precision number, false otherwise. All NaN values are considered
593 * representable (even though the bit patterns of double precision NaNs can't
594 * all be exactly represented in single precision).
595 */
596 [[nodiscard]] extern MFBT_API bool IsFloat32Representable(double aValue);
597
598 } /* namespace mozilla */
599
600 #endif /* mozilla_FloatingPoint_h */