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"
24 //===----------------------------------------------------------------------===//
26 //===----------------------------------------------------------------------===//
28 /// APInt - This class represents arbitrary precision constant integral values.
29 /// It is a functional replacement for common case unsigned integer type like
30 /// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width
31 /// integer sizes and large integer value types such as 3-bits, 15-bits, or more
32 /// than 64-bits of precision. APInt provides a variety of arithmetic operators
33 /// and methods to manipulate integer values of any bit-width. It supports both
34 /// the typical integer arithmetic and comparison operations as well as bitwise
37 /// The class has several invariants worth noting:
38 /// * All bit, byte, and word positions are zero-based.
39 /// * Once the bit width is set, it doesn't change except by the Truncate,
40 /// SignExtend, or ZeroExtend operations.
41 /// * All binary operators must be on APInt instances of the same bit width.
42 /// Attempting to use these operators on instances with different bit
43 /// widths will yield an assertion.
44 /// * The value is stored canonically as an unsigned value. For operations
45 /// where it makes a difference, there are both signed and unsigned variants
46 /// of the operation. For example, sdiv and udiv. However, because the bit
47 /// widths must be the same, operations such as Mul and Add produce the same
48 /// results regardless of whether the values are interpreted as signed or
50 /// * In general, the class tries to follow the style of computation that LLVM
51 /// uses in its IR. This simplifies its use for LLVM.
53 /// @brief Class for arbitrary precision integers.
56 uint32_t BitWidth; ///< The number of bits in this APInt.
58 /// This union is used to store the integer value. When the
59 /// integer bit-width <= 64, it uses VAL, otherwise it uses pVal.
61 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
62 uint64_t *pVal; ///< Used to store the >64 bits integer value.
65 /// This enum is used to hold the constants we needed for APInt.
67 APINT_BITS_PER_WORD = sizeof(uint64_t) * 8, ///< Bits in a word
68 APINT_WORD_SIZE = sizeof(uint64_t) ///< Byte size of a word
71 /// This constructor is used only internally for speed of construction of
72 /// temporaries. It is unsafe for general use so it is not public.
73 /// @brief Fast internal constructor
74 APInt(uint64_t* val, uint32_t bits) : BitWidth(bits), pVal(val) { }
76 /// @returns true if the number of bits <= 64, false otherwise.
77 /// @brief Determine if this APInt just has one word to store value.
78 inline bool isSingleWord() const {
79 return BitWidth <= APINT_BITS_PER_WORD;
82 /// @returns the word position for the specified bit position.
83 /// @brief Determine which word a bit is in.
84 static inline uint32_t whichWord(uint32_t bitPosition) {
85 return bitPosition / APINT_BITS_PER_WORD;
88 /// @returns the bit position in a word for the specified bit position
90 /// @brief Determine which bit in a word a bit is in.
91 static inline uint32_t whichBit(uint32_t bitPosition) {
92 return bitPosition % APINT_BITS_PER_WORD;
95 /// This method generates and returns a uint64_t (word) mask for a single
96 /// bit at a specific bit position. This is used to mask the bit in the
97 /// corresponding word.
98 /// @returns a uint64_t with only bit at "whichBit(bitPosition)" set
99 /// @brief Get a single bit mask.
100 static inline uint64_t maskBit(uint32_t bitPosition) {
101 return 1ULL << whichBit(bitPosition);
104 /// This method is used internally to clear the to "N" bits in the high order
105 /// word that are not used by the APInt. This is needed after the most
106 /// significant word is assigned a value to ensure that those bits are
108 /// @brief Clear unused high order bits
109 inline APInt& clearUnusedBits() {
110 // Compute how many bits are used in the final word
111 uint32_t wordBits = BitWidth % APINT_BITS_PER_WORD;
113 // If all bits are used, we want to leave the value alone. This also
114 // avoids the undefined behavior of >> when the shfit is the same size as
115 // the word size (64).
118 // Mask out the hight bits.
119 uint64_t mask = ~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - wordBits);
123 pVal[getNumWords() - 1] &= mask;
127 /// @returns the corresponding word for the specified bit position.
128 /// @brief Get the word corresponding to a bit position
129 inline uint64_t getWord(uint32_t bitPosition) const {
130 return isSingleWord() ? VAL : pVal[whichWord(bitPosition)];
133 /// This is used by the constructors that take string arguments.
134 /// @brief Convert a char array into an APInt
135 void fromString(uint32_t numBits, const char *strStart, uint32_t slen,
138 /// This is used by the toString method to divide by the radix. It simply
139 /// provides a more convenient form of divide for internal use since KnuthDiv
140 /// has specific constraints on its inputs. If those constraints are not met
141 /// then it provides a simpler form of divide.
142 /// @brief An internal division function for dividing APInts.
143 static void divide(const APInt LHS, uint32_t lhsWords,
144 const APInt &RHS, uint32_t rhsWords,
145 APInt *Quotient, APInt *Remainder);
148 /// @brief debug method
153 /// @name Constructors
155 /// If isSigned is true then val is treated as if it were a signed value
156 /// (i.e. as an int64_t) and the appropriate sign extension to the bit width
157 /// will be done. Otherwise, no sign extension occurs (high order bits beyond
158 /// the range of val are zero filled).
159 /// @param numBits the bit width of the constructed APInt
160 /// @param val the initial value of the APInt
161 /// @param isSigned how to treat signedness of val
162 /// @brief Create a new APInt of numBits width, initialized as val.
163 APInt(uint32_t numBits, uint64_t val, bool isSigned = false);
165 /// Note that numWords can be smaller or larger than the corresponding bit
166 /// width but any extraneous bits will be dropped.
167 /// @param numBits the bit width of the constructed APInt
168 /// @param numWords the number of words in bigVal
169 /// @param bigVal a sequence of words to form the initial value of the APInt
170 /// @brief Construct an APInt of numBits width, initialized as bigVal[].
171 APInt(uint32_t numBits, uint32_t numWords, uint64_t bigVal[]);
173 /// This constructor interprets Val as a string in the given radix. The
174 /// interpretation stops when the first charater that is not suitable for the
175 /// radix is encountered. Acceptable radix values are 2, 8, 10 and 16. It is
176 /// an error for the value implied by the string to require more bits than
178 /// @param numBits the bit width of the constructed APInt
179 /// @param val the string to be interpreted
180 /// @param radix the radix of Val to use for the intepretation
181 /// @brief Construct an APInt from a string representation.
182 APInt(uint32_t numBits, const std::string& val, uint8_t radix);
184 /// This constructor interprets the slen characters starting at StrStart as
185 /// a string in the given radix. The interpretation stops when the first
186 /// character that is not suitable for the radix is encountered. Acceptable
187 /// radix values are 2, 8, 10 and 16. It is an error for the value implied by
188 /// the string to require more bits than numBits.
189 /// @param numBits the bit width of the constructed APInt
190 /// @param strStart the start of the string to be interpreted
191 /// @param slen the maximum number of characters to interpret
192 /// @brief Construct an APInt from a string representation.
193 APInt(uint32_t numBits, const char strStart[], uint32_t slen, uint8_t radix);
195 /// Simply makes *this a copy of that.
196 /// @brief Copy Constructor.
197 APInt(const APInt& that);
199 /// @brief Destructor.
203 /// @name Value Tests
205 /// This tests the high bit of this APInt to determine if it is set.
206 /// @returns true if this APInt is negative, false otherwise
207 /// @brief Determine sign of this APInt.
208 bool isNegative() const {
209 return (*this)[BitWidth - 1];
212 /// This tests the high bit of the APInt to determine if it is unset.
213 /// @brief Determine if this APInt Value is positive (not negative).
214 bool isPositive() const {
215 return !isNegative();
218 /// This tests if the value of this APInt is strictly positive (> 0).
219 /// @returns true if this APInt is Positive and not zero.
220 /// @brief Determine if this APInt Value is strictly positive.
221 inline bool isStrictlyPositive() const {
222 return isPositive() && (*this) != 0;
225 /// This checks to see if the value has all bits of the APInt are set or not.
226 /// @brief Determine if all bits are set
227 inline bool isAllOnesValue() const {
228 return countPopulation() == BitWidth;
231 /// This checks to see if the value of this APInt is the maximum unsigned
232 /// value for the APInt's bit width.
233 /// @brief Determine if this is the largest unsigned value.
234 bool isMaxValue() const {
235 return countPopulation() == BitWidth;
238 /// This checks to see if the value of this APInt is the maximum signed
239 /// value for the APInt's bit width.
240 /// @brief Determine if this is the largest signed value.
241 bool isMaxSignedValue() const {
242 return BitWidth == 1 ? VAL == 0 :
243 !isNegative() && countPopulation() == BitWidth - 1;
246 /// This checks to see if the value of this APInt is the minimum unsigned
247 /// value for the APInt's bit width.
248 /// @brief Determine if this is the smallest unsigned value.
249 bool isMinValue() const {
250 return countPopulation() == 0;
253 /// This checks to see if the value of this APInt is the minimum signed
254 /// value for the APInt's bit width.
255 /// @brief Determine if this is the smallest signed value.
256 bool isMinSignedValue() const {
257 return BitWidth == 1 ? VAL == 1 :
258 isNegative() && countPopulation() == 1;
261 /// @brief Check if this APInt has an N-bits integer value.
262 inline bool isIntN(uint32_t N) const {
263 assert(N && "N == 0 ???");
264 if (isSingleWord()) {
265 return VAL == (VAL & (~0ULL >> (64 - N)));
267 APInt Tmp(N, getNumWords(), pVal);
268 return Tmp == (*this);
272 /// @returns true if the argument APInt value is a power of two > 0.
273 bool isPowerOf2() const;
275 /// This converts the APInt to a boolean valy as a test against zero.
276 /// @brief Boolean conversion function.
277 inline bool getBoolValue() const {
278 return countLeadingZeros() != BitWidth;
282 /// @name Value Generators
284 /// @brief Gets maximum unsigned value of APInt for specific bit width.
285 static APInt getMaxValue(uint32_t numBits) {
286 return APInt(numBits, 0).set();
289 /// @brief Gets maximum signed value of APInt for a specific bit width.
290 static APInt getSignedMaxValue(uint32_t numBits) {
291 return APInt(numBits, 0).set().clear(numBits - 1);
294 /// @brief Gets minimum unsigned value of APInt for a specific bit width.
295 static APInt getMinValue(uint32_t numBits) {
296 return APInt(numBits, 0);
299 /// @brief Gets minimum signed value of APInt for a specific bit width.
300 static APInt getSignedMinValue(uint32_t numBits) {
301 return APInt(numBits, 0).set(numBits - 1);
304 /// getSignBit - This is just a wrapper function of getSignedMinValue(), and
305 /// it helps code readability when we want to get a SignBit.
306 /// @brief Get the SignBit for a specific bit width.
307 inline static APInt getSignBit(uint32_t BitWidth) {
308 return getSignedMinValue(BitWidth);
311 /// @returns the all-ones value for an APInt of the specified bit-width.
312 /// @brief Get the all-ones value.
313 static APInt getAllOnesValue(uint32_t numBits) {
314 return APInt(numBits, 0).set();
317 /// @returns the '0' value for an APInt of the specified bit-width.
318 /// @brief Get the '0' value.
319 static APInt getNullValue(uint32_t numBits) {
320 return APInt(numBits, 0);
323 /// Get an APInt with the same BitWidth as this APInt, just zero mask
324 /// the low bits and right shift to the least significant bit.
325 /// @returns the high "numBits" bits of this APInt.
326 APInt getHiBits(uint32_t numBits) const;
328 /// Get an APInt with the same BitWidth as this APInt, just zero mask
330 /// @returns the low "numBits" bits of this APInt.
331 APInt getLoBits(uint32_t numBits) const;
333 /// Constructs an APInt value that has a contiguous range of bits set. The
334 /// bits from loBit to hiBit will be set. All other bits will be zero. For
335 /// example, with parameters(32, 15, 0) you would get 0x0000FFFF. If hiBit is
336 /// less than loBit then the set bits "wrap". For example, with
337 /// parameters (32, 3, 28), you would get 0xF000000F.
338 /// @param numBits the intended bit width of the result
339 /// @param hiBit the index of the highest bit set.
340 /// @param loBit the index of the lowest bit set.
341 /// @returns An APInt value with the requested bits set.
342 /// @brief Get a value with a block of bits set.
343 static APInt getBitsSet(uint32_t numBits, uint32_t hiBit, uint32_t loBit = 0){
344 assert(hiBit < numBits && "hiBit out of range");
345 assert(loBit < numBits && "loBit out of range");
347 return getLowBitsSet(numBits, hiBit+1) |
348 getHighBitsSet(numBits, numBits-loBit+1);
350 return getLowBitsSet(numBits, hiBit+1);
351 return getLowBitsSet(numBits, hiBit-loBit+1).shl(loBit);
354 /// Constructs an APInt value that has the top hiBitsSet bits set.
355 /// @param numBits the bitwidth of the result
356 /// @param hiBitsSet the number of high-order bits set in the result.
357 /// @brief Get a value with high bits set
358 static APInt getHighBitsSet(uint32_t numBits, uint32_t hiBitsSet) {
359 assert(hiBitsSet <= numBits && "Too many bits to set!");
360 uint32_t shiftAmt = numBits - hiBitsSet;
361 // For small values, return quickly
362 if (numBits <= APINT_BITS_PER_WORD)
363 return APInt(numBits, ~0ULL << shiftAmt);
364 return (~APInt(numBits, 0)).shl(shiftAmt);
367 /// Constructs an APInt value that has the bottom loBitsSet bits set.
368 /// @param numBits the bitwidth of the result
369 /// @param loBitsSet the number of low-order bits set in the result.
370 /// @brief Get a value with low bits set
371 static APInt getLowBitsSet(uint32_t numBits, uint32_t loBitsSet) {
372 assert(loBitsSet <= numBits && "Too many bits to set!");
373 uint32_t shiftAmt = numBits - loBitsSet;
374 // For small values, return quickly
375 if (numBits <= APINT_BITS_PER_WORD)
376 return APInt(numBits, ~0ULL >> shiftAmt);
377 return (~APInt(numBits, 0)).lshr(shiftAmt);
380 /// The hash value is computed as the sum of the words and the bit width.
381 /// @returns A hash value computed from the sum of the APInt words.
382 /// @brief Get a hash value based on this APInt
383 uint64_t getHashValue() const;
385 /// This function returns a pointer to the internal storage of the APInt.
386 /// This is useful for writing out the APInt in binary form without any
388 inline const uint64_t* getRawData() const {
394 /// @brief Set a sepcific word in the value to a new value.
395 inline void setWordToValue(uint32_t idx, uint64_t Val) {
396 assert(idx < getNumWords() && "Invalid word array index");
404 /// @name Unary Operators
406 /// @returns a new APInt value representing *this incremented by one
407 /// @brief Postfix increment operator.
408 inline const APInt operator++(int) {
414 /// @returns *this incremented by one
415 /// @brief Prefix increment operator.
418 /// @returns a new APInt representing *this decremented by one.
419 /// @brief Postfix decrement operator.
420 inline const APInt operator--(int) {
426 /// @returns *this decremented by one.
427 /// @brief Prefix decrement operator.
430 /// Performs a bitwise complement operation on this APInt.
431 /// @returns an APInt that is the bitwise complement of *this
432 /// @brief Unary bitwise complement operator.
433 APInt operator~() const;
435 /// Negates *this using two's complement logic.
436 /// @returns An APInt value representing the negation of *this.
437 /// @brief Unary negation operator
438 inline APInt operator-() const {
439 return APInt(BitWidth, 0) - (*this);
442 /// Performs logical negation operation on this APInt.
443 /// @returns true if *this is zero, false otherwise.
444 /// @brief Logical negation operator.
445 bool operator !() const;
448 /// @name Assignment Operators
450 /// @returns *this after assignment of RHS.
451 /// @brief Copy assignment operator.
452 APInt& operator=(const APInt& RHS);
454 /// The RHS value is assigned to *this. If the significant bits in RHS exceed
455 /// the bit width, the excess bits are truncated. If the bit width is larger
456 /// than 64, the value is zero filled in the unspecified high order bits.
457 /// @returns *this after assignment of RHS value.
458 /// @brief Assignment operator.
459 APInt& operator=(uint64_t RHS);
461 /// Performs a bitwise AND operation on this APInt and RHS. The result is
462 /// assigned to *this.
463 /// @returns *this after ANDing with RHS.
464 /// @brief Bitwise AND assignment operator.
465 APInt& operator&=(const APInt& RHS);
467 /// Performs a bitwise OR operation on this APInt and RHS. The result is
469 /// @returns *this after ORing with RHS.
470 /// @brief Bitwise OR assignment operator.
471 APInt& operator|=(const APInt& RHS);
473 /// Performs a bitwise XOR operation on this APInt and RHS. The result is
474 /// assigned to *this.
475 /// @returns *this after XORing with RHS.
476 /// @brief Bitwise XOR assignment operator.
477 APInt& operator^=(const APInt& RHS);
479 /// Multiplies this APInt by RHS and assigns the result to *this.
481 /// @brief Multiplication assignment operator.
482 APInt& operator*=(const APInt& RHS);
484 /// Adds RHS to *this and assigns the result to *this.
486 /// @brief Addition assignment operator.
487 APInt& operator+=(const APInt& RHS);
489 /// Subtracts RHS from *this and assigns the result to *this.
491 /// @brief Subtraction assignment operator.
492 APInt& operator-=(const APInt& RHS);
494 /// Shifts *this left by shiftAmt and assigns the result to *this.
495 /// @returns *this after shifting left by shiftAmt
496 /// @brief Left-shift assignment function.
497 inline APInt& operator<<=(uint32_t shiftAmt) {
498 *this = shl(shiftAmt);
503 /// @name Binary Operators
505 /// Performs a bitwise AND operation on *this and RHS.
506 /// @returns An APInt value representing the bitwise AND of *this and RHS.
507 /// @brief Bitwise AND operator.
508 APInt operator&(const APInt& RHS) const;
509 APInt And(const APInt& RHS) const {
510 return this->operator&(RHS);
513 /// Performs a bitwise OR operation on *this and RHS.
514 /// @returns An APInt value representing the bitwise OR of *this and RHS.
515 /// @brief Bitwise OR operator.
516 APInt operator|(const APInt& RHS) const;
517 APInt Or(const APInt& RHS) const {
518 return this->operator|(RHS);
521 /// Performs a bitwise XOR operation on *this and RHS.
522 /// @returns An APInt value representing the bitwise XOR of *this and RHS.
523 /// @brief Bitwise XOR operator.
524 APInt operator^(const APInt& RHS) const;
525 APInt Xor(const APInt& RHS) const {
526 return this->operator^(RHS);
529 /// Multiplies this APInt by RHS and returns the result.
530 /// @brief Multiplication operator.
531 APInt operator*(const APInt& RHS) const;
533 /// Adds RHS to this APInt and returns the result.
534 /// @brief Addition operator.
535 APInt operator+(const APInt& RHS) const;
536 APInt operator+(uint64_t RHS) const {
537 return (*this) + APInt(BitWidth, RHS);
540 /// Subtracts RHS from this APInt and returns the result.
541 /// @brief Subtraction operator.
542 APInt operator-(const APInt& RHS) const;
543 APInt operator-(uint64_t RHS) const {
544 return (*this) - APInt(BitWidth, RHS);
547 /// Arithmetic right-shift this APInt by shiftAmt.
548 /// @brief Arithmetic right-shift function.
549 APInt ashr(uint32_t shiftAmt) const;
551 /// Logical right-shift this APInt by shiftAmt.
552 /// @brief Logical right-shift function.
553 APInt lshr(uint32_t shiftAmt) const;
555 /// Left-shift this APInt by shiftAmt.
556 /// @brief Left-shift function.
557 APInt shl(uint32_t shiftAmt) const;
559 /// Perform an unsigned divide operation on this APInt by RHS. Both this and
560 /// RHS are treated as unsigned quantities for purposes of this division.
561 /// @returns a new APInt value containing the division result
562 /// @brief Unsigned division operation.
563 APInt udiv(const APInt& RHS) const;
565 /// Signed divide this APInt by APInt RHS.
566 /// @brief Signed division function for APInt.
567 inline APInt sdiv(const APInt& RHS) const {
569 if (RHS.isNegative())
570 return (-(*this)).udiv(-RHS);
572 return -((-(*this)).udiv(RHS));
573 else if (RHS.isNegative())
574 return -(this->udiv(-RHS));
575 return this->udiv(RHS);
578 /// Perform an unsigned remainder operation on this APInt with RHS being the
579 /// divisor. Both this and RHS are treated as unsigned quantities for purposes
580 /// of this operation. Note that this is a true remainder operation and not
581 /// a modulo operation because the sign follows the sign of the dividend
583 /// @returns a new APInt value containing the remainder result
584 /// @brief Unsigned remainder operation.
585 APInt urem(const APInt& RHS) const;
587 /// Signed remainder operation on APInt.
588 /// @brief Function for signed remainder operation.
589 inline APInt srem(const APInt& RHS) const {
591 if (RHS.isNegative())
592 return -((-(*this)).urem(-RHS));
594 return -((-(*this)).urem(RHS));
595 else if (RHS.isNegative())
596 return this->urem(-RHS);
597 return this->urem(RHS);
600 /// @returns the bit value at bitPosition
601 /// @brief Array-indexing support.
602 bool operator[](uint32_t bitPosition) const;
605 /// @name Comparison Operators
607 /// Compares this APInt with RHS for the validity of the equality
609 /// @brief Equality operator.
610 bool operator==(const APInt& RHS) const;
612 /// Compares this APInt with a uint64_t for the validity of the equality
614 /// @returns true if *this == Val
615 /// @brief Equality operator.
616 bool operator==(uint64_t Val) const;
618 /// Compares this APInt with RHS for the validity of the equality
620 /// @returns true if *this == Val
621 /// @brief Equality comparison.
622 bool eq(const APInt &RHS) const {
623 return (*this) == RHS;
626 /// Compares this APInt with RHS for the validity of the inequality
628 /// @returns true if *this != Val
629 /// @brief Inequality operator.
630 inline bool operator!=(const APInt& RHS) const {
631 return !((*this) == RHS);
634 /// Compares this APInt with a uint64_t for the validity of the inequality
636 /// @returns true if *this != Val
637 /// @brief Inequality operator.
638 inline bool operator!=(uint64_t Val) const {
639 return !((*this) == Val);
642 /// Compares this APInt with RHS for the validity of the inequality
644 /// @returns true if *this != Val
645 /// @brief Inequality comparison
646 bool ne(const APInt &RHS) const {
647 return !((*this) == RHS);
650 /// Regards both *this and RHS as unsigned quantities and compares them for
651 /// the validity of the less-than relationship.
652 /// @returns true if *this < RHS when both are considered unsigned.
653 /// @brief Unsigned less than comparison
654 bool ult(const APInt& RHS) const;
656 /// Regards both *this and RHS as signed quantities and compares them for
657 /// validity of the less-than relationship.
658 /// @returns true if *this < RHS when both are considered signed.
659 /// @brief Signed less than comparison
660 bool slt(const APInt& RHS) const;
662 /// Regards both *this and RHS as unsigned quantities and compares them for
663 /// validity of the less-or-equal relationship.
664 /// @returns true if *this <= RHS when both are considered unsigned.
665 /// @brief Unsigned less or equal comparison
666 bool ule(const APInt& RHS) const {
667 return ult(RHS) || eq(RHS);
670 /// Regards both *this and RHS as signed quantities and compares them for
671 /// validity of the less-or-equal relationship.
672 /// @returns true if *this <= RHS when both are considered signed.
673 /// @brief Signed less or equal comparison
674 bool sle(const APInt& RHS) const {
675 return slt(RHS) || eq(RHS);
678 /// Regards both *this and RHS as unsigned quantities and compares them for
679 /// the validity of the greater-than relationship.
680 /// @returns true if *this > RHS when both are considered unsigned.
681 /// @brief Unsigned greather than comparison
682 bool ugt(const APInt& RHS) const {
683 return !ult(RHS) && !eq(RHS);
686 /// Regards both *this and RHS as signed quantities and compares them for
687 /// the validity of the greater-than relationship.
688 /// @returns true if *this > RHS when both are considered signed.
689 /// @brief Signed greather than comparison
690 bool sgt(const APInt& RHS) const {
691 return !slt(RHS) && !eq(RHS);
694 /// Regards both *this and RHS as unsigned quantities and compares them for
695 /// validity of the greater-or-equal relationship.
696 /// @returns true if *this >= RHS when both are considered unsigned.
697 /// @brief Unsigned greater or equal comparison
698 bool uge(const APInt& RHS) const {
702 /// Regards both *this and RHS as signed quantities and compares them for
703 /// validity of the greater-or-equal relationship.
704 /// @returns true if *this >= RHS when both are considered signed.
705 /// @brief Signed greather or equal comparison
706 bool sge(const APInt& RHS) const {
711 /// @name Resizing Operators
713 /// Truncate the APInt to a specified width. It is an error to specify a width
714 /// that is greater than or equal to the current width.
715 /// @brief Truncate to new width.
716 APInt &trunc(uint32_t width);
718 /// This operation sign extends the APInt to a new width. If the high order
719 /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
720 /// It is an error to specify a width that is less than or equal to the
722 /// @brief Sign extend to a new width.
723 APInt &sext(uint32_t width);
725 /// This operation zero extends the APInt to a new width. Thie high order bits
726 /// are filled with 0 bits. It is an error to specify a width that is less
727 /// than or equal to the current width.
728 /// @brief Zero extend to a new width.
729 APInt &zext(uint32_t width);
731 /// Make this APInt have the bit width given by \p width. The value is sign
732 /// extended, truncated, or left alone to make it that width.
733 /// @brief Sign extend or truncate to width
734 APInt &sextOrTrunc(uint32_t width);
736 /// Make this APInt have the bit width given by \p width. The value is zero
737 /// extended, truncated, or left alone to make it that width.
738 /// @brief Zero extend or truncate to width
739 APInt &zextOrTrunc(uint32_t width);
741 /// This is a help function for convenience. If the given \p width equals to
742 /// this APInt's BitWidth, just return this APInt, otherwise, just zero
744 inline APInt &zextOrCopy(uint32_t width) {
745 if (width == BitWidth)
751 /// @name Bit Manipulation Operators
753 /// @brief Set every bit to 1.
756 /// Set the given bit to 1 whose position is given as "bitPosition".
757 /// @brief Set a given bit to 1.
758 APInt& set(uint32_t bitPosition);
760 /// @brief Set every bit to 0.
763 /// Set the given bit to 0 whose position is given as "bitPosition".
764 /// @brief Set a given bit to 0.
765 APInt& clear(uint32_t bitPosition);
767 /// @brief Toggle every bit to its opposite value.
770 /// Toggle a given bit to its opposite value whose position is given
771 /// as "bitPosition".
772 /// @brief Toggles a given bit to its opposite value.
773 APInt& flip(uint32_t bitPosition);
776 /// @name Value Characterization Functions
779 /// @returns the total number of bits.
780 inline uint32_t getBitWidth() const {
784 /// Here one word's bitwidth equals to that of uint64_t.
785 /// @returns the number of words to hold the integer value of this APInt.
786 /// @brief Get the number of words.
787 inline uint32_t getNumWords() const {
788 return (BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
791 /// This function returns the number of active bits which is defined as the
792 /// bit width minus the number of leading zeros. This is used in several
793 /// computations to see how "wide" the value is.
794 /// @brief Compute the number of active bits in the value
795 inline uint32_t getActiveBits() const {
796 return BitWidth - countLeadingZeros();
799 /// This function returns the number of active words in the value of this
800 /// APInt. This is used in conjunction with getActiveData to extract the raw
801 /// value of the APInt.
802 inline uint32_t getActiveWords() const {
803 return whichWord(getActiveBits()-1) + 1;
806 /// Computes the minimum bit width for this APInt while considering it to be
807 /// a signed (and probably negative) value. If the value is not negative,
808 /// this function returns the same value as getActiveBits(). Otherwise, it
809 /// returns the smallest bit width that will retain the negative value. For
810 /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
811 /// for -1, this function will always return 1.
812 /// @brief Get the minimum bit size for this signed APInt
813 inline uint32_t getMinSignedBits() const {
815 return BitWidth - countLeadingOnes() + 1;
816 return getActiveBits();
819 /// This method attempts to return the value of this APInt as a zero extended
820 /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
821 /// uint64_t. Otherwise an assertion will result.
822 /// @brief Get zero extended value
823 inline uint64_t getZExtValue() const {
826 assert(getActiveBits() <= 64 && "Too many bits for uint64_t");
830 /// This method attempts to return the value of this APInt as a sign extended
831 /// int64_t. The bit width must be <= 64 or the value must fit within an
832 /// int64_t. Otherwise an assertion will result.
833 /// @brief Get sign extended value
834 inline int64_t getSExtValue() const {
836 return int64_t(VAL << (APINT_BITS_PER_WORD - BitWidth)) >>
837 (APINT_BITS_PER_WORD - BitWidth);
838 assert(getActiveBits() <= 64 && "Too many bits for int64_t");
839 return int64_t(pVal[0]);
841 /// countLeadingZeros - This function is an APInt version of the
842 /// countLeadingZeros_{32,64} functions in MathExtras.h. It counts the number
843 /// of zeros from the most significant bit to the first one bit.
844 /// @returns getNumWords() * APINT_BITS_PER_WORD if the value is zero.
845 /// @returns the number of zeros from the most significant bit to the first
847 /// @brief Count the number of leading one bits.
848 uint32_t countLeadingZeros() const;
850 /// countLeadingOnes - This function counts the number of contiguous 1 bits
851 /// in the high order bits. The count stops when the first 0 bit is reached.
852 /// @returns 0 if the high order bit is not set
853 /// @returns the number of 1 bits from the most significant to the least
854 /// @brief Count the number of leading one bits.
855 uint32_t countLeadingOnes() const;
857 /// countTrailingZeros - This function is an APInt version of the
858 /// countTrailingZoers_{32,64} functions in MathExtras.h. It counts
859 /// the number of zeros from the least significant bit to the first one bit.
860 /// @returns getNumWords() * APINT_BITS_PER_WORD if the value is zero.
861 /// @returns the number of zeros from the least significant bit to the first
863 /// @brief Count the number of trailing zero bits.
864 uint32_t countTrailingZeros() const;
866 /// countPopulation - This function is an APInt version of the
867 /// countPopulation_{32,64} functions in MathExtras.h. It counts the number
868 /// of 1 bits in the APInt value.
869 /// @returns 0 if the value is zero.
870 /// @returns the number of set bits.
871 /// @brief Count the number of bits set.
872 uint32_t countPopulation() const;
875 /// @name Conversion Functions
878 /// This is used internally to convert an APInt to a string.
879 /// @brief Converts an APInt to a std::string
880 std::string toString(uint8_t radix, bool wantSigned) const;
882 /// Considers the APInt to be unsigned and converts it into a string in the
883 /// radix given. The radix can be 2, 8, 10 or 16.
884 /// @returns a character interpretation of the APInt
885 /// @brief Convert unsigned APInt to string representation.
886 inline std::string toString(uint8_t radix = 10) const {
887 return toString(radix, false);
890 /// Considers the APInt to be unsigned and converts it into a string in the
891 /// radix given. The radix can be 2, 8, 10 or 16.
892 /// @returns a character interpretation of the APInt
893 /// @brief Convert unsigned APInt to string representation.
894 inline std::string toStringSigned(uint8_t radix = 10) const {
895 return toString(radix, true);
898 /// @returns a byte-swapped representation of this APInt Value.
899 APInt byteSwap() const;
901 /// @brief Converts this APInt to a double value.
902 double roundToDouble(bool isSigned) const;
904 /// @brief Converts this unsigned APInt to a double value.
905 double roundToDouble() const {
906 return roundToDouble(false);
909 /// @brief Converts this signed APInt to a double value.
910 double signedRoundToDouble() const {
911 return roundToDouble(true);
914 /// The conversion does not do a translation from integer to double, it just
915 /// re-interprets the bits as a double. Note that it is valid to do this on
916 /// any bit width. Exactly 64 bits will be translated.
917 /// @brief Converts APInt bits to a double
918 double bitsToDouble() const {
923 T.I = (isSingleWord() ? VAL : pVal[0]);
927 /// The conversion does not do a translation from integer to float, it just
928 /// re-interprets the bits as a float. Note that it is valid to do this on
929 /// any bit width. Exactly 32 bits will be translated.
930 /// @brief Converts APInt bits to a double
931 float bitsToFloat() const {
936 T.I = uint32_t((isSingleWord() ? VAL : pVal[0]));
940 /// The conversion does not do a translation from double to integer, it just
941 /// re-interprets the bits of the double. Note that it is valid to do this on
942 /// any bit width but bits from V may get truncated.
943 /// @brief Converts a double to APInt bits.
944 APInt& doubleToBits(double V) {
954 return clearUnusedBits();
957 /// The conversion does not do a translation from float to integer, it just
958 /// re-interprets the bits of the float. Note that it is valid to do this on
959 /// any bit width but bits from V may get truncated.
960 /// @brief Converts a float to APInt bits.
961 APInt& floatToBits(float V) {
971 return clearUnusedBits();
975 /// @name Mathematics Operations
978 /// @returns the floor log base 2 of this APInt.
979 inline uint32_t logBase2() const {
980 return BitWidth - 1 - countLeadingZeros();
983 /// @brief Compute the square root
986 /// If *this is < 0 then return -(*this), otherwise *this;
987 /// @brief Get the absolute value;
996 inline bool operator==(uint64_t V1, const APInt& V2) {
1000 inline bool operator!=(uint64_t V1, const APInt& V2) {
1004 namespace APIntOps {
1006 /// @brief Determine the smaller of two APInts considered to be signed.
1007 inline APInt smin(const APInt &A, const APInt &B) {
1008 return A.slt(B) ? A : B;
1011 /// @brief Determine the larger of two APInts considered to be signed.
1012 inline APInt smax(const APInt &A, const APInt &B) {
1013 return A.sgt(B) ? A : B;
1016 /// @brief Determine the smaller of two APInts considered to be signed.
1017 inline APInt umin(const APInt &A, const APInt &B) {
1018 return A.ult(B) ? A : B;
1021 /// @brief Determine the larger of two APInts considered to be unsigned.
1022 inline APInt umax(const APInt &A, const APInt &B) {
1023 return A.ugt(B) ? A : B;
1026 /// @brief Check if the specified APInt has a N-bits integer value.
1027 inline bool isIntN(uint32_t N, const APInt& APIVal) {
1028 return APIVal.isIntN(N);
1031 /// @returns true if the argument APInt value is a sequence of ones
1032 /// starting at the least significant bit with the remainder zero.
1033 inline const bool isMask(uint32_t numBits, const APInt& APIVal) {
1034 return APIVal.getBoolValue() && ((APIVal + APInt(numBits,1)) & APIVal) == 0;
1037 /// @returns true if the argument APInt value contains a sequence of ones
1038 /// with the remainder zero.
1039 inline const bool isShiftedMask(uint32_t numBits, const APInt& APIVal) {
1040 return isMask(numBits, (APIVal - APInt(numBits,1)) | APIVal);
1043 /// @returns a byte-swapped representation of the specified APInt Value.
1044 inline APInt byteSwap(const APInt& APIVal) {
1045 return APIVal.byteSwap();
1048 /// @returns the floor log base 2 of the specified APInt value.
1049 inline uint32_t logBase2(const APInt& APIVal) {
1050 return APIVal.logBase2();
1053 /// GreatestCommonDivisor - This function returns the greatest common
1054 /// divisor of the two APInt values using Enclid's algorithm.
1055 /// @returns the greatest common divisor of Val1 and Val2
1056 /// @brief Compute GCD of two APInt values.
1057 APInt GreatestCommonDivisor(const APInt& Val1, const APInt& Val2);
1059 /// Treats the APInt as an unsigned value for conversion purposes.
1060 /// @brief Converts the given APInt to a double value.
1061 inline double RoundAPIntToDouble(const APInt& APIVal) {
1062 return APIVal.roundToDouble();
1065 /// Treats the APInt as a signed value for conversion purposes.
1066 /// @brief Converts the given APInt to a double value.
1067 inline double RoundSignedAPIntToDouble(const APInt& APIVal) {
1068 return APIVal.signedRoundToDouble();
1071 /// @brief Converts the given APInt to a float vlalue.
1072 inline float RoundAPIntToFloat(const APInt& APIVal) {
1073 return float(RoundAPIntToDouble(APIVal));
1076 /// Treast the APInt as a signed value for conversion purposes.
1077 /// @brief Converts the given APInt to a float value.
1078 inline float RoundSignedAPIntToFloat(const APInt& APIVal) {
1079 return float(APIVal.signedRoundToDouble());
1082 /// RoundDoubleToAPInt - This function convert a double value to an APInt value.
1083 /// @brief Converts the given double value into a APInt.
1084 APInt RoundDoubleToAPInt(double Double, uint32_t width);
1086 /// RoundFloatToAPInt - Converts a float value into an APInt value.
1087 /// @brief Converts a float value into a APInt.
1088 inline APInt RoundFloatToAPInt(float Float, uint32_t width) {
1089 return RoundDoubleToAPInt(double(Float), width);
1092 /// Arithmetic right-shift the APInt by shiftAmt.
1093 /// @brief Arithmetic right-shift function.
1094 inline APInt ashr(const APInt& LHS, uint32_t shiftAmt) {
1095 return LHS.ashr(shiftAmt);
1098 /// Logical right-shift the APInt by shiftAmt.
1099 /// @brief Logical right-shift function.
1100 inline APInt lshr(const APInt& LHS, uint32_t shiftAmt) {
1101 return LHS.lshr(shiftAmt);
1104 /// Left-shift the APInt by shiftAmt.
1105 /// @brief Left-shift function.
1106 inline APInt shl(const APInt& LHS, uint32_t shiftAmt) {
1107 return LHS.shl(shiftAmt);
1110 /// Signed divide APInt LHS by APInt RHS.
1111 /// @brief Signed division function for APInt.
1112 inline APInt sdiv(const APInt& LHS, const APInt& RHS) {
1113 return LHS.sdiv(RHS);
1116 /// Unsigned divide APInt LHS by APInt RHS.
1117 /// @brief Unsigned division function for APInt.
1118 inline APInt udiv(const APInt& LHS, const APInt& RHS) {
1119 return LHS.udiv(RHS);
1122 /// Signed remainder operation on APInt.
1123 /// @brief Function for signed remainder operation.
1124 inline APInt srem(const APInt& LHS, const APInt& RHS) {
1125 return LHS.srem(RHS);
1128 /// Unsigned remainder operation on APInt.
1129 /// @brief Function for unsigned remainder operation.
1130 inline APInt urem(const APInt& LHS, const APInt& RHS) {
1131 return LHS.urem(RHS);
1134 /// Performs multiplication on APInt values.
1135 /// @brief Function for multiplication operation.
1136 inline APInt mul(const APInt& LHS, const APInt& RHS) {
1140 /// Performs addition on APInt values.
1141 /// @brief Function for addition operation.
1142 inline APInt add(const APInt& LHS, const APInt& RHS) {
1146 /// Performs subtraction on APInt values.
1147 /// @brief Function for subtraction operation.
1148 inline APInt sub(const APInt& LHS, const APInt& RHS) {
1152 /// Performs bitwise AND operation on APInt LHS and
1154 /// @brief Bitwise AND function for APInt.
1155 inline APInt And(const APInt& LHS, const APInt& RHS) {
1159 /// Performs bitwise OR operation on APInt LHS and APInt RHS.
1160 /// @brief Bitwise OR function for APInt.
1161 inline APInt Or(const APInt& LHS, const APInt& RHS) {
1165 /// Performs bitwise XOR operation on APInt.
1166 /// @brief Bitwise XOR function for APInt.
1167 inline APInt Xor(const APInt& LHS, const APInt& RHS) {
1171 /// Performs a bitwise complement operation on APInt.
1172 /// @brief Bitwise complement function.
1173 inline APInt Not(const APInt& APIVal) {
1177 } // End of APIntOps namespace
1179 } // End of llvm namespace