1 //===-- llvm/Support/APInt.h - For Arbitrary Precision Integer -*- C++ -*--===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Sheng Zhou and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a class to represent arbitrary precision integral
11 // constant values and operations on them.
13 //===----------------------------------------------------------------------===//
18 #include "llvm/Support/DataTypes.h"
22 #define HOST_CHAR_BIT 8
23 #define compileTimeAssert(cond) extern int CTAssert[(cond) ? 1 : -1]
24 #define integerPartWidth (HOST_CHAR_BIT * sizeof(llvm::integerPart))
28 /* An unsigned host type used as a single part of a multi-part
30 typedef uint64_t integerPart;
32 //===----------------------------------------------------------------------===//
34 //===----------------------------------------------------------------------===//
36 /// APInt - This class represents arbitrary precision constant integral values.
37 /// It is a functional replacement for common case unsigned integer type like
38 /// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width
39 /// integer sizes and large integer value types such as 3-bits, 15-bits, or more
40 /// than 64-bits of precision. APInt provides a variety of arithmetic operators
41 /// and methods to manipulate integer values of any bit-width. It supports both
42 /// the typical integer arithmetic and comparison operations as well as bitwise
45 /// The class has several invariants worth noting:
46 /// * All bit, byte, and word positions are zero-based.
47 /// * Once the bit width is set, it doesn't change except by the Truncate,
48 /// SignExtend, or ZeroExtend operations.
49 /// * All binary operators must be on APInt instances of the same bit width.
50 /// Attempting to use these operators on instances with different bit
51 /// widths will yield an assertion.
52 /// * The value is stored canonically as an unsigned value. For operations
53 /// where it makes a difference, there are both signed and unsigned variants
54 /// of the operation. For example, sdiv and udiv. However, because the bit
55 /// widths must be the same, operations such as Mul and Add produce the same
56 /// results regardless of whether the values are interpreted as signed or
58 /// * In general, the class tries to follow the style of computation that LLVM
59 /// uses in its IR. This simplifies its use for LLVM.
61 /// @brief Class for arbitrary precision integers.
64 uint32_t BitWidth; ///< The number of bits in this APInt.
66 /// This union is used to store the integer value. When the
67 /// integer bit-width <= 64, it uses VAL, otherwise it uses pVal.
69 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
70 uint64_t *pVal; ///< Used to store the >64 bits integer value.
73 /// This enum is used to hold the constants we needed for APInt.
75 APINT_BITS_PER_WORD = sizeof(uint64_t) * 8, ///< Bits in a word
76 APINT_WORD_SIZE = sizeof(uint64_t) ///< Byte size of a word
79 /// This constructor is used only internally for speed of construction of
80 /// temporaries. It is unsafe for general use so it is not public.
81 /// @brief Fast internal constructor
82 APInt(uint64_t* val, uint32_t bits) : BitWidth(bits), pVal(val) { }
84 /// @returns true if the number of bits <= 64, false otherwise.
85 /// @brief Determine if this APInt just has one word to store value.
86 inline bool isSingleWord() const {
87 return BitWidth <= APINT_BITS_PER_WORD;
90 /// @returns the word position for the specified bit position.
91 /// @brief Determine which word a bit is in.
92 static inline uint32_t whichWord(uint32_t bitPosition) {
93 return bitPosition / APINT_BITS_PER_WORD;
96 /// @returns the bit position in a word for the specified bit position
98 /// @brief Determine which bit in a word a bit is in.
99 static inline uint32_t whichBit(uint32_t bitPosition) {
100 return bitPosition % APINT_BITS_PER_WORD;
103 /// This method generates and returns a uint64_t (word) mask for a single
104 /// bit at a specific bit position. This is used to mask the bit in the
105 /// corresponding word.
106 /// @returns a uint64_t with only bit at "whichBit(bitPosition)" set
107 /// @brief Get a single bit mask.
108 static inline uint64_t maskBit(uint32_t bitPosition) {
109 return 1ULL << whichBit(bitPosition);
112 /// This method is used internally to clear the to "N" bits in the high order
113 /// word that are not used by the APInt. This is needed after the most
114 /// significant word is assigned a value to ensure that those bits are
116 /// @brief Clear unused high order bits
117 inline APInt& clearUnusedBits() {
118 // Compute how many bits are used in the final word
119 uint32_t wordBits = BitWidth % APINT_BITS_PER_WORD;
121 // If all bits are used, we want to leave the value alone. This also
122 // avoids the undefined behavior of >> when the shfit is the same size as
123 // the word size (64).
126 // Mask out the hight bits.
127 uint64_t mask = ~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - wordBits);
131 pVal[getNumWords() - 1] &= mask;
135 /// @returns the corresponding word for the specified bit position.
136 /// @brief Get the word corresponding to a bit position
137 inline uint64_t getWord(uint32_t bitPosition) const {
138 return isSingleWord() ? VAL : pVal[whichWord(bitPosition)];
141 /// This is used by the constructors that take string arguments.
142 /// @brief Convert a char array into an APInt
143 void fromString(uint32_t numBits, const char *strStart, uint32_t slen,
146 /// This is used by the toString method to divide by the radix. It simply
147 /// provides a more convenient form of divide for internal use since KnuthDiv
148 /// has specific constraints on its inputs. If those constraints are not met
149 /// then it provides a simpler form of divide.
150 /// @brief An internal division function for dividing APInts.
151 static void divide(const APInt LHS, uint32_t lhsWords,
152 const APInt &RHS, uint32_t rhsWords,
153 APInt *Quotient, APInt *Remainder);
156 /// @brief debug method
161 /// @name Constructors
163 /// If isSigned is true then val is treated as if it were a signed value
164 /// (i.e. as an int64_t) and the appropriate sign extension to the bit width
165 /// will be done. Otherwise, no sign extension occurs (high order bits beyond
166 /// the range of val are zero filled).
167 /// @param numBits the bit width of the constructed APInt
168 /// @param val the initial value of the APInt
169 /// @param isSigned how to treat signedness of val
170 /// @brief Create a new APInt of numBits width, initialized as val.
171 APInt(uint32_t numBits, uint64_t val, bool isSigned = false);
173 /// Note that numWords can be smaller or larger than the corresponding bit
174 /// width but any extraneous bits will be dropped.
175 /// @param numBits the bit width of the constructed APInt
176 /// @param numWords the number of words in bigVal
177 /// @param bigVal a sequence of words to form the initial value of the APInt
178 /// @brief Construct an APInt of numBits width, initialized as bigVal[].
179 APInt(uint32_t numBits, uint32_t numWords, uint64_t bigVal[]);
181 /// This constructor interprets Val as a string in the given radix. The
182 /// interpretation stops when the first charater that is not suitable for the
183 /// radix is encountered. Acceptable radix values are 2, 8, 10 and 16. It is
184 /// an error for the value implied by the string to require more bits than
186 /// @param numBits the bit width of the constructed APInt
187 /// @param val the string to be interpreted
188 /// @param radix the radix of Val to use for the intepretation
189 /// @brief Construct an APInt from a string representation.
190 APInt(uint32_t numBits, const std::string& val, uint8_t radix);
192 /// This constructor interprets the slen characters starting at StrStart as
193 /// a string in the given radix. The interpretation stops when the first
194 /// character that is not suitable for the radix is encountered. Acceptable
195 /// radix values are 2, 8, 10 and 16. It is an error for the value implied by
196 /// the string to require more bits than numBits.
197 /// @param numBits the bit width of the constructed APInt
198 /// @param strStart the start of the string to be interpreted
199 /// @param slen the maximum number of characters to interpret
200 /// @param radix the radix to use for the conversion
201 /// @brief Construct an APInt from a string representation.
202 APInt(uint32_t numBits, const char strStart[], uint32_t slen, uint8_t radix);
204 /// Simply makes *this a copy of that.
205 /// @brief Copy Constructor.
206 APInt(const APInt& that);
208 /// @brief Destructor.
212 /// @name Value Tests
214 /// This tests the high bit of this APInt to determine if it is set.
215 /// @returns true if this APInt is negative, false otherwise
216 /// @brief Determine sign of this APInt.
217 bool isNegative() const {
218 return (*this)[BitWidth - 1];
221 /// This tests the high bit of the APInt to determine if it is unset.
222 /// @brief Determine if this APInt Value is positive (not negative).
223 bool isPositive() const {
224 return !isNegative();
227 /// This tests if the value of this APInt is strictly positive (> 0).
228 /// @returns true if this APInt is Positive and not zero.
229 /// @brief Determine if this APInt Value is strictly positive.
230 inline bool isStrictlyPositive() const {
231 return isPositive() && (*this) != 0;
234 /// This checks to see if the value has all bits of the APInt are set or not.
235 /// @brief Determine if all bits are set
236 inline bool isAllOnesValue() const {
237 return countPopulation() == BitWidth;
240 /// This checks to see if the value of this APInt is the maximum unsigned
241 /// value for the APInt's bit width.
242 /// @brief Determine if this is the largest unsigned value.
243 bool isMaxValue() const {
244 return countPopulation() == BitWidth;
247 /// This checks to see if the value of this APInt is the maximum signed
248 /// value for the APInt's bit width.
249 /// @brief Determine if this is the largest signed value.
250 bool isMaxSignedValue() const {
251 return BitWidth == 1 ? VAL == 0 :
252 !isNegative() && countPopulation() == BitWidth - 1;
255 /// This checks to see if the value of this APInt is the minimum unsigned
256 /// value for the APInt's bit width.
257 /// @brief Determine if this is the smallest unsigned value.
258 bool isMinValue() const {
259 return countPopulation() == 0;
262 /// This checks to see if the value of this APInt is the minimum signed
263 /// value for the APInt's bit width.
264 /// @brief Determine if this is the smallest signed value.
265 bool isMinSignedValue() const {
266 return BitWidth == 1 ? VAL == 1 :
267 isNegative() && countPopulation() == 1;
270 /// @brief Check if this APInt has an N-bits integer value.
271 inline bool isIntN(uint32_t N) const {
272 assert(N && "N == 0 ???");
273 if (isSingleWord()) {
274 return VAL == (VAL & (~0ULL >> (64 - N)));
276 APInt Tmp(N, getNumWords(), pVal);
277 return Tmp == (*this);
281 /// @returns true if the argument APInt value is a power of two > 0.
282 bool isPowerOf2() const;
284 /// isSignBit - Return true if this is the value returned by getSignBit.
285 bool isSignBit() const { return isMinSignedValue(); }
287 /// This converts the APInt to a boolean value as a test against zero.
288 /// @brief Boolean conversion function.
289 inline bool getBoolValue() const {
293 /// getLimitedValue - If this value is smaller than the specified limit,
294 /// return it, otherwise return the limit value. This causes the value
295 /// to saturate to the limit.
296 uint64_t getLimitedValue(uint64_t Limit = ~0ULL) const {
297 return (getActiveBits() > 64 || getZExtValue() > Limit) ?
298 Limit : getZExtValue();
302 /// @name Value Generators
304 /// @brief Gets maximum unsigned value of APInt for specific bit width.
305 static APInt getMaxValue(uint32_t numBits) {
306 return APInt(numBits, 0).set();
309 /// @brief Gets maximum signed value of APInt for a specific bit width.
310 static APInt getSignedMaxValue(uint32_t numBits) {
311 return APInt(numBits, 0).set().clear(numBits - 1);
314 /// @brief Gets minimum unsigned value of APInt for a specific bit width.
315 static APInt getMinValue(uint32_t numBits) {
316 return APInt(numBits, 0);
319 /// @brief Gets minimum signed value of APInt for a specific bit width.
320 static APInt getSignedMinValue(uint32_t numBits) {
321 return APInt(numBits, 0).set(numBits - 1);
324 /// getSignBit - This is just a wrapper function of getSignedMinValue(), and
325 /// it helps code readability when we want to get a SignBit.
326 /// @brief Get the SignBit for a specific bit width.
327 inline static APInt getSignBit(uint32_t BitWidth) {
328 return getSignedMinValue(BitWidth);
331 /// @returns the all-ones value for an APInt of the specified bit-width.
332 /// @brief Get the all-ones value.
333 static APInt getAllOnesValue(uint32_t numBits) {
334 return APInt(numBits, 0).set();
337 /// @returns the '0' value for an APInt of the specified bit-width.
338 /// @brief Get the '0' value.
339 static APInt getNullValue(uint32_t numBits) {
340 return APInt(numBits, 0);
343 /// Get an APInt with the same BitWidth as this APInt, just zero mask
344 /// the low bits and right shift to the least significant bit.
345 /// @returns the high "numBits" bits of this APInt.
346 APInt getHiBits(uint32_t numBits) const;
348 /// Get an APInt with the same BitWidth as this APInt, just zero mask
350 /// @returns the low "numBits" bits of this APInt.
351 APInt getLoBits(uint32_t numBits) const;
353 /// Constructs an APInt value that has a contiguous range of bits set. The
354 /// bits from loBit to hiBit will be set. All other bits will be zero. For
355 /// example, with parameters(32, 15, 0) you would get 0x0000FFFF. If hiBit is
356 /// less than loBit then the set bits "wrap". For example, with
357 /// parameters (32, 3, 28), you would get 0xF000000F.
358 /// @param numBits the intended bit width of the result
359 /// @param loBit the index of the lowest bit set.
360 /// @param hiBit the index of the highest bit set.
361 /// @returns An APInt value with the requested bits set.
362 /// @brief Get a value with a block of bits set.
363 static APInt getBitsSet(uint32_t numBits, uint32_t loBit, uint32_t hiBit) {
364 assert(hiBit < numBits && "hiBit out of range");
365 assert(loBit < numBits && "loBit out of range");
367 return getLowBitsSet(numBits, hiBit+1) |
368 getHighBitsSet(numBits, numBits-loBit+1);
369 return getLowBitsSet(numBits, hiBit-loBit+1).shl(loBit);
372 /// Constructs an APInt value that has the top hiBitsSet bits set.
373 /// @param numBits the bitwidth of the result
374 /// @param hiBitsSet the number of high-order bits set in the result.
375 /// @brief Get a value with high bits set
376 static APInt getHighBitsSet(uint32_t numBits, uint32_t hiBitsSet) {
377 assert(hiBitsSet <= numBits && "Too many bits to set!");
378 // Handle a degenerate case, to avoid shifting by word size
380 return APInt(numBits, 0);
381 uint32_t shiftAmt = numBits - hiBitsSet;
382 // For small values, return quickly
383 if (numBits <= APINT_BITS_PER_WORD)
384 return APInt(numBits, ~0ULL << shiftAmt);
385 return (~APInt(numBits, 0)).shl(shiftAmt);
388 /// Constructs an APInt value that has the bottom loBitsSet bits set.
389 /// @param numBits the bitwidth of the result
390 /// @param loBitsSet the number of low-order bits set in the result.
391 /// @brief Get a value with low bits set
392 static APInt getLowBitsSet(uint32_t numBits, uint32_t loBitsSet) {
393 assert(loBitsSet <= numBits && "Too many bits to set!");
394 // Handle a degenerate case, to avoid shifting by word size
396 return APInt(numBits, 0);
397 if (loBitsSet == APINT_BITS_PER_WORD)
398 return APInt(numBits, -1ULL);
399 // For small values, return quickly
400 if (numBits < APINT_BITS_PER_WORD)
401 return APInt(numBits, (1ULL << loBitsSet) - 1);
402 return (~APInt(numBits, 0)).lshr(numBits - loBitsSet);
405 /// The hash value is computed as the sum of the words and the bit width.
406 /// @returns A hash value computed from the sum of the APInt words.
407 /// @brief Get a hash value based on this APInt
408 uint64_t getHashValue() const;
410 /// This function returns a pointer to the internal storage of the APInt.
411 /// This is useful for writing out the APInt in binary form without any
413 inline const uint64_t* getRawData() const {
420 /// @name Unary Operators
422 /// @returns a new APInt value representing *this incremented by one
423 /// @brief Postfix increment operator.
424 inline const APInt operator++(int) {
430 /// @returns *this incremented by one
431 /// @brief Prefix increment operator.
434 /// @returns a new APInt representing *this decremented by one.
435 /// @brief Postfix decrement operator.
436 inline const APInt operator--(int) {
442 /// @returns *this decremented by one.
443 /// @brief Prefix decrement operator.
446 /// Performs a bitwise complement operation on this APInt.
447 /// @returns an APInt that is the bitwise complement of *this
448 /// @brief Unary bitwise complement operator.
449 APInt operator~() const;
451 /// Negates *this using two's complement logic.
452 /// @returns An APInt value representing the negation of *this.
453 /// @brief Unary negation operator
454 inline APInt operator-() const {
455 return APInt(BitWidth, 0) - (*this);
458 /// Performs logical negation operation on this APInt.
459 /// @returns true if *this is zero, false otherwise.
460 /// @brief Logical negation operator.
461 bool operator !() const;
464 /// @name Assignment Operators
466 /// @returns *this after assignment of RHS.
467 /// @brief Copy assignment operator.
468 APInt& operator=(const APInt& RHS);
470 /// The RHS value is assigned to *this. If the significant bits in RHS exceed
471 /// the bit width, the excess bits are truncated. If the bit width is larger
472 /// than 64, the value is zero filled in the unspecified high order bits.
473 /// @returns *this after assignment of RHS value.
474 /// @brief Assignment operator.
475 APInt& operator=(uint64_t RHS);
477 /// Performs a bitwise AND operation on this APInt and RHS. The result is
478 /// assigned to *this.
479 /// @returns *this after ANDing with RHS.
480 /// @brief Bitwise AND assignment operator.
481 APInt& operator&=(const APInt& RHS);
483 /// Performs a bitwise OR operation on this APInt and RHS. The result is
485 /// @returns *this after ORing with RHS.
486 /// @brief Bitwise OR assignment operator.
487 APInt& operator|=(const APInt& RHS);
489 /// Performs a bitwise XOR operation on this APInt and RHS. The result is
490 /// assigned to *this.
491 /// @returns *this after XORing with RHS.
492 /// @brief Bitwise XOR assignment operator.
493 APInt& operator^=(const APInt& RHS);
495 /// Multiplies this APInt by RHS and assigns the result to *this.
497 /// @brief Multiplication assignment operator.
498 APInt& operator*=(const APInt& RHS);
500 /// Adds RHS to *this and assigns the result to *this.
502 /// @brief Addition assignment operator.
503 APInt& operator+=(const APInt& RHS);
505 /// Subtracts RHS from *this and assigns the result to *this.
507 /// @brief Subtraction assignment operator.
508 APInt& operator-=(const APInt& RHS);
510 /// Shifts *this left by shiftAmt and assigns the result to *this.
511 /// @returns *this after shifting left by shiftAmt
512 /// @brief Left-shift assignment function.
513 inline APInt& operator<<=(uint32_t shiftAmt) {
514 *this = shl(shiftAmt);
519 /// @name Binary Operators
521 /// Performs a bitwise AND operation on *this and RHS.
522 /// @returns An APInt value representing the bitwise AND of *this and RHS.
523 /// @brief Bitwise AND operator.
524 APInt operator&(const APInt& RHS) const;
525 APInt And(const APInt& RHS) const {
526 return this->operator&(RHS);
529 /// Performs a bitwise OR operation on *this and RHS.
530 /// @returns An APInt value representing the bitwise OR of *this and RHS.
531 /// @brief Bitwise OR operator.
532 APInt operator|(const APInt& RHS) const;
533 APInt Or(const APInt& RHS) const {
534 return this->operator|(RHS);
537 /// Performs a bitwise XOR operation on *this and RHS.
538 /// @returns An APInt value representing the bitwise XOR of *this and RHS.
539 /// @brief Bitwise XOR operator.
540 APInt operator^(const APInt& RHS) const;
541 APInt Xor(const APInt& RHS) const {
542 return this->operator^(RHS);
545 /// Multiplies this APInt by RHS and returns the result.
546 /// @brief Multiplication operator.
547 APInt operator*(const APInt& RHS) const;
549 /// Adds RHS to this APInt and returns the result.
550 /// @brief Addition operator.
551 APInt operator+(const APInt& RHS) const;
552 APInt operator+(uint64_t RHS) const {
553 return (*this) + APInt(BitWidth, RHS);
556 /// Subtracts RHS from this APInt and returns the result.
557 /// @brief Subtraction operator.
558 APInt operator-(const APInt& RHS) const;
559 APInt operator-(uint64_t RHS) const {
560 return (*this) - APInt(BitWidth, RHS);
563 APInt operator<<(unsigned Bits) const {
567 /// Arithmetic right-shift this APInt by shiftAmt.
568 /// @brief Arithmetic right-shift function.
569 APInt ashr(uint32_t shiftAmt) const;
571 /// Logical right-shift this APInt by shiftAmt.
572 /// @brief Logical right-shift function.
573 APInt lshr(uint32_t shiftAmt) const;
575 /// Left-shift this APInt by shiftAmt.
576 /// @brief Left-shift function.
577 APInt shl(uint32_t shiftAmt) const;
579 /// @brief Rotate left by rotateAmt.
580 APInt rotl(uint32_t rotateAmt) const;
582 /// @brief Rotate right by rotateAmt.
583 APInt rotr(uint32_t rotateAmt) const;
585 /// Perform an unsigned divide operation on this APInt by RHS. Both this and
586 /// RHS are treated as unsigned quantities for purposes of this division.
587 /// @returns a new APInt value containing the division result
588 /// @brief Unsigned division operation.
589 APInt udiv(const APInt& RHS) const;
591 /// Signed divide this APInt by APInt RHS.
592 /// @brief Signed division function for APInt.
593 inline APInt sdiv(const APInt& RHS) const {
595 if (RHS.isNegative())
596 return (-(*this)).udiv(-RHS);
598 return -((-(*this)).udiv(RHS));
599 else if (RHS.isNegative())
600 return -(this->udiv(-RHS));
601 return this->udiv(RHS);
604 /// Perform an unsigned remainder operation on this APInt with RHS being the
605 /// divisor. Both this and RHS are treated as unsigned quantities for purposes
606 /// of this operation. Note that this is a true remainder operation and not
607 /// a modulo operation because the sign follows the sign of the dividend
609 /// @returns a new APInt value containing the remainder result
610 /// @brief Unsigned remainder operation.
611 APInt urem(const APInt& RHS) const;
613 /// Signed remainder operation on APInt.
614 /// @brief Function for signed remainder operation.
615 inline APInt srem(const APInt& RHS) const {
617 if (RHS.isNegative())
618 return -((-(*this)).urem(-RHS));
620 return -((-(*this)).urem(RHS));
621 else if (RHS.isNegative())
622 return this->urem(-RHS);
623 return this->urem(RHS);
626 /// Sometimes it is convenient to divide two APInt values and obtain both
627 /// the quotient and remainder. This function does both operations in the
628 /// same computation making it a little more efficient.
629 /// @brief Dual division/remainder interface.
630 static void udivrem(const APInt &LHS, const APInt &RHS,
631 APInt &Quotient, APInt &Remainder);
633 static void sdivrem(const APInt &LHS, const APInt &RHS,
634 APInt &Quotient, APInt &Remainder)
636 if (LHS.isNegative()) {
637 if (RHS.isNegative())
638 APInt::udivrem(-LHS, -RHS, Quotient, Remainder);
640 APInt::udivrem(-LHS, RHS, Quotient, Remainder);
641 Quotient = -Quotient;
642 Remainder = -Remainder;
643 } else if (RHS.isNegative()) {
644 APInt::udivrem(LHS, -RHS, Quotient, Remainder);
645 Quotient = -Quotient;
647 APInt::udivrem(LHS, RHS, Quotient, Remainder);
651 /// @returns the bit value at bitPosition
652 /// @brief Array-indexing support.
653 bool operator[](uint32_t bitPosition) const;
656 /// @name Comparison Operators
658 /// Compares this APInt with RHS for the validity of the equality
660 /// @brief Equality operator.
661 bool operator==(const APInt& RHS) const;
663 /// Compares this APInt with a uint64_t for the validity of the equality
665 /// @returns true if *this == Val
666 /// @brief Equality operator.
667 bool operator==(uint64_t Val) const;
669 /// Compares this APInt with RHS for the validity of the equality
671 /// @returns true if *this == Val
672 /// @brief Equality comparison.
673 bool eq(const APInt &RHS) const {
674 return (*this) == RHS;
677 /// Compares this APInt with RHS for the validity of the inequality
679 /// @returns true if *this != Val
680 /// @brief Inequality operator.
681 inline bool operator!=(const APInt& RHS) const {
682 return !((*this) == RHS);
685 /// Compares this APInt with a uint64_t for the validity of the inequality
687 /// @returns true if *this != Val
688 /// @brief Inequality operator.
689 inline bool operator!=(uint64_t Val) const {
690 return !((*this) == Val);
693 /// Compares this APInt with RHS for the validity of the inequality
695 /// @returns true if *this != Val
696 /// @brief Inequality comparison
697 bool ne(const APInt &RHS) const {
698 return !((*this) == RHS);
701 /// Regards both *this and RHS as unsigned quantities and compares them for
702 /// the validity of the less-than relationship.
703 /// @returns true if *this < RHS when both are considered unsigned.
704 /// @brief Unsigned less than comparison
705 bool ult(const APInt& RHS) const;
707 /// Regards both *this and RHS as signed quantities and compares them for
708 /// validity of the less-than relationship.
709 /// @returns true if *this < RHS when both are considered signed.
710 /// @brief Signed less than comparison
711 bool slt(const APInt& RHS) const;
713 /// Regards both *this and RHS as unsigned quantities and compares them for
714 /// validity of the less-or-equal relationship.
715 /// @returns true if *this <= RHS when both are considered unsigned.
716 /// @brief Unsigned less or equal comparison
717 bool ule(const APInt& RHS) const {
718 return ult(RHS) || eq(RHS);
721 /// Regards both *this and RHS as signed quantities and compares them for
722 /// validity of the less-or-equal relationship.
723 /// @returns true if *this <= RHS when both are considered signed.
724 /// @brief Signed less or equal comparison
725 bool sle(const APInt& RHS) const {
726 return slt(RHS) || eq(RHS);
729 /// Regards both *this and RHS as unsigned quantities and compares them for
730 /// the validity of the greater-than relationship.
731 /// @returns true if *this > RHS when both are considered unsigned.
732 /// @brief Unsigned greather than comparison
733 bool ugt(const APInt& RHS) const {
734 return !ult(RHS) && !eq(RHS);
737 /// Regards both *this and RHS as signed quantities and compares them for
738 /// the validity of the greater-than relationship.
739 /// @returns true if *this > RHS when both are considered signed.
740 /// @brief Signed greather than comparison
741 bool sgt(const APInt& RHS) const {
742 return !slt(RHS) && !eq(RHS);
745 /// Regards both *this and RHS as unsigned quantities and compares them for
746 /// validity of the greater-or-equal relationship.
747 /// @returns true if *this >= RHS when both are considered unsigned.
748 /// @brief Unsigned greater or equal comparison
749 bool uge(const APInt& RHS) const {
753 /// Regards both *this and RHS as signed quantities and compares them for
754 /// validity of the greater-or-equal relationship.
755 /// @returns true if *this >= RHS when both are considered signed.
756 /// @brief Signed greather or equal comparison
757 bool sge(const APInt& RHS) const {
762 /// @name Resizing Operators
764 /// Truncate the APInt to a specified width. It is an error to specify a width
765 /// that is greater than or equal to the current width.
766 /// @brief Truncate to new width.
767 APInt &trunc(uint32_t width);
769 /// This operation sign extends the APInt to a new width. If the high order
770 /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
771 /// It is an error to specify a width that is less than or equal to the
773 /// @brief Sign extend to a new width.
774 APInt &sext(uint32_t width);
776 /// This operation zero extends the APInt to a new width. The high order bits
777 /// are filled with 0 bits. It is an error to specify a width that is less
778 /// than or equal to the current width.
779 /// @brief Zero extend to a new width.
780 APInt &zext(uint32_t width);
782 /// Make this APInt have the bit width given by \p width. The value is sign
783 /// extended, truncated, or left alone to make it that width.
784 /// @brief Sign extend or truncate to width
785 APInt &sextOrTrunc(uint32_t width);
787 /// Make this APInt have the bit width given by \p width. The value is zero
788 /// extended, truncated, or left alone to make it that width.
789 /// @brief Zero extend or truncate to width
790 APInt &zextOrTrunc(uint32_t width);
793 /// @name Bit Manipulation Operators
795 /// @brief Set every bit to 1.
798 /// Set the given bit to 1 whose position is given as "bitPosition".
799 /// @brief Set a given bit to 1.
800 APInt& set(uint32_t bitPosition);
802 /// @brief Set every bit to 0.
805 /// Set the given bit to 0 whose position is given as "bitPosition".
806 /// @brief Set a given bit to 0.
807 APInt& clear(uint32_t bitPosition);
809 /// @brief Toggle every bit to its opposite value.
812 /// Toggle a given bit to its opposite value whose position is given
813 /// as "bitPosition".
814 /// @brief Toggles a given bit to its opposite value.
815 APInt& flip(uint32_t bitPosition);
818 /// @name Value Characterization Functions
821 /// @returns the total number of bits.
822 inline uint32_t getBitWidth() const {
826 /// Here one word's bitwidth equals to that of uint64_t.
827 /// @returns the number of words to hold the integer value of this APInt.
828 /// @brief Get the number of words.
829 inline uint32_t getNumWords() const {
830 return (BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
833 /// This function returns the number of active bits which is defined as the
834 /// bit width minus the number of leading zeros. This is used in several
835 /// computations to see how "wide" the value is.
836 /// @brief Compute the number of active bits in the value
837 inline uint32_t getActiveBits() const {
838 return BitWidth - countLeadingZeros();
841 /// This function returns the number of active words in the value of this
842 /// APInt. This is used in conjunction with getActiveData to extract the raw
843 /// value of the APInt.
844 inline uint32_t getActiveWords() const {
845 return whichWord(getActiveBits()-1) + 1;
848 /// Computes the minimum bit width for this APInt while considering it to be
849 /// a signed (and probably negative) value. If the value is not negative,
850 /// this function returns the same value as getActiveBits(). Otherwise, it
851 /// returns the smallest bit width that will retain the negative value. For
852 /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
853 /// for -1, this function will always return 1.
854 /// @brief Get the minimum bit size for this signed APInt
855 inline uint32_t getMinSignedBits() const {
857 return BitWidth - countLeadingOnes() + 1;
858 return getActiveBits();
861 /// This method attempts to return the value of this APInt as a zero extended
862 /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
863 /// uint64_t. Otherwise an assertion will result.
864 /// @brief Get zero extended value
865 inline uint64_t getZExtValue() const {
868 assert(getActiveBits() <= 64 && "Too many bits for uint64_t");
872 /// This method attempts to return the value of this APInt as a sign extended
873 /// int64_t. The bit width must be <= 64 or the value must fit within an
874 /// int64_t. Otherwise an assertion will result.
875 /// @brief Get sign extended value
876 inline int64_t getSExtValue() const {
878 return int64_t(VAL << (APINT_BITS_PER_WORD - BitWidth)) >>
879 (APINT_BITS_PER_WORD - BitWidth);
880 assert(getActiveBits() <= 64 && "Too many bits for int64_t");
881 return int64_t(pVal[0]);
884 /// This method determines how many bits are required to hold the APInt
885 /// equivalent of the string given by \p str of length \p slen.
886 /// @brief Get bits required for string value.
887 static uint32_t getBitsNeeded(const char* str, uint32_t slen, uint8_t radix);
889 /// countLeadingZeros - This function is an APInt version of the
890 /// countLeadingZeros_{32,64} functions in MathExtras.h. It counts the number
891 /// of zeros from the most significant bit to the first one bit.
892 /// @returns getNumWords() * APINT_BITS_PER_WORD if the value is zero.
893 /// @returns the number of zeros from the most significant bit to the first
895 /// @brief Count the number of leading one bits.
896 uint32_t countLeadingZeros() const;
898 /// countLeadingOnes - This function counts the number of contiguous 1 bits
899 /// in the high order bits. The count stops when the first 0 bit is reached.
900 /// @returns 0 if the high order bit is not set
901 /// @returns the number of 1 bits from the most significant to the least
902 /// @brief Count the number of leading one bits.
903 uint32_t countLeadingOnes() const;
905 /// countTrailingZeros - This function is an APInt version of the
906 /// countTrailingZoers_{32,64} functions in MathExtras.h. It counts
907 /// the number of zeros from the least significant bit to the first one bit.
908 /// @returns getNumWords() * APINT_BITS_PER_WORD if the value is zero.
909 /// @returns the number of zeros from the least significant bit to the first
911 /// @brief Count the number of trailing zero bits.
912 uint32_t countTrailingZeros() const;
914 /// countPopulation - This function is an APInt version of the
915 /// countPopulation_{32,64} functions in MathExtras.h. It counts the number
916 /// of 1 bits in the APInt value.
917 /// @returns 0 if the value is zero.
918 /// @returns the number of set bits.
919 /// @brief Count the number of bits set.
920 uint32_t countPopulation() const;
923 /// @name Conversion Functions
926 /// This is used internally to convert an APInt to a string.
927 /// @brief Converts an APInt to a std::string
928 std::string toString(uint8_t radix, bool wantSigned) const;
930 /// Considers the APInt to be unsigned and converts it into a string in the
931 /// radix given. The radix can be 2, 8, 10 or 16.
932 /// @returns a character interpretation of the APInt
933 /// @brief Convert unsigned APInt to string representation.
934 inline std::string toString(uint8_t radix = 10) const {
935 return toString(radix, false);
938 /// Considers the APInt to be unsigned and converts it into a string in the
939 /// radix given. The radix can be 2, 8, 10 or 16.
940 /// @returns a character interpretation of the APInt
941 /// @brief Convert unsigned APInt to string representation.
942 inline std::string toStringSigned(uint8_t radix = 10) const {
943 return toString(radix, true);
946 /// @returns a byte-swapped representation of this APInt Value.
947 APInt byteSwap() const;
949 /// @brief Converts this APInt to a double value.
950 double roundToDouble(bool isSigned) const;
952 /// @brief Converts this unsigned APInt to a double value.
953 double roundToDouble() const {
954 return roundToDouble(false);
957 /// @brief Converts this signed APInt to a double value.
958 double signedRoundToDouble() const {
959 return roundToDouble(true);
962 /// The conversion does not do a translation from integer to double, it just
963 /// re-interprets the bits as a double. Note that it is valid to do this on
964 /// any bit width. Exactly 64 bits will be translated.
965 /// @brief Converts APInt bits to a double
966 double bitsToDouble() const {
971 T.I = (isSingleWord() ? VAL : pVal[0]);
975 /// The conversion does not do a translation from integer to float, it just
976 /// re-interprets the bits as a float. Note that it is valid to do this on
977 /// any bit width. Exactly 32 bits will be translated.
978 /// @brief Converts APInt bits to a double
979 float bitsToFloat() const {
984 T.I = uint32_t((isSingleWord() ? VAL : pVal[0]));
988 /// The conversion does not do a translation from double to integer, it just
989 /// re-interprets the bits of the double. Note that it is valid to do this on
990 /// any bit width but bits from V may get truncated.
991 /// @brief Converts a double to APInt bits.
992 APInt& doubleToBits(double V) {
1002 return clearUnusedBits();
1005 /// The conversion does not do a translation from float to integer, it just
1006 /// re-interprets the bits of the float. Note that it is valid to do this on
1007 /// any bit width but bits from V may get truncated.
1008 /// @brief Converts a float to APInt bits.
1009 APInt& floatToBits(float V) {
1019 return clearUnusedBits();
1023 /// @name Mathematics Operations
1026 /// @returns the floor log base 2 of this APInt.
1027 inline uint32_t logBase2() const {
1028 return BitWidth - 1 - countLeadingZeros();
1031 /// @returns the log base 2 of this APInt if its an exact power of two, -1
1033 inline int32_t exactLogBase2() const {
1039 /// @brief Compute the square root
1042 /// If *this is < 0 then return -(*this), otherwise *this;
1043 /// @brief Get the absolute value;
1053 /// @name Building-block Operations for APInt and APFloat
1056 // These building block operations operate on a representation of
1057 // arbitrary precision, two's-complement, bignum integer values.
1058 // They should be sufficient to implement APInt and APFloat bignum
1059 // requirements. Inputs are generally a pointer to the base of an
1060 // array of integer parts, representing an unsigned bignum, and a
1061 // count of how many parts there are.
1063 /// Sets the least significant part of a bignum to the input value,
1064 /// and zeroes out higher parts. */
1065 static void tcSet(integerPart *, integerPart, unsigned int);
1067 /// Assign one bignum to another.
1068 static void tcAssign(integerPart *, const integerPart *, unsigned int);
1070 /// Returns true if a bignum is zero, false otherwise.
1071 static bool tcIsZero(const integerPart *, unsigned int);
1073 /// Extract the given bit of a bignum; returns 0 or 1. Zero-based.
1074 static int tcExtractBit(const integerPart *, unsigned int bit);
1076 /// Set the given bit of a bignum. Zero-based.
1077 static void tcSetBit(integerPart *, unsigned int bit);
1079 /// Returns the bit number of the least or most significant set bit
1080 /// of a number. If the input number has no bits set -1U is
1082 static unsigned int tcLSB(const integerPart *, unsigned int);
1083 static unsigned int tcMSB(const integerPart *, unsigned int);
1085 /// Negate a bignum in-place.
1086 static void tcNegate(integerPart *, unsigned int);
1088 /// DST += RHS + CARRY where CARRY is zero or one. Returns the
1090 static integerPart tcAdd(integerPart *, const integerPart *,
1091 integerPart carry, unsigned);
1093 /// DST -= RHS + CARRY where CARRY is zero or one. Returns the
1095 static integerPart tcSubtract(integerPart *, const integerPart *,
1096 integerPart carry, unsigned);
1098 /// DST += SRC * MULTIPLIER + PART if add is true
1099 /// DST = SRC * MULTIPLIER + PART if add is false
1101 /// Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC
1102 /// they must start at the same point, i.e. DST == SRC.
1104 /// If DSTPARTS == SRC_PARTS + 1 no overflow occurs and zero is
1105 /// returned. Otherwise DST is filled with the least significant
1106 /// DSTPARTS parts of the result, and if all of the omitted higher
1107 /// parts were zero return zero, otherwise overflow occurred and
1109 static int tcMultiplyPart(integerPart *dst, const integerPart *src,
1110 integerPart multiplier, integerPart carry,
1111 unsigned int srcParts, unsigned int dstParts,
1114 /// DST = LHS * RHS, where DST has the same width as the operands
1115 /// and is filled with the least significant parts of the result.
1116 /// Returns one if overflow occurred, otherwise zero. DST must be
1117 /// disjoint from both operands.
1118 static int tcMultiply(integerPart *, const integerPart *,
1119 const integerPart *, unsigned);
1121 /// DST = LHS * RHS, where DST has twice the width as the operands.
1122 /// No overflow occurs. DST must be disjoint from both operands.
1123 static void tcFullMultiply(integerPart *, const integerPart *,
1124 const integerPart *, unsigned);
1126 /// If RHS is zero LHS and REMAINDER are left unchanged, return one.
1127 /// Otherwise set LHS to LHS / RHS with the fractional part
1128 /// discarded, set REMAINDER to the remainder, return zero. i.e.
1130 /// OLD_LHS = RHS * LHS + REMAINDER
1132 /// SCRATCH is a bignum of the same size as the operands and result
1133 /// for use by the routine; its contents need not be initialized
1134 /// and are destroyed. LHS, REMAINDER and SCRATCH must be
1136 static int tcDivide(integerPart *lhs, const integerPart *rhs,
1137 integerPart *remainder, integerPart *scratch,
1138 unsigned int parts);
1140 /// Shift a bignum left COUNT bits. Shifted in bits are zero.
1141 /// There are no restrictions on COUNT.
1142 static void tcShiftLeft(integerPart *, unsigned int parts,
1143 unsigned int count);
1145 /// Shift a bignum right COUNT bits. Shifted in bits are zero.
1146 /// There are no restrictions on COUNT.
1147 static void tcShiftRight(integerPart *, unsigned int parts,
1148 unsigned int count);
1150 /// The obvious AND, OR and XOR and complement operations.
1151 static void tcAnd(integerPart *, const integerPart *, unsigned int);
1152 static void tcOr(integerPart *, const integerPart *, unsigned int);
1153 static void tcXor(integerPart *, const integerPart *, unsigned int);
1154 static void tcComplement(integerPart *, unsigned int);
1156 /// Comparison (unsigned) of two bignums.
1157 static int tcCompare(const integerPart *, const integerPart *,
1160 /// Increment a bignum in-place. Return the carry flag.
1161 static integerPart tcIncrement(integerPart *, unsigned int);
1163 /// Set the least significant BITS and clear the rest.
1164 static void tcSetLeastSignificantBits(integerPart *, unsigned int,
1170 inline bool operator==(uint64_t V1, const APInt& V2) {
1174 inline bool operator!=(uint64_t V1, const APInt& V2) {
1178 namespace APIntOps {
1180 /// @brief Determine the smaller of two APInts considered to be signed.
1181 inline APInt smin(const APInt &A, const APInt &B) {
1182 return A.slt(B) ? A : B;
1185 /// @brief Determine the larger of two APInts considered to be signed.
1186 inline APInt smax(const APInt &A, const APInt &B) {
1187 return A.sgt(B) ? A : B;
1190 /// @brief Determine the smaller of two APInts considered to be signed.
1191 inline APInt umin(const APInt &A, const APInt &B) {
1192 return A.ult(B) ? A : B;
1195 /// @brief Determine the larger of two APInts considered to be unsigned.
1196 inline APInt umax(const APInt &A, const APInt &B) {
1197 return A.ugt(B) ? A : B;
1200 /// @brief Check if the specified APInt has a N-bits integer value.
1201 inline bool isIntN(uint32_t N, const APInt& APIVal) {
1202 return APIVal.isIntN(N);
1205 /// @returns true if the argument APInt value is a sequence of ones
1206 /// starting at the least significant bit with the remainder zero.
1207 inline bool isMask(uint32_t numBits, const APInt& APIVal) {
1208 return APIVal.getBoolValue() && ((APIVal + APInt(numBits,1)) & APIVal) == 0;
1211 /// @returns true if the argument APInt value contains a sequence of ones
1212 /// with the remainder zero.
1213 inline bool isShiftedMask(uint32_t numBits, const APInt& APIVal) {
1214 return isMask(numBits, (APIVal - APInt(numBits,1)) | APIVal);
1217 /// @returns a byte-swapped representation of the specified APInt Value.
1218 inline APInt byteSwap(const APInt& APIVal) {
1219 return APIVal.byteSwap();
1222 /// @returns the floor log base 2 of the specified APInt value.
1223 inline uint32_t logBase2(const APInt& APIVal) {
1224 return APIVal.logBase2();
1227 /// GreatestCommonDivisor - This function returns the greatest common
1228 /// divisor of the two APInt values using Enclid's algorithm.
1229 /// @returns the greatest common divisor of Val1 and Val2
1230 /// @brief Compute GCD of two APInt values.
1231 APInt GreatestCommonDivisor(const APInt& Val1, const APInt& Val2);
1233 /// Treats the APInt as an unsigned value for conversion purposes.
1234 /// @brief Converts the given APInt to a double value.
1235 inline double RoundAPIntToDouble(const APInt& APIVal) {
1236 return APIVal.roundToDouble();
1239 /// Treats the APInt as a signed value for conversion purposes.
1240 /// @brief Converts the given APInt to a double value.
1241 inline double RoundSignedAPIntToDouble(const APInt& APIVal) {
1242 return APIVal.signedRoundToDouble();
1245 /// @brief Converts the given APInt to a float vlalue.
1246 inline float RoundAPIntToFloat(const APInt& APIVal) {
1247 return float(RoundAPIntToDouble(APIVal));
1250 /// Treast the APInt as a signed value for conversion purposes.
1251 /// @brief Converts the given APInt to a float value.
1252 inline float RoundSignedAPIntToFloat(const APInt& APIVal) {
1253 return float(APIVal.signedRoundToDouble());
1256 /// RoundDoubleToAPInt - This function convert a double value to an APInt value.
1257 /// @brief Converts the given double value into a APInt.
1258 APInt RoundDoubleToAPInt(double Double, uint32_t width);
1260 /// RoundFloatToAPInt - Converts a float value into an APInt value.
1261 /// @brief Converts a float value into a APInt.
1262 inline APInt RoundFloatToAPInt(float Float, uint32_t width) {
1263 return RoundDoubleToAPInt(double(Float), width);
1266 /// Arithmetic right-shift the APInt by shiftAmt.
1267 /// @brief Arithmetic right-shift function.
1268 inline APInt ashr(const APInt& LHS, uint32_t shiftAmt) {
1269 return LHS.ashr(shiftAmt);
1272 /// Logical right-shift the APInt by shiftAmt.
1273 /// @brief Logical right-shift function.
1274 inline APInt lshr(const APInt& LHS, uint32_t shiftAmt) {
1275 return LHS.lshr(shiftAmt);
1278 /// Left-shift the APInt by shiftAmt.
1279 /// @brief Left-shift function.
1280 inline APInt shl(const APInt& LHS, uint32_t shiftAmt) {
1281 return LHS.shl(shiftAmt);
1284 /// Signed divide APInt LHS by APInt RHS.
1285 /// @brief Signed division function for APInt.
1286 inline APInt sdiv(const APInt& LHS, const APInt& RHS) {
1287 return LHS.sdiv(RHS);
1290 /// Unsigned divide APInt LHS by APInt RHS.
1291 /// @brief Unsigned division function for APInt.
1292 inline APInt udiv(const APInt& LHS, const APInt& RHS) {
1293 return LHS.udiv(RHS);
1296 /// Signed remainder operation on APInt.
1297 /// @brief Function for signed remainder operation.
1298 inline APInt srem(const APInt& LHS, const APInt& RHS) {
1299 return LHS.srem(RHS);
1302 /// Unsigned remainder operation on APInt.
1303 /// @brief Function for unsigned remainder operation.
1304 inline APInt urem(const APInt& LHS, const APInt& RHS) {
1305 return LHS.urem(RHS);
1308 /// Performs multiplication on APInt values.
1309 /// @brief Function for multiplication operation.
1310 inline APInt mul(const APInt& LHS, const APInt& RHS) {
1314 /// Performs addition on APInt values.
1315 /// @brief Function for addition operation.
1316 inline APInt add(const APInt& LHS, const APInt& RHS) {
1320 /// Performs subtraction on APInt values.
1321 /// @brief Function for subtraction operation.
1322 inline APInt sub(const APInt& LHS, const APInt& RHS) {
1326 /// Performs bitwise AND operation on APInt LHS and
1328 /// @brief Bitwise AND function for APInt.
1329 inline APInt And(const APInt& LHS, const APInt& RHS) {
1333 /// Performs bitwise OR operation on APInt LHS and APInt RHS.
1334 /// @brief Bitwise OR function for APInt.
1335 inline APInt Or(const APInt& LHS, const APInt& RHS) {
1339 /// Performs bitwise XOR operation on APInt.
1340 /// @brief Bitwise XOR function for APInt.
1341 inline APInt Xor(const APInt& LHS, const APInt& RHS) {
1345 /// Performs a bitwise complement operation on APInt.
1346 /// @brief Bitwise complement function.
1347 inline APInt Not(const APInt& APIVal) {
1351 } // End of APIntOps namespace
1353 } // End of llvm namespace