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