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