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