Implement support for converting to string at "natural precision", and fix some
[oota-llvm.git] / include / llvm / ADT / APFloat.h
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_FLOAT_H
101 #define LLVM_FLOAT_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 StringRef;
113
114   /* When bits of a floating point number are truncated, this enum is
115      used to indicate what fraction of the LSB those bits represented.
116      It essentially combines the roles of guard and sticky bits.  */
117   enum lostFraction {           // Example of truncated bits:
118     lfExactlyZero,              // 000000
119     lfLessThanHalf,             // 0xxxxx  x's not all zero
120     lfExactlyHalf,              // 100000
121     lfMoreThanHalf              // 1xxxxx  x's not all zero
122   };
123
124   class APFloat {
125   public:
126
127     /* We support the following floating point semantics.  */
128     static const fltSemantics IEEEhalf;
129     static const fltSemantics IEEEsingle;
130     static const fltSemantics IEEEdouble;
131     static const fltSemantics IEEEquad;
132     static const fltSemantics PPCDoubleDouble;
133     static const fltSemantics x87DoubleExtended;
134     /* And this pseudo, used to construct APFloats that cannot
135        conflict with anything real. */
136     static const fltSemantics Bogus;
137
138     static unsigned int semanticsPrecision(const fltSemantics &);
139
140     /* Floating point numbers have a four-state comparison relation.  */
141     enum cmpResult {
142       cmpLessThan,
143       cmpEqual,
144       cmpGreaterThan,
145       cmpUnordered
146     };
147
148     /* IEEE-754R gives five rounding modes.  */
149     enum roundingMode {
150       rmNearestTiesToEven,
151       rmTowardPositive,
152       rmTowardNegative,
153       rmTowardZero,
154       rmNearestTiesToAway
155     };
156
157     // Operation status.  opUnderflow or opOverflow are always returned
158     // or-ed with opInexact.
159     enum opStatus {
160       opOK          = 0x00,
161       opInvalidOp   = 0x01,
162       opDivByZero   = 0x02,
163       opOverflow    = 0x04,
164       opUnderflow   = 0x08,
165       opInexact     = 0x10
166     };
167
168     // Category of internally-represented number.
169     enum fltCategory {
170       fcInfinity,
171       fcNaN,
172       fcNormal,
173       fcZero
174     };
175
176     // Constructors.
177     APFloat(const fltSemantics &); // Default construct to 0.0
178     APFloat(const fltSemantics &, const StringRef &);
179     APFloat(const fltSemantics &, integerPart);
180     APFloat(const fltSemantics &, fltCategory, bool negative, unsigned type=0);
181     explicit APFloat(double d);
182     explicit APFloat(float f);
183     explicit APFloat(const APInt &, bool isIEEE = false);
184     APFloat(const APFloat &);
185     ~APFloat();
186
187     // Convenience "constructors"
188     static APFloat getZero(const fltSemantics &Sem, bool Negative = false) {
189       return APFloat(Sem, fcZero, Negative);
190     }
191     static APFloat getInf(const fltSemantics &Sem, bool Negative = false) {
192       return APFloat(Sem, fcInfinity, Negative);
193     }
194
195     /// getNaN - Factory for QNaN values.
196     ///
197     /// \param Negative - True iff the NaN generated should be negative.
198     /// \param type - The unspecified fill bits for creating the NaN, 0 by
199     /// default.  The value is truncated as necessary.
200     static APFloat getNaN(const fltSemantics &Sem, bool Negative = false,
201                           unsigned type = 0) {
202       return APFloat(Sem, fcNaN, Negative, type);
203     }
204
205     /// getLargest - Returns the largest finite number in the given
206     /// semantics.
207     ///
208     /// \param Negative - True iff the number should be negative
209     static APFloat getLargest(const fltSemantics &Sem, bool Negative = false);
210
211     /// getSmallest - Returns the smallest (by magnitude) finite number
212     /// in the given semantics.  Might be denormalized, which implies a
213     /// relative loss of precision.
214     ///
215     /// \param Negative - True iff the number should be negative
216     static APFloat getSmallest(const fltSemantics &Sem, bool Negative = false);
217
218     /// getSmallestNormalized - Returns the smallest (by magnitude)
219     /// normalized finite number in the given semantics.
220     ///
221     /// \param Negative - True iff the number should be negative
222     static APFloat getSmallestNormalized(const fltSemantics &Sem,
223                                          bool Negative = false);
224
225     /// Profile - Used to insert APFloat objects, or objects that contain
226     ///  APFloat objects, into FoldingSets.
227     void Profile(FoldingSetNodeID& NID) const;
228
229     /// @brief Used by the Bitcode serializer to emit APInts to Bitcode.
230     void Emit(Serializer& S) const;
231
232     /// @brief Used by the Bitcode deserializer to deserialize APInts.
233     static APFloat ReadVal(Deserializer& D);
234
235     /* Arithmetic.  */
236     opStatus add(const APFloat &, roundingMode);
237     opStatus subtract(const APFloat &, roundingMode);
238     opStatus multiply(const APFloat &, roundingMode);
239     opStatus divide(const APFloat &, roundingMode);
240     /* IEEE remainder. */
241     opStatus remainder(const APFloat &);
242     /* C fmod, or llvm frem. */
243     opStatus mod(const APFloat &, roundingMode);
244     opStatus fusedMultiplyAdd(const APFloat &, const APFloat &, roundingMode);
245
246     /* Sign operations.  */
247     void changeSign();
248     void clearSign();
249     void copySign(const APFloat &);
250
251     /* Conversions.  */
252     opStatus convert(const fltSemantics &, roundingMode, bool *);
253     opStatus convertToInteger(integerPart *, unsigned int, bool,
254                               roundingMode, bool *) const;
255     opStatus convertFromAPInt(const APInt &,
256                               bool, roundingMode);
257     opStatus convertFromSignExtendedInteger(const integerPart *, unsigned int,
258                                             bool, roundingMode);
259     opStatus convertFromZeroExtendedInteger(const integerPart *, unsigned int,
260                                             bool, roundingMode);
261     opStatus convertFromString(const StringRef&, roundingMode);
262     APInt bitcastToAPInt() const;
263     double convertToDouble() const;
264     float convertToFloat() const;
265
266     /* The definition of equality is not straightforward for floating point,
267        so we won't use operator==.  Use one of the following, or write
268        whatever it is you really mean. */
269     // bool operator==(const APFloat &) const;     // DO NOT IMPLEMENT
270
271     /* IEEE comparison with another floating point number (NaNs
272        compare unordered, 0==-0). */
273     cmpResult compare(const APFloat &) const;
274
275     /* Bitwise comparison for equality (QNaNs compare equal, 0!=-0). */
276     bool bitwiseIsEqual(const APFloat &) const;
277
278     /* Write out a hexadecimal representation of the floating point
279        value to DST, which must be of sufficient size, in the C99 form
280        [-]0xh.hhhhp[+-]d.  Return the number of characters written,
281        excluding the terminating NUL.  */
282     unsigned int convertToHexString(char *dst, unsigned int hexDigits,
283                                     bool upperCase, roundingMode) const;
284
285     /* Simple queries.  */
286     fltCategory getCategory() const { return category; }
287     const fltSemantics &getSemantics() const { return *semantics; }
288     bool isZero() const { return category == fcZero; }
289     bool isNonZero() const { return category != fcZero; }
290     bool isNaN() const { return category == fcNaN; }
291     bool isInfinity() const { return category == fcInfinity; }
292     bool isNegative() const { return sign; }
293     bool isPosZero() const { return isZero() && !isNegative(); }
294     bool isNegZero() const { return isZero() && isNegative(); }
295
296     APFloat& operator=(const APFloat &);
297
298     /* Return an arbitrary integer value usable for hashing. */
299     uint32_t getHashValue() const;
300
301     /// Converts this value into a decimal string.
302     ///
303     /// \param FormatPrecision The maximum number of digits of
304     ///   precision to output.  If there are fewer digits available,
305     ///   zero padding will not be used unless the value is
306     ///   integral and small enough to be expressed in
307     ///   FormatPrecision digits.  0 means to use the natural
308     ///   precision of the number.
309     /// \param FormatMaxPadding The maximum number of zeros to
310     ///   consider inserting before falling back to scientific
311     ///   notation.  0 means to always use scientific notation.
312     ///
313     /// Number       Precision    MaxPadding      Result
314     /// ------       ---------    ----------      ------
315     /// 1.01E+4              5             2       10100
316     /// 1.01E+4              4             2       1.01E+4
317     /// 1.01E+4              5             1       1.01E+4
318     /// 1.01E-2              5             2       0.0101
319     /// 1.01E-2              4             2       0.0101
320     /// 1.01E-2              4             1       1.01E-2
321     void toString(SmallVectorImpl<char> &Str,
322                   unsigned FormatPrecision = 0,
323                   unsigned FormatMaxPadding = 3);
324
325   private:
326
327     /* Trivial queries.  */
328     integerPart *significandParts();
329     const integerPart *significandParts() const;
330     unsigned int partCount() const;
331
332     /* Significand operations.  */
333     integerPart addSignificand(const APFloat &);
334     integerPart subtractSignificand(const APFloat &, integerPart);
335     lostFraction addOrSubtractSignificand(const APFloat &, bool subtract);
336     lostFraction multiplySignificand(const APFloat &, const APFloat *);
337     lostFraction divideSignificand(const APFloat &);
338     void incrementSignificand();
339     void initialize(const fltSemantics *);
340     void shiftSignificandLeft(unsigned int);
341     lostFraction shiftSignificandRight(unsigned int);
342     unsigned int significandLSB() const;
343     unsigned int significandMSB() const;
344     void zeroSignificand();
345
346     /* Arithmetic on special values.  */
347     opStatus addOrSubtractSpecials(const APFloat &, bool subtract);
348     opStatus divideSpecials(const APFloat &);
349     opStatus multiplySpecials(const APFloat &);
350     opStatus modSpecials(const APFloat &);
351
352     /* Miscellany.  */
353     void makeNaN(unsigned = 0);
354     opStatus normalize(roundingMode, lostFraction);
355     opStatus addOrSubtract(const APFloat &, roundingMode, bool subtract);
356     cmpResult compareAbsoluteValue(const APFloat &) const;
357     opStatus handleOverflow(roundingMode);
358     bool roundAwayFromZero(roundingMode, lostFraction, unsigned int) const;
359     opStatus convertToSignExtendedInteger(integerPart *, unsigned int, bool,
360                                           roundingMode, bool *) const;
361     opStatus convertFromUnsignedParts(const integerPart *, unsigned int,
362                                       roundingMode);
363     opStatus convertFromHexadecimalString(const StringRef&, roundingMode);
364     opStatus convertFromDecimalString (const StringRef&, roundingMode);
365     char *convertNormalToHexString(char *, unsigned int, bool,
366                                    roundingMode) const;
367     opStatus roundSignificandWithExponent(const integerPart *, unsigned int,
368                                           int, roundingMode);
369
370     APInt convertHalfAPFloatToAPInt() const;
371     APInt convertFloatAPFloatToAPInt() const;
372     APInt convertDoubleAPFloatToAPInt() const;
373     APInt convertQuadrupleAPFloatToAPInt() const;
374     APInt convertF80LongDoubleAPFloatToAPInt() const;
375     APInt convertPPCDoubleDoubleAPFloatToAPInt() const;
376     void initFromAPInt(const APInt& api, bool isIEEE = false);
377     void initFromHalfAPInt(const APInt& api);
378     void initFromFloatAPInt(const APInt& api);
379     void initFromDoubleAPInt(const APInt& api);
380     void initFromQuadrupleAPInt(const APInt &api);
381     void initFromF80LongDoubleAPInt(const APInt& api);
382     void initFromPPCDoubleDoubleAPInt(const APInt& api);
383
384     void assign(const APFloat &);
385     void copySignificand(const APFloat &);
386     void freeSignificand();
387
388     /* What kind of semantics does this value obey?  */
389     const fltSemantics *semantics;
390
391     /* Significand - the fraction with an explicit integer bit.  Must be
392        at least one bit wider than the target precision.  */
393     union Significand
394     {
395       integerPart part;
396       integerPart *parts;
397     } significand;
398
399     /* The exponent - a signed number.  */
400     exponent_t exponent;
401
402     /* What kind of floating point number this is.  */
403     /* Only 2 bits are required, but VisualStudio incorrectly sign extends
404        it.  Using the extra bit keeps it from failing under VisualStudio */
405     fltCategory category: 3;
406
407     /* The sign bit of this number.  */
408     unsigned int sign: 1;
409
410     /* For PPCDoubleDouble, we have a second exponent and sign (the second
411        significand is appended to the first one, although it would be wrong to
412        regard these as a single number for arithmetic purposes).  These fields
413        are not meaningful for any other type. */
414     exponent_t exponent2 : 11;
415     unsigned int sign2: 1;
416   };
417 } /* namespace llvm */
418
419 #endif /* LLVM_FLOAT_H */