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