1// Copyright 2011 the V8 project authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include <cmath>
6
7#include "include/v8stdint.h"
8#include "src/base/logging.h"
9#include "src/utils.h"
10
11#include "src/double.h"
12#include "src/fixed-dtoa.h"
13
14namespace v8 {
15namespace internal {
16
17// Represents a 128bit type. This class should be replaced by a native type on
18// platforms that support 128bit integers.
19class UInt128 {
20 public:
21  UInt128() : high_bits_(0), low_bits_(0) { }
22  UInt128(uint64_t high, uint64_t low) : high_bits_(high), low_bits_(low) { }
23
24  void Multiply(uint32_t multiplicand) {
25    uint64_t accumulator;
26
27    accumulator = (low_bits_ & kMask32) * multiplicand;
28    uint32_t part = static_cast<uint32_t>(accumulator & kMask32);
29    accumulator >>= 32;
30    accumulator = accumulator + (low_bits_ >> 32) * multiplicand;
31    low_bits_ = (accumulator << 32) + part;
32    accumulator >>= 32;
33    accumulator = accumulator + (high_bits_ & kMask32) * multiplicand;
34    part = static_cast<uint32_t>(accumulator & kMask32);
35    accumulator >>= 32;
36    accumulator = accumulator + (high_bits_ >> 32) * multiplicand;
37    high_bits_ = (accumulator << 32) + part;
38    DCHECK((accumulator >> 32) == 0);
39  }
40
41  void Shift(int shift_amount) {
42    DCHECK(-64 <= shift_amount && shift_amount <= 64);
43    if (shift_amount == 0) {
44      return;
45    } else if (shift_amount == -64) {
46      high_bits_ = low_bits_;
47      low_bits_ = 0;
48    } else if (shift_amount == 64) {
49      low_bits_ = high_bits_;
50      high_bits_ = 0;
51    } else if (shift_amount <= 0) {
52      high_bits_ <<= -shift_amount;
53      high_bits_ += low_bits_ >> (64 + shift_amount);
54      low_bits_ <<= -shift_amount;
55    } else {
56      low_bits_ >>= shift_amount;
57      low_bits_ += high_bits_ << (64 - shift_amount);
58      high_bits_ >>= shift_amount;
59    }
60  }
61
62  // Modifies *this to *this MOD (2^power).
63  // Returns *this DIV (2^power).
64  int DivModPowerOf2(int power) {
65    if (power >= 64) {
66      int result = static_cast<int>(high_bits_ >> (power - 64));
67      high_bits_ -= static_cast<uint64_t>(result) << (power - 64);
68      return result;
69    } else {
70      uint64_t part_low = low_bits_ >> power;
71      uint64_t part_high = high_bits_ << (64 - power);
72      int result = static_cast<int>(part_low + part_high);
73      high_bits_ = 0;
74      low_bits_ -= part_low << power;
75      return result;
76    }
77  }
78
79  bool IsZero() const {
80    return high_bits_ == 0 && low_bits_ == 0;
81  }
82
83  int BitAt(int position) {
84    if (position >= 64) {
85      return static_cast<int>(high_bits_ >> (position - 64)) & 1;
86    } else {
87      return static_cast<int>(low_bits_ >> position) & 1;
88    }
89  }
90
91 private:
92  static const uint64_t kMask32 = 0xFFFFFFFF;
93  // Value == (high_bits_ << 64) + low_bits_
94  uint64_t high_bits_;
95  uint64_t low_bits_;
96};
97
98
99static const int kDoubleSignificandSize = 53;  // Includes the hidden bit.
100
101
102static void FillDigits32FixedLength(uint32_t number, int requested_length,
103                                    Vector<char> buffer, int* length) {
104  for (int i = requested_length - 1; i >= 0; --i) {
105    buffer[(*length) + i] = '0' + number % 10;
106    number /= 10;
107  }
108  *length += requested_length;
109}
110
111
112static void FillDigits32(uint32_t number, Vector<char> buffer, int* length) {
113  int number_length = 0;
114  // We fill the digits in reverse order and exchange them afterwards.
115  while (number != 0) {
116    int digit = number % 10;
117    number /= 10;
118    buffer[(*length) + number_length] = '0' + digit;
119    number_length++;
120  }
121  // Exchange the digits.
122  int i = *length;
123  int j = *length + number_length - 1;
124  while (i < j) {
125    char tmp = buffer[i];
126    buffer[i] = buffer[j];
127    buffer[j] = tmp;
128    i++;
129    j--;
130  }
131  *length += number_length;
132}
133
134
135static void FillDigits64FixedLength(uint64_t number, int requested_length,
136                                    Vector<char> buffer, int* length) {
137  const uint32_t kTen7 = 10000000;
138  // For efficiency cut the number into 3 uint32_t parts, and print those.
139  uint32_t part2 = static_cast<uint32_t>(number % kTen7);
140  number /= kTen7;
141  uint32_t part1 = static_cast<uint32_t>(number % kTen7);
142  uint32_t part0 = static_cast<uint32_t>(number / kTen7);
143
144  FillDigits32FixedLength(part0, 3, buffer, length);
145  FillDigits32FixedLength(part1, 7, buffer, length);
146  FillDigits32FixedLength(part2, 7, buffer, length);
147}
148
149
150static void FillDigits64(uint64_t number, Vector<char> buffer, int* length) {
151  const uint32_t kTen7 = 10000000;
152  // For efficiency cut the number into 3 uint32_t parts, and print those.
153  uint32_t part2 = static_cast<uint32_t>(number % kTen7);
154  number /= kTen7;
155  uint32_t part1 = static_cast<uint32_t>(number % kTen7);
156  uint32_t part0 = static_cast<uint32_t>(number / kTen7);
157
158  if (part0 != 0) {
159    FillDigits32(part0, buffer, length);
160    FillDigits32FixedLength(part1, 7, buffer, length);
161    FillDigits32FixedLength(part2, 7, buffer, length);
162  } else if (part1 != 0) {
163    FillDigits32(part1, buffer, length);
164    FillDigits32FixedLength(part2, 7, buffer, length);
165  } else {
166    FillDigits32(part2, buffer, length);
167  }
168}
169
170
171static void RoundUp(Vector<char> buffer, int* length, int* decimal_point) {
172  // An empty buffer represents 0.
173  if (*length == 0) {
174    buffer[0] = '1';
175    *decimal_point = 1;
176    *length = 1;
177    return;
178  }
179  // Round the last digit until we either have a digit that was not '9' or until
180  // we reached the first digit.
181  buffer[(*length) - 1]++;
182  for (int i = (*length) - 1; i > 0; --i) {
183    if (buffer[i] != '0' + 10) {
184      return;
185    }
186    buffer[i] = '0';
187    buffer[i - 1]++;
188  }
189  // If the first digit is now '0' + 10, we would need to set it to '0' and add
190  // a '1' in front. However we reach the first digit only if all following
191  // digits had been '9' before rounding up. Now all trailing digits are '0' and
192  // we simply switch the first digit to '1' and update the decimal-point
193  // (indicating that the point is now one digit to the right).
194  if (buffer[0] == '0' + 10) {
195    buffer[0] = '1';
196    (*decimal_point)++;
197  }
198}
199
200
201// The given fractionals number represents a fixed-point number with binary
202// point at bit (-exponent).
203// Preconditions:
204//   -128 <= exponent <= 0.
205//   0 <= fractionals * 2^exponent < 1
206//   The buffer holds the result.
207// The function will round its result. During the rounding-process digits not
208// generated by this function might be updated, and the decimal-point variable
209// might be updated. If this function generates the digits 99 and the buffer
210// already contained "199" (thus yielding a buffer of "19999") then a
211// rounding-up will change the contents of the buffer to "20000".
212static void FillFractionals(uint64_t fractionals, int exponent,
213                            int fractional_count, Vector<char> buffer,
214                            int* length, int* decimal_point) {
215  DCHECK(-128 <= exponent && exponent <= 0);
216  // 'fractionals' is a fixed-point number, with binary point at bit
217  // (-exponent). Inside the function the non-converted remainder of fractionals
218  // is a fixed-point number, with binary point at bit 'point'.
219  if (-exponent <= 64) {
220    // One 64 bit number is sufficient.
221    DCHECK(fractionals >> 56 == 0);
222    int point = -exponent;
223    for (int i = 0; i < fractional_count; ++i) {
224      if (fractionals == 0) break;
225      // Instead of multiplying by 10 we multiply by 5 and adjust the point
226      // location. This way the fractionals variable will not overflow.
227      // Invariant at the beginning of the loop: fractionals < 2^point.
228      // Initially we have: point <= 64 and fractionals < 2^56
229      // After each iteration the point is decremented by one.
230      // Note that 5^3 = 125 < 128 = 2^7.
231      // Therefore three iterations of this loop will not overflow fractionals
232      // (even without the subtraction at the end of the loop body). At this
233      // time point will satisfy point <= 61 and therefore fractionals < 2^point
234      // and any further multiplication of fractionals by 5 will not overflow.
235      fractionals *= 5;
236      point--;
237      int digit = static_cast<int>(fractionals >> point);
238      buffer[*length] = '0' + digit;
239      (*length)++;
240      fractionals -= static_cast<uint64_t>(digit) << point;
241    }
242    // If the first bit after the point is set we have to round up.
243    if (((fractionals >> (point - 1)) & 1) == 1) {
244      RoundUp(buffer, length, decimal_point);
245    }
246  } else {  // We need 128 bits.
247    DCHECK(64 < -exponent && -exponent <= 128);
248    UInt128 fractionals128 = UInt128(fractionals, 0);
249    fractionals128.Shift(-exponent - 64);
250    int point = 128;
251    for (int i = 0; i < fractional_count; ++i) {
252      if (fractionals128.IsZero()) break;
253      // As before: instead of multiplying by 10 we multiply by 5 and adjust the
254      // point location.
255      // This multiplication will not overflow for the same reasons as before.
256      fractionals128.Multiply(5);
257      point--;
258      int digit = fractionals128.DivModPowerOf2(point);
259      buffer[*length] = '0' + digit;
260      (*length)++;
261    }
262    if (fractionals128.BitAt(point - 1) == 1) {
263      RoundUp(buffer, length, decimal_point);
264    }
265  }
266}
267
268
269// Removes leading and trailing zeros.
270// If leading zeros are removed then the decimal point position is adjusted.
271static void TrimZeros(Vector<char> buffer, int* length, int* decimal_point) {
272  while (*length > 0 && buffer[(*length) - 1] == '0') {
273    (*length)--;
274  }
275  int first_non_zero = 0;
276  while (first_non_zero < *length && buffer[first_non_zero] == '0') {
277    first_non_zero++;
278  }
279  if (first_non_zero != 0) {
280    for (int i = first_non_zero; i < *length; ++i) {
281      buffer[i - first_non_zero] = buffer[i];
282    }
283    *length -= first_non_zero;
284    *decimal_point -= first_non_zero;
285  }
286}
287
288
289bool FastFixedDtoa(double v,
290                   int fractional_count,
291                   Vector<char> buffer,
292                   int* length,
293                   int* decimal_point) {
294  const uint32_t kMaxUInt32 = 0xFFFFFFFF;
295  uint64_t significand = Double(v).Significand();
296  int exponent = Double(v).Exponent();
297  // v = significand * 2^exponent (with significand a 53bit integer).
298  // If the exponent is larger than 20 (i.e. we may have a 73bit number) then we
299  // don't know how to compute the representation. 2^73 ~= 9.5*10^21.
300  // If necessary this limit could probably be increased, but we don't need
301  // more.
302  if (exponent > 20) return false;
303  if (fractional_count > 20) return false;
304  *length = 0;
305  // At most kDoubleSignificandSize bits of the significand are non-zero.
306  // Given a 64 bit integer we have 11 0s followed by 53 potentially non-zero
307  // bits:  0..11*..0xxx..53*..xx
308  if (exponent + kDoubleSignificandSize > 64) {
309    // The exponent must be > 11.
310    //
311    // We know that v = significand * 2^exponent.
312    // And the exponent > 11.
313    // We simplify the task by dividing v by 10^17.
314    // The quotient delivers the first digits, and the remainder fits into a 64
315    // bit number.
316    // Dividing by 10^17 is equivalent to dividing by 5^17*2^17.
317    const uint64_t kFive17 = V8_2PART_UINT64_C(0xB1, A2BC2EC5);  // 5^17
318    uint64_t divisor = kFive17;
319    int divisor_power = 17;
320    uint64_t dividend = significand;
321    uint32_t quotient;
322    uint64_t remainder;
323    // Let v = f * 2^e with f == significand and e == exponent.
324    // Then need q (quotient) and r (remainder) as follows:
325    //   v            = q * 10^17       + r
326    //   f * 2^e      = q * 10^17       + r
327    //   f * 2^e      = q * 5^17 * 2^17 + r
328    // If e > 17 then
329    //   f * 2^(e-17) = q * 5^17        + r/2^17
330    // else
331    //   f  = q * 5^17 * 2^(17-e) + r/2^e
332    if (exponent > divisor_power) {
333      // We only allow exponents of up to 20 and therefore (17 - e) <= 3
334      dividend <<= exponent - divisor_power;
335      quotient = static_cast<uint32_t>(dividend / divisor);
336      remainder = (dividend % divisor) << divisor_power;
337    } else {
338      divisor <<= divisor_power - exponent;
339      quotient = static_cast<uint32_t>(dividend / divisor);
340      remainder = (dividend % divisor) << exponent;
341    }
342    FillDigits32(quotient, buffer, length);
343    FillDigits64FixedLength(remainder, divisor_power, buffer, length);
344    *decimal_point = *length;
345  } else if (exponent >= 0) {
346    // 0 <= exponent <= 11
347    significand <<= exponent;
348    FillDigits64(significand, buffer, length);
349    *decimal_point = *length;
350  } else if (exponent > -kDoubleSignificandSize) {
351    // We have to cut the number.
352    uint64_t integrals = significand >> -exponent;
353    uint64_t fractionals = significand - (integrals << -exponent);
354    if (integrals > kMaxUInt32) {
355      FillDigits64(integrals, buffer, length);
356    } else {
357      FillDigits32(static_cast<uint32_t>(integrals), buffer, length);
358    }
359    *decimal_point = *length;
360    FillFractionals(fractionals, exponent, fractional_count,
361                    buffer, length, decimal_point);
362  } else if (exponent < -128) {
363    // This configuration (with at most 20 digits) means that all digits must be
364    // 0.
365    DCHECK(fractional_count <= 20);
366    buffer[0] = '\0';
367    *length = 0;
368    *decimal_point = -fractional_count;
369  } else {
370    *decimal_point = 0;
371    FillFractionals(significand, exponent, fractional_count,
372                    buffer, length, decimal_point);
373  }
374  TrimZeros(buffer, length, decimal_point);
375  buffer[*length] = '\0';
376  if ((*length) == 0) {
377    // The string is empty and the decimal_point thus has no importance. Mimick
378    // Gay's dtoa and and set it to -fractional_count.
379    *decimal_point = -fractional_count;
380  }
381  return true;
382}
383
384} }  // namespace v8::internal
385