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