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
13 //===----------------------------------------------------------------------===//
18 #include "llvm/Support/DataTypes.h"
24 /// Forward declaration.
27 APInt udiv(const APInt& LHS, const APInt& RHS);
28 APInt urem(const APInt& LHS, const APInt& RHS);
31 //===----------------------------------------------------------------------===//
33 //===----------------------------------------------------------------------===//
35 /// APInt - This class represents arbitrary precision constant integral values.
36 /// It is a functional replacement for common case unsigned integer type like
37 /// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width
38 /// integer sizes and large integer value types such as 3-bits, 15-bits, or more
39 /// than 64-bits of precision. APInt provides a variety of arithmetic operators
40 /// and methods to manipulate integer values of any bit-width. It supports both
41 /// the typical integer arithmetic and comparison operations as well as bitwise
44 /// The class has several invariants worth noting:
45 /// * All bit, byte, and word positions are zero-based.
46 /// * Once the bit width is set, it doesn't change except by the Truncate,
47 /// SignExtend, or ZeroExtend operations.
48 /// * All binary operators must be on APInt instances of the same bit width.
49 /// Attempting to use these operators on instances with different bit
50 /// widths will yield an assertion.
51 /// * The value is stored canonically as an unsigned value. For operations
52 /// where it makes a difference, there are both signed and unsigned variants
53 /// of the operation. For example, sdiv and udiv. However, because the bit
54 /// widths must be the same, operations such as Mul and Add produce the same
55 /// results regardless of whether the values are interpreted as signed or
57 /// * In general, the class tries to follow the style of computation that LLVM
58 /// uses in its IR. This simplifies its use for LLVM.
60 /// @brief Class for arbitrary precision integers.
62 unsigned BitWidth; ///< The number of bits in this APInt.
64 /// This union is used to store the integer value. When the
65 /// integer bit-width <= 64, it uses VAL;
66 /// otherwise it uses the pVal.
68 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
69 uint64_t *pVal; ///< Used to store the >64 bits integer value.
72 /// This enum is just used to hold a constant we needed for APInt.
74 APINT_BITS_PER_WORD = sizeof(uint64_t) * 8
77 /// Here one word's bitwidth equals to that of uint64_t.
78 /// @returns the number of words to hold the integer value of this APInt.
79 /// @brief Get the number of words.
80 inline unsigned getNumWords() const {
81 return (BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
84 /// @returns true if the number of bits <= 64, false otherwise.
85 /// @brief Determine if this APInt just has one word to store value.
86 inline bool isSingleWord() const {
87 return BitWidth <= APINT_BITS_PER_WORD;
90 /// @returns the word position for the specified bit position.
91 static inline unsigned whichWord(unsigned bitPosition) {
92 return bitPosition / APINT_BITS_PER_WORD;
95 /// @returns the byte position for the specified bit position.
96 static inline unsigned whichByte(unsigned bitPosition) {
97 return (bitPosition % APINT_BITS_PER_WORD) / 8;
100 /// @returns the bit position in a word for the specified bit position
102 static inline unsigned whichBit(unsigned bitPosition) {
103 return bitPosition % APINT_BITS_PER_WORD;
106 /// @returns a uint64_t type integer with just bit position at
107 /// "whichBit(bitPosition)" setting, others zero.
108 static inline uint64_t maskBit(unsigned bitPosition) {
109 return (static_cast<uint64_t>(1)) << whichBit(bitPosition);
112 /// This method is used internally to clear the to "N" bits that are not used
113 /// by the APInt. This is needed after a word is assigned a value to ensure
114 /// that those bits are zero'd out.
115 /// @brief Clear high order bits
116 inline void clearUnusedBits() {
118 VAL &= ~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - BitWidth);
120 pVal[getNumWords() - 1] &= ~uint64_t(0ULL) >>
121 (APINT_BITS_PER_WORD - (whichBit(BitWidth - 1) + 1));
124 /// @returns the corresponding word for the specified bit position.
125 inline uint64_t& getWord(unsigned bitPosition) {
126 return isSingleWord() ? VAL : pVal[whichWord(bitPosition)];
129 /// @returns the corresponding word for the specified bit position.
130 /// This is a constant version.
131 inline uint64_t getWord(unsigned bitPosition) const {
132 return isSingleWord() ? VAL : pVal[whichWord(bitPosition)];
135 /// @brief Converts a char array into an integer.
136 void fromString(unsigned numBits, const char *StrStart, unsigned slen,
140 /// @brief Create a new APInt of numBits bit-width, and initialized as val.
141 APInt(unsigned numBits, uint64_t val);
143 /// @brief Create a new APInt of numBits bit-width, and initialized as
145 APInt(unsigned numBits, unsigned numWords, uint64_t bigVal[]);
147 /// @brief Create a new APInt by translating the string represented
149 APInt(unsigned numBits, const std::string& Val, uint8_t radix);
151 /// @brief Create a new APInt by translating the char array represented
153 APInt(unsigned numBits, const char StrStart[], unsigned slen, uint8_t radix);
155 /// @brief Copy Constructor.
156 APInt(const APInt& API);
158 /// @brief Destructor.
161 /// @brief Copy assignment operator.
162 APInt& operator=(const APInt& RHS);
164 /// Assigns an integer value to the APInt.
165 /// @brief Assignment operator.
166 APInt& operator=(uint64_t RHS);
168 /// Increments the APInt by one.
169 /// @brief Postfix increment operator.
170 inline const APInt operator++(int) {
176 /// Increments the APInt by one.
177 /// @brief Prefix increment operator.
180 /// Decrements the APInt by one.
181 /// @brief Postfix decrement operator.
182 inline const APInt operator--(int) {
188 /// Decrements the APInt by one.
189 /// @brief Prefix decrement operator.
192 /// Performs bitwise AND operation on this APInt and the given APInt& RHS,
193 /// assigns the result to this APInt.
194 /// @brief Bitwise AND assignment operator.
195 APInt& operator&=(const APInt& RHS);
197 /// Performs bitwise OR operation on this APInt and the given APInt& RHS,
198 /// assigns the result to this APInt.
199 /// @brief Bitwise OR assignment operator.
200 APInt& operator|=(const APInt& RHS);
202 /// Performs bitwise XOR operation on this APInt and the given APInt& RHS,
203 /// assigns the result to this APInt.
204 /// @brief Bitwise XOR assignment operator.
205 APInt& operator^=(const APInt& RHS);
207 /// Performs a bitwise complement operation on this APInt.
208 /// @brief Bitwise complement operator.
209 APInt operator~() const;
211 /// Multiplies this APInt by the given APInt& RHS and
212 /// assigns the result to this APInt.
213 /// @brief Multiplication assignment operator.
214 APInt& operator*=(const APInt& RHS);
216 /// Adds this APInt by the given APInt& RHS and
217 /// assigns the result to this APInt.
218 /// @brief Addition assignment operator.
219 APInt& operator+=(const APInt& RHS);
221 /// Subtracts this APInt by the given APInt &RHS and
222 /// assigns the result to this APInt.
223 /// @brief Subtraction assignment operator.
224 APInt& operator-=(const APInt& RHS);
226 /// Performs bitwise AND operation on this APInt and
227 /// the given APInt& RHS.
228 /// @brief Bitwise AND operator.
229 APInt operator&(const APInt& RHS) const;
231 /// Performs bitwise OR operation on this APInt and the given APInt& RHS.
232 /// @brief Bitwise OR operator.
233 APInt operator|(const APInt& RHS) const;
235 /// Performs bitwise XOR operation on this APInt and the given APInt& RHS.
236 /// @brief Bitwise XOR operator.
237 APInt operator^(const APInt& RHS) const;
239 /// Performs logical negation operation on this APInt.
240 /// @brief Logical negation operator.
241 bool operator !() const;
243 /// Multiplies this APInt by the given APInt& RHS.
244 /// @brief Multiplication operator.
245 APInt operator*(const APInt& RHS) const;
247 /// Adds this APInt by the given APInt& RHS.
248 /// @brief Addition operator.
249 APInt operator+(const APInt& RHS) const;
251 /// Subtracts this APInt by the given APInt& RHS
252 /// @brief Subtraction operator.
253 APInt operator-(const APInt& RHS) const;
255 /// @brief Unary negation operator
256 inline APInt operator-() const {
257 return APInt(0, BitWidth) - (*this);
260 /// @brief Array-indexing support.
261 bool operator[](unsigned bitPosition) const;
263 /// Compare this APInt with the given APInt& RHS
264 /// for the validity of the equality relationship.
265 /// @brief Equality operator.
266 bool operator==(const APInt& RHS) const;
268 /// Compare this APInt with the given uint64_t value
269 /// for the validity of the equality relationship.
270 /// @brief Equality operator.
271 bool operator==(uint64_t Val) const;
273 /// Compare this APInt with the given APInt& RHS
274 /// for the validity of the inequality relationship.
275 /// @brief Inequality operator.
276 inline bool operator!=(const APInt& RHS) const {
277 return !((*this) == RHS);
280 /// Compare this APInt with the given uint64_t value
281 /// for the validity of the inequality relationship.
282 /// @brief Inequality operator.
283 inline bool operator!=(uint64_t Val) const {
284 return !((*this) == Val);
287 /// @brief Equality comparison
288 bool eq(const APInt &RHS) const {
289 return (*this) == RHS;
292 /// @brief Inequality comparison
293 bool ne(const APInt &RHS) const {
294 return !((*this) == RHS);
297 /// @brief Unsigned less than comparison
298 bool ult(const APInt& RHS) const;
300 /// @brief Signed less than comparison
301 bool slt(const APInt& RHS) const;
303 /// @brief Unsigned less or equal comparison
304 bool ule(const APInt& RHS) const {
305 return ult(RHS) || eq(RHS);
308 /// @brief Signed less or equal comparison
309 bool sle(const APInt& RHS) const {
310 return slt(RHS) || eq(RHS);
313 /// @brief Unsigned greather than comparison
314 bool ugt(const APInt& RHS) const {
315 return !ult(RHS) && !eq(RHS);
318 /// @brief Signed greather than comparison
319 bool sgt(const APInt& RHS) const {
320 return !slt(RHS) && !eq(RHS);
323 /// @brief Unsigned greater or equal comparison
324 bool uge(const APInt& RHS) const {
328 /// @brief Signed greather or equal comparison
329 bool sge(const APInt& RHS) const {
333 /// Arithmetic right-shift this APInt by shiftAmt.
334 /// @brief Arithmetic right-shift function.
335 APInt ashr(unsigned shiftAmt) const;
337 /// Logical right-shift this APInt by shiftAmt.
338 /// @brief Logical right-shift function.
339 APInt lshr(unsigned shiftAmt) const;
341 /// Left-shift this APInt by shiftAmt.
342 /// @brief Left-shift function.
343 APInt shl(unsigned shiftAmt) const;
345 /// Signed divide this APInt by APInt RHS.
346 /// @brief Signed division function for APInt.
347 inline APInt sdiv(const APInt& RHS) const {
348 bool isNegativeLHS = (*this)[BitWidth - 1];
349 bool isNegativeRHS = RHS[RHS.BitWidth - 1];
350 APInt API = APIntOps::udiv(
351 isNegativeLHS ? -(*this) : (*this), isNegativeRHS ? -RHS : RHS);
352 return isNegativeLHS != isNegativeRHS ? -API : API;;
355 /// Unsigned divide this APInt by APInt RHS.
356 /// @brief Unsigned division function for APInt.
357 APInt udiv(const APInt& RHS) const;
359 /// Signed remainder operation on APInt.
360 /// @brief Function for signed remainder operation.
361 inline APInt srem(const APInt& RHS) const {
362 bool isNegativeLHS = (*this)[BitWidth - 1];
363 bool isNegativeRHS = RHS[RHS.BitWidth - 1];
364 APInt API = APIntOps::urem(
365 isNegativeLHS ? -(*this) : (*this), isNegativeRHS ? -RHS : RHS);
366 return isNegativeLHS ? -API : API;
369 /// Unsigned remainder operation on APInt.
370 /// @brief Function for unsigned remainder operation.
371 APInt urem(const APInt& RHS) const;
373 /// Truncate the APInt to a specified width. It is an error to specify a width
374 /// that is greater than or equal to the current width.
375 /// @brief Truncate to new width.
376 void trunc(unsigned width);
378 /// This operation sign extends the APInt to a new width. If the high order
379 /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
380 /// It is an error to specify a width that is less than or equal to the
382 /// @brief Sign extend to a new width.
383 void sext(unsigned width);
385 /// This operation zero extends the APInt to a new width. Thie high order bits
386 /// are filled with 0 bits. It is an error to specify a width that is less
387 /// than or equal to the current width.
388 /// @brief Zero extend to a new width.
389 void zext(unsigned width);
391 /// @brief Set every bit to 1.
394 /// Set the given bit to 1 whose position is given as "bitPosition".
395 /// @brief Set a given bit to 1.
396 APInt& set(unsigned bitPosition);
398 /// @brief Set every bit to 0.
401 /// Set the given bit to 0 whose position is given as "bitPosition".
402 /// @brief Set a given bit to 0.
403 APInt& clear(unsigned bitPosition);
405 /// @brief Toggle every bit to its opposite value.
408 /// Toggle a given bit to its opposite value whose position is given
409 /// as "bitPosition".
410 /// @brief Toggles a given bit to its opposite value.
411 APInt& flip(unsigned bitPosition);
413 /// This function returns the number of active bits which is defined as the
414 /// bit width minus the number of leading zeros. This is used in several
415 /// computations to see how "wide" the value is.
416 /// @brief Compute the number of active bits in the value
417 inline unsigned getActiveBits() const {
418 return getNumWords() * APINT_BITS_PER_WORD - countLeadingZeros();
421 /// @returns a uint64_t value from this APInt. If this APInt contains a single
422 /// word, just returns VAL, otherwise pVal[0].
423 inline uint64_t getValue(bool isSigned = false) const {
425 return isSigned ? int64_t(VAL << (64 - BitWidth)) >>
426 (64 - BitWidth) : VAL;
427 unsigned n = getActiveBits();
430 assert(0 && "This APInt's bitwidth > 64");
433 /// @returns the largest value for an APInt of the specified bit-width and
434 /// if isSign == true, it should be largest signed value, otherwise largest
436 /// @brief Gets max value of the APInt with bitwidth <= 64.
437 static APInt getMaxValue(unsigned numBits, bool isSign);
439 /// @returns the smallest value for an APInt of the given bit-width and
440 /// if isSign == true, it should be smallest signed value, otherwise zero.
441 /// @brief Gets min value of the APInt with bitwidth <= 64.
442 static APInt getMinValue(unsigned numBits, bool isSign);
444 /// @returns the all-ones value for an APInt of the specified bit-width.
445 /// @brief Get the all-ones value.
446 static APInt getAllOnesValue(unsigned numBits);
448 /// @returns the '0' value for an APInt of the specified bit-width.
449 /// @brief Get the '0' value.
450 static APInt getNullValue(unsigned numBits);
452 /// This converts the APInt to a boolean valy as a test against zero.
453 /// @brief Boolean conversion function.
454 inline bool getBoolValue() const {
455 return countLeadingZeros() != BitWidth;
458 /// @returns a character interpretation of the APInt.
459 std::string toString(uint8_t radix = 10) const;
461 /// Get an APInt with the same BitWidth as this APInt, just zero mask
462 /// the low bits and right shift to the least significant bit.
463 /// @returns the high "numBits" bits of this APInt.
464 APInt getHiBits(unsigned numBits) const;
466 /// Get an APInt with the same BitWidth as this APInt, just zero mask
468 /// @returns the low "numBits" bits of this APInt.
469 APInt getLoBits(unsigned numBits) const;
471 /// @returns true if the argument APInt value is a power of two > 0.
472 inline bool isPowerOf2() const;
474 /// @returns the number of zeros from the most significant bit to the first
476 unsigned countLeadingZeros() const;
478 /// @returns the number of zeros from the least significant bit to the first
480 unsigned countTrailingZeros() const;
482 /// @returns the number of set bits.
483 unsigned countPopulation() const;
485 /// @returns the total number of bits.
486 inline unsigned getNumBits() const {
490 /// @brief Check if this APInt has a N-bits integer value.
491 inline bool isIntN(unsigned N) const {
492 assert(N && "N == 0 ???");
493 if (isSingleWord()) {
494 return VAL == (VAL & (~0ULL >> (64 - N)));
496 APInt Tmp(N, getNumWords(), pVal);
497 return Tmp == (*this);
501 /// @returns a byte-swapped representation of this APInt Value.
502 APInt byteSwap() const;
504 /// @returns the floor log base 2 of this APInt.
505 inline unsigned logBase2() const {
506 return getNumWords() * APINT_BITS_PER_WORD - 1 - countLeadingZeros();
509 /// @brief Converts this APInt to a double value.
510 double roundToDouble(bool isSigned = false) const;
516 /// @brief Check if the specified APInt has a N-bits integer value.
517 inline bool isIntN(unsigned N, const APInt& APIVal) {
518 return APIVal.isIntN(N);
521 /// @returns true if the argument APInt value is a sequence of ones
522 /// starting at the least significant bit with the remainder zero.
523 inline const bool isMask(unsigned numBits, const APInt& APIVal) {
524 return APIVal.getBoolValue() && ((APIVal + APInt(numBits,1)) & APIVal) == 0;
527 /// @returns true if the argument APInt value contains a sequence of ones
528 /// with the remainder zero.
529 inline const bool isShiftedMask(unsigned numBits, const APInt& APIVal) {
530 return isMask(numBits, (APIVal - APInt(numBits,1)) | APIVal);
533 /// @returns a byte-swapped representation of the specified APInt Value.
534 inline APInt byteSwap(const APInt& APIVal) {
535 return APIVal.byteSwap();
538 /// @returns the floor log base 2 of the specified APInt value.
539 inline unsigned logBase2(const APInt& APIVal) {
540 return APIVal.logBase2();
543 /// @returns the greatest common divisor of the two values
544 /// using Euclid's algorithm.
545 APInt GreatestCommonDivisor(const APInt& API1, const APInt& API2);
547 /// @brief Converts the given APInt to a double value.
548 inline double RoundAPIntToDouble(const APInt& APIVal, bool isSigned = false) {
549 return APIVal.roundToDouble(isSigned);
552 /// @brief Converts the given APInt to a float vlalue.
553 inline float RoundAPIntToFloat(const APInt& APIVal) {
554 return float(RoundAPIntToDouble(APIVal));
557 /// @brief Converts the given double value into a APInt.
558 APInt RoundDoubleToAPInt(double Double);
560 /// @brief Converts the given float value into a APInt.
561 inline APInt RoundFloatToAPInt(float Float) {
562 return RoundDoubleToAPInt(double(Float));
565 /// Arithmetic right-shift the APInt by shiftAmt.
566 /// @brief Arithmetic right-shift function.
567 inline APInt ashr(const APInt& LHS, unsigned shiftAmt) {
568 return LHS.ashr(shiftAmt);
571 /// Logical right-shift the APInt by shiftAmt.
572 /// @brief Logical right-shift function.
573 inline APInt lshr(const APInt& LHS, unsigned shiftAmt) {
574 return LHS.lshr(shiftAmt);
577 /// Left-shift the APInt by shiftAmt.
578 /// @brief Left-shift function.
579 inline APInt shl(const APInt& LHS, unsigned shiftAmt) {
580 return LHS.shl(shiftAmt);
583 /// Signed divide APInt LHS by APInt RHS.
584 /// @brief Signed division function for APInt.
585 inline APInt sdiv(const APInt& LHS, const APInt& RHS) {
586 return LHS.sdiv(RHS);
589 /// Unsigned divide APInt LHS by APInt RHS.
590 /// @brief Unsigned division function for APInt.
591 inline APInt udiv(const APInt& LHS, const APInt& RHS) {
592 return LHS.udiv(RHS);
595 /// Signed remainder operation on APInt.
596 /// @brief Function for signed remainder operation.
597 inline APInt srem(const APInt& LHS, const APInt& RHS) {
598 return LHS.srem(RHS);
601 /// Unsigned remainder operation on APInt.
602 /// @brief Function for unsigned remainder operation.
603 inline APInt urem(const APInt& LHS, const APInt& RHS) {
604 return LHS.urem(RHS);
607 /// Performs multiplication on APInt values.
608 /// @brief Function for multiplication operation.
609 inline APInt mul(const APInt& LHS, const APInt& RHS) {
613 /// Performs addition on APInt values.
614 /// @brief Function for addition operation.
615 inline APInt add(const APInt& LHS, const APInt& RHS) {
619 /// Performs subtraction on APInt values.
620 /// @brief Function for subtraction operation.
621 inline APInt sub(const APInt& LHS, const APInt& RHS) {
625 /// Performs bitwise AND operation on APInt LHS and
627 /// @brief Bitwise AND function for APInt.
628 inline APInt And(const APInt& LHS, const APInt& RHS) {
632 /// Performs bitwise OR operation on APInt LHS and APInt RHS.
633 /// @brief Bitwise OR function for APInt.
634 inline APInt Or(const APInt& LHS, const APInt& RHS) {
638 /// Performs bitwise XOR operation on APInt.
639 /// @brief Bitwise XOR function for APInt.
640 inline APInt Xor(const APInt& LHS, const APInt& RHS) {
644 /// Performs a bitwise complement operation on APInt.
645 /// @brief Bitwise complement function.
646 inline APInt Not(const APInt& APIVal) {
650 } // End of APIntOps namespace
652 } // End of llvm namespace