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