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