blob: d9f14455e45b86403ba99442e7312c9b1203d810 [file] [log] [blame]
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001//===-- APFloat.cpp - Implement APFloat class -----------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Neil Booth and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements a class to represent arbitrary precision floating
11// point values and provide a variety of arithmetic operations on them.
12//
13//===----------------------------------------------------------------------===//
14
15#include <cassert>
Neil Bootha30b0ee2007-10-03 22:26:02 +000016#include <cstring>
Chris Lattnerb39cdde2007-08-20 22:49:32 +000017#include "llvm/ADT/APFloat.h"
Dale Johannesend3b51fd2007-08-24 05:08:11 +000018#include "llvm/Support/MathExtras.h"
Chris Lattnerb39cdde2007-08-20 22:49:32 +000019
20using namespace llvm;
21
22#define convolve(lhs, rhs) ((lhs) * 4 + (rhs))
23
Neil Bootha30b0ee2007-10-03 22:26:02 +000024/* Assumed in hexadecimal significand parsing, and conversion to
25 hexadecimal strings. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +000026COMPILE_TIME_ASSERT(integerPartWidth % 4 == 0);
27
28namespace llvm {
29
30 /* Represents floating point arithmetic semantics. */
31 struct fltSemantics {
32 /* The largest E such that 2^E is representable; this matches the
33 definition of IEEE 754. */
34 exponent_t maxExponent;
35
36 /* The smallest E such that 2^E is a normalized number; this
37 matches the definition of IEEE 754. */
38 exponent_t minExponent;
39
40 /* Number of bits in the significand. This includes the integer
41 bit. */
Neil Booth7a951ca2007-10-12 15:33:27 +000042 unsigned int precision;
Chris Lattnerb39cdde2007-08-20 22:49:32 +000043 };
44
Neil Booth5b8e0c52007-10-12 15:35:10 +000045 const fltSemantics APFloat::IEEEsingle = { 127, -126, 24 };
46 const fltSemantics APFloat::IEEEdouble = { 1023, -1022, 53 };
47 const fltSemantics APFloat::IEEEquad = { 16383, -16382, 113 };
48 const fltSemantics APFloat::x87DoubleExtended = { 16383, -16382, 64 };
49 const fltSemantics APFloat::Bogus = { 0, 0, 0 };
Dale Johannesena471c2e2007-10-11 18:07:22 +000050
51 // The PowerPC format consists of two doubles. It does not map cleanly
52 // onto the usual format above. For now only storage of constants of
53 // this type is supported, no arithmetic.
Neil Booth5b8e0c52007-10-12 15:35:10 +000054 const fltSemantics APFloat::PPCDoubleDouble = { 1023, -1022, 106 };
Chris Lattnerb39cdde2007-08-20 22:49:32 +000055}
56
57/* Put a bunch of private, handy routines in an anonymous namespace. */
58namespace {
59
60 inline unsigned int
61 partCountForBits(unsigned int bits)
62 {
63 return ((bits) + integerPartWidth - 1) / integerPartWidth;
64 }
65
66 unsigned int
67 digitValue(unsigned int c)
68 {
69 unsigned int r;
70
71 r = c - '0';
72 if(r <= 9)
73 return r;
74
75 return -1U;
76 }
77
78 unsigned int
79 hexDigitValue (unsigned int c)
80 {
81 unsigned int r;
82
83 r = c - '0';
84 if(r <= 9)
85 return r;
86
87 r = c - 'A';
88 if(r <= 5)
89 return r + 10;
90
91 r = c - 'a';
92 if(r <= 5)
93 return r + 10;
94
95 return -1U;
96 }
97
98 /* This is ugly and needs cleaning up, but I don't immediately see
99 how whilst remaining safe. */
100 static int
101 totalExponent(const char *p, int exponentAdjustment)
102 {
103 integerPart unsignedExponent;
104 bool negative, overflow;
105 long exponent;
106
107 /* Move past the exponent letter and sign to the digits. */
108 p++;
109 negative = *p == '-';
110 if(*p == '-' || *p == '+')
111 p++;
112
113 unsignedExponent = 0;
114 overflow = false;
115 for(;;) {
116 unsigned int value;
117
118 value = digitValue(*p);
119 if(value == -1U)
Neil Booth4f881702007-09-26 21:33:42 +0000120 break;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000121
122 p++;
123 unsignedExponent = unsignedExponent * 10 + value;
124 if(unsignedExponent > 65535)
Neil Booth4f881702007-09-26 21:33:42 +0000125 overflow = true;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000126 }
127
128 if(exponentAdjustment > 65535 || exponentAdjustment < -65536)
129 overflow = true;
130
131 if(!overflow) {
132 exponent = unsignedExponent;
133 if(negative)
Neil Booth4f881702007-09-26 21:33:42 +0000134 exponent = -exponent;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000135 exponent += exponentAdjustment;
136 if(exponent > 65535 || exponent < -65536)
Neil Booth4f881702007-09-26 21:33:42 +0000137 overflow = true;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000138 }
139
140 if(overflow)
141 exponent = negative ? -65536: 65535;
142
143 return exponent;
144 }
145
146 const char *
147 skipLeadingZeroesAndAnyDot(const char *p, const char **dot)
148 {
149 *dot = 0;
150 while(*p == '0')
151 p++;
152
153 if(*p == '.') {
154 *dot = p++;
155 while(*p == '0')
Neil Booth4f881702007-09-26 21:33:42 +0000156 p++;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000157 }
158
159 return p;
160 }
161
162 /* Return the trailing fraction of a hexadecimal number.
163 DIGITVALUE is the first hex digit of the fraction, P points to
164 the next digit. */
165 lostFraction
166 trailingHexadecimalFraction(const char *p, unsigned int digitValue)
167 {
168 unsigned int hexDigit;
169
170 /* If the first trailing digit isn't 0 or 8 we can work out the
171 fraction immediately. */
172 if(digitValue > 8)
173 return lfMoreThanHalf;
174 else if(digitValue < 8 && digitValue > 0)
175 return lfLessThanHalf;
176
177 /* Otherwise we need to find the first non-zero digit. */
178 while(*p == '0')
179 p++;
180
181 hexDigit = hexDigitValue(*p);
182
183 /* If we ran off the end it is exactly zero or one-half, otherwise
184 a little more. */
185 if(hexDigit == -1U)
186 return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
187 else
188 return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf;
189 }
190
Neil Boothb7dea4c2007-10-03 15:16:41 +0000191 /* Return the fraction lost were a bignum truncated losing the least
192 significant BITS bits. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000193 lostFraction
Neil Bootha30b0ee2007-10-03 22:26:02 +0000194 lostFractionThroughTruncation(const integerPart *parts,
Neil Booth4f881702007-09-26 21:33:42 +0000195 unsigned int partCount,
196 unsigned int bits)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000197 {
198 unsigned int lsb;
199
200 lsb = APInt::tcLSB(parts, partCount);
201
202 /* Note this is guaranteed true if bits == 0, or LSB == -1U. */
203 if(bits <= lsb)
204 return lfExactlyZero;
205 if(bits == lsb + 1)
206 return lfExactlyHalf;
207 if(bits <= partCount * integerPartWidth
208 && APInt::tcExtractBit(parts, bits - 1))
209 return lfMoreThanHalf;
210
211 return lfLessThanHalf;
212 }
213
214 /* Shift DST right BITS bits noting lost fraction. */
215 lostFraction
216 shiftRight(integerPart *dst, unsigned int parts, unsigned int bits)
217 {
218 lostFraction lost_fraction;
219
220 lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
221
222 APInt::tcShiftRight(dst, parts, bits);
223
224 return lost_fraction;
225 }
Neil Bootha30b0ee2007-10-03 22:26:02 +0000226
Neil Booth33d4c922007-10-07 08:51:21 +0000227 /* Combine the effect of two lost fractions. */
228 lostFraction
229 combineLostFractions(lostFraction moreSignificant,
230 lostFraction lessSignificant)
231 {
232 if(lessSignificant != lfExactlyZero) {
233 if(moreSignificant == lfExactlyZero)
234 moreSignificant = lfLessThanHalf;
235 else if(moreSignificant == lfExactlyHalf)
236 moreSignificant = lfMoreThanHalf;
237 }
238
239 return moreSignificant;
240 }
Neil Bootha30b0ee2007-10-03 22:26:02 +0000241
242 /* Zero at the end to avoid modular arithmetic when adding one; used
243 when rounding up during hexadecimal output. */
244 static const char hexDigitsLower[] = "0123456789abcdef0";
245 static const char hexDigitsUpper[] = "0123456789ABCDEF0";
246 static const char infinityL[] = "infinity";
247 static const char infinityU[] = "INFINITY";
248 static const char NaNL[] = "nan";
249 static const char NaNU[] = "NAN";
250
251 /* Write out an integerPart in hexadecimal, starting with the most
252 significant nibble. Write out exactly COUNT hexdigits, return
253 COUNT. */
254 static unsigned int
255 partAsHex (char *dst, integerPart part, unsigned int count,
256 const char *hexDigitChars)
257 {
258 unsigned int result = count;
259
260 assert (count != 0 && count <= integerPartWidth / 4);
261
262 part >>= (integerPartWidth - 4 * count);
263 while (count--) {
264 dst[count] = hexDigitChars[part & 0xf];
265 part >>= 4;
266 }
267
268 return result;
269 }
270
Neil Booth92f7e8d2007-10-06 07:29:25 +0000271 /* Write out an unsigned decimal integer. */
Neil Bootha30b0ee2007-10-03 22:26:02 +0000272 static char *
Neil Booth92f7e8d2007-10-06 07:29:25 +0000273 writeUnsignedDecimal (char *dst, unsigned int n)
Neil Bootha30b0ee2007-10-03 22:26:02 +0000274 {
Neil Booth92f7e8d2007-10-06 07:29:25 +0000275 char buff[40], *p;
Neil Bootha30b0ee2007-10-03 22:26:02 +0000276
Neil Booth92f7e8d2007-10-06 07:29:25 +0000277 p = buff;
278 do
279 *p++ = '0' + n % 10;
280 while (n /= 10);
281
282 do
283 *dst++ = *--p;
284 while (p != buff);
285
286 return dst;
287 }
288
289 /* Write out a signed decimal integer. */
290 static char *
291 writeSignedDecimal (char *dst, int value)
292 {
293 if (value < 0) {
Neil Bootha30b0ee2007-10-03 22:26:02 +0000294 *dst++ = '-';
Neil Booth92f7e8d2007-10-06 07:29:25 +0000295 dst = writeUnsignedDecimal(dst, -(unsigned) value);
296 } else
297 dst = writeUnsignedDecimal(dst, value);
Neil Bootha30b0ee2007-10-03 22:26:02 +0000298
299 return dst;
300 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000301}
302
303/* Constructors. */
304void
305APFloat::initialize(const fltSemantics *ourSemantics)
306{
307 unsigned int count;
308
309 semantics = ourSemantics;
310 count = partCount();
311 if(count > 1)
312 significand.parts = new integerPart[count];
313}
314
315void
316APFloat::freeSignificand()
317{
318 if(partCount() > 1)
319 delete [] significand.parts;
320}
321
322void
323APFloat::assign(const APFloat &rhs)
324{
325 assert(semantics == rhs.semantics);
326
327 sign = rhs.sign;
328 category = rhs.category;
329 exponent = rhs.exponent;
Dale Johannesena471c2e2007-10-11 18:07:22 +0000330 sign2 = rhs.sign2;
331 exponent2 = rhs.exponent2;
Dale Johanneseneaf08942007-08-31 04:03:46 +0000332 if(category == fcNormal || category == fcNaN)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000333 copySignificand(rhs);
334}
335
336void
337APFloat::copySignificand(const APFloat &rhs)
338{
Dale Johanneseneaf08942007-08-31 04:03:46 +0000339 assert(category == fcNormal || category == fcNaN);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000340 assert(rhs.partCount() >= partCount());
341
342 APInt::tcAssign(significandParts(), rhs.significandParts(),
Neil Booth4f881702007-09-26 21:33:42 +0000343 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000344}
345
346APFloat &
347APFloat::operator=(const APFloat &rhs)
348{
349 if(this != &rhs) {
350 if(semantics != rhs.semantics) {
351 freeSignificand();
352 initialize(rhs.semantics);
353 }
354 assign(rhs);
355 }
356
357 return *this;
358}
359
Dale Johannesen343e7702007-08-24 00:56:33 +0000360bool
Dale Johannesen12595d72007-08-24 22:09:56 +0000361APFloat::bitwiseIsEqual(const APFloat &rhs) const {
Dale Johannesen343e7702007-08-24 00:56:33 +0000362 if (this == &rhs)
363 return true;
364 if (semantics != rhs.semantics ||
Dale Johanneseneaf08942007-08-31 04:03:46 +0000365 category != rhs.category ||
366 sign != rhs.sign)
Dale Johannesen343e7702007-08-24 00:56:33 +0000367 return false;
Dale Johannesena471c2e2007-10-11 18:07:22 +0000368 if (semantics==(const llvm::fltSemantics* const)&PPCDoubleDouble &&
369 sign2 != rhs.sign2)
370 return false;
Dale Johanneseneaf08942007-08-31 04:03:46 +0000371 if (category==fcZero || category==fcInfinity)
Dale Johannesen343e7702007-08-24 00:56:33 +0000372 return true;
Dale Johanneseneaf08942007-08-31 04:03:46 +0000373 else if (category==fcNormal && exponent!=rhs.exponent)
374 return false;
Dale Johannesena471c2e2007-10-11 18:07:22 +0000375 else if (semantics==(const llvm::fltSemantics* const)&PPCDoubleDouble &&
376 exponent2!=rhs.exponent2)
377 return false;
Dale Johannesen343e7702007-08-24 00:56:33 +0000378 else {
Dale Johannesen343e7702007-08-24 00:56:33 +0000379 int i= partCount();
380 const integerPart* p=significandParts();
381 const integerPart* q=rhs.significandParts();
382 for (; i>0; i--, p++, q++) {
383 if (*p != *q)
384 return false;
385 }
386 return true;
387 }
388}
389
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000390APFloat::APFloat(const fltSemantics &ourSemantics, integerPart value)
391{
Dale Johannesena471c2e2007-10-11 18:07:22 +0000392 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
393 "Compile-time arithmetic on PPC long double not supported yet");
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000394 initialize(&ourSemantics);
395 sign = 0;
396 zeroSignificand();
397 exponent = ourSemantics.precision - 1;
398 significandParts()[0] = value;
399 normalize(rmNearestTiesToEven, lfExactlyZero);
400}
401
402APFloat::APFloat(const fltSemantics &ourSemantics,
Neil Booth4f881702007-09-26 21:33:42 +0000403 fltCategory ourCategory, bool negative)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000404{
Dale Johannesena471c2e2007-10-11 18:07:22 +0000405 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
406 "Compile-time arithmetic on PPC long double not supported yet");
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000407 initialize(&ourSemantics);
408 category = ourCategory;
409 sign = negative;
410 if(category == fcNormal)
411 category = fcZero;
412}
413
414APFloat::APFloat(const fltSemantics &ourSemantics, const char *text)
415{
Dale Johannesena471c2e2007-10-11 18:07:22 +0000416 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
417 "Compile-time arithmetic on PPC long double not supported yet");
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000418 initialize(&ourSemantics);
419 convertFromString(text, rmNearestTiesToEven);
420}
421
422APFloat::APFloat(const APFloat &rhs)
423{
424 initialize(rhs.semantics);
425 assign(rhs);
426}
427
428APFloat::~APFloat()
429{
430 freeSignificand();
431}
432
433unsigned int
434APFloat::partCount() const
435{
Dale Johannesena72a5a02007-09-20 23:47:58 +0000436 return partCountForBits(semantics->precision + 1);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000437}
438
439unsigned int
440APFloat::semanticsPrecision(const fltSemantics &semantics)
441{
442 return semantics.precision;
443}
444
445const integerPart *
446APFloat::significandParts() const
447{
448 return const_cast<APFloat *>(this)->significandParts();
449}
450
451integerPart *
452APFloat::significandParts()
453{
Dale Johanneseneaf08942007-08-31 04:03:46 +0000454 assert(category == fcNormal || category == fcNaN);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000455
456 if(partCount() > 1)
457 return significand.parts;
458 else
459 return &significand.part;
460}
461
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000462void
463APFloat::zeroSignificand()
464{
465 category = fcNormal;
466 APInt::tcSet(significandParts(), 0, partCount());
467}
468
469/* Increment an fcNormal floating point number's significand. */
470void
471APFloat::incrementSignificand()
472{
473 integerPart carry;
474
475 carry = APInt::tcIncrement(significandParts(), partCount());
476
477 /* Our callers should never cause us to overflow. */
478 assert(carry == 0);
479}
480
481/* Add the significand of the RHS. Returns the carry flag. */
482integerPart
483APFloat::addSignificand(const APFloat &rhs)
484{
485 integerPart *parts;
486
487 parts = significandParts();
488
489 assert(semantics == rhs.semantics);
490 assert(exponent == rhs.exponent);
491
492 return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
493}
494
495/* Subtract the significand of the RHS with a borrow flag. Returns
496 the borrow flag. */
497integerPart
498APFloat::subtractSignificand(const APFloat &rhs, integerPart borrow)
499{
500 integerPart *parts;
501
502 parts = significandParts();
503
504 assert(semantics == rhs.semantics);
505 assert(exponent == rhs.exponent);
506
507 return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
Neil Booth4f881702007-09-26 21:33:42 +0000508 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000509}
510
511/* Multiply the significand of the RHS. If ADDEND is non-NULL, add it
512 on to the full-precision result of the multiplication. Returns the
513 lost fraction. */
514lostFraction
515APFloat::multiplySignificand(const APFloat &rhs, const APFloat *addend)
516{
Neil Booth4f881702007-09-26 21:33:42 +0000517 unsigned int omsb; // One, not zero, based MSB.
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000518 unsigned int partsCount, newPartsCount, precision;
519 integerPart *lhsSignificand;
520 integerPart scratch[4];
521 integerPart *fullSignificand;
522 lostFraction lost_fraction;
523
524 assert(semantics == rhs.semantics);
525
526 precision = semantics->precision;
527 newPartsCount = partCountForBits(precision * 2);
528
529 if(newPartsCount > 4)
530 fullSignificand = new integerPart[newPartsCount];
531 else
532 fullSignificand = scratch;
533
534 lhsSignificand = significandParts();
535 partsCount = partCount();
536
537 APInt::tcFullMultiply(fullSignificand, lhsSignificand,
Neil Booth978661d2007-10-06 00:24:48 +0000538 rhs.significandParts(), partsCount, partsCount);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000539
540 lost_fraction = lfExactlyZero;
541 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
542 exponent += rhs.exponent;
543
544 if(addend) {
545 Significand savedSignificand = significand;
546 const fltSemantics *savedSemantics = semantics;
547 fltSemantics extendedSemantics;
548 opStatus status;
549 unsigned int extendedPrecision;
550
551 /* Normalize our MSB. */
552 extendedPrecision = precision + precision - 1;
553 if(omsb != extendedPrecision)
554 {
Neil Booth4f881702007-09-26 21:33:42 +0000555 APInt::tcShiftLeft(fullSignificand, newPartsCount,
556 extendedPrecision - omsb);
557 exponent -= extendedPrecision - omsb;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000558 }
559
560 /* Create new semantics. */
561 extendedSemantics = *semantics;
562 extendedSemantics.precision = extendedPrecision;
563
564 if(newPartsCount == 1)
565 significand.part = fullSignificand[0];
566 else
567 significand.parts = fullSignificand;
568 semantics = &extendedSemantics;
569
570 APFloat extendedAddend(*addend);
571 status = extendedAddend.convert(extendedSemantics, rmTowardZero);
572 assert(status == opOK);
573 lost_fraction = addOrSubtractSignificand(extendedAddend, false);
574
575 /* Restore our state. */
576 if(newPartsCount == 1)
577 fullSignificand[0] = significand.part;
578 significand = savedSignificand;
579 semantics = savedSemantics;
580
581 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
582 }
583
584 exponent -= (precision - 1);
585
586 if(omsb > precision) {
587 unsigned int bits, significantParts;
588 lostFraction lf;
589
590 bits = omsb - precision;
591 significantParts = partCountForBits(omsb);
592 lf = shiftRight(fullSignificand, significantParts, bits);
593 lost_fraction = combineLostFractions(lf, lost_fraction);
594 exponent += bits;
595 }
596
597 APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
598
599 if(newPartsCount > 4)
600 delete [] fullSignificand;
601
602 return lost_fraction;
603}
604
605/* Multiply the significands of LHS and RHS to DST. */
606lostFraction
607APFloat::divideSignificand(const APFloat &rhs)
608{
609 unsigned int bit, i, partsCount;
610 const integerPart *rhsSignificand;
611 integerPart *lhsSignificand, *dividend, *divisor;
612 integerPart scratch[4];
613 lostFraction lost_fraction;
614
615 assert(semantics == rhs.semantics);
616
617 lhsSignificand = significandParts();
618 rhsSignificand = rhs.significandParts();
619 partsCount = partCount();
620
621 if(partsCount > 2)
622 dividend = new integerPart[partsCount * 2];
623 else
624 dividend = scratch;
625
626 divisor = dividend + partsCount;
627
628 /* Copy the dividend and divisor as they will be modified in-place. */
629 for(i = 0; i < partsCount; i++) {
630 dividend[i] = lhsSignificand[i];
631 divisor[i] = rhsSignificand[i];
632 lhsSignificand[i] = 0;
633 }
634
635 exponent -= rhs.exponent;
636
637 unsigned int precision = semantics->precision;
638
639 /* Normalize the divisor. */
640 bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
641 if(bit) {
642 exponent += bit;
643 APInt::tcShiftLeft(divisor, partsCount, bit);
644 }
645
646 /* Normalize the dividend. */
647 bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
648 if(bit) {
649 exponent -= bit;
650 APInt::tcShiftLeft(dividend, partsCount, bit);
651 }
652
653 if(APInt::tcCompare(dividend, divisor, partsCount) < 0) {
654 exponent--;
655 APInt::tcShiftLeft(dividend, partsCount, 1);
656 assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
657 }
658
659 /* Long division. */
660 for(bit = precision; bit; bit -= 1) {
661 if(APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
662 APInt::tcSubtract(dividend, divisor, 0, partsCount);
663 APInt::tcSetBit(lhsSignificand, bit - 1);
664 }
665
666 APInt::tcShiftLeft(dividend, partsCount, 1);
667 }
668
669 /* Figure out the lost fraction. */
670 int cmp = APInt::tcCompare(dividend, divisor, partsCount);
671
672 if(cmp > 0)
673 lost_fraction = lfMoreThanHalf;
674 else if(cmp == 0)
675 lost_fraction = lfExactlyHalf;
676 else if(APInt::tcIsZero(dividend, partsCount))
677 lost_fraction = lfExactlyZero;
678 else
679 lost_fraction = lfLessThanHalf;
680
681 if(partsCount > 2)
682 delete [] dividend;
683
684 return lost_fraction;
685}
686
687unsigned int
688APFloat::significandMSB() const
689{
690 return APInt::tcMSB(significandParts(), partCount());
691}
692
693unsigned int
694APFloat::significandLSB() const
695{
696 return APInt::tcLSB(significandParts(), partCount());
697}
698
699/* Note that a zero result is NOT normalized to fcZero. */
700lostFraction
701APFloat::shiftSignificandRight(unsigned int bits)
702{
703 /* Our exponent should not overflow. */
704 assert((exponent_t) (exponent + bits) >= exponent);
705
706 exponent += bits;
707
708 return shiftRight(significandParts(), partCount(), bits);
709}
710
711/* Shift the significand left BITS bits, subtract BITS from its exponent. */
712void
713APFloat::shiftSignificandLeft(unsigned int bits)
714{
715 assert(bits < semantics->precision);
716
717 if(bits) {
718 unsigned int partsCount = partCount();
719
720 APInt::tcShiftLeft(significandParts(), partsCount, bits);
721 exponent -= bits;
722
723 assert(!APInt::tcIsZero(significandParts(), partsCount));
724 }
725}
726
727APFloat::cmpResult
728APFloat::compareAbsoluteValue(const APFloat &rhs) const
729{
730 int compare;
731
732 assert(semantics == rhs.semantics);
733 assert(category == fcNormal);
734 assert(rhs.category == fcNormal);
735
736 compare = exponent - rhs.exponent;
737
738 /* If exponents are equal, do an unsigned bignum comparison of the
739 significands. */
740 if(compare == 0)
741 compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
Neil Booth4f881702007-09-26 21:33:42 +0000742 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000743
744 if(compare > 0)
745 return cmpGreaterThan;
746 else if(compare < 0)
747 return cmpLessThan;
748 else
749 return cmpEqual;
750}
751
752/* Handle overflow. Sign is preserved. We either become infinity or
753 the largest finite number. */
754APFloat::opStatus
755APFloat::handleOverflow(roundingMode rounding_mode)
756{
757 /* Infinity? */
758 if(rounding_mode == rmNearestTiesToEven
759 || rounding_mode == rmNearestTiesToAway
760 || (rounding_mode == rmTowardPositive && !sign)
761 || (rounding_mode == rmTowardNegative && sign))
762 {
763 category = fcInfinity;
764 return (opStatus) (opOverflow | opInexact);
765 }
766
767 /* Otherwise we become the largest finite number. */
768 category = fcNormal;
769 exponent = semantics->maxExponent;
770 APInt::tcSetLeastSignificantBits(significandParts(), partCount(),
Neil Booth4f881702007-09-26 21:33:42 +0000771 semantics->precision);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000772
773 return opInexact;
774}
775
Neil Boothb7dea4c2007-10-03 15:16:41 +0000776/* Returns TRUE if, when truncating the current number, with BIT the
777 new LSB, with the given lost fraction and rounding mode, the result
778 would need to be rounded away from zero (i.e., by increasing the
779 signficand). This routine must work for fcZero of both signs, and
780 fcNormal numbers. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000781bool
782APFloat::roundAwayFromZero(roundingMode rounding_mode,
Neil Boothb7dea4c2007-10-03 15:16:41 +0000783 lostFraction lost_fraction,
784 unsigned int bit) const
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000785{
Dale Johanneseneaf08942007-08-31 04:03:46 +0000786 /* NaNs and infinities should not have lost fractions. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000787 assert(category == fcNormal || category == fcZero);
788
Neil Boothb7dea4c2007-10-03 15:16:41 +0000789 /* Current callers never pass this so we don't handle it. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000790 assert(lost_fraction != lfExactlyZero);
791
792 switch(rounding_mode) {
793 default:
794 assert(0);
795
796 case rmNearestTiesToAway:
797 return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
798
799 case rmNearestTiesToEven:
800 if(lost_fraction == lfMoreThanHalf)
801 return true;
802
803 /* Our zeroes don't have a significand to test. */
804 if(lost_fraction == lfExactlyHalf && category != fcZero)
Neil Boothb7dea4c2007-10-03 15:16:41 +0000805 return APInt::tcExtractBit(significandParts(), bit);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000806
807 return false;
808
809 case rmTowardZero:
810 return false;
811
812 case rmTowardPositive:
813 return sign == false;
814
815 case rmTowardNegative:
816 return sign == true;
817 }
818}
819
820APFloat::opStatus
821APFloat::normalize(roundingMode rounding_mode,
Neil Booth4f881702007-09-26 21:33:42 +0000822 lostFraction lost_fraction)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000823{
Neil Booth4f881702007-09-26 21:33:42 +0000824 unsigned int omsb; /* One, not zero, based MSB. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000825 int exponentChange;
826
827 if(category != fcNormal)
828 return opOK;
829
830 /* Before rounding normalize the exponent of fcNormal numbers. */
831 omsb = significandMSB() + 1;
832
833 if(omsb) {
834 /* OMSB is numbered from 1. We want to place it in the integer
835 bit numbered PRECISON if possible, with a compensating change in
836 the exponent. */
837 exponentChange = omsb - semantics->precision;
838
839 /* If the resulting exponent is too high, overflow according to
840 the rounding mode. */
841 if(exponent + exponentChange > semantics->maxExponent)
842 return handleOverflow(rounding_mode);
843
844 /* Subnormal numbers have exponent minExponent, and their MSB
845 is forced based on that. */
846 if(exponent + exponentChange < semantics->minExponent)
847 exponentChange = semantics->minExponent - exponent;
848
849 /* Shifting left is easy as we don't lose precision. */
850 if(exponentChange < 0) {
851 assert(lost_fraction == lfExactlyZero);
852
853 shiftSignificandLeft(-exponentChange);
854
855 return opOK;
856 }
857
858 if(exponentChange > 0) {
859 lostFraction lf;
860
861 /* Shift right and capture any new lost fraction. */
862 lf = shiftSignificandRight(exponentChange);
863
864 lost_fraction = combineLostFractions(lf, lost_fraction);
865
866 /* Keep OMSB up-to-date. */
867 if(omsb > (unsigned) exponentChange)
Neil Booth4f881702007-09-26 21:33:42 +0000868 omsb -= (unsigned) exponentChange;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000869 else
Neil Booth4f881702007-09-26 21:33:42 +0000870 omsb = 0;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000871 }
872 }
873
874 /* Now round the number according to rounding_mode given the lost
875 fraction. */
876
877 /* As specified in IEEE 754, since we do not trap we do not report
878 underflow for exact results. */
879 if(lost_fraction == lfExactlyZero) {
880 /* Canonicalize zeroes. */
881 if(omsb == 0)
882 category = fcZero;
883
884 return opOK;
885 }
886
887 /* Increment the significand if we're rounding away from zero. */
Neil Boothb7dea4c2007-10-03 15:16:41 +0000888 if(roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000889 if(omsb == 0)
890 exponent = semantics->minExponent;
891
892 incrementSignificand();
893 omsb = significandMSB() + 1;
894
895 /* Did the significand increment overflow? */
896 if(omsb == (unsigned) semantics->precision + 1) {
897 /* Renormalize by incrementing the exponent and shifting our
Neil Booth4f881702007-09-26 21:33:42 +0000898 significand right one. However if we already have the
899 maximum exponent we overflow to infinity. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000900 if(exponent == semantics->maxExponent) {
Neil Booth4f881702007-09-26 21:33:42 +0000901 category = fcInfinity;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000902
Neil Booth4f881702007-09-26 21:33:42 +0000903 return (opStatus) (opOverflow | opInexact);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000904 }
905
906 shiftSignificandRight(1);
907
908 return opInexact;
909 }
910 }
911
912 /* The normal case - we were and are not denormal, and any
913 significand increment above didn't overflow. */
914 if(omsb == semantics->precision)
915 return opInexact;
916
917 /* We have a non-zero denormal. */
918 assert(omsb < semantics->precision);
919 assert(exponent == semantics->minExponent);
920
921 /* Canonicalize zeroes. */
922 if(omsb == 0)
923 category = fcZero;
924
925 /* The fcZero case is a denormal that underflowed to zero. */
926 return (opStatus) (opUnderflow | opInexact);
927}
928
929APFloat::opStatus
930APFloat::addOrSubtractSpecials(const APFloat &rhs, bool subtract)
931{
932 switch(convolve(category, rhs.category)) {
933 default:
934 assert(0);
935
Dale Johanneseneaf08942007-08-31 04:03:46 +0000936 case convolve(fcNaN, fcZero):
937 case convolve(fcNaN, fcNormal):
938 case convolve(fcNaN, fcInfinity):
939 case convolve(fcNaN, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000940 case convolve(fcNormal, fcZero):
941 case convolve(fcInfinity, fcNormal):
942 case convolve(fcInfinity, fcZero):
943 return opOK;
944
Dale Johanneseneaf08942007-08-31 04:03:46 +0000945 case convolve(fcZero, fcNaN):
946 case convolve(fcNormal, fcNaN):
947 case convolve(fcInfinity, fcNaN):
948 category = fcNaN;
949 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000950 return opOK;
951
952 case convolve(fcNormal, fcInfinity):
953 case convolve(fcZero, fcInfinity):
954 category = fcInfinity;
955 sign = rhs.sign ^ subtract;
956 return opOK;
957
958 case convolve(fcZero, fcNormal):
959 assign(rhs);
960 sign = rhs.sign ^ subtract;
961 return opOK;
962
963 case convolve(fcZero, fcZero):
964 /* Sign depends on rounding mode; handled by caller. */
965 return opOK;
966
967 case convolve(fcInfinity, fcInfinity):
968 /* Differently signed infinities can only be validly
969 subtracted. */
970 if(sign ^ rhs.sign != subtract) {
Dale Johanneseneaf08942007-08-31 04:03:46 +0000971 category = fcNaN;
972 // Arbitrary but deterministic value for significand
973 APInt::tcSet(significandParts(), ~0U, partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000974 return opInvalidOp;
975 }
976
977 return opOK;
978
979 case convolve(fcNormal, fcNormal):
980 return opDivByZero;
981 }
982}
983
984/* Add or subtract two normal numbers. */
985lostFraction
986APFloat::addOrSubtractSignificand(const APFloat &rhs, bool subtract)
987{
988 integerPart carry;
989 lostFraction lost_fraction;
990 int bits;
991
992 /* Determine if the operation on the absolute values is effectively
993 an addition or subtraction. */
994 subtract ^= (sign ^ rhs.sign);
995
996 /* Are we bigger exponent-wise than the RHS? */
997 bits = exponent - rhs.exponent;
998
999 /* Subtraction is more subtle than one might naively expect. */
1000 if(subtract) {
1001 APFloat temp_rhs(rhs);
1002 bool reverse;
1003
Chris Lattnerada530b2007-08-24 03:02:34 +00001004 if (bits == 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001005 reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan;
1006 lost_fraction = lfExactlyZero;
Chris Lattnerada530b2007-08-24 03:02:34 +00001007 } else if (bits > 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001008 lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
1009 shiftSignificandLeft(1);
1010 reverse = false;
Chris Lattnerada530b2007-08-24 03:02:34 +00001011 } else {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001012 lost_fraction = shiftSignificandRight(-bits - 1);
1013 temp_rhs.shiftSignificandLeft(1);
1014 reverse = true;
1015 }
1016
Chris Lattnerada530b2007-08-24 03:02:34 +00001017 if (reverse) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001018 carry = temp_rhs.subtractSignificand
Neil Booth4f881702007-09-26 21:33:42 +00001019 (*this, lost_fraction != lfExactlyZero);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001020 copySignificand(temp_rhs);
1021 sign = !sign;
1022 } else {
1023 carry = subtractSignificand
Neil Booth4f881702007-09-26 21:33:42 +00001024 (temp_rhs, lost_fraction != lfExactlyZero);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001025 }
1026
1027 /* Invert the lost fraction - it was on the RHS and
1028 subtracted. */
1029 if(lost_fraction == lfLessThanHalf)
1030 lost_fraction = lfMoreThanHalf;
1031 else if(lost_fraction == lfMoreThanHalf)
1032 lost_fraction = lfLessThanHalf;
1033
1034 /* The code above is intended to ensure that no borrow is
1035 necessary. */
1036 assert(!carry);
1037 } else {
1038 if(bits > 0) {
1039 APFloat temp_rhs(rhs);
1040
1041 lost_fraction = temp_rhs.shiftSignificandRight(bits);
1042 carry = addSignificand(temp_rhs);
1043 } else {
1044 lost_fraction = shiftSignificandRight(-bits);
1045 carry = addSignificand(rhs);
1046 }
1047
1048 /* We have a guard bit; generating a carry cannot happen. */
1049 assert(!carry);
1050 }
1051
1052 return lost_fraction;
1053}
1054
1055APFloat::opStatus
1056APFloat::multiplySpecials(const APFloat &rhs)
1057{
1058 switch(convolve(category, rhs.category)) {
1059 default:
1060 assert(0);
1061
Dale Johanneseneaf08942007-08-31 04:03:46 +00001062 case convolve(fcNaN, fcZero):
1063 case convolve(fcNaN, fcNormal):
1064 case convolve(fcNaN, fcInfinity):
1065 case convolve(fcNaN, fcNaN):
1066 return opOK;
1067
1068 case convolve(fcZero, fcNaN):
1069 case convolve(fcNormal, fcNaN):
1070 case convolve(fcInfinity, fcNaN):
1071 category = fcNaN;
1072 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001073 return opOK;
1074
1075 case convolve(fcNormal, fcInfinity):
1076 case convolve(fcInfinity, fcNormal):
1077 case convolve(fcInfinity, fcInfinity):
1078 category = fcInfinity;
1079 return opOK;
1080
1081 case convolve(fcZero, fcNormal):
1082 case convolve(fcNormal, fcZero):
1083 case convolve(fcZero, fcZero):
1084 category = fcZero;
1085 return opOK;
1086
1087 case convolve(fcZero, fcInfinity):
1088 case convolve(fcInfinity, fcZero):
Dale Johanneseneaf08942007-08-31 04:03:46 +00001089 category = fcNaN;
1090 // Arbitrary but deterministic value for significand
1091 APInt::tcSet(significandParts(), ~0U, partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001092 return opInvalidOp;
1093
1094 case convolve(fcNormal, fcNormal):
1095 return opOK;
1096 }
1097}
1098
1099APFloat::opStatus
1100APFloat::divideSpecials(const APFloat &rhs)
1101{
1102 switch(convolve(category, rhs.category)) {
1103 default:
1104 assert(0);
1105
Dale Johanneseneaf08942007-08-31 04:03:46 +00001106 case convolve(fcNaN, fcZero):
1107 case convolve(fcNaN, fcNormal):
1108 case convolve(fcNaN, fcInfinity):
1109 case convolve(fcNaN, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001110 case convolve(fcInfinity, fcZero):
1111 case convolve(fcInfinity, fcNormal):
1112 case convolve(fcZero, fcInfinity):
1113 case convolve(fcZero, fcNormal):
1114 return opOK;
1115
Dale Johanneseneaf08942007-08-31 04:03:46 +00001116 case convolve(fcZero, fcNaN):
1117 case convolve(fcNormal, fcNaN):
1118 case convolve(fcInfinity, fcNaN):
1119 category = fcNaN;
1120 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001121 return opOK;
1122
1123 case convolve(fcNormal, fcInfinity):
1124 category = fcZero;
1125 return opOK;
1126
1127 case convolve(fcNormal, fcZero):
1128 category = fcInfinity;
1129 return opDivByZero;
1130
1131 case convolve(fcInfinity, fcInfinity):
1132 case convolve(fcZero, fcZero):
Dale Johanneseneaf08942007-08-31 04:03:46 +00001133 category = fcNaN;
1134 // Arbitrary but deterministic value for significand
1135 APInt::tcSet(significandParts(), ~0U, partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001136 return opInvalidOp;
1137
1138 case convolve(fcNormal, fcNormal):
1139 return opOK;
1140 }
1141}
1142
1143/* Change sign. */
1144void
1145APFloat::changeSign()
1146{
1147 /* Look mummy, this one's easy. */
1148 sign = !sign;
1149}
1150
Dale Johannesene15c2db2007-08-31 23:35:31 +00001151void
1152APFloat::clearSign()
1153{
1154 /* So is this one. */
1155 sign = 0;
1156}
1157
1158void
1159APFloat::copySign(const APFloat &rhs)
1160{
1161 /* And this one. */
1162 sign = rhs.sign;
1163}
1164
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001165/* Normalized addition or subtraction. */
1166APFloat::opStatus
1167APFloat::addOrSubtract(const APFloat &rhs, roundingMode rounding_mode,
Neil Booth4f881702007-09-26 21:33:42 +00001168 bool subtract)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001169{
1170 opStatus fs;
1171
1172 fs = addOrSubtractSpecials(rhs, subtract);
1173
1174 /* This return code means it was not a simple case. */
1175 if(fs == opDivByZero) {
1176 lostFraction lost_fraction;
1177
1178 lost_fraction = addOrSubtractSignificand(rhs, subtract);
1179 fs = normalize(rounding_mode, lost_fraction);
1180
1181 /* Can only be zero if we lost no fraction. */
1182 assert(category != fcZero || lost_fraction == lfExactlyZero);
1183 }
1184
1185 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1186 positive zero unless rounding to minus infinity, except that
1187 adding two like-signed zeroes gives that zero. */
1188 if(category == fcZero) {
1189 if(rhs.category != fcZero || (sign == rhs.sign) == subtract)
1190 sign = (rounding_mode == rmTowardNegative);
1191 }
1192
1193 return fs;
1194}
1195
1196/* Normalized addition. */
1197APFloat::opStatus
1198APFloat::add(const APFloat &rhs, roundingMode rounding_mode)
1199{
Dale Johannesena471c2e2007-10-11 18:07:22 +00001200 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
1201 "Compile-time arithmetic on PPC long double not supported yet");
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001202 return addOrSubtract(rhs, rounding_mode, false);
1203}
1204
1205/* Normalized subtraction. */
1206APFloat::opStatus
1207APFloat::subtract(const APFloat &rhs, roundingMode rounding_mode)
1208{
Dale Johannesena471c2e2007-10-11 18:07:22 +00001209 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
1210 "Compile-time arithmetic on PPC long double not supported yet");
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001211 return addOrSubtract(rhs, rounding_mode, true);
1212}
1213
1214/* Normalized multiply. */
1215APFloat::opStatus
1216APFloat::multiply(const APFloat &rhs, roundingMode rounding_mode)
1217{
Dale Johannesena471c2e2007-10-11 18:07:22 +00001218 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
1219 "Compile-time arithmetic on PPC long double not supported yet");
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001220 opStatus fs;
1221
1222 sign ^= rhs.sign;
1223 fs = multiplySpecials(rhs);
1224
1225 if(category == fcNormal) {
1226 lostFraction lost_fraction = multiplySignificand(rhs, 0);
1227 fs = normalize(rounding_mode, lost_fraction);
1228 if(lost_fraction != lfExactlyZero)
1229 fs = (opStatus) (fs | opInexact);
1230 }
1231
1232 return fs;
1233}
1234
1235/* Normalized divide. */
1236APFloat::opStatus
1237APFloat::divide(const APFloat &rhs, roundingMode rounding_mode)
1238{
Dale Johannesena471c2e2007-10-11 18:07:22 +00001239 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
1240 "Compile-time arithmetic on PPC long double not supported yet");
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001241 opStatus fs;
1242
1243 sign ^= rhs.sign;
1244 fs = divideSpecials(rhs);
1245
1246 if(category == fcNormal) {
1247 lostFraction lost_fraction = divideSignificand(rhs);
1248 fs = normalize(rounding_mode, lost_fraction);
1249 if(lost_fraction != lfExactlyZero)
1250 fs = (opStatus) (fs | opInexact);
1251 }
1252
1253 return fs;
1254}
1255
Neil Bootha30b0ee2007-10-03 22:26:02 +00001256/* Normalized remainder. This is not currently doing TRT. */
Dale Johannesene15c2db2007-08-31 23:35:31 +00001257APFloat::opStatus
1258APFloat::mod(const APFloat &rhs, roundingMode rounding_mode)
1259{
Dale Johannesena471c2e2007-10-11 18:07:22 +00001260 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
1261 "Compile-time arithmetic on PPC long double not supported yet");
Dale Johannesene15c2db2007-08-31 23:35:31 +00001262 opStatus fs;
1263 APFloat V = *this;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001264 unsigned int origSign = sign;
Dale Johannesene15c2db2007-08-31 23:35:31 +00001265 fs = V.divide(rhs, rmNearestTiesToEven);
1266 if (fs == opDivByZero)
1267 return fs;
1268
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001269 int parts = partCount();
1270 integerPart *x = new integerPart[parts];
Neil Booth4f881702007-09-26 21:33:42 +00001271 fs = V.convertToInteger(x, parts * integerPartWidth, true,
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001272 rmNearestTiesToEven);
Dale Johannesene15c2db2007-08-31 23:35:31 +00001273 if (fs==opInvalidOp)
1274 return fs;
1275
Neil Boothccf596a2007-10-07 11:45:55 +00001276 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1277 rmNearestTiesToEven);
Dale Johannesene15c2db2007-08-31 23:35:31 +00001278 assert(fs==opOK); // should always work
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001279
Dale Johannesene15c2db2007-08-31 23:35:31 +00001280 fs = V.multiply(rhs, rounding_mode);
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001281 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1282
Dale Johannesene15c2db2007-08-31 23:35:31 +00001283 fs = subtract(V, rounding_mode);
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001284 assert(fs==opOK || fs==opInexact); // likewise
1285
1286 if (isZero())
1287 sign = origSign; // IEEE754 requires this
1288 delete[] x;
Dale Johannesene15c2db2007-08-31 23:35:31 +00001289 return fs;
1290}
1291
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001292/* Normalized fused-multiply-add. */
1293APFloat::opStatus
1294APFloat::fusedMultiplyAdd(const APFloat &multiplicand,
Neil Booth4f881702007-09-26 21:33:42 +00001295 const APFloat &addend,
1296 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001297{
Dale Johannesena471c2e2007-10-11 18:07:22 +00001298 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
1299 "Compile-time arithmetic on PPC long double not supported yet");
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001300 opStatus fs;
1301
1302 /* Post-multiplication sign, before addition. */
1303 sign ^= multiplicand.sign;
1304
1305 /* If and only if all arguments are normal do we need to do an
1306 extended-precision calculation. */
1307 if(category == fcNormal
1308 && multiplicand.category == fcNormal
1309 && addend.category == fcNormal) {
1310 lostFraction lost_fraction;
1311
1312 lost_fraction = multiplySignificand(multiplicand, &addend);
1313 fs = normalize(rounding_mode, lost_fraction);
1314 if(lost_fraction != lfExactlyZero)
1315 fs = (opStatus) (fs | opInexact);
1316
1317 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1318 positive zero unless rounding to minus infinity, except that
1319 adding two like-signed zeroes gives that zero. */
1320 if(category == fcZero && sign != addend.sign)
1321 sign = (rounding_mode == rmTowardNegative);
1322 } else {
1323 fs = multiplySpecials(multiplicand);
1324
1325 /* FS can only be opOK or opInvalidOp. There is no more work
1326 to do in the latter case. The IEEE-754R standard says it is
1327 implementation-defined in this case whether, if ADDEND is a
Dale Johanneseneaf08942007-08-31 04:03:46 +00001328 quiet NaN, we raise invalid op; this implementation does so.
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001329
1330 If we need to do the addition we can do so with normal
1331 precision. */
1332 if(fs == opOK)
1333 fs = addOrSubtract(addend, rounding_mode, false);
1334 }
1335
1336 return fs;
1337}
1338
1339/* Comparison requires normalized numbers. */
1340APFloat::cmpResult
1341APFloat::compare(const APFloat &rhs) const
1342{
Dale Johannesena471c2e2007-10-11 18:07:22 +00001343 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
1344 "Compile-time arithmetic on PPC long double not supported yet");
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001345 cmpResult result;
1346
1347 assert(semantics == rhs.semantics);
1348
1349 switch(convolve(category, rhs.category)) {
1350 default:
1351 assert(0);
1352
Dale Johanneseneaf08942007-08-31 04:03:46 +00001353 case convolve(fcNaN, fcZero):
1354 case convolve(fcNaN, fcNormal):
1355 case convolve(fcNaN, fcInfinity):
1356 case convolve(fcNaN, fcNaN):
1357 case convolve(fcZero, fcNaN):
1358 case convolve(fcNormal, fcNaN):
1359 case convolve(fcInfinity, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001360 return cmpUnordered;
1361
1362 case convolve(fcInfinity, fcNormal):
1363 case convolve(fcInfinity, fcZero):
1364 case convolve(fcNormal, fcZero):
1365 if(sign)
1366 return cmpLessThan;
1367 else
1368 return cmpGreaterThan;
1369
1370 case convolve(fcNormal, fcInfinity):
1371 case convolve(fcZero, fcInfinity):
1372 case convolve(fcZero, fcNormal):
1373 if(rhs.sign)
1374 return cmpGreaterThan;
1375 else
1376 return cmpLessThan;
1377
1378 case convolve(fcInfinity, fcInfinity):
1379 if(sign == rhs.sign)
1380 return cmpEqual;
1381 else if(sign)
1382 return cmpLessThan;
1383 else
1384 return cmpGreaterThan;
1385
1386 case convolve(fcZero, fcZero):
1387 return cmpEqual;
1388
1389 case convolve(fcNormal, fcNormal):
1390 break;
1391 }
1392
1393 /* Two normal numbers. Do they have the same sign? */
1394 if(sign != rhs.sign) {
1395 if(sign)
1396 result = cmpLessThan;
1397 else
1398 result = cmpGreaterThan;
1399 } else {
1400 /* Compare absolute values; invert result if negative. */
1401 result = compareAbsoluteValue(rhs);
1402
1403 if(sign) {
1404 if(result == cmpLessThan)
Neil Booth4f881702007-09-26 21:33:42 +00001405 result = cmpGreaterThan;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001406 else if(result == cmpGreaterThan)
Neil Booth4f881702007-09-26 21:33:42 +00001407 result = cmpLessThan;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001408 }
1409 }
1410
1411 return result;
1412}
1413
1414APFloat::opStatus
1415APFloat::convert(const fltSemantics &toSemantics,
Neil Booth4f881702007-09-26 21:33:42 +00001416 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001417{
Dale Johannesena471c2e2007-10-11 18:07:22 +00001418 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
1419 "Compile-time arithmetic on PPC long double not supported yet");
Neil Boothc8db43d2007-09-22 02:56:19 +00001420 lostFraction lostFraction;
1421 unsigned int newPartCount, oldPartCount;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001422 opStatus fs;
Neil Booth4f881702007-09-26 21:33:42 +00001423
Neil Boothc8db43d2007-09-22 02:56:19 +00001424 lostFraction = lfExactlyZero;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001425 newPartCount = partCountForBits(toSemantics.precision + 1);
Neil Boothc8db43d2007-09-22 02:56:19 +00001426 oldPartCount = partCount();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001427
Neil Boothc8db43d2007-09-22 02:56:19 +00001428 /* Handle storage complications. If our new form is wider,
1429 re-allocate our bit pattern into wider storage. If it is
1430 narrower, we ignore the excess parts, but if narrowing to a
Dale Johannesen902ff942007-09-25 17:25:00 +00001431 single part we need to free the old storage.
1432 Be careful not to reference significandParts for zeroes
1433 and infinities, since it aborts. */
Neil Boothc8db43d2007-09-22 02:56:19 +00001434 if (newPartCount > oldPartCount) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001435 integerPart *newParts;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001436 newParts = new integerPart[newPartCount];
1437 APInt::tcSet(newParts, 0, newPartCount);
Dale Johannesen902ff942007-09-25 17:25:00 +00001438 if (category==fcNormal || category==fcNaN)
1439 APInt::tcAssign(newParts, significandParts(), oldPartCount);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001440 freeSignificand();
1441 significand.parts = newParts;
Neil Boothc8db43d2007-09-22 02:56:19 +00001442 } else if (newPartCount < oldPartCount) {
1443 /* Capture any lost fraction through truncation of parts so we get
1444 correct rounding whilst normalizing. */
Dale Johannesen902ff942007-09-25 17:25:00 +00001445 if (category==fcNormal)
1446 lostFraction = lostFractionThroughTruncation
1447 (significandParts(), oldPartCount, toSemantics.precision);
1448 if (newPartCount == 1) {
1449 integerPart newPart = 0;
Neil Booth4f881702007-09-26 21:33:42 +00001450 if (category==fcNormal || category==fcNaN)
Dale Johannesen902ff942007-09-25 17:25:00 +00001451 newPart = significandParts()[0];
1452 freeSignificand();
1453 significand.part = newPart;
1454 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001455 }
1456
1457 if(category == fcNormal) {
1458 /* Re-interpret our bit-pattern. */
1459 exponent += toSemantics.precision - semantics->precision;
1460 semantics = &toSemantics;
Neil Boothc8db43d2007-09-22 02:56:19 +00001461 fs = normalize(rounding_mode, lostFraction);
Dale Johannesen902ff942007-09-25 17:25:00 +00001462 } else if (category == fcNaN) {
1463 int shift = toSemantics.precision - semantics->precision;
1464 // No normalization here, just truncate
1465 if (shift>0)
1466 APInt::tcShiftLeft(significandParts(), newPartCount, shift);
1467 else if (shift < 0)
1468 APInt::tcShiftRight(significandParts(), newPartCount, -shift);
1469 // gcc forces the Quiet bit on, which means (float)(double)(float_sNan)
1470 // does not give you back the same bits. This is dubious, and we
1471 // don't currently do it. You're really supposed to get
1472 // an invalid operation signal at runtime, but nobody does that.
1473 semantics = &toSemantics;
1474 fs = opOK;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001475 } else {
1476 semantics = &toSemantics;
1477 fs = opOK;
1478 }
1479
1480 return fs;
1481}
1482
1483/* Convert a floating point number to an integer according to the
1484 rounding mode. If the rounded integer value is out of range this
1485 returns an invalid operation exception. If the rounded value is in
1486 range but the floating point number is not the exact integer, the C
1487 standard doesn't require an inexact exception to be raised. IEEE
1488 854 does require it so we do that.
1489
1490 Note that for conversions to integer type the C standard requires
1491 round-to-zero to always be used. */
1492APFloat::opStatus
1493APFloat::convertToInteger(integerPart *parts, unsigned int width,
Neil Booth4f881702007-09-26 21:33:42 +00001494 bool isSigned,
1495 roundingMode rounding_mode) const
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001496{
Dale Johannesena471c2e2007-10-11 18:07:22 +00001497 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
1498 "Compile-time arithmetic on PPC long double not supported yet");
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001499 lostFraction lost_fraction;
1500 unsigned int msb, partsCount;
1501 int bits;
1502
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001503 partsCount = partCountForBits(width);
1504
Dale Johannesen0edc47a2007-09-25 23:07:07 +00001505 /* Handle the three special cases first. We produce
1506 a deterministic result even for the Invalid cases. */
1507 if (category == fcNaN) {
1508 // Neither sign nor isSigned affects this.
1509 APInt::tcSet(parts, 0, partsCount);
1510 return opInvalidOp;
1511 }
1512 if (category == fcInfinity) {
1513 if (!sign && isSigned)
1514 APInt::tcSetLeastSignificantBits(parts, partsCount, width-1);
1515 else if (!sign && !isSigned)
1516 APInt::tcSetLeastSignificantBits(parts, partsCount, width);
1517 else if (sign && isSigned) {
1518 APInt::tcSetLeastSignificantBits(parts, partsCount, 1);
1519 APInt::tcShiftLeft(parts, partsCount, width-1);
1520 } else // sign && !isSigned
1521 APInt::tcSet(parts, 0, partsCount);
1522 return opInvalidOp;
1523 }
1524 if (category == fcZero) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001525 APInt::tcSet(parts, 0, partsCount);
1526 return opOK;
1527 }
1528
1529 /* Shift the bit pattern so the fraction is lost. */
1530 APFloat tmp(*this);
1531
1532 bits = (int) semantics->precision - 1 - exponent;
1533
1534 if(bits > 0) {
1535 lost_fraction = tmp.shiftSignificandRight(bits);
1536 } else {
Dale Johannesen0edc47a2007-09-25 23:07:07 +00001537 if (-bits >= semantics->precision) {
1538 // Unrepresentably large.
1539 if (!sign && isSigned)
1540 APInt::tcSetLeastSignificantBits(parts, partsCount, width-1);
1541 else if (!sign && !isSigned)
1542 APInt::tcSetLeastSignificantBits(parts, partsCount, width);
1543 else if (sign && isSigned) {
1544 APInt::tcSetLeastSignificantBits(parts, partsCount, 1);
1545 APInt::tcShiftLeft(parts, partsCount, width-1);
1546 } else // sign && !isSigned
1547 APInt::tcSet(parts, 0, partsCount);
1548 return (opStatus)(opOverflow | opInexact);
1549 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001550 tmp.shiftSignificandLeft(-bits);
1551 lost_fraction = lfExactlyZero;
1552 }
1553
1554 if(lost_fraction != lfExactlyZero
Neil Boothb7dea4c2007-10-03 15:16:41 +00001555 && tmp.roundAwayFromZero(rounding_mode, lost_fraction, 0))
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001556 tmp.incrementSignificand();
1557
1558 msb = tmp.significandMSB();
1559
1560 /* Negative numbers cannot be represented as unsigned. */
1561 if(!isSigned && tmp.sign && msb != -1U)
1562 return opInvalidOp;
1563
1564 /* It takes exponent + 1 bits to represent the truncated floating
1565 point number without its sign. We lose a bit for the sign, but
1566 the maximally negative integer is a special case. */
Neil Booth4f881702007-09-26 21:33:42 +00001567 if(msb + 1 > width) /* !! Not same as msb >= width !! */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001568 return opInvalidOp;
1569
1570 if(isSigned && msb + 1 == width
1571 && (!tmp.sign || tmp.significandLSB() != msb))
1572 return opInvalidOp;
1573
1574 APInt::tcAssign(parts, tmp.significandParts(), partsCount);
1575
1576 if(tmp.sign)
1577 APInt::tcNegate(parts, partsCount);
1578
1579 if(lost_fraction == lfExactlyZero)
1580 return opOK;
1581 else
1582 return opInexact;
1583}
1584
Neil Booth643ce592007-10-07 12:07:53 +00001585/* Convert an unsigned integer SRC to a floating point number,
1586 rounding according to ROUNDING_MODE. The sign of the floating
1587 point number is not modified. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001588APFloat::opStatus
Neil Booth643ce592007-10-07 12:07:53 +00001589APFloat::convertFromUnsignedParts(const integerPart *src,
1590 unsigned int srcCount,
1591 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001592{
Neil Booth5477f852007-10-08 14:39:42 +00001593 unsigned int omsb, precision, dstCount;
Neil Booth643ce592007-10-07 12:07:53 +00001594 integerPart *dst;
Neil Booth5477f852007-10-08 14:39:42 +00001595 lostFraction lost_fraction;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001596
1597 category = fcNormal;
Neil Booth5477f852007-10-08 14:39:42 +00001598 omsb = APInt::tcMSB(src, srcCount) + 1;
Neil Booth643ce592007-10-07 12:07:53 +00001599 dst = significandParts();
1600 dstCount = partCount();
Neil Booth5477f852007-10-08 14:39:42 +00001601 precision = semantics->precision;
Neil Booth643ce592007-10-07 12:07:53 +00001602
Neil Booth5477f852007-10-08 14:39:42 +00001603 /* We want the most significant PRECISON bits of SRC. There may not
1604 be that many; extract what we can. */
1605 if (precision <= omsb) {
1606 exponent = omsb - 1;
Neil Booth643ce592007-10-07 12:07:53 +00001607 lost_fraction = lostFractionThroughTruncation(src, srcCount,
Neil Booth5477f852007-10-08 14:39:42 +00001608 omsb - precision);
1609 APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
1610 } else {
1611 exponent = precision - 1;
1612 lost_fraction = lfExactlyZero;
1613 APInt::tcExtract(dst, dstCount, src, omsb, 0);
Neil Booth643ce592007-10-07 12:07:53 +00001614 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001615
1616 return normalize(rounding_mode, lost_fraction);
1617}
1618
Neil Boothf16c5952007-10-07 12:15:41 +00001619/* Convert a two's complement integer SRC to a floating point number,
1620 rounding according to ROUNDING_MODE. ISSIGNED is true if the
1621 integer is signed, in which case it must be sign-extended. */
1622APFloat::opStatus
1623APFloat::convertFromSignExtendedInteger(const integerPart *src,
1624 unsigned int srcCount,
1625 bool isSigned,
1626 roundingMode rounding_mode)
1627{
Dale Johannesena471c2e2007-10-11 18:07:22 +00001628 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
1629 "Compile-time arithmetic on PPC long double not supported yet");
Neil Boothf16c5952007-10-07 12:15:41 +00001630 opStatus status;
1631
1632 if (isSigned
1633 && APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) {
1634 integerPart *copy;
1635
1636 /* If we're signed and negative negate a copy. */
1637 sign = true;
1638 copy = new integerPart[srcCount];
1639 APInt::tcAssign(copy, src, srcCount);
1640 APInt::tcNegate(copy, srcCount);
1641 status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
1642 delete [] copy;
1643 } else {
1644 sign = false;
1645 status = convertFromUnsignedParts(src, srcCount, rounding_mode);
1646 }
1647
1648 return status;
1649}
1650
Neil Boothccf596a2007-10-07 11:45:55 +00001651/* FIXME: should this just take a const APInt reference? */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001652APFloat::opStatus
Neil Boothccf596a2007-10-07 11:45:55 +00001653APFloat::convertFromZeroExtendedInteger(const integerPart *parts,
1654 unsigned int width, bool isSigned,
1655 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001656{
Dale Johannesena471c2e2007-10-11 18:07:22 +00001657 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
1658 "Compile-time arithmetic on PPC long double not supported yet");
Dale Johannesen910993e2007-09-21 22:09:37 +00001659 unsigned int partCount = partCountForBits(width);
Dale Johannesen910993e2007-09-21 22:09:37 +00001660 APInt api = APInt(width, partCount, parts);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001661
1662 sign = false;
Dale Johannesencce23a42007-09-30 18:17:01 +00001663 if(isSigned && APInt::tcExtractBit(parts, width - 1)) {
1664 sign = true;
1665 api = -api;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001666 }
1667
Neil Booth7a7bc0f2007-10-07 12:10:57 +00001668 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001669}
1670
1671APFloat::opStatus
1672APFloat::convertFromHexadecimalString(const char *p,
Neil Booth4f881702007-09-26 21:33:42 +00001673 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001674{
Dale Johannesena471c2e2007-10-11 18:07:22 +00001675 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
1676 "Compile-time arithmetic on PPC long double not supported yet");
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001677 lostFraction lost_fraction;
1678 integerPart *significand;
1679 unsigned int bitPos, partsCount;
1680 const char *dot, *firstSignificantDigit;
1681
1682 zeroSignificand();
1683 exponent = 0;
1684 category = fcNormal;
1685
1686 significand = significandParts();
1687 partsCount = partCount();
1688 bitPos = partsCount * integerPartWidth;
1689
Neil Booth33d4c922007-10-07 08:51:21 +00001690 /* Skip leading zeroes and any (hexa)decimal point. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001691 p = skipLeadingZeroesAndAnyDot(p, &dot);
1692 firstSignificantDigit = p;
1693
1694 for(;;) {
1695 integerPart hex_value;
1696
1697 if(*p == '.') {
1698 assert(dot == 0);
1699 dot = p++;
1700 }
1701
1702 hex_value = hexDigitValue(*p);
1703 if(hex_value == -1U) {
1704 lost_fraction = lfExactlyZero;
1705 break;
1706 }
1707
1708 p++;
1709
1710 /* Store the number whilst 4-bit nibbles remain. */
1711 if(bitPos) {
1712 bitPos -= 4;
1713 hex_value <<= bitPos % integerPartWidth;
1714 significand[bitPos / integerPartWidth] |= hex_value;
1715 } else {
1716 lost_fraction = trailingHexadecimalFraction(p, hex_value);
1717 while(hexDigitValue(*p) != -1U)
Neil Booth4f881702007-09-26 21:33:42 +00001718 p++;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001719 break;
1720 }
1721 }
1722
1723 /* Hex floats require an exponent but not a hexadecimal point. */
1724 assert(*p == 'p' || *p == 'P');
1725
1726 /* Ignore the exponent if we are zero. */
1727 if(p != firstSignificantDigit) {
1728 int expAdjustment;
1729
1730 /* Implicit hexadecimal point? */
1731 if(!dot)
1732 dot = p;
1733
1734 /* Calculate the exponent adjustment implicit in the number of
1735 significant digits. */
1736 expAdjustment = dot - firstSignificantDigit;
1737 if(expAdjustment < 0)
1738 expAdjustment++;
1739 expAdjustment = expAdjustment * 4 - 1;
1740
1741 /* Adjust for writing the significand starting at the most
1742 significant nibble. */
1743 expAdjustment += semantics->precision;
1744 expAdjustment -= partsCount * integerPartWidth;
1745
1746 /* Adjust for the given exponent. */
1747 exponent = totalExponent(p, expAdjustment);
1748 }
1749
1750 return normalize(rounding_mode, lost_fraction);
1751}
1752
1753APFloat::opStatus
Neil Booth4f881702007-09-26 21:33:42 +00001754APFloat::convertFromString(const char *p, roundingMode rounding_mode)
1755{
Dale Johannesena471c2e2007-10-11 18:07:22 +00001756 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
1757 "Compile-time arithmetic on PPC long double not supported yet");
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001758 /* Handle a leading minus sign. */
1759 if(*p == '-')
1760 sign = 1, p++;
1761 else
1762 sign = 0;
1763
1764 if(p[0] == '0' && (p[1] == 'x' || p[1] == 'X'))
1765 return convertFromHexadecimalString(p + 2, rounding_mode);
Chris Lattnerada530b2007-08-24 03:02:34 +00001766
1767 assert(0 && "Decimal to binary conversions not yet implemented");
1768 abort();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001769}
Dale Johannesen343e7702007-08-24 00:56:33 +00001770
Neil Bootha30b0ee2007-10-03 22:26:02 +00001771/* Write out a hexadecimal representation of the floating point value
1772 to DST, which must be of sufficient size, in the C99 form
1773 [-]0xh.hhhhp[+-]d. Return the number of characters written,
1774 excluding the terminating NUL.
1775
1776 If UPPERCASE, the output is in upper case, otherwise in lower case.
1777
1778 HEXDIGITS digits appear altogether, rounding the value if
1779 necessary. If HEXDIGITS is 0, the minimal precision to display the
1780 number precisely is used instead. If nothing would appear after
1781 the decimal point it is suppressed.
1782
1783 The decimal exponent is always printed and has at least one digit.
1784 Zero values display an exponent of zero. Infinities and NaNs
1785 appear as "infinity" or "nan" respectively.
1786
1787 The above rules are as specified by C99. There is ambiguity about
1788 what the leading hexadecimal digit should be. This implementation
1789 uses whatever is necessary so that the exponent is displayed as
1790 stored. This implies the exponent will fall within the IEEE format
1791 range, and the leading hexadecimal digit will be 0 (for denormals),
1792 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
1793 any other digits zero).
1794*/
1795unsigned int
1796APFloat::convertToHexString(char *dst, unsigned int hexDigits,
1797 bool upperCase, roundingMode rounding_mode) const
1798{
Dale Johannesena471c2e2007-10-11 18:07:22 +00001799 assert(semantics != (const llvm::fltSemantics* const)&PPCDoubleDouble &&
1800 "Compile-time arithmetic on PPC long double not supported yet");
Neil Bootha30b0ee2007-10-03 22:26:02 +00001801 char *p;
1802
1803 p = dst;
1804 if (sign)
1805 *dst++ = '-';
1806
1807 switch (category) {
1808 case fcInfinity:
1809 memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
1810 dst += sizeof infinityL - 1;
1811 break;
1812
1813 case fcNaN:
1814 memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
1815 dst += sizeof NaNU - 1;
1816 break;
1817
1818 case fcZero:
1819 *dst++ = '0';
1820 *dst++ = upperCase ? 'X': 'x';
1821 *dst++ = '0';
1822 if (hexDigits > 1) {
1823 *dst++ = '.';
1824 memset (dst, '0', hexDigits - 1);
1825 dst += hexDigits - 1;
1826 }
1827 *dst++ = upperCase ? 'P': 'p';
1828 *dst++ = '0';
1829 break;
1830
1831 case fcNormal:
1832 dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
1833 break;
1834 }
1835
1836 *dst = 0;
1837
1838 return dst - p;
1839}
1840
1841/* Does the hard work of outputting the correctly rounded hexadecimal
1842 form of a normal floating point number with the specified number of
1843 hexadecimal digits. If HEXDIGITS is zero the minimum number of
1844 digits necessary to print the value precisely is output. */
1845char *
1846APFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
1847 bool upperCase,
1848 roundingMode rounding_mode) const
1849{
1850 unsigned int count, valueBits, shift, partsCount, outputDigits;
1851 const char *hexDigitChars;
1852 const integerPart *significand;
1853 char *p;
1854 bool roundUp;
1855
1856 *dst++ = '0';
1857 *dst++ = upperCase ? 'X': 'x';
1858
1859 roundUp = false;
1860 hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower;
1861
1862 significand = significandParts();
1863 partsCount = partCount();
1864
1865 /* +3 because the first digit only uses the single integer bit, so
1866 we have 3 virtual zero most-significant-bits. */
1867 valueBits = semantics->precision + 3;
1868 shift = integerPartWidth - valueBits % integerPartWidth;
1869
1870 /* The natural number of digits required ignoring trailing
1871 insignificant zeroes. */
1872 outputDigits = (valueBits - significandLSB () + 3) / 4;
1873
1874 /* hexDigits of zero means use the required number for the
1875 precision. Otherwise, see if we are truncating. If we are,
Neil Booth978661d2007-10-06 00:24:48 +00001876 find out if we need to round away from zero. */
Neil Bootha30b0ee2007-10-03 22:26:02 +00001877 if (hexDigits) {
1878 if (hexDigits < outputDigits) {
1879 /* We are dropping non-zero bits, so need to check how to round.
1880 "bits" is the number of dropped bits. */
1881 unsigned int bits;
1882 lostFraction fraction;
1883
1884 bits = valueBits - hexDigits * 4;
1885 fraction = lostFractionThroughTruncation (significand, partsCount, bits);
1886 roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
1887 }
1888 outputDigits = hexDigits;
1889 }
1890
1891 /* Write the digits consecutively, and start writing in the location
1892 of the hexadecimal point. We move the most significant digit
1893 left and add the hexadecimal point later. */
1894 p = ++dst;
1895
1896 count = (valueBits + integerPartWidth - 1) / integerPartWidth;
1897
1898 while (outputDigits && count) {
1899 integerPart part;
1900
1901 /* Put the most significant integerPartWidth bits in "part". */
1902 if (--count == partsCount)
1903 part = 0; /* An imaginary higher zero part. */
1904 else
1905 part = significand[count] << shift;
1906
1907 if (count && shift)
1908 part |= significand[count - 1] >> (integerPartWidth - shift);
1909
1910 /* Convert as much of "part" to hexdigits as we can. */
1911 unsigned int curDigits = integerPartWidth / 4;
1912
1913 if (curDigits > outputDigits)
1914 curDigits = outputDigits;
1915 dst += partAsHex (dst, part, curDigits, hexDigitChars);
1916 outputDigits -= curDigits;
1917 }
1918
1919 if (roundUp) {
1920 char *q = dst;
1921
1922 /* Note that hexDigitChars has a trailing '0'. */
1923 do {
1924 q--;
1925 *q = hexDigitChars[hexDigitValue (*q) + 1];
Neil Booth978661d2007-10-06 00:24:48 +00001926 } while (*q == '0');
1927 assert (q >= p);
Neil Bootha30b0ee2007-10-03 22:26:02 +00001928 } else {
1929 /* Add trailing zeroes. */
1930 memset (dst, '0', outputDigits);
1931 dst += outputDigits;
1932 }
1933
1934 /* Move the most significant digit to before the point, and if there
1935 is something after the decimal point add it. This must come
1936 after rounding above. */
1937 p[-1] = p[0];
1938 if (dst -1 == p)
1939 dst--;
1940 else
1941 p[0] = '.';
1942
1943 /* Finally output the exponent. */
1944 *dst++ = upperCase ? 'P': 'p';
1945
Neil Booth92f7e8d2007-10-06 07:29:25 +00001946 return writeSignedDecimal (dst, exponent);
Neil Bootha30b0ee2007-10-03 22:26:02 +00001947}
1948
Dale Johannesen343e7702007-08-24 00:56:33 +00001949// For good performance it is desirable for different APFloats
1950// to produce different integers.
1951uint32_t
Neil Booth4f881702007-09-26 21:33:42 +00001952APFloat::getHashValue() const
1953{
Dale Johannesen343e7702007-08-24 00:56:33 +00001954 if (category==fcZero) return sign<<8 | semantics->precision ;
1955 else if (category==fcInfinity) return sign<<9 | semantics->precision;
Dale Johanneseneaf08942007-08-31 04:03:46 +00001956 else if (category==fcNaN) return 1<<10 | semantics->precision;
Dale Johannesen343e7702007-08-24 00:56:33 +00001957 else {
1958 uint32_t hash = sign<<11 | semantics->precision | exponent<<12;
1959 const integerPart* p = significandParts();
1960 for (int i=partCount(); i>0; i--, p++)
1961 hash ^= ((uint32_t)*p) ^ (*p)>>32;
1962 return hash;
1963 }
1964}
1965
1966// Conversion from APFloat to/from host float/double. It may eventually be
1967// possible to eliminate these and have everybody deal with APFloats, but that
1968// will take a while. This approach will not easily extend to long double.
Dale Johannesena72a5a02007-09-20 23:47:58 +00001969// Current implementation requires integerPartWidth==64, which is correct at
1970// the moment but could be made more general.
Dale Johannesen343e7702007-08-24 00:56:33 +00001971
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001972// Denormals have exponent minExponent in APFloat, but minExponent-1 in
Dale Johannesena72a5a02007-09-20 23:47:58 +00001973// the actual IEEE respresentations. We compensate for that here.
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001974
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001975APInt
Neil Booth4f881702007-09-26 21:33:42 +00001976APFloat::convertF80LongDoubleAPFloatToAPInt() const
1977{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001978 assert(semantics == (const llvm::fltSemantics* const)&x87DoubleExtended);
Dale Johannesena72a5a02007-09-20 23:47:58 +00001979 assert (partCount()==2);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001980
1981 uint64_t myexponent, mysignificand;
1982
1983 if (category==fcNormal) {
1984 myexponent = exponent+16383; //bias
Dale Johannesena72a5a02007-09-20 23:47:58 +00001985 mysignificand = significandParts()[0];
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001986 if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
1987 myexponent = 0; // denormal
1988 } else if (category==fcZero) {
1989 myexponent = 0;
1990 mysignificand = 0;
1991 } else if (category==fcInfinity) {
1992 myexponent = 0x7fff;
1993 mysignificand = 0x8000000000000000ULL;
Chris Lattnera11ef822007-10-06 06:13:42 +00001994 } else {
1995 assert(category == fcNaN && "Unknown category");
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001996 myexponent = 0x7fff;
Dale Johannesena72a5a02007-09-20 23:47:58 +00001997 mysignificand = significandParts()[0];
Chris Lattnera11ef822007-10-06 06:13:42 +00001998 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001999
2000 uint64_t words[2];
Neil Booth4f881702007-09-26 21:33:42 +00002001 words[0] = (((uint64_t)sign & 1) << 63) |
2002 ((myexponent & 0x7fff) << 48) |
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002003 ((mysignificand >>16) & 0xffffffffffffLL);
2004 words[1] = mysignificand & 0xffff;
Chris Lattnera11ef822007-10-06 06:13:42 +00002005 return APInt(80, 2, words);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002006}
2007
2008APInt
Dale Johannesena471c2e2007-10-11 18:07:22 +00002009APFloat::convertPPCDoubleDoubleAPFloatToAPInt() const
2010{
2011 assert(semantics == (const llvm::fltSemantics* const)&PPCDoubleDouble);
2012 assert (partCount()==2);
2013
2014 uint64_t myexponent, mysignificand, myexponent2, mysignificand2;
2015
2016 if (category==fcNormal) {
2017 myexponent = exponent + 1023; //bias
2018 myexponent2 = exponent2 + 1023;
2019 mysignificand = significandParts()[0];
2020 mysignificand2 = significandParts()[1];
2021 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2022 myexponent = 0; // denormal
2023 if (myexponent2==1 && !(mysignificand2 & 0x10000000000000LL))
2024 myexponent2 = 0; // denormal
2025 } else if (category==fcZero) {
2026 myexponent = 0;
2027 mysignificand = 0;
2028 myexponent2 = 0;
2029 mysignificand2 = 0;
2030 } else if (category==fcInfinity) {
2031 myexponent = 0x7ff;
2032 myexponent2 = 0;
2033 mysignificand = 0;
2034 mysignificand2 = 0;
2035 } else {
2036 assert(category == fcNaN && "Unknown category");
2037 myexponent = 0x7ff;
2038 mysignificand = significandParts()[0];
2039 myexponent2 = exponent2;
2040 mysignificand2 = significandParts()[1];
2041 }
2042
2043 uint64_t words[2];
2044 words[0] = (((uint64_t)sign & 1) << 63) |
2045 ((myexponent & 0x7ff) << 52) |
2046 (mysignificand & 0xfffffffffffffLL);
2047 words[1] = (((uint64_t)sign2 & 1) << 63) |
2048 ((myexponent2 & 0x7ff) << 52) |
2049 (mysignificand2 & 0xfffffffffffffLL);
2050 return APInt(128, 2, words);
2051}
2052
2053APInt
Neil Booth4f881702007-09-26 21:33:42 +00002054APFloat::convertDoubleAPFloatToAPInt() const
2055{
Dan Gohmancb648f92007-09-14 20:08:19 +00002056 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble);
Dale Johannesen343e7702007-08-24 00:56:33 +00002057 assert (partCount()==1);
2058
Dale Johanneseneaf08942007-08-31 04:03:46 +00002059 uint64_t myexponent, mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00002060
2061 if (category==fcNormal) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002062 myexponent = exponent+1023; //bias
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002063 mysignificand = *significandParts();
2064 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2065 myexponent = 0; // denormal
Dale Johannesen343e7702007-08-24 00:56:33 +00002066 } else if (category==fcZero) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002067 myexponent = 0;
2068 mysignificand = 0;
2069 } else if (category==fcInfinity) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002070 myexponent = 0x7ff;
2071 mysignificand = 0;
Chris Lattnera11ef822007-10-06 06:13:42 +00002072 } else {
2073 assert(category == fcNaN && "Unknown category!");
Dale Johannesen343e7702007-08-24 00:56:33 +00002074 myexponent = 0x7ff;
Dale Johanneseneaf08942007-08-31 04:03:46 +00002075 mysignificand = *significandParts();
Chris Lattnera11ef822007-10-06 06:13:42 +00002076 }
Dale Johannesen343e7702007-08-24 00:56:33 +00002077
Chris Lattnera11ef822007-10-06 06:13:42 +00002078 return APInt(64, (((((uint64_t)sign & 1) << 63) |
2079 ((myexponent & 0x7ff) << 52) |
2080 (mysignificand & 0xfffffffffffffLL))));
Dale Johannesen343e7702007-08-24 00:56:33 +00002081}
2082
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002083APInt
Neil Booth4f881702007-09-26 21:33:42 +00002084APFloat::convertFloatAPFloatToAPInt() const
2085{
Dan Gohmancb648f92007-09-14 20:08:19 +00002086 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle);
Dale Johannesen343e7702007-08-24 00:56:33 +00002087 assert (partCount()==1);
Neil Booth4f881702007-09-26 21:33:42 +00002088
Dale Johanneseneaf08942007-08-31 04:03:46 +00002089 uint32_t myexponent, mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00002090
2091 if (category==fcNormal) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002092 myexponent = exponent+127; //bias
2093 mysignificand = *significandParts();
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002094 if (myexponent == 1 && !(mysignificand & 0x400000))
2095 myexponent = 0; // denormal
Dale Johannesen343e7702007-08-24 00:56:33 +00002096 } else if (category==fcZero) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002097 myexponent = 0;
2098 mysignificand = 0;
2099 } else if (category==fcInfinity) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002100 myexponent = 0xff;
2101 mysignificand = 0;
Chris Lattnera11ef822007-10-06 06:13:42 +00002102 } else {
2103 assert(category == fcNaN && "Unknown category!");
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002104 myexponent = 0xff;
Dale Johanneseneaf08942007-08-31 04:03:46 +00002105 mysignificand = *significandParts();
Chris Lattnera11ef822007-10-06 06:13:42 +00002106 }
Dale Johannesen343e7702007-08-24 00:56:33 +00002107
Chris Lattnera11ef822007-10-06 06:13:42 +00002108 return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) |
2109 (mysignificand & 0x7fffff)));
Dale Johannesen343e7702007-08-24 00:56:33 +00002110}
2111
Dale Johannesena471c2e2007-10-11 18:07:22 +00002112// This function creates an APInt that is just a bit map of the floating
2113// point constant as it would appear in memory. It is not a conversion,
2114// and treating the result as a normal integer is unlikely to be useful.
2115
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002116APInt
Neil Booth4f881702007-09-26 21:33:42 +00002117APFloat::convertToAPInt() const
2118{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002119 if (semantics == (const llvm::fltSemantics* const)&IEEEsingle)
2120 return convertFloatAPFloatToAPInt();
Chris Lattnera11ef822007-10-06 06:13:42 +00002121
2122 if (semantics == (const llvm::fltSemantics* const)&IEEEdouble)
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002123 return convertDoubleAPFloatToAPInt();
Neil Booth4f881702007-09-26 21:33:42 +00002124
Dale Johannesena471c2e2007-10-11 18:07:22 +00002125 if (semantics == (const llvm::fltSemantics* const)&PPCDoubleDouble)
2126 return convertPPCDoubleDoubleAPFloatToAPInt();
2127
Chris Lattnera11ef822007-10-06 06:13:42 +00002128 assert(semantics == (const llvm::fltSemantics* const)&x87DoubleExtended &&
2129 "unknown format!");
2130 return convertF80LongDoubleAPFloatToAPInt();
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002131}
2132
Neil Booth4f881702007-09-26 21:33:42 +00002133float
2134APFloat::convertToFloat() const
2135{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002136 assert(semantics == (const llvm::fltSemantics* const)&IEEEsingle);
2137 APInt api = convertToAPInt();
2138 return api.bitsToFloat();
2139}
2140
Neil Booth4f881702007-09-26 21:33:42 +00002141double
2142APFloat::convertToDouble() const
2143{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002144 assert(semantics == (const llvm::fltSemantics* const)&IEEEdouble);
2145 APInt api = convertToAPInt();
2146 return api.bitsToDouble();
2147}
2148
2149/// Integer bit is explicit in this format. Current Intel book does not
2150/// define meaning of:
2151/// exponent = all 1's, integer bit not set.
2152/// exponent = 0, integer bit set. (formerly "psuedodenormals")
2153/// exponent!=0 nor all 1's, integer bit not set. (formerly "unnormals")
2154void
Neil Booth4f881702007-09-26 21:33:42 +00002155APFloat::initFromF80LongDoubleAPInt(const APInt &api)
2156{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002157 assert(api.getBitWidth()==80);
2158 uint64_t i1 = api.getRawData()[0];
2159 uint64_t i2 = api.getRawData()[1];
2160 uint64_t myexponent = (i1 >> 48) & 0x7fff;
2161 uint64_t mysignificand = ((i1 << 16) & 0xffffffffffff0000ULL) |
2162 (i2 & 0xffff);
2163
2164 initialize(&APFloat::x87DoubleExtended);
Dale Johannesena72a5a02007-09-20 23:47:58 +00002165 assert(partCount()==2);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002166
2167 sign = i1>>63;
2168 if (myexponent==0 && mysignificand==0) {
2169 // exponent, significand meaningless
2170 category = fcZero;
2171 } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
2172 // exponent, significand meaningless
2173 category = fcInfinity;
2174 } else if (myexponent==0x7fff && mysignificand!=0x8000000000000000ULL) {
2175 // exponent meaningless
2176 category = fcNaN;
Dale Johannesena72a5a02007-09-20 23:47:58 +00002177 significandParts()[0] = mysignificand;
2178 significandParts()[1] = 0;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002179 } else {
2180 category = fcNormal;
2181 exponent = myexponent - 16383;
Dale Johannesena72a5a02007-09-20 23:47:58 +00002182 significandParts()[0] = mysignificand;
2183 significandParts()[1] = 0;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002184 if (myexponent==0) // denormal
2185 exponent = -16382;
Neil Booth4f881702007-09-26 21:33:42 +00002186 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002187}
2188
2189void
Dale Johannesena471c2e2007-10-11 18:07:22 +00002190APFloat::initFromPPCDoubleDoubleAPInt(const APInt &api)
2191{
2192 assert(api.getBitWidth()==128);
2193 uint64_t i1 = api.getRawData()[0];
2194 uint64_t i2 = api.getRawData()[1];
2195 uint64_t myexponent = (i1 >> 52) & 0x7ff;
2196 uint64_t mysignificand = i1 & 0xfffffffffffffLL;
2197 uint64_t myexponent2 = (i2 >> 52) & 0x7ff;
2198 uint64_t mysignificand2 = i2 & 0xfffffffffffffLL;
2199
2200 initialize(&APFloat::PPCDoubleDouble);
2201 assert(partCount()==2);
2202
2203 sign = i1>>63;
2204 sign2 = i2>>63;
2205 if (myexponent==0 && mysignificand==0) {
2206 // exponent, significand meaningless
2207 // exponent2 and significand2 are required to be 0; we don't check
2208 category = fcZero;
2209 } else if (myexponent==0x7ff && mysignificand==0) {
2210 // exponent, significand meaningless
2211 // exponent2 and significand2 are required to be 0; we don't check
2212 category = fcInfinity;
2213 } else if (myexponent==0x7ff && mysignificand!=0) {
2214 // exponent meaningless. So is the whole second word, but keep it
2215 // for determinism.
2216 category = fcNaN;
2217 exponent2 = myexponent2;
2218 significandParts()[0] = mysignificand;
2219 significandParts()[1] = mysignificand2;
2220 } else {
2221 category = fcNormal;
2222 // Note there is no category2; the second word is treated as if it is
2223 // fcNormal, although it might be something else considered by itself.
2224 exponent = myexponent - 1023;
2225 exponent2 = myexponent2 - 1023;
2226 significandParts()[0] = mysignificand;
2227 significandParts()[1] = mysignificand2;
2228 if (myexponent==0) // denormal
2229 exponent = -1022;
2230 else
2231 significandParts()[0] |= 0x10000000000000LL; // integer bit
2232 if (myexponent2==0)
2233 exponent2 = -1022;
2234 else
2235 significandParts()[1] |= 0x10000000000000LL; // integer bit
2236 }
2237}
2238
2239void
Neil Booth4f881702007-09-26 21:33:42 +00002240APFloat::initFromDoubleAPInt(const APInt &api)
2241{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002242 assert(api.getBitWidth()==64);
2243 uint64_t i = *api.getRawData();
Dale Johannesend3b51fd2007-08-24 05:08:11 +00002244 uint64_t myexponent = (i >> 52) & 0x7ff;
2245 uint64_t mysignificand = i & 0xfffffffffffffLL;
2246
Dale Johannesen343e7702007-08-24 00:56:33 +00002247 initialize(&APFloat::IEEEdouble);
Dale Johannesen343e7702007-08-24 00:56:33 +00002248 assert(partCount()==1);
2249
Dale Johanneseneaf08942007-08-31 04:03:46 +00002250 sign = i>>63;
Dale Johannesen343e7702007-08-24 00:56:33 +00002251 if (myexponent==0 && mysignificand==0) {
2252 // exponent, significand meaningless
2253 category = fcZero;
Dale Johannesen343e7702007-08-24 00:56:33 +00002254 } else if (myexponent==0x7ff && mysignificand==0) {
2255 // exponent, significand meaningless
2256 category = fcInfinity;
Dale Johanneseneaf08942007-08-31 04:03:46 +00002257 } else if (myexponent==0x7ff && mysignificand!=0) {
2258 // exponent meaningless
2259 category = fcNaN;
2260 *significandParts() = mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00002261 } else {
Dale Johannesen343e7702007-08-24 00:56:33 +00002262 category = fcNormal;
2263 exponent = myexponent - 1023;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002264 *significandParts() = mysignificand;
2265 if (myexponent==0) // denormal
2266 exponent = -1022;
2267 else
2268 *significandParts() |= 0x10000000000000LL; // integer bit
Neil Booth4f881702007-09-26 21:33:42 +00002269 }
Dale Johannesen343e7702007-08-24 00:56:33 +00002270}
2271
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002272void
Neil Booth4f881702007-09-26 21:33:42 +00002273APFloat::initFromFloatAPInt(const APInt & api)
2274{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002275 assert(api.getBitWidth()==32);
2276 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesend3b51fd2007-08-24 05:08:11 +00002277 uint32_t myexponent = (i >> 23) & 0xff;
2278 uint32_t mysignificand = i & 0x7fffff;
2279
Dale Johannesen343e7702007-08-24 00:56:33 +00002280 initialize(&APFloat::IEEEsingle);
Dale Johannesen343e7702007-08-24 00:56:33 +00002281 assert(partCount()==1);
2282
Dale Johanneseneaf08942007-08-31 04:03:46 +00002283 sign = i >> 31;
Dale Johannesen343e7702007-08-24 00:56:33 +00002284 if (myexponent==0 && mysignificand==0) {
2285 // exponent, significand meaningless
2286 category = fcZero;
Dale Johannesen343e7702007-08-24 00:56:33 +00002287 } else if (myexponent==0xff && mysignificand==0) {
2288 // exponent, significand meaningless
2289 category = fcInfinity;
Dale Johannesen902ff942007-09-25 17:25:00 +00002290 } else if (myexponent==0xff && mysignificand!=0) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002291 // sign, exponent, significand meaningless
Dale Johanneseneaf08942007-08-31 04:03:46 +00002292 category = fcNaN;
2293 *significandParts() = mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00002294 } else {
2295 category = fcNormal;
Dale Johannesen343e7702007-08-24 00:56:33 +00002296 exponent = myexponent - 127; //bias
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002297 *significandParts() = mysignificand;
2298 if (myexponent==0) // denormal
2299 exponent = -126;
2300 else
2301 *significandParts() |= 0x800000; // integer bit
Dale Johannesen343e7702007-08-24 00:56:33 +00002302 }
2303}
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002304
2305/// Treat api as containing the bits of a floating point number. Currently
Dale Johannesena471c2e2007-10-11 18:07:22 +00002306/// we infer the floating point type from the size of the APInt. The
2307/// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful
2308/// when the size is anything else).
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002309void
Dale Johannesena471c2e2007-10-11 18:07:22 +00002310APFloat::initFromAPInt(const APInt& api, bool isIEEE)
Neil Booth4f881702007-09-26 21:33:42 +00002311{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002312 if (api.getBitWidth() == 32)
2313 return initFromFloatAPInt(api);
2314 else if (api.getBitWidth()==64)
2315 return initFromDoubleAPInt(api);
2316 else if (api.getBitWidth()==80)
2317 return initFromF80LongDoubleAPInt(api);
Dale Johannesena471c2e2007-10-11 18:07:22 +00002318 else if (api.getBitWidth()==128 && !isIEEE)
2319 return initFromPPCDoubleDoubleAPInt(api);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002320 else
2321 assert(0);
2322}
2323
Dale Johannesena471c2e2007-10-11 18:07:22 +00002324APFloat::APFloat(const APInt& api, bool isIEEE)
Neil Booth4f881702007-09-26 21:33:42 +00002325{
Dale Johannesena471c2e2007-10-11 18:07:22 +00002326 initFromAPInt(api, isIEEE);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002327}
2328
Neil Booth4f881702007-09-26 21:33:42 +00002329APFloat::APFloat(float f)
2330{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002331 APInt api = APInt(32, 0);
2332 initFromAPInt(api.floatToBits(f));
2333}
2334
Neil Booth4f881702007-09-26 21:33:42 +00002335APFloat::APFloat(double d)
2336{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002337 APInt api = APInt(64, 0);
2338 initFromAPInt(api.doubleToBits(d));
2339}