APFloat.h 49 KB

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