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"
27 // A utility function for allocating memory, checking for allocation failures,
28 // and ensuring the contents is zeroed.
29 inline static uint64_t* getClearedMemory(uint32_t numWords) {
30 uint64_t * result = new uint64_t[numWords];
31 assert(result && "APInt memory allocation fails!");
32 memset(result, 0, numWords * sizeof(uint64_t));
36 // A utility function for allocating memory and checking for allocation failure.
37 inline static uint64_t* getMemory(uint32_t numWords) {
38 uint64_t * result = new uint64_t[numWords];
39 assert(result && "APInt memory allocation fails!");
43 APInt::APInt(uint32_t numBits, uint64_t val)
44 : BitWidth(numBits), VAL(0) {
45 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
46 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
48 VAL = val & (~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - BitWidth));
50 pVal = getClearedMemory(getNumWords());
55 APInt::APInt(uint32_t numBits, uint32_t numWords, uint64_t bigVal[])
56 : BitWidth(numBits), VAL(0) {
57 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
58 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
59 assert(bigVal && "Null pointer detected!");
61 VAL = bigVal[0] & (~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - BitWidth));
63 pVal = getMemory(getNumWords());
64 // Calculate the actual length of bigVal[].
65 uint32_t maxN = std::max<uint32_t>(numWords, getNumWords());
66 uint32_t minN = std::min<uint32_t>(numWords, getNumWords());
67 memcpy(pVal, bigVal, (minN - 1) * APINT_WORD_SIZE);
68 pVal[minN-1] = bigVal[minN-1] &
70 (APINT_BITS_PER_WORD - BitWidth % APINT_BITS_PER_WORD));
71 if (maxN == getNumWords())
72 memset(pVal+numWords, 0, (getNumWords() - numWords) * APINT_WORD_SIZE);
76 /// @brief Create a new APInt by translating the char array represented
78 APInt::APInt(uint32_t numbits, const char StrStart[], uint32_t slen,
80 : BitWidth(numbits), VAL(0) {
81 fromString(numbits, StrStart, slen, radix);
84 /// @brief Create a new APInt by translating the string represented
86 APInt::APInt(uint32_t numbits, const std::string& Val, uint8_t radix)
87 : BitWidth(numbits), VAL(0) {
88 assert(!Val.empty() && "String empty?");
89 fromString(numbits, Val.c_str(), Val.size(), radix);
92 /// @brief Copy constructor
93 APInt::APInt(const APInt& that)
94 : BitWidth(that.BitWidth), VAL(0) {
98 pVal = getMemory(getNumWords());
99 memcpy(pVal, that.pVal, getNumWords() * APINT_WORD_SIZE);
104 if (!isSingleWord() && pVal)
108 /// @brief Copy assignment operator. Create a new object from the given
109 /// APInt one by initialization.
110 APInt& APInt::operator=(const APInt& RHS) {
111 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
115 memcpy(pVal, RHS.pVal, getNumWords() * APINT_WORD_SIZE);
119 /// @brief Assignment operator. Assigns a common case integer value to
121 APInt& APInt::operator=(uint64_t RHS) {
126 memset(pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
131 /// add_1 - This function adds a single "digit" integer, y, to the multiple
132 /// "digit" integer array, x[]. x[] is modified to reflect the addition and
133 /// 1 is returned if there is a carry out, otherwise 0 is returned.
134 /// @returns the carry of the addition.
135 static uint64_t add_1(uint64_t dest[],
136 uint64_t x[], uint32_t len,
138 for (uint32_t i = 0; i < len; ++i) {
150 /// @brief Prefix increment operator. Increments the APInt by one.
151 APInt& APInt::operator++() {
155 add_1(pVal, pVal, getNumWords(), 1);
160 /// sub_1 - This function subtracts a single "digit" (64-bit word), y, from
161 /// the multi-digit integer array, x[], propagating the borrowed 1 value until
162 /// no further borrowing is neeeded or it runs out of "digits" in x. The result
163 /// is 1 if "borrowing" exhausted the digits in x, or 0 if x was not exhausted.
164 /// In other words, if y > x then this function returns 1, otherwise 0.
165 static uint64_t sub_1(uint64_t x[], uint32_t len,
167 for (uint32_t i = 0; i < len; ++i) {
171 y = 1; // We have to "borrow 1" from next "digit"
173 y = 0; // No need to borrow
174 break; // Remaining digits are unchanged so exit early
180 /// @brief Prefix decrement operator. Decrements the APInt by one.
181 APInt& APInt::operator--() {
185 sub_1(pVal, getNumWords(), 1);
190 /// add - This function adds the integer array x[] by integer array
191 /// y[] and returns the carry.
192 static uint64_t add(uint64_t dest[], uint64_t x[], uint64_t y[], uint32_t len) {
194 for (uint32_t i = 0; i< len; ++i) {
195 dest[i] = x[i] + y[i] + carry;
196 uint64_t limit = std::min(x[i],y[i]);
197 carry = dest[i] < limit || (carry && dest[i] == limit);
202 /// @brief Addition assignment operator. Adds this APInt by the given APInt&
203 /// RHS and assigns the result to this APInt.
204 APInt& APInt::operator+=(const APInt& RHS) {
205 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
209 add(pVal, pVal, RHS.pVal, getNumWords());
215 /// sub - This function subtracts the integer array x[] by
216 /// integer array y[], and returns the borrow-out carry.
217 static uint64_t sub(uint64_t *dest, const uint64_t *x, const uint64_t *y,
220 for (uint32_t i = 0; i < len; ++i) {
221 uint64_t x_tmp = borrow ? x[i] - 1 : x[i];
222 borrow = y[i] > x_tmp || (borrow && x[i] == 0);
223 dest[i] = x_tmp - y[i];
228 /// @brief Subtraction assignment operator. Subtracts this APInt by the given
229 /// APInt &RHS and assigns the result to this APInt.
230 APInt& APInt::operator-=(const APInt& RHS) {
231 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
235 sub(pVal, pVal, RHS.pVal, getNumWords());
240 /// mul_1 - This function performs the multiplication operation on a
241 /// large integer (represented as an integer array) and a uint64_t integer.
242 /// @returns the carry of the multiplication.
243 static uint64_t mul_1(uint64_t dest[],
244 uint64_t x[], uint32_t len,
246 // Split y into high 32-bit part and low 32-bit part.
247 uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
248 uint64_t carry = 0, lx, hx;
249 for (uint32_t i = 0; i < len; ++i) {
250 lx = x[i] & 0xffffffffULL;
252 // hasCarry - A flag to indicate if has carry.
253 // hasCarry == 0, no carry
254 // hasCarry == 1, has carry
255 // hasCarry == 2, no carry and the calculation result == 0.
256 uint8_t hasCarry = 0;
257 dest[i] = carry + lx * ly;
258 // Determine if the add above introduces carry.
259 hasCarry = (dest[i] < carry) ? 1 : 0;
260 carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
261 // The upper limit of carry can be (2^32 - 1)(2^32 - 1) +
262 // (2^32 - 1) + 2^32 = 2^64.
263 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
265 carry += (lx * hy) & 0xffffffffULL;
266 dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
267 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) +
268 (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
274 /// mul - This function multiplies integer array x[] by integer array y[] and
275 /// stores the result into integer array dest[].
276 /// Note the array dest[]'s size should no less than xlen + ylen.
277 static void mul(uint64_t dest[], uint64_t x[], uint32_t xlen,
278 uint64_t y[], uint32_t ylen) {
279 dest[xlen] = mul_1(dest, x, xlen, y[0]);
281 for (uint32_t i = 1; i < ylen; ++i) {
282 uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
283 uint64_t carry = 0, lx, hx;
284 for (uint32_t j = 0; j < xlen; ++j) {
285 lx = x[j] & 0xffffffffULL;
287 // hasCarry - A flag to indicate if has carry.
288 // hasCarry == 0, no carry
289 // hasCarry == 1, has carry
290 // hasCarry == 2, no carry and the calculation result == 0.
291 uint8_t hasCarry = 0;
292 uint64_t resul = carry + lx * ly;
293 hasCarry = (resul < carry) ? 1 : 0;
294 carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
295 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
297 carry += (lx * hy) & 0xffffffffULL;
298 resul = (carry << 32) | (resul & 0xffffffffULL);
300 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
301 (carry >> 32) + (dest[i+j] < resul ? 1 : 0) +
302 ((lx * hy) >> 32) + hx * hy;
304 dest[i+xlen] = carry;
308 /// @brief Multiplication assignment operator. Multiplies this APInt by the
309 /// given APInt& RHS and assigns the result to this APInt.
310 APInt& APInt::operator*=(const APInt& RHS) {
311 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
315 // one-based first non-zero bit position.
316 uint32_t first = getActiveBits();
317 uint32_t xlen = !first ? 0 : whichWord(first - 1) + 1;
321 first = RHS.getActiveBits();
322 uint32_t ylen = !first ? 0 : whichWord(first - 1) + 1;
324 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
327 uint64_t *dest = getMemory(xlen+ylen);
328 mul(dest, pVal, xlen, RHS.pVal, ylen);
329 memcpy(pVal, dest, ((xlen + ylen >= getNumWords()) ?
330 getNumWords() : xlen + ylen) * APINT_WORD_SIZE);
338 /// @brief Bitwise AND assignment operator. Performs bitwise AND operation on
339 /// this APInt and the given APInt& RHS, assigns the result to this APInt.
340 APInt& APInt::operator&=(const APInt& RHS) {
341 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
342 if (isSingleWord()) {
346 uint32_t numWords = getNumWords();
347 for (uint32_t i = 0; i < numWords; ++i)
348 pVal[i] &= RHS.pVal[i];
352 /// @brief Bitwise OR assignment operator. Performs bitwise OR operation on
353 /// this APInt and the given APInt& RHS, assigns the result to this APInt.
354 APInt& APInt::operator|=(const APInt& RHS) {
355 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
356 if (isSingleWord()) {
360 uint32_t numWords = getNumWords();
361 for (uint32_t i = 0; i < numWords; ++i)
362 pVal[i] |= RHS.pVal[i];
366 /// @brief Bitwise XOR assignment operator. Performs bitwise XOR operation on
367 /// this APInt and the given APInt& RHS, assigns the result to this APInt.
368 APInt& APInt::operator^=(const APInt& RHS) {
369 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
370 if (isSingleWord()) {
372 this->clearUnusedBits();
375 uint32_t numWords = getNumWords();
376 for (uint32_t i = 0; i < numWords; ++i)
377 pVal[i] ^= RHS.pVal[i];
378 this->clearUnusedBits();
382 /// @brief Bitwise AND operator. Performs bitwise AND operation on this APInt
383 /// and the given APInt& RHS.
384 APInt APInt::operator&(const APInt& RHS) const {
385 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
387 return APInt(getBitWidth(), VAL & RHS.VAL);
390 uint32_t numWords = getNumWords();
391 for (uint32_t i = 0; i < numWords; ++i)
392 Result.pVal[i] &= RHS.pVal[i];
396 /// @brief Bitwise OR operator. Performs bitwise OR operation on this APInt
397 /// and the given APInt& RHS.
398 APInt APInt::operator|(const APInt& RHS) const {
399 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
401 return APInt(getBitWidth(), VAL | RHS.VAL);
404 uint32_t numWords = getNumWords();
405 for (uint32_t i = 0; i < numWords; ++i)
406 Result.pVal[i] |= RHS.pVal[i];
410 /// @brief Bitwise XOR operator. Performs bitwise XOR operation on this APInt
411 /// and the given APInt& RHS.
412 APInt APInt::operator^(const APInt& RHS) const {
413 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
414 if (isSingleWord()) {
415 APInt Result(BitWidth, VAL ^ RHS.VAL);
416 Result.clearUnusedBits();
420 uint32_t numWords = getNumWords();
421 for (uint32_t i = 0; i < numWords; ++i)
422 Result.pVal[i] ^= RHS.pVal[i];
426 /// @brief Logical negation operator. Performs logical negation operation on
428 bool APInt::operator !() const {
432 for (uint32_t i = 0; i < getNumWords(); ++i)
438 /// @brief Multiplication operator. Multiplies this APInt by the given APInt&
440 APInt APInt::operator*(const APInt& RHS) const {
441 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
442 if (isSingleWord()) {
443 APInt Result(BitWidth, VAL * RHS.VAL);
444 Result.clearUnusedBits();
449 Result.clearUnusedBits();
453 /// @brief Addition operator. Adds this APInt by the given APInt& RHS.
454 APInt APInt::operator+(const APInt& RHS) const {
455 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
456 if (isSingleWord()) {
457 APInt Result(BitWidth, VAL + RHS.VAL);
458 Result.clearUnusedBits();
461 APInt Result(BitWidth, 0);
462 add(Result.pVal, this->pVal, RHS.pVal, getNumWords());
463 Result.clearUnusedBits();
467 /// @brief Subtraction operator. Subtracts this APInt by the given APInt& RHS
468 APInt APInt::operator-(const APInt& RHS) const {
469 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
470 if (isSingleWord()) {
471 APInt Result(BitWidth, VAL - RHS.VAL);
472 Result.clearUnusedBits();
475 APInt Result(BitWidth, 0);
476 sub(Result.pVal, this->pVal, RHS.pVal, getNumWords());
477 Result.clearUnusedBits();
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 {
491 return VAL == RHS.VAL;
493 uint32_t n1 = getActiveBits();
494 uint32_t n2 = RHS.getActiveBits();
498 if (n1 <= APINT_BITS_PER_WORD)
499 return pVal[0] == RHS.pVal[0];
501 for (int i = whichWord(n1 - 1); i >= 0; --i)
502 if (pVal[i] != RHS.pVal[i])
507 /// @brief Equality operator. Compare this APInt with the given uint64_t value
508 /// for the validity of the equality relationship.
509 bool APInt::operator==(uint64_t Val) const {
513 uint32_t n = getActiveBits();
514 if (n <= APINT_BITS_PER_WORD)
515 return pVal[0] == Val;
520 /// @brief Unsigned less than comparison
521 bool APInt::ult(const APInt& RHS) const {
522 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
524 return VAL < RHS.VAL;
526 uint32_t n1 = getActiveBits();
527 uint32_t n2 = RHS.getActiveBits();
532 else if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
533 return pVal[0] < RHS.pVal[0];
534 for (int i = whichWord(n1 - 1); i >= 0; --i) {
535 if (pVal[i] > RHS.pVal[i]) return false;
536 else if (pVal[i] < RHS.pVal[i]) return true;
542 /// @brief Signed less than comparison
543 bool APInt::slt(const APInt& RHS) const {
544 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
545 if (isSingleWord()) {
546 int64_t lhsSext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
547 int64_t rhsSext = (int64_t(RHS.VAL) << (64-BitWidth)) >> (64-BitWidth);
548 return lhsSext < rhsSext;
553 bool lhsNegative = false;
554 bool rhsNegative = false;
555 if (lhs[BitWidth-1]) {
560 if (rhs[BitWidth-1]) {
567 return !lhs.ult(rhs);
570 else if (rhsNegative)
576 /// Set the given bit to 1 whose poition is given as "bitPosition".
577 /// @brief Set a given bit to 1.
578 APInt& APInt::set(uint32_t bitPosition) {
579 if (isSingleWord()) VAL |= maskBit(bitPosition);
580 else pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
584 /// @brief Set every bit to 1.
585 APInt& APInt::set() {
587 VAL = ~0ULL >> (APINT_BITS_PER_WORD - BitWidth);
589 for (uint32_t i = 0; i < getNumWords() - 1; ++i)
591 pVal[getNumWords() - 1] = ~0ULL >>
592 (APINT_BITS_PER_WORD - BitWidth % APINT_BITS_PER_WORD);
597 /// Set the given bit to 0 whose position is given as "bitPosition".
598 /// @brief Set a given bit to 0.
599 APInt& APInt::clear(uint32_t bitPosition) {
601 VAL &= ~maskBit(bitPosition);
603 pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
607 /// @brief Set every bit to 0.
608 APInt& APInt::clear() {
612 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
616 /// @brief Bitwise NOT operator. Performs a bitwise logical NOT operation on
618 APInt APInt::operator~() const {
624 /// @brief Toggle every bit to its opposite value.
625 APInt& APInt::flip() {
626 if (isSingleWord()) VAL = (~(VAL <<
627 (APINT_BITS_PER_WORD - BitWidth))) >> (APINT_BITS_PER_WORD - BitWidth);
630 for (; i < getNumWords() - 1; ++i)
633 APINT_BITS_PER_WORD - (BitWidth - APINT_BITS_PER_WORD * (i - 1));
634 pVal[i] = (~(pVal[i] << offset)) >> offset;
639 /// Toggle a given bit to its opposite value whose position is given
640 /// as "bitPosition".
641 /// @brief Toggles a given bit to its opposite value.
642 APInt& APInt::flip(uint32_t bitPosition) {
643 assert(bitPosition < BitWidth && "Out of the bit-width range!");
644 if ((*this)[bitPosition]) clear(bitPosition);
645 else set(bitPosition);
649 /// getMaxValue - This function returns the largest value
650 /// for an APInt of the specified bit-width and if isSign == true,
651 /// it should be largest signed value, otherwise unsigned value.
652 APInt APInt::getMaxValue(uint32_t numBits, bool isSign) {
653 APInt Result(numBits, 0);
656 Result.clear(numBits - 1);
660 /// getMinValue - This function returns the smallest value for
661 /// an APInt of the given bit-width and if isSign == true,
662 /// it should be smallest signed value, otherwise zero.
663 APInt APInt::getMinValue(uint32_t numBits, bool isSign) {
664 APInt Result(numBits, 0);
666 Result.set(numBits - 1);
670 /// getAllOnesValue - This function returns an all-ones value for
671 /// an APInt of the specified bit-width.
672 APInt APInt::getAllOnesValue(uint32_t numBits) {
673 return getMaxValue(numBits, false);
676 /// getNullValue - This function creates an '0' value for an
677 /// APInt of the specified bit-width.
678 APInt APInt::getNullValue(uint32_t numBits) {
679 return getMinValue(numBits, false);
682 /// HiBits - This function returns the high "numBits" bits of this APInt.
683 APInt APInt::getHiBits(uint32_t numBits) const {
684 return APIntOps::lshr(*this, BitWidth - numBits);
687 /// LoBits - This function returns the low "numBits" bits of this APInt.
688 APInt APInt::getLoBits(uint32_t numBits) const {
689 return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits),
693 bool APInt::isPowerOf2() const {
694 return (!!*this) && !(*this & (*this - APInt(BitWidth,1)));
697 /// countLeadingZeros - This function is a APInt version corresponding to
698 /// llvm/include/llvm/Support/MathExtras.h's function
699 /// countLeadingZeros_{32, 64}. It performs platform optimal form of counting
700 /// the number of zeros from the most significant bit to the first one bit.
701 /// @returns numWord() * 64 if the value is zero.
702 uint32_t APInt::countLeadingZeros() const {
705 Count = CountLeadingZeros_64(VAL);
707 for (uint32_t i = getNumWords(); i > 0u; --i) {
709 Count += APINT_BITS_PER_WORD;
711 Count += CountLeadingZeros_64(pVal[i-1]);
716 return Count - (APINT_BITS_PER_WORD - (BitWidth % APINT_BITS_PER_WORD));
719 /// countTrailingZeros - This function is a APInt version corresponding to
720 /// llvm/include/llvm/Support/MathExtras.h's function
721 /// countTrailingZeros_{32, 64}. It performs platform optimal form of counting
722 /// the number of zeros from the least significant bit to the first one bit.
723 /// @returns numWord() * 64 if the value is zero.
724 uint32_t APInt::countTrailingZeros() const {
726 return CountTrailingZeros_64(VAL);
727 APInt Tmp( ~(*this) & ((*this) - APInt(BitWidth,1)) );
728 return getNumWords() * APINT_BITS_PER_WORD - Tmp.countLeadingZeros();
731 /// countPopulation - This function is a APInt version corresponding to
732 /// llvm/include/llvm/Support/MathExtras.h's function
733 /// countPopulation_{32, 64}. It counts the number of set bits in a value.
734 /// @returns 0 if the value is zero.
735 uint32_t APInt::countPopulation() const {
737 return CountPopulation_64(VAL);
739 for (uint32_t i = 0; i < getNumWords(); ++i)
740 Count += CountPopulation_64(pVal[i]);
745 /// byteSwap - This function returns a byte-swapped representation of the
747 APInt APInt::byteSwap() const {
748 assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
750 return APInt(BitWidth, ByteSwap_16(VAL));
751 else if (BitWidth == 32)
752 return APInt(BitWidth, ByteSwap_32(VAL));
753 else if (BitWidth == 48) {
754 uint64_t Tmp1 = ((VAL >> 32) << 16) | (VAL & 0xFFFF);
755 Tmp1 = ByteSwap_32(Tmp1);
756 uint64_t Tmp2 = (VAL >> 16) & 0xFFFF;
757 Tmp2 = ByteSwap_16(Tmp2);
760 (Tmp1 & 0xff) | ((Tmp1<<16) & 0xffff00000000ULL) | (Tmp2 << 16));
761 } else if (BitWidth == 64)
762 return APInt(BitWidth, ByteSwap_64(VAL));
764 APInt Result(BitWidth, 0);
765 char *pByte = (char*)Result.pVal;
766 for (uint32_t i = 0; i < BitWidth / APINT_WORD_SIZE / 2; ++i) {
768 pByte[i] = pByte[BitWidth / APINT_WORD_SIZE - 1 - i];
769 pByte[BitWidth / APINT_WORD_SIZE - i - 1] = Tmp;
775 /// GreatestCommonDivisor - This function returns the greatest common
776 /// divisor of the two APInt values using Enclid's algorithm.
777 APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1,
779 APInt A = API1, B = API2;
782 B = APIntOps::urem(A, B);
788 /// DoubleRoundToAPInt - This function convert a double value to
790 APInt llvm::APIntOps::RoundDoubleToAPInt(double Double) {
796 bool isNeg = T.I >> 63;
797 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
799 return APInt(64ull, 0u);
800 uint64_t mantissa = ((T.I << 12) >> 12) | (1ULL << 52);
802 return isNeg ? -APInt(64u, mantissa >> (52 - exp)) :
803 APInt(64u, mantissa >> (52 - exp));
804 APInt Tmp(exp + 1, mantissa);
805 Tmp = Tmp.shl(exp - 52);
806 return isNeg ? -Tmp : Tmp;
809 /// RoundToDouble - This function convert this APInt to a double.
810 /// The layout for double is as following (IEEE Standard 754):
811 /// --------------------------------------
812 /// | Sign Exponent Fraction Bias |
813 /// |-------------------------------------- |
814 /// | 1[63] 11[62-52] 52[51-00] 1023 |
815 /// --------------------------------------
816 double APInt::roundToDouble(bool isSigned) const {
818 // Handle the simple case where the value is contained in one uint64_t.
819 if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
821 int64_t sext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
827 // Determine if the value is negative.
828 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
830 // Construct the absolute value if we're negative.
831 APInt Tmp(isNeg ? -(*this) : (*this));
833 // Figure out how many bits we're using.
834 uint32_t n = Tmp.getActiveBits();
836 // The exponent (without bias normalization) is just the number of bits
837 // we are using. Note that the sign bit is gone since we constructed the
841 // Return infinity for exponent overflow
843 if (!isSigned || !isNeg)
844 return double(1.0E300 * 1.0E300); // positive infinity
846 return double(-1.0E300 * 1.0E300); // negative infinity
848 exp += 1023; // Increment for 1023 bias
850 // Number of bits in mantissa is 52. To obtain the mantissa value, we must
851 // extract the high 52 bits from the correct words in pVal.
853 unsigned hiWord = whichWord(n-1);
855 mantissa = Tmp.pVal[0];
857 mantissa >>= n - 52; // shift down, we want the top 52 bits.
859 assert(hiWord > 0 && "huh?");
860 uint64_t hibits = Tmp.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
861 uint64_t lobits = Tmp.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
862 mantissa = hibits | lobits;
865 // The leading bit of mantissa is implicit, so get rid of it.
866 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
871 T.I = sign | (exp << 52) | mantissa;
875 // Truncate to new width.
876 void APInt::trunc(uint32_t width) {
877 assert(width < BitWidth && "Invalid APInt Truncate request");
880 // Sign extend to a new width.
881 void APInt::sext(uint32_t width) {
882 assert(width > BitWidth && "Invalid APInt SignExtend request");
885 // Zero extend to a new width.
886 void APInt::zext(uint32_t width) {
887 assert(width > BitWidth && "Invalid APInt ZeroExtend request");
890 /// Arithmetic right-shift this APInt by shiftAmt.
891 /// @brief Arithmetic right-shift function.
892 APInt APInt::ashr(uint32_t shiftAmt) const {
894 if (API.isSingleWord())
896 (((int64_t(API.VAL) << (APINT_BITS_PER_WORD - API.BitWidth)) >>
897 (APINT_BITS_PER_WORD - API.BitWidth)) >> shiftAmt) &
898 (~uint64_t(0UL) >> (APINT_BITS_PER_WORD - API.BitWidth));
900 if (shiftAmt >= API.BitWidth) {
901 memset(API.pVal, API[API.BitWidth-1] ? 1 : 0,
902 (API.getNumWords()-1) * APINT_WORD_SIZE);
903 API.pVal[API.getNumWords() - 1] =
905 (APINT_BITS_PER_WORD - API.BitWidth % APINT_BITS_PER_WORD);
908 for (; i < API.BitWidth - shiftAmt; ++i)
913 for (; i < API.BitWidth; ++i)
914 if (API[API.BitWidth-1])
922 /// Logical right-shift this APInt by shiftAmt.
923 /// @brief Logical right-shift function.
924 APInt APInt::lshr(uint32_t shiftAmt) const {
926 if (API.isSingleWord())
927 API.VAL >>= shiftAmt;
929 if (shiftAmt >= API.BitWidth)
930 memset(API.pVal, 0, API.getNumWords() * APINT_WORD_SIZE);
932 for (i = 0; i < API.BitWidth - shiftAmt; ++i)
933 if (API[i+shiftAmt]) API.set(i);
935 for (; i < API.BitWidth; ++i)
941 /// Left-shift this APInt by shiftAmt.
942 /// @brief Left-shift function.
943 APInt APInt::shl(uint32_t shiftAmt) const {
945 if (API.isSingleWord())
946 API.VAL <<= shiftAmt;
947 else if (shiftAmt >= API.BitWidth)
948 memset(API.pVal, 0, API.getNumWords() * APINT_WORD_SIZE);
950 if (uint32_t offset = shiftAmt / APINT_BITS_PER_WORD) {
951 for (uint32_t i = API.getNumWords() - 1; i > offset - 1; --i)
952 API.pVal[i] = API.pVal[i-offset];
953 memset(API.pVal, 0, offset * APINT_WORD_SIZE);
955 shiftAmt %= APINT_BITS_PER_WORD;
957 for (i = API.getNumWords() - 1; i > 0; --i)
958 API.pVal[i] = (API.pVal[i] << shiftAmt) |
959 (API.pVal[i-1] >> (APINT_BITS_PER_WORD - shiftAmt));
960 API.pVal[i] <<= shiftAmt;
962 API.clearUnusedBits();
967 /// subMul - This function substracts x[len-1:0] * y from
968 /// dest[offset+len-1:offset], and returns the most significant
969 /// word of the product, minus the borrow-out from the subtraction.
970 static uint32_t subMul(uint32_t dest[], uint32_t offset,
971 uint32_t x[], uint32_t len, uint32_t y) {
972 uint64_t yl = (uint64_t) y & 0xffffffffL;
976 uint64_t prod = ((uint64_t) x[j] & 0xffffffffUL) * yl;
977 uint32_t prod_low = (uint32_t) prod;
978 uint32_t prod_high = (uint32_t) (prod >> 32);
980 carry = (prod_low < carry ? 1 : 0) + prod_high;
981 uint32_t x_j = dest[offset+j];
982 prod_low = x_j - prod_low;
983 if (prod_low > x_j) ++carry;
984 dest[offset+j] = prod_low;
989 /// unitDiv - This function divides N by D,
990 /// and returns (remainder << 32) | quotient.
991 /// Assumes (N >> 32) < D.
992 static uint64_t unitDiv(uint64_t N, uint32_t D) {
993 uint64_t q, r; // q: quotient, r: remainder.
994 uint64_t a1 = N >> 32; // a1: high 32-bit part of N.
995 uint64_t a0 = N & 0xffffffffL; // a0: low 32-bit part of N
996 if (a1 < ((D - a1 - (a0 >> 31)) & 0xffffffffL)) {
1001 // Compute c1*2^32 + c0 = a1*2^32 + a0 - 2^31*d
1002 uint64_t c = N - ((uint64_t) D << 31);
1003 // Divide (c1*2^32 + c0) by d
1006 // Add 2^31 to quotient
1010 return (r << 32) | (q & 0xFFFFFFFFl);
1015 /// div - This is basically Knuth's formulation of the classical algorithm.
1016 /// Correspondance with Knuth's notation:
1017 /// Knuth's u[0:m+n] == zds[nx:0].
1018 /// Knuth's v[1:n] == y[ny-1:0]
1019 /// Knuth's n == ny.
1020 /// Knuth's m == nx-ny.
1021 /// Our nx == Knuth's m+n.
1022 /// Could be re-implemented using gmp's mpn_divrem:
1023 /// zds[nx] = mpn_divrem (&zds[ny], 0, zds, nx, y, ny).
1025 /// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
1026 /// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
1027 /// variables here have the same names as in the algorithm. Comments explain
1028 /// the algorithm and any deviation from it.
1029 static void KnuthDiv(uint32_t *u, uint32_t *v, uint32_t *q, uint32_t* r,
1030 uint32_t m, uint32_t n) {
1031 assert(u && "Must provide dividend");
1032 assert(v && "Must provide divisor");
1033 assert(q && "Must provide quotient");
1034 assert(n>1 && "n must be > 1");
1036 // Knuth uses the value b as the base of the number system. In our case b
1037 // is 2^31 so we just set it to -1u.
1038 uint64_t b = uint64_t(1) << 32;
1040 // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
1041 // u and v by d. Note that we have taken Knuth's advice here to use a power
1042 // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
1043 // 2 allows us to shift instead of multiply and it is easy to determine the
1044 // shift amount from the leading zeros. We are basically normalizing the u
1045 // and v so that its high bits are shifted to the top of v's range without
1046 // overflow. Note that this can require an extra word in u so that u must
1047 // be of length m+n+1.
1048 uint32_t shift = CountLeadingZeros_32(v[n-1]);
1049 uint32_t v_carry = 0;
1050 uint32_t u_carry = 0;
1052 for (uint32_t i = 0; i < m+n; ++i) {
1053 uint32_t u_tmp = u[i] >> (32 - shift);
1054 u[i] = (u[i] << shift) | u_carry;
1057 for (uint32_t i = 0; i < n; ++i) {
1058 uint32_t v_tmp = v[i] >> (32 - shift);
1059 v[i] = (v[i] << shift) | v_carry;
1065 // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
1068 // D3. [Calculate q'.].
1069 // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
1070 // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
1071 // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
1072 // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test
1073 // on v[n-2] determines at high speed most of the cases in which the trial
1074 // value qp is one too large, and it eliminates all cases where qp is two
1076 uint64_t qp = ((uint64_t(u[j+n]) << 32) | uint64_t(u[j+n-1])) / v[n-1];
1077 uint64_t rp = ((uint64_t(u[j+n]) << 32) | uint64_t(u[j+n-1])) % v[n-1];
1078 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1083 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1088 // D4. [Multiply and subtract.] Replace u with u - q*v (for each word).
1089 uint32_t borrow = 0;
1090 for (uint32_t i = 0; i < n; i++) {
1091 uint32_t save = u[j+i];
1092 u[j+i] = uint64_t(u[j+i]) - (qp * v[i]) - borrow;
1093 if (u[j+i] > save) {
1103 // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
1104 // negative, go to step D6; otherwise go on to step D7.
1107 // D6. [Add back]. The probability that this step is necessary is very
1108 // small, on the order of only 2/b. Make sure that test data accounts for
1109 // this possibility. Decreate qj by 1 and add v[...] to u[...]. A carry
1110 // will occur to the left of u[j+n], and it should be ignored since it
1111 // cancels with the borrow that occurred in D4.
1113 for (uint32_t i = 0; i < n; i++) {
1114 uint32_t save = u[j+i];
1115 u[j+i] += v[i] + carry;
1116 carry = u[j+i] < save;
1120 // D7. [Loop on j.] Decreate j by one. Now if j >= 0, go back to D3.
1124 // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
1125 // remainder may be obtained by dividing u[...] by d. If r is non-null we
1126 // compute the remainder (urem uses this).
1128 // The value d is expressed by the "shift" value above since we avoided
1129 // multiplication by d by using a shift left. So, all we have to do is
1130 // shift right here. In order to mak
1131 uint32_t mask = ~0u >> (32 - shift);
1133 for (int i = n-1; i >= 0; i--) {
1134 uint32_t save = u[i] & mask;
1135 r[i] = (u[i] >> shift) | carry;
1141 // This function makes calling KnuthDiv a little more convenient. It uses
1142 // APInt parameters instead of uint32_t* parameters. It can also divide APInt
1143 // values of different widths.
1144 void APInt::divide(const APInt LHS, uint32_t lhsWords,
1145 const APInt &RHS, uint32_t rhsWords,
1146 APInt *Quotient, APInt *Remainder)
1148 assert(lhsWords >= rhsWords && "Fractional result");
1150 // First, compose the values into an array of 32-bit words instead of
1151 // 64-bit words. This is a necessity of both the "short division" algorithm
1152 // and the the Knuth "classical algorithm" which requires there to be native
1153 // operations for +, -, and * on an m bit value with an m*2 bit result. We
1154 // can't use 64-bit operands here because we don't have native results of
1155 // 128-bits. Furthremore, casting the 64-bit values to 32-bit values won't
1156 // work on large-endian machines.
1157 uint64_t mask = ~0ull >> (sizeof(uint32_t)*8);
1158 uint32_t n = rhsWords * 2;
1159 uint32_t m = (lhsWords * 2) - n;
1160 // FIXME: allocate space on stack if m and n are sufficiently small.
1161 uint32_t *U = new uint32_t[m + n + 1];
1162 memset(U, 0, (m+n+1)*sizeof(uint32_t));
1163 for (unsigned i = 0; i < lhsWords; ++i) {
1164 uint64_t tmp = (lhsWords == 1 ? LHS.VAL : LHS.pVal[i]);
1165 U[i * 2] = tmp & mask;
1166 U[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1168 U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
1170 uint32_t *V = new uint32_t[n];
1171 memset(V, 0, (n)*sizeof(uint32_t));
1172 for (unsigned i = 0; i < rhsWords; ++i) {
1173 uint64_t tmp = (rhsWords == 1 ? RHS.VAL : RHS.pVal[i]);
1174 V[i * 2] = tmp & mask;
1175 V[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1178 // Set up the quotient and remainder
1179 uint32_t *Q = new uint32_t[m+n];
1180 memset(Q, 0, (m+n) * sizeof(uint32_t));
1183 R = new uint32_t[n];
1184 memset(R, 0, n * sizeof(uint32_t));
1187 // Now, adjust m and n for the Knuth division. n is the number of words in
1188 // the divisor. m is the number of words by which the dividend exceeds the
1189 // divisor (i.e. m+n is the length of the dividend). These sizes must not
1190 // contain any zero words or the Knuth algorithm fails.
1191 for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
1195 for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
1198 // If we're left with only a single word for the divisor, Knuth doesn't work
1199 // so we implement the short division algorithm here. This is much simpler
1200 // and faster because we are certain that we can divide a 64-bit quantity
1201 // by a 32-bit quantity at hardware speed and short division is simply a
1202 // series of such operations. This is just like doing short division but we
1203 // are using base 2^32 instead of base 10.
1204 assert(n != 0 && "Divide by zero?");
1206 uint32_t divisor = V[0];
1207 uint32_t remainder = 0;
1208 for (int i = m+n-1; i >= 0; i--) {
1209 uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i];
1210 if (partial_dividend == 0) {
1213 } else if (partial_dividend < divisor) {
1215 remainder = partial_dividend;
1216 } else if (partial_dividend == divisor) {
1220 Q[i] = partial_dividend / divisor;
1221 remainder = partial_dividend - (Q[i] * divisor);
1227 // Now we're ready to invoke the Knuth classical divide algorithm. In this
1229 KnuthDiv(U, V, Q, R, m, n);
1232 // If the caller wants the quotient
1234 // Set up the Quotient value's memory.
1235 if (Quotient->BitWidth != LHS.BitWidth) {
1236 if (Quotient->isSingleWord())
1239 delete Quotient->pVal;
1240 Quotient->BitWidth = LHS.BitWidth;
1241 if (!Quotient->isSingleWord())
1242 Quotient->pVal = getClearedMemory(lhsWords);
1246 // The quotient is in Q. Reconstitute the quotient into Quotient's low
1248 if (lhsWords == 1) {
1250 uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2));
1251 if (Quotient->isSingleWord())
1252 Quotient->VAL = tmp;
1254 Quotient->pVal[0] = tmp;
1256 assert(!Quotient->isSingleWord() && "Quotient APInt not large enough");
1257 for (unsigned i = 0; i < lhsWords; ++i)
1259 uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1263 // If the caller wants the remainder
1265 // Set up the Remainder value's memory.
1266 if (Remainder->BitWidth != RHS.BitWidth) {
1267 if (Remainder->isSingleWord())
1270 delete Remainder->pVal;
1271 Remainder->BitWidth = RHS.BitWidth;
1272 if (!Remainder->isSingleWord())
1273 Remainder->pVal = getClearedMemory(rhsWords);
1277 // The remainder is in R. Reconstitute the remainder into Remainder's low
1279 if (rhsWords == 1) {
1281 uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2));
1282 if (Remainder->isSingleWord())
1283 Remainder->VAL = tmp;
1285 Remainder->pVal[0] = tmp;
1287 assert(!Remainder->isSingleWord() && "Remainder APInt not large enough");
1288 for (unsigned i = 0; i < rhsWords; ++i)
1289 Remainder->pVal[i] =
1290 uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1294 // Clean up the memory we allocated.
1301 /// Unsigned divide this APInt by APInt RHS.
1302 /// @brief Unsigned division function for APInt.
1303 APInt APInt::udiv(const APInt& RHS) const {
1304 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1306 // First, deal with the easy case
1307 if (isSingleWord()) {
1308 assert(RHS.VAL != 0 && "Divide by zero?");
1309 return APInt(BitWidth, VAL / RHS.VAL);
1312 // Get some facts about the LHS and RHS number of bits and words
1313 uint32_t rhsBits = RHS.getActiveBits();
1314 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
1315 assert(rhsWords && "Divided by zero???");
1316 uint32_t lhsBits = this->getActiveBits();
1317 uint32_t lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
1319 // Make a temporary to hold the result
1320 APInt Result(*this);
1322 // Deal with some degenerate cases
1324 return Result; // 0 / X == 0
1325 else if (lhsWords < rhsWords || Result.ult(RHS)) {
1326 // X / Y with X < Y == 0
1327 memset(Result.pVal, 0, Result.getNumWords() * APINT_WORD_SIZE);
1329 } else if (Result == RHS) {
1331 memset(Result.pVal, 0, Result.getNumWords() * APINT_WORD_SIZE);
1334 } else if (lhsWords == 1 && rhsWords == 1) {
1335 // All high words are zero, just use native divide
1336 Result.pVal[0] /= RHS.pVal[0];
1340 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1341 APInt Quotient(1,0); // to hold result.
1342 divide(*this, lhsWords, RHS, rhsWords, &Quotient, 0);
1346 /// Unsigned remainder operation on APInt.
1347 /// @brief Function for unsigned remainder operation.
1348 APInt APInt::urem(const APInt& RHS) const {
1349 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1350 if (isSingleWord()) {
1351 assert(RHS.VAL != 0 && "Remainder by zero?");
1352 return APInt(BitWidth, VAL % RHS.VAL);
1355 // Make a temporary to hold the result
1356 APInt Result(*this);
1358 // Get some facts about the RHS
1359 uint32_t rhsBits = RHS.getActiveBits();
1360 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
1361 assert(rhsWords && "Performing remainder operation by zero ???");
1363 // Get some facts about the LHS
1364 uint32_t lhsBits = Result.getActiveBits();
1365 uint32_t lhsWords = !lhsBits ? 0 : (Result.whichWord(lhsBits - 1) + 1);
1367 // Check the degenerate cases
1368 if (lhsWords == 0) {
1370 memset(Result.pVal, 0, Result.getNumWords() * APINT_WORD_SIZE);
1372 } else if (lhsWords < rhsWords || Result.ult(RHS)) {
1373 // X % Y == X iff X < Y
1375 } else if (Result == RHS) {
1377 memset(Result.pVal, 0, Result.getNumWords() * APINT_WORD_SIZE);
1379 } else if (lhsWords == 1) {
1380 // All high words are zero, just use native remainder
1381 Result.pVal[0] %= RHS.pVal[0];
1385 // We have to compute it the hard way. Invoke the Knute divide algorithm.
1386 APInt Remainder(1,0);
1387 divide(*this, lhsWords, RHS, rhsWords, 0, &Remainder);
1391 /// @brief Converts a char array into an integer.
1392 void APInt::fromString(uint32_t numbits, const char *str, uint32_t slen,
1394 // Check our assumptions here
1395 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1396 "Radix should be 2, 8, 10, or 16!");
1397 assert(str && "String is null?");
1398 assert(slen <= numbits || radix != 2 && "Insufficient bit width");
1399 assert(slen*3 <= numbits || radix != 8 && "Insufficient bit width");
1400 assert(slen*4 <= numbits || radix != 16 && "Insufficient bit width");
1401 assert((slen*64)/20 <= numbits || radix != 10 && "Insufficient bit width");
1404 if (!isSingleWord())
1405 pVal = getClearedMemory(getNumWords());
1407 // Figure out if we can shift instead of multiply
1408 uint32_t shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0);
1410 // Set up an APInt for the digit to add outside the loop so we don't
1411 // constantly construct/destruct it.
1412 APInt apdigit(getBitWidth(), 0);
1413 APInt apradix(getBitWidth(), radix);
1415 // Enter digit traversal loop
1416 for (unsigned i = 0; i < slen; i++) {
1419 char cdigit = str[i];
1420 if (isdigit(cdigit))
1421 digit = cdigit - '0';
1422 else if (isxdigit(cdigit))
1424 digit = cdigit - 'a' + 10;
1425 else if (cdigit >= 'A')
1426 digit = cdigit - 'A' + 10;
1428 assert(0 && "huh?");
1430 assert(0 && "Invalid character in digit string");
1432 // Shift or multiple the value by the radix
1438 // Add in the digit we just interpreted
1439 apdigit.pVal[0] = digit;
1444 /// to_string - This function translates the APInt into a string.
1445 std::string APInt::toString(uint8_t radix, bool wantSigned) const {
1446 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1447 "Radix should be 2, 8, 10, or 16!");
1448 static const char *digits[] = {
1449 "0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"
1452 uint32_t bits_used = getActiveBits();
1453 if (isSingleWord()) {
1455 const char *format = (radix == 10 ? (wantSigned ? "%lld" : "%llu") :
1456 (radix == 16 ? "%llX" : (radix == 8 ? "%llo" : 0)));
1459 int64_t sextVal = (int64_t(VAL) << (APINT_BITS_PER_WORD-BitWidth)) >>
1460 (APINT_BITS_PER_WORD-BitWidth);
1461 sprintf(buf, format, sextVal);
1463 sprintf(buf, format, VAL);
1468 uint32_t bit = v & 1;
1470 buf[bits_used] = digits[bit][0];
1479 uint64_t mask = radix - 1;
1480 uint32_t shift = (radix == 16 ? 4 : radix == 8 ? 3 : 1);
1481 uint32_t nibbles = APINT_BITS_PER_WORD / shift;
1482 for (uint32_t i = 0; i < getNumWords(); ++i) {
1483 uint64_t value = pVal[i];
1484 for (uint32_t j = 0; j < nibbles; ++j) {
1485 result.insert(0, digits[ value & mask ]);
1493 APInt divisor(4, radix);
1494 APInt zero(tmp.getBitWidth(), 0);
1495 size_t insert_at = 0;
1496 if (wantSigned && tmp[BitWidth-1]) {
1497 // They want to print the signed version and it is a negative value
1498 // Flip the bits and add one to turn it into the equivalent positive
1499 // value and put a '-' in the result.
1505 if (tmp == APInt(tmp.getBitWidth(), 0))
1507 else while (tmp.ne(zero)) {
1509 APInt tmp2(tmp.getBitWidth(), 0);
1510 divide(tmp, tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2,
1512 uint32_t digit = APdigit.getValue();
1513 assert(digit < radix && "divide failed");
1514 result.insert(insert_at,digits[digit]);
1522 void APInt::dump() const
1524 std::cerr << "APInt(" << BitWidth << ")=" << std::setbase(16);
1527 else for (unsigned i = getNumWords(); i > 0; i--) {
1528 std::cerr << pVal[i-1] << " ";
1530 std::cerr << " (" << this->toString(10, false) << ")\n" << std::setbase(10);