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