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