LLVM: lib/Support/APFloat.cpp Source File (original) (raw)
1
2
3
4
5
6
7
8
9
10
11
12
13
23#include "llvm/Config/llvm-config.h"
28#include
29#include <limits.h>
30
31#define APFLOAT_DISPATCH_ON_SEMANTICS(METHOD_CALL) \
32 do { \
33 if (usesLayout(getSemantics())) \
34 return U.IEEE.METHOD_CALL; \
35 if (usesLayout(getSemantics())) \
36 return U.Double.METHOD_CALL; \
37 llvm_unreachable("Unexpected semantics"); \
38 } while (false)
39
40using namespace llvm;
41
42
43
44
45
46
47
48#define PackCategoriesIntoKey(_lhs, _rhs) ((_lhs) * 4 + (_rhs))
49
50
51
53
54namespace llvm {
55
56
58
59
60
62
63
64
65
66
67
68
69
71
72
73
75};
76
77
78
79
80
82
83
85
86
87
88
89
90
91
93
94
95
96
97
98
100};
101
102
104
105
107
108
109
111
112
113
115
116
118
120
122
123
125
126
128};
129
149 false, false};
150
161 53 + 53, 128};
162
164 switch (S) {
205 }
207}
208
251 else
253}
254
262}
265}
273}
282}
284
287 return A.maxExponent <= B.maxExponent && A.minExponent >= B.minExponent &&
288 A.precision <= B.precision;
289}
290
296
297
298
299
300
301
302
303
304
305
306
307
312 2 +
314
317}
321}
325}
328}
331
332
334
336 ++MinBitWidth;
337 return MinBitWidth;
338}
339
341 return semantics.hasZero;
342}
343
346}
347
350}
351
354}
355
358
359 if (Src.maxExponent >= Dst.maxExponent || Src.minExponent <= Dst.minExponent)
360 return false;
361
362
363
364
365
366
367 return Dst.precision >= Src.precision;
368}
369
372}
373
377}
378
382}
383
391 }
393}
394
395
396
399}
400
401static constexpr inline unsigned int partCountForBits(unsigned int bits) {
404}
405
406
407static inline unsigned int
409{
410 return c - '0';
411}
412
413
414
415
416
417
420 bool isNegative;
421 unsigned int absExponent;
422 const unsigned int overlargeExponent = 24000;
424
425
426 if (p == end || ((*p == '-' || *p == '+') && (p + 1) == end)) {
427 return 0;
428 }
429
430 isNegative = (*p == '-');
431 if (*p == '-' || *p == '+') {
432 p++;
433 if (p == end)
434 return createError("Exponent has no digits");
435 }
436
438 if (absExponent >= 10U)
439 return createError("Invalid character in exponent");
440
441 for (; p != end; ++p) {
442 unsigned int value;
443
445 if (value >= 10U)
446 return createError("Invalid character in exponent");
447
448 absExponent = absExponent * 10U + value;
449 if (absExponent >= overlargeExponent) {
450 absExponent = overlargeExponent;
451 break;
452 }
453 }
454
455 if (isNegative)
456 return -(int) absExponent;
457 else
458 return (int) absExponent;
459}
460
461
462
465 int exponentAdjustment) {
466 int unsignedExponent;
467 bool negative, overflow;
468 int exponent = 0;
469
470 if (p == end)
471 return createError("Exponent has no digits");
472
473 negative = *p == '-';
474 if (*p == '-' || *p == '+') {
475 p++;
476 if (p == end)
477 return createError("Exponent has no digits");
478 }
479
480 unsignedExponent = 0;
481 overflow = false;
482 for (; p != end; ++p) {
483 unsigned int value;
484
486 if (value >= 10U)
487 return createError("Invalid character in exponent");
488
489 unsignedExponent = unsignedExponent * 10 + value;
490 if (unsignedExponent > 32767) {
491 overflow = true;
492 break;
493 }
494 }
495
496 if (exponentAdjustment > 32767 || exponentAdjustment < -32768)
497 overflow = true;
498
499 if (!overflow) {
500 exponent = unsignedExponent;
501 if (negative)
502 exponent = -exponent;
503 exponent += exponentAdjustment;
504 if (exponent > 32767 || exponent < -32768)
505 overflow = true;
506 }
507
508 if (overflow)
509 exponent = negative ? -32768: 32767;
510
511 return exponent;
512}
513
518 *dot = end;
519 while (p != end && *p == '0')
520 p++;
521
522 if (p != end && *p == '.') {
523 *dot = p++;
524
525 if (end - begin == 1)
526 return createError("Significand has no digits");
527
528 while (p != end && *p == '0')
529 p++;
530 }
531
532 return p;
533}
534
535
536
537
538
539
540
541
542
543
544
545
546
547
553};
554
558
560 if (!PtrOrErr)
561 return PtrOrErr.takeError();
563
564 D->firstSigDigit = p;
565 D->exponent = 0;
566 D->normalizedExponent = 0;
567
568 for (; p != end; ++p) {
569 if (*p == '.') {
570 if (dot != end)
571 return createError("String contains multiple dots");
572 dot = p++;
573 if (p == end)
574 break;
575 }
577 break;
578 }
579
580 if (p != end) {
581 if (*p != 'e' && *p != 'E')
582 return createError("Invalid character in significand");
583 if (p == begin)
584 return createError("Significand has no digits");
585 if (dot != end && p - begin == 1)
586 return createError("Significand has no digits");
587
588
590 if (!ExpOrErr)
591 return ExpOrErr.takeError();
592 D->exponent = *ExpOrErr;
593
594
595 if (dot == end)
596 dot = p;
597 }
598
599
600 if (p != D->firstSigDigit) {
601
602 if (p != begin) {
603 do
604 do
605 p--;
606 while (p != begin && *p == '0');
607 while (p != begin && *p == '.');
608 }
609
610
612 D->normalizedExponent = (D->exponent +
614 - (dot > D->firstSigDigit && dot < p)));
615 }
616
617 D->lastSigDigit = p;
619}
620
621
622
623
626 unsigned int digitValue) {
627 unsigned int hexDigit;
628
629
630
631 if (digitValue > 8)
633 else if (digitValue < 8 && digitValue > 0)
635
636
637 while (p != end && (*p == '0' || *p == '.'))
638 p++;
639
640 if (p == end)
641 return createError("Invalid trailing hexadecimal fraction!");
642
643 hexDigit = hexDigitValue(*p);
644
645
646
647 if (hexDigit == UINT_MAX)
649 else
651}
652
653
654
657 unsigned int partCount,
658 unsigned int bits)
659{
660 unsigned int lsb;
661
663
664
665 if (bits <= lsb)
667 if (bits == lsb + 1)
672
674}
675
676
679{
681
683
685
686 return lost_fraction;
687}
688
689
693{
699 }
700
701 return moreSignificant;
702}
703
704
705
706
707
708
709
710
711static unsigned int
712HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
713{
714 assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
715
716 if (HUerr1 + HUerr2 == 0)
717 return inexactMultiply * 2;
718 else
719 return inexactMultiply + 2 * (HUerr1 + HUerr2);
720}
721
722
723
724
727 bool isNearest) {
728 unsigned int count, partBits;
730
732
733 bits--;
736
738
739 if (isNearest)
741 else
742 boundary = 0;
743
744 if (count == 0) {
745 if (part - boundary <= boundary - part)
746 return part - boundary;
747 else
748 return boundary - part;
749 }
750
751 if (part == boundary) {
753 if (parts[count])
755
756 return parts[0];
757 } else if (part == boundary - 1) {
759 if (~parts[count])
761
762 return -parts[0];
763 }
764
766}
767
768
769
770static unsigned int
772 static const APFloatBase::integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125, 15625, 78125 };
774 pow5s[0] = 78125 * 5;
775
776 unsigned int partsCount = 1;
778 unsigned int result;
780
781 p1 = dst;
782 p2 = scratch;
783
784 *p1 = firstEightPowers[power & 7];
785 power >>= 3;
786
787 result = 1;
788 pow5 = pow5s;
789
790 for (unsigned int n = 0; power; power >>= 1, n++) {
791
792 if (n != 0) {
794 partsCount, partsCount);
795 partsCount *= 2;
796 if (pow5[partsCount - 1] == 0)
797 partsCount--;
798 }
799
800 if (power & 1) {
802
804 result += partsCount;
805 if (p2[result - 1] == 0)
806 result--;
807
808
809
810 tmp = p1;
811 p1 = p2;
812 p2 = tmp;
813 }
814
815 pow5 += partsCount;
816 }
817
818 if (p1 != dst)
820
821 return result;
822}
823
824
825
830static const char NaNL[] = "nan";
831static const char NaNU[] = "NAN";
832
833
834
835
836static unsigned int
838 const char *hexDigitChars)
839{
840 unsigned int result = count;
841
843
845 while (count--) {
846 dst[count] = hexDigitChars[part & 0xf];
847 part >>= 4;
848 }
849
850 return result;
851}
852
853
854static char *
856{
857 char buff[40], *p;
858
859 p = buff;
860 do
861 *p++ = '0' + n % 10;
862 while (n /= 10);
863
864 do
865 *dst++ = *--p;
866 while (p != buff);
867
868 return dst;
869}
870
871
872static char *
874{
876 *dst++ = '-';
878 } else
880
881 return dst;
882}
883
885
886void IEEEFloat::initialize(const fltSemantics *ourSemantics) {
887 unsigned int count;
888
889 semantics = ourSemantics;
890 count = partCount();
893}
894
895void IEEEFloat::freeSignificand() {
897 delete [] significand.parts;
898}
899
900void IEEEFloat::assign(const IEEEFloat &rhs) {
901 assert(semantics == rhs.semantics);
902
903 sign = rhs.sign;
904 category = rhs.category;
905 exponent = rhs.exponent;
907 copySignificand(rhs);
908}
909
910void IEEEFloat::copySignificand(const IEEEFloat &rhs) {
912 assert(rhs.partCount() >= partCount());
913
914 APInt::tcAssign(significandParts(), rhs.significandParts(),
915 partCount());
916}
917
918
919
920
923 llvm_unreachable("This floating point format does not support NaN");
924
927 "This floating point format does not support signed values");
928
929 category = fcNaN;
930 sign = Negative;
931 exponent = exponentNaN();
932
933 integerPart *significand = significandParts();
934 unsigned numParts = partCount();
935
936 APInt fill_storage;
938
939
940 SNaN = false;
942 sign = true;
944 } else {
946 }
947 fill = &fill_storage;
948 }
949
950
951 if (!fill || fill->getNumWords() < numParts)
953 if (fill) {
955 std::min(fill->getNumWords(), numParts));
956
957
958 unsigned bitsToPreserve = semantics->precision - 1;
959 unsigned part = bitsToPreserve / 64;
960 bitsToPreserve %= 64;
961 significand[part] &= ((1ULL << bitsToPreserve) - 1);
962 for (part++; part != numParts; ++part)
963 significand[part] = 0;
964 }
965
966 unsigned QNaNBit =
968
969 if (SNaN) {
970
972
973
974
975
979
980
981 } else {
982
984 }
985
986
987
988
991}
992
994 if (this != &rhs) {
995 if (semantics != rhs.semantics) {
996 freeSignificand();
997 initialize(rhs.semantics);
998 }
999 assign(rhs);
1000 }
1001
1002 return *this;
1003}
1004
1006 freeSignificand();
1007
1008 semantics = rhs.semantics;
1009 significand = rhs.significand;
1010 exponent = rhs.exponent;
1011 category = rhs.category;
1012 sign = rhs.sign;
1013
1015 return *this;
1016}
1017
1021 semantics->precision - 1) == 0);
1022}
1023
1025
1026
1027
1029 significandMSB() == 0;
1030}
1031
1034 isSignificandAllZerosExceptMSB();
1035}
1036
1037unsigned int IEEEFloat::getNumHighBits() const {
1040
1041
1042
1043
1044 const unsigned int NumHighBits = (semantics->precision > 1)
1045 ? (Bits - semantics->precision + 1)
1046 : (Bits - semantics->precision);
1047 return NumHighBits;
1048}
1049
1050bool IEEEFloat::isSignificandAllOnes() const {
1051
1052
1053 const integerPart *Parts = significandParts();
1055 for (unsigned i = 0; i < PartCount - 1; i++)
1056 if (~Parts[i])
1057 return false;
1058
1059
1060 const unsigned NumHighBits = getNumHighBits();
1061 assert(NumHighBits <= integerPartWidth && NumHighBits > 0 &&
1062 "Can not have more high bits to fill than integerPartWidth");
1065 if ((semantics->precision <= 1) || (~(Parts[PartCount - 1] | HighBitFill)))
1066 return false;
1067
1068 return true;
1069}
1070
1071bool IEEEFloat::isSignificandAllOnesExceptLSB() const {
1072
1073
1074 const integerPart *Parts = significandParts();
1075
1076 if (Parts[0] & 1)
1077 return false;
1078
1080 for (unsigned i = 0; i < PartCount - 1; i++) {
1081 if (~Parts[i] & ~unsigned{!i})
1082 return false;
1083 }
1084
1085
1086 const unsigned NumHighBits = getNumHighBits();
1087 assert(NumHighBits <= integerPartWidth && NumHighBits > 0 &&
1088 "Can not have more high bits to fill than integerPartWidth");
1089 const integerPart HighBitFill = ~integerPart(0)
1091 if (~(Parts[PartCount - 1] | HighBitFill | 0x1))
1092 return false;
1093
1094 return true;
1095}
1096
1097bool IEEEFloat::isSignificandAllZeros() const {
1098
1099
1100 const integerPart *Parts = significandParts();
1102
1103 for (unsigned i = 0; i < PartCount - 1; i++)
1104 if (Parts[i])
1105 return false;
1106
1107
1108 const unsigned NumHighBits = getNumHighBits();
1110 "clear than integerPartWidth");
1111 const integerPart HighBitMask = ~integerPart(0) >> NumHighBits;
1112
1113 if ((semantics->precision > 1) && (Parts[PartCount - 1] & HighBitMask))
1114 return false;
1115
1116 return true;
1117}
1118
1119bool IEEEFloat::isSignificandAllZerosExceptMSB() const {
1120 const integerPart *Parts = significandParts();
1122
1123 for (unsigned i = 0; i < PartCount - 1; i++) {
1124 if (Parts[i])
1125 return false;
1126 }
1127
1128 const unsigned NumHighBits = getNumHighBits();
1131 return ((semantics->precision <= 1) || (Parts[PartCount - 1] == MSBMask));
1132}
1133
1138
1139
1140
1142 ? isSignificandAllOnesExceptLSB()
1143 : IsMaxExp;
1144 } else {
1145
1146
1147 return IsMaxExp && isSignificandAllOnes();
1148 }
1149}
1150
1152
1153 if (()) return false;
1157}
1158
1160 if (this == &rhs)
1161 return true;
1162 if (semantics != rhs.semantics ||
1163 category != rhs.category ||
1164 sign != rhs.sign)
1165 return false;
1167 return true;
1168
1170 return false;
1171
1172 return std::equal(significandParts(), significandParts() + partCount(),
1173 rhs.significandParts());
1174}
1175
1177 initialize(&ourSemantics);
1178 sign = 0;
1180 zeroSignificand();
1181 exponent = ourSemantics.precision - 1;
1182 significandParts()[0] = value;
1184}
1185
1187 initialize(&ourSemantics);
1188
1189
1190
1191
1192
1193
1195}
1196
1197
1198
1201
1203 initialize(rhs.semantics);
1204 assign(rhs);
1205}
1206
1208 *this = std::move(rhs);
1209}
1210
1212
1213unsigned int IEEEFloat::partCount() const {
1215}
1216
1218 return const_cast<IEEEFloat *>(this)->significandParts();
1219}
1220
1222 if (partCount() > 1)
1223 return significand.parts;
1224 else
1225 return &significand.part;
1226}
1227
1228void IEEEFloat::zeroSignificand() {
1229 APInt::tcSet(significandParts(), 0, partCount());
1230}
1231
1232
1233void IEEEFloat::incrementSignificand() {
1235
1237
1238
1240 (void)carry;
1241}
1242
1243
1246
1247 parts = significandParts();
1248
1249 assert(semantics == rhs.semantics);
1250 assert(exponent == rhs.exponent);
1251
1252 return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
1253}
1254
1255
1256
1260
1261 parts = significandParts();
1262
1263 assert(semantics == rhs.semantics);
1264 assert(exponent == rhs.exponent);
1265
1267 partCount());
1268}
1269
1270
1271
1272
1273lostFraction IEEEFloat::multiplySignificand(const IEEEFloat &rhs,
1274 IEEEFloat addend,
1275 bool ignoreAddend) {
1276 unsigned int omsb;
1277 unsigned int partsCount, newPartsCount, precision;
1283
1284 assert(semantics == rhs.semantics);
1285
1286 precision = semantics->precision;
1287
1288
1289
1291
1292 if (newPartsCount > 4)
1293 fullSignificand = new integerPart[newPartsCount];
1294 else
1295 fullSignificand = scratch;
1296
1297 lhsSignificand = significandParts();
1298 partsCount = partCount();
1299
1301 rhs.significandParts(), partsCount, partsCount);
1302
1304 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
1305 exponent += rhs.exponent;
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317 exponent += 2;
1318
1319 if (!ignoreAddend && addend.isNonZero()) {
1320
1321
1322
1323 Significand savedSignificand = significand;
1324 const fltSemantics *savedSemantics = semantics;
1327 unsigned int extendedPrecision;
1328
1329
1330 extendedPrecision = 2 * precision + 1;
1331 if (omsb != extendedPrecision - 1) {
1332 assert(extendedPrecision > omsb);
1334 (extendedPrecision - 1) - omsb);
1335 exponent -= (extendedPrecision - 1) - omsb;
1336 }
1337
1338
1339 extendedSemantics = *semantics;
1340 extendedSemantics.precision = extendedPrecision;
1341
1342 if (newPartsCount == 1)
1343 significand.part = fullSignificand[0];
1344 else
1345 significand.parts = fullSignificand;
1346 semantics = &extendedSemantics;
1347
1348
1349
1350
1351 IEEEFloat extendedAddend(addend);
1355 (void)status;
1356
1357
1358
1359
1360 lost_fraction = extendedAddend.shiftSignificandRight(1);
1362 "Lost precision while shifting addend for fused-multiply-add.");
1363
1364 lost_fraction = addOrSubtractSignificand(extendedAddend, false);
1365
1366
1367 if (newPartsCount == 1)
1368 fullSignificand[0] = significand.part;
1369 significand = savedSignificand;
1370 semantics = savedSemantics;
1371
1372 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
1373 }
1374
1375
1376
1377
1378
1379 exponent -= precision + 1;
1380
1381
1382
1383
1384
1385
1386
1387
1388 if (omsb > precision) {
1389 unsigned int bits, significantParts;
1391
1392 bits = omsb - precision;
1394 lf = shiftRight(fullSignificand, significantParts, bits);
1396 exponent += bits;
1397 }
1398
1399 APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
1400
1401 if (newPartsCount > 4)
1402 delete [] fullSignificand;
1403
1404 return lost_fraction;
1405}
1406
1407lostFraction IEEEFloat::multiplySignificand(const IEEEFloat &rhs) {
1408
1409
1410
1411
1412
1413 return multiplySignificand(rhs, IEEEFloat(*semantics), !semantics->hasZero);
1414}
1415
1416
1417lostFraction IEEEFloat::divideSignificand(const IEEEFloat &rhs) {
1418 unsigned int bit, i, partsCount;
1420 integerPart *lhsSignificand, *dividend, *divisor;
1423
1424 assert(semantics == rhs.semantics);
1425
1426 lhsSignificand = significandParts();
1427 rhsSignificand = rhs.significandParts();
1428 partsCount = partCount();
1429
1430 if (partsCount > 2)
1431 dividend = new integerPart[partsCount * 2];
1432 else
1433 dividend = scratch;
1434
1435 divisor = dividend + partsCount;
1436
1437
1438 for (i = 0; i < partsCount; i++) {
1439 dividend[i] = lhsSignificand[i];
1440 divisor[i] = rhsSignificand[i];
1441 lhsSignificand[i] = 0;
1442 }
1443
1444 exponent -= rhs.exponent;
1445
1446 unsigned int precision = semantics->precision;
1447
1448
1449 bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
1450 if (bit) {
1451 exponent += bit;
1453 }
1454
1455
1456 bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
1457 if (bit) {
1458 exponent -= bit;
1460 }
1461
1462
1463
1464
1466 exponent--;
1469 }
1470
1471
1472 for (bit = precision; bit; bit -= 1) {
1476 }
1477
1479 }
1480
1481
1483
1484 if (cmp > 0)
1486 else if (cmp == 0)
1490 else
1492
1493 if (partsCount > 2)
1494 delete [] dividend;
1495
1496 return lost_fraction;
1497}
1498
1499unsigned int IEEEFloat::significandMSB() const {
1500 return APInt::tcMSB(significandParts(), partCount());
1501}
1502
1503unsigned int IEEEFloat::significandLSB() const {
1504 return APInt::tcLSB(significandParts(), partCount());
1505}
1506
1507
1508lostFraction IEEEFloat::shiftSignificandRight(unsigned int bits) {
1509
1511
1512 exponent += bits;
1513
1514 return shiftRight(significandParts(), partCount(), bits);
1515}
1516
1517
1518void IEEEFloat::shiftSignificandLeft(unsigned int bits) {
1519 assert(bits < semantics->precision ||
1520 (semantics->precision == 1 && bits <= 1));
1521
1522 if (bits) {
1523 unsigned int partsCount = partCount();
1524
1526 exponent -= bits;
1527
1529 }
1530}
1531
1534
1535 assert(semantics == rhs.semantics);
1538
1539 compare = exponent - rhs.exponent;
1540
1541
1542
1545 partCount());
1546
1551 else
1553}
1554
1555
1556
1558 unsigned bits) {
1559 unsigned i = 0;
1563 }
1564
1565 if (bits)
1567
1568 while (i < parts)
1569 dst[i++] = 0;
1570}
1571
1572
1573
1576
1583 else
1586 }
1587 }
1588
1589
1597
1599}
1600
1601
1602
1603
1604
1605
1606bool IEEEFloat::roundAwayFromZero(roundingMode rounding_mode,
1608 unsigned int bit) const {
1609
1611
1612
1614
1615 switch (rounding_mode) {
1618
1621 return true;
1622
1623
1626
1627 return false;
1628
1630 return false;
1631
1633 return !sign;
1634
1636 return sign;
1637
1638 default:
1639 break;
1640 }
1642}
1643
1646 unsigned int omsb;
1647 int exponentChange;
1648
1650 return opOK;
1651
1652
1653 omsb = significandMSB() + 1;
1654
1655 if (omsb) {
1656
1657
1658
1659 exponentChange = omsb - semantics->precision;
1660
1661
1662
1663 if (exponent + exponentChange > semantics->maxExponent)
1664 return handleOverflow(rounding_mode);
1665
1666
1667
1668 if (exponent + exponentChange < semantics->minExponent)
1669 exponentChange = semantics->minExponent - exponent;
1670
1671
1672 if (exponentChange < 0) {
1674
1675 shiftSignificandLeft(-exponentChange);
1676
1677 return opOK;
1678 }
1679
1680 if (exponentChange > 0) {
1682
1683
1684 lf = shiftSignificandRight(exponentChange);
1685
1687
1688
1689 if (omsb > (unsigned) exponentChange)
1690 omsb -= exponentChange;
1691 else
1692 omsb = 0;
1693 }
1694 }
1695
1696
1697
1700 exponent == semantics->maxExponent && isSignificandAllOnes())
1701 return handleOverflow(rounding_mode);
1702
1703
1704
1705
1706
1707
1709
1710 if (omsb == 0) {
1713 sign = false;
1714 if (!semantics->hasZero)
1716 }
1717
1718 return opOK;
1719 }
1720
1721
1722 if (roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
1723 if (omsb == 0)
1725
1726 incrementSignificand();
1727 omsb = significandMSB() + 1;
1728
1729
1730 if (omsb == (unsigned) semantics->precision + 1) {
1731
1732
1733
1735
1736
1737
1738
1740
1741 shiftSignificandRight(1);
1742
1744 }
1745
1746
1747
1750 exponent == semantics->maxExponent && isSignificandAllOnes())
1751 return handleOverflow(rounding_mode);
1752 }
1753
1754
1755
1756 if (omsb == semantics->precision)
1758
1759
1760 assert(omsb < semantics->precision);
1761
1762
1763 if (omsb == 0) {
1766 sign = false;
1767
1768
1769
1770 if (!semantics->hasZero)
1772 }
1773
1774
1776}
1777
1778APFloat::opStatus IEEEFloat::addOrSubtractSpecials(const IEEEFloat &rhs,
1779 bool subtract) {
1781 default:
1783
1787 assign(rhs);
1788 [[fallthrough]];
1796 }
1798
1802 return opOK;
1803
1808 return opOK;
1809
1811 assign(rhs);
1813 return opOK;
1814
1816
1817 return opOK;
1818
1820
1821
1822 if (((sign ^ rhs.sign)!=0) != subtract) {
1825 }
1826
1827 return opOK;
1828
1831 }
1832}
1833
1834
1835lostFraction IEEEFloat::addOrSubtractSignificand(const IEEEFloat &rhs,
1836 bool subtract) {
1839 int bits;
1840
1841
1842
1843 subtract ^= static_cast<bool>(sign ^ rhs.sign);
1844
1845
1846 bits = exponent - rhs.exponent;
1847
1848
1852 "This floating point format does not support signed values");
1853
1855
1856 if (bits == 0)
1858 else if (bits > 0) {
1859 lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
1860 shiftSignificandLeft(1);
1861 } else {
1862 lost_fraction = shiftSignificandRight(-bits - 1);
1863 temp_rhs.shiftSignificandLeft(1);
1864 }
1865
1866
1868 carry = temp_rhs.subtractSignificand
1870 copySignificand(temp_rhs);
1871 sign = !sign;
1872 } else {
1873 carry = subtractSignificand
1875 }
1876
1877
1878
1883
1884
1885
1887 (void)carry;
1888 } else {
1889 if (bits > 0) {
1891
1892 lost_fraction = temp_rhs.shiftSignificandRight(bits);
1893 carry = addSignificand(temp_rhs);
1894 } else {
1895 lost_fraction = shiftSignificandRight(-bits);
1896 carry = addSignificand(rhs);
1897 }
1898
1899
1901 (void)carry;
1902 }
1903
1904 return lost_fraction;
1905}
1906
1907APFloat::opStatus IEEEFloat::multiplySpecials(const IEEEFloat &rhs) {
1909 default:
1911
1915 assign(rhs);
1916 sign = false;
1917 [[fallthrough]];
1922 sign ^= rhs.sign;
1926 }
1928
1933 return opOK;
1934
1939 return opOK;
1940
1945
1947 return opOK;
1948 }
1949}
1950
1951APFloat::opStatus IEEEFloat::divideSpecials(const IEEEFloat &rhs) {
1953 default:
1955
1959 assign(rhs);
1960 sign = false;
1961 [[fallthrough]];
1966 sign ^= rhs.sign;
1970 }
1972
1977 return opOK;
1978
1981 return opOK;
1982
1986 else
1989
1994
1996 return opOK;
1997 }
1998}
1999
2002 default:
2004
2008 assign(rhs);
2009 [[fallthrough]];
2017 }
2019
2023 return opOK;
2024
2032
2034 return opOK;
2035 }
2036}
2037
2038APFloat::opStatus IEEEFloat::remainderSpecials(const IEEEFloat &rhs) {
2040 default:
2042
2046 assign(rhs);
2047 [[fallthrough]];
2055 }
2057
2061 return opOK;
2062
2070
2072 return opDivByZero;
2073 }
2074}
2075
2076
2078
2079
2082 return;
2083
2084 sign = !sign;
2085}
2086
2087
2090 bool subtract) {
2092
2093 fs = addOrSubtractSpecials(rhs, subtract);
2094
2095
2098
2099 lost_fraction = addOrSubtractSignificand(rhs, subtract);
2100 fs = normalize(rounding_mode, lost_fraction);
2101
2102
2104 }
2105
2106
2107
2108
2109 if (category == fcZero) {
2110 if (rhs.category != fcZero || (sign == rhs.sign) == subtract)
2112
2114 sign = false;
2115 }
2116
2117 return fs;
2118}
2119
2120
2123 return addOrSubtract(rhs, rounding_mode, false);
2124}
2125
2126
2129 return addOrSubtract(rhs, rounding_mode, true);
2130}
2131
2132
2136
2137 sign ^= rhs.sign;
2138 fs = multiplySpecials(rhs);
2139
2141 sign = false;
2143 lostFraction lost_fraction = multiplySignificand(rhs);
2144 fs = normalize(rounding_mode, lost_fraction);
2147 }
2148
2149 return fs;
2150}
2151
2152
2156
2157 sign ^= rhs.sign;
2158 fs = divideSpecials(rhs);
2159
2161 sign = false;
2163 lostFraction lost_fraction = divideSignificand(rhs);
2164 fs = normalize(rounding_mode, lost_fraction);
2167 }
2168
2169 return fs;
2170}
2171
2172
2175 unsigned int origSign = sign;
2176
2177
2178 fs = remainderSpecials(rhs);
2180 return fs;
2181
2183
2184
2185
2186
2187
2190 fs = mod(P2);
2192 }
2193
2194
2196 P.sign = false;
2197 sign = false;
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233 bool losesInfo;
2234 fltSemantics extendedSemantics = *semantics;
2237 extendedSemantics.precision += 2;
2238
2245
2246
2247
2250
2254
2255
2256
2257
2262
2267 }
2268 }
2269
2271 sign = origSign;
2273
2274 sign = false;
2275 }
2276
2277 else
2278 sign ^= origSign;
2279 return fs;
2280}
2281
2282
2285 fs = modSpecials(rhs);
2286 unsigned int origSign = sign;
2287
2290 int Exp = ilogb(*this) - ilogb(rhs);
2292
2293
2296 V.sign = sign;
2297
2299
2300
2301
2302
2303
2304
2305
2306
2307 if (!semantics->hasZero && this->isSmallest())
2308 break;
2309
2311 }
2313 sign = origSign;
2315 sign = false;
2316 }
2317 return fs;
2318}
2319
2320
2325
2326
2327 sign ^= multiplicand.sign;
2328
2329
2330
2335
2336 lost_fraction = multiplySignificand(multiplicand, addend);
2337 fs = normalize(rounding_mode, lost_fraction);
2340
2341
2342
2343
2344 if (category == fcZero && !(fs & opUnderflow) && sign != addend.sign) {
2347 sign = false;
2348 }
2349 } else {
2350 fs = multiplySpecials(multiplicand);
2351
2352
2353
2354
2355
2356
2357
2358
2359 if (fs == opOK)
2360 fs = addOrSubtract(addend, rounding_mode, false);
2361 }
2362
2363 return fs;
2364}
2365
2366
2369
2371
2372
2373
2374
2375
2376
2377
2378 return opOK;
2379
2382
2383
2384
2385
2387
2388
2389
2390
2391
2393 } else {
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403 return opOK;
2404 }
2405 }
2406
2408
2409
2410
2411
2412 return opOK;
2413 }
2414
2415
2416
2417
2419 return opOK;
2420
2421
2422
2423
2424
2425
2426
2428 1);
2430 IEEEFloat MagicConstant(*semantics);
2434 MagicConstant.sign = sign;
2435
2436
2437
2439
2440 fs = add(MagicConstant, rounding_mode);
2441
2442
2443
2444 subtract(MagicConstant, rounding_mode);
2445
2446
2449
2450 return fs;
2451}
2452
2453
2456
2457 assert(semantics == rhs.semantics);
2458
2460 default:
2462
2471
2475 if (sign)
2477 else
2479
2483 if (rhs.sign)
2485 else
2487
2489 if (sign == rhs.sign)
2491 else if (sign)
2493 else
2495
2498
2500 break;
2501 }
2502
2503
2504 if (sign != rhs.sign) {
2505 if (sign)
2507 else
2509 } else {
2510
2512
2513 if (sign) {
2518 }
2519 }
2520
2521 return result;
2522}
2523
2524
2525
2526
2527
2528
2529
2530
2533 bool *losesInfo) {
2535 unsigned int newPartCount, oldPartCount;
2537 int shift;
2538 const fltSemantics &fromSemantics = *semantics;
2540
2543 oldPartCount = partCount();
2545
2546 bool X86SpecialNan = false;
2549 (!(*significandParts() & 0x8000000000000000ULL) ||
2550 !(*significandParts() & 0x4000000000000000ULL))) {
2551
2552
2553 X86SpecialNan = true;
2554 }
2555
2556
2557
2558
2559
2560
2561
2562
2564 int omsb = significandMSB() + 1;
2565 int exponentChange = omsb - fromSemantics.precision;
2566 if (exponent + exponentChange < toSemantics.minExponent)
2567 exponentChange = toSemantics.minExponent - exponent;
2568 if (exponentChange < shift)
2569 exponentChange = shift;
2570 if (exponentChange < 0) {
2571 shift -= exponentChange;
2572 exponent += exponentChange;
2573 } else if (omsb <= -shift) {
2574 exponentChange = omsb + shift - 1;
2575 shift -= exponentChange;
2576 exponent += exponentChange;
2577 }
2578 }
2579
2580
2585
2586
2587 if (newPartCount > oldPartCount) {
2588
2590 newParts = new integerPart[newPartCount];
2593 APInt::tcAssign(newParts, significandParts(), oldPartCount);
2594 freeSignificand();
2595 significand.parts = newParts;
2596 } else if (newPartCount == 1 && oldPartCount != 1) {
2597
2600 newPart = significandParts()[0];
2601 freeSignificand();
2602 significand.part = newPart;
2603 }
2604
2605
2606 semantics = &toSemantics;
2607
2608
2609
2612
2614 fs = normalize(rounding_mode, lostFraction);
2615 *losesInfo = (fs != opOK);
2616 } else if (category == fcNaN) {
2618 *losesInfo =
2622 }
2623
2624
2625
2629
2631
2632
2633
2636
2637
2638
2639
2640 if (is_signaling) {
2643 } else {
2645 }
2646 } else if (category == fcInfinity &&
2649 *losesInfo = true;
2651 } else if (category == fcZero &&
2653
2654 *losesInfo =
2657
2658 sign = false;
2659 } else {
2660 *losesInfo = false;
2662 }
2663
2666 return fs;
2667}
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2681 roundingMode rounding_mode, bool *isExact) const {
2684 unsigned int dstPartsCount, truncatedBits;
2685
2686 *isExact = false;
2687
2688
2691
2693 assert(dstPartsCount <= parts.size() && "Integer too big");
2694
2695 if (category == fcZero) {
2697
2698 *isExact = !sign;
2699 return opOK;
2700 }
2701
2702 src = significandParts();
2703
2704
2705
2706 if (exponent < 0) {
2707
2709
2710
2711 truncatedBits = semantics->precision -1U - exponent;
2712 } else {
2713
2714
2715 unsigned int bits = exponent + 1U;
2716
2717
2718 if (bits > width)
2720
2721 if (bits < semantics->precision) {
2722
2723 truncatedBits = semantics->precision - bits;
2725 } else {
2726
2728 0);
2731 truncatedBits = 0;
2732 }
2733 }
2734
2735
2736
2737 if (truncatedBits) {
2739 truncatedBits);
2741 roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
2744 }
2745 } else {
2747 }
2748
2749
2750 unsigned int omsb = APInt::tcMSB(parts.data(), dstPartsCount) + 1;
2751
2752 if (sign) {
2754
2755 if (omsb != 0)
2757 } else {
2758
2759
2760
2761 if (omsb == width &&
2764
2765
2766 if (omsb > width)
2768 }
2769
2771 } else {
2772 if (omsb >= width + )
2774 }
2775
2777 *isExact = true;
2778 return opOK;
2779 } else
2781}
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2794 unsigned int width, bool isSigned,
2795 roundingMode rounding_mode, bool *isExact) const {
2797
2798 fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode,
2799 isExact);
2800
2802 unsigned int bits, dstPartsCount;
2803
2805 assert(dstPartsCount <= parts.size() && "Integer too big");
2806
2807 if (category == fcNaN)
2808 bits = 0;
2809 else if (sign)
2811 else
2813
2817 }
2818
2819 return fs;
2820}
2821
2822
2823
2824
2827 unsigned int omsb, precision, dstCount;
2830
2833 dst = significandParts();
2834 dstCount = partCount();
2835 precision = semantics->precision;
2836
2837
2838
2839 if (precision <= omsb) {
2840 exponent = omsb - 1;
2842 omsb - precision);
2843 APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
2844 } else {
2845 exponent = precision - 1;
2848 }
2849
2850 return normalize(rounding_mode, lost_fraction);
2851}
2852
2855 unsigned int partCount = Val.getNumWords();
2856 APInt api = Val;
2857
2858 sign = false;
2860 sign = true;
2861 api = -api;
2862 }
2863
2864 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
2865}
2866
2867
2868
2869
2872 unsigned int srcCount, bool isSigned,
2875
2879
2880
2881 sign = true;
2885 status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
2886 delete [] copy;
2887 } else {
2888 sign = false;
2889 status = convertFromUnsignedParts(src, srcCount, rounding_mode);
2890 }
2891
2892 return status;
2893}
2894
2895
2898 unsigned int width, bool isSigned,
2902
2903 sign = false;
2905 sign = true;
2906 api = -api;
2907 }
2908
2909 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
2910}
2911
2913IEEEFloat::convertFromHexadecimalString(StringRef s,
2916
2918 zeroSignificand();
2919 exponent = 0;
2920
2921 integerPart *significand = significandParts();
2922 unsigned partsCount = partCount();
2924 bool computedTrailingFraction = false;
2925
2926
2931 if (!PtrOrErr)
2932 return PtrOrErr.takeError();
2935
2936 while (p != end) {
2938
2939 if (*p == '.') {
2940 if (dot != end)
2941 return createError("String contains multiple dots");
2942 dot = p++;
2943 continue;
2944 }
2945
2946 hex_value = hexDigitValue(*p);
2947 if (hex_value == UINT_MAX)
2948 break;
2949
2950 p++;
2951
2952
2953 if (bitPos) {
2954 bitPos -= 4;
2957 } else if (!computedTrailingFraction) {
2959 if (!FractOrErr)
2960 return FractOrErr.takeError();
2961 lost_fraction = *FractOrErr;
2962 computedTrailingFraction = true;
2963 }
2964 }
2965
2966
2967 if (p == end)
2968 return createError("Hex strings require an exponent");
2969 if (*p != 'p' && *p != 'P')
2970 return createError("Invalid character in significand");
2971 if (p == begin)
2972 return createError("Significand has no digits");
2973 if (dot != end && p - begin == 1)
2974 return createError("Significand has no digits");
2975
2976
2977 if (p != firstSignificantDigit) {
2978 int expAdjustment;
2979
2980
2981 if (dot == end)
2983
2984
2985
2986 expAdjustment = static_cast<int>(dot - firstSignificantDigit);
2987 if (expAdjustment < 0)
2988 expAdjustment++;
2989 expAdjustment = expAdjustment * 4 - 1;
2990
2991
2992
2993 expAdjustment += semantics->precision;
2995
2996
2997 auto ExpOrErr = totalExponent(p + 1, end, expAdjustment);
2998 if (!ExpOrErr)
2999 return ExpOrErr.takeError();
3000 exponent = *ExpOrErr;
3001 }
3002
3003 return normalize(rounding_mode, lost_fraction);
3004}
3005
3007IEEEFloat::roundSignificandWithExponent(const integerPart *decSigParts,
3008 unsigned sigPartCount, int exp,
3010 unsigned int parts, pow5PartCount;
3011 fltSemantics calcSemantics = { 32767, -32767, 0, 0 };
3013 bool isNearest;
3014
3017
3019
3020
3021 pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp);
3022
3023 for (;; parts *= 2) {
3024 opStatus sigStatus, powStatus;
3025 unsigned int excessPrecision, truncatedBits;
3026
3029 truncatedBits = excessPrecision;
3030
3032 decSig.makeZero(sign);
3034
3035 sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount,
3037 powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
3039
3040 decSig.exponent += exp;
3041
3044 unsigned int powHUerr;
3045
3046 if (exp >= 0) {
3047
3048 calcLostFraction = decSig.multiplySignificand(pow5);
3049 powHUerr = powStatus != opOK;
3050 } else {
3051 calcLostFraction = decSig.divideSignificand(pow5);
3052
3053 if (decSig.exponent < semantics->minExponent) {
3054 excessPrecision += (semantics->minExponent - decSig.exponent);
3055 truncatedBits = excessPrecision;
3056 if (excessPrecision > calcSemantics.precision)
3057 excessPrecision = calcSemantics.precision;
3058 }
3059
3060 powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2;
3061 }
3062
3063
3064
3066 (decSig.significandParts(), calcSemantics.precision - 1) == 1);
3067
3069 powHUerr);
3070 HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
3071 excessPrecision, isNearest);
3072
3073
3074 if (HUdistance >= HUerr) {
3075 APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
3076 calcSemantics.precision - excessPrecision,
3077 excessPrecision);
3078
3079
3080
3081 exponent = (decSig.exponent + semantics->precision
3082 - (calcSemantics.precision - excessPrecision));
3084 decSig.partCount(),
3085 truncatedBits);
3086 return normalize(rounding_mode, calcLostFraction);
3087 }
3088 }
3089}
3090
3095
3096
3099 return std::move(Err);
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125 if (D.firstSigDigit == str.end() || decDigitValue(*D.firstSigDigit) >= 10U) {
3129 sign = false;
3130 if (!semantics->hasZero)
3132
3133
3134
3135 } else if (D.normalizedExponent - 1 > INT_MAX / 42039) {
3136 fs = handleOverflow(rounding_mode);
3137
3138
3139
3140
3141
3142 } else if (D.normalizedExponent - 1 < INT_MIN / 42039 ||
3143 (D.normalizedExponent + 1) * 28738 <=
3145
3147 zeroSignificand();
3149
3150
3151 } else if ((D.normalizedExponent - 1) * 42039
3153
3154 fs = handleOverflow(rounding_mode);
3155 } else {
3157 unsigned int partCount;
3158
3159
3160
3161
3162
3163 partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1;
3165 decSignificand = new integerPart[partCount + 1];
3166 partCount = 0;
3167
3168
3169
3170
3171
3172 do {
3174
3175 val = 0;
3176 multiplier = 1;
3177
3178 do {
3179 if (*p == '.') {
3180 p++;
3181 if (p == str.end()) {
3182 break;
3183 }
3184 }
3186 if (decValue >= 10U) {
3187 delete[] decSignificand;
3188 return createError("Invalid character in significand");
3189 }
3190 multiplier *= 10;
3191 val = val * 10 + decValue;
3192
3193
3194 } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
3195
3196
3198 partCount, partCount + 1, false);
3199
3200
3201
3202 if (decSignificand[partCount])
3203 partCount++;
3204 } while (p <= D.lastSigDigit);
3205
3207 fs = roundSignificandWithExponent(decSignificand, partCount,
3208 D.exponent, rounding_mode);
3209
3210 delete [] decSignificand;
3211 }
3212
3213 return fs;
3214}
3215
3216bool IEEEFloat::convertFromStringSpecials(StringRef str) {
3217 const size_t MIN_NAME_SIZE = 3;
3218
3219 if (str.size() < MIN_NAME_SIZE)
3220 return false;
3221
3222 if (str == "inf" || str == "INFINITY" || str == "+Inf") {
3224 return true;
3225 }
3226
3227 bool IsNegative = str.front() == '-';
3228 if (IsNegative) {
3230 if (str.size() < MIN_NAME_SIZE)
3231 return false;
3232
3233 if (str == "inf" || str == "INFINITY" || str == "Inf") {
3235 return true;
3236 }
3237 }
3238
3239
3240 bool IsSignaling = str.front() == 's' || str.front() == 'S';
3241 if (IsSignaling) {
3243 if (str.size() < MIN_NAME_SIZE)
3244 return false;
3245 }
3246
3249
3250
3251 if (str.empty()) {
3252 makeNaN(IsSignaling, IsNegative);
3253 return true;
3254 }
3255
3256
3257 if (str.front() == '(') {
3258
3259 if (str.size() <= 2 || str.back() != ')')
3260 return false;
3261
3262 str = str.slice(1, str.size() - 1);
3263 }
3264
3265
3266 unsigned Radix = 10;
3267 if (str[0] == '0') {
3268 if (str.size() > 1 && tolower(str[1]) == 'x') {
3270 Radix = 16;
3271 } else
3272 Radix = 8;
3273 }
3274
3275
3278 makeNaN(IsSignaling, IsNegative, &Payload);
3279 return true;
3280 }
3281 }
3282
3283 return false;
3284}
3285
3288 if (str.empty())
3289 return createError("Invalid string length");
3290
3291
3292 if (convertFromStringSpecials(str))
3293 return opOK;
3294
3295
3297 size_t slen = str.size();
3298 sign = *p == '-' ? 1 : 0;
3301 "This floating point format does not support signed values");
3302
3303 if (*p == '-' || *p == '+') {
3304 p++;
3305 slen--;
3306 if (!slen)
3307 return createError("String has no digits");
3308 }
3309
3310 if (slen >= 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
3311 if (slen == 2)
3313 return convertFromHexadecimalString(StringRef(p + 2, slen - 2),
3314 rounding_mode);
3315 }
3316
3317 return convertFromDecimalString(StringRef(p, slen), rounding_mode);
3318}
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3345 bool upperCase,
3347 char *p;
3348
3349 p = dst;
3350 if (sign)
3351 *dst++ = '-';
3352
3353 switch (category) {
3357 break;
3358
3360 memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
3361 dst += sizeof NaNU - 1;
3362 break;
3363
3365 *dst++ = '0';
3366 *dst++ = upperCase ? 'X': 'x';
3367 *dst++ = '0';
3368 if (hexDigits > 1) {
3369 *dst++ = '.';
3370 memset (dst, '0', hexDigits - 1);
3371 dst += hexDigits - 1;
3372 }
3373 *dst++ = upperCase ? 'P': 'p';
3374 *dst++ = '0';
3375 break;
3376
3378 dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
3379 break;
3380 }
3381
3382 *dst = 0;
3383
3384 return static_cast<unsigned int>(dst - p);
3385}
3386
3387
3388
3389
3390
3391char *IEEEFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
3392 bool upperCase,
3394 unsigned int count, valueBits, shift, partsCount, outputDigits;
3395 const char *hexDigitChars;
3397 char *p;
3398 bool roundUp;
3399
3400 *dst++ = '0';
3401 *dst++ = upperCase ? 'X': 'x';
3402
3403 roundUp = false;
3405
3406 significand = significandParts();
3407 partsCount = partCount();
3408
3409
3410
3411 valueBits = semantics->precision + 3;
3413
3414
3415
3416 outputDigits = (valueBits - significandLSB () + 3) / 4;
3417
3418
3419
3420
3421 if (hexDigits) {
3422 if (hexDigits < outputDigits) {
3423
3424
3425 unsigned int bits;
3427
3428 bits = valueBits - hexDigits * 4;
3430 roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
3431 }
3432 outputDigits = hexDigits;
3433 }
3434
3435
3436
3437
3438 p = ++dst;
3439
3441
3442 while (outputDigits && count) {
3444
3445
3446 if (--count == partsCount)
3447 part = 0;
3448 else
3449 part = significand[count] << shift;
3450
3451 if (count && shift)
3453
3454
3456
3457 if (curDigits > outputDigits)
3458 curDigits = outputDigits;
3459 dst += partAsHex (dst, part, curDigits, hexDigitChars);
3460 outputDigits -= curDigits;
3461 }
3462
3463 if (roundUp) {
3464 char *q = dst;
3465
3466
3467 do {
3468 q--;
3469 *q = hexDigitChars[hexDigitValue (*q) + 1];
3470 } while (*q == '0');
3472 } else {
3473
3474 memset (dst, '0', outputDigits);
3475 dst += outputDigits;
3476 }
3477
3478
3479
3480
3482 if (dst -1 == p)
3483 dst--;
3484 else
3485 p[0] = '.';
3486
3487
3488 *dst++ = upperCase ? 'P': 'p';
3489
3491}
3492
3496
3499
3500
3502 Arg.semantics->precision, Arg.exponent,
3504 Arg.significandParts(),
3505 Arg.significandParts() + Arg.partCount()));
3506}
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517APInt IEEEFloat::convertF80LongDoubleAPFloatToAPInt() const {
3519 assert(partCount()==2);
3520
3521 uint64_t myexponent, mysignificand;
3522
3524 myexponent = exponent+16383;
3525 mysignificand = significandParts()[0];
3526 if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
3527 myexponent = 0;
3528 } else if (category==fcZero) {
3529 myexponent = 0;
3530 mysignificand = 0;
3532 myexponent = 0x7fff;
3533 mysignificand = 0x8000000000000000ULL;
3534 } else {
3535 assert(category == fcNaN && "Unknown category");
3536 myexponent = 0x7fff;
3537 mysignificand = significandParts()[0];
3538 }
3539
3541 words[0] = mysignificand;
3542 words[1] = ((uint64_t)(sign & 1) << 15) |
3543 (myexponent & 0x7fffLL);
3544 return APInt(80, words);
3545}
3546
3547APInt IEEEFloat::convertPPCDoubleDoubleLegacyAPFloatToAPInt() const {
3549 assert(partCount()==2);
3550
3553 bool losesInfo;
3554
3555
3556
3557
3558
3559
3560
3561 fltSemantics extendedSemantics = *semantics;
3564 fs = extended.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
3566 (void)fs;
3567
3571 (void)fs;
3572 words[0] = *u.convertDoubleAPFloatToAPInt().getRawData();
3573
3574
3575
3576
3577
3578 if (u.isFiniteNonZero() && losesInfo) {
3581 (void)fs;
3582
3587 (void)fs;
3588 words[1] = *v.convertDoubleAPFloatToAPInt().getRawData();
3589 } else {
3590 words[1] = 0;
3591 }
3592
3593 return APInt(128, words);
3594}
3595
3596template <const fltSemantics &S>
3597APInt IEEEFloat::convertIEEEFloatToAPInt() const {
3598 assert(semantics == &S);
3599 const int bias =
3600 (semantics == &semFloat8E8M0FNU) ? -S.minExponent : -(S.minExponent - 1);
3601 constexpr unsigned int trailing_significand_bits = S.precision - 1;
3602 constexpr int integer_bit_part = trailing_significand_bits / integerPartWidth;
3605 constexpr uint64_t significand_mask = integer_bit - 1;
3606 constexpr unsigned int exponent_bits =
3607 trailing_significand_bits ? (S.sizeInBits - 1 - trailing_significand_bits)
3608 : S.sizeInBits;
3609 static_assert(exponent_bits < 64);
3610 constexpr uint64_t exponent_mask = (uint64_t{1} << exponent_bits) - 1;
3611
3614 mysignificand;
3615
3617 myexponent = exponent + bias;
3618 std::copy_n(significandParts(), mysignificand.size(),
3619 mysignificand.begin());
3620 if (myexponent == 1 &&
3621 !(significandParts()[integer_bit_part] & integer_bit))
3622 myexponent = 0;
3623 } else if (category == fcZero) {
3624 if (!S.hasZero)
3626 myexponent = ::exponentZero(S) + bias;
3627 mysignificand.fill(0);
3628 } else if (category == fcInfinity) {
3632 myexponent = ::exponentInf(S) + bias;
3633 mysignificand.fill(0);
3634 } else {
3635 assert(category == fcNaN && "Unknown category!");
3638 myexponent = ::exponentNaN(S) + bias;
3639 std::copy_n(significandParts(), mysignificand.size(),
3640 mysignificand.begin());
3641 }
3642 std::array<uint64_t, (S.sizeInBits + 63) / 64> words;
3643 auto words_iter =
3644 std::copy_n(mysignificand.begin(), mysignificand.size(), words.begin());
3645 if constexpr (significand_mask != 0 || trailing_significand_bits == 0) {
3646
3647 words[mysignificand.size() - 1] &= significand_mask;
3648 }
3649 std::fill(words_iter, words.end(), uint64_t{0});
3650 constexpr size_t last_word = words.size() - 1;
3652 << ((S.sizeInBits - 1) % 64);
3653 words[last_word] |= shifted_sign;
3654 uint64_t shifted_exponent = (myexponent & exponent_mask)
3655 << (trailing_significand_bits % 64);
3656 words[last_word] |= shifted_exponent;
3657 if constexpr (last_word == 0) {
3658 return APInt(S.sizeInBits, words[0]);
3659 }
3660 return APInt(S.sizeInBits, words);
3661}
3662
3663APInt IEEEFloat::convertQuadrupleAPFloatToAPInt() const {
3664 assert(partCount() == 2);
3665 return convertIEEEFloatToAPInt();
3666}
3667
3668APInt IEEEFloat::convertDoubleAPFloatToAPInt() const {
3669 assert(partCount()==1);
3670 return convertIEEEFloatToAPInt();
3671}
3672
3673APInt IEEEFloat::convertFloatAPFloatToAPInt() const {
3674 assert(partCount()==1);
3675 return convertIEEEFloatToAPInt();
3676}
3677
3678APInt IEEEFloat::convertBFloatAPFloatToAPInt() const {
3679 assert(partCount() == 1);
3680 return convertIEEEFloatToAPInt();
3681}
3682
3683APInt IEEEFloat::convertHalfAPFloatToAPInt() const {
3684 assert(partCount()==1);
3685 return convertIEEEFloatToAPInt();
3686}
3687
3688APInt IEEEFloat::convertFloat8E5M2APFloatToAPInt() const {
3689 assert(partCount() == 1);
3690 return convertIEEEFloatToAPInt();
3691}
3692
3693APInt IEEEFloat::convertFloat8E5M2FNUZAPFloatToAPInt() const {
3694 assert(partCount() == 1);
3695 return convertIEEEFloatToAPInt();
3696}
3697
3698APInt IEEEFloat::convertFloat8E4M3APFloatToAPInt() const {
3699 assert(partCount() == 1);
3700 return convertIEEEFloatToAPInt();
3701}
3702
3703APInt IEEEFloat::convertFloat8E4M3FNAPFloatToAPInt() const {
3704 assert(partCount() == 1);
3705 return convertIEEEFloatToAPInt();
3706}
3707
3708APInt IEEEFloat::convertFloat8E4M3FNUZAPFloatToAPInt() const {
3709 assert(partCount() == 1);
3710 return convertIEEEFloatToAPInt();
3711}
3712
3713APInt IEEEFloat::convertFloat8E4M3B11FNUZAPFloatToAPInt() const {
3714 assert(partCount() == 1);
3715 return convertIEEEFloatToAPInt();
3716}
3717
3718APInt IEEEFloat::convertFloat8E3M4APFloatToAPInt() const {
3719 assert(partCount() == 1);
3720 return convertIEEEFloatToAPInt();
3721}
3722
3723APInt IEEEFloat::convertFloatTF32APFloatToAPInt() const {
3724 assert(partCount() == 1);
3725 return convertIEEEFloatToAPInt();
3726}
3727
3728APInt IEEEFloat::convertFloat8E8M0FNUAPFloatToAPInt() const {
3729 assert(partCount() == 1);
3730 return convertIEEEFloatToAPInt();
3731}
3732
3733APInt IEEEFloat::convertFloat6E3M2FNAPFloatToAPInt() const {
3734 assert(partCount() == 1);
3735 return convertIEEEFloatToAPInt();
3736}
3737
3738APInt IEEEFloat::convertFloat6E2M3FNAPFloatToAPInt() const {
3739 assert(partCount() == 1);
3740 return convertIEEEFloatToAPInt();
3741}
3742
3743APInt IEEEFloat::convertFloat4E2M1FNAPFloatToAPInt() const {
3744 assert(partCount() == 1);
3745 return convertIEEEFloatToAPInt();
3746}
3747
3748
3749
3750
3751
3754 return convertHalfAPFloatToAPInt();
3755
3757 return convertBFloatAPFloatToAPInt();
3758
3760 return convertFloatAPFloatToAPInt();
3761
3763 return convertDoubleAPFloatToAPInt();
3764
3766 return convertQuadrupleAPFloatToAPInt();
3767
3769 return convertPPCDoubleDoubleLegacyAPFloatToAPInt();
3770
3772 return convertFloat8E5M2APFloatToAPInt();
3773
3775 return convertFloat8E5M2FNUZAPFloatToAPInt();
3776
3778 return convertFloat8E4M3APFloatToAPInt();
3779
3781 return convertFloat8E4M3FNAPFloatToAPInt();
3782
3784 return convertFloat8E4M3FNUZAPFloatToAPInt();
3785
3787 return convertFloat8E4M3B11FNUZAPFloatToAPInt();
3788
3790 return convertFloat8E3M4APFloatToAPInt();
3791
3793 return convertFloatTF32APFloatToAPInt();
3794
3796 return convertFloat8E8M0FNUAPFloatToAPInt();
3797
3799 return convertFloat6E3M2FNAPFloatToAPInt();
3800
3802 return convertFloat6E2M3FNAPFloatToAPInt();
3803
3805 return convertFloat4E2M1FNAPFloatToAPInt();
3806
3808 "unknown format!");
3809 return convertF80LongDoubleAPFloatToAPInt();
3810}
3811
3814 "Float semantics are not IEEEsingle");
3817}
3818
3821 "Float semantics are not IEEEdouble");
3824}
3825
3826#ifdef HAS_IEE754_FLOAT128
3827float128 IEEEFloat::convertToQuad() const {
3829 "Float semantics are not IEEEquads");
3831 return api.bitsToQuad();
3832}
3833#endif
3834
3835
3836
3837
3838
3839
3840
3841
3842void IEEEFloat::initFromF80LongDoubleAPInt(const APInt &api) {
3845 uint64_t myexponent = (i2 & 0x7fff);
3846 uint64_t mysignificand = i1;
3847 uint8_t myintegerbit = mysignificand >> 63;
3848
3850 assert(partCount()==2);
3851
3852 sign = static_cast<unsigned int>(i2>>15);
3853 if (myexponent == 0 && mysignificand == 0) {
3855 } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
3857 } else if ((myexponent == 0x7fff && mysignificand != 0x8000000000000000ULL) ||
3858 (myexponent != 0x7fff && myexponent != 0 && myintegerbit == 0)) {
3859 category = fcNaN;
3860 exponent = exponentNaN();
3861 significandParts()[0] = mysignificand;
3862 significandParts()[1] = 0;
3863 } else {
3865 exponent = myexponent - 16383;
3866 significandParts()[0] = mysignificand;
3867 significandParts()[1] = 0;
3868 if (myexponent==0)
3869 exponent = -16382;
3870 }
3871}
3872
3873void IEEEFloat::initFromPPCDoubleDoubleLegacyAPInt(const APInt &api) {
3877 bool losesInfo;
3878
3879
3880 initFromDoubleAPInt(APInt(64, i1));
3883 (void)fs;
3884
3885
3890 (void)fs;
3891
3893 }
3894}
3895
3896
3897
3898
3899
3900
3901void IEEEFloat::initFromFloat8E8M0FNUAPInt(const APInt &api) {
3902 const uint64_t exponent_mask = 0xff;
3904 uint64_t myexponent = (val & exponent_mask);
3905
3907 assert(partCount() == 1);
3908
3909
3910 sign = 0;
3911
3912
3913
3914
3916 significandParts()[0] = mysignificand;
3917
3918
3919
3920 if (val == exponent_mask) {
3921 category = fcNaN;
3922 exponent = exponentNaN();
3923 return;
3924 }
3925
3927 exponent = myexponent - 127;
3928}
3929template <const fltSemantics &S>
3930void IEEEFloat::initFromIEEEAPInt(const APInt &api) {
3934 constexpr uint64_t significand_mask = integer_bit - 1;
3935 constexpr unsigned int trailing_significand_bits = S.precision - 1;
3936 constexpr unsigned int stored_significand_parts =
3938 constexpr unsigned int exponent_bits =
3939 S.sizeInBits - 1 - trailing_significand_bits;
3940 static_assert(exponent_bits < 64);
3941 constexpr uint64_t exponent_mask = (uint64_t{1} << exponent_bits) - 1;
3942 constexpr int bias = -(S.minExponent - 1);
3943
3944
3945
3946 std::array<integerPart, stored_significand_parts> mysignificand;
3947 std::copy_n(api.getRawData(), mysignificand.size(), mysignificand.begin());
3948 if constexpr (significand_mask != 0) {
3949 mysignificand[mysignificand.size() - 1] &= significand_mask;
3950 }
3951
3952
3953
3956 (last_word >> (trailing_significand_bits % 64)) & exponent_mask;
3957
3958 initialize(&S);
3959 assert(partCount() == mysignificand.size());
3960
3961 sign = static_cast<unsigned int>(last_word >> ((S.sizeInBits - 1) % 64));
3962
3963 bool all_zero_significand =
3965
3966 bool is_zero = myexponent == 0 && all_zero_significand;
3967
3969 if (myexponent - bias == ::exponentInf(S) && all_zero_significand) {
3971 return;
3972 }
3973 }
3974
3975 bool is_nan = false;
3976
3978 is_nan = myexponent - bias == ::exponentNaN(S) && !all_zero_significand;
3980 bool all_ones_significand =
3981 std::all_of(mysignificand.begin(), mysignificand.end() - 1,
3982 [](integerPart bits) { return bits == ~integerPart{0}; }) &&
3983 (!significand_mask ||
3984 mysignificand[mysignificand.size() - 1] == significand_mask);
3985 is_nan = myexponent - bias == ::exponentNaN(S) && all_ones_significand;
3988 }
3989
3991 category = fcNaN;
3993 std::copy_n(mysignificand.begin(), mysignificand.size(),
3994 significandParts());
3995 return;
3996 }
3997
3999 makeZero(sign);
4000 return;
4001 }
4002
4004 exponent = myexponent - bias;
4005 std::copy_n(mysignificand.begin(), mysignificand.size(), significandParts());
4006 if (myexponent == 0)
4007 exponent = S.minExponent;
4008 else
4009 significandParts()[mysignificand.size()-1] |= integer_bit;
4010}
4011
4012void IEEEFloat::initFromQuadrupleAPInt(const APInt &api) {
4013 initFromIEEEAPInt(api);
4014}
4015
4016void IEEEFloat::initFromDoubleAPInt(const APInt &api) {
4017 initFromIEEEAPInt(api);
4018}
4019
4020void IEEEFloat::initFromFloatAPInt(const APInt &api) {
4021 initFromIEEEAPInt(api);
4022}
4023
4024void IEEEFloat::initFromBFloatAPInt(const APInt &api) {
4025 initFromIEEEAPInt(api);
4026}
4027
4028void IEEEFloat::initFromHalfAPInt(const APInt &api) {
4029 initFromIEEEAPInt(api);
4030}
4031
4032void IEEEFloat::initFromFloat8E5M2APInt(const APInt &api) {
4033 initFromIEEEAPInt(api);
4034}
4035
4036void IEEEFloat::initFromFloat8E5M2FNUZAPInt(const APInt &api) {
4037 initFromIEEEAPInt(api);
4038}
4039
4040void IEEEFloat::initFromFloat8E4M3APInt(const APInt &api) {
4041 initFromIEEEAPInt(api);
4042}
4043
4044void IEEEFloat::initFromFloat8E4M3FNAPInt(const APInt &api) {
4045 initFromIEEEAPInt(api);
4046}
4047
4048void IEEEFloat::initFromFloat8E4M3FNUZAPInt(const APInt &api) {
4049 initFromIEEEAPInt(api);
4050}
4051
4052void IEEEFloat::initFromFloat8E4M3B11FNUZAPInt(const APInt &api) {
4053 initFromIEEEAPInt(api);
4054}
4055
4056void IEEEFloat::initFromFloat8E3M4APInt(const APInt &api) {
4057 initFromIEEEAPInt(api);
4058}
4059
4060void IEEEFloat::initFromFloatTF32APInt(const APInt &api) {
4061 initFromIEEEAPInt(api);
4062}
4063
4064void IEEEFloat::initFromFloat6E3M2FNAPInt(const APInt &api) {
4065 initFromIEEEAPInt(api);
4066}
4067
4068void IEEEFloat::initFromFloat6E2M3FNAPInt(const APInt &api) {
4069 initFromIEEEAPInt(api);
4070}
4071
4072void IEEEFloat::initFromFloat4E2M1FNAPInt(const APInt &api) {
4073 initFromIEEEAPInt(api);
4074}
4075
4076
4077void IEEEFloat::initFromAPInt(const fltSemantics *Sem, const APInt &api) {
4080 return initFromHalfAPInt(api);
4082 return initFromBFloatAPInt(api);
4084 return initFromFloatAPInt(api);
4086 return initFromDoubleAPInt(api);
4088 return initFromF80LongDoubleAPInt(api);
4090 return initFromQuadrupleAPInt(api);
4092 return initFromPPCDoubleDoubleLegacyAPInt(api);
4094 return initFromFloat8E5M2APInt(api);
4096 return initFromFloat8E5M2FNUZAPInt(api);
4098 return initFromFloat8E4M3APInt(api);
4100 return initFromFloat8E4M3FNAPInt(api);
4102 return initFromFloat8E4M3FNUZAPInt(api);
4104 return initFromFloat8E4M3B11FNUZAPInt(api);
4106 return initFromFloat8E3M4APInt(api);
4108 return initFromFloatTF32APInt(api);
4110 return initFromFloat8E8M0FNUAPInt(api);
4112 return initFromFloat6E3M2FNAPInt(api);
4114 return initFromFloat6E2M3FNAPInt(api);
4116 return initFromFloat4E2M1FNAPInt(api);
4117
4119}
4120
4121
4122
4123void IEEEFloat::makeLargest(bool Negative) {
4124 if (Negative && !semantics->hasSignedRepr)
4126 "This floating point format does not support signed values");
4127
4128
4129
4130
4132 sign = Negative;
4133 exponent = semantics->maxExponent;
4134
4135
4136 integerPart *significand = significandParts();
4137 unsigned PartCount = partCount();
4138 memset(significand, 0xFF, sizeof(integerPart)*(PartCount - 1));
4139
4140
4141
4142 const unsigned NumUnusedHighBits =
4143 PartCount*integerPartWidth - semantics->precision;
4144 significand[PartCount - 1] = (NumUnusedHighBits < integerPartWidth)
4145 ? (~integerPart(0) >> NumUnusedHighBits)
4146 : 0;
4149 (semantics->precision > 1))
4151}
4152
4153
4154
4155void IEEEFloat::makeSmallest(bool Negative) {
4156 if (Negative && !semantics->hasSignedRepr)
4158 "This floating point format does not support signed values");
4159
4160
4161
4162
4164 sign = Negative;
4165 exponent = semantics->minExponent;
4166 APInt::tcSet(significandParts(), 1, partCount());
4167}
4168
4169void IEEEFloat::makeSmallestNormalized(bool Negative) {
4170 if (Negative && !semantics->hasSignedRepr)
4172 "This floating point format does not support signed values");
4173
4174
4175
4176
4177
4179 zeroSignificand();
4180 sign = Negative;
4181 exponent = semantics->minExponent;
4182 APInt::tcSetBit(significandParts(), semantics->precision - 1);
4183}
4184
4186 initFromAPInt(&Sem, API);
4187}
4188
4189IEEEFloat::IEEEFloat(float f) {
4191}
4192
4193IEEEFloat::IEEEFloat(double d) {
4195}
4196
4197namespace {
4199 Buffer.append(Str.begin(), Str.end());
4200 }
4201
4202
4203
4204 void AdjustToPrecision(APInt &significand,
4205 int &exp, unsigned FormatPrecision) {
4207
4208
4209 unsigned bitsRequired = (FormatPrecision * 196 + 58) / 59;
4210
4211 if (bits <= bitsRequired) return;
4212
4213 unsigned tensRemovable = (bits - bitsRequired) * 59 / 196;
4214 if (!tensRemovable) return;
4215
4216 exp += tensRemovable;
4217
4220 while (true) {
4221 if (tensRemovable & 1)
4222 divisor *= powten;
4223 tensRemovable >>= 1;
4224 if (!tensRemovable) break;
4225 powten *= powten;
4226 }
4227
4228 significand = significand.udiv(divisor);
4229
4230
4232 }
4233
4234
4236 int &exp, unsigned FormatPrecision) {
4237 unsigned N = buffer.size();
4238 if (N <= FormatPrecision) return;
4239
4240
4241 unsigned FirstSignificant = N - FormatPrecision;
4242
4243
4244
4245
4246
4247
4248 if (buffer[FirstSignificant - 1] < '5') {
4249 while (FirstSignificant < N && buffer[FirstSignificant] == '0')
4250 FirstSignificant++;
4251
4252 exp += FirstSignificant;
4253 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
4254 return;
4255 }
4256
4257
4258
4259 for (unsigned I = FirstSignificant; I != N; ++I) {
4260 if (buffer[I] == '9') {
4261 FirstSignificant++;
4262 } else {
4263 buffer[I]++;
4264 break;
4265 }
4266 }
4267
4268
4269 if (FirstSignificant == N) {
4270 exp += FirstSignificant;
4273 return;
4274 }
4275
4276 exp += FirstSignificant;
4277 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
4278 }
4279
4281 APInt significand, unsigned FormatPrecision,
4282 unsigned FormatMaxPadding, bool TruncateZero) {
4283 const int semanticsPrecision = significand.getBitWidth();
4284
4286 Str.push_back('-');
4287
4288
4289
4290 if (!FormatPrecision) {
4291
4292
4293
4294
4295
4296
4297
4298 FormatPrecision = 2 + semanticsPrecision * 59 / 196;
4299 }
4300
4301
4302 int trailingZeros = significand.countr_zero();
4303 exp += trailingZeros;
4305
4306
4307 if (exp == 0) {
4308
4309 } else if (exp > 0) {
4310
4311 significand = significand.zext(semanticsPrecision + exp);
4312 significand <<= exp;
4313 exp = 0;
4314 } else {
4315 int texp = -exp;
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326 unsigned precision = semanticsPrecision + (137 * texp + 136) / 59;
4327
4328
4329
4330 significand = significand.zext(precision);
4331 APInt five_to_the_i(precision, 5);
4332 while (true) {
4333 if (texp & 1)
4334 significand *= five_to_the_i;
4335
4336 texp >>= 1;
4337 if (!texp)
4338 break;
4339 five_to_the_i *= five_to_the_i;
4340 }
4341 }
4342
4343 AdjustToPrecision(significand, exp, FormatPrecision);
4344
4346
4347
4348 unsigned precision = significand.getBitWidth();
4349 if (precision < 4) {
4350
4351 precision = 4;
4352 significand = significand.zext(precision);
4353 }
4354 APInt ten(precision, 10);
4355 APInt digit(precision, 0);
4356
4357 bool inTrail = true;
4358 while (significand != 0) {
4359
4360
4361 APInt::udivrem(significand, ten, significand, digit);
4362
4363 unsigned d = digit.getZExtValue();
4364
4365
4366 if (inTrail && !d)
4367 exp++;
4368 else {
4369 buffer.push_back((char) ('0' + d));
4370 inTrail = false;
4371 }
4372 }
4373
4374 assert(!buffer.empty() && "no characters in buffer!");
4375
4376
4377
4378 AdjustToPrecision(buffer, exp, FormatPrecision);
4379
4380 unsigned NDigits = buffer.size();
4381
4382
4383 bool FormatScientific;
4384 if (!FormatMaxPadding)
4385 FormatScientific = true;
4386 else {
4387 if (exp >= 0) {
4388
4389
4390
4391 FormatScientific = ((unsigned) exp > FormatMaxPadding ||
4392 NDigits + (unsigned) exp > FormatPrecision);
4393 } else {
4394
4395 int MSD = exp + (int) (NDigits - 1);
4396 if (MSD >= 0) {
4397
4398 FormatScientific = false;
4399 } else {
4400
4401
4402 FormatScientific = ((unsigned) -MSD) > FormatMaxPadding;
4403 }
4404 }
4405 }
4406
4407
4408 if (FormatScientific) {
4409 exp += (NDigits - 1);
4410
4411 Str.push_back(buffer[NDigits-1]);
4412 Str.push_back('.');
4413 if (NDigits == 1 && TruncateZero)
4414 Str.push_back('0');
4415 else
4416 for (unsigned I = 1; I != NDigits; ++I)
4417 Str.push_back(buffer[NDigits-1-I]);
4418
4419 if (!TruncateZero && FormatPrecision > NDigits - 1)
4420 Str.append(FormatPrecision - NDigits + 1, '0');
4421
4422 Str.push_back(TruncateZero ? 'E' : 'e');
4423
4424 Str.push_back(exp >= 0 ? '+' : '-');
4425 if (exp < 0)
4426 exp = -exp;
4428 do {
4429 expbuf.push_back((char) ('0' + (exp % 10)));
4430 exp /= 10;
4431 } while (exp);
4432
4433 if (!TruncateZero && expbuf.size() < 2)
4435 for (unsigned I = 0, E = expbuf.size(); I != E; ++I)
4436 Str.push_back(expbuf[E-1-I]);
4437 return;
4438 }
4439
4440
4441 if (exp >= 0) {
4442 for (unsigned I = 0; I != NDigits; ++I)
4443 Str.push_back(buffer[NDigits-1-I]);
4444 for (unsigned I = 0; I != (unsigned) exp; ++I)
4445 Str.push_back('0');
4446 return;
4447 }
4448
4449
4450
4451
4452 int NWholeDigits = exp + (int) NDigits;
4453
4454 unsigned I = 0;
4455 if (NWholeDigits > 0) {
4456 for (; I != (unsigned) NWholeDigits; ++I)
4457 Str.push_back(buffer[NDigits-I-1]);
4458 Str.push_back('.');
4459 } else {
4460 unsigned NZeros = 1 + (unsigned) -NWholeDigits;
4461
4462 Str.push_back('0');
4463 Str.push_back('.');
4464 for (unsigned Z = 1; Z != NZeros; ++Z)
4465 Str.push_back('0');
4466 }
4467
4468 for (; I != NDigits; ++I)
4469 Str.push_back(buffer[NDigits-I-1]);
4470
4471 }
4472}
4473
4475 unsigned FormatMaxPadding, bool TruncateZero) const {
4476 switch (category) {
4477 case fcInfinity:
4478 if (isNegative())
4479 return append(Str, "-Inf");
4480 else
4481 return append(Str, "+Inf");
4482
4483 case fcNaN: return append(Str, "NaN");
4484
4486 if (isNegative())
4487 Str.push_back('-');
4488
4489 if (!FormatMaxPadding) {
4490 if (TruncateZero)
4491 append(Str, "0.0E+0");
4492 else {
4493 append(Str, "0.0");
4494 if (FormatPrecision > 1)
4495 Str.append(FormatPrecision - 1, '0');
4496 append(Str, "e+00");
4497 }
4498 } else
4499 Str.push_back('0');
4500 return;
4501
4503 break;
4504 }
4505
4506
4507 int exp = exponent - ((int) semantics->precision - 1);
4508 APInt significand(
4509 semantics->precision,
4511
4512 toStringImpl(Str, isNegative(), exp, significand, FormatPrecision,
4513 FormatMaxPadding, TruncateZero);
4514
4515}
4516
4517bool IEEEFloat::getExactInverse(APFloat *inv) const {
4518
4519 if (!isFiniteNonZero())
4520 return false;
4521
4522
4523
4524 if (significandLSB() != semantics->precision - 1)
4525 return false;
4526
4527
4528 IEEEFloat reciprocal(*semantics, 1ULL);
4529 if (reciprocal.divide(*this, rmNearestTiesToEven) != opOK)
4530 return false;
4531
4532
4533
4535 return false;
4536
4538 reciprocal.significandLSB() == reciprocal.semantics->precision - 1);
4539
4540 if (inv)
4541 *inv = APFloat(reciprocal, *semantics);
4542
4543 return true;
4544}
4545
4546int IEEEFloat::getExactLog2Abs() const {
4548 return INT_MIN;
4549
4550 const integerPart *Parts = significandParts();
4551 const int PartCount = partCountForBits(semantics->precision);
4552
4553 int PopCount = 0;
4554 for (int i = 0; i < PartCount; ++i) {
4556 if (PopCount > 1)
4557 return INT_MIN;
4558 }
4559
4560 if (exponent != semantics->minExponent)
4561 return exponent;
4562
4563 int CountrParts = 0;
4564 for (int i = 0; i < PartCount;
4566 if (Parts[i] != 0) {
4567 return exponent - semantics->precision + CountrParts +
4569 }
4570 }
4571
4573}
4574
4575bool IEEEFloat::isSignaling() const {
4576 if (!isNaN())
4577 return false;
4580 return false;
4581
4582
4583
4584 return (significandParts(), semantics->precision - 2);
4585}
4586
4587
4588
4589
4590
4592
4593 if (nextDown)
4594 changeSign();
4595
4596
4598
4599
4600 switch (category) {
4601 case fcInfinity:
4602
4603 if (!isNegative())
4604 break;
4605
4606 makeLargest(true);
4607 break;
4608 case fcNaN:
4609
4610
4611
4612 if (isSignaling()) {
4613 result = opInvalidOp;
4614
4615 makeNaN(false, isNegative(), nullptr);
4616 }
4617 break;
4619
4620 makeSmallest(false);
4621 break;
4623
4624 if (isSmallest() && isNegative()) {
4625 APInt::tcSet(significandParts(), 0, partCount());
4627 exponent = 0;
4629 sign = false;
4630 if (!semantics->hasZero)
4631 makeSmallestNormalized(false);
4632 break;
4633 }
4634
4635 if (isLargest() && !isNegative()) {
4637
4638 makeNaN();
4639 break;
4640 } else if (semantics->nonFiniteBehavior ==
4642
4643 break;
4644 } else {
4645
4646 APInt::tcSet(significandParts(), 0, partCount());
4647 category = fcInfinity;
4648 exponent = semantics->maxExponent + 1;
4649 break;
4650 }
4651 }
4652
4653
4654 if (isNegative()) {
4655
4656
4657
4658
4659
4660
4661
4662 bool WillCrossBinadeBoundary =
4663 exponent != semantics->minExponent && isSignificandAllZeros();
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678 integerPart *Parts = significandParts();
4680
4681 if (WillCrossBinadeBoundary) {
4682
4683
4684
4686 exponent--;
4687 }
4688 } else {
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4700 (!isDenormal() && isSignificandAllOnes());
4701
4702 if (WillCrossBinadeBoundary) {
4703 integerPart *Parts = significandParts();
4706 assert(exponent != semantics->maxExponent &&
4707 "We can not increment an exponent beyond the maxExponent allowed"
4708 " by the given floating point semantics.");
4709 exponent++;
4710 } else {
4711 incrementSignificand();
4712 }
4713 }
4714 break;
4715 }
4716
4717
4718 if (nextDown)
4719 changeSign();
4720
4721 return result;
4722}
4723
4725 return ::exponentNaN(*semantics);
4726}
4727
4729 return ::exponentInf(*semantics);
4730}
4731
4733 return ::exponentZero(*semantics);
4734}
4735
4736void IEEEFloat::makeInf(bool Negative) {
4738 llvm_unreachable("This floating point format does not support Inf");
4739
4741
4742 makeNaN(false, Negative);
4743 return;
4744 }
4745 category = fcInfinity;
4746 sign = Negative;
4748 APInt::tcSet(significandParts(), 0, partCount());
4749}
4750
4751void IEEEFloat::makeZero(bool Negative) {
4752 if (!semantics->hasZero)
4753 llvm_unreachable("This floating point format does not support Zero");
4754
4756 sign = Negative;
4758
4759 sign = false;
4760 }
4762 APInt::tcSet(significandParts(), 0, partCount());
4763}
4764
4765void IEEEFloat::makeQuiet() {
4768 APInt::tcSetBit(significandParts(), semantics->precision - 2);
4769}
4770
4772 if (Arg.isNaN())
4779 return Arg.exponent;
4780
4783
4784 Normalized.exponent += SignificandBits;
4786 return Normalized.exponent - SignificandBits;
4787}
4788
4790 auto MaxExp = X.getSemantics().maxExponent;
4791 auto MinExp = X.getSemantics().minExponent;
4792
4793
4794
4795
4796
4797
4798
4799 int SignificandBits = X.getSemantics().precision - 1;
4800 int MaxIncrement = MaxExp - (MinExp - SignificandBits) + 1;
4801
4802
4803 X.exponent += std::clamp(Exp, -MaxIncrement - 1, MaxIncrement);
4805 if (X.isNaN())
4806 X.makeQuiet();
4807 return X;
4808}
4809
4811 Exp = ilogb(Val);
4812
4813
4816 Quiet.makeQuiet();
4818 }
4819
4821 return Val;
4822
4823
4824
4826 return scalbn(Val, -Exp, RM);
4827}
4828
4830 : Semantics(&S),
4833}
4834
4836 : Semantics(&S),
4840}
4841
4846}
4847
4849 : Semantics(&S),
4854}
4855
4858 : Semantics(&S),
4859 Floats(new APFloat[2]{std::move(First), std::move(Second)}) {
4863}
4864
4866 : Semantics(RHS.Semantics),
4869 : nullptr) {
4871}
4872
4874 : Semantics(RHS.Semantics), Floats(std::move(RHS.Floats)) {
4877}
4878
4880 if (Semantics == RHS.Semantics && RHS.Floats) {
4881 Floats[0] = RHS.Floats[0];
4882 Floats[1] = RHS.Floats[1];
4883 } else if (this != &RHS) {
4886 }
4887 return *this;
4888}
4889
4890
4891
4892
4901 Floats[0] = std::move(z);
4902 Floats[1].makeZero( false);
4904 }
4906 auto AComparedToC = a.compareAbsoluteValue(c);
4907 z = cc;
4910
4913 } else {
4914
4917 }
4919 Floats[0] = std::move(z);
4920 Floats[1].makeZero( false);
4922 }
4923 Floats[0] = z;
4927
4928 Floats[1] = a;
4929 Status |= Floats[1].subtract(z, RM);
4930 Status |= Floats[1].add(c, RM);
4931 Status |= Floats[1].add(zz, RM);
4932 } else {
4933
4934 Floats[1] = c;
4935 Status |= Floats[1].subtract(z, RM);
4936 Status |= Floats[1].add(a, RM);
4937 Status |= Floats[1].add(zz, RM);
4938 }
4939 } else {
4940
4942 Status |= q.subtract(z, RM);
4943
4944
4945
4946 auto zz = q;
4949 Status |= q.subtract(a, RM);
4950 q.changeSign();
4955 Floats[0] = std::move(z);
4956 Floats[1].makeZero( false);
4957 return opOK;
4958 }
4959 Floats[0] = z;
4960 Status |= Floats[0].add(zz, RM);
4961 if (!Floats[0].isFinite()) {
4962 Floats[1].makeZero( false);
4964 }
4965 Floats[1] = std::move(z);
4966 Status |= Floats[1].subtract(Floats[0], RM);
4967 Status |= Floats[1].add(zz, RM);
4968 }
4970}
4971
4972APFloat::opStatus DoubleAPFloat::addWithSpecial(const DoubleAPFloat &LHS,
4973 const DoubleAPFloat &RHS,
4974 DoubleAPFloat &Out,
4976 if (LHS.getCategory() == fcNaN) {
4977 Out = LHS;
4978 return opOK;
4979 }
4980 if (RHS.getCategory() == fcNaN) {
4981 Out = RHS;
4982 return opOK;
4983 }
4984 if (LHS.getCategory() == fcZero) {
4985 Out = RHS;
4986 return opOK;
4987 }
4988 if (RHS.getCategory() == fcZero) {
4989 Out = LHS;
4990 return opOK;
4991 }
4993 LHS.isNegative() != RHS.isNegative()) {
4994 Out.makeNaN(false, Out.isNegative(), nullptr);
4996 }
4998 Out = LHS;
4999 return opOK;
5000 }
5002 Out = RHS;
5003 return opOK;
5004 }
5006
5015 return Out.addImpl(A, AA, C, CC, RM);
5016}
5017
5020 return addWithSpecial(*this, RHS, *this, RM);
5021}
5022
5028 return Ret;
5029}
5030
5033 const auto &LHS = *this;
5034 auto &Out = *this;
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050 if (LHS.getCategory() == fcNaN) {
5051 Out = LHS;
5052 return opOK;
5053 }
5054 if (RHS.getCategory() == fcNaN) {
5055 Out = RHS;
5056 return opOK;
5057 }
5060 Out.makeNaN(false, false, nullptr);
5061 return opOK;
5062 }
5064 Out = LHS;
5065 return opOK;
5066 }
5068 Out = RHS;
5069 return opOK;
5070 }
5072 "Special cases not handled exhaustively");
5073
5075 APFloat A = Floats[0], B = Floats[1], C = RHS.Floats[0], D = RHS.Floats[1];
5076
5078 Status |= T.multiply(C, RM);
5079 if (.isFiniteNonZero()) {
5080 Floats[0] = T;
5081 Floats[1].makeZero( false);
5083 }
5084
5085
5087 T.changeSign();
5089 T.changeSign();
5090 {
5091
5093 Status |= V.multiply(D, RM);
5094
5096 Status |= W.multiply(C, RM);
5097 Status |= V.add(W, RM);
5098
5100 }
5101
5103 Status |= U.add(Tau, RM);
5104
5105 Floats[0] = U;
5106 if (!U.isFinite()) {
5107 Floats[1].makeZero( false);
5108 } else {
5109
5110 Status |= T.subtract(U, RM);
5111 Status |= T.add(Tau, RM);
5112 Floats[1] = T;
5113 }
5115}
5116
5121 auto Ret =
5124 return Ret;
5125}
5126
5130 auto Ret =
5133 return Ret;
5134}
5135
5141 return Ret;
5142}
5143
5154 return Ret;
5155}
5156
5162 return Ret;
5163}
5164
5166 Floats[0].changeSign();
5167 Floats[1].changeSign();
5168}
5169
5172 auto Result = Floats[0].compareAbsoluteValue(RHS.Floats[0]);
5174 return Result;
5175 Result = Floats[1].compareAbsoluteValue(RHS.Floats[1]);
5177 auto Against = Floats[0].isNegative() ^ Floats[1].isNegative();
5178 auto RHSAgainst = RHS.Floats[0].isNegative() ^ RHS.Floats[1].isNegative();
5179 if (Against && !RHSAgainst)
5181 if (!Against && RHSAgainst)
5183 if (!Against && !RHSAgainst)
5184 return Result;
5185 if (Against && RHSAgainst)
5187 }
5188 return Result;
5189}
5190
5192 return Floats[0].getCategory();
5193}
5194
5196
5198 Floats[0].makeInf(Neg);
5199 Floats[1].makeZero( false);
5200}
5201
5203 Floats[0].makeZero(Neg);
5204 Floats[1].makeZero( false);
5205}
5206
5211 if (Neg)
5213}
5214
5217 Floats[0].makeSmallest(Neg);
5218 Floats[1].makeZero( false);
5219}
5220
5224 if (Neg)
5225 Floats[0].changeSign();
5226 Floats[1].makeZero( false);
5227}
5228
5230 Floats[0].makeNaN(SNaN, Neg, fill);
5231 Floats[1].makeZero( false);
5232}
5233
5235 auto Result = Floats[0].compare(RHS.Floats[0]);
5236
5238 return Floats[1].compare(RHS.Floats[1]);
5239 return Result;
5240}
5241
5243 return Floats[0].bitwiseIsEqual(RHS.Floats[0]) &&
5244 Floats[1].bitwiseIsEqual(RHS.Floats[1]);
5245}
5246
5248 if (Arg.Floats)
5251}
5252
5256 Floats[0].bitcastToAPInt().getRawData()[0],
5257 Floats[1].bitcastToAPInt().getRawData()[0],
5258 };
5260}
5261
5268 return Ret;
5269}
5270
5274 auto Ret = Tmp.next(nextDown);
5276 return Ret;
5277}
5278
5281 unsigned int Width, bool IsSigned,
5286}
5287
5289 bool IsSigned,
5295 return Ret;
5296}
5297
5300 unsigned int InputSize,
5306 return Ret;
5307}
5308
5311 unsigned int InputSize,
5317 return Ret;
5318}
5319
5321 unsigned int HexDigits,
5322 bool UpperCase,
5327}
5328
5331 (Floats[0].isDenormal() || Floats[1].isDenormal() ||
5332
5333 Floats[0] != Floats[0] + Floats[1]);
5334}
5335
5338 return false;
5342}
5343
5346 return false;
5347
5351}
5352
5355 return false;
5359}
5360
5363 return Floats[0].isInteger() && Floats[1].isInteger();
5364}
5365
5367 unsigned FormatPrecision,
5368 unsigned FormatMaxPadding,
5369 bool TruncateZero) const {
5372 .toString(Str, FormatPrecision, FormatMaxPadding, TruncateZero);
5373}
5374
5378 if (!inv)
5383 return Ret;
5384}
5385
5387
5388 return INT_MIN;
5389}
5390
5392
5393 return INT_MIN;
5394}
5395
5400 scalbn(Arg.Floats[1], Exp, RM));
5401}
5402
5407 APFloat Second = Arg.Floats[1];
5409 Second = scalbn(Second, -Exp, RM);
5411}
5412
5413}
5414
5415APFloat::Storage::Storage(IEEEFloat F, const fltSemantics &Semantics) {
5416 if (usesLayout(Semantics)) {
5417 new (&IEEE) IEEEFloat(std::move(F));
5418 return;
5419 }
5420 if (usesLayout(Semantics)) {
5423 DoubleAPFloat(Semantics, APFloat(std::move(F), S),
5425 return;
5426 }
5428}
5429
5433}
5434
5436 if (APFloat::usesLayoutdetail::IEEEFloat(Arg.getSemantics()))
5438 if (APFloat::usesLayoutdetail::DoubleAPFloat(Arg.getSemantics()))
5441}
5442
5446 assert(StatusOrErr && "Invalid floating point representation");
5448}
5449
5459 assert(isNaN() && "Other class of FP constant");
5461}
5462
5466 *losesInfo = false;
5467 return opOK;
5468 }
5469 if (usesLayout(getSemantics()) &&
5470 usesLayout(ToSemantics))
5471 return U.IEEE.convert(ToSemantics, RM, losesInfo);
5472 if (usesLayout(getSemantics()) &&
5473 usesLayout(ToSemantics)) {
5476 *this = APFloat(ToSemantics, U.IEEE.bitcastToAPInt());
5477 return Ret;
5478 }
5479 if (usesLayout(getSemantics()) &&
5480 usesLayout(ToSemantics)) {
5481 auto Ret = getIEEE().convert(ToSemantics, RM, losesInfo);
5482 *this = APFloat(std::move(getIEEE()), ToSemantics);
5483 return Ret;
5484 }
5486}
5487
5490}
5491
5495 OS << Buffer;
5496}
5497
5498#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5501 dbgs() << '\n';
5502}
5503#endif
5504
5507}
5508
5509
5510
5511
5512
5515 bool *isExact) const {
5516 unsigned bitWidth = result.getBitWidth();
5519 rounding_mode, isExact);
5520
5521 result = APInt(bitWidth, parts);
5522 return status;
5523}
5524
5529 "Float semantics is not representable by IEEEdouble");
5531 bool LosesInfo;
5533 assert(!(St & opInexact) && !LosesInfo && "Unexpected imprecision");
5534 (void)St;
5536}
5537
5538#ifdef HAS_IEE754_FLOAT128
5539float128 APFloat::convertToQuad() const {
5541 return getIEEE().convertToQuad();
5543 "Float semantics is not representable by IEEEquad");
5545 bool LosesInfo;
5547 assert(!(St & opInexact) && !LosesInfo && "Unexpected imprecision");
5548 (void)St;
5549 return Temp.getIEEE().convertToQuad();
5550}
5551#endif
5552
5557 "Float semantics is not representable by IEEEsingle");
5559 bool LosesInfo;
5561 assert(!(St & opInexact) && !LosesInfo && "Unexpected imprecision");
5562 (void)St;
5564}
5565
5566}
5567
5568#undef APFLOAT_DISPATCH_ON_SEMANTICS
#define PackCategoriesIntoKey(_lhs, _rhs)
A macro used to combine two fcCategory enums into one key which can be used in a switch statement to ...
This file declares a class to represent arbitrary precision floating point values and provide a varie...
#define APFLOAT_DISPATCH_ON_SEMANTICS(METHOD_CALL)
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
static bool isNeg(Value *V)
Returns true if the operation is a negation of V, and it works for both integers and floats.
Looks at all the uses of the given value Returns the Liveness deduced from the uses of this value Adds all uses that cause the result to be MaybeLive to MaybeLiveRetUses If the result is MaybeLiveUses might be modified but its content should be ignored(since it might not be complete). DeadArgumentEliminationPass
Given that RA is a live value
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
static bool isSigned(unsigned int Opcode)
Utilities for dealing with flags related to floating point properties and mode controls.
This file defines a hash set that can be used to remove duplication of nodes in a graph.
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
void Profile(FoldingSetNodeID &NID) const
Used to insert APFloat objects, or objects that contain APFloat objects, into FoldingSets.
opStatus divide(const APFloat &RHS, roundingMode RM)
bool getExactInverse(APFloat *inv) const
opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
double convertToDouble() const
Converts this APFloat to host double value.
void toString(SmallVectorImpl< char > &Str, unsigned FormatPrecision=0, unsigned FormatMaxPadding=3, bool TruncateZero=true) const
opStatus add(const APFloat &RHS, roundingMode RM)
static APFloat getAllOnesValue(const fltSemantics &Semantics)
Returns a float which is bitcasted from an all one value int.
const fltSemantics & getSemantics() const
opStatus convertFromSignExtendedInteger(const integerPart *Input, unsigned int InputSize, bool IsSigned, roundingMode RM)
opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM)
unsigned int convertToHexString(char *DST, unsigned int HexDigits, bool UpperCase, roundingMode RM) const
float convertToFloat() const
Converts this APFloat to host float value.
opStatus fusedMultiplyAdd(const APFloat &Multiplicand, const APFloat &Addend, roundingMode RM)
opStatus remainder(const APFloat &RHS)
APInt bitcastToAPInt() const
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
opStatus next(bool nextDown)
FPClassTest classify() const
Return the FPClassTest which will return true for the value.
opStatus mod(const APFloat &RHS)
Expected< opStatus > convertFromString(StringRef, roundingMode)
void print(raw_ostream &) const
opStatus roundToIntegral(roundingMode RM)
static bool hasSignificand(const fltSemantics &Sem)
Returns true if the given semantics has actual significand.
opStatus convertFromZeroExtendedInteger(const integerPart *Input, unsigned int InputSize, bool IsSigned, roundingMode RM)
Class for arbitrary precision integers.
APInt udiv(const APInt &RHS) const
Unsigned division operation.
static void tcSetBit(WordType *, unsigned bit)
Set the given bit of a bignum. Zero-based.
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
static void tcSet(WordType *, WordType, unsigned)
Sets the least significant part of a bignum to the input value, and zeroes out higher parts.
static void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Dual division/remainder interface.
static int tcExtractBit(const WordType *, unsigned bit)
Extract the given bit of a bignum; returns 0 or 1. Zero-based.
APInt zext(unsigned width) const
Zero extend to a new width.
static WordType tcAdd(WordType *, const WordType *, WordType carry, unsigned)
DST += RHS + CARRY where CARRY is zero or one. Returns the carry flag.
static void tcExtract(WordType *, unsigned dstCount, const WordType *, unsigned srcBits, unsigned srcLSB)
Copy the bit vector of width srcBITS from SRC, starting at bit srcLSB, to DST, of dstCOUNT parts,...
unsigned getActiveBits() const
Compute the number of active bits in the value.
APInt trunc(unsigned width) const
Truncate to new width.
static int tcCompare(const WordType *, const WordType *, unsigned)
Comparison (unsigned) of two bignums.
static APInt floatToBits(float V)
Converts a float to APInt bits.
static void tcAssign(WordType *, const WordType *, unsigned)
Assign one bignum to another.
unsigned getBitWidth() const
Return the number of bits in the APInt.
static void tcShiftRight(WordType *, unsigned Words, unsigned Count)
Shift a bignum right Count bits.
static void tcFullMultiply(WordType *, const WordType *, const WordType *, unsigned, unsigned)
DST = LHS * RHS, where DST has width the sum of the widths of the operands.
unsigned getNumWords() const
Get the number of words.
bool isNegative() const
Determine sign of this APInt.
static void tcClearBit(WordType *, unsigned bit)
Clear the given bit of a bignum. Zero-based.
static WordType tcDecrement(WordType *dst, unsigned parts)
Decrement a bignum in-place. Return the borrow flag.
unsigned countr_zero() const
Count the number of trailing zero bits.
static unsigned tcLSB(const WordType *, unsigned n)
Returns the bit number of the least or most significant set bit of a number.
static void tcShiftLeft(WordType *, unsigned Words, unsigned Count)
Shift a bignum left Count bits.
static bool tcIsZero(const WordType *, unsigned)
Returns true if a bignum is zero, false otherwise.
static unsigned tcMSB(const WordType *parts, unsigned n)
Returns the bit number of the most significant set bit of a number.
float bitsToFloat() const
Converts APInt bits to a float.
static int tcMultiplyPart(WordType *dst, const WordType *src, WordType multiplier, WordType carry, unsigned srcParts, unsigned dstParts, bool add)
DST += SRC * MULTIPLIER + PART if add is true DST = SRC * MULTIPLIER + PART if add is false.
static constexpr unsigned APINT_BITS_PER_WORD
Bits in a word.
static WordType tcSubtract(WordType *, const WordType *, WordType carry, unsigned)
DST -= RHS + CARRY where CARRY is zero or one. Returns the carry flag.
static void tcNegate(WordType *, unsigned)
Negate a bignum in-place.
static APInt doubleToBits(double V)
Converts a double to APInt bits.
static WordType tcIncrement(WordType *dst, unsigned parts)
Increment a bignum in-place. Return the carry flag.
double bitsToDouble() const
Converts APInt bits to a double.
const uint64_t * getRawData() const
This function returns a pointer to the internal storage of the APInt.
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
An arbitrary precision integer that knows its signedness.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
size - Get the array size.
Lightweight error class with error context and mandatory checking.
static ErrorSuccess success()
Create a success value.
Tagged union holding either a T or a Error.
FoldingSetNodeID - This class is used to gather all the unique data bits of a node.
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
iterator erase(const_iterator CI)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
constexpr bool empty() const
empty - Check if the string is empty.
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
char back() const
back - Get the last character in the string.
StringRef slice(size_t Start, size_t End) const
Return a reference to the substring from [Start, End).
constexpr size_t size() const
size - Get the string size.
char front() const
front - Get the first character in the string.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
void makeSmallestNormalized(bool Neg)
DoubleAPFloat & operator=(const DoubleAPFloat &RHS)
LLVM_READONLY int getExactLog2() const
opStatus remainder(const DoubleAPFloat &RHS)
opStatus multiply(const DoubleAPFloat &RHS, roundingMode RM)
fltCategory getCategory() const
bool bitwiseIsEqual(const DoubleAPFloat &RHS) const
LLVM_READONLY int getExactLog2Abs() const
opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM)
opStatus convertFromZeroExtendedInteger(const integerPart *Input, unsigned int InputSize, bool IsSigned, roundingMode RM)
APInt bitcastToAPInt() const
bool getExactInverse(APFloat *inv) const
Expected< opStatus > convertFromString(StringRef, roundingMode)
opStatus subtract(const DoubleAPFloat &RHS, roundingMode RM)
cmpResult compareAbsoluteValue(const DoubleAPFloat &RHS) const
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
void makeSmallest(bool Neg)
opStatus next(bool nextDown)
opStatus divide(const DoubleAPFloat &RHS, roundingMode RM)
bool isSmallestNormalized() const
opStatus mod(const DoubleAPFloat &RHS)
DoubleAPFloat(const fltSemantics &S)
void toString(SmallVectorImpl< char > &Str, unsigned FormatPrecision, unsigned FormatMaxPadding, bool TruncateZero=true) const
void makeLargest(bool Neg)
cmpResult compare(const DoubleAPFloat &RHS) const
opStatus roundToIntegral(roundingMode RM)
opStatus convertFromSignExtendedInteger(const integerPart *Input, unsigned int InputSize, bool IsSigned, roundingMode RM)
opStatus fusedMultiplyAdd(const DoubleAPFloat &Multiplicand, const DoubleAPFloat &Addend, roundingMode RM)
unsigned int convertToHexString(char *DST, unsigned int HexDigits, bool UpperCase, roundingMode RM) const
opStatus add(const DoubleAPFloat &RHS, roundingMode RM)
void makeNaN(bool SNaN, bool Neg, const APInt *fill)
unsigned int convertToHexString(char *dst, unsigned int hexDigits, bool upperCase, roundingMode) const
Write out a hexadecimal representation of the floating point value to DST, which must be of sufficien...
cmpResult compareAbsoluteValue(const IEEEFloat &) const
opStatus mod(const IEEEFloat &)
C fmod, or llvm frem.
fltCategory getCategory() const
opStatus convertFromAPInt(const APInt &, bool, roundingMode)
bool isFiniteNonZero() const
bool needsCleanup() const
Returns whether this instance allocated memory.
APInt bitcastToAPInt() const
cmpResult compare(const IEEEFloat &) const
IEEE comparison with another floating point number (NaNs compare unordered, 0==-0).
bool isNegative() const
IEEE-754R isSignMinus: Returns true if and only if the current value is negative.
opStatus divide(const IEEEFloat &, roundingMode)
bool isNaN() const
Returns true if and only if the float is a quiet or signaling NaN.
opStatus remainder(const IEEEFloat &)
IEEE remainder.
double convertToDouble() const
opStatus convertFromSignExtendedInteger(const integerPart *, unsigned int, bool, roundingMode)
float convertToFloat() const
opStatus subtract(const IEEEFloat &, roundingMode)
void makeInf(bool Neg=false)
opStatus convertFromZeroExtendedInteger(const integerPart *, unsigned int, bool, roundingMode)
bool isSmallestNormalized() const
Returns true if this is the smallest (by magnitude) normalized finite number in the given semantics.
bool isLargest() const
Returns true if and only if the number has the largest possible finite magnitude in the current seman...
opStatus add(const IEEEFloat &, roundingMode)
bool isFinite() const
Returns true if and only if the current value is zero, subnormal, or normal.
Expected< opStatus > convertFromString(StringRef, roundingMode)
void makeNaN(bool SNaN=false, bool Neg=false, const APInt *fill=nullptr)
friend int ilogb(const IEEEFloat &Arg)
Returns the exponent of the internal representation of the APFloat.
opStatus multiply(const IEEEFloat &, roundingMode)
opStatus roundToIntegral(roundingMode)
IEEEFloat & operator=(const IEEEFloat &)
friend IEEEFloat scalbn(IEEEFloat X, int Exp, roundingMode)
Returns: X * 2^Exp for integral exponents.
bool bitwiseIsEqual(const IEEEFloat &) const
Bitwise comparison for equality (QNaNs compare equal, 0!=-0).
void makeSmallestNormalized(bool Negative=false)
Returns the smallest (by magnitude) normalized finite number in the given semantics.
bool isInteger() const
Returns true if and only if the number is an exact integer.
IEEEFloat(const fltSemantics &)
opStatus fusedMultiplyAdd(const IEEEFloat &, const IEEEFloat &, roundingMode)
bool isInfinity() const
IEEE-754R isInfinite(): Returns true if and only if the float is infinity.
const fltSemantics & getSemantics() const
bool isZero() const
Returns true if and only if the float is plus or minus zero.
bool isSignaling() const
Returns true if and only if the float is a signaling NaN.
void makeZero(bool Neg=false)
opStatus convert(const fltSemantics &, roundingMode, bool *)
IEEEFloat::convert - convert a value of one floating point type to another.
bool isDenormal() const
IEEE-754R isSubnormal(): Returns true if and only if the float is a denormal.
opStatus convertToInteger(MutableArrayRef< integerPart >, unsigned int, bool, roundingMode, bool *) const
bool isSmallest() const
Returns true if and only if the number has the smallest possible non-zero magnitude in the current se...
An opaque object representing a hash code.
This class implements an extremely fast bulk output stream that can only output to a stream.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
static constexpr opStatus opInexact
APFloatBase::roundingMode roundingMode
static constexpr fltCategory fcNaN
static constexpr opStatus opDivByZero
static constexpr opStatus opOverflow
static constexpr cmpResult cmpLessThan
static void tcSetLeastSignificantBits(APInt::WordType *dst, unsigned parts, unsigned bits)
APFloatBase::opStatus opStatus
static constexpr roundingMode rmTowardPositive
static constexpr uninitializedTag uninitialized
static constexpr fltCategory fcZero
static constexpr opStatus opOK
static constexpr cmpResult cmpGreaterThan
static constexpr unsigned integerPartWidth
APFloatBase::ExponentType ExponentType
hash_code hash_value(const IEEEFloat &Arg)
static constexpr fltCategory fcNormal
static constexpr opStatus opInvalidOp
IEEEFloat scalbn(IEEEFloat X, int Exp, roundingMode)
IEEEFloat frexp(const IEEEFloat &Val, int &Exp, roundingMode RM)
APFloatBase::integerPart integerPart
static constexpr cmpResult cmpUnordered
static constexpr roundingMode rmTowardNegative
static constexpr fltCategory fcInfinity
static constexpr roundingMode rmNearestTiesToAway
static constexpr roundingMode rmTowardZero
static constexpr opStatus opUnderflow
static constexpr roundingMode rmNearestTiesToEven
int ilogb(const IEEEFloat &Arg)
static constexpr cmpResult cmpEqual
std::error_code status(const Twine &path, file_status &result, bool follow=true)
Get file status as if by POSIX stat().
This is an optimization pass for GlobalISel generic memory operations.
static unsigned int partAsHex(char *dst, APFloatBase::integerPart part, unsigned int count, const char *hexDigitChars)
static constexpr fltSemantics semBogus
static const char infinityL[]
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
hash_code hash_value(const FixedPointSemantics &Val)
int popcount(T Value) noexcept
Count the number of set bits in a value.
static constexpr unsigned int partCountForBits(unsigned int bits)
static constexpr fltSemantics semFloat8E8M0FNU
static unsigned int HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
static unsigned int powerOf5(APFloatBase::integerPart *dst, unsigned int power)
static constexpr fltSemantics semFloat6E2M3FN
static constexpr APFloatBase::ExponentType exponentZero(const fltSemantics &semantics)
static Expected< int > totalExponent(StringRef::iterator p, StringRef::iterator end, int exponentAdjustment)
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
static constexpr fltSemantics semIEEEquad
const unsigned int maxPowerOfFiveExponent
static constexpr fltSemantics semFloat6E3M2FN
static char * writeUnsignedDecimal(char *dst, unsigned int n)
static constexpr fltSemantics semFloat8E4M3FNUZ
const unsigned int maxPrecision
static constexpr fltSemantics semIEEEdouble
APFloat frexp(const APFloat &X, int &Exp, APFloat::roundingMode RM)
Equivalent of C standard library function.
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
static constexpr fltSemantics semFloat8E4M3FN
static const char infinityU[]
lostFraction
Enum that represents what fraction of the LSB truncated bits of an fp number represent.
static constexpr fltSemantics semPPCDoubleDouble
static Error interpretDecimal(StringRef::iterator begin, StringRef::iterator end, decimalInfo *D)
static constexpr fltSemantics semFloat8E5M2FNUZ
bool isFinite(const Loop *L)
Return true if this loop can be assumed to run for a finite number of iterations.
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
const unsigned int maxPowerOfFiveParts
static constexpr fltSemantics semIEEEsingle
APFloat scalbn(APFloat X, int Exp, APFloat::roundingMode RM)
static constexpr fltSemantics semFloat4E2M1FN
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
static constexpr APFloatBase::ExponentType exponentNaN(const fltSemantics &semantics)
static Error createError(const Twine &Err)
static constexpr fltSemantics semIEEEhalf
static constexpr fltSemantics semPPCDoubleDoubleLegacy
static lostFraction shiftRight(APFloatBase::integerPart *dst, unsigned int parts, unsigned int bits)
static constexpr fltSemantics semFloat8E5M2
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
static const char hexDigitsUpper[]
const unsigned int maxExponent
static unsigned int decDigitValue(unsigned int c)
static constexpr fltSemantics semFloat8E4M3B11FNUZ
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
static lostFraction combineLostFractions(lostFraction moreSignificant, lostFraction lessSignificant)
static Expected< StringRef::iterator > skipLeadingZeroesAndAnyDot(StringRef::iterator begin, StringRef::iterator end, StringRef::iterator *dot)
RoundingMode
Rounding mode.
OutputIt copy(R &&Range, OutputIt Out)
static constexpr fltSemantics semX87DoubleExtended
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
static constexpr fltSemantics semFloatTF32
static constexpr APFloatBase::ExponentType exponentInf(const fltSemantics &semantics)
static lostFraction lostFractionThroughTruncation(const APFloatBase::integerPart *parts, unsigned int partCount, unsigned int bits)
static APFloatBase::integerPart ulpsFromBoundary(const APFloatBase::integerPart *parts, unsigned int bits, bool isNearest)
static char * writeSignedDecimal(char *dst, int value)
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
static constexpr fltSemantics semBFloat
static Expected< lostFraction > trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end, unsigned int digitValue)
void consumeError(Error Err)
Consume a Error without doing anything.
static constexpr fltSemantics semFloat8E3M4
static Expected< int > readExponent(StringRef::iterator begin, StringRef::iterator end)
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
static constexpr fltSemantics semFloat8E4M3
constexpr uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
static const char hexDigitsLower[]
Implement std::hash so that hash_code can be used in STL containers.
static const llvm::fltSemantics & EnumToSemantics(Semantics S)
static const fltSemantics & IEEEsingle() LLVM_READNONE
static bool semanticsHasInf(const fltSemantics &)
static const fltSemantics & Float6E3M2FN() LLVM_READNONE
static constexpr roundingMode rmNearestTiesToAway
cmpResult
IEEE-754R 5.11: Floating Point Comparison Relations.
static const fltSemantics & PPCDoubleDoubleLegacy() LLVM_READNONE
static constexpr roundingMode rmTowardNegative
static ExponentType semanticsMinExponent(const fltSemantics &)
static constexpr roundingMode rmNearestTiesToEven
static unsigned int semanticsSizeInBits(const fltSemantics &)
static bool semanticsHasSignedRepr(const fltSemantics &)
static const fltSemantics & Float8E4M3() LLVM_READNONE
static unsigned getSizeInBits(const fltSemantics &Sem)
Returns the size of the floating point number (in bits) in the given semantics.
static const fltSemantics & Float8E4M3FN() LLVM_READNONE
static const fltSemantics & PPCDoubleDouble() LLVM_READNONE
static constexpr roundingMode rmTowardZero
static const fltSemantics & x87DoubleExtended() LLVM_READNONE
uninitializedTag
Convenience enum used to construct an uninitialized APFloat.
static const fltSemantics & IEEEquad() LLVM_READNONE
static const fltSemantics & Float4E2M1FN() LLVM_READNONE
static const fltSemantics & Float8E8M0FNU() LLVM_READNONE
static const fltSemantics & Float8E4M3B11FNUZ() LLVM_READNONE
static const fltSemantics & Bogus() LLVM_READNONE
A Pseudo fltsemantic used to construct APFloats that cannot conflict with anything real.
static ExponentType semanticsMaxExponent(const fltSemantics &)
static unsigned int semanticsPrecision(const fltSemantics &)
static const fltSemantics & IEEEdouble() LLVM_READNONE
static bool semanticsHasNaN(const fltSemantics &)
static const fltSemantics & Float8E5M2() LLVM_READNONE
static Semantics SemanticsToEnum(const llvm::fltSemantics &Sem)
static constexpr unsigned integerPartWidth
static const fltSemantics & IEEEhalf() LLVM_READNONE
APInt::WordType integerPart
static constexpr roundingMode rmTowardPositive
static bool semanticsHasZero(const fltSemantics &)
static bool isRepresentableAsNormalIn(const fltSemantics &Src, const fltSemantics &Dst)
static const fltSemantics & Float8E4M3FNUZ() LLVM_READNONE
static const fltSemantics & BFloat() LLVM_READNONE
static const fltSemantics & FloatTF32() LLVM_READNONE
static bool isRepresentableBy(const fltSemantics &A, const fltSemantics &B)
static const fltSemantics & Float8E5M2FNUZ() LLVM_READNONE
static const fltSemantics & Float6E2M3FN() LLVM_READNONE
fltCategory
Category of internally-represented number.
@ S_PPCDoubleDoubleLegacy
static const fltSemantics & Float8E3M4() LLVM_READNONE
opStatus
IEEE-754R 7: Default exception handling.
int32_t ExponentType
A signed type to represent a floating point numbers unbiased exponent.
static unsigned int semanticsIntSizeInBits(const fltSemantics &, bool)
const char * lastSigDigit
const char * firstSigDigit
APFloatBase::ExponentType maxExponent
fltNonfiniteBehavior nonFiniteBehavior
APFloatBase::ExponentType minExponent
fltNanEncoding nanEncoding