In the getBitsSet function, don't optimize for a common case that is
[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 and operations on them.
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 //===----------------------------------------------------------------------===//
25 //                              APInt Class
26 //===----------------------------------------------------------------------===//
27
28 /// APInt - This class represents arbitrary precision constant integral values.
29 /// It is a functional replacement for common case unsigned integer type like 
30 /// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width 
31 /// integer sizes and large integer value types such as 3-bits, 15-bits, or more
32 /// than 64-bits of precision. APInt provides a variety of arithmetic operators 
33 /// and methods to manipulate integer values of any bit-width. It supports both
34 /// the typical integer arithmetic and comparison operations as well as bitwise
35 /// manipulation.
36 ///
37 /// The class has several invariants worth noting:
38 ///   * All bit, byte, and word positions are zero-based.
39 ///   * Once the bit width is set, it doesn't change except by the Truncate, 
40 ///     SignExtend, or ZeroExtend operations.
41 ///   * All binary operators must be on APInt instances of the same bit width.
42 ///     Attempting to use these operators on instances with different bit 
43 ///     widths will yield an assertion.
44 ///   * The value is stored canonically as an unsigned value. For operations
45 ///     where it makes a difference, there are both signed and unsigned variants
46 ///     of the operation. For example, sdiv and udiv. However, because the bit
47 ///     widths must be the same, operations such as Mul and Add produce the same
48 ///     results regardless of whether the values are interpreted as signed or
49 ///     not.
50 ///   * In general, the class tries to follow the style of computation that LLVM
51 ///     uses in its IR. This simplifies its use for LLVM.
52 ///
53 /// @brief Class for arbitrary precision integers.
54 class APInt {
55
56   uint32_t BitWidth;      ///< The number of bits in this APInt.
57
58   /// This union is used to store the integer value. When the
59   /// integer bit-width <= 64, it uses VAL, otherwise it uses pVal.
60   union {
61     uint64_t VAL;    ///< Used to store the <= 64 bits integer value.
62     uint64_t *pVal;  ///< Used to store the >64 bits integer value.
63   };
64
65   /// This enum is used to hold the constants we needed for APInt.
66   enum {
67     APINT_BITS_PER_WORD = sizeof(uint64_t) * 8, ///< Bits in a word
68     APINT_WORD_SIZE = sizeof(uint64_t)          ///< Byte size of a word
69   };
70
71   /// This constructor is used only internally for speed of construction of
72   /// temporaries. It is unsafe for general use so it is not public.
73   /// @brief Fast internal constructor
74   APInt(uint64_t* val, uint32_t bits) : BitWidth(bits), pVal(val) { }
75
76   /// @returns true if the number of bits <= 64, false otherwise.
77   /// @brief Determine if this APInt just has one word to store value.
78   inline bool isSingleWord() const { 
79     return BitWidth <= APINT_BITS_PER_WORD; 
80   }
81
82   /// @returns the word position for the specified bit position.
83   /// @brief Determine which word a bit is in.
84   static inline uint32_t whichWord(uint32_t bitPosition) { 
85     return bitPosition / APINT_BITS_PER_WORD; 
86   }
87
88   /// @returns the bit position in a word for the specified bit position 
89   /// in the APInt.
90   /// @brief Determine which bit in a word a bit is in.
91   static inline uint32_t whichBit(uint32_t bitPosition) { 
92     return bitPosition % APINT_BITS_PER_WORD; 
93   }
94
95   /// This method generates and returns a uint64_t (word) mask for a single 
96   /// bit at a specific bit position. This is used to mask the bit in the 
97   /// corresponding word.
98   /// @returns a uint64_t with only bit at "whichBit(bitPosition)" set
99   /// @brief Get a single bit mask.
100   static inline uint64_t maskBit(uint32_t bitPosition) { 
101     return 1ULL << whichBit(bitPosition); 
102   }
103
104   /// This method is used internally to clear the to "N" bits in the high order
105   /// word that are not used by the APInt. This is needed after the most 
106   /// significant word is assigned a value to ensure that those bits are 
107   /// zero'd out.
108   /// @brief Clear unused 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 Convert 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   /// @name Constructors
154   /// @{
155   /// If isSigned is true then val is treated as if it were a signed value
156   /// (i.e. as an int64_t) and the appropriate sign extension to the bit width
157   /// will be done. Otherwise, no sign extension occurs (high order bits beyond
158   /// the range of val are zero filled).
159   /// @param numBits the bit width of the constructed APInt
160   /// @param val the initial value of the APInt
161   /// @param isSigned how to treat signedness of val
162   /// @brief Create a new APInt of numBits width, initialized as val.
163   APInt(uint32_t numBits, uint64_t val, bool isSigned = false);
164
165   /// Note that numWords can be smaller or larger than the corresponding bit
166   /// width but any extraneous bits will be dropped.
167   /// @param numBits the bit width of the constructed APInt
168   /// @param numWords the number of words in bigVal
169   /// @param bigVal a sequence of words to form the initial value of the APInt
170   /// @brief Construct an APInt of numBits width, initialized as bigVal[].
171   APInt(uint32_t numBits, uint32_t numWords, uint64_t bigVal[]);
172
173   /// This constructor interprets Val as a string in the given radix. The 
174   /// interpretation stops when the first charater that is not suitable for the
175   /// radix is encountered. Acceptable radix values are 2, 8, 10 and 16. It is
176   /// an error for the value implied by the string to require more bits than 
177   /// numBits.
178   /// @param numBits the bit width of the constructed APInt
179   /// @param val the string to be interpreted
180   /// @param radix the radix of Val to use for the intepretation
181   /// @brief Construct an APInt from a string representation.
182   APInt(uint32_t numBits, const std::string& val, uint8_t radix);
183
184   /// This constructor interprets the slen characters starting at StrStart as
185   /// a string in the given radix. The interpretation stops when the first 
186   /// character that is not suitable for the radix is encountered. Acceptable
187   /// radix values are 2, 8, 10 and 16. It is an error for the value implied by
188   /// the string to require more bits than numBits.
189   /// @param numBits the bit width of the constructed APInt
190   /// @param strStart the start of the string to be interpreted
191   /// @param slen the maximum number of characters to interpret
192   /// @brief Construct an APInt from a string representation.
193   APInt(uint32_t numBits, const char strStart[], uint32_t slen, uint8_t radix);
194
195   /// Simply makes *this a copy of that.
196   /// @brief Copy Constructor.
197   APInt(const APInt& that);
198
199   /// @brief Destructor.
200   ~APInt();
201
202   /// @}
203   /// @name Value Tests
204   /// @{
205   /// This tests the high bit of this APInt to determine if it is set.
206   /// @returns true if this APInt is negative, false otherwise
207   /// @brief Determine sign of this APInt.
208   bool isNegative() const {
209     return (*this)[BitWidth - 1];
210   }
211
212   /// This tests the high bit of the APInt to determine if it is unset.
213   /// @brief Determine if this APInt Value is positive (not negative).
214   bool isPositive() const {
215     return !isNegative();
216   }
217
218   /// This tests if the value of this APInt is strictly positive (> 0).
219   /// @returns true if this APInt is Positive and not zero.
220   /// @brief Determine if this APInt Value is strictly positive.
221   inline bool isStrictlyPositive() const {
222     return isPositive() && (*this) != 0;
223   }
224
225   /// This checks to see if the value has all bits of the APInt are set or not.
226   /// @brief Determine if all bits are set
227   inline bool isAllOnesValue() const {
228     return countPopulation() == BitWidth;
229   }
230
231   /// This checks to see if the value of this APInt is the maximum unsigned
232   /// value for the APInt's bit width.
233   /// @brief Determine if this is the largest unsigned value.
234   bool isMaxValue() const {
235     return countPopulation() == BitWidth;
236   }
237
238   /// This checks to see if the value of this APInt is the maximum signed
239   /// value for the APInt's bit width.
240   /// @brief Determine if this is the largest signed value.
241   bool isMaxSignedValue() const {
242     return BitWidth == 1 ? VAL == 0 :
243                           !isNegative() && countPopulation() == BitWidth - 1;
244   }
245
246   /// This checks to see if the value of this APInt is the minimum unsigned
247   /// value for the APInt's bit width.
248   /// @brief Determine if this is the smallest unsigned value.
249   bool isMinValue() const {
250     return countPopulation() == 0;
251   }
252
253   /// This checks to see if the value of this APInt is the minimum signed
254   /// value for the APInt's bit width.
255   /// @brief Determine if this is the smallest signed value.
256   bool isMinSignedValue() const {
257     return BitWidth == 1 ? VAL == 1 :
258                            isNegative() && countPopulation() == 1;
259   }
260
261   /// @brief Check if this APInt has an N-bits integer value.
262   inline bool isIntN(uint32_t N) const {
263     assert(N && "N == 0 ???");
264     if (isSingleWord()) {
265       return VAL == (VAL & (~0ULL >> (64 - N)));
266     } else {
267       APInt Tmp(N, getNumWords(), pVal);
268       return Tmp == (*this);
269     }
270   }
271
272   /// @returns true if the argument APInt value is a power of two > 0.
273   bool isPowerOf2() const; 
274
275   /// This converts the APInt to a boolean valy as a test against zero.
276   /// @brief Boolean conversion function. 
277   inline bool getBoolValue() const {
278     return countLeadingZeros() != BitWidth;
279   }
280
281   /// @}
282   /// @name Value Generators
283   /// @{
284   /// @brief Gets maximum unsigned value of APInt for specific bit width.
285   static APInt getMaxValue(uint32_t numBits) {
286     return APInt(numBits, 0).set();
287   }
288
289   /// @brief Gets maximum signed value of APInt for a specific bit width.
290   static APInt getSignedMaxValue(uint32_t numBits) {
291     return APInt(numBits, 0).set().clear(numBits - 1);
292   }
293
294   /// @brief Gets minimum unsigned value of APInt for a specific bit width.
295   static APInt getMinValue(uint32_t numBits) {
296     return APInt(numBits, 0);
297   }
298
299   /// @brief Gets minimum signed value of APInt for a specific bit width.
300   static APInt getSignedMinValue(uint32_t numBits) {
301     return APInt(numBits, 0).set(numBits - 1);
302   }
303
304   /// getSignBit - This is just a wrapper function of getSignedMinValue(), and
305   /// it helps code readability when we want to get a SignBit.
306   /// @brief Get the SignBit for a specific bit width.
307   inline static APInt getSignBit(uint32_t BitWidth) {
308     return getSignedMinValue(BitWidth);
309   }
310
311   /// @returns the all-ones value for an APInt of the specified bit-width.
312   /// @brief Get the all-ones value.
313   static APInt getAllOnesValue(uint32_t numBits) {
314     return APInt(numBits, 0).set();
315   }
316
317   /// @returns the '0' value for an APInt of the specified bit-width.
318   /// @brief Get the '0' value.
319   static APInt getNullValue(uint32_t numBits) {
320     return APInt(numBits, 0);
321   }
322
323   /// Get an APInt with the same BitWidth as this APInt, just zero mask
324   /// the low bits and right shift to the least significant bit.
325   /// @returns the high "numBits" bits of this APInt.
326   APInt getHiBits(uint32_t numBits) const;
327
328   /// Get an APInt with the same BitWidth as this APInt, just zero mask
329   /// the high bits.
330   /// @returns the low "numBits" bits of this APInt.
331   APInt getLoBits(uint32_t numBits) const;
332
333   /// Constructs an APInt value that has a contiguous range of bits set. The
334   /// bits from loBit to hiBit will be set. All other bits will be zero. For
335   /// example, with parameters(32, 15, 0) you would get 0x0000FFFF. If hiBit is
336   /// less than loBit then the set bits "wrap". For example, with 
337   /// parameters (32, 3, 28), you would get 0xF000000F. 
338   /// @param numBits the intended bit width of the result
339   /// @param loBit the index of the lowest bit set.
340   /// @param hiBit the index of the highest bit set.
341   /// @returns An APInt value with the requested bits set.
342   /// @brief Get a value with a block of bits set.
343   static APInt getBitsSet(uint32_t numBits, uint32_t loBit, uint32_t hiBit) {
344     assert(hiBit < numBits && "hiBit out of range");
345     assert(loBit < numBits && "loBit out of range");
346     if (hiBit < loBit)
347       return getLowBitsSet(numBits, hiBit+1) |
348              getHighBitsSet(numBits, numBits-loBit+1);
349     return getLowBitsSet(numBits, hiBit-loBit+1).shl(loBit);
350   }
351
352   /// Constructs an APInt value that has the top hiBitsSet bits set.
353   /// @param numBits the bitwidth of the result
354   /// @param hiBitsSet the number of high-order bits set in the result.
355   /// @brief Get a value with high bits set
356   static APInt getHighBitsSet(uint32_t numBits, uint32_t hiBitsSet) {
357     assert(hiBitsSet <= numBits && "Too many bits to set!");
358     uint32_t shiftAmt = numBits - hiBitsSet;
359     // For small values, return quickly
360     if (numBits <= APINT_BITS_PER_WORD)
361       return APInt(numBits, ~0ULL << shiftAmt);
362     return (~APInt(numBits, 0)).shl(shiftAmt);
363   }
364
365   /// Constructs an APInt value that has the bottom loBitsSet bits set.
366   /// @param numBits the bitwidth of the result
367   /// @param loBitsSet the number of low-order bits set in the result.
368   /// @brief Get a value with low bits set
369   static APInt getLowBitsSet(uint32_t numBits, uint32_t loBitsSet) {
370     assert(loBitsSet <= numBits && "Too many bits to set!");
371     uint32_t shiftAmt = numBits - loBitsSet;
372     // For small values, return quickly
373     if (numBits <= APINT_BITS_PER_WORD)
374       return APInt(numBits, ~0ULL >> shiftAmt);
375     return (~APInt(numBits, 0)).lshr(shiftAmt);
376   }
377
378   /// The hash value is computed as the sum of the words and the bit width.
379   /// @returns A hash value computed from the sum of the APInt words.
380   /// @brief Get a hash value based on this APInt
381   uint64_t getHashValue() const;
382
383   /// This function returns a pointer to the internal storage of the APInt. 
384   /// This is useful for writing out the APInt in binary form without any
385   /// conversions.
386   inline const uint64_t* getRawData() const {
387     if (isSingleWord())
388       return &VAL;
389     return &pVal[0];
390   }
391
392   /// @brief Set a sepcific word in the value to a new value.
393   inline void setWordToValue(uint32_t idx, uint64_t Val) {
394     assert(idx < getNumWords() && "Invalid word array index");
395     if (isSingleWord())
396       VAL = Val;
397     else
398       pVal[idx] = Val;
399   }
400
401   /// @}
402   /// @name Unary Operators
403   /// @{
404   /// @returns a new APInt value representing *this incremented by one
405   /// @brief Postfix increment operator.
406   inline const APInt operator++(int) {
407     APInt API(*this);
408     ++(*this);
409     return API;
410   }
411
412   /// @returns *this incremented by one
413   /// @brief Prefix increment operator.
414   APInt& operator++();
415
416   /// @returns a new APInt representing *this decremented by one.
417   /// @brief Postfix decrement operator. 
418   inline const APInt operator--(int) {
419     APInt API(*this);
420     --(*this);
421     return API;
422   }
423
424   /// @returns *this decremented by one.
425   /// @brief Prefix decrement operator. 
426   APInt& operator--();
427
428   /// Performs a bitwise complement operation on this APInt. 
429   /// @returns an APInt that is the bitwise complement of *this
430   /// @brief Unary bitwise complement operator. 
431   APInt operator~() const;
432
433   /// Negates *this using two's complement logic.
434   /// @returns An APInt value representing the negation of *this.
435   /// @brief Unary negation operator
436   inline APInt operator-() const {
437     return APInt(BitWidth, 0) - (*this);
438   }
439
440   /// Performs logical negation operation on this APInt.
441   /// @returns true if *this is zero, false otherwise.
442   /// @brief Logical negation operator. 
443   bool operator !() const;
444
445   /// @}
446   /// @name Assignment Operators
447   /// @{
448   /// @returns *this after assignment of RHS.
449   /// @brief Copy assignment operator. 
450   APInt& operator=(const APInt& RHS);
451
452   /// The RHS value is assigned to *this. If the significant bits in RHS exceed
453   /// the bit width, the excess bits are truncated. If the bit width is larger
454   /// than 64, the value is zero filled in the unspecified high order bits.
455   /// @returns *this after assignment of RHS value.
456   /// @brief Assignment operator. 
457   APInt& operator=(uint64_t RHS);
458
459   /// Performs a bitwise AND operation on this APInt and RHS. The result is
460   /// assigned to *this. 
461   /// @returns *this after ANDing with RHS.
462   /// @brief Bitwise AND assignment operator. 
463   APInt& operator&=(const APInt& RHS);
464
465   /// Performs a bitwise OR operation on this APInt and RHS. The result is 
466   /// assigned *this;
467   /// @returns *this after ORing with RHS.
468   /// @brief Bitwise OR assignment operator. 
469   APInt& operator|=(const APInt& RHS);
470
471   /// Performs a bitwise XOR operation on this APInt and RHS. The result is
472   /// assigned to *this.
473   /// @returns *this after XORing with RHS.
474   /// @brief Bitwise XOR assignment operator. 
475   APInt& operator^=(const APInt& RHS);
476
477   /// Multiplies this APInt by RHS and assigns the result to *this.
478   /// @returns *this
479   /// @brief Multiplication assignment operator. 
480   APInt& operator*=(const APInt& RHS);
481
482   /// Adds RHS to *this and assigns the result to *this.
483   /// @returns *this
484   /// @brief Addition assignment operator. 
485   APInt& operator+=(const APInt& RHS);
486
487   /// Subtracts RHS from *this and assigns the result to *this.
488   /// @returns *this
489   /// @brief Subtraction assignment operator. 
490   APInt& operator-=(const APInt& RHS);
491
492   /// Shifts *this left by shiftAmt and assigns the result to *this.
493   /// @returns *this after shifting left by shiftAmt
494   /// @brief Left-shift assignment function.
495   inline APInt& operator<<=(uint32_t shiftAmt) {
496     *this = shl(shiftAmt);
497     return *this;
498   }
499
500   /// @}
501   /// @name Binary Operators
502   /// @{
503   /// Performs a bitwise AND operation on *this and RHS.
504   /// @returns An APInt value representing the bitwise AND of *this and RHS.
505   /// @brief Bitwise AND operator. 
506   APInt operator&(const APInt& RHS) const;
507   APInt And(const APInt& RHS) const {
508     return this->operator&(RHS);
509   }
510
511   /// Performs a bitwise OR operation on *this and RHS.
512   /// @returns An APInt value representing the bitwise OR of *this and RHS.
513   /// @brief Bitwise OR operator. 
514   APInt operator|(const APInt& RHS) const;
515   APInt Or(const APInt& RHS) const {
516     return this->operator|(RHS);
517   }
518
519   /// Performs a bitwise XOR operation on *this and RHS.
520   /// @returns An APInt value representing the bitwise XOR of *this and RHS.
521   /// @brief Bitwise XOR operator. 
522   APInt operator^(const APInt& RHS) const;
523   APInt Xor(const APInt& RHS) const {
524     return this->operator^(RHS);
525   }
526
527   /// Multiplies this APInt by RHS and returns the result.
528   /// @brief Multiplication operator. 
529   APInt operator*(const APInt& RHS) const;
530
531   /// Adds RHS to this APInt and returns the result.
532   /// @brief Addition operator. 
533   APInt operator+(const APInt& RHS) const;
534   APInt operator+(uint64_t RHS) const {
535     return (*this) + APInt(BitWidth, RHS);
536   }
537
538   /// Subtracts RHS from this APInt and returns the result.
539   /// @brief Subtraction operator. 
540   APInt operator-(const APInt& RHS) const;
541   APInt operator-(uint64_t RHS) const {
542     return (*this) - APInt(BitWidth, RHS);
543   }
544
545   /// Arithmetic right-shift this APInt by shiftAmt.
546   /// @brief Arithmetic right-shift function.
547   APInt ashr(uint32_t shiftAmt) const;
548
549   /// Logical right-shift this APInt by shiftAmt.
550   /// @brief Logical right-shift function.
551   APInt lshr(uint32_t shiftAmt) const;
552
553   /// Left-shift this APInt by shiftAmt.
554   /// @brief Left-shift function.
555   APInt shl(uint32_t shiftAmt) const;
556
557   /// Perform an unsigned divide operation on this APInt by RHS. Both this and
558   /// RHS are treated as unsigned quantities for purposes of this division.
559   /// @returns a new APInt value containing the division result
560   /// @brief Unsigned division operation.
561   APInt udiv(const APInt& RHS) const;
562
563   /// Signed divide this APInt by APInt RHS.
564   /// @brief Signed division function for APInt.
565   inline APInt sdiv(const APInt& RHS) const {
566     if (isNegative())
567       if (RHS.isNegative())
568         return (-(*this)).udiv(-RHS);
569       else
570         return -((-(*this)).udiv(RHS));
571     else if (RHS.isNegative())
572       return -(this->udiv(-RHS));
573     return this->udiv(RHS);
574   }
575
576   /// Perform an unsigned remainder operation on this APInt with RHS being the
577   /// divisor. Both this and RHS are treated as unsigned quantities for purposes
578   /// of this operation. Note that this is a true remainder operation and not
579   /// a modulo operation because the sign follows the sign of the dividend
580   /// which is *this.
581   /// @returns a new APInt value containing the remainder result
582   /// @brief Unsigned remainder operation.
583   APInt urem(const APInt& RHS) const;
584
585   /// Signed remainder operation on APInt.
586   /// @brief Function for signed remainder operation.
587   inline APInt srem(const APInt& RHS) const {
588     if (isNegative())
589       if (RHS.isNegative())
590         return -((-(*this)).urem(-RHS));
591       else
592         return -((-(*this)).urem(RHS));
593     else if (RHS.isNegative())
594       return this->urem(-RHS);
595     return this->urem(RHS);
596   }
597
598   /// @returns the bit value at bitPosition
599   /// @brief Array-indexing support.
600   bool operator[](uint32_t bitPosition) const;
601
602   /// @}
603   /// @name Comparison Operators
604   /// @{
605   /// Compares this APInt with RHS for the validity of the equality
606   /// relationship.
607   /// @brief Equality operator. 
608   bool operator==(const APInt& RHS) const;
609
610   /// Compares this APInt with a uint64_t for the validity of the equality 
611   /// relationship.
612   /// @returns true if *this == Val
613   /// @brief Equality operator.
614   bool operator==(uint64_t Val) const;
615
616   /// Compares this APInt with RHS for the validity of the equality
617   /// relationship.
618   /// @returns true if *this == Val
619   /// @brief Equality comparison.
620   bool eq(const APInt &RHS) const {
621     return (*this) == RHS; 
622   }
623
624   /// Compares this APInt with RHS for the validity of the inequality
625   /// relationship.
626   /// @returns true if *this != Val
627   /// @brief Inequality operator. 
628   inline bool operator!=(const APInt& RHS) const {
629     return !((*this) == RHS);
630   }
631
632   /// Compares this APInt with a uint64_t for the validity of the inequality 
633   /// relationship.
634   /// @returns true if *this != Val
635   /// @brief Inequality operator. 
636   inline bool operator!=(uint64_t Val) const {
637     return !((*this) == Val);
638   }
639   
640   /// Compares this APInt with RHS for the validity of the inequality
641   /// relationship.
642   /// @returns true if *this != Val
643   /// @brief Inequality comparison
644   bool ne(const APInt &RHS) const {
645     return !((*this) == RHS);
646   }
647
648   /// Regards both *this and RHS as unsigned quantities and compares them for
649   /// the validity of the less-than relationship.
650   /// @returns true if *this < RHS when both are considered unsigned.
651   /// @brief Unsigned less than comparison
652   bool ult(const APInt& RHS) const;
653
654   /// Regards both *this and RHS as signed quantities and compares them for
655   /// validity of the less-than relationship.
656   /// @returns true if *this < RHS when both are considered signed.
657   /// @brief Signed less than comparison
658   bool slt(const APInt& RHS) const;
659
660   /// Regards both *this and RHS as unsigned quantities and compares them for
661   /// validity of the less-or-equal relationship.
662   /// @returns true if *this <= RHS when both are considered unsigned.
663   /// @brief Unsigned less or equal comparison
664   bool ule(const APInt& RHS) const {
665     return ult(RHS) || eq(RHS);
666   }
667
668   /// Regards both *this and RHS as signed quantities and compares them for
669   /// validity of the less-or-equal relationship.
670   /// @returns true if *this <= RHS when both are considered signed.
671   /// @brief Signed less or equal comparison
672   bool sle(const APInt& RHS) const {
673     return slt(RHS) || eq(RHS);
674   }
675
676   /// Regards both *this and RHS as unsigned quantities and compares them for
677   /// the validity of the greater-than relationship.
678   /// @returns true if *this > RHS when both are considered unsigned.
679   /// @brief Unsigned greather than comparison
680   bool ugt(const APInt& RHS) const {
681     return !ult(RHS) && !eq(RHS);
682   }
683
684   /// Regards both *this and RHS as signed quantities and compares them for
685   /// the validity of the greater-than relationship.
686   /// @returns true if *this > RHS when both are considered signed.
687   /// @brief Signed greather than comparison
688   bool sgt(const APInt& RHS) const {
689     return !slt(RHS) && !eq(RHS);
690   }
691
692   /// Regards both *this and RHS as unsigned quantities and compares them for
693   /// validity of the greater-or-equal relationship.
694   /// @returns true if *this >= RHS when both are considered unsigned.
695   /// @brief Unsigned greater or equal comparison
696   bool uge(const APInt& RHS) const {
697     return !ult(RHS);
698   }
699
700   /// Regards both *this and RHS as signed quantities and compares them for
701   /// validity of the greater-or-equal relationship.
702   /// @returns true if *this >= RHS when both are considered signed.
703   /// @brief Signed greather or equal comparison
704   bool sge(const APInt& RHS) const {
705     return !slt(RHS);
706   }
707
708   /// @}
709   /// @name Resizing Operators
710   /// @{
711   /// Truncate the APInt to a specified width. It is an error to specify a width
712   /// that is greater than or equal to the current width. 
713   /// @brief Truncate to new width.
714   APInt &trunc(uint32_t width);
715
716   /// This operation sign extends the APInt to a new width. If the high order
717   /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
718   /// It is an error to specify a width that is less than or equal to the 
719   /// current width.
720   /// @brief Sign extend to a new width.
721   APInt &sext(uint32_t width);
722
723   /// This operation zero extends the APInt to a new width. Thie high order bits
724   /// are filled with 0 bits.  It is an error to specify a width that is less 
725   /// than or equal to the current width.
726   /// @brief Zero extend to a new width.
727   APInt &zext(uint32_t width);
728
729   /// Make this APInt have the bit width given by \p width. The value is sign
730   /// extended, truncated, or left alone to make it that width.
731   /// @brief Sign extend or truncate to width
732   APInt &sextOrTrunc(uint32_t width);
733
734   /// Make this APInt have the bit width given by \p width. The value is zero
735   /// extended, truncated, or left alone to make it that width.
736   /// @brief Zero extend or truncate to width
737   APInt &zextOrTrunc(uint32_t width);
738
739   /// This is a help function for convenience. If the given \p width equals to
740   /// this APInt's BitWidth, just return this APInt, otherwise, just zero 
741   /// extend it.
742   inline APInt &zextOrCopy(uint32_t width) {
743     if (width == BitWidth)
744       return *this;
745     return zext(width);
746   }
747
748   /// @}
749   /// @name Bit Manipulation Operators
750   /// @{
751   /// @brief Set every bit to 1.
752   APInt& set();
753
754   /// Set the given bit to 1 whose position is given as "bitPosition".
755   /// @brief Set a given bit to 1.
756   APInt& set(uint32_t bitPosition);
757
758   /// @brief Set every bit to 0.
759   APInt& clear();
760
761   /// Set the given bit to 0 whose position is given as "bitPosition".
762   /// @brief Set a given bit to 0.
763   APInt& clear(uint32_t bitPosition);
764
765   /// @brief Toggle every bit to its opposite value.
766   APInt& flip();
767
768   /// Toggle a given bit to its opposite value whose position is given 
769   /// as "bitPosition".
770   /// @brief Toggles a given bit to its opposite value.
771   APInt& flip(uint32_t bitPosition);
772
773   /// @}
774   /// @name Value Characterization Functions
775   /// @{
776
777   /// @returns the total number of bits.
778   inline uint32_t getBitWidth() const { 
779     return BitWidth; 
780   }
781
782   /// Here one word's bitwidth equals to that of uint64_t.
783   /// @returns the number of words to hold the integer value of this APInt.
784   /// @brief Get the number of words.
785   inline uint32_t getNumWords() const {
786     return (BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
787   }
788
789   /// This function returns the number of active bits which is defined as the
790   /// bit width minus the number of leading zeros. This is used in several
791   /// computations to see how "wide" the value is.
792   /// @brief Compute the number of active bits in the value
793   inline uint32_t getActiveBits() const {
794     return BitWidth - countLeadingZeros();
795   }
796
797   /// This function returns the number of active words in the value of this
798   /// APInt. This is used in conjunction with getActiveData to extract the raw
799   /// value of the APInt.
800   inline uint32_t getActiveWords() const {
801     return whichWord(getActiveBits()-1) + 1;
802   }
803
804   /// Computes the minimum bit width for this APInt while considering it to be
805   /// a signed (and probably negative) value. If the value is not negative, 
806   /// this function returns the same value as getActiveBits(). Otherwise, it
807   /// returns the smallest bit width that will retain the negative value. For
808   /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
809   /// for -1, this function will always return 1.
810   /// @brief Get the minimum bit size for this signed APInt 
811   inline uint32_t getMinSignedBits() const {
812     if (isNegative())
813       return BitWidth - countLeadingOnes() + 1;
814     return getActiveBits();
815   }
816
817   /// This method attempts to return the value of this APInt as a zero extended
818   /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
819   /// uint64_t. Otherwise an assertion will result.
820   /// @brief Get zero extended value
821   inline uint64_t getZExtValue() const {
822     if (isSingleWord())
823       return VAL;
824     assert(getActiveBits() <= 64 && "Too many bits for uint64_t");
825     return pVal[0];
826   }
827
828   /// This method attempts to return the value of this APInt as a sign extended
829   /// int64_t. The bit width must be <= 64 or the value must fit within an
830   /// int64_t. Otherwise an assertion will result.
831   /// @brief Get sign extended value
832   inline int64_t getSExtValue() const {
833     if (isSingleWord())
834       return int64_t(VAL << (APINT_BITS_PER_WORD - BitWidth)) >> 
835                      (APINT_BITS_PER_WORD - BitWidth);
836     assert(getActiveBits() <= 64 && "Too many bits for int64_t");
837     return int64_t(pVal[0]);
838   }
839   /// countLeadingZeros - This function is an APInt version of the
840   /// countLeadingZeros_{32,64} functions in MathExtras.h. It counts the number
841   /// of zeros from the most significant bit to the first one bit.
842   /// @returns getNumWords() * APINT_BITS_PER_WORD if the value is zero.
843   /// @returns the number of zeros from the most significant bit to the first
844   /// one bits.
845   /// @brief Count the number of leading one bits.
846   uint32_t countLeadingZeros() const;
847
848   /// countLeadingOnes - This function counts the number of contiguous 1 bits
849   /// in the high order bits. The count stops when the first 0 bit is reached.
850   /// @returns 0 if the high order bit is not set
851   /// @returns the number of 1 bits from the most significant to the least
852   /// @brief Count the number of leading one bits.
853   uint32_t countLeadingOnes() const;
854
855   /// countTrailingZeros - This function is an APInt version of the 
856   /// countTrailingZoers_{32,64} functions in MathExtras.h. It counts 
857   /// the number of zeros from the least significant bit to the first one bit.
858   /// @returns getNumWords() * APINT_BITS_PER_WORD if the value is zero.
859   /// @returns the number of zeros from the least significant bit to the first
860   /// one bit.
861   /// @brief Count the number of trailing zero bits.
862   uint32_t countTrailingZeros() const;
863
864   /// countPopulation - This function is an APInt version of the
865   /// countPopulation_{32,64} functions in MathExtras.h. It counts the number
866   /// of 1 bits in the APInt value. 
867   /// @returns 0 if the value is zero.
868   /// @returns the number of set bits.
869   /// @brief Count the number of bits set.
870   uint32_t countPopulation() const; 
871
872   /// @}
873   /// @name Conversion Functions
874   /// @{
875
876   /// This is used internally to convert an APInt to a string.
877   /// @brief Converts an APInt to a std::string
878   std::string toString(uint8_t radix, bool wantSigned) const;
879
880   /// Considers the APInt to be unsigned and converts it into a string in the
881   /// radix given. The radix can be 2, 8, 10 or 16.
882   /// @returns a character interpretation of the APInt
883   /// @brief Convert unsigned APInt to string representation.
884   inline std::string toString(uint8_t radix = 10) const {
885     return toString(radix, false);
886   }
887
888   /// Considers the APInt to be unsigned and converts it into a string in the
889   /// radix given. The radix can be 2, 8, 10 or 16.
890   /// @returns a character interpretation of the APInt
891   /// @brief Convert unsigned APInt to string representation.
892   inline std::string toStringSigned(uint8_t radix = 10) const {
893     return toString(radix, true);
894   }
895
896   /// @returns a byte-swapped representation of this APInt Value.
897   APInt byteSwap() const;
898
899   /// @brief Converts this APInt to a double value.
900   double roundToDouble(bool isSigned) const;
901
902   /// @brief Converts this unsigned APInt to a double value.
903   double roundToDouble() const {
904     return roundToDouble(false);
905   }
906
907   /// @brief Converts this signed APInt to a double value.
908   double signedRoundToDouble() const {
909     return roundToDouble(true);
910   }
911
912   /// The conversion does not do a translation from integer to double, it just
913   /// re-interprets the bits as a double. Note that it is valid to do this on
914   /// any bit width. Exactly 64 bits will be translated.
915   /// @brief Converts APInt bits to a double
916   double bitsToDouble() const {
917     union {
918       uint64_t I;
919       double D;
920     } T;
921     T.I = (isSingleWord() ? VAL : pVal[0]);
922     return T.D;
923   }
924
925   /// The conversion does not do a translation from integer to float, it just
926   /// re-interprets the bits as a float. Note that it is valid to do this on
927   /// any bit width. Exactly 32 bits will be translated.
928   /// @brief Converts APInt bits to a double
929   float bitsToFloat() const {
930     union {
931       uint32_t I;
932       float F;
933     } T;
934     T.I = uint32_t((isSingleWord() ? VAL : pVal[0]));
935     return T.F;
936   }
937
938   /// The conversion does not do a translation from double to integer, it just
939   /// re-interprets the bits of the double. Note that it is valid to do this on
940   /// any bit width but bits from V may get truncated.
941   /// @brief Converts a double to APInt bits.
942   APInt& doubleToBits(double V) {
943     union {
944       uint64_t I;
945       double D;
946     } T;
947     T.D = V;
948     if (isSingleWord())
949       VAL = T.I;
950     else
951       pVal[0] = T.I;
952     return clearUnusedBits();
953   }
954
955   /// The conversion does not do a translation from float to integer, it just
956   /// re-interprets the bits of the float. Note that it is valid to do this on
957   /// any bit width but bits from V may get truncated.
958   /// @brief Converts a float to APInt bits.
959   APInt& floatToBits(float V) {
960     union {
961       uint32_t I;
962       float F;
963     } T;
964     T.F = V;
965     if (isSingleWord())
966       VAL = T.I;
967     else
968       pVal[0] = T.I;
969     return clearUnusedBits();
970   }
971
972   /// @}
973   /// @name Mathematics Operations
974   /// @{
975
976   /// @returns the floor log base 2 of this APInt.
977   inline uint32_t logBase2() const {
978     return BitWidth - 1 - countLeadingZeros();
979   }
980
981   /// @brief Compute the square root
982   APInt sqrt() const;
983
984   /// If *this is < 0 then return -(*this), otherwise *this;
985   /// @brief Get the absolute value;
986   APInt abs() const {
987     if (isNegative())
988       return -(*this);
989     return *this;
990   }
991   /// @}
992 };
993
994 inline bool operator==(uint64_t V1, const APInt& V2) {
995   return V2 == V1;
996 }
997
998 inline bool operator!=(uint64_t V1, const APInt& V2) {
999   return V2 != V1;
1000 }
1001
1002 namespace APIntOps {
1003
1004 /// @brief Determine the smaller of two APInts considered to be signed.
1005 inline APInt smin(const APInt &A, const APInt &B) {
1006   return A.slt(B) ? A : B;
1007 }
1008
1009 /// @brief Determine the larger of two APInts considered to be signed.
1010 inline APInt smax(const APInt &A, const APInt &B) {
1011   return A.sgt(B) ? A : B;
1012 }
1013
1014 /// @brief Determine the smaller of two APInts considered to be signed.
1015 inline APInt umin(const APInt &A, const APInt &B) {
1016   return A.ult(B) ? A : B;
1017 }
1018
1019 /// @brief Determine the larger of two APInts considered to be unsigned.
1020 inline APInt umax(const APInt &A, const APInt &B) {
1021   return A.ugt(B) ? A : B;
1022 }
1023
1024 /// @brief Check if the specified APInt has a N-bits integer value.
1025 inline bool isIntN(uint32_t N, const APInt& APIVal) {
1026   return APIVal.isIntN(N);
1027 }
1028
1029 /// @returns true if the argument APInt value is a sequence of ones
1030 /// starting at the least significant bit with the remainder zero.
1031 inline const bool isMask(uint32_t numBits, const APInt& APIVal) {
1032   return APIVal.getBoolValue() && ((APIVal + APInt(numBits,1)) & APIVal) == 0;
1033 }
1034
1035 /// @returns true if the argument APInt value contains a sequence of ones
1036 /// with the remainder zero.
1037 inline const bool isShiftedMask(uint32_t numBits, const APInt& APIVal) {
1038   return isMask(numBits, (APIVal - APInt(numBits,1)) | APIVal);
1039 }
1040
1041 /// @returns a byte-swapped representation of the specified APInt Value.
1042 inline APInt byteSwap(const APInt& APIVal) {
1043   return APIVal.byteSwap();
1044 }
1045
1046 /// @returns the floor log base 2 of the specified APInt value.
1047 inline uint32_t logBase2(const APInt& APIVal) {
1048   return APIVal.logBase2(); 
1049 }
1050
1051 /// GreatestCommonDivisor - This function returns the greatest common
1052 /// divisor of the two APInt values using Enclid's algorithm.
1053 /// @returns the greatest common divisor of Val1 and Val2
1054 /// @brief Compute GCD of two APInt values.
1055 APInt GreatestCommonDivisor(const APInt& Val1, const APInt& Val2);
1056
1057 /// Treats the APInt as an unsigned value for conversion purposes.
1058 /// @brief Converts the given APInt to a double value.
1059 inline double RoundAPIntToDouble(const APInt& APIVal) {
1060   return APIVal.roundToDouble();
1061 }
1062
1063 /// Treats the APInt as a signed value for conversion purposes.
1064 /// @brief Converts the given APInt to a double value.
1065 inline double RoundSignedAPIntToDouble(const APInt& APIVal) {
1066   return APIVal.signedRoundToDouble();
1067 }
1068
1069 /// @brief Converts the given APInt to a float vlalue.
1070 inline float RoundAPIntToFloat(const APInt& APIVal) {
1071   return float(RoundAPIntToDouble(APIVal));
1072 }
1073
1074 /// Treast the APInt as a signed value for conversion purposes.
1075 /// @brief Converts the given APInt to a float value.
1076 inline float RoundSignedAPIntToFloat(const APInt& APIVal) {
1077   return float(APIVal.signedRoundToDouble());
1078 }
1079
1080 /// RoundDoubleToAPInt - This function convert a double value to an APInt value.
1081 /// @brief Converts the given double value into a APInt.
1082 APInt RoundDoubleToAPInt(double Double, uint32_t width);
1083
1084 /// RoundFloatToAPInt - Converts a float value into an APInt value.
1085 /// @brief Converts a float value into a APInt.
1086 inline APInt RoundFloatToAPInt(float Float, uint32_t width) {
1087   return RoundDoubleToAPInt(double(Float), width);
1088 }
1089
1090 /// Arithmetic right-shift the APInt by shiftAmt.
1091 /// @brief Arithmetic right-shift function.
1092 inline APInt ashr(const APInt& LHS, uint32_t shiftAmt) {
1093   return LHS.ashr(shiftAmt);
1094 }
1095
1096 /// Logical right-shift the APInt by shiftAmt.
1097 /// @brief Logical right-shift function.
1098 inline APInt lshr(const APInt& LHS, uint32_t shiftAmt) {
1099   return LHS.lshr(shiftAmt);
1100 }
1101
1102 /// Left-shift the APInt by shiftAmt.
1103 /// @brief Left-shift function.
1104 inline APInt shl(const APInt& LHS, uint32_t shiftAmt) {
1105   return LHS.shl(shiftAmt);
1106 }
1107
1108 /// Signed divide APInt LHS by APInt RHS.
1109 /// @brief Signed division function for APInt.
1110 inline APInt sdiv(const APInt& LHS, const APInt& RHS) {
1111   return LHS.sdiv(RHS);
1112 }
1113
1114 /// Unsigned divide APInt LHS by APInt RHS.
1115 /// @brief Unsigned division function for APInt.
1116 inline APInt udiv(const APInt& LHS, const APInt& RHS) {
1117   return LHS.udiv(RHS);
1118 }
1119
1120 /// Signed remainder operation on APInt.
1121 /// @brief Function for signed remainder operation.
1122 inline APInt srem(const APInt& LHS, const APInt& RHS) {
1123   return LHS.srem(RHS);
1124 }
1125
1126 /// Unsigned remainder operation on APInt.
1127 /// @brief Function for unsigned remainder operation.
1128 inline APInt urem(const APInt& LHS, const APInt& RHS) {
1129   return LHS.urem(RHS);
1130 }
1131
1132 /// Performs multiplication on APInt values.
1133 /// @brief Function for multiplication operation.
1134 inline APInt mul(const APInt& LHS, const APInt& RHS) {
1135   return LHS * RHS;
1136 }
1137
1138 /// Performs addition on APInt values.
1139 /// @brief Function for addition operation.
1140 inline APInt add(const APInt& LHS, const APInt& RHS) {
1141   return LHS + RHS;
1142 }
1143
1144 /// Performs subtraction on APInt values.
1145 /// @brief Function for subtraction operation.
1146 inline APInt sub(const APInt& LHS, const APInt& RHS) {
1147   return LHS - RHS;
1148 }
1149
1150 /// Performs bitwise AND operation on APInt LHS and 
1151 /// APInt RHS.
1152 /// @brief Bitwise AND function for APInt.
1153 inline APInt And(const APInt& LHS, const APInt& RHS) {
1154   return LHS & RHS;
1155 }
1156
1157 /// Performs bitwise OR operation on APInt LHS and APInt RHS.
1158 /// @brief Bitwise OR function for APInt. 
1159 inline APInt Or(const APInt& LHS, const APInt& RHS) {
1160   return LHS | RHS;
1161 }
1162
1163 /// Performs bitwise XOR operation on APInt.
1164 /// @brief Bitwise XOR function for APInt.
1165 inline APInt Xor(const APInt& LHS, const APInt& RHS) {
1166   return LHS ^ RHS;
1167
1168
1169 /// Performs a bitwise complement operation on APInt.
1170 /// @brief Bitwise complement function. 
1171 inline APInt Not(const APInt& APIVal) {
1172   return ~APIVal;
1173 }
1174
1175 } // End of APIntOps namespace
1176
1177 } // End of llvm namespace
1178
1179 #endif