blob: ed261a4194c9134e4357c11353280c7ff359e980 [file] [log] [blame]
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001//===-- APFloat.cpp - Implement APFloat class -----------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerb39cdde2007-08-20 22:49:32 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements a class to represent arbitrary precision floating
11// point values and provide a variety of arithmetic operations on them.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattner36d26c22007-12-08 19:00:03 +000015#include "llvm/ADT/APFloat.h"
Jeffrey Yasskin3d42bfb2011-07-15 07:04:56 +000016#include "llvm/ADT/APSInt.h"
Ted Kremenek1f801fa2008-02-11 17:24:50 +000017#include "llvm/ADT/FoldingSet.h"
Chandler Carruthed7692a2012-03-04 12:02:57 +000018#include "llvm/ADT/Hashing.h"
19#include "llvm/ADT/StringRef.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000020#include "llvm/Support/ErrorHandling.h"
Dale Johannesend3b51fd2007-08-24 05:08:11 +000021#include "llvm/Support/MathExtras.h"
John McCall8b3f3302010-02-26 22:20:41 +000022#include <limits.h>
Chris Lattnerfad86b02008-08-17 07:19:36 +000023#include <cstring>
Chris Lattnerb39cdde2007-08-20 22:49:32 +000024
25using namespace llvm;
26
27#define convolve(lhs, rhs) ((lhs) * 4 + (rhs))
28
Neil Bootha30b0ee2007-10-03 22:26:02 +000029/* Assumed in hexadecimal significand parsing, and conversion to
30 hexadecimal strings. */
Chris Lattner9f17eb02008-08-17 04:58:58 +000031#define COMPILE_TIME_ASSERT(cond) extern int CTAssert[(cond) ? 1 : -1]
Chris Lattnerb39cdde2007-08-20 22:49:32 +000032COMPILE_TIME_ASSERT(integerPartWidth % 4 == 0);
33
34namespace llvm {
35
36 /* Represents floating point arithmetic semantics. */
37 struct fltSemantics {
38 /* The largest E such that 2^E is representable; this matches the
39 definition of IEEE 754. */
40 exponent_t maxExponent;
41
42 /* The smallest E such that 2^E is a normalized number; this
43 matches the definition of IEEE 754. */
44 exponent_t minExponent;
45
46 /* Number of bits in the significand. This includes the integer
47 bit. */
Neil Booth7a951ca2007-10-12 15:33:27 +000048 unsigned int precision;
Neil Boothcaf19d72007-10-14 10:29:28 +000049
50 /* True if arithmetic is supported. */
51 unsigned int arithmeticOK;
Chris Lattnerb39cdde2007-08-20 22:49:32 +000052 };
53
Chris Lattnercc4287a2009-10-16 02:13:51 +000054 const fltSemantics APFloat::IEEEhalf = { 15, -14, 11, true };
Neil Boothcaf19d72007-10-14 10:29:28 +000055 const fltSemantics APFloat::IEEEsingle = { 127, -126, 24, true };
56 const fltSemantics APFloat::IEEEdouble = { 1023, -1022, 53, true };
57 const fltSemantics APFloat::IEEEquad = { 16383, -16382, 113, true };
58 const fltSemantics APFloat::x87DoubleExtended = { 16383, -16382, 64, true };
59 const fltSemantics APFloat::Bogus = { 0, 0, 0, true };
Dale Johannesena471c2e2007-10-11 18:07:22 +000060
61 // The PowerPC format consists of two doubles. It does not map cleanly
62 // onto the usual format above. For now only storage of constants of
63 // this type is supported, no arithmetic.
Neil Boothcaf19d72007-10-14 10:29:28 +000064 const fltSemantics APFloat::PPCDoubleDouble = { 1023, -1022, 106, false };
Neil Booth96c74712007-10-12 16:02:31 +000065
66 /* A tight upper bound on number of parts required to hold the value
67 pow(5, power) is
68
Neil Booth686700e2007-10-15 15:00:55 +000069 power * 815 / (351 * integerPartWidth) + 1
Dan Gohman16e02092010-03-24 19:38:02 +000070
Neil Booth96c74712007-10-12 16:02:31 +000071 However, whilst the result may require only this many parts,
72 because we are multiplying two values to get it, the
73 multiplication may require an extra part with the excess part
74 being zero (consider the trivial case of 1 * 1, tcFullMultiply
75 requires two parts to hold the single-part result). So we add an
76 extra one to guarantee enough space whilst multiplying. */
77 const unsigned int maxExponent = 16383;
78 const unsigned int maxPrecision = 113;
79 const unsigned int maxPowerOfFiveExponent = maxExponent + maxPrecision - 1;
Neil Booth686700e2007-10-15 15:00:55 +000080 const unsigned int maxPowerOfFiveParts = 2 + ((maxPowerOfFiveExponent * 815)
81 / (351 * integerPartWidth));
Chris Lattnerb39cdde2007-08-20 22:49:32 +000082}
83
Chris Lattnere213f3f2009-03-12 23:59:55 +000084/* A bunch of private, handy routines. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +000085
Chris Lattnere213f3f2009-03-12 23:59:55 +000086static inline unsigned int
87partCountForBits(unsigned int bits)
88{
89 return ((bits) + integerPartWidth - 1) / integerPartWidth;
90}
Chris Lattnerb39cdde2007-08-20 22:49:32 +000091
Chris Lattnere213f3f2009-03-12 23:59:55 +000092/* Returns 0U-9U. Return values >= 10U are not digits. */
93static inline unsigned int
94decDigitValue(unsigned int c)
95{
96 return c - '0';
97}
Chris Lattnerb39cdde2007-08-20 22:49:32 +000098
Chris Lattnere213f3f2009-03-12 23:59:55 +000099static unsigned int
100hexDigitValue(unsigned int c)
101{
102 unsigned int r;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000103
Chris Lattnere213f3f2009-03-12 23:59:55 +0000104 r = c - '0';
Dan Gohman16e02092010-03-24 19:38:02 +0000105 if (r <= 9)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000106 return r;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000107
Chris Lattnere213f3f2009-03-12 23:59:55 +0000108 r = c - 'A';
Dan Gohman16e02092010-03-24 19:38:02 +0000109 if (r <= 5)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000110 return r + 10;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000111
Chris Lattnere213f3f2009-03-12 23:59:55 +0000112 r = c - 'a';
Dan Gohman16e02092010-03-24 19:38:02 +0000113 if (r <= 5)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000114 return r + 10;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000115
Chris Lattnere213f3f2009-03-12 23:59:55 +0000116 return -1U;
117}
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000118
Chris Lattnere213f3f2009-03-12 23:59:55 +0000119static inline void
120assertArithmeticOK(const llvm::fltSemantics &semantics) {
Dan Gohman16e02092010-03-24 19:38:02 +0000121 assert(semantics.arithmeticOK &&
122 "Compile-time arithmetic does not support these semantics");
Chris Lattnere213f3f2009-03-12 23:59:55 +0000123}
Neil Boothcaf19d72007-10-14 10:29:28 +0000124
Chris Lattnere213f3f2009-03-12 23:59:55 +0000125/* Return the value of a decimal exponent of the form
126 [+-]ddddddd.
Neil Booth1870f292007-10-14 10:16:12 +0000127
Chris Lattnere213f3f2009-03-12 23:59:55 +0000128 If the exponent overflows, returns a large exponent with the
129 appropriate sign. */
130static int
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000131readExponent(StringRef::iterator begin, StringRef::iterator end)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000132{
133 bool isNegative;
134 unsigned int absExponent;
135 const unsigned int overlargeExponent = 24000; /* FIXME. */
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000136 StringRef::iterator p = begin;
137
138 assert(p != end && "Exponent has no digits");
Neil Booth1870f292007-10-14 10:16:12 +0000139
Chris Lattnere213f3f2009-03-12 23:59:55 +0000140 isNegative = (*p == '-');
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000141 if (*p == '-' || *p == '+') {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000142 p++;
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000143 assert(p != end && "Exponent has no digits");
144 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000145
Chris Lattnere213f3f2009-03-12 23:59:55 +0000146 absExponent = decDigitValue(*p++);
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000147 assert(absExponent < 10U && "Invalid character in exponent");
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000148
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000149 for (; p != end; ++p) {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000150 unsigned int value;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000151
Chris Lattnere213f3f2009-03-12 23:59:55 +0000152 value = decDigitValue(*p);
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000153 assert(value < 10U && "Invalid character in exponent");
Chris Lattnere213f3f2009-03-12 23:59:55 +0000154
Chris Lattnere213f3f2009-03-12 23:59:55 +0000155 value += absExponent * 10;
156 if (absExponent >= overlargeExponent) {
157 absExponent = overlargeExponent;
Dale Johannesenb1508d12010-08-19 17:58:35 +0000158 p = end; /* outwit assert below */
Chris Lattnere213f3f2009-03-12 23:59:55 +0000159 break;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000160 }
Chris Lattnere213f3f2009-03-12 23:59:55 +0000161 absExponent = value;
162 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000163
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000164 assert(p == end && "Invalid exponent in exponent");
165
Chris Lattnere213f3f2009-03-12 23:59:55 +0000166 if (isNegative)
167 return -(int) absExponent;
168 else
169 return (int) absExponent;
170}
171
172/* This is ugly and needs cleaning up, but I don't immediately see
173 how whilst remaining safe. */
174static int
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000175totalExponent(StringRef::iterator p, StringRef::iterator end,
176 int exponentAdjustment)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000177{
178 int unsignedExponent;
179 bool negative, overflow;
Ted Kremenek584520e2011-01-23 17:05:06 +0000180 int exponent = 0;
Chris Lattnere213f3f2009-03-12 23:59:55 +0000181
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000182 assert(p != end && "Exponent has no digits");
183
Chris Lattnere213f3f2009-03-12 23:59:55 +0000184 negative = *p == '-';
Dan Gohman16e02092010-03-24 19:38:02 +0000185 if (*p == '-' || *p == '+') {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000186 p++;
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000187 assert(p != end && "Exponent has no digits");
188 }
Chris Lattnere213f3f2009-03-12 23:59:55 +0000189
190 unsignedExponent = 0;
191 overflow = false;
Dan Gohman16e02092010-03-24 19:38:02 +0000192 for (; p != end; ++p) {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000193 unsigned int value;
194
195 value = decDigitValue(*p);
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000196 assert(value < 10U && "Invalid character in exponent");
Chris Lattnere213f3f2009-03-12 23:59:55 +0000197
Chris Lattnere213f3f2009-03-12 23:59:55 +0000198 unsignedExponent = unsignedExponent * 10 + value;
Abramo Bagnara4bb46f42011-01-06 16:55:14 +0000199 if (unsignedExponent > 32767)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000200 overflow = true;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000201 }
202
Abramo Bagnara4bb46f42011-01-06 16:55:14 +0000203 if (exponentAdjustment > 32767 || exponentAdjustment < -32768)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000204 overflow = true;
205
Dan Gohman16e02092010-03-24 19:38:02 +0000206 if (!overflow) {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000207 exponent = unsignedExponent;
Dan Gohman16e02092010-03-24 19:38:02 +0000208 if (negative)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000209 exponent = -exponent;
210 exponent += exponentAdjustment;
Abramo Bagnara4bb46f42011-01-06 16:55:14 +0000211 if (exponent > 32767 || exponent < -32768)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000212 overflow = true;
213 }
214
Dan Gohman16e02092010-03-24 19:38:02 +0000215 if (overflow)
Abramo Bagnara4bb46f42011-01-06 16:55:14 +0000216 exponent = negative ? -32768: 32767;
Chris Lattnere213f3f2009-03-12 23:59:55 +0000217
218 return exponent;
219}
220
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000221static StringRef::iterator
222skipLeadingZeroesAndAnyDot(StringRef::iterator begin, StringRef::iterator end,
223 StringRef::iterator *dot)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000224{
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000225 StringRef::iterator p = begin;
226 *dot = end;
Dan Gohman16e02092010-03-24 19:38:02 +0000227 while (*p == '0' && p != end)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000228 p++;
229
Dan Gohman16e02092010-03-24 19:38:02 +0000230 if (*p == '.') {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000231 *dot = p++;
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000232
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000233 assert(end - begin != 1 && "Significand has no digits");
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000234
Dan Gohman16e02092010-03-24 19:38:02 +0000235 while (*p == '0' && p != end)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000236 p++;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000237 }
238
Chris Lattnere213f3f2009-03-12 23:59:55 +0000239 return p;
240}
Neil Booth1870f292007-10-14 10:16:12 +0000241
Chris Lattnere213f3f2009-03-12 23:59:55 +0000242/* Given a normal decimal floating point number of the form
Neil Booth1870f292007-10-14 10:16:12 +0000243
Chris Lattnere213f3f2009-03-12 23:59:55 +0000244 dddd.dddd[eE][+-]ddd
Neil Booth686700e2007-10-15 15:00:55 +0000245
Chris Lattnere213f3f2009-03-12 23:59:55 +0000246 where the decimal point and exponent are optional, fill out the
247 structure D. Exponent is appropriate if the significand is
248 treated as an integer, and normalizedExponent if the significand
249 is taken to have the decimal point after a single leading
250 non-zero digit.
Neil Booth1870f292007-10-14 10:16:12 +0000251
Chris Lattnere213f3f2009-03-12 23:59:55 +0000252 If the value is zero, V->firstSigDigit points to a non-digit, and
253 the return exponent is zero.
254*/
255struct decimalInfo {
256 const char *firstSigDigit;
257 const char *lastSigDigit;
258 int exponent;
259 int normalizedExponent;
260};
Neil Booth1870f292007-10-14 10:16:12 +0000261
Chris Lattnere213f3f2009-03-12 23:59:55 +0000262static void
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000263interpretDecimal(StringRef::iterator begin, StringRef::iterator end,
264 decimalInfo *D)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000265{
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000266 StringRef::iterator dot = end;
267 StringRef::iterator p = skipLeadingZeroesAndAnyDot (begin, end, &dot);
Neil Booth1870f292007-10-14 10:16:12 +0000268
Chris Lattnere213f3f2009-03-12 23:59:55 +0000269 D->firstSigDigit = p;
270 D->exponent = 0;
271 D->normalizedExponent = 0;
272
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000273 for (; p != end; ++p) {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000274 if (*p == '.') {
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000275 assert(dot == end && "String contains multiple dots");
Chris Lattnere213f3f2009-03-12 23:59:55 +0000276 dot = p++;
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000277 if (p == end)
278 break;
Neil Booth1870f292007-10-14 10:16:12 +0000279 }
Chris Lattnere213f3f2009-03-12 23:59:55 +0000280 if (decDigitValue(*p) >= 10U)
281 break;
Chris Lattnere213f3f2009-03-12 23:59:55 +0000282 }
Neil Booth1870f292007-10-14 10:16:12 +0000283
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000284 if (p != end) {
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000285 assert((*p == 'e' || *p == 'E') && "Invalid character in significand");
286 assert(p != begin && "Significand has no digits");
287 assert((dot == end || p - begin != 1) && "Significand has no digits");
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000288
289 /* p points to the first non-digit in the string */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000290 D->exponent = readExponent(p + 1, end);
Neil Booth1870f292007-10-14 10:16:12 +0000291
Chris Lattnere213f3f2009-03-12 23:59:55 +0000292 /* Implied decimal point? */
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000293 if (dot == end)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000294 dot = p;
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000295 }
Neil Booth1870f292007-10-14 10:16:12 +0000296
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000297 /* If number is all zeroes accept any exponent. */
298 if (p != D->firstSigDigit) {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000299 /* Drop insignificant trailing zeroes. */
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000300 if (p != begin) {
Neil Booth1870f292007-10-14 10:16:12 +0000301 do
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000302 do
303 p--;
304 while (p != begin && *p == '0');
305 while (p != begin && *p == '.');
306 }
Neil Booth1870f292007-10-14 10:16:12 +0000307
Chris Lattnere213f3f2009-03-12 23:59:55 +0000308 /* Adjust the exponents for any decimal point. */
309 D->exponent += static_cast<exponent_t>((dot - p) - (dot > p));
310 D->normalizedExponent = (D->exponent +
311 static_cast<exponent_t>((p - D->firstSigDigit)
312 - (dot > D->firstSigDigit && dot < p)));
Neil Booth1870f292007-10-14 10:16:12 +0000313 }
314
Chris Lattnere213f3f2009-03-12 23:59:55 +0000315 D->lastSigDigit = p;
316}
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000317
Chris Lattnere213f3f2009-03-12 23:59:55 +0000318/* Return the trailing fraction of a hexadecimal number.
319 DIGITVALUE is the first hex digit of the fraction, P points to
320 the next digit. */
321static lostFraction
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000322trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end,
323 unsigned int digitValue)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000324{
325 unsigned int hexDigit;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000326
Chris Lattnere213f3f2009-03-12 23:59:55 +0000327 /* If the first trailing digit isn't 0 or 8 we can work out the
328 fraction immediately. */
Dan Gohman16e02092010-03-24 19:38:02 +0000329 if (digitValue > 8)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000330 return lfMoreThanHalf;
Dan Gohman16e02092010-03-24 19:38:02 +0000331 else if (digitValue < 8 && digitValue > 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000332 return lfLessThanHalf;
Chris Lattnere213f3f2009-03-12 23:59:55 +0000333
334 /* Otherwise we need to find the first non-zero digit. */
Dan Gohman16e02092010-03-24 19:38:02 +0000335 while (*p == '0')
Chris Lattnere213f3f2009-03-12 23:59:55 +0000336 p++;
337
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000338 assert(p != end && "Invalid trailing hexadecimal fraction!");
339
Chris Lattnere213f3f2009-03-12 23:59:55 +0000340 hexDigit = hexDigitValue(*p);
341
342 /* If we ran off the end it is exactly zero or one-half, otherwise
343 a little more. */
Dan Gohman16e02092010-03-24 19:38:02 +0000344 if (hexDigit == -1U)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000345 return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
346 else
347 return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf;
348}
349
350/* Return the fraction lost were a bignum truncated losing the least
351 significant BITS bits. */
352static lostFraction
353lostFractionThroughTruncation(const integerPart *parts,
354 unsigned int partCount,
355 unsigned int bits)
356{
357 unsigned int lsb;
358
359 lsb = APInt::tcLSB(parts, partCount);
360
361 /* Note this is guaranteed true if bits == 0, or LSB == -1U. */
Dan Gohman16e02092010-03-24 19:38:02 +0000362 if (bits <= lsb)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000363 return lfExactlyZero;
Dan Gohman16e02092010-03-24 19:38:02 +0000364 if (bits == lsb + 1)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000365 return lfExactlyHalf;
Dan Gohman16e02092010-03-24 19:38:02 +0000366 if (bits <= partCount * integerPartWidth &&
367 APInt::tcExtractBit(parts, bits - 1))
Chris Lattnere213f3f2009-03-12 23:59:55 +0000368 return lfMoreThanHalf;
369
370 return lfLessThanHalf;
371}
372
373/* Shift DST right BITS bits noting lost fraction. */
374static lostFraction
375shiftRight(integerPart *dst, unsigned int parts, unsigned int bits)
376{
377 lostFraction lost_fraction;
378
379 lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
380
381 APInt::tcShiftRight(dst, parts, bits);
382
383 return lost_fraction;
384}
385
386/* Combine the effect of two lost fractions. */
387static lostFraction
388combineLostFractions(lostFraction moreSignificant,
389 lostFraction lessSignificant)
390{
Dan Gohman16e02092010-03-24 19:38:02 +0000391 if (lessSignificant != lfExactlyZero) {
392 if (moreSignificant == lfExactlyZero)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000393 moreSignificant = lfLessThanHalf;
Dan Gohman16e02092010-03-24 19:38:02 +0000394 else if (moreSignificant == lfExactlyHalf)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000395 moreSignificant = lfMoreThanHalf;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000396 }
397
Chris Lattnere213f3f2009-03-12 23:59:55 +0000398 return moreSignificant;
399}
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000400
Chris Lattnere213f3f2009-03-12 23:59:55 +0000401/* The error from the true value, in half-ulps, on multiplying two
402 floating point numbers, which differ from the value they
403 approximate by at most HUE1 and HUE2 half-ulps, is strictly less
404 than the returned value.
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000405
Chris Lattnere213f3f2009-03-12 23:59:55 +0000406 See "How to Read Floating Point Numbers Accurately" by William D
407 Clinger. */
408static unsigned int
409HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
410{
411 assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000412
Chris Lattnere213f3f2009-03-12 23:59:55 +0000413 if (HUerr1 + HUerr2 == 0)
414 return inexactMultiply * 2; /* <= inexactMultiply half-ulps. */
415 else
416 return inexactMultiply + 2 * (HUerr1 + HUerr2);
417}
Neil Bootha30b0ee2007-10-03 22:26:02 +0000418
Chris Lattnere213f3f2009-03-12 23:59:55 +0000419/* The number of ulps from the boundary (zero, or half if ISNEAREST)
420 when the least significant BITS are truncated. BITS cannot be
421 zero. */
422static integerPart
423ulpsFromBoundary(const integerPart *parts, unsigned int bits, bool isNearest)
424{
425 unsigned int count, partBits;
426 integerPart part, boundary;
Neil Booth33d4c922007-10-07 08:51:21 +0000427
Evan Cheng99ebfa52009-10-27 21:35:42 +0000428 assert(bits != 0);
Neil Bootha30b0ee2007-10-03 22:26:02 +0000429
Chris Lattnere213f3f2009-03-12 23:59:55 +0000430 bits--;
431 count = bits / integerPartWidth;
432 partBits = bits % integerPartWidth + 1;
Neil Booth96c74712007-10-12 16:02:31 +0000433
Chris Lattnere213f3f2009-03-12 23:59:55 +0000434 part = parts[count] & (~(integerPart) 0 >> (integerPartWidth - partBits));
Neil Booth96c74712007-10-12 16:02:31 +0000435
Chris Lattnere213f3f2009-03-12 23:59:55 +0000436 if (isNearest)
437 boundary = (integerPart) 1 << (partBits - 1);
438 else
439 boundary = 0;
440
441 if (count == 0) {
442 if (part - boundary <= boundary - part)
443 return part - boundary;
Neil Booth96c74712007-10-12 16:02:31 +0000444 else
Chris Lattnere213f3f2009-03-12 23:59:55 +0000445 return boundary - part;
Neil Booth96c74712007-10-12 16:02:31 +0000446 }
447
Chris Lattnere213f3f2009-03-12 23:59:55 +0000448 if (part == boundary) {
449 while (--count)
450 if (parts[count])
451 return ~(integerPart) 0; /* A lot. */
Neil Booth96c74712007-10-12 16:02:31 +0000452
Chris Lattnere213f3f2009-03-12 23:59:55 +0000453 return parts[0];
454 } else if (part == boundary - 1) {
455 while (--count)
456 if (~parts[count])
457 return ~(integerPart) 0; /* A lot. */
Neil Booth96c74712007-10-12 16:02:31 +0000458
Chris Lattnere213f3f2009-03-12 23:59:55 +0000459 return -parts[0];
460 }
Neil Booth96c74712007-10-12 16:02:31 +0000461
Chris Lattnere213f3f2009-03-12 23:59:55 +0000462 return ~(integerPart) 0; /* A lot. */
463}
Neil Booth96c74712007-10-12 16:02:31 +0000464
Chris Lattnere213f3f2009-03-12 23:59:55 +0000465/* Place pow(5, power) in DST, and return the number of parts used.
466 DST must be at least one part larger than size of the answer. */
467static unsigned int
468powerOf5(integerPart *dst, unsigned int power)
469{
470 static const integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125,
471 15625, 78125 };
Chris Lattneree167a72009-03-13 00:24:01 +0000472 integerPart pow5s[maxPowerOfFiveParts * 2 + 5];
473 pow5s[0] = 78125 * 5;
Dan Gohman16e02092010-03-24 19:38:02 +0000474
Chris Lattner807926a2009-03-13 00:03:51 +0000475 unsigned int partsCount[16] = { 1 };
Chris Lattnere213f3f2009-03-12 23:59:55 +0000476 integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5;
477 unsigned int result;
Chris Lattnere213f3f2009-03-12 23:59:55 +0000478 assert(power <= maxExponent);
479
480 p1 = dst;
481 p2 = scratch;
482
483 *p1 = firstEightPowers[power & 7];
484 power >>= 3;
485
486 result = 1;
487 pow5 = pow5s;
488
489 for (unsigned int n = 0; power; power >>= 1, n++) {
490 unsigned int pc;
491
492 pc = partsCount[n];
493
494 /* Calculate pow(5,pow(2,n+3)) if we haven't yet. */
495 if (pc == 0) {
496 pc = partsCount[n - 1];
497 APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc);
498 pc *= 2;
499 if (pow5[pc - 1] == 0)
500 pc--;
501 partsCount[n] = pc;
Neil Booth96c74712007-10-12 16:02:31 +0000502 }
503
Chris Lattnere213f3f2009-03-12 23:59:55 +0000504 if (power & 1) {
505 integerPart *tmp;
Neil Booth96c74712007-10-12 16:02:31 +0000506
Chris Lattnere213f3f2009-03-12 23:59:55 +0000507 APInt::tcFullMultiply(p2, p1, pow5, result, pc);
508 result += pc;
509 if (p2[result - 1] == 0)
510 result--;
Neil Booth96c74712007-10-12 16:02:31 +0000511
Chris Lattnere213f3f2009-03-12 23:59:55 +0000512 /* Now result is in p1 with partsCount parts and p2 is scratch
513 space. */
514 tmp = p1, p1 = p2, p2 = tmp;
Neil Booth96c74712007-10-12 16:02:31 +0000515 }
516
Chris Lattnere213f3f2009-03-12 23:59:55 +0000517 pow5 += pc;
Neil Booth96c74712007-10-12 16:02:31 +0000518 }
519
Chris Lattnere213f3f2009-03-12 23:59:55 +0000520 if (p1 != dst)
521 APInt::tcAssign(dst, p1, result);
Neil Booth96c74712007-10-12 16:02:31 +0000522
Chris Lattnere213f3f2009-03-12 23:59:55 +0000523 return result;
524}
Neil Booth96c74712007-10-12 16:02:31 +0000525
Chris Lattnere213f3f2009-03-12 23:59:55 +0000526/* Zero at the end to avoid modular arithmetic when adding one; used
527 when rounding up during hexadecimal output. */
528static const char hexDigitsLower[] = "0123456789abcdef0";
529static const char hexDigitsUpper[] = "0123456789ABCDEF0";
530static const char infinityL[] = "infinity";
531static const char infinityU[] = "INFINITY";
532static const char NaNL[] = "nan";
533static const char NaNU[] = "NAN";
Neil Booth96c74712007-10-12 16:02:31 +0000534
Chris Lattnere213f3f2009-03-12 23:59:55 +0000535/* Write out an integerPart in hexadecimal, starting with the most
536 significant nibble. Write out exactly COUNT hexdigits, return
537 COUNT. */
538static unsigned int
539partAsHex (char *dst, integerPart part, unsigned int count,
540 const char *hexDigitChars)
541{
542 unsigned int result = count;
Neil Booth96c74712007-10-12 16:02:31 +0000543
Evan Cheng99ebfa52009-10-27 21:35:42 +0000544 assert(count != 0 && count <= integerPartWidth / 4);
Neil Booth96c74712007-10-12 16:02:31 +0000545
Chris Lattnere213f3f2009-03-12 23:59:55 +0000546 part >>= (integerPartWidth - 4 * count);
547 while (count--) {
548 dst[count] = hexDigitChars[part & 0xf];
549 part >>= 4;
Neil Booth96c74712007-10-12 16:02:31 +0000550 }
551
Chris Lattnere213f3f2009-03-12 23:59:55 +0000552 return result;
553}
Neil Bootha30b0ee2007-10-03 22:26:02 +0000554
Chris Lattnere213f3f2009-03-12 23:59:55 +0000555/* Write out an unsigned decimal integer. */
556static char *
557writeUnsignedDecimal (char *dst, unsigned int n)
558{
559 char buff[40], *p;
Neil Bootha30b0ee2007-10-03 22:26:02 +0000560
Chris Lattnere213f3f2009-03-12 23:59:55 +0000561 p = buff;
562 do
563 *p++ = '0' + n % 10;
564 while (n /= 10);
Neil Bootha30b0ee2007-10-03 22:26:02 +0000565
Chris Lattnere213f3f2009-03-12 23:59:55 +0000566 do
567 *dst++ = *--p;
568 while (p != buff);
Neil Bootha30b0ee2007-10-03 22:26:02 +0000569
Chris Lattnere213f3f2009-03-12 23:59:55 +0000570 return dst;
571}
Neil Bootha30b0ee2007-10-03 22:26:02 +0000572
Chris Lattnere213f3f2009-03-12 23:59:55 +0000573/* Write out a signed decimal integer. */
574static char *
575writeSignedDecimal (char *dst, int value)
576{
577 if (value < 0) {
578 *dst++ = '-';
579 dst = writeUnsignedDecimal(dst, -(unsigned) value);
580 } else
581 dst = writeUnsignedDecimal(dst, value);
Neil Bootha30b0ee2007-10-03 22:26:02 +0000582
Chris Lattnere213f3f2009-03-12 23:59:55 +0000583 return dst;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000584}
585
586/* Constructors. */
587void
588APFloat::initialize(const fltSemantics *ourSemantics)
589{
590 unsigned int count;
591
592 semantics = ourSemantics;
593 count = partCount();
Dan Gohman16e02092010-03-24 19:38:02 +0000594 if (count > 1)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000595 significand.parts = new integerPart[count];
596}
597
598void
599APFloat::freeSignificand()
600{
Dan Gohman16e02092010-03-24 19:38:02 +0000601 if (partCount() > 1)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000602 delete [] significand.parts;
603}
604
605void
606APFloat::assign(const APFloat &rhs)
607{
608 assert(semantics == rhs.semantics);
609
610 sign = rhs.sign;
611 category = rhs.category;
612 exponent = rhs.exponent;
Dale Johannesena471c2e2007-10-11 18:07:22 +0000613 sign2 = rhs.sign2;
614 exponent2 = rhs.exponent2;
Dan Gohman16e02092010-03-24 19:38:02 +0000615 if (category == fcNormal || category == fcNaN)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000616 copySignificand(rhs);
617}
618
619void
620APFloat::copySignificand(const APFloat &rhs)
621{
Dale Johanneseneaf08942007-08-31 04:03:46 +0000622 assert(category == fcNormal || category == fcNaN);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000623 assert(rhs.partCount() >= partCount());
624
625 APInt::tcAssign(significandParts(), rhs.significandParts(),
Neil Booth4f881702007-09-26 21:33:42 +0000626 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000627}
628
Neil Boothe5e01942007-10-14 10:39:51 +0000629/* Make this number a NaN, with an arbitrary but deterministic value
Dale Johannesen541ed9f2009-01-21 20:32:55 +0000630 for the significand. If double or longer, this is a signalling NaN,
Mike Stumpc5ca7132009-05-30 03:49:43 +0000631 which may not be ideal. If float, this is QNaN(0). */
John McCalle12b7382010-02-28 02:51:25 +0000632void APFloat::makeNaN(bool SNaN, bool Negative, const APInt *fill)
Neil Boothe5e01942007-10-14 10:39:51 +0000633{
634 category = fcNaN;
John McCalle12b7382010-02-28 02:51:25 +0000635 sign = Negative;
636
John McCall165e96b2010-02-28 12:49:50 +0000637 integerPart *significand = significandParts();
638 unsigned numParts = partCount();
639
John McCalle12b7382010-02-28 02:51:25 +0000640 // Set the significand bits to the fill.
John McCall165e96b2010-02-28 12:49:50 +0000641 if (!fill || fill->getNumWords() < numParts)
642 APInt::tcSet(significand, 0, numParts);
643 if (fill) {
John McCalld44c6cc2010-03-01 18:38:45 +0000644 APInt::tcAssign(significand, fill->getRawData(),
645 std::min(fill->getNumWords(), numParts));
John McCall165e96b2010-02-28 12:49:50 +0000646
647 // Zero out the excess bits of the significand.
648 unsigned bitsToPreserve = semantics->precision - 1;
649 unsigned part = bitsToPreserve / 64;
650 bitsToPreserve %= 64;
651 significand[part] &= ((1ULL << bitsToPreserve) - 1);
652 for (part++; part != numParts; ++part)
653 significand[part] = 0;
654 }
655
656 unsigned QNaNBit = semantics->precision - 2;
John McCalle12b7382010-02-28 02:51:25 +0000657
658 if (SNaN) {
659 // We always have to clear the QNaN bit to make it an SNaN.
John McCall165e96b2010-02-28 12:49:50 +0000660 APInt::tcClearBit(significand, QNaNBit);
John McCalle12b7382010-02-28 02:51:25 +0000661
662 // If there are no bits set in the payload, we have to set
663 // *something* to make it a NaN instead of an infinity;
664 // conventionally, this is the next bit down from the QNaN bit.
John McCall165e96b2010-02-28 12:49:50 +0000665 if (APInt::tcIsZero(significand, numParts))
666 APInt::tcSetBit(significand, QNaNBit - 1);
John McCalle12b7382010-02-28 02:51:25 +0000667 } else {
668 // We always have to set the QNaN bit to make it a QNaN.
John McCall165e96b2010-02-28 12:49:50 +0000669 APInt::tcSetBit(significand, QNaNBit);
John McCalle12b7382010-02-28 02:51:25 +0000670 }
John McCall165e96b2010-02-28 12:49:50 +0000671
672 // For x87 extended precision, we want to make a NaN, not a
673 // pseudo-NaN. Maybe we should expose the ability to make
674 // pseudo-NaNs?
675 if (semantics == &APFloat::x87DoubleExtended)
676 APInt::tcSetBit(significand, QNaNBit + 1);
John McCalle12b7382010-02-28 02:51:25 +0000677}
678
679APFloat APFloat::makeNaN(const fltSemantics &Sem, bool SNaN, bool Negative,
680 const APInt *fill) {
681 APFloat value(Sem, uninitialized);
682 value.makeNaN(SNaN, Negative, fill);
683 return value;
Neil Boothe5e01942007-10-14 10:39:51 +0000684}
685
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000686APFloat &
687APFloat::operator=(const APFloat &rhs)
688{
Dan Gohman16e02092010-03-24 19:38:02 +0000689 if (this != &rhs) {
690 if (semantics != rhs.semantics) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000691 freeSignificand();
692 initialize(rhs.semantics);
693 }
694 assign(rhs);
695 }
696
697 return *this;
698}
699
Dale Johannesen343e7702007-08-24 00:56:33 +0000700bool
Dale Johannesen12595d72007-08-24 22:09:56 +0000701APFloat::bitwiseIsEqual(const APFloat &rhs) const {
Dale Johannesen343e7702007-08-24 00:56:33 +0000702 if (this == &rhs)
703 return true;
704 if (semantics != rhs.semantics ||
Dale Johanneseneaf08942007-08-31 04:03:46 +0000705 category != rhs.category ||
706 sign != rhs.sign)
Dale Johannesen343e7702007-08-24 00:56:33 +0000707 return false;
Dan Gohmanb10abe12008-01-29 12:08:20 +0000708 if (semantics==(const llvm::fltSemantics*)&PPCDoubleDouble &&
Dale Johannesena471c2e2007-10-11 18:07:22 +0000709 sign2 != rhs.sign2)
710 return false;
Dale Johanneseneaf08942007-08-31 04:03:46 +0000711 if (category==fcZero || category==fcInfinity)
Dale Johannesen343e7702007-08-24 00:56:33 +0000712 return true;
Dale Johanneseneaf08942007-08-31 04:03:46 +0000713 else if (category==fcNormal && exponent!=rhs.exponent)
714 return false;
Dan Gohmanb10abe12008-01-29 12:08:20 +0000715 else if (semantics==(const llvm::fltSemantics*)&PPCDoubleDouble &&
Dale Johannesena471c2e2007-10-11 18:07:22 +0000716 exponent2!=rhs.exponent2)
717 return false;
Dale Johannesen343e7702007-08-24 00:56:33 +0000718 else {
Dale Johannesen343e7702007-08-24 00:56:33 +0000719 int i= partCount();
720 const integerPart* p=significandParts();
721 const integerPart* q=rhs.significandParts();
722 for (; i>0; i--, p++, q++) {
723 if (*p != *q)
724 return false;
725 }
726 return true;
727 }
728}
729
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000730APFloat::APFloat(const fltSemantics &ourSemantics, integerPart value)
Bill Wendlingf09a8b52011-03-18 09:09:44 +0000731 : exponent2(0), sign2(0) {
Neil Boothcaf19d72007-10-14 10:29:28 +0000732 assertArithmeticOK(ourSemantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000733 initialize(&ourSemantics);
734 sign = 0;
735 zeroSignificand();
736 exponent = ourSemantics.precision - 1;
737 significandParts()[0] = value;
738 normalize(rmNearestTiesToEven, lfExactlyZero);
739}
740
Bill Wendlingf09a8b52011-03-18 09:09:44 +0000741APFloat::APFloat(const fltSemantics &ourSemantics) : exponent2(0), sign2(0) {
Chris Lattnerd7bd78e2009-09-17 01:08:43 +0000742 assertArithmeticOK(ourSemantics);
743 initialize(&ourSemantics);
744 category = fcZero;
745 sign = false;
746}
747
Bill Wendlingf09a8b52011-03-18 09:09:44 +0000748APFloat::APFloat(const fltSemantics &ourSemantics, uninitializedTag tag)
749 : exponent2(0), sign2(0) {
John McCalle12b7382010-02-28 02:51:25 +0000750 assertArithmeticOK(ourSemantics);
751 // Allocates storage if necessary but does not initialize it.
752 initialize(&ourSemantics);
753}
Chris Lattnerd7bd78e2009-09-17 01:08:43 +0000754
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000755APFloat::APFloat(const fltSemantics &ourSemantics,
John McCalle12b7382010-02-28 02:51:25 +0000756 fltCategory ourCategory, bool negative)
Bill Wendlingf09a8b52011-03-18 09:09:44 +0000757 : exponent2(0), sign2(0) {
Neil Boothcaf19d72007-10-14 10:29:28 +0000758 assertArithmeticOK(ourSemantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000759 initialize(&ourSemantics);
760 category = ourCategory;
761 sign = negative;
Mike Stumpc5ca7132009-05-30 03:49:43 +0000762 if (category == fcNormal)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000763 category = fcZero;
Neil Boothe5e01942007-10-14 10:39:51 +0000764 else if (ourCategory == fcNaN)
John McCalle12b7382010-02-28 02:51:25 +0000765 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000766}
767
Benjamin Kramer38e59892010-07-14 22:38:02 +0000768APFloat::APFloat(const fltSemantics &ourSemantics, StringRef text)
Bill Wendlingf09a8b52011-03-18 09:09:44 +0000769 : exponent2(0), sign2(0) {
Neil Boothcaf19d72007-10-14 10:29:28 +0000770 assertArithmeticOK(ourSemantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000771 initialize(&ourSemantics);
772 convertFromString(text, rmNearestTiesToEven);
773}
774
Bill Wendlingf09a8b52011-03-18 09:09:44 +0000775APFloat::APFloat(const APFloat &rhs) : exponent2(0), sign2(0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000776 initialize(rhs.semantics);
777 assign(rhs);
778}
779
780APFloat::~APFloat()
781{
782 freeSignificand();
783}
784
Ted Kremenek1f801fa2008-02-11 17:24:50 +0000785// Profile - This method 'profiles' an APFloat for use with FoldingSet.
786void APFloat::Profile(FoldingSetNodeID& ID) const {
Dale Johannesen7111b022008-10-09 18:53:47 +0000787 ID.Add(bitcastToAPInt());
Ted Kremenek1f801fa2008-02-11 17:24:50 +0000788}
789
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000790unsigned int
791APFloat::partCount() const
792{
Dale Johannesena72a5a02007-09-20 23:47:58 +0000793 return partCountForBits(semantics->precision + 1);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000794}
795
796unsigned int
797APFloat::semanticsPrecision(const fltSemantics &semantics)
798{
799 return semantics.precision;
800}
801
802const integerPart *
803APFloat::significandParts() const
804{
805 return const_cast<APFloat *>(this)->significandParts();
806}
807
808integerPart *
809APFloat::significandParts()
810{
Dale Johanneseneaf08942007-08-31 04:03:46 +0000811 assert(category == fcNormal || category == fcNaN);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000812
Evan Cheng99ebfa52009-10-27 21:35:42 +0000813 if (partCount() > 1)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000814 return significand.parts;
815 else
816 return &significand.part;
817}
818
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000819void
820APFloat::zeroSignificand()
821{
822 category = fcNormal;
823 APInt::tcSet(significandParts(), 0, partCount());
824}
825
826/* Increment an fcNormal floating point number's significand. */
827void
828APFloat::incrementSignificand()
829{
830 integerPart carry;
831
832 carry = APInt::tcIncrement(significandParts(), partCount());
833
834 /* Our callers should never cause us to overflow. */
835 assert(carry == 0);
Duncan Sands1f6a3292011-08-12 14:54:45 +0000836 (void)carry;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000837}
838
839/* Add the significand of the RHS. Returns the carry flag. */
840integerPart
841APFloat::addSignificand(const APFloat &rhs)
842{
843 integerPart *parts;
844
845 parts = significandParts();
846
847 assert(semantics == rhs.semantics);
848 assert(exponent == rhs.exponent);
849
850 return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
851}
852
853/* Subtract the significand of the RHS with a borrow flag. Returns
854 the borrow flag. */
855integerPart
856APFloat::subtractSignificand(const APFloat &rhs, integerPart borrow)
857{
858 integerPart *parts;
859
860 parts = significandParts();
861
862 assert(semantics == rhs.semantics);
863 assert(exponent == rhs.exponent);
864
865 return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
Neil Booth4f881702007-09-26 21:33:42 +0000866 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000867}
868
869/* Multiply the significand of the RHS. If ADDEND is non-NULL, add it
870 on to the full-precision result of the multiplication. Returns the
871 lost fraction. */
872lostFraction
873APFloat::multiplySignificand(const APFloat &rhs, const APFloat *addend)
874{
Neil Booth4f881702007-09-26 21:33:42 +0000875 unsigned int omsb; // One, not zero, based MSB.
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000876 unsigned int partsCount, newPartsCount, precision;
877 integerPart *lhsSignificand;
878 integerPart scratch[4];
879 integerPart *fullSignificand;
880 lostFraction lost_fraction;
Dale Johannesen23a98552008-10-09 23:00:39 +0000881 bool ignored;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000882
883 assert(semantics == rhs.semantics);
884
885 precision = semantics->precision;
886 newPartsCount = partCountForBits(precision * 2);
887
Dan Gohman16e02092010-03-24 19:38:02 +0000888 if (newPartsCount > 4)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000889 fullSignificand = new integerPart[newPartsCount];
890 else
891 fullSignificand = scratch;
892
893 lhsSignificand = significandParts();
894 partsCount = partCount();
895
896 APInt::tcFullMultiply(fullSignificand, lhsSignificand,
Neil Booth978661d2007-10-06 00:24:48 +0000897 rhs.significandParts(), partsCount, partsCount);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000898
899 lost_fraction = lfExactlyZero;
900 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
901 exponent += rhs.exponent;
902
Dan Gohman16e02092010-03-24 19:38:02 +0000903 if (addend) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000904 Significand savedSignificand = significand;
905 const fltSemantics *savedSemantics = semantics;
906 fltSemantics extendedSemantics;
907 opStatus status;
908 unsigned int extendedPrecision;
909
910 /* Normalize our MSB. */
911 extendedPrecision = precision + precision - 1;
Dan Gohman16e02092010-03-24 19:38:02 +0000912 if (omsb != extendedPrecision) {
913 APInt::tcShiftLeft(fullSignificand, newPartsCount,
914 extendedPrecision - omsb);
915 exponent -= extendedPrecision - omsb;
916 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000917
918 /* Create new semantics. */
919 extendedSemantics = *semantics;
920 extendedSemantics.precision = extendedPrecision;
921
Dan Gohman16e02092010-03-24 19:38:02 +0000922 if (newPartsCount == 1)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000923 significand.part = fullSignificand[0];
924 else
925 significand.parts = fullSignificand;
926 semantics = &extendedSemantics;
927
928 APFloat extendedAddend(*addend);
Dale Johannesen23a98552008-10-09 23:00:39 +0000929 status = extendedAddend.convert(extendedSemantics, rmTowardZero, &ignored);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000930 assert(status == opOK);
Duncan Sands1f6a3292011-08-12 14:54:45 +0000931 (void)status;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000932 lost_fraction = addOrSubtractSignificand(extendedAddend, false);
933
934 /* Restore our state. */
Dan Gohman16e02092010-03-24 19:38:02 +0000935 if (newPartsCount == 1)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000936 fullSignificand[0] = significand.part;
937 significand = savedSignificand;
938 semantics = savedSemantics;
939
940 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
941 }
942
943 exponent -= (precision - 1);
944
Dan Gohman16e02092010-03-24 19:38:02 +0000945 if (omsb > precision) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000946 unsigned int bits, significantParts;
947 lostFraction lf;
948
949 bits = omsb - precision;
950 significantParts = partCountForBits(omsb);
951 lf = shiftRight(fullSignificand, significantParts, bits);
952 lost_fraction = combineLostFractions(lf, lost_fraction);
953 exponent += bits;
954 }
955
956 APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
957
Dan Gohman16e02092010-03-24 19:38:02 +0000958 if (newPartsCount > 4)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000959 delete [] fullSignificand;
960
961 return lost_fraction;
962}
963
964/* Multiply the significands of LHS and RHS to DST. */
965lostFraction
966APFloat::divideSignificand(const APFloat &rhs)
967{
968 unsigned int bit, i, partsCount;
969 const integerPart *rhsSignificand;
970 integerPart *lhsSignificand, *dividend, *divisor;
971 integerPart scratch[4];
972 lostFraction lost_fraction;
973
974 assert(semantics == rhs.semantics);
975
976 lhsSignificand = significandParts();
977 rhsSignificand = rhs.significandParts();
978 partsCount = partCount();
979
Dan Gohman16e02092010-03-24 19:38:02 +0000980 if (partsCount > 2)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000981 dividend = new integerPart[partsCount * 2];
982 else
983 dividend = scratch;
984
985 divisor = dividend + partsCount;
986
987 /* Copy the dividend and divisor as they will be modified in-place. */
Dan Gohman16e02092010-03-24 19:38:02 +0000988 for (i = 0; i < partsCount; i++) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000989 dividend[i] = lhsSignificand[i];
990 divisor[i] = rhsSignificand[i];
991 lhsSignificand[i] = 0;
992 }
993
994 exponent -= rhs.exponent;
995
996 unsigned int precision = semantics->precision;
997
998 /* Normalize the divisor. */
999 bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
Dan Gohman16e02092010-03-24 19:38:02 +00001000 if (bit) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001001 exponent += bit;
1002 APInt::tcShiftLeft(divisor, partsCount, bit);
1003 }
1004
1005 /* Normalize the dividend. */
1006 bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
Dan Gohman16e02092010-03-24 19:38:02 +00001007 if (bit) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001008 exponent -= bit;
1009 APInt::tcShiftLeft(dividend, partsCount, bit);
1010 }
1011
Neil Booth96c74712007-10-12 16:02:31 +00001012 /* Ensure the dividend >= divisor initially for the loop below.
1013 Incidentally, this means that the division loop below is
1014 guaranteed to set the integer bit to one. */
Dan Gohman16e02092010-03-24 19:38:02 +00001015 if (APInt::tcCompare(dividend, divisor, partsCount) < 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001016 exponent--;
1017 APInt::tcShiftLeft(dividend, partsCount, 1);
1018 assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
1019 }
1020
1021 /* Long division. */
Dan Gohman16e02092010-03-24 19:38:02 +00001022 for (bit = precision; bit; bit -= 1) {
1023 if (APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001024 APInt::tcSubtract(dividend, divisor, 0, partsCount);
1025 APInt::tcSetBit(lhsSignificand, bit - 1);
1026 }
1027
1028 APInt::tcShiftLeft(dividend, partsCount, 1);
1029 }
1030
1031 /* Figure out the lost fraction. */
1032 int cmp = APInt::tcCompare(dividend, divisor, partsCount);
1033
Dan Gohman16e02092010-03-24 19:38:02 +00001034 if (cmp > 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001035 lost_fraction = lfMoreThanHalf;
Dan Gohman16e02092010-03-24 19:38:02 +00001036 else if (cmp == 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001037 lost_fraction = lfExactlyHalf;
Dan Gohman16e02092010-03-24 19:38:02 +00001038 else if (APInt::tcIsZero(dividend, partsCount))
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001039 lost_fraction = lfExactlyZero;
1040 else
1041 lost_fraction = lfLessThanHalf;
1042
Dan Gohman16e02092010-03-24 19:38:02 +00001043 if (partsCount > 2)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001044 delete [] dividend;
1045
1046 return lost_fraction;
1047}
1048
1049unsigned int
1050APFloat::significandMSB() const
1051{
1052 return APInt::tcMSB(significandParts(), partCount());
1053}
1054
1055unsigned int
1056APFloat::significandLSB() const
1057{
1058 return APInt::tcLSB(significandParts(), partCount());
1059}
1060
1061/* Note that a zero result is NOT normalized to fcZero. */
1062lostFraction
1063APFloat::shiftSignificandRight(unsigned int bits)
1064{
1065 /* Our exponent should not overflow. */
1066 assert((exponent_t) (exponent + bits) >= exponent);
1067
1068 exponent += bits;
1069
1070 return shiftRight(significandParts(), partCount(), bits);
1071}
1072
1073/* Shift the significand left BITS bits, subtract BITS from its exponent. */
1074void
1075APFloat::shiftSignificandLeft(unsigned int bits)
1076{
1077 assert(bits < semantics->precision);
1078
Dan Gohman16e02092010-03-24 19:38:02 +00001079 if (bits) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001080 unsigned int partsCount = partCount();
1081
1082 APInt::tcShiftLeft(significandParts(), partsCount, bits);
1083 exponent -= bits;
1084
1085 assert(!APInt::tcIsZero(significandParts(), partsCount));
1086 }
1087}
1088
1089APFloat::cmpResult
1090APFloat::compareAbsoluteValue(const APFloat &rhs) const
1091{
1092 int compare;
1093
1094 assert(semantics == rhs.semantics);
1095 assert(category == fcNormal);
1096 assert(rhs.category == fcNormal);
1097
1098 compare = exponent - rhs.exponent;
1099
1100 /* If exponents are equal, do an unsigned bignum comparison of the
1101 significands. */
Dan Gohman16e02092010-03-24 19:38:02 +00001102 if (compare == 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001103 compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
Neil Booth4f881702007-09-26 21:33:42 +00001104 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001105
Dan Gohman16e02092010-03-24 19:38:02 +00001106 if (compare > 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001107 return cmpGreaterThan;
Dan Gohman16e02092010-03-24 19:38:02 +00001108 else if (compare < 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001109 return cmpLessThan;
1110 else
1111 return cmpEqual;
1112}
1113
1114/* Handle overflow. Sign is preserved. We either become infinity or
1115 the largest finite number. */
1116APFloat::opStatus
1117APFloat::handleOverflow(roundingMode rounding_mode)
1118{
1119 /* Infinity? */
Dan Gohman16e02092010-03-24 19:38:02 +00001120 if (rounding_mode == rmNearestTiesToEven ||
1121 rounding_mode == rmNearestTiesToAway ||
1122 (rounding_mode == rmTowardPositive && !sign) ||
1123 (rounding_mode == rmTowardNegative && sign)) {
1124 category = fcInfinity;
1125 return (opStatus) (opOverflow | opInexact);
1126 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001127
1128 /* Otherwise we become the largest finite number. */
1129 category = fcNormal;
1130 exponent = semantics->maxExponent;
1131 APInt::tcSetLeastSignificantBits(significandParts(), partCount(),
Neil Booth4f881702007-09-26 21:33:42 +00001132 semantics->precision);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001133
1134 return opInexact;
1135}
1136
Neil Boothb7dea4c2007-10-03 15:16:41 +00001137/* Returns TRUE if, when truncating the current number, with BIT the
1138 new LSB, with the given lost fraction and rounding mode, the result
1139 would need to be rounded away from zero (i.e., by increasing the
1140 signficand). This routine must work for fcZero of both signs, and
1141 fcNormal numbers. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001142bool
1143APFloat::roundAwayFromZero(roundingMode rounding_mode,
Neil Boothb7dea4c2007-10-03 15:16:41 +00001144 lostFraction lost_fraction,
1145 unsigned int bit) const
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001146{
Dale Johanneseneaf08942007-08-31 04:03:46 +00001147 /* NaNs and infinities should not have lost fractions. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001148 assert(category == fcNormal || category == fcZero);
1149
Neil Boothb7dea4c2007-10-03 15:16:41 +00001150 /* Current callers never pass this so we don't handle it. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001151 assert(lost_fraction != lfExactlyZero);
1152
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001153 switch (rounding_mode) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001154 case rmNearestTiesToAway:
1155 return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
1156
1157 case rmNearestTiesToEven:
Dan Gohman16e02092010-03-24 19:38:02 +00001158 if (lost_fraction == lfMoreThanHalf)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001159 return true;
1160
1161 /* Our zeroes don't have a significand to test. */
Dan Gohman16e02092010-03-24 19:38:02 +00001162 if (lost_fraction == lfExactlyHalf && category != fcZero)
Neil Boothb7dea4c2007-10-03 15:16:41 +00001163 return APInt::tcExtractBit(significandParts(), bit);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001164
1165 return false;
1166
1167 case rmTowardZero:
1168 return false;
1169
1170 case rmTowardPositive:
1171 return sign == false;
1172
1173 case rmTowardNegative:
1174 return sign == true;
1175 }
Chandler Carruth732f05c2012-01-10 18:08:01 +00001176 llvm_unreachable("Invalid rounding mode found");
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001177}
1178
1179APFloat::opStatus
1180APFloat::normalize(roundingMode rounding_mode,
Neil Booth4f881702007-09-26 21:33:42 +00001181 lostFraction lost_fraction)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001182{
Neil Booth4f881702007-09-26 21:33:42 +00001183 unsigned int omsb; /* One, not zero, based MSB. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001184 int exponentChange;
1185
Dan Gohman16e02092010-03-24 19:38:02 +00001186 if (category != fcNormal)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001187 return opOK;
1188
1189 /* Before rounding normalize the exponent of fcNormal numbers. */
1190 omsb = significandMSB() + 1;
1191
Dan Gohman16e02092010-03-24 19:38:02 +00001192 if (omsb) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001193 /* OMSB is numbered from 1. We want to place it in the integer
Nick Lewycky03dd4e82011-10-03 21:30:08 +00001194 bit numbered PRECISION if possible, with a compensating change in
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001195 the exponent. */
1196 exponentChange = omsb - semantics->precision;
1197
1198 /* If the resulting exponent is too high, overflow according to
1199 the rounding mode. */
Dan Gohman16e02092010-03-24 19:38:02 +00001200 if (exponent + exponentChange > semantics->maxExponent)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001201 return handleOverflow(rounding_mode);
1202
1203 /* Subnormal numbers have exponent minExponent, and their MSB
1204 is forced based on that. */
Dan Gohman16e02092010-03-24 19:38:02 +00001205 if (exponent + exponentChange < semantics->minExponent)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001206 exponentChange = semantics->minExponent - exponent;
1207
1208 /* Shifting left is easy as we don't lose precision. */
Dan Gohman16e02092010-03-24 19:38:02 +00001209 if (exponentChange < 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001210 assert(lost_fraction == lfExactlyZero);
1211
1212 shiftSignificandLeft(-exponentChange);
1213
1214 return opOK;
1215 }
1216
Dan Gohman16e02092010-03-24 19:38:02 +00001217 if (exponentChange > 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001218 lostFraction lf;
1219
1220 /* Shift right and capture any new lost fraction. */
1221 lf = shiftSignificandRight(exponentChange);
1222
1223 lost_fraction = combineLostFractions(lf, lost_fraction);
1224
1225 /* Keep OMSB up-to-date. */
Dan Gohman16e02092010-03-24 19:38:02 +00001226 if (omsb > (unsigned) exponentChange)
Neil Booth96c74712007-10-12 16:02:31 +00001227 omsb -= exponentChange;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001228 else
Neil Booth4f881702007-09-26 21:33:42 +00001229 omsb = 0;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001230 }
1231 }
1232
1233 /* Now round the number according to rounding_mode given the lost
1234 fraction. */
1235
1236 /* As specified in IEEE 754, since we do not trap we do not report
1237 underflow for exact results. */
Dan Gohman16e02092010-03-24 19:38:02 +00001238 if (lost_fraction == lfExactlyZero) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001239 /* Canonicalize zeroes. */
Dan Gohman16e02092010-03-24 19:38:02 +00001240 if (omsb == 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001241 category = fcZero;
1242
1243 return opOK;
1244 }
1245
1246 /* Increment the significand if we're rounding away from zero. */
Dan Gohman16e02092010-03-24 19:38:02 +00001247 if (roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
1248 if (omsb == 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001249 exponent = semantics->minExponent;
1250
1251 incrementSignificand();
1252 omsb = significandMSB() + 1;
1253
1254 /* Did the significand increment overflow? */
Dan Gohman16e02092010-03-24 19:38:02 +00001255 if (omsb == (unsigned) semantics->precision + 1) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001256 /* Renormalize by incrementing the exponent and shifting our
Neil Booth4f881702007-09-26 21:33:42 +00001257 significand right one. However if we already have the
1258 maximum exponent we overflow to infinity. */
Dan Gohman16e02092010-03-24 19:38:02 +00001259 if (exponent == semantics->maxExponent) {
Neil Booth4f881702007-09-26 21:33:42 +00001260 category = fcInfinity;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001261
Neil Booth4f881702007-09-26 21:33:42 +00001262 return (opStatus) (opOverflow | opInexact);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001263 }
1264
1265 shiftSignificandRight(1);
1266
1267 return opInexact;
1268 }
1269 }
1270
1271 /* The normal case - we were and are not denormal, and any
1272 significand increment above didn't overflow. */
Dan Gohman16e02092010-03-24 19:38:02 +00001273 if (omsb == semantics->precision)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001274 return opInexact;
1275
1276 /* We have a non-zero denormal. */
1277 assert(omsb < semantics->precision);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001278
1279 /* Canonicalize zeroes. */
Dan Gohman16e02092010-03-24 19:38:02 +00001280 if (omsb == 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001281 category = fcZero;
1282
1283 /* The fcZero case is a denormal that underflowed to zero. */
1284 return (opStatus) (opUnderflow | opInexact);
1285}
1286
1287APFloat::opStatus
1288APFloat::addOrSubtractSpecials(const APFloat &rhs, bool subtract)
1289{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001290 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001291 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001292 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001293
Dale Johanneseneaf08942007-08-31 04:03:46 +00001294 case convolve(fcNaN, fcZero):
1295 case convolve(fcNaN, fcNormal):
1296 case convolve(fcNaN, fcInfinity):
1297 case convolve(fcNaN, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001298 case convolve(fcNormal, fcZero):
1299 case convolve(fcInfinity, fcNormal):
1300 case convolve(fcInfinity, fcZero):
1301 return opOK;
1302
Dale Johanneseneaf08942007-08-31 04:03:46 +00001303 case convolve(fcZero, fcNaN):
1304 case convolve(fcNormal, fcNaN):
1305 case convolve(fcInfinity, fcNaN):
1306 category = fcNaN;
1307 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001308 return opOK;
1309
1310 case convolve(fcNormal, fcInfinity):
1311 case convolve(fcZero, fcInfinity):
1312 category = fcInfinity;
1313 sign = rhs.sign ^ subtract;
1314 return opOK;
1315
1316 case convolve(fcZero, fcNormal):
1317 assign(rhs);
1318 sign = rhs.sign ^ subtract;
1319 return opOK;
1320
1321 case convolve(fcZero, fcZero):
1322 /* Sign depends on rounding mode; handled by caller. */
1323 return opOK;
1324
1325 case convolve(fcInfinity, fcInfinity):
1326 /* Differently signed infinities can only be validly
1327 subtracted. */
Dan Gohman16e02092010-03-24 19:38:02 +00001328 if (((sign ^ rhs.sign)!=0) != subtract) {
Neil Boothe5e01942007-10-14 10:39:51 +00001329 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001330 return opInvalidOp;
1331 }
1332
1333 return opOK;
1334
1335 case convolve(fcNormal, fcNormal):
1336 return opDivByZero;
1337 }
1338}
1339
1340/* Add or subtract two normal numbers. */
1341lostFraction
1342APFloat::addOrSubtractSignificand(const APFloat &rhs, bool subtract)
1343{
1344 integerPart carry;
1345 lostFraction lost_fraction;
1346 int bits;
1347
1348 /* Determine if the operation on the absolute values is effectively
1349 an addition or subtraction. */
Hartmut Kaiser8df77a92007-10-25 23:15:31 +00001350 subtract ^= (sign ^ rhs.sign) ? true : false;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001351
1352 /* Are we bigger exponent-wise than the RHS? */
1353 bits = exponent - rhs.exponent;
1354
1355 /* Subtraction is more subtle than one might naively expect. */
Dan Gohman16e02092010-03-24 19:38:02 +00001356 if (subtract) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001357 APFloat temp_rhs(rhs);
1358 bool reverse;
1359
Chris Lattnerada530b2007-08-24 03:02:34 +00001360 if (bits == 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001361 reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan;
1362 lost_fraction = lfExactlyZero;
Chris Lattnerada530b2007-08-24 03:02:34 +00001363 } else if (bits > 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001364 lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
1365 shiftSignificandLeft(1);
1366 reverse = false;
Chris Lattnerada530b2007-08-24 03:02:34 +00001367 } else {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001368 lost_fraction = shiftSignificandRight(-bits - 1);
1369 temp_rhs.shiftSignificandLeft(1);
1370 reverse = true;
1371 }
1372
Chris Lattnerada530b2007-08-24 03:02:34 +00001373 if (reverse) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001374 carry = temp_rhs.subtractSignificand
Neil Booth4f881702007-09-26 21:33:42 +00001375 (*this, lost_fraction != lfExactlyZero);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001376 copySignificand(temp_rhs);
1377 sign = !sign;
1378 } else {
1379 carry = subtractSignificand
Neil Booth4f881702007-09-26 21:33:42 +00001380 (temp_rhs, lost_fraction != lfExactlyZero);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001381 }
1382
1383 /* Invert the lost fraction - it was on the RHS and
1384 subtracted. */
Dan Gohman16e02092010-03-24 19:38:02 +00001385 if (lost_fraction == lfLessThanHalf)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001386 lost_fraction = lfMoreThanHalf;
Dan Gohman16e02092010-03-24 19:38:02 +00001387 else if (lost_fraction == lfMoreThanHalf)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001388 lost_fraction = lfLessThanHalf;
1389
1390 /* The code above is intended to ensure that no borrow is
1391 necessary. */
1392 assert(!carry);
Duncan Sands1f6a3292011-08-12 14:54:45 +00001393 (void)carry;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001394 } else {
Dan Gohman16e02092010-03-24 19:38:02 +00001395 if (bits > 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001396 APFloat temp_rhs(rhs);
1397
1398 lost_fraction = temp_rhs.shiftSignificandRight(bits);
1399 carry = addSignificand(temp_rhs);
1400 } else {
1401 lost_fraction = shiftSignificandRight(-bits);
1402 carry = addSignificand(rhs);
1403 }
1404
1405 /* We have a guard bit; generating a carry cannot happen. */
1406 assert(!carry);
Duncan Sands1f6a3292011-08-12 14:54:45 +00001407 (void)carry;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001408 }
1409
1410 return lost_fraction;
1411}
1412
1413APFloat::opStatus
1414APFloat::multiplySpecials(const APFloat &rhs)
1415{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001416 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001417 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001418 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001419
Dale Johanneseneaf08942007-08-31 04:03:46 +00001420 case convolve(fcNaN, fcZero):
1421 case convolve(fcNaN, fcNormal):
1422 case convolve(fcNaN, fcInfinity):
1423 case convolve(fcNaN, fcNaN):
1424 return opOK;
1425
1426 case convolve(fcZero, fcNaN):
1427 case convolve(fcNormal, fcNaN):
1428 case convolve(fcInfinity, fcNaN):
1429 category = fcNaN;
1430 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001431 return opOK;
1432
1433 case convolve(fcNormal, fcInfinity):
1434 case convolve(fcInfinity, fcNormal):
1435 case convolve(fcInfinity, fcInfinity):
1436 category = fcInfinity;
1437 return opOK;
1438
1439 case convolve(fcZero, fcNormal):
1440 case convolve(fcNormal, fcZero):
1441 case convolve(fcZero, fcZero):
1442 category = fcZero;
1443 return opOK;
1444
1445 case convolve(fcZero, fcInfinity):
1446 case convolve(fcInfinity, fcZero):
Neil Boothe5e01942007-10-14 10:39:51 +00001447 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001448 return opInvalidOp;
1449
1450 case convolve(fcNormal, fcNormal):
1451 return opOK;
1452 }
1453}
1454
1455APFloat::opStatus
1456APFloat::divideSpecials(const APFloat &rhs)
1457{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001458 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001459 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001460 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001461
Dale Johanneseneaf08942007-08-31 04:03:46 +00001462 case convolve(fcNaN, fcZero):
1463 case convolve(fcNaN, fcNormal):
1464 case convolve(fcNaN, fcInfinity):
1465 case convolve(fcNaN, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001466 case convolve(fcInfinity, fcZero):
1467 case convolve(fcInfinity, fcNormal):
1468 case convolve(fcZero, fcInfinity):
1469 case convolve(fcZero, fcNormal):
1470 return opOK;
1471
Dale Johanneseneaf08942007-08-31 04:03:46 +00001472 case convolve(fcZero, fcNaN):
1473 case convolve(fcNormal, fcNaN):
1474 case convolve(fcInfinity, fcNaN):
1475 category = fcNaN;
1476 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001477 return opOK;
1478
1479 case convolve(fcNormal, fcInfinity):
1480 category = fcZero;
1481 return opOK;
1482
1483 case convolve(fcNormal, fcZero):
1484 category = fcInfinity;
1485 return opDivByZero;
1486
1487 case convolve(fcInfinity, fcInfinity):
1488 case convolve(fcZero, fcZero):
Neil Boothe5e01942007-10-14 10:39:51 +00001489 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001490 return opInvalidOp;
1491
1492 case convolve(fcNormal, fcNormal):
1493 return opOK;
1494 }
1495}
1496
Dale Johannesened6af242009-01-21 00:35:19 +00001497APFloat::opStatus
1498APFloat::modSpecials(const APFloat &rhs)
1499{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001500 switch (convolve(category, rhs.category)) {
Dale Johannesened6af242009-01-21 00:35:19 +00001501 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001502 llvm_unreachable(0);
Dale Johannesened6af242009-01-21 00:35:19 +00001503
1504 case convolve(fcNaN, fcZero):
1505 case convolve(fcNaN, fcNormal):
1506 case convolve(fcNaN, fcInfinity):
1507 case convolve(fcNaN, fcNaN):
1508 case convolve(fcZero, fcInfinity):
1509 case convolve(fcZero, fcNormal):
1510 case convolve(fcNormal, fcInfinity):
1511 return opOK;
1512
1513 case convolve(fcZero, fcNaN):
1514 case convolve(fcNormal, fcNaN):
1515 case convolve(fcInfinity, fcNaN):
1516 category = fcNaN;
1517 copySignificand(rhs);
1518 return opOK;
1519
1520 case convolve(fcNormal, fcZero):
1521 case convolve(fcInfinity, fcZero):
1522 case convolve(fcInfinity, fcNormal):
1523 case convolve(fcInfinity, fcInfinity):
1524 case convolve(fcZero, fcZero):
1525 makeNaN();
1526 return opInvalidOp;
1527
1528 case convolve(fcNormal, fcNormal):
1529 return opOK;
1530 }
1531}
1532
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001533/* Change sign. */
1534void
1535APFloat::changeSign()
1536{
1537 /* Look mummy, this one's easy. */
1538 sign = !sign;
1539}
1540
Dale Johannesene15c2db2007-08-31 23:35:31 +00001541void
1542APFloat::clearSign()
1543{
1544 /* So is this one. */
1545 sign = 0;
1546}
1547
1548void
1549APFloat::copySign(const APFloat &rhs)
1550{
1551 /* And this one. */
1552 sign = rhs.sign;
1553}
1554
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001555/* Normalized addition or subtraction. */
1556APFloat::opStatus
1557APFloat::addOrSubtract(const APFloat &rhs, roundingMode rounding_mode,
Neil Booth4f881702007-09-26 21:33:42 +00001558 bool subtract)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001559{
1560 opStatus fs;
1561
Neil Boothcaf19d72007-10-14 10:29:28 +00001562 assertArithmeticOK(*semantics);
1563
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001564 fs = addOrSubtractSpecials(rhs, subtract);
1565
1566 /* This return code means it was not a simple case. */
Dan Gohman16e02092010-03-24 19:38:02 +00001567 if (fs == opDivByZero) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001568 lostFraction lost_fraction;
1569
1570 lost_fraction = addOrSubtractSignificand(rhs, subtract);
1571 fs = normalize(rounding_mode, lost_fraction);
1572
1573 /* Can only be zero if we lost no fraction. */
1574 assert(category != fcZero || lost_fraction == lfExactlyZero);
1575 }
1576
1577 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1578 positive zero unless rounding to minus infinity, except that
1579 adding two like-signed zeroes gives that zero. */
Dan Gohman16e02092010-03-24 19:38:02 +00001580 if (category == fcZero) {
1581 if (rhs.category != fcZero || (sign == rhs.sign) == subtract)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001582 sign = (rounding_mode == rmTowardNegative);
1583 }
1584
1585 return fs;
1586}
1587
1588/* Normalized addition. */
1589APFloat::opStatus
1590APFloat::add(const APFloat &rhs, roundingMode rounding_mode)
1591{
1592 return addOrSubtract(rhs, rounding_mode, false);
1593}
1594
1595/* Normalized subtraction. */
1596APFloat::opStatus
1597APFloat::subtract(const APFloat &rhs, roundingMode rounding_mode)
1598{
1599 return addOrSubtract(rhs, rounding_mode, true);
1600}
1601
1602/* Normalized multiply. */
1603APFloat::opStatus
1604APFloat::multiply(const APFloat &rhs, roundingMode rounding_mode)
1605{
1606 opStatus fs;
1607
Neil Boothcaf19d72007-10-14 10:29:28 +00001608 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001609 sign ^= rhs.sign;
1610 fs = multiplySpecials(rhs);
1611
Dan Gohman16e02092010-03-24 19:38:02 +00001612 if (category == fcNormal) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001613 lostFraction lost_fraction = multiplySignificand(rhs, 0);
1614 fs = normalize(rounding_mode, lost_fraction);
Dan Gohman16e02092010-03-24 19:38:02 +00001615 if (lost_fraction != lfExactlyZero)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001616 fs = (opStatus) (fs | opInexact);
1617 }
1618
1619 return fs;
1620}
1621
1622/* Normalized divide. */
1623APFloat::opStatus
1624APFloat::divide(const APFloat &rhs, roundingMode rounding_mode)
1625{
1626 opStatus fs;
1627
Neil Boothcaf19d72007-10-14 10:29:28 +00001628 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001629 sign ^= rhs.sign;
1630 fs = divideSpecials(rhs);
1631
Dan Gohman16e02092010-03-24 19:38:02 +00001632 if (category == fcNormal) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001633 lostFraction lost_fraction = divideSignificand(rhs);
1634 fs = normalize(rounding_mode, lost_fraction);
Dan Gohman16e02092010-03-24 19:38:02 +00001635 if (lost_fraction != lfExactlyZero)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001636 fs = (opStatus) (fs | opInexact);
1637 }
1638
1639 return fs;
1640}
1641
Dale Johannesen24b66a82009-01-20 18:35:05 +00001642/* Normalized remainder. This is not currently correct in all cases. */
1643APFloat::opStatus
1644APFloat::remainder(const APFloat &rhs)
1645{
1646 opStatus fs;
1647 APFloat V = *this;
1648 unsigned int origSign = sign;
1649
1650 assertArithmeticOK(*semantics);
1651 fs = V.divide(rhs, rmNearestTiesToEven);
1652 if (fs == opDivByZero)
1653 return fs;
1654
1655 int parts = partCount();
1656 integerPart *x = new integerPart[parts];
1657 bool ignored;
1658 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1659 rmNearestTiesToEven, &ignored);
1660 if (fs==opInvalidOp)
1661 return fs;
1662
1663 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1664 rmNearestTiesToEven);
1665 assert(fs==opOK); // should always work
1666
1667 fs = V.multiply(rhs, rmNearestTiesToEven);
1668 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1669
1670 fs = subtract(V, rmNearestTiesToEven);
1671 assert(fs==opOK || fs==opInexact); // likewise
1672
1673 if (isZero())
1674 sign = origSign; // IEEE754 requires this
1675 delete[] x;
1676 return fs;
1677}
1678
Dan Gohman16e02092010-03-24 19:38:02 +00001679/* Normalized llvm frem (C fmod).
Dale Johannesen24b66a82009-01-20 18:35:05 +00001680 This is not currently correct in all cases. */
Dale Johannesene15c2db2007-08-31 23:35:31 +00001681APFloat::opStatus
1682APFloat::mod(const APFloat &rhs, roundingMode rounding_mode)
1683{
1684 opStatus fs;
Neil Boothcaf19d72007-10-14 10:29:28 +00001685 assertArithmeticOK(*semantics);
Dale Johannesened6af242009-01-21 00:35:19 +00001686 fs = modSpecials(rhs);
Dale Johannesene15c2db2007-08-31 23:35:31 +00001687
Dale Johannesened6af242009-01-21 00:35:19 +00001688 if (category == fcNormal && rhs.category == fcNormal) {
1689 APFloat V = *this;
1690 unsigned int origSign = sign;
Dale Johannesene15c2db2007-08-31 23:35:31 +00001691
Dale Johannesened6af242009-01-21 00:35:19 +00001692 fs = V.divide(rhs, rmNearestTiesToEven);
1693 if (fs == opDivByZero)
1694 return fs;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001695
Dale Johannesened6af242009-01-21 00:35:19 +00001696 int parts = partCount();
1697 integerPart *x = new integerPart[parts];
1698 bool ignored;
1699 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1700 rmTowardZero, &ignored);
1701 if (fs==opInvalidOp)
1702 return fs;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001703
Dale Johannesened6af242009-01-21 00:35:19 +00001704 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1705 rmNearestTiesToEven);
1706 assert(fs==opOK); // should always work
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001707
Dale Johannesened6af242009-01-21 00:35:19 +00001708 fs = V.multiply(rhs, rounding_mode);
1709 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1710
1711 fs = subtract(V, rounding_mode);
1712 assert(fs==opOK || fs==opInexact); // likewise
1713
1714 if (isZero())
1715 sign = origSign; // IEEE754 requires this
1716 delete[] x;
1717 }
Dale Johannesene15c2db2007-08-31 23:35:31 +00001718 return fs;
1719}
1720
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001721/* Normalized fused-multiply-add. */
1722APFloat::opStatus
1723APFloat::fusedMultiplyAdd(const APFloat &multiplicand,
Neil Booth4f881702007-09-26 21:33:42 +00001724 const APFloat &addend,
1725 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001726{
1727 opStatus fs;
1728
Neil Boothcaf19d72007-10-14 10:29:28 +00001729 assertArithmeticOK(*semantics);
1730
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001731 /* Post-multiplication sign, before addition. */
1732 sign ^= multiplicand.sign;
1733
1734 /* If and only if all arguments are normal do we need to do an
1735 extended-precision calculation. */
Dan Gohman16e02092010-03-24 19:38:02 +00001736 if (category == fcNormal &&
1737 multiplicand.category == fcNormal &&
1738 addend.category == fcNormal) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001739 lostFraction lost_fraction;
1740
1741 lost_fraction = multiplySignificand(multiplicand, &addend);
1742 fs = normalize(rounding_mode, lost_fraction);
Dan Gohman16e02092010-03-24 19:38:02 +00001743 if (lost_fraction != lfExactlyZero)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001744 fs = (opStatus) (fs | opInexact);
1745
1746 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1747 positive zero unless rounding to minus infinity, except that
1748 adding two like-signed zeroes gives that zero. */
Dan Gohman16e02092010-03-24 19:38:02 +00001749 if (category == fcZero && sign != addend.sign)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001750 sign = (rounding_mode == rmTowardNegative);
1751 } else {
1752 fs = multiplySpecials(multiplicand);
1753
1754 /* FS can only be opOK or opInvalidOp. There is no more work
1755 to do in the latter case. The IEEE-754R standard says it is
1756 implementation-defined in this case whether, if ADDEND is a
Dale Johanneseneaf08942007-08-31 04:03:46 +00001757 quiet NaN, we raise invalid op; this implementation does so.
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001758
1759 If we need to do the addition we can do so with normal
1760 precision. */
Dan Gohman16e02092010-03-24 19:38:02 +00001761 if (fs == opOK)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001762 fs = addOrSubtract(addend, rounding_mode, false);
1763 }
1764
1765 return fs;
1766}
1767
Owen Anderson7c626d32012-08-13 23:32:49 +00001768/* Rounding-mode corrrect round to integral value. */
1769APFloat::opStatus APFloat::roundToIntegral(roundingMode rounding_mode) {
1770 opStatus fs;
1771 assertArithmeticOK(*semantics);
1772
Owen Andersonc82cc582012-08-15 18:28:45 +00001773 // If the exponent is large enough, we know that this value is already
1774 // integral, and the arithmetic below would potentially cause it to saturate
1775 // to +/-Inf. Bail out early instead.
1776 if (exponent+1 >= (int)semanticsPrecision(*semantics))
1777 return opOK;
1778
Owen Anderson7c626d32012-08-13 23:32:49 +00001779 // The algorithm here is quite simple: we add 2^(p-1), where p is the
1780 // precision of our format, and then subtract it back off again. The choice
1781 // of rounding modes for the addition/subtraction determines the rounding mode
1782 // for our integral rounding as well.
Owen Anderson7c289782012-08-15 16:42:53 +00001783 // NOTE: When the input value is negative, we do subtraction followed by
Owen Andersonf7a5dfc2012-08-15 05:39:46 +00001784 // addition instead.
Owen Andersond7a85b12012-08-14 18:51:15 +00001785 APInt IntegerConstant(NextPowerOf2(semanticsPrecision(*semantics)), 1);
1786 IntegerConstant <<= semanticsPrecision(*semantics)-1;
Owen Anderson7c626d32012-08-13 23:32:49 +00001787 APFloat MagicConstant(*semantics);
1788 fs = MagicConstant.convertFromAPInt(IntegerConstant, false,
1789 rmNearestTiesToEven);
Owen Andersonf7a5dfc2012-08-15 05:39:46 +00001790 MagicConstant.copySign(*this);
1791
Owen Anderson7c626d32012-08-13 23:32:49 +00001792 if (fs != opOK)
1793 return fs;
1794
Owen Andersonf7a5dfc2012-08-15 05:39:46 +00001795 // Preserve the input sign so that we can handle 0.0/-0.0 cases correctly.
1796 bool inputSign = isNegative();
1797
Owen Anderson7c626d32012-08-13 23:32:49 +00001798 fs = add(MagicConstant, rounding_mode);
1799 if (fs != opOK && fs != opInexact)
1800 return fs;
1801
1802 fs = subtract(MagicConstant, rounding_mode);
Owen Andersonf7a5dfc2012-08-15 05:39:46 +00001803
1804 // Restore the input sign.
1805 if (inputSign != isNegative())
1806 changeSign();
1807
Owen Anderson7c626d32012-08-13 23:32:49 +00001808 return fs;
1809}
1810
1811
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001812/* Comparison requires normalized numbers. */
1813APFloat::cmpResult
1814APFloat::compare(const APFloat &rhs) const
1815{
1816 cmpResult result;
1817
Neil Boothcaf19d72007-10-14 10:29:28 +00001818 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001819 assert(semantics == rhs.semantics);
1820
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001821 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001822 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001823 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001824
Dale Johanneseneaf08942007-08-31 04:03:46 +00001825 case convolve(fcNaN, fcZero):
1826 case convolve(fcNaN, fcNormal):
1827 case convolve(fcNaN, fcInfinity):
1828 case convolve(fcNaN, fcNaN):
1829 case convolve(fcZero, fcNaN):
1830 case convolve(fcNormal, fcNaN):
1831 case convolve(fcInfinity, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001832 return cmpUnordered;
1833
1834 case convolve(fcInfinity, fcNormal):
1835 case convolve(fcInfinity, fcZero):
1836 case convolve(fcNormal, fcZero):
Dan Gohman16e02092010-03-24 19:38:02 +00001837 if (sign)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001838 return cmpLessThan;
1839 else
1840 return cmpGreaterThan;
1841
1842 case convolve(fcNormal, fcInfinity):
1843 case convolve(fcZero, fcInfinity):
1844 case convolve(fcZero, fcNormal):
Dan Gohman16e02092010-03-24 19:38:02 +00001845 if (rhs.sign)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001846 return cmpGreaterThan;
1847 else
1848 return cmpLessThan;
1849
1850 case convolve(fcInfinity, fcInfinity):
Dan Gohman16e02092010-03-24 19:38:02 +00001851 if (sign == rhs.sign)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001852 return cmpEqual;
Dan Gohman16e02092010-03-24 19:38:02 +00001853 else if (sign)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001854 return cmpLessThan;
1855 else
1856 return cmpGreaterThan;
1857
1858 case convolve(fcZero, fcZero):
1859 return cmpEqual;
1860
1861 case convolve(fcNormal, fcNormal):
1862 break;
1863 }
1864
1865 /* Two normal numbers. Do they have the same sign? */
Dan Gohman16e02092010-03-24 19:38:02 +00001866 if (sign != rhs.sign) {
1867 if (sign)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001868 result = cmpLessThan;
1869 else
1870 result = cmpGreaterThan;
1871 } else {
1872 /* Compare absolute values; invert result if negative. */
1873 result = compareAbsoluteValue(rhs);
1874
Dan Gohman16e02092010-03-24 19:38:02 +00001875 if (sign) {
1876 if (result == cmpLessThan)
Neil Booth4f881702007-09-26 21:33:42 +00001877 result = cmpGreaterThan;
Dan Gohman16e02092010-03-24 19:38:02 +00001878 else if (result == cmpGreaterThan)
Neil Booth4f881702007-09-26 21:33:42 +00001879 result = cmpLessThan;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001880 }
1881 }
1882
1883 return result;
1884}
1885
Dale Johannesen23a98552008-10-09 23:00:39 +00001886/// APFloat::convert - convert a value of one floating point type to another.
1887/// The return value corresponds to the IEEE754 exceptions. *losesInfo
1888/// records whether the transformation lost information, i.e. whether
1889/// converting the result back to the original type will produce the
1890/// original value (this is almost the same as return value==fsOK, but there
1891/// are edge cases where this is not so).
1892
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001893APFloat::opStatus
1894APFloat::convert(const fltSemantics &toSemantics,
Dale Johannesen23a98552008-10-09 23:00:39 +00001895 roundingMode rounding_mode, bool *losesInfo)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001896{
Neil Boothc8db43d2007-09-22 02:56:19 +00001897 lostFraction lostFraction;
1898 unsigned int newPartCount, oldPartCount;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001899 opStatus fs;
Eli Friedman44551422011-11-26 03:38:02 +00001900 int shift;
1901 const fltSemantics &fromSemantics = *semantics;
Neil Booth4f881702007-09-26 21:33:42 +00001902
Eli Friedman44551422011-11-26 03:38:02 +00001903 assertArithmeticOK(fromSemantics);
Dale Johannesen79f82f92008-04-20 01:34:03 +00001904 assertArithmeticOK(toSemantics);
Neil Boothc8db43d2007-09-22 02:56:19 +00001905 lostFraction = lfExactlyZero;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001906 newPartCount = partCountForBits(toSemantics.precision + 1);
Neil Boothc8db43d2007-09-22 02:56:19 +00001907 oldPartCount = partCount();
Eli Friedman44551422011-11-26 03:38:02 +00001908 shift = toSemantics.precision - fromSemantics.precision;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001909
Eli Friedman44551422011-11-26 03:38:02 +00001910 bool X86SpecialNan = false;
1911 if (&fromSemantics == &APFloat::x87DoubleExtended &&
1912 &toSemantics != &APFloat::x87DoubleExtended && category == fcNaN &&
1913 (!(*significandParts() & 0x8000000000000000ULL) ||
1914 !(*significandParts() & 0x4000000000000000ULL))) {
1915 // x86 has some unusual NaNs which cannot be represented in any other
1916 // format; note them here.
1917 X86SpecialNan = true;
1918 }
1919
1920 // If this is a truncation, perform the shift before we narrow the storage.
1921 if (shift < 0 && (category==fcNormal || category==fcNaN))
1922 lostFraction = shiftRight(significandParts(), oldPartCount, -shift);
1923
1924 // Fix the storage so it can hold to new value.
Neil Boothc8db43d2007-09-22 02:56:19 +00001925 if (newPartCount > oldPartCount) {
Eli Friedman44551422011-11-26 03:38:02 +00001926 // The new type requires more storage; make it available.
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001927 integerPart *newParts;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001928 newParts = new integerPart[newPartCount];
1929 APInt::tcSet(newParts, 0, newPartCount);
Dale Johannesen902ff942007-09-25 17:25:00 +00001930 if (category==fcNormal || category==fcNaN)
1931 APInt::tcAssign(newParts, significandParts(), oldPartCount);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001932 freeSignificand();
1933 significand.parts = newParts;
Eli Friedman44551422011-11-26 03:38:02 +00001934 } else if (newPartCount == 1 && oldPartCount != 1) {
1935 // Switch to built-in storage for a single part.
1936 integerPart newPart = 0;
1937 if (category==fcNormal || category==fcNaN)
1938 newPart = significandParts()[0];
1939 freeSignificand();
1940 significand.part = newPart;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001941 }
1942
Eli Friedman44551422011-11-26 03:38:02 +00001943 // Now that we have the right storage, switch the semantics.
1944 semantics = &toSemantics;
1945
1946 // If this is an extension, perform the shift now that the storage is
1947 // available.
1948 if (shift > 0 && (category==fcNormal || category==fcNaN))
1949 APInt::tcShiftLeft(significandParts(), newPartCount, shift);
1950
Dan Gohman16e02092010-03-24 19:38:02 +00001951 if (category == fcNormal) {
Neil Boothc8db43d2007-09-22 02:56:19 +00001952 fs = normalize(rounding_mode, lostFraction);
Dale Johannesen23a98552008-10-09 23:00:39 +00001953 *losesInfo = (fs != opOK);
Dale Johannesen902ff942007-09-25 17:25:00 +00001954 } else if (category == fcNaN) {
Eli Friedman44551422011-11-26 03:38:02 +00001955 *losesInfo = lostFraction != lfExactlyZero || X86SpecialNan;
Dale Johannesen902ff942007-09-25 17:25:00 +00001956 // gcc forces the Quiet bit on, which means (float)(double)(float_sNan)
1957 // does not give you back the same bits. This is dubious, and we
1958 // don't currently do it. You're really supposed to get
1959 // an invalid operation signal at runtime, but nobody does that.
Dale Johannesen23a98552008-10-09 23:00:39 +00001960 fs = opOK;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001961 } else {
Dale Johannesen23a98552008-10-09 23:00:39 +00001962 *losesInfo = false;
Eli Friedmanf9b1cd02011-11-28 18:50:37 +00001963 fs = opOK;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001964 }
1965
1966 return fs;
1967}
1968
1969/* Convert a floating point number to an integer according to the
1970 rounding mode. If the rounded integer value is out of range this
Neil Boothee7ae382007-11-01 22:43:37 +00001971 returns an invalid operation exception and the contents of the
1972 destination parts are unspecified. If the rounded value is in
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001973 range but the floating point number is not the exact integer, the C
1974 standard doesn't require an inexact exception to be raised. IEEE
1975 854 does require it so we do that.
1976
1977 Note that for conversions to integer type the C standard requires
1978 round-to-zero to always be used. */
1979APFloat::opStatus
Neil Boothee7ae382007-11-01 22:43:37 +00001980APFloat::convertToSignExtendedInteger(integerPart *parts, unsigned int width,
1981 bool isSigned,
Dale Johannesen23a98552008-10-09 23:00:39 +00001982 roundingMode rounding_mode,
1983 bool *isExact) const
Neil Boothee7ae382007-11-01 22:43:37 +00001984{
1985 lostFraction lost_fraction;
1986 const integerPart *src;
1987 unsigned int dstPartsCount, truncatedBits;
1988
Evan Cheng794a7db2008-11-26 01:11:57 +00001989 assertArithmeticOK(*semantics);
Neil Boothe3d936a2007-11-02 15:10:05 +00001990
Dale Johannesen23a98552008-10-09 23:00:39 +00001991 *isExact = false;
1992
Neil Boothee7ae382007-11-01 22:43:37 +00001993 /* Handle the three special cases first. */
Dan Gohman16e02092010-03-24 19:38:02 +00001994 if (category == fcInfinity || category == fcNaN)
Neil Boothee7ae382007-11-01 22:43:37 +00001995 return opInvalidOp;
1996
1997 dstPartsCount = partCountForBits(width);
1998
Dan Gohman16e02092010-03-24 19:38:02 +00001999 if (category == fcZero) {
Neil Boothee7ae382007-11-01 22:43:37 +00002000 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesene4a42452008-10-07 00:40:01 +00002001 // Negative zero can't be represented as an int.
Dale Johannesen23a98552008-10-09 23:00:39 +00002002 *isExact = !sign;
2003 return opOK;
Neil Boothee7ae382007-11-01 22:43:37 +00002004 }
2005
2006 src = significandParts();
2007
2008 /* Step 1: place our absolute value, with any fraction truncated, in
2009 the destination. */
2010 if (exponent < 0) {
2011 /* Our absolute value is less than one; truncate everything. */
2012 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesen1f54f582009-01-19 21:17:05 +00002013 /* For exponent -1 the integer bit represents .5, look at that.
2014 For smaller exponents leftmost truncated bit is 0. */
2015 truncatedBits = semantics->precision -1U - exponent;
Neil Boothee7ae382007-11-01 22:43:37 +00002016 } else {
2017 /* We want the most significant (exponent + 1) bits; the rest are
2018 truncated. */
2019 unsigned int bits = exponent + 1U;
2020
2021 /* Hopelessly large in magnitude? */
2022 if (bits > width)
2023 return opInvalidOp;
2024
2025 if (bits < semantics->precision) {
2026 /* We truncate (semantics->precision - bits) bits. */
2027 truncatedBits = semantics->precision - bits;
2028 APInt::tcExtract(parts, dstPartsCount, src, bits, truncatedBits);
2029 } else {
2030 /* We want at least as many bits as are available. */
2031 APInt::tcExtract(parts, dstPartsCount, src, semantics->precision, 0);
2032 APInt::tcShiftLeft(parts, dstPartsCount, bits - semantics->precision);
2033 truncatedBits = 0;
2034 }
2035 }
2036
2037 /* Step 2: work out any lost fraction, and increment the absolute
2038 value if we would round away from zero. */
2039 if (truncatedBits) {
2040 lost_fraction = lostFractionThroughTruncation(src, partCount(),
2041 truncatedBits);
Dan Gohman16e02092010-03-24 19:38:02 +00002042 if (lost_fraction != lfExactlyZero &&
2043 roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
Neil Boothee7ae382007-11-01 22:43:37 +00002044 if (APInt::tcIncrement(parts, dstPartsCount))
2045 return opInvalidOp; /* Overflow. */
2046 }
2047 } else {
2048 lost_fraction = lfExactlyZero;
2049 }
2050
2051 /* Step 3: check if we fit in the destination. */
2052 unsigned int omsb = APInt::tcMSB(parts, dstPartsCount) + 1;
2053
2054 if (sign) {
2055 if (!isSigned) {
2056 /* Negative numbers cannot be represented as unsigned. */
2057 if (omsb != 0)
2058 return opInvalidOp;
2059 } else {
2060 /* It takes omsb bits to represent the unsigned integer value.
2061 We lose a bit for the sign, but care is needed as the
2062 maximally negative integer is a special case. */
2063 if (omsb == width && APInt::tcLSB(parts, dstPartsCount) + 1 != omsb)
2064 return opInvalidOp;
2065
2066 /* This case can happen because of rounding. */
2067 if (omsb > width)
2068 return opInvalidOp;
2069 }
2070
2071 APInt::tcNegate (parts, dstPartsCount);
2072 } else {
2073 if (omsb >= width + !isSigned)
2074 return opInvalidOp;
2075 }
2076
Dale Johannesen23a98552008-10-09 23:00:39 +00002077 if (lost_fraction == lfExactlyZero) {
2078 *isExact = true;
Neil Boothee7ae382007-11-01 22:43:37 +00002079 return opOK;
Dale Johannesen23a98552008-10-09 23:00:39 +00002080 } else
Neil Boothee7ae382007-11-01 22:43:37 +00002081 return opInexact;
2082}
2083
2084/* Same as convertToSignExtendedInteger, except we provide
2085 deterministic values in case of an invalid operation exception,
2086 namely zero for NaNs and the minimal or maximal value respectively
Dale Johannesen23a98552008-10-09 23:00:39 +00002087 for underflow or overflow.
2088 The *isExact output tells whether the result is exact, in the sense
2089 that converting it back to the original floating point type produces
2090 the original value. This is almost equivalent to result==opOK,
2091 except for negative zeroes.
2092*/
Neil Boothee7ae382007-11-01 22:43:37 +00002093APFloat::opStatus
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002094APFloat::convertToInteger(integerPart *parts, unsigned int width,
Neil Booth4f881702007-09-26 21:33:42 +00002095 bool isSigned,
Dale Johannesen23a98552008-10-09 23:00:39 +00002096 roundingMode rounding_mode, bool *isExact) const
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002097{
Neil Boothee7ae382007-11-01 22:43:37 +00002098 opStatus fs;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002099
Dan Gohman16e02092010-03-24 19:38:02 +00002100 fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode,
Dale Johannesen23a98552008-10-09 23:00:39 +00002101 isExact);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002102
Neil Boothee7ae382007-11-01 22:43:37 +00002103 if (fs == opInvalidOp) {
2104 unsigned int bits, dstPartsCount;
2105
2106 dstPartsCount = partCountForBits(width);
2107
2108 if (category == fcNaN)
2109 bits = 0;
2110 else if (sign)
2111 bits = isSigned;
2112 else
2113 bits = width - isSigned;
2114
2115 APInt::tcSetLeastSignificantBits(parts, dstPartsCount, bits);
2116 if (sign && isSigned)
2117 APInt::tcShiftLeft(parts, dstPartsCount, width - 1);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002118 }
2119
Neil Boothee7ae382007-11-01 22:43:37 +00002120 return fs;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002121}
2122
Jeffrey Yasskin3d42bfb2011-07-15 07:04:56 +00002123/* Same as convertToInteger(integerPart*, ...), except the result is returned in
2124 an APSInt, whose initial bit-width and signed-ness are used to determine the
2125 precision of the conversion.
2126 */
2127APFloat::opStatus
2128APFloat::convertToInteger(APSInt &result,
2129 roundingMode rounding_mode, bool *isExact) const
2130{
2131 unsigned bitWidth = result.getBitWidth();
2132 SmallVector<uint64_t, 4> parts(result.getNumWords());
2133 opStatus status = convertToInteger(
2134 parts.data(), bitWidth, result.isSigned(), rounding_mode, isExact);
2135 // Keeps the original signed-ness.
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00002136 result = APInt(bitWidth, parts);
Jeffrey Yasskin3d42bfb2011-07-15 07:04:56 +00002137 return status;
2138}
2139
Neil Booth643ce592007-10-07 12:07:53 +00002140/* Convert an unsigned integer SRC to a floating point number,
2141 rounding according to ROUNDING_MODE. The sign of the floating
2142 point number is not modified. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002143APFloat::opStatus
Neil Booth643ce592007-10-07 12:07:53 +00002144APFloat::convertFromUnsignedParts(const integerPart *src,
2145 unsigned int srcCount,
2146 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002147{
Neil Booth5477f852007-10-08 14:39:42 +00002148 unsigned int omsb, precision, dstCount;
Neil Booth643ce592007-10-07 12:07:53 +00002149 integerPart *dst;
Neil Booth5477f852007-10-08 14:39:42 +00002150 lostFraction lost_fraction;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002151
Neil Boothcaf19d72007-10-14 10:29:28 +00002152 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002153 category = fcNormal;
Neil Booth5477f852007-10-08 14:39:42 +00002154 omsb = APInt::tcMSB(src, srcCount) + 1;
Neil Booth643ce592007-10-07 12:07:53 +00002155 dst = significandParts();
2156 dstCount = partCount();
Neil Booth5477f852007-10-08 14:39:42 +00002157 precision = semantics->precision;
Neil Booth643ce592007-10-07 12:07:53 +00002158
Nick Lewycky03dd4e82011-10-03 21:30:08 +00002159 /* We want the most significant PRECISION bits of SRC. There may not
Neil Booth5477f852007-10-08 14:39:42 +00002160 be that many; extract what we can. */
2161 if (precision <= omsb) {
2162 exponent = omsb - 1;
Neil Booth643ce592007-10-07 12:07:53 +00002163 lost_fraction = lostFractionThroughTruncation(src, srcCount,
Neil Booth5477f852007-10-08 14:39:42 +00002164 omsb - precision);
2165 APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
2166 } else {
2167 exponent = precision - 1;
2168 lost_fraction = lfExactlyZero;
2169 APInt::tcExtract(dst, dstCount, src, omsb, 0);
Neil Booth643ce592007-10-07 12:07:53 +00002170 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002171
2172 return normalize(rounding_mode, lost_fraction);
2173}
2174
Dan Gohman93c276e2008-02-29 01:26:11 +00002175APFloat::opStatus
2176APFloat::convertFromAPInt(const APInt &Val,
2177 bool isSigned,
2178 roundingMode rounding_mode)
2179{
2180 unsigned int partCount = Val.getNumWords();
2181 APInt api = Val;
2182
2183 sign = false;
2184 if (isSigned && api.isNegative()) {
2185 sign = true;
2186 api = -api;
2187 }
2188
2189 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
2190}
2191
Neil Boothf16c5952007-10-07 12:15:41 +00002192/* Convert a two's complement integer SRC to a floating point number,
2193 rounding according to ROUNDING_MODE. ISSIGNED is true if the
2194 integer is signed, in which case it must be sign-extended. */
2195APFloat::opStatus
2196APFloat::convertFromSignExtendedInteger(const integerPart *src,
2197 unsigned int srcCount,
2198 bool isSigned,
2199 roundingMode rounding_mode)
2200{
2201 opStatus status;
2202
Neil Boothcaf19d72007-10-14 10:29:28 +00002203 assertArithmeticOK(*semantics);
Dan Gohman16e02092010-03-24 19:38:02 +00002204 if (isSigned &&
2205 APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) {
Neil Boothf16c5952007-10-07 12:15:41 +00002206 integerPart *copy;
2207
2208 /* If we're signed and negative negate a copy. */
2209 sign = true;
2210 copy = new integerPart[srcCount];
2211 APInt::tcAssign(copy, src, srcCount);
2212 APInt::tcNegate(copy, srcCount);
2213 status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
2214 delete [] copy;
2215 } else {
2216 sign = false;
2217 status = convertFromUnsignedParts(src, srcCount, rounding_mode);
2218 }
2219
2220 return status;
2221}
2222
Neil Boothccf596a2007-10-07 11:45:55 +00002223/* FIXME: should this just take a const APInt reference? */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002224APFloat::opStatus
Neil Boothccf596a2007-10-07 11:45:55 +00002225APFloat::convertFromZeroExtendedInteger(const integerPart *parts,
2226 unsigned int width, bool isSigned,
2227 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002228{
Dale Johannesen910993e2007-09-21 22:09:37 +00002229 unsigned int partCount = partCountForBits(width);
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00002230 APInt api = APInt(width, makeArrayRef(parts, partCount));
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002231
2232 sign = false;
Dan Gohman16e02092010-03-24 19:38:02 +00002233 if (isSigned && APInt::tcExtractBit(parts, width - 1)) {
Dale Johannesencce23a42007-09-30 18:17:01 +00002234 sign = true;
2235 api = -api;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002236 }
2237
Neil Booth7a7bc0f2007-10-07 12:10:57 +00002238 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002239}
2240
2241APFloat::opStatus
Benjamin Kramer38e59892010-07-14 22:38:02 +00002242APFloat::convertFromHexadecimalString(StringRef s, roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002243{
Erick Tryzelaarf8bc8012009-08-18 18:20:37 +00002244 lostFraction lost_fraction = lfExactlyZero;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002245 integerPart *significand;
2246 unsigned int bitPos, partsCount;
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002247 StringRef::iterator dot, firstSignificantDigit;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002248
2249 zeroSignificand();
2250 exponent = 0;
2251 category = fcNormal;
2252
2253 significand = significandParts();
2254 partsCount = partCount();
2255 bitPos = partsCount * integerPartWidth;
2256
Neil Booth33d4c922007-10-07 08:51:21 +00002257 /* Skip leading zeroes and any (hexa)decimal point. */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002258 StringRef::iterator begin = s.begin();
2259 StringRef::iterator end = s.end();
2260 StringRef::iterator p = skipLeadingZeroesAndAnyDot(begin, end, &dot);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002261 firstSignificantDigit = p;
2262
Dan Gohman16e02092010-03-24 19:38:02 +00002263 for (; p != end;) {
Dale Johannesen386f3e92008-05-14 22:53:25 +00002264 integerPart hex_value;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002265
Dan Gohman16e02092010-03-24 19:38:02 +00002266 if (*p == '.') {
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002267 assert(dot == end && "String contains multiple dots");
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002268 dot = p++;
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002269 if (p == end) {
2270 break;
2271 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002272 }
2273
2274 hex_value = hexDigitValue(*p);
Dan Gohman16e02092010-03-24 19:38:02 +00002275 if (hex_value == -1U) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002276 break;
2277 }
2278
2279 p++;
2280
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002281 if (p == end) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002282 break;
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002283 } else {
2284 /* Store the number whilst 4-bit nibbles remain. */
Dan Gohman16e02092010-03-24 19:38:02 +00002285 if (bitPos) {
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002286 bitPos -= 4;
2287 hex_value <<= bitPos % integerPartWidth;
2288 significand[bitPos / integerPartWidth] |= hex_value;
2289 } else {
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002290 lost_fraction = trailingHexadecimalFraction(p, end, hex_value);
Dan Gohman16e02092010-03-24 19:38:02 +00002291 while (p != end && hexDigitValue(*p) != -1U)
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002292 p++;
2293 break;
2294 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002295 }
2296 }
2297
2298 /* Hex floats require an exponent but not a hexadecimal point. */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002299 assert(p != end && "Hex strings require an exponent");
2300 assert((*p == 'p' || *p == 'P') && "Invalid character in significand");
2301 assert(p != begin && "Significand has no digits");
2302 assert((dot == end || p - begin != 1) && "Significand has no digits");
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002303
2304 /* Ignore the exponent if we are zero. */
Dan Gohman16e02092010-03-24 19:38:02 +00002305 if (p != firstSignificantDigit) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002306 int expAdjustment;
2307
2308 /* Implicit hexadecimal point? */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002309 if (dot == end)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002310 dot = p;
2311
2312 /* Calculate the exponent adjustment implicit in the number of
2313 significant digits. */
Evan Cheng48e8c802008-05-02 21:15:08 +00002314 expAdjustment = static_cast<int>(dot - firstSignificantDigit);
Dan Gohman16e02092010-03-24 19:38:02 +00002315 if (expAdjustment < 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002316 expAdjustment++;
2317 expAdjustment = expAdjustment * 4 - 1;
2318
2319 /* Adjust for writing the significand starting at the most
2320 significant nibble. */
2321 expAdjustment += semantics->precision;
2322 expAdjustment -= partsCount * integerPartWidth;
2323
2324 /* Adjust for the given exponent. */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002325 exponent = totalExponent(p + 1, end, expAdjustment);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002326 }
2327
2328 return normalize(rounding_mode, lost_fraction);
2329}
2330
2331APFloat::opStatus
Neil Booth96c74712007-10-12 16:02:31 +00002332APFloat::roundSignificandWithExponent(const integerPart *decSigParts,
2333 unsigned sigPartCount, int exp,
2334 roundingMode rounding_mode)
2335{
2336 unsigned int parts, pow5PartCount;
Neil Boothcaf19d72007-10-14 10:29:28 +00002337 fltSemantics calcSemantics = { 32767, -32767, 0, true };
Neil Booth96c74712007-10-12 16:02:31 +00002338 integerPart pow5Parts[maxPowerOfFiveParts];
2339 bool isNearest;
2340
Dan Gohman16e02092010-03-24 19:38:02 +00002341 isNearest = (rounding_mode == rmNearestTiesToEven ||
2342 rounding_mode == rmNearestTiesToAway);
Neil Booth96c74712007-10-12 16:02:31 +00002343
2344 parts = partCountForBits(semantics->precision + 11);
2345
2346 /* Calculate pow(5, abs(exp)). */
2347 pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp);
2348
2349 for (;; parts *= 2) {
2350 opStatus sigStatus, powStatus;
2351 unsigned int excessPrecision, truncatedBits;
2352
2353 calcSemantics.precision = parts * integerPartWidth - 1;
2354 excessPrecision = calcSemantics.precision - semantics->precision;
2355 truncatedBits = excessPrecision;
2356
2357 APFloat decSig(calcSemantics, fcZero, sign);
2358 APFloat pow5(calcSemantics, fcZero, false);
2359
2360 sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount,
2361 rmNearestTiesToEven);
2362 powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
2363 rmNearestTiesToEven);
2364 /* Add exp, as 10^n = 5^n * 2^n. */
2365 decSig.exponent += exp;
2366
2367 lostFraction calcLostFraction;
Evan Cheng48e8c802008-05-02 21:15:08 +00002368 integerPart HUerr, HUdistance;
2369 unsigned int powHUerr;
Neil Booth96c74712007-10-12 16:02:31 +00002370
2371 if (exp >= 0) {
2372 /* multiplySignificand leaves the precision-th bit set to 1. */
2373 calcLostFraction = decSig.multiplySignificand(pow5, NULL);
2374 powHUerr = powStatus != opOK;
2375 } else {
2376 calcLostFraction = decSig.divideSignificand(pow5);
2377 /* Denormal numbers have less precision. */
2378 if (decSig.exponent < semantics->minExponent) {
2379 excessPrecision += (semantics->minExponent - decSig.exponent);
2380 truncatedBits = excessPrecision;
2381 if (excessPrecision > calcSemantics.precision)
2382 excessPrecision = calcSemantics.precision;
2383 }
2384 /* Extra half-ulp lost in reciprocal of exponent. */
Evan Cheng48e8c802008-05-02 21:15:08 +00002385 powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2;
Neil Booth96c74712007-10-12 16:02:31 +00002386 }
2387
2388 /* Both multiplySignificand and divideSignificand return the
2389 result with the integer bit set. */
Evan Cheng99ebfa52009-10-27 21:35:42 +00002390 assert(APInt::tcExtractBit
2391 (decSig.significandParts(), calcSemantics.precision - 1) == 1);
Neil Booth96c74712007-10-12 16:02:31 +00002392
2393 HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK,
2394 powHUerr);
2395 HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
2396 excessPrecision, isNearest);
2397
2398 /* Are we guaranteed to round correctly if we truncate? */
2399 if (HUdistance >= HUerr) {
2400 APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
2401 calcSemantics.precision - excessPrecision,
2402 excessPrecision);
2403 /* Take the exponent of decSig. If we tcExtract-ed less bits
2404 above we must adjust our exponent to compensate for the
2405 implicit right shift. */
2406 exponent = (decSig.exponent + semantics->precision
2407 - (calcSemantics.precision - excessPrecision));
2408 calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(),
2409 decSig.partCount(),
2410 truncatedBits);
2411 return normalize(rounding_mode, calcLostFraction);
2412 }
2413 }
2414}
2415
2416APFloat::opStatus
Benjamin Kramer38e59892010-07-14 22:38:02 +00002417APFloat::convertFromDecimalString(StringRef str, roundingMode rounding_mode)
Neil Booth96c74712007-10-12 16:02:31 +00002418{
Neil Booth1870f292007-10-14 10:16:12 +00002419 decimalInfo D;
Neil Booth96c74712007-10-12 16:02:31 +00002420 opStatus fs;
2421
Neil Booth1870f292007-10-14 10:16:12 +00002422 /* Scan the text. */
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002423 StringRef::iterator p = str.begin();
2424 interpretDecimal(p, str.end(), &D);
Neil Booth96c74712007-10-12 16:02:31 +00002425
Neil Booth686700e2007-10-15 15:00:55 +00002426 /* Handle the quick cases. First the case of no significant digits,
2427 i.e. zero, and then exponents that are obviously too large or too
2428 small. Writing L for log 10 / log 2, a number d.ddddd*10^exp
2429 definitely overflows if
2430
2431 (exp - 1) * L >= maxExponent
2432
2433 and definitely underflows to zero where
2434
2435 (exp + 1) * L <= minExponent - precision
2436
2437 With integer arithmetic the tightest bounds for L are
2438
2439 93/28 < L < 196/59 [ numerator <= 256 ]
2440 42039/12655 < L < 28738/8651 [ numerator <= 65536 ]
2441 */
2442
Neil Boothcc233592007-12-05 13:06:04 +00002443 if (decDigitValue(*D.firstSigDigit) >= 10U) {
Neil Booth96c74712007-10-12 16:02:31 +00002444 category = fcZero;
2445 fs = opOK;
John McCall8b3f3302010-02-26 22:20:41 +00002446
2447 /* Check whether the normalized exponent is high enough to overflow
2448 max during the log-rebasing in the max-exponent check below. */
2449 } else if (D.normalizedExponent - 1 > INT_MAX / 42039) {
2450 fs = handleOverflow(rounding_mode);
2451
2452 /* If it wasn't, then it also wasn't high enough to overflow max
2453 during the log-rebasing in the min-exponent check. Check that it
2454 won't overflow min in either check, then perform the min-exponent
2455 check. */
2456 } else if (D.normalizedExponent - 1 < INT_MIN / 42039 ||
2457 (D.normalizedExponent + 1) * 28738 <=
2458 8651 * (semantics->minExponent - (int) semantics->precision)) {
Neil Booth686700e2007-10-15 15:00:55 +00002459 /* Underflow to zero and round. */
2460 zeroSignificand();
2461 fs = normalize(rounding_mode, lfLessThanHalf);
John McCall8b3f3302010-02-26 22:20:41 +00002462
2463 /* We can finally safely perform the max-exponent check. */
Neil Booth686700e2007-10-15 15:00:55 +00002464 } else if ((D.normalizedExponent - 1) * 42039
2465 >= 12655 * semantics->maxExponent) {
2466 /* Overflow and round. */
2467 fs = handleOverflow(rounding_mode);
Neil Booth96c74712007-10-12 16:02:31 +00002468 } else {
Neil Booth1870f292007-10-14 10:16:12 +00002469 integerPart *decSignificand;
2470 unsigned int partCount;
Neil Booth96c74712007-10-12 16:02:31 +00002471
Neil Booth1870f292007-10-14 10:16:12 +00002472 /* A tight upper bound on number of bits required to hold an
Neil Booth686700e2007-10-15 15:00:55 +00002473 N-digit decimal integer is N * 196 / 59. Allocate enough space
Neil Booth1870f292007-10-14 10:16:12 +00002474 to hold the full significand, and an extra part required by
2475 tcMultiplyPart. */
Evan Cheng48e8c802008-05-02 21:15:08 +00002476 partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1;
Neil Booth686700e2007-10-15 15:00:55 +00002477 partCount = partCountForBits(1 + 196 * partCount / 59);
Neil Booth1870f292007-10-14 10:16:12 +00002478 decSignificand = new integerPart[partCount + 1];
2479 partCount = 0;
Neil Booth96c74712007-10-12 16:02:31 +00002480
Neil Booth1870f292007-10-14 10:16:12 +00002481 /* Convert to binary efficiently - we do almost all multiplication
2482 in an integerPart. When this would overflow do we do a single
2483 bignum multiplication, and then revert again to multiplication
2484 in an integerPart. */
2485 do {
2486 integerPart decValue, val, multiplier;
2487
2488 val = 0;
2489 multiplier = 1;
2490
2491 do {
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002492 if (*p == '.') {
Neil Booth1870f292007-10-14 10:16:12 +00002493 p++;
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002494 if (p == str.end()) {
2495 break;
2496 }
2497 }
Neil Booth1870f292007-10-14 10:16:12 +00002498 decValue = decDigitValue(*p++);
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002499 assert(decValue < 10U && "Invalid character in significand");
Neil Booth1870f292007-10-14 10:16:12 +00002500 multiplier *= 10;
2501 val = val * 10 + decValue;
2502 /* The maximum number that can be multiplied by ten with any
2503 digit added without overflowing an integerPart. */
2504 } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
2505
2506 /* Multiply out the current part. */
2507 APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
2508 partCount, partCount + 1, false);
2509
2510 /* If we used another part (likely but not guaranteed), increase
2511 the count. */
2512 if (decSignificand[partCount])
2513 partCount++;
2514 } while (p <= D.lastSigDigit);
Neil Booth96c74712007-10-12 16:02:31 +00002515
Neil Booth43a4b282007-11-01 22:51:07 +00002516 category = fcNormal;
Neil Booth96c74712007-10-12 16:02:31 +00002517 fs = roundSignificandWithExponent(decSignificand, partCount,
Neil Booth1870f292007-10-14 10:16:12 +00002518 D.exponent, rounding_mode);
Neil Booth96c74712007-10-12 16:02:31 +00002519
Neil Booth1870f292007-10-14 10:16:12 +00002520 delete [] decSignificand;
2521 }
Neil Booth96c74712007-10-12 16:02:31 +00002522
2523 return fs;
2524}
2525
2526APFloat::opStatus
Benjamin Kramer38e59892010-07-14 22:38:02 +00002527APFloat::convertFromString(StringRef str, roundingMode rounding_mode)
Neil Booth4f881702007-09-26 21:33:42 +00002528{
Neil Boothcaf19d72007-10-14 10:29:28 +00002529 assertArithmeticOK(*semantics);
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002530 assert(!str.empty() && "Invalid string length");
Neil Boothcaf19d72007-10-14 10:29:28 +00002531
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002532 /* Handle a leading minus sign. */
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002533 StringRef::iterator p = str.begin();
2534 size_t slen = str.size();
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002535 sign = *p == '-' ? 1 : 0;
Dan Gohman16e02092010-03-24 19:38:02 +00002536 if (*p == '-' || *p == '+') {
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002537 p++;
2538 slen--;
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002539 assert(slen && "String has no digits");
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002540 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002541
Dan Gohman16e02092010-03-24 19:38:02 +00002542 if (slen >= 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002543 assert(slen - 2 && "Invalid string");
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002544 return convertFromHexadecimalString(StringRef(p + 2, slen - 2),
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002545 rounding_mode);
2546 }
Bill Wendlingb7c0d942008-11-27 08:00:12 +00002547
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002548 return convertFromDecimalString(StringRef(p, slen), rounding_mode);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002549}
Dale Johannesen343e7702007-08-24 00:56:33 +00002550
Neil Bootha30b0ee2007-10-03 22:26:02 +00002551/* Write out a hexadecimal representation of the floating point value
2552 to DST, which must be of sufficient size, in the C99 form
2553 [-]0xh.hhhhp[+-]d. Return the number of characters written,
2554 excluding the terminating NUL.
2555
2556 If UPPERCASE, the output is in upper case, otherwise in lower case.
2557
2558 HEXDIGITS digits appear altogether, rounding the value if
2559 necessary. If HEXDIGITS is 0, the minimal precision to display the
2560 number precisely is used instead. If nothing would appear after
2561 the decimal point it is suppressed.
2562
2563 The decimal exponent is always printed and has at least one digit.
2564 Zero values display an exponent of zero. Infinities and NaNs
2565 appear as "infinity" or "nan" respectively.
2566
2567 The above rules are as specified by C99. There is ambiguity about
2568 what the leading hexadecimal digit should be. This implementation
2569 uses whatever is necessary so that the exponent is displayed as
2570 stored. This implies the exponent will fall within the IEEE format
2571 range, and the leading hexadecimal digit will be 0 (for denormals),
2572 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
2573 any other digits zero).
2574*/
2575unsigned int
2576APFloat::convertToHexString(char *dst, unsigned int hexDigits,
2577 bool upperCase, roundingMode rounding_mode) const
2578{
2579 char *p;
2580
Neil Boothcaf19d72007-10-14 10:29:28 +00002581 assertArithmeticOK(*semantics);
2582
Neil Bootha30b0ee2007-10-03 22:26:02 +00002583 p = dst;
2584 if (sign)
2585 *dst++ = '-';
2586
2587 switch (category) {
2588 case fcInfinity:
2589 memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
2590 dst += sizeof infinityL - 1;
2591 break;
2592
2593 case fcNaN:
2594 memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
2595 dst += sizeof NaNU - 1;
2596 break;
2597
2598 case fcZero:
2599 *dst++ = '0';
2600 *dst++ = upperCase ? 'X': 'x';
2601 *dst++ = '0';
2602 if (hexDigits > 1) {
2603 *dst++ = '.';
2604 memset (dst, '0', hexDigits - 1);
2605 dst += hexDigits - 1;
2606 }
2607 *dst++ = upperCase ? 'P': 'p';
2608 *dst++ = '0';
2609 break;
2610
2611 case fcNormal:
2612 dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
2613 break;
2614 }
2615
2616 *dst = 0;
2617
Evan Cheng48e8c802008-05-02 21:15:08 +00002618 return static_cast<unsigned int>(dst - p);
Neil Bootha30b0ee2007-10-03 22:26:02 +00002619}
2620
2621/* Does the hard work of outputting the correctly rounded hexadecimal
2622 form of a normal floating point number with the specified number of
2623 hexadecimal digits. If HEXDIGITS is zero the minimum number of
2624 digits necessary to print the value precisely is output. */
2625char *
2626APFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
2627 bool upperCase,
2628 roundingMode rounding_mode) const
2629{
2630 unsigned int count, valueBits, shift, partsCount, outputDigits;
2631 const char *hexDigitChars;
2632 const integerPart *significand;
2633 char *p;
2634 bool roundUp;
2635
2636 *dst++ = '0';
2637 *dst++ = upperCase ? 'X': 'x';
2638
2639 roundUp = false;
2640 hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower;
2641
2642 significand = significandParts();
2643 partsCount = partCount();
2644
2645 /* +3 because the first digit only uses the single integer bit, so
2646 we have 3 virtual zero most-significant-bits. */
2647 valueBits = semantics->precision + 3;
2648 shift = integerPartWidth - valueBits % integerPartWidth;
2649
2650 /* The natural number of digits required ignoring trailing
2651 insignificant zeroes. */
2652 outputDigits = (valueBits - significandLSB () + 3) / 4;
2653
2654 /* hexDigits of zero means use the required number for the
2655 precision. Otherwise, see if we are truncating. If we are,
Neil Booth978661d2007-10-06 00:24:48 +00002656 find out if we need to round away from zero. */
Neil Bootha30b0ee2007-10-03 22:26:02 +00002657 if (hexDigits) {
2658 if (hexDigits < outputDigits) {
2659 /* We are dropping non-zero bits, so need to check how to round.
2660 "bits" is the number of dropped bits. */
2661 unsigned int bits;
2662 lostFraction fraction;
2663
2664 bits = valueBits - hexDigits * 4;
2665 fraction = lostFractionThroughTruncation (significand, partsCount, bits);
2666 roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
2667 }
2668 outputDigits = hexDigits;
2669 }
2670
2671 /* Write the digits consecutively, and start writing in the location
2672 of the hexadecimal point. We move the most significant digit
2673 left and add the hexadecimal point later. */
2674 p = ++dst;
2675
2676 count = (valueBits + integerPartWidth - 1) / integerPartWidth;
2677
2678 while (outputDigits && count) {
2679 integerPart part;
2680
2681 /* Put the most significant integerPartWidth bits in "part". */
2682 if (--count == partsCount)
2683 part = 0; /* An imaginary higher zero part. */
2684 else
2685 part = significand[count] << shift;
2686
2687 if (count && shift)
2688 part |= significand[count - 1] >> (integerPartWidth - shift);
2689
2690 /* Convert as much of "part" to hexdigits as we can. */
2691 unsigned int curDigits = integerPartWidth / 4;
2692
2693 if (curDigits > outputDigits)
2694 curDigits = outputDigits;
2695 dst += partAsHex (dst, part, curDigits, hexDigitChars);
2696 outputDigits -= curDigits;
2697 }
2698
2699 if (roundUp) {
2700 char *q = dst;
2701
2702 /* Note that hexDigitChars has a trailing '0'. */
2703 do {
2704 q--;
2705 *q = hexDigitChars[hexDigitValue (*q) + 1];
Neil Booth978661d2007-10-06 00:24:48 +00002706 } while (*q == '0');
Evan Cheng99ebfa52009-10-27 21:35:42 +00002707 assert(q >= p);
Neil Bootha30b0ee2007-10-03 22:26:02 +00002708 } else {
2709 /* Add trailing zeroes. */
2710 memset (dst, '0', outputDigits);
2711 dst += outputDigits;
2712 }
2713
2714 /* Move the most significant digit to before the point, and if there
2715 is something after the decimal point add it. This must come
2716 after rounding above. */
2717 p[-1] = p[0];
2718 if (dst -1 == p)
2719 dst--;
2720 else
2721 p[0] = '.';
2722
2723 /* Finally output the exponent. */
2724 *dst++ = upperCase ? 'P': 'p';
2725
Neil Booth92f7e8d2007-10-06 07:29:25 +00002726 return writeSignedDecimal (dst, exponent);
Neil Bootha30b0ee2007-10-03 22:26:02 +00002727}
2728
Chandler Carruthed7692a2012-03-04 12:02:57 +00002729hash_code llvm::hash_value(const APFloat &Arg) {
2730 if (Arg.category != APFloat::fcNormal)
2731 return hash_combine((uint8_t)Arg.category,
2732 // NaN has no sign, fix it at zero.
2733 Arg.isNaN() ? (uint8_t)0 : (uint8_t)Arg.sign,
2734 Arg.semantics->precision);
2735
2736 // Normal floats need their exponent and significand hashed.
2737 return hash_combine((uint8_t)Arg.category, (uint8_t)Arg.sign,
2738 Arg.semantics->precision, Arg.exponent,
2739 hash_combine_range(
2740 Arg.significandParts(),
2741 Arg.significandParts() + Arg.partCount()));
Dale Johannesen343e7702007-08-24 00:56:33 +00002742}
2743
2744// Conversion from APFloat to/from host float/double. It may eventually be
2745// possible to eliminate these and have everybody deal with APFloats, but that
2746// will take a while. This approach will not easily extend to long double.
Dale Johannesena72a5a02007-09-20 23:47:58 +00002747// Current implementation requires integerPartWidth==64, which is correct at
2748// the moment but could be made more general.
Dale Johannesen343e7702007-08-24 00:56:33 +00002749
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002750// Denormals have exponent minExponent in APFloat, but minExponent-1 in
Dale Johannesena72a5a02007-09-20 23:47:58 +00002751// the actual IEEE respresentations. We compensate for that here.
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002752
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002753APInt
Neil Booth4f881702007-09-26 21:33:42 +00002754APFloat::convertF80LongDoubleAPFloatToAPInt() const
2755{
Dan Gohmanb10abe12008-01-29 12:08:20 +00002756 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002757 assert(partCount()==2);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002758
2759 uint64_t myexponent, mysignificand;
2760
2761 if (category==fcNormal) {
2762 myexponent = exponent+16383; //bias
Dale Johannesena72a5a02007-09-20 23:47:58 +00002763 mysignificand = significandParts()[0];
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002764 if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
2765 myexponent = 0; // denormal
2766 } else if (category==fcZero) {
2767 myexponent = 0;
2768 mysignificand = 0;
2769 } else if (category==fcInfinity) {
2770 myexponent = 0x7fff;
2771 mysignificand = 0x8000000000000000ULL;
Chris Lattnera11ef822007-10-06 06:13:42 +00002772 } else {
2773 assert(category == fcNaN && "Unknown category");
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002774 myexponent = 0x7fff;
Dale Johannesena72a5a02007-09-20 23:47:58 +00002775 mysignificand = significandParts()[0];
Chris Lattnera11ef822007-10-06 06:13:42 +00002776 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002777
2778 uint64_t words[2];
Dale Johannesen1b25cb22009-03-23 21:16:53 +00002779 words[0] = mysignificand;
2780 words[1] = ((uint64_t)(sign & 1) << 15) |
2781 (myexponent & 0x7fffLL);
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00002782 return APInt(80, words);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002783}
2784
2785APInt
Dale Johannesena471c2e2007-10-11 18:07:22 +00002786APFloat::convertPPCDoubleDoubleAPFloatToAPInt() const
2787{
Dan Gohmanb10abe12008-01-29 12:08:20 +00002788 assert(semantics == (const llvm::fltSemantics*)&PPCDoubleDouble);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002789 assert(partCount()==2);
Dale Johannesena471c2e2007-10-11 18:07:22 +00002790
2791 uint64_t myexponent, mysignificand, myexponent2, mysignificand2;
2792
2793 if (category==fcNormal) {
2794 myexponent = exponent + 1023; //bias
2795 myexponent2 = exponent2 + 1023;
2796 mysignificand = significandParts()[0];
2797 mysignificand2 = significandParts()[1];
2798 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2799 myexponent = 0; // denormal
2800 if (myexponent2==1 && !(mysignificand2 & 0x10000000000000LL))
2801 myexponent2 = 0; // denormal
2802 } else if (category==fcZero) {
2803 myexponent = 0;
2804 mysignificand = 0;
2805 myexponent2 = 0;
2806 mysignificand2 = 0;
2807 } else if (category==fcInfinity) {
2808 myexponent = 0x7ff;
2809 myexponent2 = 0;
2810 mysignificand = 0;
2811 mysignificand2 = 0;
2812 } else {
2813 assert(category == fcNaN && "Unknown category");
2814 myexponent = 0x7ff;
2815 mysignificand = significandParts()[0];
2816 myexponent2 = exponent2;
2817 mysignificand2 = significandParts()[1];
2818 }
2819
2820 uint64_t words[2];
Evan Cheng48e8c802008-05-02 21:15:08 +00002821 words[0] = ((uint64_t)(sign & 1) << 63) |
Dale Johannesena471c2e2007-10-11 18:07:22 +00002822 ((myexponent & 0x7ff) << 52) |
2823 (mysignificand & 0xfffffffffffffLL);
Evan Cheng48e8c802008-05-02 21:15:08 +00002824 words[1] = ((uint64_t)(sign2 & 1) << 63) |
Dale Johannesena471c2e2007-10-11 18:07:22 +00002825 ((myexponent2 & 0x7ff) << 52) |
2826 (mysignificand2 & 0xfffffffffffffLL);
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00002827 return APInt(128, words);
Dale Johannesena471c2e2007-10-11 18:07:22 +00002828}
2829
2830APInt
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002831APFloat::convertQuadrupleAPFloatToAPInt() const
2832{
2833 assert(semantics == (const llvm::fltSemantics*)&IEEEquad);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002834 assert(partCount()==2);
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002835
2836 uint64_t myexponent, mysignificand, mysignificand2;
2837
2838 if (category==fcNormal) {
2839 myexponent = exponent+16383; //bias
2840 mysignificand = significandParts()[0];
2841 mysignificand2 = significandParts()[1];
2842 if (myexponent==1 && !(mysignificand2 & 0x1000000000000LL))
2843 myexponent = 0; // denormal
2844 } else if (category==fcZero) {
2845 myexponent = 0;
2846 mysignificand = mysignificand2 = 0;
2847 } else if (category==fcInfinity) {
2848 myexponent = 0x7fff;
2849 mysignificand = mysignificand2 = 0;
2850 } else {
2851 assert(category == fcNaN && "Unknown category!");
2852 myexponent = 0x7fff;
2853 mysignificand = significandParts()[0];
2854 mysignificand2 = significandParts()[1];
2855 }
2856
2857 uint64_t words[2];
2858 words[0] = mysignificand;
2859 words[1] = ((uint64_t)(sign & 1) << 63) |
2860 ((myexponent & 0x7fff) << 48) |
Anton Korobeynikov4755e992009-08-21 23:09:47 +00002861 (mysignificand2 & 0xffffffffffffLL);
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002862
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00002863 return APInt(128, words);
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002864}
2865
2866APInt
Neil Booth4f881702007-09-26 21:33:42 +00002867APFloat::convertDoubleAPFloatToAPInt() const
2868{
Dan Gohmancb648f92007-09-14 20:08:19 +00002869 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002870 assert(partCount()==1);
Dale Johannesen343e7702007-08-24 00:56:33 +00002871
Dale Johanneseneaf08942007-08-31 04:03:46 +00002872 uint64_t myexponent, mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00002873
2874 if (category==fcNormal) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002875 myexponent = exponent+1023; //bias
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002876 mysignificand = *significandParts();
2877 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2878 myexponent = 0; // denormal
Dale Johannesen343e7702007-08-24 00:56:33 +00002879 } else if (category==fcZero) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002880 myexponent = 0;
2881 mysignificand = 0;
2882 } else if (category==fcInfinity) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002883 myexponent = 0x7ff;
2884 mysignificand = 0;
Chris Lattnera11ef822007-10-06 06:13:42 +00002885 } else {
2886 assert(category == fcNaN && "Unknown category!");
Dale Johannesen343e7702007-08-24 00:56:33 +00002887 myexponent = 0x7ff;
Dale Johanneseneaf08942007-08-31 04:03:46 +00002888 mysignificand = *significandParts();
Chris Lattnera11ef822007-10-06 06:13:42 +00002889 }
Dale Johannesen343e7702007-08-24 00:56:33 +00002890
Evan Cheng48e8c802008-05-02 21:15:08 +00002891 return APInt(64, ((((uint64_t)(sign & 1) << 63) |
Chris Lattnera11ef822007-10-06 06:13:42 +00002892 ((myexponent & 0x7ff) << 52) |
2893 (mysignificand & 0xfffffffffffffLL))));
Dale Johannesen343e7702007-08-24 00:56:33 +00002894}
2895
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002896APInt
Neil Booth4f881702007-09-26 21:33:42 +00002897APFloat::convertFloatAPFloatToAPInt() const
2898{
Dan Gohmancb648f92007-09-14 20:08:19 +00002899 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002900 assert(partCount()==1);
Neil Booth4f881702007-09-26 21:33:42 +00002901
Dale Johanneseneaf08942007-08-31 04:03:46 +00002902 uint32_t myexponent, mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00002903
2904 if (category==fcNormal) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002905 myexponent = exponent+127; //bias
Evan Cheng48e8c802008-05-02 21:15:08 +00002906 mysignificand = (uint32_t)*significandParts();
Dale Johannesend0763b92007-11-17 01:02:27 +00002907 if (myexponent == 1 && !(mysignificand & 0x800000))
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002908 myexponent = 0; // denormal
Dale Johannesen343e7702007-08-24 00:56:33 +00002909 } else if (category==fcZero) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002910 myexponent = 0;
2911 mysignificand = 0;
2912 } else if (category==fcInfinity) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002913 myexponent = 0xff;
2914 mysignificand = 0;
Chris Lattnera11ef822007-10-06 06:13:42 +00002915 } else {
2916 assert(category == fcNaN && "Unknown category!");
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002917 myexponent = 0xff;
Evan Cheng48e8c802008-05-02 21:15:08 +00002918 mysignificand = (uint32_t)*significandParts();
Chris Lattnera11ef822007-10-06 06:13:42 +00002919 }
Dale Johannesen343e7702007-08-24 00:56:33 +00002920
Chris Lattnera11ef822007-10-06 06:13:42 +00002921 return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) |
2922 (mysignificand & 0x7fffff)));
Dale Johannesen343e7702007-08-24 00:56:33 +00002923}
2924
Chris Lattnercc4287a2009-10-16 02:13:51 +00002925APInt
2926APFloat::convertHalfAPFloatToAPInt() const
2927{
2928 assert(semantics == (const llvm::fltSemantics*)&IEEEhalf);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002929 assert(partCount()==1);
Chris Lattnercc4287a2009-10-16 02:13:51 +00002930
2931 uint32_t myexponent, mysignificand;
2932
2933 if (category==fcNormal) {
2934 myexponent = exponent+15; //bias
2935 mysignificand = (uint32_t)*significandParts();
2936 if (myexponent == 1 && !(mysignificand & 0x400))
2937 myexponent = 0; // denormal
2938 } else if (category==fcZero) {
2939 myexponent = 0;
2940 mysignificand = 0;
2941 } else if (category==fcInfinity) {
Dale Johannesena223aed2009-10-23 04:02:51 +00002942 myexponent = 0x1f;
Chris Lattnercc4287a2009-10-16 02:13:51 +00002943 mysignificand = 0;
2944 } else {
2945 assert(category == fcNaN && "Unknown category!");
Dale Johannesena223aed2009-10-23 04:02:51 +00002946 myexponent = 0x1f;
Chris Lattnercc4287a2009-10-16 02:13:51 +00002947 mysignificand = (uint32_t)*significandParts();
2948 }
2949
2950 return APInt(16, (((sign&1) << 15) | ((myexponent&0x1f) << 10) |
2951 (mysignificand & 0x3ff)));
2952}
2953
Dale Johannesena471c2e2007-10-11 18:07:22 +00002954// This function creates an APInt that is just a bit map of the floating
2955// point constant as it would appear in memory. It is not a conversion,
2956// and treating the result as a normal integer is unlikely to be useful.
2957
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002958APInt
Dale Johannesen7111b022008-10-09 18:53:47 +00002959APFloat::bitcastToAPInt() const
Neil Booth4f881702007-09-26 21:33:42 +00002960{
Chris Lattnercc4287a2009-10-16 02:13:51 +00002961 if (semantics == (const llvm::fltSemantics*)&IEEEhalf)
2962 return convertHalfAPFloatToAPInt();
2963
Dan Gohmanb10abe12008-01-29 12:08:20 +00002964 if (semantics == (const llvm::fltSemantics*)&IEEEsingle)
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002965 return convertFloatAPFloatToAPInt();
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002966
Dan Gohmanb10abe12008-01-29 12:08:20 +00002967 if (semantics == (const llvm::fltSemantics*)&IEEEdouble)
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002968 return convertDoubleAPFloatToAPInt();
Neil Booth4f881702007-09-26 21:33:42 +00002969
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002970 if (semantics == (const llvm::fltSemantics*)&IEEEquad)
2971 return convertQuadrupleAPFloatToAPInt();
2972
Dan Gohmanb10abe12008-01-29 12:08:20 +00002973 if (semantics == (const llvm::fltSemantics*)&PPCDoubleDouble)
Dale Johannesena471c2e2007-10-11 18:07:22 +00002974 return convertPPCDoubleDoubleAPFloatToAPInt();
2975
Dan Gohmanb10abe12008-01-29 12:08:20 +00002976 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended &&
Chris Lattnera11ef822007-10-06 06:13:42 +00002977 "unknown format!");
2978 return convertF80LongDoubleAPFloatToAPInt();
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002979}
2980
Neil Booth4f881702007-09-26 21:33:42 +00002981float
2982APFloat::convertToFloat() const
2983{
Chris Lattnerad785002009-09-24 21:44:20 +00002984 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle &&
2985 "Float semantics are not IEEEsingle");
Dale Johannesen7111b022008-10-09 18:53:47 +00002986 APInt api = bitcastToAPInt();
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002987 return api.bitsToFloat();
2988}
2989
Neil Booth4f881702007-09-26 21:33:42 +00002990double
2991APFloat::convertToDouble() const
2992{
Chris Lattnerad785002009-09-24 21:44:20 +00002993 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble &&
2994 "Float semantics are not IEEEdouble");
Dale Johannesen7111b022008-10-09 18:53:47 +00002995 APInt api = bitcastToAPInt();
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002996 return api.bitsToDouble();
2997}
2998
Dale Johannesend3d8ce32008-10-06 18:22:29 +00002999/// Integer bit is explicit in this format. Intel hardware (387 and later)
3000/// does not support these bit patterns:
3001/// exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity")
3002/// exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN")
3003/// exponent = 0, integer bit 1 ("pseudodenormal")
3004/// exponent!=0 nor all 1's, integer bit 0 ("unnormal")
3005/// At the moment, the first two are treated as NaNs, the second two as Normal.
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003006void
Neil Booth4f881702007-09-26 21:33:42 +00003007APFloat::initFromF80LongDoubleAPInt(const APInt &api)
3008{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003009 assert(api.getBitWidth()==80);
3010 uint64_t i1 = api.getRawData()[0];
3011 uint64_t i2 = api.getRawData()[1];
Dale Johannesen1b25cb22009-03-23 21:16:53 +00003012 uint64_t myexponent = (i2 & 0x7fff);
3013 uint64_t mysignificand = i1;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003014
3015 initialize(&APFloat::x87DoubleExtended);
Dale Johannesena72a5a02007-09-20 23:47:58 +00003016 assert(partCount()==2);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003017
Dale Johannesen1b25cb22009-03-23 21:16:53 +00003018 sign = static_cast<unsigned int>(i2>>15);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003019 if (myexponent==0 && mysignificand==0) {
3020 // exponent, significand meaningless
3021 category = fcZero;
3022 } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
3023 // exponent, significand meaningless
3024 category = fcInfinity;
3025 } else if (myexponent==0x7fff && mysignificand!=0x8000000000000000ULL) {
3026 // exponent meaningless
3027 category = fcNaN;
Dale Johannesena72a5a02007-09-20 23:47:58 +00003028 significandParts()[0] = mysignificand;
3029 significandParts()[1] = 0;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003030 } else {
3031 category = fcNormal;
3032 exponent = myexponent - 16383;
Dale Johannesena72a5a02007-09-20 23:47:58 +00003033 significandParts()[0] = mysignificand;
3034 significandParts()[1] = 0;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003035 if (myexponent==0) // denormal
3036 exponent = -16382;
Neil Booth4f881702007-09-26 21:33:42 +00003037 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003038}
3039
3040void
Dale Johannesena471c2e2007-10-11 18:07:22 +00003041APFloat::initFromPPCDoubleDoubleAPInt(const APInt &api)
3042{
3043 assert(api.getBitWidth()==128);
3044 uint64_t i1 = api.getRawData()[0];
3045 uint64_t i2 = api.getRawData()[1];
3046 uint64_t myexponent = (i1 >> 52) & 0x7ff;
3047 uint64_t mysignificand = i1 & 0xfffffffffffffLL;
3048 uint64_t myexponent2 = (i2 >> 52) & 0x7ff;
3049 uint64_t mysignificand2 = i2 & 0xfffffffffffffLL;
3050
3051 initialize(&APFloat::PPCDoubleDouble);
3052 assert(partCount()==2);
3053
Evan Cheng48e8c802008-05-02 21:15:08 +00003054 sign = static_cast<unsigned int>(i1>>63);
3055 sign2 = static_cast<unsigned int>(i2>>63);
Dale Johannesena471c2e2007-10-11 18:07:22 +00003056 if (myexponent==0 && mysignificand==0) {
3057 // exponent, significand meaningless
3058 // exponent2 and significand2 are required to be 0; we don't check
3059 category = fcZero;
3060 } else if (myexponent==0x7ff && mysignificand==0) {
3061 // exponent, significand meaningless
3062 // exponent2 and significand2 are required to be 0; we don't check
3063 category = fcInfinity;
3064 } else if (myexponent==0x7ff && mysignificand!=0) {
Dan Gohman16e02092010-03-24 19:38:02 +00003065 // exponent meaningless. So is the whole second word, but keep it
Dale Johannesena471c2e2007-10-11 18:07:22 +00003066 // for determinism.
3067 category = fcNaN;
3068 exponent2 = myexponent2;
3069 significandParts()[0] = mysignificand;
3070 significandParts()[1] = mysignificand2;
3071 } else {
3072 category = fcNormal;
3073 // Note there is no category2; the second word is treated as if it is
3074 // fcNormal, although it might be something else considered by itself.
3075 exponent = myexponent - 1023;
3076 exponent2 = myexponent2 - 1023;
3077 significandParts()[0] = mysignificand;
3078 significandParts()[1] = mysignificand2;
3079 if (myexponent==0) // denormal
3080 exponent = -1022;
3081 else
3082 significandParts()[0] |= 0x10000000000000LL; // integer bit
Dan Gohman16e02092010-03-24 19:38:02 +00003083 if (myexponent2==0)
Dale Johannesena471c2e2007-10-11 18:07:22 +00003084 exponent2 = -1022;
3085 else
3086 significandParts()[1] |= 0x10000000000000LL; // integer bit
3087 }
3088}
3089
3090void
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00003091APFloat::initFromQuadrupleAPInt(const APInt &api)
3092{
3093 assert(api.getBitWidth()==128);
3094 uint64_t i1 = api.getRawData()[0];
3095 uint64_t i2 = api.getRawData()[1];
3096 uint64_t myexponent = (i2 >> 48) & 0x7fff;
3097 uint64_t mysignificand = i1;
3098 uint64_t mysignificand2 = i2 & 0xffffffffffffLL;
3099
3100 initialize(&APFloat::IEEEquad);
3101 assert(partCount()==2);
3102
3103 sign = static_cast<unsigned int>(i2>>63);
3104 if (myexponent==0 &&
3105 (mysignificand==0 && mysignificand2==0)) {
3106 // exponent, significand meaningless
3107 category = fcZero;
3108 } else if (myexponent==0x7fff &&
3109 (mysignificand==0 && mysignificand2==0)) {
3110 // exponent, significand meaningless
3111 category = fcInfinity;
3112 } else if (myexponent==0x7fff &&
3113 (mysignificand!=0 || mysignificand2 !=0)) {
3114 // exponent meaningless
3115 category = fcNaN;
3116 significandParts()[0] = mysignificand;
3117 significandParts()[1] = mysignificand2;
3118 } else {
3119 category = fcNormal;
3120 exponent = myexponent - 16383;
3121 significandParts()[0] = mysignificand;
3122 significandParts()[1] = mysignificand2;
3123 if (myexponent==0) // denormal
3124 exponent = -16382;
3125 else
3126 significandParts()[1] |= 0x1000000000000LL; // integer bit
3127 }
3128}
3129
3130void
Neil Booth4f881702007-09-26 21:33:42 +00003131APFloat::initFromDoubleAPInt(const APInt &api)
3132{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003133 assert(api.getBitWidth()==64);
3134 uint64_t i = *api.getRawData();
Dale Johannesend3b51fd2007-08-24 05:08:11 +00003135 uint64_t myexponent = (i >> 52) & 0x7ff;
3136 uint64_t mysignificand = i & 0xfffffffffffffLL;
3137
Dale Johannesen343e7702007-08-24 00:56:33 +00003138 initialize(&APFloat::IEEEdouble);
Dale Johannesen343e7702007-08-24 00:56:33 +00003139 assert(partCount()==1);
3140
Evan Cheng48e8c802008-05-02 21:15:08 +00003141 sign = static_cast<unsigned int>(i>>63);
Dale Johannesen343e7702007-08-24 00:56:33 +00003142 if (myexponent==0 && mysignificand==0) {
3143 // exponent, significand meaningless
3144 category = fcZero;
Dale Johannesen343e7702007-08-24 00:56:33 +00003145 } else if (myexponent==0x7ff && mysignificand==0) {
3146 // exponent, significand meaningless
3147 category = fcInfinity;
Dale Johanneseneaf08942007-08-31 04:03:46 +00003148 } else if (myexponent==0x7ff && mysignificand!=0) {
3149 // exponent meaningless
3150 category = fcNaN;
3151 *significandParts() = mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00003152 } else {
Dale Johannesen343e7702007-08-24 00:56:33 +00003153 category = fcNormal;
3154 exponent = myexponent - 1023;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00003155 *significandParts() = mysignificand;
3156 if (myexponent==0) // denormal
3157 exponent = -1022;
3158 else
3159 *significandParts() |= 0x10000000000000LL; // integer bit
Neil Booth4f881702007-09-26 21:33:42 +00003160 }
Dale Johannesen343e7702007-08-24 00:56:33 +00003161}
3162
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003163void
Neil Booth4f881702007-09-26 21:33:42 +00003164APFloat::initFromFloatAPInt(const APInt & api)
3165{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003166 assert(api.getBitWidth()==32);
3167 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesend3b51fd2007-08-24 05:08:11 +00003168 uint32_t myexponent = (i >> 23) & 0xff;
3169 uint32_t mysignificand = i & 0x7fffff;
3170
Dale Johannesen343e7702007-08-24 00:56:33 +00003171 initialize(&APFloat::IEEEsingle);
Dale Johannesen343e7702007-08-24 00:56:33 +00003172 assert(partCount()==1);
3173
Dale Johanneseneaf08942007-08-31 04:03:46 +00003174 sign = i >> 31;
Dale Johannesen343e7702007-08-24 00:56:33 +00003175 if (myexponent==0 && mysignificand==0) {
3176 // exponent, significand meaningless
3177 category = fcZero;
Dale Johannesen343e7702007-08-24 00:56:33 +00003178 } else if (myexponent==0xff && mysignificand==0) {
3179 // exponent, significand meaningless
3180 category = fcInfinity;
Dale Johannesen902ff942007-09-25 17:25:00 +00003181 } else if (myexponent==0xff && mysignificand!=0) {
Dale Johannesen343e7702007-08-24 00:56:33 +00003182 // sign, exponent, significand meaningless
Dale Johanneseneaf08942007-08-31 04:03:46 +00003183 category = fcNaN;
3184 *significandParts() = mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00003185 } else {
3186 category = fcNormal;
Dale Johannesen343e7702007-08-24 00:56:33 +00003187 exponent = myexponent - 127; //bias
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00003188 *significandParts() = mysignificand;
3189 if (myexponent==0) // denormal
3190 exponent = -126;
3191 else
3192 *significandParts() |= 0x800000; // integer bit
Dale Johannesen343e7702007-08-24 00:56:33 +00003193 }
3194}
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003195
Chris Lattnercc4287a2009-10-16 02:13:51 +00003196void
3197APFloat::initFromHalfAPInt(const APInt & api)
3198{
3199 assert(api.getBitWidth()==16);
3200 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesena223aed2009-10-23 04:02:51 +00003201 uint32_t myexponent = (i >> 10) & 0x1f;
Chris Lattnercc4287a2009-10-16 02:13:51 +00003202 uint32_t mysignificand = i & 0x3ff;
3203
3204 initialize(&APFloat::IEEEhalf);
3205 assert(partCount()==1);
3206
3207 sign = i >> 15;
3208 if (myexponent==0 && mysignificand==0) {
3209 // exponent, significand meaningless
3210 category = fcZero;
3211 } else if (myexponent==0x1f && mysignificand==0) {
3212 // exponent, significand meaningless
3213 category = fcInfinity;
3214 } else if (myexponent==0x1f && mysignificand!=0) {
3215 // sign, exponent, significand meaningless
3216 category = fcNaN;
3217 *significandParts() = mysignificand;
3218 } else {
3219 category = fcNormal;
3220 exponent = myexponent - 15; //bias
3221 *significandParts() = mysignificand;
3222 if (myexponent==0) // denormal
3223 exponent = -14;
3224 else
3225 *significandParts() |= 0x400; // integer bit
3226 }
3227}
3228
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003229/// Treat api as containing the bits of a floating point number. Currently
Dale Johannesena471c2e2007-10-11 18:07:22 +00003230/// we infer the floating point type from the size of the APInt. The
3231/// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful
3232/// when the size is anything else).
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003233void
Dale Johannesena471c2e2007-10-11 18:07:22 +00003234APFloat::initFromAPInt(const APInt& api, bool isIEEE)
Neil Booth4f881702007-09-26 21:33:42 +00003235{
Chris Lattnercc4287a2009-10-16 02:13:51 +00003236 if (api.getBitWidth() == 16)
3237 return initFromHalfAPInt(api);
3238 else if (api.getBitWidth() == 32)
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003239 return initFromFloatAPInt(api);
3240 else if (api.getBitWidth()==64)
3241 return initFromDoubleAPInt(api);
3242 else if (api.getBitWidth()==80)
3243 return initFromF80LongDoubleAPInt(api);
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00003244 else if (api.getBitWidth()==128)
3245 return (isIEEE ?
3246 initFromQuadrupleAPInt(api) : initFromPPCDoubleDoubleAPInt(api));
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003247 else
Torok Edwinc23197a2009-07-14 16:55:14 +00003248 llvm_unreachable(0);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003249}
3250
Nadav Rotem093399c2011-02-17 21:22:27 +00003251APFloat
3252APFloat::getAllOnesValue(unsigned BitWidth, bool isIEEE)
3253{
3254 return APFloat(APInt::getAllOnesValue(BitWidth), isIEEE);
3255}
3256
John McCall00e65de2009-12-24 08:56:26 +00003257APFloat APFloat::getLargest(const fltSemantics &Sem, bool Negative) {
3258 APFloat Val(Sem, fcNormal, Negative);
3259
3260 // We want (in interchange format):
3261 // sign = {Negative}
3262 // exponent = 1..10
3263 // significand = 1..1
3264
3265 Val.exponent = Sem.maxExponent; // unbiased
3266
3267 // 1-initialize all bits....
3268 Val.zeroSignificand();
3269 integerPart *significand = Val.significandParts();
3270 unsigned N = partCountForBits(Sem.precision);
3271 for (unsigned i = 0; i != N; ++i)
3272 significand[i] = ~((integerPart) 0);
3273
3274 // ...and then clear the top bits for internal consistency.
Eli Friedman7247a5f2011-10-12 21:51:36 +00003275 if (Sem.precision % integerPartWidth != 0)
3276 significand[N-1] &=
3277 (((integerPart) 1) << (Sem.precision % integerPartWidth)) - 1;
John McCall00e65de2009-12-24 08:56:26 +00003278
3279 return Val;
3280}
3281
3282APFloat APFloat::getSmallest(const fltSemantics &Sem, bool Negative) {
3283 APFloat Val(Sem, fcNormal, Negative);
3284
3285 // We want (in interchange format):
3286 // sign = {Negative}
3287 // exponent = 0..0
3288 // significand = 0..01
3289
3290 Val.exponent = Sem.minExponent; // unbiased
3291 Val.zeroSignificand();
3292 Val.significandParts()[0] = 1;
3293 return Val;
3294}
3295
3296APFloat APFloat::getSmallestNormalized(const fltSemantics &Sem, bool Negative) {
3297 APFloat Val(Sem, fcNormal, Negative);
3298
3299 // We want (in interchange format):
3300 // sign = {Negative}
3301 // exponent = 0..0
3302 // significand = 10..0
3303
3304 Val.exponent = Sem.minExponent;
3305 Val.zeroSignificand();
Dan Gohman16e02092010-03-24 19:38:02 +00003306 Val.significandParts()[partCountForBits(Sem.precision)-1] |=
Eli Friedman90196fc2011-10-12 21:56:19 +00003307 (((integerPart) 1) << ((Sem.precision - 1) % integerPartWidth));
John McCall00e65de2009-12-24 08:56:26 +00003308
3309 return Val;
3310}
3311
Bill Wendlingf09a8b52011-03-18 09:09:44 +00003312APFloat::APFloat(const APInt& api, bool isIEEE) : exponent2(0), sign2(0) {
Dale Johannesena471c2e2007-10-11 18:07:22 +00003313 initFromAPInt(api, isIEEE);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003314}
3315
Bill Wendlingf09a8b52011-03-18 09:09:44 +00003316APFloat::APFloat(float f) : exponent2(0), sign2(0) {
Jay Foade4d19c92010-11-28 21:04:48 +00003317 initFromAPInt(APInt::floatToBits(f));
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003318}
3319
Bill Wendlingf09a8b52011-03-18 09:09:44 +00003320APFloat::APFloat(double d) : exponent2(0), sign2(0) {
Jay Foade4d19c92010-11-28 21:04:48 +00003321 initFromAPInt(APInt::doubleToBits(d));
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003322}
John McCall00e65de2009-12-24 08:56:26 +00003323
3324namespace {
David Blaikie9f14ed12012-07-25 18:04:24 +00003325 void append(SmallVectorImpl<char> &Buffer, StringRef Str) {
3326 Buffer.append(Str.begin(), Str.end());
John McCall00e65de2009-12-24 08:56:26 +00003327 }
3328
John McCall003a09c2009-12-24 12:16:56 +00003329 /// Removes data from the given significand until it is no more
3330 /// precise than is required for the desired precision.
3331 void AdjustToPrecision(APInt &significand,
3332 int &exp, unsigned FormatPrecision) {
3333 unsigned bits = significand.getActiveBits();
3334
3335 // 196/59 is a very slight overestimate of lg_2(10).
3336 unsigned bitsRequired = (FormatPrecision * 196 + 58) / 59;
3337
3338 if (bits <= bitsRequired) return;
3339
3340 unsigned tensRemovable = (bits - bitsRequired) * 59 / 196;
3341 if (!tensRemovable) return;
3342
3343 exp += tensRemovable;
3344
3345 APInt divisor(significand.getBitWidth(), 1);
3346 APInt powten(significand.getBitWidth(), 10);
3347 while (true) {
3348 if (tensRemovable & 1)
3349 divisor *= powten;
3350 tensRemovable >>= 1;
3351 if (!tensRemovable) break;
3352 powten *= powten;
3353 }
3354
3355 significand = significand.udiv(divisor);
3356
3357 // Truncate the significand down to its active bit count, but
3358 // don't try to drop below 32.
John McCall6a09aff2009-12-24 23:18:09 +00003359 unsigned newPrecision = std::max(32U, significand.getActiveBits());
Jay Foad40f8f622010-12-07 08:25:19 +00003360 significand = significand.trunc(newPrecision);
John McCall003a09c2009-12-24 12:16:56 +00003361 }
3362
3363
John McCall00e65de2009-12-24 08:56:26 +00003364 void AdjustToPrecision(SmallVectorImpl<char> &buffer,
3365 int &exp, unsigned FormatPrecision) {
3366 unsigned N = buffer.size();
3367 if (N <= FormatPrecision) return;
3368
3369 // The most significant figures are the last ones in the buffer.
3370 unsigned FirstSignificant = N - FormatPrecision;
3371
3372 // Round.
3373 // FIXME: this probably shouldn't use 'round half up'.
3374
3375 // Rounding down is just a truncation, except we also want to drop
3376 // trailing zeros from the new result.
3377 if (buffer[FirstSignificant - 1] < '5') {
NAKAMURA Takumi752b2f02012-02-19 03:18:29 +00003378 while (FirstSignificant < N && buffer[FirstSignificant] == '0')
John McCall00e65de2009-12-24 08:56:26 +00003379 FirstSignificant++;
3380
3381 exp += FirstSignificant;
3382 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3383 return;
3384 }
3385
3386 // Rounding up requires a decimal add-with-carry. If we continue
3387 // the carry, the newly-introduced zeros will just be truncated.
3388 for (unsigned I = FirstSignificant; I != N; ++I) {
3389 if (buffer[I] == '9') {
3390 FirstSignificant++;
3391 } else {
3392 buffer[I]++;
3393 break;
3394 }
3395 }
3396
3397 // If we carried through, we have exactly one digit of precision.
3398 if (FirstSignificant == N) {
3399 exp += FirstSignificant;
3400 buffer.clear();
3401 buffer.push_back('1');
3402 return;
3403 }
3404
3405 exp += FirstSignificant;
3406 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3407 }
3408}
3409
3410void APFloat::toString(SmallVectorImpl<char> &Str,
3411 unsigned FormatPrecision,
Chris Lattner0ddda3b2010-03-06 19:20:13 +00003412 unsigned FormatMaxPadding) const {
John McCall00e65de2009-12-24 08:56:26 +00003413 switch (category) {
3414 case fcInfinity:
3415 if (isNegative())
3416 return append(Str, "-Inf");
3417 else
3418 return append(Str, "+Inf");
3419
3420 case fcNaN: return append(Str, "NaN");
3421
3422 case fcZero:
3423 if (isNegative())
3424 Str.push_back('-');
3425
3426 if (!FormatMaxPadding)
3427 append(Str, "0.0E+0");
3428 else
3429 Str.push_back('0');
3430 return;
3431
3432 case fcNormal:
3433 break;
3434 }
3435
3436 if (isNegative())
3437 Str.push_back('-');
3438
3439 // Decompose the number into an APInt and an exponent.
3440 int exp = exponent - ((int) semantics->precision - 1);
3441 APInt significand(semantics->precision,
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00003442 makeArrayRef(significandParts(),
3443 partCountForBits(semantics->precision)));
John McCall00e65de2009-12-24 08:56:26 +00003444
John McCall6a09aff2009-12-24 23:18:09 +00003445 // Set FormatPrecision if zero. We want to do this before we
3446 // truncate trailing zeros, as those are part of the precision.
3447 if (!FormatPrecision) {
3448 // It's an interesting question whether to use the nominal
3449 // precision or the active precision here for denormals.
3450
3451 // FormatPrecision = ceil(significandBits / lg_2(10))
3452 FormatPrecision = (semantics->precision * 59 + 195) / 196;
3453 }
3454
John McCall00e65de2009-12-24 08:56:26 +00003455 // Ignore trailing binary zeros.
3456 int trailingZeros = significand.countTrailingZeros();
3457 exp += trailingZeros;
3458 significand = significand.lshr(trailingZeros);
3459
3460 // Change the exponent from 2^e to 10^e.
3461 if (exp == 0) {
3462 // Nothing to do.
3463 } else if (exp > 0) {
3464 // Just shift left.
Jay Foad40f8f622010-12-07 08:25:19 +00003465 significand = significand.zext(semantics->precision + exp);
John McCall00e65de2009-12-24 08:56:26 +00003466 significand <<= exp;
3467 exp = 0;
3468 } else { /* exp < 0 */
3469 int texp = -exp;
3470
3471 // We transform this using the identity:
3472 // (N)(2^-e) == (N)(5^e)(10^-e)
3473 // This means we have to multiply N (the significand) by 5^e.
3474 // To avoid overflow, we have to operate on numbers large
3475 // enough to store N * 5^e:
3476 // log2(N * 5^e) == log2(N) + e * log2(5)
John McCall6a09aff2009-12-24 23:18:09 +00003477 // <= semantics->precision + e * 137 / 59
3478 // (log_2(5) ~ 2.321928 < 2.322034 ~ 137/59)
Dan Gohman16e02092010-03-24 19:38:02 +00003479
Eli Friedman9eb6b4d2011-10-07 23:40:49 +00003480 unsigned precision = semantics->precision + (137 * texp + 136) / 59;
John McCall00e65de2009-12-24 08:56:26 +00003481
3482 // Multiply significand by 5^e.
3483 // N * 5^0101 == N * 5^(1*1) * 5^(0*2) * 5^(1*4) * 5^(0*8)
Jay Foad40f8f622010-12-07 08:25:19 +00003484 significand = significand.zext(precision);
John McCall00e65de2009-12-24 08:56:26 +00003485 APInt five_to_the_i(precision, 5);
3486 while (true) {
3487 if (texp & 1) significand *= five_to_the_i;
Dan Gohman16e02092010-03-24 19:38:02 +00003488
John McCall00e65de2009-12-24 08:56:26 +00003489 texp >>= 1;
3490 if (!texp) break;
3491 five_to_the_i *= five_to_the_i;
3492 }
3493 }
3494
John McCall003a09c2009-12-24 12:16:56 +00003495 AdjustToPrecision(significand, exp, FormatPrecision);
3496
John McCall00e65de2009-12-24 08:56:26 +00003497 llvm::SmallVector<char, 256> buffer;
3498
3499 // Fill the buffer.
3500 unsigned precision = significand.getBitWidth();
3501 APInt ten(precision, 10);
3502 APInt digit(precision, 0);
3503
3504 bool inTrail = true;
3505 while (significand != 0) {
3506 // digit <- significand % 10
3507 // significand <- significand / 10
3508 APInt::udivrem(significand, ten, significand, digit);
3509
3510 unsigned d = digit.getZExtValue();
3511
3512 // Drop trailing zeros.
3513 if (inTrail && !d) exp++;
3514 else {
3515 buffer.push_back((char) ('0' + d));
3516 inTrail = false;
3517 }
3518 }
3519
3520 assert(!buffer.empty() && "no characters in buffer!");
3521
3522 // Drop down to FormatPrecision.
3523 // TODO: don't do more precise calculations above than are required.
3524 AdjustToPrecision(buffer, exp, FormatPrecision);
3525
3526 unsigned NDigits = buffer.size();
3527
John McCall6a09aff2009-12-24 23:18:09 +00003528 // Check whether we should use scientific notation.
John McCall00e65de2009-12-24 08:56:26 +00003529 bool FormatScientific;
3530 if (!FormatMaxPadding)
3531 FormatScientific = true;
3532 else {
John McCall00e65de2009-12-24 08:56:26 +00003533 if (exp >= 0) {
John McCall6a09aff2009-12-24 23:18:09 +00003534 // 765e3 --> 765000
3535 // ^^^
3536 // But we shouldn't make the number look more precise than it is.
3537 FormatScientific = ((unsigned) exp > FormatMaxPadding ||
3538 NDigits + (unsigned) exp > FormatPrecision);
John McCall00e65de2009-12-24 08:56:26 +00003539 } else {
John McCall6a09aff2009-12-24 23:18:09 +00003540 // Power of the most significant digit.
3541 int MSD = exp + (int) (NDigits - 1);
3542 if (MSD >= 0) {
John McCall00e65de2009-12-24 08:56:26 +00003543 // 765e-2 == 7.65
John McCall6a09aff2009-12-24 23:18:09 +00003544 FormatScientific = false;
John McCall00e65de2009-12-24 08:56:26 +00003545 } else {
3546 // 765e-5 == 0.00765
3547 // ^ ^^
John McCall6a09aff2009-12-24 23:18:09 +00003548 FormatScientific = ((unsigned) -MSD) > FormatMaxPadding;
John McCall00e65de2009-12-24 08:56:26 +00003549 }
3550 }
John McCall00e65de2009-12-24 08:56:26 +00003551 }
3552
3553 // Scientific formatting is pretty straightforward.
3554 if (FormatScientific) {
3555 exp += (NDigits - 1);
3556
3557 Str.push_back(buffer[NDigits-1]);
3558 Str.push_back('.');
3559 if (NDigits == 1)
3560 Str.push_back('0');
3561 else
3562 for (unsigned I = 1; I != NDigits; ++I)
3563 Str.push_back(buffer[NDigits-1-I]);
3564 Str.push_back('E');
3565
3566 Str.push_back(exp >= 0 ? '+' : '-');
3567 if (exp < 0) exp = -exp;
3568 SmallVector<char, 6> expbuf;
3569 do {
3570 expbuf.push_back((char) ('0' + (exp % 10)));
3571 exp /= 10;
3572 } while (exp);
3573 for (unsigned I = 0, E = expbuf.size(); I != E; ++I)
3574 Str.push_back(expbuf[E-1-I]);
3575 return;
3576 }
3577
3578 // Non-scientific, positive exponents.
3579 if (exp >= 0) {
3580 for (unsigned I = 0; I != NDigits; ++I)
3581 Str.push_back(buffer[NDigits-1-I]);
3582 for (unsigned I = 0; I != (unsigned) exp; ++I)
3583 Str.push_back('0');
3584 return;
3585 }
3586
3587 // Non-scientific, negative exponents.
3588
3589 // The number of digits to the left of the decimal point.
3590 int NWholeDigits = exp + (int) NDigits;
3591
3592 unsigned I = 0;
3593 if (NWholeDigits > 0) {
3594 for (; I != (unsigned) NWholeDigits; ++I)
3595 Str.push_back(buffer[NDigits-I-1]);
3596 Str.push_back('.');
3597 } else {
3598 unsigned NZeros = 1 + (unsigned) -NWholeDigits;
3599
3600 Str.push_back('0');
3601 Str.push_back('.');
3602 for (unsigned Z = 1; Z != NZeros; ++Z)
3603 Str.push_back('0');
3604 }
3605
3606 for (; I != NDigits; ++I)
3607 Str.push_back(buffer[NDigits-I-1]);
3608}
Benjamin Kramer27460002011-03-30 15:42:27 +00003609
3610bool APFloat::getExactInverse(APFloat *inv) const {
Chris Lattner7a2bdde2011-04-15 05:18:47 +00003611 // We can only guarantee the existence of an exact inverse for IEEE floats.
Benjamin Kramer27460002011-03-30 15:42:27 +00003612 if (semantics != &IEEEhalf && semantics != &IEEEsingle &&
3613 semantics != &IEEEdouble && semantics != &IEEEquad)
3614 return false;
3615
3616 // Special floats and denormals have no exact inverse.
3617 if (category != fcNormal)
3618 return false;
3619
3620 // Check that the number is a power of two by making sure that only the
3621 // integer bit is set in the significand.
3622 if (significandLSB() != semantics->precision - 1)
3623 return false;
3624
3625 // Get the inverse.
3626 APFloat reciprocal(*semantics, 1ULL);
3627 if (reciprocal.divide(*this, rmNearestTiesToEven) != opOK)
3628 return false;
3629
Benjamin Kramer83985122011-03-30 17:02:54 +00003630 // Avoid multiplication with a denormal, it is not safe on all platforms and
3631 // may be slower than a normal division.
3632 if (reciprocal.significandMSB() + 1 < reciprocal.semantics->precision)
3633 return false;
3634
3635 assert(reciprocal.category == fcNormal &&
3636 reciprocal.significandLSB() == reciprocal.semantics->precision - 1);
3637
Benjamin Kramer27460002011-03-30 15:42:27 +00003638 if (inv)
3639 *inv = reciprocal;
3640
3641 return true;
3642}