pass machinemoduleinfo down into getSymbolForDwarfGlobalReference,
[llvm/avr.git] / lib / Support / APFloat.cpp
blobbcf3d6d012525a554182f8fc20b4d25658304af4
1 //===-- APFloat.cpp - Implement APFloat class -----------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/StringRef.h"
17 #include "llvm/ADT/FoldingSet.h"
18 #include "llvm/Support/ErrorHandling.h"
19 #include "llvm/Support/MathExtras.h"
20 #include <cstring>
22 using namespace llvm;
24 #define convolve(lhs, rhs) ((lhs) * 4 + (rhs))
26 /* Assumed in hexadecimal significand parsing, and conversion to
27 hexadecimal strings. */
28 #define COMPILE_TIME_ASSERT(cond) extern int CTAssert[(cond) ? 1 : -1]
29 COMPILE_TIME_ASSERT(integerPartWidth % 4 == 0);
31 namespace llvm {
33 /* Represents floating point arithmetic semantics. */
34 struct fltSemantics {
35 /* The largest E such that 2^E is representable; this matches the
36 definition of IEEE 754. */
37 exponent_t maxExponent;
39 /* The smallest E such that 2^E is a normalized number; this
40 matches the definition of IEEE 754. */
41 exponent_t minExponent;
43 /* Number of bits in the significand. This includes the integer
44 bit. */
45 unsigned int precision;
47 /* True if arithmetic is supported. */
48 unsigned int arithmeticOK;
51 const fltSemantics APFloat::IEEEsingle = { 127, -126, 24, true };
52 const fltSemantics APFloat::IEEEdouble = { 1023, -1022, 53, true };
53 const fltSemantics APFloat::IEEEquad = { 16383, -16382, 113, true };
54 const fltSemantics APFloat::x87DoubleExtended = { 16383, -16382, 64, true };
55 const fltSemantics APFloat::Bogus = { 0, 0, 0, true };
57 // The PowerPC format consists of two doubles. It does not map cleanly
58 // onto the usual format above. For now only storage of constants of
59 // this type is supported, no arithmetic.
60 const fltSemantics APFloat::PPCDoubleDouble = { 1023, -1022, 106, false };
62 /* A tight upper bound on number of parts required to hold the value
63 pow(5, power) is
65 power * 815 / (351 * integerPartWidth) + 1
67 However, whilst the result may require only this many parts,
68 because we are multiplying two values to get it, the
69 multiplication may require an extra part with the excess part
70 being zero (consider the trivial case of 1 * 1, tcFullMultiply
71 requires two parts to hold the single-part result). So we add an
72 extra one to guarantee enough space whilst multiplying. */
73 const unsigned int maxExponent = 16383;
74 const unsigned int maxPrecision = 113;
75 const unsigned int maxPowerOfFiveExponent = maxExponent + maxPrecision - 1;
76 const unsigned int maxPowerOfFiveParts = 2 + ((maxPowerOfFiveExponent * 815)
77 / (351 * integerPartWidth));
80 /* A bunch of private, handy routines. */
82 static inline unsigned int
83 partCountForBits(unsigned int bits)
85 return ((bits) + integerPartWidth - 1) / integerPartWidth;
88 /* Returns 0U-9U. Return values >= 10U are not digits. */
89 static inline unsigned int
90 decDigitValue(unsigned int c)
92 return c - '0';
95 static unsigned int
96 hexDigitValue(unsigned int c)
98 unsigned int r;
100 r = c - '0';
101 if(r <= 9)
102 return r;
104 r = c - 'A';
105 if(r <= 5)
106 return r + 10;
108 r = c - 'a';
109 if(r <= 5)
110 return r + 10;
112 return -1U;
115 static inline void
116 assertArithmeticOK(const llvm::fltSemantics &semantics) {
117 assert(semantics.arithmeticOK
118 && "Compile-time arithmetic does not support these semantics");
121 /* Return the value of a decimal exponent of the form
122 [+-]ddddddd.
124 If the exponent overflows, returns a large exponent with the
125 appropriate sign. */
126 static int
127 readExponent(StringRef::iterator begin, StringRef::iterator end)
129 bool isNegative;
130 unsigned int absExponent;
131 const unsigned int overlargeExponent = 24000; /* FIXME. */
132 StringRef::iterator p = begin;
134 assert(p != end && "Exponent has no digits");
136 isNegative = (*p == '-');
137 if (*p == '-' || *p == '+') {
138 p++;
139 assert(p != end && "Exponent has no digits");
142 absExponent = decDigitValue(*p++);
143 assert(absExponent < 10U && "Invalid character in exponent");
145 for (; p != end; ++p) {
146 unsigned int value;
148 value = decDigitValue(*p);
149 assert(value < 10U && "Invalid character in exponent");
151 value += absExponent * 10;
152 if (absExponent >= overlargeExponent) {
153 absExponent = overlargeExponent;
154 break;
156 absExponent = value;
159 assert(p == end && "Invalid exponent in exponent");
161 if (isNegative)
162 return -(int) absExponent;
163 else
164 return (int) absExponent;
167 /* This is ugly and needs cleaning up, but I don't immediately see
168 how whilst remaining safe. */
169 static int
170 totalExponent(StringRef::iterator p, StringRef::iterator end,
171 int exponentAdjustment)
173 int unsignedExponent;
174 bool negative, overflow;
175 int exponent;
177 assert(p != end && "Exponent has no digits");
179 negative = *p == '-';
180 if(*p == '-' || *p == '+') {
181 p++;
182 assert(p != end && "Exponent has no digits");
185 unsignedExponent = 0;
186 overflow = false;
187 for(; p != end; ++p) {
188 unsigned int value;
190 value = decDigitValue(*p);
191 assert(value < 10U && "Invalid character in exponent");
193 unsignedExponent = unsignedExponent * 10 + value;
194 if(unsignedExponent > 65535)
195 overflow = true;
198 if(exponentAdjustment > 65535 || exponentAdjustment < -65536)
199 overflow = true;
201 if(!overflow) {
202 exponent = unsignedExponent;
203 if(negative)
204 exponent = -exponent;
205 exponent += exponentAdjustment;
206 if(exponent > 65535 || exponent < -65536)
207 overflow = true;
210 if(overflow)
211 exponent = negative ? -65536: 65535;
213 return exponent;
216 static StringRef::iterator
217 skipLeadingZeroesAndAnyDot(StringRef::iterator begin, StringRef::iterator end,
218 StringRef::iterator *dot)
220 StringRef::iterator p = begin;
221 *dot = end;
222 while(*p == '0' && p != end)
223 p++;
225 if(*p == '.') {
226 *dot = p++;
228 assert(end - begin != 1 && "Significand has no digits");
230 while(*p == '0' && p != end)
231 p++;
234 return p;
237 /* Given a normal decimal floating point number of the form
239 dddd.dddd[eE][+-]ddd
241 where the decimal point and exponent are optional, fill out the
242 structure D. Exponent is appropriate if the significand is
243 treated as an integer, and normalizedExponent if the significand
244 is taken to have the decimal point after a single leading
245 non-zero digit.
247 If the value is zero, V->firstSigDigit points to a non-digit, and
248 the return exponent is zero.
250 struct decimalInfo {
251 const char *firstSigDigit;
252 const char *lastSigDigit;
253 int exponent;
254 int normalizedExponent;
257 static void
258 interpretDecimal(StringRef::iterator begin, StringRef::iterator end,
259 decimalInfo *D)
261 StringRef::iterator dot = end;
262 StringRef::iterator p = skipLeadingZeroesAndAnyDot (begin, end, &dot);
264 D->firstSigDigit = p;
265 D->exponent = 0;
266 D->normalizedExponent = 0;
268 for (; p != end; ++p) {
269 if (*p == '.') {
270 assert(dot == end && "String contains multiple dots");
271 dot = p++;
272 if (p == end)
273 break;
275 if (decDigitValue(*p) >= 10U)
276 break;
279 if (p != end) {
280 assert((*p == 'e' || *p == 'E') && "Invalid character in significand");
281 assert(p != begin && "Significand has no digits");
282 assert((dot == end || p - begin != 1) && "Significand has no digits");
284 /* p points to the first non-digit in the string */
285 D->exponent = readExponent(p + 1, end);
287 /* Implied decimal point? */
288 if (dot == end)
289 dot = p;
292 /* If number is all zeroes accept any exponent. */
293 if (p != D->firstSigDigit) {
294 /* Drop insignificant trailing zeroes. */
295 if (p != begin) {
298 p--;
299 while (p != begin && *p == '0');
300 while (p != begin && *p == '.');
303 /* Adjust the exponents for any decimal point. */
304 D->exponent += static_cast<exponent_t>((dot - p) - (dot > p));
305 D->normalizedExponent = (D->exponent +
306 static_cast<exponent_t>((p - D->firstSigDigit)
307 - (dot > D->firstSigDigit && dot < p)));
310 D->lastSigDigit = p;
313 /* Return the trailing fraction of a hexadecimal number.
314 DIGITVALUE is the first hex digit of the fraction, P points to
315 the next digit. */
316 static lostFraction
317 trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end,
318 unsigned int digitValue)
320 unsigned int hexDigit;
322 /* If the first trailing digit isn't 0 or 8 we can work out the
323 fraction immediately. */
324 if(digitValue > 8)
325 return lfMoreThanHalf;
326 else if(digitValue < 8 && digitValue > 0)
327 return lfLessThanHalf;
329 /* Otherwise we need to find the first non-zero digit. */
330 while(*p == '0')
331 p++;
333 assert(p != end && "Invalid trailing hexadecimal fraction!");
335 hexDigit = hexDigitValue(*p);
337 /* If we ran off the end it is exactly zero or one-half, otherwise
338 a little more. */
339 if(hexDigit == -1U)
340 return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
341 else
342 return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf;
345 /* Return the fraction lost were a bignum truncated losing the least
346 significant BITS bits. */
347 static lostFraction
348 lostFractionThroughTruncation(const integerPart *parts,
349 unsigned int partCount,
350 unsigned int bits)
352 unsigned int lsb;
354 lsb = APInt::tcLSB(parts, partCount);
356 /* Note this is guaranteed true if bits == 0, or LSB == -1U. */
357 if(bits <= lsb)
358 return lfExactlyZero;
359 if(bits == lsb + 1)
360 return lfExactlyHalf;
361 if(bits <= partCount * integerPartWidth
362 && APInt::tcExtractBit(parts, bits - 1))
363 return lfMoreThanHalf;
365 return lfLessThanHalf;
368 /* Shift DST right BITS bits noting lost fraction. */
369 static lostFraction
370 shiftRight(integerPart *dst, unsigned int parts, unsigned int bits)
372 lostFraction lost_fraction;
374 lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
376 APInt::tcShiftRight(dst, parts, bits);
378 return lost_fraction;
381 /* Combine the effect of two lost fractions. */
382 static lostFraction
383 combineLostFractions(lostFraction moreSignificant,
384 lostFraction lessSignificant)
386 if(lessSignificant != lfExactlyZero) {
387 if(moreSignificant == lfExactlyZero)
388 moreSignificant = lfLessThanHalf;
389 else if(moreSignificant == lfExactlyHalf)
390 moreSignificant = lfMoreThanHalf;
393 return moreSignificant;
396 /* The error from the true value, in half-ulps, on multiplying two
397 floating point numbers, which differ from the value they
398 approximate by at most HUE1 and HUE2 half-ulps, is strictly less
399 than the returned value.
401 See "How to Read Floating Point Numbers Accurately" by William D
402 Clinger. */
403 static unsigned int
404 HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
406 assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
408 if (HUerr1 + HUerr2 == 0)
409 return inexactMultiply * 2; /* <= inexactMultiply half-ulps. */
410 else
411 return inexactMultiply + 2 * (HUerr1 + HUerr2);
414 /* The number of ulps from the boundary (zero, or half if ISNEAREST)
415 when the least significant BITS are truncated. BITS cannot be
416 zero. */
417 static integerPart
418 ulpsFromBoundary(const integerPart *parts, unsigned int bits, bool isNearest)
420 unsigned int count, partBits;
421 integerPart part, boundary;
423 assert (bits != 0);
425 bits--;
426 count = bits / integerPartWidth;
427 partBits = bits % integerPartWidth + 1;
429 part = parts[count] & (~(integerPart) 0 >> (integerPartWidth - partBits));
431 if (isNearest)
432 boundary = (integerPart) 1 << (partBits - 1);
433 else
434 boundary = 0;
436 if (count == 0) {
437 if (part - boundary <= boundary - part)
438 return part - boundary;
439 else
440 return boundary - part;
443 if (part == boundary) {
444 while (--count)
445 if (parts[count])
446 return ~(integerPart) 0; /* A lot. */
448 return parts[0];
449 } else if (part == boundary - 1) {
450 while (--count)
451 if (~parts[count])
452 return ~(integerPart) 0; /* A lot. */
454 return -parts[0];
457 return ~(integerPart) 0; /* A lot. */
460 /* Place pow(5, power) in DST, and return the number of parts used.
461 DST must be at least one part larger than size of the answer. */
462 static unsigned int
463 powerOf5(integerPart *dst, unsigned int power)
465 static const integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125,
466 15625, 78125 };
467 integerPart pow5s[maxPowerOfFiveParts * 2 + 5];
468 pow5s[0] = 78125 * 5;
470 unsigned int partsCount[16] = { 1 };
471 integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5;
472 unsigned int result;
473 assert(power <= maxExponent);
475 p1 = dst;
476 p2 = scratch;
478 *p1 = firstEightPowers[power & 7];
479 power >>= 3;
481 result = 1;
482 pow5 = pow5s;
484 for (unsigned int n = 0; power; power >>= 1, n++) {
485 unsigned int pc;
487 pc = partsCount[n];
489 /* Calculate pow(5,pow(2,n+3)) if we haven't yet. */
490 if (pc == 0) {
491 pc = partsCount[n - 1];
492 APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc);
493 pc *= 2;
494 if (pow5[pc - 1] == 0)
495 pc--;
496 partsCount[n] = pc;
499 if (power & 1) {
500 integerPart *tmp;
502 APInt::tcFullMultiply(p2, p1, pow5, result, pc);
503 result += pc;
504 if (p2[result - 1] == 0)
505 result--;
507 /* Now result is in p1 with partsCount parts and p2 is scratch
508 space. */
509 tmp = p1, p1 = p2, p2 = tmp;
512 pow5 += pc;
515 if (p1 != dst)
516 APInt::tcAssign(dst, p1, result);
518 return result;
521 /* Zero at the end to avoid modular arithmetic when adding one; used
522 when rounding up during hexadecimal output. */
523 static const char hexDigitsLower[] = "0123456789abcdef0";
524 static const char hexDigitsUpper[] = "0123456789ABCDEF0";
525 static const char infinityL[] = "infinity";
526 static const char infinityU[] = "INFINITY";
527 static const char NaNL[] = "nan";
528 static const char NaNU[] = "NAN";
530 /* Write out an integerPart in hexadecimal, starting with the most
531 significant nibble. Write out exactly COUNT hexdigits, return
532 COUNT. */
533 static unsigned int
534 partAsHex (char *dst, integerPart part, unsigned int count,
535 const char *hexDigitChars)
537 unsigned int result = count;
539 assert (count != 0 && count <= integerPartWidth / 4);
541 part >>= (integerPartWidth - 4 * count);
542 while (count--) {
543 dst[count] = hexDigitChars[part & 0xf];
544 part >>= 4;
547 return result;
550 /* Write out an unsigned decimal integer. */
551 static char *
552 writeUnsignedDecimal (char *dst, unsigned int n)
554 char buff[40], *p;
556 p = buff;
558 *p++ = '0' + n % 10;
559 while (n /= 10);
562 *dst++ = *--p;
563 while (p != buff);
565 return dst;
568 /* Write out a signed decimal integer. */
569 static char *
570 writeSignedDecimal (char *dst, int value)
572 if (value < 0) {
573 *dst++ = '-';
574 dst = writeUnsignedDecimal(dst, -(unsigned) value);
575 } else
576 dst = writeUnsignedDecimal(dst, value);
578 return dst;
581 /* Constructors. */
582 void
583 APFloat::initialize(const fltSemantics *ourSemantics)
585 unsigned int count;
587 semantics = ourSemantics;
588 count = partCount();
589 if(count > 1)
590 significand.parts = new integerPart[count];
593 void
594 APFloat::freeSignificand()
596 if(partCount() > 1)
597 delete [] significand.parts;
600 void
601 APFloat::assign(const APFloat &rhs)
603 assert(semantics == rhs.semantics);
605 sign = rhs.sign;
606 category = rhs.category;
607 exponent = rhs.exponent;
608 sign2 = rhs.sign2;
609 exponent2 = rhs.exponent2;
610 if(category == fcNormal || category == fcNaN)
611 copySignificand(rhs);
614 void
615 APFloat::copySignificand(const APFloat &rhs)
617 assert(category == fcNormal || category == fcNaN);
618 assert(rhs.partCount() >= partCount());
620 APInt::tcAssign(significandParts(), rhs.significandParts(),
621 partCount());
624 /* Make this number a NaN, with an arbitrary but deterministic value
625 for the significand. If double or longer, this is a signalling NaN,
626 which may not be ideal. If float, this is QNaN(0). */
627 void
628 APFloat::makeNaN(unsigned type)
630 category = fcNaN;
631 // FIXME: Add double and long double support for QNaN(0).
632 if (semantics->precision == 24 && semantics->maxExponent == 127) {
633 type |= 0x7fc00000U;
634 type &= ~0x80000000U;
635 } else
636 type = ~0U;
637 APInt::tcSet(significandParts(), type, partCount());
640 APFloat &
641 APFloat::operator=(const APFloat &rhs)
643 if(this != &rhs) {
644 if(semantics != rhs.semantics) {
645 freeSignificand();
646 initialize(rhs.semantics);
648 assign(rhs);
651 return *this;
654 bool
655 APFloat::bitwiseIsEqual(const APFloat &rhs) const {
656 if (this == &rhs)
657 return true;
658 if (semantics != rhs.semantics ||
659 category != rhs.category ||
660 sign != rhs.sign)
661 return false;
662 if (semantics==(const llvm::fltSemantics*)&PPCDoubleDouble &&
663 sign2 != rhs.sign2)
664 return false;
665 if (category==fcZero || category==fcInfinity)
666 return true;
667 else if (category==fcNormal && exponent!=rhs.exponent)
668 return false;
669 else if (semantics==(const llvm::fltSemantics*)&PPCDoubleDouble &&
670 exponent2!=rhs.exponent2)
671 return false;
672 else {
673 int i= partCount();
674 const integerPart* p=significandParts();
675 const integerPart* q=rhs.significandParts();
676 for (; i>0; i--, p++, q++) {
677 if (*p != *q)
678 return false;
680 return true;
684 APFloat::APFloat(const fltSemantics &ourSemantics, integerPart value)
686 assertArithmeticOK(ourSemantics);
687 initialize(&ourSemantics);
688 sign = 0;
689 zeroSignificand();
690 exponent = ourSemantics.precision - 1;
691 significandParts()[0] = value;
692 normalize(rmNearestTiesToEven, lfExactlyZero);
695 APFloat::APFloat(const fltSemantics &ourSemantics) {
696 assertArithmeticOK(ourSemantics);
697 initialize(&ourSemantics);
698 category = fcZero;
699 sign = false;
703 APFloat::APFloat(const fltSemantics &ourSemantics,
704 fltCategory ourCategory, bool negative, unsigned type)
706 assertArithmeticOK(ourSemantics);
707 initialize(&ourSemantics);
708 category = ourCategory;
709 sign = negative;
710 if (category == fcNormal)
711 category = fcZero;
712 else if (ourCategory == fcNaN)
713 makeNaN(type);
716 APFloat::APFloat(const fltSemantics &ourSemantics, const StringRef& text)
718 assertArithmeticOK(ourSemantics);
719 initialize(&ourSemantics);
720 convertFromString(text, rmNearestTiesToEven);
723 APFloat::APFloat(const APFloat &rhs)
725 initialize(rhs.semantics);
726 assign(rhs);
729 APFloat::~APFloat()
731 freeSignificand();
734 // Profile - This method 'profiles' an APFloat for use with FoldingSet.
735 void APFloat::Profile(FoldingSetNodeID& ID) const {
736 ID.Add(bitcastToAPInt());
739 unsigned int
740 APFloat::partCount() const
742 return partCountForBits(semantics->precision + 1);
745 unsigned int
746 APFloat::semanticsPrecision(const fltSemantics &semantics)
748 return semantics.precision;
751 const integerPart *
752 APFloat::significandParts() const
754 return const_cast<APFloat *>(this)->significandParts();
757 integerPart *
758 APFloat::significandParts()
760 assert(category == fcNormal || category == fcNaN);
762 if(partCount() > 1)
763 return significand.parts;
764 else
765 return &significand.part;
768 void
769 APFloat::zeroSignificand()
771 category = fcNormal;
772 APInt::tcSet(significandParts(), 0, partCount());
775 /* Increment an fcNormal floating point number's significand. */
776 void
777 APFloat::incrementSignificand()
779 integerPart carry;
781 carry = APInt::tcIncrement(significandParts(), partCount());
783 /* Our callers should never cause us to overflow. */
784 assert(carry == 0);
787 /* Add the significand of the RHS. Returns the carry flag. */
788 integerPart
789 APFloat::addSignificand(const APFloat &rhs)
791 integerPart *parts;
793 parts = significandParts();
795 assert(semantics == rhs.semantics);
796 assert(exponent == rhs.exponent);
798 return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
801 /* Subtract the significand of the RHS with a borrow flag. Returns
802 the borrow flag. */
803 integerPart
804 APFloat::subtractSignificand(const APFloat &rhs, integerPart borrow)
806 integerPart *parts;
808 parts = significandParts();
810 assert(semantics == rhs.semantics);
811 assert(exponent == rhs.exponent);
813 return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
814 partCount());
817 /* Multiply the significand of the RHS. If ADDEND is non-NULL, add it
818 on to the full-precision result of the multiplication. Returns the
819 lost fraction. */
820 lostFraction
821 APFloat::multiplySignificand(const APFloat &rhs, const APFloat *addend)
823 unsigned int omsb; // One, not zero, based MSB.
824 unsigned int partsCount, newPartsCount, precision;
825 integerPart *lhsSignificand;
826 integerPart scratch[4];
827 integerPart *fullSignificand;
828 lostFraction lost_fraction;
829 bool ignored;
831 assert(semantics == rhs.semantics);
833 precision = semantics->precision;
834 newPartsCount = partCountForBits(precision * 2);
836 if(newPartsCount > 4)
837 fullSignificand = new integerPart[newPartsCount];
838 else
839 fullSignificand = scratch;
841 lhsSignificand = significandParts();
842 partsCount = partCount();
844 APInt::tcFullMultiply(fullSignificand, lhsSignificand,
845 rhs.significandParts(), partsCount, partsCount);
847 lost_fraction = lfExactlyZero;
848 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
849 exponent += rhs.exponent;
851 if(addend) {
852 Significand savedSignificand = significand;
853 const fltSemantics *savedSemantics = semantics;
854 fltSemantics extendedSemantics;
855 opStatus status;
856 unsigned int extendedPrecision;
858 /* Normalize our MSB. */
859 extendedPrecision = precision + precision - 1;
860 if(omsb != extendedPrecision)
862 APInt::tcShiftLeft(fullSignificand, newPartsCount,
863 extendedPrecision - omsb);
864 exponent -= extendedPrecision - omsb;
867 /* Create new semantics. */
868 extendedSemantics = *semantics;
869 extendedSemantics.precision = extendedPrecision;
871 if(newPartsCount == 1)
872 significand.part = fullSignificand[0];
873 else
874 significand.parts = fullSignificand;
875 semantics = &extendedSemantics;
877 APFloat extendedAddend(*addend);
878 status = extendedAddend.convert(extendedSemantics, rmTowardZero, &ignored);
879 assert(status == opOK);
880 lost_fraction = addOrSubtractSignificand(extendedAddend, false);
882 /* Restore our state. */
883 if(newPartsCount == 1)
884 fullSignificand[0] = significand.part;
885 significand = savedSignificand;
886 semantics = savedSemantics;
888 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
891 exponent -= (precision - 1);
893 if(omsb > precision) {
894 unsigned int bits, significantParts;
895 lostFraction lf;
897 bits = omsb - precision;
898 significantParts = partCountForBits(omsb);
899 lf = shiftRight(fullSignificand, significantParts, bits);
900 lost_fraction = combineLostFractions(lf, lost_fraction);
901 exponent += bits;
904 APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
906 if(newPartsCount > 4)
907 delete [] fullSignificand;
909 return lost_fraction;
912 /* Multiply the significands of LHS and RHS to DST. */
913 lostFraction
914 APFloat::divideSignificand(const APFloat &rhs)
916 unsigned int bit, i, partsCount;
917 const integerPart *rhsSignificand;
918 integerPart *lhsSignificand, *dividend, *divisor;
919 integerPart scratch[4];
920 lostFraction lost_fraction;
922 assert(semantics == rhs.semantics);
924 lhsSignificand = significandParts();
925 rhsSignificand = rhs.significandParts();
926 partsCount = partCount();
928 if(partsCount > 2)
929 dividend = new integerPart[partsCount * 2];
930 else
931 dividend = scratch;
933 divisor = dividend + partsCount;
935 /* Copy the dividend and divisor as they will be modified in-place. */
936 for(i = 0; i < partsCount; i++) {
937 dividend[i] = lhsSignificand[i];
938 divisor[i] = rhsSignificand[i];
939 lhsSignificand[i] = 0;
942 exponent -= rhs.exponent;
944 unsigned int precision = semantics->precision;
946 /* Normalize the divisor. */
947 bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
948 if(bit) {
949 exponent += bit;
950 APInt::tcShiftLeft(divisor, partsCount, bit);
953 /* Normalize the dividend. */
954 bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
955 if(bit) {
956 exponent -= bit;
957 APInt::tcShiftLeft(dividend, partsCount, bit);
960 /* Ensure the dividend >= divisor initially for the loop below.
961 Incidentally, this means that the division loop below is
962 guaranteed to set the integer bit to one. */
963 if(APInt::tcCompare(dividend, divisor, partsCount) < 0) {
964 exponent--;
965 APInt::tcShiftLeft(dividend, partsCount, 1);
966 assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
969 /* Long division. */
970 for(bit = precision; bit; bit -= 1) {
971 if(APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
972 APInt::tcSubtract(dividend, divisor, 0, partsCount);
973 APInt::tcSetBit(lhsSignificand, bit - 1);
976 APInt::tcShiftLeft(dividend, partsCount, 1);
979 /* Figure out the lost fraction. */
980 int cmp = APInt::tcCompare(dividend, divisor, partsCount);
982 if(cmp > 0)
983 lost_fraction = lfMoreThanHalf;
984 else if(cmp == 0)
985 lost_fraction = lfExactlyHalf;
986 else if(APInt::tcIsZero(dividend, partsCount))
987 lost_fraction = lfExactlyZero;
988 else
989 lost_fraction = lfLessThanHalf;
991 if(partsCount > 2)
992 delete [] dividend;
994 return lost_fraction;
997 unsigned int
998 APFloat::significandMSB() const
1000 return APInt::tcMSB(significandParts(), partCount());
1003 unsigned int
1004 APFloat::significandLSB() const
1006 return APInt::tcLSB(significandParts(), partCount());
1009 /* Note that a zero result is NOT normalized to fcZero. */
1010 lostFraction
1011 APFloat::shiftSignificandRight(unsigned int bits)
1013 /* Our exponent should not overflow. */
1014 assert((exponent_t) (exponent + bits) >= exponent);
1016 exponent += bits;
1018 return shiftRight(significandParts(), partCount(), bits);
1021 /* Shift the significand left BITS bits, subtract BITS from its exponent. */
1022 void
1023 APFloat::shiftSignificandLeft(unsigned int bits)
1025 assert(bits < semantics->precision);
1027 if(bits) {
1028 unsigned int partsCount = partCount();
1030 APInt::tcShiftLeft(significandParts(), partsCount, bits);
1031 exponent -= bits;
1033 assert(!APInt::tcIsZero(significandParts(), partsCount));
1037 APFloat::cmpResult
1038 APFloat::compareAbsoluteValue(const APFloat &rhs) const
1040 int compare;
1042 assert(semantics == rhs.semantics);
1043 assert(category == fcNormal);
1044 assert(rhs.category == fcNormal);
1046 compare = exponent - rhs.exponent;
1048 /* If exponents are equal, do an unsigned bignum comparison of the
1049 significands. */
1050 if(compare == 0)
1051 compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
1052 partCount());
1054 if(compare > 0)
1055 return cmpGreaterThan;
1056 else if(compare < 0)
1057 return cmpLessThan;
1058 else
1059 return cmpEqual;
1062 /* Handle overflow. Sign is preserved. We either become infinity or
1063 the largest finite number. */
1064 APFloat::opStatus
1065 APFloat::handleOverflow(roundingMode rounding_mode)
1067 /* Infinity? */
1068 if(rounding_mode == rmNearestTiesToEven
1069 || rounding_mode == rmNearestTiesToAway
1070 || (rounding_mode == rmTowardPositive && !sign)
1071 || (rounding_mode == rmTowardNegative && sign))
1073 category = fcInfinity;
1074 return (opStatus) (opOverflow | opInexact);
1077 /* Otherwise we become the largest finite number. */
1078 category = fcNormal;
1079 exponent = semantics->maxExponent;
1080 APInt::tcSetLeastSignificantBits(significandParts(), partCount(),
1081 semantics->precision);
1083 return opInexact;
1086 /* Returns TRUE if, when truncating the current number, with BIT the
1087 new LSB, with the given lost fraction and rounding mode, the result
1088 would need to be rounded away from zero (i.e., by increasing the
1089 signficand). This routine must work for fcZero of both signs, and
1090 fcNormal numbers. */
1091 bool
1092 APFloat::roundAwayFromZero(roundingMode rounding_mode,
1093 lostFraction lost_fraction,
1094 unsigned int bit) const
1096 /* NaNs and infinities should not have lost fractions. */
1097 assert(category == fcNormal || category == fcZero);
1099 /* Current callers never pass this so we don't handle it. */
1100 assert(lost_fraction != lfExactlyZero);
1102 switch (rounding_mode) {
1103 default:
1104 llvm_unreachable(0);
1106 case rmNearestTiesToAway:
1107 return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
1109 case rmNearestTiesToEven:
1110 if(lost_fraction == lfMoreThanHalf)
1111 return true;
1113 /* Our zeroes don't have a significand to test. */
1114 if(lost_fraction == lfExactlyHalf && category != fcZero)
1115 return APInt::tcExtractBit(significandParts(), bit);
1117 return false;
1119 case rmTowardZero:
1120 return false;
1122 case rmTowardPositive:
1123 return sign == false;
1125 case rmTowardNegative:
1126 return sign == true;
1130 APFloat::opStatus
1131 APFloat::normalize(roundingMode rounding_mode,
1132 lostFraction lost_fraction)
1134 unsigned int omsb; /* One, not zero, based MSB. */
1135 int exponentChange;
1137 if(category != fcNormal)
1138 return opOK;
1140 /* Before rounding normalize the exponent of fcNormal numbers. */
1141 omsb = significandMSB() + 1;
1143 if(omsb) {
1144 /* OMSB is numbered from 1. We want to place it in the integer
1145 bit numbered PRECISON if possible, with a compensating change in
1146 the exponent. */
1147 exponentChange = omsb - semantics->precision;
1149 /* If the resulting exponent is too high, overflow according to
1150 the rounding mode. */
1151 if(exponent + exponentChange > semantics->maxExponent)
1152 return handleOverflow(rounding_mode);
1154 /* Subnormal numbers have exponent minExponent, and their MSB
1155 is forced based on that. */
1156 if(exponent + exponentChange < semantics->minExponent)
1157 exponentChange = semantics->minExponent - exponent;
1159 /* Shifting left is easy as we don't lose precision. */
1160 if(exponentChange < 0) {
1161 assert(lost_fraction == lfExactlyZero);
1163 shiftSignificandLeft(-exponentChange);
1165 return opOK;
1168 if(exponentChange > 0) {
1169 lostFraction lf;
1171 /* Shift right and capture any new lost fraction. */
1172 lf = shiftSignificandRight(exponentChange);
1174 lost_fraction = combineLostFractions(lf, lost_fraction);
1176 /* Keep OMSB up-to-date. */
1177 if(omsb > (unsigned) exponentChange)
1178 omsb -= exponentChange;
1179 else
1180 omsb = 0;
1184 /* Now round the number according to rounding_mode given the lost
1185 fraction. */
1187 /* As specified in IEEE 754, since we do not trap we do not report
1188 underflow for exact results. */
1189 if(lost_fraction == lfExactlyZero) {
1190 /* Canonicalize zeroes. */
1191 if(omsb == 0)
1192 category = fcZero;
1194 return opOK;
1197 /* Increment the significand if we're rounding away from zero. */
1198 if(roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
1199 if(omsb == 0)
1200 exponent = semantics->minExponent;
1202 incrementSignificand();
1203 omsb = significandMSB() + 1;
1205 /* Did the significand increment overflow? */
1206 if(omsb == (unsigned) semantics->precision + 1) {
1207 /* Renormalize by incrementing the exponent and shifting our
1208 significand right one. However if we already have the
1209 maximum exponent we overflow to infinity. */
1210 if(exponent == semantics->maxExponent) {
1211 category = fcInfinity;
1213 return (opStatus) (opOverflow | opInexact);
1216 shiftSignificandRight(1);
1218 return opInexact;
1222 /* The normal case - we were and are not denormal, and any
1223 significand increment above didn't overflow. */
1224 if(omsb == semantics->precision)
1225 return opInexact;
1227 /* We have a non-zero denormal. */
1228 assert(omsb < semantics->precision);
1230 /* Canonicalize zeroes. */
1231 if(omsb == 0)
1232 category = fcZero;
1234 /* The fcZero case is a denormal that underflowed to zero. */
1235 return (opStatus) (opUnderflow | opInexact);
1238 APFloat::opStatus
1239 APFloat::addOrSubtractSpecials(const APFloat &rhs, bool subtract)
1241 switch (convolve(category, rhs.category)) {
1242 default:
1243 llvm_unreachable(0);
1245 case convolve(fcNaN, fcZero):
1246 case convolve(fcNaN, fcNormal):
1247 case convolve(fcNaN, fcInfinity):
1248 case convolve(fcNaN, fcNaN):
1249 case convolve(fcNormal, fcZero):
1250 case convolve(fcInfinity, fcNormal):
1251 case convolve(fcInfinity, fcZero):
1252 return opOK;
1254 case convolve(fcZero, fcNaN):
1255 case convolve(fcNormal, fcNaN):
1256 case convolve(fcInfinity, fcNaN):
1257 category = fcNaN;
1258 copySignificand(rhs);
1259 return opOK;
1261 case convolve(fcNormal, fcInfinity):
1262 case convolve(fcZero, fcInfinity):
1263 category = fcInfinity;
1264 sign = rhs.sign ^ subtract;
1265 return opOK;
1267 case convolve(fcZero, fcNormal):
1268 assign(rhs);
1269 sign = rhs.sign ^ subtract;
1270 return opOK;
1272 case convolve(fcZero, fcZero):
1273 /* Sign depends on rounding mode; handled by caller. */
1274 return opOK;
1276 case convolve(fcInfinity, fcInfinity):
1277 /* Differently signed infinities can only be validly
1278 subtracted. */
1279 if(((sign ^ rhs.sign)!=0) != subtract) {
1280 makeNaN();
1281 return opInvalidOp;
1284 return opOK;
1286 case convolve(fcNormal, fcNormal):
1287 return opDivByZero;
1291 /* Add or subtract two normal numbers. */
1292 lostFraction
1293 APFloat::addOrSubtractSignificand(const APFloat &rhs, bool subtract)
1295 integerPart carry;
1296 lostFraction lost_fraction;
1297 int bits;
1299 /* Determine if the operation on the absolute values is effectively
1300 an addition or subtraction. */
1301 subtract ^= (sign ^ rhs.sign) ? true : false;
1303 /* Are we bigger exponent-wise than the RHS? */
1304 bits = exponent - rhs.exponent;
1306 /* Subtraction is more subtle than one might naively expect. */
1307 if(subtract) {
1308 APFloat temp_rhs(rhs);
1309 bool reverse;
1311 if (bits == 0) {
1312 reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan;
1313 lost_fraction = lfExactlyZero;
1314 } else if (bits > 0) {
1315 lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
1316 shiftSignificandLeft(1);
1317 reverse = false;
1318 } else {
1319 lost_fraction = shiftSignificandRight(-bits - 1);
1320 temp_rhs.shiftSignificandLeft(1);
1321 reverse = true;
1324 if (reverse) {
1325 carry = temp_rhs.subtractSignificand
1326 (*this, lost_fraction != lfExactlyZero);
1327 copySignificand(temp_rhs);
1328 sign = !sign;
1329 } else {
1330 carry = subtractSignificand
1331 (temp_rhs, lost_fraction != lfExactlyZero);
1334 /* Invert the lost fraction - it was on the RHS and
1335 subtracted. */
1336 if(lost_fraction == lfLessThanHalf)
1337 lost_fraction = lfMoreThanHalf;
1338 else if(lost_fraction == lfMoreThanHalf)
1339 lost_fraction = lfLessThanHalf;
1341 /* The code above is intended to ensure that no borrow is
1342 necessary. */
1343 assert(!carry);
1344 } else {
1345 if(bits > 0) {
1346 APFloat temp_rhs(rhs);
1348 lost_fraction = temp_rhs.shiftSignificandRight(bits);
1349 carry = addSignificand(temp_rhs);
1350 } else {
1351 lost_fraction = shiftSignificandRight(-bits);
1352 carry = addSignificand(rhs);
1355 /* We have a guard bit; generating a carry cannot happen. */
1356 assert(!carry);
1359 return lost_fraction;
1362 APFloat::opStatus
1363 APFloat::multiplySpecials(const APFloat &rhs)
1365 switch (convolve(category, rhs.category)) {
1366 default:
1367 llvm_unreachable(0);
1369 case convolve(fcNaN, fcZero):
1370 case convolve(fcNaN, fcNormal):
1371 case convolve(fcNaN, fcInfinity):
1372 case convolve(fcNaN, fcNaN):
1373 return opOK;
1375 case convolve(fcZero, fcNaN):
1376 case convolve(fcNormal, fcNaN):
1377 case convolve(fcInfinity, fcNaN):
1378 category = fcNaN;
1379 copySignificand(rhs);
1380 return opOK;
1382 case convolve(fcNormal, fcInfinity):
1383 case convolve(fcInfinity, fcNormal):
1384 case convolve(fcInfinity, fcInfinity):
1385 category = fcInfinity;
1386 return opOK;
1388 case convolve(fcZero, fcNormal):
1389 case convolve(fcNormal, fcZero):
1390 case convolve(fcZero, fcZero):
1391 category = fcZero;
1392 return opOK;
1394 case convolve(fcZero, fcInfinity):
1395 case convolve(fcInfinity, fcZero):
1396 makeNaN();
1397 return opInvalidOp;
1399 case convolve(fcNormal, fcNormal):
1400 return opOK;
1404 APFloat::opStatus
1405 APFloat::divideSpecials(const APFloat &rhs)
1407 switch (convolve(category, rhs.category)) {
1408 default:
1409 llvm_unreachable(0);
1411 case convolve(fcNaN, fcZero):
1412 case convolve(fcNaN, fcNormal):
1413 case convolve(fcNaN, fcInfinity):
1414 case convolve(fcNaN, fcNaN):
1415 case convolve(fcInfinity, fcZero):
1416 case convolve(fcInfinity, fcNormal):
1417 case convolve(fcZero, fcInfinity):
1418 case convolve(fcZero, fcNormal):
1419 return opOK;
1421 case convolve(fcZero, fcNaN):
1422 case convolve(fcNormal, fcNaN):
1423 case convolve(fcInfinity, fcNaN):
1424 category = fcNaN;
1425 copySignificand(rhs);
1426 return opOK;
1428 case convolve(fcNormal, fcInfinity):
1429 category = fcZero;
1430 return opOK;
1432 case convolve(fcNormal, fcZero):
1433 category = fcInfinity;
1434 return opDivByZero;
1436 case convolve(fcInfinity, fcInfinity):
1437 case convolve(fcZero, fcZero):
1438 makeNaN();
1439 return opInvalidOp;
1441 case convolve(fcNormal, fcNormal):
1442 return opOK;
1446 APFloat::opStatus
1447 APFloat::modSpecials(const APFloat &rhs)
1449 switch (convolve(category, rhs.category)) {
1450 default:
1451 llvm_unreachable(0);
1453 case convolve(fcNaN, fcZero):
1454 case convolve(fcNaN, fcNormal):
1455 case convolve(fcNaN, fcInfinity):
1456 case convolve(fcNaN, fcNaN):
1457 case convolve(fcZero, fcInfinity):
1458 case convolve(fcZero, fcNormal):
1459 case convolve(fcNormal, fcInfinity):
1460 return opOK;
1462 case convolve(fcZero, fcNaN):
1463 case convolve(fcNormal, fcNaN):
1464 case convolve(fcInfinity, fcNaN):
1465 category = fcNaN;
1466 copySignificand(rhs);
1467 return opOK;
1469 case convolve(fcNormal, fcZero):
1470 case convolve(fcInfinity, fcZero):
1471 case convolve(fcInfinity, fcNormal):
1472 case convolve(fcInfinity, fcInfinity):
1473 case convolve(fcZero, fcZero):
1474 makeNaN();
1475 return opInvalidOp;
1477 case convolve(fcNormal, fcNormal):
1478 return opOK;
1482 /* Change sign. */
1483 void
1484 APFloat::changeSign()
1486 /* Look mummy, this one's easy. */
1487 sign = !sign;
1490 void
1491 APFloat::clearSign()
1493 /* So is this one. */
1494 sign = 0;
1497 void
1498 APFloat::copySign(const APFloat &rhs)
1500 /* And this one. */
1501 sign = rhs.sign;
1504 /* Normalized addition or subtraction. */
1505 APFloat::opStatus
1506 APFloat::addOrSubtract(const APFloat &rhs, roundingMode rounding_mode,
1507 bool subtract)
1509 opStatus fs;
1511 assertArithmeticOK(*semantics);
1513 fs = addOrSubtractSpecials(rhs, subtract);
1515 /* This return code means it was not a simple case. */
1516 if(fs == opDivByZero) {
1517 lostFraction lost_fraction;
1519 lost_fraction = addOrSubtractSignificand(rhs, subtract);
1520 fs = normalize(rounding_mode, lost_fraction);
1522 /* Can only be zero if we lost no fraction. */
1523 assert(category != fcZero || lost_fraction == lfExactlyZero);
1526 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1527 positive zero unless rounding to minus infinity, except that
1528 adding two like-signed zeroes gives that zero. */
1529 if(category == fcZero) {
1530 if(rhs.category != fcZero || (sign == rhs.sign) == subtract)
1531 sign = (rounding_mode == rmTowardNegative);
1534 return fs;
1537 /* Normalized addition. */
1538 APFloat::opStatus
1539 APFloat::add(const APFloat &rhs, roundingMode rounding_mode)
1541 return addOrSubtract(rhs, rounding_mode, false);
1544 /* Normalized subtraction. */
1545 APFloat::opStatus
1546 APFloat::subtract(const APFloat &rhs, roundingMode rounding_mode)
1548 return addOrSubtract(rhs, rounding_mode, true);
1551 /* Normalized multiply. */
1552 APFloat::opStatus
1553 APFloat::multiply(const APFloat &rhs, roundingMode rounding_mode)
1555 opStatus fs;
1557 assertArithmeticOK(*semantics);
1558 sign ^= rhs.sign;
1559 fs = multiplySpecials(rhs);
1561 if(category == fcNormal) {
1562 lostFraction lost_fraction = multiplySignificand(rhs, 0);
1563 fs = normalize(rounding_mode, lost_fraction);
1564 if(lost_fraction != lfExactlyZero)
1565 fs = (opStatus) (fs | opInexact);
1568 return fs;
1571 /* Normalized divide. */
1572 APFloat::opStatus
1573 APFloat::divide(const APFloat &rhs, roundingMode rounding_mode)
1575 opStatus fs;
1577 assertArithmeticOK(*semantics);
1578 sign ^= rhs.sign;
1579 fs = divideSpecials(rhs);
1581 if(category == fcNormal) {
1582 lostFraction lost_fraction = divideSignificand(rhs);
1583 fs = normalize(rounding_mode, lost_fraction);
1584 if(lost_fraction != lfExactlyZero)
1585 fs = (opStatus) (fs | opInexact);
1588 return fs;
1591 /* Normalized remainder. This is not currently correct in all cases. */
1592 APFloat::opStatus
1593 APFloat::remainder(const APFloat &rhs)
1595 opStatus fs;
1596 APFloat V = *this;
1597 unsigned int origSign = sign;
1599 assertArithmeticOK(*semantics);
1600 fs = V.divide(rhs, rmNearestTiesToEven);
1601 if (fs == opDivByZero)
1602 return fs;
1604 int parts = partCount();
1605 integerPart *x = new integerPart[parts];
1606 bool ignored;
1607 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1608 rmNearestTiesToEven, &ignored);
1609 if (fs==opInvalidOp)
1610 return fs;
1612 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1613 rmNearestTiesToEven);
1614 assert(fs==opOK); // should always work
1616 fs = V.multiply(rhs, rmNearestTiesToEven);
1617 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1619 fs = subtract(V, rmNearestTiesToEven);
1620 assert(fs==opOK || fs==opInexact); // likewise
1622 if (isZero())
1623 sign = origSign; // IEEE754 requires this
1624 delete[] x;
1625 return fs;
1628 /* Normalized llvm frem (C fmod).
1629 This is not currently correct in all cases. */
1630 APFloat::opStatus
1631 APFloat::mod(const APFloat &rhs, roundingMode rounding_mode)
1633 opStatus fs;
1634 assertArithmeticOK(*semantics);
1635 fs = modSpecials(rhs);
1637 if (category == fcNormal && rhs.category == fcNormal) {
1638 APFloat V = *this;
1639 unsigned int origSign = sign;
1641 fs = V.divide(rhs, rmNearestTiesToEven);
1642 if (fs == opDivByZero)
1643 return fs;
1645 int parts = partCount();
1646 integerPart *x = new integerPart[parts];
1647 bool ignored;
1648 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1649 rmTowardZero, &ignored);
1650 if (fs==opInvalidOp)
1651 return fs;
1653 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1654 rmNearestTiesToEven);
1655 assert(fs==opOK); // should always work
1657 fs = V.multiply(rhs, rounding_mode);
1658 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1660 fs = subtract(V, rounding_mode);
1661 assert(fs==opOK || fs==opInexact); // likewise
1663 if (isZero())
1664 sign = origSign; // IEEE754 requires this
1665 delete[] x;
1667 return fs;
1670 /* Normalized fused-multiply-add. */
1671 APFloat::opStatus
1672 APFloat::fusedMultiplyAdd(const APFloat &multiplicand,
1673 const APFloat &addend,
1674 roundingMode rounding_mode)
1676 opStatus fs;
1678 assertArithmeticOK(*semantics);
1680 /* Post-multiplication sign, before addition. */
1681 sign ^= multiplicand.sign;
1683 /* If and only if all arguments are normal do we need to do an
1684 extended-precision calculation. */
1685 if(category == fcNormal
1686 && multiplicand.category == fcNormal
1687 && addend.category == fcNormal) {
1688 lostFraction lost_fraction;
1690 lost_fraction = multiplySignificand(multiplicand, &addend);
1691 fs = normalize(rounding_mode, lost_fraction);
1692 if(lost_fraction != lfExactlyZero)
1693 fs = (opStatus) (fs | opInexact);
1695 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1696 positive zero unless rounding to minus infinity, except that
1697 adding two like-signed zeroes gives that zero. */
1698 if(category == fcZero && sign != addend.sign)
1699 sign = (rounding_mode == rmTowardNegative);
1700 } else {
1701 fs = multiplySpecials(multiplicand);
1703 /* FS can only be opOK or opInvalidOp. There is no more work
1704 to do in the latter case. The IEEE-754R standard says it is
1705 implementation-defined in this case whether, if ADDEND is a
1706 quiet NaN, we raise invalid op; this implementation does so.
1708 If we need to do the addition we can do so with normal
1709 precision. */
1710 if(fs == opOK)
1711 fs = addOrSubtract(addend, rounding_mode, false);
1714 return fs;
1717 /* Comparison requires normalized numbers. */
1718 APFloat::cmpResult
1719 APFloat::compare(const APFloat &rhs) const
1721 cmpResult result;
1723 assertArithmeticOK(*semantics);
1724 assert(semantics == rhs.semantics);
1726 switch (convolve(category, rhs.category)) {
1727 default:
1728 llvm_unreachable(0);
1730 case convolve(fcNaN, fcZero):
1731 case convolve(fcNaN, fcNormal):
1732 case convolve(fcNaN, fcInfinity):
1733 case convolve(fcNaN, fcNaN):
1734 case convolve(fcZero, fcNaN):
1735 case convolve(fcNormal, fcNaN):
1736 case convolve(fcInfinity, fcNaN):
1737 return cmpUnordered;
1739 case convolve(fcInfinity, fcNormal):
1740 case convolve(fcInfinity, fcZero):
1741 case convolve(fcNormal, fcZero):
1742 if(sign)
1743 return cmpLessThan;
1744 else
1745 return cmpGreaterThan;
1747 case convolve(fcNormal, fcInfinity):
1748 case convolve(fcZero, fcInfinity):
1749 case convolve(fcZero, fcNormal):
1750 if(rhs.sign)
1751 return cmpGreaterThan;
1752 else
1753 return cmpLessThan;
1755 case convolve(fcInfinity, fcInfinity):
1756 if(sign == rhs.sign)
1757 return cmpEqual;
1758 else if(sign)
1759 return cmpLessThan;
1760 else
1761 return cmpGreaterThan;
1763 case convolve(fcZero, fcZero):
1764 return cmpEqual;
1766 case convolve(fcNormal, fcNormal):
1767 break;
1770 /* Two normal numbers. Do they have the same sign? */
1771 if(sign != rhs.sign) {
1772 if(sign)
1773 result = cmpLessThan;
1774 else
1775 result = cmpGreaterThan;
1776 } else {
1777 /* Compare absolute values; invert result if negative. */
1778 result = compareAbsoluteValue(rhs);
1780 if(sign) {
1781 if(result == cmpLessThan)
1782 result = cmpGreaterThan;
1783 else if(result == cmpGreaterThan)
1784 result = cmpLessThan;
1788 return result;
1791 /// APFloat::convert - convert a value of one floating point type to another.
1792 /// The return value corresponds to the IEEE754 exceptions. *losesInfo
1793 /// records whether the transformation lost information, i.e. whether
1794 /// converting the result back to the original type will produce the
1795 /// original value (this is almost the same as return value==fsOK, but there
1796 /// are edge cases where this is not so).
1798 APFloat::opStatus
1799 APFloat::convert(const fltSemantics &toSemantics,
1800 roundingMode rounding_mode, bool *losesInfo)
1802 lostFraction lostFraction;
1803 unsigned int newPartCount, oldPartCount;
1804 opStatus fs;
1806 assertArithmeticOK(*semantics);
1807 assertArithmeticOK(toSemantics);
1808 lostFraction = lfExactlyZero;
1809 newPartCount = partCountForBits(toSemantics.precision + 1);
1810 oldPartCount = partCount();
1812 /* Handle storage complications. If our new form is wider,
1813 re-allocate our bit pattern into wider storage. If it is
1814 narrower, we ignore the excess parts, but if narrowing to a
1815 single part we need to free the old storage.
1816 Be careful not to reference significandParts for zeroes
1817 and infinities, since it aborts. */
1818 if (newPartCount > oldPartCount) {
1819 integerPart *newParts;
1820 newParts = new integerPart[newPartCount];
1821 APInt::tcSet(newParts, 0, newPartCount);
1822 if (category==fcNormal || category==fcNaN)
1823 APInt::tcAssign(newParts, significandParts(), oldPartCount);
1824 freeSignificand();
1825 significand.parts = newParts;
1826 } else if (newPartCount < oldPartCount) {
1827 /* Capture any lost fraction through truncation of parts so we get
1828 correct rounding whilst normalizing. */
1829 if (category==fcNormal)
1830 lostFraction = lostFractionThroughTruncation
1831 (significandParts(), oldPartCount, toSemantics.precision);
1832 if (newPartCount == 1) {
1833 integerPart newPart = 0;
1834 if (category==fcNormal || category==fcNaN)
1835 newPart = significandParts()[0];
1836 freeSignificand();
1837 significand.part = newPart;
1841 if(category == fcNormal) {
1842 /* Re-interpret our bit-pattern. */
1843 exponent += toSemantics.precision - semantics->precision;
1844 semantics = &toSemantics;
1845 fs = normalize(rounding_mode, lostFraction);
1846 *losesInfo = (fs != opOK);
1847 } else if (category == fcNaN) {
1848 int shift = toSemantics.precision - semantics->precision;
1849 // Do this now so significandParts gets the right answer
1850 const fltSemantics *oldSemantics = semantics;
1851 semantics = &toSemantics;
1852 *losesInfo = false;
1853 // No normalization here, just truncate
1854 if (shift>0)
1855 APInt::tcShiftLeft(significandParts(), newPartCount, shift);
1856 else if (shift < 0) {
1857 unsigned ushift = -shift;
1858 // Figure out if we are losing information. This happens
1859 // if are shifting out something other than 0s, or if the x87 long
1860 // double input did not have its integer bit set (pseudo-NaN), or if the
1861 // x87 long double input did not have its QNan bit set (because the x87
1862 // hardware sets this bit when converting a lower-precision NaN to
1863 // x87 long double).
1864 if (APInt::tcLSB(significandParts(), newPartCount) < ushift)
1865 *losesInfo = true;
1866 if (oldSemantics == &APFloat::x87DoubleExtended &&
1867 (!(*significandParts() & 0x8000000000000000ULL) ||
1868 !(*significandParts() & 0x4000000000000000ULL)))
1869 *losesInfo = true;
1870 APInt::tcShiftRight(significandParts(), newPartCount, ushift);
1872 // gcc forces the Quiet bit on, which means (float)(double)(float_sNan)
1873 // does not give you back the same bits. This is dubious, and we
1874 // don't currently do it. You're really supposed to get
1875 // an invalid operation signal at runtime, but nobody does that.
1876 fs = opOK;
1877 } else {
1878 semantics = &toSemantics;
1879 fs = opOK;
1880 *losesInfo = false;
1883 return fs;
1886 /* Convert a floating point number to an integer according to the
1887 rounding mode. If the rounded integer value is out of range this
1888 returns an invalid operation exception and the contents of the
1889 destination parts are unspecified. If the rounded value is in
1890 range but the floating point number is not the exact integer, the C
1891 standard doesn't require an inexact exception to be raised. IEEE
1892 854 does require it so we do that.
1894 Note that for conversions to integer type the C standard requires
1895 round-to-zero to always be used. */
1896 APFloat::opStatus
1897 APFloat::convertToSignExtendedInteger(integerPart *parts, unsigned int width,
1898 bool isSigned,
1899 roundingMode rounding_mode,
1900 bool *isExact) const
1902 lostFraction lost_fraction;
1903 const integerPart *src;
1904 unsigned int dstPartsCount, truncatedBits;
1906 assertArithmeticOK(*semantics);
1908 *isExact = false;
1910 /* Handle the three special cases first. */
1911 if(category == fcInfinity || category == fcNaN)
1912 return opInvalidOp;
1914 dstPartsCount = partCountForBits(width);
1916 if(category == fcZero) {
1917 APInt::tcSet(parts, 0, dstPartsCount);
1918 // Negative zero can't be represented as an int.
1919 *isExact = !sign;
1920 return opOK;
1923 src = significandParts();
1925 /* Step 1: place our absolute value, with any fraction truncated, in
1926 the destination. */
1927 if (exponent < 0) {
1928 /* Our absolute value is less than one; truncate everything. */
1929 APInt::tcSet(parts, 0, dstPartsCount);
1930 /* For exponent -1 the integer bit represents .5, look at that.
1931 For smaller exponents leftmost truncated bit is 0. */
1932 truncatedBits = semantics->precision -1U - exponent;
1933 } else {
1934 /* We want the most significant (exponent + 1) bits; the rest are
1935 truncated. */
1936 unsigned int bits = exponent + 1U;
1938 /* Hopelessly large in magnitude? */
1939 if (bits > width)
1940 return opInvalidOp;
1942 if (bits < semantics->precision) {
1943 /* We truncate (semantics->precision - bits) bits. */
1944 truncatedBits = semantics->precision - bits;
1945 APInt::tcExtract(parts, dstPartsCount, src, bits, truncatedBits);
1946 } else {
1947 /* We want at least as many bits as are available. */
1948 APInt::tcExtract(parts, dstPartsCount, src, semantics->precision, 0);
1949 APInt::tcShiftLeft(parts, dstPartsCount, bits - semantics->precision);
1950 truncatedBits = 0;
1954 /* Step 2: work out any lost fraction, and increment the absolute
1955 value if we would round away from zero. */
1956 if (truncatedBits) {
1957 lost_fraction = lostFractionThroughTruncation(src, partCount(),
1958 truncatedBits);
1959 if (lost_fraction != lfExactlyZero
1960 && roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
1961 if (APInt::tcIncrement(parts, dstPartsCount))
1962 return opInvalidOp; /* Overflow. */
1964 } else {
1965 lost_fraction = lfExactlyZero;
1968 /* Step 3: check if we fit in the destination. */
1969 unsigned int omsb = APInt::tcMSB(parts, dstPartsCount) + 1;
1971 if (sign) {
1972 if (!isSigned) {
1973 /* Negative numbers cannot be represented as unsigned. */
1974 if (omsb != 0)
1975 return opInvalidOp;
1976 } else {
1977 /* It takes omsb bits to represent the unsigned integer value.
1978 We lose a bit for the sign, but care is needed as the
1979 maximally negative integer is a special case. */
1980 if (omsb == width && APInt::tcLSB(parts, dstPartsCount) + 1 != omsb)
1981 return opInvalidOp;
1983 /* This case can happen because of rounding. */
1984 if (omsb > width)
1985 return opInvalidOp;
1988 APInt::tcNegate (parts, dstPartsCount);
1989 } else {
1990 if (omsb >= width + !isSigned)
1991 return opInvalidOp;
1994 if (lost_fraction == lfExactlyZero) {
1995 *isExact = true;
1996 return opOK;
1997 } else
1998 return opInexact;
2001 /* Same as convertToSignExtendedInteger, except we provide
2002 deterministic values in case of an invalid operation exception,
2003 namely zero for NaNs and the minimal or maximal value respectively
2004 for underflow or overflow.
2005 The *isExact output tells whether the result is exact, in the sense
2006 that converting it back to the original floating point type produces
2007 the original value. This is almost equivalent to result==opOK,
2008 except for negative zeroes.
2010 APFloat::opStatus
2011 APFloat::convertToInteger(integerPart *parts, unsigned int width,
2012 bool isSigned,
2013 roundingMode rounding_mode, bool *isExact) const
2015 opStatus fs;
2017 fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode,
2018 isExact);
2020 if (fs == opInvalidOp) {
2021 unsigned int bits, dstPartsCount;
2023 dstPartsCount = partCountForBits(width);
2025 if (category == fcNaN)
2026 bits = 0;
2027 else if (sign)
2028 bits = isSigned;
2029 else
2030 bits = width - isSigned;
2032 APInt::tcSetLeastSignificantBits(parts, dstPartsCount, bits);
2033 if (sign && isSigned)
2034 APInt::tcShiftLeft(parts, dstPartsCount, width - 1);
2037 return fs;
2040 /* Convert an unsigned integer SRC to a floating point number,
2041 rounding according to ROUNDING_MODE. The sign of the floating
2042 point number is not modified. */
2043 APFloat::opStatus
2044 APFloat::convertFromUnsignedParts(const integerPart *src,
2045 unsigned int srcCount,
2046 roundingMode rounding_mode)
2048 unsigned int omsb, precision, dstCount;
2049 integerPart *dst;
2050 lostFraction lost_fraction;
2052 assertArithmeticOK(*semantics);
2053 category = fcNormal;
2054 omsb = APInt::tcMSB(src, srcCount) + 1;
2055 dst = significandParts();
2056 dstCount = partCount();
2057 precision = semantics->precision;
2059 /* We want the most significant PRECISON bits of SRC. There may not
2060 be that many; extract what we can. */
2061 if (precision <= omsb) {
2062 exponent = omsb - 1;
2063 lost_fraction = lostFractionThroughTruncation(src, srcCount,
2064 omsb - precision);
2065 APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
2066 } else {
2067 exponent = precision - 1;
2068 lost_fraction = lfExactlyZero;
2069 APInt::tcExtract(dst, dstCount, src, omsb, 0);
2072 return normalize(rounding_mode, lost_fraction);
2075 APFloat::opStatus
2076 APFloat::convertFromAPInt(const APInt &Val,
2077 bool isSigned,
2078 roundingMode rounding_mode)
2080 unsigned int partCount = Val.getNumWords();
2081 APInt api = Val;
2083 sign = false;
2084 if (isSigned && api.isNegative()) {
2085 sign = true;
2086 api = -api;
2089 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
2092 /* Convert a two's complement integer SRC to a floating point number,
2093 rounding according to ROUNDING_MODE. ISSIGNED is true if the
2094 integer is signed, in which case it must be sign-extended. */
2095 APFloat::opStatus
2096 APFloat::convertFromSignExtendedInteger(const integerPart *src,
2097 unsigned int srcCount,
2098 bool isSigned,
2099 roundingMode rounding_mode)
2101 opStatus status;
2103 assertArithmeticOK(*semantics);
2104 if (isSigned
2105 && APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) {
2106 integerPart *copy;
2108 /* If we're signed and negative negate a copy. */
2109 sign = true;
2110 copy = new integerPart[srcCount];
2111 APInt::tcAssign(copy, src, srcCount);
2112 APInt::tcNegate(copy, srcCount);
2113 status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
2114 delete [] copy;
2115 } else {
2116 sign = false;
2117 status = convertFromUnsignedParts(src, srcCount, rounding_mode);
2120 return status;
2123 /* FIXME: should this just take a const APInt reference? */
2124 APFloat::opStatus
2125 APFloat::convertFromZeroExtendedInteger(const integerPart *parts,
2126 unsigned int width, bool isSigned,
2127 roundingMode rounding_mode)
2129 unsigned int partCount = partCountForBits(width);
2130 APInt api = APInt(width, partCount, parts);
2132 sign = false;
2133 if(isSigned && APInt::tcExtractBit(parts, width - 1)) {
2134 sign = true;
2135 api = -api;
2138 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
2141 APFloat::opStatus
2142 APFloat::convertFromHexadecimalString(const StringRef &s,
2143 roundingMode rounding_mode)
2145 lostFraction lost_fraction = lfExactlyZero;
2146 integerPart *significand;
2147 unsigned int bitPos, partsCount;
2148 StringRef::iterator dot, firstSignificantDigit;
2150 zeroSignificand();
2151 exponent = 0;
2152 category = fcNormal;
2154 significand = significandParts();
2155 partsCount = partCount();
2156 bitPos = partsCount * integerPartWidth;
2158 /* Skip leading zeroes and any (hexa)decimal point. */
2159 StringRef::iterator begin = s.begin();
2160 StringRef::iterator end = s.end();
2161 StringRef::iterator p = skipLeadingZeroesAndAnyDot(begin, end, &dot);
2162 firstSignificantDigit = p;
2164 for(; p != end;) {
2165 integerPart hex_value;
2167 if(*p == '.') {
2168 assert(dot == end && "String contains multiple dots");
2169 dot = p++;
2170 if (p == end) {
2171 break;
2175 hex_value = hexDigitValue(*p);
2176 if(hex_value == -1U) {
2177 break;
2180 p++;
2182 if (p == end) {
2183 break;
2184 } else {
2185 /* Store the number whilst 4-bit nibbles remain. */
2186 if(bitPos) {
2187 bitPos -= 4;
2188 hex_value <<= bitPos % integerPartWidth;
2189 significand[bitPos / integerPartWidth] |= hex_value;
2190 } else {
2191 lost_fraction = trailingHexadecimalFraction(p, end, hex_value);
2192 while(p != end && hexDigitValue(*p) != -1U)
2193 p++;
2194 break;
2199 /* Hex floats require an exponent but not a hexadecimal point. */
2200 assert(p != end && "Hex strings require an exponent");
2201 assert((*p == 'p' || *p == 'P') && "Invalid character in significand");
2202 assert(p != begin && "Significand has no digits");
2203 assert((dot == end || p - begin != 1) && "Significand has no digits");
2205 /* Ignore the exponent if we are zero. */
2206 if(p != firstSignificantDigit) {
2207 int expAdjustment;
2209 /* Implicit hexadecimal point? */
2210 if (dot == end)
2211 dot = p;
2213 /* Calculate the exponent adjustment implicit in the number of
2214 significant digits. */
2215 expAdjustment = static_cast<int>(dot - firstSignificantDigit);
2216 if(expAdjustment < 0)
2217 expAdjustment++;
2218 expAdjustment = expAdjustment * 4 - 1;
2220 /* Adjust for writing the significand starting at the most
2221 significant nibble. */
2222 expAdjustment += semantics->precision;
2223 expAdjustment -= partsCount * integerPartWidth;
2225 /* Adjust for the given exponent. */
2226 exponent = totalExponent(p + 1, end, expAdjustment);
2229 return normalize(rounding_mode, lost_fraction);
2232 APFloat::opStatus
2233 APFloat::roundSignificandWithExponent(const integerPart *decSigParts,
2234 unsigned sigPartCount, int exp,
2235 roundingMode rounding_mode)
2237 unsigned int parts, pow5PartCount;
2238 fltSemantics calcSemantics = { 32767, -32767, 0, true };
2239 integerPart pow5Parts[maxPowerOfFiveParts];
2240 bool isNearest;
2242 isNearest = (rounding_mode == rmNearestTiesToEven
2243 || rounding_mode == rmNearestTiesToAway);
2245 parts = partCountForBits(semantics->precision + 11);
2247 /* Calculate pow(5, abs(exp)). */
2248 pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp);
2250 for (;; parts *= 2) {
2251 opStatus sigStatus, powStatus;
2252 unsigned int excessPrecision, truncatedBits;
2254 calcSemantics.precision = parts * integerPartWidth - 1;
2255 excessPrecision = calcSemantics.precision - semantics->precision;
2256 truncatedBits = excessPrecision;
2258 APFloat decSig(calcSemantics, fcZero, sign);
2259 APFloat pow5(calcSemantics, fcZero, false);
2261 sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount,
2262 rmNearestTiesToEven);
2263 powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
2264 rmNearestTiesToEven);
2265 /* Add exp, as 10^n = 5^n * 2^n. */
2266 decSig.exponent += exp;
2268 lostFraction calcLostFraction;
2269 integerPart HUerr, HUdistance;
2270 unsigned int powHUerr;
2272 if (exp >= 0) {
2273 /* multiplySignificand leaves the precision-th bit set to 1. */
2274 calcLostFraction = decSig.multiplySignificand(pow5, NULL);
2275 powHUerr = powStatus != opOK;
2276 } else {
2277 calcLostFraction = decSig.divideSignificand(pow5);
2278 /* Denormal numbers have less precision. */
2279 if (decSig.exponent < semantics->minExponent) {
2280 excessPrecision += (semantics->minExponent - decSig.exponent);
2281 truncatedBits = excessPrecision;
2282 if (excessPrecision > calcSemantics.precision)
2283 excessPrecision = calcSemantics.precision;
2285 /* Extra half-ulp lost in reciprocal of exponent. */
2286 powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2;
2289 /* Both multiplySignificand and divideSignificand return the
2290 result with the integer bit set. */
2291 assert (APInt::tcExtractBit
2292 (decSig.significandParts(), calcSemantics.precision - 1) == 1);
2294 HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK,
2295 powHUerr);
2296 HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
2297 excessPrecision, isNearest);
2299 /* Are we guaranteed to round correctly if we truncate? */
2300 if (HUdistance >= HUerr) {
2301 APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
2302 calcSemantics.precision - excessPrecision,
2303 excessPrecision);
2304 /* Take the exponent of decSig. If we tcExtract-ed less bits
2305 above we must adjust our exponent to compensate for the
2306 implicit right shift. */
2307 exponent = (decSig.exponent + semantics->precision
2308 - (calcSemantics.precision - excessPrecision));
2309 calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(),
2310 decSig.partCount(),
2311 truncatedBits);
2312 return normalize(rounding_mode, calcLostFraction);
2317 APFloat::opStatus
2318 APFloat::convertFromDecimalString(const StringRef &str, roundingMode rounding_mode)
2320 decimalInfo D;
2321 opStatus fs;
2323 /* Scan the text. */
2324 StringRef::iterator p = str.begin();
2325 interpretDecimal(p, str.end(), &D);
2327 /* Handle the quick cases. First the case of no significant digits,
2328 i.e. zero, and then exponents that are obviously too large or too
2329 small. Writing L for log 10 / log 2, a number d.ddddd*10^exp
2330 definitely overflows if
2332 (exp - 1) * L >= maxExponent
2334 and definitely underflows to zero where
2336 (exp + 1) * L <= minExponent - precision
2338 With integer arithmetic the tightest bounds for L are
2340 93/28 < L < 196/59 [ numerator <= 256 ]
2341 42039/12655 < L < 28738/8651 [ numerator <= 65536 ]
2344 if (decDigitValue(*D.firstSigDigit) >= 10U) {
2345 category = fcZero;
2346 fs = opOK;
2347 } else if ((D.normalizedExponent + 1) * 28738
2348 <= 8651 * (semantics->minExponent - (int) semantics->precision)) {
2349 /* Underflow to zero and round. */
2350 zeroSignificand();
2351 fs = normalize(rounding_mode, lfLessThanHalf);
2352 } else if ((D.normalizedExponent - 1) * 42039
2353 >= 12655 * semantics->maxExponent) {
2354 /* Overflow and round. */
2355 fs = handleOverflow(rounding_mode);
2356 } else {
2357 integerPart *decSignificand;
2358 unsigned int partCount;
2360 /* A tight upper bound on number of bits required to hold an
2361 N-digit decimal integer is N * 196 / 59. Allocate enough space
2362 to hold the full significand, and an extra part required by
2363 tcMultiplyPart. */
2364 partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1;
2365 partCount = partCountForBits(1 + 196 * partCount / 59);
2366 decSignificand = new integerPart[partCount + 1];
2367 partCount = 0;
2369 /* Convert to binary efficiently - we do almost all multiplication
2370 in an integerPart. When this would overflow do we do a single
2371 bignum multiplication, and then revert again to multiplication
2372 in an integerPart. */
2373 do {
2374 integerPart decValue, val, multiplier;
2376 val = 0;
2377 multiplier = 1;
2379 do {
2380 if (*p == '.') {
2381 p++;
2382 if (p == str.end()) {
2383 break;
2386 decValue = decDigitValue(*p++);
2387 assert(decValue < 10U && "Invalid character in significand");
2388 multiplier *= 10;
2389 val = val * 10 + decValue;
2390 /* The maximum number that can be multiplied by ten with any
2391 digit added without overflowing an integerPart. */
2392 } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
2394 /* Multiply out the current part. */
2395 APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
2396 partCount, partCount + 1, false);
2398 /* If we used another part (likely but not guaranteed), increase
2399 the count. */
2400 if (decSignificand[partCount])
2401 partCount++;
2402 } while (p <= D.lastSigDigit);
2404 category = fcNormal;
2405 fs = roundSignificandWithExponent(decSignificand, partCount,
2406 D.exponent, rounding_mode);
2408 delete [] decSignificand;
2411 return fs;
2414 APFloat::opStatus
2415 APFloat::convertFromString(const StringRef &str, roundingMode rounding_mode)
2417 assertArithmeticOK(*semantics);
2418 assert(!str.empty() && "Invalid string length");
2420 /* Handle a leading minus sign. */
2421 StringRef::iterator p = str.begin();
2422 size_t slen = str.size();
2423 sign = *p == '-' ? 1 : 0;
2424 if(*p == '-' || *p == '+') {
2425 p++;
2426 slen--;
2427 assert(slen && "String has no digits");
2430 if(slen >= 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
2431 assert(slen - 2 && "Invalid string");
2432 return convertFromHexadecimalString(StringRef(p + 2, slen - 2),
2433 rounding_mode);
2436 return convertFromDecimalString(StringRef(p, slen), rounding_mode);
2439 /* Write out a hexadecimal representation of the floating point value
2440 to DST, which must be of sufficient size, in the C99 form
2441 [-]0xh.hhhhp[+-]d. Return the number of characters written,
2442 excluding the terminating NUL.
2444 If UPPERCASE, the output is in upper case, otherwise in lower case.
2446 HEXDIGITS digits appear altogether, rounding the value if
2447 necessary. If HEXDIGITS is 0, the minimal precision to display the
2448 number precisely is used instead. If nothing would appear after
2449 the decimal point it is suppressed.
2451 The decimal exponent is always printed and has at least one digit.
2452 Zero values display an exponent of zero. Infinities and NaNs
2453 appear as "infinity" or "nan" respectively.
2455 The above rules are as specified by C99. There is ambiguity about
2456 what the leading hexadecimal digit should be. This implementation
2457 uses whatever is necessary so that the exponent is displayed as
2458 stored. This implies the exponent will fall within the IEEE format
2459 range, and the leading hexadecimal digit will be 0 (for denormals),
2460 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
2461 any other digits zero).
2463 unsigned int
2464 APFloat::convertToHexString(char *dst, unsigned int hexDigits,
2465 bool upperCase, roundingMode rounding_mode) const
2467 char *p;
2469 assertArithmeticOK(*semantics);
2471 p = dst;
2472 if (sign)
2473 *dst++ = '-';
2475 switch (category) {
2476 case fcInfinity:
2477 memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
2478 dst += sizeof infinityL - 1;
2479 break;
2481 case fcNaN:
2482 memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
2483 dst += sizeof NaNU - 1;
2484 break;
2486 case fcZero:
2487 *dst++ = '0';
2488 *dst++ = upperCase ? 'X': 'x';
2489 *dst++ = '0';
2490 if (hexDigits > 1) {
2491 *dst++ = '.';
2492 memset (dst, '0', hexDigits - 1);
2493 dst += hexDigits - 1;
2495 *dst++ = upperCase ? 'P': 'p';
2496 *dst++ = '0';
2497 break;
2499 case fcNormal:
2500 dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
2501 break;
2504 *dst = 0;
2506 return static_cast<unsigned int>(dst - p);
2509 /* Does the hard work of outputting the correctly rounded hexadecimal
2510 form of a normal floating point number with the specified number of
2511 hexadecimal digits. If HEXDIGITS is zero the minimum number of
2512 digits necessary to print the value precisely is output. */
2513 char *
2514 APFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
2515 bool upperCase,
2516 roundingMode rounding_mode) const
2518 unsigned int count, valueBits, shift, partsCount, outputDigits;
2519 const char *hexDigitChars;
2520 const integerPart *significand;
2521 char *p;
2522 bool roundUp;
2524 *dst++ = '0';
2525 *dst++ = upperCase ? 'X': 'x';
2527 roundUp = false;
2528 hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower;
2530 significand = significandParts();
2531 partsCount = partCount();
2533 /* +3 because the first digit only uses the single integer bit, so
2534 we have 3 virtual zero most-significant-bits. */
2535 valueBits = semantics->precision + 3;
2536 shift = integerPartWidth - valueBits % integerPartWidth;
2538 /* The natural number of digits required ignoring trailing
2539 insignificant zeroes. */
2540 outputDigits = (valueBits - significandLSB () + 3) / 4;
2542 /* hexDigits of zero means use the required number for the
2543 precision. Otherwise, see if we are truncating. If we are,
2544 find out if we need to round away from zero. */
2545 if (hexDigits) {
2546 if (hexDigits < outputDigits) {
2547 /* We are dropping non-zero bits, so need to check how to round.
2548 "bits" is the number of dropped bits. */
2549 unsigned int bits;
2550 lostFraction fraction;
2552 bits = valueBits - hexDigits * 4;
2553 fraction = lostFractionThroughTruncation (significand, partsCount, bits);
2554 roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
2556 outputDigits = hexDigits;
2559 /* Write the digits consecutively, and start writing in the location
2560 of the hexadecimal point. We move the most significant digit
2561 left and add the hexadecimal point later. */
2562 p = ++dst;
2564 count = (valueBits + integerPartWidth - 1) / integerPartWidth;
2566 while (outputDigits && count) {
2567 integerPart part;
2569 /* Put the most significant integerPartWidth bits in "part". */
2570 if (--count == partsCount)
2571 part = 0; /* An imaginary higher zero part. */
2572 else
2573 part = significand[count] << shift;
2575 if (count && shift)
2576 part |= significand[count - 1] >> (integerPartWidth - shift);
2578 /* Convert as much of "part" to hexdigits as we can. */
2579 unsigned int curDigits = integerPartWidth / 4;
2581 if (curDigits > outputDigits)
2582 curDigits = outputDigits;
2583 dst += partAsHex (dst, part, curDigits, hexDigitChars);
2584 outputDigits -= curDigits;
2587 if (roundUp) {
2588 char *q = dst;
2590 /* Note that hexDigitChars has a trailing '0'. */
2591 do {
2592 q--;
2593 *q = hexDigitChars[hexDigitValue (*q) + 1];
2594 } while (*q == '0');
2595 assert (q >= p);
2596 } else {
2597 /* Add trailing zeroes. */
2598 memset (dst, '0', outputDigits);
2599 dst += outputDigits;
2602 /* Move the most significant digit to before the point, and if there
2603 is something after the decimal point add it. This must come
2604 after rounding above. */
2605 p[-1] = p[0];
2606 if (dst -1 == p)
2607 dst--;
2608 else
2609 p[0] = '.';
2611 /* Finally output the exponent. */
2612 *dst++ = upperCase ? 'P': 'p';
2614 return writeSignedDecimal (dst, exponent);
2617 // For good performance it is desirable for different APFloats
2618 // to produce different integers.
2619 uint32_t
2620 APFloat::getHashValue() const
2622 if (category==fcZero) return sign<<8 | semantics->precision ;
2623 else if (category==fcInfinity) return sign<<9 | semantics->precision;
2624 else if (category==fcNaN) return 1<<10 | semantics->precision;
2625 else {
2626 uint32_t hash = sign<<11 | semantics->precision | exponent<<12;
2627 const integerPart* p = significandParts();
2628 for (int i=partCount(); i>0; i--, p++)
2629 hash ^= ((uint32_t)*p) ^ (uint32_t)((*p)>>32);
2630 return hash;
2634 // Conversion from APFloat to/from host float/double. It may eventually be
2635 // possible to eliminate these and have everybody deal with APFloats, but that
2636 // will take a while. This approach will not easily extend to long double.
2637 // Current implementation requires integerPartWidth==64, which is correct at
2638 // the moment but could be made more general.
2640 // Denormals have exponent minExponent in APFloat, but minExponent-1 in
2641 // the actual IEEE respresentations. We compensate for that here.
2643 APInt
2644 APFloat::convertF80LongDoubleAPFloatToAPInt() const
2646 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended);
2647 assert (partCount()==2);
2649 uint64_t myexponent, mysignificand;
2651 if (category==fcNormal) {
2652 myexponent = exponent+16383; //bias
2653 mysignificand = significandParts()[0];
2654 if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
2655 myexponent = 0; // denormal
2656 } else if (category==fcZero) {
2657 myexponent = 0;
2658 mysignificand = 0;
2659 } else if (category==fcInfinity) {
2660 myexponent = 0x7fff;
2661 mysignificand = 0x8000000000000000ULL;
2662 } else {
2663 assert(category == fcNaN && "Unknown category");
2664 myexponent = 0x7fff;
2665 mysignificand = significandParts()[0];
2668 uint64_t words[2];
2669 words[0] = mysignificand;
2670 words[1] = ((uint64_t)(sign & 1) << 15) |
2671 (myexponent & 0x7fffLL);
2672 return APInt(80, 2, words);
2675 APInt
2676 APFloat::convertPPCDoubleDoubleAPFloatToAPInt() const
2678 assert(semantics == (const llvm::fltSemantics*)&PPCDoubleDouble);
2679 assert (partCount()==2);
2681 uint64_t myexponent, mysignificand, myexponent2, mysignificand2;
2683 if (category==fcNormal) {
2684 myexponent = exponent + 1023; //bias
2685 myexponent2 = exponent2 + 1023;
2686 mysignificand = significandParts()[0];
2687 mysignificand2 = significandParts()[1];
2688 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2689 myexponent = 0; // denormal
2690 if (myexponent2==1 && !(mysignificand2 & 0x10000000000000LL))
2691 myexponent2 = 0; // denormal
2692 } else if (category==fcZero) {
2693 myexponent = 0;
2694 mysignificand = 0;
2695 myexponent2 = 0;
2696 mysignificand2 = 0;
2697 } else if (category==fcInfinity) {
2698 myexponent = 0x7ff;
2699 myexponent2 = 0;
2700 mysignificand = 0;
2701 mysignificand2 = 0;
2702 } else {
2703 assert(category == fcNaN && "Unknown category");
2704 myexponent = 0x7ff;
2705 mysignificand = significandParts()[0];
2706 myexponent2 = exponent2;
2707 mysignificand2 = significandParts()[1];
2710 uint64_t words[2];
2711 words[0] = ((uint64_t)(sign & 1) << 63) |
2712 ((myexponent & 0x7ff) << 52) |
2713 (mysignificand & 0xfffffffffffffLL);
2714 words[1] = ((uint64_t)(sign2 & 1) << 63) |
2715 ((myexponent2 & 0x7ff) << 52) |
2716 (mysignificand2 & 0xfffffffffffffLL);
2717 return APInt(128, 2, words);
2720 APInt
2721 APFloat::convertQuadrupleAPFloatToAPInt() const
2723 assert(semantics == (const llvm::fltSemantics*)&IEEEquad);
2724 assert (partCount()==2);
2726 uint64_t myexponent, mysignificand, mysignificand2;
2728 if (category==fcNormal) {
2729 myexponent = exponent+16383; //bias
2730 mysignificand = significandParts()[0];
2731 mysignificand2 = significandParts()[1];
2732 if (myexponent==1 && !(mysignificand2 & 0x1000000000000LL))
2733 myexponent = 0; // denormal
2734 } else if (category==fcZero) {
2735 myexponent = 0;
2736 mysignificand = mysignificand2 = 0;
2737 } else if (category==fcInfinity) {
2738 myexponent = 0x7fff;
2739 mysignificand = mysignificand2 = 0;
2740 } else {
2741 assert(category == fcNaN && "Unknown category!");
2742 myexponent = 0x7fff;
2743 mysignificand = significandParts()[0];
2744 mysignificand2 = significandParts()[1];
2747 uint64_t words[2];
2748 words[0] = mysignificand;
2749 words[1] = ((uint64_t)(sign & 1) << 63) |
2750 ((myexponent & 0x7fff) << 48) |
2751 (mysignificand2 & 0xffffffffffffLL);
2753 return APInt(128, 2, words);
2756 APInt
2757 APFloat::convertDoubleAPFloatToAPInt() const
2759 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble);
2760 assert (partCount()==1);
2762 uint64_t myexponent, mysignificand;
2764 if (category==fcNormal) {
2765 myexponent = exponent+1023; //bias
2766 mysignificand = *significandParts();
2767 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2768 myexponent = 0; // denormal
2769 } else if (category==fcZero) {
2770 myexponent = 0;
2771 mysignificand = 0;
2772 } else if (category==fcInfinity) {
2773 myexponent = 0x7ff;
2774 mysignificand = 0;
2775 } else {
2776 assert(category == fcNaN && "Unknown category!");
2777 myexponent = 0x7ff;
2778 mysignificand = *significandParts();
2781 return APInt(64, ((((uint64_t)(sign & 1) << 63) |
2782 ((myexponent & 0x7ff) << 52) |
2783 (mysignificand & 0xfffffffffffffLL))));
2786 APInt
2787 APFloat::convertFloatAPFloatToAPInt() const
2789 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle);
2790 assert (partCount()==1);
2792 uint32_t myexponent, mysignificand;
2794 if (category==fcNormal) {
2795 myexponent = exponent+127; //bias
2796 mysignificand = (uint32_t)*significandParts();
2797 if (myexponent == 1 && !(mysignificand & 0x800000))
2798 myexponent = 0; // denormal
2799 } else if (category==fcZero) {
2800 myexponent = 0;
2801 mysignificand = 0;
2802 } else if (category==fcInfinity) {
2803 myexponent = 0xff;
2804 mysignificand = 0;
2805 } else {
2806 assert(category == fcNaN && "Unknown category!");
2807 myexponent = 0xff;
2808 mysignificand = (uint32_t)*significandParts();
2811 return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) |
2812 (mysignificand & 0x7fffff)));
2815 // This function creates an APInt that is just a bit map of the floating
2816 // point constant as it would appear in memory. It is not a conversion,
2817 // and treating the result as a normal integer is unlikely to be useful.
2819 APInt
2820 APFloat::bitcastToAPInt() const
2822 if (semantics == (const llvm::fltSemantics*)&IEEEsingle)
2823 return convertFloatAPFloatToAPInt();
2825 if (semantics == (const llvm::fltSemantics*)&IEEEdouble)
2826 return convertDoubleAPFloatToAPInt();
2828 if (semantics == (const llvm::fltSemantics*)&IEEEquad)
2829 return convertQuadrupleAPFloatToAPInt();
2831 if (semantics == (const llvm::fltSemantics*)&PPCDoubleDouble)
2832 return convertPPCDoubleDoubleAPFloatToAPInt();
2834 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended &&
2835 "unknown format!");
2836 return convertF80LongDoubleAPFloatToAPInt();
2839 float
2840 APFloat::convertToFloat() const
2842 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle && "Float semantics are not IEEEsingle");
2843 APInt api = bitcastToAPInt();
2844 return api.bitsToFloat();
2847 double
2848 APFloat::convertToDouble() const
2850 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble && "Float semantics are not IEEEdouble");
2851 APInt api = bitcastToAPInt();
2852 return api.bitsToDouble();
2855 /// Integer bit is explicit in this format. Intel hardware (387 and later)
2856 /// does not support these bit patterns:
2857 /// exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity")
2858 /// exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN")
2859 /// exponent = 0, integer bit 1 ("pseudodenormal")
2860 /// exponent!=0 nor all 1's, integer bit 0 ("unnormal")
2861 /// At the moment, the first two are treated as NaNs, the second two as Normal.
2862 void
2863 APFloat::initFromF80LongDoubleAPInt(const APInt &api)
2865 assert(api.getBitWidth()==80);
2866 uint64_t i1 = api.getRawData()[0];
2867 uint64_t i2 = api.getRawData()[1];
2868 uint64_t myexponent = (i2 & 0x7fff);
2869 uint64_t mysignificand = i1;
2871 initialize(&APFloat::x87DoubleExtended);
2872 assert(partCount()==2);
2874 sign = static_cast<unsigned int>(i2>>15);
2875 if (myexponent==0 && mysignificand==0) {
2876 // exponent, significand meaningless
2877 category = fcZero;
2878 } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
2879 // exponent, significand meaningless
2880 category = fcInfinity;
2881 } else if (myexponent==0x7fff && mysignificand!=0x8000000000000000ULL) {
2882 // exponent meaningless
2883 category = fcNaN;
2884 significandParts()[0] = mysignificand;
2885 significandParts()[1] = 0;
2886 } else {
2887 category = fcNormal;
2888 exponent = myexponent - 16383;
2889 significandParts()[0] = mysignificand;
2890 significandParts()[1] = 0;
2891 if (myexponent==0) // denormal
2892 exponent = -16382;
2896 void
2897 APFloat::initFromPPCDoubleDoubleAPInt(const APInt &api)
2899 assert(api.getBitWidth()==128);
2900 uint64_t i1 = api.getRawData()[0];
2901 uint64_t i2 = api.getRawData()[1];
2902 uint64_t myexponent = (i1 >> 52) & 0x7ff;
2903 uint64_t mysignificand = i1 & 0xfffffffffffffLL;
2904 uint64_t myexponent2 = (i2 >> 52) & 0x7ff;
2905 uint64_t mysignificand2 = i2 & 0xfffffffffffffLL;
2907 initialize(&APFloat::PPCDoubleDouble);
2908 assert(partCount()==2);
2910 sign = static_cast<unsigned int>(i1>>63);
2911 sign2 = static_cast<unsigned int>(i2>>63);
2912 if (myexponent==0 && mysignificand==0) {
2913 // exponent, significand meaningless
2914 // exponent2 and significand2 are required to be 0; we don't check
2915 category = fcZero;
2916 } else if (myexponent==0x7ff && mysignificand==0) {
2917 // exponent, significand meaningless
2918 // exponent2 and significand2 are required to be 0; we don't check
2919 category = fcInfinity;
2920 } else if (myexponent==0x7ff && mysignificand!=0) {
2921 // exponent meaningless. So is the whole second word, but keep it
2922 // for determinism.
2923 category = fcNaN;
2924 exponent2 = myexponent2;
2925 significandParts()[0] = mysignificand;
2926 significandParts()[1] = mysignificand2;
2927 } else {
2928 category = fcNormal;
2929 // Note there is no category2; the second word is treated as if it is
2930 // fcNormal, although it might be something else considered by itself.
2931 exponent = myexponent - 1023;
2932 exponent2 = myexponent2 - 1023;
2933 significandParts()[0] = mysignificand;
2934 significandParts()[1] = mysignificand2;
2935 if (myexponent==0) // denormal
2936 exponent = -1022;
2937 else
2938 significandParts()[0] |= 0x10000000000000LL; // integer bit
2939 if (myexponent2==0)
2940 exponent2 = -1022;
2941 else
2942 significandParts()[1] |= 0x10000000000000LL; // integer bit
2946 void
2947 APFloat::initFromQuadrupleAPInt(const APInt &api)
2949 assert(api.getBitWidth()==128);
2950 uint64_t i1 = api.getRawData()[0];
2951 uint64_t i2 = api.getRawData()[1];
2952 uint64_t myexponent = (i2 >> 48) & 0x7fff;
2953 uint64_t mysignificand = i1;
2954 uint64_t mysignificand2 = i2 & 0xffffffffffffLL;
2956 initialize(&APFloat::IEEEquad);
2957 assert(partCount()==2);
2959 sign = static_cast<unsigned int>(i2>>63);
2960 if (myexponent==0 &&
2961 (mysignificand==0 && mysignificand2==0)) {
2962 // exponent, significand meaningless
2963 category = fcZero;
2964 } else if (myexponent==0x7fff &&
2965 (mysignificand==0 && mysignificand2==0)) {
2966 // exponent, significand meaningless
2967 category = fcInfinity;
2968 } else if (myexponent==0x7fff &&
2969 (mysignificand!=0 || mysignificand2 !=0)) {
2970 // exponent meaningless
2971 category = fcNaN;
2972 significandParts()[0] = mysignificand;
2973 significandParts()[1] = mysignificand2;
2974 } else {
2975 category = fcNormal;
2976 exponent = myexponent - 16383;
2977 significandParts()[0] = mysignificand;
2978 significandParts()[1] = mysignificand2;
2979 if (myexponent==0) // denormal
2980 exponent = -16382;
2981 else
2982 significandParts()[1] |= 0x1000000000000LL; // integer bit
2986 void
2987 APFloat::initFromDoubleAPInt(const APInt &api)
2989 assert(api.getBitWidth()==64);
2990 uint64_t i = *api.getRawData();
2991 uint64_t myexponent = (i >> 52) & 0x7ff;
2992 uint64_t mysignificand = i & 0xfffffffffffffLL;
2994 initialize(&APFloat::IEEEdouble);
2995 assert(partCount()==1);
2997 sign = static_cast<unsigned int>(i>>63);
2998 if (myexponent==0 && mysignificand==0) {
2999 // exponent, significand meaningless
3000 category = fcZero;
3001 } else if (myexponent==0x7ff && mysignificand==0) {
3002 // exponent, significand meaningless
3003 category = fcInfinity;
3004 } else if (myexponent==0x7ff && mysignificand!=0) {
3005 // exponent meaningless
3006 category = fcNaN;
3007 *significandParts() = mysignificand;
3008 } else {
3009 category = fcNormal;
3010 exponent = myexponent - 1023;
3011 *significandParts() = mysignificand;
3012 if (myexponent==0) // denormal
3013 exponent = -1022;
3014 else
3015 *significandParts() |= 0x10000000000000LL; // integer bit
3019 void
3020 APFloat::initFromFloatAPInt(const APInt & api)
3022 assert(api.getBitWidth()==32);
3023 uint32_t i = (uint32_t)*api.getRawData();
3024 uint32_t myexponent = (i >> 23) & 0xff;
3025 uint32_t mysignificand = i & 0x7fffff;
3027 initialize(&APFloat::IEEEsingle);
3028 assert(partCount()==1);
3030 sign = i >> 31;
3031 if (myexponent==0 && mysignificand==0) {
3032 // exponent, significand meaningless
3033 category = fcZero;
3034 } else if (myexponent==0xff && mysignificand==0) {
3035 // exponent, significand meaningless
3036 category = fcInfinity;
3037 } else if (myexponent==0xff && mysignificand!=0) {
3038 // sign, exponent, significand meaningless
3039 category = fcNaN;
3040 *significandParts() = mysignificand;
3041 } else {
3042 category = fcNormal;
3043 exponent = myexponent - 127; //bias
3044 *significandParts() = mysignificand;
3045 if (myexponent==0) // denormal
3046 exponent = -126;
3047 else
3048 *significandParts() |= 0x800000; // integer bit
3052 /// Treat api as containing the bits of a floating point number. Currently
3053 /// we infer the floating point type from the size of the APInt. The
3054 /// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful
3055 /// when the size is anything else).
3056 void
3057 APFloat::initFromAPInt(const APInt& api, bool isIEEE)
3059 if (api.getBitWidth() == 32)
3060 return initFromFloatAPInt(api);
3061 else if (api.getBitWidth()==64)
3062 return initFromDoubleAPInt(api);
3063 else if (api.getBitWidth()==80)
3064 return initFromF80LongDoubleAPInt(api);
3065 else if (api.getBitWidth()==128)
3066 return (isIEEE ?
3067 initFromQuadrupleAPInt(api) : initFromPPCDoubleDoubleAPInt(api));
3068 else
3069 llvm_unreachable(0);
3072 APFloat::APFloat(const APInt& api, bool isIEEE)
3074 initFromAPInt(api, isIEEE);
3077 APFloat::APFloat(float f)
3079 APInt api = APInt(32, 0);
3080 initFromAPInt(api.floatToBits(f));
3083 APFloat::APFloat(double d)
3085 APInt api = APInt(64, 0);
3086 initFromAPInt(api.doubleToBits(d));