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