LLVM API Documentation
00001 //== llvm/Support/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 // This file declares a class to represent arbitrary precision floating 00011 // point values and provide a variety of arithmetic operations on them. 00012 // 00013 //===----------------------------------------------------------------------===// 00014 00015 /* A self-contained host- and target-independent arbitrary-precision 00016 floating-point software implementation. It uses bignum integer 00017 arithmetic as provided by static functions in the APInt class. 00018 The library will work with bignum integers whose parts are any 00019 unsigned type at least 16 bits wide, but 64 bits is recommended. 00020 00021 Written for clarity rather than speed, in particular with a view 00022 to use in the front-end of a cross compiler so that target 00023 arithmetic can be correctly performed on the host. Performance 00024 should nonetheless be reasonable, particularly for its intended 00025 use. It may be useful as a base implementation for a run-time 00026 library during development of a faster target-specific one. 00027 00028 All 5 rounding modes in the IEEE-754R draft are handled correctly 00029 for all implemented operations. Currently implemented operations 00030 are add, subtract, multiply, divide, fused-multiply-add, 00031 conversion-to-float, conversion-to-integer and 00032 conversion-from-integer. New rounding modes (e.g. away from zero) 00033 can be added with three or four lines of code. 00034 00035 Four formats are built-in: IEEE single precision, double 00036 precision, quadruple precision, and x87 80-bit extended double 00037 (when operating with full extended precision). Adding a new 00038 format that obeys IEEE semantics only requires adding two lines of 00039 code: a declaration and definition of the format. 00040 00041 All operations return the status of that operation as an exception 00042 bit-mask, so multiple operations can be done consecutively with 00043 their results or-ed together. The returned status can be useful 00044 for compiler diagnostics; e.g., inexact, underflow and overflow 00045 can be easily diagnosed on constant folding, and compiler 00046 optimizers can determine what exceptions would be raised by 00047 folding operations and optimize, or perhaps not optimize, 00048 accordingly. 00049 00050 At present, underflow tininess is detected after rounding; it 00051 should be straight forward to add support for the before-rounding 00052 case too. 00053 00054 The library reads hexadecimal floating point numbers as per C99, 00055 and correctly rounds if necessary according to the specified 00056 rounding mode. Syntax is required to have been validated by the 00057 caller. It also converts floating point numbers to hexadecimal 00058 text as per the C99 %a and %A conversions. The output precision 00059 (or alternatively the natural minimal precision) can be specified; 00060 if the requested precision is less than the natural precision the 00061 output is correctly rounded for the specified rounding mode. 00062 00063 It also reads decimal floating point numbers and correctly rounds 00064 according to the specified rounding mode. 00065 00066 Conversion to decimal text is not currently implemented. 00067 00068 Non-zero finite numbers are represented internally as a sign bit, 00069 a 16-bit signed exponent, and the significand as an array of 00070 integer parts. After normalization of a number of precision P the 00071 exponent is within the range of the format, and if the number is 00072 not denormal the P-th bit of the significand is set as an explicit 00073 integer bit. For denormals the most significant bit is shifted 00074 right so that the exponent is maintained at the format's minimum, 00075 so that the smallest denormal has just the least significant bit 00076 of the significand set. The sign of zeroes and infinities is 00077 significant; the exponent and significand of such numbers is not 00078 stored, but has a known implicit (deterministic) value: 0 for the 00079 significands, 0 for zero exponent, all 1 bits for infinity 00080 exponent. For NaNs the sign and significand are deterministic, 00081 although not really meaningful, and preserved in non-conversion 00082 operations. The exponent is implicitly all 1 bits. 00083 00084 TODO 00085 ==== 00086 00087 Some features that may or may not be worth adding: 00088 00089 Binary to decimal conversion (hard). 00090 00091 Optional ability to detect underflow tininess before rounding. 00092 00093 New formats: x87 in single and double precision mode (IEEE apart 00094 from extended exponent range) (hard). 00095 00096 New operations: sqrt, IEEE remainder, C90 fmod, nextafter, 00097 nexttoward. 00098 */ 00099 00100 #ifndef LLVM_FLOAT_H 00101 #define LLVM_FLOAT_H 00102 00103 // APInt contains static functions implementing bignum arithmetic. 00104 #include "llvm/ADT/APInt.h" 00105 00106 namespace llvm { 00107 00108 /* Exponents are stored as signed numbers. */ 00109 typedef signed short exponent_t; 00110 00111 struct fltSemantics; 00112 class StringRef; 00113 00114 /* When bits of a floating point number are truncated, this enum is 00115 used to indicate what fraction of the LSB those bits represented. 00116 It essentially combines the roles of guard and sticky bits. */ 00117 enum lostFraction { // Example of truncated bits: 00118 lfExactlyZero, // 000000 00119 lfLessThanHalf, // 0xxxxx x's not all zero 00120 lfExactlyHalf, // 100000 00121 lfMoreThanHalf // 1xxxxx x's not all zero 00122 }; 00123 00124 class APFloat { 00125 public: 00126 00127 /* We support the following floating point semantics. */ 00128 static const fltSemantics IEEEsingle; 00129 static const fltSemantics IEEEdouble; 00130 static const fltSemantics IEEEquad; 00131 static const fltSemantics PPCDoubleDouble; 00132 static const fltSemantics x87DoubleExtended; 00133 /* And this pseudo, used to construct APFloats that cannot 00134 conflict with anything real. */ 00135 static const fltSemantics Bogus; 00136 00137 static unsigned int semanticsPrecision(const fltSemantics &); 00138 00139 /* Floating point numbers have a four-state comparison relation. */ 00140 enum cmpResult { 00141 cmpLessThan, 00142 cmpEqual, 00143 cmpGreaterThan, 00144 cmpUnordered 00145 }; 00146 00147 /* IEEE-754R gives five rounding modes. */ 00148 enum roundingMode { 00149 rmNearestTiesToEven, 00150 rmTowardPositive, 00151 rmTowardNegative, 00152 rmTowardZero, 00153 rmNearestTiesToAway 00154 }; 00155 00156 // Operation status. opUnderflow or opOverflow are always returned 00157 // or-ed with opInexact. 00158 enum opStatus { 00159 opOK = 0x00, 00160 opInvalidOp = 0x01, 00161 opDivByZero = 0x02, 00162 opOverflow = 0x04, 00163 opUnderflow = 0x08, 00164 opInexact = 0x10 00165 }; 00166 00167 // Category of internally-represented number. 00168 enum fltCategory { 00169 fcInfinity, 00170 fcNaN, 00171 fcNormal, 00172 fcZero 00173 }; 00174 00175 // Constructors. 00176 APFloat(const fltSemantics &, const StringRef &); 00177 APFloat(const fltSemantics &, integerPart); 00178 APFloat(const fltSemantics &, fltCategory, bool negative, unsigned type=0); 00179 explicit APFloat(double d); 00180 explicit APFloat(float f); 00181 explicit APFloat(const APInt &, bool isIEEE = false); 00182 APFloat(const APFloat &); 00183 ~APFloat(); 00184 00185 // Convenience "constructors" 00186 static APFloat getZero(const fltSemantics &Sem, bool Negative = false) { 00187 return APFloat(Sem, fcZero, Negative); 00188 } 00189 static APFloat getInf(const fltSemantics &Sem, bool Negative = false) { 00190 return APFloat(Sem, fcInfinity, Negative); 00191 } 00192 /// getNaN - Factory for QNaN values. 00193 /// 00194 /// \param Negative - True iff the NaN generated should be negative. 00195 /// \param type - The unspecified fill bits for creating the NaN, 0 by 00196 /// default. The value is truncated as necessary. 00197 static APFloat getNaN(const fltSemantics &Sem, bool Negative = false, 00198 unsigned type = 0) { 00199 return APFloat(Sem, fcNaN, Negative, type); 00200 } 00201 00202 /// Profile - Used to insert APFloat objects, or objects that contain 00203 /// APFloat objects, into FoldingSets. 00204 void Profile(FoldingSetNodeID& NID) const; 00205 00206 /// @brief Used by the Bitcode serializer to emit APInts to Bitcode. 00207 void Emit(Serializer& S) const; 00208 00209 /// @brief Used by the Bitcode deserializer to deserialize APInts. 00210 static APFloat ReadVal(Deserializer& D); 00211 00212 /* Arithmetic. */ 00213 opStatus add(const APFloat &, roundingMode); 00214 opStatus subtract(const APFloat &, roundingMode); 00215 opStatus multiply(const APFloat &, roundingMode); 00216 opStatus divide(const APFloat &, roundingMode); 00217 /* IEEE remainder. */ 00218 opStatus remainder(const APFloat &); 00219 /* C fmod, or llvm frem. */ 00220 opStatus mod(const APFloat &, roundingMode); 00221 opStatus fusedMultiplyAdd(const APFloat &, const APFloat &, roundingMode); 00222 00223 /* Sign operations. */ 00224 void changeSign(); 00225 void clearSign(); 00226 void copySign(const APFloat &); 00227 00228 /* Conversions. */ 00229 opStatus convert(const fltSemantics &, roundingMode, bool *); 00230 opStatus convertToInteger(integerPart *, unsigned int, bool, 00231 roundingMode, bool *) const; 00232 opStatus convertFromAPInt(const APInt &, 00233 bool, roundingMode); 00234 opStatus convertFromSignExtendedInteger(const integerPart *, unsigned int, 00235 bool, roundingMode); 00236 opStatus convertFromZeroExtendedInteger(const integerPart *, unsigned int, 00237 bool, roundingMode); 00238 opStatus convertFromString(const StringRef&, roundingMode); 00239 APInt bitcastToAPInt() const; 00240 double convertToDouble() const; 00241 float convertToFloat() const; 00242 00243 /* The definition of equality is not straightforward for floating point, 00244 so we won't use operator==. Use one of the following, or write 00245 whatever it is you really mean. */ 00246 // bool operator==(const APFloat &) const; // DO NOT IMPLEMENT 00247 00248 /* IEEE comparison with another floating point number (NaNs 00249 compare unordered, 0==-0). */ 00250 cmpResult compare(const APFloat &) const; 00251 00252 /* Bitwise comparison for equality (QNaNs compare equal, 0!=-0). */ 00253 bool bitwiseIsEqual(const APFloat &) const; 00254 00255 /* Write out a hexadecimal representation of the floating point 00256 value to DST, which must be of sufficient size, in the C99 form 00257 [-]0xh.hhhhp[+-]d. Return the number of characters written, 00258 excluding the terminating NUL. */ 00259 unsigned int convertToHexString(char *dst, unsigned int hexDigits, 00260 bool upperCase, roundingMode) const; 00261 00262 /* Simple queries. */ 00263 fltCategory getCategory() const { return category; } 00264 const fltSemantics &getSemantics() const { return *semantics; } 00265 bool isZero() const { return category == fcZero; } 00266 bool isNonZero() const { return category != fcZero; } 00267 bool isNaN() const { return category == fcNaN; } 00268 bool isInfinity() const { return category == fcInfinity; } 00269 bool isNegative() const { return sign; } 00270 bool isPosZero() const { return isZero() && !isNegative(); } 00271 bool isNegZero() const { return isZero() && isNegative(); } 00272 00273 APFloat& operator=(const APFloat &); 00274 00275 /* Return an arbitrary integer value usable for hashing. */ 00276 uint32_t getHashValue() const; 00277 00278 private: 00279 00280 /* Trivial queries. */ 00281 integerPart *significandParts(); 00282 const integerPart *significandParts() const; 00283 unsigned int partCount() const; 00284 00285 /* Significand operations. */ 00286 integerPart addSignificand(const APFloat &); 00287 integerPart subtractSignificand(const APFloat &, integerPart); 00288 lostFraction addOrSubtractSignificand(const APFloat &, bool subtract); 00289 lostFraction multiplySignificand(const APFloat &, const APFloat *); 00290 lostFraction divideSignificand(const APFloat &); 00291 void incrementSignificand(); 00292 void initialize(const fltSemantics *); 00293 void shiftSignificandLeft(unsigned int); 00294 lostFraction shiftSignificandRight(unsigned int); 00295 unsigned int significandLSB() const; 00296 unsigned int significandMSB() const; 00297 void zeroSignificand(); 00298 00299 /* Arithmetic on special values. */ 00300 opStatus addOrSubtractSpecials(const APFloat &, bool subtract); 00301 opStatus divideSpecials(const APFloat &); 00302 opStatus multiplySpecials(const APFloat &); 00303 opStatus modSpecials(const APFloat &); 00304 00305 /* Miscellany. */ 00306 void makeNaN(unsigned = 0); 00307 opStatus normalize(roundingMode, lostFraction); 00308 opStatus addOrSubtract(const APFloat &, roundingMode, bool subtract); 00309 cmpResult compareAbsoluteValue(const APFloat &) const; 00310 opStatus handleOverflow(roundingMode); 00311 bool roundAwayFromZero(roundingMode, lostFraction, unsigned int) const; 00312 opStatus convertToSignExtendedInteger(integerPart *, unsigned int, bool, 00313 roundingMode, bool *) const; 00314 opStatus convertFromUnsignedParts(const integerPart *, unsigned int, 00315 roundingMode); 00316 opStatus convertFromHexadecimalString(const StringRef&, roundingMode); 00317 opStatus convertFromDecimalString (const StringRef&, roundingMode); 00318 char *convertNormalToHexString(char *, unsigned int, bool, 00319 roundingMode) const; 00320 opStatus roundSignificandWithExponent(const integerPart *, unsigned int, 00321 int, roundingMode); 00322 00323 APInt convertFloatAPFloatToAPInt() const; 00324 APInt convertDoubleAPFloatToAPInt() const; 00325 APInt convertQuadrupleAPFloatToAPInt() const; 00326 APInt convertF80LongDoubleAPFloatToAPInt() const; 00327 APInt convertPPCDoubleDoubleAPFloatToAPInt() const; 00328 void initFromAPInt(const APInt& api, bool isIEEE = false); 00329 void initFromFloatAPInt(const APInt& api); 00330 void initFromDoubleAPInt(const APInt& api); 00331 void initFromQuadrupleAPInt(const APInt &api); 00332 void initFromF80LongDoubleAPInt(const APInt& api); 00333 void initFromPPCDoubleDoubleAPInt(const APInt& api); 00334 00335 void assign(const APFloat &); 00336 void copySignificand(const APFloat &); 00337 void freeSignificand(); 00338 00339 /* What kind of semantics does this value obey? */ 00340 const fltSemantics *semantics; 00341 00342 /* Significand - the fraction with an explicit integer bit. Must be 00343 at least one bit wider than the target precision. */ 00344 union Significand 00345 { 00346 integerPart part; 00347 integerPart *parts; 00348 } significand; 00349 00350 /* The exponent - a signed number. */ 00351 exponent_t exponent; 00352 00353 /* What kind of floating point number this is. */ 00354 /* Only 2 bits are required, but VisualStudio incorrectly sign extends 00355 it. Using the extra bit keeps it from failing under VisualStudio */ 00356 fltCategory category: 3; 00357 00358 /* The sign bit of this number. */ 00359 unsigned int sign: 1; 00360 00361 /* For PPCDoubleDouble, we have a second exponent and sign (the second 00362 significand is appended to the first one, although it would be wrong to 00363 regard these as a single number for arithmetic purposes). These fields 00364 are not meaningful for any other type. */ 00365 exponent_t exponent2 : 11; 00366 unsigned int sign2: 1; 00367 }; 00368 } /* namespace llvm */ 00369 00370 #endif /* LLVM_FLOAT_H */