1 //===-- llvm/ADT/APInt.h - For Arbitrary Precision Integer -----*- C++ -*--===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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"
19 #include "llvm/Support/MathExtras.h"
28 class FoldingSetNodeID;
32 class SmallVectorImpl;
34 /* An unsigned host type used as a single part of a multi-part
36 typedef uint64_t integerPart;
38 const unsigned int host_char_bit = 8;
39 const unsigned int integerPartWidth = host_char_bit *
40 static_cast<unsigned int>(sizeof(integerPart));
42 //===----------------------------------------------------------------------===//
44 //===----------------------------------------------------------------------===//
46 /// APInt - This class represents arbitrary precision constant integral values.
47 /// It is a functional replacement for common case unsigned integer type like
48 /// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width
49 /// integer sizes and large integer value types such as 3-bits, 15-bits, or more
50 /// than 64-bits of precision. APInt provides a variety of arithmetic operators
51 /// and methods to manipulate integer values of any bit-width. It supports both
52 /// the typical integer arithmetic and comparison operations as well as bitwise
55 /// The class has several invariants worth noting:
56 /// * All bit, byte, and word positions are zero-based.
57 /// * Once the bit width is set, it doesn't change except by the Truncate,
58 /// SignExtend, or ZeroExtend operations.
59 /// * All binary operators must be on APInt instances of the same bit width.
60 /// Attempting to use these operators on instances with different bit
61 /// widths will yield an assertion.
62 /// * The value is stored canonically as an unsigned value. For operations
63 /// where it makes a difference, there are both signed and unsigned variants
64 /// of the operation. For example, sdiv and udiv. However, because the bit
65 /// widths must be the same, operations such as Mul and Add produce the same
66 /// results regardless of whether the values are interpreted as signed or
68 /// * In general, the class tries to follow the style of computation that LLVM
69 /// uses in its IR. This simplifies its use for LLVM.
71 /// @brief Class for arbitrary precision integers.
73 unsigned BitWidth; ///< The number of bits in this APInt.
75 /// This union is used to store the integer value. When the
76 /// integer bit-width <= 64, it uses VAL, otherwise it uses pVal.
78 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
79 uint64_t *pVal; ///< Used to store the >64 bits integer value.
82 /// This enum is used to hold the constants we needed for APInt.
85 APINT_BITS_PER_WORD = static_cast<unsigned int>(sizeof(uint64_t)) *
87 /// Byte size of a word
88 APINT_WORD_SIZE = static_cast<unsigned int>(sizeof(uint64_t))
91 /// This constructor is used only internally for speed of construction of
92 /// temporaries. It is unsafe for general use so it is not public.
93 /// @brief Fast internal constructor
94 APInt(uint64_t* val, unsigned bits) : BitWidth(bits), pVal(val) { }
96 /// @returns true if the number of bits <= 64, false otherwise.
97 /// @brief Determine if this APInt just has one word to store value.
98 bool isSingleWord() const {
99 return BitWidth <= APINT_BITS_PER_WORD;
102 /// @returns the word position for the specified bit position.
103 /// @brief Determine which word a bit is in.
104 static unsigned whichWord(unsigned bitPosition) {
105 return bitPosition / APINT_BITS_PER_WORD;
108 /// @returns the bit position in a word for the specified bit position
110 /// @brief Determine which bit in a word a bit is in.
111 static unsigned whichBit(unsigned bitPosition) {
112 return bitPosition % APINT_BITS_PER_WORD;
115 /// This method generates and returns a uint64_t (word) mask for a single
116 /// bit at a specific bit position. This is used to mask the bit in the
117 /// corresponding word.
118 /// @returns a uint64_t with only bit at "whichBit(bitPosition)" set
119 /// @brief Get a single bit mask.
120 static uint64_t maskBit(unsigned bitPosition) {
121 return 1ULL << whichBit(bitPosition);
124 /// This method is used internally to clear the to "N" bits in the high order
125 /// word that are not used by the APInt. This is needed after the most
126 /// significant word is assigned a value to ensure that those bits are
128 /// @brief Clear unused high order bits
129 APInt& clearUnusedBits() {
130 // Compute how many bits are used in the final word
131 unsigned wordBits = BitWidth % APINT_BITS_PER_WORD;
133 // If all bits are used, we want to leave the value alone. This also
134 // avoids the undefined behavior of >> when the shift is the same size as
135 // the word size (64).
138 // Mask out the high bits.
139 uint64_t mask = ~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - wordBits);
143 pVal[getNumWords() - 1] &= mask;
147 /// @returns the corresponding word for the specified bit position.
148 /// @brief Get the word corresponding to a bit position
149 uint64_t getWord(unsigned bitPosition) const {
150 return isSingleWord() ? VAL : pVal[whichWord(bitPosition)];
153 /// This is used by the constructors that take string arguments.
154 /// @brief Convert a char array into an APInt
155 void fromString(unsigned numBits, const char *strStart, unsigned slen,
158 /// This is used by the toString method to divide by the radix. It simply
159 /// provides a more convenient form of divide for internal use since KnuthDiv
160 /// has specific constraints on its inputs. If those constraints are not met
161 /// then it provides a simpler form of divide.
162 /// @brief An internal division function for dividing APInts.
163 static void divide(const APInt LHS, unsigned lhsWords,
164 const APInt &RHS, unsigned rhsWords,
165 APInt *Quotient, APInt *Remainder);
167 /// out-of-line slow case for inline constructor
168 void initSlowCase(unsigned numBits, uint64_t val, bool isSigned);
170 /// out-of-line slow case for inline copy constructor
171 void initSlowCase(const APInt& that);
173 /// out-of-line slow case for shl
174 APInt shlSlowCase(unsigned shiftAmt) const;
176 /// out-of-line slow case for operator&
177 APInt AndSlowCase(const APInt& RHS) const;
179 /// out-of-line slow case for operator|
180 APInt OrSlowCase(const APInt& RHS) const;
182 /// out-of-line slow case for operator^
183 APInt XorSlowCase(const APInt& RHS) const;
185 /// out-of-line slow case for operator=
186 APInt& AssignSlowCase(const APInt& RHS);
188 /// out-of-line slow case for operator==
189 bool EqualSlowCase(const APInt& RHS) const;
191 /// out-of-line slow case for operator==
192 bool EqualSlowCase(uint64_t Val) const;
194 /// out-of-line slow case for countLeadingZeros
195 unsigned countLeadingZerosSlowCase() const;
197 /// out-of-line slow case for countTrailingOnes
198 unsigned countTrailingOnesSlowCase() const;
200 /// out-of-line slow case for countPopulation
201 unsigned countPopulationSlowCase() const;
204 /// @name Constructors
206 /// If isSigned is true then val is treated as if it were a signed value
207 /// (i.e. as an int64_t) and the appropriate sign extension to the bit width
208 /// will be done. Otherwise, no sign extension occurs (high order bits beyond
209 /// the range of val are zero filled).
210 /// @param numBits the bit width of the constructed APInt
211 /// @param val the initial value of the APInt
212 /// @param isSigned how to treat signedness of val
213 /// @brief Create a new APInt of numBits width, initialized as val.
214 APInt(unsigned numBits, uint64_t val, bool isSigned = false)
215 : BitWidth(numBits), VAL(0) {
216 assert(BitWidth && "bitwidth too small");
220 initSlowCase(numBits, val, isSigned);
224 /// Note that numWords can be smaller or larger than the corresponding bit
225 /// width but any extraneous bits will be dropped.
226 /// @param numBits the bit width of the constructed APInt
227 /// @param numWords the number of words in bigVal
228 /// @param bigVal a sequence of words to form the initial value of the APInt
229 /// @brief Construct an APInt of numBits width, initialized as bigVal[].
230 APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[]);
232 /// This constructor interprets the slen characters starting at StrStart as
233 /// a string in the given radix. The interpretation stops when the first
234 /// character that is not suitable for the radix is encountered. Acceptable
235 /// radix values are 2, 8, 10 and 16. It is an error for the value implied by
236 /// the string to require more bits than numBits.
237 /// @param numBits the bit width of the constructed APInt
238 /// @param strStart the start of the string to be interpreted
239 /// @param slen the maximum number of characters to interpret
240 /// @param radix the radix to use for the conversion
241 /// @brief Construct an APInt from a string representation.
242 APInt(unsigned numBits, const char strStart[], unsigned slen, uint8_t radix);
244 /// Simply makes *this a copy of that.
245 /// @brief Copy Constructor.
246 APInt(const APInt& that)
247 : BitWidth(that.BitWidth), VAL(0) {
248 assert(BitWidth && "bitwidth too small");
255 /// @brief Destructor.
261 /// Default constructor that creates an uninitialized APInt. This is useful
262 /// for object deserialization (pair this with the static method Read).
263 explicit APInt() : BitWidth(1) {}
265 /// Profile - Used to insert APInt objects, or objects that contain APInt
266 /// objects, into FoldingSets.
267 void Profile(FoldingSetNodeID& id) const;
269 /// @brief Used by the Bitcode serializer to emit APInts to Bitcode.
270 void Emit(Serializer& S) const;
272 /// @brief Used by the Bitcode deserializer to deserialize APInts.
273 void Read(Deserializer& D);
276 /// @name Value Tests
278 /// This tests the high bit of this APInt to determine if it is set.
279 /// @returns true if this APInt is negative, false otherwise
280 /// @brief Determine sign of this APInt.
281 bool isNegative() const {
282 return (*this)[BitWidth - 1];
285 /// This tests the high bit of the APInt to determine if it is unset.
286 /// @brief Determine if this APInt Value is non-negative (>= 0)
287 bool isNonNegative() const {
288 return !isNegative();
291 /// This tests if the value of this APInt is positive (> 0). Note
292 /// that 0 is not a positive value.
293 /// @returns true if this APInt is positive.
294 /// @brief Determine if this APInt Value is positive.
295 bool isStrictlyPositive() const {
296 return isNonNegative() && (*this) != 0;
299 /// This checks to see if the value has all bits of the APInt are set or not.
300 /// @brief Determine if all bits are set
301 bool isAllOnesValue() const {
302 return countPopulation() == BitWidth;
305 /// This checks to see if the value of this APInt is the maximum unsigned
306 /// value for the APInt's bit width.
307 /// @brief Determine if this is the largest unsigned value.
308 bool isMaxValue() const {
309 return countPopulation() == BitWidth;
312 /// This checks to see if the value of this APInt is the maximum signed
313 /// value for the APInt's bit width.
314 /// @brief Determine if this is the largest signed value.
315 bool isMaxSignedValue() const {
316 return BitWidth == 1 ? VAL == 0 :
317 !isNegative() && countPopulation() == BitWidth - 1;
320 /// This checks to see if the value of this APInt is the minimum unsigned
321 /// value for the APInt's bit width.
322 /// @brief Determine if this is the smallest unsigned value.
323 bool isMinValue() const {
324 return countPopulation() == 0;
327 /// This checks to see if the value of this APInt is the minimum signed
328 /// value for the APInt's bit width.
329 /// @brief Determine if this is the smallest signed value.
330 bool isMinSignedValue() const {
331 return BitWidth == 1 ? VAL == 1 :
332 isNegative() && countPopulation() == 1;
335 /// @brief Check if this APInt has an N-bits unsigned integer value.
336 bool isIntN(unsigned N) const {
337 assert(N && "N == 0 ???");
338 if (N >= getBitWidth())
342 return VAL == (VAL & (~0ULL >> (64 - N)));
343 APInt Tmp(N, getNumWords(), pVal);
344 Tmp.zext(getBitWidth());
345 return Tmp == (*this);
348 /// @brief Check if this APInt has an N-bits signed integer value.
349 bool isSignedIntN(unsigned N) const {
350 assert(N && "N == 0 ???");
351 return getMinSignedBits() <= N;
354 /// @returns true if the argument APInt value is a power of two > 0.
355 bool isPowerOf2() const;
357 /// isSignBit - Return true if this is the value returned by getSignBit.
358 bool isSignBit() const { return isMinSignedValue(); }
360 /// This converts the APInt to a boolean value as a test against zero.
361 /// @brief Boolean conversion function.
362 bool getBoolValue() const {
366 /// getLimitedValue - If this value is smaller than the specified limit,
367 /// return it, otherwise return the limit value. This causes the value
368 /// to saturate to the limit.
369 uint64_t getLimitedValue(uint64_t Limit = ~0ULL) const {
370 return (getActiveBits() > 64 || getZExtValue() > Limit) ?
371 Limit : getZExtValue();
375 /// @name Value Generators
377 /// @brief Gets maximum unsigned value of APInt for specific bit width.
378 static APInt getMaxValue(unsigned numBits) {
379 return APInt(numBits, 0).set();
382 /// @brief Gets maximum signed value of APInt for a specific bit width.
383 static APInt getSignedMaxValue(unsigned numBits) {
384 return APInt(numBits, 0).set().clear(numBits - 1);
387 /// @brief Gets minimum unsigned value of APInt for a specific bit width.
388 static APInt getMinValue(unsigned numBits) {
389 return APInt(numBits, 0);
392 /// @brief Gets minimum signed value of APInt for a specific bit width.
393 static APInt getSignedMinValue(unsigned numBits) {
394 return APInt(numBits, 0).set(numBits - 1);
397 /// getSignBit - This is just a wrapper function of getSignedMinValue(), and
398 /// it helps code readability when we want to get a SignBit.
399 /// @brief Get the SignBit for a specific bit width.
400 static APInt getSignBit(unsigned BitWidth) {
401 return getSignedMinValue(BitWidth);
404 /// @returns the all-ones value for an APInt of the specified bit-width.
405 /// @brief Get the all-ones value.
406 static APInt getAllOnesValue(unsigned numBits) {
407 return APInt(numBits, 0).set();
410 /// @returns the '0' value for an APInt of the specified bit-width.
411 /// @brief Get the '0' value.
412 static APInt getNullValue(unsigned numBits) {
413 return APInt(numBits, 0);
416 /// Get an APInt with the same BitWidth as this APInt, just zero mask
417 /// the low bits and right shift to the least significant bit.
418 /// @returns the high "numBits" bits of this APInt.
419 APInt getHiBits(unsigned numBits) const;
421 /// Get an APInt with the same BitWidth as this APInt, just zero mask
423 /// @returns the low "numBits" bits of this APInt.
424 APInt getLoBits(unsigned numBits) const;
426 /// Constructs an APInt value that has a contiguous range of bits set. The
427 /// bits from loBit (inclusive) to hiBit (exclusive) will be set. All other
428 /// bits will be zero. For example, with parameters(32, 0, 16) you would get
429 /// 0x0000FFFF. If hiBit is less than loBit then the set bits "wrap". For
430 /// example, with parameters (32, 28, 4), you would get 0xF000000F.
431 /// @param numBits the intended bit width of the result
432 /// @param loBit the index of the lowest bit set.
433 /// @param hiBit the index of the highest bit set.
434 /// @returns An APInt value with the requested bits set.
435 /// @brief Get a value with a block of bits set.
436 static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit) {
437 assert(hiBit <= numBits && "hiBit out of range");
438 assert(loBit < numBits && "loBit out of range");
440 return getLowBitsSet(numBits, hiBit) |
441 getHighBitsSet(numBits, numBits-loBit);
442 return getLowBitsSet(numBits, hiBit-loBit).shl(loBit);
445 /// Constructs an APInt value that has the top hiBitsSet bits set.
446 /// @param numBits the bitwidth of the result
447 /// @param hiBitsSet the number of high-order bits set in the result.
448 /// @brief Get a value with high bits set
449 static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet) {
450 assert(hiBitsSet <= numBits && "Too many bits to set!");
451 // Handle a degenerate case, to avoid shifting by word size
453 return APInt(numBits, 0);
454 unsigned shiftAmt = numBits - hiBitsSet;
455 // For small values, return quickly
456 if (numBits <= APINT_BITS_PER_WORD)
457 return APInt(numBits, ~0ULL << shiftAmt);
458 return (~APInt(numBits, 0)).shl(shiftAmt);
461 /// Constructs an APInt value that has the bottom loBitsSet bits set.
462 /// @param numBits the bitwidth of the result
463 /// @param loBitsSet the number of low-order bits set in the result.
464 /// @brief Get a value with low bits set
465 static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet) {
466 assert(loBitsSet <= numBits && "Too many bits to set!");
467 // Handle a degenerate case, to avoid shifting by word size
469 return APInt(numBits, 0);
470 if (loBitsSet == APINT_BITS_PER_WORD)
471 return APInt(numBits, -1ULL);
472 // For small values, return quickly.
473 if (numBits < APINT_BITS_PER_WORD)
474 return APInt(numBits, (1ULL << loBitsSet) - 1);
475 return (~APInt(numBits, 0)).lshr(numBits - loBitsSet);
478 /// The hash value is computed as the sum of the words and the bit width.
479 /// @returns A hash value computed from the sum of the APInt words.
480 /// @brief Get a hash value based on this APInt
481 uint64_t getHashValue() const;
483 /// This function returns a pointer to the internal storage of the APInt.
484 /// This is useful for writing out the APInt in binary form without any
486 const uint64_t* getRawData() const {
493 /// @name Unary Operators
495 /// @returns a new APInt value representing *this incremented by one
496 /// @brief Postfix increment operator.
497 const APInt operator++(int) {
503 /// @returns *this incremented by one
504 /// @brief Prefix increment operator.
507 /// @returns a new APInt representing *this decremented by one.
508 /// @brief Postfix decrement operator.
509 const APInt operator--(int) {
515 /// @returns *this decremented by one.
516 /// @brief Prefix decrement operator.
519 /// Performs a bitwise complement operation on this APInt.
520 /// @returns an APInt that is the bitwise complement of *this
521 /// @brief Unary bitwise complement operator.
522 APInt operator~() const {
528 /// Negates *this using two's complement logic.
529 /// @returns An APInt value representing the negation of *this.
530 /// @brief Unary negation operator
531 APInt operator-() const {
532 return APInt(BitWidth, 0) - (*this);
535 /// Performs logical negation operation on this APInt.
536 /// @returns true if *this is zero, false otherwise.
537 /// @brief Logical negation operator.
538 bool operator!() const;
541 /// @name Assignment Operators
543 /// @returns *this after assignment of RHS.
544 /// @brief Copy assignment operator.
545 APInt& operator=(const APInt& RHS) {
546 // If the bitwidths are the same, we can avoid mucking with memory
547 if (isSingleWord() && RHS.isSingleWord()) {
549 BitWidth = RHS.BitWidth;
550 return clearUnusedBits();
553 return AssignSlowCase(RHS);
556 /// The RHS value is assigned to *this. If the significant bits in RHS exceed
557 /// the bit width, the excess bits are truncated. If the bit width is larger
558 /// than 64, the value is zero filled in the unspecified high order bits.
559 /// @returns *this after assignment of RHS value.
560 /// @brief Assignment operator.
561 APInt& operator=(uint64_t RHS);
563 /// Performs a bitwise AND operation on this APInt and RHS. The result is
564 /// assigned to *this.
565 /// @returns *this after ANDing with RHS.
566 /// @brief Bitwise AND assignment operator.
567 APInt& operator&=(const APInt& RHS);
569 /// Performs a bitwise OR operation on this APInt and RHS. The result is
571 /// @returns *this after ORing with RHS.
572 /// @brief Bitwise OR assignment operator.
573 APInt& operator|=(const APInt& RHS);
575 /// Performs a bitwise XOR operation on this APInt and RHS. The result is
576 /// assigned to *this.
577 /// @returns *this after XORing with RHS.
578 /// @brief Bitwise XOR assignment operator.
579 APInt& operator^=(const APInt& RHS);
581 /// Multiplies this APInt by RHS and assigns the result to *this.
583 /// @brief Multiplication assignment operator.
584 APInt& operator*=(const APInt& RHS);
586 /// Adds RHS to *this and assigns the result to *this.
588 /// @brief Addition assignment operator.
589 APInt& operator+=(const APInt& RHS);
591 /// Subtracts RHS from *this and assigns the result to *this.
593 /// @brief Subtraction assignment operator.
594 APInt& operator-=(const APInt& RHS);
596 /// Shifts *this left by shiftAmt and assigns the result to *this.
597 /// @returns *this after shifting left by shiftAmt
598 /// @brief Left-shift assignment function.
599 APInt& operator<<=(unsigned shiftAmt) {
600 *this = shl(shiftAmt);
605 /// @name Binary Operators
607 /// Performs a bitwise AND operation on *this and RHS.
608 /// @returns An APInt value representing the bitwise AND of *this and RHS.
609 /// @brief Bitwise AND operator.
610 APInt operator&(const APInt& RHS) const {
611 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
613 return APInt(getBitWidth(), VAL & RHS.VAL);
614 return AndSlowCase(RHS);
616 APInt And(const APInt& RHS) const {
617 return this->operator&(RHS);
620 /// Performs a bitwise OR operation on *this and RHS.
621 /// @returns An APInt value representing the bitwise OR of *this and RHS.
622 /// @brief Bitwise OR operator.
623 APInt operator|(const APInt& RHS) const {
624 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
626 return APInt(getBitWidth(), VAL | RHS.VAL);
627 return OrSlowCase(RHS);
629 APInt Or(const APInt& RHS) const {
630 return this->operator|(RHS);
633 /// Performs a bitwise XOR operation on *this and RHS.
634 /// @returns An APInt value representing the bitwise XOR of *this and RHS.
635 /// @brief Bitwise XOR operator.
636 APInt operator^(const APInt& RHS) const {
637 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
639 return APInt(BitWidth, VAL ^ RHS.VAL);
640 return XorSlowCase(RHS);
642 APInt Xor(const APInt& RHS) const {
643 return this->operator^(RHS);
646 /// Multiplies this APInt by RHS and returns the result.
647 /// @brief Multiplication operator.
648 APInt operator*(const APInt& RHS) const;
650 /// Adds RHS to this APInt and returns the result.
651 /// @brief Addition operator.
652 APInt operator+(const APInt& RHS) const;
653 APInt operator+(uint64_t RHS) const {
654 return (*this) + APInt(BitWidth, RHS);
657 /// Subtracts RHS from this APInt and returns the result.
658 /// @brief Subtraction operator.
659 APInt operator-(const APInt& RHS) const;
660 APInt operator-(uint64_t RHS) const {
661 return (*this) - APInt(BitWidth, RHS);
664 APInt operator<<(unsigned Bits) const {
668 APInt operator<<(const APInt &Bits) const {
672 /// Arithmetic right-shift this APInt by shiftAmt.
673 /// @brief Arithmetic right-shift function.
674 APInt ashr(unsigned shiftAmt) const;
676 /// Logical right-shift this APInt by shiftAmt.
677 /// @brief Logical right-shift function.
678 APInt lshr(unsigned shiftAmt) const;
680 /// Left-shift this APInt by shiftAmt.
681 /// @brief Left-shift function.
682 APInt shl(unsigned shiftAmt) const {
683 assert(shiftAmt <= BitWidth && "Invalid shift amount");
684 if (isSingleWord()) {
685 if (shiftAmt == BitWidth)
686 return APInt(BitWidth, 0); // avoid undefined shift results
687 return APInt(BitWidth, VAL << shiftAmt);
689 return shlSlowCase(shiftAmt);
692 /// @brief Rotate left by rotateAmt.
693 APInt rotl(unsigned rotateAmt) const;
695 /// @brief Rotate right by rotateAmt.
696 APInt rotr(unsigned rotateAmt) const;
698 /// Arithmetic right-shift this APInt by shiftAmt.
699 /// @brief Arithmetic right-shift function.
700 APInt ashr(const APInt &shiftAmt) const;
702 /// Logical right-shift this APInt by shiftAmt.
703 /// @brief Logical right-shift function.
704 APInt lshr(const APInt &shiftAmt) const;
706 /// Left-shift this APInt by shiftAmt.
707 /// @brief Left-shift function.
708 APInt shl(const APInt &shiftAmt) const;
710 /// @brief Rotate left by rotateAmt.
711 APInt rotl(const APInt &rotateAmt) const;
713 /// @brief Rotate right by rotateAmt.
714 APInt rotr(const APInt &rotateAmt) const;
716 /// Perform an unsigned divide operation on this APInt by RHS. Both this and
717 /// RHS are treated as unsigned quantities for purposes of this division.
718 /// @returns a new APInt value containing the division result
719 /// @brief Unsigned division operation.
720 APInt udiv(const APInt& RHS) const;
722 /// Signed divide this APInt by APInt RHS.
723 /// @brief Signed division function for APInt.
724 APInt sdiv(const APInt& RHS) const {
726 if (RHS.isNegative())
727 return (-(*this)).udiv(-RHS);
729 return -((-(*this)).udiv(RHS));
730 else if (RHS.isNegative())
731 return -(this->udiv(-RHS));
732 return this->udiv(RHS);
735 /// Perform an unsigned remainder operation on this APInt with RHS being the
736 /// divisor. Both this and RHS are treated as unsigned quantities for purposes
737 /// of this operation. Note that this is a true remainder operation and not
738 /// a modulo operation because the sign follows the sign of the dividend
740 /// @returns a new APInt value containing the remainder result
741 /// @brief Unsigned remainder operation.
742 APInt urem(const APInt& RHS) const;
744 /// Signed remainder operation on APInt.
745 /// @brief Function for signed remainder operation.
746 APInt srem(const APInt& RHS) const {
748 if (RHS.isNegative())
749 return -((-(*this)).urem(-RHS));
751 return -((-(*this)).urem(RHS));
752 else if (RHS.isNegative())
753 return this->urem(-RHS);
754 return this->urem(RHS);
757 /// Sometimes it is convenient to divide two APInt values and obtain both the
758 /// quotient and remainder. This function does both operations in the same
759 /// computation making it a little more efficient. The pair of input arguments
760 /// may overlap with the pair of output arguments. It is safe to call
761 /// udivrem(X, Y, X, Y), for example.
762 /// @brief Dual division/remainder interface.
763 static void udivrem(const APInt &LHS, const APInt &RHS,
764 APInt &Quotient, APInt &Remainder);
766 static void sdivrem(const APInt &LHS, const APInt &RHS,
767 APInt &Quotient, APInt &Remainder)
769 if (LHS.isNegative()) {
770 if (RHS.isNegative())
771 APInt::udivrem(-LHS, -RHS, Quotient, Remainder);
773 APInt::udivrem(-LHS, RHS, Quotient, Remainder);
774 Quotient = -Quotient;
775 Remainder = -Remainder;
776 } else if (RHS.isNegative()) {
777 APInt::udivrem(LHS, -RHS, Quotient, Remainder);
778 Quotient = -Quotient;
780 APInt::udivrem(LHS, RHS, Quotient, Remainder);
784 /// @returns the bit value at bitPosition
785 /// @brief Array-indexing support.
786 bool operator[](unsigned bitPosition) const;
789 /// @name Comparison Operators
791 /// Compares this APInt with RHS for the validity of the equality
793 /// @brief Equality operator.
794 bool operator==(const APInt& RHS) const {
795 assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths");
797 return VAL == RHS.VAL;
798 return EqualSlowCase(RHS);
801 /// Compares this APInt with a uint64_t for the validity of the equality
803 /// @returns true if *this == Val
804 /// @brief Equality operator.
805 bool operator==(uint64_t Val) const {
808 return EqualSlowCase(Val);
811 /// Compares this APInt with RHS for the validity of the equality
813 /// @returns true if *this == Val
814 /// @brief Equality comparison.
815 bool eq(const APInt &RHS) const {
816 return (*this) == RHS;
819 /// Compares this APInt with RHS for the validity of the inequality
821 /// @returns true if *this != Val
822 /// @brief Inequality operator.
823 bool operator!=(const APInt& RHS) const {
824 return !((*this) == RHS);
827 /// Compares this APInt with a uint64_t for the validity of the inequality
829 /// @returns true if *this != Val
830 /// @brief Inequality operator.
831 bool operator!=(uint64_t Val) const {
832 return !((*this) == Val);
835 /// Compares this APInt with RHS for the validity of the inequality
837 /// @returns true if *this != Val
838 /// @brief Inequality comparison
839 bool ne(const APInt &RHS) const {
840 return !((*this) == RHS);
843 /// Regards both *this and RHS as unsigned quantities and compares them for
844 /// the validity of the less-than relationship.
845 /// @returns true if *this < RHS when both are considered unsigned.
846 /// @brief Unsigned less than comparison
847 bool ult(const APInt& RHS) const;
849 /// Regards both *this and RHS as signed quantities and compares them for
850 /// validity of the less-than relationship.
851 /// @returns true if *this < RHS when both are considered signed.
852 /// @brief Signed less than comparison
853 bool slt(const APInt& RHS) const;
855 /// Regards both *this and RHS as unsigned quantities and compares them for
856 /// validity of the less-or-equal relationship.
857 /// @returns true if *this <= RHS when both are considered unsigned.
858 /// @brief Unsigned less or equal comparison
859 bool ule(const APInt& RHS) const {
860 return ult(RHS) || eq(RHS);
863 /// Regards both *this and RHS as signed quantities and compares them for
864 /// validity of the less-or-equal relationship.
865 /// @returns true if *this <= RHS when both are considered signed.
866 /// @brief Signed less or equal comparison
867 bool sle(const APInt& RHS) const {
868 return slt(RHS) || eq(RHS);
871 /// Regards both *this and RHS as unsigned quantities and compares them for
872 /// the validity of the greater-than relationship.
873 /// @returns true if *this > RHS when both are considered unsigned.
874 /// @brief Unsigned greather than comparison
875 bool ugt(const APInt& RHS) const {
876 return !ult(RHS) && !eq(RHS);
879 /// Regards both *this and RHS as signed quantities and compares them for
880 /// the validity of the greater-than relationship.
881 /// @returns true if *this > RHS when both are considered signed.
882 /// @brief Signed greather than comparison
883 bool sgt(const APInt& RHS) const {
884 return !slt(RHS) && !eq(RHS);
887 /// Regards both *this and RHS as unsigned quantities and compares them for
888 /// validity of the greater-or-equal relationship.
889 /// @returns true if *this >= RHS when both are considered unsigned.
890 /// @brief Unsigned greater or equal comparison
891 bool uge(const APInt& RHS) const {
895 /// Regards both *this and RHS as signed quantities and compares them for
896 /// validity of the greater-or-equal relationship.
897 /// @returns true if *this >= RHS when both are considered signed.
898 /// @brief Signed greather or equal comparison
899 bool sge(const APInt& RHS) const {
903 /// This operation tests if there are any pairs of corresponding bits
904 /// between this APInt and RHS that are both set.
905 bool intersects(const APInt &RHS) const {
906 return (*this & RHS) != 0;
910 /// @name Resizing Operators
912 /// Truncate the APInt to a specified width. It is an error to specify a width
913 /// that is greater than or equal to the current width.
914 /// @brief Truncate to new width.
915 APInt &trunc(unsigned width);
917 /// This operation sign extends the APInt to a new width. If the high order
918 /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
919 /// It is an error to specify a width that is less than or equal to the
921 /// @brief Sign extend to a new width.
922 APInt &sext(unsigned width);
924 /// This operation zero extends the APInt to a new width. The high order bits
925 /// are filled with 0 bits. It is an error to specify a width that is less
926 /// than or equal to the current width.
927 /// @brief Zero extend to a new width.
928 APInt &zext(unsigned width);
930 /// Make this APInt have the bit width given by \p width. The value is sign
931 /// extended, truncated, or left alone to make it that width.
932 /// @brief Sign extend or truncate to width
933 APInt &sextOrTrunc(unsigned width);
935 /// Make this APInt have the bit width given by \p width. The value is zero
936 /// extended, truncated, or left alone to make it that width.
937 /// @brief Zero extend or truncate to width
938 APInt &zextOrTrunc(unsigned width);
941 /// @name Bit Manipulation Operators
943 /// @brief Set every bit to 1.
945 if (isSingleWord()) {
947 return clearUnusedBits();
950 // Set all the bits in all the words.
951 for (unsigned i = 0; i < getNumWords(); ++i)
953 // Clear the unused ones
954 return clearUnusedBits();
957 /// Set the given bit to 1 whose position is given as "bitPosition".
958 /// @brief Set a given bit to 1.
959 APInt& set(unsigned bitPosition);
961 /// @brief Set every bit to 0.
966 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
970 /// Set the given bit to 0 whose position is given as "bitPosition".
971 /// @brief Set a given bit to 0.
972 APInt& clear(unsigned bitPosition);
974 /// @brief Toggle every bit to its opposite value.
976 if (isSingleWord()) {
978 return clearUnusedBits();
980 for (unsigned i = 0; i < getNumWords(); ++i)
982 return clearUnusedBits();
985 /// Toggle a given bit to its opposite value whose position is given
986 /// as "bitPosition".
987 /// @brief Toggles a given bit to its opposite value.
988 APInt& flip(unsigned bitPosition);
991 /// @name Value Characterization Functions
994 /// @returns the total number of bits.
995 unsigned getBitWidth() const {
999 /// Here one word's bitwidth equals to that of uint64_t.
1000 /// @returns the number of words to hold the integer value of this APInt.
1001 /// @brief Get the number of words.
1002 unsigned getNumWords() const {
1003 return getNumWords(BitWidth);
1006 /// Here one word's bitwidth equals to that of uint64_t.
1007 /// @returns the number of words to hold the integer value with a
1008 /// given bit width.
1009 /// @brief Get the number of words.
1010 static unsigned getNumWords(unsigned BitWidth) {
1011 return (BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
1014 /// This function returns the number of active bits which is defined as the
1015 /// bit width minus the number of leading zeros. This is used in several
1016 /// computations to see how "wide" the value is.
1017 /// @brief Compute the number of active bits in the value
1018 unsigned getActiveBits() const {
1019 return BitWidth - countLeadingZeros();
1022 /// This function returns the number of active words in the value of this
1023 /// APInt. This is used in conjunction with getActiveData to extract the raw
1024 /// value of the APInt.
1025 unsigned getActiveWords() const {
1026 return whichWord(getActiveBits()-1) + 1;
1029 /// Computes the minimum bit width for this APInt while considering it to be
1030 /// a signed (and probably negative) value. If the value is not negative,
1031 /// this function returns the same value as getActiveBits()+1. Otherwise, it
1032 /// returns the smallest bit width that will retain the negative value. For
1033 /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
1034 /// for -1, this function will always return 1.
1035 /// @brief Get the minimum bit size for this signed APInt
1036 unsigned getMinSignedBits() const {
1038 return BitWidth - countLeadingOnes() + 1;
1039 return getActiveBits()+1;
1042 /// This method attempts to return the value of this APInt as a zero extended
1043 /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
1044 /// uint64_t. Otherwise an assertion will result.
1045 /// @brief Get zero extended value
1046 uint64_t getZExtValue() const {
1049 assert(getActiveBits() <= 64 && "Too many bits for uint64_t");
1053 /// This method attempts to return the value of this APInt as a sign extended
1054 /// int64_t. The bit width must be <= 64 or the value must fit within an
1055 /// int64_t. Otherwise an assertion will result.
1056 /// @brief Get sign extended value
1057 int64_t getSExtValue() const {
1059 return int64_t(VAL << (APINT_BITS_PER_WORD - BitWidth)) >>
1060 (APINT_BITS_PER_WORD - BitWidth);
1061 assert(getMinSignedBits() <= 64 && "Too many bits for int64_t");
1062 return int64_t(pVal[0]);
1065 /// This method determines how many bits are required to hold the APInt
1066 /// equivalent of the string given by \p str of length \p slen.
1067 /// @brief Get bits required for string value.
1068 static unsigned getBitsNeeded(const char* str, unsigned slen, uint8_t radix);
1070 /// countLeadingZeros - This function is an APInt version of the
1071 /// countLeadingZeros_{32,64} functions in MathExtras.h. It counts the number
1072 /// of zeros from the most significant bit to the first one bit.
1073 /// @returns BitWidth if the value is zero.
1074 /// @returns the number of zeros from the most significant bit to the first
1076 unsigned countLeadingZeros() const {
1077 if (isSingleWord()) {
1078 unsigned unusedBits = APINT_BITS_PER_WORD - BitWidth;
1079 return CountLeadingZeros_64(VAL) - unusedBits;
1081 return countLeadingZerosSlowCase();
1084 /// countLeadingOnes - This function is an APInt version of the
1085 /// countLeadingOnes_{32,64} functions in MathExtras.h. It counts the number
1086 /// of ones from the most significant bit to the first zero bit.
1087 /// @returns 0 if the high order bit is not set
1088 /// @returns the number of 1 bits from the most significant to the least
1089 /// @brief Count the number of leading one bits.
1090 unsigned countLeadingOnes() const;
1092 /// countTrailingZeros - This function is an APInt version of the
1093 /// countTrailingZeros_{32,64} functions in MathExtras.h. It counts
1094 /// the number of zeros from the least significant bit to the first set bit.
1095 /// @returns BitWidth if the value is zero.
1096 /// @returns the number of zeros from the least significant bit to the first
1098 /// @brief Count the number of trailing zero bits.
1099 unsigned countTrailingZeros() const;
1101 /// countTrailingOnes - This function is an APInt version of the
1102 /// countTrailingOnes_{32,64} functions in MathExtras.h. It counts
1103 /// the number of ones from the least significant bit to the first zero bit.
1104 /// @returns BitWidth if the value is all ones.
1105 /// @returns the number of ones from the least significant bit to the first
1107 /// @brief Count the number of trailing one bits.
1108 unsigned countTrailingOnes() const {
1110 return CountTrailingOnes_64(VAL);
1111 return countTrailingOnesSlowCase();
1114 /// countPopulation - This function is an APInt version of the
1115 /// countPopulation_{32,64} functions in MathExtras.h. It counts the number
1116 /// of 1 bits in the APInt value.
1117 /// @returns 0 if the value is zero.
1118 /// @returns the number of set bits.
1119 /// @brief Count the number of bits set.
1120 unsigned countPopulation() const {
1122 return CountPopulation_64(VAL);
1123 return countPopulationSlowCase();
1127 /// @name Conversion Functions
1129 void print(raw_ostream &OS, bool isSigned) const;
1131 /// toString - Converts an APInt to a string and append it to Str. Str is
1132 /// commonly a SmallString.
1133 void toString(SmallVectorImpl<char> &Str, unsigned Radix, bool Signed) const;
1135 /// Considers the APInt to be unsigned and converts it into a string in the
1136 /// radix given. The radix can be 2, 8, 10 or 16.
1137 void toStringUnsigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1138 toString(Str, Radix, false);
1141 /// Considers the APInt to be signed and converts it into a string in the
1142 /// radix given. The radix can be 2, 8, 10 or 16.
1143 void toStringSigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1144 toString(Str, Radix, true);
1147 /// toString - This returns the APInt as a std::string. Note that this is an
1148 /// inefficient method. It is better to pass in a SmallVector/SmallString
1149 /// to the methods above to avoid thrashing the heap for the string.
1150 std::string toString(unsigned Radix, bool Signed) const;
1153 /// @returns a byte-swapped representation of this APInt Value.
1154 APInt byteSwap() const;
1156 /// @brief Converts this APInt to a double value.
1157 double roundToDouble(bool isSigned) const;
1159 /// @brief Converts this unsigned APInt to a double value.
1160 double roundToDouble() const {
1161 return roundToDouble(false);
1164 /// @brief Converts this signed APInt to a double value.
1165 double signedRoundToDouble() const {
1166 return roundToDouble(true);
1169 /// The conversion does not do a translation from integer to double, it just
1170 /// re-interprets the bits as a double. Note that it is valid to do this on
1171 /// any bit width. Exactly 64 bits will be translated.
1172 /// @brief Converts APInt bits to a double
1173 double bitsToDouble() const {
1178 T.I = (isSingleWord() ? VAL : pVal[0]);
1182 /// The conversion does not do a translation from integer to float, it just
1183 /// re-interprets the bits as a float. Note that it is valid to do this on
1184 /// any bit width. Exactly 32 bits will be translated.
1185 /// @brief Converts APInt bits to a double
1186 float bitsToFloat() const {
1191 T.I = unsigned((isSingleWord() ? VAL : pVal[0]));
1195 /// The conversion does not do a translation from double to integer, it just
1196 /// re-interprets the bits of the double. Note that it is valid to do this on
1197 /// any bit width but bits from V may get truncated.
1198 /// @brief Converts a double to APInt bits.
1199 APInt& doubleToBits(double V) {
1209 return clearUnusedBits();
1212 /// The conversion does not do a translation from float to integer, it just
1213 /// re-interprets the bits of the float. Note that it is valid to do this on
1214 /// any bit width but bits from V may get truncated.
1215 /// @brief Converts a float to APInt bits.
1216 APInt& floatToBits(float V) {
1226 return clearUnusedBits();
1230 /// @name Mathematics Operations
1233 /// @returns the floor log base 2 of this APInt.
1234 unsigned logBase2() const {
1235 return BitWidth - 1 - countLeadingZeros();
1238 /// @returns the log base 2 of this APInt if its an exact power of two, -1
1240 int32_t exactLogBase2() const {
1246 /// @brief Compute the square root
1249 /// If *this is < 0 then return -(*this), otherwise *this;
1250 /// @brief Get the absolute value;
1257 /// @returns the multiplicative inverse for a given modulo.
1258 APInt multiplicativeInverse(const APInt& modulo) const;
1261 /// @name Support for division by constant
1264 /// Calculate the magic number for signed division by a constant.
1268 /// Calculate the magic number for unsigned division by a constant.
1273 /// @name Building-block Operations for APInt and APFloat
1276 // These building block operations operate on a representation of
1277 // arbitrary precision, two's-complement, bignum integer values.
1278 // They should be sufficient to implement APInt and APFloat bignum
1279 // requirements. Inputs are generally a pointer to the base of an
1280 // array of integer parts, representing an unsigned bignum, and a
1281 // count of how many parts there are.
1283 /// Sets the least significant part of a bignum to the input value,
1284 /// and zeroes out higher parts. */
1285 static void tcSet(integerPart *, integerPart, unsigned int);
1287 /// Assign one bignum to another.
1288 static void tcAssign(integerPart *, const integerPart *, unsigned int);
1290 /// Returns true if a bignum is zero, false otherwise.
1291 static bool tcIsZero(const integerPart *, unsigned int);
1293 /// Extract the given bit of a bignum; returns 0 or 1. Zero-based.
1294 static int tcExtractBit(const integerPart *, unsigned int bit);
1296 /// Copy the bit vector of width srcBITS from SRC, starting at bit
1297 /// srcLSB, to DST, of dstCOUNT parts, such that the bit srcLSB
1298 /// becomes the least significant bit of DST. All high bits above
1299 /// srcBITS in DST are zero-filled.
1300 static void tcExtract(integerPart *, unsigned int dstCount,
1301 const integerPart *,
1302 unsigned int srcBits, unsigned int srcLSB);
1304 /// Set the given bit of a bignum. Zero-based.
1305 static void tcSetBit(integerPart *, unsigned int bit);
1307 /// Returns the bit number of the least or most significant set bit
1308 /// of a number. If the input number has no bits set -1U is
1310 static unsigned int tcLSB(const integerPart *, unsigned int);
1311 static unsigned int tcMSB(const integerPart *parts, unsigned int n);
1313 /// Negate a bignum in-place.
1314 static void tcNegate(integerPart *, unsigned int);
1316 /// DST += RHS + CARRY where CARRY is zero or one. Returns the
1318 static integerPart tcAdd(integerPart *, const integerPart *,
1319 integerPart carry, unsigned);
1321 /// DST -= RHS + CARRY where CARRY is zero or one. Returns the
1323 static integerPart tcSubtract(integerPart *, const integerPart *,
1324 integerPart carry, unsigned);
1326 /// DST += SRC * MULTIPLIER + PART if add is true
1327 /// DST = SRC * MULTIPLIER + PART if add is false
1329 /// Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC
1330 /// they must start at the same point, i.e. DST == SRC.
1332 /// If DSTPARTS == SRC_PARTS + 1 no overflow occurs and zero is
1333 /// returned. Otherwise DST is filled with the least significant
1334 /// DSTPARTS parts of the result, and if all of the omitted higher
1335 /// parts were zero return zero, otherwise overflow occurred and
1337 static int tcMultiplyPart(integerPart *dst, const integerPart *src,
1338 integerPart multiplier, integerPart carry,
1339 unsigned int srcParts, unsigned int dstParts,
1342 /// DST = LHS * RHS, where DST has the same width as the operands
1343 /// and is filled with the least significant parts of the result.
1344 /// Returns one if overflow occurred, otherwise zero. DST must be
1345 /// disjoint from both operands.
1346 static int tcMultiply(integerPart *, const integerPart *,
1347 const integerPart *, unsigned);
1349 /// DST = LHS * RHS, where DST has width the sum of the widths of
1350 /// the operands. No overflow occurs. DST must be disjoint from
1351 /// both operands. Returns the number of parts required to hold the
1353 static unsigned int tcFullMultiply(integerPart *, const integerPart *,
1354 const integerPart *, unsigned, unsigned);
1356 /// If RHS is zero LHS and REMAINDER are left unchanged, return one.
1357 /// Otherwise set LHS to LHS / RHS with the fractional part
1358 /// discarded, set REMAINDER to the remainder, return zero. i.e.
1360 /// OLD_LHS = RHS * LHS + REMAINDER
1362 /// SCRATCH is a bignum of the same size as the operands and result
1363 /// for use by the routine; its contents need not be initialized
1364 /// and are destroyed. LHS, REMAINDER and SCRATCH must be
1366 static int tcDivide(integerPart *lhs, const integerPart *rhs,
1367 integerPart *remainder, integerPart *scratch,
1368 unsigned int parts);
1370 /// Shift a bignum left COUNT bits. Shifted in bits are zero.
1371 /// There are no restrictions on COUNT.
1372 static void tcShiftLeft(integerPart *, unsigned int parts,
1373 unsigned int count);
1375 /// Shift a bignum right COUNT bits. Shifted in bits are zero.
1376 /// There are no restrictions on COUNT.
1377 static void tcShiftRight(integerPart *, unsigned int parts,
1378 unsigned int count);
1380 /// The obvious AND, OR and XOR and complement operations.
1381 static void tcAnd(integerPart *, const integerPart *, unsigned int);
1382 static void tcOr(integerPart *, const integerPart *, unsigned int);
1383 static void tcXor(integerPart *, const integerPart *, unsigned int);
1384 static void tcComplement(integerPart *, unsigned int);
1386 /// Comparison (unsigned) of two bignums.
1387 static int tcCompare(const integerPart *, const integerPart *,
1390 /// Increment a bignum in-place. Return the carry flag.
1391 static integerPart tcIncrement(integerPart *, unsigned int);
1393 /// Set the least significant BITS and clear the rest.
1394 static void tcSetLeastSignificantBits(integerPart *, unsigned int,
1397 /// @brief debug method
1403 /// Magic data for optimising signed division by a constant.
1405 APInt m; ///< magic number
1406 unsigned s; ///< shift amount
1409 /// Magic data for optimising unsigned division by a constant.
1411 APInt m; ///< magic number
1412 bool a; ///< add indicator
1413 unsigned s; ///< shift amount
1416 inline bool operator==(uint64_t V1, const APInt& V2) {
1420 inline bool operator!=(uint64_t V1, const APInt& V2) {
1424 inline raw_ostream &operator<<(raw_ostream &OS, const APInt &I) {
1429 std::ostream &operator<<(std::ostream &o, const APInt &I);
1431 namespace APIntOps {
1433 /// @brief Determine the smaller of two APInts considered to be signed.
1434 inline APInt smin(const APInt &A, const APInt &B) {
1435 return A.slt(B) ? A : B;
1438 /// @brief Determine the larger of two APInts considered to be signed.
1439 inline APInt smax(const APInt &A, const APInt &B) {
1440 return A.sgt(B) ? A : B;
1443 /// @brief Determine the smaller of two APInts considered to be signed.
1444 inline APInt umin(const APInt &A, const APInt &B) {
1445 return A.ult(B) ? A : B;
1448 /// @brief Determine the larger of two APInts considered to be unsigned.
1449 inline APInt umax(const APInt &A, const APInt &B) {
1450 return A.ugt(B) ? A : B;
1453 /// @brief Check if the specified APInt has a N-bits unsigned integer value.
1454 inline bool isIntN(unsigned N, const APInt& APIVal) {
1455 return APIVal.isIntN(N);
1458 /// @brief Check if the specified APInt has a N-bits signed integer value.
1459 inline bool isSignedIntN(unsigned N, const APInt& APIVal) {
1460 return APIVal.isSignedIntN(N);
1463 /// @returns true if the argument APInt value is a sequence of ones
1464 /// starting at the least significant bit with the remainder zero.
1465 inline bool isMask(unsigned numBits, const APInt& APIVal) {
1466 return numBits <= APIVal.getBitWidth() &&
1467 APIVal == APInt::getLowBitsSet(APIVal.getBitWidth(), numBits);
1470 /// @returns true if the argument APInt value contains a sequence of ones
1471 /// with the remainder zero.
1472 inline bool isShiftedMask(unsigned numBits, const APInt& APIVal) {
1473 return isMask(numBits, (APIVal - APInt(numBits,1)) | APIVal);
1476 /// @returns a byte-swapped representation of the specified APInt Value.
1477 inline APInt byteSwap(const APInt& APIVal) {
1478 return APIVal.byteSwap();
1481 /// @returns the floor log base 2 of the specified APInt value.
1482 inline unsigned logBase2(const APInt& APIVal) {
1483 return APIVal.logBase2();
1486 /// GreatestCommonDivisor - This function returns the greatest common
1487 /// divisor of the two APInt values using Euclid's algorithm.
1488 /// @returns the greatest common divisor of Val1 and Val2
1489 /// @brief Compute GCD of two APInt values.
1490 APInt GreatestCommonDivisor(const APInt& Val1, const APInt& Val2);
1492 /// Treats the APInt as an unsigned value for conversion purposes.
1493 /// @brief Converts the given APInt to a double value.
1494 inline double RoundAPIntToDouble(const APInt& APIVal) {
1495 return APIVal.roundToDouble();
1498 /// Treats the APInt as a signed value for conversion purposes.
1499 /// @brief Converts the given APInt to a double value.
1500 inline double RoundSignedAPIntToDouble(const APInt& APIVal) {
1501 return APIVal.signedRoundToDouble();
1504 /// @brief Converts the given APInt to a float vlalue.
1505 inline float RoundAPIntToFloat(const APInt& APIVal) {
1506 return float(RoundAPIntToDouble(APIVal));
1509 /// Treast the APInt as a signed value for conversion purposes.
1510 /// @brief Converts the given APInt to a float value.
1511 inline float RoundSignedAPIntToFloat(const APInt& APIVal) {
1512 return float(APIVal.signedRoundToDouble());
1515 /// RoundDoubleToAPInt - This function convert a double value to an APInt value.
1516 /// @brief Converts the given double value into a APInt.
1517 APInt RoundDoubleToAPInt(double Double, unsigned width);
1519 /// RoundFloatToAPInt - Converts a float value into an APInt value.
1520 /// @brief Converts a float value into a APInt.
1521 inline APInt RoundFloatToAPInt(float Float, unsigned width) {
1522 return RoundDoubleToAPInt(double(Float), width);
1525 /// Arithmetic right-shift the APInt by shiftAmt.
1526 /// @brief Arithmetic right-shift function.
1527 inline APInt ashr(const APInt& LHS, unsigned shiftAmt) {
1528 return LHS.ashr(shiftAmt);
1531 /// Logical right-shift the APInt by shiftAmt.
1532 /// @brief Logical right-shift function.
1533 inline APInt lshr(const APInt& LHS, unsigned shiftAmt) {
1534 return LHS.lshr(shiftAmt);
1537 /// Left-shift the APInt by shiftAmt.
1538 /// @brief Left-shift function.
1539 inline APInt shl(const APInt& LHS, unsigned shiftAmt) {
1540 return LHS.shl(shiftAmt);
1543 /// Signed divide APInt LHS by APInt RHS.
1544 /// @brief Signed division function for APInt.
1545 inline APInt sdiv(const APInt& LHS, const APInt& RHS) {
1546 return LHS.sdiv(RHS);
1549 /// Unsigned divide APInt LHS by APInt RHS.
1550 /// @brief Unsigned division function for APInt.
1551 inline APInt udiv(const APInt& LHS, const APInt& RHS) {
1552 return LHS.udiv(RHS);
1555 /// Signed remainder operation on APInt.
1556 /// @brief Function for signed remainder operation.
1557 inline APInt srem(const APInt& LHS, const APInt& RHS) {
1558 return LHS.srem(RHS);
1561 /// Unsigned remainder operation on APInt.
1562 /// @brief Function for unsigned remainder operation.
1563 inline APInt urem(const APInt& LHS, const APInt& RHS) {
1564 return LHS.urem(RHS);
1567 /// Performs multiplication on APInt values.
1568 /// @brief Function for multiplication operation.
1569 inline APInt mul(const APInt& LHS, const APInt& RHS) {
1573 /// Performs addition on APInt values.
1574 /// @brief Function for addition operation.
1575 inline APInt add(const APInt& LHS, const APInt& RHS) {
1579 /// Performs subtraction on APInt values.
1580 /// @brief Function for subtraction operation.
1581 inline APInt sub(const APInt& LHS, const APInt& RHS) {
1585 /// Performs bitwise AND operation on APInt LHS and
1587 /// @brief Bitwise AND function for APInt.
1588 inline APInt And(const APInt& LHS, const APInt& RHS) {
1592 /// Performs bitwise OR operation on APInt LHS and APInt RHS.
1593 /// @brief Bitwise OR function for APInt.
1594 inline APInt Or(const APInt& LHS, const APInt& RHS) {
1598 /// Performs bitwise XOR operation on APInt.
1599 /// @brief Bitwise XOR function for APInt.
1600 inline APInt Xor(const APInt& LHS, const APInt& RHS) {
1604 /// Performs a bitwise complement operation on APInt.
1605 /// @brief Bitwise complement function.
1606 inline APInt Not(const APInt& APIVal) {
1610 } // End of APIntOps namespace
1612 } // End of llvm namespace