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