blob: 35de71497a9c283a1df5dd8e68c158d132506c66 [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"
Chris Lattnerb39cdde2007-08-20 22:49:32 +000017#include <cassert>
Neil Bootha30b0ee2007-10-03 22:26:02 +000018#include <cstring>
Dale Johannesend3b51fd2007-08-24 05:08:11 +000019#include "llvm/Support/MathExtras.h"
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 Lattnerb39cdde2007-08-20 22:49:32 +000027COMPILE_TIME_ASSERT(integerPartWidth % 4 == 0);
28
29namespace llvm {
30
31 /* Represents floating point arithmetic semantics. */
32 struct fltSemantics {
33 /* The largest E such that 2^E is representable; this matches the
34 definition of IEEE 754. */
35 exponent_t maxExponent;
36
37 /* The smallest E such that 2^E is a normalized number; this
38 matches the definition of IEEE 754. */
39 exponent_t minExponent;
40
41 /* Number of bits in the significand. This includes the integer
42 bit. */
Neil Booth7a951ca2007-10-12 15:33:27 +000043 unsigned int precision;
Neil Boothcaf19d72007-10-14 10:29:28 +000044
45 /* True if arithmetic is supported. */
46 unsigned int arithmeticOK;
Chris Lattnerb39cdde2007-08-20 22:49:32 +000047 };
48
Neil Boothcaf19d72007-10-14 10:29:28 +000049 const fltSemantics APFloat::IEEEsingle = { 127, -126, 24, true };
50 const fltSemantics APFloat::IEEEdouble = { 1023, -1022, 53, true };
51 const fltSemantics APFloat::IEEEquad = { 16383, -16382, 113, true };
52 const fltSemantics APFloat::x87DoubleExtended = { 16383, -16382, 64, true };
53 const fltSemantics APFloat::Bogus = { 0, 0, 0, true };
Dale Johannesena471c2e2007-10-11 18:07:22 +000054
55 // The PowerPC format consists of two doubles. It does not map cleanly
56 // onto the usual format above. For now only storage of constants of
57 // this type is supported, no arithmetic.
Neil Boothcaf19d72007-10-14 10:29:28 +000058 const fltSemantics APFloat::PPCDoubleDouble = { 1023, -1022, 106, false };
Neil Booth96c74712007-10-12 16:02:31 +000059
60 /* A tight upper bound on number of parts required to hold the value
61 pow(5, power) is
62
Neil Booth686700e2007-10-15 15:00:55 +000063 power * 815 / (351 * integerPartWidth) + 1
Neil Booth96c74712007-10-12 16:02:31 +000064
65 However, whilst the result may require only this many parts,
66 because we are multiplying two values to get it, the
67 multiplication may require an extra part with the excess part
68 being zero (consider the trivial case of 1 * 1, tcFullMultiply
69 requires two parts to hold the single-part result). So we add an
70 extra one to guarantee enough space whilst multiplying. */
71 const unsigned int maxExponent = 16383;
72 const unsigned int maxPrecision = 113;
73 const unsigned int maxPowerOfFiveExponent = maxExponent + maxPrecision - 1;
Neil Booth686700e2007-10-15 15:00:55 +000074 const unsigned int maxPowerOfFiveParts = 2 + ((maxPowerOfFiveExponent * 815)
75 / (351 * integerPartWidth));
Chris Lattnerb39cdde2007-08-20 22:49:32 +000076}
77
78/* Put a bunch of private, handy routines in an anonymous namespace. */
79namespace {
80
Dan Gohman3bd659b2008-04-10 21:11:47 +000081 static inline unsigned int
Chris Lattnerb39cdde2007-08-20 22:49:32 +000082 partCountForBits(unsigned int bits)
83 {
84 return ((bits) + integerPartWidth - 1) / integerPartWidth;
85 }
86
Neil Booth1870f292007-10-14 10:16:12 +000087 /* Returns 0U-9U. Return values >= 10U are not digits. */
Dan Gohman3bd659b2008-04-10 21:11:47 +000088 static inline unsigned int
Neil Booth1870f292007-10-14 10:16:12 +000089 decDigitValue(unsigned int c)
Chris Lattnerb39cdde2007-08-20 22:49:32 +000090 {
Neil Booth1870f292007-10-14 10:16:12 +000091 return c - '0';
Chris Lattnerb39cdde2007-08-20 22:49:32 +000092 }
93
Dan Gohman3bd659b2008-04-10 21:11:47 +000094 static unsigned int
Neil Booth96c74712007-10-12 16:02:31 +000095 hexDigitValue(unsigned int c)
Chris Lattnerb39cdde2007-08-20 22:49:32 +000096 {
97 unsigned int r;
98
99 r = c - '0';
100 if(r <= 9)
101 return r;
102
103 r = c - 'A';
104 if(r <= 5)
105 return r + 10;
106
107 r = c - 'a';
108 if(r <= 5)
109 return r + 10;
110
111 return -1U;
112 }
113
Dan Gohman3bd659b2008-04-10 21:11:47 +0000114 static inline void
Neil Boothcaf19d72007-10-14 10:29:28 +0000115 assertArithmeticOK(const llvm::fltSemantics &semantics) {
116 assert(semantics.arithmeticOK
117 && "Compile-time arithmetic does not support these semantics");
118 }
119
Neil Booth1870f292007-10-14 10:16:12 +0000120 /* Return the value of a decimal exponent of the form
121 [+-]ddddddd.
122
123 If the exponent overflows, returns a large exponent with the
124 appropriate sign. */
Dan Gohman3bd659b2008-04-10 21:11:47 +0000125 static int
Neil Booth1870f292007-10-14 10:16:12 +0000126 readExponent(const char *p)
127 {
128 bool isNegative;
129 unsigned int absExponent;
130 const unsigned int overlargeExponent = 24000; /* FIXME. */
131
132 isNegative = (*p == '-');
133 if (*p == '-' || *p == '+')
134 p++;
135
136 absExponent = decDigitValue(*p++);
137 assert (absExponent < 10U);
138
139 for (;;) {
140 unsigned int value;
141
142 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;
151 }
152 absExponent = value;
153 }
154
155 if (isNegative)
156 return -(int) absExponent;
157 else
158 return (int) absExponent;
159 }
160
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000161 /* This is ugly and needs cleaning up, but I don't immediately see
162 how whilst remaining safe. */
Dan Gohman3bd659b2008-04-10 21:11:47 +0000163 static int
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000164 totalExponent(const char *p, int exponentAdjustment)
165 {
166 integerPart unsignedExponent;
167 bool negative, overflow;
168 long 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
Neil Booth1870f292007-10-14 10:16:12 +0000181 value = decDigitValue(*p);
182 if(value >= 10U)
Neil Booth4f881702007-09-26 21:33:42 +0000183 break;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000184
185 p++;
186 unsignedExponent = unsignedExponent * 10 + value;
187 if(unsignedExponent > 65535)
Neil Booth4f881702007-09-26 21:33:42 +0000188 overflow = true;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000189 }
190
191 if(exponentAdjustment > 65535 || exponentAdjustment < -65536)
192 overflow = true;
193
194 if(!overflow) {
195 exponent = unsignedExponent;
196 if(negative)
Neil Booth4f881702007-09-26 21:33:42 +0000197 exponent = -exponent;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000198 exponent += exponentAdjustment;
199 if(exponent > 65535 || exponent < -65536)
Neil Booth4f881702007-09-26 21:33:42 +0000200 overflow = true;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000201 }
202
203 if(overflow)
204 exponent = negative ? -65536: 65535;
205
206 return exponent;
207 }
208
Dan Gohman3bd659b2008-04-10 21:11:47 +0000209 static const char *
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000210 skipLeadingZeroesAndAnyDot(const char *p, const char **dot)
211 {
212 *dot = 0;
213 while(*p == '0')
214 p++;
215
216 if(*p == '.') {
217 *dot = p++;
218 while(*p == '0')
Neil Booth4f881702007-09-26 21:33:42 +0000219 p++;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000220 }
221
222 return p;
223 }
224
Neil Booth1870f292007-10-14 10:16:12 +0000225 /* Given a normal decimal floating point number of the form
226
227 dddd.dddd[eE][+-]ddd
228
229 where the decimal point and exponent are optional, fill out the
Neil Booth686700e2007-10-15 15:00:55 +0000230 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.
234
Neil Bootha89e45f2007-12-05 13:01:24 +0000235 If the value is zero, V->firstSigDigit points to a non-digit, and
236 the return exponent is zero.
Neil Booth686700e2007-10-15 15:00:55 +0000237 */
Neil Booth1870f292007-10-14 10:16:12 +0000238 struct decimalInfo {
239 const char *firstSigDigit;
240 const char *lastSigDigit;
241 int exponent;
Neil Booth686700e2007-10-15 15:00:55 +0000242 int normalizedExponent;
Neil Booth1870f292007-10-14 10:16:12 +0000243 };
244
Dan Gohman3bd659b2008-04-10 21:11:47 +0000245 static void
Neil Booth1870f292007-10-14 10:16:12 +0000246 interpretDecimal(const char *p, decimalInfo *D)
247 {
248 const char *dot;
249
250 p = skipLeadingZeroesAndAnyDot (p, &dot);
251
252 D->firstSigDigit = p;
253 D->exponent = 0;
Neil Booth686700e2007-10-15 15:00:55 +0000254 D->normalizedExponent = 0;
Neil Booth1870f292007-10-14 10:16:12 +0000255
256 for (;;) {
257 if (*p == '.') {
258 assert(dot == 0);
259 dot = p++;
260 }
261 if (decDigitValue(*p) >= 10U)
262 break;
263 p++;
264 }
265
266 /* If number is all zerooes accept any exponent. */
Neil Boothcc233592007-12-05 13:06:04 +0000267 if (p != D->firstSigDigit) {
Neil Booth1870f292007-10-14 10:16:12 +0000268 if (*p == 'e' || *p == 'E')
269 D->exponent = readExponent(p + 1);
270
271 /* Implied decimal point? */
272 if (!dot)
273 dot = p;
274
275 /* Drop insignificant trailing zeroes. */
276 do
277 do
278 p--;
279 while (*p == '0');
280 while (*p == '.');
281
Neil Booth686700e2007-10-15 15:00:55 +0000282 /* Adjust the exponents for any decimal point. */
Neil Booth1870f292007-10-14 10:16:12 +0000283 D->exponent += (dot - p) - (dot > p);
Neil Booth686700e2007-10-15 15:00:55 +0000284 D->normalizedExponent = (D->exponent + (p - D->firstSigDigit)
285 - (dot > D->firstSigDigit && dot < p));
Neil Booth1870f292007-10-14 10:16:12 +0000286 }
287
288 D->lastSigDigit = p;
289 }
290
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000291 /* Return the trailing fraction of a hexadecimal number.
292 DIGITVALUE is the first hex digit of the fraction, P points to
293 the next digit. */
Dan Gohman3bd659b2008-04-10 21:11:47 +0000294 static lostFraction
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000295 trailingHexadecimalFraction(const char *p, unsigned int digitValue)
296 {
297 unsigned int hexDigit;
298
299 /* If the first trailing digit isn't 0 or 8 we can work out the
300 fraction immediately. */
301 if(digitValue > 8)
302 return lfMoreThanHalf;
303 else if(digitValue < 8 && digitValue > 0)
304 return lfLessThanHalf;
305
306 /* Otherwise we need to find the first non-zero digit. */
307 while(*p == '0')
308 p++;
309
310 hexDigit = hexDigitValue(*p);
311
312 /* If we ran off the end it is exactly zero or one-half, otherwise
313 a little more. */
314 if(hexDigit == -1U)
315 return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
316 else
317 return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf;
318 }
319
Neil Boothb7dea4c2007-10-03 15:16:41 +0000320 /* Return the fraction lost were a bignum truncated losing the least
321 significant BITS bits. */
Dan Gohman3bd659b2008-04-10 21:11:47 +0000322 static lostFraction
Neil Bootha30b0ee2007-10-03 22:26:02 +0000323 lostFractionThroughTruncation(const integerPart *parts,
Neil Booth4f881702007-09-26 21:33:42 +0000324 unsigned int partCount,
325 unsigned int bits)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000326 {
327 unsigned int lsb;
328
329 lsb = APInt::tcLSB(parts, partCount);
330
331 /* Note this is guaranteed true if bits == 0, or LSB == -1U. */
332 if(bits <= lsb)
333 return lfExactlyZero;
334 if(bits == lsb + 1)
335 return lfExactlyHalf;
336 if(bits <= partCount * integerPartWidth
337 && APInt::tcExtractBit(parts, bits - 1))
338 return lfMoreThanHalf;
339
340 return lfLessThanHalf;
341 }
342
343 /* Shift DST right BITS bits noting lost fraction. */
Dan Gohman3bd659b2008-04-10 21:11:47 +0000344 static lostFraction
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000345 shiftRight(integerPart *dst, unsigned int parts, unsigned int bits)
346 {
347 lostFraction lost_fraction;
348
349 lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
350
351 APInt::tcShiftRight(dst, parts, bits);
352
353 return lost_fraction;
354 }
Neil Bootha30b0ee2007-10-03 22:26:02 +0000355
Neil Booth33d4c922007-10-07 08:51:21 +0000356 /* Combine the effect of two lost fractions. */
Dan Gohman3bd659b2008-04-10 21:11:47 +0000357 static lostFraction
Neil Booth33d4c922007-10-07 08:51:21 +0000358 combineLostFractions(lostFraction moreSignificant,
359 lostFraction lessSignificant)
360 {
361 if(lessSignificant != lfExactlyZero) {
362 if(moreSignificant == lfExactlyZero)
363 moreSignificant = lfLessThanHalf;
364 else if(moreSignificant == lfExactlyHalf)
365 moreSignificant = lfMoreThanHalf;
366 }
367
368 return moreSignificant;
369 }
Neil Bootha30b0ee2007-10-03 22:26:02 +0000370
Neil Booth96c74712007-10-12 16:02:31 +0000371 /* The error from the true value, in half-ulps, on multiplying two
372 floating point numbers, which differ from the value they
373 approximate by at most HUE1 and HUE2 half-ulps, is strictly less
374 than the returned value.
375
376 See "How to Read Floating Point Numbers Accurately" by William D
377 Clinger. */
Dan Gohman3bd659b2008-04-10 21:11:47 +0000378 static unsigned int
Neil Booth96c74712007-10-12 16:02:31 +0000379 HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
380 {
381 assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
382
383 if (HUerr1 + HUerr2 == 0)
384 return inexactMultiply * 2; /* <= inexactMultiply half-ulps. */
385 else
386 return inexactMultiply + 2 * (HUerr1 + HUerr2);
387 }
388
389 /* The number of ulps from the boundary (zero, or half if ISNEAREST)
390 when the least significant BITS are truncated. BITS cannot be
391 zero. */
Dan Gohman3bd659b2008-04-10 21:11:47 +0000392 static integerPart
Neil Booth96c74712007-10-12 16:02:31 +0000393 ulpsFromBoundary(const integerPart *parts, unsigned int bits, bool isNearest)
394 {
395 unsigned int count, partBits;
396 integerPart part, boundary;
397
398 assert (bits != 0);
399
400 bits--;
401 count = bits / integerPartWidth;
402 partBits = bits % integerPartWidth + 1;
403
404 part = parts[count] & (~(integerPart) 0 >> (integerPartWidth - partBits));
405
406 if (isNearest)
407 boundary = (integerPart) 1 << (partBits - 1);
408 else
409 boundary = 0;
410
411 if (count == 0) {
412 if (part - boundary <= boundary - part)
413 return part - boundary;
414 else
415 return boundary - part;
416 }
417
418 if (part == boundary) {
419 while (--count)
420 if (parts[count])
421 return ~(integerPart) 0; /* A lot. */
422
423 return parts[0];
424 } else if (part == boundary - 1) {
425 while (--count)
426 if (~parts[count])
427 return ~(integerPart) 0; /* A lot. */
428
429 return -parts[0];
430 }
431
432 return ~(integerPart) 0; /* A lot. */
433 }
434
435 /* Place pow(5, power) in DST, and return the number of parts used.
436 DST must be at least one part larger than size of the answer. */
Dan Gohman3bd659b2008-04-10 21:11:47 +0000437 static unsigned int
Neil Booth96c74712007-10-12 16:02:31 +0000438 powerOf5(integerPart *dst, unsigned int power)
439 {
Neil Booth96c74712007-10-12 16:02:31 +0000440 static integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125,
441 15625, 78125 };
442 static integerPart pow5s[maxPowerOfFiveParts * 2 + 5] = { 78125 * 5 };
443 static unsigned int partsCount[16] = { 1 };
444
445 integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5;
446 unsigned int result;
447
448 assert(power <= maxExponent);
449
450 p1 = dst;
451 p2 = scratch;
452
453 *p1 = firstEightPowers[power & 7];
454 power >>= 3;
455
456 result = 1;
457 pow5 = pow5s;
458
459 for (unsigned int n = 0; power; power >>= 1, n++) {
460 unsigned int pc;
461
462 pc = partsCount[n];
463
464 /* Calculate pow(5,pow(2,n+3)) if we haven't yet. */
465 if (pc == 0) {
466 pc = partsCount[n - 1];
467 APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc);
468 pc *= 2;
469 if (pow5[pc - 1] == 0)
470 pc--;
471 partsCount[n] = pc;
472 }
473
474 if (power & 1) {
475 integerPart *tmp;
476
477 APInt::tcFullMultiply(p2, p1, pow5, result, pc);
478 result += pc;
479 if (p2[result - 1] == 0)
480 result--;
481
482 /* Now result is in p1 with partsCount parts and p2 is scratch
483 space. */
484 tmp = p1, p1 = p2, p2 = tmp;
485 }
486
487 pow5 += pc;
488 }
489
490 if (p1 != dst)
491 APInt::tcAssign(dst, p1, result);
492
493 return result;
494 }
495
Neil Bootha30b0ee2007-10-03 22:26:02 +0000496 /* Zero at the end to avoid modular arithmetic when adding one; used
497 when rounding up during hexadecimal output. */
498 static const char hexDigitsLower[] = "0123456789abcdef0";
499 static const char hexDigitsUpper[] = "0123456789ABCDEF0";
500 static const char infinityL[] = "infinity";
501 static const char infinityU[] = "INFINITY";
502 static const char NaNL[] = "nan";
503 static const char NaNU[] = "NAN";
504
505 /* Write out an integerPart in hexadecimal, starting with the most
506 significant nibble. Write out exactly COUNT hexdigits, return
507 COUNT. */
Dan Gohman3bd659b2008-04-10 21:11:47 +0000508 static unsigned int
Neil Bootha30b0ee2007-10-03 22:26:02 +0000509 partAsHex (char *dst, integerPart part, unsigned int count,
510 const char *hexDigitChars)
511 {
512 unsigned int result = count;
513
514 assert (count != 0 && count <= integerPartWidth / 4);
515
516 part >>= (integerPartWidth - 4 * count);
517 while (count--) {
518 dst[count] = hexDigitChars[part & 0xf];
519 part >>= 4;
520 }
521
522 return result;
523 }
524
Neil Booth92f7e8d2007-10-06 07:29:25 +0000525 /* Write out an unsigned decimal integer. */
Dan Gohman3bd659b2008-04-10 21:11:47 +0000526 static char *
Neil Booth92f7e8d2007-10-06 07:29:25 +0000527 writeUnsignedDecimal (char *dst, unsigned int n)
Neil Bootha30b0ee2007-10-03 22:26:02 +0000528 {
Neil Booth92f7e8d2007-10-06 07:29:25 +0000529 char buff[40], *p;
Neil Bootha30b0ee2007-10-03 22:26:02 +0000530
Neil Booth92f7e8d2007-10-06 07:29:25 +0000531 p = buff;
532 do
533 *p++ = '0' + n % 10;
534 while (n /= 10);
535
536 do
537 *dst++ = *--p;
538 while (p != buff);
539
540 return dst;
541 }
542
543 /* Write out a signed decimal integer. */
Dan Gohman3bd659b2008-04-10 21:11:47 +0000544 static char *
Neil Booth92f7e8d2007-10-06 07:29:25 +0000545 writeSignedDecimal (char *dst, int value)
546 {
547 if (value < 0) {
Neil Bootha30b0ee2007-10-03 22:26:02 +0000548 *dst++ = '-';
Neil Booth92f7e8d2007-10-06 07:29:25 +0000549 dst = writeUnsignedDecimal(dst, -(unsigned) value);
550 } else
551 dst = writeUnsignedDecimal(dst, value);
Neil Bootha30b0ee2007-10-03 22:26:02 +0000552
553 return dst;
554 }
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
601 for the significand. */
602void
603APFloat::makeNaN(void)
604{
605 category = fcNaN;
606 APInt::tcSet(significandParts(), ~0U, partCount());
607}
608
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000609APFloat &
610APFloat::operator=(const APFloat &rhs)
611{
612 if(this != &rhs) {
613 if(semantics != rhs.semantics) {
614 freeSignificand();
615 initialize(rhs.semantics);
616 }
617 assign(rhs);
618 }
619
620 return *this;
621}
622
Dale Johannesen343e7702007-08-24 00:56:33 +0000623bool
Dale Johannesen12595d72007-08-24 22:09:56 +0000624APFloat::bitwiseIsEqual(const APFloat &rhs) const {
Dale Johannesen343e7702007-08-24 00:56:33 +0000625 if (this == &rhs)
626 return true;
627 if (semantics != rhs.semantics ||
Dale Johanneseneaf08942007-08-31 04:03:46 +0000628 category != rhs.category ||
629 sign != rhs.sign)
Dale Johannesen343e7702007-08-24 00:56:33 +0000630 return false;
Dan Gohmanb10abe12008-01-29 12:08:20 +0000631 if (semantics==(const llvm::fltSemantics*)&PPCDoubleDouble &&
Dale Johannesena471c2e2007-10-11 18:07:22 +0000632 sign2 != rhs.sign2)
633 return false;
Dale Johanneseneaf08942007-08-31 04:03:46 +0000634 if (category==fcZero || category==fcInfinity)
Dale Johannesen343e7702007-08-24 00:56:33 +0000635 return true;
Dale Johanneseneaf08942007-08-31 04:03:46 +0000636 else if (category==fcNormal && exponent!=rhs.exponent)
637 return false;
Dan Gohmanb10abe12008-01-29 12:08:20 +0000638 else if (semantics==(const llvm::fltSemantics*)&PPCDoubleDouble &&
Dale Johannesena471c2e2007-10-11 18:07:22 +0000639 exponent2!=rhs.exponent2)
640 return false;
Dale Johannesen343e7702007-08-24 00:56:33 +0000641 else {
Dale Johannesen343e7702007-08-24 00:56:33 +0000642 int i= partCount();
643 const integerPart* p=significandParts();
644 const integerPart* q=rhs.significandParts();
645 for (; i>0; i--, p++, q++) {
646 if (*p != *q)
647 return false;
648 }
649 return true;
650 }
651}
652
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000653APFloat::APFloat(const fltSemantics &ourSemantics, integerPart value)
654{
Neil Boothcaf19d72007-10-14 10:29:28 +0000655 assertArithmeticOK(ourSemantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000656 initialize(&ourSemantics);
657 sign = 0;
658 zeroSignificand();
659 exponent = ourSemantics.precision - 1;
660 significandParts()[0] = value;
661 normalize(rmNearestTiesToEven, lfExactlyZero);
662}
663
664APFloat::APFloat(const fltSemantics &ourSemantics,
Neil Booth4f881702007-09-26 21:33:42 +0000665 fltCategory ourCategory, bool negative)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000666{
Neil Boothcaf19d72007-10-14 10:29:28 +0000667 assertArithmeticOK(ourSemantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000668 initialize(&ourSemantics);
669 category = ourCategory;
670 sign = negative;
671 if(category == fcNormal)
672 category = fcZero;
Neil Boothe5e01942007-10-14 10:39:51 +0000673 else if (ourCategory == fcNaN)
674 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000675}
676
677APFloat::APFloat(const fltSemantics &ourSemantics, const char *text)
678{
Neil Boothcaf19d72007-10-14 10:29:28 +0000679 assertArithmeticOK(ourSemantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000680 initialize(&ourSemantics);
681 convertFromString(text, rmNearestTiesToEven);
682}
683
684APFloat::APFloat(const APFloat &rhs)
685{
686 initialize(rhs.semantics);
687 assign(rhs);
688}
689
690APFloat::~APFloat()
691{
692 freeSignificand();
693}
694
Ted Kremenek1f801fa2008-02-11 17:24:50 +0000695// Profile - This method 'profiles' an APFloat for use with FoldingSet.
696void APFloat::Profile(FoldingSetNodeID& ID) const {
697 ID.Add(convertToAPInt());
698}
699
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000700unsigned int
701APFloat::partCount() const
702{
Dale Johannesena72a5a02007-09-20 23:47:58 +0000703 return partCountForBits(semantics->precision + 1);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000704}
705
706unsigned int
707APFloat::semanticsPrecision(const fltSemantics &semantics)
708{
709 return semantics.precision;
710}
711
712const integerPart *
713APFloat::significandParts() const
714{
715 return const_cast<APFloat *>(this)->significandParts();
716}
717
718integerPart *
719APFloat::significandParts()
720{
Dale Johanneseneaf08942007-08-31 04:03:46 +0000721 assert(category == fcNormal || category == fcNaN);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000722
723 if(partCount() > 1)
724 return significand.parts;
725 else
726 return &significand.part;
727}
728
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000729void
730APFloat::zeroSignificand()
731{
732 category = fcNormal;
733 APInt::tcSet(significandParts(), 0, partCount());
734}
735
736/* Increment an fcNormal floating point number's significand. */
737void
738APFloat::incrementSignificand()
739{
740 integerPart carry;
741
742 carry = APInt::tcIncrement(significandParts(), partCount());
743
744 /* Our callers should never cause us to overflow. */
745 assert(carry == 0);
746}
747
748/* Add the significand of the RHS. Returns the carry flag. */
749integerPart
750APFloat::addSignificand(const APFloat &rhs)
751{
752 integerPart *parts;
753
754 parts = significandParts();
755
756 assert(semantics == rhs.semantics);
757 assert(exponent == rhs.exponent);
758
759 return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
760}
761
762/* Subtract the significand of the RHS with a borrow flag. Returns
763 the borrow flag. */
764integerPart
765APFloat::subtractSignificand(const APFloat &rhs, integerPart borrow)
766{
767 integerPart *parts;
768
769 parts = significandParts();
770
771 assert(semantics == rhs.semantics);
772 assert(exponent == rhs.exponent);
773
774 return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
Neil Booth4f881702007-09-26 21:33:42 +0000775 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000776}
777
778/* Multiply the significand of the RHS. If ADDEND is non-NULL, add it
779 on to the full-precision result of the multiplication. Returns the
780 lost fraction. */
781lostFraction
782APFloat::multiplySignificand(const APFloat &rhs, const APFloat *addend)
783{
Neil Booth4f881702007-09-26 21:33:42 +0000784 unsigned int omsb; // One, not zero, based MSB.
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000785 unsigned int partsCount, newPartsCount, precision;
786 integerPart *lhsSignificand;
787 integerPart scratch[4];
788 integerPart *fullSignificand;
789 lostFraction lost_fraction;
790
791 assert(semantics == rhs.semantics);
792
793 precision = semantics->precision;
794 newPartsCount = partCountForBits(precision * 2);
795
796 if(newPartsCount > 4)
797 fullSignificand = new integerPart[newPartsCount];
798 else
799 fullSignificand = scratch;
800
801 lhsSignificand = significandParts();
802 partsCount = partCount();
803
804 APInt::tcFullMultiply(fullSignificand, lhsSignificand,
Neil Booth978661d2007-10-06 00:24:48 +0000805 rhs.significandParts(), partsCount, partsCount);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000806
807 lost_fraction = lfExactlyZero;
808 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
809 exponent += rhs.exponent;
810
811 if(addend) {
812 Significand savedSignificand = significand;
813 const fltSemantics *savedSemantics = semantics;
814 fltSemantics extendedSemantics;
815 opStatus status;
816 unsigned int extendedPrecision;
817
818 /* Normalize our MSB. */
819 extendedPrecision = precision + precision - 1;
820 if(omsb != extendedPrecision)
821 {
Neil Booth4f881702007-09-26 21:33:42 +0000822 APInt::tcShiftLeft(fullSignificand, newPartsCount,
823 extendedPrecision - omsb);
824 exponent -= extendedPrecision - omsb;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000825 }
826
827 /* Create new semantics. */
828 extendedSemantics = *semantics;
829 extendedSemantics.precision = extendedPrecision;
830
831 if(newPartsCount == 1)
832 significand.part = fullSignificand[0];
833 else
834 significand.parts = fullSignificand;
835 semantics = &extendedSemantics;
836
837 APFloat extendedAddend(*addend);
838 status = extendedAddend.convert(extendedSemantics, rmTowardZero);
839 assert(status == opOK);
840 lost_fraction = addOrSubtractSignificand(extendedAddend, false);
841
842 /* Restore our state. */
843 if(newPartsCount == 1)
844 fullSignificand[0] = significand.part;
845 significand = savedSignificand;
846 semantics = savedSemantics;
847
848 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
849 }
850
851 exponent -= (precision - 1);
852
853 if(omsb > precision) {
854 unsigned int bits, significantParts;
855 lostFraction lf;
856
857 bits = omsb - precision;
858 significantParts = partCountForBits(omsb);
859 lf = shiftRight(fullSignificand, significantParts, bits);
860 lost_fraction = combineLostFractions(lf, lost_fraction);
861 exponent += bits;
862 }
863
864 APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
865
866 if(newPartsCount > 4)
867 delete [] fullSignificand;
868
869 return lost_fraction;
870}
871
872/* Multiply the significands of LHS and RHS to DST. */
873lostFraction
874APFloat::divideSignificand(const APFloat &rhs)
875{
876 unsigned int bit, i, partsCount;
877 const integerPart *rhsSignificand;
878 integerPart *lhsSignificand, *dividend, *divisor;
879 integerPart scratch[4];
880 lostFraction lost_fraction;
881
882 assert(semantics == rhs.semantics);
883
884 lhsSignificand = significandParts();
885 rhsSignificand = rhs.significandParts();
886 partsCount = partCount();
887
888 if(partsCount > 2)
889 dividend = new integerPart[partsCount * 2];
890 else
891 dividend = scratch;
892
893 divisor = dividend + partsCount;
894
895 /* Copy the dividend and divisor as they will be modified in-place. */
896 for(i = 0; i < partsCount; i++) {
897 dividend[i] = lhsSignificand[i];
898 divisor[i] = rhsSignificand[i];
899 lhsSignificand[i] = 0;
900 }
901
902 exponent -= rhs.exponent;
903
904 unsigned int precision = semantics->precision;
905
906 /* Normalize the divisor. */
907 bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
908 if(bit) {
909 exponent += bit;
910 APInt::tcShiftLeft(divisor, partsCount, bit);
911 }
912
913 /* Normalize the dividend. */
914 bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
915 if(bit) {
916 exponent -= bit;
917 APInt::tcShiftLeft(dividend, partsCount, bit);
918 }
919
Neil Booth96c74712007-10-12 16:02:31 +0000920 /* Ensure the dividend >= divisor initially for the loop below.
921 Incidentally, this means that the division loop below is
922 guaranteed to set the integer bit to one. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000923 if(APInt::tcCompare(dividend, divisor, partsCount) < 0) {
924 exponent--;
925 APInt::tcShiftLeft(dividend, partsCount, 1);
926 assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
927 }
928
929 /* Long division. */
930 for(bit = precision; bit; bit -= 1) {
931 if(APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
932 APInt::tcSubtract(dividend, divisor, 0, partsCount);
933 APInt::tcSetBit(lhsSignificand, bit - 1);
934 }
935
936 APInt::tcShiftLeft(dividend, partsCount, 1);
937 }
938
939 /* Figure out the lost fraction. */
940 int cmp = APInt::tcCompare(dividend, divisor, partsCount);
941
942 if(cmp > 0)
943 lost_fraction = lfMoreThanHalf;
944 else if(cmp == 0)
945 lost_fraction = lfExactlyHalf;
946 else if(APInt::tcIsZero(dividend, partsCount))
947 lost_fraction = lfExactlyZero;
948 else
949 lost_fraction = lfLessThanHalf;
950
951 if(partsCount > 2)
952 delete [] dividend;
953
954 return lost_fraction;
955}
956
957unsigned int
958APFloat::significandMSB() const
959{
960 return APInt::tcMSB(significandParts(), partCount());
961}
962
963unsigned int
964APFloat::significandLSB() const
965{
966 return APInt::tcLSB(significandParts(), partCount());
967}
968
969/* Note that a zero result is NOT normalized to fcZero. */
970lostFraction
971APFloat::shiftSignificandRight(unsigned int bits)
972{
973 /* Our exponent should not overflow. */
974 assert((exponent_t) (exponent + bits) >= exponent);
975
976 exponent += bits;
977
978 return shiftRight(significandParts(), partCount(), bits);
979}
980
981/* Shift the significand left BITS bits, subtract BITS from its exponent. */
982void
983APFloat::shiftSignificandLeft(unsigned int bits)
984{
985 assert(bits < semantics->precision);
986
987 if(bits) {
988 unsigned int partsCount = partCount();
989
990 APInt::tcShiftLeft(significandParts(), partsCount, bits);
991 exponent -= bits;
992
993 assert(!APInt::tcIsZero(significandParts(), partsCount));
994 }
995}
996
997APFloat::cmpResult
998APFloat::compareAbsoluteValue(const APFloat &rhs) const
999{
1000 int compare;
1001
1002 assert(semantics == rhs.semantics);
1003 assert(category == fcNormal);
1004 assert(rhs.category == fcNormal);
1005
1006 compare = exponent - rhs.exponent;
1007
1008 /* If exponents are equal, do an unsigned bignum comparison of the
1009 significands. */
1010 if(compare == 0)
1011 compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
Neil Booth4f881702007-09-26 21:33:42 +00001012 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001013
1014 if(compare > 0)
1015 return cmpGreaterThan;
1016 else if(compare < 0)
1017 return cmpLessThan;
1018 else
1019 return cmpEqual;
1020}
1021
1022/* Handle overflow. Sign is preserved. We either become infinity or
1023 the largest finite number. */
1024APFloat::opStatus
1025APFloat::handleOverflow(roundingMode rounding_mode)
1026{
1027 /* Infinity? */
1028 if(rounding_mode == rmNearestTiesToEven
1029 || rounding_mode == rmNearestTiesToAway
1030 || (rounding_mode == rmTowardPositive && !sign)
1031 || (rounding_mode == rmTowardNegative && sign))
1032 {
1033 category = fcInfinity;
1034 return (opStatus) (opOverflow | opInexact);
1035 }
1036
1037 /* Otherwise we become the largest finite number. */
1038 category = fcNormal;
1039 exponent = semantics->maxExponent;
1040 APInt::tcSetLeastSignificantBits(significandParts(), partCount(),
Neil Booth4f881702007-09-26 21:33:42 +00001041 semantics->precision);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001042
1043 return opInexact;
1044}
1045
Neil Boothb7dea4c2007-10-03 15:16:41 +00001046/* Returns TRUE if, when truncating the current number, with BIT the
1047 new LSB, with the given lost fraction and rounding mode, the result
1048 would need to be rounded away from zero (i.e., by increasing the
1049 signficand). This routine must work for fcZero of both signs, and
1050 fcNormal numbers. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001051bool
1052APFloat::roundAwayFromZero(roundingMode rounding_mode,
Neil Boothb7dea4c2007-10-03 15:16:41 +00001053 lostFraction lost_fraction,
1054 unsigned int bit) const
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001055{
Dale Johanneseneaf08942007-08-31 04:03:46 +00001056 /* NaNs and infinities should not have lost fractions. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001057 assert(category == fcNormal || category == fcZero);
1058
Neil Boothb7dea4c2007-10-03 15:16:41 +00001059 /* Current callers never pass this so we don't handle it. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001060 assert(lost_fraction != lfExactlyZero);
1061
1062 switch(rounding_mode) {
1063 default:
1064 assert(0);
1065
1066 case rmNearestTiesToAway:
1067 return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
1068
1069 case rmNearestTiesToEven:
1070 if(lost_fraction == lfMoreThanHalf)
1071 return true;
1072
1073 /* Our zeroes don't have a significand to test. */
1074 if(lost_fraction == lfExactlyHalf && category != fcZero)
Neil Boothb7dea4c2007-10-03 15:16:41 +00001075 return APInt::tcExtractBit(significandParts(), bit);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001076
1077 return false;
1078
1079 case rmTowardZero:
1080 return false;
1081
1082 case rmTowardPositive:
1083 return sign == false;
1084
1085 case rmTowardNegative:
1086 return sign == true;
1087 }
1088}
1089
1090APFloat::opStatus
1091APFloat::normalize(roundingMode rounding_mode,
Neil Booth4f881702007-09-26 21:33:42 +00001092 lostFraction lost_fraction)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001093{
Neil Booth4f881702007-09-26 21:33:42 +00001094 unsigned int omsb; /* One, not zero, based MSB. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001095 int exponentChange;
1096
1097 if(category != fcNormal)
1098 return opOK;
1099
1100 /* Before rounding normalize the exponent of fcNormal numbers. */
1101 omsb = significandMSB() + 1;
1102
1103 if(omsb) {
1104 /* OMSB is numbered from 1. We want to place it in the integer
1105 bit numbered PRECISON if possible, with a compensating change in
1106 the exponent. */
1107 exponentChange = omsb - semantics->precision;
1108
1109 /* If the resulting exponent is too high, overflow according to
1110 the rounding mode. */
1111 if(exponent + exponentChange > semantics->maxExponent)
1112 return handleOverflow(rounding_mode);
1113
1114 /* Subnormal numbers have exponent minExponent, and their MSB
1115 is forced based on that. */
1116 if(exponent + exponentChange < semantics->minExponent)
1117 exponentChange = semantics->minExponent - exponent;
1118
1119 /* Shifting left is easy as we don't lose precision. */
1120 if(exponentChange < 0) {
1121 assert(lost_fraction == lfExactlyZero);
1122
1123 shiftSignificandLeft(-exponentChange);
1124
1125 return opOK;
1126 }
1127
1128 if(exponentChange > 0) {
1129 lostFraction lf;
1130
1131 /* Shift right and capture any new lost fraction. */
1132 lf = shiftSignificandRight(exponentChange);
1133
1134 lost_fraction = combineLostFractions(lf, lost_fraction);
1135
1136 /* Keep OMSB up-to-date. */
1137 if(omsb > (unsigned) exponentChange)
Neil Booth96c74712007-10-12 16:02:31 +00001138 omsb -= exponentChange;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001139 else
Neil Booth4f881702007-09-26 21:33:42 +00001140 omsb = 0;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001141 }
1142 }
1143
1144 /* Now round the number according to rounding_mode given the lost
1145 fraction. */
1146
1147 /* As specified in IEEE 754, since we do not trap we do not report
1148 underflow for exact results. */
1149 if(lost_fraction == lfExactlyZero) {
1150 /* Canonicalize zeroes. */
1151 if(omsb == 0)
1152 category = fcZero;
1153
1154 return opOK;
1155 }
1156
1157 /* Increment the significand if we're rounding away from zero. */
Neil Boothb7dea4c2007-10-03 15:16:41 +00001158 if(roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001159 if(omsb == 0)
1160 exponent = semantics->minExponent;
1161
1162 incrementSignificand();
1163 omsb = significandMSB() + 1;
1164
1165 /* Did the significand increment overflow? */
1166 if(omsb == (unsigned) semantics->precision + 1) {
1167 /* Renormalize by incrementing the exponent and shifting our
Neil Booth4f881702007-09-26 21:33:42 +00001168 significand right one. However if we already have the
1169 maximum exponent we overflow to infinity. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001170 if(exponent == semantics->maxExponent) {
Neil Booth4f881702007-09-26 21:33:42 +00001171 category = fcInfinity;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001172
Neil Booth4f881702007-09-26 21:33:42 +00001173 return (opStatus) (opOverflow | opInexact);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001174 }
1175
1176 shiftSignificandRight(1);
1177
1178 return opInexact;
1179 }
1180 }
1181
1182 /* The normal case - we were and are not denormal, and any
1183 significand increment above didn't overflow. */
1184 if(omsb == semantics->precision)
1185 return opInexact;
1186
1187 /* We have a non-zero denormal. */
1188 assert(omsb < semantics->precision);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001189
1190 /* Canonicalize zeroes. */
1191 if(omsb == 0)
1192 category = fcZero;
1193
1194 /* The fcZero case is a denormal that underflowed to zero. */
1195 return (opStatus) (opUnderflow | opInexact);
1196}
1197
1198APFloat::opStatus
1199APFloat::addOrSubtractSpecials(const APFloat &rhs, bool subtract)
1200{
1201 switch(convolve(category, rhs.category)) {
1202 default:
1203 assert(0);
1204
Dale Johanneseneaf08942007-08-31 04:03:46 +00001205 case convolve(fcNaN, fcZero):
1206 case convolve(fcNaN, fcNormal):
1207 case convolve(fcNaN, fcInfinity):
1208 case convolve(fcNaN, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001209 case convolve(fcNormal, fcZero):
1210 case convolve(fcInfinity, fcNormal):
1211 case convolve(fcInfinity, fcZero):
1212 return opOK;
1213
Dale Johanneseneaf08942007-08-31 04:03:46 +00001214 case convolve(fcZero, fcNaN):
1215 case convolve(fcNormal, fcNaN):
1216 case convolve(fcInfinity, fcNaN):
1217 category = fcNaN;
1218 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001219 return opOK;
1220
1221 case convolve(fcNormal, fcInfinity):
1222 case convolve(fcZero, fcInfinity):
1223 category = fcInfinity;
1224 sign = rhs.sign ^ subtract;
1225 return opOK;
1226
1227 case convolve(fcZero, fcNormal):
1228 assign(rhs);
1229 sign = rhs.sign ^ subtract;
1230 return opOK;
1231
1232 case convolve(fcZero, fcZero):
1233 /* Sign depends on rounding mode; handled by caller. */
1234 return opOK;
1235
1236 case convolve(fcInfinity, fcInfinity):
1237 /* Differently signed infinities can only be validly
1238 subtracted. */
Hartmut Kaiser8df77a92007-10-25 23:15:31 +00001239 if((sign ^ rhs.sign) != subtract) {
Neil Boothe5e01942007-10-14 10:39:51 +00001240 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001241 return opInvalidOp;
1242 }
1243
1244 return opOK;
1245
1246 case convolve(fcNormal, fcNormal):
1247 return opDivByZero;
1248 }
1249}
1250
1251/* Add or subtract two normal numbers. */
1252lostFraction
1253APFloat::addOrSubtractSignificand(const APFloat &rhs, bool subtract)
1254{
1255 integerPart carry;
1256 lostFraction lost_fraction;
1257 int bits;
1258
1259 /* Determine if the operation on the absolute values is effectively
1260 an addition or subtraction. */
Hartmut Kaiser8df77a92007-10-25 23:15:31 +00001261 subtract ^= (sign ^ rhs.sign) ? true : false;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001262
1263 /* Are we bigger exponent-wise than the RHS? */
1264 bits = exponent - rhs.exponent;
1265
1266 /* Subtraction is more subtle than one might naively expect. */
1267 if(subtract) {
1268 APFloat temp_rhs(rhs);
1269 bool reverse;
1270
Chris Lattnerada530b2007-08-24 03:02:34 +00001271 if (bits == 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001272 reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan;
1273 lost_fraction = lfExactlyZero;
Chris Lattnerada530b2007-08-24 03:02:34 +00001274 } else if (bits > 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001275 lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
1276 shiftSignificandLeft(1);
1277 reverse = false;
Chris Lattnerada530b2007-08-24 03:02:34 +00001278 } else {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001279 lost_fraction = shiftSignificandRight(-bits - 1);
1280 temp_rhs.shiftSignificandLeft(1);
1281 reverse = true;
1282 }
1283
Chris Lattnerada530b2007-08-24 03:02:34 +00001284 if (reverse) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001285 carry = temp_rhs.subtractSignificand
Neil Booth4f881702007-09-26 21:33:42 +00001286 (*this, lost_fraction != lfExactlyZero);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001287 copySignificand(temp_rhs);
1288 sign = !sign;
1289 } else {
1290 carry = subtractSignificand
Neil Booth4f881702007-09-26 21:33:42 +00001291 (temp_rhs, lost_fraction != lfExactlyZero);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001292 }
1293
1294 /* Invert the lost fraction - it was on the RHS and
1295 subtracted. */
1296 if(lost_fraction == lfLessThanHalf)
1297 lost_fraction = lfMoreThanHalf;
1298 else if(lost_fraction == lfMoreThanHalf)
1299 lost_fraction = lfLessThanHalf;
1300
1301 /* The code above is intended to ensure that no borrow is
1302 necessary. */
1303 assert(!carry);
1304 } else {
1305 if(bits > 0) {
1306 APFloat temp_rhs(rhs);
1307
1308 lost_fraction = temp_rhs.shiftSignificandRight(bits);
1309 carry = addSignificand(temp_rhs);
1310 } else {
1311 lost_fraction = shiftSignificandRight(-bits);
1312 carry = addSignificand(rhs);
1313 }
1314
1315 /* We have a guard bit; generating a carry cannot happen. */
1316 assert(!carry);
1317 }
1318
1319 return lost_fraction;
1320}
1321
1322APFloat::opStatus
1323APFloat::multiplySpecials(const APFloat &rhs)
1324{
1325 switch(convolve(category, rhs.category)) {
1326 default:
1327 assert(0);
1328
Dale Johanneseneaf08942007-08-31 04:03:46 +00001329 case convolve(fcNaN, fcZero):
1330 case convolve(fcNaN, fcNormal):
1331 case convolve(fcNaN, fcInfinity):
1332 case convolve(fcNaN, fcNaN):
1333 return opOK;
1334
1335 case convolve(fcZero, fcNaN):
1336 case convolve(fcNormal, fcNaN):
1337 case convolve(fcInfinity, fcNaN):
1338 category = fcNaN;
1339 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001340 return opOK;
1341
1342 case convolve(fcNormal, fcInfinity):
1343 case convolve(fcInfinity, fcNormal):
1344 case convolve(fcInfinity, fcInfinity):
1345 category = fcInfinity;
1346 return opOK;
1347
1348 case convolve(fcZero, fcNormal):
1349 case convolve(fcNormal, fcZero):
1350 case convolve(fcZero, fcZero):
1351 category = fcZero;
1352 return opOK;
1353
1354 case convolve(fcZero, fcInfinity):
1355 case convolve(fcInfinity, fcZero):
Neil Boothe5e01942007-10-14 10:39:51 +00001356 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001357 return opInvalidOp;
1358
1359 case convolve(fcNormal, fcNormal):
1360 return opOK;
1361 }
1362}
1363
1364APFloat::opStatus
1365APFloat::divideSpecials(const APFloat &rhs)
1366{
1367 switch(convolve(category, rhs.category)) {
1368 default:
1369 assert(0);
1370
Dale Johanneseneaf08942007-08-31 04:03:46 +00001371 case convolve(fcNaN, fcZero):
1372 case convolve(fcNaN, fcNormal):
1373 case convolve(fcNaN, fcInfinity):
1374 case convolve(fcNaN, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001375 case convolve(fcInfinity, fcZero):
1376 case convolve(fcInfinity, fcNormal):
1377 case convolve(fcZero, fcInfinity):
1378 case convolve(fcZero, fcNormal):
1379 return opOK;
1380
Dale Johanneseneaf08942007-08-31 04:03:46 +00001381 case convolve(fcZero, fcNaN):
1382 case convolve(fcNormal, fcNaN):
1383 case convolve(fcInfinity, fcNaN):
1384 category = fcNaN;
1385 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001386 return opOK;
1387
1388 case convolve(fcNormal, fcInfinity):
1389 category = fcZero;
1390 return opOK;
1391
1392 case convolve(fcNormal, fcZero):
1393 category = fcInfinity;
1394 return opDivByZero;
1395
1396 case convolve(fcInfinity, fcInfinity):
1397 case convolve(fcZero, fcZero):
Neil Boothe5e01942007-10-14 10:39:51 +00001398 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001399 return opInvalidOp;
1400
1401 case convolve(fcNormal, fcNormal):
1402 return opOK;
1403 }
1404}
1405
1406/* Change sign. */
1407void
1408APFloat::changeSign()
1409{
1410 /* Look mummy, this one's easy. */
1411 sign = !sign;
1412}
1413
Dale Johannesene15c2db2007-08-31 23:35:31 +00001414void
1415APFloat::clearSign()
1416{
1417 /* So is this one. */
1418 sign = 0;
1419}
1420
1421void
1422APFloat::copySign(const APFloat &rhs)
1423{
1424 /* And this one. */
1425 sign = rhs.sign;
1426}
1427
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001428/* Normalized addition or subtraction. */
1429APFloat::opStatus
1430APFloat::addOrSubtract(const APFloat &rhs, roundingMode rounding_mode,
Neil Booth4f881702007-09-26 21:33:42 +00001431 bool subtract)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001432{
1433 opStatus fs;
1434
Neil Boothcaf19d72007-10-14 10:29:28 +00001435 assertArithmeticOK(*semantics);
1436
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001437 fs = addOrSubtractSpecials(rhs, subtract);
1438
1439 /* This return code means it was not a simple case. */
1440 if(fs == opDivByZero) {
1441 lostFraction lost_fraction;
1442
1443 lost_fraction = addOrSubtractSignificand(rhs, subtract);
1444 fs = normalize(rounding_mode, lost_fraction);
1445
1446 /* Can only be zero if we lost no fraction. */
1447 assert(category != fcZero || lost_fraction == lfExactlyZero);
1448 }
1449
1450 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1451 positive zero unless rounding to minus infinity, except that
1452 adding two like-signed zeroes gives that zero. */
1453 if(category == fcZero) {
1454 if(rhs.category != fcZero || (sign == rhs.sign) == subtract)
1455 sign = (rounding_mode == rmTowardNegative);
1456 }
1457
1458 return fs;
1459}
1460
1461/* Normalized addition. */
1462APFloat::opStatus
1463APFloat::add(const APFloat &rhs, roundingMode rounding_mode)
1464{
1465 return addOrSubtract(rhs, rounding_mode, false);
1466}
1467
1468/* Normalized subtraction. */
1469APFloat::opStatus
1470APFloat::subtract(const APFloat &rhs, roundingMode rounding_mode)
1471{
1472 return addOrSubtract(rhs, rounding_mode, true);
1473}
1474
1475/* Normalized multiply. */
1476APFloat::opStatus
1477APFloat::multiply(const APFloat &rhs, roundingMode rounding_mode)
1478{
1479 opStatus fs;
1480
Neil Boothcaf19d72007-10-14 10:29:28 +00001481 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001482 sign ^= rhs.sign;
1483 fs = multiplySpecials(rhs);
1484
1485 if(category == fcNormal) {
1486 lostFraction lost_fraction = multiplySignificand(rhs, 0);
1487 fs = normalize(rounding_mode, lost_fraction);
1488 if(lost_fraction != lfExactlyZero)
1489 fs = (opStatus) (fs | opInexact);
1490 }
1491
1492 return fs;
1493}
1494
1495/* Normalized divide. */
1496APFloat::opStatus
1497APFloat::divide(const APFloat &rhs, roundingMode rounding_mode)
1498{
1499 opStatus fs;
1500
Neil Boothcaf19d72007-10-14 10:29:28 +00001501 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001502 sign ^= rhs.sign;
1503 fs = divideSpecials(rhs);
1504
1505 if(category == fcNormal) {
1506 lostFraction lost_fraction = divideSignificand(rhs);
1507 fs = normalize(rounding_mode, lost_fraction);
1508 if(lost_fraction != lfExactlyZero)
1509 fs = (opStatus) (fs | opInexact);
1510 }
1511
1512 return fs;
1513}
1514
Neil Bootha30b0ee2007-10-03 22:26:02 +00001515/* Normalized remainder. This is not currently doing TRT. */
Dale Johannesene15c2db2007-08-31 23:35:31 +00001516APFloat::opStatus
1517APFloat::mod(const APFloat &rhs, roundingMode rounding_mode)
1518{
1519 opStatus fs;
1520 APFloat V = *this;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001521 unsigned int origSign = sign;
Neil Boothcaf19d72007-10-14 10:29:28 +00001522
1523 assertArithmeticOK(*semantics);
Dale Johannesene15c2db2007-08-31 23:35:31 +00001524 fs = V.divide(rhs, rmNearestTiesToEven);
1525 if (fs == opDivByZero)
1526 return fs;
1527
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001528 int parts = partCount();
1529 integerPart *x = new integerPart[parts];
Neil Booth4f881702007-09-26 21:33:42 +00001530 fs = V.convertToInteger(x, parts * integerPartWidth, true,
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001531 rmNearestTiesToEven);
Dale Johannesene15c2db2007-08-31 23:35:31 +00001532 if (fs==opInvalidOp)
1533 return fs;
1534
Neil Boothccf596a2007-10-07 11:45:55 +00001535 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1536 rmNearestTiesToEven);
Dale Johannesene15c2db2007-08-31 23:35:31 +00001537 assert(fs==opOK); // should always work
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001538
Dale Johannesene15c2db2007-08-31 23:35:31 +00001539 fs = V.multiply(rhs, rounding_mode);
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001540 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1541
Dale Johannesene15c2db2007-08-31 23:35:31 +00001542 fs = subtract(V, rounding_mode);
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001543 assert(fs==opOK || fs==opInexact); // likewise
1544
1545 if (isZero())
1546 sign = origSign; // IEEE754 requires this
1547 delete[] x;
Dale Johannesene15c2db2007-08-31 23:35:31 +00001548 return fs;
1549}
1550
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001551/* Normalized fused-multiply-add. */
1552APFloat::opStatus
1553APFloat::fusedMultiplyAdd(const APFloat &multiplicand,
Neil Booth4f881702007-09-26 21:33:42 +00001554 const APFloat &addend,
1555 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001556{
1557 opStatus fs;
1558
Neil Boothcaf19d72007-10-14 10:29:28 +00001559 assertArithmeticOK(*semantics);
1560
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001561 /* Post-multiplication sign, before addition. */
1562 sign ^= multiplicand.sign;
1563
1564 /* If and only if all arguments are normal do we need to do an
1565 extended-precision calculation. */
1566 if(category == fcNormal
1567 && multiplicand.category == fcNormal
1568 && addend.category == fcNormal) {
1569 lostFraction lost_fraction;
1570
1571 lost_fraction = multiplySignificand(multiplicand, &addend);
1572 fs = normalize(rounding_mode, lost_fraction);
1573 if(lost_fraction != lfExactlyZero)
1574 fs = (opStatus) (fs | opInexact);
1575
1576 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1577 positive zero unless rounding to minus infinity, except that
1578 adding two like-signed zeroes gives that zero. */
1579 if(category == fcZero && sign != addend.sign)
1580 sign = (rounding_mode == rmTowardNegative);
1581 } else {
1582 fs = multiplySpecials(multiplicand);
1583
1584 /* FS can only be opOK or opInvalidOp. There is no more work
1585 to do in the latter case. The IEEE-754R standard says it is
1586 implementation-defined in this case whether, if ADDEND is a
Dale Johanneseneaf08942007-08-31 04:03:46 +00001587 quiet NaN, we raise invalid op; this implementation does so.
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001588
1589 If we need to do the addition we can do so with normal
1590 precision. */
1591 if(fs == opOK)
1592 fs = addOrSubtract(addend, rounding_mode, false);
1593 }
1594
1595 return fs;
1596}
1597
1598/* Comparison requires normalized numbers. */
1599APFloat::cmpResult
1600APFloat::compare(const APFloat &rhs) const
1601{
1602 cmpResult result;
1603
Neil Boothcaf19d72007-10-14 10:29:28 +00001604 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001605 assert(semantics == rhs.semantics);
1606
1607 switch(convolve(category, rhs.category)) {
1608 default:
1609 assert(0);
1610
Dale Johanneseneaf08942007-08-31 04:03:46 +00001611 case convolve(fcNaN, fcZero):
1612 case convolve(fcNaN, fcNormal):
1613 case convolve(fcNaN, fcInfinity):
1614 case convolve(fcNaN, fcNaN):
1615 case convolve(fcZero, fcNaN):
1616 case convolve(fcNormal, fcNaN):
1617 case convolve(fcInfinity, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001618 return cmpUnordered;
1619
1620 case convolve(fcInfinity, fcNormal):
1621 case convolve(fcInfinity, fcZero):
1622 case convolve(fcNormal, fcZero):
1623 if(sign)
1624 return cmpLessThan;
1625 else
1626 return cmpGreaterThan;
1627
1628 case convolve(fcNormal, fcInfinity):
1629 case convolve(fcZero, fcInfinity):
1630 case convolve(fcZero, fcNormal):
1631 if(rhs.sign)
1632 return cmpGreaterThan;
1633 else
1634 return cmpLessThan;
1635
1636 case convolve(fcInfinity, fcInfinity):
1637 if(sign == rhs.sign)
1638 return cmpEqual;
1639 else if(sign)
1640 return cmpLessThan;
1641 else
1642 return cmpGreaterThan;
1643
1644 case convolve(fcZero, fcZero):
1645 return cmpEqual;
1646
1647 case convolve(fcNormal, fcNormal):
1648 break;
1649 }
1650
1651 /* Two normal numbers. Do they have the same sign? */
1652 if(sign != rhs.sign) {
1653 if(sign)
1654 result = cmpLessThan;
1655 else
1656 result = cmpGreaterThan;
1657 } else {
1658 /* Compare absolute values; invert result if negative. */
1659 result = compareAbsoluteValue(rhs);
1660
1661 if(sign) {
1662 if(result == cmpLessThan)
Neil Booth4f881702007-09-26 21:33:42 +00001663 result = cmpGreaterThan;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001664 else if(result == cmpGreaterThan)
Neil Booth4f881702007-09-26 21:33:42 +00001665 result = cmpLessThan;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001666 }
1667 }
1668
1669 return result;
1670}
1671
1672APFloat::opStatus
1673APFloat::convert(const fltSemantics &toSemantics,
Neil Booth4f881702007-09-26 21:33:42 +00001674 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001675{
Neil Boothc8db43d2007-09-22 02:56:19 +00001676 lostFraction lostFraction;
1677 unsigned int newPartCount, oldPartCount;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001678 opStatus fs;
Neil Booth4f881702007-09-26 21:33:42 +00001679
Neil Boothcaf19d72007-10-14 10:29:28 +00001680 assertArithmeticOK(*semantics);
Dale Johannesen79f82f92008-04-20 01:34:03 +00001681 assertArithmeticOK(toSemantics);
Neil Boothc8db43d2007-09-22 02:56:19 +00001682 lostFraction = lfExactlyZero;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001683 newPartCount = partCountForBits(toSemantics.precision + 1);
Neil Boothc8db43d2007-09-22 02:56:19 +00001684 oldPartCount = partCount();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001685
Neil Boothc8db43d2007-09-22 02:56:19 +00001686 /* Handle storage complications. If our new form is wider,
1687 re-allocate our bit pattern into wider storage. If it is
1688 narrower, we ignore the excess parts, but if narrowing to a
Dale Johannesen902ff942007-09-25 17:25:00 +00001689 single part we need to free the old storage.
1690 Be careful not to reference significandParts for zeroes
1691 and infinities, since it aborts. */
Neil Boothc8db43d2007-09-22 02:56:19 +00001692 if (newPartCount > oldPartCount) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001693 integerPart *newParts;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001694 newParts = new integerPart[newPartCount];
1695 APInt::tcSet(newParts, 0, newPartCount);
Dale Johannesen902ff942007-09-25 17:25:00 +00001696 if (category==fcNormal || category==fcNaN)
1697 APInt::tcAssign(newParts, significandParts(), oldPartCount);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001698 freeSignificand();
1699 significand.parts = newParts;
Neil Boothc8db43d2007-09-22 02:56:19 +00001700 } else if (newPartCount < oldPartCount) {
1701 /* Capture any lost fraction through truncation of parts so we get
1702 correct rounding whilst normalizing. */
Dale Johannesen902ff942007-09-25 17:25:00 +00001703 if (category==fcNormal)
1704 lostFraction = lostFractionThroughTruncation
1705 (significandParts(), oldPartCount, toSemantics.precision);
1706 if (newPartCount == 1) {
1707 integerPart newPart = 0;
Neil Booth4f881702007-09-26 21:33:42 +00001708 if (category==fcNormal || category==fcNaN)
Dale Johannesen902ff942007-09-25 17:25:00 +00001709 newPart = significandParts()[0];
1710 freeSignificand();
1711 significand.part = newPart;
1712 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001713 }
1714
1715 if(category == fcNormal) {
1716 /* Re-interpret our bit-pattern. */
1717 exponent += toSemantics.precision - semantics->precision;
1718 semantics = &toSemantics;
Neil Boothc8db43d2007-09-22 02:56:19 +00001719 fs = normalize(rounding_mode, lostFraction);
Dale Johannesen902ff942007-09-25 17:25:00 +00001720 } else if (category == fcNaN) {
1721 int shift = toSemantics.precision - semantics->precision;
Dale Johannesenb63fa052008-01-31 18:34:01 +00001722 // Do this now so significandParts gets the right answer
1723 semantics = &toSemantics;
Dale Johannesen902ff942007-09-25 17:25:00 +00001724 // No normalization here, just truncate
1725 if (shift>0)
1726 APInt::tcShiftLeft(significandParts(), newPartCount, shift);
1727 else if (shift < 0)
1728 APInt::tcShiftRight(significandParts(), newPartCount, -shift);
1729 // gcc forces the Quiet bit on, which means (float)(double)(float_sNan)
1730 // does not give you back the same bits. This is dubious, and we
1731 // don't currently do it. You're really supposed to get
1732 // an invalid operation signal at runtime, but nobody does that.
Dale Johannesen902ff942007-09-25 17:25:00 +00001733 fs = opOK;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001734 } else {
1735 semantics = &toSemantics;
1736 fs = opOK;
1737 }
1738
1739 return fs;
1740}
1741
1742/* Convert a floating point number to an integer according to the
1743 rounding mode. If the rounded integer value is out of range this
Neil Boothee7ae382007-11-01 22:43:37 +00001744 returns an invalid operation exception and the contents of the
1745 destination parts are unspecified. If the rounded value is in
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001746 range but the floating point number is not the exact integer, the C
1747 standard doesn't require an inexact exception to be raised. IEEE
1748 854 does require it so we do that.
1749
1750 Note that for conversions to integer type the C standard requires
1751 round-to-zero to always be used. */
1752APFloat::opStatus
Neil Boothee7ae382007-11-01 22:43:37 +00001753APFloat::convertToSignExtendedInteger(integerPart *parts, unsigned int width,
1754 bool isSigned,
1755 roundingMode rounding_mode) const
1756{
1757 lostFraction lost_fraction;
1758 const integerPart *src;
1759 unsigned int dstPartsCount, truncatedBits;
1760
Neil Boothe3d936a2007-11-02 15:10:05 +00001761 assertArithmeticOK(*semantics);
1762
Neil Boothee7ae382007-11-01 22:43:37 +00001763 /* Handle the three special cases first. */
1764 if(category == fcInfinity || category == fcNaN)
1765 return opInvalidOp;
1766
1767 dstPartsCount = partCountForBits(width);
1768
1769 if(category == fcZero) {
1770 APInt::tcSet(parts, 0, dstPartsCount);
1771 return opOK;
1772 }
1773
1774 src = significandParts();
1775
1776 /* Step 1: place our absolute value, with any fraction truncated, in
1777 the destination. */
1778 if (exponent < 0) {
1779 /* Our absolute value is less than one; truncate everything. */
1780 APInt::tcSet(parts, 0, dstPartsCount);
1781 truncatedBits = semantics->precision;
1782 } else {
1783 /* We want the most significant (exponent + 1) bits; the rest are
1784 truncated. */
1785 unsigned int bits = exponent + 1U;
1786
1787 /* Hopelessly large in magnitude? */
1788 if (bits > width)
1789 return opInvalidOp;
1790
1791 if (bits < semantics->precision) {
1792 /* We truncate (semantics->precision - bits) bits. */
1793 truncatedBits = semantics->precision - bits;
1794 APInt::tcExtract(parts, dstPartsCount, src, bits, truncatedBits);
1795 } else {
1796 /* We want at least as many bits as are available. */
1797 APInt::tcExtract(parts, dstPartsCount, src, semantics->precision, 0);
1798 APInt::tcShiftLeft(parts, dstPartsCount, bits - semantics->precision);
1799 truncatedBits = 0;
1800 }
1801 }
1802
1803 /* Step 2: work out any lost fraction, and increment the absolute
1804 value if we would round away from zero. */
1805 if (truncatedBits) {
1806 lost_fraction = lostFractionThroughTruncation(src, partCount(),
1807 truncatedBits);
1808 if (lost_fraction != lfExactlyZero
1809 && roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
1810 if (APInt::tcIncrement(parts, dstPartsCount))
1811 return opInvalidOp; /* Overflow. */
1812 }
1813 } else {
1814 lost_fraction = lfExactlyZero;
1815 }
1816
1817 /* Step 3: check if we fit in the destination. */
1818 unsigned int omsb = APInt::tcMSB(parts, dstPartsCount) + 1;
1819
1820 if (sign) {
1821 if (!isSigned) {
1822 /* Negative numbers cannot be represented as unsigned. */
1823 if (omsb != 0)
1824 return opInvalidOp;
1825 } else {
1826 /* It takes omsb bits to represent the unsigned integer value.
1827 We lose a bit for the sign, but care is needed as the
1828 maximally negative integer is a special case. */
1829 if (omsb == width && APInt::tcLSB(parts, dstPartsCount) + 1 != omsb)
1830 return opInvalidOp;
1831
1832 /* This case can happen because of rounding. */
1833 if (omsb > width)
1834 return opInvalidOp;
1835 }
1836
1837 APInt::tcNegate (parts, dstPartsCount);
1838 } else {
1839 if (omsb >= width + !isSigned)
1840 return opInvalidOp;
1841 }
1842
1843 if (lost_fraction == lfExactlyZero)
1844 return opOK;
1845 else
1846 return opInexact;
1847}
1848
1849/* Same as convertToSignExtendedInteger, except we provide
1850 deterministic values in case of an invalid operation exception,
1851 namely zero for NaNs and the minimal or maximal value respectively
1852 for underflow or overflow. */
1853APFloat::opStatus
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001854APFloat::convertToInteger(integerPart *parts, unsigned int width,
Neil Booth4f881702007-09-26 21:33:42 +00001855 bool isSigned,
1856 roundingMode rounding_mode) const
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001857{
Neil Boothee7ae382007-11-01 22:43:37 +00001858 opStatus fs;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001859
Neil Boothee7ae382007-11-01 22:43:37 +00001860 fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001861
Neil Boothee7ae382007-11-01 22:43:37 +00001862 if (fs == opInvalidOp) {
1863 unsigned int bits, dstPartsCount;
1864
1865 dstPartsCount = partCountForBits(width);
1866
1867 if (category == fcNaN)
1868 bits = 0;
1869 else if (sign)
1870 bits = isSigned;
1871 else
1872 bits = width - isSigned;
1873
1874 APInt::tcSetLeastSignificantBits(parts, dstPartsCount, bits);
1875 if (sign && isSigned)
1876 APInt::tcShiftLeft(parts, dstPartsCount, width - 1);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001877 }
1878
Neil Boothee7ae382007-11-01 22:43:37 +00001879 return fs;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001880}
1881
Neil Booth643ce592007-10-07 12:07:53 +00001882/* Convert an unsigned integer SRC to a floating point number,
1883 rounding according to ROUNDING_MODE. The sign of the floating
1884 point number is not modified. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001885APFloat::opStatus
Neil Booth643ce592007-10-07 12:07:53 +00001886APFloat::convertFromUnsignedParts(const integerPart *src,
1887 unsigned int srcCount,
1888 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001889{
Neil Booth5477f852007-10-08 14:39:42 +00001890 unsigned int omsb, precision, dstCount;
Neil Booth643ce592007-10-07 12:07:53 +00001891 integerPart *dst;
Neil Booth5477f852007-10-08 14:39:42 +00001892 lostFraction lost_fraction;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001893
Neil Boothcaf19d72007-10-14 10:29:28 +00001894 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001895 category = fcNormal;
Neil Booth5477f852007-10-08 14:39:42 +00001896 omsb = APInt::tcMSB(src, srcCount) + 1;
Neil Booth643ce592007-10-07 12:07:53 +00001897 dst = significandParts();
1898 dstCount = partCount();
Neil Booth5477f852007-10-08 14:39:42 +00001899 precision = semantics->precision;
Neil Booth643ce592007-10-07 12:07:53 +00001900
Neil Booth5477f852007-10-08 14:39:42 +00001901 /* We want the most significant PRECISON bits of SRC. There may not
1902 be that many; extract what we can. */
1903 if (precision <= omsb) {
1904 exponent = omsb - 1;
Neil Booth643ce592007-10-07 12:07:53 +00001905 lost_fraction = lostFractionThroughTruncation(src, srcCount,
Neil Booth5477f852007-10-08 14:39:42 +00001906 omsb - precision);
1907 APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
1908 } else {
1909 exponent = precision - 1;
1910 lost_fraction = lfExactlyZero;
1911 APInt::tcExtract(dst, dstCount, src, omsb, 0);
Neil Booth643ce592007-10-07 12:07:53 +00001912 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001913
1914 return normalize(rounding_mode, lost_fraction);
1915}
1916
Dan Gohman93c276e2008-02-29 01:26:11 +00001917APFloat::opStatus
1918APFloat::convertFromAPInt(const APInt &Val,
1919 bool isSigned,
1920 roundingMode rounding_mode)
1921{
1922 unsigned int partCount = Val.getNumWords();
1923 APInt api = Val;
1924
1925 sign = false;
1926 if (isSigned && api.isNegative()) {
1927 sign = true;
1928 api = -api;
1929 }
1930
1931 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
1932}
1933
Neil Boothf16c5952007-10-07 12:15:41 +00001934/* Convert a two's complement integer SRC to a floating point number,
1935 rounding according to ROUNDING_MODE. ISSIGNED is true if the
1936 integer is signed, in which case it must be sign-extended. */
1937APFloat::opStatus
1938APFloat::convertFromSignExtendedInteger(const integerPart *src,
1939 unsigned int srcCount,
1940 bool isSigned,
1941 roundingMode rounding_mode)
1942{
1943 opStatus status;
1944
Neil Boothcaf19d72007-10-14 10:29:28 +00001945 assertArithmeticOK(*semantics);
Neil Boothf16c5952007-10-07 12:15:41 +00001946 if (isSigned
1947 && APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) {
1948 integerPart *copy;
1949
1950 /* If we're signed and negative negate a copy. */
1951 sign = true;
1952 copy = new integerPart[srcCount];
1953 APInt::tcAssign(copy, src, srcCount);
1954 APInt::tcNegate(copy, srcCount);
1955 status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
1956 delete [] copy;
1957 } else {
1958 sign = false;
1959 status = convertFromUnsignedParts(src, srcCount, rounding_mode);
1960 }
1961
1962 return status;
1963}
1964
Neil Boothccf596a2007-10-07 11:45:55 +00001965/* FIXME: should this just take a const APInt reference? */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001966APFloat::opStatus
Neil Boothccf596a2007-10-07 11:45:55 +00001967APFloat::convertFromZeroExtendedInteger(const integerPart *parts,
1968 unsigned int width, bool isSigned,
1969 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001970{
Dale Johannesen910993e2007-09-21 22:09:37 +00001971 unsigned int partCount = partCountForBits(width);
Dale Johannesen910993e2007-09-21 22:09:37 +00001972 APInt api = APInt(width, partCount, parts);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001973
1974 sign = false;
Dale Johannesencce23a42007-09-30 18:17:01 +00001975 if(isSigned && APInt::tcExtractBit(parts, width - 1)) {
1976 sign = true;
1977 api = -api;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001978 }
1979
Neil Booth7a7bc0f2007-10-07 12:10:57 +00001980 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001981}
1982
1983APFloat::opStatus
1984APFloat::convertFromHexadecimalString(const char *p,
Neil Booth4f881702007-09-26 21:33:42 +00001985 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001986{
1987 lostFraction lost_fraction;
1988 integerPart *significand;
1989 unsigned int bitPos, partsCount;
1990 const char *dot, *firstSignificantDigit;
1991
1992 zeroSignificand();
1993 exponent = 0;
1994 category = fcNormal;
1995
1996 significand = significandParts();
1997 partsCount = partCount();
1998 bitPos = partsCount * integerPartWidth;
1999
Neil Booth33d4c922007-10-07 08:51:21 +00002000 /* Skip leading zeroes and any (hexa)decimal point. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002001 p = skipLeadingZeroesAndAnyDot(p, &dot);
2002 firstSignificantDigit = p;
2003
2004 for(;;) {
2005 integerPart hex_value;
2006
2007 if(*p == '.') {
2008 assert(dot == 0);
2009 dot = p++;
2010 }
2011
2012 hex_value = hexDigitValue(*p);
2013 if(hex_value == -1U) {
2014 lost_fraction = lfExactlyZero;
2015 break;
2016 }
2017
2018 p++;
2019
2020 /* Store the number whilst 4-bit nibbles remain. */
2021 if(bitPos) {
2022 bitPos -= 4;
2023 hex_value <<= bitPos % integerPartWidth;
2024 significand[bitPos / integerPartWidth] |= hex_value;
2025 } else {
2026 lost_fraction = trailingHexadecimalFraction(p, hex_value);
2027 while(hexDigitValue(*p) != -1U)
Neil Booth4f881702007-09-26 21:33:42 +00002028 p++;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002029 break;
2030 }
2031 }
2032
2033 /* Hex floats require an exponent but not a hexadecimal point. */
2034 assert(*p == 'p' || *p == 'P');
2035
2036 /* Ignore the exponent if we are zero. */
2037 if(p != firstSignificantDigit) {
2038 int expAdjustment;
2039
2040 /* Implicit hexadecimal point? */
2041 if(!dot)
2042 dot = p;
2043
2044 /* Calculate the exponent adjustment implicit in the number of
2045 significant digits. */
2046 expAdjustment = dot - firstSignificantDigit;
2047 if(expAdjustment < 0)
2048 expAdjustment++;
2049 expAdjustment = expAdjustment * 4 - 1;
2050
2051 /* Adjust for writing the significand starting at the most
2052 significant nibble. */
2053 expAdjustment += semantics->precision;
2054 expAdjustment -= partsCount * integerPartWidth;
2055
2056 /* Adjust for the given exponent. */
2057 exponent = totalExponent(p, expAdjustment);
2058 }
2059
2060 return normalize(rounding_mode, lost_fraction);
2061}
2062
2063APFloat::opStatus
Neil Booth96c74712007-10-12 16:02:31 +00002064APFloat::roundSignificandWithExponent(const integerPart *decSigParts,
2065 unsigned sigPartCount, int exp,
2066 roundingMode rounding_mode)
2067{
2068 unsigned int parts, pow5PartCount;
Neil Boothcaf19d72007-10-14 10:29:28 +00002069 fltSemantics calcSemantics = { 32767, -32767, 0, true };
Neil Booth96c74712007-10-12 16:02:31 +00002070 integerPart pow5Parts[maxPowerOfFiveParts];
2071 bool isNearest;
2072
2073 isNearest = (rounding_mode == rmNearestTiesToEven
2074 || rounding_mode == rmNearestTiesToAway);
2075
2076 parts = partCountForBits(semantics->precision + 11);
2077
2078 /* Calculate pow(5, abs(exp)). */
2079 pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp);
2080
2081 for (;; parts *= 2) {
2082 opStatus sigStatus, powStatus;
2083 unsigned int excessPrecision, truncatedBits;
2084
2085 calcSemantics.precision = parts * integerPartWidth - 1;
2086 excessPrecision = calcSemantics.precision - semantics->precision;
2087 truncatedBits = excessPrecision;
2088
2089 APFloat decSig(calcSemantics, fcZero, sign);
2090 APFloat pow5(calcSemantics, fcZero, false);
2091
2092 sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount,
2093 rmNearestTiesToEven);
2094 powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
2095 rmNearestTiesToEven);
2096 /* Add exp, as 10^n = 5^n * 2^n. */
2097 decSig.exponent += exp;
2098
2099 lostFraction calcLostFraction;
2100 integerPart HUerr, HUdistance, powHUerr;
2101
2102 if (exp >= 0) {
2103 /* multiplySignificand leaves the precision-th bit set to 1. */
2104 calcLostFraction = decSig.multiplySignificand(pow5, NULL);
2105 powHUerr = powStatus != opOK;
2106 } else {
2107 calcLostFraction = decSig.divideSignificand(pow5);
2108 /* Denormal numbers have less precision. */
2109 if (decSig.exponent < semantics->minExponent) {
2110 excessPrecision += (semantics->minExponent - decSig.exponent);
2111 truncatedBits = excessPrecision;
2112 if (excessPrecision > calcSemantics.precision)
2113 excessPrecision = calcSemantics.precision;
2114 }
2115 /* Extra half-ulp lost in reciprocal of exponent. */
Neil Boothd1a23d52007-10-13 03:34:08 +00002116 powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0: 2;
Neil Booth96c74712007-10-12 16:02:31 +00002117 }
2118
2119 /* Both multiplySignificand and divideSignificand return the
2120 result with the integer bit set. */
2121 assert (APInt::tcExtractBit
2122 (decSig.significandParts(), calcSemantics.precision - 1) == 1);
2123
2124 HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK,
2125 powHUerr);
2126 HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
2127 excessPrecision, isNearest);
2128
2129 /* Are we guaranteed to round correctly if we truncate? */
2130 if (HUdistance >= HUerr) {
2131 APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
2132 calcSemantics.precision - excessPrecision,
2133 excessPrecision);
2134 /* Take the exponent of decSig. If we tcExtract-ed less bits
2135 above we must adjust our exponent to compensate for the
2136 implicit right shift. */
2137 exponent = (decSig.exponent + semantics->precision
2138 - (calcSemantics.precision - excessPrecision));
2139 calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(),
2140 decSig.partCount(),
2141 truncatedBits);
2142 return normalize(rounding_mode, calcLostFraction);
2143 }
2144 }
2145}
2146
2147APFloat::opStatus
2148APFloat::convertFromDecimalString(const char *p, roundingMode rounding_mode)
2149{
Neil Booth1870f292007-10-14 10:16:12 +00002150 decimalInfo D;
Neil Booth96c74712007-10-12 16:02:31 +00002151 opStatus fs;
2152
Neil Booth1870f292007-10-14 10:16:12 +00002153 /* Scan the text. */
2154 interpretDecimal(p, &D);
Neil Booth96c74712007-10-12 16:02:31 +00002155
Neil Booth686700e2007-10-15 15:00:55 +00002156 /* Handle the quick cases. First the case of no significant digits,
2157 i.e. zero, and then exponents that are obviously too large or too
2158 small. Writing L for log 10 / log 2, a number d.ddddd*10^exp
2159 definitely overflows if
2160
2161 (exp - 1) * L >= maxExponent
2162
2163 and definitely underflows to zero where
2164
2165 (exp + 1) * L <= minExponent - precision
2166
2167 With integer arithmetic the tightest bounds for L are
2168
2169 93/28 < L < 196/59 [ numerator <= 256 ]
2170 42039/12655 < L < 28738/8651 [ numerator <= 65536 ]
2171 */
2172
Neil Boothcc233592007-12-05 13:06:04 +00002173 if (decDigitValue(*D.firstSigDigit) >= 10U) {
Neil Booth96c74712007-10-12 16:02:31 +00002174 category = fcZero;
2175 fs = opOK;
Neil Booth686700e2007-10-15 15:00:55 +00002176 } else if ((D.normalizedExponent + 1) * 28738
2177 <= 8651 * (semantics->minExponent - (int) semantics->precision)) {
2178 /* Underflow to zero and round. */
2179 zeroSignificand();
2180 fs = normalize(rounding_mode, lfLessThanHalf);
2181 } else if ((D.normalizedExponent - 1) * 42039
2182 >= 12655 * semantics->maxExponent) {
2183 /* Overflow and round. */
2184 fs = handleOverflow(rounding_mode);
Neil Booth96c74712007-10-12 16:02:31 +00002185 } else {
Neil Booth1870f292007-10-14 10:16:12 +00002186 integerPart *decSignificand;
2187 unsigned int partCount;
Neil Booth96c74712007-10-12 16:02:31 +00002188
Neil Booth1870f292007-10-14 10:16:12 +00002189 /* A tight upper bound on number of bits required to hold an
Neil Booth686700e2007-10-15 15:00:55 +00002190 N-digit decimal integer is N * 196 / 59. Allocate enough space
Neil Booth1870f292007-10-14 10:16:12 +00002191 to hold the full significand, and an extra part required by
2192 tcMultiplyPart. */
2193 partCount = (D.lastSigDigit - D.firstSigDigit) + 1;
Neil Booth686700e2007-10-15 15:00:55 +00002194 partCount = partCountForBits(1 + 196 * partCount / 59);
Neil Booth1870f292007-10-14 10:16:12 +00002195 decSignificand = new integerPart[partCount + 1];
2196 partCount = 0;
Neil Booth96c74712007-10-12 16:02:31 +00002197
Neil Booth1870f292007-10-14 10:16:12 +00002198 /* Convert to binary efficiently - we do almost all multiplication
2199 in an integerPart. When this would overflow do we do a single
2200 bignum multiplication, and then revert again to multiplication
2201 in an integerPart. */
2202 do {
2203 integerPart decValue, val, multiplier;
2204
2205 val = 0;
2206 multiplier = 1;
2207
2208 do {
2209 if (*p == '.')
2210 p++;
2211
2212 decValue = decDigitValue(*p++);
2213 multiplier *= 10;
2214 val = val * 10 + decValue;
2215 /* The maximum number that can be multiplied by ten with any
2216 digit added without overflowing an integerPart. */
2217 } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
2218
2219 /* Multiply out the current part. */
2220 APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
2221 partCount, partCount + 1, false);
2222
2223 /* If we used another part (likely but not guaranteed), increase
2224 the count. */
2225 if (decSignificand[partCount])
2226 partCount++;
2227 } while (p <= D.lastSigDigit);
Neil Booth96c74712007-10-12 16:02:31 +00002228
Neil Booth43a4b282007-11-01 22:51:07 +00002229 category = fcNormal;
Neil Booth96c74712007-10-12 16:02:31 +00002230 fs = roundSignificandWithExponent(decSignificand, partCount,
Neil Booth1870f292007-10-14 10:16:12 +00002231 D.exponent, rounding_mode);
Neil Booth96c74712007-10-12 16:02:31 +00002232
Neil Booth1870f292007-10-14 10:16:12 +00002233 delete [] decSignificand;
2234 }
Neil Booth96c74712007-10-12 16:02:31 +00002235
2236 return fs;
2237}
2238
2239APFloat::opStatus
Neil Booth4f881702007-09-26 21:33:42 +00002240APFloat::convertFromString(const char *p, roundingMode rounding_mode)
2241{
Neil Boothcaf19d72007-10-14 10:29:28 +00002242 assertArithmeticOK(*semantics);
2243
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002244 /* Handle a leading minus sign. */
2245 if(*p == '-')
2246 sign = 1, p++;
2247 else
2248 sign = 0;
2249
2250 if(p[0] == '0' && (p[1] == 'x' || p[1] == 'X'))
2251 return convertFromHexadecimalString(p + 2, rounding_mode);
Neil Booth96c74712007-10-12 16:02:31 +00002252 else
2253 return convertFromDecimalString(p, rounding_mode);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002254}
Dale Johannesen343e7702007-08-24 00:56:33 +00002255
Neil Bootha30b0ee2007-10-03 22:26:02 +00002256/* Write out a hexadecimal representation of the floating point value
2257 to DST, which must be of sufficient size, in the C99 form
2258 [-]0xh.hhhhp[+-]d. Return the number of characters written,
2259 excluding the terminating NUL.
2260
2261 If UPPERCASE, the output is in upper case, otherwise in lower case.
2262
2263 HEXDIGITS digits appear altogether, rounding the value if
2264 necessary. If HEXDIGITS is 0, the minimal precision to display the
2265 number precisely is used instead. If nothing would appear after
2266 the decimal point it is suppressed.
2267
2268 The decimal exponent is always printed and has at least one digit.
2269 Zero values display an exponent of zero. Infinities and NaNs
2270 appear as "infinity" or "nan" respectively.
2271
2272 The above rules are as specified by C99. There is ambiguity about
2273 what the leading hexadecimal digit should be. This implementation
2274 uses whatever is necessary so that the exponent is displayed as
2275 stored. This implies the exponent will fall within the IEEE format
2276 range, and the leading hexadecimal digit will be 0 (for denormals),
2277 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
2278 any other digits zero).
2279*/
2280unsigned int
2281APFloat::convertToHexString(char *dst, unsigned int hexDigits,
2282 bool upperCase, roundingMode rounding_mode) const
2283{
2284 char *p;
2285
Neil Boothcaf19d72007-10-14 10:29:28 +00002286 assertArithmeticOK(*semantics);
2287
Neil Bootha30b0ee2007-10-03 22:26:02 +00002288 p = dst;
2289 if (sign)
2290 *dst++ = '-';
2291
2292 switch (category) {
2293 case fcInfinity:
2294 memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
2295 dst += sizeof infinityL - 1;
2296 break;
2297
2298 case fcNaN:
2299 memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
2300 dst += sizeof NaNU - 1;
2301 break;
2302
2303 case fcZero:
2304 *dst++ = '0';
2305 *dst++ = upperCase ? 'X': 'x';
2306 *dst++ = '0';
2307 if (hexDigits > 1) {
2308 *dst++ = '.';
2309 memset (dst, '0', hexDigits - 1);
2310 dst += hexDigits - 1;
2311 }
2312 *dst++ = upperCase ? 'P': 'p';
2313 *dst++ = '0';
2314 break;
2315
2316 case fcNormal:
2317 dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
2318 break;
2319 }
2320
2321 *dst = 0;
2322
2323 return dst - p;
2324}
2325
2326/* Does the hard work of outputting the correctly rounded hexadecimal
2327 form of a normal floating point number with the specified number of
2328 hexadecimal digits. If HEXDIGITS is zero the minimum number of
2329 digits necessary to print the value precisely is output. */
2330char *
2331APFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
2332 bool upperCase,
2333 roundingMode rounding_mode) const
2334{
2335 unsigned int count, valueBits, shift, partsCount, outputDigits;
2336 const char *hexDigitChars;
2337 const integerPart *significand;
2338 char *p;
2339 bool roundUp;
2340
2341 *dst++ = '0';
2342 *dst++ = upperCase ? 'X': 'x';
2343
2344 roundUp = false;
2345 hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower;
2346
2347 significand = significandParts();
2348 partsCount = partCount();
2349
2350 /* +3 because the first digit only uses the single integer bit, so
2351 we have 3 virtual zero most-significant-bits. */
2352 valueBits = semantics->precision + 3;
2353 shift = integerPartWidth - valueBits % integerPartWidth;
2354
2355 /* The natural number of digits required ignoring trailing
2356 insignificant zeroes. */
2357 outputDigits = (valueBits - significandLSB () + 3) / 4;
2358
2359 /* hexDigits of zero means use the required number for the
2360 precision. Otherwise, see if we are truncating. If we are,
Neil Booth978661d2007-10-06 00:24:48 +00002361 find out if we need to round away from zero. */
Neil Bootha30b0ee2007-10-03 22:26:02 +00002362 if (hexDigits) {
2363 if (hexDigits < outputDigits) {
2364 /* We are dropping non-zero bits, so need to check how to round.
2365 "bits" is the number of dropped bits. */
2366 unsigned int bits;
2367 lostFraction fraction;
2368
2369 bits = valueBits - hexDigits * 4;
2370 fraction = lostFractionThroughTruncation (significand, partsCount, bits);
2371 roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
2372 }
2373 outputDigits = hexDigits;
2374 }
2375
2376 /* Write the digits consecutively, and start writing in the location
2377 of the hexadecimal point. We move the most significant digit
2378 left and add the hexadecimal point later. */
2379 p = ++dst;
2380
2381 count = (valueBits + integerPartWidth - 1) / integerPartWidth;
2382
2383 while (outputDigits && count) {
2384 integerPart part;
2385
2386 /* Put the most significant integerPartWidth bits in "part". */
2387 if (--count == partsCount)
2388 part = 0; /* An imaginary higher zero part. */
2389 else
2390 part = significand[count] << shift;
2391
2392 if (count && shift)
2393 part |= significand[count - 1] >> (integerPartWidth - shift);
2394
2395 /* Convert as much of "part" to hexdigits as we can. */
2396 unsigned int curDigits = integerPartWidth / 4;
2397
2398 if (curDigits > outputDigits)
2399 curDigits = outputDigits;
2400 dst += partAsHex (dst, part, curDigits, hexDigitChars);
2401 outputDigits -= curDigits;
2402 }
2403
2404 if (roundUp) {
2405 char *q = dst;
2406
2407 /* Note that hexDigitChars has a trailing '0'. */
2408 do {
2409 q--;
2410 *q = hexDigitChars[hexDigitValue (*q) + 1];
Neil Booth978661d2007-10-06 00:24:48 +00002411 } while (*q == '0');
2412 assert (q >= p);
Neil Bootha30b0ee2007-10-03 22:26:02 +00002413 } else {
2414 /* Add trailing zeroes. */
2415 memset (dst, '0', outputDigits);
2416 dst += outputDigits;
2417 }
2418
2419 /* Move the most significant digit to before the point, and if there
2420 is something after the decimal point add it. This must come
2421 after rounding above. */
2422 p[-1] = p[0];
2423 if (dst -1 == p)
2424 dst--;
2425 else
2426 p[0] = '.';
2427
2428 /* Finally output the exponent. */
2429 *dst++ = upperCase ? 'P': 'p';
2430
Neil Booth92f7e8d2007-10-06 07:29:25 +00002431 return writeSignedDecimal (dst, exponent);
Neil Bootha30b0ee2007-10-03 22:26:02 +00002432}
2433
Dale Johannesen343e7702007-08-24 00:56:33 +00002434// For good performance it is desirable for different APFloats
2435// to produce different integers.
2436uint32_t
Neil Booth4f881702007-09-26 21:33:42 +00002437APFloat::getHashValue() const
2438{
Dale Johannesen343e7702007-08-24 00:56:33 +00002439 if (category==fcZero) return sign<<8 | semantics->precision ;
2440 else if (category==fcInfinity) return sign<<9 | semantics->precision;
Dale Johanneseneaf08942007-08-31 04:03:46 +00002441 else if (category==fcNaN) return 1<<10 | semantics->precision;
Dale Johannesen343e7702007-08-24 00:56:33 +00002442 else {
2443 uint32_t hash = sign<<11 | semantics->precision | exponent<<12;
2444 const integerPart* p = significandParts();
2445 for (int i=partCount(); i>0; i--, p++)
2446 hash ^= ((uint32_t)*p) ^ (*p)>>32;
2447 return hash;
2448 }
2449}
2450
2451// Conversion from APFloat to/from host float/double. It may eventually be
2452// possible to eliminate these and have everybody deal with APFloats, but that
2453// will take a while. This approach will not easily extend to long double.
Dale Johannesena72a5a02007-09-20 23:47:58 +00002454// Current implementation requires integerPartWidth==64, which is correct at
2455// the moment but could be made more general.
Dale Johannesen343e7702007-08-24 00:56:33 +00002456
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002457// Denormals have exponent minExponent in APFloat, but minExponent-1 in
Dale Johannesena72a5a02007-09-20 23:47:58 +00002458// the actual IEEE respresentations. We compensate for that here.
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002459
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002460APInt
Neil Booth4f881702007-09-26 21:33:42 +00002461APFloat::convertF80LongDoubleAPFloatToAPInt() const
2462{
Dan Gohmanb10abe12008-01-29 12:08:20 +00002463 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended);
Dale Johannesena72a5a02007-09-20 23:47:58 +00002464 assert (partCount()==2);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002465
2466 uint64_t myexponent, mysignificand;
2467
2468 if (category==fcNormal) {
2469 myexponent = exponent+16383; //bias
Dale Johannesena72a5a02007-09-20 23:47:58 +00002470 mysignificand = significandParts()[0];
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002471 if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
2472 myexponent = 0; // denormal
2473 } else if (category==fcZero) {
2474 myexponent = 0;
2475 mysignificand = 0;
2476 } else if (category==fcInfinity) {
2477 myexponent = 0x7fff;
2478 mysignificand = 0x8000000000000000ULL;
Chris Lattnera11ef822007-10-06 06:13:42 +00002479 } else {
2480 assert(category == fcNaN && "Unknown category");
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002481 myexponent = 0x7fff;
Dale Johannesena72a5a02007-09-20 23:47:58 +00002482 mysignificand = significandParts()[0];
Chris Lattnera11ef822007-10-06 06:13:42 +00002483 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002484
2485 uint64_t words[2];
Neil Booth4f881702007-09-26 21:33:42 +00002486 words[0] = (((uint64_t)sign & 1) << 63) |
2487 ((myexponent & 0x7fff) << 48) |
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002488 ((mysignificand >>16) & 0xffffffffffffLL);
2489 words[1] = mysignificand & 0xffff;
Chris Lattnera11ef822007-10-06 06:13:42 +00002490 return APInt(80, 2, words);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002491}
2492
2493APInt
Dale Johannesena471c2e2007-10-11 18:07:22 +00002494APFloat::convertPPCDoubleDoubleAPFloatToAPInt() const
2495{
Dan Gohmanb10abe12008-01-29 12:08:20 +00002496 assert(semantics == (const llvm::fltSemantics*)&PPCDoubleDouble);
Dale Johannesena471c2e2007-10-11 18:07:22 +00002497 assert (partCount()==2);
2498
2499 uint64_t myexponent, mysignificand, myexponent2, mysignificand2;
2500
2501 if (category==fcNormal) {
2502 myexponent = exponent + 1023; //bias
2503 myexponent2 = exponent2 + 1023;
2504 mysignificand = significandParts()[0];
2505 mysignificand2 = significandParts()[1];
2506 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2507 myexponent = 0; // denormal
2508 if (myexponent2==1 && !(mysignificand2 & 0x10000000000000LL))
2509 myexponent2 = 0; // denormal
2510 } else if (category==fcZero) {
2511 myexponent = 0;
2512 mysignificand = 0;
2513 myexponent2 = 0;
2514 mysignificand2 = 0;
2515 } else if (category==fcInfinity) {
2516 myexponent = 0x7ff;
2517 myexponent2 = 0;
2518 mysignificand = 0;
2519 mysignificand2 = 0;
2520 } else {
2521 assert(category == fcNaN && "Unknown category");
2522 myexponent = 0x7ff;
2523 mysignificand = significandParts()[0];
2524 myexponent2 = exponent2;
2525 mysignificand2 = significandParts()[1];
2526 }
2527
2528 uint64_t words[2];
2529 words[0] = (((uint64_t)sign & 1) << 63) |
2530 ((myexponent & 0x7ff) << 52) |
2531 (mysignificand & 0xfffffffffffffLL);
2532 words[1] = (((uint64_t)sign2 & 1) << 63) |
2533 ((myexponent2 & 0x7ff) << 52) |
2534 (mysignificand2 & 0xfffffffffffffLL);
2535 return APInt(128, 2, words);
2536}
2537
2538APInt
Neil Booth4f881702007-09-26 21:33:42 +00002539APFloat::convertDoubleAPFloatToAPInt() const
2540{
Dan Gohmancb648f92007-09-14 20:08:19 +00002541 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble);
Dale Johannesen343e7702007-08-24 00:56:33 +00002542 assert (partCount()==1);
2543
Dale Johanneseneaf08942007-08-31 04:03:46 +00002544 uint64_t myexponent, mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00002545
2546 if (category==fcNormal) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002547 myexponent = exponent+1023; //bias
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002548 mysignificand = *significandParts();
2549 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2550 myexponent = 0; // denormal
Dale Johannesen343e7702007-08-24 00:56:33 +00002551 } else if (category==fcZero) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002552 myexponent = 0;
2553 mysignificand = 0;
2554 } else if (category==fcInfinity) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002555 myexponent = 0x7ff;
2556 mysignificand = 0;
Chris Lattnera11ef822007-10-06 06:13:42 +00002557 } else {
2558 assert(category == fcNaN && "Unknown category!");
Dale Johannesen343e7702007-08-24 00:56:33 +00002559 myexponent = 0x7ff;
Dale Johanneseneaf08942007-08-31 04:03:46 +00002560 mysignificand = *significandParts();
Chris Lattnera11ef822007-10-06 06:13:42 +00002561 }
Dale Johannesen343e7702007-08-24 00:56:33 +00002562
Chris Lattnera11ef822007-10-06 06:13:42 +00002563 return APInt(64, (((((uint64_t)sign & 1) << 63) |
2564 ((myexponent & 0x7ff) << 52) |
2565 (mysignificand & 0xfffffffffffffLL))));
Dale Johannesen343e7702007-08-24 00:56:33 +00002566}
2567
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002568APInt
Neil Booth4f881702007-09-26 21:33:42 +00002569APFloat::convertFloatAPFloatToAPInt() const
2570{
Dan Gohmancb648f92007-09-14 20:08:19 +00002571 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle);
Dale Johannesen343e7702007-08-24 00:56:33 +00002572 assert (partCount()==1);
Neil Booth4f881702007-09-26 21:33:42 +00002573
Dale Johanneseneaf08942007-08-31 04:03:46 +00002574 uint32_t myexponent, mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00002575
2576 if (category==fcNormal) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002577 myexponent = exponent+127; //bias
2578 mysignificand = *significandParts();
Dale Johannesend0763b92007-11-17 01:02:27 +00002579 if (myexponent == 1 && !(mysignificand & 0x800000))
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002580 myexponent = 0; // denormal
Dale Johannesen343e7702007-08-24 00:56:33 +00002581 } else if (category==fcZero) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002582 myexponent = 0;
2583 mysignificand = 0;
2584 } else if (category==fcInfinity) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002585 myexponent = 0xff;
2586 mysignificand = 0;
Chris Lattnera11ef822007-10-06 06:13:42 +00002587 } else {
2588 assert(category == fcNaN && "Unknown category!");
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002589 myexponent = 0xff;
Dale Johanneseneaf08942007-08-31 04:03:46 +00002590 mysignificand = *significandParts();
Chris Lattnera11ef822007-10-06 06:13:42 +00002591 }
Dale Johannesen343e7702007-08-24 00:56:33 +00002592
Chris Lattnera11ef822007-10-06 06:13:42 +00002593 return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) |
2594 (mysignificand & 0x7fffff)));
Dale Johannesen343e7702007-08-24 00:56:33 +00002595}
2596
Dale Johannesena471c2e2007-10-11 18:07:22 +00002597// This function creates an APInt that is just a bit map of the floating
2598// point constant as it would appear in memory. It is not a conversion,
2599// and treating the result as a normal integer is unlikely to be useful.
2600
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002601APInt
Neil Booth4f881702007-09-26 21:33:42 +00002602APFloat::convertToAPInt() const
2603{
Dan Gohmanb10abe12008-01-29 12:08:20 +00002604 if (semantics == (const llvm::fltSemantics*)&IEEEsingle)
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002605 return convertFloatAPFloatToAPInt();
Chris Lattnera11ef822007-10-06 06:13:42 +00002606
Dan Gohmanb10abe12008-01-29 12:08:20 +00002607 if (semantics == (const llvm::fltSemantics*)&IEEEdouble)
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002608 return convertDoubleAPFloatToAPInt();
Neil Booth4f881702007-09-26 21:33:42 +00002609
Dan Gohmanb10abe12008-01-29 12:08:20 +00002610 if (semantics == (const llvm::fltSemantics*)&PPCDoubleDouble)
Dale Johannesena471c2e2007-10-11 18:07:22 +00002611 return convertPPCDoubleDoubleAPFloatToAPInt();
2612
Dan Gohmanb10abe12008-01-29 12:08:20 +00002613 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended &&
Chris Lattnera11ef822007-10-06 06:13:42 +00002614 "unknown format!");
2615 return convertF80LongDoubleAPFloatToAPInt();
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002616}
2617
Neil Booth4f881702007-09-26 21:33:42 +00002618float
2619APFloat::convertToFloat() const
2620{
Dan Gohmanb10abe12008-01-29 12:08:20 +00002621 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002622 APInt api = convertToAPInt();
2623 return api.bitsToFloat();
2624}
2625
Neil Booth4f881702007-09-26 21:33:42 +00002626double
2627APFloat::convertToDouble() const
2628{
Dan Gohmanb10abe12008-01-29 12:08:20 +00002629 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002630 APInt api = convertToAPInt();
2631 return api.bitsToDouble();
2632}
2633
2634/// Integer bit is explicit in this format. Current Intel book does not
2635/// define meaning of:
2636/// exponent = all 1's, integer bit not set.
2637/// exponent = 0, integer bit set. (formerly "psuedodenormals")
2638/// exponent!=0 nor all 1's, integer bit not set. (formerly "unnormals")
2639void
Neil Booth4f881702007-09-26 21:33:42 +00002640APFloat::initFromF80LongDoubleAPInt(const APInt &api)
2641{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002642 assert(api.getBitWidth()==80);
2643 uint64_t i1 = api.getRawData()[0];
2644 uint64_t i2 = api.getRawData()[1];
2645 uint64_t myexponent = (i1 >> 48) & 0x7fff;
2646 uint64_t mysignificand = ((i1 << 16) & 0xffffffffffff0000ULL) |
2647 (i2 & 0xffff);
2648
2649 initialize(&APFloat::x87DoubleExtended);
Dale Johannesena72a5a02007-09-20 23:47:58 +00002650 assert(partCount()==2);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002651
2652 sign = i1>>63;
2653 if (myexponent==0 && mysignificand==0) {
2654 // exponent, significand meaningless
2655 category = fcZero;
2656 } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
2657 // exponent, significand meaningless
2658 category = fcInfinity;
2659 } else if (myexponent==0x7fff && mysignificand!=0x8000000000000000ULL) {
2660 // exponent meaningless
2661 category = fcNaN;
Dale Johannesena72a5a02007-09-20 23:47:58 +00002662 significandParts()[0] = mysignificand;
2663 significandParts()[1] = 0;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002664 } else {
2665 category = fcNormal;
2666 exponent = myexponent - 16383;
Dale Johannesena72a5a02007-09-20 23:47:58 +00002667 significandParts()[0] = mysignificand;
2668 significandParts()[1] = 0;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002669 if (myexponent==0) // denormal
2670 exponent = -16382;
Neil Booth4f881702007-09-26 21:33:42 +00002671 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002672}
2673
2674void
Dale Johannesena471c2e2007-10-11 18:07:22 +00002675APFloat::initFromPPCDoubleDoubleAPInt(const APInt &api)
2676{
2677 assert(api.getBitWidth()==128);
2678 uint64_t i1 = api.getRawData()[0];
2679 uint64_t i2 = api.getRawData()[1];
2680 uint64_t myexponent = (i1 >> 52) & 0x7ff;
2681 uint64_t mysignificand = i1 & 0xfffffffffffffLL;
2682 uint64_t myexponent2 = (i2 >> 52) & 0x7ff;
2683 uint64_t mysignificand2 = i2 & 0xfffffffffffffLL;
2684
2685 initialize(&APFloat::PPCDoubleDouble);
2686 assert(partCount()==2);
2687
2688 sign = i1>>63;
2689 sign2 = i2>>63;
2690 if (myexponent==0 && mysignificand==0) {
2691 // exponent, significand meaningless
2692 // exponent2 and significand2 are required to be 0; we don't check
2693 category = fcZero;
2694 } else if (myexponent==0x7ff && mysignificand==0) {
2695 // exponent, significand meaningless
2696 // exponent2 and significand2 are required to be 0; we don't check
2697 category = fcInfinity;
2698 } else if (myexponent==0x7ff && mysignificand!=0) {
2699 // exponent meaningless. So is the whole second word, but keep it
2700 // for determinism.
2701 category = fcNaN;
2702 exponent2 = myexponent2;
2703 significandParts()[0] = mysignificand;
2704 significandParts()[1] = mysignificand2;
2705 } else {
2706 category = fcNormal;
2707 // Note there is no category2; the second word is treated as if it is
2708 // fcNormal, although it might be something else considered by itself.
2709 exponent = myexponent - 1023;
2710 exponent2 = myexponent2 - 1023;
2711 significandParts()[0] = mysignificand;
2712 significandParts()[1] = mysignificand2;
2713 if (myexponent==0) // denormal
2714 exponent = -1022;
2715 else
2716 significandParts()[0] |= 0x10000000000000LL; // integer bit
2717 if (myexponent2==0)
2718 exponent2 = -1022;
2719 else
2720 significandParts()[1] |= 0x10000000000000LL; // integer bit
2721 }
2722}
2723
2724void
Neil Booth4f881702007-09-26 21:33:42 +00002725APFloat::initFromDoubleAPInt(const APInt &api)
2726{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002727 assert(api.getBitWidth()==64);
2728 uint64_t i = *api.getRawData();
Dale Johannesend3b51fd2007-08-24 05:08:11 +00002729 uint64_t myexponent = (i >> 52) & 0x7ff;
2730 uint64_t mysignificand = i & 0xfffffffffffffLL;
2731
Dale Johannesen343e7702007-08-24 00:56:33 +00002732 initialize(&APFloat::IEEEdouble);
Dale Johannesen343e7702007-08-24 00:56:33 +00002733 assert(partCount()==1);
2734
Dale Johanneseneaf08942007-08-31 04:03:46 +00002735 sign = i>>63;
Dale Johannesen343e7702007-08-24 00:56:33 +00002736 if (myexponent==0 && mysignificand==0) {
2737 // exponent, significand meaningless
2738 category = fcZero;
Dale Johannesen343e7702007-08-24 00:56:33 +00002739 } else if (myexponent==0x7ff && mysignificand==0) {
2740 // exponent, significand meaningless
2741 category = fcInfinity;
Dale Johanneseneaf08942007-08-31 04:03:46 +00002742 } else if (myexponent==0x7ff && mysignificand!=0) {
2743 // exponent meaningless
2744 category = fcNaN;
2745 *significandParts() = mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00002746 } else {
Dale Johannesen343e7702007-08-24 00:56:33 +00002747 category = fcNormal;
2748 exponent = myexponent - 1023;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002749 *significandParts() = mysignificand;
2750 if (myexponent==0) // denormal
2751 exponent = -1022;
2752 else
2753 *significandParts() |= 0x10000000000000LL; // integer bit
Neil Booth4f881702007-09-26 21:33:42 +00002754 }
Dale Johannesen343e7702007-08-24 00:56:33 +00002755}
2756
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002757void
Neil Booth4f881702007-09-26 21:33:42 +00002758APFloat::initFromFloatAPInt(const APInt & api)
2759{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002760 assert(api.getBitWidth()==32);
2761 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesend3b51fd2007-08-24 05:08:11 +00002762 uint32_t myexponent = (i >> 23) & 0xff;
2763 uint32_t mysignificand = i & 0x7fffff;
2764
Dale Johannesen343e7702007-08-24 00:56:33 +00002765 initialize(&APFloat::IEEEsingle);
Dale Johannesen343e7702007-08-24 00:56:33 +00002766 assert(partCount()==1);
2767
Dale Johanneseneaf08942007-08-31 04:03:46 +00002768 sign = i >> 31;
Dale Johannesen343e7702007-08-24 00:56:33 +00002769 if (myexponent==0 && mysignificand==0) {
2770 // exponent, significand meaningless
2771 category = fcZero;
Dale Johannesen343e7702007-08-24 00:56:33 +00002772 } else if (myexponent==0xff && mysignificand==0) {
2773 // exponent, significand meaningless
2774 category = fcInfinity;
Dale Johannesen902ff942007-09-25 17:25:00 +00002775 } else if (myexponent==0xff && mysignificand!=0) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002776 // sign, exponent, significand meaningless
Dale Johanneseneaf08942007-08-31 04:03:46 +00002777 category = fcNaN;
2778 *significandParts() = mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00002779 } else {
2780 category = fcNormal;
Dale Johannesen343e7702007-08-24 00:56:33 +00002781 exponent = myexponent - 127; //bias
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002782 *significandParts() = mysignificand;
2783 if (myexponent==0) // denormal
2784 exponent = -126;
2785 else
2786 *significandParts() |= 0x800000; // integer bit
Dale Johannesen343e7702007-08-24 00:56:33 +00002787 }
2788}
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002789
2790/// Treat api as containing the bits of a floating point number. Currently
Dale Johannesena471c2e2007-10-11 18:07:22 +00002791/// we infer the floating point type from the size of the APInt. The
2792/// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful
2793/// when the size is anything else).
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002794void
Dale Johannesena471c2e2007-10-11 18:07:22 +00002795APFloat::initFromAPInt(const APInt& api, bool isIEEE)
Neil Booth4f881702007-09-26 21:33:42 +00002796{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002797 if (api.getBitWidth() == 32)
2798 return initFromFloatAPInt(api);
2799 else if (api.getBitWidth()==64)
2800 return initFromDoubleAPInt(api);
2801 else if (api.getBitWidth()==80)
2802 return initFromF80LongDoubleAPInt(api);
Dale Johannesena471c2e2007-10-11 18:07:22 +00002803 else if (api.getBitWidth()==128 && !isIEEE)
2804 return initFromPPCDoubleDoubleAPInt(api);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002805 else
2806 assert(0);
2807}
2808
Dale Johannesena471c2e2007-10-11 18:07:22 +00002809APFloat::APFloat(const APInt& api, bool isIEEE)
Neil Booth4f881702007-09-26 21:33:42 +00002810{
Dale Johannesena471c2e2007-10-11 18:07:22 +00002811 initFromAPInt(api, isIEEE);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002812}
2813
Neil Booth4f881702007-09-26 21:33:42 +00002814APFloat::APFloat(float f)
2815{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002816 APInt api = APInt(32, 0);
2817 initFromAPInt(api.floatToBits(f));
2818}
2819
Neil Booth4f881702007-09-26 21:33:42 +00002820APFloat::APFloat(double d)
2821{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002822 APInt api = APInt(64, 0);
2823 initFromAPInt(api.doubleToBits(d));
2824}