1 //===-- String to float conversion utils ------------------------*- 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 #ifndef LIBC_SRC_SUPPORT_STR_TO_FLOAT_H 10 #define LIBC_SRC_SUPPORT_STR_TO_FLOAT_H 11 12 #include "src/__support/FPUtil/FPBits.h" 13 #include "src/__support/ctype_utils.h" 14 #include "src/__support/detailed_powers_of_ten.h" 15 #include "src/__support/high_precision_decimal.h" 16 #include "src/__support/str_conv_utils.h" 17 #include "utils/CPP/Limits.h" 18 #include <errno.h> 19 20 namespace __llvm_libc { 21 namespace internal { 22 23 // Shifts right and rounds according to the following rules: 24 // 1) If the part being cut off is more than 2^(amountToShift - 1) then round 25 // up 26 // 2) If it is less than that number then round down 27 // 3) If it is exactly that number, then round so that the final number will be 28 // even 29 template <class T> 30 static inline T shiftRightAndRound(T numToShift, unsigned int amountToShift) { 31 T result = numToShift >> amountToShift; 32 T truncated = numToShift & ((1 << amountToShift) - 1); 33 34 if (truncated < (1 << (amountToShift - 1))) { 35 return result; 36 } else if (truncated > (1 << (amountToShift - 1))) { 37 return result + 1; 38 } else { 39 return result + (result & 1); // This rounds towards even. 40 } 41 } 42 43 template <class T> uint32_t leadingZeroes(T inputNumber) { 44 // TODO(michaelrj): investigate the portability of using something like 45 // __builtin_clz for specific types. 46 constexpr uint32_t bitsInT = sizeof(T) * 8; 47 if (inputNumber == 0) { 48 return bitsInT; 49 } 50 uint32_t curGuess = bitsInT / 2; 51 uint32_t rangeSize = bitsInT / 2; 52 // while either shifting by curGuess does not get rid of all of the bits or 53 // shifting by one less also gets rid of all of the bits then we have not 54 // found the first bit. 55 while (((inputNumber >> curGuess) > 0) || 56 ((inputNumber >> (curGuess - 1)) == 0)) { 57 // Binary search for the first set bit 58 rangeSize /= 2; 59 if (rangeSize == 0) { 60 break; 61 } 62 if ((inputNumber >> curGuess) > 0) { 63 curGuess += rangeSize; 64 } else { 65 curGuess -= rangeSize; 66 } 67 } 68 if (inputNumber >> curGuess > 0) { 69 curGuess++; 70 } 71 return bitsInT - curGuess; 72 } 73 74 static inline uint64_t low64(__uint128_t num) { 75 return static_cast<uint64_t>(num & 0xffffffffffffffff); 76 } 77 78 static inline uint64_t high64(__uint128_t num) { 79 return static_cast<uint64_t>(num >> 64); 80 } 81 82 // This Eisel-Lemire implementation is based on the algorithm described in the 83 // paper Number Parsing at a Gigabyte per Second, Software: Practice and 84 // Experience 51 (8), 2021 (https://arxiv.org/abs/2101.11408), as well as the 85 // description by Nigel Tao 86 // (https://nigeltao.github.io/blog/2020/eisel-lemire.html) and the golang 87 // implementation, also by Nigel Tao 88 // (https://github.com/golang/go/blob/release-branch.go1.16/src/strconv/eisel_lemire.go#L25) 89 // for some optimizations as well as handling 32 bit floats. 90 template <class T> 91 static inline bool 92 eiselLemire(typename fputil::FPBits<T>::UIntType mantissa, int32_t exp10, 93 typename fputil::FPBits<T>::UIntType *outputMantissa, 94 uint32_t *outputExp2) { 95 96 using BitsType = typename fputil::FPBits<T>::UIntType; 97 constexpr uint32_t BITS_IN_MANTISSA = sizeof(mantissa) * 8; 98 99 if (sizeof(T) > 8) { // This algorithm cannot handle anything longer than a 100 // double, so we skip straight to the fallback. 101 return false; 102 } 103 104 // Exp10 Range 105 if (exp10 < DETAILED_POWERS_OF_TEN_MIN_EXP_10 || 106 exp10 > DETAILED_POWERS_OF_TEN_MAX_EXP_10) { 107 return false; 108 } 109 110 // Normalization 111 uint32_t clz = leadingZeroes<BitsType>(mantissa); 112 mantissa <<= clz; 113 114 uint32_t exp2 = exp10ToExp2(exp10) + BITS_IN_MANTISSA + 115 fputil::FloatProperties<T>::exponentBias - clz; 116 117 // Multiplication 118 const uint64_t *powerOfTen = 119 DETAILED_POWERS_OF_TEN[exp10 - DETAILED_POWERS_OF_TEN_MIN_EXP_10]; 120 121 __uint128_t firstApprox = static_cast<__uint128_t>(mantissa) * 122 static_cast<__uint128_t>(powerOfTen[1]); 123 124 // Wider Approximation 125 __uint128_t finalApprox; 126 // The halfway constant is used to check if the bits that will be shifted away 127 // intially are all 1. For doubles this is 64 (bitstype size) - 52 (final 128 // mantissa size) - 3 (we shift away the last two bits separately for 129 // accuracy, and the most significant bit is ignored.) = 9. Similarly, it's 6 130 // for floats in this case. 131 const uint64_t halfwayConstant = sizeof(T) == 8 ? 0x1FF : 0x3F; 132 if ((high64(firstApprox) & halfwayConstant) == halfwayConstant && 133 low64(firstApprox) + mantissa < mantissa) { 134 __uint128_t lowBits = static_cast<__uint128_t>(mantissa) * 135 static_cast<__uint128_t>(powerOfTen[0]); 136 __uint128_t secondApprox = 137 firstApprox + static_cast<__uint128_t>(high64(lowBits)); 138 139 if ((high64(secondApprox) & halfwayConstant) == halfwayConstant && 140 low64(secondApprox) + 1 == 0 && low64(lowBits) + mantissa < mantissa) { 141 return false; 142 } 143 finalApprox = secondApprox; 144 } else { 145 finalApprox = firstApprox; 146 } 147 148 // Shifting to 54 bits for doubles and 25 bits for floats 149 BitsType msb = high64(finalApprox) >> (BITS_IN_MANTISSA - 1); 150 BitsType finalMantissa = 151 high64(finalApprox) >> (msb + BITS_IN_MANTISSA - 152 (fputil::FloatProperties<T>::mantissaWidth + 3)); 153 exp2 -= 1 ^ msb; // same as !msb 154 155 // Half-way ambiguity 156 if (low64(finalApprox) == 0 && (high64(finalApprox) & halfwayConstant) == 0 && 157 (finalMantissa & 3) == 1) { 158 return false; 159 } 160 161 // From 54 to 53 bits for doubles and 25 to 24 bits for floats 162 finalMantissa += finalMantissa & 1; 163 finalMantissa >>= 1; 164 if ((finalMantissa >> (fputil::FloatProperties<T>::mantissaWidth + 1)) > 0) { 165 finalMantissa >>= 1; 166 ++exp2; 167 } 168 169 // The if block is equivalent to (but has fewer branches than): 170 // if exp2 <= 0 || exp2 >= 0x7FF { etc } 171 if (exp2 - 1 >= (1 << fputil::FloatProperties<T>::exponentWidth) - 2) { 172 return false; 173 } 174 175 *outputMantissa = finalMantissa; 176 *outputExp2 = exp2; 177 return true; 178 } 179 180 // The nth item in POWERS_OF_TWO represents the greatest power of two less than 181 // 10^n. This tells us how much we can safely shift without overshooting. 182 constexpr uint8_t POWERS_OF_TWO[19] = { 183 0, 3, 6, 9, 13, 16, 19, 23, 26, 29, 33, 36, 39, 43, 46, 49, 53, 56, 59, 184 }; 185 constexpr int32_t NUM_POWERS_OF_TWO = 186 sizeof(POWERS_OF_TWO) / sizeof(POWERS_OF_TWO[0]); 187 188 // Takes a mantissa and base 10 exponent and converts it into its closest 189 // floating point type T equivalent. This is the fallback algorithm used when 190 // the Eisel-Lemire algorithm fails, it's slower but more accurate. It's based 191 // on the Simple Decimal Conversion algorithm by Nigel Tao, described at this 192 // link: https://nigeltao.github.io/blog/2020/parse-number-f64-simple.html 193 template <class T> 194 static inline void 195 simpleDecimalConversion(const char *__restrict numStart, 196 typename fputil::FPBits<T>::UIntType *outputMantissa, 197 uint32_t *outputExp2) { 198 199 int32_t exp2 = 0; 200 HighPrecsisionDecimal hpd = HighPrecsisionDecimal(numStart); 201 202 if (hpd.getNumDigits() == 0) { 203 *outputMantissa = 0; 204 *outputExp2 = 0; 205 return; 206 } 207 208 // If the exponent is too large and can't be represented in this size of 209 // float, return inf. 210 if (hpd.getDecimalPoint() > 0 && 211 exp10ToExp2(hpd.getDecimalPoint() - 1) > 212 static_cast<int32_t>(fputil::FloatProperties<T>::exponentBias)) { 213 *outputMantissa = 0; 214 *outputExp2 = fputil::FPBits<T>::maxExponent; 215 errno = ERANGE; // NOLINT 216 return; 217 } 218 // If the exponent is too small even for a subnormal, return 0. 219 if (hpd.getDecimalPoint() < 0 && 220 exp10ToExp2(-hpd.getDecimalPoint()) > 221 static_cast<int32_t>(fputil::FloatProperties<T>::exponentBias + 222 fputil::FloatProperties<T>::mantissaWidth)) { 223 *outputMantissa = 0; 224 *outputExp2 = 0; 225 errno = ERANGE; // NOLINT 226 return; 227 } 228 229 // Right shift until the number is smaller than 1. 230 while (hpd.getDecimalPoint() > 0) { 231 int32_t shiftAmount = 0; 232 if (hpd.getDecimalPoint() >= NUM_POWERS_OF_TWO) { 233 shiftAmount = 60; 234 } else { 235 shiftAmount = POWERS_OF_TWO[hpd.getDecimalPoint()]; 236 } 237 exp2 += shiftAmount; 238 hpd.shift(-shiftAmount); 239 } 240 241 // Left shift until the number is between 1/2 and 1 242 while (hpd.getDecimalPoint() < 0 || 243 (hpd.getDecimalPoint() == 0 && hpd.getDigits()[0] < 5)) { 244 int32_t shiftAmount = 0; 245 246 if (-hpd.getDecimalPoint() >= NUM_POWERS_OF_TWO) { 247 shiftAmount = 60; 248 } else if (hpd.getDecimalPoint() != 0) { 249 shiftAmount = POWERS_OF_TWO[-hpd.getDecimalPoint()]; 250 } else { // This handles the case of the number being between .1 and .5 251 shiftAmount = 1; 252 } 253 exp2 -= shiftAmount; 254 hpd.shift(shiftAmount); 255 } 256 257 // Left shift once so that the number is between 1 and 2 258 --exp2; 259 hpd.shift(1); 260 261 // Get the biased exponent 262 exp2 += fputil::FloatProperties<T>::exponentBias; 263 264 // Handle the exponent being too large (and return inf). 265 if (exp2 >= fputil::FPBits<T>::maxExponent) { 266 *outputMantissa = 0; 267 *outputExp2 = fputil::FPBits<T>::maxExponent; 268 errno = ERANGE; // NOLINT 269 return; 270 } 271 272 // Shift left to fill the mantissa 273 hpd.shift(fputil::FloatProperties<T>::mantissaWidth); 274 typename fputil::FPBits<T>::UIntType finalMantissa = 275 hpd.roundToIntegerType<typename fputil::FPBits<T>::UIntType>(); 276 277 // Handle subnormals 278 if (exp2 <= 0) { 279 // Shift right until there is a valid exponent 280 while (exp2 < 0) { 281 hpd.shift(-1); 282 ++exp2; 283 } 284 // Shift right one more time to compensate for the left shift to get it 285 // between 1 and 2. 286 hpd.shift(-1); 287 finalMantissa = 288 hpd.roundToIntegerType<typename fputil::FPBits<T>::UIntType>(); 289 290 // Check if by shifting right we've caused this to round to a normal number. 291 if ((finalMantissa >> fputil::FloatProperties<T>::mantissaWidth) != 0) { 292 ++exp2; 293 } 294 } 295 296 // Check if rounding added a bit, and shift down if that's the case. 297 if (finalMantissa == typename fputil::FPBits<T>::UIntType(2) 298 << fputil::FloatProperties<T>::mantissaWidth) { 299 finalMantissa >>= 1; 300 ++exp2; 301 } 302 303 *outputMantissa = finalMantissa; 304 *outputExp2 = exp2; 305 } 306 307 // Takes a mantissa and base 10 exponent and converts it into its closest 308 // floating point type T equivalient. First we try the Eisel-Lemire algorithm, 309 // then if that fails then we fall back to a more accurate algorithm for 310 // accuracy. The resulting mantissa and exponent are placed in outputMantissa 311 // and outputExp2. 312 template <class T> 313 static inline void 314 decimalExpToFloat(typename fputil::FPBits<T>::UIntType mantissa, int32_t exp10, 315 const char *__restrict numStart, bool truncated, 316 typename fputil::FPBits<T>::UIntType *outputMantissa, 317 uint32_t *outputExp2) { 318 319 // TODO: Implement Clinger's fast path, as well as other shortcuts here. 320 321 // Try Eisel-Lemire 322 if (eiselLemire<T>(mantissa, exp10, outputMantissa, outputExp2)) { 323 if (!truncated) { 324 return; 325 } 326 // If the mantissa is truncated, then the result may be off by the LSB, so 327 // check if rounding the mantissa up changes the result. If not, then it's 328 // safe, else use the fallback. 329 typename fputil::FPBits<T>::UIntType firstMantissa = *outputMantissa; 330 uint32_t firstExp2 = *outputExp2; 331 if (eiselLemire<T>(mantissa + 1, exp10, outputMantissa, outputExp2)) { 332 if (*outputMantissa == firstMantissa && *outputExp2 == firstExp2) { 333 return; 334 } 335 } 336 } 337 338 simpleDecimalConversion<T>(numStart, outputMantissa, outputExp2); 339 340 return; 341 } 342 343 // checks if the next 4 characters of the string pointer are the start of a 344 // hexadecimal floating point number. Does not advance the string pointer. 345 static inline bool is_float_hex_start(const char *__restrict src, 346 const char decimalPoint) { 347 if (!(*src == '0' && (*(src + 1) | 32) == 'x')) { 348 return false; 349 } 350 if (*(src + 2) == decimalPoint) { 351 return isalnum(*(src + 3)) && b36_char_to_int(*(src + 3)) < 16; 352 } else { 353 return isalnum(*(src + 2)) && b36_char_to_int(*(src + 2)) < 16; 354 } 355 } 356 357 // Takes a pointer to a string and a pointer to a string pointer. This function 358 // is used as the backend for all of the string to float functions. 359 template <class T> 360 static inline T strtofloatingpoint(const char *__restrict src, 361 char **__restrict strEnd) { 362 using BitsType = typename fputil::FPBits<T>::UIntType; 363 fputil::FPBits<T> result = fputil::FPBits<T>(); 364 const char *originalSrc = src; 365 bool seenDigit = false; 366 src = first_non_whitespace(src); 367 368 if (*src == '+' || *src == '-') { 369 if (*src == '-') { 370 result.setSign(true); 371 } 372 ++src; 373 } 374 375 static constexpr char DECIMAL_POINT = '.'; 376 static const char *INF_STRING = "infinity"; 377 static const char *NAN_STRING = "nan"; 378 379 bool truncated = false; 380 381 if (isdigit(*src) || *src == DECIMAL_POINT) { // regular number 382 int base = 10; 383 char exponentMarker = 'e'; 384 if (is_float_hex_start(src, DECIMAL_POINT)) { 385 base = 16; 386 src += 2; 387 exponentMarker = 'p'; 388 seenDigit = true; 389 } 390 const char *__restrict numStart = src; 391 bool afterDecimal = false; 392 393 BitsType mantissa = 0; 394 int32_t exponent = 0; 395 396 // The goal for the first step of parsing is to convert the number in src to 397 // the format mantissa * (base ^ exponent) 398 399 constexpr BitsType MANTISSA_MAX = 400 BitsType(1) << (fputil::FloatProperties<T>::mantissaWidth + 401 1); // The extra bit is to give space for the implicit 1 402 const BitsType BITSTYPE_MAX_DIV_BY_BASE = 403 __llvm_libc::cpp::NumericLimits<BitsType>::max() / base; 404 while ((isalnum(*src) || *src == DECIMAL_POINT) && 405 mantissa < BITSTYPE_MAX_DIV_BY_BASE) { 406 if (*src == DECIMAL_POINT && afterDecimal) { 407 break; // this means that *src points to a second decimal point, ending 408 // the number. 409 } else if (*src == DECIMAL_POINT) { 410 afterDecimal = true; 411 ++src; 412 continue; 413 } 414 int digit = b36_char_to_int(*src); 415 if (digit >= base) { 416 break; 417 } 418 419 mantissa = (mantissa * base) + digit; 420 seenDigit = true; 421 if (afterDecimal) { 422 --exponent; 423 } 424 425 ++src; 426 } 427 428 // The second loop is to run through the remaining digits after we've filled 429 // the mantissa. 430 while (isalnum(*src) || *src == DECIMAL_POINT) { 431 if (*src == DECIMAL_POINT && afterDecimal) { 432 break; // this means that *src points to a second decimal point, ending 433 // the number. 434 } else if (*src == DECIMAL_POINT) { 435 afterDecimal = true; 436 ++src; 437 continue; 438 } 439 int digit = b36_char_to_int(*src); 440 if (digit >= base) { 441 break; 442 } 443 444 if (digit > 0) { 445 truncated = true; 446 } 447 448 if (!afterDecimal) { 449 exponent++; 450 } 451 452 ++src; 453 } 454 455 // if our base is 16 then convert the exponent to base 2 456 if (base == 16) { 457 exponent *= 4; 458 } 459 460 if ((*src | 32) == exponentMarker) { 461 if (*(src + 1) == '+' || *(src + 1) == '-' || isdigit(*(src + 1))) { 462 ++src; 463 char *tempStrEnd; 464 int32_t add_to_exponent = strtointeger<int32_t>(src, &tempStrEnd, 10); 465 src += tempStrEnd - src; 466 exponent += add_to_exponent; 467 } 468 } 469 470 if (mantissa == 0) { // if we have a 0, then also 0 the exponent. 471 exponent = 0; 472 } else if (base == 16) { 473 474 // These two loops should normalize the number if we assume the decimal 475 // point is after the bit at mantissaWidth. 476 // For example if type T is a 32 bit float, this should result in a 477 // mantissa with its most significant 1 being at bit 23. 478 while (mantissa < (MANTISSA_MAX >> 1)) { 479 mantissa = mantissa << 1; 480 --exponent; 481 } 482 BitsType mantissaCopy = mantissa; 483 unsigned int amountToShift = 0; 484 while (mantissaCopy > MANTISSA_MAX) { 485 mantissaCopy = mantissaCopy >> 1; 486 ++amountToShift; 487 } 488 exponent += amountToShift; 489 mantissa = shiftRightAndRound(mantissa, amountToShift); 490 491 // Account for the fact that the mantissa represented an integer 492 // previously, but now represents the fractional part of a normalized 493 // number. 494 exponent += fputil::FloatProperties<T>::mantissaWidth; 495 496 int32_t biasedExponent = exponent + fputil::FPBits<T>::exponentBias; 497 if (biasedExponent <= 0) { 498 // handle subnormals here 499 500 // the most mantissa is currently normalized, meaning that the msb is 501 // one bit left of where the decimal point should go. 502 amountToShift = 1; 503 mantissaCopy = mantissa >> 1; 504 while (biasedExponent < 0 && mantissaCopy > 0) { 505 mantissaCopy = mantissaCopy >> 1; 506 ++amountToShift; 507 ++biasedExponent; 508 } 509 // If we cut off any bits to fit this number into a subnormal, then it's 510 // out of range for this size of float. 511 if ((mantissa & ((1 << amountToShift) - 1)) > 0) { 512 errno = ERANGE; // NOLINT 513 } 514 mantissa = shiftRightAndRound(mantissa, amountToShift); 515 if (mantissa == 0) { 516 biasedExponent = 0; 517 } 518 } else if (biasedExponent > result.maxExponent) { 519 // This indicates an overflow, so we make the result INF and set errno. 520 biasedExponent = result.maxExponent; 521 mantissa = 0; 522 errno = ERANGE; // NOLINT 523 } 524 525 result.setUnbiasedExponent(biasedExponent); 526 result.setMantissa(mantissa); 527 } else { // base is 10 528 BitsType outputMantissa = 0; 529 uint32_t outputExponent = 0; 530 decimalExpToFloat<T>(mantissa, exponent, numStart, truncated, 531 &outputMantissa, &outputExponent); 532 result.setMantissa(outputMantissa); 533 result.setUnbiasedExponent(outputExponent); 534 } 535 536 } else if ((*src | 32) == 'n') { // NaN 537 if ((src[1] | 32) == NAN_STRING[1] && (src[2] | 32) == NAN_STRING[2]) { 538 seenDigit = true; 539 src += 3; 540 BitsType NaNMantissa = 0; 541 if (*src == '(') { 542 char *tempSrc = 0; 543 if (isdigit(*(src + 1)) || *(src + 1) == ')') { 544 NaNMantissa = strtointeger<BitsType>(src + 1, &tempSrc, 0); 545 if (*tempSrc != ')') { 546 NaNMantissa = 0; 547 } else { 548 src = tempSrc + 1; 549 } 550 } 551 } 552 NaNMantissa |= fputil::FloatProperties<T>::quietNaNMask; 553 if (result.getSign()) { 554 result = fputil::FPBits<T>(result.buildNaN(NaNMantissa)); 555 result.setSign(true); 556 } else { 557 result.setSign(false); 558 result = fputil::FPBits<T>(result.buildNaN(NaNMantissa)); 559 } 560 } 561 } else if ((*src | 32) == 'i') { // INF 562 if ((src[1] | 32) == INF_STRING[1] && (src[2] | 32) == INF_STRING[2]) { 563 seenDigit = true; 564 if (result.getSign()) 565 result = result.negInf(); 566 else 567 result = result.inf(); 568 if ((src[3] | 32) == INF_STRING[3] && (src[4] | 32) == INF_STRING[4] && 569 (src[5] | 32) == INF_STRING[5] && (src[6] | 32) == INF_STRING[6] && 570 (src[7] | 32) == INF_STRING[7]) { 571 // if the string is "INFINITY" then strEnd needs to be set to src + 8. 572 src += 8; 573 } else { 574 src += 3; 575 } 576 } 577 } 578 if (!seenDigit) { // If there is nothing to actually parse, then return 0. 579 if (strEnd != nullptr) 580 *strEnd = const_cast<char *>(originalSrc); 581 return T(0); 582 } 583 584 if (strEnd != nullptr) 585 *strEnd = const_cast<char *>(src); 586 587 return T(result); 588 } 589 590 } // namespace internal 591 } // namespace __llvm_libc 592 593 #endif // LIBC_SRC_SUPPORT_STR_TO_FLOAT_H 594