LLVM 24.0.0git
APFloat.h
Go to the documentation of this file.
1//===- llvm/ADT/APFloat.h - Arbitrary Precision Floating Point ---*- C++ -*-==//
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/// \file
10/// This file declares a class to represent arbitrary precision floating point
11/// values and provide a variety of arithmetic operations on them.
12///
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_ADT_APFLOAT_H
16#define LLVM_ADT_APFLOAT_H
17
18#include "llvm/ADT/APInt.h"
19#include "llvm/ADT/ArrayRef.h"
24#include <memory>
25#include <optional>
26
27#define APFLOAT_DISPATCH_ON_SEMANTICS(METHOD_CALL) \
28 do { \
29 if (usesLayout<IEEEFloat>(getSemantics())) \
30 return U.IEEE.METHOD_CALL; \
31 if (usesLayout<DoubleAPFloat>(getSemantics())) \
32 return U.Double.METHOD_CALL; \
33 llvm_unreachable("Unexpected semantics"); \
34 } while (false)
35
36namespace llvm {
37
38struct fltSemantics;
39class APSInt;
40class StringRef;
41class APFloat;
42class FloatRepr;
43class raw_ostream;
44
45template <typename T> class Expected;
46template <typename T> class SmallVectorImpl;
47
48/// Enum that represents what fraction of the LSB truncated bits of an fp number
49/// represent.
50///
51/// This essentially combines the roles of guard and sticky bits.
52enum lostFraction { // Example of truncated bits:
53 lfExactlyZero, // 000000
54 lfLessThanHalf, // 0xxxxx x's not all zero
55 lfExactlyHalf, // 100000
56 lfMoreThanHalf // 1xxxxx x's not all zero
57};
58
59/// A self-contained host- and target-independent arbitrary-precision
60/// floating-point software implementation.
61///
62/// APFloat uses bignum integer arithmetic as provided by static functions in
63/// the APInt class. The library will work with bignum integers whose parts are
64/// any unsigned type at least 16 bits wide, but 64 bits is recommended.
65///
66/// Written for clarity rather than speed, in particular with a view to use in
67/// the front-end of a cross compiler so that target arithmetic can be correctly
68/// performed on the host. Performance should nonetheless be reasonable,
69/// particularly for its intended use. It may be useful as a base
70/// implementation for a run-time library during development of a faster
71/// target-specific one.
72///
73/// All 5 rounding modes in the IEEE-754R draft are handled correctly for all
74/// implemented operations. Currently implemented operations are add, subtract,
75/// multiply, divide, fused-multiply-add, conversion-to-float,
76/// conversion-to-integer and conversion-from-integer. New rounding modes
77/// (e.g. away from zero) can be added with three or four lines of code.
78///
79/// Four formats are built-in: IEEE single precision, double precision,
80/// quadruple precision, and x87 80-bit extended double (when operating with
81/// full extended precision). Adding a new format that obeys IEEE semantics
82/// only requires adding two lines of code: a declaration and definition of the
83/// format.
84///
85/// All operations return the status of that operation as an exception bit-mask,
86/// so multiple operations can be done consecutively with their results or-ed
87/// together. The returned status can be useful for compiler diagnostics; e.g.,
88/// inexact, underflow and overflow can be easily diagnosed on constant folding,
89/// and compiler optimizers can determine what exceptions would be raised by
90/// folding operations and optimize, or perhaps not optimize, accordingly.
91///
92/// At present, underflow tininess is detected after rounding; it should be
93/// straight forward to add support for the before-rounding case too.
94///
95/// The library reads hexadecimal floating point numbers as per C99, and
96/// correctly rounds if necessary according to the specified rounding mode.
97/// Syntax is required to have been validated by the caller. It also converts
98/// floating point numbers to hexadecimal text as per the C99 %a and %A
99/// conversions. The output precision (or alternatively the natural minimal
100/// precision) can be specified; if the requested precision is less than the
101/// natural precision the output is correctly rounded for the specified rounding
102/// mode.
103///
104/// It also reads decimal floating point numbers and correctly rounds according
105/// to the specified rounding mode.
106///
107/// Conversion to decimal text is not currently implemented.
108///
109/// Non-zero finite numbers are represented internally as a sign bit, a 16-bit
110/// signed exponent, and the significand as an array of integer parts. After
111/// normalization of a number of precision P the exponent is within the range of
112/// the format, and if the number is not denormal the P-th bit of the
113/// significand is set as an explicit integer bit. For denormals the most
114/// significant bit is shifted right so that the exponent is maintained at the
115/// format's minimum, so that the smallest denormal has just the least
116/// significant bit of the significand set. The sign of zeroes and infinities
117/// is significant; the exponent and significand of such numbers is not stored,
118/// but has a known implicit (deterministic) value: 0 for the significands, 0
119/// for zero exponent, all 1 bits for infinity exponent. For NaNs the sign and
120/// significand are deterministic, although not really meaningful, and preserved
121/// in non-conversion operations. The exponent is implicitly all 1 bits.
122///
123/// APFloat does not provide any exception handling beyond default exception
124/// handling. We represent Signaling NaNs via IEEE-754R 2008 6.2.1 should clause
125/// by encoding Signaling NaNs with the first bit of its trailing significand as
126/// 0.
127///
128/// TODO
129/// ====
130///
131/// Some features that may or may not be worth adding:
132///
133/// Binary to decimal conversion (hard).
134///
135/// Optional ability to detect underflow tininess before rounding.
136///
137/// New formats: x87 in single and double precision mode (IEEE apart from
138/// extended exponent range) (hard).
139///
140/// New operations: sqrt, IEEE remainder, C90 fmod, nexttoward.
141///
142
143namespace detail {
144class IEEEFloat;
145class DoubleAPFloat;
146} // namespace detail
147
148// This is the common type definitions shared by APFloat and its internal
149// implementation classes. This struct should not define any non-static data
150// members.
152public:
154 static constexpr unsigned integerPartWidth = APInt::APINT_BITS_PER_WORD;
155
156 /// A signed type to represent a floating point numbers unbiased exponent.
157 using ExponentType = int32_t;
158
159 /// \name Floating Point Semantics.
160 /// @{
167 // TODO: Documentation is missing.
169 // The IBM double-double semantics. Such a number consists of a pair of
170 // IEEE 64-bit doubles (Hi, Lo), where |Hi| > |Lo|, and if normal,
171 // (double)(Hi + Lo) == Hi. The numeric value it's modeling is Hi + Lo.
172 // Therefore it has two 53-bit mantissa parts that aren't necessarily
173 // adjacent to each other, and two 11-bit exponents.
174 //
175 // Note: we need to make the value different from semBogus as otherwise
176 // an unsafe optimization may collapse both values to a single address,
177 // and we heavily rely on them having distinct addresses.
179 // These are legacy semantics for the fallback, inaccurate implementation
180 // of IBM double-double, if the accurate semPPCDoubleDouble doesn't handle
181 // the operation. It's equivalent to having an IEEE number with consecutive
182 // 106 bits of mantissa and 11 bits of exponent.
183 //
184 // It's not equivalent to IBM double-double. For example, a legit IBM
185 // double-double, 1 + epsilon:
186 //
187 // 1 + epsilon = 1 + (1 >> 1076)
188 //
189 // is not representable by a consecutive 106 bits of mantissa.
190 //
191 // Currently, these semantics are used in the following way:
192 //
193 // semPPCDoubleDouble -> (IEEEdouble, IEEEdouble) ->
194 // (64-bit APInt, 64-bit APInt) -> (128-bit APInt) ->
195 // semPPCDoubleDoubleLegacy -> IEEE operations
196 //
197 // We use bitcastToAPInt() to get the bit representation (in APInt) of the
198 // underlying IEEEdouble, then use the APInt constructor to construct the
199 // legacy IEEE float.
200 //
201 // TODO: Implement all operations in semPPCDoubleDouble, and delete these
202 // semantics.
204 // 8-bit floating point number following IEEE-754 conventions with bit
205 // layout S1E5M2 as described in https://arxiv.org/abs/2209.05433.
207 // 8-bit floating point number mostly following IEEE-754 conventions
208 // and bit layout S1E5M2 described in https://arxiv.org/abs/2206.02915,
209 // with expanded range and with no infinity or signed zero.
210 // NaN is represented as negative zero. (FN -> Finite, UZ -> unsigned zero).
211 // This format's exponent bias is 16, instead of the 15 (2 ** (5 - 1) - 1)
212 // that IEEE precedent would imply.
214 // 8-bit floating point number following IEEE-754 conventions with bit
215 // layout S1E4M3.
217 // 8-bit floating point number mostly following IEEE-754 conventions with
218 // bit layout S1E4M3 as described in https://arxiv.org/abs/2209.05433.
219 // Unlike IEEE-754 types, there are no infinity values, and NaN is
220 // represented with the exponent and mantissa bits set to all 1s.
222 // 8-bit floating point number mostly following IEEE-754 conventions
223 // and bit layout S1E4M3 described in https://arxiv.org/abs/2206.02915,
224 // with expanded range and with no infinity or signed zero.
225 // NaN is represented as negative zero. (FN -> Finite, UZ -> unsigned zero).
226 // This format's exponent bias is 8, instead of the 7 (2 ** (4 - 1) - 1)
227 // that IEEE precedent would imply.
229 // 8-bit floating point number mostly following IEEE-754 conventions
230 // and bit layout S1E4M3 with expanded range and with no infinity or signed
231 // zero.
232 // NaN is represented as negative zero. (FN -> Finite, UZ -> unsigned zero).
233 // This format's exponent bias is 11, instead of the 7 (2 ** (4 - 1) - 1)
234 // that IEEE precedent would imply.
236 // 8-bit floating point number following IEEE-754 conventions with bit
237 // layout S1E3M4.
239 // Floating point number that occupies 32 bits or less of storage, providing
240 // improved range compared to half (16-bit) formats, at (potentially)
241 // greater throughput than single precision (32-bit) formats.
243 // 8-bit floating point number with (all the) 8 bits for the exponent
244 // like in FP32. There are no zeroes, no infinities, and no denormal values.
245 // This format has unsigned representation only. (U -> Unsigned only).
246 // NaN is represented with all bits set to 1. Bias is 127.
247 // This format represents the scale data type in the MX specification from:
248 // https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf
250 // 6-bit floating point number with bit layout S1E3M2. Unlike IEEE-754
251 // types, there are no infinity or NaN values. The format is detailed in
252 // https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf
254 // 6-bit floating point number with bit layout S1E2M3. Unlike IEEE-754
255 // types, there are no infinity or NaN values. The format is detailed in
256 // https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf
258 // 4-bit floating point number with bit layout S1E2M1. Unlike IEEE-754
259 // types, there are no infinity or NaN values. The format is detailed in
260 // https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf
262 // 8-bit floating point number mostly following IEEE-754 conventions with
263 // bit layout S0E5M3 as described in PTX ISA page.
264 // https://docs.nvidia.com/cuda/developer-preview/13.4/parallel-thread-execution/index.html#alternate-floating-point-data-formats
265 // Unlike IEEE-754 types, there are no infinity values, and NaN is
266 // represented with the exponent and mantissa bits set to all 1s.
269 };
270
273
274private:
275 LLVM_ABI static const fltSemantics semIEEEhalf;
276 LLVM_ABI static const fltSemantics semBFloat;
277 LLVM_ABI static const fltSemantics semIEEEsingle;
278 LLVM_ABI static const fltSemantics semIEEEdouble;
279 LLVM_ABI static const fltSemantics semIEEEquad;
280 LLVM_ABI static const fltSemantics semX87DoubleExtended;
281 LLVM_ABI static const fltSemantics semPPCDoubleDouble;
282 LLVM_ABI static const fltSemantics semPPCDoubleDoubleLegacy;
283 LLVM_ABI static const fltSemantics semFloat8E5M2;
284 LLVM_ABI static const fltSemantics semFloat8E5M2FNUZ;
285 LLVM_ABI static const fltSemantics semFloat8E4M3;
286 LLVM_ABI static const fltSemantics semFloat8E4M3FN;
287 LLVM_ABI static const fltSemantics semFloat8E4M3FNUZ;
288 LLVM_ABI static const fltSemantics semFloat8E4M3B11FNUZ;
289 LLVM_ABI static const fltSemantics semFloat8E3M4;
290 LLVM_ABI static const fltSemantics semFloatTF32;
291 LLVM_ABI static const fltSemantics semFloat8E8M0FNU;
292 LLVM_ABI static const fltSemantics semFloat8E5M3FNU;
293 LLVM_ABI static const fltSemantics semFloat6E3M2FN;
294 LLVM_ABI static const fltSemantics semFloat6E2M3FN;
295 LLVM_ABI static const fltSemantics semFloat4E2M1FN;
296 LLVM_ABI static const fltSemantics semBogus;
297
298 friend class detail::IEEEFloat;
300 friend class APFloat;
301
302public:
303 static constexpr const fltSemantics &IEEEhalf() { return semIEEEhalf; }
304 static constexpr const fltSemantics &BFloat() { return semBFloat; }
305 static constexpr const fltSemantics &IEEEsingle() { return semIEEEsingle; }
306 static constexpr const fltSemantics &IEEEdouble() { return semIEEEdouble; }
307 static constexpr const fltSemantics &IEEEquad() { return semIEEEquad; }
308 static constexpr const fltSemantics &x87DoubleExtended() {
309 return semX87DoubleExtended;
310 }
311 static constexpr const fltSemantics &PPCDoubleDouble() {
312 return semPPCDoubleDouble;
313 }
314 static constexpr const fltSemantics &PPCDoubleDoubleLegacy() {
315 return semPPCDoubleDoubleLegacy;
316 }
317 static constexpr const fltSemantics &Float8E5M2() { return semFloat8E5M2; }
318 static constexpr const fltSemantics &Float8E5M2FNUZ() {
319 return semFloat8E5M2FNUZ;
320 }
321 static constexpr const fltSemantics &Float8E4M3() { return semFloat8E4M3; }
322 static constexpr const fltSemantics &Float8E4M3FN() {
323 return semFloat8E4M3FN;
324 }
325 static constexpr const fltSemantics &Float8E4M3FNUZ() {
326 return semFloat8E4M3FNUZ;
327 }
328 static constexpr const fltSemantics &Float8E4M3B11FNUZ() {
329 return semFloat8E4M3B11FNUZ;
330 }
331 static constexpr const fltSemantics &Float8E3M4() { return semFloat8E3M4; }
332 static constexpr const fltSemantics &FloatTF32() { return semFloatTF32; }
333 static constexpr const fltSemantics &Float8E8M0FNU() {
334 return semFloat8E8M0FNU;
335 }
336 static constexpr const fltSemantics &Float8E5M3FNU() {
337 return semFloat8E5M3FNU;
338 }
339 static constexpr const fltSemantics &Float6E3M2FN() {
340 return semFloat6E3M2FN;
341 }
342 static constexpr const fltSemantics &Float6E2M3FN() {
343 return semFloat6E2M3FN;
344 }
345 static constexpr const fltSemantics &Float4E2M1FN() {
346 return semFloat4E2M1FN;
347 }
348
349 /// A Pseudo fltsemantic used to construct APFloats that cannot conflict with
350 /// anything real.
351 static constexpr const fltSemantics &Bogus() { return semBogus; }
352
353 // Returns true if any number described by this semantics can be precisely
354 // represented by the specified semantics. Does not take into account
355 // the value of fltNonfiniteBehavior, hasZero, hasSignedRepr.
356 LLVM_ABI static bool isRepresentableBy(const fltSemantics &A,
357 const fltSemantics &B);
358
359 /// Returns whether converting a value from \p From to \p To is known to
360 /// preserve all information. If \p IgnoreNaNs is true, differences between
361 /// NaN representations are ignored, but NaNs must remain NaNs and infinities
362 /// must remain infinities.
363 LLVM_ABI static bool isLosslesslyConvertibleTo(const fltSemantics &From,
364 const fltSemantics &To,
365 bool IgnoreNaNs = false);
366
367 /// @}
368
369 /// IEEE-754R 5.11: Floating Point Comparison Relations.
376
377 /// IEEE-754R 4.3: Rounding-direction attributes.
379
387
388 /// IEEE-754R 7: Default exception handling.
389 ///
390 /// opUnderflow or opOverflow are always returned or-ed with opInexact.
391 ///
392 /// APFloat models this behavior specified by IEEE-754:
393 /// "For operations producing results in floating-point format, the default
394 /// result of an operation that signals the invalid operation exception
395 /// shall be a quiet NaN."
396 enum opStatus {
397 opOK = 0x00,
403 };
404
405 /// Category of internally-represented number.
412
413 /// Convenience enum used to construct an uninitialized APFloat.
417
418 /// Enumeration of \c ilogb error results.
420 IEK_Zero = INT_MIN + 1,
421 IEK_NaN = INT_MIN,
422 IEK_Inf = INT_MAX
423 };
424
425 LLVM_ABI static unsigned int semanticsPrecision(const fltSemantics &);
428 LLVM_ABI static unsigned int semanticsSizeInBits(const fltSemantics &);
429 LLVM_ABI static unsigned int semanticsIntSizeInBits(const fltSemantics &,
430 bool);
431 LLVM_ABI static bool semanticsHasZero(const fltSemantics &);
432 LLVM_ABI static bool semanticsHasSignedRepr(const fltSemantics &);
433 LLVM_ABI static bool semanticsHasInf(const fltSemantics &);
434 LLVM_ABI static bool semanticsHasNaN(const fltSemantics &);
435 LLVM_ABI static bool isIEEELikeFP(const fltSemantics &);
436 LLVM_ABI static bool hasSignBitInMSB(const fltSemantics &);
437
438 // Returns true if any number described by \p Src can be precisely represented
439 // by a normal (not subnormal) value in \p Dst.
440 LLVM_ABI static bool isRepresentableAsNormalIn(const fltSemantics &Src,
441 const fltSemantics &Dst);
442
443 /// Returns the size of the floating point number (in bits) in the given
444 /// semantics.
445 LLVM_ABI static unsigned getSizeInBits(const fltSemantics &Sem);
446
447 /// Returns true if the given string is a valid arbitrary floating-point
448 /// format interpretation for llvm.convert.to.arbitrary.fp and
449 /// llvm.convert.from.arbitrary.fp intrinsics.
451
452 /// Returns the size in bits of a valid arbitrary floating-point format
453 /// string, or 0 if the string is not a valid format. Covers every format
454 /// accepted by isValidArbitraryFPFormat, not only those
455 /// getArbitraryFPSemantics can currently lower.
457
458 /// Returns the fltSemantics for a given arbitrary FP format string,
459 /// or nullptr if invalid.
461};
462
463namespace detail {
464
485static constexpr opStatus opOK = APFloatBase::opOK;
495
496class IEEEFloat final {
497public:
498 /// \name Constructors
499 /// @{
500
501 LLVM_ABI IEEEFloat(const fltSemantics &); // Default construct to +0.0
504 LLVM_ABI IEEEFloat(const fltSemantics &, const APInt &);
505 LLVM_ABI explicit IEEEFloat(double d);
506 LLVM_ABI explicit IEEEFloat(float f);
510
511 /// @}
512
513 /// Returns whether this instance allocated memory.
514 bool needsCleanup() const { return partCount() > 1; }
515
516 /// \name Convenience "constructors"
517 /// @{
518
519 /// @}
520
521 /// \name Arithmetic
522 /// @{
523
528 /// IEEE remainder.
530 /// C fmod, or llvm frem.
535 /// IEEE-754R 5.3.1: nextUp/nextDown.
536 LLVM_ABI opStatus next(bool nextDown);
537
538 /// @}
539
540 /// \name Sign operations.
541 /// @{
542
543 LLVM_ABI void changeSign();
544
545 /// @}
546
547 /// \name Conversions
548 /// @{
549
552 bool, roundingMode, bool *) const;
556 LLVM_ABI double convertToDouble() const;
557#ifdef HAS_IEE754_FLOAT128
558 LLVM_ABI float128 convertToQuad() const;
559#endif
560 LLVM_ABI float convertToFloat() const;
561
562 /// @}
563
564 /// The definition of equality is not straightforward for floating point, so
565 /// we won't use operator==. Use one of the following, or write whatever it
566 /// is you really mean.
567 bool operator==(const IEEEFloat &) const = delete;
568
569 /// IEEE comparison with another floating point number (NaNs compare
570 /// unordered, 0==-0).
571 LLVM_ABI cmpResult compare(const IEEEFloat &) const;
572
573 /// Bitwise comparison for equality (QNaNs compare equal, 0!=-0).
574 LLVM_ABI bool bitwiseIsEqual(const IEEEFloat &) const;
575
576 /// Write out a hexadecimal representation of the floating point value to DST,
577 /// which must be of sufficient size, in the C99 form [-]0xh.hhhhp[+-]d.
578 /// Return the number of characters written, excluding the terminating NUL.
579 LLVM_ABI unsigned int convertToHexString(char *dst, unsigned int hexDigits,
580 bool upperCase, roundingMode) const;
581
582 /// \name IEEE-754R 5.7.2 General operations.
583 /// @{
584
585 /// IEEE-754R isSignMinus: Returns true if and only if the current value is
586 /// negative.
587 ///
588 /// This applies to zeros and NaNs as well.
589 bool isNegative() const { return sign; }
590
591 /// IEEE-754R isNormal: Returns true if and only if the current value is normal.
592 ///
593 /// This implies that the current value of the float is not zero, subnormal,
594 /// infinite, or NaN following the definition of normality from IEEE-754R.
595 bool isNormal() const { return !isDenormal() && isFiniteNonZero(); }
596
597 /// Returns true if and only if the current value is zero, subnormal, or
598 /// normal.
599 ///
600 /// This means that the value is not infinite or NaN.
601 bool isFinite() const { return !isNaN() && !isInfinity(); }
602
603 /// Returns true if and only if the float is plus or minus zero.
604 bool isZero() const { return category == fltCategory::fcZero; }
605
606 /// IEEE-754R isSubnormal(): Returns true if and only if the float is a
607 /// denormal.
608 LLVM_ABI bool isDenormal() const;
609
610 /// IEEE-754R isInfinite(): Returns true if and only if the float is infinity.
611 bool isInfinity() const { return category == fcInfinity; }
612
613 /// Returns true if and only if the float is a quiet or signaling NaN.
614 bool isNaN() const { return category == fcNaN; }
615
616 /// Returns true if and only if the float is a signaling NaN.
617 LLVM_ABI bool isSignaling() const;
618
619 /// @}
620
621 /// \name Simple Queries
622 /// @{
623
624 fltCategory getCategory() const { return category; }
625 const fltSemantics &getSemantics() const { return *semantics; }
626 bool isNonZero() const { return category != fltCategory::fcZero; }
627 bool isFiniteNonZero() const { return isFinite() && !isZero(); }
628 bool isPosZero() const { return isZero() && !isNegative(); }
629 bool isNegZero() const { return isZero() && isNegative(); }
630
631 /// Returns true if and only if the number has the smallest possible non-zero
632 /// magnitude in the current semantics.
633 LLVM_ABI bool isSmallest() const;
634
635 /// Returns true if this is the smallest (by magnitude) normalized finite
636 /// number in the given semantics.
637 LLVM_ABI bool isSmallestNormalized() const;
638
639 /// Returns true if and only if the number has the largest possible finite
640 /// magnitude in the current semantics.
641 LLVM_ABI bool isLargest() const;
642
643 /// Returns true if and only if the number is an exact integer.
644 LLVM_ABI bool isInteger() const;
645
646 /// @}
647
650
651 /// Overload to compute a hash code for an APFloat value.
652 ///
653 /// Note that the use of hash codes for floating point values is in general
654 /// frought with peril. Equality is hard to define for these values. For
655 /// example, should negative and positive zero hash to different codes? Are
656 /// they equal or not? This hash value implementation specifically
657 /// emphasizes producing different codes for different inputs in order to
658 /// be used in canonicalization and memoization. As such, equality is
659 /// bitwiseIsEqual, and 0 != -0.
660 LLVM_ABI friend hash_code hash_value(const IEEEFloat &Arg);
661
662 /// Converts this value into a decimal string.
663 ///
664 /// \param FormatPrecision The maximum number of digits of
665 /// precision to output. If there are fewer digits available,
666 /// zero padding will not be used unless the value is
667 /// integral and small enough to be expressed in
668 /// FormatPrecision digits. 0 means to use the natural
669 /// precision of the number.
670 /// \param FormatMaxPadding The maximum number of zeros to
671 /// consider inserting before falling back to scientific
672 /// notation. 0 means to always use scientific notation.
673 ///
674 /// \param TruncateZero Indicate whether to remove the trailing zero in
675 /// fraction part or not. Also setting this parameter to false forcing
676 /// producing of output more similar to default printf behavior.
677 /// Specifically the lower e is used as exponent delimiter and exponent
678 /// always contains no less than two digits.
679 ///
680 /// Number Precision MaxPadding Result
681 /// ------ --------- ---------- ------
682 /// 1.01E+4 5 2 10100
683 /// 1.01E+4 4 2 1.01E+4
684 /// 1.01E+4 5 1 1.01E+4
685 /// 1.01E-2 5 2 0.0101
686 /// 1.01E-2 4 2 0.0101
687 /// 1.01E-2 4 1 1.01E-2
689 unsigned FormatPrecision = 0,
690 unsigned FormatMaxPadding = 3,
691 bool TruncateZero = true) const;
692
694
695 LLVM_ABI friend int ilogb(const IEEEFloat &Arg);
696
698
699 LLVM_ABI friend IEEEFloat frexp(const IEEEFloat &X, int &Exp, roundingMode);
700
701 /// \name Special value setters.
702 /// @{
703
704 LLVM_ABI void makeLargest(bool Neg = false);
705 LLVM_ABI void makeSmallest(bool Neg = false);
706 LLVM_ABI void makeNaN(bool SNaN = false, bool Neg = false,
707 const APInt *fill = nullptr);
708 LLVM_ABI void makeInf(bool Neg = false);
709 LLVM_ABI void makeZero(bool Neg = false);
710 LLVM_ABI void makeQuiet();
711
712 /// Returns the smallest (by magnitude) normalized finite number in the given
713 /// semantics.
714 ///
715 /// \param Negative - True iff the number should be negative
716 LLVM_ABI void makeSmallestNormalized(bool Negative = false);
717
718 /// @}
719
721
723
724private:
725 /// \name Simple Queries
726 /// @{
727
728 integerPart *significandParts();
729 const integerPart *significandParts() const;
730 LLVM_ABI unsigned int partCount() const;
731 static unsigned int partCountForSemantic(APFloatBase::Semantics E);
732
733 /// @}
734
735 /// \name Significand operations.
736 /// @{
737
738 integerPart addSignificand(const IEEEFloat &);
739 integerPart subtractSignificand(const IEEEFloat &, integerPart);
740 // Exported for IEEEFloatUnitTestHelper.
741 LLVM_ABI lostFraction addOrSubtractSignificand(const IEEEFloat &,
742 bool subtract);
743 lostFraction multiplySignificand(const IEEEFloat &, IEEEFloat,
744 bool ignoreAddend = false);
745 lostFraction multiplySignificand(const IEEEFloat&);
746 lostFraction divideSignificand(const IEEEFloat &);
747 void incrementSignificand();
748 void initialize(const fltSemantics *);
749 void shiftSignificandLeft(unsigned int);
750 lostFraction shiftSignificandRight(unsigned int);
751 unsigned int significandLSB() const;
752 unsigned int significandMSB() const;
753 void zeroSignificand();
754 unsigned int getNumHighBits() const;
755 /// Return true if the significand excluding the integral bit is all ones.
756 bool isSignificandAllOnes() const;
757 bool isSignificandAllOnesExceptLSB() const;
758 /// Return true if the significand excluding the integral bit is all zeros.
759 bool isSignificandAllZeros() const;
760 bool isSignificandAllZerosExceptMSB() const;
761
762 /// @}
763
764 /// \name Arithmetic on special values.
765 /// @{
766
767 opStatus addOrSubtractSpecials(const IEEEFloat &, bool subtract);
768 opStatus divideSpecials(const IEEEFloat &);
769 opStatus multiplySpecials(const IEEEFloat &);
770 opStatus modSpecials(const IEEEFloat &);
771 opStatus remainderSpecials(const IEEEFloat&);
772
773 /// @}
774
775 /// \name Miscellany
776 /// @{
777
778 bool convertFromStringSpecials(StringRef str);
780 opStatus addOrSubtract(const IEEEFloat &, roundingMode, bool subtract);
781 opStatus handleOverflow(roundingMode);
782 bool roundAwayFromZero(roundingMode, lostFraction, unsigned int) const;
783 opStatus convertToSignExtendedInteger(MutableArrayRef<integerPart>,
784 unsigned int, bool, roundingMode,
785 bool *) const;
786 opStatus convertFromUnsignedParts(const integerPart *, unsigned int,
788 Expected<opStatus> convertFromHexadecimalString(StringRef, roundingMode);
789 Expected<opStatus> convertFromDecimalString(StringRef, roundingMode);
790 char *convertNormalToHexString(char *, unsigned int, bool,
791 roundingMode) const;
792 opStatus roundSignificandWithExponent(const integerPart *, unsigned int, int,
797
798 /// @}
799
800 static IEEEFloat &fromRepr(const FloatRepr &R);
801
802 template <APFloatBase::Semantics S>
803 friend APInt bitcastForSemantics(const FloatRepr &R);
804
805 template <APFloatBase::Semantics E> APInt convertIEEEFloatToAPInt() const;
806
807 template <APFloatBase::Semantics S>
808 friend void initFromAPIntForSemantics(FloatRepr &, const APInt &);
809
810 void initFromAPInt(const fltSemantics *Sem, const APInt &api);
811 template <APFloatBase::Semantics E> void initFromIEEEAPInt(const APInt &api);
812
813 void assign(const IEEEFloat &);
814 void copySignificand(const IEEEFloat &);
815 void freeSignificand();
816
817 /// Note: this must be the first data member.
818 /// The semantics that this value obeys.
819 const fltSemantics *semantics;
820
821 /// A binary fraction with an explicit integer bit.
822 ///
823 /// The significand must be at least one bit wider than the target precision.
824 union Significand {
825 integerPart part;
826 integerPart *parts;
827 } significand;
828
829 /// The signed unbiased exponent of the value.
830 ExponentType exponent;
831
832 /// What kind of floating point number this is.
833 ///
834 /// Only 2 bits are required, but VisualStudio incorrectly sign extends it.
835 /// Using the extra bit keeps it from failing under VisualStudio.
836 fltCategory category : 3;
837
838 /// Sign bit of the number.
839 unsigned int sign : 1;
840
842 friend class llvm::FloatRepr;
843};
844
846LLVM_ABI int ilogb(const IEEEFloat &Arg);
848LLVM_ABI IEEEFloat frexp(const IEEEFloat &Val, int &Exp, roundingMode RM);
849
850// This mode implements more precise float in terms of two APFloats.
851// The interface and layout is designed for arbitrary underlying semantics,
852// though currently only PPCDoubleDouble semantics are supported, whose
853// corresponding underlying semantics are IEEEdouble.
854class DoubleAPFloat final {
855 // Note: this must be the first data member.
856 const fltSemantics *Semantics;
857 APFloat *Floats;
858
859 opStatus addImpl(const APFloat &a, const APFloat &aa, const APFloat &c,
860 const APFloat &cc, roundingMode RM);
861
862 opStatus addWithSpecial(const DoubleAPFloat &LHS, const DoubleAPFloat &RHS,
863 DoubleAPFloat &Out, roundingMode RM);
864 opStatus convertToSignExtendedInteger(MutableArrayRef<integerPart> Input,
865 unsigned int Width, bool IsSigned,
866 roundingMode RM, bool *IsExact) const;
867
868 // Convert an unsigned integer Src to a floating point number,
869 // rounding according to RM. The sign of the floating point number is not
870 // modified.
871 opStatus convertFromUnsignedParts(const integerPart *Src,
872 unsigned int SrcCount, roundingMode RM);
873
874 // Handle overflow. Sign is preserved. We either become infinity or
875 // the largest finite number.
876 opStatus handleOverflow(roundingMode RM);
877
878public:
882 LLVM_ABI DoubleAPFloat(const fltSemantics &S, const APInt &I);
884 APFloat &&Second);
888
891
892 bool needsCleanup() const { return Floats != nullptr; }
893
894 inline APFloat &getFirst();
895 inline const APFloat &getFirst() const;
896 inline APFloat &getSecond();
897 inline const APFloat &getSecond() const;
898
906 const DoubleAPFloat &Addend,
907 roundingMode RM);
909 LLVM_ABI void changeSign();
911
913 LLVM_ABI bool isNegative() const;
914
915 LLVM_ABI void makeInf(bool Neg);
916 LLVM_ABI void makeZero(bool Neg);
917 LLVM_ABI void makeLargest(bool Neg);
918 LLVM_ABI void makeSmallest(bool Neg);
919 LLVM_ABI void makeSmallestNormalized(bool Neg);
920 LLVM_ABI void makeNaN(bool SNaN, bool Neg, const APInt *fill);
921
923 LLVM_ABI bool bitwiseIsEqual(const DoubleAPFloat &RHS) const;
926 LLVM_ABI opStatus next(bool nextDown);
927
929 unsigned int Width, bool IsSigned,
930 roundingMode RM, bool *IsExact) const;
931 LLVM_ABI opStatus convertFromAPInt(const APInt &Input, bool IsSigned,
932 roundingMode RM);
933 LLVM_ABI unsigned int convertToHexString(char *DST, unsigned int HexDigits,
934 bool UpperCase,
935 roundingMode RM) const;
936
937 LLVM_ABI bool isDenormal() const;
938 LLVM_ABI bool isSmallest() const;
939 LLVM_ABI bool isSmallestNormalized() const;
940 LLVM_ABI bool isLargest() const;
941 LLVM_ABI bool isInteger() const;
942
944
945 LLVM_ABI void toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision,
946 unsigned FormatMaxPadding,
947 bool TruncateZero = true) const;
948
950
951 LLVM_ABI friend int ilogb(const DoubleAPFloat &X);
954 LLVM_ABI friend DoubleAPFloat frexp(const DoubleAPFloat &X, int &Exp,
956 LLVM_ABI friend hash_code hash_value(const DoubleAPFloat &Arg);
957};
958
960LLVM_ABI DoubleAPFloat scalbn(const DoubleAPFloat &Arg, int Exp,
961 roundingMode RM);
963
964} // End detail namespace
965
966// How the nonfinite values Inf and NaN are represented.
968 // Represents standard IEEE 754 behavior. A value is nonfinite if the
969 // exponent field is all 1s. In such cases, a value is Inf if the
970 // significand bits are all zero, and NaN otherwise
972
973 // This behavior is present in the Float8ExMyFN* types (Float8E4M3FN,
974 // Float8E5M2FNUZ, Float8E4M3FNUZ, and Float8E4M3B11FNUZ). There is no
975 // representation for Inf, and operations that would ordinarily produce Inf
976 // produce NaN instead.
977 // The details of the NaN representation(s) in this form are determined by the
978 // `fltNanEncoding` enum. We treat all NaNs as quiet, as the available
979 // encodings do not distinguish between signalling and quiet NaN.
981
982 // This behavior is present in Float6E3M2FN, Float6E2M3FN, and
983 // Float4E2M1FN types, which do not support Inf or NaN values.
985};
986
987// How NaN values are represented. This is curently only used in combination
988// with fltNonfiniteBehavior::NanOnly, and using a variant other than IEEE
989// while having IEEE non-finite behavior is liable to lead to unexpected
990// results.
991enum class fltNanEncoding {
992 // Represents the standard IEEE behavior where a value is NaN if its
993 // exponent is all 1s and the significand is non-zero.
995
996 // Represents the behavior in the Float8E4M3FN floating point type where NaN
997 // is represented by having the exponent and mantissa set to all 1s.
998 // This behavior matches the FP8 E4M3 type described in
999 // https://arxiv.org/abs/2209.05433. We treat both signed and unsigned NaNs
1000 // as non-signalling, although the paper does not state whether the NaN
1001 // values are signalling or not.
1003
1004 // Represents the behavior in Float8E{5,4}E{2,3}FNUZ floating point types
1005 // where NaN is represented by a sign bit of 1 and all 0s in the exponent
1006 // and mantissa (i.e. the negative zero encoding in a IEEE float). Since
1007 // there is only one NaN value, it is treated as quiet NaN. This matches the
1008 // behavior described in https://arxiv.org/abs/2206.02915 .
1010};
1011
1012/// Interface for fltSemantics callbacks to access the internal data of
1013/// APFloat/IEEEFloat.
1014///
1015/// Used to let user provided callback functions in fltSemantics access the
1016/// internals of APFloat without making them public and to hide the concrete
1017/// class used in APFloat
1018class FloatRepr {
1019 detail::IEEEFloat *Repr;
1020
1021 friend class detail::IEEEFloat;
1022 explicit FloatRepr(detail::IEEEFloat &F) : Repr(&F) {}
1023
1024public:
1025 /// Set the semantics and allocate storage for the significand. Must be
1026 /// called exactly once before any setter when initializing from bits.
1027 LLVM_ABI void initialize(const fltSemantics &Sem);
1028
1029 LLVM_ABI const fltSemantics &getSemantics() const;
1030
1032 /// Exponent and significand are only meaningful for fcNormal and fcNaN.
1034
1035 LLVM_ABI bool isNegative() const;
1036 LLVM_ABI void setNegative(bool Negative);
1037
1039 /// - The exponent is unbiased. Denormals use the semantics' minExponent and
1040 /// have the integer bit cleared.
1042
1044 /// The significand is precision bits wide and includes the integer bit.
1045 LLVM_ABI void setSignificand(const APInt &Significand);
1046};
1047
1048/* Represents floating point arithmetic semantics. */
1050 /* The largest E such that 2^E is representable; this matches the
1051 definition of IEEE 754. */
1053
1054 /* The smallest E such that 2^E is a normalized number; this
1055 matches the definition of IEEE 754. */
1057
1058 /* Number of bits in the significand. This includes the integer
1059 bit. */
1060 unsigned int precision;
1061
1062 /* Number of bits actually used in the semantics. */
1063 unsigned int sizeInBits;
1064
1066
1068
1069 /* Whether this semantics has an encoding for Zero */
1070 bool hasZero = true;
1071
1072 /* Whether this semantics can represent signed values */
1073 bool hasSignedRepr = true;
1074
1075 /* Whether the sign bit of this semantics is the most significant bit */
1076 bool hasSignBitInMSB = true;
1077
1078 /* Whether the format supports IEEE754 denormal representation.
1079 If both hasDenormals and hasZero are false exponent 0 is assumed to be a
1080 regular exponent instead of being reserved. This changes the bias by +1. */
1081 bool hasDenormals = true;
1082
1083 /* Whether the integer bit is explicitly represented between significant and
1084 exponent, for example as specified by the x86 double extended precision
1085 format.
1086
1087 For bit patterns designated as undefined under the standard the following
1088 conversions will happen when converting from bits. These follow x87
1089 behaviour:
1090 - exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity")
1091 - exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN")
1092 - exponent!=0 nor all 1's, integer bit 0 ("unnormal")
1093 - exponent = 0, integer bit 1 ("pseudodenormal")
1094 The first three are treated as NaNs, the last one as Normal */
1096
1097 void (*initFromAPInt)(FloatRepr &, const APInt &) = nullptr;
1098 APInt (*bitcastToAPInt)(const FloatRepr &) = nullptr;
1099};
1100
1101// This is a interface class that is currently forwarding functionalities from
1102// detail::IEEEFloat.
1103class APFloat : public APFloatBase {
1104 using IEEEFloat = detail::IEEEFloat;
1105 using DoubleAPFloat = detail::DoubleAPFloat;
1106
1107 static_assert(std::is_standard_layout<IEEEFloat>::value);
1108
1109 union Storage {
1110 const fltSemantics *semantics;
1111 IEEEFloat IEEE;
1112 DoubleAPFloat Double;
1113
1114 LLVM_ABI explicit Storage(IEEEFloat F, const fltSemantics &S);
1115 explicit Storage(DoubleAPFloat F, const fltSemantics &S)
1116 : Double(std::move(F)) {
1117 assert(&S == &PPCDoubleDouble());
1118 }
1119
1120 template <typename... ArgTypes>
1121 Storage(const fltSemantics &Semantics, ArgTypes &&... Args) {
1122 if (usesLayout<IEEEFloat>(Semantics)) {
1123 new (&IEEE) IEEEFloat(Semantics, std::forward<ArgTypes>(Args)...);
1124 return;
1125 }
1126 if (usesLayout<DoubleAPFloat>(Semantics)) {
1127 new (&Double) DoubleAPFloat(Semantics, std::forward<ArgTypes>(Args)...);
1128 return;
1129 }
1130 llvm_unreachable("Unexpected semantics");
1131 }
1132
1133 LLVM_ABI ~Storage();
1134 LLVM_ABI Storage(const Storage &RHS);
1135 LLVM_ABI Storage(Storage &&RHS);
1136 LLVM_ABI Storage &operator=(const Storage &RHS);
1137 LLVM_ABI Storage &operator=(Storage &&RHS);
1138 } U;
1139
1140 template <typename T> static bool usesLayout(const fltSemantics &Semantics) {
1141 static_assert(std::is_same<T, IEEEFloat>::value ||
1142 std::is_same<T, DoubleAPFloat>::value);
1143 if (std::is_same<T, DoubleAPFloat>::value) {
1144 return &Semantics == &PPCDoubleDouble();
1145 }
1146 return &Semantics != &PPCDoubleDouble();
1147 }
1148
1149 IEEEFloat &getIEEE() {
1150 if (usesLayout<IEEEFloat>(*U.semantics))
1151 return U.IEEE;
1152 if (usesLayout<DoubleAPFloat>(*U.semantics))
1153 return U.Double.getFirst().U.IEEE;
1154 llvm_unreachable("Unexpected semantics");
1155 }
1156
1157 const IEEEFloat &getIEEE() const {
1158 if (usesLayout<IEEEFloat>(*U.semantics))
1159 return U.IEEE;
1160 if (usesLayout<DoubleAPFloat>(*U.semantics))
1161 return U.Double.getFirst().U.IEEE;
1162 llvm_unreachable("Unexpected semantics");
1163 }
1164
1165 void makeZero(bool Neg) { APFLOAT_DISPATCH_ON_SEMANTICS(makeZero(Neg)); }
1166
1167 void makeInf(bool Neg) { APFLOAT_DISPATCH_ON_SEMANTICS(makeInf(Neg)); }
1168
1169 void makeNaN(bool SNaN, bool Neg, const APInt *fill) {
1170 APFLOAT_DISPATCH_ON_SEMANTICS(makeNaN(SNaN, Neg, fill));
1171 }
1172
1173 void makeLargest(bool Neg) {
1174 APFLOAT_DISPATCH_ON_SEMANTICS(makeLargest(Neg));
1175 }
1176
1177 void makeSmallest(bool Neg) {
1178 APFLOAT_DISPATCH_ON_SEMANTICS(makeSmallest(Neg));
1179 }
1180
1181 void makeSmallestNormalized(bool Neg) {
1182 APFLOAT_DISPATCH_ON_SEMANTICS(makeSmallestNormalized(Neg));
1183 }
1184
1185 explicit APFloat(IEEEFloat F, const fltSemantics &S) : U(std::move(F), S) {}
1186 explicit APFloat(DoubleAPFloat F, const fltSemantics &S)
1187 : U(std::move(F), S) {}
1188
1189public:
1193 template <typename T,
1194 typename = std::enable_if_t<std::is_floating_point<T>::value>>
1195 APFloat(const fltSemantics &Semantics, T V) = delete;
1196 // TODO: Remove this constructor. This isn't faster than the first one.
1200 explicit APFloat(double d) : U(IEEEFloat(d), IEEEdouble()) {}
1201 explicit APFloat(float f) : U(IEEEFloat(f), IEEEsingle()) {}
1202 APFloat(const APFloat &RHS) = default;
1203 APFloat(APFloat &&RHS) = default;
1204
1205 ~APFloat() = default;
1206
1208
1209 /// Factory for Positive and Negative Zero.
1210 ///
1211 /// \param Negative True iff the number should be negative.
1212 static APFloat getZero(const fltSemantics &Sem, bool Negative = false) {
1213 APFloat Val(Sem, uninitialized);
1214 Val.makeZero(Negative);
1215 return Val;
1216 }
1217
1218 /// Factory for Positive and Negative One.
1219 ///
1220 /// \param Negative True iff the number should be negative.
1221 static APFloat getOne(const fltSemantics &Sem, bool Negative = false) {
1222 APFloat Val(Sem, 1U);
1223 if (Negative)
1224 Val.changeSign();
1225 return Val;
1226 }
1227
1228 /// Factory for Positive and Negative Infinity.
1229 ///
1230 /// \param Negative True iff the number should be negative.
1231 static APFloat getInf(const fltSemantics &Sem, bool Negative = false) {
1232 APFloat Val(Sem, uninitialized);
1233 Val.makeInf(Negative);
1234 return Val;
1235 }
1236
1237 /// Factory for NaN values.
1238 ///
1239 /// \param Negative - True iff the NaN generated should be negative.
1240 /// \param payload - The unspecified fill bits for creating the NaN, 0 by
1241 /// default. The value is truncated as necessary.
1242 static APFloat getNaN(const fltSemantics &Sem, bool Negative = false,
1243 uint64_t payload = 0) {
1244 if (payload) {
1245 APInt intPayload(64, payload);
1246 return getQNaN(Sem, Negative, &intPayload);
1247 } else {
1248 return getQNaN(Sem, Negative, nullptr);
1249 }
1250 }
1251
1252 /// Factory for QNaN values.
1253 static APFloat getQNaN(const fltSemantics &Sem, bool Negative = false,
1254 const APInt *payload = nullptr) {
1255 APFloat Val(Sem, uninitialized);
1256 Val.makeNaN(false, Negative, payload);
1257 return Val;
1258 }
1259
1260 /// Factory for SNaN values.
1261 static APFloat getSNaN(const fltSemantics &Sem, bool Negative = false,
1262 const APInt *payload = nullptr) {
1263 APFloat Val(Sem, uninitialized);
1264 Val.makeNaN(true, Negative, payload);
1265 return Val;
1266 }
1267
1268 /// Returns the largest finite number in the given semantics.
1269 ///
1270 /// \param Negative - True iff the number should be negative
1271 static APFloat getLargest(const fltSemantics &Sem, bool Negative = false) {
1272 APFloat Val(Sem, uninitialized);
1273 Val.makeLargest(Negative);
1274 return Val;
1275 }
1276
1277 /// Returns the smallest (by magnitude) finite number in the given semantics.
1278 /// Might be denormalized, which implies a relative loss of precision.
1279 ///
1280 /// \param Negative - True iff the number should be negative
1281 static APFloat getSmallest(const fltSemantics &Sem, bool Negative = false) {
1282 APFloat Val(Sem, uninitialized);
1283 Val.makeSmallest(Negative);
1284 return Val;
1285 }
1286
1287 /// Returns the smallest (by magnitude) normalized finite number in the given
1288 /// semantics.
1289 ///
1290 /// \param Negative - True iff the number should be negative
1291 static APFloat getSmallestNormalized(const fltSemantics &Sem,
1292 bool Negative = false) {
1293 APFloat Val(Sem, uninitialized);
1294 Val.makeSmallestNormalized(Negative);
1295 return Val;
1296 }
1297
1298 /// Returns a float which is bitcasted from an all one value int.
1299 ///
1300 /// \param Semantics - type float semantics
1302
1303 /// Returns true if the given semantics has actual significand.
1304 ///
1305 /// \param Sem - type float semantics
1306 static bool hasSignificand(const fltSemantics &Sem) {
1307 return &Sem != &Float8E8M0FNU();
1308 }
1309
1310 /// Used to insert APFloat objects, or objects that contain APFloat objects,
1311 /// into FoldingSets.
1312 LLVM_ABI void Profile(FoldingSetNodeID &NID) const;
1313
1314 opStatus add(const APFloat &RHS, roundingMode RM) {
1315 assert(&getSemantics() == &RHS.getSemantics() &&
1316 "Should only call on two APFloats with the same semantics");
1317 if (usesLayout<IEEEFloat>(getSemantics()))
1318 return U.IEEE.add(RHS.U.IEEE, RM);
1319 if (usesLayout<DoubleAPFloat>(getSemantics()))
1320 return U.Double.add(RHS.U.Double, RM);
1321 llvm_unreachable("Unexpected semantics");
1322 }
1323 opStatus subtract(const APFloat &RHS, roundingMode RM) {
1324 assert(&getSemantics() == &RHS.getSemantics() &&
1325 "Should only call on two APFloats with the same semantics");
1326 if (usesLayout<IEEEFloat>(getSemantics()))
1327 return U.IEEE.subtract(RHS.U.IEEE, RM);
1328 if (usesLayout<DoubleAPFloat>(getSemantics()))
1329 return U.Double.subtract(RHS.U.Double, RM);
1330 llvm_unreachable("Unexpected semantics");
1331 }
1332 opStatus multiply(const APFloat &RHS, roundingMode RM) {
1333 assert(&getSemantics() == &RHS.getSemantics() &&
1334 "Should only call on two APFloats with the same semantics");
1335 if (usesLayout<IEEEFloat>(getSemantics()))
1336 return U.IEEE.multiply(RHS.U.IEEE, RM);
1337 if (usesLayout<DoubleAPFloat>(getSemantics()))
1338 return U.Double.multiply(RHS.U.Double, RM);
1339 llvm_unreachable("Unexpected semantics");
1340 }
1341 opStatus divide(const APFloat &RHS, roundingMode RM) {
1342 assert(&getSemantics() == &RHS.getSemantics() &&
1343 "Should only call on two APFloats with the same semantics");
1344 if (usesLayout<IEEEFloat>(getSemantics()))
1345 return U.IEEE.divide(RHS.U.IEEE, RM);
1346 if (usesLayout<DoubleAPFloat>(getSemantics()))
1347 return U.Double.divide(RHS.U.Double, RM);
1348 llvm_unreachable("Unexpected semantics");
1349 }
1350 opStatus remainder(const APFloat &RHS) {
1351 assert(&getSemantics() == &RHS.getSemantics() &&
1352 "Should only call on two APFloats with the same semantics");
1353 if (usesLayout<IEEEFloat>(getSemantics()))
1354 return U.IEEE.remainder(RHS.U.IEEE);
1355 if (usesLayout<DoubleAPFloat>(getSemantics()))
1356 return U.Double.remainder(RHS.U.Double);
1357 llvm_unreachable("Unexpected semantics");
1358 }
1359 opStatus mod(const APFloat &RHS) {
1360 assert(&getSemantics() == &RHS.getSemantics() &&
1361 "Should only call on two APFloats with the same semantics");
1362 if (usesLayout<IEEEFloat>(getSemantics()))
1363 return U.IEEE.mod(RHS.U.IEEE);
1364 if (usesLayout<DoubleAPFloat>(getSemantics()))
1365 return U.Double.mod(RHS.U.Double);
1366 llvm_unreachable("Unexpected semantics");
1367 }
1368 opStatus fusedMultiplyAdd(const APFloat &Multiplicand, const APFloat &Addend,
1369 roundingMode RM) {
1370 assert(&getSemantics() == &Multiplicand.getSemantics() &&
1371 "Should only call on APFloats with the same semantics");
1372 assert(&getSemantics() == &Addend.getSemantics() &&
1373 "Should only call on APFloats with the same semantics");
1374 if (usesLayout<IEEEFloat>(getSemantics()))
1375 return U.IEEE.fusedMultiplyAdd(Multiplicand.U.IEEE, Addend.U.IEEE, RM);
1376 if (usesLayout<DoubleAPFloat>(getSemantics()))
1377 return U.Double.fusedMultiplyAdd(Multiplicand.U.Double, Addend.U.Double,
1378 RM);
1379 llvm_unreachable("Unexpected semantics");
1380 }
1384
1385 // TODO: bool parameters are not readable and a source of bugs.
1386 // Do something.
1387 opStatus next(bool nextDown) {
1389 }
1390
1391 /// Negate an APFloat.
1392 APFloat operator-() const {
1393 APFloat Result(*this);
1394 Result.changeSign();
1395 return Result;
1396 }
1397
1398 /// Add two APFloats, rounding ties to the nearest even.
1399 /// No error checking.
1400 APFloat operator+(const APFloat &RHS) const {
1401 APFloat Result(*this);
1402 (void)Result.add(RHS, rmNearestTiesToEven);
1403 return Result;
1404 }
1405
1406 /// Subtract two APFloats, rounding ties to the nearest even.
1407 /// No error checking.
1408 APFloat operator-(const APFloat &RHS) const {
1409 APFloat Result(*this);
1410 (void)Result.subtract(RHS, rmNearestTiesToEven);
1411 return Result;
1412 }
1413
1414 /// Multiply two APFloats, rounding ties to the nearest even.
1415 /// No error checking.
1416 APFloat operator*(const APFloat &RHS) const {
1417 APFloat Result(*this);
1418 (void)Result.multiply(RHS, rmNearestTiesToEven);
1419 return Result;
1420 }
1421
1422 /// Divide the first APFloat by the second, rounding ties to the nearest even.
1423 /// No error checking.
1424 APFloat operator/(const APFloat &RHS) const {
1425 APFloat Result(*this);
1426 (void)Result.divide(RHS, rmNearestTiesToEven);
1427 return Result;
1428 }
1429
1431 void clearSign() {
1432 if (isNegative())
1433 changeSign();
1434 }
1435 void copySign(const APFloat &RHS) {
1436 if (isNegative() != RHS.isNegative())
1437 changeSign();
1438 }
1439
1440 /// A static helper to produce a copy of an APFloat value with its sign
1441 /// copied from some other APFloat.
1442 static APFloat copySign(APFloat Value, const APFloat &Sign) {
1443 Value.copySign(Sign);
1444 return Value;
1445 }
1446
1447 /// Assuming this is an IEEE-754 NaN value, quiet its signaling bit.
1448 /// This preserves the sign and payload bits.
1449 [[nodiscard]] APFloat makeQuiet() const {
1450 APFloat Result(*this);
1451 Result.getIEEE().makeQuiet();
1452 return Result;
1453 }
1454
1455 LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM,
1456 bool *losesInfo);
1457 // Convert a floating point number to an integer according to the
1458 // rounding mode. We provide deterministic values in case of an invalid
1459 // operation exception, namely zero for NaNs and the minimal or maximal value
1460 // respectively for underflow or overflow.
1461 // The *IsExact output tells whether the result is exact, in the sense that
1462 // converting it back to the original floating point type produces the
1463 // original value. This is almost equivalent to result==opOK, except for
1464 // negative zeroes.
1466 unsigned int Width, bool IsSigned, roundingMode RM,
1467 bool *IsExact) const {
1469 convertToInteger(Input, Width, IsSigned, RM, IsExact));
1470 }
1471 // Same as convertToInteger(integerPart*, ...), except the result is returned
1472 // in an APSInt, whose initial bit-width and signed-ness are used to determine
1473 // the precision of the conversion.
1474 LLVM_ABI opStatus convertToInteger(APSInt &Result, roundingMode RM,
1475 bool *IsExact) const;
1476
1477 // Convert a two's complement integer Input to a floating point number,
1478 // rounding according to RM. IsSigned is true if the integer is signed,
1479 // in which case it must be sign-extended.
1480 opStatus convertFromAPInt(const APInt &Input, bool IsSigned,
1481 roundingMode RM) {
1483 }
1484
1485 /// Fill this APFloat with the result of a string conversion.
1486 ///
1487 /// The following strings are accepted for conversion purposes:
1488 /// * Decimal floating-point literals (e.g., `0.1e-5`)
1489 /// * Hexadecimal floating-point literals (e.g., `0x1.0p-5`)
1490 /// * Positive infinity via "inf", "INFINITY", "Inf", "+Inf", or "+inf".
1491 /// * Negative infinity via "-inf", "-INFINITY", or "-Inf".
1492 /// * Quiet NaNs via "nan", "NaN", "nan(...)", or "NaN(...)", where the
1493 /// "..." is either a decimal or hexadecimal integer representing the
1494 /// payload. A negative sign may be optionally provided.
1495 /// * Signaling NaNs via "snan", "sNaN", "snan(...)", or "sNaN(...)", where
1496 /// the "..." is either a decimal or hexadecimal integer representing the
1497 /// payload. A negative sign may be optionally provided.
1498 ///
1499 /// If the input string is none of these forms, then an error is returned.
1500 ///
1501 /// If a floating-point exception occurs during conversion, then no error is
1502 /// returned, and the exception is indicated via opStatus.
1507
1508 /// Converts this APFloat to host double value.
1509 ///
1510 /// \pre The APFloat must be built using semantics, that can be represented by
1511 /// the host double type without loss of precision. It can be IEEEdouble and
1512 /// shorter semantics, like IEEEsingle and others.
1513 LLVM_ABI double convertToDouble() const;
1514
1515 /// Converts this APFloat to host float value.
1516 ///
1517 /// \pre The APFloat must be built using semantics, that can be represented by
1518 /// the host float type without loss of precision. It can be IEEEquad and
1519 /// shorter semantics, like IEEEdouble and others.
1520#ifdef HAS_IEE754_FLOAT128
1521 LLVM_ABI float128 convertToQuad() const;
1522#endif
1523
1524 /// Converts this APFloat to host float value.
1525 ///
1526 /// \pre The APFloat must be built using semantics, that can be represented by
1527 /// the host float type without loss of precision. It can be IEEEsingle and
1528 /// shorter semantics, like IEEEhalf.
1529 LLVM_ABI float convertToFloat() const;
1530
1531 bool operator==(const APFloat &RHS) const { return compare(RHS) == cmpEqual; }
1532
1533 bool operator!=(const APFloat &RHS) const { return compare(RHS) != cmpEqual; }
1534
1535 bool operator<(const APFloat &RHS) const {
1536 return compare(RHS) == cmpLessThan;
1537 }
1538
1539 bool operator>(const APFloat &RHS) const {
1540 return compare(RHS) == cmpGreaterThan;
1541 }
1542
1543 bool operator<=(const APFloat &RHS) const {
1544 cmpResult Res = compare(RHS);
1545 return Res == cmpLessThan || Res == cmpEqual;
1546 }
1547
1548 bool operator>=(const APFloat &RHS) const {
1549 cmpResult Res = compare(RHS);
1550 return Res == cmpGreaterThan || Res == cmpEqual;
1551 }
1552
1553 // IEEE comparison with another floating point number (NaNs compare unordered,
1554 // 0==-0).
1555 cmpResult compare(const APFloat &RHS) const {
1556 assert(&getSemantics() == &RHS.getSemantics() &&
1557 "Should only compare APFloats with the same semantics");
1558 if (usesLayout<IEEEFloat>(getSemantics()))
1559 return U.IEEE.compare(RHS.U.IEEE);
1560 if (usesLayout<DoubleAPFloat>(getSemantics()))
1561 return U.Double.compare(RHS.U.Double);
1562 llvm_unreachable("Unexpected semantics");
1563 }
1564
1565 // Compares the absolute value of this APFloat with another. Both operands
1566 // must be finite non-zero.
1567 cmpResult compareAbsoluteValue(const APFloat &RHS) const {
1568 assert(&getSemantics() == &RHS.getSemantics() &&
1569 "Should only compare APFloats with the same semantics");
1570 if (usesLayout<IEEEFloat>(getSemantics()))
1571 return U.IEEE.compareAbsoluteValue(RHS.U.IEEE);
1572 if (usesLayout<DoubleAPFloat>(getSemantics()))
1573 return U.Double.compareAbsoluteValue(RHS.U.Double);
1574 llvm_unreachable("Unexpected semantics");
1575 }
1576
1577 bool bitwiseIsEqual(const APFloat &RHS) const {
1578 if (&getSemantics() != &RHS.getSemantics())
1579 return false;
1580 if (usesLayout<IEEEFloat>(getSemantics()))
1581 return U.IEEE.bitwiseIsEqual(RHS.U.IEEE);
1582 if (usesLayout<DoubleAPFloat>(getSemantics()))
1583 return U.Double.bitwiseIsEqual(RHS.U.Double);
1584 llvm_unreachable("Unexpected semantics");
1585 }
1586
1587 /// We don't rely on operator== working on double values, as
1588 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
1589 /// As such, this method can be used to do an exact bit-for-bit comparison of
1590 /// two floating point values.
1591 ///
1592 /// We leave the version with the double argument here because it's just so
1593 /// convenient to write "2.0" and the like. Without this function we'd
1594 /// have to duplicate its logic everywhere it's called.
1595 bool isExactlyValue(double V) const {
1596 bool ignored;
1597 APFloat Tmp(V);
1599 return bitwiseIsEqual(Tmp);
1600 }
1601
1602 unsigned int convertToHexString(char *DST, unsigned int HexDigits,
1603 bool UpperCase, roundingMode RM) const {
1605 convertToHexString(DST, HexDigits, UpperCase, RM));
1606 }
1607
1608 bool isZero() const { return getCategory() == fcZero; }
1609 bool isInfinity() const { return getCategory() == fcInfinity; }
1610 bool isNaN() const { return getCategory() == fcNaN; }
1611
1612 bool isNegative() const { return getIEEE().isNegative(); }
1614 bool isSignaling() const { return getIEEE().isSignaling(); }
1615
1616 bool isNormal() const { return !isDenormal() && isFiniteNonZero(); }
1617 bool isFinite() const { return !isNaN() && !isInfinity(); }
1618
1619 fltCategory getCategory() const { return getIEEE().getCategory(); }
1620 const fltSemantics &getSemantics() const { return *U.semantics; }
1621 bool isNonZero() const { return !isZero(); }
1622 bool isFiniteNonZero() const { return isFinite() && !isZero(); }
1623 bool isPosZero() const { return isZero() && !isNegative(); }
1624 bool isNegZero() const { return isZero() && isNegative(); }
1625 bool isPosInfinity() const { return isInfinity() && !isNegative(); }
1626 bool isNegInfinity() const { return isInfinity() && isNegative(); }
1630
1634
1635 /// If the value is a NaN value, return an integer containing the payload of
1636 /// this value. This payload will include the quiet bit as part of the
1637 /// returned integer.
1639 assert(isNaN() && "Can only call this on a NaN value");
1641 }
1642
1643 /// Return the FPClassTest which will return true for the value.
1645
1646 APFloat &operator=(const APFloat &RHS) = default;
1647 APFloat &operator=(APFloat &&RHS) = default;
1648
1649 void toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision = 0,
1650 unsigned FormatMaxPadding = 3, bool TruncateZero = true) const {
1652 toString(Str, FormatPrecision, FormatMaxPadding, TruncateZero));
1653 }
1654
1655 /// Format the value as toString does and return true if the string parses
1656 /// back bitwise equal. Non-finite spellings ("+Inf", "NaN") parse back
1657 /// here but may not fit a caller's grammar.
1659 unsigned FormatPrecision = 0,
1660 unsigned FormatMaxPadding = 3,
1661 bool TruncateZero = true) const;
1662
1663 /// Like toString, but picks the smallest FormatPrecision whose output
1664 /// parses back bitwise equal: "3.14", not "3.1400000000000001". An integer
1665 /// in fixed notation keeps its digits: "100", not "1.0E+2".
1667 unsigned FormatMaxPadding = 3,
1668 bool TruncateZero = true) const;
1669
1670 LLVM_ABI void print(raw_ostream &) const;
1671
1672#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1673 LLVM_DUMP_METHOD void dump() const;
1674#endif
1675
1676 /// If this value is normal and has an exact, normal, multiplicative inverse,
1677 /// store it in inv and return true.
1678 LLVM_ABI bool getExactInverse(APFloat *Inv) const;
1679
1680 // If this is an exact power of two, return the exponent while ignoring the
1681 // sign bit. If it's not an exact power of 2, return INT_MIN
1686
1687 // If this is an exact power of two, return the exponent. If it's not an exact
1688 // power of 2, return INT_MIN
1690 int getExactLog2() const {
1691 return isNegative() ? INT_MIN : getExactLog2Abs();
1692 }
1693
1694 // Returns true if this value is exactly 2^N.
1696 bool isPowerOf2(int N) const { return N != INT_MIN && getExactLog2() == N; }
1697
1698 // Returns true if this value is exactly -(2^N).
1700 bool isNegPowerOf2(int N) const {
1701 return N != INT_MIN && isNegative() && getExactLog2Abs() == N;
1702 }
1703
1704 // Returns true if this value is exactly +1.0.
1705 LLVM_READONLY bool isOne() const { return isPowerOf2(0); }
1706
1707 // Returns true if this value is exactly -1.0.
1708 LLVM_READONLY bool isMinusOne() const { return isNegPowerOf2(0); }
1709
1710 LLVM_ABI friend hash_code hash_value(const APFloat &Arg);
1711 friend int ilogb(const APFloat &Arg);
1712 friend APFloat scalbn(APFloat X, int Exp, roundingMode RM);
1713 friend APFloat frexp(const APFloat &X, int &Exp, roundingMode RM);
1714 friend IEEEFloat;
1715 friend DoubleAPFloat;
1716};
1717
1718static_assert(sizeof(APFloat) == sizeof(detail::IEEEFloat),
1719 "Empty base class optimization is not performed.");
1720
1721/// See friend declarations above.
1722///
1723/// These additional declarations are required in order to compile LLVM with IBM
1724/// xlC compiler.
1726
1727/// Returns the exponent of the internal representation of the APFloat.
1728///
1729/// Because the radix of APFloat is 2, this is equivalent to floor(log2(x)).
1730/// For special APFloat values, this returns special error codes:
1731///
1732/// NaN -> \c IEK_NaN
1733/// 0 -> \c IEK_Zero
1734/// Inf -> \c IEK_Inf
1735///
1736inline int ilogb(const APFloat &Arg) {
1737 if (APFloat::usesLayout<detail::IEEEFloat>(Arg.getSemantics()))
1738 return ilogb(Arg.U.IEEE);
1739 if (APFloat::usesLayout<detail::DoubleAPFloat>(Arg.getSemantics()))
1740 return ilogb(Arg.U.Double);
1741 llvm_unreachable("Unexpected semantics");
1742}
1743
1744/// Returns: X * 2^Exp for integral exponents.
1746 if (APFloat::usesLayout<detail::IEEEFloat>(X.getSemantics()))
1747 return APFloat(scalbn(X.U.IEEE, Exp, RM), X.getSemantics());
1748 if (APFloat::usesLayout<detail::DoubleAPFloat>(X.getSemantics()))
1749 return APFloat(scalbn(X.U.Double, Exp, RM), X.getSemantics());
1750 llvm_unreachable("Unexpected semantics");
1751}
1752
1753/// Equivalent of C standard library function.
1754///
1755/// While the C standard says Exp is an unspecified value for infinity and nan,
1756/// this returns INT_MAX for infinities, and INT_MIN for NaNs.
1757inline APFloat frexp(const APFloat &X, int &Exp, APFloat::roundingMode RM) {
1758 if (APFloat::usesLayout<detail::IEEEFloat>(X.getSemantics()))
1759 return APFloat(frexp(X.U.IEEE, Exp, RM), X.getSemantics());
1760 if (APFloat::usesLayout<detail::DoubleAPFloat>(X.getSemantics()))
1761 return APFloat(frexp(X.U.Double, Exp, RM), X.getSemantics());
1762 llvm_unreachable("Unexpected semantics");
1763}
1764/// Returns the absolute value of the argument.
1766 X.clearSign();
1767 return X;
1768}
1769
1770/// Returns the negated value of the argument.
1772 X.changeSign();
1773 return X;
1774}
1775
1776/// Implements IEEE-754 2008 minNum semantics. Returns the smaller of the
1777/// 2 arguments if both are not NaN. If either argument is a qNaN, returns the
1778/// other argument. If either argument is sNaN, return a qNaN.
1779/// -0 is treated as ordered less than +0.
1781inline APFloat minnum(const APFloat &A, const APFloat &B) {
1782 if (A.isSignaling())
1783 return A.makeQuiet();
1784 if (B.isSignaling())
1785 return B.makeQuiet();
1786 if (A.isNaN())
1787 return B;
1788 if (B.isNaN())
1789 return A;
1790 if (A.isZero() && B.isZero() && (A.isNegative() != B.isNegative()))
1791 return A.isNegative() ? A : B;
1792 return B < A ? B : A;
1793}
1794
1795/// Implements IEEE-754 2008 maxNum semantics. Returns the larger of the
1796/// 2 arguments if both are not NaN. If either argument is a qNaN, returns the
1797/// other argument. If either argument is sNaN, return a qNaN.
1798/// +0 is treated as ordered greater than -0.
1800inline APFloat maxnum(const APFloat &A, const APFloat &B) {
1801 if (A.isSignaling())
1802 return A.makeQuiet();
1803 if (B.isSignaling())
1804 return B.makeQuiet();
1805 if (A.isNaN())
1806 return B;
1807 if (B.isNaN())
1808 return A;
1809 if (A.isZero() && B.isZero() && (A.isNegative() != B.isNegative()))
1810 return A.isNegative() ? B : A;
1811 return A < B ? B : A;
1812}
1813
1814/// Implements IEEE 754-2019 minimum semantics. Returns the smaller of 2
1815/// arguments, returning a quiet NaN if an argument is a NaN and treating -0
1816/// as less than +0.
1818inline APFloat minimum(const APFloat &A, const APFloat &B) {
1819 if (A.isNaN())
1820 return A.makeQuiet();
1821 if (B.isNaN())
1822 return B.makeQuiet();
1823 if (A.isZero() && B.isZero() && (A.isNegative() != B.isNegative()))
1824 return A.isNegative() ? A : B;
1825 return B < A ? B : A;
1826}
1827
1828/// Implements IEEE 754-2019 minimumNumber semantics. Returns the smaller
1829/// of 2 arguments, not propagating NaNs and treating -0 as less than +0.
1831inline APFloat minimumnum(const APFloat &A, const APFloat &B) {
1832 if (A.isNaN())
1833 return B.isNaN() ? B.makeQuiet() : B;
1834 if (B.isNaN())
1835 return A;
1836 if (A.isZero() && B.isZero() && (A.isNegative() != B.isNegative()))
1837 return A.isNegative() ? A : B;
1838 return B < A ? B : A;
1839}
1840
1841/// Implements IEEE 754-2019 maximum semantics. Returns the larger of 2
1842/// arguments, returning a quiet NaN if an argument is a NaN and treating -0
1843/// as less than +0.
1845inline APFloat maximum(const APFloat &A, const APFloat &B) {
1846 if (A.isNaN())
1847 return A.makeQuiet();
1848 if (B.isNaN())
1849 return B.makeQuiet();
1850 if (A.isZero() && B.isZero() && (A.isNegative() != B.isNegative()))
1851 return A.isNegative() ? B : A;
1852 return A < B ? B : A;
1853}
1854
1855/// Implements IEEE 754-2019 maximumNumber semantics. Returns the larger
1856/// of 2 arguments, not propagating NaNs and treating -0 as less than +0.
1858inline APFloat maximumnum(const APFloat &A, const APFloat &B) {
1859 if (A.isNaN())
1860 return B.isNaN() ? B.makeQuiet() : B;
1861 if (B.isNaN())
1862 return A;
1863 if (A.isZero() && B.isZero() && (A.isNegative() != B.isNegative()))
1864 return A.isNegative() ? B : A;
1865 return A < B ? B : A;
1866}
1867
1868/// Implement IEEE 754-2019 exp functions
1870LLVM_ABI std::optional<APFloat>
1871exp(const APFloat &X, RoundingMode RM = APFloat::rmNearestTiesToEven,
1872 APFloat::opStatus *Status = nullptr);
1873
1875 V.print(OS);
1876 return OS;
1877}
1878
1879// We want the following functions to be available in the header for inlining.
1880// We cannot define them inline in the class definition of `DoubleAPFloat`
1881// because doing so would instantiate `std::unique_ptr<APFloat[]>` before
1882// `APFloat` is defined, and that would be undefined behavior.
1883namespace detail {
1884
1886 if (this != &RHS) {
1887 this->~DoubleAPFloat();
1888 new (this) DoubleAPFloat(std::move(RHS));
1889 }
1890 return *this;
1891}
1892
1893APFloat &DoubleAPFloat::getFirst() { return Floats[0]; }
1894const APFloat &DoubleAPFloat::getFirst() const { return Floats[0]; }
1895APFloat &DoubleAPFloat::getSecond() { return Floats[1]; }
1896const APFloat &DoubleAPFloat::getSecond() const { return Floats[1]; }
1897
1898inline DoubleAPFloat::~DoubleAPFloat() { delete[] Floats; }
1899
1900} // namespace detail
1901
1902} // namespace llvm
1903
1904#undef APFLOAT_DISPATCH_ON_SEMANTICS
1905#endif // LLVM_ADT_APFLOAT_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
#define APFLOAT_DISPATCH_ON_SEMANTICS(METHOD_CALL)
Definition APFloat.h:27
This file implements a class to represent arbitrary precision integral constant values and operations...
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_ABI
Definition Compiler.h:211
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:702
#define LLVM_READONLY
Definition Compiler.h:334
Utilities for dealing with flags related to floating point properties and mode controls.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Load MIR Sample Profile
#define T
static void initialize(TargetLibraryInfoImpl &TLI, const Triple &T, const llvm::StringTable &StandardNames, VectorLibrary VecLib)
Initialize the set of available library functions based on the specified target triple.
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
uninitializedTag
Convenience enum used to construct an uninitialized APFloat.
Definition APFloat.h:414
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
IlogbErrorKinds
Enumeration of ilogb error results.
Definition APFloat.h:419
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
static APFloat getSNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for SNaN values.
Definition APFloat.h:1261
LLVM_READONLY bool isNegPowerOf2(int N) const
Definition APFloat.h:1700
opStatus divide(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1341
APFloat & operator=(APFloat &&RHS)=default
bool isFiniteNonZero() const
Definition APFloat.h:1622
APFloat(const APFloat &RHS)=default
void copySign(const APFloat &RHS)
Definition APFloat.h:1435
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:6101
LLVM_READONLY int getExactLog2Abs() const
Definition APFloat.h:1683
opStatus subtract(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1323
bool bitwiseIsEqual(const APFloat &RHS) const
Definition APFloat.h:1577
bool isNegative() const
Definition APFloat.h:1612
~APFloat()=default
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
APFloat operator+(const APFloat &RHS) const
Add two APFloats, rounding ties to the nearest even.
Definition APFloat.h:1400
friend DoubleAPFloat
Definition APFloat.h:1715
LLVM_ABI double convertToDouble() const
Converts this APFloat to host double value.
Definition APFloat.cpp:6334
bool isPosInfinity() const
Definition APFloat.h:1625
APFloat(APFloat &&RHS)=default
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
bool isExactlyValue(double V) const
We don't rely on operator== working on double values, as it returns true for things that are clearly ...
Definition APFloat.h:1595
opStatus add(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1314
LLVM_READONLY int getExactLog2() const
Definition APFloat.h:1690
APFloat(double d)
Definition APFloat.h:1200
APFloat & operator=(const APFloat &RHS)=default
LLVM_READONLY bool isPowerOf2(int N) const
Definition APFloat.h:1696
static LLVM_ABI APFloat getAllOnesValue(const fltSemantics &Semantics)
Returns a float which is bitcasted from an all one value int.
Definition APFloat.cpp:6127
LLVM_ABI friend hash_code hash_value(const APFloat &Arg)
See friend declarations above.
Definition APFloat.cpp:6015
APFloat(const fltSemantics &Semantics, integerPart I)
Definition APFloat.h:1192
bool operator!=(const APFloat &RHS) const
Definition APFloat.h:1533
APFloat(const fltSemantics &Semantics, T V)=delete
const fltSemantics & getSemantics() const
Definition APFloat.h:1620
APFloat operator-(const APFloat &RHS) const
Subtract two APFloats, rounding ties to the nearest even.
Definition APFloat.h:1408
APFloat operator*(const APFloat &RHS) const
Multiply two APFloats, rounding ties to the nearest even.
Definition APFloat.h:1416
APFloat(const fltSemantics &Semantics)
Definition APFloat.h:1190
bool isNonZero() const
Definition APFloat.h:1621
void clearSign()
Definition APFloat.h:1431
bool operator<(const APFloat &RHS) const
Definition APFloat.h:1535
bool isFinite() const
Definition APFloat.h:1617
APFloat makeQuiet() const
Assuming this is an IEEE-754 NaN value, quiet its signaling bit.
Definition APFloat.h:1449
bool isNaN() const
Definition APFloat.h:1610
opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM)
Definition APFloat.h:1480
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
opStatus multiply(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1332
LLVM_ABI float convertToFloat() const
Converts this APFloat to host float value.
Definition APFloat.cpp:6362
bool isSignaling() const
Definition APFloat.h:1614
bool operator>(const APFloat &RHS) const
Definition APFloat.h:1539
opStatus fusedMultiplyAdd(const APFloat &Multiplicand, const APFloat &Addend, roundingMode RM)
Definition APFloat.h:1368
APFloat operator/(const APFloat &RHS) const
Divide the first APFloat by the second, rounding ties to the nearest even.
Definition APFloat.h:1424
opStatus remainder(const APFloat &RHS)
Definition APFloat.h:1350
APFloat operator-() const
Negate an APFloat.
Definition APFloat.h:1392
bool isZero() const
Definition APFloat.h:1608
LLVM_READONLY bool isOne() const
Definition APFloat.h:1705
static APFloat getSmallestNormalized(const fltSemantics &Sem, bool Negative=false)
Returns the smallest (by magnitude) normalized finite number in the given semantics.
Definition APFloat.h:1291
APInt bitcastToAPInt() const
Definition APFloat.h:1504
bool isLargest() const
Definition APFloat.h:1628
friend APFloat frexp(const APFloat &X, int &Exp, roundingMode RM)
bool isSmallest() const
Definition APFloat.h:1627
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)
bool operator>=(const APFloat &RHS) const
Definition APFloat.h:1548
bool needsCleanup() const
Definition APFloat.h:1207
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
bool operator==(const APFloat &RHS) const
Definition APFloat.h:1531
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
bool isPosZero() const
Definition APFloat.h:1623
APInt getNaNPayload() const
If the value is a NaN value, return an integer containing the payload of this value.
Definition APFloat.h:1638
friend int ilogb(const APFloat &Arg)
Returns the exponent of the internal representation of the APFloat.
Definition APFloat.h:1736
LLVM_ABI Expected< opStatus > convertFromString(StringRef, roundingMode)
Fill this APFloat with the result of a string conversion.
Definition APFloat.cpp:6010
fltCategory getCategory() const
Definition APFloat.h:1619
APFloat(const fltSemantics &Semantics, uninitializedTag)
Definition APFloat.h:1197
bool isInteger() const
Definition APFloat.h:1629
bool isNegInfinity() const
Definition APFloat.h:1626
friend IEEEFloat
Definition APFloat.h:1714
LLVM_DUMP_METHOD void dump() const
Definition APFloat.cpp:6312
bool isNegZero() const
Definition APFloat.h:1624
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
static APFloat copySign(APFloat Value, const APFloat &Sign)
A static helper to produce a copy of an APFloat value with its sign copied from some other APFloat.
Definition APFloat.h:1442
LLVM_READONLY bool isMinusOne() const
Definition APFloat.h:1708
APFloat(float f)
Definition APFloat.h:1201
opStatus roundToIntegral(roundingMode RM)
Definition APFloat.h:1381
void changeSign()
Definition APFloat.h:1430
static APFloat getNaN(const fltSemantics &Sem, bool Negative=false, uint64_t payload=0)
Factory for NaN values.
Definition APFloat.h:1242
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
cmpResult compare(const APFloat &RHS) const
Definition APFloat.h:1555
bool isSmallestNormalized() const
Definition APFloat.h:1631
APFloat(const fltSemantics &Semantics, const APInt &I)
Definition APFloat.h:1199
bool isInfinity() const
Definition APFloat.h:1609
bool operator<=(const APFloat &RHS) const
Definition APFloat.h:1543
Class for arbitrary precision integers.
Definition APInt.h:78
uint64_t WordType
Definition APInt.h:80
static constexpr unsigned APINT_BITS_PER_WORD
Bits in a word.
Definition APInt.h:86
An arbitrary precision integer that knows its signedness.
Definition APSInt.h:24
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
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
LLVM Value Representation.
Definition Value.h:75
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
bool needsCleanup() const
Definition APFloat.h:892
LLVM_ABI bool isNegative() const
Definition APFloat.cpp:5280
LLVM_ABI opStatus add(const DoubleAPFloat &RHS, roundingMode RM)
Definition APFloat.cpp:4994
LLVM_ABI friend DoubleAPFloat frexp(const DoubleAPFloat &X, int &Exp, roundingMode)
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 isNonZero() const
Definition APFloat.h:626
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
LLVM_ABI friend hash_code hash_value(const IEEEFloat &Arg)
Overload to compute a hash code for an APFloat value.
Definition APFloat.cpp:3740
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
bool isNormal() const
IEEE-754R isNormal: Returns true if and only if the current value is normal.
Definition APFloat.h:595
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
friend class IEEEFloatUnitTestHelper
Definition APFloat.h:841
friend void initFromAPIntForSemantics(FloatRepr &, const APInt &)
Definition APFloat.cpp:100
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
friend APInt bitcastForSemantics(const FloatRepr &R)
Definition APFloat.cpp:93
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
bool isPosZero() const
Definition APFloat.h:628
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
bool operator==(const IEEEFloat &) const =delete
The definition of equality is not straightforward for floating point, so we won't use operator==.
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 friend IEEEFloat frexp(const IEEEFloat &X, int &Exp, roundingMode)
Definition APFloat.cpp:4768
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
bool isNegZero() const
Definition APFloat.h:629
An opaque object representing a hash code.
Definition Hashing.h:77
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
static constexpr opStatus opInexact
Definition APFloat.h:490
static constexpr fltCategory fcNaN
Definition APFloat.h:492
static constexpr opStatus opDivByZero
Definition APFloat.h:487
static constexpr opStatus opOverflow
Definition APFloat.h:488
static constexpr cmpResult cmpLessThan
Definition APFloat.h:482
static constexpr roundingMode rmTowardPositive
Definition APFloat.h:478
static constexpr uninitializedTag uninitialized
Definition APFloat.h:472
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
APFloatBase::fltCategory fltCategory
Definition APFloat.h:470
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
APFloatBase::integerPart integerPart
Definition APFloat.h:465
This is an optimization pass for GlobalISel generic memory operations.
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
hash_code hash_value(const FixedPointSemantics &Val)
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
LLVM_READONLY APFloat maximum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 maximum semantics.
Definition APFloat.h:1845
static void assign(DXContainerYAML::SourceInfo::SectionHeader &Dst, const dxbc::SourceInfo::SectionHeader &Src)
int ilogb(const APFloat &Arg)
Returns the exponent of the internal representation of the APFloat.
Definition APFloat.h:1736
APFloat frexp(const APFloat &X, int &Exp, APFloat::roundingMode RM)
Equivalent of C standard library function.
Definition APFloat.h:1757
LLVM_READONLY APFloat maxnum(const APFloat &A, const APFloat &B)
Implements IEEE-754 2008 maxNum semantics.
Definition APFloat.h:1800
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
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_READONLY APFloat minimumnum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 minimumNumber semantics.
Definition APFloat.h:1831
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
static constexpr APFloatBase::ExponentType exponentNaN(const fltSemantics &semantics)
Definition APFloat.cpp:689
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
LLVM_READONLY APFloat minnum(const APFloat &A, const APFloat &B)
Implements IEEE-754 2008 minNum semantics.
Definition APFloat.h:1781
fltNonfiniteBehavior
Definition APFloat.h:967
RoundingMode
Rounding mode.
@ TowardZero
roundTowardZero.
@ NearestTiesToEven
roundTiesToEven.
@ TowardPositive
roundTowardPositive.
@ NearestTiesToAway
roundTiesToAway.
@ TowardNegative
roundTowardNegative.
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
static constexpr APFloatBase::ExponentType exponentInf(const fltSemantics &semantics)
Definition APFloat.cpp:684
APFloat neg(APFloat X)
Returns the negated value of the argument.
Definition APFloat.h:1771
LLVM_READONLY APFloat minimum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 minimum semantics.
Definition APFloat.h:1818
LLVM_READONLY APFloat maximumnum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 maximumNumber semantics.
Definition APFloat.h:1858
fltNanEncoding
Definition APFloat.h:991
#define N
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