e13778609bbd35b8d33f29f67c130b82027f65a6
[oota-llvm.git] / lib / Support / APInt.cpp
1 //===-- APInt.cpp - Implement APInt class ---------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Sheng Zhou and Reid Spencer and is distributed 
6 // under the // University of Illinois Open Source License. See LICENSE.TXT 
7 // for details.
8 //
9 //===----------------------------------------------------------------------===//
10 //
11 // This file implements a class to represent arbitrary precision integer
12 // constant values and provide a variety of arithmetic operations on them.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #define DEBUG_TYPE "apint"
17 #include "llvm/ADT/APInt.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/MathExtras.h"
21 #include <cstring>
22 #include <cstdlib>
23 #ifndef NDEBUG
24 #include <iomanip>
25 #endif
26
27 using namespace llvm;
28
29 /// A utility function for allocating memory, checking for allocation failures,
30 /// and ensuring the contents are zeroed.
31 inline static uint64_t* getClearedMemory(uint32_t numWords) {
32   uint64_t * result = new uint64_t[numWords];
33   assert(result && "APInt memory allocation fails!");
34   memset(result, 0, numWords * sizeof(uint64_t));
35   return result;
36 }
37
38 /// A utility function for allocating memory and checking for allocation 
39 /// failure.  The content is not zeroed.
40 inline static uint64_t* getMemory(uint32_t numWords) {
41   uint64_t * result = new uint64_t[numWords];
42   assert(result && "APInt memory allocation fails!");
43   return result;
44 }
45
46 APInt::APInt(uint32_t numBits, uint64_t val)
47   : BitWidth(numBits), VAL(0) {
48   assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
49   assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
50   if (isSingleWord())
51     VAL = val;
52   else {
53     pVal = getClearedMemory(getNumWords());
54     pVal[0] = val;
55   }
56   clearUnusedBits();
57 }
58
59 APInt::APInt(uint32_t numBits, uint32_t numWords, uint64_t bigVal[])
60   : BitWidth(numBits), VAL(0)  {
61   assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
62   assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
63   assert(bigVal && "Null pointer detected!");
64   if (isSingleWord())
65     VAL = bigVal[0];
66   else {
67     // Get memory, cleared to 0
68     pVal = getClearedMemory(getNumWords());
69     // Calculate the number of words to copy
70     uint32_t words = std::min<uint32_t>(numWords, getNumWords());
71     // Copy the words from bigVal to pVal
72     memcpy(pVal, bigVal, words * APINT_WORD_SIZE);
73   }
74   // Make sure unused high bits are cleared
75   clearUnusedBits();
76 }
77
78 APInt::APInt(uint32_t numbits, const char StrStart[], uint32_t slen, 
79              uint8_t radix) 
80   : BitWidth(numbits), VAL(0) {
81   fromString(numbits, StrStart, slen, radix);
82 }
83
84 APInt::APInt(uint32_t numbits, const std::string& Val, uint8_t radix)
85   : BitWidth(numbits), VAL(0) {
86   assert(!Val.empty() && "String empty?");
87   fromString(numbits, Val.c_str(), Val.size(), radix);
88 }
89
90 APInt::APInt(const APInt& that)
91   : BitWidth(that.BitWidth), VAL(0) {
92   if (isSingleWord()) 
93     VAL = that.VAL;
94   else {
95     pVal = getMemory(getNumWords());
96     memcpy(pVal, that.pVal, getNumWords() * APINT_WORD_SIZE);
97   }
98 }
99
100 APInt::~APInt() {
101   if (!isSingleWord() && pVal) 
102     delete[] pVal;
103 }
104
105 APInt& APInt::operator=(const APInt& RHS) {
106   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
107   if (isSingleWord()) 
108     VAL = RHS.VAL;
109   else
110     memcpy(pVal, RHS.pVal, getNumWords() * APINT_WORD_SIZE);
111   return *this;
112 }
113
114 APInt& APInt::operator=(uint64_t RHS) {
115   if (isSingleWord()) 
116     VAL = RHS;
117   else {
118     pVal[0] = RHS;
119     memset(pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
120   }
121   return *this;
122 }
123
124 /// add_1 - This function adds a single "digit" integer, y, to the multiple 
125 /// "digit" integer array,  x[]. x[] is modified to reflect the addition and
126 /// 1 is returned if there is a carry out, otherwise 0 is returned.
127 /// @returns the carry of the addition.
128 static bool add_1(uint64_t dest[], uint64_t x[], uint32_t len, uint64_t y) {
129   for (uint32_t i = 0; i < len; ++i) {
130     dest[i] = y + x[i];
131     if (dest[i] < y)
132       y = 1; // Carry one to next digit.
133     else {
134       y = 0; // No need to carry so exit early
135       break;
136     }
137   }
138   return y;
139 }
140
141 /// @brief Prefix increment operator. Increments the APInt by one.
142 APInt& APInt::operator++() {
143   if (isSingleWord()) 
144     ++VAL;
145   else
146     add_1(pVal, pVal, getNumWords(), 1);
147   return clearUnusedBits();
148 }
149
150 /// sub_1 - This function subtracts a single "digit" (64-bit word), y, from 
151 /// the multi-digit integer array, x[], propagating the borrowed 1 value until 
152 /// no further borrowing is neeeded or it runs out of "digits" in x.  The result
153 /// is 1 if "borrowing" exhausted the digits in x, or 0 if x was not exhausted.
154 /// In other words, if y > x then this function returns 1, otherwise 0.
155 /// @returns the borrow out of the subtraction
156 static bool sub_1(uint64_t x[], uint32_t len, uint64_t y) {
157   for (uint32_t i = 0; i < len; ++i) {
158     uint64_t X = x[i];
159     x[i] -= y;
160     if (y > X) 
161       y = 1;  // We have to "borrow 1" from next "digit"
162     else {
163       y = 0;  // No need to borrow
164       break;  // Remaining digits are unchanged so exit early
165     }
166   }
167   return bool(y);
168 }
169
170 /// @brief Prefix decrement operator. Decrements the APInt by one.
171 APInt& APInt::operator--() {
172   if (isSingleWord()) 
173     --VAL;
174   else
175     sub_1(pVal, getNumWords(), 1);
176   return clearUnusedBits();
177 }
178
179 /// add - This function adds the integer array x to the integer array Y and
180 /// places the result in dest. 
181 /// @returns the carry out from the addition
182 /// @brief General addition of 64-bit integer arrays
183 static bool add(uint64_t *dest, const uint64_t *x, const uint64_t *y, 
184                 uint32_t len) {
185   bool carry = false;
186   for (uint32_t i = 0; i< len; ++i) {
187     uint64_t limit = std::min(x[i],y[i]); // must come first in case dest == x
188     dest[i] = x[i] + y[i] + carry;
189     carry = dest[i] < limit || (carry && dest[i] == limit);
190   }
191   return carry;
192 }
193
194 /// Adds the RHS APint to this APInt.
195 /// @returns this, after addition of RHS.
196 /// @brief Addition assignment operator. 
197 APInt& APInt::operator+=(const APInt& RHS) {
198   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
199   if (isSingleWord()) 
200     VAL += RHS.VAL;
201   else {
202     add(pVal, pVal, RHS.pVal, getNumWords());
203   }
204   return clearUnusedBits();
205 }
206
207 /// Subtracts the integer array y from the integer array x 
208 /// @returns returns the borrow out.
209 /// @brief Generalized subtraction of 64-bit integer arrays.
210 static bool sub(uint64_t *dest, const uint64_t *x, const uint64_t *y, 
211                 uint32_t len) {
212   bool borrow = false;
213   for (uint32_t i = 0; i < len; ++i) {
214     uint64_t x_tmp = borrow ? x[i] - 1 : x[i];
215     borrow = y[i] > x_tmp || (borrow && x[i] == 0);
216     dest[i] = x_tmp - y[i];
217   }
218   return borrow;
219 }
220
221 /// Subtracts the RHS APInt from this APInt
222 /// @returns this, after subtraction
223 /// @brief Subtraction assignment operator. 
224 APInt& APInt::operator-=(const APInt& RHS) {
225   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
226   if (isSingleWord()) 
227     VAL -= RHS.VAL;
228   else
229     sub(pVal, pVal, RHS.pVal, getNumWords());
230   return clearUnusedBits();
231 }
232
233 /// Multiplies an integer array, x by a a uint64_t integer and places the result
234 /// into dest. 
235 /// @returns the carry out of the multiplication.
236 /// @brief Multiply a multi-digit APInt by a single digit (64-bit) integer.
237 static uint64_t mul_1(uint64_t dest[], uint64_t x[], uint32_t len, uint64_t y) {
238   // Split y into high 32-bit part (hy)  and low 32-bit part (ly)
239   uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
240   uint64_t carry = 0;
241
242   // For each digit of x.
243   for (uint32_t i = 0; i < len; ++i) {
244     // Split x into high and low words
245     uint64_t lx = x[i] & 0xffffffffULL;
246     uint64_t hx = x[i] >> 32;
247     // hasCarry - A flag to indicate if there is a carry to the next digit.
248     // hasCarry == 0, no carry
249     // hasCarry == 1, has carry
250     // hasCarry == 2, no carry and the calculation result == 0.
251     uint8_t hasCarry = 0;
252     dest[i] = carry + lx * ly;
253     // Determine if the add above introduces carry.
254     hasCarry = (dest[i] < carry) ? 1 : 0;
255     carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
256     // The upper limit of carry can be (2^32 - 1)(2^32 - 1) + 
257     // (2^32 - 1) + 2^32 = 2^64.
258     hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
259
260     carry += (lx * hy) & 0xffffffffULL;
261     dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
262     carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) + 
263             (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
264   }
265   return carry;
266 }
267
268 /// Multiplies integer array x by integer array y and stores the result into 
269 /// the integer array dest. Note that dest's size must be >= xlen + ylen.
270 /// @brief Generalized multiplicate of integer arrays.
271 static void mul(uint64_t dest[], uint64_t x[], uint32_t xlen, uint64_t y[], 
272                 uint32_t ylen) {
273   dest[xlen] = mul_1(dest, x, xlen, y[0]);
274   for (uint32_t i = 1; i < ylen; ++i) {
275     uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
276     uint64_t carry = 0, lx = 0, hx = 0;
277     for (uint32_t j = 0; j < xlen; ++j) {
278       lx = x[j] & 0xffffffffULL;
279       hx = x[j] >> 32;
280       // hasCarry - A flag to indicate if has carry.
281       // hasCarry == 0, no carry
282       // hasCarry == 1, has carry
283       // hasCarry == 2, no carry and the calculation result == 0.
284       uint8_t hasCarry = 0;
285       uint64_t resul = carry + lx * ly;
286       hasCarry = (resul < carry) ? 1 : 0;
287       carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
288       hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
289
290       carry += (lx * hy) & 0xffffffffULL;
291       resul = (carry << 32) | (resul & 0xffffffffULL);
292       dest[i+j] += resul;
293       carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
294               (carry >> 32) + (dest[i+j] < resul ? 1 : 0) + 
295               ((lx * hy) >> 32) + hx * hy;
296     }
297     dest[i+xlen] = carry;
298   }
299 }
300
301 APInt& APInt::operator*=(const APInt& RHS) {
302   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
303   if (isSingleWord()) {
304     VAL *= RHS.VAL;
305     clearUnusedBits();
306     return *this;
307   }
308
309   // Get some bit facts about LHS and check for zero
310   uint32_t lhsBits = getActiveBits();
311   uint32_t lhsWords = !lhsBits ? 0 : whichWord(lhsBits - 1) + 1;
312   if (!lhsWords) 
313     // 0 * X ===> 0
314     return *this;
315
316   // Get some bit facts about RHS and check for zero
317   uint32_t rhsBits = RHS.getActiveBits();
318   uint32_t rhsWords = !rhsBits ? 0 : whichWord(rhsBits - 1) + 1;
319   if (!rhsWords) {
320     // X * 0 ===> 0
321     clear();
322     return *this;
323   }
324
325   // Allocate space for the result
326   uint32_t destWords = rhsWords + lhsWords;
327   uint64_t *dest = getMemory(destWords);
328
329   // Perform the long multiply
330   mul(dest, pVal, lhsWords, RHS.pVal, rhsWords);
331
332   // Copy result back into *this
333   clear();
334   uint32_t wordsToCopy = destWords >= getNumWords() ? getNumWords() : destWords;
335   memcpy(pVal, dest, wordsToCopy * APINT_WORD_SIZE);
336
337   // delete dest array and return
338   delete[] dest;
339   return *this;
340 }
341
342 APInt& APInt::operator&=(const APInt& RHS) {
343   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
344   if (isSingleWord()) {
345     VAL &= RHS.VAL;
346     return *this;
347   }
348   uint32_t numWords = getNumWords();
349   for (uint32_t i = 0; i < numWords; ++i)
350     pVal[i] &= RHS.pVal[i];
351   return *this;
352 }
353
354 APInt& APInt::operator|=(const APInt& RHS) {
355   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
356   if (isSingleWord()) {
357     VAL |= RHS.VAL;
358     return *this;
359   }
360   uint32_t numWords = getNumWords();
361   for (uint32_t i = 0; i < numWords; ++i)
362     pVal[i] |= RHS.pVal[i];
363   return *this;
364 }
365
366 APInt& APInt::operator^=(const APInt& RHS) {
367   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
368   if (isSingleWord()) {
369     VAL ^= RHS.VAL;
370     this->clearUnusedBits();
371     return *this;
372   } 
373   uint32_t numWords = getNumWords();
374   for (uint32_t i = 0; i < numWords; ++i)
375     pVal[i] ^= RHS.pVal[i];
376   return clearUnusedBits();
377 }
378
379 APInt APInt::operator&(const APInt& RHS) const {
380   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
381   if (isSingleWord())
382     return APInt(getBitWidth(), VAL & RHS.VAL);
383
384   uint32_t numWords = getNumWords();
385   uint64_t* val = getMemory(numWords);
386   for (uint32_t i = 0; i < numWords; ++i)
387     val[i] = pVal[i] & RHS.pVal[i];
388   return APInt(val, getBitWidth());
389 }
390
391 APInt APInt::operator|(const APInt& RHS) const {
392   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
393   if (isSingleWord())
394     return APInt(getBitWidth(), VAL | RHS.VAL);
395
396   uint32_t numWords = getNumWords();
397   uint64_t *val = getMemory(numWords);
398   for (uint32_t i = 0; i < numWords; ++i)
399     val[i] = pVal[i] | RHS.pVal[i];
400   return APInt(val, getBitWidth());
401 }
402
403 APInt APInt::operator^(const APInt& RHS) const {
404   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
405   if (isSingleWord())
406     return APInt(BitWidth, VAL ^ RHS.VAL).clearUnusedBits();
407
408   uint32_t numWords = getNumWords();
409   uint64_t *val = getMemory(numWords);
410   for (uint32_t i = 0; i < numWords; ++i)
411     val[i] = pVal[i] ^ RHS.pVal[i];
412
413   // 0^0==1 so clear the high bits in case they got set.
414   return APInt(val, getBitWidth()).clearUnusedBits();
415 }
416
417 bool APInt::operator !() const {
418   if (isSingleWord())
419     return !VAL;
420
421   for (uint32_t i = 0; i < getNumWords(); ++i)
422     if (pVal[i]) 
423       return false;
424   return true;
425 }
426
427 APInt APInt::operator*(const APInt& RHS) const {
428   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
429   if (isSingleWord())
430     return APInt(BitWidth, VAL * RHS.VAL).clearUnusedBits();
431   APInt Result(*this);
432   Result *= RHS;
433   return Result.clearUnusedBits();
434 }
435
436 APInt APInt::operator+(const APInt& RHS) const {
437   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
438   if (isSingleWord())
439     return APInt(BitWidth, VAL + RHS.VAL).clearUnusedBits();
440   APInt Result(BitWidth, 0);
441   add(Result.pVal, this->pVal, RHS.pVal, getNumWords());
442   return Result.clearUnusedBits();
443 }
444
445 APInt APInt::operator-(const APInt& RHS) const {
446   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
447   if (isSingleWord())
448     return APInt(BitWidth, VAL - RHS.VAL).clearUnusedBits();
449   APInt Result(BitWidth, 0);
450   sub(Result.pVal, this->pVal, RHS.pVal, getNumWords());
451   return Result.clearUnusedBits();
452 }
453
454 bool APInt::operator[](uint32_t bitPosition) const {
455   return (maskBit(bitPosition) & 
456           (isSingleWord() ?  VAL : pVal[whichWord(bitPosition)])) != 0;
457 }
458
459 bool APInt::operator==(const APInt& RHS) const {
460   if (isSingleWord())
461     return VAL == RHS.VAL;
462
463   // Get some facts about the number of bits used in the two operands.
464   uint32_t n1 = getActiveBits();
465   uint32_t n2 = RHS.getActiveBits();
466
467   // If the number of bits isn't the same, they aren't equal
468   if (n1 != n2) 
469     return false;
470
471   // If the number of bits fits in a word, we only need to compare the low word.
472   if (n1 <= APINT_BITS_PER_WORD)
473     return pVal[0] == RHS.pVal[0];
474
475   // Otherwise, compare everything
476   for (int i = whichWord(n1 - 1); i >= 0; --i)
477     if (pVal[i] != RHS.pVal[i]) 
478       return false;
479   return true;
480 }
481
482 bool APInt::operator==(uint64_t Val) const {
483   if (isSingleWord())
484     return VAL == Val;
485
486   uint32_t n = getActiveBits(); 
487   if (n <= APINT_BITS_PER_WORD)
488     return pVal[0] == Val;
489   else
490     return false;
491 }
492
493 bool APInt::ult(const APInt& RHS) const {
494   assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
495   if (isSingleWord())
496     return VAL < RHS.VAL;
497
498   // Get active bit length of both operands
499   uint32_t n1 = getActiveBits();
500   uint32_t n2 = RHS.getActiveBits();
501
502   // If magnitude of LHS is less than RHS, return true.
503   if (n1 < n2)
504     return true;
505
506   // If magnitude of RHS is greather than LHS, return false.
507   if (n2 < n1)
508     return false;
509
510   // If they bot fit in a word, just compare the low order word
511   if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
512     return pVal[0] < RHS.pVal[0];
513
514   // Otherwise, compare all words
515   for (int i = whichWord(n1 - 1); i >= 0; --i) {
516     if (pVal[i] > RHS.pVal[i]) 
517       return false;
518     if (pVal[i] < RHS.pVal[i]) 
519       return true;
520   }
521   return false;
522 }
523
524 bool APInt::slt(const APInt& RHS) const {
525   assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
526   if (isSingleWord()) {
527     int64_t lhsSext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
528     int64_t rhsSext = (int64_t(RHS.VAL) << (64-BitWidth)) >> (64-BitWidth);
529     return lhsSext < rhsSext;
530   }
531
532   APInt lhs(*this);
533   APInt rhs(*this);
534   bool lhsNegative = false;
535   bool rhsNegative = false;
536   if (lhs[BitWidth-1]) {
537     // Sign bit is set so make a note of it and perform two's complement
538     lhsNegative = true;
539     lhs.flip();
540     lhs++;
541   }
542   if (rhs[BitWidth-1]) {
543     // Sign bit is set so make a note of it and perform two's complement
544     rhsNegative = true;
545     rhs.flip();
546     rhs++;
547   }
548
549   // Now we have unsigned values to compare so do the comparison if necessary
550   // based on the negativeness of the values.
551   if (lhsNegative)
552     if (rhsNegative)
553       return !lhs.ult(rhs);
554     else
555       return true;
556   else if (rhsNegative)
557     return false;
558   else 
559     return lhs.ult(rhs);
560 }
561
562 APInt& APInt::set(uint32_t bitPosition) {
563   if (isSingleWord()) 
564     VAL |= maskBit(bitPosition);
565   else 
566     pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
567   return *this;
568 }
569
570 APInt& APInt::set() {
571   if (isSingleWord()) {
572     VAL = -1ULL;
573     return clearUnusedBits();
574   }
575
576   // Set all the bits in all the words.
577   for (uint32_t i = 0; i < getNumWords() - 1; ++i)
578     pVal[i] = -1ULL;
579   // Clear the unused ones
580   return clearUnusedBits();
581 }
582
583 /// Set the given bit to 0 whose position is given as "bitPosition".
584 /// @brief Set a given bit to 0.
585 APInt& APInt::clear(uint32_t bitPosition) {
586   if (isSingleWord()) 
587     VAL &= ~maskBit(bitPosition);
588   else 
589     pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
590   return *this;
591 }
592
593 /// @brief Set every bit to 0.
594 APInt& APInt::clear() {
595   if (isSingleWord()) 
596     VAL = 0;
597   else 
598     memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
599   return *this;
600 }
601
602 /// @brief Bitwise NOT operator. Performs a bitwise logical NOT operation on
603 /// this APInt.
604 APInt APInt::operator~() const {
605   APInt API(*this);
606   API.flip();
607   return API;
608 }
609
610 /// @brief Toggle every bit to its opposite value.
611 APInt& APInt::flip() {
612   if (isSingleWord()) {
613     VAL = ~VAL;
614     return clearUnusedBits();
615   }
616   for (uint32_t i = 0; i < getNumWords(); ++i)
617     pVal[i] = ~pVal[i];
618   return clearUnusedBits();
619 }
620
621 /// Toggle a given bit to its opposite value whose position is given 
622 /// as "bitPosition".
623 /// @brief Toggles a given bit to its opposite value.
624 APInt& APInt::flip(uint32_t bitPosition) {
625   assert(bitPosition < BitWidth && "Out of the bit-width range!");
626   if ((*this)[bitPosition]) clear(bitPosition);
627   else set(bitPosition);
628   return *this;
629 }
630
631 /// getMaxValue - This function returns the largest value
632 /// for an APInt of the specified bit-width and if isSign == true,
633 /// it should be largest signed value, otherwise unsigned value.
634 APInt APInt::getMaxValue(uint32_t numBits, bool isSign) {
635   APInt Result(numBits, 0);
636   Result.set();
637   if (isSign) 
638     Result.clear(numBits - 1);
639   return Result;
640 }
641
642 /// getMinValue - This function returns the smallest value for
643 /// an APInt of the given bit-width and if isSign == true,
644 /// it should be smallest signed value, otherwise zero.
645 APInt APInt::getMinValue(uint32_t numBits, bool isSign) {
646   APInt Result(numBits, 0);
647   if (isSign) 
648     Result.set(numBits - 1);
649   return Result;
650 }
651
652 /// getAllOnesValue - This function returns an all-ones value for
653 /// an APInt of the specified bit-width.
654 APInt APInt::getAllOnesValue(uint32_t numBits) {
655   return getMaxValue(numBits, false);
656 }
657
658 /// getNullValue - This function creates an '0' value for an
659 /// APInt of the specified bit-width.
660 APInt APInt::getNullValue(uint32_t numBits) {
661   return getMinValue(numBits, false);
662 }
663
664 /// HiBits - This function returns the high "numBits" bits of this APInt.
665 APInt APInt::getHiBits(uint32_t numBits) const {
666   return APIntOps::lshr(*this, BitWidth - numBits);
667 }
668
669 /// LoBits - This function returns the low "numBits" bits of this APInt.
670 APInt APInt::getLoBits(uint32_t numBits) const {
671   return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits), 
672                         BitWidth - numBits);
673 }
674
675 bool APInt::isPowerOf2() const {
676   return (!!*this) && !(*this & (*this - APInt(BitWidth,1)));
677 }
678
679 uint32_t APInt::countLeadingZeros() const {
680   uint32_t Count = 0;
681   if (isSingleWord())
682     Count = CountLeadingZeros_64(VAL);
683   else {
684     for (uint32_t i = getNumWords(); i > 0u; --i) {
685       if (pVal[i-1] == 0)
686         Count += APINT_BITS_PER_WORD;
687       else {
688         Count += CountLeadingZeros_64(pVal[i-1]);
689         break;
690       }
691     }
692   }
693   uint32_t remainder = BitWidth % APINT_BITS_PER_WORD;
694   if (remainder)
695     Count -= APINT_BITS_PER_WORD - remainder;
696   return Count;
697 }
698
699 uint32_t APInt::countTrailingZeros() const {
700   if (isSingleWord())
701     return CountTrailingZeros_64(VAL);
702   APInt Tmp( ~(*this) & ((*this) - APInt(BitWidth,1)) );
703   return getNumWords() * APINT_BITS_PER_WORD - Tmp.countLeadingZeros();
704 }
705
706 uint32_t APInt::countPopulation() const {
707   if (isSingleWord())
708     return CountPopulation_64(VAL);
709   uint32_t Count = 0;
710   for (uint32_t i = 0; i < getNumWords(); ++i)
711     Count += CountPopulation_64(pVal[i]);
712   return Count;
713 }
714
715 APInt APInt::byteSwap() const {
716   assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
717   if (BitWidth == 16)
718     return APInt(BitWidth, ByteSwap_16(VAL));
719   else if (BitWidth == 32)
720     return APInt(BitWidth, ByteSwap_32(VAL));
721   else if (BitWidth == 48) {
722     uint64_t Tmp1 = ((VAL >> 32) << 16) | (VAL & 0xFFFF);
723     Tmp1 = ByteSwap_32(Tmp1);
724     uint64_t Tmp2 = (VAL >> 16) & 0xFFFF;
725     Tmp2 = ByteSwap_16(Tmp2);
726     return 
727       APInt(BitWidth, 
728             (Tmp1 & 0xff) | ((Tmp1<<16) & 0xffff00000000ULL) | (Tmp2 << 16));
729   } else if (BitWidth == 64)
730     return APInt(BitWidth, ByteSwap_64(VAL));
731   else {
732     APInt Result(BitWidth, 0);
733     char *pByte = (char*)Result.pVal;
734     for (uint32_t i = 0; i < BitWidth / APINT_WORD_SIZE / 2; ++i) {
735       char Tmp = pByte[i];
736       pByte[i] = pByte[BitWidth / APINT_WORD_SIZE - 1 - i];
737       pByte[BitWidth / APINT_WORD_SIZE - i - 1] = Tmp;
738     }
739     return Result;
740   }
741 }
742
743 APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1, 
744                                             const APInt& API2) {
745   APInt A = API1, B = API2;
746   while (!!B) {
747     APInt T = B;
748     B = APIntOps::urem(A, B);
749     A = T;
750   }
751   return A;
752 }
753
754 APInt llvm::APIntOps::RoundDoubleToAPInt(double Double) {
755   union {
756     double D;
757     uint64_t I;
758   } T;
759   T.D = Double;
760   bool isNeg = T.I >> 63;
761   int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
762   if (exp < 0)
763     return APInt(64ull, 0u);
764   uint64_t mantissa = ((T.I << 12) >> 12) | (1ULL << 52);
765   if (exp < 52)
766     return isNeg ? -APInt(64u, mantissa >> (52 - exp)) : 
767                     APInt(64u, mantissa >> (52 - exp));
768   APInt Tmp(exp + 1, mantissa);
769   Tmp = Tmp.shl(exp - 52);
770   return isNeg ? -Tmp : Tmp;
771 }
772
773 /// RoundToDouble - This function convert this APInt to a double.
774 /// The layout for double is as following (IEEE Standard 754):
775 ///  --------------------------------------
776 /// |  Sign    Exponent    Fraction    Bias |
777 /// |-------------------------------------- |
778 /// |  1[63]   11[62-52]   52[51-00]   1023 |
779 ///  -------------------------------------- 
780 double APInt::roundToDouble(bool isSigned) const {
781
782   // Handle the simple case where the value is contained in one uint64_t.
783   if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
784     if (isSigned) {
785       int64_t sext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
786       return double(sext);
787     } else
788       return double(VAL);
789   }
790
791   // Determine if the value is negative.
792   bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
793
794   // Construct the absolute value if we're negative.
795   APInt Tmp(isNeg ? -(*this) : (*this));
796
797   // Figure out how many bits we're using.
798   uint32_t n = Tmp.getActiveBits();
799
800   // The exponent (without bias normalization) is just the number of bits
801   // we are using. Note that the sign bit is gone since we constructed the
802   // absolute value.
803   uint64_t exp = n;
804
805   // Return infinity for exponent overflow
806   if (exp > 1023) {
807     if (!isSigned || !isNeg)
808       return double(1.0E300 * 1.0E300); // positive infinity
809     else 
810       return double(-1.0E300 * 1.0E300); // negative infinity
811   }
812   exp += 1023; // Increment for 1023 bias
813
814   // Number of bits in mantissa is 52. To obtain the mantissa value, we must
815   // extract the high 52 bits from the correct words in pVal.
816   uint64_t mantissa;
817   unsigned hiWord = whichWord(n-1);
818   if (hiWord == 0) {
819     mantissa = Tmp.pVal[0];
820     if (n > 52)
821       mantissa >>= n - 52; // shift down, we want the top 52 bits.
822   } else {
823     assert(hiWord > 0 && "huh?");
824     uint64_t hibits = Tmp.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
825     uint64_t lobits = Tmp.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
826     mantissa = hibits | lobits;
827   }
828
829   // The leading bit of mantissa is implicit, so get rid of it.
830   uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
831   union {
832     double D;
833     uint64_t I;
834   } T;
835   T.I = sign | (exp << 52) | mantissa;
836   return T.D;
837 }
838
839 // Truncate to new width.
840 void APInt::trunc(uint32_t width) {
841   assert(width < BitWidth && "Invalid APInt Truncate request");
842   assert(width >= IntegerType::MIN_INT_BITS && "Can't truncate to 0 bits");
843   uint32_t wordsBefore = getNumWords();
844   BitWidth = width;
845   uint32_t wordsAfter = getNumWords();
846   if (wordsBefore != wordsAfter) {
847     if (wordsAfter == 1) {
848       uint64_t *tmp = pVal;
849       VAL = pVal[0];
850       delete tmp;
851     } else {
852       uint64_t *newVal = getClearedMemory(wordsAfter);
853       for (uint32_t i = 0; i < wordsAfter; ++i)
854         newVal[i] = pVal[i];
855       delete pVal;
856       pVal = newVal;
857     }
858   }
859   clearUnusedBits();
860 }
861
862 // Sign extend to a new width.
863 void APInt::sext(uint32_t width) {
864   assert(width > BitWidth && "Invalid APInt SignExtend request");
865   assert(width <= IntegerType::MAX_INT_BITS && "Too many bits");
866   bool isNegative = (*this)[BitWidth-1];
867   // If the sign bit isn't set, this is the same as zext.
868   if (!isNegative) {
869     zext(width);
870     return;
871   }
872
873   // The sign bit is set. First, get some facts
874   uint32_t wordsBefore = getNumWords();
875   uint32_t wordBits = BitWidth % APINT_BITS_PER_WORD;
876   BitWidth = width;
877   uint32_t wordsAfter = getNumWords();
878
879   // Mask the high order word appropriately
880   if (wordsBefore == wordsAfter) {
881     uint32_t newWordBits = width % APINT_BITS_PER_WORD;
882     // The extension is contained to the wordsBefore-1th word.
883     uint64_t mask = (~0ULL >> (APINT_BITS_PER_WORD - newWordBits)) <<  wordBits;
884     if (wordsBefore == 1)
885       VAL |= mask;
886     else
887       pVal[wordsBefore-1] |= mask;
888     clearUnusedBits();
889     return;
890   }
891
892   uint64_t mask = wordBits == 0 ? 0 : ~0ULL << wordBits;
893   uint64_t *newVal = getMemory(wordsAfter);
894   if (wordsBefore == 1)
895     newVal[0] = VAL | mask;
896   else {
897     for (uint32_t i = 0; i < wordsBefore; ++i)
898       newVal[i] = pVal[i];
899     newVal[wordsBefore-1] |= mask;
900   }
901   for (uint32_t i = wordsBefore; i < wordsAfter; i++)
902     newVal[i] = -1ULL;
903   if (wordsBefore != 1)
904     delete pVal;
905   pVal = newVal;
906   clearUnusedBits();
907 }
908
909 //  Zero extend to a new width.
910 void APInt::zext(uint32_t width) {
911   assert(width > BitWidth && "Invalid APInt ZeroExtend request");
912   assert(width <= IntegerType::MAX_INT_BITS && "Too many bits");
913   uint32_t wordsBefore = getNumWords();
914   BitWidth = width;
915   uint32_t wordsAfter = getNumWords();
916   if (wordsBefore != wordsAfter) {
917     uint64_t *newVal = getClearedMemory(wordsAfter);
918     if (wordsBefore == 1)
919       newVal[0] = VAL;
920     else 
921       for (uint32_t i = 0; i < wordsBefore; ++i)
922         newVal[i] = pVal[i];
923     if (wordsBefore != 1)
924       delete pVal;
925     pVal = newVal;
926   }
927 }
928
929 /// Arithmetic right-shift this APInt by shiftAmt.
930 /// @brief Arithmetic right-shift function.
931 APInt APInt::ashr(uint32_t shiftAmt) const {
932   if (isSingleWord()) {
933     if (shiftAmt == BitWidth)
934       return APInt(BitWidth, -1ULL);
935     else
936       return APInt(BitWidth, 
937         (((int64_t(VAL) << (APINT_BITS_PER_WORD - BitWidth)) >> 
938             (APINT_BITS_PER_WORD - BitWidth)) >> shiftAmt)).clearUnusedBits();
939   }
940
941   APInt Result(*this);
942   if (shiftAmt >= BitWidth) {
943     memset(Result.pVal, Result[BitWidth-1] ? 1 : 0, 
944            (getNumWords()-1) * APINT_WORD_SIZE);
945     return Result.clearUnusedBits();
946   } 
947
948   // FIXME: bit-at-a-time shift is really slow.
949   uint32_t i = 0;
950   for (; i < BitWidth - shiftAmt; ++i)
951     if (Result[i+shiftAmt]) 
952       Result.set(i);
953     else
954       Result.clear(i);
955   for (; i < BitWidth; ++i)
956     if (Result[BitWidth-1]) 
957       Result.set(i);
958     else 
959       Result.clear(i);
960   return Result;
961 }
962
963 /// Logical right-shift this APInt by shiftAmt.
964 /// @brief Logical right-shift function.
965 APInt APInt::lshr(uint32_t shiftAmt) const {
966   if (isSingleWord())
967     if (shiftAmt == BitWidth)
968       return APInt(BitWidth, 0);
969     else 
970       return APInt(BitWidth, this->VAL >> shiftAmt);
971
972   APInt Result(*this);
973   if (shiftAmt >= BitWidth) {
974     Result.clear();
975     return Result;
976   }
977
978   // FIXME: bit at a time shift is really slow
979   uint32_t i = 0;
980   for (i = 0; i < Result.BitWidth - shiftAmt; ++i)
981     if (Result[i+shiftAmt]) 
982       Result.set(i);
983     else 
984       Result.clear(i);
985   for (; i < Result.BitWidth; ++i)
986     Result.clear(i);
987   return Result;
988 }
989
990 /// Left-shift this APInt by shiftAmt.
991 /// @brief Left-shift function.
992 APInt APInt::shl(uint32_t shiftAmt) const {
993   assert(shiftAmt <= BitWidth && "Invalid shift amount");
994   if (isSingleWord()) {
995     if (shiftAmt == BitWidth)
996       return APInt(BitWidth, 0); // avoid undefined shift results
997     return APInt(BitWidth, VAL << shiftAmt).clearUnusedBits();
998   }
999
1000   // If all the bits were shifted out, the result is 0. This avoids issues
1001   // with shifting by the size of the integer type, which produces undefined
1002   // results. We define these "undefined results" to always be 0.
1003   if (shiftAmt == BitWidth)
1004     return APInt(BitWidth, 0);
1005
1006   // Create some space for the result.
1007   uint64_t * val = new uint64_t[getNumWords()];
1008
1009   // If we are shifting less than a word, do it the easy way
1010   if (shiftAmt < APINT_BITS_PER_WORD) {
1011     uint64_t carry = 0;
1012     shiftAmt %= APINT_BITS_PER_WORD;
1013     for (uint32_t i = 0; i < getNumWords(); i++) {
1014       val[i] = pVal[i] << shiftAmt | carry;
1015       carry = pVal[i] >> (APINT_BITS_PER_WORD - shiftAmt);
1016     }
1017     return APInt(val, BitWidth).clearUnusedBits();
1018   }
1019
1020   // Compute some values needed by the remaining shift algorithms
1021   uint32_t wordShift = shiftAmt % APINT_BITS_PER_WORD;
1022   uint32_t offset = shiftAmt / APINT_BITS_PER_WORD;
1023
1024   // If we are shifting whole words, just move whole words
1025   if (wordShift == 0) {
1026     for (uint32_t i = 0; i < offset; i++) 
1027       val[i] = 0;
1028     for (uint32_t i = offset; i < getNumWords(); i++)
1029       val[i] = pVal[i-offset];
1030     return APInt(val,BitWidth).clearUnusedBits();
1031   }
1032
1033   // Copy whole words from this to Result.
1034   uint32_t i = getNumWords() - 1;
1035   for (; i > offset; --i)
1036     val[i] = pVal[i-offset] << wordShift |
1037              pVal[i-offset-1] >> (APINT_BITS_PER_WORD - wordShift);
1038   val[offset] = pVal[0] << wordShift;
1039   for (i = 0; i < offset; ++i)
1040     val[i] = 0;
1041   return APInt(val, BitWidth).clearUnusedBits();
1042 }
1043
1044 /// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
1045 /// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
1046 /// variables here have the same names as in the algorithm. Comments explain
1047 /// the algorithm and any deviation from it.
1048 static void KnuthDiv(uint32_t *u, uint32_t *v, uint32_t *q, uint32_t* r, 
1049                      uint32_t m, uint32_t n) {
1050   assert(u && "Must provide dividend");
1051   assert(v && "Must provide divisor");
1052   assert(q && "Must provide quotient");
1053   assert(u != v && u != q && v != q && "Must us different memory");
1054   assert(n>1 && "n must be > 1");
1055
1056   // Knuth uses the value b as the base of the number system. In our case b
1057   // is 2^31 so we just set it to -1u.
1058   uint64_t b = uint64_t(1) << 32;
1059
1060   DEBUG(cerr << "KnuthDiv: m=" << m << " n=" << n << '\n');
1061   DEBUG(cerr << "KnuthDiv: original:");
1062   DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << std::setbase(16) << u[i]);
1063   DEBUG(cerr << " by");
1064   DEBUG(for (int i = n; i >0; i--) cerr << " " << std::setbase(16) << v[i-1]);
1065   DEBUG(cerr << '\n');
1066   // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of 
1067   // u and v by d. Note that we have taken Knuth's advice here to use a power 
1068   // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of 
1069   // 2 allows us to shift instead of multiply and it is easy to determine the 
1070   // shift amount from the leading zeros.  We are basically normalizing the u
1071   // and v so that its high bits are shifted to the top of v's range without
1072   // overflow. Note that this can require an extra word in u so that u must
1073   // be of length m+n+1.
1074   uint32_t shift = CountLeadingZeros_32(v[n-1]);
1075   uint32_t v_carry = 0;
1076   uint32_t u_carry = 0;
1077   if (shift) {
1078     for (uint32_t i = 0; i < m+n; ++i) {
1079       uint32_t u_tmp = u[i] >> (32 - shift);
1080       u[i] = (u[i] << shift) | u_carry;
1081       u_carry = u_tmp;
1082     }
1083     for (uint32_t i = 0; i < n; ++i) {
1084       uint32_t v_tmp = v[i] >> (32 - shift);
1085       v[i] = (v[i] << shift) | v_carry;
1086       v_carry = v_tmp;
1087     }
1088   }
1089   u[m+n] = u_carry;
1090   DEBUG(cerr << "KnuthDiv:   normal:");
1091   DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << std::setbase(16) << u[i]);
1092   DEBUG(cerr << " by");
1093   DEBUG(for (int i = n; i >0; i--) cerr << " " << std::setbase(16) << v[i-1]);
1094   DEBUG(cerr << '\n');
1095
1096   // D2. [Initialize j.]  Set j to m. This is the loop counter over the places.
1097   int j = m;
1098   do {
1099     DEBUG(cerr << "KnuthDiv: quotient digit #" << j << '\n');
1100     // D3. [Calculate q'.]. 
1101     //     Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
1102     //     Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
1103     // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
1104     // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test
1105     // on v[n-2] determines at high speed most of the cases in which the trial
1106     // value qp is one too large, and it eliminates all cases where qp is two 
1107     // too large. 
1108     uint64_t dividend = ((uint64_t(u[j+n]) << 32) + u[j+n-1]);
1109     DEBUG(cerr << "KnuthDiv: dividend == " << dividend << '\n');
1110     uint64_t qp = dividend / v[n-1];
1111     uint64_t rp = dividend % v[n-1];
1112     if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1113       qp--;
1114       rp += v[n-1];
1115       if (rp < b && (qp == b || qp*v[n-2] > b*rp + u[j+n-2]))
1116         qp--;
1117     }
1118     DEBUG(cerr << "KnuthDiv: qp == " << qp << ", rp == " << rp << '\n');
1119
1120     // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with
1121     // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation
1122     // consists of a simple multiplication by a one-place number, combined with
1123     // a subtraction. 
1124     bool isNegative = false;
1125     for (uint32_t i = 0; i < n; ++i) {
1126       uint64_t u_tmp = uint64_t(u[j+i]) | (uint64_t(u[j+i+1]) << 32);
1127       uint64_t subtrahend = uint64_t(qp) * uint64_t(v[i]);
1128       bool borrow = subtrahend > u_tmp;
1129       DEBUG(cerr << "KnuthDiv: u_tmp == " << u_tmp 
1130                  << ", subtrahend == " << subtrahend
1131                  << ", borrow = " << borrow << '\n');
1132
1133       uint64_t result = u_tmp - subtrahend;
1134       uint32_t k = j + i;
1135       u[k++] = result & (b-1); // subtract low word
1136       u[k++] = result >> 32;   // subtract high word
1137       while (borrow && k <= m+n) { // deal with borrow to the left
1138         borrow = u[k] == 0;
1139         u[k]--;
1140         k++;
1141       }
1142       isNegative |= borrow;
1143       DEBUG(cerr << "KnuthDiv: u[j+i] == " << u[j+i] << ",  u[j+i+1] == " << 
1144                     u[j+i+1] << '\n'); 
1145     }
1146     DEBUG(cerr << "KnuthDiv: after subtraction:");
1147     DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << u[i]);
1148     DEBUG(cerr << '\n');
1149     // The digits (u[j+n]...u[j]) should be kept positive; if the result of 
1150     // this step is actually negative, (u[j+n]...u[j]) should be left as the 
1151     // true value plus b**(n+1), namely as the b's complement of
1152     // the true value, and a "borrow" to the left should be remembered.
1153     //
1154     if (isNegative) {
1155       bool carry = true;  // true because b's complement is "complement + 1"
1156       for (uint32_t i = 0; i <= m+n; ++i) {
1157         u[i] = ~u[i] + carry; // b's complement
1158         carry = carry && u[i] == 0;
1159       }
1160     }
1161     DEBUG(cerr << "KnuthDiv: after complement:");
1162     DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << u[i]);
1163     DEBUG(cerr << '\n');
1164
1165     // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was 
1166     // negative, go to step D6; otherwise go on to step D7.
1167     q[j] = qp;
1168     if (isNegative) {
1169       // D6. [Add back]. The probability that this step is necessary is very 
1170       // small, on the order of only 2/b. Make sure that test data accounts for
1171       // this possibility. Decrease q[j] by 1 
1172       q[j]--;
1173       // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]). 
1174       // A carry will occur to the left of u[j+n], and it should be ignored 
1175       // since it cancels with the borrow that occurred in D4.
1176       bool carry = false;
1177       for (uint32_t i = 0; i < n; i++) {
1178         uint32_t limit = std::min(u[j+i],v[i]);
1179         u[j+i] += v[i] + carry;
1180         carry = u[j+i] < limit || (carry && u[j+i] == limit);
1181       }
1182       u[j+n] += carry;
1183     }
1184     DEBUG(cerr << "KnuthDiv: after correction:");
1185     DEBUG(for (int i = m+n; i >=0; i--) cerr <<" " << u[i]);
1186     DEBUG(cerr << "\nKnuthDiv: digit result = " << q[j] << '\n');
1187
1188   // D7. [Loop on j.]  Decrease j by one. Now if j >= 0, go back to D3.
1189   } while (--j >= 0);
1190
1191   DEBUG(cerr << "KnuthDiv: quotient:");
1192   DEBUG(for (int i = m; i >=0; i--) cerr <<" " << q[i]);
1193   DEBUG(cerr << '\n');
1194
1195   // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
1196   // remainder may be obtained by dividing u[...] by d. If r is non-null we
1197   // compute the remainder (urem uses this).
1198   if (r) {
1199     // The value d is expressed by the "shift" value above since we avoided
1200     // multiplication by d by using a shift left. So, all we have to do is
1201     // shift right here. In order to mak
1202     if (shift) {
1203       uint32_t carry = 0;
1204       DEBUG(cerr << "KnuthDiv: remainder:");
1205       for (int i = n-1; i >= 0; i--) {
1206         r[i] = (u[i] >> shift) | carry;
1207         carry = u[i] << (32 - shift);
1208         DEBUG(cerr << " " << r[i]);
1209       }
1210     } else {
1211       for (int i = n-1; i >= 0; i--) {
1212         r[i] = u[i];
1213         DEBUG(cerr << " " << r[i]);
1214       }
1215     }
1216     DEBUG(cerr << '\n');
1217   }
1218   DEBUG(cerr << std::setbase(10) << '\n');
1219 }
1220
1221 void APInt::divide(const APInt LHS, uint32_t lhsWords, 
1222                    const APInt &RHS, uint32_t rhsWords,
1223                    APInt *Quotient, APInt *Remainder)
1224 {
1225   assert(lhsWords >= rhsWords && "Fractional result");
1226
1227   // First, compose the values into an array of 32-bit words instead of 
1228   // 64-bit words. This is a necessity of both the "short division" algorithm
1229   // and the the Knuth "classical algorithm" which requires there to be native 
1230   // operations for +, -, and * on an m bit value with an m*2 bit result. We 
1231   // can't use 64-bit operands here because we don't have native results of 
1232   // 128-bits. Furthremore, casting the 64-bit values to 32-bit values won't 
1233   // work on large-endian machines.
1234   uint64_t mask = ~0ull >> (sizeof(uint32_t)*8);
1235   uint32_t n = rhsWords * 2;
1236   uint32_t m = (lhsWords * 2) - n;
1237
1238   // Allocate space for the temporary values we need either on the stack, if
1239   // it will fit, or on the heap if it won't.
1240   uint32_t SPACE[128];
1241   uint32_t *U = 0;
1242   uint32_t *V = 0;
1243   uint32_t *Q = 0;
1244   uint32_t *R = 0;
1245   if ((Remainder?4:3)*n+2*m+1 <= 128) {
1246     U = &SPACE[0];
1247     V = &SPACE[m+n+1];
1248     Q = &SPACE[(m+n+1) + n];
1249     if (Remainder)
1250       R = &SPACE[(m+n+1) + n + (m+n)];
1251   } else {
1252     U = new uint32_t[m + n + 1];
1253     V = new uint32_t[n];
1254     Q = new uint32_t[m+n];
1255     if (Remainder)
1256       R = new uint32_t[n];
1257   }
1258
1259   // Initialize the dividend
1260   memset(U, 0, (m+n+1)*sizeof(uint32_t));
1261   for (unsigned i = 0; i < lhsWords; ++i) {
1262     uint64_t tmp = (LHS.getNumWords() == 1 ? LHS.VAL : LHS.pVal[i]);
1263     U[i * 2] = tmp & mask;
1264     U[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1265   }
1266   U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
1267
1268   // Initialize the divisor
1269   memset(V, 0, (n)*sizeof(uint32_t));
1270   for (unsigned i = 0; i < rhsWords; ++i) {
1271     uint64_t tmp = (RHS.getNumWords() == 1 ? RHS.VAL : RHS.pVal[i]);
1272     V[i * 2] = tmp & mask;
1273     V[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1274   }
1275
1276   // initialize the quotient and remainder
1277   memset(Q, 0, (m+n) * sizeof(uint32_t));
1278   if (Remainder)
1279     memset(R, 0, n * sizeof(uint32_t));
1280
1281   // Now, adjust m and n for the Knuth division. n is the number of words in 
1282   // the divisor. m is the number of words by which the dividend exceeds the
1283   // divisor (i.e. m+n is the length of the dividend). These sizes must not 
1284   // contain any zero words or the Knuth algorithm fails.
1285   for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
1286     n--;
1287     m++;
1288   }
1289   for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
1290     m--;
1291
1292   // If we're left with only a single word for the divisor, Knuth doesn't work
1293   // so we implement the short division algorithm here. This is much simpler
1294   // and faster because we are certain that we can divide a 64-bit quantity
1295   // by a 32-bit quantity at hardware speed and short division is simply a
1296   // series of such operations. This is just like doing short division but we
1297   // are using base 2^32 instead of base 10.
1298   assert(n != 0 && "Divide by zero?");
1299   if (n == 1) {
1300     uint32_t divisor = V[0];
1301     uint32_t remainder = 0;
1302     for (int i = m+n-1; i >= 0; i--) {
1303       uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i];
1304       if (partial_dividend == 0) {
1305         Q[i] = 0;
1306         remainder = 0;
1307       } else if (partial_dividend < divisor) {
1308         Q[i] = 0;
1309         remainder = partial_dividend;
1310       } else if (partial_dividend == divisor) {
1311         Q[i] = 1;
1312         remainder = 0;
1313       } else {
1314         Q[i] = partial_dividend / divisor;
1315         remainder = partial_dividend - (Q[i] * divisor);
1316       }
1317     }
1318     if (R)
1319       R[0] = remainder;
1320   } else {
1321     // Now we're ready to invoke the Knuth classical divide algorithm. In this
1322     // case n > 1.
1323     KnuthDiv(U, V, Q, R, m, n);
1324   }
1325
1326   // If the caller wants the quotient
1327   if (Quotient) {
1328     // Set up the Quotient value's memory.
1329     if (Quotient->BitWidth != LHS.BitWidth) {
1330       if (Quotient->isSingleWord())
1331         Quotient->VAL = 0;
1332       else
1333         delete Quotient->pVal;
1334       Quotient->BitWidth = LHS.BitWidth;
1335       if (!Quotient->isSingleWord())
1336         Quotient->pVal = getClearedMemory(Quotient->getNumWords());
1337     } else
1338       Quotient->clear();
1339
1340     // The quotient is in Q. Reconstitute the quotient into Quotient's low 
1341     // order words.
1342     if (lhsWords == 1) {
1343       uint64_t tmp = 
1344         uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2));
1345       if (Quotient->isSingleWord())
1346         Quotient->VAL = tmp;
1347       else
1348         Quotient->pVal[0] = tmp;
1349     } else {
1350       assert(!Quotient->isSingleWord() && "Quotient APInt not large enough");
1351       for (unsigned i = 0; i < lhsWords; ++i)
1352         Quotient->pVal[i] = 
1353           uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1354     }
1355   }
1356
1357   // If the caller wants the remainder
1358   if (Remainder) {
1359     // Set up the Remainder value's memory.
1360     if (Remainder->BitWidth != RHS.BitWidth) {
1361       if (Remainder->isSingleWord())
1362         Remainder->VAL = 0;
1363       else
1364         delete Remainder->pVal;
1365       Remainder->BitWidth = RHS.BitWidth;
1366       if (!Remainder->isSingleWord())
1367         Remainder->pVal = getClearedMemory(Remainder->getNumWords());
1368     } else
1369       Remainder->clear();
1370
1371     // The remainder is in R. Reconstitute the remainder into Remainder's low
1372     // order words.
1373     if (rhsWords == 1) {
1374       uint64_t tmp = 
1375         uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2));
1376       if (Remainder->isSingleWord())
1377         Remainder->VAL = tmp;
1378       else
1379         Remainder->pVal[0] = tmp;
1380     } else {
1381       assert(!Remainder->isSingleWord() && "Remainder APInt not large enough");
1382       for (unsigned i = 0; i < rhsWords; ++i)
1383         Remainder->pVal[i] = 
1384           uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1385     }
1386   }
1387
1388   // Clean up the memory we allocated.
1389   if (U != &SPACE[0]) {
1390     delete [] U;
1391     delete [] V;
1392     delete [] Q;
1393     delete [] R;
1394   }
1395 }
1396
1397 APInt APInt::udiv(const APInt& RHS) const {
1398   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1399
1400   // First, deal with the easy case
1401   if (isSingleWord()) {
1402     assert(RHS.VAL != 0 && "Divide by zero?");
1403     return APInt(BitWidth, VAL / RHS.VAL);
1404   }
1405
1406   // Get some facts about the LHS and RHS number of bits and words
1407   uint32_t rhsBits = RHS.getActiveBits();
1408   uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
1409   assert(rhsWords && "Divided by zero???");
1410   uint32_t lhsBits = this->getActiveBits();
1411   uint32_t lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
1412
1413   // Deal with some degenerate cases
1414   if (!lhsWords) 
1415     // 0 / X ===> 0
1416     return APInt(BitWidth, 0); 
1417   else if (lhsWords < rhsWords || this->ult(RHS)) {
1418     // X / Y ===> 0, iff X < Y
1419     return APInt(BitWidth, 0);
1420   } else if (*this == RHS) {
1421     // X / X ===> 1
1422     return APInt(BitWidth, 1);
1423   } else if (lhsWords == 1 && rhsWords == 1) {
1424     // All high words are zero, just use native divide
1425     return APInt(BitWidth, this->pVal[0] / RHS.pVal[0]);
1426   }
1427
1428   // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1429   APInt Quotient(1,0); // to hold result.
1430   divide(*this, lhsWords, RHS, rhsWords, &Quotient, 0);
1431   return Quotient;
1432 }
1433
1434 APInt APInt::urem(const APInt& RHS) const {
1435   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1436   if (isSingleWord()) {
1437     assert(RHS.VAL != 0 && "Remainder by zero?");
1438     return APInt(BitWidth, VAL % RHS.VAL);
1439   }
1440
1441   // Get some facts about the LHS
1442   uint32_t lhsBits = getActiveBits();
1443   uint32_t lhsWords = !lhsBits ? 0 : (whichWord(lhsBits - 1) + 1);
1444
1445   // Get some facts about the RHS
1446   uint32_t rhsBits = RHS.getActiveBits();
1447   uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
1448   assert(rhsWords && "Performing remainder operation by zero ???");
1449
1450   // Check the degenerate cases
1451   if (lhsWords == 0) {
1452     // 0 % Y ===> 0
1453     return APInt(BitWidth, 0);
1454   } else if (lhsWords < rhsWords || this->ult(RHS)) {
1455     // X % Y ===> X, iff X < Y
1456     return *this;
1457   } else if (*this == RHS) {
1458     // X % X == 0;
1459     return APInt(BitWidth, 0);
1460   } else if (lhsWords == 1) {
1461     // All high words are zero, just use native remainder
1462     return APInt(BitWidth, pVal[0] % RHS.pVal[0]);
1463   }
1464
1465   // We have to compute it the hard way. Invoke the Knute divide algorithm.
1466   APInt Remainder(1,0);
1467   divide(*this, lhsWords, RHS, rhsWords, 0, &Remainder);
1468   return Remainder;
1469 }
1470
1471 void APInt::fromString(uint32_t numbits, const char *str, uint32_t slen, 
1472                        uint8_t radix) {
1473   // Check our assumptions here
1474   assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1475          "Radix should be 2, 8, 10, or 16!");
1476   assert(str && "String is null?");
1477   bool isNegative = str[0] == '-';
1478   if (isNegative)
1479     str++, slen--;
1480   assert(slen <= numbits || radix != 2 && "Insufficient bit width");
1481   assert(slen*3 <= numbits || radix != 8 && "Insufficient bit width");
1482   assert(slen*4 <= numbits || radix != 16 && "Insufficient bit width");
1483   assert((slen*64)/20 <= numbits || radix != 10 && "Insufficient bit width");
1484
1485   // Allocate memory
1486   if (!isSingleWord())
1487     pVal = getClearedMemory(getNumWords());
1488
1489   // Figure out if we can shift instead of multiply
1490   uint32_t shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0);
1491
1492   // Set up an APInt for the digit to add outside the loop so we don't
1493   // constantly construct/destruct it.
1494   APInt apdigit(getBitWidth(), 0);
1495   APInt apradix(getBitWidth(), radix);
1496
1497   // Enter digit traversal loop
1498   for (unsigned i = 0; i < slen; i++) {
1499     // Get a digit
1500     uint32_t digit = 0;
1501     char cdigit = str[i];
1502     if (isdigit(cdigit))
1503       digit = cdigit - '0';
1504     else if (isxdigit(cdigit))
1505       if (cdigit >= 'a')
1506         digit = cdigit - 'a' + 10;
1507       else if (cdigit >= 'A')
1508         digit = cdigit - 'A' + 10;
1509       else
1510         assert(0 && "huh?");
1511     else
1512       assert(0 && "Invalid character in digit string");
1513
1514     // Shift or multiple the value by the radix
1515     if (shift)
1516       this->shl(shift);
1517     else
1518       *this *= apradix;
1519
1520     // Add in the digit we just interpreted
1521     if (apdigit.isSingleWord())
1522       apdigit.VAL = digit;
1523     else
1524       apdigit.pVal[0] = digit;
1525     *this += apdigit;
1526   }
1527   // If its negative, put it in two's complement form
1528   if (isNegative) {
1529     this->flip();
1530     (*this)++;
1531   }
1532 }
1533
1534 std::string APInt::toString(uint8_t radix, bool wantSigned) const {
1535   assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1536          "Radix should be 2, 8, 10, or 16!");
1537   static const char *digits[] = { 
1538     "0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F" 
1539   };
1540   std::string result;
1541   uint32_t bits_used = getActiveBits();
1542   if (isSingleWord()) {
1543     char buf[65];
1544     const char *format = (radix == 10 ? (wantSigned ? "%lld" : "%llu") :
1545        (radix == 16 ? "%llX" : (radix == 8 ? "%llo" : 0)));
1546     if (format) {
1547       if (wantSigned) {
1548         int64_t sextVal = (int64_t(VAL) << (APINT_BITS_PER_WORD-BitWidth)) >> 
1549                            (APINT_BITS_PER_WORD-BitWidth);
1550         sprintf(buf, format, sextVal);
1551       } else 
1552         sprintf(buf, format, VAL);
1553     } else {
1554       memset(buf, 0, 65);
1555       uint64_t v = VAL;
1556       while (bits_used) {
1557         uint32_t bit = v & 1;
1558         bits_used--;
1559         buf[bits_used] = digits[bit][0];
1560         v >>=1;
1561       }
1562     }
1563     result = buf;
1564     return result;
1565   }
1566
1567   if (radix != 10) {
1568     uint64_t mask = radix - 1;
1569     uint32_t shift = (radix == 16 ? 4 : radix  == 8 ? 3 : 1);
1570     uint32_t nibbles = APINT_BITS_PER_WORD / shift;
1571     for (uint32_t i = 0; i < getNumWords(); ++i) {
1572       uint64_t value = pVal[i];
1573       for (uint32_t j = 0; j < nibbles; ++j) {
1574         result.insert(0, digits[ value & mask ]);
1575         value >>= shift;
1576       }
1577     }
1578     return result;
1579   }
1580
1581   APInt tmp(*this);
1582   APInt divisor(4, radix);
1583   APInt zero(tmp.getBitWidth(), 0);
1584   size_t insert_at = 0;
1585   if (wantSigned && tmp[BitWidth-1]) {
1586     // They want to print the signed version and it is a negative value
1587     // Flip the bits and add one to turn it into the equivalent positive
1588     // value and put a '-' in the result.
1589     tmp.flip();
1590     tmp++;
1591     result = "-";
1592     insert_at = 1;
1593   }
1594   if (tmp == APInt(tmp.getBitWidth(), 0))
1595     result = "0";
1596   else while (tmp.ne(zero)) {
1597     APInt APdigit(1,0);
1598     APInt tmp2(tmp.getBitWidth(), 0);
1599     divide(tmp, tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2, 
1600            &APdigit);
1601     uint32_t digit = APdigit.getValue();
1602     assert(digit < radix && "divide failed");
1603     result.insert(insert_at,digits[digit]);
1604     tmp = tmp2;
1605   }
1606
1607   return result;
1608 }
1609
1610 #ifndef NDEBUG
1611 void APInt::dump() const
1612 {
1613   cerr << "APInt(" << BitWidth << ")=" << std::setbase(16);
1614   if (isSingleWord())
1615     cerr << VAL;
1616   else for (unsigned i = getNumWords(); i > 0; i--) {
1617     cerr << pVal[i-1] << " ";
1618   }
1619   cerr << " (" << this->toString(10, false) << ")\n" << std::setbase(10);
1620 }
1621 #endif