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 integer
11 // constant values and provide a variety of arithmetic operations on them.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "apint"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Support/Debug.h"
19 #include "llvm/Support/MathExtras.h"
28 /// A utility function for allocating memory, checking for allocation failures,
29 /// and ensuring the contents are zeroed.
30 inline static uint64_t* getClearedMemory(uint32_t numWords) {
31 uint64_t * result = new uint64_t[numWords];
32 assert(result && "APInt memory allocation fails!");
33 memset(result, 0, numWords * sizeof(uint64_t));
37 /// A utility function for allocating memory and checking for allocation
38 /// failure. The content is not zeroed.
39 inline static uint64_t* getMemory(uint32_t numWords) {
40 uint64_t * result = new uint64_t[numWords];
41 assert(result && "APInt memory allocation fails!");
45 APInt::APInt(uint32_t numBits, uint64_t val)
46 : BitWidth(numBits), VAL(0) {
47 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
48 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
52 pVal = getClearedMemory(getNumWords());
58 APInt::APInt(uint32_t numBits, uint32_t numWords, uint64_t bigVal[])
59 : BitWidth(numBits), VAL(0) {
60 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
61 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
62 assert(bigVal && "Null pointer detected!");
66 // Get memory, cleared to 0
67 pVal = getClearedMemory(getNumWords());
68 // Calculate the number of words to copy
69 uint32_t words = std::min<uint32_t>(numWords, getNumWords());
70 // Copy the words from bigVal to pVal
71 memcpy(pVal, bigVal, words * APINT_WORD_SIZE);
73 // Make sure unused high bits are cleared
77 APInt::APInt(uint32_t numbits, const char StrStart[], uint32_t slen,
79 : BitWidth(numbits), VAL(0) {
80 fromString(numbits, StrStart, slen, radix);
83 APInt::APInt(uint32_t numbits, const std::string& Val, uint8_t radix)
84 : BitWidth(numbits), VAL(0) {
85 assert(!Val.empty() && "String empty?");
86 fromString(numbits, Val.c_str(), Val.size(), radix);
89 APInt::APInt(const APInt& that)
90 : BitWidth(that.BitWidth), VAL(0) {
94 pVal = getMemory(getNumWords());
95 memcpy(pVal, that.pVal, getNumWords() * APINT_WORD_SIZE);
100 if (!isSingleWord() && pVal)
104 APInt& APInt::operator=(const APInt& RHS) {
105 // Don't do anything for X = X
109 // If the bitwidths are the same, we can avoid mucking with memory
110 if (BitWidth == RHS.getBitWidth()) {
114 memcpy(pVal, RHS.pVal, getNumWords() * APINT_WORD_SIZE);
119 if (RHS.isSingleWord())
123 pVal = getMemory(RHS.getNumWords());
124 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
126 else if (getNumWords() == RHS.getNumWords())
127 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
128 else if (RHS.isSingleWord()) {
133 pVal = getMemory(RHS.getNumWords());
134 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
136 BitWidth = RHS.BitWidth;
137 return clearUnusedBits();
140 APInt& APInt::operator=(uint64_t RHS) {
145 memset(pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
147 return clearUnusedBits();
150 /// add_1 - This function adds a single "digit" integer, y, to the multiple
151 /// "digit" integer array, x[]. x[] is modified to reflect the addition and
152 /// 1 is returned if there is a carry out, otherwise 0 is returned.
153 /// @returns the carry of the addition.
154 static bool add_1(uint64_t dest[], uint64_t x[], uint32_t len, uint64_t y) {
155 for (uint32_t i = 0; i < len; ++i) {
158 y = 1; // Carry one to next digit.
160 y = 0; // No need to carry so exit early
167 /// @brief Prefix increment operator. Increments the APInt by one.
168 APInt& APInt::operator++() {
172 add_1(pVal, pVal, getNumWords(), 1);
173 return clearUnusedBits();
176 /// sub_1 - This function subtracts a single "digit" (64-bit word), y, from
177 /// the multi-digit integer array, x[], propagating the borrowed 1 value until
178 /// no further borrowing is neeeded or it runs out of "digits" in x. The result
179 /// is 1 if "borrowing" exhausted the digits in x, or 0 if x was not exhausted.
180 /// In other words, if y > x then this function returns 1, otherwise 0.
181 /// @returns the borrow out of the subtraction
182 static bool sub_1(uint64_t x[], uint32_t len, uint64_t y) {
183 for (uint32_t i = 0; i < len; ++i) {
187 y = 1; // We have to "borrow 1" from next "digit"
189 y = 0; // No need to borrow
190 break; // Remaining digits are unchanged so exit early
196 /// @brief Prefix decrement operator. Decrements the APInt by one.
197 APInt& APInt::operator--() {
201 sub_1(pVal, getNumWords(), 1);
202 return clearUnusedBits();
205 /// add - This function adds the integer array x to the integer array Y and
206 /// places the result in dest.
207 /// @returns the carry out from the addition
208 /// @brief General addition of 64-bit integer arrays
209 static bool add(uint64_t *dest, const uint64_t *x, const uint64_t *y,
212 for (uint32_t i = 0; i< len; ++i) {
213 uint64_t limit = std::min(x[i],y[i]); // must come first in case dest == x
214 dest[i] = x[i] + y[i] + carry;
215 carry = dest[i] < limit || (carry && dest[i] == limit);
220 /// Adds the RHS APint to this APInt.
221 /// @returns this, after addition of RHS.
222 /// @brief Addition assignment operator.
223 APInt& APInt::operator+=(const APInt& RHS) {
224 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
228 add(pVal, pVal, RHS.pVal, getNumWords());
230 return clearUnusedBits();
233 /// Subtracts the integer array y from the integer array x
234 /// @returns returns the borrow out.
235 /// @brief Generalized subtraction of 64-bit integer arrays.
236 static bool sub(uint64_t *dest, const uint64_t *x, const uint64_t *y,
239 for (uint32_t i = 0; i < len; ++i) {
240 uint64_t x_tmp = borrow ? x[i] - 1 : x[i];
241 borrow = y[i] > x_tmp || (borrow && x[i] == 0);
242 dest[i] = x_tmp - y[i];
247 /// Subtracts the RHS APInt from this APInt
248 /// @returns this, after subtraction
249 /// @brief Subtraction assignment operator.
250 APInt& APInt::operator-=(const APInt& RHS) {
251 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
255 sub(pVal, pVal, RHS.pVal, getNumWords());
256 return clearUnusedBits();
259 /// Multiplies an integer array, x by a a uint64_t integer and places the result
261 /// @returns the carry out of the multiplication.
262 /// @brief Multiply a multi-digit APInt by a single digit (64-bit) integer.
263 static uint64_t mul_1(uint64_t dest[], uint64_t x[], uint32_t len, uint64_t y) {
264 // Split y into high 32-bit part (hy) and low 32-bit part (ly)
265 uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
268 // For each digit of x.
269 for (uint32_t i = 0; i < len; ++i) {
270 // Split x into high and low words
271 uint64_t lx = x[i] & 0xffffffffULL;
272 uint64_t hx = x[i] >> 32;
273 // hasCarry - A flag to indicate if there is a carry to the next digit.
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;
294 /// Multiplies integer array x by integer array y and stores the result into
295 /// the integer array dest. Note that dest's size must be >= xlen + ylen.
296 /// @brief Generalized multiplicate of integer arrays.
297 static void mul(uint64_t dest[], uint64_t x[], uint32_t xlen, uint64_t y[],
299 dest[xlen] = mul_1(dest, x, xlen, y[0]);
300 for (uint32_t i = 1; i < ylen; ++i) {
301 uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
302 uint64_t carry = 0, lx = 0, hx = 0;
303 for (uint32_t j = 0; j < xlen; ++j) {
304 lx = x[j] & 0xffffffffULL;
306 // hasCarry - A flag to indicate if has carry.
307 // hasCarry == 0, no carry
308 // hasCarry == 1, has carry
309 // hasCarry == 2, no carry and the calculation result == 0.
310 uint8_t hasCarry = 0;
311 uint64_t resul = carry + lx * ly;
312 hasCarry = (resul < carry) ? 1 : 0;
313 carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
314 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
316 carry += (lx * hy) & 0xffffffffULL;
317 resul = (carry << 32) | (resul & 0xffffffffULL);
319 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
320 (carry >> 32) + (dest[i+j] < resul ? 1 : 0) +
321 ((lx * hy) >> 32) + hx * hy;
323 dest[i+xlen] = carry;
327 APInt& APInt::operator*=(const APInt& RHS) {
328 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
329 if (isSingleWord()) {
335 // Get some bit facts about LHS and check for zero
336 uint32_t lhsBits = getActiveBits();
337 uint32_t lhsWords = !lhsBits ? 0 : whichWord(lhsBits - 1) + 1;
342 // Get some bit facts about RHS and check for zero
343 uint32_t rhsBits = RHS.getActiveBits();
344 uint32_t rhsWords = !rhsBits ? 0 : whichWord(rhsBits - 1) + 1;
351 // Allocate space for the result
352 uint32_t destWords = rhsWords + lhsWords;
353 uint64_t *dest = getMemory(destWords);
355 // Perform the long multiply
356 mul(dest, pVal, lhsWords, RHS.pVal, rhsWords);
358 // Copy result back into *this
360 uint32_t wordsToCopy = destWords >= getNumWords() ? getNumWords() : destWords;
361 memcpy(pVal, dest, wordsToCopy * APINT_WORD_SIZE);
363 // delete dest array and return
368 APInt& APInt::operator&=(const APInt& RHS) {
369 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
370 if (isSingleWord()) {
374 uint32_t numWords = getNumWords();
375 for (uint32_t i = 0; i < numWords; ++i)
376 pVal[i] &= RHS.pVal[i];
380 APInt& APInt::operator|=(const APInt& RHS) {
381 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
382 if (isSingleWord()) {
386 uint32_t numWords = getNumWords();
387 for (uint32_t i = 0; i < numWords; ++i)
388 pVal[i] |= RHS.pVal[i];
392 APInt& APInt::operator^=(const APInt& RHS) {
393 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
394 if (isSingleWord()) {
396 this->clearUnusedBits();
399 uint32_t numWords = getNumWords();
400 for (uint32_t i = 0; i < numWords; ++i)
401 pVal[i] ^= RHS.pVal[i];
402 return clearUnusedBits();
405 APInt APInt::operator&(const APInt& RHS) const {
406 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
408 return APInt(getBitWidth(), VAL & RHS.VAL);
410 uint32_t numWords = getNumWords();
411 uint64_t* val = getMemory(numWords);
412 for (uint32_t i = 0; i < numWords; ++i)
413 val[i] = pVal[i] & RHS.pVal[i];
414 return APInt(val, getBitWidth());
417 APInt APInt::operator|(const APInt& RHS) const {
418 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
420 return APInt(getBitWidth(), VAL | RHS.VAL);
422 uint32_t numWords = getNumWords();
423 uint64_t *val = getMemory(numWords);
424 for (uint32_t i = 0; i < numWords; ++i)
425 val[i] = pVal[i] | RHS.pVal[i];
426 return APInt(val, getBitWidth());
429 APInt APInt::operator^(const APInt& RHS) const {
430 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
432 return APInt(BitWidth, VAL ^ RHS.VAL);
434 uint32_t numWords = getNumWords();
435 uint64_t *val = getMemory(numWords);
436 for (uint32_t i = 0; i < numWords; ++i)
437 val[i] = pVal[i] ^ RHS.pVal[i];
439 // 0^0==1 so clear the high bits in case they got set.
440 return APInt(val, getBitWidth()).clearUnusedBits();
443 bool APInt::operator !() const {
447 for (uint32_t i = 0; i < getNumWords(); ++i)
453 APInt APInt::operator*(const APInt& RHS) const {
454 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
456 return APInt(BitWidth, VAL * RHS.VAL);
459 return Result.clearUnusedBits();
462 APInt APInt::operator+(const APInt& RHS) const {
463 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
465 return APInt(BitWidth, VAL + RHS.VAL);
466 APInt Result(BitWidth, 0);
467 add(Result.pVal, this->pVal, RHS.pVal, getNumWords());
468 return Result.clearUnusedBits();
471 APInt APInt::operator-(const APInt& RHS) const {
472 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
474 return APInt(BitWidth, VAL - RHS.VAL);
475 APInt Result(BitWidth, 0);
476 sub(Result.pVal, this->pVal, RHS.pVal, getNumWords());
477 return Result.clearUnusedBits();
480 bool APInt::operator[](uint32_t bitPosition) const {
481 return (maskBit(bitPosition) &
482 (isSingleWord() ? VAL : pVal[whichWord(bitPosition)])) != 0;
485 bool APInt::operator==(const APInt& RHS) const {
486 assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths");
488 return VAL == RHS.VAL;
490 // Get some facts about the number of bits used in the two operands.
491 uint32_t n1 = getActiveBits();
492 uint32_t n2 = RHS.getActiveBits();
494 // If the number of bits isn't the same, they aren't equal
498 // If the number of bits fits in a word, we only need to compare the low word.
499 if (n1 <= APINT_BITS_PER_WORD)
500 return pVal[0] == RHS.pVal[0];
502 // Otherwise, compare everything
503 for (int i = whichWord(n1 - 1); i >= 0; --i)
504 if (pVal[i] != RHS.pVal[i])
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 bool APInt::ult(const APInt& RHS) const {
521 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
523 return VAL < RHS.VAL;
525 // Get active bit length of both operands
526 uint32_t n1 = getActiveBits();
527 uint32_t n2 = RHS.getActiveBits();
529 // If magnitude of LHS is less than RHS, return true.
533 // If magnitude of RHS is greather than LHS, return false.
537 // If they bot fit in a word, just compare the low order word
538 if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
539 return pVal[0] < RHS.pVal[0];
541 // Otherwise, compare all words
542 uint32_t topWord = whichWord(std::max(n1,n2)-1);
543 for (int i = topWord; i >= 0; --i) {
544 if (pVal[i] > RHS.pVal[i])
546 if (pVal[i] < RHS.pVal[i])
552 bool APInt::slt(const APInt& RHS) const {
553 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
554 if (isSingleWord()) {
555 int64_t lhsSext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
556 int64_t rhsSext = (int64_t(RHS.VAL) << (64-BitWidth)) >> (64-BitWidth);
557 return lhsSext < rhsSext;
562 bool lhsNeg = isNegative();
563 bool rhsNeg = rhs.isNegative();
565 // Sign bit is set so perform two's complement to make it positive
570 // Sign bit is set so perform two's complement to make it positive
575 // Now we have unsigned values to compare so do the comparison if necessary
576 // based on the negativeness of the values.
588 APInt& APInt::set(uint32_t bitPosition) {
590 VAL |= maskBit(bitPosition);
592 pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
596 APInt& APInt::set() {
597 if (isSingleWord()) {
599 return clearUnusedBits();
602 // Set all the bits in all the words.
603 for (uint32_t i = 0; i < getNumWords() - 1; ++i)
605 // Clear the unused ones
606 return clearUnusedBits();
609 /// Set the given bit to 0 whose position is given as "bitPosition".
610 /// @brief Set a given bit to 0.
611 APInt& APInt::clear(uint32_t bitPosition) {
613 VAL &= ~maskBit(bitPosition);
615 pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
619 /// @brief Set every bit to 0.
620 APInt& APInt::clear() {
624 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
628 /// @brief Bitwise NOT operator. Performs a bitwise logical NOT operation on
630 APInt APInt::operator~() const {
636 /// @brief Toggle every bit to its opposite value.
637 APInt& APInt::flip() {
638 if (isSingleWord()) {
640 return clearUnusedBits();
642 for (uint32_t i = 0; i < getNumWords(); ++i)
644 return clearUnusedBits();
647 /// Toggle a given bit to its opposite value whose position is given
648 /// as "bitPosition".
649 /// @brief Toggles a given bit to its opposite value.
650 APInt& APInt::flip(uint32_t bitPosition) {
651 assert(bitPosition < BitWidth && "Out of the bit-width range!");
652 if ((*this)[bitPosition]) clear(bitPosition);
653 else set(bitPosition);
657 uint64_t APInt::getHashValue() const {
658 // Put the bit width into the low order bits.
659 uint64_t hash = BitWidth;
661 // Add the sum of the words to the hash.
663 hash += VAL << 6; // clear separation of up to 64 bits
665 for (uint32_t i = 0; i < getNumWords(); ++i)
666 hash += pVal[i] << 6; // clear sepration of up to 64 bits
670 /// HiBits - This function returns the high "numBits" bits of this APInt.
671 APInt APInt::getHiBits(uint32_t numBits) const {
672 return APIntOps::lshr(*this, BitWidth - numBits);
675 /// LoBits - This function returns the low "numBits" bits of this APInt.
676 APInt APInt::getLoBits(uint32_t numBits) const {
677 return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits),
681 bool APInt::isPowerOf2() const {
682 return (!!*this) && !(*this & (*this - APInt(BitWidth,1)));
685 uint32_t APInt::countLeadingZeros() const {
688 Count = CountLeadingZeros_64(VAL);
690 for (uint32_t i = getNumWords(); i > 0u; --i) {
692 Count += APINT_BITS_PER_WORD;
694 Count += CountLeadingZeros_64(pVal[i-1]);
699 uint32_t remainder = BitWidth % APINT_BITS_PER_WORD;
701 Count -= APINT_BITS_PER_WORD - remainder;
705 static uint32_t countLeadingOnes_64(uint64_t V, uint32_t skip) {
709 while (V && (V & (1ULL << 63))) {
716 uint32_t APInt::countLeadingOnes() const {
718 return countLeadingOnes_64(VAL, APINT_BITS_PER_WORD - BitWidth);
720 uint32_t highWordBits = BitWidth % APINT_BITS_PER_WORD;
721 uint32_t shift = (highWordBits == 0 ? 0 : APINT_BITS_PER_WORD - highWordBits);
722 int i = getNumWords() - 1;
723 uint32_t Count = countLeadingOnes_64(pVal[i], shift);
724 if (Count == highWordBits) {
725 for (i--; i >= 0; --i) {
726 if (pVal[i] == -1ULL)
727 Count += APINT_BITS_PER_WORD;
729 Count += countLeadingOnes_64(pVal[i], 0);
737 uint32_t APInt::countTrailingZeros() const {
739 return CountTrailingZeros_64(VAL);
742 for (; i < getNumWords() && pVal[i] == 0; ++i)
743 Count += APINT_BITS_PER_WORD;
744 if (i < getNumWords())
745 Count += CountTrailingZeros_64(pVal[i]);
749 uint32_t APInt::countPopulation() const {
751 return CountPopulation_64(VAL);
753 for (uint32_t i = 0; i < getNumWords(); ++i)
754 Count += CountPopulation_64(pVal[i]);
758 APInt APInt::byteSwap() const {
759 assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
761 return APInt(BitWidth, ByteSwap_16(VAL));
762 else if (BitWidth == 32)
763 return APInt(BitWidth, ByteSwap_32(VAL));
764 else if (BitWidth == 48) {
765 uint64_t Tmp1 = ((VAL >> 32) << 16) | (VAL & 0xFFFF);
766 Tmp1 = ByteSwap_32(Tmp1);
767 uint64_t Tmp2 = (VAL >> 16) & 0xFFFF;
768 Tmp2 = ByteSwap_16(Tmp2);
771 (Tmp1 & 0xff) | ((Tmp1<<16) & 0xffff00000000ULL) | (Tmp2 << 16));
772 } else if (BitWidth == 64)
773 return APInt(BitWidth, ByteSwap_64(VAL));
775 APInt Result(BitWidth, 0);
776 char *pByte = (char*)Result.pVal;
777 for (uint32_t i = 0; i < BitWidth / APINT_WORD_SIZE / 2; ++i) {
779 pByte[i] = pByte[BitWidth / APINT_WORD_SIZE - 1 - i];
780 pByte[BitWidth / APINT_WORD_SIZE - i - 1] = Tmp;
786 APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1,
788 APInt A = API1, B = API2;
791 B = APIntOps::urem(A, B);
797 APInt llvm::APIntOps::RoundDoubleToAPInt(double Double, uint32_t width) {
804 // Get the sign bit from the highest order bit
805 bool isNeg = T.I >> 63;
807 // Get the 11-bit exponent and adjust for the 1023 bit bias
808 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
810 // If the exponent is negative, the value is < 0 so just return 0.
812 return APInt(64u, 0u);
814 // Extract the mantissa by clearing the top 12 bits (sign + exponent).
815 uint64_t mantissa = (T.I & (~0ULL >> 12)) | 1ULL << 52;
817 // If the exponent doesn't shift all bits out of the mantissa
819 return isNeg ? -APInt(width, mantissa >> (52 - exp)) :
820 APInt(width, mantissa >> (52 - exp));
822 // If the client didn't provide enough bits for us to shift the mantissa into
823 // then the result is undefined, just return 0
824 if (width <= exp - 52)
825 return APInt(width, 0);
827 // Otherwise, we have to shift the mantissa bits up to the right location
828 APInt Tmp(width, mantissa);
829 Tmp = Tmp.shl(exp - 52);
830 return isNeg ? -Tmp : Tmp;
833 /// RoundToDouble - This function convert this APInt to a double.
834 /// The layout for double is as following (IEEE Standard 754):
835 /// --------------------------------------
836 /// | Sign Exponent Fraction Bias |
837 /// |-------------------------------------- |
838 /// | 1[63] 11[62-52] 52[51-00] 1023 |
839 /// --------------------------------------
840 double APInt::roundToDouble(bool isSigned) const {
842 // Handle the simple case where the value is contained in one uint64_t.
843 if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
845 int64_t sext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
851 // Determine if the value is negative.
852 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
854 // Construct the absolute value if we're negative.
855 APInt Tmp(isNeg ? -(*this) : (*this));
857 // Figure out how many bits we're using.
858 uint32_t n = Tmp.getActiveBits();
860 // The exponent (without bias normalization) is just the number of bits
861 // we are using. Note that the sign bit is gone since we constructed the
865 // Return infinity for exponent overflow
867 if (!isSigned || !isNeg)
868 return double(1.0E300 * 1.0E300); // positive infinity
870 return double(-1.0E300 * 1.0E300); // negative infinity
872 exp += 1023; // Increment for 1023 bias
874 // Number of bits in mantissa is 52. To obtain the mantissa value, we must
875 // extract the high 52 bits from the correct words in pVal.
877 unsigned hiWord = whichWord(n-1);
879 mantissa = Tmp.pVal[0];
881 mantissa >>= n - 52; // shift down, we want the top 52 bits.
883 assert(hiWord > 0 && "huh?");
884 uint64_t hibits = Tmp.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
885 uint64_t lobits = Tmp.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
886 mantissa = hibits | lobits;
889 // The leading bit of mantissa is implicit, so get rid of it.
890 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
895 T.I = sign | (exp << 52) | mantissa;
899 // Truncate to new width.
900 void APInt::trunc(uint32_t width) {
901 assert(width < BitWidth && "Invalid APInt Truncate request");
902 assert(width >= IntegerType::MIN_INT_BITS && "Can't truncate to 0 bits");
903 uint32_t wordsBefore = getNumWords();
905 uint32_t wordsAfter = getNumWords();
906 if (wordsBefore != wordsAfter) {
907 if (wordsAfter == 1) {
908 uint64_t *tmp = pVal;
912 uint64_t *newVal = getClearedMemory(wordsAfter);
913 for (uint32_t i = 0; i < wordsAfter; ++i)
922 // Sign extend to a new width.
923 void APInt::sext(uint32_t width) {
924 assert(width > BitWidth && "Invalid APInt SignExtend request");
925 assert(width <= IntegerType::MAX_INT_BITS && "Too many bits");
926 // If the sign bit isn't set, this is the same as zext.
932 // The sign bit is set. First, get some facts
933 uint32_t wordsBefore = getNumWords();
934 uint32_t wordBits = BitWidth % APINT_BITS_PER_WORD;
936 uint32_t wordsAfter = getNumWords();
938 // Mask the high order word appropriately
939 if (wordsBefore == wordsAfter) {
940 uint32_t newWordBits = width % APINT_BITS_PER_WORD;
941 // The extension is contained to the wordsBefore-1th word.
942 uint64_t mask = (~0ULL >> (APINT_BITS_PER_WORD - newWordBits)) << wordBits;
943 if (wordsBefore == 1)
946 pVal[wordsBefore-1] |= mask;
951 uint64_t mask = wordBits == 0 ? 0 : ~0ULL << wordBits;
952 uint64_t *newVal = getMemory(wordsAfter);
953 if (wordsBefore == 1)
954 newVal[0] = VAL | mask;
956 for (uint32_t i = 0; i < wordsBefore; ++i)
958 newVal[wordsBefore-1] |= mask;
960 for (uint32_t i = wordsBefore; i < wordsAfter; i++)
962 if (wordsBefore != 1)
968 // Zero extend to a new width.
969 void APInt::zext(uint32_t width) {
970 assert(width > BitWidth && "Invalid APInt ZeroExtend request");
971 assert(width <= IntegerType::MAX_INT_BITS && "Too many bits");
972 uint32_t wordsBefore = getNumWords();
974 uint32_t wordsAfter = getNumWords();
975 if (wordsBefore != wordsAfter) {
976 uint64_t *newVal = getClearedMemory(wordsAfter);
977 if (wordsBefore == 1)
980 for (uint32_t i = 0; i < wordsBefore; ++i)
982 if (wordsBefore != 1)
988 /// Arithmetic right-shift this APInt by shiftAmt.
989 /// @brief Arithmetic right-shift function.
990 APInt APInt::ashr(uint32_t shiftAmt) const {
991 assert(shiftAmt <= BitWidth && "Invalid shift amount");
992 if (isSingleWord()) {
993 if (shiftAmt == BitWidth)
994 return APInt(BitWidth, 0); // undefined
996 uint32_t SignBit = APINT_BITS_PER_WORD - BitWidth;
997 return APInt(BitWidth,
998 (((int64_t(VAL) << SignBit) >> SignBit) >> shiftAmt));
1002 // If all the bits were shifted out, the result is 0 or -1. This avoids issues
1003 // with shifting by the size of the integer type, which produces undefined
1005 if (shiftAmt == BitWidth)
1007 return APInt(BitWidth, -1ULL);
1009 return APInt(BitWidth, 0);
1011 // Create some space for the result.
1012 uint64_t * val = new uint64_t[getNumWords()];
1014 // If we are shifting less than a word, compute the shift with a simple carry
1015 if (shiftAmt < APINT_BITS_PER_WORD) {
1017 for (int i = getNumWords()-1; i >= 0; --i) {
1018 val[i] = pVal[i] >> shiftAmt | carry;
1019 carry = pVal[i] << (APINT_BITS_PER_WORD - shiftAmt);
1021 return APInt(val, BitWidth).clearUnusedBits();
1024 // Compute some values needed by the remaining shift algorithms
1025 uint32_t wordShift = shiftAmt % APINT_BITS_PER_WORD;
1026 uint32_t offset = shiftAmt / APINT_BITS_PER_WORD;
1028 // If we are shifting whole words, just move whole words
1029 if (wordShift == 0) {
1030 for (uint32_t i = 0; i < getNumWords() - offset; ++i)
1031 val[i] = pVal[i+offset];
1032 for (uint32_t i = getNumWords()-offset; i < getNumWords(); i++)
1033 val[i] = (isNegative() ? -1ULL : 0);
1034 return APInt(val,BitWidth).clearUnusedBits();
1037 // Shift the low order words
1038 uint32_t breakWord = getNumWords() - offset -1;
1039 for (uint32_t i = 0; i < breakWord; ++i)
1040 val[i] = pVal[i+offset] >> wordShift |
1041 pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift);
1042 // Shift the break word.
1043 uint32_t SignBit = APINT_BITS_PER_WORD - (BitWidth % APINT_BITS_PER_WORD);
1044 val[breakWord] = uint64_t(
1045 (((int64_t(pVal[breakWord+offset]) << SignBit) >> SignBit) >> wordShift));
1047 // Remaining words are 0 or -1
1048 for (uint32_t i = breakWord+1; i < getNumWords(); ++i)
1049 val[i] = (isNegative() ? -1ULL : 0);
1050 return APInt(val, BitWidth).clearUnusedBits();
1053 /// Logical right-shift this APInt by shiftAmt.
1054 /// @brief Logical right-shift function.
1055 APInt APInt::lshr(uint32_t shiftAmt) const {
1057 if (shiftAmt == BitWidth)
1058 return APInt(BitWidth, 0);
1060 return APInt(BitWidth, this->VAL >> shiftAmt);
1062 // If all the bits were shifted out, the result is 0. This avoids issues
1063 // with shifting by the size of the integer type, which produces undefined
1064 // results. We define these "undefined results" to always be 0.
1065 if (shiftAmt == BitWidth)
1066 return APInt(BitWidth, 0);
1068 // Create some space for the result.
1069 uint64_t * val = new uint64_t[getNumWords()];
1071 // If we are shifting less than a word, compute the shift with a simple carry
1072 if (shiftAmt < APINT_BITS_PER_WORD) {
1074 for (int i = getNumWords()-1; i >= 0; --i) {
1075 val[i] = pVal[i] >> shiftAmt | carry;
1076 carry = pVal[i] << (APINT_BITS_PER_WORD - shiftAmt);
1078 return APInt(val, BitWidth).clearUnusedBits();
1081 // Compute some values needed by the remaining shift algorithms
1082 uint32_t wordShift = shiftAmt % APINT_BITS_PER_WORD;
1083 uint32_t offset = shiftAmt / APINT_BITS_PER_WORD;
1085 // If we are shifting whole words, just move whole words
1086 if (wordShift == 0) {
1087 for (uint32_t i = 0; i < getNumWords() - offset; ++i)
1088 val[i] = pVal[i+offset];
1089 for (uint32_t i = getNumWords()-offset; i < getNumWords(); i++)
1091 return APInt(val,BitWidth).clearUnusedBits();
1094 // Shift the low order words
1095 uint32_t breakWord = getNumWords() - offset -1;
1096 for (uint32_t i = 0; i < breakWord; ++i)
1097 val[i] = pVal[i+offset] >> wordShift |
1098 pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift);
1099 // Shift the break word.
1100 val[breakWord] = pVal[breakWord+offset] >> wordShift;
1102 // Remaining words are 0
1103 for (uint32_t i = breakWord+1; i < getNumWords(); ++i)
1105 return APInt(val, BitWidth).clearUnusedBits();
1108 /// Left-shift this APInt by shiftAmt.
1109 /// @brief Left-shift function.
1110 APInt APInt::shl(uint32_t shiftAmt) const {
1111 assert(shiftAmt <= BitWidth && "Invalid shift amount");
1112 if (isSingleWord()) {
1113 if (shiftAmt == BitWidth)
1114 return APInt(BitWidth, 0); // avoid undefined shift results
1115 return APInt(BitWidth, VAL << shiftAmt);
1118 // If all the bits were shifted out, the result is 0. This avoids issues
1119 // with shifting by the size of the integer type, which produces undefined
1120 // results. We define these "undefined results" to always be 0.
1121 if (shiftAmt == BitWidth)
1122 return APInt(BitWidth, 0);
1124 // Create some space for the result.
1125 uint64_t * val = new uint64_t[getNumWords()];
1127 // If we are shifting less than a word, do it the easy way
1128 if (shiftAmt < APINT_BITS_PER_WORD) {
1130 for (uint32_t i = 0; i < getNumWords(); i++) {
1131 val[i] = pVal[i] << shiftAmt | carry;
1132 carry = pVal[i] >> (APINT_BITS_PER_WORD - shiftAmt);
1134 return APInt(val, BitWidth).clearUnusedBits();
1137 // Compute some values needed by the remaining shift algorithms
1138 uint32_t wordShift = shiftAmt % APINT_BITS_PER_WORD;
1139 uint32_t offset = shiftAmt / APINT_BITS_PER_WORD;
1141 // If we are shifting whole words, just move whole words
1142 if (wordShift == 0) {
1143 for (uint32_t i = 0; i < offset; i++)
1145 for (uint32_t i = offset; i < getNumWords(); i++)
1146 val[i] = pVal[i-offset];
1147 return APInt(val,BitWidth).clearUnusedBits();
1150 // Copy whole words from this to Result.
1151 uint32_t i = getNumWords() - 1;
1152 for (; i > offset; --i)
1153 val[i] = pVal[i-offset] << wordShift |
1154 pVal[i-offset-1] >> (APINT_BITS_PER_WORD - wordShift);
1155 val[offset] = pVal[0] << wordShift;
1156 for (i = 0; i < offset; ++i)
1158 return APInt(val, BitWidth).clearUnusedBits();
1161 /// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
1162 /// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
1163 /// variables here have the same names as in the algorithm. Comments explain
1164 /// the algorithm and any deviation from it.
1165 static void KnuthDiv(uint32_t *u, uint32_t *v, uint32_t *q, uint32_t* r,
1166 uint32_t m, uint32_t n) {
1167 assert(u && "Must provide dividend");
1168 assert(v && "Must provide divisor");
1169 assert(q && "Must provide quotient");
1170 assert(u != v && u != q && v != q && "Must us different memory");
1171 assert(n>1 && "n must be > 1");
1173 // Knuth uses the value b as the base of the number system. In our case b
1174 // is 2^31 so we just set it to -1u.
1175 uint64_t b = uint64_t(1) << 32;
1177 DEBUG(cerr << "KnuthDiv: m=" << m << " n=" << n << '\n');
1178 DEBUG(cerr << "KnuthDiv: original:");
1179 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << std::setbase(16) << u[i]);
1180 DEBUG(cerr << " by");
1181 DEBUG(for (int i = n; i >0; i--) cerr << " " << std::setbase(16) << v[i-1]);
1182 DEBUG(cerr << '\n');
1183 // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
1184 // u and v by d. Note that we have taken Knuth's advice here to use a power
1185 // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
1186 // 2 allows us to shift instead of multiply and it is easy to determine the
1187 // shift amount from the leading zeros. We are basically normalizing the u
1188 // and v so that its high bits are shifted to the top of v's range without
1189 // overflow. Note that this can require an extra word in u so that u must
1190 // be of length m+n+1.
1191 uint32_t shift = CountLeadingZeros_32(v[n-1]);
1192 uint32_t v_carry = 0;
1193 uint32_t u_carry = 0;
1195 for (uint32_t i = 0; i < m+n; ++i) {
1196 uint32_t u_tmp = u[i] >> (32 - shift);
1197 u[i] = (u[i] << shift) | u_carry;
1200 for (uint32_t i = 0; i < n; ++i) {
1201 uint32_t v_tmp = v[i] >> (32 - shift);
1202 v[i] = (v[i] << shift) | v_carry;
1207 DEBUG(cerr << "KnuthDiv: normal:");
1208 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << std::setbase(16) << u[i]);
1209 DEBUG(cerr << " by");
1210 DEBUG(for (int i = n; i >0; i--) cerr << " " << std::setbase(16) << v[i-1]);
1211 DEBUG(cerr << '\n');
1213 // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
1216 DEBUG(cerr << "KnuthDiv: quotient digit #" << j << '\n');
1217 // D3. [Calculate q'.].
1218 // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
1219 // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
1220 // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
1221 // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test
1222 // on v[n-2] determines at high speed most of the cases in which the trial
1223 // value qp is one too large, and it eliminates all cases where qp is two
1225 uint64_t dividend = ((uint64_t(u[j+n]) << 32) + u[j+n-1]);
1226 DEBUG(cerr << "KnuthDiv: dividend == " << dividend << '\n');
1227 uint64_t qp = dividend / v[n-1];
1228 uint64_t rp = dividend % v[n-1];
1229 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1232 if (rp < b && (qp == b || qp*v[n-2] > b*rp + u[j+n-2]))
1235 DEBUG(cerr << "KnuthDiv: qp == " << qp << ", rp == " << rp << '\n');
1237 // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with
1238 // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation
1239 // consists of a simple multiplication by a one-place number, combined with
1242 for (uint32_t i = 0; i < n; ++i) {
1243 uint64_t u_tmp = uint64_t(u[j+i]) | (uint64_t(u[j+i+1]) << 32);
1244 uint64_t subtrahend = uint64_t(qp) * uint64_t(v[i]);
1245 bool borrow = subtrahend > u_tmp;
1246 DEBUG(cerr << "KnuthDiv: u_tmp == " << u_tmp
1247 << ", subtrahend == " << subtrahend
1248 << ", borrow = " << borrow << '\n');
1250 uint64_t result = u_tmp - subtrahend;
1252 u[k++] = result & (b-1); // subtract low word
1253 u[k++] = result >> 32; // subtract high word
1254 while (borrow && k <= m+n) { // deal with borrow to the left
1260 DEBUG(cerr << "KnuthDiv: u[j+i] == " << u[j+i] << ", u[j+i+1] == " <<
1263 DEBUG(cerr << "KnuthDiv: after subtraction:");
1264 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << u[i]);
1265 DEBUG(cerr << '\n');
1266 // The digits (u[j+n]...u[j]) should be kept positive; if the result of
1267 // this step is actually negative, (u[j+n]...u[j]) should be left as the
1268 // true value plus b**(n+1), namely as the b's complement of
1269 // the true value, and a "borrow" to the left should be remembered.
1272 bool carry = true; // true because b's complement is "complement + 1"
1273 for (uint32_t i = 0; i <= m+n; ++i) {
1274 u[i] = ~u[i] + carry; // b's complement
1275 carry = carry && u[i] == 0;
1278 DEBUG(cerr << "KnuthDiv: after complement:");
1279 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << u[i]);
1280 DEBUG(cerr << '\n');
1282 // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
1283 // negative, go to step D6; otherwise go on to step D7.
1286 // D6. [Add back]. The probability that this step is necessary is very
1287 // small, on the order of only 2/b. Make sure that test data accounts for
1288 // this possibility. Decrease q[j] by 1
1290 // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]).
1291 // A carry will occur to the left of u[j+n], and it should be ignored
1292 // since it cancels with the borrow that occurred in D4.
1294 for (uint32_t i = 0; i < n; i++) {
1295 uint32_t limit = std::min(u[j+i],v[i]);
1296 u[j+i] += v[i] + carry;
1297 carry = u[j+i] < limit || (carry && u[j+i] == limit);
1301 DEBUG(cerr << "KnuthDiv: after correction:");
1302 DEBUG(for (int i = m+n; i >=0; i--) cerr <<" " << u[i]);
1303 DEBUG(cerr << "\nKnuthDiv: digit result = " << q[j] << '\n');
1305 // D7. [Loop on j.] Decrease j by one. Now if j >= 0, go back to D3.
1308 DEBUG(cerr << "KnuthDiv: quotient:");
1309 DEBUG(for (int i = m; i >=0; i--) cerr <<" " << q[i]);
1310 DEBUG(cerr << '\n');
1312 // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
1313 // remainder may be obtained by dividing u[...] by d. If r is non-null we
1314 // compute the remainder (urem uses this).
1316 // The value d is expressed by the "shift" value above since we avoided
1317 // multiplication by d by using a shift left. So, all we have to do is
1318 // shift right here. In order to mak
1321 DEBUG(cerr << "KnuthDiv: remainder:");
1322 for (int i = n-1; i >= 0; i--) {
1323 r[i] = (u[i] >> shift) | carry;
1324 carry = u[i] << (32 - shift);
1325 DEBUG(cerr << " " << r[i]);
1328 for (int i = n-1; i >= 0; i--) {
1330 DEBUG(cerr << " " << r[i]);
1333 DEBUG(cerr << '\n');
1335 DEBUG(cerr << std::setbase(10) << '\n');
1338 void APInt::divide(const APInt LHS, uint32_t lhsWords,
1339 const APInt &RHS, uint32_t rhsWords,
1340 APInt *Quotient, APInt *Remainder)
1342 assert(lhsWords >= rhsWords && "Fractional result");
1344 // First, compose the values into an array of 32-bit words instead of
1345 // 64-bit words. This is a necessity of both the "short division" algorithm
1346 // and the the Knuth "classical algorithm" which requires there to be native
1347 // operations for +, -, and * on an m bit value with an m*2 bit result. We
1348 // can't use 64-bit operands here because we don't have native results of
1349 // 128-bits. Furthremore, casting the 64-bit values to 32-bit values won't
1350 // work on large-endian machines.
1351 uint64_t mask = ~0ull >> (sizeof(uint32_t)*8);
1352 uint32_t n = rhsWords * 2;
1353 uint32_t m = (lhsWords * 2) - n;
1355 // Allocate space for the temporary values we need either on the stack, if
1356 // it will fit, or on the heap if it won't.
1357 uint32_t SPACE[128];
1362 if ((Remainder?4:3)*n+2*m+1 <= 128) {
1365 Q = &SPACE[(m+n+1) + n];
1367 R = &SPACE[(m+n+1) + n + (m+n)];
1369 U = new uint32_t[m + n + 1];
1370 V = new uint32_t[n];
1371 Q = new uint32_t[m+n];
1373 R = new uint32_t[n];
1376 // Initialize the dividend
1377 memset(U, 0, (m+n+1)*sizeof(uint32_t));
1378 for (unsigned i = 0; i < lhsWords; ++i) {
1379 uint64_t tmp = (LHS.getNumWords() == 1 ? LHS.VAL : LHS.pVal[i]);
1380 U[i * 2] = tmp & mask;
1381 U[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1383 U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
1385 // Initialize the divisor
1386 memset(V, 0, (n)*sizeof(uint32_t));
1387 for (unsigned i = 0; i < rhsWords; ++i) {
1388 uint64_t tmp = (RHS.getNumWords() == 1 ? RHS.VAL : RHS.pVal[i]);
1389 V[i * 2] = tmp & mask;
1390 V[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1393 // initialize the quotient and remainder
1394 memset(Q, 0, (m+n) * sizeof(uint32_t));
1396 memset(R, 0, n * sizeof(uint32_t));
1398 // Now, adjust m and n for the Knuth division. n is the number of words in
1399 // the divisor. m is the number of words by which the dividend exceeds the
1400 // divisor (i.e. m+n is the length of the dividend). These sizes must not
1401 // contain any zero words or the Knuth algorithm fails.
1402 for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
1406 for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
1409 // If we're left with only a single word for the divisor, Knuth doesn't work
1410 // so we implement the short division algorithm here. This is much simpler
1411 // and faster because we are certain that we can divide a 64-bit quantity
1412 // by a 32-bit quantity at hardware speed and short division is simply a
1413 // series of such operations. This is just like doing short division but we
1414 // are using base 2^32 instead of base 10.
1415 assert(n != 0 && "Divide by zero?");
1417 uint32_t divisor = V[0];
1418 uint32_t remainder = 0;
1419 for (int i = m+n-1; i >= 0; i--) {
1420 uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i];
1421 if (partial_dividend == 0) {
1424 } else if (partial_dividend < divisor) {
1426 remainder = partial_dividend;
1427 } else if (partial_dividend == divisor) {
1431 Q[i] = partial_dividend / divisor;
1432 remainder = partial_dividend - (Q[i] * divisor);
1438 // Now we're ready to invoke the Knuth classical divide algorithm. In this
1440 KnuthDiv(U, V, Q, R, m, n);
1443 // If the caller wants the quotient
1445 // Set up the Quotient value's memory.
1446 if (Quotient->BitWidth != LHS.BitWidth) {
1447 if (Quotient->isSingleWord())
1450 delete [] Quotient->pVal;
1451 Quotient->BitWidth = LHS.BitWidth;
1452 if (!Quotient->isSingleWord())
1453 Quotient->pVal = getClearedMemory(Quotient->getNumWords());
1457 // The quotient is in Q. Reconstitute the quotient into Quotient's low
1459 if (lhsWords == 1) {
1461 uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2));
1462 if (Quotient->isSingleWord())
1463 Quotient->VAL = tmp;
1465 Quotient->pVal[0] = tmp;
1467 assert(!Quotient->isSingleWord() && "Quotient APInt not large enough");
1468 for (unsigned i = 0; i < lhsWords; ++i)
1470 uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1474 // If the caller wants the remainder
1476 // Set up the Remainder value's memory.
1477 if (Remainder->BitWidth != RHS.BitWidth) {
1478 if (Remainder->isSingleWord())
1481 delete [] Remainder->pVal;
1482 Remainder->BitWidth = RHS.BitWidth;
1483 if (!Remainder->isSingleWord())
1484 Remainder->pVal = getClearedMemory(Remainder->getNumWords());
1488 // The remainder is in R. Reconstitute the remainder into Remainder's low
1490 if (rhsWords == 1) {
1492 uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2));
1493 if (Remainder->isSingleWord())
1494 Remainder->VAL = tmp;
1496 Remainder->pVal[0] = tmp;
1498 assert(!Remainder->isSingleWord() && "Remainder APInt not large enough");
1499 for (unsigned i = 0; i < rhsWords; ++i)
1500 Remainder->pVal[i] =
1501 uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1505 // Clean up the memory we allocated.
1506 if (U != &SPACE[0]) {
1514 APInt APInt::udiv(const APInt& RHS) const {
1515 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1517 // First, deal with the easy case
1518 if (isSingleWord()) {
1519 assert(RHS.VAL != 0 && "Divide by zero?");
1520 return APInt(BitWidth, VAL / RHS.VAL);
1523 // Get some facts about the LHS and RHS number of bits and words
1524 uint32_t rhsBits = RHS.getActiveBits();
1525 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
1526 assert(rhsWords && "Divided by zero???");
1527 uint32_t lhsBits = this->getActiveBits();
1528 uint32_t lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
1530 // Deal with some degenerate cases
1533 return APInt(BitWidth, 0);
1534 else if (lhsWords < rhsWords || this->ult(RHS)) {
1535 // X / Y ===> 0, iff X < Y
1536 return APInt(BitWidth, 0);
1537 } else if (*this == RHS) {
1539 return APInt(BitWidth, 1);
1540 } else if (lhsWords == 1 && rhsWords == 1) {
1541 // All high words are zero, just use native divide
1542 return APInt(BitWidth, this->pVal[0] / RHS.pVal[0]);
1545 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1546 APInt Quotient(1,0); // to hold result.
1547 divide(*this, lhsWords, RHS, rhsWords, &Quotient, 0);
1551 APInt APInt::urem(const APInt& RHS) const {
1552 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1553 if (isSingleWord()) {
1554 assert(RHS.VAL != 0 && "Remainder by zero?");
1555 return APInt(BitWidth, VAL % RHS.VAL);
1558 // Get some facts about the LHS
1559 uint32_t lhsBits = getActiveBits();
1560 uint32_t lhsWords = !lhsBits ? 0 : (whichWord(lhsBits - 1) + 1);
1562 // Get some facts about the RHS
1563 uint32_t rhsBits = RHS.getActiveBits();
1564 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
1565 assert(rhsWords && "Performing remainder operation by zero ???");
1567 // Check the degenerate cases
1568 if (lhsWords == 0) {
1570 return APInt(BitWidth, 0);
1571 } else if (lhsWords < rhsWords || this->ult(RHS)) {
1572 // X % Y ===> X, iff X < Y
1574 } else if (*this == RHS) {
1576 return APInt(BitWidth, 0);
1577 } else if (lhsWords == 1) {
1578 // All high words are zero, just use native remainder
1579 return APInt(BitWidth, pVal[0] % RHS.pVal[0]);
1582 // We have to compute it the hard way. Invoke the Knute divide algorithm.
1583 APInt Remainder(1,0);
1584 divide(*this, lhsWords, RHS, rhsWords, 0, &Remainder);
1588 void APInt::fromString(uint32_t numbits, const char *str, uint32_t slen,
1590 // Check our assumptions here
1591 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1592 "Radix should be 2, 8, 10, or 16!");
1593 assert(str && "String is null?");
1594 bool isNeg = str[0] == '-';
1597 assert(slen <= numbits || radix != 2 && "Insufficient bit width");
1598 assert(slen*3 <= numbits || radix != 8 && "Insufficient bit width");
1599 assert(slen*4 <= numbits || radix != 16 && "Insufficient bit width");
1600 assert((slen*64)/20 <= numbits || radix != 10 && "Insufficient bit width");
1603 if (!isSingleWord())
1604 pVal = getClearedMemory(getNumWords());
1606 // Figure out if we can shift instead of multiply
1607 uint32_t shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0);
1609 // Set up an APInt for the digit to add outside the loop so we don't
1610 // constantly construct/destruct it.
1611 APInt apdigit(getBitWidth(), 0);
1612 APInt apradix(getBitWidth(), radix);
1614 // Enter digit traversal loop
1615 for (unsigned i = 0; i < slen; i++) {
1618 char cdigit = str[i];
1619 if (isdigit(cdigit))
1620 digit = cdigit - '0';
1621 else if (isxdigit(cdigit))
1623 digit = cdigit - 'a' + 10;
1624 else if (cdigit >= 'A')
1625 digit = cdigit - 'A' + 10;
1627 assert(0 && "huh?");
1629 assert(0 && "Invalid character in digit string");
1631 // Shift or multiple the value by the radix
1637 // Add in the digit we just interpreted
1638 if (apdigit.isSingleWord())
1639 apdigit.VAL = digit;
1641 apdigit.pVal[0] = digit;
1644 // If its negative, put it in two's complement form
1651 std::string APInt::toString(uint8_t radix, bool wantSigned) const {
1652 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1653 "Radix should be 2, 8, 10, or 16!");
1654 static const char *digits[] = {
1655 "0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"
1658 uint32_t bits_used = getActiveBits();
1659 if (isSingleWord()) {
1661 const char *format = (radix == 10 ? (wantSigned ? "%lld" : "%llu") :
1662 (radix == 16 ? "%llX" : (radix == 8 ? "%llo" : 0)));
1665 int64_t sextVal = (int64_t(VAL) << (APINT_BITS_PER_WORD-BitWidth)) >>
1666 (APINT_BITS_PER_WORD-BitWidth);
1667 sprintf(buf, format, sextVal);
1669 sprintf(buf, format, VAL);
1674 uint32_t bit = v & 1;
1676 buf[bits_used] = digits[bit][0];
1685 uint64_t mask = radix - 1;
1686 uint32_t shift = (radix == 16 ? 4 : radix == 8 ? 3 : 1);
1687 uint32_t nibbles = APINT_BITS_PER_WORD / shift;
1688 for (uint32_t i = 0; i < getNumWords(); ++i) {
1689 uint64_t value = pVal[i];
1690 for (uint32_t j = 0; j < nibbles; ++j) {
1691 result.insert(0, digits[ value & mask ]);
1699 APInt divisor(4, radix);
1700 APInt zero(tmp.getBitWidth(), 0);
1701 size_t insert_at = 0;
1702 if (wantSigned && tmp[BitWidth-1]) {
1703 // They want to print the signed version and it is a negative value
1704 // Flip the bits and add one to turn it into the equivalent positive
1705 // value and put a '-' in the result.
1711 if (tmp == APInt(tmp.getBitWidth(), 0))
1713 else while (tmp.ne(zero)) {
1715 APInt tmp2(tmp.getBitWidth(), 0);
1716 divide(tmp, tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2,
1718 uint32_t digit = APdigit.getZExtValue();
1719 assert(digit < radix && "divide failed");
1720 result.insert(insert_at,digits[digit]);
1728 void APInt::dump() const
1730 cerr << "APInt(" << BitWidth << ")=" << std::setbase(16);
1733 else for (unsigned i = getNumWords(); i > 0; i--) {
1734 cerr << pVal[i-1] << " ";
1736 cerr << " U(" << this->toString(10) << ") S(" << this->toStringSigned(10)
1737 << ")\n" << std::setbase(10);