forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAPFloat.cpp
4923 lines (4146 loc) · 156 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 -----------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// 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/ArrayRef.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Config/llvm-config.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/raw_ostream.h"
#include <cstring>
#include <limits.h>
#define APFLOAT_DISPATCH_ON_SEMANTICS(METHOD_CALL) \
do { \
if (usesLayout<IEEEFloat>(getSemantics())) \
return U.IEEE.METHOD_CALL; \
if (usesLayout<DoubleAPFloat>(getSemantics())) \
return U.Double.METHOD_CALL; \
llvm_unreachable("Unexpected semantics"); \
} while (false)
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. */
static_assert(APFloatBase::integerPartWidth % 4 == 0, "Part width must be divisible by 4!");
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. */
APFloatBase::ExponentType maxExponent;
/* The smallest E such that 2^E is a normalized number; this
matches the definition of IEEE 754. */
APFloatBase::ExponentType minExponent;
/* Number of bits in the significand. This includes the integer
bit. */
unsigned int precision;
/* Number of bits actually used in the semantics. */
unsigned int sizeInBits;
// Returns true if any number described by this semantics can be precisely
// represented by the specified semantics.
bool isRepresentableBy(const fltSemantics &S) const {
return maxExponent <= S.maxExponent && minExponent >= S.minExponent &&
precision <= S.precision;
}
};
static const fltSemantics semIEEEhalf = {15, -14, 11, 16};
static const fltSemantics semBFloat = {127, -126, 8, 16};
static const fltSemantics semIEEEsingle = {127, -126, 24, 32};
static const fltSemantics semIEEEdouble = {1023, -1022, 53, 64};
static const fltSemantics semIEEEquad = {16383, -16382, 113, 128};
static const fltSemantics semX87DoubleExtended = {16383, -16382, 64, 80};
static const fltSemantics semBogus = {0, 0, 0, 0};
/* The IBM double-double semantics. Such a number consists of a pair of IEEE
64-bit doubles (Hi, Lo), where |Hi| > |Lo|, and if normal,
(double)(Hi + Lo) == Hi. The numeric value it's modeling is Hi + Lo.
Therefore it has two 53-bit mantissa parts that aren't necessarily adjacent
to each other, and two 11-bit exponents.
Note: we need to make the value different from semBogus as otherwise
an unsafe optimization may collapse both values to a single address,
and we heavily rely on them having distinct addresses. */
static const fltSemantics semPPCDoubleDouble = {-1, 0, 0, 128};
/* These are legacy semantics for the fallback, inaccrurate implementation of
IBM double-double, if the accurate semPPCDoubleDouble doesn't handle the
operation. It's equivalent to having an IEEE number with consecutive 106
bits of mantissa and 11 bits of exponent.
It's not equivalent to IBM double-double. For example, a legit IBM
double-double, 1 + epsilon:
1 + epsilon = 1 + (1 >> 1076)
is not representable by a consecutive 106 bits of mantissa.
Currently, these semantics are used in the following way:
semPPCDoubleDouble -> (IEEEdouble, IEEEdouble) ->
(64-bit APInt, 64-bit APInt) -> (128-bit APInt) ->
semPPCDoubleDoubleLegacy -> IEEE operations
We use bitcastToAPInt() to get the bit representation (in APInt) of the
underlying IEEEdouble, then use the APInt constructor to construct the
legacy IEEE float.
TODO: Implement all operations in semPPCDoubleDouble, and delete these
semantics. */
static const fltSemantics semPPCDoubleDoubleLegacy = {1023, -1022 + 53,
53 + 53, 128};
const llvm::fltSemantics &APFloatBase::EnumToSemantics(Semantics S) {
switch (S) {
case S_IEEEhalf:
return IEEEhalf();
case S_BFloat:
return BFloat();
case S_IEEEsingle:
return IEEEsingle();
case S_IEEEdouble:
return IEEEdouble();
case S_x87DoubleExtended:
return x87DoubleExtended();
case S_IEEEquad:
return IEEEquad();
case S_PPCDoubleDouble:
return PPCDoubleDouble();
}
llvm_unreachable("Unrecognised floating semantics");
}
APFloatBase::Semantics
APFloatBase::SemanticsToEnum(const llvm::fltSemantics &Sem) {
if (&Sem == &llvm::APFloat::IEEEhalf())
return S_IEEEhalf;
else if (&Sem == &llvm::APFloat::BFloat())
return S_BFloat;
else if (&Sem == &llvm::APFloat::IEEEsingle())
return S_IEEEsingle;
else if (&Sem == &llvm::APFloat::IEEEdouble())
return S_IEEEdouble;
else if (&Sem == &llvm::APFloat::x87DoubleExtended())
return S_x87DoubleExtended;
else if (&Sem == &llvm::APFloat::IEEEquad())
return S_IEEEquad;
else if (&Sem == &llvm::APFloat::PPCDoubleDouble())
return S_PPCDoubleDouble;
else
llvm_unreachable("Unknown floating semantics");
}
const fltSemantics &APFloatBase::IEEEhalf() {
return semIEEEhalf;
}
const fltSemantics &APFloatBase::BFloat() {
return semBFloat;
}
const fltSemantics &APFloatBase::IEEEsingle() {
return semIEEEsingle;
}
const fltSemantics &APFloatBase::IEEEdouble() {
return semIEEEdouble;
}
const fltSemantics &APFloatBase::IEEEquad() {
return semIEEEquad;
}
const fltSemantics &APFloatBase::x87DoubleExtended() {
return semX87DoubleExtended;
}
const fltSemantics &APFloatBase::Bogus() {
return semBogus;
}
const fltSemantics &APFloatBase::PPCDoubleDouble() {
return semPPCDoubleDouble;
}
constexpr RoundingMode APFloatBase::rmNearestTiesToEven;
constexpr RoundingMode APFloatBase::rmTowardPositive;
constexpr RoundingMode APFloatBase::rmTowardNegative;
constexpr RoundingMode APFloatBase::rmTowardZero;
constexpr RoundingMode APFloatBase::rmNearestTiesToAway;
/* 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 * APFloatBase::integerPartWidth));
unsigned int APFloatBase::semanticsPrecision(const fltSemantics &semantics) {
return semantics.precision;
}
APFloatBase::ExponentType
APFloatBase::semanticsMaxExponent(const fltSemantics &semantics) {
return semantics.maxExponent;
}
APFloatBase::ExponentType
APFloatBase::semanticsMinExponent(const fltSemantics &semantics) {
return semantics.minExponent;
}
unsigned int APFloatBase::semanticsSizeInBits(const fltSemantics &semantics) {
return semantics.sizeInBits;
}
unsigned APFloatBase::getSizeInBits(const fltSemantics &Sem) {
return Sem.sizeInBits;
}
/* A bunch of private, handy routines. */
static inline Error createError(const Twine &Err) {
return make_error<StringError>(Err, inconvertibleErrorCode());
}
static inline unsigned int
partCountForBits(unsigned int bits)
{
return ((bits) + APFloatBase::integerPartWidth - 1) / APFloatBase::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 Expected<int> readExponent(StringRef::iterator begin,
StringRef::iterator end) {
bool isNegative;
unsigned int absExponent;
const unsigned int overlargeExponent = 24000; /* FIXME. */
StringRef::iterator p = begin;
// Treat no exponent as 0 to match binutils
if (p == end || ((*p == '-' || *p == '+') && (p + 1) == end)) {
return 0;
}
isNegative = (*p == '-');
if (*p == '-' || *p == '+') {
p++;
if (p == end)
return createError("Exponent has no digits");
}
absExponent = decDigitValue(*p++);
if (absExponent >= 10U)
return createError("Invalid character in exponent");
for (; p != end; ++p) {
unsigned int value;
value = decDigitValue(*p);
if (value >= 10U)
return createError("Invalid character in exponent");
absExponent = absExponent * 10U + value;
if (absExponent >= overlargeExponent) {
absExponent = overlargeExponent;
break;
}
}
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 Expected<int> totalExponent(StringRef::iterator p,
StringRef::iterator end,
int exponentAdjustment) {
int unsignedExponent;
bool negative, overflow;
int exponent = 0;
if (p == end)
return createError("Exponent has no digits");
negative = *p == '-';
if (*p == '-' || *p == '+') {
p++;
if (p == end)
return createError("Exponent has no digits");
}
unsignedExponent = 0;
overflow = false;
for (; p != end; ++p) {
unsigned int value;
value = decDigitValue(*p);
if (value >= 10U)
return createError("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 Expected<StringRef::iterator>
skipLeadingZeroesAndAnyDot(StringRef::iterator begin, StringRef::iterator end,
StringRef::iterator *dot) {
StringRef::iterator p = begin;
*dot = end;
while (p != end && *p == '0')
p++;
if (p != end && *p == '.') {
*dot = p++;
if (end - begin == 1)
return createError("Significand has no digits");
while (p != end && *p == '0')
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 Error interpretDecimal(StringRef::iterator begin,
StringRef::iterator end, decimalInfo *D) {
StringRef::iterator dot = end;
auto PtrOrErr = skipLeadingZeroesAndAnyDot(begin, end, &dot);
if (!PtrOrErr)
return PtrOrErr.takeError();
StringRef::iterator p = *PtrOrErr;
D->firstSigDigit = p;
D->exponent = 0;
D->normalizedExponent = 0;
for (; p != end; ++p) {
if (*p == '.') {
if (dot != end)
return createError("String contains multiple dots");
dot = p++;
if (p == end)
break;
}
if (decDigitValue(*p) >= 10U)
break;
}
if (p != end) {
if (*p != 'e' && *p != 'E')
return createError("Invalid character in significand");
if (p == begin)
return createError("Significand has no digits");
if (dot != end && p - begin == 1)
return createError("Significand has no digits");
/* p points to the first non-digit in the string */
auto ExpOrErr = readExponent(p + 1, end);
if (!ExpOrErr)
return ExpOrErr.takeError();
D->exponent = *ExpOrErr;
/* 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 Error::success();
}
/* Return the trailing fraction of a hexadecimal number.
DIGITVALUE is the first hex digit of the fraction, P points to
the next digit. */
static Expected<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++;
if (p == end)
return createError("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 APFloatBase::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 * APFloatBase::integerPartWidth &&
APInt::tcExtractBit(parts, bits - 1))
return lfMoreThanHalf;
return lfLessThanHalf;
}
/* Shift DST right BITS bits noting lost fraction. */
static lostFraction
shiftRight(APFloatBase::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 APFloatBase::integerPart
ulpsFromBoundary(const APFloatBase::integerPart *parts, unsigned int bits,
bool isNearest) {
unsigned int count, partBits;
APFloatBase::integerPart part, boundary;
assert(bits != 0);
bits--;
count = bits / APFloatBase::integerPartWidth;
partBits = bits % APFloatBase::integerPartWidth + 1;
part = parts[count] & (~(APFloatBase::integerPart) 0 >> (APFloatBase::integerPartWidth - partBits));
if (isNearest)
boundary = (APFloatBase::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 ~(APFloatBase::integerPart) 0; /* A lot. */
return parts[0];
} else if (part == boundary - 1) {
while (--count)
if (~parts[count])
return ~(APFloatBase::integerPart) 0; /* A lot. */
return -parts[0];
}
return ~(APFloatBase::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(APFloatBase::integerPart *dst, unsigned int power) {
static const APFloatBase::integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125, 15625, 78125 };
APFloatBase::integerPart pow5s[maxPowerOfFiveParts * 2 + 5];
pow5s[0] = 78125 * 5;
unsigned int partsCount[16] = { 1 };
APFloatBase::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) {
APFloatBase::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, APFloatBase::integerPart part, unsigned int count,
const char *hexDigitChars)
{
unsigned int result = count;
assert(count != 0 && count <= APFloatBase::integerPartWidth / 4);
part >>= (APFloatBase::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;
}
namespace detail {
/* Constructors. */
void IEEEFloat::initialize(const fltSemantics *ourSemantics) {
unsigned int count;
semantics = ourSemantics;
count = partCount();
if (count > 1)
significand.parts = new integerPart[count];
}
void IEEEFloat::freeSignificand() {
if (needsCleanup())
delete [] significand.parts;
}
void IEEEFloat::assign(const IEEEFloat &rhs) {
assert(semantics == rhs.semantics);
sign = rhs.sign;
category = rhs.category;
exponent = rhs.exponent;
if (isFiniteNonZero() || category == fcNaN)
copySignificand(rhs);
}
void IEEEFloat::copySignificand(const IEEEFloat &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 IEEEFloat::makeNaN(bool SNaN, bool Negative, const APInt *fill) {
category = fcNaN;
sign = Negative;
exponent = exponentNaN();
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 == &semX87DoubleExtended)
APInt::tcSetBit(significand, QNaNBit + 1);
}
IEEEFloat &IEEEFloat::operator=(const IEEEFloat &rhs) {
if (this != &rhs) {
if (semantics != rhs.semantics) {
freeSignificand();
initialize(rhs.semantics);
}
assign(rhs);
}
return *this;
}
IEEEFloat &IEEEFloat::operator=(IEEEFloat &&rhs) {
freeSignificand();
semantics = rhs.semantics;
significand = rhs.significand;
exponent = rhs.exponent;
category = rhs.category;
sign = rhs.sign;
rhs.semantics = &semBogus;
return *this;
}
bool IEEEFloat::isDenormal() const {
return isFiniteNonZero() && (exponent == semantics->minExponent) &&
(APInt::tcExtractBit(significandParts(),
semantics->precision - 1) == 0);
}
bool IEEEFloat::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 IEEEFloat::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 = partCountForBits(semantics->precision);
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 && NumHighBits > 0 &&
"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 IEEEFloat::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 = partCountForBits(semantics->precision);
for (unsigned i = 0; i < PartCount - 1; i++)
if (Parts[i])
return false;
// Compute how many bits are used in the final word.
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 IEEEFloat::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 IEEEFloat::isInteger() const {
// This could be made more efficient; I'm going for obviously correct.
if (!isFinite()) return false;
IEEEFloat truncated = *this;
truncated.roundToIntegral(rmTowardZero);
return compare(truncated) == cmpEqual;
}
bool IEEEFloat::bitwiseIsEqual(const IEEEFloat &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;
if (isFiniteNonZero() && exponent != rhs.exponent)
return false;
return std::equal(significandParts(), significandParts() + partCount(),
rhs.significandParts());
}
IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics, integerPart value) {
initialize(&ourSemantics);
sign = 0;
category = fcNormal;
zeroSignificand();
exponent = ourSemantics.precision - 1;
significandParts()[0] = value;
normalize(rmNearestTiesToEven, lfExactlyZero);
}
IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics) {
initialize(&ourSemantics);
makeZero(false);
}
// Delegate to the previous constructor, because later copy constructor may
// actually inspects category, which can't be garbage.
IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics, uninitializedTag tag)
: IEEEFloat(ourSemantics) {}
IEEEFloat::IEEEFloat(const IEEEFloat &rhs) {
initialize(rhs.semantics);
assign(rhs);
}
IEEEFloat::IEEEFloat(IEEEFloat &&rhs) : semantics(&semBogus) {
*this = std::move(rhs);
}
IEEEFloat::~IEEEFloat() { freeSignificand(); }
unsigned int IEEEFloat::partCount() const {
return partCountForBits(semantics->precision + 1);
}
const IEEEFloat::integerPart *IEEEFloat::significandParts() const {
return const_cast<IEEEFloat *>(this)->significandParts();
}
IEEEFloat::integerPart *IEEEFloat::significandParts() {
if (partCount() > 1)
return significand.parts;
else
return &significand.part;
}
void IEEEFloat::zeroSignificand() {
APInt::tcSet(significandParts(), 0, partCount());
}
/* Increment an fcNormal floating point number's significand. */
void IEEEFloat::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. */
IEEEFloat::integerPart IEEEFloat::addSignificand(const IEEEFloat &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. */
IEEEFloat::integerPart IEEEFloat::subtractSignificand(const IEEEFloat &rhs,