ScaledNumber.h 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/Support/ScaledNumber.h - Support for scaled numbers -*- 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. // This file contains functions (and a class) useful for working with scaled
  15. // numbers -- in particular, pairs of integers where one represents digits and
  16. // another represents a scale. The functions are helpers and live in the
  17. // namespace ScaledNumbers. The class ScaledNumber is useful for modelling
  18. // certain cost metrics that need simple, integer-like semantics that are easy
  19. // to reason about.
  20. //
  21. // These might remind you of soft-floats. If you want one of those, you're in
  22. // the wrong place. Look at include/llvm/ADT/APFloat.h instead.
  23. //
  24. //===----------------------------------------------------------------------===//
  25. #ifndef LLVM_SUPPORT_SCALEDNUMBER_H
  26. #define LLVM_SUPPORT_SCALEDNUMBER_H
  27. #include "llvm/Support/MathExtras.h"
  28. #include <algorithm>
  29. #include <cstdint>
  30. #include <limits>
  31. #include <string>
  32. #include <tuple>
  33. #include <utility>
  34. namespace llvm {
  35. namespace ScaledNumbers {
  36. /// Maximum scale; same as APFloat for easy debug printing.
  37. const int32_t MaxScale = 16383;
  38. /// Maximum scale; same as APFloat for easy debug printing.
  39. const int32_t MinScale = -16382;
  40. /// Get the width of a number.
  41. template <class DigitsT> inline int getWidth() { return sizeof(DigitsT) * 8; }
  42. /// Conditionally round up a scaled number.
  43. ///
  44. /// Given \c Digits and \c Scale, round up iff \c ShouldRound is \c true.
  45. /// Always returns \c Scale unless there's an overflow, in which case it
  46. /// returns \c 1+Scale.
  47. ///
  48. /// \pre adding 1 to \c Scale will not overflow INT16_MAX.
  49. template <class DigitsT>
  50. inline std::pair<DigitsT, int16_t> getRounded(DigitsT Digits, int16_t Scale,
  51. bool ShouldRound) {
  52. static_assert(!std::numeric_limits<DigitsT>::is_signed, "expected unsigned");
  53. if (ShouldRound)
  54. if (!++Digits)
  55. // Overflow.
  56. return std::make_pair(DigitsT(1) << (getWidth<DigitsT>() - 1), Scale + 1);
  57. return std::make_pair(Digits, Scale);
  58. }
  59. /// Convenience helper for 32-bit rounding.
  60. inline std::pair<uint32_t, int16_t> getRounded32(uint32_t Digits, int16_t Scale,
  61. bool ShouldRound) {
  62. return getRounded(Digits, Scale, ShouldRound);
  63. }
  64. /// Convenience helper for 64-bit rounding.
  65. inline std::pair<uint64_t, int16_t> getRounded64(uint64_t Digits, int16_t Scale,
  66. bool ShouldRound) {
  67. return getRounded(Digits, Scale, ShouldRound);
  68. }
  69. /// Adjust a 64-bit scaled number down to the appropriate width.
  70. ///
  71. /// \pre Adding 64 to \c Scale will not overflow INT16_MAX.
  72. template <class DigitsT>
  73. inline std::pair<DigitsT, int16_t> getAdjusted(uint64_t Digits,
  74. int16_t Scale = 0) {
  75. static_assert(!std::numeric_limits<DigitsT>::is_signed, "expected unsigned");
  76. const int Width = getWidth<DigitsT>();
  77. if (Width == 64 || Digits <= std::numeric_limits<DigitsT>::max())
  78. return std::make_pair(Digits, Scale);
  79. // Shift right and round.
  80. int Shift = 64 - Width - countLeadingZeros(Digits);
  81. return getRounded<DigitsT>(Digits >> Shift, Scale + Shift,
  82. Digits & (UINT64_C(1) << (Shift - 1)));
  83. }
  84. /// Convenience helper for adjusting to 32 bits.
  85. inline std::pair<uint32_t, int16_t> getAdjusted32(uint64_t Digits,
  86. int16_t Scale = 0) {
  87. return getAdjusted<uint32_t>(Digits, Scale);
  88. }
  89. /// Convenience helper for adjusting to 64 bits.
  90. inline std::pair<uint64_t, int16_t> getAdjusted64(uint64_t Digits,
  91. int16_t Scale = 0) {
  92. return getAdjusted<uint64_t>(Digits, Scale);
  93. }
  94. /// Multiply two 64-bit integers to create a 64-bit scaled number.
  95. ///
  96. /// Implemented with four 64-bit integer multiplies.
  97. std::pair<uint64_t, int16_t> multiply64(uint64_t LHS, uint64_t RHS);
  98. /// Multiply two 32-bit integers to create a 32-bit scaled number.
  99. ///
  100. /// Implemented with one 64-bit integer multiply.
  101. template <class DigitsT>
  102. inline std::pair<DigitsT, int16_t> getProduct(DigitsT LHS, DigitsT RHS) {
  103. static_assert(!std::numeric_limits<DigitsT>::is_signed, "expected unsigned");
  104. if (getWidth<DigitsT>() <= 32 || (LHS <= UINT32_MAX && RHS <= UINT32_MAX))
  105. return getAdjusted<DigitsT>(uint64_t(LHS) * RHS);
  106. return multiply64(LHS, RHS);
  107. }
  108. /// Convenience helper for 32-bit product.
  109. inline std::pair<uint32_t, int16_t> getProduct32(uint32_t LHS, uint32_t RHS) {
  110. return getProduct(LHS, RHS);
  111. }
  112. /// Convenience helper for 64-bit product.
  113. inline std::pair<uint64_t, int16_t> getProduct64(uint64_t LHS, uint64_t RHS) {
  114. return getProduct(LHS, RHS);
  115. }
  116. /// Divide two 64-bit integers to create a 64-bit scaled number.
  117. ///
  118. /// Implemented with long division.
  119. ///
  120. /// \pre \c Dividend and \c Divisor are non-zero.
  121. std::pair<uint64_t, int16_t> divide64(uint64_t Dividend, uint64_t Divisor);
  122. /// Divide two 32-bit integers to create a 32-bit scaled number.
  123. ///
  124. /// Implemented with one 64-bit integer divide/remainder pair.
  125. ///
  126. /// \pre \c Dividend and \c Divisor are non-zero.
  127. std::pair<uint32_t, int16_t> divide32(uint32_t Dividend, uint32_t Divisor);
  128. /// Divide two 32-bit numbers to create a 32-bit scaled number.
  129. ///
  130. /// Implemented with one 64-bit integer divide/remainder pair.
  131. ///
  132. /// Returns \c (DigitsT_MAX, MaxScale) for divide-by-zero (0 for 0/0).
  133. template <class DigitsT>
  134. std::pair<DigitsT, int16_t> getQuotient(DigitsT Dividend, DigitsT Divisor) {
  135. static_assert(!std::numeric_limits<DigitsT>::is_signed, "expected unsigned");
  136. static_assert(sizeof(DigitsT) == 4 || sizeof(DigitsT) == 8,
  137. "expected 32-bit or 64-bit digits");
  138. // Check for zero.
  139. if (!Dividend)
  140. return std::make_pair(0, 0);
  141. if (!Divisor)
  142. return std::make_pair(std::numeric_limits<DigitsT>::max(), MaxScale);
  143. if (getWidth<DigitsT>() == 64)
  144. return divide64(Dividend, Divisor);
  145. return divide32(Dividend, Divisor);
  146. }
  147. /// Convenience helper for 32-bit quotient.
  148. inline std::pair<uint32_t, int16_t> getQuotient32(uint32_t Dividend,
  149. uint32_t Divisor) {
  150. return getQuotient(Dividend, Divisor);
  151. }
  152. /// Convenience helper for 64-bit quotient.
  153. inline std::pair<uint64_t, int16_t> getQuotient64(uint64_t Dividend,
  154. uint64_t Divisor) {
  155. return getQuotient(Dividend, Divisor);
  156. }
  157. /// Implementation of getLg() and friends.
  158. ///
  159. /// Returns the rounded lg of \c Digits*2^Scale and an int specifying whether
  160. /// this was rounded up (1), down (-1), or exact (0).
  161. ///
  162. /// Returns \c INT32_MIN when \c Digits is zero.
  163. template <class DigitsT>
  164. inline std::pair<int32_t, int> getLgImpl(DigitsT Digits, int16_t Scale) {
  165. static_assert(!std::numeric_limits<DigitsT>::is_signed, "expected unsigned");
  166. if (!Digits)
  167. return std::make_pair(INT32_MIN, 0);
  168. // Get the floor of the lg of Digits.
  169. int32_t LocalFloor = sizeof(Digits) * 8 - countLeadingZeros(Digits) - 1;
  170. // Get the actual floor.
  171. int32_t Floor = Scale + LocalFloor;
  172. if (Digits == UINT64_C(1) << LocalFloor)
  173. return std::make_pair(Floor, 0);
  174. // Round based on the next digit.
  175. assert(LocalFloor >= 1);
  176. bool Round = Digits & UINT64_C(1) << (LocalFloor - 1);
  177. return std::make_pair(Floor + Round, Round ? 1 : -1);
  178. }
  179. /// Get the lg (rounded) of a scaled number.
  180. ///
  181. /// Get the lg of \c Digits*2^Scale.
  182. ///
  183. /// Returns \c INT32_MIN when \c Digits is zero.
  184. template <class DigitsT> int32_t getLg(DigitsT Digits, int16_t Scale) {
  185. return getLgImpl(Digits, Scale).first;
  186. }
  187. /// Get the lg floor of a scaled number.
  188. ///
  189. /// Get the floor of the lg of \c Digits*2^Scale.
  190. ///
  191. /// Returns \c INT32_MIN when \c Digits is zero.
  192. template <class DigitsT> int32_t getLgFloor(DigitsT Digits, int16_t Scale) {
  193. auto Lg = getLgImpl(Digits, Scale);
  194. return Lg.first - (Lg.second > 0);
  195. }
  196. /// Get the lg ceiling of a scaled number.
  197. ///
  198. /// Get the ceiling of the lg of \c Digits*2^Scale.
  199. ///
  200. /// Returns \c INT32_MIN when \c Digits is zero.
  201. template <class DigitsT> int32_t getLgCeiling(DigitsT Digits, int16_t Scale) {
  202. auto Lg = getLgImpl(Digits, Scale);
  203. return Lg.first + (Lg.second < 0);
  204. }
  205. /// Implementation for comparing scaled numbers.
  206. ///
  207. /// Compare two 64-bit numbers with different scales. Given that the scale of
  208. /// \c L is higher than that of \c R by \c ScaleDiff, compare them. Return -1,
  209. /// 1, and 0 for less than, greater than, and equal, respectively.
  210. ///
  211. /// \pre 0 <= ScaleDiff < 64.
  212. int compareImpl(uint64_t L, uint64_t R, int ScaleDiff);
  213. /// Compare two scaled numbers.
  214. ///
  215. /// Compare two scaled numbers. Returns 0 for equal, -1 for less than, and 1
  216. /// for greater than.
  217. template <class DigitsT>
  218. int compare(DigitsT LDigits, int16_t LScale, DigitsT RDigits, int16_t RScale) {
  219. static_assert(!std::numeric_limits<DigitsT>::is_signed, "expected unsigned");
  220. // Check for zero.
  221. if (!LDigits)
  222. return RDigits ? -1 : 0;
  223. if (!RDigits)
  224. return 1;
  225. // Check for the scale. Use getLgFloor to be sure that the scale difference
  226. // is always lower than 64.
  227. int32_t lgL = getLgFloor(LDigits, LScale), lgR = getLgFloor(RDigits, RScale);
  228. if (lgL != lgR)
  229. return lgL < lgR ? -1 : 1;
  230. // Compare digits.
  231. if (LScale < RScale)
  232. return compareImpl(LDigits, RDigits, RScale - LScale);
  233. return -compareImpl(RDigits, LDigits, LScale - RScale);
  234. }
  235. /// Match scales of two numbers.
  236. ///
  237. /// Given two scaled numbers, match up their scales. Change the digits and
  238. /// scales in place. Shift the digits as necessary to form equivalent numbers,
  239. /// losing precision only when necessary.
  240. ///
  241. /// If the output value of \c LDigits (\c RDigits) is \c 0, the output value of
  242. /// \c LScale (\c RScale) is unspecified.
  243. ///
  244. /// As a convenience, returns the matching scale. If the output value of one
  245. /// number is zero, returns the scale of the other. If both are zero, which
  246. /// scale is returned is unspecified.
  247. template <class DigitsT>
  248. int16_t matchScales(DigitsT &LDigits, int16_t &LScale, DigitsT &RDigits,
  249. int16_t &RScale) {
  250. static_assert(!std::numeric_limits<DigitsT>::is_signed, "expected unsigned");
  251. if (LScale < RScale)
  252. // Swap arguments.
  253. return matchScales(RDigits, RScale, LDigits, LScale);
  254. if (!LDigits)
  255. return RScale;
  256. if (!RDigits || LScale == RScale)
  257. return LScale;
  258. // Now LScale > RScale. Get the difference.
  259. int32_t ScaleDiff = int32_t(LScale) - RScale;
  260. if (ScaleDiff >= 2 * getWidth<DigitsT>()) {
  261. // Don't bother shifting. RDigits will get zero-ed out anyway.
  262. RDigits = 0;
  263. return LScale;
  264. }
  265. // Shift LDigits left as much as possible, then shift RDigits right.
  266. int32_t ShiftL = std::min<int32_t>(countLeadingZeros(LDigits), ScaleDiff);
  267. assert(ShiftL < getWidth<DigitsT>() && "can't shift more than width");
  268. int32_t ShiftR = ScaleDiff - ShiftL;
  269. if (ShiftR >= getWidth<DigitsT>()) {
  270. // Don't bother shifting. RDigits will get zero-ed out anyway.
  271. RDigits = 0;
  272. return LScale;
  273. }
  274. LDigits <<= ShiftL;
  275. RDigits >>= ShiftR;
  276. LScale -= ShiftL;
  277. RScale += ShiftR;
  278. assert(LScale == RScale && "scales should match");
  279. return LScale;
  280. }
  281. /// Get the sum of two scaled numbers.
  282. ///
  283. /// Get the sum of two scaled numbers with as much precision as possible.
  284. ///
  285. /// \pre Adding 1 to \c LScale (or \c RScale) will not overflow INT16_MAX.
  286. template <class DigitsT>
  287. std::pair<DigitsT, int16_t> getSum(DigitsT LDigits, int16_t LScale,
  288. DigitsT RDigits, int16_t RScale) {
  289. static_assert(!std::numeric_limits<DigitsT>::is_signed, "expected unsigned");
  290. // Check inputs up front. This is only relevant if addition overflows, but
  291. // testing here should catch more bugs.
  292. assert(LScale < INT16_MAX && "scale too large");
  293. assert(RScale < INT16_MAX && "scale too large");
  294. // Normalize digits to match scales.
  295. int16_t Scale = matchScales(LDigits, LScale, RDigits, RScale);
  296. // Compute sum.
  297. DigitsT Sum = LDigits + RDigits;
  298. if (Sum >= RDigits)
  299. return std::make_pair(Sum, Scale);
  300. // Adjust sum after arithmetic overflow.
  301. DigitsT HighBit = DigitsT(1) << (getWidth<DigitsT>() - 1);
  302. return std::make_pair(HighBit | Sum >> 1, Scale + 1);
  303. }
  304. /// Convenience helper for 32-bit sum.
  305. inline std::pair<uint32_t, int16_t> getSum32(uint32_t LDigits, int16_t LScale,
  306. uint32_t RDigits, int16_t RScale) {
  307. return getSum(LDigits, LScale, RDigits, RScale);
  308. }
  309. /// Convenience helper for 64-bit sum.
  310. inline std::pair<uint64_t, int16_t> getSum64(uint64_t LDigits, int16_t LScale,
  311. uint64_t RDigits, int16_t RScale) {
  312. return getSum(LDigits, LScale, RDigits, RScale);
  313. }
  314. /// Get the difference of two scaled numbers.
  315. ///
  316. /// Get LHS minus RHS with as much precision as possible.
  317. ///
  318. /// Returns \c (0, 0) if the RHS is larger than the LHS.
  319. template <class DigitsT>
  320. std::pair<DigitsT, int16_t> getDifference(DigitsT LDigits, int16_t LScale,
  321. DigitsT RDigits, int16_t RScale) {
  322. static_assert(!std::numeric_limits<DigitsT>::is_signed, "expected unsigned");
  323. // Normalize digits to match scales.
  324. const DigitsT SavedRDigits = RDigits;
  325. const int16_t SavedRScale = RScale;
  326. matchScales(LDigits, LScale, RDigits, RScale);
  327. // Compute difference.
  328. if (LDigits <= RDigits)
  329. return std::make_pair(0, 0);
  330. if (RDigits || !SavedRDigits)
  331. return std::make_pair(LDigits - RDigits, LScale);
  332. // Check if RDigits just barely lost its last bit. E.g., for 32-bit:
  333. //
  334. // 1*2^32 - 1*2^0 == 0xffffffff != 1*2^32
  335. const auto RLgFloor = getLgFloor(SavedRDigits, SavedRScale);
  336. if (!compare(LDigits, LScale, DigitsT(1), RLgFloor + getWidth<DigitsT>()))
  337. return std::make_pair(std::numeric_limits<DigitsT>::max(), RLgFloor);
  338. return std::make_pair(LDigits, LScale);
  339. }
  340. /// Convenience helper for 32-bit difference.
  341. inline std::pair<uint32_t, int16_t> getDifference32(uint32_t LDigits,
  342. int16_t LScale,
  343. uint32_t RDigits,
  344. int16_t RScale) {
  345. return getDifference(LDigits, LScale, RDigits, RScale);
  346. }
  347. /// Convenience helper for 64-bit difference.
  348. inline std::pair<uint64_t, int16_t> getDifference64(uint64_t LDigits,
  349. int16_t LScale,
  350. uint64_t RDigits,
  351. int16_t RScale) {
  352. return getDifference(LDigits, LScale, RDigits, RScale);
  353. }
  354. } // end namespace ScaledNumbers
  355. } // end namespace llvm
  356. namespace llvm {
  357. class raw_ostream;
  358. class ScaledNumberBase {
  359. public:
  360. static constexpr int DefaultPrecision = 10;
  361. static void dump(uint64_t D, int16_t E, int Width);
  362. static raw_ostream &print(raw_ostream &OS, uint64_t D, int16_t E, int Width,
  363. unsigned Precision);
  364. static std::string toString(uint64_t D, int16_t E, int Width,
  365. unsigned Precision);
  366. static int countLeadingZeros32(uint32_t N) { return countLeadingZeros(N); }
  367. static int countLeadingZeros64(uint64_t N) { return countLeadingZeros(N); }
  368. static uint64_t getHalf(uint64_t N) { return (N >> 1) + (N & 1); }
  369. static std::pair<uint64_t, bool> splitSigned(int64_t N) {
  370. if (N >= 0)
  371. return std::make_pair(N, false);
  372. uint64_t Unsigned = N == INT64_MIN ? UINT64_C(1) << 63 : uint64_t(-N);
  373. return std::make_pair(Unsigned, true);
  374. }
  375. static int64_t joinSigned(uint64_t U, bool IsNeg) {
  376. if (U > uint64_t(INT64_MAX))
  377. return IsNeg ? INT64_MIN : INT64_MAX;
  378. return IsNeg ? -int64_t(U) : int64_t(U);
  379. }
  380. };
  381. /// Simple representation of a scaled number.
  382. ///
  383. /// ScaledNumber is a number represented by digits and a scale. It uses simple
  384. /// saturation arithmetic and every operation is well-defined for every value.
  385. /// It's somewhat similar in behaviour to a soft-float, but is *not* a
  386. /// replacement for one. If you're doing numerics, look at \a APFloat instead.
  387. /// Nevertheless, we've found these semantics useful for modelling certain cost
  388. /// metrics.
  389. ///
  390. /// The number is split into a signed scale and unsigned digits. The number
  391. /// represented is \c getDigits()*2^getScale(). In this way, the digits are
  392. /// much like the mantissa in the x87 long double, but there is no canonical
  393. /// form so the same number can be represented by many bit representations.
  394. ///
  395. /// ScaledNumber is templated on the underlying integer type for digits, which
  396. /// is expected to be unsigned.
  397. ///
  398. /// Unlike APFloat, ScaledNumber does not model architecture floating point
  399. /// behaviour -- while this might make it a little faster and easier to reason
  400. /// about, it certainly makes it more dangerous for general numerics.
  401. ///
  402. /// ScaledNumber is totally ordered. However, there is no canonical form, so
  403. /// there are multiple representations of most scalars. E.g.:
  404. ///
  405. /// ScaledNumber(8u, 0) == ScaledNumber(4u, 1)
  406. /// ScaledNumber(4u, 1) == ScaledNumber(2u, 2)
  407. /// ScaledNumber(2u, 2) == ScaledNumber(1u, 3)
  408. ///
  409. /// ScaledNumber implements most arithmetic operations. Precision is kept
  410. /// where possible. Uses simple saturation arithmetic, so that operations
  411. /// saturate to 0.0 or getLargest() rather than under or overflowing. It has
  412. /// some extra arithmetic for unit inversion. 0.0/0.0 is defined to be 0.0.
  413. /// Any other division by 0.0 is defined to be getLargest().
  414. ///
  415. /// As a convenience for modifying the exponent, left and right shifting are
  416. /// both implemented, and both interpret negative shifts as positive shifts in
  417. /// the opposite direction.
  418. ///
  419. /// Scales are limited to the range accepted by x87 long double. This makes
  420. /// it trivial to add functionality to convert to APFloat (this is already
  421. /// relied on for the implementation of printing).
  422. ///
  423. /// Possible (and conflicting) future directions:
  424. ///
  425. /// 1. Turn this into a wrapper around \a APFloat.
  426. /// 2. Share the algorithm implementations with \a APFloat.
  427. /// 3. Allow \a ScaledNumber to represent a signed number.
  428. template <class DigitsT> class ScaledNumber : ScaledNumberBase {
  429. public:
  430. static_assert(!std::numeric_limits<DigitsT>::is_signed,
  431. "only unsigned floats supported");
  432. typedef DigitsT DigitsType;
  433. private:
  434. typedef std::numeric_limits<DigitsType> DigitsLimits;
  435. static constexpr int Width = sizeof(DigitsType) * 8;
  436. static_assert(Width <= 64, "invalid integer width for digits");
  437. private:
  438. DigitsType Digits = 0;
  439. int16_t Scale = 0;
  440. public:
  441. ScaledNumber() = default;
  442. constexpr ScaledNumber(DigitsType Digits, int16_t Scale)
  443. : Digits(Digits), Scale(Scale) {}
  444. private:
  445. ScaledNumber(const std::pair<DigitsT, int16_t> &X)
  446. : Digits(X.first), Scale(X.second) {}
  447. public:
  448. static ScaledNumber getZero() { return ScaledNumber(0, 0); }
  449. static ScaledNumber getOne() { return ScaledNumber(1, 0); }
  450. static ScaledNumber getLargest() {
  451. return ScaledNumber(DigitsLimits::max(), ScaledNumbers::MaxScale);
  452. }
  453. static ScaledNumber get(uint64_t N) { return adjustToWidth(N, 0); }
  454. static ScaledNumber getInverse(uint64_t N) {
  455. return get(N).invert();
  456. }
  457. static ScaledNumber getFraction(DigitsType N, DigitsType D) {
  458. return getQuotient(N, D);
  459. }
  460. int16_t getScale() const { return Scale; }
  461. DigitsType getDigits() const { return Digits; }
  462. /// Convert to the given integer type.
  463. ///
  464. /// Convert to \c IntT using simple saturating arithmetic, truncating if
  465. /// necessary.
  466. template <class IntT> IntT toInt() const;
  467. bool isZero() const { return !Digits; }
  468. bool isLargest() const { return *this == getLargest(); }
  469. bool isOne() const {
  470. if (Scale > 0 || Scale <= -Width)
  471. return false;
  472. return Digits == DigitsType(1) << -Scale;
  473. }
  474. /// The log base 2, rounded.
  475. ///
  476. /// Get the lg of the scalar. lg 0 is defined to be INT32_MIN.
  477. int32_t lg() const { return ScaledNumbers::getLg(Digits, Scale); }
  478. /// The log base 2, rounded towards INT32_MIN.
  479. ///
  480. /// Get the lg floor. lg 0 is defined to be INT32_MIN.
  481. int32_t lgFloor() const { return ScaledNumbers::getLgFloor(Digits, Scale); }
  482. /// The log base 2, rounded towards INT32_MAX.
  483. ///
  484. /// Get the lg ceiling. lg 0 is defined to be INT32_MIN.
  485. int32_t lgCeiling() const {
  486. return ScaledNumbers::getLgCeiling(Digits, Scale);
  487. }
  488. bool operator==(const ScaledNumber &X) const { return compare(X) == 0; }
  489. bool operator<(const ScaledNumber &X) const { return compare(X) < 0; }
  490. bool operator!=(const ScaledNumber &X) const { return compare(X) != 0; }
  491. bool operator>(const ScaledNumber &X) const { return compare(X) > 0; }
  492. bool operator<=(const ScaledNumber &X) const { return compare(X) <= 0; }
  493. bool operator>=(const ScaledNumber &X) const { return compare(X) >= 0; }
  494. bool operator!() const { return isZero(); }
  495. /// Convert to a decimal representation in a string.
  496. ///
  497. /// Convert to a string. Uses scientific notation for very large/small
  498. /// numbers. Scientific notation is used roughly for numbers outside of the
  499. /// range 2^-64 through 2^64.
  500. ///
  501. /// \c Precision indicates the number of decimal digits of precision to use;
  502. /// 0 requests the maximum available.
  503. ///
  504. /// As a special case to make debugging easier, if the number is small enough
  505. /// to convert without scientific notation and has more than \c Precision
  506. /// digits before the decimal place, it's printed accurately to the first
  507. /// digit past zero. E.g., assuming 10 digits of precision:
  508. ///
  509. /// 98765432198.7654... => 98765432198.8
  510. /// 8765432198.7654... => 8765432198.8
  511. /// 765432198.7654... => 765432198.8
  512. /// 65432198.7654... => 65432198.77
  513. /// 5432198.7654... => 5432198.765
  514. std::string toString(unsigned Precision = DefaultPrecision) {
  515. return ScaledNumberBase::toString(Digits, Scale, Width, Precision);
  516. }
  517. /// Print a decimal representation.
  518. ///
  519. /// Print a string. See toString for documentation.
  520. raw_ostream &print(raw_ostream &OS,
  521. unsigned Precision = DefaultPrecision) const {
  522. return ScaledNumberBase::print(OS, Digits, Scale, Width, Precision);
  523. }
  524. void dump() const { return ScaledNumberBase::dump(Digits, Scale, Width); }
  525. ScaledNumber &operator+=(const ScaledNumber &X) {
  526. std::tie(Digits, Scale) =
  527. ScaledNumbers::getSum(Digits, Scale, X.Digits, X.Scale);
  528. // Check for exponent past MaxScale.
  529. if (Scale > ScaledNumbers::MaxScale)
  530. *this = getLargest();
  531. return *this;
  532. }
  533. ScaledNumber &operator-=(const ScaledNumber &X) {
  534. std::tie(Digits, Scale) =
  535. ScaledNumbers::getDifference(Digits, Scale, X.Digits, X.Scale);
  536. return *this;
  537. }
  538. ScaledNumber &operator*=(const ScaledNumber &X);
  539. ScaledNumber &operator/=(const ScaledNumber &X);
  540. ScaledNumber &operator<<=(int16_t Shift) {
  541. shiftLeft(Shift);
  542. return *this;
  543. }
  544. ScaledNumber &operator>>=(int16_t Shift) {
  545. shiftRight(Shift);
  546. return *this;
  547. }
  548. private:
  549. void shiftLeft(int32_t Shift);
  550. void shiftRight(int32_t Shift);
  551. /// Adjust two floats to have matching exponents.
  552. ///
  553. /// Adjust \c this and \c X to have matching exponents. Returns the new \c X
  554. /// by value. Does nothing if \a isZero() for either.
  555. ///
  556. /// The value that compares smaller will lose precision, and possibly become
  557. /// \a isZero().
  558. ScaledNumber matchScales(ScaledNumber X) {
  559. ScaledNumbers::matchScales(Digits, Scale, X.Digits, X.Scale);
  560. return X;
  561. }
  562. public:
  563. /// Scale a large number accurately.
  564. ///
  565. /// Scale N (multiply it by this). Uses full precision multiplication, even
  566. /// if Width is smaller than 64, so information is not lost.
  567. uint64_t scale(uint64_t N) const;
  568. uint64_t scaleByInverse(uint64_t N) const {
  569. // TODO: implement directly, rather than relying on inverse. Inverse is
  570. // expensive.
  571. return inverse().scale(N);
  572. }
  573. int64_t scale(int64_t N) const {
  574. std::pair<uint64_t, bool> Unsigned = splitSigned(N);
  575. return joinSigned(scale(Unsigned.first), Unsigned.second);
  576. }
  577. int64_t scaleByInverse(int64_t N) const {
  578. std::pair<uint64_t, bool> Unsigned = splitSigned(N);
  579. return joinSigned(scaleByInverse(Unsigned.first), Unsigned.second);
  580. }
  581. int compare(const ScaledNumber &X) const {
  582. return ScaledNumbers::compare(Digits, Scale, X.Digits, X.Scale);
  583. }
  584. int compareTo(uint64_t N) const {
  585. return ScaledNumbers::compare<uint64_t>(Digits, Scale, N, 0);
  586. }
  587. int compareTo(int64_t N) const { return N < 0 ? 1 : compareTo(uint64_t(N)); }
  588. ScaledNumber &invert() { return *this = ScaledNumber::get(1) / *this; }
  589. ScaledNumber inverse() const { return ScaledNumber(*this).invert(); }
  590. private:
  591. static ScaledNumber getProduct(DigitsType LHS, DigitsType RHS) {
  592. return ScaledNumbers::getProduct(LHS, RHS);
  593. }
  594. static ScaledNumber getQuotient(DigitsType Dividend, DigitsType Divisor) {
  595. return ScaledNumbers::getQuotient(Dividend, Divisor);
  596. }
  597. static int countLeadingZerosWidth(DigitsType Digits) {
  598. if (Width == 64)
  599. return countLeadingZeros64(Digits);
  600. if (Width == 32)
  601. return countLeadingZeros32(Digits);
  602. return countLeadingZeros32(Digits) + Width - 32;
  603. }
  604. /// Adjust a number to width, rounding up if necessary.
  605. ///
  606. /// Should only be called for \c Shift close to zero.
  607. ///
  608. /// \pre Shift >= MinScale && Shift + 64 <= MaxScale.
  609. static ScaledNumber adjustToWidth(uint64_t N, int32_t Shift) {
  610. assert(Shift >= ScaledNumbers::MinScale && "Shift should be close to 0");
  611. assert(Shift <= ScaledNumbers::MaxScale - 64 &&
  612. "Shift should be close to 0");
  613. auto Adjusted = ScaledNumbers::getAdjusted<DigitsT>(N, Shift);
  614. return Adjusted;
  615. }
  616. static ScaledNumber getRounded(ScaledNumber P, bool Round) {
  617. // Saturate.
  618. if (P.isLargest())
  619. return P;
  620. return ScaledNumbers::getRounded(P.Digits, P.Scale, Round);
  621. }
  622. };
  623. #define SCALED_NUMBER_BOP(op, base) \
  624. template <class DigitsT> \
  625. ScaledNumber<DigitsT> operator op(const ScaledNumber<DigitsT> &L, \
  626. const ScaledNumber<DigitsT> &R) { \
  627. return ScaledNumber<DigitsT>(L) base R; \
  628. }
  629. SCALED_NUMBER_BOP(+, += )
  630. SCALED_NUMBER_BOP(-, -= )
  631. SCALED_NUMBER_BOP(*, *= )
  632. SCALED_NUMBER_BOP(/, /= )
  633. #undef SCALED_NUMBER_BOP
  634. template <class DigitsT>
  635. ScaledNumber<DigitsT> operator<<(const ScaledNumber<DigitsT> &L,
  636. int16_t Shift) {
  637. return ScaledNumber<DigitsT>(L) <<= Shift;
  638. }
  639. template <class DigitsT>
  640. ScaledNumber<DigitsT> operator>>(const ScaledNumber<DigitsT> &L,
  641. int16_t Shift) {
  642. return ScaledNumber<DigitsT>(L) >>= Shift;
  643. }
  644. template <class DigitsT>
  645. raw_ostream &operator<<(raw_ostream &OS, const ScaledNumber<DigitsT> &X) {
  646. return X.print(OS, 10);
  647. }
  648. #define SCALED_NUMBER_COMPARE_TO_TYPE(op, T1, T2) \
  649. template <class DigitsT> \
  650. bool operator op(const ScaledNumber<DigitsT> &L, T1 R) { \
  651. return L.compareTo(T2(R)) op 0; \
  652. } \
  653. template <class DigitsT> \
  654. bool operator op(T1 L, const ScaledNumber<DigitsT> &R) { \
  655. return 0 op R.compareTo(T2(L)); \
  656. }
  657. #define SCALED_NUMBER_COMPARE_TO(op) \
  658. SCALED_NUMBER_COMPARE_TO_TYPE(op, uint64_t, uint64_t) \
  659. SCALED_NUMBER_COMPARE_TO_TYPE(op, uint32_t, uint64_t) \
  660. SCALED_NUMBER_COMPARE_TO_TYPE(op, int64_t, int64_t) \
  661. SCALED_NUMBER_COMPARE_TO_TYPE(op, int32_t, int64_t)
  662. SCALED_NUMBER_COMPARE_TO(< )
  663. SCALED_NUMBER_COMPARE_TO(> )
  664. SCALED_NUMBER_COMPARE_TO(== )
  665. SCALED_NUMBER_COMPARE_TO(!= )
  666. SCALED_NUMBER_COMPARE_TO(<= )
  667. SCALED_NUMBER_COMPARE_TO(>= )
  668. #undef SCALED_NUMBER_COMPARE_TO
  669. #undef SCALED_NUMBER_COMPARE_TO_TYPE
  670. template <class DigitsT>
  671. uint64_t ScaledNumber<DigitsT>::scale(uint64_t N) const {
  672. if (Width == 64 || N <= DigitsLimits::max())
  673. return (get(N) * *this).template toInt<uint64_t>();
  674. // Defer to the 64-bit version.
  675. return ScaledNumber<uint64_t>(Digits, Scale).scale(N);
  676. }
  677. template <class DigitsT>
  678. template <class IntT>
  679. IntT ScaledNumber<DigitsT>::toInt() const {
  680. typedef std::numeric_limits<IntT> Limits;
  681. if (*this < 1)
  682. return 0;
  683. if (*this >= Limits::max())
  684. return Limits::max();
  685. IntT N = Digits;
  686. if (Scale > 0) {
  687. assert(size_t(Scale) < sizeof(IntT) * 8);
  688. return N << Scale;
  689. }
  690. if (Scale < 0) {
  691. assert(size_t(-Scale) < sizeof(IntT) * 8);
  692. return N >> -Scale;
  693. }
  694. return N;
  695. }
  696. template <class DigitsT>
  697. ScaledNumber<DigitsT> &ScaledNumber<DigitsT>::
  698. operator*=(const ScaledNumber &X) {
  699. if (isZero())
  700. return *this;
  701. if (X.isZero())
  702. return *this = X;
  703. // Save the exponents.
  704. int32_t Scales = int32_t(Scale) + int32_t(X.Scale);
  705. // Get the raw product.
  706. *this = getProduct(Digits, X.Digits);
  707. // Combine with exponents.
  708. return *this <<= Scales;
  709. }
  710. template <class DigitsT>
  711. ScaledNumber<DigitsT> &ScaledNumber<DigitsT>::
  712. operator/=(const ScaledNumber &X) {
  713. if (isZero())
  714. return *this;
  715. if (X.isZero())
  716. return *this = getLargest();
  717. // Save the exponents.
  718. int32_t Scales = int32_t(Scale) - int32_t(X.Scale);
  719. // Get the raw quotient.
  720. *this = getQuotient(Digits, X.Digits);
  721. // Combine with exponents.
  722. return *this <<= Scales;
  723. }
  724. template <class DigitsT> void ScaledNumber<DigitsT>::shiftLeft(int32_t Shift) {
  725. if (!Shift || isZero())
  726. return;
  727. assert(Shift != INT32_MIN);
  728. if (Shift < 0) {
  729. shiftRight(-Shift);
  730. return;
  731. }
  732. // Shift as much as we can in the exponent.
  733. int32_t ScaleShift = std::min(Shift, ScaledNumbers::MaxScale - Scale);
  734. Scale += ScaleShift;
  735. if (ScaleShift == Shift)
  736. return;
  737. // Check this late, since it's rare.
  738. if (isLargest())
  739. return;
  740. // Shift the digits themselves.
  741. Shift -= ScaleShift;
  742. if (Shift > countLeadingZerosWidth(Digits)) {
  743. // Saturate.
  744. *this = getLargest();
  745. return;
  746. }
  747. Digits <<= Shift;
  748. }
  749. template <class DigitsT> void ScaledNumber<DigitsT>::shiftRight(int32_t Shift) {
  750. if (!Shift || isZero())
  751. return;
  752. assert(Shift != INT32_MIN);
  753. if (Shift < 0) {
  754. shiftLeft(-Shift);
  755. return;
  756. }
  757. // Shift as much as we can in the exponent.
  758. int32_t ScaleShift = std::min(Shift, Scale - ScaledNumbers::MinScale);
  759. Scale -= ScaleShift;
  760. if (ScaleShift == Shift)
  761. return;
  762. // Shift the digits themselves.
  763. Shift -= ScaleShift;
  764. if (Shift >= Width) {
  765. // Saturate.
  766. *this = getZero();
  767. return;
  768. }
  769. Digits >>= Shift;
  770. }
  771. } // end namespace llvm
  772. #endif // LLVM_SUPPORT_SCALEDNUMBER_H
  773. #ifdef __GNUC__
  774. #pragma GCC diagnostic pop
  775. #endif