[Alignment][NFC] Use Align with TargetLowering::setMinFunctionAlignment
[llvm-core.git] / include / llvm / ADT / APInt.h
blob987ca636cef7d6a57197d91ad2216bb59d2b55ed
1 //===-- llvm/ADT/APInt.h - For Arbitrary Precision Integer -----*- C++ -*--===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// This file implements a class to represent arbitrary precision
11 /// integral constant values and operations on them.
12 ///
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_ADT_APINT_H
16 #define LLVM_ADT_APINT_H
18 #include "llvm/Support/Compiler.h"
19 #include "llvm/Support/MathExtras.h"
20 #include <cassert>
21 #include <climits>
22 #include <cstring>
23 #include <string>
25 namespace llvm {
26 class FoldingSetNodeID;
27 class StringRef;
28 class hash_code;
29 class raw_ostream;
31 template <typename T> class SmallVectorImpl;
32 template <typename T> class ArrayRef;
33 template <typename T> class Optional;
35 class APInt;
37 inline APInt operator-(APInt);
39 //===----------------------------------------------------------------------===//
40 // APInt Class
41 //===----------------------------------------------------------------------===//
43 /// Class for arbitrary precision integers.
44 ///
45 /// APInt is a functional replacement for common case unsigned integer type like
46 /// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width
47 /// integer sizes and large integer value types such as 3-bits, 15-bits, or more
48 /// than 64-bits of precision. APInt provides a variety of arithmetic operators
49 /// and methods to manipulate integer values of any bit-width. It supports both
50 /// the typical integer arithmetic and comparison operations as well as bitwise
51 /// manipulation.
52 ///
53 /// The class has several invariants worth noting:
54 /// * All bit, byte, and word positions are zero-based.
55 /// * Once the bit width is set, it doesn't change except by the Truncate,
56 /// SignExtend, or ZeroExtend operations.
57 /// * All binary operators must be on APInt instances of the same bit width.
58 /// Attempting to use these operators on instances with different bit
59 /// widths will yield an assertion.
60 /// * The value is stored canonically as an unsigned value. For operations
61 /// where it makes a difference, there are both signed and unsigned variants
62 /// of the operation. For example, sdiv and udiv. However, because the bit
63 /// widths must be the same, operations such as Mul and Add produce the same
64 /// results regardless of whether the values are interpreted as signed or
65 /// not.
66 /// * In general, the class tries to follow the style of computation that LLVM
67 /// uses in its IR. This simplifies its use for LLVM.
68 ///
69 class LLVM_NODISCARD APInt {
70 public:
71 typedef uint64_t WordType;
73 /// This enum is used to hold the constants we needed for APInt.
74 enum : unsigned {
75 /// Byte size of a word.
76 APINT_WORD_SIZE = sizeof(WordType),
77 /// Bits in a word.
78 APINT_BITS_PER_WORD = APINT_WORD_SIZE * CHAR_BIT
81 enum class Rounding {
82 DOWN,
83 TOWARD_ZERO,
84 UP,
87 static const WordType WORDTYPE_MAX = ~WordType(0);
89 private:
90 /// This union is used to store the integer value. When the
91 /// integer bit-width <= 64, it uses VAL, otherwise it uses pVal.
92 union {
93 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
94 uint64_t *pVal; ///< Used to store the >64 bits integer value.
95 } U;
97 unsigned BitWidth; ///< The number of bits in this APInt.
99 friend struct DenseMapAPIntKeyInfo;
101 friend class APSInt;
103 /// Fast internal constructor
105 /// This constructor is used only internally for speed of construction of
106 /// temporaries. It is unsafe for general use so it is not public.
107 APInt(uint64_t *val, unsigned bits) : BitWidth(bits) {
108 U.pVal = val;
111 /// Determine if this APInt just has one word to store value.
113 /// \returns true if the number of bits <= 64, false otherwise.
114 bool isSingleWord() const { return BitWidth <= APINT_BITS_PER_WORD; }
116 /// Determine which word a bit is in.
118 /// \returns the word position for the specified bit position.
119 static unsigned whichWord(unsigned bitPosition) {
120 return bitPosition / APINT_BITS_PER_WORD;
123 /// Determine which bit in a word a bit is in.
125 /// \returns the bit position in a word for the specified bit position
126 /// in the APInt.
127 static unsigned whichBit(unsigned bitPosition) {
128 return bitPosition % APINT_BITS_PER_WORD;
131 /// Get a single bit mask.
133 /// \returns a uint64_t with only bit at "whichBit(bitPosition)" set
134 /// This method generates and returns a uint64_t (word) mask for a single
135 /// bit at a specific bit position. This is used to mask the bit in the
136 /// corresponding word.
137 static uint64_t maskBit(unsigned bitPosition) {
138 return 1ULL << whichBit(bitPosition);
141 /// Clear unused high order bits
143 /// This method is used internally to clear the top "N" bits in the high order
144 /// word that are not used by the APInt. This is needed after the most
145 /// significant word is assigned a value to ensure that those bits are
146 /// zero'd out.
147 APInt &clearUnusedBits() {
148 // Compute how many bits are used in the final word
149 unsigned WordBits = ((BitWidth-1) % APINT_BITS_PER_WORD) + 1;
151 // Mask out the high bits.
152 uint64_t mask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - WordBits);
153 if (isSingleWord())
154 U.VAL &= mask;
155 else
156 U.pVal[getNumWords() - 1] &= mask;
157 return *this;
160 /// Get the word corresponding to a bit position
161 /// \returns the corresponding word for the specified bit position.
162 uint64_t getWord(unsigned bitPosition) const {
163 return isSingleWord() ? U.VAL : U.pVal[whichWord(bitPosition)];
166 /// Utility method to change the bit width of this APInt to new bit width,
167 /// allocating and/or deallocating as necessary. There is no guarantee on the
168 /// value of any bits upon return. Caller should populate the bits after.
169 void reallocate(unsigned NewBitWidth);
171 /// Convert a char array into an APInt
173 /// \param radix 2, 8, 10, 16, or 36
174 /// Converts a string into a number. The string must be non-empty
175 /// and well-formed as a number of the given base. The bit-width
176 /// must be sufficient to hold the result.
178 /// This is used by the constructors that take string arguments.
180 /// StringRef::getAsInteger is superficially similar but (1) does
181 /// not assume that the string is well-formed and (2) grows the
182 /// result to hold the input.
183 void fromString(unsigned numBits, StringRef str, uint8_t radix);
185 /// An internal division function for dividing APInts.
187 /// This is used by the toString method to divide by the radix. It simply
188 /// provides a more convenient form of divide for internal use since KnuthDiv
189 /// has specific constraints on its inputs. If those constraints are not met
190 /// then it provides a simpler form of divide.
191 static void divide(const WordType *LHS, unsigned lhsWords,
192 const WordType *RHS, unsigned rhsWords, WordType *Quotient,
193 WordType *Remainder);
195 /// out-of-line slow case for inline constructor
196 void initSlowCase(uint64_t val, bool isSigned);
198 /// shared code between two array constructors
199 void initFromArray(ArrayRef<uint64_t> array);
201 /// out-of-line slow case for inline copy constructor
202 void initSlowCase(const APInt &that);
204 /// out-of-line slow case for shl
205 void shlSlowCase(unsigned ShiftAmt);
207 /// out-of-line slow case for lshr.
208 void lshrSlowCase(unsigned ShiftAmt);
210 /// out-of-line slow case for ashr.
211 void ashrSlowCase(unsigned ShiftAmt);
213 /// out-of-line slow case for operator=
214 void AssignSlowCase(const APInt &RHS);
216 /// out-of-line slow case for operator==
217 bool EqualSlowCase(const APInt &RHS) const LLVM_READONLY;
219 /// out-of-line slow case for countLeadingZeros
220 unsigned countLeadingZerosSlowCase() const LLVM_READONLY;
222 /// out-of-line slow case for countLeadingOnes.
223 unsigned countLeadingOnesSlowCase() const LLVM_READONLY;
225 /// out-of-line slow case for countTrailingZeros.
226 unsigned countTrailingZerosSlowCase() const LLVM_READONLY;
228 /// out-of-line slow case for countTrailingOnes
229 unsigned countTrailingOnesSlowCase() const LLVM_READONLY;
231 /// out-of-line slow case for countPopulation
232 unsigned countPopulationSlowCase() const LLVM_READONLY;
234 /// out-of-line slow case for intersects.
235 bool intersectsSlowCase(const APInt &RHS) const LLVM_READONLY;
237 /// out-of-line slow case for isSubsetOf.
238 bool isSubsetOfSlowCase(const APInt &RHS) const LLVM_READONLY;
240 /// out-of-line slow case for setBits.
241 void setBitsSlowCase(unsigned loBit, unsigned hiBit);
243 /// out-of-line slow case for flipAllBits.
244 void flipAllBitsSlowCase();
246 /// out-of-line slow case for operator&=.
247 void AndAssignSlowCase(const APInt& RHS);
249 /// out-of-line slow case for operator|=.
250 void OrAssignSlowCase(const APInt& RHS);
252 /// out-of-line slow case for operator^=.
253 void XorAssignSlowCase(const APInt& RHS);
255 /// Unsigned comparison. Returns -1, 0, or 1 if this APInt is less than, equal
256 /// to, or greater than RHS.
257 int compare(const APInt &RHS) const LLVM_READONLY;
259 /// Signed comparison. Returns -1, 0, or 1 if this APInt is less than, equal
260 /// to, or greater than RHS.
261 int compareSigned(const APInt &RHS) const LLVM_READONLY;
263 public:
264 /// \name Constructors
265 /// @{
267 /// Create a new APInt of numBits width, initialized as val.
269 /// If isSigned is true then val is treated as if it were a signed value
270 /// (i.e. as an int64_t) and the appropriate sign extension to the bit width
271 /// will be done. Otherwise, no sign extension occurs (high order bits beyond
272 /// the range of val are zero filled).
274 /// \param numBits the bit width of the constructed APInt
275 /// \param val the initial value of the APInt
276 /// \param isSigned how to treat signedness of val
277 APInt(unsigned numBits, uint64_t val, bool isSigned = false)
278 : BitWidth(numBits) {
279 assert(BitWidth && "bitwidth too small");
280 if (isSingleWord()) {
281 U.VAL = val;
282 clearUnusedBits();
283 } else {
284 initSlowCase(val, isSigned);
288 /// Construct an APInt of numBits width, initialized as bigVal[].
290 /// Note that bigVal.size() can be smaller or larger than the corresponding
291 /// bit width but any extraneous bits will be dropped.
293 /// \param numBits the bit width of the constructed APInt
294 /// \param bigVal a sequence of words to form the initial value of the APInt
295 APInt(unsigned numBits, ArrayRef<uint64_t> bigVal);
297 /// Equivalent to APInt(numBits, ArrayRef<uint64_t>(bigVal, numWords)), but
298 /// deprecated because this constructor is prone to ambiguity with the
299 /// APInt(unsigned, uint64_t, bool) constructor.
301 /// If this overload is ever deleted, care should be taken to prevent calls
302 /// from being incorrectly captured by the APInt(unsigned, uint64_t, bool)
303 /// constructor.
304 APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[]);
306 /// Construct an APInt from a string representation.
308 /// This constructor interprets the string \p str in the given radix. The
309 /// interpretation stops when the first character that is not suitable for the
310 /// radix is encountered, or the end of the string. Acceptable radix values
311 /// are 2, 8, 10, 16, and 36. It is an error for the value implied by the
312 /// string to require more bits than numBits.
314 /// \param numBits the bit width of the constructed APInt
315 /// \param str the string to be interpreted
316 /// \param radix the radix to use for the conversion
317 APInt(unsigned numBits, StringRef str, uint8_t radix);
319 /// Simply makes *this a copy of that.
320 /// Copy Constructor.
321 APInt(const APInt &that) : BitWidth(that.BitWidth) {
322 if (isSingleWord())
323 U.VAL = that.U.VAL;
324 else
325 initSlowCase(that);
328 /// Move Constructor.
329 APInt(APInt &&that) : BitWidth(that.BitWidth) {
330 memcpy(&U, &that.U, sizeof(U));
331 that.BitWidth = 0;
334 /// Destructor.
335 ~APInt() {
336 if (needsCleanup())
337 delete[] U.pVal;
340 /// Default constructor that creates an uninteresting APInt
341 /// representing a 1-bit zero value.
343 /// This is useful for object deserialization (pair this with the static
344 /// method Read).
345 explicit APInt() : BitWidth(1) { U.VAL = 0; }
347 /// Returns whether this instance allocated memory.
348 bool needsCleanup() const { return !isSingleWord(); }
350 /// Used to insert APInt objects, or objects that contain APInt objects, into
351 /// FoldingSets.
352 void Profile(FoldingSetNodeID &id) const;
354 /// @}
355 /// \name Value Tests
356 /// @{
358 /// Determine sign of this APInt.
360 /// This tests the high bit of this APInt to determine if it is set.
362 /// \returns true if this APInt is negative, false otherwise
363 bool isNegative() const { return (*this)[BitWidth - 1]; }
365 /// Determine if this APInt Value is non-negative (>= 0)
367 /// This tests the high bit of the APInt to determine if it is unset.
368 bool isNonNegative() const { return !isNegative(); }
370 /// Determine if sign bit of this APInt is set.
372 /// This tests the high bit of this APInt to determine if it is set.
374 /// \returns true if this APInt has its sign bit set, false otherwise.
375 bool isSignBitSet() const { return (*this)[BitWidth-1]; }
377 /// Determine if sign bit of this APInt is clear.
379 /// This tests the high bit of this APInt to determine if it is clear.
381 /// \returns true if this APInt has its sign bit clear, false otherwise.
382 bool isSignBitClear() const { return !isSignBitSet(); }
384 /// Determine if this APInt Value is positive.
386 /// This tests if the value of this APInt is positive (> 0). Note
387 /// that 0 is not a positive value.
389 /// \returns true if this APInt is positive.
390 bool isStrictlyPositive() const { return isNonNegative() && !isNullValue(); }
392 /// Determine if all bits are set
394 /// This checks to see if the value has all bits of the APInt are set or not.
395 bool isAllOnesValue() const {
396 if (isSingleWord())
397 return U.VAL == WORDTYPE_MAX >> (APINT_BITS_PER_WORD - BitWidth);
398 return countTrailingOnesSlowCase() == BitWidth;
401 /// Determine if all bits are clear
403 /// This checks to see if the value has all bits of the APInt are clear or
404 /// not.
405 bool isNullValue() const { return !*this; }
407 /// Determine if this is a value of 1.
409 /// This checks to see if the value of this APInt is one.
410 bool isOneValue() const {
411 if (isSingleWord())
412 return U.VAL == 1;
413 return countLeadingZerosSlowCase() == BitWidth - 1;
416 /// Determine if this is the largest unsigned value.
418 /// This checks to see if the value of this APInt is the maximum unsigned
419 /// value for the APInt's bit width.
420 bool isMaxValue() const { return isAllOnesValue(); }
422 /// Determine if this is the largest signed value.
424 /// This checks to see if the value of this APInt is the maximum signed
425 /// value for the APInt's bit width.
426 bool isMaxSignedValue() const {
427 if (isSingleWord())
428 return U.VAL == ((WordType(1) << (BitWidth - 1)) - 1);
429 return !isNegative() && countTrailingOnesSlowCase() == BitWidth - 1;
432 /// Determine if this is the smallest unsigned value.
434 /// This checks to see if the value of this APInt is the minimum unsigned
435 /// value for the APInt's bit width.
436 bool isMinValue() const { return isNullValue(); }
438 /// Determine if this is the smallest signed value.
440 /// This checks to see if the value of this APInt is the minimum signed
441 /// value for the APInt's bit width.
442 bool isMinSignedValue() const {
443 if (isSingleWord())
444 return U.VAL == (WordType(1) << (BitWidth - 1));
445 return isNegative() && countTrailingZerosSlowCase() == BitWidth - 1;
448 /// Check if this APInt has an N-bits unsigned integer value.
449 bool isIntN(unsigned N) const {
450 assert(N && "N == 0 ???");
451 return getActiveBits() <= N;
454 /// Check if this APInt has an N-bits signed integer value.
455 bool isSignedIntN(unsigned N) const {
456 assert(N && "N == 0 ???");
457 return getMinSignedBits() <= N;
460 /// Check if this APInt's value is a power of two greater than zero.
462 /// \returns true if the argument APInt value is a power of two > 0.
463 bool isPowerOf2() const {
464 if (isSingleWord())
465 return isPowerOf2_64(U.VAL);
466 return countPopulationSlowCase() == 1;
469 /// Check if the APInt's value is returned by getSignMask.
471 /// \returns true if this is the value returned by getSignMask.
472 bool isSignMask() const { return isMinSignedValue(); }
474 /// Convert APInt to a boolean value.
476 /// This converts the APInt to a boolean value as a test against zero.
477 bool getBoolValue() const { return !!*this; }
479 /// If this value is smaller than the specified limit, return it, otherwise
480 /// return the limit value. This causes the value to saturate to the limit.
481 uint64_t getLimitedValue(uint64_t Limit = UINT64_MAX) const {
482 return ugt(Limit) ? Limit : getZExtValue();
485 /// Check if the APInt consists of a repeated bit pattern.
487 /// e.g. 0x01010101 satisfies isSplat(8).
488 /// \param SplatSizeInBits The size of the pattern in bits. Must divide bit
489 /// width without remainder.
490 bool isSplat(unsigned SplatSizeInBits) const;
492 /// \returns true if this APInt value is a sequence of \param numBits ones
493 /// starting at the least significant bit with the remainder zero.
494 bool isMask(unsigned numBits) const {
495 assert(numBits != 0 && "numBits must be non-zero");
496 assert(numBits <= BitWidth && "numBits out of range");
497 if (isSingleWord())
498 return U.VAL == (WORDTYPE_MAX >> (APINT_BITS_PER_WORD - numBits));
499 unsigned Ones = countTrailingOnesSlowCase();
500 return (numBits == Ones) &&
501 ((Ones + countLeadingZerosSlowCase()) == BitWidth);
504 /// \returns true if this APInt is a non-empty sequence of ones starting at
505 /// the least significant bit with the remainder zero.
506 /// Ex. isMask(0x0000FFFFU) == true.
507 bool isMask() const {
508 if (isSingleWord())
509 return isMask_64(U.VAL);
510 unsigned Ones = countTrailingOnesSlowCase();
511 return (Ones > 0) && ((Ones + countLeadingZerosSlowCase()) == BitWidth);
514 /// Return true if this APInt value contains a sequence of ones with
515 /// the remainder zero.
516 bool isShiftedMask() const {
517 if (isSingleWord())
518 return isShiftedMask_64(U.VAL);
519 unsigned Ones = countPopulationSlowCase();
520 unsigned LeadZ = countLeadingZerosSlowCase();
521 return (Ones + LeadZ + countTrailingZeros()) == BitWidth;
524 /// @}
525 /// \name Value Generators
526 /// @{
528 /// Gets maximum unsigned value of APInt for specific bit width.
529 static APInt getMaxValue(unsigned numBits) {
530 return getAllOnesValue(numBits);
533 /// Gets maximum signed value of APInt for a specific bit width.
534 static APInt getSignedMaxValue(unsigned numBits) {
535 APInt API = getAllOnesValue(numBits);
536 API.clearBit(numBits - 1);
537 return API;
540 /// Gets minimum unsigned value of APInt for a specific bit width.
541 static APInt getMinValue(unsigned numBits) { return APInt(numBits, 0); }
543 /// Gets minimum signed value of APInt for a specific bit width.
544 static APInt getSignedMinValue(unsigned numBits) {
545 APInt API(numBits, 0);
546 API.setBit(numBits - 1);
547 return API;
550 /// Get the SignMask for a specific bit width.
552 /// This is just a wrapper function of getSignedMinValue(), and it helps code
553 /// readability when we want to get a SignMask.
554 static APInt getSignMask(unsigned BitWidth) {
555 return getSignedMinValue(BitWidth);
558 /// Get the all-ones value.
560 /// \returns the all-ones value for an APInt of the specified bit-width.
561 static APInt getAllOnesValue(unsigned numBits) {
562 return APInt(numBits, WORDTYPE_MAX, true);
565 /// Get the '0' value.
567 /// \returns the '0' value for an APInt of the specified bit-width.
568 static APInt getNullValue(unsigned numBits) { return APInt(numBits, 0); }
570 /// Compute an APInt containing numBits highbits from this APInt.
572 /// Get an APInt with the same BitWidth as this APInt, just zero mask
573 /// the low bits and right shift to the least significant bit.
575 /// \returns the high "numBits" bits of this APInt.
576 APInt getHiBits(unsigned numBits) const;
578 /// Compute an APInt containing numBits lowbits from this APInt.
580 /// Get an APInt with the same BitWidth as this APInt, just zero mask
581 /// the high bits.
583 /// \returns the low "numBits" bits of this APInt.
584 APInt getLoBits(unsigned numBits) const;
586 /// Return an APInt with exactly one bit set in the result.
587 static APInt getOneBitSet(unsigned numBits, unsigned BitNo) {
588 APInt Res(numBits, 0);
589 Res.setBit(BitNo);
590 return Res;
593 /// Get a value with a block of bits set.
595 /// Constructs an APInt value that has a contiguous range of bits set. The
596 /// bits from loBit (inclusive) to hiBit (exclusive) will be set. All other
597 /// bits will be zero. For example, with parameters(32, 0, 16) you would get
598 /// 0x0000FFFF. If hiBit is less than loBit then the set bits "wrap". For
599 /// example, with parameters (32, 28, 4), you would get 0xF000000F.
601 /// \param numBits the intended bit width of the result
602 /// \param loBit the index of the lowest bit set.
603 /// \param hiBit the index of the highest bit set.
605 /// \returns An APInt value with the requested bits set.
606 static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit) {
607 APInt Res(numBits, 0);
608 Res.setBits(loBit, hiBit);
609 return Res;
612 /// Get a value with upper bits starting at loBit set.
614 /// Constructs an APInt value that has a contiguous range of bits set. The
615 /// bits from loBit (inclusive) to numBits (exclusive) will be set. All other
616 /// bits will be zero. For example, with parameters(32, 12) you would get
617 /// 0xFFFFF000.
619 /// \param numBits the intended bit width of the result
620 /// \param loBit the index of the lowest bit to set.
622 /// \returns An APInt value with the requested bits set.
623 static APInt getBitsSetFrom(unsigned numBits, unsigned loBit) {
624 APInt Res(numBits, 0);
625 Res.setBitsFrom(loBit);
626 return Res;
629 /// Get a value with high bits set
631 /// Constructs an APInt value that has the top hiBitsSet bits set.
633 /// \param numBits the bitwidth of the result
634 /// \param hiBitsSet the number of high-order bits set in the result.
635 static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet) {
636 APInt Res(numBits, 0);
637 Res.setHighBits(hiBitsSet);
638 return Res;
641 /// Get a value with low bits set
643 /// Constructs an APInt value that has the bottom loBitsSet bits set.
645 /// \param numBits the bitwidth of the result
646 /// \param loBitsSet the number of low-order bits set in the result.
647 static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet) {
648 APInt Res(numBits, 0);
649 Res.setLowBits(loBitsSet);
650 return Res;
653 /// Return a value containing V broadcasted over NewLen bits.
654 static APInt getSplat(unsigned NewLen, const APInt &V);
656 /// Determine if two APInts have the same value, after zero-extending
657 /// one of them (if needed!) to ensure that the bit-widths match.
658 static bool isSameValue(const APInt &I1, const APInt &I2) {
659 if (I1.getBitWidth() == I2.getBitWidth())
660 return I1 == I2;
662 if (I1.getBitWidth() > I2.getBitWidth())
663 return I1 == I2.zext(I1.getBitWidth());
665 return I1.zext(I2.getBitWidth()) == I2;
668 /// Overload to compute a hash_code for an APInt value.
669 friend hash_code hash_value(const APInt &Arg);
671 /// This function returns a pointer to the internal storage of the APInt.
672 /// This is useful for writing out the APInt in binary form without any
673 /// conversions.
674 const uint64_t *getRawData() const {
675 if (isSingleWord())
676 return &U.VAL;
677 return &U.pVal[0];
680 /// @}
681 /// \name Unary Operators
682 /// @{
684 /// Postfix increment operator.
686 /// Increments *this by 1.
688 /// \returns a new APInt value representing the original value of *this.
689 const APInt operator++(int) {
690 APInt API(*this);
691 ++(*this);
692 return API;
695 /// Prefix increment operator.
697 /// \returns *this incremented by one
698 APInt &operator++();
700 /// Postfix decrement operator.
702 /// Decrements *this by 1.
704 /// \returns a new APInt value representing the original value of *this.
705 const APInt operator--(int) {
706 APInt API(*this);
707 --(*this);
708 return API;
711 /// Prefix decrement operator.
713 /// \returns *this decremented by one.
714 APInt &operator--();
716 /// Logical negation operator.
718 /// Performs logical negation operation on this APInt.
720 /// \returns true if *this is zero, false otherwise.
721 bool operator!() const {
722 if (isSingleWord())
723 return U.VAL == 0;
724 return countLeadingZerosSlowCase() == BitWidth;
727 /// @}
728 /// \name Assignment Operators
729 /// @{
731 /// Copy assignment operator.
733 /// \returns *this after assignment of RHS.
734 APInt &operator=(const APInt &RHS) {
735 // If the bitwidths are the same, we can avoid mucking with memory
736 if (isSingleWord() && RHS.isSingleWord()) {
737 U.VAL = RHS.U.VAL;
738 BitWidth = RHS.BitWidth;
739 return clearUnusedBits();
742 AssignSlowCase(RHS);
743 return *this;
746 /// Move assignment operator.
747 APInt &operator=(APInt &&that) {
748 #ifdef _MSC_VER
749 // The MSVC std::shuffle implementation still does self-assignment.
750 if (this == &that)
751 return *this;
752 #endif
753 assert(this != &that && "Self-move not supported");
754 if (!isSingleWord())
755 delete[] U.pVal;
757 // Use memcpy so that type based alias analysis sees both VAL and pVal
758 // as modified.
759 memcpy(&U, &that.U, sizeof(U));
761 BitWidth = that.BitWidth;
762 that.BitWidth = 0;
764 return *this;
767 /// Assignment operator.
769 /// The RHS value is assigned to *this. If the significant bits in RHS exceed
770 /// the bit width, the excess bits are truncated. If the bit width is larger
771 /// than 64, the value is zero filled in the unspecified high order bits.
773 /// \returns *this after assignment of RHS value.
774 APInt &operator=(uint64_t RHS) {
775 if (isSingleWord()) {
776 U.VAL = RHS;
777 clearUnusedBits();
778 } else {
779 U.pVal[0] = RHS;
780 memset(U.pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
782 return *this;
785 /// Bitwise AND assignment operator.
787 /// Performs a bitwise AND operation on this APInt and RHS. The result is
788 /// assigned to *this.
790 /// \returns *this after ANDing with RHS.
791 APInt &operator&=(const APInt &RHS) {
792 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
793 if (isSingleWord())
794 U.VAL &= RHS.U.VAL;
795 else
796 AndAssignSlowCase(RHS);
797 return *this;
800 /// Bitwise AND assignment operator.
802 /// Performs a bitwise AND operation on this APInt and RHS. RHS is
803 /// logically zero-extended or truncated to match the bit-width of
804 /// the LHS.
805 APInt &operator&=(uint64_t RHS) {
806 if (isSingleWord()) {
807 U.VAL &= RHS;
808 return *this;
810 U.pVal[0] &= RHS;
811 memset(U.pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
812 return *this;
815 /// Bitwise OR assignment operator.
817 /// Performs a bitwise OR operation on this APInt and RHS. The result is
818 /// assigned *this;
820 /// \returns *this after ORing with RHS.
821 APInt &operator|=(const APInt &RHS) {
822 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
823 if (isSingleWord())
824 U.VAL |= RHS.U.VAL;
825 else
826 OrAssignSlowCase(RHS);
827 return *this;
830 /// Bitwise OR assignment operator.
832 /// Performs a bitwise OR operation on this APInt and RHS. RHS is
833 /// logically zero-extended or truncated to match the bit-width of
834 /// the LHS.
835 APInt &operator|=(uint64_t RHS) {
836 if (isSingleWord()) {
837 U.VAL |= RHS;
838 clearUnusedBits();
839 } else {
840 U.pVal[0] |= RHS;
842 return *this;
845 /// Bitwise XOR assignment operator.
847 /// Performs a bitwise XOR operation on this APInt and RHS. The result is
848 /// assigned to *this.
850 /// \returns *this after XORing with RHS.
851 APInt &operator^=(const APInt &RHS) {
852 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
853 if (isSingleWord())
854 U.VAL ^= RHS.U.VAL;
855 else
856 XorAssignSlowCase(RHS);
857 return *this;
860 /// Bitwise XOR assignment operator.
862 /// Performs a bitwise XOR operation on this APInt and RHS. RHS is
863 /// logically zero-extended or truncated to match the bit-width of
864 /// the LHS.
865 APInt &operator^=(uint64_t RHS) {
866 if (isSingleWord()) {
867 U.VAL ^= RHS;
868 clearUnusedBits();
869 } else {
870 U.pVal[0] ^= RHS;
872 return *this;
875 /// Multiplication assignment operator.
877 /// Multiplies this APInt by RHS and assigns the result to *this.
879 /// \returns *this
880 APInt &operator*=(const APInt &RHS);
881 APInt &operator*=(uint64_t RHS);
883 /// Addition assignment operator.
885 /// Adds RHS to *this and assigns the result to *this.
887 /// \returns *this
888 APInt &operator+=(const APInt &RHS);
889 APInt &operator+=(uint64_t RHS);
891 /// Subtraction assignment operator.
893 /// Subtracts RHS from *this and assigns the result to *this.
895 /// \returns *this
896 APInt &operator-=(const APInt &RHS);
897 APInt &operator-=(uint64_t RHS);
899 /// Left-shift assignment function.
901 /// Shifts *this left by shiftAmt and assigns the result to *this.
903 /// \returns *this after shifting left by ShiftAmt
904 APInt &operator<<=(unsigned ShiftAmt) {
905 assert(ShiftAmt <= BitWidth && "Invalid shift amount");
906 if (isSingleWord()) {
907 if (ShiftAmt == BitWidth)
908 U.VAL = 0;
909 else
910 U.VAL <<= ShiftAmt;
911 return clearUnusedBits();
913 shlSlowCase(ShiftAmt);
914 return *this;
917 /// Left-shift assignment function.
919 /// Shifts *this left by shiftAmt and assigns the result to *this.
921 /// \returns *this after shifting left by ShiftAmt
922 APInt &operator<<=(const APInt &ShiftAmt);
924 /// @}
925 /// \name Binary Operators
926 /// @{
928 /// Multiplication operator.
930 /// Multiplies this APInt by RHS and returns the result.
931 APInt operator*(const APInt &RHS) const;
933 /// Left logical shift operator.
935 /// Shifts this APInt left by \p Bits and returns the result.
936 APInt operator<<(unsigned Bits) const { return shl(Bits); }
938 /// Left logical shift operator.
940 /// Shifts this APInt left by \p Bits and returns the result.
941 APInt operator<<(const APInt &Bits) const { return shl(Bits); }
943 /// Arithmetic right-shift function.
945 /// Arithmetic right-shift this APInt by shiftAmt.
946 APInt ashr(unsigned ShiftAmt) const {
947 APInt R(*this);
948 R.ashrInPlace(ShiftAmt);
949 return R;
952 /// Arithmetic right-shift this APInt by ShiftAmt in place.
953 void ashrInPlace(unsigned ShiftAmt) {
954 assert(ShiftAmt <= BitWidth && "Invalid shift amount");
955 if (isSingleWord()) {
956 int64_t SExtVAL = SignExtend64(U.VAL, BitWidth);
957 if (ShiftAmt == BitWidth)
958 U.VAL = SExtVAL >> (APINT_BITS_PER_WORD - 1); // Fill with sign bit.
959 else
960 U.VAL = SExtVAL >> ShiftAmt;
961 clearUnusedBits();
962 return;
964 ashrSlowCase(ShiftAmt);
967 /// Logical right-shift function.
969 /// Logical right-shift this APInt by shiftAmt.
970 APInt lshr(unsigned shiftAmt) const {
971 APInt R(*this);
972 R.lshrInPlace(shiftAmt);
973 return R;
976 /// Logical right-shift this APInt by ShiftAmt in place.
977 void lshrInPlace(unsigned ShiftAmt) {
978 assert(ShiftAmt <= BitWidth && "Invalid shift amount");
979 if (isSingleWord()) {
980 if (ShiftAmt == BitWidth)
981 U.VAL = 0;
982 else
983 U.VAL >>= ShiftAmt;
984 return;
986 lshrSlowCase(ShiftAmt);
989 /// Left-shift function.
991 /// Left-shift this APInt by shiftAmt.
992 APInt shl(unsigned shiftAmt) const {
993 APInt R(*this);
994 R <<= shiftAmt;
995 return R;
998 /// Rotate left by rotateAmt.
999 APInt rotl(unsigned rotateAmt) const;
1001 /// Rotate right by rotateAmt.
1002 APInt rotr(unsigned rotateAmt) const;
1004 /// Arithmetic right-shift function.
1006 /// Arithmetic right-shift this APInt by shiftAmt.
1007 APInt ashr(const APInt &ShiftAmt) const {
1008 APInt R(*this);
1009 R.ashrInPlace(ShiftAmt);
1010 return R;
1013 /// Arithmetic right-shift this APInt by shiftAmt in place.
1014 void ashrInPlace(const APInt &shiftAmt);
1016 /// Logical right-shift function.
1018 /// Logical right-shift this APInt by shiftAmt.
1019 APInt lshr(const APInt &ShiftAmt) const {
1020 APInt R(*this);
1021 R.lshrInPlace(ShiftAmt);
1022 return R;
1025 /// Logical right-shift this APInt by ShiftAmt in place.
1026 void lshrInPlace(const APInt &ShiftAmt);
1028 /// Left-shift function.
1030 /// Left-shift this APInt by shiftAmt.
1031 APInt shl(const APInt &ShiftAmt) const {
1032 APInt R(*this);
1033 R <<= ShiftAmt;
1034 return R;
1037 /// Rotate left by rotateAmt.
1038 APInt rotl(const APInt &rotateAmt) const;
1040 /// Rotate right by rotateAmt.
1041 APInt rotr(const APInt &rotateAmt) const;
1043 /// Unsigned division operation.
1045 /// Perform an unsigned divide operation on this APInt by RHS. Both this and
1046 /// RHS are treated as unsigned quantities for purposes of this division.
1048 /// \returns a new APInt value containing the division result, rounded towards
1049 /// zero.
1050 APInt udiv(const APInt &RHS) const;
1051 APInt udiv(uint64_t RHS) const;
1053 /// Signed division function for APInt.
1055 /// Signed divide this APInt by APInt RHS.
1057 /// The result is rounded towards zero.
1058 APInt sdiv(const APInt &RHS) const;
1059 APInt sdiv(int64_t RHS) const;
1061 /// Unsigned remainder operation.
1063 /// Perform an unsigned remainder operation on this APInt with RHS being the
1064 /// divisor. Both this and RHS are treated as unsigned quantities for purposes
1065 /// of this operation. Note that this is a true remainder operation and not a
1066 /// modulo operation because the sign follows the sign of the dividend which
1067 /// is *this.
1069 /// \returns a new APInt value containing the remainder result
1070 APInt urem(const APInt &RHS) const;
1071 uint64_t urem(uint64_t RHS) const;
1073 /// Function for signed remainder operation.
1075 /// Signed remainder operation on APInt.
1076 APInt srem(const APInt &RHS) const;
1077 int64_t srem(int64_t RHS) const;
1079 /// Dual division/remainder interface.
1081 /// Sometimes it is convenient to divide two APInt values and obtain both the
1082 /// quotient and remainder. This function does both operations in the same
1083 /// computation making it a little more efficient. The pair of input arguments
1084 /// may overlap with the pair of output arguments. It is safe to call
1085 /// udivrem(X, Y, X, Y), for example.
1086 static void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient,
1087 APInt &Remainder);
1088 static void udivrem(const APInt &LHS, uint64_t RHS, APInt &Quotient,
1089 uint64_t &Remainder);
1091 static void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient,
1092 APInt &Remainder);
1093 static void sdivrem(const APInt &LHS, int64_t RHS, APInt &Quotient,
1094 int64_t &Remainder);
1096 // Operations that return overflow indicators.
1097 APInt sadd_ov(const APInt &RHS, bool &Overflow) const;
1098 APInt uadd_ov(const APInt &RHS, bool &Overflow) const;
1099 APInt ssub_ov(const APInt &RHS, bool &Overflow) const;
1100 APInt usub_ov(const APInt &RHS, bool &Overflow) const;
1101 APInt sdiv_ov(const APInt &RHS, bool &Overflow) const;
1102 APInt smul_ov(const APInt &RHS, bool &Overflow) const;
1103 APInt umul_ov(const APInt &RHS, bool &Overflow) const;
1104 APInt sshl_ov(const APInt &Amt, bool &Overflow) const;
1105 APInt ushl_ov(const APInt &Amt, bool &Overflow) const;
1107 // Operations that saturate
1108 APInt sadd_sat(const APInt &RHS) const;
1109 APInt uadd_sat(const APInt &RHS) const;
1110 APInt ssub_sat(const APInt &RHS) const;
1111 APInt usub_sat(const APInt &RHS) const;
1113 /// Array-indexing support.
1115 /// \returns the bit value at bitPosition
1116 bool operator[](unsigned bitPosition) const {
1117 assert(bitPosition < getBitWidth() && "Bit position out of bounds!");
1118 return (maskBit(bitPosition) & getWord(bitPosition)) != 0;
1121 /// @}
1122 /// \name Comparison Operators
1123 /// @{
1125 /// Equality operator.
1127 /// Compares this APInt with RHS for the validity of the equality
1128 /// relationship.
1129 bool operator==(const APInt &RHS) const {
1130 assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths");
1131 if (isSingleWord())
1132 return U.VAL == RHS.U.VAL;
1133 return EqualSlowCase(RHS);
1136 /// Equality operator.
1138 /// Compares this APInt with a uint64_t for the validity of the equality
1139 /// relationship.
1141 /// \returns true if *this == Val
1142 bool operator==(uint64_t Val) const {
1143 return (isSingleWord() || getActiveBits() <= 64) && getZExtValue() == Val;
1146 /// Equality comparison.
1148 /// Compares this APInt with RHS for the validity of the equality
1149 /// relationship.
1151 /// \returns true if *this == Val
1152 bool eq(const APInt &RHS) const { return (*this) == RHS; }
1154 /// Inequality operator.
1156 /// Compares this APInt with RHS for the validity of the inequality
1157 /// relationship.
1159 /// \returns true if *this != Val
1160 bool operator!=(const APInt &RHS) const { return !((*this) == RHS); }
1162 /// Inequality operator.
1164 /// Compares this APInt with a uint64_t for the validity of the inequality
1165 /// relationship.
1167 /// \returns true if *this != Val
1168 bool operator!=(uint64_t Val) const { return !((*this) == Val); }
1170 /// Inequality comparison
1172 /// Compares this APInt with RHS for the validity of the inequality
1173 /// relationship.
1175 /// \returns true if *this != Val
1176 bool ne(const APInt &RHS) const { return !((*this) == RHS); }
1178 /// Unsigned less than comparison
1180 /// Regards both *this and RHS as unsigned quantities and compares them for
1181 /// the validity of the less-than relationship.
1183 /// \returns true if *this < RHS when both are considered unsigned.
1184 bool ult(const APInt &RHS) const { return compare(RHS) < 0; }
1186 /// Unsigned less than comparison
1188 /// Regards both *this as an unsigned quantity and compares it with RHS for
1189 /// the validity of the less-than relationship.
1191 /// \returns true if *this < RHS when considered unsigned.
1192 bool ult(uint64_t RHS) const {
1193 // Only need to check active bits if not a single word.
1194 return (isSingleWord() || getActiveBits() <= 64) && getZExtValue() < RHS;
1197 /// Signed less than comparison
1199 /// Regards both *this and RHS as signed quantities and compares them for
1200 /// validity of the less-than relationship.
1202 /// \returns true if *this < RHS when both are considered signed.
1203 bool slt(const APInt &RHS) const { return compareSigned(RHS) < 0; }
1205 /// Signed less than comparison
1207 /// Regards both *this as a signed quantity and compares it with RHS for
1208 /// the validity of the less-than relationship.
1210 /// \returns true if *this < RHS when considered signed.
1211 bool slt(int64_t RHS) const {
1212 return (!isSingleWord() && getMinSignedBits() > 64) ? isNegative()
1213 : getSExtValue() < RHS;
1216 /// Unsigned less or equal comparison
1218 /// Regards both *this and RHS as unsigned quantities and compares them for
1219 /// validity of the less-or-equal relationship.
1221 /// \returns true if *this <= RHS when both are considered unsigned.
1222 bool ule(const APInt &RHS) const { return compare(RHS) <= 0; }
1224 /// Unsigned less or equal comparison
1226 /// Regards both *this as an unsigned quantity and compares it with RHS for
1227 /// the validity of the less-or-equal relationship.
1229 /// \returns true if *this <= RHS when considered unsigned.
1230 bool ule(uint64_t RHS) const { return !ugt(RHS); }
1232 /// Signed less or equal comparison
1234 /// Regards both *this and RHS as signed quantities and compares them for
1235 /// validity of the less-or-equal relationship.
1237 /// \returns true if *this <= RHS when both are considered signed.
1238 bool sle(const APInt &RHS) const { return compareSigned(RHS) <= 0; }
1240 /// Signed less or equal comparison
1242 /// Regards both *this as a signed quantity and compares it with RHS for the
1243 /// validity of the less-or-equal relationship.
1245 /// \returns true if *this <= RHS when considered signed.
1246 bool sle(uint64_t RHS) const { return !sgt(RHS); }
1248 /// Unsigned greather than comparison
1250 /// Regards both *this and RHS as unsigned quantities and compares them for
1251 /// the validity of the greater-than relationship.
1253 /// \returns true if *this > RHS when both are considered unsigned.
1254 bool ugt(const APInt &RHS) const { return !ule(RHS); }
1256 /// Unsigned greater than comparison
1258 /// Regards both *this as an unsigned quantity and compares it with RHS for
1259 /// the validity of the greater-than relationship.
1261 /// \returns true if *this > RHS when considered unsigned.
1262 bool ugt(uint64_t RHS) const {
1263 // Only need to check active bits if not a single word.
1264 return (!isSingleWord() && getActiveBits() > 64) || getZExtValue() > RHS;
1267 /// Signed greather than comparison
1269 /// Regards both *this and RHS as signed quantities and compares them for the
1270 /// validity of the greater-than relationship.
1272 /// \returns true if *this > RHS when both are considered signed.
1273 bool sgt(const APInt &RHS) const { return !sle(RHS); }
1275 /// Signed greater than comparison
1277 /// Regards both *this as a signed quantity and compares it with RHS for
1278 /// the validity of the greater-than relationship.
1280 /// \returns true if *this > RHS when considered signed.
1281 bool sgt(int64_t RHS) const {
1282 return (!isSingleWord() && getMinSignedBits() > 64) ? !isNegative()
1283 : getSExtValue() > RHS;
1286 /// Unsigned greater or equal comparison
1288 /// Regards both *this and RHS as unsigned quantities and compares them for
1289 /// validity of the greater-or-equal relationship.
1291 /// \returns true if *this >= RHS when both are considered unsigned.
1292 bool uge(const APInt &RHS) const { return !ult(RHS); }
1294 /// Unsigned greater or equal comparison
1296 /// Regards both *this as an unsigned quantity and compares it with RHS for
1297 /// the validity of the greater-or-equal relationship.
1299 /// \returns true if *this >= RHS when considered unsigned.
1300 bool uge(uint64_t RHS) const { return !ult(RHS); }
1302 /// Signed greater or equal comparison
1304 /// Regards both *this and RHS as signed quantities and compares them for
1305 /// validity of the greater-or-equal relationship.
1307 /// \returns true if *this >= RHS when both are considered signed.
1308 bool sge(const APInt &RHS) const { return !slt(RHS); }
1310 /// Signed greater or equal comparison
1312 /// Regards both *this as a signed quantity and compares it with RHS for
1313 /// the validity of the greater-or-equal relationship.
1315 /// \returns true if *this >= RHS when considered signed.
1316 bool sge(int64_t RHS) const { return !slt(RHS); }
1318 /// This operation tests if there are any pairs of corresponding bits
1319 /// between this APInt and RHS that are both set.
1320 bool intersects(const APInt &RHS) const {
1321 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1322 if (isSingleWord())
1323 return (U.VAL & RHS.U.VAL) != 0;
1324 return intersectsSlowCase(RHS);
1327 /// This operation checks that all bits set in this APInt are also set in RHS.
1328 bool isSubsetOf(const APInt &RHS) const {
1329 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1330 if (isSingleWord())
1331 return (U.VAL & ~RHS.U.VAL) == 0;
1332 return isSubsetOfSlowCase(RHS);
1335 /// @}
1336 /// \name Resizing Operators
1337 /// @{
1339 /// Truncate to new width.
1341 /// Truncate the APInt to a specified width. It is an error to specify a width
1342 /// that is greater than or equal to the current width.
1343 APInt trunc(unsigned width) const;
1345 /// Sign extend to a new width.
1347 /// This operation sign extends the APInt to a new width. If the high order
1348 /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
1349 /// It is an error to specify a width that is less than or equal to the
1350 /// current width.
1351 APInt sext(unsigned width) const;
1353 /// Zero extend to a new width.
1355 /// This operation zero extends the APInt to a new width. The high order bits
1356 /// are filled with 0 bits. It is an error to specify a width that is less
1357 /// than or equal to the current width.
1358 APInt zext(unsigned width) const;
1360 /// Sign extend or truncate to width
1362 /// Make this APInt have the bit width given by \p width. The value is sign
1363 /// extended, truncated, or left alone to make it that width.
1364 APInt sextOrTrunc(unsigned width) const;
1366 /// Zero extend or truncate to width
1368 /// Make this APInt have the bit width given by \p width. The value is zero
1369 /// extended, truncated, or left alone to make it that width.
1370 APInt zextOrTrunc(unsigned width) const;
1372 /// Sign extend or truncate to width
1374 /// Make this APInt have the bit width given by \p width. The value is sign
1375 /// extended, or left alone to make it that width.
1376 APInt sextOrSelf(unsigned width) const;
1378 /// Zero extend or truncate to width
1380 /// Make this APInt have the bit width given by \p width. The value is zero
1381 /// extended, or left alone to make it that width.
1382 APInt zextOrSelf(unsigned width) const;
1384 /// @}
1385 /// \name Bit Manipulation Operators
1386 /// @{
1388 /// Set every bit to 1.
1389 void setAllBits() {
1390 if (isSingleWord())
1391 U.VAL = WORDTYPE_MAX;
1392 else
1393 // Set all the bits in all the words.
1394 memset(U.pVal, -1, getNumWords() * APINT_WORD_SIZE);
1395 // Clear the unused ones
1396 clearUnusedBits();
1399 /// Set a given bit to 1.
1401 /// Set the given bit to 1 whose position is given as "bitPosition".
1402 void setBit(unsigned BitPosition) {
1403 assert(BitPosition < BitWidth && "BitPosition out of range");
1404 WordType Mask = maskBit(BitPosition);
1405 if (isSingleWord())
1406 U.VAL |= Mask;
1407 else
1408 U.pVal[whichWord(BitPosition)] |= Mask;
1411 /// Set the sign bit to 1.
1412 void setSignBit() {
1413 setBit(BitWidth - 1);
1416 /// Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
1417 void setBits(unsigned loBit, unsigned hiBit) {
1418 assert(hiBit <= BitWidth && "hiBit out of range");
1419 assert(loBit <= BitWidth && "loBit out of range");
1420 assert(loBit <= hiBit && "loBit greater than hiBit");
1421 if (loBit == hiBit)
1422 return;
1423 if (loBit < APINT_BITS_PER_WORD && hiBit <= APINT_BITS_PER_WORD) {
1424 uint64_t mask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - (hiBit - loBit));
1425 mask <<= loBit;
1426 if (isSingleWord())
1427 U.VAL |= mask;
1428 else
1429 U.pVal[0] |= mask;
1430 } else {
1431 setBitsSlowCase(loBit, hiBit);
1435 /// Set the top bits starting from loBit.
1436 void setBitsFrom(unsigned loBit) {
1437 return setBits(loBit, BitWidth);
1440 /// Set the bottom loBits bits.
1441 void setLowBits(unsigned loBits) {
1442 return setBits(0, loBits);
1445 /// Set the top hiBits bits.
1446 void setHighBits(unsigned hiBits) {
1447 return setBits(BitWidth - hiBits, BitWidth);
1450 /// Set every bit to 0.
1451 void clearAllBits() {
1452 if (isSingleWord())
1453 U.VAL = 0;
1454 else
1455 memset(U.pVal, 0, getNumWords() * APINT_WORD_SIZE);
1458 /// Set a given bit to 0.
1460 /// Set the given bit to 0 whose position is given as "bitPosition".
1461 void clearBit(unsigned BitPosition) {
1462 assert(BitPosition < BitWidth && "BitPosition out of range");
1463 WordType Mask = ~maskBit(BitPosition);
1464 if (isSingleWord())
1465 U.VAL &= Mask;
1466 else
1467 U.pVal[whichWord(BitPosition)] &= Mask;
1470 /// Set bottom loBits bits to 0.
1471 void clearLowBits(unsigned loBits) {
1472 assert(loBits <= BitWidth && "More bits than bitwidth");
1473 APInt Keep = getHighBitsSet(BitWidth, BitWidth - loBits);
1474 *this &= Keep;
1477 /// Set the sign bit to 0.
1478 void clearSignBit() {
1479 clearBit(BitWidth - 1);
1482 /// Toggle every bit to its opposite value.
1483 void flipAllBits() {
1484 if (isSingleWord()) {
1485 U.VAL ^= WORDTYPE_MAX;
1486 clearUnusedBits();
1487 } else {
1488 flipAllBitsSlowCase();
1492 /// Toggles a given bit to its opposite value.
1494 /// Toggle a given bit to its opposite value whose position is given
1495 /// as "bitPosition".
1496 void flipBit(unsigned bitPosition);
1498 /// Negate this APInt in place.
1499 void negate() {
1500 flipAllBits();
1501 ++(*this);
1504 /// Insert the bits from a smaller APInt starting at bitPosition.
1505 void insertBits(const APInt &SubBits, unsigned bitPosition);
1507 /// Return an APInt with the extracted bits [bitPosition,bitPosition+numBits).
1508 APInt extractBits(unsigned numBits, unsigned bitPosition) const;
1510 /// @}
1511 /// \name Value Characterization Functions
1512 /// @{
1514 /// Return the number of bits in the APInt.
1515 unsigned getBitWidth() const { return BitWidth; }
1517 /// Get the number of words.
1519 /// Here one word's bitwidth equals to that of uint64_t.
1521 /// \returns the number of words to hold the integer value of this APInt.
1522 unsigned getNumWords() const { return getNumWords(BitWidth); }
1524 /// Get the number of words.
1526 /// *NOTE* Here one word's bitwidth equals to that of uint64_t.
1528 /// \returns the number of words to hold the integer value with a given bit
1529 /// width.
1530 static unsigned getNumWords(unsigned BitWidth) {
1531 return ((uint64_t)BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
1534 /// Compute the number of active bits in the value
1536 /// This function returns the number of active bits which is defined as the
1537 /// bit width minus the number of leading zeros. This is used in several
1538 /// computations to see how "wide" the value is.
1539 unsigned getActiveBits() const { return BitWidth - countLeadingZeros(); }
1541 /// Compute the number of active words in the value of this APInt.
1543 /// This is used in conjunction with getActiveData to extract the raw value of
1544 /// the APInt.
1545 unsigned getActiveWords() const {
1546 unsigned numActiveBits = getActiveBits();
1547 return numActiveBits ? whichWord(numActiveBits - 1) + 1 : 1;
1550 /// Get the minimum bit size for this signed APInt
1552 /// Computes the minimum bit width for this APInt while considering it to be a
1553 /// signed (and probably negative) value. If the value is not negative, this
1554 /// function returns the same value as getActiveBits()+1. Otherwise, it
1555 /// returns the smallest bit width that will retain the negative value. For
1556 /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
1557 /// for -1, this function will always return 1.
1558 unsigned getMinSignedBits() const {
1559 if (isNegative())
1560 return BitWidth - countLeadingOnes() + 1;
1561 return getActiveBits() + 1;
1564 /// Get zero extended value
1566 /// This method attempts to return the value of this APInt as a zero extended
1567 /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
1568 /// uint64_t. Otherwise an assertion will result.
1569 uint64_t getZExtValue() const {
1570 if (isSingleWord())
1571 return U.VAL;
1572 assert(getActiveBits() <= 64 && "Too many bits for uint64_t");
1573 return U.pVal[0];
1576 /// Get sign extended value
1578 /// This method attempts to return the value of this APInt as a sign extended
1579 /// int64_t. The bit width must be <= 64 or the value must fit within an
1580 /// int64_t. Otherwise an assertion will result.
1581 int64_t getSExtValue() const {
1582 if (isSingleWord())
1583 return SignExtend64(U.VAL, BitWidth);
1584 assert(getMinSignedBits() <= 64 && "Too many bits for int64_t");
1585 return int64_t(U.pVal[0]);
1588 /// Get bits required for string value.
1590 /// This method determines how many bits are required to hold the APInt
1591 /// equivalent of the string given by \p str.
1592 static unsigned getBitsNeeded(StringRef str, uint8_t radix);
1594 /// The APInt version of the countLeadingZeros functions in
1595 /// MathExtras.h.
1597 /// It counts the number of zeros from the most significant bit to the first
1598 /// one bit.
1600 /// \returns BitWidth if the value is zero, otherwise returns the number of
1601 /// zeros from the most significant bit to the first one bits.
1602 unsigned countLeadingZeros() const {
1603 if (isSingleWord()) {
1604 unsigned unusedBits = APINT_BITS_PER_WORD - BitWidth;
1605 return llvm::countLeadingZeros(U.VAL) - unusedBits;
1607 return countLeadingZerosSlowCase();
1610 /// Count the number of leading one bits.
1612 /// This function is an APInt version of the countLeadingOnes
1613 /// functions in MathExtras.h. It counts the number of ones from the most
1614 /// significant bit to the first zero bit.
1616 /// \returns 0 if the high order bit is not set, otherwise returns the number
1617 /// of 1 bits from the most significant to the least
1618 unsigned countLeadingOnes() const {
1619 if (isSingleWord())
1620 return llvm::countLeadingOnes(U.VAL << (APINT_BITS_PER_WORD - BitWidth));
1621 return countLeadingOnesSlowCase();
1624 /// Computes the number of leading bits of this APInt that are equal to its
1625 /// sign bit.
1626 unsigned getNumSignBits() const {
1627 return isNegative() ? countLeadingOnes() : countLeadingZeros();
1630 /// Count the number of trailing zero bits.
1632 /// This function is an APInt version of the countTrailingZeros
1633 /// functions in MathExtras.h. It counts the number of zeros from the least
1634 /// significant bit to the first set bit.
1636 /// \returns BitWidth if the value is zero, otherwise returns the number of
1637 /// zeros from the least significant bit to the first one bit.
1638 unsigned countTrailingZeros() const {
1639 if (isSingleWord())
1640 return std::min(unsigned(llvm::countTrailingZeros(U.VAL)), BitWidth);
1641 return countTrailingZerosSlowCase();
1644 /// Count the number of trailing one bits.
1646 /// This function is an APInt version of the countTrailingOnes
1647 /// functions in MathExtras.h. It counts the number of ones from the least
1648 /// significant bit to the first zero bit.
1650 /// \returns BitWidth if the value is all ones, otherwise returns the number
1651 /// of ones from the least significant bit to the first zero bit.
1652 unsigned countTrailingOnes() const {
1653 if (isSingleWord())
1654 return llvm::countTrailingOnes(U.VAL);
1655 return countTrailingOnesSlowCase();
1658 /// Count the number of bits set.
1660 /// This function is an APInt version of the countPopulation functions
1661 /// in MathExtras.h. It counts the number of 1 bits in the APInt value.
1663 /// \returns 0 if the value is zero, otherwise returns the number of set bits.
1664 unsigned countPopulation() const {
1665 if (isSingleWord())
1666 return llvm::countPopulation(U.VAL);
1667 return countPopulationSlowCase();
1670 /// @}
1671 /// \name Conversion Functions
1672 /// @{
1673 void print(raw_ostream &OS, bool isSigned) const;
1675 /// Converts an APInt to a string and append it to Str. Str is commonly a
1676 /// SmallString.
1677 void toString(SmallVectorImpl<char> &Str, unsigned Radix, bool Signed,
1678 bool formatAsCLiteral = false) const;
1680 /// Considers the APInt to be unsigned and converts it into a string in the
1681 /// radix given. The radix can be 2, 8, 10 16, or 36.
1682 void toStringUnsigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1683 toString(Str, Radix, false, false);
1686 /// Considers the APInt to be signed and converts it into a string in the
1687 /// radix given. The radix can be 2, 8, 10, 16, or 36.
1688 void toStringSigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1689 toString(Str, Radix, true, false);
1692 /// Return the APInt as a std::string.
1694 /// Note that this is an inefficient method. It is better to pass in a
1695 /// SmallVector/SmallString to the methods above to avoid thrashing the heap
1696 /// for the string.
1697 std::string toString(unsigned Radix, bool Signed) const;
1699 /// \returns a byte-swapped representation of this APInt Value.
1700 APInt byteSwap() const;
1702 /// \returns the value with the bit representation reversed of this APInt
1703 /// Value.
1704 APInt reverseBits() const;
1706 /// Converts this APInt to a double value.
1707 double roundToDouble(bool isSigned) const;
1709 /// Converts this unsigned APInt to a double value.
1710 double roundToDouble() const { return roundToDouble(false); }
1712 /// Converts this signed APInt to a double value.
1713 double signedRoundToDouble() const { return roundToDouble(true); }
1715 /// Converts APInt bits to a double
1717 /// The conversion does not do a translation from integer to double, it just
1718 /// re-interprets the bits as a double. Note that it is valid to do this on
1719 /// any bit width. Exactly 64 bits will be translated.
1720 double bitsToDouble() const {
1721 return BitsToDouble(getWord(0));
1724 /// Converts APInt bits to a double
1726 /// The conversion does not do a translation from integer to float, it just
1727 /// re-interprets the bits as a float. Note that it is valid to do this on
1728 /// any bit width. Exactly 32 bits will be translated.
1729 float bitsToFloat() const {
1730 return BitsToFloat(getWord(0));
1733 /// Converts a double to APInt bits.
1735 /// The conversion does not do a translation from double to integer, it just
1736 /// re-interprets the bits of the double.
1737 static APInt doubleToBits(double V) {
1738 return APInt(sizeof(double) * CHAR_BIT, DoubleToBits(V));
1741 /// Converts a float to APInt bits.
1743 /// The conversion does not do a translation from float to integer, it just
1744 /// re-interprets the bits of the float.
1745 static APInt floatToBits(float V) {
1746 return APInt(sizeof(float) * CHAR_BIT, FloatToBits(V));
1749 /// @}
1750 /// \name Mathematics Operations
1751 /// @{
1753 /// \returns the floor log base 2 of this APInt.
1754 unsigned logBase2() const { return getActiveBits() - 1; }
1756 /// \returns the ceil log base 2 of this APInt.
1757 unsigned ceilLogBase2() const {
1758 APInt temp(*this);
1759 --temp;
1760 return temp.getActiveBits();
1763 /// \returns the nearest log base 2 of this APInt. Ties round up.
1765 /// NOTE: When we have a BitWidth of 1, we define:
1767 /// log2(0) = UINT32_MAX
1768 /// log2(1) = 0
1770 /// to get around any mathematical concerns resulting from
1771 /// referencing 2 in a space where 2 does no exist.
1772 unsigned nearestLogBase2() const {
1773 // Special case when we have a bitwidth of 1. If VAL is 1, then we
1774 // get 0. If VAL is 0, we get WORDTYPE_MAX which gets truncated to
1775 // UINT32_MAX.
1776 if (BitWidth == 1)
1777 return U.VAL - 1;
1779 // Handle the zero case.
1780 if (isNullValue())
1781 return UINT32_MAX;
1783 // The non-zero case is handled by computing:
1785 // nearestLogBase2(x) = logBase2(x) + x[logBase2(x)-1].
1787 // where x[i] is referring to the value of the ith bit of x.
1788 unsigned lg = logBase2();
1789 return lg + unsigned((*this)[lg - 1]);
1792 /// \returns the log base 2 of this APInt if its an exact power of two, -1
1793 /// otherwise
1794 int32_t exactLogBase2() const {
1795 if (!isPowerOf2())
1796 return -1;
1797 return logBase2();
1800 /// Compute the square root
1801 APInt sqrt() const;
1803 /// Get the absolute value;
1805 /// If *this is < 0 then return -(*this), otherwise *this;
1806 APInt abs() const {
1807 if (isNegative())
1808 return -(*this);
1809 return *this;
1812 /// \returns the multiplicative inverse for a given modulo.
1813 APInt multiplicativeInverse(const APInt &modulo) const;
1815 /// @}
1816 /// \name Support for division by constant
1817 /// @{
1819 /// Calculate the magic number for signed division by a constant.
1820 struct ms;
1821 ms magic() const;
1823 /// Calculate the magic number for unsigned division by a constant.
1824 struct mu;
1825 mu magicu(unsigned LeadingZeros = 0) const;
1827 /// @}
1828 /// \name Building-block Operations for APInt and APFloat
1829 /// @{
1831 // These building block operations operate on a representation of arbitrary
1832 // precision, two's-complement, bignum integer values. They should be
1833 // sufficient to implement APInt and APFloat bignum requirements. Inputs are
1834 // generally a pointer to the base of an array of integer parts, representing
1835 // an unsigned bignum, and a count of how many parts there are.
1837 /// Sets the least significant part of a bignum to the input value, and zeroes
1838 /// out higher parts.
1839 static void tcSet(WordType *, WordType, unsigned);
1841 /// Assign one bignum to another.
1842 static void tcAssign(WordType *, const WordType *, unsigned);
1844 /// Returns true if a bignum is zero, false otherwise.
1845 static bool tcIsZero(const WordType *, unsigned);
1847 /// Extract the given bit of a bignum; returns 0 or 1. Zero-based.
1848 static int tcExtractBit(const WordType *, unsigned bit);
1850 /// Copy the bit vector of width srcBITS from SRC, starting at bit srcLSB, to
1851 /// DST, of dstCOUNT parts, such that the bit srcLSB becomes the least
1852 /// significant bit of DST. All high bits above srcBITS in DST are
1853 /// zero-filled.
1854 static void tcExtract(WordType *, unsigned dstCount,
1855 const WordType *, unsigned srcBits,
1856 unsigned srcLSB);
1858 /// Set the given bit of a bignum. Zero-based.
1859 static void tcSetBit(WordType *, unsigned bit);
1861 /// Clear the given bit of a bignum. Zero-based.
1862 static void tcClearBit(WordType *, unsigned bit);
1864 /// Returns the bit number of the least or most significant set bit of a
1865 /// number. If the input number has no bits set -1U is returned.
1866 static unsigned tcLSB(const WordType *, unsigned n);
1867 static unsigned tcMSB(const WordType *parts, unsigned n);
1869 /// Negate a bignum in-place.
1870 static void tcNegate(WordType *, unsigned);
1872 /// DST += RHS + CARRY where CARRY is zero or one. Returns the carry flag.
1873 static WordType tcAdd(WordType *, const WordType *,
1874 WordType carry, unsigned);
1875 /// DST += RHS. Returns the carry flag.
1876 static WordType tcAddPart(WordType *, WordType, unsigned);
1878 /// DST -= RHS + CARRY where CARRY is zero or one. Returns the carry flag.
1879 static WordType tcSubtract(WordType *, const WordType *,
1880 WordType carry, unsigned);
1881 /// DST -= RHS. Returns the carry flag.
1882 static WordType tcSubtractPart(WordType *, WordType, unsigned);
1884 /// DST += SRC * MULTIPLIER + PART if add is true
1885 /// DST = SRC * MULTIPLIER + PART if add is false
1887 /// Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC they must
1888 /// start at the same point, i.e. DST == SRC.
1890 /// If DSTPARTS == SRC_PARTS + 1 no overflow occurs and zero is returned.
1891 /// Otherwise DST is filled with the least significant DSTPARTS parts of the
1892 /// result, and if all of the omitted higher parts were zero return zero,
1893 /// otherwise overflow occurred and return one.
1894 static int tcMultiplyPart(WordType *dst, const WordType *src,
1895 WordType multiplier, WordType carry,
1896 unsigned srcParts, unsigned dstParts,
1897 bool add);
1899 /// DST = LHS * RHS, where DST has the same width as the operands and is
1900 /// filled with the least significant parts of the result. Returns one if
1901 /// overflow occurred, otherwise zero. DST must be disjoint from both
1902 /// operands.
1903 static int tcMultiply(WordType *, const WordType *, const WordType *,
1904 unsigned);
1906 /// DST = LHS * RHS, where DST has width the sum of the widths of the
1907 /// operands. No overflow occurs. DST must be disjoint from both operands.
1908 static void tcFullMultiply(WordType *, const WordType *,
1909 const WordType *, unsigned, unsigned);
1911 /// If RHS is zero LHS and REMAINDER are left unchanged, return one.
1912 /// Otherwise set LHS to LHS / RHS with the fractional part discarded, set
1913 /// REMAINDER to the remainder, return zero. i.e.
1915 /// OLD_LHS = RHS * LHS + REMAINDER
1917 /// SCRATCH is a bignum of the same size as the operands and result for use by
1918 /// the routine; its contents need not be initialized and are destroyed. LHS,
1919 /// REMAINDER and SCRATCH must be distinct.
1920 static int tcDivide(WordType *lhs, const WordType *rhs,
1921 WordType *remainder, WordType *scratch,
1922 unsigned parts);
1924 /// Shift a bignum left Count bits. Shifted in bits are zero. There are no
1925 /// restrictions on Count.
1926 static void tcShiftLeft(WordType *, unsigned Words, unsigned Count);
1928 /// Shift a bignum right Count bits. Shifted in bits are zero. There are no
1929 /// restrictions on Count.
1930 static void tcShiftRight(WordType *, unsigned Words, unsigned Count);
1932 /// The obvious AND, OR and XOR and complement operations.
1933 static void tcAnd(WordType *, const WordType *, unsigned);
1934 static void tcOr(WordType *, const WordType *, unsigned);
1935 static void tcXor(WordType *, const WordType *, unsigned);
1936 static void tcComplement(WordType *, unsigned);
1938 /// Comparison (unsigned) of two bignums.
1939 static int tcCompare(const WordType *, const WordType *, unsigned);
1941 /// Increment a bignum in-place. Return the carry flag.
1942 static WordType tcIncrement(WordType *dst, unsigned parts) {
1943 return tcAddPart(dst, 1, parts);
1946 /// Decrement a bignum in-place. Return the borrow flag.
1947 static WordType tcDecrement(WordType *dst, unsigned parts) {
1948 return tcSubtractPart(dst, 1, parts);
1951 /// Set the least significant BITS and clear the rest.
1952 static void tcSetLeastSignificantBits(WordType *, unsigned, unsigned bits);
1954 /// debug method
1955 void dump() const;
1957 /// @}
1960 /// Magic data for optimising signed division by a constant.
1961 struct APInt::ms {
1962 APInt m; ///< magic number
1963 unsigned s; ///< shift amount
1966 /// Magic data for optimising unsigned division by a constant.
1967 struct APInt::mu {
1968 APInt m; ///< magic number
1969 bool a; ///< add indicator
1970 unsigned s; ///< shift amount
1973 inline bool operator==(uint64_t V1, const APInt &V2) { return V2 == V1; }
1975 inline bool operator!=(uint64_t V1, const APInt &V2) { return V2 != V1; }
1977 /// Unary bitwise complement operator.
1979 /// \returns an APInt that is the bitwise complement of \p v.
1980 inline APInt operator~(APInt v) {
1981 v.flipAllBits();
1982 return v;
1985 inline APInt operator&(APInt a, const APInt &b) {
1986 a &= b;
1987 return a;
1990 inline APInt operator&(const APInt &a, APInt &&b) {
1991 b &= a;
1992 return std::move(b);
1995 inline APInt operator&(APInt a, uint64_t RHS) {
1996 a &= RHS;
1997 return a;
2000 inline APInt operator&(uint64_t LHS, APInt b) {
2001 b &= LHS;
2002 return b;
2005 inline APInt operator|(APInt a, const APInt &b) {
2006 a |= b;
2007 return a;
2010 inline APInt operator|(const APInt &a, APInt &&b) {
2011 b |= a;
2012 return std::move(b);
2015 inline APInt operator|(APInt a, uint64_t RHS) {
2016 a |= RHS;
2017 return a;
2020 inline APInt operator|(uint64_t LHS, APInt b) {
2021 b |= LHS;
2022 return b;
2025 inline APInt operator^(APInt a, const APInt &b) {
2026 a ^= b;
2027 return a;
2030 inline APInt operator^(const APInt &a, APInt &&b) {
2031 b ^= a;
2032 return std::move(b);
2035 inline APInt operator^(APInt a, uint64_t RHS) {
2036 a ^= RHS;
2037 return a;
2040 inline APInt operator^(uint64_t LHS, APInt b) {
2041 b ^= LHS;
2042 return b;
2045 inline raw_ostream &operator<<(raw_ostream &OS, const APInt &I) {
2046 I.print(OS, true);
2047 return OS;
2050 inline APInt operator-(APInt v) {
2051 v.negate();
2052 return v;
2055 inline APInt operator+(APInt a, const APInt &b) {
2056 a += b;
2057 return a;
2060 inline APInt operator+(const APInt &a, APInt &&b) {
2061 b += a;
2062 return std::move(b);
2065 inline APInt operator+(APInt a, uint64_t RHS) {
2066 a += RHS;
2067 return a;
2070 inline APInt operator+(uint64_t LHS, APInt b) {
2071 b += LHS;
2072 return b;
2075 inline APInt operator-(APInt a, const APInt &b) {
2076 a -= b;
2077 return a;
2080 inline APInt operator-(const APInt &a, APInt &&b) {
2081 b.negate();
2082 b += a;
2083 return std::move(b);
2086 inline APInt operator-(APInt a, uint64_t RHS) {
2087 a -= RHS;
2088 return a;
2091 inline APInt operator-(uint64_t LHS, APInt b) {
2092 b.negate();
2093 b += LHS;
2094 return b;
2097 inline APInt operator*(APInt a, uint64_t RHS) {
2098 a *= RHS;
2099 return a;
2102 inline APInt operator*(uint64_t LHS, APInt b) {
2103 b *= LHS;
2104 return b;
2108 namespace APIntOps {
2110 /// Determine the smaller of two APInts considered to be signed.
2111 inline const APInt &smin(const APInt &A, const APInt &B) {
2112 return A.slt(B) ? A : B;
2115 /// Determine the larger of two APInts considered to be signed.
2116 inline const APInt &smax(const APInt &A, const APInt &B) {
2117 return A.sgt(B) ? A : B;
2120 /// Determine the smaller of two APInts considered to be signed.
2121 inline const APInt &umin(const APInt &A, const APInt &B) {
2122 return A.ult(B) ? A : B;
2125 /// Determine the larger of two APInts considered to be unsigned.
2126 inline const APInt &umax(const APInt &A, const APInt &B) {
2127 return A.ugt(B) ? A : B;
2130 /// Compute GCD of two unsigned APInt values.
2132 /// This function returns the greatest common divisor of the two APInt values
2133 /// using Stein's algorithm.
2135 /// \returns the greatest common divisor of A and B.
2136 APInt GreatestCommonDivisor(APInt A, APInt B);
2138 /// Converts the given APInt to a double value.
2140 /// Treats the APInt as an unsigned value for conversion purposes.
2141 inline double RoundAPIntToDouble(const APInt &APIVal) {
2142 return APIVal.roundToDouble();
2145 /// Converts the given APInt to a double value.
2147 /// Treats the APInt as a signed value for conversion purposes.
2148 inline double RoundSignedAPIntToDouble(const APInt &APIVal) {
2149 return APIVal.signedRoundToDouble();
2152 /// Converts the given APInt to a float vlalue.
2153 inline float RoundAPIntToFloat(const APInt &APIVal) {
2154 return float(RoundAPIntToDouble(APIVal));
2157 /// Converts the given APInt to a float value.
2159 /// Treast the APInt as a signed value for conversion purposes.
2160 inline float RoundSignedAPIntToFloat(const APInt &APIVal) {
2161 return float(APIVal.signedRoundToDouble());
2164 /// Converts the given double value into a APInt.
2166 /// This function convert a double value to an APInt value.
2167 APInt RoundDoubleToAPInt(double Double, unsigned width);
2169 /// Converts a float value into a APInt.
2171 /// Converts a float value into an APInt value.
2172 inline APInt RoundFloatToAPInt(float Float, unsigned width) {
2173 return RoundDoubleToAPInt(double(Float), width);
2176 /// Return A unsign-divided by B, rounded by the given rounding mode.
2177 APInt RoundingUDiv(const APInt &A, const APInt &B, APInt::Rounding RM);
2179 /// Return A sign-divided by B, rounded by the given rounding mode.
2180 APInt RoundingSDiv(const APInt &A, const APInt &B, APInt::Rounding RM);
2182 /// Let q(n) = An^2 + Bn + C, and BW = bit width of the value range
2183 /// (e.g. 32 for i32).
2184 /// This function finds the smallest number n, such that
2185 /// (a) n >= 0 and q(n) = 0, or
2186 /// (b) n >= 1 and q(n-1) and q(n), when evaluated in the set of all
2187 /// integers, belong to two different intervals [Rk, Rk+R),
2188 /// where R = 2^BW, and k is an integer.
2189 /// The idea here is to find when q(n) "overflows" 2^BW, while at the
2190 /// same time "allowing" subtraction. In unsigned modulo arithmetic a
2191 /// subtraction (treated as addition of negated numbers) would always
2192 /// count as an overflow, but here we want to allow values to decrease
2193 /// and increase as long as they are within the same interval.
2194 /// Specifically, adding of two negative numbers should not cause an
2195 /// overflow (as long as the magnitude does not exceed the bith width).
2196 /// On the other hand, given a positive number, adding a negative
2197 /// number to it can give a negative result, which would cause the
2198 /// value to go from [-2^BW, 0) to [0, 2^BW). In that sense, zero is
2199 /// treated as a special case of an overflow.
2201 /// This function returns None if after finding k that minimizes the
2202 /// positive solution to q(n) = kR, both solutions are contained between
2203 /// two consecutive integers.
2205 /// There are cases where q(n) > T, and q(n+1) < T (assuming evaluation
2206 /// in arithmetic modulo 2^BW, and treating the values as signed) by the
2207 /// virtue of *signed* overflow. This function will *not* find such an n,
2208 /// however it may find a value of n satisfying the inequalities due to
2209 /// an *unsigned* overflow (if the values are treated as unsigned).
2210 /// To find a solution for a signed overflow, treat it as a problem of
2211 /// finding an unsigned overflow with a range with of BW-1.
2213 /// The returned value may have a different bit width from the input
2214 /// coefficients.
2215 Optional<APInt> SolveQuadraticEquationWrap(APInt A, APInt B, APInt C,
2216 unsigned RangeWidth);
2217 } // End of APIntOps namespace
2219 // See friend declaration above. This additional declaration is required in
2220 // order to compile LLVM with IBM xlC compiler.
2221 hash_code hash_value(const APInt &Arg);
2223 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
2224 /// with the integer held in IntVal.
2225 void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst, unsigned StoreBytes);
2227 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
2228 /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
2229 void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes);
2231 } // namespace llvm
2233 #endif