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 if constexpr (S.hasSignedRepr) {
3595 uint64_t shifted_sign = static_cast<uint64_t>(sign & 1)
3596 << ((S.sizeInBits - 1) % 64);
3597 words[last_word] |= shifted_sign;
3598 }
3599 uint64_t shifted_exponent = (myexponent & exponent_mask)
3600 << (trailing_significand_bits % 64);
3601 words[last_word] |= shifted_exponent;
3602 if constexpr (last_word == 0) {
3603 return APInt(S.sizeInBits, words[0]);
3604 }
3605 return APInt(S.sizeInBits, words);
3606}
3607
3608APInt IEEEFloat::convertQuadrupleAPFloatToAPInt() const {
3609 assert(partCount() == 2);
3610 return convertIEEEFloatToAPInt<APFloatBase::semIEEEquad>();
3611}
3612
3613APInt IEEEFloat::convertDoubleAPFloatToAPInt() const {
3614 assert(partCount()==1);
3615 return convertIEEEFloatToAPInt<APFloatBase::semIEEEdouble>();
3616}
3617
3618APInt IEEEFloat::convertFloatAPFloatToAPInt() const {
3619 assert(partCount()==1);
3620 return convertIEEEFloatToAPInt<APFloatBase::semIEEEsingle>();
3621}
3622
3623APInt IEEEFloat::convertBFloatAPFloatToAPInt() const {
3624 assert(partCount() == 1);
3625 return convertIEEEFloatToAPInt<APFloatBase::semBFloat>();
3626}
3627
3628APInt IEEEFloat::convertHalfAPFloatToAPInt() const {
3629 assert(partCount()==1);
3630 return convertIEEEFloatToAPInt<APFloatBase::APFloatBase::semIEEEhalf>();
3631}
3632
3633APInt IEEEFloat::convertFloat8E5M2APFloatToAPInt() const {
3634 assert(partCount() == 1);
3635 return convertIEEEFloatToAPInt<APFloatBase::semFloat8E5M2>();
3636}
3637
3638APInt IEEEFloat::convertFloat8E5M2FNUZAPFloatToAPInt() const {
3639 assert(partCount() == 1);
3640 return convertIEEEFloatToAPInt<APFloatBase::semFloat8E5M2FNUZ>();
3641}
3642
3643APInt IEEEFloat::convertFloat8E4M3APFloatToAPInt() const {
3644 assert(partCount() == 1);
3645 return convertIEEEFloatToAPInt<APFloatBase::semFloat8E4M3>();
3646}
3647
3648APInt IEEEFloat::convertFloat8E4M3FNAPFloatToAPInt() const {
3649 assert(partCount() == 1);
3650 return convertIEEEFloatToAPInt<APFloatBase::semFloat8E4M3FN>();
3651}
3652
3653APInt IEEEFloat::convertFloat8E4M3FNUZAPFloatToAPInt() const {
3654 assert(partCount() == 1);
3655 return convertIEEEFloatToAPInt<APFloatBase::semFloat8E4M3FNUZ>();
3656}
3657
3658APInt IEEEFloat::convertFloat8E4M3B11FNUZAPFloatToAPInt() const {
3659 assert(partCount() == 1);
3660 return convertIEEEFloatToAPInt<APFloatBase::semFloat8E4M3B11FNUZ>();
3661}
3662
3663APInt IEEEFloat::convertFloat8E3M4APFloatToAPInt() const {
3664 assert(partCount() == 1);
3665 return convertIEEEFloatToAPInt<APFloatBase::semFloat8E3M4>();
3666}
3667
3668APInt IEEEFloat::convertFloatTF32APFloatToAPInt() const {
3669 assert(partCount() == 1);
3670 return convertIEEEFloatToAPInt<APFloatBase::semFloatTF32>();
3671}
3672
3673APInt IEEEFloat::convertFloat8E8M0FNUAPFloatToAPInt() const {
3674 assert(partCount() == 1);
3675 return convertIEEEFloatToAPInt<APFloatBase::semFloat8E8M0FNU>();
3676}
3677
3678APInt IEEEFloat::convertFloat8E5M3FNUAPFloatToAPInt() const {
3679 assert(partCount() == 1);
3680 return convertIEEEFloatToAPInt<APFloatBase::semFloat8E5M3FNU>();
3681}
3682
3683APInt IEEEFloat::convertFloat6E3M2FNAPFloatToAPInt() const {
3684 assert(partCount() == 1);
3685 return convertIEEEFloatToAPInt<APFloatBase::semFloat6E3M2FN>();
3686}
3687
3688APInt IEEEFloat::convertFloat6E2M3FNAPFloatToAPInt() const {
3689 assert(partCount() == 1);
3690 return convertIEEEFloatToAPInt<APFloatBase::semFloat6E2M3FN>();
3691}
3692
3693APInt IEEEFloat::convertFloat4E2M1FNAPFloatToAPInt() const {
3694 assert(partCount() == 1);
3695 return convertIEEEFloatToAPInt<APFloatBase::semFloat4E2M1FN>();
3696}
3697
3698// This function creates an APInt that is just a bit map of the floating
3699// point constant as it would appear in memory. It is not a conversion,
3700// and treating the result as a normal integer is unlikely to be useful.
3701
3703 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semIEEEhalf)
3704 return convertHalfAPFloatToAPInt();
3705
3706 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semBFloat)
3707 return convertBFloatAPFloatToAPInt();
3708
3709 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semIEEEsingle)
3710 return convertFloatAPFloatToAPInt();
3711
3712 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semIEEEdouble)
3713 return convertDoubleAPFloatToAPInt();
3714
3715 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semIEEEquad)
3716 return convertQuadrupleAPFloatToAPInt();
3717
3718 if (semantics ==
3719 (const llvm::fltSemantics *)&APFloatBase::semPPCDoubleDoubleLegacy)
3720 return convertPPCDoubleDoubleLegacyAPFloatToAPInt();
3721
3722 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat8E5M2)
3723 return convertFloat8E5M2APFloatToAPInt();
3724
3725 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat8E5M2FNUZ)
3726 return convertFloat8E5M2FNUZAPFloatToAPInt();
3727
3728 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat8E4M3)
3729 return convertFloat8E4M3APFloatToAPInt();
3730
3731 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat8E4M3FN)
3732 return convertFloat8E4M3FNAPFloatToAPInt();
3733
3734 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat8E4M3FNUZ)
3735 return convertFloat8E4M3FNUZAPFloatToAPInt();
3736
3737 if (semantics ==
3738 (const llvm::fltSemantics *)&APFloatBase::semFloat8E4M3B11FNUZ)
3739 return convertFloat8E4M3B11FNUZAPFloatToAPInt();
3740
3741 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat8E3M4)
3742 return convertFloat8E3M4APFloatToAPInt();
3743
3744 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloatTF32)
3745 return convertFloatTF32APFloatToAPInt();
3746
3747 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat8E8M0FNU)
3748 return convertFloat8E8M0FNUAPFloatToAPInt();
3749
3750 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat8E5M3FNU)
3751 return convertFloat8E5M3FNUAPFloatToAPInt();
3752
3753 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat6E3M2FN)
3754 return convertFloat6E3M2FNAPFloatToAPInt();
3755
3756 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat6E2M3FN)
3757 return convertFloat6E2M3FNAPFloatToAPInt();
3758
3759 if (semantics == (const llvm::fltSemantics *)&APFloatBase::semFloat4E2M1FN)
3760 return convertFloat4E2M1FNAPFloatToAPInt();
3761
3762 assert(semantics ==
3763 (const llvm::fltSemantics *)&APFloatBase::semX87DoubleExtended &&
3764 "unknown format!");
3765 return convertF80LongDoubleAPFloatToAPInt();
3766}
3767
3769 assert(semantics == (const llvm::fltSemantics *)&APFloatBase::semIEEEsingle &&
3770 "Float semantics are not IEEEsingle");
3771 APInt api = bitcastToAPInt();
3772 return api.bitsToFloat();
3773}
3774
3776 assert(semantics == (const llvm::fltSemantics *)&APFloatBase::semIEEEdouble &&
3777 "Float semantics are not IEEEdouble");
3778 APInt api = bitcastToAPInt();
3779 return api.bitsToDouble();
3780}
3781
3782#ifdef HAS_IEE754_FLOAT128
3783float128 IEEEFloat::convertToQuad() const {
3784 assert(semantics == (const llvm::fltSemantics *)&APFloatBase::semIEEEquad &&
3785 "Float semantics are not IEEEquads");
3786 APInt api = bitcastToAPInt();
3787 return api.bitsToQuad();
3788}
3789#endif
3790
3791void IEEEFloat::initFromF80LongDoubleAPInt(const APInt &api) {
3792 return initFromIEEEAPInt<APFloatBase::semX87DoubleExtended>(api);
3793}
3794
3795void IEEEFloat::initFromPPCDoubleDoubleLegacyAPInt(const APInt &api) {
3796 uint64_t i1 = api.getRawData()[0];
3797 uint64_t i2 = api.getRawData()[1];
3798 bool losesInfo;
3799
3800 // Get the first double and convert to our format.
3801 initFromDoubleAPInt(APInt(64, i1));
3802 [[maybe_unused]] opStatus fs = convert(APFloatBase::semPPCDoubleDoubleLegacy,
3803 rmNearestTiesToEven, &losesInfo);
3804 // (convert may return opInvalidOp if i1 is an sNaN).
3805 assert((fs == opOK || fs == opInvalidOp) && !losesInfo);
3806
3807 // Unless we have a special case, add in second double.
3808 if (isFiniteNonZero()) {
3809 IEEEFloat v(APFloatBase::semIEEEdouble, APInt(64, i2));
3810 fs = v.convert(APFloatBase::semPPCDoubleDoubleLegacy, rmNearestTiesToEven,
3811 &losesInfo);
3812 assert(fs == opOK && !losesInfo);
3813
3815 }
3816}
3817
3818// The E8M0 format has the following characteristics:
3819// It is an 8-bit unsigned format with only exponents (no actual significand).
3820// No encodings for {zero, infinities or denorms}.
3821// NaN is represented by all 1's.
3822// Bias is 127.
3823void IEEEFloat::initFromFloat8E8M0FNUAPInt(const APInt &api) {
3824 initFromIEEEAPInt<APFloatBase::semFloat8E8M0FNU>(api);
3825}
3826
3827void IEEEFloat::initFromFloat8E5M3FNUAPInt(const APInt &api) {
3828 initFromIEEEAPInt<APFloatBase::semFloat8E5M3FNU>(api);
3829}
3830
3831template <const fltSemantics &S>
3832void IEEEFloat::initFromIEEEAPInt(const APInt &api) {
3833 assert(api.getBitWidth() == S.sizeInBits);
3834
3835 constexpr unsigned int trailing_significand_bits =
3836 S.precision - 1 + S.hasExplicitIntegerBit;
3837 constexpr integerPart integer_bit =
3838 integerPart{1} << (trailing_significand_bits % integerPartWidth);
3839 constexpr uint64_t significand_mask = integer_bit - 1;
3840 constexpr unsigned int exponent_bits =
3841 S.sizeInBits - (S.hasSignedRepr ? 1 : 0) - trailing_significand_bits;
3842 static_assert(exponent_bits < 64);
3843 constexpr unsigned int stored_significand_parts =
3844 partCountForBits(trailing_significand_bits + 1);
3845 constexpr uint64_t exponent_mask = (uint64_t{1} << exponent_bits) - 1;
3846 constexpr bool is_zero_exp_reserved = S.hasDenormals || S.hasZero;
3847 constexpr int bias = -(S.minExponent - (is_zero_exp_reserved ? 1 : 0));
3848 constexpr bool has_significand = trailing_significand_bits > 0;
3849
3850 // Copy the bits of the significand. We need to clear out the exponent and
3851 // sign bit in the last word.
3852 std::array<integerPart, stored_significand_parts> mysignificand;
3853 if constexpr (has_significand) {
3854 std::copy_n(api.getRawData(), mysignificand.size(), mysignificand.begin());
3855 if constexpr (significand_mask != 0 || S.precision >= integerPartWidth) {
3856 mysignificand[mysignificand.size() - 1] &= significand_mask;
3857 }
3858 } else {
3859 std::fill_n(mysignificand.begin(), mysignificand.size(), 0);
3860 // Always set integer bit to 1 for consistency in APFloat's internal
3861 // representation.
3862 mysignificand[0] = 1;
3863 }
3864
3865 // We assume the last word holds the sign bit, the exponent, and potentially
3866 // some of the trailing significand field.
3867 uint64_t last_word = api.getRawData()[api.getNumWords() - 1];
3868 uint64_t myexponent =
3869 (last_word >> (trailing_significand_bits % 64)) & exponent_mask;
3870
3871 initialize(&S);
3872 assert(partCount() == mysignificand.size());
3873
3874 sign = S.hasSignedRepr
3875 ? static_cast<unsigned int>(last_word >> ((S.sizeInBits - 1) % 64))
3876 : 0;
3877
3878 bool all_zero_significand =
3879 has_significand && llvm::all_of(mysignificand, equal_to(0));
3880
3881 bool is_zero = myexponent == 0 && all_zero_significand && S.hasZero;
3882
3883 if constexpr (S.nonFiniteBehavior == fltNonfiniteBehavior::IEEE754) {
3884 bool is_inf = false;
3885
3886 if constexpr (S.hasExplicitIntegerBit) {
3887 // This is only used and tested for x87DoubleExtended
3888 static_assert(S.precision == 64);
3889 constexpr integerPart significand_mask_no_int_bit =
3890 (uint64_t{1} << (trailing_significand_bits - 1)) - 1;
3891 const integerPart myintegerbit =
3892 mysignificand[0] >> (trailing_significand_bits - 1);
3893
3894 is_inf = myexponent - bias == ::exponentInf(S) && myintegerbit == 1 &&
3895 (mysignificand[0] & significand_mask_no_int_bit) == 0;
3896 } else {
3897 is_inf = myexponent - bias == ::exponentInf(S) && all_zero_significand;
3898 }
3899
3900 if (is_inf) {
3901 makeInf(sign);
3902 return;
3903 }
3904 }
3905
3906 bool is_nan = false;
3907
3908 if constexpr (S.nanEncoding == fltNanEncoding::IEEE) {
3909 if constexpr (S.hasExplicitIntegerBit) {
3910 // This is only used and tested for x87DoubleExtended
3911 static_assert(S.precision == 64);
3912 const integerPart myintegerbit =
3913 mysignificand[0] >> (trailing_significand_bits - 1);
3914 constexpr integerPart significand_mask_no_int_bit =
3915 (uint64_t{1} << (trailing_significand_bits - 1)) - 1;
3916
3917 if (myexponent - bias == ::exponentNaN(S) &&
3918 (mysignificand[0] & significand_mask_no_int_bit) != 0) {
3919 // regular NaN and pseudoNaN
3920 is_nan = true;
3921 } else if (myexponent - bias == ::exponentNaN(S) &&
3922 (mysignificand[0] & significand_mask_no_int_bit) == 0) {
3923 // pseudoinfinity
3924 is_nan = true;
3925 } else if (myexponent - bias != ::exponentNaN(S) && myexponent != 0 &&
3926 myintegerbit == 0) {
3927 // unnormal
3928 is_nan = true;
3929 }
3930 } else {
3931 is_nan = myexponent - bias == ::exponentNaN(S) && !all_zero_significand;
3932 }
3933 } else if constexpr (S.nanEncoding == fltNanEncoding::AllOnes) {
3934 bool all_ones_significand =
3935 std::all_of(mysignificand.begin(), mysignificand.end() - 1,
3936 [](integerPart bits) { return bits == ~integerPart{0}; }) &&
3937 (!significand_mask ||
3938 mysignificand[mysignificand.size() - 1] == significand_mask);
3939 is_nan = myexponent - bias == ::exponentNaN(S) && all_ones_significand;
3940 } else if constexpr (S.nanEncoding == fltNanEncoding::NegativeZero) {
3941 is_nan = is_zero && sign;
3942 }
3943
3944 if (is_nan) {
3945 category = fcNaN;
3946 exponent = ::exponentNaN(S);
3947 std::copy_n(mysignificand.begin(), mysignificand.size(),
3948 significandParts());
3949 return;
3950 }
3951
3952 if (is_zero) {
3953 makeZero(sign);
3954 return;
3955 }
3956
3957 category = fcNormal;
3958 exponent = myexponent - bias;
3959 std::copy_n(mysignificand.begin(), mysignificand.size(), significandParts());
3960 if (myexponent == 0 && S.hasDenormals) // denormal
3961 exponent = S.minExponent;
3962 else {
3963 if constexpr (!S.hasExplicitIntegerBit) {
3964 significandParts()[mysignificand.size() - 1] |= integer_bit;
3965 }
3966 }
3967}
3968
3969void IEEEFloat::initFromQuadrupleAPInt(const APInt &api) {
3970 initFromIEEEAPInt<APFloatBase::semIEEEquad>(api);
3971}
3972
3973void IEEEFloat::initFromDoubleAPInt(const APInt &api) {
3974 initFromIEEEAPInt<APFloatBase::semIEEEdouble>(api);
3975}
3976
3977void IEEEFloat::initFromFloatAPInt(const APInt &api) {
3978 initFromIEEEAPInt<APFloatBase::semIEEEsingle>(api);
3979}
3980
3981void IEEEFloat::initFromBFloatAPInt(const APInt &api) {
3982 initFromIEEEAPInt<APFloatBase::semBFloat>(api);
3983}
3984
3985void IEEEFloat::initFromHalfAPInt(const APInt &api) {
3986 initFromIEEEAPInt<APFloatBase::semIEEEhalf>(api);
3987}
3988
3989void IEEEFloat::initFromFloat8E5M2APInt(const APInt &api) {
3990 initFromIEEEAPInt<APFloatBase::semFloat8E5M2>(api);
3991}
3992
3993void IEEEFloat::initFromFloat8E5M2FNUZAPInt(const APInt &api) {
3994 initFromIEEEAPInt<APFloatBase::semFloat8E5M2FNUZ>(api);
3995}
3996
3997void IEEEFloat::initFromFloat8E4M3APInt(const APInt &api) {
3998 initFromIEEEAPInt<APFloatBase::semFloat8E4M3>(api);
3999}
4000
4001void IEEEFloat::initFromFloat8E4M3FNAPInt(const APInt &api) {
4002 initFromIEEEAPInt<APFloatBase::semFloat8E4M3FN>(api);
4003}
4004
4005void IEEEFloat::initFromFloat8E4M3FNUZAPInt(const APInt &api) {
4006 initFromIEEEAPInt<APFloatBase::semFloat8E4M3FNUZ>(api);
4007}
4008
4009void IEEEFloat::initFromFloat8E4M3B11FNUZAPInt(const APInt &api) {
4010 initFromIEEEAPInt<APFloatBase::semFloat8E4M3B11FNUZ>(api);
4011}
4012
4013void IEEEFloat::initFromFloat8E3M4APInt(const APInt &api) {
4014 initFromIEEEAPInt<APFloatBase::semFloat8E3M4>(api);
4015}
4016
4017void IEEEFloat::initFromFloatTF32APInt(const APInt &api) {
4018 initFromIEEEAPInt<APFloatBase::semFloatTF32>(api);
4019}
4020
4021void IEEEFloat::initFromFloat6E3M2FNAPInt(const APInt &api) {
4022 initFromIEEEAPInt<APFloatBase::semFloat6E3M2FN>(api);
4023}
4024
4025void IEEEFloat::initFromFloat6E2M3FNAPInt(const APInt &api) {
4026 initFromIEEEAPInt<APFloatBase::semFloat6E2M3FN>(api);
4027}
4028
4029void IEEEFloat::initFromFloat4E2M1FNAPInt(const APInt &api) {
4030 initFromIEEEAPInt<APFloatBase::semFloat4E2M1FN>(api);
4031}
4032
4033/// Treat api as containing the bits of a floating point number.
4034void IEEEFloat::initFromAPInt(const fltSemantics *Sem, const APInt &api) {
4035 assert(api.getBitWidth() == Sem->sizeInBits);
4036 if (Sem == &APFloatBase::semIEEEhalf)
4037 return initFromHalfAPInt(api);
4038 if (Sem == &APFloatBase::semBFloat)
4039 return initFromBFloatAPInt(api);
4040 if (Sem == &APFloatBase::semIEEEsingle)
4041 return initFromFloatAPInt(api);
4042 if (Sem == &APFloatBase::semIEEEdouble)
4043 return initFromDoubleAPInt(api);
4044 if (Sem == &APFloatBase::semX87DoubleExtended)
4045 return initFromF80LongDoubleAPInt(api);
4046 if (Sem == &APFloatBase::semIEEEquad)
4047 return initFromQuadrupleAPInt(api);
4048 if (Sem == &APFloatBase::semPPCDoubleDoubleLegacy)
4049 return initFromPPCDoubleDoubleLegacyAPInt(api);
4050 if (Sem == &APFloatBase::semFloat8E5M2)
4051 return initFromFloat8E5M2APInt(api);
4052 if (Sem == &APFloatBase::semFloat8E5M2FNUZ)
4053 return initFromFloat8E5M2FNUZAPInt(api);
4054 if (Sem == &APFloatBase::semFloat8E4M3)
4055 return initFromFloat8E4M3APInt(api);
4056 if (Sem == &APFloatBase::semFloat8E4M3FN)
4057 return initFromFloat8E4M3FNAPInt(api);
4058 if (Sem == &APFloatBase::semFloat8E4M3FNUZ)
4059 return initFromFloat8E4M3FNUZAPInt(api);
4060 if (Sem == &APFloatBase::semFloat8E4M3B11FNUZ)
4061 return initFromFloat8E4M3B11FNUZAPInt(api);
4062 if (Sem == &APFloatBase::semFloat8E3M4)
4063 return initFromFloat8E3M4APInt(api);
4064 if (Sem == &APFloatBase::semFloatTF32)
4065 return initFromFloatTF32APInt(api);
4066 if (Sem == &APFloatBase::semFloat8E8M0FNU)
4067 return initFromFloat8E8M0FNUAPInt(api);
4068 if (Sem == &APFloatBase::semFloat8E5M3FNU)
4069 return initFromFloat8E5M3FNUAPInt(api);
4070 if (Sem == &APFloatBase::semFloat6E3M2FN)
4071 return initFromFloat6E3M2FNAPInt(api);
4072 if (Sem == &APFloatBase::semFloat6E2M3FN)
4073 return initFromFloat6E2M3FNAPInt(api);
4074 if (Sem == &APFloatBase::semFloat4E2M1FN)
4075 return initFromFloat4E2M1FNAPInt(api);
4076
4077 llvm_unreachable("unsupported semantics");
4078}
4079
4080/// Make this number the largest magnitude normal number in the given
4081/// semantics.
4082void IEEEFloat::makeLargest(bool Negative) {
4083 if (Negative && !semantics->hasSignedRepr)
4085 "This floating point format does not support signed values");
4086 // We want (in interchange format):
4087 // sign = {Negative}
4088 // exponent = 1..10
4089 // significand = 1..1
4090 category = fcNormal;
4091 sign = Negative;
4092 exponent = semantics->maxExponent;
4093
4094 // Use memset to set all but the highest integerPart to all ones.
4095 integerPart *significand = significandParts();
4096 unsigned PartCount = partCount();
4097 memset(significand, 0xFF, sizeof(integerPart)*(PartCount - 1));
4098
4099 // Set the high integerPart especially setting all unused top bits for
4100 // internal consistency.
4101 const unsigned NumUnusedHighBits =
4102 PartCount*integerPartWidth - semantics->precision;
4103 significand[PartCount - 1] = (NumUnusedHighBits < integerPartWidth)
4104 ? (~integerPart(0) >> NumUnusedHighBits)
4105 : 0;
4106 if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly &&
4107 semantics->nanEncoding == fltNanEncoding::AllOnes &&
4108 (semantics->precision > 1))
4109 significand[0] &= ~integerPart(1);
4110}
4111
4112/// Make this number the smallest magnitude denormal number in the given
4113/// semantics.
4114void IEEEFloat::makeSmallest(bool Negative) {
4115 if (Negative && !semantics->hasSignedRepr)
4117 "This floating point format does not support signed values");
4118 // We want (in interchange format):
4119 // sign = {Negative}
4120 // exponent = 0..0
4121 // significand = 0..01
4122 category = fcNormal;
4123 sign = Negative;
4124 exponent = semantics->minExponent;
4125 APInt::tcSet(significandParts(), 1, partCount());
4126}
4127
4129 if (Negative && !semantics->hasSignedRepr)
4131 "This floating point format does not support signed values");
4132 // We want (in interchange format):
4133 // sign = {Negative}
4134 // exponent = 0..0
4135 // significand = 10..0
4136
4137 category = fcNormal;
4138 zeroSignificand();
4139 sign = Negative;
4140 exponent = semantics->minExponent;
4141 APInt::tcSetBit(significandParts(), semantics->precision - 1);
4142}
4143
4144IEEEFloat::IEEEFloat(const fltSemantics &Sem, const APInt &API) {
4145 initFromAPInt(&Sem, API);
4146}
4147
4149 initFromAPInt(&APFloatBase::semIEEEsingle, APInt::floatToBits(f));
4150}
4151
4153 initFromAPInt(&APFloatBase::semIEEEdouble, APInt::doubleToBits(d));
4154}
4155
4156namespace {
4157 void append(SmallVectorImpl<char> &Buffer, StringRef Str) {
4158 Buffer.append(Str.begin(), Str.end());
4159 }
4160
4161 /// Removes data from the given significand until it is no more
4162 /// precise than is required for the desired precision.
4163 void AdjustToPrecision(APInt &significand,
4164 int &exp, unsigned FormatPrecision) {
4165 unsigned bits = significand.getActiveBits();
4166
4167 // 196/59 is a very slight overestimate of lg_2(10).
4168 unsigned bitsRequired = (FormatPrecision * 196 + 58) / 59;
4169
4170 if (bits <= bitsRequired) return;
4171
4172 unsigned tensRemovable = (bits - bitsRequired) * 59 / 196;
4173 if (!tensRemovable) return;
4174
4175 exp += tensRemovable;
4176
4177 APInt divisor(significand.getBitWidth(), 1);
4178 APInt powten(significand.getBitWidth(), 10);
4179 while (true) {
4180 if (tensRemovable & 1)
4181 divisor *= powten;
4182 tensRemovable >>= 1;
4183 if (!tensRemovable) break;
4184 powten *= powten;
4185 }
4186
4187 significand = significand.udiv(divisor);
4188
4189 // Truncate the significand down to its active bit count.
4190 significand = significand.trunc(significand.getActiveBits());
4191 }
4192
4193
4194 void AdjustToPrecision(SmallVectorImpl<char> &buffer,
4195 int &exp, unsigned FormatPrecision) {
4196 unsigned N = buffer.size();
4197 if (N <= FormatPrecision) return;
4198
4199 // The most significant figures are the last ones in the buffer.
4200 unsigned FirstSignificant = N - FormatPrecision;
4201
4202 // Round.
4203 // FIXME: this probably shouldn't use 'round half up'.
4204
4205 // Rounding down is just a truncation, except we also want to drop
4206 // trailing zeros from the new result.
4207 if (buffer[FirstSignificant - 1] < '5') {
4208 while (FirstSignificant < N && buffer[FirstSignificant] == '0')
4209 FirstSignificant++;
4210
4211 exp += FirstSignificant;
4212 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
4213 return;
4214 }
4215
4216 // Rounding up requires a decimal add-with-carry. If we continue
4217 // the carry, the newly-introduced zeros will just be truncated.
4218 for (unsigned I = FirstSignificant; I != N; ++I) {
4219 if (buffer[I] == '9') {
4220 FirstSignificant++;
4221 } else {
4222 buffer[I]++;
4223 break;
4224 }
4225 }
4226
4227 // If we carried through, we have exactly one digit of precision.
4228 if (FirstSignificant == N) {
4229 exp += FirstSignificant;
4230 buffer.clear();
4231 buffer.push_back('1');
4232 return;
4233 }
4234
4235 exp += FirstSignificant;
4236 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
4237 }
4238
4239 void toStringImpl(SmallVectorImpl<char> &Str, const bool isNeg, int exp,
4240 APInt significand, unsigned FormatPrecision,
4241 unsigned FormatMaxPadding, bool TruncateZero) {
4242 const int semanticsPrecision = significand.getBitWidth();
4243
4244 if (isNeg)
4245 Str.push_back('-');
4246
4247 // Set FormatPrecision if zero. We want to do this before we
4248 // truncate trailing zeros, as those are part of the precision.
4249 if (!FormatPrecision) {
4250 // We use enough digits so the number can be round-tripped back to an
4251 // APFloat. The formula comes from "How to Print Floating-Point Numbers
4252 // Accurately" by Steele and White.
4253 // FIXME: Using a formula based purely on the precision is conservative;
4254 // we can print fewer digits depending on the actual value being printed.
4255
4256 // FormatPrecision = 2 + floor(significandBits / lg_2(10))
4257 FormatPrecision = 2 + semanticsPrecision * 59 / 196;
4258 }
4259
4260 // Ignore trailing binary zeros.
4261 int trailingZeros = significand.countr_zero();
4262 exp += trailingZeros;
4263 significand.lshrInPlace(trailingZeros);
4264
4265 // Change the exponent from 2^e to 10^e.
4266 if (exp == 0) {
4267 // Nothing to do.
4268 } else if (exp > 0) {
4269 // Just shift left.
4270 significand = significand.zext(semanticsPrecision + exp);
4271 significand <<= exp;
4272 exp = 0;
4273 } else { /* exp < 0 */
4274 int texp = -exp;
4275
4276 // We transform this using the identity:
4277 // (N)(2^-e) == (N)(5^e)(10^-e)
4278 // This means we have to multiply N (the significand) by 5^e.
4279 // To avoid overflow, we have to operate on numbers large
4280 // enough to store N * 5^e:
4281 // log2(N * 5^e) == log2(N) + e * log2(5)
4282 // <= semantics->precision + e * 137 / 59
4283 // (log_2(5) ~ 2.321928 < 2.322034 ~ 137/59)
4284
4285 unsigned precision = semanticsPrecision + (137 * texp + 136) / 59;
4286
4287 // Multiply significand by 5^e.
4288 // N * 5^0101 == N * 5^(1*1) * 5^(0*2) * 5^(1*4) * 5^(0*8)
4289 significand = significand.zext(precision);
4290 APInt five_to_the_i(precision, 5);
4291 while (true) {
4292 if (texp & 1)
4293 significand *= five_to_the_i;
4294
4295 texp >>= 1;
4296 if (!texp)
4297 break;
4298 five_to_the_i *= five_to_the_i;
4299 }
4300 }
4301
4302 AdjustToPrecision(significand, exp, FormatPrecision);
4303
4305
4306 // Fill the buffer.
4307 unsigned precision = significand.getBitWidth();
4308 if (precision < 4) {
4309 // We need enough precision to store the value 10.
4310 precision = 4;
4311 significand = significand.zext(precision);
4312 }
4313 APInt ten(precision, 10);
4314 APInt digit(precision, 0);
4315
4316 bool inTrail = true;
4317 while (significand != 0) {
4318 // digit <- significand % 10
4319 // significand <- significand / 10
4320 APInt::udivrem(significand, ten, significand, digit);
4321
4322 unsigned d = digit.getZExtValue();
4323
4324 // Drop trailing zeros.
4325 if (inTrail && !d)
4326 exp++;
4327 else {
4328 buffer.push_back((char) ('0' + d));
4329 inTrail = false;
4330 }
4331 }
4332
4333 assert(!buffer.empty() && "no characters in buffer!");
4334
4335 // Drop down to FormatPrecision.
4336 // TODO: don't do more precise calculations above than are required.
4337 AdjustToPrecision(buffer, exp, FormatPrecision);
4338
4339 unsigned NDigits = buffer.size();
4340
4341 // Check whether we should use scientific notation.
4342 bool FormatScientific;
4343 if (!FormatMaxPadding) {
4344 FormatScientific = true;
4345 } else {
4346 if (exp >= 0) {
4347 // 765e3 --> 765000
4348 // ^^^
4349 // But we shouldn't make the number look more precise than it is.
4350 FormatScientific = ((unsigned) exp > FormatMaxPadding ||
4351 NDigits + (unsigned) exp > FormatPrecision);
4352 } else {
4353 // Power of the most significant digit.
4354 int MSD = exp + (int) (NDigits - 1);
4355 if (MSD >= 0) {
4356 // 765e-2 == 7.65
4357 FormatScientific = false;
4358 } else {
4359 // 765e-5 == 0.00765
4360 // ^ ^^
4361 FormatScientific = ((unsigned) -MSD) > FormatMaxPadding;
4362 }
4363 }
4364 }
4365
4366 // Scientific formatting is pretty straightforward.
4367 if (FormatScientific) {
4368 exp += (NDigits - 1);
4369
4370 Str.push_back(buffer[NDigits-1]);
4371 Str.push_back('.');
4372 if (NDigits == 1 && TruncateZero)
4373 Str.push_back('0');
4374 else
4375 for (unsigned I = 1; I != NDigits; ++I)
4376 Str.push_back(buffer[NDigits-1-I]);
4377 // Fill with zeros up to FormatPrecision.
4378 if (!TruncateZero && FormatPrecision > NDigits - 1)
4379 Str.append(FormatPrecision - NDigits + 1, '0');
4380 // For !TruncateZero we use lower 'e'.
4381 Str.push_back(TruncateZero ? 'E' : 'e');
4382
4383 Str.push_back(exp >= 0 ? '+' : '-');
4384 if (exp < 0)
4385 exp = -exp;
4386 SmallVector<char, 6> expbuf;
4387 do {
4388 expbuf.push_back((char) ('0' + (exp % 10)));
4389 exp /= 10;
4390 } while (exp);
4391 // Exponent always at least two digits if we do not truncate zeros.
4392 if (!TruncateZero && expbuf.size() < 2)
4393 expbuf.push_back('0');
4394 for (unsigned I = 0, E = expbuf.size(); I != E; ++I)
4395 Str.push_back(expbuf[E-1-I]);
4396 return;
4397 }
4398
4399 // Non-scientific, positive exponents.
4400 if (exp >= 0) {
4401 for (unsigned I = 0; I != NDigits; ++I)
4402 Str.push_back(buffer[NDigits-1-I]);
4403 for (unsigned I = 0; I != (unsigned) exp; ++I)
4404 Str.push_back('0');
4405 return;
4406 }
4407
4408 // Non-scientific, negative exponents.
4409
4410 // The number of digits to the left of the decimal point.
4411 int NWholeDigits = exp + (int) NDigits;
4412
4413 unsigned I = 0;
4414 if (NWholeDigits > 0) {
4415 for (; I != (unsigned) NWholeDigits; ++I)
4416 Str.push_back(buffer[NDigits-I-1]);
4417 Str.push_back('.');
4418 } else {
4419 unsigned NZeros = 1 + (unsigned) -NWholeDigits;
4420
4421 Str.push_back('0');
4422 Str.push_back('.');
4423 for (unsigned Z = 1; Z != NZeros; ++Z)
4424 Str.push_back('0');
4425 }
4426
4427 for (; I != NDigits; ++I)
4428 Str.push_back(buffer[NDigits-I-1]);
4429
4430 }
4431} // namespace
4432
4433void IEEEFloat::toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision,
4434 unsigned FormatMaxPadding, bool TruncateZero) const {
4435 switch (category) {
4436 case fcInfinity:
4437 if (isNegative())
4438 return append(Str, "-Inf");
4439 else
4440 return append(Str, "+Inf");
4441
4442 case fcNaN: return append(Str, "NaN");
4443
4444 case fcZero:
4445 if (isNegative())
4446 Str.push_back('-');
4447
4448 if (!FormatMaxPadding) {
4449 if (TruncateZero)
4450 append(Str, "0.0E+0");
4451 else {
4452 append(Str, "0.0");
4453 if (FormatPrecision > 1)
4454 Str.append(FormatPrecision - 1, '0');
4455 append(Str, "e+00");
4456 }
4457 } else {
4458 Str.push_back('0');
4459 }
4460 return;
4461
4462 case fcNormal:
4463 break;
4464 }
4465
4466 // Decompose the number into an APInt and an exponent.
4467 int exp = exponent - ((int) semantics->precision - 1);
4468 APInt significand(
4469 semantics->precision,
4470 ArrayRef(significandParts(), partCountForBits(semantics->precision)));
4471
4472 toStringImpl(Str, isNegative(), exp, significand, FormatPrecision,
4473 FormatMaxPadding, TruncateZero);
4474
4475}
4476
4478 if (!isFinite() || isZero())
4479 return INT_MIN;
4480
4481 const integerPart *Parts = significandParts();
4482 const int PartCount = partCountForBits(semantics->precision);
4483
4484 int PopCount = 0;
4485 for (int i = 0; i < PartCount; ++i) {
4486 PopCount += llvm::popcount(Parts[i]);
4487 if (PopCount > 1)
4488 return INT_MIN;
4489 }
4490
4491 if (exponent != semantics->minExponent)
4492 return exponent;
4493
4494 int CountrParts = 0;
4495 for (int i = 0; i < PartCount;
4496 ++i, CountrParts += APInt::APINT_BITS_PER_WORD) {
4497 if (Parts[i] != 0) {
4498 return exponent - semantics->precision + CountrParts +
4499 llvm::countr_zero(Parts[i]) + 1;
4500 }
4501 }
4502
4503 llvm_unreachable("didn't find the set bit");
4504}
4505
4507 if (!isNaN())
4508 return false;
4509 if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly ||
4510 semantics->nonFiniteBehavior == fltNonfiniteBehavior::FiniteOnly)
4511 return false;
4512
4513 // IEEE-754R 2008 6.2.1: A signaling NaN bit string should be encoded with the
4514 // first bit of the trailing significand being 0.
4515 return !APInt::tcExtractBit(significandParts(), semantics->precision - 2);
4516}
4517
4518/// IEEE-754R 2008 5.3.1: nextUp/nextDown.
4519///
4520/// *NOTE* since nextDown(x) = -nextUp(-x), we only implement nextUp with
4521/// appropriate sign switching before/after the computation.
4523 // If we are performing nextDown, swap sign so we have -x.
4524 if (nextDown)
4525 changeSign();
4526
4527 // Compute nextUp(x)
4528 opStatus result = opOK;
4529
4530 // Handle each float category separately.
4531 switch (category) {
4532 case fcInfinity:
4533 // nextUp(+inf) = +inf
4534 if (!isNegative())
4535 break;
4536 // nextUp(-inf) = -getLargest()
4537 makeLargest(true);
4538 break;
4539 case fcNaN:
4540 // IEEE-754R 2008 6.2 Par 2: nextUp(sNaN) = qNaN. Set Invalid flag.
4541 // IEEE-754R 2008 6.2: nextUp(qNaN) = qNaN. Must be identity so we do not
4542 // change the payload.
4543 if (isSignaling()) {
4544 result = opInvalidOp;
4545 // For consistency, propagate the sign of the sNaN to the qNaN.
4546 makeNaN(false, isNegative(), nullptr);
4547 }
4548 break;
4549 case fcZero:
4550 // nextUp(pm 0) = +getSmallest()
4551 makeSmallest(false);
4552 break;
4553 case fcNormal:
4554 // nextUp(-getSmallest()) = -0
4555 if (isSmallest() && isNegative()) {
4556 APInt::tcSet(significandParts(), 0, partCount());
4557 category = fcZero;
4558 exponent = 0;
4559 if (semantics->nanEncoding == fltNanEncoding::NegativeZero)
4560 sign = false;
4561 if (!semantics->hasZero)
4563 break;
4564 }
4565
4566 if (isLargest() && !isNegative()) {
4567 if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly) {
4568 // nextUp(getLargest()) == NAN
4569 makeNaN();
4570 break;
4571 } else if (semantics->nonFiniteBehavior ==
4573 // nextUp(getLargest()) == getLargest()
4574 break;
4575 } else {
4576 // nextUp(getLargest()) == INFINITY
4577 APInt::tcSet(significandParts(), 0, partCount());
4578 category = fcInfinity;
4579 exponent = semantics->maxExponent + 1;
4580 break;
4581 }
4582 }
4583
4584 // nextUp(normal) == normal + inc.
4585 if (isNegative()) {
4586 // If we are negative, we need to decrement the significand.
4587
4588 // We only cross a binade boundary that requires adjusting the exponent
4589 // if:
4590 // 1. exponent != semantics->minExponent. This implies we are not in the
4591 // smallest binade or are dealing with denormals.
4592 // 2. Our significand excluding the integral bit is all zeros.
4593 bool WillCrossBinadeBoundary =
4594 exponent != semantics->minExponent && isSignificandAllZeros();
4595
4596 // Decrement the significand.
4597 //
4598 // We always do this since:
4599 // 1. If we are dealing with a non-binade decrement, by definition we
4600 // just decrement the significand.
4601 // 2. If we are dealing with a normal -> normal binade decrement, since
4602 // we have an explicit integral bit the fact that all bits but the
4603 // integral bit are zero implies that subtracting one will yield a
4604 // significand with 0 integral bit and 1 in all other spots. Thus we
4605 // must just adjust the exponent and set the integral bit to 1.
4606 // 3. If we are dealing with a normal -> denormal binade decrement,
4607 // since we set the integral bit to 0 when we represent denormals, we
4608 // just decrement the significand.
4609 integerPart *Parts = significandParts();
4610 APInt::tcDecrement(Parts, partCount());
4611
4612 if (WillCrossBinadeBoundary) {
4613 // Our result is a normal number. Do the following:
4614 // 1. Set the integral bit to 1.
4615 // 2. Decrement the exponent.
4616 APInt::tcSetBit(Parts, semantics->precision - 1);
4617 exponent--;
4618 }
4619 } else {
4620 // If we are positive, we need to increment the significand.
4621
4622 // We only cross a binade boundary that requires adjusting the exponent if
4623 // the input is not a denormal and all of said input's significand bits
4624 // are set. If all of said conditions are true: clear the significand, set
4625 // the integral bit to 1, and increment the exponent. If we have a
4626 // denormal always increment since moving denormals and the numbers in the
4627 // smallest normal binade have the same exponent in our representation.
4628 // If there are only exponents, any increment always crosses the
4629 // BinadeBoundary.
4630 bool WillCrossBinadeBoundary = !APFloat::hasSignificand(*semantics) ||
4631 (!isDenormal() && isSignificandAllOnes());
4632
4633 if (WillCrossBinadeBoundary) {
4634 integerPart *Parts = significandParts();
4635 APInt::tcSet(Parts, 0, partCount());
4636 APInt::tcSetBit(Parts, semantics->precision - 1);
4637 assert(exponent != semantics->maxExponent &&
4638 "We can not increment an exponent beyond the maxExponent allowed"
4639 " by the given floating point semantics.");
4640 exponent++;
4641 } else {
4642 incrementSignificand();
4643 }
4644 }
4645 break;
4646 }
4647
4648 // If we are performing nextDown, swap sign so we have -nextUp(-x)
4649 if (nextDown)
4650 changeSign();
4651
4652 return result;
4653}
4654
4656 assert(isNaN() && "Can only be called on NaN values");
4657 // Number of bits in the payload, excluding the (maybe implied) integer bit.
4658 unsigned Bits = semantics->precision - 1;
4659 return APInt(Bits, ArrayRef(significandParts(), partCountForBits(Bits)));
4660}
4661
4662APFloatBase::ExponentType IEEEFloat::exponentNaN() const {
4663 return ::exponentNaN(*semantics);
4664}
4665
4666APFloatBase::ExponentType IEEEFloat::exponentInf() const {
4667 return ::exponentInf(*semantics);
4668}
4669
4670APFloatBase::ExponentType IEEEFloat::exponentZero() const {
4671 return ::exponentZero(*semantics);
4672}
4673
4674void IEEEFloat::makeInf(bool Negative) {
4675 if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::FiniteOnly)
4676 llvm_unreachable("This floating point format does not support Inf");
4677
4678 if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly) {
4679 // There is no Inf, so make NaN instead.
4680 makeNaN(false, Negative);
4681 return;
4682 }
4683 category = fcInfinity;
4684 sign = Negative;
4685 exponent = exponentInf();
4686 APInt::tcSet(significandParts(), 0, partCount());
4687}
4688
4689void IEEEFloat::makeZero(bool Negative) {
4690 if (!semantics->hasZero)
4691 llvm_unreachable("This floating point format does not support Zero");
4692
4693 category = fcZero;
4694 sign = Negative;
4695 if (semantics->nanEncoding == fltNanEncoding::NegativeZero) {
4696 // Merge negative zero to positive because 0b10000...000 is used for NaN
4697 sign = false;
4698 }
4699 exponent = exponentZero();
4700 APInt::tcSet(significandParts(), 0, partCount());
4701}
4702
4704 assert(isNaN());
4705 if (semantics->nonFiniteBehavior != fltNonfiniteBehavior::NanOnly)
4706 APInt::tcSetBit(significandParts(), semantics->precision - 2);
4707}
4708
4709int ilogb(const IEEEFloat &Arg) {
4710 if (Arg.isNaN())
4711 return APFloat::IEK_NaN;
4712 if (Arg.isZero())
4713 return APFloat::IEK_Zero;
4714 if (Arg.isInfinity())
4715 return APFloat::IEK_Inf;
4716 if (!Arg.isDenormal())
4717 return Arg.exponent;
4718
4719 IEEEFloat Normalized(Arg);
4720 int SignificandBits = Arg.getSemantics().precision - 1;
4721
4722 Normalized.exponent += SignificandBits;
4723 Normalized.normalize(APFloat::rmNearestTiesToEven, lfExactlyZero);
4724 return Normalized.exponent - SignificandBits;
4725}
4726
4728 auto MaxExp = X.getSemantics().maxExponent;
4729 auto MinExp = X.getSemantics().minExponent;
4730
4731 // If Exp is wildly out-of-scale, simply adding it to X.exponent will
4732 // overflow; clamp it to a safe range before adding, but ensure that the range
4733 // is large enough that the clamp does not change the result. The range we
4734 // need to support is the difference between the largest possible exponent and
4735 // the normalized exponent of half the smallest denormal.
4736
4737 int SignificandBits = X.getSemantics().precision - 1;
4738 int MaxIncrement = MaxExp - (MinExp - SignificandBits) + 1;
4739
4740 // Clamp to one past the range ends to let normalize handle overlflow.
4741 X.exponent += std::clamp(Exp, -MaxIncrement - 1, MaxIncrement);
4742 X.normalize(RoundingMode, lfExactlyZero);
4743 if (X.isNaN())
4744 X.makeQuiet();
4745 return X;
4746}
4747
4748IEEEFloat frexp(const IEEEFloat &Val, int &Exp, roundingMode RM) {
4749 Exp = ilogb(Val);
4750
4751 // Quiet signalling nans.
4752 if (Exp == APFloat::IEK_NaN) {
4753 IEEEFloat Quiet(Val);
4754 Quiet.makeQuiet();
4755 return Quiet;
4756 }
4757
4758 if (Exp == APFloat::IEK_Inf)
4759 return Val;
4760
4761 // 1 is added because frexp is defined to return a normalized fraction in
4762 // +/-[0.5, 1.0), rather than the usual +/-[1.0, 2.0).
4763 Exp = Exp == APFloat::IEK_Zero ? 0 : Exp + 1;
4764 return scalbn(Val, -Exp, RM);
4765}
4766
4768 : Semantics(&S),
4769 Floats(new APFloat[2]{APFloat(APFloatBase::semIEEEdouble),
4770 APFloat(APFloatBase::semIEEEdouble)}) {
4771 assert(Semantics == &APFloatBase::semPPCDoubleDouble);
4772}
4773
4775 : Semantics(&S), Floats(new APFloat[2]{
4776 APFloat(APFloatBase::semIEEEdouble, uninitialized),
4777 APFloat(APFloatBase::semIEEEdouble, uninitialized)}) {
4778 assert(Semantics == &APFloatBase::semPPCDoubleDouble);
4779}
4780
4782 : Semantics(&S),
4783 Floats(new APFloat[2]{APFloat(APFloatBase::semIEEEdouble, I),
4784 APFloat(APFloatBase::semIEEEdouble)}) {
4785 assert(Semantics == &APFloatBase::semPPCDoubleDouble);
4786}
4787
4789 : Semantics(&S),
4790 Floats(new APFloat[2]{
4791 APFloat(APFloatBase::semIEEEdouble, APInt(64, I.getRawData()[0])),
4792 APFloat(APFloatBase::semIEEEdouble, APInt(64, I.getRawData()[1]))}) {
4793 assert(Semantics == &APFloatBase::semPPCDoubleDouble);
4794}
4795
4797 APFloat &&Second)
4798 : Semantics(&S),
4799 Floats(new APFloat[2]{std::move(First), std::move(Second)}) {
4800 assert(Semantics == &APFloatBase::semPPCDoubleDouble);
4801 assert(&Floats[0].getSemantics() == &APFloatBase::semIEEEdouble);
4802 assert(&Floats[1].getSemantics() == &APFloatBase::semIEEEdouble);
4803}
4804
4806 : Semantics(RHS.Semantics),
4807 Floats(RHS.Floats ? new APFloat[2]{APFloat(RHS.Floats[0]),
4808 APFloat(RHS.Floats[1])}
4809 : nullptr) {
4810 assert(Semantics == &APFloatBase::semPPCDoubleDouble);
4811}
4812
4814 : Semantics(RHS.Semantics), Floats(RHS.Floats) {
4815 RHS.Semantics = &APFloatBase::semBogus;
4816 RHS.Floats = nullptr;
4817 assert(Semantics == &APFloatBase::semPPCDoubleDouble);
4818}
4819
4821 if (Semantics == RHS.Semantics && RHS.Floats) {
4822 Floats[0] = RHS.Floats[0];
4823 Floats[1] = RHS.Floats[1];
4824 } else if (this != &RHS) {
4825 this->~DoubleAPFloat();
4826 new (this) DoubleAPFloat(RHS);
4827 }
4828 return *this;
4829}
4830
4831// Returns a result such that:
4832// 1. abs(Lo) <= ulp(Hi)/2
4833// 2. Hi == RTNE(Hi + Lo)
4834// 3. Hi + Lo == X + Y
4835//
4836// Requires that log2(X) >= log2(Y).
4837static std::pair<APFloat, APFloat> fastTwoSum(APFloat X, APFloat Y) {
4838 if (!X.isFinite())
4839 return {X, APFloat::getZero(X.getSemantics(), /*Negative=*/false)};
4840 APFloat Hi = X + Y;
4841 APFloat Delta = Hi - X;
4842 APFloat Lo = Y - Delta;
4843 return {Hi, Lo};
4844}
4845
4846// Implement addition, subtraction, multiplication and division based on:
4847// "Software for Doubled-Precision Floating-Point Computations",
4848// by Seppo Linnainmaa, ACM TOMS vol 7 no 3, September 1981, pages 272-283.
4849APFloat::opStatus DoubleAPFloat::addImpl(const APFloat &a, const APFloat &aa,
4850 const APFloat &c, const APFloat &cc,
4851 roundingMode RM) {
4852 int Status = opOK;
4853 APFloat z = a;
4854 Status |= z.add(c, RM);
4855 if (!z.isFinite()) {
4856 if (!z.isInfinity()) {
4857 Floats[0] = std::move(z);
4858 Floats[1].makeZero(/* Neg = */ false);
4859 return (opStatus)Status;
4860 }
4861 Status = opOK;
4862 auto AComparedToC = a.compareAbsoluteValue(c);
4863 z = cc;
4864 Status |= z.add(aa, RM);
4865 if (AComparedToC == APFloat::cmpGreaterThan) {
4866 // z = cc + aa + c + a;
4867 Status |= z.add(c, RM);
4868 Status |= z.add(a, RM);
4869 } else {
4870 // z = cc + aa + a + c;
4871 Status |= z.add(a, RM);
4872 Status |= z.add(c, RM);
4873 }
4874 if (!z.isFinite()) {
4875 Floats[0] = std::move(z);
4876 Floats[1].makeZero(/* Neg = */ false);
4877 return (opStatus)Status;
4878 }
4879 Floats[0] = z;
4880 APFloat zz = aa;
4881 Status |= zz.add(cc, RM);
4882 if (AComparedToC == APFloat::cmpGreaterThan) {
4883 // Floats[1] = a - z + c + zz;
4884 Floats[1] = a;
4885 Status |= Floats[1].subtract(z, RM);
4886 Status |= Floats[1].add(c, RM);
4887 Status |= Floats[1].add(zz, RM);
4888 } else {
4889 // Floats[1] = c - z + a + zz;
4890 Floats[1] = c;
4891 Status |= Floats[1].subtract(z, RM);
4892 Status |= Floats[1].add(a, RM);
4893 Status |= Floats[1].add(zz, RM);
4894 }
4895 } else {
4896 // q = a - z;
4897 APFloat q = a;
4898 Status |= q.subtract(z, RM);
4899
4900 // zz = q + c + (a - (q + z)) + aa + cc;
4901 // Compute a - (q + z) as -((q + z) - a) to avoid temporary copies.
4902 auto zz = q;
4903 Status |= zz.add(c, RM);
4904 Status |= q.add(z, RM);
4905 Status |= q.subtract(a, RM);
4906 q.changeSign();
4907 Status |= zz.add(q, RM);
4908 Status |= zz.add(aa, RM);
4909 Status |= zz.add(cc, RM);
4910 if (zz.isZero() && !zz.isNegative()) {
4911 Floats[0] = std::move(z);
4912 Floats[1].makeZero(/* Neg = */ false);
4913 return opOK;
4914 }
4915 Floats[0] = z;
4916 Status |= Floats[0].add(zz, RM);
4917 if (!Floats[0].isFinite()) {
4918 Floats[1].makeZero(/* Neg = */ false);
4919 return (opStatus)Status;
4920 }
4921 Floats[1] = std::move(z);
4922 Status |= Floats[1].subtract(Floats[0], RM);
4923 Status |= Floats[1].add(zz, RM);
4924 }
4925 return (opStatus)Status;
4926}
4927
4928APFloat::opStatus DoubleAPFloat::addWithSpecial(const DoubleAPFloat &LHS,
4929 const DoubleAPFloat &RHS,
4930 DoubleAPFloat &Out,
4931 roundingMode RM) {
4932 if (LHS.getCategory() == fcNaN) {
4933 Out = LHS;
4934 return opOK;
4935 }
4936 if (RHS.getCategory() == fcNaN) {
4937 Out = RHS;
4938 return opOK;
4939 }
4940 if (LHS.getCategory() == fcZero) {
4941 Out = RHS;
4942 return opOK;
4943 }
4944 if (RHS.getCategory() == fcZero) {
4945 Out = LHS;
4946 return opOK;
4947 }
4948 if (LHS.getCategory() == fcInfinity && RHS.getCategory() == fcInfinity &&
4949 LHS.isNegative() != RHS.isNegative()) {
4950 Out.makeNaN(false, Out.isNegative(), nullptr);
4951 return opInvalidOp;
4952 }
4953 if (LHS.getCategory() == fcInfinity) {
4954 Out = LHS;
4955 return opOK;
4956 }
4957 if (RHS.getCategory() == fcInfinity) {
4958 Out = RHS;
4959 return opOK;
4960 }
4961 assert(LHS.getCategory() == fcNormal && RHS.getCategory() == fcNormal);
4962
4963 APFloat A(LHS.Floats[0]), AA(LHS.Floats[1]), C(RHS.Floats[0]),
4964 CC(RHS.Floats[1]);
4965 assert(&A.getSemantics() == &APFloatBase::semIEEEdouble);
4966 assert(&AA.getSemantics() == &APFloatBase::semIEEEdouble);
4967 assert(&C.getSemantics() == &APFloatBase::semIEEEdouble);
4968 assert(&CC.getSemantics() == &APFloatBase::semIEEEdouble);
4969 assert(&Out.Floats[0].getSemantics() == &APFloatBase::semIEEEdouble);
4970 assert(&Out.Floats[1].getSemantics() == &APFloatBase::semIEEEdouble);
4971 return Out.addImpl(A, AA, C, CC, RM);
4972}
4973
4975 roundingMode RM) {
4976 return addWithSpecial(*this, RHS, *this, RM);
4977}
4978
4980 roundingMode RM) {
4981 changeSign();
4982 auto Ret = add(RHS, RM);
4983 changeSign();
4984 return Ret;
4985}
4986
4989 const auto &LHS = *this;
4990 auto &Out = *this;
4991 /* Interesting observation: For special categories, finding the lowest
4992 common ancestor of the following layered graph gives the correct
4993 return category:
4994
4995 NaN
4996 / \
4997 Zero Inf
4998 \ /
4999 Normal
5000
5001 e.g. NaN * NaN = NaN
5002 Zero * Inf = NaN
5003 Normal * Zero = Zero
5004 Normal * Inf = Inf
5005 */
5006 if (LHS.getCategory() == fcNaN) {
5007 Out = LHS;
5008 return opOK;
5009 }
5010 if (RHS.getCategory() == fcNaN) {
5011 Out = RHS;
5012 return opOK;
5013 }
5014 if ((LHS.getCategory() == fcZero && RHS.getCategory() == fcInfinity) ||
5015 (LHS.getCategory() == fcInfinity && RHS.getCategory() == fcZero)) {
5016 Out.makeNaN(false, false, nullptr);
5017 return opOK;
5018 }
5019 if (LHS.getCategory() == fcZero || LHS.getCategory() == fcInfinity) {
5020 Out = LHS;
5021 return opOK;
5022 }
5023 if (RHS.getCategory() == fcZero || RHS.getCategory() == fcInfinity) {
5024 Out = RHS;
5025 return opOK;
5026 }
5027 assert(LHS.getCategory() == fcNormal && RHS.getCategory() == fcNormal &&
5028 "Special cases not handled exhaustively");
5029
5030 int Status = opOK;
5031 APFloat A = Floats[0], B = Floats[1], C = RHS.Floats[0], D = RHS.Floats[1];
5032 // t = a * c
5033 APFloat T = A;
5034 Status |= T.multiply(C, RM);
5035 if (!T.isFiniteNonZero()) {
5036 Floats[0] = std::move(T);
5037 Floats[1].makeZero(/* Neg = */ false);
5038 return (opStatus)Status;
5039 }
5040
5041 // tau = fmsub(a, c, t), that is -fmadd(-a, c, t).
5042 APFloat Tau = A;
5043 T.changeSign();
5044 Status |= Tau.fusedMultiplyAdd(C, T, RM);
5045 T.changeSign();
5046 {
5047 // v = a * d
5048 APFloat V = A;
5049 Status |= V.multiply(D, RM);
5050 // w = b * c
5051 APFloat W = B;
5052 Status |= W.multiply(C, RM);
5053 Status |= V.add(W, RM);
5054 // tau += v + w
5055 Status |= Tau.add(V, RM);
5056 }
5057 // u = t + tau
5058 APFloat U = T;
5059 Status |= U.add(Tau, RM);
5060
5061 Floats[0] = U;
5062 if (!U.isFinite()) {
5063 Floats[1].makeZero(/* Neg = */ false);
5064 } else {
5065 // Floats[1] = (t - u) + tau
5066 Status |= T.subtract(U, RM);
5067 Status |= T.add(Tau, RM);
5068 Floats[1] = std::move(T);
5069 }
5070 return (opStatus)Status;
5071}
5072
5075 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5076 "Unexpected Semantics");
5077 APFloat Tmp(APFloatBase::semPPCDoubleDoubleLegacy, bitcastToAPInt());
5078 auto Ret = Tmp.divide(
5079 APFloat(APFloatBase::semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt()), RM);
5080 *this = DoubleAPFloat(APFloatBase::semPPCDoubleDouble, Tmp.bitcastToAPInt());
5081 return Ret;
5082}
5083
5085 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5086 "Unexpected Semantics");
5087 APFloat Tmp(APFloatBase::semPPCDoubleDoubleLegacy, bitcastToAPInt());
5088 auto Ret = Tmp.remainder(
5089 APFloat(APFloatBase::semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt()));
5090 *this = DoubleAPFloat(APFloatBase::semPPCDoubleDouble, Tmp.bitcastToAPInt());
5091 return Ret;
5092}
5093
5095 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5096 "Unexpected Semantics");
5097 APFloat Tmp(APFloatBase::semPPCDoubleDoubleLegacy, bitcastToAPInt());
5098 auto Ret = Tmp.mod(
5099 APFloat(APFloatBase::semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt()));
5100 *this = DoubleAPFloat(APFloatBase::semPPCDoubleDouble, Tmp.bitcastToAPInt());
5101 return Ret;
5102}
5103
5106 const DoubleAPFloat &Addend,
5108 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5109 "Unexpected Semantics");
5110 APFloat Tmp(APFloatBase::semPPCDoubleDoubleLegacy, bitcastToAPInt());
5111 auto Ret = Tmp.fusedMultiplyAdd(
5112 APFloat(APFloatBase::semPPCDoubleDoubleLegacy,
5113 Multiplicand.bitcastToAPInt()),
5114 APFloat(APFloatBase::semPPCDoubleDoubleLegacy, Addend.bitcastToAPInt()),
5115 RM);
5116 *this = DoubleAPFloat(APFloatBase::semPPCDoubleDouble, Tmp.bitcastToAPInt());
5117 return Ret;
5118}
5119
5121 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5122 "Unexpected Semantics");
5123 const APFloat &Hi = getFirst();
5124 const APFloat &Lo = getSecond();
5125
5126 APFloat RoundedHi = Hi;
5127 const opStatus HiStatus = RoundedHi.roundToIntegral(RM);
5128
5129 // We can reduce the problem to just the high part if the input:
5130 // 1. Represents a non-finite value.
5131 // 2. Has a component which is zero.
5132 if (!Hi.isFiniteNonZero() || Lo.isZero()) {
5133 Floats[0] = std::move(RoundedHi);
5134 Floats[1].makeZero(/*Neg=*/false);
5135 return HiStatus;
5136 }
5137
5138 // Adjust `Rounded` in the direction of `TieBreaker` if `ToRound` was at a
5139 // halfway point.
5140 auto RoundToNearestHelper = [](APFloat ToRound, APFloat Rounded,
5141 APFloat TieBreaker) {
5142 // RoundingError tells us which direction we rounded:
5143 // - RoundingError > 0: we rounded up.
5144 // - RoundingError < 0: we rounded down.
5145 // Sterbenz' lemma ensures that RoundingError is exact.
5146 const APFloat RoundingError = Rounded - ToRound;
5147 if (TieBreaker.isNonZero() &&
5148 TieBreaker.isNegative() != RoundingError.isNegative() &&
5149 abs(RoundingError).isExactlyValue(0.5))
5150 Rounded.add(
5151 APFloat::getOne(Rounded.getSemantics(), TieBreaker.isNegative()),
5153 return Rounded;
5154 };
5155
5156 // Case 1: Hi is not an integer.
5157 // Special cases are for rounding modes that are sensitive to ties.
5158 if (RoundedHi != Hi) {
5159 // We need to consider the case where Hi was between two integers and the
5160 // rounding mode broke the tie when, in fact, Lo may have had a different
5161 // sign than Hi.
5162 if (RM == rmNearestTiesToAway || RM == rmNearestTiesToEven)
5163 RoundedHi = RoundToNearestHelper(Hi, RoundedHi, Lo);
5164
5165 Floats[0] = std::move(RoundedHi);
5166 Floats[1].makeZero(/*Neg=*/false);
5167 return HiStatus;
5168 }
5169
5170 // Case 2: Hi is an integer.
5171 // Special cases are for rounding modes which are rounding towards or away from zero.
5172 RoundingMode LoRoundingMode;
5173 if (RM == rmTowardZero)
5174 // When our input is positive, we want the Lo component rounded toward
5175 // negative infinity to get the smallest result magnitude. Likewise,
5176 // negative inputs want the Lo component rounded toward positive infinity.
5177 LoRoundingMode = isNegative() ? rmTowardPositive : rmTowardNegative;
5178 else
5179 LoRoundingMode = RM;
5180
5181 APFloat RoundedLo = Lo;
5182 const opStatus LoStatus = RoundedLo.roundToIntegral(LoRoundingMode);
5183 if (LoRoundingMode == rmNearestTiesToAway)
5184 // We need to consider the case where Lo was between two integers and the
5185 // rounding mode broke the tie when, in fact, Hi may have had a different
5186 // sign than Lo.
5187 RoundedLo = RoundToNearestHelper(Lo, RoundedLo, Hi);
5188
5189 // We must ensure that the final result has no overlap between the two APFloat values.
5190 std::tie(RoundedHi, RoundedLo) = fastTwoSum(RoundedHi, RoundedLo);
5191
5192 Floats[0] = std::move(RoundedHi);
5193 Floats[1] = std::move(RoundedLo);
5194 return LoStatus;
5195}
5196
5198 Floats[0].changeSign();
5199 Floats[1].changeSign();
5200}
5201
5204 // Compare absolute values of the high parts.
5205 const cmpResult HiPartCmp = Floats[0].compareAbsoluteValue(RHS.Floats[0]);
5206 if (HiPartCmp != cmpEqual)
5207 return HiPartCmp;
5208
5209 // Zero, regardless of sign, is equal.
5210 if (Floats[1].isZero() && RHS.Floats[1].isZero())
5211 return cmpEqual;
5212
5213 // At this point, |this->Hi| == |RHS.Hi|.
5214 // The magnitude is |Hi+Lo| which is Hi+|Lo| if signs of Hi and Lo are the
5215 // same, and Hi-|Lo| if signs are different.
5216 const bool ThisIsSubtractive =
5217 Floats[0].isNegative() != Floats[1].isNegative();
5218 const bool RHSIsSubtractive =
5219 RHS.Floats[0].isNegative() != RHS.Floats[1].isNegative();
5220
5221 // Case 1: The low part of 'this' is zero.
5222 if (Floats[1].isZero())
5223 // We are comparing |Hi| vs. |Hi| ± |RHS.Lo|.
5224 // If RHS is subtractive, its magnitude is smaller.
5225 // If RHS is additive, its magnitude is larger.
5226 return RHSIsSubtractive ? cmpGreaterThan : cmpLessThan;
5227
5228 // Case 2: The low part of 'RHS' is zero (and we know 'this' is not).
5229 if (RHS.Floats[1].isZero())
5230 // We are comparing |Hi| ± |This.Lo| vs. |Hi|.
5231 // If 'this' is subtractive, its magnitude is smaller.
5232 // If 'this' is additive, its magnitude is larger.
5233 return ThisIsSubtractive ? cmpLessThan : cmpGreaterThan;
5234
5235 // If their natures differ, the additive one is larger.
5236 if (ThisIsSubtractive != RHSIsSubtractive)
5237 return ThisIsSubtractive ? cmpLessThan : cmpGreaterThan;
5238
5239 // Case 3: Both are additive (Hi+|Lo|) or both are subtractive (Hi-|Lo|).
5240 // The comparison now depends on the magnitude of the low parts.
5241 const cmpResult LoPartCmp = Floats[1].compareAbsoluteValue(RHS.Floats[1]);
5242
5243 if (ThisIsSubtractive) {
5244 // Both are subtractive (Hi-|Lo|), so the comparison of |Lo| is inverted.
5245 if (LoPartCmp == cmpLessThan)
5246 return cmpGreaterThan;
5247 if (LoPartCmp == cmpGreaterThan)
5248 return cmpLessThan;
5249 }
5250
5251 // If additive, the comparison of |Lo| is direct.
5252 // If equal, they are equal.
5253 return LoPartCmp;
5254}
5255
5257 return Floats[0].getCategory();
5258}
5259
5260bool DoubleAPFloat::isNegative() const { return Floats[0].isNegative(); }
5261
5263 Floats[0].makeInf(Neg);
5264 Floats[1].makeZero(/* Neg = */ false);
5265}
5266
5268 Floats[0].makeZero(Neg);
5269 Floats[1].makeZero(/* Neg = */ false);
5270}
5271
5273 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5274 "Unexpected Semantics");
5275 Floats[0] =
5276 APFloat(APFloatBase::semIEEEdouble, APInt(64, 0x7fefffffffffffffull));
5277 Floats[1] =
5278 APFloat(APFloatBase::semIEEEdouble, APInt(64, 0x7c8ffffffffffffeull));
5279 if (Neg)
5280 changeSign();
5281}
5282
5284 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5285 "Unexpected Semantics");
5286 Floats[0].makeSmallest(Neg);
5287 Floats[1].makeZero(/* Neg = */ false);
5288}
5289
5291 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5292 "Unexpected Semantics");
5293 Floats[0] =
5294 APFloat(APFloatBase::semIEEEdouble, APInt(64, 0x0360000000000000ull));
5295 if (Neg)
5296 Floats[0].changeSign();
5297 Floats[1].makeZero(/* Neg = */ false);
5298}
5299
5300void DoubleAPFloat::makeNaN(bool SNaN, bool Neg, const APInt *fill) {
5301 Floats[0].makeNaN(SNaN, Neg, fill);
5302 Floats[1].makeZero(/* Neg = */ false);
5303}
5304
5306 auto Result = Floats[0].compare(RHS.Floats[0]);
5307 // |Float[0]| > |Float[1]|
5308 if (Result == APFloat::cmpEqual)
5309 return Floats[1].compare(RHS.Floats[1]);
5310 return Result;
5311}
5312
5314 return Floats[0].bitwiseIsEqual(RHS.Floats[0]) &&
5315 Floats[1].bitwiseIsEqual(RHS.Floats[1]);
5316}
5317
5319 if (Arg.Floats)
5320 return hash_combine(hash_value(Arg.Floats[0]), hash_value(Arg.Floats[1]));
5321 return hash_combine(Arg.Semantics);
5322}
5323
5325 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5326 "Unexpected Semantics");
5327 uint64_t Data[] = {
5328 Floats[0].bitcastToAPInt().getRawData()[0],
5329 Floats[1].bitcastToAPInt().getRawData()[0],
5330 };
5331 return APInt(128, Data);
5332}
5333
5335 roundingMode RM) {
5336 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5337 "Unexpected Semantics");
5338 APFloat Tmp(APFloatBase::semPPCDoubleDoubleLegacy);
5339 auto Ret = Tmp.convertFromString(S, RM);
5340 *this = DoubleAPFloat(APFloatBase::semPPCDoubleDouble, Tmp.bitcastToAPInt());
5341 return Ret;
5342}
5343
5344// The double-double lattice of values corresponds to numbers which obey:
5345// - abs(lo) <= 1/2 * ulp(hi)
5346// - roundTiesToEven(hi + lo) == hi
5347//
5348// nextUp must choose the smallest output > input that follows these rules.
5349// nexDown must choose the largest output < input that follows these rules.
5351 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5352 "Unexpected Semantics");
5353 // nextDown(x) = -nextUp(-x)
5354 if (nextDown) {
5355 changeSign();
5356 APFloat::opStatus Result = next(/*nextDown=*/false);
5357 changeSign();
5358 return Result;
5359 }
5360 switch (getCategory()) {
5361 case fcInfinity:
5362 // nextUp(+inf) = +inf
5363 // nextUp(-inf) = -getLargest()
5364 if (isNegative())
5365 makeLargest(true);
5366 return opOK;
5367
5368 case fcNaN:
5369 // IEEE-754R 2008 6.2 Par 2: nextUp(sNaN) = qNaN. Set Invalid flag.
5370 // IEEE-754R 2008 6.2: nextUp(qNaN) = qNaN. Must be identity so we do not
5371 // change the payload.
5372 if (getFirst().isSignaling()) {
5373 // For consistency, propagate the sign of the sNaN to the qNaN.
5374 makeNaN(false, isNegative(), nullptr);
5375 return opInvalidOp;
5376 }
5377 return opOK;
5378
5379 case fcZero:
5380 // nextUp(pm 0) = +getSmallest()
5381 makeSmallest(false);
5382 return opOK;
5383
5384 case fcNormal:
5385 break;
5386 }
5387
5388 const APFloat &HiOld = getFirst();
5389 const APFloat &LoOld = getSecond();
5390
5391 APFloat NextLo = LoOld;
5392 NextLo.next(/*nextDown=*/false);
5393
5394 // We want to admit values where:
5395 // 1. abs(Lo) <= ulp(Hi)/2
5396 // 2. Hi == RTNE(Hi + lo)
5397 auto InLattice = [](const APFloat &Hi, const APFloat &Lo) {
5398 return Hi + Lo == Hi;
5399 };
5400
5401 // Check if (HiOld, nextUp(LoOld) is in the lattice.
5402 if (InLattice(HiOld, NextLo)) {
5403 // Yes, the result is (HiOld, nextUp(LoOld)).
5404 Floats[1] = std::move(NextLo);
5405
5406 // TODO: Because we currently rely on semPPCDoubleDoubleLegacy, our maximum
5407 // value is defined to have exactly 106 bits of precision. This limitation
5408 // results in semPPCDoubleDouble being unable to reach its maximum canonical
5409 // value.
5410 DoubleAPFloat Largest{*Semantics, uninitialized};
5411 Largest.makeLargest(/*Neg=*/false);
5412 if (compare(Largest) == cmpGreaterThan)
5413 makeInf(/*Neg=*/false);
5414
5415 return opOK;
5416 }
5417
5418 // Now we need to handle the cases where (HiOld, nextUp(LoOld)) is not the
5419 // correct result. We know the new hi component will be nextUp(HiOld) but our
5420 // lattice rules make it a little ambiguous what the correct NextLo must be.
5421 APFloat NextHi = HiOld;
5422 NextHi.next(/*nextDown=*/false);
5423
5424 // nextUp(getLargest()) == INFINITY
5425 if (NextHi.isInfinity()) {
5426 makeInf(/*Neg=*/false);
5427 return opOK;
5428 }
5429
5430 // IEEE 754-2019 5.3.1:
5431 // "If x is the negative number of least magnitude in x's format, nextUp(x) is
5432 // -0."
5433 if (NextHi.isZero()) {
5434 makeZero(/*Neg=*/true);
5435 return opOK;
5436 }
5437
5438 // abs(NextLo) must be <= ulp(NextHi)/2. We want NextLo to be as close to
5439 // negative infinity as possible.
5440 NextLo = neg(scalbn(harrisonUlp(NextHi), -1, rmTowardZero));
5441 if (!InLattice(NextHi, NextLo))
5442 // RTNE may mean that Lo must be < ulp(NextHi) / 2 so we bump NextLo.
5443 NextLo.next(/*nextDown=*/false);
5444
5445 Floats[0] = std::move(NextHi);
5446 Floats[1] = std::move(NextLo);
5447
5448 return opOK;
5449}
5450
5451APFloat::opStatus DoubleAPFloat::convertToSignExtendedInteger(
5452 MutableArrayRef<integerPart> Input, unsigned int Width, bool IsSigned,
5453 roundingMode RM, bool *IsExact) const {
5454 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5455 "Unexpected Semantics");
5456
5457 // If Hi is not finite, or Lo is zero, the value is entirely represented
5458 // by Hi. Delegate to the simpler single-APFloat conversion.
5459 if (!getFirst().isFiniteNonZero() || getSecond().isZero())
5460 return getFirst().convertToInteger(Input, Width, IsSigned, RM, IsExact);
5461
5462 // First, round the full double-double value to an integral value. This
5463 // simplifies the rest of the function, as we no longer need to consider
5464 // fractional parts.
5465 *IsExact = false;
5466 DoubleAPFloat Integral = *this;
5467 const opStatus RoundStatus = Integral.roundToIntegral(RM);
5468 if (RoundStatus == opInvalidOp)
5469 return opInvalidOp;
5470 const APFloat &IntegralHi = Integral.getFirst();
5471 const APFloat &IntegralLo = Integral.getSecond();
5472
5473 // If rounding results in either component being zero, the sum is trivial.
5474 // Delegate to the simpler single-APFloat conversion.
5475 bool HiIsExact;
5476 if (IntegralHi.isZero() || IntegralLo.isZero()) {
5477 const opStatus HiStatus =
5478 IntegralHi.convertToInteger(Input, Width, IsSigned, RM, &HiIsExact);
5479 // The conversion from an integer-valued float to an APInt may fail if the
5480 // result would be out of range. Regardless, taking this path is only
5481 // possible if rounding occurred during the initial `roundToIntegral`.
5482 return HiStatus == opOK ? opInexact : HiStatus;
5483 }
5484
5485 // A negative number cannot be represented by an unsigned integer.
5486 // Since a double-double is canonical, if Hi is negative, the sum is negative.
5487 if (!IsSigned && IntegralHi.isNegative())
5488 return opInvalidOp;
5489
5490 // Handle the special boundary case where |Hi| is exactly the power of two
5491 // that marks the edge of the integer's range (e.g., 2^63 for int64_t). In
5492 // this situation, Hi itself won't fit, but the sum Hi + Lo might.
5493 // `PositiveOverflowWidth` is the bit number for this boundary (N-1 for
5494 // signed, N for unsigned).
5495 bool LoIsExact;
5496 const int HiExactLog2 = IntegralHi.getExactLog2Abs();
5497 const unsigned PositiveOverflowWidth = IsSigned ? Width - 1 : Width;
5498 if (HiExactLog2 >= 0 &&
5499 static_cast<unsigned>(HiExactLog2) == PositiveOverflowWidth) {
5500 // If Hi and Lo have the same sign, |Hi + Lo| > |Hi|, so the sum is
5501 // guaranteed to overflow. E.g., for uint128_t, (2^128, 1) overflows.
5502 if (IntegralHi.isNegative() == IntegralLo.isNegative())
5503 return opInvalidOp;
5504
5505 // If the signs differ, the sum will fit. We can compute the result using
5506 // properties of two's complement arithmetic without a wide intermediate
5507 // integer. E.g., for uint128_t, (2^128, -1) should be 2^128 - 1.
5508 const opStatus LoStatus = IntegralLo.convertToInteger(
5509 Input, Width, /*IsSigned=*/true, RM, &LoIsExact);
5510 if (LoStatus == opInvalidOp)
5511 return opInvalidOp;
5512
5513 // Adjust the bit pattern of Lo to account for Hi's value:
5514 // - For unsigned (Hi=2^Width): `2^Width + Lo` in `Width`-bit
5515 // arithmetic is equivalent to just `Lo`. The conversion of `Lo` above
5516 // already produced the correct final bit pattern.
5517 // - For signed (Hi=2^(Width-1)): The sum `2^(Width-1) + Lo` (where Lo<0)
5518 // can be computed by taking the two's complement pattern for `Lo` and
5519 // clearing the sign bit.
5520 if (IsSigned && !IntegralHi.isNegative())
5521 APInt::tcClearBit(Input.data(), PositiveOverflowWidth);
5522 *IsExact = RoundStatus == opOK;
5523 return RoundStatus;
5524 }
5525
5526 // Convert Hi into an integer. This may not fit but that is OK: we know that
5527 // Hi + Lo would not fit either in this situation.
5528 const opStatus HiStatus = IntegralHi.convertToInteger(
5529 Input, Width, IsSigned, rmTowardZero, &HiIsExact);
5530 if (HiStatus == opInvalidOp)
5531 return HiStatus;
5532
5533 // Convert Lo into a temporary integer of the same width.
5534 APSInt LoResult{Width, /*isUnsigned=*/!IsSigned};
5535 const opStatus LoStatus =
5536 IntegralLo.convertToInteger(LoResult, rmTowardZero, &LoIsExact);
5537 if (LoStatus == opInvalidOp)
5538 return LoStatus;
5539
5540 // Add Lo to Hi. This addition is guaranteed not to overflow because of the
5541 // double-double canonicalization rule (`|Lo| <= ulp(Hi)/2`). The only case
5542 // where the sum could cross the integer type's boundary is when Hi is a
5543 // power of two, which is handled by the special case block above.
5544 APInt::tcAdd(Input.data(), LoResult.getRawData(), /*carry=*/0, Input.size());
5545
5546 *IsExact = RoundStatus == opOK;
5547 return RoundStatus;
5548}
5549
5552 unsigned int Width, bool IsSigned,
5553 roundingMode RM, bool *IsExact) const {
5554 opStatus FS =
5555 convertToSignExtendedInteger(Input, Width, IsSigned, RM, IsExact);
5556
5557 if (FS == opInvalidOp) {
5558 const unsigned DstPartsCount = partCountForBits(Width);
5559 assert(DstPartsCount <= Input.size() && "Integer too big");
5560
5561 unsigned Bits;
5562 if (getCategory() == fcNaN)
5563 Bits = 0;
5564 else if (isNegative())
5565 Bits = IsSigned;
5566 else
5567 Bits = Width - IsSigned;
5568
5569 tcSetLeastSignificantBits(Input.data(), DstPartsCount, Bits);
5570 if (isNegative() && IsSigned)
5571 APInt::tcShiftLeft(Input.data(), DstPartsCount, Width - 1);
5572 }
5573
5574 return FS;
5575}
5576
5577APFloat::opStatus DoubleAPFloat::handleOverflow(roundingMode RM) {
5578 switch (RM) {
5580 makeLargest(/*Neg=*/isNegative());
5581 break;
5583 if (isNegative())
5584 makeInf(/*Neg=*/true);
5585 else
5586 makeLargest(/*Neg=*/false);
5587 break;
5589 if (isNegative())
5590 makeLargest(/*Neg=*/true);
5591 else
5592 makeInf(/*Neg=*/false);
5593 break;
5596 makeInf(/*Neg=*/isNegative());
5597 break;
5598 default:
5599 llvm_unreachable("Invalid rounding mode found");
5600 }
5601 opStatus S = opInexact;
5602 if (!getFirst().isFinite())
5603 S = static_cast<opStatus>(S | opOverflow);
5604 return S;
5605}
5606
5607APFloat::opStatus DoubleAPFloat::convertFromUnsignedParts(
5608 const integerPart *Src, unsigned int SrcCount, roundingMode RM) {
5609 // Find the most significant bit of the source integer. APInt::tcMSB returns
5610 // UINT_MAX for a zero value.
5611 const unsigned SrcMSB = APInt::tcMSB(Src, SrcCount);
5612 if (SrcMSB == UINT_MAX) {
5613 // The source integer is 0.
5614 makeZero(/*Neg=*/false);
5615 return opOK;
5616 }
5617
5618 // Create a minimally-sized APInt to represent the source value.
5619 const unsigned SrcBitWidth = SrcMSB + 1;
5620 APSInt SrcInt{APInt{/*numBits=*/SrcBitWidth, ArrayRef(Src, SrcCount)},
5621 /*isUnsigned=*/true};
5622
5623 // Stage 1: Initial Approximation.
5624 // Convert the source integer SrcInt to the Hi part of the DoubleAPFloat.
5625 // We use round-to-nearest because it minimizes the initial error, which is
5626 // crucial for the subsequent steps.
5628 Hi.convertFromAPInt(SrcInt, /*IsSigned=*/false, rmNearestTiesToEven);
5629
5630 // If the first approximation already overflows, the number is too large.
5631 // NOTE: The underlying semantics are *more* conservative when choosing to
5632 // overflow because their notion of ULP is much larger. As such, it is always
5633 // safe to overflow at the DoubleAPFloat level if the APFloat overflows.
5634 if (!Hi.isFinite())
5635 return handleOverflow(RM);
5636
5637 // Stage 2: Exact Error Calculation.
5638 // Calculate the exact error of the first approximation: Error = SrcInt - Hi.
5639 // This is done by converting Hi back to an integer and subtracting it from
5640 // the original source.
5641 bool HiAsIntIsExact;
5642 // Create an integer representation of Hi. Its width is determined by the
5643 // exponent of Hi, ensuring it's just large enough. This width can exceed
5644 // SrcBitWidth if the conversion to Hi rounded up to a power of two.
5645 // accurately when converted back to an integer.
5646 APSInt HiAsInt{static_cast<uint32_t>(ilogb(Hi) + 1), /*isUnsigned=*/true};
5647 Hi.convertToInteger(HiAsInt, rmNearestTiesToEven, &HiAsIntIsExact);
5648 const APInt Error = SrcInt.zext(HiAsInt.getBitWidth()) - HiAsInt;
5649
5650 // Stage 3: Error Approximation and Rounding.
5651 // Convert the integer error into the Lo part of the DoubleAPFloat. This step
5652 // captures the remainder of the original number. The rounding mode for this
5653 // conversion (LoRM) may need to be adjusted from the user-requested RM to
5654 // ensure the final sum (Hi + Lo) rounds correctly.
5655 roundingMode LoRM = RM;
5656 // Adjustments are only necessary when the initial approximation Hi was an
5657 // overestimate, making the Error negative.
5658 if (Error.isNegative()) {
5659 if (RM == rmNearestTiesToAway) {
5660 // For rmNearestTiesToAway, a tie should round away from zero. Since
5661 // SrcInt is positive, this means rounding toward +infinity.
5662 // A standard conversion of a negative Error would round ties toward
5663 // -infinity, causing the final sum Hi + Lo to be smaller. To
5664 // counteract this, we detect the tie case and override the rounding
5665 // mode for Lo to rmTowardPositive.
5666 const unsigned ErrorActiveBits = Error.getSignificantBits() - 1;
5667 const unsigned LoPrecision = getSecond().getSemantics().precision;
5668 if (ErrorActiveBits > LoPrecision) {
5669 const unsigned RoundingBoundary = ErrorActiveBits - LoPrecision;
5670 // A tie occurs when the bits to be truncated are of the form 100...0.
5671 // This is detected by checking if the number of trailing zeros is
5672 // exactly one less than the number of bits being truncated.
5673 if (Error.countTrailingZeros() == RoundingBoundary - 1)
5674 LoRM = rmTowardPositive;
5675 }
5676 } else if (RM == rmTowardZero) {
5677 // For rmTowardZero, the final positive result must be truncated (rounded
5678 // down). When Hi is an overestimate, Error is negative. A standard
5679 // rmTowardZero conversion of Error would make it *less* negative,
5680 // effectively rounding the final sum Hi + Lo *up*. To ensure the sum
5681 // rounds down correctly, we force Lo to round toward -infinity.
5682 LoRM = rmTowardNegative;
5683 }
5684 }
5685
5687 opStatus Status = Lo.convertFromAPInt(Error, /*IsSigned=*/true, LoRM);
5688
5689 // Renormalize the pair (Hi, Lo) into a canonical DoubleAPFloat form where the
5690 // components do not overlap. fastTwoSum performs this operation.
5691 std::tie(Hi, Lo) = fastTwoSum(Hi, Lo);
5692 Floats[0] = std::move(Hi);
5693 Floats[1] = std::move(Lo);
5694
5695 // A final check for overflow is needed because fastTwoSum can cause a
5696 // carry-out from Lo that pushes Hi to infinity.
5697 if (!getFirst().isFinite())
5698 return handleOverflow(RM);
5699
5700 // The largest DoubleAPFloat must be canonical. Values which are larger are
5701 // not canonical and are equivalent to overflow.
5702 if (getFirst().isFiniteNonZero() && Floats[0].isLargest()) {
5703 DoubleAPFloat Largest{*Semantics};
5704 Largest.makeLargest(/*Neg=*/false);
5705 if (compare(Largest) == APFloat::cmpGreaterThan)
5706 return handleOverflow(RM);
5707 }
5708
5709 // The final status of the operation is determined by the conversion of the
5710 // error term. If Lo could represent Error exactly, the entire conversion
5711 // is exact. Otherwise, it's inexact.
5712 return Status;
5713}
5714
5716 bool IsSigned,
5717 roundingMode RM) {
5718 const bool NegateInput = IsSigned && Input.isNegative();
5719 APInt API = Input;
5720 if (NegateInput)
5721 API.negate();
5722
5724 convertFromUnsignedParts(API.getRawData(), API.getNumWords(), RM);
5725 if (NegateInput)
5726 changeSign();
5727 return Status;
5728}
5729
5731 unsigned int HexDigits,
5732 bool UpperCase,
5733 roundingMode RM) const {
5734 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5735 "Unexpected Semantics");
5736 return APFloat(APFloatBase::semPPCDoubleDoubleLegacy, bitcastToAPInt())
5737 .convertToHexString(DST, HexDigits, UpperCase, RM);
5738}
5739
5741 return getCategory() == fcNormal &&
5742 (Floats[0].isDenormal() || Floats[1].isDenormal() ||
5743 // (double)(Hi + Lo) == Hi defines a normal number.
5744 Floats[0] != Floats[0] + Floats[1]);
5745}
5746
5748 if (getCategory() != fcNormal)
5749 return false;
5750 DoubleAPFloat Tmp(*this);
5751 Tmp.makeSmallest(this->isNegative());
5752 return Tmp.compare(*this) == cmpEqual;
5753}
5754
5756 if (getCategory() != fcNormal)
5757 return false;
5758
5759 DoubleAPFloat Tmp(*this);
5761 return Tmp.compare(*this) == cmpEqual;
5762}
5763
5765 if (getCategory() != fcNormal)
5766 return false;
5767 DoubleAPFloat Tmp(*this);
5768 Tmp.makeLargest(this->isNegative());
5769 return Tmp.compare(*this) == cmpEqual;
5770}
5771
5773 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5774 "Unexpected Semantics");
5775 return Floats[0].isInteger() && Floats[1].isInteger();
5776}
5777
5779 unsigned FormatPrecision,
5780 unsigned FormatMaxPadding,
5781 bool TruncateZero) const {
5782 assert(Semantics == &APFloatBase::semPPCDoubleDouble &&
5783 "Unexpected Semantics");
5784 APFloat(APFloatBase::semPPCDoubleDoubleLegacy, bitcastToAPInt())
5785 .toString(Str, FormatPrecision, FormatMaxPadding, TruncateZero);
5786}
5787
5789 // In order for Hi + Lo to be a power of two, the following must be true:
5790 // 1. Hi must be a power of two.
5791 // 2. Lo must be zero.
5792 if (getSecond().isNonZero())
5793 return INT_MIN;
5794 return getFirst().getExactLog2Abs();
5795}
5796
5797int ilogb(const DoubleAPFloat &Arg) {
5798 const APFloat &Hi = Arg.getFirst();
5799 const APFloat &Lo = Arg.getSecond();
5800 int IlogbResult = ilogb(Hi);
5801 // Zero and non-finite values can delegate to ilogb(Hi).
5802 if (Arg.getCategory() != fcNormal)
5803 return IlogbResult;
5804 // If Lo can't change the binade, we can delegate to ilogb(Hi).
5805 if (Lo.isZero() || Hi.isNegative() == Lo.isNegative())
5806 return IlogbResult;
5807 if (Hi.getExactLog2Abs() == INT_MIN)
5808 return IlogbResult;
5809 // Numbers of the form 2^a - 2^b or -2^a + 2^b are almost powers of two but
5810 // get nudged out of the binade by the low component.
5811 return IlogbResult - 1;
5812}
5813
5816 assert(Arg.Semantics == &APFloatBase::PPCDoubleDouble() &&
5817 "Unexpected Semantics");
5819 scalbn(Arg.Floats[0], Exp, RM),
5820 scalbn(Arg.Floats[1], Exp, RM));
5821}
5822
5823DoubleAPFloat frexp(const DoubleAPFloat &Arg, int &Exp,
5825 assert(Arg.Semantics == &APFloatBase::PPCDoubleDouble() &&
5826 "Unexpected Semantics");
5827
5828 // Get the unbiased exponent e of the number, where |Arg| = m * 2^e for m in
5829 // [1.0, 2.0).
5830 Exp = ilogb(Arg);
5831
5832 // For NaNs, quiet any signaling NaN and return the result, as per standard
5833 // practice.
5834 if (Exp == APFloat::IEK_NaN) {
5835 DoubleAPFloat Quiet{Arg};
5836 Quiet.getFirst() = Quiet.getFirst().makeQuiet();
5837 return Quiet;
5838 }
5839
5840 // For infinity, return it unchanged. The exponent remains IEK_Inf.
5841 if (Exp == APFloat::IEK_Inf)
5842 return Arg;
5843
5844 // For zero, the fraction is zero and the standard requires the exponent be 0.
5845 if (Exp == APFloat::IEK_Zero) {
5846 Exp = 0;
5847 return Arg;
5848 }
5849
5850 const APFloat &Hi = Arg.getFirst();
5851 const APFloat &Lo = Arg.getSecond();
5852
5853 // frexp requires the fraction's absolute value to be in [0.5, 1.0).
5854 // ilogb provides an exponent for an absolute value in [1.0, 2.0).
5855 // Increment the exponent to ensure the fraction is in the correct range.
5856 ++Exp;
5857
5858 const bool SignsDisagree = Hi.isNegative() != Lo.isNegative();
5859 APFloat Second = Lo;
5860 if (Arg.getCategory() == APFloat::fcNormal && Lo.isFiniteNonZero()) {
5861 roundingMode LoRoundingMode;
5862 // The interpretation of rmTowardZero depends on the sign of the combined
5863 // Arg rather than the sign of the component.
5864 if (RM == rmTowardZero)
5865 LoRoundingMode = Arg.isNegative() ? rmTowardPositive : rmTowardNegative;
5866 // For rmNearestTiesToAway, we face a similar problem. If signs disagree,
5867 // Lo is a correction *toward* zero relative to Hi. Rounding Lo
5868 // "away from zero" based on its own sign would move the value in the
5869 // wrong direction. As a safe proxy, we use rmNearestTiesToEven, which is
5870 // direction-agnostic. We only need to bother with this if Lo is scaled
5871 // down.
5872 else if (RM == rmNearestTiesToAway && SignsDisagree && Exp > 0)
5873 LoRoundingMode = rmNearestTiesToEven;
5874 else
5875 LoRoundingMode = RM;
5876 Second = scalbn(Lo, -Exp, LoRoundingMode);
5877 // The rmNearestTiesToEven proxy is correct most of the time, but it
5878 // differs from rmNearestTiesToAway when the scaled value of Lo is an
5879 // exact midpoint.
5880 // NOTE: This is morally equivalent to roundTiesTowardZero.
5881 if (RM == rmNearestTiesToAway && LoRoundingMode == rmNearestTiesToEven) {
5882 // Re-scale the result back to check if rounding occurred.
5883 const APFloat RecomposedLo = scalbn(Second, Exp, rmNearestTiesToEven);
5884 if (RecomposedLo != Lo) {
5885 // RoundingError tells us which direction we rounded:
5886 // - RoundingError > 0: we rounded up.
5887 // - RoundingError < 0: we down up.
5888 const APFloat RoundingError = RecomposedLo - Lo;
5889 // Determine if scalbn(Lo, -Exp) landed exactly on a midpoint.
5890 // We do this by checking if the absolute rounding error is exactly
5891 // half a ULP of the result.
5892 const APFloat UlpOfSecond = harrisonUlp(Second);
5893 const APFloat ScaledUlpOfSecond =
5894 scalbn(UlpOfSecond, Exp - 1, rmNearestTiesToEven);
5895 const bool IsMidpoint = abs(RoundingError) == ScaledUlpOfSecond;
5896 const bool RoundedLoAway =
5897 Second.isNegative() == RoundingError.isNegative();
5898 // The sign of Hi and Lo disagree and we rounded Lo away: we must
5899 // decrease the magnitude of Second to increase the magnitude
5900 // First+Second.
5901 if (IsMidpoint && RoundedLoAway)
5902 Second.next(/*nextDown=*/!Second.isNegative());
5903 }
5904 }
5905 // Handle a tricky edge case where Arg is slightly less than a power of two
5906 // (e.g., Arg = 2^k - epsilon). In this situation:
5907 // 1. Hi is 2^k, and Lo is a small negative value -epsilon.
5908 // 2. ilogb(Arg) correctly returns k-1.
5909 // 3. Our initial Exp becomes (k-1) + 1 = k.
5910 // 4. Scaling Hi (2^k) by 2^-k would yield a magnitude of 1.0 and
5911 // scaling Lo by 2^-k would yield zero. This would make the result 1.0
5912 // which is an invalid fraction, as the required interval is [0.5, 1.0).
5913 // We detect this specific case by checking if Hi is a power of two and if
5914 // the scaled Lo underflowed to zero. The fix: Increment Exp to k+1. This
5915 // adjusts the scale factor, causing Hi to be scaled to 0.5, which is a
5916 // valid fraction.
5917 if (Second.isZero() && SignsDisagree && Hi.getExactLog2Abs() != INT_MIN)
5918 ++Exp;
5919 }
5920
5921 APFloat First = scalbn(Hi, -Exp, RM);
5923 std::move(Second));
5924}
5925
5926APInt DoubleAPFloat::getNaNPayload() const { return Floats[0].getNaNPayload(); }
5927} // namespace detail
5928
5929APFloat::Storage::Storage(IEEEFloat F, const fltSemantics &Semantics) {
5930 if (usesLayout<IEEEFloat>(Semantics)) {
5931 new (&IEEE) IEEEFloat(std::move(F));
5932 return;
5933 }
5934 if (usesLayout<DoubleAPFloat>(Semantics)) {
5935 const fltSemantics& S = F.getSemantics();
5936 new (&Double) DoubleAPFloat(Semantics, APFloat(std::move(F), S),
5938 return;
5939 }
5940 llvm_unreachable("Unexpected semantics");
5941}
5942
5947
5948hash_code hash_value(const APFloat &Arg) {
5949 if (APFloat::usesLayout<detail::IEEEFloat>(Arg.getSemantics()))
5950 return hash_value(Arg.U.IEEE);
5951 if (APFloat::usesLayout<detail::DoubleAPFloat>(Arg.getSemantics()))
5952 return hash_value(Arg.U.Double);
5953 llvm_unreachable("Unexpected semantics");
5954}
5955
5957 : APFloat(Semantics) {
5958 auto StatusOrErr = convertFromString(S, rmNearestTiesToEven);
5959 assert(StatusOrErr && "Invalid floating point representation");
5960 consumeError(StatusOrErr.takeError());
5961}
5962
5964 if (isZero())
5965 return isNegative() ? fcNegZero : fcPosZero;
5966 if (isNormal())
5967 return isNegative() ? fcNegNormal : fcPosNormal;
5968 if (isDenormal())
5970 if (isInfinity())
5971 return isNegative() ? fcNegInf : fcPosInf;
5972 assert(isNaN() && "Other class of FP constant");
5973 return isSignaling() ? fcSNan : fcQNan;
5974}
5975
5976bool APFloat::getExactInverse(APFloat *Inv) const {
5977 // Only finite, non-zero numbers can have a useful, representable inverse.
5978 // This check filters out +/- zero, +/- infinity, and NaN.
5979 if (!isFiniteNonZero())
5980 return false;
5981
5982 // Historically, this function rejects subnormal inputs. One reason why this
5983 // might be important is that subnormals may behave differently under FTZ/DAZ
5984 // runtime behavior.
5985 if (isDenormal())
5986 return false;
5987
5988 // A number has an exact, representable inverse if and only if it is a power
5989 // of two.
5990 //
5991 // Mathematical Rationale:
5992 // 1. A binary floating-point number x is a dyadic rational, meaning it can
5993 // be written as x = M / 2^k for integers M (the significand) and k.
5994 // 2. The inverse is 1/x = 2^k / M.
5995 // 3. For 1/x to also be a dyadic rational (and thus exactly representable
5996 // in binary), its denominator M must also be a power of two.
5997 // Let's say M = 2^m.
5998 // 4. Substituting this back into the formula for x, we get
5999 // x = (2^m) / (2^k) = 2^(m-k).
6000 //
6001 // This proves that x must be a power of two.
6002
6003 // getExactLog2Abs() returns the integer exponent if the number is a power of
6004 // two or INT_MIN if it is not.
6005 const int Exp = getExactLog2Abs();
6006 if (Exp == INT_MIN)
6007 return false;
6008
6009 // The inverse of +/- 2^Exp is +/- 2^(-Exp). We can compute this by
6010 // scaling 1.0 by the negated exponent.
6011 APFloat Reciprocal =
6012 scalbn(APFloat::getOne(getSemantics(), /*Negative=*/isNegative()), -Exp,
6013 rmTowardZero);
6014
6015 // scalbn might round if the resulting exponent -Exp is outside the
6016 // representable range, causing overflow (to infinity) or underflow. We
6017 // must verify that the result is still the exact power of two we expect.
6018 if (Reciprocal.getExactLog2Abs() != -Exp)
6019 return false;
6020
6021 // Avoid multiplication with a subnormal, it is not safe on all platforms and
6022 // may be slower than a normal division.
6023 if (Reciprocal.isDenormal())
6024 return false;
6025
6026 assert(Reciprocal.isFiniteNonZero());
6027
6028 if (Inv)
6029 *Inv = std::move(Reciprocal);
6030
6031 return true;
6032}
6033
6035 roundingMode RM, bool *losesInfo) {
6036 if (&getSemantics() == &ToSemantics) {
6037 *losesInfo = false;
6038 return opOK;
6039 }
6040 if (usesLayout<IEEEFloat>(getSemantics()) &&
6041 usesLayout<IEEEFloat>(ToSemantics))
6042 return U.IEEE.convert(ToSemantics, RM, losesInfo);
6043 if (usesLayout<IEEEFloat>(getSemantics()) &&
6044 usesLayout<DoubleAPFloat>(ToSemantics)) {
6045 assert(&ToSemantics == &APFloatBase::semPPCDoubleDouble);
6046 auto Ret =
6047 U.IEEE.convert(APFloatBase::semPPCDoubleDoubleLegacy, RM, losesInfo);
6048 *this = APFloat(ToSemantics, U.IEEE.bitcastToAPInt());
6049 return Ret;
6050 }
6051 if (usesLayout<DoubleAPFloat>(getSemantics()) &&
6052 usesLayout<IEEEFloat>(ToSemantics)) {
6053 auto Ret = getIEEE().convert(ToSemantics, RM, losesInfo);
6054 *this = APFloat(std::move(getIEEE()), ToSemantics);
6055 return Ret;
6056 }
6057 llvm_unreachable("Unexpected semantics");
6058}
6059
6063
6065 SmallVector<char, 16> Buffer;
6066 toString(Buffer);
6067 OS << Buffer;
6068}
6069
6070#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
6072 print(dbgs());
6073 dbgs() << '\n';
6074}
6075#endif
6076
6078 NID.Add(bitcastToAPInt());
6079}
6080
6082 roundingMode rounding_mode,
6083 bool *isExact) const {
6084 unsigned bitWidth = result.getBitWidth();
6085 SmallVector<uint64_t, 4> parts(result.getNumWords());
6086 opStatus status = convertToInteger(parts, bitWidth, result.isSigned(),
6087 rounding_mode, isExact);
6088 // Keeps the original signed-ness.
6089 result = APInt(bitWidth, parts);
6090 return status;
6091}
6092
6094 if (&getSemantics() == &APFloatBase::semIEEEdouble)
6095 return getIEEE().convertToDouble();
6096 assert(isRepresentableBy(getSemantics(), semIEEEdouble) &&
6097 "Float semantics is not representable by IEEEdouble");
6098 APFloat Temp = *this;
6099 bool LosesInfo;
6100 [[maybe_unused]] opStatus St =
6101 Temp.convert(APFloatBase::semIEEEdouble, rmNearestTiesToEven, &LosesInfo);
6102 assert(!(St & opInexact) && !LosesInfo && "Unexpected imprecision");
6103 return Temp.getIEEE().convertToDouble();
6104}
6105
6106#ifdef HAS_IEE754_FLOAT128
6107float128 APFloat::convertToQuad() const {
6108 if (&getSemantics() == &APFloatBase::semIEEEquad)
6109 return getIEEE().convertToQuad();
6110 assert(isRepresentableBy(getSemantics(), semIEEEquad) &&
6111 "Float semantics is not representable by IEEEquad");
6112 APFloat Temp = *this;
6113 bool LosesInfo;
6114 [[maybe_unused]] opStatus St =
6115 Temp.convert(APFloatBase::semIEEEquad, rmNearestTiesToEven, &LosesInfo);
6116 assert(!(St & opInexact) && !LosesInfo && "Unexpected imprecision");
6117 return Temp.getIEEE().convertToQuad();
6118}
6119#endif
6120
6122 if (&getSemantics() == &APFloatBase::semIEEEsingle)
6123 return getIEEE().convertToFloat();
6124 assert(isRepresentableBy(getSemantics(), semIEEEsingle) &&
6125 "Float semantics is not representable by IEEEsingle");
6126 APFloat Temp = *this;
6127 bool LosesInfo;
6128 [[maybe_unused]] opStatus St =
6129 Temp.convert(APFloatBase::semIEEEsingle, rmNearestTiesToEven, &LosesInfo);
6130 assert(!(St & opInexact) && !LosesInfo && "Unexpected imprecision");
6131 return Temp.getIEEE().convertToFloat();
6132}
6133
6136 .Case("Float8E5M2", getSizeInBits(semFloat8E5M2))
6137 .Case("Float8E5M2FNUZ", getSizeInBits(semFloat8E5M2FNUZ))
6138 .Case("Float8E4M3", getSizeInBits(semFloat8E4M3))
6139 .Case("Float8E4M3FN", getSizeInBits(semFloat8E4M3FN))
6140 .Case("Float8E4M3FNUZ", getSizeInBits(semFloat8E4M3FNUZ))
6141 .Case("Float8E4M3B11FNUZ", getSizeInBits(semFloat8E4M3B11FNUZ))
6142 .Case("Float8E3M4", getSizeInBits(semFloat8E3M4))
6143 .Case("Float8E8M0FNU", getSizeInBits(semFloat8E8M0FNU))
6144 .Case("Float6E3M2FN", getSizeInBits(semFloat6E3M2FN))
6145 .Case("Float6E2M3FN", getSizeInBits(semFloat6E2M3FN))
6146 .Case("Float4E2M1FN", getSizeInBits(semFloat4E2M1FN))
6147 .Case("Float8E5M3FNU", getSizeInBits(semFloat8E5M3FNU))
6148 .Default(0);
6149}
6150
6154
6156 // TODO: extend to remaining arbitrary FP types: Float8E4M3, Float8E3M4,
6157 // Float8E5M2FNUZ, Float8E4M3FNUZ, Float8E4M3B11FNUZ, Float8E8M0FNU.
6159 .Case("Float8E5M2", &semFloat8E5M2)
6160 .Case("Float8E4M3FN", &semFloat8E4M3FN)
6161 .Case("Float8E5M3FNU", &semFloat8E5M3FNU)
6162 .Case("Float4E2M1FN", &semFloat4E2M1FN)
6163 .Case("Float6E3M2FN", &semFloat6E3M2FN)
6164 .Case("Float6E2M3FN", &semFloat6E2M3FN)
6165 .Default(nullptr);
6166}
6167
6168APFloat::Storage::~Storage() {
6169 if (usesLayout<IEEEFloat>(*semantics)) {
6170 IEEE.~IEEEFloat();
6171 return;
6172 }
6173 if (usesLayout<DoubleAPFloat>(*semantics)) {
6174 Double.~DoubleAPFloat();
6175 return;
6176 }
6177 llvm_unreachable("Unexpected semantics");
6178}
6179
6180APFloat::Storage::Storage(const APFloat::Storage &RHS) {
6181 if (usesLayout<IEEEFloat>(*RHS.semantics)) {
6182 new (this) IEEEFloat(RHS.IEEE);
6183 return;
6184 }
6185 if (usesLayout<DoubleAPFloat>(*RHS.semantics)) {
6186 new (this) DoubleAPFloat(RHS.Double);
6187 return;
6188 }
6189 llvm_unreachable("Unexpected semantics");
6190}
6191
6192APFloat::Storage::Storage(APFloat::Storage &&RHS) {
6193 if (usesLayout<IEEEFloat>(*RHS.semantics)) {
6194 new (this) IEEEFloat(std::move(RHS.IEEE));
6195 return;
6196 }
6197 if (usesLayout<DoubleAPFloat>(*RHS.semantics)) {
6198 new (this) DoubleAPFloat(std::move(RHS.Double));
6199 return;
6200 }
6201 llvm_unreachable("Unexpected semantics");
6202}
6203
6204APFloat::Storage &APFloat::Storage::operator=(const APFloat::Storage &RHS) {
6205 if (usesLayout<IEEEFloat>(*semantics) &&
6206 usesLayout<IEEEFloat>(*RHS.semantics)) {
6207 IEEE = RHS.IEEE;
6208 } else if (usesLayout<DoubleAPFloat>(*semantics) &&
6209 usesLayout<DoubleAPFloat>(*RHS.semantics)) {
6210 Double = RHS.Double;
6211 } else if (this != &RHS) {
6212 this->~Storage();
6213 new (this) Storage(RHS);
6214 }
6215 return *this;
6216}
6217
6218APFloat::Storage &APFloat::Storage::operator=(APFloat::Storage &&RHS) {
6219 if (usesLayout<IEEEFloat>(*semantics) &&
6220 usesLayout<IEEEFloat>(*RHS.semantics)) {
6221 IEEE = std::move(RHS.IEEE);
6222 } else if (usesLayout<DoubleAPFloat>(*semantics) &&
6223 usesLayout<DoubleAPFloat>(*RHS.semantics)) {
6224 Double = std::move(RHS.Double);
6225 } else if (this != &RHS) {
6226 this->~Storage();
6227 new (this) Storage(std::move(RHS));
6228 }
6229 return *this;
6230}
6231
6232namespace {
6233
6234APFloat::opStatus getOpStatusFromLibc(int libc_exceptions) {
6236 if (libc_exceptions & FE_INVALID)
6238 if (libc_exceptions & FE_DIVBYZERO)
6240 if (libc_exceptions & FE_OVERFLOW)
6242 if (libc_exceptions & FE_UNDERFLOW)
6244 if (libc_exceptions & FE_INEXACT)
6246 return status;
6247}
6248
6249} // namespace
6250
6251// TODO: Support other rounding modes when LLVM libc math implement static
6252// roundings.
6253std::optional<APFloat> exp(const APFloat &x, RoundingMode rounding_mode,
6254 APFloat::opStatus *status) {
6255
6256 if (rounding_mode == APFloatBase::rmNearestTiesToEven) {
6257 if (APFloat::SemanticsToEnum(x.getSemantics()) ==
6259 float x_val = x.convertToFloat();
6260 int exc =
6261 LIBC_NAMESPACE::shared::check::exp_exceptions(x_val, FE_TONEAREST);
6262 if (status) {
6263 *status = getOpStatusFromLibc(exc);
6264 if (x.isSignaling()) {
6265 // 32-bit x86 will silence sNaN when loading floats, so we explicitly
6266 // add the INVALID exception here.
6267 *status =
6268 static_cast<APFloat::opStatus>(*status | APFloat::opInvalidOp);
6269 }
6270 }
6271 float result = LIBC_NAMESPACE::shared::expf(x_val);
6272 return APFloat(result);
6273 }
6274 if (APFloat::SemanticsToEnum(x.getSemantics()) ==
6276 double x_val = x.convertToDouble();
6277 int exc =
6278 LIBC_NAMESPACE::shared::check::exp_exceptions(x_val, FE_TONEAREST);
6279 if (status) {
6280 *status = getOpStatusFromLibc(exc);
6281 if (x.isSignaling()) {
6282 // 32-bit x86 will silence sNaN when loading floats, so we explicitly
6283 // add the INVALID exception here.
6284 *status =
6285 static_cast<APFloat::opStatus>(*status | APFloat::opInvalidOp);
6286 }
6287 }
6288 double result = LIBC_NAMESPACE::shared::exp(x_val);
6289 return APFloat(result);
6290 }
6291 }
6292 return std::nullopt;
6293}
6294
6295} // namespace llvm
6296
6297#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:6151
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:6134
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:6155
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:6077
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:6034
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:5976
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:6093
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:6060
LLVM_ABI friend hash_code hash_value(const APFloat &Arg)
See friend declarations above.
Definition APFloat.cpp:5948
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:6121
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:5963
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:5943
friend IEEEFloat
Definition APFloat.h:1670
LLVM_DUMP_METHOD void dump() const
Definition APFloat.cpp:6071
LLVM_ABI void print(raw_ostream &) const
Definition APFloat.cpp:6064
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:5290
LLVM_ABI DoubleAPFloat & operator=(const DoubleAPFloat &RHS)
Definition APFloat.cpp:4820
LLVM_ABI void changeSign()
Definition APFloat.cpp:5197
LLVM_ABI bool isLargest() const
Definition APFloat.cpp:5764
LLVM_ABI opStatus remainder(const DoubleAPFloat &RHS)
Definition APFloat.cpp:5084
LLVM_ABI opStatus multiply(const DoubleAPFloat &RHS, roundingMode RM)
Definition APFloat.cpp:4987
LLVM_ABI fltCategory getCategory() const
Definition APFloat.cpp:5256
LLVM_ABI bool bitwiseIsEqual(const DoubleAPFloat &RHS) const
Definition APFloat.cpp:5313
LLVM_ABI LLVM_READONLY int getExactLog2Abs() const
Definition APFloat.cpp:5788
LLVM_ABI opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM)
Definition APFloat.cpp:5715
LLVM_ABI APInt bitcastToAPInt() const
Definition APFloat.cpp:5324
LLVM_ABI Expected< opStatus > convertFromString(StringRef, roundingMode)
Definition APFloat.cpp:5334
LLVM_ABI bool isSmallest() const
Definition APFloat.cpp:5747
LLVM_ABI opStatus subtract(const DoubleAPFloat &RHS, roundingMode RM)
Definition APFloat.cpp:4979
LLVM_ABI friend hash_code hash_value(const DoubleAPFloat &Arg)
Definition APFloat.cpp:5318
LLVM_ABI cmpResult compareAbsoluteValue(const DoubleAPFloat &RHS) const
Definition APFloat.cpp:5203
LLVM_ABI bool isDenormal() const
Definition APFloat.cpp:5740
LLVM_ABI opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
Definition APFloat.cpp:5551
LLVM_ABI void makeSmallest(bool Neg)
Definition APFloat.cpp:5283
LLVM_ABI friend int ilogb(const DoubleAPFloat &X)
Definition APFloat.cpp:5797
LLVM_ABI opStatus next(bool nextDown)
Definition APFloat.cpp:5350
LLVM_ABI void makeInf(bool Neg)
Definition APFloat.cpp:5262
LLVM_ABI bool isInteger() const
Definition APFloat.cpp:5772
LLVM_ABI void makeZero(bool Neg)
Definition APFloat.cpp:5267
LLVM_ABI opStatus divide(const DoubleAPFloat &RHS, roundingMode RM)
Definition APFloat.cpp:5073
LLVM_ABI bool isSmallestNormalized() const
Definition APFloat.cpp:5755
LLVM_ABI opStatus mod(const DoubleAPFloat &RHS)
Definition APFloat.cpp:5094
LLVM_ABI DoubleAPFloat(const fltSemantics &S)
Definition APFloat.cpp:4767
LLVM_ABI void toString(SmallVectorImpl< char > &Str, unsigned FormatPrecision, unsigned FormatMaxPadding, bool TruncateZero=true) const
Definition APFloat.cpp:5778
LLVM_ABI void makeLargest(bool Neg)
Definition APFloat.cpp:5272
LLVM_ABI cmpResult compare(const DoubleAPFloat &RHS) const
Definition APFloat.cpp:5305
LLVM_ABI friend DoubleAPFloat scalbn(const DoubleAPFloat &X, int Exp, roundingMode)
LLVM_ABI opStatus roundToIntegral(roundingMode RM)
Definition APFloat.cpp:5120
LLVM_ABI opStatus fusedMultiplyAdd(const DoubleAPFloat &Multiplicand, const DoubleAPFloat &Addend, roundingMode RM)
Definition APFloat.cpp:5105
LLVM_ABI APInt getNaNPayload() const
Definition APFloat.cpp:5926
LLVM_ABI unsigned int convertToHexString(char *DST, unsigned int HexDigits, bool UpperCase, roundingMode RM) const
Definition APFloat.cpp:5730
LLVM_ABI bool isNegative() const
Definition APFloat.cpp:5260
LLVM_ABI opStatus add(const DoubleAPFloat &RHS, roundingMode RM)
Definition APFloat.cpp:4974
LLVM_ABI void makeNaN(bool SNaN, bool Neg, const APInt *fill)
Definition APFloat.cpp:5300
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:4655
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:4082
LLVM_ABI LLVM_READONLY int getExactLog2Abs() const
Definition APFloat.cpp:4477
LLVM_ABI APInt bitcastToAPInt() const
Definition APFloat.cpp:3702
LLVM_ABI friend IEEEFloat scalbn(IEEEFloat X, int Exp, roundingMode)
Definition APFloat.cpp:4727
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:3775
LLVM_ABI float convertToFloat() const
Definition APFloat.cpp:3768
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:4433
LLVM_ABI void makeSmallest(bool Neg=false)
Make this number the smallest magnitude denormal number in the given semantics.
Definition APFloat.cpp:4114
LLVM_ABI void makeInf(bool Neg=false)
Definition APFloat.cpp:4674
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:4703
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:4128
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:4709
LLVM_ABI opStatus next(bool nextDown)
IEEE-754R 5.3.1: nextUp/nextDown.
Definition APFloat.cpp:4522
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:4506
LLVM_ABI void makeZero(bool Neg=false)
Definition APFloat.cpp:4689
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:4748
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:4709
static constexpr cmpResult cmpEqual
Definition APFloat.h:462
LLVM_ABI IEEEFloat scalbn(IEEEFloat X, int Exp, roundingMode)
Definition APFloat.cpp:4727
static std::pair< APFloat, APFloat > fastTwoSum(APFloat X, APFloat Y)
Definition APFloat.cpp:4837
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:6253
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