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"
29 /// A utility function for allocating memory, checking for allocation failures,
30 /// and ensuring the contents are zeroed.
31 inline static uint64_t* getClearedMemory(uint32_t numWords) {
32 uint64_t * result = new uint64_t[numWords];
33 assert(result && "APInt memory allocation fails!");
34 memset(result, 0, numWords * sizeof(uint64_t));
38 /// A utility function for allocating memory and checking for allocation
39 /// failure. The content is not zeroed.
40 inline static uint64_t* getMemory(uint32_t numWords) {
41 uint64_t * result = new uint64_t[numWords];
42 assert(result && "APInt memory allocation fails!");
46 APInt::APInt(uint32_t numBits, uint64_t val, bool isSigned )
47 : BitWidth(numBits), VAL(0) {
48 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
49 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
53 pVal = getClearedMemory(getNumWords());
55 if (isSigned && int64_t(val) < 0)
56 for (unsigned i = 1; i < getNumWords(); ++i)
62 APInt::APInt(uint32_t numBits, uint32_t numWords, uint64_t bigVal[])
63 : BitWidth(numBits), VAL(0) {
64 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
65 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
66 assert(bigVal && "Null pointer detected!");
70 // Get memory, cleared to 0
71 pVal = getClearedMemory(getNumWords());
72 // Calculate the number of words to copy
73 uint32_t words = std::min<uint32_t>(numWords, getNumWords());
74 // Copy the words from bigVal to pVal
75 memcpy(pVal, bigVal, words * APINT_WORD_SIZE);
77 // Make sure unused high bits are cleared
81 APInt::APInt(uint32_t numbits, const char StrStart[], uint32_t slen,
83 : BitWidth(numbits), VAL(0) {
84 fromString(numbits, StrStart, slen, radix);
87 APInt::APInt(uint32_t numbits, const std::string& Val, uint8_t radix)
88 : BitWidth(numbits), VAL(0) {
89 assert(!Val.empty() && "String empty?");
90 fromString(numbits, Val.c_str(), Val.size(), radix);
93 APInt::APInt(const APInt& that)
94 : BitWidth(that.BitWidth), VAL(0) {
98 pVal = getMemory(getNumWords());
99 memcpy(pVal, that.pVal, getNumWords() * APINT_WORD_SIZE);
104 if (!isSingleWord() && pVal)
108 APInt& APInt::operator=(const APInt& RHS) {
109 // Don't do anything for X = X
113 // If the bitwidths are the same, we can avoid mucking with memory
114 if (BitWidth == RHS.getBitWidth()) {
118 memcpy(pVal, RHS.pVal, getNumWords() * APINT_WORD_SIZE);
123 if (RHS.isSingleWord())
127 pVal = getMemory(RHS.getNumWords());
128 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
130 else if (getNumWords() == RHS.getNumWords())
131 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
132 else if (RHS.isSingleWord()) {
137 pVal = getMemory(RHS.getNumWords());
138 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
140 BitWidth = RHS.BitWidth;
141 return clearUnusedBits();
144 APInt& APInt::operator=(uint64_t RHS) {
149 memset(pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
151 return clearUnusedBits();
154 /// add_1 - This function adds a single "digit" integer, y, to the multiple
155 /// "digit" integer array, x[]. x[] is modified to reflect the addition and
156 /// 1 is returned if there is a carry out, otherwise 0 is returned.
157 /// @returns the carry of the addition.
158 static bool add_1(uint64_t dest[], uint64_t x[], uint32_t len, uint64_t y) {
159 for (uint32_t i = 0; i < len; ++i) {
162 y = 1; // Carry one to next digit.
164 y = 0; // No need to carry so exit early
171 /// @brief Prefix increment operator. Increments the APInt by one.
172 APInt& APInt::operator++() {
176 add_1(pVal, pVal, getNumWords(), 1);
177 return clearUnusedBits();
180 /// sub_1 - This function subtracts a single "digit" (64-bit word), y, from
181 /// the multi-digit integer array, x[], propagating the borrowed 1 value until
182 /// no further borrowing is neeeded or it runs out of "digits" in x. The result
183 /// is 1 if "borrowing" exhausted the digits in x, or 0 if x was not exhausted.
184 /// In other words, if y > x then this function returns 1, otherwise 0.
185 /// @returns the borrow out of the subtraction
186 static bool sub_1(uint64_t x[], uint32_t len, uint64_t y) {
187 for (uint32_t i = 0; i < len; ++i) {
191 y = 1; // We have to "borrow 1" from next "digit"
193 y = 0; // No need to borrow
194 break; // Remaining digits are unchanged so exit early
200 /// @brief Prefix decrement operator. Decrements the APInt by one.
201 APInt& APInt::operator--() {
205 sub_1(pVal, getNumWords(), 1);
206 return clearUnusedBits();
209 /// add - This function adds the integer array x to the integer array Y and
210 /// places the result in dest.
211 /// @returns the carry out from the addition
212 /// @brief General addition of 64-bit integer arrays
213 static bool add(uint64_t *dest, const uint64_t *x, const uint64_t *y,
216 for (uint32_t i = 0; i< len; ++i) {
217 uint64_t limit = std::min(x[i],y[i]); // must come first in case dest == x
218 dest[i] = x[i] + y[i] + carry;
219 carry = dest[i] < limit || (carry && dest[i] == limit);
224 /// Adds the RHS APint to this APInt.
225 /// @returns this, after addition of RHS.
226 /// @brief Addition assignment operator.
227 APInt& APInt::operator+=(const APInt& RHS) {
228 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
232 add(pVal, pVal, RHS.pVal, getNumWords());
234 return clearUnusedBits();
237 /// Subtracts the integer array y from the integer array x
238 /// @returns returns the borrow out.
239 /// @brief Generalized subtraction of 64-bit integer arrays.
240 static bool sub(uint64_t *dest, const uint64_t *x, const uint64_t *y,
243 for (uint32_t i = 0; i < len; ++i) {
244 uint64_t x_tmp = borrow ? x[i] - 1 : x[i];
245 borrow = y[i] > x_tmp || (borrow && x[i] == 0);
246 dest[i] = x_tmp - y[i];
251 /// Subtracts the RHS APInt from this APInt
252 /// @returns this, after subtraction
253 /// @brief Subtraction assignment operator.
254 APInt& APInt::operator-=(const APInt& RHS) {
255 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
259 sub(pVal, pVal, RHS.pVal, getNumWords());
260 return clearUnusedBits();
263 /// Multiplies an integer array, x by a a uint64_t integer and places the result
265 /// @returns the carry out of the multiplication.
266 /// @brief Multiply a multi-digit APInt by a single digit (64-bit) integer.
267 static uint64_t mul_1(uint64_t dest[], uint64_t x[], uint32_t len, uint64_t y) {
268 // Split y into high 32-bit part (hy) and low 32-bit part (ly)
269 uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
272 // For each digit of x.
273 for (uint32_t i = 0; i < len; ++i) {
274 // Split x into high and low words
275 uint64_t lx = x[i] & 0xffffffffULL;
276 uint64_t hx = x[i] >> 32;
277 // hasCarry - A flag to indicate if there is a carry to the next digit.
278 // hasCarry == 0, no carry
279 // hasCarry == 1, has carry
280 // hasCarry == 2, no carry and the calculation result == 0.
281 uint8_t hasCarry = 0;
282 dest[i] = carry + lx * ly;
283 // Determine if the add above introduces carry.
284 hasCarry = (dest[i] < carry) ? 1 : 0;
285 carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
286 // The upper limit of carry can be (2^32 - 1)(2^32 - 1) +
287 // (2^32 - 1) + 2^32 = 2^64.
288 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
290 carry += (lx * hy) & 0xffffffffULL;
291 dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
292 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) +
293 (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
298 /// Multiplies integer array x by integer array y and stores the result into
299 /// the integer array dest. Note that dest's size must be >= xlen + ylen.
300 /// @brief Generalized multiplicate of integer arrays.
301 static void mul(uint64_t dest[], uint64_t x[], uint32_t xlen, uint64_t y[],
303 dest[xlen] = mul_1(dest, x, xlen, y[0]);
304 for (uint32_t i = 1; i < ylen; ++i) {
305 uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
306 uint64_t carry = 0, lx = 0, hx = 0;
307 for (uint32_t j = 0; j < xlen; ++j) {
308 lx = x[j] & 0xffffffffULL;
310 // hasCarry - A flag to indicate if has carry.
311 // hasCarry == 0, no carry
312 // hasCarry == 1, has carry
313 // hasCarry == 2, no carry and the calculation result == 0.
314 uint8_t hasCarry = 0;
315 uint64_t resul = carry + lx * ly;
316 hasCarry = (resul < carry) ? 1 : 0;
317 carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
318 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
320 carry += (lx * hy) & 0xffffffffULL;
321 resul = (carry << 32) | (resul & 0xffffffffULL);
323 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
324 (carry >> 32) + (dest[i+j] < resul ? 1 : 0) +
325 ((lx * hy) >> 32) + hx * hy;
327 dest[i+xlen] = carry;
331 APInt& APInt::operator*=(const APInt& RHS) {
332 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
333 if (isSingleWord()) {
339 // Get some bit facts about LHS and check for zero
340 uint32_t lhsBits = getActiveBits();
341 uint32_t lhsWords = !lhsBits ? 0 : whichWord(lhsBits - 1) + 1;
346 // Get some bit facts about RHS and check for zero
347 uint32_t rhsBits = RHS.getActiveBits();
348 uint32_t rhsWords = !rhsBits ? 0 : whichWord(rhsBits - 1) + 1;
355 // Allocate space for the result
356 uint32_t destWords = rhsWords + lhsWords;
357 uint64_t *dest = getMemory(destWords);
359 // Perform the long multiply
360 mul(dest, pVal, lhsWords, RHS.pVal, rhsWords);
362 // Copy result back into *this
364 uint32_t wordsToCopy = destWords >= getNumWords() ? getNumWords() : destWords;
365 memcpy(pVal, dest, wordsToCopy * APINT_WORD_SIZE);
367 // delete dest array and return
372 APInt& APInt::operator&=(const APInt& RHS) {
373 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
374 if (isSingleWord()) {
378 uint32_t numWords = getNumWords();
379 for (uint32_t i = 0; i < numWords; ++i)
380 pVal[i] &= RHS.pVal[i];
384 APInt& APInt::operator|=(const APInt& RHS) {
385 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
386 if (isSingleWord()) {
390 uint32_t numWords = getNumWords();
391 for (uint32_t i = 0; i < numWords; ++i)
392 pVal[i] |= RHS.pVal[i];
396 APInt& APInt::operator^=(const APInt& RHS) {
397 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
398 if (isSingleWord()) {
400 this->clearUnusedBits();
403 uint32_t numWords = getNumWords();
404 for (uint32_t i = 0; i < numWords; ++i)
405 pVal[i] ^= RHS.pVal[i];
406 return clearUnusedBits();
409 APInt APInt::operator&(const APInt& RHS) const {
410 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
412 return APInt(getBitWidth(), VAL & RHS.VAL);
414 uint32_t numWords = getNumWords();
415 uint64_t* val = getMemory(numWords);
416 for (uint32_t i = 0; i < numWords; ++i)
417 val[i] = pVal[i] & RHS.pVal[i];
418 return APInt(val, getBitWidth());
421 APInt APInt::operator|(const APInt& RHS) const {
422 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
424 return APInt(getBitWidth(), VAL | RHS.VAL);
426 uint32_t numWords = getNumWords();
427 uint64_t *val = getMemory(numWords);
428 for (uint32_t i = 0; i < numWords; ++i)
429 val[i] = pVal[i] | RHS.pVal[i];
430 return APInt(val, getBitWidth());
433 APInt APInt::operator^(const APInt& RHS) const {
434 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
436 return APInt(BitWidth, VAL ^ RHS.VAL);
438 uint32_t numWords = getNumWords();
439 uint64_t *val = getMemory(numWords);
440 for (uint32_t i = 0; i < numWords; ++i)
441 val[i] = pVal[i] ^ RHS.pVal[i];
443 // 0^0==1 so clear the high bits in case they got set.
444 return APInt(val, getBitWidth()).clearUnusedBits();
447 bool APInt::operator !() const {
451 for (uint32_t i = 0; i < getNumWords(); ++i)
457 APInt APInt::operator*(const APInt& RHS) const {
458 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
460 return APInt(BitWidth, VAL * RHS.VAL);
463 return Result.clearUnusedBits();
466 APInt APInt::operator+(const APInt& RHS) const {
467 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
469 return APInt(BitWidth, VAL + RHS.VAL);
470 APInt Result(BitWidth, 0);
471 add(Result.pVal, this->pVal, RHS.pVal, getNumWords());
472 return Result.clearUnusedBits();
475 APInt APInt::operator-(const APInt& RHS) const {
476 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
478 return APInt(BitWidth, VAL - RHS.VAL);
479 APInt Result(BitWidth, 0);
480 sub(Result.pVal, this->pVal, RHS.pVal, getNumWords());
481 return Result.clearUnusedBits();
484 bool APInt::operator[](uint32_t bitPosition) const {
485 return (maskBit(bitPosition) &
486 (isSingleWord() ? VAL : pVal[whichWord(bitPosition)])) != 0;
489 bool APInt::operator==(const APInt& RHS) const {
490 assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths");
492 return VAL == RHS.VAL;
494 // Get some facts about the number of bits used in the two operands.
495 uint32_t n1 = getActiveBits();
496 uint32_t n2 = RHS.getActiveBits();
498 // If the number of bits isn't the same, they aren't equal
502 // If the number of bits fits in a word, we only need to compare the low word.
503 if (n1 <= APINT_BITS_PER_WORD)
504 return pVal[0] == RHS.pVal[0];
506 // Otherwise, compare everything
507 for (int i = whichWord(n1 - 1); i >= 0; --i)
508 if (pVal[i] != RHS.pVal[i])
513 bool APInt::operator==(uint64_t Val) const {
517 uint32_t n = getActiveBits();
518 if (n <= APINT_BITS_PER_WORD)
519 return pVal[0] == Val;
524 bool APInt::ult(const APInt& RHS) const {
525 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
527 return VAL < RHS.VAL;
529 // Get active bit length of both operands
530 uint32_t n1 = getActiveBits();
531 uint32_t n2 = RHS.getActiveBits();
533 // If magnitude of LHS is less than RHS, return true.
537 // If magnitude of RHS is greather than LHS, return false.
541 // If they bot fit in a word, just compare the low order word
542 if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
543 return pVal[0] < RHS.pVal[0];
545 // Otherwise, compare all words
546 uint32_t topWord = whichWord(std::max(n1,n2)-1);
547 for (int i = topWord; i >= 0; --i) {
548 if (pVal[i] > RHS.pVal[i])
550 if (pVal[i] < RHS.pVal[i])
556 bool APInt::slt(const APInt& RHS) const {
557 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
558 if (isSingleWord()) {
559 int64_t lhsSext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
560 int64_t rhsSext = (int64_t(RHS.VAL) << (64-BitWidth)) >> (64-BitWidth);
561 return lhsSext < rhsSext;
566 bool lhsNeg = isNegative();
567 bool rhsNeg = rhs.isNegative();
569 // Sign bit is set so perform two's complement to make it positive
574 // Sign bit is set so perform two's complement to make it positive
579 // Now we have unsigned values to compare so do the comparison if necessary
580 // based on the negativeness of the values.
592 APInt& APInt::set(uint32_t bitPosition) {
594 VAL |= maskBit(bitPosition);
596 pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
600 APInt& APInt::set() {
601 if (isSingleWord()) {
603 return clearUnusedBits();
606 // Set all the bits in all the words.
607 for (uint32_t i = 0; i < getNumWords() - 1; ++i)
609 // Clear the unused ones
610 return clearUnusedBits();
613 /// Set the given bit to 0 whose position is given as "bitPosition".
614 /// @brief Set a given bit to 0.
615 APInt& APInt::clear(uint32_t bitPosition) {
617 VAL &= ~maskBit(bitPosition);
619 pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
623 /// @brief Set every bit to 0.
624 APInt& APInt::clear() {
628 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
632 /// @brief Bitwise NOT operator. Performs a bitwise logical NOT operation on
634 APInt APInt::operator~() const {
640 /// @brief Toggle every bit to its opposite value.
641 APInt& APInt::flip() {
642 if (isSingleWord()) {
644 return clearUnusedBits();
646 for (uint32_t i = 0; i < getNumWords(); ++i)
648 return clearUnusedBits();
651 /// Toggle a given bit to its opposite value whose position is given
652 /// as "bitPosition".
653 /// @brief Toggles a given bit to its opposite value.
654 APInt& APInt::flip(uint32_t bitPosition) {
655 assert(bitPosition < BitWidth && "Out of the bit-width range!");
656 if ((*this)[bitPosition]) clear(bitPosition);
657 else set(bitPosition);
661 uint64_t APInt::getHashValue() const {
662 // Put the bit width into the low order bits.
663 uint64_t hash = BitWidth;
665 // Add the sum of the words to the hash.
667 hash += VAL << 6; // clear separation of up to 64 bits
669 for (uint32_t i = 0; i < getNumWords(); ++i)
670 hash += pVal[i] << 6; // clear sepration of up to 64 bits
674 /// HiBits - This function returns the high "numBits" bits of this APInt.
675 APInt APInt::getHiBits(uint32_t numBits) const {
676 return APIntOps::lshr(*this, BitWidth - numBits);
679 /// LoBits - This function returns the low "numBits" bits of this APInt.
680 APInt APInt::getLoBits(uint32_t numBits) const {
681 return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits),
685 bool APInt::isPowerOf2() const {
686 return (!!*this) && !(*this & (*this - APInt(BitWidth,1)));
689 uint32_t APInt::countLeadingZeros() const {
692 Count = CountLeadingZeros_64(VAL);
694 for (uint32_t i = getNumWords(); i > 0u; --i) {
696 Count += APINT_BITS_PER_WORD;
698 Count += CountLeadingZeros_64(pVal[i-1]);
703 uint32_t remainder = BitWidth % APINT_BITS_PER_WORD;
705 Count -= APINT_BITS_PER_WORD - remainder;
709 static uint32_t countLeadingOnes_64(uint64_t V, uint32_t skip) {
713 while (V && (V & (1ULL << 63))) {
720 uint32_t APInt::countLeadingOnes() const {
722 return countLeadingOnes_64(VAL, APINT_BITS_PER_WORD - BitWidth);
724 uint32_t highWordBits = BitWidth % APINT_BITS_PER_WORD;
725 uint32_t shift = (highWordBits == 0 ? 0 : APINT_BITS_PER_WORD - highWordBits);
726 int i = getNumWords() - 1;
727 uint32_t Count = countLeadingOnes_64(pVal[i], shift);
728 if (Count == highWordBits) {
729 for (i--; i >= 0; --i) {
730 if (pVal[i] == -1ULL)
731 Count += APINT_BITS_PER_WORD;
733 Count += countLeadingOnes_64(pVal[i], 0);
741 uint32_t APInt::countTrailingZeros() const {
743 return CountTrailingZeros_64(VAL);
746 for (; i < getNumWords() && pVal[i] == 0; ++i)
747 Count += APINT_BITS_PER_WORD;
748 if (i < getNumWords())
749 Count += CountTrailingZeros_64(pVal[i]);
753 uint32_t APInt::countPopulation() const {
755 return CountPopulation_64(VAL);
757 for (uint32_t i = 0; i < getNumWords(); ++i)
758 Count += CountPopulation_64(pVal[i]);
762 APInt APInt::byteSwap() const {
763 assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
765 return APInt(BitWidth, ByteSwap_16(VAL));
766 else if (BitWidth == 32)
767 return APInt(BitWidth, ByteSwap_32(VAL));
768 else if (BitWidth == 48) {
769 uint64_t Tmp1 = ((VAL >> 32) << 16) | (VAL & 0xFFFF);
770 Tmp1 = ByteSwap_32(Tmp1);
771 uint64_t Tmp2 = (VAL >> 16) & 0xFFFF;
772 Tmp2 = ByteSwap_16(Tmp2);
775 (Tmp1 & 0xff) | ((Tmp1<<16) & 0xffff00000000ULL) | (Tmp2 << 16));
776 } else if (BitWidth == 64)
777 return APInt(BitWidth, ByteSwap_64(VAL));
779 APInt Result(BitWidth, 0);
780 char *pByte = (char*)Result.pVal;
781 for (uint32_t i = 0; i < BitWidth / APINT_WORD_SIZE / 2; ++i) {
783 pByte[i] = pByte[BitWidth / APINT_WORD_SIZE - 1 - i];
784 pByte[BitWidth / APINT_WORD_SIZE - i - 1] = Tmp;
790 APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1,
792 APInt A = API1, B = API2;
795 B = APIntOps::urem(A, B);
801 APInt llvm::APIntOps::RoundDoubleToAPInt(double Double, uint32_t width) {
808 // Get the sign bit from the highest order bit
809 bool isNeg = T.I >> 63;
811 // Get the 11-bit exponent and adjust for the 1023 bit bias
812 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
814 // If the exponent is negative, the value is < 0 so just return 0.
816 return APInt(width, 0u);
818 // Extract the mantissa by clearing the top 12 bits (sign + exponent).
819 uint64_t mantissa = (T.I & (~0ULL >> 12)) | 1ULL << 52;
821 // If the exponent doesn't shift all bits out of the mantissa
823 return isNeg ? -APInt(width, mantissa >> (52 - exp)) :
824 APInt(width, mantissa >> (52 - exp));
826 // If the client didn't provide enough bits for us to shift the mantissa into
827 // then the result is undefined, just return 0
828 if (width <= exp - 52)
829 return APInt(width, 0);
831 // Otherwise, we have to shift the mantissa bits up to the right location
832 APInt Tmp(width, mantissa);
833 Tmp = Tmp.shl(exp - 52);
834 return isNeg ? -Tmp : Tmp;
837 /// RoundToDouble - This function convert this APInt to a double.
838 /// The layout for double is as following (IEEE Standard 754):
839 /// --------------------------------------
840 /// | Sign Exponent Fraction Bias |
841 /// |-------------------------------------- |
842 /// | 1[63] 11[62-52] 52[51-00] 1023 |
843 /// --------------------------------------
844 double APInt::roundToDouble(bool isSigned) const {
846 // Handle the simple case where the value is contained in one uint64_t.
847 if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
849 int64_t sext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
855 // Determine if the value is negative.
856 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
858 // Construct the absolute value if we're negative.
859 APInt Tmp(isNeg ? -(*this) : (*this));
861 // Figure out how many bits we're using.
862 uint32_t n = Tmp.getActiveBits();
864 // The exponent (without bias normalization) is just the number of bits
865 // we are using. Note that the sign bit is gone since we constructed the
869 // Return infinity for exponent overflow
871 if (!isSigned || !isNeg)
872 return double(1.0E300 * 1.0E300); // positive infinity
874 return double(-1.0E300 * 1.0E300); // negative infinity
876 exp += 1023; // Increment for 1023 bias
878 // Number of bits in mantissa is 52. To obtain the mantissa value, we must
879 // extract the high 52 bits from the correct words in pVal.
881 unsigned hiWord = whichWord(n-1);
883 mantissa = Tmp.pVal[0];
885 mantissa >>= n - 52; // shift down, we want the top 52 bits.
887 assert(hiWord > 0 && "huh?");
888 uint64_t hibits = Tmp.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
889 uint64_t lobits = Tmp.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
890 mantissa = hibits | lobits;
893 // The leading bit of mantissa is implicit, so get rid of it.
894 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
899 T.I = sign | (exp << 52) | mantissa;
903 // Truncate to new width.
904 APInt &APInt::trunc(uint32_t width) {
905 assert(width < BitWidth && "Invalid APInt Truncate request");
906 assert(width >= IntegerType::MIN_INT_BITS && "Can't truncate to 0 bits");
907 uint32_t wordsBefore = getNumWords();
909 uint32_t wordsAfter = getNumWords();
910 if (wordsBefore != wordsAfter) {
911 if (wordsAfter == 1) {
912 uint64_t *tmp = pVal;
916 uint64_t *newVal = getClearedMemory(wordsAfter);
917 for (uint32_t i = 0; i < wordsAfter; ++i)
923 return clearUnusedBits();
926 // Sign extend to a new width.
927 APInt &APInt::sext(uint32_t width) {
928 assert(width > BitWidth && "Invalid APInt SignExtend request");
929 assert(width <= IntegerType::MAX_INT_BITS && "Too many bits");
930 // If the sign bit isn't set, this is the same as zext.
936 // The sign bit is set. First, get some facts
937 uint32_t wordsBefore = getNumWords();
938 uint32_t wordBits = BitWidth % APINT_BITS_PER_WORD;
940 uint32_t wordsAfter = getNumWords();
942 // Mask the high order word appropriately
943 if (wordsBefore == wordsAfter) {
944 uint32_t newWordBits = width % APINT_BITS_PER_WORD;
945 // The extension is contained to the wordsBefore-1th word.
946 uint64_t mask = ~0ULL;
948 mask >>= APINT_BITS_PER_WORD - newWordBits;
950 if (wordsBefore == 1)
953 pVal[wordsBefore-1] |= mask;
954 return clearUnusedBits();
957 uint64_t mask = wordBits == 0 ? 0 : ~0ULL << wordBits;
958 uint64_t *newVal = getMemory(wordsAfter);
959 if (wordsBefore == 1)
960 newVal[0] = VAL | mask;
962 for (uint32_t i = 0; i < wordsBefore; ++i)
964 newVal[wordsBefore-1] |= mask;
966 for (uint32_t i = wordsBefore; i < wordsAfter; i++)
968 if (wordsBefore != 1)
971 return clearUnusedBits();
974 // Zero extend to a new width.
975 APInt &APInt::zext(uint32_t width) {
976 assert(width > BitWidth && "Invalid APInt ZeroExtend request");
977 assert(width <= IntegerType::MAX_INT_BITS && "Too many bits");
978 uint32_t wordsBefore = getNumWords();
980 uint32_t wordsAfter = getNumWords();
981 if (wordsBefore != wordsAfter) {
982 uint64_t *newVal = getClearedMemory(wordsAfter);
983 if (wordsBefore == 1)
986 for (uint32_t i = 0; i < wordsBefore; ++i)
988 if (wordsBefore != 1)
995 APInt &APInt::zextOrTrunc(uint32_t width) {
996 if (BitWidth < width)
998 if (BitWidth > width)
1003 APInt &APInt::sextOrTrunc(uint32_t width) {
1004 if (BitWidth < width)
1006 if (BitWidth > width)
1007 return trunc(width);
1011 /// Arithmetic right-shift this APInt by shiftAmt.
1012 /// @brief Arithmetic right-shift function.
1013 APInt APInt::ashr(uint32_t shiftAmt) const {
1014 assert(shiftAmt <= BitWidth && "Invalid shift amount");
1015 // Handle a degenerate case
1019 // Handle single word shifts with built-in ashr
1020 if (isSingleWord()) {
1021 if (shiftAmt == BitWidth)
1022 return APInt(BitWidth, 0); // undefined
1024 uint32_t SignBit = APINT_BITS_PER_WORD - BitWidth;
1025 return APInt(BitWidth,
1026 (((int64_t(VAL) << SignBit) >> SignBit) >> shiftAmt));
1030 // If all the bits were shifted out, the result is, technically, undefined.
1031 // We return -1 if it was negative, 0 otherwise. We check this early to avoid
1032 // issues in the algorithm below.
1033 if (shiftAmt == BitWidth)
1035 return APInt(BitWidth, -1ULL);
1037 return APInt(BitWidth, 0);
1039 // Create some space for the result.
1040 uint64_t * val = new uint64_t[getNumWords()];
1042 // Compute some values needed by the following shift algorithms
1043 uint32_t wordShift = shiftAmt % APINT_BITS_PER_WORD; // bits to shift per word
1044 uint32_t offset = shiftAmt / APINT_BITS_PER_WORD; // word offset for shift
1045 uint32_t breakWord = getNumWords() - 1 - offset; // last word affected
1046 uint32_t bitsInWord = whichBit(BitWidth); // how many bits in last word?
1047 if (bitsInWord == 0)
1048 bitsInWord = APINT_BITS_PER_WORD;
1050 // If we are shifting whole words, just move whole words
1051 if (wordShift == 0) {
1052 // Move the words containing significant bits
1053 for (uint32_t i = 0; i <= breakWord; ++i)
1054 val[i] = pVal[i+offset]; // move whole word
1056 // Adjust the top significant word for sign bit fill, if negative
1058 if (bitsInWord < APINT_BITS_PER_WORD)
1059 val[breakWord] |= ~0ULL << bitsInWord; // set high bits
1061 // Shift the low order words
1062 for (uint32_t i = 0; i < breakWord; ++i) {
1063 // This combines the shifted corresponding word with the low bits from
1064 // the next word (shifted into this word's high bits).
1065 val[i] = (pVal[i+offset] >> wordShift) |
1066 (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift));
1069 // Shift the break word. In this case there are no bits from the next word
1070 // to include in this word.
1071 val[breakWord] = pVal[breakWord+offset] >> wordShift;
1073 // Deal with sign extenstion in the break word, and possibly the word before
1076 if (wordShift > bitsInWord) {
1079 ~0ULL << (APINT_BITS_PER_WORD - (wordShift - bitsInWord));
1080 val[breakWord] |= ~0ULL;
1082 val[breakWord] |= (~0ULL << (bitsInWord - wordShift));
1085 // Remaining words are 0 or -1, just assign them.
1086 uint64_t fillValue = (isNegative() ? -1ULL : 0);
1087 for (uint32_t i = breakWord+1; i < getNumWords(); ++i)
1089 return APInt(val, BitWidth).clearUnusedBits();
1092 /// Logical right-shift this APInt by shiftAmt.
1093 /// @brief Logical right-shift function.
1094 APInt APInt::lshr(uint32_t shiftAmt) const {
1096 if (shiftAmt == BitWidth)
1097 return APInt(BitWidth, 0);
1099 return APInt(BitWidth, this->VAL >> shiftAmt);
1101 // If all the bits were shifted out, the result is 0. This avoids issues
1102 // with shifting by the size of the integer type, which produces undefined
1103 // results. We define these "undefined results" to always be 0.
1104 if (shiftAmt == BitWidth)
1105 return APInt(BitWidth, 0);
1107 // Create some space for the result.
1108 uint64_t * val = new uint64_t[getNumWords()];
1110 // If we are shifting less than a word, compute the shift with a simple carry
1111 if (shiftAmt < APINT_BITS_PER_WORD) {
1113 for (int i = getNumWords()-1; i >= 0; --i) {
1114 val[i] = (pVal[i] >> shiftAmt) | carry;
1115 carry = pVal[i] << (APINT_BITS_PER_WORD - shiftAmt);
1117 return APInt(val, BitWidth).clearUnusedBits();
1120 // Compute some values needed by the remaining shift algorithms
1121 uint32_t wordShift = shiftAmt % APINT_BITS_PER_WORD;
1122 uint32_t offset = shiftAmt / APINT_BITS_PER_WORD;
1124 // If we are shifting whole words, just move whole words
1125 if (wordShift == 0) {
1126 for (uint32_t i = 0; i < getNumWords() - offset; ++i)
1127 val[i] = pVal[i+offset];
1128 for (uint32_t i = getNumWords()-offset; i < getNumWords(); i++)
1130 return APInt(val,BitWidth).clearUnusedBits();
1133 // Shift the low order words
1134 uint32_t breakWord = getNumWords() - offset -1;
1135 for (uint32_t i = 0; i < breakWord; ++i)
1136 val[i] = (pVal[i+offset] >> wordShift) |
1137 (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift));
1138 // Shift the break word.
1139 val[breakWord] = pVal[breakWord+offset] >> wordShift;
1141 // Remaining words are 0
1142 for (uint32_t i = breakWord+1; i < getNumWords(); ++i)
1144 return APInt(val, BitWidth).clearUnusedBits();
1147 /// Left-shift this APInt by shiftAmt.
1148 /// @brief Left-shift function.
1149 APInt APInt::shl(uint32_t shiftAmt) const {
1150 assert(shiftAmt <= BitWidth && "Invalid shift amount");
1151 if (isSingleWord()) {
1152 if (shiftAmt == BitWidth)
1153 return APInt(BitWidth, 0); // avoid undefined shift results
1154 return APInt(BitWidth, VAL << shiftAmt);
1157 // If all the bits were shifted out, the result is 0. This avoids issues
1158 // with shifting by the size of the integer type, which produces undefined
1159 // results. We define these "undefined results" to always be 0.
1160 if (shiftAmt == BitWidth)
1161 return APInt(BitWidth, 0);
1163 // Create some space for the result.
1164 uint64_t * val = new uint64_t[getNumWords()];
1166 // If we are shifting less than a word, do it the easy way
1167 if (shiftAmt < APINT_BITS_PER_WORD) {
1169 for (uint32_t i = 0; i < getNumWords(); i++) {
1170 val[i] = pVal[i] << shiftAmt | carry;
1171 carry = pVal[i] >> (APINT_BITS_PER_WORD - shiftAmt);
1173 return APInt(val, BitWidth).clearUnusedBits();
1176 // Compute some values needed by the remaining shift algorithms
1177 uint32_t wordShift = shiftAmt % APINT_BITS_PER_WORD;
1178 uint32_t offset = shiftAmt / APINT_BITS_PER_WORD;
1180 // If we are shifting whole words, just move whole words
1181 if (wordShift == 0) {
1182 for (uint32_t i = 0; i < offset; i++)
1184 for (uint32_t i = offset; i < getNumWords(); i++)
1185 val[i] = pVal[i-offset];
1186 return APInt(val,BitWidth).clearUnusedBits();
1189 // Copy whole words from this to Result.
1190 uint32_t i = getNumWords() - 1;
1191 for (; i > offset; --i)
1192 val[i] = pVal[i-offset] << wordShift |
1193 pVal[i-offset-1] >> (APINT_BITS_PER_WORD - wordShift);
1194 val[offset] = pVal[0] << wordShift;
1195 for (i = 0; i < offset; ++i)
1197 return APInt(val, BitWidth).clearUnusedBits();
1201 // Square Root - this method computes and returns the square root of "this".
1202 // Three mechanisms are used for computation. For small values (<= 5 bits),
1203 // a table lookup is done. This gets some performance for common cases. For
1204 // values using less than 52 bits, the value is converted to double and then
1205 // the libc sqrt function is called. The result is rounded and then converted
1206 // back to a uint64_t which is then used to construct the result. Finally,
1207 // the Babylonian method for computing square roots is used.
1208 APInt APInt::sqrt() const {
1210 // Determine the magnitude of the value.
1211 uint32_t magnitude = getActiveBits();
1213 // Use a fast table for some small values. This also gets rid of some
1214 // rounding errors in libc sqrt for small values.
1215 if (magnitude <= 5) {
1216 static const uint8_t results[32] = {
1219 /* 3- 6 */ 2, 2, 2, 2,
1220 /* 7-12 */ 3, 3, 3, 3, 3, 3,
1221 /* 13-20 */ 4, 4, 4, 4, 4, 4, 4, 4,
1222 /* 21-30 */ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
1225 return APInt(BitWidth, results[ (isSingleWord() ? VAL : pVal[0]) ]);
1228 // If the magnitude of the value fits in less than 52 bits (the precision of
1229 // an IEEE double precision floating point value), then we can use the
1230 // libc sqrt function which will probably use a hardware sqrt computation.
1231 // This should be faster than the algorithm below.
1232 if (magnitude < 52) {
1234 // Amazingly, VC++ doesn't have round().
1235 return APInt(BitWidth,
1236 uint64_t(::sqrt(double(isSingleWord()?VAL:pVal[0]))) + 0.5);
1238 return APInt(BitWidth,
1239 uint64_t(::round(::sqrt(double(isSingleWord()?VAL:pVal[0])))));
1243 // Okay, all the short cuts are exhausted. We must compute it. The following
1244 // is a classical Babylonian method for computing the square root. This code
1245 // was adapted to APINt from a wikipedia article on such computations.
1246 // See http://www.wikipedia.org/ and go to the page named
1247 // Calculate_an_integer_square_root.
1248 uint32_t nbits = BitWidth, i = 4;
1249 APInt testy(BitWidth, 16);
1250 APInt x_old(BitWidth, 1);
1251 APInt x_new(BitWidth, 0);
1252 APInt two(BitWidth, 2);
1254 // Select a good starting value using binary logarithms.
1255 for (;; i += 2, testy = testy.shl(2))
1256 if (i >= nbits || this->ule(testy)) {
1257 x_old = x_old.shl(i / 2);
1261 // Use the Babylonian method to arrive at the integer square root:
1263 x_new = (this->udiv(x_old) + x_old).udiv(two);
1264 if (x_old.ule(x_new))
1269 // Make sure we return the closest approximation
1270 // NOTE: The rounding calculation below is correct. It will produce an
1271 // off-by-one discrepancy with results from pari/gp. That discrepancy has been
1272 // determined to be a rounding issue with pari/gp as it begins to use a
1273 // floating point representation after 192 bits. There are no discrepancies
1274 // between this algorithm and pari/gp for bit widths < 192 bits.
1275 APInt square(x_old * x_old);
1276 APInt nextSquare((x_old + 1) * (x_old +1));
1277 if (this->ult(square))
1279 else if (this->ule(nextSquare)) {
1280 APInt midpoint((nextSquare - square).udiv(two));
1281 APInt offset(*this - square);
1282 if (offset.ult(midpoint))
1287 assert(0 && "Error in APInt::sqrt computation");
1291 /// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
1292 /// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
1293 /// variables here have the same names as in the algorithm. Comments explain
1294 /// the algorithm and any deviation from it.
1295 static void KnuthDiv(uint32_t *u, uint32_t *v, uint32_t *q, uint32_t* r,
1296 uint32_t m, uint32_t n) {
1297 assert(u && "Must provide dividend");
1298 assert(v && "Must provide divisor");
1299 assert(q && "Must provide quotient");
1300 assert(u != v && u != q && v != q && "Must us different memory");
1301 assert(n>1 && "n must be > 1");
1303 // Knuth uses the value b as the base of the number system. In our case b
1304 // is 2^31 so we just set it to -1u.
1305 uint64_t b = uint64_t(1) << 32;
1307 DEBUG(cerr << "KnuthDiv: m=" << m << " n=" << n << '\n');
1308 DEBUG(cerr << "KnuthDiv: original:");
1309 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << std::setbase(16) << u[i]);
1310 DEBUG(cerr << " by");
1311 DEBUG(for (int i = n; i >0; i--) cerr << " " << std::setbase(16) << v[i-1]);
1312 DEBUG(cerr << '\n');
1313 // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
1314 // u and v by d. Note that we have taken Knuth's advice here to use a power
1315 // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
1316 // 2 allows us to shift instead of multiply and it is easy to determine the
1317 // shift amount from the leading zeros. We are basically normalizing the u
1318 // and v so that its high bits are shifted to the top of v's range without
1319 // overflow. Note that this can require an extra word in u so that u must
1320 // be of length m+n+1.
1321 uint32_t shift = CountLeadingZeros_32(v[n-1]);
1322 uint32_t v_carry = 0;
1323 uint32_t u_carry = 0;
1325 for (uint32_t i = 0; i < m+n; ++i) {
1326 uint32_t u_tmp = u[i] >> (32 - shift);
1327 u[i] = (u[i] << shift) | u_carry;
1330 for (uint32_t i = 0; i < n; ++i) {
1331 uint32_t v_tmp = v[i] >> (32 - shift);
1332 v[i] = (v[i] << shift) | v_carry;
1337 DEBUG(cerr << "KnuthDiv: normal:");
1338 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << std::setbase(16) << u[i]);
1339 DEBUG(cerr << " by");
1340 DEBUG(for (int i = n; i >0; i--) cerr << " " << std::setbase(16) << v[i-1]);
1341 DEBUG(cerr << '\n');
1343 // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
1346 DEBUG(cerr << "KnuthDiv: quotient digit #" << j << '\n');
1347 // D3. [Calculate q'.].
1348 // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
1349 // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
1350 // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
1351 // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test
1352 // on v[n-2] determines at high speed most of the cases in which the trial
1353 // value qp is one too large, and it eliminates all cases where qp is two
1355 uint64_t dividend = ((uint64_t(u[j+n]) << 32) + u[j+n-1]);
1356 DEBUG(cerr << "KnuthDiv: dividend == " << dividend << '\n');
1357 uint64_t qp = dividend / v[n-1];
1358 uint64_t rp = dividend % v[n-1];
1359 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1362 if (rp < b && (qp == b || qp*v[n-2] > b*rp + u[j+n-2]))
1365 DEBUG(cerr << "KnuthDiv: qp == " << qp << ", rp == " << rp << '\n');
1367 // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with
1368 // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation
1369 // consists of a simple multiplication by a one-place number, combined with
1372 for (uint32_t i = 0; i < n; ++i) {
1373 uint64_t u_tmp = uint64_t(u[j+i]) | (uint64_t(u[j+i+1]) << 32);
1374 uint64_t subtrahend = uint64_t(qp) * uint64_t(v[i]);
1375 bool borrow = subtrahend > u_tmp;
1376 DEBUG(cerr << "KnuthDiv: u_tmp == " << u_tmp
1377 << ", subtrahend == " << subtrahend
1378 << ", borrow = " << borrow << '\n');
1380 uint64_t result = u_tmp - subtrahend;
1382 u[k++] = result & (b-1); // subtract low word
1383 u[k++] = result >> 32; // subtract high word
1384 while (borrow && k <= m+n) { // deal with borrow to the left
1390 DEBUG(cerr << "KnuthDiv: u[j+i] == " << u[j+i] << ", u[j+i+1] == " <<
1393 DEBUG(cerr << "KnuthDiv: after subtraction:");
1394 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << u[i]);
1395 DEBUG(cerr << '\n');
1396 // The digits (u[j+n]...u[j]) should be kept positive; if the result of
1397 // this step is actually negative, (u[j+n]...u[j]) should be left as the
1398 // true value plus b**(n+1), namely as the b's complement of
1399 // the true value, and a "borrow" to the left should be remembered.
1402 bool carry = true; // true because b's complement is "complement + 1"
1403 for (uint32_t i = 0; i <= m+n; ++i) {
1404 u[i] = ~u[i] + carry; // b's complement
1405 carry = carry && u[i] == 0;
1408 DEBUG(cerr << "KnuthDiv: after complement:");
1409 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << u[i]);
1410 DEBUG(cerr << '\n');
1412 // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
1413 // negative, go to step D6; otherwise go on to step D7.
1416 // D6. [Add back]. The probability that this step is necessary is very
1417 // small, on the order of only 2/b. Make sure that test data accounts for
1418 // this possibility. Decrease q[j] by 1
1420 // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]).
1421 // A carry will occur to the left of u[j+n], and it should be ignored
1422 // since it cancels with the borrow that occurred in D4.
1424 for (uint32_t i = 0; i < n; i++) {
1425 uint32_t limit = std::min(u[j+i],v[i]);
1426 u[j+i] += v[i] + carry;
1427 carry = u[j+i] < limit || (carry && u[j+i] == limit);
1431 DEBUG(cerr << "KnuthDiv: after correction:");
1432 DEBUG(for (int i = m+n; i >=0; i--) cerr <<" " << u[i]);
1433 DEBUG(cerr << "\nKnuthDiv: digit result = " << q[j] << '\n');
1435 // D7. [Loop on j.] Decrease j by one. Now if j >= 0, go back to D3.
1438 DEBUG(cerr << "KnuthDiv: quotient:");
1439 DEBUG(for (int i = m; i >=0; i--) cerr <<" " << q[i]);
1440 DEBUG(cerr << '\n');
1442 // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
1443 // remainder may be obtained by dividing u[...] by d. If r is non-null we
1444 // compute the remainder (urem uses this).
1446 // The value d is expressed by the "shift" value above since we avoided
1447 // multiplication by d by using a shift left. So, all we have to do is
1448 // shift right here. In order to mak
1451 DEBUG(cerr << "KnuthDiv: remainder:");
1452 for (int i = n-1; i >= 0; i--) {
1453 r[i] = (u[i] >> shift) | carry;
1454 carry = u[i] << (32 - shift);
1455 DEBUG(cerr << " " << r[i]);
1458 for (int i = n-1; i >= 0; i--) {
1460 DEBUG(cerr << " " << r[i]);
1463 DEBUG(cerr << '\n');
1465 DEBUG(cerr << std::setbase(10) << '\n');
1468 void APInt::divide(const APInt LHS, uint32_t lhsWords,
1469 const APInt &RHS, uint32_t rhsWords,
1470 APInt *Quotient, APInt *Remainder)
1472 assert(lhsWords >= rhsWords && "Fractional result");
1474 // First, compose the values into an array of 32-bit words instead of
1475 // 64-bit words. This is a necessity of both the "short division" algorithm
1476 // and the the Knuth "classical algorithm" which requires there to be native
1477 // operations for +, -, and * on an m bit value with an m*2 bit result. We
1478 // can't use 64-bit operands here because we don't have native results of
1479 // 128-bits. Furthremore, casting the 64-bit values to 32-bit values won't
1480 // work on large-endian machines.
1481 uint64_t mask = ~0ull >> (sizeof(uint32_t)*8);
1482 uint32_t n = rhsWords * 2;
1483 uint32_t m = (lhsWords * 2) - n;
1485 // Allocate space for the temporary values we need either on the stack, if
1486 // it will fit, or on the heap if it won't.
1487 uint32_t SPACE[128];
1492 if ((Remainder?4:3)*n+2*m+1 <= 128) {
1495 Q = &SPACE[(m+n+1) + n];
1497 R = &SPACE[(m+n+1) + n + (m+n)];
1499 U = new uint32_t[m + n + 1];
1500 V = new uint32_t[n];
1501 Q = new uint32_t[m+n];
1503 R = new uint32_t[n];
1506 // Initialize the dividend
1507 memset(U, 0, (m+n+1)*sizeof(uint32_t));
1508 for (unsigned i = 0; i < lhsWords; ++i) {
1509 uint64_t tmp = (LHS.getNumWords() == 1 ? LHS.VAL : LHS.pVal[i]);
1510 U[i * 2] = tmp & mask;
1511 U[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1513 U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
1515 // Initialize the divisor
1516 memset(V, 0, (n)*sizeof(uint32_t));
1517 for (unsigned i = 0; i < rhsWords; ++i) {
1518 uint64_t tmp = (RHS.getNumWords() == 1 ? RHS.VAL : RHS.pVal[i]);
1519 V[i * 2] = tmp & mask;
1520 V[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1523 // initialize the quotient and remainder
1524 memset(Q, 0, (m+n) * sizeof(uint32_t));
1526 memset(R, 0, n * sizeof(uint32_t));
1528 // Now, adjust m and n for the Knuth division. n is the number of words in
1529 // the divisor. m is the number of words by which the dividend exceeds the
1530 // divisor (i.e. m+n is the length of the dividend). These sizes must not
1531 // contain any zero words or the Knuth algorithm fails.
1532 for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
1536 for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
1539 // If we're left with only a single word for the divisor, Knuth doesn't work
1540 // so we implement the short division algorithm here. This is much simpler
1541 // and faster because we are certain that we can divide a 64-bit quantity
1542 // by a 32-bit quantity at hardware speed and short division is simply a
1543 // series of such operations. This is just like doing short division but we
1544 // are using base 2^32 instead of base 10.
1545 assert(n != 0 && "Divide by zero?");
1547 uint32_t divisor = V[0];
1548 uint32_t remainder = 0;
1549 for (int i = m+n-1; i >= 0; i--) {
1550 uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i];
1551 if (partial_dividend == 0) {
1554 } else if (partial_dividend < divisor) {
1556 remainder = partial_dividend;
1557 } else if (partial_dividend == divisor) {
1561 Q[i] = partial_dividend / divisor;
1562 remainder = partial_dividend - (Q[i] * divisor);
1568 // Now we're ready to invoke the Knuth classical divide algorithm. In this
1570 KnuthDiv(U, V, Q, R, m, n);
1573 // If the caller wants the quotient
1575 // Set up the Quotient value's memory.
1576 if (Quotient->BitWidth != LHS.BitWidth) {
1577 if (Quotient->isSingleWord())
1580 delete [] Quotient->pVal;
1581 Quotient->BitWidth = LHS.BitWidth;
1582 if (!Quotient->isSingleWord())
1583 Quotient->pVal = getClearedMemory(Quotient->getNumWords());
1587 // The quotient is in Q. Reconstitute the quotient into Quotient's low
1589 if (lhsWords == 1) {
1591 uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2));
1592 if (Quotient->isSingleWord())
1593 Quotient->VAL = tmp;
1595 Quotient->pVal[0] = tmp;
1597 assert(!Quotient->isSingleWord() && "Quotient APInt not large enough");
1598 for (unsigned i = 0; i < lhsWords; ++i)
1600 uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1604 // If the caller wants the remainder
1606 // Set up the Remainder value's memory.
1607 if (Remainder->BitWidth != RHS.BitWidth) {
1608 if (Remainder->isSingleWord())
1611 delete [] Remainder->pVal;
1612 Remainder->BitWidth = RHS.BitWidth;
1613 if (!Remainder->isSingleWord())
1614 Remainder->pVal = getClearedMemory(Remainder->getNumWords());
1618 // The remainder is in R. Reconstitute the remainder into Remainder's low
1620 if (rhsWords == 1) {
1622 uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2));
1623 if (Remainder->isSingleWord())
1624 Remainder->VAL = tmp;
1626 Remainder->pVal[0] = tmp;
1628 assert(!Remainder->isSingleWord() && "Remainder APInt not large enough");
1629 for (unsigned i = 0; i < rhsWords; ++i)
1630 Remainder->pVal[i] =
1631 uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1635 // Clean up the memory we allocated.
1636 if (U != &SPACE[0]) {
1644 APInt APInt::udiv(const APInt& RHS) const {
1645 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1647 // First, deal with the easy case
1648 if (isSingleWord()) {
1649 assert(RHS.VAL != 0 && "Divide by zero?");
1650 return APInt(BitWidth, VAL / RHS.VAL);
1653 // Get some facts about the LHS and RHS number of bits and words
1654 uint32_t rhsBits = RHS.getActiveBits();
1655 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
1656 assert(rhsWords && "Divided by zero???");
1657 uint32_t lhsBits = this->getActiveBits();
1658 uint32_t lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
1660 // Deal with some degenerate cases
1663 return APInt(BitWidth, 0);
1664 else if (lhsWords < rhsWords || this->ult(RHS)) {
1665 // X / Y ===> 0, iff X < Y
1666 return APInt(BitWidth, 0);
1667 } else if (*this == RHS) {
1669 return APInt(BitWidth, 1);
1670 } else if (lhsWords == 1 && rhsWords == 1) {
1671 // All high words are zero, just use native divide
1672 return APInt(BitWidth, this->pVal[0] / RHS.pVal[0]);
1675 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1676 APInt Quotient(1,0); // to hold result.
1677 divide(*this, lhsWords, RHS, rhsWords, &Quotient, 0);
1681 APInt APInt::urem(const APInt& RHS) const {
1682 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1683 if (isSingleWord()) {
1684 assert(RHS.VAL != 0 && "Remainder by zero?");
1685 return APInt(BitWidth, VAL % RHS.VAL);
1688 // Get some facts about the LHS
1689 uint32_t lhsBits = getActiveBits();
1690 uint32_t lhsWords = !lhsBits ? 0 : (whichWord(lhsBits - 1) + 1);
1692 // Get some facts about the RHS
1693 uint32_t rhsBits = RHS.getActiveBits();
1694 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
1695 assert(rhsWords && "Performing remainder operation by zero ???");
1697 // Check the degenerate cases
1698 if (lhsWords == 0) {
1700 return APInt(BitWidth, 0);
1701 } else if (lhsWords < rhsWords || this->ult(RHS)) {
1702 // X % Y ===> X, iff X < Y
1704 } else if (*this == RHS) {
1706 return APInt(BitWidth, 0);
1707 } else if (lhsWords == 1) {
1708 // All high words are zero, just use native remainder
1709 return APInt(BitWidth, pVal[0] % RHS.pVal[0]);
1712 // We have to compute it the hard way. Invoke the Knute divide algorithm.
1713 APInt Remainder(1,0);
1714 divide(*this, lhsWords, RHS, rhsWords, 0, &Remainder);
1718 void APInt::fromString(uint32_t numbits, const char *str, uint32_t slen,
1720 // Check our assumptions here
1721 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1722 "Radix should be 2, 8, 10, or 16!");
1723 assert(str && "String is null?");
1724 bool isNeg = str[0] == '-';
1727 assert(slen <= numbits || radix != 2 && "Insufficient bit width");
1728 assert(slen*3 <= numbits || radix != 8 && "Insufficient bit width");
1729 assert(slen*4 <= numbits || radix != 16 && "Insufficient bit width");
1730 assert((slen*64)/20 <= numbits || radix != 10 && "Insufficient bit width");
1733 if (!isSingleWord())
1734 pVal = getClearedMemory(getNumWords());
1736 // Figure out if we can shift instead of multiply
1737 uint32_t shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0);
1739 // Set up an APInt for the digit to add outside the loop so we don't
1740 // constantly construct/destruct it.
1741 APInt apdigit(getBitWidth(), 0);
1742 APInt apradix(getBitWidth(), radix);
1744 // Enter digit traversal loop
1745 for (unsigned i = 0; i < slen; i++) {
1748 char cdigit = str[i];
1749 if (isdigit(cdigit))
1750 digit = cdigit - '0';
1751 else if (isxdigit(cdigit))
1753 digit = cdigit - 'a' + 10;
1754 else if (cdigit >= 'A')
1755 digit = cdigit - 'A' + 10;
1757 assert(0 && "huh?");
1759 assert(0 && "Invalid character in digit string");
1761 // Shift or multiple the value by the radix
1767 // Add in the digit we just interpreted
1768 if (apdigit.isSingleWord())
1769 apdigit.VAL = digit;
1771 apdigit.pVal[0] = digit;
1774 // If its negative, put it in two's complement form
1781 std::string APInt::toString(uint8_t radix, bool wantSigned) const {
1782 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1783 "Radix should be 2, 8, 10, or 16!");
1784 static const char *digits[] = {
1785 "0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"
1788 uint32_t bits_used = getActiveBits();
1789 if (isSingleWord()) {
1791 const char *format = (radix == 10 ? (wantSigned ? "%lld" : "%llu") :
1792 (radix == 16 ? "%llX" : (radix == 8 ? "%llo" : 0)));
1795 int64_t sextVal = (int64_t(VAL) << (APINT_BITS_PER_WORD-BitWidth)) >>
1796 (APINT_BITS_PER_WORD-BitWidth);
1797 sprintf(buf, format, sextVal);
1799 sprintf(buf, format, VAL);
1804 uint32_t bit = v & 1;
1806 buf[bits_used] = digits[bit][0];
1815 uint64_t mask = radix - 1;
1816 uint32_t shift = (radix == 16 ? 4 : radix == 8 ? 3 : 1);
1817 uint32_t nibbles = APINT_BITS_PER_WORD / shift;
1818 for (uint32_t i = 0; i < getNumWords(); ++i) {
1819 uint64_t value = pVal[i];
1820 for (uint32_t j = 0; j < nibbles; ++j) {
1821 result.insert(0, digits[ value & mask ]);
1829 APInt divisor(4, radix);
1830 APInt zero(tmp.getBitWidth(), 0);
1831 size_t insert_at = 0;
1832 if (wantSigned && tmp[BitWidth-1]) {
1833 // They want to print the signed version and it is a negative value
1834 // Flip the bits and add one to turn it into the equivalent positive
1835 // value and put a '-' in the result.
1841 if (tmp == APInt(tmp.getBitWidth(), 0))
1843 else while (tmp.ne(zero)) {
1845 APInt tmp2(tmp.getBitWidth(), 0);
1846 divide(tmp, tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2,
1848 uint32_t digit = APdigit.getZExtValue();
1849 assert(digit < radix && "divide failed");
1850 result.insert(insert_at,digits[digit]);
1858 void APInt::dump() const
1860 cerr << "APInt(" << BitWidth << ")=" << std::setbase(16);
1863 else for (unsigned i = getNumWords(); i > 0; i--) {
1864 cerr << pVal[i-1] << " ";
1866 cerr << " U(" << this->toString(10) << ") S(" << this->toStringSigned(10)
1867 << ")\n" << std::setbase(10);