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