blob: 4a24b487952a5e4cf6c4d4ab9a0fbda885e3173b [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;
Chris Lattnerb39cdde2007-08-20 22:49:32 +000043 };
44
Neil Booth5b8e0c52007-10-12 15:35:10 +000045 const fltSemantics APFloat::IEEEsingle = { 127, -126, 24 };
46 const fltSemantics APFloat::IEEEdouble = { 1023, -1022, 53 };
47 const fltSemantics APFloat::IEEEquad = { 16383, -16382, 113 };
48 const fltSemantics APFloat::x87DoubleExtended = { 16383, -16382, 64 };
49 const fltSemantics APFloat::Bogus = { 0, 0, 0 };
Dale Johannesena471c2e2007-10-11 18:07:22 +000050
51 // The PowerPC format consists of two doubles. It does not map cleanly
52 // onto the usual format above. For now only storage of constants of
53 // this type is supported, no arithmetic.
Neil Booth5b8e0c52007-10-12 15:35:10 +000054 const fltSemantics APFloat::PPCDoubleDouble = { 1023, -1022, 106 };
Neil Booth96c74712007-10-12 16:02:31 +000055
56 /* A tight upper bound on number of parts required to hold the value
57 pow(5, power) is
58
59 power * 1024 / (441 * integerPartWidth) + 1
60
61 However, whilst the result may require only this many parts,
62 because we are multiplying two values to get it, the
63 multiplication may require an extra part with the excess part
64 being zero (consider the trivial case of 1 * 1, tcFullMultiply
65 requires two parts to hold the single-part result). So we add an
66 extra one to guarantee enough space whilst multiplying. */
67 const unsigned int maxExponent = 16383;
68 const unsigned int maxPrecision = 113;
69 const unsigned int maxPowerOfFiveExponent = maxExponent + maxPrecision - 1;
70 const unsigned int maxPowerOfFiveParts = 2 + ((maxPowerOfFiveExponent * 1024)
71 / (441 * integerPartWidth));
Chris Lattnerb39cdde2007-08-20 22:49:32 +000072}
73
74/* Put a bunch of private, handy routines in an anonymous namespace. */
75namespace {
76
77 inline unsigned int
78 partCountForBits(unsigned int bits)
79 {
80 return ((bits) + integerPartWidth - 1) / integerPartWidth;
81 }
82
Neil Booth1870f292007-10-14 10:16:12 +000083 /* Returns 0U-9U. Return values >= 10U are not digits. */
84 inline unsigned int
85 decDigitValue(unsigned int c)
Chris Lattnerb39cdde2007-08-20 22:49:32 +000086 {
Neil Booth1870f292007-10-14 10:16:12 +000087 return c - '0';
Chris Lattnerb39cdde2007-08-20 22:49:32 +000088 }
89
90 unsigned int
Neil Booth96c74712007-10-12 16:02:31 +000091 hexDigitValue(unsigned int c)
Chris Lattnerb39cdde2007-08-20 22:49:32 +000092 {
93 unsigned int r;
94
95 r = c - '0';
96 if(r <= 9)
97 return r;
98
99 r = c - 'A';
100 if(r <= 5)
101 return r + 10;
102
103 r = c - 'a';
104 if(r <= 5)
105 return r + 10;
106
107 return -1U;
108 }
109
Neil Booth1870f292007-10-14 10:16:12 +0000110 /* Return the value of a decimal exponent of the form
111 [+-]ddddddd.
112
113 If the exponent overflows, returns a large exponent with the
114 appropriate sign. */
115 static int
116 readExponent(const char *p)
117 {
118 bool isNegative;
119 unsigned int absExponent;
120 const unsigned int overlargeExponent = 24000; /* FIXME. */
121
122 isNegative = (*p == '-');
123 if (*p == '-' || *p == '+')
124 p++;
125
126 absExponent = decDigitValue(*p++);
127 assert (absExponent < 10U);
128
129 for (;;) {
130 unsigned int value;
131
132 value = decDigitValue(*p);
133 if (value >= 10U)
134 break;
135
136 p++;
137 value += absExponent * 10;
138 if (absExponent >= overlargeExponent) {
139 absExponent = overlargeExponent;
140 break;
141 }
142 absExponent = value;
143 }
144
145 if (isNegative)
146 return -(int) absExponent;
147 else
148 return (int) absExponent;
149 }
150
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000151 /* This is ugly and needs cleaning up, but I don't immediately see
152 how whilst remaining safe. */
153 static int
154 totalExponent(const char *p, int exponentAdjustment)
155 {
156 integerPart unsignedExponent;
157 bool negative, overflow;
158 long exponent;
159
160 /* Move past the exponent letter and sign to the digits. */
161 p++;
162 negative = *p == '-';
163 if(*p == '-' || *p == '+')
164 p++;
165
166 unsignedExponent = 0;
167 overflow = false;
168 for(;;) {
169 unsigned int value;
170
Neil Booth1870f292007-10-14 10:16:12 +0000171 value = decDigitValue(*p);
172 if(value >= 10U)
Neil Booth4f881702007-09-26 21:33:42 +0000173 break;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000174
175 p++;
176 unsignedExponent = unsignedExponent * 10 + value;
177 if(unsignedExponent > 65535)
Neil Booth4f881702007-09-26 21:33:42 +0000178 overflow = true;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000179 }
180
181 if(exponentAdjustment > 65535 || exponentAdjustment < -65536)
182 overflow = true;
183
184 if(!overflow) {
185 exponent = unsignedExponent;
186 if(negative)
Neil Booth4f881702007-09-26 21:33:42 +0000187 exponent = -exponent;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000188 exponent += exponentAdjustment;
189 if(exponent > 65535 || exponent < -65536)
Neil Booth4f881702007-09-26 21:33:42 +0000190 overflow = true;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000191 }
192
193 if(overflow)
194 exponent = negative ? -65536: 65535;
195
196 return exponent;
197 }
198
199 const char *
200 skipLeadingZeroesAndAnyDot(const char *p, const char **dot)
201 {
202 *dot = 0;
203 while(*p == '0')
204 p++;
205
206 if(*p == '.') {
207 *dot = p++;
208 while(*p == '0')
Neil Booth4f881702007-09-26 21:33:42 +0000209 p++;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000210 }
211
212 return p;
213 }
214
Neil Booth1870f292007-10-14 10:16:12 +0000215 /* Given a normal decimal floating point number of the form
216
217 dddd.dddd[eE][+-]ddd
218
219 where the decimal point and exponent are optional, fill out the
220 structure D. If the value is zero, V->firstSigDigit
221 points to a zero, and the return exponent is zero. */
222 struct decimalInfo {
223 const char *firstSigDigit;
224 const char *lastSigDigit;
225 int exponent;
226 };
227
228 void
229 interpretDecimal(const char *p, decimalInfo *D)
230 {
231 const char *dot;
232
233 p = skipLeadingZeroesAndAnyDot (p, &dot);
234
235 D->firstSigDigit = p;
236 D->exponent = 0;
237
238 for (;;) {
239 if (*p == '.') {
240 assert(dot == 0);
241 dot = p++;
242 }
243 if (decDigitValue(*p) >= 10U)
244 break;
245 p++;
246 }
247
248 /* If number is all zerooes accept any exponent. */
249 if (p != D->firstSigDigit) {
250 if (*p == 'e' || *p == 'E')
251 D->exponent = readExponent(p + 1);
252
253 /* Implied decimal point? */
254 if (!dot)
255 dot = p;
256
257 /* Drop insignificant trailing zeroes. */
258 do
259 do
260 p--;
261 while (*p == '0');
262 while (*p == '.');
263
264 /* Adjust the specified exponent for any decimal point. */
265 D->exponent += (dot - p) - (dot > p);
266 }
267
268 D->lastSigDigit = p;
269 }
270
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000271 /* Return the trailing fraction of a hexadecimal number.
272 DIGITVALUE is the first hex digit of the fraction, P points to
273 the next digit. */
274 lostFraction
275 trailingHexadecimalFraction(const char *p, unsigned int digitValue)
276 {
277 unsigned int hexDigit;
278
279 /* If the first trailing digit isn't 0 or 8 we can work out the
280 fraction immediately. */
281 if(digitValue > 8)
282 return lfMoreThanHalf;
283 else if(digitValue < 8 && digitValue > 0)
284 return lfLessThanHalf;
285
286 /* Otherwise we need to find the first non-zero digit. */
287 while(*p == '0')
288 p++;
289
290 hexDigit = hexDigitValue(*p);
291
292 /* If we ran off the end it is exactly zero or one-half, otherwise
293 a little more. */
294 if(hexDigit == -1U)
295 return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
296 else
297 return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf;
298 }
299
Neil Boothb7dea4c2007-10-03 15:16:41 +0000300 /* Return the fraction lost were a bignum truncated losing the least
301 significant BITS bits. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000302 lostFraction
Neil Bootha30b0ee2007-10-03 22:26:02 +0000303 lostFractionThroughTruncation(const integerPart *parts,
Neil Booth4f881702007-09-26 21:33:42 +0000304 unsigned int partCount,
305 unsigned int bits)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000306 {
307 unsigned int lsb;
308
309 lsb = APInt::tcLSB(parts, partCount);
310
311 /* Note this is guaranteed true if bits == 0, or LSB == -1U. */
312 if(bits <= lsb)
313 return lfExactlyZero;
314 if(bits == lsb + 1)
315 return lfExactlyHalf;
316 if(bits <= partCount * integerPartWidth
317 && APInt::tcExtractBit(parts, bits - 1))
318 return lfMoreThanHalf;
319
320 return lfLessThanHalf;
321 }
322
323 /* Shift DST right BITS bits noting lost fraction. */
324 lostFraction
325 shiftRight(integerPart *dst, unsigned int parts, unsigned int bits)
326 {
327 lostFraction lost_fraction;
328
329 lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
330
331 APInt::tcShiftRight(dst, parts, bits);
332
333 return lost_fraction;
334 }
Neil Bootha30b0ee2007-10-03 22:26:02 +0000335
Neil Booth33d4c922007-10-07 08:51:21 +0000336 /* Combine the effect of two lost fractions. */
337 lostFraction
338 combineLostFractions(lostFraction moreSignificant,
339 lostFraction lessSignificant)
340 {
341 if(lessSignificant != lfExactlyZero) {
342 if(moreSignificant == lfExactlyZero)
343 moreSignificant = lfLessThanHalf;
344 else if(moreSignificant == lfExactlyHalf)
345 moreSignificant = lfMoreThanHalf;
346 }
347
348 return moreSignificant;
349 }
Neil Bootha30b0ee2007-10-03 22:26:02 +0000350
Neil Booth96c74712007-10-12 16:02:31 +0000351 /* The error from the true value, in half-ulps, on multiplying two
352 floating point numbers, which differ from the value they
353 approximate by at most HUE1 and HUE2 half-ulps, is strictly less
354 than the returned value.
355
356 See "How to Read Floating Point Numbers Accurately" by William D
357 Clinger. */
358 unsigned int
359 HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
360 {
361 assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
362
363 if (HUerr1 + HUerr2 == 0)
364 return inexactMultiply * 2; /* <= inexactMultiply half-ulps. */
365 else
366 return inexactMultiply + 2 * (HUerr1 + HUerr2);
367 }
368
369 /* The number of ulps from the boundary (zero, or half if ISNEAREST)
370 when the least significant BITS are truncated. BITS cannot be
371 zero. */
372 integerPart
373 ulpsFromBoundary(const integerPart *parts, unsigned int bits, bool isNearest)
374 {
375 unsigned int count, partBits;
376 integerPart part, boundary;
377
378 assert (bits != 0);
379
380 bits--;
381 count = bits / integerPartWidth;
382 partBits = bits % integerPartWidth + 1;
383
384 part = parts[count] & (~(integerPart) 0 >> (integerPartWidth - partBits));
385
386 if (isNearest)
387 boundary = (integerPart) 1 << (partBits - 1);
388 else
389 boundary = 0;
390
391 if (count == 0) {
392 if (part - boundary <= boundary - part)
393 return part - boundary;
394 else
395 return boundary - part;
396 }
397
398 if (part == boundary) {
399 while (--count)
400 if (parts[count])
401 return ~(integerPart) 0; /* A lot. */
402
403 return parts[0];
404 } else if (part == boundary - 1) {
405 while (--count)
406 if (~parts[count])
407 return ~(integerPart) 0; /* A lot. */
408
409 return -parts[0];
410 }
411
412 return ~(integerPart) 0; /* A lot. */
413 }
414
415 /* Place pow(5, power) in DST, and return the number of parts used.
416 DST must be at least one part larger than size of the answer. */
417 static unsigned int
418 powerOf5(integerPart *dst, unsigned int power)
419 {
Neil Booth96c74712007-10-12 16:02:31 +0000420 static integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125,
421 15625, 78125 };
422 static integerPart pow5s[maxPowerOfFiveParts * 2 + 5] = { 78125 * 5 };
423 static unsigned int partsCount[16] = { 1 };
424
425 integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5;
426 unsigned int result;
427
428 assert(power <= maxExponent);
429
430 p1 = dst;
431 p2 = scratch;
432
433 *p1 = firstEightPowers[power & 7];
434 power >>= 3;
435
436 result = 1;
437 pow5 = pow5s;
438
439 for (unsigned int n = 0; power; power >>= 1, n++) {
440 unsigned int pc;
441
442 pc = partsCount[n];
443
444 /* Calculate pow(5,pow(2,n+3)) if we haven't yet. */
445 if (pc == 0) {
446 pc = partsCount[n - 1];
447 APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc);
448 pc *= 2;
449 if (pow5[pc - 1] == 0)
450 pc--;
451 partsCount[n] = pc;
452 }
453
454 if (power & 1) {
455 integerPart *tmp;
456
457 APInt::tcFullMultiply(p2, p1, pow5, result, pc);
458 result += pc;
459 if (p2[result - 1] == 0)
460 result--;
461
462 /* Now result is in p1 with partsCount parts and p2 is scratch
463 space. */
464 tmp = p1, p1 = p2, p2 = tmp;
465 }
466
467 pow5 += pc;
468 }
469
470 if (p1 != dst)
471 APInt::tcAssign(dst, p1, result);
472
473 return result;
474 }
475
Neil Bootha30b0ee2007-10-03 22:26:02 +0000476 /* Zero at the end to avoid modular arithmetic when adding one; used
477 when rounding up during hexadecimal output. */
478 static const char hexDigitsLower[] = "0123456789abcdef0";
479 static const char hexDigitsUpper[] = "0123456789ABCDEF0";
480 static const char infinityL[] = "infinity";
481 static const char infinityU[] = "INFINITY";
482 static const char NaNL[] = "nan";
483 static const char NaNU[] = "NAN";
484
485 /* Write out an integerPart in hexadecimal, starting with the most
486 significant nibble. Write out exactly COUNT hexdigits, return
487 COUNT. */
488 static unsigned int
489 partAsHex (char *dst, integerPart part, unsigned int count,
490 const char *hexDigitChars)
491 {
492 unsigned int result = count;
493
494 assert (count != 0 && count <= integerPartWidth / 4);
495
496 part >>= (integerPartWidth - 4 * count);
497 while (count--) {
498 dst[count] = hexDigitChars[part & 0xf];
499 part >>= 4;
500 }
501
502 return result;
503 }
504
Neil Booth92f7e8d2007-10-06 07:29:25 +0000505 /* Write out an unsigned decimal integer. */
Neil Bootha30b0ee2007-10-03 22:26:02 +0000506 static char *
Neil Booth92f7e8d2007-10-06 07:29:25 +0000507 writeUnsignedDecimal (char *dst, unsigned int n)
Neil Bootha30b0ee2007-10-03 22:26:02 +0000508 {
Neil Booth92f7e8d2007-10-06 07:29:25 +0000509 char buff[40], *p;
Neil Bootha30b0ee2007-10-03 22:26:02 +0000510
Neil Booth92f7e8d2007-10-06 07:29:25 +0000511 p = buff;
512 do
513 *p++ = '0' + n % 10;
514 while (n /= 10);
515
516 do
517 *dst++ = *--p;
518 while (p != buff);
519
520 return dst;
521 }
522
523 /* Write out a signed decimal integer. */
524 static char *
525 writeSignedDecimal (char *dst, int value)
526 {
527 if (value < 0) {
Neil Bootha30b0ee2007-10-03 22:26:02 +0000528 *dst++ = '-';
Neil Booth92f7e8d2007-10-06 07:29:25 +0000529 dst = writeUnsignedDecimal(dst, -(unsigned) value);
530 } else
531 dst = writeUnsignedDecimal(dst, value);
Neil Bootha30b0ee2007-10-03 22:26:02 +0000532
533 return dst;
534 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000535}
536
537/* Constructors. */
538void
539APFloat::initialize(const fltSemantics *ourSemantics)
540{
541 unsigned int count;
542
543 semantics = ourSemantics;
544 count = partCount();
545 if(count > 1)
546 significand.parts = new integerPart[count];
547}
548
549void
550APFloat::freeSignificand()
551{
552 if(partCount() > 1)
553 delete [] significand.parts;
554}
555
556void
557APFloat::assign(const APFloat &rhs)
558{
559 assert(semantics == rhs.semantics);
560
561 sign = rhs.sign;
562 category = rhs.category;
563 exponent = rhs.exponent;
Dale Johannesena471c2e2007-10-11 18:07:22 +0000564 sign2 = rhs.sign2;
565 exponent2 = rhs.exponent2;
Dale Johanneseneaf08942007-08-31 04:03:46 +0000566 if(category == fcNormal || category == fcNaN)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000567 copySignificand(rhs);
568}
569
570void
571APFloat::copySignificand(const APFloat &rhs)
572{
Dale Johanneseneaf08942007-08-31 04:03:46 +0000573 assert(category == fcNormal || category == fcNaN);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000574 assert(rhs.partCount() >= partCount());
575
576 APInt::tcAssign(significandParts(), rhs.significandParts(),
Neil Booth4f881702007-09-26 21:33:42 +0000577 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000578}
579
580APFloat &
581APFloat::operator=(const APFloat &rhs)
582{
583 if(this != &rhs) {
584 if(semantics != rhs.semantics) {
585 freeSignificand();
586 initialize(rhs.semantics);
587 }
588 assign(rhs);
589 }
590
591 return *this;
592}
593
Dale Johannesen343e7702007-08-24 00:56:33 +0000594bool
Dale Johannesen12595d72007-08-24 22:09:56 +0000595APFloat::bitwiseIsEqual(const APFloat &rhs) const {
Dale Johannesen343e7702007-08-24 00:56:33 +0000596 if (this == &rhs)
597 return true;
598 if (semantics != rhs.semantics ||
Dale Johanneseneaf08942007-08-31 04:03:46 +0000599 category != rhs.category ||
600 sign != rhs.sign)
Dale Johannesen343e7702007-08-24 00:56:33 +0000601 return false;
Dale Johannesena471c2e2007-10-11 18:07:22 +0000602 if (semantics==(const llvm::fltSemantics* const)&PPCDoubleDouble &&
603 sign2 != rhs.sign2)
604 return false;
Dale Johanneseneaf08942007-08-31 04:03:46 +0000605 if (category==fcZero || category==fcInfinity)
Dale Johannesen343e7702007-08-24 00:56:33 +0000606 return true;
Dale Johanneseneaf08942007-08-31 04:03:46 +0000607 else if (category==fcNormal && exponent!=rhs.exponent)
608 return false;
Dale Johannesena471c2e2007-10-11 18:07:22 +0000609 else if (semantics==(const llvm::fltSemantics* const)&PPCDoubleDouble &&
610 exponent2!=rhs.exponent2)
611 return false;
Dale Johannesen343e7702007-08-24 00:56:33 +0000612 else {
Dale Johannesen343e7702007-08-24 00:56:33 +0000613 int i= partCount();
614 const integerPart* p=significandParts();
615 const integerPart* q=rhs.significandParts();
616 for (; i>0; i--, p++, q++) {
617 if (*p != *q)
618 return false;
619 }
620 return true;
621 }
622}
623
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000624APFloat::APFloat(const fltSemantics &ourSemantics, integerPart value)
625{
Dale Johannesena471c2e2007-10-11 18:07:22 +0000626 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
627 "Compile-time arithmetic on PPC long double not supported yet");
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000628 initialize(&ourSemantics);
629 sign = 0;
630 zeroSignificand();
631 exponent = ourSemantics.precision - 1;
632 significandParts()[0] = value;
633 normalize(rmNearestTiesToEven, lfExactlyZero);
634}
635
636APFloat::APFloat(const fltSemantics &ourSemantics,
Neil Booth4f881702007-09-26 21:33:42 +0000637 fltCategory ourCategory, bool negative)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000638{
Dale Johannesena471c2e2007-10-11 18:07:22 +0000639 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
640 "Compile-time arithmetic on PPC long double not supported yet");
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000641 initialize(&ourSemantics);
642 category = ourCategory;
643 sign = negative;
644 if(category == fcNormal)
645 category = fcZero;
646}
647
648APFloat::APFloat(const fltSemantics &ourSemantics, const char *text)
649{
Dale Johannesena471c2e2007-10-11 18:07:22 +0000650 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
651 "Compile-time arithmetic on PPC long double not supported yet");
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000652 initialize(&ourSemantics);
653 convertFromString(text, rmNearestTiesToEven);
654}
655
656APFloat::APFloat(const APFloat &rhs)
657{
658 initialize(rhs.semantics);
659 assign(rhs);
660}
661
662APFloat::~APFloat()
663{
664 freeSignificand();
665}
666
667unsigned int
668APFloat::partCount() const
669{
Dale Johannesena72a5a02007-09-20 23:47:58 +0000670 return partCountForBits(semantics->precision + 1);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000671}
672
673unsigned int
674APFloat::semanticsPrecision(const fltSemantics &semantics)
675{
676 return semantics.precision;
677}
678
679const integerPart *
680APFloat::significandParts() const
681{
682 return const_cast<APFloat *>(this)->significandParts();
683}
684
685integerPart *
686APFloat::significandParts()
687{
Dale Johanneseneaf08942007-08-31 04:03:46 +0000688 assert(category == fcNormal || category == fcNaN);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000689
690 if(partCount() > 1)
691 return significand.parts;
692 else
693 return &significand.part;
694}
695
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000696void
697APFloat::zeroSignificand()
698{
699 category = fcNormal;
700 APInt::tcSet(significandParts(), 0, partCount());
701}
702
703/* Increment an fcNormal floating point number's significand. */
704void
705APFloat::incrementSignificand()
706{
707 integerPart carry;
708
709 carry = APInt::tcIncrement(significandParts(), partCount());
710
711 /* Our callers should never cause us to overflow. */
712 assert(carry == 0);
713}
714
715/* Add the significand of the RHS. Returns the carry flag. */
716integerPart
717APFloat::addSignificand(const APFloat &rhs)
718{
719 integerPart *parts;
720
721 parts = significandParts();
722
723 assert(semantics == rhs.semantics);
724 assert(exponent == rhs.exponent);
725
726 return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
727}
728
729/* Subtract the significand of the RHS with a borrow flag. Returns
730 the borrow flag. */
731integerPart
732APFloat::subtractSignificand(const APFloat &rhs, integerPart borrow)
733{
734 integerPart *parts;
735
736 parts = significandParts();
737
738 assert(semantics == rhs.semantics);
739 assert(exponent == rhs.exponent);
740
741 return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
Neil Booth4f881702007-09-26 21:33:42 +0000742 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000743}
744
745/* Multiply the significand of the RHS. If ADDEND is non-NULL, add it
746 on to the full-precision result of the multiplication. Returns the
747 lost fraction. */
748lostFraction
749APFloat::multiplySignificand(const APFloat &rhs, const APFloat *addend)
750{
Neil Booth4f881702007-09-26 21:33:42 +0000751 unsigned int omsb; // One, not zero, based MSB.
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000752 unsigned int partsCount, newPartsCount, precision;
753 integerPart *lhsSignificand;
754 integerPart scratch[4];
755 integerPart *fullSignificand;
756 lostFraction lost_fraction;
757
758 assert(semantics == rhs.semantics);
759
760 precision = semantics->precision;
761 newPartsCount = partCountForBits(precision * 2);
762
763 if(newPartsCount > 4)
764 fullSignificand = new integerPart[newPartsCount];
765 else
766 fullSignificand = scratch;
767
768 lhsSignificand = significandParts();
769 partsCount = partCount();
770
771 APInt::tcFullMultiply(fullSignificand, lhsSignificand,
Neil Booth978661d2007-10-06 00:24:48 +0000772 rhs.significandParts(), partsCount, partsCount);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000773
774 lost_fraction = lfExactlyZero;
775 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
776 exponent += rhs.exponent;
777
778 if(addend) {
779 Significand savedSignificand = significand;
780 const fltSemantics *savedSemantics = semantics;
781 fltSemantics extendedSemantics;
782 opStatus status;
783 unsigned int extendedPrecision;
784
785 /* Normalize our MSB. */
786 extendedPrecision = precision + precision - 1;
787 if(omsb != extendedPrecision)
788 {
Neil Booth4f881702007-09-26 21:33:42 +0000789 APInt::tcShiftLeft(fullSignificand, newPartsCount,
790 extendedPrecision - omsb);
791 exponent -= extendedPrecision - omsb;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000792 }
793
794 /* Create new semantics. */
795 extendedSemantics = *semantics;
796 extendedSemantics.precision = extendedPrecision;
797
798 if(newPartsCount == 1)
799 significand.part = fullSignificand[0];
800 else
801 significand.parts = fullSignificand;
802 semantics = &extendedSemantics;
803
804 APFloat extendedAddend(*addend);
805 status = extendedAddend.convert(extendedSemantics, rmTowardZero);
806 assert(status == opOK);
807 lost_fraction = addOrSubtractSignificand(extendedAddend, false);
808
809 /* Restore our state. */
810 if(newPartsCount == 1)
811 fullSignificand[0] = significand.part;
812 significand = savedSignificand;
813 semantics = savedSemantics;
814
815 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
816 }
817
818 exponent -= (precision - 1);
819
820 if(omsb > precision) {
821 unsigned int bits, significantParts;
822 lostFraction lf;
823
824 bits = omsb - precision;
825 significantParts = partCountForBits(omsb);
826 lf = shiftRight(fullSignificand, significantParts, bits);
827 lost_fraction = combineLostFractions(lf, lost_fraction);
828 exponent += bits;
829 }
830
831 APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
832
833 if(newPartsCount > 4)
834 delete [] fullSignificand;
835
836 return lost_fraction;
837}
838
839/* Multiply the significands of LHS and RHS to DST. */
840lostFraction
841APFloat::divideSignificand(const APFloat &rhs)
842{
843 unsigned int bit, i, partsCount;
844 const integerPart *rhsSignificand;
845 integerPart *lhsSignificand, *dividend, *divisor;
846 integerPart scratch[4];
847 lostFraction lost_fraction;
848
849 assert(semantics == rhs.semantics);
850
851 lhsSignificand = significandParts();
852 rhsSignificand = rhs.significandParts();
853 partsCount = partCount();
854
855 if(partsCount > 2)
856 dividend = new integerPart[partsCount * 2];
857 else
858 dividend = scratch;
859
860 divisor = dividend + partsCount;
861
862 /* Copy the dividend and divisor as they will be modified in-place. */
863 for(i = 0; i < partsCount; i++) {
864 dividend[i] = lhsSignificand[i];
865 divisor[i] = rhsSignificand[i];
866 lhsSignificand[i] = 0;
867 }
868
869 exponent -= rhs.exponent;
870
871 unsigned int precision = semantics->precision;
872
873 /* Normalize the divisor. */
874 bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
875 if(bit) {
876 exponent += bit;
877 APInt::tcShiftLeft(divisor, partsCount, bit);
878 }
879
880 /* Normalize the dividend. */
881 bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
882 if(bit) {
883 exponent -= bit;
884 APInt::tcShiftLeft(dividend, partsCount, bit);
885 }
886
Neil Booth96c74712007-10-12 16:02:31 +0000887 /* Ensure the dividend >= divisor initially for the loop below.
888 Incidentally, this means that the division loop below is
889 guaranteed to set the integer bit to one. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000890 if(APInt::tcCompare(dividend, divisor, partsCount) < 0) {
891 exponent--;
892 APInt::tcShiftLeft(dividend, partsCount, 1);
893 assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
894 }
895
896 /* Long division. */
897 for(bit = precision; bit; bit -= 1) {
898 if(APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
899 APInt::tcSubtract(dividend, divisor, 0, partsCount);
900 APInt::tcSetBit(lhsSignificand, bit - 1);
901 }
902
903 APInt::tcShiftLeft(dividend, partsCount, 1);
904 }
905
906 /* Figure out the lost fraction. */
907 int cmp = APInt::tcCompare(dividend, divisor, partsCount);
908
909 if(cmp > 0)
910 lost_fraction = lfMoreThanHalf;
911 else if(cmp == 0)
912 lost_fraction = lfExactlyHalf;
913 else if(APInt::tcIsZero(dividend, partsCount))
914 lost_fraction = lfExactlyZero;
915 else
916 lost_fraction = lfLessThanHalf;
917
918 if(partsCount > 2)
919 delete [] dividend;
920
921 return lost_fraction;
922}
923
924unsigned int
925APFloat::significandMSB() const
926{
927 return APInt::tcMSB(significandParts(), partCount());
928}
929
930unsigned int
931APFloat::significandLSB() const
932{
933 return APInt::tcLSB(significandParts(), partCount());
934}
935
936/* Note that a zero result is NOT normalized to fcZero. */
937lostFraction
938APFloat::shiftSignificandRight(unsigned int bits)
939{
940 /* Our exponent should not overflow. */
941 assert((exponent_t) (exponent + bits) >= exponent);
942
943 exponent += bits;
944
945 return shiftRight(significandParts(), partCount(), bits);
946}
947
948/* Shift the significand left BITS bits, subtract BITS from its exponent. */
949void
950APFloat::shiftSignificandLeft(unsigned int bits)
951{
952 assert(bits < semantics->precision);
953
954 if(bits) {
955 unsigned int partsCount = partCount();
956
957 APInt::tcShiftLeft(significandParts(), partsCount, bits);
958 exponent -= bits;
959
960 assert(!APInt::tcIsZero(significandParts(), partsCount));
961 }
962}
963
964APFloat::cmpResult
965APFloat::compareAbsoluteValue(const APFloat &rhs) const
966{
967 int compare;
968
969 assert(semantics == rhs.semantics);
970 assert(category == fcNormal);
971 assert(rhs.category == fcNormal);
972
973 compare = exponent - rhs.exponent;
974
975 /* If exponents are equal, do an unsigned bignum comparison of the
976 significands. */
977 if(compare == 0)
978 compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
Neil Booth4f881702007-09-26 21:33:42 +0000979 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000980
981 if(compare > 0)
982 return cmpGreaterThan;
983 else if(compare < 0)
984 return cmpLessThan;
985 else
986 return cmpEqual;
987}
988
989/* Handle overflow. Sign is preserved. We either become infinity or
990 the largest finite number. */
991APFloat::opStatus
992APFloat::handleOverflow(roundingMode rounding_mode)
993{
994 /* Infinity? */
995 if(rounding_mode == rmNearestTiesToEven
996 || rounding_mode == rmNearestTiesToAway
997 || (rounding_mode == rmTowardPositive && !sign)
998 || (rounding_mode == rmTowardNegative && sign))
999 {
1000 category = fcInfinity;
1001 return (opStatus) (opOverflow | opInexact);
1002 }
1003
1004 /* Otherwise we become the largest finite number. */
1005 category = fcNormal;
1006 exponent = semantics->maxExponent;
1007 APInt::tcSetLeastSignificantBits(significandParts(), partCount(),
Neil Booth4f881702007-09-26 21:33:42 +00001008 semantics->precision);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001009
1010 return opInexact;
1011}
1012
Neil Boothb7dea4c2007-10-03 15:16:41 +00001013/* Returns TRUE if, when truncating the current number, with BIT the
1014 new LSB, with the given lost fraction and rounding mode, the result
1015 would need to be rounded away from zero (i.e., by increasing the
1016 signficand). This routine must work for fcZero of both signs, and
1017 fcNormal numbers. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001018bool
1019APFloat::roundAwayFromZero(roundingMode rounding_mode,
Neil Boothb7dea4c2007-10-03 15:16:41 +00001020 lostFraction lost_fraction,
1021 unsigned int bit) const
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001022{
Dale Johanneseneaf08942007-08-31 04:03:46 +00001023 /* NaNs and infinities should not have lost fractions. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001024 assert(category == fcNormal || category == fcZero);
1025
Neil Boothb7dea4c2007-10-03 15:16:41 +00001026 /* Current callers never pass this so we don't handle it. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001027 assert(lost_fraction != lfExactlyZero);
1028
1029 switch(rounding_mode) {
1030 default:
1031 assert(0);
1032
1033 case rmNearestTiesToAway:
1034 return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
1035
1036 case rmNearestTiesToEven:
1037 if(lost_fraction == lfMoreThanHalf)
1038 return true;
1039
1040 /* Our zeroes don't have a significand to test. */
1041 if(lost_fraction == lfExactlyHalf && category != fcZero)
Neil Boothb7dea4c2007-10-03 15:16:41 +00001042 return APInt::tcExtractBit(significandParts(), bit);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001043
1044 return false;
1045
1046 case rmTowardZero:
1047 return false;
1048
1049 case rmTowardPositive:
1050 return sign == false;
1051
1052 case rmTowardNegative:
1053 return sign == true;
1054 }
1055}
1056
1057APFloat::opStatus
1058APFloat::normalize(roundingMode rounding_mode,
Neil Booth4f881702007-09-26 21:33:42 +00001059 lostFraction lost_fraction)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001060{
Neil Booth4f881702007-09-26 21:33:42 +00001061 unsigned int omsb; /* One, not zero, based MSB. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001062 int exponentChange;
1063
1064 if(category != fcNormal)
1065 return opOK;
1066
1067 /* Before rounding normalize the exponent of fcNormal numbers. */
1068 omsb = significandMSB() + 1;
1069
1070 if(omsb) {
1071 /* OMSB is numbered from 1. We want to place it in the integer
1072 bit numbered PRECISON if possible, with a compensating change in
1073 the exponent. */
1074 exponentChange = omsb - semantics->precision;
1075
1076 /* If the resulting exponent is too high, overflow according to
1077 the rounding mode. */
1078 if(exponent + exponentChange > semantics->maxExponent)
1079 return handleOverflow(rounding_mode);
1080
1081 /* Subnormal numbers have exponent minExponent, and their MSB
1082 is forced based on that. */
1083 if(exponent + exponentChange < semantics->minExponent)
1084 exponentChange = semantics->minExponent - exponent;
1085
1086 /* Shifting left is easy as we don't lose precision. */
1087 if(exponentChange < 0) {
1088 assert(lost_fraction == lfExactlyZero);
1089
1090 shiftSignificandLeft(-exponentChange);
1091
1092 return opOK;
1093 }
1094
1095 if(exponentChange > 0) {
1096 lostFraction lf;
1097
1098 /* Shift right and capture any new lost fraction. */
1099 lf = shiftSignificandRight(exponentChange);
1100
1101 lost_fraction = combineLostFractions(lf, lost_fraction);
1102
1103 /* Keep OMSB up-to-date. */
1104 if(omsb > (unsigned) exponentChange)
Neil Booth96c74712007-10-12 16:02:31 +00001105 omsb -= exponentChange;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001106 else
Neil Booth4f881702007-09-26 21:33:42 +00001107 omsb = 0;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001108 }
1109 }
1110
1111 /* Now round the number according to rounding_mode given the lost
1112 fraction. */
1113
1114 /* As specified in IEEE 754, since we do not trap we do not report
1115 underflow for exact results. */
1116 if(lost_fraction == lfExactlyZero) {
1117 /* Canonicalize zeroes. */
1118 if(omsb == 0)
1119 category = fcZero;
1120
1121 return opOK;
1122 }
1123
1124 /* Increment the significand if we're rounding away from zero. */
Neil Boothb7dea4c2007-10-03 15:16:41 +00001125 if(roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001126 if(omsb == 0)
1127 exponent = semantics->minExponent;
1128
1129 incrementSignificand();
1130 omsb = significandMSB() + 1;
1131
1132 /* Did the significand increment overflow? */
1133 if(omsb == (unsigned) semantics->precision + 1) {
1134 /* Renormalize by incrementing the exponent and shifting our
Neil Booth4f881702007-09-26 21:33:42 +00001135 significand right one. However if we already have the
1136 maximum exponent we overflow to infinity. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001137 if(exponent == semantics->maxExponent) {
Neil Booth4f881702007-09-26 21:33:42 +00001138 category = fcInfinity;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001139
Neil Booth4f881702007-09-26 21:33:42 +00001140 return (opStatus) (opOverflow | opInexact);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001141 }
1142
1143 shiftSignificandRight(1);
1144
1145 return opInexact;
1146 }
1147 }
1148
1149 /* The normal case - we were and are not denormal, and any
1150 significand increment above didn't overflow. */
1151 if(omsb == semantics->precision)
1152 return opInexact;
1153
1154 /* We have a non-zero denormal. */
1155 assert(omsb < semantics->precision);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001156
1157 /* Canonicalize zeroes. */
1158 if(omsb == 0)
1159 category = fcZero;
1160
1161 /* The fcZero case is a denormal that underflowed to zero. */
1162 return (opStatus) (opUnderflow | opInexact);
1163}
1164
1165APFloat::opStatus
1166APFloat::addOrSubtractSpecials(const APFloat &rhs, bool subtract)
1167{
1168 switch(convolve(category, rhs.category)) {
1169 default:
1170 assert(0);
1171
Dale Johanneseneaf08942007-08-31 04:03:46 +00001172 case convolve(fcNaN, fcZero):
1173 case convolve(fcNaN, fcNormal):
1174 case convolve(fcNaN, fcInfinity):
1175 case convolve(fcNaN, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001176 case convolve(fcNormal, fcZero):
1177 case convolve(fcInfinity, fcNormal):
1178 case convolve(fcInfinity, fcZero):
1179 return opOK;
1180
Dale Johanneseneaf08942007-08-31 04:03:46 +00001181 case convolve(fcZero, fcNaN):
1182 case convolve(fcNormal, fcNaN):
1183 case convolve(fcInfinity, fcNaN):
1184 category = fcNaN;
1185 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001186 return opOK;
1187
1188 case convolve(fcNormal, fcInfinity):
1189 case convolve(fcZero, fcInfinity):
1190 category = fcInfinity;
1191 sign = rhs.sign ^ subtract;
1192 return opOK;
1193
1194 case convolve(fcZero, fcNormal):
1195 assign(rhs);
1196 sign = rhs.sign ^ subtract;
1197 return opOK;
1198
1199 case convolve(fcZero, fcZero):
1200 /* Sign depends on rounding mode; handled by caller. */
1201 return opOK;
1202
1203 case convolve(fcInfinity, fcInfinity):
1204 /* Differently signed infinities can only be validly
1205 subtracted. */
1206 if(sign ^ rhs.sign != subtract) {
Dale Johanneseneaf08942007-08-31 04:03:46 +00001207 category = fcNaN;
1208 // Arbitrary but deterministic value for significand
1209 APInt::tcSet(significandParts(), ~0U, partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001210 return opInvalidOp;
1211 }
1212
1213 return opOK;
1214
1215 case convolve(fcNormal, fcNormal):
1216 return opDivByZero;
1217 }
1218}
1219
1220/* Add or subtract two normal numbers. */
1221lostFraction
1222APFloat::addOrSubtractSignificand(const APFloat &rhs, bool subtract)
1223{
1224 integerPart carry;
1225 lostFraction lost_fraction;
1226 int bits;
1227
1228 /* Determine if the operation on the absolute values is effectively
1229 an addition or subtraction. */
1230 subtract ^= (sign ^ rhs.sign);
1231
1232 /* Are we bigger exponent-wise than the RHS? */
1233 bits = exponent - rhs.exponent;
1234
1235 /* Subtraction is more subtle than one might naively expect. */
1236 if(subtract) {
1237 APFloat temp_rhs(rhs);
1238 bool reverse;
1239
Chris Lattnerada530b2007-08-24 03:02:34 +00001240 if (bits == 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001241 reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan;
1242 lost_fraction = lfExactlyZero;
Chris Lattnerada530b2007-08-24 03:02:34 +00001243 } else if (bits > 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001244 lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
1245 shiftSignificandLeft(1);
1246 reverse = false;
Chris Lattnerada530b2007-08-24 03:02:34 +00001247 } else {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001248 lost_fraction = shiftSignificandRight(-bits - 1);
1249 temp_rhs.shiftSignificandLeft(1);
1250 reverse = true;
1251 }
1252
Chris Lattnerada530b2007-08-24 03:02:34 +00001253 if (reverse) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001254 carry = temp_rhs.subtractSignificand
Neil Booth4f881702007-09-26 21:33:42 +00001255 (*this, lost_fraction != lfExactlyZero);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001256 copySignificand(temp_rhs);
1257 sign = !sign;
1258 } else {
1259 carry = subtractSignificand
Neil Booth4f881702007-09-26 21:33:42 +00001260 (temp_rhs, lost_fraction != lfExactlyZero);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001261 }
1262
1263 /* Invert the lost fraction - it was on the RHS and
1264 subtracted. */
1265 if(lost_fraction == lfLessThanHalf)
1266 lost_fraction = lfMoreThanHalf;
1267 else if(lost_fraction == lfMoreThanHalf)
1268 lost_fraction = lfLessThanHalf;
1269
1270 /* The code above is intended to ensure that no borrow is
1271 necessary. */
1272 assert(!carry);
1273 } else {
1274 if(bits > 0) {
1275 APFloat temp_rhs(rhs);
1276
1277 lost_fraction = temp_rhs.shiftSignificandRight(bits);
1278 carry = addSignificand(temp_rhs);
1279 } else {
1280 lost_fraction = shiftSignificandRight(-bits);
1281 carry = addSignificand(rhs);
1282 }
1283
1284 /* We have a guard bit; generating a carry cannot happen. */
1285 assert(!carry);
1286 }
1287
1288 return lost_fraction;
1289}
1290
1291APFloat::opStatus
1292APFloat::multiplySpecials(const APFloat &rhs)
1293{
1294 switch(convolve(category, rhs.category)) {
1295 default:
1296 assert(0);
1297
Dale Johanneseneaf08942007-08-31 04:03:46 +00001298 case convolve(fcNaN, fcZero):
1299 case convolve(fcNaN, fcNormal):
1300 case convolve(fcNaN, fcInfinity):
1301 case convolve(fcNaN, fcNaN):
1302 return opOK;
1303
1304 case convolve(fcZero, fcNaN):
1305 case convolve(fcNormal, fcNaN):
1306 case convolve(fcInfinity, fcNaN):
1307 category = fcNaN;
1308 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001309 return opOK;
1310
1311 case convolve(fcNormal, fcInfinity):
1312 case convolve(fcInfinity, fcNormal):
1313 case convolve(fcInfinity, fcInfinity):
1314 category = fcInfinity;
1315 return opOK;
1316
1317 case convolve(fcZero, fcNormal):
1318 case convolve(fcNormal, fcZero):
1319 case convolve(fcZero, fcZero):
1320 category = fcZero;
1321 return opOK;
1322
1323 case convolve(fcZero, fcInfinity):
1324 case convolve(fcInfinity, fcZero):
Dale Johanneseneaf08942007-08-31 04:03:46 +00001325 category = fcNaN;
1326 // Arbitrary but deterministic value for significand
1327 APInt::tcSet(significandParts(), ~0U, partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001328 return opInvalidOp;
1329
1330 case convolve(fcNormal, fcNormal):
1331 return opOK;
1332 }
1333}
1334
1335APFloat::opStatus
1336APFloat::divideSpecials(const APFloat &rhs)
1337{
1338 switch(convolve(category, rhs.category)) {
1339 default:
1340 assert(0);
1341
Dale Johanneseneaf08942007-08-31 04:03:46 +00001342 case convolve(fcNaN, fcZero):
1343 case convolve(fcNaN, fcNormal):
1344 case convolve(fcNaN, fcInfinity):
1345 case convolve(fcNaN, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001346 case convolve(fcInfinity, fcZero):
1347 case convolve(fcInfinity, fcNormal):
1348 case convolve(fcZero, fcInfinity):
1349 case convolve(fcZero, fcNormal):
1350 return opOK;
1351
Dale Johanneseneaf08942007-08-31 04:03:46 +00001352 case convolve(fcZero, fcNaN):
1353 case convolve(fcNormal, fcNaN):
1354 case convolve(fcInfinity, fcNaN):
1355 category = fcNaN;
1356 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001357 return opOK;
1358
1359 case convolve(fcNormal, fcInfinity):
1360 category = fcZero;
1361 return opOK;
1362
1363 case convolve(fcNormal, fcZero):
1364 category = fcInfinity;
1365 return opDivByZero;
1366
1367 case convolve(fcInfinity, fcInfinity):
1368 case convolve(fcZero, fcZero):
Dale Johanneseneaf08942007-08-31 04:03:46 +00001369 category = fcNaN;
1370 // Arbitrary but deterministic value for significand
1371 APInt::tcSet(significandParts(), ~0U, partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001372 return opInvalidOp;
1373
1374 case convolve(fcNormal, fcNormal):
1375 return opOK;
1376 }
1377}
1378
1379/* Change sign. */
1380void
1381APFloat::changeSign()
1382{
1383 /* Look mummy, this one's easy. */
1384 sign = !sign;
1385}
1386
Dale Johannesene15c2db2007-08-31 23:35:31 +00001387void
1388APFloat::clearSign()
1389{
1390 /* So is this one. */
1391 sign = 0;
1392}
1393
1394void
1395APFloat::copySign(const APFloat &rhs)
1396{
1397 /* And this one. */
1398 sign = rhs.sign;
1399}
1400
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001401/* Normalized addition or subtraction. */
1402APFloat::opStatus
1403APFloat::addOrSubtract(const APFloat &rhs, roundingMode rounding_mode,
Neil Booth4f881702007-09-26 21:33:42 +00001404 bool subtract)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001405{
1406 opStatus fs;
1407
1408 fs = addOrSubtractSpecials(rhs, subtract);
1409
1410 /* This return code means it was not a simple case. */
1411 if(fs == opDivByZero) {
1412 lostFraction lost_fraction;
1413
1414 lost_fraction = addOrSubtractSignificand(rhs, subtract);
1415 fs = normalize(rounding_mode, lost_fraction);
1416
1417 /* Can only be zero if we lost no fraction. */
1418 assert(category != fcZero || lost_fraction == lfExactlyZero);
1419 }
1420
1421 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1422 positive zero unless rounding to minus infinity, except that
1423 adding two like-signed zeroes gives that zero. */
1424 if(category == fcZero) {
1425 if(rhs.category != fcZero || (sign == rhs.sign) == subtract)
1426 sign = (rounding_mode == rmTowardNegative);
1427 }
1428
1429 return fs;
1430}
1431
1432/* Normalized addition. */
1433APFloat::opStatus
1434APFloat::add(const APFloat &rhs, roundingMode rounding_mode)
1435{
Dale Johannesena471c2e2007-10-11 18:07:22 +00001436 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
1437 "Compile-time arithmetic on PPC long double not supported yet");
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001438 return addOrSubtract(rhs, rounding_mode, false);
1439}
1440
1441/* Normalized subtraction. */
1442APFloat::opStatus
1443APFloat::subtract(const APFloat &rhs, roundingMode rounding_mode)
1444{
Dale Johannesena471c2e2007-10-11 18:07:22 +00001445 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
1446 "Compile-time arithmetic on PPC long double not supported yet");
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001447 return addOrSubtract(rhs, rounding_mode, true);
1448}
1449
1450/* Normalized multiply. */
1451APFloat::opStatus
1452APFloat::multiply(const APFloat &rhs, roundingMode rounding_mode)
1453{
Dale Johannesena471c2e2007-10-11 18:07:22 +00001454 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
1455 "Compile-time arithmetic on PPC long double not supported yet");
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001456 opStatus fs;
1457
1458 sign ^= rhs.sign;
1459 fs = multiplySpecials(rhs);
1460
1461 if(category == fcNormal) {
1462 lostFraction lost_fraction = multiplySignificand(rhs, 0);
1463 fs = normalize(rounding_mode, lost_fraction);
1464 if(lost_fraction != lfExactlyZero)
1465 fs = (opStatus) (fs | opInexact);
1466 }
1467
1468 return fs;
1469}
1470
1471/* Normalized divide. */
1472APFloat::opStatus
1473APFloat::divide(const APFloat &rhs, roundingMode rounding_mode)
1474{
Dale Johannesena471c2e2007-10-11 18:07:22 +00001475 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
1476 "Compile-time arithmetic on PPC long double not supported yet");
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001477 opStatus fs;
1478
1479 sign ^= rhs.sign;
1480 fs = divideSpecials(rhs);
1481
1482 if(category == fcNormal) {
1483 lostFraction lost_fraction = divideSignificand(rhs);
1484 fs = normalize(rounding_mode, lost_fraction);
1485 if(lost_fraction != lfExactlyZero)
1486 fs = (opStatus) (fs | opInexact);
1487 }
1488
1489 return fs;
1490}
1491
Neil Bootha30b0ee2007-10-03 22:26:02 +00001492/* Normalized remainder. This is not currently doing TRT. */
Dale Johannesene15c2db2007-08-31 23:35:31 +00001493APFloat::opStatus
1494APFloat::mod(const APFloat &rhs, roundingMode rounding_mode)
1495{
Dale Johannesena471c2e2007-10-11 18:07:22 +00001496 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
1497 "Compile-time arithmetic on PPC long double not supported yet");
Dale Johannesene15c2db2007-08-31 23:35:31 +00001498 opStatus fs;
1499 APFloat V = *this;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001500 unsigned int origSign = sign;
Dale Johannesene15c2db2007-08-31 23:35:31 +00001501 fs = V.divide(rhs, rmNearestTiesToEven);
1502 if (fs == opDivByZero)
1503 return fs;
1504
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001505 int parts = partCount();
1506 integerPart *x = new integerPart[parts];
Neil Booth4f881702007-09-26 21:33:42 +00001507 fs = V.convertToInteger(x, parts * integerPartWidth, true,
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001508 rmNearestTiesToEven);
Dale Johannesene15c2db2007-08-31 23:35:31 +00001509 if (fs==opInvalidOp)
1510 return fs;
1511
Neil Boothccf596a2007-10-07 11:45:55 +00001512 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1513 rmNearestTiesToEven);
Dale Johannesene15c2db2007-08-31 23:35:31 +00001514 assert(fs==opOK); // should always work
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001515
Dale Johannesene15c2db2007-08-31 23:35:31 +00001516 fs = V.multiply(rhs, rounding_mode);
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001517 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1518
Dale Johannesene15c2db2007-08-31 23:35:31 +00001519 fs = subtract(V, rounding_mode);
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001520 assert(fs==opOK || fs==opInexact); // likewise
1521
1522 if (isZero())
1523 sign = origSign; // IEEE754 requires this
1524 delete[] x;
Dale Johannesene15c2db2007-08-31 23:35:31 +00001525 return fs;
1526}
1527
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001528/* Normalized fused-multiply-add. */
1529APFloat::opStatus
1530APFloat::fusedMultiplyAdd(const APFloat &multiplicand,
Neil Booth4f881702007-09-26 21:33:42 +00001531 const APFloat &addend,
1532 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001533{
Dale Johannesena471c2e2007-10-11 18:07:22 +00001534 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
1535 "Compile-time arithmetic on PPC long double not supported yet");
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001536 opStatus fs;
1537
1538 /* Post-multiplication sign, before addition. */
1539 sign ^= multiplicand.sign;
1540
1541 /* If and only if all arguments are normal do we need to do an
1542 extended-precision calculation. */
1543 if(category == fcNormal
1544 && multiplicand.category == fcNormal
1545 && addend.category == fcNormal) {
1546 lostFraction lost_fraction;
1547
1548 lost_fraction = multiplySignificand(multiplicand, &addend);
1549 fs = normalize(rounding_mode, lost_fraction);
1550 if(lost_fraction != lfExactlyZero)
1551 fs = (opStatus) (fs | opInexact);
1552
1553 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1554 positive zero unless rounding to minus infinity, except that
1555 adding two like-signed zeroes gives that zero. */
1556 if(category == fcZero && sign != addend.sign)
1557 sign = (rounding_mode == rmTowardNegative);
1558 } else {
1559 fs = multiplySpecials(multiplicand);
1560
1561 /* FS can only be opOK or opInvalidOp. There is no more work
1562 to do in the latter case. The IEEE-754R standard says it is
1563 implementation-defined in this case whether, if ADDEND is a
Dale Johanneseneaf08942007-08-31 04:03:46 +00001564 quiet NaN, we raise invalid op; this implementation does so.
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001565
1566 If we need to do the addition we can do so with normal
1567 precision. */
1568 if(fs == opOK)
1569 fs = addOrSubtract(addend, rounding_mode, false);
1570 }
1571
1572 return fs;
1573}
1574
1575/* Comparison requires normalized numbers. */
1576APFloat::cmpResult
1577APFloat::compare(const APFloat &rhs) const
1578{
Dale Johannesena471c2e2007-10-11 18:07:22 +00001579 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
1580 "Compile-time arithmetic on PPC long double not supported yet");
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001581 cmpResult result;
1582
1583 assert(semantics == rhs.semantics);
1584
1585 switch(convolve(category, rhs.category)) {
1586 default:
1587 assert(0);
1588
Dale Johanneseneaf08942007-08-31 04:03:46 +00001589 case convolve(fcNaN, fcZero):
1590 case convolve(fcNaN, fcNormal):
1591 case convolve(fcNaN, fcInfinity):
1592 case convolve(fcNaN, fcNaN):
1593 case convolve(fcZero, fcNaN):
1594 case convolve(fcNormal, fcNaN):
1595 case convolve(fcInfinity, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001596 return cmpUnordered;
1597
1598 case convolve(fcInfinity, fcNormal):
1599 case convolve(fcInfinity, fcZero):
1600 case convolve(fcNormal, fcZero):
1601 if(sign)
1602 return cmpLessThan;
1603 else
1604 return cmpGreaterThan;
1605
1606 case convolve(fcNormal, fcInfinity):
1607 case convolve(fcZero, fcInfinity):
1608 case convolve(fcZero, fcNormal):
1609 if(rhs.sign)
1610 return cmpGreaterThan;
1611 else
1612 return cmpLessThan;
1613
1614 case convolve(fcInfinity, fcInfinity):
1615 if(sign == rhs.sign)
1616 return cmpEqual;
1617 else if(sign)
1618 return cmpLessThan;
1619 else
1620 return cmpGreaterThan;
1621
1622 case convolve(fcZero, fcZero):
1623 return cmpEqual;
1624
1625 case convolve(fcNormal, fcNormal):
1626 break;
1627 }
1628
1629 /* Two normal numbers. Do they have the same sign? */
1630 if(sign != rhs.sign) {
1631 if(sign)
1632 result = cmpLessThan;
1633 else
1634 result = cmpGreaterThan;
1635 } else {
1636 /* Compare absolute values; invert result if negative. */
1637 result = compareAbsoluteValue(rhs);
1638
1639 if(sign) {
1640 if(result == cmpLessThan)
Neil Booth4f881702007-09-26 21:33:42 +00001641 result = cmpGreaterThan;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001642 else if(result == cmpGreaterThan)
Neil Booth4f881702007-09-26 21:33:42 +00001643 result = cmpLessThan;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001644 }
1645 }
1646
1647 return result;
1648}
1649
1650APFloat::opStatus
1651APFloat::convert(const fltSemantics &toSemantics,
Neil Booth4f881702007-09-26 21:33:42 +00001652 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001653{
Dale Johannesena471c2e2007-10-11 18:07:22 +00001654 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
1655 "Compile-time arithmetic on PPC long double not supported yet");
Neil Boothc8db43d2007-09-22 02:56:19 +00001656 lostFraction lostFraction;
1657 unsigned int newPartCount, oldPartCount;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001658 opStatus fs;
Neil Booth4f881702007-09-26 21:33:42 +00001659
Neil Boothc8db43d2007-09-22 02:56:19 +00001660 lostFraction = lfExactlyZero;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001661 newPartCount = partCountForBits(toSemantics.precision + 1);
Neil Boothc8db43d2007-09-22 02:56:19 +00001662 oldPartCount = partCount();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001663
Neil Boothc8db43d2007-09-22 02:56:19 +00001664 /* Handle storage complications. If our new form is wider,
1665 re-allocate our bit pattern into wider storage. If it is
1666 narrower, we ignore the excess parts, but if narrowing to a
Dale Johannesen902ff942007-09-25 17:25:00 +00001667 single part we need to free the old storage.
1668 Be careful not to reference significandParts for zeroes
1669 and infinities, since it aborts. */
Neil Boothc8db43d2007-09-22 02:56:19 +00001670 if (newPartCount > oldPartCount) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001671 integerPart *newParts;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001672 newParts = new integerPart[newPartCount];
1673 APInt::tcSet(newParts, 0, newPartCount);
Dale Johannesen902ff942007-09-25 17:25:00 +00001674 if (category==fcNormal || category==fcNaN)
1675 APInt::tcAssign(newParts, significandParts(), oldPartCount);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001676 freeSignificand();
1677 significand.parts = newParts;
Neil Boothc8db43d2007-09-22 02:56:19 +00001678 } else if (newPartCount < oldPartCount) {
1679 /* Capture any lost fraction through truncation of parts so we get
1680 correct rounding whilst normalizing. */
Dale Johannesen902ff942007-09-25 17:25:00 +00001681 if (category==fcNormal)
1682 lostFraction = lostFractionThroughTruncation
1683 (significandParts(), oldPartCount, toSemantics.precision);
1684 if (newPartCount == 1) {
1685 integerPart newPart = 0;
Neil Booth4f881702007-09-26 21:33:42 +00001686 if (category==fcNormal || category==fcNaN)
Dale Johannesen902ff942007-09-25 17:25:00 +00001687 newPart = significandParts()[0];
1688 freeSignificand();
1689 significand.part = newPart;
1690 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001691 }
1692
1693 if(category == fcNormal) {
1694 /* Re-interpret our bit-pattern. */
1695 exponent += toSemantics.precision - semantics->precision;
1696 semantics = &toSemantics;
Neil Boothc8db43d2007-09-22 02:56:19 +00001697 fs = normalize(rounding_mode, lostFraction);
Dale Johannesen902ff942007-09-25 17:25:00 +00001698 } else if (category == fcNaN) {
1699 int shift = toSemantics.precision - semantics->precision;
1700 // No normalization here, just truncate
1701 if (shift>0)
1702 APInt::tcShiftLeft(significandParts(), newPartCount, shift);
1703 else if (shift < 0)
1704 APInt::tcShiftRight(significandParts(), newPartCount, -shift);
1705 // gcc forces the Quiet bit on, which means (float)(double)(float_sNan)
1706 // does not give you back the same bits. This is dubious, and we
1707 // don't currently do it. You're really supposed to get
1708 // an invalid operation signal at runtime, but nobody does that.
1709 semantics = &toSemantics;
1710 fs = opOK;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001711 } else {
1712 semantics = &toSemantics;
1713 fs = opOK;
1714 }
1715
1716 return fs;
1717}
1718
1719/* Convert a floating point number to an integer according to the
1720 rounding mode. If the rounded integer value is out of range this
1721 returns an invalid operation exception. If the rounded value is in
1722 range but the floating point number is not the exact integer, the C
1723 standard doesn't require an inexact exception to be raised. IEEE
1724 854 does require it so we do that.
1725
1726 Note that for conversions to integer type the C standard requires
1727 round-to-zero to always be used. */
1728APFloat::opStatus
1729APFloat::convertToInteger(integerPart *parts, unsigned int width,
Neil Booth4f881702007-09-26 21:33:42 +00001730 bool isSigned,
1731 roundingMode rounding_mode) const
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001732{
Dale Johannesena471c2e2007-10-11 18:07:22 +00001733 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
1734 "Compile-time arithmetic on PPC long double not supported yet");
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001735 lostFraction lost_fraction;
1736 unsigned int msb, partsCount;
1737 int bits;
1738
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001739 partsCount = partCountForBits(width);
1740
Dale Johannesen0edc47a2007-09-25 23:07:07 +00001741 /* Handle the three special cases first. We produce
1742 a deterministic result even for the Invalid cases. */
1743 if (category == fcNaN) {
1744 // Neither sign nor isSigned affects this.
1745 APInt::tcSet(parts, 0, partsCount);
1746 return opInvalidOp;
1747 }
1748 if (category == fcInfinity) {
1749 if (!sign && isSigned)
1750 APInt::tcSetLeastSignificantBits(parts, partsCount, width-1);
1751 else if (!sign && !isSigned)
1752 APInt::tcSetLeastSignificantBits(parts, partsCount, width);
1753 else if (sign && isSigned) {
1754 APInt::tcSetLeastSignificantBits(parts, partsCount, 1);
1755 APInt::tcShiftLeft(parts, partsCount, width-1);
1756 } else // sign && !isSigned
1757 APInt::tcSet(parts, 0, partsCount);
1758 return opInvalidOp;
1759 }
1760 if (category == fcZero) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001761 APInt::tcSet(parts, 0, partsCount);
1762 return opOK;
1763 }
1764
1765 /* Shift the bit pattern so the fraction is lost. */
1766 APFloat tmp(*this);
1767
1768 bits = (int) semantics->precision - 1 - exponent;
1769
1770 if(bits > 0) {
1771 lost_fraction = tmp.shiftSignificandRight(bits);
1772 } else {
Dale Johannesen0edc47a2007-09-25 23:07:07 +00001773 if (-bits >= semantics->precision) {
1774 // Unrepresentably large.
1775 if (!sign && isSigned)
1776 APInt::tcSetLeastSignificantBits(parts, partsCount, width-1);
1777 else if (!sign && !isSigned)
1778 APInt::tcSetLeastSignificantBits(parts, partsCount, width);
1779 else if (sign && isSigned) {
1780 APInt::tcSetLeastSignificantBits(parts, partsCount, 1);
1781 APInt::tcShiftLeft(parts, partsCount, width-1);
1782 } else // sign && !isSigned
1783 APInt::tcSet(parts, 0, partsCount);
1784 return (opStatus)(opOverflow | opInexact);
1785 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001786 tmp.shiftSignificandLeft(-bits);
1787 lost_fraction = lfExactlyZero;
1788 }
1789
1790 if(lost_fraction != lfExactlyZero
Neil Boothb7dea4c2007-10-03 15:16:41 +00001791 && tmp.roundAwayFromZero(rounding_mode, lost_fraction, 0))
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001792 tmp.incrementSignificand();
1793
1794 msb = tmp.significandMSB();
1795
1796 /* Negative numbers cannot be represented as unsigned. */
1797 if(!isSigned && tmp.sign && msb != -1U)
1798 return opInvalidOp;
1799
1800 /* It takes exponent + 1 bits to represent the truncated floating
1801 point number without its sign. We lose a bit for the sign, but
1802 the maximally negative integer is a special case. */
Neil Booth4f881702007-09-26 21:33:42 +00001803 if(msb + 1 > width) /* !! Not same as msb >= width !! */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001804 return opInvalidOp;
1805
1806 if(isSigned && msb + 1 == width
1807 && (!tmp.sign || tmp.significandLSB() != msb))
1808 return opInvalidOp;
1809
1810 APInt::tcAssign(parts, tmp.significandParts(), partsCount);
1811
1812 if(tmp.sign)
1813 APInt::tcNegate(parts, partsCount);
1814
1815 if(lost_fraction == lfExactlyZero)
1816 return opOK;
1817 else
1818 return opInexact;
1819}
1820
Neil Booth643ce592007-10-07 12:07:53 +00001821/* Convert an unsigned integer SRC to a floating point number,
1822 rounding according to ROUNDING_MODE. The sign of the floating
1823 point number is not modified. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001824APFloat::opStatus
Neil Booth643ce592007-10-07 12:07:53 +00001825APFloat::convertFromUnsignedParts(const integerPart *src,
1826 unsigned int srcCount,
1827 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001828{
Neil Booth5477f852007-10-08 14:39:42 +00001829 unsigned int omsb, precision, dstCount;
Neil Booth643ce592007-10-07 12:07:53 +00001830 integerPart *dst;
Neil Booth5477f852007-10-08 14:39:42 +00001831 lostFraction lost_fraction;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001832
1833 category = fcNormal;
Neil Booth5477f852007-10-08 14:39:42 +00001834 omsb = APInt::tcMSB(src, srcCount) + 1;
Neil Booth643ce592007-10-07 12:07:53 +00001835 dst = significandParts();
1836 dstCount = partCount();
Neil Booth5477f852007-10-08 14:39:42 +00001837 precision = semantics->precision;
Neil Booth643ce592007-10-07 12:07:53 +00001838
Neil Booth5477f852007-10-08 14:39:42 +00001839 /* We want the most significant PRECISON bits of SRC. There may not
1840 be that many; extract what we can. */
1841 if (precision <= omsb) {
1842 exponent = omsb - 1;
Neil Booth643ce592007-10-07 12:07:53 +00001843 lost_fraction = lostFractionThroughTruncation(src, srcCount,
Neil Booth5477f852007-10-08 14:39:42 +00001844 omsb - precision);
1845 APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
1846 } else {
1847 exponent = precision - 1;
1848 lost_fraction = lfExactlyZero;
1849 APInt::tcExtract(dst, dstCount, src, omsb, 0);
Neil Booth643ce592007-10-07 12:07:53 +00001850 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001851
1852 return normalize(rounding_mode, lost_fraction);
1853}
1854
Neil Boothf16c5952007-10-07 12:15:41 +00001855/* Convert a two's complement integer SRC to a floating point number,
1856 rounding according to ROUNDING_MODE. ISSIGNED is true if the
1857 integer is signed, in which case it must be sign-extended. */
1858APFloat::opStatus
1859APFloat::convertFromSignExtendedInteger(const integerPart *src,
1860 unsigned int srcCount,
1861 bool isSigned,
1862 roundingMode rounding_mode)
1863{
Dale Johannesena471c2e2007-10-11 18:07:22 +00001864 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
1865 "Compile-time arithmetic on PPC long double not supported yet");
Neil Boothf16c5952007-10-07 12:15:41 +00001866 opStatus status;
1867
1868 if (isSigned
1869 && APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) {
1870 integerPart *copy;
1871
1872 /* If we're signed and negative negate a copy. */
1873 sign = true;
1874 copy = new integerPart[srcCount];
1875 APInt::tcAssign(copy, src, srcCount);
1876 APInt::tcNegate(copy, srcCount);
1877 status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
1878 delete [] copy;
1879 } else {
1880 sign = false;
1881 status = convertFromUnsignedParts(src, srcCount, rounding_mode);
1882 }
1883
1884 return status;
1885}
1886
Neil Boothccf596a2007-10-07 11:45:55 +00001887/* FIXME: should this just take a const APInt reference? */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001888APFloat::opStatus
Neil Boothccf596a2007-10-07 11:45:55 +00001889APFloat::convertFromZeroExtendedInteger(const integerPart *parts,
1890 unsigned int width, bool isSigned,
1891 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001892{
Dale Johannesena471c2e2007-10-11 18:07:22 +00001893 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
1894 "Compile-time arithmetic on PPC long double not supported yet");
Dale Johannesen910993e2007-09-21 22:09:37 +00001895 unsigned int partCount = partCountForBits(width);
Dale Johannesen910993e2007-09-21 22:09:37 +00001896 APInt api = APInt(width, partCount, parts);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001897
1898 sign = false;
Dale Johannesencce23a42007-09-30 18:17:01 +00001899 if(isSigned && APInt::tcExtractBit(parts, width - 1)) {
1900 sign = true;
1901 api = -api;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001902 }
1903
Neil Booth7a7bc0f2007-10-07 12:10:57 +00001904 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001905}
1906
1907APFloat::opStatus
1908APFloat::convertFromHexadecimalString(const char *p,
Neil Booth4f881702007-09-26 21:33:42 +00001909 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001910{
Dale Johannesena471c2e2007-10-11 18:07:22 +00001911 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
1912 "Compile-time arithmetic on PPC long double not supported yet");
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001913 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;
1995 fltSemantics calcSemantics = { 32767, -32767, 0 };
1996 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{
Dale Johannesena471c2e2007-10-11 18:07:22 +00002142 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
2143 "Compile-time arithmetic on PPC long double not supported yet");
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{
Dale Johannesena471c2e2007-10-11 18:07:22 +00002184 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
2185 "Compile-time arithmetic on PPC long double not supported yet");
Neil Bootha30b0ee2007-10-03 22:26:02 +00002186 char *p;
2187
2188 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}