Compute getLowBitsSet correctly. Using the complement of a 64-bit value
[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     // Handle a degenerate case, to avoid shifting by word size
359     if (hiBitsSet == 0)
360       return APInt(numBits, 0);
361     uint32_t shiftAmt = numBits - hiBitsSet;
362     // For small values, return quickly
363     if (numBits <= APINT_BITS_PER_WORD)
364       return APInt(numBits, ~0ULL << shiftAmt);
365     return (~APInt(numBits, 0)).shl(shiftAmt);
366   }
367
368   /// Constructs an APInt value that has the bottom loBitsSet bits set.
369   /// @param numBits the bitwidth of the result
370   /// @param loBitsSet the number of low-order bits set in the result.
371   /// @brief Get a value with low bits set
372   static APInt getLowBitsSet(uint32_t numBits, uint32_t loBitsSet) {
373     assert(loBitsSet <= numBits && "Too many bits to set!");
374     // Handle a degenerate case, to avoid shifting by word size
375     if (loBitsSet == 0)
376       return APInt(numBits, 0);
377     if (loBitsSet == APINT_BITS_PER_WORD)
378       return APInt(numBits, -1ULL);
379     // For small values, return quickly
380     if (numBits < APINT_BITS_PER_WORD)
381       return APInt(numBits, (1ULL << loBitsSet) - 1);
382     return (~APInt(numBits, 0)).lshr(numBits - loBitsSet);
383   }
384
385   /// The hash value is computed as the sum of the words and the bit width.
386   /// @returns A hash value computed from the sum of the APInt words.
387   /// @brief Get a hash value based on this APInt
388   uint64_t getHashValue() const;
389
390   /// This function returns a pointer to the internal storage of the APInt. 
391   /// This is useful for writing out the APInt in binary form without any
392   /// conversions.
393   inline const uint64_t* getRawData() const {
394     if (isSingleWord())
395       return &VAL;
396     return &pVal[0];
397   }
398
399   /// @brief Set a sepcific word in the value to a new value.
400   inline void setWordToValue(uint32_t idx, uint64_t Val) {
401     assert(idx < getNumWords() && "Invalid word array index");
402     if (isSingleWord())
403       VAL = Val;
404     else
405       pVal[idx] = Val;
406   }
407
408   /// @}
409   /// @name Unary Operators
410   /// @{
411   /// @returns a new APInt value representing *this incremented by one
412   /// @brief Postfix increment operator.
413   inline const APInt operator++(int) {
414     APInt API(*this);
415     ++(*this);
416     return API;
417   }
418
419   /// @returns *this incremented by one
420   /// @brief Prefix increment operator.
421   APInt& operator++();
422
423   /// @returns a new APInt representing *this decremented by one.
424   /// @brief Postfix decrement operator. 
425   inline const APInt operator--(int) {
426     APInt API(*this);
427     --(*this);
428     return API;
429   }
430
431   /// @returns *this decremented by one.
432   /// @brief Prefix decrement operator. 
433   APInt& operator--();
434
435   /// Performs a bitwise complement operation on this APInt. 
436   /// @returns an APInt that is the bitwise complement of *this
437   /// @brief Unary bitwise complement operator. 
438   APInt operator~() const;
439
440   /// Negates *this using two's complement logic.
441   /// @returns An APInt value representing the negation of *this.
442   /// @brief Unary negation operator
443   inline APInt operator-() const {
444     return APInt(BitWidth, 0) - (*this);
445   }
446
447   /// Performs logical negation operation on this APInt.
448   /// @returns true if *this is zero, false otherwise.
449   /// @brief Logical negation operator. 
450   bool operator !() const;
451
452   /// @}
453   /// @name Assignment Operators
454   /// @{
455   /// @returns *this after assignment of RHS.
456   /// @brief Copy assignment operator. 
457   APInt& operator=(const APInt& RHS);
458
459   /// The RHS value is assigned to *this. If the significant bits in RHS exceed
460   /// the bit width, the excess bits are truncated. If the bit width is larger
461   /// than 64, the value is zero filled in the unspecified high order bits.
462   /// @returns *this after assignment of RHS value.
463   /// @brief Assignment operator. 
464   APInt& operator=(uint64_t RHS);
465
466   /// Performs a bitwise AND operation on this APInt and RHS. The result is
467   /// assigned to *this. 
468   /// @returns *this after ANDing with RHS.
469   /// @brief Bitwise AND assignment operator. 
470   APInt& operator&=(const APInt& RHS);
471
472   /// Performs a bitwise OR operation on this APInt and RHS. The result is 
473   /// assigned *this;
474   /// @returns *this after ORing with RHS.
475   /// @brief Bitwise OR assignment operator. 
476   APInt& operator|=(const APInt& RHS);
477
478   /// Performs a bitwise XOR operation on this APInt and RHS. The result is
479   /// assigned to *this.
480   /// @returns *this after XORing with RHS.
481   /// @brief Bitwise XOR assignment operator. 
482   APInt& operator^=(const APInt& RHS);
483
484   /// Multiplies this APInt by RHS and assigns the result to *this.
485   /// @returns *this
486   /// @brief Multiplication assignment operator. 
487   APInt& operator*=(const APInt& RHS);
488
489   /// Adds RHS to *this and assigns the result to *this.
490   /// @returns *this
491   /// @brief Addition assignment operator. 
492   APInt& operator+=(const APInt& RHS);
493
494   /// Subtracts RHS from *this and assigns the result to *this.
495   /// @returns *this
496   /// @brief Subtraction assignment operator. 
497   APInt& operator-=(const APInt& RHS);
498
499   /// Shifts *this left by shiftAmt and assigns the result to *this.
500   /// @returns *this after shifting left by shiftAmt
501   /// @brief Left-shift assignment function.
502   inline APInt& operator<<=(uint32_t shiftAmt) {
503     *this = shl(shiftAmt);
504     return *this;
505   }
506
507   /// @}
508   /// @name Binary Operators
509   /// @{
510   /// Performs a bitwise AND operation on *this and RHS.
511   /// @returns An APInt value representing the bitwise AND of *this and RHS.
512   /// @brief Bitwise AND operator. 
513   APInt operator&(const APInt& RHS) const;
514   APInt And(const APInt& RHS) const {
515     return this->operator&(RHS);
516   }
517
518   /// Performs a bitwise OR operation on *this and RHS.
519   /// @returns An APInt value representing the bitwise OR of *this and RHS.
520   /// @brief Bitwise OR operator. 
521   APInt operator|(const APInt& RHS) const;
522   APInt Or(const APInt& RHS) const {
523     return this->operator|(RHS);
524   }
525
526   /// Performs a bitwise XOR operation on *this and RHS.
527   /// @returns An APInt value representing the bitwise XOR of *this and RHS.
528   /// @brief Bitwise XOR operator. 
529   APInt operator^(const APInt& RHS) const;
530   APInt Xor(const APInt& RHS) const {
531     return this->operator^(RHS);
532   }
533
534   /// Multiplies this APInt by RHS and returns the result.
535   /// @brief Multiplication operator. 
536   APInt operator*(const APInt& RHS) const;
537
538   /// Adds RHS to this APInt and returns the result.
539   /// @brief Addition operator. 
540   APInt operator+(const APInt& RHS) const;
541   APInt operator+(uint64_t RHS) const {
542     return (*this) + APInt(BitWidth, RHS);
543   }
544
545   /// Subtracts RHS from this APInt and returns the result.
546   /// @brief Subtraction operator. 
547   APInt operator-(const APInt& RHS) const;
548   APInt operator-(uint64_t RHS) const {
549     return (*this) - APInt(BitWidth, RHS);
550   }
551
552   /// Arithmetic right-shift this APInt by shiftAmt.
553   /// @brief Arithmetic right-shift function.
554   APInt ashr(uint32_t shiftAmt) const;
555
556   /// Logical right-shift this APInt by shiftAmt.
557   /// @brief Logical right-shift function.
558   APInt lshr(uint32_t shiftAmt) const;
559
560   /// Left-shift this APInt by shiftAmt.
561   /// @brief Left-shift function.
562   APInt shl(uint32_t shiftAmt) const;
563
564   /// Perform an unsigned divide operation on this APInt by RHS. Both this and
565   /// RHS are treated as unsigned quantities for purposes of this division.
566   /// @returns a new APInt value containing the division result
567   /// @brief Unsigned division operation.
568   APInt udiv(const APInt& RHS) const;
569
570   /// Signed divide this APInt by APInt RHS.
571   /// @brief Signed division function for APInt.
572   inline APInt sdiv(const APInt& RHS) const {
573     if (isNegative())
574       if (RHS.isNegative())
575         return (-(*this)).udiv(-RHS);
576       else
577         return -((-(*this)).udiv(RHS));
578     else if (RHS.isNegative())
579       return -(this->udiv(-RHS));
580     return this->udiv(RHS);
581   }
582
583   /// Perform an unsigned remainder operation on this APInt with RHS being the
584   /// divisor. Both this and RHS are treated as unsigned quantities for purposes
585   /// of this operation. Note that this is a true remainder operation and not
586   /// a modulo operation because the sign follows the sign of the dividend
587   /// which is *this.
588   /// @returns a new APInt value containing the remainder result
589   /// @brief Unsigned remainder operation.
590   APInt urem(const APInt& RHS) const;
591
592   /// Signed remainder operation on APInt.
593   /// @brief Function for signed remainder operation.
594   inline APInt srem(const APInt& RHS) const {
595     if (isNegative())
596       if (RHS.isNegative())
597         return -((-(*this)).urem(-RHS));
598       else
599         return -((-(*this)).urem(RHS));
600     else if (RHS.isNegative())
601       return this->urem(-RHS);
602     return this->urem(RHS);
603   }
604
605   /// @returns the bit value at bitPosition
606   /// @brief Array-indexing support.
607   bool operator[](uint32_t bitPosition) const;
608
609   /// @}
610   /// @name Comparison Operators
611   /// @{
612   /// Compares this APInt with RHS for the validity of the equality
613   /// relationship.
614   /// @brief Equality operator. 
615   bool operator==(const APInt& RHS) const;
616
617   /// Compares this APInt with a uint64_t for the validity of the equality 
618   /// relationship.
619   /// @returns true if *this == Val
620   /// @brief Equality operator.
621   bool operator==(uint64_t Val) const;
622
623   /// Compares this APInt with RHS for the validity of the equality
624   /// relationship.
625   /// @returns true if *this == Val
626   /// @brief Equality comparison.
627   bool eq(const APInt &RHS) const {
628     return (*this) == RHS; 
629   }
630
631   /// Compares this APInt with RHS for the validity of the inequality
632   /// relationship.
633   /// @returns true if *this != Val
634   /// @brief Inequality operator. 
635   inline bool operator!=(const APInt& RHS) const {
636     return !((*this) == RHS);
637   }
638
639   /// Compares this APInt with a uint64_t for the validity of the inequality 
640   /// relationship.
641   /// @returns true if *this != Val
642   /// @brief Inequality operator. 
643   inline bool operator!=(uint64_t Val) const {
644     return !((*this) == Val);
645   }
646   
647   /// Compares this APInt with RHS for the validity of the inequality
648   /// relationship.
649   /// @returns true if *this != Val
650   /// @brief Inequality comparison
651   bool ne(const APInt &RHS) const {
652     return !((*this) == RHS);
653   }
654
655   /// Regards both *this and RHS as unsigned quantities and compares them for
656   /// the validity of the less-than relationship.
657   /// @returns true if *this < RHS when both are considered unsigned.
658   /// @brief Unsigned less than comparison
659   bool ult(const APInt& RHS) const;
660
661   /// Regards both *this and RHS as signed quantities and compares them for
662   /// validity of the less-than relationship.
663   /// @returns true if *this < RHS when both are considered signed.
664   /// @brief Signed less than comparison
665   bool slt(const APInt& RHS) const;
666
667   /// Regards both *this and RHS as unsigned quantities and compares them for
668   /// validity of the less-or-equal relationship.
669   /// @returns true if *this <= RHS when both are considered unsigned.
670   /// @brief Unsigned less or equal comparison
671   bool ule(const APInt& RHS) const {
672     return ult(RHS) || eq(RHS);
673   }
674
675   /// Regards both *this and RHS as signed quantities and compares them for
676   /// validity of the less-or-equal relationship.
677   /// @returns true if *this <= RHS when both are considered signed.
678   /// @brief Signed less or equal comparison
679   bool sle(const APInt& RHS) const {
680     return slt(RHS) || eq(RHS);
681   }
682
683   /// Regards both *this and RHS as unsigned quantities and compares them for
684   /// the validity of the greater-than relationship.
685   /// @returns true if *this > RHS when both are considered unsigned.
686   /// @brief Unsigned greather than comparison
687   bool ugt(const APInt& RHS) const {
688     return !ult(RHS) && !eq(RHS);
689   }
690
691   /// Regards both *this and RHS as signed quantities and compares them for
692   /// the validity of the greater-than relationship.
693   /// @returns true if *this > RHS when both are considered signed.
694   /// @brief Signed greather than comparison
695   bool sgt(const APInt& RHS) const {
696     return !slt(RHS) && !eq(RHS);
697   }
698
699   /// Regards both *this and RHS as unsigned quantities and compares them for
700   /// validity of the greater-or-equal relationship.
701   /// @returns true if *this >= RHS when both are considered unsigned.
702   /// @brief Unsigned greater or equal comparison
703   bool uge(const APInt& RHS) const {
704     return !ult(RHS);
705   }
706
707   /// Regards both *this and RHS as signed quantities and compares them for
708   /// validity of the greater-or-equal relationship.
709   /// @returns true if *this >= RHS when both are considered signed.
710   /// @brief Signed greather or equal comparison
711   bool sge(const APInt& RHS) const {
712     return !slt(RHS);
713   }
714
715   /// @}
716   /// @name Resizing Operators
717   /// @{
718   /// Truncate the APInt to a specified width. It is an error to specify a width
719   /// that is greater than or equal to the current width. 
720   /// @brief Truncate to new width.
721   APInt &trunc(uint32_t width);
722
723   /// This operation sign extends the APInt to a new width. If the high order
724   /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
725   /// It is an error to specify a width that is less than or equal to the 
726   /// current width.
727   /// @brief Sign extend to a new width.
728   APInt &sext(uint32_t width);
729
730   /// This operation zero extends the APInt to a new width. The high order bits
731   /// are filled with 0 bits.  It is an error to specify a width that is less 
732   /// than or equal to the current width.
733   /// @brief Zero extend to a new width.
734   APInt &zext(uint32_t width);
735
736   /// Make this APInt have the bit width given by \p width. The value is sign
737   /// extended, truncated, or left alone to make it that width.
738   /// @brief Sign extend or truncate to width
739   APInt &sextOrTrunc(uint32_t width);
740
741   /// Make this APInt have the bit width given by \p width. The value is zero
742   /// extended, truncated, or left alone to make it that width.
743   /// @brief Zero extend or truncate to width
744   APInt &zextOrTrunc(uint32_t width);
745
746   /// This is a help function for convenience. If the given \p width equals to
747   /// this APInt's BitWidth, just return this APInt, otherwise, just zero 
748   /// extend it.
749   inline APInt &zextOrCopy(uint32_t width) {
750     if (width == BitWidth)
751       return *this;
752     return zext(width);
753   }
754
755   /// @}
756   /// @name Bit Manipulation Operators
757   /// @{
758   /// @brief Set every bit to 1.
759   APInt& set();
760
761   /// Set the given bit to 1 whose position is given as "bitPosition".
762   /// @brief Set a given bit to 1.
763   APInt& set(uint32_t bitPosition);
764
765   /// @brief Set every bit to 0.
766   APInt& clear();
767
768   /// Set the given bit to 0 whose position is given as "bitPosition".
769   /// @brief Set a given bit to 0.
770   APInt& clear(uint32_t bitPosition);
771
772   /// @brief Toggle every bit to its opposite value.
773   APInt& flip();
774
775   /// Toggle a given bit to its opposite value whose position is given 
776   /// as "bitPosition".
777   /// @brief Toggles a given bit to its opposite value.
778   APInt& flip(uint32_t bitPosition);
779
780   /// @}
781   /// @name Value Characterization Functions
782   /// @{
783
784   /// @returns the total number of bits.
785   inline uint32_t getBitWidth() const { 
786     return BitWidth; 
787   }
788
789   /// Here one word's bitwidth equals to that of uint64_t.
790   /// @returns the number of words to hold the integer value of this APInt.
791   /// @brief Get the number of words.
792   inline uint32_t getNumWords() const {
793     return (BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
794   }
795
796   /// This function returns the number of active bits which is defined as the
797   /// bit width minus the number of leading zeros. This is used in several
798   /// computations to see how "wide" the value is.
799   /// @brief Compute the number of active bits in the value
800   inline uint32_t getActiveBits() const {
801     return BitWidth - countLeadingZeros();
802   }
803
804   /// This function returns the number of active words in the value of this
805   /// APInt. This is used in conjunction with getActiveData to extract the raw
806   /// value of the APInt.
807   inline uint32_t getActiveWords() const {
808     return whichWord(getActiveBits()-1) + 1;
809   }
810
811   /// Computes the minimum bit width for this APInt while considering it to be
812   /// a signed (and probably negative) value. If the value is not negative, 
813   /// this function returns the same value as getActiveBits(). Otherwise, it
814   /// returns the smallest bit width that will retain the negative value. For
815   /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
816   /// for -1, this function will always return 1.
817   /// @brief Get the minimum bit size for this signed APInt 
818   inline uint32_t getMinSignedBits() const {
819     if (isNegative())
820       return BitWidth - countLeadingOnes() + 1;
821     return getActiveBits();
822   }
823
824   /// This method attempts to return the value of this APInt as a zero extended
825   /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
826   /// uint64_t. Otherwise an assertion will result.
827   /// @brief Get zero extended value
828   inline uint64_t getZExtValue() const {
829     if (isSingleWord())
830       return VAL;
831     assert(getActiveBits() <= 64 && "Too many bits for uint64_t");
832     return pVal[0];
833   }
834
835   /// This method attempts to return the value of this APInt as a sign extended
836   /// int64_t. The bit width must be <= 64 or the value must fit within an
837   /// int64_t. Otherwise an assertion will result.
838   /// @brief Get sign extended value
839   inline int64_t getSExtValue() const {
840     if (isSingleWord())
841       return int64_t(VAL << (APINT_BITS_PER_WORD - BitWidth)) >> 
842                      (APINT_BITS_PER_WORD - BitWidth);
843     assert(getActiveBits() <= 64 && "Too many bits for int64_t");
844     return int64_t(pVal[0]);
845   }
846   /// countLeadingZeros - This function is an APInt version of the
847   /// countLeadingZeros_{32,64} functions in MathExtras.h. It counts the number
848   /// of zeros from the most significant bit to the first one bit.
849   /// @returns getNumWords() * APINT_BITS_PER_WORD if the value is zero.
850   /// @returns the number of zeros from the most significant bit to the first
851   /// one bits.
852   /// @brief Count the number of leading one bits.
853   uint32_t countLeadingZeros() const;
854
855   /// countLeadingOnes - This function counts the number of contiguous 1 bits
856   /// in the high order bits. The count stops when the first 0 bit is reached.
857   /// @returns 0 if the high order bit is not set
858   /// @returns the number of 1 bits from the most significant to the least
859   /// @brief Count the number of leading one bits.
860   uint32_t countLeadingOnes() const;
861
862   /// countTrailingZeros - This function is an APInt version of the 
863   /// countTrailingZoers_{32,64} functions in MathExtras.h. It counts 
864   /// the number of zeros from the least significant bit to the first one bit.
865   /// @returns getNumWords() * APINT_BITS_PER_WORD if the value is zero.
866   /// @returns the number of zeros from the least significant bit to the first
867   /// one bit.
868   /// @brief Count the number of trailing zero bits.
869   uint32_t countTrailingZeros() const;
870
871   /// countPopulation - This function is an APInt version of the
872   /// countPopulation_{32,64} functions in MathExtras.h. It counts the number
873   /// of 1 bits in the APInt value. 
874   /// @returns 0 if the value is zero.
875   /// @returns the number of set bits.
876   /// @brief Count the number of bits set.
877   uint32_t countPopulation() const; 
878
879   /// @}
880   /// @name Conversion Functions
881   /// @{
882
883   /// This is used internally to convert an APInt to a string.
884   /// @brief Converts an APInt to a std::string
885   std::string toString(uint8_t radix, bool wantSigned) const;
886
887   /// Considers the APInt to be unsigned and converts it into a string in the
888   /// radix given. The radix can be 2, 8, 10 or 16.
889   /// @returns a character interpretation of the APInt
890   /// @brief Convert unsigned APInt to string representation.
891   inline std::string toString(uint8_t radix = 10) const {
892     return toString(radix, false);
893   }
894
895   /// Considers the APInt to be unsigned and converts it into a string in the
896   /// radix given. The radix can be 2, 8, 10 or 16.
897   /// @returns a character interpretation of the APInt
898   /// @brief Convert unsigned APInt to string representation.
899   inline std::string toStringSigned(uint8_t radix = 10) const {
900     return toString(radix, true);
901   }
902
903   /// @returns a byte-swapped representation of this APInt Value.
904   APInt byteSwap() const;
905
906   /// @brief Converts this APInt to a double value.
907   double roundToDouble(bool isSigned) const;
908
909   /// @brief Converts this unsigned APInt to a double value.
910   double roundToDouble() const {
911     return roundToDouble(false);
912   }
913
914   /// @brief Converts this signed APInt to a double value.
915   double signedRoundToDouble() const {
916     return roundToDouble(true);
917   }
918
919   /// The conversion does not do a translation from integer to double, it just
920   /// re-interprets the bits as a double. Note that it is valid to do this on
921   /// any bit width. Exactly 64 bits will be translated.
922   /// @brief Converts APInt bits to a double
923   double bitsToDouble() const {
924     union {
925       uint64_t I;
926       double D;
927     } T;
928     T.I = (isSingleWord() ? VAL : pVal[0]);
929     return T.D;
930   }
931
932   /// The conversion does not do a translation from integer to float, it just
933   /// re-interprets the bits as a float. Note that it is valid to do this on
934   /// any bit width. Exactly 32 bits will be translated.
935   /// @brief Converts APInt bits to a double
936   float bitsToFloat() const {
937     union {
938       uint32_t I;
939       float F;
940     } T;
941     T.I = uint32_t((isSingleWord() ? VAL : pVal[0]));
942     return T.F;
943   }
944
945   /// The conversion does not do a translation from double to integer, it just
946   /// re-interprets the bits of the double. Note that it is valid to do this on
947   /// any bit width but bits from V may get truncated.
948   /// @brief Converts a double to APInt bits.
949   APInt& doubleToBits(double V) {
950     union {
951       uint64_t I;
952       double D;
953     } T;
954     T.D = V;
955     if (isSingleWord())
956       VAL = T.I;
957     else
958       pVal[0] = T.I;
959     return clearUnusedBits();
960   }
961
962   /// The conversion does not do a translation from float to integer, it just
963   /// re-interprets the bits of the float. Note that it is valid to do this on
964   /// any bit width but bits from V may get truncated.
965   /// @brief Converts a float to APInt bits.
966   APInt& floatToBits(float V) {
967     union {
968       uint32_t I;
969       float F;
970     } T;
971     T.F = V;
972     if (isSingleWord())
973       VAL = T.I;
974     else
975       pVal[0] = T.I;
976     return clearUnusedBits();
977   }
978
979   /// @}
980   /// @name Mathematics Operations
981   /// @{
982
983   /// @returns the floor log base 2 of this APInt.
984   inline uint32_t logBase2() const {
985     return BitWidth - 1 - countLeadingZeros();
986   }
987
988   /// @brief Compute the square root
989   APInt sqrt() const;
990
991   /// If *this is < 0 then return -(*this), otherwise *this;
992   /// @brief Get the absolute value;
993   APInt abs() const {
994     if (isNegative())
995       return -(*this);
996     return *this;
997   }
998   /// @}
999 };
1000
1001 inline bool operator==(uint64_t V1, const APInt& V2) {
1002   return V2 == V1;
1003 }
1004
1005 inline bool operator!=(uint64_t V1, const APInt& V2) {
1006   return V2 != V1;
1007 }
1008
1009 namespace APIntOps {
1010
1011 /// @brief Determine the smaller of two APInts considered to be signed.
1012 inline APInt smin(const APInt &A, const APInt &B) {
1013   return A.slt(B) ? A : B;
1014 }
1015
1016 /// @brief Determine the larger of two APInts considered to be signed.
1017 inline APInt smax(const APInt &A, const APInt &B) {
1018   return A.sgt(B) ? A : B;
1019 }
1020
1021 /// @brief Determine the smaller of two APInts considered to be signed.
1022 inline APInt umin(const APInt &A, const APInt &B) {
1023   return A.ult(B) ? A : B;
1024 }
1025
1026 /// @brief Determine the larger of two APInts considered to be unsigned.
1027 inline APInt umax(const APInt &A, const APInt &B) {
1028   return A.ugt(B) ? A : B;
1029 }
1030
1031 /// @brief Check if the specified APInt has a N-bits integer value.
1032 inline bool isIntN(uint32_t N, const APInt& APIVal) {
1033   return APIVal.isIntN(N);
1034 }
1035
1036 /// @returns true if the argument APInt value is a sequence of ones
1037 /// starting at the least significant bit with the remainder zero.
1038 inline const bool isMask(uint32_t numBits, const APInt& APIVal) {
1039   return APIVal.getBoolValue() && ((APIVal + APInt(numBits,1)) & APIVal) == 0;
1040 }
1041
1042 /// @returns true if the argument APInt value contains a sequence of ones
1043 /// with the remainder zero.
1044 inline const bool isShiftedMask(uint32_t numBits, const APInt& APIVal) {
1045   return isMask(numBits, (APIVal - APInt(numBits,1)) | APIVal);
1046 }
1047
1048 /// @returns a byte-swapped representation of the specified APInt Value.
1049 inline APInt byteSwap(const APInt& APIVal) {
1050   return APIVal.byteSwap();
1051 }
1052
1053 /// @returns the floor log base 2 of the specified APInt value.
1054 inline uint32_t logBase2(const APInt& APIVal) {
1055   return APIVal.logBase2(); 
1056 }
1057
1058 /// GreatestCommonDivisor - This function returns the greatest common
1059 /// divisor of the two APInt values using Enclid's algorithm.
1060 /// @returns the greatest common divisor of Val1 and Val2
1061 /// @brief Compute GCD of two APInt values.
1062 APInt GreatestCommonDivisor(const APInt& Val1, const APInt& Val2);
1063
1064 /// Treats the APInt as an unsigned value for conversion purposes.
1065 /// @brief Converts the given APInt to a double value.
1066 inline double RoundAPIntToDouble(const APInt& APIVal) {
1067   return APIVal.roundToDouble();
1068 }
1069
1070 /// Treats the APInt as a signed value for conversion purposes.
1071 /// @brief Converts the given APInt to a double value.
1072 inline double RoundSignedAPIntToDouble(const APInt& APIVal) {
1073   return APIVal.signedRoundToDouble();
1074 }
1075
1076 /// @brief Converts the given APInt to a float vlalue.
1077 inline float RoundAPIntToFloat(const APInt& APIVal) {
1078   return float(RoundAPIntToDouble(APIVal));
1079 }
1080
1081 /// Treast the APInt as a signed value for conversion purposes.
1082 /// @brief Converts the given APInt to a float value.
1083 inline float RoundSignedAPIntToFloat(const APInt& APIVal) {
1084   return float(APIVal.signedRoundToDouble());
1085 }
1086
1087 /// RoundDoubleToAPInt - This function convert a double value to an APInt value.
1088 /// @brief Converts the given double value into a APInt.
1089 APInt RoundDoubleToAPInt(double Double, uint32_t width);
1090
1091 /// RoundFloatToAPInt - Converts a float value into an APInt value.
1092 /// @brief Converts a float value into a APInt.
1093 inline APInt RoundFloatToAPInt(float Float, uint32_t width) {
1094   return RoundDoubleToAPInt(double(Float), width);
1095 }
1096
1097 /// Arithmetic right-shift the APInt by shiftAmt.
1098 /// @brief Arithmetic right-shift function.
1099 inline APInt ashr(const APInt& LHS, uint32_t shiftAmt) {
1100   return LHS.ashr(shiftAmt);
1101 }
1102
1103 /// Logical right-shift the APInt by shiftAmt.
1104 /// @brief Logical right-shift function.
1105 inline APInt lshr(const APInt& LHS, uint32_t shiftAmt) {
1106   return LHS.lshr(shiftAmt);
1107 }
1108
1109 /// Left-shift the APInt by shiftAmt.
1110 /// @brief Left-shift function.
1111 inline APInt shl(const APInt& LHS, uint32_t shiftAmt) {
1112   return LHS.shl(shiftAmt);
1113 }
1114
1115 /// Signed divide APInt LHS by APInt RHS.
1116 /// @brief Signed division function for APInt.
1117 inline APInt sdiv(const APInt& LHS, const APInt& RHS) {
1118   return LHS.sdiv(RHS);
1119 }
1120
1121 /// Unsigned divide APInt LHS by APInt RHS.
1122 /// @brief Unsigned division function for APInt.
1123 inline APInt udiv(const APInt& LHS, const APInt& RHS) {
1124   return LHS.udiv(RHS);
1125 }
1126
1127 /// Signed remainder operation on APInt.
1128 /// @brief Function for signed remainder operation.
1129 inline APInt srem(const APInt& LHS, const APInt& RHS) {
1130   return LHS.srem(RHS);
1131 }
1132
1133 /// Unsigned remainder operation on APInt.
1134 /// @brief Function for unsigned remainder operation.
1135 inline APInt urem(const APInt& LHS, const APInt& RHS) {
1136   return LHS.urem(RHS);
1137 }
1138
1139 /// Performs multiplication on APInt values.
1140 /// @brief Function for multiplication operation.
1141 inline APInt mul(const APInt& LHS, const APInt& RHS) {
1142   return LHS * RHS;
1143 }
1144
1145 /// Performs addition on APInt values.
1146 /// @brief Function for addition operation.
1147 inline APInt add(const APInt& LHS, const APInt& RHS) {
1148   return LHS + RHS;
1149 }
1150
1151 /// Performs subtraction on APInt values.
1152 /// @brief Function for subtraction operation.
1153 inline APInt sub(const APInt& LHS, const APInt& RHS) {
1154   return LHS - RHS;
1155 }
1156
1157 /// Performs bitwise AND operation on APInt LHS and 
1158 /// APInt RHS.
1159 /// @brief Bitwise AND function for APInt.
1160 inline APInt And(const APInt& LHS, const APInt& RHS) {
1161   return LHS & RHS;
1162 }
1163
1164 /// Performs bitwise OR operation on APInt LHS and APInt RHS.
1165 /// @brief Bitwise OR function for APInt. 
1166 inline APInt Or(const APInt& LHS, const APInt& RHS) {
1167   return LHS | RHS;
1168 }
1169
1170 /// Performs bitwise XOR operation on APInt.
1171 /// @brief Bitwise XOR function for APInt.
1172 inline APInt Xor(const APInt& LHS, const APInt& RHS) {
1173   return LHS ^ RHS;
1174
1175
1176 /// Performs a bitwise complement operation on APInt.
1177 /// @brief Bitwise complement function. 
1178 inline APInt Not(const APInt& APIVal) {
1179   return ~APIVal;
1180 }
1181
1182 } // End of APIntOps namespace
1183
1184 } // End of llvm namespace
1185
1186 #endif