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