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