1 //===-- APInt.cpp - Implement APInt class ---------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Sheng Zhou and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a class to represent arbitrary precision integral
13 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/APInt.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Support/MathExtras.h"
23 /// lshift - This function shift x[0:len-1] left by shiftAmt bits, and
24 /// store the len least significant words of the result in
25 /// dest[d_offset:d_offset+len-1]. It returns the bits shifted out from
26 /// the most significant digit.
27 static uint64_t lshift(uint64_t dest[], unsigned d_offset,
28 uint64_t x[], unsigned len, unsigned shiftAmt) {
29 unsigned count = APINT_BITS_PER_WORD - shiftAmt;
31 uint64_t high_word = x[i], retVal = high_word >> count;
34 uint64_t low_word = x[i];
35 dest[d_offset+i] = (high_word << shiftAmt) | (low_word >> count);
38 dest[d_offset+i] = high_word << shiftAmt;
43 APInt::APInt(unsigned numBits, uint64_t val)
45 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
46 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
48 VAL = val & (~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - BitWidth));
50 // Memory allocation and check if successful.
51 assert((pVal = new uint64_t[getNumWords()]) &&
52 "APInt memory allocation fails!");
53 memset(pVal, 0, getNumWords() * 8);
58 APInt::APInt(unsigned numBits, unsigned numWords, uint64_t bigVal[])
60 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
61 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
62 assert(bigVal && "Null pointer detected!");
64 VAL = bigVal[0] & (~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - BitWidth));
66 // Memory allocation and check if successful.
67 assert((pVal = new uint64_t[getNumWords()]) &&
68 "APInt memory allocation fails!");
69 // Calculate the actual length of bigVal[].
70 unsigned maxN = std::max<unsigned>(numWords, getNumWords());
71 unsigned minN = std::min<unsigned>(numWords, getNumWords());
72 memcpy(pVal, bigVal, (minN - 1) * 8);
73 pVal[minN-1] = bigVal[minN-1] &
75 (APINT_BITS_PER_WORD - BitWidth % APINT_BITS_PER_WORD));
76 if (maxN == getNumWords())
77 memset(pVal+numWords, 0, (getNumWords() - numWords) * 8);
81 /// @brief Create a new APInt by translating the char array represented
83 APInt::APInt(unsigned numbits, const char StrStart[], unsigned slen,
85 fromString(numbits, StrStart, slen, radix);
88 /// @brief Create a new APInt by translating the string represented
90 APInt::APInt(unsigned numbits, const std::string& Val, uint8_t radix) {
91 assert(!Val.empty() && "String empty?");
92 fromString(numbits, Val.c_str(), Val.size(), radix);
95 APInt::APInt(const APInt& APIVal)
96 : BitWidth(APIVal.BitWidth) {
97 if (isSingleWord()) VAL = APIVal.VAL;
99 // Memory allocation and check if successful.
100 assert((pVal = new uint64_t[getNumWords()]) &&
101 "APInt memory allocation fails!");
102 memcpy(pVal, APIVal.pVal, getNumWords() * 8);
107 if (!isSingleWord() && pVal) delete[] pVal;
110 /// @brief Copy assignment operator. Create a new object from the given
111 /// APInt one by initialization.
112 APInt& APInt::operator=(const APInt& RHS) {
113 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
115 VAL = RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
117 unsigned minN = std::min(getNumWords(), RHS.getNumWords());
118 memcpy(pVal, RHS.isSingleWord() ? &RHS.VAL : RHS.pVal, minN * 8);
119 if (getNumWords() != minN)
120 memset(pVal + minN, 0, (getNumWords() - minN) * 8);
125 /// @brief Assignment operator. Assigns a common case integer value to
127 APInt& APInt::operator=(uint64_t RHS) {
132 memset(pVal, 0, (getNumWords() - 1) * 8);
138 /// add_1 - This function adds the integer array x[] by integer y and
139 /// returns the carry.
140 /// @returns the carry of the addition.
141 static uint64_t add_1(uint64_t dest[], uint64_t x[], unsigned len, uint64_t y) {
142 for (unsigned i = 0; i < len; ++i) {
154 /// @brief Prefix increment operator. Increments the APInt by one.
155 APInt& APInt::operator++() {
159 add_1(pVal, pVal, getNumWords(), 1);
164 /// sub_1 - This function subtracts the integer array x[] by
165 /// integer y and returns the borrow-out carry.
166 static uint64_t sub_1(uint64_t x[], unsigned len, uint64_t y) {
167 for (unsigned i = 0; i < len; ++i) {
180 /// @brief Prefix decrement operator. Decrements the APInt by one.
181 APInt& APInt::operator--() {
182 if (isSingleWord()) --VAL;
184 sub_1(pVal, getNumWords(), 1);
189 /// add - This function adds the integer array x[] by integer array
190 /// y[] and returns the carry.
191 static uint64_t add(uint64_t dest[], uint64_t x[], uint64_t y[], unsigned len) {
193 for (unsigned i = 0; i< len; ++i) {
195 dest[i] = carry + y[i];
196 carry = carry < x[i] ? 1 : (dest[i] < carry ? 1 : 0);
201 /// @brief Addition assignment operator. Adds this APInt by the given APInt&
202 /// RHS and assigns the result to this APInt.
203 APInt& APInt::operator+=(const APInt& RHS) {
204 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
205 if (isSingleWord()) VAL += RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
207 if (RHS.isSingleWord()) add_1(pVal, pVal, getNumWords(), RHS.VAL);
209 if (getNumWords() <= RHS.getNumWords())
210 add(pVal, pVal, RHS.pVal, getNumWords());
212 uint64_t carry = add(pVal, pVal, RHS.pVal, RHS.getNumWords());
213 add_1(pVal + RHS.getNumWords(), pVal + RHS.getNumWords(),
214 getNumWords() - RHS.getNumWords(), carry);
222 /// sub - This function subtracts the integer array x[] by
223 /// integer array y[], and returns the borrow-out carry.
224 static uint64_t sub(uint64_t dest[], uint64_t x[], uint64_t y[], unsigned len) {
228 for (unsigned i = 0; i < len; ++i) {
229 uint64_t Y = y[i], X = x[i];
240 /// @brief Subtraction assignment operator. Subtracts this APInt by the given
241 /// APInt &RHS and assigns the result to this APInt.
242 APInt& APInt::operator-=(const APInt& RHS) {
243 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
245 VAL -= RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
247 if (RHS.isSingleWord())
248 sub_1(pVal, getNumWords(), RHS.VAL);
250 if (RHS.getNumWords() < getNumWords()) {
251 uint64_t carry = sub(pVal, pVal, RHS.pVal, RHS.getNumWords());
252 sub_1(pVal + RHS.getNumWords(), getNumWords() - RHS.getNumWords(),
256 sub(pVal, pVal, RHS.pVal, getNumWords());
263 /// mul_1 - This function performs the multiplication operation on a
264 /// large integer (represented as an integer array) and a uint64_t integer.
265 /// @returns the carry of the multiplication.
266 static uint64_t mul_1(uint64_t dest[], uint64_t x[],
267 unsigned len, uint64_t y) {
268 // Split y into high 32-bit part and low 32-bit part.
269 uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
270 uint64_t carry = 0, lx, hx;
271 for (unsigned i = 0; i < len; ++i) {
272 lx = x[i] & 0xffffffffULL;
274 // hasCarry - A flag to indicate if has carry.
275 // hasCarry == 0, no carry
276 // hasCarry == 1, has carry
277 // hasCarry == 2, no carry and the calculation result == 0.
278 uint8_t hasCarry = 0;
279 dest[i] = carry + lx * ly;
280 // Determine if the add above introduces carry.
281 hasCarry = (dest[i] < carry) ? 1 : 0;
282 carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
283 // The upper limit of carry can be (2^32 - 1)(2^32 - 1) +
284 // (2^32 - 1) + 2^32 = 2^64.
285 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
287 carry += (lx * hy) & 0xffffffffULL;
288 dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
289 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) +
290 (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
296 /// mul - This function multiplies integer array x[] by integer array y[] and
297 /// stores the result into integer array dest[].
298 /// Note the array dest[]'s size should no less than xlen + ylen.
299 static void mul(uint64_t dest[], uint64_t x[], unsigned xlen,
300 uint64_t y[], unsigned ylen) {
301 dest[xlen] = mul_1(dest, x, xlen, y[0]);
303 for (unsigned i = 1; i < ylen; ++i) {
304 uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
305 uint64_t carry = 0, lx, hx;
306 for (unsigned j = 0; j < xlen; ++j) {
307 lx = x[j] & 0xffffffffULL;
309 // hasCarry - A flag to indicate if has carry.
310 // hasCarry == 0, no carry
311 // hasCarry == 1, has carry
312 // hasCarry == 2, no carry and the calculation result == 0.
313 uint8_t hasCarry = 0;
314 uint64_t resul = carry + lx * ly;
315 hasCarry = (resul < carry) ? 1 : 0;
316 carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
317 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
319 carry += (lx * hy) & 0xffffffffULL;
320 resul = (carry << 32) | (resul & 0xffffffffULL);
322 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
323 (carry >> 32) + (dest[i+j] < resul ? 1 : 0) +
324 ((lx * hy) >> 32) + hx * hy;
326 dest[i+xlen] = carry;
330 /// @brief Multiplication assignment operator. Multiplies this APInt by the
331 /// given APInt& RHS and assigns the result to this APInt.
332 APInt& APInt::operator*=(const APInt& RHS) {
333 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
334 if (isSingleWord()) VAL *= RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
336 // one-based first non-zero bit position.
337 unsigned first = getActiveBits();
338 unsigned xlen = !first ? 0 : whichWord(first - 1) + 1;
341 else if (RHS.isSingleWord())
342 mul_1(pVal, pVal, xlen, RHS.VAL);
344 first = RHS.getActiveBits();
345 unsigned ylen = !first ? 0 : whichWord(first - 1) + 1;
347 memset(pVal, 0, getNumWords() * 8);
350 uint64_t *dest = new uint64_t[xlen+ylen];
351 assert(dest && "Memory Allocation Failed!");
352 mul(dest, pVal, xlen, RHS.pVal, ylen);
353 memcpy(pVal, dest, ((xlen + ylen >= getNumWords()) ?
354 getNumWords() : xlen + ylen) * 8);
362 /// @brief Bitwise AND assignment operator. Performs bitwise AND operation on
363 /// this APInt and the given APInt& RHS, assigns the result to this APInt.
364 APInt& APInt::operator&=(const APInt& RHS) {
365 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
366 if (isSingleWord()) {
367 if (RHS.isSingleWord()) VAL &= RHS.VAL;
368 else VAL &= RHS.pVal[0];
370 if (RHS.isSingleWord()) {
371 memset(pVal, 0, (getNumWords() - 1) * 8);
374 unsigned minwords = getNumWords() < RHS.getNumWords() ?
375 getNumWords() : RHS.getNumWords();
376 for (unsigned i = 0; i < minwords; ++i)
377 pVal[i] &= RHS.pVal[i];
378 if (getNumWords() > minwords)
379 memset(pVal+minwords, 0, (getNumWords() - minwords) * 8);
385 /// @brief Bitwise OR assignment operator. Performs bitwise OR operation on
386 /// this APInt and the given APInt& RHS, assigns the result to this APInt.
387 APInt& APInt::operator|=(const APInt& RHS) {
388 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
389 if (isSingleWord()) {
390 if (RHS.isSingleWord()) VAL |= RHS.VAL;
391 else VAL |= RHS.pVal[0];
393 if (RHS.isSingleWord()) {
396 unsigned minwords = getNumWords() < RHS.getNumWords() ?
397 getNumWords() : RHS.getNumWords();
398 for (unsigned i = 0; i < minwords; ++i)
399 pVal[i] |= RHS.pVal[i];
406 /// @brief Bitwise XOR assignment operator. Performs bitwise XOR operation on
407 /// this APInt and the given APInt& RHS, assigns the result to this APInt.
408 APInt& APInt::operator^=(const APInt& RHS) {
409 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
410 if (isSingleWord()) {
414 unsigned numWords = getNumWords();
415 for (unsigned i = 0; i < numWords; ++i)
416 pVal[i] ^= RHS.pVal[i];
420 /// @brief Bitwise AND operator. Performs bitwise AND operation on this APInt
421 /// and the given APInt& RHS.
422 APInt APInt::operator&(const APInt& RHS) const {
423 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
428 /// @brief Bitwise OR operator. Performs bitwise OR operation on this APInt
429 /// and the given APInt& RHS.
430 APInt APInt::operator|(const APInt& RHS) const {
431 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
434 API.clearUnusedBits();
438 /// @brief Bitwise XOR operator. Performs bitwise XOR operation on this APInt
439 /// and the given APInt& RHS.
440 APInt APInt::operator^(const APInt& RHS) const {
441 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
444 API.clearUnusedBits();
449 /// @brief Logical negation operator. Performs logical negation operation on
451 bool APInt::operator !() const {
455 for (unsigned i = 0; i < getNumWords(); ++i)
461 /// @brief Multiplication operator. Multiplies this APInt by the given APInt&
463 APInt APInt::operator*(const APInt& RHS) const {
464 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
467 API.clearUnusedBits();
471 /// @brief Addition operator. Adds this APInt by the given APInt& RHS.
472 APInt APInt::operator+(const APInt& RHS) const {
473 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
476 API.clearUnusedBits();
480 /// @brief Subtraction operator. Subtracts this APInt by the given APInt& RHS
481 APInt APInt::operator-(const APInt& RHS) const {
482 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
488 /// @brief Array-indexing support.
489 bool APInt::operator[](unsigned bitPosition) const {
490 return (maskBit(bitPosition) & (isSingleWord() ?
491 VAL : pVal[whichWord(bitPosition)])) != 0;
494 /// @brief Equality operator. Compare this APInt with the given APInt& RHS
495 /// for the validity of the equality relationship.
496 bool APInt::operator==(const APInt& RHS) const {
497 unsigned n1 = getActiveBits();
498 unsigned n2 = RHS.getActiveBits();
499 if (n1 != n2) return false;
500 else if (isSingleWord())
501 return VAL == (RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0]);
503 if (n1 <= APINT_BITS_PER_WORD)
504 return pVal[0] == (RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0]);
505 for (int i = whichWord(n1 - 1); i >= 0; --i)
506 if (pVal[i] != RHS.pVal[i]) return false;
511 /// @brief Equality operator. Compare this APInt with the given uint64_t value
512 /// for the validity of the equality relationship.
513 bool APInt::operator==(uint64_t Val) const {
517 unsigned n = getActiveBits();
518 if (n <= APINT_BITS_PER_WORD)
519 return pVal[0] == Val;
525 /// @brief Unsigned less than comparison
526 bool APInt::ult(const APInt& RHS) const {
527 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
529 return VAL < RHS.VAL;
531 unsigned n1 = getActiveBits();
532 unsigned n2 = RHS.getActiveBits();
537 else if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
538 return pVal[0] < RHS.pVal[0];
539 for (int i = whichWord(n1 - 1); i >= 0; --i) {
540 if (pVal[i] > RHS.pVal[i]) return false;
541 else if (pVal[i] < RHS.pVal[i]) return true;
547 /// @brief Signed less than comparison
548 bool APInt::slt(const APInt& RHS) const {
549 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
551 return VAL < RHS.VAL;
553 unsigned n1 = getActiveBits();
554 unsigned n2 = RHS.getActiveBits();
559 else if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
560 return pVal[0] < RHS.pVal[0];
561 for (int i = whichWord(n1 - 1); i >= 0; --i) {
562 if (pVal[i] > RHS.pVal[i]) return false;
563 else if (pVal[i] < RHS.pVal[i]) return true;
569 /// Set the given bit to 1 whose poition is given as "bitPosition".
570 /// @brief Set a given bit to 1.
571 APInt& APInt::set(unsigned bitPosition) {
572 if (isSingleWord()) VAL |= maskBit(bitPosition);
573 else pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
577 /// @brief Set every bit to 1.
578 APInt& APInt::set() {
580 VAL = ~0ULL >> (APINT_BITS_PER_WORD - BitWidth);
582 for (unsigned i = 0; i < getNumWords() - 1; ++i)
584 pVal[getNumWords() - 1] = ~0ULL >>
585 (APINT_BITS_PER_WORD - BitWidth % APINT_BITS_PER_WORD);
590 /// Set the given bit to 0 whose position is given as "bitPosition".
591 /// @brief Set a given bit to 0.
592 APInt& APInt::clear(unsigned bitPosition) {
593 if (isSingleWord()) VAL &= ~maskBit(bitPosition);
594 else pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
598 /// @brief Set every bit to 0.
599 APInt& APInt::clear() {
600 if (isSingleWord()) VAL = 0;
602 memset(pVal, 0, getNumWords() * 8);
606 /// @brief Bitwise NOT operator. Performs a bitwise logical NOT operation on
608 APInt APInt::operator~() const {
614 /// @brief Toggle every bit to its opposite value.
615 APInt& APInt::flip() {
616 if (isSingleWord()) VAL = (~(VAL <<
617 (APINT_BITS_PER_WORD - BitWidth))) >> (APINT_BITS_PER_WORD - BitWidth);
620 for (; i < getNumWords() - 1; ++i)
623 APINT_BITS_PER_WORD - (BitWidth - APINT_BITS_PER_WORD * (i - 1));
624 pVal[i] = (~(pVal[i] << offset)) >> offset;
629 /// Toggle a given bit to its opposite value whose position is given
630 /// as "bitPosition".
631 /// @brief Toggles a given bit to its opposite value.
632 APInt& APInt::flip(unsigned bitPosition) {
633 assert(bitPosition < BitWidth && "Out of the bit-width range!");
634 if ((*this)[bitPosition]) clear(bitPosition);
635 else set(bitPosition);
639 /// to_string - This function translates the APInt into a string.
640 std::string APInt::toString(uint8_t radix, bool wantSigned) const {
641 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
642 "Radix should be 2, 8, 10, or 16!");
643 static const char *digits[] = {
644 "0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"
647 unsigned bits_used = getActiveBits();
648 if (isSingleWord()) {
650 const char *format = (radix == 10 ? (wantSigned ? "%lld" : "%llu") :
651 (radix == 16 ? "%llX" : (radix == 8 ? "%llo" : 0)));
654 int64_t sextVal = (int64_t(VAL) << (APINT_BITS_PER_WORD-BitWidth)) >>
655 (APINT_BITS_PER_WORD-BitWidth);
656 sprintf(buf, format, sextVal);
658 sprintf(buf, format, VAL);
663 unsigned bit = v & 1;
665 buf[bits_used] = digits[bit][0];
674 APInt divisor(tmp.getBitWidth(), radix);
675 APInt zero(tmp.getBitWidth(), 0);
676 size_t insert_at = 0;
677 if (wantSigned && tmp[BitWidth-1]) {
678 // They want to print the signed version and it is a negative value
679 // Flip the bits and add one to turn it into the equivalent positive
680 // value and put a '-' in the result.
688 else while (tmp.ne(zero)) {
689 APInt APdigit = APIntOps::urem(tmp,divisor);
690 unsigned digit = APdigit.getValue();
691 assert(digit < radix && "urem failed");
692 result.insert(insert_at,digits[digit]);
693 tmp = APIntOps::udiv(tmp, divisor);
699 /// getMaxValue - This function returns the largest value
700 /// for an APInt of the specified bit-width and if isSign == true,
701 /// it should be largest signed value, otherwise unsigned value.
702 APInt APInt::getMaxValue(unsigned numBits, bool isSign) {
703 APInt APIVal(numBits, 0);
705 if (isSign) APIVal.clear(numBits - 1);
709 /// getMinValue - This function returns the smallest value for
710 /// an APInt of the given bit-width and if isSign == true,
711 /// it should be smallest signed value, otherwise zero.
712 APInt APInt::getMinValue(unsigned numBits, bool isSign) {
713 APInt APIVal(numBits, 0);
714 if (isSign) APIVal.set(numBits - 1);
718 /// getAllOnesValue - This function returns an all-ones value for
719 /// an APInt of the specified bit-width.
720 APInt APInt::getAllOnesValue(unsigned numBits) {
721 return getMaxValue(numBits, false);
724 /// getNullValue - This function creates an '0' value for an
725 /// APInt of the specified bit-width.
726 APInt APInt::getNullValue(unsigned numBits) {
727 return getMinValue(numBits, false);
730 /// HiBits - This function returns the high "numBits" bits of this APInt.
731 APInt APInt::getHiBits(unsigned numBits) const {
732 return APIntOps::lshr(*this, BitWidth - numBits);
735 /// LoBits - This function returns the low "numBits" bits of this APInt.
736 APInt APInt::getLoBits(unsigned numBits) const {
737 return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits),
741 bool APInt::isPowerOf2() const {
742 return (!!*this) && !(*this & (*this - APInt(BitWidth,1)));
745 /// countLeadingZeros - This function is a APInt version corresponding to
746 /// llvm/include/llvm/Support/MathExtras.h's function
747 /// countLeadingZeros_{32, 64}. It performs platform optimal form of counting
748 /// the number of zeros from the most significant bit to the first one bit.
749 /// @returns numWord() * 64 if the value is zero.
750 unsigned APInt::countLeadingZeros() const {
752 return CountLeadingZeros_64(VAL) - (APINT_BITS_PER_WORD - BitWidth);
754 for (unsigned i = getNumWords(); i > 0u; --i) {
755 unsigned tmp = CountLeadingZeros_64(pVal[i-1]);
757 if (tmp != APINT_BITS_PER_WORD)
758 if (i == getNumWords())
759 Count -= (APINT_BITS_PER_WORD - whichBit(BitWidth));
765 /// countTrailingZeros - This function is a APInt version corresponding to
766 /// llvm/include/llvm/Support/MathExtras.h's function
767 /// countTrailingZeros_{32, 64}. It performs platform optimal form of counting
768 /// the number of zeros from the least significant bit to the first one bit.
769 /// @returns numWord() * 64 if the value is zero.
770 unsigned APInt::countTrailingZeros() const {
772 return CountTrailingZeros_64(VAL);
773 APInt Tmp( ~(*this) & ((*this) - APInt(BitWidth,1)) );
774 return getNumWords() * APINT_BITS_PER_WORD - Tmp.countLeadingZeros();
777 /// countPopulation - This function is a APInt version corresponding to
778 /// llvm/include/llvm/Support/MathExtras.h's function
779 /// countPopulation_{32, 64}. It counts the number of set bits in a value.
780 /// @returns 0 if the value is zero.
781 unsigned APInt::countPopulation() const {
783 return CountPopulation_64(VAL);
785 for (unsigned i = 0; i < getNumWords(); ++i)
786 Count += CountPopulation_64(pVal[i]);
791 /// byteSwap - This function returns a byte-swapped representation of the
793 APInt APInt::byteSwap() const {
794 assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
796 return APInt(BitWidth, ByteSwap_16(VAL));
797 else if (BitWidth == 32)
798 return APInt(BitWidth, ByteSwap_32(VAL));
799 else if (BitWidth == 48) {
800 uint64_t Tmp1 = ((VAL >> 32) << 16) | (VAL & 0xFFFF);
801 Tmp1 = ByteSwap_32(Tmp1);
802 uint64_t Tmp2 = (VAL >> 16) & 0xFFFF;
803 Tmp2 = ByteSwap_16(Tmp2);
806 (Tmp1 & 0xff) | ((Tmp1<<16) & 0xffff00000000ULL) | (Tmp2 << 16));
807 } else if (BitWidth == 64)
808 return APInt(BitWidth, ByteSwap_64(VAL));
810 APInt Result(BitWidth, 0);
811 char *pByte = (char*)Result.pVal;
812 for (unsigned i = 0; i < BitWidth / 8 / 2; ++i) {
814 pByte[i] = pByte[BitWidth / 8 - 1 - i];
815 pByte[BitWidth / 8 - i - 1] = Tmp;
821 /// GreatestCommonDivisor - This function returns the greatest common
822 /// divisor of the two APInt values using Enclid's algorithm.
823 APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1,
825 APInt A = API1, B = API2;
828 B = APIntOps::urem(A, B);
834 /// DoubleRoundToAPInt - This function convert a double value to
836 APInt llvm::APIntOps::RoundDoubleToAPInt(double Double) {
842 bool isNeg = T.I >> 63;
843 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
845 return APInt(64ull, 0u);
846 uint64_t mantissa = ((T.I << 12) >> 12) | (1ULL << 52);
848 return isNeg ? -APInt(64u, mantissa >> (52 - exp)) :
849 APInt(64u, mantissa >> (52 - exp));
850 APInt Tmp(exp + 1, mantissa);
851 Tmp = Tmp.shl(exp - 52);
852 return isNeg ? -Tmp : Tmp;
855 /// RoundToDouble - This function convert this APInt to a double.
856 /// The layout for double is as following (IEEE Standard 754):
857 /// --------------------------------------
858 /// | Sign Exponent Fraction Bias |
859 /// |-------------------------------------- |
860 /// | 1[63] 11[62-52] 52[51-00] 1023 |
861 /// --------------------------------------
862 double APInt::roundToDouble(bool isSigned) const {
863 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
864 APInt Tmp(isNeg ? -(*this) : (*this));
865 if (Tmp.isSingleWord())
866 return isSigned ? double(int64_t(Tmp.VAL)) : double(Tmp.VAL);
867 unsigned n = Tmp.getActiveBits();
868 if (n <= APINT_BITS_PER_WORD)
869 return isSigned ? double(int64_t(Tmp.pVal[0])) : double(Tmp.pVal[0]);
870 // Exponent when normalized to have decimal point directly after
871 // leading one. This is stored excess 1023 in the exponent bit field.
872 uint64_t exp = n - 1;
875 assert(exp <= 1023 && "Infinity value!");
877 // Number of bits in mantissa including the leading one
880 if (n % APINT_BITS_PER_WORD >= 53)
881 mantissa = Tmp.pVal[whichWord(n - 1)] >> (n % APINT_BITS_PER_WORD - 53);
883 mantissa = (Tmp.pVal[whichWord(n - 1)] << (53 - n % APINT_BITS_PER_WORD)) |
884 (Tmp.pVal[whichWord(n - 1) - 1] >>
885 (11 + n % APINT_BITS_PER_WORD));
886 // The leading bit of mantissa is implicit, so get rid of it.
887 mantissa &= ~(1ULL << 52);
888 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
894 T.I = sign | (exp << 52) | mantissa;
898 // Truncate to new width.
899 void APInt::trunc(unsigned width) {
900 assert(width < BitWidth && "Invalid APInt Truncate request");
903 // Sign extend to a new width.
904 void APInt::sext(unsigned width) {
905 assert(width > BitWidth && "Invalid APInt SignExtend request");
908 // Zero extend to a new width.
909 void APInt::zext(unsigned width) {
910 assert(width > BitWidth && "Invalid APInt ZeroExtend request");
913 /// Arithmetic right-shift this APInt by shiftAmt.
914 /// @brief Arithmetic right-shift function.
915 APInt APInt::ashr(unsigned shiftAmt) const {
917 if (API.isSingleWord())
919 (((int64_t(API.VAL) << (APINT_BITS_PER_WORD - API.BitWidth)) >>
920 (APINT_BITS_PER_WORD - API.BitWidth)) >> shiftAmt) &
921 (~uint64_t(0UL) >> (APINT_BITS_PER_WORD - API.BitWidth));
923 if (shiftAmt >= API.BitWidth) {
924 memset(API.pVal, API[API.BitWidth-1] ? 1 : 0, (API.getNumWords()-1) * 8);
925 API.pVal[API.getNumWords() - 1] =
927 (APINT_BITS_PER_WORD - API.BitWidth % APINT_BITS_PER_WORD);
930 for (; i < API.BitWidth - shiftAmt; ++i)
935 for (; i < API.BitWidth; ++i)
936 if (API[API.BitWidth-1])
944 /// Logical right-shift this APInt by shiftAmt.
945 /// @brief Logical right-shift function.
946 APInt APInt::lshr(unsigned shiftAmt) const {
948 if (API.isSingleWord())
949 API.VAL >>= shiftAmt;
951 if (shiftAmt >= API.BitWidth)
952 memset(API.pVal, 0, API.getNumWords() * 8);
954 for (i = 0; i < API.BitWidth - shiftAmt; ++i)
955 if (API[i+shiftAmt]) API.set(i);
957 for (; i < API.BitWidth; ++i)
963 /// Left-shift this APInt by shiftAmt.
964 /// @brief Left-shift function.
965 APInt APInt::shl(unsigned shiftAmt) const {
967 if (API.isSingleWord())
968 API.VAL <<= shiftAmt;
969 else if (shiftAmt >= API.BitWidth)
970 memset(API.pVal, 0, API.getNumWords() * 8);
972 if (unsigned offset = shiftAmt / APINT_BITS_PER_WORD) {
973 for (unsigned i = API.getNumWords() - 1; i > offset - 1; --i)
974 API.pVal[i] = API.pVal[i-offset];
975 memset(API.pVal, 0, offset * 8);
977 shiftAmt %= APINT_BITS_PER_WORD;
979 for (i = API.getNumWords() - 1; i > 0; --i)
980 API.pVal[i] = (API.pVal[i] << shiftAmt) |
981 (API.pVal[i-1] >> (APINT_BITS_PER_WORD - shiftAmt));
982 API.pVal[i] <<= shiftAmt;
984 API.clearUnusedBits();
988 /// subMul - This function substracts x[len-1:0] * y from
989 /// dest[offset+len-1:offset], and returns the most significant
990 /// word of the product, minus the borrow-out from the subtraction.
991 static unsigned subMul(unsigned dest[], unsigned offset,
992 unsigned x[], unsigned len, unsigned y) {
993 uint64_t yl = (uint64_t) y & 0xffffffffL;
997 uint64_t prod = ((uint64_t) x[j] & 0xffffffffUL) * yl;
998 unsigned prod_low = (unsigned) prod;
999 unsigned prod_high = (unsigned) (prod >> 32);
1001 carry = (prod_low < carry ? 1 : 0) + prod_high;
1002 unsigned x_j = dest[offset+j];
1003 prod_low = x_j - prod_low;
1004 if (prod_low > x_j) ++carry;
1005 dest[offset+j] = prod_low;
1006 } while (++j < len);
1010 /// unitDiv - This function divides N by D,
1011 /// and returns (remainder << 32) | quotient.
1012 /// Assumes (N >> 32) < D.
1013 static uint64_t unitDiv(uint64_t N, unsigned D) {
1014 uint64_t q, r; // q: quotient, r: remainder.
1015 uint64_t a1 = N >> 32; // a1: high 32-bit part of N.
1016 uint64_t a0 = N & 0xffffffffL; // a0: low 32-bit part of N
1017 if (a1 < ((D - a1 - (a0 >> 31)) & 0xffffffffL)) {
1022 // Compute c1*2^32 + c0 = a1*2^32 + a0 - 2^31*d
1023 uint64_t c = N - ((uint64_t) D << 31);
1024 // Divide (c1*2^32 + c0) by d
1027 // Add 2^31 to quotient
1031 return (r << 32) | (q & 0xFFFFFFFFl);
1034 /// div - This is basically Knuth's formulation of the classical algorithm.
1035 /// Correspondance with Knuth's notation:
1036 /// Knuth's u[0:m+n] == zds[nx:0].
1037 /// Knuth's v[1:n] == y[ny-1:0]
1038 /// Knuth's n == ny.
1039 /// Knuth's m == nx-ny.
1040 /// Our nx == Knuth's m+n.
1041 /// Could be re-implemented using gmp's mpn_divrem:
1042 /// zds[nx] = mpn_divrem (&zds[ny], 0, zds, nx, y, ny).
1043 static void div(unsigned zds[], unsigned nx, unsigned y[], unsigned ny) {
1045 do { // loop over digits of quotient
1046 // Knuth's j == our nx-j.
1047 // Knuth's u[j:j+n] == our zds[j:j-ny].
1048 unsigned qhat; // treated as unsigned
1049 if (zds[j] == y[ny-1])
1050 qhat = -1U; // 0xffffffff
1052 uint64_t w = (((uint64_t)(zds[j])) << 32) +
1053 ((uint64_t)zds[j-1] & 0xffffffffL);
1054 qhat = (unsigned) unitDiv(w, y[ny-1]);
1057 unsigned borrow = subMul(zds, j - ny, y, ny, qhat);
1058 unsigned save = zds[j];
1059 uint64_t num = ((uint64_t)save&0xffffffffL) -
1060 ((uint64_t)borrow&0xffffffffL);
1064 for (unsigned i = 0; i < ny; i++) {
1065 carry += ((uint64_t) zds[j-ny+i] & 0xffffffffL)
1066 + ((uint64_t) y[i] & 0xffffffffL);
1067 zds[j-ny+i] = (unsigned) carry;
1075 } while (--j >= ny);
1078 /// Unsigned divide this APInt by APInt RHS.
1079 /// @brief Unsigned division function for APInt.
1080 APInt APInt::udiv(const APInt& RHS) const {
1081 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1083 // First, deal with the easy case
1084 if (isSingleWord()) {
1085 assert(RHS.VAL != 0 && "Divide by zero?");
1086 return APInt(BitWidth, VAL / RHS.VAL);
1089 // Make a temporary to hold the result
1090 APInt Result(*this);
1092 // Get some facts about the LHS and RHS number of bits and words
1093 unsigned rhsBits = RHS.getActiveBits();
1094 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
1095 assert(rhsWords && "Divided by zero???");
1096 unsigned lhsBits = Result.getActiveBits();
1097 unsigned lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
1099 // Deal with some degenerate cases
1101 return Result; // 0 / X == 0
1102 else if (lhsWords < rhsWords || Result.ult(RHS))
1103 // X / Y with X < Y == 0
1104 memset(Result.pVal, 0, Result.getNumWords() * 8);
1105 else if (Result == RHS) {
1107 memset(Result.pVal, 0, Result.getNumWords() * 8);
1109 } else if (lhsWords == 1)
1110 // All high words are zero, just use native divide
1111 Result.pVal[0] /= RHS.pVal[0];
1113 // Compute it the hard way ..
1114 APInt X(BitWidth, 0);
1115 APInt Y(BitWidth, 0);
1117 (APINT_BITS_PER_WORD - 1) - ((rhsBits - 1) % APINT_BITS_PER_WORD );
1119 Y = APIntOps::shl(RHS, nshift);
1120 X = APIntOps::shl(Result, nshift);
1123 div((unsigned*)X.pVal, lhsWords * 2 - 1,
1124 (unsigned*)(Y.isSingleWord()? &Y.VAL : Y.pVal), rhsWords*2);
1125 memset(Result.pVal, 0, Result.getNumWords() * 8);
1126 memcpy(Result.pVal, X.pVal + rhsWords, (lhsWords - rhsWords) * 8);
1131 /// Unsigned remainder operation on APInt.
1132 /// @brief Function for unsigned remainder operation.
1133 APInt APInt::urem(const APInt& RHS) const {
1134 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1135 if (isSingleWord()) {
1136 assert(RHS.VAL != 0 && "Remainder by zero?");
1137 return APInt(BitWidth, VAL % RHS.VAL);
1140 // Make a temporary to hold the result
1141 APInt Result(*this);
1143 // Get some facts about the RHS
1144 unsigned rhsBits = RHS.getActiveBits();
1145 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
1146 assert(rhsWords && "Performing remainder operation by zero ???");
1148 // Get some facts about the LHS
1149 unsigned lhsBits = Result.getActiveBits();
1150 unsigned lhsWords = !lhsBits ? 0 : (Result.whichWord(lhsBits - 1) + 1);
1152 // Check the degenerate cases
1155 memset(Result.pVal, 0, Result.getNumWords() * 8);
1156 else if (lhsWords < rhsWords || Result.ult(RHS))
1157 // X % Y == X iff X < Y
1159 else if (Result == RHS)
1161 memset(Result.pVal, 0, Result.getNumWords() * 8);
1162 else if (lhsWords == 1)
1163 // All high words are zero, just use native remainder
1164 Result.pVal[0] %= RHS.pVal[0];
1166 // Do it the hard way
1167 APInt X((lhsWords+1)*APINT_BITS_PER_WORD, 0);
1168 APInt Y(rhsWords*APINT_BITS_PER_WORD, 0);
1170 (APINT_BITS_PER_WORD - 1) - (rhsBits - 1) % APINT_BITS_PER_WORD;
1172 APIntOps::shl(Y, nshift);
1173 APIntOps::shl(X, nshift);
1175 div((unsigned*)X.pVal, rhsWords*2-1,
1176 (unsigned*)(Y.isSingleWord()? &Y.VAL : Y.pVal), rhsWords*2);
1177 memset(Result.pVal, 0, Result.getNumWords() * 8);
1178 for (unsigned i = 0; i < rhsWords-1; ++i)
1179 Result.pVal[i] = (X.pVal[i] >> nshift) |
1180 (X.pVal[i+1] << (APINT_BITS_PER_WORD - nshift));
1181 Result.pVal[rhsWords-1] = X.pVal[rhsWords-1] >> nshift;
1186 /// @brief Converts a char array into an integer.
1187 void APInt::fromString(unsigned numbits, const char *StrStart, unsigned slen,
1189 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1190 "Radix should be 2, 8, 10, or 16!");
1191 assert(StrStart && "String is null?");
1193 // If the radix is a power of 2, read the input
1194 // from most significant to least significant.
1195 if ((radix & (radix - 1)) == 0) {
1196 unsigned nextBitPos = 0, bits_per_digit = radix / 8 + 2;
1197 uint64_t resDigit = 0;
1198 BitWidth = slen * bits_per_digit;
1199 if (getNumWords() > 1)
1200 assert((pVal = new uint64_t[getNumWords()]) &&
1201 "APInt memory allocation fails!");
1202 for (int i = slen - 1; i >= 0; --i) {
1203 uint64_t digit = StrStart[i] - '0';
1204 resDigit |= digit << nextBitPos;
1205 nextBitPos += bits_per_digit;
1206 if (nextBitPos >= APINT_BITS_PER_WORD) {
1207 if (isSingleWord()) {
1211 pVal[size++] = resDigit;
1212 nextBitPos -= APINT_BITS_PER_WORD;
1213 resDigit = digit >> (bits_per_digit - nextBitPos);
1216 if (!isSingleWord() && size <= getNumWords())
1217 pVal[size] = resDigit;
1218 } else { // General case. The radix is not a power of 2.
1219 // For 10-radix, the max value of 64-bit integer is 18446744073709551615,
1220 // and its digits number is 20.
1221 const unsigned chars_per_word = 20;
1222 if (slen < chars_per_word ||
1223 (slen == chars_per_word && // In case the value <= 2^64 - 1
1224 strcmp(StrStart, "18446744073709551615") <= 0)) {
1225 BitWidth = APINT_BITS_PER_WORD;
1226 VAL = strtoull(StrStart, 0, 10);
1227 } else { // In case the value > 2^64 - 1
1228 BitWidth = (slen / chars_per_word + 1) * APINT_BITS_PER_WORD;
1229 assert((pVal = new uint64_t[getNumWords()]) &&
1230 "APInt memory allocation fails!");
1231 memset(pVal, 0, getNumWords() * 8);
1232 unsigned str_pos = 0;
1233 while (str_pos < slen) {
1234 unsigned chunk = slen - str_pos;
1235 if (chunk > chars_per_word - 1)
1236 chunk = chars_per_word - 1;
1237 uint64_t resDigit = StrStart[str_pos++] - '0';
1238 uint64_t big_base = radix;
1239 while (--chunk > 0) {
1240 resDigit = resDigit * radix + StrStart[str_pos++] - '0';
1248 carry = mul_1(pVal, pVal, size, big_base);
1249 carry += add_1(pVal, pVal, size, resDigit);
1252 if (carry) pVal[size++] = carry;