forked from llvm-mirror/llvm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAPFloat.cpp
3906 lines (3252 loc) · 115 KB
/
APFloat.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===-- APFloat.cpp - Implement APFloat class -----------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements a class to represent arbitrary precision floating
// point values and provide a variety of arithmetic operations on them.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/APSInt.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/MathExtras.h"
#include <cstring>
#include <limits.h>
using namespace llvm;
/// A macro used to combine two fcCategory enums into one key which can be used
/// in a switch statement to classify how the interaction of two APFloat's
/// categories affects an operation.
///
/// TODO: If clang source code is ever allowed to use constexpr in its own
/// codebase, change this into a static inline function.
#define PackCategoriesIntoKey(_lhs, _rhs) ((_lhs) * 4 + (_rhs))
/* Assumed in hexadecimal significand parsing, and conversion to
hexadecimal strings. */
#define COMPILE_TIME_ASSERT(cond) extern int CTAssert[(cond) ? 1 : -1]
COMPILE_TIME_ASSERT(integerPartWidth % 4 == 0);
namespace llvm {
/* Represents floating point arithmetic semantics. */
struct fltSemantics {
/* The largest E such that 2^E is representable; this matches the
definition of IEEE 754. */
APFloat::ExponentType maxExponent;
/* The smallest E such that 2^E is a normalized number; this
matches the definition of IEEE 754. */
APFloat::ExponentType minExponent;
/* Number of bits in the significand. This includes the integer
bit. */
unsigned int precision;
};
const fltSemantics APFloat::IEEEhalf = { 15, -14, 11 };
const fltSemantics APFloat::IEEEsingle = { 127, -126, 24 };
const fltSemantics APFloat::IEEEdouble = { 1023, -1022, 53 };
const fltSemantics APFloat::IEEEquad = { 16383, -16382, 113 };
const fltSemantics APFloat::x87DoubleExtended = { 16383, -16382, 64 };
const fltSemantics APFloat::Bogus = { 0, 0, 0 };
/* The PowerPC format consists of two doubles. It does not map cleanly
onto the usual format above. It is approximated using twice the
mantissa bits. Note that for exponents near the double minimum,
we no longer can represent the full 106 mantissa bits, so those
will be treated as denormal numbers.
FIXME: While this approximation is equivalent to what GCC uses for
compile-time arithmetic on PPC double-double numbers, it is not able
to represent all possible values held by a PPC double-double number,
for example: (long double) 1.0 + (long double) 0x1p-106
Should this be replaced by a full emulation of PPC double-double? */
const fltSemantics APFloat::PPCDoubleDouble = { 1023, -1022 + 53, 53 + 53 };
/* A tight upper bound on number of parts required to hold the value
pow(5, power) is
power * 815 / (351 * integerPartWidth) + 1
However, whilst the result may require only this many parts,
because we are multiplying two values to get it, the
multiplication may require an extra part with the excess part
being zero (consider the trivial case of 1 * 1, tcFullMultiply
requires two parts to hold the single-part result). So we add an
extra one to guarantee enough space whilst multiplying. */
const unsigned int maxExponent = 16383;
const unsigned int maxPrecision = 113;
const unsigned int maxPowerOfFiveExponent = maxExponent + maxPrecision - 1;
const unsigned int maxPowerOfFiveParts = 2 + ((maxPowerOfFiveExponent * 815)
/ (351 * integerPartWidth));
}
/* A bunch of private, handy routines. */
static inline unsigned int
partCountForBits(unsigned int bits)
{
return ((bits) + integerPartWidth - 1) / integerPartWidth;
}
/* Returns 0U-9U. Return values >= 10U are not digits. */
static inline unsigned int
decDigitValue(unsigned int c)
{
return c - '0';
}
/* Return the value of a decimal exponent of the form
[+-]ddddddd.
If the exponent overflows, returns a large exponent with the
appropriate sign. */
static int
readExponent(StringRef::iterator begin, StringRef::iterator end)
{
bool isNegative;
unsigned int absExponent;
const unsigned int overlargeExponent = 24000; /* FIXME. */
StringRef::iterator p = begin;
assert(p != end && "Exponent has no digits");
isNegative = (*p == '-');
if (*p == '-' || *p == '+') {
p++;
assert(p != end && "Exponent has no digits");
}
absExponent = decDigitValue(*p++);
assert(absExponent < 10U && "Invalid character in exponent");
for (; p != end; ++p) {
unsigned int value;
value = decDigitValue(*p);
assert(value < 10U && "Invalid character in exponent");
value += absExponent * 10;
if (absExponent >= overlargeExponent) {
absExponent = overlargeExponent;
p = end; /* outwit assert below */
break;
}
absExponent = value;
}
assert(p == end && "Invalid exponent in exponent");
if (isNegative)
return -(int) absExponent;
else
return (int) absExponent;
}
/* This is ugly and needs cleaning up, but I don't immediately see
how whilst remaining safe. */
static int
totalExponent(StringRef::iterator p, StringRef::iterator end,
int exponentAdjustment)
{
int unsignedExponent;
bool negative, overflow;
int exponent = 0;
assert(p != end && "Exponent has no digits");
negative = *p == '-';
if (*p == '-' || *p == '+') {
p++;
assert(p != end && "Exponent has no digits");
}
unsignedExponent = 0;
overflow = false;
for (; p != end; ++p) {
unsigned int value;
value = decDigitValue(*p);
assert(value < 10U && "Invalid character in exponent");
unsignedExponent = unsignedExponent * 10 + value;
if (unsignedExponent > 32767) {
overflow = true;
break;
}
}
if (exponentAdjustment > 32767 || exponentAdjustment < -32768)
overflow = true;
if (!overflow) {
exponent = unsignedExponent;
if (negative)
exponent = -exponent;
exponent += exponentAdjustment;
if (exponent > 32767 || exponent < -32768)
overflow = true;
}
if (overflow)
exponent = negative ? -32768: 32767;
return exponent;
}
static StringRef::iterator
skipLeadingZeroesAndAnyDot(StringRef::iterator begin, StringRef::iterator end,
StringRef::iterator *dot)
{
StringRef::iterator p = begin;
*dot = end;
while (*p == '0' && p != end)
p++;
if (*p == '.') {
*dot = p++;
assert(end - begin != 1 && "Significand has no digits");
while (*p == '0' && p != end)
p++;
}
return p;
}
/* Given a normal decimal floating point number of the form
dddd.dddd[eE][+-]ddd
where the decimal point and exponent are optional, fill out the
structure D. Exponent is appropriate if the significand is
treated as an integer, and normalizedExponent if the significand
is taken to have the decimal point after a single leading
non-zero digit.
If the value is zero, V->firstSigDigit points to a non-digit, and
the return exponent is zero.
*/
struct decimalInfo {
const char *firstSigDigit;
const char *lastSigDigit;
int exponent;
int normalizedExponent;
};
static void
interpretDecimal(StringRef::iterator begin, StringRef::iterator end,
decimalInfo *D)
{
StringRef::iterator dot = end;
StringRef::iterator p = skipLeadingZeroesAndAnyDot (begin, end, &dot);
D->firstSigDigit = p;
D->exponent = 0;
D->normalizedExponent = 0;
for (; p != end; ++p) {
if (*p == '.') {
assert(dot == end && "String contains multiple dots");
dot = p++;
if (p == end)
break;
}
if (decDigitValue(*p) >= 10U)
break;
}
if (p != end) {
assert((*p == 'e' || *p == 'E') && "Invalid character in significand");
assert(p != begin && "Significand has no digits");
assert((dot == end || p - begin != 1) && "Significand has no digits");
/* p points to the first non-digit in the string */
D->exponent = readExponent(p + 1, end);
/* Implied decimal point? */
if (dot == end)
dot = p;
}
/* If number is all zeroes accept any exponent. */
if (p != D->firstSigDigit) {
/* Drop insignificant trailing zeroes. */
if (p != begin) {
do
do
p--;
while (p != begin && *p == '0');
while (p != begin && *p == '.');
}
/* Adjust the exponents for any decimal point. */
D->exponent += static_cast<APFloat::ExponentType>((dot - p) - (dot > p));
D->normalizedExponent = (D->exponent +
static_cast<APFloat::ExponentType>((p - D->firstSigDigit)
- (dot > D->firstSigDigit && dot < p)));
}
D->lastSigDigit = p;
}
/* Return the trailing fraction of a hexadecimal number.
DIGITVALUE is the first hex digit of the fraction, P points to
the next digit. */
static lostFraction
trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end,
unsigned int digitValue)
{
unsigned int hexDigit;
/* If the first trailing digit isn't 0 or 8 we can work out the
fraction immediately. */
if (digitValue > 8)
return lfMoreThanHalf;
else if (digitValue < 8 && digitValue > 0)
return lfLessThanHalf;
// Otherwise we need to find the first non-zero digit.
while (p != end && (*p == '0' || *p == '.'))
p++;
assert(p != end && "Invalid trailing hexadecimal fraction!");
hexDigit = hexDigitValue(*p);
/* If we ran off the end it is exactly zero or one-half, otherwise
a little more. */
if (hexDigit == -1U)
return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
else
return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf;
}
/* Return the fraction lost were a bignum truncated losing the least
significant BITS bits. */
static lostFraction
lostFractionThroughTruncation(const integerPart *parts,
unsigned int partCount,
unsigned int bits)
{
unsigned int lsb;
lsb = APInt::tcLSB(parts, partCount);
/* Note this is guaranteed true if bits == 0, or LSB == -1U. */
if (bits <= lsb)
return lfExactlyZero;
if (bits == lsb + 1)
return lfExactlyHalf;
if (bits <= partCount * integerPartWidth &&
APInt::tcExtractBit(parts, bits - 1))
return lfMoreThanHalf;
return lfLessThanHalf;
}
/* Shift DST right BITS bits noting lost fraction. */
static lostFraction
shiftRight(integerPart *dst, unsigned int parts, unsigned int bits)
{
lostFraction lost_fraction;
lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
APInt::tcShiftRight(dst, parts, bits);
return lost_fraction;
}
/* Combine the effect of two lost fractions. */
static lostFraction
combineLostFractions(lostFraction moreSignificant,
lostFraction lessSignificant)
{
if (lessSignificant != lfExactlyZero) {
if (moreSignificant == lfExactlyZero)
moreSignificant = lfLessThanHalf;
else if (moreSignificant == lfExactlyHalf)
moreSignificant = lfMoreThanHalf;
}
return moreSignificant;
}
/* The error from the true value, in half-ulps, on multiplying two
floating point numbers, which differ from the value they
approximate by at most HUE1 and HUE2 half-ulps, is strictly less
than the returned value.
See "How to Read Floating Point Numbers Accurately" by William D
Clinger. */
static unsigned int
HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
{
assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
if (HUerr1 + HUerr2 == 0)
return inexactMultiply * 2; /* <= inexactMultiply half-ulps. */
else
return inexactMultiply + 2 * (HUerr1 + HUerr2);
}
/* The number of ulps from the boundary (zero, or half if ISNEAREST)
when the least significant BITS are truncated. BITS cannot be
zero. */
static integerPart
ulpsFromBoundary(const integerPart *parts, unsigned int bits, bool isNearest)
{
unsigned int count, partBits;
integerPart part, boundary;
assert(bits != 0);
bits--;
count = bits / integerPartWidth;
partBits = bits % integerPartWidth + 1;
part = parts[count] & (~(integerPart) 0 >> (integerPartWidth - partBits));
if (isNearest)
boundary = (integerPart) 1 << (partBits - 1);
else
boundary = 0;
if (count == 0) {
if (part - boundary <= boundary - part)
return part - boundary;
else
return boundary - part;
}
if (part == boundary) {
while (--count)
if (parts[count])
return ~(integerPart) 0; /* A lot. */
return parts[0];
} else if (part == boundary - 1) {
while (--count)
if (~parts[count])
return ~(integerPart) 0; /* A lot. */
return -parts[0];
}
return ~(integerPart) 0; /* A lot. */
}
/* Place pow(5, power) in DST, and return the number of parts used.
DST must be at least one part larger than size of the answer. */
static unsigned int
powerOf5(integerPart *dst, unsigned int power)
{
static const integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125,
15625, 78125 };
integerPart pow5s[maxPowerOfFiveParts * 2 + 5];
pow5s[0] = 78125 * 5;
unsigned int partsCount[16] = { 1 };
integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5;
unsigned int result;
assert(power <= maxExponent);
p1 = dst;
p2 = scratch;
*p1 = firstEightPowers[power & 7];
power >>= 3;
result = 1;
pow5 = pow5s;
for (unsigned int n = 0; power; power >>= 1, n++) {
unsigned int pc;
pc = partsCount[n];
/* Calculate pow(5,pow(2,n+3)) if we haven't yet. */
if (pc == 0) {
pc = partsCount[n - 1];
APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc);
pc *= 2;
if (pow5[pc - 1] == 0)
pc--;
partsCount[n] = pc;
}
if (power & 1) {
integerPart *tmp;
APInt::tcFullMultiply(p2, p1, pow5, result, pc);
result += pc;
if (p2[result - 1] == 0)
result--;
/* Now result is in p1 with partsCount parts and p2 is scratch
space. */
tmp = p1, p1 = p2, p2 = tmp;
}
pow5 += pc;
}
if (p1 != dst)
APInt::tcAssign(dst, p1, result);
return result;
}
/* Zero at the end to avoid modular arithmetic when adding one; used
when rounding up during hexadecimal output. */
static const char hexDigitsLower[] = "0123456789abcdef0";
static const char hexDigitsUpper[] = "0123456789ABCDEF0";
static const char infinityL[] = "infinity";
static const char infinityU[] = "INFINITY";
static const char NaNL[] = "nan";
static const char NaNU[] = "NAN";
/* Write out an integerPart in hexadecimal, starting with the most
significant nibble. Write out exactly COUNT hexdigits, return
COUNT. */
static unsigned int
partAsHex (char *dst, integerPart part, unsigned int count,
const char *hexDigitChars)
{
unsigned int result = count;
assert(count != 0 && count <= integerPartWidth / 4);
part >>= (integerPartWidth - 4 * count);
while (count--) {
dst[count] = hexDigitChars[part & 0xf];
part >>= 4;
}
return result;
}
/* Write out an unsigned decimal integer. */
static char *
writeUnsignedDecimal (char *dst, unsigned int n)
{
char buff[40], *p;
p = buff;
do
*p++ = '0' + n % 10;
while (n /= 10);
do
*dst++ = *--p;
while (p != buff);
return dst;
}
/* Write out a signed decimal integer. */
static char *
writeSignedDecimal (char *dst, int value)
{
if (value < 0) {
*dst++ = '-';
dst = writeUnsignedDecimal(dst, -(unsigned) value);
} else
dst = writeUnsignedDecimal(dst, value);
return dst;
}
/* Constructors. */
void
APFloat::initialize(const fltSemantics *ourSemantics)
{
unsigned int count;
semantics = ourSemantics;
count = partCount();
if (count > 1)
significand.parts = new integerPart[count];
}
void
APFloat::freeSignificand()
{
if (needsCleanup())
delete [] significand.parts;
}
void
APFloat::assign(const APFloat &rhs)
{
assert(semantics == rhs.semantics);
sign = rhs.sign;
category = rhs.category;
exponent = rhs.exponent;
if (isFiniteNonZero() || category == fcNaN)
copySignificand(rhs);
}
void
APFloat::copySignificand(const APFloat &rhs)
{
assert(isFiniteNonZero() || category == fcNaN);
assert(rhs.partCount() >= partCount());
APInt::tcAssign(significandParts(), rhs.significandParts(),
partCount());
}
/* Make this number a NaN, with an arbitrary but deterministic value
for the significand. If double or longer, this is a signalling NaN,
which may not be ideal. If float, this is QNaN(0). */
void APFloat::makeNaN(bool SNaN, bool Negative, const APInt *fill)
{
category = fcNaN;
sign = Negative;
integerPart *significand = significandParts();
unsigned numParts = partCount();
// Set the significand bits to the fill.
if (!fill || fill->getNumWords() < numParts)
APInt::tcSet(significand, 0, numParts);
if (fill) {
APInt::tcAssign(significand, fill->getRawData(),
std::min(fill->getNumWords(), numParts));
// Zero out the excess bits of the significand.
unsigned bitsToPreserve = semantics->precision - 1;
unsigned part = bitsToPreserve / 64;
bitsToPreserve %= 64;
significand[part] &= ((1ULL << bitsToPreserve) - 1);
for (part++; part != numParts; ++part)
significand[part] = 0;
}
unsigned QNaNBit = semantics->precision - 2;
if (SNaN) {
// We always have to clear the QNaN bit to make it an SNaN.
APInt::tcClearBit(significand, QNaNBit);
// If there are no bits set in the payload, we have to set
// *something* to make it a NaN instead of an infinity;
// conventionally, this is the next bit down from the QNaN bit.
if (APInt::tcIsZero(significand, numParts))
APInt::tcSetBit(significand, QNaNBit - 1);
} else {
// We always have to set the QNaN bit to make it a QNaN.
APInt::tcSetBit(significand, QNaNBit);
}
// For x87 extended precision, we want to make a NaN, not a
// pseudo-NaN. Maybe we should expose the ability to make
// pseudo-NaNs?
if (semantics == &APFloat::x87DoubleExtended)
APInt::tcSetBit(significand, QNaNBit + 1);
}
APFloat APFloat::makeNaN(const fltSemantics &Sem, bool SNaN, bool Negative,
const APInt *fill) {
APFloat value(Sem, uninitialized);
value.makeNaN(SNaN, Negative, fill);
return value;
}
APFloat &
APFloat::operator=(const APFloat &rhs)
{
if (this != &rhs) {
if (semantics != rhs.semantics) {
freeSignificand();
initialize(rhs.semantics);
}
assign(rhs);
}
return *this;
}
APFloat &
APFloat::operator=(APFloat &&rhs) {
freeSignificand();
semantics = rhs.semantics;
significand = rhs.significand;
exponent = rhs.exponent;
category = rhs.category;
sign = rhs.sign;
rhs.semantics = &Bogus;
return *this;
}
bool
APFloat::isDenormal() const {
return isFiniteNonZero() && (exponent == semantics->minExponent) &&
(APInt::tcExtractBit(significandParts(),
semantics->precision - 1) == 0);
}
bool
APFloat::isSmallest() const {
// The smallest number by magnitude in our format will be the smallest
// denormal, i.e. the floating point number with exponent being minimum
// exponent and significand bitwise equal to 1 (i.e. with MSB equal to 0).
return isFiniteNonZero() && exponent == semantics->minExponent &&
significandMSB() == 0;
}
bool APFloat::isSignificandAllOnes() const {
// Test if the significand excluding the integral bit is all ones. This allows
// us to test for binade boundaries.
const integerPart *Parts = significandParts();
const unsigned PartCount = partCount();
for (unsigned i = 0; i < PartCount - 1; i++)
if (~Parts[i])
return false;
// Set the unused high bits to all ones when we compare.
const unsigned NumHighBits =
PartCount*integerPartWidth - semantics->precision + 1;
assert(NumHighBits <= integerPartWidth && "Can not have more high bits to "
"fill than integerPartWidth");
const integerPart HighBitFill =
~integerPart(0) << (integerPartWidth - NumHighBits);
if (~(Parts[PartCount - 1] | HighBitFill))
return false;
return true;
}
bool APFloat::isSignificandAllZeros() const {
// Test if the significand excluding the integral bit is all zeros. This
// allows us to test for binade boundaries.
const integerPart *Parts = significandParts();
const unsigned PartCount = partCount();
for (unsigned i = 0; i < PartCount - 1; i++)
if (Parts[i])
return false;
const unsigned NumHighBits =
PartCount*integerPartWidth - semantics->precision + 1;
assert(NumHighBits <= integerPartWidth && "Can not have more high bits to "
"clear than integerPartWidth");
const integerPart HighBitMask = ~integerPart(0) >> NumHighBits;
if (Parts[PartCount - 1] & HighBitMask)
return false;
return true;
}
bool
APFloat::isLargest() const {
// The largest number by magnitude in our format will be the floating point
// number with maximum exponent and with significand that is all ones.
return isFiniteNonZero() && exponent == semantics->maxExponent
&& isSignificandAllOnes();
}
bool
APFloat::bitwiseIsEqual(const APFloat &rhs) const {
if (this == &rhs)
return true;
if (semantics != rhs.semantics ||
category != rhs.category ||
sign != rhs.sign)
return false;
if (category==fcZero || category==fcInfinity)
return true;
else if (isFiniteNonZero() && exponent!=rhs.exponent)
return false;
else {
int i= partCount();
const integerPart* p=significandParts();
const integerPart* q=rhs.significandParts();
for (; i>0; i--, p++, q++) {
if (*p != *q)
return false;
}
return true;
}
}
APFloat::APFloat(const fltSemantics &ourSemantics, integerPart value) {
initialize(&ourSemantics);
sign = 0;
category = fcNormal;
zeroSignificand();
exponent = ourSemantics.precision - 1;
significandParts()[0] = value;
normalize(rmNearestTiesToEven, lfExactlyZero);
}
APFloat::APFloat(const fltSemantics &ourSemantics) {
initialize(&ourSemantics);
category = fcZero;
sign = false;
}
APFloat::APFloat(const fltSemantics &ourSemantics, uninitializedTag tag) {
// Allocates storage if necessary but does not initialize it.
initialize(&ourSemantics);
}
APFloat::APFloat(const fltSemantics &ourSemantics, StringRef text) {
initialize(&ourSemantics);
convertFromString(text, rmNearestTiesToEven);
}
APFloat::APFloat(const APFloat &rhs) {
initialize(rhs.semantics);
assign(rhs);
}
APFloat::APFloat(APFloat &&rhs) : semantics(&Bogus) {
*this = std::move(rhs);
}
APFloat::~APFloat()
{
freeSignificand();
}
// Profile - This method 'profiles' an APFloat for use with FoldingSet.
void APFloat::Profile(FoldingSetNodeID& ID) const {
ID.Add(bitcastToAPInt());
}
unsigned int
APFloat::partCount() const
{
return partCountForBits(semantics->precision + 1);
}
unsigned int
APFloat::semanticsPrecision(const fltSemantics &semantics)
{
return semantics.precision;
}
const integerPart *
APFloat::significandParts() const
{
return const_cast<APFloat *>(this)->significandParts();
}
integerPart *
APFloat::significandParts()
{
if (partCount() > 1)
return significand.parts;
else
return &significand.part;
}
void
APFloat::zeroSignificand()
{
APInt::tcSet(significandParts(), 0, partCount());
}
/* Increment an fcNormal floating point number's significand. */
void
APFloat::incrementSignificand()
{
integerPart carry;
carry = APInt::tcIncrement(significandParts(), partCount());
/* Our callers should never cause us to overflow. */
assert(carry == 0);
(void)carry;
}
/* Add the significand of the RHS. Returns the carry flag. */
integerPart
APFloat::addSignificand(const APFloat &rhs)
{
integerPart *parts;
parts = significandParts();
assert(semantics == rhs.semantics);
assert(exponent == rhs.exponent);
return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
}
/* Subtract the significand of the RHS with a borrow flag. Returns
the borrow flag. */
integerPart
APFloat::subtractSignificand(const APFloat &rhs, integerPart borrow)
{
integerPart *parts;
parts = significandParts();
assert(semantics == rhs.semantics);
assert(exponent == rhs.exponent);
return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
partCount());
}
/* Multiply the significand of the RHS. If ADDEND is non-NULL, add it
on to the full-precision result of the multiplication. Returns the
lost fraction. */
lostFraction
APFloat::multiplySignificand(const APFloat &rhs, const APFloat *addend)
{
unsigned int omsb; // One, not zero, based MSB.
unsigned int partsCount, newPartsCount, precision;
integerPart *lhsSignificand;
integerPart scratch[4];
integerPart *fullSignificand;
lostFraction lost_fraction;
bool ignored;
assert(semantics == rhs.semantics);
precision = semantics->precision;
newPartsCount = partCountForBits(precision * 2);
if (newPartsCount > 4)
fullSignificand = new integerPart[newPartsCount];
else
fullSignificand = scratch;
lhsSignificand = significandParts();
partsCount = partCount();
APInt::tcFullMultiply(fullSignificand, lhsSignificand,
rhs.significandParts(), partsCount, partsCount);
lost_fraction = lfExactlyZero;
omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
exponent += rhs.exponent;
// Assume the operands involved in the multiplication are single-precision
// FP, and the two multiplicants are:
// *this = a23 . a22 ... a0 * 2^e1
// rhs = b23 . b22 ... b0 * 2^e2
// the result of multiplication is:
// *this = c47 c46 . c45 ... c0 * 2^(e1+e2)
// Note that there are two significant bits at the left-hand side of the
// radix point. Move the radix point toward left by one bit, and adjust
// exponent accordingly.
exponent += 1;
if (addend) {
// The intermediate result of the multiplication has "2 * precision"
// signicant bit; adjust the addend to be consistent with mul result.
//
Significand savedSignificand = significand;
const fltSemantics *savedSemantics = semantics;
fltSemantics extendedSemantics;
opStatus status;
unsigned int extendedPrecision;
/* Normalize our MSB. */
extendedPrecision = 2 * precision;
if (omsb != extendedPrecision) {
assert(extendedPrecision > omsb);
APInt::tcShiftLeft(fullSignificand, newPartsCount,
extendedPrecision - omsb);
exponent -= extendedPrecision - omsb;
}
/* Create new semantics. */
extendedSemantics = *semantics;
extendedSemantics.precision = extendedPrecision;
if (newPartsCount == 1)
significand.part = fullSignificand[0];
else
significand.parts = fullSignificand;
semantics = &extendedSemantics;
APFloat extendedAddend(*addend);
status = extendedAddend.convert(extendedSemantics, rmTowardZero, &ignored);
assert(status == opOK);
(void)status;
lost_fraction = addOrSubtractSignificand(extendedAddend, false);
/* Restore our state. */
if (newPartsCount == 1)
fullSignificand[0] = significand.part;
significand = savedSignificand;
semantics = savedSemantics;
omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
}