LLVM API Documentation

APFloat.cpp

Go to the documentation of this file.
00001 //===-- APFloat.cpp - Implement APFloat class -----------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements a class to represent arbitrary precision floating
00011 // point values and provide a variety of arithmetic operations on them.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/ADT/APFloat.h"
00016 #include "llvm/ADT/FoldingSet.h"
00017 #include "llvm/Support/MathExtras.h"
00018 #include <cstring>
00019 
00020 using namespace llvm;
00021 
00022 #define convolve(lhs, rhs) ((lhs) * 4 + (rhs))
00023 
00024 /* Assumed in hexadecimal significand parsing, and conversion to
00025    hexadecimal strings.  */
00026 #define COMPILE_TIME_ASSERT(cond) extern int CTAssert[(cond) ? 1 : -1]
00027 COMPILE_TIME_ASSERT(integerPartWidth % 4 == 0);
00028 
00029 namespace llvm {
00030 
00031   /* Represents floating point arithmetic semantics.  */
00032   struct fltSemantics {
00033     /* The largest E such that 2^E is representable; this matches the
00034        definition of IEEE 754.  */
00035     exponent_t maxExponent;
00036 
00037     /* The smallest E such that 2^E is a normalized number; this
00038        matches the definition of IEEE 754.  */
00039     exponent_t minExponent;
00040 
00041     /* Number of bits in the significand.  This includes the integer
00042        bit.  */
00043     unsigned int precision;
00044 
00045     /* True if arithmetic is supported.  */
00046     unsigned int arithmeticOK;
00047   };
00048 
00049   const fltSemantics APFloat::IEEEsingle = { 127, -126, 24, true };
00050   const fltSemantics APFloat::IEEEdouble = { 1023, -1022, 53, true };
00051   const fltSemantics APFloat::IEEEquad = { 16383, -16382, 113, true };
00052   const fltSemantics APFloat::x87DoubleExtended = { 16383, -16382, 64, true };
00053   const fltSemantics APFloat::Bogus = { 0, 0, 0, true };
00054 
00055   // The PowerPC format consists of two doubles.  It does not map cleanly
00056   // onto the usual format above.  For now only storage of constants of
00057   // this type is supported, no arithmetic.
00058   const fltSemantics APFloat::PPCDoubleDouble = { 1023, -1022, 106, false };
00059 
00060   /* A tight upper bound on number of parts required to hold the value
00061      pow(5, power) is
00062 
00063        power * 815 / (351 * integerPartWidth) + 1
00064        
00065      However, whilst the result may require only this many parts,
00066      because we are multiplying two values to get it, the
00067      multiplication may require an extra part with the excess part
00068      being zero (consider the trivial case of 1 * 1, tcFullMultiply
00069      requires two parts to hold the single-part result).  So we add an
00070      extra one to guarantee enough space whilst multiplying.  */
00071   const unsigned int maxExponent = 16383;
00072   const unsigned int maxPrecision = 113;
00073   const unsigned int maxPowerOfFiveExponent = maxExponent + maxPrecision - 1;
00074   const unsigned int maxPowerOfFiveParts = 2 + ((maxPowerOfFiveExponent * 815)
00075                                                 / (351 * integerPartWidth));
00076 }
00077 
00078 /* Put a bunch of private, handy routines in an anonymous namespace.  */
00079 namespace {
00080 
00081   static inline unsigned int
00082   partCountForBits(unsigned int bits)
00083   {
00084     return ((bits) + integerPartWidth - 1) / integerPartWidth;
00085   }
00086 
00087   /* Returns 0U-9U.  Return values >= 10U are not digits.  */
00088   static inline unsigned int
00089   decDigitValue(unsigned int c)
00090   {
00091     return c - '0';
00092   }
00093 
00094   static unsigned int
00095   hexDigitValue(unsigned int c)
00096   {
00097     unsigned int r;
00098 
00099     r = c - '0';
00100     if(r <= 9)
00101       return r;
00102 
00103     r = c - 'A';
00104     if(r <= 5)
00105       return r + 10;
00106 
00107     r = c - 'a';
00108     if(r <= 5)
00109       return r + 10;
00110 
00111     return -1U;
00112   }
00113 
00114   static inline void
00115   assertArithmeticOK(const llvm::fltSemantics &semantics) {
00116     assert(semantics.arithmeticOK
00117            && "Compile-time arithmetic does not support these semantics");
00118   }
00119 
00120   /* Return the value of a decimal exponent of the form
00121      [+-]ddddddd.
00122 
00123      If the exponent overflows, returns a large exponent with the
00124      appropriate sign.  */
00125   static int
00126   readExponent(const char *p)
00127   {
00128     bool isNegative;
00129     unsigned int absExponent;
00130     const unsigned int overlargeExponent = 24000;  /* FIXME.  */
00131 
00132     isNegative = (*p == '-');
00133     if (*p == '-' || *p == '+')
00134       p++;
00135 
00136     absExponent = decDigitValue(*p++);
00137     assert (absExponent < 10U);
00138 
00139     for (;;) {
00140       unsigned int value;
00141 
00142       value = decDigitValue(*p);
00143       if (value >= 10U)
00144         break;
00145 
00146       p++;
00147       value += absExponent * 10;
00148       if (absExponent >= overlargeExponent) {
00149         absExponent = overlargeExponent;
00150         break;
00151       }
00152       absExponent = value;
00153     }
00154 
00155     if (isNegative)
00156       return -(int) absExponent;
00157     else
00158       return (int) absExponent;
00159   }
00160 
00161   /* This is ugly and needs cleaning up, but I don't immediately see
00162      how whilst remaining safe.  */
00163   static int
00164   totalExponent(const char *p, int exponentAdjustment)
00165   {
00166     int unsignedExponent;
00167     bool negative, overflow;
00168     int exponent;
00169 
00170     /* Move past the exponent letter and sign to the digits.  */
00171     p++;
00172     negative = *p == '-';
00173     if(*p == '-' || *p == '+')
00174       p++;
00175 
00176     unsignedExponent = 0;
00177     overflow = false;
00178     for(;;) {
00179       unsigned int value;
00180 
00181       value = decDigitValue(*p);
00182       if(value >= 10U)
00183         break;
00184 
00185       p++;
00186       unsignedExponent = unsignedExponent * 10 + value;
00187       if(unsignedExponent > 65535)
00188         overflow = true;
00189     }
00190 
00191     if(exponentAdjustment > 65535 || exponentAdjustment < -65536)
00192       overflow = true;
00193 
00194     if(!overflow) {
00195       exponent = unsignedExponent;
00196       if(negative)
00197         exponent = -exponent;
00198       exponent += exponentAdjustment;
00199       if(exponent > 65535 || exponent < -65536)
00200         overflow = true;
00201     }
00202 
00203     if(overflow)
00204       exponent = negative ? -65536: 65535;
00205 
00206     return exponent;
00207   }
00208 
00209   static const char *
00210   skipLeadingZeroesAndAnyDot(const char *p, const char **dot)
00211   {
00212     *dot = 0;
00213     while(*p == '0')
00214       p++;
00215 
00216     if(*p == '.') {
00217       *dot = p++;
00218       while(*p == '0')
00219         p++;
00220     }
00221 
00222     return p;
00223   }
00224 
00225   /* Given a normal decimal floating point number of the form
00226 
00227        dddd.dddd[eE][+-]ddd
00228 
00229      where the decimal point and exponent are optional, fill out the
00230      structure D.  Exponent is appropriate if the significand is
00231      treated as an integer, and normalizedExponent if the significand
00232      is taken to have the decimal point after a single leading
00233      non-zero digit.
00234 
00235      If the value is zero, V->firstSigDigit points to a non-digit, and
00236      the return exponent is zero.
00237   */
00238   struct decimalInfo {
00239     const char *firstSigDigit;
00240     const char *lastSigDigit;
00241     int exponent;
00242     int normalizedExponent;
00243   };
00244 
00245   static void
00246   interpretDecimal(const char *p, decimalInfo *D)
00247   {
00248     const char *dot;
00249 
00250     p = skipLeadingZeroesAndAnyDot (p, &dot);
00251 
00252     D->firstSigDigit = p;
00253     D->exponent = 0;
00254     D->normalizedExponent = 0;
00255 
00256     for (;;) {
00257       if (*p == '.') {
00258         assert(dot == 0);
00259         dot = p++;
00260       }
00261       if (decDigitValue(*p) >= 10U)
00262         break;
00263       p++;
00264     }
00265 
00266     /* If number is all zerooes accept any exponent.  */
00267     if (p != D->firstSigDigit) {
00268       if (*p == 'e' || *p == 'E')
00269         D->exponent = readExponent(p + 1);
00270 
00271       /* Implied decimal point?  */
00272       if (!dot)
00273         dot = p;
00274 
00275       /* Drop insignificant trailing zeroes.  */
00276       do
00277         do
00278           p--;
00279         while (*p == '0');
00280       while (*p == '.');
00281 
00282       /* Adjust the exponents for any decimal point.  */
00283       D->exponent += static_cast<exponent_t>((dot - p) - (dot > p));
00284       D->normalizedExponent = (D->exponent +
00285                 static_cast<exponent_t>((p - D->firstSigDigit)
00286                                         - (dot > D->firstSigDigit && dot < p)));
00287     }
00288 
00289     D->lastSigDigit = p;
00290   }
00291 
00292   /* Return the trailing fraction of a hexadecimal number.
00293      DIGITVALUE is the first hex digit of the fraction, P points to
00294      the next digit.  */
00295   static lostFraction
00296   trailingHexadecimalFraction(const char *p, unsigned int digitValue)
00297   {
00298     unsigned int hexDigit;
00299 
00300     /* If the first trailing digit isn't 0 or 8 we can work out the
00301        fraction immediately.  */
00302     if(digitValue > 8)
00303       return lfMoreThanHalf;
00304     else if(digitValue < 8 && digitValue > 0)
00305       return lfLessThanHalf;
00306 
00307     /* Otherwise we need to find the first non-zero digit.  */
00308     while(*p == '0')
00309       p++;
00310 
00311     hexDigit = hexDigitValue(*p);
00312 
00313     /* If we ran off the end it is exactly zero or one-half, otherwise
00314        a little more.  */
00315     if(hexDigit == -1U)
00316       return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
00317     else
00318       return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf;
00319   }
00320 
00321   /* Return the fraction lost were a bignum truncated losing the least
00322      significant BITS bits.  */
00323   static lostFraction
00324   lostFractionThroughTruncation(const integerPart *parts,
00325                                 unsigned int partCount,
00326                                 unsigned int bits)
00327   {
00328     unsigned int lsb;
00329 
00330     lsb = APInt::tcLSB(parts, partCount);
00331 
00332     /* Note this is guaranteed true if bits == 0, or LSB == -1U.  */
00333     if(bits <= lsb)
00334       return lfExactlyZero;
00335     if(bits == lsb + 1)
00336       return lfExactlyHalf;
00337     if(bits <= partCount * integerPartWidth
00338        && APInt::tcExtractBit(parts, bits - 1))
00339       return lfMoreThanHalf;
00340 
00341     return lfLessThanHalf;
00342   }
00343 
00344   /* Shift DST right BITS bits noting lost fraction.  */
00345   static lostFraction
00346   shiftRight(integerPart *dst, unsigned int parts, unsigned int bits)
00347   {
00348     lostFraction lost_fraction;
00349 
00350     lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
00351 
00352     APInt::tcShiftRight(dst, parts, bits);
00353 
00354     return lost_fraction;
00355   }
00356 
00357   /* Combine the effect of two lost fractions.  */
00358   static lostFraction
00359   combineLostFractions(lostFraction moreSignificant,
00360                        lostFraction lessSignificant)
00361   {
00362     if(lessSignificant != lfExactlyZero) {
00363       if(moreSignificant == lfExactlyZero)
00364         moreSignificant = lfLessThanHalf;
00365       else if(moreSignificant == lfExactlyHalf)
00366         moreSignificant = lfMoreThanHalf;
00367     }
00368 
00369     return moreSignificant;
00370   }
00371 
00372   /* The error from the true value, in half-ulps, on multiplying two
00373      floating point numbers, which differ from the value they
00374      approximate by at most HUE1 and HUE2 half-ulps, is strictly less
00375      than the returned value.
00376 
00377      See "How to Read Floating Point Numbers Accurately" by William D
00378      Clinger.  */
00379   static unsigned int
00380   HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
00381   {
00382     assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
00383 
00384     if (HUerr1 + HUerr2 == 0)
00385       return inexactMultiply * 2;  /* <= inexactMultiply half-ulps.  */
00386     else
00387       return inexactMultiply + 2 * (HUerr1 + HUerr2);
00388   }
00389 
00390   /* The number of ulps from the boundary (zero, or half if ISNEAREST)
00391      when the least significant BITS are truncated.  BITS cannot be
00392      zero.  */
00393   static integerPart
00394   ulpsFromBoundary(const integerPart *parts, unsigned int bits, bool isNearest)
00395   {
00396     unsigned int count, partBits;
00397     integerPart part, boundary;
00398 
00399     assert (bits != 0);
00400 
00401     bits--;
00402     count = bits / integerPartWidth;
00403     partBits = bits % integerPartWidth + 1;
00404 
00405     part = parts[count] & (~(integerPart) 0 >> (integerPartWidth - partBits));
00406 
00407     if (isNearest)
00408       boundary = (integerPart) 1 << (partBits - 1);
00409     else
00410       boundary = 0;
00411 
00412     if (count == 0) {
00413       if (part - boundary <= boundary - part)
00414         return part - boundary;
00415       else
00416         return boundary - part;
00417     }
00418 
00419     if (part == boundary) {
00420       while (--count)
00421         if (parts[count])
00422           return ~(integerPart) 0; /* A lot.  */
00423 
00424       return parts[0];
00425     } else if (part == boundary - 1) {
00426       while (--count)
00427         if (~parts[count])
00428           return ~(integerPart) 0; /* A lot.  */
00429 
00430       return -parts[0];
00431     }
00432 
00433     return ~(integerPart) 0; /* A lot.  */
00434   }
00435 
00436   /* Place pow(5, power) in DST, and return the number of parts used.
00437      DST must be at least one part larger than size of the answer.  */
00438   static unsigned int
00439   powerOf5(integerPart *dst, unsigned int power)
00440   {
00441     static const integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125,
00442                                                     15625, 78125 };
00443     static integerPart pow5s[maxPowerOfFiveParts * 2 + 5] = { 78125 * 5 };
00444     static unsigned int partsCount[16] = { 1 };
00445 
00446     integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5;
00447     unsigned int result;
00448 
00449     assert(power <= maxExponent);
00450 
00451     p1 = dst;
00452     p2 = scratch;
00453 
00454     *p1 = firstEightPowers[power & 7];
00455     power >>= 3;
00456 
00457     result = 1;
00458     pow5 = pow5s;
00459 
00460     for (unsigned int n = 0; power; power >>= 1, n++) {
00461       unsigned int pc;
00462 
00463       pc = partsCount[n];
00464 
00465       /* Calculate pow(5,pow(2,n+3)) if we haven't yet.  */
00466       if (pc == 0) {
00467         pc = partsCount[n - 1];
00468         APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc);
00469         pc *= 2;
00470         if (pow5[pc - 1] == 0)
00471           pc--;
00472         partsCount[n] = pc;
00473       }
00474 
00475       if (power & 1) {
00476         integerPart *tmp;
00477 
00478         APInt::tcFullMultiply(p2, p1, pow5, result, pc);
00479         result += pc;
00480         if (p2[result - 1] == 0)
00481           result--;
00482 
00483         /* Now result is in p1 with partsCount parts and p2 is scratch
00484            space.  */
00485         tmp = p1, p1 = p2, p2 = tmp;
00486       }
00487 
00488       pow5 += pc;
00489     }
00490 
00491     if (p1 != dst)
00492       APInt::tcAssign(dst, p1, result);
00493 
00494     return result;
00495   }
00496 
00497   /* Zero at the end to avoid modular arithmetic when adding one; used
00498      when rounding up during hexadecimal output.  */
00499   static const char hexDigitsLower[] = "0123456789abcdef0";
00500   static const char hexDigitsUpper[] = "0123456789ABCDEF0";
00501   static const char infinityL[] = "infinity";
00502   static const char infinityU[] = "INFINITY";
00503   static const char NaNL[] = "nan";
00504   static const char NaNU[] = "NAN";
00505 
00506   /* Write out an integerPart in hexadecimal, starting with the most
00507      significant nibble.  Write out exactly COUNT hexdigits, return
00508      COUNT.  */
00509   static unsigned int
00510   partAsHex (char *dst, integerPart part, unsigned int count,
00511              const char *hexDigitChars)
00512   {
00513     unsigned int result = count;
00514 
00515     assert (count != 0 && count <= integerPartWidth / 4);
00516 
00517     part >>= (integerPartWidth - 4 * count);
00518     while (count--) {
00519       dst[count] = hexDigitChars[part & 0xf];
00520       part >>= 4;
00521     }
00522 
00523     return result;
00524   }
00525 
00526   /* Write out an unsigned decimal integer.  */
00527   static char *
00528   writeUnsignedDecimal (char *dst, unsigned int n)
00529   {
00530     char buff[40], *p;
00531 
00532     p = buff;
00533     do
00534       *p++ = '0' + n % 10;
00535     while (n /= 10);
00536 
00537     do
00538       *dst++ = *--p;
00539     while (p != buff);
00540 
00541     return dst;
00542   }
00543 
00544   /* Write out a signed decimal integer.  */
00545   static char *
00546   writeSignedDecimal (char *dst, int value)
00547   {
00548     if (value < 0) {
00549       *dst++ = '-';
00550       dst = writeUnsignedDecimal(dst, -(unsigned) value);
00551     } else
00552       dst = writeUnsignedDecimal(dst, value);
00553 
00554     return dst;
00555   }
00556 }
00557 
00558 /* Constructors.  */
00559 void
00560 APFloat::initialize(const fltSemantics *ourSemantics)
00561 {
00562   unsigned int count;
00563 
00564   semantics = ourSemantics;
00565   count = partCount();
00566   if(count > 1)
00567     significand.parts = new integerPart[count];
00568 }
00569 
00570 void
00571 APFloat::freeSignificand()
00572 {
00573   if(partCount() > 1)
00574     delete [] significand.parts;
00575 }
00576 
00577 void
00578 APFloat::assign(const APFloat &rhs)
00579 {
00580   assert(semantics == rhs.semantics);
00581 
00582   sign = rhs.sign;
00583   category = rhs.category;
00584   exponent = rhs.exponent;
00585   sign2 = rhs.sign2;
00586   exponent2 = rhs.exponent2;
00587   if(category == fcNormal || category == fcNaN)
00588     copySignificand(rhs);
00589 }
00590 
00591 void
00592 APFloat::copySignificand(const APFloat &rhs)
00593 {
00594   assert(category == fcNormal || category == fcNaN);
00595   assert(rhs.partCount() >= partCount());
00596 
00597   APInt::tcAssign(significandParts(), rhs.significandParts(),
00598                   partCount());
00599 }
00600 
00601 /* Make this number a NaN, with an arbitrary but deterministic value
00602    for the significand.  If double or longer, this is a signalling NaN,
00603    which may not be ideal. */
00604 void
00605 APFloat::makeNaN(void)
00606 {
00607   category = fcNaN;
00608   APInt::tcSet(significandParts(), ~0U, partCount());
00609 }
00610 
00611 APFloat &
00612 APFloat::operator=(const APFloat &rhs)
00613 {
00614   if(this != &rhs) {
00615     if(semantics != rhs.semantics) {
00616       freeSignificand();
00617       initialize(rhs.semantics);
00618     }
00619     assign(rhs);
00620   }
00621 
00622   return *this;
00623 }
00624 
00625 bool
00626 APFloat::bitwiseIsEqual(const APFloat &rhs) const {
00627   if (this == &rhs)
00628     return true;
00629   if (semantics != rhs.semantics ||
00630       category != rhs.category ||
00631       sign != rhs.sign)
00632     return false;
00633   if (semantics==(const llvm::fltSemantics*)&PPCDoubleDouble &&
00634       sign2 != rhs.sign2)
00635     return false;
00636   if (category==fcZero || category==fcInfinity)
00637     return true;
00638   else if (category==fcNormal && exponent!=rhs.exponent)
00639     return false;
00640   else if (semantics==(const llvm::fltSemantics*)&PPCDoubleDouble &&
00641            exponent2!=rhs.exponent2)
00642     return false;
00643   else {
00644     int i= partCount();
00645     const integerPart* p=significandParts();
00646     const integerPart* q=rhs.significandParts();
00647     for (; i>0; i--, p++, q++) {
00648       if (*p != *q)
00649         return false;
00650     }
00651     return true;
00652   }
00653 }
00654 
00655 APFloat::APFloat(const fltSemantics &ourSemantics, integerPart value)
00656 {
00657   assertArithmeticOK(ourSemantics);
00658   initialize(&ourSemantics);
00659   sign = 0;
00660   zeroSignificand();
00661   exponent = ourSemantics.precision - 1;
00662   significandParts()[0] = value;
00663   normalize(rmNearestTiesToEven, lfExactlyZero);
00664 }
00665 
00666 APFloat::APFloat(const fltSemantics &ourSemantics,
00667                  fltCategory ourCategory, bool negative)
00668 {
00669   assertArithmeticOK(ourSemantics);
00670   initialize(&ourSemantics);
00671   category = ourCategory;
00672   sign = negative;
00673   if(category == fcNormal)
00674     category = fcZero;
00675   else if (ourCategory == fcNaN)
00676     makeNaN();
00677 }
00678 
00679 APFloat::APFloat(const fltSemantics &ourSemantics, const char *text)
00680 {
00681   assertArithmeticOK(ourSemantics);
00682   initialize(&ourSemantics);
00683   convertFromString(text, rmNearestTiesToEven);
00684 }
00685 
00686 APFloat::APFloat(const APFloat &rhs)
00687 {
00688   initialize(rhs.semantics);
00689   assign(rhs);
00690 }
00691 
00692 APFloat::~APFloat()
00693 {
00694   freeSignificand();
00695 }
00696 
00697 // Profile - This method 'profiles' an APFloat for use with FoldingSet.
00698 void APFloat::Profile(FoldingSetNodeID& ID) const {
00699   ID.Add(bitcastToAPInt());
00700 }
00701 
00702 unsigned int
00703 APFloat::partCount() const
00704 {
00705   return partCountForBits(semantics->precision + 1);
00706 }
00707 
00708 unsigned int
00709 APFloat::semanticsPrecision(const fltSemantics &semantics)
00710 {
00711   return semantics.precision;
00712 }
00713 
00714 const integerPart *
00715 APFloat::significandParts() const
00716 {
00717   return const_cast<APFloat *>(this)->significandParts();
00718 }
00719 
00720 integerPart *
00721 APFloat::significandParts()
00722 {
00723   assert(category == fcNormal || category == fcNaN);
00724 
00725   if(partCount() > 1)
00726     return significand.parts;
00727   else
00728     return &significand.part;
00729 }
00730 
00731 void
00732 APFloat::zeroSignificand()
00733 {
00734   category = fcNormal;
00735   APInt::tcSet(significandParts(), 0, partCount());
00736 }
00737 
00738 /* Increment an fcNormal floating point number's significand.  */
00739 void
00740 APFloat::incrementSignificand()
00741 {
00742   integerPart carry;
00743 
00744   carry = APInt::tcIncrement(significandParts(), partCount());
00745 
00746   /* Our callers should never cause us to overflow.  */
00747   assert(carry == 0);
00748 }
00749 
00750 /* Add the significand of the RHS.  Returns the carry flag.  */
00751 integerPart
00752 APFloat::addSignificand(const APFloat &rhs)
00753 {
00754   integerPart *parts;
00755 
00756   parts = significandParts();
00757 
00758   assert(semantics == rhs.semantics);
00759   assert(exponent == rhs.exponent);
00760 
00761   return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
00762 }
00763 
00764 /* Subtract the significand of the RHS with a borrow flag.  Returns
00765    the borrow flag.  */
00766 integerPart
00767 APFloat::subtractSignificand(const APFloat &rhs, integerPart borrow)
00768 {
00769   integerPart *parts;
00770 
00771   parts = significandParts();
00772 
00773   assert(semantics == rhs.semantics);
00774   assert(exponent == rhs.exponent);
00775 
00776   return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
00777                            partCount());
00778 }
00779 
00780 /* Multiply the significand of the RHS.  If ADDEND is non-NULL, add it
00781    on to the full-precision result of the multiplication.  Returns the
00782    lost fraction.  */
00783 lostFraction
00784 APFloat::multiplySignificand(const APFloat &rhs, const APFloat *addend)
00785 {
00786   unsigned int omsb;        // One, not zero, based MSB.
00787   unsigned int partsCount, newPartsCount, precision;
00788   integerPart *lhsSignificand;
00789   integerPart scratch[4];
00790   integerPart *fullSignificand;
00791   lostFraction lost_fraction;
00792   bool ignored;
00793 
00794   assert(semantics == rhs.semantics);
00795 
00796   precision = semantics->precision;
00797   newPartsCount = partCountForBits(precision * 2);
00798 
00799   if(newPartsCount > 4)
00800     fullSignificand = new integerPart[newPartsCount];
00801   else
00802     fullSignificand = scratch;
00803 
00804   lhsSignificand = significandParts();
00805   partsCount = partCount();
00806 
00807   APInt::tcFullMultiply(fullSignificand, lhsSignificand,
00808                         rhs.significandParts(), partsCount, partsCount);
00809 
00810   lost_fraction = lfExactlyZero;
00811   omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
00812   exponent += rhs.exponent;
00813 
00814   if(addend) {
00815     Significand savedSignificand = significand;
00816     const fltSemantics *savedSemantics = semantics;
00817     fltSemantics extendedSemantics;
00818     opStatus status;
00819     unsigned int extendedPrecision;
00820 
00821     /* Normalize our MSB.  */
00822     extendedPrecision = precision + precision - 1;
00823     if(omsb != extendedPrecision)
00824       {
00825         APInt::tcShiftLeft(fullSignificand, newPartsCount,
00826                            extendedPrecision - omsb);
00827         exponent -= extendedPrecision - omsb;
00828       }
00829 
00830     /* Create new semantics.  */
00831     extendedSemantics = *semantics;
00832     extendedSemantics.precision = extendedPrecision;
00833 
00834     if(newPartsCount == 1)
00835       significand.part = fullSignificand[0];
00836     else
00837       significand.parts = fullSignificand;
00838     semantics = &extendedSemantics;
00839 
00840     APFloat extendedAddend(*addend);
00841     status = extendedAddend.convert(extendedSemantics, rmTowardZero, &ignored);
00842     assert(status == opOK);
00843     lost_fraction = addOrSubtractSignificand(extendedAddend, false);
00844 
00845     /* Restore our state.  */
00846     if(newPartsCount == 1)
00847       fullSignificand[0] = significand.part;
00848     significand = savedSignificand;
00849     semantics = savedSemantics;
00850 
00851     omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
00852   }
00853 
00854   exponent -= (precision - 1);
00855 
00856   if(omsb > precision) {
00857     unsigned int bits, significantParts;
00858     lostFraction lf;
00859 
00860     bits = omsb - precision;
00861     significantParts = partCountForBits(omsb);
00862     lf = shiftRight(fullSignificand, significantParts, bits);
00863     lost_fraction = combineLostFractions(lf, lost_fraction);
00864     exponent += bits;
00865   }
00866 
00867   APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
00868 
00869   if(newPartsCount > 4)
00870     delete [] fullSignificand;
00871 
00872   return lost_fraction;
00873 }
00874 
00875 /* Multiply the significands of LHS and RHS to DST.  */
00876 lostFraction
00877 APFloat::divideSignificand(const APFloat &rhs)
00878 {
00879   unsigned int bit, i, partsCount;
00880   const integerPart *rhsSignificand;
00881   integerPart *lhsSignificand, *dividend, *divisor;
00882   integerPart scratch[4];
00883   lostFraction lost_fraction;
00884 
00885   assert(semantics == rhs.semantics);
00886 
00887   lhsSignificand = significandParts();
00888   rhsSignificand = rhs.significandParts();
00889   partsCount = partCount();
00890 
00891   if(partsCount > 2)
00892     dividend = new integerPart[partsCount * 2];
00893   else
00894     dividend = scratch;
00895 
00896   divisor = dividend + partsCount;
00897 
00898   /* Copy the dividend and divisor as they will be modified in-place.  */
00899   for(i = 0; i < partsCount; i++) {
00900     dividend[i] = lhsSignificand[i];
00901     divisor[i] = rhsSignificand[i];
00902     lhsSignificand[i] = 0;
00903   }
00904 
00905   exponent -= rhs.exponent;
00906 
00907   unsigned int precision = semantics->precision;
00908 
00909   /* Normalize the divisor.  */
00910   bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
00911   if(bit) {
00912     exponent += bit;
00913     APInt::tcShiftLeft(divisor, partsCount, bit);
00914   }
00915 
00916   /* Normalize the dividend.  */
00917   bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
00918   if(bit) {
00919     exponent -= bit;
00920     APInt::tcShiftLeft(dividend, partsCount, bit);
00921   }
00922 
00923   /* Ensure the dividend >= divisor initially for the loop below.
00924      Incidentally, this means that the division loop below is
00925      guaranteed to set the integer bit to one.  */
00926   if(APInt::tcCompare(dividend, divisor, partsCount) < 0) {
00927     exponent--;
00928     APInt::tcShiftLeft(dividend, partsCount, 1);
00929     assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
00930   }
00931 
00932   /* Long division.  */
00933   for(bit = precision; bit; bit -= 1) {
00934     if(APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
00935       APInt::tcSubtract(dividend, divisor, 0, partsCount);
00936       APInt::tcSetBit(lhsSignificand, bit - 1);
00937     }
00938 
00939     APInt::tcShiftLeft(dividend, partsCount, 1);
00940   }
00941 
00942   /* Figure out the lost fraction.  */
00943   int cmp = APInt::tcCompare(dividend, divisor, partsCount);
00944 
00945   if(cmp > 0)
00946     lost_fraction = lfMoreThanHalf;
00947   else if(cmp == 0)
00948     lost_fraction = lfExactlyHalf;
00949   else if(APInt::tcIsZero(dividend, partsCount))
00950     lost_fraction = lfExactlyZero;
00951   else
00952     lost_fraction = lfLessThanHalf;
00953 
00954   if(partsCount > 2)
00955     delete [] dividend;
00956 
00957   return lost_fraction;
00958 }
00959 
00960 unsigned int
00961 APFloat::significandMSB() const
00962 {
00963   return APInt::tcMSB(significandParts(), partCount());
00964 }
00965 
00966 unsigned int
00967 APFloat::significandLSB() const
00968 {
00969   return APInt::tcLSB(significandParts(), partCount());
00970 }
00971 
00972 /* Note that a zero result is NOT normalized to fcZero.  */
00973 lostFraction
00974 APFloat::shiftSignificandRight(unsigned int bits)
00975 {
00976   /* Our exponent should not overflow.  */
00977   assert((exponent_t) (exponent + bits) >= exponent);
00978 
00979   exponent += bits;
00980 
00981   return shiftRight(significandParts(), partCount(), bits);
00982 }
00983 
00984 /* Shift the significand left BITS bits, subtract BITS from its exponent.  */
00985 void
00986 APFloat::shiftSignificandLeft(unsigned int bits)
00987 {
00988   assert(bits < semantics->precision);
00989 
00990   if(bits) {
00991     unsigned int partsCount = partCount();
00992 
00993     APInt::tcShiftLeft(significandParts(), partsCount, bits);
00994     exponent -= bits;
00995 
00996     assert(!APInt::tcIsZero(significandParts(), partsCount));
00997   }
00998 }
00999 
01000 APFloat::cmpResult
01001 APFloat::compareAbsoluteValue(const APFloat &rhs) const
01002 {
01003   int compare;
01004 
01005   assert(semantics == rhs.semantics);
01006   assert(category == fcNormal);
01007   assert(rhs.category == fcNormal);
01008 
01009   compare = exponent - rhs.exponent;
01010 
01011   /* If exponents are equal, do an unsigned bignum comparison of the
01012      significands.  */
01013   if(compare == 0)
01014     compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
01015                                partCount());
01016 
01017   if(compare > 0)
01018     return cmpGreaterThan;
01019   else if(compare < 0)
01020     return cmpLessThan;
01021   else
01022     return cmpEqual;
01023 }
01024 
01025 /* Handle overflow.  Sign is preserved.  We either become infinity or
01026    the largest finite number.  */
01027 APFloat::opStatus
01028 APFloat::handleOverflow(roundingMode rounding_mode)
01029 {
01030   /* Infinity?  */
01031   if(rounding_mode == rmNearestTiesToEven
01032      || rounding_mode == rmNearestTiesToAway
01033      || (rounding_mode == rmTowardPositive && !sign)
01034      || (rounding_mode == rmTowardNegative && sign))
01035     {
01036       category = fcInfinity;
01037       return (opStatus) (opOverflow | opInexact);
01038     }
01039 
01040   /* Otherwise we become the largest finite number.  */
01041   category = fcNormal;
01042   exponent = semantics->maxExponent;
01043   APInt::tcSetLeastSignificantBits(significandParts(), partCount(),
01044                                    semantics->precision);
01045 
01046   return opInexact;
01047 }
01048 
01049 /* Returns TRUE if, when truncating the current number, with BIT the
01050    new LSB, with the given lost fraction and rounding mode, the result
01051    would need to be rounded away from zero (i.e., by increasing the
01052    signficand).  This routine must work for fcZero of both signs, and
01053    fcNormal numbers.  */
01054 bool
01055 APFloat::roundAwayFromZero(roundingMode rounding_mode,
01056                            lostFraction lost_fraction,
01057                            unsigned int bit) const
01058 {
01059   /* NaNs and infinities should not have lost fractions.  */
01060   assert(category == fcNormal || category == fcZero);
01061 
01062   /* Current callers never pass this so we don't handle it.  */
01063   assert(lost_fraction != lfExactlyZero);
01064 
01065   switch(rounding_mode) {
01066   default:
01067     assert(0);
01068 
01069   case rmNearestTiesToAway:
01070     return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
01071 
01072   case rmNearestTiesToEven:
01073     if(lost_fraction == lfMoreThanHalf)
01074       return true;
01075 
01076     /* Our zeroes don't have a significand to test.  */
01077     if(lost_fraction == lfExactlyHalf && category != fcZero)
01078       return APInt::tcExtractBit(significandParts(), bit);
01079 
01080     return false;
01081 
01082   case rmTowardZero:
01083     return false;
01084 
01085   case rmTowardPositive:
01086     return sign == false;
01087 
01088   case rmTowardNegative:
01089     return sign == true;
01090   }
01091 }
01092 
01093 APFloat::opStatus
01094 APFloat::normalize(roundingMode rounding_mode,
01095                    lostFraction lost_fraction)
01096 {
01097   unsigned int omsb;                /* One, not zero, based MSB.  */
01098   int exponentChange;
01099 
01100   if(category != fcNormal)
01101     return opOK;
01102 
01103   /* Before rounding normalize the exponent of fcNormal numbers.  */
01104   omsb = significandMSB() + 1;
01105 
01106   if(omsb) {
01107     /* OMSB is numbered from 1.  We want to place it in the integer
01108        bit numbered PRECISON if possible, with a compensating change in
01109        the exponent.  */
01110     exponentChange = omsb - semantics->precision;
01111 
01112     /* If the resulting exponent is too high, overflow according to
01113        the rounding mode.  */
01114     if(exponent + exponentChange > semantics->maxExponent)
01115       return handleOverflow(rounding_mode);
01116 
01117     /* Subnormal numbers have exponent minExponent, and their MSB
01118        is forced based on that.  */
01119     if(exponent + exponentChange < semantics->minExponent)
01120       exponentChange = semantics->minExponent - exponent;
01121 
01122     /* Shifting left is easy as we don't lose precision.  */
01123     if(exponentChange < 0) {
01124       assert(lost_fraction == lfExactlyZero);
01125 
01126       shiftSignificandLeft(-exponentChange);
01127 
01128       return opOK;
01129     }
01130 
01131     if(exponentChange > 0) {
01132       lostFraction lf;
01133 
01134       /* Shift right and capture any new lost fraction.  */
01135       lf = shiftSignificandRight(exponentChange);
01136 
01137       lost_fraction = combineLostFractions(lf, lost_fraction);
01138 
01139       /* Keep OMSB up-to-date.  */
01140       if(omsb > (unsigned) exponentChange)
01141         omsb -= exponentChange;
01142       else
01143         omsb = 0;
01144     }
01145   }
01146 
01147   /* Now round the number according to rounding_mode given the lost
01148      fraction.  */
01149 
01150   /* As specified in IEEE 754, since we do not trap we do not report
01151      underflow for exact results.  */
01152   if(lost_fraction == lfExactlyZero) {
01153     /* Canonicalize zeroes.  */
01154     if(omsb == 0)
01155       category = fcZero;
01156 
01157     return opOK;
01158   }
01159 
01160   /* Increment the significand if we're rounding away from zero.  */
01161   if(roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
01162     if(omsb == 0)
01163       exponent = semantics->minExponent;
01164 
01165     incrementSignificand();
01166     omsb = significandMSB() + 1;
01167 
01168     /* Did the significand increment overflow?  */
01169     if(omsb == (unsigned) semantics->precision + 1) {
01170       /* Renormalize by incrementing the exponent and shifting our
01171          significand right one.  However if we already have the
01172          maximum exponent we overflow to infinity.  */
01173       if(exponent == semantics->maxExponent) {
01174         category = fcInfinity;
01175 
01176         return (opStatus) (opOverflow | opInexact);
01177       }
01178 
01179       shiftSignificandRight(1);
01180 
01181       return opInexact;
01182     }
01183   }
01184 
01185   /* The normal case - we were and are not denormal, and any
01186      significand increment above didn't overflow.  */
01187   if(omsb == semantics->precision)
01188     return opInexact;
01189 
01190   /* We have a non-zero denormal.  */
01191   assert(omsb < semantics->precision);
01192 
01193   /* Canonicalize zeroes.  */
01194   if(omsb == 0)
01195     category = fcZero;
01196 
01197   /* The fcZero case is a denormal that underflowed to zero.  */
01198   return (opStatus) (opUnderflow | opInexact);
01199 }
01200 
01201 APFloat::opStatus
01202 APFloat::addOrSubtractSpecials(const APFloat &rhs, bool subtract)
01203 {
01204   switch(convolve(category, rhs.category)) {
01205   default:
01206     assert(0);
01207 
01208   case convolve(fcNaN, fcZero):
01209   case convolve(fcNaN, fcNormal):
01210   case convolve(fcNaN, fcInfinity):
01211   case convolve(fcNaN, fcNaN):
01212   case convolve(fcNormal, fcZero):
01213   case convolve(fcInfinity, fcNormal):
01214   case convolve(fcInfinity, fcZero):
01215     return opOK;
01216 
01217   case convolve(fcZero, fcNaN):
01218   case convolve(fcNormal, fcNaN):
01219   case convolve(fcInfinity, fcNaN):
01220     category = fcNaN;
01221     copySignificand(rhs);
01222     return opOK;
01223 
01224   case convolve(fcNormal, fcInfinity):
01225   case convolve(fcZero, fcInfinity):
01226     category = fcInfinity;
01227     sign = rhs.sign ^ subtract;
01228     return opOK;
01229 
01230   case convolve(fcZero, fcNormal):
01231     assign(rhs);
01232     sign = rhs.sign ^ subtract;
01233     return opOK;
01234 
01235   case convolve(fcZero, fcZero):
01236     /* Sign depends on rounding mode; handled by caller.  */
01237     return opOK;
01238 
01239   case convolve(fcInfinity, fcInfinity):
01240     /* Differently signed infinities can only be validly
01241        subtracted.  */
01242     if((sign ^ rhs.sign) != subtract) {
01243       makeNaN();
01244       return opInvalidOp;
01245     }
01246 
01247     return opOK;
01248 
01249   case convolve(fcNormal, fcNormal):
01250     return opDivByZero;
01251   }
01252 }
01253 
01254 /* Add or subtract two normal numbers.  */
01255 lostFraction
01256 APFloat::addOrSubtractSignificand(const APFloat &rhs, bool subtract)
01257 {
01258   integerPart carry;
01259   lostFraction lost_fraction;
01260   int bits;
01261 
01262   /* Determine if the operation on the absolute values is effectively
01263      an addition or subtraction.  */
01264   subtract ^= (sign ^ rhs.sign) ? true : false;
01265 
01266   /* Are we bigger exponent-wise than the RHS?  */
01267   bits = exponent - rhs.exponent;
01268 
01269   /* Subtraction is more subtle than one might naively expect.  */
01270   if(subtract) {
01271     APFloat temp_rhs(rhs);
01272     bool reverse;
01273 
01274     if (bits == 0) {
01275       reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan;
01276       lost_fraction = lfExactlyZero;
01277     } else if (bits > 0) {
01278       lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
01279       shiftSignificandLeft(1);
01280       reverse = false;
01281     } else {
01282       lost_fraction = shiftSignificandRight(-bits - 1);
01283       temp_rhs.shiftSignificandLeft(1);
01284       reverse = true;
01285     }
01286 
01287     if (reverse) {
01288       carry = temp_rhs.subtractSignificand
01289         (*this, lost_fraction != lfExactlyZero);
01290       copySignificand(temp_rhs);
01291       sign = !sign;
01292     } else {
01293       carry = subtractSignificand
01294         (temp_rhs, lost_fraction != lfExactlyZero);
01295     }
01296 
01297     /* Invert the lost fraction - it was on the RHS and
01298        subtracted.  */
01299     if(lost_fraction == lfLessThanHalf)
01300       lost_fraction = lfMoreThanHalf;
01301     else if(lost_fraction == lfMoreThanHalf)
01302       lost_fraction = lfLessThanHalf;
01303 
01304     /* The code above is intended to ensure that no borrow is
01305        necessary.  */
01306     assert(!carry);
01307   } else {
01308     if(bits > 0) {
01309       APFloat temp_rhs(rhs);
01310 
01311       lost_fraction = temp_rhs.shiftSignificandRight(bits);
01312       carry = addSignificand(temp_rhs);
01313     } else {
01314       lost_fraction = shiftSignificandRight(-bits);
01315       carry = addSignificand(rhs);
01316     }
01317 
01318     /* We have a guard bit; generating a carry cannot happen.  */
01319     assert(!carry);
01320   }
01321 
01322   return lost_fraction;
01323 }
01324 
01325 APFloat::opStatus
01326 APFloat::multiplySpecials(const APFloat &rhs)
01327 {
01328   switch(convolve(category, rhs.category)) {
01329   default:
01330     assert(0);
01331 
01332   case convolve(fcNaN, fcZero):
01333   case convolve(fcNaN, fcNormal):
01334   case convolve(fcNaN, fcInfinity):
01335   case convolve(fcNaN, fcNaN):
01336     return opOK;
01337 
01338   case convolve(fcZero, fcNaN):
01339   case convolve(fcNormal, fcNaN):
01340   case convolve(fcInfinity, fcNaN):
01341     category = fcNaN;
01342     copySignificand(rhs);
01343     return opOK;
01344 
01345   case convolve(fcNormal, fcInfinity):
01346   case convolve(fcInfinity, fcNormal):
01347   case convolve(fcInfinity, fcInfinity):
01348     category = fcInfinity;
01349     return opOK;
01350 
01351   case convolve(fcZero, fcNormal):
01352   case convolve(fcNormal, fcZero):
01353   case convolve(fcZero, fcZero):
01354     category = fcZero;
01355     return opOK;
01356 
01357   case convolve(fcZero, fcInfinity):
01358   case convolve(fcInfinity, fcZero):
01359     makeNaN();
01360     return opInvalidOp;
01361 
01362   case convolve(fcNormal, fcNormal):
01363     return opOK;
01364   }
01365 }
01366 
01367 APFloat::opStatus
01368 APFloat::divideSpecials(const APFloat &rhs)
01369 {
01370   switch(convolve(category, rhs.category)) {
01371   default:
01372     assert(0);
01373 
01374   case convolve(fcNaN, fcZero):
01375   case convolve(fcNaN, fcNormal):
01376   case convolve(fcNaN, fcInfinity):
01377   case convolve(fcNaN, fcNaN):
01378   case convolve(fcInfinity, fcZero):
01379   case convolve(fcInfinity, fcNormal):
01380   case convolve(fcZero, fcInfinity):
01381   case convolve(fcZero, fcNormal):
01382     return opOK;
01383 
01384   case convolve(fcZero, fcNaN):
01385   case convolve(fcNormal, fcNaN):
01386   case convolve(fcInfinity, fcNaN):
01387     category = fcNaN;
01388     copySignificand(rhs);
01389     return opOK;
01390 
01391   case convolve(fcNormal, fcInfinity):
01392     category = fcZero;
01393     return opOK;
01394 
01395   case convolve(fcNormal, fcZero):
01396     category = fcInfinity;
01397     return opDivByZero;
01398 
01399   case convolve(fcInfinity, fcInfinity):
01400   case convolve(fcZero, fcZero):
01401     makeNaN();
01402     return opInvalidOp;
01403 
01404   case convolve(fcNormal, fcNormal):
01405     return opOK;
01406   }
01407 }
01408 
01409 APFloat::opStatus
01410 APFloat::modSpecials(const APFloat &rhs)
01411 {
01412   switch(convolve(category, rhs.category)) {
01413   default:
01414     assert(0);
01415 
01416   case convolve(fcNaN, fcZero):
01417   case convolve(fcNaN, fcNormal):
01418   case convolve(fcNaN, fcInfinity):
01419   case convolve(fcNaN, fcNaN):
01420   case convolve(fcZero, fcInfinity):
01421   case convolve(fcZero, fcNormal):
01422   case convolve(fcNormal, fcInfinity):
01423     return opOK;
01424 
01425   case convolve(fcZero, fcNaN):
01426   case convolve(fcNormal, fcNaN):
01427   case convolve(fcInfinity, fcNaN):
01428     category = fcNaN;
01429     copySignificand(rhs);
01430     return opOK;
01431 
01432   case convolve(fcNormal, fcZero):
01433   case convolve(fcInfinity, fcZero):
01434   case convolve(fcInfinity, fcNormal):
01435   case convolve(fcInfinity, fcInfinity):
01436   case convolve(fcZero, fcZero):
01437     makeNaN();
01438     return opInvalidOp;
01439 
01440   case convolve(fcNormal, fcNormal):
01441     return opOK;
01442   }
01443 }
01444 
01445 /* Change sign.  */
01446 void
01447 APFloat::changeSign()
01448 {
01449   /* Look mummy, this one's easy.  */
01450   sign = !sign;
01451 }
01452 
01453 void
01454 APFloat::clearSign()
01455 {
01456   /* So is this one. */
01457   sign = 0;
01458 }
01459 
01460 void
01461 APFloat::copySign(const APFloat &rhs)
01462 {
01463   /* And this one. */
01464   sign = rhs.sign;
01465 }
01466 
01467 /* Normalized addition or subtraction.  */
01468 APFloat::opStatus
01469 APFloat::addOrSubtract(const APFloat &rhs, roundingMode rounding_mode,
01470                        bool subtract)
01471 {
01472   opStatus fs;
01473 
01474   assertArithmeticOK(*semantics);
01475 
01476   fs = addOrSubtractSpecials(rhs, subtract);
01477 
01478   /* This return code means it was not a simple case.  */
01479   if(fs == opDivByZero) {
01480     lostFraction lost_fraction;
01481 
01482     lost_fraction = addOrSubtractSignificand(rhs, subtract);
01483     fs = normalize(rounding_mode, lost_fraction);
01484 
01485     /* Can only be zero if we lost no fraction.  */
01486     assert(category != fcZero || lost_fraction == lfExactlyZero);
01487   }
01488 
01489   /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
01490      positive zero unless rounding to minus infinity, except that
01491      adding two like-signed zeroes gives that zero.  */
01492   if(category == fcZero) {
01493     if(rhs.category != fcZero || (sign == rhs.sign) == subtract)
01494       sign = (rounding_mode == rmTowardNegative);
01495   }
01496 
01497   return fs;
01498 }
01499 
01500 /* Normalized addition.  */
01501 APFloat::opStatus
01502 APFloat::add(const APFloat &rhs, roundingMode rounding_mode)
01503 {
01504   return addOrSubtract(rhs, rounding_mode, false);
01505 }
01506 
01507 /* Normalized subtraction.  */
01508 APFloat::opStatus
01509 APFloat::subtract(const APFloat &rhs, roundingMode rounding_mode)
01510 {
01511   return addOrSubtract(rhs, rounding_mode, true);
01512 }
01513 
01514 /* Normalized multiply.  */
01515 APFloat::opStatus
01516 APFloat::multiply(const APFloat &rhs, roundingMode rounding_mode)
01517 {
01518   opStatus fs;
01519 
01520   assertArithmeticOK(*semantics);
01521   sign ^= rhs.sign;
01522   fs = multiplySpecials(rhs);
01523 
01524   if(category == fcNormal) {
01525     lostFraction lost_fraction = multiplySignificand(rhs, 0);
01526     fs = normalize(rounding_mode, lost_fraction);
01527     if(lost_fraction != lfExactlyZero)
01528       fs = (opStatus) (fs | opInexact);
01529   }
01530 
01531   return fs;
01532 }
01533 
01534 /* Normalized divide.  */
01535 APFloat::opStatus
01536 APFloat::divide(const APFloat &rhs, roundingMode rounding_mode)
01537 {
01538   opStatus fs;
01539 
01540   assertArithmeticOK(*semantics);
01541   sign ^= rhs.sign;
01542   fs = divideSpecials(rhs);
01543 
01544   if(category == fcNormal) {
01545     lostFraction lost_fraction = divideSignificand(rhs);
01546     fs = normalize(rounding_mode, lost_fraction);
01547     if(lost_fraction != lfExactlyZero)
01548       fs = (opStatus) (fs | opInexact);
01549   }
01550 
01551   return fs;
01552 }
01553 
01554 /* Normalized remainder.  This is not currently correct in all cases.  */
01555 APFloat::opStatus
01556 APFloat::remainder(const APFloat &rhs)
01557 {
01558   opStatus fs;
01559   APFloat V = *this;
01560   unsigned int origSign = sign;
01561 
01562   assertArithmeticOK(*semantics);
01563   fs = V.divide(rhs, rmNearestTiesToEven);
01564   if (fs == opDivByZero)
01565     return fs;
01566 
01567   int parts = partCount();
01568   integerPart *x = new integerPart[parts];
01569   bool ignored;
01570   fs = V.convertToInteger(x, parts * integerPartWidth, true,
01571                           rmNearestTiesToEven, &ignored);
01572   if (fs==opInvalidOp)
01573     return fs;
01574 
01575   fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
01576                                         rmNearestTiesToEven);
01577   assert(fs==opOK);   // should always work
01578 
01579   fs = V.multiply(rhs, rmNearestTiesToEven);
01580   assert(fs==opOK || fs==opInexact);   // should not overflow or underflow
01581 
01582   fs = subtract(V, rmNearestTiesToEven);
01583   assert(fs==opOK || fs==opInexact);   // likewise
01584 
01585   if (isZero())
01586     sign = origSign;    // IEEE754 requires this
01587   delete[] x;
01588   return fs;
01589 }
01590 
01591 /* Normalized llvm frem (C fmod).  
01592    This is not currently correct in all cases.  */
01593 APFloat::opStatus
01594 APFloat::mod(const APFloat &rhs, roundingMode rounding_mode)
01595 {
01596   opStatus fs;
01597   assertArithmeticOK(*semantics);
01598   fs = modSpecials(rhs);
01599 
01600   if (category == fcNormal && rhs.category == fcNormal) {
01601     APFloat V = *this;
01602     unsigned int origSign = sign;
01603 
01604     fs = V.divide(rhs, rmNearestTiesToEven);
01605     if (fs == opDivByZero)
01606       return fs;
01607 
01608     int parts = partCount();
01609     integerPart *x = new integerPart[parts];
01610     bool ignored;
01611     fs = V.convertToInteger(x, parts * integerPartWidth, true,
01612                             rmTowardZero, &ignored);
01613     if (fs==opInvalidOp)
01614       return fs;
01615 
01616     fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
01617                                           rmNearestTiesToEven);
01618     assert(fs==opOK);   // should always work
01619 
01620     fs = V.multiply(rhs, rounding_mode);
01621     assert(fs==opOK || fs==opInexact);   // should not overflow or underflow
01622 
01623     fs = subtract(V, rounding_mode);
01624     assert(fs==opOK || fs==opInexact);   // likewise
01625 
01626     if (isZero())
01627       sign = origSign;    // IEEE754 requires this
01628     delete[] x;
01629   }
01630   return fs;
01631 }
01632 
01633 /* Normalized fused-multiply-add.  */
01634 APFloat::opStatus
01635 APFloat::fusedMultiplyAdd(const APFloat &multiplicand,
01636                           const APFloat &addend,
01637                           roundingMode rounding_mode)
01638 {
01639   opStatus fs;
01640 
01641   assertArithmeticOK(*semantics);
01642 
01643   /* Post-multiplication sign, before addition.  */
01644   sign ^= multiplicand.sign;
01645 
01646   /* If and only if all arguments are normal do we need to do an
01647      extended-precision calculation.  */
01648   if(category == fcNormal
01649      && multiplicand.category == fcNormal
01650      && addend.category == fcNormal) {
01651     lostFraction lost_fraction;
01652 
01653     lost_fraction = multiplySignificand(multiplicand, &addend);
01654     fs = normalize(rounding_mode, lost_fraction);
01655     if(lost_fraction != lfExactlyZero)
01656       fs = (opStatus) (fs | opInexact);
01657 
01658     /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
01659        positive zero unless rounding to minus infinity, except that
01660        adding two like-signed zeroes gives that zero.  */
01661     if(category == fcZero && sign != addend.sign)
01662       sign = (rounding_mode == rmTowardNegative);
01663   } else {
01664     fs = multiplySpecials(multiplicand);
01665 
01666     /* FS can only be opOK or opInvalidOp.  There is no more work
01667        to do in the latter case.  The IEEE-754R standard says it is
01668        implementation-defined in this case whether, if ADDEND is a
01669        quiet NaN, we raise invalid op; this implementation does so.
01670 
01671        If we need to do the addition we can do so with normal
01672        precision.  */
01673     if(fs == opOK)
01674       fs = addOrSubtract(addend, rounding_mode, false);
01675   }
01676 
01677   return fs;
01678 }
01679 
01680 /* Comparison requires normalized numbers.  */
01681 APFloat::cmpResult
01682 APFloat::compare(const APFloat &rhs) const
01683 {
01684   cmpResult result;
01685 
01686   assertArithmeticOK(*semantics);
01687   assert(semantics == rhs.semantics);
01688 
01689   switch(convolve(category, rhs.category)) {
01690   default:
01691     assert(0);
01692 
01693   case convolve(fcNaN, fcZero):
01694   case convolve(fcNaN, fcNormal):
01695   case convolve(fcNaN, fcInfinity):
01696   case convolve(fcNaN, fcNaN):
01697   case convolve(fcZero, fcNaN):
01698   case convolve(fcNormal, fcNaN):
01699   case convolve(fcInfinity, fcNaN):
01700     return cmpUnordered;
01701 
01702   case convolve(fcInfinity, fcNormal):
01703   case convolve(fcInfinity, fcZero):
01704   case convolve(fcNormal, fcZero):
01705     if(sign)
01706       return cmpLessThan;
01707     else
01708       return cmpGreaterThan;
01709 
01710   case convolve(fcNormal, fcInfinity):
01711   case convolve(fcZero, fcInfinity):
01712   case convolve(fcZero, fcNormal):
01713     if(rhs.sign)
01714       return cmpGreaterThan;
01715     else
01716       return cmpLessThan;
01717 
01718   case convolve(fcInfinity, fcInfinity):
01719     if(sign == rhs.sign)
01720       return cmpEqual;
01721     else if(sign)
01722       return cmpLessThan;
01723     else
01724       return cmpGreaterThan;
01725 
01726   case convolve(fcZero, fcZero):
01727     return cmpEqual;
01728 
01729   case convolve(fcNormal, fcNormal):
01730     break;
01731   }
01732 
01733   /* Two normal numbers.  Do they have the same sign?  */
01734   if(sign != rhs.sign) {
01735     if(sign)
01736       result = cmpLessThan;
01737     else
01738       result = cmpGreaterThan;
01739   } else {
01740     /* Compare absolute values; invert result if negative.  */
01741     result = compareAbsoluteValue(rhs);
01742 
01743     if(sign) {
01744       if(result == cmpLessThan)
01745         result = cmpGreaterThan;
01746       else if(result == cmpGreaterThan)
01747         result = cmpLessThan;
01748     }
01749   }
01750 
01751   return result;
01752 }
01753 
01754 /// APFloat::convert - convert a value of one floating point type to another.
01755 /// The return value corresponds to the IEEE754 exceptions.  *losesInfo
01756 /// records whether the transformation lost information, i.e. whether
01757 /// converting the result back to the original type will produce the
01758 /// original value (this is almost the same as return value==fsOK, but there
01759 /// are edge cases where this is not so).
01760 
01761 APFloat::opStatus
01762 APFloat::convert(const fltSemantics &toSemantics,
01763                  roundingMode rounding_mode, bool *losesInfo)
01764 {
01765   lostFraction lostFraction;
01766   unsigned int newPartCount, oldPartCount;
01767   opStatus fs;
01768 
01769   assertArithmeticOK(*semantics);
01770   assertArithmeticOK(toSemantics);
01771   lostFraction = lfExactlyZero;
01772   newPartCount = partCountForBits(toSemantics.precision + 1);
01773   oldPartCount = partCount();
01774 
01775   /* Handle storage complications.  If our new form is wider,
01776      re-allocate our bit pattern into wider storage.  If it is
01777      narrower, we ignore the excess parts, but if narrowing to a
01778      single part we need to free the old storage.
01779      Be careful not to reference significandParts for zeroes
01780      and infinities, since it aborts.  */
01781   if (newPartCount > oldPartCount) {
01782     integerPart *newParts;
01783     newParts = new integerPart[newPartCount];
01784     APInt::tcSet(newParts, 0, newPartCount);
01785     if (category==fcNormal || category==fcNaN)
01786       APInt::tcAssign(newParts, significandParts(), oldPartCount);
01787     freeSignificand();
01788     significand.parts = newParts;
01789   } else if (newPartCount < oldPartCount) {
01790     /* Capture any lost fraction through truncation of parts so we get
01791        correct rounding whilst normalizing.  */
01792     if (category==fcNormal)
01793       lostFraction = lostFractionThroughTruncation
01794         (significandParts(), oldPartCount, toSemantics.precision);
01795     if (newPartCount == 1) {
01796         integerPart newPart = 0;
01797         if (category==fcNormal || category==fcNaN)
01798           newPart = significandParts()[0];
01799         freeSignificand();
01800         significand.part = newPart;
01801     }
01802   }
01803 
01804   if(category == fcNormal) {
01805     /* Re-interpret our bit-pattern.  */
01806     exponent += toSemantics.precision - semantics->precision;
01807     semantics = &toSemantics;
01808     fs = normalize(rounding_mode, lostFraction);
01809     *losesInfo = (fs != opOK);
01810   } else if (category == fcNaN) {
01811     int shift = toSemantics.precision - semantics->precision;
01812     // Do this now so significandParts gets the right answer
01813     const fltSemantics *oldSemantics = semantics;
01814     semantics = &toSemantics;
01815     *losesInfo = false;
01816     // No normalization here, just truncate
01817     if (shift>0)
01818       APInt::tcShiftLeft(significandParts(), newPartCount, shift);
01819     else if (shift < 0) {
01820       unsigned ushift = -shift;
01821       // Figure out if we are losing information.  This happens
01822       // if are shifting out something other than 0s, or if the x87 long
01823       // double input did not have its integer bit set (pseudo-NaN), or if the
01824       // x87 long double input did not have its QNan bit set (because the x87
01825       // hardware sets this bit when converting a lower-precision NaN to
01826       // x87 long double).
01827       if (APInt::tcLSB(significandParts(), newPartCount) < ushift)
01828         *losesInfo = true;
01829       if (oldSemantics == &APFloat::x87DoubleExtended && 
01830           (!(*significandParts() & 0x8000000000000000ULL) ||
01831            !(*significandParts() & 0x4000000000000000ULL)))
01832         *losesInfo = true;
01833       APInt::tcShiftRight(significandParts(), newPartCount, ushift);
01834     }
01835     // gcc forces the Quiet bit on, which means (float)(double)(float_sNan)
01836     // does not give you back the same bits.  This is dubious, and we
01837     // don't currently do it.  You're really supposed to get
01838     // an invalid operation signal at runtime, but nobody does that.
01839     fs = opOK;
01840   } else {
01841     semantics = &toSemantics;
01842     fs = opOK;
01843     *losesInfo = false;
01844   }
01845 
01846   return fs;
01847 }
01848 
01849 /* Convert a floating point number to an integer according to the
01850    rounding mode.  If the rounded integer value is out of range this
01851    returns an invalid operation exception and the contents of the
01852    destination parts are unspecified.  If the rounded value is in
01853    range but the floating point number is not the exact integer, the C
01854    standard doesn't require an inexact exception to be raised.  IEEE
01855    854 does require it so we do that.
01856 
01857    Note that for conversions to integer type the C standard requires
01858    round-to-zero to always be used.  */
01859 APFloat::opStatus
01860 APFloat::convertToSignExtendedInteger(integerPart *parts, unsigned int width,
01861                                       bool isSigned,
01862                                       roundingMode rounding_mode,
01863                                       bool *isExact) const
01864 {
01865   lostFraction lost_fraction;
01866   const integerPart *src;
01867   unsigned int dstPartsCount, truncatedBits;
01868 
01869   assertArithmeticOK(*semantics);
01870 
01871   *isExact = false;
01872 
01873   /* Handle the three special cases first.  */
01874   if(category == fcInfinity || category == fcNaN)
01875     return opInvalidOp;
01876 
01877   dstPartsCount = partCountForBits(width);
01878 
01879   if(category == fcZero) {
01880     APInt::tcSet(parts, 0, dstPartsCount);
01881     // Negative zero can't be represented as an int.
01882     *isExact = !sign;
01883     return opOK;
01884   }
01885 
01886   src = significandParts();
01887 
01888   /* Step 1: place our absolute value, with any fraction truncated, in
01889      the destination.  */
01890   if (exponent < 0) {
01891     /* Our absolute value is less than one; truncate everything.  */
01892     APInt::tcSet(parts, 0, dstPartsCount);
01893     /* For exponent -1 the integer bit represents .5, look at that.
01894        For smaller exponents leftmost truncated bit is 0. */
01895     truncatedBits = semantics->precision -1U - exponent;
01896   } else {
01897     /* We want the most significant (exponent + 1) bits; the rest are
01898        truncated.  */
01899     unsigned int bits = exponent + 1U;
01900 
01901     /* Hopelessly large in magnitude?  */
01902     if (bits > width)
01903       return opInvalidOp;
01904 
01905     if (bits < semantics->precision) {
01906       /* We truncate (semantics->precision - bits) bits.  */
01907       truncatedBits = semantics->precision - bits;
01908       APInt::tcExtract(parts, dstPartsCount, src, bits, truncatedBits);
01909     } else {
01910       /* We want at least as many bits as are available.  */
01911       APInt::tcExtract(parts, dstPartsCount, src, semantics->precision, 0);
01912       APInt::tcShiftLeft(parts, dstPartsCount, bits - semantics->precision);
01913       truncatedBits = 0;
01914     }
01915   }
01916 
01917   /* Step 2: work out any lost fraction, and increment the absolute
01918      value if we would round away from zero.  */
01919   if (truncatedBits) {
01920     lost_fraction = lostFractionThroughTruncation(src, partCount(),
01921                                                   truncatedBits);
01922     if (lost_fraction != lfExactlyZero
01923         && roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
01924       if (APInt::tcIncrement(parts, dstPartsCount))
01925         return opInvalidOp;     /* Overflow.  */
01926     }
01927   } else {
01928     lost_fraction = lfExactlyZero;
01929   }
01930 
01931   /* Step 3: check if we fit in the destination.  */
01932   unsigned int omsb = APInt::tcMSB(parts, dstPartsCount) + 1;
01933 
01934   if (sign) {
01935     if (!isSigned) {
01936       /* Negative numbers cannot be represented as unsigned.  */
01937       if (omsb != 0)
01938         return opInvalidOp;
01939     } else {
01940       /* It takes omsb bits to represent the unsigned integer value.
01941          We lose a bit for the sign, but care is needed as the
01942          maximally negative integer is a special case.  */
01943       if (omsb == width && APInt::tcLSB(parts, dstPartsCount) + 1 != omsb)
01944         return opInvalidOp;
01945 
01946       /* This case can happen because of rounding.  */
01947       if (omsb > width)
01948         return opInvalidOp;
01949     }
01950 
01951     APInt::tcNegate (parts, dstPartsCount);
01952   } else {
01953     if (omsb >= width + !isSigned)
01954       return opInvalidOp;
01955   }
01956 
01957   if (lost_fraction == lfExactlyZero) {
01958     *isExact = true;
01959     return opOK;
01960   } else
01961     return opInexact;
01962 }
01963 
01964 /* Same as convertToSignExtendedInteger, except we provide
01965    deterministic values in case of an invalid operation exception,
01966    namely zero for NaNs and the minimal or maximal value respectively
01967    for underflow or overflow.
01968    The *isExact output tells whether the result is exact, in the sense
01969    that converting it back to the original floating point type produces
01970    the original value.  This is almost equivalent to result==opOK,
01971    except for negative zeroes.
01972 */
01973 APFloat::opStatus
01974 APFloat::convertToInteger(integerPart *parts, unsigned int width,
01975                           bool isSigned,
01976                           roundingMode rounding_mode, bool *isExact) const
01977 {
01978   opStatus fs;
01979 
01980   fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode, 
01981                                     isExact);
01982 
01983   if (fs == opInvalidOp) {
01984     unsigned int bits, dstPartsCount;
01985 
01986     dstPartsCount = partCountForBits(width);
01987 
01988     if (category == fcNaN)
01989       bits = 0;
01990     else if (sign)
01991       bits = isSigned;
01992     else
01993       bits = width - isSigned;
01994 
01995     APInt::tcSetLeastSignificantBits(parts, dstPartsCount, bits);
01996     if (sign && isSigned)
01997       APInt::tcShiftLeft(parts, dstPartsCount, width - 1);
01998   }
01999 
02000   return fs;
02001 }
02002 
02003 /* Convert an unsigned integer SRC to a floating point number,
02004    rounding according to ROUNDING_MODE.  The sign of the floating
02005    point number is not modified.  */
02006 APFloat::opStatus
02007 APFloat::convertFromUnsignedParts(const integerPart *src,
02008                                   unsigned int srcCount,
02009                                   roundingMode rounding_mode)
02010 {
02011   unsigned int omsb, precision, dstCount;
02012   integerPart *dst;
02013   lostFraction lost_fraction;
02014 
02015   assertArithmeticOK(*semantics);
02016   category = fcNormal;
02017   omsb = APInt::tcMSB(src, srcCount) + 1;
02018   dst = significandParts();
02019   dstCount = partCount();
02020   precision = semantics->precision;
02021 
02022   /* We want the most significant PRECISON bits of SRC.  There may not
02023      be that many; extract what we can.  */
02024   if (precision <= omsb) {
02025     exponent = omsb - 1;
02026     lost_fraction = lostFractionThroughTruncation(src, srcCount,
02027                                                   omsb - precision);
02028     APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
02029   } else {
02030     exponent = precision - 1;
02031     lost_fraction = lfExactlyZero;
02032     APInt::tcExtract(dst, dstCount, src, omsb, 0);
02033   }
02034 
02035   return normalize(rounding_mode, lost_fraction);
02036 }
02037 
02038 APFloat::opStatus
02039 APFloat::convertFromAPInt(const APInt &Val,
02040                           bool isSigned,
02041                           roundingMode rounding_mode)
02042 {
02043   unsigned int partCount = Val.getNumWords();
02044   APInt api = Val;
02045 
02046   sign = false;
02047   if (isSigned && api.isNegative()) {
02048     sign = true;
02049     api = -api;
02050   }
02051 
02052   return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
02053 }
02054 
02055 /* Convert a two's complement integer SRC to a floating point number,
02056    rounding according to ROUNDING_MODE.  ISSIGNED is true if the
02057    integer is signed, in which case it must be sign-extended.  */
02058 APFloat::opStatus
02059 APFloat::convertFromSignExtendedInteger(const integerPart *src,
02060                                         unsigned int srcCount,
02061                                         bool isSigned,
02062                                         roundingMode rounding_mode)
02063 {
02064   opStatus status;
02065 
02066   assertArithmeticOK(*semantics);
02067   if (isSigned
02068       && APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) {
02069     integerPart *copy;
02070 
02071     /* If we're signed and negative negate a copy.  */
02072     sign = true;
02073     copy = new integerPart[srcCount];
02074     APInt::tcAssign(copy, src, srcCount);
02075     APInt::tcNegate(copy, srcCount);
02076     status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
02077     delete [] copy;
02078   } else {
02079     sign = false;
02080     status = convertFromUnsignedParts(src, srcCount, rounding_mode);
02081   }
02082 
02083   return status;
02084 }
02085 
02086 /* FIXME: should this just take a const APInt reference?  */
02087 APFloat::opStatus
02088 APFloat::convertFromZeroExtendedInteger(const integerPart *parts,
02089                                         unsigned int width, bool isSigned,
02090                                         roundingMode rounding_mode)
02091 {
02092   unsigned int partCount = partCountForBits(width);
02093   APInt api = APInt(width, partCount, parts);
02094 
02095   sign = false;
02096   if(isSigned && APInt::tcExtractBit(parts, width - 1)) {
02097     sign = true;
02098     api = -api;
02099   }
02100 
02101   return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
02102 }
02103 
02104 APFloat::opStatus
02105 APFloat::convertFromHexadecimalString(const char *p,
02106                                       roundingMode rounding_mode)
02107 {
02108   lostFraction lost_fraction;
02109   integerPart *significand;
02110   unsigned int bitPos, partsCount;
02111   const char *dot, *firstSignificantDigit;
02112 
02113   zeroSignificand();
02114   exponent = 0;
02115   category = fcNormal;
02116 
02117   significand = significandParts();
02118   partsCount = partCount();
02119   bitPos = partsCount * integerPartWidth;
02120 
02121   /* Skip leading zeroes and any (hexa)decimal point.  */
02122   p = skipLeadingZeroesAndAnyDot(p, &dot);
02123   firstSignificantDigit = p;
02124 
02125   for(;;) {
02126     integerPart hex_value;
02127 
02128     if(*p == '.') {
02129       assert(dot == 0);
02130       dot = p++;
02131     }
02132 
02133     hex_value = hexDigitValue(*p);
02134     if(hex_value == -1U) {
02135       lost_fraction = lfExactlyZero;
02136       break;
02137     }
02138 
02139     p++;
02140 
02141     /* Store the number whilst 4-bit nibbles remain.  */
02142     if(bitPos) {
02143       bitPos -= 4;
02144       hex_value <<= bitPos % integerPartWidth;
02145       significand[bitPos / integerPartWidth] |= hex_value;
02146     } else {
02147       lost_fraction = trailingHexadecimalFraction(p, hex_value);
02148       while(hexDigitValue(*p) != -1U)
02149         p++;
02150       break;
02151     }
02152   }
02153 
02154   /* Hex floats require an exponent but not a hexadecimal point.  */
02155   assert(*p == 'p' || *p == 'P');
02156 
02157   /* Ignore the exponent if we are zero.  */
02158   if(p != firstSignificantDigit) {
02159     int expAdjustment;
02160 
02161     /* Implicit hexadecimal point?  */
02162     if(!dot)
02163       dot = p;
02164 
02165     /* Calculate the exponent adjustment implicit in the number of
02166        significant digits.  */
02167     expAdjustment = static_cast<int>(dot - firstSignificantDigit);
02168     if(expAdjustment < 0)
02169       expAdjustment++;
02170     expAdjustment = expAdjustment * 4 - 1;
02171 
02172     /* Adjust for writing the significand starting at the most
02173        significant nibble.  */
02174     expAdjustment += semantics->precision;
02175     expAdjustment -= partsCount * integerPartWidth;
02176 
02177     /* Adjust for the given exponent.  */
02178     exponent = totalExponent(p, expAdjustment);
02179   }
02180 
02181   return normalize(rounding_mode, lost_fraction);
02182 }
02183 
02184 APFloat::opStatus
02185 APFloat::roundSignificandWithExponent(const integerPart *decSigParts,
02186                                       unsigned sigPartCount, int exp,
02187                                       roundingMode rounding_mode)
02188 {
02189   unsigned int parts, pow5PartCount;
02190   fltSemantics calcSemantics = { 32767, -32767, 0, true };
02191   integerPart pow5Parts[maxPowerOfFiveParts];
02192   bool isNearest;
02193 
02194   isNearest = (rounding_mode == rmNearestTiesToEven
02195                || rounding_mode == rmNearestTiesToAway);
02196 
02197   parts = partCountForBits(semantics->precision + 11);
02198 
02199   /* Calculate pow(5, abs(exp)).  */
02200   pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp);
02201 
02202   for (;; parts *= 2) {
02203     opStatus sigStatus, powStatus;
02204     unsigned int excessPrecision, truncatedBits;
02205 
02206     calcSemantics.precision = parts * integerPartWidth - 1;
02207     excessPrecision = calcSemantics.precision - semantics->precision;
02208     truncatedBits = excessPrecision;
02209 
02210     APFloat decSig(calcSemantics, fcZero, sign);
02211     APFloat pow5(calcSemantics, fcZero, false);
02212 
02213     sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount,
02214                                                 rmNearestTiesToEven);
02215     powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
02216                                               rmNearestTiesToEven);
02217     /* Add exp, as 10^n = 5^n * 2^n.  */
02218     decSig.exponent += exp;
02219 
02220     lostFraction calcLostFraction;
02221     integerPart HUerr, HUdistance;
02222     unsigned int powHUerr;
02223 
02224     if (exp >= 0) {
02225       /* multiplySignificand leaves the precision-th bit set to 1.  */
02226       calcLostFraction = decSig.multiplySignificand(pow5, NULL);
02227       powHUerr = powStatus != opOK;
02228     } else {
02229       calcLostFraction = decSig.divideSignificand(pow5);
02230       /* Denormal numbers have less precision.  */
02231       if (decSig.exponent < semantics->minExponent) {
02232         excessPrecision += (semantics->minExponent - decSig.exponent);
02233         truncatedBits = excessPrecision;
02234         if (excessPrecision > calcSemantics.precision)
02235           excessPrecision = calcSemantics.precision;
02236       }
02237       /* Extra half-ulp lost in reciprocal of exponent.  */
02238       powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2;
02239     }
02240 
02241     /* Both multiplySignificand and divideSignificand return the
02242        result with the integer bit set.  */
02243     assert (APInt::tcExtractBit
02244             (decSig.significandParts(), calcSemantics.precision - 1) == 1);
02245 
02246     HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK,
02247                        powHUerr);
02248     HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
02249                                       excessPrecision, isNearest);
02250 
02251     /* Are we guaranteed to round correctly if we truncate?  */
02252     if (HUdistance >= HUerr) {
02253       APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
02254                        calcSemantics.precision - excessPrecision,
02255                        excessPrecision);
02256       /* Take the exponent of decSig.  If we tcExtract-ed less bits
02257          above we must adjust our exponent to compensate for the
02258          implicit right shift.  */
02259       exponent = (decSig.exponent + semantics->precision
02260                   - (calcSemantics.precision - excessPrecision));
02261       calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(),
02262                                                        decSig.partCount(),
02263                                                        truncatedBits);
02264       return normalize(rounding_mode, calcLostFraction);
02265     }
02266   }
02267 }
02268 
02269 APFloat::opStatus
02270 APFloat::convertFromDecimalString(const char *p, roundingMode rounding_mode)
02271 {
02272   decimalInfo D;
02273   opStatus fs;
02274 
02275   /* Scan the text.  */
02276   interpretDecimal(p, &D);
02277 
02278   /* Handle the quick cases.  First the case of no significant digits,
02279      i.e. zero, and then exponents that are obviously too large or too
02280      small.  Writing L for log 10 / log 2, a number d.ddddd*10^exp
02281      definitely overflows if
02282 
02283            (exp - 1) * L >= maxExponent
02284 
02285      and definitely underflows to zero where
02286 
02287            (exp + 1) * L <= minExponent - precision
02288 
02289      With integer arithmetic the tightest bounds for L are
02290 
02291            93/28 < L < 196/59            [ numerator <= 256 ]
02292            42039/12655 < L < 28738/8651  [ numerator <= 65536 ]
02293   */
02294 
02295   if (decDigitValue(*D.firstSigDigit) >= 10U) {
02296     category = fcZero;
02297     fs = opOK;
02298   } else if ((D.normalizedExponent + 1) * 28738
02299              <= 8651 * (semantics->minExponent - (int) semantics->precision)) {
02300     /* Underflow to zero and round.  */
02301     zeroSignificand();
02302     fs = normalize(rounding_mode, lfLessThanHalf);
02303   } else if ((D.normalizedExponent - 1) * 42039
02304              >= 12655 * semantics->maxExponent) {
02305     /* Overflow and round.  */
02306     fs = handleOverflow(rounding_mode);
02307   } else {
02308     integerPart *decSignificand;
02309     unsigned int partCount;
02310 
02311     /* A tight upper bound on number of bits required to hold an
02312        N-digit decimal integer is N * 196 / 59.  Allocate enough space
02313        to hold the full significand, and an extra part required by
02314        tcMultiplyPart.  */
02315     partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1;
02316     partCount = partCountForBits(1 + 196 * partCount / 59);
02317     decSignificand = new integerPart[partCount + 1];
02318     partCount = 0;
02319 
02320     /* Convert to binary efficiently - we do almost all multiplication
02321        in an integerPart.  When this would overflow do we do a single
02322        bignum multiplication, and then revert again to multiplication
02323        in an integerPart.  */
02324     do {
02325       integerPart decValue, val, multiplier;
02326 
02327       val = 0;
02328       multiplier = 1;
02329 
02330       do {
02331         if (*p == '.')
02332           p++;
02333 
02334         decValue = decDigitValue(*p++);
02335         multiplier *= 10;
02336         val = val * 10 + decValue;
02337         /* The maximum number that can be multiplied by ten with any
02338            digit added without overflowing an integerPart.  */
02339       } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
02340 
02341       /* Multiply out the current part.  */
02342       APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
02343                             partCount, partCount + 1, false);
02344 
02345       /* If we used another part (likely but not guaranteed), increase
02346          the count.  */
02347       if (decSignificand[partCount])
02348         partCount++;
02349     } while (p <= D.lastSigDigit);
02350 
02351     category = fcNormal;
02352     fs = roundSignificandWithExponent(decSignificand, partCount,
02353                                       D.exponent, rounding_mode);
02354 
02355     delete [] decSignificand;
02356   }
02357 
02358   return fs;
02359 }
02360 
02361 APFloat::opStatus
02362 APFloat::convertFromString(const char *p, roundingMode rounding_mode)
02363 {
02364   assertArithmeticOK(*semantics);
02365 
02366   /* Handle a leading minus sign.  */
02367   if(*p == '-')
02368     sign = 1, p++;
02369   else
02370     sign = 0;
02371 
02372   if(p[0] == '0' && (p[1] == 'x' || p[1] == 'X'))
02373     return convertFromHexadecimalString(p + 2, rounding_mode);
02374 
02375   return convertFromDecimalString(p, rounding_mode);
02376 }
02377 
02378 /* Write out a hexadecimal representation of the floating point value
02379    to DST, which must be of sufficient size, in the C99 form
02380    [-]0xh.hhhhp[+-]d.  Return the number of characters written,
02381    excluding the terminating NUL.
02382 
02383    If UPPERCASE, the output is in upper case, otherwise in lower case.
02384 
02385    HEXDIGITS digits appear altogether, rounding the value if
02386    necessary.  If HEXDIGITS is 0, the minimal precision to display the
02387    number precisely is used instead.  If nothing would appear after
02388    the decimal point it is suppressed.
02389 
02390    The decimal exponent is always printed and has at least one digit.
02391    Zero values display an exponent of zero.  Infinities and NaNs
02392    appear as "infinity" or "nan" respectively.
02393 
02394    The above rules are as specified by C99.  There is ambiguity about
02395    what the leading hexadecimal digit should be.  This implementation
02396    uses whatever is necessary so that the exponent is displayed as
02397    stored.  This implies the exponent will fall within the IEEE format
02398    range, and the leading hexadecimal digit will be 0 (for denormals),
02399    1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
02400    any other digits zero).
02401 */
02402 unsigned int
02403 APFloat::convertToHexString(char *dst, unsigned int hexDigits,
02404                             bool upperCase, roundingMode rounding_mode) const
02405 {
02406   char *p;
02407 
02408   assertArithmeticOK(*semantics);
02409 
02410   p = dst;
02411   if (sign)
02412     *dst++ = '-';
02413 
02414   switch (category) {
02415   case fcInfinity:
02416     memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
02417     dst += sizeof infinityL - 1;
02418     break;
02419 
02420   case fcNaN:
02421     memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
02422     dst += sizeof NaNU - 1;
02423     break;
02424 
02425   case fcZero:
02426     *dst++ = '0';
02427     *dst++ = upperCase ? 'X': 'x';
02428     *dst++ = '0';
02429     if (hexDigits > 1) {
02430       *dst++ = '.';
02431       memset (dst, '0', hexDigits - 1);
02432       dst += hexDigits - 1;
02433     }
02434     *dst++ = upperCase ? 'P': 'p';
02435     *dst++ = '0';
02436     break;
02437 
02438   case fcNormal:
02439     dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
02440     break;
02441   }
02442 
02443   *dst = 0;
02444 
02445   return static_cast<unsigned int>(dst - p);
02446 }
02447 
02448 /* Does the hard work of outputting the correctly rounded hexadecimal
02449    form of a normal floating point number with the specified number of
02450    hexadecimal digits.  If HEXDIGITS is zero the minimum number of
02451    digits necessary to print the value precisely is output.  */
02452 char *
02453 APFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
02454                                   bool upperCase,
02455                                   roundingMode rounding_mode) const
02456 {
02457   unsigned int count, valueBits, shift, partsCount, outputDigits;
02458   const char *hexDigitChars;
02459   const integerPart *significand;
02460   char *p;
02461   bool roundUp;
02462 
02463   *dst++ = '0';
02464   *dst++ = upperCase ? 'X': 'x';
02465 
02466   roundUp = false;
02467   hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower;
02468 
02469   significand = significandParts();
02470   partsCount = partCount();
02471 
02472   /* +3 because the first digit only uses the single integer bit, so
02473      we have 3 virtual zero most-significant-bits.  */
02474   valueBits = semantics->precision + 3;
02475   shift = integerPartWidth - valueBits % integerPartWidth;
02476 
02477   /* The natural number of digits required ignoring trailing
02478      insignificant zeroes.  */
02479   outputDigits = (valueBits - significandLSB () + 3) / 4;
02480 
02481   /* hexDigits of zero means use the required number for the
02482      precision.  Otherwise, see if we are truncating.  If we are,
02483      find out if we need to round away from zero.  */
02484   if (hexDigits) {
02485     if (hexDigits < outputDigits) {
02486       /* We are dropping non-zero bits, so need to check how to round.
02487          "bits" is the number of dropped bits.  */
02488       unsigned int bits;
02489       lostFraction fraction;
02490 
02491       bits = valueBits - hexDigits * 4;
02492       fraction = lostFractionThroughTruncation (significand, partsCount, bits);
02493       roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
02494     }
02495     outputDigits = hexDigits;
02496   }
02497 
02498   /* Write the digits consecutively, and start writing in the location
02499      of the hexadecimal point.  We move the most significant digit
02500      left and add the hexadecimal point later.  */
02501   p = ++dst;
02502 
02503   count = (valueBits + integerPartWidth - 1) / integerPartWidth;
02504 
02505   while (outputDigits && count) {
02506     integerPart part;
02507 
02508     /* Put the most significant integerPartWidth bits in "part".  */
02509     if (--count == partsCount)
02510       part = 0;  /* An imaginary higher zero part.  */
02511     else
02512       part = significand[count] << shift;
02513 
02514     if (count && shift)
02515       part |= significand[count - 1] >> (integerPartWidth - shift);
02516 
02517     /* Convert as much of "part" to hexdigits as we can.  */
02518     unsigned int curDigits = integerPartWidth / 4;
02519 
02520     if (curDigits > outputDigits)
02521       curDigits = outputDigits;
02522     dst += partAsHex (dst, part, curDigits, hexDigitChars);
02523     outputDigits -= curDigits;
02524   }
02525 
02526   if (roundUp) {
02527     char *q = dst;
02528 
02529     /* Note that hexDigitChars has a trailing '0'.  */
02530     do {
02531       q--;
02532       *q = hexDigitChars[hexDigitValue (*q) + 1];
02533     } while (*q == '0');
02534     assert (q >= p);
02535   } else {
02536     /* Add trailing zeroes.  */
02537     memset (dst, '0', outputDigits);
02538     dst += outputDigits;
02539   }
02540 
02541   /* Move the most significant digit to before the point, and if there
02542      is something after the decimal point add it.  This must come
02543      after rounding above.  */
02544   p[-1] = p[0];
02545   if (dst -1 == p)
02546     dst--;
02547   else
02548     p[0] = '.';
02549 
02550   /* Finally output the exponent.  */
02551   *dst++ = upperCase ? 'P': 'p';
02552 
02553   return writeSignedDecimal (dst, exponent);
02554 }
02555 
02556 // For good performance it is desirable for different APFloats
02557 // to produce different integers.
02558 uint32_t
02559 APFloat::getHashValue() const
02560 {
02561   if (category==fcZero) return sign<<8 | semantics->precision ;
02562   else if (category==fcInfinity) return sign<<9 | semantics->precision;
02563   else if (category==fcNaN) return 1<<10 | semantics->precision;
02564   else {
02565     uint32_t hash = sign<<11 | semantics->precision | exponent<<12;
02566     const integerPart* p = significandParts();
02567     for (int i=partCount(); i>0; i--, p++)
02568       hash ^= ((uint32_t)*p) ^ (uint32_t)((*p)>>32);
02569     return hash;
02570   }
02571 }
02572 
02573 // Conversion from APFloat to/from host float/double.  It may eventually be
02574 // possible to eliminate these and have everybody deal with APFloats, but that
02575 // will take a while.  This approach will not easily extend to long double.
02576 // Current implementation requires integerPartWidth==64, which is correct at
02577 // the moment but could be made more general.
02578 
02579 // Denormals have exponent minExponent in APFloat, but minExponent-1 in
02580 // the actual IEEE respresentations.  We compensate for that here.
02581 
02582 APInt
02583 APFloat::convertF80LongDoubleAPFloatToAPInt() const
02584 {
02585   assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended);
02586   assert (partCount()==2);
02587 
02588   uint64_t myexponent, mysignificand;
02589 
02590   if (category==fcNormal) {
02591     myexponent = exponent+16383; //bias
02592     mysignificand = significandParts()[0];
02593     if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
02594       myexponent = 0;   // denormal
02595   } else if (category==fcZero) {
02596     myexponent = 0;
02597     mysignificand = 0;
02598   } else if (category==fcInfinity) {
02599     myexponent = 0x7fff;
02600     mysignificand = 0x8000000000000000ULL;
02601   } else {
02602     assert(category == fcNaN && "Unknown category");
02603     myexponent = 0x7fff;
02604     mysignificand = significandParts()[0];
02605   }
02606 
02607   uint64_t words[2];
02608   words[0] =  ((uint64_t)(sign & 1) << 63) |
02609               ((myexponent & 0x7fffLL) <<  48) |
02610               ((mysignificand >>16) & 0xffffffffffffLL);
02611   words[1] = mysignificand & 0xffff;
02612   return APInt(80, 2, words);
02613 }
02614 
02615 APInt
02616 APFloat::convertPPCDoubleDoubleAPFloatToAPInt() const
02617 {
02618   assert(semantics == (const llvm::fltSemantics*)&PPCDoubleDouble);
02619   assert (partCount()==2);
02620 
02621   uint64_t myexponent, mysignificand, myexponent2, mysignificand2;
02622 
02623   if (category==fcNormal) {
02624     myexponent = exponent + 1023; //bias
02625     myexponent2 = exponent2 + 1023;
02626     mysignificand = significandParts()[0];
02627     mysignificand2 = significandParts()[1];
02628     if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
02629       myexponent = 0;   // denormal
02630     if (myexponent2==1 && !(mysignificand2 & 0x10000000000000LL))
02631       myexponent2 = 0;   // denormal
02632   } else if (category==fcZero) {
02633     myexponent = 0;
02634     mysignificand = 0;
02635     myexponent2 = 0;
02636     mysignificand2 = 0;
02637   } else if (category==fcInfinity) {
02638     myexponent = 0x7ff;
02639     myexponent2 = 0;
02640     mysignificand = 0;
02641     mysignificand2 = 0;
02642   } else {
02643     assert(category == fcNaN && "Unknown category");
02644     myexponent = 0x7ff;
02645     mysignificand = significandParts()[0];
02646     myexponent2 = exponent2;
02647     mysignificand2 = significandParts()[1];
02648   }
02649 
02650   uint64_t words[2];
02651   words[0] =  ((uint64_t)(sign & 1) << 63) |
02652               ((myexponent & 0x7ff) <<  52) |
02653               (mysignificand & 0xfffffffffffffLL);
02654   words[1] =  ((uint64_t)(sign2 & 1) << 63) |
02655               ((myexponent2 & 0x7ff) <<  52) |
02656               (mysignificand2 & 0xfffffffffffffLL);
02657   return APInt(128, 2, words);
02658 }
02659 
02660 APInt
02661 APFloat::convertDoubleAPFloatToAPInt() const
02662 {
02663   assert(semantics == (const llvm::fltSemantics*)&IEEEdouble);
02664   assert (partCount()==1);
02665 
02666   uint64_t myexponent, mysignificand;
02667 
02668   if (category==fcNormal) {
02669     myexponent = exponent+1023; //bias
02670     mysignificand = *significandParts();
02671     if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
02672       myexponent = 0;   // denormal
02673   } else if (category==fcZero) {
02674     myexponent = 0;
02675     mysignificand = 0;
02676   } else if (category==fcInfinity) {
02677     myexponent = 0x7ff;
02678     mysignificand = 0;
02679   } else {
02680     assert(category == fcNaN && "Unknown category!");
02681     myexponent = 0x7ff;
02682     mysignificand = *significandParts();
02683   }
02684 
02685   return APInt(64, ((((uint64_t)(sign & 1) << 63) |
02686                      ((myexponent & 0x7ff) <<  52) |
02687                      (mysignificand & 0xfffffffffffffLL))));
02688 }
02689 
02690 APInt
02691 APFloat::convertFloatAPFloatToAPInt() const
02692 {
02693   assert(semantics == (const llvm::fltSemantics*)&IEEEsingle);
02694   assert (partCount()==1);
02695 
02696   uint32_t myexponent, mysignificand;
02697 
02698   if (category==fcNormal) {
02699     myexponent = exponent+127; //bias
02700     mysignificand = (uint32_t)*significandParts();
02701     if (myexponent == 1 && !(mysignificand & 0x800000))
02702       myexponent = 0;   // denormal
02703   } else if (category==fcZero) {
02704     myexponent = 0;
02705     mysignificand = 0;
02706   } else if (category==fcInfinity) {
02707     myexponent = 0xff;
02708     mysignificand = 0;
02709   } else {
02710     assert(category == fcNaN && "Unknown category!");
02711     myexponent = 0xff;
02712     mysignificand = (uint32_t)*significandParts();
02713   }
02714 
02715   return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) |
02716                     (mysignificand & 0x7fffff)));
02717 }
02718 
02719 // This function creates an APInt that is just a bit map of the floating
02720 // point constant as it would appear in memory.  It is not a conversion,
02721 // and treating the result as a normal integer is unlikely to be useful.
02722 
02723 APInt
02724 APFloat::bitcastToAPInt() const
02725 {
02726   if (semantics == (const llvm::fltSemantics*)&IEEEsingle)
02727     return convertFloatAPFloatToAPInt();
02728   
02729   if (semantics == (const llvm::fltSemantics*)&IEEEdouble)
02730     return convertDoubleAPFloatToAPInt();
02731 
02732   if (semantics == (const llvm::fltSemantics*)&PPCDoubleDouble)
02733     return convertPPCDoubleDoubleAPFloatToAPInt();
02734 
02735   assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended &&
02736          "unknown format!");
02737   return convertF80LongDoubleAPFloatToAPInt();
02738 }
02739 
02740 float
02741 APFloat::convertToFloat() const
02742 {
02743   assert(semantics == (const llvm::fltSemantics*)&IEEEsingle);
02744   APInt api = bitcastToAPInt();
02745   return api.bitsToFloat();
02746 }
02747 
02748 double
02749 APFloat::convertToDouble() const
02750 {
02751   assert(semantics == (const llvm::fltSemantics*)&IEEEdouble);
02752   APInt api = bitcastToAPInt();
02753   return api.bitsToDouble();
02754 }
02755 
02756 /// Integer bit is explicit in this format.  Intel hardware (387 and later)
02757 /// does not support these bit patterns:
02758 ///  exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity")
02759 ///  exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN")
02760 ///  exponent = 0, integer bit 1 ("pseudodenormal")
02761 ///  exponent!=0 nor all 1's, integer bit 0 ("unnormal")
02762 /// At the moment, the first two are treated as NaNs, the second two as Normal.
02763 void
02764 APFloat::initFromF80LongDoubleAPInt(const APInt &api)
02765 {
02766   assert(api.getBitWidth()==80);
02767   uint64_t i1 = api.getRawData()[0];
02768   uint64_t i2 = api.getRawData()[1];
02769   uint64_t myexponent = (i1 >> 48) & 0x7fff;
02770   uint64_t mysignificand = ((i1 << 16) &  0xffffffffffff0000ULL) |
02771                           (i2 & 0xffff);
02772 
02773   initialize(&APFloat::x87DoubleExtended);
02774   assert(partCount()==2);
02775 
02776   sign = static_cast<unsigned int>(i1>>63);
02777   if (myexponent==0 && mysignificand==0) {
02778     // exponent, significand meaningless
02779     category = fcZero;
02780   } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
02781     // exponent, significand meaningless
02782     category = fcInfinity;
02783   } else if (myexponent==0x7fff && mysignificand!=0x8000000000000000ULL) {
02784     // exponent meaningless
02785     category = fcNaN;
02786     significandParts()[0] = mysignificand;
02787     significandParts()[1] = 0;
02788   } else {
02789     category = fcNormal;
02790     exponent = myexponent - 16383;
02791     significandParts()[0] = mysignificand;
02792     significandParts()[1] = 0;
02793     if (myexponent==0)          // denormal
02794       exponent = -16382;
02795   }
02796 }
02797 
02798 void
02799 APFloat::initFromPPCDoubleDoubleAPInt(const APInt &api)
02800 {
02801   assert(api.getBitWidth()==128);
02802   uint64_t i1 = api.getRawData()[0];
02803   uint64_t i2 = api.getRawData()[1];
02804   uint64_t myexponent = (i1 >> 52) & 0x7ff;
02805   uint64_t mysignificand = i1 & 0xfffffffffffffLL;
02806   uint64_t myexponent2 = (i2 >> 52) & 0x7ff;
02807   uint64_t mysignificand2 = i2 & 0xfffffffffffffLL;
02808 
02809   initialize(&APFloat::PPCDoubleDouble);
02810   assert(partCount()==2);
02811 
02812   sign = static_cast<unsigned int>(i1>>63);
02813   sign2 = static_cast<unsigned int>(i2>>63);
02814   if (myexponent==0 && mysignificand==0) {
02815     // exponent, significand meaningless
02816     // exponent2 and significand2 are required to be 0; we don't check
02817     category = fcZero;
02818   } else if (myexponent==0x7ff && mysignificand==0) {
02819     // exponent, significand meaningless
02820     // exponent2 and significand2 are required to be 0; we don't check
02821     category = fcInfinity;
02822   } else if (myexponent==0x7ff && mysignificand!=0) {
02823     // exponent meaningless.  So is the whole second word, but keep it 
02824     // for determinism.
02825     category = fcNaN;
02826     exponent2 = myexponent2;
02827     significandParts()[0] = mysignificand;
02828     significandParts()[1] = mysignificand2;
02829   } else {
02830     category = fcNormal;
02831     // Note there is no category2; the second word is treated as if it is
02832     // fcNormal, although it might be something else considered by itself.
02833     exponent = myexponent - 1023;
02834     exponent2 = myexponent2 - 1023;
02835     significandParts()[0] = mysignificand;
02836     significandParts()[1] = mysignificand2;
02837     if (myexponent==0)          // denormal
02838       exponent = -1022;
02839     else
02840       significandParts()[0] |= 0x10000000000000LL;  // integer bit
02841     if (myexponent2==0) 
02842       exponent2 = -1022;
02843     else
02844       significandParts()[1] |= 0x10000000000000LL;  // integer bit
02845   }
02846 }
02847 
02848 void
02849 APFloat::initFromDoubleAPInt(const APInt &api)
02850 {
02851   assert(api.getBitWidth()==64);
02852   uint64_t i = *api.getRawData();
02853   uint64_t myexponent = (i >> 52) & 0x7ff;
02854   uint64_t mysignificand = i & 0xfffffffffffffLL;
02855 
02856   initialize(&APFloat::IEEEdouble);
02857   assert(partCount()==1);
02858 
02859   sign = static_cast<unsigned int>(i>>63);
02860   if (myexponent==0 && mysignificand==0) {
02861     // exponent, significand meaningless
02862     category = fcZero;
02863   } else if (myexponent==0x7ff && mysignificand==0) {
02864     // exponent, significand meaningless
02865     category = fcInfinity;
02866   } else if (myexponent==0x7ff && mysignificand!=0) {
02867     // exponent meaningless
02868     category = fcNaN;
02869     *significandParts() = mysignificand;
02870   } else {
02871     category = fcNormal;
02872     exponent = myexponent - 1023;
02873     *significandParts() = mysignificand;
02874     if (myexponent==0)          // denormal
02875       exponent = -1022;
02876     else
02877       *significandParts() |= 0x10000000000000LL;  // integer bit
02878   }
02879 }
02880 
02881 void
02882 APFloat::initFromFloatAPInt(const APInt & api)
02883 {
02884   assert(api.getBitWidth()==32);
02885   uint32_t i = (uint32_t)*api.getRawData();
02886   uint32_t myexponent = (i >> 23) & 0xff;
02887   uint32_t mysignificand = i & 0x7fffff;
02888 
02889   initialize(&APFloat::IEEEsingle);
02890   assert(partCount()==1);
02891 
02892   sign = i >> 31;
02893   if (myexponent==0 && mysignificand==0) {
02894     // exponent, significand meaningless
02895     category = fcZero;
02896   } else if (myexponent==0xff && mysignificand==0) {
02897     // exponent, significand meaningless
02898     category = fcInfinity;
02899   } else if (myexponent==0xff && mysignificand!=0) {
02900     // sign, exponent, significand meaningless
02901     category = fcNaN;
02902     *significandParts() = mysignificand;
02903   } else {
02904     category = fcNormal;
02905     exponent = myexponent - 127;  //bias
02906     *significandParts() = mysignificand;
02907     if (myexponent==0)    // denormal
02908       exponent = -126;
02909     else
02910       *significandParts() |= 0x800000; // integer bit
02911   }
02912 }
02913 
02914 /// Treat api as containing the bits of a floating point number.  Currently
02915 /// we infer the floating point type from the size of the APInt.  The
02916 /// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful
02917 /// when the size is anything else).
02918 void
02919 APFloat::initFromAPInt(const APInt& api, bool isIEEE)
02920 {
02921   if (api.getBitWidth() == 32)
02922     return initFromFloatAPInt(api);
02923   else if (api.getBitWidth()==64)
02924     return initFromDoubleAPInt(api);
02925   else if (api.getBitWidth()==80)
02926     return initFromF80LongDoubleAPInt(api);
02927   else if (api.getBitWidth()==128 && !isIEEE)
02928     return initFromPPCDoubleDoubleAPInt(api);
02929   else
02930     assert(0);
02931 }
02932 
02933 APFloat::APFloat(const APInt& api, bool isIEEE)
02934 {
02935   initFromAPInt(api, isIEEE);
02936 }
02937 
02938 APFloat::APFloat(float f)
02939 {
02940   APInt api = APInt(32, 0);
02941   initFromAPInt(api.floatToBits(f));
02942 }
02943 
02944 APFloat::APFloat(double d)
02945 {
02946   APInt api = APInt(64, 0);
02947   initFromAPInt(api.doubleToBits(d));
02948 }