1 //===-- APInt.cpp - Implement APInt class ---------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Sheng Zhou and Reid Spencer and is distributed
6 // under the // University of Illinois Open Source License. See LICENSE.TXT
9 //===----------------------------------------------------------------------===//
11 // This file implements a class to represent arbitrary precision integer
12 // constant values and provide a variety of arithmetic operations on them.
14 //===----------------------------------------------------------------------===//
17 #define DEBUG_TYPE "apint"
18 #include "llvm/ADT/APInt.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/MathExtras.h"
30 /// A utility function for allocating memory, checking for allocation failures,
31 /// and ensuring the contents are zeroed.
32 inline static uint64_t* getClearedMemory(uint32_t numWords) {
33 uint64_t * result = new uint64_t[numWords];
34 assert(result && "APInt memory allocation fails!");
35 memset(result, 0, numWords * sizeof(uint64_t));
39 /// A utility function for allocating memory and checking for allocation
40 /// failure. The content is not zeroed.
41 inline static uint64_t* getMemory(uint32_t numWords) {
42 uint64_t * result = new uint64_t[numWords];
43 assert(result && "APInt memory allocation fails!");
47 APInt::APInt(uint32_t numBits, uint64_t val)
48 : BitWidth(numBits), VAL(0) {
49 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
50 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
54 pVal = getClearedMemory(getNumWords());
60 APInt::APInt(uint32_t numBits, uint32_t numWords, uint64_t bigVal[])
61 : BitWidth(numBits), VAL(0) {
62 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
63 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
64 assert(bigVal && "Null pointer detected!");
68 // Get memory, cleared to 0
69 pVal = getClearedMemory(getNumWords());
70 // Calculate the number of words to copy
71 uint32_t words = std::min<uint32_t>(numWords, getNumWords());
72 // Copy the words from bigVal to pVal
73 memcpy(pVal, bigVal, words * APINT_WORD_SIZE);
75 // Make sure unused high bits are cleared
79 APInt::APInt(uint32_t numbits, const char StrStart[], uint32_t slen,
81 : BitWidth(numbits), VAL(0) {
82 fromString(numbits, StrStart, slen, radix);
85 APInt::APInt(uint32_t numbits, const std::string& Val, uint8_t radix)
86 : BitWidth(numbits), VAL(0) {
87 assert(!Val.empty() && "String empty?");
88 fromString(numbits, Val.c_str(), Val.size(), radix);
91 APInt::APInt(const APInt& that)
92 : BitWidth(that.BitWidth), VAL(0) {
96 pVal = getMemory(getNumWords());
97 memcpy(pVal, that.pVal, getNumWords() * APINT_WORD_SIZE);
102 if (!isSingleWord() && pVal)
106 APInt& APInt::operator=(const APInt& RHS) {
107 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
111 memcpy(pVal, RHS.pVal, getNumWords() * APINT_WORD_SIZE);
115 APInt& APInt::operator=(uint64_t RHS) {
120 memset(pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
125 /// add_1 - This function adds a single "digit" integer, y, to the multiple
126 /// "digit" integer array, x[]. x[] is modified to reflect the addition and
127 /// 1 is returned if there is a carry out, otherwise 0 is returned.
128 /// @returns the carry of the addition.
129 static bool add_1(uint64_t dest[], uint64_t x[], uint32_t len, uint64_t y) {
130 for (uint32_t i = 0; i < len; ++i) {
133 y = 1; // Carry one to next digit.
135 y = 0; // No need to carry so exit early
142 /// @brief Prefix increment operator. Increments the APInt by one.
143 APInt& APInt::operator++() {
147 add_1(pVal, pVal, getNumWords(), 1);
148 return clearUnusedBits();
151 /// sub_1 - This function subtracts a single "digit" (64-bit word), y, from
152 /// the multi-digit integer array, x[], propagating the borrowed 1 value until
153 /// no further borrowing is neeeded or it runs out of "digits" in x. The result
154 /// is 1 if "borrowing" exhausted the digits in x, or 0 if x was not exhausted.
155 /// In other words, if y > x then this function returns 1, otherwise 0.
156 /// @returns the borrow out of the subtraction
157 static bool sub_1(uint64_t x[], uint32_t len, uint64_t y) {
158 for (uint32_t i = 0; i < len; ++i) {
162 y = 1; // We have to "borrow 1" from next "digit"
164 y = 0; // No need to borrow
165 break; // Remaining digits are unchanged so exit early
171 /// @brief Prefix decrement operator. Decrements the APInt by one.
172 APInt& APInt::operator--() {
176 sub_1(pVal, getNumWords(), 1);
177 return clearUnusedBits();
180 /// add - This function adds the integer array x to the integer array Y and
181 /// places the result in dest.
182 /// @returns the carry out from the addition
183 /// @brief General addition of 64-bit integer arrays
184 static bool add(uint64_t *dest, const uint64_t *x, const uint64_t *y,
187 for (uint32_t i = 0; i< len; ++i) {
188 uint64_t limit = std::min(x[i],y[i]); // must come first in case dest == x
189 dest[i] = x[i] + y[i] + carry;
190 carry = dest[i] < limit || (carry && dest[i] == limit);
195 /// Adds the RHS APint to this APInt.
196 /// @returns this, after addition of RHS.
197 /// @brief Addition assignment operator.
198 APInt& APInt::operator+=(const APInt& RHS) {
199 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
203 add(pVal, pVal, RHS.pVal, getNumWords());
205 return clearUnusedBits();
208 /// Subtracts the integer array y from the integer array x
209 /// @returns returns the borrow out.
210 /// @brief Generalized subtraction of 64-bit integer arrays.
211 static bool sub(uint64_t *dest, const uint64_t *x, const uint64_t *y,
214 for (uint32_t i = 0; i < len; ++i) {
215 uint64_t x_tmp = borrow ? x[i] - 1 : x[i];
216 borrow = y[i] > x_tmp || (borrow && x[i] == 0);
217 dest[i] = x_tmp - y[i];
222 /// Subtracts the RHS APInt from this APInt
223 /// @returns this, after subtraction
224 /// @brief Subtraction assignment operator.
225 APInt& APInt::operator-=(const APInt& RHS) {
226 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
230 sub(pVal, pVal, RHS.pVal, getNumWords());
231 return clearUnusedBits();
234 /// Multiplies an integer array, x by a a uint64_t integer and places the result
236 /// @returns the carry out of the multiplication.
237 /// @brief Multiply a multi-digit APInt by a single digit (64-bit) integer.
238 static uint64_t mul_1(uint64_t dest[], uint64_t x[], uint32_t len, uint64_t y) {
239 // Split y into high 32-bit part (hy) and low 32-bit part (ly)
240 uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
243 // For each digit of x.
244 for (uint32_t i = 0; i < len; ++i) {
245 // Split x into high and low words
246 uint64_t lx = x[i] & 0xffffffffULL;
247 uint64_t hx = x[i] >> 32;
248 // hasCarry - A flag to indicate if there is a carry to the next digit.
249 // hasCarry == 0, no carry
250 // hasCarry == 1, has carry
251 // hasCarry == 2, no carry and the calculation result == 0.
252 uint8_t hasCarry = 0;
253 dest[i] = carry + lx * ly;
254 // Determine if the add above introduces carry.
255 hasCarry = (dest[i] < carry) ? 1 : 0;
256 carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
257 // The upper limit of carry can be (2^32 - 1)(2^32 - 1) +
258 // (2^32 - 1) + 2^32 = 2^64.
259 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
261 carry += (lx * hy) & 0xffffffffULL;
262 dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
263 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) +
264 (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
269 /// Multiplies integer array x by integer array y and stores the result into
270 /// the integer array dest. Note that dest's size must be >= xlen + ylen.
271 /// @brief Generalized multiplicate of integer arrays.
272 static void mul(uint64_t dest[], uint64_t x[], uint32_t xlen, uint64_t y[],
274 dest[xlen] = mul_1(dest, x, xlen, y[0]);
275 for (uint32_t i = 1; i < ylen; ++i) {
276 uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
277 uint64_t carry = 0, lx = 0, hx = 0;
278 for (uint32_t j = 0; j < xlen; ++j) {
279 lx = x[j] & 0xffffffffULL;
281 // hasCarry - A flag to indicate if has carry.
282 // hasCarry == 0, no carry
283 // hasCarry == 1, has carry
284 // hasCarry == 2, no carry and the calculation result == 0.
285 uint8_t hasCarry = 0;
286 uint64_t resul = carry + lx * ly;
287 hasCarry = (resul < carry) ? 1 : 0;
288 carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
289 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
291 carry += (lx * hy) & 0xffffffffULL;
292 resul = (carry << 32) | (resul & 0xffffffffULL);
294 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
295 (carry >> 32) + (dest[i+j] < resul ? 1 : 0) +
296 ((lx * hy) >> 32) + hx * hy;
298 dest[i+xlen] = carry;
302 APInt& APInt::operator*=(const APInt& RHS) {
303 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
304 if (isSingleWord()) {
310 // Get some bit facts about LHS and check for zero
311 uint32_t lhsBits = getActiveBits();
312 uint32_t lhsWords = !lhsBits ? 0 : whichWord(lhsBits - 1) + 1;
317 // Get some bit facts about RHS and check for zero
318 uint32_t rhsBits = RHS.getActiveBits();
319 uint32_t rhsWords = !rhsBits ? 0 : whichWord(rhsBits - 1) + 1;
326 // Allocate space for the result
327 uint32_t destWords = rhsWords + lhsWords;
328 uint64_t *dest = getMemory(destWords);
330 // Perform the long multiply
331 mul(dest, pVal, lhsWords, RHS.pVal, rhsWords);
333 // Copy result back into *this
335 uint32_t wordsToCopy = destWords >= getNumWords() ? getNumWords() : destWords;
336 memcpy(pVal, dest, wordsToCopy * APINT_WORD_SIZE);
338 // delete dest array and return
343 APInt& APInt::operator&=(const APInt& RHS) {
344 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
345 if (isSingleWord()) {
349 uint32_t numWords = getNumWords();
350 for (uint32_t i = 0; i < numWords; ++i)
351 pVal[i] &= RHS.pVal[i];
355 APInt& APInt::operator|=(const APInt& RHS) {
356 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
357 if (isSingleWord()) {
361 uint32_t numWords = getNumWords();
362 for (uint32_t i = 0; i < numWords; ++i)
363 pVal[i] |= RHS.pVal[i];
367 APInt& APInt::operator^=(const APInt& RHS) {
368 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
369 if (isSingleWord()) {
371 this->clearUnusedBits();
374 uint32_t numWords = getNumWords();
375 for (uint32_t i = 0; i < numWords; ++i)
376 pVal[i] ^= RHS.pVal[i];
377 return clearUnusedBits();
380 APInt APInt::operator&(const APInt& RHS) const {
381 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
383 return APInt(getBitWidth(), VAL & RHS.VAL);
385 uint32_t numWords = getNumWords();
386 uint64_t* val = getMemory(numWords);
387 for (uint32_t i = 0; i < numWords; ++i)
388 val[i] = pVal[i] & RHS.pVal[i];
389 return APInt(val, getBitWidth());
392 APInt APInt::operator|(const APInt& RHS) const {
393 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
395 return APInt(getBitWidth(), VAL | RHS.VAL);
397 uint32_t numWords = getNumWords();
398 uint64_t *val = getMemory(numWords);
399 for (uint32_t i = 0; i < numWords; ++i)
400 val[i] = pVal[i] | RHS.pVal[i];
401 return APInt(val, getBitWidth());
404 APInt APInt::operator^(const APInt& RHS) const {
405 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
407 return APInt(BitWidth, VAL ^ RHS.VAL);
409 uint32_t numWords = getNumWords();
410 uint64_t *val = getMemory(numWords);
411 for (uint32_t i = 0; i < numWords; ++i)
412 val[i] = pVal[i] ^ RHS.pVal[i];
414 // 0^0==1 so clear the high bits in case they got set.
415 return APInt(val, getBitWidth()).clearUnusedBits();
418 bool APInt::operator !() const {
422 for (uint32_t i = 0; i < getNumWords(); ++i)
428 APInt APInt::operator*(const APInt& RHS) const {
429 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
431 return APInt(BitWidth, VAL * RHS.VAL);
434 return Result.clearUnusedBits();
437 APInt APInt::operator+(const APInt& RHS) const {
438 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
440 return APInt(BitWidth, VAL + RHS.VAL);
441 APInt Result(BitWidth, 0);
442 add(Result.pVal, this->pVal, RHS.pVal, getNumWords());
443 return Result.clearUnusedBits();
446 APInt APInt::operator-(const APInt& RHS) const {
447 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
449 return APInt(BitWidth, VAL - RHS.VAL);
450 APInt Result(BitWidth, 0);
451 sub(Result.pVal, this->pVal, RHS.pVal, getNumWords());
452 return Result.clearUnusedBits();
455 bool APInt::operator[](uint32_t bitPosition) const {
456 return (maskBit(bitPosition) &
457 (isSingleWord() ? VAL : pVal[whichWord(bitPosition)])) != 0;
460 bool APInt::operator==(const APInt& RHS) const {
462 return VAL == RHS.VAL;
464 // Get some facts about the number of bits used in the two operands.
465 uint32_t n1 = getActiveBits();
466 uint32_t n2 = RHS.getActiveBits();
468 // If the number of bits isn't the same, they aren't equal
472 // If the number of bits fits in a word, we only need to compare the low word.
473 if (n1 <= APINT_BITS_PER_WORD)
474 return pVal[0] == RHS.pVal[0];
476 // Otherwise, compare everything
477 for (int i = whichWord(n1 - 1); i >= 0; --i)
478 if (pVal[i] != RHS.pVal[i])
483 bool APInt::operator==(uint64_t Val) const {
487 uint32_t n = getActiveBits();
488 if (n <= APINT_BITS_PER_WORD)
489 return pVal[0] == Val;
494 bool APInt::ult(const APInt& RHS) const {
495 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
497 return VAL < RHS.VAL;
499 // Get active bit length of both operands
500 uint32_t n1 = getActiveBits();
501 uint32_t n2 = RHS.getActiveBits();
503 // If magnitude of LHS is less than RHS, return true.
507 // If magnitude of RHS is greather than LHS, return false.
511 // If they bot fit in a word, just compare the low order word
512 if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
513 return pVal[0] < RHS.pVal[0];
515 // Otherwise, compare all words
516 for (int i = whichWord(n1 - 1); i >= 0; --i) {
517 if (pVal[i] > RHS.pVal[i])
519 if (pVal[i] < RHS.pVal[i])
525 bool APInt::slt(const APInt& RHS) const {
526 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
527 if (isSingleWord()) {
528 int64_t lhsSext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
529 int64_t rhsSext = (int64_t(RHS.VAL) << (64-BitWidth)) >> (64-BitWidth);
530 return lhsSext < rhsSext;
535 bool lhsNegative = false;
536 bool rhsNegative = false;
537 if (lhs[BitWidth-1]) {
538 // Sign bit is set so make a note of it and perform two's complement
543 if (rhs[BitWidth-1]) {
544 // Sign bit is set so make a note of it and perform two's complement
550 // Now we have unsigned values to compare so do the comparison if necessary
551 // based on the negativeness of the values.
554 return !lhs.ult(rhs);
557 else if (rhsNegative)
563 APInt& APInt::set(uint32_t bitPosition) {
565 VAL |= maskBit(bitPosition);
567 pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
571 APInt& APInt::set() {
572 if (isSingleWord()) {
574 return clearUnusedBits();
577 // Set all the bits in all the words.
578 for (uint32_t i = 0; i < getNumWords() - 1; ++i)
580 // Clear the unused ones
581 return clearUnusedBits();
584 /// Set the given bit to 0 whose position is given as "bitPosition".
585 /// @brief Set a given bit to 0.
586 APInt& APInt::clear(uint32_t bitPosition) {
588 VAL &= ~maskBit(bitPosition);
590 pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
594 /// @brief Set every bit to 0.
595 APInt& APInt::clear() {
599 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
603 /// @brief Bitwise NOT operator. Performs a bitwise logical NOT operation on
605 APInt APInt::operator~() const {
611 /// @brief Toggle every bit to its opposite value.
612 APInt& APInt::flip() {
613 if (isSingleWord()) {
615 return clearUnusedBits();
617 for (uint32_t i = 0; i < getNumWords(); ++i)
619 return clearUnusedBits();
622 /// Toggle a given bit to its opposite value whose position is given
623 /// as "bitPosition".
624 /// @brief Toggles a given bit to its opposite value.
625 APInt& APInt::flip(uint32_t bitPosition) {
626 assert(bitPosition < BitWidth && "Out of the bit-width range!");
627 if ((*this)[bitPosition]) clear(bitPosition);
628 else set(bitPosition);
632 /// getMaxValue - This function returns the largest value
633 /// for an APInt of the specified bit-width and if isSign == true,
634 /// it should be largest signed value, otherwise unsigned value.
635 APInt APInt::getMaxValue(uint32_t numBits, bool isSign) {
636 APInt Result(numBits, 0);
639 Result.clear(numBits - 1);
643 /// getMinValue - This function returns the smallest value for
644 /// an APInt of the given bit-width and if isSign == true,
645 /// it should be smallest signed value, otherwise zero.
646 APInt APInt::getMinValue(uint32_t numBits, bool isSign) {
647 APInt Result(numBits, 0);
649 Result.set(numBits - 1);
653 /// getAllOnesValue - This function returns an all-ones value for
654 /// an APInt of the specified bit-width.
655 APInt APInt::getAllOnesValue(uint32_t numBits) {
656 return getMaxValue(numBits, false);
659 /// getNullValue - This function creates an '0' value for an
660 /// APInt of the specified bit-width.
661 APInt APInt::getNullValue(uint32_t numBits) {
662 return getMinValue(numBits, false);
665 /// HiBits - This function returns the high "numBits" bits of this APInt.
666 APInt APInt::getHiBits(uint32_t numBits) const {
667 return APIntOps::lshr(*this, BitWidth - numBits);
670 /// LoBits - This function returns the low "numBits" bits of this APInt.
671 APInt APInt::getLoBits(uint32_t numBits) const {
672 return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits),
676 bool APInt::isPowerOf2() const {
677 return (!!*this) && !(*this & (*this - APInt(BitWidth,1)));
680 uint32_t APInt::countLeadingZeros() const {
683 Count = CountLeadingZeros_64(VAL);
685 for (uint32_t i = getNumWords(); i > 0u; --i) {
687 Count += APINT_BITS_PER_WORD;
689 Count += CountLeadingZeros_64(pVal[i-1]);
694 uint32_t remainder = BitWidth % APINT_BITS_PER_WORD;
696 Count -= APINT_BITS_PER_WORD - remainder;
700 uint32_t APInt::countTrailingZeros() const {
702 return CountTrailingZeros_64(VAL);
705 for (; i < getNumWords() && pVal[i] == 0; ++i)
706 Count += APINT_BITS_PER_WORD;
707 if (i < getNumWords())
708 Count += CountTrailingZeros_64(pVal[i]);
712 uint32_t APInt::countPopulation() const {
714 return CountPopulation_64(VAL);
716 for (uint32_t i = 0; i < getNumWords(); ++i)
717 Count += CountPopulation_64(pVal[i]);
721 APInt APInt::byteSwap() const {
722 assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
724 return APInt(BitWidth, ByteSwap_16(VAL));
725 else if (BitWidth == 32)
726 return APInt(BitWidth, ByteSwap_32(VAL));
727 else if (BitWidth == 48) {
728 uint64_t Tmp1 = ((VAL >> 32) << 16) | (VAL & 0xFFFF);
729 Tmp1 = ByteSwap_32(Tmp1);
730 uint64_t Tmp2 = (VAL >> 16) & 0xFFFF;
731 Tmp2 = ByteSwap_16(Tmp2);
734 (Tmp1 & 0xff) | ((Tmp1<<16) & 0xffff00000000ULL) | (Tmp2 << 16));
735 } else if (BitWidth == 64)
736 return APInt(BitWidth, ByteSwap_64(VAL));
738 APInt Result(BitWidth, 0);
739 char *pByte = (char*)Result.pVal;
740 for (uint32_t i = 0; i < BitWidth / APINT_WORD_SIZE / 2; ++i) {
742 pByte[i] = pByte[BitWidth / APINT_WORD_SIZE - 1 - i];
743 pByte[BitWidth / APINT_WORD_SIZE - i - 1] = Tmp;
749 APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1,
751 APInt A = API1, B = API2;
754 B = APIntOps::urem(A, B);
760 APInt llvm::APIntOps::RoundDoubleToAPInt(double Double) {
766 bool isNeg = T.I >> 63;
767 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
769 return APInt(64ull, 0u);
770 uint64_t mantissa = ((T.I << 12) >> 12) | (1ULL << 52);
772 return isNeg ? -APInt(64u, mantissa >> (52 - exp)) :
773 APInt(64u, mantissa >> (52 - exp));
774 APInt Tmp(exp + 1, mantissa);
775 Tmp = Tmp.shl(exp - 52);
776 return isNeg ? -Tmp : Tmp;
779 /// RoundToDouble - This function convert this APInt to a double.
780 /// The layout for double is as following (IEEE Standard 754):
781 /// --------------------------------------
782 /// | Sign Exponent Fraction Bias |
783 /// |-------------------------------------- |
784 /// | 1[63] 11[62-52] 52[51-00] 1023 |
785 /// --------------------------------------
786 double APInt::roundToDouble(bool isSigned) const {
788 // Handle the simple case where the value is contained in one uint64_t.
789 if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
791 int64_t sext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
797 // Determine if the value is negative.
798 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
800 // Construct the absolute value if we're negative.
801 APInt Tmp(isNeg ? -(*this) : (*this));
803 // Figure out how many bits we're using.
804 uint32_t n = Tmp.getActiveBits();
806 // The exponent (without bias normalization) is just the number of bits
807 // we are using. Note that the sign bit is gone since we constructed the
811 // Return infinity for exponent overflow
813 if (!isSigned || !isNeg)
814 return double(1.0E300 * 1.0E300); // positive infinity
816 return double(-1.0E300 * 1.0E300); // negative infinity
818 exp += 1023; // Increment for 1023 bias
820 // Number of bits in mantissa is 52. To obtain the mantissa value, we must
821 // extract the high 52 bits from the correct words in pVal.
823 unsigned hiWord = whichWord(n-1);
825 mantissa = Tmp.pVal[0];
827 mantissa >>= n - 52; // shift down, we want the top 52 bits.
829 assert(hiWord > 0 && "huh?");
830 uint64_t hibits = Tmp.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
831 uint64_t lobits = Tmp.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
832 mantissa = hibits | lobits;
835 // The leading bit of mantissa is implicit, so get rid of it.
836 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
841 T.I = sign | (exp << 52) | mantissa;
845 // Truncate to new width.
846 void APInt::trunc(uint32_t width) {
847 assert(width < BitWidth && "Invalid APInt Truncate request");
848 assert(width >= IntegerType::MIN_INT_BITS && "Can't truncate to 0 bits");
849 uint32_t wordsBefore = getNumWords();
851 uint32_t wordsAfter = getNumWords();
852 if (wordsBefore != wordsAfter) {
853 if (wordsAfter == 1) {
854 uint64_t *tmp = pVal;
858 uint64_t *newVal = getClearedMemory(wordsAfter);
859 for (uint32_t i = 0; i < wordsAfter; ++i)
868 // Sign extend to a new width.
869 void APInt::sext(uint32_t width) {
870 assert(width > BitWidth && "Invalid APInt SignExtend request");
871 assert(width <= IntegerType::MAX_INT_BITS && "Too many bits");
872 // If the sign bit isn't set, this is the same as zext.
878 // The sign bit is set. First, get some facts
879 uint32_t wordsBefore = getNumWords();
880 uint32_t wordBits = BitWidth % APINT_BITS_PER_WORD;
882 uint32_t wordsAfter = getNumWords();
884 // Mask the high order word appropriately
885 if (wordsBefore == wordsAfter) {
886 uint32_t newWordBits = width % APINT_BITS_PER_WORD;
887 // The extension is contained to the wordsBefore-1th word.
888 uint64_t mask = (~0ULL >> (APINT_BITS_PER_WORD - newWordBits)) << wordBits;
889 if (wordsBefore == 1)
892 pVal[wordsBefore-1] |= mask;
897 uint64_t mask = wordBits == 0 ? 0 : ~0ULL << wordBits;
898 uint64_t *newVal = getMemory(wordsAfter);
899 if (wordsBefore == 1)
900 newVal[0] = VAL | mask;
902 for (uint32_t i = 0; i < wordsBefore; ++i)
904 newVal[wordsBefore-1] |= mask;
906 for (uint32_t i = wordsBefore; i < wordsAfter; i++)
908 if (wordsBefore != 1)
914 // Zero extend to a new width.
915 void APInt::zext(uint32_t width) {
916 assert(width > BitWidth && "Invalid APInt ZeroExtend request");
917 assert(width <= IntegerType::MAX_INT_BITS && "Too many bits");
918 uint32_t wordsBefore = getNumWords();
920 uint32_t wordsAfter = getNumWords();
921 if (wordsBefore != wordsAfter) {
922 uint64_t *newVal = getClearedMemory(wordsAfter);
923 if (wordsBefore == 1)
926 for (uint32_t i = 0; i < wordsBefore; ++i)
928 if (wordsBefore != 1)
934 /// Arithmetic right-shift this APInt by shiftAmt.
935 /// @brief Arithmetic right-shift function.
936 APInt APInt::ashr(uint32_t shiftAmt) const {
937 assert(shiftAmt <= BitWidth && "Invalid shift amount");
938 if (isSingleWord()) {
939 if (shiftAmt == BitWidth)
940 return APInt(BitWidth, 0); // undefined
942 uint32_t SignBit = APINT_BITS_PER_WORD - BitWidth;
943 return APInt(BitWidth,
944 (((int64_t(VAL) << SignBit) >> SignBit) >> shiftAmt));
948 // If all the bits were shifted out, the result is 0 or -1. This avoids issues
949 // with shifting by the size of the integer type, which produces undefined
951 if (shiftAmt == BitWidth)
953 return APInt(BitWidth, -1ULL);
955 return APInt(BitWidth, 0);
957 // Create some space for the result.
958 uint64_t * val = new uint64_t[getNumWords()];
960 // If we are shifting less than a word, compute the shift with a simple carry
961 if (shiftAmt < APINT_BITS_PER_WORD) {
963 for (int i = getNumWords()-1; i >= 0; --i) {
964 val[i] = pVal[i] >> shiftAmt | carry;
965 carry = pVal[i] << (APINT_BITS_PER_WORD - shiftAmt);
967 return APInt(val, BitWidth).clearUnusedBits();
970 // Compute some values needed by the remaining shift algorithms
971 uint32_t wordShift = shiftAmt % APINT_BITS_PER_WORD;
972 uint32_t offset = shiftAmt / APINT_BITS_PER_WORD;
974 // If we are shifting whole words, just move whole words
975 if (wordShift == 0) {
976 for (uint32_t i = 0; i < getNumWords() - offset; ++i)
977 val[i] = pVal[i+offset];
978 for (uint32_t i = getNumWords()-offset; i < getNumWords(); i++)
979 val[i] = (isNegative() ? -1ULL : 0);
980 return APInt(val,BitWidth).clearUnusedBits();
983 // Shift the low order words
984 uint32_t breakWord = getNumWords() - offset -1;
985 for (uint32_t i = 0; i < breakWord; ++i)
986 val[i] = pVal[i+offset] >> wordShift |
987 pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift);
988 // Shift the break word.
989 uint32_t SignBit = APINT_BITS_PER_WORD - (BitWidth % APINT_BITS_PER_WORD);
990 val[breakWord] = uint64_t(
991 (((int64_t(pVal[breakWord+offset]) << SignBit) >> SignBit) >> wordShift));
993 // Remaining words are 0 or -1
994 for (uint32_t i = breakWord+1; i < getNumWords(); ++i)
995 val[i] = (isNegative() ? -1ULL : 0);
996 return APInt(val, BitWidth).clearUnusedBits();
999 /// Logical right-shift this APInt by shiftAmt.
1000 /// @brief Logical right-shift function.
1001 APInt APInt::lshr(uint32_t shiftAmt) const {
1003 if (shiftAmt == BitWidth)
1004 return APInt(BitWidth, 0);
1006 return APInt(BitWidth, this->VAL >> shiftAmt);
1008 // If all the bits were shifted out, the result is 0. This avoids issues
1009 // with shifting by the size of the integer type, which produces undefined
1010 // results. We define these "undefined results" to always be 0.
1011 if (shiftAmt == BitWidth)
1012 return APInt(BitWidth, 0);
1014 // Create some space for the result.
1015 uint64_t * val = new uint64_t[getNumWords()];
1017 // If we are shifting less than a word, compute the shift with a simple carry
1018 if (shiftAmt < APINT_BITS_PER_WORD) {
1020 for (int i = getNumWords()-1; i >= 0; --i) {
1021 val[i] = pVal[i] >> shiftAmt | carry;
1022 carry = pVal[i] << (APINT_BITS_PER_WORD - shiftAmt);
1024 return APInt(val, BitWidth).clearUnusedBits();
1027 // Compute some values needed by the remaining shift algorithms
1028 uint32_t wordShift = shiftAmt % APINT_BITS_PER_WORD;
1029 uint32_t offset = shiftAmt / APINT_BITS_PER_WORD;
1031 // If we are shifting whole words, just move whole words
1032 if (wordShift == 0) {
1033 for (uint32_t i = 0; i < getNumWords() - offset; ++i)
1034 val[i] = pVal[i+offset];
1035 for (uint32_t i = getNumWords()-offset; i < getNumWords(); i++)
1037 return APInt(val,BitWidth).clearUnusedBits();
1040 // Shift the low order words
1041 uint32_t breakWord = getNumWords() - offset -1;
1042 for (uint32_t i = 0; i < breakWord; ++i)
1043 val[i] = pVal[i+offset] >> wordShift |
1044 pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift);
1045 // Shift the break word.
1046 val[breakWord] = pVal[breakWord+offset] >> wordShift;
1048 // Remaining words are 0
1049 for (uint32_t i = breakWord+1; i < getNumWords(); ++i)
1051 return APInt(val, BitWidth).clearUnusedBits();
1054 /// Left-shift this APInt by shiftAmt.
1055 /// @brief Left-shift function.
1056 APInt APInt::shl(uint32_t shiftAmt) const {
1057 assert(shiftAmt <= BitWidth && "Invalid shift amount");
1058 if (isSingleWord()) {
1059 if (shiftAmt == BitWidth)
1060 return APInt(BitWidth, 0); // avoid undefined shift results
1061 return APInt(BitWidth, VAL << shiftAmt);
1064 // If all the bits were shifted out, the result is 0. This avoids issues
1065 // with shifting by the size of the integer type, which produces undefined
1066 // results. We define these "undefined results" to always be 0.
1067 if (shiftAmt == BitWidth)
1068 return APInt(BitWidth, 0);
1070 // Create some space for the result.
1071 uint64_t * val = new uint64_t[getNumWords()];
1073 // If we are shifting less than a word, do it the easy way
1074 if (shiftAmt < APINT_BITS_PER_WORD) {
1076 for (uint32_t i = 0; i < getNumWords(); i++) {
1077 val[i] = pVal[i] << shiftAmt | carry;
1078 carry = pVal[i] >> (APINT_BITS_PER_WORD - shiftAmt);
1080 return APInt(val, BitWidth).clearUnusedBits();
1083 // Compute some values needed by the remaining shift algorithms
1084 uint32_t wordShift = shiftAmt % APINT_BITS_PER_WORD;
1085 uint32_t offset = shiftAmt / APINT_BITS_PER_WORD;
1087 // If we are shifting whole words, just move whole words
1088 if (wordShift == 0) {
1089 for (uint32_t i = 0; i < offset; i++)
1091 for (uint32_t i = offset; i < getNumWords(); i++)
1092 val[i] = pVal[i-offset];
1093 return APInt(val,BitWidth).clearUnusedBits();
1096 // Copy whole words from this to Result.
1097 uint32_t i = getNumWords() - 1;
1098 for (; i > offset; --i)
1099 val[i] = pVal[i-offset] << wordShift |
1100 pVal[i-offset-1] >> (APINT_BITS_PER_WORD - wordShift);
1101 val[offset] = pVal[0] << wordShift;
1102 for (i = 0; i < offset; ++i)
1104 return APInt(val, BitWidth).clearUnusedBits();
1107 /// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
1108 /// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
1109 /// variables here have the same names as in the algorithm. Comments explain
1110 /// the algorithm and any deviation from it.
1111 static void KnuthDiv(uint32_t *u, uint32_t *v, uint32_t *q, uint32_t* r,
1112 uint32_t m, uint32_t n) {
1113 assert(u && "Must provide dividend");
1114 assert(v && "Must provide divisor");
1115 assert(q && "Must provide quotient");
1116 assert(u != v && u != q && v != q && "Must us different memory");
1117 assert(n>1 && "n must be > 1");
1119 // Knuth uses the value b as the base of the number system. In our case b
1120 // is 2^31 so we just set it to -1u.
1121 uint64_t b = uint64_t(1) << 32;
1123 DEBUG(cerr << "KnuthDiv: m=" << m << " n=" << n << '\n');
1124 DEBUG(cerr << "KnuthDiv: original:");
1125 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << std::setbase(16) << u[i]);
1126 DEBUG(cerr << " by");
1127 DEBUG(for (int i = n; i >0; i--) cerr << " " << std::setbase(16) << v[i-1]);
1128 DEBUG(cerr << '\n');
1129 // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
1130 // u and v by d. Note that we have taken Knuth's advice here to use a power
1131 // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
1132 // 2 allows us to shift instead of multiply and it is easy to determine the
1133 // shift amount from the leading zeros. We are basically normalizing the u
1134 // and v so that its high bits are shifted to the top of v's range without
1135 // overflow. Note that this can require an extra word in u so that u must
1136 // be of length m+n+1.
1137 uint32_t shift = CountLeadingZeros_32(v[n-1]);
1138 uint32_t v_carry = 0;
1139 uint32_t u_carry = 0;
1141 for (uint32_t i = 0; i < m+n; ++i) {
1142 uint32_t u_tmp = u[i] >> (32 - shift);
1143 u[i] = (u[i] << shift) | u_carry;
1146 for (uint32_t i = 0; i < n; ++i) {
1147 uint32_t v_tmp = v[i] >> (32 - shift);
1148 v[i] = (v[i] << shift) | v_carry;
1153 DEBUG(cerr << "KnuthDiv: normal:");
1154 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << std::setbase(16) << u[i]);
1155 DEBUG(cerr << " by");
1156 DEBUG(for (int i = n; i >0; i--) cerr << " " << std::setbase(16) << v[i-1]);
1157 DEBUG(cerr << '\n');
1159 // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
1162 DEBUG(cerr << "KnuthDiv: quotient digit #" << j << '\n');
1163 // D3. [Calculate q'.].
1164 // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
1165 // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
1166 // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
1167 // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test
1168 // on v[n-2] determines at high speed most of the cases in which the trial
1169 // value qp is one too large, and it eliminates all cases where qp is two
1171 uint64_t dividend = ((uint64_t(u[j+n]) << 32) + u[j+n-1]);
1172 DEBUG(cerr << "KnuthDiv: dividend == " << dividend << '\n');
1173 uint64_t qp = dividend / v[n-1];
1174 uint64_t rp = dividend % v[n-1];
1175 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1178 if (rp < b && (qp == b || qp*v[n-2] > b*rp + u[j+n-2]))
1181 DEBUG(cerr << "KnuthDiv: qp == " << qp << ", rp == " << rp << '\n');
1183 // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with
1184 // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation
1185 // consists of a simple multiplication by a one-place number, combined with
1188 for (uint32_t i = 0; i < n; ++i) {
1189 uint64_t u_tmp = uint64_t(u[j+i]) | (uint64_t(u[j+i+1]) << 32);
1190 uint64_t subtrahend = uint64_t(qp) * uint64_t(v[i]);
1191 bool borrow = subtrahend > u_tmp;
1192 DEBUG(cerr << "KnuthDiv: u_tmp == " << u_tmp
1193 << ", subtrahend == " << subtrahend
1194 << ", borrow = " << borrow << '\n');
1196 uint64_t result = u_tmp - subtrahend;
1198 u[k++] = result & (b-1); // subtract low word
1199 u[k++] = result >> 32; // subtract high word
1200 while (borrow && k <= m+n) { // deal with borrow to the left
1206 DEBUG(cerr << "KnuthDiv: u[j+i] == " << u[j+i] << ", u[j+i+1] == " <<
1209 DEBUG(cerr << "KnuthDiv: after subtraction:");
1210 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << u[i]);
1211 DEBUG(cerr << '\n');
1212 // The digits (u[j+n]...u[j]) should be kept positive; if the result of
1213 // this step is actually negative, (u[j+n]...u[j]) should be left as the
1214 // true value plus b**(n+1), namely as the b's complement of
1215 // the true value, and a "borrow" to the left should be remembered.
1218 bool carry = true; // true because b's complement is "complement + 1"
1219 for (uint32_t i = 0; i <= m+n; ++i) {
1220 u[i] = ~u[i] + carry; // b's complement
1221 carry = carry && u[i] == 0;
1224 DEBUG(cerr << "KnuthDiv: after complement:");
1225 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << u[i]);
1226 DEBUG(cerr << '\n');
1228 // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
1229 // negative, go to step D6; otherwise go on to step D7.
1232 // D6. [Add back]. The probability that this step is necessary is very
1233 // small, on the order of only 2/b. Make sure that test data accounts for
1234 // this possibility. Decrease q[j] by 1
1236 // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]).
1237 // A carry will occur to the left of u[j+n], and it should be ignored
1238 // since it cancels with the borrow that occurred in D4.
1240 for (uint32_t i = 0; i < n; i++) {
1241 uint32_t limit = std::min(u[j+i],v[i]);
1242 u[j+i] += v[i] + carry;
1243 carry = u[j+i] < limit || (carry && u[j+i] == limit);
1247 DEBUG(cerr << "KnuthDiv: after correction:");
1248 DEBUG(for (int i = m+n; i >=0; i--) cerr <<" " << u[i]);
1249 DEBUG(cerr << "\nKnuthDiv: digit result = " << q[j] << '\n');
1251 // D7. [Loop on j.] Decrease j by one. Now if j >= 0, go back to D3.
1254 DEBUG(cerr << "KnuthDiv: quotient:");
1255 DEBUG(for (int i = m; i >=0; i--) cerr <<" " << q[i]);
1256 DEBUG(cerr << '\n');
1258 // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
1259 // remainder may be obtained by dividing u[...] by d. If r is non-null we
1260 // compute the remainder (urem uses this).
1262 // The value d is expressed by the "shift" value above since we avoided
1263 // multiplication by d by using a shift left. So, all we have to do is
1264 // shift right here. In order to mak
1267 DEBUG(cerr << "KnuthDiv: remainder:");
1268 for (int i = n-1; i >= 0; i--) {
1269 r[i] = (u[i] >> shift) | carry;
1270 carry = u[i] << (32 - shift);
1271 DEBUG(cerr << " " << r[i]);
1274 for (int i = n-1; i >= 0; i--) {
1276 DEBUG(cerr << " " << r[i]);
1279 DEBUG(cerr << '\n');
1281 DEBUG(cerr << std::setbase(10) << '\n');
1284 void APInt::divide(const APInt LHS, uint32_t lhsWords,
1285 const APInt &RHS, uint32_t rhsWords,
1286 APInt *Quotient, APInt *Remainder)
1288 assert(lhsWords >= rhsWords && "Fractional result");
1290 // First, compose the values into an array of 32-bit words instead of
1291 // 64-bit words. This is a necessity of both the "short division" algorithm
1292 // and the the Knuth "classical algorithm" which requires there to be native
1293 // operations for +, -, and * on an m bit value with an m*2 bit result. We
1294 // can't use 64-bit operands here because we don't have native results of
1295 // 128-bits. Furthremore, casting the 64-bit values to 32-bit values won't
1296 // work on large-endian machines.
1297 uint64_t mask = ~0ull >> (sizeof(uint32_t)*8);
1298 uint32_t n = rhsWords * 2;
1299 uint32_t m = (lhsWords * 2) - n;
1301 // Allocate space for the temporary values we need either on the stack, if
1302 // it will fit, or on the heap if it won't.
1303 uint32_t SPACE[128];
1308 if ((Remainder?4:3)*n+2*m+1 <= 128) {
1311 Q = &SPACE[(m+n+1) + n];
1313 R = &SPACE[(m+n+1) + n + (m+n)];
1315 U = new uint32_t[m + n + 1];
1316 V = new uint32_t[n];
1317 Q = new uint32_t[m+n];
1319 R = new uint32_t[n];
1322 // Initialize the dividend
1323 memset(U, 0, (m+n+1)*sizeof(uint32_t));
1324 for (unsigned i = 0; i < lhsWords; ++i) {
1325 uint64_t tmp = (LHS.getNumWords() == 1 ? LHS.VAL : LHS.pVal[i]);
1326 U[i * 2] = tmp & mask;
1327 U[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1329 U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
1331 // Initialize the divisor
1332 memset(V, 0, (n)*sizeof(uint32_t));
1333 for (unsigned i = 0; i < rhsWords; ++i) {
1334 uint64_t tmp = (RHS.getNumWords() == 1 ? RHS.VAL : RHS.pVal[i]);
1335 V[i * 2] = tmp & mask;
1336 V[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1339 // initialize the quotient and remainder
1340 memset(Q, 0, (m+n) * sizeof(uint32_t));
1342 memset(R, 0, n * sizeof(uint32_t));
1344 // Now, adjust m and n for the Knuth division. n is the number of words in
1345 // the divisor. m is the number of words by which the dividend exceeds the
1346 // divisor (i.e. m+n is the length of the dividend). These sizes must not
1347 // contain any zero words or the Knuth algorithm fails.
1348 for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
1352 for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
1355 // If we're left with only a single word for the divisor, Knuth doesn't work
1356 // so we implement the short division algorithm here. This is much simpler
1357 // and faster because we are certain that we can divide a 64-bit quantity
1358 // by a 32-bit quantity at hardware speed and short division is simply a
1359 // series of such operations. This is just like doing short division but we
1360 // are using base 2^32 instead of base 10.
1361 assert(n != 0 && "Divide by zero?");
1363 uint32_t divisor = V[0];
1364 uint32_t remainder = 0;
1365 for (int i = m+n-1; i >= 0; i--) {
1366 uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i];
1367 if (partial_dividend == 0) {
1370 } else if (partial_dividend < divisor) {
1372 remainder = partial_dividend;
1373 } else if (partial_dividend == divisor) {
1377 Q[i] = partial_dividend / divisor;
1378 remainder = partial_dividend - (Q[i] * divisor);
1384 // Now we're ready to invoke the Knuth classical divide algorithm. In this
1386 KnuthDiv(U, V, Q, R, m, n);
1389 // If the caller wants the quotient
1391 // Set up the Quotient value's memory.
1392 if (Quotient->BitWidth != LHS.BitWidth) {
1393 if (Quotient->isSingleWord())
1396 delete Quotient->pVal;
1397 Quotient->BitWidth = LHS.BitWidth;
1398 if (!Quotient->isSingleWord())
1399 Quotient->pVal = getClearedMemory(Quotient->getNumWords());
1403 // The quotient is in Q. Reconstitute the quotient into Quotient's low
1405 if (lhsWords == 1) {
1407 uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2));
1408 if (Quotient->isSingleWord())
1409 Quotient->VAL = tmp;
1411 Quotient->pVal[0] = tmp;
1413 assert(!Quotient->isSingleWord() && "Quotient APInt not large enough");
1414 for (unsigned i = 0; i < lhsWords; ++i)
1416 uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1420 // If the caller wants the remainder
1422 // Set up the Remainder value's memory.
1423 if (Remainder->BitWidth != RHS.BitWidth) {
1424 if (Remainder->isSingleWord())
1427 delete Remainder->pVal;
1428 Remainder->BitWidth = RHS.BitWidth;
1429 if (!Remainder->isSingleWord())
1430 Remainder->pVal = getClearedMemory(Remainder->getNumWords());
1434 // The remainder is in R. Reconstitute the remainder into Remainder's low
1436 if (rhsWords == 1) {
1438 uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2));
1439 if (Remainder->isSingleWord())
1440 Remainder->VAL = tmp;
1442 Remainder->pVal[0] = tmp;
1444 assert(!Remainder->isSingleWord() && "Remainder APInt not large enough");
1445 for (unsigned i = 0; i < rhsWords; ++i)
1446 Remainder->pVal[i] =
1447 uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1451 // Clean up the memory we allocated.
1452 if (U != &SPACE[0]) {
1460 APInt APInt::udiv(const APInt& RHS) const {
1461 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1463 // First, deal with the easy case
1464 if (isSingleWord()) {
1465 assert(RHS.VAL != 0 && "Divide by zero?");
1466 return APInt(BitWidth, VAL / RHS.VAL);
1469 // Get some facts about the LHS and RHS number of bits and words
1470 uint32_t rhsBits = RHS.getActiveBits();
1471 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
1472 assert(rhsWords && "Divided by zero???");
1473 uint32_t lhsBits = this->getActiveBits();
1474 uint32_t lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
1476 // Deal with some degenerate cases
1479 return APInt(BitWidth, 0);
1480 else if (lhsWords < rhsWords || this->ult(RHS)) {
1481 // X / Y ===> 0, iff X < Y
1482 return APInt(BitWidth, 0);
1483 } else if (*this == RHS) {
1485 return APInt(BitWidth, 1);
1486 } else if (lhsWords == 1 && rhsWords == 1) {
1487 // All high words are zero, just use native divide
1488 return APInt(BitWidth, this->pVal[0] / RHS.pVal[0]);
1491 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1492 APInt Quotient(1,0); // to hold result.
1493 divide(*this, lhsWords, RHS, rhsWords, &Quotient, 0);
1497 APInt APInt::urem(const APInt& RHS) const {
1498 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1499 if (isSingleWord()) {
1500 assert(RHS.VAL != 0 && "Remainder by zero?");
1501 return APInt(BitWidth, VAL % RHS.VAL);
1504 // Get some facts about the LHS
1505 uint32_t lhsBits = getActiveBits();
1506 uint32_t lhsWords = !lhsBits ? 0 : (whichWord(lhsBits - 1) + 1);
1508 // Get some facts about the RHS
1509 uint32_t rhsBits = RHS.getActiveBits();
1510 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
1511 assert(rhsWords && "Performing remainder operation by zero ???");
1513 // Check the degenerate cases
1514 if (lhsWords == 0) {
1516 return APInt(BitWidth, 0);
1517 } else if (lhsWords < rhsWords || this->ult(RHS)) {
1518 // X % Y ===> X, iff X < Y
1520 } else if (*this == RHS) {
1522 return APInt(BitWidth, 0);
1523 } else if (lhsWords == 1) {
1524 // All high words are zero, just use native remainder
1525 return APInt(BitWidth, pVal[0] % RHS.pVal[0]);
1528 // We have to compute it the hard way. Invoke the Knute divide algorithm.
1529 APInt Remainder(1,0);
1530 divide(*this, lhsWords, RHS, rhsWords, 0, &Remainder);
1534 void APInt::fromString(uint32_t numbits, const char *str, uint32_t slen,
1536 // Check our assumptions here
1537 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1538 "Radix should be 2, 8, 10, or 16!");
1539 assert(str && "String is null?");
1540 bool isNeg = str[0] == '-';
1543 assert(slen <= numbits || radix != 2 && "Insufficient bit width");
1544 assert(slen*3 <= numbits || radix != 8 && "Insufficient bit width");
1545 assert(slen*4 <= numbits || radix != 16 && "Insufficient bit width");
1546 assert((slen*64)/20 <= numbits || radix != 10 && "Insufficient bit width");
1549 if (!isSingleWord())
1550 pVal = getClearedMemory(getNumWords());
1552 // Figure out if we can shift instead of multiply
1553 uint32_t shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0);
1555 // Set up an APInt for the digit to add outside the loop so we don't
1556 // constantly construct/destruct it.
1557 APInt apdigit(getBitWidth(), 0);
1558 APInt apradix(getBitWidth(), radix);
1560 // Enter digit traversal loop
1561 for (unsigned i = 0; i < slen; i++) {
1564 char cdigit = str[i];
1565 if (isdigit(cdigit))
1566 digit = cdigit - '0';
1567 else if (isxdigit(cdigit))
1569 digit = cdigit - 'a' + 10;
1570 else if (cdigit >= 'A')
1571 digit = cdigit - 'A' + 10;
1573 assert(0 && "huh?");
1575 assert(0 && "Invalid character in digit string");
1577 // Shift or multiple the value by the radix
1583 // Add in the digit we just interpreted
1584 if (apdigit.isSingleWord())
1585 apdigit.VAL = digit;
1587 apdigit.pVal[0] = digit;
1590 // If its negative, put it in two's complement form
1597 std::string APInt::toString(uint8_t radix, bool wantSigned) const {
1598 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1599 "Radix should be 2, 8, 10, or 16!");
1600 static const char *digits[] = {
1601 "0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"
1604 uint32_t bits_used = getActiveBits();
1605 if (isSingleWord()) {
1607 const char *format = (radix == 10 ? (wantSigned ? "%lld" : "%llu") :
1608 (radix == 16 ? "%llX" : (radix == 8 ? "%llo" : 0)));
1611 int64_t sextVal = (int64_t(VAL) << (APINT_BITS_PER_WORD-BitWidth)) >>
1612 (APINT_BITS_PER_WORD-BitWidth);
1613 sprintf(buf, format, sextVal);
1615 sprintf(buf, format, VAL);
1620 uint32_t bit = v & 1;
1622 buf[bits_used] = digits[bit][0];
1631 uint64_t mask = radix - 1;
1632 uint32_t shift = (radix == 16 ? 4 : radix == 8 ? 3 : 1);
1633 uint32_t nibbles = APINT_BITS_PER_WORD / shift;
1634 for (uint32_t i = 0; i < getNumWords(); ++i) {
1635 uint64_t value = pVal[i];
1636 for (uint32_t j = 0; j < nibbles; ++j) {
1637 result.insert(0, digits[ value & mask ]);
1645 APInt divisor(4, radix);
1646 APInt zero(tmp.getBitWidth(), 0);
1647 size_t insert_at = 0;
1648 if (wantSigned && tmp[BitWidth-1]) {
1649 // They want to print the signed version and it is a negative value
1650 // Flip the bits and add one to turn it into the equivalent positive
1651 // value and put a '-' in the result.
1657 if (tmp == APInt(tmp.getBitWidth(), 0))
1659 else while (tmp.ne(zero)) {
1661 APInt tmp2(tmp.getBitWidth(), 0);
1662 divide(tmp, tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2,
1664 uint32_t digit = APdigit.getValue();
1665 assert(digit < radix && "divide failed");
1666 result.insert(insert_at,digits[digit]);
1674 void APInt::dump() const
1676 cerr << "APInt(" << BitWidth << ")=" << std::setbase(16);
1679 else for (unsigned i = getNumWords(); i > 0; i--) {
1680 cerr << pVal[i-1] << " ";
1682 cerr << " (" << this->toString(10, false) << ")\n" << std::setbase(10);