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/// \brief
11/// This file declares a class to represent arbitrary precision floating point
12/// values and provide a variety of arithmetic operations on them.
13///
14//===----------------------------------------------------------------------===//
15
16#ifndef LLVM_ADT_APFLOAT_H
17#define LLVM_ADT_APFLOAT_H
18
19#include "llvm/ADT/APInt.h"
20#include "llvm/ADT/ArrayRef.h"
21#include "llvm/Support/ErrorHandling.h"
22#include <memory>
23
24#define APFLOAT_DISPATCH_ON_SEMANTICS(METHOD_CALL) \
25 do { \
26 if (usesLayout<IEEEFloat>(getSemantics())) \
27 return U.IEEE.METHOD_CALL; \
28 if (usesLayout<DoubleAPFloat>(getSemantics())) \
29 return U.Double.METHOD_CALL; \
30 llvm_unreachable("Unexpected semantics"); \
31 } while (false)
32
33namespace llvm {
34
35struct fltSemantics;
36class APSInt;
37class StringRef;
38class APFloat;
39class raw_ostream;
40
41template <typename T> class SmallVectorImpl;
42
43/// Enum that represents what fraction of the LSB truncated bits of an fp number
44/// represent.
45///
46/// This essentially combines the roles of guard and sticky bits.
47enum lostFraction { // Example of truncated bits:
48 lfExactlyZero, // 000000
49 lfLessThanHalf, // 0xxxxx x's not all zero
50 lfExactlyHalf, // 100000
51 lfMoreThanHalf // 1xxxxx x's not all zero
52};
53
54/// A self-contained host- and target-independent arbitrary-precision
55/// floating-point software implementation.
56///
57/// APFloat uses bignum integer arithmetic as provided by static functions in
58/// the APInt class. The library will work with bignum integers whose parts are
59/// any unsigned type at least 16 bits wide, but 64 bits is recommended.
60///
61/// Written for clarity rather than speed, in particular with a view to use in
62/// the front-end of a cross compiler so that target arithmetic can be correctly
63/// performed on the host. Performance should nonetheless be reasonable,
64/// particularly for its intended use. It may be useful as a base
65/// implementation for a run-time library during development of a faster
66/// target-specific one.
67///
68/// All 5 rounding modes in the IEEE-754R draft are handled correctly for all
69/// implemented operations. Currently implemented operations are add, subtract,
70/// multiply, divide, fused-multiply-add, conversion-to-float,
71/// conversion-to-integer and conversion-from-integer. New rounding modes
72/// (e.g. away from zero) can be added with three or four lines of code.
73///
74/// Four formats are built-in: IEEE single precision, double precision,
75/// quadruple precision, and x87 80-bit extended double (when operating with
76/// full extended precision). Adding a new format that obeys IEEE semantics
77/// only requires adding two lines of code: a declaration and definition of the
78/// format.
79///
80/// All operations return the status of that operation as an exception bit-mask,
81/// so multiple operations can be done consecutively with their results or-ed
82/// together. The returned status can be useful for compiler diagnostics; e.g.,
83/// inexact, underflow and overflow can be easily diagnosed on constant folding,
84/// and compiler optimizers can determine what exceptions would be raised by
85/// folding operations and optimize, or perhaps not optimize, accordingly.
86///
87/// At present, underflow tininess is detected after rounding; it should be
88/// straight forward to add support for the before-rounding case too.
89///
90/// The library reads hexadecimal floating point numbers as per C99, and
91/// correctly rounds if necessary according to the specified rounding mode.
92/// Syntax is required to have been validated by the caller. It also converts
93/// floating point numbers to hexadecimal text as per the C99 %a and %A
94/// conversions. The output precision (or alternatively the natural minimal
95/// precision) can be specified; if the requested precision is less than the
96/// natural precision the output is correctly rounded for the specified rounding
97/// mode.
98///
99/// It also reads decimal floating point numbers and correctly rounds according
100/// to the specified rounding mode.
101///
102/// Conversion to decimal text is not currently implemented.
103///
104/// Non-zero finite numbers are represented internally as a sign bit, a 16-bit
105/// signed exponent, and the significand as an array of integer parts. After
106/// normalization of a number of precision P the exponent is within the range of
107/// the format, and if the number is not denormal the P-th bit of the
108/// significand is set as an explicit integer bit. For denormals the most
109/// significant bit is shifted right so that the exponent is maintained at the
110/// format's minimum, so that the smallest denormal has just the least
111/// significant bit of the significand set. The sign of zeroes and infinities
112/// is significant; the exponent and significand of such numbers is not stored,
113/// but has a known implicit (deterministic) value: 0 for the significands, 0
114/// for zero exponent, all 1 bits for infinity exponent. For NaNs the sign and
115/// significand are deterministic, although not really meaningful, and preserved
116/// in non-conversion operations. The exponent is implicitly all 1 bits.
117///
118/// APFloat does not provide any exception handling beyond default exception
119/// handling. We represent Signaling NaNs via IEEE-754R 2008 6.2.1 should clause
120/// by encoding Signaling NaNs with the first bit of its trailing significand as
121/// 0.
122///
123/// TODO
124/// ====
125///
126/// Some features that may or may not be worth adding:
127///
128/// Binary to decimal conversion (hard).
129///
130/// Optional ability to detect underflow tininess before rounding.
131///
132/// New formats: x87 in single and double precision mode (IEEE apart from
133/// extended exponent range) (hard).
134///
135/// New operations: sqrt, IEEE remainder, C90 fmod, nexttoward.
136///
137
138// This is the common type definitions shared by APFloat and its internal
139// implementation classes. This struct should not define any non-static data
140// members.
141struct APFloatBase {
142 typedef APInt::WordType integerPart;
143 static const unsigned integerPartWidth = APInt::APINT_BITS_PER_WORD;
144
145 /// A signed type to represent a floating point numbers unbiased exponent.
146 typedef signed short ExponentType;
147
148 /// \name Floating Point Semantics.
149 /// @{
150
151 static const fltSemantics &IEEEhalf() LLVM_READNONE;
152 static const fltSemantics &IEEEsingle() LLVM_READNONE;
153 static const fltSemantics &IEEEdouble() LLVM_READNONE;
154 static const fltSemantics &IEEEquad() LLVM_READNONE;
155 static const fltSemantics &PPCDoubleDouble() LLVM_READNONE;
156 static const fltSemantics &x87DoubleExtended() LLVM_READNONE;
157
158 /// A Pseudo fltsemantic used to construct APFloats that cannot conflict with
159 /// anything real.
160 static const fltSemantics &Bogus() LLVM_READNONE;
161
162 /// @}
163
164 /// IEEE-754R 5.11: Floating Point Comparison Relations.
165 enum cmpResult {
166 cmpLessThan,
167 cmpEqual,
168 cmpGreaterThan,
169 cmpUnordered
170 };
171
172 /// IEEE-754R 4.3: Rounding-direction attributes.
173 enum roundingMode {
174 rmNearestTiesToEven,
175 rmTowardPositive,
176 rmTowardNegative,
177 rmTowardZero,
178 rmNearestTiesToAway
179 };
180
181 /// IEEE-754R 7: Default exception handling.
182 ///
183 /// opUnderflow or opOverflow are always returned or-ed with opInexact.
184 enum opStatus {
185 opOK = 0x00,
186 opInvalidOp = 0x01,
187 opDivByZero = 0x02,
188 opOverflow = 0x04,
189 opUnderflow = 0x08,
190 opInexact = 0x10
191 };
192
193 /// Category of internally-represented number.
194 enum fltCategory {
195 fcInfinity,
196 fcNaN,
197 fcNormal,
198 fcZero
199 };
200
201 /// Convenience enum used to construct an uninitialized APFloat.
202 enum uninitializedTag {
203 uninitialized
204 };
205
206 /// Enumeration of \c ilogb error results.
207 enum IlogbErrorKinds {
208 IEK_Zero = INT_MIN + 1,
209 IEK_NaN = INT_MIN,
210 IEK_Inf = INT_MAX
211 };
212
213 static unsigned int semanticsPrecision(const fltSemantics &);
214 static ExponentType semanticsMinExponent(const fltSemantics &);
215 static ExponentType semanticsMaxExponent(const fltSemantics &);
216 static unsigned int semanticsSizeInBits(const fltSemantics &);
217
218 /// Returns the size of the floating point number (in bits) in the given
219 /// semantics.
220 static unsigned getSizeInBits(const fltSemantics &Sem);
221};
222
223namespace detail {
224
225class IEEEFloat final : public APFloatBase {
226public:
227 /// \name Constructors
228 /// @{
229
230 IEEEFloat(const fltSemantics &); // Default construct to 0.0
231 IEEEFloat(const fltSemantics &, integerPart);
232 IEEEFloat(const fltSemantics &, uninitializedTag);
233 IEEEFloat(const fltSemantics &, const APInt &);
234 explicit IEEEFloat(double d);
235 explicit IEEEFloat(float f);
236 IEEEFloat(const IEEEFloat &);
237 IEEEFloat(IEEEFloat &&);
238 ~IEEEFloat();
239
240 /// @}
241
242 /// Returns whether this instance allocated memory.
243 bool needsCleanup() const { return partCount() > 1; }
244
245 /// \name Convenience "constructors"
246 /// @{
247
248 /// @}
249
250 /// \name Arithmetic
251 /// @{
252
253 opStatus add(const IEEEFloat &, roundingMode);
254 opStatus subtract(const IEEEFloat &, roundingMode);
255 opStatus multiply(const IEEEFloat &, roundingMode);
256 opStatus divide(const IEEEFloat &, roundingMode);
257 /// IEEE remainder.
258 opStatus remainder(const IEEEFloat &);
259 /// C fmod, or llvm frem.
260 opStatus mod(const IEEEFloat &);
261 opStatus fusedMultiplyAdd(const IEEEFloat &, const IEEEFloat &, roundingMode);
262 opStatus roundToIntegral(roundingMode);
263 /// IEEE-754R 5.3.1: nextUp/nextDown.
264 opStatus next(bool nextDown);
265
266 /// @}
267
268 /// \name Sign operations.
269 /// @{
270
271 void changeSign();
272
273 /// @}
274
275 /// \name Conversions
276 /// @{
277
278 opStatus convert(const fltSemantics &, roundingMode, bool *);
279 opStatus convertToInteger(MutableArrayRef<integerPart>, unsigned int, bool,
280 roundingMode, bool *) const;
281 opStatus convertFromAPInt(const APInt &, bool, roundingMode);
282 opStatus convertFromSignExtendedInteger(const integerPart *, unsigned int,
283 bool, roundingMode);
284 opStatus convertFromZeroExtendedInteger(const integerPart *, unsigned int,
285 bool, roundingMode);
286 opStatus convertFromString(StringRef, roundingMode);
287 APInt bitcastToAPInt() const;
288 double convertToDouble() const;
289 float convertToFloat() const;
290
291 /// @}
292
293 /// The definition of equality is not straightforward for floating point, so
294 /// we won't use operator==. Use one of the following, or write whatever it
295 /// is you really mean.
296 bool operator==(const IEEEFloat &) const = delete;
297
298 /// IEEE comparison with another floating point number (NaNs compare
299 /// unordered, 0==-0).
300 cmpResult compare(const IEEEFloat &) const;
301
302 /// Bitwise comparison for equality (QNaNs compare equal, 0!=-0).
303 bool bitwiseIsEqual(const IEEEFloat &) const;
304
305 /// Write out a hexadecimal representation of the floating point value to DST,
306 /// which must be of sufficient size, in the C99 form [-]0xh.hhhhp[+-]d.
307 /// Return the number of characters written, excluding the terminating NUL.
308 unsigned int convertToHexString(char *dst, unsigned int hexDigits,
309 bool upperCase, roundingMode) const;
310
311 /// \name IEEE-754R 5.7.2 General operations.
312 /// @{
313
314 /// IEEE-754R isSignMinus: Returns true if and only if the current value is
315 /// negative.
316 ///
317 /// This applies to zeros and NaNs as well.
318 bool isNegative() const { return sign; }
319
320 /// IEEE-754R isNormal: Returns true if and only if the current value is normal.
321 ///
322 /// This implies that the current value of the float is not zero, subnormal,
323 /// infinite, or NaN following the definition of normality from IEEE-754R.
324 bool isNormal() const { return !isDenormal() && isFiniteNonZero(); }
325
326 /// Returns true if and only if the current value is zero, subnormal, or
327 /// normal.
328 ///
329 /// This means that the value is not infinite or NaN.
330 bool isFinite() const { return !isNaN() && !isInfinity(); }
331
332 /// Returns true if and only if the float is plus or minus zero.
333 bool isZero() const { return category == fcZero; }
334
335 /// IEEE-754R isSubnormal(): Returns true if and only if the float is a
336 /// denormal.
337 bool isDenormal() const;
338
339 /// IEEE-754R isInfinite(): Returns true if and only if the float is infinity.
340 bool isInfinity() const { return category == fcInfinity; }
341
342 /// Returns true if and only if the float is a quiet or signaling NaN.
343 bool isNaN() const { return category == fcNaN; }
344
345 /// Returns true if and only if the float is a signaling NaN.
346 bool isSignaling() const;
347
348 /// @}
349
350 /// \name Simple Queries
351 /// @{
352
353 fltCategory getCategory() const { return category; }
354 const fltSemantics &getSemantics() const { return *semantics; }
355 bool isNonZero() const { return category != fcZero; }
356 bool isFiniteNonZero() const { return isFinite() && !isZero(); }
357 bool isPosZero() const { return isZero() && !isNegative(); }
358 bool isNegZero() const { return isZero() && isNegative(); }
359
360 /// Returns true if and only if the number has the smallest possible non-zero
361 /// magnitude in the current semantics.
362 bool isSmallest() const;
363
364 /// Returns true if and only if the number has the largest possible finite
365 /// magnitude in the current semantics.
366 bool isLargest() const;
367
368 /// Returns true if and only if the number is an exact integer.
369 bool isInteger() const;
370
371 /// @}
372
373 IEEEFloat &operator=(const IEEEFloat &);
374 IEEEFloat &operator=(IEEEFloat &&);
375
376 /// Overload to compute a hash code for an APFloat value.
377 ///
378 /// Note that the use of hash codes for floating point values is in general
379 /// frought with peril. Equality is hard to define for these values. For
380 /// example, should negative and positive zero hash to different codes? Are
381 /// they equal or not? This hash value implementation specifically
382 /// emphasizes producing different codes for different inputs in order to
383 /// be used in canonicalization and memoization. As such, equality is
384 /// bitwiseIsEqual, and 0 != -0.
385 friend hash_code hash_value(const IEEEFloat &Arg);
386
387 /// Converts this value into a decimal string.
388 ///
389 /// \param FormatPrecision The maximum number of digits of
390 /// precision to output. If there are fewer digits available,
391 /// zero padding will not be used unless the value is
392 /// integral and small enough to be expressed in
393 /// FormatPrecision digits. 0 means to use the natural
394 /// precision of the number.
395 /// \param FormatMaxPadding The maximum number of zeros to
396 /// consider inserting before falling back to scientific
397 /// notation. 0 means to always use scientific notation.
398 ///
399 /// \param TruncateZero Indicate whether to remove the trailing zero in
400 /// fraction part or not. Also setting this parameter to false forcing
401 /// producing of output more similar to default printf behavior.
402 /// Specifically the lower e is used as exponent delimiter and exponent
403 /// always contains no less than two digits.
404 ///
405 /// Number Precision MaxPadding Result
406 /// ------ --------- ---------- ------
407 /// 1.01E+4 5 2 10100
408 /// 1.01E+4 4 2 1.01E+4
409 /// 1.01E+4 5 1 1.01E+4
410 /// 1.01E-2 5 2 0.0101
411 /// 1.01E-2 4 2 0.0101
412 /// 1.01E-2 4 1 1.01E-2
413 void toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision = 0,
414 unsigned FormatMaxPadding = 3, bool TruncateZero = true) const;
415
416 /// If this value has an exact multiplicative inverse, store it in inv and
417 /// return true.
418 bool getExactInverse(APFloat *inv) const;
419
420 /// Returns the exponent of the internal representation of the APFloat.
421 ///
422 /// Because the radix of APFloat is 2, this is equivalent to floor(log2(x)).
423 /// For special APFloat values, this returns special error codes:
424 ///
425 /// NaN -> \c IEK_NaN
426 /// 0 -> \c IEK_Zero
427 /// Inf -> \c IEK_Inf
428 ///
429 friend int ilogb(const IEEEFloat &Arg);
430
431 /// Returns: X * 2^Exp for integral exponents.
432 friend IEEEFloat scalbn(IEEEFloat X, int Exp, roundingMode);
433
434 friend IEEEFloat frexp(const IEEEFloat &X, int &Exp, roundingMode);
435
436 /// \name Special value setters.
437 /// @{
438
439 void makeLargest(bool Neg = false);
440 void makeSmallest(bool Neg = false);
441 void makeNaN(bool SNaN = false, bool Neg = false,
442 const APInt *fill = nullptr);
443 void makeInf(bool Neg = false);
444 void makeZero(bool Neg = false);
445 void makeQuiet();
446
447 /// Returns the smallest (by magnitude) normalized finite number in the given
448 /// semantics.
449 ///
450 /// \param Negative - True iff the number should be negative
451 void makeSmallestNormalized(bool Negative = false);
452
453 /// @}
454
455 cmpResult compareAbsoluteValue(const IEEEFloat &) const;
456
457private:
458 /// \name Simple Queries
459 /// @{
460
461 integerPart *significandParts();
462 const integerPart *significandParts() const;
463 unsigned int partCount() const;
464
465 /// @}
466
467 /// \name Significand operations.
468 /// @{
469
470 integerPart addSignificand(const IEEEFloat &);
471 integerPart subtractSignificand(const IEEEFloat &, integerPart);
472 lostFraction addOrSubtractSignificand(const IEEEFloat &, bool subtract);
473 lostFraction multiplySignificand(const IEEEFloat &, const IEEEFloat *);
474 lostFraction divideSignificand(const IEEEFloat &);
475 void incrementSignificand();
476 void initialize(const fltSemantics *);
477 void shiftSignificandLeft(unsigned int);
478 lostFraction shiftSignificandRight(unsigned int);
479 unsigned int significandLSB() const;
480 unsigned int significandMSB() const;
481 void zeroSignificand();
482 /// Return true if the significand excluding the integral bit is all ones.
483 bool isSignificandAllOnes() const;
484 /// Return true if the significand excluding the integral bit is all zeros.
485 bool isSignificandAllZeros() const;
486
487 /// @}
488
489 /// \name Arithmetic on special values.
490 /// @{
491
492 opStatus addOrSubtractSpecials(const IEEEFloat &, bool subtract);
493 opStatus divideSpecials(const IEEEFloat &);
494 opStatus multiplySpecials(const IEEEFloat &);
495 opStatus modSpecials(const IEEEFloat &);
496
497 /// @}
498
499 /// \name Miscellany
500 /// @{
501
502 bool convertFromStringSpecials(StringRef str);
503 opStatus normalize(roundingMode, lostFraction);
504 opStatus addOrSubtract(const IEEEFloat &, roundingMode, bool subtract);
505 opStatus handleOverflow(roundingMode);
506 bool roundAwayFromZero(roundingMode, lostFraction, unsigned int) const;
507 opStatus convertToSignExtendedInteger(MutableArrayRef<integerPart>,
508 unsigned int, bool, roundingMode,
509 bool *) const;
510 opStatus convertFromUnsignedParts(const integerPart *, unsigned int,
511 roundingMode);
512 opStatus convertFromHexadecimalString(StringRef, roundingMode);
513 opStatus convertFromDecimalString(StringRef, roundingMode);
514 char *convertNormalToHexString(char *, unsigned int, bool,
515 roundingMode) const;
516 opStatus roundSignificandWithExponent(const integerPart *, unsigned int, int,
517 roundingMode);
518
519 /// @}
520
521 APInt convertHalfAPFloatToAPInt() const;
522 APInt convertFloatAPFloatToAPInt() const;
523 APInt convertDoubleAPFloatToAPInt() const;
524 APInt convertQuadrupleAPFloatToAPInt() const;
525 APInt convertF80LongDoubleAPFloatToAPInt() const;
526 APInt convertPPCDoubleDoubleAPFloatToAPInt() const;
527 void initFromAPInt(const fltSemantics *Sem, const APInt &api);
528 void initFromHalfAPInt(const APInt &api);
529 void initFromFloatAPInt(const APInt &api);
530 void initFromDoubleAPInt(const APInt &api);
531 void initFromQuadrupleAPInt(const APInt &api);
532 void initFromF80LongDoubleAPInt(const APInt &api);
533 void initFromPPCDoubleDoubleAPInt(const APInt &api);
534
535 void assign(const IEEEFloat &);
536 void copySignificand(const IEEEFloat &);
537 void freeSignificand();
538
539 /// Note: this must be the first data member.
540 /// The semantics that this value obeys.
541 const fltSemantics *semantics;
542
543 /// A binary fraction with an explicit integer bit.
544 ///
545 /// The significand must be at least one bit wider than the target precision.
546 union Significand {
547 integerPart part;
548 integerPart *parts;
549 } significand;
550
551 /// The signed unbiased exponent of the value.
552 ExponentType exponent;
553
554 /// What kind of floating point number this is.
555 ///
556 /// Only 2 bits are required, but VisualStudio incorrectly sign extends it.
557 /// Using the extra bit keeps it from failing under VisualStudio.
558 fltCategory category : 3;
559
560 /// Sign bit of the number.
561 unsigned int sign : 1;
562};
563
564hash_code hash_value(const IEEEFloat &Arg);
565int ilogb(const IEEEFloat &Arg);
566IEEEFloat scalbn(IEEEFloat X, int Exp, IEEEFloat::roundingMode);
567IEEEFloat frexp(const IEEEFloat &Val, int &Exp, IEEEFloat::roundingMode RM);
568
569// This mode implements more precise float in terms of two APFloats.
570// The interface and layout is designed for arbitray underlying semantics,
571// though currently only PPCDoubleDouble semantics are supported, whose
572// corresponding underlying semantics are IEEEdouble.
573class DoubleAPFloat final : public APFloatBase {
574 // Note: this must be the first data member.
575 const fltSemantics *Semantics;
576 std::unique_ptr<APFloat[]> Floats;
577
578 opStatus addImpl(const APFloat &a, const APFloat &aa, const APFloat &c,
579 const APFloat &cc, roundingMode RM);
580
581 opStatus addWithSpecial(const DoubleAPFloat &LHS, const DoubleAPFloat &RHS,
582 DoubleAPFloat &Out, roundingMode RM);
583
584public:
585 DoubleAPFloat(const fltSemantics &S);
586 DoubleAPFloat(const fltSemantics &S, uninitializedTag);
587 DoubleAPFloat(const fltSemantics &S, integerPart);
588 DoubleAPFloat(const fltSemantics &S, const APInt &I);
589 DoubleAPFloat(const fltSemantics &S, APFloat &&First, APFloat &&Second);
590 DoubleAPFloat(const DoubleAPFloat &RHS);
591 DoubleAPFloat(DoubleAPFloat &&RHS);
592
593 DoubleAPFloat &operator=(const DoubleAPFloat &RHS);
594
595 DoubleAPFloat &operator=(DoubleAPFloat &&RHS) {
596 if (this != &RHS) {
597 this->~DoubleAPFloat();
598 new (this) DoubleAPFloat(std::move(RHS));
599 }
600 return *this;
601 }
602
603 bool needsCleanup() const { return Floats != nullptr; }
604
605 APFloat &getFirst() { return Floats[0]; }
606 const APFloat &getFirst() const { return Floats[0]; }
607 APFloat &getSecond() { return Floats[1]; }
608 const APFloat &getSecond() const { return Floats[1]; }
609
610 opStatus add(const DoubleAPFloat &RHS, roundingMode RM);
611 opStatus subtract(const DoubleAPFloat &RHS, roundingMode RM);
612 opStatus multiply(const DoubleAPFloat &RHS, roundingMode RM);
613 opStatus divide(const DoubleAPFloat &RHS, roundingMode RM);
614 opStatus remainder(const DoubleAPFloat &RHS);
615 opStatus mod(const DoubleAPFloat &RHS);
616 opStatus fusedMultiplyAdd(const DoubleAPFloat &Multiplicand,
617 const DoubleAPFloat &Addend, roundingMode RM);
618 opStatus roundToIntegral(roundingMode RM);
619 void changeSign();
620 cmpResult compareAbsoluteValue(const DoubleAPFloat &RHS) const;
621
622 fltCategory getCategory() const;
623 bool isNegative() const;
624
625 void makeInf(bool Neg);
626 void makeZero(bool Neg);
627 void makeLargest(bool Neg);
628 void makeSmallest(bool Neg);
629 void makeSmallestNormalized(bool Neg);
630 void makeNaN(bool SNaN, bool Neg, const APInt *fill);
631
632 cmpResult compare(const DoubleAPFloat &RHS) const;
633 bool bitwiseIsEqual(const DoubleAPFloat &RHS) const;
634 APInt bitcastToAPInt() const;
635 opStatus convertFromString(StringRef, roundingMode);
636 opStatus next(bool nextDown);
637
638 opStatus convertToInteger(MutableArrayRef<integerPart> Input,
639 unsigned int Width, bool IsSigned, roundingMode RM,
640 bool *IsExact) const;
641 opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM);
642 opStatus convertFromSignExtendedInteger(const integerPart *Input,
643 unsigned int InputSize, bool IsSigned,
644 roundingMode RM);
645 opStatus convertFromZeroExtendedInteger(const integerPart *Input,
646 unsigned int InputSize, bool IsSigned,
647 roundingMode RM);
648 unsigned int convertToHexString(char *DST, unsigned int HexDigits,
649 bool UpperCase, roundingMode RM) const;
650
651 bool isDenormal() const;
652 bool isSmallest() const;
653 bool isLargest() const;
654 bool isInteger() const;
655
656 void toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision,
657 unsigned FormatMaxPadding, bool TruncateZero = true) const;
658
659 bool getExactInverse(APFloat *inv) const;
660
661 friend int ilogb(const DoubleAPFloat &Arg);
662 friend DoubleAPFloat scalbn(DoubleAPFloat X, int Exp, roundingMode);
663 friend DoubleAPFloat frexp(const DoubleAPFloat &X, int &Exp, roundingMode);
664 friend hash_code hash_value(const DoubleAPFloat &Arg);
665};
666
667hash_code hash_value(const DoubleAPFloat &Arg);
668
669} // End detail namespace
670
671// This is a interface class that is currently forwarding functionalities from
672// detail::IEEEFloat.
673class APFloat : public APFloatBase {
674 typedef detail::IEEEFloat IEEEFloat;
675 typedef detail::DoubleAPFloat DoubleAPFloat;
676
677 static_assert(std::is_standard_layout<IEEEFloat>::value, "");
678
679 union Storage {
680 const fltSemantics *semantics;
681 IEEEFloat IEEE;
682 DoubleAPFloat Double;
683
684 explicit Storage(IEEEFloat F, const fltSemantics &S);
685 explicit Storage(DoubleAPFloat F, const fltSemantics &S)
686 : Double(std::move(F)) {
687 assert(&S == &PPCDoubleDouble());
688 }
689
690 template <typename... ArgTypes>
691 Storage(const fltSemantics &Semantics, ArgTypes &&... Args) {
692 if (usesLayout<IEEEFloat>(Semantics)) {
693 new (&IEEE) IEEEFloat(Semantics, std::forward<ArgTypes>(Args)...);
694 return;
695 }
696 if (usesLayout<DoubleAPFloat>(Semantics)) {
697 new (&Double) DoubleAPFloat(Semantics, std::forward<ArgTypes>(Args)...);
698 return;
699 }
700 llvm_unreachable("Unexpected semantics");
701 }
702
703 ~Storage() {
704 if (usesLayout<IEEEFloat>(*semantics)) {
705 IEEE.~IEEEFloat();
706 return;
707 }
708 if (usesLayout<DoubleAPFloat>(*semantics)) {
709 Double.~DoubleAPFloat();
710 return;
711 }
712 llvm_unreachable("Unexpected semantics");
713 }
714
715 Storage(const Storage &RHS) {
716 if (usesLayout<IEEEFloat>(*RHS.semantics)) {
717 new (this) IEEEFloat(RHS.IEEE);
718 return;
719 }
720 if (usesLayout<DoubleAPFloat>(*RHS.semantics)) {
721 new (this) DoubleAPFloat(RHS.Double);
722 return;
723 }
724 llvm_unreachable("Unexpected semantics");
725 }
726
727 Storage(Storage &&RHS) {
728 if (usesLayout<IEEEFloat>(*RHS.semantics)) {
729 new (this) IEEEFloat(std::move(RHS.IEEE));
730 return;
731 }
732 if (usesLayout<DoubleAPFloat>(*RHS.semantics)) {
733 new (this) DoubleAPFloat(std::move(RHS.Double));
734 return;
735 }
736 llvm_unreachable("Unexpected semantics");
737 }
738
739 Storage &operator=(const Storage &RHS) {
740 if (usesLayout<IEEEFloat>(*semantics) &&
741 usesLayout<IEEEFloat>(*RHS.semantics)) {
742 IEEE = RHS.IEEE;
743 } else if (usesLayout<DoubleAPFloat>(*semantics) &&
744 usesLayout<DoubleAPFloat>(*RHS.semantics)) {
745 Double = RHS.Double;
746 } else if (this != &RHS) {
747 this->~Storage();
748 new (this) Storage(RHS);
749 }
750 return *this;
751 }
752
753 Storage &operator=(Storage &&RHS) {
754 if (usesLayout<IEEEFloat>(*semantics) &&
755 usesLayout<IEEEFloat>(*RHS.semantics)) {
756 IEEE = std::move(RHS.IEEE);
757 } else if (usesLayout<DoubleAPFloat>(*semantics) &&
758 usesLayout<DoubleAPFloat>(*RHS.semantics)) {
759 Double = std::move(RHS.Double);
760 } else if (this != &RHS) {
761 this->~Storage();
762 new (this) Storage(std::move(RHS));
763 }
764 return *this;
765 }
766 } U;
767
768 template <typename T> static bool usesLayout(const fltSemantics &Semantics) {
769 static_assert(std::is_same<T, IEEEFloat>::value ||
770 std::is_same<T, DoubleAPFloat>::value, "");
771 if (std::is_same<T, DoubleAPFloat>::value) {
772 return &Semantics == &PPCDoubleDouble();
773 }
774 return &Semantics != &PPCDoubleDouble();
775 }
776
777 IEEEFloat &getIEEE() {
778 if (usesLayout<IEEEFloat>(*U.semantics))
779 return U.IEEE;
780 if (usesLayout<DoubleAPFloat>(*U.semantics))
781 return U.Double.getFirst().U.IEEE;
782 llvm_unreachable("Unexpected semantics");
783 }
784
785 const IEEEFloat &getIEEE() const {
786 if (usesLayout<IEEEFloat>(*U.semantics))
787 return U.IEEE;
788 if (usesLayout<DoubleAPFloat>(*U.semantics))
789 return U.Double.getFirst().U.IEEE;
790 llvm_unreachable("Unexpected semantics");
791 }
792
793 void makeZero(bool Neg) { APFLOAT_DISPATCH_ON_SEMANTICS(makeZero(Neg)); }
794
795 void makeInf(bool Neg) { APFLOAT_DISPATCH_ON_SEMANTICS(makeInf(Neg)); }
796
797 void makeNaN(bool SNaN, bool Neg, const APInt *fill) {
798 APFLOAT_DISPATCH_ON_SEMANTICS(makeNaN(SNaN, Neg, fill));
799 }
800
801 void makeLargest(bool Neg) {
802 APFLOAT_DISPATCH_ON_SEMANTICS(makeLargest(Neg));
803 }
804
805 void makeSmallest(bool Neg) {
806 APFLOAT_DISPATCH_ON_SEMANTICS(makeSmallest(Neg));
807 }
808
809 void makeSmallestNormalized(bool Neg) {
810 APFLOAT_DISPATCH_ON_SEMANTICS(makeSmallestNormalized(Neg));
811 }
812
813 // FIXME: This is due to clang 3.3 (or older version) always checks for the
814 // default constructor in an array aggregate initialization, even if no
815 // elements in the array is default initialized.
816 APFloat() : U(IEEEdouble()) {
817 llvm_unreachable("This is a workaround for old clang.");
818 }
819
820 explicit APFloat(IEEEFloat F, const fltSemantics &S) : U(std::move(F), S) {}
821 explicit APFloat(DoubleAPFloat F, const fltSemantics &S)
822 : U(std::move(F), S) {}
823
824 cmpResult compareAbsoluteValue(const APFloat &RHS) const {
825 assert(&getSemantics() == &RHS.getSemantics() &&
826 "Should only compare APFloats with the same semantics");
827 if (usesLayout<IEEEFloat>(getSemantics()))
828 return U.IEEE.compareAbsoluteValue(RHS.U.IEEE);
829 if (usesLayout<DoubleAPFloat>(getSemantics()))
830 return U.Double.compareAbsoluteValue(RHS.U.Double);
831 llvm_unreachable("Unexpected semantics");
832 }
833
834public:
835 APFloat(const fltSemantics &Semantics) : U(Semantics) {}
836 APFloat(const fltSemantics &Semantics, StringRef S);
837 APFloat(const fltSemantics &Semantics, integerPart I) : U(Semantics, I) {}
838 // TODO: Remove this constructor. This isn't faster than the first one.
839 APFloat(const fltSemantics &Semantics, uninitializedTag)
840 : U(Semantics, uninitialized) {}
841 APFloat(const fltSemantics &Semantics, const APInt &I) : U(Semantics, I) {}
842 explicit APFloat(double d) : U(IEEEFloat(d), IEEEdouble()) {}
843 explicit APFloat(float f) : U(IEEEFloat(f), IEEEsingle()) {}
844 APFloat(const APFloat &RHS) = default;
845 APFloat(APFloat &&RHS) = default;
846
847 ~APFloat() = default;
848
849 bool needsCleanup() const { APFLOAT_DISPATCH_ON_SEMANTICS(needsCleanup()); }
850
851 /// Factory for Positive and Negative Zero.
852 ///
853 /// \param Negative True iff the number should be negative.
854 static APFloat getZero(const fltSemantics &Sem, bool Negative = false) {
855 APFloat Val(Sem, uninitialized);
856 Val.makeZero(Negative);
857 return Val;
858 }
859
860 /// Factory for Positive and Negative Infinity.
861 ///
862 /// \param Negative True iff the number should be negative.
863 static APFloat getInf(const fltSemantics &Sem, bool Negative = false) {
864 APFloat Val(Sem, uninitialized);
865 Val.makeInf(Negative);
866 return Val;
867 }
868
869 /// Factory for NaN values.
870 ///
871 /// \param Negative - True iff the NaN generated should be negative.
872 /// \param payload - The unspecified fill bits for creating the NaN, 0 by
873 /// default. The value is truncated as necessary.
874 static APFloat getNaN(const fltSemantics &Sem, bool Negative = false,
875 uint64_t payload = 0) {
876 if (payload) {
877 APInt intPayload(64, payload);
878 return getQNaN(Sem, Negative, &intPayload);
879 } else {
880 return getQNaN(Sem, Negative, nullptr);
881 }
882 }
883
884 /// Factory for QNaN values.
885 static APFloat getQNaN(const fltSemantics &Sem, bool Negative = false,
886 const APInt *payload = nullptr) {
887 APFloat Val(Sem, uninitialized);
888 Val.makeNaN(false, Negative, payload);
889 return Val;
890 }
891
892 /// Factory for SNaN values.
893 static APFloat getSNaN(const fltSemantics &Sem, bool Negative = false,
894 const APInt *payload = nullptr) {
895 APFloat Val(Sem, uninitialized);
896 Val.makeNaN(true, Negative, payload);
897 return Val;
898 }
899
900 /// Returns the largest finite number in the given semantics.
901 ///
902 /// \param Negative - True iff the number should be negative
903 static APFloat getLargest(const fltSemantics &Sem, bool Negative = false) {
904 APFloat Val(Sem, uninitialized);
905 Val.makeLargest(Negative);
906 return Val;
907 }
908
909 /// Returns the smallest (by magnitude) finite number in the given semantics.
910 /// Might be denormalized, which implies a relative loss of precision.
911 ///
912 /// \param Negative - True iff the number should be negative
913 static APFloat getSmallest(const fltSemantics &Sem, bool Negative = false) {
914 APFloat Val(Sem, uninitialized);
915 Val.makeSmallest(Negative);
916 return Val;
917 }
918
919 /// Returns the smallest (by magnitude) normalized finite number in the given
920 /// semantics.
921 ///
922 /// \param Negative - True iff the number should be negative
923 static APFloat getSmallestNormalized(const fltSemantics &Sem,
924 bool Negative = false) {
925 APFloat Val(Sem, uninitialized);
926 Val.makeSmallestNormalized(Negative);
927 return Val;
928 }
929
930 /// Returns a float which is bitcasted from an all one value int.
931 ///
932 /// \param BitWidth - Select float type
933 /// \param isIEEE - If 128 bit number, select between PPC and IEEE
934 static APFloat getAllOnesValue(unsigned BitWidth, bool isIEEE = false);
935
936 /// Used to insert APFloat objects, or objects that contain APFloat objects,
937 /// into FoldingSets.
938 void Profile(FoldingSetNodeID &NID) const;
939
940 opStatus add(const APFloat &RHS, roundingMode RM) {
941 assert(&getSemantics() == &RHS.getSemantics() &&
942 "Should only call on two APFloats with the same semantics");
943 if (usesLayout<IEEEFloat>(getSemantics()))
944 return U.IEEE.add(RHS.U.IEEE, RM);
945 if (usesLayout<DoubleAPFloat>(getSemantics()))
946 return U.Double.add(RHS.U.Double, RM);
947 llvm_unreachable("Unexpected semantics");
948 }
949 opStatus subtract(const APFloat &RHS, roundingMode RM) {
950 assert(&getSemantics() == &RHS.getSemantics() &&
951 "Should only call on two APFloats with the same semantics");
952 if (usesLayout<IEEEFloat>(getSemantics()))
953 return U.IEEE.subtract(RHS.U.IEEE, RM);
954 if (usesLayout<DoubleAPFloat>(getSemantics()))
955 return U.Double.subtract(RHS.U.Double, RM);
956 llvm_unreachable("Unexpected semantics");
957 }
958 opStatus multiply(const APFloat &RHS, roundingMode RM) {
959 assert(&getSemantics() == &RHS.getSemantics() &&
960 "Should only call on two APFloats with the same semantics");
961 if (usesLayout<IEEEFloat>(getSemantics()))
962 return U.IEEE.multiply(RHS.U.IEEE, RM);
963 if (usesLayout<DoubleAPFloat>(getSemantics()))
964 return U.Double.multiply(RHS.U.Double, RM);
965 llvm_unreachable("Unexpected semantics");
966 }
967 opStatus divide(const APFloat &RHS, roundingMode RM) {
968 assert(&getSemantics() == &RHS.getSemantics() &&
969 "Should only call on two APFloats with the same semantics");
970 if (usesLayout<IEEEFloat>(getSemantics()))
971 return U.IEEE.divide(RHS.U.IEEE, RM);
972 if (usesLayout<DoubleAPFloat>(getSemantics()))
973 return U.Double.divide(RHS.U.Double, RM);
974 llvm_unreachable("Unexpected semantics");
975 }
976 opStatus remainder(const APFloat &RHS) {
977 assert(&getSemantics() == &RHS.getSemantics() &&
978 "Should only call on two APFloats with the same semantics");
979 if (usesLayout<IEEEFloat>(getSemantics()))
980 return U.IEEE.remainder(RHS.U.IEEE);
981 if (usesLayout<DoubleAPFloat>(getSemantics()))
982 return U.Double.remainder(RHS.U.Double);
983 llvm_unreachable("Unexpected semantics");
984 }
985 opStatus mod(const APFloat &RHS) {
986 assert(&getSemantics() == &RHS.getSemantics() &&
987 "Should only call on two APFloats with the same semantics");
988 if (usesLayout<IEEEFloat>(getSemantics()))
989 return U.IEEE.mod(RHS.U.IEEE);
990 if (usesLayout<DoubleAPFloat>(getSemantics()))
991 return U.Double.mod(RHS.U.Double);
992 llvm_unreachable("Unexpected semantics");
993 }
994 opStatus fusedMultiplyAdd(const APFloat &Multiplicand, const APFloat &Addend,
995 roundingMode RM) {
996 assert(&getSemantics() == &Multiplicand.getSemantics() &&
997 "Should only call on APFloats with the same semantics");
998 assert(&getSemantics() == &Addend.getSemantics() &&
999 "Should only call on APFloats with the same semantics");
1000 if (usesLayout<IEEEFloat>(getSemantics()))
1001 return U.IEEE.fusedMultiplyAdd(Multiplicand.U.IEEE, Addend.U.IEEE, RM);
1002 if (usesLayout<DoubleAPFloat>(getSemantics()))
1003 return U.Double.fusedMultiplyAdd(Multiplicand.U.Double, Addend.U.Double,
1004 RM);
1005 llvm_unreachable("Unexpected semantics");
1006 }
1007 opStatus roundToIntegral(roundingMode RM) {
1008 APFLOAT_DISPATCH_ON_SEMANTICS(roundToIntegral(RM));
1009 }
1010
1011 // TODO: bool parameters are not readable and a source of bugs.
1012 // Do something.
1013 opStatus next(bool nextDown) {
1014 APFLOAT_DISPATCH_ON_SEMANTICS(next(nextDown));
1015 }
1016
1017 /// Add two APFloats, rounding ties to the nearest even.
1018 /// No error checking.
1019 APFloat operator+(const APFloat &RHS) const {
1020 APFloat Result(*this);
1021 (void)Result.add(RHS, rmNearestTiesToEven);
1022 return Result;
1023 }
1024
1025 /// Subtract two APFloats, rounding ties to the nearest even.
1026 /// No error checking.
1027 APFloat operator-(const APFloat &RHS) const {
1028 APFloat Result(*this);
1029 (void)Result.subtract(RHS, rmNearestTiesToEven);
1030 return Result;
1031 }
1032
1033 /// Multiply two APFloats, rounding ties to the nearest even.
1034 /// No error checking.
1035 APFloat operator*(const APFloat &RHS) const {
1036 APFloat Result(*this);
1037 (void)Result.multiply(RHS, rmNearestTiesToEven);
1038 return Result;
1039 }
1040
1041 /// Divide the first APFloat by the second, rounding ties to the nearest even.
1042 /// No error checking.
1043 APFloat operator/(const APFloat &RHS) const {
1044 APFloat Result(*this);
1045 (void)Result.divide(RHS, rmNearestTiesToEven);
1046 return Result;
1047 }
1048
1049 void changeSign() { APFLOAT_DISPATCH_ON_SEMANTICS(changeSign()); }
1050 void clearSign() {
1051 if (isNegative())
1052 changeSign();
1053 }
1054 void copySign(const APFloat &RHS) {
1055 if (isNegative() != RHS.isNegative())
1056 changeSign();
1057 }
1058
1059 /// A static helper to produce a copy of an APFloat value with its sign
1060 /// copied from some other APFloat.
1061 static APFloat copySign(APFloat Value, const APFloat &Sign) {
1062 Value.copySign(Sign);
1063 return Value;
1064 }
1065
1066 opStatus convert(const fltSemantics &ToSemantics, roundingMode RM,
1067 bool *losesInfo);
1068 opStatus convertToInteger(MutableArrayRef<integerPart> Input,
1069 unsigned int Width, bool IsSigned, roundingMode RM,
1070 bool *IsExact) const {
1071 APFLOAT_DISPATCH_ON_SEMANTICS(
1072 convertToInteger(Input, Width, IsSigned, RM, IsExact));
1073 }
1074 opStatus convertToInteger(APSInt &Result, roundingMode RM,
1075 bool *IsExact) const;
1076 opStatus convertFromAPInt(const APInt &Input, bool IsSigned,
1077 roundingMode RM) {
1078 APFLOAT_DISPATCH_ON_SEMANTICS(convertFromAPInt(Input, IsSigned, RM));
1079 }
1080 opStatus convertFromSignExtendedInteger(const integerPart *Input,
1081 unsigned int InputSize, bool IsSigned,
1082 roundingMode RM) {
1083 APFLOAT_DISPATCH_ON_SEMANTICS(
1084 convertFromSignExtendedInteger(Input, InputSize, IsSigned, RM));
1085 }
1086 opStatus convertFromZeroExtendedInteger(const integerPart *Input,
1087 unsigned int InputSize, bool IsSigned,
1088 roundingMode RM) {
1089 APFLOAT_DISPATCH_ON_SEMANTICS(
1090 convertFromZeroExtendedInteger(Input, InputSize, IsSigned, RM));
1091 }
1092 opStatus convertFromString(StringRef, roundingMode);
1093 APInt bitcastToAPInt() const {
1094 APFLOAT_DISPATCH_ON_SEMANTICS(bitcastToAPInt());
1095 }
1096 double convertToDouble() const { return getIEEE().convertToDouble(); }
1097 float convertToFloat() const { return getIEEE().convertToFloat(); }
1098
1099 bool operator==(const APFloat &) const = delete;
1100
1101 cmpResult compare(const APFloat &RHS) const {
1102 assert(&getSemantics() == &RHS.getSemantics() &&
1103 "Should only compare APFloats with the same semantics");
1104 if (usesLayout<IEEEFloat>(getSemantics()))
1105 return U.IEEE.compare(RHS.U.IEEE);
1106 if (usesLayout<DoubleAPFloat>(getSemantics()))
1107 return U.Double.compare(RHS.U.Double);
1108 llvm_unreachable("Unexpected semantics");
1109 }
1110
1111 bool bitwiseIsEqual(const APFloat &RHS) const {
1112 if (&getSemantics() != &RHS.getSemantics())
1113 return false;
1114 if (usesLayout<IEEEFloat>(getSemantics()))
1115 return U.IEEE.bitwiseIsEqual(RHS.U.IEEE);
1116 if (usesLayout<DoubleAPFloat>(getSemantics()))
1117 return U.Double.bitwiseIsEqual(RHS.U.Double);
1118 llvm_unreachable("Unexpected semantics");
1119 }
1120
1121 /// We don't rely on operator== working on double values, as
1122 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
1123 /// As such, this method can be used to do an exact bit-for-bit comparison of
1124 /// two floating point values.
1125 ///
1126 /// We leave the version with the double argument here because it's just so
1127 /// convenient to write "2.0" and the like. Without this function we'd
1128 /// have to duplicate its logic everywhere it's called.
1129 bool isExactlyValue(double V) const {
1130 bool ignored;
1131 APFloat Tmp(V);
1132 Tmp.convert(getSemantics(), APFloat::rmNearestTiesToEven, &ignored);
1133 return bitwiseIsEqual(Tmp);
1134 }
1135
1136 unsigned int convertToHexString(char *DST, unsigned int HexDigits,
1137 bool UpperCase, roundingMode RM) const {
1138 APFLOAT_DISPATCH_ON_SEMANTICS(
1139 convertToHexString(DST, HexDigits, UpperCase, RM));
1140 }
1141
1142 bool isZero() const { return getCategory() == fcZero; }
1143 bool isInfinity() const { return getCategory() == fcInfinity; }
1144 bool isNaN() const { return getCategory() == fcNaN; }
1145
1146 bool isNegative() const { return getIEEE().isNegative(); }
1147 bool isDenormal() const { APFLOAT_DISPATCH_ON_SEMANTICS(isDenormal()); }
1148 bool isSignaling() const { return getIEEE().isSignaling(); }
1149
1150 bool isNormal() const { return !isDenormal() && isFiniteNonZero(); }
1151 bool isFinite() const { return !isNaN() && !isInfinity(); }
1152
1153 fltCategory getCategory() const { return getIEEE().getCategory(); }
1154 const fltSemantics &getSemantics() const { return *U.semantics; }
1155 bool isNonZero() const { return !isZero(); }
1156 bool isFiniteNonZero() const { return isFinite() && !isZero(); }
1157 bool isPosZero() const { return isZero() && !isNegative(); }
1158 bool isNegZero() const { return isZero() && isNegative(); }
1159 bool isSmallest() const { APFLOAT_DISPATCH_ON_SEMANTICS(isSmallest()); }
1160 bool isLargest() const { APFLOAT_DISPATCH_ON_SEMANTICS(isLargest()); }
1161 bool isInteger() const { APFLOAT_DISPATCH_ON_SEMANTICS(isInteger()); }
1162
1163 APFloat &operator=(const APFloat &RHS) = default;
1164 APFloat &operator=(APFloat &&RHS) = default;
1165
1166 void toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision = 0,
1167 unsigned FormatMaxPadding = 3, bool TruncateZero = true) const {
1168 APFLOAT_DISPATCH_ON_SEMANTICS(
1169 toString(Str, FormatPrecision, FormatMaxPadding, TruncateZero));
1170 }
1171
1172 void print(raw_ostream &) const;
1173 void dump() const;
1174
1175 bool getExactInverse(APFloat *inv) const {
1176 APFLOAT_DISPATCH_ON_SEMANTICS(getExactInverse(inv));
1177 }
1178
1179 friend hash_code hash_value(const APFloat &Arg);
1180 friend int ilogb(const APFloat &Arg) { return ilogb(Arg.getIEEE()); }
1181 friend APFloat scalbn(APFloat X, int Exp, roundingMode RM);
1182 friend APFloat frexp(const APFloat &X, int &Exp, roundingMode RM);
1183 friend IEEEFloat;
1184 friend DoubleAPFloat;
1185};
1186
1187/// See friend declarations above.
1188///
1189/// These additional declarations are required in order to compile LLVM with IBM
1190/// xlC compiler.
1191hash_code hash_value(const APFloat &Arg);
1192inline APFloat scalbn(APFloat X, int Exp, APFloat::roundingMode RM) {
1193 if (APFloat::usesLayout<detail::IEEEFloat>(X.getSemantics()))
1194 return APFloat(scalbn(X.U.IEEE, Exp, RM), X.getSemantics());
1195 if (APFloat::usesLayout<detail::DoubleAPFloat>(X.getSemantics()))
1196 return APFloat(scalbn(X.U.Double, Exp, RM), X.getSemantics());
1197 llvm_unreachable("Unexpected semantics");
1198}
1199
1200/// Equivalent of C standard library function.
1201///
1202/// While the C standard says Exp is an unspecified value for infinity and nan,
1203/// this returns INT_MAX for infinities, and INT_MIN for NaNs.
1204inline APFloat frexp(const APFloat &X, int &Exp, APFloat::roundingMode RM) {
1205 if (APFloat::usesLayout<detail::IEEEFloat>(X.getSemantics()))
1206 return APFloat(frexp(X.U.IEEE, Exp, RM), X.getSemantics());
1207 if (APFloat::usesLayout<detail::DoubleAPFloat>(X.getSemantics()))
1208 return APFloat(frexp(X.U.Double, Exp, RM), X.getSemantics());
1209 llvm_unreachable("Unexpected semantics");
1210}
1211/// Returns the absolute value of the argument.
1212inline APFloat abs(APFloat X) {
1213 X.clearSign();
1214 return X;
1215}
1216
1217/// Returns the negated value of the argument.
1218inline APFloat neg(APFloat X) {
1219 X.changeSign();
1220 return X;
1221}
1222
1223/// Implements IEEE minNum semantics. Returns the smaller of the 2 arguments if
1224/// both are not NaN. If either argument is a NaN, returns the other argument.
1225LLVM_READONLY
1226inline APFloat minnum(const APFloat &A, const APFloat &B) {
1227 if (A.isNaN())
1228 return B;
1229 if (B.isNaN())
1230 return A;
1231 return (B.compare(A) == APFloat::cmpLessThan) ? B : A;
1232}
1233
1234/// Implements IEEE maxNum semantics. Returns the larger of the 2 arguments if
1235/// both are not NaN. If either argument is a NaN, returns the other argument.
1236LLVM_READONLY
1237inline APFloat maxnum(const APFloat &A, const APFloat &B) {
1238 if (A.isNaN())
1239 return B;
1240 if (B.isNaN())
1241 return A;
1242 return (A.compare(B) == APFloat::cmpLessThan) ? B : A;
1243}
1244
1245/// Implements IEEE 754-2018 minimum semantics. Returns the smaller of 2
1246/// arguments, propagating NaNs and treating -0 as less than +0.
1247LLVM_READONLY
1248inline APFloat minimum(const APFloat &A, const APFloat &B) {
1249 if (A.isNaN())
1250 return A;
1251 if (B.isNaN())
1252 return B;
1253 if (A.isZero() && B.isZero() && (A.isNegative() != B.isNegative()))
1254 return A.isNegative() ? A : B;
1255 return (B.compare(A) == APFloat::cmpLessThan) ? B : A;
1256}
1257
1258/// Implements IEEE 754-2018 maximum semantics. Returns the larger of 2
1259/// arguments, propagating NaNs and treating -0 as less than +0.
1260LLVM_READONLY
1261inline APFloat maximum(const APFloat &A, const APFloat &B) {
1262 if (A.isNaN())
1263 return A;
1264 if (B.isNaN())
1265 return B;
1266 if (A.isZero() && B.isZero() && (A.isNegative() != B.isNegative()))
1267 return A.isNegative() ? B : A;
1268 return (A.compare(B) == APFloat::cmpLessThan) ? B : A;
1269}
1270
1271} // namespace llvm
1272
1273#undef APFLOAT_DISPATCH_ON_SEMANTICS
1274#endif // LLVM_ADT_APFLOAT_H
1275