a9e051df21a6659c7048bcebca4676743f012009
[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 <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   
28   /* An unsigned host type used as a single part of a multi-part
29      bignum.  */
30   typedef uint64_t integerPart;
31
32   const unsigned int host_char_bit = 8;
33   const unsigned int integerPartWidth = host_char_bit * sizeof(integerPart);
34
35 //===----------------------------------------------------------------------===//
36 //                              APInt Class
37 //===----------------------------------------------------------------------===//
38
39 /// APInt - This class represents arbitrary precision constant integral values.
40 /// It is a functional replacement for common case unsigned integer type like 
41 /// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width 
42 /// integer sizes and large integer value types such as 3-bits, 15-bits, or more
43 /// than 64-bits of precision. APInt provides a variety of arithmetic operators 
44 /// and methods to manipulate integer values of any bit-width. It supports both
45 /// the typical integer arithmetic and comparison operations as well as bitwise
46 /// manipulation.
47 ///
48 /// The class has several invariants worth noting:
49 ///   * All bit, byte, and word positions are zero-based.
50 ///   * Once the bit width is set, it doesn't change except by the Truncate, 
51 ///     SignExtend, or ZeroExtend operations.
52 ///   * All binary operators must be on APInt instances of the same bit width.
53 ///     Attempting to use these operators on instances with different bit 
54 ///     widths will yield an assertion.
55 ///   * The value is stored canonically as an unsigned value. For operations
56 ///     where it makes a difference, there are both signed and unsigned variants
57 ///     of the operation. For example, sdiv and udiv. However, because the bit
58 ///     widths must be the same, operations such as Mul and Add produce the same
59 ///     results regardless of whether the values are interpreted as signed or
60 ///     not.
61 ///   * In general, the class tries to follow the style of computation that LLVM
62 ///     uses in its IR. This simplifies its use for LLVM.
63 ///
64 /// @brief Class for arbitrary precision integers.
65 class APInt {
66
67   uint32_t BitWidth;      ///< The number of bits in this APInt.
68
69   /// This union is used to store the integer value. When the
70   /// integer bit-width <= 64, it uses VAL, otherwise it uses pVal.
71   union {
72     uint64_t VAL;    ///< Used to store the <= 64 bits integer value.
73     uint64_t *pVal;  ///< Used to store the >64 bits integer value.
74   };
75
76   /// This enum is used to hold the constants we needed for APInt.
77   enum {
78     APINT_BITS_PER_WORD = sizeof(uint64_t) * 8, ///< Bits in a word
79     APINT_WORD_SIZE = sizeof(uint64_t)          ///< Byte size of a word
80   };
81
82   /// This constructor is used only internally for speed of construction of
83   /// temporaries. It is unsafe for general use so it is not public.
84   /// @brief Fast internal constructor
85   APInt(uint64_t* val, uint32_t bits) : BitWidth(bits), pVal(val) { }
86
87   /// @returns true if the number of bits <= 64, false otherwise.
88   /// @brief Determine if this APInt just has one word to store value.
89   inline bool isSingleWord() const { 
90     return BitWidth <= APINT_BITS_PER_WORD; 
91   }
92
93   /// @returns the word position for the specified bit position.
94   /// @brief Determine which word a bit is in.
95   static inline uint32_t whichWord(uint32_t bitPosition) { 
96     return bitPosition / APINT_BITS_PER_WORD; 
97   }
98
99   /// @returns the bit position in a word for the specified bit position 
100   /// in the APInt.
101   /// @brief Determine which bit in a word a bit is in.
102   static inline uint32_t whichBit(uint32_t bitPosition) { 
103     return bitPosition % APINT_BITS_PER_WORD; 
104   }
105
106   /// This method generates and returns a uint64_t (word) mask for a single 
107   /// bit at a specific bit position. This is used to mask the bit in the 
108   /// corresponding word.
109   /// @returns a uint64_t with only bit at "whichBit(bitPosition)" set
110   /// @brief Get a single bit mask.
111   static inline uint64_t maskBit(uint32_t bitPosition) { 
112     return 1ULL << whichBit(bitPosition); 
113   }
114
115   /// This method is used internally to clear the to "N" bits in the high order
116   /// word that are not used by the APInt. This is needed after the most 
117   /// significant word is assigned a value to ensure that those bits are 
118   /// zero'd out.
119   /// @brief Clear unused high order bits
120   inline APInt& clearUnusedBits() {
121     // Compute how many bits are used in the final word
122     uint32_t wordBits = BitWidth % APINT_BITS_PER_WORD;
123     if (wordBits == 0)
124       // If all bits are used, we want to leave the value alone. This also
125       // avoids the undefined behavior of >> when the shfit is the same size as
126       // the word size (64).
127       return *this;
128
129     // Mask out the hight bits.
130     uint64_t mask = ~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - wordBits);
131     if (isSingleWord())
132       VAL &= mask;
133     else
134       pVal[getNumWords() - 1] &= mask;
135     return *this;
136   }
137
138   /// @returns the corresponding word for the specified bit position.
139   /// @brief Get the word corresponding to a bit position
140   inline uint64_t getWord(uint32_t bitPosition) const { 
141     return isSingleWord() ? VAL : pVal[whichWord(bitPosition)]; 
142   }
143
144   /// This is used by the constructors that take string arguments.
145   /// @brief Convert a char array into an APInt
146   void fromString(uint32_t numBits, const char *strStart, uint32_t slen, 
147                   uint8_t radix);
148
149   /// This is used by the toString method to divide by the radix. It simply
150   /// provides a more convenient form of divide for internal use since KnuthDiv
151   /// has specific constraints on its inputs. If those constraints are not met
152   /// then it provides a simpler form of divide.
153   /// @brief An internal division function for dividing APInts.
154   static void divide(const APInt LHS, uint32_t lhsWords, 
155                      const APInt &RHS, uint32_t rhsWords,
156                      APInt *Quotient, APInt *Remainder);
157
158 public:
159   /// @name Constructors
160   /// @{
161   /// If isSigned is true then val is treated as if it were a signed value
162   /// (i.e. as an int64_t) and the appropriate sign extension to the bit width
163   /// will be done. Otherwise, no sign extension occurs (high order bits beyond
164   /// the range of val are zero filled).
165   /// @param numBits the bit width of the constructed APInt
166   /// @param val the initial value of the APInt
167   /// @param isSigned how to treat signedness of val
168   /// @brief Create a new APInt of numBits width, initialized as val.
169   APInt(uint32_t numBits, uint64_t val, bool isSigned = false);
170
171   /// Note that numWords can be smaller or larger than the corresponding bit
172   /// width but any extraneous bits will be dropped.
173   /// @param numBits the bit width of the constructed APInt
174   /// @param numWords the number of words in bigVal
175   /// @param bigVal a sequence of words to form the initial value of the APInt
176   /// @brief Construct an APInt of numBits width, initialized as bigVal[].
177   APInt(uint32_t numBits, uint32_t numWords, const uint64_t bigVal[]);
178
179   /// This constructor interprets Val as a string in the given radix. The 
180   /// interpretation stops when the first charater that is not suitable for the
181   /// radix is encountered. Acceptable radix values are 2, 8, 10 and 16. It is
182   /// an error for the value implied by the string to require more bits than 
183   /// numBits.
184   /// @param numBits the bit width of the constructed APInt
185   /// @param val the string to be interpreted
186   /// @param radix the radix of Val to use for the intepretation
187   /// @brief Construct an APInt from a string representation.
188   APInt(uint32_t numBits, const std::string& val, uint8_t radix);
189
190   /// This constructor interprets the slen characters starting at StrStart as
191   /// a string in the given radix. The interpretation stops when the first 
192   /// character that is not suitable for the radix is encountered. Acceptable
193   /// radix values are 2, 8, 10 and 16. It is an error for the value implied by
194   /// the string to require more bits than numBits.
195   /// @param numBits the bit width of the constructed APInt
196   /// @param strStart the start of the string to be interpreted
197   /// @param slen the maximum number of characters to interpret
198   /// @param radix the radix to use for the conversion
199   /// @brief Construct an APInt from a string representation.
200   APInt(uint32_t numBits, const char strStart[], uint32_t slen, uint8_t radix);
201
202   /// Simply makes *this a copy of that.
203   /// @brief Copy Constructor.
204   APInt(const APInt& that);
205
206   /// @brief Destructor.
207   ~APInt();
208   
209   /// Default constructor that creates an uninitialized APInt.  This is useful
210   ///  for object deserialization (pair this with the static method Read).
211   explicit APInt() : BitWidth(1) {}
212   
213   /// @brief Used by the Bitcode serializer to emit APInts to Bitcode.
214   void Emit(Serializer& S) const;
215   
216   /// @brief Used by the Bitcode deserializer to deserialize APInts.
217   void Read(Deserializer& D);
218
219   /// @}
220   /// @name Value Tests
221   /// @{
222   /// This tests the high bit of this APInt to determine if it is set.
223   /// @returns true if this APInt is negative, false otherwise
224   /// @brief Determine sign of this APInt.
225   bool isNegative() const {
226     return (*this)[BitWidth - 1];
227   }
228
229   /// This tests the high bit of the APInt to determine if it is unset.
230   /// @brief Determine if this APInt Value is positive (not negative).
231   bool isPositive() const {
232     return !isNegative();
233   }
234
235   /// This tests if the value of this APInt is strictly positive (> 0).
236   /// @returns true if this APInt is Positive and not zero.
237   /// @brief Determine if this APInt Value is strictly positive.
238   inline bool isStrictlyPositive() const {
239     return isPositive() && (*this) != 0;
240   }
241
242   /// This checks to see if the value has all bits of the APInt are set or not.
243   /// @brief Determine if all bits are set
244   inline bool isAllOnesValue() const {
245     return countPopulation() == BitWidth;
246   }
247
248   /// This checks to see if the value of this APInt is the maximum unsigned
249   /// value for the APInt's bit width.
250   /// @brief Determine if this is the largest unsigned value.
251   bool isMaxValue() const {
252     return countPopulation() == BitWidth;
253   }
254
255   /// This checks to see if the value of this APInt is the maximum signed
256   /// value for the APInt's bit width.
257   /// @brief Determine if this is the largest signed value.
258   bool isMaxSignedValue() const {
259     return BitWidth == 1 ? VAL == 0 :
260                           !isNegative() && countPopulation() == BitWidth - 1;
261   }
262
263   /// This checks to see if the value of this APInt is the minimum unsigned
264   /// value for the APInt's bit width.
265   /// @brief Determine if this is the smallest unsigned value.
266   bool isMinValue() const {
267     return countPopulation() == 0;
268   }
269
270   /// This checks to see if the value of this APInt is the minimum signed
271   /// value for the APInt's bit width.
272   /// @brief Determine if this is the smallest signed value.
273   bool isMinSignedValue() const {
274     return BitWidth == 1 ? VAL == 1 :
275                            isNegative() && countPopulation() == 1;
276   }
277
278   /// @brief Check if this APInt has an N-bits integer value.
279   inline bool isIntN(uint32_t N) const {
280     assert(N && "N == 0 ???");
281     if (isSingleWord()) {
282       return VAL == (VAL & (~0ULL >> (64 - N)));
283     } else {
284       APInt Tmp(N, getNumWords(), pVal);
285       return Tmp == (*this);
286     }
287   }
288
289   /// @returns true if the argument APInt value is a power of two > 0.
290   bool isPowerOf2() const; 
291
292   /// isSignBit - Return true if this is the value returned by getSignBit.
293   bool isSignBit() const { return isMinSignedValue(); }
294   
295   /// This converts the APInt to a boolean value as a test against zero.
296   /// @brief Boolean conversion function. 
297   inline bool getBoolValue() const {
298     return *this != 0;
299   }
300
301   /// getLimitedValue - If this value is smaller than the specified limit,
302   /// return it, otherwise return the limit value.  This causes the value
303   /// to saturate to the limit.
304   uint64_t getLimitedValue(uint64_t Limit = ~0ULL) const {
305     return (getActiveBits() > 64 || getZExtValue() > Limit) ?
306       Limit :  getZExtValue();
307   }
308
309   /// @}
310   /// @name Value Generators
311   /// @{
312   /// @brief Gets maximum unsigned value of APInt for specific bit width.
313   static APInt getMaxValue(uint32_t numBits) {
314     return APInt(numBits, 0).set();
315   }
316
317   /// @brief Gets maximum signed value of APInt for a specific bit width.
318   static APInt getSignedMaxValue(uint32_t numBits) {
319     return APInt(numBits, 0).set().clear(numBits - 1);
320   }
321
322   /// @brief Gets minimum unsigned value of APInt for a specific bit width.
323   static APInt getMinValue(uint32_t numBits) {
324     return APInt(numBits, 0);
325   }
326
327   /// @brief Gets minimum signed value of APInt for a specific bit width.
328   static APInt getSignedMinValue(uint32_t numBits) {
329     return APInt(numBits, 0).set(numBits - 1);
330   }
331
332   /// getSignBit - This is just a wrapper function of getSignedMinValue(), and
333   /// it helps code readability when we want to get a SignBit.
334   /// @brief Get the SignBit for a specific bit width.
335   inline static APInt getSignBit(uint32_t BitWidth) {
336     return getSignedMinValue(BitWidth);
337   }
338
339   /// @returns the all-ones value for an APInt of the specified bit-width.
340   /// @brief Get the all-ones value.
341   static APInt getAllOnesValue(uint32_t numBits) {
342     return APInt(numBits, 0).set();
343   }
344
345   /// @returns the '0' value for an APInt of the specified bit-width.
346   /// @brief Get the '0' value.
347   static APInt getNullValue(uint32_t numBits) {
348     return APInt(numBits, 0);
349   }
350
351   /// Get an APInt with the same BitWidth as this APInt, just zero mask
352   /// the low bits and right shift to the least significant bit.
353   /// @returns the high "numBits" bits of this APInt.
354   APInt getHiBits(uint32_t numBits) const;
355
356   /// Get an APInt with the same BitWidth as this APInt, just zero mask
357   /// the high bits.
358   /// @returns the low "numBits" bits of this APInt.
359   APInt getLoBits(uint32_t numBits) const;
360
361   /// Constructs an APInt value that has a contiguous range of bits set. The
362   /// bits from loBit to hiBit will be set. All other bits will be zero. For
363   /// example, with parameters(32, 15, 0) you would get 0x0000FFFF. If hiBit is
364   /// less than loBit then the set bits "wrap". For example, with 
365   /// parameters (32, 3, 28), you would get 0xF000000F. 
366   /// @param numBits the intended bit width of the result
367   /// @param loBit the index of the lowest bit set.
368   /// @param hiBit the index of the highest bit set.
369   /// @returns An APInt value with the requested bits set.
370   /// @brief Get a value with a block of bits set.
371   static APInt getBitsSet(uint32_t numBits, uint32_t loBit, uint32_t hiBit) {
372     assert(hiBit < numBits && "hiBit out of range");
373     assert(loBit < numBits && "loBit out of range");
374     if (hiBit < loBit)
375       return getLowBitsSet(numBits, hiBit+1) |
376              getHighBitsSet(numBits, numBits-loBit+1);
377     return getLowBitsSet(numBits, hiBit-loBit+1).shl(loBit);
378   }
379
380   /// Constructs an APInt value that has the top hiBitsSet bits set.
381   /// @param numBits the bitwidth of the result
382   /// @param hiBitsSet the number of high-order bits set in the result.
383   /// @brief Get a value with high bits set
384   static APInt getHighBitsSet(uint32_t numBits, uint32_t hiBitsSet) {
385     assert(hiBitsSet <= numBits && "Too many bits to set!");
386     // Handle a degenerate case, to avoid shifting by word size
387     if (hiBitsSet == 0)
388       return APInt(numBits, 0);
389     uint32_t shiftAmt = numBits - hiBitsSet;
390     // For small values, return quickly
391     if (numBits <= APINT_BITS_PER_WORD)
392       return APInt(numBits, ~0ULL << shiftAmt);
393     return (~APInt(numBits, 0)).shl(shiftAmt);
394   }
395
396   /// Constructs an APInt value that has the bottom loBitsSet bits set.
397   /// @param numBits the bitwidth of the result
398   /// @param loBitsSet the number of low-order bits set in the result.
399   /// @brief Get a value with low bits set
400   static APInt getLowBitsSet(uint32_t numBits, uint32_t loBitsSet) {
401     assert(loBitsSet <= numBits && "Too many bits to set!");
402     // Handle a degenerate case, to avoid shifting by word size
403     if (loBitsSet == 0)
404       return APInt(numBits, 0);
405     if (loBitsSet == APINT_BITS_PER_WORD)
406       return APInt(numBits, -1ULL);
407     // For small values, return quickly
408     if (numBits < APINT_BITS_PER_WORD)
409       return APInt(numBits, (1ULL << loBitsSet) - 1);
410     return (~APInt(numBits, 0)).lshr(numBits - loBitsSet);
411   }
412
413   /// The hash value is computed as the sum of the words and the bit width.
414   /// @returns A hash value computed from the sum of the APInt words.
415   /// @brief Get a hash value based on this APInt
416   uint64_t getHashValue() const;
417
418   /// This function returns a pointer to the internal storage of the APInt. 
419   /// This is useful for writing out the APInt in binary form without any
420   /// conversions.
421   inline const uint64_t* getRawData() const {
422     if (isSingleWord())
423       return &VAL;
424     return &pVal[0];
425   }
426
427   /// @}
428   /// @name Unary Operators
429   /// @{
430   /// @returns a new APInt value representing *this incremented by one
431   /// @brief Postfix increment operator.
432   inline const APInt operator++(int) {
433     APInt API(*this);
434     ++(*this);
435     return API;
436   }
437
438   /// @returns *this incremented by one
439   /// @brief Prefix increment operator.
440   APInt& operator++();
441
442   /// @returns a new APInt representing *this decremented by one.
443   /// @brief Postfix decrement operator. 
444   inline const APInt operator--(int) {
445     APInt API(*this);
446     --(*this);
447     return API;
448   }
449
450   /// @returns *this decremented by one.
451   /// @brief Prefix decrement operator. 
452   APInt& operator--();
453
454   /// Performs a bitwise complement operation on this APInt. 
455   /// @returns an APInt that is the bitwise complement of *this
456   /// @brief Unary bitwise complement operator. 
457   APInt operator~() const;
458
459   /// Negates *this using two's complement logic.
460   /// @returns An APInt value representing the negation of *this.
461   /// @brief Unary negation operator
462   inline APInt operator-() const {
463     return APInt(BitWidth, 0) - (*this);
464   }
465
466   /// Performs logical negation operation on this APInt.
467   /// @returns true if *this is zero, false otherwise.
468   /// @brief Logical negation operator. 
469   bool operator !() const;
470
471   /// @}
472   /// @name Assignment Operators
473   /// @{
474   /// @returns *this after assignment of RHS.
475   /// @brief Copy assignment operator. 
476   APInt& operator=(const APInt& RHS);
477
478   /// The RHS value is assigned to *this. If the significant bits in RHS exceed
479   /// the bit width, the excess bits are truncated. If the bit width is larger
480   /// than 64, the value is zero filled in the unspecified high order bits.
481   /// @returns *this after assignment of RHS value.
482   /// @brief Assignment operator. 
483   APInt& operator=(uint64_t RHS);
484
485   /// Performs a bitwise AND operation on this APInt and RHS. The result is
486   /// assigned to *this. 
487   /// @returns *this after ANDing with RHS.
488   /// @brief Bitwise AND assignment operator. 
489   APInt& operator&=(const APInt& RHS);
490
491   /// Performs a bitwise OR operation on this APInt and RHS. The result is 
492   /// assigned *this;
493   /// @returns *this after ORing with RHS.
494   /// @brief Bitwise OR assignment operator. 
495   APInt& operator|=(const APInt& RHS);
496
497   /// Performs a bitwise XOR operation on this APInt and RHS. The result is
498   /// assigned to *this.
499   /// @returns *this after XORing with RHS.
500   /// @brief Bitwise XOR assignment operator. 
501   APInt& operator^=(const APInt& RHS);
502
503   /// Multiplies this APInt by RHS and assigns the result to *this.
504   /// @returns *this
505   /// @brief Multiplication assignment operator. 
506   APInt& operator*=(const APInt& RHS);
507
508   /// Adds RHS to *this and assigns the result to *this.
509   /// @returns *this
510   /// @brief Addition assignment operator. 
511   APInt& operator+=(const APInt& RHS);
512
513   /// Subtracts RHS from *this and assigns the result to *this.
514   /// @returns *this
515   /// @brief Subtraction assignment operator. 
516   APInt& operator-=(const APInt& RHS);
517
518   /// Shifts *this left by shiftAmt and assigns the result to *this.
519   /// @returns *this after shifting left by shiftAmt
520   /// @brief Left-shift assignment function.
521   inline APInt& operator<<=(uint32_t shiftAmt) {
522     *this = shl(shiftAmt);
523     return *this;
524   }
525
526   /// @}
527   /// @name Binary Operators
528   /// @{
529   /// Performs a bitwise AND operation on *this and RHS.
530   /// @returns An APInt value representing the bitwise AND of *this and RHS.
531   /// @brief Bitwise AND operator. 
532   APInt operator&(const APInt& RHS) const;
533   APInt And(const APInt& RHS) const {
534     return this->operator&(RHS);
535   }
536
537   /// Performs a bitwise OR operation on *this and RHS.
538   /// @returns An APInt value representing the bitwise OR of *this and RHS.
539   /// @brief Bitwise OR operator. 
540   APInt operator|(const APInt& RHS) const;
541   APInt Or(const APInt& RHS) const {
542     return this->operator|(RHS);
543   }
544
545   /// Performs a bitwise XOR operation on *this and RHS.
546   /// @returns An APInt value representing the bitwise XOR of *this and RHS.
547   /// @brief Bitwise XOR operator. 
548   APInt operator^(const APInt& RHS) const;
549   APInt Xor(const APInt& RHS) const {
550     return this->operator^(RHS);
551   }
552
553   /// Multiplies this APInt by RHS and returns the result.
554   /// @brief Multiplication operator. 
555   APInt operator*(const APInt& RHS) const;
556
557   /// Adds RHS to this APInt and returns the result.
558   /// @brief Addition operator. 
559   APInt operator+(const APInt& RHS) const;
560   APInt operator+(uint64_t RHS) const {
561     return (*this) + APInt(BitWidth, RHS);
562   }
563
564   /// Subtracts RHS from this APInt and returns the result.
565   /// @brief Subtraction operator. 
566   APInt operator-(const APInt& RHS) const;
567   APInt operator-(uint64_t RHS) const {
568     return (*this) - APInt(BitWidth, RHS);
569   }
570   
571   APInt operator<<(unsigned Bits) const {
572     return shl(Bits);
573   }
574
575   /// Arithmetic right-shift this APInt by shiftAmt.
576   /// @brief Arithmetic right-shift function.
577   APInt ashr(uint32_t shiftAmt) const;
578
579   /// Logical right-shift this APInt by shiftAmt.
580   /// @brief Logical right-shift function.
581   APInt lshr(uint32_t shiftAmt) const;
582
583   /// Left-shift this APInt by shiftAmt.
584   /// @brief Left-shift function.
585   APInt shl(uint32_t shiftAmt) const;
586
587   /// @brief Rotate left by rotateAmt.
588   APInt rotl(uint32_t rotateAmt) const;
589
590   /// @brief Rotate right by rotateAmt.
591   APInt rotr(uint32_t rotateAmt) const;
592
593   /// Perform an unsigned divide operation on this APInt by RHS. Both this and
594   /// RHS are treated as unsigned quantities for purposes of this division.
595   /// @returns a new APInt value containing the division result
596   /// @brief Unsigned division operation.
597   APInt udiv(const APInt& RHS) const;
598
599   /// Signed divide this APInt by APInt RHS.
600   /// @brief Signed division function for APInt.
601   inline APInt sdiv(const APInt& RHS) const {
602     if (isNegative())
603       if (RHS.isNegative())
604         return (-(*this)).udiv(-RHS);
605       else
606         return -((-(*this)).udiv(RHS));
607     else if (RHS.isNegative())
608       return -(this->udiv(-RHS));
609     return this->udiv(RHS);
610   }
611
612   /// Perform an unsigned remainder operation on this APInt with RHS being the
613   /// divisor. Both this and RHS are treated as unsigned quantities for purposes
614   /// of this operation. Note that this is a true remainder operation and not
615   /// a modulo operation because the sign follows the sign of the dividend
616   /// which is *this.
617   /// @returns a new APInt value containing the remainder result
618   /// @brief Unsigned remainder operation.
619   APInt urem(const APInt& RHS) const;
620
621   /// Signed remainder operation on APInt.
622   /// @brief Function for signed remainder operation.
623   inline APInt srem(const APInt& RHS) const {
624     if (isNegative())
625       if (RHS.isNegative())
626         return -((-(*this)).urem(-RHS));
627       else
628         return -((-(*this)).urem(RHS));
629     else if (RHS.isNegative())
630       return this->urem(-RHS);
631     return this->urem(RHS);
632   }
633
634   /// Sometimes it is convenient to divide two APInt values and obtain both
635   /// the quotient and remainder. This function does both operations in the
636   /// same computation making it a little more efficient.
637   /// @brief Dual division/remainder interface.
638   static void udivrem(const APInt &LHS, const APInt &RHS, 
639                       APInt &Quotient, APInt &Remainder);
640
641   static void sdivrem(const APInt &LHS, const APInt &RHS,
642                       APInt &Quotient, APInt &Remainder)
643   {
644     if (LHS.isNegative()) {
645       if (RHS.isNegative())
646         APInt::udivrem(-LHS, -RHS, Quotient, Remainder);
647       else
648         APInt::udivrem(-LHS, RHS, Quotient, Remainder);
649       Quotient = -Quotient;
650       Remainder = -Remainder;
651     } else if (RHS.isNegative()) {
652       APInt::udivrem(LHS, -RHS, Quotient, Remainder);
653       Quotient = -Quotient;
654     } else {
655       APInt::udivrem(LHS, RHS, Quotient, Remainder);
656     }
657   }
658
659   /// @returns the bit value at bitPosition
660   /// @brief Array-indexing support.
661   bool operator[](uint32_t bitPosition) const;
662
663   /// @}
664   /// @name Comparison Operators
665   /// @{
666   /// Compares this APInt with RHS for the validity of the equality
667   /// relationship.
668   /// @brief Equality operator. 
669   bool operator==(const APInt& RHS) const;
670
671   /// Compares this APInt with a uint64_t for the validity of the equality 
672   /// relationship.
673   /// @returns true if *this == Val
674   /// @brief Equality operator.
675   bool operator==(uint64_t Val) const;
676
677   /// Compares this APInt with RHS for the validity of the equality
678   /// relationship.
679   /// @returns true if *this == Val
680   /// @brief Equality comparison.
681   bool eq(const APInt &RHS) const {
682     return (*this) == RHS; 
683   }
684
685   /// Compares this APInt with RHS for the validity of the inequality
686   /// relationship.
687   /// @returns true if *this != Val
688   /// @brief Inequality operator. 
689   inline bool operator!=(const APInt& RHS) const {
690     return !((*this) == RHS);
691   }
692
693   /// Compares this APInt with a uint64_t for the validity of the inequality 
694   /// relationship.
695   /// @returns true if *this != Val
696   /// @brief Inequality operator. 
697   inline bool operator!=(uint64_t Val) const {
698     return !((*this) == Val);
699   }
700   
701   /// Compares this APInt with RHS for the validity of the inequality
702   /// relationship.
703   /// @returns true if *this != Val
704   /// @brief Inequality comparison
705   bool ne(const APInt &RHS) const {
706     return !((*this) == RHS);
707   }
708
709   /// Regards both *this and RHS as unsigned quantities and compares them for
710   /// the validity of the less-than relationship.
711   /// @returns true if *this < RHS when both are considered unsigned.
712   /// @brief Unsigned less than comparison
713   bool ult(const APInt& RHS) const;
714
715   /// Regards both *this and RHS as signed quantities and compares them for
716   /// validity of the less-than relationship.
717   /// @returns true if *this < RHS when both are considered signed.
718   /// @brief Signed less than comparison
719   bool slt(const APInt& RHS) const;
720
721   /// Regards both *this and RHS as unsigned quantities and compares them for
722   /// validity of the less-or-equal relationship.
723   /// @returns true if *this <= RHS when both are considered unsigned.
724   /// @brief Unsigned less or equal comparison
725   bool ule(const APInt& RHS) const {
726     return ult(RHS) || eq(RHS);
727   }
728
729   /// Regards both *this and RHS as signed quantities and compares them for
730   /// validity of the less-or-equal relationship.
731   /// @returns true if *this <= RHS when both are considered signed.
732   /// @brief Signed less or equal comparison
733   bool sle(const APInt& RHS) const {
734     return slt(RHS) || eq(RHS);
735   }
736
737   /// Regards both *this and RHS as unsigned quantities and compares them for
738   /// the validity of the greater-than relationship.
739   /// @returns true if *this > RHS when both are considered unsigned.
740   /// @brief Unsigned greather than comparison
741   bool ugt(const APInt& RHS) const {
742     return !ult(RHS) && !eq(RHS);
743   }
744
745   /// Regards both *this and RHS as signed quantities and compares them for
746   /// the validity of the greater-than relationship.
747   /// @returns true if *this > RHS when both are considered signed.
748   /// @brief Signed greather than comparison
749   bool sgt(const APInt& RHS) const {
750     return !slt(RHS) && !eq(RHS);
751   }
752
753   /// Regards both *this and RHS as unsigned quantities and compares them for
754   /// validity of the greater-or-equal relationship.
755   /// @returns true if *this >= RHS when both are considered unsigned.
756   /// @brief Unsigned greater or equal comparison
757   bool uge(const APInt& RHS) const {
758     return !ult(RHS);
759   }
760
761   /// Regards both *this and RHS as signed quantities and compares them for
762   /// validity of the greater-or-equal relationship.
763   /// @returns true if *this >= RHS when both are considered signed.
764   /// @brief Signed greather or equal comparison
765   bool sge(const APInt& RHS) const {
766     return !slt(RHS);
767   }
768
769   /// @}
770   /// @name Resizing Operators
771   /// @{
772   /// Truncate the APInt to a specified width. It is an error to specify a width
773   /// that is greater than or equal to the current width. 
774   /// @brief Truncate to new width.
775   APInt &trunc(uint32_t width);
776
777   /// This operation sign extends the APInt to a new width. If the high order
778   /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
779   /// It is an error to specify a width that is less than or equal to the 
780   /// current width.
781   /// @brief Sign extend to a new width.
782   APInt &sext(uint32_t width);
783
784   /// This operation zero extends the APInt to a new width. The high order bits
785   /// are filled with 0 bits.  It is an error to specify a width that is less 
786   /// than or equal to the current width.
787   /// @brief Zero extend to a new width.
788   APInt &zext(uint32_t width);
789
790   /// Make this APInt have the bit width given by \p width. The value is sign
791   /// extended, truncated, or left alone to make it that width.
792   /// @brief Sign extend or truncate to width
793   APInt &sextOrTrunc(uint32_t width);
794
795   /// Make this APInt have the bit width given by \p width. The value is zero
796   /// extended, truncated, or left alone to make it that width.
797   /// @brief Zero extend or truncate to width
798   APInt &zextOrTrunc(uint32_t width);
799
800   /// @}
801   /// @name Bit Manipulation Operators
802   /// @{
803   /// @brief Set every bit to 1.
804   APInt& set();
805
806   /// Set the given bit to 1 whose position is given as "bitPosition".
807   /// @brief Set a given bit to 1.
808   APInt& set(uint32_t bitPosition);
809
810   /// @brief Set every bit to 0.
811   APInt& clear();
812
813   /// Set the given bit to 0 whose position is given as "bitPosition".
814   /// @brief Set a given bit to 0.
815   APInt& clear(uint32_t bitPosition);
816
817   /// @brief Toggle every bit to its opposite value.
818   APInt& flip();
819
820   /// Toggle a given bit to its opposite value whose position is given 
821   /// as "bitPosition".
822   /// @brief Toggles a given bit to its opposite value.
823   APInt& flip(uint32_t bitPosition);
824
825   /// @}
826   /// @name Value Characterization Functions
827   /// @{
828
829   /// @returns the total number of bits.
830   inline uint32_t getBitWidth() const { 
831     return BitWidth; 
832   }
833
834   /// Here one word's bitwidth equals to that of uint64_t.
835   /// @returns the number of words to hold the integer value of this APInt.
836   /// @brief Get the number of words.
837   inline uint32_t getNumWords() const {
838     return (BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
839   }
840
841   /// This function returns the number of active bits which is defined as the
842   /// bit width minus the number of leading zeros. This is used in several
843   /// computations to see how "wide" the value is.
844   /// @brief Compute the number of active bits in the value
845   inline uint32_t getActiveBits() const {
846     return BitWidth - countLeadingZeros();
847   }
848
849   /// This function returns the number of active words in the value of this
850   /// APInt. This is used in conjunction with getActiveData to extract the raw
851   /// value of the APInt.
852   inline uint32_t getActiveWords() const {
853     return whichWord(getActiveBits()-1) + 1;
854   }
855
856   /// Computes the minimum bit width for this APInt while considering it to be
857   /// a signed (and probably negative) value. If the value is not negative, 
858   /// this function returns the same value as getActiveBits(). Otherwise, it
859   /// returns the smallest bit width that will retain the negative value. For
860   /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
861   /// for -1, this function will always return 1.
862   /// @brief Get the minimum bit size for this signed APInt 
863   inline uint32_t getMinSignedBits() const {
864     if (isNegative())
865       return BitWidth - countLeadingOnes() + 1;
866     return getActiveBits()+1;
867   }
868
869   /// This method attempts to return the value of this APInt as a zero extended
870   /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
871   /// uint64_t. Otherwise an assertion will result.
872   /// @brief Get zero extended value
873   inline uint64_t getZExtValue() const {
874     if (isSingleWord())
875       return VAL;
876     assert(getActiveBits() <= 64 && "Too many bits for uint64_t");
877     return pVal[0];
878   }
879
880   /// This method attempts to return the value of this APInt as a sign extended
881   /// int64_t. The bit width must be <= 64 or the value must fit within an
882   /// int64_t. Otherwise an assertion will result.
883   /// @brief Get sign extended value
884   inline int64_t getSExtValue() const {
885     if (isSingleWord())
886       return int64_t(VAL << (APINT_BITS_PER_WORD - BitWidth)) >> 
887                      (APINT_BITS_PER_WORD - BitWidth);
888     assert(getActiveBits() <= 64 && "Too many bits for int64_t");
889     return int64_t(pVal[0]);
890   }
891
892   /// This method determines how many bits are required to hold the APInt
893   /// equivalent of the string given by \p str of length \p slen.
894   /// @brief Get bits required for string value.
895   static uint32_t getBitsNeeded(const char* str, uint32_t slen, uint8_t radix);
896
897   /// countLeadingZeros - This function is an APInt version of the
898   /// countLeadingZeros_{32,64} functions in MathExtras.h. It counts the number
899   /// of zeros from the most significant bit to the first one bit.
900   /// @returns BitWidth if the value is zero.
901   /// @returns the number of zeros from the most significant bit to the first
902   /// 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 set bit.
915   /// @returns BitWidth 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