blob: 214abecf35a32fd8fc100796e246959827131042 [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"
Ted Kremenek1f801fa2008-02-11 17:24:50 +000016#include "llvm/ADT/FoldingSet.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000017#include "llvm/Support/ErrorHandling.h"
Dale Johannesend3b51fd2007-08-24 05:08:11 +000018#include "llvm/Support/MathExtras.h"
Chris Lattnerfad86b02008-08-17 07:19:36 +000019#include <cstring>
Chris Lattnerb39cdde2007-08-20 22:49:32 +000020
21using namespace llvm;
22
23#define convolve(lhs, rhs) ((lhs) * 4 + (rhs))
24
Neil Bootha30b0ee2007-10-03 22:26:02 +000025/* Assumed in hexadecimal significand parsing, and conversion to
26 hexadecimal strings. */
Chris Lattner9f17eb02008-08-17 04:58:58 +000027#define COMPILE_TIME_ASSERT(cond) extern int CTAssert[(cond) ? 1 : -1]
Chris Lattnerb39cdde2007-08-20 22:49:32 +000028COMPILE_TIME_ASSERT(integerPartWidth % 4 == 0);
29
30namespace llvm {
31
32 /* Represents floating point arithmetic semantics. */
33 struct fltSemantics {
34 /* The largest E such that 2^E is representable; this matches the
35 definition of IEEE 754. */
36 exponent_t maxExponent;
37
38 /* The smallest E such that 2^E is a normalized number; this
39 matches the definition of IEEE 754. */
40 exponent_t minExponent;
41
42 /* Number of bits in the significand. This includes the integer
43 bit. */
Neil Booth7a951ca2007-10-12 15:33:27 +000044 unsigned int precision;
Neil Boothcaf19d72007-10-14 10:29:28 +000045
46 /* True if arithmetic is supported. */
47 unsigned int arithmeticOK;
Chris Lattnerb39cdde2007-08-20 22:49:32 +000048 };
49
Neil Boothcaf19d72007-10-14 10:29:28 +000050 const fltSemantics APFloat::IEEEsingle = { 127, -126, 24, true };
51 const fltSemantics APFloat::IEEEdouble = { 1023, -1022, 53, true };
52 const fltSemantics APFloat::IEEEquad = { 16383, -16382, 113, true };
53 const fltSemantics APFloat::x87DoubleExtended = { 16383, -16382, 64, true };
54 const fltSemantics APFloat::Bogus = { 0, 0, 0, true };
Dale Johannesena471c2e2007-10-11 18:07:22 +000055
56 // The PowerPC format consists of two doubles. It does not map cleanly
57 // onto the usual format above. For now only storage of constants of
58 // this type is supported, no arithmetic.
Neil Boothcaf19d72007-10-14 10:29:28 +000059 const fltSemantics APFloat::PPCDoubleDouble = { 1023, -1022, 106, false };
Neil Booth96c74712007-10-12 16:02:31 +000060
61 /* A tight upper bound on number of parts required to hold the value
62 pow(5, power) is
63
Neil Booth686700e2007-10-15 15:00:55 +000064 power * 815 / (351 * integerPartWidth) + 1
Neil Booth96c74712007-10-12 16:02:31 +000065
66 However, whilst the result may require only this many parts,
67 because we are multiplying two values to get it, the
68 multiplication may require an extra part with the excess part
69 being zero (consider the trivial case of 1 * 1, tcFullMultiply
70 requires two parts to hold the single-part result). So we add an
71 extra one to guarantee enough space whilst multiplying. */
72 const unsigned int maxExponent = 16383;
73 const unsigned int maxPrecision = 113;
74 const unsigned int maxPowerOfFiveExponent = maxExponent + maxPrecision - 1;
Neil Booth686700e2007-10-15 15:00:55 +000075 const unsigned int maxPowerOfFiveParts = 2 + ((maxPowerOfFiveExponent * 815)
76 / (351 * integerPartWidth));
Chris Lattnerb39cdde2007-08-20 22:49:32 +000077}
78
Chris Lattnere213f3f2009-03-12 23:59:55 +000079/* A bunch of private, handy routines. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +000080
Chris Lattnere213f3f2009-03-12 23:59:55 +000081static inline unsigned int
82partCountForBits(unsigned int bits)
83{
84 return ((bits) + integerPartWidth - 1) / integerPartWidth;
85}
Chris Lattnerb39cdde2007-08-20 22:49:32 +000086
Chris Lattnere213f3f2009-03-12 23:59:55 +000087/* Returns 0U-9U. Return values >= 10U are not digits. */
88static inline unsigned int
89decDigitValue(unsigned int c)
90{
91 return c - '0';
92}
Chris Lattnerb39cdde2007-08-20 22:49:32 +000093
Chris Lattnere213f3f2009-03-12 23:59:55 +000094static unsigned int
95hexDigitValue(unsigned int c)
96{
97 unsigned int r;
Chris Lattnerb39cdde2007-08-20 22:49:32 +000098
Chris Lattnere213f3f2009-03-12 23:59:55 +000099 r = c - '0';
100 if(r <= 9)
101 return r;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000102
Chris Lattnere213f3f2009-03-12 23:59:55 +0000103 r = c - 'A';
104 if(r <= 5)
105 return r + 10;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000106
Chris Lattnere213f3f2009-03-12 23:59:55 +0000107 r = c - 'a';
108 if(r <= 5)
109 return r + 10;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000110
Chris Lattnere213f3f2009-03-12 23:59:55 +0000111 return -1U;
112}
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000113
Chris Lattnere213f3f2009-03-12 23:59:55 +0000114static inline void
115assertArithmeticOK(const llvm::fltSemantics &semantics) {
116 assert(semantics.arithmeticOK
117 && "Compile-time arithmetic does not support these semantics");
118}
Neil Boothcaf19d72007-10-14 10:29:28 +0000119
Chris Lattnere213f3f2009-03-12 23:59:55 +0000120/* Return the value of a decimal exponent of the form
121 [+-]ddddddd.
Neil Booth1870f292007-10-14 10:16:12 +0000122
Chris Lattnere213f3f2009-03-12 23:59:55 +0000123 If the exponent overflows, returns a large exponent with the
124 appropriate sign. */
125static int
126readExponent(const char *p)
127{
128 bool isNegative;
129 unsigned int absExponent;
130 const unsigned int overlargeExponent = 24000; /* FIXME. */
Neil Booth1870f292007-10-14 10:16:12 +0000131
Chris Lattnere213f3f2009-03-12 23:59:55 +0000132 isNegative = (*p == '-');
133 if (*p == '-' || *p == '+')
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000134 p++;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000135
Chris Lattnere213f3f2009-03-12 23:59:55 +0000136 absExponent = decDigitValue(*p++);
137 assert (absExponent < 10U);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000138
Chris Lattnere213f3f2009-03-12 23:59:55 +0000139 for (;;) {
140 unsigned int value;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000141
Chris Lattnere213f3f2009-03-12 23:59:55 +0000142 value = decDigitValue(*p);
143 if (value >= 10U)
144 break;
145
146 p++;
147 value += absExponent * 10;
148 if (absExponent >= overlargeExponent) {
149 absExponent = overlargeExponent;
150 break;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000151 }
Chris Lattnere213f3f2009-03-12 23:59:55 +0000152 absExponent = value;
153 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000154
Chris Lattnere213f3f2009-03-12 23:59:55 +0000155 if (isNegative)
156 return -(int) absExponent;
157 else
158 return (int) absExponent;
159}
160
161/* This is ugly and needs cleaning up, but I don't immediately see
162 how whilst remaining safe. */
163static int
164totalExponent(const char *p, int exponentAdjustment)
165{
166 int unsignedExponent;
167 bool negative, overflow;
168 int exponent;
169
170 /* Move past the exponent letter and sign to the digits. */
171 p++;
172 negative = *p == '-';
173 if(*p == '-' || *p == '+')
174 p++;
175
176 unsignedExponent = 0;
177 overflow = false;
178 for(;;) {
179 unsigned int value;
180
181 value = decDigitValue(*p);
182 if(value >= 10U)
183 break;
184
185 p++;
186 unsignedExponent = unsignedExponent * 10 + value;
187 if(unsignedExponent > 65535)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000188 overflow = true;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000189 }
190
Chris Lattnere213f3f2009-03-12 23:59:55 +0000191 if(exponentAdjustment > 65535 || exponentAdjustment < -65536)
192 overflow = true;
193
194 if(!overflow) {
195 exponent = unsignedExponent;
196 if(negative)
197 exponent = -exponent;
198 exponent += exponentAdjustment;
199 if(exponent > 65535 || exponent < -65536)
200 overflow = true;
201 }
202
203 if(overflow)
204 exponent = negative ? -65536: 65535;
205
206 return exponent;
207}
208
209static const char *
210skipLeadingZeroesAndAnyDot(const char *p, const char **dot)
211{
212 *dot = 0;
213 while(*p == '0')
214 p++;
215
216 if(*p == '.') {
217 *dot = p++;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000218 while(*p == '0')
219 p++;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000220 }
221
Chris Lattnere213f3f2009-03-12 23:59:55 +0000222 return p;
223}
Neil Booth1870f292007-10-14 10:16:12 +0000224
Chris Lattnere213f3f2009-03-12 23:59:55 +0000225/* Given a normal decimal floating point number of the form
Neil Booth1870f292007-10-14 10:16:12 +0000226
Chris Lattnere213f3f2009-03-12 23:59:55 +0000227 dddd.dddd[eE][+-]ddd
Neil Booth686700e2007-10-15 15:00:55 +0000228
Chris Lattnere213f3f2009-03-12 23:59:55 +0000229 where the decimal point and exponent are optional, fill out the
230 structure D. Exponent is appropriate if the significand is
231 treated as an integer, and normalizedExponent if the significand
232 is taken to have the decimal point after a single leading
233 non-zero digit.
Neil Booth1870f292007-10-14 10:16:12 +0000234
Chris Lattnere213f3f2009-03-12 23:59:55 +0000235 If the value is zero, V->firstSigDigit points to a non-digit, and
236 the return exponent is zero.
237*/
238struct decimalInfo {
239 const char *firstSigDigit;
240 const char *lastSigDigit;
241 int exponent;
242 int normalizedExponent;
243};
Neil Booth1870f292007-10-14 10:16:12 +0000244
Chris Lattnere213f3f2009-03-12 23:59:55 +0000245static void
246interpretDecimal(const char *p, decimalInfo *D)
247{
248 const char *dot;
Neil Booth1870f292007-10-14 10:16:12 +0000249
Chris Lattnere213f3f2009-03-12 23:59:55 +0000250 p = skipLeadingZeroesAndAnyDot (p, &dot);
Neil Booth1870f292007-10-14 10:16:12 +0000251
Chris Lattnere213f3f2009-03-12 23:59:55 +0000252 D->firstSigDigit = p;
253 D->exponent = 0;
254 D->normalizedExponent = 0;
255
256 for (;;) {
257 if (*p == '.') {
258 assert(dot == 0);
259 dot = p++;
Neil Booth1870f292007-10-14 10:16:12 +0000260 }
Chris Lattnere213f3f2009-03-12 23:59:55 +0000261 if (decDigitValue(*p) >= 10U)
262 break;
263 p++;
264 }
Neil Booth1870f292007-10-14 10:16:12 +0000265
Chris Lattnere213f3f2009-03-12 23:59:55 +0000266 /* If number is all zerooes accept any exponent. */
267 if (p != D->firstSigDigit) {
268 if (*p == 'e' || *p == 'E')
269 D->exponent = readExponent(p + 1);
Neil Booth1870f292007-10-14 10:16:12 +0000270
Chris Lattnere213f3f2009-03-12 23:59:55 +0000271 /* Implied decimal point? */
272 if (!dot)
273 dot = p;
Neil Booth1870f292007-10-14 10:16:12 +0000274
Chris Lattnere213f3f2009-03-12 23:59:55 +0000275 /* Drop insignificant trailing zeroes. */
276 do
Neil Booth1870f292007-10-14 10:16:12 +0000277 do
Chris Lattnere213f3f2009-03-12 23:59:55 +0000278 p--;
279 while (*p == '0');
280 while (*p == '.');
Neil Booth1870f292007-10-14 10:16:12 +0000281
Chris Lattnere213f3f2009-03-12 23:59:55 +0000282 /* Adjust the exponents for any decimal point. */
283 D->exponent += static_cast<exponent_t>((dot - p) - (dot > p));
284 D->normalizedExponent = (D->exponent +
285 static_cast<exponent_t>((p - D->firstSigDigit)
286 - (dot > D->firstSigDigit && dot < p)));
Neil Booth1870f292007-10-14 10:16:12 +0000287 }
288
Chris Lattnere213f3f2009-03-12 23:59:55 +0000289 D->lastSigDigit = p;
290}
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000291
Chris Lattnere213f3f2009-03-12 23:59:55 +0000292/* Return the trailing fraction of a hexadecimal number.
293 DIGITVALUE is the first hex digit of the fraction, P points to
294 the next digit. */
295static lostFraction
296trailingHexadecimalFraction(const char *p, unsigned int digitValue)
297{
298 unsigned int hexDigit;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000299
Chris Lattnere213f3f2009-03-12 23:59:55 +0000300 /* If the first trailing digit isn't 0 or 8 we can work out the
301 fraction immediately. */
302 if(digitValue > 8)
303 return lfMoreThanHalf;
304 else if(digitValue < 8 && digitValue > 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000305 return lfLessThanHalf;
Chris Lattnere213f3f2009-03-12 23:59:55 +0000306
307 /* Otherwise we need to find the first non-zero digit. */
308 while(*p == '0')
309 p++;
310
311 hexDigit = hexDigitValue(*p);
312
313 /* If we ran off the end it is exactly zero or one-half, otherwise
314 a little more. */
315 if(hexDigit == -1U)
316 return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
317 else
318 return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf;
319}
320
321/* Return the fraction lost were a bignum truncated losing the least
322 significant BITS bits. */
323static lostFraction
324lostFractionThroughTruncation(const integerPart *parts,
325 unsigned int partCount,
326 unsigned int bits)
327{
328 unsigned int lsb;
329
330 lsb = APInt::tcLSB(parts, partCount);
331
332 /* Note this is guaranteed true if bits == 0, or LSB == -1U. */
333 if(bits <= lsb)
334 return lfExactlyZero;
335 if(bits == lsb + 1)
336 return lfExactlyHalf;
337 if(bits <= partCount * integerPartWidth
338 && APInt::tcExtractBit(parts, bits - 1))
339 return lfMoreThanHalf;
340
341 return lfLessThanHalf;
342}
343
344/* Shift DST right BITS bits noting lost fraction. */
345static lostFraction
346shiftRight(integerPart *dst, unsigned int parts, unsigned int bits)
347{
348 lostFraction lost_fraction;
349
350 lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
351
352 APInt::tcShiftRight(dst, parts, bits);
353
354 return lost_fraction;
355}
356
357/* Combine the effect of two lost fractions. */
358static lostFraction
359combineLostFractions(lostFraction moreSignificant,
360 lostFraction lessSignificant)
361{
362 if(lessSignificant != lfExactlyZero) {
363 if(moreSignificant == lfExactlyZero)
364 moreSignificant = lfLessThanHalf;
365 else if(moreSignificant == lfExactlyHalf)
366 moreSignificant = lfMoreThanHalf;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000367 }
368
Chris Lattnere213f3f2009-03-12 23:59:55 +0000369 return moreSignificant;
370}
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000371
Chris Lattnere213f3f2009-03-12 23:59:55 +0000372/* The error from the true value, in half-ulps, on multiplying two
373 floating point numbers, which differ from the value they
374 approximate by at most HUE1 and HUE2 half-ulps, is strictly less
375 than the returned value.
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000376
Chris Lattnere213f3f2009-03-12 23:59:55 +0000377 See "How to Read Floating Point Numbers Accurately" by William D
378 Clinger. */
379static unsigned int
380HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
381{
382 assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000383
Chris Lattnere213f3f2009-03-12 23:59:55 +0000384 if (HUerr1 + HUerr2 == 0)
385 return inexactMultiply * 2; /* <= inexactMultiply half-ulps. */
386 else
387 return inexactMultiply + 2 * (HUerr1 + HUerr2);
388}
Neil Bootha30b0ee2007-10-03 22:26:02 +0000389
Chris Lattnere213f3f2009-03-12 23:59:55 +0000390/* The number of ulps from the boundary (zero, or half if ISNEAREST)
391 when the least significant BITS are truncated. BITS cannot be
392 zero. */
393static integerPart
394ulpsFromBoundary(const integerPart *parts, unsigned int bits, bool isNearest)
395{
396 unsigned int count, partBits;
397 integerPart part, boundary;
Neil Booth33d4c922007-10-07 08:51:21 +0000398
Chris Lattnere213f3f2009-03-12 23:59:55 +0000399 assert (bits != 0);
Neil Bootha30b0ee2007-10-03 22:26:02 +0000400
Chris Lattnere213f3f2009-03-12 23:59:55 +0000401 bits--;
402 count = bits / integerPartWidth;
403 partBits = bits % integerPartWidth + 1;
Neil Booth96c74712007-10-12 16:02:31 +0000404
Chris Lattnere213f3f2009-03-12 23:59:55 +0000405 part = parts[count] & (~(integerPart) 0 >> (integerPartWidth - partBits));
Neil Booth96c74712007-10-12 16:02:31 +0000406
Chris Lattnere213f3f2009-03-12 23:59:55 +0000407 if (isNearest)
408 boundary = (integerPart) 1 << (partBits - 1);
409 else
410 boundary = 0;
411
412 if (count == 0) {
413 if (part - boundary <= boundary - part)
414 return part - boundary;
Neil Booth96c74712007-10-12 16:02:31 +0000415 else
Chris Lattnere213f3f2009-03-12 23:59:55 +0000416 return boundary - part;
Neil Booth96c74712007-10-12 16:02:31 +0000417 }
418
Chris Lattnere213f3f2009-03-12 23:59:55 +0000419 if (part == boundary) {
420 while (--count)
421 if (parts[count])
422 return ~(integerPart) 0; /* A lot. */
Neil Booth96c74712007-10-12 16:02:31 +0000423
Chris Lattnere213f3f2009-03-12 23:59:55 +0000424 return parts[0];
425 } else if (part == boundary - 1) {
426 while (--count)
427 if (~parts[count])
428 return ~(integerPart) 0; /* A lot. */
Neil Booth96c74712007-10-12 16:02:31 +0000429
Chris Lattnere213f3f2009-03-12 23:59:55 +0000430 return -parts[0];
431 }
Neil Booth96c74712007-10-12 16:02:31 +0000432
Chris Lattnere213f3f2009-03-12 23:59:55 +0000433 return ~(integerPart) 0; /* A lot. */
434}
Neil Booth96c74712007-10-12 16:02:31 +0000435
Chris Lattnere213f3f2009-03-12 23:59:55 +0000436/* Place pow(5, power) in DST, and return the number of parts used.
437 DST must be at least one part larger than size of the answer. */
438static unsigned int
439powerOf5(integerPart *dst, unsigned int power)
440{
441 static const integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125,
442 15625, 78125 };
Chris Lattneree167a72009-03-13 00:24:01 +0000443 integerPart pow5s[maxPowerOfFiveParts * 2 + 5];
444 pow5s[0] = 78125 * 5;
445
Chris Lattner807926a2009-03-13 00:03:51 +0000446 unsigned int partsCount[16] = { 1 };
Chris Lattnere213f3f2009-03-12 23:59:55 +0000447 integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5;
448 unsigned int result;
Chris Lattnere213f3f2009-03-12 23:59:55 +0000449 assert(power <= maxExponent);
450
451 p1 = dst;
452 p2 = scratch;
453
454 *p1 = firstEightPowers[power & 7];
455 power >>= 3;
456
457 result = 1;
458 pow5 = pow5s;
459
460 for (unsigned int n = 0; power; power >>= 1, n++) {
461 unsigned int pc;
462
463 pc = partsCount[n];
464
465 /* Calculate pow(5,pow(2,n+3)) if we haven't yet. */
466 if (pc == 0) {
467 pc = partsCount[n - 1];
468 APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc);
469 pc *= 2;
470 if (pow5[pc - 1] == 0)
471 pc--;
472 partsCount[n] = pc;
Neil Booth96c74712007-10-12 16:02:31 +0000473 }
474
Chris Lattnere213f3f2009-03-12 23:59:55 +0000475 if (power & 1) {
476 integerPart *tmp;
Neil Booth96c74712007-10-12 16:02:31 +0000477
Chris Lattnere213f3f2009-03-12 23:59:55 +0000478 APInt::tcFullMultiply(p2, p1, pow5, result, pc);
479 result += pc;
480 if (p2[result - 1] == 0)
481 result--;
Neil Booth96c74712007-10-12 16:02:31 +0000482
Chris Lattnere213f3f2009-03-12 23:59:55 +0000483 /* Now result is in p1 with partsCount parts and p2 is scratch
484 space. */
485 tmp = p1, p1 = p2, p2 = tmp;
Neil Booth96c74712007-10-12 16:02:31 +0000486 }
487
Chris Lattnere213f3f2009-03-12 23:59:55 +0000488 pow5 += pc;
Neil Booth96c74712007-10-12 16:02:31 +0000489 }
490
Chris Lattnere213f3f2009-03-12 23:59:55 +0000491 if (p1 != dst)
492 APInt::tcAssign(dst, p1, result);
Neil Booth96c74712007-10-12 16:02:31 +0000493
Chris Lattnere213f3f2009-03-12 23:59:55 +0000494 return result;
495}
Neil Booth96c74712007-10-12 16:02:31 +0000496
Chris Lattnere213f3f2009-03-12 23:59:55 +0000497/* Zero at the end to avoid modular arithmetic when adding one; used
498 when rounding up during hexadecimal output. */
499static const char hexDigitsLower[] = "0123456789abcdef0";
500static const char hexDigitsUpper[] = "0123456789ABCDEF0";
501static const char infinityL[] = "infinity";
502static const char infinityU[] = "INFINITY";
503static const char NaNL[] = "nan";
504static const char NaNU[] = "NAN";
Neil Booth96c74712007-10-12 16:02:31 +0000505
Chris Lattnere213f3f2009-03-12 23:59:55 +0000506/* Write out an integerPart in hexadecimal, starting with the most
507 significant nibble. Write out exactly COUNT hexdigits, return
508 COUNT. */
509static unsigned int
510partAsHex (char *dst, integerPart part, unsigned int count,
511 const char *hexDigitChars)
512{
513 unsigned int result = count;
Neil Booth96c74712007-10-12 16:02:31 +0000514
Chris Lattnere213f3f2009-03-12 23:59:55 +0000515 assert (count != 0 && count <= integerPartWidth / 4);
Neil Booth96c74712007-10-12 16:02:31 +0000516
Chris Lattnere213f3f2009-03-12 23:59:55 +0000517 part >>= (integerPartWidth - 4 * count);
518 while (count--) {
519 dst[count] = hexDigitChars[part & 0xf];
520 part >>= 4;
Neil Booth96c74712007-10-12 16:02:31 +0000521 }
522
Chris Lattnere213f3f2009-03-12 23:59:55 +0000523 return result;
524}
Neil Bootha30b0ee2007-10-03 22:26:02 +0000525
Chris Lattnere213f3f2009-03-12 23:59:55 +0000526/* Write out an unsigned decimal integer. */
527static char *
528writeUnsignedDecimal (char *dst, unsigned int n)
529{
530 char buff[40], *p;
Neil Bootha30b0ee2007-10-03 22:26:02 +0000531
Chris Lattnere213f3f2009-03-12 23:59:55 +0000532 p = buff;
533 do
534 *p++ = '0' + n % 10;
535 while (n /= 10);
Neil Bootha30b0ee2007-10-03 22:26:02 +0000536
Chris Lattnere213f3f2009-03-12 23:59:55 +0000537 do
538 *dst++ = *--p;
539 while (p != buff);
Neil Bootha30b0ee2007-10-03 22:26:02 +0000540
Chris Lattnere213f3f2009-03-12 23:59:55 +0000541 return dst;
542}
Neil Bootha30b0ee2007-10-03 22:26:02 +0000543
Chris Lattnere213f3f2009-03-12 23:59:55 +0000544/* Write out a signed decimal integer. */
545static char *
546writeSignedDecimal (char *dst, int value)
547{
548 if (value < 0) {
549 *dst++ = '-';
550 dst = writeUnsignedDecimal(dst, -(unsigned) value);
551 } else
552 dst = writeUnsignedDecimal(dst, value);
Neil Bootha30b0ee2007-10-03 22:26:02 +0000553
Chris Lattnere213f3f2009-03-12 23:59:55 +0000554 return dst;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000555}
556
557/* Constructors. */
558void
559APFloat::initialize(const fltSemantics *ourSemantics)
560{
561 unsigned int count;
562
563 semantics = ourSemantics;
564 count = partCount();
565 if(count > 1)
566 significand.parts = new integerPart[count];
567}
568
569void
570APFloat::freeSignificand()
571{
572 if(partCount() > 1)
573 delete [] significand.parts;
574}
575
576void
577APFloat::assign(const APFloat &rhs)
578{
579 assert(semantics == rhs.semantics);
580
581 sign = rhs.sign;
582 category = rhs.category;
583 exponent = rhs.exponent;
Dale Johannesena471c2e2007-10-11 18:07:22 +0000584 sign2 = rhs.sign2;
585 exponent2 = rhs.exponent2;
Dale Johanneseneaf08942007-08-31 04:03:46 +0000586 if(category == fcNormal || category == fcNaN)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000587 copySignificand(rhs);
588}
589
590void
591APFloat::copySignificand(const APFloat &rhs)
592{
Dale Johanneseneaf08942007-08-31 04:03:46 +0000593 assert(category == fcNormal || category == fcNaN);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000594 assert(rhs.partCount() >= partCount());
595
596 APInt::tcAssign(significandParts(), rhs.significandParts(),
Neil Booth4f881702007-09-26 21:33:42 +0000597 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000598}
599
Neil Boothe5e01942007-10-14 10:39:51 +0000600/* Make this number a NaN, with an arbitrary but deterministic value
Dale Johannesen541ed9f2009-01-21 20:32:55 +0000601 for the significand. If double or longer, this is a signalling NaN,
Mike Stumpc5ca7132009-05-30 03:49:43 +0000602 which may not be ideal. If float, this is QNaN(0). */
Neil Boothe5e01942007-10-14 10:39:51 +0000603void
Mike Stumpc5ca7132009-05-30 03:49:43 +0000604APFloat::makeNaN(unsigned type)
Neil Boothe5e01942007-10-14 10:39:51 +0000605{
606 category = fcNaN;
Mike Stumpc5ca7132009-05-30 03:49:43 +0000607 // FIXME: Add double and long double support for QNaN(0).
608 if (semantics->precision == 24 && semantics->maxExponent == 127) {
609 type |= 0x7fc00000U;
610 type &= ~0x80000000U;
611 } else
612 type = ~0U;
613 APInt::tcSet(significandParts(), type, partCount());
Neil Boothe5e01942007-10-14 10:39:51 +0000614}
615
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000616APFloat &
617APFloat::operator=(const APFloat &rhs)
618{
619 if(this != &rhs) {
620 if(semantics != rhs.semantics) {
621 freeSignificand();
622 initialize(rhs.semantics);
623 }
624 assign(rhs);
625 }
626
627 return *this;
628}
629
Dale Johannesen343e7702007-08-24 00:56:33 +0000630bool
Dale Johannesen12595d72007-08-24 22:09:56 +0000631APFloat::bitwiseIsEqual(const APFloat &rhs) const {
Dale Johannesen343e7702007-08-24 00:56:33 +0000632 if (this == &rhs)
633 return true;
634 if (semantics != rhs.semantics ||
Dale Johanneseneaf08942007-08-31 04:03:46 +0000635 category != rhs.category ||
636 sign != rhs.sign)
Dale Johannesen343e7702007-08-24 00:56:33 +0000637 return false;
Dan Gohmanb10abe12008-01-29 12:08:20 +0000638 if (semantics==(const llvm::fltSemantics*)&PPCDoubleDouble &&
Dale Johannesena471c2e2007-10-11 18:07:22 +0000639 sign2 != rhs.sign2)
640 return false;
Dale Johanneseneaf08942007-08-31 04:03:46 +0000641 if (category==fcZero || category==fcInfinity)
Dale Johannesen343e7702007-08-24 00:56:33 +0000642 return true;
Dale Johanneseneaf08942007-08-31 04:03:46 +0000643 else if (category==fcNormal && exponent!=rhs.exponent)
644 return false;
Dan Gohmanb10abe12008-01-29 12:08:20 +0000645 else if (semantics==(const llvm::fltSemantics*)&PPCDoubleDouble &&
Dale Johannesena471c2e2007-10-11 18:07:22 +0000646 exponent2!=rhs.exponent2)
647 return false;
Dale Johannesen343e7702007-08-24 00:56:33 +0000648 else {
Dale Johannesen343e7702007-08-24 00:56:33 +0000649 int i= partCount();
650 const integerPart* p=significandParts();
651 const integerPart* q=rhs.significandParts();
652 for (; i>0; i--, p++, q++) {
653 if (*p != *q)
654 return false;
655 }
656 return true;
657 }
658}
659
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000660APFloat::APFloat(const fltSemantics &ourSemantics, integerPart value)
661{
Neil Boothcaf19d72007-10-14 10:29:28 +0000662 assertArithmeticOK(ourSemantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000663 initialize(&ourSemantics);
664 sign = 0;
665 zeroSignificand();
666 exponent = ourSemantics.precision - 1;
667 significandParts()[0] = value;
668 normalize(rmNearestTiesToEven, lfExactlyZero);
669}
670
671APFloat::APFloat(const fltSemantics &ourSemantics,
Mike Stumpc5ca7132009-05-30 03:49:43 +0000672 fltCategory ourCategory, bool negative, unsigned type)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000673{
Neil Boothcaf19d72007-10-14 10:29:28 +0000674 assertArithmeticOK(ourSemantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000675 initialize(&ourSemantics);
676 category = ourCategory;
677 sign = negative;
Mike Stumpc5ca7132009-05-30 03:49:43 +0000678 if (category == fcNormal)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000679 category = fcZero;
Neil Boothe5e01942007-10-14 10:39:51 +0000680 else if (ourCategory == fcNaN)
Mike Stumpc5ca7132009-05-30 03:49:43 +0000681 makeNaN(type);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000682}
683
684APFloat::APFloat(const fltSemantics &ourSemantics, const char *text)
685{
Neil Boothcaf19d72007-10-14 10:29:28 +0000686 assertArithmeticOK(ourSemantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000687 initialize(&ourSemantics);
688 convertFromString(text, rmNearestTiesToEven);
689}
690
691APFloat::APFloat(const APFloat &rhs)
692{
693 initialize(rhs.semantics);
694 assign(rhs);
695}
696
697APFloat::~APFloat()
698{
699 freeSignificand();
700}
701
Ted Kremenek1f801fa2008-02-11 17:24:50 +0000702// Profile - This method 'profiles' an APFloat for use with FoldingSet.
703void APFloat::Profile(FoldingSetNodeID& ID) const {
Dale Johannesen7111b022008-10-09 18:53:47 +0000704 ID.Add(bitcastToAPInt());
Ted Kremenek1f801fa2008-02-11 17:24:50 +0000705}
706
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000707unsigned int
708APFloat::partCount() const
709{
Dale Johannesena72a5a02007-09-20 23:47:58 +0000710 return partCountForBits(semantics->precision + 1);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000711}
712
713unsigned int
714APFloat::semanticsPrecision(const fltSemantics &semantics)
715{
716 return semantics.precision;
717}
718
719const integerPart *
720APFloat::significandParts() const
721{
722 return const_cast<APFloat *>(this)->significandParts();
723}
724
725integerPart *
726APFloat::significandParts()
727{
Dale Johanneseneaf08942007-08-31 04:03:46 +0000728 assert(category == fcNormal || category == fcNaN);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000729
730 if(partCount() > 1)
731 return significand.parts;
732 else
733 return &significand.part;
734}
735
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000736void
737APFloat::zeroSignificand()
738{
739 category = fcNormal;
740 APInt::tcSet(significandParts(), 0, partCount());
741}
742
743/* Increment an fcNormal floating point number's significand. */
744void
745APFloat::incrementSignificand()
746{
747 integerPart carry;
748
749 carry = APInt::tcIncrement(significandParts(), partCount());
750
751 /* Our callers should never cause us to overflow. */
752 assert(carry == 0);
753}
754
755/* Add the significand of the RHS. Returns the carry flag. */
756integerPart
757APFloat::addSignificand(const APFloat &rhs)
758{
759 integerPart *parts;
760
761 parts = significandParts();
762
763 assert(semantics == rhs.semantics);
764 assert(exponent == rhs.exponent);
765
766 return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
767}
768
769/* Subtract the significand of the RHS with a borrow flag. Returns
770 the borrow flag. */
771integerPart
772APFloat::subtractSignificand(const APFloat &rhs, integerPart borrow)
773{
774 integerPart *parts;
775
776 parts = significandParts();
777
778 assert(semantics == rhs.semantics);
779 assert(exponent == rhs.exponent);
780
781 return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
Neil Booth4f881702007-09-26 21:33:42 +0000782 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000783}
784
785/* Multiply the significand of the RHS. If ADDEND is non-NULL, add it
786 on to the full-precision result of the multiplication. Returns the
787 lost fraction. */
788lostFraction
789APFloat::multiplySignificand(const APFloat &rhs, const APFloat *addend)
790{
Neil Booth4f881702007-09-26 21:33:42 +0000791 unsigned int omsb; // One, not zero, based MSB.
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000792 unsigned int partsCount, newPartsCount, precision;
793 integerPart *lhsSignificand;
794 integerPart scratch[4];
795 integerPart *fullSignificand;
796 lostFraction lost_fraction;
Dale Johannesen23a98552008-10-09 23:00:39 +0000797 bool ignored;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000798
799 assert(semantics == rhs.semantics);
800
801 precision = semantics->precision;
802 newPartsCount = partCountForBits(precision * 2);
803
804 if(newPartsCount > 4)
805 fullSignificand = new integerPart[newPartsCount];
806 else
807 fullSignificand = scratch;
808
809 lhsSignificand = significandParts();
810 partsCount = partCount();
811
812 APInt::tcFullMultiply(fullSignificand, lhsSignificand,
Neil Booth978661d2007-10-06 00:24:48 +0000813 rhs.significandParts(), partsCount, partsCount);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000814
815 lost_fraction = lfExactlyZero;
816 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
817 exponent += rhs.exponent;
818
819 if(addend) {
820 Significand savedSignificand = significand;
821 const fltSemantics *savedSemantics = semantics;
822 fltSemantics extendedSemantics;
823 opStatus status;
824 unsigned int extendedPrecision;
825
826 /* Normalize our MSB. */
827 extendedPrecision = precision + precision - 1;
828 if(omsb != extendedPrecision)
829 {
Neil Booth4f881702007-09-26 21:33:42 +0000830 APInt::tcShiftLeft(fullSignificand, newPartsCount,
831 extendedPrecision - omsb);
832 exponent -= extendedPrecision - omsb;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000833 }
834
835 /* Create new semantics. */
836 extendedSemantics = *semantics;
837 extendedSemantics.precision = extendedPrecision;
838
839 if(newPartsCount == 1)
840 significand.part = fullSignificand[0];
841 else
842 significand.parts = fullSignificand;
843 semantics = &extendedSemantics;
844
845 APFloat extendedAddend(*addend);
Dale Johannesen23a98552008-10-09 23:00:39 +0000846 status = extendedAddend.convert(extendedSemantics, rmTowardZero, &ignored);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000847 assert(status == opOK);
848 lost_fraction = addOrSubtractSignificand(extendedAddend, false);
849
850 /* Restore our state. */
851 if(newPartsCount == 1)
852 fullSignificand[0] = significand.part;
853 significand = savedSignificand;
854 semantics = savedSemantics;
855
856 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
857 }
858
859 exponent -= (precision - 1);
860
861 if(omsb > precision) {
862 unsigned int bits, significantParts;
863 lostFraction lf;
864
865 bits = omsb - precision;
866 significantParts = partCountForBits(omsb);
867 lf = shiftRight(fullSignificand, significantParts, bits);
868 lost_fraction = combineLostFractions(lf, lost_fraction);
869 exponent += bits;
870 }
871
872 APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
873
874 if(newPartsCount > 4)
875 delete [] fullSignificand;
876
877 return lost_fraction;
878}
879
880/* Multiply the significands of LHS and RHS to DST. */
881lostFraction
882APFloat::divideSignificand(const APFloat &rhs)
883{
884 unsigned int bit, i, partsCount;
885 const integerPart *rhsSignificand;
886 integerPart *lhsSignificand, *dividend, *divisor;
887 integerPart scratch[4];
888 lostFraction lost_fraction;
889
890 assert(semantics == rhs.semantics);
891
892 lhsSignificand = significandParts();
893 rhsSignificand = rhs.significandParts();
894 partsCount = partCount();
895
896 if(partsCount > 2)
897 dividend = new integerPart[partsCount * 2];
898 else
899 dividend = scratch;
900
901 divisor = dividend + partsCount;
902
903 /* Copy the dividend and divisor as they will be modified in-place. */
904 for(i = 0; i < partsCount; i++) {
905 dividend[i] = lhsSignificand[i];
906 divisor[i] = rhsSignificand[i];
907 lhsSignificand[i] = 0;
908 }
909
910 exponent -= rhs.exponent;
911
912 unsigned int precision = semantics->precision;
913
914 /* Normalize the divisor. */
915 bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
916 if(bit) {
917 exponent += bit;
918 APInt::tcShiftLeft(divisor, partsCount, bit);
919 }
920
921 /* Normalize the dividend. */
922 bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
923 if(bit) {
924 exponent -= bit;
925 APInt::tcShiftLeft(dividend, partsCount, bit);
926 }
927
Neil Booth96c74712007-10-12 16:02:31 +0000928 /* Ensure the dividend >= divisor initially for the loop below.
929 Incidentally, this means that the division loop below is
930 guaranteed to set the integer bit to one. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000931 if(APInt::tcCompare(dividend, divisor, partsCount) < 0) {
932 exponent--;
933 APInt::tcShiftLeft(dividend, partsCount, 1);
934 assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
935 }
936
937 /* Long division. */
938 for(bit = precision; bit; bit -= 1) {
939 if(APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
940 APInt::tcSubtract(dividend, divisor, 0, partsCount);
941 APInt::tcSetBit(lhsSignificand, bit - 1);
942 }
943
944 APInt::tcShiftLeft(dividend, partsCount, 1);
945 }
946
947 /* Figure out the lost fraction. */
948 int cmp = APInt::tcCompare(dividend, divisor, partsCount);
949
950 if(cmp > 0)
951 lost_fraction = lfMoreThanHalf;
952 else if(cmp == 0)
953 lost_fraction = lfExactlyHalf;
954 else if(APInt::tcIsZero(dividend, partsCount))
955 lost_fraction = lfExactlyZero;
956 else
957 lost_fraction = lfLessThanHalf;
958
959 if(partsCount > 2)
960 delete [] dividend;
961
962 return lost_fraction;
963}
964
965unsigned int
966APFloat::significandMSB() const
967{
968 return APInt::tcMSB(significandParts(), partCount());
969}
970
971unsigned int
972APFloat::significandLSB() const
973{
974 return APInt::tcLSB(significandParts(), partCount());
975}
976
977/* Note that a zero result is NOT normalized to fcZero. */
978lostFraction
979APFloat::shiftSignificandRight(unsigned int bits)
980{
981 /* Our exponent should not overflow. */
982 assert((exponent_t) (exponent + bits) >= exponent);
983
984 exponent += bits;
985
986 return shiftRight(significandParts(), partCount(), bits);
987}
988
989/* Shift the significand left BITS bits, subtract BITS from its exponent. */
990void
991APFloat::shiftSignificandLeft(unsigned int bits)
992{
993 assert(bits < semantics->precision);
994
995 if(bits) {
996 unsigned int partsCount = partCount();
997
998 APInt::tcShiftLeft(significandParts(), partsCount, bits);
999 exponent -= bits;
1000
1001 assert(!APInt::tcIsZero(significandParts(), partsCount));
1002 }
1003}
1004
1005APFloat::cmpResult
1006APFloat::compareAbsoluteValue(const APFloat &rhs) const
1007{
1008 int compare;
1009
1010 assert(semantics == rhs.semantics);
1011 assert(category == fcNormal);
1012 assert(rhs.category == fcNormal);
1013
1014 compare = exponent - rhs.exponent;
1015
1016 /* If exponents are equal, do an unsigned bignum comparison of the
1017 significands. */
1018 if(compare == 0)
1019 compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
Neil Booth4f881702007-09-26 21:33:42 +00001020 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001021
1022 if(compare > 0)
1023 return cmpGreaterThan;
1024 else if(compare < 0)
1025 return cmpLessThan;
1026 else
1027 return cmpEqual;
1028}
1029
1030/* Handle overflow. Sign is preserved. We either become infinity or
1031 the largest finite number. */
1032APFloat::opStatus
1033APFloat::handleOverflow(roundingMode rounding_mode)
1034{
1035 /* Infinity? */
1036 if(rounding_mode == rmNearestTiesToEven
1037 || rounding_mode == rmNearestTiesToAway
1038 || (rounding_mode == rmTowardPositive && !sign)
1039 || (rounding_mode == rmTowardNegative && sign))
1040 {
1041 category = fcInfinity;
1042 return (opStatus) (opOverflow | opInexact);
1043 }
1044
1045 /* Otherwise we become the largest finite number. */
1046 category = fcNormal;
1047 exponent = semantics->maxExponent;
1048 APInt::tcSetLeastSignificantBits(significandParts(), partCount(),
Neil Booth4f881702007-09-26 21:33:42 +00001049 semantics->precision);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001050
1051 return opInexact;
1052}
1053
Neil Boothb7dea4c2007-10-03 15:16:41 +00001054/* Returns TRUE if, when truncating the current number, with BIT the
1055 new LSB, with the given lost fraction and rounding mode, the result
1056 would need to be rounded away from zero (i.e., by increasing the
1057 signficand). This routine must work for fcZero of both signs, and
1058 fcNormal numbers. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001059bool
1060APFloat::roundAwayFromZero(roundingMode rounding_mode,
Neil Boothb7dea4c2007-10-03 15:16:41 +00001061 lostFraction lost_fraction,
1062 unsigned int bit) const
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001063{
Dale Johanneseneaf08942007-08-31 04:03:46 +00001064 /* NaNs and infinities should not have lost fractions. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001065 assert(category == fcNormal || category == fcZero);
1066
Neil Boothb7dea4c2007-10-03 15:16:41 +00001067 /* Current callers never pass this so we don't handle it. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001068 assert(lost_fraction != lfExactlyZero);
1069
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001070 switch (rounding_mode) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001071 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001072 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001073
1074 case rmNearestTiesToAway:
1075 return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
1076
1077 case rmNearestTiesToEven:
1078 if(lost_fraction == lfMoreThanHalf)
1079 return true;
1080
1081 /* Our zeroes don't have a significand to test. */
1082 if(lost_fraction == lfExactlyHalf && category != fcZero)
Neil Boothb7dea4c2007-10-03 15:16:41 +00001083 return APInt::tcExtractBit(significandParts(), bit);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001084
1085 return false;
1086
1087 case rmTowardZero:
1088 return false;
1089
1090 case rmTowardPositive:
1091 return sign == false;
1092
1093 case rmTowardNegative:
1094 return sign == true;
1095 }
1096}
1097
1098APFloat::opStatus
1099APFloat::normalize(roundingMode rounding_mode,
Neil Booth4f881702007-09-26 21:33:42 +00001100 lostFraction lost_fraction)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001101{
Neil Booth4f881702007-09-26 21:33:42 +00001102 unsigned int omsb; /* One, not zero, based MSB. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001103 int exponentChange;
1104
1105 if(category != fcNormal)
1106 return opOK;
1107
1108 /* Before rounding normalize the exponent of fcNormal numbers. */
1109 omsb = significandMSB() + 1;
1110
1111 if(omsb) {
1112 /* OMSB is numbered from 1. We want to place it in the integer
1113 bit numbered PRECISON if possible, with a compensating change in
1114 the exponent. */
1115 exponentChange = omsb - semantics->precision;
1116
1117 /* If the resulting exponent is too high, overflow according to
1118 the rounding mode. */
1119 if(exponent + exponentChange > semantics->maxExponent)
1120 return handleOverflow(rounding_mode);
1121
1122 /* Subnormal numbers have exponent minExponent, and their MSB
1123 is forced based on that. */
1124 if(exponent + exponentChange < semantics->minExponent)
1125 exponentChange = semantics->minExponent - exponent;
1126
1127 /* Shifting left is easy as we don't lose precision. */
1128 if(exponentChange < 0) {
1129 assert(lost_fraction == lfExactlyZero);
1130
1131 shiftSignificandLeft(-exponentChange);
1132
1133 return opOK;
1134 }
1135
1136 if(exponentChange > 0) {
1137 lostFraction lf;
1138
1139 /* Shift right and capture any new lost fraction. */
1140 lf = shiftSignificandRight(exponentChange);
1141
1142 lost_fraction = combineLostFractions(lf, lost_fraction);
1143
1144 /* Keep OMSB up-to-date. */
1145 if(omsb > (unsigned) exponentChange)
Neil Booth96c74712007-10-12 16:02:31 +00001146 omsb -= exponentChange;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001147 else
Neil Booth4f881702007-09-26 21:33:42 +00001148 omsb = 0;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001149 }
1150 }
1151
1152 /* Now round the number according to rounding_mode given the lost
1153 fraction. */
1154
1155 /* As specified in IEEE 754, since we do not trap we do not report
1156 underflow for exact results. */
1157 if(lost_fraction == lfExactlyZero) {
1158 /* Canonicalize zeroes. */
1159 if(omsb == 0)
1160 category = fcZero;
1161
1162 return opOK;
1163 }
1164
1165 /* Increment the significand if we're rounding away from zero. */
Neil Boothb7dea4c2007-10-03 15:16:41 +00001166 if(roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001167 if(omsb == 0)
1168 exponent = semantics->minExponent;
1169
1170 incrementSignificand();
1171 omsb = significandMSB() + 1;
1172
1173 /* Did the significand increment overflow? */
1174 if(omsb == (unsigned) semantics->precision + 1) {
1175 /* Renormalize by incrementing the exponent and shifting our
Neil Booth4f881702007-09-26 21:33:42 +00001176 significand right one. However if we already have the
1177 maximum exponent we overflow to infinity. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001178 if(exponent == semantics->maxExponent) {
Neil Booth4f881702007-09-26 21:33:42 +00001179 category = fcInfinity;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001180
Neil Booth4f881702007-09-26 21:33:42 +00001181 return (opStatus) (opOverflow | opInexact);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001182 }
1183
1184 shiftSignificandRight(1);
1185
1186 return opInexact;
1187 }
1188 }
1189
1190 /* The normal case - we were and are not denormal, and any
1191 significand increment above didn't overflow. */
1192 if(omsb == semantics->precision)
1193 return opInexact;
1194
1195 /* We have a non-zero denormal. */
1196 assert(omsb < semantics->precision);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001197
1198 /* Canonicalize zeroes. */
1199 if(omsb == 0)
1200 category = fcZero;
1201
1202 /* The fcZero case is a denormal that underflowed to zero. */
1203 return (opStatus) (opUnderflow | opInexact);
1204}
1205
1206APFloat::opStatus
1207APFloat::addOrSubtractSpecials(const APFloat &rhs, bool subtract)
1208{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001209 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001210 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001211 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001212
Dale Johanneseneaf08942007-08-31 04:03:46 +00001213 case convolve(fcNaN, fcZero):
1214 case convolve(fcNaN, fcNormal):
1215 case convolve(fcNaN, fcInfinity):
1216 case convolve(fcNaN, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001217 case convolve(fcNormal, fcZero):
1218 case convolve(fcInfinity, fcNormal):
1219 case convolve(fcInfinity, fcZero):
1220 return opOK;
1221
Dale Johanneseneaf08942007-08-31 04:03:46 +00001222 case convolve(fcZero, fcNaN):
1223 case convolve(fcNormal, fcNaN):
1224 case convolve(fcInfinity, fcNaN):
1225 category = fcNaN;
1226 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001227 return opOK;
1228
1229 case convolve(fcNormal, fcInfinity):
1230 case convolve(fcZero, fcInfinity):
1231 category = fcInfinity;
1232 sign = rhs.sign ^ subtract;
1233 return opOK;
1234
1235 case convolve(fcZero, fcNormal):
1236 assign(rhs);
1237 sign = rhs.sign ^ subtract;
1238 return opOK;
1239
1240 case convolve(fcZero, fcZero):
1241 /* Sign depends on rounding mode; handled by caller. */
1242 return opOK;
1243
1244 case convolve(fcInfinity, fcInfinity):
1245 /* Differently signed infinities can only be validly
1246 subtracted. */
Cedric Venetaff9c272009-02-14 16:06:42 +00001247 if(((sign ^ rhs.sign)!=0) != subtract) {
Neil Boothe5e01942007-10-14 10:39:51 +00001248 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001249 return opInvalidOp;
1250 }
1251
1252 return opOK;
1253
1254 case convolve(fcNormal, fcNormal):
1255 return opDivByZero;
1256 }
1257}
1258
1259/* Add or subtract two normal numbers. */
1260lostFraction
1261APFloat::addOrSubtractSignificand(const APFloat &rhs, bool subtract)
1262{
1263 integerPart carry;
1264 lostFraction lost_fraction;
1265 int bits;
1266
1267 /* Determine if the operation on the absolute values is effectively
1268 an addition or subtraction. */
Hartmut Kaiser8df77a92007-10-25 23:15:31 +00001269 subtract ^= (sign ^ rhs.sign) ? true : false;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001270
1271 /* Are we bigger exponent-wise than the RHS? */
1272 bits = exponent - rhs.exponent;
1273
1274 /* Subtraction is more subtle than one might naively expect. */
1275 if(subtract) {
1276 APFloat temp_rhs(rhs);
1277 bool reverse;
1278
Chris Lattnerada530b2007-08-24 03:02:34 +00001279 if (bits == 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001280 reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan;
1281 lost_fraction = lfExactlyZero;
Chris Lattnerada530b2007-08-24 03:02:34 +00001282 } else if (bits > 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001283 lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
1284 shiftSignificandLeft(1);
1285 reverse = false;
Chris Lattnerada530b2007-08-24 03:02:34 +00001286 } else {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001287 lost_fraction = shiftSignificandRight(-bits - 1);
1288 temp_rhs.shiftSignificandLeft(1);
1289 reverse = true;
1290 }
1291
Chris Lattnerada530b2007-08-24 03:02:34 +00001292 if (reverse) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001293 carry = temp_rhs.subtractSignificand
Neil Booth4f881702007-09-26 21:33:42 +00001294 (*this, lost_fraction != lfExactlyZero);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001295 copySignificand(temp_rhs);
1296 sign = !sign;
1297 } else {
1298 carry = subtractSignificand
Neil Booth4f881702007-09-26 21:33:42 +00001299 (temp_rhs, lost_fraction != lfExactlyZero);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001300 }
1301
1302 /* Invert the lost fraction - it was on the RHS and
1303 subtracted. */
1304 if(lost_fraction == lfLessThanHalf)
1305 lost_fraction = lfMoreThanHalf;
1306 else if(lost_fraction == lfMoreThanHalf)
1307 lost_fraction = lfLessThanHalf;
1308
1309 /* The code above is intended to ensure that no borrow is
1310 necessary. */
1311 assert(!carry);
1312 } else {
1313 if(bits > 0) {
1314 APFloat temp_rhs(rhs);
1315
1316 lost_fraction = temp_rhs.shiftSignificandRight(bits);
1317 carry = addSignificand(temp_rhs);
1318 } else {
1319 lost_fraction = shiftSignificandRight(-bits);
1320 carry = addSignificand(rhs);
1321 }
1322
1323 /* We have a guard bit; generating a carry cannot happen. */
1324 assert(!carry);
1325 }
1326
1327 return lost_fraction;
1328}
1329
1330APFloat::opStatus
1331APFloat::multiplySpecials(const APFloat &rhs)
1332{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001333 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001334 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001335 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001336
Dale Johanneseneaf08942007-08-31 04:03:46 +00001337 case convolve(fcNaN, fcZero):
1338 case convolve(fcNaN, fcNormal):
1339 case convolve(fcNaN, fcInfinity):
1340 case convolve(fcNaN, fcNaN):
1341 return opOK;
1342
1343 case convolve(fcZero, fcNaN):
1344 case convolve(fcNormal, fcNaN):
1345 case convolve(fcInfinity, fcNaN):
1346 category = fcNaN;
1347 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001348 return opOK;
1349
1350 case convolve(fcNormal, fcInfinity):
1351 case convolve(fcInfinity, fcNormal):
1352 case convolve(fcInfinity, fcInfinity):
1353 category = fcInfinity;
1354 return opOK;
1355
1356 case convolve(fcZero, fcNormal):
1357 case convolve(fcNormal, fcZero):
1358 case convolve(fcZero, fcZero):
1359 category = fcZero;
1360 return opOK;
1361
1362 case convolve(fcZero, fcInfinity):
1363 case convolve(fcInfinity, fcZero):
Neil Boothe5e01942007-10-14 10:39:51 +00001364 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001365 return opInvalidOp;
1366
1367 case convolve(fcNormal, fcNormal):
1368 return opOK;
1369 }
1370}
1371
1372APFloat::opStatus
1373APFloat::divideSpecials(const APFloat &rhs)
1374{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001375 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001376 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001377 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001378
Dale Johanneseneaf08942007-08-31 04:03:46 +00001379 case convolve(fcNaN, fcZero):
1380 case convolve(fcNaN, fcNormal):
1381 case convolve(fcNaN, fcInfinity):
1382 case convolve(fcNaN, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001383 case convolve(fcInfinity, fcZero):
1384 case convolve(fcInfinity, fcNormal):
1385 case convolve(fcZero, fcInfinity):
1386 case convolve(fcZero, fcNormal):
1387 return opOK;
1388
Dale Johanneseneaf08942007-08-31 04:03:46 +00001389 case convolve(fcZero, fcNaN):
1390 case convolve(fcNormal, fcNaN):
1391 case convolve(fcInfinity, fcNaN):
1392 category = fcNaN;
1393 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001394 return opOK;
1395
1396 case convolve(fcNormal, fcInfinity):
1397 category = fcZero;
1398 return opOK;
1399
1400 case convolve(fcNormal, fcZero):
1401 category = fcInfinity;
1402 return opDivByZero;
1403
1404 case convolve(fcInfinity, fcInfinity):
1405 case convolve(fcZero, fcZero):
Neil Boothe5e01942007-10-14 10:39:51 +00001406 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001407 return opInvalidOp;
1408
1409 case convolve(fcNormal, fcNormal):
1410 return opOK;
1411 }
1412}
1413
Dale Johannesened6af242009-01-21 00:35:19 +00001414APFloat::opStatus
1415APFloat::modSpecials(const APFloat &rhs)
1416{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001417 switch (convolve(category, rhs.category)) {
Dale Johannesened6af242009-01-21 00:35:19 +00001418 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001419 llvm_unreachable(0);
Dale Johannesened6af242009-01-21 00:35:19 +00001420
1421 case convolve(fcNaN, fcZero):
1422 case convolve(fcNaN, fcNormal):
1423 case convolve(fcNaN, fcInfinity):
1424 case convolve(fcNaN, fcNaN):
1425 case convolve(fcZero, fcInfinity):
1426 case convolve(fcZero, fcNormal):
1427 case convolve(fcNormal, fcInfinity):
1428 return opOK;
1429
1430 case convolve(fcZero, fcNaN):
1431 case convolve(fcNormal, fcNaN):
1432 case convolve(fcInfinity, fcNaN):
1433 category = fcNaN;
1434 copySignificand(rhs);
1435 return opOK;
1436
1437 case convolve(fcNormal, fcZero):
1438 case convolve(fcInfinity, fcZero):
1439 case convolve(fcInfinity, fcNormal):
1440 case convolve(fcInfinity, fcInfinity):
1441 case convolve(fcZero, fcZero):
1442 makeNaN();
1443 return opInvalidOp;
1444
1445 case convolve(fcNormal, fcNormal):
1446 return opOK;
1447 }
1448}
1449
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001450/* Change sign. */
1451void
1452APFloat::changeSign()
1453{
1454 /* Look mummy, this one's easy. */
1455 sign = !sign;
1456}
1457
Dale Johannesene15c2db2007-08-31 23:35:31 +00001458void
1459APFloat::clearSign()
1460{
1461 /* So is this one. */
1462 sign = 0;
1463}
1464
1465void
1466APFloat::copySign(const APFloat &rhs)
1467{
1468 /* And this one. */
1469 sign = rhs.sign;
1470}
1471
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001472/* Normalized addition or subtraction. */
1473APFloat::opStatus
1474APFloat::addOrSubtract(const APFloat &rhs, roundingMode rounding_mode,
Neil Booth4f881702007-09-26 21:33:42 +00001475 bool subtract)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001476{
1477 opStatus fs;
1478
Neil Boothcaf19d72007-10-14 10:29:28 +00001479 assertArithmeticOK(*semantics);
1480
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001481 fs = addOrSubtractSpecials(rhs, subtract);
1482
1483 /* This return code means it was not a simple case. */
1484 if(fs == opDivByZero) {
1485 lostFraction lost_fraction;
1486
1487 lost_fraction = addOrSubtractSignificand(rhs, subtract);
1488 fs = normalize(rounding_mode, lost_fraction);
1489
1490 /* Can only be zero if we lost no fraction. */
1491 assert(category != fcZero || lost_fraction == lfExactlyZero);
1492 }
1493
1494 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1495 positive zero unless rounding to minus infinity, except that
1496 adding two like-signed zeroes gives that zero. */
1497 if(category == fcZero) {
1498 if(rhs.category != fcZero || (sign == rhs.sign) == subtract)
1499 sign = (rounding_mode == rmTowardNegative);
1500 }
1501
1502 return fs;
1503}
1504
1505/* Normalized addition. */
1506APFloat::opStatus
1507APFloat::add(const APFloat &rhs, roundingMode rounding_mode)
1508{
1509 return addOrSubtract(rhs, rounding_mode, false);
1510}
1511
1512/* Normalized subtraction. */
1513APFloat::opStatus
1514APFloat::subtract(const APFloat &rhs, roundingMode rounding_mode)
1515{
1516 return addOrSubtract(rhs, rounding_mode, true);
1517}
1518
1519/* Normalized multiply. */
1520APFloat::opStatus
1521APFloat::multiply(const APFloat &rhs, roundingMode rounding_mode)
1522{
1523 opStatus fs;
1524
Neil Boothcaf19d72007-10-14 10:29:28 +00001525 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001526 sign ^= rhs.sign;
1527 fs = multiplySpecials(rhs);
1528
1529 if(category == fcNormal) {
1530 lostFraction lost_fraction = multiplySignificand(rhs, 0);
1531 fs = normalize(rounding_mode, lost_fraction);
1532 if(lost_fraction != lfExactlyZero)
1533 fs = (opStatus) (fs | opInexact);
1534 }
1535
1536 return fs;
1537}
1538
1539/* Normalized divide. */
1540APFloat::opStatus
1541APFloat::divide(const APFloat &rhs, roundingMode rounding_mode)
1542{
1543 opStatus fs;
1544
Neil Boothcaf19d72007-10-14 10:29:28 +00001545 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001546 sign ^= rhs.sign;
1547 fs = divideSpecials(rhs);
1548
1549 if(category == fcNormal) {
1550 lostFraction lost_fraction = divideSignificand(rhs);
1551 fs = normalize(rounding_mode, lost_fraction);
1552 if(lost_fraction != lfExactlyZero)
1553 fs = (opStatus) (fs | opInexact);
1554 }
1555
1556 return fs;
1557}
1558
Dale Johannesen24b66a82009-01-20 18:35:05 +00001559/* Normalized remainder. This is not currently correct in all cases. */
1560APFloat::opStatus
1561APFloat::remainder(const APFloat &rhs)
1562{
1563 opStatus fs;
1564 APFloat V = *this;
1565 unsigned int origSign = sign;
1566
1567 assertArithmeticOK(*semantics);
1568 fs = V.divide(rhs, rmNearestTiesToEven);
1569 if (fs == opDivByZero)
1570 return fs;
1571
1572 int parts = partCount();
1573 integerPart *x = new integerPart[parts];
1574 bool ignored;
1575 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1576 rmNearestTiesToEven, &ignored);
1577 if (fs==opInvalidOp)
1578 return fs;
1579
1580 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1581 rmNearestTiesToEven);
1582 assert(fs==opOK); // should always work
1583
1584 fs = V.multiply(rhs, rmNearestTiesToEven);
1585 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1586
1587 fs = subtract(V, rmNearestTiesToEven);
1588 assert(fs==opOK || fs==opInexact); // likewise
1589
1590 if (isZero())
1591 sign = origSign; // IEEE754 requires this
1592 delete[] x;
1593 return fs;
1594}
1595
1596/* Normalized llvm frem (C fmod).
1597 This is not currently correct in all cases. */
Dale Johannesene15c2db2007-08-31 23:35:31 +00001598APFloat::opStatus
1599APFloat::mod(const APFloat &rhs, roundingMode rounding_mode)
1600{
1601 opStatus fs;
Neil Boothcaf19d72007-10-14 10:29:28 +00001602 assertArithmeticOK(*semantics);
Dale Johannesened6af242009-01-21 00:35:19 +00001603 fs = modSpecials(rhs);
Dale Johannesene15c2db2007-08-31 23:35:31 +00001604
Dale Johannesened6af242009-01-21 00:35:19 +00001605 if (category == fcNormal && rhs.category == fcNormal) {
1606 APFloat V = *this;
1607 unsigned int origSign = sign;
Dale Johannesene15c2db2007-08-31 23:35:31 +00001608
Dale Johannesened6af242009-01-21 00:35:19 +00001609 fs = V.divide(rhs, rmNearestTiesToEven);
1610 if (fs == opDivByZero)
1611 return fs;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001612
Dale Johannesened6af242009-01-21 00:35:19 +00001613 int parts = partCount();
1614 integerPart *x = new integerPart[parts];
1615 bool ignored;
1616 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1617 rmTowardZero, &ignored);
1618 if (fs==opInvalidOp)
1619 return fs;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001620
Dale Johannesened6af242009-01-21 00:35:19 +00001621 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1622 rmNearestTiesToEven);
1623 assert(fs==opOK); // should always work
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001624
Dale Johannesened6af242009-01-21 00:35:19 +00001625 fs = V.multiply(rhs, rounding_mode);
1626 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1627
1628 fs = subtract(V, rounding_mode);
1629 assert(fs==opOK || fs==opInexact); // likewise
1630
1631 if (isZero())
1632 sign = origSign; // IEEE754 requires this
1633 delete[] x;
1634 }
Dale Johannesene15c2db2007-08-31 23:35:31 +00001635 return fs;
1636}
1637
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001638/* Normalized fused-multiply-add. */
1639APFloat::opStatus
1640APFloat::fusedMultiplyAdd(const APFloat &multiplicand,
Neil Booth4f881702007-09-26 21:33:42 +00001641 const APFloat &addend,
1642 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001643{
1644 opStatus fs;
1645
Neil Boothcaf19d72007-10-14 10:29:28 +00001646 assertArithmeticOK(*semantics);
1647
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001648 /* Post-multiplication sign, before addition. */
1649 sign ^= multiplicand.sign;
1650
1651 /* If and only if all arguments are normal do we need to do an
1652 extended-precision calculation. */
1653 if(category == fcNormal
1654 && multiplicand.category == fcNormal
1655 && addend.category == fcNormal) {
1656 lostFraction lost_fraction;
1657
1658 lost_fraction = multiplySignificand(multiplicand, &addend);
1659 fs = normalize(rounding_mode, lost_fraction);
1660 if(lost_fraction != lfExactlyZero)
1661 fs = (opStatus) (fs | opInexact);
1662
1663 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1664 positive zero unless rounding to minus infinity, except that
1665 adding two like-signed zeroes gives that zero. */
1666 if(category == fcZero && sign != addend.sign)
1667 sign = (rounding_mode == rmTowardNegative);
1668 } else {
1669 fs = multiplySpecials(multiplicand);
1670
1671 /* FS can only be opOK or opInvalidOp. There is no more work
1672 to do in the latter case. The IEEE-754R standard says it is
1673 implementation-defined in this case whether, if ADDEND is a
Dale Johanneseneaf08942007-08-31 04:03:46 +00001674 quiet NaN, we raise invalid op; this implementation does so.
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001675
1676 If we need to do the addition we can do so with normal
1677 precision. */
1678 if(fs == opOK)
1679 fs = addOrSubtract(addend, rounding_mode, false);
1680 }
1681
1682 return fs;
1683}
1684
1685/* Comparison requires normalized numbers. */
1686APFloat::cmpResult
1687APFloat::compare(const APFloat &rhs) const
1688{
1689 cmpResult result;
1690
Neil Boothcaf19d72007-10-14 10:29:28 +00001691 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001692 assert(semantics == rhs.semantics);
1693
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001694 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001695 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001696 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001697
Dale Johanneseneaf08942007-08-31 04:03:46 +00001698 case convolve(fcNaN, fcZero):
1699 case convolve(fcNaN, fcNormal):
1700 case convolve(fcNaN, fcInfinity):
1701 case convolve(fcNaN, fcNaN):
1702 case convolve(fcZero, fcNaN):
1703 case convolve(fcNormal, fcNaN):
1704 case convolve(fcInfinity, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001705 return cmpUnordered;
1706
1707 case convolve(fcInfinity, fcNormal):
1708 case convolve(fcInfinity, fcZero):
1709 case convolve(fcNormal, fcZero):
1710 if(sign)
1711 return cmpLessThan;
1712 else
1713 return cmpGreaterThan;
1714
1715 case convolve(fcNormal, fcInfinity):
1716 case convolve(fcZero, fcInfinity):
1717 case convolve(fcZero, fcNormal):
1718 if(rhs.sign)
1719 return cmpGreaterThan;
1720 else
1721 return cmpLessThan;
1722
1723 case convolve(fcInfinity, fcInfinity):
1724 if(sign == rhs.sign)
1725 return cmpEqual;
1726 else if(sign)
1727 return cmpLessThan;
1728 else
1729 return cmpGreaterThan;
1730
1731 case convolve(fcZero, fcZero):
1732 return cmpEqual;
1733
1734 case convolve(fcNormal, fcNormal):
1735 break;
1736 }
1737
1738 /* Two normal numbers. Do they have the same sign? */
1739 if(sign != rhs.sign) {
1740 if(sign)
1741 result = cmpLessThan;
1742 else
1743 result = cmpGreaterThan;
1744 } else {
1745 /* Compare absolute values; invert result if negative. */
1746 result = compareAbsoluteValue(rhs);
1747
1748 if(sign) {
1749 if(result == cmpLessThan)
Neil Booth4f881702007-09-26 21:33:42 +00001750 result = cmpGreaterThan;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001751 else if(result == cmpGreaterThan)
Neil Booth4f881702007-09-26 21:33:42 +00001752 result = cmpLessThan;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001753 }
1754 }
1755
1756 return result;
1757}
1758
Dale Johannesen23a98552008-10-09 23:00:39 +00001759/// APFloat::convert - convert a value of one floating point type to another.
1760/// The return value corresponds to the IEEE754 exceptions. *losesInfo
1761/// records whether the transformation lost information, i.e. whether
1762/// converting the result back to the original type will produce the
1763/// original value (this is almost the same as return value==fsOK, but there
1764/// are edge cases where this is not so).
1765
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001766APFloat::opStatus
1767APFloat::convert(const fltSemantics &toSemantics,
Dale Johannesen23a98552008-10-09 23:00:39 +00001768 roundingMode rounding_mode, bool *losesInfo)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001769{
Neil Boothc8db43d2007-09-22 02:56:19 +00001770 lostFraction lostFraction;
1771 unsigned int newPartCount, oldPartCount;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001772 opStatus fs;
Neil Booth4f881702007-09-26 21:33:42 +00001773
Neil Boothcaf19d72007-10-14 10:29:28 +00001774 assertArithmeticOK(*semantics);
Dale Johannesen79f82f92008-04-20 01:34:03 +00001775 assertArithmeticOK(toSemantics);
Neil Boothc8db43d2007-09-22 02:56:19 +00001776 lostFraction = lfExactlyZero;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001777 newPartCount = partCountForBits(toSemantics.precision + 1);
Neil Boothc8db43d2007-09-22 02:56:19 +00001778 oldPartCount = partCount();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001779
Neil Boothc8db43d2007-09-22 02:56:19 +00001780 /* Handle storage complications. If our new form is wider,
1781 re-allocate our bit pattern into wider storage. If it is
1782 narrower, we ignore the excess parts, but if narrowing to a
Dale Johannesen902ff942007-09-25 17:25:00 +00001783 single part we need to free the old storage.
1784 Be careful not to reference significandParts for zeroes
1785 and infinities, since it aborts. */
Neil Boothc8db43d2007-09-22 02:56:19 +00001786 if (newPartCount > oldPartCount) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001787 integerPart *newParts;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001788 newParts = new integerPart[newPartCount];
1789 APInt::tcSet(newParts, 0, newPartCount);
Dale Johannesen902ff942007-09-25 17:25:00 +00001790 if (category==fcNormal || category==fcNaN)
1791 APInt::tcAssign(newParts, significandParts(), oldPartCount);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001792 freeSignificand();
1793 significand.parts = newParts;
Neil Boothc8db43d2007-09-22 02:56:19 +00001794 } else if (newPartCount < oldPartCount) {
1795 /* Capture any lost fraction through truncation of parts so we get
1796 correct rounding whilst normalizing. */
Dale Johannesen902ff942007-09-25 17:25:00 +00001797 if (category==fcNormal)
1798 lostFraction = lostFractionThroughTruncation
1799 (significandParts(), oldPartCount, toSemantics.precision);
1800 if (newPartCount == 1) {
1801 integerPart newPart = 0;
Neil Booth4f881702007-09-26 21:33:42 +00001802 if (category==fcNormal || category==fcNaN)
Dale Johannesen902ff942007-09-25 17:25:00 +00001803 newPart = significandParts()[0];
1804 freeSignificand();
1805 significand.part = newPart;
1806 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001807 }
1808
1809 if(category == fcNormal) {
1810 /* Re-interpret our bit-pattern. */
1811 exponent += toSemantics.precision - semantics->precision;
1812 semantics = &toSemantics;
Neil Boothc8db43d2007-09-22 02:56:19 +00001813 fs = normalize(rounding_mode, lostFraction);
Dale Johannesen23a98552008-10-09 23:00:39 +00001814 *losesInfo = (fs != opOK);
Dale Johannesen902ff942007-09-25 17:25:00 +00001815 } else if (category == fcNaN) {
1816 int shift = toSemantics.precision - semantics->precision;
Dale Johannesenb63fa052008-01-31 18:34:01 +00001817 // Do this now so significandParts gets the right answer
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001818 const fltSemantics *oldSemantics = semantics;
Dale Johannesenb63fa052008-01-31 18:34:01 +00001819 semantics = &toSemantics;
Dale Johannesen23a98552008-10-09 23:00:39 +00001820 *losesInfo = false;
Dale Johannesen902ff942007-09-25 17:25:00 +00001821 // No normalization here, just truncate
1822 if (shift>0)
1823 APInt::tcShiftLeft(significandParts(), newPartCount, shift);
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001824 else if (shift < 0) {
1825 unsigned ushift = -shift;
Dale Johannesen23a98552008-10-09 23:00:39 +00001826 // Figure out if we are losing information. This happens
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001827 // if are shifting out something other than 0s, or if the x87 long
1828 // double input did not have its integer bit set (pseudo-NaN), or if the
1829 // x87 long double input did not have its QNan bit set (because the x87
1830 // hardware sets this bit when converting a lower-precision NaN to
1831 // x87 long double).
1832 if (APInt::tcLSB(significandParts(), newPartCount) < ushift)
Dale Johannesen23a98552008-10-09 23:00:39 +00001833 *losesInfo = true;
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001834 if (oldSemantics == &APFloat::x87DoubleExtended &&
1835 (!(*significandParts() & 0x8000000000000000ULL) ||
1836 !(*significandParts() & 0x4000000000000000ULL)))
Dale Johannesen23a98552008-10-09 23:00:39 +00001837 *losesInfo = true;
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001838 APInt::tcShiftRight(significandParts(), newPartCount, ushift);
1839 }
Dale Johannesen902ff942007-09-25 17:25:00 +00001840 // gcc forces the Quiet bit on, which means (float)(double)(float_sNan)
1841 // does not give you back the same bits. This is dubious, and we
1842 // don't currently do it. You're really supposed to get
1843 // an invalid operation signal at runtime, but nobody does that.
Dale Johannesen23a98552008-10-09 23:00:39 +00001844 fs = opOK;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001845 } else {
1846 semantics = &toSemantics;
1847 fs = opOK;
Dale Johannesen23a98552008-10-09 23:00:39 +00001848 *losesInfo = false;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001849 }
1850
1851 return fs;
1852}
1853
1854/* Convert a floating point number to an integer according to the
1855 rounding mode. If the rounded integer value is out of range this
Neil Boothee7ae382007-11-01 22:43:37 +00001856 returns an invalid operation exception and the contents of the
1857 destination parts are unspecified. If the rounded value is in
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001858 range but the floating point number is not the exact integer, the C
1859 standard doesn't require an inexact exception to be raised. IEEE
1860 854 does require it so we do that.
1861
1862 Note that for conversions to integer type the C standard requires
1863 round-to-zero to always be used. */
1864APFloat::opStatus
Neil Boothee7ae382007-11-01 22:43:37 +00001865APFloat::convertToSignExtendedInteger(integerPart *parts, unsigned int width,
1866 bool isSigned,
Dale Johannesen23a98552008-10-09 23:00:39 +00001867 roundingMode rounding_mode,
1868 bool *isExact) const
Neil Boothee7ae382007-11-01 22:43:37 +00001869{
1870 lostFraction lost_fraction;
1871 const integerPart *src;
1872 unsigned int dstPartsCount, truncatedBits;
1873
Evan Cheng794a7db2008-11-26 01:11:57 +00001874 assertArithmeticOK(*semantics);
Neil Boothe3d936a2007-11-02 15:10:05 +00001875
Dale Johannesen23a98552008-10-09 23:00:39 +00001876 *isExact = false;
1877
Neil Boothee7ae382007-11-01 22:43:37 +00001878 /* Handle the three special cases first. */
1879 if(category == fcInfinity || category == fcNaN)
1880 return opInvalidOp;
1881
1882 dstPartsCount = partCountForBits(width);
1883
1884 if(category == fcZero) {
1885 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesene4a42452008-10-07 00:40:01 +00001886 // Negative zero can't be represented as an int.
Dale Johannesen23a98552008-10-09 23:00:39 +00001887 *isExact = !sign;
1888 return opOK;
Neil Boothee7ae382007-11-01 22:43:37 +00001889 }
1890
1891 src = significandParts();
1892
1893 /* Step 1: place our absolute value, with any fraction truncated, in
1894 the destination. */
1895 if (exponent < 0) {
1896 /* Our absolute value is less than one; truncate everything. */
1897 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesen1f54f582009-01-19 21:17:05 +00001898 /* For exponent -1 the integer bit represents .5, look at that.
1899 For smaller exponents leftmost truncated bit is 0. */
1900 truncatedBits = semantics->precision -1U - exponent;
Neil Boothee7ae382007-11-01 22:43:37 +00001901 } else {
1902 /* We want the most significant (exponent + 1) bits; the rest are
1903 truncated. */
1904 unsigned int bits = exponent + 1U;
1905
1906 /* Hopelessly large in magnitude? */
1907 if (bits > width)
1908 return opInvalidOp;
1909
1910 if (bits < semantics->precision) {
1911 /* We truncate (semantics->precision - bits) bits. */
1912 truncatedBits = semantics->precision - bits;
1913 APInt::tcExtract(parts, dstPartsCount, src, bits, truncatedBits);
1914 } else {
1915 /* We want at least as many bits as are available. */
1916 APInt::tcExtract(parts, dstPartsCount, src, semantics->precision, 0);
1917 APInt::tcShiftLeft(parts, dstPartsCount, bits - semantics->precision);
1918 truncatedBits = 0;
1919 }
1920 }
1921
1922 /* Step 2: work out any lost fraction, and increment the absolute
1923 value if we would round away from zero. */
1924 if (truncatedBits) {
1925 lost_fraction = lostFractionThroughTruncation(src, partCount(),
1926 truncatedBits);
1927 if (lost_fraction != lfExactlyZero
1928 && roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
1929 if (APInt::tcIncrement(parts, dstPartsCount))
1930 return opInvalidOp; /* Overflow. */
1931 }
1932 } else {
1933 lost_fraction = lfExactlyZero;
1934 }
1935
1936 /* Step 3: check if we fit in the destination. */
1937 unsigned int omsb = APInt::tcMSB(parts, dstPartsCount) + 1;
1938
1939 if (sign) {
1940 if (!isSigned) {
1941 /* Negative numbers cannot be represented as unsigned. */
1942 if (omsb != 0)
1943 return opInvalidOp;
1944 } else {
1945 /* It takes omsb bits to represent the unsigned integer value.
1946 We lose a bit for the sign, but care is needed as the
1947 maximally negative integer is a special case. */
1948 if (omsb == width && APInt::tcLSB(parts, dstPartsCount) + 1 != omsb)
1949 return opInvalidOp;
1950
1951 /* This case can happen because of rounding. */
1952 if (omsb > width)
1953 return opInvalidOp;
1954 }
1955
1956 APInt::tcNegate (parts, dstPartsCount);
1957 } else {
1958 if (omsb >= width + !isSigned)
1959 return opInvalidOp;
1960 }
1961
Dale Johannesen23a98552008-10-09 23:00:39 +00001962 if (lost_fraction == lfExactlyZero) {
1963 *isExact = true;
Neil Boothee7ae382007-11-01 22:43:37 +00001964 return opOK;
Dale Johannesen23a98552008-10-09 23:00:39 +00001965 } else
Neil Boothee7ae382007-11-01 22:43:37 +00001966 return opInexact;
1967}
1968
1969/* Same as convertToSignExtendedInteger, except we provide
1970 deterministic values in case of an invalid operation exception,
1971 namely zero for NaNs and the minimal or maximal value respectively
Dale Johannesen23a98552008-10-09 23:00:39 +00001972 for underflow or overflow.
1973 The *isExact output tells whether the result is exact, in the sense
1974 that converting it back to the original floating point type produces
1975 the original value. This is almost equivalent to result==opOK,
1976 except for negative zeroes.
1977*/
Neil Boothee7ae382007-11-01 22:43:37 +00001978APFloat::opStatus
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001979APFloat::convertToInteger(integerPart *parts, unsigned int width,
Neil Booth4f881702007-09-26 21:33:42 +00001980 bool isSigned,
Dale Johannesen23a98552008-10-09 23:00:39 +00001981 roundingMode rounding_mode, bool *isExact) const
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001982{
Neil Boothee7ae382007-11-01 22:43:37 +00001983 opStatus fs;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001984
Dale Johannesen23a98552008-10-09 23:00:39 +00001985 fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode,
1986 isExact);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001987
Neil Boothee7ae382007-11-01 22:43:37 +00001988 if (fs == opInvalidOp) {
1989 unsigned int bits, dstPartsCount;
1990
1991 dstPartsCount = partCountForBits(width);
1992
1993 if (category == fcNaN)
1994 bits = 0;
1995 else if (sign)
1996 bits = isSigned;
1997 else
1998 bits = width - isSigned;
1999
2000 APInt::tcSetLeastSignificantBits(parts, dstPartsCount, bits);
2001 if (sign && isSigned)
2002 APInt::tcShiftLeft(parts, dstPartsCount, width - 1);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002003 }
2004
Neil Boothee7ae382007-11-01 22:43:37 +00002005 return fs;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002006}
2007
Neil Booth643ce592007-10-07 12:07:53 +00002008/* Convert an unsigned integer SRC to a floating point number,
2009 rounding according to ROUNDING_MODE. The sign of the floating
2010 point number is not modified. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002011APFloat::opStatus
Neil Booth643ce592007-10-07 12:07:53 +00002012APFloat::convertFromUnsignedParts(const integerPart *src,
2013 unsigned int srcCount,
2014 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002015{
Neil Booth5477f852007-10-08 14:39:42 +00002016 unsigned int omsb, precision, dstCount;
Neil Booth643ce592007-10-07 12:07:53 +00002017 integerPart *dst;
Neil Booth5477f852007-10-08 14:39:42 +00002018 lostFraction lost_fraction;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002019
Neil Boothcaf19d72007-10-14 10:29:28 +00002020 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002021 category = fcNormal;
Neil Booth5477f852007-10-08 14:39:42 +00002022 omsb = APInt::tcMSB(src, srcCount) + 1;
Neil Booth643ce592007-10-07 12:07:53 +00002023 dst = significandParts();
2024 dstCount = partCount();
Neil Booth5477f852007-10-08 14:39:42 +00002025 precision = semantics->precision;
Neil Booth643ce592007-10-07 12:07:53 +00002026
Neil Booth5477f852007-10-08 14:39:42 +00002027 /* We want the most significant PRECISON bits of SRC. There may not
2028 be that many; extract what we can. */
2029 if (precision <= omsb) {
2030 exponent = omsb - 1;
Neil Booth643ce592007-10-07 12:07:53 +00002031 lost_fraction = lostFractionThroughTruncation(src, srcCount,
Neil Booth5477f852007-10-08 14:39:42 +00002032 omsb - precision);
2033 APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
2034 } else {
2035 exponent = precision - 1;
2036 lost_fraction = lfExactlyZero;
2037 APInt::tcExtract(dst, dstCount, src, omsb, 0);
Neil Booth643ce592007-10-07 12:07:53 +00002038 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002039
2040 return normalize(rounding_mode, lost_fraction);
2041}
2042
Dan Gohman93c276e2008-02-29 01:26:11 +00002043APFloat::opStatus
2044APFloat::convertFromAPInt(const APInt &Val,
2045 bool isSigned,
2046 roundingMode rounding_mode)
2047{
2048 unsigned int partCount = Val.getNumWords();
2049 APInt api = Val;
2050
2051 sign = false;
2052 if (isSigned && api.isNegative()) {
2053 sign = true;
2054 api = -api;
2055 }
2056
2057 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
2058}
2059
Neil Boothf16c5952007-10-07 12:15:41 +00002060/* Convert a two's complement integer SRC to a floating point number,
2061 rounding according to ROUNDING_MODE. ISSIGNED is true if the
2062 integer is signed, in which case it must be sign-extended. */
2063APFloat::opStatus
2064APFloat::convertFromSignExtendedInteger(const integerPart *src,
2065 unsigned int srcCount,
2066 bool isSigned,
2067 roundingMode rounding_mode)
2068{
2069 opStatus status;
2070
Neil Boothcaf19d72007-10-14 10:29:28 +00002071 assertArithmeticOK(*semantics);
Neil Boothf16c5952007-10-07 12:15:41 +00002072 if (isSigned
2073 && APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) {
2074 integerPart *copy;
2075
2076 /* If we're signed and negative negate a copy. */
2077 sign = true;
2078 copy = new integerPart[srcCount];
2079 APInt::tcAssign(copy, src, srcCount);
2080 APInt::tcNegate(copy, srcCount);
2081 status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
2082 delete [] copy;
2083 } else {
2084 sign = false;
2085 status = convertFromUnsignedParts(src, srcCount, rounding_mode);
2086 }
2087
2088 return status;
2089}
2090
Neil Boothccf596a2007-10-07 11:45:55 +00002091/* FIXME: should this just take a const APInt reference? */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002092APFloat::opStatus
Neil Boothccf596a2007-10-07 11:45:55 +00002093APFloat::convertFromZeroExtendedInteger(const integerPart *parts,
2094 unsigned int width, bool isSigned,
2095 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002096{
Dale Johannesen910993e2007-09-21 22:09:37 +00002097 unsigned int partCount = partCountForBits(width);
Dale Johannesen910993e2007-09-21 22:09:37 +00002098 APInt api = APInt(width, partCount, parts);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002099
2100 sign = false;
Dale Johannesencce23a42007-09-30 18:17:01 +00002101 if(isSigned && APInt::tcExtractBit(parts, width - 1)) {
2102 sign = true;
2103 api = -api;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002104 }
2105
Neil Booth7a7bc0f2007-10-07 12:10:57 +00002106 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002107}
2108
2109APFloat::opStatus
2110APFloat::convertFromHexadecimalString(const char *p,
Neil Booth4f881702007-09-26 21:33:42 +00002111 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002112{
2113 lostFraction lost_fraction;
2114 integerPart *significand;
2115 unsigned int bitPos, partsCount;
2116 const char *dot, *firstSignificantDigit;
2117
2118 zeroSignificand();
2119 exponent = 0;
2120 category = fcNormal;
2121
2122 significand = significandParts();
2123 partsCount = partCount();
2124 bitPos = partsCount * integerPartWidth;
2125
Neil Booth33d4c922007-10-07 08:51:21 +00002126 /* Skip leading zeroes and any (hexa)decimal point. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002127 p = skipLeadingZeroesAndAnyDot(p, &dot);
2128 firstSignificantDigit = p;
2129
2130 for(;;) {
Dale Johannesen386f3e92008-05-14 22:53:25 +00002131 integerPart hex_value;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002132
2133 if(*p == '.') {
2134 assert(dot == 0);
2135 dot = p++;
2136 }
2137
2138 hex_value = hexDigitValue(*p);
2139 if(hex_value == -1U) {
2140 lost_fraction = lfExactlyZero;
2141 break;
2142 }
2143
2144 p++;
2145
2146 /* Store the number whilst 4-bit nibbles remain. */
2147 if(bitPos) {
2148 bitPos -= 4;
2149 hex_value <<= bitPos % integerPartWidth;
2150 significand[bitPos / integerPartWidth] |= hex_value;
2151 } else {
2152 lost_fraction = trailingHexadecimalFraction(p, hex_value);
2153 while(hexDigitValue(*p) != -1U)
Neil Booth4f881702007-09-26 21:33:42 +00002154 p++;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002155 break;
2156 }
2157 }
2158
2159 /* Hex floats require an exponent but not a hexadecimal point. */
2160 assert(*p == 'p' || *p == 'P');
2161
2162 /* Ignore the exponent if we are zero. */
2163 if(p != firstSignificantDigit) {
2164 int expAdjustment;
2165
2166 /* Implicit hexadecimal point? */
2167 if(!dot)
2168 dot = p;
2169
2170 /* Calculate the exponent adjustment implicit in the number of
2171 significant digits. */
Evan Cheng48e8c802008-05-02 21:15:08 +00002172 expAdjustment = static_cast<int>(dot - firstSignificantDigit);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002173 if(expAdjustment < 0)
2174 expAdjustment++;
2175 expAdjustment = expAdjustment * 4 - 1;
2176
2177 /* Adjust for writing the significand starting at the most
2178 significant nibble. */
2179 expAdjustment += semantics->precision;
2180 expAdjustment -= partsCount * integerPartWidth;
2181
2182 /* Adjust for the given exponent. */
2183 exponent = totalExponent(p, expAdjustment);
2184 }
2185
2186 return normalize(rounding_mode, lost_fraction);
2187}
2188
2189APFloat::opStatus
Neil Booth96c74712007-10-12 16:02:31 +00002190APFloat::roundSignificandWithExponent(const integerPart *decSigParts,
2191 unsigned sigPartCount, int exp,
2192 roundingMode rounding_mode)
2193{
2194 unsigned int parts, pow5PartCount;
Neil Boothcaf19d72007-10-14 10:29:28 +00002195 fltSemantics calcSemantics = { 32767, -32767, 0, true };
Neil Booth96c74712007-10-12 16:02:31 +00002196 integerPart pow5Parts[maxPowerOfFiveParts];
2197 bool isNearest;
2198
2199 isNearest = (rounding_mode == rmNearestTiesToEven
2200 || rounding_mode == rmNearestTiesToAway);
2201
2202 parts = partCountForBits(semantics->precision + 11);
2203
2204 /* Calculate pow(5, abs(exp)). */
2205 pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp);
2206
2207 for (;; parts *= 2) {
2208 opStatus sigStatus, powStatus;
2209 unsigned int excessPrecision, truncatedBits;
2210
2211 calcSemantics.precision = parts * integerPartWidth - 1;
2212 excessPrecision = calcSemantics.precision - semantics->precision;
2213 truncatedBits = excessPrecision;
2214
2215 APFloat decSig(calcSemantics, fcZero, sign);
2216 APFloat pow5(calcSemantics, fcZero, false);
2217
2218 sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount,
2219 rmNearestTiesToEven);
2220 powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
2221 rmNearestTiesToEven);
2222 /* Add exp, as 10^n = 5^n * 2^n. */
2223 decSig.exponent += exp;
2224
2225 lostFraction calcLostFraction;
Evan Cheng48e8c802008-05-02 21:15:08 +00002226 integerPart HUerr, HUdistance;
2227 unsigned int powHUerr;
Neil Booth96c74712007-10-12 16:02:31 +00002228
2229 if (exp >= 0) {
2230 /* multiplySignificand leaves the precision-th bit set to 1. */
2231 calcLostFraction = decSig.multiplySignificand(pow5, NULL);
2232 powHUerr = powStatus != opOK;
2233 } else {
2234 calcLostFraction = decSig.divideSignificand(pow5);
2235 /* Denormal numbers have less precision. */
2236 if (decSig.exponent < semantics->minExponent) {
2237 excessPrecision += (semantics->minExponent - decSig.exponent);
2238 truncatedBits = excessPrecision;
2239 if (excessPrecision > calcSemantics.precision)
2240 excessPrecision = calcSemantics.precision;
2241 }
2242 /* Extra half-ulp lost in reciprocal of exponent. */
Evan Cheng48e8c802008-05-02 21:15:08 +00002243 powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2;
Neil Booth96c74712007-10-12 16:02:31 +00002244 }
2245
2246 /* Both multiplySignificand and divideSignificand return the
2247 result with the integer bit set. */
2248 assert (APInt::tcExtractBit
2249 (decSig.significandParts(), calcSemantics.precision - 1) == 1);
2250
2251 HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK,
2252 powHUerr);
2253 HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
2254 excessPrecision, isNearest);
2255
2256 /* Are we guaranteed to round correctly if we truncate? */
2257 if (HUdistance >= HUerr) {
2258 APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
2259 calcSemantics.precision - excessPrecision,
2260 excessPrecision);
2261 /* Take the exponent of decSig. If we tcExtract-ed less bits
2262 above we must adjust our exponent to compensate for the
2263 implicit right shift. */
2264 exponent = (decSig.exponent + semantics->precision
2265 - (calcSemantics.precision - excessPrecision));
2266 calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(),
2267 decSig.partCount(),
2268 truncatedBits);
2269 return normalize(rounding_mode, calcLostFraction);
2270 }
2271 }
2272}
2273
2274APFloat::opStatus
2275APFloat::convertFromDecimalString(const char *p, roundingMode rounding_mode)
2276{
Neil Booth1870f292007-10-14 10:16:12 +00002277 decimalInfo D;
Neil Booth96c74712007-10-12 16:02:31 +00002278 opStatus fs;
2279
Neil Booth1870f292007-10-14 10:16:12 +00002280 /* Scan the text. */
2281 interpretDecimal(p, &D);
Neil Booth96c74712007-10-12 16:02:31 +00002282
Neil Booth686700e2007-10-15 15:00:55 +00002283 /* Handle the quick cases. First the case of no significant digits,
2284 i.e. zero, and then exponents that are obviously too large or too
2285 small. Writing L for log 10 / log 2, a number d.ddddd*10^exp
2286 definitely overflows if
2287
2288 (exp - 1) * L >= maxExponent
2289
2290 and definitely underflows to zero where
2291
2292 (exp + 1) * L <= minExponent - precision
2293
2294 With integer arithmetic the tightest bounds for L are
2295
2296 93/28 < L < 196/59 [ numerator <= 256 ]
2297 42039/12655 < L < 28738/8651 [ numerator <= 65536 ]
2298 */
2299
Neil Boothcc233592007-12-05 13:06:04 +00002300 if (decDigitValue(*D.firstSigDigit) >= 10U) {
Neil Booth96c74712007-10-12 16:02:31 +00002301 category = fcZero;
2302 fs = opOK;
Neil Booth686700e2007-10-15 15:00:55 +00002303 } else if ((D.normalizedExponent + 1) * 28738
2304 <= 8651 * (semantics->minExponent - (int) semantics->precision)) {
2305 /* Underflow to zero and round. */
2306 zeroSignificand();
2307 fs = normalize(rounding_mode, lfLessThanHalf);
2308 } else if ((D.normalizedExponent - 1) * 42039
2309 >= 12655 * semantics->maxExponent) {
2310 /* Overflow and round. */
2311 fs = handleOverflow(rounding_mode);
Neil Booth96c74712007-10-12 16:02:31 +00002312 } else {
Neil Booth1870f292007-10-14 10:16:12 +00002313 integerPart *decSignificand;
2314 unsigned int partCount;
Neil Booth96c74712007-10-12 16:02:31 +00002315
Neil Booth1870f292007-10-14 10:16:12 +00002316 /* A tight upper bound on number of bits required to hold an
Neil Booth686700e2007-10-15 15:00:55 +00002317 N-digit decimal integer is N * 196 / 59. Allocate enough space
Neil Booth1870f292007-10-14 10:16:12 +00002318 to hold the full significand, and an extra part required by
2319 tcMultiplyPart. */
Evan Cheng48e8c802008-05-02 21:15:08 +00002320 partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1;
Neil Booth686700e2007-10-15 15:00:55 +00002321 partCount = partCountForBits(1 + 196 * partCount / 59);
Neil Booth1870f292007-10-14 10:16:12 +00002322 decSignificand = new integerPart[partCount + 1];
2323 partCount = 0;
Neil Booth96c74712007-10-12 16:02:31 +00002324
Neil Booth1870f292007-10-14 10:16:12 +00002325 /* Convert to binary efficiently - we do almost all multiplication
2326 in an integerPart. When this would overflow do we do a single
2327 bignum multiplication, and then revert again to multiplication
2328 in an integerPart. */
2329 do {
2330 integerPart decValue, val, multiplier;
2331
2332 val = 0;
2333 multiplier = 1;
2334
2335 do {
2336 if (*p == '.')
2337 p++;
2338
2339 decValue = decDigitValue(*p++);
2340 multiplier *= 10;
2341 val = val * 10 + decValue;
2342 /* The maximum number that can be multiplied by ten with any
2343 digit added without overflowing an integerPart. */
2344 } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
2345
2346 /* Multiply out the current part. */
2347 APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
2348 partCount, partCount + 1, false);
2349
2350 /* If we used another part (likely but not guaranteed), increase
2351 the count. */
2352 if (decSignificand[partCount])
2353 partCount++;
2354 } while (p <= D.lastSigDigit);
Neil Booth96c74712007-10-12 16:02:31 +00002355
Neil Booth43a4b282007-11-01 22:51:07 +00002356 category = fcNormal;
Neil Booth96c74712007-10-12 16:02:31 +00002357 fs = roundSignificandWithExponent(decSignificand, partCount,
Neil Booth1870f292007-10-14 10:16:12 +00002358 D.exponent, rounding_mode);
Neil Booth96c74712007-10-12 16:02:31 +00002359
Neil Booth1870f292007-10-14 10:16:12 +00002360 delete [] decSignificand;
2361 }
Neil Booth96c74712007-10-12 16:02:31 +00002362
2363 return fs;
2364}
2365
2366APFloat::opStatus
Neil Booth4f881702007-09-26 21:33:42 +00002367APFloat::convertFromString(const char *p, roundingMode rounding_mode)
2368{
Neil Boothcaf19d72007-10-14 10:29:28 +00002369 assertArithmeticOK(*semantics);
2370
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002371 /* Handle a leading minus sign. */
2372 if(*p == '-')
2373 sign = 1, p++;
2374 else
2375 sign = 0;
2376
2377 if(p[0] == '0' && (p[1] == 'x' || p[1] == 'X'))
2378 return convertFromHexadecimalString(p + 2, rounding_mode);
Bill Wendlingb7c0d942008-11-27 08:00:12 +00002379
2380 return convertFromDecimalString(p, rounding_mode);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002381}
Dale Johannesen343e7702007-08-24 00:56:33 +00002382
Neil Bootha30b0ee2007-10-03 22:26:02 +00002383/* Write out a hexadecimal representation of the floating point value
2384 to DST, which must be of sufficient size, in the C99 form
2385 [-]0xh.hhhhp[+-]d. Return the number of characters written,
2386 excluding the terminating NUL.
2387
2388 If UPPERCASE, the output is in upper case, otherwise in lower case.
2389
2390 HEXDIGITS digits appear altogether, rounding the value if
2391 necessary. If HEXDIGITS is 0, the minimal precision to display the
2392 number precisely is used instead. If nothing would appear after
2393 the decimal point it is suppressed.
2394
2395 The decimal exponent is always printed and has at least one digit.
2396 Zero values display an exponent of zero. Infinities and NaNs
2397 appear as "infinity" or "nan" respectively.
2398
2399 The above rules are as specified by C99. There is ambiguity about
2400 what the leading hexadecimal digit should be. This implementation
2401 uses whatever is necessary so that the exponent is displayed as
2402 stored. This implies the exponent will fall within the IEEE format
2403 range, and the leading hexadecimal digit will be 0 (for denormals),
2404 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
2405 any other digits zero).
2406*/
2407unsigned int
2408APFloat::convertToHexString(char *dst, unsigned int hexDigits,
2409 bool upperCase, roundingMode rounding_mode) const
2410{
2411 char *p;
2412
Neil Boothcaf19d72007-10-14 10:29:28 +00002413 assertArithmeticOK(*semantics);
2414
Neil Bootha30b0ee2007-10-03 22:26:02 +00002415 p = dst;
2416 if (sign)
2417 *dst++ = '-';
2418
2419 switch (category) {
2420 case fcInfinity:
2421 memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
2422 dst += sizeof infinityL - 1;
2423 break;
2424
2425 case fcNaN:
2426 memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
2427 dst += sizeof NaNU - 1;
2428 break;
2429
2430 case fcZero:
2431 *dst++ = '0';
2432 *dst++ = upperCase ? 'X': 'x';
2433 *dst++ = '0';
2434 if (hexDigits > 1) {
2435 *dst++ = '.';
2436 memset (dst, '0', hexDigits - 1);
2437 dst += hexDigits - 1;
2438 }
2439 *dst++ = upperCase ? 'P': 'p';
2440 *dst++ = '0';
2441 break;
2442
2443 case fcNormal:
2444 dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
2445 break;
2446 }
2447
2448 *dst = 0;
2449
Evan Cheng48e8c802008-05-02 21:15:08 +00002450 return static_cast<unsigned int>(dst - p);
Neil Bootha30b0ee2007-10-03 22:26:02 +00002451}
2452
2453/* Does the hard work of outputting the correctly rounded hexadecimal
2454 form of a normal floating point number with the specified number of
2455 hexadecimal digits. If HEXDIGITS is zero the minimum number of
2456 digits necessary to print the value precisely is output. */
2457char *
2458APFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
2459 bool upperCase,
2460 roundingMode rounding_mode) const
2461{
2462 unsigned int count, valueBits, shift, partsCount, outputDigits;
2463 const char *hexDigitChars;
2464 const integerPart *significand;
2465 char *p;
2466 bool roundUp;
2467
2468 *dst++ = '0';
2469 *dst++ = upperCase ? 'X': 'x';
2470
2471 roundUp = false;
2472 hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower;
2473
2474 significand = significandParts();
2475 partsCount = partCount();
2476
2477 /* +3 because the first digit only uses the single integer bit, so
2478 we have 3 virtual zero most-significant-bits. */
2479 valueBits = semantics->precision + 3;
2480 shift = integerPartWidth - valueBits % integerPartWidth;
2481
2482 /* The natural number of digits required ignoring trailing
2483 insignificant zeroes. */
2484 outputDigits = (valueBits - significandLSB () + 3) / 4;
2485
2486 /* hexDigits of zero means use the required number for the
2487 precision. Otherwise, see if we are truncating. If we are,
Neil Booth978661d2007-10-06 00:24:48 +00002488 find out if we need to round away from zero. */
Neil Bootha30b0ee2007-10-03 22:26:02 +00002489 if (hexDigits) {
2490 if (hexDigits < outputDigits) {
2491 /* We are dropping non-zero bits, so need to check how to round.
2492 "bits" is the number of dropped bits. */
2493 unsigned int bits;
2494 lostFraction fraction;
2495
2496 bits = valueBits - hexDigits * 4;
2497 fraction = lostFractionThroughTruncation (significand, partsCount, bits);
2498 roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
2499 }
2500 outputDigits = hexDigits;
2501 }
2502
2503 /* Write the digits consecutively, and start writing in the location
2504 of the hexadecimal point. We move the most significant digit
2505 left and add the hexadecimal point later. */
2506 p = ++dst;
2507
2508 count = (valueBits + integerPartWidth - 1) / integerPartWidth;
2509
2510 while (outputDigits && count) {
2511 integerPart part;
2512
2513 /* Put the most significant integerPartWidth bits in "part". */
2514 if (--count == partsCount)
2515 part = 0; /* An imaginary higher zero part. */
2516 else
2517 part = significand[count] << shift;
2518
2519 if (count && shift)
2520 part |= significand[count - 1] >> (integerPartWidth - shift);
2521
2522 /* Convert as much of "part" to hexdigits as we can. */
2523 unsigned int curDigits = integerPartWidth / 4;
2524
2525 if (curDigits > outputDigits)
2526 curDigits = outputDigits;
2527 dst += partAsHex (dst, part, curDigits, hexDigitChars);
2528 outputDigits -= curDigits;
2529 }
2530
2531 if (roundUp) {
2532 char *q = dst;
2533
2534 /* Note that hexDigitChars has a trailing '0'. */
2535 do {
2536 q--;
2537 *q = hexDigitChars[hexDigitValue (*q) + 1];
Neil Booth978661d2007-10-06 00:24:48 +00002538 } while (*q == '0');
2539 assert (q >= p);
Neil Bootha30b0ee2007-10-03 22:26:02 +00002540 } else {
2541 /* Add trailing zeroes. */
2542 memset (dst, '0', outputDigits);
2543 dst += outputDigits;
2544 }
2545
2546 /* Move the most significant digit to before the point, and if there
2547 is something after the decimal point add it. This must come
2548 after rounding above. */
2549 p[-1] = p[0];
2550 if (dst -1 == p)
2551 dst--;
2552 else
2553 p[0] = '.';
2554
2555 /* Finally output the exponent. */
2556 *dst++ = upperCase ? 'P': 'p';
2557
Neil Booth92f7e8d2007-10-06 07:29:25 +00002558 return writeSignedDecimal (dst, exponent);
Neil Bootha30b0ee2007-10-03 22:26:02 +00002559}
2560
Dale Johannesen343e7702007-08-24 00:56:33 +00002561// For good performance it is desirable for different APFloats
2562// to produce different integers.
2563uint32_t
Neil Booth4f881702007-09-26 21:33:42 +00002564APFloat::getHashValue() const
2565{
Dale Johannesen343e7702007-08-24 00:56:33 +00002566 if (category==fcZero) return sign<<8 | semantics->precision ;
2567 else if (category==fcInfinity) return sign<<9 | semantics->precision;
Dale Johanneseneaf08942007-08-31 04:03:46 +00002568 else if (category==fcNaN) return 1<<10 | semantics->precision;
Dale Johannesen343e7702007-08-24 00:56:33 +00002569 else {
2570 uint32_t hash = sign<<11 | semantics->precision | exponent<<12;
2571 const integerPart* p = significandParts();
2572 for (int i=partCount(); i>0; i--, p++)
Evan Cheng48e8c802008-05-02 21:15:08 +00002573 hash ^= ((uint32_t)*p) ^ (uint32_t)((*p)>>32);
Dale Johannesen343e7702007-08-24 00:56:33 +00002574 return hash;
2575 }
2576}
2577
2578// Conversion from APFloat to/from host float/double. It may eventually be
2579// possible to eliminate these and have everybody deal with APFloats, but that
2580// will take a while. This approach will not easily extend to long double.
Dale Johannesena72a5a02007-09-20 23:47:58 +00002581// Current implementation requires integerPartWidth==64, which is correct at
2582// the moment but could be made more general.
Dale Johannesen343e7702007-08-24 00:56:33 +00002583
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002584// Denormals have exponent minExponent in APFloat, but minExponent-1 in
Dale Johannesena72a5a02007-09-20 23:47:58 +00002585// the actual IEEE respresentations. We compensate for that here.
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002586
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002587APInt
Neil Booth4f881702007-09-26 21:33:42 +00002588APFloat::convertF80LongDoubleAPFloatToAPInt() const
2589{
Dan Gohmanb10abe12008-01-29 12:08:20 +00002590 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended);
Dale Johannesena72a5a02007-09-20 23:47:58 +00002591 assert (partCount()==2);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002592
2593 uint64_t myexponent, mysignificand;
2594
2595 if (category==fcNormal) {
2596 myexponent = exponent+16383; //bias
Dale Johannesena72a5a02007-09-20 23:47:58 +00002597 mysignificand = significandParts()[0];
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002598 if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
2599 myexponent = 0; // denormal
2600 } else if (category==fcZero) {
2601 myexponent = 0;
2602 mysignificand = 0;
2603 } else if (category==fcInfinity) {
2604 myexponent = 0x7fff;
2605 mysignificand = 0x8000000000000000ULL;
Chris Lattnera11ef822007-10-06 06:13:42 +00002606 } else {
2607 assert(category == fcNaN && "Unknown category");
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002608 myexponent = 0x7fff;
Dale Johannesena72a5a02007-09-20 23:47:58 +00002609 mysignificand = significandParts()[0];
Chris Lattnera11ef822007-10-06 06:13:42 +00002610 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002611
2612 uint64_t words[2];
Dale Johannesen1b25cb22009-03-23 21:16:53 +00002613 words[0] = mysignificand;
2614 words[1] = ((uint64_t)(sign & 1) << 15) |
2615 (myexponent & 0x7fffLL);
Chris Lattnera11ef822007-10-06 06:13:42 +00002616 return APInt(80, 2, words);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002617}
2618
2619APInt
Dale Johannesena471c2e2007-10-11 18:07:22 +00002620APFloat::convertPPCDoubleDoubleAPFloatToAPInt() const
2621{
Dan Gohmanb10abe12008-01-29 12:08:20 +00002622 assert(semantics == (const llvm::fltSemantics*)&PPCDoubleDouble);
Dale Johannesena471c2e2007-10-11 18:07:22 +00002623 assert (partCount()==2);
2624
2625 uint64_t myexponent, mysignificand, myexponent2, mysignificand2;
2626
2627 if (category==fcNormal) {
2628 myexponent = exponent + 1023; //bias
2629 myexponent2 = exponent2 + 1023;
2630 mysignificand = significandParts()[0];
2631 mysignificand2 = significandParts()[1];
2632 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2633 myexponent = 0; // denormal
2634 if (myexponent2==1 && !(mysignificand2 & 0x10000000000000LL))
2635 myexponent2 = 0; // denormal
2636 } else if (category==fcZero) {
2637 myexponent = 0;
2638 mysignificand = 0;
2639 myexponent2 = 0;
2640 mysignificand2 = 0;
2641 } else if (category==fcInfinity) {
2642 myexponent = 0x7ff;
2643 myexponent2 = 0;
2644 mysignificand = 0;
2645 mysignificand2 = 0;
2646 } else {
2647 assert(category == fcNaN && "Unknown category");
2648 myexponent = 0x7ff;
2649 mysignificand = significandParts()[0];
2650 myexponent2 = exponent2;
2651 mysignificand2 = significandParts()[1];
2652 }
2653
2654 uint64_t words[2];
Evan Cheng48e8c802008-05-02 21:15:08 +00002655 words[0] = ((uint64_t)(sign & 1) << 63) |
Dale Johannesena471c2e2007-10-11 18:07:22 +00002656 ((myexponent & 0x7ff) << 52) |
2657 (mysignificand & 0xfffffffffffffLL);
Evan Cheng48e8c802008-05-02 21:15:08 +00002658 words[1] = ((uint64_t)(sign2 & 1) << 63) |
Dale Johannesena471c2e2007-10-11 18:07:22 +00002659 ((myexponent2 & 0x7ff) << 52) |
2660 (mysignificand2 & 0xfffffffffffffLL);
2661 return APInt(128, 2, words);
2662}
2663
2664APInt
Neil Booth4f881702007-09-26 21:33:42 +00002665APFloat::convertDoubleAPFloatToAPInt() const
2666{
Dan Gohmancb648f92007-09-14 20:08:19 +00002667 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble);
Dale Johannesen343e7702007-08-24 00:56:33 +00002668 assert (partCount()==1);
2669
Dale Johanneseneaf08942007-08-31 04:03:46 +00002670 uint64_t myexponent, mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00002671
2672 if (category==fcNormal) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002673 myexponent = exponent+1023; //bias
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002674 mysignificand = *significandParts();
2675 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2676 myexponent = 0; // denormal
Dale Johannesen343e7702007-08-24 00:56:33 +00002677 } else if (category==fcZero) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002678 myexponent = 0;
2679 mysignificand = 0;
2680 } else if (category==fcInfinity) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002681 myexponent = 0x7ff;
2682 mysignificand = 0;
Chris Lattnera11ef822007-10-06 06:13:42 +00002683 } else {
2684 assert(category == fcNaN && "Unknown category!");
Dale Johannesen343e7702007-08-24 00:56:33 +00002685 myexponent = 0x7ff;
Dale Johanneseneaf08942007-08-31 04:03:46 +00002686 mysignificand = *significandParts();
Chris Lattnera11ef822007-10-06 06:13:42 +00002687 }
Dale Johannesen343e7702007-08-24 00:56:33 +00002688
Evan Cheng48e8c802008-05-02 21:15:08 +00002689 return APInt(64, ((((uint64_t)(sign & 1) << 63) |
Chris Lattnera11ef822007-10-06 06:13:42 +00002690 ((myexponent & 0x7ff) << 52) |
2691 (mysignificand & 0xfffffffffffffLL))));
Dale Johannesen343e7702007-08-24 00:56:33 +00002692}
2693
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002694APInt
Neil Booth4f881702007-09-26 21:33:42 +00002695APFloat::convertFloatAPFloatToAPInt() const
2696{
Dan Gohmancb648f92007-09-14 20:08:19 +00002697 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle);
Dale Johannesen343e7702007-08-24 00:56:33 +00002698 assert (partCount()==1);
Neil Booth4f881702007-09-26 21:33:42 +00002699
Dale Johanneseneaf08942007-08-31 04:03:46 +00002700 uint32_t myexponent, mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00002701
2702 if (category==fcNormal) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002703 myexponent = exponent+127; //bias
Evan Cheng48e8c802008-05-02 21:15:08 +00002704 mysignificand = (uint32_t)*significandParts();
Dale Johannesend0763b92007-11-17 01:02:27 +00002705 if (myexponent == 1 && !(mysignificand & 0x800000))
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002706 myexponent = 0; // denormal
Dale Johannesen343e7702007-08-24 00:56:33 +00002707 } else if (category==fcZero) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002708 myexponent = 0;
2709 mysignificand = 0;
2710 } else if (category==fcInfinity) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002711 myexponent = 0xff;
2712 mysignificand = 0;
Chris Lattnera11ef822007-10-06 06:13:42 +00002713 } else {
2714 assert(category == fcNaN && "Unknown category!");
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002715 myexponent = 0xff;
Evan Cheng48e8c802008-05-02 21:15:08 +00002716 mysignificand = (uint32_t)*significandParts();
Chris Lattnera11ef822007-10-06 06:13:42 +00002717 }
Dale Johannesen343e7702007-08-24 00:56:33 +00002718
Chris Lattnera11ef822007-10-06 06:13:42 +00002719 return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) |
2720 (mysignificand & 0x7fffff)));
Dale Johannesen343e7702007-08-24 00:56:33 +00002721}
2722
Dale Johannesena471c2e2007-10-11 18:07:22 +00002723// This function creates an APInt that is just a bit map of the floating
2724// point constant as it would appear in memory. It is not a conversion,
2725// and treating the result as a normal integer is unlikely to be useful.
2726
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002727APInt
Dale Johannesen7111b022008-10-09 18:53:47 +00002728APFloat::bitcastToAPInt() const
Neil Booth4f881702007-09-26 21:33:42 +00002729{
Dan Gohmanb10abe12008-01-29 12:08:20 +00002730 if (semantics == (const llvm::fltSemantics*)&IEEEsingle)
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002731 return convertFloatAPFloatToAPInt();
Chris Lattnera11ef822007-10-06 06:13:42 +00002732
Dan Gohmanb10abe12008-01-29 12:08:20 +00002733 if (semantics == (const llvm::fltSemantics*)&IEEEdouble)
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002734 return convertDoubleAPFloatToAPInt();
Neil Booth4f881702007-09-26 21:33:42 +00002735
Dan Gohmanb10abe12008-01-29 12:08:20 +00002736 if (semantics == (const llvm::fltSemantics*)&PPCDoubleDouble)
Dale Johannesena471c2e2007-10-11 18:07:22 +00002737 return convertPPCDoubleDoubleAPFloatToAPInt();
2738
Dan Gohmanb10abe12008-01-29 12:08:20 +00002739 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended &&
Chris Lattnera11ef822007-10-06 06:13:42 +00002740 "unknown format!");
2741 return convertF80LongDoubleAPFloatToAPInt();
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002742}
2743
Neil Booth4f881702007-09-26 21:33:42 +00002744float
2745APFloat::convertToFloat() const
2746{
Dan Gohmanb10abe12008-01-29 12:08:20 +00002747 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle);
Dale Johannesen7111b022008-10-09 18:53:47 +00002748 APInt api = bitcastToAPInt();
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002749 return api.bitsToFloat();
2750}
2751
Neil Booth4f881702007-09-26 21:33:42 +00002752double
2753APFloat::convertToDouble() const
2754{
Dan Gohmanb10abe12008-01-29 12:08:20 +00002755 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble);
Dale Johannesen7111b022008-10-09 18:53:47 +00002756 APInt api = bitcastToAPInt();
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002757 return api.bitsToDouble();
2758}
2759
Dale Johannesend3d8ce32008-10-06 18:22:29 +00002760/// Integer bit is explicit in this format. Intel hardware (387 and later)
2761/// does not support these bit patterns:
2762/// exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity")
2763/// exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN")
2764/// exponent = 0, integer bit 1 ("pseudodenormal")
2765/// exponent!=0 nor all 1's, integer bit 0 ("unnormal")
2766/// At the moment, the first two are treated as NaNs, the second two as Normal.
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002767void
Neil Booth4f881702007-09-26 21:33:42 +00002768APFloat::initFromF80LongDoubleAPInt(const APInt &api)
2769{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002770 assert(api.getBitWidth()==80);
2771 uint64_t i1 = api.getRawData()[0];
2772 uint64_t i2 = api.getRawData()[1];
Dale Johannesen1b25cb22009-03-23 21:16:53 +00002773 uint64_t myexponent = (i2 & 0x7fff);
2774 uint64_t mysignificand = i1;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002775
2776 initialize(&APFloat::x87DoubleExtended);
Dale Johannesena72a5a02007-09-20 23:47:58 +00002777 assert(partCount()==2);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002778
Dale Johannesen1b25cb22009-03-23 21:16:53 +00002779 sign = static_cast<unsigned int>(i2>>15);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002780 if (myexponent==0 && mysignificand==0) {
2781 // exponent, significand meaningless
2782 category = fcZero;
2783 } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
2784 // exponent, significand meaningless
2785 category = fcInfinity;
2786 } else if (myexponent==0x7fff && mysignificand!=0x8000000000000000ULL) {
2787 // exponent meaningless
2788 category = fcNaN;
Dale Johannesena72a5a02007-09-20 23:47:58 +00002789 significandParts()[0] = mysignificand;
2790 significandParts()[1] = 0;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002791 } else {
2792 category = fcNormal;
2793 exponent = myexponent - 16383;
Dale Johannesena72a5a02007-09-20 23:47:58 +00002794 significandParts()[0] = mysignificand;
2795 significandParts()[1] = 0;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002796 if (myexponent==0) // denormal
2797 exponent = -16382;
Neil Booth4f881702007-09-26 21:33:42 +00002798 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002799}
2800
2801void
Dale Johannesena471c2e2007-10-11 18:07:22 +00002802APFloat::initFromPPCDoubleDoubleAPInt(const APInt &api)
2803{
2804 assert(api.getBitWidth()==128);
2805 uint64_t i1 = api.getRawData()[0];
2806 uint64_t i2 = api.getRawData()[1];
2807 uint64_t myexponent = (i1 >> 52) & 0x7ff;
2808 uint64_t mysignificand = i1 & 0xfffffffffffffLL;
2809 uint64_t myexponent2 = (i2 >> 52) & 0x7ff;
2810 uint64_t mysignificand2 = i2 & 0xfffffffffffffLL;
2811
2812 initialize(&APFloat::PPCDoubleDouble);
2813 assert(partCount()==2);
2814
Evan Cheng48e8c802008-05-02 21:15:08 +00002815 sign = static_cast<unsigned int>(i1>>63);
2816 sign2 = static_cast<unsigned int>(i2>>63);
Dale Johannesena471c2e2007-10-11 18:07:22 +00002817 if (myexponent==0 && mysignificand==0) {
2818 // exponent, significand meaningless
2819 // exponent2 and significand2 are required to be 0; we don't check
2820 category = fcZero;
2821 } else if (myexponent==0x7ff && mysignificand==0) {
2822 // exponent, significand meaningless
2823 // exponent2 and significand2 are required to be 0; we don't check
2824 category = fcInfinity;
2825 } else if (myexponent==0x7ff && mysignificand!=0) {
2826 // exponent meaningless. So is the whole second word, but keep it
2827 // for determinism.
2828 category = fcNaN;
2829 exponent2 = myexponent2;
2830 significandParts()[0] = mysignificand;
2831 significandParts()[1] = mysignificand2;
2832 } else {
2833 category = fcNormal;
2834 // Note there is no category2; the second word is treated as if it is
2835 // fcNormal, although it might be something else considered by itself.
2836 exponent = myexponent - 1023;
2837 exponent2 = myexponent2 - 1023;
2838 significandParts()[0] = mysignificand;
2839 significandParts()[1] = mysignificand2;
2840 if (myexponent==0) // denormal
2841 exponent = -1022;
2842 else
2843 significandParts()[0] |= 0x10000000000000LL; // integer bit
2844 if (myexponent2==0)
2845 exponent2 = -1022;
2846 else
2847 significandParts()[1] |= 0x10000000000000LL; // integer bit
2848 }
2849}
2850
2851void
Neil Booth4f881702007-09-26 21:33:42 +00002852APFloat::initFromDoubleAPInt(const APInt &api)
2853{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002854 assert(api.getBitWidth()==64);
2855 uint64_t i = *api.getRawData();
Dale Johannesend3b51fd2007-08-24 05:08:11 +00002856 uint64_t myexponent = (i >> 52) & 0x7ff;
2857 uint64_t mysignificand = i & 0xfffffffffffffLL;
2858
Dale Johannesen343e7702007-08-24 00:56:33 +00002859 initialize(&APFloat::IEEEdouble);
Dale Johannesen343e7702007-08-24 00:56:33 +00002860 assert(partCount()==1);
2861
Evan Cheng48e8c802008-05-02 21:15:08 +00002862 sign = static_cast<unsigned int>(i>>63);
Dale Johannesen343e7702007-08-24 00:56:33 +00002863 if (myexponent==0 && mysignificand==0) {
2864 // exponent, significand meaningless
2865 category = fcZero;
Dale Johannesen343e7702007-08-24 00:56:33 +00002866 } else if (myexponent==0x7ff && mysignificand==0) {
2867 // exponent, significand meaningless
2868 category = fcInfinity;
Dale Johanneseneaf08942007-08-31 04:03:46 +00002869 } else if (myexponent==0x7ff && mysignificand!=0) {
2870 // exponent meaningless
2871 category = fcNaN;
2872 *significandParts() = mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00002873 } else {
Dale Johannesen343e7702007-08-24 00:56:33 +00002874 category = fcNormal;
2875 exponent = myexponent - 1023;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002876 *significandParts() = mysignificand;
2877 if (myexponent==0) // denormal
2878 exponent = -1022;
2879 else
2880 *significandParts() |= 0x10000000000000LL; // integer bit
Neil Booth4f881702007-09-26 21:33:42 +00002881 }
Dale Johannesen343e7702007-08-24 00:56:33 +00002882}
2883
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002884void
Neil Booth4f881702007-09-26 21:33:42 +00002885APFloat::initFromFloatAPInt(const APInt & api)
2886{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002887 assert(api.getBitWidth()==32);
2888 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesend3b51fd2007-08-24 05:08:11 +00002889 uint32_t myexponent = (i >> 23) & 0xff;
2890 uint32_t mysignificand = i & 0x7fffff;
2891
Dale Johannesen343e7702007-08-24 00:56:33 +00002892 initialize(&APFloat::IEEEsingle);
Dale Johannesen343e7702007-08-24 00:56:33 +00002893 assert(partCount()==1);
2894
Dale Johanneseneaf08942007-08-31 04:03:46 +00002895 sign = i >> 31;
Dale Johannesen343e7702007-08-24 00:56:33 +00002896 if (myexponent==0 && mysignificand==0) {
2897 // exponent, significand meaningless
2898 category = fcZero;
Dale Johannesen343e7702007-08-24 00:56:33 +00002899 } else if (myexponent==0xff && mysignificand==0) {
2900 // exponent, significand meaningless
2901 category = fcInfinity;
Dale Johannesen902ff942007-09-25 17:25:00 +00002902 } else if (myexponent==0xff && mysignificand!=0) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002903 // sign, exponent, significand meaningless
Dale Johanneseneaf08942007-08-31 04:03:46 +00002904 category = fcNaN;
2905 *significandParts() = mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00002906 } else {
2907 category = fcNormal;
Dale Johannesen343e7702007-08-24 00:56:33 +00002908 exponent = myexponent - 127; //bias
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002909 *significandParts() = mysignificand;
2910 if (myexponent==0) // denormal
2911 exponent = -126;
2912 else
2913 *significandParts() |= 0x800000; // integer bit
Dale Johannesen343e7702007-08-24 00:56:33 +00002914 }
2915}
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002916
2917/// Treat api as containing the bits of a floating point number. Currently
Dale Johannesena471c2e2007-10-11 18:07:22 +00002918/// we infer the floating point type from the size of the APInt. The
2919/// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful
2920/// when the size is anything else).
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002921void
Dale Johannesena471c2e2007-10-11 18:07:22 +00002922APFloat::initFromAPInt(const APInt& api, bool isIEEE)
Neil Booth4f881702007-09-26 21:33:42 +00002923{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002924 if (api.getBitWidth() == 32)
2925 return initFromFloatAPInt(api);
2926 else if (api.getBitWidth()==64)
2927 return initFromDoubleAPInt(api);
2928 else if (api.getBitWidth()==80)
2929 return initFromF80LongDoubleAPInt(api);
Dale Johannesena471c2e2007-10-11 18:07:22 +00002930 else if (api.getBitWidth()==128 && !isIEEE)
2931 return initFromPPCDoubleDoubleAPInt(api);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002932 else
Torok Edwinc23197a2009-07-14 16:55:14 +00002933 llvm_unreachable(0);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002934}
2935
Dale Johannesena471c2e2007-10-11 18:07:22 +00002936APFloat::APFloat(const APInt& api, bool isIEEE)
Neil Booth4f881702007-09-26 21:33:42 +00002937{
Dale Johannesena471c2e2007-10-11 18:07:22 +00002938 initFromAPInt(api, isIEEE);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002939}
2940
Neil Booth4f881702007-09-26 21:33:42 +00002941APFloat::APFloat(float f)
2942{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002943 APInt api = APInt(32, 0);
2944 initFromAPInt(api.floatToBits(f));
2945}
2946
Neil Booth4f881702007-09-26 21:33:42 +00002947APFloat::APFloat(double d)
2948{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002949 APInt api = APInt(64, 0);
2950 initFromAPInt(api.doubleToBits(d));
2951}