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