APFloat.h 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/ADT/APFloat.h - Arbitrary Precision Floating Point ---*- C++ -*-==//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. ///
  14. /// \file
  15. /// This file declares a class to represent arbitrary precision floating point
  16. /// values and provide a variety of arithmetic operations on them.
  17. ///
  18. //===----------------------------------------------------------------------===//
  19. #ifndef LLVM_ADT_APFLOAT_H
  20. #define LLVM_ADT_APFLOAT_H
  21. #include "llvm/ADT/APInt.h"
  22. #include "llvm/ADT/ArrayRef.h"
  23. #include "llvm/ADT/FloatingPointMode.h"
  24. #include "llvm/Support/ErrorHandling.h"
  25. #include <memory>
  26. #define APFLOAT_DISPATCH_ON_SEMANTICS(METHOD_CALL) \
  27. do { \
  28. if (usesLayout<IEEEFloat>(getSemantics())) \
  29. return U.IEEE.METHOD_CALL; \
  30. if (usesLayout<DoubleAPFloat>(getSemantics())) \
  31. return U.Double.METHOD_CALL; \
  32. llvm_unreachable("Unexpected semantics"); \
  33. } while (false)
  34. namespace llvm {
  35. struct fltSemantics;
  36. class APSInt;
  37. class StringRef;
  38. class APFloat;
  39. class raw_ostream;
  40. template <typename T> class Expected;
  41. template <typename T> class SmallVectorImpl;
  42. /// Enum that represents what fraction of the LSB truncated bits of an fp number
  43. /// represent.
  44. ///
  45. /// This essentially combines the roles of guard and sticky bits.
  46. enum lostFraction { // Example of truncated bits:
  47. lfExactlyZero, // 000000
  48. lfLessThanHalf, // 0xxxxx x's not all zero
  49. lfExactlyHalf, // 100000
  50. lfMoreThanHalf // 1xxxxx x's not all zero
  51. };
  52. /// A self-contained host- and target-independent arbitrary-precision
  53. /// floating-point software implementation.
  54. ///
  55. /// APFloat uses bignum integer arithmetic as provided by static functions in
  56. /// the APInt class. The library will work with bignum integers whose parts are
  57. /// any unsigned type at least 16 bits wide, but 64 bits is recommended.
  58. ///
  59. /// Written for clarity rather than speed, in particular with a view to use in
  60. /// the front-end of a cross compiler so that target arithmetic can be correctly
  61. /// performed on the host. Performance should nonetheless be reasonable,
  62. /// particularly for its intended use. It may be useful as a base
  63. /// implementation for a run-time library during development of a faster
  64. /// target-specific one.
  65. ///
  66. /// All 5 rounding modes in the IEEE-754R draft are handled correctly for all
  67. /// implemented operations. Currently implemented operations are add, subtract,
  68. /// multiply, divide, fused-multiply-add, conversion-to-float,
  69. /// conversion-to-integer and conversion-from-integer. New rounding modes
  70. /// (e.g. away from zero) can be added with three or four lines of code.
  71. ///
  72. /// Four formats are built-in: IEEE single precision, double precision,
  73. /// quadruple precision, and x87 80-bit extended double (when operating with
  74. /// full extended precision). Adding a new format that obeys IEEE semantics
  75. /// only requires adding two lines of code: a declaration and definition of the
  76. /// format.
  77. ///
  78. /// All operations return the status of that operation as an exception bit-mask,
  79. /// so multiple operations can be done consecutively with their results or-ed
  80. /// together. The returned status can be useful for compiler diagnostics; e.g.,
  81. /// inexact, underflow and overflow can be easily diagnosed on constant folding,
  82. /// and compiler optimizers can determine what exceptions would be raised by
  83. /// folding operations and optimize, or perhaps not optimize, accordingly.
  84. ///
  85. /// At present, underflow tininess is detected after rounding; it should be
  86. /// straight forward to add support for the before-rounding case too.
  87. ///
  88. /// The library reads hexadecimal floating point numbers as per C99, and
  89. /// correctly rounds if necessary according to the specified rounding mode.
  90. /// Syntax is required to have been validated by the caller. It also converts
  91. /// floating point numbers to hexadecimal text as per the C99 %a and %A
  92. /// conversions. The output precision (or alternatively the natural minimal
  93. /// precision) can be specified; if the requested precision is less than the
  94. /// natural precision the output is correctly rounded for the specified rounding
  95. /// mode.
  96. ///
  97. /// It also reads decimal floating point numbers and correctly rounds according
  98. /// to the specified rounding mode.
  99. ///
  100. /// Conversion to decimal text is not currently implemented.
  101. ///
  102. /// Non-zero finite numbers are represented internally as a sign bit, a 16-bit
  103. /// signed exponent, and the significand as an array of integer parts. After
  104. /// normalization of a number of precision P the exponent is within the range of
  105. /// the format, and if the number is not denormal the P-th bit of the
  106. /// significand is set as an explicit integer bit. For denormals the most
  107. /// significant bit is shifted right so that the exponent is maintained at the
  108. /// format's minimum, so that the smallest denormal has just the least
  109. /// significant bit of the significand set. The sign of zeroes and infinities
  110. /// is significant; the exponent and significand of such numbers is not stored,
  111. /// but has a known implicit (deterministic) value: 0 for the significands, 0
  112. /// for zero exponent, all 1 bits for infinity exponent. For NaNs the sign and
  113. /// significand are deterministic, although not really meaningful, and preserved
  114. /// in non-conversion operations. The exponent is implicitly all 1 bits.
  115. ///
  116. /// APFloat does not provide any exception handling beyond default exception
  117. /// handling. We represent Signaling NaNs via IEEE-754R 2008 6.2.1 should clause
  118. /// by encoding Signaling NaNs with the first bit of its trailing significand as
  119. /// 0.
  120. ///
  121. /// TODO
  122. /// ====
  123. ///
  124. /// Some features that may or may not be worth adding:
  125. ///
  126. /// Binary to decimal conversion (hard).
  127. ///
  128. /// Optional ability to detect underflow tininess before rounding.
  129. ///
  130. /// New formats: x87 in single and double precision mode (IEEE apart from
  131. /// extended exponent range) (hard).
  132. ///
  133. /// New operations: sqrt, IEEE remainder, C90 fmod, nexttoward.
  134. ///
  135. // This is the common type definitions shared by APFloat and its internal
  136. // implementation classes. This struct should not define any non-static data
  137. // members.
  138. struct APFloatBase {
  139. typedef APInt::WordType integerPart;
  140. static constexpr unsigned integerPartWidth = APInt::APINT_BITS_PER_WORD;
  141. /// A signed type to represent a floating point numbers unbiased exponent.
  142. typedef int32_t ExponentType;
  143. /// \name Floating Point Semantics.
  144. /// @{
  145. enum Semantics {
  146. S_IEEEhalf,
  147. S_BFloat,
  148. S_IEEEsingle,
  149. S_IEEEdouble,
  150. S_x87DoubleExtended,
  151. S_IEEEquad,
  152. S_PPCDoubleDouble
  153. };
  154. static const llvm::fltSemantics &EnumToSemantics(Semantics S);
  155. static Semantics SemanticsToEnum(const llvm::fltSemantics &Sem);
  156. static const fltSemantics &IEEEhalf() LLVM_READNONE;
  157. static const fltSemantics &BFloat() LLVM_READNONE;
  158. static const fltSemantics &IEEEsingle() LLVM_READNONE;
  159. static const fltSemantics &IEEEdouble() LLVM_READNONE;
  160. static const fltSemantics &IEEEquad() LLVM_READNONE;
  161. static const fltSemantics &PPCDoubleDouble() LLVM_READNONE;
  162. static const fltSemantics &x87DoubleExtended() LLVM_READNONE;
  163. /// A Pseudo fltsemantic used to construct APFloats that cannot conflict with
  164. /// anything real.
  165. static const fltSemantics &Bogus() LLVM_READNONE;
  166. /// @}
  167. /// IEEE-754R 5.11: Floating Point Comparison Relations.
  168. enum cmpResult {
  169. cmpLessThan,
  170. cmpEqual,
  171. cmpGreaterThan,
  172. cmpUnordered
  173. };
  174. /// IEEE-754R 4.3: Rounding-direction attributes.
  175. using roundingMode = llvm::RoundingMode;
  176. static constexpr roundingMode rmNearestTiesToEven =
  177. RoundingMode::NearestTiesToEven;
  178. static constexpr roundingMode rmTowardPositive = RoundingMode::TowardPositive;
  179. static constexpr roundingMode rmTowardNegative = RoundingMode::TowardNegative;
  180. static constexpr roundingMode rmTowardZero = RoundingMode::TowardZero;
  181. static constexpr roundingMode rmNearestTiesToAway =
  182. RoundingMode::NearestTiesToAway;
  183. /// IEEE-754R 7: Default exception handling.
  184. ///
  185. /// opUnderflow or opOverflow are always returned or-ed with opInexact.
  186. ///
  187. /// APFloat models this behavior specified by IEEE-754:
  188. /// "For operations producing results in floating-point format, the default
  189. /// result of an operation that signals the invalid operation exception
  190. /// shall be a quiet NaN."
  191. enum opStatus {
  192. opOK = 0x00,
  193. opInvalidOp = 0x01,
  194. opDivByZero = 0x02,
  195. opOverflow = 0x04,
  196. opUnderflow = 0x08,
  197. opInexact = 0x10
  198. };
  199. /// Category of internally-represented number.
  200. enum fltCategory {
  201. fcInfinity,
  202. fcNaN,
  203. fcNormal,
  204. fcZero
  205. };
  206. /// Convenience enum used to construct an uninitialized APFloat.
  207. enum uninitializedTag {
  208. uninitialized
  209. };
  210. /// Enumeration of \c ilogb error results.
  211. enum IlogbErrorKinds {
  212. IEK_Zero = INT_MIN + 1,
  213. IEK_NaN = INT_MIN,
  214. IEK_Inf = INT_MAX
  215. };
  216. static unsigned int semanticsPrecision(const fltSemantics &);
  217. static ExponentType semanticsMinExponent(const fltSemantics &);
  218. static ExponentType semanticsMaxExponent(const fltSemantics &);
  219. static unsigned int semanticsSizeInBits(const fltSemantics &);
  220. /// Returns the size of the floating point number (in bits) in the given
  221. /// semantics.
  222. static unsigned getSizeInBits(const fltSemantics &Sem);
  223. };
  224. namespace detail {
  225. class IEEEFloat final : public APFloatBase {
  226. public:
  227. /// \name Constructors
  228. /// @{
  229. IEEEFloat(const fltSemantics &); // Default construct to +0.0
  230. IEEEFloat(const fltSemantics &, integerPart);
  231. IEEEFloat(const fltSemantics &, uninitializedTag);
  232. IEEEFloat(const fltSemantics &, const APInt &);
  233. explicit IEEEFloat(double d);
  234. explicit IEEEFloat(float f);
  235. IEEEFloat(const IEEEFloat &);
  236. IEEEFloat(IEEEFloat &&);
  237. ~IEEEFloat();
  238. /// @}
  239. /// Returns whether this instance allocated memory.
  240. bool needsCleanup() const { return partCount() > 1; }
  241. /// \name Convenience "constructors"
  242. /// @{
  243. /// @}
  244. /// \name Arithmetic
  245. /// @{
  246. opStatus add(const IEEEFloat &, roundingMode);
  247. opStatus subtract(const IEEEFloat &, roundingMode);
  248. opStatus multiply(const IEEEFloat &, roundingMode);
  249. opStatus divide(const IEEEFloat &, roundingMode);
  250. /// IEEE remainder.
  251. opStatus remainder(const IEEEFloat &);
  252. /// C fmod, or llvm frem.
  253. opStatus mod(const IEEEFloat &);
  254. opStatus fusedMultiplyAdd(const IEEEFloat &, const IEEEFloat &, roundingMode);
  255. opStatus roundToIntegral(roundingMode);
  256. /// IEEE-754R 5.3.1: nextUp/nextDown.
  257. opStatus next(bool nextDown);
  258. /// @}
  259. /// \name Sign operations.
  260. /// @{
  261. void changeSign();
  262. /// @}
  263. /// \name Conversions
  264. /// @{
  265. opStatus convert(const fltSemantics &, roundingMode, bool *);
  266. opStatus convertToInteger(MutableArrayRef<integerPart>, unsigned int, bool,
  267. roundingMode, bool *) const;
  268. opStatus convertFromAPInt(const APInt &, bool, roundingMode);
  269. opStatus convertFromSignExtendedInteger(const integerPart *, unsigned int,
  270. bool, roundingMode);
  271. opStatus convertFromZeroExtendedInteger(const integerPart *, unsigned int,
  272. bool, roundingMode);
  273. Expected<opStatus> convertFromString(StringRef, roundingMode);
  274. APInt bitcastToAPInt() const;
  275. double convertToDouble() const;
  276. float convertToFloat() const;
  277. /// @}
  278. /// The definition of equality is not straightforward for floating point, so
  279. /// we won't use operator==. Use one of the following, or write whatever it
  280. /// is you really mean.
  281. bool operator==(const IEEEFloat &) const = delete;
  282. /// IEEE comparison with another floating point number (NaNs compare
  283. /// unordered, 0==-0).
  284. cmpResult compare(const IEEEFloat &) const;
  285. /// Bitwise comparison for equality (QNaNs compare equal, 0!=-0).
  286. bool bitwiseIsEqual(const IEEEFloat &) const;
  287. /// Write out a hexadecimal representation of the floating point value to DST,
  288. /// which must be of sufficient size, in the C99 form [-]0xh.hhhhp[+-]d.
  289. /// Return the number of characters written, excluding the terminating NUL.
  290. unsigned int convertToHexString(char *dst, unsigned int hexDigits,
  291. bool upperCase, roundingMode) const;
  292. /// \name IEEE-754R 5.7.2 General operations.
  293. /// @{
  294. /// IEEE-754R isSignMinus: Returns true if and only if the current value is
  295. /// negative.
  296. ///
  297. /// This applies to zeros and NaNs as well.
  298. bool isNegative() const { return sign; }
  299. /// IEEE-754R isNormal: Returns true if and only if the current value is normal.
  300. ///
  301. /// This implies that the current value of the float is not zero, subnormal,
  302. /// infinite, or NaN following the definition of normality from IEEE-754R.
  303. bool isNormal() const { return !isDenormal() && isFiniteNonZero(); }
  304. /// Returns true if and only if the current value is zero, subnormal, or
  305. /// normal.
  306. ///
  307. /// This means that the value is not infinite or NaN.
  308. bool isFinite() const { return !isNaN() && !isInfinity(); }
  309. /// Returns true if and only if the float is plus or minus zero.
  310. bool isZero() const { return category == fcZero; }
  311. /// IEEE-754R isSubnormal(): Returns true if and only if the float is a
  312. /// denormal.
  313. bool isDenormal() const;
  314. /// IEEE-754R isInfinite(): Returns true if and only if the float is infinity.
  315. bool isInfinity() const { return category == fcInfinity; }
  316. /// Returns true if and only if the float is a quiet or signaling NaN.
  317. bool isNaN() const { return category == fcNaN; }
  318. /// Returns true if and only if the float is a signaling NaN.
  319. bool isSignaling() const;
  320. /// @}
  321. /// \name Simple Queries
  322. /// @{
  323. fltCategory getCategory() const { return category; }
  324. const fltSemantics &getSemantics() const { return *semantics; }
  325. bool isNonZero() const { return category != fcZero; }
  326. bool isFiniteNonZero() const { return isFinite() && !isZero(); }
  327. bool isPosZero() const { return isZero() && !isNegative(); }
  328. bool isNegZero() const { return isZero() && isNegative(); }
  329. /// Returns true if and only if the number has the smallest possible non-zero
  330. /// magnitude in the current semantics.
  331. bool isSmallest() const;
  332. /// Returns true if and only if the number has the largest possible finite
  333. /// magnitude in the current semantics.
  334. bool isLargest() const;
  335. /// Returns true if and only if the number is an exact integer.
  336. bool isInteger() const;
  337. /// @}
  338. IEEEFloat &operator=(const IEEEFloat &);
  339. IEEEFloat &operator=(IEEEFloat &&);
  340. /// Overload to compute a hash code for an APFloat value.
  341. ///
  342. /// Note that the use of hash codes for floating point values is in general
  343. /// frought with peril. Equality is hard to define for these values. For
  344. /// example, should negative and positive zero hash to different codes? Are
  345. /// they equal or not? This hash value implementation specifically
  346. /// emphasizes producing different codes for different inputs in order to
  347. /// be used in canonicalization and memoization. As such, equality is
  348. /// bitwiseIsEqual, and 0 != -0.
  349. friend hash_code hash_value(const IEEEFloat &Arg);
  350. /// Converts this value into a decimal string.
  351. ///
  352. /// \param FormatPrecision The maximum number of digits of
  353. /// precision to output. If there are fewer digits available,
  354. /// zero padding will not be used unless the value is
  355. /// integral and small enough to be expressed in
  356. /// FormatPrecision digits. 0 means to use the natural
  357. /// precision of the number.
  358. /// \param FormatMaxPadding The maximum number of zeros to
  359. /// consider inserting before falling back to scientific
  360. /// notation. 0 means to always use scientific notation.
  361. ///
  362. /// \param TruncateZero Indicate whether to remove the trailing zero in
  363. /// fraction part or not. Also setting this parameter to false forcing
  364. /// producing of output more similar to default printf behavior.
  365. /// Specifically the lower e is used as exponent delimiter and exponent
  366. /// always contains no less than two digits.
  367. ///
  368. /// Number Precision MaxPadding Result
  369. /// ------ --------- ---------- ------
  370. /// 1.01E+4 5 2 10100
  371. /// 1.01E+4 4 2 1.01E+4
  372. /// 1.01E+4 5 1 1.01E+4
  373. /// 1.01E-2 5 2 0.0101
  374. /// 1.01E-2 4 2 0.0101
  375. /// 1.01E-2 4 1 1.01E-2
  376. void toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision = 0,
  377. unsigned FormatMaxPadding = 3, bool TruncateZero = true) const;
  378. /// If this value has an exact multiplicative inverse, store it in inv and
  379. /// return true.
  380. bool getExactInverse(APFloat *inv) const;
  381. /// Returns the exponent of the internal representation of the APFloat.
  382. ///
  383. /// Because the radix of APFloat is 2, this is equivalent to floor(log2(x)).
  384. /// For special APFloat values, this returns special error codes:
  385. ///
  386. /// NaN -> \c IEK_NaN
  387. /// 0 -> \c IEK_Zero
  388. /// Inf -> \c IEK_Inf
  389. ///
  390. friend int ilogb(const IEEEFloat &Arg);
  391. /// Returns: X * 2^Exp for integral exponents.
  392. friend IEEEFloat scalbn(IEEEFloat X, int Exp, roundingMode);
  393. friend IEEEFloat frexp(const IEEEFloat &X, int &Exp, roundingMode);
  394. /// \name Special value setters.
  395. /// @{
  396. void makeLargest(bool Neg = false);
  397. void makeSmallest(bool Neg = false);
  398. void makeNaN(bool SNaN = false, bool Neg = false,
  399. const APInt *fill = nullptr);
  400. void makeInf(bool Neg = false);
  401. void makeZero(bool Neg = false);
  402. void makeQuiet();
  403. /// Returns the smallest (by magnitude) normalized finite number in the given
  404. /// semantics.
  405. ///
  406. /// \param Negative - True iff the number should be negative
  407. void makeSmallestNormalized(bool Negative = false);
  408. /// @}
  409. cmpResult compareAbsoluteValue(const IEEEFloat &) const;
  410. private:
  411. /// \name Simple Queries
  412. /// @{
  413. integerPart *significandParts();
  414. const integerPart *significandParts() const;
  415. unsigned int partCount() const;
  416. /// @}
  417. /// \name Significand operations.
  418. /// @{
  419. integerPart addSignificand(const IEEEFloat &);
  420. integerPart subtractSignificand(const IEEEFloat &, integerPart);
  421. lostFraction addOrSubtractSignificand(const IEEEFloat &, bool subtract);
  422. lostFraction multiplySignificand(const IEEEFloat &, IEEEFloat);
  423. lostFraction multiplySignificand(const IEEEFloat&);
  424. lostFraction divideSignificand(const IEEEFloat &);
  425. void incrementSignificand();
  426. void initialize(const fltSemantics *);
  427. void shiftSignificandLeft(unsigned int);
  428. lostFraction shiftSignificandRight(unsigned int);
  429. unsigned int significandLSB() const;
  430. unsigned int significandMSB() const;
  431. void zeroSignificand();
  432. /// Return true if the significand excluding the integral bit is all ones.
  433. bool isSignificandAllOnes() const;
  434. /// Return true if the significand excluding the integral bit is all zeros.
  435. bool isSignificandAllZeros() const;
  436. /// @}
  437. /// \name Arithmetic on special values.
  438. /// @{
  439. opStatus addOrSubtractSpecials(const IEEEFloat &, bool subtract);
  440. opStatus divideSpecials(const IEEEFloat &);
  441. opStatus multiplySpecials(const IEEEFloat &);
  442. opStatus modSpecials(const IEEEFloat &);
  443. opStatus remainderSpecials(const IEEEFloat&);
  444. /// @}
  445. /// \name Miscellany
  446. /// @{
  447. bool convertFromStringSpecials(StringRef str);
  448. opStatus normalize(roundingMode, lostFraction);
  449. opStatus addOrSubtract(const IEEEFloat &, roundingMode, bool subtract);
  450. opStatus handleOverflow(roundingMode);
  451. bool roundAwayFromZero(roundingMode, lostFraction, unsigned int) const;
  452. opStatus convertToSignExtendedInteger(MutableArrayRef<integerPart>,
  453. unsigned int, bool, roundingMode,
  454. bool *) const;
  455. opStatus convertFromUnsignedParts(const integerPart *, unsigned int,
  456. roundingMode);
  457. Expected<opStatus> convertFromHexadecimalString(StringRef, roundingMode);
  458. Expected<opStatus> convertFromDecimalString(StringRef, roundingMode);
  459. char *convertNormalToHexString(char *, unsigned int, bool,
  460. roundingMode) const;
  461. opStatus roundSignificandWithExponent(const integerPart *, unsigned int, int,
  462. roundingMode);
  463. ExponentType exponentNaN() const;
  464. ExponentType exponentInf() const;
  465. ExponentType exponentZero() const;
  466. /// @}
  467. APInt convertHalfAPFloatToAPInt() const;
  468. APInt convertBFloatAPFloatToAPInt() const;
  469. APInt convertFloatAPFloatToAPInt() const;
  470. APInt convertDoubleAPFloatToAPInt() const;
  471. APInt convertQuadrupleAPFloatToAPInt() const;
  472. APInt convertF80LongDoubleAPFloatToAPInt() const;
  473. APInt convertPPCDoubleDoubleAPFloatToAPInt() const;
  474. void initFromAPInt(const fltSemantics *Sem, const APInt &api);
  475. void initFromHalfAPInt(const APInt &api);
  476. void initFromBFloatAPInt(const APInt &api);
  477. void initFromFloatAPInt(const APInt &api);
  478. void initFromDoubleAPInt(const APInt &api);
  479. void initFromQuadrupleAPInt(const APInt &api);
  480. void initFromF80LongDoubleAPInt(const APInt &api);
  481. void initFromPPCDoubleDoubleAPInt(const APInt &api);
  482. void assign(const IEEEFloat &);
  483. void copySignificand(const IEEEFloat &);
  484. void freeSignificand();
  485. /// Note: this must be the first data member.
  486. /// The semantics that this value obeys.
  487. const fltSemantics *semantics;
  488. /// A binary fraction with an explicit integer bit.
  489. ///
  490. /// The significand must be at least one bit wider than the target precision.
  491. union Significand {
  492. integerPart part;
  493. integerPart *parts;
  494. } significand;
  495. /// The signed unbiased exponent of the value.
  496. ExponentType exponent;
  497. /// What kind of floating point number this is.
  498. ///
  499. /// Only 2 bits are required, but VisualStudio incorrectly sign extends it.
  500. /// Using the extra bit keeps it from failing under VisualStudio.
  501. fltCategory category : 3;
  502. /// Sign bit of the number.
  503. unsigned int sign : 1;
  504. };
  505. hash_code hash_value(const IEEEFloat &Arg);
  506. int ilogb(const IEEEFloat &Arg);
  507. IEEEFloat scalbn(IEEEFloat X, int Exp, IEEEFloat::roundingMode);
  508. IEEEFloat frexp(const IEEEFloat &Val, int &Exp, IEEEFloat::roundingMode RM);
  509. // This mode implements more precise float in terms of two APFloats.
  510. // The interface and layout is designed for arbitrary underlying semantics,
  511. // though currently only PPCDoubleDouble semantics are supported, whose
  512. // corresponding underlying semantics are IEEEdouble.
  513. class DoubleAPFloat final : public APFloatBase {
  514. // Note: this must be the first data member.
  515. const fltSemantics *Semantics;
  516. std::unique_ptr<APFloat[]> Floats;
  517. opStatus addImpl(const APFloat &a, const APFloat &aa, const APFloat &c,
  518. const APFloat &cc, roundingMode RM);
  519. opStatus addWithSpecial(const DoubleAPFloat &LHS, const DoubleAPFloat &RHS,
  520. DoubleAPFloat &Out, roundingMode RM);
  521. public:
  522. DoubleAPFloat(const fltSemantics &S);
  523. DoubleAPFloat(const fltSemantics &S, uninitializedTag);
  524. DoubleAPFloat(const fltSemantics &S, integerPart);
  525. DoubleAPFloat(const fltSemantics &S, const APInt &I);
  526. DoubleAPFloat(const fltSemantics &S, APFloat &&First, APFloat &&Second);
  527. DoubleAPFloat(const DoubleAPFloat &RHS);
  528. DoubleAPFloat(DoubleAPFloat &&RHS);
  529. DoubleAPFloat &operator=(const DoubleAPFloat &RHS);
  530. DoubleAPFloat &operator=(DoubleAPFloat &&RHS) {
  531. if (this != &RHS) {
  532. this->~DoubleAPFloat();
  533. new (this) DoubleAPFloat(std::move(RHS));
  534. }
  535. return *this;
  536. }
  537. bool needsCleanup() const { return Floats != nullptr; }
  538. APFloat &getFirst() { return Floats[0]; }
  539. const APFloat &getFirst() const { return Floats[0]; }
  540. APFloat &getSecond() { return Floats[1]; }
  541. const APFloat &getSecond() const { return Floats[1]; }
  542. opStatus add(const DoubleAPFloat &RHS, roundingMode RM);
  543. opStatus subtract(const DoubleAPFloat &RHS, roundingMode RM);
  544. opStatus multiply(const DoubleAPFloat &RHS, roundingMode RM);
  545. opStatus divide(const DoubleAPFloat &RHS, roundingMode RM);
  546. opStatus remainder(const DoubleAPFloat &RHS);
  547. opStatus mod(const DoubleAPFloat &RHS);
  548. opStatus fusedMultiplyAdd(const DoubleAPFloat &Multiplicand,
  549. const DoubleAPFloat &Addend, roundingMode RM);
  550. opStatus roundToIntegral(roundingMode RM);
  551. void changeSign();
  552. cmpResult compareAbsoluteValue(const DoubleAPFloat &RHS) const;
  553. fltCategory getCategory() const;
  554. bool isNegative() const;
  555. void makeInf(bool Neg);
  556. void makeZero(bool Neg);
  557. void makeLargest(bool Neg);
  558. void makeSmallest(bool Neg);
  559. void makeSmallestNormalized(bool Neg);
  560. void makeNaN(bool SNaN, bool Neg, const APInt *fill);
  561. cmpResult compare(const DoubleAPFloat &RHS) const;
  562. bool bitwiseIsEqual(const DoubleAPFloat &RHS) const;
  563. APInt bitcastToAPInt() const;
  564. Expected<opStatus> convertFromString(StringRef, roundingMode);
  565. opStatus next(bool nextDown);
  566. opStatus convertToInteger(MutableArrayRef<integerPart> Input,
  567. unsigned int Width, bool IsSigned, roundingMode RM,
  568. bool *IsExact) const;
  569. opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM);
  570. opStatus convertFromSignExtendedInteger(const integerPart *Input,
  571. unsigned int InputSize, bool IsSigned,
  572. roundingMode RM);
  573. opStatus convertFromZeroExtendedInteger(const integerPart *Input,
  574. unsigned int InputSize, bool IsSigned,
  575. roundingMode RM);
  576. unsigned int convertToHexString(char *DST, unsigned int HexDigits,
  577. bool UpperCase, roundingMode RM) const;
  578. bool isDenormal() const;
  579. bool isSmallest() const;
  580. bool isLargest() const;
  581. bool isInteger() const;
  582. void toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision,
  583. unsigned FormatMaxPadding, bool TruncateZero = true) const;
  584. bool getExactInverse(APFloat *inv) const;
  585. friend DoubleAPFloat scalbn(const DoubleAPFloat &X, int Exp, roundingMode);
  586. friend DoubleAPFloat frexp(const DoubleAPFloat &X, int &Exp, roundingMode);
  587. friend hash_code hash_value(const DoubleAPFloat &Arg);
  588. };
  589. hash_code hash_value(const DoubleAPFloat &Arg);
  590. } // End detail namespace
  591. // This is a interface class that is currently forwarding functionalities from
  592. // detail::IEEEFloat.
  593. class APFloat : public APFloatBase {
  594. typedef detail::IEEEFloat IEEEFloat;
  595. typedef detail::DoubleAPFloat DoubleAPFloat;
  596. static_assert(std::is_standard_layout<IEEEFloat>::value, "");
  597. union Storage {
  598. const fltSemantics *semantics;
  599. IEEEFloat IEEE;
  600. DoubleAPFloat Double;
  601. explicit Storage(IEEEFloat F, const fltSemantics &S);
  602. explicit Storage(DoubleAPFloat F, const fltSemantics &S)
  603. : Double(std::move(F)) {
  604. assert(&S == &PPCDoubleDouble());
  605. }
  606. template <typename... ArgTypes>
  607. Storage(const fltSemantics &Semantics, ArgTypes &&... Args) {
  608. if (usesLayout<IEEEFloat>(Semantics)) {
  609. new (&IEEE) IEEEFloat(Semantics, std::forward<ArgTypes>(Args)...);
  610. return;
  611. }
  612. if (usesLayout<DoubleAPFloat>(Semantics)) {
  613. new (&Double) DoubleAPFloat(Semantics, std::forward<ArgTypes>(Args)...);
  614. return;
  615. }
  616. llvm_unreachable("Unexpected semantics");
  617. }
  618. ~Storage() {
  619. if (usesLayout<IEEEFloat>(*semantics)) {
  620. IEEE.~IEEEFloat();
  621. return;
  622. }
  623. if (usesLayout<DoubleAPFloat>(*semantics)) {
  624. Double.~DoubleAPFloat();
  625. return;
  626. }
  627. llvm_unreachable("Unexpected semantics");
  628. }
  629. Storage(const Storage &RHS) {
  630. if (usesLayout<IEEEFloat>(*RHS.semantics)) {
  631. new (this) IEEEFloat(RHS.IEEE);
  632. return;
  633. }
  634. if (usesLayout<DoubleAPFloat>(*RHS.semantics)) {
  635. new (this) DoubleAPFloat(RHS.Double);
  636. return;
  637. }
  638. llvm_unreachable("Unexpected semantics");
  639. }
  640. Storage(Storage &&RHS) {
  641. if (usesLayout<IEEEFloat>(*RHS.semantics)) {
  642. new (this) IEEEFloat(std::move(RHS.IEEE));
  643. return;
  644. }
  645. if (usesLayout<DoubleAPFloat>(*RHS.semantics)) {
  646. new (this) DoubleAPFloat(std::move(RHS.Double));
  647. return;
  648. }
  649. llvm_unreachable("Unexpected semantics");
  650. }
  651. Storage &operator=(const Storage &RHS) {
  652. if (usesLayout<IEEEFloat>(*semantics) &&
  653. usesLayout<IEEEFloat>(*RHS.semantics)) {
  654. IEEE = RHS.IEEE;
  655. } else if (usesLayout<DoubleAPFloat>(*semantics) &&
  656. usesLayout<DoubleAPFloat>(*RHS.semantics)) {
  657. Double = RHS.Double;
  658. } else if (this != &RHS) {
  659. this->~Storage();
  660. new (this) Storage(RHS);
  661. }
  662. return *this;
  663. }
  664. Storage &operator=(Storage &&RHS) {
  665. if (usesLayout<IEEEFloat>(*semantics) &&
  666. usesLayout<IEEEFloat>(*RHS.semantics)) {
  667. IEEE = std::move(RHS.IEEE);
  668. } else if (usesLayout<DoubleAPFloat>(*semantics) &&
  669. usesLayout<DoubleAPFloat>(*RHS.semantics)) {
  670. Double = std::move(RHS.Double);
  671. } else if (this != &RHS) {
  672. this->~Storage();
  673. new (this) Storage(std::move(RHS));
  674. }
  675. return *this;
  676. }
  677. } U;
  678. template <typename T> static bool usesLayout(const fltSemantics &Semantics) {
  679. static_assert(std::is_same<T, IEEEFloat>::value ||
  680. std::is_same<T, DoubleAPFloat>::value, "");
  681. if (std::is_same<T, DoubleAPFloat>::value) {
  682. return &Semantics == &PPCDoubleDouble();
  683. }
  684. return &Semantics != &PPCDoubleDouble();
  685. }
  686. IEEEFloat &getIEEE() {
  687. if (usesLayout<IEEEFloat>(*U.semantics))
  688. return U.IEEE;
  689. if (usesLayout<DoubleAPFloat>(*U.semantics))
  690. return U.Double.getFirst().U.IEEE;
  691. llvm_unreachable("Unexpected semantics");
  692. }
  693. const IEEEFloat &getIEEE() const {
  694. if (usesLayout<IEEEFloat>(*U.semantics))
  695. return U.IEEE;
  696. if (usesLayout<DoubleAPFloat>(*U.semantics))
  697. return U.Double.getFirst().U.IEEE;
  698. llvm_unreachable("Unexpected semantics");
  699. }
  700. void makeZero(bool Neg) { APFLOAT_DISPATCH_ON_SEMANTICS(makeZero(Neg)); }
  701. void makeInf(bool Neg) { APFLOAT_DISPATCH_ON_SEMANTICS(makeInf(Neg)); }
  702. void makeNaN(bool SNaN, bool Neg, const APInt *fill) {
  703. APFLOAT_DISPATCH_ON_SEMANTICS(makeNaN(SNaN, Neg, fill));
  704. }
  705. void makeLargest(bool Neg) {
  706. APFLOAT_DISPATCH_ON_SEMANTICS(makeLargest(Neg));
  707. }
  708. void makeSmallest(bool Neg) {
  709. APFLOAT_DISPATCH_ON_SEMANTICS(makeSmallest(Neg));
  710. }
  711. void makeSmallestNormalized(bool Neg) {
  712. APFLOAT_DISPATCH_ON_SEMANTICS(makeSmallestNormalized(Neg));
  713. }
  714. // FIXME: This is due to clang 3.3 (or older version) always checks for the
  715. // default constructor in an array aggregate initialization, even if no
  716. // elements in the array is default initialized.
  717. APFloat() : U(IEEEdouble()) {
  718. llvm_unreachable("This is a workaround for old clang.");
  719. }
  720. explicit APFloat(IEEEFloat F, const fltSemantics &S) : U(std::move(F), S) {}
  721. explicit APFloat(DoubleAPFloat F, const fltSemantics &S)
  722. : U(std::move(F), S) {}
  723. cmpResult compareAbsoluteValue(const APFloat &RHS) const {
  724. assert(&getSemantics() == &RHS.getSemantics() &&
  725. "Should only compare APFloats with the same semantics");
  726. if (usesLayout<IEEEFloat>(getSemantics()))
  727. return U.IEEE.compareAbsoluteValue(RHS.U.IEEE);
  728. if (usesLayout<DoubleAPFloat>(getSemantics()))
  729. return U.Double.compareAbsoluteValue(RHS.U.Double);
  730. llvm_unreachable("Unexpected semantics");
  731. }
  732. public:
  733. APFloat(const fltSemantics &Semantics) : U(Semantics) {}
  734. APFloat(const fltSemantics &Semantics, StringRef S);
  735. APFloat(const fltSemantics &Semantics, integerPart I) : U(Semantics, I) {}
  736. template <typename T,
  737. typename = std::enable_if_t<std::is_floating_point<T>::value>>
  738. APFloat(const fltSemantics &Semantics, T V) = delete;
  739. // TODO: Remove this constructor. This isn't faster than the first one.
  740. APFloat(const fltSemantics &Semantics, uninitializedTag)
  741. : U(Semantics, uninitialized) {}
  742. APFloat(const fltSemantics &Semantics, const APInt &I) : U(Semantics, I) {}
  743. explicit APFloat(double d) : U(IEEEFloat(d), IEEEdouble()) {}
  744. explicit APFloat(float f) : U(IEEEFloat(f), IEEEsingle()) {}
  745. APFloat(const APFloat &RHS) = default;
  746. APFloat(APFloat &&RHS) = default;
  747. ~APFloat() = default;
  748. bool needsCleanup() const { APFLOAT_DISPATCH_ON_SEMANTICS(needsCleanup()); }
  749. /// Factory for Positive and Negative Zero.
  750. ///
  751. /// \param Negative True iff the number should be negative.
  752. static APFloat getZero(const fltSemantics &Sem, bool Negative = false) {
  753. APFloat Val(Sem, uninitialized);
  754. Val.makeZero(Negative);
  755. return Val;
  756. }
  757. /// Factory for Positive and Negative Infinity.
  758. ///
  759. /// \param Negative True iff the number should be negative.
  760. static APFloat getInf(const fltSemantics &Sem, bool Negative = false) {
  761. APFloat Val(Sem, uninitialized);
  762. Val.makeInf(Negative);
  763. return Val;
  764. }
  765. /// Factory for NaN values.
  766. ///
  767. /// \param Negative - True iff the NaN generated should be negative.
  768. /// \param payload - The unspecified fill bits for creating the NaN, 0 by
  769. /// default. The value is truncated as necessary.
  770. static APFloat getNaN(const fltSemantics &Sem, bool Negative = false,
  771. uint64_t payload = 0) {
  772. if (payload) {
  773. APInt intPayload(64, payload);
  774. return getQNaN(Sem, Negative, &intPayload);
  775. } else {
  776. return getQNaN(Sem, Negative, nullptr);
  777. }
  778. }
  779. /// Factory for QNaN values.
  780. static APFloat getQNaN(const fltSemantics &Sem, bool Negative = false,
  781. const APInt *payload = nullptr) {
  782. APFloat Val(Sem, uninitialized);
  783. Val.makeNaN(false, Negative, payload);
  784. return Val;
  785. }
  786. /// Factory for SNaN values.
  787. static APFloat getSNaN(const fltSemantics &Sem, bool Negative = false,
  788. const APInt *payload = nullptr) {
  789. APFloat Val(Sem, uninitialized);
  790. Val.makeNaN(true, Negative, payload);
  791. return Val;
  792. }
  793. /// Returns the largest finite number in the given semantics.
  794. ///
  795. /// \param Negative - True iff the number should be negative
  796. static APFloat getLargest(const fltSemantics &Sem, bool Negative = false) {
  797. APFloat Val(Sem, uninitialized);
  798. Val.makeLargest(Negative);
  799. return Val;
  800. }
  801. /// Returns the smallest (by magnitude) finite number in the given semantics.
  802. /// Might be denormalized, which implies a relative loss of precision.
  803. ///
  804. /// \param Negative - True iff the number should be negative
  805. static APFloat getSmallest(const fltSemantics &Sem, bool Negative = false) {
  806. APFloat Val(Sem, uninitialized);
  807. Val.makeSmallest(Negative);
  808. return Val;
  809. }
  810. /// Returns the smallest (by magnitude) normalized finite number in the given
  811. /// semantics.
  812. ///
  813. /// \param Negative - True iff the number should be negative
  814. static APFloat getSmallestNormalized(const fltSemantics &Sem,
  815. bool Negative = false) {
  816. APFloat Val(Sem, uninitialized);
  817. Val.makeSmallestNormalized(Negative);
  818. return Val;
  819. }
  820. /// Returns a float which is bitcasted from an all one value int.
  821. ///
  822. /// \param Semantics - type float semantics
  823. static APFloat getAllOnesValue(const fltSemantics &Semantics);
  824. /// Used to insert APFloat objects, or objects that contain APFloat objects,
  825. /// into FoldingSets.
  826. void Profile(FoldingSetNodeID &NID) const;
  827. opStatus add(const APFloat &RHS, roundingMode RM) {
  828. assert(&getSemantics() == &RHS.getSemantics() &&
  829. "Should only call on two APFloats with the same semantics");
  830. if (usesLayout<IEEEFloat>(getSemantics()))
  831. return U.IEEE.add(RHS.U.IEEE, RM);
  832. if (usesLayout<DoubleAPFloat>(getSemantics()))
  833. return U.Double.add(RHS.U.Double, RM);
  834. llvm_unreachable("Unexpected semantics");
  835. }
  836. opStatus subtract(const APFloat &RHS, roundingMode RM) {
  837. assert(&getSemantics() == &RHS.getSemantics() &&
  838. "Should only call on two APFloats with the same semantics");
  839. if (usesLayout<IEEEFloat>(getSemantics()))
  840. return U.IEEE.subtract(RHS.U.IEEE, RM);
  841. if (usesLayout<DoubleAPFloat>(getSemantics()))
  842. return U.Double.subtract(RHS.U.Double, RM);
  843. llvm_unreachable("Unexpected semantics");
  844. }
  845. opStatus multiply(const APFloat &RHS, roundingMode RM) {
  846. assert(&getSemantics() == &RHS.getSemantics() &&
  847. "Should only call on two APFloats with the same semantics");
  848. if (usesLayout<IEEEFloat>(getSemantics()))
  849. return U.IEEE.multiply(RHS.U.IEEE, RM);
  850. if (usesLayout<DoubleAPFloat>(getSemantics()))
  851. return U.Double.multiply(RHS.U.Double, RM);
  852. llvm_unreachable("Unexpected semantics");
  853. }
  854. opStatus divide(const APFloat &RHS, roundingMode RM) {
  855. assert(&getSemantics() == &RHS.getSemantics() &&
  856. "Should only call on two APFloats with the same semantics");
  857. if (usesLayout<IEEEFloat>(getSemantics()))
  858. return U.IEEE.divide(RHS.U.IEEE, RM);
  859. if (usesLayout<DoubleAPFloat>(getSemantics()))
  860. return U.Double.divide(RHS.U.Double, RM);
  861. llvm_unreachable("Unexpected semantics");
  862. }
  863. opStatus remainder(const APFloat &RHS) {
  864. assert(&getSemantics() == &RHS.getSemantics() &&
  865. "Should only call on two APFloats with the same semantics");
  866. if (usesLayout<IEEEFloat>(getSemantics()))
  867. return U.IEEE.remainder(RHS.U.IEEE);
  868. if (usesLayout<DoubleAPFloat>(getSemantics()))
  869. return U.Double.remainder(RHS.U.Double);
  870. llvm_unreachable("Unexpected semantics");
  871. }
  872. opStatus mod(const APFloat &RHS) {
  873. assert(&getSemantics() == &RHS.getSemantics() &&
  874. "Should only call on two APFloats with the same semantics");
  875. if (usesLayout<IEEEFloat>(getSemantics()))
  876. return U.IEEE.mod(RHS.U.IEEE);
  877. if (usesLayout<DoubleAPFloat>(getSemantics()))
  878. return U.Double.mod(RHS.U.Double);
  879. llvm_unreachable("Unexpected semantics");
  880. }
  881. opStatus fusedMultiplyAdd(const APFloat &Multiplicand, const APFloat &Addend,
  882. roundingMode RM) {
  883. assert(&getSemantics() == &Multiplicand.getSemantics() &&
  884. "Should only call on APFloats with the same semantics");
  885. assert(&getSemantics() == &Addend.getSemantics() &&
  886. "Should only call on APFloats with the same semantics");
  887. if (usesLayout<IEEEFloat>(getSemantics()))
  888. return U.IEEE.fusedMultiplyAdd(Multiplicand.U.IEEE, Addend.U.IEEE, RM);
  889. if (usesLayout<DoubleAPFloat>(getSemantics()))
  890. return U.Double.fusedMultiplyAdd(Multiplicand.U.Double, Addend.U.Double,
  891. RM);
  892. llvm_unreachable("Unexpected semantics");
  893. }
  894. opStatus roundToIntegral(roundingMode RM) {
  895. APFLOAT_DISPATCH_ON_SEMANTICS(roundToIntegral(RM));
  896. }
  897. // TODO: bool parameters are not readable and a source of bugs.
  898. // Do something.
  899. opStatus next(bool nextDown) {
  900. APFLOAT_DISPATCH_ON_SEMANTICS(next(nextDown));
  901. }
  902. /// Negate an APFloat.
  903. APFloat operator-() const {
  904. APFloat Result(*this);
  905. Result.changeSign();
  906. return Result;
  907. }
  908. /// Add two APFloats, rounding ties to the nearest even.
  909. /// No error checking.
  910. APFloat operator+(const APFloat &RHS) const {
  911. APFloat Result(*this);
  912. (void)Result.add(RHS, rmNearestTiesToEven);
  913. return Result;
  914. }
  915. /// Subtract two APFloats, rounding ties to the nearest even.
  916. /// No error checking.
  917. APFloat operator-(const APFloat &RHS) const {
  918. APFloat Result(*this);
  919. (void)Result.subtract(RHS, rmNearestTiesToEven);
  920. return Result;
  921. }
  922. /// Multiply two APFloats, rounding ties to the nearest even.
  923. /// No error checking.
  924. APFloat operator*(const APFloat &RHS) const {
  925. APFloat Result(*this);
  926. (void)Result.multiply(RHS, rmNearestTiesToEven);
  927. return Result;
  928. }
  929. /// Divide the first APFloat by the second, rounding ties to the nearest even.
  930. /// No error checking.
  931. APFloat operator/(const APFloat &RHS) const {
  932. APFloat Result(*this);
  933. (void)Result.divide(RHS, rmNearestTiesToEven);
  934. return Result;
  935. }
  936. void changeSign() { APFLOAT_DISPATCH_ON_SEMANTICS(changeSign()); }
  937. void clearSign() {
  938. if (isNegative())
  939. changeSign();
  940. }
  941. void copySign(const APFloat &RHS) {
  942. if (isNegative() != RHS.isNegative())
  943. changeSign();
  944. }
  945. /// A static helper to produce a copy of an APFloat value with its sign
  946. /// copied from some other APFloat.
  947. static APFloat copySign(APFloat Value, const APFloat &Sign) {
  948. Value.copySign(Sign);
  949. return Value;
  950. }
  951. opStatus convert(const fltSemantics &ToSemantics, roundingMode RM,
  952. bool *losesInfo);
  953. opStatus convertToInteger(MutableArrayRef<integerPart> Input,
  954. unsigned int Width, bool IsSigned, roundingMode RM,
  955. bool *IsExact) const {
  956. APFLOAT_DISPATCH_ON_SEMANTICS(
  957. convertToInteger(Input, Width, IsSigned, RM, IsExact));
  958. }
  959. opStatus convertToInteger(APSInt &Result, roundingMode RM,
  960. bool *IsExact) const;
  961. opStatus convertFromAPInt(const APInt &Input, bool IsSigned,
  962. roundingMode RM) {
  963. APFLOAT_DISPATCH_ON_SEMANTICS(convertFromAPInt(Input, IsSigned, RM));
  964. }
  965. opStatus convertFromSignExtendedInteger(const integerPart *Input,
  966. unsigned int InputSize, bool IsSigned,
  967. roundingMode RM) {
  968. APFLOAT_DISPATCH_ON_SEMANTICS(
  969. convertFromSignExtendedInteger(Input, InputSize, IsSigned, RM));
  970. }
  971. opStatus convertFromZeroExtendedInteger(const integerPart *Input,
  972. unsigned int InputSize, bool IsSigned,
  973. roundingMode RM) {
  974. APFLOAT_DISPATCH_ON_SEMANTICS(
  975. convertFromZeroExtendedInteger(Input, InputSize, IsSigned, RM));
  976. }
  977. Expected<opStatus> convertFromString(StringRef, roundingMode);
  978. APInt bitcastToAPInt() const {
  979. APFLOAT_DISPATCH_ON_SEMANTICS(bitcastToAPInt());
  980. }
  981. /// Converts this APFloat to host double value.
  982. ///
  983. /// \pre The APFloat must be built using semantics, that can be represented by
  984. /// the host double type without loss of precision. It can be IEEEdouble and
  985. /// shorter semantics, like IEEEsingle and others.
  986. double convertToDouble() const;
  987. /// Converts this APFloat to host float value.
  988. ///
  989. /// \pre The APFloat must be built using semantics, that can be represented by
  990. /// the host float type without loss of precision. It can be IEEEsingle and
  991. /// shorter semantics, like IEEEhalf.
  992. float convertToFloat() const;
  993. bool operator==(const APFloat &RHS) const { return compare(RHS) == cmpEqual; }
  994. bool operator!=(const APFloat &RHS) const { return compare(RHS) != cmpEqual; }
  995. bool operator<(const APFloat &RHS) const {
  996. return compare(RHS) == cmpLessThan;
  997. }
  998. bool operator>(const APFloat &RHS) const {
  999. return compare(RHS) == cmpGreaterThan;
  1000. }
  1001. bool operator<=(const APFloat &RHS) const {
  1002. cmpResult Res = compare(RHS);
  1003. return Res == cmpLessThan || Res == cmpEqual;
  1004. }
  1005. bool operator>=(const APFloat &RHS) const {
  1006. cmpResult Res = compare(RHS);
  1007. return Res == cmpGreaterThan || Res == cmpEqual;
  1008. }
  1009. cmpResult compare(const APFloat &RHS) const {
  1010. assert(&getSemantics() == &RHS.getSemantics() &&
  1011. "Should only compare APFloats with the same semantics");
  1012. if (usesLayout<IEEEFloat>(getSemantics()))
  1013. return U.IEEE.compare(RHS.U.IEEE);
  1014. if (usesLayout<DoubleAPFloat>(getSemantics()))
  1015. return U.Double.compare(RHS.U.Double);
  1016. llvm_unreachable("Unexpected semantics");
  1017. }
  1018. bool bitwiseIsEqual(const APFloat &RHS) const {
  1019. if (&getSemantics() != &RHS.getSemantics())
  1020. return false;
  1021. if (usesLayout<IEEEFloat>(getSemantics()))
  1022. return U.IEEE.bitwiseIsEqual(RHS.U.IEEE);
  1023. if (usesLayout<DoubleAPFloat>(getSemantics()))
  1024. return U.Double.bitwiseIsEqual(RHS.U.Double);
  1025. llvm_unreachable("Unexpected semantics");
  1026. }
  1027. /// We don't rely on operator== working on double values, as
  1028. /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
  1029. /// As such, this method can be used to do an exact bit-for-bit comparison of
  1030. /// two floating point values.
  1031. ///
  1032. /// We leave the version with the double argument here because it's just so
  1033. /// convenient to write "2.0" and the like. Without this function we'd
  1034. /// have to duplicate its logic everywhere it's called.
  1035. bool isExactlyValue(double V) const {
  1036. bool ignored;
  1037. APFloat Tmp(V);
  1038. Tmp.convert(getSemantics(), APFloat::rmNearestTiesToEven, &ignored);
  1039. return bitwiseIsEqual(Tmp);
  1040. }
  1041. unsigned int convertToHexString(char *DST, unsigned int HexDigits,
  1042. bool UpperCase, roundingMode RM) const {
  1043. APFLOAT_DISPATCH_ON_SEMANTICS(
  1044. convertToHexString(DST, HexDigits, UpperCase, RM));
  1045. }
  1046. bool isZero() const { return getCategory() == fcZero; }
  1047. bool isInfinity() const { return getCategory() == fcInfinity; }
  1048. bool isNaN() const { return getCategory() == fcNaN; }
  1049. bool isNegative() const { return getIEEE().isNegative(); }
  1050. bool isDenormal() const { APFLOAT_DISPATCH_ON_SEMANTICS(isDenormal()); }
  1051. bool isSignaling() const { return getIEEE().isSignaling(); }
  1052. bool isNormal() const { return !isDenormal() && isFiniteNonZero(); }
  1053. bool isFinite() const { return !isNaN() && !isInfinity(); }
  1054. fltCategory getCategory() const { return getIEEE().getCategory(); }
  1055. const fltSemantics &getSemantics() const { return *U.semantics; }
  1056. bool isNonZero() const { return !isZero(); }
  1057. bool isFiniteNonZero() const { return isFinite() && !isZero(); }
  1058. bool isPosZero() const { return isZero() && !isNegative(); }
  1059. bool isNegZero() const { return isZero() && isNegative(); }
  1060. bool isSmallest() const { APFLOAT_DISPATCH_ON_SEMANTICS(isSmallest()); }
  1061. bool isLargest() const { APFLOAT_DISPATCH_ON_SEMANTICS(isLargest()); }
  1062. bool isInteger() const { APFLOAT_DISPATCH_ON_SEMANTICS(isInteger()); }
  1063. bool isIEEE() const { return usesLayout<IEEEFloat>(getSemantics()); }
  1064. APFloat &operator=(const APFloat &RHS) = default;
  1065. APFloat &operator=(APFloat &&RHS) = default;
  1066. void toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision = 0,
  1067. unsigned FormatMaxPadding = 3, bool TruncateZero = true) const {
  1068. APFLOAT_DISPATCH_ON_SEMANTICS(
  1069. toString(Str, FormatPrecision, FormatMaxPadding, TruncateZero));
  1070. }
  1071. void print(raw_ostream &) const;
  1072. void dump() const;
  1073. bool getExactInverse(APFloat *inv) const {
  1074. APFLOAT_DISPATCH_ON_SEMANTICS(getExactInverse(inv));
  1075. }
  1076. friend hash_code hash_value(const APFloat &Arg);
  1077. friend int ilogb(const APFloat &Arg) { return ilogb(Arg.getIEEE()); }
  1078. friend APFloat scalbn(APFloat X, int Exp, roundingMode RM);
  1079. friend APFloat frexp(const APFloat &X, int &Exp, roundingMode RM);
  1080. friend IEEEFloat;
  1081. friend DoubleAPFloat;
  1082. };
  1083. /// See friend declarations above.
  1084. ///
  1085. /// These additional declarations are required in order to compile LLVM with IBM
  1086. /// xlC compiler.
  1087. hash_code hash_value(const APFloat &Arg);
  1088. inline APFloat scalbn(APFloat X, int Exp, APFloat::roundingMode RM) {
  1089. if (APFloat::usesLayout<detail::IEEEFloat>(X.getSemantics()))
  1090. return APFloat(scalbn(X.U.IEEE, Exp, RM), X.getSemantics());
  1091. if (APFloat::usesLayout<detail::DoubleAPFloat>(X.getSemantics()))
  1092. return APFloat(scalbn(X.U.Double, Exp, RM), X.getSemantics());
  1093. llvm_unreachable("Unexpected semantics");
  1094. }
  1095. /// Equivalent of C standard library function.
  1096. ///
  1097. /// While the C standard says Exp is an unspecified value for infinity and nan,
  1098. /// this returns INT_MAX for infinities, and INT_MIN for NaNs.
  1099. inline APFloat frexp(const APFloat &X, int &Exp, APFloat::roundingMode RM) {
  1100. if (APFloat::usesLayout<detail::IEEEFloat>(X.getSemantics()))
  1101. return APFloat(frexp(X.U.IEEE, Exp, RM), X.getSemantics());
  1102. if (APFloat::usesLayout<detail::DoubleAPFloat>(X.getSemantics()))
  1103. return APFloat(frexp(X.U.Double, Exp, RM), X.getSemantics());
  1104. llvm_unreachable("Unexpected semantics");
  1105. }
  1106. /// Returns the absolute value of the argument.
  1107. inline APFloat abs(APFloat X) {
  1108. X.clearSign();
  1109. return X;
  1110. }
  1111. /// Returns the negated value of the argument.
  1112. inline APFloat neg(APFloat X) {
  1113. X.changeSign();
  1114. return X;
  1115. }
  1116. /// Implements IEEE minNum semantics. Returns the smaller of the 2 arguments if
  1117. /// both are not NaN. If either argument is a NaN, returns the other argument.
  1118. LLVM_READONLY
  1119. inline APFloat minnum(const APFloat &A, const APFloat &B) {
  1120. if (A.isNaN())
  1121. return B;
  1122. if (B.isNaN())
  1123. return A;
  1124. return B < A ? B : A;
  1125. }
  1126. /// Implements IEEE maxNum semantics. Returns the larger of the 2 arguments if
  1127. /// both are not NaN. If either argument is a NaN, returns the other argument.
  1128. LLVM_READONLY
  1129. inline APFloat maxnum(const APFloat &A, const APFloat &B) {
  1130. if (A.isNaN())
  1131. return B;
  1132. if (B.isNaN())
  1133. return A;
  1134. return A < B ? B : A;
  1135. }
  1136. /// Implements IEEE 754-2018 minimum semantics. Returns the smaller of 2
  1137. /// arguments, propagating NaNs and treating -0 as less than +0.
  1138. LLVM_READONLY
  1139. inline APFloat minimum(const APFloat &A, const APFloat &B) {
  1140. if (A.isNaN())
  1141. return A;
  1142. if (B.isNaN())
  1143. return B;
  1144. if (A.isZero() && B.isZero() && (A.isNegative() != B.isNegative()))
  1145. return A.isNegative() ? A : B;
  1146. return B < A ? B : A;
  1147. }
  1148. /// Implements IEEE 754-2018 maximum semantics. Returns the larger of 2
  1149. /// arguments, propagating NaNs and treating -0 as less than +0.
  1150. LLVM_READONLY
  1151. inline APFloat maximum(const APFloat &A, const APFloat &B) {
  1152. if (A.isNaN())
  1153. return A;
  1154. if (B.isNaN())
  1155. return B;
  1156. if (A.isZero() && B.isZero() && (A.isNegative() != B.isNegative()))
  1157. return A.isNegative() ? B : A;
  1158. return A < B ? B : A;
  1159. }
  1160. } // namespace llvm
  1161. #undef APFLOAT_DISPATCH_ON_SEMANTICS
  1162. #endif // LLVM_ADT_APFLOAT_H
  1163. #ifdef __GNUC__
  1164. #pragma GCC diagnostic pop
  1165. #endif