1 //===- llvm/ADT/APFloat.h - Arbitrary Precision Floating Point ---*- C++ -*-==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
12 /// This file declares a class to represent arbitrary precision floating point
13 /// values and provide a variety of arithmetic operations on them.
15 //===----------------------------------------------------------------------===//
17 #ifndef LLVM_ADT_APFLOAT_H
18 #define LLVM_ADT_APFLOAT_H
20 #include "llvm/ADT/APInt.h"
28 /// Enum that represents what fraction of the LSB truncated bits of an fp number
31 /// This essentially combines the roles of guard and sticky bits.
32 enum lostFraction { // Example of truncated bits:
33 lfExactlyZero, // 000000
34 lfLessThanHalf, // 0xxxxx x's not all zero
35 lfExactlyHalf, // 100000
36 lfMoreThanHalf // 1xxxxx x's not all zero
39 /// \brief A self-contained host- and target-independent arbitrary-precision
40 /// floating-point software implementation.
42 /// APFloat uses bignum integer arithmetic as provided by static functions in
43 /// the APInt class. The library will work with bignum integers whose parts are
44 /// any unsigned type at least 16 bits wide, but 64 bits is recommended.
46 /// Written for clarity rather than speed, in particular with a view to use in
47 /// the front-end of a cross compiler so that target arithmetic can be correctly
48 /// performed on the host. Performance should nonetheless be reasonable,
49 /// particularly for its intended use. It may be useful as a base
50 /// implementation for a run-time library during development of a faster
51 /// target-specific one.
53 /// All 5 rounding modes in the IEEE-754R draft are handled correctly for all
54 /// implemented operations. Currently implemented operations are add, subtract,
55 /// multiply, divide, fused-multiply-add, conversion-to-float,
56 /// conversion-to-integer and conversion-from-integer. New rounding modes
57 /// (e.g. away from zero) can be added with three or four lines of code.
59 /// Four formats are built-in: IEEE single precision, double precision,
60 /// quadruple precision, and x87 80-bit extended double (when operating with
61 /// full extended precision). Adding a new format that obeys IEEE semantics
62 /// only requires adding two lines of code: a declaration and definition of the
65 /// All operations return the status of that operation as an exception bit-mask,
66 /// so multiple operations can be done consecutively with their results or-ed
67 /// together. The returned status can be useful for compiler diagnostics; e.g.,
68 /// inexact, underflow and overflow can be easily diagnosed on constant folding,
69 /// and compiler optimizers can determine what exceptions would be raised by
70 /// folding operations and optimize, or perhaps not optimize, accordingly.
72 /// At present, underflow tininess is detected after rounding; it should be
73 /// straight forward to add support for the before-rounding case too.
75 /// The library reads hexadecimal floating point numbers as per C99, and
76 /// correctly rounds if necessary according to the specified rounding mode.
77 /// Syntax is required to have been validated by the caller. It also converts
78 /// floating point numbers to hexadecimal text as per the C99 %a and %A
79 /// conversions. The output precision (or alternatively the natural minimal
80 /// precision) can be specified; if the requested precision is less than the
81 /// natural precision the output is correctly rounded for the specified rounding
84 /// It also reads decimal floating point numbers and correctly rounds according
85 /// to the specified rounding mode.
87 /// Conversion to decimal text is not currently implemented.
89 /// Non-zero finite numbers are represented internally as a sign bit, a 16-bit
90 /// signed exponent, and the significand as an array of integer parts. After
91 /// normalization of a number of precision P the exponent is within the range of
92 /// the format, and if the number is not denormal the P-th bit of the
93 /// significand is set as an explicit integer bit. For denormals the most
94 /// significant bit is shifted right so that the exponent is maintained at the
95 /// format's minimum, so that the smallest denormal has just the least
96 /// significant bit of the significand set. The sign of zeroes and infinities
97 /// is significant; the exponent and significand of such numbers is not stored,
98 /// but has a known implicit (deterministic) value: 0 for the significands, 0
99 /// for zero exponent, all 1 bits for infinity exponent. For NaNs the sign and
100 /// significand are deterministic, although not really meaningful, and preserved
101 /// in non-conversion operations. The exponent is implicitly all 1 bits.
103 /// APFloat does not provide any exception handling beyond default exception
104 /// handling. We represent Signaling NaNs via IEEE-754R 2008 6.2.1 should clause
105 /// by encoding Signaling NaNs with the first bit of its trailing significand as
111 /// Some features that may or may not be worth adding:
113 /// Binary to decimal conversion (hard).
115 /// Optional ability to detect underflow tininess before rounding.
117 /// New formats: x87 in single and double precision mode (IEEE apart from
118 /// extended exponent range) (hard).
120 /// New operations: sqrt, IEEE remainder, C90 fmod, nexttoward.
125 /// A signed type to represent a floating point numbers unbiased exponent.
126 typedef signed short ExponentType;
128 /// \name Floating Point Semantics.
131 static const fltSemantics IEEEhalf;
132 static const fltSemantics IEEEsingle;
133 static const fltSemantics IEEEdouble;
134 static const fltSemantics IEEEquad;
135 static const fltSemantics PPCDoubleDouble;
136 static const fltSemantics x87DoubleExtended;
138 /// A Pseudo fltsemantic used to construct APFloats that cannot conflict with
140 static const fltSemantics Bogus;
144 static unsigned int semanticsPrecision(const fltSemantics &);
146 /// IEEE-754R 5.11: Floating Point Comparison Relations.
154 /// IEEE-754R 4.3: Rounding-direction attributes.
163 /// IEEE-754R 7: Default exception handling.
165 /// opUnderflow or opOverflow are always returned or-ed with opInexact.
175 /// Category of internally-represented number.
183 /// Convenience enum used to construct an uninitialized APFloat.
184 enum uninitializedTag {
188 /// \name Constructors
191 APFloat(const fltSemantics &); // Default construct to 0.0
192 APFloat(const fltSemantics &, StringRef);
193 APFloat(const fltSemantics &, integerPart);
194 APFloat(const fltSemantics &, uninitializedTag);
195 APFloat(const fltSemantics &, const APInt &);
196 explicit APFloat(double d);
197 explicit APFloat(float f);
198 APFloat(const APFloat &);
204 /// \brief Returns whether this instance allocated memory.
205 bool needsCleanup() const { return partCount() > 1; }
207 /// \name Convenience "constructors"
210 /// Factory for Positive and Negative Zero.
212 /// \param Negative True iff the number should be negative.
213 static APFloat getZero(const fltSemantics &Sem, bool Negative = false) {
214 APFloat Val(Sem, uninitialized);
215 Val.makeZero(Negative);
219 /// Factory for Positive and Negative Infinity.
221 /// \param Negative True iff the number should be negative.
222 static APFloat getInf(const fltSemantics &Sem, bool Negative = false) {
223 APFloat Val(Sem, uninitialized);
224 Val.makeInf(Negative);
228 /// Factory for QNaN values.
230 /// \param Negative - True iff the NaN generated should be negative.
231 /// \param type - The unspecified fill bits for creating the NaN, 0 by
232 /// default. The value is truncated as necessary.
233 static APFloat getNaN(const fltSemantics &Sem, bool Negative = false,
236 APInt fill(64, type);
237 return getQNaN(Sem, Negative, &fill);
239 return getQNaN(Sem, Negative, nullptr);
243 /// Factory for QNaN values.
244 static APFloat getQNaN(const fltSemantics &Sem, bool Negative = false,
245 const APInt *payload = nullptr) {
246 return makeNaN(Sem, false, Negative, payload);
249 /// Factory for SNaN values.
250 static APFloat getSNaN(const fltSemantics &Sem, bool Negative = false,
251 const APInt *payload = nullptr) {
252 return makeNaN(Sem, true, Negative, payload);
255 /// Returns the largest finite number in the given semantics.
257 /// \param Negative - True iff the number should be negative
258 static APFloat getLargest(const fltSemantics &Sem, bool Negative = false);
260 /// Returns the smallest (by magnitude) finite number in the given semantics.
261 /// Might be denormalized, which implies a relative loss of precision.
263 /// \param Negative - True iff the number should be negative
264 static APFloat getSmallest(const fltSemantics &Sem, bool Negative = false);
266 /// Returns the smallest (by magnitude) normalized finite number in the given
269 /// \param Negative - True iff the number should be negative
270 static APFloat getSmallestNormalized(const fltSemantics &Sem,
271 bool Negative = false);
273 /// Returns a float which is bitcasted from an all one value int.
275 /// \param BitWidth - Select float type
276 /// \param isIEEE - If 128 bit number, select between PPC and IEEE
277 static APFloat getAllOnesValue(unsigned BitWidth, bool isIEEE = false);
281 /// Used to insert APFloat objects, or objects that contain APFloat objects,
282 /// into FoldingSets.
283 void Profile(FoldingSetNodeID &NID) const;
288 opStatus add(const APFloat &, roundingMode);
289 opStatus subtract(const APFloat &, roundingMode);
290 opStatus multiply(const APFloat &, roundingMode);
291 opStatus divide(const APFloat &, roundingMode);
293 opStatus remainder(const APFloat &);
294 /// C fmod, or llvm frem.
295 opStatus mod(const APFloat &, roundingMode);
296 opStatus fusedMultiplyAdd(const APFloat &, const APFloat &, roundingMode);
297 opStatus roundToIntegral(roundingMode);
298 /// IEEE-754R 5.3.1: nextUp/nextDown.
299 opStatus next(bool nextDown);
301 /// \brief Operator+ overload which provides the default
302 /// \c nmNearestTiesToEven rounding mode and *no* error checking.
303 APFloat operator+(const APFloat &RHS) const {
304 APFloat Result = *this;
305 Result.add(RHS, rmNearestTiesToEven);
309 /// \brief Operator- overload which provides the default
310 /// \c nmNearestTiesToEven rounding mode and *no* error checking.
311 APFloat operator-(const APFloat &RHS) const {
312 APFloat Result = *this;
313 Result.subtract(RHS, rmNearestTiesToEven);
317 /// \brief Operator* overload which provides the default
318 /// \c nmNearestTiesToEven rounding mode and *no* error checking.
319 APFloat operator*(const APFloat &RHS) const {
320 APFloat Result = *this;
321 Result.multiply(RHS, rmNearestTiesToEven);
325 /// \brief Operator/ overload which provides the default
326 /// \c nmNearestTiesToEven rounding mode and *no* error checking.
327 APFloat operator/(const APFloat &RHS) const {
328 APFloat Result = *this;
329 Result.divide(RHS, rmNearestTiesToEven);
335 /// \name Sign operations.
340 void copySign(const APFloat &);
342 /// \brief A static helper to produce a copy of an APFloat value with its sign
343 /// copied from some other APFloat.
344 static APFloat copySign(APFloat Value, const APFloat &Sign) {
345 Value.copySign(Sign);
351 /// \name Conversions
354 opStatus convert(const fltSemantics &, roundingMode, bool *);
355 opStatus convertToInteger(integerPart *, unsigned int, bool, roundingMode,
357 opStatus convertToInteger(APSInt &, roundingMode, bool *) const;
358 opStatus convertFromAPInt(const APInt &, bool, roundingMode);
359 opStatus convertFromSignExtendedInteger(const integerPart *, unsigned int,
361 opStatus convertFromZeroExtendedInteger(const integerPart *, unsigned int,
363 opStatus convertFromString(StringRef, roundingMode);
364 APInt bitcastToAPInt() const;
365 double convertToDouble() const;
366 float convertToFloat() const;
370 /// The definition of equality is not straightforward for floating point, so
371 /// we won't use operator==. Use one of the following, or write whatever it
372 /// is you really mean.
373 bool operator==(const APFloat &) const = delete;
375 /// IEEE comparison with another floating point number (NaNs compare
376 /// unordered, 0==-0).
377 cmpResult compare(const APFloat &) const;
379 /// Bitwise comparison for equality (QNaNs compare equal, 0!=-0).
380 bool bitwiseIsEqual(const APFloat &) const;
382 /// Write out a hexadecimal representation of the floating point value to DST,
383 /// which must be of sufficient size, in the C99 form [-]0xh.hhhhp[+-]d.
384 /// Return the number of characters written, excluding the terminating NUL.
385 unsigned int convertToHexString(char *dst, unsigned int hexDigits,
386 bool upperCase, roundingMode) const;
388 /// \name IEEE-754R 5.7.2 General operations.
391 /// IEEE-754R isSignMinus: Returns true if and only if the current value is
394 /// This applies to zeros and NaNs as well.
395 bool isNegative() const { return sign; }
397 /// IEEE-754R isNormal: Returns true if and only if the current value is normal.
399 /// This implies that the current value of the float is not zero, subnormal,
400 /// infinite, or NaN following the definition of normality from IEEE-754R.
401 bool isNormal() const { return !isDenormal() && isFiniteNonZero(); }
403 /// Returns true if and only if the current value is zero, subnormal, or
406 /// This means that the value is not infinite or NaN.
407 bool isFinite() const { return !isNaN() && !isInfinity(); }
409 /// Returns true if and only if the float is plus or minus zero.
410 bool isZero() const { return category == fcZero; }
412 /// IEEE-754R isSubnormal(): Returns true if and only if the float is a
414 bool isDenormal() const;
416 /// IEEE-754R isInfinite(): Returns true if and only if the float is infinity.
417 bool isInfinity() const { return category == fcInfinity; }
419 /// Returns true if and only if the float is a quiet or signaling NaN.
420 bool isNaN() const { return category == fcNaN; }
422 /// Returns true if and only if the float is a signaling NaN.
423 bool isSignaling() const;
427 /// \name Simple Queries
430 fltCategory getCategory() const { return category; }
431 const fltSemantics &getSemantics() const { return *semantics; }
432 bool isNonZero() const { return category != fcZero; }
433 bool isFiniteNonZero() const { return isFinite() && !isZero(); }
434 bool isPosZero() const { return isZero() && !isNegative(); }
435 bool isNegZero() const { return isZero() && isNegative(); }
437 /// Returns true if and only if the number has the smallest possible non-zero
438 /// magnitude in the current semantics.
439 bool isSmallest() const;
441 /// Returns true if and only if the number has the largest possible finite
442 /// magnitude in the current semantics.
443 bool isLargest() const;
447 APFloat &operator=(const APFloat &);
448 APFloat &operator=(APFloat &&);
450 /// \brief Overload to compute a hash code for an APFloat value.
452 /// Note that the use of hash codes for floating point values is in general
453 /// frought with peril. Equality is hard to define for these values. For
454 /// example, should negative and positive zero hash to different codes? Are
455 /// they equal or not? This hash value implementation specifically
456 /// emphasizes producing different codes for different inputs in order to
457 /// be used in canonicalization and memoization. As such, equality is
458 /// bitwiseIsEqual, and 0 != -0.
459 friend hash_code hash_value(const APFloat &Arg);
461 /// Converts this value into a decimal string.
463 /// \param FormatPrecision The maximum number of digits of
464 /// precision to output. If there are fewer digits available,
465 /// zero padding will not be used unless the value is
466 /// integral and small enough to be expressed in
467 /// FormatPrecision digits. 0 means to use the natural
468 /// precision of the number.
469 /// \param FormatMaxPadding The maximum number of zeros to
470 /// consider inserting before falling back to scientific
471 /// notation. 0 means to always use scientific notation.
473 /// Number Precision MaxPadding Result
474 /// ------ --------- ---------- ------
475 /// 1.01E+4 5 2 10100
476 /// 1.01E+4 4 2 1.01E+4
477 /// 1.01E+4 5 1 1.01E+4
478 /// 1.01E-2 5 2 0.0101
479 /// 1.01E-2 4 2 0.0101
480 /// 1.01E-2 4 1 1.01E-2
481 void toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision = 0,
482 unsigned FormatMaxPadding = 3) const;
484 /// If this value has an exact multiplicative inverse, store it in inv and
486 bool getExactInverse(APFloat *inv) const;
488 /// \brief Enumeration of \c ilogb error results.
489 enum IlogbErrorKinds {
490 IEK_Zero = INT_MIN+1,
495 /// \brief Returns the exponent of the internal representation of the APFloat.
497 /// Because the radix of APFloat is 2, this is equivalent to floor(log2(x)).
498 /// For special APFloat values, this returns special error codes:
500 /// NaN -> \c IEK_NaN
502 /// Inf -> \c IEK_Inf
504 friend int ilogb(const APFloat &Arg) {
509 if (Arg.isInfinity())
515 /// \brief Returns: X * 2^Exp for integral exponents.
516 friend APFloat scalbn(APFloat X, int Exp);
520 /// \name Simple Queries
523 integerPart *significandParts();
524 const integerPart *significandParts() const;
525 unsigned int partCount() const;
529 /// \name Significand operations.
532 integerPart addSignificand(const APFloat &);
533 integerPart subtractSignificand(const APFloat &, integerPart);
534 lostFraction addOrSubtractSignificand(const APFloat &, bool subtract);
535 lostFraction multiplySignificand(const APFloat &, const APFloat *);
536 lostFraction divideSignificand(const APFloat &);
537 void incrementSignificand();
538 void initialize(const fltSemantics *);
539 void shiftSignificandLeft(unsigned int);
540 lostFraction shiftSignificandRight(unsigned int);
541 unsigned int significandLSB() const;
542 unsigned int significandMSB() const;
543 void zeroSignificand();
544 /// Return true if the significand excluding the integral bit is all ones.
545 bool isSignificandAllOnes() const;
546 /// Return true if the significand excluding the integral bit is all zeros.
547 bool isSignificandAllZeros() const;
551 /// \name Arithmetic on special values.
554 opStatus addOrSubtractSpecials(const APFloat &, bool subtract);
555 opStatus divideSpecials(const APFloat &);
556 opStatus multiplySpecials(const APFloat &);
557 opStatus modSpecials(const APFloat &);
561 /// \name Special value setters.
564 void makeLargest(bool Neg = false);
565 void makeSmallest(bool Neg = false);
566 void makeNaN(bool SNaN = false, bool Neg = false,
567 const APInt *fill = nullptr);
568 static APFloat makeNaN(const fltSemantics &Sem, bool SNaN, bool Negative,
570 void makeInf(bool Neg = false);
571 void makeZero(bool Neg = false);
578 bool convertFromStringSpecials(StringRef str);
579 opStatus normalize(roundingMode, lostFraction);
580 opStatus addOrSubtract(const APFloat &, roundingMode, bool subtract);
581 cmpResult compareAbsoluteValue(const APFloat &) const;
582 opStatus handleOverflow(roundingMode);
583 bool roundAwayFromZero(roundingMode, lostFraction, unsigned int) const;
584 opStatus convertToSignExtendedInteger(integerPart *, unsigned int, bool,
585 roundingMode, bool *) const;
586 opStatus convertFromUnsignedParts(const integerPart *, unsigned int,
588 opStatus convertFromHexadecimalString(StringRef, roundingMode);
589 opStatus convertFromDecimalString(StringRef, roundingMode);
590 char *convertNormalToHexString(char *, unsigned int, bool,
592 opStatus roundSignificandWithExponent(const integerPart *, unsigned int, int,
597 APInt convertHalfAPFloatToAPInt() const;
598 APInt convertFloatAPFloatToAPInt() const;
599 APInt convertDoubleAPFloatToAPInt() const;
600 APInt convertQuadrupleAPFloatToAPInt() const;
601 APInt convertF80LongDoubleAPFloatToAPInt() const;
602 APInt convertPPCDoubleDoubleAPFloatToAPInt() const;
603 void initFromAPInt(const fltSemantics *Sem, const APInt &api);
604 void initFromHalfAPInt(const APInt &api);
605 void initFromFloatAPInt(const APInt &api);
606 void initFromDoubleAPInt(const APInt &api);
607 void initFromQuadrupleAPInt(const APInt &api);
608 void initFromF80LongDoubleAPInt(const APInt &api);
609 void initFromPPCDoubleDoubleAPInt(const APInt &api);
611 void assign(const APFloat &);
612 void copySignificand(const APFloat &);
613 void freeSignificand();
615 /// The semantics that this value obeys.
616 const fltSemantics *semantics;
618 /// A binary fraction with an explicit integer bit.
620 /// The significand must be at least one bit wider than the target precision.
626 /// The signed unbiased exponent of the value.
627 ExponentType exponent;
629 /// What kind of floating point number this is.
631 /// Only 2 bits are required, but VisualStudio incorrectly sign extends it.
632 /// Using the extra bit keeps it from failing under VisualStudio.
633 fltCategory category : 3;
635 /// Sign bit of the number.
636 unsigned int sign : 1;
639 /// See friend declarations above.
641 /// These additional declarations are required in order to compile LLVM with IBM
643 hash_code hash_value(const APFloat &Arg);
644 APFloat scalbn(APFloat X, int Exp);
646 /// \brief Returns the absolute value of the argument.
647 inline APFloat abs(APFloat X) {
652 /// Implements IEEE minNum semantics. Returns the smaller of the 2 arguments if
653 /// both are not NaN. If either argument is a NaN, returns the other argument.
655 inline APFloat minnum(const APFloat &A, const APFloat &B) {
660 return (B.compare(A) == APFloat::cmpLessThan) ? B : A;
663 /// Implements IEEE maxNum semantics. Returns the larger of the 2 arguments if
664 /// both are not NaN. If either argument is a NaN, returns the other argument.
666 inline APFloat maxnum(const APFloat &A, const APFloat &B) {
671 return (A.compare(B) == APFloat::cmpLessThan) ? B : A;
676 #endif // LLVM_ADT_APFLOAT_H