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 COMPILE_TIME_ASSERT(cond) extern int CTAssert[(cond) ? 1 : -1]
26 /* An unsigned host type used as a single part of a multi-part
28 typedef uint64_t integerPart;
30 const unsigned int host_char_bit = 8;
31 const unsigned int integerPartWidth = host_char_bit * sizeof(integerPart);
33 //===----------------------------------------------------------------------===//
35 //===----------------------------------------------------------------------===//
37 /// APInt - This class represents arbitrary precision constant integral values.
38 /// It is a functional replacement for common case unsigned integer type like
39 /// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width
40 /// integer sizes and large integer value types such as 3-bits, 15-bits, or more
41 /// than 64-bits of precision. APInt provides a variety of arithmetic operators
42 /// and methods to manipulate integer values of any bit-width. It supports both
43 /// the typical integer arithmetic and comparison operations as well as bitwise
46 /// The class has several invariants worth noting:
47 /// * All bit, byte, and word positions are zero-based.
48 /// * Once the bit width is set, it doesn't change except by the Truncate,
49 /// SignExtend, or ZeroExtend operations.
50 /// * All binary operators must be on APInt instances of the same bit width.
51 /// Attempting to use these operators on instances with different bit
52 /// widths will yield an assertion.
53 /// * The value is stored canonically as an unsigned value. For operations
54 /// where it makes a difference, there are both signed and unsigned variants
55 /// of the operation. For example, sdiv and udiv. However, because the bit
56 /// widths must be the same, operations such as Mul and Add produce the same
57 /// results regardless of whether the values are interpreted as signed or
59 /// * In general, the class tries to follow the style of computation that LLVM
60 /// uses in its IR. This simplifies its use for LLVM.
62 /// @brief Class for arbitrary precision integers.
65 uint32_t BitWidth; ///< The number of bits in this APInt.
67 /// This union is used to store the integer value. When the
68 /// integer bit-width <= 64, it uses VAL, otherwise it uses pVal.
70 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
71 uint64_t *pVal; ///< Used to store the >64 bits integer value.
74 /// This enum is used to hold the constants we needed for APInt.
76 APINT_BITS_PER_WORD = sizeof(uint64_t) * 8, ///< Bits in a word
77 APINT_WORD_SIZE = sizeof(uint64_t) ///< Byte size of a word
80 /// This constructor is used only internally for speed of construction of
81 /// temporaries. It is unsafe for general use so it is not public.
82 /// @brief Fast internal constructor
83 APInt(uint64_t* val, uint32_t bits) : BitWidth(bits), pVal(val) { }
85 /// @returns true if the number of bits <= 64, false otherwise.
86 /// @brief Determine if this APInt just has one word to store value.
87 inline bool isSingleWord() const {
88 return BitWidth <= APINT_BITS_PER_WORD;
91 /// @returns the word position for the specified bit position.
92 /// @brief Determine which word a bit is in.
93 static inline uint32_t whichWord(uint32_t bitPosition) {
94 return bitPosition / APINT_BITS_PER_WORD;
97 /// @returns the bit position in a word for the specified bit position
99 /// @brief Determine which bit in a word a bit is in.
100 static inline uint32_t whichBit(uint32_t bitPosition) {
101 return bitPosition % APINT_BITS_PER_WORD;
104 /// This method generates and returns a uint64_t (word) mask for a single
105 /// bit at a specific bit position. This is used to mask the bit in the
106 /// corresponding word.
107 /// @returns a uint64_t with only bit at "whichBit(bitPosition)" set
108 /// @brief Get a single bit mask.
109 static inline uint64_t maskBit(uint32_t bitPosition) {
110 return 1ULL << whichBit(bitPosition);
113 /// This method is used internally to clear the to "N" bits in the high order
114 /// word that are not used by the APInt. This is needed after the most
115 /// significant word is assigned a value to ensure that those bits are
117 /// @brief Clear unused high order bits
118 inline APInt& clearUnusedBits() {
119 // Compute how many bits are used in the final word
120 uint32_t wordBits = BitWidth % APINT_BITS_PER_WORD;
122 // If all bits are used, we want to leave the value alone. This also
123 // avoids the undefined behavior of >> when the shfit is the same size as
124 // the word size (64).
127 // Mask out the hight bits.
128 uint64_t mask = ~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - wordBits);
132 pVal[getNumWords() - 1] &= mask;
136 /// @returns the corresponding word for the specified bit position.
137 /// @brief Get the word corresponding to a bit position
138 inline uint64_t getWord(uint32_t bitPosition) const {
139 return isSingleWord() ? VAL : pVal[whichWord(bitPosition)];
142 /// This is used by the constructors that take string arguments.
143 /// @brief Convert a char array into an APInt
144 void fromString(uint32_t numBits, const char *strStart, uint32_t slen,
147 /// This is used by the toString method to divide by the radix. It simply
148 /// provides a more convenient form of divide for internal use since KnuthDiv
149 /// has specific constraints on its inputs. If those constraints are not met
150 /// then it provides a simpler form of divide.
151 /// @brief An internal division function for dividing APInts.
152 static void divide(const APInt LHS, uint32_t lhsWords,
153 const APInt &RHS, uint32_t rhsWords,
154 APInt *Quotient, APInt *Remainder);
157 /// @brief debug method
162 /// @name Constructors
164 /// If isSigned is true then val is treated as if it were a signed value
165 /// (i.e. as an int64_t) and the appropriate sign extension to the bit width
166 /// will be done. Otherwise, no sign extension occurs (high order bits beyond
167 /// the range of val are zero filled).
168 /// @param numBits the bit width of the constructed APInt
169 /// @param val the initial value of the APInt
170 /// @param isSigned how to treat signedness of val
171 /// @brief Create a new APInt of numBits width, initialized as val.
172 APInt(uint32_t numBits, uint64_t val, bool isSigned = false);
174 /// Note that numWords can be smaller or larger than the corresponding bit
175 /// width but any extraneous bits will be dropped.
176 /// @param numBits the bit width of the constructed APInt
177 /// @param numWords the number of words in bigVal
178 /// @param bigVal a sequence of words to form the initial value of the APInt
179 /// @brief Construct an APInt of numBits width, initialized as bigVal[].
180 APInt(uint32_t numBits, uint32_t numWords, uint64_t bigVal[]);
182 /// This constructor interprets Val as a string in the given radix. The
183 /// interpretation stops when the first charater that is not suitable for the
184 /// radix is encountered. Acceptable radix values are 2, 8, 10 and 16. It is
185 /// an error for the value implied by the string to require more bits than
187 /// @param numBits the bit width of the constructed APInt
188 /// @param val the string to be interpreted
189 /// @param radix the radix of Val to use for the intepretation
190 /// @brief Construct an APInt from a string representation.
191 APInt(uint32_t numBits, const std::string& val, uint8_t radix);
193 /// This constructor interprets the slen characters starting at StrStart as
194 /// a string in the given radix. The interpretation stops when the first
195 /// character that is not suitable for the radix is encountered. Acceptable
196 /// radix values are 2, 8, 10 and 16. It is an error for the value implied by
197 /// the string to require more bits than numBits.
198 /// @param numBits the bit width of the constructed APInt
199 /// @param strStart the start of the string to be interpreted
200 /// @param slen the maximum number of characters to interpret
201 /// @param radix the radix to use for the conversion
202 /// @brief Construct an APInt from a string representation.
203 APInt(uint32_t numBits, const char strStart[], uint32_t slen, uint8_t radix);
205 /// Simply makes *this a copy of that.
206 /// @brief Copy Constructor.
207 APInt(const APInt& that);
209 /// @brief Destructor.
213 /// @name Value Tests
215 /// This tests the high bit of this APInt to determine if it is set.
216 /// @returns true if this APInt is negative, false otherwise
217 /// @brief Determine sign of this APInt.
218 bool isNegative() const {
219 return (*this)[BitWidth - 1];
222 /// This tests the high bit of the APInt to determine if it is unset.
223 /// @brief Determine if this APInt Value is positive (not negative).
224 bool isPositive() const {
225 return !isNegative();
228 /// This tests if the value of this APInt is strictly positive (> 0).
229 /// @returns true if this APInt is Positive and not zero.
230 /// @brief Determine if this APInt Value is strictly positive.
231 inline bool isStrictlyPositive() const {
232 return isPositive() && (*this) != 0;
235 /// This checks to see if the value has all bits of the APInt are set or not.
236 /// @brief Determine if all bits are set
237 inline bool isAllOnesValue() const {
238 return countPopulation() == BitWidth;
241 /// This checks to see if the value of this APInt is the maximum unsigned
242 /// value for the APInt's bit width.
243 /// @brief Determine if this is the largest unsigned value.
244 bool isMaxValue() const {
245 return countPopulation() == BitWidth;
248 /// This checks to see if the value of this APInt is the maximum signed
249 /// value for the APInt's bit width.
250 /// @brief Determine if this is the largest signed value.
251 bool isMaxSignedValue() const {
252 return BitWidth == 1 ? VAL == 0 :
253 !isNegative() && countPopulation() == BitWidth - 1;
256 /// This checks to see if the value of this APInt is the minimum unsigned
257 /// value for the APInt's bit width.
258 /// @brief Determine if this is the smallest unsigned value.
259 bool isMinValue() const {
260 return countPopulation() == 0;
263 /// This checks to see if the value of this APInt is the minimum signed
264 /// value for the APInt's bit width.
265 /// @brief Determine if this is the smallest signed value.
266 bool isMinSignedValue() const {
267 return BitWidth == 1 ? VAL == 1 :
268 isNegative() && countPopulation() == 1;
271 /// @brief Check if this APInt has an N-bits integer value.
272 inline bool isIntN(uint32_t N) const {
273 assert(N && "N == 0 ???");
274 if (isSingleWord()) {
275 return VAL == (VAL & (~0ULL >> (64 - N)));
277 APInt Tmp(N, getNumWords(), pVal);
278 return Tmp == (*this);
282 /// @returns true if the argument APInt value is a power of two > 0.
283 bool isPowerOf2() const;
285 /// isSignBit - Return true if this is the value returned by getSignBit.
286 bool isSignBit() const { return isMinSignedValue(); }
288 /// This converts the APInt to a boolean value as a test against zero.
289 /// @brief Boolean conversion function.
290 inline bool getBoolValue() const {
294 /// getLimitedValue - If this value is smaller than the specified limit,
295 /// return it, otherwise return the limit value. This causes the value
296 /// to saturate to the limit.
297 uint64_t getLimitedValue(uint64_t Limit = ~0ULL) const {
298 return (getActiveBits() > 64 || getZExtValue() > Limit) ?
299 Limit : getZExtValue();
303 /// @name Value Generators
305 /// @brief Gets maximum unsigned value of APInt for specific bit width.
306 static APInt getMaxValue(uint32_t numBits) {
307 return APInt(numBits, 0).set();
310 /// @brief Gets maximum signed value of APInt for a specific bit width.
311 static APInt getSignedMaxValue(uint32_t numBits) {
312 return APInt(numBits, 0).set().clear(numBits - 1);
315 /// @brief Gets minimum unsigned value of APInt for a specific bit width.
316 static APInt getMinValue(uint32_t numBits) {
317 return APInt(numBits, 0);
320 /// @brief Gets minimum signed value of APInt for a specific bit width.
321 static APInt getSignedMinValue(uint32_t numBits) {
322 return APInt(numBits, 0).set(numBits - 1);
325 /// getSignBit - This is just a wrapper function of getSignedMinValue(), and
326 /// it helps code readability when we want to get a SignBit.
327 /// @brief Get the SignBit for a specific bit width.
328 inline static APInt getSignBit(uint32_t BitWidth) {
329 return getSignedMinValue(BitWidth);
332 /// @returns the all-ones value for an APInt of the specified bit-width.
333 /// @brief Get the all-ones value.
334 static APInt getAllOnesValue(uint32_t numBits) {
335 return APInt(numBits, 0).set();
338 /// @returns the '0' value for an APInt of the specified bit-width.
339 /// @brief Get the '0' value.
340 static APInt getNullValue(uint32_t numBits) {
341 return APInt(numBits, 0);
344 /// Get an APInt with the same BitWidth as this APInt, just zero mask
345 /// the low bits and right shift to the least significant bit.
346 /// @returns the high "numBits" bits of this APInt.
347 APInt getHiBits(uint32_t numBits) const;
349 /// Get an APInt with the same BitWidth as this APInt, just zero mask
351 /// @returns the low "numBits" bits of this APInt.
352 APInt getLoBits(uint32_t numBits) const;
354 /// Constructs an APInt value that has a contiguous range of bits set. The
355 /// bits from loBit to hiBit will be set. All other bits will be zero. For
356 /// example, with parameters(32, 15, 0) you would get 0x0000FFFF. If hiBit is
357 /// less than loBit then the set bits "wrap". For example, with
358 /// parameters (32, 3, 28), you would get 0xF000000F.
359 /// @param numBits the intended bit width of the result
360 /// @param loBit the index of the lowest bit set.
361 /// @param hiBit the index of the highest bit set.
362 /// @returns An APInt value with the requested bits set.
363 /// @brief Get a value with a block of bits set.
364 static APInt getBitsSet(uint32_t numBits, uint32_t loBit, uint32_t hiBit) {
365 assert(hiBit < numBits && "hiBit out of range");
366 assert(loBit < numBits && "loBit out of range");
368 return getLowBitsSet(numBits, hiBit+1) |
369 getHighBitsSet(numBits, numBits-loBit+1);
370 return getLowBitsSet(numBits, hiBit-loBit+1).shl(loBit);
373 /// Constructs an APInt value that has the top hiBitsSet bits set.
374 /// @param numBits the bitwidth of the result
375 /// @param hiBitsSet the number of high-order bits set in the result.
376 /// @brief Get a value with high bits set
377 static APInt getHighBitsSet(uint32_t numBits, uint32_t hiBitsSet) {
378 assert(hiBitsSet <= numBits && "Too many bits to set!");
379 // Handle a degenerate case, to avoid shifting by word size
381 return APInt(numBits, 0);
382 uint32_t shiftAmt = numBits - hiBitsSet;
383 // For small values, return quickly
384 if (numBits <= APINT_BITS_PER_WORD)
385 return APInt(numBits, ~0ULL << shiftAmt);
386 return (~APInt(numBits, 0)).shl(shiftAmt);
389 /// Constructs an APInt value that has the bottom loBitsSet bits set.
390 /// @param numBits the bitwidth of the result
391 /// @param loBitsSet the number of low-order bits set in the result.
392 /// @brief Get a value with low bits set
393 static APInt getLowBitsSet(uint32_t numBits, uint32_t loBitsSet) {
394 assert(loBitsSet <= numBits && "Too many bits to set!");
395 // Handle a degenerate case, to avoid shifting by word size
397 return APInt(numBits, 0);
398 if (loBitsSet == APINT_BITS_PER_WORD)
399 return APInt(numBits, -1ULL);
400 // For small values, return quickly
401 if (numBits < APINT_BITS_PER_WORD)
402 return APInt(numBits, (1ULL << loBitsSet) - 1);
403 return (~APInt(numBits, 0)).lshr(numBits - loBitsSet);
406 /// The hash value is computed as the sum of the words and the bit width.
407 /// @returns A hash value computed from the sum of the APInt words.
408 /// @brief Get a hash value based on this APInt
409 uint64_t getHashValue() const;
411 /// This function returns a pointer to the internal storage of the APInt.
412 /// This is useful for writing out the APInt in binary form without any
414 inline const uint64_t* getRawData() const {
421 /// @name Unary Operators
423 /// @returns a new APInt value representing *this incremented by one
424 /// @brief Postfix increment operator.
425 inline const APInt operator++(int) {
431 /// @returns *this incremented by one
432 /// @brief Prefix increment operator.
435 /// @returns a new APInt representing *this decremented by one.
436 /// @brief Postfix decrement operator.
437 inline const APInt operator--(int) {
443 /// @returns *this decremented by one.
444 /// @brief Prefix decrement operator.
447 /// Performs a bitwise complement operation on this APInt.
448 /// @returns an APInt that is the bitwise complement of *this
449 /// @brief Unary bitwise complement operator.
450 APInt operator~() const;
452 /// Negates *this using two's complement logic.
453 /// @returns An APInt value representing the negation of *this.
454 /// @brief Unary negation operator
455 inline APInt operator-() const {
456 return APInt(BitWidth, 0) - (*this);
459 /// Performs logical negation operation on this APInt.
460 /// @returns true if *this is zero, false otherwise.
461 /// @brief Logical negation operator.
462 bool operator !() const;
465 /// @name Assignment Operators
467 /// @returns *this after assignment of RHS.
468 /// @brief Copy assignment operator.
469 APInt& operator=(const APInt& RHS);
471 /// The RHS value is assigned to *this. If the significant bits in RHS exceed
472 /// the bit width, the excess bits are truncated. If the bit width is larger
473 /// than 64, the value is zero filled in the unspecified high order bits.
474 /// @returns *this after assignment of RHS value.
475 /// @brief Assignment operator.
476 APInt& operator=(uint64_t RHS);
478 /// Performs a bitwise AND operation on this APInt and RHS. The result is
479 /// assigned to *this.
480 /// @returns *this after ANDing with RHS.
481 /// @brief Bitwise AND assignment operator.
482 APInt& operator&=(const APInt& RHS);
484 /// Performs a bitwise OR operation on this APInt and RHS. The result is
486 /// @returns *this after ORing with RHS.
487 /// @brief Bitwise OR assignment operator.
488 APInt& operator|=(const APInt& RHS);
490 /// Performs a bitwise XOR operation on this APInt and RHS. The result is
491 /// assigned to *this.
492 /// @returns *this after XORing with RHS.
493 /// @brief Bitwise XOR assignment operator.
494 APInt& operator^=(const APInt& RHS);
496 /// Multiplies this APInt by RHS and assigns the result to *this.
498 /// @brief Multiplication assignment operator.
499 APInt& operator*=(const APInt& RHS);
501 /// Adds RHS to *this and assigns the result to *this.
503 /// @brief Addition assignment operator.
504 APInt& operator+=(const APInt& RHS);
506 /// Subtracts RHS from *this and assigns the result to *this.
508 /// @brief Subtraction assignment operator.
509 APInt& operator-=(const APInt& RHS);
511 /// Shifts *this left by shiftAmt and assigns the result to *this.
512 /// @returns *this after shifting left by shiftAmt
513 /// @brief Left-shift assignment function.
514 inline APInt& operator<<=(uint32_t shiftAmt) {
515 *this = shl(shiftAmt);
520 /// @name Binary Operators
522 /// Performs a bitwise AND operation on *this and RHS.
523 /// @returns An APInt value representing the bitwise AND of *this and RHS.
524 /// @brief Bitwise AND operator.
525 APInt operator&(const APInt& RHS) const;
526 APInt And(const APInt& RHS) const {
527 return this->operator&(RHS);
530 /// Performs a bitwise OR operation on *this and RHS.
531 /// @returns An APInt value representing the bitwise OR of *this and RHS.
532 /// @brief Bitwise OR operator.
533 APInt operator|(const APInt& RHS) const;
534 APInt Or(const APInt& RHS) const {
535 return this->operator|(RHS);
538 /// Performs a bitwise XOR operation on *this and RHS.
539 /// @returns An APInt value representing the bitwise XOR of *this and RHS.
540 /// @brief Bitwise XOR operator.
541 APInt operator^(const APInt& RHS) const;
542 APInt Xor(const APInt& RHS) const {
543 return this->operator^(RHS);
546 /// Multiplies this APInt by RHS and returns the result.
547 /// @brief Multiplication operator.
548 APInt operator*(const APInt& RHS) const;
550 /// Adds RHS to this APInt and returns the result.
551 /// @brief Addition operator.
552 APInt operator+(const APInt& RHS) const;
553 APInt operator+(uint64_t RHS) const {
554 return (*this) + APInt(BitWidth, RHS);
557 /// Subtracts RHS from this APInt and returns the result.
558 /// @brief Subtraction operator.
559 APInt operator-(const APInt& RHS) const;
560 APInt operator-(uint64_t RHS) const {
561 return (*this) - APInt(BitWidth, RHS);
564 APInt operator<<(unsigned Bits) const {
568 /// Arithmetic right-shift this APInt by shiftAmt.
569 /// @brief Arithmetic right-shift function.
570 APInt ashr(uint32_t shiftAmt) const;
572 /// Logical right-shift this APInt by shiftAmt.
573 /// @brief Logical right-shift function.
574 APInt lshr(uint32_t shiftAmt) const;
576 /// Left-shift this APInt by shiftAmt.
577 /// @brief Left-shift function.
578 APInt shl(uint32_t shiftAmt) const;
580 /// @brief Rotate left by rotateAmt.
581 APInt rotl(uint32_t rotateAmt) const;
583 /// @brief Rotate right by rotateAmt.
584 APInt rotr(uint32_t rotateAmt) const;
586 /// Perform an unsigned divide operation on this APInt by RHS. Both this and
587 /// RHS are treated as unsigned quantities for purposes of this division.
588 /// @returns a new APInt value containing the division result
589 /// @brief Unsigned division operation.
590 APInt udiv(const APInt& RHS) const;
592 /// Signed divide this APInt by APInt RHS.
593 /// @brief Signed division function for APInt.
594 inline APInt sdiv(const APInt& RHS) const {
596 if (RHS.isNegative())
597 return (-(*this)).udiv(-RHS);
599 return -((-(*this)).udiv(RHS));
600 else if (RHS.isNegative())
601 return -(this->udiv(-RHS));
602 return this->udiv(RHS);
605 /// Perform an unsigned remainder operation on this APInt with RHS being the
606 /// divisor. Both this and RHS are treated as unsigned quantities for purposes
607 /// of this operation. Note that this is a true remainder operation and not
608 /// a modulo operation because the sign follows the sign of the dividend
610 /// @returns a new APInt value containing the remainder result
611 /// @brief Unsigned remainder operation.
612 APInt urem(const APInt& RHS) const;
614 /// Signed remainder operation on APInt.
615 /// @brief Function for signed remainder operation.
616 inline APInt srem(const APInt& RHS) const {
618 if (RHS.isNegative())
619 return -((-(*this)).urem(-RHS));
621 return -((-(*this)).urem(RHS));
622 else if (RHS.isNegative())
623 return this->urem(-RHS);
624 return this->urem(RHS);
627 /// Sometimes it is convenient to divide two APInt values and obtain both
628 /// the quotient and remainder. This function does both operations in the
629 /// same computation making it a little more efficient.
630 /// @brief Dual division/remainder interface.
631 static void udivrem(const APInt &LHS, const APInt &RHS,
632 APInt &Quotient, APInt &Remainder);
634 static void sdivrem(const APInt &LHS, const APInt &RHS,
635 APInt &Quotient, APInt &Remainder)
637 if (LHS.isNegative()) {
638 if (RHS.isNegative())
639 APInt::udivrem(-LHS, -RHS, Quotient, Remainder);
641 APInt::udivrem(-LHS, RHS, Quotient, Remainder);
642 Quotient = -Quotient;
643 Remainder = -Remainder;
644 } else if (RHS.isNegative()) {
645 APInt::udivrem(LHS, -RHS, Quotient, Remainder);
646 Quotient = -Quotient;
648 APInt::udivrem(LHS, RHS, Quotient, Remainder);
652 /// @returns the bit value at bitPosition
653 /// @brief Array-indexing support.
654 bool operator[](uint32_t bitPosition) const;
657 /// @name Comparison Operators
659 /// Compares this APInt with RHS for the validity of the equality
661 /// @brief Equality operator.
662 bool operator==(const APInt& RHS) const;
664 /// Compares this APInt with a uint64_t for the validity of the equality
666 /// @returns true if *this == Val
667 /// @brief Equality operator.
668 bool operator==(uint64_t Val) const;
670 /// Compares this APInt with RHS for the validity of the equality
672 /// @returns true if *this == Val
673 /// @brief Equality comparison.
674 bool eq(const APInt &RHS) const {
675 return (*this) == RHS;
678 /// Compares this APInt with RHS for the validity of the inequality
680 /// @returns true if *this != Val
681 /// @brief Inequality operator.
682 inline bool operator!=(const APInt& RHS) const {
683 return !((*this) == RHS);
686 /// Compares this APInt with a uint64_t for the validity of the inequality
688 /// @returns true if *this != Val
689 /// @brief Inequality operator.
690 inline bool operator!=(uint64_t Val) const {
691 return !((*this) == Val);
694 /// Compares this APInt with RHS for the validity of the inequality
696 /// @returns true if *this != Val
697 /// @brief Inequality comparison
698 bool ne(const APInt &RHS) const {
699 return !((*this) == RHS);
702 /// Regards both *this and RHS as unsigned quantities and compares them for
703 /// the validity of the less-than relationship.
704 /// @returns true if *this < RHS when both are considered unsigned.
705 /// @brief Unsigned less than comparison
706 bool ult(const APInt& RHS) const;
708 /// Regards both *this and RHS as signed quantities and compares them for
709 /// validity of the less-than relationship.
710 /// @returns true if *this < RHS when both are considered signed.
711 /// @brief Signed less than comparison
712 bool slt(const APInt& RHS) const;
714 /// Regards both *this and RHS as unsigned quantities and compares them for
715 /// validity of the less-or-equal relationship.
716 /// @returns true if *this <= RHS when both are considered unsigned.
717 /// @brief Unsigned less or equal comparison
718 bool ule(const APInt& RHS) const {
719 return ult(RHS) || eq(RHS);
722 /// Regards both *this and RHS as signed quantities and compares them for
723 /// validity of the less-or-equal relationship.
724 /// @returns true if *this <= RHS when both are considered signed.
725 /// @brief Signed less or equal comparison
726 bool sle(const APInt& RHS) const {
727 return slt(RHS) || eq(RHS);
730 /// Regards both *this and RHS as unsigned quantities and compares them for
731 /// the validity of the greater-than relationship.
732 /// @returns true if *this > RHS when both are considered unsigned.
733 /// @brief Unsigned greather than comparison
734 bool ugt(const APInt& RHS) const {
735 return !ult(RHS) && !eq(RHS);
738 /// Regards both *this and RHS as signed quantities and compares them for
739 /// the validity of the greater-than relationship.
740 /// @returns true if *this > RHS when both are considered signed.
741 /// @brief Signed greather than comparison
742 bool sgt(const APInt& RHS) const {
743 return !slt(RHS) && !eq(RHS);
746 /// Regards both *this and RHS as unsigned quantities and compares them for
747 /// validity of the greater-or-equal relationship.
748 /// @returns true if *this >= RHS when both are considered unsigned.
749 /// @brief Unsigned greater or equal comparison
750 bool uge(const APInt& RHS) const {
754 /// Regards both *this and RHS as signed quantities and compares them for
755 /// validity of the greater-or-equal relationship.
756 /// @returns true if *this >= RHS when both are considered signed.
757 /// @brief Signed greather or equal comparison
758 bool sge(const APInt& RHS) const {
763 /// @name Resizing Operators
765 /// Truncate the APInt to a specified width. It is an error to specify a width
766 /// that is greater than or equal to the current width.
767 /// @brief Truncate to new width.
768 APInt &trunc(uint32_t width);
770 /// This operation sign extends the APInt to a new width. If the high order
771 /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
772 /// It is an error to specify a width that is less than or equal to the
774 /// @brief Sign extend to a new width.
775 APInt &sext(uint32_t width);
777 /// This operation zero extends the APInt to a new width. The high order bits
778 /// are filled with 0 bits. It is an error to specify a width that is less
779 /// than or equal to the current width.
780 /// @brief Zero extend to a new width.
781 APInt &zext(uint32_t width);
783 /// Make this APInt have the bit width given by \p width. The value is sign
784 /// extended, truncated, or left alone to make it that width.
785 /// @brief Sign extend or truncate to width
786 APInt &sextOrTrunc(uint32_t width);
788 /// Make this APInt have the bit width given by \p width. The value is zero
789 /// extended, truncated, or left alone to make it that width.
790 /// @brief Zero extend or truncate to width
791 APInt &zextOrTrunc(uint32_t width);
794 /// @name Bit Manipulation Operators
796 /// @brief Set every bit to 1.
799 /// Set the given bit to 1 whose position is given as "bitPosition".
800 /// @brief Set a given bit to 1.
801 APInt& set(uint32_t bitPosition);
803 /// @brief Set every bit to 0.
806 /// Set the given bit to 0 whose position is given as "bitPosition".
807 /// @brief Set a given bit to 0.
808 APInt& clear(uint32_t bitPosition);
810 /// @brief Toggle every bit to its opposite value.
813 /// Toggle a given bit to its opposite value whose position is given
814 /// as "bitPosition".
815 /// @brief Toggles a given bit to its opposite value.
816 APInt& flip(uint32_t bitPosition);
819 /// @name Value Characterization Functions
822 /// @returns the total number of bits.
823 inline uint32_t getBitWidth() const {
827 /// Here one word's bitwidth equals to that of uint64_t.
828 /// @returns the number of words to hold the integer value of this APInt.
829 /// @brief Get the number of words.
830 inline uint32_t getNumWords() const {
831 return (BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
834 /// This function returns the number of active bits which is defined as the
835 /// bit width minus the number of leading zeros. This is used in several
836 /// computations to see how "wide" the value is.
837 /// @brief Compute the number of active bits in the value
838 inline uint32_t getActiveBits() const {
839 return BitWidth - countLeadingZeros();
842 /// This function returns the number of active words in the value of this
843 /// APInt. This is used in conjunction with getActiveData to extract the raw
844 /// value of the APInt.
845 inline uint32_t getActiveWords() const {
846 return whichWord(getActiveBits()-1) + 1;
849 /// Computes the minimum bit width for this APInt while considering it to be
850 /// a signed (and probably negative) value. If the value is not negative,
851 /// this function returns the same value as getActiveBits(). Otherwise, it
852 /// returns the smallest bit width that will retain the negative value. For
853 /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
854 /// for -1, this function will always return 1.
855 /// @brief Get the minimum bit size for this signed APInt
856 inline uint32_t getMinSignedBits() const {
858 return BitWidth - countLeadingOnes() + 1;
859 return getActiveBits()+1;
862 /// This method attempts to return the value of this APInt as a zero extended
863 /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
864 /// uint64_t. Otherwise an assertion will result.
865 /// @brief Get zero extended value
866 inline uint64_t getZExtValue() const {
869 assert(getActiveBits() <= 64 && "Too many bits for uint64_t");
873 /// This method attempts to return the value of this APInt as a sign extended
874 /// int64_t. The bit width must be <= 64 or the value must fit within an
875 /// int64_t. Otherwise an assertion will result.
876 /// @brief Get sign extended value
877 inline int64_t getSExtValue() const {
879 return int64_t(VAL << (APINT_BITS_PER_WORD - BitWidth)) >>
880 (APINT_BITS_PER_WORD - BitWidth);
881 assert(getActiveBits() <= 64 && "Too many bits for int64_t");
882 return int64_t(pVal[0]);
885 /// This method determines how many bits are required to hold the APInt
886 /// equivalent of the string given by \p str of length \p slen.
887 /// @brief Get bits required for string value.
888 static uint32_t getBitsNeeded(const char* str, uint32_t slen, uint8_t radix);
890 /// countLeadingZeros - This function is an APInt version of the
891 /// countLeadingZeros_{32,64} functions in MathExtras.h. It counts the number
892 /// of zeros from the most significant bit to the first one bit.
893 /// @returns getNumWords() * APINT_BITS_PER_WORD if the value is zero.
894 /// @returns the number of zeros from the most significant bit to the first
896 /// @brief Count the number of leading one bits.
897 uint32_t countLeadingZeros() const;
899 /// countLeadingOnes - This function counts the number of contiguous 1 bits
900 /// in the high order bits. The count stops when the first 0 bit is reached.
901 /// @returns 0 if the high order bit is not set
902 /// @returns the number of 1 bits from the most significant to the least
903 /// @brief Count the number of leading one bits.
904 uint32_t countLeadingOnes() const;
906 /// countTrailingZeros - This function is an APInt version of the
907 /// countTrailingZoers_{32,64} functions in MathExtras.h. It counts
908 /// the number of zeros from the least significant bit to the first one bit.
909 /// @returns getNumWords() * APINT_BITS_PER_WORD if the value is zero.
910 /// @returns the number of zeros from the least significant bit to the first
912 /// @brief Count the number of trailing zero bits.
913 uint32_t countTrailingZeros() const;
915 /// countPopulation - This function is an APInt version of the
916 /// countPopulation_{32,64} functions in MathExtras.h. It counts the number
917 /// of 1 bits in the APInt value.
918 /// @returns 0 if the value is zero.
919 /// @returns the number of set bits.
920 /// @brief Count the number of bits set.
921 uint32_t countPopulation() const;
924 /// @name Conversion Functions
927 /// This is used internally to convert an APInt to a string.
928 /// @brief Converts an APInt to a std::string
929 std::string toString(uint8_t radix, bool wantSigned) const;
931 /// Considers the APInt to be unsigned and converts it into a string in the
932 /// radix given. The radix can be 2, 8, 10 or 16.
933 /// @returns a character interpretation of the APInt
934 /// @brief Convert unsigned APInt to string representation.
935 inline std::string toStringUnsigned(uint8_t radix = 10) const {
936 return toString(radix, false);
939 /// Considers the APInt to be unsigned and converts it into a string in the
940 /// radix given. The radix can be 2, 8, 10 or 16.
941 /// @returns a character interpretation of the APInt
942 /// @brief Convert unsigned APInt to string representation.
943 inline std::string toStringSigned(uint8_t radix = 10) const {
944 return toString(radix, true);
947 /// @returns a byte-swapped representation of this APInt Value.
948 APInt byteSwap() const;
950 /// @brief Converts this APInt to a double value.
951 double roundToDouble(bool isSigned) const;
953 /// @brief Converts this unsigned APInt to a double value.
954 double roundToDouble() const {
955 return roundToDouble(false);
958 /// @brief Converts this signed APInt to a double value.
959 double signedRoundToDouble() const {
960 return roundToDouble(true);
963 /// The conversion does not do a translation from integer to double, it just
964 /// re-interprets the bits as a double. Note that it is valid to do this on
965 /// any bit width. Exactly 64 bits will be translated.
966 /// @brief Converts APInt bits to a double
967 double bitsToDouble() const {
972 T.I = (isSingleWord() ? VAL : pVal[0]);
976 /// The conversion does not do a translation from integer to float, it just
977 /// re-interprets the bits as a float. Note that it is valid to do this on
978 /// any bit width. Exactly 32 bits will be translated.
979 /// @brief Converts APInt bits to a double
980 float bitsToFloat() const {
985 T.I = uint32_t((isSingleWord() ? VAL : pVal[0]));
989 /// The conversion does not do a translation from double to integer, it just
990 /// re-interprets the bits of the double. Note that it is valid to do this on
991 /// any bit width but bits from V may get truncated.
992 /// @brief Converts a double to APInt bits.
993 APInt& doubleToBits(double V) {
1003 return clearUnusedBits();
1006 /// The conversion does not do a translation from float to integer, it just
1007 /// re-interprets the bits of the float. Note that it is valid to do this on
1008 /// any bit width but bits from V may get truncated.
1009 /// @brief Converts a float to APInt bits.
1010 APInt& floatToBits(float V) {
1020 return clearUnusedBits();
1024 /// @name Mathematics Operations
1027 /// @returns the floor log base 2 of this APInt.
1028 inline uint32_t logBase2() const {
1029 return BitWidth - 1 - countLeadingZeros();
1032 /// @returns the log base 2 of this APInt if its an exact power of two, -1
1034 inline int32_t exactLogBase2() const {
1040 /// @brief Compute the square root
1043 /// If *this is < 0 then return -(*this), otherwise *this;
1044 /// @brief Get the absolute value;
1054 /// @name Building-block Operations for APInt and APFloat
1057 // These building block operations operate on a representation of
1058 // arbitrary precision, two's-complement, bignum integer values.
1059 // They should be sufficient to implement APInt and APFloat bignum
1060 // requirements. Inputs are generally a pointer to the base of an
1061 // array of integer parts, representing an unsigned bignum, and a
1062 // count of how many parts there are.
1064 /// Sets the least significant part of a bignum to the input value,
1065 /// and zeroes out higher parts. */
1066 static void tcSet(integerPart *, integerPart, unsigned int);
1068 /// Assign one bignum to another.
1069 static void tcAssign(integerPart *, const integerPart *, unsigned int);
1071 /// Returns true if a bignum is zero, false otherwise.
1072 static bool tcIsZero(const integerPart *, unsigned int);
1074 /// Extract the given bit of a bignum; returns 0 or 1. Zero-based.
1075 static int tcExtractBit(const integerPart *, unsigned int bit);
1077 /// Set the given bit of a bignum. Zero-based.
1078 static void tcSetBit(integerPart *, unsigned int bit);
1080 /// Returns the bit number of the least or most significant set bit
1081 /// of a number. If the input number has no bits set -1U is
1083 static unsigned int tcLSB(const integerPart *, unsigned int);
1084 static unsigned int tcMSB(const integerPart *, unsigned int);
1086 /// Negate a bignum in-place.
1087 static void tcNegate(integerPart *, unsigned int);
1089 /// DST += RHS + CARRY where CARRY is zero or one. Returns the
1091 static integerPart tcAdd(integerPart *, const integerPart *,
1092 integerPart carry, unsigned);
1094 /// DST -= RHS + CARRY where CARRY is zero or one. Returns the
1096 static integerPart tcSubtract(integerPart *, const integerPart *,
1097 integerPart carry, unsigned);
1099 /// DST += SRC * MULTIPLIER + PART if add is true
1100 /// DST = SRC * MULTIPLIER + PART if add is false
1102 /// Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC
1103 /// they must start at the same point, i.e. DST == SRC.
1105 /// If DSTPARTS == SRC_PARTS + 1 no overflow occurs and zero is
1106 /// returned. Otherwise DST is filled with the least significant
1107 /// DSTPARTS parts of the result, and if all of the omitted higher
1108 /// parts were zero return zero, otherwise overflow occurred and
1110 static int tcMultiplyPart(integerPart *dst, const integerPart *src,
1111 integerPart multiplier, integerPart carry,
1112 unsigned int srcParts, unsigned int dstParts,
1115 /// DST = LHS * RHS, where DST has the same width as the operands
1116 /// and is filled with the least significant parts of the result.
1117 /// Returns one if overflow occurred, otherwise zero. DST must be
1118 /// disjoint from both operands.
1119 static int tcMultiply(integerPart *, const integerPart *,
1120 const integerPart *, unsigned);
1122 /// DST = LHS * RHS, where DST has twice the width as the operands.
1123 /// No overflow occurs. DST must be disjoint from both operands.
1124 static void tcFullMultiply(integerPart *, const integerPart *,
1125 const integerPart *, unsigned);
1127 /// If RHS is zero LHS and REMAINDER are left unchanged, return one.
1128 /// Otherwise set LHS to LHS / RHS with the fractional part
1129 /// discarded, set REMAINDER to the remainder, return zero. i.e.
1131 /// OLD_LHS = RHS * LHS + REMAINDER
1133 /// SCRATCH is a bignum of the same size as the operands and result
1134 /// for use by the routine; its contents need not be initialized
1135 /// and are destroyed. LHS, REMAINDER and SCRATCH must be
1137 static int tcDivide(integerPart *lhs, const integerPart *rhs,
1138 integerPart *remainder, integerPart *scratch,
1139 unsigned int parts);
1141 /// Shift a bignum left COUNT bits. Shifted in bits are zero.
1142 /// There are no restrictions on COUNT.
1143 static void tcShiftLeft(integerPart *, unsigned int parts,
1144 unsigned int count);
1146 /// Shift a bignum right COUNT bits. Shifted in bits are zero.
1147 /// There are no restrictions on COUNT.
1148 static void tcShiftRight(integerPart *, unsigned int parts,
1149 unsigned int count);
1151 /// The obvious AND, OR and XOR and complement operations.
1152 static void tcAnd(integerPart *, const integerPart *, unsigned int);
1153 static void tcOr(integerPart *, const integerPart *, unsigned int);
1154 static void tcXor(integerPart *, const integerPart *, unsigned int);
1155 static void tcComplement(integerPart *, unsigned int);
1157 /// Comparison (unsigned) of two bignums.
1158 static int tcCompare(const integerPart *, const integerPart *,
1161 /// Increment a bignum in-place. Return the carry flag.
1162 static integerPart tcIncrement(integerPart *, unsigned int);
1164 /// Set the least significant BITS and clear the rest.
1165 static void tcSetLeastSignificantBits(integerPart *, unsigned int,
1171 inline bool operator==(uint64_t V1, const APInt& V2) {
1175 inline bool operator!=(uint64_t V1, const APInt& V2) {
1179 namespace APIntOps {
1181 /// @brief Determine the smaller of two APInts considered to be signed.
1182 inline APInt smin(const APInt &A, const APInt &B) {
1183 return A.slt(B) ? A : B;
1186 /// @brief Determine the larger of two APInts considered to be signed.
1187 inline APInt smax(const APInt &A, const APInt &B) {
1188 return A.sgt(B) ? A : B;
1191 /// @brief Determine the smaller of two APInts considered to be signed.
1192 inline APInt umin(const APInt &A, const APInt &B) {
1193 return A.ult(B) ? A : B;
1196 /// @brief Determine the larger of two APInts considered to be unsigned.
1197 inline APInt umax(const APInt &A, const APInt &B) {
1198 return A.ugt(B) ? A : B;
1201 /// @brief Check if the specified APInt has a N-bits integer value.
1202 inline bool isIntN(uint32_t N, const APInt& APIVal) {
1203 return APIVal.isIntN(N);
1206 /// @returns true if the argument APInt value is a sequence of ones
1207 /// starting at the least significant bit with the remainder zero.
1208 inline bool isMask(uint32_t numBits, const APInt& APIVal) {
1209 return APIVal.getBoolValue() && ((APIVal + APInt(numBits,1)) & APIVal) == 0;
1212 /// @returns true if the argument APInt value contains a sequence of ones
1213 /// with the remainder zero.
1214 inline bool isShiftedMask(uint32_t numBits, const APInt& APIVal) {
1215 return isMask(numBits, (APIVal - APInt(numBits,1)) | APIVal);
1218 /// @returns a byte-swapped representation of the specified APInt Value.
1219 inline APInt byteSwap(const APInt& APIVal) {
1220 return APIVal.byteSwap();
1223 /// @returns the floor log base 2 of the specified APInt value.
1224 inline uint32_t logBase2(const APInt& APIVal) {
1225 return APIVal.logBase2();
1228 /// GreatestCommonDivisor - This function returns the greatest common
1229 /// divisor of the two APInt values using Enclid's algorithm.
1230 /// @returns the greatest common divisor of Val1 and Val2
1231 /// @brief Compute GCD of two APInt values.
1232 APInt GreatestCommonDivisor(const APInt& Val1, const APInt& Val2);
1234 /// Treats the APInt as an unsigned value for conversion purposes.
1235 /// @brief Converts the given APInt to a double value.
1236 inline double RoundAPIntToDouble(const APInt& APIVal) {
1237 return APIVal.roundToDouble();
1240 /// Treats the APInt as a signed value for conversion purposes.
1241 /// @brief Converts the given APInt to a double value.
1242 inline double RoundSignedAPIntToDouble(const APInt& APIVal) {
1243 return APIVal.signedRoundToDouble();
1246 /// @brief Converts the given APInt to a float vlalue.
1247 inline float RoundAPIntToFloat(const APInt& APIVal) {
1248 return float(RoundAPIntToDouble(APIVal));
1251 /// Treast the APInt as a signed value for conversion purposes.
1252 /// @brief Converts the given APInt to a float value.
1253 inline float RoundSignedAPIntToFloat(const APInt& APIVal) {
1254 return float(APIVal.signedRoundToDouble());
1257 /// RoundDoubleToAPInt - This function convert a double value to an APInt value.
1258 /// @brief Converts the given double value into a APInt.
1259 APInt RoundDoubleToAPInt(double Double, uint32_t width);
1261 /// RoundFloatToAPInt - Converts a float value into an APInt value.
1262 /// @brief Converts a float value into a APInt.
1263 inline APInt RoundFloatToAPInt(float Float, uint32_t width) {
1264 return RoundDoubleToAPInt(double(Float), width);
1267 /// Arithmetic right-shift the APInt by shiftAmt.
1268 /// @brief Arithmetic right-shift function.
1269 inline APInt ashr(const APInt& LHS, uint32_t shiftAmt) {
1270 return LHS.ashr(shiftAmt);
1273 /// Logical right-shift the APInt by shiftAmt.
1274 /// @brief Logical right-shift function.
1275 inline APInt lshr(const APInt& LHS, uint32_t shiftAmt) {
1276 return LHS.lshr(shiftAmt);
1279 /// Left-shift the APInt by shiftAmt.
1280 /// @brief Left-shift function.
1281 inline APInt shl(const APInt& LHS, uint32_t shiftAmt) {
1282 return LHS.shl(shiftAmt);
1285 /// Signed divide APInt LHS by APInt RHS.
1286 /// @brief Signed division function for APInt.
1287 inline APInt sdiv(const APInt& LHS, const APInt& RHS) {
1288 return LHS.sdiv(RHS);
1291 /// Unsigned divide APInt LHS by APInt RHS.
1292 /// @brief Unsigned division function for APInt.
1293 inline APInt udiv(const APInt& LHS, const APInt& RHS) {
1294 return LHS.udiv(RHS);
1297 /// Signed remainder operation on APInt.
1298 /// @brief Function for signed remainder operation.
1299 inline APInt srem(const APInt& LHS, const APInt& RHS) {
1300 return LHS.srem(RHS);
1303 /// Unsigned remainder operation on APInt.
1304 /// @brief Function for unsigned remainder operation.
1305 inline APInt urem(const APInt& LHS, const APInt& RHS) {
1306 return LHS.urem(RHS);
1309 /// Performs multiplication on APInt values.
1310 /// @brief Function for multiplication operation.
1311 inline APInt mul(const APInt& LHS, const APInt& RHS) {
1315 /// Performs addition on APInt values.
1316 /// @brief Function for addition operation.
1317 inline APInt add(const APInt& LHS, const APInt& RHS) {
1321 /// Performs subtraction on APInt values.
1322 /// @brief Function for subtraction operation.
1323 inline APInt sub(const APInt& LHS, const APInt& RHS) {
1327 /// Performs bitwise AND operation on APInt LHS and
1329 /// @brief Bitwise AND function for APInt.
1330 inline APInt And(const APInt& LHS, const APInt& RHS) {
1334 /// Performs bitwise OR operation on APInt LHS and APInt RHS.
1335 /// @brief Bitwise OR function for APInt.
1336 inline APInt Or(const APInt& LHS, const APInt& RHS) {
1340 /// Performs bitwise XOR operation on APInt.
1341 /// @brief Bitwise XOR function for APInt.
1342 inline APInt Xor(const APInt& LHS, const APInt& RHS) {
1346 /// Performs a bitwise complement operation on APInt.
1347 /// @brief Bitwise complement function.
1348 inline APInt Not(const APInt& APIVal) {
1352 } // End of APIntOps namespace
1354 } // End of llvm namespace