LLVM API Documentation
00001 //===- llvm/ADT/APFloat.h - Arbitrary Precision Floating Point ---*- C++ -*-==// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 /// 00010 /// \file 00011 /// \brief 00012 /// This file declares a class to represent arbitrary precision floating point 00013 /// values and provide a variety of arithmetic operations on them. 00014 /// 00015 //===----------------------------------------------------------------------===// 00016 00017 #ifndef LLVM_ADT_APFLOAT_H 00018 #define LLVM_ADT_APFLOAT_H 00019 00020 #include "llvm/ADT/APInt.h" 00021 00022 namespace llvm { 00023 00024 struct fltSemantics; 00025 class APSInt; 00026 class StringRef; 00027 00028 /// Enum that represents what fraction of the LSB truncated bits of an fp number 00029 /// represent. 00030 /// 00031 /// This essentially combines the roles of guard and sticky bits. 00032 enum lostFraction { // Example of truncated bits: 00033 lfExactlyZero, // 000000 00034 lfLessThanHalf, // 0xxxxx x's not all zero 00035 lfExactlyHalf, // 100000 00036 lfMoreThanHalf // 1xxxxx x's not all zero 00037 }; 00038 00039 /// \brief A self-contained host- and target-independent arbitrary-precision 00040 /// floating-point software implementation. 00041 /// 00042 /// APFloat uses bignum integer arithmetic as provided by static functions in 00043 /// the APInt class. The library will work with bignum integers whose parts are 00044 /// any unsigned type at least 16 bits wide, but 64 bits is recommended. 00045 /// 00046 /// Written for clarity rather than speed, in particular with a view to use in 00047 /// the front-end of a cross compiler so that target arithmetic can be correctly 00048 /// performed on the host. Performance should nonetheless be reasonable, 00049 /// particularly for its intended use. It may be useful as a base 00050 /// implementation for a run-time library during development of a faster 00051 /// target-specific one. 00052 /// 00053 /// All 5 rounding modes in the IEEE-754R draft are handled correctly for all 00054 /// implemented operations. Currently implemented operations are add, subtract, 00055 /// multiply, divide, fused-multiply-add, conversion-to-float, 00056 /// conversion-to-integer and conversion-from-integer. New rounding modes 00057 /// (e.g. away from zero) can be added with three or four lines of code. 00058 /// 00059 /// Four formats are built-in: IEEE single precision, double precision, 00060 /// quadruple precision, and x87 80-bit extended double (when operating with 00061 /// full extended precision). Adding a new format that obeys IEEE semantics 00062 /// only requires adding two lines of code: a declaration and definition of the 00063 /// format. 00064 /// 00065 /// All operations return the status of that operation as an exception bit-mask, 00066 /// so multiple operations can be done consecutively with their results or-ed 00067 /// together. The returned status can be useful for compiler diagnostics; e.g., 00068 /// inexact, underflow and overflow can be easily diagnosed on constant folding, 00069 /// and compiler optimizers can determine what exceptions would be raised by 00070 /// folding operations and optimize, or perhaps not optimize, accordingly. 00071 /// 00072 /// At present, underflow tininess is detected after rounding; it should be 00073 /// straight forward to add support for the before-rounding case too. 00074 /// 00075 /// The library reads hexadecimal floating point numbers as per C99, and 00076 /// correctly rounds if necessary according to the specified rounding mode. 00077 /// Syntax is required to have been validated by the caller. It also converts 00078 /// floating point numbers to hexadecimal text as per the C99 %a and %A 00079 /// conversions. The output precision (or alternatively the natural minimal 00080 /// precision) can be specified; if the requested precision is less than the 00081 /// natural precision the output is correctly rounded for the specified rounding 00082 /// mode. 00083 /// 00084 /// It also reads decimal floating point numbers and correctly rounds according 00085 /// to the specified rounding mode. 00086 /// 00087 /// Conversion to decimal text is not currently implemented. 00088 /// 00089 /// Non-zero finite numbers are represented internally as a sign bit, a 16-bit 00090 /// signed exponent, and the significand as an array of integer parts. After 00091 /// normalization of a number of precision P the exponent is within the range of 00092 /// the format, and if the number is not denormal the P-th bit of the 00093 /// significand is set as an explicit integer bit. For denormals the most 00094 /// significant bit is shifted right so that the exponent is maintained at the 00095 /// format's minimum, so that the smallest denormal has just the least 00096 /// significant bit of the significand set. The sign of zeroes and infinities 00097 /// is significant; the exponent and significand of such numbers is not stored, 00098 /// but has a known implicit (deterministic) value: 0 for the significands, 0 00099 /// for zero exponent, all 1 bits for infinity exponent. For NaNs the sign and 00100 /// significand are deterministic, although not really meaningful, and preserved 00101 /// in non-conversion operations. The exponent is implicitly all 1 bits. 00102 /// 00103 /// APFloat does not provide any exception handling beyond default exception 00104 /// handling. We represent Signaling NaNs via IEEE-754R 2008 6.2.1 should clause 00105 /// by encoding Signaling NaNs with the first bit of its trailing significand as 00106 /// 0. 00107 /// 00108 /// TODO 00109 /// ==== 00110 /// 00111 /// Some features that may or may not be worth adding: 00112 /// 00113 /// Binary to decimal conversion (hard). 00114 /// 00115 /// Optional ability to detect underflow tininess before rounding. 00116 /// 00117 /// New formats: x87 in single and double precision mode (IEEE apart from 00118 /// extended exponent range) (hard). 00119 /// 00120 /// New operations: sqrt, IEEE remainder, C90 fmod, nexttoward. 00121 /// 00122 class APFloat { 00123 public: 00124 00125 /// A signed type to represent a floating point numbers unbiased exponent. 00126 typedef signed short ExponentType; 00127 00128 /// \name Floating Point Semantics. 00129 /// @{ 00130 00131 static const fltSemantics IEEEhalf; 00132 static const fltSemantics IEEEsingle; 00133 static const fltSemantics IEEEdouble; 00134 static const fltSemantics IEEEquad; 00135 static const fltSemantics PPCDoubleDouble; 00136 static const fltSemantics x87DoubleExtended; 00137 00138 /// A Pseudo fltsemantic used to construct APFloats that cannot conflict with 00139 /// anything real. 00140 static const fltSemantics Bogus; 00141 00142 /// @} 00143 00144 static unsigned int semanticsPrecision(const fltSemantics &); 00145 00146 /// IEEE-754R 5.11: Floating Point Comparison Relations. 00147 enum cmpResult { 00148 cmpLessThan, 00149 cmpEqual, 00150 cmpGreaterThan, 00151 cmpUnordered 00152 }; 00153 00154 /// IEEE-754R 4.3: Rounding-direction attributes. 00155 enum roundingMode { 00156 rmNearestTiesToEven, 00157 rmTowardPositive, 00158 rmTowardNegative, 00159 rmTowardZero, 00160 rmNearestTiesToAway 00161 }; 00162 00163 /// IEEE-754R 7: Default exception handling. 00164 /// 00165 /// opUnderflow or opOverflow are always returned or-ed with opInexact. 00166 enum opStatus { 00167 opOK = 0x00, 00168 opInvalidOp = 0x01, 00169 opDivByZero = 0x02, 00170 opOverflow = 0x04, 00171 opUnderflow = 0x08, 00172 opInexact = 0x10 00173 }; 00174 00175 /// Category of internally-represented number. 00176 enum fltCategory { 00177 fcInfinity, 00178 fcNaN, 00179 fcNormal, 00180 fcZero 00181 }; 00182 00183 /// Convenience enum used to construct an uninitialized APFloat. 00184 enum uninitializedTag { 00185 uninitialized 00186 }; 00187 00188 /// \name Constructors 00189 /// @{ 00190 00191 APFloat(const fltSemantics &); // Default construct to 0.0 00192 APFloat(const fltSemantics &, StringRef); 00193 APFloat(const fltSemantics &, integerPart); 00194 APFloat(const fltSemantics &, uninitializedTag); 00195 APFloat(const fltSemantics &, const APInt &); 00196 explicit APFloat(double d); 00197 explicit APFloat(float f); 00198 APFloat(const APFloat &); 00199 APFloat(APFloat &&); 00200 ~APFloat(); 00201 00202 /// @} 00203 00204 /// \brief Returns whether this instance allocated memory. 00205 bool needsCleanup() const { return partCount() > 1; } 00206 00207 /// \name Convenience "constructors" 00208 /// @{ 00209 00210 /// Factory for Positive and Negative Zero. 00211 /// 00212 /// \param Negative True iff the number should be negative. 00213 static APFloat getZero(const fltSemantics &Sem, bool Negative = false) { 00214 APFloat Val(Sem, uninitialized); 00215 Val.makeZero(Negative); 00216 return Val; 00217 } 00218 00219 /// Factory for Positive and Negative Infinity. 00220 /// 00221 /// \param Negative True iff the number should be negative. 00222 static APFloat getInf(const fltSemantics &Sem, bool Negative = false) { 00223 APFloat Val(Sem, uninitialized); 00224 Val.makeInf(Negative); 00225 return Val; 00226 } 00227 00228 /// Factory for QNaN values. 00229 /// 00230 /// \param Negative - True iff the NaN generated should be negative. 00231 /// \param type - The unspecified fill bits for creating the NaN, 0 by 00232 /// default. The value is truncated as necessary. 00233 static APFloat getNaN(const fltSemantics &Sem, bool Negative = false, 00234 unsigned type = 0) { 00235 if (type) { 00236 APInt fill(64, type); 00237 return getQNaN(Sem, Negative, &fill); 00238 } else { 00239 return getQNaN(Sem, Negative, nullptr); 00240 } 00241 } 00242 00243 /// Factory for QNaN values. 00244 static APFloat getQNaN(const fltSemantics &Sem, bool Negative = false, 00245 const APInt *payload = nullptr) { 00246 return makeNaN(Sem, false, Negative, payload); 00247 } 00248 00249 /// Factory for SNaN values. 00250 static APFloat getSNaN(const fltSemantics &Sem, bool Negative = false, 00251 const APInt *payload = nullptr) { 00252 return makeNaN(Sem, true, Negative, payload); 00253 } 00254 00255 /// Returns the largest finite number in the given semantics. 00256 /// 00257 /// \param Negative - True iff the number should be negative 00258 static APFloat getLargest(const fltSemantics &Sem, bool Negative = false); 00259 00260 /// Returns the smallest (by magnitude) finite number in the given semantics. 00261 /// Might be denormalized, which implies a relative loss of precision. 00262 /// 00263 /// \param Negative - True iff the number should be negative 00264 static APFloat getSmallest(const fltSemantics &Sem, bool Negative = false); 00265 00266 /// Returns the smallest (by magnitude) normalized finite number in the given 00267 /// semantics. 00268 /// 00269 /// \param Negative - True iff the number should be negative 00270 static APFloat getSmallestNormalized(const fltSemantics &Sem, 00271 bool Negative = false); 00272 00273 /// Returns a float which is bitcasted from an all one value int. 00274 /// 00275 /// \param BitWidth - Select float type 00276 /// \param isIEEE - If 128 bit number, select between PPC and IEEE 00277 static APFloat getAllOnesValue(unsigned BitWidth, bool isIEEE = false); 00278 00279 /// @} 00280 00281 /// Used to insert APFloat objects, or objects that contain APFloat objects, 00282 /// into FoldingSets. 00283 void Profile(FoldingSetNodeID &NID) const; 00284 00285 /// \brief Used by the Bitcode serializer to emit APInts to Bitcode. 00286 void Emit(Serializer &S) const; 00287 00288 /// \brief Used by the Bitcode deserializer to deserialize APInts. 00289 static APFloat ReadVal(Deserializer &D); 00290 00291 /// \name Arithmetic 00292 /// @{ 00293 00294 opStatus add(const APFloat &, roundingMode); 00295 opStatus subtract(const APFloat &, roundingMode); 00296 opStatus multiply(const APFloat &, roundingMode); 00297 opStatus divide(const APFloat &, roundingMode); 00298 /// IEEE remainder. 00299 opStatus remainder(const APFloat &); 00300 /// C fmod, or llvm frem. 00301 opStatus mod(const APFloat &, roundingMode); 00302 opStatus fusedMultiplyAdd(const APFloat &, const APFloat &, roundingMode); 00303 opStatus roundToIntegral(roundingMode); 00304 /// IEEE-754R 5.3.1: nextUp/nextDown. 00305 opStatus next(bool nextDown); 00306 00307 /// @} 00308 00309 /// \name Sign operations. 00310 /// @{ 00311 00312 void changeSign(); 00313 void clearSign(); 00314 void copySign(const APFloat &); 00315 00316 /// @} 00317 00318 /// \name Conversions 00319 /// @{ 00320 00321 opStatus convert(const fltSemantics &, roundingMode, bool *); 00322 opStatus convertToInteger(integerPart *, unsigned int, bool, roundingMode, 00323 bool *) const; 00324 opStatus convertToInteger(APSInt &, roundingMode, bool *) const; 00325 opStatus convertFromAPInt(const APInt &, bool, roundingMode); 00326 opStatus convertFromSignExtendedInteger(const integerPart *, unsigned int, 00327 bool, roundingMode); 00328 opStatus convertFromZeroExtendedInteger(const integerPart *, unsigned int, 00329 bool, roundingMode); 00330 opStatus convertFromString(StringRef, roundingMode); 00331 APInt bitcastToAPInt() const; 00332 double convertToDouble() const; 00333 float convertToFloat() const; 00334 00335 /// @} 00336 00337 /// The definition of equality is not straightforward for floating point, so 00338 /// we won't use operator==. Use one of the following, or write whatever it 00339 /// is you really mean. 00340 bool operator==(const APFloat &) const LLVM_DELETED_FUNCTION; 00341 00342 /// IEEE comparison with another floating point number (NaNs compare 00343 /// unordered, 0==-0). 00344 cmpResult compare(const APFloat &) const; 00345 00346 /// Bitwise comparison for equality (QNaNs compare equal, 0!=-0). 00347 bool bitwiseIsEqual(const APFloat &) const; 00348 00349 /// Write out a hexadecimal representation of the floating point value to DST, 00350 /// which must be of sufficient size, in the C99 form [-]0xh.hhhhp[+-]d. 00351 /// Return the number of characters written, excluding the terminating NUL. 00352 unsigned int convertToHexString(char *dst, unsigned int hexDigits, 00353 bool upperCase, roundingMode) const; 00354 00355 /// \name IEEE-754R 5.7.2 General operations. 00356 /// @{ 00357 00358 /// IEEE-754R isSignMinus: Returns true if and only if the current value is 00359 /// negative. 00360 /// 00361 /// This applies to zeros and NaNs as well. 00362 bool isNegative() const { return sign; } 00363 00364 /// IEEE-754R isNormal: Returns true if and only if the current value is normal. 00365 /// 00366 /// This implies that the current value of the float is not zero, subnormal, 00367 /// infinite, or NaN following the definition of normality from IEEE-754R. 00368 bool isNormal() const { return !isDenormal() && isFiniteNonZero(); } 00369 00370 /// Returns true if and only if the current value is zero, subnormal, or 00371 /// normal. 00372 /// 00373 /// This means that the value is not infinite or NaN. 00374 bool isFinite() const { return !isNaN() && !isInfinity(); } 00375 00376 /// Returns true if and only if the float is plus or minus zero. 00377 bool isZero() const { return category == fcZero; } 00378 00379 /// IEEE-754R isSubnormal(): Returns true if and only if the float is a 00380 /// denormal. 00381 bool isDenormal() const; 00382 00383 /// IEEE-754R isInfinite(): Returns true if and only if the float is infinity. 00384 bool isInfinity() const { return category == fcInfinity; } 00385 00386 /// Returns true if and only if the float is a quiet or signaling NaN. 00387 bool isNaN() const { return category == fcNaN; } 00388 00389 /// Returns true if and only if the float is a signaling NaN. 00390 bool isSignaling() const; 00391 00392 /// @} 00393 00394 /// \name Simple Queries 00395 /// @{ 00396 00397 fltCategory getCategory() const { return category; } 00398 const fltSemantics &getSemantics() const { return *semantics; } 00399 bool isNonZero() const { return category != fcZero; } 00400 bool isFiniteNonZero() const { return isFinite() && !isZero(); } 00401 bool isPosZero() const { return isZero() && !isNegative(); } 00402 bool isNegZero() const { return isZero() && isNegative(); } 00403 00404 /// Returns true if and only if the number has the smallest possible non-zero 00405 /// magnitude in the current semantics. 00406 bool isSmallest() const; 00407 00408 /// Returns true if and only if the number has the largest possible finite 00409 /// magnitude in the current semantics. 00410 bool isLargest() const; 00411 00412 /// @} 00413 00414 APFloat &operator=(const APFloat &); 00415 APFloat &operator=(APFloat &&); 00416 00417 /// \brief Overload to compute a hash code for an APFloat value. 00418 /// 00419 /// Note that the use of hash codes for floating point values is in general 00420 /// frought with peril. Equality is hard to define for these values. For 00421 /// example, should negative and positive zero hash to different codes? Are 00422 /// they equal or not? This hash value implementation specifically 00423 /// emphasizes producing different codes for different inputs in order to 00424 /// be used in canonicalization and memoization. As such, equality is 00425 /// bitwiseIsEqual, and 0 != -0. 00426 friend hash_code hash_value(const APFloat &Arg); 00427 00428 /// Converts this value into a decimal string. 00429 /// 00430 /// \param FormatPrecision The maximum number of digits of 00431 /// precision to output. If there are fewer digits available, 00432 /// zero padding will not be used unless the value is 00433 /// integral and small enough to be expressed in 00434 /// FormatPrecision digits. 0 means to use the natural 00435 /// precision of the number. 00436 /// \param FormatMaxPadding The maximum number of zeros to 00437 /// consider inserting before falling back to scientific 00438 /// notation. 0 means to always use scientific notation. 00439 /// 00440 /// Number Precision MaxPadding Result 00441 /// ------ --------- ---------- ------ 00442 /// 1.01E+4 5 2 10100 00443 /// 1.01E+4 4 2 1.01E+4 00444 /// 1.01E+4 5 1 1.01E+4 00445 /// 1.01E-2 5 2 0.0101 00446 /// 1.01E-2 4 2 0.0101 00447 /// 1.01E-2 4 1 1.01E-2 00448 void toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision = 0, 00449 unsigned FormatMaxPadding = 3) const; 00450 00451 /// If this value has an exact multiplicative inverse, store it in inv and 00452 /// return true. 00453 bool getExactInverse(APFloat *inv) const; 00454 00455 private: 00456 00457 /// \name Simple Queries 00458 /// @{ 00459 00460 integerPart *significandParts(); 00461 const integerPart *significandParts() const; 00462 unsigned int partCount() const; 00463 00464 /// @} 00465 00466 /// \name Significand operations. 00467 /// @{ 00468 00469 integerPart addSignificand(const APFloat &); 00470 integerPart subtractSignificand(const APFloat &, integerPart); 00471 lostFraction addOrSubtractSignificand(const APFloat &, bool subtract); 00472 lostFraction multiplySignificand(const APFloat &, const APFloat *); 00473 lostFraction divideSignificand(const APFloat &); 00474 void incrementSignificand(); 00475 void initialize(const fltSemantics *); 00476 void shiftSignificandLeft(unsigned int); 00477 lostFraction shiftSignificandRight(unsigned int); 00478 unsigned int significandLSB() const; 00479 unsigned int significandMSB() const; 00480 void zeroSignificand(); 00481 /// Return true if the significand excluding the integral bit is all ones. 00482 bool isSignificandAllOnes() const; 00483 /// Return true if the significand excluding the integral bit is all zeros. 00484 bool isSignificandAllZeros() const; 00485 00486 /// @} 00487 00488 /// \name Arithmetic on special values. 00489 /// @{ 00490 00491 opStatus addOrSubtractSpecials(const APFloat &, bool subtract); 00492 opStatus divideSpecials(const APFloat &); 00493 opStatus multiplySpecials(const APFloat &); 00494 opStatus modSpecials(const APFloat &); 00495 00496 /// @} 00497 00498 /// \name Special value setters. 00499 /// @{ 00500 00501 void makeLargest(bool Neg = false); 00502 void makeSmallest(bool Neg = false); 00503 void makeNaN(bool SNaN = false, bool Neg = false, 00504 const APInt *fill = nullptr); 00505 static APFloat makeNaN(const fltSemantics &Sem, bool SNaN, bool Negative, 00506 const APInt *fill); 00507 void makeInf(bool Neg = false); 00508 void makeZero(bool Neg = false); 00509 00510 /// @} 00511 00512 /// \name Miscellany 00513 /// @{ 00514 00515 bool convertFromStringSpecials(StringRef str); 00516 opStatus normalize(roundingMode, lostFraction); 00517 opStatus addOrSubtract(const APFloat &, roundingMode, bool subtract); 00518 cmpResult compareAbsoluteValue(const APFloat &) const; 00519 opStatus handleOverflow(roundingMode); 00520 bool roundAwayFromZero(roundingMode, lostFraction, unsigned int) const; 00521 opStatus convertToSignExtendedInteger(integerPart *, unsigned int, bool, 00522 roundingMode, bool *) const; 00523 opStatus convertFromUnsignedParts(const integerPart *, unsigned int, 00524 roundingMode); 00525 opStatus convertFromHexadecimalString(StringRef, roundingMode); 00526 opStatus convertFromDecimalString(StringRef, roundingMode); 00527 char *convertNormalToHexString(char *, unsigned int, bool, 00528 roundingMode) const; 00529 opStatus roundSignificandWithExponent(const integerPart *, unsigned int, int, 00530 roundingMode); 00531 00532 /// @} 00533 00534 APInt convertHalfAPFloatToAPInt() const; 00535 APInt convertFloatAPFloatToAPInt() const; 00536 APInt convertDoubleAPFloatToAPInt() const; 00537 APInt convertQuadrupleAPFloatToAPInt() const; 00538 APInt convertF80LongDoubleAPFloatToAPInt() const; 00539 APInt convertPPCDoubleDoubleAPFloatToAPInt() const; 00540 void initFromAPInt(const fltSemantics *Sem, const APInt &api); 00541 void initFromHalfAPInt(const APInt &api); 00542 void initFromFloatAPInt(const APInt &api); 00543 void initFromDoubleAPInt(const APInt &api); 00544 void initFromQuadrupleAPInt(const APInt &api); 00545 void initFromF80LongDoubleAPInt(const APInt &api); 00546 void initFromPPCDoubleDoubleAPInt(const APInt &api); 00547 00548 void assign(const APFloat &); 00549 void copySignificand(const APFloat &); 00550 void freeSignificand(); 00551 00552 /// The semantics that this value obeys. 00553 const fltSemantics *semantics; 00554 00555 /// A binary fraction with an explicit integer bit. 00556 /// 00557 /// The significand must be at least one bit wider than the target precision. 00558 union Significand { 00559 integerPart part; 00560 integerPart *parts; 00561 } significand; 00562 00563 /// The signed unbiased exponent of the value. 00564 ExponentType exponent; 00565 00566 /// What kind of floating point number this is. 00567 /// 00568 /// Only 2 bits are required, but VisualStudio incorrectly sign extends it. 00569 /// Using the extra bit keeps it from failing under VisualStudio. 00570 fltCategory category : 3; 00571 00572 /// Sign bit of the number. 00573 unsigned int sign : 1; 00574 }; 00575 00576 /// See friend declaration above. 00577 /// 00578 /// This additional declaration is required in order to compile LLVM with IBM 00579 /// xlC compiler. 00580 hash_code hash_value(const APFloat &Arg); 00581 } // namespace llvm 00582 00583 #endif // LLVM_ADT_APFLOAT_H