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.
63 uint32_t BitWidth; ///< The number of bits in this APInt.
65 /// This union is used to store the integer value. When the
66 /// integer bit-width <= 64, it uses VAL;
67 /// otherwise it uses the pVal.
69 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
70 uint64_t *pVal; ///< Used to store the >64 bits integer value.
73 /// This enum is just used to hold a constant we needed for APInt.
75 APINT_BITS_PER_WORD = sizeof(uint64_t) * 8
78 /// Here one word's bitwidth equals to that of uint64_t.
79 /// @returns the number of words to hold the integer value of this APInt.
80 /// @brief Get the number of words.
81 inline uint32_t getNumWords() const {
82 return (BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
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 static inline uint32_t whichWord(uint32_t bitPosition) {
93 return bitPosition / APINT_BITS_PER_WORD;
96 /// @returns the bit position in a word for the specified bit position
98 static inline uint32_t whichBit(uint32_t bitPosition) {
99 return bitPosition % APINT_BITS_PER_WORD;
102 /// @returns a uint64_t type integer with just bit position at
103 /// "whichBit(bitPosition)" setting, others zero.
104 static inline uint64_t maskBit(uint32_t bitPosition) {
105 return (static_cast<uint64_t>(1)) << whichBit(bitPosition);
108 /// This method is used internally to clear the to "N" bits that are not used
109 /// by the APInt. This is needed after a word is assigned a value to ensure
110 /// that those bits are zero'd out.
111 /// @brief Clear high order bits
112 inline void clearUnusedBits() {
114 VAL &= ~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - BitWidth);
116 pVal[getNumWords() - 1] &= ~uint64_t(0ULL) >>
117 (APINT_BITS_PER_WORD - (whichBit(BitWidth - 1) + 1));
120 /// @returns the corresponding word for the specified bit position.
121 /// This is a constant version.
122 inline uint64_t getWord(uint32_t bitPosition) const {
123 return isSingleWord() ? VAL : pVal[whichWord(bitPosition)];
126 /// @brief Converts a char array into an integer.
127 void fromString(uint32_t numBits, const char *StrStart, uint32_t slen,
131 /// @brief Create a new APInt of numBits bit-width, and initialized as val.
132 APInt(uint32_t numBits, uint64_t val);
134 /// @brief Create a new APInt of numBits bit-width, and initialized as
136 APInt(uint32_t numBits, uint32_t numWords, uint64_t bigVal[]);
138 /// @brief Create a new APInt by translating the string represented
140 APInt(uint32_t numBits, const std::string& Val, uint8_t radix);
142 /// @brief Create a new APInt by translating the char array represented
144 APInt(uint32_t numBits, const char StrStart[], uint32_t slen, uint8_t radix);
146 /// @brief Copy Constructor.
147 APInt(const APInt& API);
149 /// @brief Destructor.
152 /// @brief Copy assignment operator.
153 APInt& operator=(const APInt& RHS);
155 /// Assigns an integer value to the APInt.
156 /// @brief Assignment operator.
157 APInt& operator=(uint64_t RHS);
159 /// Increments the APInt by one.
160 /// @brief Postfix increment operator.
161 inline const APInt operator++(int) {
167 /// Increments the APInt by one.
168 /// @brief Prefix increment operator.
171 /// Decrements the APInt by one.
172 /// @brief Postfix decrement operator.
173 inline const APInt operator--(int) {
179 /// Decrements the APInt by one.
180 /// @brief Prefix decrement operator.
183 /// Performs bitwise AND operation on this APInt and the given APInt& RHS,
184 /// assigns the result to this APInt.
185 /// @brief Bitwise AND assignment operator.
186 APInt& operator&=(const APInt& RHS);
188 /// Performs bitwise OR operation on this APInt and the given APInt& RHS,
189 /// assigns the result to this APInt.
190 /// @brief Bitwise OR assignment operator.
191 APInt& operator|=(const APInt& RHS);
193 /// Performs bitwise XOR operation on this APInt and the given APInt& RHS,
194 /// assigns the result to this APInt.
195 /// @brief Bitwise XOR assignment operator.
196 APInt& operator^=(const APInt& RHS);
198 /// Performs a bitwise complement operation on this APInt.
199 /// @brief Bitwise complement operator.
200 APInt operator~() const;
202 /// Multiplies this APInt by the given APInt& RHS and
203 /// assigns the result to this APInt.
204 /// @brief Multiplication assignment operator.
205 APInt& operator*=(const APInt& RHS);
207 /// Adds this APInt by the given APInt& RHS and
208 /// assigns the result to this APInt.
209 /// @brief Addition assignment operator.
210 APInt& operator+=(const APInt& RHS);
212 /// Subtracts this APInt by the given APInt &RHS and
213 /// assigns the result to this APInt.
214 /// @brief Subtraction assignment operator.
215 APInt& operator-=(const APInt& RHS);
217 /// Performs bitwise AND operation on this APInt and
218 /// the given APInt& RHS.
219 /// @brief Bitwise AND operator.
220 APInt operator&(const APInt& RHS) const;
222 /// Performs bitwise OR operation on this APInt and the given APInt& RHS.
223 /// @brief Bitwise OR operator.
224 APInt operator|(const APInt& RHS) const;
226 /// Performs bitwise XOR operation on this APInt and the given APInt& RHS.
227 /// @brief Bitwise XOR operator.
228 APInt operator^(const APInt& RHS) const;
230 /// Performs logical negation operation on this APInt.
231 /// @brief Logical negation operator.
232 bool operator !() const;
234 /// Multiplies this APInt by the given APInt& RHS.
235 /// @brief Multiplication operator.
236 APInt operator*(const APInt& RHS) const;
238 /// Adds this APInt by the given APInt& RHS.
239 /// @brief Addition operator.
240 APInt operator+(const APInt& RHS) const;
242 /// Subtracts this APInt by the given APInt& RHS
243 /// @brief Subtraction operator.
244 APInt operator-(const APInt& RHS) const;
246 /// @brief Unary negation operator
247 inline APInt operator-() const {
248 return APInt(BitWidth, 0) - (*this);
251 /// @brief Array-indexing support.
252 bool operator[](uint32_t bitPosition) const;
254 /// Compare this APInt with the given APInt& RHS
255 /// for the validity of the equality relationship.
256 /// @brief Equality operator.
257 bool operator==(const APInt& RHS) const;
259 /// Compare this APInt with the given uint64_t value
260 /// for the validity of the equality relationship.
261 /// @brief Equality operator.
262 bool operator==(uint64_t Val) const;
264 /// Compare this APInt with the given APInt& RHS
265 /// for the validity of the inequality relationship.
266 /// @brief Inequality operator.
267 inline bool operator!=(const APInt& RHS) const {
268 return !((*this) == RHS);
271 /// Compare this APInt with the given uint64_t value
272 /// for the validity of the inequality relationship.
273 /// @brief Inequality operator.
274 inline bool operator!=(uint64_t Val) const {
275 return !((*this) == Val);
278 /// @brief Equality comparison
279 bool eq(const APInt &RHS) const {
280 return (*this) == RHS;
283 /// @brief Inequality comparison
284 bool ne(const APInt &RHS) const {
285 return !((*this) == RHS);
288 /// @brief Unsigned less than comparison
289 bool ult(const APInt& RHS) const;
291 /// @brief Signed less than comparison
292 bool slt(const APInt& RHS) const;
294 /// @brief Unsigned less or equal comparison
295 bool ule(const APInt& RHS) const {
296 return ult(RHS) || eq(RHS);
299 /// @brief Signed less or equal comparison
300 bool sle(const APInt& RHS) const {
301 return slt(RHS) || eq(RHS);
304 /// @brief Unsigned greather than comparison
305 bool ugt(const APInt& RHS) const {
306 return !ult(RHS) && !eq(RHS);
309 /// @brief Signed greather than comparison
310 bool sgt(const APInt& RHS) const {
311 return !slt(RHS) && !eq(RHS);
314 /// @brief Unsigned greater or equal comparison
315 bool uge(const APInt& RHS) const {
319 /// @brief Signed greather or equal comparison
320 bool sge(const APInt& RHS) const {
324 /// Arithmetic right-shift this APInt by shiftAmt.
325 /// @brief Arithmetic right-shift function.
326 APInt ashr(uint32_t shiftAmt) const;
328 /// Logical right-shift this APInt by shiftAmt.
329 /// @brief Logical right-shift function.
330 APInt lshr(uint32_t shiftAmt) const;
332 /// Left-shift this APInt by shiftAmt.
333 /// @brief Left-shift function.
334 APInt shl(uint32_t shiftAmt) const;
336 /// Signed divide this APInt by APInt RHS.
337 /// @brief Signed division function for APInt.
338 inline APInt sdiv(const APInt& RHS) const {
339 bool isNegativeLHS = (*this)[BitWidth - 1];
340 bool isNegativeRHS = RHS[RHS.BitWidth - 1];
341 APInt Result = APIntOps::udiv(
342 isNegativeLHS ? -(*this) : (*this), isNegativeRHS ? -RHS : RHS);
343 return isNegativeLHS != isNegativeRHS ? -Result : Result;
346 /// Unsigned divide this APInt by APInt RHS.
347 /// @brief Unsigned division function for APInt.
348 APInt udiv(const APInt& RHS) const;
350 /// Signed remainder operation on APInt.
351 /// @brief Function for signed remainder operation.
352 inline APInt srem(const APInt& RHS) const {
353 bool isNegativeLHS = (*this)[BitWidth - 1];
354 bool isNegativeRHS = RHS[RHS.BitWidth - 1];
355 APInt Result = APIntOps::urem(
356 isNegativeLHS ? -(*this) : (*this), isNegativeRHS ? -RHS : RHS);
357 return isNegativeLHS ? -Result : Result;
360 /// Unsigned remainder operation on APInt.
361 /// @brief Function for unsigned remainder operation.
362 APInt urem(const APInt& RHS) const;
364 /// Truncate the APInt to a specified width. It is an error to specify a width
365 /// that is greater than or equal to the current width.
366 /// @brief Truncate to new width.
367 void trunc(uint32_t width);
369 /// This operation sign extends the APInt to a new width. If the high order
370 /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
371 /// It is an error to specify a width that is less than or equal to the
373 /// @brief Sign extend to a new width.
374 void sext(uint32_t width);
376 /// This operation zero extends the APInt to a new width. Thie high order bits
377 /// are filled with 0 bits. It is an error to specify a width that is less
378 /// than or equal to the current width.
379 /// @brief Zero extend to a new width.
380 void zext(uint32_t width);
382 /// @brief Set every bit to 1.
385 /// Set the given bit to 1 whose position is given as "bitPosition".
386 /// @brief Set a given bit to 1.
387 APInt& set(uint32_t bitPosition);
389 /// @brief Set every bit to 0.
392 /// Set the given bit to 0 whose position is given as "bitPosition".
393 /// @brief Set a given bit to 0.
394 APInt& clear(uint32_t bitPosition);
396 /// @brief Toggle every bit to its opposite value.
399 /// Toggle a given bit to its opposite value whose position is given
400 /// as "bitPosition".
401 /// @brief Toggles a given bit to its opposite value.
402 APInt& flip(uint32_t bitPosition);
404 /// This function returns the number of active bits which is defined as the
405 /// bit width minus the number of leading zeros. This is used in several
406 /// computations to see how "wide" the value is.
407 /// @brief Compute the number of active bits in the value
408 inline uint32_t getActiveBits() const {
409 return getNumWords() * APINT_BITS_PER_WORD - countLeadingZeros();
412 /// @returns a uint64_t value from this APInt. If this APInt contains a single
413 /// word, just returns VAL, otherwise pVal[0].
414 inline uint64_t getValue(bool isSigned = false) const {
416 return isSigned ? int64_t(VAL << (64 - BitWidth)) >>
417 (64 - BitWidth) : VAL;
418 uint32_t n = getActiveBits();
421 assert(0 && "This APInt's bitwidth > 64");
424 /// @returns the largest value for an APInt of the specified bit-width and
425 /// if isSign == true, it should be largest signed value, otherwise largest
427 /// @brief Gets max value of the APInt with bitwidth <= 64.
428 static APInt getMaxValue(uint32_t numBits, bool isSign);
430 /// @returns the smallest value for an APInt of the given bit-width and
431 /// if isSign == true, it should be smallest signed value, otherwise zero.
432 /// @brief Gets min value of the APInt with bitwidth <= 64.
433 static APInt getMinValue(uint32_t numBits, bool isSign);
435 /// @returns the all-ones value for an APInt of the specified bit-width.
436 /// @brief Get the all-ones value.
437 static APInt getAllOnesValue(uint32_t numBits);
439 /// @returns the '0' value for an APInt of the specified bit-width.
440 /// @brief Get the '0' value.
441 static APInt getNullValue(uint32_t numBits);
443 /// This converts the APInt to a boolean valy as a test against zero.
444 /// @brief Boolean conversion function.
445 inline bool getBoolValue() const {
446 return countLeadingZeros() != BitWidth;
449 /// @returns a character interpretation of the APInt.
450 std::string toString(uint8_t radix = 10, bool wantSigned = true) const;
452 /// Get an APInt with the same BitWidth as this APInt, just zero mask
453 /// the low bits and right shift to the least significant bit.
454 /// @returns the high "numBits" bits of this APInt.
455 APInt getHiBits(uint32_t numBits) const;
457 /// Get an APInt with the same BitWidth as this APInt, just zero mask
459 /// @returns the low "numBits" bits of this APInt.
460 APInt getLoBits(uint32_t numBits) const;
462 /// @returns true if the argument APInt value is a power of two > 0.
463 bool isPowerOf2() const;
465 /// @returns the number of zeros from the most significant bit to the first
467 uint32_t countLeadingZeros() const;
469 /// @returns the number of zeros from the least significant bit to the first
471 uint32_t countTrailingZeros() const;
473 /// @returns the number of set bits.
474 uint32_t countPopulation() const;
476 /// @returns the total number of bits.
477 inline uint32_t getBitWidth() const {
481 /// @brief Check if this APInt has a N-bits integer value.
482 inline bool isIntN(uint32_t N) const {
483 assert(N && "N == 0 ???");
484 if (isSingleWord()) {
485 return VAL == (VAL & (~0ULL >> (64 - N)));
487 APInt Tmp(N, getNumWords(), pVal);
488 return Tmp == (*this);
492 /// @returns a byte-swapped representation of this APInt Value.
493 APInt byteSwap() const;
495 /// @returns the floor log base 2 of this APInt.
496 inline uint32_t logBase2() const {
497 return getNumWords() * APINT_BITS_PER_WORD - 1 - countLeadingZeros();
500 /// @brief Converts this APInt to a double value.
501 double roundToDouble(bool isSigned = false) const;
507 /// @brief Check if the specified APInt has a N-bits integer value.
508 inline bool isIntN(uint32_t N, const APInt& APIVal) {
509 return APIVal.isIntN(N);
512 /// @returns true if the argument APInt value is a sequence of ones
513 /// starting at the least significant bit with the remainder zero.
514 inline const bool isMask(uint32_t numBits, const APInt& APIVal) {
515 return APIVal.getBoolValue() && ((APIVal + APInt(numBits,1)) & APIVal) == 0;
518 /// @returns true if the argument APInt value contains a sequence of ones
519 /// with the remainder zero.
520 inline const bool isShiftedMask(uint32_t numBits, const APInt& APIVal) {
521 return isMask(numBits, (APIVal - APInt(numBits,1)) | APIVal);
524 /// @returns a byte-swapped representation of the specified APInt Value.
525 inline APInt byteSwap(const APInt& APIVal) {
526 return APIVal.byteSwap();
529 /// @returns the floor log base 2 of the specified APInt value.
530 inline uint32_t logBase2(const APInt& APIVal) {
531 return APIVal.logBase2();
534 /// @returns the greatest common divisor of the two values
535 /// using Euclid's algorithm.
536 APInt GreatestCommonDivisor(const APInt& API1, const APInt& API2);
538 /// @brief Converts the given APInt to a double value.
539 inline double RoundAPIntToDouble(const APInt& APIVal, bool isSigned = false) {
540 return APIVal.roundToDouble(isSigned);
543 /// @brief Converts the given APInt to a float vlalue.
544 inline float RoundAPIntToFloat(const APInt& APIVal) {
545 return float(RoundAPIntToDouble(APIVal));
548 /// @brief Converts the given double value into a APInt.
549 APInt RoundDoubleToAPInt(double Double);
551 /// @brief Converts the given float value into a APInt.
552 inline APInt RoundFloatToAPInt(float Float) {
553 return RoundDoubleToAPInt(double(Float));
556 /// Arithmetic right-shift the APInt by shiftAmt.
557 /// @brief Arithmetic right-shift function.
558 inline APInt ashr(const APInt& LHS, uint32_t shiftAmt) {
559 return LHS.ashr(shiftAmt);
562 /// Logical right-shift the APInt by shiftAmt.
563 /// @brief Logical right-shift function.
564 inline APInt lshr(const APInt& LHS, uint32_t shiftAmt) {
565 return LHS.lshr(shiftAmt);
568 /// Left-shift the APInt by shiftAmt.
569 /// @brief Left-shift function.
570 inline APInt shl(const APInt& LHS, uint32_t shiftAmt) {
571 return LHS.shl(shiftAmt);
574 /// Signed divide APInt LHS by APInt RHS.
575 /// @brief Signed division function for APInt.
576 inline APInt sdiv(const APInt& LHS, const APInt& RHS) {
577 return LHS.sdiv(RHS);
580 /// Unsigned divide APInt LHS by APInt RHS.
581 /// @brief Unsigned division function for APInt.
582 inline APInt udiv(const APInt& LHS, const APInt& RHS) {
583 return LHS.udiv(RHS);
586 /// Signed remainder operation on APInt.
587 /// @brief Function for signed remainder operation.
588 inline APInt srem(const APInt& LHS, const APInt& RHS) {
589 return LHS.srem(RHS);
592 /// Unsigned remainder operation on APInt.
593 /// @brief Function for unsigned remainder operation.
594 inline APInt urem(const APInt& LHS, const APInt& RHS) {
595 return LHS.urem(RHS);
598 /// Performs multiplication on APInt values.
599 /// @brief Function for multiplication operation.
600 inline APInt mul(const APInt& LHS, const APInt& RHS) {
604 /// Performs addition on APInt values.
605 /// @brief Function for addition operation.
606 inline APInt add(const APInt& LHS, const APInt& RHS) {
610 /// Performs subtraction on APInt values.
611 /// @brief Function for subtraction operation.
612 inline APInt sub(const APInt& LHS, const APInt& RHS) {
616 /// Performs bitwise AND operation on APInt LHS and
618 /// @brief Bitwise AND function for APInt.
619 inline APInt And(const APInt& LHS, const APInt& RHS) {
623 /// Performs bitwise OR operation on APInt LHS and APInt RHS.
624 /// @brief Bitwise OR function for APInt.
625 inline APInt Or(const APInt& LHS, const APInt& RHS) {
629 /// Performs bitwise XOR operation on APInt.
630 /// @brief Bitwise XOR function for APInt.
631 inline APInt Xor(const APInt& LHS, const APInt& RHS) {
635 /// Performs a bitwise complement operation on APInt.
636 /// @brief Bitwise complement function.
637 inline APInt Not(const APInt& APIVal) {
641 } // End of APIntOps namespace
643 } // End of llvm namespace