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