1 //===-- APFloat.cpp - Implement APFloat class -----------------------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file implements a class to represent arbitrary precision floating
11 // point values and provide a variety of arithmetic operations on them.
13 //===----------------------------------------------------------------------===//
17 #include "llvm/ADT/APFloat.h"
18 #include "llvm/Support/MathExtras.h"
22 #define convolve(lhs, rhs) ((lhs) * 4 + (rhs))
24 /* Assumed in hexadecimal significand parsing, and conversion to
25 hexadecimal strings. */
26 COMPILE_TIME_ASSERT(integerPartWidth % 4 == 0);
30 /* Represents floating point arithmetic semantics. */
32 /* The largest E such that 2^E is representable; this matches the
33 definition of IEEE 754. */
34 exponent_t maxExponent;
36 /* The smallest E such that 2^E is a normalized number; this
37 matches the definition of IEEE 754. */
38 exponent_t minExponent;
40 /* Number of bits in the significand. This includes the integer
42 unsigned int precision;
44 /* True if arithmetic is supported. */
45 unsigned int arithmeticOK;
48 const fltSemantics APFloat::IEEEsingle = { 127, -126, 24, true };
49 const fltSemantics APFloat::IEEEdouble = { 1023, -1022, 53, true };
50 const fltSemantics APFloat::IEEEquad = { 16383, -16382, 113, true };
51 const fltSemantics APFloat::x87DoubleExtended = { 16383, -16382, 64, true };
52 const fltSemantics APFloat::Bogus = { 0, 0, 0, true };
54 // The PowerPC format consists of two doubles. It does not map cleanly
55 // onto the usual format above. For now only storage of constants of
56 // this type is supported, no arithmetic.
57 const fltSemantics APFloat::PPCDoubleDouble = { 1023, -1022, 106, false };
59 /* A tight upper bound on number of parts required to hold the value
62 power * 1024 / (441 * integerPartWidth) + 1
64 However, whilst the result may require only this many parts,
65 because we are multiplying two values to get it, the
66 multiplication may require an extra part with the excess part
67 being zero (consider the trivial case of 1 * 1, tcFullMultiply
68 requires two parts to hold the single-part result). So we add an
69 extra one to guarantee enough space whilst multiplying. */
70 const unsigned int maxExponent = 16383;
71 const unsigned int maxPrecision = 113;
72 const unsigned int maxPowerOfFiveExponent = maxExponent + maxPrecision - 1;
73 const unsigned int maxPowerOfFiveParts = 2 + ((maxPowerOfFiveExponent * 1024)
74 / (441 * integerPartWidth));
77 /* Put a bunch of private, handy routines in an anonymous namespace. */
81 partCountForBits(unsigned int bits)
83 return ((bits) + integerPartWidth - 1) / integerPartWidth;
86 /* Returns 0U-9U. Return values >= 10U are not digits. */
88 decDigitValue(unsigned int c)
94 hexDigitValue(unsigned int c)
114 assertArithmeticOK(const llvm::fltSemantics &semantics) {
115 assert(semantics.arithmeticOK
116 && "Compile-time arithmetic does not support these semantics");
119 /* Return the value of a decimal exponent of the form
122 If the exponent overflows, returns a large exponent with the
125 readExponent(const char *p)
128 unsigned int absExponent;
129 const unsigned int overlargeExponent = 24000; /* FIXME. */
131 isNegative = (*p == '-');
132 if (*p == '-' || *p == '+')
135 absExponent = decDigitValue(*p++);
136 assert (absExponent < 10U);
141 value = decDigitValue(*p);
146 value += absExponent * 10;
147 if (absExponent >= overlargeExponent) {
148 absExponent = overlargeExponent;
155 return -(int) absExponent;
157 return (int) absExponent;
160 /* This is ugly and needs cleaning up, but I don't immediately see
161 how whilst remaining safe. */
163 totalExponent(const char *p, int exponentAdjustment)
165 integerPart unsignedExponent;
166 bool negative, overflow;
169 /* Move past the exponent letter and sign to the digits. */
171 negative = *p == '-';
172 if(*p == '-' || *p == '+')
175 unsignedExponent = 0;
180 value = decDigitValue(*p);
185 unsignedExponent = unsignedExponent * 10 + value;
186 if(unsignedExponent > 65535)
190 if(exponentAdjustment > 65535 || exponentAdjustment < -65536)
194 exponent = unsignedExponent;
196 exponent = -exponent;
197 exponent += exponentAdjustment;
198 if(exponent > 65535 || exponent < -65536)
203 exponent = negative ? -65536: 65535;
209 skipLeadingZeroesAndAnyDot(const char *p, const char **dot)
224 /* Given a normal decimal floating point number of the form
228 where the decimal point and exponent are optional, fill out the
229 structure D. If the value is zero, V->firstSigDigit
230 points to a zero, and the return exponent is zero. */
232 const char *firstSigDigit;
233 const char *lastSigDigit;
238 interpretDecimal(const char *p, decimalInfo *D)
242 p = skipLeadingZeroesAndAnyDot (p, &dot);
244 D->firstSigDigit = p;
252 if (decDigitValue(*p) >= 10U)
257 /* If number is all zerooes accept any exponent. */
258 if (p != D->firstSigDigit) {
259 if (*p == 'e' || *p == 'E')
260 D->exponent = readExponent(p + 1);
262 /* Implied decimal point? */
266 /* Drop insignificant trailing zeroes. */
273 /* Adjust the specified exponent for any decimal point. */
274 D->exponent += (dot - p) - (dot > p);
280 /* Return the trailing fraction of a hexadecimal number.
281 DIGITVALUE is the first hex digit of the fraction, P points to
284 trailingHexadecimalFraction(const char *p, unsigned int digitValue)
286 unsigned int hexDigit;
288 /* If the first trailing digit isn't 0 or 8 we can work out the
289 fraction immediately. */
291 return lfMoreThanHalf;
292 else if(digitValue < 8 && digitValue > 0)
293 return lfLessThanHalf;
295 /* Otherwise we need to find the first non-zero digit. */
299 hexDigit = hexDigitValue(*p);
301 /* If we ran off the end it is exactly zero or one-half, otherwise
304 return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
306 return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf;
309 /* Return the fraction lost were a bignum truncated losing the least
310 significant BITS bits. */
312 lostFractionThroughTruncation(const integerPart *parts,
313 unsigned int partCount,
318 lsb = APInt::tcLSB(parts, partCount);
320 /* Note this is guaranteed true if bits == 0, or LSB == -1U. */
322 return lfExactlyZero;
324 return lfExactlyHalf;
325 if(bits <= partCount * integerPartWidth
326 && APInt::tcExtractBit(parts, bits - 1))
327 return lfMoreThanHalf;
329 return lfLessThanHalf;
332 /* Shift DST right BITS bits noting lost fraction. */
334 shiftRight(integerPart *dst, unsigned int parts, unsigned int bits)
336 lostFraction lost_fraction;
338 lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
340 APInt::tcShiftRight(dst, parts, bits);
342 return lost_fraction;
345 /* Combine the effect of two lost fractions. */
347 combineLostFractions(lostFraction moreSignificant,
348 lostFraction lessSignificant)
350 if(lessSignificant != lfExactlyZero) {
351 if(moreSignificant == lfExactlyZero)
352 moreSignificant = lfLessThanHalf;
353 else if(moreSignificant == lfExactlyHalf)
354 moreSignificant = lfMoreThanHalf;
357 return moreSignificant;
360 /* The error from the true value, in half-ulps, on multiplying two
361 floating point numbers, which differ from the value they
362 approximate by at most HUE1 and HUE2 half-ulps, is strictly less
363 than the returned value.
365 See "How to Read Floating Point Numbers Accurately" by William D
368 HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
370 assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
372 if (HUerr1 + HUerr2 == 0)
373 return inexactMultiply * 2; /* <= inexactMultiply half-ulps. */
375 return inexactMultiply + 2 * (HUerr1 + HUerr2);
378 /* The number of ulps from the boundary (zero, or half if ISNEAREST)
379 when the least significant BITS are truncated. BITS cannot be
382 ulpsFromBoundary(const integerPart *parts, unsigned int bits, bool isNearest)
384 unsigned int count, partBits;
385 integerPart part, boundary;
390 count = bits / integerPartWidth;
391 partBits = bits % integerPartWidth + 1;
393 part = parts[count] & (~(integerPart) 0 >> (integerPartWidth - partBits));
396 boundary = (integerPart) 1 << (partBits - 1);
401 if (part - boundary <= boundary - part)
402 return part - boundary;
404 return boundary - part;
407 if (part == boundary) {
410 return ~(integerPart) 0; /* A lot. */
413 } else if (part == boundary - 1) {
416 return ~(integerPart) 0; /* A lot. */
421 return ~(integerPart) 0; /* A lot. */
424 /* Place pow(5, power) in DST, and return the number of parts used.
425 DST must be at least one part larger than size of the answer. */
427 powerOf5(integerPart *dst, unsigned int power)
429 static integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125,
431 static integerPart pow5s[maxPowerOfFiveParts * 2 + 5] = { 78125 * 5 };
432 static unsigned int partsCount[16] = { 1 };
434 integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5;
437 assert(power <= maxExponent);
442 *p1 = firstEightPowers[power & 7];
448 for (unsigned int n = 0; power; power >>= 1, n++) {
453 /* Calculate pow(5,pow(2,n+3)) if we haven't yet. */
455 pc = partsCount[n - 1];
456 APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc);
458 if (pow5[pc - 1] == 0)
466 APInt::tcFullMultiply(p2, p1, pow5, result, pc);
468 if (p2[result - 1] == 0)
471 /* Now result is in p1 with partsCount parts and p2 is scratch
473 tmp = p1, p1 = p2, p2 = tmp;
480 APInt::tcAssign(dst, p1, result);
485 /* Zero at the end to avoid modular arithmetic when adding one; used
486 when rounding up during hexadecimal output. */
487 static const char hexDigitsLower[] = "0123456789abcdef0";
488 static const char hexDigitsUpper[] = "0123456789ABCDEF0";
489 static const char infinityL[] = "infinity";
490 static const char infinityU[] = "INFINITY";
491 static const char NaNL[] = "nan";
492 static const char NaNU[] = "NAN";
494 /* Write out an integerPart in hexadecimal, starting with the most
495 significant nibble. Write out exactly COUNT hexdigits, return
498 partAsHex (char *dst, integerPart part, unsigned int count,
499 const char *hexDigitChars)
501 unsigned int result = count;
503 assert (count != 0 && count <= integerPartWidth / 4);
505 part >>= (integerPartWidth - 4 * count);
507 dst[count] = hexDigitChars[part & 0xf];
514 /* Write out an unsigned decimal integer. */
516 writeUnsignedDecimal (char *dst, unsigned int n)
532 /* Write out a signed decimal integer. */
534 writeSignedDecimal (char *dst, int value)
538 dst = writeUnsignedDecimal(dst, -(unsigned) value);
540 dst = writeUnsignedDecimal(dst, value);
548 APFloat::initialize(const fltSemantics *ourSemantics)
552 semantics = ourSemantics;
555 significand.parts = new integerPart[count];
559 APFloat::freeSignificand()
562 delete [] significand.parts;
566 APFloat::assign(const APFloat &rhs)
568 assert(semantics == rhs.semantics);
571 category = rhs.category;
572 exponent = rhs.exponent;
574 exponent2 = rhs.exponent2;
575 if(category == fcNormal || category == fcNaN)
576 copySignificand(rhs);
580 APFloat::copySignificand(const APFloat &rhs)
582 assert(category == fcNormal || category == fcNaN);
583 assert(rhs.partCount() >= partCount());
585 APInt::tcAssign(significandParts(), rhs.significandParts(),
590 APFloat::operator=(const APFloat &rhs)
593 if(semantics != rhs.semantics) {
595 initialize(rhs.semantics);
604 APFloat::bitwiseIsEqual(const APFloat &rhs) const {
607 if (semantics != rhs.semantics ||
608 category != rhs.category ||
611 if (semantics==(const llvm::fltSemantics* const)&PPCDoubleDouble &&
614 if (category==fcZero || category==fcInfinity)
616 else if (category==fcNormal && exponent!=rhs.exponent)
618 else if (semantics==(const llvm::fltSemantics* const)&PPCDoubleDouble &&
619 exponent2!=rhs.exponent2)
623 const integerPart* p=significandParts();
624 const integerPart* q=rhs.significandParts();
625 for (; i>0; i--, p++, q++) {
633 APFloat::APFloat(const fltSemantics &ourSemantics, integerPart value)
635 assertArithmeticOK(ourSemantics);
636 initialize(&ourSemantics);
639 exponent = ourSemantics.precision - 1;
640 significandParts()[0] = value;
641 normalize(rmNearestTiesToEven, lfExactlyZero);
644 APFloat::APFloat(const fltSemantics &ourSemantics,
645 fltCategory ourCategory, bool negative)
647 assertArithmeticOK(ourSemantics);
648 initialize(&ourSemantics);
649 category = ourCategory;
651 if(category == fcNormal)
655 APFloat::APFloat(const fltSemantics &ourSemantics, const char *text)
657 assertArithmeticOK(ourSemantics);
658 initialize(&ourSemantics);
659 convertFromString(text, rmNearestTiesToEven);
662 APFloat::APFloat(const APFloat &rhs)
664 initialize(rhs.semantics);
674 APFloat::partCount() const
676 return partCountForBits(semantics->precision + 1);
680 APFloat::semanticsPrecision(const fltSemantics &semantics)
682 return semantics.precision;
686 APFloat::significandParts() const
688 return const_cast<APFloat *>(this)->significandParts();
692 APFloat::significandParts()
694 assert(category == fcNormal || category == fcNaN);
697 return significand.parts;
699 return &significand.part;
703 APFloat::zeroSignificand()
706 APInt::tcSet(significandParts(), 0, partCount());
709 /* Increment an fcNormal floating point number's significand. */
711 APFloat::incrementSignificand()
715 carry = APInt::tcIncrement(significandParts(), partCount());
717 /* Our callers should never cause us to overflow. */
721 /* Add the significand of the RHS. Returns the carry flag. */
723 APFloat::addSignificand(const APFloat &rhs)
727 parts = significandParts();
729 assert(semantics == rhs.semantics);
730 assert(exponent == rhs.exponent);
732 return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
735 /* Subtract the significand of the RHS with a borrow flag. Returns
738 APFloat::subtractSignificand(const APFloat &rhs, integerPart borrow)
742 parts = significandParts();
744 assert(semantics == rhs.semantics);
745 assert(exponent == rhs.exponent);
747 return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
751 /* Multiply the significand of the RHS. If ADDEND is non-NULL, add it
752 on to the full-precision result of the multiplication. Returns the
755 APFloat::multiplySignificand(const APFloat &rhs, const APFloat *addend)
757 unsigned int omsb; // One, not zero, based MSB.
758 unsigned int partsCount, newPartsCount, precision;
759 integerPart *lhsSignificand;
760 integerPart scratch[4];
761 integerPart *fullSignificand;
762 lostFraction lost_fraction;
764 assert(semantics == rhs.semantics);
766 precision = semantics->precision;
767 newPartsCount = partCountForBits(precision * 2);
769 if(newPartsCount > 4)
770 fullSignificand = new integerPart[newPartsCount];
772 fullSignificand = scratch;
774 lhsSignificand = significandParts();
775 partsCount = partCount();
777 APInt::tcFullMultiply(fullSignificand, lhsSignificand,
778 rhs.significandParts(), partsCount, partsCount);
780 lost_fraction = lfExactlyZero;
781 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
782 exponent += rhs.exponent;
785 Significand savedSignificand = significand;
786 const fltSemantics *savedSemantics = semantics;
787 fltSemantics extendedSemantics;
789 unsigned int extendedPrecision;
791 /* Normalize our MSB. */
792 extendedPrecision = precision + precision - 1;
793 if(omsb != extendedPrecision)
795 APInt::tcShiftLeft(fullSignificand, newPartsCount,
796 extendedPrecision - omsb);
797 exponent -= extendedPrecision - omsb;
800 /* Create new semantics. */
801 extendedSemantics = *semantics;
802 extendedSemantics.precision = extendedPrecision;
804 if(newPartsCount == 1)
805 significand.part = fullSignificand[0];
807 significand.parts = fullSignificand;
808 semantics = &extendedSemantics;
810 APFloat extendedAddend(*addend);
811 status = extendedAddend.convert(extendedSemantics, rmTowardZero);
812 assert(status == opOK);
813 lost_fraction = addOrSubtractSignificand(extendedAddend, false);
815 /* Restore our state. */
816 if(newPartsCount == 1)
817 fullSignificand[0] = significand.part;
818 significand = savedSignificand;
819 semantics = savedSemantics;
821 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
824 exponent -= (precision - 1);
826 if(omsb > precision) {
827 unsigned int bits, significantParts;
830 bits = omsb - precision;
831 significantParts = partCountForBits(omsb);
832 lf = shiftRight(fullSignificand, significantParts, bits);
833 lost_fraction = combineLostFractions(lf, lost_fraction);
837 APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
839 if(newPartsCount > 4)
840 delete [] fullSignificand;
842 return lost_fraction;
845 /* Multiply the significands of LHS and RHS to DST. */
847 APFloat::divideSignificand(const APFloat &rhs)
849 unsigned int bit, i, partsCount;
850 const integerPart *rhsSignificand;
851 integerPart *lhsSignificand, *dividend, *divisor;
852 integerPart scratch[4];
853 lostFraction lost_fraction;
855 assert(semantics == rhs.semantics);
857 lhsSignificand = significandParts();
858 rhsSignificand = rhs.significandParts();
859 partsCount = partCount();
862 dividend = new integerPart[partsCount * 2];
866 divisor = dividend + partsCount;
868 /* Copy the dividend and divisor as they will be modified in-place. */
869 for(i = 0; i < partsCount; i++) {
870 dividend[i] = lhsSignificand[i];
871 divisor[i] = rhsSignificand[i];
872 lhsSignificand[i] = 0;
875 exponent -= rhs.exponent;
877 unsigned int precision = semantics->precision;
879 /* Normalize the divisor. */
880 bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
883 APInt::tcShiftLeft(divisor, partsCount, bit);
886 /* Normalize the dividend. */
887 bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
890 APInt::tcShiftLeft(dividend, partsCount, bit);
893 /* Ensure the dividend >= divisor initially for the loop below.
894 Incidentally, this means that the division loop below is
895 guaranteed to set the integer bit to one. */
896 if(APInt::tcCompare(dividend, divisor, partsCount) < 0) {
898 APInt::tcShiftLeft(dividend, partsCount, 1);
899 assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
903 for(bit = precision; bit; bit -= 1) {
904 if(APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
905 APInt::tcSubtract(dividend, divisor, 0, partsCount);
906 APInt::tcSetBit(lhsSignificand, bit - 1);
909 APInt::tcShiftLeft(dividend, partsCount, 1);
912 /* Figure out the lost fraction. */
913 int cmp = APInt::tcCompare(dividend, divisor, partsCount);
916 lost_fraction = lfMoreThanHalf;
918 lost_fraction = lfExactlyHalf;
919 else if(APInt::tcIsZero(dividend, partsCount))
920 lost_fraction = lfExactlyZero;
922 lost_fraction = lfLessThanHalf;
927 return lost_fraction;
931 APFloat::significandMSB() const
933 return APInt::tcMSB(significandParts(), partCount());
937 APFloat::significandLSB() const
939 return APInt::tcLSB(significandParts(), partCount());
942 /* Note that a zero result is NOT normalized to fcZero. */
944 APFloat::shiftSignificandRight(unsigned int bits)
946 /* Our exponent should not overflow. */
947 assert((exponent_t) (exponent + bits) >= exponent);
951 return shiftRight(significandParts(), partCount(), bits);
954 /* Shift the significand left BITS bits, subtract BITS from its exponent. */
956 APFloat::shiftSignificandLeft(unsigned int bits)
958 assert(bits < semantics->precision);
961 unsigned int partsCount = partCount();
963 APInt::tcShiftLeft(significandParts(), partsCount, bits);
966 assert(!APInt::tcIsZero(significandParts(), partsCount));
971 APFloat::compareAbsoluteValue(const APFloat &rhs) const
975 assert(semantics == rhs.semantics);
976 assert(category == fcNormal);
977 assert(rhs.category == fcNormal);
979 compare = exponent - rhs.exponent;
981 /* If exponents are equal, do an unsigned bignum comparison of the
984 compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
988 return cmpGreaterThan;
995 /* Handle overflow. Sign is preserved. We either become infinity or
996 the largest finite number. */
998 APFloat::handleOverflow(roundingMode rounding_mode)
1001 if(rounding_mode == rmNearestTiesToEven
1002 || rounding_mode == rmNearestTiesToAway
1003 || (rounding_mode == rmTowardPositive && !sign)
1004 || (rounding_mode == rmTowardNegative && sign))
1006 category = fcInfinity;
1007 return (opStatus) (opOverflow | opInexact);
1010 /* Otherwise we become the largest finite number. */
1011 category = fcNormal;
1012 exponent = semantics->maxExponent;
1013 APInt::tcSetLeastSignificantBits(significandParts(), partCount(),
1014 semantics->precision);
1019 /* Returns TRUE if, when truncating the current number, with BIT the
1020 new LSB, with the given lost fraction and rounding mode, the result
1021 would need to be rounded away from zero (i.e., by increasing the
1022 signficand). This routine must work for fcZero of both signs, and
1023 fcNormal numbers. */
1025 APFloat::roundAwayFromZero(roundingMode rounding_mode,
1026 lostFraction lost_fraction,
1027 unsigned int bit) const
1029 /* NaNs and infinities should not have lost fractions. */
1030 assert(category == fcNormal || category == fcZero);
1032 /* Current callers never pass this so we don't handle it. */
1033 assert(lost_fraction != lfExactlyZero);
1035 switch(rounding_mode) {
1039 case rmNearestTiesToAway:
1040 return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
1042 case rmNearestTiesToEven:
1043 if(lost_fraction == lfMoreThanHalf)
1046 /* Our zeroes don't have a significand to test. */
1047 if(lost_fraction == lfExactlyHalf && category != fcZero)
1048 return APInt::tcExtractBit(significandParts(), bit);
1055 case rmTowardPositive:
1056 return sign == false;
1058 case rmTowardNegative:
1059 return sign == true;
1064 APFloat::normalize(roundingMode rounding_mode,
1065 lostFraction lost_fraction)
1067 unsigned int omsb; /* One, not zero, based MSB. */
1070 if(category != fcNormal)
1073 /* Before rounding normalize the exponent of fcNormal numbers. */
1074 omsb = significandMSB() + 1;
1077 /* OMSB is numbered from 1. We want to place it in the integer
1078 bit numbered PRECISON if possible, with a compensating change in
1080 exponentChange = omsb - semantics->precision;
1082 /* If the resulting exponent is too high, overflow according to
1083 the rounding mode. */
1084 if(exponent + exponentChange > semantics->maxExponent)
1085 return handleOverflow(rounding_mode);
1087 /* Subnormal numbers have exponent minExponent, and their MSB
1088 is forced based on that. */
1089 if(exponent + exponentChange < semantics->minExponent)
1090 exponentChange = semantics->minExponent - exponent;
1092 /* Shifting left is easy as we don't lose precision. */
1093 if(exponentChange < 0) {
1094 assert(lost_fraction == lfExactlyZero);
1096 shiftSignificandLeft(-exponentChange);
1101 if(exponentChange > 0) {
1104 /* Shift right and capture any new lost fraction. */
1105 lf = shiftSignificandRight(exponentChange);
1107 lost_fraction = combineLostFractions(lf, lost_fraction);
1109 /* Keep OMSB up-to-date. */
1110 if(omsb > (unsigned) exponentChange)
1111 omsb -= exponentChange;
1117 /* Now round the number according to rounding_mode given the lost
1120 /* As specified in IEEE 754, since we do not trap we do not report
1121 underflow for exact results. */
1122 if(lost_fraction == lfExactlyZero) {
1123 /* Canonicalize zeroes. */
1130 /* Increment the significand if we're rounding away from zero. */
1131 if(roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
1133 exponent = semantics->minExponent;
1135 incrementSignificand();
1136 omsb = significandMSB() + 1;
1138 /* Did the significand increment overflow? */
1139 if(omsb == (unsigned) semantics->precision + 1) {
1140 /* Renormalize by incrementing the exponent and shifting our
1141 significand right one. However if we already have the
1142 maximum exponent we overflow to infinity. */
1143 if(exponent == semantics->maxExponent) {
1144 category = fcInfinity;
1146 return (opStatus) (opOverflow | opInexact);
1149 shiftSignificandRight(1);
1155 /* The normal case - we were and are not denormal, and any
1156 significand increment above didn't overflow. */
1157 if(omsb == semantics->precision)
1160 /* We have a non-zero denormal. */
1161 assert(omsb < semantics->precision);
1163 /* Canonicalize zeroes. */
1167 /* The fcZero case is a denormal that underflowed to zero. */
1168 return (opStatus) (opUnderflow | opInexact);
1172 APFloat::addOrSubtractSpecials(const APFloat &rhs, bool subtract)
1174 switch(convolve(category, rhs.category)) {
1178 case convolve(fcNaN, fcZero):
1179 case convolve(fcNaN, fcNormal):
1180 case convolve(fcNaN, fcInfinity):
1181 case convolve(fcNaN, fcNaN):
1182 case convolve(fcNormal, fcZero):
1183 case convolve(fcInfinity, fcNormal):
1184 case convolve(fcInfinity, fcZero):
1187 case convolve(fcZero, fcNaN):
1188 case convolve(fcNormal, fcNaN):
1189 case convolve(fcInfinity, fcNaN):
1191 copySignificand(rhs);
1194 case convolve(fcNormal, fcInfinity):
1195 case convolve(fcZero, fcInfinity):
1196 category = fcInfinity;
1197 sign = rhs.sign ^ subtract;
1200 case convolve(fcZero, fcNormal):
1202 sign = rhs.sign ^ subtract;
1205 case convolve(fcZero, fcZero):
1206 /* Sign depends on rounding mode; handled by caller. */
1209 case convolve(fcInfinity, fcInfinity):
1210 /* Differently signed infinities can only be validly
1212 if(sign ^ rhs.sign != subtract) {
1214 // Arbitrary but deterministic value for significand
1215 APInt::tcSet(significandParts(), ~0U, partCount());
1221 case convolve(fcNormal, fcNormal):
1226 /* Add or subtract two normal numbers. */
1228 APFloat::addOrSubtractSignificand(const APFloat &rhs, bool subtract)
1231 lostFraction lost_fraction;
1234 /* Determine if the operation on the absolute values is effectively
1235 an addition or subtraction. */
1236 subtract ^= (sign ^ rhs.sign);
1238 /* Are we bigger exponent-wise than the RHS? */
1239 bits = exponent - rhs.exponent;
1241 /* Subtraction is more subtle than one might naively expect. */
1243 APFloat temp_rhs(rhs);
1247 reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan;
1248 lost_fraction = lfExactlyZero;
1249 } else if (bits > 0) {
1250 lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
1251 shiftSignificandLeft(1);
1254 lost_fraction = shiftSignificandRight(-bits - 1);
1255 temp_rhs.shiftSignificandLeft(1);
1260 carry = temp_rhs.subtractSignificand
1261 (*this, lost_fraction != lfExactlyZero);
1262 copySignificand(temp_rhs);
1265 carry = subtractSignificand
1266 (temp_rhs, lost_fraction != lfExactlyZero);
1269 /* Invert the lost fraction - it was on the RHS and
1271 if(lost_fraction == lfLessThanHalf)
1272 lost_fraction = lfMoreThanHalf;
1273 else if(lost_fraction == lfMoreThanHalf)
1274 lost_fraction = lfLessThanHalf;
1276 /* The code above is intended to ensure that no borrow is
1281 APFloat temp_rhs(rhs);
1283 lost_fraction = temp_rhs.shiftSignificandRight(bits);
1284 carry = addSignificand(temp_rhs);
1286 lost_fraction = shiftSignificandRight(-bits);
1287 carry = addSignificand(rhs);
1290 /* We have a guard bit; generating a carry cannot happen. */
1294 return lost_fraction;
1298 APFloat::multiplySpecials(const APFloat &rhs)
1300 switch(convolve(category, rhs.category)) {
1304 case convolve(fcNaN, fcZero):
1305 case convolve(fcNaN, fcNormal):
1306 case convolve(fcNaN, fcInfinity):
1307 case convolve(fcNaN, fcNaN):
1310 case convolve(fcZero, fcNaN):
1311 case convolve(fcNormal, fcNaN):
1312 case convolve(fcInfinity, fcNaN):
1314 copySignificand(rhs);
1317 case convolve(fcNormal, fcInfinity):
1318 case convolve(fcInfinity, fcNormal):
1319 case convolve(fcInfinity, fcInfinity):
1320 category = fcInfinity;
1323 case convolve(fcZero, fcNormal):
1324 case convolve(fcNormal, fcZero):
1325 case convolve(fcZero, fcZero):
1329 case convolve(fcZero, fcInfinity):
1330 case convolve(fcInfinity, fcZero):
1332 // Arbitrary but deterministic value for significand
1333 APInt::tcSet(significandParts(), ~0U, partCount());
1336 case convolve(fcNormal, fcNormal):
1342 APFloat::divideSpecials(const APFloat &rhs)
1344 switch(convolve(category, rhs.category)) {
1348 case convolve(fcNaN, fcZero):
1349 case convolve(fcNaN, fcNormal):
1350 case convolve(fcNaN, fcInfinity):
1351 case convolve(fcNaN, fcNaN):
1352 case convolve(fcInfinity, fcZero):
1353 case convolve(fcInfinity, fcNormal):
1354 case convolve(fcZero, fcInfinity):
1355 case convolve(fcZero, fcNormal):
1358 case convolve(fcZero, fcNaN):
1359 case convolve(fcNormal, fcNaN):
1360 case convolve(fcInfinity, fcNaN):
1362 copySignificand(rhs);
1365 case convolve(fcNormal, fcInfinity):
1369 case convolve(fcNormal, fcZero):
1370 category = fcInfinity;
1373 case convolve(fcInfinity, fcInfinity):
1374 case convolve(fcZero, fcZero):
1376 // Arbitrary but deterministic value for significand
1377 APInt::tcSet(significandParts(), ~0U, partCount());
1380 case convolve(fcNormal, fcNormal):
1387 APFloat::changeSign()
1389 /* Look mummy, this one's easy. */
1394 APFloat::clearSign()
1396 /* So is this one. */
1401 APFloat::copySign(const APFloat &rhs)
1407 /* Normalized addition or subtraction. */
1409 APFloat::addOrSubtract(const APFloat &rhs, roundingMode rounding_mode,
1414 assertArithmeticOK(*semantics);
1416 fs = addOrSubtractSpecials(rhs, subtract);
1418 /* This return code means it was not a simple case. */
1419 if(fs == opDivByZero) {
1420 lostFraction lost_fraction;
1422 lost_fraction = addOrSubtractSignificand(rhs, subtract);
1423 fs = normalize(rounding_mode, lost_fraction);
1425 /* Can only be zero if we lost no fraction. */
1426 assert(category != fcZero || lost_fraction == lfExactlyZero);
1429 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1430 positive zero unless rounding to minus infinity, except that
1431 adding two like-signed zeroes gives that zero. */
1432 if(category == fcZero) {
1433 if(rhs.category != fcZero || (sign == rhs.sign) == subtract)
1434 sign = (rounding_mode == rmTowardNegative);
1440 /* Normalized addition. */
1442 APFloat::add(const APFloat &rhs, roundingMode rounding_mode)
1444 return addOrSubtract(rhs, rounding_mode, false);
1447 /* Normalized subtraction. */
1449 APFloat::subtract(const APFloat &rhs, roundingMode rounding_mode)
1451 return addOrSubtract(rhs, rounding_mode, true);
1454 /* Normalized multiply. */
1456 APFloat::multiply(const APFloat &rhs, roundingMode rounding_mode)
1460 assertArithmeticOK(*semantics);
1462 fs = multiplySpecials(rhs);
1464 if(category == fcNormal) {
1465 lostFraction lost_fraction = multiplySignificand(rhs, 0);
1466 fs = normalize(rounding_mode, lost_fraction);
1467 if(lost_fraction != lfExactlyZero)
1468 fs = (opStatus) (fs | opInexact);
1474 /* Normalized divide. */
1476 APFloat::divide(const APFloat &rhs, roundingMode rounding_mode)
1480 assertArithmeticOK(*semantics);
1482 fs = divideSpecials(rhs);
1484 if(category == fcNormal) {
1485 lostFraction lost_fraction = divideSignificand(rhs);
1486 fs = normalize(rounding_mode, lost_fraction);
1487 if(lost_fraction != lfExactlyZero)
1488 fs = (opStatus) (fs | opInexact);
1494 /* Normalized remainder. This is not currently doing TRT. */
1496 APFloat::mod(const APFloat &rhs, roundingMode rounding_mode)
1500 unsigned int origSign = sign;
1502 assertArithmeticOK(*semantics);
1503 fs = V.divide(rhs, rmNearestTiesToEven);
1504 if (fs == opDivByZero)
1507 int parts = partCount();
1508 integerPart *x = new integerPart[parts];
1509 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1510 rmNearestTiesToEven);
1511 if (fs==opInvalidOp)
1514 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1515 rmNearestTiesToEven);
1516 assert(fs==opOK); // should always work
1518 fs = V.multiply(rhs, rounding_mode);
1519 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1521 fs = subtract(V, rounding_mode);
1522 assert(fs==opOK || fs==opInexact); // likewise
1525 sign = origSign; // IEEE754 requires this
1530 /* Normalized fused-multiply-add. */
1532 APFloat::fusedMultiplyAdd(const APFloat &multiplicand,
1533 const APFloat &addend,
1534 roundingMode rounding_mode)
1538 assertArithmeticOK(*semantics);
1540 /* Post-multiplication sign, before addition. */
1541 sign ^= multiplicand.sign;
1543 /* If and only if all arguments are normal do we need to do an
1544 extended-precision calculation. */
1545 if(category == fcNormal
1546 && multiplicand.category == fcNormal
1547 && addend.category == fcNormal) {
1548 lostFraction lost_fraction;
1550 lost_fraction = multiplySignificand(multiplicand, &addend);
1551 fs = normalize(rounding_mode, lost_fraction);
1552 if(lost_fraction != lfExactlyZero)
1553 fs = (opStatus) (fs | opInexact);
1555 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1556 positive zero unless rounding to minus infinity, except that
1557 adding two like-signed zeroes gives that zero. */
1558 if(category == fcZero && sign != addend.sign)
1559 sign = (rounding_mode == rmTowardNegative);
1561 fs = multiplySpecials(multiplicand);
1563 /* FS can only be opOK or opInvalidOp. There is no more work
1564 to do in the latter case. The IEEE-754R standard says it is
1565 implementation-defined in this case whether, if ADDEND is a
1566 quiet NaN, we raise invalid op; this implementation does so.
1568 If we need to do the addition we can do so with normal
1571 fs = addOrSubtract(addend, rounding_mode, false);
1577 /* Comparison requires normalized numbers. */
1579 APFloat::compare(const APFloat &rhs) const
1583 assertArithmeticOK(*semantics);
1584 assert(semantics == rhs.semantics);
1586 switch(convolve(category, rhs.category)) {
1590 case convolve(fcNaN, fcZero):
1591 case convolve(fcNaN, fcNormal):
1592 case convolve(fcNaN, fcInfinity):
1593 case convolve(fcNaN, fcNaN):
1594 case convolve(fcZero, fcNaN):
1595 case convolve(fcNormal, fcNaN):
1596 case convolve(fcInfinity, fcNaN):
1597 return cmpUnordered;
1599 case convolve(fcInfinity, fcNormal):
1600 case convolve(fcInfinity, fcZero):
1601 case convolve(fcNormal, fcZero):
1605 return cmpGreaterThan;
1607 case convolve(fcNormal, fcInfinity):
1608 case convolve(fcZero, fcInfinity):
1609 case convolve(fcZero, fcNormal):
1611 return cmpGreaterThan;
1615 case convolve(fcInfinity, fcInfinity):
1616 if(sign == rhs.sign)
1621 return cmpGreaterThan;
1623 case convolve(fcZero, fcZero):
1626 case convolve(fcNormal, fcNormal):
1630 /* Two normal numbers. Do they have the same sign? */
1631 if(sign != rhs.sign) {
1633 result = cmpLessThan;
1635 result = cmpGreaterThan;
1637 /* Compare absolute values; invert result if negative. */
1638 result = compareAbsoluteValue(rhs);
1641 if(result == cmpLessThan)
1642 result = cmpGreaterThan;
1643 else if(result == cmpGreaterThan)
1644 result = cmpLessThan;
1652 APFloat::convert(const fltSemantics &toSemantics,
1653 roundingMode rounding_mode)
1655 lostFraction lostFraction;
1656 unsigned int newPartCount, oldPartCount;
1659 assertArithmeticOK(*semantics);
1660 lostFraction = lfExactlyZero;
1661 newPartCount = partCountForBits(toSemantics.precision + 1);
1662 oldPartCount = partCount();
1664 /* Handle storage complications. If our new form is wider,
1665 re-allocate our bit pattern into wider storage. If it is
1666 narrower, we ignore the excess parts, but if narrowing to a
1667 single part we need to free the old storage.
1668 Be careful not to reference significandParts for zeroes
1669 and infinities, since it aborts. */
1670 if (newPartCount > oldPartCount) {
1671 integerPart *newParts;
1672 newParts = new integerPart[newPartCount];
1673 APInt::tcSet(newParts, 0, newPartCount);
1674 if (category==fcNormal || category==fcNaN)
1675 APInt::tcAssign(newParts, significandParts(), oldPartCount);
1677 significand.parts = newParts;
1678 } else if (newPartCount < oldPartCount) {
1679 /* Capture any lost fraction through truncation of parts so we get
1680 correct rounding whilst normalizing. */
1681 if (category==fcNormal)
1682 lostFraction = lostFractionThroughTruncation
1683 (significandParts(), oldPartCount, toSemantics.precision);
1684 if (newPartCount == 1) {
1685 integerPart newPart = 0;
1686 if (category==fcNormal || category==fcNaN)
1687 newPart = significandParts()[0];
1689 significand.part = newPart;
1693 if(category == fcNormal) {
1694 /* Re-interpret our bit-pattern. */
1695 exponent += toSemantics.precision - semantics->precision;
1696 semantics = &toSemantics;
1697 fs = normalize(rounding_mode, lostFraction);
1698 } else if (category == fcNaN) {
1699 int shift = toSemantics.precision - semantics->precision;
1700 // No normalization here, just truncate
1702 APInt::tcShiftLeft(significandParts(), newPartCount, shift);
1704 APInt::tcShiftRight(significandParts(), newPartCount, -shift);
1705 // gcc forces the Quiet bit on, which means (float)(double)(float_sNan)
1706 // does not give you back the same bits. This is dubious, and we
1707 // don't currently do it. You're really supposed to get
1708 // an invalid operation signal at runtime, but nobody does that.
1709 semantics = &toSemantics;
1712 semantics = &toSemantics;
1719 /* Convert a floating point number to an integer according to the
1720 rounding mode. If the rounded integer value is out of range this
1721 returns an invalid operation exception. If the rounded value is in
1722 range but the floating point number is not the exact integer, the C
1723 standard doesn't require an inexact exception to be raised. IEEE
1724 854 does require it so we do that.
1726 Note that for conversions to integer type the C standard requires
1727 round-to-zero to always be used. */
1729 APFloat::convertToInteger(integerPart *parts, unsigned int width,
1731 roundingMode rounding_mode) const
1733 lostFraction lost_fraction;
1734 unsigned int msb, partsCount;
1737 assertArithmeticOK(*semantics);
1738 partsCount = partCountForBits(width);
1740 /* Handle the three special cases first. We produce
1741 a deterministic result even for the Invalid cases. */
1742 if (category == fcNaN) {
1743 // Neither sign nor isSigned affects this.
1744 APInt::tcSet(parts, 0, partsCount);
1747 if (category == fcInfinity) {
1748 if (!sign && isSigned)
1749 APInt::tcSetLeastSignificantBits(parts, partsCount, width-1);
1750 else if (!sign && !isSigned)
1751 APInt::tcSetLeastSignificantBits(parts, partsCount, width);
1752 else if (sign && isSigned) {
1753 APInt::tcSetLeastSignificantBits(parts, partsCount, 1);
1754 APInt::tcShiftLeft(parts, partsCount, width-1);
1755 } else // sign && !isSigned
1756 APInt::tcSet(parts, 0, partsCount);
1759 if (category == fcZero) {
1760 APInt::tcSet(parts, 0, partsCount);
1764 /* Shift the bit pattern so the fraction is lost. */
1767 bits = (int) semantics->precision - 1 - exponent;
1770 lost_fraction = tmp.shiftSignificandRight(bits);
1772 if (-bits >= semantics->precision) {
1773 // Unrepresentably large.
1774 if (!sign && isSigned)
1775 APInt::tcSetLeastSignificantBits(parts, partsCount, width-1);
1776 else if (!sign && !isSigned)
1777 APInt::tcSetLeastSignificantBits(parts, partsCount, width);
1778 else if (sign && isSigned) {
1779 APInt::tcSetLeastSignificantBits(parts, partsCount, 1);
1780 APInt::tcShiftLeft(parts, partsCount, width-1);
1781 } else // sign && !isSigned
1782 APInt::tcSet(parts, 0, partsCount);
1783 return (opStatus)(opOverflow | opInexact);
1785 tmp.shiftSignificandLeft(-bits);
1786 lost_fraction = lfExactlyZero;
1789 if(lost_fraction != lfExactlyZero
1790 && tmp.roundAwayFromZero(rounding_mode, lost_fraction, 0))
1791 tmp.incrementSignificand();
1793 msb = tmp.significandMSB();
1795 /* Negative numbers cannot be represented as unsigned. */
1796 if(!isSigned && tmp.sign && msb != -1U)
1799 /* It takes exponent + 1 bits to represent the truncated floating
1800 point number without its sign. We lose a bit for the sign, but
1801 the maximally negative integer is a special case. */
1802 if(msb + 1 > width) /* !! Not same as msb >= width !! */
1805 if(isSigned && msb + 1 == width
1806 && (!tmp.sign || tmp.significandLSB() != msb))
1809 APInt::tcAssign(parts, tmp.significandParts(), partsCount);
1812 APInt::tcNegate(parts, partsCount);
1814 if(lost_fraction == lfExactlyZero)
1820 /* Convert an unsigned integer SRC to a floating point number,
1821 rounding according to ROUNDING_MODE. The sign of the floating
1822 point number is not modified. */
1824 APFloat::convertFromUnsignedParts(const integerPart *src,
1825 unsigned int srcCount,
1826 roundingMode rounding_mode)
1828 unsigned int omsb, precision, dstCount;
1830 lostFraction lost_fraction;
1832 assertArithmeticOK(*semantics);
1833 category = fcNormal;
1834 omsb = APInt::tcMSB(src, srcCount) + 1;
1835 dst = significandParts();
1836 dstCount = partCount();
1837 precision = semantics->precision;
1839 /* We want the most significant PRECISON bits of SRC. There may not
1840 be that many; extract what we can. */
1841 if (precision <= omsb) {
1842 exponent = omsb - 1;
1843 lost_fraction = lostFractionThroughTruncation(src, srcCount,
1845 APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
1847 exponent = precision - 1;
1848 lost_fraction = lfExactlyZero;
1849 APInt::tcExtract(dst, dstCount, src, omsb, 0);
1852 return normalize(rounding_mode, lost_fraction);
1855 /* Convert a two's complement integer SRC to a floating point number,
1856 rounding according to ROUNDING_MODE. ISSIGNED is true if the
1857 integer is signed, in which case it must be sign-extended. */
1859 APFloat::convertFromSignExtendedInteger(const integerPart *src,
1860 unsigned int srcCount,
1862 roundingMode rounding_mode)
1866 assertArithmeticOK(*semantics);
1868 && APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) {
1871 /* If we're signed and negative negate a copy. */
1873 copy = new integerPart[srcCount];
1874 APInt::tcAssign(copy, src, srcCount);
1875 APInt::tcNegate(copy, srcCount);
1876 status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
1880 status = convertFromUnsignedParts(src, srcCount, rounding_mode);
1886 /* FIXME: should this just take a const APInt reference? */
1888 APFloat::convertFromZeroExtendedInteger(const integerPart *parts,
1889 unsigned int width, bool isSigned,
1890 roundingMode rounding_mode)
1892 unsigned int partCount = partCountForBits(width);
1893 APInt api = APInt(width, partCount, parts);
1896 if(isSigned && APInt::tcExtractBit(parts, width - 1)) {
1901 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
1905 APFloat::convertFromHexadecimalString(const char *p,
1906 roundingMode rounding_mode)
1908 lostFraction lost_fraction;
1909 integerPart *significand;
1910 unsigned int bitPos, partsCount;
1911 const char *dot, *firstSignificantDigit;
1915 category = fcNormal;
1917 significand = significandParts();
1918 partsCount = partCount();
1919 bitPos = partsCount * integerPartWidth;
1921 /* Skip leading zeroes and any (hexa)decimal point. */
1922 p = skipLeadingZeroesAndAnyDot(p, &dot);
1923 firstSignificantDigit = p;
1926 integerPart hex_value;
1933 hex_value = hexDigitValue(*p);
1934 if(hex_value == -1U) {
1935 lost_fraction = lfExactlyZero;
1941 /* Store the number whilst 4-bit nibbles remain. */
1944 hex_value <<= bitPos % integerPartWidth;
1945 significand[bitPos / integerPartWidth] |= hex_value;
1947 lost_fraction = trailingHexadecimalFraction(p, hex_value);
1948 while(hexDigitValue(*p) != -1U)
1954 /* Hex floats require an exponent but not a hexadecimal point. */
1955 assert(*p == 'p' || *p == 'P');
1957 /* Ignore the exponent if we are zero. */
1958 if(p != firstSignificantDigit) {
1961 /* Implicit hexadecimal point? */
1965 /* Calculate the exponent adjustment implicit in the number of
1966 significant digits. */
1967 expAdjustment = dot - firstSignificantDigit;
1968 if(expAdjustment < 0)
1970 expAdjustment = expAdjustment * 4 - 1;
1972 /* Adjust for writing the significand starting at the most
1973 significant nibble. */
1974 expAdjustment += semantics->precision;
1975 expAdjustment -= partsCount * integerPartWidth;
1977 /* Adjust for the given exponent. */
1978 exponent = totalExponent(p, expAdjustment);
1981 return normalize(rounding_mode, lost_fraction);
1985 APFloat::roundSignificandWithExponent(const integerPart *decSigParts,
1986 unsigned sigPartCount, int exp,
1987 roundingMode rounding_mode)
1989 unsigned int parts, pow5PartCount;
1990 fltSemantics calcSemantics = { 32767, -32767, 0, true };
1991 integerPart pow5Parts[maxPowerOfFiveParts];
1994 isNearest = (rounding_mode == rmNearestTiesToEven
1995 || rounding_mode == rmNearestTiesToAway);
1997 parts = partCountForBits(semantics->precision + 11);
1999 /* Calculate pow(5, abs(exp)). */
2000 pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp);
2002 for (;; parts *= 2) {
2003 opStatus sigStatus, powStatus;
2004 unsigned int excessPrecision, truncatedBits;
2006 calcSemantics.precision = parts * integerPartWidth - 1;
2007 excessPrecision = calcSemantics.precision - semantics->precision;
2008 truncatedBits = excessPrecision;
2010 APFloat decSig(calcSemantics, fcZero, sign);
2011 APFloat pow5(calcSemantics, fcZero, false);
2013 sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount,
2014 rmNearestTiesToEven);
2015 powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
2016 rmNearestTiesToEven);
2017 /* Add exp, as 10^n = 5^n * 2^n. */
2018 decSig.exponent += exp;
2020 lostFraction calcLostFraction;
2021 integerPart HUerr, HUdistance, powHUerr;
2024 /* multiplySignificand leaves the precision-th bit set to 1. */
2025 calcLostFraction = decSig.multiplySignificand(pow5, NULL);
2026 powHUerr = powStatus != opOK;
2028 calcLostFraction = decSig.divideSignificand(pow5);
2029 /* Denormal numbers have less precision. */
2030 if (decSig.exponent < semantics->minExponent) {
2031 excessPrecision += (semantics->minExponent - decSig.exponent);
2032 truncatedBits = excessPrecision;
2033 if (excessPrecision > calcSemantics.precision)
2034 excessPrecision = calcSemantics.precision;
2036 /* Extra half-ulp lost in reciprocal of exponent. */
2037 powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0: 2;
2040 /* Both multiplySignificand and divideSignificand return the
2041 result with the integer bit set. */
2042 assert (APInt::tcExtractBit
2043 (decSig.significandParts(), calcSemantics.precision - 1) == 1);
2045 HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK,
2047 HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
2048 excessPrecision, isNearest);
2050 /* Are we guaranteed to round correctly if we truncate? */
2051 if (HUdistance >= HUerr) {
2052 APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
2053 calcSemantics.precision - excessPrecision,
2055 /* Take the exponent of decSig. If we tcExtract-ed less bits
2056 above we must adjust our exponent to compensate for the
2057 implicit right shift. */
2058 exponent = (decSig.exponent + semantics->precision
2059 - (calcSemantics.precision - excessPrecision));
2060 calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(),
2063 return normalize(rounding_mode, calcLostFraction);
2069 APFloat::convertFromDecimalString(const char *p, roundingMode rounding_mode)
2074 /* Scan the text. */
2075 interpretDecimal(p, &D);
2077 if (*D.firstSigDigit == '0') {
2081 integerPart *decSignificand;
2082 unsigned int partCount;
2084 /* A tight upper bound on number of bits required to hold an
2085 N-digit decimal integer is N * 256 / 77. Allocate enough space
2086 to hold the full significand, and an extra part required by
2088 partCount = (D.lastSigDigit - D.firstSigDigit) + 1;
2089 partCount = partCountForBits(1 + 256 * partCount / 77);
2090 decSignificand = new integerPart[partCount + 1];
2093 /* Convert to binary efficiently - we do almost all multiplication
2094 in an integerPart. When this would overflow do we do a single
2095 bignum multiplication, and then revert again to multiplication
2096 in an integerPart. */
2098 integerPart decValue, val, multiplier;
2107 decValue = decDigitValue(*p++);
2109 val = val * 10 + decValue;
2110 /* The maximum number that can be multiplied by ten with any
2111 digit added without overflowing an integerPart. */
2112 } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
2114 /* Multiply out the current part. */
2115 APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
2116 partCount, partCount + 1, false);
2118 /* If we used another part (likely but not guaranteed), increase
2120 if (decSignificand[partCount])
2122 } while (p <= D.lastSigDigit);
2124 category = fcNormal;
2125 fs = roundSignificandWithExponent(decSignificand, partCount,
2126 D.exponent, rounding_mode);
2128 delete [] decSignificand;
2135 APFloat::convertFromString(const char *p, roundingMode rounding_mode)
2137 assertArithmeticOK(*semantics);
2139 /* Handle a leading minus sign. */
2145 if(p[0] == '0' && (p[1] == 'x' || p[1] == 'X'))
2146 return convertFromHexadecimalString(p + 2, rounding_mode);
2148 return convertFromDecimalString(p, rounding_mode);
2151 /* Write out a hexadecimal representation of the floating point value
2152 to DST, which must be of sufficient size, in the C99 form
2153 [-]0xh.hhhhp[+-]d. Return the number of characters written,
2154 excluding the terminating NUL.
2156 If UPPERCASE, the output is in upper case, otherwise in lower case.
2158 HEXDIGITS digits appear altogether, rounding the value if
2159 necessary. If HEXDIGITS is 0, the minimal precision to display the
2160 number precisely is used instead. If nothing would appear after
2161 the decimal point it is suppressed.
2163 The decimal exponent is always printed and has at least one digit.
2164 Zero values display an exponent of zero. Infinities and NaNs
2165 appear as "infinity" or "nan" respectively.
2167 The above rules are as specified by C99. There is ambiguity about
2168 what the leading hexadecimal digit should be. This implementation
2169 uses whatever is necessary so that the exponent is displayed as
2170 stored. This implies the exponent will fall within the IEEE format
2171 range, and the leading hexadecimal digit will be 0 (for denormals),
2172 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
2173 any other digits zero).
2176 APFloat::convertToHexString(char *dst, unsigned int hexDigits,
2177 bool upperCase, roundingMode rounding_mode) const
2181 assertArithmeticOK(*semantics);
2189 memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
2190 dst += sizeof infinityL - 1;
2194 memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
2195 dst += sizeof NaNU - 1;
2200 *dst++ = upperCase ? 'X': 'x';
2202 if (hexDigits > 1) {
2204 memset (dst, '0', hexDigits - 1);
2205 dst += hexDigits - 1;
2207 *dst++ = upperCase ? 'P': 'p';
2212 dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
2221 /* Does the hard work of outputting the correctly rounded hexadecimal
2222 form of a normal floating point number with the specified number of
2223 hexadecimal digits. If HEXDIGITS is zero the minimum number of
2224 digits necessary to print the value precisely is output. */
2226 APFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
2228 roundingMode rounding_mode) const
2230 unsigned int count, valueBits, shift, partsCount, outputDigits;
2231 const char *hexDigitChars;
2232 const integerPart *significand;
2237 *dst++ = upperCase ? 'X': 'x';
2240 hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower;
2242 significand = significandParts();
2243 partsCount = partCount();
2245 /* +3 because the first digit only uses the single integer bit, so
2246 we have 3 virtual zero most-significant-bits. */
2247 valueBits = semantics->precision + 3;
2248 shift = integerPartWidth - valueBits % integerPartWidth;
2250 /* The natural number of digits required ignoring trailing
2251 insignificant zeroes. */
2252 outputDigits = (valueBits - significandLSB () + 3) / 4;
2254 /* hexDigits of zero means use the required number for the
2255 precision. Otherwise, see if we are truncating. If we are,
2256 find out if we need to round away from zero. */
2258 if (hexDigits < outputDigits) {
2259 /* We are dropping non-zero bits, so need to check how to round.
2260 "bits" is the number of dropped bits. */
2262 lostFraction fraction;
2264 bits = valueBits - hexDigits * 4;
2265 fraction = lostFractionThroughTruncation (significand, partsCount, bits);
2266 roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
2268 outputDigits = hexDigits;
2271 /* Write the digits consecutively, and start writing in the location
2272 of the hexadecimal point. We move the most significant digit
2273 left and add the hexadecimal point later. */
2276 count = (valueBits + integerPartWidth - 1) / integerPartWidth;
2278 while (outputDigits && count) {
2281 /* Put the most significant integerPartWidth bits in "part". */
2282 if (--count == partsCount)
2283 part = 0; /* An imaginary higher zero part. */
2285 part = significand[count] << shift;
2288 part |= significand[count - 1] >> (integerPartWidth - shift);
2290 /* Convert as much of "part" to hexdigits as we can. */
2291 unsigned int curDigits = integerPartWidth / 4;
2293 if (curDigits > outputDigits)
2294 curDigits = outputDigits;
2295 dst += partAsHex (dst, part, curDigits, hexDigitChars);
2296 outputDigits -= curDigits;
2302 /* Note that hexDigitChars has a trailing '0'. */
2305 *q = hexDigitChars[hexDigitValue (*q) + 1];
2306 } while (*q == '0');
2309 /* Add trailing zeroes. */
2310 memset (dst, '0', outputDigits);
2311 dst += outputDigits;
2314 /* Move the most significant digit to before the point, and if there
2315 is something after the decimal point add it. This must come
2316 after rounding above. */
2323 /* Finally output the exponent. */
2324 *dst++ = upperCase ? 'P': 'p';
2326 return writeSignedDecimal (dst, exponent);
2329 // For good performance it is desirable for different APFloats
2330 // to produce different integers.
2332 APFloat::getHashValue() const
2334 if (category==fcZero) return sign<<8 | semantics->precision ;
2335 else if (category==fcInfinity) return sign<<9 | semantics->precision;
2336 else if (category==fcNaN) return 1<<10 | semantics->precision;
2338 uint32_t hash = sign<<11 | semantics->precision | exponent<<12;
2339 const integerPart* p = significandParts();
2340 for (int i=partCount(); i>0; i--, p++)
2341 hash ^= ((uint32_t)*p) ^ (*p)>>32;
2346 // Conversion from APFloat to/from host float/double. It may eventually be
2347 // possible to eliminate these and have everybody deal with APFloats, but that
2348 // will take a while. This approach will not easily extend to long double.
2349 // Current implementation requires integerPartWidth==64, which is correct at
2350 // the moment but could be made more general.
2352 // Denormals have exponent minExponent in APFloat, but minExponent-1 in
2353 // the actual IEEE respresentations. We compensate for that here.
2356 APFloat::convertF80LongDoubleAPFloatToAPInt() const
2358 assert(semantics == (const llvm::fltSemantics* const)&x87DoubleExtended);
2359 assert (partCount()==2);
2361 uint64_t myexponent, mysignificand;
2363 if (category==fcNormal) {
2364 myexponent = exponent+16383; //bias
2365 mysignificand = significandParts()[0];
2366 if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
2367 myexponent = 0; // denormal
2368 } else if (category==fcZero) {
2371 } else if (category==fcInfinity) {
2372 myexponent = 0x7fff;
2373 mysignificand = 0x8000000000000000ULL;
2375 assert(category == fcNaN && "Unknown category");
2376 myexponent = 0x7fff;
2377 mysignificand = significandParts()[0];
2381 words[0] = (((uint64_t)sign & 1) << 63) |
2382 ((myexponent & 0x7fff) << 48) |
2383 ((mysignificand >>16) & 0xffffffffffffLL);
2384 words[1] = mysignificand & 0xffff;
2385 return APInt(80, 2, words);
2389 APFloat::convertPPCDoubleDoubleAPFloatToAPInt() const
2391 assert(semantics == (const llvm::fltSemantics* const)&PPCDoubleDouble);
2392 assert (partCount()==2);
2394 uint64_t myexponent, mysignificand, myexponent2, mysignificand2;
2396 if (category==fcNormal) {
2397 myexponent = exponent + 1023; //bias
2398 myexponent2 = exponent2 + 1023;
2399 mysignificand = significandParts()[0];
2400 mysignificand2 = significandParts()[1];
2401 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2402 myexponent = 0; // denormal
2403 if (myexponent2==1 && !(mysignificand2 & 0x10000000000000LL))
2404 myexponent2 = 0; // denormal
2405 } else if (category==fcZero) {
2410 } else if (category==fcInfinity) {
2416 assert(category == fcNaN && "Unknown category");
2418 mysignificand = significandParts()[0];
2419 myexponent2 = exponent2;
2420 mysignificand2 = significandParts()[1];
2424 words[0] = (((uint64_t)sign & 1) << 63) |
2425 ((myexponent & 0x7ff) << 52) |
2426 (mysignificand & 0xfffffffffffffLL);
2427 words[1] = (((uint64_t)sign2 & 1) << 63) |
2428 ((myexponent2 & 0x7ff) << 52) |
2429 (mysignificand2 & 0xfffffffffffffLL);
2430 return APInt(128, 2, words);
2434 APFloat::convertDoubleAPFloatToAPInt() const
2436 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble);
2437 assert (partCount()==1);
2439 uint64_t myexponent, mysignificand;
2441 if (category==fcNormal) {
2442 myexponent = exponent+1023; //bias
2443 mysignificand = *significandParts();
2444 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2445 myexponent = 0; // denormal
2446 } else if (category==fcZero) {
2449 } else if (category==fcInfinity) {
2453 assert(category == fcNaN && "Unknown category!");
2455 mysignificand = *significandParts();
2458 return APInt(64, (((((uint64_t)sign & 1) << 63) |
2459 ((myexponent & 0x7ff) << 52) |
2460 (mysignificand & 0xfffffffffffffLL))));
2464 APFloat::convertFloatAPFloatToAPInt() const
2466 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle);
2467 assert (partCount()==1);
2469 uint32_t myexponent, mysignificand;
2471 if (category==fcNormal) {
2472 myexponent = exponent+127; //bias
2473 mysignificand = *significandParts();
2474 if (myexponent == 1 && !(mysignificand & 0x400000))
2475 myexponent = 0; // denormal
2476 } else if (category==fcZero) {
2479 } else if (category==fcInfinity) {
2483 assert(category == fcNaN && "Unknown category!");
2485 mysignificand = *significandParts();
2488 return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) |
2489 (mysignificand & 0x7fffff)));
2492 // This function creates an APInt that is just a bit map of the floating
2493 // point constant as it would appear in memory. It is not a conversion,
2494 // and treating the result as a normal integer is unlikely to be useful.
2497 APFloat::convertToAPInt() const
2499 if (semantics == (const llvm::fltSemantics* const)&IEEEsingle)
2500 return convertFloatAPFloatToAPInt();
2502 if (semantics == (const llvm::fltSemantics* const)&IEEEdouble)
2503 return convertDoubleAPFloatToAPInt();
2505 if (semantics == (const llvm::fltSemantics* const)&PPCDoubleDouble)
2506 return convertPPCDoubleDoubleAPFloatToAPInt();
2508 assert(semantics == (const llvm::fltSemantics* const)&x87DoubleExtended &&
2510 return convertF80LongDoubleAPFloatToAPInt();
2514 APFloat::convertToFloat() const
2516 assert(semantics == (const llvm::fltSemantics* const)&IEEEsingle);
2517 APInt api = convertToAPInt();
2518 return api.bitsToFloat();
2522 APFloat::convertToDouble() const
2524 assert(semantics == (const llvm::fltSemantics* const)&IEEEdouble);
2525 APInt api = convertToAPInt();
2526 return api.bitsToDouble();
2529 /// Integer bit is explicit in this format. Current Intel book does not
2530 /// define meaning of:
2531 /// exponent = all 1's, integer bit not set.
2532 /// exponent = 0, integer bit set. (formerly "psuedodenormals")
2533 /// exponent!=0 nor all 1's, integer bit not set. (formerly "unnormals")
2535 APFloat::initFromF80LongDoubleAPInt(const APInt &api)
2537 assert(api.getBitWidth()==80);
2538 uint64_t i1 = api.getRawData()[0];
2539 uint64_t i2 = api.getRawData()[1];
2540 uint64_t myexponent = (i1 >> 48) & 0x7fff;
2541 uint64_t mysignificand = ((i1 << 16) & 0xffffffffffff0000ULL) |
2544 initialize(&APFloat::x87DoubleExtended);
2545 assert(partCount()==2);
2548 if (myexponent==0 && mysignificand==0) {
2549 // exponent, significand meaningless
2551 } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
2552 // exponent, significand meaningless
2553 category = fcInfinity;
2554 } else if (myexponent==0x7fff && mysignificand!=0x8000000000000000ULL) {
2555 // exponent meaningless
2557 significandParts()[0] = mysignificand;
2558 significandParts()[1] = 0;
2560 category = fcNormal;
2561 exponent = myexponent - 16383;
2562 significandParts()[0] = mysignificand;
2563 significandParts()[1] = 0;
2564 if (myexponent==0) // denormal
2570 APFloat::initFromPPCDoubleDoubleAPInt(const APInt &api)
2572 assert(api.getBitWidth()==128);
2573 uint64_t i1 = api.getRawData()[0];
2574 uint64_t i2 = api.getRawData()[1];
2575 uint64_t myexponent = (i1 >> 52) & 0x7ff;
2576 uint64_t mysignificand = i1 & 0xfffffffffffffLL;
2577 uint64_t myexponent2 = (i2 >> 52) & 0x7ff;
2578 uint64_t mysignificand2 = i2 & 0xfffffffffffffLL;
2580 initialize(&APFloat::PPCDoubleDouble);
2581 assert(partCount()==2);
2585 if (myexponent==0 && mysignificand==0) {
2586 // exponent, significand meaningless
2587 // exponent2 and significand2 are required to be 0; we don't check
2589 } else if (myexponent==0x7ff && mysignificand==0) {
2590 // exponent, significand meaningless
2591 // exponent2 and significand2 are required to be 0; we don't check
2592 category = fcInfinity;
2593 } else if (myexponent==0x7ff && mysignificand!=0) {
2594 // exponent meaningless. So is the whole second word, but keep it
2597 exponent2 = myexponent2;
2598 significandParts()[0] = mysignificand;
2599 significandParts()[1] = mysignificand2;
2601 category = fcNormal;
2602 // Note there is no category2; the second word is treated as if it is
2603 // fcNormal, although it might be something else considered by itself.
2604 exponent = myexponent - 1023;
2605 exponent2 = myexponent2 - 1023;
2606 significandParts()[0] = mysignificand;
2607 significandParts()[1] = mysignificand2;
2608 if (myexponent==0) // denormal
2611 significandParts()[0] |= 0x10000000000000LL; // integer bit
2615 significandParts()[1] |= 0x10000000000000LL; // integer bit
2620 APFloat::initFromDoubleAPInt(const APInt &api)
2622 assert(api.getBitWidth()==64);
2623 uint64_t i = *api.getRawData();
2624 uint64_t myexponent = (i >> 52) & 0x7ff;
2625 uint64_t mysignificand = i & 0xfffffffffffffLL;
2627 initialize(&APFloat::IEEEdouble);
2628 assert(partCount()==1);
2631 if (myexponent==0 && mysignificand==0) {
2632 // exponent, significand meaningless
2634 } else if (myexponent==0x7ff && mysignificand==0) {
2635 // exponent, significand meaningless
2636 category = fcInfinity;
2637 } else if (myexponent==0x7ff && mysignificand!=0) {
2638 // exponent meaningless
2640 *significandParts() = mysignificand;
2642 category = fcNormal;
2643 exponent = myexponent - 1023;
2644 *significandParts() = mysignificand;
2645 if (myexponent==0) // denormal
2648 *significandParts() |= 0x10000000000000LL; // integer bit
2653 APFloat::initFromFloatAPInt(const APInt & api)
2655 assert(api.getBitWidth()==32);
2656 uint32_t i = (uint32_t)*api.getRawData();
2657 uint32_t myexponent = (i >> 23) & 0xff;
2658 uint32_t mysignificand = i & 0x7fffff;
2660 initialize(&APFloat::IEEEsingle);
2661 assert(partCount()==1);
2664 if (myexponent==0 && mysignificand==0) {
2665 // exponent, significand meaningless
2667 } else if (myexponent==0xff && mysignificand==0) {
2668 // exponent, significand meaningless
2669 category = fcInfinity;
2670 } else if (myexponent==0xff && mysignificand!=0) {
2671 // sign, exponent, significand meaningless
2673 *significandParts() = mysignificand;
2675 category = fcNormal;
2676 exponent = myexponent - 127; //bias
2677 *significandParts() = mysignificand;
2678 if (myexponent==0) // denormal
2681 *significandParts() |= 0x800000; // integer bit
2685 /// Treat api as containing the bits of a floating point number. Currently
2686 /// we infer the floating point type from the size of the APInt. The
2687 /// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful
2688 /// when the size is anything else).
2690 APFloat::initFromAPInt(const APInt& api, bool isIEEE)
2692 if (api.getBitWidth() == 32)
2693 return initFromFloatAPInt(api);
2694 else if (api.getBitWidth()==64)
2695 return initFromDoubleAPInt(api);
2696 else if (api.getBitWidth()==80)
2697 return initFromF80LongDoubleAPInt(api);
2698 else if (api.getBitWidth()==128 && !isIEEE)
2699 return initFromPPCDoubleDoubleAPInt(api);
2704 APFloat::APFloat(const APInt& api, bool isIEEE)
2706 initFromAPInt(api, isIEEE);
2709 APFloat::APFloat(float f)
2711 APInt api = APInt(32, 0);
2712 initFromAPInt(api.floatToBits(f));
2715 APFloat::APFloat(double d)
2717 APInt api = APInt(64, 0);
2718 initFromAPInt(api.doubleToBits(d));