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