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,
76 APINT_WORD_SIZE = sizeof(uint64_t)
79 /// Here one word's bitwidth equals to that of uint64_t.
80 /// @returns the number of words to hold the integer value of this APInt.
81 /// @brief Get the number of words.
82 inline uint32_t getNumWords() const {
83 return (BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
86 /// @returns true if the number of bits <= 64, false otherwise.
87 /// @brief Determine if this APInt just has one word to store value.
88 inline bool isSingleWord() const {
89 return BitWidth <= APINT_BITS_PER_WORD;
92 /// @returns the word position for the specified bit position.
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 static inline uint32_t whichBit(uint32_t bitPosition) {
100 return bitPosition % APINT_BITS_PER_WORD;
103 /// @returns a uint64_t type integer with just bit position at
104 /// "whichBit(bitPosition)" setting, others zero.
105 static inline uint64_t maskBit(uint32_t bitPosition) {
106 return (static_cast<uint64_t>(1)) << whichBit(bitPosition);
109 /// This method is used internally to clear the to "N" bits that are not used
110 /// by the APInt. This is needed after a word is assigned a value to ensure
111 /// that those bits are zero'd out.
112 /// @brief Clear high order bits
113 inline void clearUnusedBits() {
115 VAL &= ~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - BitWidth);
117 pVal[getNumWords() - 1] &= ~uint64_t(0ULL) >>
118 (APINT_BITS_PER_WORD - (whichBit(BitWidth - 1) + 1));
121 /// @returns the corresponding word for the specified bit position.
122 /// This is a constant version.
123 inline uint64_t getWord(uint32_t bitPosition) const {
124 return isSingleWord() ? VAL : pVal[whichWord(bitPosition)];
127 /// @brief Converts a char array into an integer.
128 void fromString(uint32_t numBits, const char *StrStart, uint32_t slen,
132 /// @brief debug method
137 /// @brief An internal division function for dividing APInts.
138 static void divide(const APInt LHS, uint32_t lhsWords,
139 const APInt &RHS, uint32_t rhsWords,
140 APInt *Quotient, APInt *Remainder);
142 /// @brief Create a new APInt of numBits bit-width, and initialized as val.
143 APInt(uint32_t numBits, uint64_t val);
145 /// @brief Create a new APInt of numBits bit-width, and initialized as
147 APInt(uint32_t numBits, uint32_t numWords, uint64_t bigVal[]);
149 /// @brief Create a new APInt by translating the string represented
151 APInt(uint32_t numBits, const std::string& Val, uint8_t radix);
153 /// @brief Create a new APInt by translating the char array represented
155 APInt(uint32_t numBits, const char StrStart[], uint32_t slen, uint8_t radix);
157 /// @brief Copy Constructor.
158 APInt(const APInt& API);
160 /// @brief Destructor.
163 /// @brief Copy assignment operator.
164 APInt& operator=(const APInt& RHS);
166 /// Assigns an integer value to the APInt.
167 /// @brief Assignment operator.
168 APInt& operator=(uint64_t RHS);
170 /// Increments the APInt by one.
171 /// @brief Postfix increment operator.
172 inline const APInt operator++(int) {
178 /// Increments the APInt by one.
179 /// @brief Prefix increment operator.
182 /// Decrements the APInt by one.
183 /// @brief Postfix decrement operator.
184 inline const APInt operator--(int) {
190 /// Decrements the APInt by one.
191 /// @brief Prefix decrement operator.
194 /// Performs bitwise AND operation on this APInt and the given APInt& RHS,
195 /// assigns the result to this APInt.
196 /// @brief Bitwise AND assignment operator.
197 APInt& operator&=(const APInt& RHS);
199 /// Performs bitwise OR operation on this APInt and the given APInt& RHS,
200 /// assigns the result to this APInt.
201 /// @brief Bitwise OR assignment operator.
202 APInt& operator|=(const APInt& RHS);
204 /// Performs bitwise XOR operation on this APInt and the given APInt& RHS,
205 /// assigns the result to this APInt.
206 /// @brief Bitwise XOR assignment operator.
207 APInt& operator^=(const APInt& RHS);
209 /// Performs a bitwise complement operation on this APInt.
210 /// @brief Bitwise complement operator.
211 APInt operator~() const;
213 /// Multiplies this APInt by the given APInt& RHS and
214 /// assigns the result to this APInt.
215 /// @brief Multiplication assignment operator.
216 APInt& operator*=(const APInt& RHS);
218 /// Adds this APInt by the given APInt& RHS and
219 /// assigns the result to this APInt.
220 /// @brief Addition assignment operator.
221 APInt& operator+=(const APInt& RHS);
223 /// Subtracts this APInt by the given APInt &RHS and
224 /// assigns the result to this APInt.
225 /// @brief Subtraction assignment operator.
226 APInt& operator-=(const APInt& RHS);
228 /// Performs bitwise AND operation on this APInt and
229 /// the given APInt& RHS.
230 /// @brief Bitwise AND operator.
231 APInt operator&(const APInt& RHS) const;
233 /// Performs bitwise OR operation on this APInt and the given APInt& RHS.
234 /// @brief Bitwise OR operator.
235 APInt operator|(const APInt& RHS) const;
237 /// Performs bitwise XOR operation on this APInt and the given APInt& RHS.
238 /// @brief Bitwise XOR operator.
239 APInt operator^(const APInt& RHS) const;
241 /// Performs logical negation operation on this APInt.
242 /// @brief Logical negation operator.
243 bool operator !() const;
245 /// Multiplies this APInt by the given APInt& RHS.
246 /// @brief Multiplication operator.
247 APInt operator*(const APInt& RHS) const;
249 /// Adds this APInt by the given APInt& RHS.
250 /// @brief Addition operator.
251 APInt operator+(const APInt& RHS) const;
253 /// Subtracts this APInt by the given APInt& RHS
254 /// @brief Subtraction operator.
255 APInt operator-(const APInt& RHS) const;
257 /// @brief Unary negation operator
258 inline APInt operator-() const {
259 return APInt(BitWidth, 0) - (*this);
262 /// @brief Array-indexing support.
263 bool operator[](uint32_t bitPosition) const;
265 /// Compare this APInt with the given APInt& RHS
266 /// for the validity of the equality relationship.
267 /// @brief Equality operator.
268 bool operator==(const APInt& RHS) const;
270 /// Compare this APInt with the given uint64_t value
271 /// for the validity of the equality relationship.
272 /// @brief Equality operator.
273 bool operator==(uint64_t Val) const;
275 /// Compare this APInt with the given APInt& RHS
276 /// for the validity of the inequality relationship.
277 /// @brief Inequality operator.
278 inline bool operator!=(const APInt& RHS) const {
279 return !((*this) == RHS);
282 /// Compare this APInt with the given uint64_t value
283 /// for the validity of the inequality relationship.
284 /// @brief Inequality operator.
285 inline bool operator!=(uint64_t Val) const {
286 return !((*this) == Val);
289 /// @brief Equality comparison
290 bool eq(const APInt &RHS) const {
291 return (*this) == RHS;
294 /// @brief Inequality comparison
295 bool ne(const APInt &RHS) const {
296 return !((*this) == RHS);
299 /// @brief Unsigned less than comparison
300 bool ult(const APInt& RHS) const;
302 /// @brief Signed less than comparison
303 bool slt(const APInt& RHS) const;
305 /// @brief Unsigned less or equal comparison
306 bool ule(const APInt& RHS) const {
307 return ult(RHS) || eq(RHS);
310 /// @brief Signed less or equal comparison
311 bool sle(const APInt& RHS) const {
312 return slt(RHS) || eq(RHS);
315 /// @brief Unsigned greather than comparison
316 bool ugt(const APInt& RHS) const {
317 return !ult(RHS) && !eq(RHS);
320 /// @brief Signed greather than comparison
321 bool sgt(const APInt& RHS) const {
322 return !slt(RHS) && !eq(RHS);
325 /// @brief Unsigned greater or equal comparison
326 bool uge(const APInt& RHS) const {
330 /// @brief Signed greather or equal comparison
331 bool sge(const APInt& RHS) const {
335 /// Arithmetic right-shift this APInt by shiftAmt.
336 /// @brief Arithmetic right-shift function.
337 APInt ashr(uint32_t shiftAmt) const;
339 /// Logical right-shift this APInt by shiftAmt.
340 /// @brief Logical right-shift function.
341 APInt lshr(uint32_t shiftAmt) const;
343 /// Left-shift this APInt by shiftAmt.
344 /// @brief Left-shift function.
345 APInt shl(uint32_t shiftAmt) const;
347 /// Signed divide this APInt by APInt RHS.
348 /// @brief Signed division function for APInt.
349 inline APInt sdiv(const APInt& RHS) const {
350 bool isNegativeLHS = (*this)[BitWidth - 1];
351 bool isNegativeRHS = RHS[RHS.BitWidth - 1];
352 APInt Result = APIntOps::udiv(
353 isNegativeLHS ? -(*this) : (*this), isNegativeRHS ? -RHS : RHS);
354 return isNegativeLHS != isNegativeRHS ? -Result : Result;
357 /// Unsigned divide this APInt by APInt RHS.
358 /// @brief Unsigned division function for APInt.
359 APInt udiv(const APInt& RHS) const;
361 /// Signed remainder operation on APInt.
362 /// @brief Function for signed remainder operation.
363 inline APInt srem(const APInt& RHS) const {
364 bool isNegativeLHS = (*this)[BitWidth - 1];
365 bool isNegativeRHS = RHS[RHS.BitWidth - 1];
366 APInt Result = APIntOps::urem(
367 isNegativeLHS ? -(*this) : (*this), isNegativeRHS ? -RHS : RHS);
368 return isNegativeLHS ? -Result : Result;
371 /// Unsigned remainder operation on APInt.
372 /// @brief Function for unsigned remainder operation.
373 APInt urem(const APInt& RHS) const;
375 /// Truncate the APInt to a specified width. It is an error to specify a width
376 /// that is greater than or equal to the current width.
377 /// @brief Truncate to new width.
378 void trunc(uint32_t width);
380 /// This operation sign extends the APInt to a new width. If the high order
381 /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
382 /// It is an error to specify a width that is less than or equal to the
384 /// @brief Sign extend to a new width.
385 void sext(uint32_t width);
387 /// This operation zero extends the APInt to a new width. Thie high order bits
388 /// are filled with 0 bits. It is an error to specify a width that is less
389 /// than or equal to the current width.
390 /// @brief Zero extend to a new width.
391 void zext(uint32_t width);
393 /// @brief Set every bit to 1.
396 /// Set the given bit to 1 whose position is given as "bitPosition".
397 /// @brief Set a given bit to 1.
398 APInt& set(uint32_t bitPosition);
400 /// @brief Set every bit to 0.
403 /// Set the given bit to 0 whose position is given as "bitPosition".
404 /// @brief Set a given bit to 0.
405 APInt& clear(uint32_t bitPosition);
407 /// @brief Toggle every bit to its opposite value.
410 /// Toggle a given bit to its opposite value whose position is given
411 /// as "bitPosition".
412 /// @brief Toggles a given bit to its opposite value.
413 APInt& flip(uint32_t bitPosition);
415 /// This function returns the number of active bits which is defined as the
416 /// bit width minus the number of leading zeros. This is used in several
417 /// computations to see how "wide" the value is.
418 /// @brief Compute the number of active bits in the value
419 inline uint32_t getActiveBits() const {
420 return BitWidth - countLeadingZeros();
423 /// @returns a uint64_t value from this APInt. If this APInt contains a single
424 /// word, just returns VAL, otherwise pVal[0].
425 inline uint64_t getValue(bool isSigned = false) const {
427 return isSigned ? int64_t(VAL << (64 - BitWidth)) >>
428 (64 - BitWidth) : VAL;
429 uint32_t n = getActiveBits();
432 assert(0 && "This APInt's bitwidth > 64");
435 /// @returns the largest value for an APInt of the specified bit-width and
436 /// if isSign == true, it should be largest signed value, otherwise largest
438 /// @brief Gets max value of the APInt with bitwidth <= 64.
439 static APInt getMaxValue(uint32_t numBits, bool isSign);
441 /// @returns the smallest value for an APInt of the given bit-width and
442 /// if isSign == true, it should be smallest signed value, otherwise zero.
443 /// @brief Gets min value of the APInt with bitwidth <= 64.
444 static APInt getMinValue(uint32_t numBits, bool isSign);
446 /// @returns the all-ones value for an APInt of the specified bit-width.
447 /// @brief Get the all-ones value.
448 static APInt getAllOnesValue(uint32_t numBits);
450 /// @returns the '0' value for an APInt of the specified bit-width.
451 /// @brief Get the '0' value.
452 static APInt getNullValue(uint32_t numBits);
454 /// This converts the APInt to a boolean valy as a test against zero.
455 /// @brief Boolean conversion function.
456 inline bool getBoolValue() const {
457 return countLeadingZeros() != BitWidth;
460 /// @returns a character interpretation of the APInt.
461 std::string toString(uint8_t radix = 10, bool wantSigned = true) const;
463 /// Get an APInt with the same BitWidth as this APInt, just zero mask
464 /// the low bits and right shift to the least significant bit.
465 /// @returns the high "numBits" bits of this APInt.
466 APInt getHiBits(uint32_t numBits) const;
468 /// Get an APInt with the same BitWidth as this APInt, just zero mask
470 /// @returns the low "numBits" bits of this APInt.
471 APInt getLoBits(uint32_t numBits) const;
473 /// @returns true if the argument APInt value is a power of two > 0.
474 bool isPowerOf2() const;
476 /// @returns the number of zeros from the most significant bit to the first
478 uint32_t countLeadingZeros() const;
480 /// @returns the number of zeros from the least significant bit to the first
482 uint32_t countTrailingZeros() const;
484 /// @returns the number of set bits.
485 uint32_t countPopulation() const;
487 /// @returns the total number of bits.
488 inline uint32_t getBitWidth() const {
492 /// @brief Check if this APInt has a N-bits integer value.
493 inline bool isIntN(uint32_t N) const {
494 assert(N && "N == 0 ???");
495 if (isSingleWord()) {
496 return VAL == (VAL & (~0ULL >> (64 - N)));
498 APInt Tmp(N, getNumWords(), pVal);
499 return Tmp == (*this);
503 /// @returns a byte-swapped representation of this APInt Value.
504 APInt byteSwap() const;
506 /// @returns the floor log base 2 of this APInt.
507 inline uint32_t logBase2() const {
508 return getNumWords() * APINT_BITS_PER_WORD - 1 - countLeadingZeros();
511 /// @brief Converts this APInt to a double value.
512 double roundToDouble(bool isSigned = false) const;
518 /// @brief Check if the specified APInt has a N-bits integer value.
519 inline bool isIntN(uint32_t N, const APInt& APIVal) {
520 return APIVal.isIntN(N);
523 /// @returns true if the argument APInt value is a sequence of ones
524 /// starting at the least significant bit with the remainder zero.
525 inline const bool isMask(uint32_t numBits, const APInt& APIVal) {
526 return APIVal.getBoolValue() && ((APIVal + APInt(numBits,1)) & APIVal) == 0;
529 /// @returns true if the argument APInt value contains a sequence of ones
530 /// with the remainder zero.
531 inline const bool isShiftedMask(uint32_t numBits, const APInt& APIVal) {
532 return isMask(numBits, (APIVal - APInt(numBits,1)) | APIVal);
535 /// @returns a byte-swapped representation of the specified APInt Value.
536 inline APInt byteSwap(const APInt& APIVal) {
537 return APIVal.byteSwap();
540 /// @returns the floor log base 2 of the specified APInt value.
541 inline uint32_t logBase2(const APInt& APIVal) {
542 return APIVal.logBase2();
545 /// @returns the greatest common divisor of the two values
546 /// using Euclid's algorithm.
547 APInt GreatestCommonDivisor(const APInt& API1, const APInt& API2);
549 /// @brief Converts the given APInt to a double value.
550 inline double RoundAPIntToDouble(const APInt& APIVal, bool isSigned = false) {
551 return APIVal.roundToDouble(isSigned);
554 /// @brief Converts the given APInt to a float vlalue.
555 inline float RoundAPIntToFloat(const APInt& APIVal) {
556 return float(RoundAPIntToDouble(APIVal));
559 /// @brief Converts the given double value into a APInt.
560 APInt RoundDoubleToAPInt(double Double);
562 /// @brief Converts the given float value into a APInt.
563 inline APInt RoundFloatToAPInt(float Float) {
564 return RoundDoubleToAPInt(double(Float));
567 /// Arithmetic right-shift the APInt by shiftAmt.
568 /// @brief Arithmetic right-shift function.
569 inline APInt ashr(const APInt& LHS, uint32_t shiftAmt) {
570 return LHS.ashr(shiftAmt);
573 /// Logical right-shift the APInt by shiftAmt.
574 /// @brief Logical right-shift function.
575 inline APInt lshr(const APInt& LHS, uint32_t shiftAmt) {
576 return LHS.lshr(shiftAmt);
579 /// Left-shift the APInt by shiftAmt.
580 /// @brief Left-shift function.
581 inline APInt shl(const APInt& LHS, uint32_t shiftAmt) {
582 return LHS.shl(shiftAmt);
585 /// Signed divide APInt LHS by APInt RHS.
586 /// @brief Signed division function for APInt.
587 inline APInt sdiv(const APInt& LHS, const APInt& RHS) {
588 return LHS.sdiv(RHS);
591 /// Unsigned divide APInt LHS by APInt RHS.
592 /// @brief Unsigned division function for APInt.
593 inline APInt udiv(const APInt& LHS, const APInt& RHS) {
594 return LHS.udiv(RHS);
597 /// Signed remainder operation on APInt.
598 /// @brief Function for signed remainder operation.
599 inline APInt srem(const APInt& LHS, const APInt& RHS) {
600 return LHS.srem(RHS);
603 /// Unsigned remainder operation on APInt.
604 /// @brief Function for unsigned remainder operation.
605 inline APInt urem(const APInt& LHS, const APInt& RHS) {
606 return LHS.urem(RHS);
609 /// Performs multiplication on APInt values.
610 /// @brief Function for multiplication operation.
611 inline APInt mul(const APInt& LHS, const APInt& RHS) {
615 /// Performs addition on APInt values.
616 /// @brief Function for addition operation.
617 inline APInt add(const APInt& LHS, const APInt& RHS) {
621 /// Performs subtraction on APInt values.
622 /// @brief Function for subtraction operation.
623 inline APInt sub(const APInt& LHS, const APInt& RHS) {
627 /// Performs bitwise AND operation on APInt LHS and
629 /// @brief Bitwise AND function for APInt.
630 inline APInt And(const APInt& LHS, const APInt& RHS) {
634 /// Performs bitwise OR operation on APInt LHS and APInt RHS.
635 /// @brief Bitwise OR function for APInt.
636 inline APInt Or(const APInt& LHS, const APInt& RHS) {
640 /// Performs bitwise XOR operation on APInt.
641 /// @brief Bitwise XOR function for APInt.
642 inline APInt Xor(const APInt& LHS, const APInt& RHS) {
646 /// Performs a bitwise complement operation on APInt.
647 /// @brief Bitwise complement function.
648 inline APInt Not(const APInt& APIVal) {
652 } // End of APIntOps namespace
654 } // End of llvm namespace