Change internal representation of ConstantFP to use APFloat.
[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 using 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.  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.  The library reads
34     and correctly rounds hexadecimal floating point numbers as per
35     C99; syntax is required to have been validated by the caller.
36     Conversion from decimal is not currently implemented.
37
38     Four formats are built-in: IEEE single precision, double
39     precision, quadruple precision, and x87 80-bit extended double
40     (when operating with full extended precision).  Adding a new
41     format that obeys IEEE semantics only requires adding two lines of
42     code: a declaration and definition of the format.
43
44     All operations return the status of that operation as an exception
45     bit-mask, so multiple operations can be done consecutively with
46     their results or-ed together.  The returned status can be useful
47     for compiler diagnostics; e.g., inexact, underflow and overflow
48     can be easily diagnosed on constant folding, and compiler
49     optimizers can determine what exceptions would be raised by
50     folding operations and optimize, or perhaps not optimize,
51     accordingly.
52
53     At present, underflow tininess is detected after rounding; it
54     should be straight forward to add support for the before-rounding
55     case too.
56
57     Non-zero finite numbers are represented internally as a sign bit,
58     a 16-bit signed exponent, and the significand as an array of
59     integer parts.  After normalization of a number of precision P the
60     exponent is within the range of the format, and if the number is
61     not denormal the P-th bit of the significand is set as an explicit
62     integer bit.  For denormals the most significant bit is shifted
63     right so that the exponent is maintained at the format's minimum,
64     so that the smallest denormal has just the least significant bit
65     of the significand set.  The sign of zeroes and infinities is
66     significant; the exponent and significand of such numbers is
67     indeterminate and meaningless.  For QNaNs the sign bit, as well as
68     the exponent and significand are indeterminate and meaningless.
69
70     TODO
71     ====
72
73     Some features that may or may not be worth adding:
74
75     Conversions to and from decimal strings (hard).
76
77     Conversions to hexadecimal string.
78
79     Read and write IEEE-format in-memory representations.
80
81     Optional ability to detect underflow tininess before rounding.
82
83     New formats: x87 in single and double precision mode (IEEE apart
84     from extended exponent range) and IBM two-double extended
85     precision (hard).
86
87     New operations: sqrt, copysign, nextafter, nexttoward.
88 */
89
90 #ifndef LLVM_FLOAT_H
91 #define LLVM_FLOAT_H
92
93 // APInt contains static functions implementing bignum arithmetic.
94 #include "llvm/ADT/APInt.h"
95
96 namespace llvm {
97
98   /* Exponents are stored as signed numbers.  */
99   typedef signed short exponent_t;
100
101   struct fltSemantics;
102
103   /* When bits of a floating point number are truncated, this enum is
104      used to indicate what fraction of the LSB those bits represented.
105      It essentially combines the roles of guard and sticky bits.  */
106   enum lostFraction {           // Example of truncated bits:
107     lfExactlyZero,              // 000000
108     lfLessThanHalf,             // 0xxxxx  x's not all zero
109     lfExactlyHalf,              // 100000
110     lfMoreThanHalf              // 1xxxxx  x's not all zero
111   };
112
113   class APFloat {
114   public:
115
116     /* We support the following floating point semantics.  */
117     static const fltSemantics IEEEsingle;
118     static const fltSemantics IEEEdouble;
119     static const fltSemantics IEEEquad;
120     static const fltSemantics x87DoubleExtended;
121     /* And this psuedo, used to construct APFloats that cannot
122        conflict with anything real. */
123     static const fltSemantics Bogus;
124
125     static unsigned int semanticsPrecision(const fltSemantics &);
126
127     /* Floating point numbers have a four-state comparison relation.  */
128     enum cmpResult {
129       cmpLessThan,
130       cmpEqual,
131       cmpGreaterThan,
132       cmpUnordered
133     };
134
135     /* IEEE-754R gives five rounding modes.  */
136     enum roundingMode {
137       rmNearestTiesToEven,
138       rmTowardPositive,
139       rmTowardNegative,
140       rmTowardZero,
141       rmNearestTiesToAway
142     };
143
144     /* Operation status.  opUnderflow or opOverflow are always returned
145        or-ed with opInexact.  */
146     enum opStatus {
147       opOK          = 0x00,
148       opInvalidOp   = 0x01,
149       opDivByZero   = 0x02,
150       opOverflow    = 0x04,
151       opUnderflow   = 0x08,
152       opInexact     = 0x10
153     };
154
155     /* Category of internally-represented number.  */
156     enum fltCategory {
157       fcInfinity,
158       fcQNaN,
159       fcNormal,
160       fcZero
161     };
162
163     /* Constructors.  */
164     APFloat(const fltSemantics &, const char *);
165     APFloat(const fltSemantics &, integerPart);
166     APFloat(const fltSemantics &, fltCategory, bool negative);
167     APFloat(double d);
168     APFloat(float f);
169     APFloat(const APFloat &);
170     ~APFloat();
171
172     /* Arithmetic.  */
173     opStatus add(const APFloat &, roundingMode);
174     opStatus subtract(const APFloat &, roundingMode);
175     opStatus multiply(const APFloat &, roundingMode);
176     opStatus divide(const APFloat &, roundingMode);
177     opStatus fusedMultiplyAdd(const APFloat &, const APFloat &, roundingMode);
178     void changeSign();
179
180     /* Conversions.  */
181     opStatus convert(const fltSemantics &, roundingMode);
182     opStatus convertToInteger(integerPart *, unsigned int, bool,
183                               roundingMode) const;
184     opStatus convertFromInteger(const integerPart *, unsigned int, bool,
185                                 roundingMode);
186     opStatus convertFromString(const char *, roundingMode);
187     double convertToDouble() const;
188     float convertToFloat() const;
189
190     /* IEEE comparison with another floating point number (QNaNs
191        compare unordered, 0==-0). */
192     cmpResult compare(const APFloat &) const;
193
194     /* Bitwise comparison for equality (QNaNs compare equal, 0!=-0). */
195     bool operator==(const APFloat &) const;
196
197     /* Simple queries.  */
198     fltCategory getCategory() const { return category; }
199     const fltSemantics &getSemantics() const { return *semantics; }
200     bool isZero() const { return category == fcZero; }
201     bool isNonZero() const { return category != fcZero; }
202     bool isNegative() const { return sign; }
203
204     APFloat& operator=(const APFloat &);
205
206     /* Return an arbitrary integer value usable for hashing. */
207     uint32_t getHashValue() const;
208
209   private:
210
211     /* Trivial queries.  */
212     integerPart *significandParts();
213     const integerPart *significandParts() const;
214     unsigned int partCount() const;
215
216     /* Significand operations.  */
217     integerPart addSignificand(const APFloat &);
218     integerPart subtractSignificand(const APFloat &, integerPart);
219     lostFraction addOrSubtractSignificand(const APFloat &, bool subtract);
220     lostFraction multiplySignificand(const APFloat &, const APFloat *);
221     lostFraction divideSignificand(const APFloat &);
222     void incrementSignificand();
223     void initialize(const fltSemantics *);
224     void shiftSignificandLeft(unsigned int);
225     lostFraction shiftSignificandRight(unsigned int);
226     unsigned int significandLSB() const;
227     unsigned int significandMSB() const;
228     void zeroSignificand();
229
230     /* Arithmetic on special values.  */
231     opStatus addOrSubtractSpecials(const APFloat &, bool subtract);
232     opStatus divideSpecials(const APFloat &);
233     opStatus multiplySpecials(const APFloat &);
234
235     /* Miscellany.  */
236     opStatus normalize(roundingMode, lostFraction);
237     opStatus addOrSubtract(const APFloat &, roundingMode, bool subtract);
238     cmpResult compareAbsoluteValue(const APFloat &) const;
239     opStatus handleOverflow(roundingMode);
240     bool roundAwayFromZero(roundingMode, lostFraction);
241     opStatus convertFromUnsignedInteger(integerPart *, unsigned int,
242                                         roundingMode);
243     lostFraction combineLostFractions(lostFraction, lostFraction);
244     opStatus convertFromHexadecimalString(const char *, roundingMode);
245
246     void assign(const APFloat &);
247     void copySignificand(const APFloat &);
248     void freeSignificand();
249
250     /* What kind of semantics does this value obey?  */
251     const fltSemantics *semantics;
252
253     /* Significand - the fraction with an explicit integer bit.  Must be
254        at least one bit wider than the target precision.  */
255     union Significand
256     {
257       integerPart part;
258       integerPart *parts;
259     } significand;
260
261     /* The exponent - a signed number.  */
262     exponent_t exponent;
263
264     /* What kind of floating point number this is.  */
265     fltCategory category: 2;
266
267     /* The sign bit of this number.  */
268     unsigned int sign: 1;
269   };
270 } /* namespace llvm */
271
272 #endif /* LLVM_FLOAT_H */