Make add_1 exit early if carry is 0.
[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 using namespace llvm;
21
22 #if 0
23 /// lshift - This function shift x[0:len-1] left by shiftAmt bits, and 
24 /// store the len least significant words of the result in 
25 /// dest[d_offset:d_offset+len-1]. It returns the bits shifted out from 
26 /// the most significant digit.
27 static uint64_t lshift(uint64_t dest[], unsigned d_offset,
28                        uint64_t x[], unsigned len, unsigned shiftAmt) {
29   unsigned count = APINT_BITS_PER_WORD - shiftAmt;
30   int i = len - 1;
31   uint64_t high_word = x[i], retVal = high_word >> count;
32   ++d_offset;
33   while (--i >= 0) {
34     uint64_t low_word = x[i];
35     dest[d_offset+i] = (high_word << shiftAmt) | (low_word >> count);
36     high_word = low_word;
37   }
38   dest[d_offset+i] = high_word << shiftAmt;
39   return retVal;
40 }
41 #endif
42
43 APInt::APInt(unsigned numBits, uint64_t val)
44   : BitWidth(numBits) {
45   assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
46   assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
47   if (isSingleWord()) 
48     VAL = val & (~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - BitWidth));
49   else {
50     // Memory allocation and check if successful.
51     assert((pVal = new uint64_t[getNumWords()]) && 
52             "APInt memory allocation fails!");
53     memset(pVal, 0, getNumWords() * 8);
54     pVal[0] = val;
55   }
56 }
57
58 APInt::APInt(unsigned numBits, unsigned numWords, uint64_t bigVal[])
59   : BitWidth(numBits) {
60   assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
61   assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
62   assert(bigVal && "Null pointer detected!");
63   if (isSingleWord())
64     VAL = bigVal[0] & (~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - BitWidth));
65   else {
66     // Memory allocation and check if successful.
67     assert((pVal = new uint64_t[getNumWords()]) && 
68            "APInt memory allocation fails!");
69     // Calculate the actual length of bigVal[].
70     unsigned maxN = std::max<unsigned>(numWords, getNumWords());
71     unsigned minN = std::min<unsigned>(numWords, getNumWords());
72     memcpy(pVal, bigVal, (minN - 1) * 8);
73     pVal[minN-1] = bigVal[minN-1] & 
74                     (~uint64_t(0ULL) >> 
75                      (APINT_BITS_PER_WORD - BitWidth % APINT_BITS_PER_WORD));
76     if (maxN == getNumWords())
77       memset(pVal+numWords, 0, (getNumWords() - numWords) * 8);
78   }
79 }
80
81 /// @brief Create a new APInt by translating the char array represented
82 /// integer value.
83 APInt::APInt(unsigned numbits, const char StrStart[], unsigned slen, 
84              uint8_t radix) {
85   fromString(numbits, StrStart, slen, radix);
86 }
87
88 /// @brief Create a new APInt by translating the string represented
89 /// integer value.
90 APInt::APInt(unsigned numbits, const std::string& Val, uint8_t radix) {
91   assert(!Val.empty() && "String empty?");
92   fromString(numbits, Val.c_str(), Val.size(), radix);
93 }
94
95 APInt::APInt(const APInt& APIVal)
96   : BitWidth(APIVal.BitWidth) {
97   if (isSingleWord()) VAL = APIVal.VAL;
98   else {
99     // Memory allocation and check if successful.
100     assert((pVal = new uint64_t[getNumWords()]) && 
101            "APInt memory allocation fails!");
102     memcpy(pVal, APIVal.pVal, getNumWords() * 8);
103   }
104 }
105
106 APInt::~APInt() {
107   if (!isSingleWord() && pVal) delete[] pVal;
108 }
109
110 /// @brief Copy assignment operator. Create a new object from the given
111 /// APInt one by initialization.
112 APInt& APInt::operator=(const APInt& RHS) {
113   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
114   if (isSingleWord()) 
115     VAL = RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
116   else {
117     unsigned minN = std::min(getNumWords(), RHS.getNumWords());
118     memcpy(pVal, RHS.isSingleWord() ? &RHS.VAL : RHS.pVal, minN * 8);
119     if (getNumWords() != minN)
120       memset(pVal + minN, 0, (getNumWords() - minN) * 8);
121   }
122   return *this;
123 }
124
125 /// @brief Assignment operator. Assigns a common case integer value to 
126 /// the APInt.
127 APInt& APInt::operator=(uint64_t RHS) {
128   if (isSingleWord()) 
129     VAL = RHS;
130   else {
131     pVal[0] = RHS;
132     memset(pVal, 0, (getNumWords() - 1) * 8);
133   }
134   clearUnusedBits();
135   return *this;
136 }
137
138 /// add_1 - This function adds the integer array x[] by integer y and
139 /// returns the carry.
140 /// @returns the carry of the addition.
141 static uint64_t add_1(uint64_t dest[], uint64_t x[], unsigned len, uint64_t y) {
142   for (unsigned i = 0; i < len; ++i) {
143     dest[i] = y + x[i];
144     if (dest[i] < y)
145       y = 1;
146     else {
147       y = 0;
148       break;
149     }
150   }
151   return y;
152 }
153
154 /// @brief Prefix increment operator. Increments the APInt by one.
155 APInt& APInt::operator++() {
156   if (isSingleWord()) 
157     ++VAL;
158   else
159     add_1(pVal, pVal, getNumWords(), 1);
160   clearUnusedBits();
161   return *this;
162 }
163
164 /// sub_1 - This function subtracts the integer array x[] by
165 /// integer y and returns the borrow-out carry.
166 static uint64_t sub_1(uint64_t x[], unsigned len, uint64_t y) {
167   for (unsigned i = 0; i < len; ++i) {
168     uint64_t X = x[i];
169     x[i] -= y;
170     if (y > X) 
171       y = 1;
172     else {
173       y = 0;
174       break;
175     }
176   }
177   return y;
178 }
179
180 /// @brief Prefix decrement operator. Decrements the APInt by one.
181 APInt& APInt::operator--() {
182   if (isSingleWord()) --VAL;
183   else
184     sub_1(pVal, getNumWords(), 1);
185   clearUnusedBits();
186   return *this;
187 }
188
189 /// add - This function adds the integer array x[] by integer array
190 /// y[] and returns the carry.
191 static uint64_t add(uint64_t dest[], uint64_t x[], uint64_t y[], unsigned len) {
192   unsigned carry = 0;
193   for (unsigned i = 0; i< len; ++i) {
194     carry += x[i];
195     dest[i] = carry + y[i];
196     carry = carry < x[i] ? 1 : (dest[i] < carry ? 1 : 0);
197   }
198   return carry;
199 }
200
201 /// @brief Addition assignment operator. Adds this APInt by the given APInt&
202 /// RHS and assigns the result to this APInt.
203 APInt& APInt::operator+=(const APInt& RHS) {
204   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
205   if (isSingleWord()) VAL += RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
206   else {
207     if (RHS.isSingleWord()) add_1(pVal, pVal, getNumWords(), RHS.VAL);
208     else {
209       if (getNumWords() <= RHS.getNumWords()) 
210         add(pVal, pVal, RHS.pVal, getNumWords());
211       else {
212         uint64_t carry = add(pVal, pVal, RHS.pVal, RHS.getNumWords());
213         add_1(pVal + RHS.getNumWords(), pVal + RHS.getNumWords(), 
214               getNumWords() - RHS.getNumWords(), carry);
215       }
216     }
217   }
218   clearUnusedBits();
219   return *this;
220 }
221
222 /// sub - This function subtracts the integer array x[] by
223 /// integer array y[], and returns the borrow-out carry.
224 static uint64_t sub(uint64_t dest[], uint64_t x[], uint64_t y[], unsigned len) {
225   // Carry indicator.
226   uint64_t cy = 0;
227   
228   for (unsigned i = 0; i < len; ++i) {
229     uint64_t Y = y[i], X = x[i];
230     Y += cy;
231
232     cy = Y < cy ? 1 : 0;
233     Y = X - Y;
234     cy += Y > X ? 1 : 0;
235     dest[i] = Y;
236   }
237   return cy;
238 }
239
240 /// @brief Subtraction assignment operator. Subtracts this APInt by the given
241 /// APInt &RHS and assigns the result to this APInt.
242 APInt& APInt::operator-=(const APInt& RHS) {
243   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
244   if (isSingleWord()) 
245     VAL -= RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
246   else {
247     if (RHS.isSingleWord())
248       sub_1(pVal, getNumWords(), RHS.VAL);
249     else {
250       if (RHS.getNumWords() < getNumWords()) { 
251         uint64_t carry = sub(pVal, pVal, RHS.pVal, RHS.getNumWords());
252         sub_1(pVal + RHS.getNumWords(), getNumWords() - RHS.getNumWords(), 
253               carry); 
254       }
255       else
256         sub(pVal, pVal, RHS.pVal, getNumWords());
257     }
258   }
259   clearUnusedBits();
260   return *this;
261 }
262
263 /// mul_1 - This function performs the multiplication operation on a
264 /// large integer (represented as an integer array) and a uint64_t integer.
265 /// @returns the carry of the multiplication.
266 static uint64_t mul_1(uint64_t dest[], uint64_t x[],
267                      unsigned len, 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 (unsigned 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[], unsigned xlen,
300                uint64_t y[], unsigned ylen) {
301   dest[xlen] = mul_1(dest, x, xlen, y[0]);
302
303   for (unsigned 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 (unsigned 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     unsigned first = getActiveBits();
338     unsigned 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       unsigned ylen = !first ? 0 : whichWord(first - 1) + 1;
346       if (!ylen) {
347         memset(pVal, 0, getNumWords() * 8);
348         return *this;
349       }
350       uint64_t *dest = new uint64_t[xlen+ylen];
351       assert(dest && "Memory Allocation Failed!");
352       mul(dest, pVal, xlen, RHS.pVal, ylen);
353       memcpy(pVal, dest, ((xlen + ylen >= getNumWords()) ? 
354                          getNumWords() : xlen + ylen) * 8);
355       delete[] dest;
356     }
357   }
358   clearUnusedBits();
359   return *this;
360 }
361
362 /// @brief Bitwise AND assignment operator. Performs bitwise AND operation on
363 /// this APInt and the given APInt& RHS, assigns the result to this APInt.
364 APInt& APInt::operator&=(const APInt& RHS) {
365   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
366   if (isSingleWord()) {
367     if (RHS.isSingleWord()) VAL &= RHS.VAL;
368     else VAL &= RHS.pVal[0];
369   } else {
370     if (RHS.isSingleWord()) {
371       memset(pVal, 0, (getNumWords() - 1) * 8);
372       pVal[0] &= RHS.VAL;
373     } else {
374       unsigned minwords = getNumWords() < RHS.getNumWords() ? 
375                           getNumWords() : RHS.getNumWords();
376       for (unsigned i = 0; i < minwords; ++i)
377         pVal[i] &= RHS.pVal[i];
378       if (getNumWords() > minwords) 
379         memset(pVal+minwords, 0, (getNumWords() - minwords) * 8);
380     }
381   }
382   return *this;
383 }
384
385 /// @brief Bitwise OR assignment operator. Performs bitwise OR operation on 
386 /// this APInt and the given APInt& RHS, assigns the result to this APInt.
387 APInt& APInt::operator|=(const APInt& RHS) {
388   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
389   if (isSingleWord()) {
390     if (RHS.isSingleWord()) VAL |= RHS.VAL;
391     else VAL |= RHS.pVal[0];
392   } else {
393     if (RHS.isSingleWord()) {
394       pVal[0] |= RHS.VAL;
395     } else {
396       unsigned minwords = getNumWords() < RHS.getNumWords() ? 
397                           getNumWords() : RHS.getNumWords();
398       for (unsigned i = 0; i < minwords; ++i)
399         pVal[i] |= RHS.pVal[i];
400     }
401   }
402   clearUnusedBits();
403   return *this;
404 }
405
406 /// @brief Bitwise XOR assignment operator. Performs bitwise XOR operation on
407 /// this APInt and the given APInt& RHS, assigns the result to this APInt.
408 APInt& APInt::operator^=(const APInt& RHS) {
409   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
410   if (isSingleWord()) {
411     VAL ^= RHS.VAL;
412     return *this;
413   } 
414   unsigned numWords = getNumWords();
415   for (unsigned i = 0; i < numWords; ++i)
416       pVal[i] ^= RHS.pVal[i];
417   return *this;
418 }
419
420 /// @brief Bitwise AND operator. Performs bitwise AND operation on this APInt
421 /// and the given APInt& RHS.
422 APInt APInt::operator&(const APInt& RHS) const {
423   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
424   APInt API(RHS);
425   return API &= *this;
426 }
427
428 /// @brief Bitwise OR operator. Performs bitwise OR operation on this APInt 
429 /// and the given APInt& RHS.
430 APInt APInt::operator|(const APInt& RHS) const {
431   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
432   APInt API(RHS);
433   API |= *this;
434   API.clearUnusedBits();
435   return API;
436 }
437
438 /// @brief Bitwise XOR operator. Performs bitwise XOR operation on this APInt
439 /// and the given APInt& RHS.
440 APInt APInt::operator^(const APInt& RHS) const {
441   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
442   APInt API(RHS);
443   API ^= *this;
444   API.clearUnusedBits();
445   return API;
446 }
447
448
449 /// @brief Logical negation operator. Performs logical negation operation on
450 /// this APInt.
451 bool APInt::operator !() const {
452   if (isSingleWord())
453     return !VAL;
454   else
455     for (unsigned i = 0; i < getNumWords(); ++i)
456        if (pVal[i]) 
457          return false;
458   return true;
459 }
460
461 /// @brief Multiplication operator. Multiplies this APInt by the given APInt& 
462 /// RHS.
463 APInt APInt::operator*(const APInt& RHS) const {
464   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
465   APInt API(RHS);
466   API *= *this;
467   API.clearUnusedBits();
468   return API;
469 }
470
471 /// @brief Addition operator. Adds this APInt by the given APInt& RHS.
472 APInt APInt::operator+(const APInt& RHS) const {
473   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
474   APInt API(*this);
475   API += RHS;
476   API.clearUnusedBits();
477   return API;
478 }
479
480 /// @brief Subtraction operator. Subtracts this APInt by the given APInt& RHS
481 APInt APInt::operator-(const APInt& RHS) const {
482   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
483   APInt API(*this);
484   API -= RHS;
485   return API;
486 }
487
488 /// @brief Array-indexing support.
489 bool APInt::operator[](unsigned bitPosition) const {
490   return (maskBit(bitPosition) & (isSingleWord() ? 
491           VAL : pVal[whichWord(bitPosition)])) != 0;
492 }
493
494 /// @brief Equality operator. Compare this APInt with the given APInt& RHS 
495 /// for the validity of the equality relationship.
496 bool APInt::operator==(const APInt& RHS) const {
497   unsigned n1 = getActiveBits();
498   unsigned n2 = RHS.getActiveBits();
499   if (n1 != n2) return false;
500   else if (isSingleWord()) 
501     return VAL == (RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0]);
502   else {
503     if (n1 <= APINT_BITS_PER_WORD)
504       return pVal[0] == (RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0]);
505     for (int i = whichWord(n1 - 1); i >= 0; --i)
506       if (pVal[i] != RHS.pVal[i]) return false;
507   }
508   return true;
509 }
510
511 /// @brief Equality operator. Compare this APInt with the given uint64_t value 
512 /// for the validity of the equality relationship.
513 bool APInt::operator==(uint64_t Val) const {
514   if (isSingleWord())
515     return VAL == Val;
516   else {
517     unsigned n = getActiveBits(); 
518     if (n <= APINT_BITS_PER_WORD)
519       return pVal[0] == Val;
520     else
521       return false;
522   }
523 }
524
525 /// @brief Unsigned less than comparison
526 bool APInt::ult(const APInt& RHS) const {
527   assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
528   if (isSingleWord())
529     return VAL < RHS.VAL;
530   else {
531     unsigned n1 = getActiveBits();
532     unsigned n2 = RHS.getActiveBits();
533     if (n1 < n2)
534       return true;
535     else if (n2 < n1)
536       return false;
537     else if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
538       return pVal[0] < RHS.pVal[0];
539     for (int i = whichWord(n1 - 1); i >= 0; --i) {
540       if (pVal[i] > RHS.pVal[i]) return false;
541       else if (pVal[i] < RHS.pVal[i]) return true;
542     }
543   }
544   return false;
545 }
546
547 /// @brief Signed less than comparison
548 bool APInt::slt(const APInt& RHS) const {
549   assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
550   if (isSingleWord())
551     return VAL < RHS.VAL;
552   else {
553     unsigned n1 = getActiveBits();
554     unsigned n2 = RHS.getActiveBits();
555     if (n1 < n2)
556       return true;
557     else if (n2 < n1)
558       return false;
559     else if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
560       return pVal[0] < RHS.pVal[0];
561     for (int i = whichWord(n1 - 1); i >= 0; --i) {
562       if (pVal[i] > RHS.pVal[i]) return false;
563       else if (pVal[i] < RHS.pVal[i]) return true;
564     }
565   }
566   return false;
567 }
568
569 /// Set the given bit to 1 whose poition is given as "bitPosition".
570 /// @brief Set a given bit to 1.
571 APInt& APInt::set(unsigned bitPosition) {
572   if (isSingleWord()) VAL |= maskBit(bitPosition);
573   else pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
574   return *this;
575 }
576
577 /// @brief Set every bit to 1.
578 APInt& APInt::set() {
579   if (isSingleWord()) 
580     VAL = ~0ULL >> (APINT_BITS_PER_WORD - BitWidth);
581   else {
582     for (unsigned i = 0; i < getNumWords() - 1; ++i)
583       pVal[i] = -1ULL;
584     pVal[getNumWords() - 1] = ~0ULL >> 
585       (APINT_BITS_PER_WORD - BitWidth % APINT_BITS_PER_WORD);
586   }
587   return *this;
588 }
589
590 /// Set the given bit to 0 whose position is given as "bitPosition".
591 /// @brief Set a given bit to 0.
592 APInt& APInt::clear(unsigned bitPosition) {
593   if (isSingleWord()) VAL &= ~maskBit(bitPosition);
594   else pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
595   return *this;
596 }
597
598 /// @brief Set every bit to 0.
599 APInt& APInt::clear() {
600   if (isSingleWord()) VAL = 0;
601   else 
602     memset(pVal, 0, getNumWords() * 8);
603   return *this;
604 }
605
606 /// @brief Bitwise NOT operator. Performs a bitwise logical NOT operation on
607 /// this APInt.
608 APInt APInt::operator~() const {
609   APInt API(*this);
610   API.flip();
611   return API;
612 }
613
614 /// @brief Toggle every bit to its opposite value.
615 APInt& APInt::flip() {
616   if (isSingleWord()) VAL = (~(VAL << 
617         (APINT_BITS_PER_WORD - BitWidth))) >> (APINT_BITS_PER_WORD - BitWidth);
618   else {
619     unsigned i = 0;
620     for (; i < getNumWords() - 1; ++i)
621       pVal[i] = ~pVal[i];
622     unsigned offset = 
623       APINT_BITS_PER_WORD - (BitWidth - APINT_BITS_PER_WORD * (i - 1));
624     pVal[i] = (~(pVal[i] << offset)) >> offset;
625   }
626   return *this;
627 }
628
629 /// Toggle a given bit to its opposite value whose position is given 
630 /// as "bitPosition".
631 /// @brief Toggles a given bit to its opposite value.
632 APInt& APInt::flip(unsigned bitPosition) {
633   assert(bitPosition < BitWidth && "Out of the bit-width range!");
634   if ((*this)[bitPosition]) clear(bitPosition);
635   else set(bitPosition);
636   return *this;
637 }
638
639 /// to_string - This function translates the APInt into a string.
640 std::string APInt::toString(uint8_t radix, bool wantSigned) const {
641   assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
642          "Radix should be 2, 8, 10, or 16!");
643   static const char *digits[] = { 
644     "0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F" 
645   };
646   std::string result;
647   unsigned bits_used = getActiveBits();
648   if (isSingleWord()) {
649     char buf[65];
650     const char *format = (radix == 10 ? (wantSigned ? "%lld" : "%llu") :
651        (radix == 16 ? "%llX" : (radix == 8 ? "%llo" : 0)));
652     if (format) {
653       if (wantSigned) {
654         int64_t sextVal = (int64_t(VAL) << (APINT_BITS_PER_WORD-BitWidth)) >> 
655                            (APINT_BITS_PER_WORD-BitWidth);
656         sprintf(buf, format, sextVal);
657       } else 
658         sprintf(buf, format, VAL);
659     } else {
660       memset(buf, 0, 65);
661       uint64_t v = VAL;
662       while (bits_used) {
663         unsigned bit = v & 1;
664         bits_used--;
665         buf[bits_used] = digits[bit][0];
666         v >>=1;
667       }
668     }
669     result = buf;
670     return result;
671   }
672
673   APInt tmp(*this);
674   APInt divisor(tmp.getBitWidth(), radix);
675   APInt zero(tmp.getBitWidth(), 0);
676   size_t insert_at = 0;
677   if (wantSigned && tmp[BitWidth-1]) {
678     // They want to print the signed version and it is a negative value
679     // Flip the bits and add one to turn it into the equivalent positive
680     // value and put a '-' in the result.
681     tmp.flip();
682     tmp++;
683     result = "-";
684     insert_at = 1;
685   }
686   if (tmp == 0)
687     result = "0";
688   else while (tmp.ne(zero)) {
689     APInt APdigit = APIntOps::urem(tmp,divisor);
690     unsigned digit = APdigit.getValue();
691     assert(digit < radix && "urem failed");
692     result.insert(insert_at,digits[digit]);
693     tmp = APIntOps::udiv(tmp, divisor);
694   }
695
696   return result;
697 }
698
699 /// getMaxValue - This function returns the largest value
700 /// for an APInt of the specified bit-width and if isSign == true,
701 /// it should be largest signed value, otherwise unsigned value.
702 APInt APInt::getMaxValue(unsigned numBits, bool isSign) {
703   APInt APIVal(numBits, 0);
704   APIVal.set();
705   if (isSign) APIVal.clear(numBits - 1);
706   return APIVal;
707 }
708
709 /// getMinValue - This function returns the smallest value for
710 /// an APInt of the given bit-width and if isSign == true,
711 /// it should be smallest signed value, otherwise zero.
712 APInt APInt::getMinValue(unsigned numBits, bool isSign) {
713   APInt APIVal(numBits, 0);
714   if (isSign) APIVal.set(numBits - 1);
715   return APIVal;
716 }
717
718 /// getAllOnesValue - This function returns an all-ones value for
719 /// an APInt of the specified bit-width.
720 APInt APInt::getAllOnesValue(unsigned numBits) {
721   return getMaxValue(numBits, false);
722 }
723
724 /// getNullValue - This function creates an '0' value for an
725 /// APInt of the specified bit-width.
726 APInt APInt::getNullValue(unsigned numBits) {
727   return getMinValue(numBits, false);
728 }
729
730 /// HiBits - This function returns the high "numBits" bits of this APInt.
731 APInt APInt::getHiBits(unsigned numBits) const {
732   return APIntOps::lshr(*this, BitWidth - numBits);
733 }
734
735 /// LoBits - This function returns the low "numBits" bits of this APInt.
736 APInt APInt::getLoBits(unsigned numBits) const {
737   return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits), 
738                         BitWidth - numBits);
739 }
740
741 bool APInt::isPowerOf2() const {
742   return (!!*this) && !(*this & (*this - APInt(BitWidth,1)));
743 }
744
745 /// countLeadingZeros - This function is a APInt version corresponding to 
746 /// llvm/include/llvm/Support/MathExtras.h's function 
747 /// countLeadingZeros_{32, 64}. It performs platform optimal form of counting 
748 /// the number of zeros from the most significant bit to the first one bit.
749 /// @returns numWord() * 64 if the value is zero.
750 unsigned APInt::countLeadingZeros() const {
751   if (isSingleWord())
752     return CountLeadingZeros_64(VAL) - (APINT_BITS_PER_WORD - BitWidth);
753   unsigned Count = 0;
754   for (unsigned i = getNumWords(); i > 0u; --i) {
755     unsigned tmp = CountLeadingZeros_64(pVal[i-1]);
756     Count += tmp;
757     if (tmp != APINT_BITS_PER_WORD)
758       if (i == getNumWords())
759         Count -= (APINT_BITS_PER_WORD - whichBit(BitWidth));
760       break;
761   }
762   return Count;
763 }
764
765 /// countTrailingZeros - This function is a APInt version corresponding to
766 /// llvm/include/llvm/Support/MathExtras.h's function 
767 /// countTrailingZeros_{32, 64}. It performs platform optimal form of counting 
768 /// the number of zeros from the least significant bit to the first one bit.
769 /// @returns numWord() * 64 if the value is zero.
770 unsigned APInt::countTrailingZeros() const {
771   if (isSingleWord())
772     return CountTrailingZeros_64(VAL);
773   APInt Tmp( ~(*this) & ((*this) - APInt(BitWidth,1)) );
774   return getNumWords() * APINT_BITS_PER_WORD - Tmp.countLeadingZeros();
775 }
776
777 /// countPopulation - This function is a APInt version corresponding to
778 /// llvm/include/llvm/Support/MathExtras.h's function
779 /// countPopulation_{32, 64}. It counts the number of set bits in a value.
780 /// @returns 0 if the value is zero.
781 unsigned APInt::countPopulation() const {
782   if (isSingleWord())
783     return CountPopulation_64(VAL);
784   unsigned Count = 0;
785   for (unsigned i = 0; i < getNumWords(); ++i)
786     Count += CountPopulation_64(pVal[i]);
787   return Count;
788 }
789
790
791 /// byteSwap - This function returns a byte-swapped representation of the
792 /// this APInt.
793 APInt APInt::byteSwap() const {
794   assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
795   if (BitWidth == 16)
796     return APInt(BitWidth, ByteSwap_16(VAL));
797   else if (BitWidth == 32)
798     return APInt(BitWidth, ByteSwap_32(VAL));
799   else if (BitWidth == 48) {
800     uint64_t Tmp1 = ((VAL >> 32) << 16) | (VAL & 0xFFFF);
801     Tmp1 = ByteSwap_32(Tmp1);
802     uint64_t Tmp2 = (VAL >> 16) & 0xFFFF;
803     Tmp2 = ByteSwap_16(Tmp2);
804     return 
805       APInt(BitWidth, 
806             (Tmp1 & 0xff) | ((Tmp1<<16) & 0xffff00000000ULL) | (Tmp2 << 16));
807   } else if (BitWidth == 64)
808     return APInt(BitWidth, ByteSwap_64(VAL));
809   else {
810     APInt Result(BitWidth, 0);
811     char *pByte = (char*)Result.pVal;
812     for (unsigned i = 0; i < BitWidth / 8 / 2; ++i) {
813       char Tmp = pByte[i];
814       pByte[i] = pByte[BitWidth / 8 - 1 - i];
815       pByte[BitWidth / 8 - i - 1] = Tmp;
816     }
817     return Result;
818   }
819 }
820
821 /// GreatestCommonDivisor - This function returns the greatest common
822 /// divisor of the two APInt values using Enclid's algorithm.
823 APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1, 
824                                             const APInt& API2) {
825   APInt A = API1, B = API2;
826   while (!!B) {
827     APInt T = B;
828     B = APIntOps::urem(A, B);
829     A = T;
830   }
831   return A;
832 }
833
834 /// DoubleRoundToAPInt - This function convert a double value to
835 /// a APInt value.
836 APInt llvm::APIntOps::RoundDoubleToAPInt(double Double) {
837   union {
838     double D;
839     uint64_t I;
840   } T;
841   T.D = Double;
842   bool isNeg = T.I >> 63;
843   int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
844   if (exp < 0)
845     return APInt(64ull, 0u);
846   uint64_t mantissa = ((T.I << 12) >> 12) | (1ULL << 52);
847   if (exp < 52)
848     return isNeg ? -APInt(64u, mantissa >> (52 - exp)) : 
849                     APInt(64u, mantissa >> (52 - exp));
850   APInt Tmp(exp + 1, mantissa);
851   Tmp = Tmp.shl(exp - 52);
852   return isNeg ? -Tmp : Tmp;
853 }
854
855 /// RoundToDouble - This function convert this APInt to a double.
856 /// The layout for double is as following (IEEE Standard 754):
857 ///  --------------------------------------
858 /// |  Sign    Exponent    Fraction    Bias |
859 /// |-------------------------------------- |
860 /// |  1[63]   11[62-52]   52[51-00]   1023 |
861 ///  -------------------------------------- 
862 double APInt::roundToDouble(bool isSigned) const {
863   bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
864   APInt Tmp(isNeg ? -(*this) : (*this));
865   if (Tmp.isSingleWord())
866     return isSigned ? double(int64_t(Tmp.VAL)) : double(Tmp.VAL);
867   unsigned n = Tmp.getActiveBits();
868   if (n <= APINT_BITS_PER_WORD) 
869     return isSigned ? double(int64_t(Tmp.pVal[0])) : double(Tmp.pVal[0]);
870   // Exponent when normalized to have decimal point directly after
871   // leading one. This is stored excess 1023 in the exponent bit field.
872   uint64_t exp = n - 1;
873
874   // Gross overflow.
875   assert(exp <= 1023 && "Infinity value!");
876
877   // Number of bits in mantissa including the leading one
878   // equals to 53.
879   uint64_t mantissa;
880   if (n % APINT_BITS_PER_WORD >= 53)
881     mantissa = Tmp.pVal[whichWord(n - 1)] >> (n % APINT_BITS_PER_WORD - 53);
882   else
883     mantissa = (Tmp.pVal[whichWord(n - 1)] << (53 - n % APINT_BITS_PER_WORD)) | 
884                (Tmp.pVal[whichWord(n - 1) - 1] >> 
885                 (11 + n % APINT_BITS_PER_WORD));
886   // The leading bit of mantissa is implicit, so get rid of it.
887   mantissa &= ~(1ULL << 52);
888   uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
889   exp += 1023;
890   union {
891     double D;
892     uint64_t I;
893   } T;
894   T.I = sign | (exp << 52) | mantissa;
895   return T.D;
896 }
897
898 // Truncate to new width.
899 void APInt::trunc(unsigned width) {
900   assert(width < BitWidth && "Invalid APInt Truncate request");
901 }
902
903 // Sign extend to a new width.
904 void APInt::sext(unsigned width) {
905   assert(width > BitWidth && "Invalid APInt SignExtend request");
906 }
907
908 //  Zero extend to a new width.
909 void APInt::zext(unsigned width) {
910   assert(width > BitWidth && "Invalid APInt ZeroExtend request");
911 }
912
913 /// Arithmetic right-shift this APInt by shiftAmt.
914 /// @brief Arithmetic right-shift function.
915 APInt APInt::ashr(unsigned shiftAmt) const {
916   APInt API(*this);
917   if (API.isSingleWord())
918     API.VAL = 
919       (((int64_t(API.VAL) << (APINT_BITS_PER_WORD - API.BitWidth)) >> 
920           (APINT_BITS_PER_WORD - API.BitWidth)) >> shiftAmt) & 
921       (~uint64_t(0UL) >> (APINT_BITS_PER_WORD - API.BitWidth));
922   else {
923     if (shiftAmt >= API.BitWidth) {
924       memset(API.pVal, API[API.BitWidth-1] ? 1 : 0, (API.getNumWords()-1) * 8);
925       API.pVal[API.getNumWords() - 1] = 
926         ~uint64_t(0UL) >> 
927           (APINT_BITS_PER_WORD - API.BitWidth % APINT_BITS_PER_WORD);
928     } else {
929       unsigned i = 0;
930       for (; i < API.BitWidth - shiftAmt; ++i)
931         if (API[i+shiftAmt]) 
932           API.set(i);
933         else
934           API.clear(i);
935       for (; i < API.BitWidth; ++i)
936         if (API[API.BitWidth-1]) 
937           API.set(i);
938         else API.clear(i);
939     }
940   }
941   return API;
942 }
943
944 /// Logical right-shift this APInt by shiftAmt.
945 /// @brief Logical right-shift function.
946 APInt APInt::lshr(unsigned shiftAmt) const {
947   APInt API(*this);
948   if (API.isSingleWord())
949     API.VAL >>= shiftAmt;
950   else {
951     if (shiftAmt >= API.BitWidth)
952       memset(API.pVal, 0, API.getNumWords() * 8);
953     unsigned i = 0;
954     for (i = 0; i < API.BitWidth - shiftAmt; ++i)
955       if (API[i+shiftAmt]) API.set(i);
956       else API.clear(i);
957     for (; i < API.BitWidth; ++i)
958       API.clear(i);
959   }
960   return API;
961 }
962
963 /// Left-shift this APInt by shiftAmt.
964 /// @brief Left-shift function.
965 APInt APInt::shl(unsigned shiftAmt) const {
966   APInt API(*this);
967   if (API.isSingleWord())
968     API.VAL <<= shiftAmt;
969   else if (shiftAmt >= API.BitWidth)
970     memset(API.pVal, 0, API.getNumWords() * 8);
971   else {
972     if (unsigned offset = shiftAmt / APINT_BITS_PER_WORD) {
973       for (unsigned i = API.getNumWords() - 1; i > offset - 1; --i)
974         API.pVal[i] = API.pVal[i-offset];
975       memset(API.pVal, 0, offset * 8);
976     }
977     shiftAmt %= APINT_BITS_PER_WORD;
978     unsigned i;
979     for (i = API.getNumWords() - 1; i > 0; --i)
980       API.pVal[i] = (API.pVal[i] << shiftAmt) | 
981                     (API.pVal[i-1] >> (APINT_BITS_PER_WORD - shiftAmt));
982     API.pVal[i] <<= shiftAmt;
983   }
984   API.clearUnusedBits();
985   return API;
986 }
987
988 /// subMul - This function substracts x[len-1:0] * y from 
989 /// dest[offset+len-1:offset], and returns the most significant 
990 /// word of the product, minus the borrow-out from the subtraction.
991 static unsigned subMul(unsigned dest[], unsigned offset, 
992                         unsigned x[], unsigned len, unsigned y) {
993   uint64_t yl = (uint64_t) y & 0xffffffffL;
994   unsigned carry = 0;
995   unsigned j = 0;
996   do {
997     uint64_t prod = ((uint64_t) x[j] & 0xffffffffUL) * yl;
998     unsigned prod_low = (unsigned) prod;
999     unsigned prod_high = (unsigned) (prod >> 32);
1000     prod_low += carry;
1001     carry = (prod_low < carry ? 1 : 0) + prod_high;
1002     unsigned x_j = dest[offset+j];
1003     prod_low = x_j - prod_low;
1004     if (prod_low > x_j) ++carry;
1005     dest[offset+j] = prod_low;
1006   } while (++j < len);
1007   return carry;
1008 }
1009
1010 /// unitDiv - This function divides N by D, 
1011 /// and returns (remainder << 32) | quotient.
1012 /// Assumes (N >> 32) < D.
1013 static uint64_t unitDiv(uint64_t N, unsigned D) {
1014   uint64_t q, r;                   // q: quotient, r: remainder.
1015   uint64_t a1 = N >> 32;           // a1: high 32-bit part of N.
1016   uint64_t a0 = N & 0xffffffffL;   // a0: low 32-bit part of N
1017   if (a1 < ((D - a1 - (a0 >> 31)) & 0xffffffffL)) {
1018       q = N / D;
1019       r = N % D;
1020   }
1021   else {
1022     // Compute c1*2^32 + c0 = a1*2^32 + a0 - 2^31*d
1023     uint64_t c = N - ((uint64_t) D << 31);
1024     // Divide (c1*2^32 + c0) by d
1025     q = c / D;
1026     r = c % D;
1027     // Add 2^31 to quotient 
1028     q += 1 << 31;
1029   }
1030
1031   return (r << 32) | (q & 0xFFFFFFFFl);
1032 }
1033
1034 /// div - This is basically Knuth's formulation of the classical algorithm.
1035 /// Correspondance with Knuth's notation:
1036 /// Knuth's u[0:m+n] == zds[nx:0].
1037 /// Knuth's v[1:n] == y[ny-1:0]
1038 /// Knuth's n == ny.
1039 /// Knuth's m == nx-ny.
1040 /// Our nx == Knuth's m+n.
1041 /// Could be re-implemented using gmp's mpn_divrem:
1042 /// zds[nx] = mpn_divrem (&zds[ny], 0, zds, nx, y, ny).
1043 static void div(unsigned zds[], unsigned nx, unsigned y[], unsigned ny) {
1044   unsigned j = nx;
1045   do {                          // loop over digits of quotient
1046     // Knuth's j == our nx-j.
1047     // Knuth's u[j:j+n] == our zds[j:j-ny].
1048     unsigned qhat;  // treated as unsigned
1049     if (zds[j] == y[ny-1]) 
1050       qhat = -1U;  // 0xffffffff
1051     else {
1052       uint64_t w = (((uint64_t)(zds[j])) << 32) + 
1053                    ((uint64_t)zds[j-1] & 0xffffffffL);
1054       qhat = (unsigned) unitDiv(w, y[ny-1]);
1055     }
1056     if (qhat) {
1057       unsigned borrow = subMul(zds, j - ny, y, ny, qhat);
1058       unsigned save = zds[j];
1059       uint64_t num = ((uint64_t)save&0xffffffffL) - 
1060                      ((uint64_t)borrow&0xffffffffL);
1061       while (num) {
1062         qhat--;
1063         uint64_t carry = 0;
1064         for (unsigned i = 0;  i < ny; i++) {
1065           carry += ((uint64_t) zds[j-ny+i] & 0xffffffffL)
1066             + ((uint64_t) y[i] & 0xffffffffL);
1067           zds[j-ny+i] = (unsigned) carry;
1068           carry >>= 32;
1069         }
1070         zds[j] += carry;
1071         num = carry - 1;
1072       }
1073     }
1074     zds[j] = qhat;
1075   } while (--j >= ny);
1076 }
1077
1078 /// Unsigned divide this APInt by APInt RHS.
1079 /// @brief Unsigned division function for APInt.
1080 APInt APInt::udiv(const APInt& RHS) const {
1081   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1082
1083   // First, deal with the easy case
1084   if (isSingleWord()) {
1085     assert(RHS.VAL != 0 && "Divide by zero?");
1086     return APInt(BitWidth, VAL / RHS.VAL);
1087   }
1088
1089   // Make a temporary to hold the result
1090   APInt Result(*this);
1091
1092   // Get some facts about the LHS and RHS number of bits and words
1093   unsigned rhsBits = RHS.getActiveBits();
1094   unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
1095   assert(rhsWords && "Divided by zero???");
1096   unsigned lhsBits = Result.getActiveBits();
1097   unsigned lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
1098
1099   // Deal with some degenerate cases
1100   if (!lhsWords) 
1101     return Result; // 0 / X == 0
1102   else if (lhsWords < rhsWords || Result.ult(RHS))
1103     // X / Y with X < Y == 0
1104     memset(Result.pVal, 0, Result.getNumWords() * 8);
1105   else if (Result == RHS) {
1106     // X / X == 1
1107     memset(Result.pVal, 0, Result.getNumWords() * 8);
1108     Result.pVal[0] = 1;
1109   } else if (lhsWords == 1)
1110     // All high words are zero, just use native divide
1111     Result.pVal[0] /= RHS.pVal[0];
1112   else {
1113     // Compute it the hard way ..
1114     APInt X(BitWidth, 0);
1115     APInt Y(BitWidth, 0);
1116     unsigned nshift = 
1117       (APINT_BITS_PER_WORD - 1) - ((rhsBits - 1) % APINT_BITS_PER_WORD );
1118     if (nshift) {
1119       Y = APIntOps::shl(RHS, nshift);
1120       X = APIntOps::shl(Result, nshift);
1121       ++lhsWords;
1122     }
1123     div((unsigned*)X.pVal, lhsWords * 2 - 1, 
1124         (unsigned*)(Y.isSingleWord()? &Y.VAL : Y.pVal), rhsWords*2);
1125     memset(Result.pVal, 0, Result.getNumWords() * 8);
1126     memcpy(Result.pVal, X.pVal + rhsWords, (lhsWords - rhsWords) * 8);
1127   }
1128   return Result;
1129 }
1130
1131 /// Unsigned remainder operation on APInt.
1132 /// @brief Function for unsigned remainder operation.
1133 APInt APInt::urem(const APInt& RHS) const {
1134   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1135   if (isSingleWord()) {
1136     assert(RHS.VAL != 0 && "Remainder by zero?");
1137     return APInt(BitWidth, VAL % RHS.VAL);
1138   }
1139
1140   // Make a temporary to hold the result
1141   APInt Result(*this);
1142
1143   // Get some facts about the RHS
1144   unsigned rhsBits = RHS.getActiveBits();
1145   unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
1146   assert(rhsWords && "Performing remainder operation by zero ???");
1147
1148   // Get some facts about the LHS
1149   unsigned lhsBits = Result.getActiveBits();
1150   unsigned lhsWords = !lhsBits ? 0 : (Result.whichWord(lhsBits - 1) + 1);
1151
1152   // Check the degenerate cases
1153   if (lhsWords == 0)
1154     // 0 % Y == 0
1155     memset(Result.pVal, 0, Result.getNumWords() * 8);
1156   else if (lhsWords < rhsWords || Result.ult(RHS))
1157     // X % Y == X iff X < Y
1158     return Result;
1159   else if (Result == RHS)
1160     // X % X == 0;
1161     memset(Result.pVal, 0, Result.getNumWords() * 8);
1162   else if (lhsWords == 1) 
1163     // All high words are zero, just use native remainder
1164     Result.pVal[0] %=  RHS.pVal[0];
1165   else {
1166     // Do it the hard way
1167     APInt X((lhsWords+1)*APINT_BITS_PER_WORD, 0);
1168     APInt Y(rhsWords*APINT_BITS_PER_WORD, 0);
1169     unsigned nshift = 
1170       (APINT_BITS_PER_WORD - 1) - (rhsBits - 1) % APINT_BITS_PER_WORD;
1171     if (nshift) {
1172       APIntOps::shl(Y, nshift);
1173       APIntOps::shl(X, nshift);
1174     }
1175     div((unsigned*)X.pVal, rhsWords*2-1, 
1176         (unsigned*)(Y.isSingleWord()? &Y.VAL : Y.pVal), rhsWords*2);
1177     memset(Result.pVal, 0, Result.getNumWords() * 8);
1178     for (unsigned i = 0; i < rhsWords-1; ++i)
1179       Result.pVal[i] = (X.pVal[i] >> nshift) | 
1180                         (X.pVal[i+1] << (APINT_BITS_PER_WORD - nshift));
1181     Result.pVal[rhsWords-1] = X.pVal[rhsWords-1] >> nshift;
1182   }
1183   return Result;
1184 }
1185
1186 /// @brief Converts a char array into an integer.
1187 void APInt::fromString(unsigned numbits, const char *StrStart, unsigned slen, 
1188                        uint8_t radix) {
1189   assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1190          "Radix should be 2, 8, 10, or 16!");
1191   assert(StrStart && "String is null?");
1192   unsigned size = 0;
1193   // If the radix is a power of 2, read the input
1194   // from most significant to least significant.
1195   if ((radix & (radix - 1)) == 0) {
1196     unsigned nextBitPos = 0, bits_per_digit = radix / 8 + 2;
1197     uint64_t resDigit = 0;
1198     BitWidth = slen * bits_per_digit;
1199     if (getNumWords() > 1)
1200       assert((pVal = new uint64_t[getNumWords()]) && 
1201              "APInt memory allocation fails!");
1202     for (int i = slen - 1; i >= 0; --i) {
1203       uint64_t digit = StrStart[i] - '0';
1204       resDigit |= digit << nextBitPos;
1205       nextBitPos += bits_per_digit;
1206       if (nextBitPos >= APINT_BITS_PER_WORD) {
1207         if (isSingleWord()) {
1208           VAL = resDigit;
1209            break;
1210         }
1211         pVal[size++] = resDigit;
1212         nextBitPos -= APINT_BITS_PER_WORD;
1213         resDigit = digit >> (bits_per_digit - nextBitPos);
1214       }
1215     }
1216     if (!isSingleWord() && size <= getNumWords()) 
1217       pVal[size] = resDigit;
1218   } else {   // General case.  The radix is not a power of 2.
1219     // For 10-radix, the max value of 64-bit integer is 18446744073709551615,
1220     // and its digits number is 20.
1221     const unsigned chars_per_word = 20;
1222     if (slen < chars_per_word || 
1223         (slen == chars_per_word &&             // In case the value <= 2^64 - 1
1224          strcmp(StrStart, "18446744073709551615") <= 0)) {
1225       BitWidth = APINT_BITS_PER_WORD;
1226       VAL = strtoull(StrStart, 0, 10);
1227     } else { // In case the value > 2^64 - 1
1228       BitWidth = (slen / chars_per_word + 1) * APINT_BITS_PER_WORD;
1229       assert((pVal = new uint64_t[getNumWords()]) && 
1230              "APInt memory allocation fails!");
1231       memset(pVal, 0, getNumWords() * 8);
1232       unsigned str_pos = 0;
1233       while (str_pos < slen) {
1234         unsigned chunk = slen - str_pos;
1235         if (chunk > chars_per_word - 1)
1236           chunk = chars_per_word - 1;
1237         uint64_t resDigit = StrStart[str_pos++] - '0';
1238         uint64_t big_base = radix;
1239         while (--chunk > 0) {
1240           resDigit = resDigit * radix + StrStart[str_pos++] - '0';
1241           big_base *= radix;
1242         }
1243        
1244         uint64_t carry;
1245         if (!size)
1246           carry = resDigit;
1247         else {
1248           carry = mul_1(pVal, pVal, size, big_base);
1249           carry += add_1(pVal, pVal, size, resDigit);
1250         }
1251         
1252         if (carry) pVal[size++] = carry;
1253       }
1254     }
1255   }
1256 }
1257