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