/3rd_party/llvm/include/llvm/ADT/APFloat.h

https://code.google.com/p/softart/ · C++ Header · 580 lines · 223 code · 92 blank · 265 comment · 11 complexity · 4627978b165b91a5a04bb593b50dac2b MD5 · raw file

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