LLVM 24.0.0git
APFloat.cpp
Go to the documentation of this file.
1//===-- APFloat.cpp - Implement APFloat class -----------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements a class to represent arbitrary precision floating
10// point values and provide a variety of arithmetic operations on them.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/ADT/APFloat.h"
15#include "llvm/ADT/APSInt.h"
16#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/FoldingSet.h"
19#include "llvm/ADT/Hashing.h"
20#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/StringRef.h"
24#include "llvm/Config/llvm-config.h"
25#include "llvm/Support/Debug.h"
26#include "llvm/Support/Error.h"
29#include <cstring>
30#include <limits.h>
31
32/// Shared headers from LLVM libc
33/// Make sure to add ${LLVM_SOURCE_DIR}/../libc to include directories.
34///
35/// Notes: So far it looks like APFloat does not check errnos or floating-point
36/// exceptions after calling the math functions, so we will configure LLVM libc
37/// math functions to skip setting errnos and floating-point exceptions
38/// explicitly. We also put them in a separate namespace so that the symbols
39/// do not clash with other libc math builds just in case.
40#define LIBC_NAMESPACE __llvm_libc_apfloat
41#define LIBC_MATH (LIBC_MATH_NO_ERRNO | LIBC_MATH_NO_EXCEPT)
42
43#include "shared/math.h"
44#include "shared/math_check_exceptions.h"
45
46#define APFLOAT_DISPATCH_ON_SEMANTICS(METHOD_CALL) \
47 do { \
48 if (usesLayout<IEEEFloat>(getSemantics())) \
49 return U.IEEE.METHOD_CALL; \
50 if (usesLayout<DoubleAPFloat>(getSemantics())) \
51 return U.Double.METHOD_CALL; \
52 llvm_unreachable("Unexpected semantics"); \
53 } while (false)
54
55using namespace llvm;
56
57/// A macro used to combine two fcCategory enums into one key which can be used
58/// in a switch statement to classify how the interaction of two APFloat's
59/// categories affects an operation.
60///
61/// TODO: If clang source code is ever allowed to use constexpr in its own
62/// codebase, change this into a static inline function.
63#define PackCategoriesIntoKey(_lhs, _rhs) ((_lhs) * 4 + (_rhs))
64
65/* Assumed in hexadecimal significand parsing, and conversion to
66 hexadecimal strings. */
67static_assert(APFloatBase::integerPartWidth % 4 == 0, "Part width must be divisible by 4!");
68
69namespace llvm {
70
71constexpr fltSemantics APFloatBase::semIEEEhalf = {15, -14, 11, 16};
72constexpr fltSemantics APFloatBase::semBFloat = {127, -126, 8, 16};
73constexpr fltSemantics APFloatBase::semIEEEsingle = {127, -126, 24, 32};
74constexpr fltSemantics APFloatBase::semIEEEdouble = {1023, -1022, 53, 64};
75constexpr fltSemantics APFloatBase::semIEEEquad = {16383, -16382, 113, 128};
76constexpr fltSemantics APFloatBase::semFloat8E5M2 = {15, -14, 3, 8};
77constexpr fltSemantics APFloatBase::semFloat8E5M2FNUZ = {
79constexpr fltSemantics APFloatBase::semFloat8E4M3 = {7, -6, 4, 8};
80constexpr fltSemantics APFloatBase::semFloat8E4M3FN = {
82constexpr fltSemantics APFloatBase::semFloat8E4M3FNUZ = {
84constexpr fltSemantics APFloatBase::semFloat8E4M3B11FNUZ = {
86constexpr fltSemantics APFloatBase::semFloat8E3M4 = {3, -2, 5, 8};
87constexpr fltSemantics APFloatBase::semFloatTF32 = {127, -126, 11, 19};
88constexpr fltSemantics APFloatBase::semFloat8E8M0FNU = {
89 127,
90 -127,
91 1,
92 8,
95 false,
96 false,
97 false,
98 false};
99
100constexpr fltSemantics APFloatBase::semFloat8E5M3FNU = {
101 16,
102 -14,
103 4,
104 8,
107 true,
108 false,
109 false};
110
111constexpr fltSemantics APFloatBase::semFloat6E3M2FN = {
113constexpr fltSemantics APFloatBase::semFloat6E2M3FN = {
115constexpr fltSemantics APFloatBase::semFloat4E2M1FN = {
117constexpr fltSemantics APFloatBase::semX87DoubleExtended = {
118 16383,
119 -16382,
120 64,
121 80,
124 true,
125 true,
126 true,
127 true,
128 true};
129constexpr fltSemantics APFloatBase::semBogus = {0, 0, 0, 0};
130constexpr fltSemantics APFloatBase::semPPCDoubleDouble = {-1, 0, 0, 128};
131constexpr fltSemantics APFloatBase::semPPCDoubleDoubleLegacy = {
132 1023, -1022 + 53, 53 + 53, 128};
133
135 switch (S) {
136 case S_IEEEhalf:
137 return IEEEhalf();
138 case S_BFloat:
139 return BFloat();
140 case S_IEEEsingle:
141 return IEEEsingle();
142 case S_IEEEdouble:
143 return IEEEdouble();
144 case S_IEEEquad:
145 return IEEEquad();
147 return PPCDoubleDouble();
149 return PPCDoubleDoubleLegacy();
150 case S_Float8E5M2:
151 return Float8E5M2();
152 case S_Float8E5M2FNUZ:
153 return Float8E5M2FNUZ();
154 case S_Float8E4M3:
155 return Float8E4M3();
156 case S_Float8E4M3FN:
157 return Float8E4M3FN();
158 case S_Float8E4M3FNUZ:
159 return Float8E4M3FNUZ();
161 return Float8E4M3B11FNUZ();
162 case S_Float8E3M4:
163 return Float8E3M4();
164 case S_FloatTF32:
165 return FloatTF32();
166 case S_Float8E8M0FNU:
167 return Float8E8M0FNU();
168 case S_Float8E5M3FNU:
169 return Float8E5M3FNU();
170 case S_Float6E3M2FN:
171 return Float6E3M2FN();
172 case S_Float6E2M3FN:
173 return Float6E2M3FN();
174 case S_Float4E2M1FN:
175 return Float4E2M1FN();
177 return x87DoubleExtended();
178 }
179 llvm_unreachable("Unrecognised floating semantics");
180}
181
184 if (&Sem == &llvm::APFloat::IEEEhalf())
185 return S_IEEEhalf;
186 else if (&Sem == &llvm::APFloat::BFloat())
187 return S_BFloat;
188 else if (&Sem == &llvm::APFloat::IEEEsingle())
189 return S_IEEEsingle;
190 else if (&Sem == &llvm::APFloat::IEEEdouble())
191 return S_IEEEdouble;
192 else if (&Sem == &llvm::APFloat::IEEEquad())
193 return S_IEEEquad;
194 else if (&Sem == &llvm::APFloat::PPCDoubleDouble())
195 return S_PPCDoubleDouble;
196 else if (&Sem == &llvm::APFloat::PPCDoubleDoubleLegacy())
198 else if (&Sem == &llvm::APFloat::Float8E5M2())
199 return S_Float8E5M2;
200 else if (&Sem == &llvm::APFloat::Float8E5M2FNUZ())
201 return S_Float8E5M2FNUZ;
202 else if (&Sem == &llvm::APFloat::Float8E4M3())
203 return S_Float8E4M3;
204 else if (&Sem == &llvm::APFloat::Float8E4M3FN())
205 return S_Float8E4M3FN;
206 else if (&Sem == &llvm::APFloat::Float8E4M3FNUZ())
207 return S_Float8E4M3FNUZ;
208 else if (&Sem == &llvm::APFloat::Float8E4M3B11FNUZ())
209 return S_Float8E4M3B11FNUZ;
210 else if (&Sem == &llvm::APFloat::Float8E3M4())
211 return S_Float8E3M4;
212 else if (&Sem == &llvm::APFloat::FloatTF32())
213 return S_FloatTF32;
214 else if (&Sem == &llvm::APFloat::Float8E8M0FNU())
215 return S_Float8E8M0FNU;
216 else if (&Sem == &llvm::APFloat::Float8E5M3FNU())
217 return S_Float8E5M3FNU;
218 else if (&Sem == &llvm::APFloat::Float6E3M2FN())
219 return S_Float6E3M2FN;
220 else if (&Sem == &llvm::APFloat::Float6E2M3FN())
221 return S_Float6E2M3FN;
222 else if (&Sem == &llvm::APFloat::Float4E2M1FN())
223 return S_Float4E2M1FN;
224 else if (&Sem == &llvm::APFloat::x87DoubleExtended())
225 return S_x87DoubleExtended;
226 else
227 llvm_unreachable("Unknown floating semantics");
228}
229
231 const fltSemantics &B) {
232 return A.maxExponent <= B.maxExponent && A.minExponent >= B.minExponent &&
233 A.precision <= B.precision;
234}
235
237 const fltSemantics &To,
238 bool IgnoreNaNs) {
239 if (&From == &To)
240 return true;
241
242 // PPC double-double cannot be described by a conventional exponent range
243 // and precision. In particular, converting it to another semantics drops
244 // its low double, so conservatively reject conversions involving it.
245 if (&From == &semPPCDoubleDouble || &To == &semPPCDoubleDouble)
246 return false;
247
248 if (!isRepresentableBy(From, To))
249 return false;
250
251 if ((From.hasZero && !To.hasZero) ||
252 (From.hasSignedRepr && !To.hasSignedRepr))
253 return false;
254
255 // NegativeZero NaN encoding repurposes the negative-zero bit pattern, so a
256 // conversion to such a format cannot preserve a source negative zero.
257 bool FromHasSignedZero = From.hasZero && From.hasSignedRepr &&
259 bool ToHasSignedZero = To.hasZero && To.hasSignedRepr &&
261 if (FromHasSignedZero && !ToHasSignedZero)
262 return false;
263
264 // isRepresentableBy compares normalized exponent ranges. Also ensure that
265 // the smallest source value, which may be denormal, is represented exactly
266 // by the destination semantics.
267 APFloat SmallestFrom = APFloat::getSmallest(From);
268 bool LosesInfo = false;
269 (void)SmallestFrom.convert(To, APFloat::rmNearestTiesToEven, &LosesInfo);
270 if (LosesInfo)
271 return false;
272
274 return true;
275
276 // Even when NaN representations can be ignored, NaNs must remain NaNs and
277 // infinities must remain infinities. Otherwise the conversion can change
278 // whether an operation with nnan has poison-producing operands.
279 if (IgnoreNaNs) {
283 }
284
286 // Converting an IEEE signaling NaN to another semantics quiets it, so the
287 // original value cannot be recovered by converting it back.
288 return false;
289 }
290
291 // NanOnly formats have no signaling NaNs. IEEE semantics can represent
292 // their quiet NaNs; conversions between NanOnly formats are conservatively
293 // accepted only when they use the same NaN encoding.
295 return true;
297 From.nanEncoding == To.nanEncoding;
298}
299
300/* A tight upper bound on number of parts required to hold the value
301 pow(5, power) is
302
303 power * 815 / (351 * integerPartWidth) + 1
304
305 However, whilst the result may require only this many parts,
306 because we are multiplying two values to get it, the
307 multiplication may require an extra part with the excess part
308 being zero (consider the trivial case of 1 * 1, tcFullMultiply
309 requires two parts to hold the single-part result). So we add an
310 extra one to guarantee enough space whilst multiplying. */
311const unsigned int maxExponent = 16383;
312const unsigned int maxPrecision = 113;
314const unsigned int maxPowerOfFiveParts =
315 2 +
317
318unsigned int APFloatBase::semanticsPrecision(const fltSemantics &semantics) {
319 return semantics.precision;
320}
323 return semantics.maxExponent;
324}
327 return semantics.minExponent;
328}
329unsigned int APFloatBase::semanticsSizeInBits(const fltSemantics &semantics) {
330 return semantics.sizeInBits;
331}
333 bool isSigned) {
334 // The max FP value is pow(2, MaxExponent) * (1 + MaxFraction), so we need
335 // at least one more bit than the MaxExponent to hold the max FP value.
336 unsigned int MinBitWidth = semanticsMaxExponent(semantics) + 1;
337 // Extra sign bit needed.
338 if (isSigned)
339 ++MinBitWidth;
340 return MinBitWidth;
341}
342
344 return semantics.hasZero;
345}
346
348 return semantics.hasSignedRepr;
349}
350
354
358
360 // Keep in sync with Type::isIEEELikeFPTy
361 return SemanticsToEnum(semantics) <= S_IEEEquad;
362}
363
365 return semantics.hasSignBitInMSB;
366}
367
369 const fltSemantics &Dst) {
370 // Exponent range must be larger.
371 if (Src.maxExponent >= Dst.maxExponent || Src.minExponent <= Dst.minExponent)
372 return false;
373
374 // If the mantissa is long enough, the result value could still be denormal
375 // with a larger exponent range.
376 //
377 // FIXME: This condition is probably not accurate but also shouldn't be a
378 // practical concern with existing types.
379 return Dst.precision >= Src.precision;
380}
381
383 return Sem.sizeInBits;
384}
385
386static constexpr APFloatBase::ExponentType
387exponentZero(const fltSemantics &semantics) {
388 return semantics.minExponent - 1;
389}
390
391static constexpr APFloatBase::ExponentType
392exponentInf(const fltSemantics &semantics) {
393 return semantics.maxExponent + 1;
394}
395
396static constexpr APFloatBase::ExponentType
397exponentNaN(const fltSemantics &semantics) {
400 return exponentZero(semantics);
401 if (semantics.hasSignedRepr || semantics.precision > 1)
402 return semantics.maxExponent;
403 }
404 return semantics.maxExponent + 1;
405}
406
407/* A bunch of private, handy routines. */
408
409static inline Error createError(const Twine &Err) {
411}
412
413static constexpr inline unsigned int partCountForBits(unsigned int bits) {
414 return std::max(1u, (bits + APFloatBase::integerPartWidth - 1) /
416}
417
418/* Returns 0U-9U. Return values >= 10U are not digits. */
419static inline unsigned int
420decDigitValue(unsigned int c)
421{
422 return c - '0';
423}
424
425/* Return the value of a decimal exponent of the form
426 [+-]ddddddd.
427
428 If the exponent overflows, returns a large exponent with the
429 appropriate sign. */
432 const unsigned int overlargeExponent = 24000; /* FIXME. */
433 StringRef::iterator p = begin;
434
435 // Treat no exponent as 0 to match binutils
436 if (p == end || ((*p == '-' || *p == '+') && (p + 1) == end))
437 return 0;
438
439 bool isNegative = *p == '-';
440 if (*p == '-' || *p == '+') {
441 p++;
442 if (p == end)
443 return createError("Exponent has no digits");
444 }
445
446 unsigned absExponent = decDigitValue(*p++);
447 if (absExponent >= 10U)
448 return createError("Invalid character in exponent");
449
450 for (; p != end; ++p) {
451 unsigned value = decDigitValue(*p);
452 if (value >= 10U)
453 return createError("Invalid character in exponent");
454
455 absExponent = absExponent * 10U + value;
456 if (absExponent >= overlargeExponent) {
457 absExponent = overlargeExponent;
458 break;
459 }
460 }
461
462 if (isNegative)
463 return -(int) absExponent;
464 else
465 return (int) absExponent;
466}
467
468/* This is ugly and needs cleaning up, but I don't immediately see
469 how whilst remaining safe. */
472 int exponentAdjustment) {
473 int exponent = 0;
474
475 if (p == end)
476 return createError("Exponent has no digits");
477
478 bool negative = *p == '-';
479 if (*p == '-' || *p == '+') {
480 p++;
481 if (p == end)
482 return createError("Exponent has no digits");
483 }
484
485 int unsignedExponent = 0;
486 bool overflow = false;
487 for (; p != end; ++p) {
488 unsigned int value;
489
490 value = decDigitValue(*p);
491 if (value >= 10U)
492 return createError("Invalid character in exponent");
493
494 unsignedExponent = unsignedExponent * 10 + value;
495 if (unsignedExponent > 32767) {
496 overflow = true;
497 break;
498 }
499 }
500
501 if (exponentAdjustment > 32767 || exponentAdjustment < -32768)
502 overflow = true;
503
504 if (!overflow) {
505 exponent = unsignedExponent;
506 if (negative)
507 exponent = -exponent;
508 exponent += exponentAdjustment;
509 if (exponent > 32767 || exponent < -32768)
510 overflow = true;
511 }
512
513 if (overflow)
514 exponent = negative ? -32768: 32767;
515
516 return exponent;
517}
518
521 StringRef::iterator *dot) {
522 StringRef::iterator p = begin;
523 *dot = end;
524 while (p != end && *p == '0')
525 p++;
526
527 if (p != end && *p == '.') {
528 *dot = p++;
529
530 if (end - begin == 1)
531 return createError("Significand has no digits");
532
533 while (p != end && *p == '0')
534 p++;
535 }
536
537 return p;
538}
539
540/* Given a normal decimal floating point number of the form
541
542 dddd.dddd[eE][+-]ddd
543
544 where the decimal point and exponent are optional, fill out the
545 structure D. Exponent is appropriate if the significand is
546 treated as an integer, and normalizedExponent if the significand
547 is taken to have the decimal point after a single leading
548 non-zero digit.
549
550 If the value is zero, V->firstSigDigit points to a non-digit, and
551 the return exponent is zero.
552*/
554 const char *firstSigDigit;
555 const char *lastSigDigit;
558};
559
562 StringRef::iterator dot = end;
563
564 auto PtrOrErr = skipLeadingZeroesAndAnyDot(begin, end, &dot);
565 if (!PtrOrErr)
566 return PtrOrErr.takeError();
567 StringRef::iterator p = *PtrOrErr;
568
569 D->firstSigDigit = p;
570 D->exponent = 0;
571 D->normalizedExponent = 0;
572
573 for (; p != end; ++p) {
574 if (*p == '.') {
575 if (dot != end)
576 return createError("String contains multiple dots");
577 dot = p++;
578 if (p == end)
579 break;
580 }
581 if (decDigitValue(*p) >= 10U)
582 break;
583 }
584
585 if (p != end) {
586 if (*p != 'e' && *p != 'E')
587 return createError("Invalid character in significand");
588 if (p == begin)
589 return createError("Significand has no digits");
590 if (dot != end && p - begin == 1)
591 return createError("Significand has no digits");
592
593 /* p points to the first non-digit in the string */
594 auto ExpOrErr = readExponent(p + 1, end);
595 if (!ExpOrErr)
596 return ExpOrErr.takeError();
597 D->exponent = *ExpOrErr;
598
599 /* Implied decimal point? */
600 if (dot == end)
601 dot = p;
602 }
603
604 /* If number is all zeroes accept any exponent. */
605 if (p != D->firstSigDigit) {
606 /* Drop insignificant trailing zeroes. */
607 if (p != begin) {
608 do
609 do
610 p--;
611 while (p != begin && *p == '0');
612 while (p != begin && *p == '.');
613 }
614
615 /* Adjust the exponents for any decimal point. */
616 D->exponent += static_cast<APFloat::ExponentType>((dot - p) - (dot > p));
617 D->normalizedExponent = (D->exponent +
618 static_cast<APFloat::ExponentType>((p - D->firstSigDigit)
619 - (dot > D->firstSigDigit && dot < p)));
620 }
621
622 D->lastSigDigit = p;
623 return Error::success();
624}
625
626/* Return the trailing fraction of a hexadecimal number.
627 DIGITVALUE is the first hex digit of the fraction, P points to
628 the next digit. */
631 unsigned int digitValue) {
632 /* If the first trailing digit isn't 0 or 8 we can work out the
633 fraction immediately. */
634 if (digitValue > 8)
635 return lfMoreThanHalf;
636 else if (digitValue < 8 && digitValue > 0)
637 return lfLessThanHalf;
638
639 // Otherwise we need to find the first non-zero digit.
640 while (p != end && (*p == '0' || *p == '.'))
641 p++;
642
643 if (p == end)
644 return createError("Invalid trailing hexadecimal fraction!");
645
646 unsigned hexDigit = hexDigitValue(*p);
647
648 /* If we ran off the end it is exactly zero or one-half, otherwise
649 a little more. */
650 if (hexDigit == UINT_MAX)
651 return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
652 else
653 return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf;
654}
655
656/* Return the fraction lost were a bignum truncated losing the least
657 significant BITS bits. */
658static lostFraction
660 unsigned int partCount,
661 unsigned int bits)
662{
663 unsigned lsb = APInt::tcLSB(parts, partCount);
664
665 /* Note this is guaranteed true if bits == 0, or LSB == UINT_MAX. */
666 if (bits <= lsb)
667 return lfExactlyZero;
668 if (bits == lsb + 1)
669 return lfExactlyHalf;
670 if (bits <= partCount * APFloatBase::integerPartWidth &&
671 APInt::tcExtractBit(parts, bits - 1))
672 return lfMoreThanHalf;
673
674 return lfLessThanHalf;
675}
676
677/* Shift DST right BITS bits noting lost fraction. */
678static lostFraction
679shiftRight(APFloatBase::integerPart *dst, unsigned int parts, unsigned int bits)
680{
681 lostFraction lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
682
683 APInt::tcShiftRight(dst, parts, bits);
684
685 return lost_fraction;
686}
687
688/* Combine the effect of two lost fractions. */
689static lostFraction
691 lostFraction lessSignificant)
692{
693 if (lessSignificant != lfExactlyZero) {
694 if (moreSignificant == lfExactlyZero)
695 moreSignificant = lfLessThanHalf;
696 else if (moreSignificant == lfExactlyHalf)
697 moreSignificant = lfMoreThanHalf;
698 }
699
700 return moreSignificant;
701}
702
703/* The error from the true value, in half-ulps, on multiplying two
704 floating point numbers, which differ from the value they
705 approximate by at most HUE1 and HUE2 half-ulps, is strictly less
706 than the returned value.
707
708 See "How to Read Floating Point Numbers Accurately" by William D
709 Clinger. */
710static unsigned int
711HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
712{
713 assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
714
715 if (HUerr1 + HUerr2 == 0)
716 return inexactMultiply * 2; /* <= inexactMultiply half-ulps. */
717 else
718 return inexactMultiply + 2 * (HUerr1 + HUerr2);
719}
720
721/* The number of ulps from the boundary (zero, or half if ISNEAREST)
722 when the least significant BITS are truncated. BITS cannot be
723 zero. */
725ulpsFromBoundary(const APFloatBase::integerPart *parts, unsigned int bits,
726 bool isNearest) {
727 assert(bits != 0);
728
729 bits--;
730 unsigned count = bits / APFloatBase::integerPartWidth;
731 unsigned partBits = bits % APFloatBase::integerPartWidth + 1;
732
734 parts[count] & (~(APFloatBase::integerPart)0 >>
735 (APFloatBase::integerPartWidth - partBits));
736
738 if (isNearest)
739 boundary = (APFloatBase::integerPart) 1 << (partBits - 1);
740 else
741 boundary = 0;
742
743 if (count == 0) {
744 if (part - boundary <= boundary - part)
745 return part - boundary;
746 else
747 return boundary - part;
748 }
749
750 if (part == boundary) {
751 while (--count)
752 if (parts[count])
753 return ~(APFloatBase::integerPart) 0; /* A lot. */
754
755 return parts[0];
756 } else if (part == boundary - 1) {
757 while (--count)
758 if (~parts[count])
759 return ~(APFloatBase::integerPart) 0; /* A lot. */
760
761 return -parts[0];
762 }
763
764 return ~(APFloatBase::integerPart) 0; /* A lot. */
765}
766
767/* Place pow(5, power) in DST, and return the number of parts used.
768 DST must be at least one part larger than size of the answer. */
769static unsigned int
770powerOf5(APFloatBase::integerPart *dst, unsigned int power) {
771 static const APFloatBase::integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125, 15625, 78125 };
773 pow5s[0] = 78125 * 5;
774
775 unsigned int partsCount = 1;
776 APFloatBase::integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5;
777 assert(power <= maxExponent);
778
779 p1 = dst;
780 p2 = scratch;
781
782 *p1 = firstEightPowers[power & 7];
783 power >>= 3;
784
785 unsigned result = 1;
786 pow5 = pow5s;
787
788 for (unsigned int n = 0; power; power >>= 1, n++) {
789 /* Calculate pow(5,pow(2,n+3)) if we haven't yet. */
790 if (n != 0) {
791 APInt::tcFullMultiply(pow5, pow5 - partsCount, pow5 - partsCount,
792 partsCount, partsCount);
793 partsCount *= 2;
794 if (pow5[partsCount - 1] == 0)
795 partsCount--;
796 }
797
798 if (power & 1) {
800
801 APInt::tcFullMultiply(p2, p1, pow5, result, partsCount);
802 result += partsCount;
803 if (p2[result - 1] == 0)
804 result--;
805
806 /* Now result is in p1 with partsCount parts and p2 is scratch
807 space. */
808 tmp = p1;
809 p1 = p2;
810 p2 = tmp;
811 }
812
813 pow5 += partsCount;
814 }
815
816 if (p1 != dst)
817 APInt::tcAssign(dst, p1, result);
818
819 return result;
820}
821
822/* Zero at the end to avoid modular arithmetic when adding one; used
823 when rounding up during hexadecimal output. */
824static const char hexDigitsLower[] = "0123456789abcdef0";
825static const char hexDigitsUpper[] = "0123456789ABCDEF0";
826static const char infinityL[] = "infinity";
827static const char infinityU[] = "INFINITY";
828static const char NaNL[] = "nan";
829static const char NaNU[] = "NAN";
830
831/* Write out an integerPart in hexadecimal, starting with the most
832 significant nibble. Write out exactly COUNT hexdigits, return
833 COUNT. */
834static unsigned int
835partAsHex (char *dst, APFloatBase::integerPart part, unsigned int count,
836 const char *hexDigitChars)
837{
838 unsigned int result = count;
839
841
842 part >>= (APFloatBase::integerPartWidth - 4 * count);
843 while (count--) {
844 dst[count] = hexDigitChars[part & 0xf];
845 part >>= 4;
846 }
847
848 return result;
849}
850
851/* Write out an unsigned decimal integer. */
852static char *writeUnsignedDecimal(char *dst, unsigned int n) {
853 char buff[40], *p;
854
855 p = buff;
856 do
857 *p++ = '0' + n % 10;
858 while (n /= 10);
859
860 do
861 *dst++ = *--p;
862 while (p != buff);
863
864 return dst;
865}
866
867/* Write out a signed decimal integer. */
868static char *writeSignedDecimal(char *dst, int value) {
869 if (value < 0) {
870 *dst++ = '-';
871 dst = writeUnsignedDecimal(dst, -(unsigned) value);
872 } else {
873 dst = writeUnsignedDecimal(dst, value);
874 }
875
876 return dst;
877}
878
879// Compute the ULP of the input using a definition from:
880// Jean-Michel Muller. On the definition of ulp(x). [Research Report] RR-5504,
881// LIP RR-2005-09, INRIA, LIP. 2005, pp.16. inria-00070503
882static APFloat harrisonUlp(const APFloat &X) {
883 const fltSemantics &Sem = X.getSemantics();
884 switch (X.getCategory()) {
885 case APFloat::fcNaN:
886 return APFloat::getQNaN(Sem);
888 return APFloat::getInf(Sem);
889 case APFloat::fcZero:
890 return APFloat::getSmallest(Sem);
892 break;
893 }
894 if (X.isDenormal() || X.isSmallestNormalized())
895 return APFloat::getSmallest(Sem);
896 int Exp = ilogb(X);
897 if (X.getExactLog2() != INT_MIN)
898 Exp -= 1;
899 return scalbn(APFloat::getOne(Sem), Exp - (Sem.precision - 1),
901}
902
903namespace detail {
904/* Constructors. */
905void IEEEFloat::initialize(const fltSemantics *ourSemantics) {
906 semantics = ourSemantics;
907 unsigned count = partCount();
908 if (count > 1)
909 significand.parts = new integerPart[count];
910}
911
912void IEEEFloat::freeSignificand() {
913 if (needsCleanup())
914 delete [] significand.parts;
915}
916
917void IEEEFloat::assign(const IEEEFloat &rhs) {
918 assert(semantics == rhs.semantics);
919
920 sign = rhs.sign;
921 category = rhs.category;
922 exponent = rhs.exponent;
923 if (isFiniteNonZero() || category == fcNaN)
924 copySignificand(rhs);
925}
926
927void IEEEFloat::copySignificand(const IEEEFloat &rhs) {
928 assert(isFiniteNonZero() || category == fcNaN);
929 assert(rhs.partCount() >= partCount());
930
931 APInt::tcAssign(significandParts(), rhs.significandParts(),
932 partCount());
933}
934
935/* Make this number a NaN, with an arbitrary but deterministic value
936 for the significand. If double or longer, this is a signalling NaN,
937 which may not be ideal. If float, this is QNaN(0). */
938void IEEEFloat::makeNaN(bool SNaN, bool Negative, const APInt *fill) {
939 if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::FiniteOnly)
940 llvm_unreachable("This floating point format does not support NaN");
941
942 if (Negative && !semantics->hasSignedRepr)
944 "This floating point format does not support signed values");
945
946 category = fcNaN;
947 sign = Negative;
948 exponent = exponentNaN();
949
950 integerPart *significand = significandParts();
951 unsigned numParts = partCount();
952
953 APInt fill_storage;
954 if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly) {
955 // Finite-only types do not distinguish signalling and quiet NaN, so
956 // make them all signalling.
957 SNaN = false;
958 if (semantics->nanEncoding == fltNanEncoding::NegativeZero) {
959 sign = true;
960 fill_storage = APInt::getZero(semantics->precision - 1);
961 } else {
962 fill_storage = APInt::getAllOnes(semantics->precision - 1);
963 }
964 fill = &fill_storage;
965 }
966
967 // Set the significand bits to the fill.
968 if (!fill || fill->getNumWords() < numParts)
969 APInt::tcSet(significand, 0, numParts);
970 if (fill) {
971 APInt::tcAssign(significand, fill->getRawData(),
972 std::min(fill->getNumWords(), numParts));
973
974 // Zero out the excess bits of the significand.
975 unsigned bitsToPreserve = semantics->precision - 1;
976 unsigned part = bitsToPreserve / 64;
977 bitsToPreserve %= 64;
978 significand[part] &= ((1ULL << bitsToPreserve) - 1);
979 for (part++; part != numParts; ++part)
980 significand[part] = 0;
981 }
982
983 unsigned QNaNBit =
984 (semantics->precision >= 2) ? (semantics->precision - 2) : 0;
985
986 if (SNaN) {
987 // We always have to clear the QNaN bit to make it an SNaN.
988 APInt::tcClearBit(significand, QNaNBit);
989
990 // If there are no bits set in the payload, we have to set
991 // *something* to make it a NaN instead of an infinity;
992 // conventionally, this is the next bit down from the QNaN bit.
993 if (APInt::tcIsZero(significand, numParts))
994 APInt::tcSetBit(significand, QNaNBit - 1);
995 } else if (semantics->nanEncoding == fltNanEncoding::NegativeZero) {
996 // The only NaN is a quiet NaN, and it has no bits sets in the significand.
997 // Do nothing.
998 } else {
999 // We always have to set the QNaN bit to make it a QNaN.
1000 APInt::tcSetBit(significand, QNaNBit);
1001 }
1002
1003 // For x87 extended precision, we want to make a NaN, not a
1004 // pseudo-NaN. Maybe we should expose the ability to make
1005 // pseudo-NaNs?
1006 if (semantics == &APFloatBase::semX87DoubleExtended)
1007 APInt::tcSetBit(significand, QNaNBit + 1);
1008}
1009
1011 if (this != &rhs) {
1012 if (semantics != rhs.semantics) {
1013 freeSignificand();
1014 initialize(rhs.semantics);
1015 }
1016 assign(rhs);
1017 }
1018
1019 return *this;
1020}
1021
1023 freeSignificand();
1024
1025 semantics = rhs.semantics;
1026 significand = rhs.significand;
1027 exponent = rhs.exponent;
1028 category = rhs.category;
1029 sign = rhs.sign;
1030
1031 rhs.semantics = &APFloatBase::semBogus;
1032 return *this;
1033}
1034
1037 (exponent == semantics->minExponent) &&
1038 (APInt::tcExtractBit(significandParts(), semantics->precision - 1) ==
1039 0);
1040}
1041
1043 // The smallest number by magnitude in our format will be the smallest
1044 // denormal, i.e. the floating point number with exponent being minimum
1045 // exponent and significand bitwise equal to 1 (i.e. with MSB equal to 0).
1046 return isFiniteNonZero() && exponent == semantics->minExponent &&
1047 significandMSB() == 0;
1048}
1049
1051 return getCategory() == fcNormal && exponent == semantics->minExponent &&
1052 isSignificandAllZerosExceptMSB();
1053}
1054
1055unsigned int IEEEFloat::getNumHighBits() const {
1056 const unsigned int PartCount = partCountForBits(semantics->precision);
1057 const unsigned int Bits = PartCount * integerPartWidth;
1058
1059 // Compute how many bits are used in the final word.
1060 // When precision is just 1, it represents the 'Pth'
1061 // Precision bit and not the actual significand bit.
1062 const unsigned int NumHighBits = (semantics->precision > 1)
1063 ? (Bits - semantics->precision + 1)
1064 : (Bits - semantics->precision);
1065 return NumHighBits;
1066}
1067
1068bool IEEEFloat::isSignificandAllOnes() const {
1069 // Test if the significand excluding the integral bit is all ones. This allows
1070 // us to test for binade boundaries.
1071 const integerPart *Parts = significandParts();
1072 const unsigned PartCount = partCountForBits(semantics->precision);
1073 for (unsigned i = 0; i < PartCount - 1; i++)
1074 if (~Parts[i])
1075 return false;
1076
1077 // Set the unused high bits to all ones when we compare.
1078 const unsigned NumHighBits = getNumHighBits();
1079 assert(NumHighBits <= integerPartWidth && NumHighBits > 0 &&
1080 "Can not have more high bits to fill than integerPartWidth");
1081 const integerPart HighBitFill =
1082 ~integerPart(0) << (integerPartWidth - NumHighBits);
1083 if ((semantics->precision <= 1) || (~(Parts[PartCount - 1] | HighBitFill)))
1084 return false;
1085
1086 return true;
1087}
1088
1089bool IEEEFloat::isSignificandAllOnesExceptLSB() const {
1090 // Test if the significand excluding the integral bit is all ones except for
1091 // the least significant bit.
1092 const integerPart *Parts = significandParts();
1093
1094 if (Parts[0] & 1)
1095 return false;
1096
1097 const unsigned PartCount = partCountForBits(semantics->precision);
1098 for (unsigned i = 0; i < PartCount - 1; i++) {
1099 if (~Parts[i] & ~unsigned{!i})
1100 return false;
1101 }
1102
1103 // Set the unused high bits to all ones when we compare.
1104 const unsigned NumHighBits = getNumHighBits();
1105 assert(NumHighBits <= integerPartWidth && NumHighBits > 0 &&
1106 "Can not have more high bits to fill than integerPartWidth");
1107 const integerPart HighBitFill = ~integerPart(0)
1108 << (integerPartWidth - NumHighBits);
1109 if (~(Parts[PartCount - 1] | HighBitFill | 0x1))
1110 return false;
1111
1112 return true;
1113}
1114
1115bool IEEEFloat::isSignificandAllZeros() const {
1116 // Test if the significand excluding the integral bit is all zeros. This
1117 // allows us to test for binade boundaries.
1118 const integerPart *Parts = significandParts();
1119 const unsigned PartCount = partCountForBits(semantics->precision);
1120
1121 for (unsigned i = 0; i < PartCount - 1; i++)
1122 if (Parts[i])
1123 return false;
1124
1125 // Compute how many bits are used in the final word.
1126 const unsigned NumHighBits = getNumHighBits();
1127 assert(NumHighBits < integerPartWidth && "Can not have more high bits to "
1128 "clear than integerPartWidth");
1129 const integerPart HighBitMask = ~integerPart(0) >> NumHighBits;
1130
1131 if ((semantics->precision > 1) && (Parts[PartCount - 1] & HighBitMask))
1132 return false;
1133
1134 return true;
1135}
1136
1137bool IEEEFloat::isSignificandAllZerosExceptMSB() const {
1138 const integerPart *Parts = significandParts();
1139 const unsigned PartCount = partCountForBits(semantics->precision);
1140
1141 for (unsigned i = 0; i < PartCount - 1; i++) {
1142 if (Parts[i])
1143 return false;
1144 }
1145
1146 const unsigned NumHighBits = getNumHighBits();
1147 const integerPart MSBMask = integerPart(1)
1148 << (integerPartWidth - NumHighBits);
1149 return ((semantics->precision <= 1) || (Parts[PartCount - 1] == MSBMask));
1150}
1151
1153 bool IsMaxExp = isFiniteNonZero() && exponent == semantics->maxExponent;
1154 if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly &&
1155 semantics->nanEncoding == fltNanEncoding::AllOnes) {
1156 // The largest number by magnitude in our format will be the floating point
1157 // number with maximum exponent and with significand that is all ones except
1158 // the LSB.
1159 return (IsMaxExp && APFloat::hasSignificand(*semantics))
1160 ? isSignificandAllOnesExceptLSB()
1161 : IsMaxExp;
1162 } else {
1163 // The largest number by magnitude in our format will be the floating point
1164 // number with maximum exponent and with significand that is all ones.
1165 return IsMaxExp && isSignificandAllOnes();
1166 }
1167}
1168
1170 // This could be made more efficient; I'm going for obviously correct.
1171 if (!isFinite()) return false;
1172 IEEEFloat truncated = *this;
1173 truncated.roundToIntegral(rmTowardZero);
1174 return compare(truncated) == cmpEqual;
1175}
1176
1177bool IEEEFloat::bitwiseIsEqual(const IEEEFloat &rhs) const {
1178 if (this == &rhs)
1179 return true;
1180 if (semantics != rhs.semantics ||
1181 category != rhs.category ||
1182 sign != rhs.sign)
1183 return false;
1184 if (category==fcZero || category==fcInfinity)
1185 return true;
1186
1187 if (isFiniteNonZero() && exponent != rhs.exponent)
1188 return false;
1189
1190 return std::equal(significandParts(), significandParts() + partCount(),
1191 rhs.significandParts());
1192}
1193
1195 initialize(&ourSemantics);
1196 sign = 0;
1197 category = fcNormal;
1198 zeroSignificand();
1199 exponent = ourSemantics.precision - 1;
1200 significandParts()[0] = value;
1202}
1203
1205 initialize(&ourSemantics);
1206 // The Float8E8MOFNU format does not have a representation
1207 // for zero. So, use the closest representation instead.
1208 // Moreover, the all-zero encoding represents a valid
1209 // normal value (which is the smallestNormalized here).
1210 // Hence, we call makeSmallestNormalized (where category is
1211 // 'fcNormal') instead of makeZero (where category is 'fcZero').
1212 ourSemantics.hasZero ? makeZero(false) : makeSmallestNormalized(false);
1213}
1214
1215// Delegate to the previous constructor, because later copy constructor may
1216// actually inspects category, which can't be garbage.
1218 : IEEEFloat(ourSemantics) {}
1219
1221 initialize(rhs.semantics);
1222 assign(rhs);
1223}
1224
1225IEEEFloat::IEEEFloat(IEEEFloat &&rhs) : semantics(&APFloatBase::semBogus) {
1226 *this = std::move(rhs);
1227}
1228
1229IEEEFloat::~IEEEFloat() { freeSignificand(); }
1230
1231unsigned int IEEEFloat::partCount() const {
1232 return partCountForBits(semantics->precision + 1);
1233}
1234
1235const APFloat::integerPart *IEEEFloat::significandParts() const {
1236 return const_cast<IEEEFloat *>(this)->significandParts();
1237}
1238
1239APFloat::integerPart *IEEEFloat::significandParts() {
1240 if (partCount() > 1)
1241 return significand.parts;
1242 else
1243 return &significand.part;
1244}
1245
1246void IEEEFloat::zeroSignificand() {
1247 APInt::tcSet(significandParts(), 0, partCount());
1248}
1249
1250/* Increment an fcNormal floating point number's significand. */
1251void IEEEFloat::incrementSignificand() {
1252 [[maybe_unused]] integerPart carry =
1253 APInt::tcIncrement(significandParts(), partCount());
1254
1255 /* Our callers should never cause us to overflow. */
1256 assert(carry == 0);
1257}
1258
1259/* Add the significand of the RHS. Returns the carry flag. */
1260APFloat::integerPart IEEEFloat::addSignificand(const IEEEFloat &rhs) {
1261 integerPart *parts = significandParts();
1262
1263 assert(semantics == rhs.semantics);
1264 assert(exponent == rhs.exponent);
1265
1266 return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
1267}
1268
1269/* Subtract the significand of the RHS with a borrow flag. Returns
1270 the borrow flag. */
1271APFloat::integerPart IEEEFloat::subtractSignificand(const IEEEFloat &rhs,
1272 integerPart borrow) {
1273 integerPart *parts = significandParts();
1274
1275 assert(semantics == rhs.semantics);
1276 assert(exponent == rhs.exponent);
1277
1278 return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
1279 partCount());
1280}
1281
1282/* Multiply the significand of the RHS. If ADDEND is non-NULL, add it
1283 on to the full-precision result of the multiplication. Returns the
1284 lost fraction. */
1285lostFraction IEEEFloat::multiplySignificand(const IEEEFloat &rhs,
1286 IEEEFloat addend,
1287 bool ignoreAddend) {
1288 integerPart scratch[4];
1289 bool ignored;
1290
1291 assert(semantics == rhs.semantics);
1292
1293 unsigned precision = semantics->precision;
1294
1295 // Allocate space for twice as many bits as the original significand, plus one
1296 // extra bit for the addition to overflow into.
1297 unsigned newPartsCount = partCountForBits(precision * 2 + 1);
1298
1299 // FIXME: Replace with SmallVector<4>.
1300 integerPart *fullSignificand =
1301 newPartsCount > 4 ? new integerPart[newPartsCount] : scratch;
1302
1303 integerPart *lhsSignificand = significandParts();
1304 unsigned partsCount = partCount();
1305
1306 APInt::tcFullMultiply(fullSignificand, lhsSignificand,
1307 rhs.significandParts(), partsCount, partsCount);
1308
1309 lostFraction lost_fraction = lfExactlyZero;
1310 // One, not zero, based MSB.
1311 unsigned omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
1312 exponent += rhs.exponent;
1313
1314 // Assume the operands involved in the multiplication are single-precision
1315 // FP, and the two multiplicants are:
1316 // *this = a23 . a22 ... a0 * 2^e1
1317 // rhs = b23 . b22 ... b0 * 2^e2
1318 // the result of multiplication is:
1319 // *this = c48 c47 c46 . c45 ... c0 * 2^(e1+e2)
1320 // Note that there are three significant bits at the left-hand side of the
1321 // radix point: two for the multiplication, and an overflow bit for the
1322 // addition (that will always be zero at this point). Move the radix point
1323 // toward left by two bits, and adjust exponent accordingly.
1324 exponent += 2;
1325
1326 if (!ignoreAddend && addend.isNonZero()) {
1327 // The intermediate result of the multiplication has "2 * precision"
1328 // signicant bit; adjust the addend to be consistent with mul result.
1329 //
1330 Significand savedSignificand = significand;
1331 const fltSemantics *savedSemantics = semantics;
1332
1333 // Normalize our MSB to one below the top bit to allow for overflow.
1334 unsigned extendedPrecision = 2 * precision + 1;
1335 if (omsb != extendedPrecision - 1) {
1336 assert(extendedPrecision > omsb);
1337 APInt::tcShiftLeft(fullSignificand, newPartsCount,
1338 (extendedPrecision - 1) - omsb);
1339 exponent -= (extendedPrecision - 1) - omsb;
1340 }
1341
1342 /* Create new semantics. */
1343 fltSemantics extendedSemantics = *semantics;
1344 extendedSemantics.precision = extendedPrecision;
1345
1346 if (newPartsCount == 1)
1347 significand.part = fullSignificand[0];
1348 else
1349 significand.parts = fullSignificand;
1350 semantics = &extendedSemantics;
1351
1352 // Make a copy so we can convert it to the extended semantics.
1353 // Note that we cannot convert the addend directly, as the extendedSemantics
1354 // is a local variable (which we take a reference to).
1355 IEEEFloat extendedAddend(addend);
1356 [[maybe_unused]] opStatus status = extendedAddend.convert(
1357 extendedSemantics, APFloat::rmTowardZero, &ignored);
1358 assert(status == APFloat::opOK);
1359
1360 // Shift the significand of the addend right by one bit. This guarantees
1361 // that the high bit of the significand is zero (same as fullSignificand),
1362 // so the addition will overflow (if it does overflow at all) into the top bit.
1363 lost_fraction = extendedAddend.shiftSignificandRight(1);
1364 assert(lost_fraction == lfExactlyZero &&
1365 "Lost precision while shifting addend for fused-multiply-add.");
1366
1367 lost_fraction = addOrSubtractSignificand(extendedAddend, false);
1368
1369 /* Restore our state. */
1370 if (newPartsCount == 1)
1371 fullSignificand[0] = significand.part;
1372 significand = savedSignificand;
1373 semantics = savedSemantics;
1374
1375 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
1376 }
1377
1378 // Convert the result having "2 * precision" significant-bits back to the one
1379 // having "precision" significant-bits. First, move the radix point from
1380 // poision "2*precision - 1" to "precision - 1". The exponent need to be
1381 // adjusted by "2*precision - 1" - "precision - 1" = "precision".
1382 exponent -= precision + 1;
1383
1384 // In case MSB resides at the left-hand side of radix point, shift the
1385 // mantissa right by some amount to make sure the MSB reside right before
1386 // the radix point (i.e. "MSB . rest-significant-bits").
1387 //
1388 // Note that the result is not normalized when "omsb < precision". So, the
1389 // caller needs to call IEEEFloat::normalize() if normalized value is
1390 // expected.
1391 if (omsb > precision) {
1392 unsigned int bits, significantParts;
1393 lostFraction lf;
1394
1395 bits = omsb - precision;
1396 significantParts = partCountForBits(omsb);
1397 lf = shiftRight(fullSignificand, significantParts, bits);
1398 lost_fraction = combineLostFractions(lf, lost_fraction);
1399 exponent += bits;
1400 }
1401
1402 APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
1403
1404 if (newPartsCount > 4)
1405 delete [] fullSignificand;
1406
1407 return lost_fraction;
1408}
1409
1410lostFraction IEEEFloat::multiplySignificand(const IEEEFloat &rhs) {
1411 // When the given semantics has zero, the addend here is a zero.
1412 // i.e . it belongs to the 'fcZero' category.
1413 // But when the semantics does not support zero, we need to
1414 // explicitly convey that this addend should be ignored
1415 // for multiplication.
1416 return multiplySignificand(rhs, IEEEFloat(*semantics), !semantics->hasZero);
1417}
1418
1419/* Multiply the significands of LHS and RHS to DST. */
1420lostFraction IEEEFloat::divideSignificand(const IEEEFloat &rhs) {
1421 integerPart scratch[4];
1422
1423 assert(semantics == rhs.semantics);
1424
1425 integerPart *lhsSignificand = significandParts();
1426 const integerPart *rhsSignificand = rhs.significandParts();
1427 unsigned partsCount = partCount();
1428
1429 integerPart *dividend =
1430 partsCount > 2 ? new integerPart[partsCount * 2] : scratch;
1431 integerPart *divisor = dividend + partsCount;
1432
1433 /* Copy the dividend and divisor as they will be modified in-place. */
1434 for (unsigned i = 0; i < partsCount; i++) {
1435 dividend[i] = lhsSignificand[i];
1436 divisor[i] = rhsSignificand[i];
1437 lhsSignificand[i] = 0;
1438 }
1439
1440 exponent -= rhs.exponent;
1441
1442 unsigned int precision = semantics->precision;
1443
1444 /* Normalize the divisor. */
1445 unsigned bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
1446 if (bit) {
1447 exponent += bit;
1448 APInt::tcShiftLeft(divisor, partsCount, bit);
1449 }
1450
1451 /* Normalize the dividend. */
1452 bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
1453 if (bit) {
1454 exponent -= bit;
1455 APInt::tcShiftLeft(dividend, partsCount, bit);
1456 }
1457
1458 /* Ensure the dividend >= divisor initially for the loop below.
1459 Incidentally, this means that the division loop below is
1460 guaranteed to set the integer bit to one. */
1461 if (APInt::tcCompare(dividend, divisor, partsCount) < 0) {
1462 exponent--;
1463 APInt::tcShiftLeft(dividend, partsCount, 1);
1464 assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
1465 }
1466
1467 /* Long division. */
1468 for (bit = precision; bit; bit -= 1) {
1469 if (APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
1470 APInt::tcSubtract(dividend, divisor, 0, partsCount);
1471 APInt::tcSetBit(lhsSignificand, bit - 1);
1472 }
1473
1474 APInt::tcShiftLeft(dividend, partsCount, 1);
1475 }
1476
1477 /* Figure out the lost fraction. */
1478 int cmp = APInt::tcCompare(dividend, divisor, partsCount);
1479
1480 lostFraction lost_fraction;
1481 if (cmp > 0)
1482 lost_fraction = lfMoreThanHalf;
1483 else if (cmp == 0)
1484 lost_fraction = lfExactlyHalf;
1485 else if (APInt::tcIsZero(dividend, partsCount))
1486 lost_fraction = lfExactlyZero;
1487 else
1488 lost_fraction = lfLessThanHalf;
1489
1490 if (partsCount > 2)
1491 delete [] dividend;
1492
1493 return lost_fraction;
1494}
1495
1496unsigned int IEEEFloat::significandMSB() const {
1497 return APInt::tcMSB(significandParts(), partCount());
1498}
1499
1500unsigned int IEEEFloat::significandLSB() const {
1501 return APInt::tcLSB(significandParts(), partCount());
1502}
1503
1504/* Note that a zero result is NOT normalized to fcZero. */
1505lostFraction IEEEFloat::shiftSignificandRight(unsigned int bits) {
1506 /* Our exponent should not overflow. */
1507 assert((ExponentType) (exponent + bits) >= exponent);
1508
1509 exponent += bits;
1510
1511 return shiftRight(significandParts(), partCount(), bits);
1512}
1513
1514/* Shift the significand left BITS bits, subtract BITS from its exponent. */
1515void IEEEFloat::shiftSignificandLeft(unsigned int bits) {
1516 assert(bits < semantics->precision ||
1517 (semantics->precision == 1 && bits <= 1));
1518
1519 if (bits) {
1520 unsigned int partsCount = partCount();
1521
1522 APInt::tcShiftLeft(significandParts(), partsCount, bits);
1523 exponent -= bits;
1524
1525 assert(!APInt::tcIsZero(significandParts(), partsCount));
1526 }
1527}
1528
1530 assert(semantics == rhs.semantics);
1532 assert(rhs.isFiniteNonZero());
1533
1534 int compare = exponent - rhs.exponent;
1535
1536 /* If exponents are equal, do an unsigned bignum comparison of the
1537 significands. */
1538 if (compare == 0)
1539 compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
1540 partCount());
1541
1542 if (compare > 0)
1543 return cmpGreaterThan;
1544 else if (compare < 0)
1545 return cmpLessThan;
1546 else
1547 return cmpEqual;
1548}
1549
1550/* Set the least significant BITS bits of a bignum, clear the
1551 rest. */
1552static void tcSetLeastSignificantBits(APInt::WordType *dst, unsigned parts,
1553 unsigned bits) {
1554 unsigned i = 0;
1555 while (bits > APInt::APINT_BITS_PER_WORD) {
1556 dst[i++] = ~(APInt::WordType)0;
1558 }
1559
1560 if (bits)
1561 dst[i++] = ~(APInt::WordType)0 >> (APInt::APINT_BITS_PER_WORD - bits);
1562
1563 while (i < parts)
1564 dst[i++] = 0;
1565}
1566
1567/* Handle overflow. Sign is preserved. We either become infinity or
1568 the largest finite number. */
1569APFloat::opStatus IEEEFloat::handleOverflow(roundingMode rounding_mode) {
1571 /* Infinity? */
1572 if (rounding_mode == rmNearestTiesToEven ||
1573 rounding_mode == rmNearestTiesToAway ||
1574 (rounding_mode == rmTowardPositive && !sign) ||
1575 (rounding_mode == rmTowardNegative && sign)) {
1577 makeNaN(false, sign);
1578 else
1579 category = fcInfinity;
1580 return static_cast<opStatus>(opOverflow | opInexact);
1581 }
1582 }
1583
1584 /* Otherwise we become the largest finite number. */
1585 category = fcNormal;
1586 exponent = semantics->maxExponent;
1587 tcSetLeastSignificantBits(significandParts(), partCount(),
1588 semantics->precision);
1589 if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly &&
1590 semantics->nanEncoding == fltNanEncoding::AllOnes)
1591 APInt::tcClearBit(significandParts(), 0);
1592
1593 return opInexact;
1594}
1595
1596/* Returns TRUE if, when truncating the current number, with BIT the
1597 new LSB, with the given lost fraction and rounding mode, the result
1598 would need to be rounded away from zero (i.e., by increasing the
1599 signficand). This routine must work for fcZero of both signs, and
1600 fcNormal numbers. */
1601bool IEEEFloat::roundAwayFromZero(roundingMode rounding_mode,
1602 lostFraction lost_fraction,
1603 unsigned int bit) const {
1604 /* NaNs and infinities should not have lost fractions. */
1605 assert(isFiniteNonZero() || category == fcZero);
1606
1607 /* Current callers never pass this so we don't handle it. */
1608 assert(lost_fraction != lfExactlyZero);
1609
1610 switch (rounding_mode) {
1612 return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
1613
1615 if (lost_fraction == lfMoreThanHalf)
1616 return true;
1617
1618 /* Our zeroes don't have a significand to test. */
1619 if (lost_fraction == lfExactlyHalf && category != fcZero)
1620 return APInt::tcExtractBit(significandParts(), bit);
1621
1622 return false;
1623
1624 case rmTowardZero:
1625 return false;
1626
1627 case rmTowardPositive:
1628 return !sign;
1629
1630 case rmTowardNegative:
1631 return sign;
1632
1633 default:
1634 break;
1635 }
1636 llvm_unreachable("Invalid rounding mode found");
1637}
1638
1639APFloat::opStatus IEEEFloat::normalize(roundingMode rounding_mode,
1640 lostFraction lost_fraction) {
1641 if (!isFiniteNonZero())
1642 return opOK;
1643
1644 /* Before rounding normalize the exponent of fcNormal numbers. */
1645 /* One, not zero, based MSB. */
1646 unsigned omsb = significandMSB() + 1;
1647
1648 // Only skip this `if` if the value is exactly zero.
1649 if (omsb || lost_fraction != lfExactlyZero) {
1650 /* OMSB is numbered from 1. We want to place it in the integer
1651 bit numbered PRECISION if possible, with a compensating change in
1652 the exponent. */
1653 int exponentChange = omsb - semantics->precision;
1654
1655 /* If the resulting exponent is too high, overflow according to
1656 the rounding mode. */
1657 if (exponent + exponentChange > semantics->maxExponent)
1658 return handleOverflow(rounding_mode);
1659
1660 /* Subnormal numbers have exponent minExponent, and their MSB
1661 is forced based on that. */
1662 if (exponent + exponentChange < semantics->minExponent)
1663 exponentChange = semantics->minExponent - exponent;
1664
1665 /* Shifting left is easy as we don't lose precision. */
1666 if (exponentChange < 0) {
1667 assert(lost_fraction == lfExactlyZero);
1668
1669 shiftSignificandLeft(-exponentChange);
1670
1671 return opOK;
1672 }
1673
1674 if (exponentChange > 0) {
1675 lostFraction lf;
1676
1677 /* Shift right and capture any new lost fraction. */
1678 lf = shiftSignificandRight(exponentChange);
1679
1680 lost_fraction = combineLostFractions(lf, lost_fraction);
1681
1682 /* Keep OMSB up-to-date. */
1683 if (omsb > (unsigned) exponentChange)
1684 omsb -= exponentChange;
1685 else
1686 omsb = 0;
1687 }
1688 }
1689
1690 // The all-ones values is an overflow if NaN is all ones. If NaN is
1691 // represented by negative zero, then it is a valid finite value.
1692 if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly &&
1693 semantics->nanEncoding == fltNanEncoding::AllOnes &&
1694 exponent == semantics->maxExponent && isSignificandAllOnes())
1695 return handleOverflow(rounding_mode);
1696
1697 /* Now round the number according to rounding_mode given the lost
1698 fraction. */
1699
1700 /* As specified in IEEE 754, since we do not trap we do not report
1701 underflow for exact results. */
1702 if (lost_fraction == lfExactlyZero) {
1703 /* Canonicalize zeroes. */
1704 if (omsb == 0) {
1705 category = fcZero;
1706 if (semantics->nanEncoding == fltNanEncoding::NegativeZero)
1707 sign = false;
1708 if (!semantics->hasZero)
1710 }
1711
1712 return opOK;
1713 }
1714
1715 /* Increment the significand if we're rounding away from zero. */
1716 if (roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
1717 if (omsb == 0)
1718 exponent = semantics->minExponent;
1719
1720 incrementSignificand();
1721 omsb = significandMSB() + 1;
1722
1723 /* Did the significand increment overflow? */
1724 if (omsb == (unsigned) semantics->precision + 1) {
1725 /* Renormalize by incrementing the exponent and shifting our
1726 significand right one. However if we already have the
1727 maximum exponent we overflow to infinity. */
1728 if (exponent == semantics->maxExponent)
1729 // Invoke overflow handling with a rounding mode that will guarantee
1730 // that the result gets turned into the correct infinity representation.
1731 // This is needed instead of just setting the category to infinity to
1732 // account for 8-bit floating point types that have no inf, only NaN.
1733 return handleOverflow(sign ? rmTowardNegative : rmTowardPositive);
1734
1735 shiftSignificandRight(1);
1736
1737 return opInexact;
1738 }
1739
1740 // The all-ones values is an overflow if NaN is all ones. If NaN is
1741 // represented by negative zero, then it is a valid finite value.
1742 if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly &&
1743 semantics->nanEncoding == fltNanEncoding::AllOnes &&
1744 exponent == semantics->maxExponent && isSignificandAllOnes())
1745 return handleOverflow(rounding_mode);
1746 }
1747
1748 /* The normal case - we were and are not denormal, and any
1749 significand increment above didn't overflow. */
1750 if (omsb == semantics->precision)
1751 return opInexact;
1752
1753 /* We have a non-zero denormal. */
1754 assert(omsb < semantics->precision);
1755
1756 /* Canonicalize zeroes. */
1757 if (omsb == 0) {
1758 category = fcZero;
1759 if (semantics->nanEncoding == fltNanEncoding::NegativeZero)
1760 sign = false;
1761 // This condition handles the case where the semantics
1762 // does not have zero but uses the all-zero encoding
1763 // to represent the smallest normal value.
1764 if (!semantics->hasZero)
1766 }
1767
1768 /* The fcZero case is a denormal that underflowed to zero. */
1769 return (opStatus) (opUnderflow | opInexact);
1770}
1771
1772APFloat::opStatus IEEEFloat::addOrSubtractSpecials(const IEEEFloat &rhs,
1773 bool subtract) {
1774 switch (PackCategoriesIntoKey(category, rhs.category)) {
1775 default:
1776 llvm_unreachable(nullptr);
1777
1781 assign(rhs);
1782 [[fallthrough]];
1787 if (isSignaling()) {
1788 makeQuiet();
1789 return opInvalidOp;
1790 }
1791 return rhs.isSignaling() ? opInvalidOp : opOK;
1792
1796 return opOK;
1797
1800 category = fcInfinity;
1801 sign = rhs.sign ^ subtract;
1802 return opOK;
1803
1805 assign(rhs);
1806 sign = rhs.sign ^ subtract;
1807 return opOK;
1808
1810 /* Sign depends on rounding mode; handled by caller. */
1811 return opOK;
1812
1814 /* Differently signed infinities can only be validly
1815 subtracted. */
1816 if (((sign ^ rhs.sign)!=0) != subtract) {
1817 makeNaN();
1818 return opInvalidOp;
1819 }
1820
1821 return opOK;
1822
1824 return opDivByZero;
1825 }
1826}
1827
1828/* Add or subtract two normal numbers. */
1829lostFraction IEEEFloat::addOrSubtractSignificand(const IEEEFloat &rhs,
1830 bool subtract) {
1831 [[maybe_unused]] integerPart carry = 0;
1832 lostFraction lost_fraction;
1833
1834 /* Determine if the operation on the absolute values is effectively
1835 an addition or subtraction. */
1836 subtract ^= static_cast<bool>(sign ^ rhs.sign);
1837
1838 /* Are we bigger exponent-wise than the RHS? */
1839 int bits = exponent - rhs.exponent;
1840
1841 /* Subtraction is more subtle than one might naively expect. */
1842 if (subtract) {
1843 if ((bits < 0) && !semantics->hasSignedRepr)
1845 "This floating point format does not support signed values");
1846
1847 IEEEFloat temp_rhs(rhs);
1848 bool lost_fraction_is_from_rhs = false;
1849
1850 if (bits == 0)
1851 lost_fraction = lfExactlyZero;
1852 else if (bits > 0) {
1853 lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
1854 lost_fraction_is_from_rhs = true;
1855 shiftSignificandLeft(1);
1856 } else {
1857 lost_fraction = shiftSignificandRight(-bits - 1);
1858 temp_rhs.shiftSignificandLeft(1);
1859 }
1860
1861 // Should we reverse the subtraction.
1862 cmpResult cmp_result = compareAbsoluteValue(temp_rhs);
1863 if (cmp_result == cmpLessThan) {
1864 bool borrow =
1865 lost_fraction != lfExactlyZero && !lost_fraction_is_from_rhs;
1866 if (borrow) {
1867 // The lost fraction is being subtracted, borrow from the significand
1868 // and invert `lost_fraction`.
1869 if (lost_fraction == lfLessThanHalf)
1870 lost_fraction = lfMoreThanHalf;
1871 else if (lost_fraction == lfMoreThanHalf)
1872 lost_fraction = lfLessThanHalf;
1873 }
1874 carry = temp_rhs.subtractSignificand(*this, borrow);
1875 copySignificand(temp_rhs);
1876 sign = !sign;
1877 } else if (cmp_result == cmpGreaterThan) {
1878 bool borrow = lost_fraction != lfExactlyZero && lost_fraction_is_from_rhs;
1879 if (borrow) {
1880 // The lost fraction is being subtracted, borrow from the significand
1881 // and invert `lost_fraction`.
1882 if (lost_fraction == lfLessThanHalf)
1883 lost_fraction = lfMoreThanHalf;
1884 else if (lost_fraction == lfMoreThanHalf)
1885 lost_fraction = lfLessThanHalf;
1886 }
1887 carry = subtractSignificand(temp_rhs, borrow);
1888 } else { // cmpEqual
1889 zeroSignificand();
1890 if (lost_fraction != lfExactlyZero && lost_fraction_is_from_rhs) {
1891 // rhs is slightly larger due to the lost fraction, flip the sign.
1892 sign = !sign;
1893 }
1894 }
1895
1896 /* The code above is intended to ensure that no borrow is
1897 necessary. */
1898 assert(!carry);
1899 } else {
1900 if (bits > 0) {
1901 IEEEFloat temp_rhs(rhs);
1902
1903 lost_fraction = temp_rhs.shiftSignificandRight(bits);
1904 carry = addSignificand(temp_rhs);
1905 } else {
1906 lost_fraction = shiftSignificandRight(-bits);
1907 carry = addSignificand(rhs);
1908 }
1909
1910 /* We have a guard bit; generating a carry cannot happen. */
1911 assert(!carry);
1912 }
1913
1914 return lost_fraction;
1915}
1916
1917APFloat::opStatus IEEEFloat::multiplySpecials(const IEEEFloat &rhs) {
1918 switch (PackCategoriesIntoKey(category, rhs.category)) {
1919 default:
1920 llvm_unreachable(nullptr);
1921
1925 assign(rhs);
1926 sign = false;
1927 [[fallthrough]];
1932 sign ^= rhs.sign; // restore the original sign
1933 if (isSignaling()) {
1934 makeQuiet();
1935 return opInvalidOp;
1936 }
1937 return rhs.isSignaling() ? opInvalidOp : opOK;
1938
1942 category = fcInfinity;
1943 return opOK;
1944
1948 category = fcZero;
1949 return opOK;
1950
1953 makeNaN();
1954 return opInvalidOp;
1955
1957 return opOK;
1958 }
1959}
1960
1961APFloat::opStatus IEEEFloat::divideSpecials(const IEEEFloat &rhs) {
1962 switch (PackCategoriesIntoKey(category, rhs.category)) {
1963 default:
1964 llvm_unreachable(nullptr);
1965
1969 assign(rhs);
1970 sign = false;
1971 [[fallthrough]];
1976 sign ^= rhs.sign; // restore the original sign
1977 if (isSignaling()) {
1978 makeQuiet();
1979 return opInvalidOp;
1980 }
1981 return rhs.isSignaling() ? opInvalidOp : opOK;
1982
1987 return opOK;
1988
1990 category = fcZero;
1991 return opOK;
1992
1994 if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly)
1995 makeNaN(false, sign);
1996 else
1997 category = fcInfinity;
1998 return opDivByZero;
1999
2002 makeNaN();
2003 return opInvalidOp;
2004
2006 return opOK;
2007 }
2008}
2009
2010APFloat::opStatus IEEEFloat::modSpecials(const IEEEFloat &rhs) {
2011 switch (PackCategoriesIntoKey(category, rhs.category)) {
2012 default:
2013 llvm_unreachable(nullptr);
2014
2018 assign(rhs);
2019 [[fallthrough]];
2024 if (isSignaling()) {
2025 makeQuiet();
2026 return opInvalidOp;
2027 }
2028 return rhs.isSignaling() ? opInvalidOp : opOK;
2029
2033 return opOK;
2034
2040 makeNaN();
2041 return opInvalidOp;
2042
2044 return opOK;
2045 }
2046}
2047
2048APFloat::opStatus IEEEFloat::remainderSpecials(const IEEEFloat &rhs) {
2049 switch (PackCategoriesIntoKey(category, rhs.category)) {
2050 default:
2051 llvm_unreachable(nullptr);
2052
2056 assign(rhs);
2057 [[fallthrough]];
2062 if (isSignaling()) {
2063 makeQuiet();
2064 return opInvalidOp;
2065 }
2066 return rhs.isSignaling() ? opInvalidOp : opOK;
2067
2071 return opOK;
2072
2078 makeNaN();
2079 return opInvalidOp;
2080
2082 return opDivByZero; // fake status, indicating this is not a special case
2083 }
2084}
2085
2086/* Change sign. */
2088 // With NaN-as-negative-zero, neither NaN or negative zero can change
2089 // their signs.
2090 if (semantics->nanEncoding == fltNanEncoding::NegativeZero &&
2091 (isZero() || isNaN()))
2092 return;
2093 /* Look mummy, this one's easy. */
2094 sign = !sign;
2095}
2096
2097/* Normalized addition or subtraction. */
2098APFloat::opStatus IEEEFloat::addOrSubtract(const IEEEFloat &rhs,
2099 roundingMode rounding_mode,
2100 bool subtract) {
2101 opStatus fs = addOrSubtractSpecials(rhs, subtract);
2102
2103 /* This return code means it was not a simple case. */
2104 if (fs == opDivByZero) {
2105 lostFraction lost_fraction;
2106
2107 lost_fraction = addOrSubtractSignificand(rhs, subtract);
2108 fs = normalize(rounding_mode, lost_fraction);
2109
2110 /* Can only be zero if we lost no fraction. */
2111 assert(category != fcZero || lost_fraction == lfExactlyZero);
2112 }
2113
2114 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
2115 positive zero unless rounding to minus infinity, except that
2116 adding two like-signed zeroes gives that zero. */
2117 if (category == fcZero) {
2118 if (rhs.category != fcZero || (sign == rhs.sign) == subtract)
2119 sign = (rounding_mode == rmTowardNegative);
2120 // NaN-in-negative-zero means zeros need to be normalized to +0.
2121 if (semantics->nanEncoding == fltNanEncoding::NegativeZero)
2122 sign = false;
2123 }
2124
2125 return fs;
2126}
2127
2128/* Normalized addition. */
2130 roundingMode rounding_mode) {
2131 return addOrSubtract(rhs, rounding_mode, false);
2132}
2133
2134/* Normalized subtraction. */
2136 roundingMode rounding_mode) {
2137 return addOrSubtract(rhs, rounding_mode, true);
2138}
2139
2140/* Normalized multiply. */
2142 roundingMode rounding_mode) {
2143 sign ^= rhs.sign;
2144 opStatus fs = multiplySpecials(rhs);
2145
2146 if (isZero() && semantics->nanEncoding == fltNanEncoding::NegativeZero)
2147 sign = false;
2148 if (isFiniteNonZero()) {
2149 lostFraction lost_fraction = multiplySignificand(rhs);
2150 fs = normalize(rounding_mode, lost_fraction);
2151 if (lost_fraction != lfExactlyZero)
2152 fs = (opStatus) (fs | opInexact);
2153 }
2154
2155 return fs;
2156}
2157
2158/* Normalized divide. */
2160 roundingMode rounding_mode) {
2161 sign ^= rhs.sign;
2162 opStatus fs = divideSpecials(rhs);
2163
2164 if (isZero() && semantics->nanEncoding == fltNanEncoding::NegativeZero)
2165 sign = false;
2166 if (isFiniteNonZero()) {
2167 lostFraction lost_fraction = divideSignificand(rhs);
2168 fs = normalize(rounding_mode, lost_fraction);
2169 if (lost_fraction != lfExactlyZero)
2170 fs = (opStatus) (fs | opInexact);
2171 }
2172
2173 return fs;
2174}
2175
2176/* Normalized remainder. */
2178 unsigned int origSign = sign;
2179
2180 // First handle the special cases.
2181 opStatus fs = remainderSpecials(rhs);
2182 if (fs != opDivByZero)
2183 return fs;
2184
2185 fs = opOK;
2186
2187 // Make sure the current value is less than twice the denom. If the addition
2188 // did not succeed (an overflow has happened), which means that the finite
2189 // value we currently posses must be less than twice the denom (as we are
2190 // using the same semantics).
2191 IEEEFloat P2 = rhs;
2192 if (P2.add(rhs, rmNearestTiesToEven) == opOK) {
2193 fs = mod(P2);
2194 assert(fs == opOK);
2195 }
2196
2197 // Lets work with absolute numbers.
2198 IEEEFloat P = rhs;
2199 P.sign = false;
2200 sign = false;
2201
2202 //
2203 // To calculate the remainder we use the following scheme.
2204 //
2205 // The remainder is defained as follows:
2206 //
2207 // remainder = numer - rquot * denom = x - r * p
2208 //
2209 // Where r is the result of: x/p, rounded toward the nearest integral value
2210 // (with halfway cases rounded toward the even number).
2211 //
2212 // Currently, (after x mod 2p):
2213 // r is the number of 2p's present inside x, which is inherently, an even
2214 // number of p's.
2215 //
2216 // We may split the remaining calculation into 4 options:
2217 // - if x < 0.5p then we round to the nearest number with is 0, and are done.
2218 // - if x == 0.5p then we round to the nearest even number which is 0, and we
2219 // are done as well.
2220 // - if 0.5p < x < p then we round to nearest number which is 1, and we have
2221 // to subtract 1p at least once.
2222 // - if x >= p then we must subtract p at least once, as x must be a
2223 // remainder.
2224 //
2225 // By now, we were done, or we added 1 to r, which in turn, now an odd number.
2226 //
2227 // We can now split the remaining calculation to the following 3 options:
2228 // - if x < 0.5p then we round to the nearest number with is 0, and are done.
2229 // - if x == 0.5p then we round to the nearest even number. As r is odd, we
2230 // must round up to the next even number. so we must subtract p once more.
2231 // - if x > 0.5p (and inherently x < p) then we must round r up to the next
2232 // integral, and subtract p once more.
2233 //
2234
2235 // Extend the semantics to prevent an overflow/underflow or inexact result.
2236 bool losesInfo;
2237 fltSemantics extendedSemantics = *semantics;
2238 extendedSemantics.maxExponent++;
2239 extendedSemantics.minExponent--;
2240 extendedSemantics.precision += 2;
2241
2242 IEEEFloat VEx = *this;
2243 fs = VEx.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
2244 assert(fs == opOK && !losesInfo);
2245 IEEEFloat PEx = P;
2246 fs = PEx.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
2247 assert(fs == opOK && !losesInfo);
2248
2249 // It is simpler to work with 2x instead of 0.5p, and we do not need to lose
2250 // any fraction.
2251 fs = VEx.add(VEx, rmNearestTiesToEven);
2252 assert(fs == opOK);
2253
2254 if (VEx.compare(PEx) == cmpGreaterThan) {
2256 assert(fs == opOK);
2257
2258 // Make VEx = this.add(this), but because we have different semantics, we do
2259 // not want to `convert` again, so we just subtract PEx twice (which equals
2260 // to the desired value).
2261 fs = VEx.subtract(PEx, rmNearestTiesToEven);
2262 assert(fs == opOK);
2263 fs = VEx.subtract(PEx, rmNearestTiesToEven);
2264 assert(fs == opOK);
2265
2266 cmpResult result = VEx.compare(PEx);
2267 if (result == cmpGreaterThan || result == cmpEqual) {
2269 assert(fs == opOK);
2270 }
2271 }
2272
2273 if (isZero()) {
2274 sign = origSign; // IEEE754 requires this
2275 if (semantics->nanEncoding == fltNanEncoding::NegativeZero)
2276 // But some 8-bit floats only have positive 0.
2277 sign = false;
2278 } else {
2279 sign ^= origSign;
2280 }
2281 return fs;
2282}
2283
2284/* Normalized llvm frem (C fmod). */
2286 opStatus fs = modSpecials(rhs);
2287 unsigned int origSign = sign;
2288
2289 while (isFiniteNonZero() && rhs.isFiniteNonZero() &&
2291 int Exp = ilogb(*this) - ilogb(rhs);
2292 IEEEFloat V = scalbn(rhs, Exp, rmNearestTiesToEven);
2293 // V can overflow to NaN with fltNonfiniteBehavior::NanOnly, so explicitly
2294 // check for it.
2295 if (V.isNaN() || compareAbsoluteValue(V) == cmpLessThan)
2296 V = scalbn(rhs, Exp - 1, rmNearestTiesToEven);
2297 V.sign = sign;
2298
2300
2301 // When the semantics supports zero, this loop's
2302 // exit-condition is handled by the 'isFiniteNonZero'
2303 // category check above. However, when the semantics
2304 // does not have 'fcZero' and we have reached the
2305 // minimum possible value, (and any further subtract
2306 // will underflow to the same value) explicitly
2307 // provide an exit-path here.
2308 if (!semantics->hasZero && this->isSmallest())
2309 break;
2310
2311 assert(fs==opOK);
2312 }
2313 if (isZero()) {
2314 sign = origSign; // fmod requires this
2315 if (semantics->nanEncoding == fltNanEncoding::NegativeZero)
2316 sign = false;
2317 }
2318 return fs;
2319}
2320
2321/* Normalized fused-multiply-add. */
2323 const IEEEFloat &addend,
2324 roundingMode rounding_mode) {
2325 opStatus fs;
2326
2327 /* Post-multiplication sign, before addition. */
2328 sign ^= multiplicand.sign;
2329
2330 /* If and only if all arguments are normal do we need to do an
2331 extended-precision calculation. */
2332 if (isFiniteNonZero() &&
2333 multiplicand.isFiniteNonZero() &&
2334 addend.isFinite()) {
2335 lostFraction lost_fraction;
2336
2337 lost_fraction = multiplySignificand(multiplicand, addend);
2338 fs = normalize(rounding_mode, lost_fraction);
2339 if (lost_fraction != lfExactlyZero)
2340 fs = (opStatus) (fs | opInexact);
2341
2342 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
2343 positive zero unless rounding to minus infinity, except that
2344 adding two like-signed zeroes gives that zero. */
2345 if (category == fcZero && !(fs & opUnderflow) && sign != addend.sign) {
2346 sign = (rounding_mode == rmTowardNegative);
2347 if (semantics->nanEncoding == fltNanEncoding::NegativeZero)
2348 sign = false;
2349 }
2350 } else {
2351 fs = multiplySpecials(multiplicand);
2352
2353 /* FS can only be opOK or opInvalidOp. There is no more work
2354 to do in the latter case. The IEEE-754R standard says it is
2355 implementation-defined in this case whether, if ADDEND is a
2356 quiet NaN, we raise invalid op; this implementation does so.
2357
2358 If we need to do the addition we can do so with normal
2359 precision. */
2360 if (fs == opOK)
2361 fs = addOrSubtract(addend, rounding_mode, false);
2362 }
2363
2364 return fs;
2365}
2366
2367/* Rounding-mode correct round to integral value. */
2369 if (isInfinity())
2370 // [IEEE Std 754-2008 6.1]:
2371 // The behavior of infinity in floating-point arithmetic is derived from the
2372 // limiting cases of real arithmetic with operands of arbitrarily
2373 // large magnitude, when such a limit exists.
2374 // ...
2375 // Operations on infinite operands are usually exact and therefore signal no
2376 // exceptions ...
2377 return opOK;
2378
2379 if (isNaN()) {
2380 if (isSignaling()) {
2381 // [IEEE Std 754-2008 6.2]:
2382 // Under default exception handling, any operation signaling an invalid
2383 // operation exception and for which a floating-point result is to be
2384 // delivered shall deliver a quiet NaN.
2385 makeQuiet();
2386 // [IEEE Std 754-2008 6.2]:
2387 // Signaling NaNs shall be reserved operands that, under default exception
2388 // handling, signal the invalid operation exception(see 7.2) for every
2389 // general-computational and signaling-computational operation except for
2390 // the conversions described in 5.12.
2391 return opInvalidOp;
2392 } else {
2393 // [IEEE Std 754-2008 6.2]:
2394 // For an operation with quiet NaN inputs, other than maximum and minimum
2395 // operations, if a floating-point result is to be delivered the result
2396 // shall be a quiet NaN which should be one of the input NaNs.
2397 // ...
2398 // Every general-computational and quiet-computational operation involving
2399 // one or more input NaNs, none of them signaling, shall signal no
2400 // exception, except fusedMultiplyAdd might signal the invalid operation
2401 // exception(see 7.2).
2402 return opOK;
2403 }
2404 }
2405
2406 if (isZero()) {
2407 // [IEEE Std 754-2008 6.3]:
2408 // ... the sign of the result of conversions, the quantize operation, the
2409 // roundToIntegral operations, and the roundToIntegralExact(see 5.3.1) is
2410 // the sign of the first or only operand.
2411 return opOK;
2412 }
2413
2414 // If the exponent is large enough, we know that this value is already
2415 // integral, and the arithmetic below would potentially cause it to saturate
2416 // to +/-Inf. Bail out early instead.
2417 if (exponent + 1 >= (int)APFloat::semanticsPrecision(*semantics))
2418 return opOK;
2419
2420 // The algorithm here is quite simple: we add 2^(p-1), where p is the
2421 // precision of our format, and then subtract it back off again. The choice
2422 // of rounding modes for the addition/subtraction determines the rounding mode
2423 // for our integral rounding as well.
2424 // NOTE: When the input value is negative, we do subtraction followed by
2425 // addition instead.
2426 APInt IntegerConstant(NextPowerOf2(APFloat::semanticsPrecision(*semantics)),
2427 1);
2428 IntegerConstant <<= APFloat::semanticsPrecision(*semantics) - 1;
2429 IEEEFloat MagicConstant(*semantics);
2430 opStatus fs = MagicConstant.convertFromAPInt(IntegerConstant, false,
2432 assert(fs == opOK);
2433 MagicConstant.sign = sign;
2434
2435 // Preserve the input sign so that we can handle the case of zero result
2436 // correctly.
2437 bool inputSign = isNegative();
2438
2439 fs = add(MagicConstant, rounding_mode);
2440
2441 // Current value and 'MagicConstant' are both integers, so the result of the
2442 // subtraction is always exact according to Sterbenz' lemma.
2443 subtract(MagicConstant, rounding_mode);
2444
2445 // Restore the input sign.
2446 if (inputSign != isNegative())
2447 changeSign();
2448
2449 return fs;
2450}
2451
2452/* Comparison requires normalized numbers. */
2454 assert(semantics == rhs.semantics);
2455
2456 switch (PackCategoriesIntoKey(category, rhs.category)) {
2457 default:
2458 llvm_unreachable(nullptr);
2459
2467 return cmpUnordered;
2468
2472 if (sign)
2473 return cmpLessThan;
2474 else
2475 return cmpGreaterThan;
2476
2480 if (rhs.sign)
2481 return cmpGreaterThan;
2482 else
2483 return cmpLessThan;
2484
2486 if (sign == rhs.sign)
2487 return cmpEqual;
2488 else if (sign)
2489 return cmpLessThan;
2490 else
2491 return cmpGreaterThan;
2492
2494 return cmpEqual;
2495
2497 break;
2498 }
2499
2500 cmpResult result;
2501 /* Two normal numbers. Do they have the same sign? */
2502 if (sign != rhs.sign) {
2503 if (sign)
2504 result = cmpLessThan;
2505 else
2506 result = cmpGreaterThan;
2507 } else {
2508 /* Compare absolute values; invert result if negative. */
2509 result = compareAbsoluteValue(rhs);
2510
2511 if (sign) {
2512 if (result == cmpLessThan)
2513 result = cmpGreaterThan;
2514 else if (result == cmpGreaterThan)
2515 result = cmpLessThan;
2516 }
2517 }
2518
2519 return result;
2520}
2521
2522/// IEEEFloat::convert - convert a value of one floating point type to another.
2523/// The return value corresponds to the IEEE754 exceptions. *losesInfo
2524/// records whether the transformation lost information, i.e. whether
2525/// converting the result back to the original type will produce the
2526/// original value (this is almost the same as return value==fsOK, but there
2527/// are edge cases where this is not so).
2528
2530 roundingMode rounding_mode,
2531 bool *losesInfo) {
2532 opStatus fs;
2533 const fltSemantics &fromSemantics = *semantics;
2534 bool is_signaling = isSignaling();
2535
2537 unsigned newPartCount = partCountForBits(toSemantics.precision + 1);
2538 unsigned oldPartCount = partCount();
2539 int shift = toSemantics.precision - fromSemantics.precision;
2540
2541 bool X86SpecialNan = false;
2542 if (&fromSemantics == &APFloatBase::semX87DoubleExtended &&
2543 &toSemantics != &APFloatBase::semX87DoubleExtended && category == fcNaN &&
2544 (!(*significandParts() & 0x8000000000000000ULL) ||
2545 !(*significandParts() & 0x4000000000000000ULL))) {
2546 // x86 has some unusual NaNs which cannot be represented in any other
2547 // format; note them here.
2548 X86SpecialNan = true;
2549 }
2550
2551 // If this is a truncation of a denormal number, and the target semantics
2552 // has larger exponent range than the source semantics (this can happen
2553 // when truncating from PowerPC double-double to double format), the
2554 // right shift could lose result mantissa bits. Adjust exponent instead
2555 // of performing excessive shift.
2556 // Also do a similar trick in case shifting denormal would produce zero
2557 // significand as this case isn't handled correctly by normalize.
2558 if (shift < 0 && isFiniteNonZero()) {
2559 int omsb = significandMSB() + 1;
2560 int exponentChange = omsb - fromSemantics.precision;
2561 if (exponent + exponentChange < toSemantics.minExponent)
2562 exponentChange = toSemantics.minExponent - exponent;
2563 exponentChange = std::max(exponentChange, shift);
2564 if (exponentChange < 0) {
2565 shift -= exponentChange;
2566 exponent += exponentChange;
2567 } else if (omsb <= -shift) {
2568 exponentChange = omsb + shift - 1; // leave at least one bit set
2569 shift -= exponentChange;
2570 exponent += exponentChange;
2571 }
2572 }
2573
2574 // If this is a truncation, perform the shift before we narrow the storage.
2575 if (shift < 0 && (isFiniteNonZero() ||
2576 (category == fcNaN && semantics->nonFiniteBehavior !=
2578 lostFraction = shiftRight(significandParts(), oldPartCount, -shift);
2579
2580 // Fix the storage so it can hold to new value.
2581 if (newPartCount > oldPartCount) {
2582 // The new type requires more storage; make it available.
2583 integerPart *newParts;
2584 newParts = new integerPart[newPartCount];
2585 APInt::tcSet(newParts, 0, newPartCount);
2586 if (isFiniteNonZero() || category==fcNaN)
2587 APInt::tcAssign(newParts, significandParts(), oldPartCount);
2588 freeSignificand();
2589 significand.parts = newParts;
2590 } else if (newPartCount == 1 && oldPartCount != 1) {
2591 // Switch to built-in storage for a single part.
2592 integerPart newPart = 0;
2593 if (isFiniteNonZero() || category==fcNaN)
2594 newPart = significandParts()[0];
2595 freeSignificand();
2596 significand.part = newPart;
2597 }
2598
2599 // Now that we have the right storage, switch the semantics.
2600 semantics = &toSemantics;
2601
2602 // If this is an extension, perform the shift now that the storage is
2603 // available.
2604 if (shift > 0 && (isFiniteNonZero() || category==fcNaN))
2605 APInt::tcShiftLeft(significandParts(), newPartCount, shift);
2606
2607 if (isFiniteNonZero()) {
2608 fs = normalize(rounding_mode, lostFraction);
2609 *losesInfo = (fs != opOK);
2610 } else if (category == fcNaN) {
2611 if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly) {
2612 *losesInfo =
2614 makeNaN(false, sign);
2615 fs = is_signaling ? opInvalidOp : opOK;
2616 } else {
2617 // If NaN is negative zero, we need to create a new NaN to avoid
2618 // converting NaN to -Inf.
2619 if (fromSemantics.nanEncoding == fltNanEncoding::NegativeZero &&
2620 semantics->nanEncoding != fltNanEncoding::NegativeZero)
2621 makeNaN(false, false);
2622
2623 // If the source has no significand, there are no payload bits to carry
2624 // over, and an all-zero significand would encode an Inf. Create a new
2625 // NaN.
2626 if (!APFloat::hasSignificand(fromSemantics))
2627 makeNaN(false, sign);
2628
2629 *losesInfo = lostFraction != lfExactlyZero || X86SpecialNan;
2630
2631 // For x87 extended precision, we want to make a NaN, not a special NaN
2632 // if the input wasn't special either.
2633 if (!X86SpecialNan && semantics == &APFloatBase::semX87DoubleExtended)
2634 APInt::tcSetBit(significandParts(), semantics->precision - 1);
2635
2636 // Convert of sNaN creates qNaN and raises an exception (invalid op).
2637 // This also guarantees that a sNaN does not become Inf on a truncation
2638 // that loses all payload bits.
2639 if (is_signaling) {
2640 makeQuiet();
2641 fs = opInvalidOp;
2642 } else {
2643 fs = opOK;
2644 }
2645 }
2646 } else if (category == fcInfinity &&
2647 semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly) {
2648 makeNaN(false, sign);
2649 *losesInfo = true;
2650 fs = opInexact;
2651 } else if (category == fcZero &&
2652 semantics->nanEncoding == fltNanEncoding::NegativeZero) {
2653 // Negative zero loses info, but positive zero doesn't.
2654 *losesInfo =
2655 fromSemantics.nanEncoding != fltNanEncoding::NegativeZero && sign;
2656 fs = *losesInfo ? opInexact : opOK;
2657 // NaN is negative zero means -0 -> +0, which can lose information
2658 sign = false;
2659 } else {
2660 *losesInfo = false;
2661 fs = opOK;
2662 }
2663
2664 // The target may have no encoding for a negative value, or none for zero.
2665 // The paths above only report what rounding lost, so report these here too:
2666 // a caller that checks losesInfo would otherwise accept a result the target
2667 // cannot represent, and printing that result asserts.
2668 if ((sign && !semantics->hasSignedRepr) ||
2669 (category == fcZero && !semantics->hasZero)) {
2670 *losesInfo = true;
2671 if (fs == opOK)
2672 fs = opInexact;
2673 }
2674
2675 if (category == fcZero && !semantics->hasZero)
2677 return fs;
2678}
2679
2680/* Convert a floating point number to an integer according to the
2681 rounding mode. If the rounded integer value is out of range this
2682 returns an invalid operation exception and the contents of the
2683 destination parts are unspecified. If the rounded value is in
2684 range but the floating point number is not the exact integer, the C
2685 standard doesn't require an inexact exception to be raised. IEEE
2686 854 does require it so we do that.
2687
2688 Note that for conversions to integer type the C standard requires
2689 round-to-zero to always be used. */
2690APFloat::opStatus IEEEFloat::convertToSignExtendedInteger(
2691 MutableArrayRef<integerPart> parts, unsigned int width, bool isSigned,
2692 roundingMode rounding_mode, bool *isExact) const {
2693 *isExact = false;
2694
2695 /* Handle the three special cases first. */
2696 if (category == fcInfinity || category == fcNaN)
2697 return opInvalidOp;
2698
2699 unsigned dstPartsCount = partCountForBits(width);
2700 assert(dstPartsCount <= parts.size() && "Integer too big");
2701
2702 if (category == fcZero) {
2703 APInt::tcSet(parts.data(), 0, dstPartsCount);
2704 // Negative zero can't be represented as an int.
2705 *isExact = !sign;
2706 return opOK;
2707 }
2708
2709 const integerPart *src = significandParts();
2710
2711 unsigned truncatedBits;
2712 /* Step 1: place our absolute value, with any fraction truncated, in
2713 the destination. */
2714 if (exponent < 0) {
2715 /* Our absolute value is less than one; truncate everything. */
2716 APInt::tcSet(parts.data(), 0, dstPartsCount);
2717 /* For exponent -1 the integer bit represents .5, look at that.
2718 For smaller exponents leftmost truncated bit is 0. */
2719 truncatedBits = semantics->precision -1U - exponent;
2720 } else {
2721 /* We want the most significant (exponent + 1) bits; the rest are
2722 truncated. */
2723 unsigned int bits = exponent + 1U;
2724
2725 /* Hopelessly large in magnitude? */
2726 if (bits > width)
2727 return opInvalidOp;
2728
2729 if (bits < semantics->precision) {
2730 /* We truncate (semantics->precision - bits) bits. */
2731 truncatedBits = semantics->precision - bits;
2732 APInt::tcExtract(parts.data(), dstPartsCount, src, bits, truncatedBits);
2733 } else {
2734 /* We want at least as many bits as are available. */
2735 APInt::tcExtract(parts.data(), dstPartsCount, src, semantics->precision,
2736 0);
2737 APInt::tcShiftLeft(parts.data(), dstPartsCount,
2738 bits - semantics->precision);
2739 truncatedBits = 0;
2740 }
2741 }
2742
2743 /* Step 2: work out any lost fraction, and increment the absolute
2744 value if we would round away from zero. */
2745 lostFraction lost_fraction;
2746 if (truncatedBits) {
2747 lost_fraction = lostFractionThroughTruncation(src, partCount(),
2748 truncatedBits);
2749 if (lost_fraction != lfExactlyZero &&
2750 roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
2751 if (APInt::tcIncrement(parts.data(), dstPartsCount))
2752 return opInvalidOp; /* Overflow. */
2753 }
2754 } else {
2755 lost_fraction = lfExactlyZero;
2756 }
2757
2758 /* Step 3: check if we fit in the destination. */
2759 unsigned int omsb = APInt::tcMSB(parts.data(), dstPartsCount) + 1;
2760
2761 if (sign) {
2762 if (!isSigned) {
2763 /* Negative numbers cannot be represented as unsigned. */
2764 if (omsb != 0)
2765 return opInvalidOp;
2766 } else {
2767 /* It takes omsb bits to represent the unsigned integer value.
2768 We lose a bit for the sign, but care is needed as the
2769 maximally negative integer is a special case. */
2770 if (omsb == width &&
2771 APInt::tcLSB(parts.data(), dstPartsCount) + 1 != omsb)
2772 return opInvalidOp;
2773
2774 /* This case can happen because of rounding. */
2775 if (omsb > width)
2776 return opInvalidOp;
2777 }
2778
2779 APInt::tcNegate (parts.data(), dstPartsCount);
2780 } else {
2781 if (omsb >= width + !isSigned)
2782 return opInvalidOp;
2783 }
2784
2785 if (lost_fraction == lfExactlyZero) {
2786 *isExact = true;
2787 return opOK;
2788 }
2789 return opInexact;
2790}
2791
2792/* Same as convertToSignExtendedInteger, except we provide
2793 deterministic values in case of an invalid operation exception,
2794 namely zero for NaNs and the minimal or maximal value respectively
2795 for underflow or overflow.
2796 The *isExact output tells whether the result is exact, in the sense
2797 that converting it back to the original floating point type produces
2798 the original value. This is almost equivalent to result==opOK,
2799 except for negative zeroes.
2800*/
2803 unsigned int width, bool isSigned,
2804 roundingMode rounding_mode, bool *isExact) const {
2805 opStatus fs = convertToSignExtendedInteger(parts, width, isSigned,
2806 rounding_mode, isExact);
2807
2808 if (fs == opInvalidOp) {
2809 unsigned int bits, dstPartsCount;
2810
2811 dstPartsCount = partCountForBits(width);
2812 assert(dstPartsCount <= parts.size() && "Integer too big");
2813
2814 if (category == fcNaN)
2815 bits = 0;
2816 else if (sign)
2817 bits = isSigned;
2818 else
2819 bits = width - isSigned;
2820
2821 tcSetLeastSignificantBits(parts.data(), dstPartsCount, bits);
2822 if (sign && isSigned)
2823 APInt::tcShiftLeft(parts.data(), dstPartsCount, width - 1);
2824 }
2825
2826 return fs;
2827}
2828
2829/* Convert an unsigned integer SRC to a floating point number,
2830 rounding according to ROUNDING_MODE. The sign of the floating
2831 point number is not modified. */
2832APFloat::opStatus IEEEFloat::convertFromUnsignedParts(
2833 const integerPart *src, unsigned int srcCount, roundingMode rounding_mode) {
2834 category = fcNormal;
2835 unsigned omsb = APInt::tcMSB(src, srcCount) + 1;
2836 integerPart *dst = significandParts();
2837 unsigned dstCount = partCount();
2838 unsigned precision = semantics->precision;
2839
2840 /* We want the most significant PRECISION bits of SRC. There may not
2841 be that many; extract what we can. */
2842 lostFraction lost_fraction;
2843 if (precision <= omsb) {
2844 exponent = omsb - 1;
2845 lost_fraction = lostFractionThroughTruncation(src, srcCount,
2846 omsb - precision);
2847 APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
2848 } else {
2849 exponent = precision - 1;
2850 lost_fraction = lfExactlyZero;
2851 APInt::tcExtract(dst, dstCount, src, omsb, 0);
2852 }
2853
2854 return normalize(rounding_mode, lost_fraction);
2855}
2856
2858 roundingMode rounding_mode) {
2859 unsigned int partCount = Val.getNumWords();
2860 APInt api = Val;
2861
2862 sign = false;
2863 if (isSigned && api.isNegative()) {
2864 sign = true;
2865 api = -api;
2866 }
2867
2868 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
2869}
2870
2872IEEEFloat::convertFromHexadecimalString(StringRef s,
2873 roundingMode rounding_mode) {
2874 lostFraction lost_fraction = lfExactlyZero;
2875
2876 category = fcNormal;
2877 zeroSignificand();
2878 exponent = 0;
2879
2880 integerPart *significand = significandParts();
2881 unsigned partsCount = partCount();
2882 unsigned bitPos = partsCount * integerPartWidth;
2883 bool computedTrailingFraction = false;
2884
2885 // Skip leading zeroes and any (hexa)decimal point.
2886 StringRef::iterator begin = s.begin();
2887 StringRef::iterator end = s.end();
2889 auto PtrOrErr = skipLeadingZeroesAndAnyDot(begin, end, &dot);
2890 if (!PtrOrErr)
2891 return PtrOrErr.takeError();
2892 StringRef::iterator p = *PtrOrErr;
2893 StringRef::iterator firstSignificantDigit = p;
2894
2895 while (p != end) {
2896 integerPart hex_value;
2897
2898 if (*p == '.') {
2899 if (dot != end)
2900 return createError("String contains multiple dots");
2901 dot = p++;
2902 continue;
2903 }
2904
2905 hex_value = hexDigitValue(*p);
2906 if (hex_value == UINT_MAX)
2907 break;
2908
2909 p++;
2910
2911 // Store the number while we have space.
2912 if (bitPos) {
2913 bitPos -= 4;
2914 hex_value <<= bitPos % integerPartWidth;
2915 significand[bitPos / integerPartWidth] |= hex_value;
2916 } else if (!computedTrailingFraction) {
2917 auto FractOrErr = trailingHexadecimalFraction(p, end, hex_value);
2918 if (!FractOrErr)
2919 return FractOrErr.takeError();
2920 lost_fraction = *FractOrErr;
2921 computedTrailingFraction = true;
2922 }
2923 }
2924
2925 /* Hex floats require an exponent but not a hexadecimal point. */
2926 if (p == end)
2927 return createError("Hex strings require an exponent");
2928 if (*p != 'p' && *p != 'P')
2929 return createError("Invalid character in significand");
2930 if (p == begin)
2931 return createError("Significand has no digits");
2932 if (dot != end && p - begin == 1)
2933 return createError("Significand has no digits");
2934
2935 /* Ignore the exponent if we are zero. */
2936 if (p != firstSignificantDigit) {
2937 int expAdjustment;
2938
2939 /* Implicit hexadecimal point? */
2940 if (dot == end)
2941 dot = p;
2942
2943 /* Calculate the exponent adjustment implicit in the number of
2944 significant digits. */
2945 expAdjustment = static_cast<int>(dot - firstSignificantDigit);
2946 if (expAdjustment < 0)
2947 expAdjustment++;
2948 expAdjustment = expAdjustment * 4 - 1;
2949
2950 /* Adjust for writing the significand starting at the most
2951 significant nibble. */
2952 expAdjustment += semantics->precision;
2953 expAdjustment -= partsCount * integerPartWidth;
2954
2955 /* Adjust for the given exponent. */
2956 auto ExpOrErr = totalExponent(p + 1, end, expAdjustment);
2957 if (!ExpOrErr)
2958 return ExpOrErr.takeError();
2959 exponent = *ExpOrErr;
2960 }
2961
2962 return normalize(rounding_mode, lost_fraction);
2963}
2964
2966IEEEFloat::roundSignificandWithExponent(const integerPart *decSigParts,
2967 unsigned sigPartCount, int exp,
2968 roundingMode rounding_mode) {
2969 fltSemantics calcSemantics = { 32767, -32767, 0, 0 };
2971
2972 bool isNearest = rounding_mode == rmNearestTiesToEven ||
2973 rounding_mode == rmNearestTiesToAway;
2974
2975 unsigned parts = partCountForBits(semantics->precision + 11);
2976
2977 /* Calculate pow(5, abs(exp)). */
2978 unsigned pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp : -exp);
2979
2980 for (;; parts *= 2) {
2981 unsigned int excessPrecision, truncatedBits;
2982
2983 calcSemantics.precision = parts * integerPartWidth - 1;
2984 excessPrecision = calcSemantics.precision - semantics->precision;
2985 truncatedBits = excessPrecision;
2986
2987 IEEEFloat decSig(calcSemantics, uninitialized);
2988 decSig.makeZero(sign);
2989 IEEEFloat pow5(calcSemantics);
2990
2991 opStatus sigStatus = decSig.convertFromUnsignedParts(
2992 decSigParts, sigPartCount, rmNearestTiesToEven);
2993 opStatus powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
2995 /* Add exp, as 10^n = 5^n * 2^n. */
2996 decSig.exponent += exp;
2997
2998 lostFraction calcLostFraction;
2999 integerPart HUerr, HUdistance;
3000 unsigned int powHUerr;
3001
3002 if (exp >= 0) {
3003 /* multiplySignificand leaves the precision-th bit set to 1. */
3004 calcLostFraction = decSig.multiplySignificand(pow5);
3005 powHUerr = powStatus != opOK;
3006 } else {
3007 calcLostFraction = decSig.divideSignificand(pow5);
3008 /* Denormal numbers have less precision. */
3009 if (decSig.exponent < semantics->minExponent) {
3010 excessPrecision += (semantics->minExponent - decSig.exponent);
3011 truncatedBits = excessPrecision;
3012 excessPrecision = std::min(excessPrecision, calcSemantics.precision);
3013 }
3014 /* Extra half-ulp lost in reciprocal of exponent. */
3015 powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2;
3016 }
3017
3018 /* Both multiplySignificand and divideSignificand return the
3019 result with the integer bit set. */
3021 (decSig.significandParts(), calcSemantics.precision - 1) == 1);
3022
3023 HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK,
3024 powHUerr);
3025 HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
3026 excessPrecision, isNearest);
3027
3028 /* Are we guaranteed to round correctly if we truncate? */
3029 if (HUdistance >= HUerr) {
3030 APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
3031 calcSemantics.precision - excessPrecision,
3032 excessPrecision);
3033 /* Take the exponent of decSig. If we tcExtract-ed less bits
3034 above we must adjust our exponent to compensate for the
3035 implicit right shift. */
3036 exponent = (decSig.exponent + semantics->precision
3037 - (calcSemantics.precision - excessPrecision));
3038 calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(),
3039 decSig.partCount(),
3040 truncatedBits);
3041 return static_cast<opStatus>(normalize(rounding_mode, calcLostFraction) |
3042 ((sigStatus | powStatus) & opInexact));
3043 }
3044 }
3045}
3046
3047Expected<APFloat::opStatus>
3048IEEEFloat::convertFromDecimalString(StringRef str, roundingMode rounding_mode) {
3049 decimalInfo D;
3050 opStatus fs;
3051
3052 /* Scan the text. */
3053 StringRef::iterator p = str.begin();
3054 if (Error Err = interpretDecimal(p, str.end(), &D))
3055 return std::move(Err);
3056
3057 /* Handle the quick cases. First the case of no significant digits,
3058 i.e. zero, and then exponents that are obviously too large or too
3059 small. Writing L for log 10 / log 2, a number d.ddddd*10^exp
3060 definitely overflows if
3061
3062 (exp - 1) * L >= maxExponent
3063
3064 and definitely underflows to zero where
3065
3066 (exp + 1) * L <= minExponent - precision
3067
3068 With integer arithmetic the tightest bounds for L are
3069
3070 93/28 < L < 196/59 [ numerator <= 256 ]
3071 42039/12655 < L < 28738/8651 [ numerator <= 65536 ]
3072 */
3073
3074 // Test if we have a zero number allowing for strings with no null terminators
3075 // and zero decimals with non-zero exponents.
3076 //
3077 // We computed firstSigDigit by ignoring all zeros and dots. Thus if
3078 // D->firstSigDigit equals str.end(), every digit must be a zero and there can
3079 // be at most one dot. On the other hand, if we have a zero with a non-zero
3080 // exponent, then we know that D.firstSigDigit will be non-numeric.
3081 if (D.firstSigDigit == str.end() || decDigitValue(*D.firstSigDigit) >= 10U) {
3082 category = fcZero;
3083 fs = opOK;
3084 if (semantics->nanEncoding == fltNanEncoding::NegativeZero)
3085 sign = false;
3086 if (!semantics->hasZero)
3088
3089 /* Check whether the normalized exponent is high enough to overflow
3090 max during the log-rebasing in the max-exponent check below. */
3091 } else if (D.normalizedExponent - 1 > INT_MAX / 42039) {
3092 fs = handleOverflow(rounding_mode);
3093
3094 /* If it wasn't, then it also wasn't high enough to overflow max
3095 during the log-rebasing in the min-exponent check. Check that it
3096 won't overflow min in either check, then perform the min-exponent
3097 check. */
3098 } else if (D.normalizedExponent - 1 < INT_MIN / 42039 ||
3099 (D.normalizedExponent + 1) * 28738 <=
3100 8651 * (semantics->minExponent - (int) semantics->precision)) {
3101 /* Underflow to zero and round. */
3102 category = fcNormal;
3103 zeroSignificand();
3104 fs = normalize(rounding_mode, lfLessThanHalf);
3105
3106 /* We can finally safely perform the max-exponent check. */
3107 } else if ((D.normalizedExponent - 1) * 42039
3108 >= 12655 * semantics->maxExponent) {
3109 /* Overflow and round. */
3110 fs = handleOverflow(rounding_mode);
3111 } else {
3112 integerPart *decSignificand;
3113 unsigned int partCount;
3114
3115 /* A tight upper bound on number of bits required to hold an
3116 N-digit decimal integer is N * 196 / 59. Allocate enough space
3117 to hold the full significand, and an extra part required by
3118 tcMultiplyPart. */
3119 partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1;
3120 partCount = partCountForBits(1 + 196 * partCount / 59);
3121 decSignificand = new integerPart[partCount + 1];
3122 partCount = 0;
3123
3124 /* Convert to binary efficiently - we do almost all multiplication
3125 in an integerPart. When this would overflow do we do a single
3126 bignum multiplication, and then revert again to multiplication
3127 in an integerPart. */
3128 do {
3129 integerPart decValue, val, multiplier;
3130
3131 val = 0;
3132 multiplier = 1;
3133
3134 do {
3135 if (*p == '.') {
3136 p++;
3137 if (p == str.end()) {
3138 break;
3139 }
3140 }
3141 decValue = decDigitValue(*p++);
3142 if (decValue >= 10U) {
3143 delete[] decSignificand;
3144 return createError("Invalid character in significand");
3145 }
3146 multiplier *= 10;
3147 val = val * 10 + decValue;
3148 /* The maximum number that can be multiplied by ten with any
3149 digit added without overflowing an integerPart. */
3150 } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
3151
3152 /* Multiply out the current part. */
3153 APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
3154 partCount, partCount + 1, false);
3155
3156 /* If we used another part (likely but not guaranteed), increase
3157 the count. */
3158 if (decSignificand[partCount])
3159 partCount++;
3160 } while (p <= D.lastSigDigit);
3161
3162 category = fcNormal;
3163 fs = roundSignificandWithExponent(decSignificand, partCount,
3164 D.exponent, rounding_mode);
3165
3166 delete [] decSignificand;
3167 }
3168
3169 return fs;
3170}
3171
3172bool IEEEFloat::convertFromStringSpecials(StringRef str) {
3173 const size_t MIN_NAME_SIZE = 3;
3174
3175 if (str.size() < MIN_NAME_SIZE)
3176 return false;
3177
3178 if (str == "inf" || str == "INFINITY" || str == "+Inf" || str == "+inf") {
3179 makeInf(false);
3180 return true;
3181 }
3182
3183 bool IsNegative = str.consume_front("-");
3184 if (IsNegative) {
3185 if (str.size() < MIN_NAME_SIZE)
3186 return false;
3187
3188 if (str == "inf" || str == "INFINITY" || str == "Inf") {
3189 makeInf(true);
3190 return true;
3191 }
3192 }
3193
3194 // If we have a 's' (or 'S') prefix, then this is a Signaling NaN.
3195 bool IsSignaling = str.consume_front_insensitive("s");
3196 if (IsSignaling) {
3197 if (str.size() < MIN_NAME_SIZE)
3198 return false;
3199 }
3200
3201 if (str.consume_front("nan") || str.consume_front("NaN")) {
3202 // A NaN without payload.
3203 if (str.empty()) {
3204 makeNaN(IsSignaling, IsNegative);
3205 return true;
3206 }
3207
3208 // Allow the payload to be inside parentheses.
3209 if (str.front() == '(') {
3210 // Parentheses should be balanced (and not empty).
3211 if (str.size() <= 2 || str.back() != ')')
3212 return false;
3213
3214 str = str.slice(1, str.size() - 1);
3215 }
3216
3217 // Determine the payload number's radix.
3218 unsigned Radix = 10;
3219 if (str[0] == '0') {
3220 if (str.size() > 1 && tolower(str[1]) == 'x') {
3221 str = str.drop_front(2);
3222 Radix = 16;
3223 } else {
3224 Radix = 8;
3225 }
3226 }
3227
3228 // Parse the payload and make the NaN.
3229 APInt Payload;
3230 if (!str.getAsInteger(Radix, Payload)) {
3231 makeNaN(IsSignaling, IsNegative, &Payload);
3232 return true;
3233 }
3234 }
3235
3236 return false;
3237}
3238
3239Expected<APFloat::opStatus>
3241 if (str.empty())
3242 return createError("Invalid string length");
3243
3244 // Handle special cases.
3245 if (convertFromStringSpecials(str))
3246 return opOK;
3247
3248 /* Handle a leading minus sign. */
3249 StringRef::iterator p = str.begin();
3250 size_t slen = str.size();
3251 sign = *p == '-' ? 1 : 0;
3252 if (sign && !semantics->hasSignedRepr)
3254 "This floating point format does not support signed values");
3255
3256 if (*p == '-' || *p == '+') {
3257 p++;
3258 slen--;
3259 if (!slen)
3260 return createError("String has no digits");
3261 }
3262
3263 if (slen >= 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
3264 if (slen == 2)
3265 return createError("Invalid string");
3266 return convertFromHexadecimalString(StringRef(p + 2, slen - 2),
3267 rounding_mode);
3268 }
3269
3270 return convertFromDecimalString(StringRef(p, slen), rounding_mode);
3271}
3272
3273/* Write out a hexadecimal representation of the floating point value
3274 to DST, which must be of sufficient size, in the C99 form
3275 [-]0xh.hhhhp[+-]d. Return the number of characters written,
3276 excluding the terminating NUL.
3277
3278 If UPPERCASE, the output is in upper case, otherwise in lower case.
3279
3280 HEXDIGITS digits appear altogether, rounding the value if
3281 necessary. If HEXDIGITS is 0, the minimal precision to display the
3282 number precisely is used instead. If nothing would appear after
3283 the decimal point it is suppressed.
3284
3285 The decimal exponent is always printed and has at least one digit.
3286 Zero values display an exponent of zero. Infinities and NaNs
3287 appear as "infinity" or "nan" respectively.
3288
3289 The above rules are as specified by C99. There is ambiguity about
3290 what the leading hexadecimal digit should be. This implementation
3291 uses whatever is necessary so that the exponent is displayed as
3292 stored. This implies the exponent will fall within the IEEE format
3293 range, and the leading hexadecimal digit will be 0 (for denormals),
3294 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
3295 any other digits zero).
3296*/
3297unsigned int IEEEFloat::convertToHexString(char *dst, unsigned int hexDigits,
3298 bool upperCase,
3299 roundingMode rounding_mode) const {
3300 char *p = dst;
3301 if (sign)
3302 *dst++ = '-';
3303
3304 switch (category) {
3305 case fcInfinity:
3306 memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
3307 dst += sizeof infinityL - 1;
3308 break;
3309
3310 case fcNaN:
3311 memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
3312 dst += sizeof NaNU - 1;
3313 break;
3314
3315 case fcZero:
3316 *dst++ = '0';
3317 *dst++ = upperCase ? 'X': 'x';
3318 *dst++ = '0';
3319 if (hexDigits > 1) {
3320 *dst++ = '.';
3321 memset (dst, '0', hexDigits - 1);
3322 dst += hexDigits - 1;
3323 }
3324 *dst++ = upperCase ? 'P': 'p';
3325 *dst++ = '0';
3326 break;
3327
3328 case fcNormal:
3329 dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
3330 break;
3331 }
3332
3333 *dst = 0;
3334
3335 return static_cast<unsigned int>(dst - p);
3336}
3337
3338/* Does the hard work of outputting the correctly rounded hexadecimal
3339 form of a normal floating point number with the specified number of
3340 hexadecimal digits. If HEXDIGITS is zero the minimum number of
3341 digits necessary to print the value precisely is output. */
3342char *IEEEFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
3343 bool upperCase,
3344 roundingMode rounding_mode) const {
3345 *dst++ = '0';
3346 *dst++ = upperCase ? 'X': 'x';
3347
3348 bool roundUp = false;
3349 const char *hexDigitChars = upperCase ? hexDigitsUpper : hexDigitsLower;
3350
3351 const integerPart *significand = significandParts();
3352 unsigned partsCount = partCount();
3353
3354 /* +3 because the first digit only uses the single integer bit, so
3355 we have 3 virtual zero most-significant-bits. */
3356 unsigned valueBits = semantics->precision + 3;
3357 unsigned shift = integerPartWidth - valueBits % integerPartWidth;
3358
3359 /* The natural number of digits required ignoring trailing
3360 insignificant zeroes. */
3361 unsigned outputDigits = (valueBits - significandLSB() + 3) / 4;
3362
3363 /* hexDigits of zero means use the required number for the
3364 precision. Otherwise, see if we are truncating. If we are,
3365 find out if we need to round away from zero. */
3366 if (hexDigits) {
3367 if (hexDigits < outputDigits) {
3368 /* We are dropping non-zero bits, so need to check how to round.
3369 "bits" is the number of dropped bits. */
3370 unsigned int bits;
3371 lostFraction fraction;
3372
3373 bits = valueBits - hexDigits * 4;
3374 fraction = lostFractionThroughTruncation (significand, partsCount, bits);
3375 roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
3376 }
3377 outputDigits = hexDigits;
3378 }
3379
3380 /* Write the digits consecutively, and start writing in the location
3381 of the hexadecimal point. We move the most significant digit
3382 left and add the hexadecimal point later. */
3383 char *p = ++dst;
3384
3385 unsigned count = (valueBits + integerPartWidth - 1) / integerPartWidth;
3386
3387 while (outputDigits && count) {
3388 integerPart part;
3389
3390 /* Put the most significant integerPartWidth bits in "part". */
3391 if (--count == partsCount)
3392 part = 0; /* An imaginary higher zero part. */
3393 else
3394 part = significand[count] << shift;
3395
3396 if (count && shift)
3397 part |= significand[count - 1] >> (integerPartWidth - shift);
3398
3399 /* Convert as much of "part" to hexdigits as we can. */
3400 unsigned int curDigits = integerPartWidth / 4;
3401
3402 curDigits = std::min(curDigits, outputDigits);
3403 dst += partAsHex (dst, part, curDigits, hexDigitChars);
3404 outputDigits -= curDigits;
3405 }
3406
3407 if (roundUp) {
3408 char *q = dst;
3409
3410 /* Note that hexDigitChars has a trailing '0'. */
3411 do {
3412 q--;
3413 *q = hexDigitChars[hexDigitValue (*q) + 1];
3414 } while (*q == '0');
3415 assert(q >= p);
3416 } else {
3417 /* Add trailing zeroes. */
3418 memset (dst, '0', outputDigits);
3419 dst += outputDigits;
3420 }
3421
3422 /* Move the most significant digit to before the point, and if there
3423 is something after the decimal point add it. This must come
3424 after rounding above. */
3425 p[-1] = p[0];
3426 if (dst -1 == p)
3427 dst--;
3428 else
3429 p[0] = '.';
3430
3431 /* Finally output the exponent. */
3432 *dst++ = upperCase ? 'P': 'p';
3433
3434 return writeSignedDecimal (dst, exponent);
3435}
3436
3438 if (!Arg.isFiniteNonZero())
3439 return hash_combine((uint8_t)Arg.category,
3440 // NaN has no sign, fix it at zero.
3441 Arg.isNaN() ? (uint8_t)0 : (uint8_t)Arg.sign,
3442 Arg.semantics->precision);
3443
3444 // Normal floats need their exponent and significand hashed.
3445 return hash_combine((uint8_t)Arg.category, (uint8_t)Arg.sign,
3446 Arg.semantics->precision, Arg.exponent,
3448 Arg.significandParts(),
3449 Arg.significandParts() + Arg.partCount()));
3450}
3451
3452// Conversion from APFloat to/from host float/double. It may eventually be
3453// possible to eliminate these and have everybody deal with APFloats, but that
3454// will take a while. This approach will not easily extend to long double.
3455// Current implementation requires integerPartWidth==64, which is correct at
3456// the moment but could be made more general.
3457
3458// Denormals have exponent minExponent in APFloat, but minExponent-1 in
3459// the actual IEEE respresentations. We compensate for that here.
3460
3461APInt IEEEFloat::convertF80LongDoubleAPFloatToAPInt() const {
3462 assert(partCount() == 2);
3463 return convertIEEEFloatToAPInt<APFloatBase::semX87DoubleExtended>();
3464}
3465
3466APInt IEEEFloat::convertPPCDoubleDoubleLegacyAPFloatToAPInt() const {
3467 assert(semantics ==
3468 (const llvm::fltSemantics *)&APFloatBase::semPPCDoubleDoubleLegacy);
3469 assert(partCount()==2);
3470
3471 uint64_t words[2];
3472 bool losesInfo;
3473
3474 // Convert number to double. To avoid spurious underflows, we re-
3475 // normalize against the "double" minExponent first, and only *then*
3476 // truncate the mantissa. The result of that second conversion
3477 // may be inexact, but should never underflow.
3478 // Declare fltSemantics before APFloat that uses it (and
3479 // saves pointer to it) to ensure correct destruction order.
3480 fltSemantics extendedSemantics = *semantics;
3481 extendedSemantics.minExponent = APFloatBase::semIEEEdouble.minExponent;
3482 IEEEFloat extended(*this);
3483 [[maybe_unused]] opStatus fs =
3484 extended.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
3485 assert(fs == opOK && !losesInfo);
3486
3487 IEEEFloat u(extended);
3488 fs = u.convert(APFloatBase::semIEEEdouble, rmNearestTiesToEven, &losesInfo);
3489 assert(fs == opOK || fs == opInexact);
3490 words[0] = *u.convertDoubleAPFloatToAPInt().getRawData();
3491
3492 // If conversion was exact or resulted in a special case, we're done;
3493 // just set the second double to zero. Otherwise, re-convert back to
3494 // the extended format and compute the difference. This now should
3495 // convert exactly to double.
3496 if (u.isFiniteNonZero() && losesInfo) {
3497 fs = u.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
3498 assert(fs == opOK && !losesInfo);
3499
3500 IEEEFloat v(extended);
3501 v.subtract(u, rmNearestTiesToEven);
3502 fs = v.convert(APFloatBase::semIEEEdouble, rmNearestTiesToEven, &losesInfo);
3503 assert(fs == opOK && !losesInfo);
3504 words[1] = *v.convertDoubleAPFloatToAPInt().getRawData();
3505 } else {
3506 words[1] = 0;
3507 }
3508
3509 return APInt(128, words);
3510}
3511
3512template <const fltSemantics &S>
3513APInt IEEEFloat::convertIEEEFloatToAPInt() const {
3514 assert(semantics == &S);
3515 constexpr unsigned int trailing_significand_bits =
3516 S.precision - 1 + S.hasExplicitIntegerBit;
3517 constexpr int integer_bit_part = (S.precision - 1) / integerPartWidth;
3518 constexpr integerPart integer_bit = integerPart{1}
3519 << ((S.precision - 1) % integerPartWidth);
3520 constexpr uint64_t significand_mask = integer_bit - 1;
3521 constexpr unsigned int exponent_bits =
3522 S.sizeInBits - (S.hasSignedRepr ? 1 : 0) - trailing_significand_bits;
3523 static_assert(exponent_bits < 64);
3524 constexpr uint64_t exponent_mask = (uint64_t{1} << exponent_bits) - 1;
3525 constexpr bool is_zero_exp_reserved = S.hasDenormals || S.hasZero;
3526 constexpr int bias = -(S.minExponent - (is_zero_exp_reserved ? 1 : 0));
3527
3528 uint64_t myexponent;
3529 std::array<integerPart, partCountForBits(trailing_significand_bits)>
3530 mysignificand;
3531
3532 if (isFiniteNonZero()) {
3533 myexponent = exponent + bias;
3534 std::copy_n(significandParts(), mysignificand.size(),
3535 mysignificand.begin());
3536 if (myexponent == 1 &&
3537 !(significandParts()[integer_bit_part] & integer_bit))
3538 myexponent = 0; // denormal
3539 } else if (category == fcZero) {
3540 if (!S.hasZero)
3541 llvm_unreachable("semantics does not support zero!");
3542 myexponent = ::exponentZero(S) + bias;
3543 mysignificand.fill(0);
3544 } else if (category == fcInfinity) {
3545 if (S.nonFiniteBehavior == fltNonfiniteBehavior::NanOnly ||
3546 S.nonFiniteBehavior == fltNonfiniteBehavior::FiniteOnly)
3547 llvm_unreachable("semantics don't support inf!");
3548 myexponent = ::exponentInf(S) + bias;
3549 mysignificand.fill(0);
3550 if constexpr (S.hasExplicitIntegerBit) {
3551 mysignificand[0] = integerPart{1} << (trailing_significand_bits - 1);
3552 }
3553 } else {
3554 assert(category == fcNaN && "Unknown category!");
3555 if (S.nonFiniteBehavior == fltNonfiniteBehavior::FiniteOnly)
3556 llvm_unreachable("semantics don't support NaN!");
3557 myexponent = ::exponentNaN(S) + bias;
3558 std::copy_n(significandParts(), mysignificand.size(),
3559 mysignificand.begin());
3560 }
3561 std::array<uint64_t, (S.sizeInBits + 63) / 64> words;
3562 auto words_iter =
3563 std::copy_n(mysignificand.begin(), mysignificand.size(), words.begin());
3564 if constexpr (!S.hasExplicitIntegerBit) {
3565 if constexpr (significand_mask != 0 || trailing_significand_bits == 0) {
3566 // Clear the integer bit.
3567 words[mysignificand.size() - 1] &= significand_mask;
3568 }
3569 }
3570 std::fill(words_iter, words.end(), uint64_t{0});
3571 constexpr size_t last_word = words.size() - 1;
3572 uint64_t shifted_sign = static_cast<uint64_t>(sign & 1)
3573 << ((S.sizeInBits - 1) % 64);
3574 words[last_word] |= shifted_sign;
3575 uint64_t shifted_exponent = (myexponent & exponent_mask)
3576 << (trailing_significand_bits % 64);
3577 words[last_word] |= shifted_exponent;
3578 if constexpr (last_word == 0) {
3579 return APInt(S.sizeInBits, words[0]);
3580 }
3581 return APInt(S.sizeInBits, words);
3582}
3583
3584APInt IEEEFloat::convertQuadrupleAPFloatToAPInt() const {
3585 assert(partCount() == 2);
3586 return convertIEEEFloatToAPInt<APFloatBase::semIEEEquad>();
3587}
3588
3589APInt IEEEFloat::convertDoubleAPFloatToAPInt() const {
3590 assert(partCount()==1);
3591 return convertIEEEFloatToAPInt<APFloatBase::semIEEEdouble>();
3592}
3593
3594APInt IEEEFloat::convertFloatAPFloatToAPInt() const {
3595 assert(partCount()==1);
3596 return convertIEEEFloatToAPInt<APFloatBase::semIEEEsingle>();
3597}
3598
3599APInt IEEEFloat::convertBFloatAPFloatToAPInt() const {
3600 assert(partCount() == 1);
3601 return convertIEEEFloatToAPInt<APFloatBase::semBFloat>();
3602}
3603
3604APInt IEEEFloat::convertHalfAPFloatToAPInt() const {
3605 assert(partCount()==1);
3606 return convertIEEEFloatToAPInt<APFloatBase::APFloatBase::semIEEEhalf>();
3607}
3608
3609APInt IEEEFloat::convertFloat8E5M2APFloatToAPInt() const {
3610 assert(partCount() == 1);
3611 return convertIEEEFloatToAPInt<APFloatBase::semFloat8E5M2>();
3612}
3613
3614APInt IEEEFloat::convertFloat8E5M2FNUZAPFloatToAPInt() const {
3615 assert(partCount() == 1);
3616 return convertIEEEFloatToAPInt<APFloatBase::semFloat8E5M2FNUZ>();
3617}
3618
3619APInt IEEEFloat::convertFloat8E4M3APFloatToAPInt() const {
3620 assert(partCount() == 1);
3621 return convertIEEEFloatToAPInt<APFloatBase::semFloat8E4M3>();
3622}
3623
3624APInt IEEEFloat::convertFloat8E4M3FNAPFloatToAPInt() const {
3625 assert(partCount() == 1);
3626 return convertIEEEFloatToAPInt<APFloatBase::semFloat8E4M3FN>();
3627}
3628
3629APInt IEEEFloat::convertFloat8E4M3FNUZAPFloatToAPInt() const {
3630 assert(partCount() == 1);
3631 return convertIEEEFloatToAPInt<APFloatBase::semFloat8E4M3FNUZ>();
3632}
3633
3634APInt IEEEFloat::convertFloat8E4M3B11FNUZAPFloatToAPInt() const {
3635 assert(partCount() == 1);
3636 return convertIEEEFloatToAPInt<APFloatBase::semFloat8E4M3B11FNUZ>();
3637}
3638
3639APInt IEEEFloat::convertFloat8E3M4APFloatToAPInt() const {
3640 assert(partCount() == 1);
3641 return convertIEEEFloatToAPInt<APFloatBase::semFloat8E3M4>();
3642}
3643
3644APInt IEEEFloat::convertFloatTF32APFloatToAPInt() const {
3645 assert(partCount() == 1);
3646 return convertIEEEFloatToAPInt<APFloatBase::semFloatTF32>();
3647}
3648
3649APInt IEEEFloat::convertFloat8E8M0FNUAPFloatToAPInt() const {
3650 assert(partCount() == 1);
3651 return convertIEEEFloatToAPInt<APFloatBase::semFloat8E8M0FNU>();
3652}
3653
3654APInt IEEEFloat::convertFloat8E5M3FNUAPFloatToAPInt() const {
3655 assert(partCount() == 1);
3656 return convertIEEEFloatToAPInt<APFloatBase::semFloat8E5M3FNU>();
3657}
3658
3659APInt IEEEFloat::convertFloat6E3M2FNAPFloatToAPInt() const {
3660 assert(partCount() == 1);
3661 return convertIEEEFloatToAPInt<APFloatBase::semFloat6E3M2FN>();
3662}
3663
3664APInt IEEEFloat::convertFloat6E2M3FNAPFloatToAPInt() const {
3665 assert(partCount() == 1);
3666 return convertIEEEFloatToAPInt<APFloatBase::semFloat6E2M3FN>();
3667}
3668
3669APInt IEEEFloat::convertFloat4E2M1FNAPFloatToAPInt() const {
3670 assert(partCount() == 1);
3671 return convertIEEEFloatToAPInt<APFloatBase::semFloat4E2M1FN>();
3672}
3673
3674// This function creates an APInt that is just a bit map of the floating
3675// point constant as it would appear in memory. It is not a conversion,
3676// and treating the result as a normal integer is unlikely to be useful.
3677
3679 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semIEEEhalf)
3680 return convertHalfAPFloatToAPInt();
3681
3682 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semBFloat)
3683 return convertBFloatAPFloatToAPInt();
3684
3685 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semIEEEsingle)
3686 return convertFloatAPFloatToAPInt();
3687
3688 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semIEEEdouble)
3689 return convertDoubleAPFloatToAPInt();
3690
3691 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semIEEEquad)
3692 return convertQuadrupleAPFloatToAPInt();
3693
3694 if (semantics ==
3695 (const llvm::fltSemantics *)&APFloatBase::semPPCDoubleDoubleLegacy)
3696 return convertPPCDoubleDoubleLegacyAPFloatToAPInt();
3697
3698 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat8E5M2)
3699 return convertFloat8E5M2APFloatToAPInt();
3700
3701 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat8E5M2FNUZ)
3702 return convertFloat8E5M2FNUZAPFloatToAPInt();
3703
3704 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat8E4M3)
3705 return convertFloat8E4M3APFloatToAPInt();
3706
3707 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat8E4M3FN)
3708 return convertFloat8E4M3FNAPFloatToAPInt();
3709
3710 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat8E4M3FNUZ)
3711 return convertFloat8E4M3FNUZAPFloatToAPInt();
3712
3713 if (semantics ==
3714 (const llvm::fltSemantics *)&APFloatBase::semFloat8E4M3B11FNUZ)
3715 return convertFloat8E4M3B11FNUZAPFloatToAPInt();
3716
3717 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat8E3M4)
3718 return convertFloat8E3M4APFloatToAPInt();
3719
3720 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloatTF32)
3721 return convertFloatTF32APFloatToAPInt();
3722
3723 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat8E8M0FNU)
3724 return convertFloat8E8M0FNUAPFloatToAPInt();
3725
3726 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat8E5M3FNU)
3727 return convertFloat8E5M3FNUAPFloatToAPInt();
3728
3729 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat6E3M2FN)
3730 return convertFloat6E3M2FNAPFloatToAPInt();
3731
3732 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat6E2M3FN)
3733 return convertFloat6E2M3FNAPFloatToAPInt();
3734
3735 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat4E2M1FN)
3736 return convertFloat4E2M1FNAPFloatToAPInt();
3737
3738 assert(semantics ==
3739 (const llvm::fltSemantics *)&APFloatBase::semX87DoubleExtended &&
3740 "unknown format!");
3741 return convertF80LongDoubleAPFloatToAPInt();
3742}
3743
3745 assert(semantics == (const llvm::fltSemantics *)&APFloatBase::semIEEEsingle &&
3746 "Float semantics are not IEEEsingle");
3747 APInt api = bitcastToAPInt();
3748 return api.bitsToFloat();
3749}
3750
3752 assert(semantics == (const llvm::fltSemantics *)&APFloatBase::semIEEEdouble &&
3753 "Float semantics are not IEEEdouble");
3754 APInt api = bitcastToAPInt();
3755 return api.bitsToDouble();
3756}
3757
3758#ifdef HAS_IEE754_FLOAT128
3759float128 IEEEFloat::convertToQuad() const {
3760 assert(semantics == (const llvm::fltSemantics *)&APFloatBase::semIEEEquad &&
3761 "Float semantics are not IEEEquads");
3762 APInt api = bitcastToAPInt();
3763 return api.bitsToQuad();
3764}
3765#endif
3766
3767void IEEEFloat::initFromF80LongDoubleAPInt(const APInt &api) {
3768 return initFromIEEEAPInt<APFloatBase::semX87DoubleExtended>(api);
3769}
3770
3771void IEEEFloat::initFromPPCDoubleDoubleLegacyAPInt(const APInt &api) {
3772 uint64_t i1 = api.getRawData()[0];
3773 uint64_t i2 = api.getRawData()[1];
3774 bool losesInfo;
3775
3776 // Get the first double and convert to our format.
3777 initFromDoubleAPInt(APInt(64, i1));
3778 [[maybe_unused]] opStatus fs = convert(APFloatBase::semPPCDoubleDoubleLegacy,
3779 rmNearestTiesToEven, &losesInfo);
3780 // (convert may return opInvalidOp if i1 is an sNaN).
3781 assert((fs == opOK || fs == opInvalidOp) && !losesInfo);
3782
3783 // Unless we have a special case, add in second double.
3784 if (isFiniteNonZero()) {
3785 IEEEFloat v(APFloatBase::semIEEEdouble, APInt(64, i2));
3786 fs = v.convert(APFloatBase::semPPCDoubleDoubleLegacy, rmNearestTiesToEven,
3787 &losesInfo);
3788 assert(fs == opOK && !losesInfo);
3789
3791 }
3792}
3793
3794// The E8M0 format has the following characteristics:
3795// It is an 8-bit unsigned format with only exponents (no actual significand).
3796// No encodings for {zero, infinities or denorms}.
3797// NaN is represented by all 1's.
3798// Bias is 127.
3799void IEEEFloat::initFromFloat8E8M0FNUAPInt(const APInt &api) {
3800 initFromIEEEAPInt<APFloatBase::semFloat8E8M0FNU>(api);
3801}
3802
3803void IEEEFloat::initFromFloat8E5M3FNUAPInt(const APInt &api) {
3804 initFromIEEEAPInt<APFloatBase::semFloat8E5M3FNU>(api);
3805}
3806
3807template <const fltSemantics &S>
3808void IEEEFloat::initFromIEEEAPInt(const APInt &api) {
3809 assert(api.getBitWidth() == S.sizeInBits);
3810
3811 constexpr unsigned int trailing_significand_bits =
3812 S.precision - 1 + S.hasExplicitIntegerBit;
3813 constexpr integerPart integer_bit =
3814 integerPart{1} << (trailing_significand_bits % integerPartWidth);
3815 constexpr uint64_t significand_mask = integer_bit - 1;
3816 constexpr unsigned int exponent_bits =
3817 S.sizeInBits - (S.hasSignedRepr ? 1 : 0) - trailing_significand_bits;
3818 static_assert(exponent_bits < 64);
3819 constexpr unsigned int stored_significand_parts =
3820 partCountForBits(trailing_significand_bits + 1);
3821 constexpr uint64_t exponent_mask = (uint64_t{1} << exponent_bits) - 1;
3822 constexpr bool is_zero_exp_reserved = S.hasDenormals || S.hasZero;
3823 constexpr int bias = -(S.minExponent - (is_zero_exp_reserved ? 1 : 0));
3824 constexpr bool has_significand = trailing_significand_bits > 0;
3825
3826 // Copy the bits of the significand. We need to clear out the exponent and
3827 // sign bit in the last word.
3828 std::array<integerPart, stored_significand_parts> mysignificand;
3829 if constexpr (has_significand) {
3830 std::copy_n(api.getRawData(), mysignificand.size(), mysignificand.begin());
3831 if constexpr (significand_mask != 0 || S.precision >= integerPartWidth) {
3832 mysignificand[mysignificand.size() - 1] &= significand_mask;
3833 }
3834 } else {
3835 std::fill_n(mysignificand.begin(), mysignificand.size(), 0);
3836 // Always set integer bit to 1 for consistency in APFloat's internal
3837 // representation.
3838 mysignificand[0] = 1;
3839 }
3840
3841 // We assume the last word holds the sign bit, the exponent, and potentially
3842 // some of the trailing significand field.
3843 uint64_t last_word = api.getRawData()[api.getNumWords() - 1];
3844 uint64_t myexponent =
3845 (last_word >> (trailing_significand_bits % 64)) & exponent_mask;
3846
3847 initialize(&S);
3848 assert(partCount() == mysignificand.size());
3849
3850 sign = S.hasSignedRepr
3851 ? static_cast<unsigned int>(last_word >> ((S.sizeInBits - 1) % 64))
3852 : 0;
3853
3854 bool all_zero_significand =
3855 has_significand && llvm::all_of(mysignificand, equal_to(0));
3856
3857 bool is_zero = myexponent == 0 && all_zero_significand && S.hasZero;
3858
3859 if constexpr (S.nonFiniteBehavior == fltNonfiniteBehavior::IEEE754) {
3860 bool is_inf = false;
3861
3862 if constexpr (S.hasExplicitIntegerBit) {
3863 // This is only used and tested for x87DoubleExtended
3864 static_assert(S.precision == 64);
3865 constexpr integerPart significand_mask_no_int_bit =
3866 (uint64_t{1} << (trailing_significand_bits - 1)) - 1;
3867 const integerPart myintegerbit =
3868 mysignificand[0] >> (trailing_significand_bits - 1);
3869
3870 is_inf = myexponent - bias == ::exponentInf(S) && myintegerbit == 1 &&
3871 (mysignificand[0] & significand_mask_no_int_bit) == 0;
3872 } else {
3873 is_inf = myexponent - bias == ::exponentInf(S) && all_zero_significand;
3874 }
3875
3876 if (is_inf) {
3877 makeInf(sign);
3878 return;
3879 }
3880 }
3881
3882 bool is_nan = false;
3883
3884 if constexpr (S.nanEncoding == fltNanEncoding::IEEE) {
3885 if constexpr (S.hasExplicitIntegerBit) {
3886 // This is only used and tested for x87DoubleExtended
3887 static_assert(S.precision == 64);
3888 const integerPart myintegerbit =
3889 mysignificand[0] >> (trailing_significand_bits - 1);
3890 constexpr integerPart significand_mask_no_int_bit =
3891 (uint64_t{1} << (trailing_significand_bits - 1)) - 1;
3892
3893 if (myexponent - bias == ::exponentNaN(S) &&
3894 (mysignificand[0] & significand_mask_no_int_bit) != 0) {
3895 // regular NaN and pseudoNaN
3896 is_nan = true;
3897 } else if (myexponent - bias == ::exponentNaN(S) &&
3898 (mysignificand[0] & significand_mask_no_int_bit) == 0) {
3899 // pseudoinfinity
3900 is_nan = true;
3901 } else if (myexponent - bias != ::exponentNaN(S) && myexponent != 0 &&
3902 myintegerbit == 0) {
3903 // unnormal
3904 is_nan = true;
3905 }
3906 } else {
3907 is_nan = myexponent - bias == ::exponentNaN(S) && !all_zero_significand;
3908 }
3909 } else if constexpr (S.nanEncoding == fltNanEncoding::AllOnes) {
3910 bool all_ones_significand =
3911 std::all_of(mysignificand.begin(), mysignificand.end() - 1,
3912 [](integerPart bits) { return bits == ~integerPart{0}; }) &&
3913 (!significand_mask ||
3914 mysignificand[mysignificand.size() - 1] == significand_mask);
3915 is_nan = myexponent - bias == ::exponentNaN(S) && all_ones_significand;
3916 } else if constexpr (S.nanEncoding == fltNanEncoding::NegativeZero) {
3917 is_nan = is_zero && sign;
3918 }
3919
3920 if (is_nan) {
3921 category = fcNaN;
3922 exponent = ::exponentNaN(S);
3923 std::copy_n(mysignificand.begin(), mysignificand.size(),
3924 significandParts());
3925 return;
3926 }
3927
3928 if (is_zero) {
3929 makeZero(sign);
3930 return;
3931 }
3932
3933 category = fcNormal;
3934 exponent = myexponent - bias;
3935 std::copy_n(mysignificand.begin(), mysignificand.size(), significandParts());
3936 if (myexponent == 0 && S.hasDenormals) // denormal
3937 exponent = S.minExponent;
3938 else {
3939 if constexpr (!S.hasExplicitIntegerBit) {
3940 significandParts()[mysignificand.size() - 1] |= integer_bit;
3941 }
3942 }
3943}
3944
3945void IEEEFloat::initFromQuadrupleAPInt(const APInt &api) {
3946 initFromIEEEAPInt<APFloatBase::semIEEEquad>(api);
3947}
3948
3949void IEEEFloat::initFromDoubleAPInt(const APInt &api) {
3950 initFromIEEEAPInt<APFloatBase::semIEEEdouble>(api);
3951}
3952
3953void IEEEFloat::initFromFloatAPInt(const APInt &api) {
3954 initFromIEEEAPInt<APFloatBase::semIEEEsingle>(api);
3955}
3956
3957void IEEEFloat::initFromBFloatAPInt(const APInt &api) {
3958 initFromIEEEAPInt<APFloatBase::semBFloat>(api);
3959}
3960
3961void IEEEFloat::initFromHalfAPInt(const APInt &api) {
3962 initFromIEEEAPInt<APFloatBase::semIEEEhalf>(api);
3963}
3964
3965void IEEEFloat::initFromFloat8E5M2APInt(const APInt &api) {
3966 initFromIEEEAPInt<APFloatBase::semFloat8E5M2>(api);
3967}
3968
3969void IEEEFloat::initFromFloat8E5M2FNUZAPInt(const APInt &api) {
3970 initFromIEEEAPInt<APFloatBase::semFloat8E5M2FNUZ>(api);
3971}
3972
3973void IEEEFloat::initFromFloat8E4M3APInt(const APInt &api) {
3974 initFromIEEEAPInt<APFloatBase::semFloat8E4M3>(api);
3975}
3976
3977void IEEEFloat::initFromFloat8E4M3FNAPInt(const APInt &api) {
3978 initFromIEEEAPInt<APFloatBase::semFloat8E4M3FN>(api);
3979}
3980
3981void IEEEFloat::initFromFloat8E4M3FNUZAPInt(const APInt &api) {
3982 initFromIEEEAPInt<APFloatBase::semFloat8E4M3FNUZ>(api);
3983}
3984
3985void IEEEFloat::initFromFloat8E4M3B11FNUZAPInt(const APInt &api) {
3986 initFromIEEEAPInt<APFloatBase::semFloat8E4M3B11FNUZ>(api);
3987}
3988
3989void IEEEFloat::initFromFloat8E3M4APInt(const APInt &api) {
3990 initFromIEEEAPInt<APFloatBase::semFloat8E3M4>(api);
3991}
3992
3993void IEEEFloat::initFromFloatTF32APInt(const APInt &api) {
3994 initFromIEEEAPInt<APFloatBase::semFloatTF32>(api);
3995}
3996
3997void IEEEFloat::initFromFloat6E3M2FNAPInt(const APInt &api) {
3998 initFromIEEEAPInt<APFloatBase::semFloat6E3M2FN>(api);
3999}
4000
4001void IEEEFloat::initFromFloat6E2M3FNAPInt(const APInt &api) {
4002 initFromIEEEAPInt<APFloatBase::semFloat6E2M3FN>(api);
4003}
4004
4005void IEEEFloat::initFromFloat4E2M1FNAPInt(const APInt &api) {
4006 initFromIEEEAPInt<APFloatBase::semFloat4E2M1FN>(api);
4007}
4008
4009/// Treat api as containing the bits of a floating point number.
4010void IEEEFloat::initFromAPInt(const fltSemantics *Sem, const APInt &api) {
4011 assert(api.getBitWidth() == Sem->sizeInBits);
4012 if (Sem == &APFloatBase::semIEEEhalf)
4013 return initFromHalfAPInt(api);
4014 if (Sem == &APFloatBase::semBFloat)
4015 return initFromBFloatAPInt(api);
4016 if (Sem == &APFloatBase::semIEEEsingle)
4017 return initFromFloatAPInt(api);
4018 if (Sem == &APFloatBase::semIEEEdouble)
4019 return initFromDoubleAPInt(api);
4020 if (Sem == &APFloatBase::semX87DoubleExtended)
4021 return initFromF80LongDoubleAPInt(api);
4022 if (Sem == &APFloatBase::semIEEEquad)
4023 return initFromQuadrupleAPInt(api);
4024 if (Sem == &APFloatBase::semPPCDoubleDoubleLegacy)
4025 return initFromPPCDoubleDoubleLegacyAPInt(api);
4026 if (Sem == &APFloatBase::semFloat8E5M2)
4027 return initFromFloat8E5M2APInt(api);
4028 if (Sem == &APFloatBase::semFloat8E5M2FNUZ)
4029 return initFromFloat8E5M2FNUZAPInt(api);
4030 if (Sem == &APFloatBase::semFloat8E4M3)
4031 return initFromFloat8E4M3APInt(api);
4032 if (Sem == &APFloatBase::semFloat8E4M3FN)
4033 return initFromFloat8E4M3FNAPInt(api);
4034 if (Sem == &APFloatBase::semFloat8E4M3FNUZ)
4035 return initFromFloat8E4M3FNUZAPInt(api);
4036 if (Sem == &APFloatBase::semFloat8E4M3B11FNUZ)
4037 return initFromFloat8E4M3B11FNUZAPInt(api);
4038 if (Sem == &APFloatBase::semFloat8E3M4)
4039 return initFromFloat8E3M4APInt(api);
4040 if (Sem == &APFloatBase::semFloatTF32)
4041 return initFromFloatTF32APInt(api);
4042 if (Sem == &APFloatBase::semFloat8E8M0FNU)
4043 return initFromFloat8E8M0FNUAPInt(api);
4044 if (Sem == &APFloatBase::semFloat8E5M3FNU)
4045 return initFromFloat8E5M3FNUAPInt(api);
4046 if (Sem == &APFloatBase::semFloat6E3M2FN)
4047 return initFromFloat6E3M2FNAPInt(api);
4048 if (Sem == &APFloatBase::semFloat6E2M3FN)
4049 return initFromFloat6E2M3FNAPInt(api);
4050 if (Sem == &APFloatBase::semFloat4E2M1FN)
4051 return initFromFloat4E2M1FNAPInt(api);
4052
4053 llvm_unreachable("unsupported semantics");
4054}
4055
4056/// Make this number the largest magnitude normal number in the given
4057/// semantics.
4058void IEEEFloat::makeLargest(bool Negative) {
4059 if (Negative && !semantics->hasSignedRepr)
4061 "This floating point format does not support signed values");
4062 // We want (in interchange format):
4063 // sign = {Negative}
4064 // exponent = 1..10
4065 // significand = 1..1
4066 category = fcNormal;
4067 sign = Negative;
4068 exponent = semantics->maxExponent;
4069
4070 // Use memset to set all but the highest integerPart to all ones.
4071 integerPart *significand = significandParts();
4072 unsigned PartCount = partCount();
4073 memset(significand, 0xFF, sizeof(integerPart)*(PartCount - 1));
4074
4075 // Set the high integerPart especially setting all unused top bits for
4076 // internal consistency.
4077 const unsigned NumUnusedHighBits =
4078 PartCount*integerPartWidth - semantics->precision;
4079 significand[PartCount - 1] = (NumUnusedHighBits < integerPartWidth)
4080 ? (~integerPart(0) >> NumUnusedHighBits)
4081 : 0;
4082 if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly &&
4083 semantics->nanEncoding == fltNanEncoding::AllOnes &&
4084 (semantics->precision > 1))
4085 significand[0] &= ~integerPart(1);
4086}
4087
4088/// Make this number the smallest magnitude denormal number in the given
4089/// semantics.
4090void IEEEFloat::makeSmallest(bool Negative) {
4091 if (Negative && !semantics->hasSignedRepr)
4093 "This floating point format does not support signed values");
4094 // We want (in interchange format):
4095 // sign = {Negative}
4096 // exponent = 0..0
4097 // significand = 0..01
4098 category = fcNormal;
4099 sign = Negative;
4100 exponent = semantics->minExponent;
4101 APInt::tcSet(significandParts(), 1, partCount());
4102}
4103
4105 if (Negative && !semantics->hasSignedRepr)
4107 "This floating point format does not support signed values");
4108 // We want (in interchange format):
4109 // sign = {Negative}
4110 // exponent = 0..0
4111 // significand = 10..0
4112
4113 category = fcNormal;
4114 zeroSignificand();
4115 sign = Negative;
4116 exponent = semantics->minExponent;
4117 APInt::tcSetBit(significandParts(), semantics->precision - 1);
4118}
4119
4120IEEEFloat::IEEEFloat(const fltSemantics &Sem, const APInt &API) {
4121 initFromAPInt(&Sem, API);
4122}
4123
4125 initFromAPInt(&APFloatBase::semIEEEsingle, APInt::floatToBits(f));
4126}
4127
4129 initFromAPInt(&APFloatBase::semIEEEdouble, APInt::doubleToBits(d));
4130}
4131
4132namespace {
4133 void append(SmallVectorImpl<char> &Buffer, StringRef Str) {
4134 Buffer.append(Str.begin(), Str.end());
4135 }
4136
4137 /// Removes data from the given significand until it is no more
4138 /// precise than is required for the desired precision.
4139 void AdjustToPrecision(APInt &significand,
4140 int &exp, unsigned FormatPrecision) {
4141 unsigned bits = significand.getActiveBits();
4142
4143 // 196/59 is a very slight overestimate of lg_2(10).
4144 unsigned bitsRequired = (FormatPrecision * 196 + 58) / 59;
4145
4146 if (bits <= bitsRequired) return;
4147
4148 unsigned tensRemovable = (bits - bitsRequired) * 59 / 196;
4149 if (!tensRemovable) return;
4150
4151 exp += tensRemovable;
4152
4153 APInt divisor(significand.getBitWidth(), 1);
4154 APInt powten(significand.getBitWidth(), 10);
4155 while (true) {
4156 if (tensRemovable & 1)
4157 divisor *= powten;
4158 tensRemovable >>= 1;
4159 if (!tensRemovable) break;
4160 powten *= powten;
4161 }
4162
4163 significand = significand.udiv(divisor);
4164
4165 // Truncate the significand down to its active bit count.
4166 significand = significand.trunc(significand.getActiveBits());
4167 }
4168
4169
4170 void AdjustToPrecision(SmallVectorImpl<char> &buffer,
4171 int &exp, unsigned FormatPrecision) {
4172 unsigned N = buffer.size();
4173 if (N <= FormatPrecision) return;
4174
4175 // The most significant figures are the last ones in the buffer.
4176 unsigned FirstSignificant = N - FormatPrecision;
4177
4178 // Round.
4179 // FIXME: this probably shouldn't use 'round half up'.
4180
4181 // Rounding down is just a truncation, except we also want to drop
4182 // trailing zeros from the new result.
4183 if (buffer[FirstSignificant - 1] < '5') {
4184 while (FirstSignificant < N && buffer[FirstSignificant] == '0')
4185 FirstSignificant++;
4186
4187 exp += FirstSignificant;
4188 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
4189 return;
4190 }
4191
4192 // Rounding up requires a decimal add-with-carry. If we continue
4193 // the carry, the newly-introduced zeros will just be truncated.
4194 for (unsigned I = FirstSignificant; I != N; ++I) {
4195 if (buffer[I] == '9') {
4196 FirstSignificant++;
4197 } else {
4198 buffer[I]++;
4199 break;
4200 }
4201 }
4202
4203 // If we carried through, we have exactly one digit of precision.
4204 if (FirstSignificant == N) {
4205 exp += FirstSignificant;
4206 buffer.clear();
4207 buffer.push_back('1');
4208 return;
4209 }
4210
4211 exp += FirstSignificant;
4212 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
4213 }
4214
4215 void toStringImpl(SmallVectorImpl<char> &Str, const bool isNeg, int exp,
4216 APInt significand, unsigned FormatPrecision,
4217 unsigned FormatMaxPadding, bool TruncateZero) {
4218 const int semanticsPrecision = significand.getBitWidth();
4219
4220 if (isNeg)
4221 Str.push_back('-');
4222
4223 // Set FormatPrecision if zero. We want to do this before we
4224 // truncate trailing zeros, as those are part of the precision.
4225 if (!FormatPrecision) {
4226 // We use enough digits so the number can be round-tripped back to an
4227 // APFloat. The formula comes from "How to Print Floating-Point Numbers
4228 // Accurately" by Steele and White.
4229 // FIXME: Using a formula based purely on the precision is conservative;
4230 // we can print fewer digits depending on the actual value being printed.
4231
4232 // FormatPrecision = 2 + floor(significandBits / lg_2(10))
4233 FormatPrecision = 2 + semanticsPrecision * 59 / 196;
4234 }
4235
4236 // Ignore trailing binary zeros.
4237 int trailingZeros = significand.countr_zero();
4238 exp += trailingZeros;
4239 significand.lshrInPlace(trailingZeros);
4240
4241 // Change the exponent from 2^e to 10^e.
4242 if (exp == 0) {
4243 // Nothing to do.
4244 } else if (exp > 0) {
4245 // Just shift left.
4246 significand = significand.zext(semanticsPrecision + exp);
4247 significand <<= exp;
4248 exp = 0;
4249 } else { /* exp < 0 */
4250 int texp = -exp;
4251
4252 // We transform this using the identity:
4253 // (N)(2^-e) == (N)(5^e)(10^-e)
4254 // This means we have to multiply N (the significand) by 5^e.
4255 // To avoid overflow, we have to operate on numbers large
4256 // enough to store N * 5^e:
4257 // log2(N * 5^e) == log2(N) + e * log2(5)
4258 // <= semantics->precision + e * 137 / 59
4259 // (log_2(5) ~ 2.321928 < 2.322034 ~ 137/59)
4260
4261 unsigned precision = semanticsPrecision + (137 * texp + 136) / 59;
4262
4263 // Multiply significand by 5^e.
4264 // N * 5^0101 == N * 5^(1*1) * 5^(0*2) * 5^(1*4) * 5^(0*8)
4265 significand = significand.zext(precision);
4266 APInt five_to_the_i(precision, 5);
4267 while (true) {
4268 if (texp & 1)
4269 significand *= five_to_the_i;
4270
4271 texp >>= 1;
4272 if (!texp)
4273 break;
4274 five_to_the_i *= five_to_the_i;
4275 }
4276 }
4277
4278 AdjustToPrecision(significand, exp, FormatPrecision);
4279
4281
4282 // Fill the buffer.
4283 unsigned precision = significand.getBitWidth();
4284 if (precision < 4) {
4285 // We need enough precision to store the value 10.
4286 precision = 4;
4287 significand = significand.zext(precision);
4288 }
4289 APInt ten(precision, 10);
4290 APInt digit(precision, 0);
4291
4292 bool inTrail = true;
4293 while (significand != 0) {
4294 // digit <- significand % 10
4295 // significand <- significand / 10
4296 APInt::udivrem(significand, ten, significand, digit);
4297
4298 unsigned d = digit.getZExtValue();
4299
4300 // Drop trailing zeros.
4301 if (inTrail && !d)
4302 exp++;
4303 else {
4304 buffer.push_back((char) ('0' + d));
4305 inTrail = false;
4306 }
4307 }
4308
4309 assert(!buffer.empty() && "no characters in buffer!");
4310
4311 // Drop down to FormatPrecision.
4312 // TODO: don't do more precise calculations above than are required.
4313 AdjustToPrecision(buffer, exp, FormatPrecision);
4314
4315 unsigned NDigits = buffer.size();
4316
4317 // Check whether we should use scientific notation.
4318 bool FormatScientific;
4319 if (!FormatMaxPadding) {
4320 FormatScientific = true;
4321 } else {
4322 if (exp >= 0) {
4323 // 765e3 --> 765000
4324 // ^^^
4325 // But we shouldn't make the number look more precise than it is.
4326 FormatScientific = ((unsigned) exp > FormatMaxPadding ||
4327 NDigits + (unsigned) exp > FormatPrecision);
4328 } else {
4329 // Power of the most significant digit.
4330 int MSD = exp + (int) (NDigits - 1);
4331 if (MSD >= 0) {
4332 // 765e-2 == 7.65
4333 FormatScientific = false;
4334 } else {
4335 // 765e-5 == 0.00765
4336 // ^ ^^
4337 FormatScientific = ((unsigned) -MSD) > FormatMaxPadding;
4338 }
4339 }
4340 }
4341
4342 // Scientific formatting is pretty straightforward.
4343 if (FormatScientific) {
4344 exp += (NDigits - 1);
4345
4346 Str.push_back(buffer[NDigits-1]);
4347 Str.push_back('.');
4348 if (NDigits == 1 && TruncateZero)
4349 Str.push_back('0');
4350 else
4351 for (unsigned I = 1; I != NDigits; ++I)
4352 Str.push_back(buffer[NDigits-1-I]);
4353 // Fill with zeros up to FormatPrecision.
4354 if (!TruncateZero && FormatPrecision > NDigits - 1)
4355 Str.append(FormatPrecision - NDigits + 1, '0');
4356 // For !TruncateZero we use lower 'e'.
4357 Str.push_back(TruncateZero ? 'E' : 'e');
4358
4359 Str.push_back(exp >= 0 ? '+' : '-');
4360 if (exp < 0)
4361 exp = -exp;
4362 SmallVector<char, 6> expbuf;
4363 do {
4364 expbuf.push_back((char) ('0' + (exp % 10)));
4365 exp /= 10;
4366 } while (exp);
4367 // Exponent always at least two digits if we do not truncate zeros.
4368 if (!TruncateZero && expbuf.size() < 2)
4369 expbuf.push_back('0');
4370 for (unsigned I = 0, E = expbuf.size(); I != E; ++I)
4371 Str.push_back(expbuf[E-1-I]);
4372 return;
4373 }
4374
4375 // Non-scientific, positive exponents.
4376 if (exp >= 0) {
4377 for (unsigned I = 0; I != NDigits; ++I)
4378 Str.push_back(buffer[NDigits-1-I]);
4379 for (unsigned I = 0; I != (unsigned) exp; ++I)
4380 Str.push_back('0');
4381 return;
4382 }
4383
4384 // Non-scientific, negative exponents.
4385
4386 // The number of digits to the left of the decimal point.
4387 int NWholeDigits = exp + (int) NDigits;
4388
4389 unsigned I = 0;
4390 if (NWholeDigits > 0) {
4391 for (; I != (unsigned) NWholeDigits; ++I)
4392 Str.push_back(buffer[NDigits-I-1]);
4393 Str.push_back('.');
4394 } else {
4395 unsigned NZeros = 1 + (unsigned) -NWholeDigits;
4396
4397 Str.push_back('0');
4398 Str.push_back('.');
4399 for (unsigned Z = 1; Z != NZeros; ++Z)
4400 Str.push_back('0');
4401 }
4402
4403 for (; I != NDigits; ++I)
4404 Str.push_back(buffer[NDigits-I-1]);
4405
4406 }
4407} // namespace
4408
4409void IEEEFloat::toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision,
4410 unsigned FormatMaxPadding, bool TruncateZero) const {
4411 switch (category) {
4412 case fcInfinity:
4413 if (isNegative())
4414 return append(Str, "-Inf");
4415 else
4416 return append(Str, "+Inf");
4417
4418 case fcNaN: return append(Str, "NaN");
4419
4420 case fcZero:
4421 if (isNegative())
4422 Str.push_back('-');
4423
4424 if (!FormatMaxPadding) {
4425 if (TruncateZero)
4426 append(Str, "0.0E+0");
4427 else {
4428 append(Str, "0.0");
4429 if (FormatPrecision > 1)
4430 Str.append(FormatPrecision - 1, '0');
4431 append(Str, "e+00");
4432 }
4433 } else {
4434 Str.push_back('0');
4435 }
4436 return;
4437
4438 case fcNormal:
4439 break;
4440 }
4441
4442 // Decompose the number into an APInt and an exponent.
4443 int exp = exponent - ((int) semantics->precision - 1);
4444 APInt significand(
4445 semantics->precision,
4446 ArrayRef(significandParts(), partCountForBits(semantics->precision)));
4447
4448 toStringImpl(Str, isNegative(), exp, significand, FormatPrecision,
4449 FormatMaxPadding, TruncateZero);
4450
4451}
4452
4454 if (!isFinite() || isZero())
4455 return INT_MIN;
4456
4457 const integerPart *Parts = significandParts();
4458 const int PartCount = partCountForBits(semantics->precision);
4459
4460 int PopCount = 0;
4461 for (int i = 0; i < PartCount; ++i) {
4462 PopCount += llvm::popcount(Parts[i]);
4463 if (PopCount > 1)
4464 return INT_MIN;
4465 }
4466
4467 if (exponent != semantics->minExponent)
4468 return exponent;
4469
4470 int CountrParts = 0;
4471 for (int i = 0; i < PartCount;
4472 ++i, CountrParts += APInt::APINT_BITS_PER_WORD) {
4473 if (Parts[i] != 0) {
4474 return exponent - semantics->precision + CountrParts +
4475 llvm::countr_zero(Parts[i]) + 1;
4476 }
4477 }
4478
4479 llvm_unreachable("didn't find the set bit");
4480}
4481
4483 if (!isNaN())
4484 return false;
4485 if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly ||
4486 semantics->nonFiniteBehavior == fltNonfiniteBehavior::FiniteOnly)
4487 return false;
4488
4489 // IEEE-754R 2008 6.2.1: A signaling NaN bit string should be encoded with the
4490 // first bit of the trailing significand being 0.
4491 return !APInt::tcExtractBit(significandParts(), semantics->precision - 2);
4492}
4493
4494/// IEEE-754R 2008 5.3.1: nextUp/nextDown.
4495///
4496/// *NOTE* since nextDown(x) = -nextUp(-x), we only implement nextUp with
4497/// appropriate sign switching before/after the computation.
4499 // If we are performing nextDown, swap sign so we have -x.
4500 if (nextDown)
4501 changeSign();
4502
4503 // Compute nextUp(x)
4504 opStatus result = opOK;
4505
4506 // Handle each float category separately.
4507 switch (category) {
4508 case fcInfinity:
4509 // nextUp(+inf) = +inf
4510 if (!isNegative())
4511 break;
4512 // nextUp(-inf) = -getLargest()
4513 makeLargest(true);
4514 break;
4515 case fcNaN:
4516 // IEEE-754R 2008 6.2 Par 2: nextUp(sNaN) = qNaN. Set Invalid flag.
4517 // IEEE-754R 2008 6.2: nextUp(qNaN) = qNaN. Must be identity so we do not
4518 // change the payload.
4519 if (isSignaling()) {
4520 result = opInvalidOp;
4521 // For consistency, propagate the sign of the sNaN to the qNaN.
4522 makeNaN(false, isNegative(), nullptr);
4523 }
4524 break;
4525 case fcZero:
4526 // nextUp(pm 0) = +getSmallest()
4527 makeSmallest(false);
4528 break;
4529 case fcNormal:
4530 // nextUp(-getSmallest()) = -0
4531 if (isSmallest() && isNegative()) {
4532 APInt::tcSet(significandParts(), 0, partCount());
4533 category = fcZero;
4534 exponent = 0;
4535 if (semantics->nanEncoding == fltNanEncoding::NegativeZero)
4536 sign = false;
4537 if (!semantics->hasZero)
4539 break;
4540 }
4541
4542 if (isLargest() && !isNegative()) {
4543 if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly) {
4544 // nextUp(getLargest()) == NAN
4545 makeNaN();
4546 break;
4547 } else if (semantics->nonFiniteBehavior ==
4549 // nextUp(getLargest()) == getLargest()
4550 break;
4551 } else {
4552 // nextUp(getLargest()) == INFINITY
4553 APInt::tcSet(significandParts(), 0, partCount());
4554 category = fcInfinity;
4555 exponent = semantics->maxExponent + 1;
4556 break;
4557 }
4558 }
4559
4560 // nextUp(normal) == normal + inc.
4561 if (isNegative()) {
4562 // If we are negative, we need to decrement the significand.
4563
4564 // We only cross a binade boundary that requires adjusting the exponent
4565 // if:
4566 // 1. exponent != semantics->minExponent. This implies we are not in the
4567 // smallest binade or are dealing with denormals.
4568 // 2. Our significand excluding the integral bit is all zeros.
4569 bool WillCrossBinadeBoundary =
4570 exponent != semantics->minExponent && isSignificandAllZeros();
4571
4572 // Decrement the significand.
4573 //
4574 // We always do this since:
4575 // 1. If we are dealing with a non-binade decrement, by definition we
4576 // just decrement the significand.
4577 // 2. If we are dealing with a normal -> normal binade decrement, since
4578 // we have an explicit integral bit the fact that all bits but the
4579 // integral bit are zero implies that subtracting one will yield a
4580 // significand with 0 integral bit and 1 in all other spots. Thus we
4581 // must just adjust the exponent and set the integral bit to 1.
4582 // 3. If we are dealing with a normal -> denormal binade decrement,
4583 // since we set the integral bit to 0 when we represent denormals, we
4584 // just decrement the significand.
4585 integerPart *Parts = significandParts();
4586 APInt::tcDecrement(Parts, partCount());
4587
4588 if (WillCrossBinadeBoundary) {
4589 // Our result is a normal number. Do the following:
4590 // 1. Set the integral bit to 1.
4591 // 2. Decrement the exponent.
4592 APInt::tcSetBit(Parts, semantics->precision - 1);
4593 exponent--;
4594 }
4595 } else {
4596 // If we are positive, we need to increment the significand.
4597
4598 // We only cross a binade boundary that requires adjusting the exponent if
4599 // the input is not a denormal and all of said input's significand bits
4600 // are set. If all of said conditions are true: clear the significand, set
4601 // the integral bit to 1, and increment the exponent. If we have a
4602 // denormal always increment since moving denormals and the numbers in the
4603 // smallest normal binade have the same exponent in our representation.
4604 // If there are only exponents, any increment always crosses the
4605 // BinadeBoundary.
4606 bool WillCrossBinadeBoundary = !APFloat::hasSignificand(*semantics) ||
4607 (!isDenormal() && isSignificandAllOnes());
4608
4609 if (WillCrossBinadeBoundary) {
4610 integerPart *Parts = significandParts();
4611 APInt::tcSet(Parts, 0, partCount());
4612 APInt::tcSetBit(Parts, semantics->precision - 1);
4613 assert(exponent != semantics->maxExponent &&
4614 "We can not increment an exponent beyond the maxExponent allowed"
4615 " by the given floating point semantics.");
4616 exponent++;
4617 } else {
4618 incrementSignificand();
4619 }
4620 }
4621 break;
4622 }
4623
4624 // If we are performing nextDown, swap sign so we have -nextUp(-x)
4625 if (nextDown)
4626 changeSign();
4627
4628 return result;
4629}
4630
4632 assert(isNaN() && "Can only be called on NaN values");
4633 // Number of bits in the payload, excluding the (maybe implied) integer bit.
4634 unsigned Bits = semantics->precision - 1;
4635 return APInt(Bits, ArrayRef(significandParts(), partCountForBits(Bits)));
4636}
4637
4638APFloatBase::ExponentType IEEEFloat::exponentNaN() const {
4639 return ::exponentNaN(*semantics);
4640}
4641
4642APFloatBase::ExponentType IEEEFloat::exponentInf() const {
4643 return ::exponentInf(*semantics);
4644}
4645
4646APFloatBase::ExponentType IEEEFloat::exponentZero() const {
4647 return ::exponentZero(*semantics);
4648}
4649
4650void IEEEFloat::makeInf(bool Negative) {
4651 if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::FiniteOnly)
4652 llvm_unreachable("This floating point format does not support Inf");
4653
4654 if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly) {
4655 // There is no Inf, so make NaN instead.
4656 makeNaN(false, Negative);
4657 return;
4658 }
4659 category = fcInfinity;
4660 sign = Negative;
4661 exponent = exponentInf();
4662 APInt::tcSet(significandParts(), 0, partCount());
4663}
4664
4665void IEEEFloat::makeZero(bool Negative) {
4666 if (!semantics->hasZero)
4667 llvm_unreachable("This floating point format does not support Zero");
4668
4669 category = fcZero;
4670 sign = Negative;
4671 if (semantics->nanEncoding == fltNanEncoding::NegativeZero) {
4672 // Merge negative zero to positive because 0b10000...000 is used for NaN
4673 sign = false;
4674 }
4675 exponent = exponentZero();
4676 APInt::tcSet(significandParts(), 0, partCount());
4677}
4678
4680 assert(isNaN());
4681 if (semantics->nonFiniteBehavior != fltNonfiniteBehavior::NanOnly)
4682 APInt::tcSetBit(significandParts(), semantics->precision - 2);
4683}
4684
4685int ilogb(const IEEEFloat &Arg) {
4686 if (Arg.isNaN())
4687 return APFloat::IEK_NaN;
4688 if (Arg.isZero())
4689 return APFloat::IEK_Zero;
4690 if (Arg.isInfinity())
4691 return APFloat::IEK_Inf;
4692 if (!Arg.isDenormal())
4693 return Arg.exponent;
4694
4695 IEEEFloat Normalized(Arg);
4696 int SignificandBits = Arg.getSemantics().precision - 1;
4697
4698 Normalized.exponent += SignificandBits;
4699 Normalized.normalize(APFloat::rmNearestTiesToEven, lfExactlyZero);
4700 return Normalized.exponent - SignificandBits;
4701}
4702
4704 auto MaxExp = X.getSemantics().maxExponent;
4705 auto MinExp = X.getSemantics().minExponent;
4706
4707 // If Exp is wildly out-of-scale, simply adding it to X.exponent will
4708 // overflow; clamp it to a safe range before adding, but ensure that the range
4709 // is large enough that the clamp does not change the result. The range we
4710 // need to support is the difference between the largest possible exponent and
4711 // the normalized exponent of half the smallest denormal.
4712
4713 int SignificandBits = X.getSemantics().precision - 1;
4714 int MaxIncrement = MaxExp - (MinExp - SignificandBits) + 1;
4715
4716 // Clamp to one past the range ends to let normalize handle overlflow.
4717 X.exponent += std::clamp(Exp, -MaxIncrement - 1, MaxIncrement);
4718 X.normalize(RoundingMode, lfExactlyZero);
4719 if (X.isNaN())
4720 X.makeQuiet();
4721 return X;
4722}
4723
4724IEEEFloat frexp(const IEEEFloat &Val, int &Exp, roundingMode RM) {
4725 Exp = ilogb(Val);
4726
4727 // Quiet signalling nans.
4728 if (Exp == APFloat::IEK_NaN) {
4729 IEEEFloat Quiet(Val);
4730 Quiet.makeQuiet();
4731 return Quiet;
4732 }
4733
4734 if (Exp == APFloat::IEK_Inf)
4735 return Val;
4736
4737 // 1 is added because frexp is defined to return a normalized fraction in
4738 // +/-[0.5, 1.0), rather than the usual +/-[1.0, 2.0).
4739 Exp = Exp == APFloat::IEK_Zero ? 0 : Exp + 1;
4740 return scalbn(Val, -Exp, RM);
4741}
4742
4744 : Semantics(&S),
4745 Floats(new APFloat[2]{APFloat(APFloatBase::semIEEEdouble),
4746 APFloat(APFloatBase::semIEEEdouble)}) {
4747 assert(Semantics == &APFloatBase::semPPCDoubleDouble);
4748}
4749
4751 : Semantics(&S), Floats(new APFloat[2]{
4752 APFloat(APFloatBase::semIEEEdouble, uninitialized),
4753 APFloat(APFloatBase::semIEEEdouble, uninitialized)}) {
4754 assert(Semantics == &APFloatBase::semPPCDoubleDouble);
4755}
4756
4758 : Semantics(&S),
4759 Floats(new APFloat[2]{APFloat(APFloatBase::semIEEEdouble, I),
4760 APFloat(APFloatBase::semIEEEdouble)}) {
4761 assert(Semantics == &APFloatBase::semPPCDoubleDouble);
4762}
4763
4765 : Semantics(&S),
4766 Floats(new APFloat[2]{
4767 APFloat(APFloatBase::semIEEEdouble, APInt(64, I.getRawData()[0])),
4768 APFloat(APFloatBase::semIEEEdouble, APInt(64, I.getRawData()[1]))}) {
4769 assert(Semantics == &APFloatBase::semPPCDoubleDouble);
4770}
4771
4773 APFloat &&Second)
4774 : Semantics(&S),
4775 Floats(new APFloat[2]{std::move(First), std::move(Second)}) {
4776 assert(Semantics == &APFloatBase::semPPCDoubleDouble);
4777 assert(&Floats[0].getSemantics() == &APFloatBase::semIEEEdouble);
4778 assert(&Floats[1].getSemantics() == &APFloatBase::semIEEEdouble);
4779}
4780
4782 : Semantics(RHS.Semantics),
4783 Floats(RHS.Floats ? new APFloat[2]{APFloat(RHS.Floats[0]),
4784 APFloat(RHS.Floats[1])}
4785 : nullptr) {
4786 assert(Semantics == &APFloatBase::semPPCDoubleDouble);
4787}
4788
4790 : Semantics(RHS.Semantics), Floats(RHS.Floats) {
4791 RHS.Semantics = &APFloatBase::semBogus;
4792 RHS.Floats = nullptr;
4793 assert(Semantics == &APFloatBase::semPPCDoubleDouble);
4794}
4795
4797 if (Semantics == RHS.Semantics && RHS.Floats) {
4798 Floats[0] = RHS.Floats[0];
4799 Floats[1] = RHS.Floats[1];
4800 } else if (this != &RHS) {
4801 this->~DoubleAPFloat();
4802 new (this) DoubleAPFloat(RHS);
4803 }
4804 return *this;
4805}
4806
4807// Returns a result such that:
4808// 1. abs(Lo) <= ulp(Hi)/2
4809// 2. Hi == RTNE(Hi + Lo)
4810// 3. Hi + Lo == X + Y
4811//
4812// Requires that log2(X) >= log2(Y).
4813static std::pair<APFloat, APFloat> fastTwoSum(APFloat X, APFloat Y) {
4814 if (!X.isFinite())
4815 return {X, APFloat::getZero(X.getSemantics(), /*Negative=*/false)};
4816 APFloat Hi = X + Y;
4817 APFloat Delta = Hi - X;
4818 APFloat Lo = Y - Delta;
4819 return {Hi, Lo};
4820}
4821
4822// Implement addition, subtraction, multiplication and division based on:
4823// "Software for Doubled-Precision Floating-Point Computations",
4824// by Seppo Linnainmaa, ACM TOMS vol 7 no 3, September 1981, pages 272-283.
4825APFloat::opStatus DoubleAPFloat::addImpl(const APFloat &a, const APFloat &aa,
4826 const APFloat &c, const APFloat &cc,
4827 roundingMode RM) {
4828 int Status = opOK;
4829 APFloat z = a;
4830 Status |= z.add(c, RM);
4831 if (!z.isFinite()) {
4832 if (!z.isInfinity()) {
4833 Floats[0] = std::move(z);
4834 Floats[1].makeZero(/* Neg = */ false);
4835 return (opStatus)Status;
4836 }
4837 Status = opOK;
4838 auto AComparedToC = a.compareAbsoluteValue(c);
4839 z = cc;
4840 Status |= z.add(aa, RM);
4841 if (AComparedToC == APFloat::cmpGreaterThan) {
4842 // z = cc + aa + c + a;
4843 Status |= z.add(c, RM);
4844 Status |= z.add(a, RM);
4845 } else {
4846 // z = cc + aa + a + c;
4847 Status |= z.add(a, RM);
4848 Status |= z.add(c, RM);
4849 }
4850 if (!z.isFinite()) {
4851 Floats[0] = std::move(z);
4852 Floats[1].makeZero(/* Neg = */ false);
4853 return (opStatus)Status;
4854 }
4855 Floats[0] = z;
4856 APFloat zz = aa;
4857 Status |= zz.add(cc, RM);
4858 if (AComparedToC == APFloat::cmpGreaterThan) {
4859 // Floats[1] = a - z + c + zz;
4860 Floats[1] = a;
4861 Status |= Floats[1].subtract(z, RM);
4862 Status |= Floats[1].add(c, RM);
4863 Status |= Floats[1].add(zz, RM);
4864 } else {
4865 // Floats[1] = c - z + a + zz;
4866 Floats[1] = c;
4867 Status |= Floats[1].subtract(z, RM);
4868 Status |= Floats[1].add(a, RM);
4869 Status |= Floats[1].add(zz, RM);
4870 }
4871 } else {
4872 // q = a - z;
4873 APFloat q = a;
4874 Status |= q.subtract(z, RM);
4875
4876 // zz = q + c + (a - (q + z)) + aa + cc;
4877 // Compute a - (q + z) as -((q + z) - a) to avoid temporary copies.
4878 auto zz = q;
4879 Status |= zz.add(c, RM);
4880 Status |= q.add(z, RM);
4881 Status |= q.subtract(a, RM);
4882 q.changeSign();
4883 Status |= zz.add(q, RM);
4884 Status |= zz.add(aa, RM);
4885 Status |= zz.add(cc, RM);
4886 if (zz.isZero() && !zz.isNegative()) {
4887 Floats[0] = std::move(z);
4888 Floats[1].makeZero(/* Neg = */ false);
4889 return opOK;
4890 }
4891 Floats[0] = z;
4892 Status |= Floats[0].add(zz, RM);
4893 if (!Floats[0].isFinite()) {
4894 Floats[1].makeZero(/* Neg = */ false);
4895 return (opStatus)Status;
4896 }
4897 Floats[1] = std::move(z);
4898 Status |= Floats[1].subtract(Floats[0], RM);
4899 Status |= Floats[1].add(zz, RM);
4900 }
4901 return (opStatus)Status;
4902}
4903
4904APFloat::opStatus DoubleAPFloat::addWithSpecial(const DoubleAPFloat &LHS,
4905 const DoubleAPFloat &RHS,
4906 DoubleAPFloat &Out,
4907 roundingMode RM) {
4908 if (LHS.getCategory() == fcNaN) {
4909 Out = LHS;
4910 return opOK;
4911 }
4912 if (RHS.getCategory() == fcNaN) {
4913 Out = RHS;
4914 return opOK;
4915 }
4916 if (LHS.getCategory() == fcZero) {
4917 Out = RHS;
4918 return opOK;
4919 }
4920 if (RHS.getCategory() == fcZero) {
4921 Out = LHS;
4922 return opOK;
4923 }
4924 if (LHS.getCategory() == fcInfinity && RHS.getCategory() == fcInfinity &&
4925 LHS.isNegative() != RHS.isNegative()) {
4926 Out.makeNaN(false, Out.isNegative(), nullptr);
4927 return opInvalidOp;
4928 }
4929 if (LHS.getCategory() == fcInfinity) {
4930 Out = LHS;
4931 return opOK;
4932 }
4933 if (RHS.getCategory() == fcInfinity) {
4934 Out = RHS;
4935 return opOK;
4936 }
4937 assert(LHS.getCategory() == fcNormal && RHS.getCategory() == fcNormal);
4938
4939 APFloat A(LHS.Floats[0]), AA(LHS.Floats[1]), C(RHS.Floats[0]),
4940 CC(RHS.Floats[1]);
4941 assert(&A.getSemantics() == &APFloatBase::semIEEEdouble);
4942 assert(&AA.getSemantics() == &APFloatBase::semIEEEdouble);
4943 assert(&C.getSemantics() == &APFloatBase::semIEEEdouble);
4944 assert(&CC.getSemantics() == &APFloatBase::semIEEEdouble);
4945 assert(&Out.Floats[0].getSemantics() == &APFloatBase::semIEEEdouble);
4946 assert(&Out.Floats[1].getSemantics() == &APFloatBase::semIEEEdouble);
4947 return Out.addImpl(A, AA, C, CC, RM);
4948}
4949
4951 roundingMode RM) {
4952 return addWithSpecial(*this, RHS, *this, RM);
4953}
4954
4956 roundingMode RM) {
4957 changeSign();
4958 auto Ret = add(RHS, RM);
4959 changeSign();
4960 return Ret;
4961}
4962
4965 const auto &LHS = *this;
4966 auto &Out = *this;
4967 /* Interesting observation: For special categories, finding the lowest
4968 common ancestor of the following layered graph gives the correct
4969 return category:
4970
4971 NaN
4972 / \
4973 Zero Inf
4974 \ /
4975 Normal
4976
4977 e.g. NaN * NaN = NaN
4978 Zero * Inf = NaN
4979 Normal * Zero = Zero
4980 Normal * Inf = Inf
4981 */
4982 if (LHS.getCategory() == fcNaN) {
4983 Out = LHS;
4984 return opOK;
4985 }
4986 if (RHS.getCategory() == fcNaN) {
4987 Out = RHS;
4988 return opOK;
4989 }
4990 if ((LHS.getCategory() == fcZero && RHS.getCategory() == fcInfinity) ||
4991 (LHS.getCategory() == fcInfinity && RHS.getCategory() == fcZero)) {
4992 Out.makeNaN(false, false, nullptr);
4993 return opOK;
4994 }
4995 if (LHS.getCategory() == fcZero || LHS.getCategory() == fcInfinity) {
4996 Out = LHS;
4997 return opOK;
4998 }
4999 if (RHS.getCategory() == fcZero || RHS.getCategory() == fcInfinity) {
5000 Out = RHS;
5001 return opOK;
5002 }
5003 assert(LHS.getCategory() == fcNormal && RHS.getCategory() == fcNormal &&
5004 "Special cases not handled exhaustively");
5005
5006 int Status = opOK;
5007 APFloat A = Floats[0], B = Floats[1], C = RHS.Floats[0], D = RHS.Floats[1];
5008 // t = a * c
5009 APFloat T = A;
5010 Status |= T.multiply(C, RM);
5011 if (!T.isFiniteNonZero()) {
5012 Floats[0] = std::move(T);
5013 Floats[1].makeZero(/* Neg = */ false);
5014 return (opStatus)Status;
5015 }
5016
5017 // tau = fmsub(a, c, t), that is -fmadd(-a, c, t).
5018 APFloat Tau = A;
5019 T.changeSign();
5020 Status |= Tau.fusedMultiplyAdd(C, T, RM);
5021 T.changeSign();
5022 {
5023 // v = a * d
5024 APFloat V = A;
5025 Status |= V.multiply(D, RM);
5026 // w = b * c
5027 APFloat W = B;
5028 Status |= W.multiply(C, RM);
5029 Status |= V.add(W, RM);
5030 // tau += v + w
5031 Status |= Tau.add(V, RM);
5032 }
5033 // u = t + tau
5034 APFloat U = T;
5035 Status |= U.add(Tau, RM);
5036
5037 Floats[0] = U;
5038 if (!U.isFinite()) {
5039 Floats[1].makeZero(/* Neg = */ false);
5040 } else {
5041 // Floats[1] = (t - u) + tau
5042 Status |= T.subtract(U, RM);
5043 Status |= T.add(Tau, RM);
5044 Floats[1] = std::move(T);
5045 }
5046 return (opStatus)Status;
5047}
5048
5051 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5052 "Unexpected Semantics");
5053 APFloat Tmp(APFloatBase::semPPCDoubleDoubleLegacy, bitcastToAPInt());
5054 auto Ret = Tmp.divide(
5055 APFloat(APFloatBase::semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt()), RM);
5056 *this = DoubleAPFloat(APFloatBase::semPPCDoubleDouble, Tmp.bitcastToAPInt());
5057 return Ret;
5058}
5059
5061 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5062 "Unexpected Semantics");
5063 APFloat Tmp(APFloatBase::semPPCDoubleDoubleLegacy, bitcastToAPInt());
5064 auto Ret = Tmp.remainder(
5065 APFloat(APFloatBase::semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt()));
5066 *this = DoubleAPFloat(APFloatBase::semPPCDoubleDouble, Tmp.bitcastToAPInt());
5067 return Ret;
5068}
5069
5071 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5072 "Unexpected Semantics");
5073 APFloat Tmp(APFloatBase::semPPCDoubleDoubleLegacy, bitcastToAPInt());
5074 auto Ret = Tmp.mod(
5075 APFloat(APFloatBase::semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt()));
5076 *this = DoubleAPFloat(APFloatBase::semPPCDoubleDouble, Tmp.bitcastToAPInt());
5077 return Ret;
5078}
5079
5082 const DoubleAPFloat &Addend,
5084 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5085 "Unexpected Semantics");
5086 APFloat Tmp(APFloatBase::semPPCDoubleDoubleLegacy, bitcastToAPInt());
5087 auto Ret = Tmp.fusedMultiplyAdd(
5088 APFloat(APFloatBase::semPPCDoubleDoubleLegacy,
5089 Multiplicand.bitcastToAPInt()),
5090 APFloat(APFloatBase::semPPCDoubleDoubleLegacy, Addend.bitcastToAPInt()),
5091 RM);
5092 *this = DoubleAPFloat(APFloatBase::semPPCDoubleDouble, Tmp.bitcastToAPInt());
5093 return Ret;
5094}
5095
5097 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5098 "Unexpected Semantics");
5099 const APFloat &Hi = getFirst();
5100 const APFloat &Lo = getSecond();
5101
5102 APFloat RoundedHi = Hi;
5103 const opStatus HiStatus = RoundedHi.roundToIntegral(RM);
5104
5105 // We can reduce the problem to just the high part if the input:
5106 // 1. Represents a non-finite value.
5107 // 2. Has a component which is zero.
5108 if (!Hi.isFiniteNonZero() || Lo.isZero()) {
5109 Floats[0] = std::move(RoundedHi);
5110 Floats[1].makeZero(/*Neg=*/false);
5111 return HiStatus;
5112 }
5113
5114 // Adjust `Rounded` in the direction of `TieBreaker` if `ToRound` was at a
5115 // halfway point.
5116 auto RoundToNearestHelper = [](APFloat ToRound, APFloat Rounded,
5117 APFloat TieBreaker) {
5118 // RoundingError tells us which direction we rounded:
5119 // - RoundingError > 0: we rounded up.
5120 // - RoundingError < 0: we rounded down.
5121 // Sterbenz' lemma ensures that RoundingError is exact.
5122 const APFloat RoundingError = Rounded - ToRound;
5123 if (TieBreaker.isNonZero() &&
5124 TieBreaker.isNegative() != RoundingError.isNegative() &&
5125 abs(RoundingError).isExactlyValue(0.5))
5126 Rounded.add(
5127 APFloat::getOne(Rounded.getSemantics(), TieBreaker.isNegative()),
5129 return Rounded;
5130 };
5131
5132 // Case 1: Hi is not an integer.
5133 // Special cases are for rounding modes that are sensitive to ties.
5134 if (RoundedHi != Hi) {
5135 // We need to consider the case where Hi was between two integers and the
5136 // rounding mode broke the tie when, in fact, Lo may have had a different
5137 // sign than Hi.
5138 if (RM == rmNearestTiesToAway || RM == rmNearestTiesToEven)
5139 RoundedHi = RoundToNearestHelper(Hi, RoundedHi, Lo);
5140
5141 Floats[0] = std::move(RoundedHi);
5142 Floats[1].makeZero(/*Neg=*/false);
5143 return HiStatus;
5144 }
5145
5146 // Case 2: Hi is an integer.
5147 // Special cases are for rounding modes which are rounding towards or away from zero.
5148 RoundingMode LoRoundingMode;
5149 if (RM == rmTowardZero)
5150 // When our input is positive, we want the Lo component rounded toward
5151 // negative infinity to get the smallest result magnitude. Likewise,
5152 // negative inputs want the Lo component rounded toward positive infinity.
5153 LoRoundingMode = isNegative() ? rmTowardPositive : rmTowardNegative;
5154 else
5155 LoRoundingMode = RM;
5156
5157 APFloat RoundedLo = Lo;
5158 const opStatus LoStatus = RoundedLo.roundToIntegral(LoRoundingMode);
5159 if (LoRoundingMode == rmNearestTiesToAway)
5160 // We need to consider the case where Lo was between two integers and the
5161 // rounding mode broke the tie when, in fact, Hi may have had a different
5162 // sign than Lo.
5163 RoundedLo = RoundToNearestHelper(Lo, RoundedLo, Hi);
5164
5165 // We must ensure that the final result has no overlap between the two APFloat values.
5166 std::tie(RoundedHi, RoundedLo) = fastTwoSum(RoundedHi, RoundedLo);
5167
5168 Floats[0] = std::move(RoundedHi);
5169 Floats[1] = std::move(RoundedLo);
5170 return LoStatus;
5171}
5172
5174 Floats[0].changeSign();
5175 Floats[1].changeSign();
5176}
5177
5180 // Compare absolute values of the high parts.
5181 const cmpResult HiPartCmp = Floats[0].compareAbsoluteValue(RHS.Floats[0]);
5182 if (HiPartCmp != cmpEqual)
5183 return HiPartCmp;
5184
5185 // Zero, regardless of sign, is equal.
5186 if (Floats[1].isZero() && RHS.Floats[1].isZero())
5187 return cmpEqual;
5188
5189 // At this point, |this->Hi| == |RHS.Hi|.
5190 // The magnitude is |Hi+Lo| which is Hi+|Lo| if signs of Hi and Lo are the
5191 // same, and Hi-|Lo| if signs are different.
5192 const bool ThisIsSubtractive =
5193 Floats[0].isNegative() != Floats[1].isNegative();
5194 const bool RHSIsSubtractive =
5195 RHS.Floats[0].isNegative() != RHS.Floats[1].isNegative();
5196
5197 // Case 1: The low part of 'this' is zero.
5198 if (Floats[1].isZero())
5199 // We are comparing |Hi| vs. |Hi| ± |RHS.Lo|.
5200 // If RHS is subtractive, its magnitude is smaller.
5201 // If RHS is additive, its magnitude is larger.
5202 return RHSIsSubtractive ? cmpGreaterThan : cmpLessThan;
5203
5204 // Case 2: The low part of 'RHS' is zero (and we know 'this' is not).
5205 if (RHS.Floats[1].isZero())
5206 // We are comparing |Hi| ± |This.Lo| vs. |Hi|.
5207 // If 'this' is subtractive, its magnitude is smaller.
5208 // If 'this' is additive, its magnitude is larger.
5209 return ThisIsSubtractive ? cmpLessThan : cmpGreaterThan;
5210
5211 // If their natures differ, the additive one is larger.
5212 if (ThisIsSubtractive != RHSIsSubtractive)
5213 return ThisIsSubtractive ? cmpLessThan : cmpGreaterThan;
5214
5215 // Case 3: Both are additive (Hi+|Lo|) or both are subtractive (Hi-|Lo|).
5216 // The comparison now depends on the magnitude of the low parts.
5217 const cmpResult LoPartCmp = Floats[1].compareAbsoluteValue(RHS.Floats[1]);
5218
5219 if (ThisIsSubtractive) {
5220 // Both are subtractive (Hi-|Lo|), so the comparison of |Lo| is inverted.
5221 if (LoPartCmp == cmpLessThan)
5222 return cmpGreaterThan;
5223 if (LoPartCmp == cmpGreaterThan)
5224 return cmpLessThan;
5225 }
5226
5227 // If additive, the comparison of |Lo| is direct.
5228 // If equal, they are equal.
5229 return LoPartCmp;
5230}
5231
5233 return Floats[0].getCategory();
5234}
5235
5236bool DoubleAPFloat::isNegative() const { return Floats[0].isNegative(); }
5237
5239 Floats[0].makeInf(Neg);
5240 Floats[1].makeZero(/* Neg = */ false);
5241}
5242
5244 Floats[0].makeZero(Neg);
5245 Floats[1].makeZero(/* Neg = */ false);
5246}
5247
5249 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5250 "Unexpected Semantics");
5251 Floats[0] =
5252 APFloat(APFloatBase::semIEEEdouble, APInt(64, 0x7fefffffffffffffull));
5253 Floats[1] =
5254 APFloat(APFloatBase::semIEEEdouble, APInt(64, 0x7c8ffffffffffffeull));
5255 if (Neg)
5256 changeSign();
5257}
5258
5260 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5261 "Unexpected Semantics");
5262 Floats[0].makeSmallest(Neg);
5263 Floats[1].makeZero(/* Neg = */ false);
5264}
5265
5267 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5268 "Unexpected Semantics");
5269 Floats[0] =
5270 APFloat(APFloatBase::semIEEEdouble, APInt(64, 0x0360000000000000ull));
5271 if (Neg)
5272 Floats[0].changeSign();
5273 Floats[1].makeZero(/* Neg = */ false);
5274}
5275
5276void DoubleAPFloat::makeNaN(bool SNaN, bool Neg, const APInt *fill) {
5277 Floats[0].makeNaN(SNaN, Neg, fill);
5278 Floats[1].makeZero(/* Neg = */ false);
5279}
5280
5282 auto Result = Floats[0].compare(RHS.Floats[0]);
5283 // |Float[0]| > |Float[1]|
5284 if (Result == APFloat::cmpEqual)
5285 return Floats[1].compare(RHS.Floats[1]);
5286 return Result;
5287}
5288
5290 return Floats[0].bitwiseIsEqual(RHS.Floats[0]) &&
5291 Floats[1].bitwiseIsEqual(RHS.Floats[1]);
5292}
5293
5295 if (Arg.Floats)
5296 return hash_combine(hash_value(Arg.Floats[0]), hash_value(Arg.Floats[1]));
5297 return hash_combine(Arg.Semantics);
5298}
5299
5301 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5302 "Unexpected Semantics");
5303 uint64_t Data[] = {
5304 Floats[0].bitcastToAPInt().getRawData()[0],
5305 Floats[1].bitcastToAPInt().getRawData()[0],
5306 };
5307 return APInt(128, Data);
5308}
5309
5311 roundingMode RM) {
5312 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5313 "Unexpected Semantics");
5314 APFloat Tmp(APFloatBase::semPPCDoubleDoubleLegacy);
5315 auto Ret = Tmp.convertFromString(S, RM);
5316 *this = DoubleAPFloat(APFloatBase::semPPCDoubleDouble, Tmp.bitcastToAPInt());
5317 return Ret;
5318}
5319
5320// The double-double lattice of values corresponds to numbers which obey:
5321// - abs(lo) <= 1/2 * ulp(hi)
5322// - roundTiesToEven(hi + lo) == hi
5323//
5324// nextUp must choose the smallest output > input that follows these rules.
5325// nexDown must choose the largest output < input that follows these rules.
5327 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5328 "Unexpected Semantics");
5329 // nextDown(x) = -nextUp(-x)
5330 if (nextDown) {
5331 changeSign();
5332 APFloat::opStatus Result = next(/*nextDown=*/false);
5333 changeSign();
5334 return Result;
5335 }
5336 switch (getCategory()) {
5337 case fcInfinity:
5338 // nextUp(+inf) = +inf
5339 // nextUp(-inf) = -getLargest()
5340 if (isNegative())
5341 makeLargest(true);
5342 return opOK;
5343
5344 case fcNaN:
5345 // IEEE-754R 2008 6.2 Par 2: nextUp(sNaN) = qNaN. Set Invalid flag.
5346 // IEEE-754R 2008 6.2: nextUp(qNaN) = qNaN. Must be identity so we do not
5347 // change the payload.
5348 if (getFirst().isSignaling()) {
5349 // For consistency, propagate the sign of the sNaN to the qNaN.
5350 makeNaN(false, isNegative(), nullptr);
5351 return opInvalidOp;
5352 }
5353 return opOK;
5354
5355 case fcZero:
5356 // nextUp(pm 0) = +getSmallest()
5357 makeSmallest(false);
5358 return opOK;
5359
5360 case fcNormal:
5361 break;
5362 }
5363
5364 const APFloat &HiOld = getFirst();
5365 const APFloat &LoOld = getSecond();
5366
5367 APFloat NextLo = LoOld;
5368 NextLo.next(/*nextDown=*/false);
5369
5370 // We want to admit values where:
5371 // 1. abs(Lo) <= ulp(Hi)/2
5372 // 2. Hi == RTNE(Hi + lo)
5373 auto InLattice = [](const APFloat &Hi, const APFloat &Lo) {
5374 return Hi + Lo == Hi;
5375 };
5376
5377 // Check if (HiOld, nextUp(LoOld) is in the lattice.
5378 if (InLattice(HiOld, NextLo)) {
5379 // Yes, the result is (HiOld, nextUp(LoOld)).
5380 Floats[1] = std::move(NextLo);
5381
5382 // TODO: Because we currently rely on semPPCDoubleDoubleLegacy, our maximum
5383 // value is defined to have exactly 106 bits of precision. This limitation
5384 // results in semPPCDoubleDouble being unable to reach its maximum canonical
5385 // value.
5386 DoubleAPFloat Largest{*Semantics, uninitialized};
5387 Largest.makeLargest(/*Neg=*/false);
5388 if (compare(Largest) == cmpGreaterThan)
5389 makeInf(/*Neg=*/false);
5390
5391 return opOK;
5392 }
5393
5394 // Now we need to handle the cases where (HiOld, nextUp(LoOld)) is not the
5395 // correct result. We know the new hi component will be nextUp(HiOld) but our
5396 // lattice rules make it a little ambiguous what the correct NextLo must be.
5397 APFloat NextHi = HiOld;
5398 NextHi.next(/*nextDown=*/false);
5399
5400 // nextUp(getLargest()) == INFINITY
5401 if (NextHi.isInfinity()) {
5402 makeInf(/*Neg=*/false);
5403 return opOK;
5404 }
5405
5406 // IEEE 754-2019 5.3.1:
5407 // "If x is the negative number of least magnitude in x's format, nextUp(x) is
5408 // -0."
5409 if (NextHi.isZero()) {
5410 makeZero(/*Neg=*/true);
5411 return opOK;
5412 }
5413
5414 // abs(NextLo) must be <= ulp(NextHi)/2. We want NextLo to be as close to
5415 // negative infinity as possible.
5416 NextLo = neg(scalbn(harrisonUlp(NextHi), -1, rmTowardZero));
5417 if (!InLattice(NextHi, NextLo))
5418 // RTNE may mean that Lo must be < ulp(NextHi) / 2 so we bump NextLo.
5419 NextLo.next(/*nextDown=*/false);
5420
5421 Floats[0] = std::move(NextHi);
5422 Floats[1] = std::move(NextLo);
5423
5424 return opOK;
5425}
5426
5427APFloat::opStatus DoubleAPFloat::convertToSignExtendedInteger(
5428 MutableArrayRef<integerPart> Input, unsigned int Width, bool IsSigned,
5429 roundingMode RM, bool *IsExact) const {
5430 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5431 "Unexpected Semantics");
5432
5433 // If Hi is not finite, or Lo is zero, the value is entirely represented
5434 // by Hi. Delegate to the simpler single-APFloat conversion.
5435 if (!getFirst().isFiniteNonZero() || getSecond().isZero())
5436 return getFirst().convertToInteger(Input, Width, IsSigned, RM, IsExact);
5437
5438 // First, round the full double-double value to an integral value. This
5439 // simplifies the rest of the function, as we no longer need to consider
5440 // fractional parts.
5441 *IsExact = false;
5442 DoubleAPFloat Integral = *this;
5443 const opStatus RoundStatus = Integral.roundToIntegral(RM);
5444 if (RoundStatus == opInvalidOp)
5445 return opInvalidOp;
5446 const APFloat &IntegralHi = Integral.getFirst();
5447 const APFloat &IntegralLo = Integral.getSecond();
5448
5449 // If rounding results in either component being zero, the sum is trivial.
5450 // Delegate to the simpler single-APFloat conversion.
5451 bool HiIsExact;
5452 if (IntegralHi.isZero() || IntegralLo.isZero()) {
5453 const opStatus HiStatus =
5454 IntegralHi.convertToInteger(Input, Width, IsSigned, RM, &HiIsExact);
5455 // The conversion from an integer-valued float to an APInt may fail if the
5456 // result would be out of range. Regardless, taking this path is only
5457 // possible if rounding occurred during the initial `roundToIntegral`.
5458 return HiStatus == opOK ? opInexact : HiStatus;
5459 }
5460
5461 // A negative number cannot be represented by an unsigned integer.
5462 // Since a double-double is canonical, if Hi is negative, the sum is negative.
5463 if (!IsSigned && IntegralHi.isNegative())
5464 return opInvalidOp;
5465
5466 // Handle the special boundary case where |Hi| is exactly the power of two
5467 // that marks the edge of the integer's range (e.g., 2^63 for int64_t). In
5468 // this situation, Hi itself won't fit, but the sum Hi + Lo might.
5469 // `PositiveOverflowWidth` is the bit number for this boundary (N-1 for
5470 // signed, N for unsigned).
5471 bool LoIsExact;
5472 const int HiExactLog2 = IntegralHi.getExactLog2Abs();
5473 const unsigned PositiveOverflowWidth = IsSigned ? Width - 1 : Width;
5474 if (HiExactLog2 >= 0 &&
5475 static_cast<unsigned>(HiExactLog2) == PositiveOverflowWidth) {
5476 // If Hi and Lo have the same sign, |Hi + Lo| > |Hi|, so the sum is
5477 // guaranteed to overflow. E.g., for uint128_t, (2^128, 1) overflows.
5478 if (IntegralHi.isNegative() == IntegralLo.isNegative())
5479 return opInvalidOp;
5480
5481 // If the signs differ, the sum will fit. We can compute the result using
5482 // properties of two's complement arithmetic without a wide intermediate
5483 // integer. E.g., for uint128_t, (2^128, -1) should be 2^128 - 1.
5484 const opStatus LoStatus = IntegralLo.convertToInteger(
5485 Input, Width, /*IsSigned=*/true, RM, &LoIsExact);
5486 if (LoStatus == opInvalidOp)
5487 return opInvalidOp;
5488
5489 // Adjust the bit pattern of Lo to account for Hi's value:
5490 // - For unsigned (Hi=2^Width): `2^Width + Lo` in `Width`-bit
5491 // arithmetic is equivalent to just `Lo`. The conversion of `Lo` above
5492 // already produced the correct final bit pattern.
5493 // - For signed (Hi=2^(Width-1)): The sum `2^(Width-1) + Lo` (where Lo<0)
5494 // can be computed by taking the two's complement pattern for `Lo` and
5495 // clearing the sign bit.
5496 if (IsSigned && !IntegralHi.isNegative())
5497 APInt::tcClearBit(Input.data(), PositiveOverflowWidth);
5498 *IsExact = RoundStatus == opOK;
5499 return RoundStatus;
5500 }
5501
5502 // Convert Hi into an integer. This may not fit but that is OK: we know that
5503 // Hi + Lo would not fit either in this situation.
5504 const opStatus HiStatus = IntegralHi.convertToInteger(
5505 Input, Width, IsSigned, rmTowardZero, &HiIsExact);
5506 if (HiStatus == opInvalidOp)
5507 return HiStatus;
5508
5509 // Convert Lo into a temporary integer of the same width.
5510 APSInt LoResult{Width, /*isUnsigned=*/!IsSigned};
5511 const opStatus LoStatus =
5512 IntegralLo.convertToInteger(LoResult, rmTowardZero, &LoIsExact);
5513 if (LoStatus == opInvalidOp)
5514 return LoStatus;
5515
5516 // Add Lo to Hi. This addition is guaranteed not to overflow because of the
5517 // double-double canonicalization rule (`|Lo| <= ulp(Hi)/2`). The only case
5518 // where the sum could cross the integer type's boundary is when Hi is a
5519 // power of two, which is handled by the special case block above.
5520 APInt::tcAdd(Input.data(), LoResult.getRawData(), /*carry=*/0, Input.size());
5521
5522 *IsExact = RoundStatus == opOK;
5523 return RoundStatus;
5524}
5525
5528 unsigned int Width, bool IsSigned,
5529 roundingMode RM, bool *IsExact) const {
5530 opStatus FS =
5531 convertToSignExtendedInteger(Input, Width, IsSigned, RM, IsExact);
5532
5533 if (FS == opInvalidOp) {
5534 const unsigned DstPartsCount = partCountForBits(Width);
5535 assert(DstPartsCount <= Input.size() && "Integer too big");
5536
5537 unsigned Bits;
5538 if (getCategory() == fcNaN)
5539 Bits = 0;
5540 else if (isNegative())
5541 Bits = IsSigned;
5542 else
5543 Bits = Width - IsSigned;
5544
5545 tcSetLeastSignificantBits(Input.data(), DstPartsCount, Bits);
5546 if (isNegative() && IsSigned)
5547 APInt::tcShiftLeft(Input.data(), DstPartsCount, Width - 1);
5548 }
5549
5550 return FS;
5551}
5552
5553APFloat::opStatus DoubleAPFloat::handleOverflow(roundingMode RM) {
5554 switch (RM) {
5556 makeLargest(/*Neg=*/isNegative());
5557 break;
5559 if (isNegative())
5560 makeInf(/*Neg=*/true);
5561 else
5562 makeLargest(/*Neg=*/false);
5563 break;
5565 if (isNegative())
5566 makeLargest(/*Neg=*/true);
5567 else
5568 makeInf(/*Neg=*/false);
5569 break;
5572 makeInf(/*Neg=*/isNegative());
5573 break;
5574 default:
5575 llvm_unreachable("Invalid rounding mode found");
5576 }
5577 opStatus S = opInexact;
5578 if (!getFirst().isFinite())
5579 S = static_cast<opStatus>(S | opOverflow);
5580 return S;
5581}
5582
5583APFloat::opStatus DoubleAPFloat::convertFromUnsignedParts(
5584 const integerPart *Src, unsigned int SrcCount, roundingMode RM) {
5585 // Find the most significant bit of the source integer. APInt::tcMSB returns
5586 // UINT_MAX for a zero value.
5587 const unsigned SrcMSB = APInt::tcMSB(Src, SrcCount);
5588 if (SrcMSB == UINT_MAX) {
5589 // The source integer is 0.
5590 makeZero(/*Neg=*/false);
5591 return opOK;
5592 }
5593
5594 // Create a minimally-sized APInt to represent the source value.
5595 const unsigned SrcBitWidth = SrcMSB + 1;
5596 APSInt SrcInt{APInt{/*numBits=*/SrcBitWidth, ArrayRef(Src, SrcCount)},
5597 /*isUnsigned=*/true};
5598
5599 // Stage 1: Initial Approximation.
5600 // Convert the source integer SrcInt to the Hi part of the DoubleAPFloat.
5601 // We use round-to-nearest because it minimizes the initial error, which is
5602 // crucial for the subsequent steps.
5604 Hi.convertFromAPInt(SrcInt, /*IsSigned=*/false, rmNearestTiesToEven);
5605
5606 // If the first approximation already overflows, the number is too large.
5607 // NOTE: The underlying semantics are *more* conservative when choosing to
5608 // overflow because their notion of ULP is much larger. As such, it is always
5609 // safe to overflow at the DoubleAPFloat level if the APFloat overflows.
5610 if (!Hi.isFinite())
5611 return handleOverflow(RM);
5612
5613 // Stage 2: Exact Error Calculation.
5614 // Calculate the exact error of the first approximation: Error = SrcInt - Hi.
5615 // This is done by converting Hi back to an integer and subtracting it from
5616 // the original source.
5617 bool HiAsIntIsExact;
5618 // Create an integer representation of Hi. Its width is determined by the
5619 // exponent of Hi, ensuring it's just large enough. This width can exceed
5620 // SrcBitWidth if the conversion to Hi rounded up to a power of two.
5621 // accurately when converted back to an integer.
5622 APSInt HiAsInt{static_cast<uint32_t>(ilogb(Hi) + 1), /*isUnsigned=*/true};
5623 Hi.convertToInteger(HiAsInt, rmNearestTiesToEven, &HiAsIntIsExact);
5624 const APInt Error = SrcInt.zext(HiAsInt.getBitWidth()) - HiAsInt;
5625
5626 // Stage 3: Error Approximation and Rounding.
5627 // Convert the integer error into the Lo part of the DoubleAPFloat. This step
5628 // captures the remainder of the original number. The rounding mode for this
5629 // conversion (LoRM) may need to be adjusted from the user-requested RM to
5630 // ensure the final sum (Hi + Lo) rounds correctly.
5631 roundingMode LoRM = RM;
5632 // Adjustments are only necessary when the initial approximation Hi was an
5633 // overestimate, making the Error negative.
5634 if (Error.isNegative()) {
5635 if (RM == rmNearestTiesToAway) {
5636 // For rmNearestTiesToAway, a tie should round away from zero. Since
5637 // SrcInt is positive, this means rounding toward +infinity.
5638 // A standard conversion of a negative Error would round ties toward
5639 // -infinity, causing the final sum Hi + Lo to be smaller. To
5640 // counteract this, we detect the tie case and override the rounding
5641 // mode for Lo to rmTowardPositive.
5642 const unsigned ErrorActiveBits = Error.getSignificantBits() - 1;
5643 const unsigned LoPrecision = getSecond().getSemantics().precision;
5644 if (ErrorActiveBits > LoPrecision) {
5645 const unsigned RoundingBoundary = ErrorActiveBits - LoPrecision;
5646 // A tie occurs when the bits to be truncated are of the form 100...0.
5647 // This is detected by checking if the number of trailing zeros is
5648 // exactly one less than the number of bits being truncated.
5649 if (Error.countTrailingZeros() == RoundingBoundary - 1)
5650 LoRM = rmTowardPositive;
5651 }
5652 } else if (RM == rmTowardZero) {
5653 // For rmTowardZero, the final positive result must be truncated (rounded
5654 // down). When Hi is an overestimate, Error is negative. A standard
5655 // rmTowardZero conversion of Error would make it *less* negative,
5656 // effectively rounding the final sum Hi + Lo *up*. To ensure the sum
5657 // rounds down correctly, we force Lo to round toward -infinity.
5658 LoRM = rmTowardNegative;
5659 }
5660 }
5661
5663 opStatus Status = Lo.convertFromAPInt(Error, /*IsSigned=*/true, LoRM);
5664
5665 // Renormalize the pair (Hi, Lo) into a canonical DoubleAPFloat form where the
5666 // components do not overlap. fastTwoSum performs this operation.
5667 std::tie(Hi, Lo) = fastTwoSum(Hi, Lo);
5668 Floats[0] = std::move(Hi);
5669 Floats[1] = std::move(Lo);
5670
5671 // A final check for overflow is needed because fastTwoSum can cause a
5672 // carry-out from Lo that pushes Hi to infinity.
5673 if (!getFirst().isFinite())
5674 return handleOverflow(RM);
5675
5676 // The largest DoubleAPFloat must be canonical. Values which are larger are
5677 // not canonical and are equivalent to overflow.
5678 if (getFirst().isFiniteNonZero() && Floats[0].isLargest()) {
5679 DoubleAPFloat Largest{*Semantics};
5680 Largest.makeLargest(/*Neg=*/false);
5681 if (compare(Largest) == APFloat::cmpGreaterThan)
5682 return handleOverflow(RM);
5683 }
5684
5685 // The final status of the operation is determined by the conversion of the
5686 // error term. If Lo could represent Error exactly, the entire conversion
5687 // is exact. Otherwise, it's inexact.
5688 return Status;
5689}
5690
5692 bool IsSigned,
5693 roundingMode RM) {
5694 const bool NegateInput = IsSigned && Input.isNegative();
5695 APInt API = Input;
5696 if (NegateInput)
5697 API.negate();
5698
5700 convertFromUnsignedParts(API.getRawData(), API.getNumWords(), RM);
5701 if (NegateInput)
5702 changeSign();
5703 return Status;
5704}
5705
5707 unsigned int HexDigits,
5708 bool UpperCase,
5709 roundingMode RM) const {
5710 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5711 "Unexpected Semantics");
5712 return APFloat(APFloatBase::semPPCDoubleDoubleLegacy, bitcastToAPInt())
5713 .convertToHexString(DST, HexDigits, UpperCase, RM);
5714}
5715
5717 return getCategory() == fcNormal &&
5718 (Floats[0].isDenormal() || Floats[1].isDenormal() ||
5719 // (double)(Hi + Lo) == Hi defines a normal number.
5720 Floats[0] != Floats[0] + Floats[1]);
5721}
5722
5724 if (getCategory() != fcNormal)
5725 return false;
5726 DoubleAPFloat Tmp(*this);
5727 Tmp.makeSmallest(this->isNegative());
5728 return Tmp.compare(*this) == cmpEqual;
5729}
5730
5732 if (getCategory() != fcNormal)
5733 return false;
5734
5735 DoubleAPFloat Tmp(*this);
5737 return Tmp.compare(*this) == cmpEqual;
5738}
5739
5741 if (getCategory() != fcNormal)
5742 return false;
5743 DoubleAPFloat Tmp(*this);
5744 Tmp.makeLargest(this->isNegative());
5745 return Tmp.compare(*this) == cmpEqual;
5746}
5747
5749 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5750 "Unexpected Semantics");
5751 return Floats[0].isInteger() && Floats[1].isInteger();
5752}
5753
5755 unsigned FormatPrecision,
5756 unsigned FormatMaxPadding,
5757 bool TruncateZero) const {
5758 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5759 "Unexpected Semantics");
5760 APFloat(APFloatBase::semPPCDoubleDoubleLegacy, bitcastToAPInt())
5761 .toString(Str, FormatPrecision, FormatMaxPadding, TruncateZero);
5762}
5763
5765 // In order for Hi + Lo to be a power of two, the following must be true:
5766 // 1. Hi must be a power of two.
5767 // 2. Lo must be zero.
5768 if (getSecond().isNonZero())
5769 return INT_MIN;
5770 return getFirst().getExactLog2Abs();
5771}
5772
5773int ilogb(const DoubleAPFloat &Arg) {
5774 const APFloat &Hi = Arg.getFirst();
5775 const APFloat &Lo = Arg.getSecond();
5776 int IlogbResult = ilogb(Hi);
5777 // Zero and non-finite values can delegate to ilogb(Hi).
5778 if (Arg.getCategory() != fcNormal)
5779 return IlogbResult;
5780 // If Lo can't change the binade, we can delegate to ilogb(Hi).
5781 if (Lo.isZero() || Hi.isNegative() == Lo.isNegative())
5782 return IlogbResult;
5783 if (Hi.getExactLog2Abs() == INT_MIN)
5784 return IlogbResult;
5785 // Numbers of the form 2^a - 2^b or -2^a + 2^b are almost powers of two but
5786 // get nudged out of the binade by the low component.
5787 return IlogbResult - 1;
5788}
5789
5792 assert(Arg.Semantics == &APFloatBase::PPCDoubleDouble() &&
5793 "Unexpected Semantics");
5795 scalbn(Arg.Floats[0], Exp, RM),
5796 scalbn(Arg.Floats[1], Exp, RM));
5797}
5798
5799DoubleAPFloat frexp(const DoubleAPFloat &Arg, int &Exp,
5801 assert(Arg.Semantics == &APFloatBase::PPCDoubleDouble() &&
5802 "Unexpected Semantics");
5803
5804 // Get the unbiased exponent e of the number, where |Arg| = m * 2^e for m in
5805 // [1.0, 2.0).
5806 Exp = ilogb(Arg);
5807
5808 // For NaNs, quiet any signaling NaN and return the result, as per standard
5809 // practice.
5810 if (Exp == APFloat::IEK_NaN) {
5811 DoubleAPFloat Quiet{Arg};
5812 Quiet.getFirst() = Quiet.getFirst().makeQuiet();
5813 return Quiet;
5814 }
5815
5816 // For infinity, return it unchanged. The exponent remains IEK_Inf.
5817 if (Exp == APFloat::IEK_Inf)
5818 return Arg;
5819
5820 // For zero, the fraction is zero and the standard requires the exponent be 0.
5821 if (Exp == APFloat::IEK_Zero) {
5822 Exp = 0;
5823 return Arg;
5824 }
5825
5826 const APFloat &Hi = Arg.getFirst();
5827 const APFloat &Lo = Arg.getSecond();
5828
5829 // frexp requires the fraction's absolute value to be in [0.5, 1.0).
5830 // ilogb provides an exponent for an absolute value in [1.0, 2.0).
5831 // Increment the exponent to ensure the fraction is in the correct range.
5832 ++Exp;
5833
5834 const bool SignsDisagree = Hi.isNegative() != Lo.isNegative();
5835 APFloat Second = Lo;
5836 if (Arg.getCategory() == APFloat::fcNormal && Lo.isFiniteNonZero()) {
5837 roundingMode LoRoundingMode;
5838 // The interpretation of rmTowardZero depends on the sign of the combined
5839 // Arg rather than the sign of the component.
5840 if (RM == rmTowardZero)
5841 LoRoundingMode = Arg.isNegative() ? rmTowardPositive : rmTowardNegative;
5842 // For rmNearestTiesToAway, we face a similar problem. If signs disagree,
5843 // Lo is a correction *toward* zero relative to Hi. Rounding Lo
5844 // "away from zero" based on its own sign would move the value in the
5845 // wrong direction. As a safe proxy, we use rmNearestTiesToEven, which is
5846 // direction-agnostic. We only need to bother with this if Lo is scaled
5847 // down.
5848 else if (RM == rmNearestTiesToAway && SignsDisagree && Exp > 0)
5849 LoRoundingMode = rmNearestTiesToEven;
5850 else
5851 LoRoundingMode = RM;
5852 Second = scalbn(Lo, -Exp, LoRoundingMode);
5853 // The rmNearestTiesToEven proxy is correct most of the time, but it
5854 // differs from rmNearestTiesToAway when the scaled value of Lo is an
5855 // exact midpoint.
5856 // NOTE: This is morally equivalent to roundTiesTowardZero.
5857 if (RM == rmNearestTiesToAway && LoRoundingMode == rmNearestTiesToEven) {
5858 // Re-scale the result back to check if rounding occurred.
5859 const APFloat RecomposedLo = scalbn(Second, Exp, rmNearestTiesToEven);
5860 if (RecomposedLo != Lo) {
5861 // RoundingError tells us which direction we rounded:
5862 // - RoundingError > 0: we rounded up.
5863 // - RoundingError < 0: we down up.
5864 const APFloat RoundingError = RecomposedLo - Lo;
5865 // Determine if scalbn(Lo, -Exp) landed exactly on a midpoint.
5866 // We do this by checking if the absolute rounding error is exactly
5867 // half a ULP of the result.
5868 const APFloat UlpOfSecond = harrisonUlp(Second);
5869 const APFloat ScaledUlpOfSecond =
5870 scalbn(UlpOfSecond, Exp - 1, rmNearestTiesToEven);
5871 const bool IsMidpoint = abs(RoundingError) == ScaledUlpOfSecond;
5872 const bool RoundedLoAway =
5873 Second.isNegative() == RoundingError.isNegative();
5874 // The sign of Hi and Lo disagree and we rounded Lo away: we must
5875 // decrease the magnitude of Second to increase the magnitude
5876 // First+Second.
5877 if (IsMidpoint && RoundedLoAway)
5878 Second.next(/*nextDown=*/!Second.isNegative());
5879 }
5880 }
5881 // Handle a tricky edge case where Arg is slightly less than a power of two
5882 // (e.g., Arg = 2^k - epsilon). In this situation:
5883 // 1. Hi is 2^k, and Lo is a small negative value -epsilon.
5884 // 2. ilogb(Arg) correctly returns k-1.
5885 // 3. Our initial Exp becomes (k-1) + 1 = k.
5886 // 4. Scaling Hi (2^k) by 2^-k would yield a magnitude of 1.0 and
5887 // scaling Lo by 2^-k would yield zero. This would make the result 1.0
5888 // which is an invalid fraction, as the required interval is [0.5, 1.0).
5889 // We detect this specific case by checking if Hi is a power of two and if
5890 // the scaled Lo underflowed to zero. The fix: Increment Exp to k+1. This
5891 // adjusts the scale factor, causing Hi to be scaled to 0.5, which is a
5892 // valid fraction.
5893 if (Second.isZero() && SignsDisagree && Hi.getExactLog2Abs() != INT_MIN)
5894 ++Exp;
5895 }
5896
5897 APFloat First = scalbn(Hi, -Exp, RM);
5899 std::move(Second));
5900}
5901
5902APInt DoubleAPFloat::getNaNPayload() const { return Floats[0].getNaNPayload(); }
5903} // namespace detail
5904
5905APFloat::Storage::Storage(IEEEFloat F, const fltSemantics &Semantics) {
5906 if (usesLayout<IEEEFloat>(Semantics)) {
5907 new (&IEEE) IEEEFloat(std::move(F));
5908 return;
5909 }
5910 if (usesLayout<DoubleAPFloat>(Semantics)) {
5911 const fltSemantics& S = F.getSemantics();
5912 new (&Double) DoubleAPFloat(Semantics, APFloat(std::move(F), S),
5914 return;
5915 }
5916 llvm_unreachable("Unexpected semantics");
5917}
5918
5923
5924hash_code hash_value(const APFloat &Arg) {
5925 if (APFloat::usesLayout<detail::IEEEFloat>(Arg.getSemantics()))
5926 return hash_value(Arg.U.IEEE);
5927 if (APFloat::usesLayout<detail::DoubleAPFloat>(Arg.getSemantics()))
5928 return hash_value(Arg.U.Double);
5929 llvm_unreachable("Unexpected semantics");
5930}
5931
5933 : APFloat(Semantics) {
5934 auto StatusOrErr = convertFromString(S, rmNearestTiesToEven);
5935 assert(StatusOrErr && "Invalid floating point representation");
5936 consumeError(StatusOrErr.takeError());
5937}
5938
5940 if (isZero())
5941 return isNegative() ? fcNegZero : fcPosZero;
5942 if (isNormal())
5943 return isNegative() ? fcNegNormal : fcPosNormal;
5944 if (isDenormal())
5946 if (isInfinity())
5947 return isNegative() ? fcNegInf : fcPosInf;
5948 assert(isNaN() && "Other class of FP constant");
5949 return isSignaling() ? fcSNan : fcQNan;
5950}
5951
5952bool APFloat::getExactInverse(APFloat *Inv) const {
5953 // Only finite, non-zero numbers can have a useful, representable inverse.
5954 // This check filters out +/- zero, +/- infinity, and NaN.
5955 if (!isFiniteNonZero())
5956 return false;
5957
5958 // Historically, this function rejects subnormal inputs. One reason why this
5959 // might be important is that subnormals may behave differently under FTZ/DAZ
5960 // runtime behavior.
5961 if (isDenormal())
5962 return false;
5963
5964 // A number has an exact, representable inverse if and only if it is a power
5965 // of two.
5966 //
5967 // Mathematical Rationale:
5968 // 1. A binary floating-point number x is a dyadic rational, meaning it can
5969 // be written as x = M / 2^k for integers M (the significand) and k.
5970 // 2. The inverse is 1/x = 2^k / M.
5971 // 3. For 1/x to also be a dyadic rational (and thus exactly representable
5972 // in binary), its denominator M must also be a power of two.
5973 // Let's say M = 2^m.
5974 // 4. Substituting this back into the formula for x, we get
5975 // x = (2^m) / (2^k) = 2^(m-k).
5976 //
5977 // This proves that x must be a power of two.
5978
5979 // getExactLog2Abs() returns the integer exponent if the number is a power of
5980 // two or INT_MIN if it is not.
5981 const int Exp = getExactLog2Abs();
5982 if (Exp == INT_MIN)
5983 return false;
5984
5985 // The inverse of +/- 2^Exp is +/- 2^(-Exp). We can compute this by
5986 // scaling 1.0 by the negated exponent.
5987 APFloat Reciprocal =
5988 scalbn(APFloat::getOne(getSemantics(), /*Negative=*/isNegative()), -Exp,
5989 rmTowardZero);
5990
5991 // scalbn might round if the resulting exponent -Exp is outside the
5992 // representable range, causing overflow (to infinity) or underflow. We
5993 // must verify that the result is still the exact power of two we expect.
5994 if (Reciprocal.getExactLog2Abs() != -Exp)
5995 return false;
5996
5997 // Avoid multiplication with a subnormal, it is not safe on all platforms and
5998 // may be slower than a normal division.
5999 if (Reciprocal.isDenormal())
6000 return false;
6001
6002 assert(Reciprocal.isFiniteNonZero());
6003
6004 if (Inv)
6005 *Inv = std::move(Reciprocal);
6006
6007 return true;
6008}
6009
6011 roundingMode RM, bool *losesInfo) {
6012 if (&getSemantics() == &ToSemantics) {
6013 *losesInfo = false;
6014 return opOK;
6015 }
6016 if (usesLayout<IEEEFloat>(getSemantics()) &&
6017 usesLayout<IEEEFloat>(ToSemantics))
6018 return U.IEEE.convert(ToSemantics, RM, losesInfo);
6019 if (usesLayout<IEEEFloat>(getSemantics()) &&
6020 usesLayout<DoubleAPFloat>(ToSemantics)) {
6021 assert(&ToSemantics == &APFloatBase::semPPCDoubleDouble);
6022 auto Ret =
6023 U.IEEE.convert(APFloatBase::semPPCDoubleDoubleLegacy, RM, losesInfo);
6024 *this = APFloat(ToSemantics, U.IEEE.bitcastToAPInt());
6025 return Ret;
6026 }
6027 if (usesLayout<DoubleAPFloat>(getSemantics()) &&
6028 usesLayout<IEEEFloat>(ToSemantics)) {
6029 auto Ret = getIEEE().convert(ToSemantics, RM, losesInfo);
6030 *this = APFloat(std::move(getIEEE()), ToSemantics);
6031 return Ret;
6032 }
6033 llvm_unreachable("Unexpected semantics");
6034}
6035
6039
6041 SmallVector<char, 16> Buffer;
6042 toString(Buffer);
6043 OS << Buffer;
6044}
6045
6046#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
6048 print(dbgs());
6049 dbgs() << '\n';
6050}
6051#endif
6052
6054 NID.Add(bitcastToAPInt());
6055}
6056
6058 roundingMode rounding_mode,
6059 bool *isExact) const {
6060 unsigned bitWidth = result.getBitWidth();
6061 SmallVector<uint64_t, 4> parts(result.getNumWords());
6062 opStatus status = convertToInteger(parts, bitWidth, result.isSigned(),
6063 rounding_mode, isExact);
6064 // Keeps the original signed-ness.
6065 result = APInt(bitWidth, parts);
6066 return status;
6067}
6068
6070 if (&getSemantics() == &APFloatBase::semIEEEdouble)
6071 return getIEEE().convertToDouble();
6072 assert(isRepresentableBy(getSemantics(), semIEEEdouble) &&
6073 "Float semantics is not representable by IEEEdouble");
6074 APFloat Temp = *this;
6075 bool LosesInfo;
6076 [[maybe_unused]] opStatus St =
6077 Temp.convert(APFloatBase::semIEEEdouble, rmNearestTiesToEven, &LosesInfo);
6078 assert(!(St & opInexact) && !LosesInfo && "Unexpected imprecision");
6079 return Temp.getIEEE().convertToDouble();
6080}
6081
6082#ifdef HAS_IEE754_FLOAT128
6083float128 APFloat::convertToQuad() const {
6084 if (&getSemantics() == &APFloatBase::semIEEEquad)
6085 return getIEEE().convertToQuad();
6086 assert(isRepresentableBy(getSemantics(), semIEEEquad) &&
6087 "Float semantics is not representable by IEEEquad");
6088 APFloat Temp = *this;
6089 bool LosesInfo;
6090 [[maybe_unused]] opStatus St =
6091 Temp.convert(APFloatBase::semIEEEquad, rmNearestTiesToEven, &LosesInfo);
6092 assert(!(St & opInexact) && !LosesInfo && "Unexpected imprecision");
6093 return Temp.getIEEE().convertToQuad();
6094}
6095#endif
6096
6098 if (&getSemantics() == &APFloatBase::semIEEEsingle)
6099 return getIEEE().convertToFloat();
6100 assert(isRepresentableBy(getSemantics(), semIEEEsingle) &&
6101 "Float semantics is not representable by IEEEsingle");
6102 APFloat Temp = *this;
6103 bool LosesInfo;
6104 [[maybe_unused]] opStatus St =
6105 Temp.convert(APFloatBase::semIEEEsingle, rmNearestTiesToEven, &LosesInfo);
6106 assert(!(St & opInexact) && !LosesInfo && "Unexpected imprecision");
6107 return Temp.getIEEE().convertToFloat();
6108}
6109
6112 .Case("Float8E5M2", getSizeInBits(semFloat8E5M2))
6113 .Case("Float8E5M2FNUZ", getSizeInBits(semFloat8E5M2FNUZ))
6114 .Case("Float8E4M3", getSizeInBits(semFloat8E4M3))
6115 .Case("Float8E4M3FN", getSizeInBits(semFloat8E4M3FN))
6116 .Case("Float8E4M3FNUZ", getSizeInBits(semFloat8E4M3FNUZ))
6117 .Case("Float8E4M3B11FNUZ", getSizeInBits(semFloat8E4M3B11FNUZ))
6118 .Case("Float8E3M4", getSizeInBits(semFloat8E3M4))
6119 .Case("Float8E8M0FNU", getSizeInBits(semFloat8E8M0FNU))
6120 .Case("Float6E3M2FN", getSizeInBits(semFloat6E3M2FN))
6121 .Case("Float6E2M3FN", getSizeInBits(semFloat6E2M3FN))
6122 .Case("Float4E2M1FN", getSizeInBits(semFloat4E2M1FN))
6123 .Case("Float8E5M3FNU", getSizeInBits(semFloat8E5M3FNU))
6124 .Default(0);
6125}
6126
6130
6132 // TODO: extend to remaining arbitrary FP types: Float8E4M3, Float8E3M4,
6133 // Float8E5M2FNUZ, Float8E4M3FNUZ, Float8E4M3B11FNUZ, Float8E8M0FNU.
6135 .Case("Float8E5M2", &semFloat8E5M2)
6136 .Case("Float8E4M3FN", &semFloat8E4M3FN)
6137 .Case("Float8E5M3FNU", &semFloat8E5M3FNU)
6138 .Case("Float4E2M1FN", &semFloat4E2M1FN)
6139 .Case("Float6E3M2FN", &semFloat6E3M2FN)
6140 .Case("Float6E2M3FN", &semFloat6E2M3FN)
6141 .Default(nullptr);
6142}
6143
6144APFloat::Storage::~Storage() {
6145 if (usesLayout<IEEEFloat>(*semantics)) {
6146 IEEE.~IEEEFloat();
6147 return;
6148 }
6149 if (usesLayout<DoubleAPFloat>(*semantics)) {
6150 Double.~DoubleAPFloat();
6151 return;
6152 }
6153 llvm_unreachable("Unexpected semantics");
6154}
6155
6156APFloat::Storage::Storage(const APFloat::Storage &RHS) {
6157 if (usesLayout<IEEEFloat>(*RHS.semantics)) {
6158 new (this) IEEEFloat(RHS.IEEE);
6159 return;
6160 }
6161 if (usesLayout<DoubleAPFloat>(*RHS.semantics)) {
6162 new (this) DoubleAPFloat(RHS.Double);
6163 return;
6164 }
6165 llvm_unreachable("Unexpected semantics");
6166}
6167
6168APFloat::Storage::Storage(APFloat::Storage &&RHS) {
6169 if (usesLayout<IEEEFloat>(*RHS.semantics)) {
6170 new (this) IEEEFloat(std::move(RHS.IEEE));
6171 return;
6172 }
6173 if (usesLayout<DoubleAPFloat>(*RHS.semantics)) {
6174 new (this) DoubleAPFloat(std::move(RHS.Double));
6175 return;
6176 }
6177 llvm_unreachable("Unexpected semantics");
6178}
6179
6180APFloat::Storage &APFloat::Storage::operator=(const APFloat::Storage &RHS) {
6181 if (usesLayout<IEEEFloat>(*semantics) &&
6182 usesLayout<IEEEFloat>(*RHS.semantics)) {
6183 IEEE = RHS.IEEE;
6184 } else if (usesLayout<DoubleAPFloat>(*semantics) &&
6185 usesLayout<DoubleAPFloat>(*RHS.semantics)) {
6186 Double = RHS.Double;
6187 } else if (this != &RHS) {
6188 this->~Storage();
6189 new (this) Storage(RHS);
6190 }
6191 return *this;
6192}
6193
6194APFloat::Storage &APFloat::Storage::operator=(APFloat::Storage &&RHS) {
6195 if (usesLayout<IEEEFloat>(*semantics) &&
6196 usesLayout<IEEEFloat>(*RHS.semantics)) {
6197 IEEE = std::move(RHS.IEEE);
6198 } else if (usesLayout<DoubleAPFloat>(*semantics) &&
6199 usesLayout<DoubleAPFloat>(*RHS.semantics)) {
6200 Double = std::move(RHS.Double);
6201 } else if (this != &RHS) {
6202 this->~Storage();
6203 new (this) Storage(std::move(RHS));
6204 }
6205 return *this;
6206}
6207
6208namespace {
6209
6210APFloat::opStatus getOpStatusFromLibc(int libc_exceptions) {
6212 if (libc_exceptions & FE_INVALID)
6214 if (libc_exceptions & FE_DIVBYZERO)
6216 if (libc_exceptions & FE_OVERFLOW)
6218 if (libc_exceptions & FE_UNDERFLOW)
6220 if (libc_exceptions & FE_INEXACT)
6222 return status;
6223}
6224
6225} // namespace
6226
6227// TODO: Support other rounding modes when LLVM libc math implement static
6228// roundings.
6229std::optional<APFloat> exp(const APFloat &x, RoundingMode rounding_mode,
6230 APFloat::opStatus *status) {
6231
6232 if (rounding_mode == APFloatBase::rmNearestTiesToEven) {
6233 if (APFloat::SemanticsToEnum(x.getSemantics()) ==
6235 float x_val = x.convertToFloat();
6236 int exc =
6237 LIBC_NAMESPACE::shared::check::exp_exceptions(x_val, FE_TONEAREST);
6238 if (status) {
6239 *status = getOpStatusFromLibc(exc);
6240 if (x.isSignaling()) {
6241 // 32-bit x86 will silence sNaN when loading floats, so we explicitly
6242 // add the INVALID exception here.
6243 *status =
6244 static_cast<APFloat::opStatus>(*status | APFloat::opInvalidOp);
6245 }
6246 }
6247 float result = LIBC_NAMESPACE::shared::expf(x_val);
6248 return APFloat(result);
6249 }
6250 if (APFloat::SemanticsToEnum(x.getSemantics()) ==
6252 double x_val = x.convertToDouble();
6253 int exc =
6254 LIBC_NAMESPACE::shared::check::exp_exceptions(x_val, FE_TONEAREST);
6255 if (status) {
6256 *status = getOpStatusFromLibc(exc);
6257 if (x.isSignaling()) {
6258 // 32-bit x86 will silence sNaN when loading floats, so we explicitly
6259 // add the INVALID exception here.
6260 *status =
6261 static_cast<APFloat::opStatus>(*status | APFloat::opInvalidOp);
6262 }
6263 }
6264 double result = LIBC_NAMESPACE::shared::exp(x_val);
6265 return APFloat(result);
6266 }
6267 }
6268 return std::nullopt;
6269}
6270
6271} // namespace llvm
6272
6273#undef APFLOAT_DISPATCH_ON_SEMANTICS
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
#define PackCategoriesIntoKey(_lhs, _rhs)
A macro used to combine two fcCategory enums into one key which can be used in a switch statement to ...
Definition APFloat.cpp:63
This file declares a class to represent arbitrary precision floating point values and provide a varie...
#define APFLOAT_DISPATCH_ON_SEMANTICS(METHOD_CALL)
Definition APFloat.h:27
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
Function Alias Analysis false
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:678
static bool isNeg(Value *V)
Returns true if the operation is a negation of V, and it works for both integers and floats.
static bool isSigned(unsigned 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)
Definition Lint.cpp:539
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
#define P(N)
if(PassOpts->AAPipeline)
This file contains some templates that are useful if you are working with the STL at all.
This file contains some functions that are useful when dealing with strings.
This file implements the StringSwitch template, which mimics a switch() statement whose cases are str...
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
Value * RHS
Value * LHS
The Input class is used to parse a yaml document into in-memory structs and vectors.
static const fltSemantics & IEEEsingle()
Definition APFloat.h:304
static const fltSemantics & Float8E4M3FN()
Definition APFloat.h:314
static LLVM_ABI const llvm::fltSemantics & EnumToSemantics(Semantics S)
Definition APFloat.cpp:134
static LLVM_ABI bool semanticsHasInf(const fltSemantics &)
Definition APFloat.cpp:351
cmpResult
IEEE-754R 5.11: Floating Point Comparison Relations.
Definition APFloat.h:351
static constexpr roundingMode rmTowardZero
Definition APFloat.h:365
static LLVM_ABI ExponentType semanticsMinExponent(const fltSemantics &)
Definition APFloat.cpp:326
llvm::RoundingMode roundingMode
IEEE-754R 4.3: Rounding-direction attributes.
Definition APFloat.h:359
static const fltSemantics & BFloat()
Definition APFloat.h:303
static const fltSemantics & IEEEquad()
Definition APFloat.h:306
static LLVM_ABI unsigned int semanticsSizeInBits(const fltSemantics &)
Definition APFloat.cpp:329
static const fltSemantics & Float8E8M0FNU()
Definition APFloat.h:321
static LLVM_ABI bool semanticsHasSignedRepr(const fltSemantics &)
Definition APFloat.cpp:347
static const fltSemantics & IEEEdouble()
Definition APFloat.h:305
static LLVM_ABI unsigned getSizeInBits(const fltSemantics &Sem)
Returns the size of the floating point number (in bits) in the given semantics.
Definition APFloat.cpp:382
static const fltSemantics & x87DoubleExtended()
Definition APFloat.h:326
static constexpr roundingMode rmTowardNegative
Definition APFloat.h:364
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:361
static LLVM_ABI bool isValidArbitraryFPFormat(StringRef Format)
Returns true if the given string is a valid arbitrary floating-point format interpretation for llvm....
Definition APFloat.cpp:6127
static LLVM_ABI bool hasSignBitInMSB(const fltSemantics &)
Definition APFloat.cpp:364
static LLVM_ABI ExponentType semanticsMaxExponent(const fltSemantics &)
Definition APFloat.cpp:322
friend class APFloat
Definition APFloat.h:299
static LLVM_ABI unsigned int semanticsPrecision(const fltSemantics &)
Definition APFloat.cpp:318
static LLVM_ABI bool semanticsHasNaN(const fltSemantics &)
Definition APFloat.cpp:355
static LLVM_ABI Semantics SemanticsToEnum(const llvm::fltSemantics &Sem)
Definition APFloat.cpp:183
int32_t ExponentType
A signed type to represent a floating point numbers unbiased exponent.
Definition APFloat.h:156
static constexpr unsigned integerPartWidth
Definition APFloat.h:153
static const fltSemantics & PPCDoubleDoubleLegacy()
Definition APFloat.h:308
static LLVM_ABI bool isLosslesslyConvertibleTo(const fltSemantics &From, const fltSemantics &To, bool IgnoreNaNs=false)
Returns whether converting a value from From to To is known to preserve all information.
Definition APFloat.cpp:236
APInt::WordType integerPart
Definition APFloat.h:152
static LLVM_ABI bool semanticsHasZero(const fltSemantics &)
Definition APFloat.cpp:343
static LLVM_ABI bool isRepresentableAsNormalIn(const fltSemantics &Src, const fltSemantics &Dst)
Definition APFloat.cpp:368
static const fltSemantics & Float8E5M2FNUZ()
Definition APFloat.h:312
static const fltSemantics & Float8E4M3FNUZ()
Definition APFloat.h:315
static constexpr roundingMode rmTowardPositive
Definition APFloat.h:363
static const fltSemantics & IEEEhalf()
Definition APFloat.h:302
static const fltSemantics & Float4E2M1FN()
Definition APFloat.h:325
static const fltSemantics & Float6E2M3FN()
Definition APFloat.h:324
static const fltSemantics & Float8E4M3()
Definition APFloat.h:313
static const fltSemantics & Float8E4M3B11FNUZ()
Definition APFloat.h:316
static LLVM_ABI bool isRepresentableBy(const fltSemantics &A, const fltSemantics &B)
Definition APFloat.cpp:230
static const fltSemantics & Float8E3M4()
Definition APFloat.h:319
static LLVM_ABI bool isIEEELikeFP(const fltSemantics &)
Definition APFloat.cpp:359
static const fltSemantics & Float8E5M2()
Definition APFloat.h:311
fltCategory
Category of internally-represented number.
Definition APFloat.h:387
static constexpr roundingMode rmNearestTiesToAway
Definition APFloat.h:366
static const fltSemantics & PPCDoubleDouble()
Definition APFloat.h:307
static const fltSemantics & Float6E3M2FN()
Definition APFloat.h:323
opStatus
IEEE-754R 7: Default exception handling.
Definition APFloat.h:377
static const fltSemantics & Float8E5M3FNU()
Definition APFloat.h:322
static LLVM_ABI unsigned getArbitraryFPFormatSizeInBits(StringRef Format)
Returns the size in bits of a valid arbitrary floating-point format string, or 0 if the string is not...
Definition APFloat.cpp:6110
static LLVM_ABI const fltSemantics * getArbitraryFPSemantics(StringRef Format)
Returns the fltSemantics for a given arbitrary FP format string, or nullptr if invalid.
Definition APFloat.cpp:6131
static const fltSemantics & FloatTF32()
Definition APFloat.h:320
static LLVM_ABI unsigned int semanticsIntSizeInBits(const fltSemantics &, bool)
Definition APFloat.cpp:332
static APFloat getQNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for QNaN values.
Definition APFloat.h:1224
LLVM_ABI void Profile(FoldingSetNodeID &NID) const
Used to insert APFloat objects, or objects that contain APFloat objects, into FoldingSets.
Definition APFloat.cpp:6053
opStatus divide(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1312
bool isFiniteNonZero() const
Definition APFloat.h:1593
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:6010
LLVM_READONLY int getExactLog2Abs() const
Definition APFloat.h:1639
bool isNegative() const
Definition APFloat.h:1583
LLVM_ABI bool getExactInverse(APFloat *Inv) const
If this value is normal and has an exact, normal, multiplicative inverse, store it in inv and return ...
Definition APFloat.cpp:5952
cmpResult compareAbsoluteValue(const APFloat &RHS) const
Definition APFloat.h:1538
friend DoubleAPFloat
Definition APFloat.h:1671
LLVM_ABI double convertToDouble() const
Converts this APFloat to host double value.
Definition APFloat.cpp:6069
void toString(SmallVectorImpl< char > &Str, unsigned FormatPrecision=0, unsigned FormatMaxPadding=3, bool TruncateZero=true) const
Definition APFloat.h:1620
bool isNormal() const
Definition APFloat.h:1587
bool isDenormal() const
Definition APFloat.h:1584
opStatus add(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1285
static LLVM_ABI APFloat getAllOnesValue(const fltSemantics &Semantics)
Returns a float which is bitcasted from an all one value int.
Definition APFloat.cpp:6036
LLVM_ABI friend hash_code hash_value(const APFloat &Arg)
See friend declarations above.
Definition APFloat.cpp:5924
const fltSemantics & getSemantics() const
Definition APFloat.h:1591
bool isFinite() const
Definition APFloat.h:1588
bool isNaN() const
Definition APFloat.h:1581
static APFloat getOne(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative One.
Definition APFloat.h:1192
unsigned int convertToHexString(char *DST, unsigned int HexDigits, bool UpperCase, roundingMode RM) const
Definition APFloat.h:1573
LLVM_ABI float convertToFloat() const
Converts this APFloat to host float value.
Definition APFloat.cpp:6097
bool isSignaling() const
Definition APFloat.h:1585
opStatus fusedMultiplyAdd(const APFloat &Multiplicand, const APFloat &Addend, roundingMode RM)
Definition APFloat.h:1339
opStatus remainder(const APFloat &RHS)
Definition APFloat.h:1321
bool isZero() const
Definition APFloat.h:1579
APInt bitcastToAPInt() const
Definition APFloat.h:1475
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
Definition APFloat.h:1436
opStatus next(bool nextDown)
Definition APFloat.h:1358
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
Definition APFloat.h:1202
friend APFloat scalbn(APFloat X, int Exp, roundingMode RM)
static APFloat getSmallest(const fltSemantics &Sem, bool Negative=false)
Returns the smallest (by magnitude) finite number in the given semantics.
Definition APFloat.h:1252
LLVM_ABI FPClassTest classify() const
Return the FPClassTest which will return true for the value.
Definition APFloat.cpp:5939
opStatus mod(const APFloat &RHS)
Definition APFloat.h:1330
LLVM_ABI Expected< opStatus > convertFromString(StringRef, roundingMode)
Fill this APFloat with the result of a string conversion.
Definition APFloat.cpp:5919
friend IEEEFloat
Definition APFloat.h:1670
LLVM_DUMP_METHOD void dump() const
Definition APFloat.cpp:6047
LLVM_ABI void print(raw_ostream &) const
Definition APFloat.cpp:6040
opStatus roundToIntegral(roundingMode RM)
Definition APFloat.h:1352
static bool hasSignificand(const fltSemantics &Sem)
Returns true if the given semantics has actual significand.
Definition APFloat.h:1277
static APFloat getZero(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Zero.
Definition APFloat.h:1183
bool isInfinity() const
Definition APFloat.h:1580
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1600
static LLVM_ABI void tcSetBit(WordType *, unsigned bit)
Set the given bit of a bignum. Zero-based.
Definition APInt.cpp:2404
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:231
static LLVM_ABI void tcSet(WordType *, WordType, unsigned)
Sets the least significant part of a bignum to the input value, and zeroes out higher parts.
Definition APInt.cpp:2376
static LLVM_ABI void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Dual division/remainder interface.
Definition APInt.cpp:1794
static LLVM_ABI int tcExtractBit(const WordType *, unsigned bit)
Extract the given bit of a bignum; returns 0 or 1. Zero-based.
Definition APInt.cpp:2399
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1056
static LLVM_ABI WordType tcAdd(WordType *, const WordType *, WordType carry, unsigned)
DST += RHS + CARRY where CARRY is zero or one. Returns the carry flag.
Definition APInt.cpp:2478
static LLVM_ABI 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,...
Definition APInt.cpp:2448
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1533
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:969
static LLVM_ABI int tcCompare(const WordType *, const WordType *, unsigned)
Comparison (unsigned) of two bignums.
Definition APInt.cpp:2788
static APInt floatToBits(float V)
Converts a float to APInt bits.
Definition APInt.h:1773
uint64_t WordType
Definition APInt.h:80
static LLVM_ABI void tcAssign(WordType *, const WordType *, unsigned)
Assign one bignum to another.
Definition APInt.cpp:2384
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1509
static LLVM_ABI void tcShiftRight(WordType *, unsigned Words, unsigned Count)
Shift a bignum right Count bits.
Definition APInt.cpp:2762
static LLVM_ABI void tcFullMultiply(WordType *, const WordType *, const WordType *, unsigned, unsigned)
DST = LHS * RHS, where DST has width the sum of the widths of the operands.
Definition APInt.cpp:2668
unsigned getNumWords() const
Get the number of words.
Definition APInt.h:1516
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:326
static LLVM_ABI void tcClearBit(WordType *, unsigned bit)
Clear the given bit of a bignum. Zero-based.
Definition APInt.cpp:2409
void negate()
Negate this APInt in place.
Definition APInt.h:1489
static WordType tcDecrement(WordType *dst, unsigned parts)
Decrement a bignum in-place. Return the borrow flag.
Definition APInt.h:1939
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1660
static LLVM_ABI unsigned tcLSB(const WordType *, unsigned n)
Returns the bit number of the least or most significant set bit of a number.
Definition APInt.cpp:2415
static LLVM_ABI void tcShiftLeft(WordType *, unsigned Words, unsigned Count)
Shift a bignum left Count bits.
Definition APInt.cpp:2735
static LLVM_ABI bool tcIsZero(const WordType *, unsigned)
Returns true if a bignum is zero, false otherwise.
Definition APInt.cpp:2390
static LLVM_ABI unsigned tcMSB(const WordType *parts, unsigned n)
Returns the bit number of the most significant set bit of a number.
Definition APInt.cpp:2428
float bitsToFloat() const
Converts APInt bits to a float.
Definition APInt.h:1757
static LLVM_ABI 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.
Definition APInt.cpp:2566
static constexpr unsigned APINT_BITS_PER_WORD
Bits in a word.
Definition APInt.h:86
static LLVM_ABI WordType tcSubtract(WordType *, const WordType *, WordType carry, unsigned)
DST -= RHS + CARRY where CARRY is zero or one. Returns the carry flag.
Definition APInt.cpp:2513
static LLVM_ABI void tcNegate(WordType *, unsigned)
Negate a bignum in-place.
Definition APInt.cpp:2552
static APInt doubleToBits(double V)
Converts a double to APInt bits.
Definition APInt.h:1765
static WordType tcIncrement(WordType *dst, unsigned parts)
Increment a bignum in-place. Return the carry flag.
Definition APInt.h:1934
double bitsToDouble() const
Converts APInt bits to a double.
Definition APInt.h:1743
const uint64_t * getRawData() const
This function returns a pointer to the internal storage of the APInt.
Definition APInt.h:572
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:197
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
Definition APInt.h:861
An arbitrary precision integer that knows its signedness.
Definition APSInt.h:24
bool isSigned() const
Definition APSInt.h:78
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
This class is used to gather all the unique data bits of a node.
Definition FoldingSet.h:214
void Add(const T &x)
Definition FoldingSet.h:253
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
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.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition StringRef.h:490
const char * iterator
Definition StringRef.h:60
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition StringRef.h:635
iterator begin() const
Definition StringRef.h:114
char back() const
Get the last character in the string.
Definition StringRef.h:153
StringRef slice(size_t Start, size_t End) const
Return a reference to the substring from [Start, End).
Definition StringRef.h:720
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
char front() const
Get the first character in the string.
Definition StringRef.h:147
iterator end() const
Definition StringRef.h:116
bool consume_front(char Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
Definition StringRef.h:661
bool consume_front_insensitive(StringRef Prefix)
Returns true if this StringRef has the given prefix, ignoring case, and removes that prefix.
Definition StringRef.h:681
A switch()-like statement whose cases are string literals.
StringSwitch & Case(StringLiteral S, T Value)
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM_ABI void makeSmallestNormalized(bool Neg)
Definition APFloat.cpp:5266
LLVM_ABI DoubleAPFloat & operator=(const DoubleAPFloat &RHS)
Definition APFloat.cpp:4796
LLVM_ABI void changeSign()
Definition APFloat.cpp:5173
LLVM_ABI bool isLargest() const
Definition APFloat.cpp:5740
LLVM_ABI opStatus remainder(const DoubleAPFloat &RHS)
Definition APFloat.cpp:5060
LLVM_ABI opStatus multiply(const DoubleAPFloat &RHS, roundingMode RM)
Definition APFloat.cpp:4963
LLVM_ABI fltCategory getCategory() const
Definition APFloat.cpp:5232
LLVM_ABI bool bitwiseIsEqual(const DoubleAPFloat &RHS) const
Definition APFloat.cpp:5289
LLVM_ABI LLVM_READONLY int getExactLog2Abs() const
Definition APFloat.cpp:5764
LLVM_ABI opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM)
Definition APFloat.cpp:5691
LLVM_ABI APInt bitcastToAPInt() const
Definition APFloat.cpp:5300
LLVM_ABI Expected< opStatus > convertFromString(StringRef, roundingMode)
Definition APFloat.cpp:5310
LLVM_ABI bool isSmallest() const
Definition APFloat.cpp:5723
LLVM_ABI opStatus subtract(const DoubleAPFloat &RHS, roundingMode RM)
Definition APFloat.cpp:4955
LLVM_ABI friend hash_code hash_value(const DoubleAPFloat &Arg)
Definition APFloat.cpp:5294
LLVM_ABI cmpResult compareAbsoluteValue(const DoubleAPFloat &RHS) const
Definition APFloat.cpp:5179
LLVM_ABI bool isDenormal() const
Definition APFloat.cpp:5716
LLVM_ABI opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
Definition APFloat.cpp:5527
LLVM_ABI void makeSmallest(bool Neg)
Definition APFloat.cpp:5259
LLVM_ABI friend int ilogb(const DoubleAPFloat &X)
Definition APFloat.cpp:5773
LLVM_ABI opStatus next(bool nextDown)
Definition APFloat.cpp:5326
LLVM_ABI void makeInf(bool Neg)
Definition APFloat.cpp:5238
LLVM_ABI bool isInteger() const
Definition APFloat.cpp:5748
LLVM_ABI void makeZero(bool Neg)
Definition APFloat.cpp:5243
LLVM_ABI opStatus divide(const DoubleAPFloat &RHS, roundingMode RM)
Definition APFloat.cpp:5049
LLVM_ABI bool isSmallestNormalized() const
Definition APFloat.cpp:5731
LLVM_ABI opStatus mod(const DoubleAPFloat &RHS)
Definition APFloat.cpp:5070
LLVM_ABI DoubleAPFloat(const fltSemantics &S)
Definition APFloat.cpp:4743
LLVM_ABI void toString(SmallVectorImpl< char > &Str, unsigned FormatPrecision, unsigned FormatMaxPadding, bool TruncateZero=true) const
Definition APFloat.cpp:5754
LLVM_ABI void makeLargest(bool Neg)
Definition APFloat.cpp:5248
LLVM_ABI cmpResult compare(const DoubleAPFloat &RHS) const
Definition APFloat.cpp:5281
LLVM_ABI friend DoubleAPFloat scalbn(const DoubleAPFloat &X, int Exp, roundingMode)
LLVM_ABI opStatus roundToIntegral(roundingMode RM)
Definition APFloat.cpp:5096
LLVM_ABI opStatus fusedMultiplyAdd(const DoubleAPFloat &Multiplicand, const DoubleAPFloat &Addend, roundingMode RM)
Definition APFloat.cpp:5081
LLVM_ABI APInt getNaNPayload() const
Definition APFloat.cpp:5902
LLVM_ABI unsigned int convertToHexString(char *DST, unsigned int HexDigits, bool UpperCase, roundingMode RM) const
Definition APFloat.cpp:5706
LLVM_ABI bool isNegative() const
Definition APFloat.cpp:5236
LLVM_ABI opStatus add(const DoubleAPFloat &RHS, roundingMode RM)
Definition APFloat.cpp:4950
LLVM_ABI void makeNaN(bool SNaN, bool Neg, const APInt *fill)
Definition APFloat.cpp:5276
LLVM_ABI 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...
Definition APFloat.cpp:3297
LLVM_ABI cmpResult compareAbsoluteValue(const IEEEFloat &) const
Definition APFloat.cpp:1529
LLVM_ABI opStatus mod(const IEEEFloat &)
C fmod, or llvm frem.
Definition APFloat.cpp:2285
fltCategory getCategory() const
Definition APFloat.h:605
LLVM_ABI opStatus convertFromAPInt(const APInt &, bool, roundingMode)
Definition APFloat.cpp:2857
LLVM_ABI APInt getNaNPayload() const
Definition APFloat.cpp:4631
bool isFiniteNonZero() const
Definition APFloat.h:608
bool needsCleanup() const
Returns whether this instance allocated memory.
Definition APFloat.h:495
LLVM_ABI void makeLargest(bool Neg=false)
Make this number the largest magnitude normal number in the given semantics.
Definition APFloat.cpp:4058
LLVM_ABI LLVM_READONLY int getExactLog2Abs() const
Definition APFloat.cpp:4453
LLVM_ABI APInt bitcastToAPInt() const
Definition APFloat.cpp:3678
LLVM_ABI friend IEEEFloat scalbn(IEEEFloat X, int Exp, roundingMode)
Definition APFloat.cpp:4703
LLVM_ABI cmpResult compare(const IEEEFloat &) const
IEEE comparison with another floating point number (NaNs compare unordered, 0==-0).
Definition APFloat.cpp:2453
bool isNegative() const
IEEE-754R isSignMinus: Returns true if and only if the current value is negative.
Definition APFloat.h:570
LLVM_ABI opStatus divide(const IEEEFloat &, roundingMode)
Definition APFloat.cpp:2159
bool isNaN() const
Returns true if and only if the float is a quiet or signaling NaN.
Definition APFloat.h:595
LLVM_ABI opStatus remainder(const IEEEFloat &)
IEEE remainder.
Definition APFloat.cpp:2177
LLVM_ABI double convertToDouble() const
Definition APFloat.cpp:3751
LLVM_ABI float convertToFloat() const
Definition APFloat.cpp:3744
LLVM_ABI opStatus subtract(const IEEEFloat &, roundingMode)
Definition APFloat.cpp:2135
LLVM_ABI void toString(SmallVectorImpl< char > &Str, unsigned FormatPrecision=0, unsigned FormatMaxPadding=3, bool TruncateZero=true) const
Converts this value into a decimal string.
Definition APFloat.cpp:4409
LLVM_ABI void makeSmallest(bool Neg=false)
Make this number the smallest magnitude denormal number in the given semantics.
Definition APFloat.cpp:4090
LLVM_ABI void makeInf(bool Neg=false)
Definition APFloat.cpp:4650
LLVM_ABI bool isSmallestNormalized() const
Returns true if this is the smallest (by magnitude) normalized finite number in the given semantics.
Definition APFloat.cpp:1050
LLVM_ABI void makeQuiet()
Definition APFloat.cpp:4679
LLVM_ABI bool isLargest() const
Returns true if and only if the number has the largest possible finite magnitude in the current seman...
Definition APFloat.cpp:1152
LLVM_ABI opStatus add(const IEEEFloat &, roundingMode)
Definition APFloat.cpp:2129
bool isFinite() const
Returns true if and only if the current value is zero, subnormal, or normal.
Definition APFloat.h:582
LLVM_ABI Expected< opStatus > convertFromString(StringRef, roundingMode)
Definition APFloat.cpp:3240
LLVM_ABI void makeNaN(bool SNaN=false, bool Neg=false, const APInt *fill=nullptr)
Definition APFloat.cpp:938
LLVM_ABI opStatus multiply(const IEEEFloat &, roundingMode)
Definition APFloat.cpp:2141
LLVM_ABI opStatus roundToIntegral(roundingMode)
Definition APFloat.cpp:2368
LLVM_ABI IEEEFloat & operator=(const IEEEFloat &)
Definition APFloat.cpp:1010
LLVM_ABI bool bitwiseIsEqual(const IEEEFloat &) const
Bitwise comparison for equality (QNaNs compare equal, 0!=-0).
Definition APFloat.cpp:1177
LLVM_ABI void makeSmallestNormalized(bool Negative=false)
Returns the smallest (by magnitude) normalized finite number in the given semantics.
Definition APFloat.cpp:4104
LLVM_ABI bool isInteger() const
Returns true if and only if the number is an exact integer.
Definition APFloat.cpp:1169
LLVM_ABI IEEEFloat(const fltSemantics &)
Definition APFloat.cpp:1204
LLVM_ABI opStatus fusedMultiplyAdd(const IEEEFloat &, const IEEEFloat &, roundingMode)
Definition APFloat.cpp:2322
LLVM_ABI friend int ilogb(const IEEEFloat &Arg)
Definition APFloat.cpp:4685
LLVM_ABI opStatus next(bool nextDown)
IEEE-754R 5.3.1: nextUp/nextDown.
Definition APFloat.cpp:4498
bool isInfinity() const
IEEE-754R isInfinite(): Returns true if and only if the float is infinity.
Definition APFloat.h:592
const fltSemantics & getSemantics() const
Definition APFloat.h:606
bool isZero() const
Returns true if and only if the float is plus or minus zero.
Definition APFloat.h:585
LLVM_ABI bool isSignaling() const
Returns true if and only if the float is a signaling NaN.
Definition APFloat.cpp:4482
LLVM_ABI void makeZero(bool Neg=false)
Definition APFloat.cpp:4665
LLVM_ABI opStatus convert(const fltSemantics &, roundingMode, bool *)
IEEEFloat::convert - convert a value of one floating point type to another.
Definition APFloat.cpp:2529
LLVM_ABI void changeSign()
Definition APFloat.cpp:2087
LLVM_ABI bool isDenormal() const
IEEE-754R isSubnormal(): Returns true if and only if the float is a denormal.
Definition APFloat.cpp:1035
LLVM_ABI opStatus convertToInteger(MutableArrayRef< integerPart >, unsigned int, bool, roundingMode, bool *) const
Definition APFloat.cpp:2802
LLVM_ABI bool isSmallest() const
Returns true if and only if the number has the smallest possible non-zero magnitude in the current se...
Definition APFloat.cpp:1042
An opaque object representing a hash code.
Definition Hashing.h:77
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
static constexpr opStatus opInexact
Definition APFloat.h:471
LLVM_ABI SlowDynamicAPInt abs(const SlowDynamicAPInt &X)
Redeclarations of friend declarations above to make it discoverable by lookups.
static constexpr fltCategory fcNaN
Definition APFloat.h:473
static constexpr opStatus opDivByZero
Definition APFloat.h:468
static constexpr opStatus opOverflow
Definition APFloat.h:469
static constexpr cmpResult cmpLessThan
Definition APFloat.h:463
const char unit< Period >::value[]
Definition Chrono.h:104
static void tcSetLeastSignificantBits(APInt::WordType *dst, unsigned parts, unsigned bits)
Definition APFloat.cpp:1552
static constexpr roundingMode rmTowardPositive
Definition APFloat.h:459
static constexpr uninitializedTag uninitialized
Definition APFloat.h:453
static constexpr fltCategory fcZero
Definition APFloat.h:475
static constexpr opStatus opOK
Definition APFloat.h:466
static constexpr cmpResult cmpGreaterThan
Definition APFloat.h:464
static constexpr unsigned integerPartWidth
Definition APFloat.h:461
LLVM_ABI hash_code hash_value(const IEEEFloat &Arg)
Definition APFloat.cpp:3437
APFloatBase::ExponentType ExponentType
Definition APFloat.h:452
static constexpr fltCategory fcNormal
Definition APFloat.h:474
static constexpr opStatus opInvalidOp
Definition APFloat.h:467
APFloatBase::opStatus opStatus
Definition APFloat.h:449
LLVM_ABI IEEEFloat frexp(const IEEEFloat &Val, int &Exp, roundingMode RM)
Definition APFloat.cpp:4724
APFloatBase::uninitializedTag uninitializedTag
Definition APFloat.h:447
static constexpr cmpResult cmpUnordered
Definition APFloat.h:465
static constexpr roundingMode rmTowardNegative
Definition APFloat.h:458
APFloatBase::roundingMode roundingMode
Definition APFloat.h:448
APFloatBase::cmpResult cmpResult
Definition APFloat.h:450
static constexpr fltCategory fcInfinity
Definition APFloat.h:472
static constexpr roundingMode rmNearestTiesToAway
Definition APFloat.h:456
static constexpr roundingMode rmTowardZero
Definition APFloat.h:460
static constexpr opStatus opUnderflow
Definition APFloat.h:470
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:454
LLVM_ABI int ilogb(const IEEEFloat &Arg)
Definition APFloat.cpp:4685
static constexpr cmpResult cmpEqual
Definition APFloat.h:462
LLVM_ABI IEEEFloat scalbn(IEEEFloat X, int Exp, roundingMode)
Definition APFloat.cpp:4703
static std::pair< APFloat, APFloat > fastTwoSum(APFloat X, APFloat Y)
Definition APFloat.cpp:4813
APFloatBase::integerPart integerPart
Definition APFloat.h:446
FormattedNumber decValue(uint64_t N, unsigned Width=DEC_WIDTH)
Definition LVSupport.h:123
LLVM_ABI 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)
Definition APFloat.cpp:835
void fill(R &&Range, T &&Value)
Provide wrappers to std::fill which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1759
static const char infinityL[]
Definition APFloat.cpp:826
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
static constexpr unsigned int partCountForBits(unsigned int bits)
Definition APFloat.cpp:413
static const char NaNU[]
Definition APFloat.cpp:829
static unsigned int HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
Definition APFloat.cpp:711
static unsigned int powerOf5(APFloatBase::integerPart *dst, unsigned int power)
Definition APFloat.cpp:770
unsigned hexDigitValue(char C)
Interpret the given character C as a hexadecimal digit and return its value.
static APFloat harrisonUlp(const APFloat &X)
Definition APFloat.cpp:882
static constexpr APFloatBase::ExponentType exponentZero(const fltSemantics &semantics)
Definition APFloat.cpp:387
static Expected< int > totalExponent(StringRef::iterator p, StringRef::iterator end, int exponentAdjustment)
Definition APFloat.cpp:470
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition Error.cpp:94
const unsigned int maxPowerOfFiveExponent
Definition APFloat.cpp:313
int ilogb(const APFloat &Arg)
Returns the exponent of the internal representation of the APFloat.
Definition APFloat.h:1692
static char * writeUnsignedDecimal(char *dst, unsigned int n)
Definition APFloat.cpp:852
constexpr auto equal_to(T &&Arg)
Functor variant of std::equal_to that can be used as a UnaryPredicate in functional algorithms like a...
Definition STLExtras.h:2173
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:156
const unsigned int maxPrecision
Definition APFloat.cpp:312
APFloat frexp(const APFloat &X, int &Exp, APFloat::roundingMode RM)
Equivalent of C standard library function.
Definition APFloat.h:1713
static const char NaNL[]
Definition APFloat.cpp:828
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
static const char infinityU[]
Definition APFloat.cpp:827
lostFraction
Enum that represents what fraction of the LSB truncated bits of an fp number represent.
Definition APFloat.h:51
@ lfMoreThanHalf
Definition APFloat.h:55
@ lfLessThanHalf
Definition APFloat.h:53
@ lfExactlyHalf
Definition APFloat.h:54
@ lfExactlyZero
Definition APFloat.h:52
static Error interpretDecimal(StringRef::iterator begin, StringRef::iterator end, decimalInfo *D)
Definition APFloat.cpp:560
LLVM_READONLY LLVM_ABI std::optional< APFloat > exp(const APFloat &X, RoundingMode RM=APFloat::rmNearestTiesToEven, APFloat::opStatus *Status=nullptr)
Implement IEEE 754-2019 exp functions.
Definition APFloat.cpp:6229
LLVM_ABI 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
Definition APFloat.cpp:314
APFloat scalbn(APFloat X, int Exp, APFloat::roundingMode RM)
Returns: X * 2^Exp for integral exponents.
Definition APFloat.h:1701
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
static constexpr APFloatBase::ExponentType exponentNaN(const fltSemantics &semantics)
Definition APFloat.cpp:397
static Error createError(const Twine &Err)
Definition APFloat.cpp:409
static lostFraction shiftRight(APFloatBase::integerPart *dst, unsigned int parts, unsigned int bits)
Definition APFloat.cpp:679
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
static const char hexDigitsUpper[]
Definition APFloat.cpp:825
const unsigned int maxExponent
Definition APFloat.cpp:311
static unsigned int decDigitValue(unsigned int c)
Definition APFloat.cpp:420
fltNonfiniteBehavior
Definition APFloat.h:977
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...
Definition STLExtras.h:2012
static lostFraction combineLostFractions(lostFraction moreSignificant, lostFraction lessSignificant)
Definition APFloat.cpp:690
static Expected< StringRef::iterator > skipLeadingZeroesAndAnyDot(StringRef::iterator begin, StringRef::iterator end, StringRef::iterator *dot)
Definition APFloat.cpp:520
RoundingMode
Rounding mode.
ArrayRef(const T &OneElt) -> ArrayRef< T >
static constexpr APFloatBase::ExponentType exponentInf(const fltSemantics &semantics)
Definition APFloat.cpp:392
static lostFraction lostFractionThroughTruncation(const APFloatBase::integerPart *parts, unsigned int partCount, unsigned int bits)
Definition APFloat.cpp:659
APFloat neg(APFloat X)
Returns the negated value of the argument.
Definition APFloat.h:1727
static APFloatBase::integerPart ulpsFromBoundary(const APFloatBase::integerPart *parts, unsigned int bits, bool isNearest)
Definition APFloat.cpp:725
static char * writeSignedDecimal(char *dst, int value)
Definition APFloat.cpp:868
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Definition Hashing.h:305
static Expected< lostFraction > trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end, unsigned int digitValue)
Definition APFloat.cpp:630
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1106
static Expected< int > readExponent(StringRef::iterator begin, StringRef::iterator end)
Definition APFloat.cpp:430
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition Hashing.h:285
constexpr uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
Definition MathExtras.h:368
static const char hexDigitsLower[]
Definition APFloat.cpp:824
#define N
const char * lastSigDigit
Definition APFloat.cpp:555
const char * firstSigDigit
Definition APFloat.cpp:554
APFloatBase::ExponentType maxExponent
Definition APFloat.h:1026
fltNonfiniteBehavior nonFiniteBehavior
Definition APFloat.h:1039
APFloatBase::ExponentType minExponent
Definition APFloat.h:1030
unsigned int sizeInBits
Definition APFloat.h:1037
unsigned int precision
Definition APFloat.h:1034
fltNanEncoding nanEncoding
Definition APFloat.h:1041