1 //===-- llvm/ADT/APInt.h - For Arbitrary Precision Integer -----*- C++ -*--===//
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
7 //===----------------------------------------------------------------------===//
10 /// This file implements a class to represent arbitrary precision
11 /// integral constant values and operations on them.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_ADT_APINT_H
16 #define LLVM_ADT_APINT_H
18 #include "llvm/Support/Compiler.h"
19 #include "llvm/Support/MathExtras.h"
26 class FoldingSetNodeID;
31 template <typename T> class SmallVectorImpl;
32 template <typename T> class ArrayRef;
33 template <typename T> class Optional;
34 template <typename T, typename Enable> struct DenseMapInfo;
38 inline APInt operator-(APInt);
40 //===----------------------------------------------------------------------===//
42 //===----------------------------------------------------------------------===//
44 /// Class for arbitrary precision integers.
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
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
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.
75 class LLVM_NODISCARD APInt {
77 typedef uint64_t WordType;
79 /// This enum is used to hold the constants we needed for APInt.
81 /// Byte size of a word.
82 APINT_WORD_SIZE = sizeof(WordType),
84 APINT_BITS_PER_WORD = APINT_WORD_SIZE * CHAR_BIT
93 static constexpr WordType WORDTYPE_MAX = ~WordType(0);
95 /// \name Constructors
98 /// Create a new APInt of numBits width, initialized as val.
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).
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)
109 : BitWidth(numBits) {
110 if (isSingleWord()) {
114 initSlowCase(val, isSigned);
118 /// Construct an APInt of numBits width, initialized as bigVal[].
120 /// Note that bigVal.size() can be smaller or larger than the corresponding
121 /// bit width but any extraneous bits will be dropped.
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);
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.
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)
134 APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[]);
136 /// Construct an APInt from a string representation.
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.
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);
149 /// Default constructor that creates an APInt with a 1-bit zero value.
150 explicit APInt() { U.VAL = 0; }
152 /// Copy Constructor.
153 APInt(const APInt &that) : BitWidth(that.BitWidth) {
160 /// Move Constructor.
161 APInt(APInt &&that) : BitWidth(that.BitWidth) {
162 memcpy(&U, &that.U, sizeof(U));
173 /// \name Value Generators
176 /// Get the '0' value for the specified bit-width.
177 static APInt getZero(unsigned numBits) { return APInt(numBits, 0); }
179 /// NOTE: This is soft-deprecated. Please use `getZero()` instead.
180 static APInt getNullValue(unsigned numBits) { return getZero(numBits); }
182 /// Return an APInt zero bits wide.
183 static APInt getZeroWidth() { return getZero(0); }
185 /// Gets maximum unsigned value of APInt for specific bit width.
186 static APInt getMaxValue(unsigned numBits) { return getAllOnes(numBits); }
188 /// Gets maximum signed value of APInt for a specific bit width.
189 static APInt getSignedMaxValue(unsigned numBits) {
190 APInt API = getAllOnes(numBits);
191 API.clearBit(numBits - 1);
195 /// Gets minimum unsigned value of APInt for a specific bit width.
196 static APInt getMinValue(unsigned numBits) { return APInt(numBits, 0); }
198 /// Gets minimum signed value of APInt for a specific bit width.
199 static APInt getSignedMinValue(unsigned numBits) {
200 APInt API(numBits, 0);
201 API.setBit(numBits - 1);
205 /// Get the SignMask for a specific bit width.
207 /// This is just a wrapper function of getSignedMinValue(), and it helps code
208 /// readability when we want to get a SignMask.
209 static APInt getSignMask(unsigned BitWidth) {
210 return getSignedMinValue(BitWidth);
213 /// Return an APInt of a specified width with all bits set.
214 static APInt getAllOnes(unsigned numBits) {
215 return APInt(numBits, WORDTYPE_MAX, true);
218 /// NOTE: This is soft-deprecated. Please use `getAllOnes()` instead.
219 static APInt getAllOnesValue(unsigned numBits) { return getAllOnes(numBits); }
221 /// Return an APInt with exactly one bit set in the result.
222 static APInt getOneBitSet(unsigned numBits, unsigned BitNo) {
223 APInt Res(numBits, 0);
228 /// Get a value with a block of bits set.
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
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.
240 /// \returns An APInt value with the requested bits set.
241 static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit) {
242 APInt Res(numBits, 0);
243 Res.setBits(loBit, hiBit);
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
253 static APInt getBitsSetWithWrap(unsigned numBits, unsigned loBit,
255 APInt Res(numBits, 0);
256 Res.setBitsWithWrap(loBit, hiBit);
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
265 /// \param numBits the intended bit width of the result
266 /// \param loBit the index of the lowest bit to set.
268 /// \returns An APInt value with the requested bits set.
269 static APInt getBitsSetFrom(unsigned numBits, unsigned loBit) {
270 APInt Res(numBits, 0);
271 Res.setBitsFrom(loBit);
275 /// Constructs an APInt value that has the top hiBitsSet bits set.
277 /// \param numBits the bitwidth of the result
278 /// \param hiBitsSet the number of high-order bits set in the result.
279 static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet) {
280 APInt Res(numBits, 0);
281 Res.setHighBits(hiBitsSet);
285 /// Constructs an APInt value that has the bottom loBitsSet bits set.
287 /// \param numBits the bitwidth of the result
288 /// \param loBitsSet the number of low-order bits set in the result.
289 static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet) {
290 APInt Res(numBits, 0);
291 Res.setLowBits(loBitsSet);
295 /// Return a value containing V broadcasted over NewLen bits.
296 static APInt getSplat(unsigned NewLen, const APInt &V);
299 /// \name Value Tests
302 /// Determine if this APInt just has one word to store value.
304 /// \returns true if the number of bits <= 64, false otherwise.
305 bool isSingleWord() const { return BitWidth <= APINT_BITS_PER_WORD; }
307 /// Determine sign of this APInt.
309 /// This tests the high bit of this APInt to determine if it is set.
311 /// \returns true if this APInt is negative, false otherwise
312 bool isNegative() const { return (*this)[BitWidth - 1]; }
314 /// Determine if this APInt Value is non-negative (>= 0)
316 /// This tests the high bit of the APInt to determine if it is unset.
317 bool isNonNegative() const { return !isNegative(); }
319 /// Determine if sign bit of this APInt is set.
321 /// This tests the high bit of this APInt to determine if it is set.
323 /// \returns true if this APInt has its sign bit set, false otherwise.
324 bool isSignBitSet() const { return (*this)[BitWidth - 1]; }
326 /// Determine if sign bit of this APInt is clear.
328 /// This tests the high bit of this APInt to determine if it is clear.
330 /// \returns true if this APInt has its sign bit clear, false otherwise.
331 bool isSignBitClear() const { return !isSignBitSet(); }
333 /// Determine if this APInt Value is positive.
335 /// This tests if the value of this APInt is positive (> 0). Note
336 /// that 0 is not a positive value.
338 /// \returns true if this APInt is positive.
339 bool isStrictlyPositive() const { return isNonNegative() && !isZero(); }
341 /// Determine if this APInt Value is non-positive (<= 0).
343 /// \returns true if this APInt is non-positive.
344 bool isNonPositive() const { return !isStrictlyPositive(); }
346 /// Determine if all bits are set. This is true for zero-width values.
347 bool isAllOnes() const {
351 return U.VAL == WORDTYPE_MAX >> (APINT_BITS_PER_WORD - BitWidth);
352 return countTrailingOnesSlowCase() == BitWidth;
355 /// NOTE: This is soft-deprecated. Please use `isAllOnes()` instead.
356 bool isAllOnesValue() const { return isAllOnes(); }
358 /// Determine if this value is zero, i.e. all bits are clear.
359 bool isZero() const {
362 return countLeadingZerosSlowCase() == BitWidth;
365 /// NOTE: This is soft-deprecated. Please use `isZero()` instead.
366 bool isNullValue() const { return isZero(); }
368 /// Determine if this is a value of 1.
370 /// This checks to see if the value of this APInt is one.
374 return countLeadingZerosSlowCase() == BitWidth - 1;
377 /// NOTE: This is soft-deprecated. Please use `isOne()` instead.
378 bool isOneValue() const { return isOne(); }
380 /// Determine if this is the largest unsigned value.
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 isAllOnes(); }
386 /// Determine if this is the largest signed value.
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 if (isSingleWord()) {
392 assert(BitWidth && "zero width values not allowed");
393 return U.VAL == ((WordType(1) << (BitWidth - 1)) - 1);
395 return !isNegative() && countTrailingOnesSlowCase() == BitWidth - 1;
398 /// Determine if this is the smallest unsigned value.
400 /// This checks to see if the value of this APInt is the minimum unsigned
401 /// value for the APInt's bit width.
402 bool isMinValue() const { return isZero(); }
404 /// Determine if this is the smallest signed value.
406 /// This checks to see if the value of this APInt is the minimum signed
407 /// value for the APInt's bit width.
408 bool isMinSignedValue() const {
409 if (isSingleWord()) {
410 assert(BitWidth && "zero width values not allowed");
411 return U.VAL == (WordType(1) << (BitWidth - 1));
413 return isNegative() && countTrailingZerosSlowCase() == BitWidth - 1;
416 /// Check if this APInt has an N-bits unsigned integer value.
417 bool isIntN(unsigned N) const { return getActiveBits() <= N; }
419 /// Check if this APInt has an N-bits signed integer value.
420 bool isSignedIntN(unsigned N) const { return getSignificantBits() <= N; }
422 /// Check if this APInt's value is a power of two greater than zero.
424 /// \returns true if the argument APInt value is a power of two > 0.
425 bool isPowerOf2() const {
426 if (isSingleWord()) {
427 assert(BitWidth && "zero width values not allowed");
428 return isPowerOf2_64(U.VAL);
430 return countPopulationSlowCase() == 1;
433 /// Check if this APInt's negated value is a power of two greater than zero.
434 bool isNegatedPowerOf2() const {
435 assert(BitWidth && "zero width values not allowed");
438 // NegatedPowerOf2 - shifted mask in the top bits.
439 unsigned LO = countLeadingOnes();
440 unsigned TZ = countTrailingZeros();
441 return (LO + TZ) == BitWidth;
444 /// Check if the APInt's value is returned by getSignMask.
446 /// \returns true if this is the value returned by getSignMask.
447 bool isSignMask() const { return isMinSignedValue(); }
449 /// Convert APInt to a boolean value.
451 /// This converts the APInt to a boolean value as a test against zero.
452 bool getBoolValue() const { return !isZero(); }
454 /// If this value is smaller than the specified limit, return it, otherwise
455 /// return the limit value. This causes the value to saturate to the limit.
456 uint64_t getLimitedValue(uint64_t Limit = UINT64_MAX) const {
457 return ugt(Limit) ? Limit : getZExtValue();
460 /// Check if the APInt consists of a repeated bit pattern.
462 /// e.g. 0x01010101 satisfies isSplat(8).
463 /// \param SplatSizeInBits The size of the pattern in bits. Must divide bit
464 /// width without remainder.
465 bool isSplat(unsigned SplatSizeInBits) const;
467 /// \returns true if this APInt value is a sequence of \param numBits ones
468 /// starting at the least significant bit with the remainder zero.
469 bool isMask(unsigned numBits) const {
470 assert(numBits != 0 && "numBits must be non-zero");
471 assert(numBits <= BitWidth && "numBits out of range");
473 return U.VAL == (WORDTYPE_MAX >> (APINT_BITS_PER_WORD - numBits));
474 unsigned Ones = countTrailingOnesSlowCase();
475 return (numBits == Ones) &&
476 ((Ones + countLeadingZerosSlowCase()) == BitWidth);
479 /// \returns true if this APInt is a non-empty sequence of ones starting at
480 /// the least significant bit with the remainder zero.
481 /// Ex. isMask(0x0000FFFFU) == true.
482 bool isMask() const {
484 return isMask_64(U.VAL);
485 unsigned Ones = countTrailingOnesSlowCase();
486 return (Ones > 0) && ((Ones + countLeadingZerosSlowCase()) == BitWidth);
489 /// Return true if this APInt value contains a non-empty sequence of ones with
490 /// the remainder zero.
491 bool isShiftedMask() const {
493 return isShiftedMask_64(U.VAL);
494 unsigned Ones = countPopulationSlowCase();
495 unsigned LeadZ = countLeadingZerosSlowCase();
496 return (Ones + LeadZ + countTrailingZeros()) == BitWidth;
499 /// Return true if this APInt value contains a non-empty sequence of ones with
500 /// the remainder zero. If true, \p MaskIdx will specify the index of the
501 /// lowest set bit and \p MaskLen is updated to specify the length of the
502 /// mask, else neither are updated.
503 bool isShiftedMask(unsigned &MaskIdx, unsigned &MaskLen) const {
505 return isShiftedMask_64(U.VAL, MaskIdx, MaskLen);
506 unsigned Ones = countPopulationSlowCase();
507 unsigned LeadZ = countLeadingZerosSlowCase();
508 unsigned TrailZ = countTrailingZerosSlowCase();
509 if ((Ones + LeadZ + TrailZ) != BitWidth)
516 /// Compute an APInt containing numBits highbits from this APInt.
518 /// Get an APInt with the same BitWidth as this APInt, just zero mask the low
519 /// bits and right shift to the least significant bit.
521 /// \returns the high "numBits" bits of this APInt.
522 APInt getHiBits(unsigned numBits) const;
524 /// Compute an APInt containing numBits lowbits from this APInt.
526 /// Get an APInt with the same BitWidth as this APInt, just zero mask the high
529 /// \returns the low "numBits" bits of this APInt.
530 APInt getLoBits(unsigned numBits) const;
532 /// Determine if two APInts have the same value, after zero-extending
533 /// one of them (if needed!) to ensure that the bit-widths match.
534 static bool isSameValue(const APInt &I1, const APInt &I2) {
535 if (I1.getBitWidth() == I2.getBitWidth())
538 if (I1.getBitWidth() > I2.getBitWidth())
539 return I1 == I2.zext(I1.getBitWidth());
541 return I1.zext(I2.getBitWidth()) == I2;
544 /// Overload to compute a hash_code for an APInt value.
545 friend hash_code hash_value(const APInt &Arg);
547 /// This function returns a pointer to the internal storage of the APInt.
548 /// This is useful for writing out the APInt in binary form without any
550 const uint64_t *getRawData() const {
557 /// \name Unary Operators
560 /// Postfix increment operator. Increment *this by 1.
562 /// \returns a new APInt value representing the original value of *this.
563 APInt operator++(int) {
569 /// Prefix increment operator.
571 /// \returns *this incremented by one
574 /// Postfix decrement operator. Decrement *this by 1.
576 /// \returns a new APInt value representing the original value of *this.
577 APInt operator--(int) {
583 /// Prefix decrement operator.
585 /// \returns *this decremented by one.
588 /// Logical negation operation on this APInt returns true if zero, like normal
590 bool operator!() const { return isZero(); }
593 /// \name Assignment Operators
596 /// Copy assignment operator.
598 /// \returns *this after assignment of RHS.
599 APInt &operator=(const APInt &RHS) {
600 // The common case (both source or dest being inline) doesn't require
601 // allocation or deallocation.
602 if (isSingleWord() && RHS.isSingleWord()) {
604 BitWidth = RHS.BitWidth;
612 /// Move assignment operator.
613 APInt &operator=(APInt &&that) {
614 #ifdef EXPENSIVE_CHECKS
615 // Some std::shuffle implementations still do self-assignment.
619 assert(this != &that && "Self-move not supported");
623 // Use memcpy so that type based alias analysis sees both VAL and pVal
625 memcpy(&U, &that.U, sizeof(U));
627 BitWidth = that.BitWidth;
632 /// Assignment operator.
634 /// The RHS value is assigned to *this. If the significant bits in RHS exceed
635 /// the bit width, the excess bits are truncated. If the bit width is larger
636 /// than 64, the value is zero filled in the unspecified high order bits.
638 /// \returns *this after assignment of RHS value.
639 APInt &operator=(uint64_t RHS) {
640 if (isSingleWord()) {
642 return clearUnusedBits();
645 memset(U.pVal + 1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
649 /// Bitwise AND assignment operator.
651 /// Performs a bitwise AND operation on this APInt and RHS. The result is
652 /// assigned to *this.
654 /// \returns *this after ANDing with RHS.
655 APInt &operator&=(const APInt &RHS) {
656 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
660 andAssignSlowCase(RHS);
664 /// Bitwise AND assignment operator.
666 /// Performs a bitwise AND operation on this APInt and RHS. RHS is
667 /// logically zero-extended or truncated to match the bit-width of
669 APInt &operator&=(uint64_t RHS) {
670 if (isSingleWord()) {
675 memset(U.pVal + 1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
679 /// Bitwise OR assignment operator.
681 /// Performs a bitwise OR operation on this APInt and RHS. The result is
684 /// \returns *this after ORing with RHS.
685 APInt &operator|=(const APInt &RHS) {
686 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
690 orAssignSlowCase(RHS);
694 /// Bitwise OR assignment operator.
696 /// Performs a bitwise OR operation on this APInt and RHS. RHS is
697 /// logically zero-extended or truncated to match the bit-width of
699 APInt &operator|=(uint64_t RHS) {
700 if (isSingleWord()) {
702 return clearUnusedBits();
708 /// Bitwise XOR assignment operator.
710 /// Performs a bitwise XOR operation on this APInt and RHS. The result is
711 /// assigned to *this.
713 /// \returns *this after XORing with RHS.
714 APInt &operator^=(const APInt &RHS) {
715 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
719 xorAssignSlowCase(RHS);
723 /// Bitwise XOR assignment operator.
725 /// Performs a bitwise XOR operation on this APInt and RHS. RHS is
726 /// logically zero-extended or truncated to match the bit-width of
728 APInt &operator^=(uint64_t RHS) {
729 if (isSingleWord()) {
731 return clearUnusedBits();
737 /// Multiplication assignment operator.
739 /// Multiplies this APInt by RHS and assigns the result to *this.
742 APInt &operator*=(const APInt &RHS);
743 APInt &operator*=(uint64_t RHS);
745 /// Addition assignment operator.
747 /// Adds RHS to *this and assigns the result to *this.
750 APInt &operator+=(const APInt &RHS);
751 APInt &operator+=(uint64_t RHS);
753 /// Subtraction assignment operator.
755 /// Subtracts RHS from *this and assigns the result to *this.
758 APInt &operator-=(const APInt &RHS);
759 APInt &operator-=(uint64_t RHS);
761 /// Left-shift assignment function.
763 /// Shifts *this left by shiftAmt and assigns the result to *this.
765 /// \returns *this after shifting left by ShiftAmt
766 APInt &operator<<=(unsigned ShiftAmt) {
767 assert(ShiftAmt <= BitWidth && "Invalid shift amount");
768 if (isSingleWord()) {
769 if (ShiftAmt == BitWidth)
773 return clearUnusedBits();
775 shlSlowCase(ShiftAmt);
779 /// Left-shift assignment function.
781 /// Shifts *this left by shiftAmt and assigns the result to *this.
783 /// \returns *this after shifting left by ShiftAmt
784 APInt &operator<<=(const APInt &ShiftAmt);
787 /// \name Binary Operators
790 /// Multiplication operator.
792 /// Multiplies this APInt by RHS and returns the result.
793 APInt operator*(const APInt &RHS) const;
795 /// Left logical shift operator.
797 /// Shifts this APInt left by \p Bits and returns the result.
798 APInt operator<<(unsigned Bits) const { return shl(Bits); }
800 /// Left logical shift operator.
802 /// Shifts this APInt left by \p Bits and returns the result.
803 APInt operator<<(const APInt &Bits) const { return shl(Bits); }
805 /// Arithmetic right-shift function.
807 /// Arithmetic right-shift this APInt by shiftAmt.
808 APInt ashr(unsigned ShiftAmt) const {
810 R.ashrInPlace(ShiftAmt);
814 /// Arithmetic right-shift this APInt by ShiftAmt in place.
815 void ashrInPlace(unsigned ShiftAmt) {
816 assert(ShiftAmt <= BitWidth && "Invalid shift amount");
817 if (isSingleWord()) {
818 int64_t SExtVAL = SignExtend64(U.VAL, BitWidth);
819 if (ShiftAmt == BitWidth)
820 U.VAL = SExtVAL >> (APINT_BITS_PER_WORD - 1); // Fill with sign bit.
822 U.VAL = SExtVAL >> ShiftAmt;
826 ashrSlowCase(ShiftAmt);
829 /// Logical right-shift function.
831 /// Logical right-shift this APInt by shiftAmt.
832 APInt lshr(unsigned shiftAmt) const {
834 R.lshrInPlace(shiftAmt);
838 /// Logical right-shift this APInt by ShiftAmt in place.
839 void lshrInPlace(unsigned ShiftAmt) {
840 assert(ShiftAmt <= BitWidth && "Invalid shift amount");
841 if (isSingleWord()) {
842 if (ShiftAmt == BitWidth)
848 lshrSlowCase(ShiftAmt);
851 /// Left-shift function.
853 /// Left-shift this APInt by shiftAmt.
854 APInt shl(unsigned shiftAmt) const {
860 /// Rotate left by rotateAmt.
861 APInt rotl(unsigned rotateAmt) const;
863 /// Rotate right by rotateAmt.
864 APInt rotr(unsigned rotateAmt) const;
866 /// Arithmetic right-shift function.
868 /// Arithmetic right-shift this APInt by shiftAmt.
869 APInt ashr(const APInt &ShiftAmt) const {
871 R.ashrInPlace(ShiftAmt);
875 /// Arithmetic right-shift this APInt by shiftAmt in place.
876 void ashrInPlace(const APInt &shiftAmt);
878 /// Logical right-shift function.
880 /// Logical right-shift this APInt by shiftAmt.
881 APInt lshr(const APInt &ShiftAmt) const {
883 R.lshrInPlace(ShiftAmt);
887 /// Logical right-shift this APInt by ShiftAmt in place.
888 void lshrInPlace(const APInt &ShiftAmt);
890 /// Left-shift function.
892 /// Left-shift this APInt by shiftAmt.
893 APInt shl(const APInt &ShiftAmt) const {
899 /// Rotate left by rotateAmt.
900 APInt rotl(const APInt &rotateAmt) const;
902 /// Rotate right by rotateAmt.
903 APInt rotr(const APInt &rotateAmt) const;
905 /// Concatenate the bits from "NewLSB" onto the bottom of *this. This is
907 /// (this->zext(NewWidth) << NewLSB.getBitWidth()) | NewLSB.zext(NewWidth)
908 APInt concat(const APInt &NewLSB) const {
909 /// If the result will be small, then both the merged values are small.
910 unsigned NewWidth = getBitWidth() + NewLSB.getBitWidth();
911 if (NewWidth <= APINT_BITS_PER_WORD)
912 return APInt(NewWidth, (U.VAL << NewLSB.getBitWidth()) | NewLSB.U.VAL);
913 return concatSlowCase(NewLSB);
916 /// Unsigned division operation.
918 /// Perform an unsigned divide operation on this APInt by RHS. Both this and
919 /// RHS are treated as unsigned quantities for purposes of this division.
921 /// \returns a new APInt value containing the division result, rounded towards
923 APInt udiv(const APInt &RHS) const;
924 APInt udiv(uint64_t RHS) const;
926 /// Signed division function for APInt.
928 /// Signed divide this APInt by APInt RHS.
930 /// The result is rounded towards zero.
931 APInt sdiv(const APInt &RHS) const;
932 APInt sdiv(int64_t RHS) const;
934 /// Unsigned remainder operation.
936 /// Perform an unsigned remainder operation on this APInt with RHS being the
937 /// divisor. Both this and RHS are treated as unsigned quantities for purposes
938 /// of this operation. Note that this is a true remainder operation and not a
939 /// modulo operation because the sign follows the sign of the dividend which
942 /// \returns a new APInt value containing the remainder result
943 APInt urem(const APInt &RHS) const;
944 uint64_t urem(uint64_t RHS) const;
946 /// Function for signed remainder operation.
948 /// Signed remainder operation on APInt.
949 APInt srem(const APInt &RHS) const;
950 int64_t srem(int64_t RHS) const;
952 /// Dual division/remainder interface.
954 /// Sometimes it is convenient to divide two APInt values and obtain both the
955 /// quotient and remainder. This function does both operations in the same
956 /// computation making it a little more efficient. The pair of input arguments
957 /// may overlap with the pair of output arguments. It is safe to call
958 /// udivrem(X, Y, X, Y), for example.
959 static void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient,
961 static void udivrem(const APInt &LHS, uint64_t RHS, APInt &Quotient,
962 uint64_t &Remainder);
964 static void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient,
966 static void sdivrem(const APInt &LHS, int64_t RHS, APInt &Quotient,
969 // Operations that return overflow indicators.
970 APInt sadd_ov(const APInt &RHS, bool &Overflow) const;
971 APInt uadd_ov(const APInt &RHS, bool &Overflow) const;
972 APInt ssub_ov(const APInt &RHS, bool &Overflow) const;
973 APInt usub_ov(const APInt &RHS, bool &Overflow) const;
974 APInt sdiv_ov(const APInt &RHS, bool &Overflow) const;
975 APInt smul_ov(const APInt &RHS, bool &Overflow) const;
976 APInt umul_ov(const APInt &RHS, bool &Overflow) const;
977 APInt sshl_ov(const APInt &Amt, bool &Overflow) const;
978 APInt ushl_ov(const APInt &Amt, bool &Overflow) const;
980 // Operations that saturate
981 APInt sadd_sat(const APInt &RHS) const;
982 APInt uadd_sat(const APInt &RHS) const;
983 APInt ssub_sat(const APInt &RHS) const;
984 APInt usub_sat(const APInt &RHS) const;
985 APInt smul_sat(const APInt &RHS) const;
986 APInt umul_sat(const APInt &RHS) const;
987 APInt sshl_sat(const APInt &RHS) const;
988 APInt ushl_sat(const APInt &RHS) const;
990 /// Array-indexing support.
992 /// \returns the bit value at bitPosition
993 bool operator[](unsigned bitPosition) const {
994 assert(bitPosition < getBitWidth() && "Bit position out of bounds!");
995 return (maskBit(bitPosition) & getWord(bitPosition)) != 0;
999 /// \name Comparison Operators
1002 /// Equality operator.
1004 /// Compares this APInt with RHS for the validity of the equality
1006 bool operator==(const APInt &RHS) const {
1007 assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths");
1009 return U.VAL == RHS.U.VAL;
1010 return equalSlowCase(RHS);
1013 /// Equality operator.
1015 /// Compares this APInt with a uint64_t for the validity of the equality
1018 /// \returns true if *this == Val
1019 bool operator==(uint64_t Val) const {
1020 return (isSingleWord() || getActiveBits() <= 64) && getZExtValue() == Val;
1023 /// Equality comparison.
1025 /// Compares this APInt with RHS for the validity of the equality
1028 /// \returns true if *this == Val
1029 bool eq(const APInt &RHS) const { return (*this) == RHS; }
1031 /// Inequality operator.
1033 /// Compares this APInt with RHS for the validity of the inequality
1036 /// \returns true if *this != Val
1037 bool operator!=(const APInt &RHS) const { return !((*this) == RHS); }
1039 /// Inequality operator.
1041 /// Compares this APInt with a uint64_t for the validity of the inequality
1044 /// \returns true if *this != Val
1045 bool operator!=(uint64_t Val) const { return !((*this) == Val); }
1047 /// Inequality comparison
1049 /// Compares this APInt with RHS for the validity of the inequality
1052 /// \returns true if *this != Val
1053 bool ne(const APInt &RHS) const { return !((*this) == RHS); }
1055 /// Unsigned less than comparison
1057 /// Regards both *this and RHS as unsigned quantities and compares them for
1058 /// the validity of the less-than relationship.
1060 /// \returns true if *this < RHS when both are considered unsigned.
1061 bool ult(const APInt &RHS) const { return compare(RHS) < 0; }
1063 /// Unsigned less than comparison
1065 /// Regards both *this as an unsigned quantity and compares it with RHS for
1066 /// the validity of the less-than relationship.
1068 /// \returns true if *this < RHS when considered unsigned.
1069 bool ult(uint64_t RHS) const {
1070 // Only need to check active bits if not a single word.
1071 return (isSingleWord() || getActiveBits() <= 64) && getZExtValue() < RHS;
1074 /// Signed less than comparison
1076 /// Regards both *this and RHS as signed quantities and compares them for
1077 /// validity of the less-than relationship.
1079 /// \returns true if *this < RHS when both are considered signed.
1080 bool slt(const APInt &RHS) const { return compareSigned(RHS) < 0; }
1082 /// Signed less than comparison
1084 /// Regards both *this as a signed quantity and compares it with RHS for
1085 /// the validity of the less-than relationship.
1087 /// \returns true if *this < RHS when considered signed.
1088 bool slt(int64_t RHS) const {
1089 return (!isSingleWord() && getSignificantBits() > 64)
1091 : getSExtValue() < RHS;
1094 /// Unsigned less or equal comparison
1096 /// Regards both *this and RHS as unsigned quantities and compares them for
1097 /// validity of the less-or-equal relationship.
1099 /// \returns true if *this <= RHS when both are considered unsigned.
1100 bool ule(const APInt &RHS) const { return compare(RHS) <= 0; }
1102 /// Unsigned less or equal comparison
1104 /// Regards both *this as an unsigned quantity and compares it with RHS for
1105 /// the validity of the less-or-equal relationship.
1107 /// \returns true if *this <= RHS when considered unsigned.
1108 bool ule(uint64_t RHS) const { return !ugt(RHS); }
1110 /// Signed less or equal comparison
1112 /// Regards both *this and RHS as signed quantities and compares them for
1113 /// validity of the less-or-equal relationship.
1115 /// \returns true if *this <= RHS when both are considered signed.
1116 bool sle(const APInt &RHS) const { return compareSigned(RHS) <= 0; }
1118 /// Signed less or equal comparison
1120 /// Regards both *this as a signed quantity and compares it with RHS for the
1121 /// validity of the less-or-equal relationship.
1123 /// \returns true if *this <= RHS when considered signed.
1124 bool sle(uint64_t RHS) const { return !sgt(RHS); }
1126 /// Unsigned greater than comparison
1128 /// Regards both *this and RHS as unsigned quantities and compares them for
1129 /// the validity of the greater-than relationship.
1131 /// \returns true if *this > RHS when both are considered unsigned.
1132 bool ugt(const APInt &RHS) const { return !ule(RHS); }
1134 /// Unsigned greater than comparison
1136 /// Regards both *this as an unsigned quantity and compares it with RHS for
1137 /// the validity of the greater-than relationship.
1139 /// \returns true if *this > RHS when considered unsigned.
1140 bool ugt(uint64_t RHS) const {
1141 // Only need to check active bits if not a single word.
1142 return (!isSingleWord() && getActiveBits() > 64) || getZExtValue() > RHS;
1145 /// Signed greater than comparison
1147 /// Regards both *this and RHS as signed quantities and compares them for the
1148 /// validity of the greater-than relationship.
1150 /// \returns true if *this > RHS when both are considered signed.
1151 bool sgt(const APInt &RHS) const { return !sle(RHS); }
1153 /// Signed greater than comparison
1155 /// Regards both *this as a signed quantity and compares it with RHS for
1156 /// the validity of the greater-than relationship.
1158 /// \returns true if *this > RHS when considered signed.
1159 bool sgt(int64_t RHS) const {
1160 return (!isSingleWord() && getSignificantBits() > 64)
1162 : getSExtValue() > RHS;
1165 /// Unsigned greater or equal comparison
1167 /// Regards both *this and RHS as unsigned quantities and compares them for
1168 /// validity of the greater-or-equal relationship.
1170 /// \returns true if *this >= RHS when both are considered unsigned.
1171 bool uge(const APInt &RHS) const { return !ult(RHS); }
1173 /// Unsigned greater or equal comparison
1175 /// Regards both *this as an unsigned quantity and compares it with RHS for
1176 /// the validity of the greater-or-equal relationship.
1178 /// \returns true if *this >= RHS when considered unsigned.
1179 bool uge(uint64_t RHS) const { return !ult(RHS); }
1181 /// Signed greater or equal comparison
1183 /// Regards both *this and RHS as signed quantities and compares them for
1184 /// validity of the greater-or-equal relationship.
1186 /// \returns true if *this >= RHS when both are considered signed.
1187 bool sge(const APInt &RHS) const { return !slt(RHS); }
1189 /// Signed greater or equal comparison
1191 /// Regards both *this as a signed quantity and compares it with RHS for
1192 /// the validity of the greater-or-equal relationship.
1194 /// \returns true if *this >= RHS when considered signed.
1195 bool sge(int64_t RHS) const { return !slt(RHS); }
1197 /// This operation tests if there are any pairs of corresponding bits
1198 /// between this APInt and RHS that are both set.
1199 bool intersects(const APInt &RHS) const {
1200 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1202 return (U.VAL & RHS.U.VAL) != 0;
1203 return intersectsSlowCase(RHS);
1206 /// This operation checks that all bits set in this APInt are also set in RHS.
1207 bool isSubsetOf(const APInt &RHS) const {
1208 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1210 return (U.VAL & ~RHS.U.VAL) == 0;
1211 return isSubsetOfSlowCase(RHS);
1215 /// \name Resizing Operators
1218 /// Truncate to new width.
1220 /// Truncate the APInt to a specified width. It is an error to specify a width
1221 /// that is greater than the current width.
1222 APInt trunc(unsigned width) const;
1224 /// Truncate to new width with unsigned saturation.
1226 /// If the APInt, treated as unsigned integer, can be losslessly truncated to
1227 /// the new bitwidth, then return truncated APInt. Else, return max value.
1228 APInt truncUSat(unsigned width) const;
1230 /// Truncate to new width with signed saturation.
1232 /// If this APInt, treated as signed integer, can be losslessly truncated to
1233 /// the new bitwidth, then return truncated APInt. Else, return either
1234 /// signed min value if the APInt was negative, or signed max value.
1235 APInt truncSSat(unsigned width) const;
1237 /// Sign extend to a new width.
1239 /// This operation sign extends the APInt to a new width. If the high order
1240 /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
1241 /// It is an error to specify a width that is less than the
1243 APInt sext(unsigned width) const;
1245 /// Zero extend to a new width.
1247 /// This operation zero extends the APInt to a new width. The high order bits
1248 /// are filled with 0 bits. It is an error to specify a width that is less
1249 /// than the current width.
1250 APInt zext(unsigned width) const;
1252 /// Sign extend or truncate to width
1254 /// Make this APInt have the bit width given by \p width. The value is sign
1255 /// extended, truncated, or left alone to make it that width.
1256 APInt sextOrTrunc(unsigned width) const;
1258 /// Zero extend or truncate to width
1260 /// Make this APInt have the bit width given by \p width. The value is zero
1261 /// extended, truncated, or left alone to make it that width.
1262 APInt zextOrTrunc(unsigned width) const;
1265 /// \name Bit Manipulation Operators
1268 /// Set every bit to 1.
1271 U.VAL = WORDTYPE_MAX;
1273 // Set all the bits in all the words.
1274 memset(U.pVal, -1, getNumWords() * APINT_WORD_SIZE);
1275 // Clear the unused ones
1279 /// Set the given bit to 1 whose position is given as "bitPosition".
1280 void setBit(unsigned BitPosition) {
1281 assert(BitPosition < BitWidth && "BitPosition out of range");
1282 WordType Mask = maskBit(BitPosition);
1286 U.pVal[whichWord(BitPosition)] |= Mask;
1289 /// Set the sign bit to 1.
1290 void setSignBit() { setBit(BitWidth - 1); }
1292 /// Set a given bit to a given value.
1293 void setBitVal(unsigned BitPosition, bool BitValue) {
1295 setBit(BitPosition);
1297 clearBit(BitPosition);
1300 /// Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
1301 /// This function handles "wrap" case when \p loBit >= \p hiBit, and calls
1302 /// setBits when \p loBit < \p hiBit.
1303 /// For \p loBit == \p hiBit wrap case, set every bit to 1.
1304 void setBitsWithWrap(unsigned loBit, unsigned hiBit) {
1305 assert(hiBit <= BitWidth && "hiBit out of range");
1306 assert(loBit <= BitWidth && "loBit out of range");
1307 if (loBit < hiBit) {
1308 setBits(loBit, hiBit);
1312 setHighBits(BitWidth - loBit);
1315 /// Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
1316 /// This function handles case when \p loBit <= \p hiBit.
1317 void setBits(unsigned loBit, unsigned hiBit) {
1318 assert(hiBit <= BitWidth && "hiBit out of range");
1319 assert(loBit <= BitWidth && "loBit out of range");
1320 assert(loBit <= hiBit && "loBit greater than hiBit");
1323 if (loBit < APINT_BITS_PER_WORD && hiBit <= APINT_BITS_PER_WORD) {
1324 uint64_t mask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - (hiBit - loBit));
1331 setBitsSlowCase(loBit, hiBit);
1335 /// Set the top bits starting from loBit.
1336 void setBitsFrom(unsigned loBit) { return setBits(loBit, BitWidth); }
1338 /// Set the bottom loBits bits.
1339 void setLowBits(unsigned loBits) { return setBits(0, loBits); }
1341 /// Set the top hiBits bits.
1342 void setHighBits(unsigned hiBits) {
1343 return setBits(BitWidth - hiBits, BitWidth);
1346 /// Set every bit to 0.
1347 void clearAllBits() {
1351 memset(U.pVal, 0, getNumWords() * APINT_WORD_SIZE);
1354 /// Set a given bit to 0.
1356 /// Set the given bit to 0 whose position is given as "bitPosition".
1357 void clearBit(unsigned BitPosition) {
1358 assert(BitPosition < BitWidth && "BitPosition out of range");
1359 WordType Mask = ~maskBit(BitPosition);
1363 U.pVal[whichWord(BitPosition)] &= Mask;
1366 /// Set bottom loBits bits to 0.
1367 void clearLowBits(unsigned loBits) {
1368 assert(loBits <= BitWidth && "More bits than bitwidth");
1369 APInt Keep = getHighBitsSet(BitWidth, BitWidth - loBits);
1373 /// Set the sign bit to 0.
1374 void clearSignBit() { clearBit(BitWidth - 1); }
1376 /// Toggle every bit to its opposite value.
1377 void flipAllBits() {
1378 if (isSingleWord()) {
1379 U.VAL ^= WORDTYPE_MAX;
1382 flipAllBitsSlowCase();
1386 /// Toggles a given bit to its opposite value.
1388 /// Toggle a given bit to its opposite value whose position is given
1389 /// as "bitPosition".
1390 void flipBit(unsigned bitPosition);
1392 /// Negate this APInt in place.
1398 /// Insert the bits from a smaller APInt starting at bitPosition.
1399 void insertBits(const APInt &SubBits, unsigned bitPosition);
1400 void insertBits(uint64_t SubBits, unsigned bitPosition, unsigned numBits);
1402 /// Return an APInt with the extracted bits [bitPosition,bitPosition+numBits).
1403 APInt extractBits(unsigned numBits, unsigned bitPosition) const;
1404 uint64_t extractBitsAsZExtValue(unsigned numBits, unsigned bitPosition) const;
1407 /// \name Value Characterization Functions
1410 /// Return the number of bits in the APInt.
1411 unsigned getBitWidth() const { return BitWidth; }
1413 /// Get the number of words.
1415 /// Here one word's bitwidth equals to that of uint64_t.
1417 /// \returns the number of words to hold the integer value of this APInt.
1418 unsigned getNumWords() const { return getNumWords(BitWidth); }
1420 /// Get the number of words.
1422 /// *NOTE* Here one word's bitwidth equals to that of uint64_t.
1424 /// \returns the number of words to hold the integer value with a given bit
1426 static unsigned getNumWords(unsigned BitWidth) {
1427 return ((uint64_t)BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
1430 /// Compute the number of active bits in the value
1432 /// This function returns the number of active bits which is defined as the
1433 /// bit width minus the number of leading zeros. This is used in several
1434 /// computations to see how "wide" the value is.
1435 unsigned getActiveBits() const { return BitWidth - countLeadingZeros(); }
1437 /// Compute the number of active words in the value of this APInt.
1439 /// This is used in conjunction with getActiveData to extract the raw value of
1441 unsigned getActiveWords() const {
1442 unsigned numActiveBits = getActiveBits();
1443 return numActiveBits ? whichWord(numActiveBits - 1) + 1 : 1;
1446 /// Get the minimum bit size for this signed APInt
1448 /// Computes the minimum bit width for this APInt while considering it to be a
1449 /// signed (and probably negative) value. If the value is not negative, this
1450 /// function returns the same value as getActiveBits()+1. Otherwise, it
1451 /// returns the smallest bit width that will retain the negative value. For
1452 /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
1453 /// for -1, this function will always return 1.
1454 unsigned getSignificantBits() const {
1455 return BitWidth - getNumSignBits() + 1;
1458 /// NOTE: This is soft-deprecated. Please use `getSignificantBits()` instead.
1459 unsigned getMinSignedBits() const { return getSignificantBits(); }
1461 /// Get zero extended value
1463 /// This method attempts to return the value of this APInt as a zero extended
1464 /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
1465 /// uint64_t. Otherwise an assertion will result.
1466 uint64_t getZExtValue() const {
1469 assert(getActiveBits() <= 64 && "Too many bits for uint64_t");
1473 /// Get sign extended value
1475 /// This method attempts to return the value of this APInt as a sign extended
1476 /// int64_t. The bit width must be <= 64 or the value must fit within an
1477 /// int64_t. Otherwise an assertion will result.
1478 int64_t getSExtValue() const {
1480 return SignExtend64(U.VAL, BitWidth);
1481 assert(getSignificantBits() <= 64 && "Too many bits for int64_t");
1482 return int64_t(U.pVal[0]);
1485 /// Get bits required for string value.
1487 /// This method determines how many bits are required to hold the APInt
1488 /// equivalent of the string given by \p str.
1489 static unsigned getBitsNeeded(StringRef str, uint8_t radix);
1491 /// Get the bits that are sufficient to represent the string value. This may
1492 /// over estimate the amount of bits required, but it does not require
1493 /// parsing the value in the string.
1494 static unsigned getSufficientBitsNeeded(StringRef Str, uint8_t Radix);
1496 /// The APInt version of the countLeadingZeros functions in
1499 /// It counts the number of zeros from the most significant bit to the first
1502 /// \returns BitWidth if the value is zero, otherwise returns the number of
1503 /// zeros from the most significant bit to the first one bits.
1504 unsigned countLeadingZeros() const {
1505 if (isSingleWord()) {
1506 unsigned unusedBits = APINT_BITS_PER_WORD - BitWidth;
1507 return llvm::countLeadingZeros(U.VAL) - unusedBits;
1509 return countLeadingZerosSlowCase();
1512 /// Count the number of leading one bits.
1514 /// This function is an APInt version of the countLeadingOnes
1515 /// functions in MathExtras.h. It counts the number of ones from the most
1516 /// significant bit to the first zero bit.
1518 /// \returns 0 if the high order bit is not set, otherwise returns the number
1519 /// of 1 bits from the most significant to the least
1520 unsigned countLeadingOnes() const {
1521 if (isSingleWord()) {
1522 if (LLVM_UNLIKELY(BitWidth == 0))
1524 return llvm::countLeadingOnes(U.VAL << (APINT_BITS_PER_WORD - BitWidth));
1526 return countLeadingOnesSlowCase();
1529 /// Computes the number of leading bits of this APInt that are equal to its
1531 unsigned getNumSignBits() const {
1532 return isNegative() ? countLeadingOnes() : countLeadingZeros();
1535 /// Count the number of trailing zero bits.
1537 /// This function is an APInt version of the countTrailingZeros
1538 /// functions in MathExtras.h. It counts the number of zeros from the least
1539 /// significant bit to the first set bit.
1541 /// \returns BitWidth if the value is zero, otherwise returns the number of
1542 /// zeros from the least significant bit to the first one bit.
1543 unsigned countTrailingZeros() const {
1544 if (isSingleWord()) {
1545 unsigned TrailingZeros = llvm::countTrailingZeros(U.VAL);
1546 return (TrailingZeros > BitWidth ? BitWidth : TrailingZeros);
1548 return countTrailingZerosSlowCase();
1551 /// Count the number of trailing one bits.
1553 /// This function is an APInt version of the countTrailingOnes
1554 /// functions in MathExtras.h. It counts the number of ones from the least
1555 /// significant bit to the first zero bit.
1557 /// \returns BitWidth if the value is all ones, otherwise returns the number
1558 /// of ones from the least significant bit to the first zero bit.
1559 unsigned countTrailingOnes() const {
1561 return llvm::countTrailingOnes(U.VAL);
1562 return countTrailingOnesSlowCase();
1565 /// Count the number of bits set.
1567 /// This function is an APInt version of the countPopulation functions
1568 /// in MathExtras.h. It counts the number of 1 bits in the APInt value.
1570 /// \returns 0 if the value is zero, otherwise returns the number of set bits.
1571 unsigned countPopulation() const {
1573 return llvm::countPopulation(U.VAL);
1574 return countPopulationSlowCase();
1578 /// \name Conversion Functions
1580 void print(raw_ostream &OS, bool isSigned) const;
1582 /// Converts an APInt to a string and append it to Str. Str is commonly a
1584 void toString(SmallVectorImpl<char> &Str, unsigned Radix, bool Signed,
1585 bool formatAsCLiteral = false) const;
1587 /// Considers the APInt to be unsigned and converts it into a string in the
1588 /// radix given. The radix can be 2, 8, 10 16, or 36.
1589 void toStringUnsigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1590 toString(Str, Radix, false, false);
1593 /// Considers the APInt to be signed and converts it into a string in the
1594 /// radix given. The radix can be 2, 8, 10, 16, or 36.
1595 void toStringSigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1596 toString(Str, Radix, true, false);
1599 /// \returns a byte-swapped representation of this APInt Value.
1600 APInt byteSwap() const;
1602 /// \returns the value with the bit representation reversed of this APInt
1604 APInt reverseBits() const;
1606 /// Converts this APInt to a double value.
1607 double roundToDouble(bool isSigned) const;
1609 /// Converts this unsigned APInt to a double value.
1610 double roundToDouble() const { return roundToDouble(false); }
1612 /// Converts this signed APInt to a double value.
1613 double signedRoundToDouble() const { return roundToDouble(true); }
1615 /// Converts APInt bits to a double
1617 /// The conversion does not do a translation from integer to double, it just
1618 /// re-interprets the bits as a double. Note that it is valid to do this on
1619 /// any bit width. Exactly 64 bits will be translated.
1620 double bitsToDouble() const { return BitsToDouble(getWord(0)); }
1622 /// Converts APInt bits to a float
1624 /// The conversion does not do a translation from integer to float, it just
1625 /// re-interprets the bits as a float. Note that it is valid to do this on
1626 /// any bit width. Exactly 32 bits will be translated.
1627 float bitsToFloat() const {
1628 return BitsToFloat(static_cast<uint32_t>(getWord(0)));
1631 /// Converts a double to APInt bits.
1633 /// The conversion does not do a translation from double to integer, it just
1634 /// re-interprets the bits of the double.
1635 static APInt doubleToBits(double V) {
1636 return APInt(sizeof(double) * CHAR_BIT, DoubleToBits(V));
1639 /// Converts a float to APInt bits.
1641 /// The conversion does not do a translation from float to integer, it just
1642 /// re-interprets the bits of the float.
1643 static APInt floatToBits(float V) {
1644 return APInt(sizeof(float) * CHAR_BIT, FloatToBits(V));
1648 /// \name Mathematics Operations
1651 /// \returns the floor log base 2 of this APInt.
1652 unsigned logBase2() const { return getActiveBits() - 1; }
1654 /// \returns the ceil log base 2 of this APInt.
1655 unsigned ceilLogBase2() const {
1658 return temp.getActiveBits();
1661 /// \returns the nearest log base 2 of this APInt. Ties round up.
1663 /// NOTE: When we have a BitWidth of 1, we define:
1665 /// log2(0) = UINT32_MAX
1668 /// to get around any mathematical concerns resulting from
1669 /// referencing 2 in a space where 2 does no exist.
1670 unsigned nearestLogBase2() const;
1672 /// \returns the log base 2 of this APInt if its an exact power of two, -1
1674 int32_t exactLogBase2() const {
1680 /// Compute the square root.
1683 /// Get the absolute value. If *this is < 0 then return -(*this), otherwise
1684 /// *this. Note that the "most negative" signed number (e.g. -128 for 8 bit
1685 /// wide APInt) is unchanged due to how negation works.
1692 /// \returns the multiplicative inverse for a given modulo.
1693 APInt multiplicativeInverse(const APInt &modulo) const;
1696 /// \name Building-block Operations for APInt and APFloat
1699 // These building block operations operate on a representation of arbitrary
1700 // precision, two's-complement, bignum integer values. They should be
1701 // sufficient to implement APInt and APFloat bignum requirements. Inputs are
1702 // generally a pointer to the base of an array of integer parts, representing
1703 // an unsigned bignum, and a count of how many parts there are.
1705 /// Sets the least significant part of a bignum to the input value, and zeroes
1706 /// out higher parts.
1707 static void tcSet(WordType *, WordType, unsigned);
1709 /// Assign one bignum to another.
1710 static void tcAssign(WordType *, const WordType *, unsigned);
1712 /// Returns true if a bignum is zero, false otherwise.
1713 static bool tcIsZero(const WordType *, unsigned);
1715 /// Extract the given bit of a bignum; returns 0 or 1. Zero-based.
1716 static int tcExtractBit(const WordType *, unsigned bit);
1718 /// Copy the bit vector of width srcBITS from SRC, starting at bit srcLSB, to
1719 /// DST, of dstCOUNT parts, such that the bit srcLSB becomes the least
1720 /// significant bit of DST. All high bits above srcBITS in DST are
1722 static void tcExtract(WordType *, unsigned dstCount, const WordType *,
1723 unsigned srcBits, unsigned srcLSB);
1725 /// Set the given bit of a bignum. Zero-based.
1726 static void tcSetBit(WordType *, unsigned bit);
1728 /// Clear the given bit of a bignum. Zero-based.
1729 static void tcClearBit(WordType *, unsigned bit);
1731 /// Returns the bit number of the least or most significant set bit of a
1732 /// number. If the input number has no bits set -1U is returned.
1733 static unsigned tcLSB(const WordType *, unsigned n);
1734 static unsigned tcMSB(const WordType *parts, unsigned n);
1736 /// Negate a bignum in-place.
1737 static void tcNegate(WordType *, unsigned);
1739 /// DST += RHS + CARRY where CARRY is zero or one. Returns the carry flag.
1740 static WordType tcAdd(WordType *, const WordType *, WordType carry, unsigned);
1741 /// DST += RHS. Returns the carry flag.
1742 static WordType tcAddPart(WordType *, WordType, unsigned);
1744 /// DST -= RHS + CARRY where CARRY is zero or one. Returns the carry flag.
1745 static WordType tcSubtract(WordType *, const WordType *, WordType carry,
1747 /// DST -= RHS. Returns the carry flag.
1748 static WordType tcSubtractPart(WordType *, WordType, unsigned);
1750 /// DST += SRC * MULTIPLIER + PART if add is true
1751 /// DST = SRC * MULTIPLIER + PART if add is false
1753 /// Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC they must
1754 /// start at the same point, i.e. DST == SRC.
1756 /// If DSTPARTS == SRC_PARTS + 1 no overflow occurs and zero is returned.
1757 /// Otherwise DST is filled with the least significant DSTPARTS parts of the
1758 /// result, and if all of the omitted higher parts were zero return zero,
1759 /// otherwise overflow occurred and return one.
1760 static int tcMultiplyPart(WordType *dst, const WordType *src,
1761 WordType multiplier, WordType carry,
1762 unsigned srcParts, unsigned dstParts, bool add);
1764 /// DST = LHS * RHS, where DST has the same width as the operands and is
1765 /// filled with the least significant parts of the result. Returns one if
1766 /// overflow occurred, otherwise zero. DST must be disjoint from both
1768 static int tcMultiply(WordType *, const WordType *, const WordType *,
1771 /// DST = LHS * RHS, where DST has width the sum of the widths of the
1772 /// operands. No overflow occurs. DST must be disjoint from both operands.
1773 static void tcFullMultiply(WordType *, const WordType *, const WordType *,
1774 unsigned, unsigned);
1776 /// If RHS is zero LHS and REMAINDER are left unchanged, return one.
1777 /// Otherwise set LHS to LHS / RHS with the fractional part discarded, set
1778 /// REMAINDER to the remainder, return zero. i.e.
1780 /// OLD_LHS = RHS * LHS + REMAINDER
1782 /// SCRATCH is a bignum of the same size as the operands and result for use by
1783 /// the routine; its contents need not be initialized and are destroyed. LHS,
1784 /// REMAINDER and SCRATCH must be distinct.
1785 static int tcDivide(WordType *lhs, const WordType *rhs, WordType *remainder,
1786 WordType *scratch, unsigned parts);
1788 /// Shift a bignum left Count bits. Shifted in bits are zero. There are no
1789 /// restrictions on Count.
1790 static void tcShiftLeft(WordType *, unsigned Words, unsigned Count);
1792 /// Shift a bignum right Count bits. Shifted in bits are zero. There are no
1793 /// restrictions on Count.
1794 static void tcShiftRight(WordType *, unsigned Words, unsigned Count);
1796 /// Comparison (unsigned) of two bignums.
1797 static int tcCompare(const WordType *, const WordType *, unsigned);
1799 /// Increment a bignum in-place. Return the carry flag.
1800 static WordType tcIncrement(WordType *dst, unsigned parts) {
1801 return tcAddPart(dst, 1, parts);
1804 /// Decrement a bignum in-place. Return the borrow flag.
1805 static WordType tcDecrement(WordType *dst, unsigned parts) {
1806 return tcSubtractPart(dst, 1, parts);
1809 /// Used to insert APInt objects, or objects that contain APInt objects, into
1811 void Profile(FoldingSetNodeID &id) const;
1816 /// Returns whether this instance allocated memory.
1817 bool needsCleanup() const { return !isSingleWord(); }
1820 /// This union is used to store the integer value. When the
1821 /// integer bit-width <= 64, it uses VAL, otherwise it uses pVal.
1823 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
1824 uint64_t *pVal; ///< Used to store the >64 bits integer value.
1827 unsigned BitWidth = 1; ///< The number of bits in this APInt.
1829 friend struct DenseMapInfo<APInt, void>;
1830 friend class APSInt;
1832 /// This constructor is used only internally for speed of construction of
1833 /// temporaries. It is unsafe since it takes ownership of the pointer, so it
1835 APInt(uint64_t *val, unsigned bits) : BitWidth(bits) { U.pVal = val; }
1837 /// Determine which word a bit is in.
1839 /// \returns the word position for the specified bit position.
1840 static unsigned whichWord(unsigned bitPosition) {
1841 return bitPosition / APINT_BITS_PER_WORD;
1844 /// Determine which bit in a word the specified bit position is in.
1845 static unsigned whichBit(unsigned bitPosition) {
1846 return bitPosition % APINT_BITS_PER_WORD;
1849 /// Get a single bit mask.
1851 /// \returns a uint64_t with only bit at "whichBit(bitPosition)" set
1852 /// This method generates and returns a uint64_t (word) mask for a single
1853 /// bit at a specific bit position. This is used to mask the bit in the
1854 /// corresponding word.
1855 static uint64_t maskBit(unsigned bitPosition) {
1856 return 1ULL << whichBit(bitPosition);
1859 /// Clear unused high order bits
1861 /// This method is used internally to clear the top "N" bits in the high order
1862 /// word that are not used by the APInt. This is needed after the most
1863 /// significant word is assigned a value to ensure that those bits are
1865 APInt &clearUnusedBits() {
1866 // Compute how many bits are used in the final word.
1867 unsigned WordBits = ((BitWidth - 1) % APINT_BITS_PER_WORD) + 1;
1869 // Mask out the high bits.
1870 uint64_t mask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - WordBits);
1871 if (LLVM_UNLIKELY(BitWidth == 0))
1877 U.pVal[getNumWords() - 1] &= mask;
1881 /// Get the word corresponding to a bit position
1882 /// \returns the corresponding word for the specified bit position.
1883 uint64_t getWord(unsigned bitPosition) const {
1884 return isSingleWord() ? U.VAL : U.pVal[whichWord(bitPosition)];
1887 /// Utility method to change the bit width of this APInt to new bit width,
1888 /// allocating and/or deallocating as necessary. There is no guarantee on the
1889 /// value of any bits upon return. Caller should populate the bits after.
1890 void reallocate(unsigned NewBitWidth);
1892 /// Convert a char array into an APInt
1894 /// \param radix 2, 8, 10, 16, or 36
1895 /// Converts a string into a number. The string must be non-empty
1896 /// and well-formed as a number of the given base. The bit-width
1897 /// must be sufficient to hold the result.
1899 /// This is used by the constructors that take string arguments.
1901 /// StringRef::getAsInteger is superficially similar but (1) does
1902 /// not assume that the string is well-formed and (2) grows the
1903 /// result to hold the input.
1904 void fromString(unsigned numBits, StringRef str, uint8_t radix);
1906 /// An internal division function for dividing APInts.
1908 /// This is used by the toString method to divide by the radix. It simply
1909 /// provides a more convenient form of divide for internal use since KnuthDiv
1910 /// has specific constraints on its inputs. If those constraints are not met
1911 /// then it provides a simpler form of divide.
1912 static void divide(const WordType *LHS, unsigned lhsWords,
1913 const WordType *RHS, unsigned rhsWords, WordType *Quotient,
1914 WordType *Remainder);
1916 /// out-of-line slow case for inline constructor
1917 void initSlowCase(uint64_t val, bool isSigned);
1919 /// shared code between two array constructors
1920 void initFromArray(ArrayRef<uint64_t> array);
1922 /// out-of-line slow case for inline copy constructor
1923 void initSlowCase(const APInt &that);
1925 /// out-of-line slow case for shl
1926 void shlSlowCase(unsigned ShiftAmt);
1928 /// out-of-line slow case for lshr.
1929 void lshrSlowCase(unsigned ShiftAmt);
1931 /// out-of-line slow case for ashr.
1932 void ashrSlowCase(unsigned ShiftAmt);
1934 /// out-of-line slow case for operator=
1935 void assignSlowCase(const APInt &RHS);
1937 /// out-of-line slow case for operator==
1938 bool equalSlowCase(const APInt &RHS) const LLVM_READONLY;
1940 /// out-of-line slow case for countLeadingZeros
1941 unsigned countLeadingZerosSlowCase() const LLVM_READONLY;
1943 /// out-of-line slow case for countLeadingOnes.
1944 unsigned countLeadingOnesSlowCase() const LLVM_READONLY;
1946 /// out-of-line slow case for countTrailingZeros.
1947 unsigned countTrailingZerosSlowCase() const LLVM_READONLY;
1949 /// out-of-line slow case for countTrailingOnes
1950 unsigned countTrailingOnesSlowCase() const LLVM_READONLY;
1952 /// out-of-line slow case for countPopulation
1953 unsigned countPopulationSlowCase() const LLVM_READONLY;
1955 /// out-of-line slow case for intersects.
1956 bool intersectsSlowCase(const APInt &RHS) const LLVM_READONLY;
1958 /// out-of-line slow case for isSubsetOf.
1959 bool isSubsetOfSlowCase(const APInt &RHS) const LLVM_READONLY;
1961 /// out-of-line slow case for setBits.
1962 void setBitsSlowCase(unsigned loBit, unsigned hiBit);
1964 /// out-of-line slow case for flipAllBits.
1965 void flipAllBitsSlowCase();
1967 /// out-of-line slow case for concat.
1968 APInt concatSlowCase(const APInt &NewLSB) const;
1970 /// out-of-line slow case for operator&=.
1971 void andAssignSlowCase(const APInt &RHS);
1973 /// out-of-line slow case for operator|=.
1974 void orAssignSlowCase(const APInt &RHS);
1976 /// out-of-line slow case for operator^=.
1977 void xorAssignSlowCase(const APInt &RHS);
1979 /// Unsigned comparison. Returns -1, 0, or 1 if this APInt is less than, equal
1980 /// to, or greater than RHS.
1981 int compare(const APInt &RHS) const LLVM_READONLY;
1983 /// Signed comparison. Returns -1, 0, or 1 if this APInt is less than, equal
1984 /// to, or greater than RHS.
1985 int compareSigned(const APInt &RHS) const LLVM_READONLY;
1990 inline bool operator==(uint64_t V1, const APInt &V2) { return V2 == V1; }
1992 inline bool operator!=(uint64_t V1, const APInt &V2) { return V2 != V1; }
1994 /// Unary bitwise complement operator.
1996 /// \returns an APInt that is the bitwise complement of \p v.
1997 inline APInt operator~(APInt v) {
2002 inline APInt operator&(APInt a, const APInt &b) {
2007 inline APInt operator&(const APInt &a, APInt &&b) {
2009 return std::move(b);
2012 inline APInt operator&(APInt a, uint64_t RHS) {
2017 inline APInt operator&(uint64_t LHS, APInt b) {
2022 inline APInt operator|(APInt a, const APInt &b) {
2027 inline APInt operator|(const APInt &a, APInt &&b) {
2029 return std::move(b);
2032 inline APInt operator|(APInt a, uint64_t RHS) {
2037 inline APInt operator|(uint64_t LHS, APInt b) {
2042 inline APInt operator^(APInt a, const APInt &b) {
2047 inline APInt operator^(const APInt &a, APInt &&b) {
2049 return std::move(b);
2052 inline APInt operator^(APInt a, uint64_t RHS) {
2057 inline APInt operator^(uint64_t LHS, APInt b) {
2062 inline raw_ostream &operator<<(raw_ostream &OS, const APInt &I) {
2067 inline APInt operator-(APInt v) {
2072 inline APInt operator+(APInt a, const APInt &b) {
2077 inline APInt operator+(const APInt &a, APInt &&b) {
2079 return std::move(b);
2082 inline APInt operator+(APInt a, uint64_t RHS) {
2087 inline APInt operator+(uint64_t LHS, APInt b) {
2092 inline APInt operator-(APInt a, const APInt &b) {
2097 inline APInt operator-(const APInt &a, APInt &&b) {
2100 return std::move(b);
2103 inline APInt operator-(APInt a, uint64_t RHS) {
2108 inline APInt operator-(uint64_t LHS, APInt b) {
2114 inline APInt operator*(APInt a, uint64_t RHS) {
2119 inline APInt operator*(uint64_t LHS, APInt b) {
2124 namespace APIntOps {
2126 /// Determine the smaller of two APInts considered to be signed.
2127 inline const APInt &smin(const APInt &A, const APInt &B) {
2128 return A.slt(B) ? A : B;
2131 /// Determine the larger of two APInts considered to be signed.
2132 inline const APInt &smax(const APInt &A, const APInt &B) {
2133 return A.sgt(B) ? A : B;
2136 /// Determine the smaller of two APInts considered to be unsigned.
2137 inline const APInt &umin(const APInt &A, const APInt &B) {
2138 return A.ult(B) ? A : B;
2141 /// Determine the larger of two APInts considered to be unsigned.
2142 inline const APInt &umax(const APInt &A, const APInt &B) {
2143 return A.ugt(B) ? A : B;
2146 /// Compute GCD of two unsigned APInt values.
2148 /// This function returns the greatest common divisor of the two APInt values
2149 /// using Stein's algorithm.
2151 /// \returns the greatest common divisor of A and B.
2152 APInt GreatestCommonDivisor(APInt A, APInt B);
2154 /// Converts the given APInt to a double value.
2156 /// Treats the APInt as an unsigned value for conversion purposes.
2157 inline double RoundAPIntToDouble(const APInt &APIVal) {
2158 return APIVal.roundToDouble();
2161 /// Converts the given APInt to a double value.
2163 /// Treats the APInt as a signed value for conversion purposes.
2164 inline double RoundSignedAPIntToDouble(const APInt &APIVal) {
2165 return APIVal.signedRoundToDouble();
2168 /// Converts the given APInt to a float value.
2169 inline float RoundAPIntToFloat(const APInt &APIVal) {
2170 return float(RoundAPIntToDouble(APIVal));
2173 /// Converts the given APInt to a float value.
2175 /// Treats the APInt as a signed value for conversion purposes.
2176 inline float RoundSignedAPIntToFloat(const APInt &APIVal) {
2177 return float(APIVal.signedRoundToDouble());
2180 /// Converts the given double value into a APInt.
2182 /// This function convert a double value to an APInt value.
2183 APInt RoundDoubleToAPInt(double Double, unsigned width);
2185 /// Converts a float value into a APInt.
2187 /// Converts a float value into an APInt value.
2188 inline APInt RoundFloatToAPInt(float Float, unsigned width) {
2189 return RoundDoubleToAPInt(double(Float), width);
2192 /// Return A unsign-divided by B, rounded by the given rounding mode.
2193 APInt RoundingUDiv(const APInt &A, const APInt &B, APInt::Rounding RM);
2195 /// Return A sign-divided by B, rounded by the given rounding mode.
2196 APInt RoundingSDiv(const APInt &A, const APInt &B, APInt::Rounding RM);
2198 /// Let q(n) = An^2 + Bn + C, and BW = bit width of the value range
2199 /// (e.g. 32 for i32).
2200 /// This function finds the smallest number n, such that
2201 /// (a) n >= 0 and q(n) = 0, or
2202 /// (b) n >= 1 and q(n-1) and q(n), when evaluated in the set of all
2203 /// integers, belong to two different intervals [Rk, Rk+R),
2204 /// where R = 2^BW, and k is an integer.
2205 /// The idea here is to find when q(n) "overflows" 2^BW, while at the
2206 /// same time "allowing" subtraction. In unsigned modulo arithmetic a
2207 /// subtraction (treated as addition of negated numbers) would always
2208 /// count as an overflow, but here we want to allow values to decrease
2209 /// and increase as long as they are within the same interval.
2210 /// Specifically, adding of two negative numbers should not cause an
2211 /// overflow (as long as the magnitude does not exceed the bit width).
2212 /// On the other hand, given a positive number, adding a negative
2213 /// number to it can give a negative result, which would cause the
2214 /// value to go from [-2^BW, 0) to [0, 2^BW). In that sense, zero is
2215 /// treated as a special case of an overflow.
2217 /// This function returns None if after finding k that minimizes the
2218 /// positive solution to q(n) = kR, both solutions are contained between
2219 /// two consecutive integers.
2221 /// There are cases where q(n) > T, and q(n+1) < T (assuming evaluation
2222 /// in arithmetic modulo 2^BW, and treating the values as signed) by the
2223 /// virtue of *signed* overflow. This function will *not* find such an n,
2224 /// however it may find a value of n satisfying the inequalities due to
2225 /// an *unsigned* overflow (if the values are treated as unsigned).
2226 /// To find a solution for a signed overflow, treat it as a problem of
2227 /// finding an unsigned overflow with a range with of BW-1.
2229 /// The returned value may have a different bit width from the input
2231 Optional<APInt> SolveQuadraticEquationWrap(APInt A, APInt B, APInt C,
2232 unsigned RangeWidth);
2234 /// Compare two values, and if they are different, return the position of the
2235 /// most significant bit that is different in the values.
2236 Optional<unsigned> GetMostSignificantDifferentBit(const APInt &A,
2239 /// Splat/Merge neighboring bits to widen/narrow the bitmask represented
2240 /// by \param A to \param NewBitWidth bits.
2242 /// MatchAnyBits: (Default)
2243 /// e.g. ScaleBitMask(0b0101, 8) -> 0b00110011
2244 /// e.g. ScaleBitMask(0b00011011, 4) -> 0b0111
2247 /// e.g. ScaleBitMask(0b0101, 8) -> 0b00110011
2248 /// e.g. ScaleBitMask(0b00011011, 4) -> 0b0001
2249 /// A.getBitwidth() or NewBitWidth must be a whole multiples of the other.
2250 APInt ScaleBitMask(const APInt &A, unsigned NewBitWidth,
2251 bool MatchAllBits = false);
2252 } // namespace APIntOps
2254 // See friend declaration above. This additional declaration is required in
2255 // order to compile LLVM with IBM xlC compiler.
2256 hash_code hash_value(const APInt &Arg);
2258 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
2259 /// with the integer held in IntVal.
2260 void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst, unsigned StoreBytes);
2262 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
2263 /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
2264 void LoadIntFromMemory(APInt &IntVal, const uint8_t *Src, unsigned LoadBytes);
2266 /// Provide DenseMapInfo for APInt.
2267 template <> struct DenseMapInfo<APInt, void> {
2268 static inline APInt getEmptyKey() {
2269 APInt V(nullptr, 0);
2274 static inline APInt getTombstoneKey() {
2275 APInt V(nullptr, 0);
2280 static unsigned getHashValue(const APInt &Key);
2282 static bool isEqual(const APInt &LHS, const APInt &RHS) {
2283 return LHS.getBitWidth() == RHS.getBitWidth() && LHS == RHS;