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/ADT/ArrayRef.h"
20 #include "llvm/Support/Compiler.h"
21 #include "llvm/Support/MathExtras.h"
29 class FoldingSetNodeID;
35 template <typename T> class SmallVectorImpl;
37 // An unsigned host type used as a single part of a multi-part
39 typedef uint64_t integerPart;
41 const unsigned int host_char_bit = 8;
42 const unsigned int integerPartWidth =
43 host_char_bit * static_cast<unsigned int>(sizeof(integerPart));
45 //===----------------------------------------------------------------------===//
47 //===----------------------------------------------------------------------===//
49 /// \brief Class for arbitrary precision integers.
51 /// APInt is a functional replacement for common case unsigned integer type like
52 /// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width
53 /// integer sizes and large integer value types such as 3-bits, 15-bits, or more
54 /// than 64-bits of precision. APInt provides a variety of arithmetic operators
55 /// and methods to manipulate integer values of any bit-width. It supports both
56 /// the typical integer arithmetic and comparison operations as well as bitwise
59 /// The class has several invariants worth noting:
60 /// * All bit, byte, and word positions are zero-based.
61 /// * Once the bit width is set, it doesn't change except by the Truncate,
62 /// SignExtend, or ZeroExtend operations.
63 /// * All binary operators must be on APInt instances of the same bit width.
64 /// Attempting to use these operators on instances with different bit
65 /// widths will yield an assertion.
66 /// * The value is stored canonically as an unsigned value. For operations
67 /// where it makes a difference, there are both signed and unsigned variants
68 /// of the operation. For example, sdiv and udiv. However, because the bit
69 /// widths must be the same, operations such as Mul and Add produce the same
70 /// results regardless of whether the values are interpreted as signed or
72 /// * In general, the class tries to follow the style of computation that LLVM
73 /// uses in its IR. This simplifies its use for LLVM.
76 unsigned BitWidth; ///< The number of bits in this APInt.
78 /// This union is used to store the integer value. When the
79 /// integer bit-width <= 64, it uses VAL, otherwise it uses pVal.
81 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
82 uint64_t *pVal; ///< Used to store the >64 bits integer value.
85 /// This enum is used to hold the constants we needed for APInt.
89 static_cast<unsigned int>(sizeof(uint64_t)) * CHAR_BIT,
90 /// Byte size of a word
91 APINT_WORD_SIZE = static_cast<unsigned int>(sizeof(uint64_t))
94 friend struct DenseMapAPIntKeyInfo;
96 /// \brief Fast internal constructor
98 /// This constructor is used only internally for speed of construction of
99 /// temporaries. It is unsafe for general use so it is not public.
100 APInt(uint64_t *val, unsigned bits) : BitWidth(bits), pVal(val) {}
102 /// \brief Determine if this APInt just has one word to store value.
104 /// \returns true if the number of bits <= 64, false otherwise.
105 bool isSingleWord() const { return BitWidth <= APINT_BITS_PER_WORD; }
107 /// \brief Determine which word a bit is in.
109 /// \returns the word position for the specified bit position.
110 static unsigned whichWord(unsigned bitPosition) {
111 return bitPosition / APINT_BITS_PER_WORD;
114 /// \brief Determine which bit in a word a bit is in.
116 /// \returns the bit position in a word for the specified bit position
118 static unsigned whichBit(unsigned bitPosition) {
119 return bitPosition % APINT_BITS_PER_WORD;
122 /// \brief Get a single bit mask.
124 /// \returns a uint64_t with only bit at "whichBit(bitPosition)" set
125 /// This method generates and returns a uint64_t (word) mask for a single
126 /// bit at a specific bit position. This is used to mask the bit in the
127 /// corresponding word.
128 static uint64_t maskBit(unsigned bitPosition) {
129 return 1ULL << whichBit(bitPosition);
132 /// \brief Clear unused high order bits
134 /// This method is used internally to clear the to "N" bits in the high order
135 /// word that are not used by the APInt. This is needed after the most
136 /// significant word is assigned a value to ensure that those bits are
138 APInt &clearUnusedBits() {
139 // Compute how many bits are used in the final word
140 unsigned wordBits = BitWidth % APINT_BITS_PER_WORD;
142 // If all bits are used, we want to leave the value alone. This also
143 // avoids the undefined behavior of >> when the shift is the same size as
144 // the word size (64).
147 // Mask out the high bits.
148 uint64_t mask = ~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - wordBits);
152 pVal[getNumWords() - 1] &= mask;
156 /// \brief Get the word corresponding to a bit position
157 /// \returns the corresponding word for the specified bit position.
158 uint64_t getWord(unsigned bitPosition) const {
159 return isSingleWord() ? VAL : pVal[whichWord(bitPosition)];
162 /// \brief Convert a char array into an APInt
164 /// \param radix 2, 8, 10, 16, or 36
165 /// Converts a string into a number. The string must be non-empty
166 /// and well-formed as a number of the given base. The bit-width
167 /// must be sufficient to hold the result.
169 /// This is used by the constructors that take string arguments.
171 /// StringRef::getAsInteger is superficially similar but (1) does
172 /// not assume that the string is well-formed and (2) grows the
173 /// result to hold the input.
174 void fromString(unsigned numBits, StringRef str, uint8_t radix);
176 /// \brief An internal division function for dividing APInts.
178 /// This is used by the toString method to divide by the radix. It simply
179 /// provides a more convenient form of divide for internal use since KnuthDiv
180 /// has specific constraints on its inputs. If those constraints are not met
181 /// then it provides a simpler form of divide.
182 static void divide(const APInt LHS, unsigned lhsWords, const APInt &RHS,
183 unsigned rhsWords, APInt *Quotient, APInt *Remainder);
185 /// out-of-line slow case for inline constructor
186 void initSlowCase(unsigned numBits, uint64_t val, bool isSigned);
188 /// shared code between two array constructors
189 void initFromArray(ArrayRef<uint64_t> array);
191 /// out-of-line slow case for inline copy constructor
192 void initSlowCase(const APInt &that);
194 /// out-of-line slow case for shl
195 APInt shlSlowCase(unsigned shiftAmt) const;
197 /// out-of-line slow case for operator&
198 APInt AndSlowCase(const APInt &RHS) const;
200 /// out-of-line slow case for operator|
201 APInt OrSlowCase(const APInt &RHS) const;
203 /// out-of-line slow case for operator^
204 APInt XorSlowCase(const APInt &RHS) const;
206 /// out-of-line slow case for operator=
207 APInt &AssignSlowCase(const APInt &RHS);
209 /// out-of-line slow case for operator==
210 bool EqualSlowCase(const APInt &RHS) const;
212 /// out-of-line slow case for operator==
213 bool EqualSlowCase(uint64_t Val) const;
215 /// out-of-line slow case for countLeadingZeros
216 unsigned countLeadingZerosSlowCase() const;
218 /// out-of-line slow case for countTrailingOnes
219 unsigned countTrailingOnesSlowCase() const;
221 /// out-of-line slow case for countPopulation
222 unsigned countPopulationSlowCase() const;
225 /// \name Constructors
228 /// \brief Create a new APInt of numBits width, initialized as val.
230 /// If isSigned is true then val is treated as if it were a signed value
231 /// (i.e. as an int64_t) and the appropriate sign extension to the bit width
232 /// will be done. Otherwise, no sign extension occurs (high order bits beyond
233 /// the range of val are zero filled).
235 /// \param numBits the bit width of the constructed APInt
236 /// \param val the initial value of the APInt
237 /// \param isSigned how to treat signedness of val
238 APInt(unsigned numBits, uint64_t val, bool isSigned = false)
239 : BitWidth(numBits), VAL(0) {
240 assert(BitWidth && "bitwidth too small");
244 initSlowCase(numBits, val, isSigned);
248 /// \brief Construct an APInt of numBits width, initialized as bigVal[].
250 /// Note that bigVal.size() can be smaller or larger than the corresponding
251 /// bit width but any extraneous bits will be dropped.
253 /// \param numBits the bit width of the constructed APInt
254 /// \param bigVal a sequence of words to form the initial value of the APInt
255 APInt(unsigned numBits, ArrayRef<uint64_t> bigVal);
257 /// Equivalent to APInt(numBits, ArrayRef<uint64_t>(bigVal, numWords)), but
258 /// deprecated because this constructor is prone to ambiguity with the
259 /// APInt(unsigned, uint64_t, bool) constructor.
261 /// If this overload is ever deleted, care should be taken to prevent calls
262 /// from being incorrectly captured by the APInt(unsigned, uint64_t, bool)
264 APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[]);
266 /// \brief Construct an APInt from a string representation.
268 /// This constructor interprets the string \p str in the given radix. The
269 /// interpretation stops when the first character that is not suitable for the
270 /// radix is encountered, or the end of the string. Acceptable radix values
271 /// are 2, 8, 10, 16, and 36. It is an error for the value implied by the
272 /// string to require more bits than numBits.
274 /// \param numBits the bit width of the constructed APInt
275 /// \param str the string to be interpreted
276 /// \param radix the radix to use for the conversion
277 APInt(unsigned numBits, StringRef str, uint8_t radix);
279 /// Simply makes *this a copy of that.
280 /// @brief Copy Constructor.
281 APInt(const APInt &that) : BitWidth(that.BitWidth), VAL(0) {
288 /// \brief Move Constructor.
289 APInt(APInt &&that) : BitWidth(that.BitWidth), VAL(that.VAL) {
293 /// \brief Destructor.
299 /// \brief Default constructor that creates an uninitialized APInt.
301 /// This is useful for object deserialization (pair this with the static
303 explicit APInt() : BitWidth(1) {}
305 /// \brief Returns whether this instance allocated memory.
306 bool needsCleanup() const { return !isSingleWord(); }
308 /// Used to insert APInt objects, or objects that contain APInt objects, into
310 void Profile(FoldingSetNodeID &id) const;
313 /// \name Value Tests
316 /// \brief Determine sign of this APInt.
318 /// This tests the high bit of this APInt to determine if it is set.
320 /// \returns true if this APInt is negative, false otherwise
321 bool isNegative() const { return (*this)[BitWidth - 1]; }
323 /// \brief Determine if this APInt Value is non-negative (>= 0)
325 /// This tests the high bit of the APInt to determine if it is unset.
326 bool isNonNegative() const { return !isNegative(); }
328 /// \brief Determine if this APInt Value is positive.
330 /// This tests if the value of this APInt is positive (> 0). Note
331 /// that 0 is not a positive value.
333 /// \returns true if this APInt is positive.
334 bool isStrictlyPositive() const { return isNonNegative() && !!*this; }
336 /// \brief Determine if all bits are set
338 /// This checks to see if the value has all bits of the APInt are set or not.
339 bool isAllOnesValue() const {
341 return VAL == ~integerPart(0) >> (APINT_BITS_PER_WORD - BitWidth);
342 return countPopulationSlowCase() == BitWidth;
345 /// \brief Determine if this is the largest unsigned value.
347 /// This checks to see if the value of this APInt is the maximum unsigned
348 /// value for the APInt's bit width.
349 bool isMaxValue() const { return isAllOnesValue(); }
351 /// \brief Determine if this is the largest signed value.
353 /// This checks to see if the value of this APInt is the maximum signed
354 /// value for the APInt's bit width.
355 bool isMaxSignedValue() const {
356 return BitWidth == 1 ? VAL == 0
357 : !isNegative() && countPopulation() == BitWidth - 1;
360 /// \brief Determine if this is the smallest unsigned value.
362 /// This checks to see if the value of this APInt is the minimum unsigned
363 /// value for the APInt's bit width.
364 bool isMinValue() const { return !*this; }
366 /// \brief Determine if this is the smallest signed value.
368 /// This checks to see if the value of this APInt is the minimum signed
369 /// value for the APInt's bit width.
370 bool isMinSignedValue() const {
371 return BitWidth == 1 ? VAL == 1 : isNegative() && isPowerOf2();
374 /// \brief Check if this APInt has an N-bits unsigned integer value.
375 bool isIntN(unsigned N) const {
376 assert(N && "N == 0 ???");
377 return getActiveBits() <= N;
380 /// \brief Check if this APInt has an N-bits signed integer value.
381 bool isSignedIntN(unsigned N) const {
382 assert(N && "N == 0 ???");
383 return getMinSignedBits() <= N;
386 /// \brief Check if this APInt's value is a power of two greater than zero.
388 /// \returns true if the argument APInt value is a power of two > 0.
389 bool isPowerOf2() const {
391 return isPowerOf2_64(VAL);
392 return countPopulationSlowCase() == 1;
395 /// \brief Check if the APInt's value is returned by getSignBit.
397 /// \returns true if this is the value returned by getSignBit.
398 bool isSignBit() const { return isMinSignedValue(); }
400 /// \brief Convert APInt to a boolean value.
402 /// This converts the APInt to a boolean value as a test against zero.
403 bool getBoolValue() const { return !!*this; }
405 /// If this value is smaller than the specified limit, return it, otherwise
406 /// return the limit value. This causes the value to saturate to the limit.
407 uint64_t getLimitedValue(uint64_t Limit = ~0ULL) const {
408 return (getActiveBits() > 64 || getZExtValue() > Limit) ? Limit
413 /// \name Value Generators
416 /// \brief Gets maximum unsigned value of APInt for specific bit width.
417 static APInt getMaxValue(unsigned numBits) {
418 return getAllOnesValue(numBits);
421 /// \brief Gets maximum signed value of APInt for a specific bit width.
422 static APInt getSignedMaxValue(unsigned numBits) {
423 APInt API = getAllOnesValue(numBits);
424 API.clearBit(numBits - 1);
428 /// \brief Gets minimum unsigned value of APInt for a specific bit width.
429 static APInt getMinValue(unsigned numBits) { return APInt(numBits, 0); }
431 /// \brief Gets minimum signed value of APInt for a specific bit width.
432 static APInt getSignedMinValue(unsigned numBits) {
433 APInt API(numBits, 0);
434 API.setBit(numBits - 1);
438 /// \brief Get the SignBit for a specific bit width.
440 /// This is just a wrapper function of getSignedMinValue(), and it helps code
441 /// readability when we want to get a SignBit.
442 static APInt getSignBit(unsigned BitWidth) {
443 return getSignedMinValue(BitWidth);
446 /// \brief Get the all-ones value.
448 /// \returns the all-ones value for an APInt of the specified bit-width.
449 static APInt getAllOnesValue(unsigned numBits) {
450 return APInt(numBits, UINT64_MAX, true);
453 /// \brief Get the '0' value.
455 /// \returns the '0' value for an APInt of the specified bit-width.
456 static APInt getNullValue(unsigned numBits) { return APInt(numBits, 0); }
458 /// \brief Compute an APInt containing numBits highbits from this APInt.
460 /// Get an APInt with the same BitWidth as this APInt, just zero mask
461 /// the low bits and right shift to the least significant bit.
463 /// \returns the high "numBits" bits of this APInt.
464 APInt getHiBits(unsigned numBits) const;
466 /// \brief Compute an APInt containing numBits lowbits from this APInt.
468 /// Get an APInt with the same BitWidth as this APInt, just zero mask
471 /// \returns the low "numBits" bits of this APInt.
472 APInt getLoBits(unsigned numBits) const;
474 /// \brief Return an APInt with exactly one bit set in the result.
475 static APInt getOneBitSet(unsigned numBits, unsigned BitNo) {
476 APInt Res(numBits, 0);
481 /// \brief Get a value with a block of bits set.
483 /// Constructs an APInt value that has a contiguous range of bits set. The
484 /// bits from loBit (inclusive) to hiBit (exclusive) will be set. All other
485 /// bits will be zero. For example, with parameters(32, 0, 16) you would get
486 /// 0x0000FFFF. If hiBit is less than loBit then the set bits "wrap". For
487 /// example, with parameters (32, 28, 4), you would get 0xF000000F.
489 /// \param numBits the intended bit width of the result
490 /// \param loBit the index of the lowest bit set.
491 /// \param hiBit the index of the highest bit set.
493 /// \returns An APInt value with the requested bits set.
494 static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit) {
495 assert(hiBit <= numBits && "hiBit out of range");
496 assert(loBit < numBits && "loBit out of range");
498 return getLowBitsSet(numBits, hiBit) |
499 getHighBitsSet(numBits, numBits - loBit);
500 return getLowBitsSet(numBits, hiBit - loBit).shl(loBit);
503 /// \brief Get a value with high bits set
505 /// Constructs an APInt value that has the top hiBitsSet bits set.
507 /// \param numBits the bitwidth of the result
508 /// \param hiBitsSet the number of high-order bits set in the result.
509 static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet) {
510 assert(hiBitsSet <= numBits && "Too many bits to set!");
511 // Handle a degenerate case, to avoid shifting by word size
513 return APInt(numBits, 0);
514 unsigned shiftAmt = numBits - hiBitsSet;
515 // For small values, return quickly
516 if (numBits <= APINT_BITS_PER_WORD)
517 return APInt(numBits, ~0ULL << shiftAmt);
518 return getAllOnesValue(numBits).shl(shiftAmt);
521 /// \brief Get a value with low bits set
523 /// Constructs an APInt value that has the bottom loBitsSet bits set.
525 /// \param numBits the bitwidth of the result
526 /// \param loBitsSet the number of low-order bits set in the result.
527 static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet) {
528 assert(loBitsSet <= numBits && "Too many bits to set!");
529 // Handle a degenerate case, to avoid shifting by word size
531 return APInt(numBits, 0);
532 if (loBitsSet == APINT_BITS_PER_WORD)
533 return APInt(numBits, UINT64_MAX);
534 // For small values, return quickly.
535 if (loBitsSet <= APINT_BITS_PER_WORD)
536 return APInt(numBits, UINT64_MAX >> (APINT_BITS_PER_WORD - loBitsSet));
537 return getAllOnesValue(numBits).lshr(numBits - loBitsSet);
540 /// \brief Return a value containing V broadcasted over NewLen bits.
541 static APInt getSplat(unsigned NewLen, const APInt &V) {
542 assert(NewLen >= V.getBitWidth() && "Can't splat to smaller bit width!");
544 APInt Val = V.zextOrSelf(NewLen);
545 for (unsigned I = V.getBitWidth(); I < NewLen; I <<= 1)
551 /// \brief Determine if two APInts have the same value, after zero-extending
552 /// one of them (if needed!) to ensure that the bit-widths match.
553 static bool isSameValue(const APInt &I1, const APInt &I2) {
554 if (I1.getBitWidth() == I2.getBitWidth())
557 if (I1.getBitWidth() > I2.getBitWidth())
558 return I1 == I2.zext(I1.getBitWidth());
560 return I1.zext(I2.getBitWidth()) == I2;
563 /// \brief Overload to compute a hash_code for an APInt value.
564 friend hash_code hash_value(const APInt &Arg);
566 /// This function returns a pointer to the internal storage of the APInt.
567 /// This is useful for writing out the APInt in binary form without any
569 const uint64_t *getRawData() const {
576 /// \name Unary Operators
579 /// \brief Postfix increment operator.
581 /// \returns a new APInt value representing *this incremented by one
582 const APInt operator++(int) {
588 /// \brief Prefix increment operator.
590 /// \returns *this incremented by one
593 /// \brief Postfix decrement operator.
595 /// \returns a new APInt representing *this decremented by one.
596 const APInt operator--(int) {
602 /// \brief Prefix decrement operator.
604 /// \returns *this decremented by one.
607 /// \brief Unary bitwise complement operator.
609 /// Performs a bitwise complement operation on this APInt.
611 /// \returns an APInt that is the bitwise complement of *this
612 APInt operator~() const {
614 Result.flipAllBits();
618 /// \brief Unary negation operator
620 /// Negates *this using two's complement logic.
622 /// \returns An APInt value representing the negation of *this.
623 APInt operator-() const { return APInt(BitWidth, 0) - (*this); }
625 /// \brief Logical negation operator.
627 /// Performs logical negation operation on this APInt.
629 /// \returns true if *this is zero, false otherwise.
630 bool operator!() const {
634 for (unsigned i = 0; i != getNumWords(); ++i)
641 /// \name Assignment Operators
644 /// \brief Copy assignment operator.
646 /// \returns *this after assignment of RHS.
647 APInt &operator=(const APInt &RHS) {
648 // If the bitwidths are the same, we can avoid mucking with memory
649 if (isSingleWord() && RHS.isSingleWord()) {
651 BitWidth = RHS.BitWidth;
652 return clearUnusedBits();
655 return AssignSlowCase(RHS);
658 /// @brief Move assignment operator.
659 APInt &operator=(APInt &&that) {
660 if (!isSingleWord()) {
661 // The MSVC STL shipped in 2013 requires that self move assignment be a
662 // no-op. Otherwise algorithms like stable_sort will produce answers
663 // where half of the output is left in a moved-from state.
669 // Use memcpy so that type based alias analysis sees both VAL and pVal
671 memcpy(&VAL, &that.VAL, sizeof(uint64_t));
673 // If 'this == &that', avoid zeroing our own bitwidth by storing to 'that'
675 unsigned ThatBitWidth = that.BitWidth;
677 BitWidth = ThatBitWidth;
682 /// \brief Assignment operator.
684 /// The RHS value is assigned to *this. If the significant bits in RHS exceed
685 /// the bit width, the excess bits are truncated. If the bit width is larger
686 /// than 64, the value is zero filled in the unspecified high order bits.
688 /// \returns *this after assignment of RHS value.
689 APInt &operator=(uint64_t RHS);
691 /// \brief Bitwise AND assignment operator.
693 /// Performs a bitwise AND operation on this APInt and RHS. The result is
694 /// assigned to *this.
696 /// \returns *this after ANDing with RHS.
697 APInt &operator&=(const APInt &RHS);
699 /// \brief Bitwise OR assignment operator.
701 /// Performs a bitwise OR operation on this APInt and RHS. The result is
704 /// \returns *this after ORing with RHS.
705 APInt &operator|=(const APInt &RHS);
707 /// \brief Bitwise OR assignment operator.
709 /// Performs a bitwise OR operation on this APInt and RHS. RHS is
710 /// logically zero-extended or truncated to match the bit-width of
712 APInt &operator|=(uint64_t RHS) {
713 if (isSingleWord()) {
722 /// \brief Bitwise XOR assignment operator.
724 /// Performs a bitwise XOR operation on this APInt and RHS. The result is
725 /// assigned to *this.
727 /// \returns *this after XORing with RHS.
728 APInt &operator^=(const APInt &RHS);
730 /// \brief Multiplication assignment operator.
732 /// Multiplies this APInt by RHS and assigns the result to *this.
735 APInt &operator*=(const APInt &RHS);
737 /// \brief Addition assignment operator.
739 /// Adds RHS to *this and assigns the result to *this.
742 APInt &operator+=(const APInt &RHS);
744 /// \brief Subtraction assignment operator.
746 /// Subtracts RHS from *this and assigns the result to *this.
749 APInt &operator-=(const APInt &RHS);
751 /// \brief Left-shift assignment function.
753 /// Shifts *this left by shiftAmt and assigns the result to *this.
755 /// \returns *this after shifting left by shiftAmt
756 APInt &operator<<=(unsigned shiftAmt) {
757 *this = shl(shiftAmt);
762 /// \name Binary Operators
765 /// \brief Bitwise AND operator.
767 /// Performs a bitwise AND operation on *this and RHS.
769 /// \returns An APInt value representing the bitwise AND of *this and RHS.
770 APInt operator&(const APInt &RHS) const {
771 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
773 return APInt(getBitWidth(), VAL & RHS.VAL);
774 return AndSlowCase(RHS);
776 APInt LLVM_ATTRIBUTE_UNUSED_RESULT And(const APInt &RHS) const {
777 return this->operator&(RHS);
780 /// \brief Bitwise OR operator.
782 /// Performs a bitwise OR operation on *this and RHS.
784 /// \returns An APInt value representing the bitwise OR of *this and RHS.
785 APInt operator|(const APInt &RHS) const {
786 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
788 return APInt(getBitWidth(), VAL | RHS.VAL);
789 return OrSlowCase(RHS);
792 /// \brief Bitwise OR function.
794 /// Performs a bitwise or on *this and RHS. This is implemented bny simply
795 /// calling operator|.
797 /// \returns An APInt value representing the bitwise OR of *this and RHS.
798 APInt LLVM_ATTRIBUTE_UNUSED_RESULT Or(const APInt &RHS) const {
799 return this->operator|(RHS);
802 /// \brief Bitwise XOR operator.
804 /// Performs a bitwise XOR operation on *this and RHS.
806 /// \returns An APInt value representing the bitwise XOR of *this and RHS.
807 APInt operator^(const APInt &RHS) const {
808 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
810 return APInt(BitWidth, VAL ^ RHS.VAL);
811 return XorSlowCase(RHS);
814 /// \brief Bitwise XOR function.
816 /// Performs a bitwise XOR operation on *this and RHS. This is implemented
817 /// through the usage of operator^.
819 /// \returns An APInt value representing the bitwise XOR of *this and RHS.
820 APInt LLVM_ATTRIBUTE_UNUSED_RESULT Xor(const APInt &RHS) const {
821 return this->operator^(RHS);
824 /// \brief Multiplication operator.
826 /// Multiplies this APInt by RHS and returns the result.
827 APInt operator*(const APInt &RHS) const;
829 /// \brief Addition operator.
831 /// Adds RHS to this APInt and returns the result.
832 APInt operator+(const APInt &RHS) const;
833 APInt operator+(uint64_t RHS) const { return (*this) + APInt(BitWidth, RHS); }
835 /// \brief Subtraction operator.
837 /// Subtracts RHS from this APInt and returns the result.
838 APInt operator-(const APInt &RHS) const;
839 APInt operator-(uint64_t RHS) const { return (*this) - APInt(BitWidth, RHS); }
841 /// \brief Left logical shift operator.
843 /// Shifts this APInt left by \p Bits and returns the result.
844 APInt operator<<(unsigned Bits) const { return shl(Bits); }
846 /// \brief Left logical shift operator.
848 /// Shifts this APInt left by \p Bits and returns the result.
849 APInt operator<<(const APInt &Bits) const { return shl(Bits); }
851 /// \brief Arithmetic right-shift function.
853 /// Arithmetic right-shift this APInt by shiftAmt.
854 APInt LLVM_ATTRIBUTE_UNUSED_RESULT ashr(unsigned shiftAmt) const;
856 /// \brief Logical right-shift function.
858 /// Logical right-shift this APInt by shiftAmt.
859 APInt LLVM_ATTRIBUTE_UNUSED_RESULT lshr(unsigned shiftAmt) const;
861 /// \brief Left-shift function.
863 /// Left-shift this APInt by shiftAmt.
864 APInt LLVM_ATTRIBUTE_UNUSED_RESULT shl(unsigned shiftAmt) const {
865 assert(shiftAmt <= BitWidth && "Invalid shift amount");
866 if (isSingleWord()) {
867 if (shiftAmt >= BitWidth)
868 return APInt(BitWidth, 0); // avoid undefined shift results
869 return APInt(BitWidth, VAL << shiftAmt);
871 return shlSlowCase(shiftAmt);
874 /// \brief Rotate left by rotateAmt.
875 APInt LLVM_ATTRIBUTE_UNUSED_RESULT rotl(unsigned rotateAmt) const;
877 /// \brief Rotate right by rotateAmt.
878 APInt LLVM_ATTRIBUTE_UNUSED_RESULT rotr(unsigned rotateAmt) const;
880 /// \brief Arithmetic right-shift function.
882 /// Arithmetic right-shift this APInt by shiftAmt.
883 APInt LLVM_ATTRIBUTE_UNUSED_RESULT ashr(const APInt &shiftAmt) const;
885 /// \brief Logical right-shift function.
887 /// Logical right-shift this APInt by shiftAmt.
888 APInt LLVM_ATTRIBUTE_UNUSED_RESULT lshr(const APInt &shiftAmt) const;
890 /// \brief Left-shift function.
892 /// Left-shift this APInt by shiftAmt.
893 APInt LLVM_ATTRIBUTE_UNUSED_RESULT shl(const APInt &shiftAmt) const;
895 /// \brief Rotate left by rotateAmt.
896 APInt LLVM_ATTRIBUTE_UNUSED_RESULT rotl(const APInt &rotateAmt) const;
898 /// \brief Rotate right by rotateAmt.
899 APInt LLVM_ATTRIBUTE_UNUSED_RESULT rotr(const APInt &rotateAmt) const;
901 /// \brief Unsigned division operation.
903 /// Perform an unsigned divide operation on this APInt by RHS. Both this and
904 /// RHS are treated as unsigned quantities for purposes of this division.
906 /// \returns a new APInt value containing the division result
907 APInt LLVM_ATTRIBUTE_UNUSED_RESULT udiv(const APInt &RHS) const;
909 /// \brief Signed division function for APInt.
911 /// Signed divide this APInt by APInt RHS.
912 APInt LLVM_ATTRIBUTE_UNUSED_RESULT sdiv(const APInt &RHS) const;
914 /// \brief Unsigned remainder operation.
916 /// Perform an unsigned remainder operation on this APInt with RHS being the
917 /// divisor. Both this and RHS are treated as unsigned quantities for purposes
918 /// of this operation. Note that this is a true remainder operation and not a
919 /// modulo operation because the sign follows the sign of the dividend which
922 /// \returns a new APInt value containing the remainder result
923 APInt LLVM_ATTRIBUTE_UNUSED_RESULT urem(const APInt &RHS) const;
925 /// \brief Function for signed remainder operation.
927 /// Signed remainder operation on APInt.
928 APInt LLVM_ATTRIBUTE_UNUSED_RESULT srem(const APInt &RHS) const;
930 /// \brief Dual division/remainder interface.
932 /// Sometimes it is convenient to divide two APInt values and obtain both the
933 /// quotient and remainder. This function does both operations in the same
934 /// computation making it a little more efficient. The pair of input arguments
935 /// may overlap with the pair of output arguments. It is safe to call
936 /// udivrem(X, Y, X, Y), for example.
937 static void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient,
940 static void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient,
943 // Operations that return overflow indicators.
944 APInt sadd_ov(const APInt &RHS, bool &Overflow) const;
945 APInt uadd_ov(const APInt &RHS, bool &Overflow) const;
946 APInt ssub_ov(const APInt &RHS, bool &Overflow) const;
947 APInt usub_ov(const APInt &RHS, bool &Overflow) const;
948 APInt sdiv_ov(const APInt &RHS, bool &Overflow) const;
949 APInt smul_ov(const APInt &RHS, bool &Overflow) const;
950 APInt umul_ov(const APInt &RHS, bool &Overflow) const;
951 APInt sshl_ov(const APInt &Amt, bool &Overflow) const;
952 APInt ushl_ov(const APInt &Amt, bool &Overflow) const;
954 /// \brief Array-indexing support.
956 /// \returns the bit value at bitPosition
957 bool operator[](unsigned bitPosition) const {
958 assert(bitPosition < getBitWidth() && "Bit position out of bounds!");
959 return (maskBit(bitPosition) &
960 (isSingleWord() ? VAL : pVal[whichWord(bitPosition)])) !=
965 /// \name Comparison Operators
968 /// \brief Equality operator.
970 /// Compares this APInt with RHS for the validity of the equality
972 bool operator==(const APInt &RHS) const {
973 assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths");
975 return VAL == RHS.VAL;
976 return EqualSlowCase(RHS);
979 /// \brief Equality operator.
981 /// Compares this APInt with a uint64_t for the validity of the equality
984 /// \returns true if *this == Val
985 bool operator==(uint64_t Val) const {
988 return EqualSlowCase(Val);
991 /// \brief Equality comparison.
993 /// Compares this APInt with RHS for the validity of the equality
996 /// \returns true if *this == Val
997 bool eq(const APInt &RHS) const { return (*this) == RHS; }
999 /// \brief Inequality operator.
1001 /// Compares this APInt with RHS for the validity of the inequality
1004 /// \returns true if *this != Val
1005 bool operator!=(const APInt &RHS) const { return !((*this) == RHS); }
1007 /// \brief Inequality operator.
1009 /// Compares this APInt with a uint64_t for the validity of the inequality
1012 /// \returns true if *this != Val
1013 bool operator!=(uint64_t Val) const { return !((*this) == Val); }
1015 /// \brief Inequality comparison
1017 /// Compares this APInt with RHS for the validity of the inequality
1020 /// \returns true if *this != Val
1021 bool ne(const APInt &RHS) const { return !((*this) == RHS); }
1023 /// \brief Unsigned less than comparison
1025 /// Regards both *this and RHS as unsigned quantities and compares them for
1026 /// the validity of the less-than relationship.
1028 /// \returns true if *this < RHS when both are considered unsigned.
1029 bool ult(const APInt &RHS) const;
1031 /// \brief Unsigned less than comparison
1033 /// Regards both *this as an unsigned quantity and compares it with RHS for
1034 /// the validity of the less-than relationship.
1036 /// \returns true if *this < RHS when considered unsigned.
1037 bool ult(uint64_t RHS) const { return ult(APInt(getBitWidth(), RHS)); }
1039 /// \brief Signed less than comparison
1041 /// Regards both *this and RHS as signed quantities and compares them for
1042 /// validity of the less-than relationship.
1044 /// \returns true if *this < RHS when both are considered signed.
1045 bool slt(const APInt &RHS) const;
1047 /// \brief Signed less than comparison
1049 /// Regards both *this as a signed quantity and compares it with RHS for
1050 /// the validity of the less-than relationship.
1052 /// \returns true if *this < RHS when considered signed.
1053 bool slt(uint64_t RHS) const { return slt(APInt(getBitWidth(), RHS)); }
1055 /// \brief Unsigned less or equal comparison
1057 /// Regards both *this and RHS as unsigned quantities and compares them for
1058 /// validity of the less-or-equal relationship.
1060 /// \returns true if *this <= RHS when both are considered unsigned.
1061 bool ule(const APInt &RHS) const { return ult(RHS) || eq(RHS); }
1063 /// \brief Unsigned less or equal comparison
1065 /// Regards both *this as an unsigned quantity and compares it with RHS for
1066 /// the validity of the less-or-equal relationship.
1068 /// \returns true if *this <= RHS when considered unsigned.
1069 bool ule(uint64_t RHS) const { return ule(APInt(getBitWidth(), RHS)); }
1071 /// \brief Signed less or equal comparison
1073 /// Regards both *this and RHS as signed quantities and compares them for
1074 /// validity of the less-or-equal relationship.
1076 /// \returns true if *this <= RHS when both are considered signed.
1077 bool sle(const APInt &RHS) const { return slt(RHS) || eq(RHS); }
1079 /// \brief Signed less or equal comparison
1081 /// Regards both *this as a signed quantity and compares it with RHS for the
1082 /// validity of the less-or-equal relationship.
1084 /// \returns true if *this <= RHS when considered signed.
1085 bool sle(uint64_t RHS) const { return sle(APInt(getBitWidth(), RHS)); }
1087 /// \brief Unsigned greather than comparison
1089 /// Regards both *this and RHS as unsigned quantities and compares them for
1090 /// the validity of the greater-than relationship.
1092 /// \returns true if *this > RHS when both are considered unsigned.
1093 bool ugt(const APInt &RHS) const { return !ult(RHS) && !eq(RHS); }
1095 /// \brief Unsigned greater than comparison
1097 /// Regards both *this as an unsigned quantity and compares it with RHS for
1098 /// the validity of the greater-than relationship.
1100 /// \returns true if *this > RHS when considered unsigned.
1101 bool ugt(uint64_t RHS) const { return ugt(APInt(getBitWidth(), RHS)); }
1103 /// \brief Signed greather than comparison
1105 /// Regards both *this and RHS as signed quantities and compares them for the
1106 /// validity of the greater-than relationship.
1108 /// \returns true if *this > RHS when both are considered signed.
1109 bool sgt(const APInt &RHS) const { return !slt(RHS) && !eq(RHS); }
1111 /// \brief Signed greater than comparison
1113 /// Regards both *this as a signed quantity and compares it with RHS for
1114 /// the validity of the greater-than relationship.
1116 /// \returns true if *this > RHS when considered signed.
1117 bool sgt(uint64_t RHS) const { return sgt(APInt(getBitWidth(), RHS)); }
1119 /// \brief Unsigned greater or equal comparison
1121 /// Regards both *this and RHS as unsigned quantities and compares them for
1122 /// validity of the greater-or-equal relationship.
1124 /// \returns true if *this >= RHS when both are considered unsigned.
1125 bool uge(const APInt &RHS) const { return !ult(RHS); }
1127 /// \brief Unsigned greater or equal comparison
1129 /// Regards both *this as an unsigned quantity and compares it with RHS for
1130 /// the validity of the greater-or-equal relationship.
1132 /// \returns true if *this >= RHS when considered unsigned.
1133 bool uge(uint64_t RHS) const { return uge(APInt(getBitWidth(), RHS)); }
1135 /// \brief Signed greather or equal comparison
1137 /// Regards both *this and RHS as signed quantities and compares them for
1138 /// validity of the greater-or-equal relationship.
1140 /// \returns true if *this >= RHS when both are considered signed.
1141 bool sge(const APInt &RHS) const { return !slt(RHS); }
1143 /// \brief Signed greater or equal comparison
1145 /// Regards both *this as a signed quantity and compares it with RHS for
1146 /// the validity of the greater-or-equal relationship.
1148 /// \returns true if *this >= RHS when considered signed.
1149 bool sge(uint64_t RHS) const { return sge(APInt(getBitWidth(), RHS)); }
1151 /// This operation tests if there are any pairs of corresponding bits
1152 /// between this APInt and RHS that are both set.
1153 bool intersects(const APInt &RHS) const { return (*this & RHS) != 0; }
1156 /// \name Resizing Operators
1159 /// \brief Truncate to new width.
1161 /// Truncate the APInt to a specified width. It is an error to specify a width
1162 /// that is greater than or equal to the current width.
1163 APInt LLVM_ATTRIBUTE_UNUSED_RESULT trunc(unsigned width) const;
1165 /// \brief Sign extend to a new width.
1167 /// This operation sign extends the APInt to a new width. If the high order
1168 /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
1169 /// It is an error to specify a width that is less than or equal to the
1171 APInt LLVM_ATTRIBUTE_UNUSED_RESULT sext(unsigned width) const;
1173 /// \brief Zero extend to a new width.
1175 /// This operation zero extends the APInt to a new width. The high order bits
1176 /// are filled with 0 bits. It is an error to specify a width that is less
1177 /// than or equal to the current width.
1178 APInt LLVM_ATTRIBUTE_UNUSED_RESULT zext(unsigned width) const;
1180 /// \brief Sign extend or truncate to width
1182 /// Make this APInt have the bit width given by \p width. The value is sign
1183 /// extended, truncated, or left alone to make it that width.
1184 APInt LLVM_ATTRIBUTE_UNUSED_RESULT sextOrTrunc(unsigned width) const;
1186 /// \brief Zero extend or truncate to width
1188 /// Make this APInt have the bit width given by \p width. The value is zero
1189 /// extended, truncated, or left alone to make it that width.
1190 APInt LLVM_ATTRIBUTE_UNUSED_RESULT zextOrTrunc(unsigned width) const;
1192 /// \brief Sign extend or truncate to width
1194 /// Make this APInt have the bit width given by \p width. The value is sign
1195 /// extended, or left alone to make it that width.
1196 APInt LLVM_ATTRIBUTE_UNUSED_RESULT sextOrSelf(unsigned width) const;
1198 /// \brief Zero extend or truncate to width
1200 /// Make this APInt have the bit width given by \p width. The value is zero
1201 /// extended, or left alone to make it that width.
1202 APInt LLVM_ATTRIBUTE_UNUSED_RESULT zextOrSelf(unsigned width) const;
1205 /// \name Bit Manipulation Operators
1208 /// \brief Set every bit to 1.
1213 // Set all the bits in all the words.
1214 for (unsigned i = 0; i < getNumWords(); ++i)
1215 pVal[i] = UINT64_MAX;
1217 // Clear the unused ones
1221 /// \brief Set a given bit to 1.
1223 /// Set the given bit to 1 whose position is given as "bitPosition".
1224 void setBit(unsigned bitPosition);
1226 /// \brief Set every bit to 0.
1227 void clearAllBits() {
1231 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
1234 /// \brief Set a given bit to 0.
1236 /// Set the given bit to 0 whose position is given as "bitPosition".
1237 void clearBit(unsigned bitPosition);
1239 /// \brief Toggle every bit to its opposite value.
1240 void flipAllBits() {
1244 for (unsigned i = 0; i < getNumWords(); ++i)
1245 pVal[i] ^= UINT64_MAX;
1250 /// \brief Toggles a given bit to its opposite value.
1252 /// Toggle a given bit to its opposite value whose position is given
1253 /// as "bitPosition".
1254 void flipBit(unsigned bitPosition);
1257 /// \name Value Characterization Functions
1260 /// \brief Return the number of bits in the APInt.
1261 unsigned getBitWidth() const { return BitWidth; }
1263 /// \brief Get the number of words.
1265 /// Here one word's bitwidth equals to that of uint64_t.
1267 /// \returns the number of words to hold the integer value of this APInt.
1268 unsigned getNumWords() const { return getNumWords(BitWidth); }
1270 /// \brief Get the number of words.
1272 /// *NOTE* Here one word's bitwidth equals to that of uint64_t.
1274 /// \returns the number of words to hold the integer value with a given bit
1276 static unsigned getNumWords(unsigned BitWidth) {
1277 return ((uint64_t)BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
1280 /// \brief Compute the number of active bits in the value
1282 /// This function returns the number of active bits which is defined as the
1283 /// bit width minus the number of leading zeros. This is used in several
1284 /// computations to see how "wide" the value is.
1285 unsigned getActiveBits() const { return BitWidth - countLeadingZeros(); }
1287 /// \brief Compute the number of active words in the value of this APInt.
1289 /// This is used in conjunction with getActiveData to extract the raw value of
1291 unsigned getActiveWords() const {
1292 unsigned numActiveBits = getActiveBits();
1293 return numActiveBits ? whichWord(numActiveBits - 1) + 1 : 1;
1296 /// \brief Get the minimum bit size for this signed APInt
1298 /// Computes the minimum bit width for this APInt while considering it to be a
1299 /// signed (and probably negative) value. If the value is not negative, this
1300 /// function returns the same value as getActiveBits()+1. Otherwise, it
1301 /// returns the smallest bit width that will retain the negative value. For
1302 /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
1303 /// for -1, this function will always return 1.
1304 unsigned getMinSignedBits() const {
1306 return BitWidth - countLeadingOnes() + 1;
1307 return getActiveBits() + 1;
1310 /// \brief Get zero extended value
1312 /// This method attempts to return the value of this APInt as a zero extended
1313 /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
1314 /// uint64_t. Otherwise an assertion will result.
1315 uint64_t getZExtValue() const {
1318 assert(getActiveBits() <= 64 && "Too many bits for uint64_t");
1322 /// \brief Get sign extended value
1324 /// This method attempts to return the value of this APInt as a sign extended
1325 /// int64_t. The bit width must be <= 64 or the value must fit within an
1326 /// int64_t. Otherwise an assertion will result.
1327 int64_t getSExtValue() const {
1329 return int64_t(VAL << (APINT_BITS_PER_WORD - BitWidth)) >>
1330 (APINT_BITS_PER_WORD - BitWidth);
1331 assert(getMinSignedBits() <= 64 && "Too many bits for int64_t");
1332 return int64_t(pVal[0]);
1335 /// \brief Get bits required for string value.
1337 /// This method determines how many bits are required to hold the APInt
1338 /// equivalent of the string given by \p str.
1339 static unsigned getBitsNeeded(StringRef str, uint8_t radix);
1341 /// \brief The APInt version of the countLeadingZeros functions in
1344 /// It counts the number of zeros from the most significant bit to the first
1347 /// \returns BitWidth if the value is zero, otherwise returns the number of
1348 /// zeros from the most significant bit to the first one bits.
1349 unsigned countLeadingZeros() const {
1350 if (isSingleWord()) {
1351 unsigned unusedBits = APINT_BITS_PER_WORD - BitWidth;
1352 return llvm::countLeadingZeros(VAL) - unusedBits;
1354 return countLeadingZerosSlowCase();
1357 /// \brief Count the number of leading one bits.
1359 /// This function is an APInt version of the countLeadingOnes_{32,64}
1360 /// functions in MathExtras.h. It counts the number of ones from the most
1361 /// significant bit to the first zero bit.
1363 /// \returns 0 if the high order bit is not set, otherwise returns the number
1364 /// of 1 bits from the most significant to the least
1365 unsigned countLeadingOnes() const;
1367 /// Computes the number of leading bits of this APInt that are equal to its
1369 unsigned getNumSignBits() const {
1370 return isNegative() ? countLeadingOnes() : countLeadingZeros();
1373 /// \brief Count the number of trailing zero bits.
1375 /// This function is an APInt version of the countTrailingZeros_{32,64}
1376 /// functions in MathExtras.h. It counts the number of zeros from the least
1377 /// significant bit to the first set bit.
1379 /// \returns BitWidth if the value is zero, otherwise returns the number of
1380 /// zeros from the least significant bit to the first one bit.
1381 unsigned countTrailingZeros() const;
1383 /// \brief Count the number of trailing one bits.
1385 /// This function is an APInt version of the countTrailingOnes_{32,64}
1386 /// functions in MathExtras.h. It counts the number of ones from the least
1387 /// significant bit to the first zero bit.
1389 /// \returns BitWidth if the value is all ones, otherwise returns the number
1390 /// of ones from the least significant bit to the first zero bit.
1391 unsigned countTrailingOnes() const {
1393 return CountTrailingOnes_64(VAL);
1394 return countTrailingOnesSlowCase();
1397 /// \brief Count the number of bits set.
1399 /// This function is an APInt version of the countPopulation_{32,64} functions
1400 /// in MathExtras.h. It counts the number of 1 bits in the APInt value.
1402 /// \returns 0 if the value is zero, otherwise returns the number of set bits.
1403 unsigned countPopulation() const {
1405 return CountPopulation_64(VAL);
1406 return countPopulationSlowCase();
1410 /// \name Conversion Functions
1412 void print(raw_ostream &OS, bool isSigned) const;
1414 /// Converts an APInt to a string and append it to Str. Str is commonly a
1416 void toString(SmallVectorImpl<char> &Str, unsigned Radix, bool Signed,
1417 bool formatAsCLiteral = false) const;
1419 /// Considers the APInt to be unsigned and converts it into a string in the
1420 /// radix given. The radix can be 2, 8, 10 16, or 36.
1421 void toStringUnsigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1422 toString(Str, Radix, false, false);
1425 /// Considers the APInt to be signed and converts it into a string in the
1426 /// radix given. The radix can be 2, 8, 10, 16, or 36.
1427 void toStringSigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1428 toString(Str, Radix, true, false);
1431 /// \brief Return the APInt as a std::string.
1433 /// Note that this is an inefficient method. It is better to pass in a
1434 /// SmallVector/SmallString to the methods above to avoid thrashing the heap
1436 std::string toString(unsigned Radix, bool Signed) const;
1438 /// \returns a byte-swapped representation of this APInt Value.
1439 APInt LLVM_ATTRIBUTE_UNUSED_RESULT byteSwap() const;
1441 /// \brief Converts this APInt to a double value.
1442 double roundToDouble(bool isSigned) const;
1444 /// \brief Converts this unsigned APInt to a double value.
1445 double roundToDouble() const { return roundToDouble(false); }
1447 /// \brief Converts this signed APInt to a double value.
1448 double signedRoundToDouble() const { return roundToDouble(true); }
1450 /// \brief Converts APInt bits to a double
1452 /// The conversion does not do a translation from integer to double, it just
1453 /// re-interprets the bits as a double. Note that it is valid to do this on
1454 /// any bit width. Exactly 64 bits will be translated.
1455 double bitsToDouble() const {
1460 T.I = (isSingleWord() ? VAL : pVal[0]);
1464 /// \brief Converts APInt bits to a double
1466 /// The conversion does not do a translation from integer to float, it just
1467 /// re-interprets the bits as a float. Note that it is valid to do this on
1468 /// any bit width. Exactly 32 bits will be translated.
1469 float bitsToFloat() const {
1474 T.I = unsigned((isSingleWord() ? VAL : pVal[0]));
1478 /// \brief Converts a double to APInt bits.
1480 /// The conversion does not do a translation from double to integer, it just
1481 /// re-interprets the bits of the double.
1482 static APInt LLVM_ATTRIBUTE_UNUSED_RESULT doubleToBits(double V) {
1488 return APInt(sizeof T * CHAR_BIT, T.I);
1491 /// \brief Converts a float to APInt bits.
1493 /// The conversion does not do a translation from float to integer, it just
1494 /// re-interprets the bits of the float.
1495 static APInt LLVM_ATTRIBUTE_UNUSED_RESULT floatToBits(float V) {
1501 return APInt(sizeof T * CHAR_BIT, T.I);
1505 /// \name Mathematics Operations
1508 /// \returns the floor log base 2 of this APInt.
1509 unsigned logBase2() const { return BitWidth - 1 - countLeadingZeros(); }
1511 /// \returns the ceil log base 2 of this APInt.
1512 unsigned ceilLogBase2() const {
1513 return BitWidth - (*this - 1).countLeadingZeros();
1516 /// \returns the nearest log base 2 of this APInt. Ties round up.
1518 /// NOTE: When we have a BitWidth of 1, we define:
1520 /// log2(0) = UINT32_MAX
1523 /// to get around any mathematical concerns resulting from
1524 /// referencing 2 in a space where 2 does no exist.
1525 unsigned nearestLogBase2() const {
1526 // Special case when we have a bitwidth of 1. If VAL is 1, then we
1527 // get 0. If VAL is 0, we get UINT64_MAX which gets truncated to
1532 // Handle the zero case.
1533 if (!getBoolValue())
1536 // The non-zero case is handled by computing:
1538 // nearestLogBase2(x) = logBase2(x) + x[logBase2(x)-1].
1540 // where x[i] is referring to the value of the ith bit of x.
1541 unsigned lg = logBase2();
1542 return lg + unsigned((*this)[lg - 1]);
1545 /// \returns the log base 2 of this APInt if its an exact power of two, -1
1547 int32_t exactLogBase2() const {
1553 /// \brief Compute the square root
1554 APInt LLVM_ATTRIBUTE_UNUSED_RESULT sqrt() const;
1556 /// \brief Get the absolute value;
1558 /// If *this is < 0 then return -(*this), otherwise *this;
1559 APInt LLVM_ATTRIBUTE_UNUSED_RESULT abs() const {
1565 /// \returns the multiplicative inverse for a given modulo.
1566 APInt multiplicativeInverse(const APInt &modulo) const;
1569 /// \name Support for division by constant
1572 /// Calculate the magic number for signed division by a constant.
1576 /// Calculate the magic number for unsigned division by a constant.
1578 mu magicu(unsigned LeadingZeros = 0) const;
1581 /// \name Building-block Operations for APInt and APFloat
1584 // These building block operations operate on a representation of arbitrary
1585 // precision, two's-complement, bignum integer values. They should be
1586 // sufficient to implement APInt and APFloat bignum requirements. Inputs are
1587 // generally a pointer to the base of an array of integer parts, representing
1588 // an unsigned bignum, and a count of how many parts there are.
1590 /// Sets the least significant part of a bignum to the input value, and zeroes
1591 /// out higher parts.
1592 static void tcSet(integerPart *, integerPart, unsigned int);
1594 /// Assign one bignum to another.
1595 static void tcAssign(integerPart *, const integerPart *, unsigned int);
1597 /// Returns true if a bignum is zero, false otherwise.
1598 static bool tcIsZero(const integerPart *, unsigned int);
1600 /// Extract the given bit of a bignum; returns 0 or 1. Zero-based.
1601 static int tcExtractBit(const integerPart *, unsigned int bit);
1603 /// Copy the bit vector of width srcBITS from SRC, starting at bit srcLSB, to
1604 /// DST, of dstCOUNT parts, such that the bit srcLSB becomes the least
1605 /// significant bit of DST. All high bits above srcBITS in DST are
1607 static void tcExtract(integerPart *, unsigned int dstCount,
1608 const integerPart *, unsigned int srcBits,
1609 unsigned int srcLSB);
1611 /// Set the given bit of a bignum. Zero-based.
1612 static void tcSetBit(integerPart *, unsigned int bit);
1614 /// Clear the given bit of a bignum. Zero-based.
1615 static void tcClearBit(integerPart *, unsigned int bit);
1617 /// Returns the bit number of the least or most significant set bit of a
1618 /// number. If the input number has no bits set -1U is returned.
1619 static unsigned int tcLSB(const integerPart *, unsigned int);
1620 static unsigned int tcMSB(const integerPart *parts, unsigned int n);
1622 /// Negate a bignum in-place.
1623 static void tcNegate(integerPart *, unsigned int);
1625 /// DST += RHS + CARRY where CARRY is zero or one. Returns the carry flag.
1626 static integerPart tcAdd(integerPart *, const integerPart *,
1627 integerPart carry, unsigned);
1629 /// DST -= RHS + CARRY where CARRY is zero or one. Returns the carry flag.
1630 static integerPart tcSubtract(integerPart *, const integerPart *,
1631 integerPart carry, unsigned);
1633 /// DST += SRC * MULTIPLIER + PART if add is true
1634 /// DST = SRC * MULTIPLIER + PART if add is false
1636 /// Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC they must
1637 /// start at the same point, i.e. DST == SRC.
1639 /// If DSTPARTS == SRC_PARTS + 1 no overflow occurs and zero is returned.
1640 /// Otherwise DST is filled with the least significant DSTPARTS parts of the
1641 /// result, and if all of the omitted higher parts were zero return zero,
1642 /// otherwise overflow occurred and return one.
1643 static int tcMultiplyPart(integerPart *dst, const integerPart *src,
1644 integerPart multiplier, integerPart carry,
1645 unsigned int srcParts, unsigned int dstParts,
1648 /// DST = LHS * RHS, where DST has the same width as the operands and is
1649 /// filled with the least significant parts of the result. Returns one if
1650 /// overflow occurred, otherwise zero. DST must be disjoint from both
1652 static int tcMultiply(integerPart *, const integerPart *, const integerPart *,
1655 /// DST = LHS * RHS, where DST has width the sum of the widths of the
1656 /// operands. No overflow occurs. DST must be disjoint from both
1657 /// operands. Returns the number of parts required to hold the result.
1658 static unsigned int tcFullMultiply(integerPart *, const integerPart *,
1659 const integerPart *, unsigned, unsigned);
1661 /// If RHS is zero LHS and REMAINDER are left unchanged, return one.
1662 /// Otherwise set LHS to LHS / RHS with the fractional part discarded, set
1663 /// REMAINDER to the remainder, return zero. i.e.
1665 /// OLD_LHS = RHS * LHS + REMAINDER
1667 /// SCRATCH is a bignum of the same size as the operands and result for use by
1668 /// the routine; its contents need not be initialized and are destroyed. LHS,
1669 /// REMAINDER and SCRATCH must be distinct.
1670 static int tcDivide(integerPart *lhs, const integerPart *rhs,
1671 integerPart *remainder, integerPart *scratch,
1672 unsigned int parts);
1674 /// Shift a bignum left COUNT bits. Shifted in bits are zero. There are no
1675 /// restrictions on COUNT.
1676 static void tcShiftLeft(integerPart *, unsigned int parts,
1677 unsigned int count);
1679 /// Shift a bignum right COUNT bits. Shifted in bits are zero. There are no
1680 /// restrictions on COUNT.
1681 static void tcShiftRight(integerPart *, unsigned int parts,
1682 unsigned int count);
1684 /// The obvious AND, OR and XOR and complement operations.
1685 static void tcAnd(integerPart *, const integerPart *, unsigned int);
1686 static void tcOr(integerPart *, const integerPart *, unsigned int);
1687 static void tcXor(integerPart *, const integerPart *, unsigned int);
1688 static void tcComplement(integerPart *, unsigned int);
1690 /// Comparison (unsigned) of two bignums.
1691 static int tcCompare(const integerPart *, const integerPart *, unsigned int);
1693 /// Increment a bignum in-place. Return the carry flag.
1694 static integerPart tcIncrement(integerPart *, unsigned int);
1696 /// Decrement a bignum in-place. Return the borrow flag.
1697 static integerPart tcDecrement(integerPart *, unsigned int);
1699 /// Set the least significant BITS and clear the rest.
1700 static void tcSetLeastSignificantBits(integerPart *, unsigned int,
1703 /// \brief debug method
1709 /// Magic data for optimising signed division by a constant.
1711 APInt m; ///< magic number
1712 unsigned s; ///< shift amount
1715 /// Magic data for optimising unsigned division by a constant.
1717 APInt m; ///< magic number
1718 bool a; ///< add indicator
1719 unsigned s; ///< shift amount
1722 inline bool operator==(uint64_t V1, const APInt &V2) { return V2 == V1; }
1724 inline bool operator!=(uint64_t V1, const APInt &V2) { return V2 != V1; }
1726 inline raw_ostream &operator<<(raw_ostream &OS, const APInt &I) {
1731 namespace APIntOps {
1733 /// \brief Determine the smaller of two APInts considered to be signed.
1734 inline APInt smin(const APInt &A, const APInt &B) { return A.slt(B) ? A : B; }
1736 /// \brief Determine the larger of two APInts considered to be signed.
1737 inline APInt smax(const APInt &A, const APInt &B) { return A.sgt(B) ? A : B; }
1739 /// \brief Determine the smaller of two APInts considered to be signed.
1740 inline APInt umin(const APInt &A, const APInt &B) { return A.ult(B) ? A : B; }
1742 /// \brief Determine the larger of two APInts considered to be unsigned.
1743 inline APInt umax(const APInt &A, const APInt &B) { return A.ugt(B) ? A : B; }
1745 /// \brief Check if the specified APInt has a N-bits unsigned integer value.
1746 inline bool isIntN(unsigned N, const APInt &APIVal) { return APIVal.isIntN(N); }
1748 /// \brief Check if the specified APInt has a N-bits signed integer value.
1749 inline bool isSignedIntN(unsigned N, const APInt &APIVal) {
1750 return APIVal.isSignedIntN(N);
1753 /// \returns true if the argument APInt value is a sequence of ones starting at
1754 /// the least significant bit with the remainder zero.
1755 inline bool isMask(unsigned numBits, const APInt &APIVal) {
1756 return numBits <= APIVal.getBitWidth() &&
1757 APIVal == APInt::getLowBitsSet(APIVal.getBitWidth(), numBits);
1760 /// \brief Return true if the argument APInt value contains a sequence of ones
1761 /// with the remainder zero.
1762 inline bool isShiftedMask(unsigned numBits, const APInt &APIVal) {
1763 return isMask(numBits, (APIVal - APInt(numBits, 1)) | APIVal);
1766 /// \brief Returns a byte-swapped representation of the specified APInt Value.
1767 inline APInt byteSwap(const APInt &APIVal) { return APIVal.byteSwap(); }
1769 /// \brief Returns the floor log base 2 of the specified APInt value.
1770 inline unsigned logBase2(const APInt &APIVal) { return APIVal.logBase2(); }
1772 /// \brief Compute GCD of two APInt values.
1774 /// This function returns the greatest common divisor of the two APInt values
1775 /// using Euclid's algorithm.
1777 /// \returns the greatest common divisor of Val1 and Val2
1778 APInt GreatestCommonDivisor(const APInt &Val1, const APInt &Val2);
1780 /// \brief Converts the given APInt to a double value.
1782 /// Treats the APInt as an unsigned value for conversion purposes.
1783 inline double RoundAPIntToDouble(const APInt &APIVal) {
1784 return APIVal.roundToDouble();
1787 /// \brief Converts the given APInt to a double value.
1789 /// Treats the APInt as a signed value for conversion purposes.
1790 inline double RoundSignedAPIntToDouble(const APInt &APIVal) {
1791 return APIVal.signedRoundToDouble();
1794 /// \brief Converts the given APInt to a float vlalue.
1795 inline float RoundAPIntToFloat(const APInt &APIVal) {
1796 return float(RoundAPIntToDouble(APIVal));
1799 /// \brief Converts the given APInt to a float value.
1801 /// Treast the APInt as a signed value for conversion purposes.
1802 inline float RoundSignedAPIntToFloat(const APInt &APIVal) {
1803 return float(APIVal.signedRoundToDouble());
1806 /// \brief Converts the given double value into a APInt.
1808 /// This function convert a double value to an APInt value.
1809 APInt RoundDoubleToAPInt(double Double, unsigned width);
1811 /// \brief Converts a float value into a APInt.
1813 /// Converts a float value into an APInt value.
1814 inline APInt RoundFloatToAPInt(float Float, unsigned width) {
1815 return RoundDoubleToAPInt(double(Float), width);
1818 /// \brief Arithmetic right-shift function.
1820 /// Arithmetic right-shift the APInt by shiftAmt.
1821 inline APInt ashr(const APInt &LHS, unsigned shiftAmt) {
1822 return LHS.ashr(shiftAmt);
1825 /// \brief Logical right-shift function.
1827 /// Logical right-shift the APInt by shiftAmt.
1828 inline APInt lshr(const APInt &LHS, unsigned shiftAmt) {
1829 return LHS.lshr(shiftAmt);
1832 /// \brief Left-shift function.
1834 /// Left-shift the APInt by shiftAmt.
1835 inline APInt shl(const APInt &LHS, unsigned shiftAmt) {
1836 return LHS.shl(shiftAmt);
1839 /// \brief Signed division function for APInt.
1841 /// Signed divide APInt LHS by APInt RHS.
1842 inline APInt sdiv(const APInt &LHS, const APInt &RHS) { return LHS.sdiv(RHS); }
1844 /// \brief Unsigned division function for APInt.
1846 /// Unsigned divide APInt LHS by APInt RHS.
1847 inline APInt udiv(const APInt &LHS, const APInt &RHS) { return LHS.udiv(RHS); }
1849 /// \brief Function for signed remainder operation.
1851 /// Signed remainder operation on APInt.
1852 inline APInt srem(const APInt &LHS, const APInt &RHS) { return LHS.srem(RHS); }
1854 /// \brief Function for unsigned remainder operation.
1856 /// Unsigned remainder operation on APInt.
1857 inline APInt urem(const APInt &LHS, const APInt &RHS) { return LHS.urem(RHS); }
1859 /// \brief Function for multiplication operation.
1861 /// Performs multiplication on APInt values.
1862 inline APInt mul(const APInt &LHS, const APInt &RHS) { return LHS * RHS; }
1864 /// \brief Function for addition operation.
1866 /// Performs addition on APInt values.
1867 inline APInt add(const APInt &LHS, const APInt &RHS) { return LHS + RHS; }
1869 /// \brief Function for subtraction operation.
1871 /// Performs subtraction on APInt values.
1872 inline APInt sub(const APInt &LHS, const APInt &RHS) { return LHS - RHS; }
1874 /// \brief Bitwise AND function for APInt.
1876 /// Performs bitwise AND operation on APInt LHS and
1878 inline APInt And(const APInt &LHS, const APInt &RHS) { return LHS & RHS; }
1880 /// \brief Bitwise OR function for APInt.
1882 /// Performs bitwise OR operation on APInt LHS and APInt RHS.
1883 inline APInt Or(const APInt &LHS, const APInt &RHS) { return LHS | RHS; }
1885 /// \brief Bitwise XOR function for APInt.
1887 /// Performs bitwise XOR operation on APInt.
1888 inline APInt Xor(const APInt &LHS, const APInt &RHS) { return LHS ^ RHS; }
1890 /// \brief Bitwise complement function.
1892 /// Performs a bitwise complement operation on APInt.
1893 inline APInt Not(const APInt &APIVal) { return ~APIVal; }
1895 } // End of APIntOps namespace
1897 // See friend declaration above. This additional declaration is required in
1898 // order to compile LLVM with IBM xlC compiler.
1899 hash_code hash_value(const APInt &Arg);
1900 } // End of llvm namespace