combineLostFractions does not need to be a member function
[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 was developed by Neil Booth and is distributed under the
6 // University of Illinois Open Source 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     Conversion to and from decimal text is not currently implemented.
64
65     Non-zero finite numbers are represented internally as a sign bit,
66     a 16-bit signed exponent, and the significand as an array of
67     integer parts.  After normalization of a number of precision P the
68     exponent is within the range of the format, and if the number is
69     not denormal the P-th bit of the significand is set as an explicit
70     integer bit.  For denormals the most significant bit is shifted
71     right so that the exponent is maintained at the format's minimum,
72     so that the smallest denormal has just the least significant bit
73     of the significand set.  The sign of zeroes and infinities is
74     significant; the exponent and significand of such numbers is not
75     stored, but has a known implicit (deterministic) value: 0 for the
76     significands, 0 for zero exponent, all 1 bits for infinity
77     exponent.  For NaNs the sign and significand are deterministic,
78     although not really meaningful, and preserved in non-conversion
79     operations.  The exponent is implicitly all 1 bits.
80
81     TODO
82     ====
83
84     Some features that may or may not be worth adding:
85
86     Conversions to and from decimal strings (hard).
87
88     Optional ability to detect underflow tininess before rounding.
89
90     New formats: x87 in single and double precision mode (IEEE apart
91     from extended exponent range) and IBM two-double extended
92     precision (hard).
93
94     New operations: sqrt, IEEE remainder, C90 fmod, nextafter,
95     nexttoward.
96 */
97
98 #ifndef LLVM_FLOAT_H
99 #define LLVM_FLOAT_H
100
101 // APInt contains static functions implementing bignum arithmetic.
102 #include "llvm/ADT/APInt.h"
103 #include "llvm/CodeGen/ValueTypes.h"
104
105 namespace llvm {
106
107   /* Exponents are stored as signed numbers.  */
108   typedef signed short exponent_t;
109
110   struct fltSemantics;
111
112   /* When bits of a floating point number are truncated, this enum is
113      used to indicate what fraction of the LSB those bits represented.
114      It essentially combines the roles of guard and sticky bits.  */
115   enum lostFraction {           // Example of truncated bits:
116     lfExactlyZero,              // 000000
117     lfLessThanHalf,             // 0xxxxx  x's not all zero
118     lfExactlyHalf,              // 100000
119     lfMoreThanHalf              // 1xxxxx  x's not all zero
120   };
121
122   class APFloat {
123   public:
124
125     /* We support the following floating point semantics.  */
126     static const fltSemantics IEEEsingle;
127     static const fltSemantics IEEEdouble;
128     static const fltSemantics IEEEquad;
129     static const fltSemantics x87DoubleExtended;
130     /* And this psuedo, used to construct APFloats that cannot
131        conflict with anything real. */
132     static const fltSemantics Bogus;
133
134     static unsigned int semanticsPrecision(const fltSemantics &);
135
136     /* Floating point numbers have a four-state comparison relation.  */
137     enum cmpResult {
138       cmpLessThan,
139       cmpEqual,
140       cmpGreaterThan,
141       cmpUnordered
142     };
143
144     /* IEEE-754R gives five rounding modes.  */
145     enum roundingMode {
146       rmNearestTiesToEven,
147       rmTowardPositive,
148       rmTowardNegative,
149       rmTowardZero,
150       rmNearestTiesToAway
151     };
152
153     /* Operation status.  opUnderflow or opOverflow are always returned
154        or-ed with opInexact.  */
155     enum opStatus {
156       opOK          = 0x00,
157       opInvalidOp   = 0x01,
158       opDivByZero   = 0x02,
159       opOverflow    = 0x04,
160       opUnderflow   = 0x08,
161       opInexact     = 0x10
162     };
163
164     /* Category of internally-represented number.  */
165     enum fltCategory {
166       fcInfinity,
167       fcNaN,
168       fcNormal,
169       fcZero
170     };
171
172     /* Constructors.  */
173     APFloat(const fltSemantics &, const char *);
174     APFloat(const fltSemantics &, integerPart);
175     APFloat(const fltSemantics &, fltCategory, bool negative);
176     explicit APFloat(double d);
177     explicit APFloat(float f);
178     explicit APFloat(const APInt &);
179     APFloat(const APFloat &);
180     ~APFloat();
181
182     /* Arithmetic.  */
183     opStatus add(const APFloat &, roundingMode);
184     opStatus subtract(const APFloat &, roundingMode);
185     opStatus multiply(const APFloat &, roundingMode);
186     opStatus divide(const APFloat &, roundingMode);
187     opStatus mod(const APFloat &, roundingMode);
188     void copySign(const APFloat &);
189     opStatus fusedMultiplyAdd(const APFloat &, const APFloat &, roundingMode);
190     void changeSign();    // neg
191     void clearSign();     // abs
192
193     /* Conversions.  */
194     opStatus convert(const fltSemantics &, roundingMode);
195     opStatus convertToInteger(integerPart *, unsigned int, bool,
196                               roundingMode) const;
197     opStatus convertFromInteger(const integerPart *, unsigned int, bool,
198                                 roundingMode);
199     opStatus convertFromString(const char *, roundingMode);
200     APInt convertToAPInt() const;
201     double convertToDouble() const;
202     float convertToFloat() const;
203
204     /* The definition of equality is not straightforward for floating point,
205        so we won't use operator==.  Use one of the following, or write
206        whatever it is you really mean. */
207     // bool operator==(const APFloat &) const;     // DO NOT IMPLEMENT
208
209     /* IEEE comparison with another floating point number (NaNs
210        compare unordered, 0==-0). */
211     cmpResult compare(const APFloat &) const;
212
213     /* Write out a hexadecimal representation of the floating point
214        value to DST, which must be of sufficient size, in the C99 form
215        [-]0xh.hhhhp[+-]d.  Return the number of characters written,
216        excluding the terminating NUL.  */
217     unsigned int convertToHexString(char *dst, unsigned int hexDigits,
218                                     bool upperCase, roundingMode) const;
219
220     /* Bitwise comparison for equality (QNaNs compare equal, 0!=-0). */
221     bool bitwiseIsEqual(const APFloat &) const;
222
223     /* Simple queries.  */
224     fltCategory getCategory() const { return category; }
225     const fltSemantics &getSemantics() const { return *semantics; }
226     bool isZero() const { return category == fcZero; }
227     bool isNonZero() const { return category != fcZero; }
228     bool isNegative() const { return sign; }
229     bool isPosZero() const { return isZero() && !isNegative(); }
230     bool isNegZero() const { return isZero() && isNegative(); }
231
232     APFloat& operator=(const APFloat &);
233
234     /* Return an arbitrary integer value usable for hashing. */
235     uint32_t getHashValue() const;
236
237   private:
238
239     /* Trivial queries.  */
240     integerPart *significandParts();
241     const integerPart *significandParts() const;
242     unsigned int partCount() const;
243
244     /* Significand operations.  */
245     integerPart addSignificand(const APFloat &);
246     integerPart subtractSignificand(const APFloat &, integerPart);
247     lostFraction addOrSubtractSignificand(const APFloat &, bool subtract);
248     lostFraction multiplySignificand(const APFloat &, const APFloat *);
249     lostFraction divideSignificand(const APFloat &);
250     void incrementSignificand();
251     void initialize(const fltSemantics *);
252     void shiftSignificandLeft(unsigned int);
253     lostFraction shiftSignificandRight(unsigned int);
254     unsigned int significandLSB() const;
255     unsigned int significandMSB() const;
256     void zeroSignificand();
257
258     /* Arithmetic on special values.  */
259     opStatus addOrSubtractSpecials(const APFloat &, bool subtract);
260     opStatus divideSpecials(const APFloat &);
261     opStatus multiplySpecials(const APFloat &);
262
263     /* Miscellany.  */
264     opStatus normalize(roundingMode, lostFraction);
265     opStatus addOrSubtract(const APFloat &, roundingMode, bool subtract);
266     cmpResult compareAbsoluteValue(const APFloat &) const;
267     opStatus handleOverflow(roundingMode);
268     bool roundAwayFromZero(roundingMode, lostFraction, unsigned int) const;
269     opStatus convertFromUnsignedInteger(integerPart *, unsigned int,
270                                         roundingMode);
271     opStatus convertFromHexadecimalString(const char *, roundingMode);
272     char *convertNormalToHexString(char *, unsigned int, bool,
273                                    roundingMode) const;
274     APInt convertFloatAPFloatToAPInt() const;
275     APInt convertDoubleAPFloatToAPInt() const;
276     APInt convertF80LongDoubleAPFloatToAPInt() const;
277     void initFromAPInt(const APInt& api);
278     void initFromFloatAPInt(const APInt& api);
279     void initFromDoubleAPInt(const APInt& api);
280     void initFromF80LongDoubleAPInt(const APInt& api);
281
282     void assign(const APFloat &);
283     void copySignificand(const APFloat &);
284     void freeSignificand();
285
286     /* What kind of semantics does this value obey?  */
287     const fltSemantics *semantics;
288
289     /* Significand - the fraction with an explicit integer bit.  Must be
290        at least one bit wider than the target precision.  */
291     union Significand
292     {
293       integerPart part;
294       integerPart *parts;
295     } significand;
296
297     /* The exponent - a signed number.  */
298     exponent_t exponent;
299
300     /* What kind of floating point number this is.  */
301     /* Only 2 bits are required, but VisualStudio incorrectly sign extends
302        it.  Using the extra bit keeps it from failing under VisualStudio */
303     fltCategory category: 3;
304
305     /* The sign bit of this number.  */
306     unsigned int sign: 1;
307   };
308 } /* namespace llvm */
309
310 #endif /* LLVM_FLOAT_H */