Line data Source code
1 : // Copyright 2012 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 "src/strtod.h"
6 :
7 : #include <stdarg.h>
8 : #include <cmath>
9 :
10 : #include "src/bignum.h"
11 : #include "src/cached-powers.h"
12 : #include "src/double.h"
13 : #include "src/globals.h"
14 : #include "src/utils.h"
15 :
16 : namespace v8 {
17 : namespace internal {
18 :
19 : // 2^53 = 9007199254740992.
20 : // Any integer with at most 15 decimal digits will hence fit into a double
21 : // (which has a 53bit significand) without loss of precision.
22 : static const int kMaxExactDoubleIntegerDecimalDigits = 15;
23 : // 2^64 = 18446744073709551616 > 10^19
24 : static const int kMaxUint64DecimalDigits = 19;
25 :
26 : // Max double: 1.7976931348623157 x 10^308
27 : // Min non-zero double: 4.9406564584124654 x 10^-324
28 : // Any x >= 10^309 is interpreted as +infinity.
29 : // Any x <= 10^-324 is interpreted as 0.
30 : // Note that 2.5e-324 (despite being smaller than the min double) will be read
31 : // as non-zero (equal to the min non-zero double).
32 : static const int kMaxDecimalPower = 309;
33 : static const int kMinDecimalPower = -324;
34 :
35 : // 2^64 = 18446744073709551616
36 : static const uint64_t kMaxUint64 = V8_2PART_UINT64_C(0xFFFFFFFF, FFFFFFFF);
37 :
38 :
39 : static const double exact_powers_of_ten[] = {
40 : 1.0, // 10^0
41 : 10.0,
42 : 100.0,
43 : 1000.0,
44 : 10000.0,
45 : 100000.0,
46 : 1000000.0,
47 : 10000000.0,
48 : 100000000.0,
49 : 1000000000.0,
50 : 10000000000.0, // 10^10
51 : 100000000000.0,
52 : 1000000000000.0,
53 : 10000000000000.0,
54 : 100000000000000.0,
55 : 1000000000000000.0,
56 : 10000000000000000.0,
57 : 100000000000000000.0,
58 : 1000000000000000000.0,
59 : 10000000000000000000.0,
60 : 100000000000000000000.0, // 10^20
61 : 1000000000000000000000.0,
62 : // 10^22 = 0x21e19e0c9bab2400000 = 0x878678326eac9 * 2^22
63 : 10000000000000000000000.0
64 : };
65 : static const int kExactPowersOfTenSize = arraysize(exact_powers_of_ten);
66 :
67 : // Maximum number of significant digits in the decimal representation.
68 : // In fact the value is 772 (see conversions.cc), but to give us some margin
69 : // we round up to 780.
70 : static const int kMaxSignificantDecimalDigits = 780;
71 :
72 : static Vector<const char> TrimLeadingZeros(Vector<const char> buffer) {
73 3572705 : for (int i = 0; i < buffer.length(); i++) {
74 7142048 : if (buffer[i] != '0') {
75 3569557 : return buffer.SubVector(i, buffer.length());
76 : }
77 : }
78 : return Vector<const char>(buffer.start(), 0);
79 : }
80 :
81 :
82 : static Vector<const char> TrimTrailingZeros(Vector<const char> buffer) {
83 3933363 : for (int i = buffer.length() - 1; i >= 0; --i) {
84 7866298 : if (buffer[i] != '0') {
85 3569557 : return buffer.SubVector(0, i + 1);
86 : }
87 : }
88 : return Vector<const char>(buffer.start(), 0);
89 : }
90 :
91 :
92 : static void TrimToMaxSignificantDigits(Vector<const char> buffer,
93 : int exponent,
94 : char* significant_buffer,
95 : int* significant_exponent) {
96 97375 : for (int i = 0; i < kMaxSignificantDecimalDigits - 1; ++i) {
97 194750 : significant_buffer[i] = buffer[i];
98 : }
99 : // The input buffer has been trimmed. Therefore the last digit must be
100 : // different from '0'.
101 : DCHECK_NE(buffer[buffer.length() - 1], '0');
102 : // Set the last digit to be non-zero. This is sufficient to guarantee
103 : // correct rounding.
104 125 : significant_buffer[kMaxSignificantDecimalDigits - 1] = '1';
105 : *significant_exponent =
106 125 : exponent + (buffer.length() - kMaxSignificantDecimalDigits);
107 : }
108 :
109 :
110 : // Reads digits from the buffer and converts them to a uint64.
111 : // Reads in as many digits as fit into a uint64.
112 : // When the string starts with "1844674407370955161" no further digit is read.
113 : // Since 2^64 = 18446744073709551616 it would still be possible read another
114 : // digit if it was less or equal than 6, but this would complicate the code.
115 : static uint64_t ReadUint64(Vector<const char> buffer,
116 : int* number_of_read_digits) {
117 : uint64_t result = 0;
118 : int i = 0;
119 17262467 : while (i < buffer.length() && result <= (kMaxUint64 / 10 - 1)) {
120 27386496 : int digit = buffer[i++] - '0';
121 : DCHECK(0 <= digit && digit <= 9);
122 13693248 : result = 10 * result + digit;
123 : }
124 : *number_of_read_digits = i;
125 : return result;
126 : }
127 :
128 :
129 : // Reads a DiyFp from the buffer.
130 : // The returned DiyFp is not necessarily normalized.
131 : // If remaining_decimals is zero then the returned DiyFp is accurate.
132 : // Otherwise it has been rounded and has error of at most 1/2 ulp.
133 51654 : static void ReadDiyFp(Vector<const char> buffer,
134 : DiyFp* result,
135 : int* remaining_decimals) {
136 : int read_digits;
137 : uint64_t significand = ReadUint64(buffer, &read_digits);
138 51654 : if (buffer.length() == read_digits) {
139 45314 : *result = DiyFp(significand, 0);
140 45314 : *remaining_decimals = 0;
141 : } else {
142 : // Round the significand.
143 12680 : if (buffer[read_digits] >= '5') {
144 2455 : significand++;
145 : }
146 : // Compute the binary exponent.
147 : int exponent = 0;
148 6340 : *result = DiyFp(significand, exponent);
149 6340 : *remaining_decimals = buffer.length() - read_digits;
150 : }
151 51654 : }
152 :
153 :
154 3569219 : static bool DoubleStrtod(Vector<const char> trimmed,
155 : int exponent,
156 : double* result) {
157 : #if (V8_TARGET_ARCH_IA32 || defined(USE_SIMULATOR)) && !defined(_MSC_VER)
158 : // On x86 the floating-point stack can be 64 or 80 bits wide. If it is
159 : // 80 bits wide (as is the case on Linux) then double-rounding occurs and the
160 : // result is not accurate.
161 : // We know that Windows32 with MSVC, unlike with MinGW32, uses 64 bits and is
162 : // therefore accurate.
163 : // Note that the ARM and MIPS simulators are compiled for 32bits. They
164 : // therefore exhibit the same problem.
165 : return false;
166 : #endif
167 3569219 : if (trimmed.length() <= kMaxExactDoubleIntegerDecimalDigits) {
168 : int read_digits;
169 : // The trimmed input fits into a double.
170 : // If the 10^exponent (resp. 10^-exponent) fits into a double too then we
171 : // can compute the result-double simply by multiplying (resp. dividing) the
172 : // two numbers.
173 : // This is possible because IEEE guarantees that floating-point operations
174 : // return the best possible approximation.
175 3520307 : if (exponent < 0 && -exponent < kExactPowersOfTenSize) {
176 : // 10^-exponent fits into a double.
177 702514 : *result = static_cast<double>(ReadUint64(trimmed, &read_digits));
178 : DCHECK(read_digits == trimmed.length());
179 702514 : *result /= exact_powers_of_ten[-exponent];
180 702514 : return true;
181 : }
182 2817793 : if (0 <= exponent && exponent < kExactPowersOfTenSize) {
183 : // 10^exponent fits into a double.
184 2814501 : *result = static_cast<double>(ReadUint64(trimmed, &read_digits));
185 : DCHECK(read_digits == trimmed.length());
186 2814501 : *result *= exact_powers_of_ten[exponent];
187 2814501 : return true;
188 : }
189 : int remaining_digits =
190 3292 : kMaxExactDoubleIntegerDecimalDigits - trimmed.length();
191 6051 : if ((0 <= exponent) &&
192 2759 : (exponent - remaining_digits < kExactPowersOfTenSize)) {
193 : // The trimmed string was short and we can multiply it with
194 : // 10^remaining_digits. As a result the remaining exponent now fits
195 : // into a double too.
196 550 : *result = static_cast<double>(ReadUint64(trimmed, &read_digits));
197 : DCHECK(read_digits == trimmed.length());
198 550 : *result *= exact_powers_of_ten[remaining_digits];
199 550 : *result *= exact_powers_of_ten[exponent - remaining_digits];
200 550 : return true;
201 : }
202 : }
203 : return false;
204 : }
205 :
206 :
207 : // Returns 10^exponent as an exact DiyFp.
208 : // The given exponent must be in the range [1; kDecimalExponentDistance[.
209 50235 : static DiyFp AdjustmentPowerOfTen(int exponent) {
210 : DCHECK_LT(0, exponent);
211 : DCHECK_LT(exponent, PowersOfTenCache::kDecimalExponentDistance);
212 : // Simply hardcode the remaining powers for the given decimal exponent
213 : // distance.
214 : DCHECK_EQ(PowersOfTenCache::kDecimalExponentDistance, 8);
215 50235 : switch (exponent) {
216 7103 : case 1: return DiyFp(V8_2PART_UINT64_C(0xa0000000, 00000000), -60);
217 1105 : case 2: return DiyFp(V8_2PART_UINT64_C(0xc8000000, 00000000), -57);
218 2011 : case 3: return DiyFp(V8_2PART_UINT64_C(0xfa000000, 00000000), -54);
219 8189 : case 4: return DiyFp(V8_2PART_UINT64_C(0x9c400000, 00000000), -50);
220 21640 : case 5: return DiyFp(V8_2PART_UINT64_C(0xc3500000, 00000000), -47);
221 8588 : case 6: return DiyFp(V8_2PART_UINT64_C(0xf4240000, 00000000), -44);
222 1599 : case 7: return DiyFp(V8_2PART_UINT64_C(0x98968000, 00000000), -40);
223 : default:
224 0 : UNREACHABLE();
225 : }
226 : }
227 :
228 :
229 : // If the function returns true then the result is the correct double.
230 : // Otherwise it is either the correct double or the double that is just below
231 : // the correct double.
232 51654 : static bool DiyFpStrtod(Vector<const char> buffer,
233 : int exponent,
234 : double* result) {
235 : DiyFp input;
236 : int remaining_decimals;
237 51654 : ReadDiyFp(buffer, &input, &remaining_decimals);
238 : // Since we may have dropped some digits the input is not accurate.
239 : // If remaining_decimals is different than 0 than the error is at most
240 : // .5 ulp (unit in the last place).
241 : // We don't want to deal with fractions and therefore keep a common
242 : // denominator.
243 : const int kDenominatorLog = 3;
244 : const int kDenominator = 1 << kDenominatorLog;
245 : // Move the remaining decimals into the exponent.
246 51654 : exponent += remaining_decimals;
247 51654 : int64_t error = (remaining_decimals == 0 ? 0 : kDenominator / 2);
248 :
249 51654 : int old_e = input.e();
250 : input.Normalize();
251 51654 : error <<= old_e - input.e();
252 :
253 : DCHECK_LE(exponent, PowersOfTenCache::kMaxDecimalExponent);
254 51654 : if (exponent < PowersOfTenCache::kMinDecimalExponent) {
255 0 : *result = 0.0;
256 0 : return true;
257 : }
258 : DiyFp cached_power;
259 : int cached_decimal_exponent;
260 : PowersOfTenCache::GetCachedPowerForDecimalExponent(exponent,
261 : &cached_power,
262 51654 : &cached_decimal_exponent);
263 :
264 51654 : if (cached_decimal_exponent != exponent) {
265 50235 : int adjustment_exponent = exponent - cached_decimal_exponent;
266 50235 : DiyFp adjustment_power = AdjustmentPowerOfTen(adjustment_exponent);
267 50235 : input.Multiply(adjustment_power);
268 100470 : if (kMaxUint64DecimalDigits - buffer.length() >= adjustment_exponent) {
269 : // The product of input with the adjustment power fits into a 64 bit
270 : // integer.
271 : DCHECK_EQ(DiyFp::kSignificandSize, 64);
272 : } else {
273 : // The adjustment power is exact. There is hence only an error of 0.5.
274 40951 : error += kDenominator / 2;
275 : }
276 : }
277 :
278 51654 : input.Multiply(cached_power);
279 : // The error introduced by a multiplication of a*b equals
280 : // error_a + error_b + error_a*error_b/2^64 + 0.5
281 : // Substituting a with 'input' and b with 'cached_power' we have
282 : // error_b = 0.5 (all cached powers have an error of less than 0.5 ulp),
283 : // error_ab = 0 or 1 / kDenominator > error_a*error_b/ 2^64
284 : int error_b = kDenominator / 2;
285 51654 : int error_ab = (error == 0 ? 0 : 1); // We round up to 1.
286 : int fixed_error = kDenominator / 2;
287 51654 : error += error_b + error_ab + fixed_error;
288 :
289 51654 : old_e = input.e();
290 : input.Normalize();
291 51654 : error <<= old_e - input.e();
292 :
293 : // See if the double's significand changes if we add/subtract the error.
294 51654 : int order_of_magnitude = DiyFp::kSignificandSize + input.e();
295 : int effective_significand_size =
296 : Double::SignificandSizeForOrderOfMagnitude(order_of_magnitude);
297 : int precision_digits_count =
298 51654 : DiyFp::kSignificandSize - effective_significand_size;
299 51654 : if (precision_digits_count + kDenominatorLog >= DiyFp::kSignificandSize) {
300 : // This can only happen for very small denormals. In this case the
301 : // half-way multiplied by the denominator exceeds the range of an uint64.
302 : // Simply shift everything to the right.
303 : int shift_amount = (precision_digits_count + kDenominatorLog) -
304 90 : DiyFp::kSignificandSize + 1;
305 90 : input.set_f(input.f() >> shift_amount);
306 90 : input.set_e(input.e() + shift_amount);
307 : // We add 1 for the lost precision of error, and kDenominator for
308 : // the lost precision of input.f().
309 90 : error = (error >> shift_amount) + 1 + kDenominator;
310 : precision_digits_count -= shift_amount;
311 : }
312 : // We use uint64_ts now. This only works if the DiyFp uses uint64_ts too.
313 : DCHECK_EQ(DiyFp::kSignificandSize, 64);
314 : DCHECK_LT(precision_digits_count, 64);
315 : uint64_t one64 = 1;
316 51654 : uint64_t precision_bits_mask = (one64 << precision_digits_count) - 1;
317 51654 : uint64_t precision_bits = input.f() & precision_bits_mask;
318 51654 : uint64_t half_way = one64 << (precision_digits_count - 1);
319 51654 : precision_bits *= kDenominator;
320 51654 : half_way *= kDenominator;
321 : DiyFp rounded_input(input.f() >> precision_digits_count,
322 51654 : input.e() + precision_digits_count);
323 51654 : if (precision_bits >= half_way + error) {
324 25663 : rounded_input.set_f(rounded_input.f() + 1);
325 : }
326 : // If the last_bits are too close to the half-way case than we are too
327 : // inaccurate and round down. In this case we return false so that we can
328 : // fall back to a more precise algorithm.
329 :
330 51654 : *result = Double(rounded_input).value();
331 51654 : if (half_way - error < precision_bits && precision_bits < half_way + error) {
332 : // Too imprecise. The caller will have to fall back to a slower version.
333 : // However the returned number is guaranteed to be either the correct
334 : // double, or the next-lower double.
335 : return false;
336 : } else {
337 51381 : return true;
338 : }
339 : }
340 :
341 :
342 : // Returns the correct double for the buffer*10^exponent.
343 : // The variable guess should be a close guess that is either the correct double
344 : // or its lower neighbor (the nearest double less than the correct one).
345 : // Preconditions:
346 : // buffer.length() + exponent <= kMaxDecimalPower + 1
347 : // buffer.length() + exponent > kMinDecimalPower
348 : // buffer.length() <= kMaxDecimalSignificantDigits
349 273 : static double BignumStrtod(Vector<const char> buffer,
350 : int exponent,
351 : double guess) {
352 273 : if (guess == V8_INFINITY) {
353 : return guess;
354 : }
355 :
356 : DiyFp upper_boundary = Double(guess).UpperBoundary();
357 :
358 : DCHECK(buffer.length() + exponent <= kMaxDecimalPower + 1);
359 : DCHECK_GT(buffer.length() + exponent, kMinDecimalPower);
360 : DCHECK_LE(buffer.length(), kMaxSignificantDecimalDigits);
361 : // Make sure that the Bignum will be able to hold all our numbers.
362 : // Our Bignum implementation has a separate field for exponents. Shifts will
363 : // consume at most one bigit (< 64 bits).
364 : // ln(10) == 3.3219...
365 : DCHECK_LT((kMaxDecimalPower + 1) * 333 / 100, Bignum::kMaxSignificantBits);
366 273 : Bignum input;
367 273 : Bignum boundary;
368 273 : input.AssignDecimalString(buffer);
369 273 : boundary.AssignUInt64(upper_boundary.f());
370 273 : if (exponent >= 0) {
371 98 : input.MultiplyByPowerOfTen(exponent);
372 : } else {
373 175 : boundary.MultiplyByPowerOfTen(-exponent);
374 : }
375 273 : if (upper_boundary.e() > 0) {
376 134 : boundary.ShiftLeft(upper_boundary.e());
377 : } else {
378 139 : input.ShiftLeft(-upper_boundary.e());
379 : }
380 273 : int comparison = Bignum::Compare(input, boundary);
381 273 : if (comparison < 0) {
382 : return guess;
383 202 : } else if (comparison > 0) {
384 102 : return Double(guess).NextDouble();
385 100 : } else if ((Double(guess).Significand() & 1) == 0) {
386 : // Round towards even.
387 : return guess;
388 : } else {
389 54 : return Double(guess).NextDouble();
390 : }
391 : }
392 :
393 :
394 3569771 : double Strtod(Vector<const char> buffer, int exponent) {
395 : Vector<const char> left_trimmed = TrimLeadingZeros(buffer);
396 : Vector<const char> trimmed = TrimTrailingZeros(left_trimmed);
397 3569771 : exponent += left_trimmed.length() - trimmed.length();
398 3569771 : if (trimmed.length() == 0) return 0.0;
399 3569557 : if (trimmed.length() > kMaxSignificantDecimalDigits) {
400 : char significant_buffer[kMaxSignificantDecimalDigits];
401 : int significant_exponent;
402 : TrimToMaxSignificantDigits(trimmed, exponent,
403 : significant_buffer, &significant_exponent);
404 : return Strtod(Vector<const char>(significant_buffer,
405 : kMaxSignificantDecimalDigits),
406 125 : significant_exponent);
407 : }
408 3569432 : if (exponent + trimmed.length() - 1 >= kMaxDecimalPower) return V8_INFINITY;
409 3569347 : if (exponent + trimmed.length() <= kMinDecimalPower) return 0.0;
410 :
411 : double guess;
412 3620873 : if (DoubleStrtod(trimmed, exponent, &guess) ||
413 51654 : DiyFpStrtod(trimmed, exponent, &guess)) {
414 3568946 : return guess;
415 : }
416 273 : return BignumStrtod(trimmed, exponent, guess);
417 : }
418 :
419 : } // namespace internal
420 : } // namespace v8
|