Coverage Report

Created: 2019-03-24 22:13

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