1 //===-- APInt.cpp - Implement APInt class ---------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Sheng Zhou and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a class to represent arbitrary precision integral
13 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/APInt.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Support/MathExtras.h"
22 // A utility function for allocating memory, checking for allocation failures,
23 // and ensuring the contents is zeroed.
24 inline static uint64_t* getClearedMemory(uint32_t numWords) {
25 uint64_t * result = new uint64_t[numWords];
26 assert(result && "APInt memory allocation fails!");
27 memset(result, 0, numWords * sizeof(uint64_t));
31 // A utility function for allocating memory and checking for allocation failure.
32 inline static uint64_t* getMemory(uint32_t numWords) {
33 uint64_t * result = new uint64_t[numWords];
34 assert(result && "APInt memory allocation fails!");
38 APInt::APInt(uint32_t numBits, uint64_t val)
39 : BitWidth(numBits), pVal(0) {
40 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
41 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
43 VAL = val & (~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - BitWidth));
45 pVal = getClearedMemory(getNumWords());
50 APInt::APInt(uint32_t numBits, uint32_t numWords, uint64_t bigVal[])
51 : BitWidth(numBits), pVal(0) {
52 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
53 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
54 assert(bigVal && "Null pointer detected!");
56 VAL = bigVal[0] & (~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - BitWidth));
58 pVal = getMemory(getNumWords());
59 // Calculate the actual length of bigVal[].
60 uint32_t maxN = std::max<uint32_t>(numWords, getNumWords());
61 uint32_t minN = std::min<uint32_t>(numWords, getNumWords());
62 memcpy(pVal, bigVal, (minN - 1) * APINT_WORD_SIZE);
63 pVal[minN-1] = bigVal[minN-1] &
65 (APINT_BITS_PER_WORD - BitWidth % APINT_BITS_PER_WORD));
66 if (maxN == getNumWords())
67 memset(pVal+numWords, 0, (getNumWords() - numWords) * APINT_WORD_SIZE);
71 /// @brief Create a new APInt by translating the char array represented
73 APInt::APInt(uint32_t numbits, const char StrStart[], uint32_t slen,
75 : BitWidth(numbits), pVal(0) {
76 fromString(numbits, StrStart, slen, radix);
79 /// @brief Create a new APInt by translating the string represented
81 APInt::APInt(uint32_t numbits, const std::string& Val, uint8_t radix)
82 : BitWidth(numbits), pVal(0) {
83 assert(!Val.empty() && "String empty?");
84 fromString(numbits, Val.c_str(), Val.size(), radix);
87 /// @brief Copy constructor
88 APInt::APInt(const APInt& APIVal)
89 : BitWidth(APIVal.BitWidth), pVal(0) {
93 pVal = getMemory(getNumWords());
94 memcpy(pVal, APIVal.pVal, getNumWords() * APINT_WORD_SIZE);
99 if (!isSingleWord() && pVal)
103 /// @brief Copy assignment operator. Create a new object from the given
104 /// APInt one by initialization.
105 APInt& APInt::operator=(const APInt& RHS) {
106 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
110 memcpy(pVal, RHS.pVal, getNumWords() * APINT_WORD_SIZE);
114 /// @brief Assignment operator. Assigns a common case integer value to
116 APInt& APInt::operator=(uint64_t RHS) {
121 memset(pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
126 /// add_1 - This function adds a single "digit" integer, y, to the multiple
127 /// "digit" integer array, x[]. x[] is modified to reflect the addition and
128 /// 1 is returned if there is a carry out, otherwise 0 is returned.
129 /// @returns the carry of the addition.
130 static uint64_t add_1(uint64_t dest[],
131 uint64_t x[], uint32_t len,
133 for (uint32_t i = 0; i < len; ++i) {
145 /// @brief Prefix increment operator. Increments the APInt by one.
146 APInt& APInt::operator++() {
150 add_1(pVal, pVal, getNumWords(), 1);
155 /// sub_1 - This function subtracts a single "digit" (64-bit word), y, from
156 /// the multi-digit integer array, x[], propagating the borrowed 1 value until
157 /// no further borrowing is neeeded or it runs out of "digits" in x. The result
158 /// is 1 if "borrowing" exhausted the digits in x, or 0 if x was not exhausted.
159 /// In other words, if y > x then this function returns 1, otherwise 0.
160 static uint64_t sub_1(uint64_t x[], uint32_t len,
162 for (uint32_t i = 0; i < len; ++i) {
166 y = 1; // We have to "borrow 1" from next "digit"
168 y = 0; // No need to borrow
169 break; // Remaining digits are unchanged so exit early
175 /// @brief Prefix decrement operator. Decrements the APInt by one.
176 APInt& APInt::operator--() {
180 sub_1(pVal, getNumWords(), 1);
185 /// add - This function adds the integer array x[] by integer array
186 /// y[] and returns the carry.
187 static uint64_t add(uint64_t dest[], uint64_t x[],
188 uint64_t y[], uint32_t len) {
190 for (uint32_t i = 0; i< len; ++i) {
192 dest[i] = carry + y[i];
193 carry = carry < x[i] ? 1 : (dest[i] < carry ? 1 : 0);
198 /// @brief Addition assignment operator. Adds this APInt by the given APInt&
199 /// RHS and assigns the result to this APInt.
200 APInt& APInt::operator+=(const APInt& RHS) {
201 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
202 if (isSingleWord()) VAL += RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
204 if (RHS.isSingleWord()) add_1(pVal, pVal, getNumWords(), RHS.VAL);
206 if (getNumWords() <= RHS.getNumWords())
207 add(pVal, pVal, RHS.pVal, getNumWords());
209 uint64_t carry = add(pVal, pVal, RHS.pVal, RHS.getNumWords());
210 add_1(pVal + RHS.getNumWords(), pVal + RHS.getNumWords(),
211 getNumWords() - RHS.getNumWords(), carry);
219 /// sub - This function subtracts the integer array x[] by
220 /// integer array y[], and returns the borrow-out carry.
221 static uint64_t sub(uint64_t dest[], uint64_t x[],
222 uint64_t y[], uint32_t len) {
226 for (uint32_t i = 0; i < len; ++i) {
227 uint64_t Y = y[i], X = x[i];
238 /// @brief Subtraction assignment operator. Subtracts this APInt by the given
239 /// APInt &RHS and assigns the result to this APInt.
240 APInt& APInt::operator-=(const APInt& RHS) {
241 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
243 VAL -= RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
245 if (RHS.isSingleWord())
246 sub_1(pVal, getNumWords(), RHS.VAL);
248 if (RHS.getNumWords() < getNumWords()) {
249 uint64_t carry = sub(pVal, pVal, RHS.pVal, RHS.getNumWords());
250 sub_1(pVal + RHS.getNumWords(), getNumWords() - RHS.getNumWords(),
254 sub(pVal, pVal, RHS.pVal, getNumWords());
261 /// mul_1 - This function performs the multiplication operation on a
262 /// large integer (represented as an integer array) and a uint64_t integer.
263 /// @returns the carry of the multiplication.
264 static uint64_t mul_1(uint64_t dest[],
265 uint64_t x[], uint32_t len,
267 // Split y into high 32-bit part and low 32-bit part.
268 uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
269 uint64_t carry = 0, lx, hx;
270 for (uint32_t i = 0; i < len; ++i) {
271 lx = x[i] & 0xffffffffULL;
273 // hasCarry - A flag to indicate if has carry.
274 // hasCarry == 0, no carry
275 // hasCarry == 1, has carry
276 // hasCarry == 2, no carry and the calculation result == 0.
277 uint8_t hasCarry = 0;
278 dest[i] = carry + lx * ly;
279 // Determine if the add above introduces carry.
280 hasCarry = (dest[i] < carry) ? 1 : 0;
281 carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
282 // The upper limit of carry can be (2^32 - 1)(2^32 - 1) +
283 // (2^32 - 1) + 2^32 = 2^64.
284 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
286 carry += (lx * hy) & 0xffffffffULL;
287 dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
288 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) +
289 (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
295 /// mul - This function multiplies integer array x[] by integer array y[] and
296 /// stores the result into integer array dest[].
297 /// Note the array dest[]'s size should no less than xlen + ylen.
298 static void mul(uint64_t dest[], uint64_t x[], uint32_t xlen,
299 uint64_t y[], uint32_t ylen) {
300 dest[xlen] = mul_1(dest, x, xlen, y[0]);
302 for (uint32_t i = 1; i < ylen; ++i) {
303 uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
304 uint64_t carry = 0, lx, hx;
305 for (uint32_t j = 0; j < xlen; ++j) {
306 lx = x[j] & 0xffffffffULL;
308 // hasCarry - A flag to indicate if has carry.
309 // hasCarry == 0, no carry
310 // hasCarry == 1, has carry
311 // hasCarry == 2, no carry and the calculation result == 0.
312 uint8_t hasCarry = 0;
313 uint64_t resul = carry + lx * ly;
314 hasCarry = (resul < carry) ? 1 : 0;
315 carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
316 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
318 carry += (lx * hy) & 0xffffffffULL;
319 resul = (carry << 32) | (resul & 0xffffffffULL);
321 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
322 (carry >> 32) + (dest[i+j] < resul ? 1 : 0) +
323 ((lx * hy) >> 32) + hx * hy;
325 dest[i+xlen] = carry;
329 /// @brief Multiplication assignment operator. Multiplies this APInt by the
330 /// given APInt& RHS and assigns the result to this APInt.
331 APInt& APInt::operator*=(const APInt& RHS) {
332 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
333 if (isSingleWord()) VAL *= RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
335 // one-based first non-zero bit position.
336 uint32_t first = getActiveBits();
337 uint32_t xlen = !first ? 0 : whichWord(first - 1) + 1;
340 else if (RHS.isSingleWord())
341 mul_1(pVal, pVal, xlen, RHS.VAL);
343 first = RHS.getActiveBits();
344 uint32_t ylen = !first ? 0 : whichWord(first - 1) + 1;
346 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
349 uint64_t *dest = getMemory(xlen+ylen);
350 mul(dest, pVal, xlen, RHS.pVal, ylen);
351 memcpy(pVal, dest, ((xlen + ylen >= getNumWords()) ?
352 getNumWords() : xlen + ylen) * APINT_WORD_SIZE);
360 /// @brief Bitwise AND assignment operator. Performs bitwise AND operation on
361 /// this APInt and the given APInt& RHS, assigns the result to this APInt.
362 APInt& APInt::operator&=(const APInt& RHS) {
363 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
364 if (isSingleWord()) {
368 uint32_t numWords = getNumWords();
369 for (uint32_t i = 0; i < numWords; ++i)
370 pVal[i] &= RHS.pVal[i];
374 /// @brief Bitwise OR assignment operator. Performs bitwise OR operation on
375 /// this APInt and the given APInt& RHS, assigns the result to this APInt.
376 APInt& APInt::operator|=(const APInt& RHS) {
377 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
378 if (isSingleWord()) {
382 uint32_t numWords = getNumWords();
383 for (uint32_t i = 0; i < numWords; ++i)
384 pVal[i] |= RHS.pVal[i];
388 /// @brief Bitwise XOR assignment operator. Performs bitwise XOR operation on
389 /// this APInt and the given APInt& RHS, assigns the result to this APInt.
390 APInt& APInt::operator^=(const APInt& RHS) {
391 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
392 if (isSingleWord()) {
396 uint32_t numWords = getNumWords();
397 for (uint32_t i = 0; i < numWords; ++i)
398 pVal[i] ^= RHS.pVal[i];
402 /// @brief Bitwise AND operator. Performs bitwise AND operation on this APInt
403 /// and the given APInt& RHS.
404 APInt APInt::operator&(const APInt& RHS) const {
405 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
407 return APInt(getBitWidth(), VAL & RHS.VAL);
410 uint32_t numWords = getNumWords();
411 for (uint32_t i = 0; i < numWords; ++i)
412 Result.pVal[i] &= RHS.pVal[i];
416 /// @brief Bitwise OR operator. Performs bitwise OR operation on this APInt
417 /// and the given APInt& RHS.
418 APInt APInt::operator|(const APInt& RHS) const {
419 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
421 return APInt(getBitWidth(), VAL | RHS.VAL);
423 uint32_t numWords = getNumWords();
424 for (uint32_t i = 0; i < numWords; ++i)
425 Result.pVal[i] |= RHS.pVal[i];
429 /// @brief Bitwise XOR operator. Performs bitwise XOR operation on this APInt
430 /// and the given APInt& RHS.
431 APInt APInt::operator^(const APInt& RHS) const {
432 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
434 return APInt(getBitWidth(), VAL ^ RHS.VAL);
436 uint32_t numWords = getNumWords();
437 for (uint32_t i = 0; i < numWords; ++i)
438 Result.pVal[i] ^= RHS.pVal[i];
442 /// @brief Logical negation operator. Performs logical negation operation on
444 bool APInt::operator !() const {
448 for (uint32_t i = 0; i < getNumWords(); ++i)
454 /// @brief Multiplication operator. Multiplies this APInt by the given APInt&
456 APInt APInt::operator*(const APInt& RHS) const {
457 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
460 API.clearUnusedBits();
464 /// @brief Addition operator. Adds this APInt by the given APInt& RHS.
465 APInt APInt::operator+(const APInt& RHS) const {
466 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
469 API.clearUnusedBits();
473 /// @brief Subtraction operator. Subtracts this APInt by the given APInt& RHS
474 APInt APInt::operator-(const APInt& RHS) const {
475 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
481 /// @brief Array-indexing support.
482 bool APInt::operator[](uint32_t bitPosition) const {
483 return (maskBit(bitPosition) & (isSingleWord() ?
484 VAL : pVal[whichWord(bitPosition)])) != 0;
487 /// @brief Equality operator. Compare this APInt with the given APInt& RHS
488 /// for the validity of the equality relationship.
489 bool APInt::operator==(const APInt& RHS) const {
490 uint32_t n1 = getActiveBits();
491 uint32_t n2 = RHS.getActiveBits();
492 if (n1 != n2) return false;
493 else if (isSingleWord())
494 return VAL == (RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0]);
496 if (n1 <= APINT_BITS_PER_WORD)
497 return pVal[0] == (RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0]);
498 for (int i = whichWord(n1 - 1); i >= 0; --i)
499 if (pVal[i] != RHS.pVal[i]) return false;
504 /// @brief Equality operator. Compare this APInt with the given uint64_t value
505 /// for the validity of the equality relationship.
506 bool APInt::operator==(uint64_t Val) const {
510 uint32_t n = getActiveBits();
511 if (n <= APINT_BITS_PER_WORD)
512 return pVal[0] == Val;
518 /// @brief Unsigned less than comparison
519 bool APInt::ult(const APInt& RHS) const {
520 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
522 return VAL < RHS.VAL;
524 uint32_t n1 = getActiveBits();
525 uint32_t n2 = RHS.getActiveBits();
530 else if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
531 return pVal[0] < RHS.pVal[0];
532 for (int i = whichWord(n1 - 1); i >= 0; --i) {
533 if (pVal[i] > RHS.pVal[i]) return false;
534 else if (pVal[i] < RHS.pVal[i]) return true;
540 /// @brief Signed less than comparison
541 bool APInt::slt(const APInt& RHS) const {
542 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
543 if (isSingleWord()) {
544 int64_t lhsSext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
545 int64_t rhsSext = (int64_t(RHS.VAL) << (64-BitWidth)) >> (64-BitWidth);
546 return lhsSext < rhsSext;
551 bool lhsNegative = false;
552 bool rhsNegative = false;
553 if (lhs[BitWidth-1]) {
558 if (rhs[BitWidth-1]) {
565 return !lhs.ult(rhs);
568 else if (rhsNegative)
574 /// Set the given bit to 1 whose poition is given as "bitPosition".
575 /// @brief Set a given bit to 1.
576 APInt& APInt::set(uint32_t bitPosition) {
577 if (isSingleWord()) VAL |= maskBit(bitPosition);
578 else pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
582 /// @brief Set every bit to 1.
583 APInt& APInt::set() {
585 VAL = ~0ULL >> (APINT_BITS_PER_WORD - BitWidth);
587 for (uint32_t i = 0; i < getNumWords() - 1; ++i)
589 pVal[getNumWords() - 1] = ~0ULL >>
590 (APINT_BITS_PER_WORD - BitWidth % APINT_BITS_PER_WORD);
595 /// Set the given bit to 0 whose position is given as "bitPosition".
596 /// @brief Set a given bit to 0.
597 APInt& APInt::clear(uint32_t bitPosition) {
599 VAL &= ~maskBit(bitPosition);
601 pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
605 /// @brief Set every bit to 0.
606 APInt& APInt::clear() {
610 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
614 /// @brief Bitwise NOT operator. Performs a bitwise logical NOT operation on
616 APInt APInt::operator~() const {
622 /// @brief Toggle every bit to its opposite value.
623 APInt& APInt::flip() {
624 if (isSingleWord()) VAL = (~(VAL <<
625 (APINT_BITS_PER_WORD - BitWidth))) >> (APINT_BITS_PER_WORD - BitWidth);
628 for (; i < getNumWords() - 1; ++i)
631 APINT_BITS_PER_WORD - (BitWidth - APINT_BITS_PER_WORD * (i - 1));
632 pVal[i] = (~(pVal[i] << offset)) >> offset;
637 /// Toggle a given bit to its opposite value whose position is given
638 /// as "bitPosition".
639 /// @brief Toggles a given bit to its opposite value.
640 APInt& APInt::flip(uint32_t bitPosition) {
641 assert(bitPosition < BitWidth && "Out of the bit-width range!");
642 if ((*this)[bitPosition]) clear(bitPosition);
643 else set(bitPosition);
647 /// getMaxValue - This function returns the largest value
648 /// for an APInt of the specified bit-width and if isSign == true,
649 /// it should be largest signed value, otherwise unsigned value.
650 APInt APInt::getMaxValue(uint32_t numBits, bool isSign) {
651 APInt Result(numBits, 0);
654 Result.clear(numBits - 1);
658 /// getMinValue - This function returns the smallest value for
659 /// an APInt of the given bit-width and if isSign == true,
660 /// it should be smallest signed value, otherwise zero.
661 APInt APInt::getMinValue(uint32_t numBits, bool isSign) {
662 APInt Result(numBits, 0);
664 Result.set(numBits - 1);
668 /// getAllOnesValue - This function returns an all-ones value for
669 /// an APInt of the specified bit-width.
670 APInt APInt::getAllOnesValue(uint32_t numBits) {
671 return getMaxValue(numBits, false);
674 /// getNullValue - This function creates an '0' value for an
675 /// APInt of the specified bit-width.
676 APInt APInt::getNullValue(uint32_t numBits) {
677 return getMinValue(numBits, false);
680 /// HiBits - This function returns the high "numBits" bits of this APInt.
681 APInt APInt::getHiBits(uint32_t numBits) const {
682 return APIntOps::lshr(*this, BitWidth - numBits);
685 /// LoBits - This function returns the low "numBits" bits of this APInt.
686 APInt APInt::getLoBits(uint32_t numBits) const {
687 return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits),
691 bool APInt::isPowerOf2() const {
692 return (!!*this) && !(*this & (*this - APInt(BitWidth,1)));
695 /// countLeadingZeros - This function is a APInt version corresponding to
696 /// llvm/include/llvm/Support/MathExtras.h's function
697 /// countLeadingZeros_{32, 64}. It performs platform optimal form of counting
698 /// the number of zeros from the most significant bit to the first one bit.
699 /// @returns numWord() * 64 if the value is zero.
700 uint32_t APInt::countLeadingZeros() const {
702 return CountLeadingZeros_64(VAL) - (APINT_BITS_PER_WORD - BitWidth);
704 for (uint32_t i = getNumWords(); i > 0u; --i) {
705 uint32_t tmp = CountLeadingZeros_64(pVal[i-1]);
707 if (tmp != APINT_BITS_PER_WORD)
708 if (i == getNumWords())
709 Count -= (APINT_BITS_PER_WORD - whichBit(BitWidth));
715 /// countTrailingZeros - This function is a APInt version corresponding to
716 /// llvm/include/llvm/Support/MathExtras.h's function
717 /// countTrailingZeros_{32, 64}. It performs platform optimal form of counting
718 /// the number of zeros from the least significant bit to the first one bit.
719 /// @returns numWord() * 64 if the value is zero.
720 uint32_t APInt::countTrailingZeros() const {
722 return CountTrailingZeros_64(VAL);
723 APInt Tmp( ~(*this) & ((*this) - APInt(BitWidth,1)) );
724 return getNumWords() * APINT_BITS_PER_WORD - Tmp.countLeadingZeros();
727 /// countPopulation - This function is a APInt version corresponding to
728 /// llvm/include/llvm/Support/MathExtras.h's function
729 /// countPopulation_{32, 64}. It counts the number of set bits in a value.
730 /// @returns 0 if the value is zero.
731 uint32_t APInt::countPopulation() const {
733 return CountPopulation_64(VAL);
735 for (uint32_t i = 0; i < getNumWords(); ++i)
736 Count += CountPopulation_64(pVal[i]);
741 /// byteSwap - This function returns a byte-swapped representation of the
743 APInt APInt::byteSwap() const {
744 assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
746 return APInt(BitWidth, ByteSwap_16(VAL));
747 else if (BitWidth == 32)
748 return APInt(BitWidth, ByteSwap_32(VAL));
749 else if (BitWidth == 48) {
750 uint64_t Tmp1 = ((VAL >> 32) << 16) | (VAL & 0xFFFF);
751 Tmp1 = ByteSwap_32(Tmp1);
752 uint64_t Tmp2 = (VAL >> 16) & 0xFFFF;
753 Tmp2 = ByteSwap_16(Tmp2);
756 (Tmp1 & 0xff) | ((Tmp1<<16) & 0xffff00000000ULL) | (Tmp2 << 16));
757 } else if (BitWidth == 64)
758 return APInt(BitWidth, ByteSwap_64(VAL));
760 APInt Result(BitWidth, 0);
761 char *pByte = (char*)Result.pVal;
762 for (uint32_t i = 0; i < BitWidth / APINT_WORD_SIZE / 2; ++i) {
764 pByte[i] = pByte[BitWidth / APINT_WORD_SIZE - 1 - i];
765 pByte[BitWidth / APINT_WORD_SIZE - i - 1] = Tmp;
771 /// GreatestCommonDivisor - This function returns the greatest common
772 /// divisor of the two APInt values using Enclid's algorithm.
773 APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1,
775 APInt A = API1, B = API2;
778 B = APIntOps::urem(A, B);
784 /// DoubleRoundToAPInt - This function convert a double value to
786 APInt llvm::APIntOps::RoundDoubleToAPInt(double Double) {
792 bool isNeg = T.I >> 63;
793 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
795 return APInt(64ull, 0u);
796 uint64_t mantissa = ((T.I << 12) >> 12) | (1ULL << 52);
798 return isNeg ? -APInt(64u, mantissa >> (52 - exp)) :
799 APInt(64u, mantissa >> (52 - exp));
800 APInt Tmp(exp + 1, mantissa);
801 Tmp = Tmp.shl(exp - 52);
802 return isNeg ? -Tmp : Tmp;
805 /// RoundToDouble - This function convert this APInt to a double.
806 /// The layout for double is as following (IEEE Standard 754):
807 /// --------------------------------------
808 /// | Sign Exponent Fraction Bias |
809 /// |-------------------------------------- |
810 /// | 1[63] 11[62-52] 52[51-00] 1023 |
811 /// --------------------------------------
812 double APInt::roundToDouble(bool isSigned) const {
814 // Handle the simple case where the value is contained in one uint64_t.
815 if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
817 int64_t sext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
823 // Determine if the value is negative.
824 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
826 // Construct the absolute value if we're negative.
827 APInt Tmp(isNeg ? -(*this) : (*this));
829 // Figure out how many bits we're using.
830 uint32_t n = Tmp.getActiveBits();
832 // The exponent (without bias normalization) is just the number of bits
833 // we are using. Note that the sign bit is gone since we constructed the
837 // Return infinity for exponent overflow
839 if (!isSigned || !isNeg)
840 return double(0x0.0p2047L); // positive infinity
842 return double(-0x0.0p2047L); // negative infinity
844 exp += 1023; // Increment for 1023 bias
846 // Number of bits in mantissa is 52. To obtain the mantissa value, we must
847 // extract the high 52 bits from the correct words in pVal.
849 unsigned hiWord = whichWord(n-1);
851 mantissa = Tmp.pVal[0];
853 mantissa >>= n - 52; // shift down, we want the top 52 bits.
855 assert(hiWord > 0 && "huh?");
856 uint64_t hibits = Tmp.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
857 uint64_t lobits = Tmp.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
858 mantissa = hibits | lobits;
861 // The leading bit of mantissa is implicit, so get rid of it.
862 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
867 T.I = sign | (exp << 52) | mantissa;
871 // Truncate to new width.
872 void APInt::trunc(uint32_t width) {
873 assert(width < BitWidth && "Invalid APInt Truncate request");
876 // Sign extend to a new width.
877 void APInt::sext(uint32_t width) {
878 assert(width > BitWidth && "Invalid APInt SignExtend request");
881 // Zero extend to a new width.
882 void APInt::zext(uint32_t width) {
883 assert(width > BitWidth && "Invalid APInt ZeroExtend request");
886 /// Arithmetic right-shift this APInt by shiftAmt.
887 /// @brief Arithmetic right-shift function.
888 APInt APInt::ashr(uint32_t shiftAmt) const {
890 if (API.isSingleWord())
892 (((int64_t(API.VAL) << (APINT_BITS_PER_WORD - API.BitWidth)) >>
893 (APINT_BITS_PER_WORD - API.BitWidth)) >> shiftAmt) &
894 (~uint64_t(0UL) >> (APINT_BITS_PER_WORD - API.BitWidth));
896 if (shiftAmt >= API.BitWidth) {
897 memset(API.pVal, API[API.BitWidth-1] ? 1 : 0,
898 (API.getNumWords()-1) * APINT_WORD_SIZE);
899 API.pVal[API.getNumWords() - 1] =
901 (APINT_BITS_PER_WORD - API.BitWidth % APINT_BITS_PER_WORD);
904 for (; i < API.BitWidth - shiftAmt; ++i)
909 for (; i < API.BitWidth; ++i)
910 if (API[API.BitWidth-1])
918 /// Logical right-shift this APInt by shiftAmt.
919 /// @brief Logical right-shift function.
920 APInt APInt::lshr(uint32_t shiftAmt) const {
922 if (API.isSingleWord())
923 API.VAL >>= shiftAmt;
925 if (shiftAmt >= API.BitWidth)
926 memset(API.pVal, 0, API.getNumWords() * APINT_WORD_SIZE);
928 for (i = 0; i < API.BitWidth - shiftAmt; ++i)
929 if (API[i+shiftAmt]) API.set(i);
931 for (; i < API.BitWidth; ++i)
937 /// Left-shift this APInt by shiftAmt.
938 /// @brief Left-shift function.
939 APInt APInt::shl(uint32_t shiftAmt) const {
941 if (API.isSingleWord())
942 API.VAL <<= shiftAmt;
943 else if (shiftAmt >= API.BitWidth)
944 memset(API.pVal, 0, API.getNumWords() * APINT_WORD_SIZE);
946 if (uint32_t offset = shiftAmt / APINT_BITS_PER_WORD) {
947 for (uint32_t i = API.getNumWords() - 1; i > offset - 1; --i)
948 API.pVal[i] = API.pVal[i-offset];
949 memset(API.pVal, 0, offset * APINT_WORD_SIZE);
951 shiftAmt %= APINT_BITS_PER_WORD;
953 for (i = API.getNumWords() - 1; i > 0; --i)
954 API.pVal[i] = (API.pVal[i] << shiftAmt) |
955 (API.pVal[i-1] >> (APINT_BITS_PER_WORD - shiftAmt));
956 API.pVal[i] <<= shiftAmt;
958 API.clearUnusedBits();
963 /// subMul - This function substracts x[len-1:0] * y from
964 /// dest[offset+len-1:offset], and returns the most significant
965 /// word of the product, minus the borrow-out from the subtraction.
966 static uint32_t subMul(uint32_t dest[], uint32_t offset,
967 uint32_t x[], uint32_t len, uint32_t y) {
968 uint64_t yl = (uint64_t) y & 0xffffffffL;
972 uint64_t prod = ((uint64_t) x[j] & 0xffffffffUL) * yl;
973 uint32_t prod_low = (uint32_t) prod;
974 uint32_t prod_high = (uint32_t) (prod >> 32);
976 carry = (prod_low < carry ? 1 : 0) + prod_high;
977 uint32_t x_j = dest[offset+j];
978 prod_low = x_j - prod_low;
979 if (prod_low > x_j) ++carry;
980 dest[offset+j] = prod_low;
985 /// unitDiv - This function divides N by D,
986 /// and returns (remainder << 32) | quotient.
987 /// Assumes (N >> 32) < D.
988 static uint64_t unitDiv(uint64_t N, uint32_t D) {
989 uint64_t q, r; // q: quotient, r: remainder.
990 uint64_t a1 = N >> 32; // a1: high 32-bit part of N.
991 uint64_t a0 = N & 0xffffffffL; // a0: low 32-bit part of N
992 if (a1 < ((D - a1 - (a0 >> 31)) & 0xffffffffL)) {
997 // Compute c1*2^32 + c0 = a1*2^32 + a0 - 2^31*d
998 uint64_t c = N - ((uint64_t) D << 31);
999 // Divide (c1*2^32 + c0) by d
1002 // Add 2^31 to quotient
1006 return (r << 32) | (q & 0xFFFFFFFFl);
1011 /// div - This is basically Knuth's formulation of the classical algorithm.
1012 /// Correspondance with Knuth's notation:
1013 /// Knuth's u[0:m+n] == zds[nx:0].
1014 /// Knuth's v[1:n] == y[ny-1:0]
1015 /// Knuth's n == ny.
1016 /// Knuth's m == nx-ny.
1017 /// Our nx == Knuth's m+n.
1018 /// Could be re-implemented using gmp's mpn_divrem:
1019 /// zds[nx] = mpn_divrem (&zds[ny], 0, zds, nx, y, ny).
1021 /// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
1022 /// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
1023 /// variables here have the same names as in the algorithm. Comments explain
1024 /// the algorithm and any deviation from it.
1025 static void KnuthDiv(uint32_t *u, uint32_t *v, uint32_t *q, uint32_t* r,
1026 uint32_t m, uint32_t n) {
1027 assert(u && "Must provide dividend");
1028 assert(v && "Must provide divisor");
1029 assert(q && "Must provide quotient");
1030 assert(n>1 && "n must be > 1");
1032 // Knuth uses the value b as the base of the number system. In our case b
1033 // is 2^31 so we just set it to -1u.
1034 uint64_t b = uint64_t(1) << 32;
1036 // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
1037 // u and v by d. Note that we have taken Knuth's advice here to use a power
1038 // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
1039 // 2 allows us to shift instead of multiply and it is easy to determine the
1040 // shift amount from the leading zeros. We are basically normalizing the u
1041 // and v so that its high bits are shifted to the top of v's range without
1042 // overflow. Note that this can require an extra word in u so that u must
1043 // be of length m+n+1.
1044 uint32_t shift = CountLeadingZeros_32(v[n-1]);
1045 uint32_t v_carry = 0;
1046 uint32_t u_carry = 0;
1048 for (uint32_t i = 0; i < m+n; ++i) {
1049 uint32_t u_tmp = u[i] >> (32 - shift);
1050 u[i] = (u[i] << shift) | u_carry;
1053 for (uint32_t i = 0; i < n; ++i) {
1054 uint32_t v_tmp = v[i] >> (32 - shift);
1055 v[i] = (v[i] << shift) | v_carry;
1061 // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
1064 // D3. [Calculate q'.].
1065 // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
1066 // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
1067 // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
1068 // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test
1069 // on v[n-2] determines at high speed most of the cases in which the trial
1070 // value qp is one too large, and it eliminates all cases where qp is two
1072 uint64_t qp = ((uint64_t(u[j+n]) << 32) | uint64_t(u[j+n-1])) / v[n-1];
1073 uint64_t rp = ((uint64_t(u[j+n]) << 32) | uint64_t(u[j+n-1])) % v[n-1];
1074 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1079 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1084 // D4. [Multiply and subtract.] Replace u with u - q*v (for each word).
1085 uint32_t borrow = 0;
1086 for (uint32_t i = 0; i < n; i++) {
1087 uint32_t save = u[j+i];
1088 u[j+i] = uint64_t(u[j+i]) - (qp * v[i]) - borrow;
1089 if (u[j+i] > save) {
1099 // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
1100 // negative, go to step D6; otherwise go on to step D7.
1103 // D6. [Add back]. The probability that this step is necessary is very
1104 // small, on the order of only 2/b. Make sure that test data accounts for
1105 // this possibility. Decreate qj by 1 and add v[...] to u[...]. A carry
1106 // will occur to the left of u[j+n], and it should be ignored since it
1107 // cancels with the borrow that occurred in D4.
1109 for (uint32_t i = 0; i < n; i++) {
1110 uint32_t save = u[j+i];
1111 u[j+i] += v[i] + carry;
1112 carry = u[j+i] < save;
1116 // D7. [Loop on j.] Decreate j by one. Now if j >= 0, go back to D3.
1120 // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
1121 // remainder may be obtained by dividing u[...] by d. If r is non-null we
1122 // compute the remainder (urem uses this).
1124 // The value d is expressed by the "shift" value above since we avoided
1125 // multiplication by d by using a shift left. So, all we have to do is
1126 // shift right here. In order to mak
1127 uint32_t mask = ~0u >> (32 - shift);
1129 for (int i = n-1; i >= 0; i--) {
1130 uint32_t save = u[i] & mask;
1131 r[i] = (u[i] >> shift) | carry;
1137 // This function makes calling KnuthDiv a little more convenient. It uses
1138 // APInt parameters instead of uint32_t* parameters. It can also divide APInt
1139 // values of different widths.
1140 void APInt::divide(const APInt LHS, uint32_t lhsWords,
1141 const APInt &RHS, uint32_t rhsWords,
1142 APInt *Quotient, APInt *Remainder)
1144 assert(lhsWords >= rhsWords && "Fractional result");
1146 // First, compose the values into an array of 32-bit words instead of
1147 // 64-bit words. This is a necessity of both the "short division" algorithm
1148 // and the the Knuth "classical algorithm" which requires there to be native
1149 // operations for +, -, and * on an m bit value with an m*2 bit result. We
1150 // can't use 64-bit operands here because we don't have native results of
1151 // 128-bits. Furthremore, casting the 64-bit values to 32-bit values won't
1152 // work on large-endian machines.
1153 uint64_t mask = ~0ull >> (sizeof(uint32_t)*8);
1154 uint32_t n = rhsWords * 2;
1155 uint32_t m = (lhsWords * 2) - n;
1156 // FIXME: allocate space on stack if m and n are sufficiently small.
1157 uint32_t *U = new uint32_t[m + n + 1];
1158 memset(U, 0, (m+n+1)*sizeof(uint32_t));
1159 for (unsigned i = 0; i < lhsWords; ++i) {
1160 uint64_t tmp = (lhsWords == 1 ? LHS.VAL : LHS.pVal[i]);
1161 U[i * 2] = tmp & mask;
1162 U[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1164 U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
1166 uint32_t *V = new uint32_t[n];
1167 memset(V, 0, (n)*sizeof(uint32_t));
1168 for (unsigned i = 0; i < rhsWords; ++i) {
1169 uint64_t tmp = (rhsWords == 1 ? RHS.VAL : RHS.pVal[i]);
1170 V[i * 2] = tmp & mask;
1171 V[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1174 // Set up the quotient and remainder
1175 uint32_t *Q = new uint32_t[m+n];
1176 memset(Q, 0, (m+n) * sizeof(uint32_t));
1179 R = new uint32_t[n];
1180 memset(R, 0, n * sizeof(uint32_t));
1183 // Now, adjust m and n for the Knuth division. n is the number of words in
1184 // the divisor. m is the number of words by which the dividend exceeds the
1185 // divisor (i.e. m+n is the length of the dividend). These sizes must not
1186 // contain any zero words or the Knuth algorithm fails.
1187 for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
1191 for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
1194 // If we're left with only a single word for the divisor, Knuth doesn't work
1195 // so we implement the short division algorithm here. This is much simpler
1196 // and faster because we are certain that we can divide a 64-bit quantity
1197 // by a 32-bit quantity at hardware speed and short division is simply a
1198 // series of such operations. This is just like doing short division but we
1199 // are using base 2^32 instead of base 10.
1200 assert(n != 0 && "Divide by zero?");
1202 uint32_t divisor = V[0];
1203 uint32_t remainder = 0;
1204 for (int i = m+n-1; i >= 0; i--) {
1205 uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i];
1206 if (partial_dividend == 0) {
1209 } else if (partial_dividend < divisor) {
1211 remainder = partial_dividend;
1212 } else if (partial_dividend == divisor) {
1216 Q[i] = partial_dividend / divisor;
1217 remainder = partial_dividend - (Q[i] * divisor);
1223 // Now we're ready to invoke the Knuth classical divide algorithm. In this
1225 KnuthDiv(U, V, Q, R, m, n);
1228 // If the caller wants the quotient
1230 // Set up the Quotient value's memory.
1231 if (Quotient->BitWidth != LHS.BitWidth) {
1232 if (Quotient->isSingleWord())
1235 delete Quotient->pVal;
1236 Quotient->BitWidth = LHS.BitWidth;
1237 if (!Quotient->isSingleWord())
1238 Quotient->pVal = getClearedMemory(lhsWords);
1242 // The quotient is in Q. Reconstitute the quotient into Quotient's low
1244 if (lhsWords == 1) {
1246 uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2));
1247 if (Quotient->isSingleWord())
1248 Quotient->VAL = tmp;
1250 Quotient->pVal[0] = tmp;
1252 assert(!Quotient->isSingleWord() && "Quotient APInt not large enough");
1253 for (unsigned i = 0; i < lhsWords; ++i)
1255 uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1259 // If the caller wants the remainder
1261 // Set up the Remainder value's memory.
1262 if (Remainder->BitWidth != RHS.BitWidth) {
1263 if (Remainder->isSingleWord())
1266 delete Remainder->pVal;
1267 Remainder->BitWidth = RHS.BitWidth;
1268 if (!Remainder->isSingleWord())
1269 Remainder->pVal = getClearedMemory(rhsWords);
1273 // The remainder is in R. Reconstitute the remainder into Remainder's low
1275 if (rhsWords == 1) {
1277 uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2));
1278 if (Remainder->isSingleWord())
1279 Remainder->VAL = tmp;
1281 Remainder->pVal[0] = tmp;
1283 assert(!Remainder->isSingleWord() && "Remainder APInt not large enough");
1284 for (unsigned i = 0; i < rhsWords; ++i)
1285 Remainder->pVal[i] =
1286 uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1290 // Clean up the memory we allocated.
1297 /// Unsigned divide this APInt by APInt RHS.
1298 /// @brief Unsigned division function for APInt.
1299 APInt APInt::udiv(const APInt& RHS) const {
1300 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1302 // First, deal with the easy case
1303 if (isSingleWord()) {
1304 assert(RHS.VAL != 0 && "Divide by zero?");
1305 return APInt(BitWidth, VAL / RHS.VAL);
1308 // Get some facts about the LHS and RHS number of bits and words
1309 uint32_t rhsBits = RHS.getActiveBits();
1310 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
1311 assert(rhsWords && "Divided by zero???");
1312 uint32_t lhsBits = this->getActiveBits();
1313 uint32_t lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
1315 // Make a temporary to hold the result
1316 APInt Result(*this);
1318 // Deal with some degenerate cases
1320 return Result; // 0 / X == 0
1321 else if (lhsWords < rhsWords || Result.ult(RHS)) {
1322 // X / Y with X < Y == 0
1323 memset(Result.pVal, 0, Result.getNumWords() * APINT_WORD_SIZE);
1325 } else if (Result == RHS) {
1327 memset(Result.pVal, 0, Result.getNumWords() * APINT_WORD_SIZE);
1330 } else if (lhsWords == 1 && rhsWords == 1) {
1331 // All high words are zero, just use native divide
1332 Result.pVal[0] /= RHS.pVal[0];
1336 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1337 APInt Quotient(1,0); // to hold result.
1338 divide(*this, lhsWords, RHS, rhsWords, &Quotient, 0);
1342 /// Unsigned remainder operation on APInt.
1343 /// @brief Function for unsigned remainder operation.
1344 APInt APInt::urem(const APInt& RHS) const {
1345 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1346 if (isSingleWord()) {
1347 assert(RHS.VAL != 0 && "Remainder by zero?");
1348 return APInt(BitWidth, VAL % RHS.VAL);
1351 // Make a temporary to hold the result
1352 APInt Result(*this);
1354 // Get some facts about the RHS
1355 uint32_t rhsBits = RHS.getActiveBits();
1356 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
1357 assert(rhsWords && "Performing remainder operation by zero ???");
1359 // Get some facts about the LHS
1360 uint32_t lhsBits = Result.getActiveBits();
1361 uint32_t lhsWords = !lhsBits ? 0 : (Result.whichWord(lhsBits - 1) + 1);
1363 // Check the degenerate cases
1364 if (lhsWords == 0) {
1366 memset(Result.pVal, 0, Result.getNumWords() * APINT_WORD_SIZE);
1368 } else if (lhsWords < rhsWords || Result.ult(RHS)) {
1369 // X % Y == X iff X < Y
1371 } else if (Result == RHS) {
1373 memset(Result.pVal, 0, Result.getNumWords() * APINT_WORD_SIZE);
1375 } else if (lhsWords == 1) {
1376 // All high words are zero, just use native remainder
1377 Result.pVal[0] %= RHS.pVal[0];
1381 // We have to compute it the hard way. Invoke the Knute divide algorithm.
1382 APInt Remainder(1,0);
1383 divide(*this, lhsWords, RHS, rhsWords, 0, &Remainder);
1387 /// @brief Converts a char array into an integer.
1388 void APInt::fromString(uint32_t numbits, const char *StrStart, uint32_t slen,
1390 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1391 "Radix should be 2, 8, 10, or 16!");
1392 assert(StrStart && "String is null?");
1394 // If the radix is a power of 2, read the input
1395 // from most significant to least significant.
1396 if ((radix & (radix - 1)) == 0) {
1397 uint32_t nextBitPos = 0;
1398 uint32_t bits_per_digit = radix / 8 + 2;
1399 uint64_t resDigit = 0;
1400 BitWidth = slen * bits_per_digit;
1401 if (getNumWords() > 1)
1402 pVal = getMemory(getNumWords());
1403 for (int i = slen - 1; i >= 0; --i) {
1404 uint64_t digit = StrStart[i] - '0';
1405 resDigit |= digit << nextBitPos;
1406 nextBitPos += bits_per_digit;
1407 if (nextBitPos >= APINT_BITS_PER_WORD) {
1408 if (isSingleWord()) {
1412 pVal[size++] = resDigit;
1413 nextBitPos -= APINT_BITS_PER_WORD;
1414 resDigit = digit >> (bits_per_digit - nextBitPos);
1417 if (!isSingleWord() && size <= getNumWords())
1418 pVal[size] = resDigit;
1419 } else { // General case. The radix is not a power of 2.
1420 // For 10-radix, the max value of 64-bit integer is 18446744073709551615,
1421 // and its digits number is 20.
1422 const uint32_t chars_per_word = 20;
1423 if (slen < chars_per_word ||
1424 (slen == chars_per_word && // In case the value <= 2^64 - 1
1425 strcmp(StrStart, "18446744073709551615") <= 0)) {
1426 BitWidth = APINT_BITS_PER_WORD;
1427 VAL = strtoull(StrStart, 0, 10);
1428 } else { // In case the value > 2^64 - 1
1429 BitWidth = (slen / chars_per_word + 1) * APINT_BITS_PER_WORD;
1430 pVal = getClearedMemory(getNumWords());
1431 uint32_t str_pos = 0;
1432 while (str_pos < slen) {
1433 uint32_t chunk = slen - str_pos;
1434 if (chunk > chars_per_word - 1)
1435 chunk = chars_per_word - 1;
1436 uint64_t resDigit = StrStart[str_pos++] - '0';
1437 uint64_t big_base = radix;
1438 while (--chunk > 0) {
1439 resDigit = resDigit * radix + StrStart[str_pos++] - '0';
1447 carry = mul_1(pVal, pVal, size, big_base);
1448 carry += add_1(pVal, pVal, size, resDigit);
1451 if (carry) pVal[size++] = carry;
1457 /// to_string - This function translates the APInt into a string.
1458 std::string APInt::toString(uint8_t radix, bool wantSigned) const {
1459 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1460 "Radix should be 2, 8, 10, or 16!");
1461 static const char *digits[] = {
1462 "0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"
1465 uint32_t bits_used = getActiveBits();
1466 if (isSingleWord()) {
1468 const char *format = (radix == 10 ? (wantSigned ? "%lld" : "%llu") :
1469 (radix == 16 ? "%llX" : (radix == 8 ? "%llo" : 0)));
1472 int64_t sextVal = (int64_t(VAL) << (APINT_BITS_PER_WORD-BitWidth)) >>
1473 (APINT_BITS_PER_WORD-BitWidth);
1474 sprintf(buf, format, sextVal);
1476 sprintf(buf, format, VAL);
1481 uint32_t bit = v & 1;
1483 buf[bits_used] = digits[bit][0];
1492 uint64_t mask = radix - 1;
1493 uint32_t shift = (radix == 16 ? 4 : radix == 8 ? 3 : 1);
1494 uint32_t nibbles = APINT_BITS_PER_WORD / shift;
1495 for (uint32_t i = 0; i < getNumWords(); ++i) {
1496 uint64_t value = pVal[i];
1497 for (uint32_t j = 0; j < nibbles; ++j) {
1498 result.insert(0, digits[ value & mask ]);
1506 APInt divisor(4, radix);
1507 APInt zero(tmp.getBitWidth(), 0);
1508 size_t insert_at = 0;
1509 if (wantSigned && tmp[BitWidth-1]) {
1510 // They want to print the signed version and it is a negative value
1511 // Flip the bits and add one to turn it into the equivalent positive
1512 // value and put a '-' in the result.
1520 else while (tmp.ne(zero)) {
1522 divide(tmp, tmp.getNumWords(), divisor, divisor.getNumWords(), 0, &APdigit);
1523 uint32_t digit = APdigit.getValue();
1524 assert(digit < radix && "urem failed");
1525 result.insert(insert_at,digits[digit]);
1526 APInt tmp2(tmp.getBitWidth(), 0);
1527 divide(tmp, tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2, 0);