Fix a comment.
[oota-llvm.git] / include / llvm / ADT / APInt.h
1 //===-- llvm/Support/APInt.h - For Arbitrary Precision Integer -*- C++ -*--===//
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 #ifndef LLVM_APINT_H
16 #define LLVM_APINT_H
17
18 #include "llvm/Support/DataTypes.h"
19 #include <cassert>
20 #include <string>
21
22 namespace llvm {
23
24 /// Forward declaration.
25 class APInt;
26 namespace APIntOps {
27   APInt udiv(const APInt& LHS, const APInt& RHS);
28   APInt urem(const APInt& LHS, const APInt& RHS);
29 }
30
31 //===----------------------------------------------------------------------===//
32 //                              APInt Class
33 //===----------------------------------------------------------------------===//
34
35 /// APInt - This class represents arbitrary precision constant integral values.
36 /// It is a functional replacement for common case unsigned integer type like 
37 /// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width 
38 /// integer sizes and large integer value types such as 3-bits, 15-bits, or more
39 /// than 64-bits of precision. APInt provides a variety of arithmetic operators 
40 /// and methods to manipulate integer values of any bit-width. It supports both
41 /// the typical integer arithmetic and comparison operations as well as bitwise
42 /// manipulation.
43 ///
44 /// The class has several invariants worth noting:
45 ///   * All bit, byte, and word positions are zero-based.
46 ///   * Once the bit width is set, it doesn't change except by the Truncate, 
47 ///     SignExtend, or ZeroExtend operations.
48 ///   * All binary operators must be on APInt instances of the same bit width.
49 ///     Attempting to use these operators on instances with different bit 
50 ///     widths will yield an assertion.
51 ///   * The value is stored canonically as an unsigned value. For operations
52 ///     where it makes a difference, there are both signed and unsigned variants
53 ///     of the operation. For example, sdiv and udiv. However, because the bit
54 ///     widths must be the same, operations such as Mul and Add produce the same
55 ///     results regardless of whether the values are interpreted as signed or
56 ///     not.
57 ///   * In general, the class tries to follow the style of computation that LLVM
58 ///     uses in its IR. This simplifies its use for LLVM.
59 ///
60 /// @brief Class for arbitrary precision integers.
61 class APInt {
62
63   uint32_t BitWidth;      ///< The number of bits in this APInt.
64
65   /// This union is used to store the integer value. When the
66   /// integer bit-width <= 64, it uses VAL; 
67   /// otherwise it uses the pVal.
68   union {
69     uint64_t VAL;    ///< Used to store the <= 64 bits integer value.
70     uint64_t *pVal;  ///< Used to store the >64 bits integer value.
71   };
72
73   /// This enum is just used to hold a constant we needed for APInt.
74   enum {
75     APINT_BITS_PER_WORD = sizeof(uint64_t) * 8,
76     APINT_WORD_SIZE = sizeof(uint64_t)
77   };
78
79   // Fast internal constructor
80   APInt(uint64_t* val, uint32_t bits) : BitWidth(bits), pVal(val) { }
81
82   /// @returns true if the number of bits <= 64, false otherwise.
83   /// @brief Determine if this APInt just has one word to store value.
84   inline bool isSingleWord() const { 
85     return BitWidth <= APINT_BITS_PER_WORD; 
86   }
87
88   /// @returns the word position for the specified bit position.
89   static inline uint32_t whichWord(uint32_t bitPosition) { 
90     return bitPosition / APINT_BITS_PER_WORD; 
91   }
92
93   /// @returns the bit position in a word for the specified bit position 
94   /// in APInt.
95   static inline uint32_t whichBit(uint32_t bitPosition) { 
96     return bitPosition % APINT_BITS_PER_WORD; 
97   }
98
99   /// @returns a uint64_t type integer with just bit position at
100   /// "whichBit(bitPosition)" setting, others zero.
101   static inline uint64_t maskBit(uint32_t bitPosition) { 
102     return 1ULL << whichBit(bitPosition); 
103   }
104
105   /// This method is used internally to clear the to "N" bits that are not used
106   /// by the APInt. This is needed after the most significant word is assigned 
107   /// a value to ensure that those bits are zero'd out.
108   /// @brief Clear high order bits
109   inline APInt& clearUnusedBits() {
110     // Compute how many bits are used in the final word
111     uint32_t wordBits = BitWidth % APINT_BITS_PER_WORD;
112     if (wordBits == 0)
113       // If all bits are used, we want to leave the value alone. This also
114       // avoids the undefined behavior of >> when the shfit is the same size as
115       // the word size (64).
116       return *this;
117
118     // Mask out the hight bits.
119     uint64_t mask = ~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - wordBits);
120     if (isSingleWord())
121       VAL &= mask;
122     else
123       pVal[getNumWords() - 1] &= mask;
124     return *this;
125   }
126
127   /// @returns the corresponding word for the specified bit position.
128   /// @brief Get the word corresponding to a bit position
129   inline uint64_t getWord(uint32_t bitPosition) const { 
130     return isSingleWord() ? VAL : pVal[whichWord(bitPosition)]; 
131   }
132
133   /// This is used by the constructors that take string arguments.
134   /// @brief Converts a char array into an APInt
135   void fromString(uint32_t numBits, const char *StrStart, uint32_t slen, 
136                   uint8_t radix);
137
138   /// This is used by the toString method to divide by the radix. It simply
139   /// provides a more convenient form of divide for internal use since KnuthDiv
140   /// has specific constraints on its inputs. If those constraints are not met
141   /// then it provides a simpler form of divide.
142   /// @brief An internal division function for dividing APInts.
143   static void divide(const APInt LHS, uint32_t lhsWords, 
144                      const APInt &RHS, uint32_t rhsWords,
145                      APInt *Quotient, APInt *Remainder);
146
147 #ifndef NDEBUG
148   /// @brief debug method
149   void dump() const;
150 #endif
151
152 public:
153   /// @brief Create a new APInt of numBits width, initialized as val.
154   APInt(uint32_t numBits, uint64_t val, bool isSigned = false);
155
156   /// Note that numWords can be smaller or larger than the corresponding bit
157   /// width but any extraneous bits will be dropped.
158   /// @brief Create a new APInt of numBits width, initialized as bigVal[].
159   APInt(uint32_t numBits, uint32_t numWords, uint64_t bigVal[]);
160
161   /// @brief Create a new APInt by translating the string represented 
162   /// integer value.
163   APInt(uint32_t numBits, const std::string& Val, uint8_t radix);
164
165   /// @brief Create a new APInt by translating the char array represented
166   /// integer value.
167   APInt(uint32_t numBits, const char StrStart[], uint32_t slen, uint8_t radix);
168
169   /// @brief Copy Constructor.
170   APInt(const APInt& API);
171
172   /// @brief Destructor.
173   ~APInt();
174
175   /// @brief Copy assignment operator. 
176   APInt& operator=(const APInt& RHS);
177
178   /// Assigns an integer value to the APInt.
179   /// @brief Assignment operator. 
180   APInt& operator=(uint64_t RHS);
181
182   /// Increments the APInt by one.
183   /// @brief Postfix increment operator.
184   inline const APInt operator++(int) {
185     APInt API(*this);
186     ++(*this);
187     return API;
188   }
189
190   /// Increments the APInt by one.
191   /// @brief Prefix increment operator.
192   APInt& operator++();
193
194   /// Decrements the APInt by one.
195   /// @brief Postfix decrement operator. 
196   inline const APInt operator--(int) {
197     APInt API(*this);
198     --(*this);
199     return API;
200   }
201
202   /// Decrements the APInt by one.
203   /// @brief Prefix decrement operator. 
204   APInt& operator--();
205
206   /// Performs bitwise AND operation on this APInt and the given APInt& RHS, 
207   /// assigns the result to this APInt.
208   /// @brief Bitwise AND assignment operator. 
209   APInt& operator&=(const APInt& RHS);
210
211   /// Performs bitwise OR operation on this APInt and the given APInt& RHS, 
212   /// assigns the result to this APInt.
213   /// @brief Bitwise OR assignment operator. 
214   APInt& operator|=(const APInt& RHS);
215
216   /// Performs bitwise XOR operation on this APInt and the given APInt& RHS, 
217   /// assigns the result to this APInt.
218   /// @brief Bitwise XOR assignment operator. 
219   APInt& operator^=(const APInt& RHS);
220
221   /// Performs a bitwise complement operation on this APInt.
222   /// @brief Bitwise complement operator. 
223   APInt operator~() const;
224
225   /// Multiplies this APInt by the  given APInt& RHS and 
226   /// assigns the result to this APInt.
227   /// @brief Multiplication assignment operator. 
228   APInt& operator*=(const APInt& RHS);
229
230   /// Adds this APInt by the given APInt& RHS and 
231   /// assigns the result to this APInt.
232   /// @brief Addition assignment operator. 
233   APInt& operator+=(const APInt& RHS);
234
235   /// Subtracts this APInt by the given APInt &RHS and 
236   /// assigns the result to this APInt.
237   /// @brief Subtraction assignment operator. 
238   APInt& operator-=(const APInt& RHS);
239
240   /// Performs bitwise AND operation on this APInt and 
241   /// the given APInt& RHS.
242   /// @brief Bitwise AND operator. 
243   APInt operator&(const APInt& RHS) const;
244   APInt And(const APInt& RHS) const {
245     return this->operator&(RHS);
246   }
247
248   /// Performs bitwise OR operation on this APInt and the given APInt& RHS.
249   /// @brief Bitwise OR operator. 
250   APInt operator|(const APInt& RHS) const;
251   APInt Or(const APInt& RHS) const {
252     return this->operator|(RHS);
253   }
254
255   /// Performs bitwise XOR operation on this APInt and the given APInt& RHS.
256   /// @brief Bitwise XOR operator. 
257   APInt operator^(const APInt& RHS) const;
258   APInt Xor(const APInt& RHS) const {
259     return this->operator^(RHS);
260   }
261
262   /// Performs logical negation operation on this APInt.
263   /// @brief Logical negation operator. 
264   bool operator !() const;
265
266   /// Multiplies this APInt by the given APInt& RHS.
267   /// @brief Multiplication operator. 
268   APInt operator*(const APInt& RHS) const;
269
270   /// Adds this APInt by the given APInt& RHS.
271   /// @brief Addition operator. 
272   APInt operator+(const APInt& RHS) const;
273   APInt operator+(uint64_t RHS) const {
274     return (*this) + APInt(BitWidth, RHS);
275   }
276
277
278   /// Subtracts this APInt by the given APInt& RHS
279   /// @brief Subtraction operator. 
280   APInt operator-(const APInt& RHS) const;
281   APInt operator-(uint64_t RHS) const {
282     return (*this) - APInt(BitWidth, RHS);
283   }
284
285   /// @brief Unary negation operator
286   inline APInt operator-() const {
287     return APInt(BitWidth, 0) - (*this);
288   }
289
290   /// @brief Array-indexing support.
291   bool operator[](uint32_t bitPosition) const;
292
293   /// Compare this APInt with the given APInt& RHS 
294   /// for the validity of the equality relationship.
295   /// @brief Equality operator. 
296   bool operator==(const APInt& RHS) const;
297
298   /// Compare this APInt with the given uint64_t value
299   /// for the validity of the equality relationship.
300   /// @brief Equality operator.
301   bool operator==(uint64_t Val) const;
302
303   /// Compare this APInt with the given APInt& RHS 
304   /// for the validity of the inequality relationship.
305   /// @brief Inequality operator. 
306   inline bool operator!=(const APInt& RHS) const {
307     return !((*this) == RHS);
308   }
309
310   /// Compare this APInt with the given uint64_t value 
311   /// for the validity of the inequality relationship.
312   /// @brief Inequality operator. 
313   inline bool operator!=(uint64_t Val) const {
314     return !((*this) == Val);
315   }
316   
317   /// @brief Equality comparison
318   bool eq(const APInt &RHS) const {
319     return (*this) == RHS; 
320   }
321
322   /// @brief Inequality comparison
323   bool ne(const APInt &RHS) const {
324     return !((*this) == RHS);
325   }
326
327   /// @brief Unsigned less than comparison
328   bool ult(const APInt& RHS) const;
329
330   /// @brief Signed less than comparison
331   bool slt(const APInt& RHS) const;
332
333   /// @brief Unsigned less or equal comparison
334   bool ule(const APInt& RHS) const {
335     return ult(RHS) || eq(RHS);
336   }
337
338   /// @brief Signed less or equal comparison
339   bool sle(const APInt& RHS) const {
340     return slt(RHS) || eq(RHS);
341   }
342
343   /// @brief Unsigned greather than comparison
344   bool ugt(const APInt& RHS) const {
345     return !ult(RHS) && !eq(RHS);
346   }
347
348   /// @brief Signed greather than comparison
349   bool sgt(const APInt& RHS) const {
350     return !slt(RHS) && !eq(RHS);
351   }
352
353   /// @brief Unsigned greater or equal comparison
354   bool uge(const APInt& RHS) const {
355     return !ult(RHS);
356   }
357
358   /// @brief Signed greather or equal comparison
359   bool sge(const APInt& RHS) const {
360     return !slt(RHS);
361   }
362
363   /// This just tests the high bit of this APInt to determine if it is negative.
364   /// @returns true if this APInt is negative, false otherwise
365   /// @brief Determine sign of this APInt.
366   bool isNegative() const {
367     return (*this)[BitWidth - 1];
368   }
369
370   /// This just tests the high bit of the APInt to determine if the value is
371   /// positove or not.
372   /// @brief Determine if this APInt Value is positive.
373   bool isPositive() const {
374     return !isNegative();
375   }
376
377   /// This just tests if the value of this APInt is strictly positive (> 0).
378   /// @brief Determine if this APInt Value is strictly positive.
379   inline bool isStrictlyPositive() const {
380     return isPositive() && (*this) != 0;
381   }
382
383   /// Arithmetic right-shift this APInt by shiftAmt.
384   /// @brief Arithmetic right-shift function.
385   APInt ashr(uint32_t shiftAmt) const;
386
387   /// Logical right-shift this APInt by shiftAmt.
388   /// @brief Logical right-shift function.
389   APInt lshr(uint32_t shiftAmt) const;
390
391   /// Left-shift this APInt by shiftAmt.
392   /// @brief Left-shift function.
393   APInt shl(uint32_t shiftAmt) const;
394
395   /// Left-shift this APInt by shiftAmt and
396   /// assigns the result to this APInt.
397   /// @brief Lef-shift assignment function.
398   inline APInt& operator<<=(uint32_t shiftAmt) {
399     *this = shl(shiftAmt);
400     return *this;
401   }
402
403   /// Signed divide this APInt by APInt RHS.
404   /// @brief Signed division function for APInt.
405   inline APInt sdiv(const APInt& RHS) const {
406     bool isNegativeLHS = isNegative();
407     bool isNegativeRHS = RHS.isNegative();
408     APInt Result = APIntOps::udiv(
409         isNegativeLHS ? -(*this) : (*this), isNegativeRHS ? -RHS : RHS);
410     return isNegativeLHS != isNegativeRHS ? -Result : Result;
411   }
412
413   /// Unsigned divide this APInt by APInt RHS.
414   /// @brief Unsigned division function for APInt.
415   APInt udiv(const APInt& RHS) const;
416
417   /// Signed remainder operation on APInt.
418   /// @brief Function for signed remainder operation.
419   inline APInt srem(const APInt& RHS) const {
420     bool isNegativeLHS = isNegative();
421     bool isNegativeRHS = RHS.isNegative();
422     APInt Result = APIntOps::urem(
423         isNegativeLHS ? -(*this) : (*this), isNegativeRHS ? -RHS : RHS);
424     return isNegativeLHS ? -Result : Result;
425   }
426
427   /// Unsigned remainder operation on APInt.
428   /// @brief Function for unsigned remainder operation.
429   APInt urem(const APInt& RHS) const;
430
431   /// Truncate the APInt to a specified width. It is an error to specify a width
432   /// that is greater than or equal to the current width. 
433   /// @brief Truncate to new width.
434   APInt &trunc(uint32_t width);
435
436   /// This operation sign extends the APInt to a new width. If the high order
437   /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
438   /// It is an error to specify a width that is less than or equal to the 
439   /// current width.
440   /// @brief Sign extend to a new width.
441   APInt &sext(uint32_t width);
442
443   /// This operation zero extends the APInt to a new width. Thie high order bits
444   /// are filled with 0 bits.  It is an error to specify a width that is less 
445   /// than or equal to the current width.
446   /// @brief Zero extend to a new width.
447   APInt &zext(uint32_t width);
448
449   /// Make this APInt have the bit width given by \p width. The value is sign
450   /// extended, truncated, or left alone to make it that width.
451   /// @brief Sign extend or truncate to width
452   APInt &sextOrTrunc(uint32_t width);
453
454   /// Make this APInt have the bit width given by \p width. The value is zero
455   /// extended, truncated, or left alone to make it that width.
456   /// @brief Zero extend or truncate to width
457   APInt &zextOrTrunc(uint32_t width);
458
459   /// This is a help function for convenience. If the given \p width equals to
460   /// this APInt's BitWidth, just return this APInt, otherwise, just zero 
461   /// extend it.
462   inline APInt &zextOrCopy(uint32_t width) {
463     if (width == BitWidth)
464       return *this;
465     return zext(width);
466   }
467
468   /// @brief Set every bit to 1.
469   APInt& set();
470
471   /// Set the given bit to 1 whose position is given as "bitPosition".
472   /// @brief Set a given bit to 1.
473   APInt& set(uint32_t bitPosition);
474
475   /// @brief Set every bit to 0.
476   APInt& clear();
477
478   /// Set the given bit to 0 whose position is given as "bitPosition".
479   /// @brief Set a given bit to 0.
480   APInt& clear(uint32_t bitPosition);
481
482   /// @brief Toggle every bit to its opposite value.
483   APInt& flip();
484
485   /// Toggle a given bit to its opposite value whose position is given 
486   /// as "bitPosition".
487   /// @brief Toggles a given bit to its opposite value.
488   APInt& flip(uint32_t bitPosition);
489
490   inline void setWordToValue(uint32_t idx, uint64_t Val) {
491     assert(idx < getNumWords() && "Invalid word array index");
492     if (isSingleWord())
493       VAL = Val;
494     else
495       pVal[idx] = Val;
496   }
497
498   /// This function returns the number of active bits which is defined as the
499   /// bit width minus the number of leading zeros. This is used in several
500   /// computations to see how "wide" the value is.
501   /// @brief Compute the number of active bits in the value
502   inline uint32_t getActiveBits() const {
503     return BitWidth - countLeadingZeros();
504   }
505
506   /// This function returns the number of active words in the value of this
507   /// APInt. This is used in conjunction with getActiveData to extract the raw
508   /// value of the APInt.
509   inline uint32_t getActiveWords() const {
510     return whichWord(getActiveBits()-1) + 1;
511   }
512
513   /// Here one word's bitwidth equals to that of uint64_t.
514   /// @returns the number of words to hold the integer value of this APInt.
515   /// @brief Get the number of words.
516   inline uint32_t getNumWords() const {
517     return (BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
518   }
519
520   /// This function returns a pointer to the internal storage of the APInt. 
521   /// This is useful for writing out the APInt in binary form without any
522   /// conversions.
523   inline const uint64_t* getRawData() const {
524     if (isSingleWord())
525       return &VAL;
526     return &pVal[0];
527   }
528
529   /// Computes the minimum bit width for this APInt while considering it to be
530   /// a signed (and probably negative) value. If the value is not negative, 
531   /// this function returns the same value as getActiveBits(). Otherwise, it
532   /// returns the smallest bit width that will retain the negative value. For
533   /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
534   /// for -1, this function will always return 1.
535   /// @brief Get the minimum bit size for this signed APInt 
536   inline uint32_t getMinSignedBits() const {
537     if (isNegative())
538       return BitWidth - countLeadingOnes() + 1;
539     return getActiveBits();
540   }
541
542   /// This method attempts to return the value of this APInt as a zero extended
543   /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
544   /// uint64_t. Otherwise an assertion will result.
545   /// @brief Get zero extended value
546   inline uint64_t getZExtValue() const {
547     if (isSingleWord())
548       return VAL;
549     assert(getActiveBits() <= 64 && "Too many bits for uint64_t");
550     return pVal[0];
551   }
552
553   /// This method attempts to return the value of this APInt as a sign extended
554   /// int64_t. The bit width must be <= 64 or the value must fit within an
555   /// int64_t. Otherwise an assertion will result.
556   /// @brief Get sign extended value
557   inline int64_t getSExtValue() const {
558     if (isSingleWord())
559       return int64_t(VAL << (APINT_BITS_PER_WORD - BitWidth)) >> 
560                      (APINT_BITS_PER_WORD - BitWidth);
561     assert(getActiveBits() <= 64 && "Too many bits for int64_t");
562     return int64_t(pVal[0]);
563   }
564
565   /// @brief Gets maximum unsigned value of APInt for specific bit width.
566   static APInt getMaxValue(uint32_t numBits) {
567     return APInt(numBits, 0).set();
568   }
569
570   /// @brief Gets maximum signed value of APInt for a specific bit width.
571   static APInt getSignedMaxValue(uint32_t numBits) {
572     return APInt(numBits, 0).set().clear(numBits - 1);
573   }
574
575   /// @brief Gets minimum unsigned value of APInt for a specific bit width.
576   static APInt getMinValue(uint32_t numBits) {
577     return APInt(numBits, 0);
578   }
579
580   /// @brief Gets minimum signed value of APInt for a specific bit width.
581   static APInt getSignedMinValue(uint32_t numBits) {
582     return APInt(numBits, 0).set(numBits - 1);
583   }
584
585   /// getSignBit - This is just a wrapper function of getSignedMinValue(), and
586   /// it helps code readability when we want to get a SignBit.
587   /// @brief Get the SignBit for a specific bit width.
588   inline static APInt getSignBit(uint32_t BitWidth) {
589     return getSignedMinValue(BitWidth);
590   }
591
592   /// @returns the all-ones value for an APInt of the specified bit-width.
593   /// @brief Get the all-ones value.
594   static APInt getAllOnesValue(uint32_t numBits) {
595     return APInt(numBits, 0).set();
596   }
597
598   /// @returns the '0' value for an APInt of the specified bit-width.
599   /// @brief Get the '0' value.
600   static APInt getNullValue(uint32_t numBits) {
601     return APInt(numBits, 0);
602   }
603
604   /// The hash value is computed as the sum of the words and the bit width.
605   /// @returns A hash value computed from the sum of the APInt words.
606   /// @brief Get a hash value based on this APInt
607   uint64_t getHashValue() const;
608
609   /// This converts the APInt to a boolean valy as a test against zero.
610   /// @brief Boolean conversion function. 
611   inline bool getBoolValue() const {
612     return countLeadingZeros() != BitWidth;
613   }
614
615   /// This checks to see if the value has all bits of the APInt are set or not.
616   /// @brief Determine if all bits are set
617   inline bool isAllOnesValue() const {
618     return countPopulation() == BitWidth;
619   }
620
621   /// This checks to see if the value of this APInt is the maximum unsigned
622   /// value for the APInt's bit width.
623   /// @brief Determine if this is the largest unsigned value.
624   bool isMaxValue() const {
625     return countPopulation() == BitWidth;
626   }
627
628   /// This checks to see if the value of this APInt is the maximum signed
629   /// value for the APInt's bit width.
630   /// @brief Determine if this is the largest signed value.
631   bool isMaxSignedValue() const {
632     return BitWidth == 1 ? VAL == 0 :
633                           !isNegative() && countPopulation() == BitWidth - 1;
634   }
635
636   /// This checks to see if the value of this APInt is the minimum unsigned
637   /// value for the APInt's bit width.
638   /// @brief Determine if this is the smallest unsigned value.
639   bool isMinValue() const {
640     return countPopulation() == 0;
641   }
642
643   /// This checks to see if the value of this APInt is the minimum signed
644   /// value for the APInt's bit width.
645   /// @brief Determine if this is the smallest signed value.
646   bool isMinSignedValue() const {
647     return BitWidth == 1 ? VAL == 1 :
648                            isNegative() && countPopulation() == 1;
649   }
650
651   /// This is used internally to convert an APInt to a string.
652   /// @brief Converts an APInt to a std::string
653   std::string toString(uint8_t radix, bool wantSigned) const;
654
655   /// Considers the APInt to be unsigned and converts it into a string in the
656   /// radix given. The radix can be 2, 8, 10 or 16.
657   /// @returns a character interpretation of the APInt
658   /// @brief Convert unsigned APInt to string representation.
659   inline std::string toString(uint8_t radix = 10) const {
660     return toString(radix, false);
661   }
662
663   /// Considers the APInt to be unsigned and converts it into a string in the
664   /// radix given. The radix can be 2, 8, 10 or 16.
665   /// @returns a character interpretation of the APInt
666   /// @brief Convert unsigned APInt to string representation.
667   inline std::string toStringSigned(uint8_t radix = 10) const {
668     return toString(radix, true);
669   }
670
671   /// Get an APInt with the same BitWidth as this APInt, just zero mask
672   /// the low bits and right shift to the least significant bit.
673   /// @returns the high "numBits" bits of this APInt.
674   APInt getHiBits(uint32_t numBits) const;
675
676   /// Get an APInt with the same BitWidth as this APInt, just zero mask
677   /// the high bits.
678   /// @returns the low "numBits" bits of this APInt.
679   APInt getLoBits(uint32_t numBits) const;
680
681   /// @returns true if the argument APInt value is a power of two > 0.
682   bool isPowerOf2() const; 
683
684   /// countLeadingZeros - This function is an APInt version of the
685   /// countLeadingZeros_{32,64} functions in MathExtras.h. It counts the number
686   /// of zeros from the most significant bit to the first one bit.
687   /// @returns getNumWords() * APINT_BITS_PER_WORD if the value is zero.
688   /// @returns the number of zeros from the most significant bit to the first
689   /// one bits.
690   /// @brief Count the number of leading one bits.
691   uint32_t countLeadingZeros() const;
692
693   /// countLeadingOnes - This function counts the number of contiguous 1 bits
694   /// in the high order bits. The count stops when the first 0 bit is reached.
695   /// @returns 0 if the high order bit is not set
696   /// @returns the number of 1 bits from the most significant to the least
697   /// @brief Count the number of leading one bits.
698   uint32_t countLeadingOnes() const;
699
700   /// countTrailingZeros - This function is an APInt version of the 
701   /// countTrailingZoers_{32,64} functions in MathExtras.h. It counts 
702   /// the number of zeros from the least significant bit to the first one bit.
703   /// @returns getNumWords() * APINT_BITS_PER_WORD if the value is zero.
704   /// @returns the number of zeros from the least significant bit to the first
705   /// one bit.
706   /// @brief Count the number of trailing zero bits.
707   uint32_t countTrailingZeros() const;
708
709   /// countPopulation - This function is an APInt version of the
710   /// countPopulation_{32,64} functions in MathExtras.h. It counts the number
711   /// of 1 bits in the APInt value. 
712   /// @returns 0 if the value is zero.
713   /// @returns the number of set bits.
714   /// @brief Count the number of bits set.
715   uint32_t countPopulation() const; 
716
717   /// @returns the total number of bits.
718   inline uint32_t getBitWidth() const { 
719     return BitWidth; 
720   }
721
722   /// @brief Check if this APInt has a N-bits integer value.
723   inline bool isIntN(uint32_t N) const {
724     assert(N && "N == 0 ???");
725     if (isSingleWord()) {
726       return VAL == (VAL & (~0ULL >> (64 - N)));
727     } else {
728       APInt Tmp(N, getNumWords(), pVal);
729       return Tmp == (*this);
730     }
731   }
732
733   /// @returns a byte-swapped representation of this APInt Value.
734   APInt byteSwap() const;
735
736   /// @returns the floor log base 2 of this APInt.
737   inline uint32_t logBase2() const {
738     return BitWidth - 1 - countLeadingZeros();
739   }
740
741   /// @brief Converts this APInt to a double value.
742   double roundToDouble(bool isSigned) const;
743
744   /// @brief Converts this unsigned APInt to a double value.
745   double roundToDouble() const {
746     return roundToDouble(false);
747   }
748
749   /// @brief Converts this signed APInt to a double value.
750   double signedRoundToDouble() const {
751     return roundToDouble(true);
752   }
753
754   /// The conversion does not do a translation from integer to double, it just
755   /// re-interprets the bits as a double. Note that it is valid to do this on
756   /// any bit width. Exactly 64 bits will be translated.
757   /// @brief Converts APInt bits to a double
758   double bitsToDouble() const {
759     union {
760       uint64_t I;
761       double D;
762     } T;
763     T.I = (isSingleWord() ? VAL : pVal[0]);
764     return T.D;
765   }
766
767   /// The conversion does not do a translation from integer to float, it just
768   /// re-interprets the bits as a float. Note that it is valid to do this on
769   /// any bit width. Exactly 32 bits will be translated.
770   /// @brief Converts APInt bits to a double
771   float bitsToFloat() const {
772     union {
773       uint32_t I;
774       float F;
775     } T;
776     T.I = uint32_t((isSingleWord() ? VAL : pVal[0]));
777     return T.F;
778   }
779
780   /// The conversion does not do a translation from double to integer, it just
781   /// re-interprets the bits of the double. Note that it is valid to do this on
782   /// any bit width but bits from V may get truncated.
783   /// @brief Converts a double to APInt bits.
784   APInt& doubleToBits(double V) {
785     union {
786       uint64_t I;
787       double D;
788     } T;
789     T.D = V;
790     if (isSingleWord())
791       VAL = T.I;
792     else
793       pVal[0] = T.I;
794     return clearUnusedBits();
795   }
796
797   /// The conversion does not do a translation from float to integer, it just
798   /// re-interprets the bits of the float. Note that it is valid to do this on
799   /// any bit width but bits from V may get truncated.
800   /// @brief Converts a float to APInt bits.
801   APInt& floatToBits(float V) {
802     union {
803       uint32_t I;
804       float F;
805     } T;
806     T.F = V;
807     if (isSingleWord())
808       VAL = T.I;
809     else
810       pVal[0] = T.I;
811     return clearUnusedBits();
812   }
813
814   /// @brief Compute the square root
815   APInt sqrt() const;
816
817   /// If *this is < 0 then return -(*this), otherwise *this;
818   /// @brief Get the absolute value;
819   APInt abs() const {
820     if (isNegative())
821       return -(*this);
822     return *this;
823   }
824 };
825
826 inline bool operator==(uint64_t V1, const APInt& V2) {
827   return V2 == V1;
828 }
829
830 inline bool operator!=(uint64_t V1, const APInt& V2) {
831   return V2 != V1;
832 }
833
834 namespace APIntOps {
835
836 /// @brief Determine the smaller of two APInts considered to be signed.
837 inline APInt smin(const APInt &A, const APInt &B) {
838   return A.slt(B) ? A : B;
839 }
840
841 /// @brief Determine the larger of two APInts considered to be signed.
842 inline APInt smax(const APInt &A, const APInt &B) {
843   return A.sgt(B) ? A : B;
844 }
845
846 /// @brief Determine the smaller of two APInts considered to be signed.
847 inline APInt umin(const APInt &A, const APInt &B) {
848   return A.ult(B) ? A : B;
849 }
850
851 /// @brief Determine the larger of two APInts considered to be unsigned.
852 inline APInt umax(const APInt &A, const APInt &B) {
853   return A.ugt(B) ? A : B;
854 }
855
856 /// @brief Check if the specified APInt has a N-bits integer value.
857 inline bool isIntN(uint32_t N, const APInt& APIVal) {
858   return APIVal.isIntN(N);
859 }
860
861 /// @returns true if the argument APInt value is a sequence of ones
862 /// starting at the least significant bit with the remainder zero.
863 inline const bool isMask(uint32_t numBits, const APInt& APIVal) {
864   return APIVal.getBoolValue() && ((APIVal + APInt(numBits,1)) & APIVal) == 0;
865 }
866
867 /// @returns true if the argument APInt value contains a sequence of ones
868 /// with the remainder zero.
869 inline const bool isShiftedMask(uint32_t numBits, const APInt& APIVal) {
870   return isMask(numBits, (APIVal - APInt(numBits,1)) | APIVal);
871 }
872
873 /// @returns a byte-swapped representation of the specified APInt Value.
874 inline APInt byteSwap(const APInt& APIVal) {
875   return APIVal.byteSwap();
876 }
877
878 /// @returns the floor log base 2 of the specified APInt value.
879 inline uint32_t logBase2(const APInt& APIVal) {
880   return APIVal.logBase2(); 
881 }
882
883 /// GreatestCommonDivisor - This function returns the greatest common
884 /// divisor of the two APInt values using Enclid's algorithm.
885 /// @returns the greatest common divisor of Val1 and Val2
886 /// @brief Compute GCD of two APInt values.
887 APInt GreatestCommonDivisor(const APInt& Val1, const APInt& Val2);
888
889 /// Treats the APInt as an unsigned value for conversion purposes.
890 /// @brief Converts the given APInt to a double value.
891 inline double RoundAPIntToDouble(const APInt& APIVal) {
892   return APIVal.roundToDouble();
893 }
894
895 /// Treats the APInt as a signed value for conversion purposes.
896 /// @brief Converts the given APInt to a double value.
897 inline double RoundSignedAPIntToDouble(const APInt& APIVal) {
898   return APIVal.signedRoundToDouble();
899 }
900
901 /// @brief Converts the given APInt to a float vlalue.
902 inline float RoundAPIntToFloat(const APInt& APIVal) {
903   return float(RoundAPIntToDouble(APIVal));
904 }
905
906 /// Treast the APInt as a signed value for conversion purposes.
907 /// @brief Converts the given APInt to a float value.
908 inline float RoundSignedAPIntToFloat(const APInt& APIVal) {
909   return float(APIVal.signedRoundToDouble());
910 }
911
912 /// RoundDoubleToAPInt - This function convert a double value to an APInt value.
913 /// @brief Converts the given double value into a APInt.
914 APInt RoundDoubleToAPInt(double Double, uint32_t width);
915
916 /// RoundFloatToAPInt - Converts a float value into an APInt value.
917 /// @brief Converts a float value into a APInt.
918 inline APInt RoundFloatToAPInt(float Float, uint32_t width) {
919   return RoundDoubleToAPInt(double(Float), width);
920 }
921
922 /// Arithmetic right-shift the APInt by shiftAmt.
923 /// @brief Arithmetic right-shift function.
924 inline APInt ashr(const APInt& LHS, uint32_t shiftAmt) {
925   return LHS.ashr(shiftAmt);
926 }
927
928 /// Logical right-shift the APInt by shiftAmt.
929 /// @brief Logical right-shift function.
930 inline APInt lshr(const APInt& LHS, uint32_t shiftAmt) {
931   return LHS.lshr(shiftAmt);
932 }
933
934 /// Left-shift the APInt by shiftAmt.
935 /// @brief Left-shift function.
936 inline APInt shl(const APInt& LHS, uint32_t shiftAmt) {
937   return LHS.shl(shiftAmt);
938 }
939
940 /// Signed divide APInt LHS by APInt RHS.
941 /// @brief Signed division function for APInt.
942 inline APInt sdiv(const APInt& LHS, const APInt& RHS) {
943   return LHS.sdiv(RHS);
944 }
945
946 /// Unsigned divide APInt LHS by APInt RHS.
947 /// @brief Unsigned division function for APInt.
948 inline APInt udiv(const APInt& LHS, const APInt& RHS) {
949   return LHS.udiv(RHS);
950 }
951
952 /// Signed remainder operation on APInt.
953 /// @brief Function for signed remainder operation.
954 inline APInt srem(const APInt& LHS, const APInt& RHS) {
955   return LHS.srem(RHS);
956 }
957
958 /// Unsigned remainder operation on APInt.
959 /// @brief Function for unsigned remainder operation.
960 inline APInt urem(const APInt& LHS, const APInt& RHS) {
961   return LHS.urem(RHS);
962 }
963
964 /// Performs multiplication on APInt values.
965 /// @brief Function for multiplication operation.
966 inline APInt mul(const APInt& LHS, const APInt& RHS) {
967   return LHS * RHS;
968 }
969
970 /// Performs addition on APInt values.
971 /// @brief Function for addition operation.
972 inline APInt add(const APInt& LHS, const APInt& RHS) {
973   return LHS + RHS;
974 }
975
976 /// Performs subtraction on APInt values.
977 /// @brief Function for subtraction operation.
978 inline APInt sub(const APInt& LHS, const APInt& RHS) {
979   return LHS - RHS;
980 }
981
982 /// Performs bitwise AND operation on APInt LHS and 
983 /// APInt RHS.
984 /// @brief Bitwise AND function for APInt.
985 inline APInt And(const APInt& LHS, const APInt& RHS) {
986   return LHS & RHS;
987 }
988
989 /// Performs bitwise OR operation on APInt LHS and APInt RHS.
990 /// @brief Bitwise OR function for APInt. 
991 inline APInt Or(const APInt& LHS, const APInt& RHS) {
992   return LHS | RHS;
993 }
994
995 /// Performs bitwise XOR operation on APInt.
996 /// @brief Bitwise XOR function for APInt.
997 inline APInt Xor(const APInt& LHS, const APInt& RHS) {
998   return LHS ^ RHS;
999
1000
1001 /// Performs a bitwise complement operation on APInt.
1002 /// @brief Bitwise complement function. 
1003 inline APInt Not(const APInt& APIVal) {
1004   return ~APIVal;
1005 }
1006
1007 } // End of APIntOps namespace
1008
1009 } // End of llvm namespace
1010
1011 #endif