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