| 512 | } |
| 513 | |
| 514 | bool StringRef::getAsInteger(unsigned Radix, APInt &Result) const { |
| 515 | StringRef Str = *this; |
| 516 | |
| 517 | // Autosense radix if not specified. |
| 518 | if (Radix == 0) |
| 519 | Radix = GetAutoSenseRadix(Str); |
| 520 | |
| 521 | assert(Radix > 1 && Radix <= 36); |
| 522 | |
| 523 | // Empty strings (after the radix autosense) are invalid. |
| 524 | if (Str.empty()) return true; |
| 525 | |
| 526 | // Skip leading zeroes. This can be a significant improvement if |
| 527 | // it means we don't need > 64 bits. |
| 528 | while (!Str.empty() && Str.front() == '0') |
| 529 | Str = Str.substr(1); |
| 530 | |
| 531 | // If it was nothing but zeroes.... |
| 532 | if (Str.empty()) { |
| 533 | Result = APInt(64, 0); |
| 534 | return false; |
| 535 | } |
| 536 | |
| 537 | // (Over-)estimate the required number of bits. |
| 538 | unsigned Log2Radix = 0; |
| 539 | while ((1U << Log2Radix) < Radix) Log2Radix++; |
| 540 | bool IsPowerOf2Radix = ((1U << Log2Radix) == Radix); |
| 541 | |
| 542 | unsigned BitWidth = Log2Radix * Str.size(); |
| 543 | if (BitWidth < Result.getBitWidth()) |
| 544 | BitWidth = Result.getBitWidth(); // don't shrink the result |
| 545 | else if (BitWidth > Result.getBitWidth()) |
| 546 | Result = Result.zext(BitWidth); |
| 547 | |
| 548 | APInt RadixAP, CharAP; // unused unless !IsPowerOf2Radix |
| 549 | if (!IsPowerOf2Radix) { |
| 550 | // These must have the same bit-width as Result. |
| 551 | RadixAP = APInt(BitWidth, Radix); |
| 552 | CharAP = APInt(BitWidth, 0); |
| 553 | } |
| 554 | |
| 555 | // Parse all the bytes of the string given this radix. |
| 556 | Result = 0; |
| 557 | while (!Str.empty()) { |
| 558 | unsigned CharVal; |
| 559 | if (Str[0] >= '0' && Str[0] <= '9') |
| 560 | CharVal = Str[0]-'0'; |
| 561 | else if (Str[0] >= 'a' && Str[0] <= 'z') |
| 562 | CharVal = Str[0]-'a'+10; |
| 563 | else if (Str[0] >= 'A' && Str[0] <= 'Z') |
| 564 | CharVal = Str[0]-'A'+10; |
| 565 | else |
| 566 | return true; |
| 567 | |
| 568 | // If the parsed value is larger than the integer radix, the string is |
| 569 | // invalid. |
| 570 | if (CharVal >= Radix) |
| 571 | return true; |
no test coverage detected