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 /// \brief Convert a char array into an APInt
162 /// \param radix 2, 8, 10, 16, or 36
163 /// Converts a string into a number. The string must be non-empty
164 /// and well-formed as a number of the given base. The bit-width
165 /// must be sufficient to hold the result.
167 /// This is used by the constructors that take string arguments.
169 /// StringRef::getAsInteger is superficially similar but (1) does
170 /// not assume that the string is well-formed and (2) grows the
171 /// result to hold the input.
172 void fromString(unsigned numBits, StringRef str, uint8_t radix);
174 /// \brief An internal division function for dividing APInts.
176 /// This is used by the toString method to divide by the radix. It simply
177 /// provides a more convenient form of divide for internal use since KnuthDiv
178 /// has specific constraints on its inputs. If those constraints are not met
179 /// then it provides a simpler form of divide.
180 static void divide(const APInt &LHS, unsigned lhsWords, const APInt &RHS,
181 unsigned rhsWords, APInt *Quotient, APInt *Remainder);
183 /// out-of-line slow case for inline constructor
184 void initSlowCase(uint64_t val, bool isSigned);
186 /// shared code between two array constructors
187 void initFromArray(ArrayRef<uint64_t> array);
189 /// out-of-line slow case for inline copy constructor
190 void initSlowCase(const APInt &that);
192 /// out-of-line slow case for shl
193 void shlSlowCase(unsigned ShiftAmt);
195 /// out-of-line slow case for lshr.
196 void lshrSlowCase(unsigned ShiftAmt);
198 /// out-of-line slow case for ashr.
199 void ashrSlowCase(unsigned ShiftAmt);
201 /// out-of-line slow case for operator=
202 void AssignSlowCase(const APInt &RHS);
204 /// out-of-line slow case for operator==
205 bool EqualSlowCase(const APInt &RHS) const LLVM_READONLY;
207 /// out-of-line slow case for countLeadingZeros
208 unsigned countLeadingZerosSlowCase() const LLVM_READONLY;
210 /// out-of-line slow case for countTrailingOnes
211 unsigned countTrailingOnesSlowCase() const LLVM_READONLY;
213 /// out-of-line slow case for countPopulation
214 unsigned countPopulationSlowCase() const LLVM_READONLY;
216 /// out-of-line slow case for intersects.
217 bool intersectsSlowCase(const APInt &RHS) const LLVM_READONLY;
219 /// out-of-line slow case for isSubsetOf.
220 bool isSubsetOfSlowCase(const APInt &RHS) const LLVM_READONLY;
222 /// out-of-line slow case for setBits.
223 void setBitsSlowCase(unsigned loBit, unsigned hiBit);
225 /// out-of-line slow case for flipAllBits.
226 void flipAllBitsSlowCase();
228 /// out-of-line slow case for operator&=.
229 void AndAssignSlowCase(const APInt& RHS);
231 /// out-of-line slow case for operator|=.
232 void OrAssignSlowCase(const APInt& RHS);
234 /// out-of-line slow case for operator^=.
235 void XorAssignSlowCase(const APInt& RHS);
237 /// Unsigned comparison. Returns -1, 0, or 1 if this APInt is less than, equal
238 /// to, or greater than RHS.
239 int compare(const APInt &RHS) const LLVM_READONLY;
241 /// Signed comparison. Returns -1, 0, or 1 if this APInt is less than, equal
242 /// to, or greater than RHS.
243 int compareSigned(const APInt &RHS) const LLVM_READONLY;
246 /// \name Constructors
249 /// \brief Create a new APInt of numBits width, initialized as val.
251 /// If isSigned is true then val is treated as if it were a signed value
252 /// (i.e. as an int64_t) and the appropriate sign extension to the bit width
253 /// will be done. Otherwise, no sign extension occurs (high order bits beyond
254 /// the range of val are zero filled).
256 /// \param numBits the bit width of the constructed APInt
257 /// \param val the initial value of the APInt
258 /// \param isSigned how to treat signedness of val
259 APInt(unsigned numBits, uint64_t val, bool isSigned = false)
260 : BitWidth(numBits) {
261 assert(BitWidth && "bitwidth too small");
262 if (isSingleWord()) {
266 initSlowCase(val, isSigned);
270 /// \brief Construct an APInt of numBits width, initialized as bigVal[].
272 /// Note that bigVal.size() can be smaller or larger than the corresponding
273 /// bit width but any extraneous bits will be dropped.
275 /// \param numBits the bit width of the constructed APInt
276 /// \param bigVal a sequence of words to form the initial value of the APInt
277 APInt(unsigned numBits, ArrayRef<uint64_t> bigVal);
279 /// Equivalent to APInt(numBits, ArrayRef<uint64_t>(bigVal, numWords)), but
280 /// deprecated because this constructor is prone to ambiguity with the
281 /// APInt(unsigned, uint64_t, bool) constructor.
283 /// If this overload is ever deleted, care should be taken to prevent calls
284 /// from being incorrectly captured by the APInt(unsigned, uint64_t, bool)
286 APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[]);
288 /// \brief Construct an APInt from a string representation.
290 /// This constructor interprets the string \p str in the given radix. The
291 /// interpretation stops when the first character that is not suitable for the
292 /// radix is encountered, or the end of the string. Acceptable radix values
293 /// are 2, 8, 10, 16, and 36. It is an error for the value implied by the
294 /// string to require more bits than numBits.
296 /// \param numBits the bit width of the constructed APInt
297 /// \param str the string to be interpreted
298 /// \param radix the radix to use for the conversion
299 APInt(unsigned numBits, StringRef str, uint8_t radix);
301 /// Simply makes *this a copy of that.
302 /// @brief Copy Constructor.
303 APInt(const APInt &that) : BitWidth(that.BitWidth) {
310 /// \brief Move Constructor.
311 APInt(APInt &&that) : BitWidth(that.BitWidth) {
312 memcpy(&U, &that.U, sizeof(U));
316 /// \brief Destructor.
322 /// \brief Default constructor that creates an uninteresting APInt
323 /// representing a 1-bit zero value.
325 /// This is useful for object deserialization (pair this with the static
327 explicit APInt() : BitWidth(1) { U.VAL = 0; }
329 /// \brief Returns whether this instance allocated memory.
330 bool needsCleanup() const { return !isSingleWord(); }
332 /// Used to insert APInt objects, or objects that contain APInt objects, into
334 void Profile(FoldingSetNodeID &id) const;
337 /// \name Value Tests
340 /// \brief Determine sign of this APInt.
342 /// This tests the high bit of this APInt to determine if it is set.
344 /// \returns true if this APInt is negative, false otherwise
345 bool isNegative() const { return (*this)[BitWidth - 1]; }
347 /// \brief Determine if this APInt Value is non-negative (>= 0)
349 /// This tests the high bit of the APInt to determine if it is unset.
350 bool isNonNegative() const { return !isNegative(); }
352 /// \brief Determine if sign bit of this APInt is set.
354 /// This tests the high bit of this APInt to determine if it is set.
356 /// \returns true if this APInt has its sign bit set, false otherwise.
357 bool isSignBitSet() const { return (*this)[BitWidth-1]; }
359 /// \brief Determine if sign bit of this APInt is clear.
361 /// This tests the high bit of this APInt to determine if it is clear.
363 /// \returns true if this APInt has its sign bit clear, false otherwise.
364 bool isSignBitClear() const { return !isSignBitSet(); }
366 /// \brief Determine if this APInt Value is positive.
368 /// This tests if the value of this APInt is positive (> 0). Note
369 /// that 0 is not a positive value.
371 /// \returns true if this APInt is positive.
372 bool isStrictlyPositive() const { return isNonNegative() && !isNullValue(); }
374 /// \brief Determine if all bits are set
376 /// This checks to see if the value has all bits of the APInt are set or not.
377 bool isAllOnesValue() const {
379 return U.VAL == WORD_MAX >> (APINT_BITS_PER_WORD - BitWidth);
380 return countPopulationSlowCase() == BitWidth;
383 /// \brief Determine if all bits are clear
385 /// This checks to see if the value has all bits of the APInt are clear or
387 bool isNullValue() const { return !*this; }
389 /// \brief Determine if this is the largest unsigned value.
391 /// This checks to see if the value of this APInt is the maximum unsigned
392 /// value for the APInt's bit width.
393 bool isMaxValue() const { return isAllOnesValue(); }
395 /// \brief Determine if this is the largest signed value.
397 /// This checks to see if the value of this APInt is the maximum signed
398 /// value for the APInt's bit width.
399 bool isMaxSignedValue() const {
400 return !isNegative() && countPopulation() == BitWidth - 1;
403 /// \brief Determine if this is the smallest unsigned value.
405 /// This checks to see if the value of this APInt is the minimum unsigned
406 /// value for the APInt's bit width.
407 bool isMinValue() const { return isNullValue(); }
409 /// \brief Determine if this is the smallest signed value.
411 /// This checks to see if the value of this APInt is the minimum signed
412 /// value for the APInt's bit width.
413 bool isMinSignedValue() const {
414 return isNegative() && isPowerOf2();
417 /// \brief Check if this APInt has an N-bits unsigned integer value.
418 bool isIntN(unsigned N) const {
419 assert(N && "N == 0 ???");
420 return getActiveBits() <= N;
423 /// \brief Check if this APInt has an N-bits signed integer value.
424 bool isSignedIntN(unsigned N) const {
425 assert(N && "N == 0 ???");
426 return getMinSignedBits() <= N;
429 /// \brief Check if this APInt's value is a power of two greater than zero.
431 /// \returns true if the argument APInt value is a power of two > 0.
432 bool isPowerOf2() const {
434 return isPowerOf2_64(U.VAL);
435 return countPopulationSlowCase() == 1;
438 /// \brief Check if the APInt's value is returned by getSignMask.
440 /// \returns true if this is the value returned by getSignMask.
441 bool isSignMask() const { return isMinSignedValue(); }
443 /// \brief Convert APInt to a boolean value.
445 /// This converts the APInt to a boolean value as a test against zero.
446 bool getBoolValue() const { return !!*this; }
448 /// If this value is smaller than the specified limit, return it, otherwise
449 /// return the limit value. This causes the value to saturate to the limit.
450 uint64_t getLimitedValue(uint64_t Limit = UINT64_MAX) const {
451 return ugt(Limit) ? Limit : getZExtValue();
454 /// \brief Check if the APInt consists of a repeated bit pattern.
456 /// e.g. 0x01010101 satisfies isSplat(8).
457 /// \param SplatSizeInBits The size of the pattern in bits. Must divide bit
458 /// width without remainder.
459 bool isSplat(unsigned SplatSizeInBits) const;
461 /// \returns true if this APInt value is a sequence of \param numBits ones
462 /// starting at the least significant bit with the remainder zero.
463 bool isMask(unsigned numBits) const {
464 assert(numBits != 0 && "numBits must be non-zero");
465 assert(numBits <= BitWidth && "numBits out of range");
467 return U.VAL == (WORD_MAX >> (APINT_BITS_PER_WORD - numBits));
468 unsigned Ones = countTrailingOnesSlowCase();
469 return (numBits == Ones) &&
470 ((Ones + countLeadingZerosSlowCase()) == BitWidth);
473 /// \returns true if this APInt is a non-empty sequence of ones starting at
474 /// the least significant bit with the remainder zero.
475 /// Ex. isMask(0x0000FFFFU) == true.
476 bool isMask() const {
478 return isMask_64(U.VAL);
479 unsigned Ones = countTrailingOnesSlowCase();
480 return (Ones > 0) && ((Ones + countLeadingZerosSlowCase()) == BitWidth);
483 /// \brief Return true if this APInt value contains a sequence of ones with
484 /// the remainder zero.
485 bool isShiftedMask() const {
487 return isShiftedMask_64(U.VAL);
488 unsigned Ones = countPopulationSlowCase();
489 unsigned LeadZ = countLeadingZerosSlowCase();
490 return (Ones + LeadZ + countTrailingZeros()) == BitWidth;
494 /// \name Value Generators
497 /// \brief Gets maximum unsigned value of APInt for specific bit width.
498 static APInt getMaxValue(unsigned numBits) {
499 return getAllOnesValue(numBits);
502 /// \brief Gets maximum signed value of APInt for a specific bit width.
503 static APInt getSignedMaxValue(unsigned numBits) {
504 APInt API = getAllOnesValue(numBits);
505 API.clearBit(numBits - 1);
509 /// \brief Gets minimum unsigned value of APInt for a specific bit width.
510 static APInt getMinValue(unsigned numBits) { return APInt(numBits, 0); }
512 /// \brief Gets minimum signed value of APInt for a specific bit width.
513 static APInt getSignedMinValue(unsigned numBits) {
514 APInt API(numBits, 0);
515 API.setBit(numBits - 1);
519 /// \brief Get the SignMask for a specific bit width.
521 /// This is just a wrapper function of getSignedMinValue(), and it helps code
522 /// readability when we want to get a SignMask.
523 static APInt getSignMask(unsigned BitWidth) {
524 return getSignedMinValue(BitWidth);
527 /// \brief Get the all-ones value.
529 /// \returns the all-ones value for an APInt of the specified bit-width.
530 static APInt getAllOnesValue(unsigned numBits) {
531 return APInt(numBits, WORD_MAX, true);
534 /// \brief Get the '0' value.
536 /// \returns the '0' value for an APInt of the specified bit-width.
537 static APInt getNullValue(unsigned numBits) { return APInt(numBits, 0); }
539 /// \brief Compute an APInt containing numBits highbits from this APInt.
541 /// Get an APInt with the same BitWidth as this APInt, just zero mask
542 /// the low bits and right shift to the least significant bit.
544 /// \returns the high "numBits" bits of this APInt.
545 APInt getHiBits(unsigned numBits) const;
547 /// \brief Compute an APInt containing numBits lowbits from this APInt.
549 /// Get an APInt with the same BitWidth as this APInt, just zero mask
552 /// \returns the low "numBits" bits of this APInt.
553 APInt getLoBits(unsigned numBits) const;
555 /// \brief Return an APInt with exactly one bit set in the result.
556 static APInt getOneBitSet(unsigned numBits, unsigned BitNo) {
557 APInt Res(numBits, 0);
562 /// \brief Get a value with a block of bits set.
564 /// Constructs an APInt value that has a contiguous range of bits set. The
565 /// bits from loBit (inclusive) to hiBit (exclusive) will be set. All other
566 /// bits will be zero. For example, with parameters(32, 0, 16) you would get
567 /// 0x0000FFFF. If hiBit is less than loBit then the set bits "wrap". For
568 /// example, with parameters (32, 28, 4), you would get 0xF000000F.
570 /// \param numBits the intended bit width of the result
571 /// \param loBit the index of the lowest bit set.
572 /// \param hiBit the index of the highest bit set.
574 /// \returns An APInt value with the requested bits set.
575 static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit) {
576 APInt Res(numBits, 0);
577 Res.setBits(loBit, hiBit);
581 /// \brief Get a value with upper bits starting at loBit set.
583 /// Constructs an APInt value that has a contiguous range of bits set. The
584 /// bits from loBit (inclusive) to numBits (exclusive) will be set. All other
585 /// bits will be zero. For example, with parameters(32, 12) you would get
588 /// \param numBits the intended bit width of the result
589 /// \param loBit the index of the lowest bit to set.
591 /// \returns An APInt value with the requested bits set.
592 static APInt getBitsSetFrom(unsigned numBits, unsigned loBit) {
593 APInt Res(numBits, 0);
594 Res.setBitsFrom(loBit);
598 /// \brief Get a value with high bits set
600 /// Constructs an APInt value that has the top hiBitsSet bits set.
602 /// \param numBits the bitwidth of the result
603 /// \param hiBitsSet the number of high-order bits set in the result.
604 static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet) {
605 APInt Res(numBits, 0);
606 Res.setHighBits(hiBitsSet);
610 /// \brief Get a value with low bits set
612 /// Constructs an APInt value that has the bottom loBitsSet bits set.
614 /// \param numBits the bitwidth of the result
615 /// \param loBitsSet the number of low-order bits set in the result.
616 static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet) {
617 APInt Res(numBits, 0);
618 Res.setLowBits(loBitsSet);
622 /// \brief Return a value containing V broadcasted over NewLen bits.
623 static APInt getSplat(unsigned NewLen, const APInt &V);
625 /// \brief Determine if two APInts have the same value, after zero-extending
626 /// one of them (if needed!) to ensure that the bit-widths match.
627 static bool isSameValue(const APInt &I1, const APInt &I2) {
628 if (I1.getBitWidth() == I2.getBitWidth())
631 if (I1.getBitWidth() > I2.getBitWidth())
632 return I1 == I2.zext(I1.getBitWidth());
634 return I1.zext(I2.getBitWidth()) == I2;
637 /// \brief Overload to compute a hash_code for an APInt value.
638 friend hash_code hash_value(const APInt &Arg);
640 /// This function returns a pointer to the internal storage of the APInt.
641 /// This is useful for writing out the APInt in binary form without any
643 const uint64_t *getRawData() const {
650 /// \name Unary Operators
653 /// \brief Postfix increment operator.
655 /// Increments *this by 1.
657 /// \returns a new APInt value representing the original value of *this.
658 const APInt operator++(int) {
664 /// \brief Prefix increment operator.
666 /// \returns *this incremented by one
669 /// \brief Postfix decrement operator.
671 /// Decrements *this by 1.
673 /// \returns a new APInt value representing the original value of *this.
674 const APInt operator--(int) {
680 /// \brief Prefix decrement operator.
682 /// \returns *this decremented by one.
685 /// \brief Logical negation operator.
687 /// Performs logical negation operation on this APInt.
689 /// \returns true if *this is zero, false otherwise.
690 bool operator!() const {
693 return countLeadingZerosSlowCase() == BitWidth;
697 /// \name Assignment Operators
700 /// \brief Copy assignment operator.
702 /// \returns *this after assignment of RHS.
703 APInt &operator=(const APInt &RHS) {
704 // If the bitwidths are the same, we can avoid mucking with memory
705 if (isSingleWord() && RHS.isSingleWord()) {
707 BitWidth = RHS.BitWidth;
708 return clearUnusedBits();
715 /// @brief Move assignment operator.
716 APInt &operator=(APInt &&that) {
717 assert(this != &that && "Self-move not supported");
721 // Use memcpy so that type based alias analysis sees both VAL and pVal
723 memcpy(&U, &that.U, sizeof(U));
725 BitWidth = that.BitWidth;
731 /// \brief Assignment operator.
733 /// The RHS value is assigned to *this. If the significant bits in RHS exceed
734 /// the bit width, the excess bits are truncated. If the bit width is larger
735 /// than 64, the value is zero filled in the unspecified high order bits.
737 /// \returns *this after assignment of RHS value.
738 APInt &operator=(uint64_t RHS) {
739 if (isSingleWord()) {
744 memset(U.pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
749 /// \brief Bitwise AND assignment operator.
751 /// Performs a bitwise AND operation on this APInt and RHS. The result is
752 /// assigned to *this.
754 /// \returns *this after ANDing with RHS.
755 APInt &operator&=(const APInt &RHS) {
756 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
760 AndAssignSlowCase(RHS);
764 /// \brief Bitwise AND assignment operator.
766 /// Performs a bitwise AND operation on this APInt and RHS. RHS is
767 /// logically zero-extended or truncated to match the bit-width of
769 APInt &operator&=(uint64_t RHS) {
770 if (isSingleWord()) {
775 memset(U.pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
779 /// \brief Bitwise OR assignment operator.
781 /// Performs a bitwise OR operation on this APInt and RHS. The result is
784 /// \returns *this after ORing with RHS.
785 APInt &operator|=(const APInt &RHS) {
786 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
790 OrAssignSlowCase(RHS);
794 /// \brief Bitwise OR assignment operator.
796 /// Performs a bitwise OR operation on this APInt and RHS. RHS is
797 /// logically zero-extended or truncated to match the bit-width of
799 APInt &operator|=(uint64_t RHS) {
800 if (isSingleWord()) {
809 /// \brief Bitwise XOR assignment operator.
811 /// Performs a bitwise XOR operation on this APInt and RHS. The result is
812 /// assigned to *this.
814 /// \returns *this after XORing with RHS.
815 APInt &operator^=(const APInt &RHS) {
816 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
820 XorAssignSlowCase(RHS);
824 /// \brief Bitwise XOR assignment operator.
826 /// Performs a bitwise XOR operation on this APInt and RHS. RHS is
827 /// logically zero-extended or truncated to match the bit-width of
829 APInt &operator^=(uint64_t RHS) {
830 if (isSingleWord()) {
839 /// \brief Multiplication assignment operator.
841 /// Multiplies this APInt by RHS and assigns the result to *this.
844 APInt &operator*=(const APInt &RHS);
846 /// \brief Addition assignment operator.
848 /// Adds RHS to *this and assigns the result to *this.
851 APInt &operator+=(const APInt &RHS);
852 APInt &operator+=(uint64_t RHS);
854 /// \brief Subtraction assignment operator.
856 /// Subtracts RHS from *this and assigns the result to *this.
859 APInt &operator-=(const APInt &RHS);
860 APInt &operator-=(uint64_t RHS);
862 /// \brief Left-shift assignment function.
864 /// Shifts *this left by shiftAmt and assigns the result to *this.
866 /// \returns *this after shifting left by ShiftAmt
867 APInt &operator<<=(unsigned ShiftAmt) {
868 assert(ShiftAmt <= BitWidth && "Invalid shift amount");
869 if (isSingleWord()) {
870 if (ShiftAmt == BitWidth)
874 return clearUnusedBits();
876 shlSlowCase(ShiftAmt);
880 /// \brief Left-shift assignment function.
882 /// Shifts *this left by shiftAmt and assigns the result to *this.
884 /// \returns *this after shifting left by ShiftAmt
885 APInt &operator<<=(const APInt &ShiftAmt);
888 /// \name Binary Operators
891 /// \brief Multiplication operator.
893 /// Multiplies this APInt by RHS and returns the result.
894 APInt operator*(const APInt &RHS) const;
896 /// \brief Left logical shift operator.
898 /// Shifts this APInt left by \p Bits and returns the result.
899 APInt operator<<(unsigned Bits) const { return shl(Bits); }
901 /// \brief Left logical shift operator.
903 /// Shifts this APInt left by \p Bits and returns the result.
904 APInt operator<<(const APInt &Bits) const { return shl(Bits); }
906 /// \brief Arithmetic right-shift function.
908 /// Arithmetic right-shift this APInt by shiftAmt.
909 APInt ashr(unsigned ShiftAmt) const {
911 R.ashrInPlace(ShiftAmt);
915 /// Arithmetic right-shift this APInt by ShiftAmt in place.
916 void ashrInPlace(unsigned ShiftAmt) {
917 assert(ShiftAmt <= BitWidth && "Invalid shift amount");
918 if (isSingleWord()) {
919 int64_t SExtVAL = SignExtend64(U.VAL, BitWidth);
920 if (ShiftAmt == BitWidth)
921 U.VAL = SExtVAL >> (APINT_BITS_PER_WORD - 1); // Fill with sign bit.
923 U.VAL = SExtVAL >> ShiftAmt;
927 ashrSlowCase(ShiftAmt);
930 /// \brief Logical right-shift function.
932 /// Logical right-shift this APInt by shiftAmt.
933 APInt lshr(unsigned shiftAmt) const {
935 R.lshrInPlace(shiftAmt);
939 /// Logical right-shift this APInt by ShiftAmt in place.
940 void lshrInPlace(unsigned ShiftAmt) {
941 assert(ShiftAmt <= BitWidth && "Invalid shift amount");
942 if (isSingleWord()) {
943 if (ShiftAmt == BitWidth)
949 lshrSlowCase(ShiftAmt);
952 /// \brief Left-shift function.
954 /// Left-shift this APInt by shiftAmt.
955 APInt shl(unsigned shiftAmt) const {
961 /// \brief Rotate left by rotateAmt.
962 APInt rotl(unsigned rotateAmt) const;
964 /// \brief Rotate right by rotateAmt.
965 APInt rotr(unsigned rotateAmt) const;
967 /// \brief Arithmetic right-shift function.
969 /// Arithmetic right-shift this APInt by shiftAmt.
970 APInt ashr(const APInt &ShiftAmt) const {
972 R.ashrInPlace(ShiftAmt);
976 /// Arithmetic right-shift this APInt by shiftAmt in place.
977 void ashrInPlace(const APInt &shiftAmt);
979 /// \brief Logical right-shift function.
981 /// Logical right-shift this APInt by shiftAmt.
982 APInt lshr(const APInt &ShiftAmt) const {
984 R.lshrInPlace(ShiftAmt);
988 /// Logical right-shift this APInt by ShiftAmt in place.
989 void lshrInPlace(const APInt &ShiftAmt);
991 /// \brief Left-shift function.
993 /// Left-shift this APInt by shiftAmt.
994 APInt shl(const APInt &ShiftAmt) const {
1000 /// \brief Rotate left by rotateAmt.
1001 APInt rotl(const APInt &rotateAmt) const;
1003 /// \brief Rotate right by rotateAmt.
1004 APInt rotr(const APInt &rotateAmt) const;
1006 /// \brief Unsigned division operation.
1008 /// Perform an unsigned divide operation on this APInt by RHS. Both this and
1009 /// RHS are treated as unsigned quantities for purposes of this division.
1011 /// \returns a new APInt value containing the division result
1012 APInt udiv(const APInt &RHS) const;
1014 /// \brief Signed division function for APInt.
1016 /// Signed divide this APInt by APInt RHS.
1017 APInt sdiv(const APInt &RHS) const;
1019 /// \brief Unsigned remainder operation.
1021 /// Perform an unsigned remainder operation on this APInt with RHS being the
1022 /// divisor. Both this and RHS are treated as unsigned quantities for purposes
1023 /// of this operation. Note that this is a true remainder operation and not a
1024 /// modulo operation because the sign follows the sign of the dividend which
1027 /// \returns a new APInt value containing the remainder result
1028 APInt urem(const APInt &RHS) const;
1030 /// \brief Function for signed remainder operation.
1032 /// Signed remainder operation on APInt.
1033 APInt srem(const APInt &RHS) const;
1035 /// \brief Dual division/remainder interface.
1037 /// Sometimes it is convenient to divide two APInt values and obtain both the
1038 /// quotient and remainder. This function does both operations in the same
1039 /// computation making it a little more efficient. The pair of input arguments
1040 /// may overlap with the pair of output arguments. It is safe to call
1041 /// udivrem(X, Y, X, Y), for example.
1042 static void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient,
1045 static void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient,
1048 // Operations that return overflow indicators.
1049 APInt sadd_ov(const APInt &RHS, bool &Overflow) const;
1050 APInt uadd_ov(const APInt &RHS, bool &Overflow) const;
1051 APInt ssub_ov(const APInt &RHS, bool &Overflow) const;
1052 APInt usub_ov(const APInt &RHS, bool &Overflow) const;
1053 APInt sdiv_ov(const APInt &RHS, bool &Overflow) const;
1054 APInt smul_ov(const APInt &RHS, bool &Overflow) const;
1055 APInt umul_ov(const APInt &RHS, bool &Overflow) const;
1056 APInt sshl_ov(const APInt &Amt, bool &Overflow) const;
1057 APInt ushl_ov(const APInt &Amt, bool &Overflow) const;
1059 /// \brief Array-indexing support.
1061 /// \returns the bit value at bitPosition
1062 bool operator[](unsigned bitPosition) const {
1063 assert(bitPosition < getBitWidth() && "Bit position out of bounds!");
1064 return (maskBit(bitPosition) &
1065 (isSingleWord() ? U.VAL : U.pVal[whichWord(bitPosition)])) !=
1070 /// \name Comparison Operators
1073 /// \brief Equality operator.
1075 /// Compares this APInt with RHS for the validity of the equality
1077 bool operator==(const APInt &RHS) const {
1078 assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths");
1080 return U.VAL == RHS.U.VAL;
1081 return EqualSlowCase(RHS);
1084 /// \brief Equality operator.
1086 /// Compares this APInt with a uint64_t for the validity of the equality
1089 /// \returns true if *this == Val
1090 bool operator==(uint64_t Val) const {
1091 return (isSingleWord() || getActiveBits() <= 64) && getZExtValue() == Val;
1094 /// \brief Equality comparison.
1096 /// Compares this APInt with RHS for the validity of the equality
1099 /// \returns true if *this == Val
1100 bool eq(const APInt &RHS) const { return (*this) == RHS; }
1102 /// \brief Inequality operator.
1104 /// Compares this APInt with RHS for the validity of the inequality
1107 /// \returns true if *this != Val
1108 bool operator!=(const APInt &RHS) const { return !((*this) == RHS); }
1110 /// \brief Inequality operator.
1112 /// Compares this APInt with a uint64_t for the validity of the inequality
1115 /// \returns true if *this != Val
1116 bool operator!=(uint64_t Val) const { return !((*this) == Val); }
1118 /// \brief Inequality comparison
1120 /// Compares this APInt with RHS for the validity of the inequality
1123 /// \returns true if *this != Val
1124 bool ne(const APInt &RHS) const { return !((*this) == RHS); }
1126 /// \brief Unsigned less than comparison
1128 /// Regards both *this and RHS as unsigned quantities and compares them for
1129 /// the validity of the less-than relationship.
1131 /// \returns true if *this < RHS when both are considered unsigned.
1132 bool ult(const APInt &RHS) const { return compare(RHS) < 0; }
1134 /// \brief Unsigned less than comparison
1136 /// Regards both *this as an unsigned quantity and compares it with RHS for
1137 /// the validity of the less-than relationship.
1139 /// \returns true if *this < RHS when considered unsigned.
1140 bool ult(uint64_t RHS) const {
1141 // Only need to check active bits if not a single word.
1142 return (isSingleWord() || getActiveBits() <= 64) && getZExtValue() < RHS;
1145 /// \brief Signed less than comparison
1147 /// Regards both *this and RHS as signed quantities and compares them for
1148 /// validity of the less-than relationship.
1150 /// \returns true if *this < RHS when both are considered signed.
1151 bool slt(const APInt &RHS) const { return compareSigned(RHS) < 0; }
1153 /// \brief Signed less than comparison
1155 /// Regards both *this as a signed quantity and compares it with RHS for
1156 /// the validity of the less-than relationship.
1158 /// \returns true if *this < RHS when considered signed.
1159 bool slt(int64_t RHS) const {
1160 return (!isSingleWord() && getMinSignedBits() > 64) ? isNegative()
1161 : getSExtValue() < RHS;
1164 /// \brief Unsigned less or equal comparison
1166 /// Regards both *this and RHS as unsigned quantities and compares them for
1167 /// validity of the less-or-equal relationship.
1169 /// \returns true if *this <= RHS when both are considered unsigned.
1170 bool ule(const APInt &RHS) const { return compare(RHS) <= 0; }
1172 /// \brief Unsigned less or equal comparison
1174 /// Regards both *this as an unsigned quantity and compares it with RHS for
1175 /// the validity of the less-or-equal relationship.
1177 /// \returns true if *this <= RHS when considered unsigned.
1178 bool ule(uint64_t RHS) const { return !ugt(RHS); }
1180 /// \brief Signed less or equal comparison
1182 /// Regards both *this and RHS as signed quantities and compares them for
1183 /// validity of the less-or-equal relationship.
1185 /// \returns true if *this <= RHS when both are considered signed.
1186 bool sle(const APInt &RHS) const { return compareSigned(RHS) <= 0; }
1188 /// \brief Signed less or equal comparison
1190 /// Regards both *this as a signed quantity and compares it with RHS for the
1191 /// validity of the less-or-equal relationship.
1193 /// \returns true if *this <= RHS when considered signed.
1194 bool sle(uint64_t RHS) const { return !sgt(RHS); }
1196 /// \brief Unsigned greather than comparison
1198 /// Regards both *this and RHS as unsigned quantities and compares them for
1199 /// the validity of the greater-than relationship.
1201 /// \returns true if *this > RHS when both are considered unsigned.
1202 bool ugt(const APInt &RHS) const { return !ule(RHS); }
1204 /// \brief Unsigned greater than comparison
1206 /// Regards both *this as an unsigned quantity and compares it with RHS for
1207 /// the validity of the greater-than relationship.
1209 /// \returns true if *this > RHS when considered unsigned.
1210 bool ugt(uint64_t RHS) const {
1211 // Only need to check active bits if not a single word.
1212 return (!isSingleWord() && getActiveBits() > 64) || getZExtValue() > RHS;
1215 /// \brief Signed greather than comparison
1217 /// Regards both *this and RHS as signed quantities and compares them for the
1218 /// validity of the greater-than relationship.
1220 /// \returns true if *this > RHS when both are considered signed.
1221 bool sgt(const APInt &RHS) const { return !sle(RHS); }
1223 /// \brief Signed greater than comparison
1225 /// Regards both *this as a signed quantity and compares it with RHS for
1226 /// the validity of the greater-than relationship.
1228 /// \returns true if *this > RHS when considered signed.
1229 bool sgt(int64_t RHS) const {
1230 return (!isSingleWord() && getMinSignedBits() > 64) ? !isNegative()
1231 : getSExtValue() > RHS;
1234 /// \brief Unsigned greater or equal comparison
1236 /// Regards both *this and RHS as unsigned quantities and compares them for
1237 /// validity of the greater-or-equal relationship.
1239 /// \returns true if *this >= RHS when both are considered unsigned.
1240 bool uge(const APInt &RHS) const { return !ult(RHS); }
1242 /// \brief Unsigned greater or equal comparison
1244 /// Regards both *this as an unsigned quantity and compares it with RHS for
1245 /// the validity of the greater-or-equal relationship.
1247 /// \returns true if *this >= RHS when considered unsigned.
1248 bool uge(uint64_t RHS) const { return !ult(RHS); }
1250 /// \brief Signed greather or equal comparison
1252 /// Regards both *this and RHS as signed quantities and compares them for
1253 /// validity of the greater-or-equal relationship.
1255 /// \returns true if *this >= RHS when both are considered signed.
1256 bool sge(const APInt &RHS) const { return !slt(RHS); }
1258 /// \brief Signed greater or equal comparison
1260 /// Regards both *this as a signed quantity and compares it with RHS for
1261 /// the validity of the greater-or-equal relationship.
1263 /// \returns true if *this >= RHS when considered signed.
1264 bool sge(int64_t RHS) const { return !slt(RHS); }
1266 /// This operation tests if there are any pairs of corresponding bits
1267 /// between this APInt and RHS that are both set.
1268 bool intersects(const APInt &RHS) const {
1269 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1271 return (U.VAL & RHS.U.VAL) != 0;
1272 return intersectsSlowCase(RHS);
1275 /// This operation checks that all bits set in this APInt are also set in RHS.
1276 bool isSubsetOf(const APInt &RHS) const {
1277 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1279 return (U.VAL & ~RHS.U.VAL) == 0;
1280 return isSubsetOfSlowCase(RHS);
1284 /// \name Resizing Operators
1287 /// \brief Truncate to new width.
1289 /// Truncate the APInt to a specified width. It is an error to specify a width
1290 /// that is greater than or equal to the current width.
1291 APInt trunc(unsigned width) const;
1293 /// \brief Sign extend to a new width.
1295 /// This operation sign extends the APInt to a new width. If the high order
1296 /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
1297 /// It is an error to specify a width that is less than or equal to the
1299 APInt sext(unsigned width) const;
1301 /// \brief Zero extend to a new width.
1303 /// This operation zero extends the APInt to a new width. The high order bits
1304 /// are filled with 0 bits. It is an error to specify a width that is less
1305 /// than or equal to the current width.
1306 APInt zext(unsigned width) const;
1308 /// \brief Sign extend or truncate to width
1310 /// Make this APInt have the bit width given by \p width. The value is sign
1311 /// extended, truncated, or left alone to make it that width.
1312 APInt sextOrTrunc(unsigned width) const;
1314 /// \brief Zero extend or truncate to width
1316 /// Make this APInt have the bit width given by \p width. The value is zero
1317 /// extended, truncated, or left alone to make it that width.
1318 APInt zextOrTrunc(unsigned width) const;
1320 /// \brief Sign extend or truncate to width
1322 /// Make this APInt have the bit width given by \p width. The value is sign
1323 /// extended, or left alone to make it that width.
1324 APInt sextOrSelf(unsigned width) const;
1326 /// \brief Zero extend or truncate to width
1328 /// Make this APInt have the bit width given by \p width. The value is zero
1329 /// extended, or left alone to make it that width.
1330 APInt zextOrSelf(unsigned width) const;
1333 /// \name Bit Manipulation Operators
1336 /// \brief Set every bit to 1.
1341 // Set all the bits in all the words.
1342 memset(U.pVal, -1, getNumWords() * APINT_WORD_SIZE);
1343 // Clear the unused ones
1347 /// \brief Set a given bit to 1.
1349 /// Set the given bit to 1 whose position is given as "bitPosition".
1350 void setBit(unsigned BitPosition) {
1351 assert(BitPosition <= BitWidth && "BitPosition out of range");
1352 WordType Mask = maskBit(BitPosition);
1356 U.pVal[whichWord(BitPosition)] |= Mask;
1359 /// Set the sign bit to 1.
1361 setBit(BitWidth - 1);
1364 /// Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
1365 void setBits(unsigned loBit, unsigned hiBit) {
1366 assert(hiBit <= BitWidth && "hiBit out of range");
1367 assert(loBit <= BitWidth && "loBit out of range");
1368 assert(loBit <= hiBit && "loBit greater than hiBit");
1371 if (loBit < APINT_BITS_PER_WORD && hiBit <= APINT_BITS_PER_WORD) {
1372 uint64_t mask = WORD_MAX >> (APINT_BITS_PER_WORD - (hiBit - loBit));
1379 setBitsSlowCase(loBit, hiBit);
1383 /// Set the top bits starting from loBit.
1384 void setBitsFrom(unsigned loBit) {
1385 return setBits(loBit, BitWidth);
1388 /// Set the bottom loBits bits.
1389 void setLowBits(unsigned loBits) {
1390 return setBits(0, loBits);
1393 /// Set the top hiBits bits.
1394 void setHighBits(unsigned hiBits) {
1395 return setBits(BitWidth - hiBits, BitWidth);
1398 /// \brief Set every bit to 0.
1399 void clearAllBits() {
1403 memset(U.pVal, 0, getNumWords() * APINT_WORD_SIZE);
1406 /// \brief Set a given bit to 0.
1408 /// Set the given bit to 0 whose position is given as "bitPosition".
1409 void clearBit(unsigned BitPosition) {
1410 assert(BitPosition <= BitWidth && "BitPosition out of range");
1411 WordType Mask = ~maskBit(BitPosition);
1415 U.pVal[whichWord(BitPosition)] &= Mask;
1418 /// Set the sign bit to 0.
1419 void clearSignBit() {
1420 clearBit(BitWidth - 1);
1423 /// \brief Toggle every bit to its opposite value.
1424 void flipAllBits() {
1425 if (isSingleWord()) {
1429 flipAllBitsSlowCase();
1433 /// \brief Toggles a given bit to its opposite value.
1435 /// Toggle a given bit to its opposite value whose position is given
1436 /// as "bitPosition".
1437 void flipBit(unsigned bitPosition);
1439 /// Insert the bits from a smaller APInt starting at bitPosition.
1440 void insertBits(const APInt &SubBits, unsigned bitPosition);
1442 /// Return an APInt with the extracted bits [bitPosition,bitPosition+numBits).
1443 APInt extractBits(unsigned numBits, unsigned bitPosition) const;
1446 /// \name Value Characterization Functions
1449 /// \brief Return the number of bits in the APInt.
1450 unsigned getBitWidth() const { return BitWidth; }
1452 /// \brief Get the number of words.
1454 /// Here one word's bitwidth equals to that of uint64_t.
1456 /// \returns the number of words to hold the integer value of this APInt.
1457 unsigned getNumWords() const { return getNumWords(BitWidth); }
1459 /// \brief Get the number of words.
1461 /// *NOTE* Here one word's bitwidth equals to that of uint64_t.
1463 /// \returns the number of words to hold the integer value with a given bit
1465 static unsigned getNumWords(unsigned BitWidth) {
1466 return ((uint64_t)BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
1469 /// \brief Compute the number of active bits in the value
1471 /// This function returns the number of active bits which is defined as the
1472 /// bit width minus the number of leading zeros. This is used in several
1473 /// computations to see how "wide" the value is.
1474 unsigned getActiveBits() const { return BitWidth - countLeadingZeros(); }
1476 /// \brief Compute the number of active words in the value of this APInt.
1478 /// This is used in conjunction with getActiveData to extract the raw value of
1480 unsigned getActiveWords() const {
1481 unsigned numActiveBits = getActiveBits();
1482 return numActiveBits ? whichWord(numActiveBits - 1) + 1 : 1;
1485 /// \brief Get the minimum bit size for this signed APInt
1487 /// Computes the minimum bit width for this APInt while considering it to be a
1488 /// signed (and probably negative) value. If the value is not negative, this
1489 /// function returns the same value as getActiveBits()+1. Otherwise, it
1490 /// returns the smallest bit width that will retain the negative value. For
1491 /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
1492 /// for -1, this function will always return 1.
1493 unsigned getMinSignedBits() const {
1495 return BitWidth - countLeadingOnes() + 1;
1496 return getActiveBits() + 1;
1499 /// \brief Get zero extended value
1501 /// This method attempts to return the value of this APInt as a zero extended
1502 /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
1503 /// uint64_t. Otherwise an assertion will result.
1504 uint64_t getZExtValue() const {
1507 assert(getActiveBits() <= 64 && "Too many bits for uint64_t");
1511 /// \brief Get sign extended value
1513 /// This method attempts to return the value of this APInt as a sign extended
1514 /// int64_t. The bit width must be <= 64 or the value must fit within an
1515 /// int64_t. Otherwise an assertion will result.
1516 int64_t getSExtValue() const {
1518 return SignExtend64(U.VAL, BitWidth);
1519 assert(getMinSignedBits() <= 64 && "Too many bits for int64_t");
1520 return int64_t(U.pVal[0]);
1523 /// \brief Get bits required for string value.
1525 /// This method determines how many bits are required to hold the APInt
1526 /// equivalent of the string given by \p str.
1527 static unsigned getBitsNeeded(StringRef str, uint8_t radix);
1529 /// \brief The APInt version of the countLeadingZeros functions in
1532 /// It counts the number of zeros from the most significant bit to the first
1535 /// \returns BitWidth if the value is zero, otherwise returns the number of
1536 /// zeros from the most significant bit to the first one bits.
1537 unsigned countLeadingZeros() const {
1538 if (isSingleWord()) {
1539 unsigned unusedBits = APINT_BITS_PER_WORD - BitWidth;
1540 return llvm::countLeadingZeros(U.VAL) - unusedBits;
1542 return countLeadingZerosSlowCase();
1545 /// \brief Count the number of leading one bits.
1547 /// This function is an APInt version of the countLeadingOnes
1548 /// functions in MathExtras.h. It counts the number of ones from the most
1549 /// significant bit to the first zero bit.
1551 /// \returns 0 if the high order bit is not set, otherwise returns the number
1552 /// of 1 bits from the most significant to the least
1553 unsigned countLeadingOnes() const LLVM_READONLY;
1555 /// Computes the number of leading bits of this APInt that are equal to its
1557 unsigned getNumSignBits() const {
1558 return isNegative() ? countLeadingOnes() : countLeadingZeros();
1561 /// \brief Count the number of trailing zero bits.
1563 /// This function is an APInt version of the countTrailingZeros
1564 /// functions in MathExtras.h. It counts the number of zeros from the least
1565 /// significant bit to the first set bit.
1567 /// \returns BitWidth if the value is zero, otherwise returns the number of
1568 /// zeros from the least significant bit to the first one bit.
1569 unsigned countTrailingZeros() const LLVM_READONLY;
1571 /// \brief Count the number of trailing one bits.
1573 /// This function is an APInt version of the countTrailingOnes
1574 /// functions in MathExtras.h. It counts the number of ones from the least
1575 /// significant bit to the first zero bit.
1577 /// \returns BitWidth if the value is all ones, otherwise returns the number
1578 /// of ones from the least significant bit to the first zero bit.
1579 unsigned countTrailingOnes() const {
1581 return llvm::countTrailingOnes(U.VAL);
1582 return countTrailingOnesSlowCase();
1585 /// \brief Count the number of bits set.
1587 /// This function is an APInt version of the countPopulation functions
1588 /// in MathExtras.h. It counts the number of 1 bits in the APInt value.
1590 /// \returns 0 if the value is zero, otherwise returns the number of set bits.
1591 unsigned countPopulation() const {
1593 return llvm::countPopulation(U.VAL);
1594 return countPopulationSlowCase();
1598 /// \name Conversion Functions
1600 void print(raw_ostream &OS, bool isSigned) const;
1602 /// Converts an APInt to a string and append it to Str. Str is commonly a
1604 void toString(SmallVectorImpl<char> &Str, unsigned Radix, bool Signed,
1605 bool formatAsCLiteral = false) const;
1607 /// Considers the APInt to be unsigned and converts it into a string in the
1608 /// radix given. The radix can be 2, 8, 10 16, or 36.
1609 void toStringUnsigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1610 toString(Str, Radix, false, false);
1613 /// Considers the APInt to be signed and converts it into a string in the
1614 /// radix given. The radix can be 2, 8, 10, 16, or 36.
1615 void toStringSigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1616 toString(Str, Radix, true, false);
1619 /// \brief Return the APInt as a std::string.
1621 /// Note that this is an inefficient method. It is better to pass in a
1622 /// SmallVector/SmallString to the methods above to avoid thrashing the heap
1624 std::string toString(unsigned Radix, bool Signed) const;
1626 /// \returns a byte-swapped representation of this APInt Value.
1627 APInt byteSwap() const;
1629 /// \returns the value with the bit representation reversed of this APInt
1631 APInt reverseBits() const;
1633 /// \brief Converts this APInt to a double value.
1634 double roundToDouble(bool isSigned) const;
1636 /// \brief Converts this unsigned APInt to a double value.
1637 double roundToDouble() const { return roundToDouble(false); }
1639 /// \brief Converts this signed APInt to a double value.
1640 double signedRoundToDouble() const { return roundToDouble(true); }
1642 /// \brief Converts APInt bits to a double
1644 /// The conversion does not do a translation from integer to double, it just
1645 /// re-interprets the bits as a double. Note that it is valid to do this on
1646 /// any bit width. Exactly 64 bits will be translated.
1647 double bitsToDouble() const {
1652 T.I = (isSingleWord() ? U.VAL : U.pVal[0]);
1656 /// \brief Converts APInt bits to a double
1658 /// The conversion does not do a translation from integer to float, it just
1659 /// re-interprets the bits as a float. Note that it is valid to do this on
1660 /// any bit width. Exactly 32 bits will be translated.
1661 float bitsToFloat() const {
1666 T.I = unsigned((isSingleWord() ? U.VAL : U.pVal[0]));
1670 /// \brief Converts a double to APInt bits.
1672 /// The conversion does not do a translation from double to integer, it just
1673 /// re-interprets the bits of the double.
1674 static APInt doubleToBits(double V) {
1680 return APInt(sizeof T * CHAR_BIT, T.I);
1683 /// \brief Converts a float to APInt bits.
1685 /// The conversion does not do a translation from float to integer, it just
1686 /// re-interprets the bits of the float.
1687 static APInt floatToBits(float V) {
1693 return APInt(sizeof T * CHAR_BIT, T.I);
1697 /// \name Mathematics Operations
1700 /// \returns the floor log base 2 of this APInt.
1701 unsigned logBase2() const { return BitWidth - 1 - countLeadingZeros(); }
1703 /// \returns the ceil log base 2 of this APInt.
1704 unsigned ceilLogBase2() const {
1707 return BitWidth - temp.countLeadingZeros();
1710 /// \returns the nearest log base 2 of this APInt. Ties round up.
1712 /// NOTE: When we have a BitWidth of 1, we define:
1714 /// log2(0) = UINT32_MAX
1717 /// to get around any mathematical concerns resulting from
1718 /// referencing 2 in a space where 2 does no exist.
1719 unsigned nearestLogBase2() const {
1720 // Special case when we have a bitwidth of 1. If VAL is 1, then we
1721 // get 0. If VAL is 0, we get WORD_MAX which gets truncated to
1726 // Handle the zero case.
1730 // The non-zero case is handled by computing:
1732 // nearestLogBase2(x) = logBase2(x) + x[logBase2(x)-1].
1734 // where x[i] is referring to the value of the ith bit of x.
1735 unsigned lg = logBase2();
1736 return lg + unsigned((*this)[lg - 1]);
1739 /// \returns the log base 2 of this APInt if its an exact power of two, -1
1741 int32_t exactLogBase2() const {
1747 /// \brief Compute the square root
1750 /// \brief Get the absolute value;
1752 /// If *this is < 0 then return -(*this), otherwise *this;
1759 /// \returns the multiplicative inverse for a given modulo.
1760 APInt multiplicativeInverse(const APInt &modulo) const;
1763 /// \name Support for division by constant
1766 /// Calculate the magic number for signed division by a constant.
1770 /// Calculate the magic number for unsigned division by a constant.
1772 mu magicu(unsigned LeadingZeros = 0) const;
1775 /// \name Building-block Operations for APInt and APFloat
1778 // These building block operations operate on a representation of arbitrary
1779 // precision, two's-complement, bignum integer values. They should be
1780 // sufficient to implement APInt and APFloat bignum requirements. Inputs are
1781 // generally a pointer to the base of an array of integer parts, representing
1782 // an unsigned bignum, and a count of how many parts there are.
1784 /// Sets the least significant part of a bignum to the input value, and zeroes
1785 /// out higher parts.
1786 static void tcSet(WordType *, WordType, unsigned);
1788 /// Assign one bignum to another.
1789 static void tcAssign(WordType *, const WordType *, unsigned);
1791 /// Returns true if a bignum is zero, false otherwise.
1792 static bool tcIsZero(const WordType *, unsigned);
1794 /// Extract the given bit of a bignum; returns 0 or 1. Zero-based.
1795 static int tcExtractBit(const WordType *, unsigned bit);
1797 /// Copy the bit vector of width srcBITS from SRC, starting at bit srcLSB, to
1798 /// DST, of dstCOUNT parts, such that the bit srcLSB becomes the least
1799 /// significant bit of DST. All high bits above srcBITS in DST are
1801 static void tcExtract(WordType *, unsigned dstCount,
1802 const WordType *, unsigned srcBits,
1805 /// Set the given bit of a bignum. Zero-based.
1806 static void tcSetBit(WordType *, unsigned bit);
1808 /// Clear the given bit of a bignum. Zero-based.
1809 static void tcClearBit(WordType *, unsigned bit);
1811 /// Returns the bit number of the least or most significant set bit of a
1812 /// number. If the input number has no bits set -1U is returned.
1813 static unsigned tcLSB(const WordType *, unsigned n);
1814 static unsigned tcMSB(const WordType *parts, unsigned n);
1816 /// Negate a bignum in-place.
1817 static void tcNegate(WordType *, unsigned);
1819 /// DST += RHS + CARRY where CARRY is zero or one. Returns the carry flag.
1820 static WordType tcAdd(WordType *, const WordType *,
1821 WordType carry, unsigned);
1822 /// DST += RHS. Returns the carry flag.
1823 static WordType tcAddPart(WordType *, WordType, unsigned);
1825 /// DST -= RHS + CARRY where CARRY is zero or one. Returns the carry flag.
1826 static WordType tcSubtract(WordType *, const WordType *,
1827 WordType carry, unsigned);
1828 /// DST -= RHS. Returns the carry flag.
1829 static WordType tcSubtractPart(WordType *, WordType, unsigned);
1831 /// DST += SRC * MULTIPLIER + PART if add is true
1832 /// DST = SRC * MULTIPLIER + PART if add is false
1834 /// Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC they must
1835 /// start at the same point, i.e. DST == SRC.
1837 /// If DSTPARTS == SRC_PARTS + 1 no overflow occurs and zero is returned.
1838 /// Otherwise DST is filled with the least significant DSTPARTS parts of the
1839 /// result, and if all of the omitted higher parts were zero return zero,
1840 /// otherwise overflow occurred and return one.
1841 static int tcMultiplyPart(WordType *dst, const WordType *src,
1842 WordType multiplier, WordType carry,
1843 unsigned srcParts, unsigned dstParts,
1846 /// DST = LHS * RHS, where DST has the same width as the operands and is
1847 /// filled with the least significant parts of the result. Returns one if
1848 /// overflow occurred, otherwise zero. DST must be disjoint from both
1850 static int tcMultiply(WordType *, const WordType *, const WordType *,
1853 /// DST = LHS * RHS, where DST has width the sum of the widths of the
1854 /// operands. No overflow occurs. DST must be disjoint from both
1855 /// operands. Returns the number of parts required to hold the result.
1856 static unsigned tcFullMultiply(WordType *, const WordType *,
1857 const WordType *, unsigned, unsigned);
1859 /// If RHS is zero LHS and REMAINDER are left unchanged, return one.
1860 /// Otherwise set LHS to LHS / RHS with the fractional part discarded, set
1861 /// REMAINDER to the remainder, return zero. i.e.
1863 /// OLD_LHS = RHS * LHS + REMAINDER
1865 /// SCRATCH is a bignum of the same size as the operands and result for use by
1866 /// the routine; its contents need not be initialized and are destroyed. LHS,
1867 /// REMAINDER and SCRATCH must be distinct.
1868 static int tcDivide(WordType *lhs, const WordType *rhs,
1869 WordType *remainder, WordType *scratch,
1872 /// Shift a bignum left Count bits. Shifted in bits are zero. There are no
1873 /// restrictions on Count.
1874 static void tcShiftLeft(WordType *, unsigned Words, unsigned Count);
1876 /// Shift a bignum right Count bits. Shifted in bits are zero. There are no
1877 /// restrictions on Count.
1878 static void tcShiftRight(WordType *, unsigned Words, unsigned Count);
1880 /// The obvious AND, OR and XOR and complement operations.
1881 static void tcAnd(WordType *, const WordType *, unsigned);
1882 static void tcOr(WordType *, const WordType *, unsigned);
1883 static void tcXor(WordType *, const WordType *, unsigned);
1884 static void tcComplement(WordType *, unsigned);
1886 /// Comparison (unsigned) of two bignums.
1887 static int tcCompare(const WordType *, const WordType *, unsigned);
1889 /// Increment a bignum in-place. Return the carry flag.
1890 static WordType tcIncrement(WordType *dst, unsigned parts) {
1891 return tcAddPart(dst, 1, parts);
1894 /// Decrement a bignum in-place. Return the borrow flag.
1895 static WordType tcDecrement(WordType *dst, unsigned parts) {
1896 return tcSubtractPart(dst, 1, parts);
1899 /// Set the least significant BITS and clear the rest.
1900 static void tcSetLeastSignificantBits(WordType *, unsigned, unsigned bits);
1902 /// \brief debug method
1908 /// Magic data for optimising signed division by a constant.
1910 APInt m; ///< magic number
1911 unsigned s; ///< shift amount
1914 /// Magic data for optimising unsigned division by a constant.
1916 APInt m; ///< magic number
1917 bool a; ///< add indicator
1918 unsigned s; ///< shift amount
1921 inline bool operator==(uint64_t V1, const APInt &V2) { return V2 == V1; }
1923 inline bool operator!=(uint64_t V1, const APInt &V2) { return V2 != V1; }
1925 /// \brief Unary bitwise complement operator.
1927 /// \returns an APInt that is the bitwise complement of \p v.
1928 inline APInt operator~(APInt v) {
1933 inline APInt operator&(APInt a, const APInt &b) {
1938 inline APInt operator&(const APInt &a, APInt &&b) {
1940 return std::move(b);
1943 inline APInt operator&(APInt a, uint64_t RHS) {
1948 inline APInt operator&(uint64_t LHS, APInt b) {
1953 inline APInt operator|(APInt a, const APInt &b) {
1958 inline APInt operator|(const APInt &a, APInt &&b) {
1960 return std::move(b);
1963 inline APInt operator|(APInt a, uint64_t RHS) {
1968 inline APInt operator|(uint64_t LHS, APInt b) {
1973 inline APInt operator^(APInt a, const APInt &b) {
1978 inline APInt operator^(const APInt &a, APInt &&b) {
1980 return std::move(b);
1983 inline APInt operator^(APInt a, uint64_t RHS) {
1988 inline APInt operator^(uint64_t LHS, APInt b) {
1993 inline raw_ostream &operator<<(raw_ostream &OS, const APInt &I) {
1998 inline APInt operator-(APInt v) {
2004 inline APInt operator+(APInt a, const APInt &b) {
2009 inline APInt operator+(const APInt &a, APInt &&b) {
2011 return std::move(b);
2014 inline APInt operator+(APInt a, uint64_t RHS) {
2019 inline APInt operator+(uint64_t LHS, APInt b) {
2024 inline APInt operator-(APInt a, const APInt &b) {
2029 inline APInt operator-(const APInt &a, APInt &&b) {
2032 return std::move(b);
2035 inline APInt operator-(APInt a, uint64_t RHS) {
2040 inline APInt operator-(uint64_t LHS, APInt b) {
2047 namespace APIntOps {
2049 /// \brief Determine the smaller of two APInts considered to be signed.
2050 inline const APInt &smin(const APInt &A, const APInt &B) {
2051 return A.slt(B) ? A : B;
2054 /// \brief Determine the larger of two APInts considered to be signed.
2055 inline const APInt &smax(const APInt &A, const APInt &B) {
2056 return A.sgt(B) ? A : B;
2059 /// \brief Determine the smaller of two APInts considered to be signed.
2060 inline const APInt &umin(const APInt &A, const APInt &B) {
2061 return A.ult(B) ? A : B;
2064 /// \brief Determine the larger of two APInts considered to be unsigned.
2065 inline const APInt &umax(const APInt &A, const APInt &B) {
2066 return A.ugt(B) ? A : B;
2069 /// \brief Compute GCD of two unsigned APInt values.
2071 /// This function returns the greatest common divisor of the two APInt values
2072 /// using Stein's algorithm.
2074 /// \returns the greatest common divisor of A and B.
2075 APInt GreatestCommonDivisor(APInt A, APInt B);
2077 /// \brief Converts the given APInt to a double value.
2079 /// Treats the APInt as an unsigned value for conversion purposes.
2080 inline double RoundAPIntToDouble(const APInt &APIVal) {
2081 return APIVal.roundToDouble();
2084 /// \brief Converts the given APInt to a double value.
2086 /// Treats the APInt as a signed value for conversion purposes.
2087 inline double RoundSignedAPIntToDouble(const APInt &APIVal) {
2088 return APIVal.signedRoundToDouble();
2091 /// \brief Converts the given APInt to a float vlalue.
2092 inline float RoundAPIntToFloat(const APInt &APIVal) {
2093 return float(RoundAPIntToDouble(APIVal));
2096 /// \brief Converts the given APInt to a float value.
2098 /// Treast the APInt as a signed value for conversion purposes.
2099 inline float RoundSignedAPIntToFloat(const APInt &APIVal) {
2100 return float(APIVal.signedRoundToDouble());
2103 /// \brief Converts the given double value into a APInt.
2105 /// This function convert a double value to an APInt value.
2106 APInt RoundDoubleToAPInt(double Double, unsigned width);
2108 /// \brief Converts a float value into a APInt.
2110 /// Converts a float value into an APInt value.
2111 inline APInt RoundFloatToAPInt(float Float, unsigned width) {
2112 return RoundDoubleToAPInt(double(Float), width);
2115 } // End of APIntOps namespace
2117 // See friend declaration above. This additional declaration is required in
2118 // order to compile LLVM with IBM xlC compiler.
2119 hash_code hash_value(const APInt &Arg);
2120 } // End of llvm namespace