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;
37 inline APInt operator-(APInt);
39 //===----------------------------------------------------------------------===//
41 //===----------------------------------------------------------------------===//
43 /// Class for arbitrary precision integers.
45 /// APInt is a functional replacement for common case unsigned integer type like
46 /// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width
47 /// integer sizes and large integer value types such as 3-bits, 15-bits, or more
48 /// than 64-bits of precision. APInt provides a variety of arithmetic operators
49 /// and methods to manipulate integer values of any bit-width. It supports both
50 /// the typical integer arithmetic and comparison operations as well as bitwise
53 /// The class has several invariants worth noting:
54 /// * All bit, byte, and word positions are zero-based.
55 /// * Once the bit width is set, it doesn't change except by the Truncate,
56 /// SignExtend, or ZeroExtend operations.
57 /// * All binary operators must be on APInt instances of the same bit width.
58 /// Attempting to use these operators on instances with different bit
59 /// widths will yield an assertion.
60 /// * The value is stored canonically as an unsigned value. For operations
61 /// where it makes a difference, there are both signed and unsigned variants
62 /// of the operation. For example, sdiv and udiv. However, because the bit
63 /// widths must be the same, operations such as Mul and Add produce the same
64 /// results regardless of whether the values are interpreted as signed or
66 /// * In general, the class tries to follow the style of computation that LLVM
67 /// uses in its IR. This simplifies its use for LLVM.
69 class LLVM_NODISCARD APInt {
71 typedef uint64_t WordType;
73 /// This enum is used to hold the constants we needed for APInt.
75 /// Byte size of a word.
76 APINT_WORD_SIZE = sizeof(WordType),
78 APINT_BITS_PER_WORD = APINT_WORD_SIZE * CHAR_BIT
87 static constexpr WordType WORDTYPE_MAX = ~WordType(0);
90 /// This union is used to store the integer value. When the
91 /// integer bit-width <= 64, it uses VAL, otherwise it uses pVal.
93 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
94 uint64_t *pVal; ///< Used to store the >64 bits integer value.
97 unsigned BitWidth; ///< The number of bits in this APInt.
99 friend struct DenseMapAPIntKeyInfo;
103 /// Fast internal constructor
105 /// This constructor is used only internally for speed of construction of
106 /// temporaries. It is unsafe for general use so it is not public.
107 APInt(uint64_t *val, unsigned bits) : BitWidth(bits) {
111 /// Determine if this APInt just has one word to store value.
113 /// \returns true if the number of bits <= 64, false otherwise.
114 bool isSingleWord() const { return BitWidth <= APINT_BITS_PER_WORD; }
116 /// Determine which word a bit is in.
118 /// \returns the word position for the specified bit position.
119 static unsigned whichWord(unsigned bitPosition) {
120 return bitPosition / APINT_BITS_PER_WORD;
123 /// Determine which bit in a word a bit is in.
125 /// \returns the bit position in a word for the specified bit position
127 static unsigned whichBit(unsigned bitPosition) {
128 return bitPosition % APINT_BITS_PER_WORD;
131 /// Get a single bit mask.
133 /// \returns a uint64_t with only bit at "whichBit(bitPosition)" set
134 /// This method generates and returns a uint64_t (word) mask for a single
135 /// bit at a specific bit position. This is used to mask the bit in the
136 /// corresponding word.
137 static uint64_t maskBit(unsigned bitPosition) {
138 return 1ULL << whichBit(bitPosition);
141 /// Clear unused high order bits
143 /// This method is used internally to clear the top "N" bits in the high order
144 /// word that are not used by the APInt. This is needed after the most
145 /// significant word is assigned a value to ensure that those bits are
147 APInt &clearUnusedBits() {
148 // Compute how many bits are used in the final word
149 unsigned WordBits = ((BitWidth-1) % APINT_BITS_PER_WORD) + 1;
151 // Mask out the high bits.
152 uint64_t mask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - WordBits);
156 U.pVal[getNumWords() - 1] &= mask;
160 /// Get the word corresponding to a bit position
161 /// \returns the corresponding word for the specified bit position.
162 uint64_t getWord(unsigned bitPosition) const {
163 return isSingleWord() ? U.VAL : U.pVal[whichWord(bitPosition)];
166 /// Utility method to change the bit width of this APInt to new bit width,
167 /// allocating and/or deallocating as necessary. There is no guarantee on the
168 /// value of any bits upon return. Caller should populate the bits after.
169 void reallocate(unsigned NewBitWidth);
171 /// Convert a char array into an APInt
173 /// \param radix 2, 8, 10, 16, or 36
174 /// Converts a string into a number. The string must be non-empty
175 /// and well-formed as a number of the given base. The bit-width
176 /// must be sufficient to hold the result.
178 /// This is used by the constructors that take string arguments.
180 /// StringRef::getAsInteger is superficially similar but (1) does
181 /// not assume that the string is well-formed and (2) grows the
182 /// result to hold the input.
183 void fromString(unsigned numBits, StringRef str, uint8_t radix);
185 /// An internal division function for dividing APInts.
187 /// This is used by the toString method to divide by the radix. It simply
188 /// provides a more convenient form of divide for internal use since KnuthDiv
189 /// has specific constraints on its inputs. If those constraints are not met
190 /// then it provides a simpler form of divide.
191 static void divide(const WordType *LHS, unsigned lhsWords,
192 const WordType *RHS, unsigned rhsWords, WordType *Quotient,
193 WordType *Remainder);
195 /// out-of-line slow case for inline constructor
196 void initSlowCase(uint64_t val, bool isSigned);
198 /// shared code between two array constructors
199 void initFromArray(ArrayRef<uint64_t> array);
201 /// out-of-line slow case for inline copy constructor
202 void initSlowCase(const APInt &that);
204 /// out-of-line slow case for shl
205 void shlSlowCase(unsigned ShiftAmt);
207 /// out-of-line slow case for lshr.
208 void lshrSlowCase(unsigned ShiftAmt);
210 /// out-of-line slow case for ashr.
211 void ashrSlowCase(unsigned ShiftAmt);
213 /// out-of-line slow case for operator=
214 void AssignSlowCase(const APInt &RHS);
216 /// out-of-line slow case for operator==
217 bool EqualSlowCase(const APInt &RHS) const LLVM_READONLY;
219 /// out-of-line slow case for countLeadingZeros
220 unsigned countLeadingZerosSlowCase() const LLVM_READONLY;
222 /// out-of-line slow case for countLeadingOnes.
223 unsigned countLeadingOnesSlowCase() const LLVM_READONLY;
225 /// out-of-line slow case for countTrailingZeros.
226 unsigned countTrailingZerosSlowCase() const LLVM_READONLY;
228 /// out-of-line slow case for countTrailingOnes
229 unsigned countTrailingOnesSlowCase() const LLVM_READONLY;
231 /// out-of-line slow case for countPopulation
232 unsigned countPopulationSlowCase() const LLVM_READONLY;
234 /// out-of-line slow case for intersects.
235 bool intersectsSlowCase(const APInt &RHS) const LLVM_READONLY;
237 /// out-of-line slow case for isSubsetOf.
238 bool isSubsetOfSlowCase(const APInt &RHS) const LLVM_READONLY;
240 /// out-of-line slow case for setBits.
241 void setBitsSlowCase(unsigned loBit, unsigned hiBit);
243 /// out-of-line slow case for flipAllBits.
244 void flipAllBitsSlowCase();
246 /// out-of-line slow case for operator&=.
247 void AndAssignSlowCase(const APInt& RHS);
249 /// out-of-line slow case for operator|=.
250 void OrAssignSlowCase(const APInt& RHS);
252 /// out-of-line slow case for operator^=.
253 void XorAssignSlowCase(const APInt& RHS);
255 /// Unsigned comparison. Returns -1, 0, or 1 if this APInt is less than, equal
256 /// to, or greater than RHS.
257 int compare(const APInt &RHS) const LLVM_READONLY;
259 /// Signed comparison. Returns -1, 0, or 1 if this APInt is less than, equal
260 /// to, or greater than RHS.
261 int compareSigned(const APInt &RHS) const LLVM_READONLY;
264 /// \name Constructors
267 /// Create a new APInt of numBits width, initialized as val.
269 /// If isSigned is true then val is treated as if it were a signed value
270 /// (i.e. as an int64_t) and the appropriate sign extension to the bit width
271 /// will be done. Otherwise, no sign extension occurs (high order bits beyond
272 /// the range of val are zero filled).
274 /// \param numBits the bit width of the constructed APInt
275 /// \param val the initial value of the APInt
276 /// \param isSigned how to treat signedness of val
277 APInt(unsigned numBits, uint64_t val, bool isSigned = false)
278 : BitWidth(numBits) {
279 assert(BitWidth && "bitwidth too small");
280 if (isSingleWord()) {
284 initSlowCase(val, isSigned);
288 /// Construct an APInt of numBits width, initialized as bigVal[].
290 /// Note that bigVal.size() can be smaller or larger than the corresponding
291 /// bit width but any extraneous bits will be dropped.
293 /// \param numBits the bit width of the constructed APInt
294 /// \param bigVal a sequence of words to form the initial value of the APInt
295 APInt(unsigned numBits, ArrayRef<uint64_t> bigVal);
297 /// Equivalent to APInt(numBits, ArrayRef<uint64_t>(bigVal, numWords)), but
298 /// deprecated because this constructor is prone to ambiguity with the
299 /// APInt(unsigned, uint64_t, bool) constructor.
301 /// If this overload is ever deleted, care should be taken to prevent calls
302 /// from being incorrectly captured by the APInt(unsigned, uint64_t, bool)
304 APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[]);
306 /// Construct an APInt from a string representation.
308 /// This constructor interprets the string \p str in the given radix. The
309 /// interpretation stops when the first character that is not suitable for the
310 /// radix is encountered, or the end of the string. Acceptable radix values
311 /// are 2, 8, 10, 16, and 36. It is an error for the value implied by the
312 /// string to require more bits than numBits.
314 /// \param numBits the bit width of the constructed APInt
315 /// \param str the string to be interpreted
316 /// \param radix the radix to use for the conversion
317 APInt(unsigned numBits, StringRef str, uint8_t radix);
319 /// Simply makes *this a copy of that.
320 /// Copy Constructor.
321 APInt(const APInt &that) : BitWidth(that.BitWidth) {
328 /// Move Constructor.
329 APInt(APInt &&that) : BitWidth(that.BitWidth) {
330 memcpy(&U, &that.U, sizeof(U));
340 /// Default constructor that creates an uninteresting APInt
341 /// representing a 1-bit zero value.
343 /// This is useful for object deserialization (pair this with the static
345 explicit APInt() : BitWidth(1) { U.VAL = 0; }
347 /// Returns whether this instance allocated memory.
348 bool needsCleanup() const { return !isSingleWord(); }
350 /// Used to insert APInt objects, or objects that contain APInt objects, into
352 void Profile(FoldingSetNodeID &id) const;
355 /// \name Value Tests
358 /// Determine sign of this APInt.
360 /// This tests the high bit of this APInt to determine if it is set.
362 /// \returns true if this APInt is negative, false otherwise
363 bool isNegative() const { return (*this)[BitWidth - 1]; }
365 /// Determine if this APInt Value is non-negative (>= 0)
367 /// This tests the high bit of the APInt to determine if it is unset.
368 bool isNonNegative() const { return !isNegative(); }
370 /// Determine if sign bit of this APInt is set.
372 /// This tests the high bit of this APInt to determine if it is set.
374 /// \returns true if this APInt has its sign bit set, false otherwise.
375 bool isSignBitSet() const { return (*this)[BitWidth-1]; }
377 /// Determine if sign bit of this APInt is clear.
379 /// This tests the high bit of this APInt to determine if it is clear.
381 /// \returns true if this APInt has its sign bit clear, false otherwise.
382 bool isSignBitClear() const { return !isSignBitSet(); }
384 /// Determine if this APInt Value is positive.
386 /// This tests if the value of this APInt is positive (> 0). Note
387 /// that 0 is not a positive value.
389 /// \returns true if this APInt is positive.
390 bool isStrictlyPositive() const { return isNonNegative() && !isNullValue(); }
392 /// Determine if this APInt Value is non-positive (<= 0).
394 /// \returns true if this APInt is non-positive.
395 bool isNonPositive() const { return !isStrictlyPositive(); }
397 /// Determine if all bits are set
399 /// This checks to see if the value has all bits of the APInt are set or not.
400 bool isAllOnesValue() const {
402 return U.VAL == WORDTYPE_MAX >> (APINT_BITS_PER_WORD - BitWidth);
403 return countTrailingOnesSlowCase() == BitWidth;
406 /// Determine if all bits are clear
408 /// This checks to see if the value has all bits of the APInt are clear or
410 bool isNullValue() const { return !*this; }
412 /// Determine if this is a value of 1.
414 /// This checks to see if the value of this APInt is one.
415 bool isOneValue() const {
418 return countLeadingZerosSlowCase() == BitWidth - 1;
421 /// Determine if this is the largest unsigned value.
423 /// This checks to see if the value of this APInt is the maximum unsigned
424 /// value for the APInt's bit width.
425 bool isMaxValue() const { return isAllOnesValue(); }
427 /// Determine if this is the largest signed value.
429 /// This checks to see if the value of this APInt is the maximum signed
430 /// value for the APInt's bit width.
431 bool isMaxSignedValue() const {
433 return U.VAL == ((WordType(1) << (BitWidth - 1)) - 1);
434 return !isNegative() && countTrailingOnesSlowCase() == BitWidth - 1;
437 /// Determine if this is the smallest unsigned value.
439 /// This checks to see if the value of this APInt is the minimum unsigned
440 /// value for the APInt's bit width.
441 bool isMinValue() const { return isNullValue(); }
443 /// Determine if this is the smallest signed value.
445 /// This checks to see if the value of this APInt is the minimum signed
446 /// value for the APInt's bit width.
447 bool isMinSignedValue() const {
449 return U.VAL == (WordType(1) << (BitWidth - 1));
450 return isNegative() && countTrailingZerosSlowCase() == BitWidth - 1;
453 /// Check if this APInt has an N-bits unsigned integer value.
454 bool isIntN(unsigned N) const {
455 assert(N && "N == 0 ???");
456 return getActiveBits() <= N;
459 /// Check if this APInt has an N-bits signed integer value.
460 bool isSignedIntN(unsigned N) const {
461 assert(N && "N == 0 ???");
462 return getMinSignedBits() <= N;
465 /// Check if this APInt's value is a power of two greater than zero.
467 /// \returns true if the argument APInt value is a power of two > 0.
468 bool isPowerOf2() const {
470 return isPowerOf2_64(U.VAL);
471 return countPopulationSlowCase() == 1;
474 /// Check if the APInt's value is returned by getSignMask.
476 /// \returns true if this is the value returned by getSignMask.
477 bool isSignMask() const { return isMinSignedValue(); }
479 /// Convert APInt to a boolean value.
481 /// This converts the APInt to a boolean value as a test against zero.
482 bool getBoolValue() const { return !!*this; }
484 /// If this value is smaller than the specified limit, return it, otherwise
485 /// return the limit value. This causes the value to saturate to the limit.
486 uint64_t getLimitedValue(uint64_t Limit = UINT64_MAX) const {
487 return ugt(Limit) ? Limit : getZExtValue();
490 /// Check if the APInt consists of a repeated bit pattern.
492 /// e.g. 0x01010101 satisfies isSplat(8).
493 /// \param SplatSizeInBits The size of the pattern in bits. Must divide bit
494 /// width without remainder.
495 bool isSplat(unsigned SplatSizeInBits) const;
497 /// \returns true if this APInt value is a sequence of \param numBits ones
498 /// starting at the least significant bit with the remainder zero.
499 bool isMask(unsigned numBits) const {
500 assert(numBits != 0 && "numBits must be non-zero");
501 assert(numBits <= BitWidth && "numBits out of range");
503 return U.VAL == (WORDTYPE_MAX >> (APINT_BITS_PER_WORD - numBits));
504 unsigned Ones = countTrailingOnesSlowCase();
505 return (numBits == Ones) &&
506 ((Ones + countLeadingZerosSlowCase()) == BitWidth);
509 /// \returns true if this APInt is a non-empty sequence of ones starting at
510 /// the least significant bit with the remainder zero.
511 /// Ex. isMask(0x0000FFFFU) == true.
512 bool isMask() const {
514 return isMask_64(U.VAL);
515 unsigned Ones = countTrailingOnesSlowCase();
516 return (Ones > 0) && ((Ones + countLeadingZerosSlowCase()) == BitWidth);
519 /// Return true if this APInt value contains a sequence of ones with
520 /// the remainder zero.
521 bool isShiftedMask() const {
523 return isShiftedMask_64(U.VAL);
524 unsigned Ones = countPopulationSlowCase();
525 unsigned LeadZ = countLeadingZerosSlowCase();
526 return (Ones + LeadZ + countTrailingZeros()) == BitWidth;
530 /// \name Value Generators
533 /// Gets maximum unsigned value of APInt for specific bit width.
534 static APInt getMaxValue(unsigned numBits) {
535 return getAllOnesValue(numBits);
538 /// Gets maximum signed value of APInt for a specific bit width.
539 static APInt getSignedMaxValue(unsigned numBits) {
540 APInt API = getAllOnesValue(numBits);
541 API.clearBit(numBits - 1);
545 /// Gets minimum unsigned value of APInt for a specific bit width.
546 static APInt getMinValue(unsigned numBits) { return APInt(numBits, 0); }
548 /// Gets minimum signed value of APInt for a specific bit width.
549 static APInt getSignedMinValue(unsigned numBits) {
550 APInt API(numBits, 0);
551 API.setBit(numBits - 1);
555 /// Get the SignMask for a specific bit width.
557 /// This is just a wrapper function of getSignedMinValue(), and it helps code
558 /// readability when we want to get a SignMask.
559 static APInt getSignMask(unsigned BitWidth) {
560 return getSignedMinValue(BitWidth);
563 /// Get the all-ones value.
565 /// \returns the all-ones value for an APInt of the specified bit-width.
566 static APInt getAllOnesValue(unsigned numBits) {
567 return APInt(numBits, WORDTYPE_MAX, true);
570 /// Get the '0' value.
572 /// \returns the '0' value for an APInt of the specified bit-width.
573 static APInt getNullValue(unsigned numBits) { return APInt(numBits, 0); }
575 /// Compute an APInt containing numBits highbits from this APInt.
577 /// Get an APInt with the same BitWidth as this APInt, just zero mask
578 /// the low bits and right shift to the least significant bit.
580 /// \returns the high "numBits" bits of this APInt.
581 APInt getHiBits(unsigned numBits) const;
583 /// Compute an APInt containing numBits lowbits from this APInt.
585 /// Get an APInt with the same BitWidth as this APInt, just zero mask
588 /// \returns the low "numBits" bits of this APInt.
589 APInt getLoBits(unsigned numBits) const;
591 /// Return an APInt with exactly one bit set in the result.
592 static APInt getOneBitSet(unsigned numBits, unsigned BitNo) {
593 APInt Res(numBits, 0);
598 /// Get a value with a block of bits set.
600 /// Constructs an APInt value that has a contiguous range of bits set. The
601 /// bits from loBit (inclusive) to hiBit (exclusive) will be set. All other
602 /// bits will be zero. For example, with parameters(32, 0, 16) you would get
603 /// 0x0000FFFF. Please call getBitsSetWithWrap if \p loBit may be greater than
606 /// \param numBits the intended bit width of the result
607 /// \param loBit the index of the lowest bit set.
608 /// \param hiBit the index of the highest bit set.
610 /// \returns An APInt value with the requested bits set.
611 static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit) {
612 assert(loBit <= hiBit && "loBit greater than hiBit");
613 APInt Res(numBits, 0);
614 Res.setBits(loBit, hiBit);
618 /// Wrap version of getBitsSet.
619 /// If \p hiBit is bigger than \p loBit, this is same with getBitsSet.
620 /// If \p hiBit is not bigger than \p loBit, the set bits "wrap". For example,
621 /// with parameters (32, 28, 4), you would get 0xF000000F.
622 /// If \p hiBit is equal to \p loBit, you would get a result with all bits
624 static APInt getBitsSetWithWrap(unsigned numBits, unsigned loBit,
626 APInt Res(numBits, 0);
627 Res.setBitsWithWrap(loBit, hiBit);
631 /// Get a value with upper bits starting at loBit set.
633 /// Constructs an APInt value that has a contiguous range of bits set. The
634 /// bits from loBit (inclusive) to numBits (exclusive) will be set. All other
635 /// bits will be zero. For example, with parameters(32, 12) you would get
638 /// \param numBits the intended bit width of the result
639 /// \param loBit the index of the lowest bit to set.
641 /// \returns An APInt value with the requested bits set.
642 static APInt getBitsSetFrom(unsigned numBits, unsigned loBit) {
643 APInt Res(numBits, 0);
644 Res.setBitsFrom(loBit);
648 /// Get a value with high bits set
650 /// Constructs an APInt value that has the top hiBitsSet bits set.
652 /// \param numBits the bitwidth of the result
653 /// \param hiBitsSet the number of high-order bits set in the result.
654 static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet) {
655 APInt Res(numBits, 0);
656 Res.setHighBits(hiBitsSet);
660 /// Get a value with low bits set
662 /// Constructs an APInt value that has the bottom loBitsSet bits set.
664 /// \param numBits the bitwidth of the result
665 /// \param loBitsSet the number of low-order bits set in the result.
666 static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet) {
667 APInt Res(numBits, 0);
668 Res.setLowBits(loBitsSet);
672 /// Return a value containing V broadcasted over NewLen bits.
673 static APInt getSplat(unsigned NewLen, const APInt &V);
675 /// Determine if two APInts have the same value, after zero-extending
676 /// one of them (if needed!) to ensure that the bit-widths match.
677 static bool isSameValue(const APInt &I1, const APInt &I2) {
678 if (I1.getBitWidth() == I2.getBitWidth())
681 if (I1.getBitWidth() > I2.getBitWidth())
682 return I1 == I2.zext(I1.getBitWidth());
684 return I1.zext(I2.getBitWidth()) == I2;
687 /// Overload to compute a hash_code for an APInt value.
688 friend hash_code hash_value(const APInt &Arg);
690 /// This function returns a pointer to the internal storage of the APInt.
691 /// This is useful for writing out the APInt in binary form without any
693 const uint64_t *getRawData() const {
700 /// \name Unary Operators
703 /// Postfix increment operator.
705 /// Increments *this by 1.
707 /// \returns a new APInt value representing the original value of *this.
708 const APInt operator++(int) {
714 /// Prefix increment operator.
716 /// \returns *this incremented by one
719 /// Postfix decrement operator.
721 /// Decrements *this by 1.
723 /// \returns a new APInt value representing the original value of *this.
724 const APInt operator--(int) {
730 /// Prefix decrement operator.
732 /// \returns *this decremented by one.
735 /// Logical negation operator.
737 /// Performs logical negation operation on this APInt.
739 /// \returns true if *this is zero, false otherwise.
740 bool operator!() const {
743 return countLeadingZerosSlowCase() == BitWidth;
747 /// \name Assignment Operators
750 /// Copy assignment operator.
752 /// \returns *this after assignment of RHS.
753 APInt &operator=(const APInt &RHS) {
754 // If the bitwidths are the same, we can avoid mucking with memory
755 if (isSingleWord() && RHS.isSingleWord()) {
757 BitWidth = RHS.BitWidth;
758 return clearUnusedBits();
765 /// Move assignment operator.
766 APInt &operator=(APInt &&that) {
768 // The MSVC std::shuffle implementation still does self-assignment.
772 assert(this != &that && "Self-move not supported");
776 // Use memcpy so that type based alias analysis sees both VAL and pVal
778 memcpy(&U, &that.U, sizeof(U));
780 BitWidth = that.BitWidth;
786 /// Assignment operator.
788 /// The RHS value is assigned to *this. If the significant bits in RHS exceed
789 /// the bit width, the excess bits are truncated. If the bit width is larger
790 /// than 64, the value is zero filled in the unspecified high order bits.
792 /// \returns *this after assignment of RHS value.
793 APInt &operator=(uint64_t RHS) {
794 if (isSingleWord()) {
799 memset(U.pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
804 /// Bitwise AND assignment operator.
806 /// Performs a bitwise AND operation on this APInt and RHS. The result is
807 /// assigned to *this.
809 /// \returns *this after ANDing with RHS.
810 APInt &operator&=(const APInt &RHS) {
811 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
815 AndAssignSlowCase(RHS);
819 /// Bitwise AND assignment operator.
821 /// Performs a bitwise AND operation on this APInt and RHS. RHS is
822 /// logically zero-extended or truncated to match the bit-width of
824 APInt &operator&=(uint64_t RHS) {
825 if (isSingleWord()) {
830 memset(U.pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
834 /// Bitwise OR assignment operator.
836 /// Performs a bitwise OR operation on this APInt and RHS. The result is
839 /// \returns *this after ORing with RHS.
840 APInt &operator|=(const APInt &RHS) {
841 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
845 OrAssignSlowCase(RHS);
849 /// Bitwise OR assignment operator.
851 /// Performs a bitwise OR operation on this APInt and RHS. RHS is
852 /// logically zero-extended or truncated to match the bit-width of
854 APInt &operator|=(uint64_t RHS) {
855 if (isSingleWord()) {
864 /// Bitwise XOR assignment operator.
866 /// Performs a bitwise XOR operation on this APInt and RHS. The result is
867 /// assigned to *this.
869 /// \returns *this after XORing with RHS.
870 APInt &operator^=(const APInt &RHS) {
871 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
875 XorAssignSlowCase(RHS);
879 /// Bitwise XOR assignment operator.
881 /// Performs a bitwise XOR operation on this APInt and RHS. RHS is
882 /// logically zero-extended or truncated to match the bit-width of
884 APInt &operator^=(uint64_t RHS) {
885 if (isSingleWord()) {
894 /// Multiplication assignment operator.
896 /// Multiplies this APInt by RHS and assigns the result to *this.
899 APInt &operator*=(const APInt &RHS);
900 APInt &operator*=(uint64_t RHS);
902 /// Addition assignment operator.
904 /// Adds RHS to *this and assigns the result to *this.
907 APInt &operator+=(const APInt &RHS);
908 APInt &operator+=(uint64_t RHS);
910 /// Subtraction assignment operator.
912 /// Subtracts RHS from *this and assigns the result to *this.
915 APInt &operator-=(const APInt &RHS);
916 APInt &operator-=(uint64_t RHS);
918 /// Left-shift assignment function.
920 /// Shifts *this left by shiftAmt and assigns the result to *this.
922 /// \returns *this after shifting left by ShiftAmt
923 APInt &operator<<=(unsigned ShiftAmt) {
924 assert(ShiftAmt <= BitWidth && "Invalid shift amount");
925 if (isSingleWord()) {
926 if (ShiftAmt == BitWidth)
930 return clearUnusedBits();
932 shlSlowCase(ShiftAmt);
936 /// Left-shift assignment function.
938 /// Shifts *this left by shiftAmt and assigns the result to *this.
940 /// \returns *this after shifting left by ShiftAmt
941 APInt &operator<<=(const APInt &ShiftAmt);
944 /// \name Binary Operators
947 /// Multiplication operator.
949 /// Multiplies this APInt by RHS and returns the result.
950 APInt operator*(const APInt &RHS) const;
952 /// Left logical shift operator.
954 /// Shifts this APInt left by \p Bits and returns the result.
955 APInt operator<<(unsigned Bits) const { return shl(Bits); }
957 /// Left logical shift operator.
959 /// Shifts this APInt left by \p Bits and returns the result.
960 APInt operator<<(const APInt &Bits) const { return shl(Bits); }
962 /// Arithmetic right-shift function.
964 /// Arithmetic right-shift this APInt by shiftAmt.
965 APInt ashr(unsigned ShiftAmt) const {
967 R.ashrInPlace(ShiftAmt);
971 /// Arithmetic right-shift this APInt by ShiftAmt in place.
972 void ashrInPlace(unsigned ShiftAmt) {
973 assert(ShiftAmt <= BitWidth && "Invalid shift amount");
974 if (isSingleWord()) {
975 int64_t SExtVAL = SignExtend64(U.VAL, BitWidth);
976 if (ShiftAmt == BitWidth)
977 U.VAL = SExtVAL >> (APINT_BITS_PER_WORD - 1); // Fill with sign bit.
979 U.VAL = SExtVAL >> ShiftAmt;
983 ashrSlowCase(ShiftAmt);
986 /// Logical right-shift function.
988 /// Logical right-shift this APInt by shiftAmt.
989 APInt lshr(unsigned shiftAmt) const {
991 R.lshrInPlace(shiftAmt);
995 /// Logical right-shift this APInt by ShiftAmt in place.
996 void lshrInPlace(unsigned ShiftAmt) {
997 assert(ShiftAmt <= BitWidth && "Invalid shift amount");
998 if (isSingleWord()) {
999 if (ShiftAmt == BitWidth)
1005 lshrSlowCase(ShiftAmt);
1008 /// Left-shift function.
1010 /// Left-shift this APInt by shiftAmt.
1011 APInt shl(unsigned shiftAmt) const {
1017 /// Rotate left by rotateAmt.
1018 APInt rotl(unsigned rotateAmt) const;
1020 /// Rotate right by rotateAmt.
1021 APInt rotr(unsigned rotateAmt) const;
1023 /// Arithmetic right-shift function.
1025 /// Arithmetic right-shift this APInt by shiftAmt.
1026 APInt ashr(const APInt &ShiftAmt) const {
1028 R.ashrInPlace(ShiftAmt);
1032 /// Arithmetic right-shift this APInt by shiftAmt in place.
1033 void ashrInPlace(const APInt &shiftAmt);
1035 /// Logical right-shift function.
1037 /// Logical right-shift this APInt by shiftAmt.
1038 APInt lshr(const APInt &ShiftAmt) const {
1040 R.lshrInPlace(ShiftAmt);
1044 /// Logical right-shift this APInt by ShiftAmt in place.
1045 void lshrInPlace(const APInt &ShiftAmt);
1047 /// Left-shift function.
1049 /// Left-shift this APInt by shiftAmt.
1050 APInt shl(const APInt &ShiftAmt) const {
1056 /// Rotate left by rotateAmt.
1057 APInt rotl(const APInt &rotateAmt) const;
1059 /// Rotate right by rotateAmt.
1060 APInt rotr(const APInt &rotateAmt) const;
1062 /// Unsigned division operation.
1064 /// Perform an unsigned divide operation on this APInt by RHS. Both this and
1065 /// RHS are treated as unsigned quantities for purposes of this division.
1067 /// \returns a new APInt value containing the division result, rounded towards
1069 APInt udiv(const APInt &RHS) const;
1070 APInt udiv(uint64_t RHS) const;
1072 /// Signed division function for APInt.
1074 /// Signed divide this APInt by APInt RHS.
1076 /// The result is rounded towards zero.
1077 APInt sdiv(const APInt &RHS) const;
1078 APInt sdiv(int64_t RHS) const;
1080 /// Unsigned remainder operation.
1082 /// Perform an unsigned remainder operation on this APInt with RHS being the
1083 /// divisor. Both this and RHS are treated as unsigned quantities for purposes
1084 /// of this operation. Note that this is a true remainder operation and not a
1085 /// modulo operation because the sign follows the sign of the dividend which
1088 /// \returns a new APInt value containing the remainder result
1089 APInt urem(const APInt &RHS) const;
1090 uint64_t urem(uint64_t RHS) const;
1092 /// Function for signed remainder operation.
1094 /// Signed remainder operation on APInt.
1095 APInt srem(const APInt &RHS) const;
1096 int64_t srem(int64_t RHS) const;
1098 /// Dual division/remainder interface.
1100 /// Sometimes it is convenient to divide two APInt values and obtain both the
1101 /// quotient and remainder. This function does both operations in the same
1102 /// computation making it a little more efficient. The pair of input arguments
1103 /// may overlap with the pair of output arguments. It is safe to call
1104 /// udivrem(X, Y, X, Y), for example.
1105 static void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient,
1107 static void udivrem(const APInt &LHS, uint64_t RHS, APInt &Quotient,
1108 uint64_t &Remainder);
1110 static void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient,
1112 static void sdivrem(const APInt &LHS, int64_t RHS, APInt &Quotient,
1113 int64_t &Remainder);
1115 // Operations that return overflow indicators.
1116 APInt sadd_ov(const APInt &RHS, bool &Overflow) const;
1117 APInt uadd_ov(const APInt &RHS, bool &Overflow) const;
1118 APInt ssub_ov(const APInt &RHS, bool &Overflow) const;
1119 APInt usub_ov(const APInt &RHS, bool &Overflow) const;
1120 APInt sdiv_ov(const APInt &RHS, bool &Overflow) const;
1121 APInt smul_ov(const APInt &RHS, bool &Overflow) const;
1122 APInt umul_ov(const APInt &RHS, bool &Overflow) const;
1123 APInt sshl_ov(const APInt &Amt, bool &Overflow) const;
1124 APInt ushl_ov(const APInt &Amt, bool &Overflow) const;
1126 // Operations that saturate
1127 APInt sadd_sat(const APInt &RHS) const;
1128 APInt uadd_sat(const APInt &RHS) const;
1129 APInt ssub_sat(const APInt &RHS) const;
1130 APInt usub_sat(const APInt &RHS) const;
1131 APInt smul_sat(const APInt &RHS) const;
1132 APInt umul_sat(const APInt &RHS) const;
1133 APInt sshl_sat(const APInt &RHS) const;
1134 APInt ushl_sat(const APInt &RHS) const;
1136 /// Array-indexing support.
1138 /// \returns the bit value at bitPosition
1139 bool operator[](unsigned bitPosition) const {
1140 assert(bitPosition < getBitWidth() && "Bit position out of bounds!");
1141 return (maskBit(bitPosition) & getWord(bitPosition)) != 0;
1145 /// \name Comparison Operators
1148 /// Equality operator.
1150 /// Compares this APInt with RHS for the validity of the equality
1152 bool operator==(const APInt &RHS) const {
1153 assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths");
1155 return U.VAL == RHS.U.VAL;
1156 return EqualSlowCase(RHS);
1159 /// Equality operator.
1161 /// Compares this APInt with a uint64_t for the validity of the equality
1164 /// \returns true if *this == Val
1165 bool operator==(uint64_t Val) const {
1166 return (isSingleWord() || getActiveBits() <= 64) && getZExtValue() == Val;
1169 /// Equality comparison.
1171 /// Compares this APInt with RHS for the validity of the equality
1174 /// \returns true if *this == Val
1175 bool eq(const APInt &RHS) const { return (*this) == RHS; }
1177 /// Inequality operator.
1179 /// Compares this APInt with RHS for the validity of the inequality
1182 /// \returns true if *this != Val
1183 bool operator!=(const APInt &RHS) const { return !((*this) == RHS); }
1185 /// Inequality operator.
1187 /// Compares this APInt with a uint64_t for the validity of the inequality
1190 /// \returns true if *this != Val
1191 bool operator!=(uint64_t Val) const { return !((*this) == Val); }
1193 /// Inequality comparison
1195 /// Compares this APInt with RHS for the validity of the inequality
1198 /// \returns true if *this != Val
1199 bool ne(const APInt &RHS) const { return !((*this) == RHS); }
1201 /// Unsigned less than comparison
1203 /// Regards both *this and RHS as unsigned quantities and compares them for
1204 /// the validity of the less-than relationship.
1206 /// \returns true if *this < RHS when both are considered unsigned.
1207 bool ult(const APInt &RHS) const { return compare(RHS) < 0; }
1209 /// Unsigned less than comparison
1211 /// Regards both *this as an unsigned quantity and compares it with RHS for
1212 /// the validity of the less-than relationship.
1214 /// \returns true if *this < RHS when considered unsigned.
1215 bool ult(uint64_t RHS) const {
1216 // Only need to check active bits if not a single word.
1217 return (isSingleWord() || getActiveBits() <= 64) && getZExtValue() < RHS;
1220 /// Signed less than comparison
1222 /// Regards both *this and RHS as signed quantities and compares them for
1223 /// validity of the less-than relationship.
1225 /// \returns true if *this < RHS when both are considered signed.
1226 bool slt(const APInt &RHS) const { return compareSigned(RHS) < 0; }
1228 /// Signed less than comparison
1230 /// Regards both *this as a signed quantity and compares it with RHS for
1231 /// the validity of the less-than relationship.
1233 /// \returns true if *this < RHS when considered signed.
1234 bool slt(int64_t RHS) const {
1235 return (!isSingleWord() && getMinSignedBits() > 64) ? isNegative()
1236 : getSExtValue() < RHS;
1239 /// Unsigned less or equal comparison
1241 /// Regards both *this and RHS as unsigned quantities and compares them for
1242 /// validity of the less-or-equal relationship.
1244 /// \returns true if *this <= RHS when both are considered unsigned.
1245 bool ule(const APInt &RHS) const { return compare(RHS) <= 0; }
1247 /// Unsigned less or equal comparison
1249 /// Regards both *this as an unsigned quantity and compares it with RHS for
1250 /// the validity of the less-or-equal relationship.
1252 /// \returns true if *this <= RHS when considered unsigned.
1253 bool ule(uint64_t RHS) const { return !ugt(RHS); }
1255 /// Signed less or equal comparison
1257 /// Regards both *this and RHS as signed quantities and compares them for
1258 /// validity of the less-or-equal relationship.
1260 /// \returns true if *this <= RHS when both are considered signed.
1261 bool sle(const APInt &RHS) const { return compareSigned(RHS) <= 0; }
1263 /// Signed less or equal comparison
1265 /// Regards both *this as a signed quantity and compares it with RHS for the
1266 /// validity of the less-or-equal relationship.
1268 /// \returns true if *this <= RHS when considered signed.
1269 bool sle(uint64_t RHS) const { return !sgt(RHS); }
1271 /// Unsigned greater than comparison
1273 /// Regards both *this and RHS as unsigned quantities and compares them for
1274 /// the validity of the greater-than relationship.
1276 /// \returns true if *this > RHS when both are considered unsigned.
1277 bool ugt(const APInt &RHS) const { return !ule(RHS); }
1279 /// Unsigned greater than comparison
1281 /// Regards both *this as an unsigned quantity and compares it with RHS for
1282 /// the validity of the greater-than relationship.
1284 /// \returns true if *this > RHS when considered unsigned.
1285 bool ugt(uint64_t RHS) const {
1286 // Only need to check active bits if not a single word.
1287 return (!isSingleWord() && getActiveBits() > 64) || getZExtValue() > RHS;
1290 /// Signed greater than comparison
1292 /// Regards both *this and RHS as signed quantities and compares them for the
1293 /// validity of the greater-than relationship.
1295 /// \returns true if *this > RHS when both are considered signed.
1296 bool sgt(const APInt &RHS) const { return !sle(RHS); }
1298 /// Signed greater than comparison
1300 /// Regards both *this as a signed quantity and compares it with RHS for
1301 /// the validity of the greater-than relationship.
1303 /// \returns true if *this > RHS when considered signed.
1304 bool sgt(int64_t RHS) const {
1305 return (!isSingleWord() && getMinSignedBits() > 64) ? !isNegative()
1306 : getSExtValue() > RHS;
1309 /// Unsigned greater or equal comparison
1311 /// Regards both *this and RHS as unsigned quantities and compares them for
1312 /// validity of the greater-or-equal relationship.
1314 /// \returns true if *this >= RHS when both are considered unsigned.
1315 bool uge(const APInt &RHS) const { return !ult(RHS); }
1317 /// Unsigned greater or equal comparison
1319 /// Regards both *this as an unsigned quantity and compares it with RHS for
1320 /// the validity of the greater-or-equal relationship.
1322 /// \returns true if *this >= RHS when considered unsigned.
1323 bool uge(uint64_t RHS) const { return !ult(RHS); }
1325 /// Signed greater or equal comparison
1327 /// Regards both *this and RHS as signed quantities and compares them for
1328 /// validity of the greater-or-equal relationship.
1330 /// \returns true if *this >= RHS when both are considered signed.
1331 bool sge(const APInt &RHS) const { return !slt(RHS); }
1333 /// Signed greater or equal comparison
1335 /// Regards both *this as a signed quantity and compares it with RHS for
1336 /// the validity of the greater-or-equal relationship.
1338 /// \returns true if *this >= RHS when considered signed.
1339 bool sge(int64_t RHS) const { return !slt(RHS); }
1341 /// This operation tests if there are any pairs of corresponding bits
1342 /// between this APInt and RHS that are both set.
1343 bool intersects(const APInt &RHS) const {
1344 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1346 return (U.VAL & RHS.U.VAL) != 0;
1347 return intersectsSlowCase(RHS);
1350 /// This operation checks that all bits set in this APInt are also set in RHS.
1351 bool isSubsetOf(const APInt &RHS) const {
1352 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1354 return (U.VAL & ~RHS.U.VAL) == 0;
1355 return isSubsetOfSlowCase(RHS);
1359 /// \name Resizing Operators
1362 /// Truncate to new width.
1364 /// Truncate the APInt to a specified width. It is an error to specify a width
1365 /// that is greater than or equal to the current width.
1366 APInt trunc(unsigned width) const;
1368 /// Truncate to new width with unsigned saturation.
1370 /// If the APInt, treated as unsigned integer, can be losslessly truncated to
1371 /// the new bitwidth, then return truncated APInt. Else, return max value.
1372 APInt truncUSat(unsigned width) const;
1374 /// Truncate to new width with signed saturation.
1376 /// If this APInt, treated as signed integer, can be losslessly truncated to
1377 /// the new bitwidth, then return truncated APInt. Else, return either
1378 /// signed min value if the APInt was negative, or signed max value.
1379 APInt truncSSat(unsigned width) const;
1381 /// Sign extend to a new width.
1383 /// This operation sign extends the APInt to a new width. If the high order
1384 /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
1385 /// It is an error to specify a width that is less than or equal to the
1387 APInt sext(unsigned width) const;
1389 /// Zero extend to a new width.
1391 /// This operation zero extends the APInt to a new width. The high order bits
1392 /// are filled with 0 bits. It is an error to specify a width that is less
1393 /// than or equal to the current width.
1394 APInt zext(unsigned width) const;
1396 /// Sign extend or truncate to width
1398 /// Make this APInt have the bit width given by \p width. The value is sign
1399 /// extended, truncated, or left alone to make it that width.
1400 APInt sextOrTrunc(unsigned width) const;
1402 /// Zero extend or truncate to width
1404 /// Make this APInt have the bit width given by \p width. The value is zero
1405 /// extended, truncated, or left alone to make it that width.
1406 APInt zextOrTrunc(unsigned width) const;
1408 /// Sign extend or truncate to width
1410 /// Make this APInt have the bit width given by \p width. The value is sign
1411 /// extended, or left alone to make it that width.
1412 APInt sextOrSelf(unsigned width) const;
1414 /// Zero extend or truncate to width
1416 /// Make this APInt have the bit width given by \p width. The value is zero
1417 /// extended, or left alone to make it that width.
1418 APInt zextOrSelf(unsigned width) const;
1421 /// \name Bit Manipulation Operators
1424 /// Set every bit to 1.
1427 U.VAL = WORDTYPE_MAX;
1429 // Set all the bits in all the words.
1430 memset(U.pVal, -1, getNumWords() * APINT_WORD_SIZE);
1431 // Clear the unused ones
1435 /// Set a given bit to 1.
1437 /// Set the given bit to 1 whose position is given as "bitPosition".
1438 void setBit(unsigned BitPosition) {
1439 assert(BitPosition < BitWidth && "BitPosition out of range");
1440 WordType Mask = maskBit(BitPosition);
1444 U.pVal[whichWord(BitPosition)] |= Mask;
1447 /// Set the sign bit to 1.
1449 setBit(BitWidth - 1);
1452 /// Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
1453 /// This function handles "wrap" case when \p loBit >= \p hiBit, and calls
1454 /// setBits when \p loBit < \p hiBit.
1455 /// For \p loBit == \p hiBit wrap case, set every bit to 1.
1456 void setBitsWithWrap(unsigned loBit, unsigned hiBit) {
1457 assert(hiBit <= BitWidth && "hiBit out of range");
1458 assert(loBit <= BitWidth && "loBit out of range");
1459 if (loBit < hiBit) {
1460 setBits(loBit, hiBit);
1464 setHighBits(BitWidth - loBit);
1467 /// Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
1468 /// This function handles case when \p loBit <= \p hiBit.
1469 void setBits(unsigned loBit, unsigned hiBit) {
1470 assert(hiBit <= BitWidth && "hiBit out of range");
1471 assert(loBit <= BitWidth && "loBit out of range");
1472 assert(loBit <= hiBit && "loBit greater than hiBit");
1475 if (loBit < APINT_BITS_PER_WORD && hiBit <= APINT_BITS_PER_WORD) {
1476 uint64_t mask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - (hiBit - loBit));
1483 setBitsSlowCase(loBit, hiBit);
1487 /// Set the top bits starting from loBit.
1488 void setBitsFrom(unsigned loBit) {
1489 return setBits(loBit, BitWidth);
1492 /// Set the bottom loBits bits.
1493 void setLowBits(unsigned loBits) {
1494 return setBits(0, loBits);
1497 /// Set the top hiBits bits.
1498 void setHighBits(unsigned hiBits) {
1499 return setBits(BitWidth - hiBits, BitWidth);
1502 /// Set every bit to 0.
1503 void clearAllBits() {
1507 memset(U.pVal, 0, getNumWords() * APINT_WORD_SIZE);
1510 /// Set a given bit to 0.
1512 /// Set the given bit to 0 whose position is given as "bitPosition".
1513 void clearBit(unsigned BitPosition) {
1514 assert(BitPosition < BitWidth && "BitPosition out of range");
1515 WordType Mask = ~maskBit(BitPosition);
1519 U.pVal[whichWord(BitPosition)] &= Mask;
1522 /// Set bottom loBits bits to 0.
1523 void clearLowBits(unsigned loBits) {
1524 assert(loBits <= BitWidth && "More bits than bitwidth");
1525 APInt Keep = getHighBitsSet(BitWidth, BitWidth - loBits);
1529 /// Set the sign bit to 0.
1530 void clearSignBit() {
1531 clearBit(BitWidth - 1);
1534 /// Toggle every bit to its opposite value.
1535 void flipAllBits() {
1536 if (isSingleWord()) {
1537 U.VAL ^= WORDTYPE_MAX;
1540 flipAllBitsSlowCase();
1544 /// Toggles a given bit to its opposite value.
1546 /// Toggle a given bit to its opposite value whose position is given
1547 /// as "bitPosition".
1548 void flipBit(unsigned bitPosition);
1550 /// Negate this APInt in place.
1556 /// Insert the bits from a smaller APInt starting at bitPosition.
1557 void insertBits(const APInt &SubBits, unsigned bitPosition);
1558 void insertBits(uint64_t SubBits, unsigned bitPosition, unsigned numBits);
1560 /// Return an APInt with the extracted bits [bitPosition,bitPosition+numBits).
1561 APInt extractBits(unsigned numBits, unsigned bitPosition) const;
1562 uint64_t extractBitsAsZExtValue(unsigned numBits, unsigned bitPosition) const;
1565 /// \name Value Characterization Functions
1568 /// Return the number of bits in the APInt.
1569 unsigned getBitWidth() const { return BitWidth; }
1571 /// Get the number of words.
1573 /// Here one word's bitwidth equals to that of uint64_t.
1575 /// \returns the number of words to hold the integer value of this APInt.
1576 unsigned getNumWords() const { return getNumWords(BitWidth); }
1578 /// Get the number of words.
1580 /// *NOTE* Here one word's bitwidth equals to that of uint64_t.
1582 /// \returns the number of words to hold the integer value with a given bit
1584 static unsigned getNumWords(unsigned BitWidth) {
1585 return ((uint64_t)BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
1588 /// Compute the number of active bits in the value
1590 /// This function returns the number of active bits which is defined as the
1591 /// bit width minus the number of leading zeros. This is used in several
1592 /// computations to see how "wide" the value is.
1593 unsigned getActiveBits() const { return BitWidth - countLeadingZeros(); }
1595 /// Compute the number of active words in the value of this APInt.
1597 /// This is used in conjunction with getActiveData to extract the raw value of
1599 unsigned getActiveWords() const {
1600 unsigned numActiveBits = getActiveBits();
1601 return numActiveBits ? whichWord(numActiveBits - 1) + 1 : 1;
1604 /// Get the minimum bit size for this signed APInt
1606 /// Computes the minimum bit width for this APInt while considering it to be a
1607 /// signed (and probably negative) value. If the value is not negative, this
1608 /// function returns the same value as getActiveBits()+1. Otherwise, it
1609 /// returns the smallest bit width that will retain the negative value. For
1610 /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
1611 /// for -1, this function will always return 1.
1612 unsigned getMinSignedBits() const {
1614 return BitWidth - countLeadingOnes() + 1;
1615 return getActiveBits() + 1;
1618 /// Get zero extended value
1620 /// This method attempts to return the value of this APInt as a zero extended
1621 /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
1622 /// uint64_t. Otherwise an assertion will result.
1623 uint64_t getZExtValue() const {
1626 assert(getActiveBits() <= 64 && "Too many bits for uint64_t");
1630 /// Get sign extended value
1632 /// This method attempts to return the value of this APInt as a sign extended
1633 /// int64_t. The bit width must be <= 64 or the value must fit within an
1634 /// int64_t. Otherwise an assertion will result.
1635 int64_t getSExtValue() const {
1637 return SignExtend64(U.VAL, BitWidth);
1638 assert(getMinSignedBits() <= 64 && "Too many bits for int64_t");
1639 return int64_t(U.pVal[0]);
1642 /// Get bits required for string value.
1644 /// This method determines how many bits are required to hold the APInt
1645 /// equivalent of the string given by \p str.
1646 static unsigned getBitsNeeded(StringRef str, uint8_t radix);
1648 /// The APInt version of the countLeadingZeros functions in
1651 /// It counts the number of zeros from the most significant bit to the first
1654 /// \returns BitWidth if the value is zero, otherwise returns the number of
1655 /// zeros from the most significant bit to the first one bits.
1656 unsigned countLeadingZeros() const {
1657 if (isSingleWord()) {
1658 unsigned unusedBits = APINT_BITS_PER_WORD - BitWidth;
1659 return llvm::countLeadingZeros(U.VAL) - unusedBits;
1661 return countLeadingZerosSlowCase();
1664 /// Count the number of leading one bits.
1666 /// This function is an APInt version of the countLeadingOnes
1667 /// functions in MathExtras.h. It counts the number of ones from the most
1668 /// significant bit to the first zero bit.
1670 /// \returns 0 if the high order bit is not set, otherwise returns the number
1671 /// of 1 bits from the most significant to the least
1672 unsigned countLeadingOnes() const {
1674 return llvm::countLeadingOnes(U.VAL << (APINT_BITS_PER_WORD - BitWidth));
1675 return countLeadingOnesSlowCase();
1678 /// Computes the number of leading bits of this APInt that are equal to its
1680 unsigned getNumSignBits() const {
1681 return isNegative() ? countLeadingOnes() : countLeadingZeros();
1684 /// Count the number of trailing zero bits.
1686 /// This function is an APInt version of the countTrailingZeros
1687 /// functions in MathExtras.h. It counts the number of zeros from the least
1688 /// significant bit to the first set bit.
1690 /// \returns BitWidth if the value is zero, otherwise returns the number of
1691 /// zeros from the least significant bit to the first one bit.
1692 unsigned countTrailingZeros() const {
1694 return std::min(unsigned(llvm::countTrailingZeros(U.VAL)), BitWidth);
1695 return countTrailingZerosSlowCase();
1698 /// Count the number of trailing one bits.
1700 /// This function is an APInt version of the countTrailingOnes
1701 /// functions in MathExtras.h. It counts the number of ones from the least
1702 /// significant bit to the first zero bit.
1704 /// \returns BitWidth if the value is all ones, otherwise returns the number
1705 /// of ones from the least significant bit to the first zero bit.
1706 unsigned countTrailingOnes() const {
1708 return llvm::countTrailingOnes(U.VAL);
1709 return countTrailingOnesSlowCase();
1712 /// Count the number of bits set.
1714 /// This function is an APInt version of the countPopulation functions
1715 /// in MathExtras.h. It counts the number of 1 bits in the APInt value.
1717 /// \returns 0 if the value is zero, otherwise returns the number of set bits.
1718 unsigned countPopulation() const {
1720 return llvm::countPopulation(U.VAL);
1721 return countPopulationSlowCase();
1725 /// \name Conversion Functions
1727 void print(raw_ostream &OS, bool isSigned) const;
1729 /// Converts an APInt to a string and append it to Str. Str is commonly a
1731 void toString(SmallVectorImpl<char> &Str, unsigned Radix, bool Signed,
1732 bool formatAsCLiteral = false) const;
1734 /// Considers the APInt to be unsigned and converts it into a string in the
1735 /// radix given. The radix can be 2, 8, 10 16, or 36.
1736 void toStringUnsigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1737 toString(Str, Radix, false, false);
1740 /// Considers the APInt to be signed and converts it into a string in the
1741 /// radix given. The radix can be 2, 8, 10, 16, or 36.
1742 void toStringSigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1743 toString(Str, Radix, true, false);
1746 /// Return the APInt as a std::string.
1748 /// Note that this is an inefficient method. It is better to pass in a
1749 /// SmallVector/SmallString to the methods above to avoid thrashing the heap
1751 std::string toString(unsigned Radix, bool Signed) const;
1753 /// \returns a byte-swapped representation of this APInt Value.
1754 APInt byteSwap() const;
1756 /// \returns the value with the bit representation reversed of this APInt
1758 APInt reverseBits() const;
1760 /// Converts this APInt to a double value.
1761 double roundToDouble(bool isSigned) const;
1763 /// Converts this unsigned APInt to a double value.
1764 double roundToDouble() const { return roundToDouble(false); }
1766 /// Converts this signed APInt to a double value.
1767 double signedRoundToDouble() const { return roundToDouble(true); }
1769 /// Converts APInt bits to a double
1771 /// The conversion does not do a translation from integer to double, it just
1772 /// re-interprets the bits as a double. Note that it is valid to do this on
1773 /// any bit width. Exactly 64 bits will be translated.
1774 double bitsToDouble() const {
1775 return BitsToDouble(getWord(0));
1778 /// Converts APInt bits to a float
1780 /// The conversion does not do a translation from integer to float, it just
1781 /// re-interprets the bits as a float. Note that it is valid to do this on
1782 /// any bit width. Exactly 32 bits will be translated.
1783 float bitsToFloat() const {
1784 return BitsToFloat(static_cast<uint32_t>(getWord(0)));
1787 /// Converts a double to APInt bits.
1789 /// The conversion does not do a translation from double to integer, it just
1790 /// re-interprets the bits of the double.
1791 static APInt doubleToBits(double V) {
1792 return APInt(sizeof(double) * CHAR_BIT, DoubleToBits(V));
1795 /// Converts a float to APInt bits.
1797 /// The conversion does not do a translation from float to integer, it just
1798 /// re-interprets the bits of the float.
1799 static APInt floatToBits(float V) {
1800 return APInt(sizeof(float) * CHAR_BIT, FloatToBits(V));
1804 /// \name Mathematics Operations
1807 /// \returns the floor log base 2 of this APInt.
1808 unsigned logBase2() const { return getActiveBits() - 1; }
1810 /// \returns the ceil log base 2 of this APInt.
1811 unsigned ceilLogBase2() const {
1814 return temp.getActiveBits();
1817 /// \returns the nearest log base 2 of this APInt. Ties round up.
1819 /// NOTE: When we have a BitWidth of 1, we define:
1821 /// log2(0) = UINT32_MAX
1824 /// to get around any mathematical concerns resulting from
1825 /// referencing 2 in a space where 2 does no exist.
1826 unsigned nearestLogBase2() const {
1827 // Special case when we have a bitwidth of 1. If VAL is 1, then we
1828 // get 0. If VAL is 0, we get WORDTYPE_MAX which gets truncated to
1833 // Handle the zero case.
1837 // The non-zero case is handled by computing:
1839 // nearestLogBase2(x) = logBase2(x) + x[logBase2(x)-1].
1841 // where x[i] is referring to the value of the ith bit of x.
1842 unsigned lg = logBase2();
1843 return lg + unsigned((*this)[lg - 1]);
1846 /// \returns the log base 2 of this APInt if its an exact power of two, -1
1848 int32_t exactLogBase2() const {
1854 /// Compute the square root
1857 /// Get the absolute value;
1859 /// If *this is < 0 then return -(*this), otherwise *this;
1866 /// \returns the multiplicative inverse for a given modulo.
1867 APInt multiplicativeInverse(const APInt &modulo) const;
1870 /// \name Support for division by constant
1873 /// Calculate the magic number for signed division by a constant.
1877 /// Calculate the magic number for unsigned division by a constant.
1879 mu magicu(unsigned LeadingZeros = 0) const;
1882 /// \name Building-block Operations for APInt and APFloat
1885 // These building block operations operate on a representation of arbitrary
1886 // precision, two's-complement, bignum integer values. They should be
1887 // sufficient to implement APInt and APFloat bignum requirements. Inputs are
1888 // generally a pointer to the base of an array of integer parts, representing
1889 // an unsigned bignum, and a count of how many parts there are.
1891 /// Sets the least significant part of a bignum to the input value, and zeroes
1892 /// out higher parts.
1893 static void tcSet(WordType *, WordType, unsigned);
1895 /// Assign one bignum to another.
1896 static void tcAssign(WordType *, const WordType *, unsigned);
1898 /// Returns true if a bignum is zero, false otherwise.
1899 static bool tcIsZero(const WordType *, unsigned);
1901 /// Extract the given bit of a bignum; returns 0 or 1. Zero-based.
1902 static int tcExtractBit(const WordType *, unsigned bit);
1904 /// Copy the bit vector of width srcBITS from SRC, starting at bit srcLSB, to
1905 /// DST, of dstCOUNT parts, such that the bit srcLSB becomes the least
1906 /// significant bit of DST. All high bits above srcBITS in DST are
1908 static void tcExtract(WordType *, unsigned dstCount,
1909 const WordType *, unsigned srcBits,
1912 /// Set the given bit of a bignum. Zero-based.
1913 static void tcSetBit(WordType *, unsigned bit);
1915 /// Clear the given bit of a bignum. Zero-based.
1916 static void tcClearBit(WordType *, unsigned bit);
1918 /// Returns the bit number of the least or most significant set bit of a
1919 /// number. If the input number has no bits set -1U is returned.
1920 static unsigned tcLSB(const WordType *, unsigned n);
1921 static unsigned tcMSB(const WordType *parts, unsigned n);
1923 /// Negate a bignum in-place.
1924 static void tcNegate(WordType *, unsigned);
1926 /// DST += RHS + CARRY where CARRY is zero or one. Returns the carry flag.
1927 static WordType tcAdd(WordType *, const WordType *,
1928 WordType carry, unsigned);
1929 /// DST += RHS. Returns the carry flag.
1930 static WordType tcAddPart(WordType *, WordType, unsigned);
1932 /// DST -= RHS + CARRY where CARRY is zero or one. Returns the carry flag.
1933 static WordType tcSubtract(WordType *, const WordType *,
1934 WordType carry, unsigned);
1935 /// DST -= RHS. Returns the carry flag.
1936 static WordType tcSubtractPart(WordType *, WordType, unsigned);
1938 /// DST += SRC * MULTIPLIER + PART if add is true
1939 /// DST = SRC * MULTIPLIER + PART if add is false
1941 /// Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC they must
1942 /// start at the same point, i.e. DST == SRC.
1944 /// If DSTPARTS == SRC_PARTS + 1 no overflow occurs and zero is returned.
1945 /// Otherwise DST is filled with the least significant DSTPARTS parts of the
1946 /// result, and if all of the omitted higher parts were zero return zero,
1947 /// otherwise overflow occurred and return one.
1948 static int tcMultiplyPart(WordType *dst, const WordType *src,
1949 WordType multiplier, WordType carry,
1950 unsigned srcParts, unsigned dstParts,
1953 /// DST = LHS * RHS, where DST has the same width as the operands and is
1954 /// filled with the least significant parts of the result. Returns one if
1955 /// overflow occurred, otherwise zero. DST must be disjoint from both
1957 static int tcMultiply(WordType *, const WordType *, const WordType *,
1960 /// DST = LHS * RHS, where DST has width the sum of the widths of the
1961 /// operands. No overflow occurs. DST must be disjoint from both operands.
1962 static void tcFullMultiply(WordType *, const WordType *,
1963 const WordType *, unsigned, unsigned);
1965 /// If RHS is zero LHS and REMAINDER are left unchanged, return one.
1966 /// Otherwise set LHS to LHS / RHS with the fractional part discarded, set
1967 /// REMAINDER to the remainder, return zero. i.e.
1969 /// OLD_LHS = RHS * LHS + REMAINDER
1971 /// SCRATCH is a bignum of the same size as the operands and result for use by
1972 /// the routine; its contents need not be initialized and are destroyed. LHS,
1973 /// REMAINDER and SCRATCH must be distinct.
1974 static int tcDivide(WordType *lhs, const WordType *rhs,
1975 WordType *remainder, WordType *scratch,
1978 /// Shift a bignum left Count bits. Shifted in bits are zero. There are no
1979 /// restrictions on Count.
1980 static void tcShiftLeft(WordType *, unsigned Words, unsigned Count);
1982 /// Shift a bignum right Count bits. Shifted in bits are zero. There are no
1983 /// restrictions on Count.
1984 static void tcShiftRight(WordType *, unsigned Words, unsigned Count);
1986 /// The obvious AND, OR and XOR and complement operations.
1987 static void tcAnd(WordType *, const WordType *, unsigned);
1988 static void tcOr(WordType *, const WordType *, unsigned);
1989 static void tcXor(WordType *, const WordType *, unsigned);
1990 static void tcComplement(WordType *, unsigned);
1992 /// Comparison (unsigned) of two bignums.
1993 static int tcCompare(const WordType *, const WordType *, unsigned);
1995 /// Increment a bignum in-place. Return the carry flag.
1996 static WordType tcIncrement(WordType *dst, unsigned parts) {
1997 return tcAddPart(dst, 1, parts);
2000 /// Decrement a bignum in-place. Return the borrow flag.
2001 static WordType tcDecrement(WordType *dst, unsigned parts) {
2002 return tcSubtractPart(dst, 1, parts);
2005 /// Set the least significant BITS and clear the rest.
2006 static void tcSetLeastSignificantBits(WordType *, unsigned, unsigned bits);
2014 /// Magic data for optimising signed division by a constant.
2016 APInt m; ///< magic number
2017 unsigned s; ///< shift amount
2020 /// Magic data for optimising unsigned division by a constant.
2022 APInt m; ///< magic number
2023 bool a; ///< add indicator
2024 unsigned s; ///< shift amount
2027 inline bool operator==(uint64_t V1, const APInt &V2) { return V2 == V1; }
2029 inline bool operator!=(uint64_t V1, const APInt &V2) { return V2 != V1; }
2031 /// Unary bitwise complement operator.
2033 /// \returns an APInt that is the bitwise complement of \p v.
2034 inline APInt operator~(APInt v) {
2039 inline APInt operator&(APInt a, const APInt &b) {
2044 inline APInt operator&(const APInt &a, APInt &&b) {
2046 return std::move(b);
2049 inline APInt operator&(APInt a, uint64_t RHS) {
2054 inline APInt operator&(uint64_t LHS, APInt b) {
2059 inline APInt operator|(APInt a, const APInt &b) {
2064 inline APInt operator|(const APInt &a, APInt &&b) {
2066 return std::move(b);
2069 inline APInt operator|(APInt a, uint64_t RHS) {
2074 inline APInt operator|(uint64_t LHS, APInt b) {
2079 inline APInt operator^(APInt a, const APInt &b) {
2084 inline APInt operator^(const APInt &a, APInt &&b) {
2086 return std::move(b);
2089 inline APInt operator^(APInt a, uint64_t RHS) {
2094 inline APInt operator^(uint64_t LHS, APInt b) {
2099 inline raw_ostream &operator<<(raw_ostream &OS, const APInt &I) {
2104 inline APInt operator-(APInt v) {
2109 inline APInt operator+(APInt a, const APInt &b) {
2114 inline APInt operator+(const APInt &a, APInt &&b) {
2116 return std::move(b);
2119 inline APInt operator+(APInt a, uint64_t RHS) {
2124 inline APInt operator+(uint64_t LHS, APInt b) {
2129 inline APInt operator-(APInt a, const APInt &b) {
2134 inline APInt operator-(const APInt &a, APInt &&b) {
2137 return std::move(b);
2140 inline APInt operator-(APInt a, uint64_t RHS) {
2145 inline APInt operator-(uint64_t LHS, APInt b) {
2151 inline APInt operator*(APInt a, uint64_t RHS) {
2156 inline APInt operator*(uint64_t LHS, APInt b) {
2162 namespace APIntOps {
2164 /// Determine the smaller of two APInts considered to be signed.
2165 inline const APInt &smin(const APInt &A, const APInt &B) {
2166 return A.slt(B) ? A : B;
2169 /// Determine the larger of two APInts considered to be signed.
2170 inline const APInt &smax(const APInt &A, const APInt &B) {
2171 return A.sgt(B) ? A : B;
2174 /// Determine the smaller of two APInts considered to be signed.
2175 inline const APInt &umin(const APInt &A, const APInt &B) {
2176 return A.ult(B) ? A : B;
2179 /// Determine the larger of two APInts considered to be unsigned.
2180 inline const APInt &umax(const APInt &A, const APInt &B) {
2181 return A.ugt(B) ? A : B;
2184 /// Compute GCD of two unsigned APInt values.
2186 /// This function returns the greatest common divisor of the two APInt values
2187 /// using Stein's algorithm.
2189 /// \returns the greatest common divisor of A and B.
2190 APInt GreatestCommonDivisor(APInt A, APInt B);
2192 /// Converts the given APInt to a double value.
2194 /// Treats the APInt as an unsigned value for conversion purposes.
2195 inline double RoundAPIntToDouble(const APInt &APIVal) {
2196 return APIVal.roundToDouble();
2199 /// Converts the given APInt to a double value.
2201 /// Treats the APInt as a signed value for conversion purposes.
2202 inline double RoundSignedAPIntToDouble(const APInt &APIVal) {
2203 return APIVal.signedRoundToDouble();
2206 /// Converts the given APInt to a float vlalue.
2207 inline float RoundAPIntToFloat(const APInt &APIVal) {
2208 return float(RoundAPIntToDouble(APIVal));
2211 /// Converts the given APInt to a float value.
2213 /// Treats the APInt as a signed value for conversion purposes.
2214 inline float RoundSignedAPIntToFloat(const APInt &APIVal) {
2215 return float(APIVal.signedRoundToDouble());
2218 /// Converts the given double value into a APInt.
2220 /// This function convert a double value to an APInt value.
2221 APInt RoundDoubleToAPInt(double Double, unsigned width);
2223 /// Converts a float value into a APInt.
2225 /// Converts a float value into an APInt value.
2226 inline APInt RoundFloatToAPInt(float Float, unsigned width) {
2227 return RoundDoubleToAPInt(double(Float), width);
2230 /// Return A unsign-divided by B, rounded by the given rounding mode.
2231 APInt RoundingUDiv(const APInt &A, const APInt &B, APInt::Rounding RM);
2233 /// Return A sign-divided by B, rounded by the given rounding mode.
2234 APInt RoundingSDiv(const APInt &A, const APInt &B, APInt::Rounding RM);
2236 /// Let q(n) = An^2 + Bn + C, and BW = bit width of the value range
2237 /// (e.g. 32 for i32).
2238 /// This function finds the smallest number n, such that
2239 /// (a) n >= 0 and q(n) = 0, or
2240 /// (b) n >= 1 and q(n-1) and q(n), when evaluated in the set of all
2241 /// integers, belong to two different intervals [Rk, Rk+R),
2242 /// where R = 2^BW, and k is an integer.
2243 /// The idea here is to find when q(n) "overflows" 2^BW, while at the
2244 /// same time "allowing" subtraction. In unsigned modulo arithmetic a
2245 /// subtraction (treated as addition of negated numbers) would always
2246 /// count as an overflow, but here we want to allow values to decrease
2247 /// and increase as long as they are within the same interval.
2248 /// Specifically, adding of two negative numbers should not cause an
2249 /// overflow (as long as the magnitude does not exceed the bit width).
2250 /// On the other hand, given a positive number, adding a negative
2251 /// number to it can give a negative result, which would cause the
2252 /// value to go from [-2^BW, 0) to [0, 2^BW). In that sense, zero is
2253 /// treated as a special case of an overflow.
2255 /// This function returns None if after finding k that minimizes the
2256 /// positive solution to q(n) = kR, both solutions are contained between
2257 /// two consecutive integers.
2259 /// There are cases where q(n) > T, and q(n+1) < T (assuming evaluation
2260 /// in arithmetic modulo 2^BW, and treating the values as signed) by the
2261 /// virtue of *signed* overflow. This function will *not* find such an n,
2262 /// however it may find a value of n satisfying the inequalities due to
2263 /// an *unsigned* overflow (if the values are treated as unsigned).
2264 /// To find a solution for a signed overflow, treat it as a problem of
2265 /// finding an unsigned overflow with a range with of BW-1.
2267 /// The returned value may have a different bit width from the input
2269 Optional<APInt> SolveQuadraticEquationWrap(APInt A, APInt B, APInt C,
2270 unsigned RangeWidth);
2272 /// Compare two values, and if they are different, return the position of the
2273 /// most significant bit that is different in the values.
2274 Optional<unsigned> GetMostSignificantDifferentBit(const APInt &A,
2277 } // End of APIntOps namespace
2279 // See friend declaration above. This additional declaration is required in
2280 // order to compile LLVM with IBM xlC compiler.
2281 hash_code hash_value(const APInt &Arg);
2283 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
2284 /// with the integer held in IntVal.
2285 void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst, unsigned StoreBytes);
2287 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
2288 /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
2289 void LoadIntFromMemory(APInt &IntVal, const uint8_t *Src, unsigned LoadBytes);