blob: d8441743b5e53a15b8740eaf375aff73ed3ac279 [file] [log] [blame]
Zhou Shengfd43dcf2007-02-06 03:00:16 +00001//===-- APInt.cpp - Implement APInt class ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
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.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements a class to represent arbitrary precision integral
11// constant values.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/ADT/APInt.h"
Chris Lattner6ad4c142007-02-06 05:38:37 +000016
17#if 0
Zhou Shengfd43dcf2007-02-06 03:00:16 +000018#include "llvm/DerivedTypes.h"
19#include "llvm/Support/MathExtras.h"
20#include <strings.h>
21#include <iostream>
22#include <sstream>
23#include <iomanip>
24#include <cstdlib>
25using namespace llvm;
26
27APInt::APInt(uint64_t val, unsigned numBits, bool sign)
28 : bitsnum(numBits), isSigned(sign) {
29 assert(bitsnum >= IntegerType::MIN_INT_BITS && "bitwidth too small");
30 assert(bitsnum <= IntegerType::MAX_INT_BITS && "bitwidth too large");
31 if (isSingleWord())
32 VAL = val & (~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - bitsnum));
33 else {
34 // Memory allocation and check if successful.
35 assert((pVal = new uint64_t[numWords()]) &&
36 "APInt memory allocation fails!");
37 bzero(pVal, numWords() * 8);
38 pVal[0] = val;
39 }
40}
41
42APInt::APInt(unsigned numBits, uint64_t bigVal[], bool sign)
43 : bitsnum(numBits), isSigned(sign) {
44 assert(bitsnum >= IntegerType::MIN_INT_BITS && "bitwidth too small");
45 assert(bitsnum <= IntegerType::MAX_INT_BITS && "bitwidth too large");
46 assert(bigVal && "Null pointer detected!");
47 if (isSingleWord())
48 VAL = bigVal[0] & (~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - bitsnum));
49 else {
50 // Memory allocation and check if successful.
51 assert((pVal = new uint64_t[numWords()]) &&
52 "APInt memory allocation fails!");
53 // Calculate the actual length of bigVal[].
54 unsigned n = sizeof(*bigVal) / sizeof(bigVal[0]);
55 unsigned maxN = std::max<unsigned>(n, numWords());
56 unsigned minN = std::min<unsigned>(n, numWords());
57 memcpy(pVal, bigVal, (minN - 1) * 8);
58 pVal[minN-1] = bigVal[minN-1] & (~uint64_t(0ULL) >> (64 - bitsnum % 64));
59 if (maxN == numWords())
60 bzero(pVal+n, (numWords() - n) * 8);
61 }
62}
63
64APInt::APInt(std::string& Val, uint8_t radix, bool sign)
65 : isSigned(sign) {
66 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
67 "Radix should be 2, 8, 10, or 16!");
68 assert(!Val.empty() && "String empty?");
69 unsigned slen = Val.size();
70 unsigned size = 0;
71 // If the radix is a power of 2, read the input
72 // from most significant to least significant.
73 if ((radix & (radix - 1)) == 0) {
74 unsigned nextBitPos = 0, bits_per_digit = radix / 8 + 2;
75 uint64_t resDigit = 0;
76 bitsnum = slen * bits_per_digit;
77 if (numWords() > 1)
78 assert((pVal = new uint64_t[numWords()]) &&
79 "APInt memory allocation fails!");
80 for (int i = slen - 1; i >= 0; --i) {
81 uint64_t digit = Val[i] - 48; // '0' == 48.
82 resDigit |= digit << nextBitPos;
83 nextBitPos += bits_per_digit;
84 if (nextBitPos >= 64) {
85 if (isSingleWord()) {
86 VAL = resDigit;
87 break;
88 }
89 pVal[size++] = resDigit;
90 nextBitPos -= 64;
91 resDigit = digit >> (bits_per_digit - nextBitPos);
92 }
93 }
94 if (!isSingleWord() && size <= numWords())
95 pVal[size] = resDigit;
96 } else { // General case. The radix is not a power of 2.
97 // For 10-radix, the max value of 64-bit integer is 18446744073709551615,
98 // and its digits number is 14.
99 const unsigned chars_per_word = 20;
100 if (slen < chars_per_word ||
101 (Val <= "18446744073709551615" &&
102 slen == chars_per_word)) { // In case Val <= 2^64 - 1
103 bitsnum = 64;
104 VAL = strtoull(Val.c_str(), 0, 10);
105 } else { // In case Val > 2^64 - 1
106 bitsnum = (slen / chars_per_word + 1) * 64;
107 assert((pVal = new uint64_t[numWords()]) &&
108 "APInt memory allocation fails!");
109 bzero(pVal, numWords() * 8);
110 unsigned str_pos = 0;
111 while (str_pos < slen) {
112 unsigned chunk = slen - str_pos;
113 if (chunk > chars_per_word - 1)
114 chunk = chars_per_word - 1;
115 uint64_t resDigit = Val[str_pos++] - 48; // 48 == '0'.
116 uint64_t big_base = radix;
117 while (--chunk > 0) {
118 resDigit = resDigit * radix + Val[str_pos++] - 48;
119 big_base *= radix;
120 }
121
122 uint64_t carry;
123 if (!size)
124 carry = resDigit;
125 else {
126 carry = mul_1(pVal, pVal, size, big_base);
127 carry += add_1(pVal, pVal, size, resDigit);
128 }
129
130 if (carry) pVal[size++] = carry;
131 }
132 }
133 }
134}
135
136APInt::APInt(const APInt& APIVal)
137 : bitsnum(APIVal.bitsnum), isSigned(APIVal.isSigned) {
138 if (isSingleWord()) VAL = APIVal.VAL;
139 else {
140 // Memory allocation and check if successful.
141 assert((pVal = new uint64_t[numWords()]) &&
142 "APInt memory allocation fails!");
143 memcpy(pVal, APIVal.pVal, numWords() * 8);
144 }
145}
146
147APInt::~APInt() {
148 if (!isSingleWord() && pVal) delete[] pVal;
149}
150
151/// whichByte - This function returns the word position
152/// for the specified bit position.
153inline unsigned APInt::whichByte(unsigned bitPosition)
154{ return (bitPosition % APINT_BITS_PER_WORD) / 8; }
155
156/// getWord - returns the corresponding word for the specified bit position.
157inline uint64_t& APInt::getWord(unsigned bitPosition)
158{ return isSingleWord() ? VAL : pVal[whichWord(bitPosition)]; }
159
160/// getWord - returns the corresponding word for the specified bit position.
161/// This is a constant version.
162inline uint64_t APInt::getWord(unsigned bitPosition) const
163{ return isSingleWord() ? VAL : pVal[whichWord(bitPosition)]; }
164
165/// mul_1 - This function multiplies the integer array x[] by a integer y and
166/// returns the carry.
167uint64_t APInt::mul_1(uint64_t dest[], uint64_t x[],
168 unsigned len, uint64_t y) {
169 // Split y into high 32-bit part and low 32-bit part.
170 uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
171 uint64_t carry = 0, lx, hx;
172 for (unsigned i = 0; i < len; ++i) {
173 lx = x[i] & 0xffffffffULL;
174 hx = x[i] >> 32;
175 // hasCarry - A flag to indicate if has carry.
176 // hasCarry == 0, no carry
177 // hasCarry == 1, has carry
178 // hasCarry == 2, no carry and the calculation result == 0.
179 uint8_t hasCarry = 0;
180 dest[i] = carry + lx * ly;
181 // Determine if the add above introduces carry.
182 hasCarry = (dest[i] < carry) ? 1 : 0;
183 carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
184 // The upper limit of carry can be (2^32 - 1)(2^32 - 1) +
185 // (2^32 - 1) + 2^32 = 2^64.
186 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
187
188 carry += (lx * hy) & 0xffffffffULL;
189 dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
190 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) +
191 (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
192 }
193
194 return carry;
195}
196
197/// mul - This function multiplies integer array x[] by integer array y[] and
198/// stores the result into integer array dest[].
199/// Note the array dest[]'s size should no less than xlen + ylen.
200void APInt::mul(uint64_t dest[], uint64_t x[], unsigned xlen,
201 uint64_t y[], unsigned ylen) {
202 dest[xlen] = mul_1(dest, x, xlen, y[0]);
203
204 for (unsigned i = 1; i < ylen; ++i) {
205 uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
206 uint64_t carry = 0, lx, hx;
207 for (unsigned j = 0; j < xlen; ++j) {
208 lx = x[j] & 0xffffffffULL;
209 hx = x[j] >> 32;
210 // hasCarry - A flag to indicate if has carry.
211 // hasCarry == 0, no carry
212 // hasCarry == 1, has carry
213 // hasCarry == 2, no carry and the calculation result == 0.
214 uint8_t hasCarry = 0;
215 uint64_t resul = carry + lx * ly;
216 hasCarry = (resul < carry) ? 1 : 0;
217 carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
218 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
219
220 carry += (lx * hy) & 0xffffffffULL;
221 resul = (carry << 32) | (resul & 0xffffffffULL);
222 dest[i+j] += resul;
223 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
224 (carry >> 32) + (dest[i+j] < resul ? 1 : 0) +
225 ((lx * hy) >> 32) + hx * hy;
226 }
227 dest[i+xlen] = carry;
228 }
229}
230
231/// add_1 - This function adds the integer array x[] by integer y and
232/// returns the carry.
233uint64_t APInt::add_1(uint64_t dest[], uint64_t x[],
234 unsigned len, uint64_t y) {
235 uint64_t carry = y;
236
237 for (unsigned i = 0; i < len; ++i) {
238 dest[i] = carry + x[i];
239 carry = (dest[i] < carry) ? 1 : 0;
240 }
241 return carry;
242}
243
244/// add - This function adds the integer array x[] by integer array
245/// y[] and returns the carry.
246uint64_t APInt::add(uint64_t dest[], uint64_t x[],
247 uint64_t y[], unsigned len) {
248 unsigned carry = 0;
249
250 for (unsigned i = 0; i< len; ++i) {
251 carry += x[i];
252 dest[i] = carry + y[i];
253 carry = carry < x[i] ? 1 : (dest[i] < carry ? 1 : 0);
254 }
255 return carry;
256}
257
258/// sub_1 - This function subtracts the integer array x[] by
259/// integer y and returns the borrow-out carry.
260uint64_t APInt::sub_1(uint64_t x[], unsigned len, uint64_t y) {
261 uint64_t cy = y;
262
263 for (unsigned i = 0; i < len; ++i) {
264 uint64_t X = x[i];
265 x[i] -= cy;
266 if (cy > X)
267 cy = 1;
268 else {
269 cy = 0;
270 break;
271 }
272 }
273
274 return cy;
275}
276
277/// sub - This function subtracts the integer array x[] by
278/// integer array y[], and returns the borrow-out carry.
279uint64_t APInt::sub(uint64_t dest[], uint64_t x[],
280 uint64_t y[], unsigned len) {
281 // Carry indicator.
282 uint64_t cy = 0;
283
284 for (unsigned i = 0; i < len; ++i) {
285 uint64_t Y = y[i], X = x[i];
286 Y += cy;
287
288 cy = Y < cy ? 1 : 0;
289 Y = X - Y;
290 cy += Y > X ? 1 : 0;
291 dest[i] = Y;
292 }
293 return cy;
294}
295
296/// UnitDiv - This function divides N by D,
297/// and returns (remainder << 32) | quotient.
298/// Assumes (N >> 32) < D.
299uint64_t APInt::unitDiv(uint64_t N, unsigned D) {
300 uint64_t q, r; // q: quotient, r: remainder.
301 uint64_t a1 = N >> 32; // a1: high 32-bit part of N.
302 uint64_t a0 = N & 0xffffffffL; // a0: low 32-bit part of N
303 if (a1 < ((D - a1 - (a0 >> 31)) & 0xffffffffL)) {
304 q = N / D;
305 r = N % D;
306 }
307 else {
308 // Compute c1*2^32 + c0 = a1*2^32 + a0 - 2^31*d
309 uint64_t c = N - ((uint64_t) D << 31);
310 // Divide (c1*2^32 + c0) by d
311 q = c / D;
312 r = c % D;
313 // Add 2^31 to quotient
314 q += 1 << 31;
315 }
316
317 return (r << 32) | (q & 0xFFFFFFFFl);
318}
319
320/// subMul - This function substracts x[len-1:0] * y from
321/// dest[offset+len-1:offset], and returns the most significant
322/// word of the product, minus the borrow-out from the subtraction.
323unsigned APInt::subMul(unsigned dest[], unsigned offset,
324 unsigned x[], unsigned len, unsigned y) {
325 uint64_t yl = (uint64_t) y & 0xffffffffL;
326 unsigned carry = 0;
327 unsigned j = 0;
328 do {
329 uint64_t prod = ((uint64_t) x[j] & 0xffffffffL) * yl;
330 unsigned prod_low = (unsigned) prod;
331 unsigned prod_high = (unsigned) (prod >> 32);
332 prod_low += carry;
333 carry = (prod_low < carry ? 1 : 0) + prod_high;
334 unsigned x_j = dest[offset+j];
335 prod_low = x_j - prod_low;
336 if (prod_low > x_j) ++carry;
337 dest[offset+j] = prod_low;
338 } while (++j < len);
339 return carry;
340}
341
342/// div - This is basically Knuth's formulation of the classical algorithm.
343/// Correspondance with Knuth's notation:
344/// Knuth's u[0:m+n] == zds[nx:0].
345/// Knuth's v[1:n] == y[ny-1:0]
346/// Knuth's n == ny.
347/// Knuth's m == nx-ny.
348/// Our nx == Knuth's m+n.
349/// Could be re-implemented using gmp's mpn_divrem:
350/// zds[nx] = mpn_divrem (&zds[ny], 0, zds, nx, y, ny).
351void APInt::div(unsigned zds[], unsigned nx, unsigned y[], unsigned ny) {
352 unsigned j = nx;
353 do { // loop over digits of quotient
354 // Knuth's j == our nx-j.
355 // Knuth's u[j:j+n] == our zds[j:j-ny].
356 unsigned qhat; // treated as unsigned
357 if (zds[j] == y[ny-1]) qhat = -1U; // 0xffffffff
358 else {
359 uint64_t w = (((uint64_t)(zds[j])) << 32) +
360 ((uint64_t)zds[j-1] & 0xffffffffL);
361 qhat = (unsigned) unitDiv(w, y[ny-1]);
362 }
363 if (qhat) {
364 unsigned borrow = subMul(zds, j - ny, y, ny, qhat);
365 unsigned save = zds[j];
366 uint64_t num = ((uint64_t)save&0xffffffffL) -
367 ((uint64_t)borrow&0xffffffffL);
368 while (num) {
369 qhat--;
370 uint64_t carry = 0;
371 for (unsigned i = 0; i < ny; i++) {
372 carry += ((uint64_t) zds[j-ny+i] & 0xffffffffL)
373 + ((uint64_t) y[i] & 0xffffffffL);
374 zds[j-ny+i] = (unsigned) carry;
375 carry >>= 32;
376 }
377 zds[j] += carry;
378 num = carry - 1;
379 }
380 }
381 zds[j] = qhat;
382 } while (--j >= ny);
383}
384
385/// lshift - This function shift x[0:len-1] left by shiftAmt bits, and
386/// store the len least significant words of the result in
387/// dest[d_offset:d_offset+len-1]. It returns the bits shifted out from
388/// the most significant digit.
389uint64_t APInt::lshift(uint64_t dest[], unsigned d_offset,
390 uint64_t x[], unsigned len, unsigned shiftAmt) {
391 unsigned count = 64 - shiftAmt;
392 int i = len - 1;
393 uint64_t high_word = x[i], retVal = high_word >> count;
394 ++d_offset;
395 while (--i >= 0) {
396 uint64_t low_word = x[i];
397 dest[d_offset+i] = (high_word << shiftAmt) | (low_word >> count);
398 high_word = low_word;
399 }
400 dest[d_offset+i] = high_word << shiftAmt;
401 return retVal;
402}
403
404/// @brief Copy assignment operator. Create a new object from the given
405/// APInt one by initialization.
406APInt& APInt::operator=(const APInt& RHS) {
407 if (isSingleWord()) VAL = RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
408 else {
409 unsigned minN = std::min(numWords(), RHS.numWords());
410 memcpy(pVal, RHS.isSingleWord() ? &RHS.VAL : RHS.pVal, minN * 8);
411 if (numWords() != minN)
412 bzero(pVal + minN, (numWords() - minN) * 8);
413 }
414 return *this;
415}
416
417/// @brief Assignment operator. Assigns a common case integer value to
418/// the APInt.
419APInt& APInt::operator=(uint64_t RHS) {
420 if (isSingleWord()) VAL = RHS;
421 else {
422 pVal[0] = RHS;
423 bzero(pVal, (numWords() - 1) * 8);
424 }
425 return *this;
426}
427
428/// @brief Postfix increment operator. Increments the APInt by one.
429const APInt APInt::operator++(int) {
430 APInt API(*this);
431 if (isSingleWord()) ++VAL;
432 else
433 add_1(pVal, pVal, numWords(), 1);
434 API.TruncToBits();
435 return API;
436}
437
438/// @brief Prefix increment operator. Increments the APInt by one.
439APInt& APInt::operator++() {
440 if (isSingleWord()) ++VAL;
441 else
442 add_1(pVal, pVal, numWords(), 1);
443 TruncToBits();
444 return *this;
445}
446
447/// @brief Postfix decrement operator. Decrements the APInt by one.
448const APInt APInt::operator--(int) {
449 APInt API(*this);
450 if (isSingleWord()) --VAL;
451 else
452 sub_1(API.pVal, API.numWords(), 1);
453 API.TruncToBits();
454 return API;
455}
456
457/// @brief Prefix decrement operator. Decrements the APInt by one.
458APInt& APInt::operator--() {
459 if (isSingleWord()) --VAL;
460 else
461 sub_1(pVal, numWords(), 1);
462 TruncToBits();
463 return *this;
464}
465
466/// @brief Addition assignment operator. Adds this APInt by the given APInt&
467/// RHS and assigns the result to this APInt.
468APInt& APInt::operator+=(const APInt& RHS) {
469 if (isSingleWord()) VAL += RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
470 else {
471 if (RHS.isSingleWord()) add_1(pVal, pVal, numWords(), RHS.VAL);
472 else {
473 if (numWords() <= RHS.numWords())
474 add(pVal, pVal, RHS.pVal, numWords());
475 else {
476 uint64_t carry = add(pVal, pVal, RHS.pVal, RHS.numWords());
477 add_1(pVal + RHS.numWords(), pVal + RHS.numWords(),
478 numWords() - RHS.numWords(), carry);
479 }
480 }
481 }
482 TruncToBits();
483 return *this;
484}
485
486/// @brief Subtraction assignment operator. Subtracts this APInt by the given
487/// APInt &RHS and assigns the result to this APInt.
488APInt& APInt::operator-=(const APInt& RHS) {
489 if (isSingleWord())
490 VAL -= RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
491 else {
492 if (RHS.isSingleWord())
493 sub_1(pVal, numWords(), RHS.VAL);
494 else {
495 if (RHS.numWords() < numWords()) {
496 uint64_t carry = sub(pVal, pVal, RHS.pVal, RHS.numWords());
497 sub_1(pVal + RHS.numWords(), numWords() - RHS.numWords(), carry);
498 }
499 else
500 sub(pVal, pVal, RHS.pVal, numWords());
501 }
502 }
503 TruncToBits();
504 return *this;
505}
506
507/// @brief Multiplication assignment operator. Multiplies this APInt by the
508/// given APInt& RHS and assigns the result to this APInt.
509APInt& APInt::operator*=(const APInt& RHS) {
510 if (isSingleWord()) VAL *= RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
511 else {
512 // one-based first non-zero bit position.
513 unsigned first = numWords() * APINT_BITS_PER_WORD - CountLeadingZeros();
514 unsigned xlen = !first ? 0 : whichWord(first - 1) + 1;
515 if (!xlen)
516 return *this;
517 else if (RHS.isSingleWord())
518 mul_1(pVal, pVal, xlen, RHS.VAL);
519 else {
520 first = RHS.numWords() * APINT_BITS_PER_WORD - RHS.CountLeadingZeros();
521 unsigned ylen = !first ? 0 : whichWord(first - 1) + 1;
522 if (!ylen) {
523 bzero(pVal, numWords() * 8);
524 return *this;
525 }
526 uint64_t *dest = new uint64_t[xlen+ylen];
527 assert(dest && "Memory Allocation Failed!");
528 mul(dest, pVal, xlen, RHS.pVal, ylen);
529 memcpy(pVal, dest, ((xlen + ylen >= numWords()) ? numWords() : xlen + ylen) * 8);
530 delete[] dest;
531 }
532 }
533 TruncToBits();
534 return *this;
535}
536
537/// @brief Division assignment operator. Divides this APInt by the given APInt
538/// &RHS and assigns the result to this APInt.
539APInt& APInt::operator/=(const APInt& RHS) {
540 unsigned first = RHS.numWords() * APINT_BITS_PER_WORD -
541 RHS.CountLeadingZeros();
542 unsigned ylen = !first ? 0 : whichWord(first - 1) + 1;
543 assert(ylen && "Divided by zero???");
544 if (isSingleWord()) {
545 if (isSigned && RHS.isSigned)
546 VAL = RHS.isSingleWord() ? (int64_t(VAL) / int64_t(RHS.VAL)) :
547 (ylen > 1 ? 0 : int64_t(VAL) / int64_t(RHS.pVal[0]));
548 else
549 VAL = RHS.isSingleWord() ? (VAL / RHS.VAL) :
550 (ylen > 1 ? 0 : VAL / RHS.pVal[0]);
551 } else {
552 unsigned first2 = numWords() * APINT_BITS_PER_WORD - CountLeadingZeros();
553 unsigned xlen = !first2 ? 0 : whichWord(first2 - 1) + 1;
554 if (!xlen)
555 return *this;
556 else if ((*this) < RHS)
557 bzero(pVal, numWords() * 8);
558 else if ((*this) == RHS) {
559 bzero(pVal, numWords() * 8);
560 pVal[0] = 1;
561 } else if (xlen == 1)
562 pVal[0] /= RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
563 else {
564 uint64_t *xwords = new uint64_t[xlen+1], *ywords = new uint64_t[ylen];
565 assert(xwords && ywords && "Memory Allocation Failed!");
566 memcpy(xwords, pVal, xlen * 8);
567 xwords[xlen] = 0;
568 memcpy(ywords, RHS.isSingleWord() ? &RHS.VAL : RHS.pVal, ylen * 8);
569 if (unsigned nshift = 63 - (first - 1) % 64) {
570 lshift(ywords, 0, ywords, ylen, nshift);
571 unsigned xlentmp = xlen;
572 xwords[xlen++] = lshift(xwords, 0, xwords, xlentmp, nshift);
573 }
574 div((unsigned*)xwords, xlen*2-1, (unsigned*)ywords, ylen*2);
575 bzero(pVal, numWords() * 8);
576 memcpy(pVal, xwords + ylen, (xlen - ylen) * 8);
577 delete[] xwords;
578 delete[] ywords;
579 }
580 }
581 return *this;
582}
583
584/// @brief Remainder assignment operator. Yields the remainder from the
585/// division of this APInt by the given APInt& RHS and assigns the remainder
586/// to this APInt.
587APInt& APInt::operator%=(const APInt& RHS) {
588 unsigned first = RHS.numWords() * APINT_BITS_PER_WORD -
589 RHS.CountLeadingZeros();
590 unsigned ylen = !first ? 0 : whichWord(first - 1) + 1;
591 assert(ylen && "Performing remainder operation by zero ???");
592 if (isSingleWord()) {
593 if (isSigned && RHS.isSigned)
594 VAL = RHS.isSingleWord() ? (int64_t(VAL) % int64_t(RHS.VAL)) :
595 (ylen > 1 ? VAL : int64_t(VAL) % int64_t(RHS.pVal[0]));
596 else
597 VAL = RHS.isSingleWord() ? (VAL % RHS.VAL) :
598 (ylen > 1 ? VAL : VAL % RHS.pVal[0]);
599 } else {
600 unsigned first2 = numWords() * APINT_BITS_PER_WORD - CountLeadingZeros();
601 unsigned xlen = !first2 ? 0 : whichWord(first2 - 1) + 1;
602 if (!xlen || (*this) < RHS)
603 return *this;
604 else if ((*this) == RHS)
605 bzero(pVal, numWords() * 8);
606 else if (xlen == 1)
607 pVal[0] %= RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
608 else {
609 uint64_t *xwords = new uint64_t[xlen+1], *ywords = new uint64_t[ylen];
610 assert(xwords && ywords && "Memory Allocation Failed!");
611 memcpy(xwords, pVal, xlen * 8);
612 xwords[xlen] = 0;
613 memcpy(ywords, RHS.isSingleWord() ? &RHS.VAL : RHS.pVal, ylen * 8);
614 unsigned nshift = 63 - (first - 1) % 64;
615 if (nshift) {
616 lshift(ywords, 0, ywords, ylen, nshift);
617 unsigned xlentmp = xlen;
618 xwords[xlen++] = lshift(xwords, 0, xwords, xlentmp, nshift);
619 }
620 div((unsigned*)xwords, xlen*2-1, (unsigned*)ywords, ylen*2);
621 bzero(pVal, numWords() * 8);
622 for (unsigned i = 0; i < ylen-1; ++i)
623 pVal[i] = (xwords[i] >> nshift) | (xwords[i+1] << (64 - nshift));
624 pVal[ylen-1] = xwords[ylen-1] >> nshift;
625 delete[] xwords;
626 delete[] ywords;
627 }
628 }
629 return *this;
630}
631
632/// @brief Bitwise AND assignment operator. Performs bitwise AND operation on
633/// this APInt and the given APInt& RHS, assigns the result to this APInt.
634APInt& APInt::operator&=(const APInt& RHS) {
635 if (isSingleWord()) {
636 if (RHS.isSingleWord()) VAL &= RHS.VAL;
637 else VAL &= RHS.pVal[0];
638 } else {
639 if (RHS.isSingleWord()) {
640 bzero(pVal, (numWords() - 1) * 8);
641 pVal[0] &= RHS.VAL;
642 } else {
643 unsigned minwords = numWords() < RHS.numWords() ? numWords() : RHS.numWords();
644 for (unsigned i = 0; i < minwords; ++i)
645 pVal[i] &= RHS.pVal[i];
646 if (numWords() > minwords) bzero(pVal+minwords, (numWords() - minwords) * 8);
647 }
648 }
649 return *this;
650}
651
652/// @brief Bitwise OR assignment operator. Performs bitwise OR operation on
653/// this APInt and the given APInt& RHS, assigns the result to this APInt.
654APInt& APInt::operator|=(const APInt& RHS) {
655 if (isSingleWord()) {
656 if (RHS.isSingleWord()) VAL |= RHS.VAL;
657 else VAL |= RHS.pVal[0];
658 } else {
659 if (RHS.isSingleWord()) {
660 pVal[0] |= RHS.VAL;
661 } else {
662 unsigned minwords = numWords() < RHS.numWords() ? numWords() : RHS.numWords();
663 for (unsigned i = 0; i < minwords; ++i)
664 pVal[i] |= RHS.pVal[i];
665 }
666 }
667 TruncToBits();
668 return *this;
669}
670
671/// @brief Bitwise XOR assignment operator. Performs bitwise XOR operation on
672/// this APInt and the given APInt& RHS, assigns the result to this APInt.
673APInt& APInt::operator^=(const APInt& RHS) {
674 if (isSingleWord()) {
675 if (RHS.isSingleWord()) VAL ^= RHS.VAL;
676 else VAL ^= RHS.pVal[0];
677 } else {
678 if (RHS.isSingleWord()) {
679 for (unsigned i = 0; i < numWords(); ++i)
680 pVal[i] ^= RHS.VAL;
681 } else {
682 unsigned minwords = numWords() < RHS.numWords() ? numWords() : RHS.numWords();
683 for (unsigned i = 0; i < minwords; ++i)
684 pVal[i] ^= RHS.pVal[i];
685 if (numWords() > minwords)
686 for (unsigned i = minwords; i < numWords(); ++i)
687 pVal[i] ^= 0;
688 }
689 }
690 TruncToBits();
691 return *this;
692}
693
694/// @brief Bitwise AND operator. Performs bitwise AND operation on this APInt
695/// and the given APInt& RHS.
696APInt APInt::operator&(const APInt& RHS) const {
697 APInt API(RHS);
698 return API &= *this;
699}
700
701/// @brief Bitwise OR operator. Performs bitwise OR operation on this APInt
702/// and the given APInt& RHS.
703APInt APInt::operator|(const APInt& RHS) const {
704 APInt API(RHS);
705 API |= *this;
706 API.TruncToBits();
707 return API;
708}
709
710/// @brief Bitwise XOR operator. Performs bitwise XOR operation on this APInt
711/// and the given APInt& RHS.
712APInt APInt::operator^(const APInt& RHS) const {
713 APInt API(RHS);
714 API ^= *this;
715 API.TruncToBits();
716 return API;
717}
718
719/// @brief Logical AND operator. Performs logical AND operation on this APInt
720/// and the given APInt& RHS.
721bool APInt::operator&&(const APInt& RHS) const {
722 if (isSingleWord())
723 return RHS.isSingleWord() ? VAL && RHS.VAL : VAL && RHS.pVal[0];
724 else if (RHS.isSingleWord())
725 return RHS.VAL && pVal[0];
726 else {
727 unsigned minN = std::min(numWords(), RHS.numWords());
728 for (unsigned i = 0; i < minN; ++i)
729 if (pVal[i] && RHS.pVal[i])
730 return true;
731 }
732 return false;
733}
734
735/// @brief Logical OR operator. Performs logical OR operation on this APInt
736/// and the given APInt& RHS.
737bool APInt::operator||(const APInt& RHS) const {
738 if (isSingleWord())
739 return RHS.isSingleWord() ? VAL || RHS.VAL : VAL || RHS.pVal[0];
740 else if (RHS.isSingleWord())
741 return RHS.VAL || pVal[0];
742 else {
743 unsigned minN = std::min(numWords(), RHS.numWords());
744 for (unsigned i = 0; i < minN; ++i)
745 if (pVal[i] || RHS.pVal[i])
746 return true;
747 }
748 return false;
749}
750
751/// @brief Logical negation operator. Performs logical negation operation on
752/// this APInt.
753bool APInt::operator !() const {
754 if (isSingleWord())
755 return !VAL;
756 else
757 for (unsigned i = 0; i < numWords(); ++i)
758 if (pVal[i])
759 return false;
760 return true;
761}
762
763/// @brief Multiplication operator. Multiplies this APInt by the given APInt&
764/// RHS.
765APInt APInt::operator*(const APInt& RHS) const {
766 APInt API(RHS);
767 API *= *this;
768 API.TruncToBits();
769 return API;
770}
771
772/// @brief Division operator. Divides this APInt by the given APInt& RHS.
773APInt APInt::operator/(const APInt& RHS) const {
774 APInt API(*this);
775 return API /= RHS;
776}
777
778/// @brief Remainder operator. Yields the remainder from the division of this
779/// APInt and the given APInt& RHS.
780APInt APInt::operator%(const APInt& RHS) const {
781 APInt API(*this);
782 return API %= RHS;
783}
784
785/// @brief Addition operator. Adds this APInt by the given APInt& RHS.
786APInt APInt::operator+(const APInt& RHS) const {
787 APInt API(*this);
788 API += RHS;
789 API.TruncToBits();
790 return API;
791}
792
793/// @brief Subtraction operator. Subtracts this APInt by the given APInt& RHS
794APInt APInt::operator-(const APInt& RHS) const {
795 APInt API(*this);
796 API -= RHS;
797 API.TruncToBits();
798 return API;
799}
800
801/// @brief Array-indexing support.
802bool APInt::operator[](unsigned bitPosition) const {
803 return maskBit(bitPosition) & (isSingleWord() ?
804 VAL : pVal[whichWord(bitPosition)]) != 0;
805}
806
807/// @brief Equality operator. Compare this APInt with the given APInt& RHS
808/// for the validity of the equality relationship.
809bool APInt::operator==(const APInt& RHS) const {
810 unsigned n1 = numWords() * APINT_BITS_PER_WORD - CountLeadingZeros(),
811 n2 = RHS.numWords() * APINT_BITS_PER_WORD - RHS.CountLeadingZeros();
812 if (n1 != n2) return false;
813 else if (isSingleWord())
814 return VAL == (RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0]);
815 else {
816 if (n1 <= 64)
817 return pVal[0] == (RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0]);
818 for (int i = whichWord(n1 - 1); i >= 0; --i)
819 if (pVal[i] != RHS.pVal[i]) return false;
820 }
821 return true;
822}
823
824/// @brief Inequality operator. Compare this APInt with the given APInt& RHS
825/// for the validity of the inequality relationship.
826bool APInt::operator!=(const APInt& RHS) const {
827 return !((*this) == RHS);
828}
829
830/// @brief Less-than operator. Compare this APInt with the given APInt& RHS
831/// for the validity of the less-than relationship.
832bool APInt::operator <(const APInt& RHS) const {
833 if (isSigned && RHS.isSigned) {
834 if ((*this)[bitsnum-1] > RHS[RHS.bitsnum-1])
835 return false;
836 else if ((*this)[bitsnum-1] < RHS[RHS.bitsnum-1])
837 return true;
838 }
839 unsigned n1 = numWords() * 64 - CountLeadingZeros(),
840 n2 = RHS.numWords() * 64 - RHS.CountLeadingZeros();
841 if (n1 < n2) return true;
842 else if (n1 > n2) return false;
843 else if (isSingleWord())
844 return VAL < (RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0]);
845 else {
846 if (n1 <= 64)
847 return pVal[0] < (RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0]);
848 for (int i = whichWord(n1 - 1); i >= 0; --i) {
849 if (pVal[i] > RHS.pVal[i]) return false;
850 else if (pVal[i] < RHS.pVal[i]) return true;
851 }
852 }
853 return false;
854}
855
856/// @brief Less-than-or-equal operator. Compare this APInt with the given
857/// APInt& RHS for the validity of the less-than-or-equal relationship.
858bool APInt::operator<=(const APInt& RHS) const {
859 return (*this) == RHS || (*this) < RHS;
860}
861
862/// @brief Greater-than operator. Compare this APInt with the given APInt& RHS
863/// for the validity of the greater-than relationship.
864bool APInt::operator >(const APInt& RHS) const {
865 return !((*this) <= RHS);
866}
867
868/// @brief Greater-than-or-equal operator. Compare this APInt with the given
869/// APInt& RHS for the validity of the greater-than-or-equal relationship.
870bool APInt::operator>=(const APInt& RHS) const {
871 return !((*this) < RHS);
872}
873
874/// Set the given bit to 1 whose poition is given as "bitPosition".
875/// @brief Set a given bit to 1.
876APInt& APInt::set(unsigned bitPosition) {
877 if (isSingleWord()) VAL |= maskBit(bitPosition);
878 else pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
879 return *this;
880}
881
882/// @brief Set every bit to 1.
883APInt& APInt::set() {
884 if (isSingleWord()) VAL = -1ULL;
885 else
886 for (unsigned i = 0; i < numWords(); ++i)
887 pVal[i] = -1ULL;
888 return *this;
889}
890
891/// Set the given bit to 0 whose position is given as "bitPosition".
892/// @brief Set a given bit to 0.
893APInt& APInt::clear(unsigned bitPosition) {
894 if (isSingleWord()) VAL &= ~maskBit(bitPosition);
895 else pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
896 return *this;
897}
898
899/// @brief Set every bit to 0.
900APInt& APInt::clear() {
901 if (isSingleWord()) VAL = 0;
902 else bzero(pVal, numWords() * 8);
903 return *this;
904}
905
906/// @brief Left-shift assignment operator. Left-shift the APInt by shiftAmt
907/// and assigns the result to this APInt.
908APInt& APInt::operator<<=(unsigned shiftAmt) {
909 if (shiftAmt >= bitsnum) {
910 if (isSingleWord()) VAL = 0;
911 else bzero(pVal, numWords() * 8);
912 } else {
913 for (unsigned i = 0; i < shiftAmt; ++i) clear(i);
914 for (unsigned i = shiftAmt; i < bitsnum; ++i) {
915 if ((*this)[i-shiftAmt]) set(i);
916 else clear(i);
917 }
918 }
919 return *this;
920}
921
922/// @brief Left-shift operator. Left-shift the APInt by shiftAmt.
923APInt APInt::operator<<(unsigned shiftAmt) const {
924 APInt API(*this);
925 API <<= shiftAmt;
926 return API;
927}
928
929/// @brief Right-shift assignment operator. Right-shift the APInt by shiftAmt
930/// and assigns the result to this APInt.
931APInt& APInt::operator>>=(unsigned shiftAmt) {
932 bool isAShr = isSigned && (*this)[bitsnum-1];
933 if (isSingleWord())
934 VAL = isAShr ? (int64_t(VAL) >> shiftAmt) : (VAL >> shiftAmt);
935 else {
936 unsigned i = 0;
937 for (i = 0; i < bitsnum - shiftAmt; ++i)
938 if ((*this)[i+shiftAmt]) set(i);
939 else clear(i);
940 for (; i < bitsnum; ++i)
941 isAShr ? set(i) : clear(i);
942 }
943 return *this;
944}
945
946/// @brief Right-shift operator. Right-shift the APInt by shiftAmt.
947APInt APInt::operator>>(unsigned shiftAmt) const {
948 APInt API(*this);
949 API >>= shiftAmt;
950 return API;
951}
952
953/// @brief Bitwise NOT operator. Performs a bitwise logical NOT operation on
954/// this APInt.
955APInt APInt::operator~() const {
956 APInt API(*this);
957 API.flip();
958 return API;
959}
960
961/// @brief Toggle every bit to its opposite value.
962APInt& APInt::flip() {
963 if (isSingleWord()) VAL = (~(VAL << (64 - bitsnum))) >> (64 - bitsnum);
964 else {
965 unsigned i = 0;
966 for (; i < numWords() - 1; ++i)
967 pVal[i] = ~pVal[i];
968 unsigned offset = 64 - (bitsnum - 64 * (i - 1));
969 pVal[i] = (~(pVal[i] << offset)) >> offset;
970 }
971 return *this;
972}
973
974/// Toggle a given bit to its opposite value whose position is given
975/// as "bitPosition".
976/// @brief Toggles a given bit to its opposite value.
977APInt& APInt::flip(unsigned bitPosition) {
978 assert(bitPosition < bitsnum && "Out of the bit-width range!");
979 if ((*this)[bitPosition]) clear(bitPosition);
980 else set(bitPosition);
981 return *this;
982}
983
984/// to_string - This function translates the APInt into a string.
985std::string APInt::to_string(uint8_t radix) const {
986 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
987 "Radix should be 2, 8, 10, or 16!");
988 std::ostringstream buf;
989 buf << std::setbase(radix);
990 // If the radix is a power of 2, set the format of ostringstream,
991 // and output the value into buf.
992 if ((radix & (radix - 1)) == 0) {
993 if (isSingleWord()) buf << VAL;
994 else {
995 buf << pVal[numWords()-1];
996 buf << std::setw(64 / (radix / 8 + 2)) << std::setfill('0');
997 for (int i = numWords() - 2; i >= 0; --i)
998 buf << pVal[i];
999 }
1000 }
1001 else { // If the radix = 10, need to translate the value into a
1002 // string.
1003 if (isSingleWord()) buf << VAL;
1004 else {
1005 // FIXME: To be supported.
1006 }
1007 }
1008 return buf.str();
1009}
1010
1011/// getMaxValue - This function returns the largest value
1012/// for an APInt of the specified bit-width and if isSign == true,
1013/// it should be largest signed value, otherwise unsigned value.
1014APInt APInt::getMaxValue(unsigned numBits, bool isSign) {
1015 APInt APIVal(numBits, 1);
1016 APIVal.set();
1017 return isSign ? APIVal.clear(numBits) : APIVal;
1018}
1019
1020/// getMinValue - This function returns the smallest value for
1021/// an APInt of the given bit-width and if isSign == true,
1022/// it should be smallest signed value, otherwise zero.
1023APInt APInt::getMinValue(unsigned numBits, bool isSign) {
1024 APInt APIVal(0, numBits);
1025 return isSign ? APIVal : APIVal.set(numBits);
1026}
1027
1028/// getAllOnesValue - This function returns an all-ones value for
1029/// an APInt of the specified bit-width.
1030APInt APInt::getAllOnesValue(unsigned numBits) {
1031 return getMaxValue(numBits, false);
1032}
1033
1034/// getNullValue - This function creates an '0' value for an
1035/// APInt of the specified bit-width.
1036APInt APInt::getNullValue(unsigned numBits) {
1037 return getMinValue(numBits, true);
1038}
1039
1040/// HiBits - This function returns the high "numBits" bits of this APInt.
1041APInt APInt::HiBits(unsigned numBits) const {
1042 return (*this) >> (bitsnum - numBits);
1043}
1044
1045/// LoBits - This function returns the low "numBits" bits of this APInt.
1046APInt APInt::LoBits(unsigned numBits) const {
1047 return ((*this) << (bitsnum - numBits)) >> (bitsnum - numBits);
1048}
1049
1050/// CountLeadingZeros - This function is a APInt version corresponding to
1051/// llvm/include/llvm/Support/MathExtras.h's function
1052/// CountLeadingZeros_{32, 64}. It performs platform optimal form of counting
1053/// the number of zeros from the most significant bit to the first one bit.
1054/// @returns numWord() * 64 if the value is zero.
1055unsigned APInt::CountLeadingZeros() const {
1056 if (isSingleWord())
1057 return CountLeadingZeros_64(VAL);
1058 unsigned Count = 0;
1059 for (int i = numWords() - 1; i >= 0; --i) {
1060 unsigned tmp = CountLeadingZeros_64(pVal[i]);
1061 Count += tmp;
1062 if (tmp != 64)
1063 break;
1064 }
1065 return Count;
1066}
1067
1068/// CountTrailingZero - This function is a APInt version corresponding to
1069/// llvm/include/llvm/Support/MathExtras.h's function
1070/// CountTrailingZeros_{32, 64}. It performs platform optimal form of counting
1071/// the number of zeros from the least significant bit to the first one bit.
1072/// @returns numWord() * 64 if the value is zero.
1073unsigned APInt::CountTrailingZeros() const {
1074 if (isSingleWord())
1075 return CountTrailingZeros_64(~VAL & (VAL - 1));
1076 APInt Tmp = ~(*this) & ((*this) - 1);
1077 return numWords() * 64 - Tmp.CountLeadingZeros();
1078}
1079
1080/// CountPopulation - This function is a APInt version corresponding to
1081/// llvm/include/llvm/Support/MathExtras.h's function
1082/// CountPopulation_{32, 64}. It counts the number of set bits in a value.
1083/// @returns 0 if the value is zero.
1084unsigned APInt::CountPopulation() const {
1085 if (isSingleWord())
1086 return CountPopulation_64(VAL);
1087 unsigned Count = 0;
1088 for (unsigned i = 0; i < numWords(); ++i)
1089 Count += CountPopulation_64(pVal[i]);
1090 return Count;
1091}
1092
1093
1094/// ByteSwap - This function returns a byte-swapped representation of the
1095/// APInt argument, APIVal.
1096APInt llvm::ByteSwap(const APInt& APIVal) {
1097 if (APIVal.bitsnum <= 32)
1098 return APInt(APIVal.bitsnum, ByteSwap_32(unsigned(APIVal.VAL)));
1099 else if (APIVal.bitsnum <= 64)
1100 return APInt(APIVal.bitsnum, ByteSwap_64(APIVal.VAL));
1101 else
1102 return APIVal;
1103}
1104
1105/// GreatestCommonDivisor - This function returns the greatest common
1106/// divisor of the two APInt values using Enclid's algorithm.
1107APInt llvm::GreatestCommonDivisor(const APInt& API1, const APInt& API2) {
1108 APInt A = API1, B = API2;
1109 while (!!B) {
1110 APInt T = B;
1111 B = A % B;
1112 A = T;
1113 }
1114 return A;
1115}
Chris Lattner6ad4c142007-02-06 05:38:37 +00001116
1117#endif
1118