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