[FastISel][AArch64] Refactor float zero materialization. NFCI.
[oota-llvm.git] / lib / Support / APFloat.cpp
1 //===-- APFloat.cpp - Implement APFloat class -----------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements a class to represent arbitrary precision floating
11 // point values and provide a variety of arithmetic operations on them.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APSInt.h"
17 #include "llvm/ADT/FoldingSet.h"
18 #include "llvm/ADT/Hashing.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/MathExtras.h"
23 #include <cstring>
24 #include <limits.h>
25
26 using namespace llvm;
27
28 /// A macro used to combine two fcCategory enums into one key which can be used
29 /// in a switch statement to classify how the interaction of two APFloat's
30 /// categories affects an operation.
31 ///
32 /// TODO: If clang source code is ever allowed to use constexpr in its own
33 /// codebase, change this into a static inline function.
34 #define PackCategoriesIntoKey(_lhs, _rhs) ((_lhs) * 4 + (_rhs))
35
36 /* Assumed in hexadecimal significand parsing, and conversion to
37    hexadecimal strings.  */
38 #define COMPILE_TIME_ASSERT(cond) extern int CTAssert[(cond) ? 1 : -1]
39 COMPILE_TIME_ASSERT(integerPartWidth % 4 == 0);
40
41 namespace llvm {
42
43   /* Represents floating point arithmetic semantics.  */
44   struct fltSemantics {
45     /* The largest E such that 2^E is representable; this matches the
46        definition of IEEE 754.  */
47     APFloat::ExponentType maxExponent;
48
49     /* The smallest E such that 2^E is a normalized number; this
50        matches the definition of IEEE 754.  */
51     APFloat::ExponentType minExponent;
52
53     /* Number of bits in the significand.  This includes the integer
54        bit.  */
55     unsigned int precision;
56   };
57
58   const fltSemantics APFloat::IEEEhalf = { 15, -14, 11 };
59   const fltSemantics APFloat::IEEEsingle = { 127, -126, 24 };
60   const fltSemantics APFloat::IEEEdouble = { 1023, -1022, 53 };
61   const fltSemantics APFloat::IEEEquad = { 16383, -16382, 113 };
62   const fltSemantics APFloat::x87DoubleExtended = { 16383, -16382, 64 };
63   const fltSemantics APFloat::Bogus = { 0, 0, 0 };
64
65   /* The PowerPC format consists of two doubles.  It does not map cleanly
66      onto the usual format above.  It is approximated using twice the
67      mantissa bits.  Note that for exponents near the double minimum,
68      we no longer can represent the full 106 mantissa bits, so those
69      will be treated as denormal numbers.
70
71      FIXME: While this approximation is equivalent to what GCC uses for
72      compile-time arithmetic on PPC double-double numbers, it is not able
73      to represent all possible values held by a PPC double-double number,
74      for example: (long double) 1.0 + (long double) 0x1p-106
75      Should this be replaced by a full emulation of PPC double-double?  */
76   const fltSemantics APFloat::PPCDoubleDouble = { 1023, -1022 + 53, 53 + 53 };
77
78   /* A tight upper bound on number of parts required to hold the value
79      pow(5, power) is
80
81        power * 815 / (351 * integerPartWidth) + 1
82
83      However, whilst the result may require only this many parts,
84      because we are multiplying two values to get it, the
85      multiplication may require an extra part with the excess part
86      being zero (consider the trivial case of 1 * 1, tcFullMultiply
87      requires two parts to hold the single-part result).  So we add an
88      extra one to guarantee enough space whilst multiplying.  */
89   const unsigned int maxExponent = 16383;
90   const unsigned int maxPrecision = 113;
91   const unsigned int maxPowerOfFiveExponent = maxExponent + maxPrecision - 1;
92   const unsigned int maxPowerOfFiveParts = 2 + ((maxPowerOfFiveExponent * 815)
93                                                 / (351 * integerPartWidth));
94 }
95
96 /* A bunch of private, handy routines.  */
97
98 static inline unsigned int
99 partCountForBits(unsigned int bits)
100 {
101   return ((bits) + integerPartWidth - 1) / integerPartWidth;
102 }
103
104 /* Returns 0U-9U.  Return values >= 10U are not digits.  */
105 static inline unsigned int
106 decDigitValue(unsigned int c)
107 {
108   return c - '0';
109 }
110
111 /* Return the value of a decimal exponent of the form
112    [+-]ddddddd.
113
114    If the exponent overflows, returns a large exponent with the
115    appropriate sign.  */
116 static int
117 readExponent(StringRef::iterator begin, StringRef::iterator end)
118 {
119   bool isNegative;
120   unsigned int absExponent;
121   const unsigned int overlargeExponent = 24000;  /* FIXME.  */
122   StringRef::iterator p = begin;
123
124   assert(p != end && "Exponent has no digits");
125
126   isNegative = (*p == '-');
127   if (*p == '-' || *p == '+') {
128     p++;
129     assert(p != end && "Exponent has no digits");
130   }
131
132   absExponent = decDigitValue(*p++);
133   assert(absExponent < 10U && "Invalid character in exponent");
134
135   for (; p != end; ++p) {
136     unsigned int value;
137
138     value = decDigitValue(*p);
139     assert(value < 10U && "Invalid character in exponent");
140
141     value += absExponent * 10;
142     if (absExponent >= overlargeExponent) {
143       absExponent = overlargeExponent;
144       p = end;  /* outwit assert below */
145       break;
146     }
147     absExponent = value;
148   }
149
150   assert(p == end && "Invalid exponent in exponent");
151
152   if (isNegative)
153     return -(int) absExponent;
154   else
155     return (int) absExponent;
156 }
157
158 /* This is ugly and needs cleaning up, but I don't immediately see
159    how whilst remaining safe.  */
160 static int
161 totalExponent(StringRef::iterator p, StringRef::iterator end,
162               int exponentAdjustment)
163 {
164   int unsignedExponent;
165   bool negative, overflow;
166   int exponent = 0;
167
168   assert(p != end && "Exponent has no digits");
169
170   negative = *p == '-';
171   if (*p == '-' || *p == '+') {
172     p++;
173     assert(p != end && "Exponent has no digits");
174   }
175
176   unsignedExponent = 0;
177   overflow = false;
178   for (; p != end; ++p) {
179     unsigned int value;
180
181     value = decDigitValue(*p);
182     assert(value < 10U && "Invalid character in exponent");
183
184     unsignedExponent = unsignedExponent * 10 + value;
185     if (unsignedExponent > 32767) {
186       overflow = true;
187       break;
188     }
189   }
190
191   if (exponentAdjustment > 32767 || exponentAdjustment < -32768)
192     overflow = true;
193
194   if (!overflow) {
195     exponent = unsignedExponent;
196     if (negative)
197       exponent = -exponent;
198     exponent += exponentAdjustment;
199     if (exponent > 32767 || exponent < -32768)
200       overflow = true;
201   }
202
203   if (overflow)
204     exponent = negative ? -32768: 32767;
205
206   return exponent;
207 }
208
209 static StringRef::iterator
210 skipLeadingZeroesAndAnyDot(StringRef::iterator begin, StringRef::iterator end,
211                            StringRef::iterator *dot)
212 {
213   StringRef::iterator p = begin;
214   *dot = end;
215   while (*p == '0' && p != end)
216     p++;
217
218   if (*p == '.') {
219     *dot = p++;
220
221     assert(end - begin != 1 && "Significand has no digits");
222
223     while (*p == '0' && p != end)
224       p++;
225   }
226
227   return p;
228 }
229
230 /* Given a normal decimal floating point number of the form
231
232      dddd.dddd[eE][+-]ddd
233
234    where the decimal point and exponent are optional, fill out the
235    structure D.  Exponent is appropriate if the significand is
236    treated as an integer, and normalizedExponent if the significand
237    is taken to have the decimal point after a single leading
238    non-zero digit.
239
240    If the value is zero, V->firstSigDigit points to a non-digit, and
241    the return exponent is zero.
242 */
243 struct decimalInfo {
244   const char *firstSigDigit;
245   const char *lastSigDigit;
246   int exponent;
247   int normalizedExponent;
248 };
249
250 static void
251 interpretDecimal(StringRef::iterator begin, StringRef::iterator end,
252                  decimalInfo *D)
253 {
254   StringRef::iterator dot = end;
255   StringRef::iterator p = skipLeadingZeroesAndAnyDot (begin, end, &dot);
256
257   D->firstSigDigit = p;
258   D->exponent = 0;
259   D->normalizedExponent = 0;
260
261   for (; p != end; ++p) {
262     if (*p == '.') {
263       assert(dot == end && "String contains multiple dots");
264       dot = p++;
265       if (p == end)
266         break;
267     }
268     if (decDigitValue(*p) >= 10U)
269       break;
270   }
271
272   if (p != end) {
273     assert((*p == 'e' || *p == 'E') && "Invalid character in significand");
274     assert(p != begin && "Significand has no digits");
275     assert((dot == end || p - begin != 1) && "Significand has no digits");
276
277     /* p points to the first non-digit in the string */
278     D->exponent = readExponent(p + 1, end);
279
280     /* Implied decimal point?  */
281     if (dot == end)
282       dot = p;
283   }
284
285   /* If number is all zeroes accept any exponent.  */
286   if (p != D->firstSigDigit) {
287     /* Drop insignificant trailing zeroes.  */
288     if (p != begin) {
289       do
290         do
291           p--;
292         while (p != begin && *p == '0');
293       while (p != begin && *p == '.');
294     }
295
296     /* Adjust the exponents for any decimal point.  */
297     D->exponent += static_cast<APFloat::ExponentType>((dot - p) - (dot > p));
298     D->normalizedExponent = (D->exponent +
299               static_cast<APFloat::ExponentType>((p - D->firstSigDigit)
300                                       - (dot > D->firstSigDigit && dot < p)));
301   }
302
303   D->lastSigDigit = p;
304 }
305
306 /* Return the trailing fraction of a hexadecimal number.
307    DIGITVALUE is the first hex digit of the fraction, P points to
308    the next digit.  */
309 static lostFraction
310 trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end,
311                             unsigned int digitValue)
312 {
313   unsigned int hexDigit;
314
315   /* If the first trailing digit isn't 0 or 8 we can work out the
316      fraction immediately.  */
317   if (digitValue > 8)
318     return lfMoreThanHalf;
319   else if (digitValue < 8 && digitValue > 0)
320     return lfLessThanHalf;
321
322   // Otherwise we need to find the first non-zero digit.
323   while (p != end && (*p == '0' || *p == '.'))
324     p++;
325
326   assert(p != end && "Invalid trailing hexadecimal fraction!");
327
328   hexDigit = hexDigitValue(*p);
329
330   /* If we ran off the end it is exactly zero or one-half, otherwise
331      a little more.  */
332   if (hexDigit == -1U)
333     return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
334   else
335     return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf;
336 }
337
338 /* Return the fraction lost were a bignum truncated losing the least
339    significant BITS bits.  */
340 static lostFraction
341 lostFractionThroughTruncation(const integerPart *parts,
342                               unsigned int partCount,
343                               unsigned int bits)
344 {
345   unsigned int lsb;
346
347   lsb = APInt::tcLSB(parts, partCount);
348
349   /* Note this is guaranteed true if bits == 0, or LSB == -1U.  */
350   if (bits <= lsb)
351     return lfExactlyZero;
352   if (bits == lsb + 1)
353     return lfExactlyHalf;
354   if (bits <= partCount * integerPartWidth &&
355       APInt::tcExtractBit(parts, bits - 1))
356     return lfMoreThanHalf;
357
358   return lfLessThanHalf;
359 }
360
361 /* Shift DST right BITS bits noting lost fraction.  */
362 static lostFraction
363 shiftRight(integerPart *dst, unsigned int parts, unsigned int bits)
364 {
365   lostFraction lost_fraction;
366
367   lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
368
369   APInt::tcShiftRight(dst, parts, bits);
370
371   return lost_fraction;
372 }
373
374 /* Combine the effect of two lost fractions.  */
375 static lostFraction
376 combineLostFractions(lostFraction moreSignificant,
377                      lostFraction lessSignificant)
378 {
379   if (lessSignificant != lfExactlyZero) {
380     if (moreSignificant == lfExactlyZero)
381       moreSignificant = lfLessThanHalf;
382     else if (moreSignificant == lfExactlyHalf)
383       moreSignificant = lfMoreThanHalf;
384   }
385
386   return moreSignificant;
387 }
388
389 /* The error from the true value, in half-ulps, on multiplying two
390    floating point numbers, which differ from the value they
391    approximate by at most HUE1 and HUE2 half-ulps, is strictly less
392    than the returned value.
393
394    See "How to Read Floating Point Numbers Accurately" by William D
395    Clinger.  */
396 static unsigned int
397 HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
398 {
399   assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
400
401   if (HUerr1 + HUerr2 == 0)
402     return inexactMultiply * 2;  /* <= inexactMultiply half-ulps.  */
403   else
404     return inexactMultiply + 2 * (HUerr1 + HUerr2);
405 }
406
407 /* The number of ulps from the boundary (zero, or half if ISNEAREST)
408    when the least significant BITS are truncated.  BITS cannot be
409    zero.  */
410 static integerPart
411 ulpsFromBoundary(const integerPart *parts, unsigned int bits, bool isNearest)
412 {
413   unsigned int count, partBits;
414   integerPart part, boundary;
415
416   assert(bits != 0);
417
418   bits--;
419   count = bits / integerPartWidth;
420   partBits = bits % integerPartWidth + 1;
421
422   part = parts[count] & (~(integerPart) 0 >> (integerPartWidth - partBits));
423
424   if (isNearest)
425     boundary = (integerPart) 1 << (partBits - 1);
426   else
427     boundary = 0;
428
429   if (count == 0) {
430     if (part - boundary <= boundary - part)
431       return part - boundary;
432     else
433       return boundary - part;
434   }
435
436   if (part == boundary) {
437     while (--count)
438       if (parts[count])
439         return ~(integerPart) 0; /* A lot.  */
440
441     return parts[0];
442   } else if (part == boundary - 1) {
443     while (--count)
444       if (~parts[count])
445         return ~(integerPart) 0; /* A lot.  */
446
447     return -parts[0];
448   }
449
450   return ~(integerPart) 0; /* A lot.  */
451 }
452
453 /* Place pow(5, power) in DST, and return the number of parts used.
454    DST must be at least one part larger than size of the answer.  */
455 static unsigned int
456 powerOf5(integerPart *dst, unsigned int power)
457 {
458   static const integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125,
459                                                   15625, 78125 };
460   integerPart pow5s[maxPowerOfFiveParts * 2 + 5];
461   pow5s[0] = 78125 * 5;
462
463   unsigned int partsCount[16] = { 1 };
464   integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5;
465   unsigned int result;
466   assert(power <= maxExponent);
467
468   p1 = dst;
469   p2 = scratch;
470
471   *p1 = firstEightPowers[power & 7];
472   power >>= 3;
473
474   result = 1;
475   pow5 = pow5s;
476
477   for (unsigned int n = 0; power; power >>= 1, n++) {
478     unsigned int pc;
479
480     pc = partsCount[n];
481
482     /* Calculate pow(5,pow(2,n+3)) if we haven't yet.  */
483     if (pc == 0) {
484       pc = partsCount[n - 1];
485       APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc);
486       pc *= 2;
487       if (pow5[pc - 1] == 0)
488         pc--;
489       partsCount[n] = pc;
490     }
491
492     if (power & 1) {
493       integerPart *tmp;
494
495       APInt::tcFullMultiply(p2, p1, pow5, result, pc);
496       result += pc;
497       if (p2[result - 1] == 0)
498         result--;
499
500       /* Now result is in p1 with partsCount parts and p2 is scratch
501          space.  */
502       tmp = p1, p1 = p2, p2 = tmp;
503     }
504
505     pow5 += pc;
506   }
507
508   if (p1 != dst)
509     APInt::tcAssign(dst, p1, result);
510
511   return result;
512 }
513
514 /* Zero at the end to avoid modular arithmetic when adding one; used
515    when rounding up during hexadecimal output.  */
516 static const char hexDigitsLower[] = "0123456789abcdef0";
517 static const char hexDigitsUpper[] = "0123456789ABCDEF0";
518 static const char infinityL[] = "infinity";
519 static const char infinityU[] = "INFINITY";
520 static const char NaNL[] = "nan";
521 static const char NaNU[] = "NAN";
522
523 /* Write out an integerPart in hexadecimal, starting with the most
524    significant nibble.  Write out exactly COUNT hexdigits, return
525    COUNT.  */
526 static unsigned int
527 partAsHex (char *dst, integerPart part, unsigned int count,
528            const char *hexDigitChars)
529 {
530   unsigned int result = count;
531
532   assert(count != 0 && count <= integerPartWidth / 4);
533
534   part >>= (integerPartWidth - 4 * count);
535   while (count--) {
536     dst[count] = hexDigitChars[part & 0xf];
537     part >>= 4;
538   }
539
540   return result;
541 }
542
543 /* Write out an unsigned decimal integer.  */
544 static char *
545 writeUnsignedDecimal (char *dst, unsigned int n)
546 {
547   char buff[40], *p;
548
549   p = buff;
550   do
551     *p++ = '0' + n % 10;
552   while (n /= 10);
553
554   do
555     *dst++ = *--p;
556   while (p != buff);
557
558   return dst;
559 }
560
561 /* Write out a signed decimal integer.  */
562 static char *
563 writeSignedDecimal (char *dst, int value)
564 {
565   if (value < 0) {
566     *dst++ = '-';
567     dst = writeUnsignedDecimal(dst, -(unsigned) value);
568   } else
569     dst = writeUnsignedDecimal(dst, value);
570
571   return dst;
572 }
573
574 /* Constructors.  */
575 void
576 APFloat::initialize(const fltSemantics *ourSemantics)
577 {
578   unsigned int count;
579
580   semantics = ourSemantics;
581   count = partCount();
582   if (count > 1)
583     significand.parts = new integerPart[count];
584 }
585
586 void
587 APFloat::freeSignificand()
588 {
589   if (needsCleanup())
590     delete [] significand.parts;
591 }
592
593 void
594 APFloat::assign(const APFloat &rhs)
595 {
596   assert(semantics == rhs.semantics);
597
598   sign = rhs.sign;
599   category = rhs.category;
600   exponent = rhs.exponent;
601   if (isFiniteNonZero() || category == fcNaN)
602     copySignificand(rhs);
603 }
604
605 void
606 APFloat::copySignificand(const APFloat &rhs)
607 {
608   assert(isFiniteNonZero() || category == fcNaN);
609   assert(rhs.partCount() >= partCount());
610
611   APInt::tcAssign(significandParts(), rhs.significandParts(),
612                   partCount());
613 }
614
615 /* Make this number a NaN, with an arbitrary but deterministic value
616    for the significand.  If double or longer, this is a signalling NaN,
617    which may not be ideal.  If float, this is QNaN(0).  */
618 void APFloat::makeNaN(bool SNaN, bool Negative, const APInt *fill)
619 {
620   category = fcNaN;
621   sign = Negative;
622
623   integerPart *significand = significandParts();
624   unsigned numParts = partCount();
625
626   // Set the significand bits to the fill.
627   if (!fill || fill->getNumWords() < numParts)
628     APInt::tcSet(significand, 0, numParts);
629   if (fill) {
630     APInt::tcAssign(significand, fill->getRawData(),
631                     std::min(fill->getNumWords(), numParts));
632
633     // Zero out the excess bits of the significand.
634     unsigned bitsToPreserve = semantics->precision - 1;
635     unsigned part = bitsToPreserve / 64;
636     bitsToPreserve %= 64;
637     significand[part] &= ((1ULL << bitsToPreserve) - 1);
638     for (part++; part != numParts; ++part)
639       significand[part] = 0;
640   }
641
642   unsigned QNaNBit = semantics->precision - 2;
643
644   if (SNaN) {
645     // We always have to clear the QNaN bit to make it an SNaN.
646     APInt::tcClearBit(significand, QNaNBit);
647
648     // If there are no bits set in the payload, we have to set
649     // *something* to make it a NaN instead of an infinity;
650     // conventionally, this is the next bit down from the QNaN bit.
651     if (APInt::tcIsZero(significand, numParts))
652       APInt::tcSetBit(significand, QNaNBit - 1);
653   } else {
654     // We always have to set the QNaN bit to make it a QNaN.
655     APInt::tcSetBit(significand, QNaNBit);
656   }
657
658   // For x87 extended precision, we want to make a NaN, not a
659   // pseudo-NaN.  Maybe we should expose the ability to make
660   // pseudo-NaNs?
661   if (semantics == &APFloat::x87DoubleExtended)
662     APInt::tcSetBit(significand, QNaNBit + 1);
663 }
664
665 APFloat APFloat::makeNaN(const fltSemantics &Sem, bool SNaN, bool Negative,
666                          const APInt *fill) {
667   APFloat value(Sem, uninitialized);
668   value.makeNaN(SNaN, Negative, fill);
669   return value;
670 }
671
672 APFloat &
673 APFloat::operator=(const APFloat &rhs)
674 {
675   if (this != &rhs) {
676     if (semantics != rhs.semantics) {
677       freeSignificand();
678       initialize(rhs.semantics);
679     }
680     assign(rhs);
681   }
682
683   return *this;
684 }
685
686 APFloat &
687 APFloat::operator=(APFloat &&rhs) {
688   freeSignificand();
689
690   semantics = rhs.semantics;
691   significand = rhs.significand;
692   exponent = rhs.exponent;
693   category = rhs.category;
694   sign = rhs.sign;
695
696   rhs.semantics = &Bogus;
697   return *this;
698 }
699
700 bool
701 APFloat::isDenormal() const {
702   return isFiniteNonZero() && (exponent == semantics->minExponent) &&
703          (APInt::tcExtractBit(significandParts(), 
704                               semantics->precision - 1) == 0);
705 }
706
707 bool
708 APFloat::isSmallest() const {
709   // The smallest number by magnitude in our format will be the smallest
710   // denormal, i.e. the floating point number with exponent being minimum
711   // exponent and significand bitwise equal to 1 (i.e. with MSB equal to 0).
712   return isFiniteNonZero() && exponent == semantics->minExponent &&
713     significandMSB() == 0;
714 }
715
716 bool APFloat::isSignificandAllOnes() const {
717   // Test if the significand excluding the integral bit is all ones. This allows
718   // us to test for binade boundaries.
719   const integerPart *Parts = significandParts();
720   const unsigned PartCount = partCount();
721   for (unsigned i = 0; i < PartCount - 1; i++)
722     if (~Parts[i])
723       return false;
724
725   // Set the unused high bits to all ones when we compare.
726   const unsigned NumHighBits =
727     PartCount*integerPartWidth - semantics->precision + 1;
728   assert(NumHighBits <= integerPartWidth && "Can not have more high bits to "
729          "fill than integerPartWidth");
730   const integerPart HighBitFill =
731     ~integerPart(0) << (integerPartWidth - NumHighBits);
732   if (~(Parts[PartCount - 1] | HighBitFill))
733     return false;
734
735   return true;
736 }
737
738 bool APFloat::isSignificandAllZeros() const {
739   // Test if the significand excluding the integral bit is all zeros. This
740   // allows us to test for binade boundaries.
741   const integerPart *Parts = significandParts();
742   const unsigned PartCount = partCount();
743
744   for (unsigned i = 0; i < PartCount - 1; i++)
745     if (Parts[i])
746       return false;
747
748   const unsigned NumHighBits =
749     PartCount*integerPartWidth - semantics->precision + 1;
750   assert(NumHighBits <= integerPartWidth && "Can not have more high bits to "
751          "clear than integerPartWidth");
752   const integerPart HighBitMask = ~integerPart(0) >> NumHighBits;
753
754   if (Parts[PartCount - 1] & HighBitMask)
755     return false;
756
757   return true;
758 }
759
760 bool
761 APFloat::isLargest() const {
762   // The largest number by magnitude in our format will be the floating point
763   // number with maximum exponent and with significand that is all ones.
764   return isFiniteNonZero() && exponent == semantics->maxExponent
765     && isSignificandAllOnes();
766 }
767
768 bool
769 APFloat::bitwiseIsEqual(const APFloat &rhs) const {
770   if (this == &rhs)
771     return true;
772   if (semantics != rhs.semantics ||
773       category != rhs.category ||
774       sign != rhs.sign)
775     return false;
776   if (category==fcZero || category==fcInfinity)
777     return true;
778   else if (isFiniteNonZero() && exponent!=rhs.exponent)
779     return false;
780   else {
781     int i= partCount();
782     const integerPart* p=significandParts();
783     const integerPart* q=rhs.significandParts();
784     for (; i>0; i--, p++, q++) {
785       if (*p != *q)
786         return false;
787     }
788     return true;
789   }
790 }
791
792 APFloat::APFloat(const fltSemantics &ourSemantics, integerPart value) {
793   initialize(&ourSemantics);
794   sign = 0;
795   category = fcNormal;
796   zeroSignificand();
797   exponent = ourSemantics.precision - 1;
798   significandParts()[0] = value;
799   normalize(rmNearestTiesToEven, lfExactlyZero);
800 }
801
802 APFloat::APFloat(const fltSemantics &ourSemantics) {
803   initialize(&ourSemantics);
804   category = fcZero;
805   sign = false;
806 }
807
808 APFloat::APFloat(const fltSemantics &ourSemantics, uninitializedTag tag) {
809   // Allocates storage if necessary but does not initialize it.
810   initialize(&ourSemantics);
811 }
812
813 APFloat::APFloat(const fltSemantics &ourSemantics, StringRef text) {
814   initialize(&ourSemantics);
815   convertFromString(text, rmNearestTiesToEven);
816 }
817
818 APFloat::APFloat(const APFloat &rhs) {
819   initialize(rhs.semantics);
820   assign(rhs);
821 }
822
823 APFloat::APFloat(APFloat &&rhs) : semantics(&Bogus) {
824   *this = std::move(rhs);
825 }
826
827 APFloat::~APFloat()
828 {
829   freeSignificand();
830 }
831
832 // Profile - This method 'profiles' an APFloat for use with FoldingSet.
833 void APFloat::Profile(FoldingSetNodeID& ID) const {
834   ID.Add(bitcastToAPInt());
835 }
836
837 unsigned int
838 APFloat::partCount() const
839 {
840   return partCountForBits(semantics->precision + 1);
841 }
842
843 unsigned int
844 APFloat::semanticsPrecision(const fltSemantics &semantics)
845 {
846   return semantics.precision;
847 }
848
849 const integerPart *
850 APFloat::significandParts() const
851 {
852   return const_cast<APFloat *>(this)->significandParts();
853 }
854
855 integerPart *
856 APFloat::significandParts()
857 {
858   if (partCount() > 1)
859     return significand.parts;
860   else
861     return &significand.part;
862 }
863
864 void
865 APFloat::zeroSignificand()
866 {
867   APInt::tcSet(significandParts(), 0, partCount());
868 }
869
870 /* Increment an fcNormal floating point number's significand.  */
871 void
872 APFloat::incrementSignificand()
873 {
874   integerPart carry;
875
876   carry = APInt::tcIncrement(significandParts(), partCount());
877
878   /* Our callers should never cause us to overflow.  */
879   assert(carry == 0);
880   (void)carry;
881 }
882
883 /* Add the significand of the RHS.  Returns the carry flag.  */
884 integerPart
885 APFloat::addSignificand(const APFloat &rhs)
886 {
887   integerPart *parts;
888
889   parts = significandParts();
890
891   assert(semantics == rhs.semantics);
892   assert(exponent == rhs.exponent);
893
894   return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
895 }
896
897 /* Subtract the significand of the RHS with a borrow flag.  Returns
898    the borrow flag.  */
899 integerPart
900 APFloat::subtractSignificand(const APFloat &rhs, integerPart borrow)
901 {
902   integerPart *parts;
903
904   parts = significandParts();
905
906   assert(semantics == rhs.semantics);
907   assert(exponent == rhs.exponent);
908
909   return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
910                            partCount());
911 }
912
913 /* Multiply the significand of the RHS.  If ADDEND is non-NULL, add it
914    on to the full-precision result of the multiplication.  Returns the
915    lost fraction.  */
916 lostFraction
917 APFloat::multiplySignificand(const APFloat &rhs, const APFloat *addend)
918 {
919   unsigned int omsb;        // One, not zero, based MSB.
920   unsigned int partsCount, newPartsCount, precision;
921   integerPart *lhsSignificand;
922   integerPart scratch[4];
923   integerPart *fullSignificand;
924   lostFraction lost_fraction;
925   bool ignored;
926
927   assert(semantics == rhs.semantics);
928
929   precision = semantics->precision;
930   newPartsCount = partCountForBits(precision * 2);
931
932   if (newPartsCount > 4)
933     fullSignificand = new integerPart[newPartsCount];
934   else
935     fullSignificand = scratch;
936
937   lhsSignificand = significandParts();
938   partsCount = partCount();
939
940   APInt::tcFullMultiply(fullSignificand, lhsSignificand,
941                         rhs.significandParts(), partsCount, partsCount);
942
943   lost_fraction = lfExactlyZero;
944   omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
945   exponent += rhs.exponent;
946
947   // Assume the operands involved in the multiplication are single-precision
948   // FP, and the two multiplicants are:
949   //   *this = a23 . a22 ... a0 * 2^e1
950   //     rhs = b23 . b22 ... b0 * 2^e2
951   // the result of multiplication is:
952   //   *this = c47 c46 . c45 ... c0 * 2^(e1+e2)
953   // Note that there are two significant bits at the left-hand side of the 
954   // radix point. Move the radix point toward left by one bit, and adjust
955   // exponent accordingly.
956   exponent += 1;
957
958   if (addend) {
959     // The intermediate result of the multiplication has "2 * precision" 
960     // signicant bit; adjust the addend to be consistent with mul result.
961     //
962     Significand savedSignificand = significand;
963     const fltSemantics *savedSemantics = semantics;
964     fltSemantics extendedSemantics;
965     opStatus status;
966     unsigned int extendedPrecision;
967
968     /* Normalize our MSB.  */
969     extendedPrecision = 2 * precision;
970     if (omsb != extendedPrecision) {
971       assert(extendedPrecision > omsb);
972       APInt::tcShiftLeft(fullSignificand, newPartsCount,
973                          extendedPrecision - omsb);
974       exponent -= extendedPrecision - omsb;
975     }
976
977     /* Create new semantics.  */
978     extendedSemantics = *semantics;
979     extendedSemantics.precision = extendedPrecision;
980
981     if (newPartsCount == 1)
982       significand.part = fullSignificand[0];
983     else
984       significand.parts = fullSignificand;
985     semantics = &extendedSemantics;
986
987     APFloat extendedAddend(*addend);
988     status = extendedAddend.convert(extendedSemantics, rmTowardZero, &ignored);
989     assert(status == opOK);
990     (void)status;
991     lost_fraction = addOrSubtractSignificand(extendedAddend, false);
992
993     /* Restore our state.  */
994     if (newPartsCount == 1)
995       fullSignificand[0] = significand.part;
996     significand = savedSignificand;
997     semantics = savedSemantics;
998
999     omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
1000   }
1001
1002   // Convert the result having "2 * precision" significant-bits back to the one
1003   // having "precision" significant-bits. First, move the radix point from 
1004   // poision "2*precision - 1" to "precision - 1". The exponent need to be
1005   // adjusted by "2*precision - 1" - "precision - 1" = "precision".
1006   exponent -= precision;
1007
1008   // In case MSB resides at the left-hand side of radix point, shift the
1009   // mantissa right by some amount to make sure the MSB reside right before
1010   // the radix point (i.e. "MSB . rest-significant-bits").
1011   //
1012   // Note that the result is not normalized when "omsb < precision". So, the
1013   // caller needs to call APFloat::normalize() if normalized value is expected.
1014   if (omsb > precision) {
1015     unsigned int bits, significantParts;
1016     lostFraction lf;
1017
1018     bits = omsb - precision;
1019     significantParts = partCountForBits(omsb);
1020     lf = shiftRight(fullSignificand, significantParts, bits);
1021     lost_fraction = combineLostFractions(lf, lost_fraction);
1022     exponent += bits;
1023   }
1024
1025   APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
1026
1027   if (newPartsCount > 4)
1028     delete [] fullSignificand;
1029
1030   return lost_fraction;
1031 }
1032
1033 /* Multiply the significands of LHS and RHS to DST.  */
1034 lostFraction
1035 APFloat::divideSignificand(const APFloat &rhs)
1036 {
1037   unsigned int bit, i, partsCount;
1038   const integerPart *rhsSignificand;
1039   integerPart *lhsSignificand, *dividend, *divisor;
1040   integerPart scratch[4];
1041   lostFraction lost_fraction;
1042
1043   assert(semantics == rhs.semantics);
1044
1045   lhsSignificand = significandParts();
1046   rhsSignificand = rhs.significandParts();
1047   partsCount = partCount();
1048
1049   if (partsCount > 2)
1050     dividend = new integerPart[partsCount * 2];
1051   else
1052     dividend = scratch;
1053
1054   divisor = dividend + partsCount;
1055
1056   /* Copy the dividend and divisor as they will be modified in-place.  */
1057   for (i = 0; i < partsCount; i++) {
1058     dividend[i] = lhsSignificand[i];
1059     divisor[i] = rhsSignificand[i];
1060     lhsSignificand[i] = 0;
1061   }
1062
1063   exponent -= rhs.exponent;
1064
1065   unsigned int precision = semantics->precision;
1066
1067   /* Normalize the divisor.  */
1068   bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
1069   if (bit) {
1070     exponent += bit;
1071     APInt::tcShiftLeft(divisor, partsCount, bit);
1072   }
1073
1074   /* Normalize the dividend.  */
1075   bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
1076   if (bit) {
1077     exponent -= bit;
1078     APInt::tcShiftLeft(dividend, partsCount, bit);
1079   }
1080
1081   /* Ensure the dividend >= divisor initially for the loop below.
1082      Incidentally, this means that the division loop below is
1083      guaranteed to set the integer bit to one.  */
1084   if (APInt::tcCompare(dividend, divisor, partsCount) < 0) {
1085     exponent--;
1086     APInt::tcShiftLeft(dividend, partsCount, 1);
1087     assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
1088   }
1089
1090   /* Long division.  */
1091   for (bit = precision; bit; bit -= 1) {
1092     if (APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
1093       APInt::tcSubtract(dividend, divisor, 0, partsCount);
1094       APInt::tcSetBit(lhsSignificand, bit - 1);
1095     }
1096
1097     APInt::tcShiftLeft(dividend, partsCount, 1);
1098   }
1099
1100   /* Figure out the lost fraction.  */
1101   int cmp = APInt::tcCompare(dividend, divisor, partsCount);
1102
1103   if (cmp > 0)
1104     lost_fraction = lfMoreThanHalf;
1105   else if (cmp == 0)
1106     lost_fraction = lfExactlyHalf;
1107   else if (APInt::tcIsZero(dividend, partsCount))
1108     lost_fraction = lfExactlyZero;
1109   else
1110     lost_fraction = lfLessThanHalf;
1111
1112   if (partsCount > 2)
1113     delete [] dividend;
1114
1115   return lost_fraction;
1116 }
1117
1118 unsigned int
1119 APFloat::significandMSB() const
1120 {
1121   return APInt::tcMSB(significandParts(), partCount());
1122 }
1123
1124 unsigned int
1125 APFloat::significandLSB() const
1126 {
1127   return APInt::tcLSB(significandParts(), partCount());
1128 }
1129
1130 /* Note that a zero result is NOT normalized to fcZero.  */
1131 lostFraction
1132 APFloat::shiftSignificandRight(unsigned int bits)
1133 {
1134   /* Our exponent should not overflow.  */
1135   assert((ExponentType) (exponent + bits) >= exponent);
1136
1137   exponent += bits;
1138
1139   return shiftRight(significandParts(), partCount(), bits);
1140 }
1141
1142 /* Shift the significand left BITS bits, subtract BITS from its exponent.  */
1143 void
1144 APFloat::shiftSignificandLeft(unsigned int bits)
1145 {
1146   assert(bits < semantics->precision);
1147
1148   if (bits) {
1149     unsigned int partsCount = partCount();
1150
1151     APInt::tcShiftLeft(significandParts(), partsCount, bits);
1152     exponent -= bits;
1153
1154     assert(!APInt::tcIsZero(significandParts(), partsCount));
1155   }
1156 }
1157
1158 APFloat::cmpResult
1159 APFloat::compareAbsoluteValue(const APFloat &rhs) const
1160 {
1161   int compare;
1162
1163   assert(semantics == rhs.semantics);
1164   assert(isFiniteNonZero());
1165   assert(rhs.isFiniteNonZero());
1166
1167   compare = exponent - rhs.exponent;
1168
1169   /* If exponents are equal, do an unsigned bignum comparison of the
1170      significands.  */
1171   if (compare == 0)
1172     compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
1173                                partCount());
1174
1175   if (compare > 0)
1176     return cmpGreaterThan;
1177   else if (compare < 0)
1178     return cmpLessThan;
1179   else
1180     return cmpEqual;
1181 }
1182
1183 /* Handle overflow.  Sign is preserved.  We either become infinity or
1184    the largest finite number.  */
1185 APFloat::opStatus
1186 APFloat::handleOverflow(roundingMode rounding_mode)
1187 {
1188   /* Infinity?  */
1189   if (rounding_mode == rmNearestTiesToEven ||
1190       rounding_mode == rmNearestTiesToAway ||
1191       (rounding_mode == rmTowardPositive && !sign) ||
1192       (rounding_mode == rmTowardNegative && sign)) {
1193     category = fcInfinity;
1194     return (opStatus) (opOverflow | opInexact);
1195   }
1196
1197   /* Otherwise we become the largest finite number.  */
1198   category = fcNormal;
1199   exponent = semantics->maxExponent;
1200   APInt::tcSetLeastSignificantBits(significandParts(), partCount(),
1201                                    semantics->precision);
1202
1203   return opInexact;
1204 }
1205
1206 /* Returns TRUE if, when truncating the current number, with BIT the
1207    new LSB, with the given lost fraction and rounding mode, the result
1208    would need to be rounded away from zero (i.e., by increasing the
1209    signficand).  This routine must work for fcZero of both signs, and
1210    fcNormal numbers.  */
1211 bool
1212 APFloat::roundAwayFromZero(roundingMode rounding_mode,
1213                            lostFraction lost_fraction,
1214                            unsigned int bit) const
1215 {
1216   /* NaNs and infinities should not have lost fractions.  */
1217   assert(isFiniteNonZero() || category == fcZero);
1218
1219   /* Current callers never pass this so we don't handle it.  */
1220   assert(lost_fraction != lfExactlyZero);
1221
1222   switch (rounding_mode) {
1223   case rmNearestTiesToAway:
1224     return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
1225
1226   case rmNearestTiesToEven:
1227     if (lost_fraction == lfMoreThanHalf)
1228       return true;
1229
1230     /* Our zeroes don't have a significand to test.  */
1231     if (lost_fraction == lfExactlyHalf && category != fcZero)
1232       return APInt::tcExtractBit(significandParts(), bit);
1233
1234     return false;
1235
1236   case rmTowardZero:
1237     return false;
1238
1239   case rmTowardPositive:
1240     return sign == false;
1241
1242   case rmTowardNegative:
1243     return sign == true;
1244   }
1245   llvm_unreachable("Invalid rounding mode found");
1246 }
1247
1248 APFloat::opStatus
1249 APFloat::normalize(roundingMode rounding_mode,
1250                    lostFraction lost_fraction)
1251 {
1252   unsigned int omsb;                /* One, not zero, based MSB.  */
1253   int exponentChange;
1254
1255   if (!isFiniteNonZero())
1256     return opOK;
1257
1258   /* Before rounding normalize the exponent of fcNormal numbers.  */
1259   omsb = significandMSB() + 1;
1260
1261   if (omsb) {
1262     /* OMSB is numbered from 1.  We want to place it in the integer
1263        bit numbered PRECISION if possible, with a compensating change in
1264        the exponent.  */
1265     exponentChange = omsb - semantics->precision;
1266
1267     /* If the resulting exponent is too high, overflow according to
1268        the rounding mode.  */
1269     if (exponent + exponentChange > semantics->maxExponent)
1270       return handleOverflow(rounding_mode);
1271
1272     /* Subnormal numbers have exponent minExponent, and their MSB
1273        is forced based on that.  */
1274     if (exponent + exponentChange < semantics->minExponent)
1275       exponentChange = semantics->minExponent - exponent;
1276
1277     /* Shifting left is easy as we don't lose precision.  */
1278     if (exponentChange < 0) {
1279       assert(lost_fraction == lfExactlyZero);
1280
1281       shiftSignificandLeft(-exponentChange);
1282
1283       return opOK;
1284     }
1285
1286     if (exponentChange > 0) {
1287       lostFraction lf;
1288
1289       /* Shift right and capture any new lost fraction.  */
1290       lf = shiftSignificandRight(exponentChange);
1291
1292       lost_fraction = combineLostFractions(lf, lost_fraction);
1293
1294       /* Keep OMSB up-to-date.  */
1295       if (omsb > (unsigned) exponentChange)
1296         omsb -= exponentChange;
1297       else
1298         omsb = 0;
1299     }
1300   }
1301
1302   /* Now round the number according to rounding_mode given the lost
1303      fraction.  */
1304
1305   /* As specified in IEEE 754, since we do not trap we do not report
1306      underflow for exact results.  */
1307   if (lost_fraction == lfExactlyZero) {
1308     /* Canonicalize zeroes.  */
1309     if (omsb == 0)
1310       category = fcZero;
1311
1312     return opOK;
1313   }
1314
1315   /* Increment the significand if we're rounding away from zero.  */
1316   if (roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
1317     if (omsb == 0)
1318       exponent = semantics->minExponent;
1319
1320     incrementSignificand();
1321     omsb = significandMSB() + 1;
1322
1323     /* Did the significand increment overflow?  */
1324     if (omsb == (unsigned) semantics->precision + 1) {
1325       /* Renormalize by incrementing the exponent and shifting our
1326          significand right one.  However if we already have the
1327          maximum exponent we overflow to infinity.  */
1328       if (exponent == semantics->maxExponent) {
1329         category = fcInfinity;
1330
1331         return (opStatus) (opOverflow | opInexact);
1332       }
1333
1334       shiftSignificandRight(1);
1335
1336       return opInexact;
1337     }
1338   }
1339
1340   /* The normal case - we were and are not denormal, and any
1341      significand increment above didn't overflow.  */
1342   if (omsb == semantics->precision)
1343     return opInexact;
1344
1345   /* We have a non-zero denormal.  */
1346   assert(omsb < semantics->precision);
1347
1348   /* Canonicalize zeroes.  */
1349   if (omsb == 0)
1350     category = fcZero;
1351
1352   /* The fcZero case is a denormal that underflowed to zero.  */
1353   return (opStatus) (opUnderflow | opInexact);
1354 }
1355
1356 APFloat::opStatus
1357 APFloat::addOrSubtractSpecials(const APFloat &rhs, bool subtract)
1358 {
1359   switch (PackCategoriesIntoKey(category, rhs.category)) {
1360   default:
1361     llvm_unreachable(nullptr);
1362
1363   case PackCategoriesIntoKey(fcNaN, fcZero):
1364   case PackCategoriesIntoKey(fcNaN, fcNormal):
1365   case PackCategoriesIntoKey(fcNaN, fcInfinity):
1366   case PackCategoriesIntoKey(fcNaN, fcNaN):
1367   case PackCategoriesIntoKey(fcNormal, fcZero):
1368   case PackCategoriesIntoKey(fcInfinity, fcNormal):
1369   case PackCategoriesIntoKey(fcInfinity, fcZero):
1370     return opOK;
1371
1372   case PackCategoriesIntoKey(fcZero, fcNaN):
1373   case PackCategoriesIntoKey(fcNormal, fcNaN):
1374   case PackCategoriesIntoKey(fcInfinity, fcNaN):
1375     // We need to be sure to flip the sign here for subtraction because we
1376     // don't have a separate negate operation so -NaN becomes 0 - NaN here.
1377     sign = rhs.sign ^ subtract;
1378     category = fcNaN;
1379     copySignificand(rhs);
1380     return opOK;
1381
1382   case PackCategoriesIntoKey(fcNormal, fcInfinity):
1383   case PackCategoriesIntoKey(fcZero, fcInfinity):
1384     category = fcInfinity;
1385     sign = rhs.sign ^ subtract;
1386     return opOK;
1387
1388   case PackCategoriesIntoKey(fcZero, fcNormal):
1389     assign(rhs);
1390     sign = rhs.sign ^ subtract;
1391     return opOK;
1392
1393   case PackCategoriesIntoKey(fcZero, fcZero):
1394     /* Sign depends on rounding mode; handled by caller.  */
1395     return opOK;
1396
1397   case PackCategoriesIntoKey(fcInfinity, fcInfinity):
1398     /* Differently signed infinities can only be validly
1399        subtracted.  */
1400     if (((sign ^ rhs.sign)!=0) != subtract) {
1401       makeNaN();
1402       return opInvalidOp;
1403     }
1404
1405     return opOK;
1406
1407   case PackCategoriesIntoKey(fcNormal, fcNormal):
1408     return opDivByZero;
1409   }
1410 }
1411
1412 /* Add or subtract two normal numbers.  */
1413 lostFraction
1414 APFloat::addOrSubtractSignificand(const APFloat &rhs, bool subtract)
1415 {
1416   integerPart carry;
1417   lostFraction lost_fraction;
1418   int bits;
1419
1420   /* Determine if the operation on the absolute values is effectively
1421      an addition or subtraction.  */
1422   subtract ^= (sign ^ rhs.sign) ? true : false;
1423
1424   /* Are we bigger exponent-wise than the RHS?  */
1425   bits = exponent - rhs.exponent;
1426
1427   /* Subtraction is more subtle than one might naively expect.  */
1428   if (subtract) {
1429     APFloat temp_rhs(rhs);
1430     bool reverse;
1431
1432     if (bits == 0) {
1433       reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan;
1434       lost_fraction = lfExactlyZero;
1435     } else if (bits > 0) {
1436       lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
1437       shiftSignificandLeft(1);
1438       reverse = false;
1439     } else {
1440       lost_fraction = shiftSignificandRight(-bits - 1);
1441       temp_rhs.shiftSignificandLeft(1);
1442       reverse = true;
1443     }
1444
1445     if (reverse) {
1446       carry = temp_rhs.subtractSignificand
1447         (*this, lost_fraction != lfExactlyZero);
1448       copySignificand(temp_rhs);
1449       sign = !sign;
1450     } else {
1451       carry = subtractSignificand
1452         (temp_rhs, lost_fraction != lfExactlyZero);
1453     }
1454
1455     /* Invert the lost fraction - it was on the RHS and
1456        subtracted.  */
1457     if (lost_fraction == lfLessThanHalf)
1458       lost_fraction = lfMoreThanHalf;
1459     else if (lost_fraction == lfMoreThanHalf)
1460       lost_fraction = lfLessThanHalf;
1461
1462     /* The code above is intended to ensure that no borrow is
1463        necessary.  */
1464     assert(!carry);
1465     (void)carry;
1466   } else {
1467     if (bits > 0) {
1468       APFloat temp_rhs(rhs);
1469
1470       lost_fraction = temp_rhs.shiftSignificandRight(bits);
1471       carry = addSignificand(temp_rhs);
1472     } else {
1473       lost_fraction = shiftSignificandRight(-bits);
1474       carry = addSignificand(rhs);
1475     }
1476
1477     /* We have a guard bit; generating a carry cannot happen.  */
1478     assert(!carry);
1479     (void)carry;
1480   }
1481
1482   return lost_fraction;
1483 }
1484
1485 APFloat::opStatus
1486 APFloat::multiplySpecials(const APFloat &rhs)
1487 {
1488   switch (PackCategoriesIntoKey(category, rhs.category)) {
1489   default:
1490     llvm_unreachable(nullptr);
1491
1492   case PackCategoriesIntoKey(fcNaN, fcZero):
1493   case PackCategoriesIntoKey(fcNaN, fcNormal):
1494   case PackCategoriesIntoKey(fcNaN, fcInfinity):
1495   case PackCategoriesIntoKey(fcNaN, fcNaN):
1496     sign = false;
1497     return opOK;
1498
1499   case PackCategoriesIntoKey(fcZero, fcNaN):
1500   case PackCategoriesIntoKey(fcNormal, fcNaN):
1501   case PackCategoriesIntoKey(fcInfinity, fcNaN):
1502     sign = false;
1503     category = fcNaN;
1504     copySignificand(rhs);
1505     return opOK;
1506
1507   case PackCategoriesIntoKey(fcNormal, fcInfinity):
1508   case PackCategoriesIntoKey(fcInfinity, fcNormal):
1509   case PackCategoriesIntoKey(fcInfinity, fcInfinity):
1510     category = fcInfinity;
1511     return opOK;
1512
1513   case PackCategoriesIntoKey(fcZero, fcNormal):
1514   case PackCategoriesIntoKey(fcNormal, fcZero):
1515   case PackCategoriesIntoKey(fcZero, fcZero):
1516     category = fcZero;
1517     return opOK;
1518
1519   case PackCategoriesIntoKey(fcZero, fcInfinity):
1520   case PackCategoriesIntoKey(fcInfinity, fcZero):
1521     makeNaN();
1522     return opInvalidOp;
1523
1524   case PackCategoriesIntoKey(fcNormal, fcNormal):
1525     return opOK;
1526   }
1527 }
1528
1529 APFloat::opStatus
1530 APFloat::divideSpecials(const APFloat &rhs)
1531 {
1532   switch (PackCategoriesIntoKey(category, rhs.category)) {
1533   default:
1534     llvm_unreachable(nullptr);
1535
1536   case PackCategoriesIntoKey(fcZero, fcNaN):
1537   case PackCategoriesIntoKey(fcNormal, fcNaN):
1538   case PackCategoriesIntoKey(fcInfinity, fcNaN):
1539     category = fcNaN;
1540     copySignificand(rhs);
1541   case PackCategoriesIntoKey(fcNaN, fcZero):
1542   case PackCategoriesIntoKey(fcNaN, fcNormal):
1543   case PackCategoriesIntoKey(fcNaN, fcInfinity):
1544   case PackCategoriesIntoKey(fcNaN, fcNaN):
1545     sign = false;
1546   case PackCategoriesIntoKey(fcInfinity, fcZero):
1547   case PackCategoriesIntoKey(fcInfinity, fcNormal):
1548   case PackCategoriesIntoKey(fcZero, fcInfinity):
1549   case PackCategoriesIntoKey(fcZero, fcNormal):
1550     return opOK;
1551
1552   case PackCategoriesIntoKey(fcNormal, fcInfinity):
1553     category = fcZero;
1554     return opOK;
1555
1556   case PackCategoriesIntoKey(fcNormal, fcZero):
1557     category = fcInfinity;
1558     return opDivByZero;
1559
1560   case PackCategoriesIntoKey(fcInfinity, fcInfinity):
1561   case PackCategoriesIntoKey(fcZero, fcZero):
1562     makeNaN();
1563     return opInvalidOp;
1564
1565   case PackCategoriesIntoKey(fcNormal, fcNormal):
1566     return opOK;
1567   }
1568 }
1569
1570 APFloat::opStatus
1571 APFloat::modSpecials(const APFloat &rhs)
1572 {
1573   switch (PackCategoriesIntoKey(category, rhs.category)) {
1574   default:
1575     llvm_unreachable(nullptr);
1576
1577   case PackCategoriesIntoKey(fcNaN, fcZero):
1578   case PackCategoriesIntoKey(fcNaN, fcNormal):
1579   case PackCategoriesIntoKey(fcNaN, fcInfinity):
1580   case PackCategoriesIntoKey(fcNaN, fcNaN):
1581   case PackCategoriesIntoKey(fcZero, fcInfinity):
1582   case PackCategoriesIntoKey(fcZero, fcNormal):
1583   case PackCategoriesIntoKey(fcNormal, fcInfinity):
1584     return opOK;
1585
1586   case PackCategoriesIntoKey(fcZero, fcNaN):
1587   case PackCategoriesIntoKey(fcNormal, fcNaN):
1588   case PackCategoriesIntoKey(fcInfinity, fcNaN):
1589     sign = false;
1590     category = fcNaN;
1591     copySignificand(rhs);
1592     return opOK;
1593
1594   case PackCategoriesIntoKey(fcNormal, fcZero):
1595   case PackCategoriesIntoKey(fcInfinity, fcZero):
1596   case PackCategoriesIntoKey(fcInfinity, fcNormal):
1597   case PackCategoriesIntoKey(fcInfinity, fcInfinity):
1598   case PackCategoriesIntoKey(fcZero, fcZero):
1599     makeNaN();
1600     return opInvalidOp;
1601
1602   case PackCategoriesIntoKey(fcNormal, fcNormal):
1603     return opOK;
1604   }
1605 }
1606
1607 /* Change sign.  */
1608 void
1609 APFloat::changeSign()
1610 {
1611   /* Look mummy, this one's easy.  */
1612   sign = !sign;
1613 }
1614
1615 void
1616 APFloat::clearSign()
1617 {
1618   /* So is this one. */
1619   sign = 0;
1620 }
1621
1622 void
1623 APFloat::copySign(const APFloat &rhs)
1624 {
1625   /* And this one. */
1626   sign = rhs.sign;
1627 }
1628
1629 /* Normalized addition or subtraction.  */
1630 APFloat::opStatus
1631 APFloat::addOrSubtract(const APFloat &rhs, roundingMode rounding_mode,
1632                        bool subtract)
1633 {
1634   opStatus fs;
1635
1636   fs = addOrSubtractSpecials(rhs, subtract);
1637
1638   /* This return code means it was not a simple case.  */
1639   if (fs == opDivByZero) {
1640     lostFraction lost_fraction;
1641
1642     lost_fraction = addOrSubtractSignificand(rhs, subtract);
1643     fs = normalize(rounding_mode, lost_fraction);
1644
1645     /* Can only be zero if we lost no fraction.  */
1646     assert(category != fcZero || lost_fraction == lfExactlyZero);
1647   }
1648
1649   /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1650      positive zero unless rounding to minus infinity, except that
1651      adding two like-signed zeroes gives that zero.  */
1652   if (category == fcZero) {
1653     if (rhs.category != fcZero || (sign == rhs.sign) == subtract)
1654       sign = (rounding_mode == rmTowardNegative);
1655   }
1656
1657   return fs;
1658 }
1659
1660 /* Normalized addition.  */
1661 APFloat::opStatus
1662 APFloat::add(const APFloat &rhs, roundingMode rounding_mode)
1663 {
1664   return addOrSubtract(rhs, rounding_mode, false);
1665 }
1666
1667 /* Normalized subtraction.  */
1668 APFloat::opStatus
1669 APFloat::subtract(const APFloat &rhs, roundingMode rounding_mode)
1670 {
1671   return addOrSubtract(rhs, rounding_mode, true);
1672 }
1673
1674 /* Normalized multiply.  */
1675 APFloat::opStatus
1676 APFloat::multiply(const APFloat &rhs, roundingMode rounding_mode)
1677 {
1678   opStatus fs;
1679
1680   sign ^= rhs.sign;
1681   fs = multiplySpecials(rhs);
1682
1683   if (isFiniteNonZero()) {
1684     lostFraction lost_fraction = multiplySignificand(rhs, nullptr);
1685     fs = normalize(rounding_mode, lost_fraction);
1686     if (lost_fraction != lfExactlyZero)
1687       fs = (opStatus) (fs | opInexact);
1688   }
1689
1690   return fs;
1691 }
1692
1693 /* Normalized divide.  */
1694 APFloat::opStatus
1695 APFloat::divide(const APFloat &rhs, roundingMode rounding_mode)
1696 {
1697   opStatus fs;
1698
1699   sign ^= rhs.sign;
1700   fs = divideSpecials(rhs);
1701
1702   if (isFiniteNonZero()) {
1703     lostFraction lost_fraction = divideSignificand(rhs);
1704     fs = normalize(rounding_mode, lost_fraction);
1705     if (lost_fraction != lfExactlyZero)
1706       fs = (opStatus) (fs | opInexact);
1707   }
1708
1709   return fs;
1710 }
1711
1712 /* Normalized remainder.  This is not currently correct in all cases.  */
1713 APFloat::opStatus
1714 APFloat::remainder(const APFloat &rhs)
1715 {
1716   opStatus fs;
1717   APFloat V = *this;
1718   unsigned int origSign = sign;
1719
1720   fs = V.divide(rhs, rmNearestTiesToEven);
1721   if (fs == opDivByZero)
1722     return fs;
1723
1724   int parts = partCount();
1725   auto XOwner = make_unique<integerPart[]>(parts);
1726   auto x = XOwner.get();
1727   bool ignored;
1728   fs = V.convertToInteger(x, parts * integerPartWidth, true,
1729                           rmNearestTiesToEven, &ignored);
1730   if (fs==opInvalidOp)
1731     return fs;
1732
1733   fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1734                                         rmNearestTiesToEven);
1735   assert(fs==opOK);   // should always work
1736
1737   fs = V.multiply(rhs, rmNearestTiesToEven);
1738   assert(fs==opOK || fs==opInexact);   // should not overflow or underflow
1739
1740   fs = subtract(V, rmNearestTiesToEven);
1741   assert(fs==opOK || fs==opInexact);   // likewise
1742
1743   if (isZero())
1744     sign = origSign;    // IEEE754 requires this
1745   return fs;
1746 }
1747
1748 /* Normalized llvm frem (C fmod).
1749    This is not currently correct in all cases.  */
1750 APFloat::opStatus
1751 APFloat::mod(const APFloat &rhs, roundingMode rounding_mode)
1752 {
1753   opStatus fs;
1754   fs = modSpecials(rhs);
1755
1756   if (isFiniteNonZero() && rhs.isFiniteNonZero()) {
1757     APFloat V = *this;
1758     unsigned int origSign = sign;
1759
1760     fs = V.divide(rhs, rmNearestTiesToEven);
1761     if (fs == opDivByZero)
1762       return fs;
1763
1764     int parts = partCount();
1765     auto XOwner = make_unique<integerPart[]>(parts);
1766     auto x = XOwner.get();
1767     bool ignored;
1768     fs = V.convertToInteger(x, parts * integerPartWidth, true,
1769                             rmTowardZero, &ignored);
1770     if (fs==opInvalidOp)
1771       return fs;
1772
1773     fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1774                                           rmNearestTiesToEven);
1775     assert(fs==opOK);   // should always work
1776
1777     fs = V.multiply(rhs, rounding_mode);
1778     assert(fs==opOK || fs==opInexact);   // should not overflow or underflow
1779
1780     fs = subtract(V, rounding_mode);
1781     assert(fs==opOK || fs==opInexact);   // likewise
1782
1783     if (isZero())
1784       sign = origSign;    // IEEE754 requires this
1785   }
1786   return fs;
1787 }
1788
1789 /* Normalized fused-multiply-add.  */
1790 APFloat::opStatus
1791 APFloat::fusedMultiplyAdd(const APFloat &multiplicand,
1792                           const APFloat &addend,
1793                           roundingMode rounding_mode)
1794 {
1795   opStatus fs;
1796
1797   /* Post-multiplication sign, before addition.  */
1798   sign ^= multiplicand.sign;
1799
1800   /* If and only if all arguments are normal do we need to do an
1801      extended-precision calculation.  */
1802   if (isFiniteNonZero() &&
1803       multiplicand.isFiniteNonZero() &&
1804       addend.isFiniteNonZero()) {
1805     lostFraction lost_fraction;
1806
1807     lost_fraction = multiplySignificand(multiplicand, &addend);
1808     fs = normalize(rounding_mode, lost_fraction);
1809     if (lost_fraction != lfExactlyZero)
1810       fs = (opStatus) (fs | opInexact);
1811
1812     /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1813        positive zero unless rounding to minus infinity, except that
1814        adding two like-signed zeroes gives that zero.  */
1815     if (category == fcZero && sign != addend.sign)
1816       sign = (rounding_mode == rmTowardNegative);
1817   } else {
1818     fs = multiplySpecials(multiplicand);
1819
1820     /* FS can only be opOK or opInvalidOp.  There is no more work
1821        to do in the latter case.  The IEEE-754R standard says it is
1822        implementation-defined in this case whether, if ADDEND is a
1823        quiet NaN, we raise invalid op; this implementation does so.
1824
1825        If we need to do the addition we can do so with normal
1826        precision.  */
1827     if (fs == opOK)
1828       fs = addOrSubtract(addend, rounding_mode, false);
1829   }
1830
1831   return fs;
1832 }
1833
1834 /* Rounding-mode corrrect round to integral value.  */
1835 APFloat::opStatus APFloat::roundToIntegral(roundingMode rounding_mode) {
1836   opStatus fs;
1837
1838   // If the exponent is large enough, we know that this value is already
1839   // integral, and the arithmetic below would potentially cause it to saturate
1840   // to +/-Inf.  Bail out early instead.
1841   if (isFiniteNonZero() && exponent+1 >= (int)semanticsPrecision(*semantics))
1842     return opOK;
1843
1844   // The algorithm here is quite simple: we add 2^(p-1), where p is the
1845   // precision of our format, and then subtract it back off again.  The choice
1846   // of rounding modes for the addition/subtraction determines the rounding mode
1847   // for our integral rounding as well.
1848   // NOTE: When the input value is negative, we do subtraction followed by
1849   // addition instead.
1850   APInt IntegerConstant(NextPowerOf2(semanticsPrecision(*semantics)), 1);
1851   IntegerConstant <<= semanticsPrecision(*semantics)-1;
1852   APFloat MagicConstant(*semantics);
1853   fs = MagicConstant.convertFromAPInt(IntegerConstant, false,
1854                                       rmNearestTiesToEven);
1855   MagicConstant.copySign(*this);
1856
1857   if (fs != opOK)
1858     return fs;
1859
1860   // Preserve the input sign so that we can handle 0.0/-0.0 cases correctly.
1861   bool inputSign = isNegative();
1862
1863   fs = add(MagicConstant, rounding_mode);
1864   if (fs != opOK && fs != opInexact)
1865     return fs;
1866
1867   fs = subtract(MagicConstant, rounding_mode);
1868
1869   // Restore the input sign.
1870   if (inputSign != isNegative())
1871     changeSign();
1872
1873   return fs;
1874 }
1875
1876
1877 /* Comparison requires normalized numbers.  */
1878 APFloat::cmpResult
1879 APFloat::compare(const APFloat &rhs) const
1880 {
1881   cmpResult result;
1882
1883   assert(semantics == rhs.semantics);
1884
1885   switch (PackCategoriesIntoKey(category, rhs.category)) {
1886   default:
1887     llvm_unreachable(nullptr);
1888
1889   case PackCategoriesIntoKey(fcNaN, fcZero):
1890   case PackCategoriesIntoKey(fcNaN, fcNormal):
1891   case PackCategoriesIntoKey(fcNaN, fcInfinity):
1892   case PackCategoriesIntoKey(fcNaN, fcNaN):
1893   case PackCategoriesIntoKey(fcZero, fcNaN):
1894   case PackCategoriesIntoKey(fcNormal, fcNaN):
1895   case PackCategoriesIntoKey(fcInfinity, fcNaN):
1896     return cmpUnordered;
1897
1898   case PackCategoriesIntoKey(fcInfinity, fcNormal):
1899   case PackCategoriesIntoKey(fcInfinity, fcZero):
1900   case PackCategoriesIntoKey(fcNormal, fcZero):
1901     if (sign)
1902       return cmpLessThan;
1903     else
1904       return cmpGreaterThan;
1905
1906   case PackCategoriesIntoKey(fcNormal, fcInfinity):
1907   case PackCategoriesIntoKey(fcZero, fcInfinity):
1908   case PackCategoriesIntoKey(fcZero, fcNormal):
1909     if (rhs.sign)
1910       return cmpGreaterThan;
1911     else
1912       return cmpLessThan;
1913
1914   case PackCategoriesIntoKey(fcInfinity, fcInfinity):
1915     if (sign == rhs.sign)
1916       return cmpEqual;
1917     else if (sign)
1918       return cmpLessThan;
1919     else
1920       return cmpGreaterThan;
1921
1922   case PackCategoriesIntoKey(fcZero, fcZero):
1923     return cmpEqual;
1924
1925   case PackCategoriesIntoKey(fcNormal, fcNormal):
1926     break;
1927   }
1928
1929   /* Two normal numbers.  Do they have the same sign?  */
1930   if (sign != rhs.sign) {
1931     if (sign)
1932       result = cmpLessThan;
1933     else
1934       result = cmpGreaterThan;
1935   } else {
1936     /* Compare absolute values; invert result if negative.  */
1937     result = compareAbsoluteValue(rhs);
1938
1939     if (sign) {
1940       if (result == cmpLessThan)
1941         result = cmpGreaterThan;
1942       else if (result == cmpGreaterThan)
1943         result = cmpLessThan;
1944     }
1945   }
1946
1947   return result;
1948 }
1949
1950 /// APFloat::convert - convert a value of one floating point type to another.
1951 /// The return value corresponds to the IEEE754 exceptions.  *losesInfo
1952 /// records whether the transformation lost information, i.e. whether
1953 /// converting the result back to the original type will produce the
1954 /// original value (this is almost the same as return value==fsOK, but there
1955 /// are edge cases where this is not so).
1956
1957 APFloat::opStatus
1958 APFloat::convert(const fltSemantics &toSemantics,
1959                  roundingMode rounding_mode, bool *losesInfo)
1960 {
1961   lostFraction lostFraction;
1962   unsigned int newPartCount, oldPartCount;
1963   opStatus fs;
1964   int shift;
1965   const fltSemantics &fromSemantics = *semantics;
1966
1967   lostFraction = lfExactlyZero;
1968   newPartCount = partCountForBits(toSemantics.precision + 1);
1969   oldPartCount = partCount();
1970   shift = toSemantics.precision - fromSemantics.precision;
1971
1972   bool X86SpecialNan = false;
1973   if (&fromSemantics == &APFloat::x87DoubleExtended &&
1974       &toSemantics != &APFloat::x87DoubleExtended && category == fcNaN &&
1975       (!(*significandParts() & 0x8000000000000000ULL) ||
1976        !(*significandParts() & 0x4000000000000000ULL))) {
1977     // x86 has some unusual NaNs which cannot be represented in any other
1978     // format; note them here.
1979     X86SpecialNan = true;
1980   }
1981
1982   // If this is a truncation of a denormal number, and the target semantics
1983   // has larger exponent range than the source semantics (this can happen
1984   // when truncating from PowerPC double-double to double format), the
1985   // right shift could lose result mantissa bits.  Adjust exponent instead
1986   // of performing excessive shift.
1987   if (shift < 0 && isFiniteNonZero()) {
1988     int exponentChange = significandMSB() + 1 - fromSemantics.precision;
1989     if (exponent + exponentChange < toSemantics.minExponent)
1990       exponentChange = toSemantics.minExponent - exponent;
1991     if (exponentChange < shift)
1992       exponentChange = shift;
1993     if (exponentChange < 0) {
1994       shift -= exponentChange;
1995       exponent += exponentChange;
1996     }
1997   }
1998
1999   // If this is a truncation, perform the shift before we narrow the storage.
2000   if (shift < 0 && (isFiniteNonZero() || category==fcNaN))
2001     lostFraction = shiftRight(significandParts(), oldPartCount, -shift);
2002
2003   // Fix the storage so it can hold to new value.
2004   if (newPartCount > oldPartCount) {
2005     // The new type requires more storage; make it available.
2006     integerPart *newParts;
2007     newParts = new integerPart[newPartCount];
2008     APInt::tcSet(newParts, 0, newPartCount);
2009     if (isFiniteNonZero() || category==fcNaN)
2010       APInt::tcAssign(newParts, significandParts(), oldPartCount);
2011     freeSignificand();
2012     significand.parts = newParts;
2013   } else if (newPartCount == 1 && oldPartCount != 1) {
2014     // Switch to built-in storage for a single part.
2015     integerPart newPart = 0;
2016     if (isFiniteNonZero() || category==fcNaN)
2017       newPart = significandParts()[0];
2018     freeSignificand();
2019     significand.part = newPart;
2020   }
2021
2022   // Now that we have the right storage, switch the semantics.
2023   semantics = &toSemantics;
2024
2025   // If this is an extension, perform the shift now that the storage is
2026   // available.
2027   if (shift > 0 && (isFiniteNonZero() || category==fcNaN))
2028     APInt::tcShiftLeft(significandParts(), newPartCount, shift);
2029
2030   if (isFiniteNonZero()) {
2031     fs = normalize(rounding_mode, lostFraction);
2032     *losesInfo = (fs != opOK);
2033   } else if (category == fcNaN) {
2034     *losesInfo = lostFraction != lfExactlyZero || X86SpecialNan;
2035
2036     // For x87 extended precision, we want to make a NaN, not a special NaN if
2037     // the input wasn't special either.
2038     if (!X86SpecialNan && semantics == &APFloat::x87DoubleExtended)
2039       APInt::tcSetBit(significandParts(), semantics->precision - 1);
2040
2041     // gcc forces the Quiet bit on, which means (float)(double)(float_sNan)
2042     // does not give you back the same bits.  This is dubious, and we
2043     // don't currently do it.  You're really supposed to get
2044     // an invalid operation signal at runtime, but nobody does that.
2045     fs = opOK;
2046   } else {
2047     *losesInfo = false;
2048     fs = opOK;
2049   }
2050
2051   return fs;
2052 }
2053
2054 /* Convert a floating point number to an integer according to the
2055    rounding mode.  If the rounded integer value is out of range this
2056    returns an invalid operation exception and the contents of the
2057    destination parts are unspecified.  If the rounded value is in
2058    range but the floating point number is not the exact integer, the C
2059    standard doesn't require an inexact exception to be raised.  IEEE
2060    854 does require it so we do that.
2061
2062    Note that for conversions to integer type the C standard requires
2063    round-to-zero to always be used.  */
2064 APFloat::opStatus
2065 APFloat::convertToSignExtendedInteger(integerPart *parts, unsigned int width,
2066                                       bool isSigned,
2067                                       roundingMode rounding_mode,
2068                                       bool *isExact) const
2069 {
2070   lostFraction lost_fraction;
2071   const integerPart *src;
2072   unsigned int dstPartsCount, truncatedBits;
2073
2074   *isExact = false;
2075
2076   /* Handle the three special cases first.  */
2077   if (category == fcInfinity || category == fcNaN)
2078     return opInvalidOp;
2079
2080   dstPartsCount = partCountForBits(width);
2081
2082   if (category == fcZero) {
2083     APInt::tcSet(parts, 0, dstPartsCount);
2084     // Negative zero can't be represented as an int.
2085     *isExact = !sign;
2086     return opOK;
2087   }
2088
2089   src = significandParts();
2090
2091   /* Step 1: place our absolute value, with any fraction truncated, in
2092      the destination.  */
2093   if (exponent < 0) {
2094     /* Our absolute value is less than one; truncate everything.  */
2095     APInt::tcSet(parts, 0, dstPartsCount);
2096     /* For exponent -1 the integer bit represents .5, look at that.
2097        For smaller exponents leftmost truncated bit is 0. */
2098     truncatedBits = semantics->precision -1U - exponent;
2099   } else {
2100     /* We want the most significant (exponent + 1) bits; the rest are
2101        truncated.  */
2102     unsigned int bits = exponent + 1U;
2103
2104     /* Hopelessly large in magnitude?  */
2105     if (bits > width)
2106       return opInvalidOp;
2107
2108     if (bits < semantics->precision) {
2109       /* We truncate (semantics->precision - bits) bits.  */
2110       truncatedBits = semantics->precision - bits;
2111       APInt::tcExtract(parts, dstPartsCount, src, bits, truncatedBits);
2112     } else {
2113       /* We want at least as many bits as are available.  */
2114       APInt::tcExtract(parts, dstPartsCount, src, semantics->precision, 0);
2115       APInt::tcShiftLeft(parts, dstPartsCount, bits - semantics->precision);
2116       truncatedBits = 0;
2117     }
2118   }
2119
2120   /* Step 2: work out any lost fraction, and increment the absolute
2121      value if we would round away from zero.  */
2122   if (truncatedBits) {
2123     lost_fraction = lostFractionThroughTruncation(src, partCount(),
2124                                                   truncatedBits);
2125     if (lost_fraction != lfExactlyZero &&
2126         roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
2127       if (APInt::tcIncrement(parts, dstPartsCount))
2128         return opInvalidOp;     /* Overflow.  */
2129     }
2130   } else {
2131     lost_fraction = lfExactlyZero;
2132   }
2133
2134   /* Step 3: check if we fit in the destination.  */
2135   unsigned int omsb = APInt::tcMSB(parts, dstPartsCount) + 1;
2136
2137   if (sign) {
2138     if (!isSigned) {
2139       /* Negative numbers cannot be represented as unsigned.  */
2140       if (omsb != 0)
2141         return opInvalidOp;
2142     } else {
2143       /* It takes omsb bits to represent the unsigned integer value.
2144          We lose a bit for the sign, but care is needed as the
2145          maximally negative integer is a special case.  */
2146       if (omsb == width && APInt::tcLSB(parts, dstPartsCount) + 1 != omsb)
2147         return opInvalidOp;
2148
2149       /* This case can happen because of rounding.  */
2150       if (omsb > width)
2151         return opInvalidOp;
2152     }
2153
2154     APInt::tcNegate (parts, dstPartsCount);
2155   } else {
2156     if (omsb >= width + !isSigned)
2157       return opInvalidOp;
2158   }
2159
2160   if (lost_fraction == lfExactlyZero) {
2161     *isExact = true;
2162     return opOK;
2163   } else
2164     return opInexact;
2165 }
2166
2167 /* Same as convertToSignExtendedInteger, except we provide
2168    deterministic values in case of an invalid operation exception,
2169    namely zero for NaNs and the minimal or maximal value respectively
2170    for underflow or overflow.
2171    The *isExact output tells whether the result is exact, in the sense
2172    that converting it back to the original floating point type produces
2173    the original value.  This is almost equivalent to result==opOK,
2174    except for negative zeroes.
2175 */
2176 APFloat::opStatus
2177 APFloat::convertToInteger(integerPart *parts, unsigned int width,
2178                           bool isSigned,
2179                           roundingMode rounding_mode, bool *isExact) const
2180 {
2181   opStatus fs;
2182
2183   fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode,
2184                                     isExact);
2185
2186   if (fs == opInvalidOp) {
2187     unsigned int bits, dstPartsCount;
2188
2189     dstPartsCount = partCountForBits(width);
2190
2191     if (category == fcNaN)
2192       bits = 0;
2193     else if (sign)
2194       bits = isSigned;
2195     else
2196       bits = width - isSigned;
2197
2198     APInt::tcSetLeastSignificantBits(parts, dstPartsCount, bits);
2199     if (sign && isSigned)
2200       APInt::tcShiftLeft(parts, dstPartsCount, width - 1);
2201   }
2202
2203   return fs;
2204 }
2205
2206 /* Same as convertToInteger(integerPart*, ...), except the result is returned in
2207    an APSInt, whose initial bit-width and signed-ness are used to determine the
2208    precision of the conversion.
2209  */
2210 APFloat::opStatus
2211 APFloat::convertToInteger(APSInt &result,
2212                           roundingMode rounding_mode, bool *isExact) const
2213 {
2214   unsigned bitWidth = result.getBitWidth();
2215   SmallVector<uint64_t, 4> parts(result.getNumWords());
2216   opStatus status = convertToInteger(
2217     parts.data(), bitWidth, result.isSigned(), rounding_mode, isExact);
2218   // Keeps the original signed-ness.
2219   result = APInt(bitWidth, parts);
2220   return status;
2221 }
2222
2223 /* Convert an unsigned integer SRC to a floating point number,
2224    rounding according to ROUNDING_MODE.  The sign of the floating
2225    point number is not modified.  */
2226 APFloat::opStatus
2227 APFloat::convertFromUnsignedParts(const integerPart *src,
2228                                   unsigned int srcCount,
2229                                   roundingMode rounding_mode)
2230 {
2231   unsigned int omsb, precision, dstCount;
2232   integerPart *dst;
2233   lostFraction lost_fraction;
2234
2235   category = fcNormal;
2236   omsb = APInt::tcMSB(src, srcCount) + 1;
2237   dst = significandParts();
2238   dstCount = partCount();
2239   precision = semantics->precision;
2240
2241   /* We want the most significant PRECISION bits of SRC.  There may not
2242      be that many; extract what we can.  */
2243   if (precision <= omsb) {
2244     exponent = omsb - 1;
2245     lost_fraction = lostFractionThroughTruncation(src, srcCount,
2246                                                   omsb - precision);
2247     APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
2248   } else {
2249     exponent = precision - 1;
2250     lost_fraction = lfExactlyZero;
2251     APInt::tcExtract(dst, dstCount, src, omsb, 0);
2252   }
2253
2254   return normalize(rounding_mode, lost_fraction);
2255 }
2256
2257 APFloat::opStatus
2258 APFloat::convertFromAPInt(const APInt &Val,
2259                           bool isSigned,
2260                           roundingMode rounding_mode)
2261 {
2262   unsigned int partCount = Val.getNumWords();
2263   APInt api = Val;
2264
2265   sign = false;
2266   if (isSigned && api.isNegative()) {
2267     sign = true;
2268     api = -api;
2269   }
2270
2271   return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
2272 }
2273
2274 /* Convert a two's complement integer SRC to a floating point number,
2275    rounding according to ROUNDING_MODE.  ISSIGNED is true if the
2276    integer is signed, in which case it must be sign-extended.  */
2277 APFloat::opStatus
2278 APFloat::convertFromSignExtendedInteger(const integerPart *src,
2279                                         unsigned int srcCount,
2280                                         bool isSigned,
2281                                         roundingMode rounding_mode)
2282 {
2283   opStatus status;
2284
2285   if (isSigned &&
2286       APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) {
2287     auto C = make_unique<integerPart[]>(srcCount);
2288     auto copy = C.get();
2289
2290     /* If we're signed and negative negate a copy.  */
2291     sign = true;
2292     APInt::tcAssign(copy, src, srcCount);
2293     APInt::tcNegate(copy, srcCount);
2294     status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
2295   } else {
2296     sign = false;
2297     status = convertFromUnsignedParts(src, srcCount, rounding_mode);
2298   }
2299
2300   return status;
2301 }
2302
2303 /* FIXME: should this just take a const APInt reference?  */
2304 APFloat::opStatus
2305 APFloat::convertFromZeroExtendedInteger(const integerPart *parts,
2306                                         unsigned int width, bool isSigned,
2307                                         roundingMode rounding_mode)
2308 {
2309   unsigned int partCount = partCountForBits(width);
2310   APInt api = APInt(width, makeArrayRef(parts, partCount));
2311
2312   sign = false;
2313   if (isSigned && APInt::tcExtractBit(parts, width - 1)) {
2314     sign = true;
2315     api = -api;
2316   }
2317
2318   return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
2319 }
2320
2321 APFloat::opStatus
2322 APFloat::convertFromHexadecimalString(StringRef s, roundingMode rounding_mode)
2323 {
2324   lostFraction lost_fraction = lfExactlyZero;
2325
2326   category = fcNormal;
2327   zeroSignificand();
2328   exponent = 0;
2329
2330   integerPart *significand = significandParts();
2331   unsigned partsCount = partCount();
2332   unsigned bitPos = partsCount * integerPartWidth;
2333   bool computedTrailingFraction = false;
2334
2335   // Skip leading zeroes and any (hexa)decimal point.
2336   StringRef::iterator begin = s.begin();
2337   StringRef::iterator end = s.end();
2338   StringRef::iterator dot;
2339   StringRef::iterator p = skipLeadingZeroesAndAnyDot(begin, end, &dot);
2340   StringRef::iterator firstSignificantDigit = p;
2341
2342   while (p != end) {
2343     integerPart hex_value;
2344
2345     if (*p == '.') {
2346       assert(dot == end && "String contains multiple dots");
2347       dot = p++;
2348       continue;
2349     }
2350
2351     hex_value = hexDigitValue(*p);
2352     if (hex_value == -1U)
2353       break;
2354
2355     p++;
2356
2357     // Store the number while we have space.
2358     if (bitPos) {
2359       bitPos -= 4;
2360       hex_value <<= bitPos % integerPartWidth;
2361       significand[bitPos / integerPartWidth] |= hex_value;
2362     } else if (!computedTrailingFraction) {
2363       lost_fraction = trailingHexadecimalFraction(p, end, hex_value);
2364       computedTrailingFraction = true;
2365     }
2366   }
2367
2368   /* Hex floats require an exponent but not a hexadecimal point.  */
2369   assert(p != end && "Hex strings require an exponent");
2370   assert((*p == 'p' || *p == 'P') && "Invalid character in significand");
2371   assert(p != begin && "Significand has no digits");
2372   assert((dot == end || p - begin != 1) && "Significand has no digits");
2373
2374   /* Ignore the exponent if we are zero.  */
2375   if (p != firstSignificantDigit) {
2376     int expAdjustment;
2377
2378     /* Implicit hexadecimal point?  */
2379     if (dot == end)
2380       dot = p;
2381
2382     /* Calculate the exponent adjustment implicit in the number of
2383        significant digits.  */
2384     expAdjustment = static_cast<int>(dot - firstSignificantDigit);
2385     if (expAdjustment < 0)
2386       expAdjustment++;
2387     expAdjustment = expAdjustment * 4 - 1;
2388
2389     /* Adjust for writing the significand starting at the most
2390        significant nibble.  */
2391     expAdjustment += semantics->precision;
2392     expAdjustment -= partsCount * integerPartWidth;
2393
2394     /* Adjust for the given exponent.  */
2395     exponent = totalExponent(p + 1, end, expAdjustment);
2396   }
2397
2398   return normalize(rounding_mode, lost_fraction);
2399 }
2400
2401 APFloat::opStatus
2402 APFloat::roundSignificandWithExponent(const integerPart *decSigParts,
2403                                       unsigned sigPartCount, int exp,
2404                                       roundingMode rounding_mode)
2405 {
2406   unsigned int parts, pow5PartCount;
2407   fltSemantics calcSemantics = { 32767, -32767, 0 };
2408   integerPart pow5Parts[maxPowerOfFiveParts];
2409   bool isNearest;
2410
2411   isNearest = (rounding_mode == rmNearestTiesToEven ||
2412                rounding_mode == rmNearestTiesToAway);
2413
2414   parts = partCountForBits(semantics->precision + 11);
2415
2416   /* Calculate pow(5, abs(exp)).  */
2417   pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp);
2418
2419   for (;; parts *= 2) {
2420     opStatus sigStatus, powStatus;
2421     unsigned int excessPrecision, truncatedBits;
2422
2423     calcSemantics.precision = parts * integerPartWidth - 1;
2424     excessPrecision = calcSemantics.precision - semantics->precision;
2425     truncatedBits = excessPrecision;
2426
2427     APFloat decSig = APFloat::getZero(calcSemantics, sign);
2428     APFloat pow5(calcSemantics);
2429
2430     sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount,
2431                                                 rmNearestTiesToEven);
2432     powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
2433                                               rmNearestTiesToEven);
2434     /* Add exp, as 10^n = 5^n * 2^n.  */
2435     decSig.exponent += exp;
2436
2437     lostFraction calcLostFraction;
2438     integerPart HUerr, HUdistance;
2439     unsigned int powHUerr;
2440
2441     if (exp >= 0) {
2442       /* multiplySignificand leaves the precision-th bit set to 1.  */
2443       calcLostFraction = decSig.multiplySignificand(pow5, nullptr);
2444       powHUerr = powStatus != opOK;
2445     } else {
2446       calcLostFraction = decSig.divideSignificand(pow5);
2447       /* Denormal numbers have less precision.  */
2448       if (decSig.exponent < semantics->minExponent) {
2449         excessPrecision += (semantics->minExponent - decSig.exponent);
2450         truncatedBits = excessPrecision;
2451         if (excessPrecision > calcSemantics.precision)
2452           excessPrecision = calcSemantics.precision;
2453       }
2454       /* Extra half-ulp lost in reciprocal of exponent.  */
2455       powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2;
2456     }
2457
2458     /* Both multiplySignificand and divideSignificand return the
2459        result with the integer bit set.  */
2460     assert(APInt::tcExtractBit
2461            (decSig.significandParts(), calcSemantics.precision - 1) == 1);
2462
2463     HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK,
2464                        powHUerr);
2465     HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
2466                                       excessPrecision, isNearest);
2467
2468     /* Are we guaranteed to round correctly if we truncate?  */
2469     if (HUdistance >= HUerr) {
2470       APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
2471                        calcSemantics.precision - excessPrecision,
2472                        excessPrecision);
2473       /* Take the exponent of decSig.  If we tcExtract-ed less bits
2474          above we must adjust our exponent to compensate for the
2475          implicit right shift.  */
2476       exponent = (decSig.exponent + semantics->precision
2477                   - (calcSemantics.precision - excessPrecision));
2478       calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(),
2479                                                        decSig.partCount(),
2480                                                        truncatedBits);
2481       return normalize(rounding_mode, calcLostFraction);
2482     }
2483   }
2484 }
2485
2486 APFloat::opStatus
2487 APFloat::convertFromDecimalString(StringRef str, roundingMode rounding_mode)
2488 {
2489   decimalInfo D;
2490   opStatus fs;
2491
2492   /* Scan the text.  */
2493   StringRef::iterator p = str.begin();
2494   interpretDecimal(p, str.end(), &D);
2495
2496   /* Handle the quick cases.  First the case of no significant digits,
2497      i.e. zero, and then exponents that are obviously too large or too
2498      small.  Writing L for log 10 / log 2, a number d.ddddd*10^exp
2499      definitely overflows if
2500
2501            (exp - 1) * L >= maxExponent
2502
2503      and definitely underflows to zero where
2504
2505            (exp + 1) * L <= minExponent - precision
2506
2507      With integer arithmetic the tightest bounds for L are
2508
2509            93/28 < L < 196/59            [ numerator <= 256 ]
2510            42039/12655 < L < 28738/8651  [ numerator <= 65536 ]
2511   */
2512
2513   // Test if we have a zero number allowing for strings with no null terminators
2514   // and zero decimals with non-zero exponents.
2515   // 
2516   // We computed firstSigDigit by ignoring all zeros and dots. Thus if
2517   // D->firstSigDigit equals str.end(), every digit must be a zero and there can
2518   // be at most one dot. On the other hand, if we have a zero with a non-zero
2519   // exponent, then we know that D.firstSigDigit will be non-numeric.
2520   if (D.firstSigDigit == str.end() || decDigitValue(*D.firstSigDigit) >= 10U) {
2521     category = fcZero;
2522     fs = opOK;
2523
2524   /* Check whether the normalized exponent is high enough to overflow
2525      max during the log-rebasing in the max-exponent check below. */
2526   } else if (D.normalizedExponent - 1 > INT_MAX / 42039) {
2527     fs = handleOverflow(rounding_mode);
2528
2529   /* If it wasn't, then it also wasn't high enough to overflow max
2530      during the log-rebasing in the min-exponent check.  Check that it
2531      won't overflow min in either check, then perform the min-exponent
2532      check. */
2533   } else if (D.normalizedExponent - 1 < INT_MIN / 42039 ||
2534              (D.normalizedExponent + 1) * 28738 <=
2535                8651 * (semantics->minExponent - (int) semantics->precision)) {
2536     /* Underflow to zero and round.  */
2537     category = fcNormal;
2538     zeroSignificand();
2539     fs = normalize(rounding_mode, lfLessThanHalf);
2540
2541   /* We can finally safely perform the max-exponent check. */
2542   } else if ((D.normalizedExponent - 1) * 42039
2543              >= 12655 * semantics->maxExponent) {
2544     /* Overflow and round.  */
2545     fs = handleOverflow(rounding_mode);
2546   } else {
2547     unsigned int partCount;
2548
2549     /* A tight upper bound on number of bits required to hold an
2550        N-digit decimal integer is N * 196 / 59.  Allocate enough space
2551        to hold the full significand, and an extra part required by
2552        tcMultiplyPart.  */
2553     partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1;
2554     partCount = partCountForBits(1 + 196 * partCount / 59);
2555     auto DecSignificandOwner = make_unique<integerPart[]>(partCount + 1);
2556     auto decSignificand = DecSignificandOwner.get();
2557     partCount = 0;
2558
2559     /* Convert to binary efficiently - we do almost all multiplication
2560        in an integerPart.  When this would overflow do we do a single
2561        bignum multiplication, and then revert again to multiplication
2562        in an integerPart.  */
2563     do {
2564       integerPart decValue, val, multiplier;
2565
2566       val = 0;
2567       multiplier = 1;
2568
2569       do {
2570         if (*p == '.') {
2571           p++;
2572           if (p == str.end()) {
2573             break;
2574           }
2575         }
2576         decValue = decDigitValue(*p++);
2577         assert(decValue < 10U && "Invalid character in significand");
2578         multiplier *= 10;
2579         val = val * 10 + decValue;
2580         /* The maximum number that can be multiplied by ten with any
2581            digit added without overflowing an integerPart.  */
2582       } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
2583
2584       /* Multiply out the current part.  */
2585       APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
2586                             partCount, partCount + 1, false);
2587
2588       /* If we used another part (likely but not guaranteed), increase
2589          the count.  */
2590       if (decSignificand[partCount])
2591         partCount++;
2592     } while (p <= D.lastSigDigit);
2593
2594     category = fcNormal;
2595     fs = roundSignificandWithExponent(decSignificand, partCount,
2596                                       D.exponent, rounding_mode);
2597   }
2598
2599   return fs;
2600 }
2601
2602 bool
2603 APFloat::convertFromStringSpecials(StringRef str) {
2604   if (str.equals("inf") || str.equals("INFINITY")) {
2605     makeInf(false);
2606     return true;
2607   }
2608
2609   if (str.equals("-inf") || str.equals("-INFINITY")) {
2610     makeInf(true);
2611     return true;
2612   }
2613
2614   if (str.equals("nan") || str.equals("NaN")) {
2615     makeNaN(false, false);
2616     return true;
2617   }
2618
2619   if (str.equals("-nan") || str.equals("-NaN")) {
2620     makeNaN(false, true);
2621     return true;
2622   }
2623
2624   return false;
2625 }
2626
2627 APFloat::opStatus
2628 APFloat::convertFromString(StringRef str, roundingMode rounding_mode)
2629 {
2630   assert(!str.empty() && "Invalid string length");
2631
2632   // Handle special cases.
2633   if (convertFromStringSpecials(str))
2634     return opOK;
2635
2636   /* Handle a leading minus sign.  */
2637   StringRef::iterator p = str.begin();
2638   size_t slen = str.size();
2639   sign = *p == '-' ? 1 : 0;
2640   if (*p == '-' || *p == '+') {
2641     p++;
2642     slen--;
2643     assert(slen && "String has no digits");
2644   }
2645
2646   if (slen >= 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
2647     assert(slen - 2 && "Invalid string");
2648     return convertFromHexadecimalString(StringRef(p + 2, slen - 2),
2649                                         rounding_mode);
2650   }
2651
2652   return convertFromDecimalString(StringRef(p, slen), rounding_mode);
2653 }
2654
2655 /* Write out a hexadecimal representation of the floating point value
2656    to DST, which must be of sufficient size, in the C99 form
2657    [-]0xh.hhhhp[+-]d.  Return the number of characters written,
2658    excluding the terminating NUL.
2659
2660    If UPPERCASE, the output is in upper case, otherwise in lower case.
2661
2662    HEXDIGITS digits appear altogether, rounding the value if
2663    necessary.  If HEXDIGITS is 0, the minimal precision to display the
2664    number precisely is used instead.  If nothing would appear after
2665    the decimal point it is suppressed.
2666
2667    The decimal exponent is always printed and has at least one digit.
2668    Zero values display an exponent of zero.  Infinities and NaNs
2669    appear as "infinity" or "nan" respectively.
2670
2671    The above rules are as specified by C99.  There is ambiguity about
2672    what the leading hexadecimal digit should be.  This implementation
2673    uses whatever is necessary so that the exponent is displayed as
2674    stored.  This implies the exponent will fall within the IEEE format
2675    range, and the leading hexadecimal digit will be 0 (for denormals),
2676    1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
2677    any other digits zero).
2678 */
2679 unsigned int
2680 APFloat::convertToHexString(char *dst, unsigned int hexDigits,
2681                             bool upperCase, roundingMode rounding_mode) const
2682 {
2683   char *p;
2684
2685   p = dst;
2686   if (sign)
2687     *dst++ = '-';
2688
2689   switch (category) {
2690   case fcInfinity:
2691     memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
2692     dst += sizeof infinityL - 1;
2693     break;
2694
2695   case fcNaN:
2696     memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
2697     dst += sizeof NaNU - 1;
2698     break;
2699
2700   case fcZero:
2701     *dst++ = '0';
2702     *dst++ = upperCase ? 'X': 'x';
2703     *dst++ = '0';
2704     if (hexDigits > 1) {
2705       *dst++ = '.';
2706       memset (dst, '0', hexDigits - 1);
2707       dst += hexDigits - 1;
2708     }
2709     *dst++ = upperCase ? 'P': 'p';
2710     *dst++ = '0';
2711     break;
2712
2713   case fcNormal:
2714     dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
2715     break;
2716   }
2717
2718   *dst = 0;
2719
2720   return static_cast<unsigned int>(dst - p);
2721 }
2722
2723 /* Does the hard work of outputting the correctly rounded hexadecimal
2724    form of a normal floating point number with the specified number of
2725    hexadecimal digits.  If HEXDIGITS is zero the minimum number of
2726    digits necessary to print the value precisely is output.  */
2727 char *
2728 APFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
2729                                   bool upperCase,
2730                                   roundingMode rounding_mode) const
2731 {
2732   unsigned int count, valueBits, shift, partsCount, outputDigits;
2733   const char *hexDigitChars;
2734   const integerPart *significand;
2735   char *p;
2736   bool roundUp;
2737
2738   *dst++ = '0';
2739   *dst++ = upperCase ? 'X': 'x';
2740
2741   roundUp = false;
2742   hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower;
2743
2744   significand = significandParts();
2745   partsCount = partCount();
2746
2747   /* +3 because the first digit only uses the single integer bit, so
2748      we have 3 virtual zero most-significant-bits.  */
2749   valueBits = semantics->precision + 3;
2750   shift = integerPartWidth - valueBits % integerPartWidth;
2751
2752   /* The natural number of digits required ignoring trailing
2753      insignificant zeroes.  */
2754   outputDigits = (valueBits - significandLSB () + 3) / 4;
2755
2756   /* hexDigits of zero means use the required number for the
2757      precision.  Otherwise, see if we are truncating.  If we are,
2758      find out if we need to round away from zero.  */
2759   if (hexDigits) {
2760     if (hexDigits < outputDigits) {
2761       /* We are dropping non-zero bits, so need to check how to round.
2762          "bits" is the number of dropped bits.  */
2763       unsigned int bits;
2764       lostFraction fraction;
2765
2766       bits = valueBits - hexDigits * 4;
2767       fraction = lostFractionThroughTruncation (significand, partsCount, bits);
2768       roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
2769     }
2770     outputDigits = hexDigits;
2771   }
2772
2773   /* Write the digits consecutively, and start writing in the location
2774      of the hexadecimal point.  We move the most significant digit
2775      left and add the hexadecimal point later.  */
2776   p = ++dst;
2777
2778   count = (valueBits + integerPartWidth - 1) / integerPartWidth;
2779
2780   while (outputDigits && count) {
2781     integerPart part;
2782
2783     /* Put the most significant integerPartWidth bits in "part".  */
2784     if (--count == partsCount)
2785       part = 0;  /* An imaginary higher zero part.  */
2786     else
2787       part = significand[count] << shift;
2788
2789     if (count && shift)
2790       part |= significand[count - 1] >> (integerPartWidth - shift);
2791
2792     /* Convert as much of "part" to hexdigits as we can.  */
2793     unsigned int curDigits = integerPartWidth / 4;
2794
2795     if (curDigits > outputDigits)
2796       curDigits = outputDigits;
2797     dst += partAsHex (dst, part, curDigits, hexDigitChars);
2798     outputDigits -= curDigits;
2799   }
2800
2801   if (roundUp) {
2802     char *q = dst;
2803
2804     /* Note that hexDigitChars has a trailing '0'.  */
2805     do {
2806       q--;
2807       *q = hexDigitChars[hexDigitValue (*q) + 1];
2808     } while (*q == '0');
2809     assert(q >= p);
2810   } else {
2811     /* Add trailing zeroes.  */
2812     memset (dst, '0', outputDigits);
2813     dst += outputDigits;
2814   }
2815
2816   /* Move the most significant digit to before the point, and if there
2817      is something after the decimal point add it.  This must come
2818      after rounding above.  */
2819   p[-1] = p[0];
2820   if (dst -1 == p)
2821     dst--;
2822   else
2823     p[0] = '.';
2824
2825   /* Finally output the exponent.  */
2826   *dst++ = upperCase ? 'P': 'p';
2827
2828   return writeSignedDecimal (dst, exponent);
2829 }
2830
2831 hash_code llvm::hash_value(const APFloat &Arg) {
2832   if (!Arg.isFiniteNonZero())
2833     return hash_combine((uint8_t)Arg.category,
2834                         // NaN has no sign, fix it at zero.
2835                         Arg.isNaN() ? (uint8_t)0 : (uint8_t)Arg.sign,
2836                         Arg.semantics->precision);
2837
2838   // Normal floats need their exponent and significand hashed.
2839   return hash_combine((uint8_t)Arg.category, (uint8_t)Arg.sign,
2840                       Arg.semantics->precision, Arg.exponent,
2841                       hash_combine_range(
2842                         Arg.significandParts(),
2843                         Arg.significandParts() + Arg.partCount()));
2844 }
2845
2846 // Conversion from APFloat to/from host float/double.  It may eventually be
2847 // possible to eliminate these and have everybody deal with APFloats, but that
2848 // will take a while.  This approach will not easily extend to long double.
2849 // Current implementation requires integerPartWidth==64, which is correct at
2850 // the moment but could be made more general.
2851
2852 // Denormals have exponent minExponent in APFloat, but minExponent-1 in
2853 // the actual IEEE respresentations.  We compensate for that here.
2854
2855 APInt
2856 APFloat::convertF80LongDoubleAPFloatToAPInt() const
2857 {
2858   assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended);
2859   assert(partCount()==2);
2860
2861   uint64_t myexponent, mysignificand;
2862
2863   if (isFiniteNonZero()) {
2864     myexponent = exponent+16383; //bias
2865     mysignificand = significandParts()[0];
2866     if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
2867       myexponent = 0;   // denormal
2868   } else if (category==fcZero) {
2869     myexponent = 0;
2870     mysignificand = 0;
2871   } else if (category==fcInfinity) {
2872     myexponent = 0x7fff;
2873     mysignificand = 0x8000000000000000ULL;
2874   } else {
2875     assert(category == fcNaN && "Unknown category");
2876     myexponent = 0x7fff;
2877     mysignificand = significandParts()[0];
2878   }
2879
2880   uint64_t words[2];
2881   words[0] = mysignificand;
2882   words[1] =  ((uint64_t)(sign & 1) << 15) |
2883               (myexponent & 0x7fffLL);
2884   return APInt(80, words);
2885 }
2886
2887 APInt
2888 APFloat::convertPPCDoubleDoubleAPFloatToAPInt() const
2889 {
2890   assert(semantics == (const llvm::fltSemantics*)&PPCDoubleDouble);
2891   assert(partCount()==2);
2892
2893   uint64_t words[2];
2894   opStatus fs;
2895   bool losesInfo;
2896
2897   // Convert number to double.  To avoid spurious underflows, we re-
2898   // normalize against the "double" minExponent first, and only *then*
2899   // truncate the mantissa.  The result of that second conversion
2900   // may be inexact, but should never underflow.
2901   // Declare fltSemantics before APFloat that uses it (and
2902   // saves pointer to it) to ensure correct destruction order.
2903   fltSemantics extendedSemantics = *semantics;
2904   extendedSemantics.minExponent = IEEEdouble.minExponent;
2905   APFloat extended(*this);
2906   fs = extended.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
2907   assert(fs == opOK && !losesInfo);
2908   (void)fs;
2909
2910   APFloat u(extended);
2911   fs = u.convert(IEEEdouble, rmNearestTiesToEven, &losesInfo);
2912   assert(fs == opOK || fs == opInexact);
2913   (void)fs;
2914   words[0] = *u.convertDoubleAPFloatToAPInt().getRawData();
2915
2916   // If conversion was exact or resulted in a special case, we're done;
2917   // just set the second double to zero.  Otherwise, re-convert back to
2918   // the extended format and compute the difference.  This now should
2919   // convert exactly to double.
2920   if (u.isFiniteNonZero() && losesInfo) {
2921     fs = u.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
2922     assert(fs == opOK && !losesInfo);
2923     (void)fs;
2924
2925     APFloat v(extended);
2926     v.subtract(u, rmNearestTiesToEven);
2927     fs = v.convert(IEEEdouble, rmNearestTiesToEven, &losesInfo);
2928     assert(fs == opOK && !losesInfo);
2929     (void)fs;
2930     words[1] = *v.convertDoubleAPFloatToAPInt().getRawData();
2931   } else {
2932     words[1] = 0;
2933   }
2934
2935   return APInt(128, words);
2936 }
2937
2938 APInt
2939 APFloat::convertQuadrupleAPFloatToAPInt() const
2940 {
2941   assert(semantics == (const llvm::fltSemantics*)&IEEEquad);
2942   assert(partCount()==2);
2943
2944   uint64_t myexponent, mysignificand, mysignificand2;
2945
2946   if (isFiniteNonZero()) {
2947     myexponent = exponent+16383; //bias
2948     mysignificand = significandParts()[0];
2949     mysignificand2 = significandParts()[1];
2950     if (myexponent==1 && !(mysignificand2 & 0x1000000000000LL))
2951       myexponent = 0;   // denormal
2952   } else if (category==fcZero) {
2953     myexponent = 0;
2954     mysignificand = mysignificand2 = 0;
2955   } else if (category==fcInfinity) {
2956     myexponent = 0x7fff;
2957     mysignificand = mysignificand2 = 0;
2958   } else {
2959     assert(category == fcNaN && "Unknown category!");
2960     myexponent = 0x7fff;
2961     mysignificand = significandParts()[0];
2962     mysignificand2 = significandParts()[1];
2963   }
2964
2965   uint64_t words[2];
2966   words[0] = mysignificand;
2967   words[1] = ((uint64_t)(sign & 1) << 63) |
2968              ((myexponent & 0x7fff) << 48) |
2969              (mysignificand2 & 0xffffffffffffLL);
2970
2971   return APInt(128, words);
2972 }
2973
2974 APInt
2975 APFloat::convertDoubleAPFloatToAPInt() const
2976 {
2977   assert(semantics == (const llvm::fltSemantics*)&IEEEdouble);
2978   assert(partCount()==1);
2979
2980   uint64_t myexponent, mysignificand;
2981
2982   if (isFiniteNonZero()) {
2983     myexponent = exponent+1023; //bias
2984     mysignificand = *significandParts();
2985     if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2986       myexponent = 0;   // denormal
2987   } else if (category==fcZero) {
2988     myexponent = 0;
2989     mysignificand = 0;
2990   } else if (category==fcInfinity) {
2991     myexponent = 0x7ff;
2992     mysignificand = 0;
2993   } else {
2994     assert(category == fcNaN && "Unknown category!");
2995     myexponent = 0x7ff;
2996     mysignificand = *significandParts();
2997   }
2998
2999   return APInt(64, ((((uint64_t)(sign & 1) << 63) |
3000                      ((myexponent & 0x7ff) <<  52) |
3001                      (mysignificand & 0xfffffffffffffLL))));
3002 }
3003
3004 APInt
3005 APFloat::convertFloatAPFloatToAPInt() const
3006 {
3007   assert(semantics == (const llvm::fltSemantics*)&IEEEsingle);
3008   assert(partCount()==1);
3009
3010   uint32_t myexponent, mysignificand;
3011
3012   if (isFiniteNonZero()) {
3013     myexponent = exponent+127; //bias
3014     mysignificand = (uint32_t)*significandParts();
3015     if (myexponent == 1 && !(mysignificand & 0x800000))
3016       myexponent = 0;   // denormal
3017   } else if (category==fcZero) {
3018     myexponent = 0;
3019     mysignificand = 0;
3020   } else if (category==fcInfinity) {
3021     myexponent = 0xff;
3022     mysignificand = 0;
3023   } else {
3024     assert(category == fcNaN && "Unknown category!");
3025     myexponent = 0xff;
3026     mysignificand = (uint32_t)*significandParts();
3027   }
3028
3029   return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) |
3030                     (mysignificand & 0x7fffff)));
3031 }
3032
3033 APInt
3034 APFloat::convertHalfAPFloatToAPInt() const
3035 {
3036   assert(semantics == (const llvm::fltSemantics*)&IEEEhalf);
3037   assert(partCount()==1);
3038
3039   uint32_t myexponent, mysignificand;
3040
3041   if (isFiniteNonZero()) {
3042     myexponent = exponent+15; //bias
3043     mysignificand = (uint32_t)*significandParts();
3044     if (myexponent == 1 && !(mysignificand & 0x400))
3045       myexponent = 0;   // denormal
3046   } else if (category==fcZero) {
3047     myexponent = 0;
3048     mysignificand = 0;
3049   } else if (category==fcInfinity) {
3050     myexponent = 0x1f;
3051     mysignificand = 0;
3052   } else {
3053     assert(category == fcNaN && "Unknown category!");
3054     myexponent = 0x1f;
3055     mysignificand = (uint32_t)*significandParts();
3056   }
3057
3058   return APInt(16, (((sign&1) << 15) | ((myexponent&0x1f) << 10) |
3059                     (mysignificand & 0x3ff)));
3060 }
3061
3062 // This function creates an APInt that is just a bit map of the floating
3063 // point constant as it would appear in memory.  It is not a conversion,
3064 // and treating the result as a normal integer is unlikely to be useful.
3065
3066 APInt
3067 APFloat::bitcastToAPInt() const
3068 {
3069   if (semantics == (const llvm::fltSemantics*)&IEEEhalf)
3070     return convertHalfAPFloatToAPInt();
3071
3072   if (semantics == (const llvm::fltSemantics*)&IEEEsingle)
3073     return convertFloatAPFloatToAPInt();
3074
3075   if (semantics == (const llvm::fltSemantics*)&IEEEdouble)
3076     return convertDoubleAPFloatToAPInt();
3077
3078   if (semantics == (const llvm::fltSemantics*)&IEEEquad)
3079     return convertQuadrupleAPFloatToAPInt();
3080
3081   if (semantics == (const llvm::fltSemantics*)&PPCDoubleDouble)
3082     return convertPPCDoubleDoubleAPFloatToAPInt();
3083
3084   assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended &&
3085          "unknown format!");
3086   return convertF80LongDoubleAPFloatToAPInt();
3087 }
3088
3089 float
3090 APFloat::convertToFloat() const
3091 {
3092   assert(semantics == (const llvm::fltSemantics*)&IEEEsingle &&
3093          "Float semantics are not IEEEsingle");
3094   APInt api = bitcastToAPInt();
3095   return api.bitsToFloat();
3096 }
3097
3098 double
3099 APFloat::convertToDouble() const
3100 {
3101   assert(semantics == (const llvm::fltSemantics*)&IEEEdouble &&
3102          "Float semantics are not IEEEdouble");
3103   APInt api = bitcastToAPInt();
3104   return api.bitsToDouble();
3105 }
3106
3107 /// Integer bit is explicit in this format.  Intel hardware (387 and later)
3108 /// does not support these bit patterns:
3109 ///  exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity")
3110 ///  exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN")
3111 ///  exponent = 0, integer bit 1 ("pseudodenormal")
3112 ///  exponent!=0 nor all 1's, integer bit 0 ("unnormal")
3113 /// At the moment, the first two are treated as NaNs, the second two as Normal.
3114 void
3115 APFloat::initFromF80LongDoubleAPInt(const APInt &api)
3116 {
3117   assert(api.getBitWidth()==80);
3118   uint64_t i1 = api.getRawData()[0];
3119   uint64_t i2 = api.getRawData()[1];
3120   uint64_t myexponent = (i2 & 0x7fff);
3121   uint64_t mysignificand = i1;
3122
3123   initialize(&APFloat::x87DoubleExtended);
3124   assert(partCount()==2);
3125
3126   sign = static_cast<unsigned int>(i2>>15);
3127   if (myexponent==0 && mysignificand==0) {
3128     // exponent, significand meaningless
3129     category = fcZero;
3130   } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
3131     // exponent, significand meaningless
3132     category = fcInfinity;
3133   } else if (myexponent==0x7fff && mysignificand!=0x8000000000000000ULL) {
3134     // exponent meaningless
3135     category = fcNaN;
3136     significandParts()[0] = mysignificand;
3137     significandParts()[1] = 0;
3138   } else {
3139     category = fcNormal;
3140     exponent = myexponent - 16383;
3141     significandParts()[0] = mysignificand;
3142     significandParts()[1] = 0;
3143     if (myexponent==0)          // denormal
3144       exponent = -16382;
3145   }
3146 }
3147
3148 void
3149 APFloat::initFromPPCDoubleDoubleAPInt(const APInt &api)
3150 {
3151   assert(api.getBitWidth()==128);
3152   uint64_t i1 = api.getRawData()[0];
3153   uint64_t i2 = api.getRawData()[1];
3154   opStatus fs;
3155   bool losesInfo;
3156
3157   // Get the first double and convert to our format.
3158   initFromDoubleAPInt(APInt(64, i1));
3159   fs = convert(PPCDoubleDouble, rmNearestTiesToEven, &losesInfo);
3160   assert(fs == opOK && !losesInfo);
3161   (void)fs;
3162
3163   // Unless we have a special case, add in second double.
3164   if (isFiniteNonZero()) {
3165     APFloat v(IEEEdouble, APInt(64, i2));
3166     fs = v.convert(PPCDoubleDouble, rmNearestTiesToEven, &losesInfo);
3167     assert(fs == opOK && !losesInfo);
3168     (void)fs;
3169
3170     add(v, rmNearestTiesToEven);
3171   }
3172 }
3173
3174 void
3175 APFloat::initFromQuadrupleAPInt(const APInt &api)
3176 {
3177   assert(api.getBitWidth()==128);
3178   uint64_t i1 = api.getRawData()[0];
3179   uint64_t i2 = api.getRawData()[1];
3180   uint64_t myexponent = (i2 >> 48) & 0x7fff;
3181   uint64_t mysignificand  = i1;
3182   uint64_t mysignificand2 = i2 & 0xffffffffffffLL;
3183
3184   initialize(&APFloat::IEEEquad);
3185   assert(partCount()==2);
3186
3187   sign = static_cast<unsigned int>(i2>>63);
3188   if (myexponent==0 &&
3189       (mysignificand==0 && mysignificand2==0)) {
3190     // exponent, significand meaningless
3191     category = fcZero;
3192   } else if (myexponent==0x7fff &&
3193              (mysignificand==0 && mysignificand2==0)) {
3194     // exponent, significand meaningless
3195     category = fcInfinity;
3196   } else if (myexponent==0x7fff &&
3197              (mysignificand!=0 || mysignificand2 !=0)) {
3198     // exponent meaningless
3199     category = fcNaN;
3200     significandParts()[0] = mysignificand;
3201     significandParts()[1] = mysignificand2;
3202   } else {
3203     category = fcNormal;
3204     exponent = myexponent - 16383;
3205     significandParts()[0] = mysignificand;
3206     significandParts()[1] = mysignificand2;
3207     if (myexponent==0)          // denormal
3208       exponent = -16382;
3209     else
3210       significandParts()[1] |= 0x1000000000000LL;  // integer bit
3211   }
3212 }
3213
3214 void
3215 APFloat::initFromDoubleAPInt(const APInt &api)
3216 {
3217   assert(api.getBitWidth()==64);
3218   uint64_t i = *api.getRawData();
3219   uint64_t myexponent = (i >> 52) & 0x7ff;
3220   uint64_t mysignificand = i & 0xfffffffffffffLL;
3221
3222   initialize(&APFloat::IEEEdouble);
3223   assert(partCount()==1);
3224
3225   sign = static_cast<unsigned int>(i>>63);
3226   if (myexponent==0 && mysignificand==0) {
3227     // exponent, significand meaningless
3228     category = fcZero;
3229   } else if (myexponent==0x7ff && mysignificand==0) {
3230     // exponent, significand meaningless
3231     category = fcInfinity;
3232   } else if (myexponent==0x7ff && mysignificand!=0) {
3233     // exponent meaningless
3234     category = fcNaN;
3235     *significandParts() = mysignificand;
3236   } else {
3237     category = fcNormal;
3238     exponent = myexponent - 1023;
3239     *significandParts() = mysignificand;
3240     if (myexponent==0)          // denormal
3241       exponent = -1022;
3242     else
3243       *significandParts() |= 0x10000000000000LL;  // integer bit
3244   }
3245 }
3246
3247 void
3248 APFloat::initFromFloatAPInt(const APInt & api)
3249 {
3250   assert(api.getBitWidth()==32);
3251   uint32_t i = (uint32_t)*api.getRawData();
3252   uint32_t myexponent = (i >> 23) & 0xff;
3253   uint32_t mysignificand = i & 0x7fffff;
3254
3255   initialize(&APFloat::IEEEsingle);
3256   assert(partCount()==1);
3257
3258   sign = i >> 31;
3259   if (myexponent==0 && mysignificand==0) {
3260     // exponent, significand meaningless
3261     category = fcZero;
3262   } else if (myexponent==0xff && mysignificand==0) {
3263     // exponent, significand meaningless
3264     category = fcInfinity;
3265   } else if (myexponent==0xff && mysignificand!=0) {
3266     // sign, exponent, significand meaningless
3267     category = fcNaN;
3268     *significandParts() = mysignificand;
3269   } else {
3270     category = fcNormal;
3271     exponent = myexponent - 127;  //bias
3272     *significandParts() = mysignificand;
3273     if (myexponent==0)    // denormal
3274       exponent = -126;
3275     else
3276       *significandParts() |= 0x800000; // integer bit
3277   }
3278 }
3279
3280 void
3281 APFloat::initFromHalfAPInt(const APInt & api)
3282 {
3283   assert(api.getBitWidth()==16);
3284   uint32_t i = (uint32_t)*api.getRawData();
3285   uint32_t myexponent = (i >> 10) & 0x1f;
3286   uint32_t mysignificand = i & 0x3ff;
3287
3288   initialize(&APFloat::IEEEhalf);
3289   assert(partCount()==1);
3290
3291   sign = i >> 15;
3292   if (myexponent==0 && mysignificand==0) {
3293     // exponent, significand meaningless
3294     category = fcZero;
3295   } else if (myexponent==0x1f && mysignificand==0) {
3296     // exponent, significand meaningless
3297     category = fcInfinity;
3298   } else if (myexponent==0x1f && mysignificand!=0) {
3299     // sign, exponent, significand meaningless
3300     category = fcNaN;
3301     *significandParts() = mysignificand;
3302   } else {
3303     category = fcNormal;
3304     exponent = myexponent - 15;  //bias
3305     *significandParts() = mysignificand;
3306     if (myexponent==0)    // denormal
3307       exponent = -14;
3308     else
3309       *significandParts() |= 0x400; // integer bit
3310   }
3311 }
3312
3313 /// Treat api as containing the bits of a floating point number.  Currently
3314 /// we infer the floating point type from the size of the APInt.  The
3315 /// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful
3316 /// when the size is anything else).
3317 void
3318 APFloat::initFromAPInt(const fltSemantics* Sem, const APInt& api)
3319 {
3320   if (Sem == &IEEEhalf)
3321     return initFromHalfAPInt(api);
3322   if (Sem == &IEEEsingle)
3323     return initFromFloatAPInt(api);
3324   if (Sem == &IEEEdouble)
3325     return initFromDoubleAPInt(api);
3326   if (Sem == &x87DoubleExtended)
3327     return initFromF80LongDoubleAPInt(api);
3328   if (Sem == &IEEEquad)
3329     return initFromQuadrupleAPInt(api);
3330   if (Sem == &PPCDoubleDouble)
3331     return initFromPPCDoubleDoubleAPInt(api);
3332
3333   llvm_unreachable(nullptr);
3334 }
3335
3336 APFloat
3337 APFloat::getAllOnesValue(unsigned BitWidth, bool isIEEE)
3338 {
3339   switch (BitWidth) {
3340   case 16:
3341     return APFloat(IEEEhalf, APInt::getAllOnesValue(BitWidth));
3342   case 32:
3343     return APFloat(IEEEsingle, APInt::getAllOnesValue(BitWidth));
3344   case 64:
3345     return APFloat(IEEEdouble, APInt::getAllOnesValue(BitWidth));
3346   case 80:
3347     return APFloat(x87DoubleExtended, APInt::getAllOnesValue(BitWidth));
3348   case 128:
3349     if (isIEEE)
3350       return APFloat(IEEEquad, APInt::getAllOnesValue(BitWidth));
3351     return APFloat(PPCDoubleDouble, APInt::getAllOnesValue(BitWidth));
3352   default:
3353     llvm_unreachable("Unknown floating bit width");
3354   }
3355 }
3356
3357 /// Make this number the largest magnitude normal number in the given
3358 /// semantics.
3359 void APFloat::makeLargest(bool Negative) {
3360   // We want (in interchange format):
3361   //   sign = {Negative}
3362   //   exponent = 1..10
3363   //   significand = 1..1
3364   category = fcNormal;
3365   sign = Negative;
3366   exponent = semantics->maxExponent;
3367
3368   // Use memset to set all but the highest integerPart to all ones.
3369   integerPart *significand = significandParts();
3370   unsigned PartCount = partCount();
3371   memset(significand, 0xFF, sizeof(integerPart)*(PartCount - 1));
3372
3373   // Set the high integerPart especially setting all unused top bits for
3374   // internal consistency.
3375   const unsigned NumUnusedHighBits =
3376     PartCount*integerPartWidth - semantics->precision;
3377   significand[PartCount - 1] = ~integerPart(0) >> NumUnusedHighBits;
3378 }
3379
3380 /// Make this number the smallest magnitude denormal number in the given
3381 /// semantics.
3382 void APFloat::makeSmallest(bool Negative) {
3383   // We want (in interchange format):
3384   //   sign = {Negative}
3385   //   exponent = 0..0
3386   //   significand = 0..01
3387   category = fcNormal;
3388   sign = Negative;
3389   exponent = semantics->minExponent;
3390   APInt::tcSet(significandParts(), 1, partCount());
3391 }
3392
3393
3394 APFloat APFloat::getLargest(const fltSemantics &Sem, bool Negative) {
3395   // We want (in interchange format):
3396   //   sign = {Negative}
3397   //   exponent = 1..10
3398   //   significand = 1..1
3399   APFloat Val(Sem, uninitialized);
3400   Val.makeLargest(Negative);
3401   return Val;
3402 }
3403
3404 APFloat APFloat::getSmallest(const fltSemantics &Sem, bool Negative) {
3405   // We want (in interchange format):
3406   //   sign = {Negative}
3407   //   exponent = 0..0
3408   //   significand = 0..01
3409   APFloat Val(Sem, uninitialized);
3410   Val.makeSmallest(Negative);
3411   return Val;
3412 }
3413
3414 APFloat APFloat::getSmallestNormalized(const fltSemantics &Sem, bool Negative) {
3415   APFloat Val(Sem, uninitialized);
3416
3417   // We want (in interchange format):
3418   //   sign = {Negative}
3419   //   exponent = 0..0
3420   //   significand = 10..0
3421
3422   Val.category = fcNormal;
3423   Val.zeroSignificand();
3424   Val.sign = Negative;
3425   Val.exponent = Sem.minExponent;
3426   Val.significandParts()[partCountForBits(Sem.precision)-1] |=
3427     (((integerPart) 1) << ((Sem.precision - 1) % integerPartWidth));
3428
3429   return Val;
3430 }
3431
3432 APFloat::APFloat(const fltSemantics &Sem, const APInt &API) {
3433   initFromAPInt(&Sem, API);
3434 }
3435
3436 APFloat::APFloat(float f) {
3437   initFromAPInt(&IEEEsingle, APInt::floatToBits(f));
3438 }
3439
3440 APFloat::APFloat(double d) {
3441   initFromAPInt(&IEEEdouble, APInt::doubleToBits(d));
3442 }
3443
3444 namespace {
3445   void append(SmallVectorImpl<char> &Buffer, StringRef Str) {
3446     Buffer.append(Str.begin(), Str.end());
3447   }
3448
3449   /// Removes data from the given significand until it is no more
3450   /// precise than is required for the desired precision.
3451   void AdjustToPrecision(APInt &significand,
3452                          int &exp, unsigned FormatPrecision) {
3453     unsigned bits = significand.getActiveBits();
3454
3455     // 196/59 is a very slight overestimate of lg_2(10).
3456     unsigned bitsRequired = (FormatPrecision * 196 + 58) / 59;
3457
3458     if (bits <= bitsRequired) return;
3459
3460     unsigned tensRemovable = (bits - bitsRequired) * 59 / 196;
3461     if (!tensRemovable) return;
3462
3463     exp += tensRemovable;
3464
3465     APInt divisor(significand.getBitWidth(), 1);
3466     APInt powten(significand.getBitWidth(), 10);
3467     while (true) {
3468       if (tensRemovable & 1)
3469         divisor *= powten;
3470       tensRemovable >>= 1;
3471       if (!tensRemovable) break;
3472       powten *= powten;
3473     }
3474
3475     significand = significand.udiv(divisor);
3476
3477     // Truncate the significand down to its active bit count.
3478     significand = significand.trunc(significand.getActiveBits());
3479   }
3480
3481
3482   void AdjustToPrecision(SmallVectorImpl<char> &buffer,
3483                          int &exp, unsigned FormatPrecision) {
3484     unsigned N = buffer.size();
3485     if (N <= FormatPrecision) return;
3486
3487     // The most significant figures are the last ones in the buffer.
3488     unsigned FirstSignificant = N - FormatPrecision;
3489
3490     // Round.
3491     // FIXME: this probably shouldn't use 'round half up'.
3492
3493     // Rounding down is just a truncation, except we also want to drop
3494     // trailing zeros from the new result.
3495     if (buffer[FirstSignificant - 1] < '5') {
3496       while (FirstSignificant < N && buffer[FirstSignificant] == '0')
3497         FirstSignificant++;
3498
3499       exp += FirstSignificant;
3500       buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3501       return;
3502     }
3503
3504     // Rounding up requires a decimal add-with-carry.  If we continue
3505     // the carry, the newly-introduced zeros will just be truncated.
3506     for (unsigned I = FirstSignificant; I != N; ++I) {
3507       if (buffer[I] == '9') {
3508         FirstSignificant++;
3509       } else {
3510         buffer[I]++;
3511         break;
3512       }
3513     }
3514
3515     // If we carried through, we have exactly one digit of precision.
3516     if (FirstSignificant == N) {
3517       exp += FirstSignificant;
3518       buffer.clear();
3519       buffer.push_back('1');
3520       return;
3521     }
3522
3523     exp += FirstSignificant;
3524     buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3525   }
3526 }
3527
3528 void APFloat::toString(SmallVectorImpl<char> &Str,
3529                        unsigned FormatPrecision,
3530                        unsigned FormatMaxPadding) const {
3531   switch (category) {
3532   case fcInfinity:
3533     if (isNegative())
3534       return append(Str, "-Inf");
3535     else
3536       return append(Str, "+Inf");
3537
3538   case fcNaN: return append(Str, "NaN");
3539
3540   case fcZero:
3541     if (isNegative())
3542       Str.push_back('-');
3543
3544     if (!FormatMaxPadding)
3545       append(Str, "0.0E+0");
3546     else
3547       Str.push_back('0');
3548     return;
3549
3550   case fcNormal:
3551     break;
3552   }
3553
3554   if (isNegative())
3555     Str.push_back('-');
3556
3557   // Decompose the number into an APInt and an exponent.
3558   int exp = exponent - ((int) semantics->precision - 1);
3559   APInt significand(semantics->precision,
3560                     makeArrayRef(significandParts(),
3561                                  partCountForBits(semantics->precision)));
3562
3563   // Set FormatPrecision if zero.  We want to do this before we
3564   // truncate trailing zeros, as those are part of the precision.
3565   if (!FormatPrecision) {
3566     // We use enough digits so the number can be round-tripped back to an
3567     // APFloat. The formula comes from "How to Print Floating-Point Numbers
3568     // Accurately" by Steele and White.
3569     // FIXME: Using a formula based purely on the precision is conservative;
3570     // we can print fewer digits depending on the actual value being printed.
3571
3572     // FormatPrecision = 2 + floor(significandBits / lg_2(10))
3573     FormatPrecision = 2 + semantics->precision * 59 / 196;
3574   }
3575
3576   // Ignore trailing binary zeros.
3577   int trailingZeros = significand.countTrailingZeros();
3578   exp += trailingZeros;
3579   significand = significand.lshr(trailingZeros);
3580
3581   // Change the exponent from 2^e to 10^e.
3582   if (exp == 0) {
3583     // Nothing to do.
3584   } else if (exp > 0) {
3585     // Just shift left.
3586     significand = significand.zext(semantics->precision + exp);
3587     significand <<= exp;
3588     exp = 0;
3589   } else { /* exp < 0 */
3590     int texp = -exp;
3591
3592     // We transform this using the identity:
3593     //   (N)(2^-e) == (N)(5^e)(10^-e)
3594     // This means we have to multiply N (the significand) by 5^e.
3595     // To avoid overflow, we have to operate on numbers large
3596     // enough to store N * 5^e:
3597     //   log2(N * 5^e) == log2(N) + e * log2(5)
3598     //                 <= semantics->precision + e * 137 / 59
3599     //   (log_2(5) ~ 2.321928 < 2.322034 ~ 137/59)
3600
3601     unsigned precision = semantics->precision + (137 * texp + 136) / 59;
3602
3603     // Multiply significand by 5^e.
3604     //   N * 5^0101 == N * 5^(1*1) * 5^(0*2) * 5^(1*4) * 5^(0*8)
3605     significand = significand.zext(precision);
3606     APInt five_to_the_i(precision, 5);
3607     while (true) {
3608       if (texp & 1) significand *= five_to_the_i;
3609
3610       texp >>= 1;
3611       if (!texp) break;
3612       five_to_the_i *= five_to_the_i;
3613     }
3614   }
3615
3616   AdjustToPrecision(significand, exp, FormatPrecision);
3617
3618   SmallVector<char, 256> buffer;
3619
3620   // Fill the buffer.
3621   unsigned precision = significand.getBitWidth();
3622   APInt ten(precision, 10);
3623   APInt digit(precision, 0);
3624
3625   bool inTrail = true;
3626   while (significand != 0) {
3627     // digit <- significand % 10
3628     // significand <- significand / 10
3629     APInt::udivrem(significand, ten, significand, digit);
3630
3631     unsigned d = digit.getZExtValue();
3632
3633     // Drop trailing zeros.
3634     if (inTrail && !d) exp++;
3635     else {
3636       buffer.push_back((char) ('0' + d));
3637       inTrail = false;
3638     }
3639   }
3640
3641   assert(!buffer.empty() && "no characters in buffer!");
3642
3643   // Drop down to FormatPrecision.
3644   // TODO: don't do more precise calculations above than are required.
3645   AdjustToPrecision(buffer, exp, FormatPrecision);
3646
3647   unsigned NDigits = buffer.size();
3648
3649   // Check whether we should use scientific notation.
3650   bool FormatScientific;
3651   if (!FormatMaxPadding)
3652     FormatScientific = true;
3653   else {
3654     if (exp >= 0) {
3655       // 765e3 --> 765000
3656       //              ^^^
3657       // But we shouldn't make the number look more precise than it is.
3658       FormatScientific = ((unsigned) exp > FormatMaxPadding ||
3659                           NDigits + (unsigned) exp > FormatPrecision);
3660     } else {
3661       // Power of the most significant digit.
3662       int MSD = exp + (int) (NDigits - 1);
3663       if (MSD >= 0) {
3664         // 765e-2 == 7.65
3665         FormatScientific = false;
3666       } else {
3667         // 765e-5 == 0.00765
3668         //           ^ ^^
3669         FormatScientific = ((unsigned) -MSD) > FormatMaxPadding;
3670       }
3671     }
3672   }
3673
3674   // Scientific formatting is pretty straightforward.
3675   if (FormatScientific) {
3676     exp += (NDigits - 1);
3677
3678     Str.push_back(buffer[NDigits-1]);
3679     Str.push_back('.');
3680     if (NDigits == 1)
3681       Str.push_back('0');
3682     else
3683       for (unsigned I = 1; I != NDigits; ++I)
3684         Str.push_back(buffer[NDigits-1-I]);
3685     Str.push_back('E');
3686
3687     Str.push_back(exp >= 0 ? '+' : '-');
3688     if (exp < 0) exp = -exp;
3689     SmallVector<char, 6> expbuf;
3690     do {
3691       expbuf.push_back((char) ('0' + (exp % 10)));
3692       exp /= 10;
3693     } while (exp);
3694     for (unsigned I = 0, E = expbuf.size(); I != E; ++I)
3695       Str.push_back(expbuf[E-1-I]);
3696     return;
3697   }
3698
3699   // Non-scientific, positive exponents.
3700   if (exp >= 0) {
3701     for (unsigned I = 0; I != NDigits; ++I)
3702       Str.push_back(buffer[NDigits-1-I]);
3703     for (unsigned I = 0; I != (unsigned) exp; ++I)
3704       Str.push_back('0');
3705     return;
3706   }
3707
3708   // Non-scientific, negative exponents.
3709
3710   // The number of digits to the left of the decimal point.
3711   int NWholeDigits = exp + (int) NDigits;
3712
3713   unsigned I = 0;
3714   if (NWholeDigits > 0) {
3715     for (; I != (unsigned) NWholeDigits; ++I)
3716       Str.push_back(buffer[NDigits-I-1]);
3717     Str.push_back('.');
3718   } else {
3719     unsigned NZeros = 1 + (unsigned) -NWholeDigits;
3720
3721     Str.push_back('0');
3722     Str.push_back('.');
3723     for (unsigned Z = 1; Z != NZeros; ++Z)
3724       Str.push_back('0');
3725   }
3726
3727   for (; I != NDigits; ++I)
3728     Str.push_back(buffer[NDigits-I-1]);
3729 }
3730
3731 bool APFloat::getExactInverse(APFloat *inv) const {
3732   // Special floats and denormals have no exact inverse.
3733   if (!isFiniteNonZero())
3734     return false;
3735
3736   // Check that the number is a power of two by making sure that only the
3737   // integer bit is set in the significand.
3738   if (significandLSB() != semantics->precision - 1)
3739     return false;
3740
3741   // Get the inverse.
3742   APFloat reciprocal(*semantics, 1ULL);
3743   if (reciprocal.divide(*this, rmNearestTiesToEven) != opOK)
3744     return false;
3745
3746   // Avoid multiplication with a denormal, it is not safe on all platforms and
3747   // may be slower than a normal division.
3748   if (reciprocal.isDenormal())
3749     return false;
3750
3751   assert(reciprocal.isFiniteNonZero() &&
3752          reciprocal.significandLSB() == reciprocal.semantics->precision - 1);
3753
3754   if (inv)
3755     *inv = reciprocal;
3756
3757   return true;
3758 }
3759
3760 bool APFloat::isSignaling() const {
3761   if (!isNaN())
3762     return false;
3763
3764   // IEEE-754R 2008 6.2.1: A signaling NaN bit string should be encoded with the
3765   // first bit of the trailing significand being 0.
3766   return !APInt::tcExtractBit(significandParts(), semantics->precision - 2);
3767 }
3768
3769 /// IEEE-754R 2008 5.3.1: nextUp/nextDown.
3770 ///
3771 /// *NOTE* since nextDown(x) = -nextUp(-x), we only implement nextUp with
3772 /// appropriate sign switching before/after the computation.
3773 APFloat::opStatus APFloat::next(bool nextDown) {
3774   // If we are performing nextDown, swap sign so we have -x.
3775   if (nextDown)
3776     changeSign();
3777
3778   // Compute nextUp(x)
3779   opStatus result = opOK;
3780
3781   // Handle each float category separately.
3782   switch (category) {
3783   case fcInfinity:
3784     // nextUp(+inf) = +inf
3785     if (!isNegative())
3786       break;
3787     // nextUp(-inf) = -getLargest()
3788     makeLargest(true);
3789     break;
3790   case fcNaN:
3791     // IEEE-754R 2008 6.2 Par 2: nextUp(sNaN) = qNaN. Set Invalid flag.
3792     // IEEE-754R 2008 6.2: nextUp(qNaN) = qNaN. Must be identity so we do not
3793     //                     change the payload.
3794     if (isSignaling()) {
3795       result = opInvalidOp;
3796       // For consistency, propagate the sign of the sNaN to the qNaN.
3797       makeNaN(false, isNegative(), nullptr);
3798     }
3799     break;
3800   case fcZero:
3801     // nextUp(pm 0) = +getSmallest()
3802     makeSmallest(false);
3803     break;
3804   case fcNormal:
3805     // nextUp(-getSmallest()) = -0
3806     if (isSmallest() && isNegative()) {
3807       APInt::tcSet(significandParts(), 0, partCount());
3808       category = fcZero;
3809       exponent = 0;
3810       break;
3811     }
3812
3813     // nextUp(getLargest()) == INFINITY
3814     if (isLargest() && !isNegative()) {
3815       APInt::tcSet(significandParts(), 0, partCount());
3816       category = fcInfinity;
3817       exponent = semantics->maxExponent + 1;
3818       break;
3819     }
3820
3821     // nextUp(normal) == normal + inc.
3822     if (isNegative()) {
3823       // If we are negative, we need to decrement the significand.
3824
3825       // We only cross a binade boundary that requires adjusting the exponent
3826       // if:
3827       //   1. exponent != semantics->minExponent. This implies we are not in the
3828       //   smallest binade or are dealing with denormals.
3829       //   2. Our significand excluding the integral bit is all zeros.
3830       bool WillCrossBinadeBoundary =
3831         exponent != semantics->minExponent && isSignificandAllZeros();
3832
3833       // Decrement the significand.
3834       //
3835       // We always do this since:
3836       //   1. If we are dealing with a non-binade decrement, by definition we
3837       //   just decrement the significand.
3838       //   2. If we are dealing with a normal -> normal binade decrement, since
3839       //   we have an explicit integral bit the fact that all bits but the
3840       //   integral bit are zero implies that subtracting one will yield a
3841       //   significand with 0 integral bit and 1 in all other spots. Thus we
3842       //   must just adjust the exponent and set the integral bit to 1.
3843       //   3. If we are dealing with a normal -> denormal binade decrement,
3844       //   since we set the integral bit to 0 when we represent denormals, we
3845       //   just decrement the significand.
3846       integerPart *Parts = significandParts();
3847       APInt::tcDecrement(Parts, partCount());
3848
3849       if (WillCrossBinadeBoundary) {
3850         // Our result is a normal number. Do the following:
3851         // 1. Set the integral bit to 1.
3852         // 2. Decrement the exponent.
3853         APInt::tcSetBit(Parts, semantics->precision - 1);
3854         exponent--;
3855       }
3856     } else {
3857       // If we are positive, we need to increment the significand.
3858
3859       // We only cross a binade boundary that requires adjusting the exponent if
3860       // the input is not a denormal and all of said input's significand bits
3861       // are set. If all of said conditions are true: clear the significand, set
3862       // the integral bit to 1, and increment the exponent. If we have a
3863       // denormal always increment since moving denormals and the numbers in the
3864       // smallest normal binade have the same exponent in our representation.
3865       bool WillCrossBinadeBoundary = !isDenormal() && isSignificandAllOnes();
3866
3867       if (WillCrossBinadeBoundary) {
3868         integerPart *Parts = significandParts();
3869         APInt::tcSet(Parts, 0, partCount());
3870         APInt::tcSetBit(Parts, semantics->precision - 1);
3871         assert(exponent != semantics->maxExponent &&
3872                "We can not increment an exponent beyond the maxExponent allowed"
3873                " by the given floating point semantics.");
3874         exponent++;
3875       } else {
3876         incrementSignificand();
3877       }
3878     }
3879     break;
3880   }
3881
3882   // If we are performing nextDown, swap sign so we have -nextUp(-x)
3883   if (nextDown)
3884     changeSign();
3885
3886   return result;
3887 }
3888
3889 void
3890 APFloat::makeInf(bool Negative) {
3891   category = fcInfinity;
3892   sign = Negative;
3893   exponent = semantics->maxExponent + 1;
3894   APInt::tcSet(significandParts(), 0, partCount());
3895 }
3896
3897 void
3898 APFloat::makeZero(bool Negative) {
3899   category = fcZero;
3900   sign = Negative;
3901   exponent = semantics->minExponent-1;
3902   APInt::tcSet(significandParts(), 0, partCount());  
3903 }