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 /// mul_1 - This function performs the multiplication operation on a
23 /// large integer (represented as an integer array) and a uint64_t integer.
24 /// @returns the carry of the multiplication.
25 static uint64_t mul_1(uint64_t dest[], uint64_t x[],
26 unsigned len, uint64_t y) {
27 // Split y into high 32-bit part and low 32-bit part.
28 uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
29 uint64_t carry = 0, lx, hx;
30 for (unsigned i = 0; i < len; ++i) {
31 lx = x[i] & 0xffffffffULL;
33 // hasCarry - A flag to indicate if has carry.
34 // hasCarry == 0, no carry
35 // hasCarry == 1, has carry
36 // hasCarry == 2, no carry and the calculation result == 0.
38 dest[i] = carry + lx * ly;
39 // Determine if the add above introduces carry.
40 hasCarry = (dest[i] < carry) ? 1 : 0;
41 carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
42 // The upper limit of carry can be (2^32 - 1)(2^32 - 1) +
43 // (2^32 - 1) + 2^32 = 2^64.
44 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
46 carry += (lx * hy) & 0xffffffffULL;
47 dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
48 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) +
49 (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
55 /// mul - This function multiplies integer array x[] by integer array y[] and
56 /// stores the result into integer array dest[].
57 /// Note the array dest[]'s size should no less than xlen + ylen.
58 static void mul(uint64_t dest[], uint64_t x[], unsigned xlen,
59 uint64_t y[], unsigned ylen) {
60 dest[xlen] = mul_1(dest, x, xlen, y[0]);
62 for (unsigned i = 1; i < ylen; ++i) {
63 uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
64 uint64_t carry = 0, lx, hx;
65 for (unsigned j = 0; j < xlen; ++j) {
66 lx = x[j] & 0xffffffffULL;
68 // hasCarry - A flag to indicate if has carry.
69 // hasCarry == 0, no carry
70 // hasCarry == 1, has carry
71 // hasCarry == 2, no carry and the calculation result == 0.
73 uint64_t resul = carry + lx * ly;
74 hasCarry = (resul < carry) ? 1 : 0;
75 carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
76 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
78 carry += (lx * hy) & 0xffffffffULL;
79 resul = (carry << 32) | (resul & 0xffffffffULL);
81 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
82 (carry >> 32) + (dest[i+j] < resul ? 1 : 0) +
83 ((lx * hy) >> 32) + hx * hy;
89 /// add_1 - This function adds the integer array x[] by integer y and
90 /// returns the carry.
91 /// @returns the carry of the addition.
92 static uint64_t add_1(uint64_t dest[], uint64_t x[],
93 unsigned len, uint64_t y) {
96 for (unsigned i = 0; i < len; ++i) {
97 dest[i] = carry + x[i];
98 carry = (dest[i] < carry) ? 1 : 0;
103 /// add - This function adds the integer array x[] by integer array
104 /// y[] and returns the carry.
105 static uint64_t add(uint64_t dest[], uint64_t x[],
106 uint64_t y[], unsigned len) {
109 for (unsigned i = 0; i< len; ++i) {
111 dest[i] = carry + y[i];
112 carry = carry < x[i] ? 1 : (dest[i] < carry ? 1 : 0);
117 /// sub_1 - This function subtracts the integer array x[] by
118 /// integer y and returns the borrow-out carry.
119 static uint64_t sub_1(uint64_t x[], unsigned len, uint64_t y) {
122 for (unsigned i = 0; i < len; ++i) {
136 /// sub - This function subtracts the integer array x[] by
137 /// integer array y[], and returns the borrow-out carry.
138 static uint64_t sub(uint64_t dest[], uint64_t x[],
139 uint64_t y[], unsigned len) {
143 for (unsigned i = 0; i < len; ++i) {
144 uint64_t Y = y[i], X = x[i];
155 /// UnitDiv - This function divides N by D,
156 /// and returns (remainder << 32) | quotient.
157 /// Assumes (N >> 32) < D.
158 static uint64_t unitDiv(uint64_t N, unsigned D) {
159 uint64_t q, r; // q: quotient, r: remainder.
160 uint64_t a1 = N >> 32; // a1: high 32-bit part of N.
161 uint64_t a0 = N & 0xffffffffL; // a0: low 32-bit part of N
162 if (a1 < ((D - a1 - (a0 >> 31)) & 0xffffffffL)) {
167 // Compute c1*2^32 + c0 = a1*2^32 + a0 - 2^31*d
168 uint64_t c = N - ((uint64_t) D << 31);
169 // Divide (c1*2^32 + c0) by d
172 // Add 2^31 to quotient
176 return (r << 32) | (q & 0xFFFFFFFFl);
179 /// subMul - This function substracts x[len-1:0] * y from
180 /// dest[offset+len-1:offset], and returns the most significant
181 /// word of the product, minus the borrow-out from the subtraction.
182 static unsigned subMul(unsigned dest[], unsigned offset,
183 unsigned x[], unsigned len, unsigned y) {
184 uint64_t yl = (uint64_t) y & 0xffffffffL;
188 uint64_t prod = ((uint64_t) x[j] & 0xffffffffL) * yl;
189 unsigned prod_low = (unsigned) prod;
190 unsigned prod_high = (unsigned) (prod >> 32);
192 carry = (prod_low < carry ? 1 : 0) + prod_high;
193 unsigned x_j = dest[offset+j];
194 prod_low = x_j - prod_low;
195 if (prod_low > x_j) ++carry;
196 dest[offset+j] = prod_low;
201 /// div - This is basically Knuth's formulation of the classical algorithm.
202 /// Correspondance with Knuth's notation:
203 /// Knuth's u[0:m+n] == zds[nx:0].
204 /// Knuth's v[1:n] == y[ny-1:0]
206 /// Knuth's m == nx-ny.
207 /// Our nx == Knuth's m+n.
208 /// Could be re-implemented using gmp's mpn_divrem:
209 /// zds[nx] = mpn_divrem (&zds[ny], 0, zds, nx, y, ny).
210 static void div(unsigned zds[], unsigned nx, unsigned y[], unsigned ny) {
212 do { // loop over digits of quotient
213 // Knuth's j == our nx-j.
214 // Knuth's u[j:j+n] == our zds[j:j-ny].
215 unsigned qhat; // treated as unsigned
216 if (zds[j] == y[ny-1]) qhat = -1U; // 0xffffffff
218 uint64_t w = (((uint64_t)(zds[j])) << 32) +
219 ((uint64_t)zds[j-1] & 0xffffffffL);
220 qhat = (unsigned) unitDiv(w, y[ny-1]);
223 unsigned borrow = subMul(zds, j - ny, y, ny, qhat);
224 unsigned save = zds[j];
225 uint64_t num = ((uint64_t)save&0xffffffffL) -
226 ((uint64_t)borrow&0xffffffffL);
230 for (unsigned i = 0; i < ny; i++) {
231 carry += ((uint64_t) zds[j-ny+i] & 0xffffffffL)
232 + ((uint64_t) y[i] & 0xffffffffL);
233 zds[j-ny+i] = (unsigned) carry;
245 /// lshift - This function shift x[0:len-1] left by shiftAmt bits, and
246 /// store the len least significant words of the result in
247 /// dest[d_offset:d_offset+len-1]. It returns the bits shifted out from
248 /// the most significant digit.
249 static uint64_t lshift(uint64_t dest[], unsigned d_offset,
250 uint64_t x[], unsigned len, unsigned shiftAmt) {
251 unsigned count = 64 - shiftAmt;
253 uint64_t high_word = x[i], retVal = high_word >> count;
256 uint64_t low_word = x[i];
257 dest[d_offset+i] = (high_word << shiftAmt) | (low_word >> count);
258 high_word = low_word;
260 dest[d_offset+i] = high_word << shiftAmt;
265 APInt::APInt(unsigned numBits, uint64_t val)
266 : BitWidth(numBits) {
267 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
268 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
270 VAL = val & (~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - BitWidth));
272 // Memory allocation and check if successful.
273 assert((pVal = new uint64_t[getNumWords()]) &&
274 "APInt memory allocation fails!");
275 memset(pVal, 0, getNumWords() * 8);
280 APInt::APInt(unsigned numBits, unsigned numWords, uint64_t bigVal[])
281 : BitWidth(numBits) {
282 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
283 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
284 assert(bigVal && "Null pointer detected!");
286 VAL = bigVal[0] & (~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - BitWidth));
288 // Memory allocation and check if successful.
289 assert((pVal = new uint64_t[getNumWords()]) &&
290 "APInt memory allocation fails!");
291 // Calculate the actual length of bigVal[].
292 unsigned maxN = std::max<unsigned>(numWords, getNumWords());
293 unsigned minN = std::min<unsigned>(numWords, getNumWords());
294 memcpy(pVal, bigVal, (minN - 1) * 8);
295 pVal[minN-1] = bigVal[minN-1] & (~uint64_t(0ULL) >> (64 - BitWidth % 64));
296 if (maxN == getNumWords())
297 memset(pVal+numWords, 0, (getNumWords() - numWords) * 8);
301 /// @brief Create a new APInt by translating the char array represented
303 APInt::APInt(unsigned numbits, const char StrStart[], unsigned slen,
305 fromString(numbits, StrStart, slen, radix);
308 /// @brief Create a new APInt by translating the string represented
310 APInt::APInt(unsigned numbits, const std::string& Val, uint8_t radix) {
311 assert(!Val.empty() && "String empty?");
312 fromString(numbits, Val.c_str(), Val.size(), radix);
315 /// @brief Converts a char array into an integer.
316 void APInt::fromString(unsigned numbits, const char *StrStart, unsigned slen,
318 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
319 "Radix should be 2, 8, 10, or 16!");
320 assert(StrStart && "String is null?");
322 // If the radix is a power of 2, read the input
323 // from most significant to least significant.
324 if ((radix & (radix - 1)) == 0) {
325 unsigned nextBitPos = 0, bits_per_digit = radix / 8 + 2;
326 uint64_t resDigit = 0;
327 BitWidth = slen * bits_per_digit;
328 if (getNumWords() > 1)
329 assert((pVal = new uint64_t[getNumWords()]) &&
330 "APInt memory allocation fails!");
331 for (int i = slen - 1; i >= 0; --i) {
332 uint64_t digit = StrStart[i] - 48; // '0' == 48.
333 resDigit |= digit << nextBitPos;
334 nextBitPos += bits_per_digit;
335 if (nextBitPos >= 64) {
336 if (isSingleWord()) {
340 pVal[size++] = resDigit;
342 resDigit = digit >> (bits_per_digit - nextBitPos);
345 if (!isSingleWord() && size <= getNumWords())
346 pVal[size] = resDigit;
347 } else { // General case. The radix is not a power of 2.
348 // For 10-radix, the max value of 64-bit integer is 18446744073709551615,
349 // and its digits number is 20.
350 const unsigned chars_per_word = 20;
351 if (slen < chars_per_word ||
352 (slen == chars_per_word && // In case the value <= 2^64 - 1
353 strcmp(StrStart, "18446744073709551615") <= 0)) {
355 VAL = strtoull(StrStart, 0, 10);
356 } else { // In case the value > 2^64 - 1
357 BitWidth = (slen / chars_per_word + 1) * 64;
358 assert((pVal = new uint64_t[getNumWords()]) &&
359 "APInt memory allocation fails!");
360 memset(pVal, 0, getNumWords() * 8);
361 unsigned str_pos = 0;
362 while (str_pos < slen) {
363 unsigned chunk = slen - str_pos;
364 if (chunk > chars_per_word - 1)
365 chunk = chars_per_word - 1;
366 uint64_t resDigit = StrStart[str_pos++] - 48; // 48 == '0'.
367 uint64_t big_base = radix;
368 while (--chunk > 0) {
369 resDigit = resDigit * radix + StrStart[str_pos++] - 48;
377 carry = mul_1(pVal, pVal, size, big_base);
378 carry += add_1(pVal, pVal, size, resDigit);
381 if (carry) pVal[size++] = carry;
387 APInt::APInt(const APInt& APIVal)
388 : BitWidth(APIVal.BitWidth) {
389 if (isSingleWord()) VAL = APIVal.VAL;
391 // Memory allocation and check if successful.
392 assert((pVal = new uint64_t[getNumWords()]) &&
393 "APInt memory allocation fails!");
394 memcpy(pVal, APIVal.pVal, getNumWords() * 8);
399 if (!isSingleWord() && pVal) delete[] pVal;
402 /// @brief Copy assignment operator. Create a new object from the given
403 /// APInt one by initialization.
404 APInt& APInt::operator=(const APInt& RHS) {
405 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
407 VAL = RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
409 unsigned minN = std::min(getNumWords(), RHS.getNumWords());
410 memcpy(pVal, RHS.isSingleWord() ? &RHS.VAL : RHS.pVal, minN * 8);
411 if (getNumWords() != minN)
412 memset(pVal + minN, 0, (getNumWords() - minN) * 8);
417 /// @brief Assignment operator. Assigns a common case integer value to
419 APInt& APInt::operator=(uint64_t RHS) {
424 memset(pVal, 0, (getNumWords() - 1) * 8);
430 /// @brief Prefix increment operator. Increments the APInt by one.
431 APInt& APInt::operator++() {
435 add_1(pVal, pVal, getNumWords(), 1);
440 /// @brief Prefix decrement operator. Decrements the APInt by one.
441 APInt& APInt::operator--() {
442 if (isSingleWord()) --VAL;
444 sub_1(pVal, getNumWords(), 1);
449 /// @brief Addition assignment operator. Adds this APInt by the given APInt&
450 /// RHS and assigns the result to this APInt.
451 APInt& APInt::operator+=(const APInt& RHS) {
452 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
453 if (isSingleWord()) VAL += RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
455 if (RHS.isSingleWord()) add_1(pVal, pVal, getNumWords(), RHS.VAL);
457 if (getNumWords() <= RHS.getNumWords())
458 add(pVal, pVal, RHS.pVal, getNumWords());
460 uint64_t carry = add(pVal, pVal, RHS.pVal, RHS.getNumWords());
461 add_1(pVal + RHS.getNumWords(), pVal + RHS.getNumWords(),
462 getNumWords() - RHS.getNumWords(), carry);
470 /// @brief Subtraction assignment operator. Subtracts this APInt by the given
471 /// APInt &RHS and assigns the result to this APInt.
472 APInt& APInt::operator-=(const APInt& RHS) {
473 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
475 VAL -= RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
477 if (RHS.isSingleWord())
478 sub_1(pVal, getNumWords(), RHS.VAL);
480 if (RHS.getNumWords() < getNumWords()) {
481 uint64_t carry = sub(pVal, pVal, RHS.pVal, RHS.getNumWords());
482 sub_1(pVal + RHS.getNumWords(), getNumWords() - RHS.getNumWords(), carry);
485 sub(pVal, pVal, RHS.pVal, getNumWords());
492 /// @brief Multiplication assignment operator. Multiplies this APInt by the
493 /// given APInt& RHS and assigns the result to this APInt.
494 APInt& APInt::operator*=(const APInt& RHS) {
495 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
496 if (isSingleWord()) VAL *= RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
498 // one-based first non-zero bit position.
499 unsigned first = getActiveBits();
500 unsigned xlen = !first ? 0 : whichWord(first - 1) + 1;
503 else if (RHS.isSingleWord())
504 mul_1(pVal, pVal, xlen, RHS.VAL);
506 first = RHS.getActiveBits();
507 unsigned ylen = !first ? 0 : whichWord(first - 1) + 1;
509 memset(pVal, 0, getNumWords() * 8);
512 uint64_t *dest = new uint64_t[xlen+ylen];
513 assert(dest && "Memory Allocation Failed!");
514 mul(dest, pVal, xlen, RHS.pVal, ylen);
515 memcpy(pVal, dest, ((xlen + ylen >= getNumWords()) ?
516 getNumWords() : xlen + ylen) * 8);
524 /// @brief Bitwise AND assignment operator. Performs bitwise AND operation on
525 /// this APInt and the given APInt& RHS, assigns the result to this APInt.
526 APInt& APInt::operator&=(const APInt& RHS) {
527 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
528 if (isSingleWord()) {
529 if (RHS.isSingleWord()) VAL &= RHS.VAL;
530 else VAL &= RHS.pVal[0];
532 if (RHS.isSingleWord()) {
533 memset(pVal, 0, (getNumWords() - 1) * 8);
536 unsigned minwords = getNumWords() < RHS.getNumWords() ?
537 getNumWords() : RHS.getNumWords();
538 for (unsigned i = 0; i < minwords; ++i)
539 pVal[i] &= RHS.pVal[i];
540 if (getNumWords() > minwords)
541 memset(pVal+minwords, 0, (getNumWords() - minwords) * 8);
547 /// @brief Bitwise OR assignment operator. Performs bitwise OR operation on
548 /// this APInt and the given APInt& RHS, assigns the result to this APInt.
549 APInt& APInt::operator|=(const APInt& RHS) {
550 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
551 if (isSingleWord()) {
552 if (RHS.isSingleWord()) VAL |= RHS.VAL;
553 else VAL |= RHS.pVal[0];
555 if (RHS.isSingleWord()) {
558 unsigned minwords = getNumWords() < RHS.getNumWords() ?
559 getNumWords() : RHS.getNumWords();
560 for (unsigned i = 0; i < minwords; ++i)
561 pVal[i] |= RHS.pVal[i];
568 /// @brief Bitwise XOR assignment operator. Performs bitwise XOR operation on
569 /// this APInt and the given APInt& RHS, assigns the result to this APInt.
570 APInt& APInt::operator^=(const APInt& RHS) {
571 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
572 if (isSingleWord()) {
573 if (RHS.isSingleWord()) VAL ^= RHS.VAL;
574 else VAL ^= RHS.pVal[0];
576 if (RHS.isSingleWord()) {
577 for (unsigned i = 0; i < getNumWords(); ++i)
580 unsigned minwords = getNumWords() < RHS.getNumWords() ?
581 getNumWords() : RHS.getNumWords();
582 for (unsigned i = 0; i < minwords; ++i)
583 pVal[i] ^= RHS.pVal[i];
584 if (getNumWords() > minwords)
585 for (unsigned i = minwords; i < getNumWords(); ++i)
593 /// @brief Bitwise AND operator. Performs bitwise AND operation on this APInt
594 /// and the given APInt& RHS.
595 APInt APInt::operator&(const APInt& RHS) const {
596 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
601 /// @brief Bitwise OR operator. Performs bitwise OR operation on this APInt
602 /// and the given APInt& RHS.
603 APInt APInt::operator|(const APInt& RHS) const {
604 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
607 API.clearUnusedBits();
611 /// @brief Bitwise XOR operator. Performs bitwise XOR operation on this APInt
612 /// and the given APInt& RHS.
613 APInt APInt::operator^(const APInt& RHS) const {
614 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
617 API.clearUnusedBits();
622 /// @brief Logical negation operator. Performs logical negation operation on
624 bool APInt::operator !() const {
628 for (unsigned i = 0; i < getNumWords(); ++i)
634 /// @brief Multiplication operator. Multiplies this APInt by the given APInt&
636 APInt APInt::operator*(const APInt& RHS) const {
637 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
640 API.clearUnusedBits();
644 /// @brief Addition operator. Adds this APInt by the given APInt& RHS.
645 APInt APInt::operator+(const APInt& RHS) const {
646 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
649 API.clearUnusedBits();
653 /// @brief Subtraction operator. Subtracts this APInt by the given APInt& RHS
654 APInt APInt::operator-(const APInt& RHS) const {
655 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
661 /// @brief Array-indexing support.
662 bool APInt::operator[](unsigned bitPosition) const {
663 return (maskBit(bitPosition) & (isSingleWord() ?
664 VAL : pVal[whichWord(bitPosition)])) != 0;
667 /// @brief Equality operator. Compare this APInt with the given APInt& RHS
668 /// for the validity of the equality relationship.
669 bool APInt::operator==(const APInt& RHS) const {
670 unsigned n1 = getActiveBits();
671 unsigned n2 = RHS.getActiveBits();
672 if (n1 != n2) return false;
673 else if (isSingleWord())
674 return VAL == (RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0]);
677 return pVal[0] == (RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0]);
678 for (int i = whichWord(n1 - 1); i >= 0; --i)
679 if (pVal[i] != RHS.pVal[i]) return false;
684 /// @brief Equality operator. Compare this APInt with the given uint64_t value
685 /// for the validity of the equality relationship.
686 bool APInt::operator==(uint64_t Val) const {
690 unsigned n = getActiveBits();
692 return pVal[0] == Val;
698 /// @brief Unsigned less than comparison
699 bool APInt::ult(const APInt& RHS) const {
700 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
702 return VAL < RHS.VAL;
704 unsigned n1 = getActiveBits();
705 unsigned n2 = RHS.getActiveBits();
710 else if (n1 <= 64 && n2 <= 64)
711 return pVal[0] < RHS.pVal[0];
712 for (int i = whichWord(n1 - 1); i >= 0; --i) {
713 if (pVal[i] > RHS.pVal[i]) return false;
714 else if (pVal[i] < RHS.pVal[i]) return true;
720 /// @brief Signed less than comparison
721 bool APInt::slt(const APInt& RHS) const {
722 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
724 return VAL < RHS.VAL;
726 unsigned n1 = getActiveBits();
727 unsigned n2 = RHS.getActiveBits();
732 else if (n1 <= 64 && n2 <= 64)
733 return pVal[0] < RHS.pVal[0];
734 for (int i = whichWord(n1 - 1); i >= 0; --i) {
735 if (pVal[i] > RHS.pVal[i]) return false;
736 else if (pVal[i] < RHS.pVal[i]) return true;
742 /// Set the given bit to 1 whose poition is given as "bitPosition".
743 /// @brief Set a given bit to 1.
744 APInt& APInt::set(unsigned bitPosition) {
745 if (isSingleWord()) VAL |= maskBit(bitPosition);
746 else pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
750 /// @brief Set every bit to 1.
751 APInt& APInt::set() {
752 if (isSingleWord()) VAL = ~0ULL >> (64 - BitWidth);
754 for (unsigned i = 0; i < getNumWords() - 1; ++i)
756 pVal[getNumWords() - 1] = ~0ULL >> (64 - BitWidth % 64);
761 /// Set the given bit to 0 whose position is given as "bitPosition".
762 /// @brief Set a given bit to 0.
763 APInt& APInt::clear(unsigned bitPosition) {
764 if (isSingleWord()) VAL &= ~maskBit(bitPosition);
765 else pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
769 /// @brief Set every bit to 0.
770 APInt& APInt::clear() {
771 if (isSingleWord()) VAL = 0;
773 memset(pVal, 0, getNumWords() * 8);
777 /// @brief Bitwise NOT operator. Performs a bitwise logical NOT operation on
779 APInt APInt::operator~() const {
785 /// @brief Toggle every bit to its opposite value.
786 APInt& APInt::flip() {
787 if (isSingleWord()) VAL = (~(VAL << (64 - BitWidth))) >> (64 - BitWidth);
790 for (; i < getNumWords() - 1; ++i)
792 unsigned offset = 64 - (BitWidth - 64 * (i - 1));
793 pVal[i] = (~(pVal[i] << offset)) >> offset;
798 /// Toggle a given bit to its opposite value whose position is given
799 /// as "bitPosition".
800 /// @brief Toggles a given bit to its opposite value.
801 APInt& APInt::flip(unsigned bitPosition) {
802 assert(bitPosition < BitWidth && "Out of the bit-width range!");
803 if ((*this)[bitPosition]) clear(bitPosition);
804 else set(bitPosition);
808 /// to_string - This function translates the APInt into a string.
809 std::string APInt::toString(uint8_t radix) const {
810 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
811 "Radix should be 2, 8, 10, or 16!");
812 static const char *digits[] = {
813 "0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"
816 unsigned bits_used = getActiveBits();
817 if (isSingleWord()) {
819 const char *format = (radix == 10 ? "%llu" :
820 (radix == 16 ? "%llX" : (radix == 8 ? "%llo" : 0)));
822 sprintf(buf, format, VAL);
827 unsigned bit = v & 1;
829 buf[bits_used] = digits[bit][0];
838 APInt divisor(tmp.getBitWidth(), radix);
839 APInt zero(tmp.getBitWidth(), 0);
842 else while (tmp.ne(zero)) {
843 APInt APdigit = APIntOps::urem(tmp,divisor);
844 unsigned digit = APdigit.getValue();
845 assert(digit < radix && "urem failed");
846 result.insert(0,digits[digit]);
847 tmp = APIntOps::udiv(tmp, divisor);
853 /// getMaxValue - This function returns the largest value
854 /// for an APInt of the specified bit-width and if isSign == true,
855 /// it should be largest signed value, otherwise unsigned value.
856 APInt APInt::getMaxValue(unsigned numBits, bool isSign) {
857 APInt APIVal(numBits, 0);
859 if (isSign) APIVal.clear(numBits - 1);
863 /// getMinValue - This function returns the smallest value for
864 /// an APInt of the given bit-width and if isSign == true,
865 /// it should be smallest signed value, otherwise zero.
866 APInt APInt::getMinValue(unsigned numBits, bool isSign) {
867 APInt APIVal(numBits, 0);
868 if (isSign) APIVal.set(numBits - 1);
872 /// getAllOnesValue - This function returns an all-ones value for
873 /// an APInt of the specified bit-width.
874 APInt APInt::getAllOnesValue(unsigned numBits) {
875 return getMaxValue(numBits, false);
878 /// getNullValue - This function creates an '0' value for an
879 /// APInt of the specified bit-width.
880 APInt APInt::getNullValue(unsigned numBits) {
881 return getMinValue(numBits, false);
884 /// HiBits - This function returns the high "numBits" bits of this APInt.
885 APInt APInt::getHiBits(unsigned numBits) const {
886 return APIntOps::lshr(*this, BitWidth - numBits);
889 /// LoBits - This function returns the low "numBits" bits of this APInt.
890 APInt APInt::getLoBits(unsigned numBits) const {
891 return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits),
895 bool APInt::isPowerOf2() const {
896 return (!!*this) && !(*this & (*this - APInt(BitWidth,1)));
899 /// countLeadingZeros - This function is a APInt version corresponding to
900 /// llvm/include/llvm/Support/MathExtras.h's function
901 /// countLeadingZeros_{32, 64}. It performs platform optimal form of counting
902 /// the number of zeros from the most significant bit to the first one bit.
903 /// @returns numWord() * 64 if the value is zero.
904 unsigned APInt::countLeadingZeros() const {
906 return CountLeadingZeros_64(VAL);
908 for (int i = getNumWords() - 1; i >= 0; --i) {
909 unsigned tmp = CountLeadingZeros_64(pVal[i]);
917 /// countTrailingZeros - This function is a APInt version corresponding to
918 /// llvm/include/llvm/Support/MathExtras.h's function
919 /// countTrailingZeros_{32, 64}. It performs platform optimal form of counting
920 /// the number of zeros from the least significant bit to the first one bit.
921 /// @returns numWord() * 64 if the value is zero.
922 unsigned APInt::countTrailingZeros() const {
924 return CountTrailingZeros_64(~VAL & (VAL - 1));
925 APInt Tmp( ~(*this) & ((*this) - APInt(BitWidth,1)) );
926 return getNumWords() * APINT_BITS_PER_WORD - Tmp.countLeadingZeros();
929 /// countPopulation - This function is a APInt version corresponding to
930 /// llvm/include/llvm/Support/MathExtras.h's function
931 /// countPopulation_{32, 64}. It counts the number of set bits in a value.
932 /// @returns 0 if the value is zero.
933 unsigned APInt::countPopulation() const {
935 return CountPopulation_64(VAL);
937 for (unsigned i = 0; i < getNumWords(); ++i)
938 Count += CountPopulation_64(pVal[i]);
943 /// byteSwap - This function returns a byte-swapped representation of the
945 APInt APInt::byteSwap() const {
946 assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
948 return APInt(BitWidth, ByteSwap_16(VAL));
949 else if (BitWidth == 32)
950 return APInt(BitWidth, ByteSwap_32(VAL));
951 else if (BitWidth == 48) {
952 uint64_t Tmp1 = ((VAL >> 32) << 16) | (VAL & 0xFFFF);
953 Tmp1 = ByteSwap_32(Tmp1);
954 uint64_t Tmp2 = (VAL >> 16) & 0xFFFF;
955 Tmp2 = ByteSwap_16(Tmp2);
958 (Tmp1 & 0xff) | ((Tmp1<<16) & 0xffff00000000ULL) | (Tmp2 << 16));
959 } else if (BitWidth == 64)
960 return APInt(BitWidth, ByteSwap_64(VAL));
962 APInt Result(BitWidth, 0);
963 char *pByte = (char*)Result.pVal;
964 for (unsigned i = 0; i < BitWidth / 8 / 2; ++i) {
966 pByte[i] = pByte[BitWidth / 8 - 1 - i];
967 pByte[BitWidth / 8 - i - 1] = Tmp;
973 /// GreatestCommonDivisor - This function returns the greatest common
974 /// divisor of the two APInt values using Enclid's algorithm.
975 APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1,
977 APInt A = API1, B = API2;
980 B = APIntOps::urem(A, B);
986 /// DoubleRoundToAPInt - This function convert a double value to
988 APInt llvm::APIntOps::RoundDoubleToAPInt(double Double) {
994 bool isNeg = T.I >> 63;
995 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
997 return APInt(64ull, 0u);
998 uint64_t mantissa = ((T.I << 12) >> 12) | (1ULL << 52);
1000 return isNeg ? -APInt(64u, mantissa >> (52 - exp)) :
1001 APInt(64u, mantissa >> (52 - exp));
1002 APInt Tmp(exp + 1, mantissa);
1003 Tmp = Tmp.shl(exp - 52);
1004 return isNeg ? -Tmp : Tmp;
1007 /// RoundToDouble - This function convert this APInt to a double.
1008 /// The layout for double is as following (IEEE Standard 754):
1009 /// --------------------------------------
1010 /// | Sign Exponent Fraction Bias |
1011 /// |-------------------------------------- |
1012 /// | 1[63] 11[62-52] 52[51-00] 1023 |
1013 /// --------------------------------------
1014 double APInt::roundToDouble(bool isSigned) const {
1015 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
1016 APInt Tmp(isNeg ? -(*this) : (*this));
1017 if (Tmp.isSingleWord())
1018 return isSigned ? double(int64_t(Tmp.VAL)) : double(Tmp.VAL);
1019 unsigned n = Tmp.getActiveBits();
1021 return isSigned ? double(int64_t(Tmp.pVal[0])) : double(Tmp.pVal[0]);
1022 // Exponent when normalized to have decimal point directly after
1023 // leading one. This is stored excess 1023 in the exponent bit field.
1024 uint64_t exp = n - 1;
1027 assert(exp <= 1023 && "Infinity value!");
1029 // Number of bits in mantissa including the leading one
1033 mantissa = Tmp.pVal[whichWord(n - 1)] >> (n % 64 - 53);
1035 mantissa = (Tmp.pVal[whichWord(n - 1)] << (53 - n % 64)) |
1036 (Tmp.pVal[whichWord(n - 1) - 1] >> (11 + n % 64));
1037 // The leading bit of mantissa is implicit, so get rid of it.
1038 mantissa &= ~(1ULL << 52);
1039 uint64_t sign = isNeg ? (1ULL << 63) : 0;
1045 T.I = sign | (exp << 52) | mantissa;
1049 // Truncate to new width.
1050 void APInt::trunc(unsigned width) {
1051 assert(width < BitWidth && "Invalid APInt Truncate request");
1054 // Sign extend to a new width.
1055 void APInt::sext(unsigned width) {
1056 assert(width > BitWidth && "Invalid APInt SignExtend request");
1059 // Zero extend to a new width.
1060 void APInt::zext(unsigned width) {
1061 assert(width > BitWidth && "Invalid APInt ZeroExtend request");
1064 /// Arithmetic right-shift this APInt by shiftAmt.
1065 /// @brief Arithmetic right-shift function.
1066 APInt APInt::ashr(unsigned shiftAmt) const {
1068 if (API.isSingleWord())
1069 API.VAL = (((int64_t(API.VAL) << (64 - API.BitWidth)) >> (64 - API.BitWidth))
1070 >> shiftAmt) & (~uint64_t(0UL) >> (64 - API.BitWidth));
1072 if (shiftAmt >= API.BitWidth) {
1073 memset(API.pVal, API[API.BitWidth-1] ? 1 : 0, (API.getNumWords()-1) * 8);
1074 API.pVal[API.getNumWords() - 1] = ~uint64_t(0UL) >>
1075 (64 - API.BitWidth % 64);
1078 for (; i < API.BitWidth - shiftAmt; ++i)
1079 if (API[i+shiftAmt])
1083 for (; i < API.BitWidth; ++i)
1084 if (API[API.BitWidth-1])
1092 /// Logical right-shift this APInt by shiftAmt.
1093 /// @brief Logical right-shift function.
1094 APInt APInt::lshr(unsigned shiftAmt) const {
1096 if (API.isSingleWord())
1097 API.VAL >>= shiftAmt;
1099 if (shiftAmt >= API.BitWidth)
1100 memset(API.pVal, 0, API.getNumWords() * 8);
1102 for (i = 0; i < API.BitWidth - shiftAmt; ++i)
1103 if (API[i+shiftAmt]) API.set(i);
1105 for (; i < API.BitWidth; ++i)
1111 /// Left-shift this APInt by shiftAmt.
1112 /// @brief Left-shift function.
1113 APInt APInt::shl(unsigned shiftAmt) const {
1115 if (API.isSingleWord())
1116 API.VAL <<= shiftAmt;
1117 else if (shiftAmt >= API.BitWidth)
1118 memset(API.pVal, 0, API.getNumWords() * 8);
1120 if (unsigned offset = shiftAmt / 64) {
1121 for (unsigned i = API.getNumWords() - 1; i > offset - 1; --i)
1122 API.pVal[i] = API.pVal[i-offset];
1123 memset(API.pVal, 0, offset * 8);
1127 for (i = API.getNumWords() - 1; i > 0; --i)
1128 API.pVal[i] = (API.pVal[i] << shiftAmt) |
1129 (API.pVal[i-1] >> (64-shiftAmt));
1130 API.pVal[i] <<= shiftAmt;
1132 API.clearUnusedBits();
1136 /// Unsigned divide this APInt by APInt RHS.
1137 /// @brief Unsigned division function for APInt.
1138 APInt APInt::udiv(const APInt& RHS) const {
1139 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1141 unsigned first = RHS.getActiveBits();
1142 unsigned ylen = !first ? 0 : APInt::whichWord(first - 1) + 1;
1143 assert(ylen && "Divided by zero???");
1144 if (API.isSingleWord()) {
1145 API.VAL = RHS.isSingleWord() ? (API.VAL / RHS.VAL) :
1146 (ylen > 1 ? 0 : API.VAL / RHS.pVal[0]);
1148 unsigned first2 = API.getActiveBits();
1149 unsigned xlen = !first2 ? 0 : APInt::whichWord(first2 - 1) + 1;
1152 else if (xlen < ylen || API.ult(RHS))
1153 memset(API.pVal, 0, API.getNumWords() * 8);
1154 else if (API == RHS) {
1155 memset(API.pVal, 0, API.getNumWords() * 8);
1157 } else if (xlen == 1)
1158 API.pVal[0] /= RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
1160 APInt X(BitWidth, 0);
1161 APInt Y(BitWidth, 0);
1162 if (unsigned nshift = 63 - (first - 1) % 64) {
1163 Y = APIntOps::shl(RHS, nshift);
1164 X = APIntOps::shl(API, nshift);
1167 div((unsigned*)X.pVal, xlen*2-1,
1168 (unsigned*)(Y.isSingleWord() ? &Y.VAL : Y.pVal), ylen*2);
1169 memset(API.pVal, 0, API.getNumWords() * 8);
1170 memcpy(API.pVal, X.pVal + ylen, (xlen - ylen) * 8);
1176 /// Unsigned remainder operation on APInt.
1177 /// @brief Function for unsigned remainder operation.
1178 APInt APInt::urem(const APInt& RHS) const {
1179 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1181 unsigned first = RHS.getActiveBits();
1182 unsigned ylen = !first ? 0 : APInt::whichWord(first - 1) + 1;
1183 assert(ylen && "Performing remainder operation by zero ???");
1184 if (API.isSingleWord()) {
1185 API.VAL = RHS.isSingleWord() ? (API.VAL % RHS.VAL) :
1186 (ylen > 1 ? API.VAL : API.VAL % RHS.pVal[0]);
1188 unsigned first2 = API.getActiveBits();
1189 unsigned xlen = !first2 ? 0 : API.whichWord(first2 - 1) + 1;
1190 if (!xlen || xlen < ylen || API.ult(RHS))
1192 else if (API == RHS)
1193 memset(API.pVal, 0, API.getNumWords() * 8);
1195 API.pVal[0] %= RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
1197 APInt X((xlen+1)*64, 0), Y(ylen*64, 0);
1198 unsigned nshift = 63 - (first - 1) % 64;
1200 APIntOps::shl(Y, nshift);
1201 APIntOps::shl(X, nshift);
1203 div((unsigned*)X.pVal, xlen*2-1,
1204 (unsigned*)(Y.isSingleWord() ? &Y.VAL : Y.pVal), ylen*2);
1205 memset(API.pVal, 0, API.getNumWords() * 8);
1206 for (unsigned i = 0; i < ylen-1; ++i)
1207 API.pVal[i] = (X.pVal[i] >> nshift) | (X.pVal[i+1] << (64 - nshift));
1208 API.pVal[ylen-1] = X.pVal[ylen-1] >> nshift;