Coverage Report

Created: 2026-08-31 07:21

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