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