blob: 8f07bd5fae2df5bd42089ca8308e165b1a423de8 [file] [log] [blame]
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001//===-- APFloat.cpp - Implement APFloat class -----------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Neil Booth and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements a class to represent arbitrary precision floating
11// point values and provide a variety of arithmetic operations on them.
12//
13//===----------------------------------------------------------------------===//
14
15#include <cassert>
Neil Bootha30b0ee2007-10-03 22:26:02 +000016#include <cstring>
Chris Lattnerb39cdde2007-08-20 22:49:32 +000017#include "llvm/ADT/APFloat.h"
Dale Johannesend3b51fd2007-08-24 05:08:11 +000018#include "llvm/Support/MathExtras.h"
Chris Lattnerb39cdde2007-08-20 22:49:32 +000019
20using namespace llvm;
21
22#define convolve(lhs, rhs) ((lhs) * 4 + (rhs))
23
Neil Bootha30b0ee2007-10-03 22:26:02 +000024/* Assumed in hexadecimal significand parsing, and conversion to
25 hexadecimal strings. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +000026COMPILE_TIME_ASSERT(integerPartWidth % 4 == 0);
27
28namespace llvm {
29
30 /* Represents floating point arithmetic semantics. */
31 struct fltSemantics {
32 /* The largest E such that 2^E is representable; this matches the
33 definition of IEEE 754. */
34 exponent_t maxExponent;
35
36 /* The smallest E such that 2^E is a normalized number; this
37 matches the definition of IEEE 754. */
38 exponent_t minExponent;
39
40 /* Number of bits in the significand. This includes the integer
41 bit. */
Neil Booth7a951ca2007-10-12 15:33:27 +000042 unsigned int precision;
Neil Boothcaf19d72007-10-14 10:29:28 +000043
44 /* True if arithmetic is supported. */
45 unsigned int arithmeticOK;
Chris Lattnerb39cdde2007-08-20 22:49:32 +000046 };
47
Neil Boothcaf19d72007-10-14 10:29:28 +000048 const fltSemantics APFloat::IEEEsingle = { 127, -126, 24, true };
49 const fltSemantics APFloat::IEEEdouble = { 1023, -1022, 53, true };
50 const fltSemantics APFloat::IEEEquad = { 16383, -16382, 113, true };
51 const fltSemantics APFloat::x87DoubleExtended = { 16383, -16382, 64, true };
52 const fltSemantics APFloat::Bogus = { 0, 0, 0, true };
Dale Johannesena471c2e2007-10-11 18:07:22 +000053
54 // The PowerPC format consists of two doubles. It does not map cleanly
55 // onto the usual format above. For now only storage of constants of
56 // this type is supported, no arithmetic.
Neil Boothcaf19d72007-10-14 10:29:28 +000057 const fltSemantics APFloat::PPCDoubleDouble = { 1023, -1022, 106, false };
Neil Booth96c74712007-10-12 16:02:31 +000058
59 /* A tight upper bound on number of parts required to hold the value
60 pow(5, power) is
61
62 power * 1024 / (441 * integerPartWidth) + 1
63
64 However, whilst the result may require only this many parts,
65 because we are multiplying two values to get it, the
66 multiplication may require an extra part with the excess part
67 being zero (consider the trivial case of 1 * 1, tcFullMultiply
68 requires two parts to hold the single-part result). So we add an
69 extra one to guarantee enough space whilst multiplying. */
70 const unsigned int maxExponent = 16383;
71 const unsigned int maxPrecision = 113;
72 const unsigned int maxPowerOfFiveExponent = maxExponent + maxPrecision - 1;
73 const unsigned int maxPowerOfFiveParts = 2 + ((maxPowerOfFiveExponent * 1024)
74 / (441 * integerPartWidth));
Chris Lattnerb39cdde2007-08-20 22:49:32 +000075}
76
77/* Put a bunch of private, handy routines in an anonymous namespace. */
78namespace {
79
80 inline unsigned int
81 partCountForBits(unsigned int bits)
82 {
83 return ((bits) + integerPartWidth - 1) / integerPartWidth;
84 }
85
Neil Booth1870f292007-10-14 10:16:12 +000086 /* Returns 0U-9U. Return values >= 10U are not digits. */
87 inline unsigned int
88 decDigitValue(unsigned int c)
Chris Lattnerb39cdde2007-08-20 22:49:32 +000089 {
Neil Booth1870f292007-10-14 10:16:12 +000090 return c - '0';
Chris Lattnerb39cdde2007-08-20 22:49:32 +000091 }
92
93 unsigned int
Neil Booth96c74712007-10-12 16:02:31 +000094 hexDigitValue(unsigned int c)
Chris Lattnerb39cdde2007-08-20 22:49:32 +000095 {
96 unsigned int r;
97
98 r = c - '0';
99 if(r <= 9)
100 return r;
101
102 r = c - 'A';
103 if(r <= 5)
104 return r + 10;
105
106 r = c - 'a';
107 if(r <= 5)
108 return r + 10;
109
110 return -1U;
111 }
112
Neil Boothcaf19d72007-10-14 10:29:28 +0000113 inline void
114 assertArithmeticOK(const llvm::fltSemantics &semantics) {
115 assert(semantics.arithmeticOK
116 && "Compile-time arithmetic does not support these semantics");
117 }
118
Neil Booth1870f292007-10-14 10:16:12 +0000119 /* Return the value of a decimal exponent of the form
120 [+-]ddddddd.
121
122 If the exponent overflows, returns a large exponent with the
123 appropriate sign. */
124 static int
125 readExponent(const char *p)
126 {
127 bool isNegative;
128 unsigned int absExponent;
129 const unsigned int overlargeExponent = 24000; /* FIXME. */
130
131 isNegative = (*p == '-');
132 if (*p == '-' || *p == '+')
133 p++;
134
135 absExponent = decDigitValue(*p++);
136 assert (absExponent < 10U);
137
138 for (;;) {
139 unsigned int value;
140
141 value = decDigitValue(*p);
142 if (value >= 10U)
143 break;
144
145 p++;
146 value += absExponent * 10;
147 if (absExponent >= overlargeExponent) {
148 absExponent = overlargeExponent;
149 break;
150 }
151 absExponent = value;
152 }
153
154 if (isNegative)
155 return -(int) absExponent;
156 else
157 return (int) absExponent;
158 }
159
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000160 /* This is ugly and needs cleaning up, but I don't immediately see
161 how whilst remaining safe. */
162 static int
163 totalExponent(const char *p, int exponentAdjustment)
164 {
165 integerPart unsignedExponent;
166 bool negative, overflow;
167 long exponent;
168
169 /* Move past the exponent letter and sign to the digits. */
170 p++;
171 negative = *p == '-';
172 if(*p == '-' || *p == '+')
173 p++;
174
175 unsignedExponent = 0;
176 overflow = false;
177 for(;;) {
178 unsigned int value;
179
Neil Booth1870f292007-10-14 10:16:12 +0000180 value = decDigitValue(*p);
181 if(value >= 10U)
Neil Booth4f881702007-09-26 21:33:42 +0000182 break;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000183
184 p++;
185 unsignedExponent = unsignedExponent * 10 + value;
186 if(unsignedExponent > 65535)
Neil Booth4f881702007-09-26 21:33:42 +0000187 overflow = true;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000188 }
189
190 if(exponentAdjustment > 65535 || exponentAdjustment < -65536)
191 overflow = true;
192
193 if(!overflow) {
194 exponent = unsignedExponent;
195 if(negative)
Neil Booth4f881702007-09-26 21:33:42 +0000196 exponent = -exponent;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000197 exponent += exponentAdjustment;
198 if(exponent > 65535 || exponent < -65536)
Neil Booth4f881702007-09-26 21:33:42 +0000199 overflow = true;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000200 }
201
202 if(overflow)
203 exponent = negative ? -65536: 65535;
204
205 return exponent;
206 }
207
208 const char *
209 skipLeadingZeroesAndAnyDot(const char *p, const char **dot)
210 {
211 *dot = 0;
212 while(*p == '0')
213 p++;
214
215 if(*p == '.') {
216 *dot = p++;
217 while(*p == '0')
Neil Booth4f881702007-09-26 21:33:42 +0000218 p++;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000219 }
220
221 return p;
222 }
223
Neil Booth1870f292007-10-14 10:16:12 +0000224 /* Given a normal decimal floating point number of the form
225
226 dddd.dddd[eE][+-]ddd
227
228 where the decimal point and exponent are optional, fill out the
229 structure D. If the value is zero, V->firstSigDigit
230 points to a zero, and the return exponent is zero. */
231 struct decimalInfo {
232 const char *firstSigDigit;
233 const char *lastSigDigit;
234 int exponent;
235 };
236
237 void
238 interpretDecimal(const char *p, decimalInfo *D)
239 {
240 const char *dot;
241
242 p = skipLeadingZeroesAndAnyDot (p, &dot);
243
244 D->firstSigDigit = p;
245 D->exponent = 0;
246
247 for (;;) {
248 if (*p == '.') {
249 assert(dot == 0);
250 dot = p++;
251 }
252 if (decDigitValue(*p) >= 10U)
253 break;
254 p++;
255 }
256
257 /* If number is all zerooes accept any exponent. */
258 if (p != D->firstSigDigit) {
259 if (*p == 'e' || *p == 'E')
260 D->exponent = readExponent(p + 1);
261
262 /* Implied decimal point? */
263 if (!dot)
264 dot = p;
265
266 /* Drop insignificant trailing zeroes. */
267 do
268 do
269 p--;
270 while (*p == '0');
271 while (*p == '.');
272
273 /* Adjust the specified exponent for any decimal point. */
274 D->exponent += (dot - p) - (dot > p);
275 }
276
277 D->lastSigDigit = p;
278 }
279
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000280 /* Return the trailing fraction of a hexadecimal number.
281 DIGITVALUE is the first hex digit of the fraction, P points to
282 the next digit. */
283 lostFraction
284 trailingHexadecimalFraction(const char *p, unsigned int digitValue)
285 {
286 unsigned int hexDigit;
287
288 /* If the first trailing digit isn't 0 or 8 we can work out the
289 fraction immediately. */
290 if(digitValue > 8)
291 return lfMoreThanHalf;
292 else if(digitValue < 8 && digitValue > 0)
293 return lfLessThanHalf;
294
295 /* Otherwise we need to find the first non-zero digit. */
296 while(*p == '0')
297 p++;
298
299 hexDigit = hexDigitValue(*p);
300
301 /* If we ran off the end it is exactly zero or one-half, otherwise
302 a little more. */
303 if(hexDigit == -1U)
304 return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
305 else
306 return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf;
307 }
308
Neil Boothb7dea4c2007-10-03 15:16:41 +0000309 /* Return the fraction lost were a bignum truncated losing the least
310 significant BITS bits. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000311 lostFraction
Neil Bootha30b0ee2007-10-03 22:26:02 +0000312 lostFractionThroughTruncation(const integerPart *parts,
Neil Booth4f881702007-09-26 21:33:42 +0000313 unsigned int partCount,
314 unsigned int bits)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000315 {
316 unsigned int lsb;
317
318 lsb = APInt::tcLSB(parts, partCount);
319
320 /* Note this is guaranteed true if bits == 0, or LSB == -1U. */
321 if(bits <= lsb)
322 return lfExactlyZero;
323 if(bits == lsb + 1)
324 return lfExactlyHalf;
325 if(bits <= partCount * integerPartWidth
326 && APInt::tcExtractBit(parts, bits - 1))
327 return lfMoreThanHalf;
328
329 return lfLessThanHalf;
330 }
331
332 /* Shift DST right BITS bits noting lost fraction. */
333 lostFraction
334 shiftRight(integerPart *dst, unsigned int parts, unsigned int bits)
335 {
336 lostFraction lost_fraction;
337
338 lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
339
340 APInt::tcShiftRight(dst, parts, bits);
341
342 return lost_fraction;
343 }
Neil Bootha30b0ee2007-10-03 22:26:02 +0000344
Neil Booth33d4c922007-10-07 08:51:21 +0000345 /* Combine the effect of two lost fractions. */
346 lostFraction
347 combineLostFractions(lostFraction moreSignificant,
348 lostFraction lessSignificant)
349 {
350 if(lessSignificant != lfExactlyZero) {
351 if(moreSignificant == lfExactlyZero)
352 moreSignificant = lfLessThanHalf;
353 else if(moreSignificant == lfExactlyHalf)
354 moreSignificant = lfMoreThanHalf;
355 }
356
357 return moreSignificant;
358 }
Neil Bootha30b0ee2007-10-03 22:26:02 +0000359
Neil Booth96c74712007-10-12 16:02:31 +0000360 /* The error from the true value, in half-ulps, on multiplying two
361 floating point numbers, which differ from the value they
362 approximate by at most HUE1 and HUE2 half-ulps, is strictly less
363 than the returned value.
364
365 See "How to Read Floating Point Numbers Accurately" by William D
366 Clinger. */
367 unsigned int
368 HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
369 {
370 assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
371
372 if (HUerr1 + HUerr2 == 0)
373 return inexactMultiply * 2; /* <= inexactMultiply half-ulps. */
374 else
375 return inexactMultiply + 2 * (HUerr1 + HUerr2);
376 }
377
378 /* The number of ulps from the boundary (zero, or half if ISNEAREST)
379 when the least significant BITS are truncated. BITS cannot be
380 zero. */
381 integerPart
382 ulpsFromBoundary(const integerPart *parts, unsigned int bits, bool isNearest)
383 {
384 unsigned int count, partBits;
385 integerPart part, boundary;
386
387 assert (bits != 0);
388
389 bits--;
390 count = bits / integerPartWidth;
391 partBits = bits % integerPartWidth + 1;
392
393 part = parts[count] & (~(integerPart) 0 >> (integerPartWidth - partBits));
394
395 if (isNearest)
396 boundary = (integerPart) 1 << (partBits - 1);
397 else
398 boundary = 0;
399
400 if (count == 0) {
401 if (part - boundary <= boundary - part)
402 return part - boundary;
403 else
404 return boundary - part;
405 }
406
407 if (part == boundary) {
408 while (--count)
409 if (parts[count])
410 return ~(integerPart) 0; /* A lot. */
411
412 return parts[0];
413 } else if (part == boundary - 1) {
414 while (--count)
415 if (~parts[count])
416 return ~(integerPart) 0; /* A lot. */
417
418 return -parts[0];
419 }
420
421 return ~(integerPart) 0; /* A lot. */
422 }
423
424 /* Place pow(5, power) in DST, and return the number of parts used.
425 DST must be at least one part larger than size of the answer. */
426 static unsigned int
427 powerOf5(integerPart *dst, unsigned int power)
428 {
Neil Booth96c74712007-10-12 16:02:31 +0000429 static integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125,
430 15625, 78125 };
431 static integerPart pow5s[maxPowerOfFiveParts * 2 + 5] = { 78125 * 5 };
432 static unsigned int partsCount[16] = { 1 };
433
434 integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5;
435 unsigned int result;
436
437 assert(power <= maxExponent);
438
439 p1 = dst;
440 p2 = scratch;
441
442 *p1 = firstEightPowers[power & 7];
443 power >>= 3;
444
445 result = 1;
446 pow5 = pow5s;
447
448 for (unsigned int n = 0; power; power >>= 1, n++) {
449 unsigned int pc;
450
451 pc = partsCount[n];
452
453 /* Calculate pow(5,pow(2,n+3)) if we haven't yet. */
454 if (pc == 0) {
455 pc = partsCount[n - 1];
456 APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc);
457 pc *= 2;
458 if (pow5[pc - 1] == 0)
459 pc--;
460 partsCount[n] = pc;
461 }
462
463 if (power & 1) {
464 integerPart *tmp;
465
466 APInt::tcFullMultiply(p2, p1, pow5, result, pc);
467 result += pc;
468 if (p2[result - 1] == 0)
469 result--;
470
471 /* Now result is in p1 with partsCount parts and p2 is scratch
472 space. */
473 tmp = p1, p1 = p2, p2 = tmp;
474 }
475
476 pow5 += pc;
477 }
478
479 if (p1 != dst)
480 APInt::tcAssign(dst, p1, result);
481
482 return result;
483 }
484
Neil Bootha30b0ee2007-10-03 22:26:02 +0000485 /* Zero at the end to avoid modular arithmetic when adding one; used
486 when rounding up during hexadecimal output. */
487 static const char hexDigitsLower[] = "0123456789abcdef0";
488 static const char hexDigitsUpper[] = "0123456789ABCDEF0";
489 static const char infinityL[] = "infinity";
490 static const char infinityU[] = "INFINITY";
491 static const char NaNL[] = "nan";
492 static const char NaNU[] = "NAN";
493
494 /* Write out an integerPart in hexadecimal, starting with the most
495 significant nibble. Write out exactly COUNT hexdigits, return
496 COUNT. */
497 static unsigned int
498 partAsHex (char *dst, integerPart part, unsigned int count,
499 const char *hexDigitChars)
500 {
501 unsigned int result = count;
502
503 assert (count != 0 && count <= integerPartWidth / 4);
504
505 part >>= (integerPartWidth - 4 * count);
506 while (count--) {
507 dst[count] = hexDigitChars[part & 0xf];
508 part >>= 4;
509 }
510
511 return result;
512 }
513
Neil Booth92f7e8d2007-10-06 07:29:25 +0000514 /* Write out an unsigned decimal integer. */
Neil Bootha30b0ee2007-10-03 22:26:02 +0000515 static char *
Neil Booth92f7e8d2007-10-06 07:29:25 +0000516 writeUnsignedDecimal (char *dst, unsigned int n)
Neil Bootha30b0ee2007-10-03 22:26:02 +0000517 {
Neil Booth92f7e8d2007-10-06 07:29:25 +0000518 char buff[40], *p;
Neil Bootha30b0ee2007-10-03 22:26:02 +0000519
Neil Booth92f7e8d2007-10-06 07:29:25 +0000520 p = buff;
521 do
522 *p++ = '0' + n % 10;
523 while (n /= 10);
524
525 do
526 *dst++ = *--p;
527 while (p != buff);
528
529 return dst;
530 }
531
532 /* Write out a signed decimal integer. */
533 static char *
534 writeSignedDecimal (char *dst, int value)
535 {
536 if (value < 0) {
Neil Bootha30b0ee2007-10-03 22:26:02 +0000537 *dst++ = '-';
Neil Booth92f7e8d2007-10-06 07:29:25 +0000538 dst = writeUnsignedDecimal(dst, -(unsigned) value);
539 } else
540 dst = writeUnsignedDecimal(dst, value);
Neil Bootha30b0ee2007-10-03 22:26:02 +0000541
542 return dst;
543 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000544}
545
546/* Constructors. */
547void
548APFloat::initialize(const fltSemantics *ourSemantics)
549{
550 unsigned int count;
551
552 semantics = ourSemantics;
553 count = partCount();
554 if(count > 1)
555 significand.parts = new integerPart[count];
556}
557
558void
559APFloat::freeSignificand()
560{
561 if(partCount() > 1)
562 delete [] significand.parts;
563}
564
565void
566APFloat::assign(const APFloat &rhs)
567{
568 assert(semantics == rhs.semantics);
569
570 sign = rhs.sign;
571 category = rhs.category;
572 exponent = rhs.exponent;
Dale Johannesena471c2e2007-10-11 18:07:22 +0000573 sign2 = rhs.sign2;
574 exponent2 = rhs.exponent2;
Dale Johanneseneaf08942007-08-31 04:03:46 +0000575 if(category == fcNormal || category == fcNaN)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000576 copySignificand(rhs);
577}
578
579void
580APFloat::copySignificand(const APFloat &rhs)
581{
Dale Johanneseneaf08942007-08-31 04:03:46 +0000582 assert(category == fcNormal || category == fcNaN);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000583 assert(rhs.partCount() >= partCount());
584
585 APInt::tcAssign(significandParts(), rhs.significandParts(),
Neil Booth4f881702007-09-26 21:33:42 +0000586 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000587}
588
Neil Boothe5e01942007-10-14 10:39:51 +0000589/* Make this number a NaN, with an arbitrary but deterministic value
590 for the significand. */
591void
592APFloat::makeNaN(void)
593{
594 category = fcNaN;
595 APInt::tcSet(significandParts(), ~0U, partCount());
596}
597
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000598APFloat &
599APFloat::operator=(const APFloat &rhs)
600{
601 if(this != &rhs) {
602 if(semantics != rhs.semantics) {
603 freeSignificand();
604 initialize(rhs.semantics);
605 }
606 assign(rhs);
607 }
608
609 return *this;
610}
611
Dale Johannesen343e7702007-08-24 00:56:33 +0000612bool
Dale Johannesen12595d72007-08-24 22:09:56 +0000613APFloat::bitwiseIsEqual(const APFloat &rhs) const {
Dale Johannesen343e7702007-08-24 00:56:33 +0000614 if (this == &rhs)
615 return true;
616 if (semantics != rhs.semantics ||
Dale Johanneseneaf08942007-08-31 04:03:46 +0000617 category != rhs.category ||
618 sign != rhs.sign)
Dale Johannesen343e7702007-08-24 00:56:33 +0000619 return false;
Dale Johannesena471c2e2007-10-11 18:07:22 +0000620 if (semantics==(const llvm::fltSemantics* const)&PPCDoubleDouble &&
621 sign2 != rhs.sign2)
622 return false;
Dale Johanneseneaf08942007-08-31 04:03:46 +0000623 if (category==fcZero || category==fcInfinity)
Dale Johannesen343e7702007-08-24 00:56:33 +0000624 return true;
Dale Johanneseneaf08942007-08-31 04:03:46 +0000625 else if (category==fcNormal && exponent!=rhs.exponent)
626 return false;
Dale Johannesena471c2e2007-10-11 18:07:22 +0000627 else if (semantics==(const llvm::fltSemantics* const)&PPCDoubleDouble &&
628 exponent2!=rhs.exponent2)
629 return false;
Dale Johannesen343e7702007-08-24 00:56:33 +0000630 else {
Dale Johannesen343e7702007-08-24 00:56:33 +0000631 int i= partCount();
632 const integerPart* p=significandParts();
633 const integerPart* q=rhs.significandParts();
634 for (; i>0; i--, p++, q++) {
635 if (*p != *q)
636 return false;
637 }
638 return true;
639 }
640}
641
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000642APFloat::APFloat(const fltSemantics &ourSemantics, integerPart value)
643{
Neil Boothcaf19d72007-10-14 10:29:28 +0000644 assertArithmeticOK(ourSemantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000645 initialize(&ourSemantics);
646 sign = 0;
647 zeroSignificand();
648 exponent = ourSemantics.precision - 1;
649 significandParts()[0] = value;
650 normalize(rmNearestTiesToEven, lfExactlyZero);
651}
652
653APFloat::APFloat(const fltSemantics &ourSemantics,
Neil Booth4f881702007-09-26 21:33:42 +0000654 fltCategory ourCategory, bool negative)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000655{
Neil Boothcaf19d72007-10-14 10:29:28 +0000656 assertArithmeticOK(ourSemantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000657 initialize(&ourSemantics);
658 category = ourCategory;
659 sign = negative;
660 if(category == fcNormal)
661 category = fcZero;
Neil Boothe5e01942007-10-14 10:39:51 +0000662 else if (ourCategory == fcNaN)
663 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000664}
665
666APFloat::APFloat(const fltSemantics &ourSemantics, const char *text)
667{
Neil Boothcaf19d72007-10-14 10:29:28 +0000668 assertArithmeticOK(ourSemantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000669 initialize(&ourSemantics);
670 convertFromString(text, rmNearestTiesToEven);
671}
672
673APFloat::APFloat(const APFloat &rhs)
674{
675 initialize(rhs.semantics);
676 assign(rhs);
677}
678
679APFloat::~APFloat()
680{
681 freeSignificand();
682}
683
684unsigned int
685APFloat::partCount() const
686{
Dale Johannesena72a5a02007-09-20 23:47:58 +0000687 return partCountForBits(semantics->precision + 1);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000688}
689
690unsigned int
691APFloat::semanticsPrecision(const fltSemantics &semantics)
692{
693 return semantics.precision;
694}
695
696const integerPart *
697APFloat::significandParts() const
698{
699 return const_cast<APFloat *>(this)->significandParts();
700}
701
702integerPart *
703APFloat::significandParts()
704{
Dale Johanneseneaf08942007-08-31 04:03:46 +0000705 assert(category == fcNormal || category == fcNaN);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000706
707 if(partCount() > 1)
708 return significand.parts;
709 else
710 return &significand.part;
711}
712
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000713void
714APFloat::zeroSignificand()
715{
716 category = fcNormal;
717 APInt::tcSet(significandParts(), 0, partCount());
718}
719
720/* Increment an fcNormal floating point number's significand. */
721void
722APFloat::incrementSignificand()
723{
724 integerPart carry;
725
726 carry = APInt::tcIncrement(significandParts(), partCount());
727
728 /* Our callers should never cause us to overflow. */
729 assert(carry == 0);
730}
731
732/* Add the significand of the RHS. Returns the carry flag. */
733integerPart
734APFloat::addSignificand(const APFloat &rhs)
735{
736 integerPart *parts;
737
738 parts = significandParts();
739
740 assert(semantics == rhs.semantics);
741 assert(exponent == rhs.exponent);
742
743 return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
744}
745
746/* Subtract the significand of the RHS with a borrow flag. Returns
747 the borrow flag. */
748integerPart
749APFloat::subtractSignificand(const APFloat &rhs, integerPart borrow)
750{
751 integerPart *parts;
752
753 parts = significandParts();
754
755 assert(semantics == rhs.semantics);
756 assert(exponent == rhs.exponent);
757
758 return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
Neil Booth4f881702007-09-26 21:33:42 +0000759 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000760}
761
762/* Multiply the significand of the RHS. If ADDEND is non-NULL, add it
763 on to the full-precision result of the multiplication. Returns the
764 lost fraction. */
765lostFraction
766APFloat::multiplySignificand(const APFloat &rhs, const APFloat *addend)
767{
Neil Booth4f881702007-09-26 21:33:42 +0000768 unsigned int omsb; // One, not zero, based MSB.
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000769 unsigned int partsCount, newPartsCount, precision;
770 integerPart *lhsSignificand;
771 integerPart scratch[4];
772 integerPart *fullSignificand;
773 lostFraction lost_fraction;
774
775 assert(semantics == rhs.semantics);
776
777 precision = semantics->precision;
778 newPartsCount = partCountForBits(precision * 2);
779
780 if(newPartsCount > 4)
781 fullSignificand = new integerPart[newPartsCount];
782 else
783 fullSignificand = scratch;
784
785 lhsSignificand = significandParts();
786 partsCount = partCount();
787
788 APInt::tcFullMultiply(fullSignificand, lhsSignificand,
Neil Booth978661d2007-10-06 00:24:48 +0000789 rhs.significandParts(), partsCount, partsCount);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000790
791 lost_fraction = lfExactlyZero;
792 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
793 exponent += rhs.exponent;
794
795 if(addend) {
796 Significand savedSignificand = significand;
797 const fltSemantics *savedSemantics = semantics;
798 fltSemantics extendedSemantics;
799 opStatus status;
800 unsigned int extendedPrecision;
801
802 /* Normalize our MSB. */
803 extendedPrecision = precision + precision - 1;
804 if(omsb != extendedPrecision)
805 {
Neil Booth4f881702007-09-26 21:33:42 +0000806 APInt::tcShiftLeft(fullSignificand, newPartsCount,
807 extendedPrecision - omsb);
808 exponent -= extendedPrecision - omsb;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000809 }
810
811 /* Create new semantics. */
812 extendedSemantics = *semantics;
813 extendedSemantics.precision = extendedPrecision;
814
815 if(newPartsCount == 1)
816 significand.part = fullSignificand[0];
817 else
818 significand.parts = fullSignificand;
819 semantics = &extendedSemantics;
820
821 APFloat extendedAddend(*addend);
822 status = extendedAddend.convert(extendedSemantics, rmTowardZero);
823 assert(status == opOK);
824 lost_fraction = addOrSubtractSignificand(extendedAddend, false);
825
826 /* Restore our state. */
827 if(newPartsCount == 1)
828 fullSignificand[0] = significand.part;
829 significand = savedSignificand;
830 semantics = savedSemantics;
831
832 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
833 }
834
835 exponent -= (precision - 1);
836
837 if(omsb > precision) {
838 unsigned int bits, significantParts;
839 lostFraction lf;
840
841 bits = omsb - precision;
842 significantParts = partCountForBits(omsb);
843 lf = shiftRight(fullSignificand, significantParts, bits);
844 lost_fraction = combineLostFractions(lf, lost_fraction);
845 exponent += bits;
846 }
847
848 APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
849
850 if(newPartsCount > 4)
851 delete [] fullSignificand;
852
853 return lost_fraction;
854}
855
856/* Multiply the significands of LHS and RHS to DST. */
857lostFraction
858APFloat::divideSignificand(const APFloat &rhs)
859{
860 unsigned int bit, i, partsCount;
861 const integerPart *rhsSignificand;
862 integerPart *lhsSignificand, *dividend, *divisor;
863 integerPart scratch[4];
864 lostFraction lost_fraction;
865
866 assert(semantics == rhs.semantics);
867
868 lhsSignificand = significandParts();
869 rhsSignificand = rhs.significandParts();
870 partsCount = partCount();
871
872 if(partsCount > 2)
873 dividend = new integerPart[partsCount * 2];
874 else
875 dividend = scratch;
876
877 divisor = dividend + partsCount;
878
879 /* Copy the dividend and divisor as they will be modified in-place. */
880 for(i = 0; i < partsCount; i++) {
881 dividend[i] = lhsSignificand[i];
882 divisor[i] = rhsSignificand[i];
883 lhsSignificand[i] = 0;
884 }
885
886 exponent -= rhs.exponent;
887
888 unsigned int precision = semantics->precision;
889
890 /* Normalize the divisor. */
891 bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
892 if(bit) {
893 exponent += bit;
894 APInt::tcShiftLeft(divisor, partsCount, bit);
895 }
896
897 /* Normalize the dividend. */
898 bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
899 if(bit) {
900 exponent -= bit;
901 APInt::tcShiftLeft(dividend, partsCount, bit);
902 }
903
Neil Booth96c74712007-10-12 16:02:31 +0000904 /* Ensure the dividend >= divisor initially for the loop below.
905 Incidentally, this means that the division loop below is
906 guaranteed to set the integer bit to one. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000907 if(APInt::tcCompare(dividend, divisor, partsCount) < 0) {
908 exponent--;
909 APInt::tcShiftLeft(dividend, partsCount, 1);
910 assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
911 }
912
913 /* Long division. */
914 for(bit = precision; bit; bit -= 1) {
915 if(APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
916 APInt::tcSubtract(dividend, divisor, 0, partsCount);
917 APInt::tcSetBit(lhsSignificand, bit - 1);
918 }
919
920 APInt::tcShiftLeft(dividend, partsCount, 1);
921 }
922
923 /* Figure out the lost fraction. */
924 int cmp = APInt::tcCompare(dividend, divisor, partsCount);
925
926 if(cmp > 0)
927 lost_fraction = lfMoreThanHalf;
928 else if(cmp == 0)
929 lost_fraction = lfExactlyHalf;
930 else if(APInt::tcIsZero(dividend, partsCount))
931 lost_fraction = lfExactlyZero;
932 else
933 lost_fraction = lfLessThanHalf;
934
935 if(partsCount > 2)
936 delete [] dividend;
937
938 return lost_fraction;
939}
940
941unsigned int
942APFloat::significandMSB() const
943{
944 return APInt::tcMSB(significandParts(), partCount());
945}
946
947unsigned int
948APFloat::significandLSB() const
949{
950 return APInt::tcLSB(significandParts(), partCount());
951}
952
953/* Note that a zero result is NOT normalized to fcZero. */
954lostFraction
955APFloat::shiftSignificandRight(unsigned int bits)
956{
957 /* Our exponent should not overflow. */
958 assert((exponent_t) (exponent + bits) >= exponent);
959
960 exponent += bits;
961
962 return shiftRight(significandParts(), partCount(), bits);
963}
964
965/* Shift the significand left BITS bits, subtract BITS from its exponent. */
966void
967APFloat::shiftSignificandLeft(unsigned int bits)
968{
969 assert(bits < semantics->precision);
970
971 if(bits) {
972 unsigned int partsCount = partCount();
973
974 APInt::tcShiftLeft(significandParts(), partsCount, bits);
975 exponent -= bits;
976
977 assert(!APInt::tcIsZero(significandParts(), partsCount));
978 }
979}
980
981APFloat::cmpResult
982APFloat::compareAbsoluteValue(const APFloat &rhs) const
983{
984 int compare;
985
986 assert(semantics == rhs.semantics);
987 assert(category == fcNormal);
988 assert(rhs.category == fcNormal);
989
990 compare = exponent - rhs.exponent;
991
992 /* If exponents are equal, do an unsigned bignum comparison of the
993 significands. */
994 if(compare == 0)
995 compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
Neil Booth4f881702007-09-26 21:33:42 +0000996 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000997
998 if(compare > 0)
999 return cmpGreaterThan;
1000 else if(compare < 0)
1001 return cmpLessThan;
1002 else
1003 return cmpEqual;
1004}
1005
1006/* Handle overflow. Sign is preserved. We either become infinity or
1007 the largest finite number. */
1008APFloat::opStatus
1009APFloat::handleOverflow(roundingMode rounding_mode)
1010{
1011 /* Infinity? */
1012 if(rounding_mode == rmNearestTiesToEven
1013 || rounding_mode == rmNearestTiesToAway
1014 || (rounding_mode == rmTowardPositive && !sign)
1015 || (rounding_mode == rmTowardNegative && sign))
1016 {
1017 category = fcInfinity;
1018 return (opStatus) (opOverflow | opInexact);
1019 }
1020
1021 /* Otherwise we become the largest finite number. */
1022 category = fcNormal;
1023 exponent = semantics->maxExponent;
1024 APInt::tcSetLeastSignificantBits(significandParts(), partCount(),
Neil Booth4f881702007-09-26 21:33:42 +00001025 semantics->precision);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001026
1027 return opInexact;
1028}
1029
Neil Boothb7dea4c2007-10-03 15:16:41 +00001030/* Returns TRUE if, when truncating the current number, with BIT the
1031 new LSB, with the given lost fraction and rounding mode, the result
1032 would need to be rounded away from zero (i.e., by increasing the
1033 signficand). This routine must work for fcZero of both signs, and
1034 fcNormal numbers. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001035bool
1036APFloat::roundAwayFromZero(roundingMode rounding_mode,
Neil Boothb7dea4c2007-10-03 15:16:41 +00001037 lostFraction lost_fraction,
1038 unsigned int bit) const
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001039{
Dale Johanneseneaf08942007-08-31 04:03:46 +00001040 /* NaNs and infinities should not have lost fractions. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001041 assert(category == fcNormal || category == fcZero);
1042
Neil Boothb7dea4c2007-10-03 15:16:41 +00001043 /* Current callers never pass this so we don't handle it. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001044 assert(lost_fraction != lfExactlyZero);
1045
1046 switch(rounding_mode) {
1047 default:
1048 assert(0);
1049
1050 case rmNearestTiesToAway:
1051 return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
1052
1053 case rmNearestTiesToEven:
1054 if(lost_fraction == lfMoreThanHalf)
1055 return true;
1056
1057 /* Our zeroes don't have a significand to test. */
1058 if(lost_fraction == lfExactlyHalf && category != fcZero)
Neil Boothb7dea4c2007-10-03 15:16:41 +00001059 return APInt::tcExtractBit(significandParts(), bit);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001060
1061 return false;
1062
1063 case rmTowardZero:
1064 return false;
1065
1066 case rmTowardPositive:
1067 return sign == false;
1068
1069 case rmTowardNegative:
1070 return sign == true;
1071 }
1072}
1073
1074APFloat::opStatus
1075APFloat::normalize(roundingMode rounding_mode,
Neil Booth4f881702007-09-26 21:33:42 +00001076 lostFraction lost_fraction)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001077{
Neil Booth4f881702007-09-26 21:33:42 +00001078 unsigned int omsb; /* One, not zero, based MSB. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001079 int exponentChange;
1080
1081 if(category != fcNormal)
1082 return opOK;
1083
1084 /* Before rounding normalize the exponent of fcNormal numbers. */
1085 omsb = significandMSB() + 1;
1086
1087 if(omsb) {
1088 /* OMSB is numbered from 1. We want to place it in the integer
1089 bit numbered PRECISON if possible, with a compensating change in
1090 the exponent. */
1091 exponentChange = omsb - semantics->precision;
1092
1093 /* If the resulting exponent is too high, overflow according to
1094 the rounding mode. */
1095 if(exponent + exponentChange > semantics->maxExponent)
1096 return handleOverflow(rounding_mode);
1097
1098 /* Subnormal numbers have exponent minExponent, and their MSB
1099 is forced based on that. */
1100 if(exponent + exponentChange < semantics->minExponent)
1101 exponentChange = semantics->minExponent - exponent;
1102
1103 /* Shifting left is easy as we don't lose precision. */
1104 if(exponentChange < 0) {
1105 assert(lost_fraction == lfExactlyZero);
1106
1107 shiftSignificandLeft(-exponentChange);
1108
1109 return opOK;
1110 }
1111
1112 if(exponentChange > 0) {
1113 lostFraction lf;
1114
1115 /* Shift right and capture any new lost fraction. */
1116 lf = shiftSignificandRight(exponentChange);
1117
1118 lost_fraction = combineLostFractions(lf, lost_fraction);
1119
1120 /* Keep OMSB up-to-date. */
1121 if(omsb > (unsigned) exponentChange)
Neil Booth96c74712007-10-12 16:02:31 +00001122 omsb -= exponentChange;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001123 else
Neil Booth4f881702007-09-26 21:33:42 +00001124 omsb = 0;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001125 }
1126 }
1127
1128 /* Now round the number according to rounding_mode given the lost
1129 fraction. */
1130
1131 /* As specified in IEEE 754, since we do not trap we do not report
1132 underflow for exact results. */
1133 if(lost_fraction == lfExactlyZero) {
1134 /* Canonicalize zeroes. */
1135 if(omsb == 0)
1136 category = fcZero;
1137
1138 return opOK;
1139 }
1140
1141 /* Increment the significand if we're rounding away from zero. */
Neil Boothb7dea4c2007-10-03 15:16:41 +00001142 if(roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001143 if(omsb == 0)
1144 exponent = semantics->minExponent;
1145
1146 incrementSignificand();
1147 omsb = significandMSB() + 1;
1148
1149 /* Did the significand increment overflow? */
1150 if(omsb == (unsigned) semantics->precision + 1) {
1151 /* Renormalize by incrementing the exponent and shifting our
Neil Booth4f881702007-09-26 21:33:42 +00001152 significand right one. However if we already have the
1153 maximum exponent we overflow to infinity. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001154 if(exponent == semantics->maxExponent) {
Neil Booth4f881702007-09-26 21:33:42 +00001155 category = fcInfinity;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001156
Neil Booth4f881702007-09-26 21:33:42 +00001157 return (opStatus) (opOverflow | opInexact);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001158 }
1159
1160 shiftSignificandRight(1);
1161
1162 return opInexact;
1163 }
1164 }
1165
1166 /* The normal case - we were and are not denormal, and any
1167 significand increment above didn't overflow. */
1168 if(omsb == semantics->precision)
1169 return opInexact;
1170
1171 /* We have a non-zero denormal. */
1172 assert(omsb < semantics->precision);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001173
1174 /* Canonicalize zeroes. */
1175 if(omsb == 0)
1176 category = fcZero;
1177
1178 /* The fcZero case is a denormal that underflowed to zero. */
1179 return (opStatus) (opUnderflow | opInexact);
1180}
1181
1182APFloat::opStatus
1183APFloat::addOrSubtractSpecials(const APFloat &rhs, bool subtract)
1184{
1185 switch(convolve(category, rhs.category)) {
1186 default:
1187 assert(0);
1188
Dale Johanneseneaf08942007-08-31 04:03:46 +00001189 case convolve(fcNaN, fcZero):
1190 case convolve(fcNaN, fcNormal):
1191 case convolve(fcNaN, fcInfinity):
1192 case convolve(fcNaN, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001193 case convolve(fcNormal, fcZero):
1194 case convolve(fcInfinity, fcNormal):
1195 case convolve(fcInfinity, fcZero):
1196 return opOK;
1197
Dale Johanneseneaf08942007-08-31 04:03:46 +00001198 case convolve(fcZero, fcNaN):
1199 case convolve(fcNormal, fcNaN):
1200 case convolve(fcInfinity, fcNaN):
1201 category = fcNaN;
1202 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001203 return opOK;
1204
1205 case convolve(fcNormal, fcInfinity):
1206 case convolve(fcZero, fcInfinity):
1207 category = fcInfinity;
1208 sign = rhs.sign ^ subtract;
1209 return opOK;
1210
1211 case convolve(fcZero, fcNormal):
1212 assign(rhs);
1213 sign = rhs.sign ^ subtract;
1214 return opOK;
1215
1216 case convolve(fcZero, fcZero):
1217 /* Sign depends on rounding mode; handled by caller. */
1218 return opOK;
1219
1220 case convolve(fcInfinity, fcInfinity):
1221 /* Differently signed infinities can only be validly
1222 subtracted. */
1223 if(sign ^ rhs.sign != subtract) {
Neil Boothe5e01942007-10-14 10:39:51 +00001224 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001225 return opInvalidOp;
1226 }
1227
1228 return opOK;
1229
1230 case convolve(fcNormal, fcNormal):
1231 return opDivByZero;
1232 }
1233}
1234
1235/* Add or subtract two normal numbers. */
1236lostFraction
1237APFloat::addOrSubtractSignificand(const APFloat &rhs, bool subtract)
1238{
1239 integerPart carry;
1240 lostFraction lost_fraction;
1241 int bits;
1242
1243 /* Determine if the operation on the absolute values is effectively
1244 an addition or subtraction. */
1245 subtract ^= (sign ^ rhs.sign);
1246
1247 /* Are we bigger exponent-wise than the RHS? */
1248 bits = exponent - rhs.exponent;
1249
1250 /* Subtraction is more subtle than one might naively expect. */
1251 if(subtract) {
1252 APFloat temp_rhs(rhs);
1253 bool reverse;
1254
Chris Lattnerada530b2007-08-24 03:02:34 +00001255 if (bits == 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001256 reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan;
1257 lost_fraction = lfExactlyZero;
Chris Lattnerada530b2007-08-24 03:02:34 +00001258 } else if (bits > 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001259 lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
1260 shiftSignificandLeft(1);
1261 reverse = false;
Chris Lattnerada530b2007-08-24 03:02:34 +00001262 } else {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001263 lost_fraction = shiftSignificandRight(-bits - 1);
1264 temp_rhs.shiftSignificandLeft(1);
1265 reverse = true;
1266 }
1267
Chris Lattnerada530b2007-08-24 03:02:34 +00001268 if (reverse) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001269 carry = temp_rhs.subtractSignificand
Neil Booth4f881702007-09-26 21:33:42 +00001270 (*this, lost_fraction != lfExactlyZero);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001271 copySignificand(temp_rhs);
1272 sign = !sign;
1273 } else {
1274 carry = subtractSignificand
Neil Booth4f881702007-09-26 21:33:42 +00001275 (temp_rhs, lost_fraction != lfExactlyZero);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001276 }
1277
1278 /* Invert the lost fraction - it was on the RHS and
1279 subtracted. */
1280 if(lost_fraction == lfLessThanHalf)
1281 lost_fraction = lfMoreThanHalf;
1282 else if(lost_fraction == lfMoreThanHalf)
1283 lost_fraction = lfLessThanHalf;
1284
1285 /* The code above is intended to ensure that no borrow is
1286 necessary. */
1287 assert(!carry);
1288 } else {
1289 if(bits > 0) {
1290 APFloat temp_rhs(rhs);
1291
1292 lost_fraction = temp_rhs.shiftSignificandRight(bits);
1293 carry = addSignificand(temp_rhs);
1294 } else {
1295 lost_fraction = shiftSignificandRight(-bits);
1296 carry = addSignificand(rhs);
1297 }
1298
1299 /* We have a guard bit; generating a carry cannot happen. */
1300 assert(!carry);
1301 }
1302
1303 return lost_fraction;
1304}
1305
1306APFloat::opStatus
1307APFloat::multiplySpecials(const APFloat &rhs)
1308{
1309 switch(convolve(category, rhs.category)) {
1310 default:
1311 assert(0);
1312
Dale Johanneseneaf08942007-08-31 04:03:46 +00001313 case convolve(fcNaN, fcZero):
1314 case convolve(fcNaN, fcNormal):
1315 case convolve(fcNaN, fcInfinity):
1316 case convolve(fcNaN, fcNaN):
1317 return opOK;
1318
1319 case convolve(fcZero, fcNaN):
1320 case convolve(fcNormal, fcNaN):
1321 case convolve(fcInfinity, fcNaN):
1322 category = fcNaN;
1323 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001324 return opOK;
1325
1326 case convolve(fcNormal, fcInfinity):
1327 case convolve(fcInfinity, fcNormal):
1328 case convolve(fcInfinity, fcInfinity):
1329 category = fcInfinity;
1330 return opOK;
1331
1332 case convolve(fcZero, fcNormal):
1333 case convolve(fcNormal, fcZero):
1334 case convolve(fcZero, fcZero):
1335 category = fcZero;
1336 return opOK;
1337
1338 case convolve(fcZero, fcInfinity):
1339 case convolve(fcInfinity, fcZero):
Neil Boothe5e01942007-10-14 10:39:51 +00001340 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001341 return opInvalidOp;
1342
1343 case convolve(fcNormal, fcNormal):
1344 return opOK;
1345 }
1346}
1347
1348APFloat::opStatus
1349APFloat::divideSpecials(const APFloat &rhs)
1350{
1351 switch(convolve(category, rhs.category)) {
1352 default:
1353 assert(0);
1354
Dale Johanneseneaf08942007-08-31 04:03:46 +00001355 case convolve(fcNaN, fcZero):
1356 case convolve(fcNaN, fcNormal):
1357 case convolve(fcNaN, fcInfinity):
1358 case convolve(fcNaN, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001359 case convolve(fcInfinity, fcZero):
1360 case convolve(fcInfinity, fcNormal):
1361 case convolve(fcZero, fcInfinity):
1362 case convolve(fcZero, fcNormal):
1363 return opOK;
1364
Dale Johanneseneaf08942007-08-31 04:03:46 +00001365 case convolve(fcZero, fcNaN):
1366 case convolve(fcNormal, fcNaN):
1367 case convolve(fcInfinity, fcNaN):
1368 category = fcNaN;
1369 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001370 return opOK;
1371
1372 case convolve(fcNormal, fcInfinity):
1373 category = fcZero;
1374 return opOK;
1375
1376 case convolve(fcNormal, fcZero):
1377 category = fcInfinity;
1378 return opDivByZero;
1379
1380 case convolve(fcInfinity, fcInfinity):
1381 case convolve(fcZero, fcZero):
Neil Boothe5e01942007-10-14 10:39:51 +00001382 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001383 return opInvalidOp;
1384
1385 case convolve(fcNormal, fcNormal):
1386 return opOK;
1387 }
1388}
1389
1390/* Change sign. */
1391void
1392APFloat::changeSign()
1393{
1394 /* Look mummy, this one's easy. */
1395 sign = !sign;
1396}
1397
Dale Johannesene15c2db2007-08-31 23:35:31 +00001398void
1399APFloat::clearSign()
1400{
1401 /* So is this one. */
1402 sign = 0;
1403}
1404
1405void
1406APFloat::copySign(const APFloat &rhs)
1407{
1408 /* And this one. */
1409 sign = rhs.sign;
1410}
1411
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001412/* Normalized addition or subtraction. */
1413APFloat::opStatus
1414APFloat::addOrSubtract(const APFloat &rhs, roundingMode rounding_mode,
Neil Booth4f881702007-09-26 21:33:42 +00001415 bool subtract)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001416{
1417 opStatus fs;
1418
Neil Boothcaf19d72007-10-14 10:29:28 +00001419 assertArithmeticOK(*semantics);
1420
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001421 fs = addOrSubtractSpecials(rhs, subtract);
1422
1423 /* This return code means it was not a simple case. */
1424 if(fs == opDivByZero) {
1425 lostFraction lost_fraction;
1426
1427 lost_fraction = addOrSubtractSignificand(rhs, subtract);
1428 fs = normalize(rounding_mode, lost_fraction);
1429
1430 /* Can only be zero if we lost no fraction. */
1431 assert(category != fcZero || lost_fraction == lfExactlyZero);
1432 }
1433
1434 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1435 positive zero unless rounding to minus infinity, except that
1436 adding two like-signed zeroes gives that zero. */
1437 if(category == fcZero) {
1438 if(rhs.category != fcZero || (sign == rhs.sign) == subtract)
1439 sign = (rounding_mode == rmTowardNegative);
1440 }
1441
1442 return fs;
1443}
1444
1445/* Normalized addition. */
1446APFloat::opStatus
1447APFloat::add(const APFloat &rhs, roundingMode rounding_mode)
1448{
1449 return addOrSubtract(rhs, rounding_mode, false);
1450}
1451
1452/* Normalized subtraction. */
1453APFloat::opStatus
1454APFloat::subtract(const APFloat &rhs, roundingMode rounding_mode)
1455{
1456 return addOrSubtract(rhs, rounding_mode, true);
1457}
1458
1459/* Normalized multiply. */
1460APFloat::opStatus
1461APFloat::multiply(const APFloat &rhs, roundingMode rounding_mode)
1462{
1463 opStatus fs;
1464
Neil Boothcaf19d72007-10-14 10:29:28 +00001465 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001466 sign ^= rhs.sign;
1467 fs = multiplySpecials(rhs);
1468
1469 if(category == fcNormal) {
1470 lostFraction lost_fraction = multiplySignificand(rhs, 0);
1471 fs = normalize(rounding_mode, lost_fraction);
1472 if(lost_fraction != lfExactlyZero)
1473 fs = (opStatus) (fs | opInexact);
1474 }
1475
1476 return fs;
1477}
1478
1479/* Normalized divide. */
1480APFloat::opStatus
1481APFloat::divide(const APFloat &rhs, roundingMode rounding_mode)
1482{
1483 opStatus fs;
1484
Neil Boothcaf19d72007-10-14 10:29:28 +00001485 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001486 sign ^= rhs.sign;
1487 fs = divideSpecials(rhs);
1488
1489 if(category == fcNormal) {
1490 lostFraction lost_fraction = divideSignificand(rhs);
1491 fs = normalize(rounding_mode, lost_fraction);
1492 if(lost_fraction != lfExactlyZero)
1493 fs = (opStatus) (fs | opInexact);
1494 }
1495
1496 return fs;
1497}
1498
Neil Bootha30b0ee2007-10-03 22:26:02 +00001499/* Normalized remainder. This is not currently doing TRT. */
Dale Johannesene15c2db2007-08-31 23:35:31 +00001500APFloat::opStatus
1501APFloat::mod(const APFloat &rhs, roundingMode rounding_mode)
1502{
1503 opStatus fs;
1504 APFloat V = *this;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001505 unsigned int origSign = sign;
Neil Boothcaf19d72007-10-14 10:29:28 +00001506
1507 assertArithmeticOK(*semantics);
Dale Johannesene15c2db2007-08-31 23:35:31 +00001508 fs = V.divide(rhs, rmNearestTiesToEven);
1509 if (fs == opDivByZero)
1510 return fs;
1511
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001512 int parts = partCount();
1513 integerPart *x = new integerPart[parts];
Neil Booth4f881702007-09-26 21:33:42 +00001514 fs = V.convertToInteger(x, parts * integerPartWidth, true,
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001515 rmNearestTiesToEven);
Dale Johannesene15c2db2007-08-31 23:35:31 +00001516 if (fs==opInvalidOp)
1517 return fs;
1518
Neil Boothccf596a2007-10-07 11:45:55 +00001519 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1520 rmNearestTiesToEven);
Dale Johannesene15c2db2007-08-31 23:35:31 +00001521 assert(fs==opOK); // should always work
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001522
Dale Johannesene15c2db2007-08-31 23:35:31 +00001523 fs = V.multiply(rhs, rounding_mode);
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001524 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1525
Dale Johannesene15c2db2007-08-31 23:35:31 +00001526 fs = subtract(V, rounding_mode);
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001527 assert(fs==opOK || fs==opInexact); // likewise
1528
1529 if (isZero())
1530 sign = origSign; // IEEE754 requires this
1531 delete[] x;
Dale Johannesene15c2db2007-08-31 23:35:31 +00001532 return fs;
1533}
1534
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001535/* Normalized fused-multiply-add. */
1536APFloat::opStatus
1537APFloat::fusedMultiplyAdd(const APFloat &multiplicand,
Neil Booth4f881702007-09-26 21:33:42 +00001538 const APFloat &addend,
1539 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001540{
1541 opStatus fs;
1542
Neil Boothcaf19d72007-10-14 10:29:28 +00001543 assertArithmeticOK(*semantics);
1544
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001545 /* Post-multiplication sign, before addition. */
1546 sign ^= multiplicand.sign;
1547
1548 /* If and only if all arguments are normal do we need to do an
1549 extended-precision calculation. */
1550 if(category == fcNormal
1551 && multiplicand.category == fcNormal
1552 && addend.category == fcNormal) {
1553 lostFraction lost_fraction;
1554
1555 lost_fraction = multiplySignificand(multiplicand, &addend);
1556 fs = normalize(rounding_mode, lost_fraction);
1557 if(lost_fraction != lfExactlyZero)
1558 fs = (opStatus) (fs | opInexact);
1559
1560 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1561 positive zero unless rounding to minus infinity, except that
1562 adding two like-signed zeroes gives that zero. */
1563 if(category == fcZero && sign != addend.sign)
1564 sign = (rounding_mode == rmTowardNegative);
1565 } else {
1566 fs = multiplySpecials(multiplicand);
1567
1568 /* FS can only be opOK or opInvalidOp. There is no more work
1569 to do in the latter case. The IEEE-754R standard says it is
1570 implementation-defined in this case whether, if ADDEND is a
Dale Johanneseneaf08942007-08-31 04:03:46 +00001571 quiet NaN, we raise invalid op; this implementation does so.
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001572
1573 If we need to do the addition we can do so with normal
1574 precision. */
1575 if(fs == opOK)
1576 fs = addOrSubtract(addend, rounding_mode, false);
1577 }
1578
1579 return fs;
1580}
1581
1582/* Comparison requires normalized numbers. */
1583APFloat::cmpResult
1584APFloat::compare(const APFloat &rhs) const
1585{
1586 cmpResult result;
1587
Neil Boothcaf19d72007-10-14 10:29:28 +00001588 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001589 assert(semantics == rhs.semantics);
1590
1591 switch(convolve(category, rhs.category)) {
1592 default:
1593 assert(0);
1594
Dale Johanneseneaf08942007-08-31 04:03:46 +00001595 case convolve(fcNaN, fcZero):
1596 case convolve(fcNaN, fcNormal):
1597 case convolve(fcNaN, fcInfinity):
1598 case convolve(fcNaN, fcNaN):
1599 case convolve(fcZero, fcNaN):
1600 case convolve(fcNormal, fcNaN):
1601 case convolve(fcInfinity, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001602 return cmpUnordered;
1603
1604 case convolve(fcInfinity, fcNormal):
1605 case convolve(fcInfinity, fcZero):
1606 case convolve(fcNormal, fcZero):
1607 if(sign)
1608 return cmpLessThan;
1609 else
1610 return cmpGreaterThan;
1611
1612 case convolve(fcNormal, fcInfinity):
1613 case convolve(fcZero, fcInfinity):
1614 case convolve(fcZero, fcNormal):
1615 if(rhs.sign)
1616 return cmpGreaterThan;
1617 else
1618 return cmpLessThan;
1619
1620 case convolve(fcInfinity, fcInfinity):
1621 if(sign == rhs.sign)
1622 return cmpEqual;
1623 else if(sign)
1624 return cmpLessThan;
1625 else
1626 return cmpGreaterThan;
1627
1628 case convolve(fcZero, fcZero):
1629 return cmpEqual;
1630
1631 case convolve(fcNormal, fcNormal):
1632 break;
1633 }
1634
1635 /* Two normal numbers. Do they have the same sign? */
1636 if(sign != rhs.sign) {
1637 if(sign)
1638 result = cmpLessThan;
1639 else
1640 result = cmpGreaterThan;
1641 } else {
1642 /* Compare absolute values; invert result if negative. */
1643 result = compareAbsoluteValue(rhs);
1644
1645 if(sign) {
1646 if(result == cmpLessThan)
Neil Booth4f881702007-09-26 21:33:42 +00001647 result = cmpGreaterThan;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001648 else if(result == cmpGreaterThan)
Neil Booth4f881702007-09-26 21:33:42 +00001649 result = cmpLessThan;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001650 }
1651 }
1652
1653 return result;
1654}
1655
1656APFloat::opStatus
1657APFloat::convert(const fltSemantics &toSemantics,
Neil Booth4f881702007-09-26 21:33:42 +00001658 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001659{
Neil Boothc8db43d2007-09-22 02:56:19 +00001660 lostFraction lostFraction;
1661 unsigned int newPartCount, oldPartCount;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001662 opStatus fs;
Neil Booth4f881702007-09-26 21:33:42 +00001663
Neil Boothcaf19d72007-10-14 10:29:28 +00001664 assertArithmeticOK(*semantics);
Neil Boothc8db43d2007-09-22 02:56:19 +00001665 lostFraction = lfExactlyZero;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001666 newPartCount = partCountForBits(toSemantics.precision + 1);
Neil Boothc8db43d2007-09-22 02:56:19 +00001667 oldPartCount = partCount();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001668
Neil Boothc8db43d2007-09-22 02:56:19 +00001669 /* Handle storage complications. If our new form is wider,
1670 re-allocate our bit pattern into wider storage. If it is
1671 narrower, we ignore the excess parts, but if narrowing to a
Dale Johannesen902ff942007-09-25 17:25:00 +00001672 single part we need to free the old storage.
1673 Be careful not to reference significandParts for zeroes
1674 and infinities, since it aborts. */
Neil Boothc8db43d2007-09-22 02:56:19 +00001675 if (newPartCount > oldPartCount) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001676 integerPart *newParts;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001677 newParts = new integerPart[newPartCount];
1678 APInt::tcSet(newParts, 0, newPartCount);
Dale Johannesen902ff942007-09-25 17:25:00 +00001679 if (category==fcNormal || category==fcNaN)
1680 APInt::tcAssign(newParts, significandParts(), oldPartCount);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001681 freeSignificand();
1682 significand.parts = newParts;
Neil Boothc8db43d2007-09-22 02:56:19 +00001683 } else if (newPartCount < oldPartCount) {
1684 /* Capture any lost fraction through truncation of parts so we get
1685 correct rounding whilst normalizing. */
Dale Johannesen902ff942007-09-25 17:25:00 +00001686 if (category==fcNormal)
1687 lostFraction = lostFractionThroughTruncation
1688 (significandParts(), oldPartCount, toSemantics.precision);
1689 if (newPartCount == 1) {
1690 integerPart newPart = 0;
Neil Booth4f881702007-09-26 21:33:42 +00001691 if (category==fcNormal || category==fcNaN)
Dale Johannesen902ff942007-09-25 17:25:00 +00001692 newPart = significandParts()[0];
1693 freeSignificand();
1694 significand.part = newPart;
1695 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001696 }
1697
1698 if(category == fcNormal) {
1699 /* Re-interpret our bit-pattern. */
1700 exponent += toSemantics.precision - semantics->precision;
1701 semantics = &toSemantics;
Neil Boothc8db43d2007-09-22 02:56:19 +00001702 fs = normalize(rounding_mode, lostFraction);
Dale Johannesen902ff942007-09-25 17:25:00 +00001703 } else if (category == fcNaN) {
1704 int shift = toSemantics.precision - semantics->precision;
1705 // No normalization here, just truncate
1706 if (shift>0)
1707 APInt::tcShiftLeft(significandParts(), newPartCount, shift);
1708 else if (shift < 0)
1709 APInt::tcShiftRight(significandParts(), newPartCount, -shift);
1710 // gcc forces the Quiet bit on, which means (float)(double)(float_sNan)
1711 // does not give you back the same bits. This is dubious, and we
1712 // don't currently do it. You're really supposed to get
1713 // an invalid operation signal at runtime, but nobody does that.
1714 semantics = &toSemantics;
1715 fs = opOK;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001716 } else {
1717 semantics = &toSemantics;
1718 fs = opOK;
1719 }
1720
1721 return fs;
1722}
1723
1724/* Convert a floating point number to an integer according to the
1725 rounding mode. If the rounded integer value is out of range this
1726 returns an invalid operation exception. If the rounded value is in
1727 range but the floating point number is not the exact integer, the C
1728 standard doesn't require an inexact exception to be raised. IEEE
1729 854 does require it so we do that.
1730
1731 Note that for conversions to integer type the C standard requires
1732 round-to-zero to always be used. */
1733APFloat::opStatus
1734APFloat::convertToInteger(integerPart *parts, unsigned int width,
Neil Booth4f881702007-09-26 21:33:42 +00001735 bool isSigned,
1736 roundingMode rounding_mode) const
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001737{
1738 lostFraction lost_fraction;
1739 unsigned int msb, partsCount;
1740 int bits;
1741
Neil Boothcaf19d72007-10-14 10:29:28 +00001742 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001743 partsCount = partCountForBits(width);
1744
Dale Johannesen0edc47a2007-09-25 23:07:07 +00001745 /* Handle the three special cases first. We produce
1746 a deterministic result even for the Invalid cases. */
1747 if (category == fcNaN) {
1748 // Neither sign nor isSigned affects this.
1749 APInt::tcSet(parts, 0, partsCount);
1750 return opInvalidOp;
1751 }
1752 if (category == fcInfinity) {
1753 if (!sign && isSigned)
1754 APInt::tcSetLeastSignificantBits(parts, partsCount, width-1);
1755 else if (!sign && !isSigned)
1756 APInt::tcSetLeastSignificantBits(parts, partsCount, width);
1757 else if (sign && isSigned) {
1758 APInt::tcSetLeastSignificantBits(parts, partsCount, 1);
1759 APInt::tcShiftLeft(parts, partsCount, width-1);
1760 } else // sign && !isSigned
1761 APInt::tcSet(parts, 0, partsCount);
1762 return opInvalidOp;
1763 }
1764 if (category == fcZero) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001765 APInt::tcSet(parts, 0, partsCount);
1766 return opOK;
1767 }
1768
1769 /* Shift the bit pattern so the fraction is lost. */
1770 APFloat tmp(*this);
1771
1772 bits = (int) semantics->precision - 1 - exponent;
1773
1774 if(bits > 0) {
1775 lost_fraction = tmp.shiftSignificandRight(bits);
1776 } else {
Neil Boothe5e01942007-10-14 10:39:51 +00001777 if ((unsigned) -bits >= semantics->precision) {
Dale Johannesen0edc47a2007-09-25 23:07:07 +00001778 // Unrepresentably large.
1779 if (!sign && isSigned)
1780 APInt::tcSetLeastSignificantBits(parts, partsCount, width-1);
1781 else if (!sign && !isSigned)
1782 APInt::tcSetLeastSignificantBits(parts, partsCount, width);
1783 else if (sign && isSigned) {
1784 APInt::tcSetLeastSignificantBits(parts, partsCount, 1);
1785 APInt::tcShiftLeft(parts, partsCount, width-1);
1786 } else // sign && !isSigned
1787 APInt::tcSet(parts, 0, partsCount);
1788 return (opStatus)(opOverflow | opInexact);
1789 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001790 tmp.shiftSignificandLeft(-bits);
1791 lost_fraction = lfExactlyZero;
1792 }
1793
1794 if(lost_fraction != lfExactlyZero
Neil Boothb7dea4c2007-10-03 15:16:41 +00001795 && tmp.roundAwayFromZero(rounding_mode, lost_fraction, 0))
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001796 tmp.incrementSignificand();
1797
1798 msb = tmp.significandMSB();
1799
1800 /* Negative numbers cannot be represented as unsigned. */
1801 if(!isSigned && tmp.sign && msb != -1U)
1802 return opInvalidOp;
1803
1804 /* It takes exponent + 1 bits to represent the truncated floating
1805 point number without its sign. We lose a bit for the sign, but
1806 the maximally negative integer is a special case. */
Neil Booth4f881702007-09-26 21:33:42 +00001807 if(msb + 1 > width) /* !! Not same as msb >= width !! */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001808 return opInvalidOp;
1809
1810 if(isSigned && msb + 1 == width
1811 && (!tmp.sign || tmp.significandLSB() != msb))
1812 return opInvalidOp;
1813
1814 APInt::tcAssign(parts, tmp.significandParts(), partsCount);
1815
1816 if(tmp.sign)
1817 APInt::tcNegate(parts, partsCount);
1818
1819 if(lost_fraction == lfExactlyZero)
1820 return opOK;
1821 else
1822 return opInexact;
1823}
1824
Neil Booth643ce592007-10-07 12:07:53 +00001825/* Convert an unsigned integer SRC to a floating point number,
1826 rounding according to ROUNDING_MODE. The sign of the floating
1827 point number is not modified. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001828APFloat::opStatus
Neil Booth643ce592007-10-07 12:07:53 +00001829APFloat::convertFromUnsignedParts(const integerPart *src,
1830 unsigned int srcCount,
1831 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001832{
Neil Booth5477f852007-10-08 14:39:42 +00001833 unsigned int omsb, precision, dstCount;
Neil Booth643ce592007-10-07 12:07:53 +00001834 integerPart *dst;
Neil Booth5477f852007-10-08 14:39:42 +00001835 lostFraction lost_fraction;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001836
Neil Boothcaf19d72007-10-14 10:29:28 +00001837 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001838 category = fcNormal;
Neil Booth5477f852007-10-08 14:39:42 +00001839 omsb = APInt::tcMSB(src, srcCount) + 1;
Neil Booth643ce592007-10-07 12:07:53 +00001840 dst = significandParts();
1841 dstCount = partCount();
Neil Booth5477f852007-10-08 14:39:42 +00001842 precision = semantics->precision;
Neil Booth643ce592007-10-07 12:07:53 +00001843
Neil Booth5477f852007-10-08 14:39:42 +00001844 /* We want the most significant PRECISON bits of SRC. There may not
1845 be that many; extract what we can. */
1846 if (precision <= omsb) {
1847 exponent = omsb - 1;
Neil Booth643ce592007-10-07 12:07:53 +00001848 lost_fraction = lostFractionThroughTruncation(src, srcCount,
Neil Booth5477f852007-10-08 14:39:42 +00001849 omsb - precision);
1850 APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
1851 } else {
1852 exponent = precision - 1;
1853 lost_fraction = lfExactlyZero;
1854 APInt::tcExtract(dst, dstCount, src, omsb, 0);
Neil Booth643ce592007-10-07 12:07:53 +00001855 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001856
1857 return normalize(rounding_mode, lost_fraction);
1858}
1859
Neil Boothf16c5952007-10-07 12:15:41 +00001860/* Convert a two's complement integer SRC to a floating point number,
1861 rounding according to ROUNDING_MODE. ISSIGNED is true if the
1862 integer is signed, in which case it must be sign-extended. */
1863APFloat::opStatus
1864APFloat::convertFromSignExtendedInteger(const integerPart *src,
1865 unsigned int srcCount,
1866 bool isSigned,
1867 roundingMode rounding_mode)
1868{
1869 opStatus status;
1870
Neil Boothcaf19d72007-10-14 10:29:28 +00001871 assertArithmeticOK(*semantics);
Neil Boothf16c5952007-10-07 12:15:41 +00001872 if (isSigned
1873 && APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) {
1874 integerPart *copy;
1875
1876 /* If we're signed and negative negate a copy. */
1877 sign = true;
1878 copy = new integerPart[srcCount];
1879 APInt::tcAssign(copy, src, srcCount);
1880 APInt::tcNegate(copy, srcCount);
1881 status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
1882 delete [] copy;
1883 } else {
1884 sign = false;
1885 status = convertFromUnsignedParts(src, srcCount, rounding_mode);
1886 }
1887
1888 return status;
1889}
1890
Neil Boothccf596a2007-10-07 11:45:55 +00001891/* FIXME: should this just take a const APInt reference? */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001892APFloat::opStatus
Neil Boothccf596a2007-10-07 11:45:55 +00001893APFloat::convertFromZeroExtendedInteger(const integerPart *parts,
1894 unsigned int width, bool isSigned,
1895 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001896{
Dale Johannesen910993e2007-09-21 22:09:37 +00001897 unsigned int partCount = partCountForBits(width);
Dale Johannesen910993e2007-09-21 22:09:37 +00001898 APInt api = APInt(width, partCount, parts);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001899
1900 sign = false;
Dale Johannesencce23a42007-09-30 18:17:01 +00001901 if(isSigned && APInt::tcExtractBit(parts, width - 1)) {
1902 sign = true;
1903 api = -api;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001904 }
1905
Neil Booth7a7bc0f2007-10-07 12:10:57 +00001906 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001907}
1908
1909APFloat::opStatus
1910APFloat::convertFromHexadecimalString(const char *p,
Neil Booth4f881702007-09-26 21:33:42 +00001911 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001912{
1913 lostFraction lost_fraction;
1914 integerPart *significand;
1915 unsigned int bitPos, partsCount;
1916 const char *dot, *firstSignificantDigit;
1917
1918 zeroSignificand();
1919 exponent = 0;
1920 category = fcNormal;
1921
1922 significand = significandParts();
1923 partsCount = partCount();
1924 bitPos = partsCount * integerPartWidth;
1925
Neil Booth33d4c922007-10-07 08:51:21 +00001926 /* Skip leading zeroes and any (hexa)decimal point. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001927 p = skipLeadingZeroesAndAnyDot(p, &dot);
1928 firstSignificantDigit = p;
1929
1930 for(;;) {
1931 integerPart hex_value;
1932
1933 if(*p == '.') {
1934 assert(dot == 0);
1935 dot = p++;
1936 }
1937
1938 hex_value = hexDigitValue(*p);
1939 if(hex_value == -1U) {
1940 lost_fraction = lfExactlyZero;
1941 break;
1942 }
1943
1944 p++;
1945
1946 /* Store the number whilst 4-bit nibbles remain. */
1947 if(bitPos) {
1948 bitPos -= 4;
1949 hex_value <<= bitPos % integerPartWidth;
1950 significand[bitPos / integerPartWidth] |= hex_value;
1951 } else {
1952 lost_fraction = trailingHexadecimalFraction(p, hex_value);
1953 while(hexDigitValue(*p) != -1U)
Neil Booth4f881702007-09-26 21:33:42 +00001954 p++;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001955 break;
1956 }
1957 }
1958
1959 /* Hex floats require an exponent but not a hexadecimal point. */
1960 assert(*p == 'p' || *p == 'P');
1961
1962 /* Ignore the exponent if we are zero. */
1963 if(p != firstSignificantDigit) {
1964 int expAdjustment;
1965
1966 /* Implicit hexadecimal point? */
1967 if(!dot)
1968 dot = p;
1969
1970 /* Calculate the exponent adjustment implicit in the number of
1971 significant digits. */
1972 expAdjustment = dot - firstSignificantDigit;
1973 if(expAdjustment < 0)
1974 expAdjustment++;
1975 expAdjustment = expAdjustment * 4 - 1;
1976
1977 /* Adjust for writing the significand starting at the most
1978 significant nibble. */
1979 expAdjustment += semantics->precision;
1980 expAdjustment -= partsCount * integerPartWidth;
1981
1982 /* Adjust for the given exponent. */
1983 exponent = totalExponent(p, expAdjustment);
1984 }
1985
1986 return normalize(rounding_mode, lost_fraction);
1987}
1988
1989APFloat::opStatus
Neil Booth96c74712007-10-12 16:02:31 +00001990APFloat::roundSignificandWithExponent(const integerPart *decSigParts,
1991 unsigned sigPartCount, int exp,
1992 roundingMode rounding_mode)
1993{
1994 unsigned int parts, pow5PartCount;
Neil Boothcaf19d72007-10-14 10:29:28 +00001995 fltSemantics calcSemantics = { 32767, -32767, 0, true };
Neil Booth96c74712007-10-12 16:02:31 +00001996 integerPart pow5Parts[maxPowerOfFiveParts];
1997 bool isNearest;
1998
1999 isNearest = (rounding_mode == rmNearestTiesToEven
2000 || rounding_mode == rmNearestTiesToAway);
2001
2002 parts = partCountForBits(semantics->precision + 11);
2003
2004 /* Calculate pow(5, abs(exp)). */
2005 pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp);
2006
2007 for (;; parts *= 2) {
2008 opStatus sigStatus, powStatus;
2009 unsigned int excessPrecision, truncatedBits;
2010
2011 calcSemantics.precision = parts * integerPartWidth - 1;
2012 excessPrecision = calcSemantics.precision - semantics->precision;
2013 truncatedBits = excessPrecision;
2014
2015 APFloat decSig(calcSemantics, fcZero, sign);
2016 APFloat pow5(calcSemantics, fcZero, false);
2017
2018 sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount,
2019 rmNearestTiesToEven);
2020 powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
2021 rmNearestTiesToEven);
2022 /* Add exp, as 10^n = 5^n * 2^n. */
2023 decSig.exponent += exp;
2024
2025 lostFraction calcLostFraction;
2026 integerPart HUerr, HUdistance, powHUerr;
2027
2028 if (exp >= 0) {
2029 /* multiplySignificand leaves the precision-th bit set to 1. */
2030 calcLostFraction = decSig.multiplySignificand(pow5, NULL);
2031 powHUerr = powStatus != opOK;
2032 } else {
2033 calcLostFraction = decSig.divideSignificand(pow5);
2034 /* Denormal numbers have less precision. */
2035 if (decSig.exponent < semantics->minExponent) {
2036 excessPrecision += (semantics->minExponent - decSig.exponent);
2037 truncatedBits = excessPrecision;
2038 if (excessPrecision > calcSemantics.precision)
2039 excessPrecision = calcSemantics.precision;
2040 }
2041 /* Extra half-ulp lost in reciprocal of exponent. */
Neil Boothd1a23d52007-10-13 03:34:08 +00002042 powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0: 2;
Neil Booth96c74712007-10-12 16:02:31 +00002043 }
2044
2045 /* Both multiplySignificand and divideSignificand return the
2046 result with the integer bit set. */
2047 assert (APInt::tcExtractBit
2048 (decSig.significandParts(), calcSemantics.precision - 1) == 1);
2049
2050 HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK,
2051 powHUerr);
2052 HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
2053 excessPrecision, isNearest);
2054
2055 /* Are we guaranteed to round correctly if we truncate? */
2056 if (HUdistance >= HUerr) {
2057 APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
2058 calcSemantics.precision - excessPrecision,
2059 excessPrecision);
2060 /* Take the exponent of decSig. If we tcExtract-ed less bits
2061 above we must adjust our exponent to compensate for the
2062 implicit right shift. */
2063 exponent = (decSig.exponent + semantics->precision
2064 - (calcSemantics.precision - excessPrecision));
2065 calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(),
2066 decSig.partCount(),
2067 truncatedBits);
2068 return normalize(rounding_mode, calcLostFraction);
2069 }
2070 }
2071}
2072
2073APFloat::opStatus
2074APFloat::convertFromDecimalString(const char *p, roundingMode rounding_mode)
2075{
Neil Booth1870f292007-10-14 10:16:12 +00002076 decimalInfo D;
Neil Booth96c74712007-10-12 16:02:31 +00002077 opStatus fs;
2078
Neil Booth1870f292007-10-14 10:16:12 +00002079 /* Scan the text. */
2080 interpretDecimal(p, &D);
Neil Booth96c74712007-10-12 16:02:31 +00002081
Neil Booth1870f292007-10-14 10:16:12 +00002082 if (*D.firstSigDigit == '0') {
Neil Booth96c74712007-10-12 16:02:31 +00002083 category = fcZero;
2084 fs = opOK;
2085 } else {
Neil Booth1870f292007-10-14 10:16:12 +00002086 integerPart *decSignificand;
2087 unsigned int partCount;
Neil Booth96c74712007-10-12 16:02:31 +00002088
Neil Booth1870f292007-10-14 10:16:12 +00002089 /* A tight upper bound on number of bits required to hold an
2090 N-digit decimal integer is N * 256 / 77. Allocate enough space
2091 to hold the full significand, and an extra part required by
2092 tcMultiplyPart. */
2093 partCount = (D.lastSigDigit - D.firstSigDigit) + 1;
2094 partCount = partCountForBits(1 + 256 * partCount / 77);
2095 decSignificand = new integerPart[partCount + 1];
2096 partCount = 0;
Neil Booth96c74712007-10-12 16:02:31 +00002097
Neil Booth1870f292007-10-14 10:16:12 +00002098 /* Convert to binary efficiently - we do almost all multiplication
2099 in an integerPart. When this would overflow do we do a single
2100 bignum multiplication, and then revert again to multiplication
2101 in an integerPart. */
2102 do {
2103 integerPart decValue, val, multiplier;
2104
2105 val = 0;
2106 multiplier = 1;
2107
2108 do {
2109 if (*p == '.')
2110 p++;
2111
2112 decValue = decDigitValue(*p++);
2113 multiplier *= 10;
2114 val = val * 10 + decValue;
2115 /* The maximum number that can be multiplied by ten with any
2116 digit added without overflowing an integerPart. */
2117 } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
2118
2119 /* Multiply out the current part. */
2120 APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
2121 partCount, partCount + 1, false);
2122
2123 /* If we used another part (likely but not guaranteed), increase
2124 the count. */
2125 if (decSignificand[partCount])
2126 partCount++;
2127 } while (p <= D.lastSigDigit);
Neil Booth96c74712007-10-12 16:02:31 +00002128
2129 category = fcNormal;
2130 fs = roundSignificandWithExponent(decSignificand, partCount,
Neil Booth1870f292007-10-14 10:16:12 +00002131 D.exponent, rounding_mode);
Neil Booth96c74712007-10-12 16:02:31 +00002132
Neil Booth1870f292007-10-14 10:16:12 +00002133 delete [] decSignificand;
2134 }
Neil Booth96c74712007-10-12 16:02:31 +00002135
2136 return fs;
2137}
2138
2139APFloat::opStatus
Neil Booth4f881702007-09-26 21:33:42 +00002140APFloat::convertFromString(const char *p, roundingMode rounding_mode)
2141{
Neil Boothcaf19d72007-10-14 10:29:28 +00002142 assertArithmeticOK(*semantics);
2143
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002144 /* Handle a leading minus sign. */
2145 if(*p == '-')
2146 sign = 1, p++;
2147 else
2148 sign = 0;
2149
2150 if(p[0] == '0' && (p[1] == 'x' || p[1] == 'X'))
2151 return convertFromHexadecimalString(p + 2, rounding_mode);
Neil Booth96c74712007-10-12 16:02:31 +00002152 else
2153 return convertFromDecimalString(p, rounding_mode);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002154}
Dale Johannesen343e7702007-08-24 00:56:33 +00002155
Neil Bootha30b0ee2007-10-03 22:26:02 +00002156/* Write out a hexadecimal representation of the floating point value
2157 to DST, which must be of sufficient size, in the C99 form
2158 [-]0xh.hhhhp[+-]d. Return the number of characters written,
2159 excluding the terminating NUL.
2160
2161 If UPPERCASE, the output is in upper case, otherwise in lower case.
2162
2163 HEXDIGITS digits appear altogether, rounding the value if
2164 necessary. If HEXDIGITS is 0, the minimal precision to display the
2165 number precisely is used instead. If nothing would appear after
2166 the decimal point it is suppressed.
2167
2168 The decimal exponent is always printed and has at least one digit.
2169 Zero values display an exponent of zero. Infinities and NaNs
2170 appear as "infinity" or "nan" respectively.
2171
2172 The above rules are as specified by C99. There is ambiguity about
2173 what the leading hexadecimal digit should be. This implementation
2174 uses whatever is necessary so that the exponent is displayed as
2175 stored. This implies the exponent will fall within the IEEE format
2176 range, and the leading hexadecimal digit will be 0 (for denormals),
2177 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
2178 any other digits zero).
2179*/
2180unsigned int
2181APFloat::convertToHexString(char *dst, unsigned int hexDigits,
2182 bool upperCase, roundingMode rounding_mode) const
2183{
2184 char *p;
2185
Neil Boothcaf19d72007-10-14 10:29:28 +00002186 assertArithmeticOK(*semantics);
2187
Neil Bootha30b0ee2007-10-03 22:26:02 +00002188 p = dst;
2189 if (sign)
2190 *dst++ = '-';
2191
2192 switch (category) {
2193 case fcInfinity:
2194 memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
2195 dst += sizeof infinityL - 1;
2196 break;
2197
2198 case fcNaN:
2199 memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
2200 dst += sizeof NaNU - 1;
2201 break;
2202
2203 case fcZero:
2204 *dst++ = '0';
2205 *dst++ = upperCase ? 'X': 'x';
2206 *dst++ = '0';
2207 if (hexDigits > 1) {
2208 *dst++ = '.';
2209 memset (dst, '0', hexDigits - 1);
2210 dst += hexDigits - 1;
2211 }
2212 *dst++ = upperCase ? 'P': 'p';
2213 *dst++ = '0';
2214 break;
2215
2216 case fcNormal:
2217 dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
2218 break;
2219 }
2220
2221 *dst = 0;
2222
2223 return dst - p;
2224}
2225
2226/* Does the hard work of outputting the correctly rounded hexadecimal
2227 form of a normal floating point number with the specified number of
2228 hexadecimal digits. If HEXDIGITS is zero the minimum number of
2229 digits necessary to print the value precisely is output. */
2230char *
2231APFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
2232 bool upperCase,
2233 roundingMode rounding_mode) const
2234{
2235 unsigned int count, valueBits, shift, partsCount, outputDigits;
2236 const char *hexDigitChars;
2237 const integerPart *significand;
2238 char *p;
2239 bool roundUp;
2240
2241 *dst++ = '0';
2242 *dst++ = upperCase ? 'X': 'x';
2243
2244 roundUp = false;
2245 hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower;
2246
2247 significand = significandParts();
2248 partsCount = partCount();
2249
2250 /* +3 because the first digit only uses the single integer bit, so
2251 we have 3 virtual zero most-significant-bits. */
2252 valueBits = semantics->precision + 3;
2253 shift = integerPartWidth - valueBits % integerPartWidth;
2254
2255 /* The natural number of digits required ignoring trailing
2256 insignificant zeroes. */
2257 outputDigits = (valueBits - significandLSB () + 3) / 4;
2258
2259 /* hexDigits of zero means use the required number for the
2260 precision. Otherwise, see if we are truncating. If we are,
Neil Booth978661d2007-10-06 00:24:48 +00002261 find out if we need to round away from zero. */
Neil Bootha30b0ee2007-10-03 22:26:02 +00002262 if (hexDigits) {
2263 if (hexDigits < outputDigits) {
2264 /* We are dropping non-zero bits, so need to check how to round.
2265 "bits" is the number of dropped bits. */
2266 unsigned int bits;
2267 lostFraction fraction;
2268
2269 bits = valueBits - hexDigits * 4;
2270 fraction = lostFractionThroughTruncation (significand, partsCount, bits);
2271 roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
2272 }
2273 outputDigits = hexDigits;
2274 }
2275
2276 /* Write the digits consecutively, and start writing in the location
2277 of the hexadecimal point. We move the most significant digit
2278 left and add the hexadecimal point later. */
2279 p = ++dst;
2280
2281 count = (valueBits + integerPartWidth - 1) / integerPartWidth;
2282
2283 while (outputDigits && count) {
2284 integerPart part;
2285
2286 /* Put the most significant integerPartWidth bits in "part". */
2287 if (--count == partsCount)
2288 part = 0; /* An imaginary higher zero part. */
2289 else
2290 part = significand[count] << shift;
2291
2292 if (count && shift)
2293 part |= significand[count - 1] >> (integerPartWidth - shift);
2294
2295 /* Convert as much of "part" to hexdigits as we can. */
2296 unsigned int curDigits = integerPartWidth / 4;
2297
2298 if (curDigits > outputDigits)
2299 curDigits = outputDigits;
2300 dst += partAsHex (dst, part, curDigits, hexDigitChars);
2301 outputDigits -= curDigits;
2302 }
2303
2304 if (roundUp) {
2305 char *q = dst;
2306
2307 /* Note that hexDigitChars has a trailing '0'. */
2308 do {
2309 q--;
2310 *q = hexDigitChars[hexDigitValue (*q) + 1];
Neil Booth978661d2007-10-06 00:24:48 +00002311 } while (*q == '0');
2312 assert (q >= p);
Neil Bootha30b0ee2007-10-03 22:26:02 +00002313 } else {
2314 /* Add trailing zeroes. */
2315 memset (dst, '0', outputDigits);
2316 dst += outputDigits;
2317 }
2318
2319 /* Move the most significant digit to before the point, and if there
2320 is something after the decimal point add it. This must come
2321 after rounding above. */
2322 p[-1] = p[0];
2323 if (dst -1 == p)
2324 dst--;
2325 else
2326 p[0] = '.';
2327
2328 /* Finally output the exponent. */
2329 *dst++ = upperCase ? 'P': 'p';
2330
Neil Booth92f7e8d2007-10-06 07:29:25 +00002331 return writeSignedDecimal (dst, exponent);
Neil Bootha30b0ee2007-10-03 22:26:02 +00002332}
2333
Dale Johannesen343e7702007-08-24 00:56:33 +00002334// For good performance it is desirable for different APFloats
2335// to produce different integers.
2336uint32_t
Neil Booth4f881702007-09-26 21:33:42 +00002337APFloat::getHashValue() const
2338{
Dale Johannesen343e7702007-08-24 00:56:33 +00002339 if (category==fcZero) return sign<<8 | semantics->precision ;
2340 else if (category==fcInfinity) return sign<<9 | semantics->precision;
Dale Johanneseneaf08942007-08-31 04:03:46 +00002341 else if (category==fcNaN) return 1<<10 | semantics->precision;
Dale Johannesen343e7702007-08-24 00:56:33 +00002342 else {
2343 uint32_t hash = sign<<11 | semantics->precision | exponent<<12;
2344 const integerPart* p = significandParts();
2345 for (int i=partCount(); i>0; i--, p++)
2346 hash ^= ((uint32_t)*p) ^ (*p)>>32;
2347 return hash;
2348 }
2349}
2350
2351// Conversion from APFloat to/from host float/double. It may eventually be
2352// possible to eliminate these and have everybody deal with APFloats, but that
2353// will take a while. This approach will not easily extend to long double.
Dale Johannesena72a5a02007-09-20 23:47:58 +00002354// Current implementation requires integerPartWidth==64, which is correct at
2355// the moment but could be made more general.
Dale Johannesen343e7702007-08-24 00:56:33 +00002356
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002357// Denormals have exponent minExponent in APFloat, but minExponent-1 in
Dale Johannesena72a5a02007-09-20 23:47:58 +00002358// the actual IEEE respresentations. We compensate for that here.
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002359
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002360APInt
Neil Booth4f881702007-09-26 21:33:42 +00002361APFloat::convertF80LongDoubleAPFloatToAPInt() const
2362{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002363 assert(semantics == (const llvm::fltSemantics* const)&x87DoubleExtended);
Dale Johannesena72a5a02007-09-20 23:47:58 +00002364 assert (partCount()==2);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002365
2366 uint64_t myexponent, mysignificand;
2367
2368 if (category==fcNormal) {
2369 myexponent = exponent+16383; //bias
Dale Johannesena72a5a02007-09-20 23:47:58 +00002370 mysignificand = significandParts()[0];
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002371 if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
2372 myexponent = 0; // denormal
2373 } else if (category==fcZero) {
2374 myexponent = 0;
2375 mysignificand = 0;
2376 } else if (category==fcInfinity) {
2377 myexponent = 0x7fff;
2378 mysignificand = 0x8000000000000000ULL;
Chris Lattnera11ef822007-10-06 06:13:42 +00002379 } else {
2380 assert(category == fcNaN && "Unknown category");
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002381 myexponent = 0x7fff;
Dale Johannesena72a5a02007-09-20 23:47:58 +00002382 mysignificand = significandParts()[0];
Chris Lattnera11ef822007-10-06 06:13:42 +00002383 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002384
2385 uint64_t words[2];
Neil Booth4f881702007-09-26 21:33:42 +00002386 words[0] = (((uint64_t)sign & 1) << 63) |
2387 ((myexponent & 0x7fff) << 48) |
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002388 ((mysignificand >>16) & 0xffffffffffffLL);
2389 words[1] = mysignificand & 0xffff;
Chris Lattnera11ef822007-10-06 06:13:42 +00002390 return APInt(80, 2, words);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002391}
2392
2393APInt
Dale Johannesena471c2e2007-10-11 18:07:22 +00002394APFloat::convertPPCDoubleDoubleAPFloatToAPInt() const
2395{
2396 assert(semantics == (const llvm::fltSemantics* const)&PPCDoubleDouble);
2397 assert (partCount()==2);
2398
2399 uint64_t myexponent, mysignificand, myexponent2, mysignificand2;
2400
2401 if (category==fcNormal) {
2402 myexponent = exponent + 1023; //bias
2403 myexponent2 = exponent2 + 1023;
2404 mysignificand = significandParts()[0];
2405 mysignificand2 = significandParts()[1];
2406 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2407 myexponent = 0; // denormal
2408 if (myexponent2==1 && !(mysignificand2 & 0x10000000000000LL))
2409 myexponent2 = 0; // denormal
2410 } else if (category==fcZero) {
2411 myexponent = 0;
2412 mysignificand = 0;
2413 myexponent2 = 0;
2414 mysignificand2 = 0;
2415 } else if (category==fcInfinity) {
2416 myexponent = 0x7ff;
2417 myexponent2 = 0;
2418 mysignificand = 0;
2419 mysignificand2 = 0;
2420 } else {
2421 assert(category == fcNaN && "Unknown category");
2422 myexponent = 0x7ff;
2423 mysignificand = significandParts()[0];
2424 myexponent2 = exponent2;
2425 mysignificand2 = significandParts()[1];
2426 }
2427
2428 uint64_t words[2];
2429 words[0] = (((uint64_t)sign & 1) << 63) |
2430 ((myexponent & 0x7ff) << 52) |
2431 (mysignificand & 0xfffffffffffffLL);
2432 words[1] = (((uint64_t)sign2 & 1) << 63) |
2433 ((myexponent2 & 0x7ff) << 52) |
2434 (mysignificand2 & 0xfffffffffffffLL);
2435 return APInt(128, 2, words);
2436}
2437
2438APInt
Neil Booth4f881702007-09-26 21:33:42 +00002439APFloat::convertDoubleAPFloatToAPInt() const
2440{
Dan Gohmancb648f92007-09-14 20:08:19 +00002441 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble);
Dale Johannesen343e7702007-08-24 00:56:33 +00002442 assert (partCount()==1);
2443
Dale Johanneseneaf08942007-08-31 04:03:46 +00002444 uint64_t myexponent, mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00002445
2446 if (category==fcNormal) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002447 myexponent = exponent+1023; //bias
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002448 mysignificand = *significandParts();
2449 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2450 myexponent = 0; // denormal
Dale Johannesen343e7702007-08-24 00:56:33 +00002451 } else if (category==fcZero) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002452 myexponent = 0;
2453 mysignificand = 0;
2454 } else if (category==fcInfinity) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002455 myexponent = 0x7ff;
2456 mysignificand = 0;
Chris Lattnera11ef822007-10-06 06:13:42 +00002457 } else {
2458 assert(category == fcNaN && "Unknown category!");
Dale Johannesen343e7702007-08-24 00:56:33 +00002459 myexponent = 0x7ff;
Dale Johanneseneaf08942007-08-31 04:03:46 +00002460 mysignificand = *significandParts();
Chris Lattnera11ef822007-10-06 06:13:42 +00002461 }
Dale Johannesen343e7702007-08-24 00:56:33 +00002462
Chris Lattnera11ef822007-10-06 06:13:42 +00002463 return APInt(64, (((((uint64_t)sign & 1) << 63) |
2464 ((myexponent & 0x7ff) << 52) |
2465 (mysignificand & 0xfffffffffffffLL))));
Dale Johannesen343e7702007-08-24 00:56:33 +00002466}
2467
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002468APInt
Neil Booth4f881702007-09-26 21:33:42 +00002469APFloat::convertFloatAPFloatToAPInt() const
2470{
Dan Gohmancb648f92007-09-14 20:08:19 +00002471 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle);
Dale Johannesen343e7702007-08-24 00:56:33 +00002472 assert (partCount()==1);
Neil Booth4f881702007-09-26 21:33:42 +00002473
Dale Johanneseneaf08942007-08-31 04:03:46 +00002474 uint32_t myexponent, mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00002475
2476 if (category==fcNormal) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002477 myexponent = exponent+127; //bias
2478 mysignificand = *significandParts();
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002479 if (myexponent == 1 && !(mysignificand & 0x400000))
2480 myexponent = 0; // denormal
Dale Johannesen343e7702007-08-24 00:56:33 +00002481 } else if (category==fcZero) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002482 myexponent = 0;
2483 mysignificand = 0;
2484 } else if (category==fcInfinity) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002485 myexponent = 0xff;
2486 mysignificand = 0;
Chris Lattnera11ef822007-10-06 06:13:42 +00002487 } else {
2488 assert(category == fcNaN && "Unknown category!");
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002489 myexponent = 0xff;
Dale Johanneseneaf08942007-08-31 04:03:46 +00002490 mysignificand = *significandParts();
Chris Lattnera11ef822007-10-06 06:13:42 +00002491 }
Dale Johannesen343e7702007-08-24 00:56:33 +00002492
Chris Lattnera11ef822007-10-06 06:13:42 +00002493 return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) |
2494 (mysignificand & 0x7fffff)));
Dale Johannesen343e7702007-08-24 00:56:33 +00002495}
2496
Dale Johannesena471c2e2007-10-11 18:07:22 +00002497// This function creates an APInt that is just a bit map of the floating
2498// point constant as it would appear in memory. It is not a conversion,
2499// and treating the result as a normal integer is unlikely to be useful.
2500
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002501APInt
Neil Booth4f881702007-09-26 21:33:42 +00002502APFloat::convertToAPInt() const
2503{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002504 if (semantics == (const llvm::fltSemantics* const)&IEEEsingle)
2505 return convertFloatAPFloatToAPInt();
Chris Lattnera11ef822007-10-06 06:13:42 +00002506
2507 if (semantics == (const llvm::fltSemantics* const)&IEEEdouble)
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002508 return convertDoubleAPFloatToAPInt();
Neil Booth4f881702007-09-26 21:33:42 +00002509
Dale Johannesena471c2e2007-10-11 18:07:22 +00002510 if (semantics == (const llvm::fltSemantics* const)&PPCDoubleDouble)
2511 return convertPPCDoubleDoubleAPFloatToAPInt();
2512
Chris Lattnera11ef822007-10-06 06:13:42 +00002513 assert(semantics == (const llvm::fltSemantics* const)&x87DoubleExtended &&
2514 "unknown format!");
2515 return convertF80LongDoubleAPFloatToAPInt();
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002516}
2517
Neil Booth4f881702007-09-26 21:33:42 +00002518float
2519APFloat::convertToFloat() const
2520{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002521 assert(semantics == (const llvm::fltSemantics* const)&IEEEsingle);
2522 APInt api = convertToAPInt();
2523 return api.bitsToFloat();
2524}
2525
Neil Booth4f881702007-09-26 21:33:42 +00002526double
2527APFloat::convertToDouble() const
2528{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002529 assert(semantics == (const llvm::fltSemantics* const)&IEEEdouble);
2530 APInt api = convertToAPInt();
2531 return api.bitsToDouble();
2532}
2533
2534/// Integer bit is explicit in this format. Current Intel book does not
2535/// define meaning of:
2536/// exponent = all 1's, integer bit not set.
2537/// exponent = 0, integer bit set. (formerly "psuedodenormals")
2538/// exponent!=0 nor all 1's, integer bit not set. (formerly "unnormals")
2539void
Neil Booth4f881702007-09-26 21:33:42 +00002540APFloat::initFromF80LongDoubleAPInt(const APInt &api)
2541{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002542 assert(api.getBitWidth()==80);
2543 uint64_t i1 = api.getRawData()[0];
2544 uint64_t i2 = api.getRawData()[1];
2545 uint64_t myexponent = (i1 >> 48) & 0x7fff;
2546 uint64_t mysignificand = ((i1 << 16) & 0xffffffffffff0000ULL) |
2547 (i2 & 0xffff);
2548
2549 initialize(&APFloat::x87DoubleExtended);
Dale Johannesena72a5a02007-09-20 23:47:58 +00002550 assert(partCount()==2);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002551
2552 sign = i1>>63;
2553 if (myexponent==0 && mysignificand==0) {
2554 // exponent, significand meaningless
2555 category = fcZero;
2556 } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
2557 // exponent, significand meaningless
2558 category = fcInfinity;
2559 } else if (myexponent==0x7fff && mysignificand!=0x8000000000000000ULL) {
2560 // exponent meaningless
2561 category = fcNaN;
Dale Johannesena72a5a02007-09-20 23:47:58 +00002562 significandParts()[0] = mysignificand;
2563 significandParts()[1] = 0;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002564 } else {
2565 category = fcNormal;
2566 exponent = myexponent - 16383;
Dale Johannesena72a5a02007-09-20 23:47:58 +00002567 significandParts()[0] = mysignificand;
2568 significandParts()[1] = 0;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002569 if (myexponent==0) // denormal
2570 exponent = -16382;
Neil Booth4f881702007-09-26 21:33:42 +00002571 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002572}
2573
2574void
Dale Johannesena471c2e2007-10-11 18:07:22 +00002575APFloat::initFromPPCDoubleDoubleAPInt(const APInt &api)
2576{
2577 assert(api.getBitWidth()==128);
2578 uint64_t i1 = api.getRawData()[0];
2579 uint64_t i2 = api.getRawData()[1];
2580 uint64_t myexponent = (i1 >> 52) & 0x7ff;
2581 uint64_t mysignificand = i1 & 0xfffffffffffffLL;
2582 uint64_t myexponent2 = (i2 >> 52) & 0x7ff;
2583 uint64_t mysignificand2 = i2 & 0xfffffffffffffLL;
2584
2585 initialize(&APFloat::PPCDoubleDouble);
2586 assert(partCount()==2);
2587
2588 sign = i1>>63;
2589 sign2 = i2>>63;
2590 if (myexponent==0 && mysignificand==0) {
2591 // exponent, significand meaningless
2592 // exponent2 and significand2 are required to be 0; we don't check
2593 category = fcZero;
2594 } else if (myexponent==0x7ff && mysignificand==0) {
2595 // exponent, significand meaningless
2596 // exponent2 and significand2 are required to be 0; we don't check
2597 category = fcInfinity;
2598 } else if (myexponent==0x7ff && mysignificand!=0) {
2599 // exponent meaningless. So is the whole second word, but keep it
2600 // for determinism.
2601 category = fcNaN;
2602 exponent2 = myexponent2;
2603 significandParts()[0] = mysignificand;
2604 significandParts()[1] = mysignificand2;
2605 } else {
2606 category = fcNormal;
2607 // Note there is no category2; the second word is treated as if it is
2608 // fcNormal, although it might be something else considered by itself.
2609 exponent = myexponent - 1023;
2610 exponent2 = myexponent2 - 1023;
2611 significandParts()[0] = mysignificand;
2612 significandParts()[1] = mysignificand2;
2613 if (myexponent==0) // denormal
2614 exponent = -1022;
2615 else
2616 significandParts()[0] |= 0x10000000000000LL; // integer bit
2617 if (myexponent2==0)
2618 exponent2 = -1022;
2619 else
2620 significandParts()[1] |= 0x10000000000000LL; // integer bit
2621 }
2622}
2623
2624void
Neil Booth4f881702007-09-26 21:33:42 +00002625APFloat::initFromDoubleAPInt(const APInt &api)
2626{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002627 assert(api.getBitWidth()==64);
2628 uint64_t i = *api.getRawData();
Dale Johannesend3b51fd2007-08-24 05:08:11 +00002629 uint64_t myexponent = (i >> 52) & 0x7ff;
2630 uint64_t mysignificand = i & 0xfffffffffffffLL;
2631
Dale Johannesen343e7702007-08-24 00:56:33 +00002632 initialize(&APFloat::IEEEdouble);
Dale Johannesen343e7702007-08-24 00:56:33 +00002633 assert(partCount()==1);
2634
Dale Johanneseneaf08942007-08-31 04:03:46 +00002635 sign = i>>63;
Dale Johannesen343e7702007-08-24 00:56:33 +00002636 if (myexponent==0 && mysignificand==0) {
2637 // exponent, significand meaningless
2638 category = fcZero;
Dale Johannesen343e7702007-08-24 00:56:33 +00002639 } else if (myexponent==0x7ff && mysignificand==0) {
2640 // exponent, significand meaningless
2641 category = fcInfinity;
Dale Johanneseneaf08942007-08-31 04:03:46 +00002642 } else if (myexponent==0x7ff && mysignificand!=0) {
2643 // exponent meaningless
2644 category = fcNaN;
2645 *significandParts() = mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00002646 } else {
Dale Johannesen343e7702007-08-24 00:56:33 +00002647 category = fcNormal;
2648 exponent = myexponent - 1023;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002649 *significandParts() = mysignificand;
2650 if (myexponent==0) // denormal
2651 exponent = -1022;
2652 else
2653 *significandParts() |= 0x10000000000000LL; // integer bit
Neil Booth4f881702007-09-26 21:33:42 +00002654 }
Dale Johannesen343e7702007-08-24 00:56:33 +00002655}
2656
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002657void
Neil Booth4f881702007-09-26 21:33:42 +00002658APFloat::initFromFloatAPInt(const APInt & api)
2659{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002660 assert(api.getBitWidth()==32);
2661 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesend3b51fd2007-08-24 05:08:11 +00002662 uint32_t myexponent = (i >> 23) & 0xff;
2663 uint32_t mysignificand = i & 0x7fffff;
2664
Dale Johannesen343e7702007-08-24 00:56:33 +00002665 initialize(&APFloat::IEEEsingle);
Dale Johannesen343e7702007-08-24 00:56:33 +00002666 assert(partCount()==1);
2667
Dale Johanneseneaf08942007-08-31 04:03:46 +00002668 sign = i >> 31;
Dale Johannesen343e7702007-08-24 00:56:33 +00002669 if (myexponent==0 && mysignificand==0) {
2670 // exponent, significand meaningless
2671 category = fcZero;
Dale Johannesen343e7702007-08-24 00:56:33 +00002672 } else if (myexponent==0xff && mysignificand==0) {
2673 // exponent, significand meaningless
2674 category = fcInfinity;
Dale Johannesen902ff942007-09-25 17:25:00 +00002675 } else if (myexponent==0xff && mysignificand!=0) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002676 // sign, exponent, significand meaningless
Dale Johanneseneaf08942007-08-31 04:03:46 +00002677 category = fcNaN;
2678 *significandParts() = mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00002679 } else {
2680 category = fcNormal;
Dale Johannesen343e7702007-08-24 00:56:33 +00002681 exponent = myexponent - 127; //bias
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002682 *significandParts() = mysignificand;
2683 if (myexponent==0) // denormal
2684 exponent = -126;
2685 else
2686 *significandParts() |= 0x800000; // integer bit
Dale Johannesen343e7702007-08-24 00:56:33 +00002687 }
2688}
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002689
2690/// Treat api as containing the bits of a floating point number. Currently
Dale Johannesena471c2e2007-10-11 18:07:22 +00002691/// we infer the floating point type from the size of the APInt. The
2692/// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful
2693/// when the size is anything else).
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002694void
Dale Johannesena471c2e2007-10-11 18:07:22 +00002695APFloat::initFromAPInt(const APInt& api, bool isIEEE)
Neil Booth4f881702007-09-26 21:33:42 +00002696{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002697 if (api.getBitWidth() == 32)
2698 return initFromFloatAPInt(api);
2699 else if (api.getBitWidth()==64)
2700 return initFromDoubleAPInt(api);
2701 else if (api.getBitWidth()==80)
2702 return initFromF80LongDoubleAPInt(api);
Dale Johannesena471c2e2007-10-11 18:07:22 +00002703 else if (api.getBitWidth()==128 && !isIEEE)
2704 return initFromPPCDoubleDoubleAPInt(api);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002705 else
2706 assert(0);
2707}
2708
Dale Johannesena471c2e2007-10-11 18:07:22 +00002709APFloat::APFloat(const APInt& api, bool isIEEE)
Neil Booth4f881702007-09-26 21:33:42 +00002710{
Dale Johannesena471c2e2007-10-11 18:07:22 +00002711 initFromAPInt(api, isIEEE);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002712}
2713
Neil Booth4f881702007-09-26 21:33:42 +00002714APFloat::APFloat(float f)
2715{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002716 APInt api = APInt(32, 0);
2717 initFromAPInt(api.floatToBits(f));
2718}
2719
Neil Booth4f881702007-09-26 21:33:42 +00002720APFloat::APFloat(double d)
2721{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002722 APInt api = APInt(64, 0);
2723 initFromAPInt(api.doubleToBits(d));
2724}