Removed a comment above an include which is unnecessary and added a missing closing...
[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 /// \file
11 /// \brief
12 /// This file declares a class to represent arbitrary precision floating point
13 /// values and provide a variety of arithmetic operations on them.
14 ///
15 //===----------------------------------------------------------------------===//
16
17 #ifndef LLVM_ADT_APFLOAT_H
18 #define LLVM_ADT_APFLOAT_H
19
20 #include "llvm/ADT/APInt.h"
21
22 namespace llvm {
23
24 /// A signed type to represent a floating point numbers unbiased exponent.
25 typedef signed short exponent_t;
26
27 struct fltSemantics;
28 class APSInt;
29 class StringRef;
30
31 /// Enum that represents what fraction of the LSB truncated bits of an fp number
32 /// represent.
33 ///
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
40 };
41
42 /// \brief A self-contained host- and target-independent arbitrary-precision
43 /// floating-point software implementation.
44 ///
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.
48 ///
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.
55 ///
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.
61 ///
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
66 /// format.
67 ///
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.
74 ///
75 /// At present, underflow tininess is detected after rounding; it should be
76 /// straight forward to add support for the before-rounding case too.
77 ///
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
85 /// mode.
86 ///
87 /// It also reads decimal floating point numbers and correctly rounds according
88 /// to the specified rounding mode.
89 ///
90 /// Conversion to decimal text is not currently implemented.
91 ///
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.
105 ///
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
109 /// 0.
110 ///
111 /// TODO
112 /// ====
113 ///
114 /// Some features that may or may not be worth adding:
115 ///
116 /// Binary to decimal conversion (hard).
117 ///
118 /// Optional ability to detect underflow tininess before rounding.
119 ///
120 /// New formats: x87 in single and double precision mode (IEEE apart from
121 /// extended exponent range) (hard).
122 ///
123 /// New operations: sqrt, IEEE remainder, C90 fmod, nextafter, nexttoward.
124 ///
125 class APFloat {
126 public:
127
128   /// \name Floating Point Semantics.
129   /// @{
130
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;
137
138   /// A Pseudo fltsemantic used to construct APFloats that cannot conflict with
139   /// anything real.
140   static const fltSemantics Bogus;
141
142   /// @}
143
144   static unsigned int semanticsPrecision(const fltSemantics &);
145
146   /// IEEE-754R 5.11: Floating Point Comparison Relations.
147   enum cmpResult {
148     cmpLessThan,
149     cmpEqual,
150     cmpGreaterThan,
151     cmpUnordered
152   };
153
154   /// IEEE-754R 4.3: Rounding-direction attributes.
155   enum roundingMode {
156     rmNearestTiesToEven,
157     rmTowardPositive,
158     rmTowardNegative,
159     rmTowardZero,
160     rmNearestTiesToAway
161   };
162
163   /// IEEE-754R 7: Default exception handling.
164   ///
165   /// opUnderflow or opOverflow are always returned or-ed with opInexact.
166   enum opStatus {
167     opOK = 0x00,
168     opInvalidOp = 0x01,
169     opDivByZero = 0x02,
170     opOverflow = 0x04,
171     opUnderflow = 0x08,
172     opInexact = 0x10
173   };
174
175   /// Category of internally-represented number.
176   enum fltCategory {
177     fcInfinity,
178     fcNaN,
179     fcNormal,
180     fcZero
181   };
182
183   /// Convenience enum used to construct an uninitialized APFloat.
184   enum uninitializedTag {
185     uninitialized
186   };
187
188   /// \name Constructors
189   /// @{
190
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 &);
200   ~APFloat();
201
202   /// @}
203
204   /// \name Convenience "constructors"
205   /// @{
206
207   /// Factory for Positive and Negative Zero.
208   ///
209   /// \param Negative True iff the number should be negative.
210   static APFloat getZero(const fltSemantics &Sem, bool Negative = false) {
211     return APFloat(Sem, fcZero, Negative);
212   }
213
214   /// Factory for Positive and Negative Infinity.
215   ///
216   /// \param Negative True iff the number should be negative.
217   static APFloat getInf(const fltSemantics &Sem, bool Negative = false) {
218     return APFloat(Sem, fcInfinity, Negative);
219   }
220
221   /// Factory for QNaN values.
222   ///
223   /// \param Negative - True iff the NaN generated should be negative.
224   /// \param type - The unspecified fill bits for creating the NaN, 0 by
225   /// default.  The value is truncated as necessary.
226   static APFloat getNaN(const fltSemantics &Sem, bool Negative = false,
227                         unsigned type = 0) {
228     if (type) {
229       APInt fill(64, type);
230       return getQNaN(Sem, Negative, &fill);
231     } else {
232       return getQNaN(Sem, Negative, 0);
233     }
234   }
235
236   /// Factory for QNaN values.
237   static APFloat getQNaN(const fltSemantics &Sem, bool Negative = false,
238                          const APInt *payload = 0) {
239     return makeNaN(Sem, false, Negative, payload);
240   }
241
242   /// Factory for SNaN values.
243   static APFloat getSNaN(const fltSemantics &Sem, bool Negative = false,
244                          const APInt *payload = 0) {
245     return makeNaN(Sem, true, Negative, payload);
246   }
247
248   /// Returns the largest finite number in the given semantics.
249   ///
250   /// \param Negative - True iff the number should be negative
251   static APFloat getLargest(const fltSemantics &Sem, bool Negative = false);
252
253   /// Returns the smallest (by magnitude) finite number in the given semantics.
254   /// Might be denormalized, which implies a relative loss of precision.
255   ///
256   /// \param Negative - True iff the number should be negative
257   static APFloat getSmallest(const fltSemantics &Sem, bool Negative = false);
258
259   /// Returns the smallest (by magnitude) normalized finite number in the given
260   /// semantics.
261   ///
262   /// \param Negative - True iff the number should be negative
263   static APFloat getSmallestNormalized(const fltSemantics &Sem,
264                                        bool Negative = false);
265
266   /// Returns a float which is bitcasted from an all one value int.
267   ///
268   /// \param BitWidth - Select float type
269   /// \param isIEEE   - If 128 bit number, select between PPC and IEEE
270   static APFloat getAllOnesValue(unsigned BitWidth, bool isIEEE = false);
271
272   /// @}
273
274   /// Used to insert APFloat objects, or objects that contain APFloat objects,
275   /// into FoldingSets.
276   void Profile(FoldingSetNodeID &NID) const;
277
278   /// \brief Used by the Bitcode serializer to emit APInts to Bitcode.
279   void Emit(Serializer &S) const;
280
281   /// \brief Used by the Bitcode deserializer to deserialize APInts.
282   static APFloat ReadVal(Deserializer &D);
283
284   /// \name Arithmetic
285   /// @{
286
287   opStatus add(const APFloat &, roundingMode);
288   opStatus subtract(const APFloat &, roundingMode);
289   opStatus multiply(const APFloat &, roundingMode);
290   opStatus divide(const APFloat &, roundingMode);
291   /// IEEE remainder.
292   opStatus remainder(const APFloat &);
293   /// C fmod, or llvm frem.
294   opStatus mod(const APFloat &, roundingMode);
295   opStatus fusedMultiplyAdd(const APFloat &, const APFloat &, roundingMode);
296   opStatus roundToIntegral(roundingMode);
297   /// IEEE-754R 5.3.1: nextUp/nextDown.
298   opStatus next(bool nextDown);
299
300   /// \name Sign operations.
301   /// @{
302
303   void changeSign();
304   void clearSign();
305   void copySign(const APFloat &);
306
307   /// @}
308
309   /// \name Conversions
310   /// @{
311
312   opStatus convert(const fltSemantics &, roundingMode, bool *);
313   opStatus convertToInteger(integerPart *, unsigned int, bool, roundingMode,
314                             bool *) const;
315   opStatus convertToInteger(APSInt &, roundingMode, bool *) const;
316   opStatus convertFromAPInt(const APInt &, bool, roundingMode);
317   opStatus convertFromSignExtendedInteger(const integerPart *, unsigned int,
318                                           bool, roundingMode);
319   opStatus convertFromZeroExtendedInteger(const integerPart *, unsigned int,
320                                           bool, roundingMode);
321   opStatus convertFromString(StringRef, roundingMode);
322   APInt bitcastToAPInt() const;
323   double convertToDouble() const;
324   float convertToFloat() const;
325
326   /// @}
327
328   /// The definition of equality is not straightforward for floating point, so
329   /// we won't use operator==.  Use one of the following, or write whatever it
330   /// is you really mean.
331   bool operator==(const APFloat &) const LLVM_DELETED_FUNCTION;
332
333   /// IEEE comparison with another floating point number (NaNs compare
334   /// unordered, 0==-0).
335   cmpResult compare(const APFloat &) const;
336
337   /// Bitwise comparison for equality (QNaNs compare equal, 0!=-0).
338   bool bitwiseIsEqual(const APFloat &) const;
339
340   /// Write out a hexadecimal representation of the floating point value to DST,
341   /// which must be of sufficient size, in the C99 form [-]0xh.hhhhp[+-]d.
342   /// Return the number of characters written, excluding the terminating NUL.
343   unsigned int convertToHexString(char *dst, unsigned int hexDigits,
344                                   bool upperCase, roundingMode) const;
345
346   /// \name Simple Queries
347   /// @{
348
349   fltCategory getCategory() const { return category; }
350   const fltSemantics &getSemantics() const { return *semantics; }
351   bool isZero() const { return category == fcZero; }
352   bool isNonZero() const { return category != fcZero; }
353   bool isNormal() const { return category == fcNormal; }
354   bool isNaN() const { return category == fcNaN; }
355   bool isInfinity() const { return category == fcInfinity; }
356   bool isNegative() const { return sign; }
357   bool isPosZero() const { return isZero() && !isNegative(); }
358   bool isNegZero() const { return isZero() && isNegative(); }
359   bool isDenormal() const;
360   /// IEEE-754R 5.7.2: isSignaling. Returns true if this is a signaling NaN.
361   bool isSignaling() const;
362
363   /// @}
364
365   APFloat &operator=(const APFloat &);
366
367   /// \brief Overload to compute a hash code for an APFloat value.
368   ///
369   /// Note that the use of hash codes for floating point values is in general
370   /// frought with peril. Equality is hard to define for these values. For
371   /// example, should negative and positive zero hash to different codes? Are
372   /// they equal or not? This hash value implementation specifically
373   /// emphasizes producing different codes for different inputs in order to
374   /// be used in canonicalization and memoization. As such, equality is
375   /// bitwiseIsEqual, and 0 != -0.
376   friend hash_code hash_value(const APFloat &Arg);
377
378   /// Converts this value into a decimal string.
379   ///
380   /// \param FormatPrecision The maximum number of digits of
381   ///   precision to output.  If there are fewer digits available,
382   ///   zero padding will not be used unless the value is
383   ///   integral and small enough to be expressed in
384   ///   FormatPrecision digits.  0 means to use the natural
385   ///   precision of the number.
386   /// \param FormatMaxPadding The maximum number of zeros to
387   ///   consider inserting before falling back to scientific
388   ///   notation.  0 means to always use scientific notation.
389   ///
390   /// Number       Precision    MaxPadding      Result
391   /// ------       ---------    ----------      ------
392   /// 1.01E+4              5             2       10100
393   /// 1.01E+4              4             2       1.01E+4
394   /// 1.01E+4              5             1       1.01E+4
395   /// 1.01E-2              5             2       0.0101
396   /// 1.01E-2              4             2       0.0101
397   /// 1.01E-2              4             1       1.01E-2
398   void toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision = 0,
399                 unsigned FormatMaxPadding = 3) const;
400
401   /// If this value has an exact multiplicative inverse, store it in inv and
402   /// return true.
403   bool getExactInverse(APFloat *inv) const;
404
405 private:
406
407   /// \name Simple Queries
408   /// @{
409
410   integerPart *significandParts();
411   const integerPart *significandParts() const;
412   unsigned int partCount() const;
413
414   /// @}
415
416   /// \name Significand operations.
417   /// @{
418
419   integerPart addSignificand(const APFloat &);
420   integerPart subtractSignificand(const APFloat &, integerPart);
421   lostFraction addOrSubtractSignificand(const APFloat &, bool subtract);
422   lostFraction multiplySignificand(const APFloat &, const APFloat *);
423   lostFraction divideSignificand(const APFloat &);
424   void incrementSignificand();
425   void initialize(const fltSemantics *);
426   void shiftSignificandLeft(unsigned int);
427   lostFraction shiftSignificandRight(unsigned int);
428   unsigned int significandLSB() const;
429   unsigned int significandMSB() const;
430   void zeroSignificand();
431   /// Return true if the significand excluding the integral bit is all ones.
432   bool isSignificandAllOnes() const;
433   /// Return true if the significand excluding the integral bit is all zeros.
434   bool isSignificandAllZeros() const;
435
436   /// @}
437
438   /// \name Arithmetic on special values.
439   /// @{
440
441   opStatus addOrSubtractSpecials(const APFloat &, bool subtract);
442   opStatus divideSpecials(const APFloat &);
443   opStatus multiplySpecials(const APFloat &);
444   opStatus modSpecials(const APFloat &);
445
446   /// @}
447
448   /// \name Special value setters.
449   /// @{
450
451   void makeLargest(bool Neg = false);
452   void makeSmallest(bool Neg = false);
453   void makeNaN(bool SNaN = false, bool Neg = false, const APInt *fill = 0);
454   static APFloat makeNaN(const fltSemantics &Sem, bool SNaN, bool Negative,
455                          const APInt *fill);
456
457   /// @}
458
459   /// \name Special value queries only useful internally to APFloat
460   /// @{
461
462   /// Returns true if and only if the number has the smallest possible non-zero
463   /// magnitude in the current semantics.
464   bool isSmallest() const;
465   /// Returns true if and only if the number has the largest possible finite
466   /// magnitude in the current semantics.
467   bool isLargest() const;
468
469   /// @}
470
471   /// \name Miscellany
472   /// @{
473
474   opStatus normalize(roundingMode, lostFraction);
475   opStatus addOrSubtract(const APFloat &, roundingMode, bool subtract);
476   cmpResult compareAbsoluteValue(const APFloat &) const;
477   opStatus handleOverflow(roundingMode);
478   bool roundAwayFromZero(roundingMode, lostFraction, unsigned int) const;
479   opStatus convertToSignExtendedInteger(integerPart *, unsigned int, bool,
480                                         roundingMode, bool *) const;
481   opStatus convertFromUnsignedParts(const integerPart *, unsigned int,
482                                     roundingMode);
483   opStatus convertFromHexadecimalString(StringRef, roundingMode);
484   opStatus convertFromDecimalString(StringRef, roundingMode);
485   char *convertNormalToHexString(char *, unsigned int, bool,
486                                  roundingMode) const;
487   opStatus roundSignificandWithExponent(const integerPart *, unsigned int, int,
488                                         roundingMode);
489
490   /// @}
491
492   APInt convertHalfAPFloatToAPInt() const;
493   APInt convertFloatAPFloatToAPInt() const;
494   APInt convertDoubleAPFloatToAPInt() const;
495   APInt convertQuadrupleAPFloatToAPInt() const;
496   APInt convertF80LongDoubleAPFloatToAPInt() const;
497   APInt convertPPCDoubleDoubleAPFloatToAPInt() const;
498   void initFromAPInt(const fltSemantics *Sem, const APInt &api);
499   void initFromHalfAPInt(const APInt &api);
500   void initFromFloatAPInt(const APInt &api);
501   void initFromDoubleAPInt(const APInt &api);
502   void initFromQuadrupleAPInt(const APInt &api);
503   void initFromF80LongDoubleAPInt(const APInt &api);
504   void initFromPPCDoubleDoubleAPInt(const APInt &api);
505
506   void assign(const APFloat &);
507   void copySignificand(const APFloat &);
508   void freeSignificand();
509
510   /// The semantics that this value obeys.
511   const fltSemantics *semantics;
512
513   /// A binary fraction with an explicit integer bit.
514   ///
515   /// The significand must be at least one bit wider than the target precision.
516   union Significand {
517     integerPart part;
518     integerPart *parts;
519   } significand;
520
521   /// The signed unbiased exponent of the value.
522   exponent_t exponent;
523
524   /// What kind of floating point number this is.
525   ///
526   /// Only 2 bits are required, but VisualStudio incorrectly sign extends it.
527   /// Using the extra bit keeps it from failing under VisualStudio.
528   fltCategory category : 3;
529
530   /// Sign bit of the number.
531   unsigned int sign : 1;
532 };
533
534 /// See friend declaration above.
535 ///
536 /// This additional declaration is required in order to compile LLVM with IBM
537 /// xlC compiler.
538 hash_code hash_value(const APFloat &Arg);
539 } // namespace llvm
540
541 #endif // LLVM_ADT_APFLOAT_H