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"
22 // A utility function for allocating memory, checking for allocation failures,
23 // and ensuring the contents is zeroed.
24 inline static uint64_t* getClearedMemory(uint32_t numWords) {
25 uint64_t * result = new uint64_t[numWords];
26 assert(result && "APInt memory allocation fails!");
27 memset(result, 0, numWords * sizeof(uint64_t));
31 // A utility function for allocating memory and checking for allocation failure.
32 inline static uint64_t* getMemory(uint32_t numWords) {
33 uint64_t * result = new uint64_t[numWords];
34 assert(result && "APInt memory allocation fails!");
38 APInt::APInt(uint32_t numBits, uint64_t val)
40 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
41 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
43 VAL = val & (~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - BitWidth));
45 pVal = getClearedMemory(getNumWords());
50 APInt::APInt(uint32_t numBits, uint32_t numWords, uint64_t bigVal[])
52 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
53 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
54 assert(bigVal && "Null pointer detected!");
56 VAL = bigVal[0] & (~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - BitWidth));
58 pVal = getMemory(getNumWords());
59 // Calculate the actual length of bigVal[].
60 uint32_t maxN = std::max<uint32_t>(numWords, getNumWords());
61 uint32_t minN = std::min<uint32_t>(numWords, getNumWords());
62 memcpy(pVal, bigVal, (minN - 1) * APINT_WORD_SIZE);
63 pVal[minN-1] = bigVal[minN-1] &
65 (APINT_BITS_PER_WORD - BitWidth % APINT_BITS_PER_WORD));
66 if (maxN == getNumWords())
67 memset(pVal+numWords, 0, (getNumWords() - numWords) * APINT_WORD_SIZE);
71 /// @brief Create a new APInt by translating the char array represented
73 APInt::APInt(uint32_t numbits, const char StrStart[], uint32_t slen,
75 fromString(numbits, StrStart, slen, radix);
78 /// @brief Create a new APInt by translating the string represented
80 APInt::APInt(uint32_t numbits, const std::string& Val, uint8_t radix) {
81 assert(!Val.empty() && "String empty?");
82 fromString(numbits, Val.c_str(), Val.size(), radix);
85 /// @brief Copy constructor
86 APInt::APInt(const APInt& APIVal)
87 : BitWidth(APIVal.BitWidth) {
91 pVal = getMemory(getNumWords());
92 memcpy(pVal, APIVal.pVal, getNumWords() * APINT_WORD_SIZE);
97 if (!isSingleWord() && pVal) delete[] pVal;
100 /// @brief Copy assignment operator. Create a new object from the given
101 /// APInt one by initialization.
102 APInt& APInt::operator=(const APInt& RHS) {
103 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
107 memcpy(pVal, RHS.pVal, getNumWords() * APINT_WORD_SIZE);
111 /// @brief Assignment operator. Assigns a common case integer value to
113 APInt& APInt::operator=(uint64_t RHS) {
118 memset(pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
123 /// add_1 - This function adds a single "digit" integer, y, to the multiple
124 /// "digit" integer array, x[]. x[] is modified to reflect the addition and
125 /// 1 is returned if there is a carry out, otherwise 0 is returned.
126 /// @returns the carry of the addition.
127 static uint64_t add_1(uint64_t dest[],
128 uint64_t x[], uint32_t len,
130 for (uint32_t i = 0; i < len; ++i) {
142 /// @brief Prefix increment operator. Increments the APInt by one.
143 APInt& APInt::operator++() {
147 add_1(pVal, pVal, getNumWords(), 1);
152 /// sub_1 - This function subtracts a single "digit" (64-bit word), y, from
153 /// the multi-digit integer array, x[], propagating the borrowed 1 value until
154 /// no further borrowing is neeeded or it runs out of "digits" in x. The result
155 /// is 1 if "borrowing" exhausted the digits in x, or 0 if x was not exhausted.
156 /// In other words, if y > x then this function returns 1, otherwise 0.
157 static uint64_t sub_1(uint64_t x[], uint32_t len,
159 for (uint32_t i = 0; i < len; ++i) {
163 y = 1; // We have to "borrow 1" from next "digit"
165 y = 0; // No need to borrow
166 break; // Remaining digits are unchanged so exit early
172 /// @brief Prefix decrement operator. Decrements the APInt by one.
173 APInt& APInt::operator--() {
177 sub_1(pVal, getNumWords(), 1);
182 /// add - This function adds the integer array x[] by integer array
183 /// y[] and returns the carry.
184 static uint64_t add(uint64_t dest[], uint64_t x[],
185 uint64_t y[], uint32_t len) {
187 for (uint32_t i = 0; i< len; ++i) {
189 dest[i] = carry + y[i];
190 carry = carry < x[i] ? 1 : (dest[i] < carry ? 1 : 0);
195 /// @brief Addition assignment operator. Adds this APInt by the given APInt&
196 /// RHS and assigns the result to this APInt.
197 APInt& APInt::operator+=(const APInt& RHS) {
198 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
199 if (isSingleWord()) VAL += RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
201 if (RHS.isSingleWord()) add_1(pVal, pVal, getNumWords(), RHS.VAL);
203 if (getNumWords() <= RHS.getNumWords())
204 add(pVal, pVal, RHS.pVal, getNumWords());
206 uint64_t carry = add(pVal, pVal, RHS.pVal, RHS.getNumWords());
207 add_1(pVal + RHS.getNumWords(), pVal + RHS.getNumWords(),
208 getNumWords() - RHS.getNumWords(), carry);
216 /// sub - This function subtracts the integer array x[] by
217 /// integer array y[], and returns the borrow-out carry.
218 static uint64_t sub(uint64_t dest[], uint64_t x[],
219 uint64_t y[], uint32_t len) {
223 for (uint32_t i = 0; i < len; ++i) {
224 uint64_t Y = y[i], X = x[i];
235 /// @brief Subtraction assignment operator. Subtracts this APInt by the given
236 /// APInt &RHS and assigns the result to this APInt.
237 APInt& APInt::operator-=(const APInt& RHS) {
238 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
240 VAL -= RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
242 if (RHS.isSingleWord())
243 sub_1(pVal, getNumWords(), RHS.VAL);
245 if (RHS.getNumWords() < getNumWords()) {
246 uint64_t carry = sub(pVal, pVal, RHS.pVal, RHS.getNumWords());
247 sub_1(pVal + RHS.getNumWords(), getNumWords() - RHS.getNumWords(),
251 sub(pVal, pVal, RHS.pVal, getNumWords());
258 /// mul_1 - This function performs the multiplication operation on a
259 /// large integer (represented as an integer array) and a uint64_t integer.
260 /// @returns the carry of the multiplication.
261 static uint64_t mul_1(uint64_t dest[],
262 uint64_t x[], uint32_t len,
264 // Split y into high 32-bit part and low 32-bit part.
265 uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
266 uint64_t carry = 0, lx, hx;
267 for (uint32_t i = 0; i < len; ++i) {
268 lx = x[i] & 0xffffffffULL;
270 // hasCarry - A flag to indicate if has carry.
271 // hasCarry == 0, no carry
272 // hasCarry == 1, has carry
273 // hasCarry == 2, no carry and the calculation result == 0.
274 uint8_t hasCarry = 0;
275 dest[i] = carry + lx * ly;
276 // Determine if the add above introduces carry.
277 hasCarry = (dest[i] < carry) ? 1 : 0;
278 carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
279 // The upper limit of carry can be (2^32 - 1)(2^32 - 1) +
280 // (2^32 - 1) + 2^32 = 2^64.
281 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
283 carry += (lx * hy) & 0xffffffffULL;
284 dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
285 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) +
286 (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
292 /// mul - This function multiplies integer array x[] by integer array y[] and
293 /// stores the result into integer array dest[].
294 /// Note the array dest[]'s size should no less than xlen + ylen.
295 static void mul(uint64_t dest[], uint64_t x[], uint32_t xlen,
296 uint64_t y[], uint32_t ylen) {
297 dest[xlen] = mul_1(dest, x, xlen, y[0]);
299 for (uint32_t i = 1; i < ylen; ++i) {
300 uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
301 uint64_t carry = 0, lx, hx;
302 for (uint32_t j = 0; j < xlen; ++j) {
303 lx = x[j] & 0xffffffffULL;
305 // hasCarry - A flag to indicate if has carry.
306 // hasCarry == 0, no carry
307 // hasCarry == 1, has carry
308 // hasCarry == 2, no carry and the calculation result == 0.
309 uint8_t hasCarry = 0;
310 uint64_t resul = carry + lx * ly;
311 hasCarry = (resul < carry) ? 1 : 0;
312 carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
313 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
315 carry += (lx * hy) & 0xffffffffULL;
316 resul = (carry << 32) | (resul & 0xffffffffULL);
318 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
319 (carry >> 32) + (dest[i+j] < resul ? 1 : 0) +
320 ((lx * hy) >> 32) + hx * hy;
322 dest[i+xlen] = carry;
326 /// @brief Multiplication assignment operator. Multiplies this APInt by the
327 /// given APInt& RHS and assigns the result to this APInt.
328 APInt& APInt::operator*=(const APInt& RHS) {
329 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
330 if (isSingleWord()) VAL *= RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
332 // one-based first non-zero bit position.
333 uint32_t first = getActiveBits();
334 uint32_t xlen = !first ? 0 : whichWord(first - 1) + 1;
337 else if (RHS.isSingleWord())
338 mul_1(pVal, pVal, xlen, RHS.VAL);
340 first = RHS.getActiveBits();
341 uint32_t ylen = !first ? 0 : whichWord(first - 1) + 1;
343 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
346 uint64_t *dest = getMemory(xlen+ylen);
347 mul(dest, pVal, xlen, RHS.pVal, ylen);
348 memcpy(pVal, dest, ((xlen + ylen >= getNumWords()) ?
349 getNumWords() : xlen + ylen) * APINT_WORD_SIZE);
357 /// @brief Bitwise AND assignment operator. Performs bitwise AND operation on
358 /// this APInt and the given APInt& RHS, assigns the result to this APInt.
359 APInt& APInt::operator&=(const APInt& RHS) {
360 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
361 if (isSingleWord()) {
365 uint32_t numWords = getNumWords();
366 for (uint32_t i = 0; i < numWords; ++i)
367 pVal[i] &= RHS.pVal[i];
371 /// @brief Bitwise OR assignment operator. Performs bitwise OR operation on
372 /// this APInt and the given APInt& RHS, assigns the result to this APInt.
373 APInt& APInt::operator|=(const APInt& RHS) {
374 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
375 if (isSingleWord()) {
379 uint32_t numWords = getNumWords();
380 for (uint32_t i = 0; i < numWords; ++i)
381 pVal[i] |= RHS.pVal[i];
385 /// @brief Bitwise XOR assignment operator. Performs bitwise XOR 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()) {
393 uint32_t numWords = getNumWords();
394 for (uint32_t i = 0; i < numWords; ++i)
395 pVal[i] ^= RHS.pVal[i];
399 /// @brief Bitwise AND operator. Performs bitwise AND operation on this APInt
400 /// and the given APInt& RHS.
401 APInt APInt::operator&(const APInt& RHS) const {
402 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
404 return APInt(getBitWidth(), VAL & RHS.VAL);
407 uint32_t numWords = getNumWords();
408 for (uint32_t i = 0; i < numWords; ++i)
409 Result.pVal[i] &= RHS.pVal[i];
413 /// @brief Bitwise OR operator. Performs bitwise OR operation on this APInt
414 /// and the given APInt& RHS.
415 APInt APInt::operator|(const APInt& RHS) const {
416 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
418 return APInt(getBitWidth(), VAL | RHS.VAL);
420 uint32_t numWords = getNumWords();
421 for (uint32_t i = 0; i < numWords; ++i)
422 Result.pVal[i] |= RHS.pVal[i];
426 /// @brief Bitwise XOR operator. Performs bitwise XOR operation on this APInt
427 /// and the given APInt& RHS.
428 APInt APInt::operator^(const APInt& RHS) const {
429 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
431 return APInt(getBitWidth(), VAL ^ RHS.VAL);
433 uint32_t numWords = getNumWords();
434 for (uint32_t i = 0; i < numWords; ++i)
435 Result.pVal[i] ^= RHS.pVal[i];
439 /// @brief Logical negation operator. Performs logical negation operation on
441 bool APInt::operator !() const {
445 for (uint32_t i = 0; i < getNumWords(); ++i)
451 /// @brief Multiplication operator. Multiplies this APInt by the given APInt&
453 APInt APInt::operator*(const APInt& RHS) const {
454 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
457 API.clearUnusedBits();
461 /// @brief Addition operator. Adds this APInt by the given APInt& RHS.
462 APInt APInt::operator+(const APInt& RHS) const {
463 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
466 API.clearUnusedBits();
470 /// @brief Subtraction operator. Subtracts this APInt by the given APInt& RHS
471 APInt APInt::operator-(const APInt& RHS) const {
472 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
478 /// @brief Array-indexing support.
479 bool APInt::operator[](uint32_t bitPosition) const {
480 return (maskBit(bitPosition) & (isSingleWord() ?
481 VAL : pVal[whichWord(bitPosition)])) != 0;
484 /// @brief Equality operator. Compare this APInt with the given APInt& RHS
485 /// for the validity of the equality relationship.
486 bool APInt::operator==(const APInt& RHS) const {
487 uint32_t n1 = getActiveBits();
488 uint32_t n2 = RHS.getActiveBits();
489 if (n1 != n2) return false;
490 else if (isSingleWord())
491 return VAL == (RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0]);
493 if (n1 <= APINT_BITS_PER_WORD)
494 return pVal[0] == (RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0]);
495 for (int i = whichWord(n1 - 1); i >= 0; --i)
496 if (pVal[i] != RHS.pVal[i]) return false;
501 /// @brief Equality operator. Compare this APInt with the given uint64_t value
502 /// for the validity of the equality relationship.
503 bool APInt::operator==(uint64_t Val) const {
507 uint32_t n = getActiveBits();
508 if (n <= APINT_BITS_PER_WORD)
509 return pVal[0] == Val;
515 /// @brief Unsigned less than comparison
516 bool APInt::ult(const APInt& RHS) const {
517 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
519 return VAL < RHS.VAL;
521 uint32_t n1 = getActiveBits();
522 uint32_t n2 = RHS.getActiveBits();
527 else if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
528 return pVal[0] < RHS.pVal[0];
529 for (int i = whichWord(n1 - 1); i >= 0; --i) {
530 if (pVal[i] > RHS.pVal[i]) return false;
531 else if (pVal[i] < RHS.pVal[i]) return true;
537 /// @brief Signed less than comparison
538 bool APInt::slt(const APInt& RHS) const {
539 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
540 if (isSingleWord()) {
541 int64_t lhsSext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
542 int64_t rhsSext = (int64_t(RHS.VAL) << (64-BitWidth)) >> (64-BitWidth);
543 return lhsSext < rhsSext;
548 bool lhsNegative = false;
549 bool rhsNegative = false;
550 if (lhs[BitWidth-1]) {
555 if (rhs[BitWidth-1]) {
562 return !lhs.ult(rhs);
565 else if (rhsNegative)
571 /// Set the given bit to 1 whose poition is given as "bitPosition".
572 /// @brief Set a given bit to 1.
573 APInt& APInt::set(uint32_t bitPosition) {
574 if (isSingleWord()) VAL |= maskBit(bitPosition);
575 else pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
579 /// @brief Set every bit to 1.
580 APInt& APInt::set() {
582 VAL = ~0ULL >> (APINT_BITS_PER_WORD - BitWidth);
584 for (uint32_t i = 0; i < getNumWords() - 1; ++i)
586 pVal[getNumWords() - 1] = ~0ULL >>
587 (APINT_BITS_PER_WORD - BitWidth % APINT_BITS_PER_WORD);
592 /// Set the given bit to 0 whose position is given as "bitPosition".
593 /// @brief Set a given bit to 0.
594 APInt& APInt::clear(uint32_t bitPosition) {
596 VAL &= ~maskBit(bitPosition);
598 pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
602 /// @brief Set every bit to 0.
603 APInt& APInt::clear() {
607 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
611 /// @brief Bitwise NOT operator. Performs a bitwise logical NOT operation on
613 APInt APInt::operator~() const {
619 /// @brief Toggle every bit to its opposite value.
620 APInt& APInt::flip() {
621 if (isSingleWord()) VAL = (~(VAL <<
622 (APINT_BITS_PER_WORD - BitWidth))) >> (APINT_BITS_PER_WORD - BitWidth);
625 for (; i < getNumWords() - 1; ++i)
628 APINT_BITS_PER_WORD - (BitWidth - APINT_BITS_PER_WORD * (i - 1));
629 pVal[i] = (~(pVal[i] << offset)) >> offset;
634 /// Toggle a given bit to its opposite value whose position is given
635 /// as "bitPosition".
636 /// @brief Toggles a given bit to its opposite value.
637 APInt& APInt::flip(uint32_t bitPosition) {
638 assert(bitPosition < BitWidth && "Out of the bit-width range!");
639 if ((*this)[bitPosition]) clear(bitPosition);
640 else set(bitPosition);
644 /// to_string - This function translates the APInt into a string.
645 std::string APInt::toString(uint8_t radix, bool wantSigned) const {
646 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
647 "Radix should be 2, 8, 10, or 16!");
648 static const char *digits[] = {
649 "0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"
652 uint32_t bits_used = getActiveBits();
653 if (isSingleWord()) {
655 const char *format = (radix == 10 ? (wantSigned ? "%lld" : "%llu") :
656 (radix == 16 ? "%llX" : (radix == 8 ? "%llo" : 0)));
659 int64_t sextVal = (int64_t(VAL) << (APINT_BITS_PER_WORD-BitWidth)) >>
660 (APINT_BITS_PER_WORD-BitWidth);
661 sprintf(buf, format, sextVal);
663 sprintf(buf, format, VAL);
668 uint32_t bit = v & 1;
670 buf[bits_used] = digits[bit][0];
679 APInt divisor(tmp.getBitWidth(), radix);
680 APInt zero(tmp.getBitWidth(), 0);
681 size_t insert_at = 0;
682 if (wantSigned && tmp[BitWidth-1]) {
683 // They want to print the signed version and it is a negative value
684 // Flip the bits and add one to turn it into the equivalent positive
685 // value and put a '-' in the result.
693 else while (tmp.ne(zero)) {
694 APInt APdigit = APIntOps::urem(tmp,divisor);
695 uint32_t digit = APdigit.getValue();
696 assert(digit < radix && "urem failed");
697 result.insert(insert_at,digits[digit]);
698 tmp = APIntOps::udiv(tmp, divisor);
704 /// getMaxValue - This function returns the largest value
705 /// for an APInt of the specified bit-width and if isSign == true,
706 /// it should be largest signed value, otherwise unsigned value.
707 APInt APInt::getMaxValue(uint32_t numBits, bool isSign) {
708 APInt APIVal(numBits, 0);
710 if (isSign) APIVal.clear(numBits - 1);
714 /// getMinValue - This function returns the smallest value for
715 /// an APInt of the given bit-width and if isSign == true,
716 /// it should be smallest signed value, otherwise zero.
717 APInt APInt::getMinValue(uint32_t numBits, bool isSign) {
718 APInt APIVal(numBits, 0);
719 if (isSign) APIVal.set(numBits - 1);
723 /// getAllOnesValue - This function returns an all-ones value for
724 /// an APInt of the specified bit-width.
725 APInt APInt::getAllOnesValue(uint32_t numBits) {
726 return getMaxValue(numBits, false);
729 /// getNullValue - This function creates an '0' value for an
730 /// APInt of the specified bit-width.
731 APInt APInt::getNullValue(uint32_t numBits) {
732 return getMinValue(numBits, false);
735 /// HiBits - This function returns the high "numBits" bits of this APInt.
736 APInt APInt::getHiBits(uint32_t numBits) const {
737 return APIntOps::lshr(*this, BitWidth - numBits);
740 /// LoBits - This function returns the low "numBits" bits of this APInt.
741 APInt APInt::getLoBits(uint32_t numBits) const {
742 return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits),
746 bool APInt::isPowerOf2() const {
747 return (!!*this) && !(*this & (*this - APInt(BitWidth,1)));
750 /// countLeadingZeros - This function is a APInt version corresponding to
751 /// llvm/include/llvm/Support/MathExtras.h's function
752 /// countLeadingZeros_{32, 64}. It performs platform optimal form of counting
753 /// the number of zeros from the most significant bit to the first one bit.
754 /// @returns numWord() * 64 if the value is zero.
755 uint32_t APInt::countLeadingZeros() const {
757 return CountLeadingZeros_64(VAL) - (APINT_BITS_PER_WORD - BitWidth);
759 for (uint32_t i = getNumWords(); i > 0u; --i) {
760 uint32_t tmp = CountLeadingZeros_64(pVal[i-1]);
762 if (tmp != APINT_BITS_PER_WORD)
763 if (i == getNumWords())
764 Count -= (APINT_BITS_PER_WORD - whichBit(BitWidth));
770 /// countTrailingZeros - This function is a APInt version corresponding to
771 /// llvm/include/llvm/Support/MathExtras.h's function
772 /// countTrailingZeros_{32, 64}. It performs platform optimal form of counting
773 /// the number of zeros from the least significant bit to the first one bit.
774 /// @returns numWord() * 64 if the value is zero.
775 uint32_t APInt::countTrailingZeros() const {
777 return CountTrailingZeros_64(VAL);
778 APInt Tmp( ~(*this) & ((*this) - APInt(BitWidth,1)) );
779 return getNumWords() * APINT_BITS_PER_WORD - Tmp.countLeadingZeros();
782 /// countPopulation - This function is a APInt version corresponding to
783 /// llvm/include/llvm/Support/MathExtras.h's function
784 /// countPopulation_{32, 64}. It counts the number of set bits in a value.
785 /// @returns 0 if the value is zero.
786 uint32_t APInt::countPopulation() const {
788 return CountPopulation_64(VAL);
790 for (uint32_t i = 0; i < getNumWords(); ++i)
791 Count += CountPopulation_64(pVal[i]);
796 /// byteSwap - This function returns a byte-swapped representation of the
798 APInt APInt::byteSwap() const {
799 assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
801 return APInt(BitWidth, ByteSwap_16(VAL));
802 else if (BitWidth == 32)
803 return APInt(BitWidth, ByteSwap_32(VAL));
804 else if (BitWidth == 48) {
805 uint64_t Tmp1 = ((VAL >> 32) << 16) | (VAL & 0xFFFF);
806 Tmp1 = ByteSwap_32(Tmp1);
807 uint64_t Tmp2 = (VAL >> 16) & 0xFFFF;
808 Tmp2 = ByteSwap_16(Tmp2);
811 (Tmp1 & 0xff) | ((Tmp1<<16) & 0xffff00000000ULL) | (Tmp2 << 16));
812 } else if (BitWidth == 64)
813 return APInt(BitWidth, ByteSwap_64(VAL));
815 APInt Result(BitWidth, 0);
816 char *pByte = (char*)Result.pVal;
817 for (uint32_t i = 0; i < BitWidth / APINT_WORD_SIZE / 2; ++i) {
819 pByte[i] = pByte[BitWidth / APINT_WORD_SIZE - 1 - i];
820 pByte[BitWidth / APINT_WORD_SIZE - i - 1] = Tmp;
826 /// GreatestCommonDivisor - This function returns the greatest common
827 /// divisor of the two APInt values using Enclid's algorithm.
828 APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1,
830 APInt A = API1, B = API2;
833 B = APIntOps::urem(A, B);
839 /// DoubleRoundToAPInt - This function convert a double value to
841 APInt llvm::APIntOps::RoundDoubleToAPInt(double Double) {
847 bool isNeg = T.I >> 63;
848 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
850 return APInt(64ull, 0u);
851 uint64_t mantissa = ((T.I << 12) >> 12) | (1ULL << 52);
853 return isNeg ? -APInt(64u, mantissa >> (52 - exp)) :
854 APInt(64u, mantissa >> (52 - exp));
855 APInt Tmp(exp + 1, mantissa);
856 Tmp = Tmp.shl(exp - 52);
857 return isNeg ? -Tmp : Tmp;
860 /// RoundToDouble - This function convert this APInt to a double.
861 /// The layout for double is as following (IEEE Standard 754):
862 /// --------------------------------------
863 /// | Sign Exponent Fraction Bias |
864 /// |-------------------------------------- |
865 /// | 1[63] 11[62-52] 52[51-00] 1023 |
866 /// --------------------------------------
867 double APInt::roundToDouble(bool isSigned) const {
868 if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
870 int64_t sext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
876 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
877 APInt Tmp(isNeg ? -(*this) : (*this));
878 uint32_t n = Tmp.getActiveBits();
879 // Exponent when normalized to have decimal point directly after
880 // leading one. This is stored excess 1023 in the exponent bit field.
881 uint64_t exp = n - 1;
884 assert(exp <= 1023 && "Infinity value!");
886 // Number of bits in mantissa including the leading one
889 if (n % APINT_BITS_PER_WORD >= 53)
890 mantissa = Tmp.pVal[whichWord(n - 1)] >> (n % APINT_BITS_PER_WORD - 53);
892 mantissa = (Tmp.pVal[whichWord(n - 1)] << (53 - n % APINT_BITS_PER_WORD)) |
893 (Tmp.pVal[whichWord(n - 1) - 1] >>
894 (11 + n % APINT_BITS_PER_WORD));
895 // The leading bit of mantissa is implicit, so get rid of it.
896 mantissa &= ~(1ULL << 52);
897 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
903 T.I = sign | (exp << 52) | mantissa;
907 // Truncate to new width.
908 void APInt::trunc(uint32_t width) {
909 assert(width < BitWidth && "Invalid APInt Truncate request");
912 // Sign extend to a new width.
913 void APInt::sext(uint32_t width) {
914 assert(width > BitWidth && "Invalid APInt SignExtend request");
917 // Zero extend to a new width.
918 void APInt::zext(uint32_t width) {
919 assert(width > BitWidth && "Invalid APInt ZeroExtend request");
922 /// Arithmetic right-shift this APInt by shiftAmt.
923 /// @brief Arithmetic right-shift function.
924 APInt APInt::ashr(uint32_t shiftAmt) const {
926 if (API.isSingleWord())
928 (((int64_t(API.VAL) << (APINT_BITS_PER_WORD - API.BitWidth)) >>
929 (APINT_BITS_PER_WORD - API.BitWidth)) >> shiftAmt) &
930 (~uint64_t(0UL) >> (APINT_BITS_PER_WORD - API.BitWidth));
932 if (shiftAmt >= API.BitWidth) {
933 memset(API.pVal, API[API.BitWidth-1] ? 1 : 0,
934 (API.getNumWords()-1) * APINT_WORD_SIZE);
935 API.pVal[API.getNumWords() - 1] =
937 (APINT_BITS_PER_WORD - API.BitWidth % APINT_BITS_PER_WORD);
940 for (; i < API.BitWidth - shiftAmt; ++i)
945 for (; i < API.BitWidth; ++i)
946 if (API[API.BitWidth-1])
954 /// Logical right-shift this APInt by shiftAmt.
955 /// @brief Logical right-shift function.
956 APInt APInt::lshr(uint32_t shiftAmt) const {
958 if (API.isSingleWord())
959 API.VAL >>= shiftAmt;
961 if (shiftAmt >= API.BitWidth)
962 memset(API.pVal, 0, API.getNumWords() * APINT_WORD_SIZE);
964 for (i = 0; i < API.BitWidth - shiftAmt; ++i)
965 if (API[i+shiftAmt]) API.set(i);
967 for (; i < API.BitWidth; ++i)
973 /// Left-shift this APInt by shiftAmt.
974 /// @brief Left-shift function.
975 APInt APInt::shl(uint32_t shiftAmt) const {
977 if (API.isSingleWord())
978 API.VAL <<= shiftAmt;
979 else if (shiftAmt >= API.BitWidth)
980 memset(API.pVal, 0, API.getNumWords() * APINT_WORD_SIZE);
982 if (uint32_t offset = shiftAmt / APINT_BITS_PER_WORD) {
983 for (uint32_t i = API.getNumWords() - 1; i > offset - 1; --i)
984 API.pVal[i] = API.pVal[i-offset];
985 memset(API.pVal, 0, offset * APINT_WORD_SIZE);
987 shiftAmt %= APINT_BITS_PER_WORD;
989 for (i = API.getNumWords() - 1; i > 0; --i)
990 API.pVal[i] = (API.pVal[i] << shiftAmt) |
991 (API.pVal[i-1] >> (APINT_BITS_PER_WORD - shiftAmt));
992 API.pVal[i] <<= shiftAmt;
994 API.clearUnusedBits();
998 /// subMul - This function substracts x[len-1:0] * y from
999 /// dest[offset+len-1:offset], and returns the most significant
1000 /// word of the product, minus the borrow-out from the subtraction.
1001 static uint32_t subMul(uint32_t dest[], uint32_t offset,
1002 uint32_t x[], uint32_t len, uint32_t y) {
1003 uint64_t yl = (uint64_t) y & 0xffffffffL;
1007 uint64_t prod = ((uint64_t) x[j] & 0xffffffffUL) * yl;
1008 uint32_t prod_low = (uint32_t) prod;
1009 uint32_t prod_high = (uint32_t) (prod >> 32);
1011 carry = (prod_low < carry ? 1 : 0) + prod_high;
1012 uint32_t x_j = dest[offset+j];
1013 prod_low = x_j - prod_low;
1014 if (prod_low > x_j) ++carry;
1015 dest[offset+j] = prod_low;
1016 } while (++j < len);
1020 /// unitDiv - This function divides N by D,
1021 /// and returns (remainder << 32) | quotient.
1022 /// Assumes (N >> 32) < D.
1023 static uint64_t unitDiv(uint64_t N, uint32_t D) {
1024 uint64_t q, r; // q: quotient, r: remainder.
1025 uint64_t a1 = N >> 32; // a1: high 32-bit part of N.
1026 uint64_t a0 = N & 0xffffffffL; // a0: low 32-bit part of N
1027 if (a1 < ((D - a1 - (a0 >> 31)) & 0xffffffffL)) {
1032 // Compute c1*2^32 + c0 = a1*2^32 + a0 - 2^31*d
1033 uint64_t c = N - ((uint64_t) D << 31);
1034 // Divide (c1*2^32 + c0) by d
1037 // Add 2^31 to quotient
1041 return (r << 32) | (q & 0xFFFFFFFFl);
1044 /// div - This is basically Knuth's formulation of the classical algorithm.
1045 /// Correspondance with Knuth's notation:
1046 /// Knuth's u[0:m+n] == zds[nx:0].
1047 /// Knuth's v[1:n] == y[ny-1:0]
1048 /// Knuth's n == ny.
1049 /// Knuth's m == nx-ny.
1050 /// Our nx == Knuth's m+n.
1051 /// Could be re-implemented using gmp's mpn_divrem:
1052 /// zds[nx] = mpn_divrem (&zds[ny], 0, zds, nx, y, ny).
1053 static void div(uint32_t zds[], uint32_t nx, uint32_t y[], uint32_t ny) {
1055 do { // loop over digits of quotient
1056 // Knuth's j == our nx-j.
1057 // Knuth's u[j:j+n] == our zds[j:j-ny].
1058 uint32_t qhat; // treated as unsigned
1059 if (zds[j] == y[ny-1])
1060 qhat = -1U; // 0xffffffff
1062 uint64_t w = (((uint64_t)(zds[j])) << 32) +
1063 ((uint64_t)zds[j-1] & 0xffffffffL);
1064 qhat = (uint32_t) unitDiv(w, y[ny-1]);
1067 uint32_t borrow = subMul(zds, j - ny, y, ny, qhat);
1068 uint32_t save = zds[j];
1069 uint64_t num = ((uint64_t)save&0xffffffffL) -
1070 ((uint64_t)borrow&0xffffffffL);
1074 for (uint32_t i = 0; i < ny; i++) {
1075 carry += ((uint64_t) zds[j-ny+i] & 0xffffffffL)
1076 + ((uint64_t) y[i] & 0xffffffffL);
1077 zds[j-ny+i] = (uint32_t) carry;
1085 } while (--j >= ny);
1088 /// Unsigned divide this APInt by APInt RHS.
1089 /// @brief Unsigned division function for APInt.
1090 APInt APInt::udiv(const APInt& RHS) const {
1091 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1093 // First, deal with the easy case
1094 if (isSingleWord()) {
1095 assert(RHS.VAL != 0 && "Divide by zero?");
1096 return APInt(BitWidth, VAL / RHS.VAL);
1099 // Make a temporary to hold the result
1100 APInt Result(*this);
1102 // Get some facts about the LHS and RHS number of bits and words
1103 uint32_t rhsBits = RHS.getActiveBits();
1104 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
1105 assert(rhsWords && "Divided by zero???");
1106 uint32_t lhsBits = Result.getActiveBits();
1107 uint32_t lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
1109 // Deal with some degenerate cases
1111 return Result; // 0 / X == 0
1112 else if (lhsWords < rhsWords || Result.ult(RHS))
1113 // X / Y with X < Y == 0
1114 memset(Result.pVal, 0, Result.getNumWords() * APINT_WORD_SIZE);
1115 else if (Result == RHS) {
1117 memset(Result.pVal, 0, Result.getNumWords() * APINT_WORD_SIZE);
1119 } else if (lhsWords == 1)
1120 // All high words are zero, just use native divide
1121 Result.pVal[0] /= RHS.pVal[0];
1123 // Compute it the hard way ..
1124 APInt X(BitWidth, 0);
1125 APInt Y(BitWidth, 0);
1127 (APINT_BITS_PER_WORD - 1) - ((rhsBits - 1) % APINT_BITS_PER_WORD );
1129 Y = APIntOps::shl(RHS, nshift);
1130 X = APIntOps::shl(Result, nshift);
1133 div((uint32_t*)X.pVal, lhsWords * 2 - 1,
1134 (uint32_t*)(Y.isSingleWord()? &Y.VAL : Y.pVal), rhsWords*2);
1135 memset(Result.pVal, 0, Result.getNumWords() * APINT_WORD_SIZE);
1136 memcpy(Result.pVal, X.pVal + rhsWords,
1137 (lhsWords - rhsWords) * APINT_WORD_SIZE);
1142 /// Unsigned remainder operation on APInt.
1143 /// @brief Function for unsigned remainder operation.
1144 APInt APInt::urem(const APInt& RHS) const {
1145 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1146 if (isSingleWord()) {
1147 assert(RHS.VAL != 0 && "Remainder by zero?");
1148 return APInt(BitWidth, VAL % RHS.VAL);
1151 // Make a temporary to hold the result
1152 APInt Result(*this);
1154 // Get some facts about the RHS
1155 uint32_t rhsBits = RHS.getActiveBits();
1156 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
1157 assert(rhsWords && "Performing remainder operation by zero ???");
1159 // Get some facts about the LHS
1160 uint32_t lhsBits = Result.getActiveBits();
1161 uint32_t lhsWords = !lhsBits ? 0 : (Result.whichWord(lhsBits - 1) + 1);
1163 // Check the degenerate cases
1166 memset(Result.pVal, 0, Result.getNumWords() * APINT_WORD_SIZE);
1167 else if (lhsWords < rhsWords || Result.ult(RHS))
1168 // X % Y == X iff X < Y
1170 else if (Result == RHS)
1172 memset(Result.pVal, 0, Result.getNumWords() * APINT_WORD_SIZE);
1173 else if (lhsWords == 1)
1174 // All high words are zero, just use native remainder
1175 Result.pVal[0] %= RHS.pVal[0];
1177 // Do it the hard way
1178 APInt X((lhsWords+1)*APINT_BITS_PER_WORD, 0);
1179 APInt Y(rhsWords*APINT_BITS_PER_WORD, 0);
1181 (APINT_BITS_PER_WORD - 1) - (rhsBits - 1) % APINT_BITS_PER_WORD;
1183 APIntOps::shl(Y, nshift);
1184 APIntOps::shl(X, nshift);
1186 div((uint32_t*)X.pVal, rhsWords*2-1,
1187 (uint32_t*)(Y.isSingleWord()? &Y.VAL : Y.pVal), rhsWords*2);
1188 memset(Result.pVal, 0, Result.getNumWords() * APINT_WORD_SIZE);
1189 for (uint32_t i = 0; i < rhsWords-1; ++i)
1190 Result.pVal[i] = (X.pVal[i] >> nshift) |
1191 (X.pVal[i+1] << (APINT_BITS_PER_WORD - nshift));
1192 Result.pVal[rhsWords-1] = X.pVal[rhsWords-1] >> nshift;
1197 /// @brief Converts a char array into an integer.
1198 void APInt::fromString(uint32_t numbits, const char *StrStart, uint32_t slen,
1200 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1201 "Radix should be 2, 8, 10, or 16!");
1202 assert(StrStart && "String is null?");
1204 // If the radix is a power of 2, read the input
1205 // from most significant to least significant.
1206 if ((radix & (radix - 1)) == 0) {
1207 uint32_t nextBitPos = 0;
1208 uint32_t bits_per_digit = radix / 8 + 2;
1209 uint64_t resDigit = 0;
1210 BitWidth = slen * bits_per_digit;
1211 if (getNumWords() > 1)
1212 pVal = getMemory(getNumWords());
1213 for (int i = slen - 1; i >= 0; --i) {
1214 uint64_t digit = StrStart[i] - '0';
1215 resDigit |= digit << nextBitPos;
1216 nextBitPos += bits_per_digit;
1217 if (nextBitPos >= APINT_BITS_PER_WORD) {
1218 if (isSingleWord()) {
1222 pVal[size++] = resDigit;
1223 nextBitPos -= APINT_BITS_PER_WORD;
1224 resDigit = digit >> (bits_per_digit - nextBitPos);
1227 if (!isSingleWord() && size <= getNumWords())
1228 pVal[size] = resDigit;
1229 } else { // General case. The radix is not a power of 2.
1230 // For 10-radix, the max value of 64-bit integer is 18446744073709551615,
1231 // and its digits number is 20.
1232 const uint32_t chars_per_word = 20;
1233 if (slen < chars_per_word ||
1234 (slen == chars_per_word && // In case the value <= 2^64 - 1
1235 strcmp(StrStart, "18446744073709551615") <= 0)) {
1236 BitWidth = APINT_BITS_PER_WORD;
1237 VAL = strtoull(StrStart, 0, 10);
1238 } else { // In case the value > 2^64 - 1
1239 BitWidth = (slen / chars_per_word + 1) * APINT_BITS_PER_WORD;
1240 pVal = getClearedMemory(getNumWords());
1241 uint32_t str_pos = 0;
1242 while (str_pos < slen) {
1243 uint32_t chunk = slen - str_pos;
1244 if (chunk > chars_per_word - 1)
1245 chunk = chars_per_word - 1;
1246 uint64_t resDigit = StrStart[str_pos++] - '0';
1247 uint64_t big_base = radix;
1248 while (--chunk > 0) {
1249 resDigit = resDigit * radix + StrStart[str_pos++] - '0';
1257 carry = mul_1(pVal, pVal, size, big_base);
1258 carry += add_1(pVal, pVal, size, resDigit);
1261 if (carry) pVal[size++] = carry;