Home | History | Annotate | Download | only in ADT
      1 //== llvm/Support/APFloat.h - Arbitrary Precision Floating Point -*- C++ -*-==//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This file declares a class to represent arbitrary precision floating
     11 // point values and provide a variety of arithmetic operations on them.
     12 //
     13 //===----------------------------------------------------------------------===//
     14 
     15 /*  A self-contained host- and target-independent arbitrary-precision
     16     floating-point software implementation.  It uses bignum integer
     17     arithmetic as provided by static functions in the APInt class.
     18     The library will work with bignum integers whose parts are any
     19     unsigned type at least 16 bits wide, but 64 bits is recommended.
     20 
     21     Written for clarity rather than speed, in particular with a view
     22     to use in the front-end of a cross compiler so that target
     23     arithmetic can be correctly performed on the host.  Performance
     24     should nonetheless be reasonable, particularly for its intended
     25     use.  It may be useful as a base implementation for a run-time
     26     library during development of a faster target-specific one.
     27 
     28     All 5 rounding modes in the IEEE-754R draft are handled correctly
     29     for all implemented operations.  Currently implemented operations
     30     are add, subtract, multiply, divide, fused-multiply-add,
     31     conversion-to-float, conversion-to-integer and
     32     conversion-from-integer.  New rounding modes (e.g. away from zero)
     33     can be added with three or four lines of code.
     34 
     35     Four formats are built-in: IEEE single precision, double
     36     precision, quadruple precision, and x87 80-bit extended double
     37     (when operating with full extended precision).  Adding a new
     38     format that obeys IEEE semantics only requires adding two lines of
     39     code: a declaration and definition of the format.
     40 
     41     All operations return the status of that operation as an exception
     42     bit-mask, so multiple operations can be done consecutively with
     43     their results or-ed together.  The returned status can be useful
     44     for compiler diagnostics; e.g., inexact, underflow and overflow
     45     can be easily diagnosed on constant folding, and compiler
     46     optimizers can determine what exceptions would be raised by
     47     folding operations and optimize, or perhaps not optimize,
     48     accordingly.
     49 
     50     At present, underflow tininess is detected after rounding; it
     51     should be straight forward to add support for the before-rounding
     52     case too.
     53 
     54     The library reads hexadecimal floating point numbers as per C99,
     55     and correctly rounds if necessary according to the specified
     56     rounding mode.  Syntax is required to have been validated by the
     57     caller.  It also converts floating point numbers to hexadecimal
     58     text as per the C99 %a and %A conversions.  The output precision
     59     (or alternatively the natural minimal precision) can be specified;
     60     if the requested precision is less than the natural precision the
     61     output is correctly rounded for the specified rounding mode.
     62 
     63     It also reads decimal floating point numbers and correctly rounds
     64     according to the specified rounding mode.
     65 
     66     Conversion to decimal text is not currently implemented.
     67 
     68     Non-zero finite numbers are represented internally as a sign bit,
     69     a 16-bit signed exponent, and the significand as an array of
     70     integer parts.  After normalization of a number of precision P the
     71     exponent is within the range of the format, and if the number is
     72     not denormal the P-th bit of the significand is set as an explicit
     73     integer bit.  For denormals the most significant bit is shifted
     74     right so that the exponent is maintained at the format's minimum,
     75     so that the smallest denormal has just the least significant bit
     76     of the significand set.  The sign of zeroes and infinities is
     77     significant; the exponent and significand of such numbers is not
     78     stored, but has a known implicit (deterministic) value: 0 for the
     79     significands, 0 for zero exponent, all 1 bits for infinity
     80     exponent.  For NaNs the sign and significand are deterministic,
     81     although not really meaningful, and preserved in non-conversion
     82     operations.  The exponent is implicitly all 1 bits.
     83 
     84     TODO
     85     ====
     86 
     87     Some features that may or may not be worth adding:
     88 
     89     Binary to decimal conversion (hard).
     90 
     91     Optional ability to detect underflow tininess before rounding.
     92 
     93     New formats: x87 in single and double precision mode (IEEE apart
     94     from extended exponent range) (hard).
     95 
     96     New operations: sqrt, IEEE remainder, C90 fmod, nextafter,
     97     nexttoward.
     98 */
     99 
    100 #ifndef LLVM_ADT_APFLOAT_H
    101 #define LLVM_ADT_APFLOAT_H
    102 
    103 // APInt contains static functions implementing bignum arithmetic.
    104 #include "llvm/ADT/APInt.h"
    105 
    106 namespace llvm {
    107 
    108   /* Exponents are stored as signed numbers.  */
    109   typedef signed short exponent_t;
    110 
    111   struct fltSemantics;
    112   class APSInt;
    113   class StringRef;
    114 
    115   /* When bits of a floating point number are truncated, this enum is
    116      used to indicate what fraction of the LSB those bits represented.
    117      It essentially combines the roles of guard and sticky bits.  */
    118   enum lostFraction {           // Example of truncated bits:
    119     lfExactlyZero,              // 000000
    120     lfLessThanHalf,             // 0xxxxx  x's not all zero
    121     lfExactlyHalf,              // 100000
    122     lfMoreThanHalf              // 1xxxxx  x's not all zero
    123   };
    124 
    125   class APFloat {
    126   public:
    127 
    128     /* We support the following floating point semantics.  */
    129     static const fltSemantics IEEEhalf;
    130     static const fltSemantics IEEEsingle;
    131     static const fltSemantics IEEEdouble;
    132     static const fltSemantics IEEEquad;
    133     static const fltSemantics PPCDoubleDouble;
    134     static const fltSemantics x87DoubleExtended;
    135     /* And this pseudo, used to construct APFloats that cannot
    136        conflict with anything real. */
    137     static const fltSemantics Bogus;
    138 
    139     static unsigned int semanticsPrecision(const fltSemantics &);
    140 
    141     /* Floating point numbers have a four-state comparison relation.  */
    142     enum cmpResult {
    143       cmpLessThan,
    144       cmpEqual,
    145       cmpGreaterThan,
    146       cmpUnordered
    147     };
    148 
    149     /* IEEE-754R gives five rounding modes.  */
    150     enum roundingMode {
    151       rmNearestTiesToEven,
    152       rmTowardPositive,
    153       rmTowardNegative,
    154       rmTowardZero,
    155       rmNearestTiesToAway
    156     };
    157 
    158     // Operation status.  opUnderflow or opOverflow are always returned
    159     // or-ed with opInexact.
    160     enum opStatus {
    161       opOK          = 0x00,
    162       opInvalidOp   = 0x01,
    163       opDivByZero   = 0x02,
    164       opOverflow    = 0x04,
    165       opUnderflow   = 0x08,
    166       opInexact     = 0x10
    167     };
    168 
    169     // Category of internally-represented number.
    170     enum fltCategory {
    171       fcInfinity,
    172       fcNaN,
    173       fcNormal,
    174       fcZero
    175     };
    176 
    177     enum uninitializedTag {
    178       uninitialized
    179     };
    180 
    181     // Constructors.
    182     APFloat(const fltSemantics &); // Default construct to 0.0
    183     APFloat(const fltSemantics &, StringRef);
    184     APFloat(const fltSemantics &, integerPart);
    185     APFloat(const fltSemantics &, fltCategory, bool negative);
    186     APFloat(const fltSemantics &, uninitializedTag);
    187     APFloat(const fltSemantics &, const APInt &);
    188     explicit APFloat(double d);
    189     explicit APFloat(float f);
    190     APFloat(const APFloat &);
    191     ~APFloat();
    192 
    193     // Convenience "constructors"
    194     static APFloat getZero(const fltSemantics &Sem, bool Negative = false) {
    195       return APFloat(Sem, fcZero, Negative);
    196     }
    197     static APFloat getInf(const fltSemantics &Sem, bool Negative = false) {
    198       return APFloat(Sem, fcInfinity, Negative);
    199     }
    200 
    201     /// getNaN - Factory for QNaN values.
    202     ///
    203     /// \param Negative - True iff the NaN generated should be negative.
    204     /// \param type - The unspecified fill bits for creating the NaN, 0 by
    205     /// default.  The value is truncated as necessary.
    206     static APFloat getNaN(const fltSemantics &Sem, bool Negative = false,
    207                           unsigned type = 0) {
    208       if (type) {
    209         APInt fill(64, type);
    210         return getQNaN(Sem, Negative, &fill);
    211       } else {
    212         return getQNaN(Sem, Negative, 0);
    213       }
    214     }
    215 
    216     /// getQNan - Factory for QNaN values.
    217     static APFloat getQNaN(const fltSemantics &Sem,
    218                            bool Negative = false,
    219                            const APInt *payload = 0) {
    220       return makeNaN(Sem, false, Negative, payload);
    221     }
    222 
    223     /// getSNan - Factory for SNaN values.
    224     static APFloat getSNaN(const fltSemantics &Sem,
    225                            bool Negative = false,
    226                            const APInt *payload = 0) {
    227       return makeNaN(Sem, true, Negative, payload);
    228     }
    229 
    230     /// getLargest - Returns the largest finite number in the given
    231     /// semantics.
    232     ///
    233     /// \param Negative - True iff the number should be negative
    234     static APFloat getLargest(const fltSemantics &Sem, bool Negative = false);
    235 
    236     /// getSmallest - Returns the smallest (by magnitude) finite number
    237     /// in the given semantics.  Might be denormalized, which implies a
    238     /// relative loss of precision.
    239     ///
    240     /// \param Negative - True iff the number should be negative
    241     static APFloat getSmallest(const fltSemantics &Sem, bool Negative = false);
    242 
    243     /// getSmallestNormalized - Returns the smallest (by magnitude)
    244     /// normalized finite number in the given semantics.
    245     ///
    246     /// \param Negative - True iff the number should be negative
    247     static APFloat getSmallestNormalized(const fltSemantics &Sem,
    248                                          bool Negative = false);
    249 
    250     /// getAllOnesValue - Returns a float which is bitcasted from
    251     /// an all one value int.
    252     ///
    253     /// \param BitWidth - Select float type
    254     /// \param isIEEE   - If 128 bit number, select between PPC and IEEE
    255     static APFloat getAllOnesValue(unsigned BitWidth, bool isIEEE = false);
    256 
    257     /// Profile - Used to insert APFloat objects, or objects that contain
    258     ///  APFloat objects, into FoldingSets.
    259     void Profile(FoldingSetNodeID& NID) const;
    260 
    261     /// @brief Used by the Bitcode serializer to emit APInts to Bitcode.
    262     void Emit(Serializer& S) const;
    263 
    264     /// @brief Used by the Bitcode deserializer to deserialize APInts.
    265     static APFloat ReadVal(Deserializer& D);
    266 
    267     /* Arithmetic.  */
    268     opStatus add(const APFloat &, roundingMode);
    269     opStatus subtract(const APFloat &, roundingMode);
    270     opStatus multiply(const APFloat &, roundingMode);
    271     opStatus divide(const APFloat &, roundingMode);
    272     /* IEEE remainder. */
    273     opStatus remainder(const APFloat &);
    274     /* C fmod, or llvm frem. */
    275     opStatus mod(const APFloat &, roundingMode);
    276     opStatus fusedMultiplyAdd(const APFloat &, const APFloat &, roundingMode);
    277     opStatus roundToIntegral(roundingMode);
    278 
    279     /* Sign operations.  */
    280     void changeSign();
    281     void clearSign();
    282     void copySign(const APFloat &);
    283 
    284     /* Conversions.  */
    285     opStatus convert(const fltSemantics &, roundingMode, bool *);
    286     opStatus convertToInteger(integerPart *, unsigned int, bool,
    287                               roundingMode, bool *) const;
    288     opStatus convertToInteger(APSInt&, roundingMode, bool *) const;
    289     opStatus convertFromAPInt(const APInt &,
    290                               bool, roundingMode);
    291     opStatus convertFromSignExtendedInteger(const integerPart *, unsigned int,
    292                                             bool, roundingMode);
    293     opStatus convertFromZeroExtendedInteger(const integerPart *, unsigned int,
    294                                             bool, roundingMode);
    295     opStatus convertFromString(StringRef, roundingMode);
    296     APInt bitcastToAPInt() const;
    297     double convertToDouble() const;
    298     float convertToFloat() const;
    299 
    300     /* The definition of equality is not straightforward for floating point,
    301        so we won't use operator==.  Use one of the following, or write
    302        whatever it is you really mean. */
    303     bool operator==(const APFloat &) const LLVM_DELETED_FUNCTION;
    304 
    305     /* IEEE comparison with another floating point number (NaNs
    306        compare unordered, 0==-0). */
    307     cmpResult compare(const APFloat &) const;
    308 
    309     /* Bitwise comparison for equality (QNaNs compare equal, 0!=-0). */
    310     bool bitwiseIsEqual(const APFloat &) const;
    311 
    312     /* Write out a hexadecimal representation of the floating point
    313        value to DST, which must be of sufficient size, in the C99 form
    314        [-]0xh.hhhhp[+-]d.  Return the number of characters written,
    315        excluding the terminating NUL.  */
    316     unsigned int convertToHexString(char *dst, unsigned int hexDigits,
    317                                     bool upperCase, roundingMode) const;
    318 
    319     /* Simple queries.  */
    320     fltCategory getCategory() const { return category; }
    321     const fltSemantics &getSemantics() const { return *semantics; }
    322     bool isZero() const { return category == fcZero; }
    323     bool isNonZero() const { return category != fcZero; }
    324     bool isNormal() const { return category == fcNormal; }
    325     bool isNaN() const { return category == fcNaN; }
    326     bool isInfinity() const { return category == fcInfinity; }
    327     bool isNegative() const { return sign; }
    328     bool isPosZero() const { return isZero() && !isNegative(); }
    329     bool isNegZero() const { return isZero() && isNegative(); }
    330     bool isDenormal() const;
    331 
    332     APFloat& operator=(const APFloat &);
    333 
    334     /// \brief Overload to compute a hash code for an APFloat value.
    335     ///
    336     /// Note that the use of hash codes for floating point values is in general
    337     /// frought with peril. Equality is hard to define for these values. For
    338     /// example, should negative and positive zero hash to different codes? Are
    339     /// they equal or not? This hash value implementation specifically
    340     /// emphasizes producing different codes for different inputs in order to
    341     /// be used in canonicalization and memoization. As such, equality is
    342     /// bitwiseIsEqual, and 0 != -0.
    343     friend hash_code hash_value(const APFloat &Arg);
    344 
    345     /// Converts this value into a decimal string.
    346     ///
    347     /// \param FormatPrecision The maximum number of digits of
    348     ///   precision to output.  If there are fewer digits available,
    349     ///   zero padding will not be used unless the value is
    350     ///   integral and small enough to be expressed in
    351     ///   FormatPrecision digits.  0 means to use the natural
    352     ///   precision of the number.
    353     /// \param FormatMaxPadding The maximum number of zeros to
    354     ///   consider inserting before falling back to scientific
    355     ///   notation.  0 means to always use scientific notation.
    356     ///
    357     /// Number       Precision    MaxPadding      Result
    358     /// ------       ---------    ----------      ------
    359     /// 1.01E+4              5             2       10100
    360     /// 1.01E+4              4             2       1.01E+4
    361     /// 1.01E+4              5             1       1.01E+4
    362     /// 1.01E-2              5             2       0.0101
    363     /// 1.01E-2              4             2       0.0101
    364     /// 1.01E-2              4             1       1.01E-2
    365     void toString(SmallVectorImpl<char> &Str,
    366                   unsigned FormatPrecision = 0,
    367                   unsigned FormatMaxPadding = 3) const;
    368 
    369     /// getExactInverse - If this value has an exact multiplicative inverse,
    370     /// store it in inv and return true.
    371     bool getExactInverse(APFloat *inv) const;
    372 
    373   private:
    374 
    375     /* Trivial queries.  */
    376     integerPart *significandParts();
    377     const integerPart *significandParts() const;
    378     unsigned int partCount() const;
    379 
    380     /* Significand operations.  */
    381     integerPart addSignificand(const APFloat &);
    382     integerPart subtractSignificand(const APFloat &, integerPart);
    383     lostFraction addOrSubtractSignificand(const APFloat &, bool subtract);
    384     lostFraction multiplySignificand(const APFloat &, const APFloat *);
    385     lostFraction divideSignificand(const APFloat &);
    386     void incrementSignificand();
    387     void initialize(const fltSemantics *);
    388     void shiftSignificandLeft(unsigned int);
    389     lostFraction shiftSignificandRight(unsigned int);
    390     unsigned int significandLSB() const;
    391     unsigned int significandMSB() const;
    392     void zeroSignificand();
    393 
    394     /* Arithmetic on special values.  */
    395     opStatus addOrSubtractSpecials(const APFloat &, bool subtract);
    396     opStatus divideSpecials(const APFloat &);
    397     opStatus multiplySpecials(const APFloat &);
    398     opStatus modSpecials(const APFloat &);
    399 
    400     /* Miscellany.  */
    401     static APFloat makeNaN(const fltSemantics &Sem, bool SNaN, bool Negative,
    402                            const APInt *fill);
    403     void makeNaN(bool SNaN = false, bool Neg = false, const APInt *fill = 0);
    404     opStatus normalize(roundingMode, lostFraction);
    405     opStatus addOrSubtract(const APFloat &, roundingMode, bool subtract);
    406     cmpResult compareAbsoluteValue(const APFloat &) const;
    407     opStatus handleOverflow(roundingMode);
    408     bool roundAwayFromZero(roundingMode, lostFraction, unsigned int) const;
    409     opStatus convertToSignExtendedInteger(integerPart *, unsigned int, bool,
    410                                           roundingMode, bool *) const;
    411     opStatus convertFromUnsignedParts(const integerPart *, unsigned int,
    412                                       roundingMode);
    413     opStatus convertFromHexadecimalString(StringRef, roundingMode);
    414     opStatus convertFromDecimalString(StringRef, roundingMode);
    415     char *convertNormalToHexString(char *, unsigned int, bool,
    416                                    roundingMode) const;
    417     opStatus roundSignificandWithExponent(const integerPart *, unsigned int,
    418                                           int, roundingMode);
    419 
    420     APInt convertHalfAPFloatToAPInt() const;
    421     APInt convertFloatAPFloatToAPInt() const;
    422     APInt convertDoubleAPFloatToAPInt() const;
    423     APInt convertQuadrupleAPFloatToAPInt() const;
    424     APInt convertF80LongDoubleAPFloatToAPInt() const;
    425     APInt convertPPCDoubleDoubleAPFloatToAPInt() const;
    426     void initFromAPInt(const fltSemantics *Sem, const APInt& api);
    427     void initFromHalfAPInt(const APInt& api);
    428     void initFromFloatAPInt(const APInt& api);
    429     void initFromDoubleAPInt(const APInt& api);
    430     void initFromQuadrupleAPInt(const APInt &api);
    431     void initFromF80LongDoubleAPInt(const APInt& api);
    432     void initFromPPCDoubleDoubleAPInt(const APInt& api);
    433 
    434     void assign(const APFloat &);
    435     void copySignificand(const APFloat &);
    436     void freeSignificand();
    437 
    438     /* What kind of semantics does this value obey?  */
    439     const fltSemantics *semantics;
    440 
    441     /* Significand - the fraction with an explicit integer bit.  Must be
    442        at least one bit wider than the target precision.  */
    443     union Significand
    444     {
    445       integerPart part;
    446       integerPart *parts;
    447     } significand;
    448 
    449     /* The exponent - a signed number.  */
    450     exponent_t exponent;
    451 
    452     /* What kind of floating point number this is.  */
    453     /* Only 2 bits are required, but VisualStudio incorrectly sign extends
    454        it.  Using the extra bit keeps it from failing under VisualStudio */
    455     fltCategory category: 3;
    456 
    457     /* The sign bit of this number.  */
    458     unsigned int sign: 1;
    459   };
    460 
    461   // See friend declaration above. This additional declaration is required in
    462   // order to compile LLVM with IBM xlC compiler.
    463   hash_code hash_value(const APFloat &Arg);
    464 } /* namespace llvm */
    465 
    466 #endif /* LLVM_ADT_APFLOAT_H */
    467