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