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
82 /// This union is used to store the integer value. When the
83 /// integer bit-width <= 64, it uses VAL, otherwise it uses pVal.
85 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
86 uint64_t *pVal; ///< Used to store the >64 bits integer value.
89 unsigned BitWidth; ///< The number of bits in this APInt.
91 friend struct DenseMapAPIntKeyInfo;
93 /// \brief Fast internal constructor
95 /// This constructor is used only internally for speed of construction of
96 /// temporaries. It is unsafe for general use so it is not public.
97 APInt(uint64_t *val, unsigned bits) : pVal(val), BitWidth(bits) {}
99 /// \brief Determine if this APInt just has one word to store value.
101 /// \returns true if the number of bits <= 64, false otherwise.
102 bool isSingleWord() const { return BitWidth <= APINT_BITS_PER_WORD; }
104 /// \brief Determine which word a bit is in.
106 /// \returns the word position for the specified bit position.
107 static unsigned whichWord(unsigned bitPosition) {
108 return bitPosition / APINT_BITS_PER_WORD;
111 /// \brief Determine which bit in a word a bit is in.
113 /// \returns the bit position in a word for the specified bit position
115 static unsigned whichBit(unsigned bitPosition) {
116 return bitPosition % APINT_BITS_PER_WORD;
119 /// \brief Get a single bit mask.
121 /// \returns a uint64_t with only bit at "whichBit(bitPosition)" set
122 /// This method generates and returns a uint64_t (word) mask for a single
123 /// bit at a specific bit position. This is used to mask the bit in the
124 /// corresponding word.
125 static uint64_t maskBit(unsigned bitPosition) {
126 return 1ULL << whichBit(bitPosition);
129 /// \brief Clear unused high order bits
131 /// This method is used internally to clear the top "N" bits in the high order
132 /// word that are not used by the APInt. This is needed after the most
133 /// significant word is assigned a value to ensure that those bits are
135 APInt &clearUnusedBits() {
136 // Compute how many bits are used in the final word
137 unsigned wordBits = BitWidth % APINT_BITS_PER_WORD;
139 // If all bits are used, we want to leave the value alone. This also
140 // avoids the undefined behavior of >> when the shift is the same size as
141 // the word size (64).
144 // Mask out the high bits.
145 uint64_t mask = UINT64_MAX >> (APINT_BITS_PER_WORD - wordBits);
149 pVal[getNumWords() - 1] &= mask;
153 /// \brief Get the word corresponding to a bit position
154 /// \returns the corresponding word for the specified bit position.
155 uint64_t getWord(unsigned bitPosition) const {
156 return isSingleWord() ? VAL : pVal[whichWord(bitPosition)];
159 /// \brief Convert a char array into an APInt
161 /// \param radix 2, 8, 10, 16, or 36
162 /// Converts a string into a number. The string must be non-empty
163 /// and well-formed as a number of the given base. The bit-width
164 /// must be sufficient to hold the result.
166 /// This is used by the constructors that take string arguments.
168 /// StringRef::getAsInteger is superficially similar but (1) does
169 /// not assume that the string is well-formed and (2) grows the
170 /// result to hold the input.
171 void fromString(unsigned numBits, StringRef str, uint8_t radix);
173 /// \brief An internal division function for dividing APInts.
175 /// This is used by the toString method to divide by the radix. It simply
176 /// provides a more convenient form of divide for internal use since KnuthDiv
177 /// has specific constraints on its inputs. If those constraints are not met
178 /// then it provides a simpler form of divide.
179 static void divide(const APInt &LHS, unsigned lhsWords, const APInt &RHS,
180 unsigned rhsWords, APInt *Quotient, APInt *Remainder);
182 /// out-of-line slow case for inline constructor
183 void initSlowCase(uint64_t val, bool isSigned);
185 /// shared code between two array constructors
186 void initFromArray(ArrayRef<uint64_t> array);
188 /// out-of-line slow case for inline copy constructor
189 void initSlowCase(const APInt &that);
191 /// out-of-line slow case for shl
192 void shlSlowCase(unsigned ShiftAmt);
194 /// out-of-line slow case for lshr.
195 void lshrSlowCase(unsigned ShiftAmt);
197 /// out-of-line slow case for operator=
198 void AssignSlowCase(const APInt &RHS);
200 /// out-of-line slow case for operator==
201 bool EqualSlowCase(const APInt &RHS) const LLVM_READONLY;
203 /// out-of-line slow case for countLeadingZeros
204 unsigned countLeadingZerosSlowCase() const LLVM_READONLY;
206 /// out-of-line slow case for countTrailingOnes
207 unsigned countTrailingOnesSlowCase() const LLVM_READONLY;
209 /// out-of-line slow case for countPopulation
210 unsigned countPopulationSlowCase() const LLVM_READONLY;
212 /// out-of-line slow case for intersects.
213 bool intersectsSlowCase(const APInt &RHS) const LLVM_READONLY;
215 /// out-of-line slow case for isSubsetOf.
216 bool isSubsetOfSlowCase(const APInt &RHS) const LLVM_READONLY;
218 /// out-of-line slow case for setBits.
219 void setBitsSlowCase(unsigned loBit, unsigned hiBit);
221 /// out-of-line slow case for flipAllBits.
222 void flipAllBitsSlowCase();
224 /// out-of-line slow case for operator&=.
225 void AndAssignSlowCase(const APInt& RHS);
227 /// out-of-line slow case for operator|=.
228 void OrAssignSlowCase(const APInt& RHS);
230 /// out-of-line slow case for operator^=.
231 void XorAssignSlowCase(const APInt& RHS);
234 /// \name Constructors
237 /// \brief Create a new APInt of numBits width, initialized as val.
239 /// If isSigned is true then val is treated as if it were a signed value
240 /// (i.e. as an int64_t) and the appropriate sign extension to the bit width
241 /// will be done. Otherwise, no sign extension occurs (high order bits beyond
242 /// the range of val are zero filled).
244 /// \param numBits the bit width of the constructed APInt
245 /// \param val the initial value of the APInt
246 /// \param isSigned how to treat signedness of val
247 APInt(unsigned numBits, uint64_t val, bool isSigned = false)
248 : BitWidth(numBits) {
249 assert(BitWidth && "bitwidth too small");
250 if (isSingleWord()) {
254 initSlowCase(val, isSigned);
258 /// \brief Construct an APInt of numBits width, initialized as bigVal[].
260 /// Note that bigVal.size() can be smaller or larger than the corresponding
261 /// bit width but any extraneous bits will be dropped.
263 /// \param numBits the bit width of the constructed APInt
264 /// \param bigVal a sequence of words to form the initial value of the APInt
265 APInt(unsigned numBits, ArrayRef<uint64_t> bigVal);
267 /// Equivalent to APInt(numBits, ArrayRef<uint64_t>(bigVal, numWords)), but
268 /// deprecated because this constructor is prone to ambiguity with the
269 /// APInt(unsigned, uint64_t, bool) constructor.
271 /// If this overload is ever deleted, care should be taken to prevent calls
272 /// from being incorrectly captured by the APInt(unsigned, uint64_t, bool)
274 APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[]);
276 /// \brief Construct an APInt from a string representation.
278 /// This constructor interprets the string \p str in the given radix. The
279 /// interpretation stops when the first character that is not suitable for the
280 /// radix is encountered, or the end of the string. Acceptable radix values
281 /// are 2, 8, 10, 16, and 36. It is an error for the value implied by the
282 /// string to require more bits than numBits.
284 /// \param numBits the bit width of the constructed APInt
285 /// \param str the string to be interpreted
286 /// \param radix the radix to use for the conversion
287 APInt(unsigned numBits, StringRef str, uint8_t radix);
289 /// Simply makes *this a copy of that.
290 /// @brief Copy Constructor.
291 APInt(const APInt &that) : BitWidth(that.BitWidth) {
298 /// \brief Move Constructor.
299 APInt(APInt &&that) : VAL(that.VAL), BitWidth(that.BitWidth) {
303 /// \brief Destructor.
309 /// \brief Default constructor that creates an uninteresting APInt
310 /// representing a 1-bit zero value.
312 /// This is useful for object deserialization (pair this with the static
314 explicit APInt() : VAL(0), BitWidth(1) {}
316 /// \brief Returns whether this instance allocated memory.
317 bool needsCleanup() const { return !isSingleWord(); }
319 /// Used to insert APInt objects, or objects that contain APInt objects, into
321 void Profile(FoldingSetNodeID &id) const;
324 /// \name Value Tests
327 /// \brief Determine sign of this APInt.
329 /// This tests the high bit of this APInt to determine if it is set.
331 /// \returns true if this APInt is negative, false otherwise
332 bool isNegative() const { return (*this)[BitWidth - 1]; }
334 /// \brief Determine if this APInt Value is non-negative (>= 0)
336 /// This tests the high bit of the APInt to determine if it is unset.
337 bool isNonNegative() const { return !isNegative(); }
339 /// \brief Determine if sign bit of this APInt is set.
341 /// This tests the high bit of this APInt to determine if it is set.
343 /// \returns true if this APInt has its sign bit set, false otherwise.
344 bool isSignBitSet() const { return (*this)[BitWidth-1]; }
346 /// \brief Determine if sign bit of this APInt is clear.
348 /// This tests the high bit of this APInt to determine if it is clear.
350 /// \returns true if this APInt has its sign bit clear, false otherwise.
351 bool isSignBitClear() const { return !isSignBitSet(); }
353 /// \brief Determine if this APInt Value is positive.
355 /// This tests if the value of this APInt is positive (> 0). Note
356 /// that 0 is not a positive value.
358 /// \returns true if this APInt is positive.
359 bool isStrictlyPositive() const { return isNonNegative() && !!*this; }
361 /// \brief Determine if all bits are set
363 /// This checks to see if the value has all bits of the APInt are set or not.
364 bool isAllOnesValue() const {
366 return VAL == UINT64_MAX >> (APINT_BITS_PER_WORD - BitWidth);
367 return countPopulationSlowCase() == BitWidth;
370 /// \brief Determine if this is the largest unsigned value.
372 /// This checks to see if the value of this APInt is the maximum unsigned
373 /// value for the APInt's bit width.
374 bool isMaxValue() const { return isAllOnesValue(); }
376 /// \brief Determine if this is the largest signed value.
378 /// This checks to see if the value of this APInt is the maximum signed
379 /// value for the APInt's bit width.
380 bool isMaxSignedValue() const {
381 return !isNegative() && countPopulation() == BitWidth - 1;
384 /// \brief Determine if this is the smallest unsigned value.
386 /// This checks to see if the value of this APInt is the minimum unsigned
387 /// value for the APInt's bit width.
388 bool isMinValue() const { return !*this; }
390 /// \brief Determine if this is the smallest signed value.
392 /// This checks to see if the value of this APInt is the minimum signed
393 /// value for the APInt's bit width.
394 bool isMinSignedValue() const {
395 return isNegative() && isPowerOf2();
398 /// \brief Check if this APInt has an N-bits unsigned integer value.
399 bool isIntN(unsigned N) const {
400 assert(N && "N == 0 ???");
401 return getActiveBits() <= N;
404 /// \brief Check if this APInt has an N-bits signed integer value.
405 bool isSignedIntN(unsigned N) const {
406 assert(N && "N == 0 ???");
407 return getMinSignedBits() <= N;
410 /// \brief Check if this APInt's value is a power of two greater than zero.
412 /// \returns true if the argument APInt value is a power of two > 0.
413 bool isPowerOf2() const {
415 return isPowerOf2_64(VAL);
416 return countPopulationSlowCase() == 1;
419 /// \brief Check if the APInt's value is returned by getSignMask.
421 /// \returns true if this is the value returned by getSignMask.
422 bool isSignMask() const { return isMinSignedValue(); }
424 /// \brief Convert APInt to a boolean value.
426 /// This converts the APInt to a boolean value as a test against zero.
427 bool getBoolValue() const { return !!*this; }
429 /// If this value is smaller than the specified limit, return it, otherwise
430 /// return the limit value. This causes the value to saturate to the limit.
431 uint64_t getLimitedValue(uint64_t Limit = UINT64_MAX) const {
432 return ugt(Limit) ? Limit : getZExtValue();
435 /// \brief Check if the APInt consists of a repeated bit pattern.
437 /// e.g. 0x01010101 satisfies isSplat(8).
438 /// \param SplatSizeInBits The size of the pattern in bits. Must divide bit
439 /// width without remainder.
440 bool isSplat(unsigned SplatSizeInBits) const;
442 /// \returns true if this APInt value is a sequence of \param numBits ones
443 /// starting at the least significant bit with the remainder zero.
444 bool isMask(unsigned numBits) const {
445 assert(numBits != 0 && "numBits must be non-zero");
446 assert(numBits <= BitWidth && "numBits out of range");
448 return VAL == (UINT64_MAX >> (APINT_BITS_PER_WORD - numBits));
449 unsigned Ones = countTrailingOnesSlowCase();
450 return (numBits == Ones) &&
451 ((Ones + countLeadingZerosSlowCase()) == BitWidth);
454 /// \returns true if this APInt is a non-empty sequence of ones starting at
455 /// the least significant bit with the remainder zero.
456 /// Ex. isMask(0x0000FFFFU) == true.
457 bool isMask() const {
459 return isMask_64(VAL);
460 unsigned Ones = countTrailingOnesSlowCase();
461 return (Ones > 0) && ((Ones + countLeadingZerosSlowCase()) == BitWidth);
464 /// \brief Return true if this APInt value contains a sequence of ones with
465 /// the remainder zero.
466 bool isShiftedMask() const {
468 return isShiftedMask_64(VAL);
469 unsigned Ones = countPopulationSlowCase();
470 unsigned LeadZ = countLeadingZerosSlowCase();
471 return (Ones + LeadZ + countTrailingZeros()) == BitWidth;
475 /// \name Value Generators
478 /// \brief Gets maximum unsigned value of APInt for specific bit width.
479 static APInt getMaxValue(unsigned numBits) {
480 return getAllOnesValue(numBits);
483 /// \brief Gets maximum signed value of APInt for a specific bit width.
484 static APInt getSignedMaxValue(unsigned numBits) {
485 APInt API = getAllOnesValue(numBits);
486 API.clearBit(numBits - 1);
490 /// \brief Gets minimum unsigned value of APInt for a specific bit width.
491 static APInt getMinValue(unsigned numBits) { return APInt(numBits, 0); }
493 /// \brief Gets minimum signed value of APInt for a specific bit width.
494 static APInt getSignedMinValue(unsigned numBits) {
495 APInt API(numBits, 0);
496 API.setBit(numBits - 1);
500 /// \brief Get the SignMask for a specific bit width.
502 /// This is just a wrapper function of getSignedMinValue(), and it helps code
503 /// readability when we want to get a SignMask.
504 static APInt getSignMask(unsigned BitWidth) {
505 return getSignedMinValue(BitWidth);
508 /// \brief Get the all-ones value.
510 /// \returns the all-ones value for an APInt of the specified bit-width.
511 static APInt getAllOnesValue(unsigned numBits) {
512 return APInt(numBits, UINT64_MAX, true);
515 /// \brief Get the '0' value.
517 /// \returns the '0' value for an APInt of the specified bit-width.
518 static APInt getNullValue(unsigned numBits) { return APInt(numBits, 0); }
520 /// \brief Compute an APInt containing numBits highbits from this APInt.
522 /// Get an APInt with the same BitWidth as this APInt, just zero mask
523 /// the low bits and right shift to the least significant bit.
525 /// \returns the high "numBits" bits of this APInt.
526 APInt getHiBits(unsigned numBits) const;
528 /// \brief Compute an APInt containing numBits lowbits from this APInt.
530 /// Get an APInt with the same BitWidth as this APInt, just zero mask
533 /// \returns the low "numBits" bits of this APInt.
534 APInt getLoBits(unsigned numBits) const;
536 /// \brief Return an APInt with exactly one bit set in the result.
537 static APInt getOneBitSet(unsigned numBits, unsigned BitNo) {
538 APInt Res(numBits, 0);
543 /// \brief Get a value with a block of bits set.
545 /// Constructs an APInt value that has a contiguous range of bits set. The
546 /// bits from loBit (inclusive) to hiBit (exclusive) will be set. All other
547 /// bits will be zero. For example, with parameters(32, 0, 16) you would get
548 /// 0x0000FFFF. If hiBit is less than loBit then the set bits "wrap". For
549 /// example, with parameters (32, 28, 4), you would get 0xF000000F.
551 /// \param numBits the intended bit width of the result
552 /// \param loBit the index of the lowest bit set.
553 /// \param hiBit the index of the highest bit set.
555 /// \returns An APInt value with the requested bits set.
556 static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit) {
557 APInt Res(numBits, 0);
558 Res.setBits(loBit, hiBit);
562 /// \brief Get a value with upper bits starting at loBit set.
564 /// Constructs an APInt value that has a contiguous range of bits set. The
565 /// bits from loBit (inclusive) to numBits (exclusive) will be set. All other
566 /// bits will be zero. For example, with parameters(32, 12) you would get
569 /// \param numBits the intended bit width of the result
570 /// \param loBit the index of the lowest bit to set.
572 /// \returns An APInt value with the requested bits set.
573 static APInt getBitsSetFrom(unsigned numBits, unsigned loBit) {
574 APInt Res(numBits, 0);
575 Res.setBitsFrom(loBit);
579 /// \brief Get a value with high bits set
581 /// Constructs an APInt value that has the top hiBitsSet bits set.
583 /// \param numBits the bitwidth of the result
584 /// \param hiBitsSet the number of high-order bits set in the result.
585 static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet) {
586 APInt Res(numBits, 0);
587 Res.setHighBits(hiBitsSet);
591 /// \brief Get a value with low bits set
593 /// Constructs an APInt value that has the bottom loBitsSet bits set.
595 /// \param numBits the bitwidth of the result
596 /// \param loBitsSet the number of low-order bits set in the result.
597 static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet) {
598 APInt Res(numBits, 0);
599 Res.setLowBits(loBitsSet);
603 /// \brief Return a value containing V broadcasted over NewLen bits.
604 static APInt getSplat(unsigned NewLen, const APInt &V) {
605 assert(NewLen >= V.getBitWidth() && "Can't splat to smaller bit width!");
607 APInt Val = V.zextOrSelf(NewLen);
608 for (unsigned I = V.getBitWidth(); I < NewLen; I <<= 1)
614 /// \brief Determine if two APInts have the same value, after zero-extending
615 /// one of them (if needed!) to ensure that the bit-widths match.
616 static bool isSameValue(const APInt &I1, const APInt &I2) {
617 if (I1.getBitWidth() == I2.getBitWidth())
620 if (I1.getBitWidth() > I2.getBitWidth())
621 return I1 == I2.zext(I1.getBitWidth());
623 return I1.zext(I2.getBitWidth()) == I2;
626 /// \brief Overload to compute a hash_code for an APInt value.
627 friend hash_code hash_value(const APInt &Arg);
629 /// This function returns a pointer to the internal storage of the APInt.
630 /// This is useful for writing out the APInt in binary form without any
632 const uint64_t *getRawData() const {
639 /// \name Unary Operators
642 /// \brief Postfix increment operator.
644 /// Increments *this by 1.
646 /// \returns a new APInt value representing the original value of *this.
647 const APInt operator++(int) {
653 /// \brief Prefix increment operator.
655 /// \returns *this incremented by one
658 /// \brief Postfix decrement operator.
660 /// Decrements *this by 1.
662 /// \returns a new APInt value representing the original value of *this.
663 const APInt operator--(int) {
669 /// \brief Prefix decrement operator.
671 /// \returns *this decremented by one.
674 /// \brief Logical negation operator.
676 /// Performs logical negation operation on this APInt.
678 /// \returns true if *this is zero, false otherwise.
679 bool operator!() const {
684 /// \name Assignment Operators
687 /// \brief Copy assignment operator.
689 /// \returns *this after assignment of RHS.
690 APInt &operator=(const APInt &RHS) {
691 // If the bitwidths are the same, we can avoid mucking with memory
692 if (isSingleWord() && RHS.isSingleWord()) {
694 BitWidth = RHS.BitWidth;
695 return clearUnusedBits();
702 /// @brief Move assignment operator.
703 APInt &operator=(APInt &&that) {
704 assert(this != &that && "Self-move not supported");
708 // Use memcpy so that type based alias analysis sees both VAL and pVal
710 memcpy(&VAL, &that.VAL, sizeof(uint64_t));
712 BitWidth = that.BitWidth;
718 /// \brief Assignment operator.
720 /// The RHS value is assigned to *this. If the significant bits in RHS exceed
721 /// the bit width, the excess bits are truncated. If the bit width is larger
722 /// than 64, the value is zero filled in the unspecified high order bits.
724 /// \returns *this after assignment of RHS value.
725 APInt &operator=(uint64_t RHS) {
726 if (isSingleWord()) {
731 memset(pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
736 /// \brief Bitwise AND assignment operator.
738 /// Performs a bitwise AND operation on this APInt and RHS. The result is
739 /// assigned to *this.
741 /// \returns *this after ANDing with RHS.
742 APInt &operator&=(const APInt &RHS) {
743 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
747 AndAssignSlowCase(RHS);
751 /// \brief Bitwise AND assignment operator.
753 /// Performs a bitwise AND operation on this APInt and RHS. RHS is
754 /// logically zero-extended or truncated to match the bit-width of
756 APInt &operator&=(uint64_t RHS) {
757 if (isSingleWord()) {
762 memset(pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
766 /// \brief Bitwise OR assignment operator.
768 /// Performs a bitwise OR operation on this APInt and RHS. The result is
771 /// \returns *this after ORing with RHS.
772 APInt &operator|=(const APInt &RHS) {
773 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
777 OrAssignSlowCase(RHS);
781 /// \brief Bitwise OR assignment operator.
783 /// Performs a bitwise OR operation on this APInt and RHS. RHS is
784 /// logically zero-extended or truncated to match the bit-width of
786 APInt &operator|=(uint64_t RHS) {
787 if (isSingleWord()) {
796 /// \brief Bitwise XOR assignment operator.
798 /// Performs a bitwise XOR operation on this APInt and RHS. The result is
799 /// assigned to *this.
801 /// \returns *this after XORing with RHS.
802 APInt &operator^=(const APInt &RHS) {
803 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
807 XorAssignSlowCase(RHS);
811 /// \brief Bitwise XOR assignment operator.
813 /// Performs a bitwise XOR operation on this APInt and RHS. RHS is
814 /// logically zero-extended or truncated to match the bit-width of
816 APInt &operator^=(uint64_t RHS) {
817 if (isSingleWord()) {
826 /// \brief Multiplication assignment operator.
828 /// Multiplies this APInt by RHS and assigns the result to *this.
831 APInt &operator*=(const APInt &RHS);
833 /// \brief Addition assignment operator.
835 /// Adds RHS to *this and assigns the result to *this.
838 APInt &operator+=(const APInt &RHS);
839 APInt &operator+=(uint64_t RHS);
841 /// \brief Subtraction assignment operator.
843 /// Subtracts RHS from *this and assigns the result to *this.
846 APInt &operator-=(const APInt &RHS);
847 APInt &operator-=(uint64_t RHS);
849 /// \brief Left-shift assignment function.
851 /// Shifts *this left by shiftAmt and assigns the result to *this.
853 /// \returns *this after shifting left by ShiftAmt
854 APInt &operator<<=(unsigned ShiftAmt) {
855 assert(ShiftAmt <= BitWidth && "Invalid shift amount");
856 if (isSingleWord()) {
857 if (ShiftAmt == BitWidth)
861 return clearUnusedBits();
863 shlSlowCase(ShiftAmt);
868 /// \name Binary Operators
871 /// \brief Multiplication operator.
873 /// Multiplies this APInt by RHS and returns the result.
874 APInt operator*(const APInt &RHS) const;
876 /// \brief Left logical shift operator.
878 /// Shifts this APInt left by \p Bits and returns the result.
879 APInt operator<<(unsigned Bits) const { return shl(Bits); }
881 /// \brief Left logical shift operator.
883 /// Shifts this APInt left by \p Bits and returns the result.
884 APInt operator<<(const APInt &Bits) const { return shl(Bits); }
886 /// \brief Arithmetic right-shift function.
888 /// Arithmetic right-shift this APInt by shiftAmt.
889 APInt ashr(unsigned shiftAmt) const;
891 /// \brief Logical right-shift function.
893 /// Logical right-shift this APInt by shiftAmt.
894 APInt lshr(unsigned shiftAmt) const {
896 R.lshrInPlace(shiftAmt);
900 /// Logical right-shift this APInt by ShiftAmt in place.
901 void lshrInPlace(unsigned ShiftAmt) {
902 assert(ShiftAmt <= BitWidth && "Invalid shift amount");
903 if (isSingleWord()) {
904 if (ShiftAmt == BitWidth)
910 lshrSlowCase(ShiftAmt);
913 /// \brief Left-shift function.
915 /// Left-shift this APInt by shiftAmt.
916 APInt shl(unsigned shiftAmt) const {
922 /// \brief Rotate left by rotateAmt.
923 APInt rotl(unsigned rotateAmt) const;
925 /// \brief Rotate right by rotateAmt.
926 APInt rotr(unsigned rotateAmt) const;
928 /// \brief Arithmetic right-shift function.
930 /// Arithmetic right-shift this APInt by shiftAmt.
931 APInt ashr(const APInt &shiftAmt) const;
933 /// \brief Logical right-shift function.
935 /// Logical right-shift this APInt by shiftAmt.
936 APInt lshr(const APInt &ShiftAmt) const {
938 R.lshrInPlace(ShiftAmt);
942 /// Logical right-shift this APInt by ShiftAmt in place.
943 void lshrInPlace(const APInt &ShiftAmt);
945 /// \brief Left-shift function.
947 /// Left-shift this APInt by shiftAmt.
948 APInt shl(const APInt &shiftAmt) const;
950 /// \brief Rotate left by rotateAmt.
951 APInt rotl(const APInt &rotateAmt) const;
953 /// \brief Rotate right by rotateAmt.
954 APInt rotr(const APInt &rotateAmt) const;
956 /// \brief Unsigned division operation.
958 /// Perform an unsigned divide operation on this APInt by RHS. Both this and
959 /// RHS are treated as unsigned quantities for purposes of this division.
961 /// \returns a new APInt value containing the division result
962 APInt udiv(const APInt &RHS) const;
964 /// \brief Signed division function for APInt.
966 /// Signed divide this APInt by APInt RHS.
967 APInt sdiv(const APInt &RHS) const;
969 /// \brief Unsigned remainder operation.
971 /// Perform an unsigned remainder operation on this APInt with RHS being the
972 /// divisor. Both this and RHS are treated as unsigned quantities for purposes
973 /// of this operation. Note that this is a true remainder operation and not a
974 /// modulo operation because the sign follows the sign of the dividend which
977 /// \returns a new APInt value containing the remainder result
978 APInt urem(const APInt &RHS) const;
980 /// \brief Function for signed remainder operation.
982 /// Signed remainder operation on APInt.
983 APInt srem(const APInt &RHS) const;
985 /// \brief Dual division/remainder interface.
987 /// Sometimes it is convenient to divide two APInt values and obtain both the
988 /// quotient and remainder. This function does both operations in the same
989 /// computation making it a little more efficient. The pair of input arguments
990 /// may overlap with the pair of output arguments. It is safe to call
991 /// udivrem(X, Y, X, Y), for example.
992 static void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient,
995 static void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient,
998 // Operations that return overflow indicators.
999 APInt sadd_ov(const APInt &RHS, bool &Overflow) const;
1000 APInt uadd_ov(const APInt &RHS, bool &Overflow) const;
1001 APInt ssub_ov(const APInt &RHS, bool &Overflow) const;
1002 APInt usub_ov(const APInt &RHS, bool &Overflow) const;
1003 APInt sdiv_ov(const APInt &RHS, bool &Overflow) const;
1004 APInt smul_ov(const APInt &RHS, bool &Overflow) const;
1005 APInt umul_ov(const APInt &RHS, bool &Overflow) const;
1006 APInt sshl_ov(const APInt &Amt, bool &Overflow) const;
1007 APInt ushl_ov(const APInt &Amt, bool &Overflow) const;
1009 /// \brief Array-indexing support.
1011 /// \returns the bit value at bitPosition
1012 bool operator[](unsigned bitPosition) const {
1013 assert(bitPosition < getBitWidth() && "Bit position out of bounds!");
1014 return (maskBit(bitPosition) &
1015 (isSingleWord() ? VAL : pVal[whichWord(bitPosition)])) !=
1020 /// \name Comparison Operators
1023 /// \brief Equality operator.
1025 /// Compares this APInt with RHS for the validity of the equality
1027 bool operator==(const APInt &RHS) const {
1028 assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths");
1030 return VAL == RHS.VAL;
1031 return EqualSlowCase(RHS);
1034 /// \brief Equality operator.
1036 /// Compares this APInt with a uint64_t for the validity of the equality
1039 /// \returns true if *this == Val
1040 bool operator==(uint64_t Val) const {
1041 return (isSingleWord() || getActiveBits() <= 64) && getZExtValue() == Val;
1044 /// \brief Equality comparison.
1046 /// Compares this APInt with RHS for the validity of the equality
1049 /// \returns true if *this == Val
1050 bool eq(const APInt &RHS) const { return (*this) == RHS; }
1052 /// \brief Inequality operator.
1054 /// Compares this APInt with RHS for the validity of the inequality
1057 /// \returns true if *this != Val
1058 bool operator!=(const APInt &RHS) const { return !((*this) == RHS); }
1060 /// \brief Inequality operator.
1062 /// Compares this APInt with a uint64_t for the validity of the inequality
1065 /// \returns true if *this != Val
1066 bool operator!=(uint64_t Val) const { return !((*this) == Val); }
1068 /// \brief Inequality comparison
1070 /// Compares this APInt with RHS for the validity of the inequality
1073 /// \returns true if *this != Val
1074 bool ne(const APInt &RHS) const { return !((*this) == RHS); }
1076 /// \brief Unsigned less than comparison
1078 /// Regards both *this and RHS as unsigned quantities and compares them for
1079 /// the validity of the less-than relationship.
1081 /// \returns true if *this < RHS when both are considered unsigned.
1082 bool ult(const APInt &RHS) const LLVM_READONLY;
1084 /// \brief Unsigned less than comparison
1086 /// Regards both *this as an unsigned quantity and compares it with RHS for
1087 /// the validity of the less-than relationship.
1089 /// \returns true if *this < RHS when considered unsigned.
1090 bool ult(uint64_t RHS) const {
1091 // Only need to check active bits if not a single word.
1092 return (isSingleWord() || getActiveBits() <= 64) && getZExtValue() < RHS;
1095 /// \brief Signed less than comparison
1097 /// Regards both *this and RHS as signed quantities and compares them for
1098 /// validity of the less-than relationship.
1100 /// \returns true if *this < RHS when both are considered signed.
1101 bool slt(const APInt &RHS) const LLVM_READONLY;
1103 /// \brief Signed less than comparison
1105 /// Regards both *this as a signed quantity and compares it with RHS for
1106 /// the validity of the less-than relationship.
1108 /// \returns true if *this < RHS when considered signed.
1109 bool slt(int64_t RHS) const {
1110 return (!isSingleWord() && getMinSignedBits() > 64) ? isNegative()
1111 : getSExtValue() < RHS;
1114 /// \brief Unsigned less or equal comparison
1116 /// Regards both *this and RHS as unsigned quantities and compares them for
1117 /// validity of the less-or-equal relationship.
1119 /// \returns true if *this <= RHS when both are considered unsigned.
1120 bool ule(const APInt &RHS) const { return ult(RHS) || eq(RHS); }
1122 /// \brief Unsigned less or equal comparison
1124 /// Regards both *this as an unsigned quantity and compares it with RHS for
1125 /// the validity of the less-or-equal relationship.
1127 /// \returns true if *this <= RHS when considered unsigned.
1128 bool ule(uint64_t RHS) const { return !ugt(RHS); }
1130 /// \brief Signed less or equal comparison
1132 /// Regards both *this and RHS as signed quantities and compares them for
1133 /// validity of the less-or-equal relationship.
1135 /// \returns true if *this <= RHS when both are considered signed.
1136 bool sle(const APInt &RHS) const { return slt(RHS) || eq(RHS); }
1138 /// \brief Signed less or equal comparison
1140 /// Regards both *this as a signed quantity and compares it with RHS for the
1141 /// validity of the less-or-equal relationship.
1143 /// \returns true if *this <= RHS when considered signed.
1144 bool sle(uint64_t RHS) const { return !sgt(RHS); }
1146 /// \brief Unsigned greather than comparison
1148 /// Regards both *this and RHS as unsigned quantities and compares them for
1149 /// the validity of the greater-than relationship.
1151 /// \returns true if *this > RHS when both are considered unsigned.
1152 bool ugt(const APInt &RHS) const { return !ult(RHS) && !eq(RHS); }
1154 /// \brief Unsigned greater than comparison
1156 /// Regards both *this as an unsigned quantity and compares it with RHS for
1157 /// the validity of the greater-than relationship.
1159 /// \returns true if *this > RHS when considered unsigned.
1160 bool ugt(uint64_t RHS) const {
1161 // Only need to check active bits if not a single word.
1162 return (!isSingleWord() && getActiveBits() > 64) || getZExtValue() > RHS;
1165 /// \brief Signed greather than comparison
1167 /// Regards both *this and RHS as signed quantities and compares them for the
1168 /// validity of the greater-than relationship.
1170 /// \returns true if *this > RHS when both are considered signed.
1171 bool sgt(const APInt &RHS) const { return !slt(RHS) && !eq(RHS); }
1173 /// \brief Signed greater than comparison
1175 /// Regards both *this as a signed quantity and compares it with RHS for
1176 /// the validity of the greater-than relationship.
1178 /// \returns true if *this > RHS when considered signed.
1179 bool sgt(int64_t RHS) const {
1180 return (!isSingleWord() && getMinSignedBits() > 64) ? !isNegative()
1181 : getSExtValue() > RHS;
1184 /// \brief Unsigned greater or equal comparison
1186 /// Regards both *this and RHS as unsigned quantities and compares them for
1187 /// validity of the greater-or-equal relationship.
1189 /// \returns true if *this >= RHS when both are considered unsigned.
1190 bool uge(const APInt &RHS) const { return !ult(RHS); }
1192 /// \brief Unsigned greater or equal comparison
1194 /// Regards both *this as an unsigned quantity and compares it with RHS for
1195 /// the validity of the greater-or-equal relationship.
1197 /// \returns true if *this >= RHS when considered unsigned.
1198 bool uge(uint64_t RHS) const { return !ult(RHS); }
1200 /// \brief Signed greather or equal comparison
1202 /// Regards both *this and RHS as signed quantities and compares them for
1203 /// validity of the greater-or-equal relationship.
1205 /// \returns true if *this >= RHS when both are considered signed.
1206 bool sge(const APInt &RHS) const { return !slt(RHS); }
1208 /// \brief Signed greater or equal comparison
1210 /// Regards both *this as a signed quantity and compares it with RHS for
1211 /// the validity of the greater-or-equal relationship.
1213 /// \returns true if *this >= RHS when considered signed.
1214 bool sge(int64_t RHS) const { return !slt(RHS); }
1216 /// This operation tests if there are any pairs of corresponding bits
1217 /// between this APInt and RHS that are both set.
1218 bool intersects(const APInt &RHS) const {
1219 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1221 return (VAL & RHS.VAL) != 0;
1222 return intersectsSlowCase(RHS);
1225 /// This operation checks that all bits set in this APInt are also set in RHS.
1226 bool isSubsetOf(const APInt &RHS) const {
1227 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1229 return (VAL & ~RHS.VAL) == 0;
1230 return isSubsetOfSlowCase(RHS);
1234 /// \name Resizing Operators
1237 /// \brief Truncate to new width.
1239 /// Truncate the APInt to a specified width. It is an error to specify a width
1240 /// that is greater than or equal to the current width.
1241 APInt trunc(unsigned width) const;
1243 /// \brief Sign extend to a new width.
1245 /// This operation sign extends the APInt to a new width. If the high order
1246 /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
1247 /// It is an error to specify a width that is less than or equal to the
1249 APInt sext(unsigned width) const;
1251 /// \brief Zero extend to a new width.
1253 /// This operation zero extends the APInt to a new width. The high order bits
1254 /// are filled with 0 bits. It is an error to specify a width that is less
1255 /// than or equal to the current width.
1256 APInt zext(unsigned width) const;
1258 /// \brief Sign extend or truncate to width
1260 /// Make this APInt have the bit width given by \p width. The value is sign
1261 /// extended, truncated, or left alone to make it that width.
1262 APInt sextOrTrunc(unsigned width) const;
1264 /// \brief Zero extend or truncate to width
1266 /// Make this APInt have the bit width given by \p width. The value is zero
1267 /// extended, truncated, or left alone to make it that width.
1268 APInt zextOrTrunc(unsigned width) const;
1270 /// \brief Sign extend or truncate to width
1272 /// Make this APInt have the bit width given by \p width. The value is sign
1273 /// extended, or left alone to make it that width.
1274 APInt sextOrSelf(unsigned width) const;
1276 /// \brief Zero extend or truncate to width
1278 /// Make this APInt have the bit width given by \p width. The value is zero
1279 /// extended, or left alone to make it that width.
1280 APInt zextOrSelf(unsigned width) const;
1283 /// \name Bit Manipulation Operators
1286 /// \brief Set every bit to 1.
1291 // Set all the bits in all the words.
1292 memset(pVal, -1, getNumWords() * APINT_WORD_SIZE);
1293 // Clear the unused ones
1297 /// \brief Set a given bit to 1.
1299 /// Set the given bit to 1 whose position is given as "bitPosition".
1300 void setBit(unsigned bitPosition);
1302 /// Set the sign bit to 1.
1304 setBit(BitWidth - 1);
1307 /// Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
1308 void setBits(unsigned loBit, unsigned hiBit) {
1309 assert(hiBit <= BitWidth && "hiBit out of range");
1310 assert(loBit <= BitWidth && "loBit out of range");
1313 if (loBit > hiBit) {
1315 setHighBits(BitWidth - loBit);
1318 if (loBit < APINT_BITS_PER_WORD && hiBit <= APINT_BITS_PER_WORD) {
1319 uint64_t mask = UINT64_MAX >> (APINT_BITS_PER_WORD - (hiBit - loBit));
1326 setBitsSlowCase(loBit, hiBit);
1330 /// Set the top bits starting from loBit.
1331 void setBitsFrom(unsigned loBit) {
1332 return setBits(loBit, BitWidth);
1335 /// Set the bottom loBits bits.
1336 void setLowBits(unsigned loBits) {
1337 return setBits(0, loBits);
1340 /// Set the top hiBits bits.
1341 void setHighBits(unsigned hiBits) {
1342 return setBits(BitWidth - hiBits, BitWidth);
1345 /// \brief Set every bit to 0.
1346 void clearAllBits() {
1350 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
1353 /// \brief Set a given bit to 0.
1355 /// Set the given bit to 0 whose position is given as "bitPosition".
1356 void clearBit(unsigned bitPosition);
1358 /// \brief Toggle every bit to its opposite value.
1359 void flipAllBits() {
1360 if (isSingleWord()) {
1364 flipAllBitsSlowCase();
1368 /// \brief Toggles a given bit to its opposite value.
1370 /// Toggle a given bit to its opposite value whose position is given
1371 /// as "bitPosition".
1372 void flipBit(unsigned bitPosition);
1374 /// Insert the bits from a smaller APInt starting at bitPosition.
1375 void insertBits(const APInt &SubBits, unsigned bitPosition);
1377 /// Return an APInt with the extracted bits [bitPosition,bitPosition+numBits).
1378 APInt extractBits(unsigned numBits, unsigned bitPosition) const;
1381 /// \name Value Characterization Functions
1384 /// \brief Return the number of bits in the APInt.
1385 unsigned getBitWidth() const { return BitWidth; }
1387 /// \brief Get the number of words.
1389 /// Here one word's bitwidth equals to that of uint64_t.
1391 /// \returns the number of words to hold the integer value of this APInt.
1392 unsigned getNumWords() const { return getNumWords(BitWidth); }
1394 /// \brief Get the number of words.
1396 /// *NOTE* Here one word's bitwidth equals to that of uint64_t.
1398 /// \returns the number of words to hold the integer value with a given bit
1400 static unsigned getNumWords(unsigned BitWidth) {
1401 return ((uint64_t)BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
1404 /// \brief Compute the number of active bits in the value
1406 /// This function returns the number of active bits which is defined as the
1407 /// bit width minus the number of leading zeros. This is used in several
1408 /// computations to see how "wide" the value is.
1409 unsigned getActiveBits() const { return BitWidth - countLeadingZeros(); }
1411 /// \brief Compute the number of active words in the value of this APInt.
1413 /// This is used in conjunction with getActiveData to extract the raw value of
1415 unsigned getActiveWords() const {
1416 unsigned numActiveBits = getActiveBits();
1417 return numActiveBits ? whichWord(numActiveBits - 1) + 1 : 1;
1420 /// \brief Get the minimum bit size for this signed APInt
1422 /// Computes the minimum bit width for this APInt while considering it to be a
1423 /// signed (and probably negative) value. If the value is not negative, this
1424 /// function returns the same value as getActiveBits()+1. Otherwise, it
1425 /// returns the smallest bit width that will retain the negative value. For
1426 /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
1427 /// for -1, this function will always return 1.
1428 unsigned getMinSignedBits() const {
1430 return BitWidth - countLeadingOnes() + 1;
1431 return getActiveBits() + 1;
1434 /// \brief Get zero extended value
1436 /// This method attempts to return the value of this APInt as a zero extended
1437 /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
1438 /// uint64_t. Otherwise an assertion will result.
1439 uint64_t getZExtValue() const {
1442 assert(getActiveBits() <= 64 && "Too many bits for uint64_t");
1446 /// \brief Get sign extended value
1448 /// This method attempts to return the value of this APInt as a sign extended
1449 /// int64_t. The bit width must be <= 64 or the value must fit within an
1450 /// int64_t. Otherwise an assertion will result.
1451 int64_t getSExtValue() const {
1453 return SignExtend64(VAL, BitWidth);
1454 assert(getMinSignedBits() <= 64 && "Too many bits for int64_t");
1455 return int64_t(pVal[0]);
1458 /// \brief Get bits required for string value.
1460 /// This method determines how many bits are required to hold the APInt
1461 /// equivalent of the string given by \p str.
1462 static unsigned getBitsNeeded(StringRef str, uint8_t radix);
1464 /// \brief The APInt version of the countLeadingZeros functions in
1467 /// It counts the number of zeros from the most significant bit to the first
1470 /// \returns BitWidth if the value is zero, otherwise returns the number of
1471 /// zeros from the most significant bit to the first one bits.
1472 unsigned countLeadingZeros() const {
1473 if (isSingleWord()) {
1474 unsigned unusedBits = APINT_BITS_PER_WORD - BitWidth;
1475 return llvm::countLeadingZeros(VAL) - unusedBits;
1477 return countLeadingZerosSlowCase();
1480 /// \brief Count the number of leading one bits.
1482 /// This function is an APInt version of the countLeadingOnes
1483 /// functions in MathExtras.h. It counts the number of ones from the most
1484 /// significant bit to the first zero bit.
1486 /// \returns 0 if the high order bit is not set, otherwise returns the number
1487 /// of 1 bits from the most significant to the least
1488 unsigned countLeadingOnes() const LLVM_READONLY;
1490 /// Computes the number of leading bits of this APInt that are equal to its
1492 unsigned getNumSignBits() const {
1493 return isNegative() ? countLeadingOnes() : countLeadingZeros();
1496 /// \brief Count the number of trailing zero bits.
1498 /// This function is an APInt version of the countTrailingZeros
1499 /// functions in MathExtras.h. It counts the number of zeros from the least
1500 /// significant bit to the first set bit.
1502 /// \returns BitWidth if the value is zero, otherwise returns the number of
1503 /// zeros from the least significant bit to the first one bit.
1504 unsigned countTrailingZeros() const LLVM_READONLY;
1506 /// \brief Count the number of trailing one bits.
1508 /// This function is an APInt version of the countTrailingOnes
1509 /// functions in MathExtras.h. It counts the number of ones from the least
1510 /// significant bit to the first zero bit.
1512 /// \returns BitWidth if the value is all ones, otherwise returns the number
1513 /// of ones from the least significant bit to the first zero bit.
1514 unsigned countTrailingOnes() const {
1516 return llvm::countTrailingOnes(VAL);
1517 return countTrailingOnesSlowCase();
1520 /// \brief Count the number of bits set.
1522 /// This function is an APInt version of the countPopulation functions
1523 /// in MathExtras.h. It counts the number of 1 bits in the APInt value.
1525 /// \returns 0 if the value is zero, otherwise returns the number of set bits.
1526 unsigned countPopulation() const {
1528 return llvm::countPopulation(VAL);
1529 return countPopulationSlowCase();
1533 /// \name Conversion Functions
1535 void print(raw_ostream &OS, bool isSigned) const;
1537 /// Converts an APInt to a string and append it to Str. Str is commonly a
1539 void toString(SmallVectorImpl<char> &Str, unsigned Radix, bool Signed,
1540 bool formatAsCLiteral = false) const;
1542 /// Considers the APInt to be unsigned and converts it into a string in the
1543 /// radix given. The radix can be 2, 8, 10 16, or 36.
1544 void toStringUnsigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1545 toString(Str, Radix, false, false);
1548 /// Considers the APInt to be signed and converts it into a string in the
1549 /// radix given. The radix can be 2, 8, 10, 16, or 36.
1550 void toStringSigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1551 toString(Str, Radix, true, false);
1554 /// \brief Return the APInt as a std::string.
1556 /// Note that this is an inefficient method. It is better to pass in a
1557 /// SmallVector/SmallString to the methods above to avoid thrashing the heap
1559 std::string toString(unsigned Radix, bool Signed) const;
1561 /// \returns a byte-swapped representation of this APInt Value.
1562 APInt byteSwap() const;
1564 /// \returns the value with the bit representation reversed of this APInt
1566 APInt reverseBits() const;
1568 /// \brief Converts this APInt to a double value.
1569 double roundToDouble(bool isSigned) const;
1571 /// \brief Converts this unsigned APInt to a double value.
1572 double roundToDouble() const { return roundToDouble(false); }
1574 /// \brief Converts this signed APInt to a double value.
1575 double signedRoundToDouble() const { return roundToDouble(true); }
1577 /// \brief Converts APInt bits to a double
1579 /// The conversion does not do a translation from integer to double, it just
1580 /// re-interprets the bits as a double. Note that it is valid to do this on
1581 /// any bit width. Exactly 64 bits will be translated.
1582 double bitsToDouble() const {
1587 T.I = (isSingleWord() ? VAL : pVal[0]);
1591 /// \brief Converts APInt bits to a double
1593 /// The conversion does not do a translation from integer to float, it just
1594 /// re-interprets the bits as a float. Note that it is valid to do this on
1595 /// any bit width. Exactly 32 bits will be translated.
1596 float bitsToFloat() const {
1601 T.I = unsigned((isSingleWord() ? VAL : pVal[0]));
1605 /// \brief Converts a double to APInt bits.
1607 /// The conversion does not do a translation from double to integer, it just
1608 /// re-interprets the bits of the double.
1609 static APInt doubleToBits(double V) {
1615 return APInt(sizeof T * CHAR_BIT, T.I);
1618 /// \brief Converts a float to APInt bits.
1620 /// The conversion does not do a translation from float to integer, it just
1621 /// re-interprets the bits of the float.
1622 static APInt floatToBits(float V) {
1628 return APInt(sizeof T * CHAR_BIT, T.I);
1632 /// \name Mathematics Operations
1635 /// \returns the floor log base 2 of this APInt.
1636 unsigned logBase2() const { return BitWidth - 1 - countLeadingZeros(); }
1638 /// \returns the ceil log base 2 of this APInt.
1639 unsigned ceilLogBase2() const {
1642 return BitWidth - temp.countLeadingZeros();
1645 /// \returns the nearest log base 2 of this APInt. Ties round up.
1647 /// NOTE: When we have a BitWidth of 1, we define:
1649 /// log2(0) = UINT32_MAX
1652 /// to get around any mathematical concerns resulting from
1653 /// referencing 2 in a space where 2 does no exist.
1654 unsigned nearestLogBase2() const {
1655 // Special case when we have a bitwidth of 1. If VAL is 1, then we
1656 // get 0. If VAL is 0, we get UINT64_MAX which gets truncated to
1661 // Handle the zero case.
1662 if (!getBoolValue())
1665 // The non-zero case is handled by computing:
1667 // nearestLogBase2(x) = logBase2(x) + x[logBase2(x)-1].
1669 // where x[i] is referring to the value of the ith bit of x.
1670 unsigned lg = logBase2();
1671 return lg + unsigned((*this)[lg - 1]);
1674 /// \returns the log base 2 of this APInt if its an exact power of two, -1
1676 int32_t exactLogBase2() const {
1682 /// \brief Compute the square root
1685 /// \brief Get the absolute value;
1687 /// If *this is < 0 then return -(*this), otherwise *this;
1694 /// \returns the multiplicative inverse for a given modulo.
1695 APInt multiplicativeInverse(const APInt &modulo) const;
1698 /// \name Support for division by constant
1701 /// Calculate the magic number for signed division by a constant.
1705 /// Calculate the magic number for unsigned division by a constant.
1707 mu magicu(unsigned LeadingZeros = 0) const;
1710 /// \name Building-block Operations for APInt and APFloat
1713 // These building block operations operate on a representation of arbitrary
1714 // precision, two's-complement, bignum integer values. They should be
1715 // sufficient to implement APInt and APFloat bignum requirements. Inputs are
1716 // generally a pointer to the base of an array of integer parts, representing
1717 // an unsigned bignum, and a count of how many parts there are.
1719 /// Sets the least significant part of a bignum to the input value, and zeroes
1720 /// out higher parts.
1721 static void tcSet(WordType *, WordType, unsigned);
1723 /// Assign one bignum to another.
1724 static void tcAssign(WordType *, const WordType *, unsigned);
1726 /// Returns true if a bignum is zero, false otherwise.
1727 static bool tcIsZero(const WordType *, unsigned);
1729 /// Extract the given bit of a bignum; returns 0 or 1. Zero-based.
1730 static int tcExtractBit(const WordType *, unsigned bit);
1732 /// Copy the bit vector of width srcBITS from SRC, starting at bit srcLSB, to
1733 /// DST, of dstCOUNT parts, such that the bit srcLSB becomes the least
1734 /// significant bit of DST. All high bits above srcBITS in DST are
1736 static void tcExtract(WordType *, unsigned dstCount,
1737 const WordType *, unsigned srcBits,
1740 /// Set the given bit of a bignum. Zero-based.
1741 static void tcSetBit(WordType *, unsigned bit);
1743 /// Clear the given bit of a bignum. Zero-based.
1744 static void tcClearBit(WordType *, unsigned bit);
1746 /// Returns the bit number of the least or most significant set bit of a
1747 /// number. If the input number has no bits set -1U is returned.
1748 static unsigned tcLSB(const WordType *, unsigned n);
1749 static unsigned tcMSB(const WordType *parts, unsigned n);
1751 /// Negate a bignum in-place.
1752 static void tcNegate(WordType *, unsigned);
1754 /// DST += RHS + CARRY where CARRY is zero or one. Returns the carry flag.
1755 static WordType tcAdd(WordType *, const WordType *,
1756 WordType carry, unsigned);
1757 /// DST += RHS. Returns the carry flag.
1758 static WordType tcAddPart(WordType *, WordType, unsigned);
1760 /// DST -= RHS + CARRY where CARRY is zero or one. Returns the carry flag.
1761 static WordType tcSubtract(WordType *, const WordType *,
1762 WordType carry, unsigned);
1763 /// DST -= RHS. Returns the carry flag.
1764 static WordType tcSubtractPart(WordType *, WordType, unsigned);
1766 /// DST += SRC * MULTIPLIER + PART if add is true
1767 /// DST = SRC * MULTIPLIER + PART if add is false
1769 /// Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC they must
1770 /// start at the same point, i.e. DST == SRC.
1772 /// If DSTPARTS == SRC_PARTS + 1 no overflow occurs and zero is returned.
1773 /// Otherwise DST is filled with the least significant DSTPARTS parts of the
1774 /// result, and if all of the omitted higher parts were zero return zero,
1775 /// otherwise overflow occurred and return one.
1776 static int tcMultiplyPart(WordType *dst, const WordType *src,
1777 WordType multiplier, WordType carry,
1778 unsigned srcParts, unsigned dstParts,
1781 /// DST = LHS * RHS, where DST has the same width as the operands and is
1782 /// filled with the least significant parts of the result. Returns one if
1783 /// overflow occurred, otherwise zero. DST must be disjoint from both
1785 static int tcMultiply(WordType *, const WordType *, const WordType *,
1788 /// DST = LHS * RHS, where DST has width the sum of the widths of the
1789 /// operands. No overflow occurs. DST must be disjoint from both
1790 /// operands. Returns the number of parts required to hold the result.
1791 static unsigned tcFullMultiply(WordType *, const WordType *,
1792 const WordType *, unsigned, unsigned);
1794 /// If RHS is zero LHS and REMAINDER are left unchanged, return one.
1795 /// Otherwise set LHS to LHS / RHS with the fractional part discarded, set
1796 /// REMAINDER to the remainder, return zero. i.e.
1798 /// OLD_LHS = RHS * LHS + REMAINDER
1800 /// SCRATCH is a bignum of the same size as the operands and result for use by
1801 /// the routine; its contents need not be initialized and are destroyed. LHS,
1802 /// REMAINDER and SCRATCH must be distinct.
1803 static int tcDivide(WordType *lhs, const WordType *rhs,
1804 WordType *remainder, WordType *scratch,
1807 /// Shift a bignum left Count bits. Shifted in bits are zero. There are no
1808 /// restrictions on Count.
1809 static void tcShiftLeft(WordType *, unsigned Words, unsigned Count);
1811 /// Shift a bignum right Count bits. Shifted in bits are zero. There are no
1812 /// restrictions on Count.
1813 static void tcShiftRight(WordType *, unsigned Words, unsigned Count);
1815 /// The obvious AND, OR and XOR and complement operations.
1816 static void tcAnd(WordType *, const WordType *, unsigned);
1817 static void tcOr(WordType *, const WordType *, unsigned);
1818 static void tcXor(WordType *, const WordType *, unsigned);
1819 static void tcComplement(WordType *, unsigned);
1821 /// Comparison (unsigned) of two bignums.
1822 static int tcCompare(const WordType *, const WordType *, unsigned);
1824 /// Increment a bignum in-place. Return the carry flag.
1825 static WordType tcIncrement(WordType *dst, unsigned parts) {
1826 return tcAddPart(dst, 1, parts);
1829 /// Decrement a bignum in-place. Return the borrow flag.
1830 static WordType tcDecrement(WordType *dst, unsigned parts) {
1831 return tcSubtractPart(dst, 1, parts);
1834 /// Set the least significant BITS and clear the rest.
1835 static void tcSetLeastSignificantBits(WordType *, unsigned, unsigned bits);
1837 /// \brief debug method
1843 /// Magic data for optimising signed division by a constant.
1845 APInt m; ///< magic number
1846 unsigned s; ///< shift amount
1849 /// Magic data for optimising unsigned division by a constant.
1851 APInt m; ///< magic number
1852 bool a; ///< add indicator
1853 unsigned s; ///< shift amount
1856 inline bool operator==(uint64_t V1, const APInt &V2) { return V2 == V1; }
1858 inline bool operator!=(uint64_t V1, const APInt &V2) { return V2 != V1; }
1860 /// \brief Unary bitwise complement operator.
1862 /// \returns an APInt that is the bitwise complement of \p v.
1863 inline APInt operator~(APInt v) {
1868 inline APInt operator&(APInt a, const APInt &b) {
1873 inline APInt operator&(const APInt &a, APInt &&b) {
1875 return std::move(b);
1878 inline APInt operator&(APInt a, uint64_t RHS) {
1883 inline APInt operator&(uint64_t LHS, APInt b) {
1888 inline APInt operator|(APInt a, const APInt &b) {
1893 inline APInt operator|(const APInt &a, APInt &&b) {
1895 return std::move(b);
1898 inline APInt operator|(APInt a, uint64_t RHS) {
1903 inline APInt operator|(uint64_t LHS, APInt b) {
1908 inline APInt operator^(APInt a, const APInt &b) {
1913 inline APInt operator^(const APInt &a, APInt &&b) {
1915 return std::move(b);
1918 inline APInt operator^(APInt a, uint64_t RHS) {
1923 inline APInt operator^(uint64_t LHS, APInt b) {
1928 inline raw_ostream &operator<<(raw_ostream &OS, const APInt &I) {
1933 inline APInt operator-(APInt v) {
1939 inline APInt operator+(APInt a, const APInt &b) {
1944 inline APInt operator+(const APInt &a, APInt &&b) {
1946 return std::move(b);
1949 inline APInt operator+(APInt a, uint64_t RHS) {
1954 inline APInt operator+(uint64_t LHS, APInt b) {
1959 inline APInt operator-(APInt a, const APInt &b) {
1964 inline APInt operator-(const APInt &a, APInt &&b) {
1967 return std::move(b);
1970 inline APInt operator-(APInt a, uint64_t RHS) {
1975 inline APInt operator-(uint64_t LHS, APInt b) {
1982 namespace APIntOps {
1984 /// \brief Determine the smaller of two APInts considered to be signed.
1985 inline const APInt &smin(const APInt &A, const APInt &B) {
1986 return A.slt(B) ? A : B;
1989 /// \brief Determine the larger of two APInts considered to be signed.
1990 inline const APInt &smax(const APInt &A, const APInt &B) {
1991 return A.sgt(B) ? A : B;
1994 /// \brief Determine the smaller of two APInts considered to be signed.
1995 inline const APInt &umin(const APInt &A, const APInt &B) {
1996 return A.ult(B) ? A : B;
1999 /// \brief Determine the larger of two APInts considered to be unsigned.
2000 inline const APInt &umax(const APInt &A, const APInt &B) {
2001 return A.ugt(B) ? A : B;
2004 /// \brief Compute GCD of two unsigned APInt values.
2006 /// This function returns the greatest common divisor of the two APInt values
2007 /// using Stein's algorithm.
2009 /// \returns the greatest common divisor of A and B.
2010 APInt GreatestCommonDivisor(APInt A, APInt B);
2012 /// \brief Converts the given APInt to a double value.
2014 /// Treats the APInt as an unsigned value for conversion purposes.
2015 inline double RoundAPIntToDouble(const APInt &APIVal) {
2016 return APIVal.roundToDouble();
2019 /// \brief Converts the given APInt to a double value.
2021 /// Treats the APInt as a signed value for conversion purposes.
2022 inline double RoundSignedAPIntToDouble(const APInt &APIVal) {
2023 return APIVal.signedRoundToDouble();
2026 /// \brief Converts the given APInt to a float vlalue.
2027 inline float RoundAPIntToFloat(const APInt &APIVal) {
2028 return float(RoundAPIntToDouble(APIVal));
2031 /// \brief Converts the given APInt to a float value.
2033 /// Treast the APInt as a signed value for conversion purposes.
2034 inline float RoundSignedAPIntToFloat(const APInt &APIVal) {
2035 return float(APIVal.signedRoundToDouble());
2038 /// \brief Converts the given double value into a APInt.
2040 /// This function convert a double value to an APInt value.
2041 APInt RoundDoubleToAPInt(double Double, unsigned width);
2043 /// \brief Converts a float value into a APInt.
2045 /// Converts a float value into an APInt value.
2046 inline APInt RoundFloatToAPInt(float Float, unsigned width) {
2047 return RoundDoubleToAPInt(double(Float), width);
2050 } // End of APIntOps namespace
2052 // See friend declaration above. This additional declaration is required in
2053 // order to compile LLVM with IBM xlC compiler.
2054 hash_code hash_value(const APInt &Arg);
2055 } // End of llvm namespace