1 //===- llvm/ADT/APFloat.h - Arbitrary Precision Floating Point ---*- C++ -*-==//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// \brief
12 /// This file declares a class to represent arbitrary precision floating point
13 /// values and provide a variety of arithmetic operations on them.
14 ///
15 //===----------------------------------------------------------------------===//
16
17 #ifndef LLVM_ADT_APFLOAT_H
18 #define LLVM_ADT_APFLOAT_H
19
20 #include "llvm/ADT/APInt.h"
21
22 namespace llvm {
23
24 struct fltSemantics;
25 class APSInt;
26 class StringRef;
27
28 /// Enum that represents what fraction of the LSB truncated bits of an fp number
29 /// represent.
30 ///
31 /// This essentially combines the roles of guard and sticky bits.
32 enum lostFraction { // Example of truncated bits:
33 lfExactlyZero, // 000000
34 lfLessThanHalf, // 0xxxxx x's not all zero
35 lfExactlyHalf, // 100000
36 lfMoreThanHalf // 1xxxxx x's not all zero
37 };
38
39 /// \brief A self-contained host- and target-independent arbitrary-precision
40 /// floating-point software implementation.
41 ///
42 /// APFloat uses bignum integer arithmetic as provided by static functions in
43 /// the APInt class. The library will work with bignum integers whose parts are
44 /// any unsigned type at least 16 bits wide, but 64 bits is recommended.
45 ///
46 /// Written for clarity rather than speed, in particular with a view to use in
47 /// the front-end of a cross compiler so that target arithmetic can be correctly
48 /// performed on the host. Performance should nonetheless be reasonable,
49 /// particularly for its intended use. It may be useful as a base
50 /// implementation for a run-time library during development of a faster
51 /// target-specific one.
52 ///
53 /// All 5 rounding modes in the IEEE-754R draft are handled correctly for all
54 /// implemented operations. Currently implemented operations are add, subtract,
55 /// multiply, divide, fused-multiply-add, conversion-to-float,
56 /// conversion-to-integer and conversion-from-integer. New rounding modes
57 /// (e.g. away from zero) can be added with three or four lines of code.
58 ///
59 /// Four formats are built-in: IEEE single precision, double precision,
60 /// quadruple precision, and x87 80-bit extended double (when operating with
61 /// full extended precision). Adding a new format that obeys IEEE semantics
62 /// only requires adding two lines of code: a declaration and definition of the
63 /// format.
64 ///
65 /// All operations return the status of that operation as an exception bit-mask,
66 /// so multiple operations can be done consecutively with their results or-ed
67 /// together. The returned status can be useful for compiler diagnostics; e.g.,
68 /// inexact, underflow and overflow can be easily diagnosed on constant folding,
69 /// and compiler optimizers can determine what exceptions would be raised by
70 /// folding operations and optimize, or perhaps not optimize, accordingly.
71 ///
72 /// At present, underflow tininess is detected after rounding; it should be
73 /// straight forward to add support for the before-rounding case too.
74 ///
75 /// The library reads hexadecimal floating point numbers as per C99, and
76 /// correctly rounds if necessary according to the specified rounding mode.
77 /// Syntax is required to have been validated by the caller. It also converts
78 /// floating point numbers to hexadecimal text as per the C99 %a and %A
79 /// conversions. The output precision (or alternatively the natural minimal
80 /// precision) can be specified; if the requested precision is less than the
81 /// natural precision the output is correctly rounded for the specified rounding
82 /// mode.
83 ///
84 /// It also reads decimal floating point numbers and correctly rounds according
85 /// to the specified rounding mode.
86 ///
87 /// Conversion to decimal text is not currently implemented.
88 ///
89 /// Non-zero finite numbers are represented internally as a sign bit, a 16-bit
90 /// signed exponent, and the significand as an array of integer parts. After
91 /// normalization of a number of precision P the exponent is within the range of
92 /// the format, and if the number is not denormal the P-th bit of the
93 /// significand is set as an explicit integer bit. For denormals the most
94 /// significant bit is shifted right so that the exponent is maintained at the
95 /// format's minimum, so that the smallest denormal has just the least
96 /// significant bit of the significand set. The sign of zeroes and infinities
97 /// is significant; the exponent and significand of such numbers is not stored,
98 /// but has a known implicit (deterministic) value: 0 for the significands, 0
99 /// for zero exponent, all 1 bits for infinity exponent. For NaNs the sign and
100 /// significand are deterministic, although not really meaningful, and preserved
101 /// in non-conversion operations. The exponent is implicitly all 1 bits.
102 ///
103 /// APFloat does not provide any exception handling beyond default exception
104 /// handling. We represent Signaling NaNs via IEEE-754R 2008 6.2.1 should clause
105 /// by encoding Signaling NaNs with the first bit of its trailing significand as
106 /// 0.
107 ///
108 /// TODO
109 /// ====
110 ///
111 /// Some features that may or may not be worth adding:
112 ///
113 /// Binary to decimal conversion (hard).
114 ///
115 /// Optional ability to detect underflow tininess before rounding.
116 ///
117 /// New formats: x87 in single and double precision mode (IEEE apart from
118 /// extended exponent range) (hard).
119 ///
120 /// New operations: sqrt, IEEE remainder, C90 fmod, nexttoward.
121 ///
122 class APFloat {
123 public:
124
125 /// A signed type to represent a floating point numbers unbiased exponent.
126 typedef signed short ExponentType;
127
128 /// \name Floating Point Semantics.
129 /// @{
130
131 static const fltSemantics IEEEhalf;
132 static const fltSemantics IEEEsingle;
133 static const fltSemantics IEEEdouble;
134 static const fltSemantics IEEEquad;
135 static const fltSemantics PPCDoubleDouble;
136 static const fltSemantics x87DoubleExtended;
137
138 /// A Pseudo fltsemantic used to construct APFloats that cannot conflict with
139 /// anything real.
140 static const fltSemantics Bogus;
141
142 /// @}
143
144 static unsigned int semanticsPrecision(const fltSemantics &);
145
146 /// IEEE-754R 5.11: Floating Point Comparison Relations.
147 enum cmpResult {
148 cmpLessThan,
149 cmpEqual,
150 cmpGreaterThan,
151 cmpUnordered
152 };
153
154 /// IEEE-754R 4.3: Rounding-direction attributes.
155 enum roundingMode {
156 rmNearestTiesToEven,
157 rmTowardPositive,
158 rmTowardNegative,
159 rmTowardZero,
160 rmNearestTiesToAway
161 };
162
163 /// IEEE-754R 7: Default exception handling.
164 ///
165 /// opUnderflow or opOverflow are always returned or-ed with opInexact.
166 enum opStatus {
167 opOK = 0x00,
168 opInvalidOp = 0x01,
169 opDivByZero = 0x02,
170 opOverflow = 0x04,
171 opUnderflow = 0x08,
172 opInexact = 0x10
173 };
174
175 /// Category of internally-represented number.
176 enum fltCategory {
177 fcInfinity,
178 fcNaN,
179 fcNormal,
180 fcZero
181 };
182
183 /// Convenience enum used to construct an uninitialized APFloat.
184 enum uninitializedTag {
185 uninitialized
186 };
187
188 /// \name Constructors
189 /// @{
190
191 APFloat(const fltSemantics &); // Default construct to 0.0
192 APFloat(const fltSemantics &, StringRef);
193 APFloat(const fltSemantics &, integerPart);
194 APFloat(const fltSemantics &, uninitializedTag);
195 APFloat(const fltSemantics &, const APInt &);
196 explicit APFloat(double d);
197 explicit APFloat(float f);
198 APFloat(const APFloat &);
199 APFloat(APFloat &&);
200 ~APFloat();
201
202 /// @}
203
204 /// \brief Returns whether this instance allocated memory.
needsCleanup()205 bool needsCleanup() const { return partCount() > 1; }
206
207 /// \name Convenience "constructors"
208 /// @{
209
210 /// Factory for Positive and Negative Zero.
211 ///
212 /// \param Negative True iff the number should be negative.
213 static APFloat getZero(const fltSemantics &Sem, bool Negative = false) {
214 APFloat Val(Sem, uninitialized);
215 Val.makeZero(Negative);
216 return Val;
217 }
218
219 /// Factory for Positive and Negative Infinity.
220 ///
221 /// \param Negative True iff the number should be negative.
222 static APFloat getInf(const fltSemantics &Sem, bool Negative = false) {
223 APFloat Val(Sem, uninitialized);
224 Val.makeInf(Negative);
225 return Val;
226 }
227
228 /// Factory for QNaN values.
229 ///
230 /// \param Negative - True iff the NaN generated should be negative.
231 /// \param type - The unspecified fill bits for creating the NaN, 0 by
232 /// default. The value is truncated as necessary.
233 static APFloat getNaN(const fltSemantics &Sem, bool Negative = false,
234 unsigned type = 0) {
235 if (type) {
236 APInt fill(64, type);
237 return getQNaN(Sem, Negative, &fill);
238 } else {
239 return getQNaN(Sem, Negative, nullptr);
240 }
241 }
242
243 /// Factory for QNaN values.
244 static APFloat getQNaN(const fltSemantics &Sem, bool Negative = false,
245 const APInt *payload = nullptr) {
246 return makeNaN(Sem, false, Negative, payload);
247 }
248
249 /// Factory for SNaN values.
250 static APFloat getSNaN(const fltSemantics &Sem, bool Negative = false,
251 const APInt *payload = nullptr) {
252 return makeNaN(Sem, true, Negative, payload);
253 }
254
255 /// Returns the largest finite number in the given semantics.
256 ///
257 /// \param Negative - True iff the number should be negative
258 static APFloat getLargest(const fltSemantics &Sem, bool Negative = false);
259
260 /// Returns the smallest (by magnitude) finite number in the given semantics.
261 /// Might be denormalized, which implies a relative loss of precision.
262 ///
263 /// \param Negative - True iff the number should be negative
264 static APFloat getSmallest(const fltSemantics &Sem, bool Negative = false);
265
266 /// Returns the smallest (by magnitude) normalized finite number in the given
267 /// semantics.
268 ///
269 /// \param Negative - True iff the number should be negative
270 static APFloat getSmallestNormalized(const fltSemantics &Sem,
271 bool Negative = false);
272
273 /// Returns a float which is bitcasted from an all one value int.
274 ///
275 /// \param BitWidth - Select float type
276 /// \param isIEEE - If 128 bit number, select between PPC and IEEE
277 static APFloat getAllOnesValue(unsigned BitWidth, bool isIEEE = false);
278
279 /// @}
280
281 /// Used to insert APFloat objects, or objects that contain APFloat objects,
282 /// into FoldingSets.
283 void Profile(FoldingSetNodeID &NID) const;
284
285 /// \brief Used by the Bitcode serializer to emit APInts to Bitcode.
286 void Emit(Serializer &S) const;
287
288 /// \brief Used by the Bitcode deserializer to deserialize APInts.
289 static APFloat ReadVal(Deserializer &D);
290
291 /// \name Arithmetic
292 /// @{
293
294 opStatus add(const APFloat &, roundingMode);
295 opStatus subtract(const APFloat &, roundingMode);
296 opStatus multiply(const APFloat &, roundingMode);
297 opStatus divide(const APFloat &, roundingMode);
298 /// IEEE remainder.
299 opStatus remainder(const APFloat &);
300 /// C fmod, or llvm frem.
301 opStatus mod(const APFloat &, roundingMode);
302 opStatus fusedMultiplyAdd(const APFloat &, const APFloat &, roundingMode);
303 opStatus roundToIntegral(roundingMode);
304 /// IEEE-754R 5.3.1: nextUp/nextDown.
305 opStatus next(bool nextDown);
306
307 /// \brief Operator+ overload which provides the default
308 /// \c nmNearestTiesToEven rounding mode and *no* error checking.
309 APFloat operator+(const APFloat &RHS) const {
310 APFloat Result = *this;
311 Result.add(RHS, rmNearestTiesToEven);
312 return Result;
313 }
314
315 /// \brief Operator- overload which provides the default
316 /// \c nmNearestTiesToEven rounding mode and *no* error checking.
317 APFloat operator-(const APFloat &RHS) const {
318 APFloat Result = *this;
319 Result.subtract(RHS, rmNearestTiesToEven);
320 return Result;
321 }
322
323 /// \brief Operator* overload which provides the default
324 /// \c nmNearestTiesToEven rounding mode and *no* error checking.
325 APFloat operator*(const APFloat &RHS) const {
326 APFloat Result = *this;
327 Result.multiply(RHS, rmNearestTiesToEven);
328 return Result;
329 }
330
331 /// \brief Operator/ overload which provides the default
332 /// \c nmNearestTiesToEven rounding mode and *no* error checking.
333 APFloat operator/(const APFloat &RHS) const {
334 APFloat Result = *this;
335 Result.divide(RHS, rmNearestTiesToEven);
336 return Result;
337 }
338
339 /// @}
340
341 /// \name Sign operations.
342 /// @{
343
344 void changeSign();
345 void clearSign();
346 void copySign(const APFloat &);
347
348 /// \brief A static helper to produce a copy of an APFloat value with its sign
349 /// copied from some other APFloat.
copySign(APFloat Value,const APFloat & Sign)350 static APFloat copySign(APFloat Value, const APFloat &Sign) {
351 Value.copySign(Sign);
352 return std::move(Value);
353 }
354
355 /// @}
356
357 /// \name Conversions
358 /// @{
359
360 opStatus convert(const fltSemantics &, roundingMode, bool *);
361 opStatus convertToInteger(integerPart *, unsigned int, bool, roundingMode,
362 bool *) const;
363 opStatus convertToInteger(APSInt &, roundingMode, bool *) const;
364 opStatus convertFromAPInt(const APInt &, bool, roundingMode);
365 opStatus convertFromSignExtendedInteger(const integerPart *, unsigned int,
366 bool, roundingMode);
367 opStatus convertFromZeroExtendedInteger(const integerPart *, unsigned int,
368 bool, roundingMode);
369 opStatus convertFromString(StringRef, roundingMode);
370 APInt bitcastToAPInt() const;
371 double convertToDouble() const;
372 float convertToFloat() const;
373
374 /// @}
375
376 /// The definition of equality is not straightforward for floating point, so
377 /// we won't use operator==. Use one of the following, or write whatever it
378 /// is you really mean.
379 bool operator==(const APFloat &) const LLVM_DELETED_FUNCTION;
380
381 /// IEEE comparison with another floating point number (NaNs compare
382 /// unordered, 0==-0).
383 cmpResult compare(const APFloat &) const;
384
385 /// Bitwise comparison for equality (QNaNs compare equal, 0!=-0).
386 bool bitwiseIsEqual(const APFloat &) const;
387
388 /// Write out a hexadecimal representation of the floating point value to DST,
389 /// which must be of sufficient size, in the C99 form [-]0xh.hhhhp[+-]d.
390 /// Return the number of characters written, excluding the terminating NUL.
391 unsigned int convertToHexString(char *dst, unsigned int hexDigits,
392 bool upperCase, roundingMode) const;
393
394 /// \name IEEE-754R 5.7.2 General operations.
395 /// @{
396
397 /// IEEE-754R isSignMinus: Returns true if and only if the current value is
398 /// negative.
399 ///
400 /// This applies to zeros and NaNs as well.
isNegative()401 bool isNegative() const { return sign; }
402
403 /// IEEE-754R isNormal: Returns true if and only if the current value is normal.
404 ///
405 /// This implies that the current value of the float is not zero, subnormal,
406 /// infinite, or NaN following the definition of normality from IEEE-754R.
isNormal()407 bool isNormal() const { return !isDenormal() && isFiniteNonZero(); }
408
409 /// Returns true if and only if the current value is zero, subnormal, or
410 /// normal.
411 ///
412 /// This means that the value is not infinite or NaN.
isFinite()413 bool isFinite() const { return !isNaN() && !isInfinity(); }
414
415 /// Returns true if and only if the float is plus or minus zero.
isZero()416 bool isZero() const { return category == fcZero; }
417
418 /// IEEE-754R isSubnormal(): Returns true if and only if the float is a
419 /// denormal.
420 bool isDenormal() const;
421
422 /// IEEE-754R isInfinite(): Returns true if and only if the float is infinity.
isInfinity()423 bool isInfinity() const { return category == fcInfinity; }
424
425 /// Returns true if and only if the float is a quiet or signaling NaN.
isNaN()426 bool isNaN() const { return category == fcNaN; }
427
428 /// Returns true if and only if the float is a signaling NaN.
429 bool isSignaling() const;
430
431 /// @}
432
433 /// \name Simple Queries
434 /// @{
435
getCategory()436 fltCategory getCategory() const { return category; }
getSemantics()437 const fltSemantics &getSemantics() const { return *semantics; }
isNonZero()438 bool isNonZero() const { return category != fcZero; }
isFiniteNonZero()439 bool isFiniteNonZero() const { return isFinite() && !isZero(); }
isPosZero()440 bool isPosZero() const { return isZero() && !isNegative(); }
isNegZero()441 bool isNegZero() const { return isZero() && isNegative(); }
442
443 /// Returns true if and only if the number has the smallest possible non-zero
444 /// magnitude in the current semantics.
445 bool isSmallest() const;
446
447 /// Returns true if and only if the number has the largest possible finite
448 /// magnitude in the current semantics.
449 bool isLargest() const;
450
451 /// @}
452
453 APFloat &operator=(const APFloat &);
454 APFloat &operator=(APFloat &&);
455
456 /// \brief Overload to compute a hash code for an APFloat value.
457 ///
458 /// Note that the use of hash codes for floating point values is in general
459 /// frought with peril. Equality is hard to define for these values. For
460 /// example, should negative and positive zero hash to different codes? Are
461 /// they equal or not? This hash value implementation specifically
462 /// emphasizes producing different codes for different inputs in order to
463 /// be used in canonicalization and memoization. As such, equality is
464 /// bitwiseIsEqual, and 0 != -0.
465 friend hash_code hash_value(const APFloat &Arg);
466
467 /// Converts this value into a decimal string.
468 ///
469 /// \param FormatPrecision The maximum number of digits of
470 /// precision to output. If there are fewer digits available,
471 /// zero padding will not be used unless the value is
472 /// integral and small enough to be expressed in
473 /// FormatPrecision digits. 0 means to use the natural
474 /// precision of the number.
475 /// \param FormatMaxPadding The maximum number of zeros to
476 /// consider inserting before falling back to scientific
477 /// notation. 0 means to always use scientific notation.
478 ///
479 /// Number Precision MaxPadding Result
480 /// ------ --------- ---------- ------
481 /// 1.01E+4 5 2 10100
482 /// 1.01E+4 4 2 1.01E+4
483 /// 1.01E+4 5 1 1.01E+4
484 /// 1.01E-2 5 2 0.0101
485 /// 1.01E-2 4 2 0.0101
486 /// 1.01E-2 4 1 1.01E-2
487 void toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision = 0,
488 unsigned FormatMaxPadding = 3) const;
489
490 /// If this value has an exact multiplicative inverse, store it in inv and
491 /// return true.
492 bool getExactInverse(APFloat *inv) const;
493
494 /// \brief Enumeration of \c ilogb error results.
495 enum IlogbErrorKinds {
496 IEK_Zero = INT_MIN+1,
497 IEK_NaN = INT_MIN,
498 IEK_Inf = INT_MAX
499 };
500
501 /// \brief Returns the exponent of the internal representation of the APFloat.
502 ///
503 /// Because the radix of APFloat is 2, this is equivalent to floor(log2(x)).
504 /// For special APFloat values, this returns special error codes:
505 ///
506 /// NaN -> \c IEK_NaN
507 /// 0 -> \c IEK_Zero
508 /// Inf -> \c IEK_Inf
509 ///
ilogb(const APFloat & Arg)510 friend int ilogb(const APFloat &Arg) {
511 if (Arg.isNaN())
512 return IEK_NaN;
513 if (Arg.isZero())
514 return IEK_Zero;
515 if (Arg.isInfinity())
516 return IEK_Inf;
517
518 return Arg.exponent;
519 }
520
521 /// \brief Returns: X * 2^Exp for integral exponents.
522 friend APFloat scalbn(APFloat X, int Exp);
523
524 private:
525
526 /// \name Simple Queries
527 /// @{
528
529 integerPart *significandParts();
530 const integerPart *significandParts() const;
531 unsigned int partCount() const;
532
533 /// @}
534
535 /// \name Significand operations.
536 /// @{
537
538 integerPart addSignificand(const APFloat &);
539 integerPart subtractSignificand(const APFloat &, integerPart);
540 lostFraction addOrSubtractSignificand(const APFloat &, bool subtract);
541 lostFraction multiplySignificand(const APFloat &, const APFloat *);
542 lostFraction divideSignificand(const APFloat &);
543 void incrementSignificand();
544 void initialize(const fltSemantics *);
545 void shiftSignificandLeft(unsigned int);
546 lostFraction shiftSignificandRight(unsigned int);
547 unsigned int significandLSB() const;
548 unsigned int significandMSB() const;
549 void zeroSignificand();
550 /// Return true if the significand excluding the integral bit is all ones.
551 bool isSignificandAllOnes() const;
552 /// Return true if the significand excluding the integral bit is all zeros.
553 bool isSignificandAllZeros() const;
554
555 /// @}
556
557 /// \name Arithmetic on special values.
558 /// @{
559
560 opStatus addOrSubtractSpecials(const APFloat &, bool subtract);
561 opStatus divideSpecials(const APFloat &);
562 opStatus multiplySpecials(const APFloat &);
563 opStatus modSpecials(const APFloat &);
564
565 /// @}
566
567 /// \name Special value setters.
568 /// @{
569
570 void makeLargest(bool Neg = false);
571 void makeSmallest(bool Neg = false);
572 void makeNaN(bool SNaN = false, bool Neg = false,
573 const APInt *fill = nullptr);
574 static APFloat makeNaN(const fltSemantics &Sem, bool SNaN, bool Negative,
575 const APInt *fill);
576 void makeInf(bool Neg = false);
577 void makeZero(bool Neg = false);
578
579 /// @}
580
581 /// \name Miscellany
582 /// @{
583
584 bool convertFromStringSpecials(StringRef str);
585 opStatus normalize(roundingMode, lostFraction);
586 opStatus addOrSubtract(const APFloat &, roundingMode, bool subtract);
587 cmpResult compareAbsoluteValue(const APFloat &) const;
588 opStatus handleOverflow(roundingMode);
589 bool roundAwayFromZero(roundingMode, lostFraction, unsigned int) const;
590 opStatus convertToSignExtendedInteger(integerPart *, unsigned int, bool,
591 roundingMode, bool *) const;
592 opStatus convertFromUnsignedParts(const integerPart *, unsigned int,
593 roundingMode);
594 opStatus convertFromHexadecimalString(StringRef, roundingMode);
595 opStatus convertFromDecimalString(StringRef, roundingMode);
596 char *convertNormalToHexString(char *, unsigned int, bool,
597 roundingMode) const;
598 opStatus roundSignificandWithExponent(const integerPart *, unsigned int, int,
599 roundingMode);
600
601 /// @}
602
603 APInt convertHalfAPFloatToAPInt() const;
604 APInt convertFloatAPFloatToAPInt() const;
605 APInt convertDoubleAPFloatToAPInt() const;
606 APInt convertQuadrupleAPFloatToAPInt() const;
607 APInt convertF80LongDoubleAPFloatToAPInt() const;
608 APInt convertPPCDoubleDoubleAPFloatToAPInt() const;
609 void initFromAPInt(const fltSemantics *Sem, const APInt &api);
610 void initFromHalfAPInt(const APInt &api);
611 void initFromFloatAPInt(const APInt &api);
612 void initFromDoubleAPInt(const APInt &api);
613 void initFromQuadrupleAPInt(const APInt &api);
614 void initFromF80LongDoubleAPInt(const APInt &api);
615 void initFromPPCDoubleDoubleAPInt(const APInt &api);
616
617 void assign(const APFloat &);
618 void copySignificand(const APFloat &);
619 void freeSignificand();
620
621 /// The semantics that this value obeys.
622 const fltSemantics *semantics;
623
624 /// A binary fraction with an explicit integer bit.
625 ///
626 /// The significand must be at least one bit wider than the target precision.
627 union Significand {
628 integerPart part;
629 integerPart *parts;
630 } significand;
631
632 /// The signed unbiased exponent of the value.
633 ExponentType exponent;
634
635 /// What kind of floating point number this is.
636 ///
637 /// Only 2 bits are required, but VisualStudio incorrectly sign extends it.
638 /// Using the extra bit keeps it from failing under VisualStudio.
639 fltCategory category : 3;
640
641 /// Sign bit of the number.
642 unsigned int sign : 1;
643 };
644
645 /// See friend declarations above.
646 ///
647 /// These additional declarations are required in order to compile LLVM with IBM
648 /// xlC compiler.
649 hash_code hash_value(const APFloat &Arg);
650 APFloat scalbn(APFloat X, int Exp);
651
652 /// \brief Returns the absolute value of the argument.
abs(APFloat X)653 inline APFloat abs(APFloat X) {
654 X.clearSign();
655 return X;
656 }
657
658 /// Implements IEEE minNum semantics. Returns the smaller of the 2 arguments if
659 /// both are not NaN. If either argument is a NaN, returns the other argument.
660 LLVM_READONLY
minnum(const APFloat & A,const APFloat & B)661 inline APFloat minnum(const APFloat &A, const APFloat &B) {
662 if (A.isNaN())
663 return B;
664 if (B.isNaN())
665 return A;
666 return (B.compare(A) == APFloat::cmpLessThan) ? B : A;
667 }
668
669 /// Implements IEEE maxNum semantics. Returns the larger of the 2 arguments if
670 /// both are not NaN. If either argument is a NaN, returns the other argument.
671 LLVM_READONLY
maxnum(const APFloat & A,const APFloat & B)672 inline APFloat maxnum(const APFloat &A, const APFloat &B) {
673 if (A.isNaN())
674 return B;
675 if (B.isNaN())
676 return A;
677 return (A.compare(B) == APFloat::cmpLessThan) ? B : A;
678 }
679
680 } // namespace llvm
681
682 #endif // LLVM_ADT_APFLOAT_H
683