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 /// @name Constructors
159 /// If isSigned is true then val is treated as if it were a signed value
160 /// (i.e. as an int64_t) and the appropriate sign extension to the bit width
161 /// will be done. Otherwise, no sign extension occurs (high order bits beyond
162 /// the range of val are zero filled).
163 /// @param numBits the bit width of the constructed APInt
164 /// @param val the initial value of the APInt
165 /// @param isSigned how to treat signedness of val
166 /// @brief Create a new APInt of numBits width, initialized as val.
167 APInt(uint32_t numBits, uint64_t val, bool isSigned = false);
169 /// Note that numWords can be smaller or larger than the corresponding bit
170 /// width but any extraneous bits will be dropped.
171 /// @param numBits the bit width of the constructed APInt
172 /// @param numWords the number of words in bigVal
173 /// @param bigVal a sequence of words to form the initial value of the APInt
174 /// @brief Construct an APInt of numBits width, initialized as bigVal[].
175 APInt(uint32_t numBits, uint32_t numWords, const uint64_t bigVal[]);
177 /// This constructor interprets Val as a string in the given radix. The
178 /// interpretation stops when the first charater that is not suitable for the
179 /// radix is encountered. Acceptable radix values are 2, 8, 10 and 16. It is
180 /// an error for the value implied by the string to require more bits than
182 /// @param numBits the bit width of the constructed APInt
183 /// @param val the string to be interpreted
184 /// @param radix the radix of Val to use for the intepretation
185 /// @brief Construct an APInt from a string representation.
186 APInt(uint32_t numBits, const std::string& val, uint8_t radix);
188 /// This constructor interprets the slen characters starting at StrStart as
189 /// a string in the given radix. The interpretation stops when the first
190 /// character that is not suitable for the radix is encountered. Acceptable
191 /// radix values are 2, 8, 10 and 16. It is an error for the value implied by
192 /// the string to require more bits than numBits.
193 /// @param numBits the bit width of the constructed APInt
194 /// @param strStart the start of the string to be interpreted
195 /// @param slen the maximum number of characters to interpret
196 /// @param radix the radix to use for the conversion
197 /// @brief Construct an APInt from a string representation.
198 APInt(uint32_t numBits, const char strStart[], uint32_t slen, uint8_t radix);
200 /// Simply makes *this a copy of that.
201 /// @brief Copy Constructor.
202 APInt(const APInt& that);
204 /// @brief Destructor.
208 /// @name Value Tests
210 /// This tests the high bit of this APInt to determine if it is set.
211 /// @returns true if this APInt is negative, false otherwise
212 /// @brief Determine sign of this APInt.
213 bool isNegative() const {
214 return (*this)[BitWidth - 1];
217 /// This tests the high bit of the APInt to determine if it is unset.
218 /// @brief Determine if this APInt Value is positive (not negative).
219 bool isPositive() const {
220 return !isNegative();
223 /// This tests if the value of this APInt is strictly positive (> 0).
224 /// @returns true if this APInt is Positive and not zero.
225 /// @brief Determine if this APInt Value is strictly positive.
226 inline bool isStrictlyPositive() const {
227 return isPositive() && (*this) != 0;
230 /// This checks to see if the value has all bits of the APInt are set or not.
231 /// @brief Determine if all bits are set
232 inline bool isAllOnesValue() const {
233 return countPopulation() == BitWidth;
236 /// This checks to see if the value of this APInt is the maximum unsigned
237 /// value for the APInt's bit width.
238 /// @brief Determine if this is the largest unsigned value.
239 bool isMaxValue() const {
240 return countPopulation() == BitWidth;
243 /// This checks to see if the value of this APInt is the maximum signed
244 /// value for the APInt's bit width.
245 /// @brief Determine if this is the largest signed value.
246 bool isMaxSignedValue() const {
247 return BitWidth == 1 ? VAL == 0 :
248 !isNegative() && countPopulation() == BitWidth - 1;
251 /// This checks to see if the value of this APInt is the minimum unsigned
252 /// value for the APInt's bit width.
253 /// @brief Determine if this is the smallest unsigned value.
254 bool isMinValue() const {
255 return countPopulation() == 0;
258 /// This checks to see if the value of this APInt is the minimum signed
259 /// value for the APInt's bit width.
260 /// @brief Determine if this is the smallest signed value.
261 bool isMinSignedValue() const {
262 return BitWidth == 1 ? VAL == 1 :
263 isNegative() && countPopulation() == 1;
266 /// @brief Check if this APInt has an N-bits integer value.
267 inline bool isIntN(uint32_t N) const {
268 assert(N && "N == 0 ???");
269 if (isSingleWord()) {
270 return VAL == (VAL & (~0ULL >> (64 - N)));
272 APInt Tmp(N, getNumWords(), pVal);
273 return Tmp == (*this);
277 /// @returns true if the argument APInt value is a power of two > 0.
278 bool isPowerOf2() const;
280 /// isSignBit - Return true if this is the value returned by getSignBit.
281 bool isSignBit() const { return isMinSignedValue(); }
283 /// This converts the APInt to a boolean value as a test against zero.
284 /// @brief Boolean conversion function.
285 inline bool getBoolValue() const {
289 /// getLimitedValue - If this value is smaller than the specified limit,
290 /// return it, otherwise return the limit value. This causes the value
291 /// to saturate to the limit.
292 uint64_t getLimitedValue(uint64_t Limit = ~0ULL) const {
293 return (getActiveBits() > 64 || getZExtValue() > Limit) ?
294 Limit : getZExtValue();
298 /// @name Value Generators
300 /// @brief Gets maximum unsigned value of APInt for specific bit width.
301 static APInt getMaxValue(uint32_t numBits) {
302 return APInt(numBits, 0).set();
305 /// @brief Gets maximum signed value of APInt for a specific bit width.
306 static APInt getSignedMaxValue(uint32_t numBits) {
307 return APInt(numBits, 0).set().clear(numBits - 1);
310 /// @brief Gets minimum unsigned value of APInt for a specific bit width.
311 static APInt getMinValue(uint32_t numBits) {
312 return APInt(numBits, 0);
315 /// @brief Gets minimum signed value of APInt for a specific bit width.
316 static APInt getSignedMinValue(uint32_t numBits) {
317 return APInt(numBits, 0).set(numBits - 1);
320 /// getSignBit - This is just a wrapper function of getSignedMinValue(), and
321 /// it helps code readability when we want to get a SignBit.
322 /// @brief Get the SignBit for a specific bit width.
323 inline static APInt getSignBit(uint32_t BitWidth) {
324 return getSignedMinValue(BitWidth);
327 /// @returns the all-ones value for an APInt of the specified bit-width.
328 /// @brief Get the all-ones value.
329 static APInt getAllOnesValue(uint32_t numBits) {
330 return APInt(numBits, 0).set();
333 /// @returns the '0' value for an APInt of the specified bit-width.
334 /// @brief Get the '0' value.
335 static APInt getNullValue(uint32_t numBits) {
336 return APInt(numBits, 0);
339 /// Get an APInt with the same BitWidth as this APInt, just zero mask
340 /// the low bits and right shift to the least significant bit.
341 /// @returns the high "numBits" bits of this APInt.
342 APInt getHiBits(uint32_t numBits) const;
344 /// Get an APInt with the same BitWidth as this APInt, just zero mask
346 /// @returns the low "numBits" bits of this APInt.
347 APInt getLoBits(uint32_t numBits) const;
349 /// Constructs an APInt value that has a contiguous range of bits set. The
350 /// bits from loBit to hiBit will be set. All other bits will be zero. For
351 /// example, with parameters(32, 15, 0) you would get 0x0000FFFF. If hiBit is
352 /// less than loBit then the set bits "wrap". For example, with
353 /// parameters (32, 3, 28), you would get 0xF000000F.
354 /// @param numBits the intended bit width of the result
355 /// @param loBit the index of the lowest bit set.
356 /// @param hiBit the index of the highest bit set.
357 /// @returns An APInt value with the requested bits set.
358 /// @brief Get a value with a block of bits set.
359 static APInt getBitsSet(uint32_t numBits, uint32_t loBit, uint32_t hiBit) {
360 assert(hiBit < numBits && "hiBit out of range");
361 assert(loBit < numBits && "loBit out of range");
363 return getLowBitsSet(numBits, hiBit+1) |
364 getHighBitsSet(numBits, numBits-loBit+1);
365 return getLowBitsSet(numBits, hiBit-loBit+1).shl(loBit);
368 /// Constructs an APInt value that has the top hiBitsSet bits set.
369 /// @param numBits the bitwidth of the result
370 /// @param hiBitsSet the number of high-order bits set in the result.
371 /// @brief Get a value with high bits set
372 static APInt getHighBitsSet(uint32_t numBits, uint32_t hiBitsSet) {
373 assert(hiBitsSet <= numBits && "Too many bits to set!");
374 // Handle a degenerate case, to avoid shifting by word size
376 return APInt(numBits, 0);
377 uint32_t shiftAmt = numBits - hiBitsSet;
378 // For small values, return quickly
379 if (numBits <= APINT_BITS_PER_WORD)
380 return APInt(numBits, ~0ULL << shiftAmt);
381 return (~APInt(numBits, 0)).shl(shiftAmt);
384 /// Constructs an APInt value that has the bottom loBitsSet bits set.
385 /// @param numBits the bitwidth of the result
386 /// @param loBitsSet the number of low-order bits set in the result.
387 /// @brief Get a value with low bits set
388 static APInt getLowBitsSet(uint32_t numBits, uint32_t loBitsSet) {
389 assert(loBitsSet <= numBits && "Too many bits to set!");
390 // Handle a degenerate case, to avoid shifting by word size
392 return APInt(numBits, 0);
393 if (loBitsSet == APINT_BITS_PER_WORD)
394 return APInt(numBits, -1ULL);
395 // For small values, return quickly
396 if (numBits < APINT_BITS_PER_WORD)
397 return APInt(numBits, (1ULL << loBitsSet) - 1);
398 return (~APInt(numBits, 0)).lshr(numBits - loBitsSet);
401 /// The hash value is computed as the sum of the words and the bit width.
402 /// @returns A hash value computed from the sum of the APInt words.
403 /// @brief Get a hash value based on this APInt
404 uint64_t getHashValue() const;
406 /// This function returns a pointer to the internal storage of the APInt.
407 /// This is useful for writing out the APInt in binary form without any
409 inline const uint64_t* getRawData() const {
416 /// @name Unary Operators
418 /// @returns a new APInt value representing *this incremented by one
419 /// @brief Postfix increment operator.
420 inline const APInt operator++(int) {
426 /// @returns *this incremented by one
427 /// @brief Prefix increment operator.
430 /// @returns a new APInt representing *this decremented by one.
431 /// @brief Postfix decrement operator.
432 inline const APInt operator--(int) {
438 /// @returns *this decremented by one.
439 /// @brief Prefix decrement operator.
442 /// Performs a bitwise complement operation on this APInt.
443 /// @returns an APInt that is the bitwise complement of *this
444 /// @brief Unary bitwise complement operator.
445 APInt operator~() const;
447 /// Negates *this using two's complement logic.
448 /// @returns An APInt value representing the negation of *this.
449 /// @brief Unary negation operator
450 inline APInt operator-() const {
451 return APInt(BitWidth, 0) - (*this);
454 /// Performs logical negation operation on this APInt.
455 /// @returns true if *this is zero, false otherwise.
456 /// @brief Logical negation operator.
457 bool operator !() const;
460 /// @name Assignment Operators
462 /// @returns *this after assignment of RHS.
463 /// @brief Copy assignment operator.
464 APInt& operator=(const APInt& RHS);
466 /// The RHS value is assigned to *this. If the significant bits in RHS exceed
467 /// the bit width, the excess bits are truncated. If the bit width is larger
468 /// than 64, the value is zero filled in the unspecified high order bits.
469 /// @returns *this after assignment of RHS value.
470 /// @brief Assignment operator.
471 APInt& operator=(uint64_t RHS);
473 /// Performs a bitwise AND operation on this APInt and RHS. The result is
474 /// assigned to *this.
475 /// @returns *this after ANDing with RHS.
476 /// @brief Bitwise AND assignment operator.
477 APInt& operator&=(const APInt& RHS);
479 /// Performs a bitwise OR operation on this APInt and RHS. The result is
481 /// @returns *this after ORing with RHS.
482 /// @brief Bitwise OR assignment operator.
483 APInt& operator|=(const APInt& RHS);
485 /// Performs a bitwise XOR operation on this APInt and RHS. The result is
486 /// assigned to *this.
487 /// @returns *this after XORing with RHS.
488 /// @brief Bitwise XOR assignment operator.
489 APInt& operator^=(const APInt& RHS);
491 /// Multiplies this APInt by RHS and assigns the result to *this.
493 /// @brief Multiplication assignment operator.
494 APInt& operator*=(const APInt& RHS);
496 /// Adds RHS to *this and assigns the result to *this.
498 /// @brief Addition assignment operator.
499 APInt& operator+=(const APInt& RHS);
501 /// Subtracts RHS from *this and assigns the result to *this.
503 /// @brief Subtraction assignment operator.
504 APInt& operator-=(const APInt& RHS);
506 /// Shifts *this left by shiftAmt and assigns the result to *this.
507 /// @returns *this after shifting left by shiftAmt
508 /// @brief Left-shift assignment function.
509 inline APInt& operator<<=(uint32_t shiftAmt) {
510 *this = shl(shiftAmt);
515 /// @name Binary Operators
517 /// Performs a bitwise AND operation on *this and RHS.
518 /// @returns An APInt value representing the bitwise AND of *this and RHS.
519 /// @brief Bitwise AND operator.
520 APInt operator&(const APInt& RHS) const;
521 APInt And(const APInt& RHS) const {
522 return this->operator&(RHS);
525 /// Performs a bitwise OR operation on *this and RHS.
526 /// @returns An APInt value representing the bitwise OR of *this and RHS.
527 /// @brief Bitwise OR operator.
528 APInt operator|(const APInt& RHS) const;
529 APInt Or(const APInt& RHS) const {
530 return this->operator|(RHS);
533 /// Performs a bitwise XOR operation on *this and RHS.
534 /// @returns An APInt value representing the bitwise XOR of *this and RHS.
535 /// @brief Bitwise XOR operator.
536 APInt operator^(const APInt& RHS) const;
537 APInt Xor(const APInt& RHS) const {
538 return this->operator^(RHS);
541 /// Multiplies this APInt by RHS and returns the result.
542 /// @brief Multiplication operator.
543 APInt operator*(const APInt& RHS) const;
545 /// Adds RHS to this APInt and returns the result.
546 /// @brief Addition operator.
547 APInt operator+(const APInt& RHS) const;
548 APInt operator+(uint64_t RHS) const {
549 return (*this) + APInt(BitWidth, RHS);
552 /// Subtracts RHS from this APInt and returns the result.
553 /// @brief Subtraction operator.
554 APInt operator-(const APInt& RHS) const;
555 APInt operator-(uint64_t RHS) const {
556 return (*this) - APInt(BitWidth, RHS);
559 APInt operator<<(unsigned Bits) const {
563 /// Arithmetic right-shift this APInt by shiftAmt.
564 /// @brief Arithmetic right-shift function.
565 APInt ashr(uint32_t shiftAmt) const;
567 /// Logical right-shift this APInt by shiftAmt.
568 /// @brief Logical right-shift function.
569 APInt lshr(uint32_t shiftAmt) const;
571 /// Left-shift this APInt by shiftAmt.
572 /// @brief Left-shift function.
573 APInt shl(uint32_t shiftAmt) const;
575 /// @brief Rotate left by rotateAmt.
576 APInt rotl(uint32_t rotateAmt) const;
578 /// @brief Rotate right by rotateAmt.
579 APInt rotr(uint32_t rotateAmt) const;
581 /// Perform an unsigned divide operation on this APInt by RHS. Both this and
582 /// RHS are treated as unsigned quantities for purposes of this division.
583 /// @returns a new APInt value containing the division result
584 /// @brief Unsigned division operation.
585 APInt udiv(const APInt& RHS) const;
587 /// Signed divide this APInt by APInt RHS.
588 /// @brief Signed division function for APInt.
589 inline APInt sdiv(const APInt& RHS) const {
591 if (RHS.isNegative())
592 return (-(*this)).udiv(-RHS);
594 return -((-(*this)).udiv(RHS));
595 else if (RHS.isNegative())
596 return -(this->udiv(-RHS));
597 return this->udiv(RHS);
600 /// Perform an unsigned remainder operation on this APInt with RHS being the
601 /// divisor. Both this and RHS are treated as unsigned quantities for purposes
602 /// of this operation. Note that this is a true remainder operation and not
603 /// a modulo operation because the sign follows the sign of the dividend
605 /// @returns a new APInt value containing the remainder result
606 /// @brief Unsigned remainder operation.
607 APInt urem(const APInt& RHS) const;
609 /// Signed remainder operation on APInt.
610 /// @brief Function for signed remainder operation.
611 inline APInt srem(const APInt& RHS) const {
613 if (RHS.isNegative())
614 return -((-(*this)).urem(-RHS));
616 return -((-(*this)).urem(RHS));
617 else if (RHS.isNegative())
618 return this->urem(-RHS);
619 return this->urem(RHS);
622 /// Sometimes it is convenient to divide two APInt values and obtain both
623 /// the quotient and remainder. This function does both operations in the
624 /// same computation making it a little more efficient.
625 /// @brief Dual division/remainder interface.
626 static void udivrem(const APInt &LHS, const APInt &RHS,
627 APInt &Quotient, APInt &Remainder);
629 static void sdivrem(const APInt &LHS, const APInt &RHS,
630 APInt &Quotient, APInt &Remainder)
632 if (LHS.isNegative()) {
633 if (RHS.isNegative())
634 APInt::udivrem(-LHS, -RHS, Quotient, Remainder);
636 APInt::udivrem(-LHS, RHS, Quotient, Remainder);
637 Quotient = -Quotient;
638 Remainder = -Remainder;
639 } else if (RHS.isNegative()) {
640 APInt::udivrem(LHS, -RHS, Quotient, Remainder);
641 Quotient = -Quotient;
643 APInt::udivrem(LHS, RHS, Quotient, Remainder);
647 /// @returns the bit value at bitPosition
648 /// @brief Array-indexing support.
649 bool operator[](uint32_t bitPosition) const;
652 /// @name Comparison Operators
654 /// Compares this APInt with RHS for the validity of the equality
656 /// @brief Equality operator.
657 bool operator==(const APInt& RHS) const;
659 /// Compares this APInt with a uint64_t for the validity of the equality
661 /// @returns true if *this == Val
662 /// @brief Equality operator.
663 bool operator==(uint64_t Val) const;
665 /// Compares this APInt with RHS for the validity of the equality
667 /// @returns true if *this == Val
668 /// @brief Equality comparison.
669 bool eq(const APInt &RHS) const {
670 return (*this) == RHS;
673 /// Compares this APInt with RHS for the validity of the inequality
675 /// @returns true if *this != Val
676 /// @brief Inequality operator.
677 inline bool operator!=(const APInt& RHS) const {
678 return !((*this) == RHS);
681 /// Compares this APInt with a uint64_t for the validity of the inequality
683 /// @returns true if *this != Val
684 /// @brief Inequality operator.
685 inline bool operator!=(uint64_t Val) const {
686 return !((*this) == Val);
689 /// Compares this APInt with RHS for the validity of the inequality
691 /// @returns true if *this != Val
692 /// @brief Inequality comparison
693 bool ne(const APInt &RHS) const {
694 return !((*this) == RHS);
697 /// Regards both *this and RHS as unsigned quantities and compares them for
698 /// the validity of the less-than relationship.
699 /// @returns true if *this < RHS when both are considered unsigned.
700 /// @brief Unsigned less than comparison
701 bool ult(const APInt& RHS) const;
703 /// Regards both *this and RHS as signed quantities and compares them for
704 /// validity of the less-than relationship.
705 /// @returns true if *this < RHS when both are considered signed.
706 /// @brief Signed less than comparison
707 bool slt(const APInt& RHS) const;
709 /// Regards both *this and RHS as unsigned quantities and compares them for
710 /// validity of the less-or-equal relationship.
711 /// @returns true if *this <= RHS when both are considered unsigned.
712 /// @brief Unsigned less or equal comparison
713 bool ule(const APInt& RHS) const {
714 return ult(RHS) || eq(RHS);
717 /// Regards both *this and RHS as signed quantities and compares them for
718 /// validity of the less-or-equal relationship.
719 /// @returns true if *this <= RHS when both are considered signed.
720 /// @brief Signed less or equal comparison
721 bool sle(const APInt& RHS) const {
722 return slt(RHS) || eq(RHS);
725 /// Regards both *this and RHS as unsigned quantities and compares them for
726 /// the validity of the greater-than relationship.
727 /// @returns true if *this > RHS when both are considered unsigned.
728 /// @brief Unsigned greather than comparison
729 bool ugt(const APInt& RHS) const {
730 return !ult(RHS) && !eq(RHS);
733 /// Regards both *this and RHS as signed quantities and compares them for
734 /// the validity of the greater-than relationship.
735 /// @returns true if *this > RHS when both are considered signed.
736 /// @brief Signed greather than comparison
737 bool sgt(const APInt& RHS) const {
738 return !slt(RHS) && !eq(RHS);
741 /// Regards both *this and RHS as unsigned quantities and compares them for
742 /// validity of the greater-or-equal relationship.
743 /// @returns true if *this >= RHS when both are considered unsigned.
744 /// @brief Unsigned greater or equal comparison
745 bool uge(const APInt& RHS) const {
749 /// Regards both *this and RHS as signed quantities and compares them for
750 /// validity of the greater-or-equal relationship.
751 /// @returns true if *this >= RHS when both are considered signed.
752 /// @brief Signed greather or equal comparison
753 bool sge(const APInt& RHS) const {
758 /// @name Resizing Operators
760 /// Truncate the APInt to a specified width. It is an error to specify a width
761 /// that is greater than or equal to the current width.
762 /// @brief Truncate to new width.
763 APInt &trunc(uint32_t width);
765 /// This operation sign extends the APInt to a new width. If the high order
766 /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
767 /// It is an error to specify a width that is less than or equal to the
769 /// @brief Sign extend to a new width.
770 APInt &sext(uint32_t width);
772 /// This operation zero extends the APInt to a new width. The high order bits
773 /// are filled with 0 bits. It is an error to specify a width that is less
774 /// than or equal to the current width.
775 /// @brief Zero extend to a new width.
776 APInt &zext(uint32_t width);
778 /// Make this APInt have the bit width given by \p width. The value is sign
779 /// extended, truncated, or left alone to make it that width.
780 /// @brief Sign extend or truncate to width
781 APInt &sextOrTrunc(uint32_t width);
783 /// Make this APInt have the bit width given by \p width. The value is zero
784 /// extended, truncated, or left alone to make it that width.
785 /// @brief Zero extend or truncate to width
786 APInt &zextOrTrunc(uint32_t width);
789 /// @name Bit Manipulation Operators
791 /// @brief Set every bit to 1.
794 /// Set the given bit to 1 whose position is given as "bitPosition".
795 /// @brief Set a given bit to 1.
796 APInt& set(uint32_t bitPosition);
798 /// @brief Set every bit to 0.
801 /// Set the given bit to 0 whose position is given as "bitPosition".
802 /// @brief Set a given bit to 0.
803 APInt& clear(uint32_t bitPosition);
805 /// @brief Toggle every bit to its opposite value.
808 /// Toggle a given bit to its opposite value whose position is given
809 /// as "bitPosition".
810 /// @brief Toggles a given bit to its opposite value.
811 APInt& flip(uint32_t bitPosition);
814 /// @name Value Characterization Functions
817 /// @returns the total number of bits.
818 inline uint32_t getBitWidth() const {
822 /// Here one word's bitwidth equals to that of uint64_t.
823 /// @returns the number of words to hold the integer value of this APInt.
824 /// @brief Get the number of words.
825 inline uint32_t getNumWords() const {
826 return (BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
829 /// This function returns the number of active bits which is defined as the
830 /// bit width minus the number of leading zeros. This is used in several
831 /// computations to see how "wide" the value is.
832 /// @brief Compute the number of active bits in the value
833 inline uint32_t getActiveBits() const {
834 return BitWidth - countLeadingZeros();
837 /// This function returns the number of active words in the value of this
838 /// APInt. This is used in conjunction with getActiveData to extract the raw
839 /// value of the APInt.
840 inline uint32_t getActiveWords() const {
841 return whichWord(getActiveBits()-1) + 1;
844 /// Computes the minimum bit width for this APInt while considering it to be
845 /// a signed (and probably negative) value. If the value is not negative,
846 /// this function returns the same value as getActiveBits(). Otherwise, it
847 /// returns the smallest bit width that will retain the negative value. For
848 /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
849 /// for -1, this function will always return 1.
850 /// @brief Get the minimum bit size for this signed APInt
851 inline uint32_t getMinSignedBits() const {
853 return BitWidth - countLeadingOnes() + 1;
854 return getActiveBits()+1;
857 /// This method attempts to return the value of this APInt as a zero extended
858 /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
859 /// uint64_t. Otherwise an assertion will result.
860 /// @brief Get zero extended value
861 inline uint64_t getZExtValue() const {
864 assert(getActiveBits() <= 64 && "Too many bits for uint64_t");
868 /// This method attempts to return the value of this APInt as a sign extended
869 /// int64_t. The bit width must be <= 64 or the value must fit within an
870 /// int64_t. Otherwise an assertion will result.
871 /// @brief Get sign extended value
872 inline int64_t getSExtValue() const {
874 return int64_t(VAL << (APINT_BITS_PER_WORD - BitWidth)) >>
875 (APINT_BITS_PER_WORD - BitWidth);
876 assert(getActiveBits() <= 64 && "Too many bits for int64_t");
877 return int64_t(pVal[0]);
880 /// This method determines how many bits are required to hold the APInt
881 /// equivalent of the string given by \p str of length \p slen.
882 /// @brief Get bits required for string value.
883 static uint32_t getBitsNeeded(const char* str, uint32_t slen, uint8_t radix);
885 /// countLeadingZeros - This function is an APInt version of the
886 /// countLeadingZeros_{32,64} functions in MathExtras.h. It counts the number
887 /// of zeros from the most significant bit to the first one bit.
888 /// @returns getNumWords() * APINT_BITS_PER_WORD if the value is zero.
889 /// @returns the number of zeros from the most significant bit to the first
891 /// @brief Count the number of leading one bits.
892 uint32_t countLeadingZeros() const;
894 /// countLeadingOnes - This function counts the number of contiguous 1 bits
895 /// in the high order bits. The count stops when the first 0 bit is reached.
896 /// @returns 0 if the high order bit is not set
897 /// @returns the number of 1 bits from the most significant to the least
898 /// @brief Count the number of leading one bits.
899 uint32_t countLeadingOnes() const;
901 /// countTrailingZeros - This function is an APInt version of the
902 /// countTrailingZoers_{32,64} functions in MathExtras.h. It counts
903 /// the number of zeros from the least significant bit to the first one bit.
904 /// @returns getNumWords() * APINT_BITS_PER_WORD if the value is zero.
905 /// @returns the number of zeros from the least significant bit to the first
907 /// @brief Count the number of trailing zero bits.
908 uint32_t countTrailingZeros() const;
910 /// countPopulation - This function is an APInt version of the
911 /// countPopulation_{32,64} functions in MathExtras.h. It counts the number
912 /// of 1 bits in the APInt value.
913 /// @returns 0 if the value is zero.
914 /// @returns the number of set bits.
915 /// @brief Count the number of bits set.
916 uint32_t countPopulation() const;
919 /// @name Conversion Functions
922 /// This is used internally to convert an APInt to a string.
923 /// @brief Converts an APInt to a std::string
924 std::string toString(uint8_t radix, bool wantSigned) const;
926 /// Considers the APInt to be unsigned and converts it into a string in the
927 /// radix given. The radix can be 2, 8, 10 or 16.
928 /// @returns a character interpretation of the APInt
929 /// @brief Convert unsigned APInt to string representation.
930 inline std::string toStringUnsigned(uint8_t radix = 10) const {
931 return toString(radix, false);
934 /// Considers the APInt to be unsigned and converts it into a string in the
935 /// radix given. The radix can be 2, 8, 10 or 16.
936 /// @returns a character interpretation of the APInt
937 /// @brief Convert unsigned APInt to string representation.
938 inline std::string toStringSigned(uint8_t radix = 10) const {
939 return toString(radix, true);
942 /// @returns a byte-swapped representation of this APInt Value.
943 APInt byteSwap() const;
945 /// @brief Converts this APInt to a double value.
946 double roundToDouble(bool isSigned) const;
948 /// @brief Converts this unsigned APInt to a double value.
949 double roundToDouble() const {
950 return roundToDouble(false);
953 /// @brief Converts this signed APInt to a double value.
954 double signedRoundToDouble() const {
955 return roundToDouble(true);
958 /// The conversion does not do a translation from integer to double, it just
959 /// re-interprets the bits as a double. Note that it is valid to do this on
960 /// any bit width. Exactly 64 bits will be translated.
961 /// @brief Converts APInt bits to a double
962 double bitsToDouble() const {
967 T.I = (isSingleWord() ? VAL : pVal[0]);
971 /// The conversion does not do a translation from integer to float, it just
972 /// re-interprets the bits as a float. Note that it is valid to do this on
973 /// any bit width. Exactly 32 bits will be translated.
974 /// @brief Converts APInt bits to a double
975 float bitsToFloat() const {
980 T.I = uint32_t((isSingleWord() ? VAL : pVal[0]));
984 /// The conversion does not do a translation from double to integer, it just
985 /// re-interprets the bits of the double. Note that it is valid to do this on
986 /// any bit width but bits from V may get truncated.
987 /// @brief Converts a double to APInt bits.
988 APInt& doubleToBits(double V) {
998 return clearUnusedBits();
1001 /// The conversion does not do a translation from float to integer, it just
1002 /// re-interprets the bits of the float. Note that it is valid to do this on
1003 /// any bit width but bits from V may get truncated.
1004 /// @brief Converts a float to APInt bits.
1005 APInt& floatToBits(float V) {
1015 return clearUnusedBits();
1019 /// @name Mathematics Operations
1022 /// @returns the floor log base 2 of this APInt.
1023 inline uint32_t logBase2() const {
1024 return BitWidth - 1 - countLeadingZeros();
1027 /// @returns the log base 2 of this APInt if its an exact power of two, -1
1029 inline int32_t exactLogBase2() const {
1035 /// @brief Compute the square root
1038 /// If *this is < 0 then return -(*this), otherwise *this;
1039 /// @brief Get the absolute value;
1049 /// @name Building-block Operations for APInt and APFloat
1052 // These building block operations operate on a representation of
1053 // arbitrary precision, two's-complement, bignum integer values.
1054 // They should be sufficient to implement APInt and APFloat bignum
1055 // requirements. Inputs are generally a pointer to the base of an
1056 // array of integer parts, representing an unsigned bignum, and a
1057 // count of how many parts there are.
1059 /// Sets the least significant part of a bignum to the input value,
1060 /// and zeroes out higher parts. */
1061 static void tcSet(integerPart *, integerPart, unsigned int);
1063 /// Assign one bignum to another.
1064 static void tcAssign(integerPart *, const integerPart *, unsigned int);
1066 /// Returns true if a bignum is zero, false otherwise.
1067 static bool tcIsZero(const integerPart *, unsigned int);
1069 /// Extract the given bit of a bignum; returns 0 or 1. Zero-based.
1070 static int tcExtractBit(const integerPart *, unsigned int bit);
1072 /// Copy the bit vector of width srcBITS from SRC, starting at bit
1073 /// srcLSB, to DST, of dstCOUNT parts, such that the bit srcLSB
1074 /// becomes the least significant bit of DST. All high bits above
1075 /// srcBITS in DST are zero-filled.
1076 static void tcExtract(integerPart *, unsigned int dstCount, const integerPart *,
1077 unsigned int srcBits, unsigned int srcLSB);
1079 /// Set the given bit of a bignum. Zero-based.
1080 static void tcSetBit(integerPart *, unsigned int bit);
1082 /// Returns the bit number of the least or most significant set bit
1083 /// of a number. If the input number has no bits set -1U is
1085 static unsigned int tcLSB(const integerPart *, unsigned int);
1086 static unsigned int tcMSB(const integerPart *, unsigned int);
1088 /// Negate a bignum in-place.
1089 static void tcNegate(integerPart *, unsigned int);
1091 /// DST += RHS + CARRY where CARRY is zero or one. Returns the
1093 static integerPart tcAdd(integerPart *, const integerPart *,
1094 integerPart carry, unsigned);
1096 /// DST -= RHS + CARRY where CARRY is zero or one. Returns the
1098 static integerPart tcSubtract(integerPart *, const integerPart *,
1099 integerPart carry, unsigned);
1101 /// DST += SRC * MULTIPLIER + PART if add is true
1102 /// DST = SRC * MULTIPLIER + PART if add is false
1104 /// Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC
1105 /// they must start at the same point, i.e. DST == SRC.
1107 /// If DSTPARTS == SRC_PARTS + 1 no overflow occurs and zero is
1108 /// returned. Otherwise DST is filled with the least significant
1109 /// DSTPARTS parts of the result, and if all of the omitted higher
1110 /// parts were zero return zero, otherwise overflow occurred and
1112 static int tcMultiplyPart(integerPart *dst, const integerPart *src,
1113 integerPart multiplier, integerPart carry,
1114 unsigned int srcParts, unsigned int dstParts,
1117 /// DST = LHS * RHS, where DST has the same width as the operands
1118 /// and is filled with the least significant parts of the result.
1119 /// Returns one if overflow occurred, otherwise zero. DST must be
1120 /// disjoint from both operands.
1121 static int tcMultiply(integerPart *, const integerPart *,
1122 const integerPart *, unsigned);
1124 /// DST = LHS * RHS, where DST has width the sum of the widths of
1125 /// the operands. No overflow occurs. DST must be disjoint from
1126 /// both operands. Returns the number of parts required to hold the
1128 static unsigned int tcFullMultiply(integerPart *, const integerPart *,
1129 const integerPart *, unsigned, unsigned);
1131 /// If RHS is zero LHS and REMAINDER are left unchanged, return one.
1132 /// Otherwise set LHS to LHS / RHS with the fractional part
1133 /// discarded, set REMAINDER to the remainder, return zero. i.e.
1135 /// OLD_LHS = RHS * LHS + REMAINDER
1137 /// SCRATCH is a bignum of the same size as the operands and result
1138 /// for use by the routine; its contents need not be initialized
1139 /// and are destroyed. LHS, REMAINDER and SCRATCH must be
1141 static int tcDivide(integerPart *lhs, const integerPart *rhs,
1142 integerPart *remainder, integerPart *scratch,
1143 unsigned int parts);
1145 /// Shift a bignum left COUNT bits. Shifted in bits are zero.
1146 /// There are no restrictions on COUNT.
1147 static void tcShiftLeft(integerPart *, unsigned int parts,
1148 unsigned int count);
1150 /// Shift a bignum right COUNT bits. Shifted in bits are zero.
1151 /// There are no restrictions on COUNT.
1152 static void tcShiftRight(integerPart *, unsigned int parts,
1153 unsigned int count);
1155 /// The obvious AND, OR and XOR and complement operations.
1156 static void tcAnd(integerPart *, const integerPart *, unsigned int);
1157 static void tcOr(integerPart *, const integerPart *, unsigned int);
1158 static void tcXor(integerPart *, const integerPart *, unsigned int);
1159 static void tcComplement(integerPart *, unsigned int);
1161 /// Comparison (unsigned) of two bignums.
1162 static int tcCompare(const integerPart *, const integerPart *,
1165 /// Increment a bignum in-place. Return the carry flag.
1166 static integerPart tcIncrement(integerPart *, unsigned int);
1168 /// Set the least significant BITS and clear the rest.
1169 static void tcSetLeastSignificantBits(integerPart *, unsigned int,
1172 /// @brief debug method
1178 inline bool operator==(uint64_t V1, const APInt& V2) {
1182 inline bool operator!=(uint64_t V1, const APInt& V2) {
1186 namespace APIntOps {
1188 /// @brief Determine the smaller of two APInts considered to be signed.
1189 inline APInt smin(const APInt &A, const APInt &B) {
1190 return A.slt(B) ? A : B;
1193 /// @brief Determine the larger of two APInts considered to be signed.
1194 inline APInt smax(const APInt &A, const APInt &B) {
1195 return A.sgt(B) ? A : B;
1198 /// @brief Determine the smaller of two APInts considered to be signed.
1199 inline APInt umin(const APInt &A, const APInt &B) {
1200 return A.ult(B) ? A : B;
1203 /// @brief Determine the larger of two APInts considered to be unsigned.
1204 inline APInt umax(const APInt &A, const APInt &B) {
1205 return A.ugt(B) ? A : B;
1208 /// @brief Check if the specified APInt has a N-bits integer value.
1209 inline bool isIntN(uint32_t N, const APInt& APIVal) {
1210 return APIVal.isIntN(N);
1213 /// @returns true if the argument APInt value is a sequence of ones
1214 /// starting at the least significant bit with the remainder zero.
1215 inline bool isMask(uint32_t numBits, const APInt& APIVal) {
1216 return APIVal.getBoolValue() && ((APIVal + APInt(numBits,1)) & APIVal) == 0;
1219 /// @returns true if the argument APInt value contains a sequence of ones
1220 /// with the remainder zero.
1221 inline bool isShiftedMask(uint32_t numBits, const APInt& APIVal) {
1222 return isMask(numBits, (APIVal - APInt(numBits,1)) | APIVal);
1225 /// @returns a byte-swapped representation of the specified APInt Value.
1226 inline APInt byteSwap(const APInt& APIVal) {
1227 return APIVal.byteSwap();
1230 /// @returns the floor log base 2 of the specified APInt value.
1231 inline uint32_t logBase2(const APInt& APIVal) {
1232 return APIVal.logBase2();
1235 /// GreatestCommonDivisor - This function returns the greatest common
1236 /// divisor of the two APInt values using Enclid's algorithm.
1237 /// @returns the greatest common divisor of Val1 and Val2
1238 /// @brief Compute GCD of two APInt values.
1239 APInt GreatestCommonDivisor(const APInt& Val1, const APInt& Val2);
1241 /// Treats the APInt as an unsigned value for conversion purposes.
1242 /// @brief Converts the given APInt to a double value.
1243 inline double RoundAPIntToDouble(const APInt& APIVal) {
1244 return APIVal.roundToDouble();
1247 /// Treats the APInt as a signed value for conversion purposes.
1248 /// @brief Converts the given APInt to a double value.
1249 inline double RoundSignedAPIntToDouble(const APInt& APIVal) {
1250 return APIVal.signedRoundToDouble();
1253 /// @brief Converts the given APInt to a float vlalue.
1254 inline float RoundAPIntToFloat(const APInt& APIVal) {
1255 return float(RoundAPIntToDouble(APIVal));
1258 /// Treast the APInt as a signed value for conversion purposes.
1259 /// @brief Converts the given APInt to a float value.
1260 inline float RoundSignedAPIntToFloat(const APInt& APIVal) {
1261 return float(APIVal.signedRoundToDouble());
1264 /// RoundDoubleToAPInt - This function convert a double value to an APInt value.
1265 /// @brief Converts the given double value into a APInt.
1266 APInt RoundDoubleToAPInt(double Double, uint32_t width);
1268 /// RoundFloatToAPInt - Converts a float value into an APInt value.
1269 /// @brief Converts a float value into a APInt.
1270 inline APInt RoundFloatToAPInt(float Float, uint32_t width) {
1271 return RoundDoubleToAPInt(double(Float), width);
1274 /// Arithmetic right-shift the APInt by shiftAmt.
1275 /// @brief Arithmetic right-shift function.
1276 inline APInt ashr(const APInt& LHS, uint32_t shiftAmt) {
1277 return LHS.ashr(shiftAmt);
1280 /// Logical right-shift the APInt by shiftAmt.
1281 /// @brief Logical right-shift function.
1282 inline APInt lshr(const APInt& LHS, uint32_t shiftAmt) {
1283 return LHS.lshr(shiftAmt);
1286 /// Left-shift the APInt by shiftAmt.
1287 /// @brief Left-shift function.
1288 inline APInt shl(const APInt& LHS, uint32_t shiftAmt) {
1289 return LHS.shl(shiftAmt);
1292 /// Signed divide APInt LHS by APInt RHS.
1293 /// @brief Signed division function for APInt.
1294 inline APInt sdiv(const APInt& LHS, const APInt& RHS) {
1295 return LHS.sdiv(RHS);
1298 /// Unsigned divide APInt LHS by APInt RHS.
1299 /// @brief Unsigned division function for APInt.
1300 inline APInt udiv(const APInt& LHS, const APInt& RHS) {
1301 return LHS.udiv(RHS);
1304 /// Signed remainder operation on APInt.
1305 /// @brief Function for signed remainder operation.
1306 inline APInt srem(const APInt& LHS, const APInt& RHS) {
1307 return LHS.srem(RHS);
1310 /// Unsigned remainder operation on APInt.
1311 /// @brief Function for unsigned remainder operation.
1312 inline APInt urem(const APInt& LHS, const APInt& RHS) {
1313 return LHS.urem(RHS);
1316 /// Performs multiplication on APInt values.
1317 /// @brief Function for multiplication operation.
1318 inline APInt mul(const APInt& LHS, const APInt& RHS) {
1322 /// Performs addition on APInt values.
1323 /// @brief Function for addition operation.
1324 inline APInt add(const APInt& LHS, const APInt& RHS) {
1328 /// Performs subtraction on APInt values.
1329 /// @brief Function for subtraction operation.
1330 inline APInt sub(const APInt& LHS, const APInt& RHS) {
1334 /// Performs bitwise AND operation on APInt LHS and
1336 /// @brief Bitwise AND function for APInt.
1337 inline APInt And(const APInt& LHS, const APInt& RHS) {
1341 /// Performs bitwise OR operation on APInt LHS and APInt RHS.
1342 /// @brief Bitwise OR function for APInt.
1343 inline APInt Or(const APInt& LHS, const APInt& RHS) {
1347 /// Performs bitwise XOR operation on APInt.
1348 /// @brief Bitwise XOR function for APInt.
1349 inline APInt Xor(const APInt& LHS, const APInt& RHS) {
1353 /// Performs a bitwise complement operation on APInt.
1354 /// @brief Bitwise complement function.
1355 inline APInt Not(const APInt& APIVal) {
1359 } // End of APIntOps namespace
1361 } // End of llvm namespace