1 //===-- llvm/ADT/APInt.h - For Arbitrary Precision Integer -----*- C++ -*--===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief This file implements a class to represent arbitrary precision
12 /// integral constant values and operations on them.
14 //===----------------------------------------------------------------------===//
16 #ifndef LLVM_ADT_APINT_H
17 #define LLVM_ADT_APINT_H
19 #include "llvm/Support/Compiler.h"
20 #include "llvm/Support/MathExtras.h"
27 class FoldingSetNodeID;
32 template <typename T> class SmallVectorImpl;
33 template <typename T> class ArrayRef;
37 inline APInt operator-(APInt);
39 //===----------------------------------------------------------------------===//
41 //===----------------------------------------------------------------------===//
43 /// \brief 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
81 static const WordType WORD_MAX = ~WordType(0);
84 /// This union is used to store the integer value. When the
85 /// integer bit-width <= 64, it uses VAL, otherwise it uses pVal.
87 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
88 uint64_t *pVal; ///< Used to store the >64 bits integer value.
91 unsigned BitWidth; ///< The number of bits in this APInt.
93 friend struct DenseMapAPIntKeyInfo;
97 /// \brief Fast internal constructor
99 /// This constructor is used only internally for speed of construction of
100 /// temporaries. It is unsafe for general use so it is not public.
101 APInt(uint64_t *val, unsigned bits) : BitWidth(bits) {
105 /// \brief Determine if this APInt just has one word to store value.
107 /// \returns true if the number of bits <= 64, false otherwise.
108 bool isSingleWord() const { return BitWidth <= APINT_BITS_PER_WORD; }
110 /// \brief Determine which word a bit is in.
112 /// \returns the word position for the specified bit position.
113 static unsigned whichWord(unsigned bitPosition) {
114 return bitPosition / APINT_BITS_PER_WORD;
117 /// \brief Determine which bit in a word a bit is in.
119 /// \returns the bit position in a word for the specified bit position
121 static unsigned whichBit(unsigned bitPosition) {
122 return bitPosition % APINT_BITS_PER_WORD;
125 /// \brief Get a single bit mask.
127 /// \returns a uint64_t with only bit at "whichBit(bitPosition)" set
128 /// This method generates and returns a uint64_t (word) mask for a single
129 /// bit at a specific bit position. This is used to mask the bit in the
130 /// corresponding word.
131 static uint64_t maskBit(unsigned bitPosition) {
132 return 1ULL << whichBit(bitPosition);
135 /// \brief Clear unused high order bits
137 /// This method is used internally to clear the top "N" bits in the high order
138 /// word that are not used by the APInt. This is needed after the most
139 /// significant word is assigned a value to ensure that those bits are
141 APInt &clearUnusedBits() {
142 // Compute how many bits are used in the final word
143 unsigned WordBits = ((BitWidth-1) % APINT_BITS_PER_WORD) + 1;
145 // Mask out the high bits.
146 uint64_t mask = WORD_MAX >> (APINT_BITS_PER_WORD - WordBits);
150 U.pVal[getNumWords() - 1] &= mask;
154 /// \brief Get the word corresponding to a bit position
155 /// \returns the corresponding word for the specified bit position.
156 uint64_t getWord(unsigned bitPosition) const {
157 return isSingleWord() ? U.VAL : U.pVal[whichWord(bitPosition)];
160 /// Utility method to change the bit width of this APInt to new bit width,
161 /// allocating and/or deallocating as necessary. There is no guarantee on the
162 /// value of any bits upon return. Caller should populate the bits after.
163 void reallocate(unsigned NewBitWidth);
165 /// \brief Convert a char array into an APInt
167 /// \param radix 2, 8, 10, 16, or 36
168 /// Converts a string into a number. The string must be non-empty
169 /// and well-formed as a number of the given base. The bit-width
170 /// must be sufficient to hold the result.
172 /// This is used by the constructors that take string arguments.
174 /// StringRef::getAsInteger is superficially similar but (1) does
175 /// not assume that the string is well-formed and (2) grows the
176 /// result to hold the input.
177 void fromString(unsigned numBits, StringRef str, uint8_t radix);
179 /// \brief An internal division function for dividing APInts.
181 /// This is used by the toString method to divide by the radix. It simply
182 /// provides a more convenient form of divide for internal use since KnuthDiv
183 /// has specific constraints on its inputs. If those constraints are not met
184 /// then it provides a simpler form of divide.
185 static void divide(const WordType *LHS, unsigned lhsWords,
186 const WordType *RHS, unsigned rhsWords, WordType *Quotient,
187 WordType *Remainder);
189 /// out-of-line slow case for inline constructor
190 void initSlowCase(uint64_t val, bool isSigned);
192 /// shared code between two array constructors
193 void initFromArray(ArrayRef<uint64_t> array);
195 /// out-of-line slow case for inline copy constructor
196 void initSlowCase(const APInt &that);
198 /// out-of-line slow case for shl
199 void shlSlowCase(unsigned ShiftAmt);
201 /// out-of-line slow case for lshr.
202 void lshrSlowCase(unsigned ShiftAmt);
204 /// out-of-line slow case for ashr.
205 void ashrSlowCase(unsigned ShiftAmt);
207 /// out-of-line slow case for operator=
208 void AssignSlowCase(const APInt &RHS);
210 /// out-of-line slow case for operator==
211 bool EqualSlowCase(const APInt &RHS) const LLVM_READONLY;
213 /// out-of-line slow case for countLeadingZeros
214 unsigned countLeadingZerosSlowCase() const LLVM_READONLY;
216 /// out-of-line slow case for countTrailingOnes
217 unsigned countTrailingOnesSlowCase() const LLVM_READONLY;
219 /// out-of-line slow case for countPopulation
220 unsigned countPopulationSlowCase() const LLVM_READONLY;
222 /// out-of-line slow case for intersects.
223 bool intersectsSlowCase(const APInt &RHS) const LLVM_READONLY;
225 /// out-of-line slow case for isSubsetOf.
226 bool isSubsetOfSlowCase(const APInt &RHS) const LLVM_READONLY;
228 /// out-of-line slow case for setBits.
229 void setBitsSlowCase(unsigned loBit, unsigned hiBit);
231 /// out-of-line slow case for flipAllBits.
232 void flipAllBitsSlowCase();
234 /// out-of-line slow case for operator&=.
235 void AndAssignSlowCase(const APInt& RHS);
237 /// out-of-line slow case for operator|=.
238 void OrAssignSlowCase(const APInt& RHS);
240 /// out-of-line slow case for operator^=.
241 void XorAssignSlowCase(const APInt& RHS);
243 /// Unsigned comparison. Returns -1, 0, or 1 if this APInt is less than, equal
244 /// to, or greater than RHS.
245 int compare(const APInt &RHS) const LLVM_READONLY;
247 /// Signed comparison. Returns -1, 0, or 1 if this APInt is less than, equal
248 /// to, or greater than RHS.
249 int compareSigned(const APInt &RHS) const LLVM_READONLY;
252 /// \name Constructors
255 /// \brief Create a new APInt of numBits width, initialized as val.
257 /// If isSigned is true then val is treated as if it were a signed value
258 /// (i.e. as an int64_t) and the appropriate sign extension to the bit width
259 /// will be done. Otherwise, no sign extension occurs (high order bits beyond
260 /// the range of val are zero filled).
262 /// \param numBits the bit width of the constructed APInt
263 /// \param val the initial value of the APInt
264 /// \param isSigned how to treat signedness of val
265 APInt(unsigned numBits, uint64_t val, bool isSigned = false)
266 : BitWidth(numBits) {
267 assert(BitWidth && "bitwidth too small");
268 if (isSingleWord()) {
272 initSlowCase(val, isSigned);
276 /// \brief Construct an APInt of numBits width, initialized as bigVal[].
278 /// Note that bigVal.size() can be smaller or larger than the corresponding
279 /// bit width but any extraneous bits will be dropped.
281 /// \param numBits the bit width of the constructed APInt
282 /// \param bigVal a sequence of words to form the initial value of the APInt
283 APInt(unsigned numBits, ArrayRef<uint64_t> bigVal);
285 /// Equivalent to APInt(numBits, ArrayRef<uint64_t>(bigVal, numWords)), but
286 /// deprecated because this constructor is prone to ambiguity with the
287 /// APInt(unsigned, uint64_t, bool) constructor.
289 /// If this overload is ever deleted, care should be taken to prevent calls
290 /// from being incorrectly captured by the APInt(unsigned, uint64_t, bool)
292 APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[]);
294 /// \brief Construct an APInt from a string representation.
296 /// This constructor interprets the string \p str in the given radix. The
297 /// interpretation stops when the first character that is not suitable for the
298 /// radix is encountered, or the end of the string. Acceptable radix values
299 /// are 2, 8, 10, 16, and 36. It is an error for the value implied by the
300 /// string to require more bits than numBits.
302 /// \param numBits the bit width of the constructed APInt
303 /// \param str the string to be interpreted
304 /// \param radix the radix to use for the conversion
305 APInt(unsigned numBits, StringRef str, uint8_t radix);
307 /// Simply makes *this a copy of that.
308 /// @brief Copy Constructor.
309 APInt(const APInt &that) : BitWidth(that.BitWidth) {
316 /// \brief Move Constructor.
317 APInt(APInt &&that) : BitWidth(that.BitWidth) {
318 memcpy(&U, &that.U, sizeof(U));
322 /// \brief Destructor.
328 /// \brief Default constructor that creates an uninteresting APInt
329 /// representing a 1-bit zero value.
331 /// This is useful for object deserialization (pair this with the static
333 explicit APInt() : BitWidth(1) { U.VAL = 0; }
335 /// \brief Returns whether this instance allocated memory.
336 bool needsCleanup() const { return !isSingleWord(); }
338 /// Used to insert APInt objects, or objects that contain APInt objects, into
340 void Profile(FoldingSetNodeID &id) const;
343 /// \name Value Tests
346 /// \brief Determine sign of this APInt.
348 /// This tests the high bit of this APInt to determine if it is set.
350 /// \returns true if this APInt is negative, false otherwise
351 bool isNegative() const { return (*this)[BitWidth - 1]; }
353 /// \brief Determine if this APInt Value is non-negative (>= 0)
355 /// This tests the high bit of the APInt to determine if it is unset.
356 bool isNonNegative() const { return !isNegative(); }
358 /// \brief Determine if sign bit of this APInt is set.
360 /// This tests the high bit of this APInt to determine if it is set.
362 /// \returns true if this APInt has its sign bit set, false otherwise.
363 bool isSignBitSet() const { return (*this)[BitWidth-1]; }
365 /// \brief Determine if sign bit of this APInt is clear.
367 /// This tests the high bit of this APInt to determine if it is clear.
369 /// \returns true if this APInt has its sign bit clear, false otherwise.
370 bool isSignBitClear() const { return !isSignBitSet(); }
372 /// \brief Determine if this APInt Value is positive.
374 /// This tests if the value of this APInt is positive (> 0). Note
375 /// that 0 is not a positive value.
377 /// \returns true if this APInt is positive.
378 bool isStrictlyPositive() const { return isNonNegative() && !isNullValue(); }
380 /// \brief Determine if all bits are set
382 /// This checks to see if the value has all bits of the APInt are set or not.
383 bool isAllOnesValue() const {
385 return U.VAL == WORD_MAX >> (APINT_BITS_PER_WORD - BitWidth);
386 return countPopulationSlowCase() == BitWidth;
389 /// \brief Determine if all bits are clear
391 /// This checks to see if the value has all bits of the APInt are clear or
393 bool isNullValue() const { return !*this; }
395 /// \brief Determine if this is a value of 1.
397 /// This checks to see if the value of this APInt is one.
398 bool isOneValue() const { return getActiveBits() == 1; }
400 /// \brief Determine if this is the largest unsigned value.
402 /// This checks to see if the value of this APInt is the maximum unsigned
403 /// value for the APInt's bit width.
404 bool isMaxValue() const { return isAllOnesValue(); }
406 /// \brief Determine if this is the largest signed value.
408 /// This checks to see if the value of this APInt is the maximum signed
409 /// value for the APInt's bit width.
410 bool isMaxSignedValue() const {
411 return !isNegative() && countPopulation() == BitWidth - 1;
414 /// \brief Determine if this is the smallest unsigned value.
416 /// This checks to see if the value of this APInt is the minimum unsigned
417 /// value for the APInt's bit width.
418 bool isMinValue() const { return isNullValue(); }
420 /// \brief Determine if this is the smallest signed value.
422 /// This checks to see if the value of this APInt is the minimum signed
423 /// value for the APInt's bit width.
424 bool isMinSignedValue() const {
425 return isNegative() && isPowerOf2();
428 /// \brief Check if this APInt has an N-bits unsigned integer value.
429 bool isIntN(unsigned N) const {
430 assert(N && "N == 0 ???");
431 return getActiveBits() <= N;
434 /// \brief Check if this APInt has an N-bits signed integer value.
435 bool isSignedIntN(unsigned N) const {
436 assert(N && "N == 0 ???");
437 return getMinSignedBits() <= N;
440 /// \brief Check if this APInt's value is a power of two greater than zero.
442 /// \returns true if the argument APInt value is a power of two > 0.
443 bool isPowerOf2() const {
445 return isPowerOf2_64(U.VAL);
446 return countPopulationSlowCase() == 1;
449 /// \brief Check if the APInt's value is returned by getSignMask.
451 /// \returns true if this is the value returned by getSignMask.
452 bool isSignMask() const { return isMinSignedValue(); }
454 /// \brief Convert APInt to a boolean value.
456 /// This converts the APInt to a boolean value as a test against zero.
457 bool getBoolValue() const { return !!*this; }
459 /// If this value is smaller than the specified limit, return it, otherwise
460 /// return the limit value. This causes the value to saturate to the limit.
461 uint64_t getLimitedValue(uint64_t Limit = UINT64_MAX) const {
462 return ugt(Limit) ? Limit : getZExtValue();
465 /// \brief Check if the APInt consists of a repeated bit pattern.
467 /// e.g. 0x01010101 satisfies isSplat(8).
468 /// \param SplatSizeInBits The size of the pattern in bits. Must divide bit
469 /// width without remainder.
470 bool isSplat(unsigned SplatSizeInBits) const;
472 /// \returns true if this APInt value is a sequence of \param numBits ones
473 /// starting at the least significant bit with the remainder zero.
474 bool isMask(unsigned numBits) const {
475 assert(numBits != 0 && "numBits must be non-zero");
476 assert(numBits <= BitWidth && "numBits out of range");
478 return U.VAL == (WORD_MAX >> (APINT_BITS_PER_WORD - numBits));
479 unsigned Ones = countTrailingOnesSlowCase();
480 return (numBits == Ones) &&
481 ((Ones + countLeadingZerosSlowCase()) == BitWidth);
484 /// \returns true if this APInt is a non-empty sequence of ones starting at
485 /// the least significant bit with the remainder zero.
486 /// Ex. isMask(0x0000FFFFU) == true.
487 bool isMask() const {
489 return isMask_64(U.VAL);
490 unsigned Ones = countTrailingOnesSlowCase();
491 return (Ones > 0) && ((Ones + countLeadingZerosSlowCase()) == BitWidth);
494 /// \brief Return true if this APInt value contains a sequence of ones with
495 /// the remainder zero.
496 bool isShiftedMask() const {
498 return isShiftedMask_64(U.VAL);
499 unsigned Ones = countPopulationSlowCase();
500 unsigned LeadZ = countLeadingZerosSlowCase();
501 return (Ones + LeadZ + countTrailingZeros()) == BitWidth;
505 /// \name Value Generators
508 /// \brief Gets maximum unsigned value of APInt for specific bit width.
509 static APInt getMaxValue(unsigned numBits) {
510 return getAllOnesValue(numBits);
513 /// \brief Gets maximum signed value of APInt for a specific bit width.
514 static APInt getSignedMaxValue(unsigned numBits) {
515 APInt API = getAllOnesValue(numBits);
516 API.clearBit(numBits - 1);
520 /// \brief Gets minimum unsigned value of APInt for a specific bit width.
521 static APInt getMinValue(unsigned numBits) { return APInt(numBits, 0); }
523 /// \brief Gets minimum signed value of APInt for a specific bit width.
524 static APInt getSignedMinValue(unsigned numBits) {
525 APInt API(numBits, 0);
526 API.setBit(numBits - 1);
530 /// \brief Get the SignMask for a specific bit width.
532 /// This is just a wrapper function of getSignedMinValue(), and it helps code
533 /// readability when we want to get a SignMask.
534 static APInt getSignMask(unsigned BitWidth) {
535 return getSignedMinValue(BitWidth);
538 /// \brief Get the all-ones value.
540 /// \returns the all-ones value for an APInt of the specified bit-width.
541 static APInt getAllOnesValue(unsigned numBits) {
542 return APInt(numBits, WORD_MAX, true);
545 /// \brief Get the '0' value.
547 /// \returns the '0' value for an APInt of the specified bit-width.
548 static APInt getNullValue(unsigned numBits) { return APInt(numBits, 0); }
550 /// \brief Compute an APInt containing numBits highbits from this APInt.
552 /// Get an APInt with the same BitWidth as this APInt, just zero mask
553 /// the low bits and right shift to the least significant bit.
555 /// \returns the high "numBits" bits of this APInt.
556 APInt getHiBits(unsigned numBits) const;
558 /// \brief Compute an APInt containing numBits lowbits from this APInt.
560 /// Get an APInt with the same BitWidth as this APInt, just zero mask
563 /// \returns the low "numBits" bits of this APInt.
564 APInt getLoBits(unsigned numBits) const;
566 /// \brief Return an APInt with exactly one bit set in the result.
567 static APInt getOneBitSet(unsigned numBits, unsigned BitNo) {
568 APInt Res(numBits, 0);
573 /// \brief Get a value with a block of bits set.
575 /// Constructs an APInt value that has a contiguous range of bits set. The
576 /// bits from loBit (inclusive) to hiBit (exclusive) will be set. All other
577 /// bits will be zero. For example, with parameters(32, 0, 16) you would get
578 /// 0x0000FFFF. If hiBit is less than loBit then the set bits "wrap". For
579 /// example, with parameters (32, 28, 4), you would get 0xF000000F.
581 /// \param numBits the intended bit width of the result
582 /// \param loBit the index of the lowest bit set.
583 /// \param hiBit the index of the highest bit set.
585 /// \returns An APInt value with the requested bits set.
586 static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit) {
587 APInt Res(numBits, 0);
588 Res.setBits(loBit, hiBit);
592 /// \brief Get a value with upper bits starting at loBit set.
594 /// Constructs an APInt value that has a contiguous range of bits set. The
595 /// bits from loBit (inclusive) to numBits (exclusive) will be set. All other
596 /// bits will be zero. For example, with parameters(32, 12) you would get
599 /// \param numBits the intended bit width of the result
600 /// \param loBit the index of the lowest bit to set.
602 /// \returns An APInt value with the requested bits set.
603 static APInt getBitsSetFrom(unsigned numBits, unsigned loBit) {
604 APInt Res(numBits, 0);
605 Res.setBitsFrom(loBit);
609 /// \brief Get a value with high bits set
611 /// Constructs an APInt value that has the top hiBitsSet bits set.
613 /// \param numBits the bitwidth of the result
614 /// \param hiBitsSet the number of high-order bits set in the result.
615 static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet) {
616 APInt Res(numBits, 0);
617 Res.setHighBits(hiBitsSet);
621 /// \brief Get a value with low bits set
623 /// Constructs an APInt value that has the bottom loBitsSet bits set.
625 /// \param numBits the bitwidth of the result
626 /// \param loBitsSet the number of low-order bits set in the result.
627 static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet) {
628 APInt Res(numBits, 0);
629 Res.setLowBits(loBitsSet);
633 /// \brief Return a value containing V broadcasted over NewLen bits.
634 static APInt getSplat(unsigned NewLen, const APInt &V);
636 /// \brief Determine if two APInts have the same value, after zero-extending
637 /// one of them (if needed!) to ensure that the bit-widths match.
638 static bool isSameValue(const APInt &I1, const APInt &I2) {
639 if (I1.getBitWidth() == I2.getBitWidth())
642 if (I1.getBitWidth() > I2.getBitWidth())
643 return I1 == I2.zext(I1.getBitWidth());
645 return I1.zext(I2.getBitWidth()) == I2;
648 /// \brief Overload to compute a hash_code for an APInt value.
649 friend hash_code hash_value(const APInt &Arg);
651 /// This function returns a pointer to the internal storage of the APInt.
652 /// This is useful for writing out the APInt in binary form without any
654 const uint64_t *getRawData() const {
661 /// \name Unary Operators
664 /// \brief Postfix increment operator.
666 /// Increments *this by 1.
668 /// \returns a new APInt value representing the original value of *this.
669 const APInt operator++(int) {
675 /// \brief Prefix increment operator.
677 /// \returns *this incremented by one
680 /// \brief Postfix decrement operator.
682 /// Decrements *this by 1.
684 /// \returns a new APInt value representing the original value of *this.
685 const APInt operator--(int) {
691 /// \brief Prefix decrement operator.
693 /// \returns *this decremented by one.
696 /// \brief Logical negation operator.
698 /// Performs logical negation operation on this APInt.
700 /// \returns true if *this is zero, false otherwise.
701 bool operator!() const {
704 return countLeadingZerosSlowCase() == BitWidth;
708 /// \name Assignment Operators
711 /// \brief Copy assignment operator.
713 /// \returns *this after assignment of RHS.
714 APInt &operator=(const APInt &RHS) {
715 // If the bitwidths are the same, we can avoid mucking with memory
716 if (isSingleWord() && RHS.isSingleWord()) {
718 BitWidth = RHS.BitWidth;
719 return clearUnusedBits();
726 /// @brief Move assignment operator.
727 APInt &operator=(APInt &&that) {
728 assert(this != &that && "Self-move not supported");
732 // Use memcpy so that type based alias analysis sees both VAL and pVal
734 memcpy(&U, &that.U, sizeof(U));
736 BitWidth = that.BitWidth;
742 /// \brief Assignment operator.
744 /// The RHS value is assigned to *this. If the significant bits in RHS exceed
745 /// the bit width, the excess bits are truncated. If the bit width is larger
746 /// than 64, the value is zero filled in the unspecified high order bits.
748 /// \returns *this after assignment of RHS value.
749 APInt &operator=(uint64_t RHS) {
750 if (isSingleWord()) {
755 memset(U.pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
760 /// \brief Bitwise AND assignment operator.
762 /// Performs a bitwise AND operation on this APInt and RHS. The result is
763 /// assigned to *this.
765 /// \returns *this after ANDing with RHS.
766 APInt &operator&=(const APInt &RHS) {
767 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
771 AndAssignSlowCase(RHS);
775 /// \brief Bitwise AND assignment operator.
777 /// Performs a bitwise AND operation on this APInt and RHS. RHS is
778 /// logically zero-extended or truncated to match the bit-width of
780 APInt &operator&=(uint64_t RHS) {
781 if (isSingleWord()) {
786 memset(U.pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
790 /// \brief Bitwise OR assignment operator.
792 /// Performs a bitwise OR operation on this APInt and RHS. The result is
795 /// \returns *this after ORing with RHS.
796 APInt &operator|=(const APInt &RHS) {
797 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
801 OrAssignSlowCase(RHS);
805 /// \brief Bitwise OR assignment operator.
807 /// Performs a bitwise OR operation on this APInt and RHS. RHS is
808 /// logically zero-extended or truncated to match the bit-width of
810 APInt &operator|=(uint64_t RHS) {
811 if (isSingleWord()) {
820 /// \brief Bitwise XOR assignment operator.
822 /// Performs a bitwise XOR operation on this APInt and RHS. The result is
823 /// assigned to *this.
825 /// \returns *this after XORing with RHS.
826 APInt &operator^=(const APInt &RHS) {
827 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
831 XorAssignSlowCase(RHS);
835 /// \brief Bitwise XOR assignment operator.
837 /// Performs a bitwise XOR operation on this APInt and RHS. RHS is
838 /// logically zero-extended or truncated to match the bit-width of
840 APInt &operator^=(uint64_t RHS) {
841 if (isSingleWord()) {
850 /// \brief Multiplication assignment operator.
852 /// Multiplies this APInt by RHS and assigns the result to *this.
855 APInt &operator*=(const APInt &RHS);
856 APInt &operator*=(uint64_t RHS);
858 /// \brief Addition assignment operator.
860 /// Adds RHS to *this and assigns the result to *this.
863 APInt &operator+=(const APInt &RHS);
864 APInt &operator+=(uint64_t RHS);
866 /// \brief Subtraction assignment operator.
868 /// Subtracts RHS from *this and assigns the result to *this.
871 APInt &operator-=(const APInt &RHS);
872 APInt &operator-=(uint64_t RHS);
874 /// \brief Left-shift assignment function.
876 /// Shifts *this left by shiftAmt and assigns the result to *this.
878 /// \returns *this after shifting left by ShiftAmt
879 APInt &operator<<=(unsigned ShiftAmt) {
880 assert(ShiftAmt <= BitWidth && "Invalid shift amount");
881 if (isSingleWord()) {
882 if (ShiftAmt == BitWidth)
886 return clearUnusedBits();
888 shlSlowCase(ShiftAmt);
892 /// \brief Left-shift assignment function.
894 /// Shifts *this left by shiftAmt and assigns the result to *this.
896 /// \returns *this after shifting left by ShiftAmt
897 APInt &operator<<=(const APInt &ShiftAmt);
900 /// \name Binary Operators
903 /// \brief Multiplication operator.
905 /// Multiplies this APInt by RHS and returns the result.
906 APInt operator*(const APInt &RHS) const;
908 /// \brief Left logical shift operator.
910 /// Shifts this APInt left by \p Bits and returns the result.
911 APInt operator<<(unsigned Bits) const { return shl(Bits); }
913 /// \brief Left logical shift operator.
915 /// Shifts this APInt left by \p Bits and returns the result.
916 APInt operator<<(const APInt &Bits) const { return shl(Bits); }
918 /// \brief Arithmetic right-shift function.
920 /// Arithmetic right-shift this APInt by shiftAmt.
921 APInt ashr(unsigned ShiftAmt) const {
923 R.ashrInPlace(ShiftAmt);
927 /// Arithmetic right-shift this APInt by ShiftAmt in place.
928 void ashrInPlace(unsigned ShiftAmt) {
929 assert(ShiftAmt <= BitWidth && "Invalid shift amount");
930 if (isSingleWord()) {
931 int64_t SExtVAL = SignExtend64(U.VAL, BitWidth);
932 if (ShiftAmt == BitWidth)
933 U.VAL = SExtVAL >> (APINT_BITS_PER_WORD - 1); // Fill with sign bit.
935 U.VAL = SExtVAL >> ShiftAmt;
939 ashrSlowCase(ShiftAmt);
942 /// \brief Logical right-shift function.
944 /// Logical right-shift this APInt by shiftAmt.
945 APInt lshr(unsigned shiftAmt) const {
947 R.lshrInPlace(shiftAmt);
951 /// Logical right-shift this APInt by ShiftAmt in place.
952 void lshrInPlace(unsigned ShiftAmt) {
953 assert(ShiftAmt <= BitWidth && "Invalid shift amount");
954 if (isSingleWord()) {
955 if (ShiftAmt == BitWidth)
961 lshrSlowCase(ShiftAmt);
964 /// \brief Left-shift function.
966 /// Left-shift this APInt by shiftAmt.
967 APInt shl(unsigned shiftAmt) const {
973 /// \brief Rotate left by rotateAmt.
974 APInt rotl(unsigned rotateAmt) const;
976 /// \brief Rotate right by rotateAmt.
977 APInt rotr(unsigned rotateAmt) const;
979 /// \brief Arithmetic right-shift function.
981 /// Arithmetic right-shift this APInt by shiftAmt.
982 APInt ashr(const APInt &ShiftAmt) const {
984 R.ashrInPlace(ShiftAmt);
988 /// Arithmetic right-shift this APInt by shiftAmt in place.
989 void ashrInPlace(const APInt &shiftAmt);
991 /// \brief Logical right-shift function.
993 /// Logical right-shift this APInt by shiftAmt.
994 APInt lshr(const APInt &ShiftAmt) const {
996 R.lshrInPlace(ShiftAmt);
1000 /// Logical right-shift this APInt by ShiftAmt in place.
1001 void lshrInPlace(const APInt &ShiftAmt);
1003 /// \brief Left-shift function.
1005 /// Left-shift this APInt by shiftAmt.
1006 APInt shl(const APInt &ShiftAmt) const {
1012 /// \brief Rotate left by rotateAmt.
1013 APInt rotl(const APInt &rotateAmt) const;
1015 /// \brief Rotate right by rotateAmt.
1016 APInt rotr(const APInt &rotateAmt) const;
1018 /// \brief Unsigned division operation.
1020 /// Perform an unsigned divide operation on this APInt by RHS. Both this and
1021 /// RHS are treated as unsigned quantities for purposes of this division.
1023 /// \returns a new APInt value containing the division result
1024 APInt udiv(const APInt &RHS) const;
1025 APInt udiv(uint64_t RHS) const;
1027 /// \brief Signed division function for APInt.
1029 /// Signed divide this APInt by APInt RHS.
1030 APInt sdiv(const APInt &RHS) const;
1031 APInt sdiv(int64_t RHS) const;
1033 /// \brief Unsigned remainder operation.
1035 /// Perform an unsigned remainder operation on this APInt with RHS being the
1036 /// divisor. Both this and RHS are treated as unsigned quantities for purposes
1037 /// of this operation. Note that this is a true remainder operation and not a
1038 /// modulo operation because the sign follows the sign of the dividend which
1041 /// \returns a new APInt value containing the remainder result
1042 APInt urem(const APInt &RHS) const;
1043 uint64_t urem(uint64_t RHS) const;
1045 /// \brief Function for signed remainder operation.
1047 /// Signed remainder operation on APInt.
1048 APInt srem(const APInt &RHS) const;
1049 int64_t srem(int64_t RHS) const;
1051 /// \brief Dual division/remainder interface.
1053 /// Sometimes it is convenient to divide two APInt values and obtain both the
1054 /// quotient and remainder. This function does both operations in the same
1055 /// computation making it a little more efficient. The pair of input arguments
1056 /// may overlap with the pair of output arguments. It is safe to call
1057 /// udivrem(X, Y, X, Y), for example.
1058 static void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient,
1060 static void udivrem(const APInt &LHS, uint64_t RHS, APInt &Quotient,
1061 uint64_t &Remainder);
1063 static void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient,
1065 static void sdivrem(const APInt &LHS, int64_t RHS, APInt &Quotient,
1066 int64_t &Remainder);
1068 // Operations that return overflow indicators.
1069 APInt sadd_ov(const APInt &RHS, bool &Overflow) const;
1070 APInt uadd_ov(const APInt &RHS, bool &Overflow) const;
1071 APInt ssub_ov(const APInt &RHS, bool &Overflow) const;
1072 APInt usub_ov(const APInt &RHS, bool &Overflow) const;
1073 APInt sdiv_ov(const APInt &RHS, bool &Overflow) const;
1074 APInt smul_ov(const APInt &RHS, bool &Overflow) const;
1075 APInt umul_ov(const APInt &RHS, bool &Overflow) const;
1076 APInt sshl_ov(const APInt &Amt, bool &Overflow) const;
1077 APInt ushl_ov(const APInt &Amt, bool &Overflow) const;
1079 /// \brief Array-indexing support.
1081 /// \returns the bit value at bitPosition
1082 bool operator[](unsigned bitPosition) const {
1083 assert(bitPosition < getBitWidth() && "Bit position out of bounds!");
1084 return (maskBit(bitPosition) & getWord(bitPosition)) != 0;
1088 /// \name Comparison Operators
1091 /// \brief Equality operator.
1093 /// Compares this APInt with RHS for the validity of the equality
1095 bool operator==(const APInt &RHS) const {
1096 assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths");
1098 return U.VAL == RHS.U.VAL;
1099 return EqualSlowCase(RHS);
1102 /// \brief Equality operator.
1104 /// Compares this APInt with a uint64_t for the validity of the equality
1107 /// \returns true if *this == Val
1108 bool operator==(uint64_t Val) const {
1109 return (isSingleWord() || getActiveBits() <= 64) && getZExtValue() == Val;
1112 /// \brief Equality comparison.
1114 /// Compares this APInt with RHS for the validity of the equality
1117 /// \returns true if *this == Val
1118 bool eq(const APInt &RHS) const { return (*this) == RHS; }
1120 /// \brief Inequality operator.
1122 /// Compares this APInt with RHS for the validity of the inequality
1125 /// \returns true if *this != Val
1126 bool operator!=(const APInt &RHS) const { return !((*this) == RHS); }
1128 /// \brief Inequality operator.
1130 /// Compares this APInt with a uint64_t for the validity of the inequality
1133 /// \returns true if *this != Val
1134 bool operator!=(uint64_t Val) const { return !((*this) == Val); }
1136 /// \brief Inequality comparison
1138 /// Compares this APInt with RHS for the validity of the inequality
1141 /// \returns true if *this != Val
1142 bool ne(const APInt &RHS) const { return !((*this) == RHS); }
1144 /// \brief Unsigned less than comparison
1146 /// Regards both *this and RHS as unsigned quantities and compares them for
1147 /// the validity of the less-than relationship.
1149 /// \returns true if *this < RHS when both are considered unsigned.
1150 bool ult(const APInt &RHS) const { return compare(RHS) < 0; }
1152 /// \brief Unsigned less than comparison
1154 /// Regards both *this as an unsigned quantity and compares it with RHS for
1155 /// the validity of the less-than relationship.
1157 /// \returns true if *this < RHS when considered unsigned.
1158 bool ult(uint64_t RHS) const {
1159 // Only need to check active bits if not a single word.
1160 return (isSingleWord() || getActiveBits() <= 64) && getZExtValue() < RHS;
1163 /// \brief Signed less than comparison
1165 /// Regards both *this and RHS as signed quantities and compares them for
1166 /// validity of the less-than relationship.
1168 /// \returns true if *this < RHS when both are considered signed.
1169 bool slt(const APInt &RHS) const { return compareSigned(RHS) < 0; }
1171 /// \brief Signed less than comparison
1173 /// Regards both *this as a signed quantity and compares it with RHS for
1174 /// the validity of the less-than relationship.
1176 /// \returns true if *this < RHS when considered signed.
1177 bool slt(int64_t RHS) const {
1178 return (!isSingleWord() && getMinSignedBits() > 64) ? isNegative()
1179 : getSExtValue() < RHS;
1182 /// \brief Unsigned less or equal comparison
1184 /// Regards both *this and RHS as unsigned quantities and compares them for
1185 /// validity of the less-or-equal relationship.
1187 /// \returns true if *this <= RHS when both are considered unsigned.
1188 bool ule(const APInt &RHS) const { return compare(RHS) <= 0; }
1190 /// \brief Unsigned less or equal comparison
1192 /// Regards both *this as an unsigned quantity and compares it with RHS for
1193 /// the validity of the less-or-equal relationship.
1195 /// \returns true if *this <= RHS when considered unsigned.
1196 bool ule(uint64_t RHS) const { return !ugt(RHS); }
1198 /// \brief Signed less or equal comparison
1200 /// Regards both *this and RHS as signed quantities and compares them for
1201 /// validity of the less-or-equal relationship.
1203 /// \returns true if *this <= RHS when both are considered signed.
1204 bool sle(const APInt &RHS) const { return compareSigned(RHS) <= 0; }
1206 /// \brief Signed less or equal comparison
1208 /// Regards both *this as a signed quantity and compares it with RHS for the
1209 /// validity of the less-or-equal relationship.
1211 /// \returns true if *this <= RHS when considered signed.
1212 bool sle(uint64_t RHS) const { return !sgt(RHS); }
1214 /// \brief Unsigned greather than comparison
1216 /// Regards both *this and RHS as unsigned quantities and compares them for
1217 /// the validity of the greater-than relationship.
1219 /// \returns true if *this > RHS when both are considered unsigned.
1220 bool ugt(const APInt &RHS) const { return !ule(RHS); }
1222 /// \brief Unsigned greater than comparison
1224 /// Regards both *this as an unsigned quantity and compares it with RHS for
1225 /// the validity of the greater-than relationship.
1227 /// \returns true if *this > RHS when considered unsigned.
1228 bool ugt(uint64_t RHS) const {
1229 // Only need to check active bits if not a single word.
1230 return (!isSingleWord() && getActiveBits() > 64) || getZExtValue() > RHS;
1233 /// \brief Signed greather than comparison
1235 /// Regards both *this and RHS as signed quantities and compares them for the
1236 /// validity of the greater-than relationship.
1238 /// \returns true if *this > RHS when both are considered signed.
1239 bool sgt(const APInt &RHS) const { return !sle(RHS); }
1241 /// \brief Signed greater than comparison
1243 /// Regards both *this as a signed quantity and compares it with RHS for
1244 /// the validity of the greater-than relationship.
1246 /// \returns true if *this > RHS when considered signed.
1247 bool sgt(int64_t RHS) const {
1248 return (!isSingleWord() && getMinSignedBits() > 64) ? !isNegative()
1249 : getSExtValue() > RHS;
1252 /// \brief Unsigned greater or equal comparison
1254 /// Regards both *this and RHS as unsigned quantities and compares them for
1255 /// validity of the greater-or-equal relationship.
1257 /// \returns true if *this >= RHS when both are considered unsigned.
1258 bool uge(const APInt &RHS) const { return !ult(RHS); }
1260 /// \brief Unsigned greater or equal comparison
1262 /// Regards both *this as an unsigned quantity and compares it with RHS for
1263 /// the validity of the greater-or-equal relationship.
1265 /// \returns true if *this >= RHS when considered unsigned.
1266 bool uge(uint64_t RHS) const { return !ult(RHS); }
1268 /// \brief Signed greather or equal comparison
1270 /// Regards both *this and RHS as signed quantities and compares them for
1271 /// validity of the greater-or-equal relationship.
1273 /// \returns true if *this >= RHS when both are considered signed.
1274 bool sge(const APInt &RHS) const { return !slt(RHS); }
1276 /// \brief Signed greater or equal comparison
1278 /// Regards both *this as a signed quantity and compares it with RHS for
1279 /// the validity of the greater-or-equal relationship.
1281 /// \returns true if *this >= RHS when considered signed.
1282 bool sge(int64_t RHS) const { return !slt(RHS); }
1284 /// This operation tests if there are any pairs of corresponding bits
1285 /// between this APInt and RHS that are both set.
1286 bool intersects(const APInt &RHS) const {
1287 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1289 return (U.VAL & RHS.U.VAL) != 0;
1290 return intersectsSlowCase(RHS);
1293 /// This operation checks that all bits set in this APInt are also set in RHS.
1294 bool isSubsetOf(const APInt &RHS) const {
1295 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1297 return (U.VAL & ~RHS.U.VAL) == 0;
1298 return isSubsetOfSlowCase(RHS);
1302 /// \name Resizing Operators
1305 /// \brief Truncate to new width.
1307 /// Truncate the APInt to a specified width. It is an error to specify a width
1308 /// that is greater than or equal to the current width.
1309 APInt trunc(unsigned width) const;
1311 /// \brief Sign extend to a new width.
1313 /// This operation sign extends the APInt to a new width. If the high order
1314 /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
1315 /// It is an error to specify a width that is less than or equal to the
1317 APInt sext(unsigned width) const;
1319 /// \brief Zero extend to a new width.
1321 /// This operation zero extends the APInt to a new width. The high order bits
1322 /// are filled with 0 bits. It is an error to specify a width that is less
1323 /// than or equal to the current width.
1324 APInt zext(unsigned width) const;
1326 /// \brief Sign extend or truncate to width
1328 /// Make this APInt have the bit width given by \p width. The value is sign
1329 /// extended, truncated, or left alone to make it that width.
1330 APInt sextOrTrunc(unsigned width) const;
1332 /// \brief Zero extend or truncate to width
1334 /// Make this APInt have the bit width given by \p width. The value is zero
1335 /// extended, truncated, or left alone to make it that width.
1336 APInt zextOrTrunc(unsigned width) const;
1338 /// \brief Sign extend or truncate to width
1340 /// Make this APInt have the bit width given by \p width. The value is sign
1341 /// extended, or left alone to make it that width.
1342 APInt sextOrSelf(unsigned width) const;
1344 /// \brief Zero extend or truncate to width
1346 /// Make this APInt have the bit width given by \p width. The value is zero
1347 /// extended, or left alone to make it that width.
1348 APInt zextOrSelf(unsigned width) const;
1351 /// \name Bit Manipulation Operators
1354 /// \brief Set every bit to 1.
1359 // Set all the bits in all the words.
1360 memset(U.pVal, -1, getNumWords() * APINT_WORD_SIZE);
1361 // Clear the unused ones
1365 /// \brief Set a given bit to 1.
1367 /// Set the given bit to 1 whose position is given as "bitPosition".
1368 void setBit(unsigned BitPosition) {
1369 assert(BitPosition <= BitWidth && "BitPosition out of range");
1370 WordType Mask = maskBit(BitPosition);
1374 U.pVal[whichWord(BitPosition)] |= Mask;
1377 /// Set the sign bit to 1.
1379 setBit(BitWidth - 1);
1382 /// Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
1383 void setBits(unsigned loBit, unsigned hiBit) {
1384 assert(hiBit <= BitWidth && "hiBit out of range");
1385 assert(loBit <= BitWidth && "loBit out of range");
1386 assert(loBit <= hiBit && "loBit greater than hiBit");
1389 if (loBit < APINT_BITS_PER_WORD && hiBit <= APINT_BITS_PER_WORD) {
1390 uint64_t mask = WORD_MAX >> (APINT_BITS_PER_WORD - (hiBit - loBit));
1397 setBitsSlowCase(loBit, hiBit);
1401 /// Set the top bits starting from loBit.
1402 void setBitsFrom(unsigned loBit) {
1403 return setBits(loBit, BitWidth);
1406 /// Set the bottom loBits bits.
1407 void setLowBits(unsigned loBits) {
1408 return setBits(0, loBits);
1411 /// Set the top hiBits bits.
1412 void setHighBits(unsigned hiBits) {
1413 return setBits(BitWidth - hiBits, BitWidth);
1416 /// \brief Set every bit to 0.
1417 void clearAllBits() {
1421 memset(U.pVal, 0, getNumWords() * APINT_WORD_SIZE);
1424 /// \brief Set a given bit to 0.
1426 /// Set the given bit to 0 whose position is given as "bitPosition".
1427 void clearBit(unsigned BitPosition) {
1428 assert(BitPosition <= BitWidth && "BitPosition out of range");
1429 WordType Mask = ~maskBit(BitPosition);
1433 U.pVal[whichWord(BitPosition)] &= Mask;
1436 /// Set the sign bit to 0.
1437 void clearSignBit() {
1438 clearBit(BitWidth - 1);
1441 /// \brief Toggle every bit to its opposite value.
1442 void flipAllBits() {
1443 if (isSingleWord()) {
1447 flipAllBitsSlowCase();
1451 /// \brief Toggles a given bit to its opposite value.
1453 /// Toggle a given bit to its opposite value whose position is given
1454 /// as "bitPosition".
1455 void flipBit(unsigned bitPosition);
1457 /// Negate this APInt in place.
1463 /// Insert the bits from a smaller APInt starting at bitPosition.
1464 void insertBits(const APInt &SubBits, unsigned bitPosition);
1466 /// Return an APInt with the extracted bits [bitPosition,bitPosition+numBits).
1467 APInt extractBits(unsigned numBits, unsigned bitPosition) const;
1470 /// \name Value Characterization Functions
1473 /// \brief Return the number of bits in the APInt.
1474 unsigned getBitWidth() const { return BitWidth; }
1476 /// \brief Get the number of words.
1478 /// Here one word's bitwidth equals to that of uint64_t.
1480 /// \returns the number of words to hold the integer value of this APInt.
1481 unsigned getNumWords() const { return getNumWords(BitWidth); }
1483 /// \brief Get the number of words.
1485 /// *NOTE* Here one word's bitwidth equals to that of uint64_t.
1487 /// \returns the number of words to hold the integer value with a given bit
1489 static unsigned getNumWords(unsigned BitWidth) {
1490 return ((uint64_t)BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
1493 /// \brief Compute the number of active bits in the value
1495 /// This function returns the number of active bits which is defined as the
1496 /// bit width minus the number of leading zeros. This is used in several
1497 /// computations to see how "wide" the value is.
1498 unsigned getActiveBits() const { return BitWidth - countLeadingZeros(); }
1500 /// \brief Compute the number of active words in the value of this APInt.
1502 /// This is used in conjunction with getActiveData to extract the raw value of
1504 unsigned getActiveWords() const {
1505 unsigned numActiveBits = getActiveBits();
1506 return numActiveBits ? whichWord(numActiveBits - 1) + 1 : 1;
1509 /// \brief Get the minimum bit size for this signed APInt
1511 /// Computes the minimum bit width for this APInt while considering it to be a
1512 /// signed (and probably negative) value. If the value is not negative, this
1513 /// function returns the same value as getActiveBits()+1. Otherwise, it
1514 /// returns the smallest bit width that will retain the negative value. For
1515 /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
1516 /// for -1, this function will always return 1.
1517 unsigned getMinSignedBits() const {
1519 return BitWidth - countLeadingOnes() + 1;
1520 return getActiveBits() + 1;
1523 /// \brief Get zero extended value
1525 /// This method attempts to return the value of this APInt as a zero extended
1526 /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
1527 /// uint64_t. Otherwise an assertion will result.
1528 uint64_t getZExtValue() const {
1531 assert(getActiveBits() <= 64 && "Too many bits for uint64_t");
1535 /// \brief Get sign extended value
1537 /// This method attempts to return the value of this APInt as a sign extended
1538 /// int64_t. The bit width must be <= 64 or the value must fit within an
1539 /// int64_t. Otherwise an assertion will result.
1540 int64_t getSExtValue() const {
1542 return SignExtend64(U.VAL, BitWidth);
1543 assert(getMinSignedBits() <= 64 && "Too many bits for int64_t");
1544 return int64_t(U.pVal[0]);
1547 /// \brief Get bits required for string value.
1549 /// This method determines how many bits are required to hold the APInt
1550 /// equivalent of the string given by \p str.
1551 static unsigned getBitsNeeded(StringRef str, uint8_t radix);
1553 /// \brief The APInt version of the countLeadingZeros functions in
1556 /// It counts the number of zeros from the most significant bit to the first
1559 /// \returns BitWidth if the value is zero, otherwise returns the number of
1560 /// zeros from the most significant bit to the first one bits.
1561 unsigned countLeadingZeros() const {
1562 if (isSingleWord()) {
1563 unsigned unusedBits = APINT_BITS_PER_WORD - BitWidth;
1564 return llvm::countLeadingZeros(U.VAL) - unusedBits;
1566 return countLeadingZerosSlowCase();
1569 /// \brief Count the number of leading one bits.
1571 /// This function is an APInt version of the countLeadingOnes
1572 /// functions in MathExtras.h. It counts the number of ones from the most
1573 /// significant bit to the first zero bit.
1575 /// \returns 0 if the high order bit is not set, otherwise returns the number
1576 /// of 1 bits from the most significant to the least
1577 unsigned countLeadingOnes() const LLVM_READONLY;
1579 /// Computes the number of leading bits of this APInt that are equal to its
1581 unsigned getNumSignBits() const {
1582 return isNegative() ? countLeadingOnes() : countLeadingZeros();
1585 /// \brief Count the number of trailing zero bits.
1587 /// This function is an APInt version of the countTrailingZeros
1588 /// functions in MathExtras.h. It counts the number of zeros from the least
1589 /// significant bit to the first set bit.
1591 /// \returns BitWidth if the value is zero, otherwise returns the number of
1592 /// zeros from the least significant bit to the first one bit.
1593 unsigned countTrailingZeros() const LLVM_READONLY;
1595 /// \brief Count the number of trailing one bits.
1597 /// This function is an APInt version of the countTrailingOnes
1598 /// functions in MathExtras.h. It counts the number of ones from the least
1599 /// significant bit to the first zero bit.
1601 /// \returns BitWidth if the value is all ones, otherwise returns the number
1602 /// of ones from the least significant bit to the first zero bit.
1603 unsigned countTrailingOnes() const {
1605 return llvm::countTrailingOnes(U.VAL);
1606 return countTrailingOnesSlowCase();
1609 /// \brief Count the number of bits set.
1611 /// This function is an APInt version of the countPopulation functions
1612 /// in MathExtras.h. It counts the number of 1 bits in the APInt value.
1614 /// \returns 0 if the value is zero, otherwise returns the number of set bits.
1615 unsigned countPopulation() const {
1617 return llvm::countPopulation(U.VAL);
1618 return countPopulationSlowCase();
1622 /// \name Conversion Functions
1624 void print(raw_ostream &OS, bool isSigned) const;
1626 /// Converts an APInt to a string and append it to Str. Str is commonly a
1628 void toString(SmallVectorImpl<char> &Str, unsigned Radix, bool Signed,
1629 bool formatAsCLiteral = false) const;
1631 /// Considers the APInt to be unsigned and converts it into a string in the
1632 /// radix given. The radix can be 2, 8, 10 16, or 36.
1633 void toStringUnsigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1634 toString(Str, Radix, false, false);
1637 /// Considers the APInt to be signed and converts it into a string in the
1638 /// radix given. The radix can be 2, 8, 10, 16, or 36.
1639 void toStringSigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1640 toString(Str, Radix, true, false);
1643 /// \brief Return the APInt as a std::string.
1645 /// Note that this is an inefficient method. It is better to pass in a
1646 /// SmallVector/SmallString to the methods above to avoid thrashing the heap
1648 std::string toString(unsigned Radix, bool Signed) const;
1650 /// \returns a byte-swapped representation of this APInt Value.
1651 APInt byteSwap() const;
1653 /// \returns the value with the bit representation reversed of this APInt
1655 APInt reverseBits() const;
1657 /// \brief Converts this APInt to a double value.
1658 double roundToDouble(bool isSigned) const;
1660 /// \brief Converts this unsigned APInt to a double value.
1661 double roundToDouble() const { return roundToDouble(false); }
1663 /// \brief Converts this signed APInt to a double value.
1664 double signedRoundToDouble() const { return roundToDouble(true); }
1666 /// \brief Converts APInt bits to a double
1668 /// The conversion does not do a translation from integer to double, it just
1669 /// re-interprets the bits as a double. Note that it is valid to do this on
1670 /// any bit width. Exactly 64 bits will be translated.
1671 double bitsToDouble() const {
1672 return BitsToDouble(getWord(0));
1675 /// \brief Converts APInt bits to a double
1677 /// The conversion does not do a translation from integer to float, it just
1678 /// re-interprets the bits as a float. Note that it is valid to do this on
1679 /// any bit width. Exactly 32 bits will be translated.
1680 float bitsToFloat() const {
1681 return BitsToFloat(getWord(0));
1684 /// \brief Converts a double to APInt bits.
1686 /// The conversion does not do a translation from double to integer, it just
1687 /// re-interprets the bits of the double.
1688 static APInt doubleToBits(double V) {
1689 return APInt(sizeof(double) * CHAR_BIT, DoubleToBits(V));
1692 /// \brief Converts a float to APInt bits.
1694 /// The conversion does not do a translation from float to integer, it just
1695 /// re-interprets the bits of the float.
1696 static APInt floatToBits(float V) {
1697 return APInt(sizeof(float) * CHAR_BIT, FloatToBits(V));
1701 /// \name Mathematics Operations
1704 /// \returns the floor log base 2 of this APInt.
1705 unsigned logBase2() const { return BitWidth - 1 - countLeadingZeros(); }
1707 /// \returns the ceil log base 2 of this APInt.
1708 unsigned ceilLogBase2() const {
1711 return BitWidth - temp.countLeadingZeros();
1714 /// \returns the nearest log base 2 of this APInt. Ties round up.
1716 /// NOTE: When we have a BitWidth of 1, we define:
1718 /// log2(0) = UINT32_MAX
1721 /// to get around any mathematical concerns resulting from
1722 /// referencing 2 in a space where 2 does no exist.
1723 unsigned nearestLogBase2() const {
1724 // Special case when we have a bitwidth of 1. If VAL is 1, then we
1725 // get 0. If VAL is 0, we get WORD_MAX which gets truncated to
1730 // Handle the zero case.
1734 // The non-zero case is handled by computing:
1736 // nearestLogBase2(x) = logBase2(x) + x[logBase2(x)-1].
1738 // where x[i] is referring to the value of the ith bit of x.
1739 unsigned lg = logBase2();
1740 return lg + unsigned((*this)[lg - 1]);
1743 /// \returns the log base 2 of this APInt if its an exact power of two, -1
1745 int32_t exactLogBase2() const {
1751 /// \brief Compute the square root
1754 /// \brief Get the absolute value;
1756 /// If *this is < 0 then return -(*this), otherwise *this;
1763 /// \returns the multiplicative inverse for a given modulo.
1764 APInt multiplicativeInverse(const APInt &modulo) const;
1767 /// \name Support for division by constant
1770 /// Calculate the magic number for signed division by a constant.
1774 /// Calculate the magic number for unsigned division by a constant.
1776 mu magicu(unsigned LeadingZeros = 0) const;
1779 /// \name Building-block Operations for APInt and APFloat
1782 // These building block operations operate on a representation of arbitrary
1783 // precision, two's-complement, bignum integer values. They should be
1784 // sufficient to implement APInt and APFloat bignum requirements. Inputs are
1785 // generally a pointer to the base of an array of integer parts, representing
1786 // an unsigned bignum, and a count of how many parts there are.
1788 /// Sets the least significant part of a bignum to the input value, and zeroes
1789 /// out higher parts.
1790 static void tcSet(WordType *, WordType, unsigned);
1792 /// Assign one bignum to another.
1793 static void tcAssign(WordType *, const WordType *, unsigned);
1795 /// Returns true if a bignum is zero, false otherwise.
1796 static bool tcIsZero(const WordType *, unsigned);
1798 /// Extract the given bit of a bignum; returns 0 or 1. Zero-based.
1799 static int tcExtractBit(const WordType *, unsigned bit);
1801 /// Copy the bit vector of width srcBITS from SRC, starting at bit srcLSB, to
1802 /// DST, of dstCOUNT parts, such that the bit srcLSB becomes the least
1803 /// significant bit of DST. All high bits above srcBITS in DST are
1805 static void tcExtract(WordType *, unsigned dstCount,
1806 const WordType *, unsigned srcBits,
1809 /// Set the given bit of a bignum. Zero-based.
1810 static void tcSetBit(WordType *, unsigned bit);
1812 /// Clear the given bit of a bignum. Zero-based.
1813 static void tcClearBit(WordType *, unsigned bit);
1815 /// Returns the bit number of the least or most significant set bit of a
1816 /// number. If the input number has no bits set -1U is returned.
1817 static unsigned tcLSB(const WordType *, unsigned n);
1818 static unsigned tcMSB(const WordType *parts, unsigned n);
1820 /// Negate a bignum in-place.
1821 static void tcNegate(WordType *, unsigned);
1823 /// DST += RHS + CARRY where CARRY is zero or one. Returns the carry flag.
1824 static WordType tcAdd(WordType *, const WordType *,
1825 WordType carry, unsigned);
1826 /// DST += RHS. Returns the carry flag.
1827 static WordType tcAddPart(WordType *, WordType, unsigned);
1829 /// DST -= RHS + CARRY where CARRY is zero or one. Returns the carry flag.
1830 static WordType tcSubtract(WordType *, const WordType *,
1831 WordType carry, unsigned);
1832 /// DST -= RHS. Returns the carry flag.
1833 static WordType tcSubtractPart(WordType *, WordType, unsigned);
1835 /// DST += SRC * MULTIPLIER + PART if add is true
1836 /// DST = SRC * MULTIPLIER + PART if add is false
1838 /// Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC they must
1839 /// start at the same point, i.e. DST == SRC.
1841 /// If DSTPARTS == SRC_PARTS + 1 no overflow occurs and zero is returned.
1842 /// Otherwise DST is filled with the least significant DSTPARTS parts of the
1843 /// result, and if all of the omitted higher parts were zero return zero,
1844 /// otherwise overflow occurred and return one.
1845 static int tcMultiplyPart(WordType *dst, const WordType *src,
1846 WordType multiplier, WordType carry,
1847 unsigned srcParts, unsigned dstParts,
1850 /// DST = LHS * RHS, where DST has the same width as the operands and is
1851 /// filled with the least significant parts of the result. Returns one if
1852 /// overflow occurred, otherwise zero. DST must be disjoint from both
1854 static int tcMultiply(WordType *, const WordType *, const WordType *,
1857 /// DST = LHS * RHS, where DST has width the sum of the widths of the
1858 /// operands. No overflow occurs. DST must be disjoint from both operands.
1859 static void tcFullMultiply(WordType *, const WordType *,
1860 const WordType *, unsigned, unsigned);
1862 /// If RHS is zero LHS and REMAINDER are left unchanged, return one.
1863 /// Otherwise set LHS to LHS / RHS with the fractional part discarded, set
1864 /// REMAINDER to the remainder, return zero. i.e.
1866 /// OLD_LHS = RHS * LHS + REMAINDER
1868 /// SCRATCH is a bignum of the same size as the operands and result for use by
1869 /// the routine; its contents need not be initialized and are destroyed. LHS,
1870 /// REMAINDER and SCRATCH must be distinct.
1871 static int tcDivide(WordType *lhs, const WordType *rhs,
1872 WordType *remainder, WordType *scratch,
1875 /// Shift a bignum left Count bits. Shifted in bits are zero. There are no
1876 /// restrictions on Count.
1877 static void tcShiftLeft(WordType *, unsigned Words, unsigned Count);
1879 /// Shift a bignum right Count bits. Shifted in bits are zero. There are no
1880 /// restrictions on Count.
1881 static void tcShiftRight(WordType *, unsigned Words, unsigned Count);
1883 /// The obvious AND, OR and XOR and complement operations.
1884 static void tcAnd(WordType *, const WordType *, unsigned);
1885 static void tcOr(WordType *, const WordType *, unsigned);
1886 static void tcXor(WordType *, const WordType *, unsigned);
1887 static void tcComplement(WordType *, unsigned);
1889 /// Comparison (unsigned) of two bignums.
1890 static int tcCompare(const WordType *, const WordType *, unsigned);
1892 /// Increment a bignum in-place. Return the carry flag.
1893 static WordType tcIncrement(WordType *dst, unsigned parts) {
1894 return tcAddPart(dst, 1, parts);
1897 /// Decrement a bignum in-place. Return the borrow flag.
1898 static WordType tcDecrement(WordType *dst, unsigned parts) {
1899 return tcSubtractPart(dst, 1, parts);
1902 /// Set the least significant BITS and clear the rest.
1903 static void tcSetLeastSignificantBits(WordType *, unsigned, unsigned bits);
1905 /// \brief debug method
1911 /// Magic data for optimising signed division by a constant.
1913 APInt m; ///< magic number
1914 unsigned s; ///< shift amount
1917 /// Magic data for optimising unsigned division by a constant.
1919 APInt m; ///< magic number
1920 bool a; ///< add indicator
1921 unsigned s; ///< shift amount
1924 inline bool operator==(uint64_t V1, const APInt &V2) { return V2 == V1; }
1926 inline bool operator!=(uint64_t V1, const APInt &V2) { return V2 != V1; }
1928 /// \brief Unary bitwise complement operator.
1930 /// \returns an APInt that is the bitwise complement of \p v.
1931 inline APInt operator~(APInt v) {
1936 inline APInt operator&(APInt a, const APInt &b) {
1941 inline APInt operator&(const APInt &a, APInt &&b) {
1943 return std::move(b);
1946 inline APInt operator&(APInt a, uint64_t RHS) {
1951 inline APInt operator&(uint64_t LHS, APInt b) {
1956 inline APInt operator|(APInt a, const APInt &b) {
1961 inline APInt operator|(const APInt &a, APInt &&b) {
1963 return std::move(b);
1966 inline APInt operator|(APInt a, uint64_t RHS) {
1971 inline APInt operator|(uint64_t LHS, APInt b) {
1976 inline APInt operator^(APInt a, const APInt &b) {
1981 inline APInt operator^(const APInt &a, APInt &&b) {
1983 return std::move(b);
1986 inline APInt operator^(APInt a, uint64_t RHS) {
1991 inline APInt operator^(uint64_t LHS, APInt b) {
1996 inline raw_ostream &operator<<(raw_ostream &OS, const APInt &I) {
2001 inline APInt operator-(APInt v) {
2006 inline APInt operator+(APInt a, const APInt &b) {
2011 inline APInt operator+(const APInt &a, APInt &&b) {
2013 return std::move(b);
2016 inline APInt operator+(APInt a, uint64_t RHS) {
2021 inline APInt operator+(uint64_t LHS, APInt b) {
2026 inline APInt operator-(APInt a, const APInt &b) {
2031 inline APInt operator-(const APInt &a, APInt &&b) {
2034 return std::move(b);
2037 inline APInt operator-(APInt a, uint64_t RHS) {
2042 inline APInt operator-(uint64_t LHS, APInt b) {
2048 inline APInt operator*(APInt a, uint64_t RHS) {
2053 inline APInt operator*(uint64_t LHS, APInt b) {
2059 namespace APIntOps {
2061 /// \brief Determine the smaller of two APInts considered to be signed.
2062 inline const APInt &smin(const APInt &A, const APInt &B) {
2063 return A.slt(B) ? A : B;
2066 /// \brief Determine the larger of two APInts considered to be signed.
2067 inline const APInt &smax(const APInt &A, const APInt &B) {
2068 return A.sgt(B) ? A : B;
2071 /// \brief Determine the smaller of two APInts considered to be signed.
2072 inline const APInt &umin(const APInt &A, const APInt &B) {
2073 return A.ult(B) ? A : B;
2076 /// \brief Determine the larger of two APInts considered to be unsigned.
2077 inline const APInt &umax(const APInt &A, const APInt &B) {
2078 return A.ugt(B) ? A : B;
2081 /// \brief Compute GCD of two unsigned APInt values.
2083 /// This function returns the greatest common divisor of the two APInt values
2084 /// using Stein's algorithm.
2086 /// \returns the greatest common divisor of A and B.
2087 APInt GreatestCommonDivisor(APInt A, APInt B);
2089 /// \brief Converts the given APInt to a double value.
2091 /// Treats the APInt as an unsigned value for conversion purposes.
2092 inline double RoundAPIntToDouble(const APInt &APIVal) {
2093 return APIVal.roundToDouble();
2096 /// \brief Converts the given APInt to a double value.
2098 /// Treats the APInt as a signed value for conversion purposes.
2099 inline double RoundSignedAPIntToDouble(const APInt &APIVal) {
2100 return APIVal.signedRoundToDouble();
2103 /// \brief Converts the given APInt to a float vlalue.
2104 inline float RoundAPIntToFloat(const APInt &APIVal) {
2105 return float(RoundAPIntToDouble(APIVal));
2108 /// \brief Converts the given APInt to a float value.
2110 /// Treast the APInt as a signed value for conversion purposes.
2111 inline float RoundSignedAPIntToFloat(const APInt &APIVal) {
2112 return float(APIVal.signedRoundToDouble());
2115 /// \brief Converts the given double value into a APInt.
2117 /// This function convert a double value to an APInt value.
2118 APInt RoundDoubleToAPInt(double Double, unsigned width);
2120 /// \brief Converts a float value into a APInt.
2122 /// Converts a float value into an APInt value.
2123 inline APInt RoundFloatToAPInt(float Float, unsigned width) {
2124 return RoundDoubleToAPInt(double(Float), width);
2127 } // End of APIntOps namespace
2129 // See friend declaration above. This additional declaration is required in
2130 // order to compile LLVM with IBM xlC compiler.
2131 hash_code hash_value(const APInt &Arg);
2132 } // End of llvm namespace