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