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