a6ec167da3559a862802b44cae1e180b9a23169f
[oota-llvm.git] / include / llvm / ADT / APInt.h
1 //===-- llvm/ADT/APInt.h - For Arbitrary Precision Integer -----*- C++ -*--===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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 #define COMPILE_TIME_ASSERT(cond) extern int CTAssert[(cond) ? 1 : -1]
23
24 namespace llvm {
25   class Serializer;
26   class Deserializer;
27   class FoldingSetNodeID;
28   
29   /* An unsigned host type used as a single part of a multi-part
30      bignum.  */
31   typedef uint64_t integerPart;
32
33   const unsigned int host_char_bit = 8;
34   const unsigned int integerPartWidth = host_char_bit * sizeof(integerPart);
35
36 //===----------------------------------------------------------------------===//
37 //                              APInt Class
38 //===----------------------------------------------------------------------===//
39
40 /// APInt - This class represents arbitrary precision constant integral values.
41 /// It is a functional replacement for common case unsigned integer type like 
42 /// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width 
43 /// integer sizes and large integer value types such as 3-bits, 15-bits, or more
44 /// than 64-bits of precision. APInt provides a variety of arithmetic operators 
45 /// and methods to manipulate integer values of any bit-width. It supports both
46 /// the typical integer arithmetic and comparison operations as well as bitwise
47 /// manipulation.
48 ///
49 /// The class has several invariants worth noting:
50 ///   * All bit, byte, and word positions are zero-based.
51 ///   * Once the bit width is set, it doesn't change except by the Truncate, 
52 ///     SignExtend, or ZeroExtend operations.
53 ///   * All binary operators must be on APInt instances of the same bit width.
54 ///     Attempting to use these operators on instances with different bit 
55 ///     widths will yield an assertion.
56 ///   * The value is stored canonically as an unsigned value. For operations
57 ///     where it makes a difference, there are both signed and unsigned variants
58 ///     of the operation. For example, sdiv and udiv. However, because the bit
59 ///     widths must be the same, operations such as Mul and Add produce the same
60 ///     results regardless of whether the values are interpreted as signed or
61 ///     not.
62 ///   * In general, the class tries to follow the style of computation that LLVM
63 ///     uses in its IR. This simplifies its use for LLVM.
64 ///
65 /// @brief Class for arbitrary precision integers.
66 class APInt {
67
68   uint32_t BitWidth;      ///< The number of bits in this APInt.
69
70   /// This union is used to store the integer value. When the
71   /// integer bit-width <= 64, it uses VAL, otherwise it uses pVal.
72   union {
73     uint64_t VAL;    ///< Used to store the <= 64 bits integer value.
74     uint64_t *pVal;  ///< Used to store the >64 bits integer value.
75   };
76
77   /// This enum is used to hold the constants we needed for APInt.
78   enum {
79     APINT_BITS_PER_WORD = sizeof(uint64_t) * 8, ///< Bits in a word
80     APINT_WORD_SIZE = sizeof(uint64_t)          ///< Byte size of a word
81   };
82
83   /// This constructor is used only internally for speed of construction of
84   /// temporaries. It is unsafe for general use so it is not public.
85   /// @brief Fast internal constructor
86   APInt(uint64_t* val, uint32_t bits) : BitWidth(bits), pVal(val) { }
87
88   /// @returns true if the number of bits <= 64, false otherwise.
89   /// @brief Determine if this APInt just has one word to store value.
90   inline bool isSingleWord() const { 
91     return BitWidth <= APINT_BITS_PER_WORD; 
92   }
93
94   /// @returns the word position for the specified bit position.
95   /// @brief Determine which word a bit is in.
96   static inline uint32_t whichWord(uint32_t bitPosition) { 
97     return bitPosition / APINT_BITS_PER_WORD; 
98   }
99
100   /// @returns the bit position in a word for the specified bit position 
101   /// in the APInt.
102   /// @brief Determine which bit in a word a bit is in.
103   static inline uint32_t whichBit(uint32_t bitPosition) { 
104     return bitPosition % APINT_BITS_PER_WORD; 
105   }
106
107   /// This method generates and returns a uint64_t (word) mask for a single 
108   /// bit at a specific bit position. This is used to mask the bit in the 
109   /// corresponding word.
110   /// @returns a uint64_t with only bit at "whichBit(bitPosition)" set
111   /// @brief Get a single bit mask.
112   static inline uint64_t maskBit(uint32_t bitPosition) { 
113     return 1ULL << whichBit(bitPosition); 
114   }
115
116   /// This method is used internally to clear the to "N" bits in the high order
117   /// word that are not used by the APInt. This is needed after the most 
118   /// significant word is assigned a value to ensure that those bits are 
119   /// zero'd out.
120   /// @brief Clear unused high order bits
121   inline APInt& clearUnusedBits() {
122     // Compute how many bits are used in the final word
123     uint32_t wordBits = BitWidth % APINT_BITS_PER_WORD;
124     if (wordBits == 0)
125       // If all bits are used, we want to leave the value alone. This also
126       // avoids the undefined behavior of >> when the shfit is the same size as
127       // the word size (64).
128       return *this;
129
130     // Mask out the hight bits.
131     uint64_t mask = ~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - wordBits);
132     if (isSingleWord())
133       VAL &= mask;
134     else
135       pVal[getNumWords() - 1] &= mask;
136     return *this;
137   }
138
139   /// @returns the corresponding word for the specified bit position.
140   /// @brief Get the word corresponding to a bit position
141   inline uint64_t getWord(uint32_t bitPosition) const { 
142     return isSingleWord() ? VAL : pVal[whichWord(bitPosition)]; 
143   }
144
145   /// This is used by the constructors that take string arguments.
146   /// @brief Convert a char array into an APInt
147   void fromString(uint32_t numBits, const char *strStart, uint32_t slen, 
148                   uint8_t radix);
149
150   /// This is used by the toString method to divide by the radix. It simply
151   /// provides a more convenient form of divide for internal use since KnuthDiv
152   /// has specific constraints on its inputs. If those constraints are not met
153   /// then it provides a simpler form of divide.
154   /// @brief An internal division function for dividing APInts.
155   static void divide(const APInt LHS, uint32_t lhsWords, 
156                      const APInt &RHS, uint32_t rhsWords,
157                      APInt *Quotient, APInt *Remainder);
158
159 public:
160   /// @name Constructors
161   /// @{
162   /// If isSigned is true then val is treated as if it were a signed value
163   /// (i.e. as an int64_t) and the appropriate sign extension to the bit width
164   /// will be done. Otherwise, no sign extension occurs (high order bits beyond
165   /// the range of val are zero filled).
166   /// @param numBits the bit width of the constructed APInt
167   /// @param val the initial value of the APInt
168   /// @param isSigned how to treat signedness of val
169   /// @brief Create a new APInt of numBits width, initialized as val.
170   APInt(uint32_t numBits, uint64_t val, bool isSigned = false);
171
172   /// Note that numWords can be smaller or larger than the corresponding bit
173   /// width but any extraneous bits will be dropped.
174   /// @param numBits the bit width of the constructed APInt
175   /// @param numWords the number of words in bigVal
176   /// @param bigVal a sequence of words to form the initial value of the APInt
177   /// @brief Construct an APInt of numBits width, initialized as bigVal[].
178   APInt(uint32_t numBits, uint32_t numWords, const uint64_t bigVal[]);
179
180   /// This constructor interprets Val as a string in the given radix. The 
181   /// interpretation stops when the first charater that is not suitable for the
182   /// radix is encountered. Acceptable radix values are 2, 8, 10 and 16. It is
183   /// an error for the value implied by the string to require more bits than 
184   /// numBits.
185   /// @param numBits the bit width of the constructed APInt
186   /// @param val the string to be interpreted
187   /// @param radix the radix of Val to use for the intepretation
188   /// @brief Construct an APInt from a string representation.
189   APInt(uint32_t numBits, const std::string& val, uint8_t radix);
190
191   /// This constructor interprets the slen characters starting at StrStart as
192   /// a string in the given radix. The interpretation stops when the first 
193   /// character that is not suitable for the radix is encountered. Acceptable
194   /// radix values are 2, 8, 10 and 16. It is an error for the value implied by
195   /// the string to require more bits than numBits.
196   /// @param numBits the bit width of the constructed APInt
197   /// @param strStart the start of the string to be interpreted
198   /// @param slen the maximum number of characters to interpret
199   /// @param radix the radix to use for the conversion
200   /// @brief Construct an APInt from a string representation.
201   APInt(uint32_t numBits, const char strStart[], uint32_t slen, uint8_t radix);
202
203   /// Simply makes *this a copy of that.
204   /// @brief Copy Constructor.
205   APInt(const APInt& that);
206
207   /// @brief Destructor.
208   ~APInt();
209   
210   /// Default constructor that creates an uninitialized APInt.  This is useful
211   ///  for object deserialization (pair this with the static method Read).
212   explicit APInt() : BitWidth(1) {}
213   
214   /// Profile - Used to insert APInt objects, or objects that contain APInt 
215   ///  objects, into FoldingSets.
216   void Profile(FoldingSetNodeID& id) const;
217   
218   /// @brief Used by the Bitcode serializer to emit APInts to Bitcode.
219   void Emit(Serializer& S) const;
220   
221   /// @brief Used by the Bitcode deserializer to deserialize APInts.
222   void Read(Deserializer& D);
223
224   /// @}
225   /// @name Value Tests
226   /// @{
227   /// This tests the high bit of this APInt to determine if it is set.
228   /// @returns true if this APInt is negative, false otherwise
229   /// @brief Determine sign of this APInt.
230   bool isNegative() const {
231     return (*this)[BitWidth - 1];
232   }
233
234   /// This tests the high bit of the APInt to determine if it is unset.
235   /// @brief Determine if this APInt Value is positive (not negative).
236   bool isPositive() const {
237     return !isNegative();
238   }
239
240   /// This tests if the value of this APInt is strictly positive (> 0).
241   /// @returns true if this APInt is Positive and not zero.
242   /// @brief Determine if this APInt Value is strictly positive.
243   inline bool isStrictlyPositive() const {
244     return isPositive() && (*this) != 0;
245   }
246
247   /// This checks to see if the value has all bits of the APInt are set or not.
248   /// @brief Determine if all bits are set
249   inline bool isAllOnesValue() const {
250     return countPopulation() == BitWidth;
251   }
252
253   /// This checks to see if the value of this APInt is the maximum unsigned
254   /// value for the APInt's bit width.
255   /// @brief Determine if this is the largest unsigned value.
256   bool isMaxValue() const {
257     return countPopulation() == BitWidth;
258   }
259
260   /// This checks to see if the value of this APInt is the maximum signed
261   /// value for the APInt's bit width.
262   /// @brief Determine if this is the largest signed value.
263   bool isMaxSignedValue() const {
264     return BitWidth == 1 ? VAL == 0 :
265                           !isNegative() && countPopulation() == BitWidth - 1;
266   }
267
268   /// This checks to see if the value of this APInt is the minimum unsigned
269   /// value for the APInt's bit width.
270   /// @brief Determine if this is the smallest unsigned value.
271   bool isMinValue() const {
272     return countPopulation() == 0;
273   }
274
275   /// This checks to see if the value of this APInt is the minimum signed
276   /// value for the APInt's bit width.
277   /// @brief Determine if this is the smallest signed value.
278   bool isMinSignedValue() const {
279     return BitWidth == 1 ? VAL == 1 :
280                            isNegative() && countPopulation() == 1;
281   }
282
283   /// @brief Check if this APInt has an N-bits integer value.
284   inline bool isIntN(uint32_t N) const {
285     assert(N && "N == 0 ???");
286     if (isSingleWord()) {
287       return VAL == (VAL & (~0ULL >> (64 - N)));
288     } else {
289       APInt Tmp(N, getNumWords(), pVal);
290       return Tmp == (*this);
291     }
292   }
293
294   /// @returns true if the argument APInt value is a power of two > 0.
295   bool isPowerOf2() const; 
296
297   /// isSignBit - Return true if this is the value returned by getSignBit.
298   bool isSignBit() const { return isMinSignedValue(); }
299   
300   /// This converts the APInt to a boolean value as a test against zero.
301   /// @brief Boolean conversion function. 
302   inline bool getBoolValue() const {
303     return *this != 0;
304   }
305
306   /// getLimitedValue - If this value is smaller than the specified limit,
307   /// return it, otherwise return the limit value.  This causes the value
308   /// to saturate to the limit.
309   uint64_t getLimitedValue(uint64_t Limit = ~0ULL) const {
310     return (getActiveBits() > 64 || getZExtValue() > Limit) ?
311       Limit :  getZExtValue();
312   }
313
314   /// @}
315   /// @name Value Generators
316   /// @{
317   /// @brief Gets maximum unsigned value of APInt for specific bit width.
318   static APInt getMaxValue(uint32_t numBits) {
319     return APInt(numBits, 0).set();
320   }
321
322   /// @brief Gets maximum signed value of APInt for a specific bit width.
323   static APInt getSignedMaxValue(uint32_t numBits) {
324     return APInt(numBits, 0).set().clear(numBits - 1);
325   }
326
327   /// @brief Gets minimum unsigned value of APInt for a specific bit width.
328   static APInt getMinValue(uint32_t numBits) {
329     return APInt(numBits, 0);
330   }
331
332   /// @brief Gets minimum signed value of APInt for a specific bit width.
333   static APInt getSignedMinValue(uint32_t numBits) {
334     return APInt(numBits, 0).set(numBits - 1);
335   }
336
337   /// getSignBit - This is just a wrapper function of getSignedMinValue(), and
338   /// it helps code readability when we want to get a SignBit.
339   /// @brief Get the SignBit for a specific bit width.
340   inline static APInt getSignBit(uint32_t BitWidth) {
341     return getSignedMinValue(BitWidth);
342   }
343
344   /// @returns the all-ones value for an APInt of the specified bit-width.
345   /// @brief Get the all-ones value.
346   static APInt getAllOnesValue(uint32_t numBits) {
347     return APInt(numBits, 0).set();
348   }
349
350   /// @returns the '0' value for an APInt of the specified bit-width.
351   /// @brief Get the '0' value.
352   static APInt getNullValue(uint32_t numBits) {
353     return APInt(numBits, 0);
354   }
355
356   /// Get an APInt with the same BitWidth as this APInt, just zero mask
357   /// the low bits and right shift to the least significant bit.
358   /// @returns the high "numBits" bits of this APInt.
359   APInt getHiBits(uint32_t numBits) const;
360
361   /// Get an APInt with the same BitWidth as this APInt, just zero mask
362   /// the high bits.
363   /// @returns the low "numBits" bits of this APInt.
364   APInt getLoBits(uint32_t numBits) const;
365
366   /// Constructs an APInt value that has a contiguous range of bits set. The
367   /// bits from loBit to hiBit will be set. All other bits will be zero. For
368   /// example, with parameters(32, 15, 0) you would get 0x0000FFFF. If hiBit is
369   /// less than loBit then the set bits "wrap". For example, with 
370   /// parameters (32, 3, 28), you would get 0xF000000F. 
371   /// @param numBits the intended bit width of the result
372   /// @param loBit the index of the lowest bit set.
373   /// @param hiBit the index of the highest bit set.
374   /// @returns An APInt value with the requested bits set.
375   /// @brief Get a value with a block of bits set.
376   static APInt getBitsSet(uint32_t numBits, uint32_t loBit, uint32_t hiBit) {
377     assert(hiBit < numBits && "hiBit out of range");
378     assert(loBit < numBits && "loBit out of range");
379     if (hiBit < loBit)
380       return getLowBitsSet(numBits, hiBit+1) |
381              getHighBitsSet(numBits, numBits-loBit+1);
382     return getLowBitsSet(numBits, hiBit-loBit+1).shl(loBit);
383   }
384
385   /// Constructs an APInt value that has the top hiBitsSet bits set.
386   /// @param numBits the bitwidth of the result
387   /// @param hiBitsSet the number of high-order bits set in the result.
388   /// @brief Get a value with high bits set
389   static APInt getHighBitsSet(uint32_t numBits, uint32_t hiBitsSet) {
390     assert(hiBitsSet <= numBits && "Too many bits to set!");
391     // Handle a degenerate case, to avoid shifting by word size
392     if (hiBitsSet == 0)
393       return APInt(numBits, 0);
394     uint32_t shiftAmt = numBits - hiBitsSet;
395     // For small values, return quickly
396     if (numBits <= APINT_BITS_PER_WORD)
397       return APInt(numBits, ~0ULL << shiftAmt);
398     return (~APInt(numBits, 0)).shl(shiftAmt);
399   }
400
401   /// Constructs an APInt value that has the bottom loBitsSet bits set.
402   /// @param numBits the bitwidth of the result
403   /// @param loBitsSet the number of low-order bits set in the result.
404   /// @brief Get a value with low bits set
405   static APInt getLowBitsSet(uint32_t numBits, uint32_t loBitsSet) {
406     assert(loBitsSet <= numBits && "Too many bits to set!");
407     // Handle a degenerate case, to avoid shifting by word size
408     if (loBitsSet == 0)
409       return APInt(numBits, 0);
410     if (loBitsSet == APINT_BITS_PER_WORD)
411       return APInt(numBits, -1ULL);
412     // For small values, return quickly
413     if (numBits < APINT_BITS_PER_WORD)
414       return APInt(numBits, (1ULL << loBitsSet) - 1);
415     return (~APInt(numBits, 0)).lshr(numBits - loBitsSet);
416   }
417
418   /// The hash value is computed as the sum of the words and the bit width.
419   /// @returns A hash value computed from the sum of the APInt words.
420   /// @brief Get a hash value based on this APInt
421   uint64_t getHashValue() const;
422
423   /// This function returns a pointer to the internal storage of the APInt. 
424   /// This is useful for writing out the APInt in binary form without any
425   /// conversions.
426   inline const uint64_t* getRawData() const {
427     if (isSingleWord())
428       return &VAL;
429     return &pVal[0];
430   }
431
432   /// @}
433   /// @name Unary Operators
434   /// @{
435   /// @returns a new APInt value representing *this incremented by one
436   /// @brief Postfix increment operator.
437   inline const APInt operator++(int) {
438     APInt API(*this);
439     ++(*this);
440     return API;
441   }
442
443   /// @returns *this incremented by one
444   /// @brief Prefix increment operator.
445   APInt& operator++();
446
447   /// @returns a new APInt representing *this decremented by one.
448   /// @brief Postfix decrement operator. 
449   inline const APInt operator--(int) {
450     APInt API(*this);
451     --(*this);
452     return API;
453   }
454
455   /// @returns *this decremented by one.
456   /// @brief Prefix decrement operator. 
457   APInt& operator--();
458
459   /// Performs a bitwise complement operation on this APInt. 
460   /// @returns an APInt that is the bitwise complement of *this
461   /// @brief Unary bitwise complement operator. 
462   APInt operator~() const;
463
464   /// Negates *this using two's complement logic.
465   /// @returns An APInt value representing the negation of *this.
466   /// @brief Unary negation operator
467   inline APInt operator-() const {
468     return APInt(BitWidth, 0) - (*this);
469   }
470
471   /// Performs logical negation operation on this APInt.
472   /// @returns true if *this is zero, false otherwise.
473   /// @brief Logical negation operator. 
474   bool operator !() const;
475
476   /// @}
477   /// @name Assignment Operators
478   /// @{
479   /// @returns *this after assignment of RHS.
480   /// @brief Copy assignment operator. 
481   APInt& operator=(const APInt& RHS);
482
483   /// The RHS value is assigned to *this. If the significant bits in RHS exceed
484   /// the bit width, the excess bits are truncated. If the bit width is larger
485   /// than 64, the value is zero filled in the unspecified high order bits.
486   /// @returns *this after assignment of RHS value.
487   /// @brief Assignment operator. 
488   APInt& operator=(uint64_t RHS);
489
490   /// Performs a bitwise AND operation on this APInt and RHS. The result is
491   /// assigned to *this. 
492   /// @returns *this after ANDing with RHS.
493   /// @brief Bitwise AND assignment operator. 
494   APInt& operator&=(const APInt& RHS);
495
496   /// Performs a bitwise OR operation on this APInt and RHS. The result is 
497   /// assigned *this;
498   /// @returns *this after ORing with RHS.
499   /// @brief Bitwise OR assignment operator. 
500   APInt& operator|=(const APInt& RHS);
501
502   /// Performs a bitwise XOR operation on this APInt and RHS. The result is
503   /// assigned to *this.
504   /// @returns *this after XORing with RHS.
505   /// @brief Bitwise XOR assignment operator. 
506   APInt& operator^=(const APInt& RHS);
507
508   /// Multiplies this APInt by RHS and assigns the result to *this.
509   /// @returns *this
510   /// @brief Multiplication assignment operator. 
511   APInt& operator*=(const APInt& RHS);
512
513   /// Adds RHS to *this and assigns the result to *this.
514   /// @returns *this
515   /// @brief Addition assignment operator. 
516   APInt& operator+=(const APInt& RHS);
517
518   /// Subtracts RHS from *this and assigns the result to *this.
519   /// @returns *this
520   /// @brief Subtraction assignment operator. 
521   APInt& operator-=(const APInt& RHS);
522
523   /// Shifts *this left by shiftAmt and assigns the result to *this.
524   /// @returns *this after shifting left by shiftAmt
525   /// @brief Left-shift assignment function.
526   inline APInt& operator<<=(uint32_t shiftAmt) {
527     *this = shl(shiftAmt);
528     return *this;
529   }
530
531   /// @}
532   /// @name Binary Operators
533   /// @{
534   /// Performs a bitwise AND operation on *this and RHS.
535   /// @returns An APInt value representing the bitwise AND of *this and RHS.
536   /// @brief Bitwise AND operator. 
537   APInt operator&(const APInt& RHS) const;
538   APInt And(const APInt& RHS) const {
539     return this->operator&(RHS);
540   }
541
542   /// Performs a bitwise OR operation on *this and RHS.
543   /// @returns An APInt value representing the bitwise OR of *this and RHS.
544   /// @brief Bitwise OR operator. 
545   APInt operator|(const APInt& RHS) const;
546   APInt Or(const APInt& RHS) const {
547     return this->operator|(RHS);
548   }
549
550   /// Performs a bitwise XOR operation on *this and RHS.
551   /// @returns An APInt value representing the bitwise XOR of *this and RHS.
552   /// @brief Bitwise XOR operator. 
553   APInt operator^(const APInt& RHS) const;
554   APInt Xor(const APInt& RHS) const {
555     return this->operator^(RHS);
556   }
557
558   /// Multiplies this APInt by RHS and returns the result.
559   /// @brief Multiplication operator. 
560   APInt operator*(const APInt& RHS) const;
561
562   /// Adds RHS to this APInt and returns the result.
563   /// @brief Addition operator. 
564   APInt operator+(const APInt& RHS) const;
565   APInt operator+(uint64_t RHS) const {
566     return (*this) + APInt(BitWidth, RHS);
567   }
568
569   /// Subtracts RHS from this APInt and returns the result.
570   /// @brief Subtraction operator. 
571   APInt operator-(const APInt& RHS) const;
572   APInt operator-(uint64_t RHS) const {
573     return (*this) - APInt(BitWidth, RHS);
574   }
575   
576   APInt operator<<(unsigned Bits) const {
577     return shl(Bits);
578   }
579
580   /// Arithmetic right-shift this APInt by shiftAmt.
581   /// @brief Arithmetic right-shift function.
582   APInt ashr(uint32_t shiftAmt) const;
583
584   /// Logical right-shift this APInt by shiftAmt.
585   /// @brief Logical right-shift function.
586   APInt lshr(uint32_t shiftAmt) const;
587
588   /// Left-shift this APInt by shiftAmt.
589   /// @brief Left-shift function.
590   APInt shl(uint32_t shiftAmt) const;
591
592   /// @brief Rotate left by rotateAmt.
593   APInt rotl(uint32_t rotateAmt) const;
594
595   /// @brief Rotate right by rotateAmt.
596   APInt rotr(uint32_t rotateAmt) const;
597
598   /// Perform an unsigned divide operation on this APInt by RHS. Both this and
599   /// RHS are treated as unsigned quantities for purposes of this division.
600   /// @returns a new APInt value containing the division result
601   /// @brief Unsigned division operation.
602   APInt udiv(const APInt& RHS) const;
603
604   /// Signed divide this APInt by APInt RHS.
605   /// @brief Signed division function for APInt.
606   inline APInt sdiv(const APInt& RHS) const {
607     if (isNegative())
608       if (RHS.isNegative())
609         return (-(*this)).udiv(-RHS);
610       else
611         return -((-(*this)).udiv(RHS));
612     else if (RHS.isNegative())
613       return -(this->udiv(-RHS));
614     return this->udiv(RHS);
615   }
616
617   /// Perform an unsigned remainder operation on this APInt with RHS being the
618   /// divisor. Both this and RHS are treated as unsigned quantities for purposes
619   /// of this operation. Note that this is a true remainder operation and not
620   /// a modulo operation because the sign follows the sign of the dividend
621   /// which is *this.
622   /// @returns a new APInt value containing the remainder result
623   /// @brief Unsigned remainder operation.
624   APInt urem(const APInt& RHS) const;
625
626   /// Signed remainder operation on APInt.
627   /// @brief Function for signed remainder operation.
628   inline APInt srem(const APInt& RHS) const {
629     if (isNegative())
630       if (RHS.isNegative())
631         return -((-(*this)).urem(-RHS));
632       else
633         return -((-(*this)).urem(RHS));
634     else if (RHS.isNegative())
635       return this->urem(-RHS);
636     return this->urem(RHS);
637   }
638
639   /// Sometimes it is convenient to divide two APInt values and obtain both
640   /// the quotient and remainder. This function does both operations in the
641   /// same computation making it a little more efficient.
642   /// @brief Dual division/remainder interface.
643   static void udivrem(const APInt &LHS, const APInt &RHS, 
644                       APInt &Quotient, APInt &Remainder);
645
646   static void sdivrem(const APInt &LHS, const APInt &RHS,
647                       APInt &Quotient, APInt &Remainder)
648   {
649     if (LHS.isNegative()) {
650       if (RHS.isNegative())
651         APInt::udivrem(-LHS, -RHS, Quotient, Remainder);
652       else
653         APInt::udivrem(-LHS, RHS, Quotient, Remainder);
654       Quotient = -Quotient;
655       Remainder = -Remainder;
656     } else if (RHS.isNegative()) {
657       APInt::udivrem(LHS, -RHS, Quotient, Remainder);
658       Quotient = -Quotient;
659     } else {
660       APInt::udivrem(LHS, RHS, Quotient, Remainder);
661     }
662   }
663
664   /// @returns the bit value at bitPosition
665   /// @brief Array-indexing support.
666   bool operator[](uint32_t bitPosition) const;
667
668   /// @}
669   /// @name Comparison Operators
670   /// @{
671   /// Compares this APInt with RHS for the validity of the equality
672   /// relationship.
673   /// @brief Equality operator. 
674   bool operator==(const APInt& RHS) const;
675
676   /// Compares this APInt with a uint64_t for the validity of the equality 
677   /// relationship.
678   /// @returns true if *this == Val
679   /// @brief Equality operator.
680   bool operator==(uint64_t Val) const;
681
682   /// Compares this APInt with RHS for the validity of the equality
683   /// relationship.
684   /// @returns true if *this == Val
685   /// @brief Equality comparison.
686   bool eq(const APInt &RHS) const {
687     return (*this) == RHS; 
688   }
689
690   /// Compares this APInt with RHS for the validity of the inequality
691   /// relationship.
692   /// @returns true if *this != Val
693   /// @brief Inequality operator. 
694   inline bool operator!=(const APInt& RHS) const {
695     return !((*this) == RHS);
696   }
697
698   /// Compares this APInt with a uint64_t for the validity of the inequality 
699   /// relationship.
700   /// @returns true if *this != Val
701   /// @brief Inequality operator. 
702   inline bool operator!=(uint64_t Val) const {
703     return !((*this) == Val);
704   }
705   
706   /// Compares this APInt with RHS for the validity of the inequality
707   /// relationship.
708   /// @returns true if *this != Val
709   /// @brief Inequality comparison
710   bool ne(const APInt &RHS) const {
711     return !((*this) == RHS);
712   }
713
714   /// Regards both *this and RHS as unsigned quantities and compares them for
715   /// the validity of the less-than relationship.
716   /// @returns true if *this < RHS when both are considered unsigned.
717   /// @brief Unsigned less than comparison
718   bool ult(const APInt& RHS) const;
719
720   /// Regards both *this and RHS as signed quantities and compares them for
721   /// validity of the less-than relationship.
722   /// @returns true if *this < RHS when both are considered signed.
723   /// @brief Signed less than comparison
724   bool slt(const APInt& RHS) const;
725
726   /// Regards both *this and RHS as unsigned quantities and compares them for
727   /// validity of the less-or-equal relationship.
728   /// @returns true if *this <= RHS when both are considered unsigned.
729   /// @brief Unsigned less or equal comparison
730   bool ule(const APInt& RHS) const {
731     return ult(RHS) || eq(RHS);
732   }
733
734   /// Regards both *this and RHS as signed quantities and compares them for
735   /// validity of the less-or-equal relationship.
736   /// @returns true if *this <= RHS when both are considered signed.
737   /// @brief Signed less or equal comparison
738   bool sle(const APInt& RHS) const {
739     return slt(RHS) || eq(RHS);
740   }
741
742   /// Regards both *this and RHS as unsigned quantities and compares them for
743   /// the validity of the greater-than relationship.
744   /// @returns true if *this > RHS when both are considered unsigned.
745   /// @brief Unsigned greather than comparison
746   bool ugt(const APInt& RHS) const {
747     return !ult(RHS) && !eq(RHS);
748   }
749
750   /// Regards both *this and RHS as signed quantities and compares them for
751   /// the validity of the greater-than relationship.
752   /// @returns true if *this > RHS when both are considered signed.
753   /// @brief Signed greather than comparison
754   bool sgt(const APInt& RHS) const {
755     return !slt(RHS) && !eq(RHS);
756   }
757
758   /// Regards both *this and RHS as unsigned quantities and compares them for
759   /// validity of the greater-or-equal relationship.
760   /// @returns true if *this >= RHS when both are considered unsigned.
761   /// @brief Unsigned greater or equal comparison
762   bool uge(const APInt& RHS) const {
763     return !ult(RHS);
764   }
765
766   /// Regards both *this and RHS as signed quantities and compares them for
767   /// validity of the greater-or-equal relationship.
768   /// @returns true if *this >= RHS when both are considered signed.
769   /// @brief Signed greather or equal comparison
770   bool sge(const APInt& RHS) const {
771     return !slt(RHS);
772   }
773
774   /// @}
775   /// @name Resizing Operators
776   /// @{
777   /// Truncate the APInt to a specified width. It is an error to specify a width
778   /// that is greater than or equal to the current width. 
779   /// @brief Truncate to new width.
780   APInt &trunc(uint32_t width);
781
782   /// This operation sign extends the APInt to a new width. If the high order
783   /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
784   /// It is an error to specify a width that is less than or equal to the 
785   /// current width.
786   /// @brief Sign extend to a new width.
787   APInt &sext(uint32_t width);
788
789   /// This operation zero extends the APInt to a new width. The high order bits
790   /// are filled with 0 bits.  It is an error to specify a width that is less 
791   /// than or equal to the current width.
792   /// @brief Zero extend to a new width.
793   APInt &zext(uint32_t width);
794
795   /// Make this APInt have the bit width given by \p width. The value is sign
796   /// extended, truncated, or left alone to make it that width.
797   /// @brief Sign extend or truncate to width
798   APInt &sextOrTrunc(uint32_t width);
799
800   /// Make this APInt have the bit width given by \p width. The value is zero
801   /// extended, truncated, or left alone to make it that width.
802   /// @brief Zero extend or truncate to width
803   APInt &zextOrTrunc(uint32_t width);
804
805   /// @}
806   /// @name Bit Manipulation Operators
807   /// @{
808   /// @brief Set every bit to 1.
809   APInt& set();
810
811   /// Set the given bit to 1 whose position is given as "bitPosition".
812   /// @brief Set a given bit to 1.
813   APInt& set(uint32_t bitPosition);
814
815   /// @brief Set every bit to 0.
816   APInt& clear();
817
818   /// Set the given bit to 0 whose position is given as "bitPosition".
819   /// @brief Set a given bit to 0.
820   APInt& clear(uint32_t bitPosition);
821
822   /// @brief Toggle every bit to its opposite value.
823   APInt& flip();
824
825   /// Toggle a given bit to its opposite value whose position is given 
826   /// as "bitPosition".
827   /// @brief Toggles a given bit to its opposite value.
828   APInt& flip(uint32_t bitPosition);
829
830   /// @}
831   /// @name Value Characterization Functions
832   /// @{
833
834   /// @returns the total number of bits.
835   inline uint32_t getBitWidth() const { 
836     return BitWidth; 
837   }
838
839   /// Here one word's bitwidth equals to that of uint64_t.
840   /// @returns the number of words to hold the integer value of this APInt.
841   /// @brief Get the number of words.
842   inline uint32_t getNumWords() const {
843     return (BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
844   }
845
846   /// This function returns the number of active bits which is defined as the
847   /// bit width minus the number of leading zeros. This is used in several
848   /// computations to see how "wide" the value is.
849   /// @brief Compute the number of active bits in the value
850   inline uint32_t getActiveBits() const {
851     return BitWidth - countLeadingZeros();
852   }
853
854   /// This function returns the number of active words in the value of this
855   /// APInt. This is used in conjunction with getActiveData to extract the raw
856   /// value of the APInt.
857   inline uint32_t getActiveWords() const {
858     return whichWord(getActiveBits()-1) + 1;
859   }
860
861   /// Computes the minimum bit width for this APInt while considering it to be
862   /// a signed (and probably negative) value. If the value is not negative, 
863   /// this function returns the same value as getActiveBits(). Otherwise, it
864   /// returns the smallest bit width that will retain the negative value. For
865   /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
866   /// for -1, this function will always return 1.
867   /// @brief Get the minimum bit size for this signed APInt 
868   inline uint32_t getMinSignedBits() const {
869     if (isNegative())
870       return BitWidth - countLeadingOnes() + 1;
871     return getActiveBits()+1;
872   }
873
874   /// This method attempts to return the value of this APInt as a zero extended
875   /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
876   /// uint64_t. Otherwise an assertion will result.
877   /// @brief Get zero extended value
878   inline uint64_t getZExtValue() const {
879     if (isSingleWord())
880       return VAL;
881     assert(getActiveBits() <= 64 && "Too many bits for uint64_t");
882     return pVal[0];
883   }
884
885   /// This method attempts to return the value of this APInt as a sign extended
886   /// int64_t. The bit width must be <= 64 or the value must fit within an
887   /// int64_t. Otherwise an assertion will result.
888   /// @brief Get sign extended value
889   inline int64_t getSExtValue() const {
890     if (isSingleWord())
891       return int64_t(VAL << (APINT_BITS_PER_WORD - BitWidth)) >> 
892                      (APINT_BITS_PER_WORD - BitWidth);
893     assert(getActiveBits() <= 64 && "Too many bits for int64_t");
894     return int64_t(pVal[0]);
895   }
896
897   /// This method determines how many bits are required to hold the APInt
898   /// equivalent of the string given by \p str of length \p slen.
899   /// @brief Get bits required for string value.
900   static uint32_t getBitsNeeded(const char* str, uint32_t slen, uint8_t radix);
901
902   /// countLeadingZeros - This function is an APInt version of the
903   /// countLeadingZeros_{32,64} functions in MathExtras.h. It counts the number
904   /// of zeros from the most significant bit to the first one bit.
905   /// @returns BitWidth if the value is zero.
906   /// @returns the number of zeros from the most significant bit to the first
907   /// one bits.
908   uint32_t countLeadingZeros() const;
909
910   /// countLeadingOnes - This function counts the number of contiguous 1 bits
911   /// in the high order bits. The count stops when the first 0 bit is reached.
912   /// @returns 0 if the high order bit is not set
913   /// @returns the number of 1 bits from the most significant to the least
914   /// @brief Count the number of leading one bits.
915   uint32_t countLeadingOnes() const;
916
917   /// countTrailingZeros - This function is an APInt version of the 
918   /// countTrailingZoers_{32,64} functions in MathExtras.h. It counts 
919   /// the number of zeros from the least significant bit to the first set bit.
920   /// @returns BitWidth if the value is zero.
921   /// @returns the number of zeros from the least significant bit to the first
922   /// one bit.
923   /// @brief Count the number of trailing zero bits.
924   uint32_t countTrailingZeros() const;
925
926   /// countPopulation - This function is an APInt version of the
927   /// countPopulation_{32,64} functions in MathExtras.h. It counts the number
928   /// of 1 bits in the APInt value. 
929   /// @returns 0 if the value is zero.
930   /// @returns the number of set bits.
931   /// @brief Count the number of bits set.
932   uint32_t countPopulation() const; 
933
934   /// @}
935   /// @name Conversion Functions
936   /// @{
937
938   /// This is used internally to convert an APInt to a string.
939   /// @brief Converts an APInt to a std::string
940   std::string toString(uint8_t radix, bool wantSigned) const;
941
942   /// Considers the APInt to be unsigned and converts it into a string in the
943   /// radix given. The radix can be 2, 8, 10 or 16.
944   /// @returns a character interpretation of the APInt
945   /// @brief Convert unsigned APInt to string representation.
946   inline std::string toStringUnsigned(uint8_t radix = 10) const {
947     return toString(radix, false);
948   }
949
950   /// Considers the APInt to be unsigned and converts it into a string in the
951   /// radix given. The radix can be 2, 8, 10 or 16.
952   /// @returns a character interpretation of the APInt
953   /// @brief Convert unsigned APInt to string representation.
954   inline std::string toStringSigned(uint8_t radix = 10) const {
955     return toString(radix, true);
956   }
957
958   /// @returns a byte-swapped representation of this APInt Value.
959   APInt byteSwap() const;
960
961   /// @brief Converts this APInt to a double value.
962   double roundToDouble(bool isSigned) const;
963
964   /// @brief Converts this unsigned APInt to a double value.
965   double roundToDouble() const {
966     return roundToDouble(false);
967   }
968
969   /// @brief Converts this signed APInt to a double value.
970   double signedRoundToDouble() const {
971     return roundToDouble(true);
972   }
973
974   /// The conversion does not do a translation from integer to double, it just
975   /// re-interprets the bits as a double. Note that it is valid to do this on
976   /// any bit width. Exactly 64 bits will be translated.
977   /// @brief Converts APInt bits to a double
978   double bitsToDouble() const {
979     union {
980       uint64_t I;
981       double D;
982     } T;
983     T.I = (isSingleWord() ? VAL : pVal[0]);
984     return T.D;
985   }
986
987   /// The conversion does not do a translation from integer to float, it just
988   /// re-interprets the bits as a float. Note that it is valid to do this on
989   /// any bit width. Exactly 32 bits will be translated.
990   /// @brief Converts APInt bits to a double
991   float bitsToFloat() const {
992     union {
993       uint32_t I;
994       float F;
995     } T;
996     T.I = uint32_t((isSingleWord() ? VAL : pVal[0]));
997     return T.F;
998   }
999
1000   /// The conversion does not do a translation from double to integer, it just
1001   /// re-interprets the bits of the double. Note that it is valid to do this on
1002   /// any bit width but bits from V may get truncated.
1003   /// @brief Converts a double to APInt bits.
1004   APInt& doubleToBits(double V) {
1005     union {
1006       uint64_t I;
1007       double D;
1008     } T;
1009     T.D = V;
1010     if (isSingleWord())
1011       VAL = T.I;
1012     else
1013       pVal[0] = T.I;
1014     return clearUnusedBits();
1015   }
1016
1017   /// The conversion does not do a translation from float to integer, it just
1018   /// re-interprets the bits of the float. Note that it is valid to do this on
1019   /// any bit width but bits from V may get truncated.
1020   /// @brief Converts a float to APInt bits.
1021   APInt& floatToBits(float V) {
1022     union {
1023       uint32_t I;
1024       float F;
1025     } T;
1026     T.F = V;
1027     if (isSingleWord())
1028       VAL = T.I;
1029     else
1030       pVal[0] = T.I;
1031     return clearUnusedBits();
1032   }
1033
1034   /// @}
1035   /// @name Mathematics Operations
1036   /// @{
1037
1038   /// @returns the floor log base 2 of this APInt.
1039   inline uint32_t logBase2() const {
1040     return BitWidth - 1 - countLeadingZeros();
1041   }
1042
1043   /// @returns the log base 2 of this APInt if its an exact power of two, -1
1044   /// otherwise
1045   inline int32_t exactLogBase2() const {
1046     if (!isPowerOf2())
1047       return -1;
1048     return logBase2();
1049   }
1050
1051   /// @brief Compute the square root
1052   APInt sqrt() const;
1053
1054   /// If *this is < 0 then return -(*this), otherwise *this;
1055   /// @brief Get the absolute value;
1056   APInt abs() const {
1057     if (isNegative())
1058       return -(*this);
1059     return *this;
1060   }
1061
1062   /// @}
1063
1064   /// @}
1065   /// @name Building-block Operations for APInt and APFloat
1066   /// @{
1067
1068   // These building block operations operate on a representation of
1069   // arbitrary precision, two's-complement, bignum integer values.
1070   // They should be sufficient to implement APInt and APFloat bignum
1071   // requirements.  Inputs are generally a pointer to the base of an
1072   // array of integer parts, representing an unsigned bignum, and a
1073   // count of how many parts there are.
1074
1075   /// Sets the least significant part of a bignum to the input value,
1076   /// and zeroes out higher parts.  */
1077   static void tcSet(integerPart *, integerPart, unsigned int);
1078
1079   /// Assign one bignum to another.
1080   static void tcAssign(integerPart *, const integerPart *, unsigned int);
1081
1082   /// Returns true if a bignum is zero, false otherwise.
1083   static bool tcIsZero(const integerPart *, unsigned int);
1084
1085   /// Extract the given bit of a bignum; returns 0 or 1.  Zero-based.
1086   static int tcExtractBit(const integerPart *, unsigned int bit);
1087
1088   /// Copy the bit vector of width srcBITS from SRC, starting at bit
1089   /// srcLSB, to DST, of dstCOUNT parts, such that the bit srcLSB
1090   /// becomes the least significant bit of DST.  All high bits above
1091   /// srcBITS in DST are zero-filled.
1092   static void tcExtract(integerPart *, unsigned int dstCount, const integerPart *,
1093                         unsigned int srcBits, unsigned int srcLSB);
1094
1095   /// Set the given bit of a bignum.  Zero-based.
1096   static void tcSetBit(integerPart *, unsigned int bit);
1097
1098   /// Returns the bit number of the least or most significant set bit
1099   /// of a number.  If the input number has no bits set -1U is
1100   /// returned.
1101   static unsigned int tcLSB(const integerPart *, unsigned int);
1102   static unsigned int tcMSB(const integerPart *, unsigned int);
1103
1104   /// Negate a bignum in-place.
1105   static void tcNegate(integerPart *, unsigned int);
1106
1107   /// DST += RHS + CARRY where CARRY is zero or one.  Returns the
1108   /// carry flag.
1109   static integerPart tcAdd(integerPart *, const integerPart *,
1110                            integerPart carry, unsigned);
1111
1112   /// DST -= RHS + CARRY where CARRY is zero or one.  Returns the
1113   /// carry flag.
1114   static integerPart tcSubtract(integerPart *, const integerPart *,
1115                                 integerPart carry, unsigned);
1116
1117   ///  DST += SRC * MULTIPLIER + PART   if add is true
1118   ///  DST  = SRC * MULTIPLIER + PART   if add is false
1119   ///
1120   ///  Requires 0 <= DSTPARTS <= SRCPARTS + 1.  If DST overlaps SRC
1121   ///  they must start at the same point, i.e. DST == SRC.
1122   ///
1123   ///  If DSTPARTS == SRC_PARTS + 1 no overflow occurs and zero is
1124   ///  returned.  Otherwise DST is filled with the least significant
1125   ///  DSTPARTS parts of the result, and if all of the omitted higher
1126   ///  parts were zero return zero, otherwise overflow occurred and
1127   ///  return one.
1128   static int tcMultiplyPart(integerPart *dst, const integerPart *src,
1129                             integerPart multiplier, integerPart carry,
1130                             unsigned int srcParts, unsigned int dstParts,
1131                             bool add);
1132
1133   /// DST = LHS * RHS, where DST has the same width as the operands
1134   /// and is filled with the least significant parts of the result.
1135   /// Returns one if overflow occurred, otherwise zero.  DST must be
1136   /// disjoint from both operands.
1137   static int tcMultiply(integerPart *, const integerPart *,
1138                         const integerPart *, unsigned);
1139
1140   /// DST = LHS * RHS, where DST has width the sum of the widths of
1141   /// the operands.  No overflow occurs.  DST must be disjoint from
1142   /// both operands. Returns the number of parts required to hold the
1143   /// result.
1144   static unsigned int tcFullMultiply(integerPart *, const integerPart *,
1145                                      const integerPart *, unsigned, unsigned);
1146
1147   /// If RHS is zero LHS and REMAINDER are left unchanged, return one.
1148   /// Otherwise set LHS to LHS / RHS with the fractional part
1149   /// discarded, set REMAINDER to the remainder, return zero.  i.e.
1150   ///
1151   ///  OLD_LHS = RHS * LHS + REMAINDER
1152   ///
1153   ///  SCRATCH is a bignum of the same size as the operands and result
1154   ///  for use by the routine; its contents need not be initialized
1155   ///  and are destroyed.  LHS, REMAINDER and SCRATCH must be
1156   ///  distinct.
1157   static int tcDivide(integerPart *lhs, const integerPart *rhs,
1158                       integerPart *remainder, integerPart *scratch,
1159                       unsigned int parts);
1160
1161   /// Shift a bignum left COUNT bits.  Shifted in bits are zero.
1162   /// There are no restrictions on COUNT.
1163   static void tcShiftLeft(integerPart *, unsigned int parts,
1164                           unsigned int count);
1165
1166   /// Shift a bignum right COUNT bits.  Shifted in bits are zero.
1167   /// There are no restrictions on COUNT.
1168   static void tcShiftRight(integerPart *, unsigned int parts,
1169                            unsigned int count);
1170
1171   /// The obvious AND, OR and XOR and complement operations.
1172   static void tcAnd(integerPart *, const integerPart *, unsigned int);
1173   static void tcOr(integerPart *, const integerPart *, unsigned int);
1174   static void tcXor(integerPart *, const integerPart *, unsigned int);
1175   static void tcComplement(integerPart *, unsigned int);
1176   
1177   /// Comparison (unsigned) of two bignums.
1178   static int tcCompare(const integerPart *, const integerPart *,
1179                        unsigned int);
1180
1181   /// Increment a bignum in-place.  Return the carry flag.
1182   static integerPart tcIncrement(integerPart *, unsigned int);
1183
1184   /// Set the least significant BITS and clear the rest.
1185   static void tcSetLeastSignificantBits(integerPart *, unsigned int,
1186                                         unsigned int bits);
1187
1188   /// @brief debug method
1189   void dump() const;
1190
1191   /// @}
1192 };
1193
1194 inline bool operator==(uint64_t V1, const APInt& V2) {
1195   return V2 == V1;
1196 }
1197
1198 inline bool operator!=(uint64_t V1, const APInt& V2) {
1199   return V2 != V1;
1200 }
1201
1202 namespace APIntOps {
1203
1204 /// @brief Determine the smaller of two APInts considered to be signed.
1205 inline APInt smin(const APInt &A, const APInt &B) {
1206   return A.slt(B) ? A : B;
1207 }
1208
1209 /// @brief Determine the larger of two APInts considered to be signed.
1210 inline APInt smax(const APInt &A, const APInt &B) {
1211   return A.sgt(B) ? A : B;
1212 }
1213
1214 /// @brief Determine the smaller of two APInts considered to be signed.
1215 inline APInt umin(const APInt &A, const APInt &B) {
1216   return A.ult(B) ? A : B;
1217 }
1218
1219 /// @brief Determine the larger of two APInts considered to be unsigned.
1220 inline APInt umax(const APInt &A, const APInt &B) {
1221   return A.ugt(B) ? A : B;
1222 }
1223
1224 /// @brief Check if the specified APInt has a N-bits integer value.
1225 inline bool isIntN(uint32_t N, const APInt& APIVal) {
1226   return APIVal.isIntN(N);
1227 }
1228
1229 /// @returns true if the argument APInt value is a sequence of ones
1230 /// starting at the least significant bit with the remainder zero.
1231 inline bool isMask(uint32_t numBits, const APInt& APIVal) {
1232   return APIVal.getBoolValue() && ((APIVal + APInt(numBits,1)) & APIVal) == 0;
1233 }
1234
1235 /// @returns true if the argument APInt value contains a sequence of ones
1236 /// with the remainder zero.
1237 inline bool isShiftedMask(uint32_t numBits, const APInt& APIVal) {
1238   return isMask(numBits, (APIVal - APInt(numBits,1)) | APIVal);
1239 }
1240
1241 /// @returns a byte-swapped representation of the specified APInt Value.
1242 inline APInt byteSwap(const APInt& APIVal) {
1243   return APIVal.byteSwap();
1244 }
1245
1246 /// @returns the floor log base 2 of the specified APInt value.
1247 inline uint32_t logBase2(const APInt& APIVal) {
1248   return APIVal.logBase2(); 
1249 }
1250
1251 /// GreatestCommonDivisor - This function returns the greatest common
1252 /// divisor of the two APInt values using Enclid's algorithm.
1253 /// @returns the greatest common divisor of Val1 and Val2
1254 /// @brief Compute GCD of two APInt values.
1255 APInt GreatestCommonDivisor(const APInt& Val1, const APInt& Val2);
1256
1257 /// Treats the APInt as an unsigned value for conversion purposes.
1258 /// @brief Converts the given APInt to a double value.
1259 inline double RoundAPIntToDouble(const APInt& APIVal) {
1260   return APIVal.roundToDouble();
1261 }
1262
1263 /// Treats the APInt as a signed value for conversion purposes.
1264 /// @brief Converts the given APInt to a double value.
1265 inline double RoundSignedAPIntToDouble(const APInt& APIVal) {
1266   return APIVal.signedRoundToDouble();
1267 }
1268
1269 /// @brief Converts the given APInt to a float vlalue.
1270 inline float RoundAPIntToFloat(const APInt& APIVal) {
1271   return float(RoundAPIntToDouble(APIVal));
1272 }
1273
1274 /// Treast the APInt as a signed value for conversion purposes.
1275 /// @brief Converts the given APInt to a float value.
1276 inline float RoundSignedAPIntToFloat(const APInt& APIVal) {
1277   return float(APIVal.signedRoundToDouble());
1278 }
1279
1280 /// RoundDoubleToAPInt - This function convert a double value to an APInt value.
1281 /// @brief Converts the given double value into a APInt.
1282 APInt RoundDoubleToAPInt(double Double, uint32_t width);
1283
1284 /// RoundFloatToAPInt - Converts a float value into an APInt value.
1285 /// @brief Converts a float value into a APInt.
1286 inline APInt RoundFloatToAPInt(float Float, uint32_t width) {
1287   return RoundDoubleToAPInt(double(Float), width);
1288 }
1289
1290 /// Arithmetic right-shift the APInt by shiftAmt.
1291 /// @brief Arithmetic right-shift function.
1292 inline APInt ashr(const APInt& LHS, uint32_t shiftAmt) {
1293   return LHS.ashr(shiftAmt);
1294 }
1295
1296 /// Logical right-shift the APInt by shiftAmt.
1297 /// @brief Logical right-shift function.
1298 inline APInt lshr(const APInt& LHS, uint32_t shiftAmt) {
1299   return LHS.lshr(shiftAmt);
1300 }
1301
1302 /// Left-shift the APInt by shiftAmt.
1303 /// @brief Left-shift function.
1304 inline APInt shl(const APInt& LHS, uint32_t shiftAmt) {
1305   return LHS.shl(shiftAmt);
1306 }
1307
1308 /// Signed divide APInt LHS by APInt RHS.
1309 /// @brief Signed division function for APInt.
1310 inline APInt sdiv(const APInt& LHS, const APInt& RHS) {
1311   return LHS.sdiv(RHS);
1312 }
1313
1314 /// Unsigned divide APInt LHS by APInt RHS.
1315 /// @brief Unsigned division function for APInt.
1316 inline APInt udiv(const APInt& LHS, const APInt& RHS) {
1317   return LHS.udiv(RHS);
1318 }
1319
1320 /// Signed remainder operation on APInt.
1321 /// @brief Function for signed remainder operation.
1322 inline APInt srem(const APInt& LHS, const APInt& RHS) {
1323   return LHS.srem(RHS);
1324 }
1325
1326 /// Unsigned remainder operation on APInt.
1327 /// @brief Function for unsigned remainder operation.
1328 inline APInt urem(const APInt& LHS, const APInt& RHS) {
1329   return LHS.urem(RHS);
1330 }
1331
1332 /// Performs multiplication on APInt values.
1333 /// @brief Function for multiplication operation.
1334 inline APInt mul(const APInt& LHS, const APInt& RHS) {
1335   return LHS * RHS;
1336 }
1337
1338 /// Performs addition on APInt values.
1339 /// @brief Function for addition operation.
1340 inline APInt add(const APInt& LHS, const APInt& RHS) {
1341   return LHS + RHS;
1342 }
1343
1344 /// Performs subtraction on APInt values.
1345 /// @brief Function for subtraction operation.
1346 inline APInt sub(const APInt& LHS, const APInt& RHS) {
1347   return LHS - RHS;
1348 }
1349
1350 /// Performs bitwise AND operation on APInt LHS and 
1351 /// APInt RHS.
1352 /// @brief Bitwise AND function for APInt.
1353 inline APInt And(const APInt& LHS, const APInt& RHS) {
1354   return LHS & RHS;
1355 }
1356
1357 /// Performs bitwise OR operation on APInt LHS and APInt RHS.
1358 /// @brief Bitwise OR function for APInt. 
1359 inline APInt Or(const APInt& LHS, const APInt& RHS) {
1360   return LHS | RHS;
1361 }
1362
1363 /// Performs bitwise XOR operation on APInt.
1364 /// @brief Bitwise XOR function for APInt.
1365 inline APInt Xor(const APInt& LHS, const APInt& RHS) {
1366   return LHS ^ RHS;
1367
1368
1369 /// Performs a bitwise complement operation on APInt.
1370 /// @brief Bitwise complement function. 
1371 inline APInt Not(const APInt& APIVal) {
1372   return ~APIVal;
1373 }
1374
1375 } // End of APIntOps namespace
1376
1377 } // End of llvm namespace
1378
1379 #endif