1 //== llvm/Support/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"
24 /// A signed type to represent a floating point numbers unbiased exponent.
25 typedef signed short exponent_t;
31 /// Enum that represents what fraction of the LSB truncated bits of an fp number
34 /// This essentially combines the roles of guard and sticky bits.
35 enum lostFraction { // Example of truncated bits:
36 lfExactlyZero, // 000000
37 lfLessThanHalf, // 0xxxxx x's not all zero
38 lfExactlyHalf, // 100000
39 lfMoreThanHalf // 1xxxxx x's not all zero
42 /// \brief A self-contained host- and target-independent arbitrary-precision
43 /// floating-point software implementation.
45 /// APFloat uses bignum integer arithmetic as provided by static functions in
46 /// the APInt class. The library will work with bignum integers whose parts are
47 /// any unsigned type at least 16 bits wide, but 64 bits is recommended.
49 /// Written for clarity rather than speed, in particular with a view to use in
50 /// the front-end of a cross compiler so that target arithmetic can be correctly
51 /// performed on the host. Performance should nonetheless be reasonable,
52 /// particularly for its intended use. It may be useful as a base
53 /// implementation for a run-time library during development of a faster
54 /// target-specific one.
56 /// All 5 rounding modes in the IEEE-754R draft are handled correctly for all
57 /// implemented operations. Currently implemented operations are add, subtract,
58 /// multiply, divide, fused-multiply-add, conversion-to-float,
59 /// conversion-to-integer and conversion-from-integer. New rounding modes
60 /// (e.g. away from zero) can be added with three or four lines of code.
62 /// Four formats are built-in: IEEE single precision, double precision,
63 /// quadruple precision, and x87 80-bit extended double (when operating with
64 /// full extended precision). Adding a new format that obeys IEEE semantics
65 /// only requires adding two lines of code: a declaration and definition of the
68 /// All operations return the status of that operation as an exception bit-mask,
69 /// so multiple operations can be done consecutively with their results or-ed
70 /// together. The returned status can be useful for compiler diagnostics; e.g.,
71 /// inexact, underflow and overflow can be easily diagnosed on constant folding,
72 /// and compiler optimizers can determine what exceptions would be raised by
73 /// folding operations and optimize, or perhaps not optimize, accordingly.
75 /// At present, underflow tininess is detected after rounding; it should be
76 /// straight forward to add support for the before-rounding case too.
78 /// The library reads hexadecimal floating point numbers as per C99, and
79 /// correctly rounds if necessary according to the specified rounding mode.
80 /// Syntax is required to have been validated by the caller. It also converts
81 /// floating point numbers to hexadecimal text as per the C99 %a and %A
82 /// conversions. The output precision (or alternatively the natural minimal
83 /// precision) can be specified; if the requested precision is less than the
84 /// natural precision the output is correctly rounded for the specified rounding
87 /// It also reads decimal floating point numbers and correctly rounds according
88 /// to the specified rounding mode.
90 /// Conversion to decimal text is not currently implemented.
92 /// Non-zero finite numbers are represented internally as a sign bit, a 16-bit
93 /// signed exponent, and the significand as an array of integer parts. After
94 /// normalization of a number of precision P the exponent is within the range of
95 /// the format, and if the number is not denormal the P-th bit of the
96 /// significand is set as an explicit integer bit. For denormals the most
97 /// significant bit is shifted right so that the exponent is maintained at the
98 /// format's minimum, so that the smallest denormal has just the least
99 /// significant bit of the significand set. The sign of zeroes and infinities
100 /// is significant; the exponent and significand of such numbers is not stored,
101 /// but has a known implicit (deterministic) value: 0 for the significands, 0
102 /// for zero exponent, all 1 bits for infinity exponent. For NaNs the sign and
103 /// significand are deterministic, although not really meaningful, and preserved
104 /// in non-conversion operations. The exponent is implicitly all 1 bits.
106 /// APFloat does not provide any exception handling beyond default exception
107 /// handling. We represent Signaling NaNs via IEEE-754R 2008 6.2.1 should clause
108 /// by encoding Signaling NaNs with the first bit of its trailing significand as
114 /// Some features that may or may not be worth adding:
116 /// Binary to decimal conversion (hard).
118 /// Optional ability to detect underflow tininess before rounding.
120 /// New formats: x87 in single and double precision mode (IEEE apart from
121 /// extended exponent range) (hard).
123 /// New operations: sqrt, IEEE remainder, C90 fmod, nextafter, nexttoward.
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 &, fltCategory, bool negative);
195 APFloat(const fltSemantics &, uninitializedTag);
196 APFloat(const fltSemantics &, const APInt &);
197 explicit APFloat(double d);
198 explicit APFloat(float f);
199 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 return APFloat(Sem, fcZero, Negative);
217 /// Factory for Positive and Negative Infinity.
219 /// \param Negative True iff the number should be negative.
220 static APFloat getInf(const fltSemantics &Sem, bool Negative = false) {
221 return APFloat(Sem, fcInfinity, Negative);
224 /// Factory for QNaN values.
226 /// \param Negative - True iff the NaN generated should be negative.
227 /// \param type - The unspecified fill bits for creating the NaN, 0 by
228 /// default. The value is truncated as necessary.
229 static APFloat getNaN(const fltSemantics &Sem, bool Negative = false,
232 APInt fill(64, type);
233 return getQNaN(Sem, Negative, &fill);
235 return getQNaN(Sem, Negative, 0);
239 /// Factory for QNaN values.
240 static APFloat getQNaN(const fltSemantics &Sem, bool Negative = false,
241 const APInt *payload = 0) {
242 return makeNaN(Sem, false, Negative, payload);
245 /// Factory for SNaN values.
246 static APFloat getSNaN(const fltSemantics &Sem, bool Negative = false,
247 const APInt *payload = 0) {
248 return makeNaN(Sem, true, Negative, payload);
251 /// Returns the largest finite number in the given semantics.
253 /// \param Negative - True iff the number should be negative
254 static APFloat getLargest(const fltSemantics &Sem, bool Negative = false);
256 /// Returns the smallest (by magnitude) finite number in the given semantics.
257 /// Might be denormalized, which implies a relative loss of precision.
259 /// \param Negative - True iff the number should be negative
260 static APFloat getSmallest(const fltSemantics &Sem, bool Negative = false);
262 /// Returns the smallest (by magnitude) normalized finite number in the given
265 /// \param Negative - True iff the number should be negative
266 static APFloat getSmallestNormalized(const fltSemantics &Sem,
267 bool Negative = false);
269 /// Returns a float which is bitcasted from an all one value int.
271 /// \param BitWidth - Select float type
272 /// \param isIEEE - If 128 bit number, select between PPC and IEEE
273 static APFloat getAllOnesValue(unsigned BitWidth, bool isIEEE = false);
277 /// Used to insert APFloat objects, or objects that contain APFloat objects,
278 /// into FoldingSets.
279 void Profile(FoldingSetNodeID &NID) const;
281 /// \brief Used by the Bitcode serializer to emit APInts to Bitcode.
282 void Emit(Serializer &S) const;
284 /// \brief Used by the Bitcode deserializer to deserialize APInts.
285 static APFloat ReadVal(Deserializer &D);
290 opStatus add(const APFloat &, roundingMode);
291 opStatus subtract(const APFloat &, roundingMode);
292 opStatus multiply(const APFloat &, roundingMode);
293 opStatus divide(const APFloat &, roundingMode);
295 opStatus remainder(const APFloat &);
296 /// C fmod, or llvm frem.
297 opStatus mod(const APFloat &, roundingMode);
298 opStatus fusedMultiplyAdd(const APFloat &, const APFloat &, roundingMode);
299 opStatus roundToIntegral(roundingMode);
300 /// IEEE-754R 5.3.1: nextUp/nextDown.
301 opStatus next(bool nextDown);
303 /// \name Sign operations.
308 void copySign(const APFloat &);
312 /// \name Conversions
315 opStatus convert(const fltSemantics &, roundingMode, bool *);
316 opStatus convertToInteger(integerPart *, unsigned int, bool, roundingMode,
318 opStatus convertToInteger(APSInt &, roundingMode, bool *) const;
319 opStatus convertFromAPInt(const APInt &, bool, roundingMode);
320 opStatus convertFromSignExtendedInteger(const integerPart *, unsigned int,
322 opStatus convertFromZeroExtendedInteger(const integerPart *, unsigned int,
324 opStatus convertFromString(StringRef, roundingMode);
325 APInt bitcastToAPInt() const;
326 double convertToDouble() const;
327 float convertToFloat() const;
331 /// The definition of equality is not straightforward for floating point, so
332 /// we won't use operator==. Use one of the following, or write whatever it
333 /// is you really mean.
334 bool operator==(const APFloat &) const LLVM_DELETED_FUNCTION;
336 /// IEEE comparison with another floating point number (NaNs compare
337 /// unordered, 0==-0).
338 cmpResult compare(const APFloat &) const;
340 /// Bitwise comparison for equality (QNaNs compare equal, 0!=-0).
341 bool bitwiseIsEqual(const APFloat &) const;
343 /// Write out a hexadecimal representation of the floating point value to DST,
344 /// which must be of sufficient size, in the C99 form [-]0xh.hhhhp[+-]d.
345 /// Return the number of characters written, excluding the terminating NUL.
346 unsigned int convertToHexString(char *dst, unsigned int hexDigits,
347 bool upperCase, roundingMode) const;
349 /// \name Simple Queries
352 fltCategory getCategory() const { return category; }
353 const fltSemantics &getSemantics() const { return *semantics; }
354 bool isZero() const { return category == fcZero; }
355 bool isNonZero() const { return category != fcZero; }
356 bool isNormal() const { return category == fcNormal; }
357 bool isNaN() const { return category == fcNaN; }
358 bool isInfinity() const { return category == fcInfinity; }
359 bool isNegative() const { return sign; }
360 bool isPosZero() const { return isZero() && !isNegative(); }
361 bool isNegZero() const { return isZero() && isNegative(); }
362 bool isDenormal() const;
363 /// IEEE-754R 5.7.2: isSignaling. Returns true if this is a signaling NaN.
364 bool isSignaling() const;
368 APFloat &operator=(const APFloat &);
370 /// \brief Overload to compute a hash code for an APFloat value.
372 /// Note that the use of hash codes for floating point values is in general
373 /// frought with peril. Equality is hard to define for these values. For
374 /// example, should negative and positive zero hash to different codes? Are
375 /// they equal or not? This hash value implementation specifically
376 /// emphasizes producing different codes for different inputs in order to
377 /// be used in canonicalization and memoization. As such, equality is
378 /// bitwiseIsEqual, and 0 != -0.
379 friend hash_code hash_value(const APFloat &Arg);
381 /// Converts this value into a decimal string.
383 /// \param FormatPrecision The maximum number of digits of
384 /// precision to output. If there are fewer digits available,
385 /// zero padding will not be used unless the value is
386 /// integral and small enough to be expressed in
387 /// FormatPrecision digits. 0 means to use the natural
388 /// precision of the number.
389 /// \param FormatMaxPadding The maximum number of zeros to
390 /// consider inserting before falling back to scientific
391 /// notation. 0 means to always use scientific notation.
393 /// Number Precision MaxPadding Result
394 /// ------ --------- ---------- ------
395 /// 1.01E+4 5 2 10100
396 /// 1.01E+4 4 2 1.01E+4
397 /// 1.01E+4 5 1 1.01E+4
398 /// 1.01E-2 5 2 0.0101
399 /// 1.01E-2 4 2 0.0101
400 /// 1.01E-2 4 1 1.01E-2
401 void toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision = 0,
402 unsigned FormatMaxPadding = 3) const;
404 /// If this value has an exact multiplicative inverse, store it in inv and
406 bool getExactInverse(APFloat *inv) const;
410 /// \name Simple Queries
413 integerPart *significandParts();
414 const integerPart *significandParts() const;
415 unsigned int partCount() const;
419 /// \name Significand operations.
422 integerPart addSignificand(const APFloat &);
423 integerPart subtractSignificand(const APFloat &, integerPart);
424 lostFraction addOrSubtractSignificand(const APFloat &, bool subtract);
425 lostFraction multiplySignificand(const APFloat &, const APFloat *);
426 lostFraction divideSignificand(const APFloat &);
427 void incrementSignificand();
428 void initialize(const fltSemantics *);
429 void shiftSignificandLeft(unsigned int);
430 lostFraction shiftSignificandRight(unsigned int);
431 unsigned int significandLSB() const;
432 unsigned int significandMSB() const;
433 void zeroSignificand();
434 /// Return true if the significand excluding the integral bit is all ones.
435 bool isSignificandAllOnes() const;
436 /// Return true if the significand excluding the integral bit is all zeros.
437 bool isSignificandAllZeros() const;
441 /// \name Arithmetic on special values.
444 opStatus addOrSubtractSpecials(const APFloat &, bool subtract);
445 opStatus divideSpecials(const APFloat &);
446 opStatus multiplySpecials(const APFloat &);
447 opStatus modSpecials(const APFloat &);
451 /// \name Special value setters.
454 void makeLargest(bool Neg = false);
455 void makeSmallest(bool Neg = false);
456 void makeNaN(bool SNaN = false, bool Neg = false, const APInt *fill = 0);
457 static APFloat makeNaN(const fltSemantics &Sem, bool SNaN, bool Negative,
462 /// \name Special value queries only useful internally to APFloat
465 /// Returns true if and only if the number has the smallest possible non-zero
466 /// magnitude in the current semantics.
467 bool isSmallest() const;
468 /// Returns true if and only if the number has the largest possible finite
469 /// magnitude in the current semantics.
470 bool isLargest() const;
477 opStatus normalize(roundingMode, lostFraction);
478 opStatus addOrSubtract(const APFloat &, roundingMode, bool subtract);
479 cmpResult compareAbsoluteValue(const APFloat &) const;
480 opStatus handleOverflow(roundingMode);
481 bool roundAwayFromZero(roundingMode, lostFraction, unsigned int) const;
482 opStatus convertToSignExtendedInteger(integerPart *, unsigned int, bool,
483 roundingMode, bool *) const;
484 opStatus convertFromUnsignedParts(const integerPart *, unsigned int,
486 opStatus convertFromHexadecimalString(StringRef, roundingMode);
487 opStatus convertFromDecimalString(StringRef, roundingMode);
488 char *convertNormalToHexString(char *, unsigned int, bool,
490 opStatus roundSignificandWithExponent(const integerPart *, unsigned int, int,
495 APInt convertHalfAPFloatToAPInt() const;
496 APInt convertFloatAPFloatToAPInt() const;
497 APInt convertDoubleAPFloatToAPInt() const;
498 APInt convertQuadrupleAPFloatToAPInt() const;
499 APInt convertF80LongDoubleAPFloatToAPInt() const;
500 APInt convertPPCDoubleDoubleAPFloatToAPInt() const;
501 void initFromAPInt(const fltSemantics *Sem, const APInt &api);
502 void initFromHalfAPInt(const APInt &api);
503 void initFromFloatAPInt(const APInt &api);
504 void initFromDoubleAPInt(const APInt &api);
505 void initFromQuadrupleAPInt(const APInt &api);
506 void initFromF80LongDoubleAPInt(const APInt &api);
507 void initFromPPCDoubleDoubleAPInt(const APInt &api);
509 void assign(const APFloat &);
510 void copySignificand(const APFloat &);
511 void freeSignificand();
513 /// The semantics that this value obeys.
514 const fltSemantics *semantics;
516 /// A binary fraction with an explicit integer bit.
518 /// The significand must be at least one bit wider than the target precision.
524 /// The signed unbiased exponent of the value.
527 /// What kind of floating point number this is.
529 /// Only 2 bits are required, but VisualStudio incorrectly sign extends it.
530 /// Using the extra bit keeps it from failing under VisualStudio.
531 fltCategory category : 3;
533 /// Sign bit of the number.
534 unsigned int sign : 1;
537 /// See friend declaration above.
539 /// This additional declaration is required in order to compile LLVM with IBM
541 hash_code hash_value(const APFloat &Arg);
544 #endif // LLVM_ADT_APFLOAT_H