LLVM 20.0.0git
APInt.h
Go to the documentation of this file.
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//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_ADT_APINT_H
16#define LLVM_ADT_APINT_H
17
21#include <cassert>
22#include <climits>
23#include <cstring>
24#include <optional>
25#include <utility>
26
27namespace llvm {
28class FoldingSetNodeID;
29class StringRef;
30class hash_code;
31class raw_ostream;
32struct Align;
33class DynamicAPInt;
34
35template <typename T> class SmallVectorImpl;
36template <typename T> class ArrayRef;
37template <typename T, typename Enable> struct DenseMapInfo;
38
39class APInt;
40
41inline APInt operator-(APInt);
42
43//===----------------------------------------------------------------------===//
44// APInt Class
45//===----------------------------------------------------------------------===//
46
47/// Class for arbitrary precision integers.
48///
49/// APInt is a functional replacement for common case unsigned integer type like
50/// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width
51/// integer sizes and large integer value types such as 3-bits, 15-bits, or more
52/// than 64-bits of precision. APInt provides a variety of arithmetic operators
53/// and methods to manipulate integer values of any bit-width. It supports both
54/// the typical integer arithmetic and comparison operations as well as bitwise
55/// manipulation.
56///
57/// The class has several invariants worth noting:
58/// * All bit, byte, and word positions are zero-based.
59/// * Once the bit width is set, it doesn't change except by the Truncate,
60/// SignExtend, or ZeroExtend operations.
61/// * All binary operators must be on APInt instances of the same bit width.
62/// Attempting to use these operators on instances with different bit
63/// widths will yield an assertion.
64/// * The value is stored canonically as an unsigned value. For operations
65/// where it makes a difference, there are both signed and unsigned variants
66/// of the operation. For example, sdiv and udiv. However, because the bit
67/// widths must be the same, operations such as Mul and Add produce the same
68/// results regardless of whether the values are interpreted as signed or
69/// not.
70/// * In general, the class tries to follow the style of computation that LLVM
71/// uses in its IR. This simplifies its use for LLVM.
72/// * APInt supports zero-bit-width values, but operations that require bits
73/// are not defined on it (e.g. you cannot ask for the sign of a zero-bit
74/// integer). This means that operations like zero extension and logical
75/// shifts are defined, but sign extension and ashr is not. Zero bit values
76/// compare and hash equal to themselves, and countLeadingZeros returns 0.
77///
78class [[nodiscard]] APInt {
79public:
81
82 /// This enum is used to hold the constants we needed for APInt.
83 enum : unsigned {
84 /// Byte size of a word.
85 APINT_WORD_SIZE = sizeof(WordType),
86 /// Bits in a word.
87 APINT_BITS_PER_WORD = APINT_WORD_SIZE * CHAR_BIT
88 };
89
90 enum class Rounding {
91 DOWN,
92 TOWARD_ZERO,
93 UP,
94 };
95
96 static constexpr WordType WORDTYPE_MAX = ~WordType(0);
97
98 /// \name Constructors
99 /// @{
100
101 /// Create a new APInt of numBits width, initialized as val.
102 ///
103 /// If isSigned is true then val is treated as if it were a signed value
104 /// (i.e. as an int64_t) and the appropriate sign extension to the bit width
105 /// will be done. Otherwise, no sign extension occurs (high order bits beyond
106 /// the range of val are zero filled).
107 ///
108 /// \param numBits the bit width of the constructed APInt
109 /// \param val the initial value of the APInt
110 /// \param isSigned how to treat signedness of val
111 APInt(unsigned numBits, uint64_t val, bool isSigned = false)
112 : BitWidth(numBits) {
113 if (isSingleWord()) {
114 U.VAL = val;
116 } else {
117 initSlowCase(val, isSigned);
118 }
119 }
120
121 /// Construct an APInt of numBits width, initialized as bigVal[].
122 ///
123 /// Note that bigVal.size() can be smaller or larger than the corresponding
124 /// bit width but any extraneous bits will be dropped.
125 ///
126 /// \param numBits the bit width of the constructed APInt
127 /// \param bigVal a sequence of words to form the initial value of the APInt
128 APInt(unsigned numBits, ArrayRef<uint64_t> bigVal);
129
130 /// Equivalent to APInt(numBits, ArrayRef<uint64_t>(bigVal, numWords)), but
131 /// deprecated because this constructor is prone to ambiguity with the
132 /// APInt(unsigned, uint64_t, bool) constructor.
133 ///
134 /// If this overload is ever deleted, care should be taken to prevent calls
135 /// from being incorrectly captured by the APInt(unsigned, uint64_t, bool)
136 /// constructor.
137 APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[]);
138
139 /// Construct an APInt from a string representation.
140 ///
141 /// This constructor interprets the string \p str in the given radix. The
142 /// interpretation stops when the first character that is not suitable for the
143 /// radix is encountered, or the end of the string. Acceptable radix values
144 /// are 2, 8, 10, 16, and 36. It is an error for the value implied by the
145 /// string to require more bits than numBits.
146 ///
147 /// \param numBits the bit width of the constructed APInt
148 /// \param str the string to be interpreted
149 /// \param radix the radix to use for the conversion
150 APInt(unsigned numBits, StringRef str, uint8_t radix);
151
152 /// Default constructor that creates an APInt with a 1-bit zero value.
153 explicit APInt() { U.VAL = 0; }
154
155 /// Copy Constructor.
156 APInt(const APInt &that) : BitWidth(that.BitWidth) {
157 if (isSingleWord())
158 U.VAL = that.U.VAL;
159 else
160 initSlowCase(that);
161 }
162
163 /// Move Constructor.
164 APInt(APInt &&that) : BitWidth(that.BitWidth) {
165 memcpy(&U, &that.U, sizeof(U));
166 that.BitWidth = 0;
167 }
168
169 /// Destructor.
171 if (needsCleanup())
172 delete[] U.pVal;
173 }
174
175 /// @}
176 /// \name Value Generators
177 /// @{
178
179 /// Get the '0' value for the specified bit-width.
180 static APInt getZero(unsigned numBits) { return APInt(numBits, 0); }
181
182 /// Return an APInt zero bits wide.
183 static APInt getZeroWidth() { return getZero(0); }
184
185 /// Gets maximum unsigned value of APInt for specific bit width.
186 static APInt getMaxValue(unsigned numBits) { return getAllOnes(numBits); }
187
188 /// Gets maximum signed value of APInt for a specific bit width.
189 static APInt getSignedMaxValue(unsigned numBits) {
190 APInt API = getAllOnes(numBits);
191 API.clearBit(numBits - 1);
192 return API;
193 }
194
195 /// Gets minimum unsigned value of APInt for a specific bit width.
196 static APInt getMinValue(unsigned numBits) { return APInt(numBits, 0); }
197
198 /// Gets minimum signed value of APInt for a specific bit width.
199 static APInt getSignedMinValue(unsigned numBits) {
200 APInt API(numBits, 0);
201 API.setBit(numBits - 1);
202 return API;
203 }
204
205 /// Get the SignMask for a specific bit width.
206 ///
207 /// This is just a wrapper function of getSignedMinValue(), and it helps code
208 /// readability when we want to get a SignMask.
209 static APInt getSignMask(unsigned BitWidth) {
210 return getSignedMinValue(BitWidth);
211 }
212
213 /// Return an APInt of a specified width with all bits set.
214 static APInt getAllOnes(unsigned numBits) {
215 return APInt(numBits, WORDTYPE_MAX, true);
216 }
217
218 /// Return an APInt with exactly one bit set in the result.
219 static APInt getOneBitSet(unsigned numBits, unsigned BitNo) {
220 APInt Res(numBits, 0);
221 Res.setBit(BitNo);
222 return Res;
223 }
224
225 /// Get a value with a block of bits set.
226 ///
227 /// Constructs an APInt value that has a contiguous range of bits set. The
228 /// bits from loBit (inclusive) to hiBit (exclusive) will be set. All other
229 /// bits will be zero. For example, with parameters(32, 0, 16) you would get
230 /// 0x0000FFFF. Please call getBitsSetWithWrap if \p loBit may be greater than
231 /// \p hiBit.
232 ///
233 /// \param numBits the intended bit width of the result
234 /// \param loBit the index of the lowest bit set.
235 /// \param hiBit the index of the highest bit set.
236 ///
237 /// \returns An APInt value with the requested bits set.
238 static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit) {
239 APInt Res(numBits, 0);
240 Res.setBits(loBit, hiBit);
241 return Res;
242 }
243
244 /// Wrap version of getBitsSet.
245 /// If \p hiBit is bigger than \p loBit, this is same with getBitsSet.
246 /// If \p hiBit is not bigger than \p loBit, the set bits "wrap". For example,
247 /// with parameters (32, 28, 4), you would get 0xF000000F.
248 /// If \p hiBit is equal to \p loBit, you would get a result with all bits
249 /// set.
250 static APInt getBitsSetWithWrap(unsigned numBits, unsigned loBit,
251 unsigned hiBit) {
252 APInt Res(numBits, 0);
253 Res.setBitsWithWrap(loBit, hiBit);
254 return Res;
255 }
256
257 /// Constructs an APInt value that has a contiguous range of bits set. The
258 /// bits from loBit (inclusive) to numBits (exclusive) will be set. All other
259 /// bits will be zero. For example, with parameters(32, 12) you would get
260 /// 0xFFFFF000.
261 ///
262 /// \param numBits the intended bit width of the result
263 /// \param loBit the index of the lowest bit to set.
264 ///
265 /// \returns An APInt value with the requested bits set.
266 static APInt getBitsSetFrom(unsigned numBits, unsigned loBit) {
267 APInt Res(numBits, 0);
268 Res.setBitsFrom(loBit);
269 return Res;
270 }
271
272 /// Constructs an APInt value that has the top hiBitsSet bits set.
273 ///
274 /// \param numBits the bitwidth of the result
275 /// \param hiBitsSet the number of high-order bits set in the result.
276 static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet) {
277 APInt Res(numBits, 0);
278 Res.setHighBits(hiBitsSet);
279 return Res;
280 }
281
282 /// Constructs an APInt value that has the bottom loBitsSet bits set.
283 ///
284 /// \param numBits the bitwidth of the result
285 /// \param loBitsSet the number of low-order bits set in the result.
286 static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet) {
287 APInt Res(numBits, 0);
288 Res.setLowBits(loBitsSet);
289 return Res;
290 }
291
292 /// Return a value containing V broadcasted over NewLen bits.
293 static APInt getSplat(unsigned NewLen, const APInt &V);
294
295 /// @}
296 /// \name Value Tests
297 /// @{
298
299 /// Determine if this APInt just has one word to store value.
300 ///
301 /// \returns true if the number of bits <= 64, false otherwise.
302 bool isSingleWord() const { return BitWidth <= APINT_BITS_PER_WORD; }
303
304 /// Determine sign of this APInt.
305 ///
306 /// This tests the high bit of this APInt to determine if it is set.
307 ///
308 /// \returns true if this APInt is negative, false otherwise
309 bool isNegative() const { return (*this)[BitWidth - 1]; }
310
311 /// Determine if this APInt Value is non-negative (>= 0)
312 ///
313 /// This tests the high bit of the APInt to determine if it is unset.
314 bool isNonNegative() const { return !isNegative(); }
315
316 /// Determine if sign bit of this APInt is set.
317 ///
318 /// This tests the high bit of this APInt to determine if it is set.
319 ///
320 /// \returns true if this APInt has its sign bit set, false otherwise.
321 bool isSignBitSet() const { return (*this)[BitWidth - 1]; }
322
323 /// Determine if sign bit of this APInt is clear.
324 ///
325 /// This tests the high bit of this APInt to determine if it is clear.
326 ///
327 /// \returns true if this APInt has its sign bit clear, false otherwise.
328 bool isSignBitClear() const { return !isSignBitSet(); }
329
330 /// Determine if this APInt Value is positive.
331 ///
332 /// This tests if the value of this APInt is positive (> 0). Note
333 /// that 0 is not a positive value.
334 ///
335 /// \returns true if this APInt is positive.
336 bool isStrictlyPositive() const { return isNonNegative() && !isZero(); }
337
338 /// Determine if this APInt Value is non-positive (<= 0).
339 ///
340 /// \returns true if this APInt is non-positive.
341 bool isNonPositive() const { return !isStrictlyPositive(); }
342
343 /// Determine if this APInt Value only has the specified bit set.
344 ///
345 /// \returns true if this APInt only has the specified bit set.
346 bool isOneBitSet(unsigned BitNo) const {
347 return (*this)[BitNo] && popcount() == 1;
348 }
349
350 /// Determine if all bits are set. This is true for zero-width values.
351 bool isAllOnes() const {
352 if (BitWidth == 0)
353 return true;
354 if (isSingleWord())
355 return U.VAL == WORDTYPE_MAX >> (APINT_BITS_PER_WORD - BitWidth);
356 return countTrailingOnesSlowCase() == BitWidth;
357 }
358
359 /// Determine if this value is zero, i.e. all bits are clear.
360 bool isZero() const {
361 if (isSingleWord())
362 return U.VAL == 0;
363 return countLeadingZerosSlowCase() == BitWidth;
364 }
365
366 /// Determine if this is a value of 1.
367 ///
368 /// This checks to see if the value of this APInt is one.
369 bool isOne() const {
370 if (isSingleWord())
371 return U.VAL == 1;
372 return countLeadingZerosSlowCase() == BitWidth - 1;
373 }
374
375 /// Determine if this is the largest unsigned value.
376 ///
377 /// This checks to see if the value of this APInt is the maximum unsigned
378 /// value for the APInt's bit width.
379 bool isMaxValue() const { return isAllOnes(); }
380
381 /// Determine if this is the largest signed value.
382 ///
383 /// This checks to see if the value of this APInt is the maximum signed
384 /// value for the APInt's bit width.
385 bool isMaxSignedValue() const {
386 if (isSingleWord()) {
387 assert(BitWidth && "zero width values not allowed");
388 return U.VAL == ((WordType(1) << (BitWidth - 1)) - 1);
389 }
390 return !isNegative() && countTrailingOnesSlowCase() == BitWidth - 1;
391 }
392
393 /// Determine if this is the smallest unsigned value.
394 ///
395 /// This checks to see if the value of this APInt is the minimum unsigned
396 /// value for the APInt's bit width.
397 bool isMinValue() const { return isZero(); }
398
399 /// Determine if this is the smallest signed value.
400 ///
401 /// This checks to see if the value of this APInt is the minimum signed
402 /// value for the APInt's bit width.
403 bool isMinSignedValue() const {
404 if (isSingleWord()) {
405 assert(BitWidth && "zero width values not allowed");
406 return U.VAL == (WordType(1) << (BitWidth - 1));
407 }
408 return isNegative() && countTrailingZerosSlowCase() == BitWidth - 1;
409 }
410
411 /// Check if this APInt has an N-bits unsigned integer value.
412 bool isIntN(unsigned N) const { return getActiveBits() <= N; }
413
414 /// Check if this APInt has an N-bits signed integer value.
415 bool isSignedIntN(unsigned N) const { return getSignificantBits() <= N; }
416
417 /// Check if this APInt's value is a power of two greater than zero.
418 ///
419 /// \returns true if the argument APInt value is a power of two > 0.
420 bool isPowerOf2() const {
421 if (isSingleWord()) {
422 assert(BitWidth && "zero width values not allowed");
423 return isPowerOf2_64(U.VAL);
424 }
425 return countPopulationSlowCase() == 1;
426 }
427
428 /// Check if this APInt's negated value is a power of two greater than zero.
429 bool isNegatedPowerOf2() const {
430 assert(BitWidth && "zero width values not allowed");
431 if (isNonNegative())
432 return false;
433 // NegatedPowerOf2 - shifted mask in the top bits.
434 unsigned LO = countl_one();
435 unsigned TZ = countr_zero();
436 return (LO + TZ) == BitWidth;
437 }
438
439 /// Checks if this APInt -interpreted as an address- is aligned to the
440 /// provided value.
441 bool isAligned(Align A) const;
442
443 /// Check if the APInt's value is returned by getSignMask.
444 ///
445 /// \returns true if this is the value returned by getSignMask.
446 bool isSignMask() const { return isMinSignedValue(); }
447
448 /// Convert APInt to a boolean value.
449 ///
450 /// This converts the APInt to a boolean value as a test against zero.
451 bool getBoolValue() const { return !isZero(); }
452
453 /// If this value is smaller than the specified limit, return it, otherwise
454 /// return the limit value. This causes the value to saturate to the limit.
456 return ugt(Limit) ? Limit : getZExtValue();
457 }
458
459 /// Check if the APInt consists of a repeated bit pattern.
460 ///
461 /// e.g. 0x01010101 satisfies isSplat(8).
462 /// \param SplatSizeInBits The size of the pattern in bits. Must divide bit
463 /// width without remainder.
464 bool isSplat(unsigned SplatSizeInBits) const;
465
466 /// \returns true if this APInt value is a sequence of \param numBits ones
467 /// starting at the least significant bit with the remainder zero.
468 bool isMask(unsigned numBits) const {
469 assert(numBits != 0 && "numBits must be non-zero");
470 assert(numBits <= BitWidth && "numBits out of range");
471 if (isSingleWord())
472 return U.VAL == (WORDTYPE_MAX >> (APINT_BITS_PER_WORD - numBits));
473 unsigned Ones = countTrailingOnesSlowCase();
474 return (numBits == Ones) &&
475 ((Ones + countLeadingZerosSlowCase()) == BitWidth);
476 }
477
478 /// \returns true if this APInt is a non-empty sequence of ones starting at
479 /// the least significant bit with the remainder zero.
480 /// Ex. isMask(0x0000FFFFU) == true.
481 bool isMask() const {
482 if (isSingleWord())
483 return isMask_64(U.VAL);
484 unsigned Ones = countTrailingOnesSlowCase();
485 return (Ones > 0) && ((Ones + countLeadingZerosSlowCase()) == BitWidth);
486 }
487
488 /// Return true if this APInt value contains a non-empty sequence of ones with
489 /// the remainder zero.
490 bool isShiftedMask() const {
491 if (isSingleWord())
492 return isShiftedMask_64(U.VAL);
493 unsigned Ones = countPopulationSlowCase();
494 unsigned LeadZ = countLeadingZerosSlowCase();
495 return (Ones + LeadZ + countr_zero()) == BitWidth;
496 }
497
498 /// Return true if this APInt value contains a non-empty sequence of ones with
499 /// the remainder zero. If true, \p MaskIdx will specify the index of the
500 /// lowest set bit and \p MaskLen is updated to specify the length of the
501 /// mask, else neither are updated.
502 bool isShiftedMask(unsigned &MaskIdx, unsigned &MaskLen) const {
503 if (isSingleWord())
504 return isShiftedMask_64(U.VAL, MaskIdx, MaskLen);
505 unsigned Ones = countPopulationSlowCase();
506 unsigned LeadZ = countLeadingZerosSlowCase();
507 unsigned TrailZ = countTrailingZerosSlowCase();
508 if ((Ones + LeadZ + TrailZ) != BitWidth)
509 return false;
510 MaskLen = Ones;
511 MaskIdx = TrailZ;
512 return true;
513 }
514
515 /// Compute an APInt containing numBits highbits from this APInt.
516 ///
517 /// Get an APInt with the same BitWidth as this APInt, just zero mask the low
518 /// bits and right shift to the least significant bit.
519 ///
520 /// \returns the high "numBits" bits of this APInt.
521 APInt getHiBits(unsigned numBits) const;
522
523 /// Compute an APInt containing numBits lowbits from this APInt.
524 ///
525 /// Get an APInt with the same BitWidth as this APInt, just zero mask the high
526 /// bits.
527 ///
528 /// \returns the low "numBits" bits of this APInt.
529 APInt getLoBits(unsigned numBits) const;
530
531 /// Determine if two APInts have the same value, after zero-extending
532 /// one of them (if needed!) to ensure that the bit-widths match.
533 static bool isSameValue(const APInt &I1, const APInt &I2) {
534 if (I1.getBitWidth() == I2.getBitWidth())
535 return I1 == I2;
536
537 if (I1.getBitWidth() > I2.getBitWidth())
538 return I1 == I2.zext(I1.getBitWidth());
539
540 return I1.zext(I2.getBitWidth()) == I2;
541 }
542
543 /// Overload to compute a hash_code for an APInt value.
544 friend hash_code hash_value(const APInt &Arg);
545
546 /// This function returns a pointer to the internal storage of the APInt.
547 /// This is useful for writing out the APInt in binary form without any
548 /// conversions.
549 const uint64_t *getRawData() const {
550 if (isSingleWord())
551 return &U.VAL;
552 return &U.pVal[0];
553 }
554
555 /// @}
556 /// \name Unary Operators
557 /// @{
558
559 /// Postfix increment operator. Increment *this by 1.
560 ///
561 /// \returns a new APInt value representing the original value of *this.
563 APInt API(*this);
564 ++(*this);
565 return API;
566 }
567
568 /// Prefix increment operator.
569 ///
570 /// \returns *this incremented by one
571 APInt &operator++();
572
573 /// Postfix decrement operator. Decrement *this by 1.
574 ///
575 /// \returns a new APInt value representing the original value of *this.
577 APInt API(*this);
578 --(*this);
579 return API;
580 }
581
582 /// Prefix decrement operator.
583 ///
584 /// \returns *this decremented by one.
585 APInt &operator--();
586
587 /// Logical negation operation on this APInt returns true if zero, like normal
588 /// integers.
589 bool operator!() const { return isZero(); }
590
591 /// @}
592 /// \name Assignment Operators
593 /// @{
594
595 /// Copy assignment operator.
596 ///
597 /// \returns *this after assignment of RHS.
599 // The common case (both source or dest being inline) doesn't require
600 // allocation or deallocation.
601 if (isSingleWord() && RHS.isSingleWord()) {
602 U.VAL = RHS.U.VAL;
603 BitWidth = RHS.BitWidth;
604 return *this;
605 }
606
607 assignSlowCase(RHS);
608 return *this;
609 }
610
611 /// Move assignment operator.
613#ifdef EXPENSIVE_CHECKS
614 // Some std::shuffle implementations still do self-assignment.
615 if (this == &that)
616 return *this;
617#endif
618 assert(this != &that && "Self-move not supported");
619 if (!isSingleWord())
620 delete[] U.pVal;
621
622 // Use memcpy so that type based alias analysis sees both VAL and pVal
623 // as modified.
624 memcpy(&U, &that.U, sizeof(U));
625
626 BitWidth = that.BitWidth;
627 that.BitWidth = 0;
628 return *this;
629 }
630
631 /// Assignment operator.
632 ///
633 /// The RHS value is assigned to *this. If the significant bits in RHS exceed
634 /// the bit width, the excess bits are truncated. If the bit width is larger
635 /// than 64, the value is zero filled in the unspecified high order bits.
636 ///
637 /// \returns *this after assignment of RHS value.
639 if (isSingleWord()) {
640 U.VAL = RHS;
641 return clearUnusedBits();
642 }
643 U.pVal[0] = RHS;
644 memset(U.pVal + 1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
645 return *this;
646 }
647
648 /// Bitwise AND assignment operator.
649 ///
650 /// Performs a bitwise AND operation on this APInt and RHS. The result is
651 /// assigned to *this.
652 ///
653 /// \returns *this after ANDing with RHS.
655 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
656 if (isSingleWord())
657 U.VAL &= RHS.U.VAL;
658 else
659 andAssignSlowCase(RHS);
660 return *this;
661 }
662
663 /// Bitwise AND assignment operator.
664 ///
665 /// Performs a bitwise AND operation on this APInt and RHS. RHS is
666 /// logically zero-extended or truncated to match the bit-width of
667 /// the LHS.
669 if (isSingleWord()) {
670 U.VAL &= RHS;
671 return *this;
672 }
673 U.pVal[0] &= RHS;
674 memset(U.pVal + 1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
675 return *this;
676 }
677
678 /// Bitwise OR assignment operator.
679 ///
680 /// Performs a bitwise OR operation on this APInt and RHS. The result is
681 /// assigned *this;
682 ///
683 /// \returns *this after ORing with RHS.
685 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
686 if (isSingleWord())
687 U.VAL |= RHS.U.VAL;
688 else
689 orAssignSlowCase(RHS);
690 return *this;
691 }
692
693 /// Bitwise OR assignment operator.
694 ///
695 /// Performs a bitwise OR operation on this APInt and RHS. RHS is
696 /// logically zero-extended or truncated to match the bit-width of
697 /// the LHS.
699 if (isSingleWord()) {
700 U.VAL |= RHS;
701 return clearUnusedBits();
702 }
703 U.pVal[0] |= RHS;
704 return *this;
705 }
706
707 /// Bitwise XOR assignment operator.
708 ///
709 /// Performs a bitwise XOR operation on this APInt and RHS. The result is
710 /// assigned to *this.
711 ///
712 /// \returns *this after XORing with RHS.
714 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
715 if (isSingleWord())
716 U.VAL ^= RHS.U.VAL;
717 else
718 xorAssignSlowCase(RHS);
719 return *this;
720 }
721
722 /// Bitwise XOR assignment operator.
723 ///
724 /// Performs a bitwise XOR operation on this APInt and RHS. RHS is
725 /// logically zero-extended or truncated to match the bit-width of
726 /// the LHS.
728 if (isSingleWord()) {
729 U.VAL ^= RHS;
730 return clearUnusedBits();
731 }
732 U.pVal[0] ^= RHS;
733 return *this;
734 }
735
736 /// Multiplication assignment operator.
737 ///
738 /// Multiplies this APInt by RHS and assigns the result to *this.
739 ///
740 /// \returns *this
741 APInt &operator*=(const APInt &RHS);
743
744 /// Addition assignment operator.
745 ///
746 /// Adds RHS to *this and assigns the result to *this.
747 ///
748 /// \returns *this
749 APInt &operator+=(const APInt &RHS);
751
752 /// Subtraction assignment operator.
753 ///
754 /// Subtracts RHS from *this and assigns the result to *this.
755 ///
756 /// \returns *this
757 APInt &operator-=(const APInt &RHS);
759
760 /// Left-shift assignment function.
761 ///
762 /// Shifts *this left by shiftAmt and assigns the result to *this.
763 ///
764 /// \returns *this after shifting left by ShiftAmt
765 APInt &operator<<=(unsigned ShiftAmt) {
766 assert(ShiftAmt <= BitWidth && "Invalid shift amount");
767 if (isSingleWord()) {
768 if (ShiftAmt == BitWidth)
769 U.VAL = 0;
770 else
771 U.VAL <<= ShiftAmt;
772 return clearUnusedBits();
773 }
774 shlSlowCase(ShiftAmt);
775 return *this;
776 }
777
778 /// Left-shift assignment function.
779 ///
780 /// Shifts *this left by shiftAmt and assigns the result to *this.
781 ///
782 /// \returns *this after shifting left by ShiftAmt
783 APInt &operator<<=(const APInt &ShiftAmt);
784
785 /// @}
786 /// \name Binary Operators
787 /// @{
788
789 /// Multiplication operator.
790 ///
791 /// Multiplies this APInt by RHS and returns the result.
792 APInt operator*(const APInt &RHS) const;
793
794 /// Left logical shift operator.
795 ///
796 /// Shifts this APInt left by \p Bits and returns the result.
797 APInt operator<<(unsigned Bits) const { return shl(Bits); }
798
799 /// Left logical shift operator.
800 ///
801 /// Shifts this APInt left by \p Bits and returns the result.
802 APInt operator<<(const APInt &Bits) const { return shl(Bits); }
803
804 /// Arithmetic right-shift function.
805 ///
806 /// Arithmetic right-shift this APInt by shiftAmt.
807 APInt ashr(unsigned ShiftAmt) const {
808 APInt R(*this);
809 R.ashrInPlace(ShiftAmt);
810 return R;
811 }
812
813 /// Arithmetic right-shift this APInt by ShiftAmt in place.
814 void ashrInPlace(unsigned ShiftAmt) {
815 assert(ShiftAmt <= BitWidth && "Invalid shift amount");
816 if (isSingleWord()) {
817 int64_t SExtVAL = SignExtend64(U.VAL, BitWidth);
818 if (ShiftAmt == BitWidth)
819 U.VAL = SExtVAL >> (APINT_BITS_PER_WORD - 1); // Fill with sign bit.
820 else
821 U.VAL = SExtVAL >> ShiftAmt;
823 return;
824 }
825 ashrSlowCase(ShiftAmt);
826 }
827
828 /// Logical right-shift function.
829 ///
830 /// Logical right-shift this APInt by shiftAmt.
831 APInt lshr(unsigned shiftAmt) const {
832 APInt R(*this);
833 R.lshrInPlace(shiftAmt);
834 return R;
835 }
836
837 /// Logical right-shift this APInt by ShiftAmt in place.
838 void lshrInPlace(unsigned ShiftAmt) {
839 assert(ShiftAmt <= BitWidth && "Invalid shift amount");
840 if (isSingleWord()) {
841 if (ShiftAmt == BitWidth)
842 U.VAL = 0;
843 else
844 U.VAL >>= ShiftAmt;
845 return;
846 }
847 lshrSlowCase(ShiftAmt);
848 }
849
850 /// Left-shift function.
851 ///
852 /// Left-shift this APInt by shiftAmt.
853 APInt shl(unsigned shiftAmt) const {
854 APInt R(*this);
855 R <<= shiftAmt;
856 return R;
857 }
858
859 /// relative logical shift right
860 APInt relativeLShr(int RelativeShift) const {
861 return RelativeShift > 0 ? lshr(RelativeShift) : shl(-RelativeShift);
862 }
863
864 /// relative logical shift left
865 APInt relativeLShl(int RelativeShift) const {
866 return relativeLShr(-RelativeShift);
867 }
868
869 /// relative arithmetic shift right
870 APInt relativeAShr(int RelativeShift) const {
871 return RelativeShift > 0 ? ashr(RelativeShift) : shl(-RelativeShift);
872 }
873
874 /// relative arithmetic shift left
875 APInt relativeAShl(int RelativeShift) const {
876 return relativeAShr(-RelativeShift);
877 }
878
879 /// Rotate left by rotateAmt.
880 APInt rotl(unsigned rotateAmt) const;
881
882 /// Rotate right by rotateAmt.
883 APInt rotr(unsigned rotateAmt) const;
884
885 /// Arithmetic right-shift function.
886 ///
887 /// Arithmetic right-shift this APInt by shiftAmt.
888 APInt ashr(const APInt &ShiftAmt) const {
889 APInt R(*this);
890 R.ashrInPlace(ShiftAmt);
891 return R;
892 }
893
894 /// Arithmetic right-shift this APInt by shiftAmt in place.
895 void ashrInPlace(const APInt &shiftAmt);
896
897 /// Logical right-shift function.
898 ///
899 /// Logical right-shift this APInt by shiftAmt.
900 APInt lshr(const APInt &ShiftAmt) const {
901 APInt R(*this);
902 R.lshrInPlace(ShiftAmt);
903 return R;
904 }
905
906 /// Logical right-shift this APInt by ShiftAmt in place.
907 void lshrInPlace(const APInt &ShiftAmt);
908
909 /// Left-shift function.
910 ///
911 /// Left-shift this APInt by shiftAmt.
912 APInt shl(const APInt &ShiftAmt) const {
913 APInt R(*this);
914 R <<= ShiftAmt;
915 return R;
916 }
917
918 /// Rotate left by rotateAmt.
919 APInt rotl(const APInt &rotateAmt) const;
920
921 /// Rotate right by rotateAmt.
922 APInt rotr(const APInt &rotateAmt) const;
923
924 /// Concatenate the bits from "NewLSB" onto the bottom of *this. This is
925 /// equivalent to:
926 /// (this->zext(NewWidth) << NewLSB.getBitWidth()) | NewLSB.zext(NewWidth)
927 APInt concat(const APInt &NewLSB) const {
928 /// If the result will be small, then both the merged values are small.
929 unsigned NewWidth = getBitWidth() + NewLSB.getBitWidth();
930 if (NewWidth <= APINT_BITS_PER_WORD)
931 return APInt(NewWidth, (U.VAL << NewLSB.getBitWidth()) | NewLSB.U.VAL);
932 return concatSlowCase(NewLSB);
933 }
934
935 /// Unsigned division operation.
936 ///
937 /// Perform an unsigned divide operation on this APInt by RHS. Both this and
938 /// RHS are treated as unsigned quantities for purposes of this division.
939 ///
940 /// \returns a new APInt value containing the division result, rounded towards
941 /// zero.
942 APInt udiv(const APInt &RHS) const;
943 APInt udiv(uint64_t RHS) const;
944
945 /// Signed division function for APInt.
946 ///
947 /// Signed divide this APInt by APInt RHS.
948 ///
949 /// The result is rounded towards zero.
950 APInt sdiv(const APInt &RHS) const;
951 APInt sdiv(int64_t RHS) const;
952
953 /// Unsigned remainder operation.
954 ///
955 /// Perform an unsigned remainder operation on this APInt with RHS being the
956 /// divisor. Both this and RHS are treated as unsigned quantities for purposes
957 /// of this operation.
958 ///
959 /// \returns a new APInt value containing the remainder result
960 APInt urem(const APInt &RHS) const;
961 uint64_t urem(uint64_t RHS) const;
962
963 /// Function for signed remainder operation.
964 ///
965 /// Signed remainder operation on APInt.
966 ///
967 /// Note that this is a true remainder operation and not a modulo operation
968 /// because the sign follows the sign of the dividend which is *this.
969 APInt srem(const APInt &RHS) const;
970 int64_t srem(int64_t RHS) const;
971
972 /// Dual division/remainder interface.
973 ///
974 /// Sometimes it is convenient to divide two APInt values and obtain both the
975 /// quotient and remainder. This function does both operations in the same
976 /// computation making it a little more efficient. The pair of input arguments
977 /// may overlap with the pair of output arguments. It is safe to call
978 /// udivrem(X, Y, X, Y), for example.
979 static void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient,
980 APInt &Remainder);
981 static void udivrem(const APInt &LHS, uint64_t RHS, APInt &Quotient,
982 uint64_t &Remainder);
983
984 static void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient,
985 APInt &Remainder);
986 static void sdivrem(const APInt &LHS, int64_t RHS, APInt &Quotient,
987 int64_t &Remainder);
988
989 // Operations that return overflow indicators.
990 APInt sadd_ov(const APInt &RHS, bool &Overflow) const;
991 APInt uadd_ov(const APInt &RHS, bool &Overflow) const;
992 APInt ssub_ov(const APInt &RHS, bool &Overflow) const;
993 APInt usub_ov(const APInt &RHS, bool &Overflow) const;
994 APInt sdiv_ov(const APInt &RHS, bool &Overflow) const;
995 APInt smul_ov(const APInt &RHS, bool &Overflow) const;
996 APInt umul_ov(const APInt &RHS, bool &Overflow) const;
997 APInt sshl_ov(const APInt &Amt, bool &Overflow) const;
998 APInt sshl_ov(unsigned Amt, bool &Overflow) const;
999 APInt ushl_ov(const APInt &Amt, bool &Overflow) const;
1000 APInt ushl_ov(unsigned Amt, bool &Overflow) const;
1001
1002 /// Signed integer floor division operation.
1003 ///
1004 /// Rounds towards negative infinity, i.e. 5 / -2 = -3. Iff minimum value
1005 /// divided by -1 set Overflow to true.
1006 APInt sfloordiv_ov(const APInt &RHS, bool &Overflow) const;
1007
1008 // Operations that saturate
1009 APInt sadd_sat(const APInt &RHS) const;
1010 APInt uadd_sat(const APInt &RHS) const;
1011 APInt ssub_sat(const APInt &RHS) const;
1012 APInt usub_sat(const APInt &RHS) const;
1013 APInt smul_sat(const APInt &RHS) const;
1014 APInt umul_sat(const APInt &RHS) const;
1015 APInt sshl_sat(const APInt &RHS) const;
1016 APInt sshl_sat(unsigned RHS) const;
1017 APInt ushl_sat(const APInt &RHS) const;
1018 APInt ushl_sat(unsigned RHS) const;
1019
1020 /// Array-indexing support.
1021 ///
1022 /// \returns the bit value at bitPosition
1023 bool operator[](unsigned bitPosition) const {
1024 assert(bitPosition < getBitWidth() && "Bit position out of bounds!");
1025 return (maskBit(bitPosition) & getWord(bitPosition)) != 0;
1026 }
1027
1028 /// @}
1029 /// \name Comparison Operators
1030 /// @{
1031
1032 /// Equality operator.
1033 ///
1034 /// Compares this APInt with RHS for the validity of the equality
1035 /// relationship.
1036 bool operator==(const APInt &RHS) const {
1037 assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths");
1038 if (isSingleWord())
1039 return U.VAL == RHS.U.VAL;
1040 return equalSlowCase(RHS);
1041 }
1042
1043 /// Equality operator.
1044 ///
1045 /// Compares this APInt with a uint64_t for the validity of the equality
1046 /// relationship.
1047 ///
1048 /// \returns true if *this == Val
1049 bool operator==(uint64_t Val) const {
1050 return (isSingleWord() || getActiveBits() <= 64) && getZExtValue() == Val;
1051 }
1052
1053 /// Equality comparison.
1054 ///
1055 /// Compares this APInt with RHS for the validity of the equality
1056 /// relationship.
1057 ///
1058 /// \returns true if *this == Val
1059 bool eq(const APInt &RHS) const { return (*this) == RHS; }
1060
1061 /// Inequality operator.
1062 ///
1063 /// Compares this APInt with RHS for the validity of the inequality
1064 /// relationship.
1065 ///
1066 /// \returns true if *this != Val
1067 bool operator!=(const APInt &RHS) const { return !((*this) == RHS); }
1068
1069 /// Inequality operator.
1070 ///
1071 /// Compares this APInt with a uint64_t for the validity of the inequality
1072 /// relationship.
1073 ///
1074 /// \returns true if *this != Val
1075 bool operator!=(uint64_t Val) const { return !((*this) == Val); }
1076
1077 /// Inequality comparison
1078 ///
1079 /// Compares this APInt with RHS for the validity of the inequality
1080 /// relationship.
1081 ///
1082 /// \returns true if *this != Val
1083 bool ne(const APInt &RHS) const { return !((*this) == RHS); }
1084
1085 /// Unsigned less than comparison
1086 ///
1087 /// Regards both *this and RHS as unsigned quantities and compares them for
1088 /// the validity of the less-than relationship.
1089 ///
1090 /// \returns true if *this < RHS when both are considered unsigned.
1091 bool ult(const APInt &RHS) const { return compare(RHS) < 0; }
1092
1093 /// Unsigned less than comparison
1094 ///
1095 /// Regards both *this as an unsigned quantity and compares it with RHS for
1096 /// the validity of the less-than relationship.
1097 ///
1098 /// \returns true if *this < RHS when considered unsigned.
1099 bool ult(uint64_t RHS) const {
1100 // Only need to check active bits if not a single word.
1101 return (isSingleWord() || getActiveBits() <= 64) && getZExtValue() < RHS;
1102 }
1103
1104 /// Signed less than comparison
1105 ///
1106 /// Regards both *this and RHS as signed quantities and compares them for
1107 /// validity of the less-than relationship.
1108 ///
1109 /// \returns true if *this < RHS when both are considered signed.
1110 bool slt(const APInt &RHS) const { return compareSigned(RHS) < 0; }
1111
1112 /// Signed less than comparison
1113 ///
1114 /// Regards both *this as a signed quantity and compares it with RHS for
1115 /// the validity of the less-than relationship.
1116 ///
1117 /// \returns true if *this < RHS when considered signed.
1118 bool slt(int64_t RHS) const {
1119 return (!isSingleWord() && getSignificantBits() > 64)
1120 ? isNegative()
1121 : getSExtValue() < RHS;
1122 }
1123
1124 /// Unsigned less or equal comparison
1125 ///
1126 /// Regards both *this and RHS as unsigned quantities and compares them for
1127 /// validity of the less-or-equal relationship.
1128 ///
1129 /// \returns true if *this <= RHS when both are considered unsigned.
1130 bool ule(const APInt &RHS) const { return compare(RHS) <= 0; }
1131
1132 /// Unsigned less or equal comparison
1133 ///
1134 /// Regards both *this as an unsigned quantity and compares it with RHS for
1135 /// the validity of the less-or-equal relationship.
1136 ///
1137 /// \returns true if *this <= RHS when considered unsigned.
1138 bool ule(uint64_t RHS) const { return !ugt(RHS); }
1139
1140 /// Signed less or equal comparison
1141 ///
1142 /// Regards both *this and RHS as signed quantities and compares them for
1143 /// validity of the less-or-equal relationship.
1144 ///
1145 /// \returns true if *this <= RHS when both are considered signed.
1146 bool sle(const APInt &RHS) const { return compareSigned(RHS) <= 0; }
1147
1148 /// Signed less or equal comparison
1149 ///
1150 /// Regards both *this as a signed quantity and compares it with RHS for the
1151 /// validity of the less-or-equal relationship.
1152 ///
1153 /// \returns true if *this <= RHS when considered signed.
1154 bool sle(uint64_t RHS) const { return !sgt(RHS); }
1155
1156 /// Unsigned greater than comparison
1157 ///
1158 /// Regards both *this and RHS as unsigned quantities and compares them for
1159 /// the validity of the greater-than relationship.
1160 ///
1161 /// \returns true if *this > RHS when both are considered unsigned.
1162 bool ugt(const APInt &RHS) const { return !ule(RHS); }
1163
1164 /// Unsigned greater than comparison
1165 ///
1166 /// Regards both *this as an unsigned quantity and compares it with RHS for
1167 /// the validity of the greater-than relationship.
1168 ///
1169 /// \returns true if *this > RHS when considered unsigned.
1170 bool ugt(uint64_t RHS) const {
1171 // Only need to check active bits if not a single word.
1172 return (!isSingleWord() && getActiveBits() > 64) || getZExtValue() > RHS;
1173 }
1174
1175 /// Signed greater than comparison
1176 ///
1177 /// Regards both *this and RHS as signed quantities and compares them for the
1178 /// validity of the greater-than relationship.
1179 ///
1180 /// \returns true if *this > RHS when both are considered signed.
1181 bool sgt(const APInt &RHS) const { return !sle(RHS); }
1182
1183 /// Signed greater than comparison
1184 ///
1185 /// Regards both *this as a signed quantity and compares it with RHS for
1186 /// the validity of the greater-than relationship.
1187 ///
1188 /// \returns true if *this > RHS when considered signed.
1189 bool sgt(int64_t RHS) const {
1190 return (!isSingleWord() && getSignificantBits() > 64)
1191 ? !isNegative()
1192 : getSExtValue() > RHS;
1193 }
1194
1195 /// Unsigned greater or equal comparison
1196 ///
1197 /// Regards both *this and RHS as unsigned quantities and compares them for
1198 /// validity of the greater-or-equal relationship.
1199 ///
1200 /// \returns true if *this >= RHS when both are considered unsigned.
1201 bool uge(const APInt &RHS) const { return !ult(RHS); }
1202
1203 /// Unsigned greater or equal comparison
1204 ///
1205 /// Regards both *this as an unsigned quantity and compares it with RHS for
1206 /// the validity of the greater-or-equal relationship.
1207 ///
1208 /// \returns true if *this >= RHS when considered unsigned.
1209 bool uge(uint64_t RHS) const { return !ult(RHS); }
1210
1211 /// Signed greater or equal comparison
1212 ///
1213 /// Regards both *this and RHS as signed quantities and compares them for
1214 /// validity of the greater-or-equal relationship.
1215 ///
1216 /// \returns true if *this >= RHS when both are considered signed.
1217 bool sge(const APInt &RHS) const { return !slt(RHS); }
1218
1219 /// Signed greater or equal comparison
1220 ///
1221 /// Regards both *this as a signed quantity and compares it with RHS for
1222 /// the validity of the greater-or-equal relationship.
1223 ///
1224 /// \returns true if *this >= RHS when considered signed.
1225 bool sge(int64_t RHS) const { return !slt(RHS); }
1226
1227 /// This operation tests if there are any pairs of corresponding bits
1228 /// between this APInt and RHS that are both set.
1229 bool intersects(const APInt &RHS) const {
1230 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1231 if (isSingleWord())
1232 return (U.VAL & RHS.U.VAL) != 0;
1233 return intersectsSlowCase(RHS);
1234 }
1235
1236 /// This operation checks that all bits set in this APInt are also set in RHS.
1237 bool isSubsetOf(const APInt &RHS) const {
1238 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1239 if (isSingleWord())
1240 return (U.VAL & ~RHS.U.VAL) == 0;
1241 return isSubsetOfSlowCase(RHS);
1242 }
1243
1244 /// @}
1245 /// \name Resizing Operators
1246 /// @{
1247
1248 /// Truncate to new width.
1249 ///
1250 /// Truncate the APInt to a specified width. It is an error to specify a width
1251 /// that is greater than the current width.
1252 APInt trunc(unsigned width) const;
1253
1254 /// Truncate to new width with unsigned saturation.
1255 ///
1256 /// If the APInt, treated as unsigned integer, can be losslessly truncated to
1257 /// the new bitwidth, then return truncated APInt. Else, return max value.
1258 APInt truncUSat(unsigned width) const;
1259
1260 /// Truncate to new width with signed saturation.
1261 ///
1262 /// If this APInt, treated as signed integer, can be losslessly truncated to
1263 /// the new bitwidth, then return truncated APInt. Else, return either
1264 /// signed min value if the APInt was negative, or signed max value.
1265 APInt truncSSat(unsigned width) const;
1266
1267 /// Sign extend to a new width.
1268 ///
1269 /// This operation sign extends the APInt to a new width. If the high order
1270 /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
1271 /// It is an error to specify a width that is less than the
1272 /// current width.
1273 APInt sext(unsigned width) const;
1274
1275 /// Zero extend to a new width.
1276 ///
1277 /// This operation zero extends the APInt to a new width. The high order bits
1278 /// are filled with 0 bits. It is an error to specify a width that is less
1279 /// than the current width.
1280 APInt zext(unsigned width) const;
1281
1282 /// Sign extend or truncate to width
1283 ///
1284 /// Make this APInt have the bit width given by \p width. The value is sign
1285 /// extended, truncated, or left alone to make it that width.
1286 APInt sextOrTrunc(unsigned width) const;
1287
1288 /// Zero extend or truncate to width
1289 ///
1290 /// Make this APInt have the bit width given by \p width. The value is zero
1291 /// extended, truncated, or left alone to make it that width.
1292 APInt zextOrTrunc(unsigned width) const;
1293
1294 /// @}
1295 /// \name Bit Manipulation Operators
1296 /// @{
1297
1298 /// Set every bit to 1.
1299 void setAllBits() {
1300 if (isSingleWord())
1301 U.VAL = WORDTYPE_MAX;
1302 else
1303 // Set all the bits in all the words.
1304 memset(U.pVal, -1, getNumWords() * APINT_WORD_SIZE);
1305 // Clear the unused ones
1307 }
1308
1309 /// Set the given bit to 1 whose position is given as "bitPosition".
1310 void setBit(unsigned BitPosition) {
1311 assert(BitPosition < BitWidth && "BitPosition out of range");
1312 WordType Mask = maskBit(BitPosition);
1313 if (isSingleWord())
1314 U.VAL |= Mask;
1315 else
1316 U.pVal[whichWord(BitPosition)] |= Mask;
1317 }
1318
1319 /// Set the sign bit to 1.
1320 void setSignBit() { setBit(BitWidth - 1); }
1321
1322 /// Set a given bit to a given value.
1323 void setBitVal(unsigned BitPosition, bool BitValue) {
1324 if (BitValue)
1325 setBit(BitPosition);
1326 else
1327 clearBit(BitPosition);
1328 }
1329
1330 /// Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
1331 /// This function handles "wrap" case when \p loBit >= \p hiBit, and calls
1332 /// setBits when \p loBit < \p hiBit.
1333 /// For \p loBit == \p hiBit wrap case, set every bit to 1.
1334 void setBitsWithWrap(unsigned loBit, unsigned hiBit) {
1335 assert(hiBit <= BitWidth && "hiBit out of range");
1336 assert(loBit <= BitWidth && "loBit out of range");
1337 if (loBit < hiBit) {
1338 setBits(loBit, hiBit);
1339 return;
1340 }
1341 setLowBits(hiBit);
1342 setHighBits(BitWidth - loBit);
1343 }
1344
1345 /// Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
1346 /// This function handles case when \p loBit <= \p hiBit.
1347 void setBits(unsigned loBit, unsigned hiBit) {
1348 assert(hiBit <= BitWidth && "hiBit out of range");
1349 assert(loBit <= BitWidth && "loBit out of range");
1350 assert(loBit <= hiBit && "loBit greater than hiBit");
1351 if (loBit == hiBit)
1352 return;
1353 if (loBit < APINT_BITS_PER_WORD && hiBit <= APINT_BITS_PER_WORD) {
1354 uint64_t mask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - (hiBit - loBit));
1355 mask <<= loBit;
1356 if (isSingleWord())
1357 U.VAL |= mask;
1358 else
1359 U.pVal[0] |= mask;
1360 } else {
1361 setBitsSlowCase(loBit, hiBit);
1362 }
1363 }
1364
1365 /// Set the top bits starting from loBit.
1366 void setBitsFrom(unsigned loBit) { return setBits(loBit, BitWidth); }
1367
1368 /// Set the bottom loBits bits.
1369 void setLowBits(unsigned loBits) { return setBits(0, loBits); }
1370
1371 /// Set the top hiBits bits.
1372 void setHighBits(unsigned hiBits) {
1373 return setBits(BitWidth - hiBits, BitWidth);
1374 }
1375
1376 /// Set every bit to 0.
1378 if (isSingleWord())
1379 U.VAL = 0;
1380 else
1381 memset(U.pVal, 0, getNumWords() * APINT_WORD_SIZE);
1382 }
1383
1384 /// Set a given bit to 0.
1385 ///
1386 /// Set the given bit to 0 whose position is given as "bitPosition".
1387 void clearBit(unsigned BitPosition) {
1388 assert(BitPosition < BitWidth && "BitPosition out of range");
1389 WordType Mask = ~maskBit(BitPosition);
1390 if (isSingleWord())
1391 U.VAL &= Mask;
1392 else
1393 U.pVal[whichWord(BitPosition)] &= Mask;
1394 }
1395
1396 /// Set bottom loBits bits to 0.
1397 void clearLowBits(unsigned loBits) {
1398 assert(loBits <= BitWidth && "More bits than bitwidth");
1399 APInt Keep = getHighBitsSet(BitWidth, BitWidth - loBits);
1400 *this &= Keep;
1401 }
1402
1403 /// Set top hiBits bits to 0.
1404 void clearHighBits(unsigned hiBits) {
1405 assert(hiBits <= BitWidth && "More bits than bitwidth");
1406 APInt Keep = getLowBitsSet(BitWidth, BitWidth - hiBits);
1407 *this &= Keep;
1408 }
1409
1410 /// Set the sign bit to 0.
1411 void clearSignBit() { clearBit(BitWidth - 1); }
1412
1413 /// Toggle every bit to its opposite value.
1415 if (isSingleWord()) {
1416 U.VAL ^= WORDTYPE_MAX;
1418 } else {
1419 flipAllBitsSlowCase();
1420 }
1421 }
1422
1423 /// Toggles a given bit to its opposite value.
1424 ///
1425 /// Toggle a given bit to its opposite value whose position is given
1426 /// as "bitPosition".
1427 void flipBit(unsigned bitPosition);
1428
1429 /// Negate this APInt in place.
1430 void negate() {
1431 flipAllBits();
1432 ++(*this);
1433 }
1434
1435 /// Insert the bits from a smaller APInt starting at bitPosition.
1436 void insertBits(const APInt &SubBits, unsigned bitPosition);
1437 void insertBits(uint64_t SubBits, unsigned bitPosition, unsigned numBits);
1438
1439 /// Return an APInt with the extracted bits [bitPosition,bitPosition+numBits).
1440 APInt extractBits(unsigned numBits, unsigned bitPosition) const;
1441 uint64_t extractBitsAsZExtValue(unsigned numBits, unsigned bitPosition) const;
1442
1443 /// @}
1444 /// \name Value Characterization Functions
1445 /// @{
1446
1447 /// Return the number of bits in the APInt.
1448 unsigned getBitWidth() const { return BitWidth; }
1449
1450 /// Get the number of words.
1451 ///
1452 /// Here one word's bitwidth equals to that of uint64_t.
1453 ///
1454 /// \returns the number of words to hold the integer value of this APInt.
1455 unsigned getNumWords() const { return getNumWords(BitWidth); }
1456
1457 /// Get the number of words.
1458 ///
1459 /// *NOTE* Here one word's bitwidth equals to that of uint64_t.
1460 ///
1461 /// \returns the number of words to hold the integer value with a given bit
1462 /// width.
1463 static unsigned getNumWords(unsigned BitWidth) {
1464 return ((uint64_t)BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
1465 }
1466
1467 /// Compute the number of active bits in the value
1468 ///
1469 /// This function returns the number of active bits which is defined as the
1470 /// bit width minus the number of leading zeros. This is used in several
1471 /// computations to see how "wide" the value is.
1472 unsigned getActiveBits() const { return BitWidth - countl_zero(); }
1473
1474 /// Compute the number of active words in the value of this APInt.
1475 ///
1476 /// This is used in conjunction with getActiveData to extract the raw value of
1477 /// the APInt.
1478 unsigned getActiveWords() const {
1479 unsigned numActiveBits = getActiveBits();
1480 return numActiveBits ? whichWord(numActiveBits - 1) + 1 : 1;
1481 }
1482
1483 /// Get the minimum bit size for this signed APInt
1484 ///
1485 /// Computes the minimum bit width for this APInt while considering it to be a
1486 /// signed (and probably negative) value. If the value is not negative, this
1487 /// function returns the same value as getActiveBits()+1. Otherwise, it
1488 /// returns the smallest bit width that will retain the negative value. For
1489 /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
1490 /// for -1, this function will always return 1.
1491 unsigned getSignificantBits() const {
1492 return BitWidth - getNumSignBits() + 1;
1493 }
1494
1495 /// Get zero extended value
1496 ///
1497 /// This method attempts to return the value of this APInt as a zero extended
1498 /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
1499 /// uint64_t. Otherwise an assertion will result.
1501 if (isSingleWord())
1502 return U.VAL;
1503 assert(getActiveBits() <= 64 && "Too many bits for uint64_t");
1504 return U.pVal[0];
1505 }
1506
1507 /// Get zero extended value if possible
1508 ///
1509 /// This method attempts to return the value of this APInt as a zero extended
1510 /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
1511 /// uint64_t. Otherwise no value is returned.
1512 std::optional<uint64_t> tryZExtValue() const {
1513 return (getActiveBits() <= 64) ? std::optional<uint64_t>(getZExtValue())
1514 : std::nullopt;
1515 };
1516
1517 /// Get sign extended value
1518 ///
1519 /// This method attempts to return the value of this APInt as a sign extended
1520 /// int64_t. The bit width must be <= 64 or the value must fit within an
1521 /// int64_t. Otherwise an assertion will result.
1522 int64_t getSExtValue() const {
1523 if (isSingleWord())
1524 return SignExtend64(U.VAL, BitWidth);
1525 assert(getSignificantBits() <= 64 && "Too many bits for int64_t");
1526 return int64_t(U.pVal[0]);
1527 }
1528
1529 /// Get sign extended value if possible
1530 ///
1531 /// This method attempts to return the value of this APInt as a sign extended
1532 /// int64_t. The bitwidth must be <= 64 or the value must fit within an
1533 /// int64_t. Otherwise no value is returned.
1534 std::optional<int64_t> trySExtValue() const {
1535 return (getSignificantBits() <= 64) ? std::optional<int64_t>(getSExtValue())
1536 : std::nullopt;
1537 };
1538
1539 /// Get bits required for string value.
1540 ///
1541 /// This method determines how many bits are required to hold the APInt
1542 /// equivalent of the string given by \p str.
1543 static unsigned getBitsNeeded(StringRef str, uint8_t radix);
1544
1545 /// Get the bits that are sufficient to represent the string value. This may
1546 /// over estimate the amount of bits required, but it does not require
1547 /// parsing the value in the string.
1548 static unsigned getSufficientBitsNeeded(StringRef Str, uint8_t Radix);
1549
1550 /// The APInt version of std::countl_zero.
1551 ///
1552 /// It counts the number of zeros from the most significant bit to the first
1553 /// one bit.
1554 ///
1555 /// \returns BitWidth if the value is zero, otherwise returns the number of
1556 /// zeros from the most significant bit to the first one bits.
1557 unsigned countl_zero() const {
1558 if (isSingleWord()) {
1559 unsigned unusedBits = APINT_BITS_PER_WORD - BitWidth;
1560 return llvm::countl_zero(U.VAL) - unusedBits;
1561 }
1562 return countLeadingZerosSlowCase();
1563 }
1564
1565 unsigned countLeadingZeros() const { return countl_zero(); }
1566
1567 /// Count the number of leading one bits.
1568 ///
1569 /// This function is an APInt version of std::countl_one. It counts the number
1570 /// of ones from the most significant bit to the first zero bit.
1571 ///
1572 /// \returns 0 if the high order bit is not set, otherwise returns the number
1573 /// of 1 bits from the most significant to the least
1574 unsigned countl_one() const {
1575 if (isSingleWord()) {
1576 if (LLVM_UNLIKELY(BitWidth == 0))
1577 return 0;
1578 return llvm::countl_one(U.VAL << (APINT_BITS_PER_WORD - BitWidth));
1579 }
1580 return countLeadingOnesSlowCase();
1581 }
1582
1583 unsigned countLeadingOnes() const { return countl_one(); }
1584
1585 /// Computes the number of leading bits of this APInt that are equal to its
1586 /// sign bit.
1587 unsigned getNumSignBits() const {
1588 return isNegative() ? countl_one() : countl_zero();
1589 }
1590
1591 /// Count the number of trailing zero bits.
1592 ///
1593 /// This function is an APInt version of std::countr_zero. It counts the
1594 /// number of zeros from the least significant bit to the first set bit.
1595 ///
1596 /// \returns BitWidth if the value is zero, otherwise returns the number of
1597 /// zeros from the least significant bit to the first one bit.
1598 unsigned countr_zero() const {
1599 if (isSingleWord()) {
1600 unsigned TrailingZeros = llvm::countr_zero(U.VAL);
1601 return (TrailingZeros > BitWidth ? BitWidth : TrailingZeros);
1602 }
1603 return countTrailingZerosSlowCase();
1604 }
1605
1606 unsigned countTrailingZeros() const { return countr_zero(); }
1607
1608 /// Count the number of trailing one bits.
1609 ///
1610 /// This function is an APInt version of std::countr_one. It counts the number
1611 /// of ones from the least significant bit to the first zero bit.
1612 ///
1613 /// \returns BitWidth if the value is all ones, otherwise returns the number
1614 /// of ones from the least significant bit to the first zero bit.
1615 unsigned countr_one() const {
1616 if (isSingleWord())
1617 return llvm::countr_one(U.VAL);
1618 return countTrailingOnesSlowCase();
1619 }
1620
1621 unsigned countTrailingOnes() const { return countr_one(); }
1622
1623 /// Count the number of bits set.
1624 ///
1625 /// This function is an APInt version of std::popcount. It counts the number
1626 /// of 1 bits in the APInt value.
1627 ///
1628 /// \returns 0 if the value is zero, otherwise returns the number of set bits.
1629 unsigned popcount() const {
1630 if (isSingleWord())
1631 return llvm::popcount(U.VAL);
1632 return countPopulationSlowCase();
1633 }
1634
1635 /// @}
1636 /// \name Conversion Functions
1637 /// @{
1638 void print(raw_ostream &OS, bool isSigned) const;
1639
1640 /// Converts an APInt to a string and append it to Str. Str is commonly a
1641 /// SmallString. If Radix > 10, UpperCase determine the case of letter
1642 /// digits.
1643 void toString(SmallVectorImpl<char> &Str, unsigned Radix, bool Signed,
1644 bool formatAsCLiteral = false, bool UpperCase = true,
1645 bool InsertSeparators = false) const;
1646
1647 /// Considers the APInt to be unsigned and converts it into a string in the
1648 /// radix given. The radix can be 2, 8, 10 16, or 36.
1649 void toStringUnsigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1650 toString(Str, Radix, false, false);
1651 }
1652
1653 /// Considers the APInt to be signed and converts it into a string in the
1654 /// radix given. The radix can be 2, 8, 10, 16, or 36.
1655 void toStringSigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1656 toString(Str, Radix, true, false);
1657 }
1658
1659 /// \returns a byte-swapped representation of this APInt Value.
1660 APInt byteSwap() const;
1661
1662 /// \returns the value with the bit representation reversed of this APInt
1663 /// Value.
1664 APInt reverseBits() const;
1665
1666 /// Converts this APInt to a double value.
1667 double roundToDouble(bool isSigned) const;
1668
1669 /// Converts this unsigned APInt to a double value.
1670 double roundToDouble() const { return roundToDouble(false); }
1671
1672 /// Converts this signed APInt to a double value.
1673 double signedRoundToDouble() const { return roundToDouble(true); }
1674
1675 /// Converts APInt bits to a double
1676 ///
1677 /// The conversion does not do a translation from integer to double, it just
1678 /// re-interprets the bits as a double. Note that it is valid to do this on
1679 /// any bit width. Exactly 64 bits will be translated.
1680 double bitsToDouble() const { return llvm::bit_cast<double>(getWord(0)); }
1681
1682#ifdef HAS_IEE754_FLOAT128
1683 float128 bitsToQuad() const {
1684 __uint128_t ul = ((__uint128_t)U.pVal[1] << 64) + U.pVal[0];
1685 return llvm::bit_cast<float128>(ul);
1686 }
1687#endif
1688
1689 /// Converts APInt bits to a float
1690 ///
1691 /// The conversion does not do a translation from integer to float, it just
1692 /// re-interprets the bits as a float. Note that it is valid to do this on
1693 /// any bit width. Exactly 32 bits will be translated.
1694 float bitsToFloat() const {
1695 return llvm::bit_cast<float>(static_cast<uint32_t>(getWord(0)));
1696 }
1697
1698 /// Converts a double to APInt bits.
1699 ///
1700 /// The conversion does not do a translation from double to integer, it just
1701 /// re-interprets the bits of the double.
1702 static APInt doubleToBits(double V) {
1703 return APInt(sizeof(double) * CHAR_BIT, llvm::bit_cast<uint64_t>(V));
1704 }
1705
1706 /// Converts a float to APInt bits.
1707 ///
1708 /// The conversion does not do a translation from float to integer, it just
1709 /// re-interprets the bits of the float.
1710 static APInt floatToBits(float V) {
1711 return APInt(sizeof(float) * CHAR_BIT, llvm::bit_cast<uint32_t>(V));
1712 }
1713
1714 /// @}
1715 /// \name Mathematics Operations
1716 /// @{
1717
1718 /// \returns the floor log base 2 of this APInt.
1719 unsigned logBase2() const { return getActiveBits() - 1; }
1720
1721 /// \returns the ceil log base 2 of this APInt.
1722 unsigned ceilLogBase2() const {
1723 APInt temp(*this);
1724 --temp;
1725 return temp.getActiveBits();
1726 }
1727
1728 /// \returns the nearest log base 2 of this APInt. Ties round up.
1729 ///
1730 /// NOTE: When we have a BitWidth of 1, we define:
1731 ///
1732 /// log2(0) = UINT32_MAX
1733 /// log2(1) = 0
1734 ///
1735 /// to get around any mathematical concerns resulting from
1736 /// referencing 2 in a space where 2 does no exist.
1737 unsigned nearestLogBase2() const;
1738
1739 /// \returns the log base 2 of this APInt if its an exact power of two, -1
1740 /// otherwise
1741 int32_t exactLogBase2() const {
1742 if (!isPowerOf2())
1743 return -1;
1744 return logBase2();
1745 }
1746
1747 /// Compute the square root.
1748 APInt sqrt() const;
1749
1750 /// Get the absolute value. If *this is < 0 then return -(*this), otherwise
1751 /// *this. Note that the "most negative" signed number (e.g. -128 for 8 bit
1752 /// wide APInt) is unchanged due to how negation works.
1753 APInt abs() const {
1754 if (isNegative())
1755 return -(*this);
1756 return *this;
1757 }
1758
1759 /// \returns the multiplicative inverse of an odd APInt modulo 2^BitWidth.
1760 APInt multiplicativeInverse() const;
1761
1762 /// @}
1763 /// \name Building-block Operations for APInt and APFloat
1764 /// @{
1765
1766 // These building block operations operate on a representation of arbitrary
1767 // precision, two's-complement, bignum integer values. They should be
1768 // sufficient to implement APInt and APFloat bignum requirements. Inputs are
1769 // generally a pointer to the base of an array of integer parts, representing
1770 // an unsigned bignum, and a count of how many parts there are.
1771
1772 /// Sets the least significant part of a bignum to the input value, and zeroes
1773 /// out higher parts.
1774 static void tcSet(WordType *, WordType, unsigned);
1775
1776 /// Assign one bignum to another.
1777 static void tcAssign(WordType *, const WordType *, unsigned);
1778
1779 /// Returns true if a bignum is zero, false otherwise.
1780 static bool tcIsZero(const WordType *, unsigned);
1781
1782 /// Extract the given bit of a bignum; returns 0 or 1. Zero-based.
1783 static int tcExtractBit(const WordType *, unsigned bit);
1784
1785 /// Copy the bit vector of width srcBITS from SRC, starting at bit srcLSB, to
1786 /// DST, of dstCOUNT parts, such that the bit srcLSB becomes the least
1787 /// significant bit of DST. All high bits above srcBITS in DST are
1788 /// zero-filled.
1789 static void tcExtract(WordType *, unsigned dstCount, const WordType *,
1790 unsigned srcBits, unsigned srcLSB);
1791
1792 /// Set the given bit of a bignum. Zero-based.
1793 static void tcSetBit(WordType *, unsigned bit);
1794
1795 /// Clear the given bit of a bignum. Zero-based.
1796 static void tcClearBit(WordType *, unsigned bit);
1797
1798 /// Returns the bit number of the least or most significant set bit of a
1799 /// number. If the input number has no bits set -1U is returned.
1800 static unsigned tcLSB(const WordType *, unsigned n);
1801 static unsigned tcMSB(const WordType *parts, unsigned n);
1802
1803 /// Negate a bignum in-place.
1804 static void tcNegate(WordType *, unsigned);
1805
1806 /// DST += RHS + CARRY where CARRY is zero or one. Returns the carry flag.
1807 static WordType tcAdd(WordType *, const WordType *, WordType carry, unsigned);
1808 /// DST += RHS. Returns the carry flag.
1809 static WordType tcAddPart(WordType *, WordType, unsigned);
1810
1811 /// DST -= RHS + CARRY where CARRY is zero or one. Returns the carry flag.
1812 static WordType tcSubtract(WordType *, const WordType *, WordType carry,
1813 unsigned);
1814 /// DST -= RHS. Returns the carry flag.
1815 static WordType tcSubtractPart(WordType *, WordType, unsigned);
1816
1817 /// DST += SRC * MULTIPLIER + PART if add is true
1818 /// DST = SRC * MULTIPLIER + PART if add is false
1819 ///
1820 /// Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC they must
1821 /// start at the same point, i.e. DST == SRC.
1822 ///
1823 /// If DSTPARTS == SRC_PARTS + 1 no overflow occurs and zero is returned.
1824 /// Otherwise DST is filled with the least significant DSTPARTS parts of the
1825 /// result, and if all of the omitted higher parts were zero return zero,
1826 /// otherwise overflow occurred and return one.
1827 static int tcMultiplyPart(WordType *dst, const WordType *src,
1828 WordType multiplier, WordType carry,
1829 unsigned srcParts, unsigned dstParts, bool add);
1830
1831 /// DST = LHS * RHS, where DST has the same width as the operands and is
1832 /// filled with the least significant parts of the result. Returns one if
1833 /// overflow occurred, otherwise zero. DST must be disjoint from both
1834 /// operands.
1835 static int tcMultiply(WordType *, const WordType *, const WordType *,
1836 unsigned);
1837
1838 /// DST = LHS * RHS, where DST has width the sum of the widths of the
1839 /// operands. No overflow occurs. DST must be disjoint from both operands.
1840 static void tcFullMultiply(WordType *, const WordType *, const WordType *,
1841 unsigned, unsigned);
1842
1843 /// If RHS is zero LHS and REMAINDER are left unchanged, return one.
1844 /// Otherwise set LHS to LHS / RHS with the fractional part discarded, set
1845 /// REMAINDER to the remainder, return zero. i.e.
1846 ///
1847 /// OLD_LHS = RHS * LHS + REMAINDER
1848 ///
1849 /// SCRATCH is a bignum of the same size as the operands and result for use by
1850 /// the routine; its contents need not be initialized and are destroyed. LHS,
1851 /// REMAINDER and SCRATCH must be distinct.
1852 static int tcDivide(WordType *lhs, const WordType *rhs, WordType *remainder,
1853 WordType *scratch, unsigned parts);
1854
1855 /// Shift a bignum left Count bits. Shifted in bits are zero. There are no
1856 /// restrictions on Count.
1857 static void tcShiftLeft(WordType *, unsigned Words, unsigned Count);
1858
1859 /// Shift a bignum right Count bits. Shifted in bits are zero. There are no
1860 /// restrictions on Count.
1861 static void tcShiftRight(WordType *, unsigned Words, unsigned Count);
1862
1863 /// Comparison (unsigned) of two bignums.
1864 static int tcCompare(const WordType *, const WordType *, unsigned);
1865
1866 /// Increment a bignum in-place. Return the carry flag.
1867 static WordType tcIncrement(WordType *dst, unsigned parts) {
1868 return tcAddPart(dst, 1, parts);
1869 }
1870
1871 /// Decrement a bignum in-place. Return the borrow flag.
1872 static WordType tcDecrement(WordType *dst, unsigned parts) {
1873 return tcSubtractPart(dst, 1, parts);
1874 }
1875
1876 /// Used to insert APInt objects, or objects that contain APInt objects, into
1877 /// FoldingSets.
1878 void Profile(FoldingSetNodeID &id) const;
1879
1880 /// debug method
1881 void dump() const;
1882
1883 /// Returns whether this instance allocated memory.
1884 bool needsCleanup() const { return !isSingleWord(); }
1885
1886private:
1887 /// This union is used to store the integer value. When the
1888 /// integer bit-width <= 64, it uses VAL, otherwise it uses pVal.
1889 union {
1890 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
1891 uint64_t *pVal; ///< Used to store the >64 bits integer value.
1892 } U;
1893
1894 unsigned BitWidth = 1; ///< The number of bits in this APInt.
1895
1896 friend struct DenseMapInfo<APInt, void>;
1897 friend class APSInt;
1898
1899 // Make DynamicAPInt a friend so it can access BitWidth directly.
1900 friend DynamicAPInt;
1901
1902 /// This constructor is used only internally for speed of construction of
1903 /// temporaries. It is unsafe since it takes ownership of the pointer, so it
1904 /// is not public.
1905 APInt(uint64_t *val, unsigned bits) : BitWidth(bits) { U.pVal = val; }
1906
1907 /// Determine which word a bit is in.
1908 ///
1909 /// \returns the word position for the specified bit position.
1910 static unsigned whichWord(unsigned bitPosition) {
1911 return bitPosition / APINT_BITS_PER_WORD;
1912 }
1913
1914 /// Determine which bit in a word the specified bit position is in.
1915 static unsigned whichBit(unsigned bitPosition) {
1916 return bitPosition % APINT_BITS_PER_WORD;
1917 }
1918
1919 /// Get a single bit mask.
1920 ///
1921 /// \returns a uint64_t with only bit at "whichBit(bitPosition)" set
1922 /// This method generates and returns a uint64_t (word) mask for a single
1923 /// bit at a specific bit position. This is used to mask the bit in the
1924 /// corresponding word.
1925 static uint64_t maskBit(unsigned bitPosition) {
1926 return 1ULL << whichBit(bitPosition);
1927 }
1928
1929 /// Clear unused high order bits
1930 ///
1931 /// This method is used internally to clear the top "N" bits in the high order
1932 /// word that are not used by the APInt. This is needed after the most
1933 /// significant word is assigned a value to ensure that those bits are
1934 /// zero'd out.
1935 APInt &clearUnusedBits() {
1936 // Compute how many bits are used in the final word.
1937 unsigned WordBits = ((BitWidth - 1) % APINT_BITS_PER_WORD) + 1;
1938
1939 // Mask out the high bits.
1940 uint64_t mask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - WordBits);
1941 if (LLVM_UNLIKELY(BitWidth == 0))
1942 mask = 0;
1943
1944 if (isSingleWord())
1945 U.VAL &= mask;
1946 else
1947 U.pVal[getNumWords() - 1] &= mask;
1948 return *this;
1949 }
1950
1951 /// Get the word corresponding to a bit position
1952 /// \returns the corresponding word for the specified bit position.
1953 uint64_t getWord(unsigned bitPosition) const {
1954 return isSingleWord() ? U.VAL : U.pVal[whichWord(bitPosition)];
1955 }
1956
1957 /// Utility method to change the bit width of this APInt to new bit width,
1958 /// allocating and/or deallocating as necessary. There is no guarantee on the
1959 /// value of any bits upon return. Caller should populate the bits after.
1960 void reallocate(unsigned NewBitWidth);
1961
1962 /// Convert a char array into an APInt
1963 ///
1964 /// \param radix 2, 8, 10, 16, or 36
1965 /// Converts a string into a number. The string must be non-empty
1966 /// and well-formed as a number of the given base. The bit-width
1967 /// must be sufficient to hold the result.
1968 ///
1969 /// This is used by the constructors that take string arguments.
1970 ///
1971 /// StringRef::getAsInteger is superficially similar but (1) does
1972 /// not assume that the string is well-formed and (2) grows the
1973 /// result to hold the input.
1974 void fromString(unsigned numBits, StringRef str, uint8_t radix);
1975
1976 /// An internal division function for dividing APInts.
1977 ///
1978 /// This is used by the toString method to divide by the radix. It simply
1979 /// provides a more convenient form of divide for internal use since KnuthDiv
1980 /// has specific constraints on its inputs. If those constraints are not met
1981 /// then it provides a simpler form of divide.
1982 static void divide(const WordType *LHS, unsigned lhsWords,
1983 const WordType *RHS, unsigned rhsWords, WordType *Quotient,
1984 WordType *Remainder);
1985
1986 /// out-of-line slow case for inline constructor
1987 void initSlowCase(uint64_t val, bool isSigned);
1988
1989 /// shared code between two array constructors
1990 void initFromArray(ArrayRef<uint64_t> array);
1991
1992 /// out-of-line slow case for inline copy constructor
1993 void initSlowCase(const APInt &that);
1994
1995 /// out-of-line slow case for shl
1996 void shlSlowCase(unsigned ShiftAmt);
1997
1998 /// out-of-line slow case for lshr.
1999 void lshrSlowCase(unsigned ShiftAmt);
2000
2001 /// out-of-line slow case for ashr.
2002 void ashrSlowCase(unsigned ShiftAmt);
2003
2004 /// out-of-line slow case for operator=
2005 void assignSlowCase(const APInt &RHS);
2006
2007 /// out-of-line slow case for operator==
2008 bool equalSlowCase(const APInt &RHS) const LLVM_READONLY;
2009
2010 /// out-of-line slow case for countLeadingZeros
2011 unsigned countLeadingZerosSlowCase() const LLVM_READONLY;
2012
2013 /// out-of-line slow case for countLeadingOnes.
2014 unsigned countLeadingOnesSlowCase() const LLVM_READONLY;
2015
2016 /// out-of-line slow case for countTrailingZeros.
2017 unsigned countTrailingZerosSlowCase() const LLVM_READONLY;
2018
2019 /// out-of-line slow case for countTrailingOnes
2020 unsigned countTrailingOnesSlowCase() const LLVM_READONLY;
2021
2022 /// out-of-line slow case for countPopulation
2023 unsigned countPopulationSlowCase() const LLVM_READONLY;
2024
2025 /// out-of-line slow case for intersects.
2026 bool intersectsSlowCase(const APInt &RHS) const LLVM_READONLY;
2027
2028 /// out-of-line slow case for isSubsetOf.
2029 bool isSubsetOfSlowCase(const APInt &RHS) const LLVM_READONLY;
2030
2031 /// out-of-line slow case for setBits.
2032 void setBitsSlowCase(unsigned loBit, unsigned hiBit);
2033
2034 /// out-of-line slow case for flipAllBits.
2035 void flipAllBitsSlowCase();
2036
2037 /// out-of-line slow case for concat.
2038 APInt concatSlowCase(const APInt &NewLSB) const;
2039
2040 /// out-of-line slow case for operator&=.
2041 void andAssignSlowCase(const APInt &RHS);
2042
2043 /// out-of-line slow case for operator|=.
2044 void orAssignSlowCase(const APInt &RHS);
2045
2046 /// out-of-line slow case for operator^=.
2047 void xorAssignSlowCase(const APInt &RHS);
2048
2049 /// Unsigned comparison. Returns -1, 0, or 1 if this APInt is less than, equal
2050 /// to, or greater than RHS.
2051 int compare(const APInt &RHS) const LLVM_READONLY;
2052
2053 /// Signed comparison. Returns -1, 0, or 1 if this APInt is less than, equal
2054 /// to, or greater than RHS.
2055 int compareSigned(const APInt &RHS) const LLVM_READONLY;
2056
2057 /// @}
2058};
2059
2060inline bool operator==(uint64_t V1, const APInt &V2) { return V2 == V1; }
2061
2062inline bool operator!=(uint64_t V1, const APInt &V2) { return V2 != V1; }
2063
2064/// Unary bitwise complement operator.
2065///
2066/// \returns an APInt that is the bitwise complement of \p v.
2068 v.flipAllBits();
2069 return v;
2070}
2071
2072inline APInt operator&(APInt a, const APInt &b) {
2073 a &= b;
2074 return a;
2075}
2076
2077inline APInt operator&(const APInt &a, APInt &&b) {
2078 b &= a;
2079 return std::move(b);
2080}
2081
2083 a &= RHS;
2084 return a;
2085}
2086
2088 b &= LHS;
2089 return b;
2090}
2091
2092inline APInt operator|(APInt a, const APInt &b) {
2093 a |= b;
2094 return a;
2095}
2096
2097inline APInt operator|(const APInt &a, APInt &&b) {
2098 b |= a;
2099 return std::move(b);
2100}
2101
2103 a |= RHS;
2104 return a;
2105}
2106
2108 b |= LHS;
2109 return b;
2110}
2111
2112inline APInt operator^(APInt a, const APInt &b) {
2113 a ^= b;
2114 return a;
2115}
2116
2117inline APInt operator^(const APInt &a, APInt &&b) {
2118 b ^= a;
2119 return std::move(b);
2120}
2121
2123 a ^= RHS;
2124 return a;
2125}
2126
2128 b ^= LHS;
2129 return b;
2130}
2131
2133 I.print(OS, true);
2134 return OS;
2135}
2136
2138 v.negate();
2139 return v;
2140}
2141
2142inline APInt operator+(APInt a, const APInt &b) {
2143 a += b;
2144 return a;
2145}
2146
2147inline APInt operator+(const APInt &a, APInt &&b) {
2148 b += a;
2149 return std::move(b);
2150}
2151
2153 a += RHS;
2154 return a;
2155}
2156
2158 b += LHS;
2159 return b;
2160}
2161
2162inline APInt operator-(APInt a, const APInt &b) {
2163 a -= b;
2164 return a;
2165}
2166
2167inline APInt operator-(const APInt &a, APInt &&b) {
2168 b.negate();
2169 b += a;
2170 return std::move(b);
2171}
2172
2174 a -= RHS;
2175 return a;
2176}
2177
2179 b.negate();
2180 b += LHS;
2181 return b;
2182}
2183
2185 a *= RHS;
2186 return a;
2187}
2188
2190 b *= LHS;
2191 return b;
2192}
2193
2194namespace APIntOps {
2195
2196/// Determine the smaller of two APInts considered to be signed.
2197inline const APInt &smin(const APInt &A, const APInt &B) {
2198 return A.slt(B) ? A : B;
2199}
2200
2201/// Determine the larger of two APInts considered to be signed.
2202inline const APInt &smax(const APInt &A, const APInt &B) {
2203 return A.sgt(B) ? A : B;
2204}
2205
2206/// Determine the smaller of two APInts considered to be unsigned.
2207inline const APInt &umin(const APInt &A, const APInt &B) {
2208 return A.ult(B) ? A : B;
2209}
2210
2211/// Determine the larger of two APInts considered to be unsigned.
2212inline const APInt &umax(const APInt &A, const APInt &B) {
2213 return A.ugt(B) ? A : B;
2214}
2215
2216/// Determine the absolute difference of two APInts considered to be signed.
2217inline const APInt abds(const APInt &A, const APInt &B) {
2218 return A.sge(B) ? (A - B) : (B - A);
2219}
2220
2221/// Determine the absolute difference of two APInts considered to be unsigned.
2222inline const APInt abdu(const APInt &A, const APInt &B) {
2223 return A.uge(B) ? (A - B) : (B - A);
2224}
2225
2226/// Compute the floor of the signed average of C1 and C2
2227APInt avgFloorS(const APInt &C1, const APInt &C2);
2228
2229/// Compute the floor of the unsigned average of C1 and C2
2230APInt avgFloorU(const APInt &C1, const APInt &C2);
2231
2232/// Compute the ceil of the signed average of C1 and C2
2233APInt avgCeilS(const APInt &C1, const APInt &C2);
2234
2235/// Compute the ceil of the unsigned average of C1 and C2
2236APInt avgCeilU(const APInt &C1, const APInt &C2);
2237
2238/// Performs (2*N)-bit multiplication on sign-extended operands.
2239/// Returns the high N bits of the multiplication result.
2240APInt mulhs(const APInt &C1, const APInt &C2);
2241
2242/// Performs (2*N)-bit multiplication on zero-extended operands.
2243/// Returns the high N bits of the multiplication result.
2244APInt mulhu(const APInt &C1, const APInt &C2);
2245
2246/// Compute GCD of two unsigned APInt values.
2247///
2248/// This function returns the greatest common divisor of the two APInt values
2249/// using Stein's algorithm.
2250///
2251/// \returns the greatest common divisor of A and B.
2252APInt GreatestCommonDivisor(APInt A, APInt B);
2253
2254/// Converts the given APInt to a double value.
2255///
2256/// Treats the APInt as an unsigned value for conversion purposes.
2257inline double RoundAPIntToDouble(const APInt &APIVal) {
2258 return APIVal.roundToDouble();
2259}
2260
2261/// Converts the given APInt to a double value.
2262///
2263/// Treats the APInt as a signed value for conversion purposes.
2264inline double RoundSignedAPIntToDouble(const APInt &APIVal) {
2265 return APIVal.signedRoundToDouble();
2266}
2267
2268/// Converts the given APInt to a float value.
2269inline float RoundAPIntToFloat(const APInt &APIVal) {
2270 return float(RoundAPIntToDouble(APIVal));
2271}
2272
2273/// Converts the given APInt to a float value.
2274///
2275/// Treats the APInt as a signed value for conversion purposes.
2276inline float RoundSignedAPIntToFloat(const APInt &APIVal) {
2277 return float(APIVal.signedRoundToDouble());
2278}
2279
2280/// Converts the given double value into a APInt.
2281///
2282/// This function convert a double value to an APInt value.
2283APInt RoundDoubleToAPInt(double Double, unsigned width);
2284
2285/// Converts a float value into a APInt.
2286///
2287/// Converts a float value into an APInt value.
2288inline APInt RoundFloatToAPInt(float Float, unsigned width) {
2289 return RoundDoubleToAPInt(double(Float), width);
2290}
2291
2292/// Return A unsign-divided by B, rounded by the given rounding mode.
2293APInt RoundingUDiv(const APInt &A, const APInt &B, APInt::Rounding RM);
2294
2295/// Return A sign-divided by B, rounded by the given rounding mode.
2296APInt RoundingSDiv(const APInt &A, const APInt &B, APInt::Rounding RM);
2297
2298/// Let q(n) = An^2 + Bn + C, and BW = bit width of the value range
2299/// (e.g. 32 for i32).
2300/// This function finds the smallest number n, such that
2301/// (a) n >= 0 and q(n) = 0, or
2302/// (b) n >= 1 and q(n-1) and q(n), when evaluated in the set of all
2303/// integers, belong to two different intervals [Rk, Rk+R),
2304/// where R = 2^BW, and k is an integer.
2305/// The idea here is to find when q(n) "overflows" 2^BW, while at the
2306/// same time "allowing" subtraction. In unsigned modulo arithmetic a
2307/// subtraction (treated as addition of negated numbers) would always
2308/// count as an overflow, but here we want to allow values to decrease
2309/// and increase as long as they are within the same interval.
2310/// Specifically, adding of two negative numbers should not cause an
2311/// overflow (as long as the magnitude does not exceed the bit width).
2312/// On the other hand, given a positive number, adding a negative
2313/// number to it can give a negative result, which would cause the
2314/// value to go from [-2^BW, 0) to [0, 2^BW). In that sense, zero is
2315/// treated as a special case of an overflow.
2316///
2317/// This function returns std::nullopt if after finding k that minimizes the
2318/// positive solution to q(n) = kR, both solutions are contained between
2319/// two consecutive integers.
2320///
2321/// There are cases where q(n) > T, and q(n+1) < T (assuming evaluation
2322/// in arithmetic modulo 2^BW, and treating the values as signed) by the
2323/// virtue of *signed* overflow. This function will *not* find such an n,
2324/// however it may find a value of n satisfying the inequalities due to
2325/// an *unsigned* overflow (if the values are treated as unsigned).
2326/// To find a solution for a signed overflow, treat it as a problem of
2327/// finding an unsigned overflow with a range with of BW-1.
2328///
2329/// The returned value may have a different bit width from the input
2330/// coefficients.
2331std::optional<APInt> SolveQuadraticEquationWrap(APInt A, APInt B, APInt C,
2332 unsigned RangeWidth);
2333
2334/// Compare two values, and if they are different, return the position of the
2335/// most significant bit that is different in the values.
2336std::optional<unsigned> GetMostSignificantDifferentBit(const APInt &A,
2337 const APInt &B);
2338
2339/// Splat/Merge neighboring bits to widen/narrow the bitmask represented
2340/// by \param A to \param NewBitWidth bits.
2341///
2342/// MatchAnyBits: (Default)
2343/// e.g. ScaleBitMask(0b0101, 8) -> 0b00110011
2344/// e.g. ScaleBitMask(0b00011011, 4) -> 0b0111
2345///
2346/// MatchAllBits:
2347/// e.g. ScaleBitMask(0b0101, 8) -> 0b00110011
2348/// e.g. ScaleBitMask(0b00011011, 4) -> 0b0001
2349/// A.getBitwidth() or NewBitWidth must be a whole multiples of the other.
2350APInt ScaleBitMask(const APInt &A, unsigned NewBitWidth,
2351 bool MatchAllBits = false);
2352} // namespace APIntOps
2353
2354// See friend declaration above. This additional declaration is required in
2355// order to compile LLVM with IBM xlC compiler.
2356hash_code hash_value(const APInt &Arg);
2357
2358/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
2359/// with the integer held in IntVal.
2360void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst, unsigned StoreBytes);
2361
2362/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
2363/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
2364void LoadIntFromMemory(APInt &IntVal, const uint8_t *Src, unsigned LoadBytes);
2365
2366/// Provide DenseMapInfo for APInt.
2367template <> struct DenseMapInfo<APInt, void> {
2368 static inline APInt getEmptyKey() {
2369 APInt V(nullptr, 0);
2370 V.U.VAL = ~0ULL;
2371 return V;
2372 }
2373
2374 static inline APInt getTombstoneKey() {
2375 APInt V(nullptr, 0);
2376 V.U.VAL = ~1ULL;
2377 return V;
2378 }
2379
2380 static unsigned getHashValue(const APInt &Key);
2381
2382 static bool isEqual(const APInt &LHS, const APInt &RHS) {
2383 return LHS.getBitWidth() == RHS.getBitWidth() && LHS == RHS;
2384 }
2385};
2386
2387} // namespace llvm
2388
2389#endif
aarch64 promote const
always inline
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
raw_ostream & operator<<(raw_ostream &OS, const binary_le_impl< value_type > &BLE)
#define LLVM_UNLIKELY(EXPR)
Definition: Compiler.h:241
#define LLVM_READONLY
Definition: Compiler.h:227
uint64_t Align
static bool isSigned(unsigned int Opcode)
static KnownBits extractBits(unsigned BitWidth, const KnownBits &SrcOpKnown, const KnownBits &OffsetKnown, const KnownBits &WidthKnown)
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition: Lint.cpp:512
static bool isAligned(const Value *Base, const APInt &Offset, Align Alignment, const DataLayout &DL)
Definition: Loads.cpp:29
static bool isSplat(Value *V)
Return true if V is a splat of a value (which is used when multiplying a matrix with a scalar).
#define I(x, y, z)
Definition: MD5.cpp:58
static const char * toString(MIToken::TokenKind TokenKind)
Definition: MIParser.cpp:616
Load MIR Sample Profile
const uint64_t BitWidth
static uint64_t clearUnusedBits(uint64_t Val, unsigned Size)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow)
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition: APInt.h:78
std::optional< uint64_t > tryZExtValue() const
Get zero extended value if possible.
Definition: APInt.h:1512
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition: APInt.h:214
bool slt(int64_t RHS) const
Signed less than comparison.
Definition: APInt.h:1118
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition: APInt.h:1387
APInt relativeLShr(int RelativeShift) const
relative logical shift right
Definition: APInt.h:860
bool isNegatedPowerOf2() const
Check if this APInt's negated value is a power of two greater than zero.
Definition: APInt.h:429
APInt zext(unsigned width) const
Zero extend to a new width.
Definition: APInt.cpp:981
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition: APInt.h:209
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition: APInt.h:403
APInt operator--(int)
Postfix decrement operator.
Definition: APInt.h:576
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1500
uint64_t * pVal
Used to store the >64 bits integer value.
Definition: APInt.h:1891
void setHighBits(unsigned hiBits)
Set the top hiBits bits.
Definition: APInt.h:1372
unsigned popcount() const
Count the number of bits set.
Definition: APInt.h:1629
~APInt()
Destructor.
Definition: APInt.h:170
void setBitsFrom(unsigned loBit)
Set the top bits starting from loBit.
Definition: APInt.h:1366
APInt operator<<(const APInt &Bits) const
Left logical shift operator.
Definition: APInt.h:802
bool isMask() const
Definition: APInt.h:481
APInt operator<<(unsigned Bits) const
Left logical shift operator.
Definition: APInt.h:797
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition: APInt.h:1472
bool sgt(int64_t RHS) const
Signed greater than comparison.
Definition: APInt.h:1189
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition: APInt.h:186
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition: APInt.h:1310
bool operator[](unsigned bitPosition) const
Array-indexing support.
Definition: APInt.h:1023
bool operator!=(const APInt &RHS) const
Inequality operator.
Definition: APInt.h:1067
void toStringUnsigned(SmallVectorImpl< char > &Str, unsigned Radix=10) const
Considers the APInt to be unsigned and converts it into a string in the radix given.
Definition: APInt.h:1649
APInt & operator&=(const APInt &RHS)
Bitwise AND assignment operator.
Definition: APInt.h:654
APInt abs() const
Get the absolute value.
Definition: APInt.h:1753
unsigned ceilLogBase2() const
Definition: APInt.h:1722
unsigned countLeadingOnes() const
Definition: APInt.h:1583
APInt relativeLShl(int RelativeShift) const
relative logical shift left
Definition: APInt.h:865
APInt & operator=(const APInt &RHS)
Copy assignment operator.
Definition: APInt.h:598
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition: APInt.h:1181
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition: APInt.h:351
APInt & operator^=(uint64_t RHS)
Bitwise XOR assignment operator.
Definition: APInt.h:727
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition: APInt.h:1162
static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit)
Get a value with a block of bits set.
Definition: APInt.h:238
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition: APInt.h:360
APInt & operator|=(uint64_t RHS)
Bitwise OR assignment operator.
Definition: APInt.h:698
bool isSignMask() const
Check if the APInt's value is returned by getSignMask.
Definition: APInt.h:446
static APInt floatToBits(float V)
Converts a float to APInt bits.
Definition: APInt.h:1710
void setSignBit()
Set the sign bit to 1.
Definition: APInt.h:1320
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1448
uint64_t WordType
Definition: APInt.h:80
bool sle(uint64_t RHS) const
Signed less or equal comparison.
Definition: APInt.h:1154
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition: APInt.h:1091
bool uge(uint64_t RHS) const
Unsigned greater or equal comparison.
Definition: APInt.h:1209
bool operator!() const
Logical negation operation on this APInt returns true if zero, like normal integers.
Definition: APInt.h:589
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition: APInt.h:189
APInt & operator=(uint64_t RHS)
Assignment operator.
Definition: APInt.h:638
APInt relativeAShr(int RelativeShift) const
relative arithmetic shift right
Definition: APInt.h:870
friend hash_code hash_value(const APInt &Arg)
Overload to compute a hash_code for an APInt value.
APInt(const APInt &that)
Copy Constructor.
Definition: APInt.h:156
APInt & operator|=(const APInt &RHS)
Bitwise OR assignment operator.
Definition: APInt.h:684
bool isSingleWord() const
Determine if this APInt just has one word to store value.
Definition: APInt.h:302
bool operator==(uint64_t Val) const
Equality operator.
Definition: APInt.h:1049
APInt operator++(int)
Postfix increment operator.
Definition: APInt.h:562
unsigned getNumWords() const
Get the number of words.
Definition: APInt.h:1455
bool isMinValue() const
Determine if this is the smallest unsigned value.
Definition: APInt.h:397
APInt ashr(const APInt &ShiftAmt) const
Arithmetic right-shift function.
Definition: APInt.h:888
APInt(unsigned numBits, uint64_t val, bool isSigned=false)
Create a new APInt of numBits width, initialized as val.
Definition: APInt.h:111
APInt()
Default constructor that creates an APInt with a 1-bit zero value.
Definition: APInt.h:153
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition: APInt.h:196
APInt(APInt &&that)
Move Constructor.
Definition: APInt.h:164
bool isNegative() const
Determine sign of this APInt.
Definition: APInt.h:309
APInt concat(const APInt &NewLSB) const
Concatenate the bits from "NewLSB" onto the bottom of *this.
Definition: APInt.h:927
bool intersects(const APInt &RHS) const
This operation tests if there are any pairs of corresponding bits between this APInt and RHS that are...
Definition: APInt.h:1229
bool eq(const APInt &RHS) const
Equality comparison.
Definition: APInt.h:1059
int32_t exactLogBase2() const
Definition: APInt.h:1741
APInt & operator<<=(unsigned ShiftAmt)
Left-shift assignment function.
Definition: APInt.h:765
double roundToDouble() const
Converts this unsigned APInt to a double value.
Definition: APInt.h:1670
void clearAllBits()
Set every bit to 0.
Definition: APInt.h:1377
APInt relativeAShl(int RelativeShift) const
relative arithmetic shift left
Definition: APInt.h:875
void ashrInPlace(unsigned ShiftAmt)
Arithmetic right-shift this APInt by ShiftAmt in place.
Definition: APInt.h:814
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition: APInt.h:1146
void negate()
Negate this APInt in place.
Definition: APInt.h:1430
static WordType tcDecrement(WordType *dst, unsigned parts)
Decrement a bignum in-place. Return the borrow flag.
Definition: APInt.h:1872
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition: APInt.h:1598
bool isSignedIntN(unsigned N) const
Check if this APInt has an N-bits signed integer value.
Definition: APInt.h:415
unsigned getNumSignBits() const
Computes the number of leading bits of this APInt that are equal to its sign bit.
Definition: APInt.h:1587
bool isOneBitSet(unsigned BitNo) const
Determine if this APInt Value only has the specified bit set.
Definition: APInt.h:346
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition: APInt.h:1557
bool operator==(const APInt &RHS) const
Equality operator.
Definition: APInt.h:1036
APInt shl(const APInt &ShiftAmt) const
Left-shift function.
Definition: APInt.h:912
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition: APInt.h:199
bool isShiftedMask(unsigned &MaskIdx, unsigned &MaskLen) const
Return true if this APInt value contains a non-empty sequence of ones with the remainder zero.
Definition: APInt.h:502
void setBitsWithWrap(unsigned loBit, unsigned hiBit)
Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
Definition: APInt.h:1334
APInt lshr(const APInt &ShiftAmt) const
Logical right-shift function.
Definition: APInt.h:900
bool isNonPositive() const
Determine if this APInt Value is non-positive (<= 0).
Definition: APInt.h:341
unsigned countTrailingZeros() const
Definition: APInt.h:1606
unsigned getSignificantBits() const
Get the minimum bit size for this signed APInt.
Definition: APInt.h:1491
unsigned countLeadingZeros() const
Definition: APInt.h:1565
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition: APInt.h:336
void flipAllBits()
Toggle every bit to its opposite value.
Definition: APInt.h:1414
static unsigned getNumWords(unsigned BitWidth)
Get the number of words.
Definition: APInt.h:1463
bool needsCleanup() const
Returns whether this instance allocated memory.
Definition: APInt.h:1884
unsigned countl_one() const
Count the number of leading one bits.
Definition: APInt.h:1574
void clearLowBits(unsigned loBits)
Set bottom loBits bits to 0.
Definition: APInt.h:1397
unsigned logBase2() const
Definition: APInt.h:1719
static APInt getZeroWidth()
Return an APInt zero bits wide.
Definition: APInt.h:183
double signedRoundToDouble() const
Converts this signed APInt to a double value.
Definition: APInt.h:1673
bool isShiftedMask() const
Return true if this APInt value contains a non-empty sequence of ones with the remainder zero.
Definition: APInt.h:490
float bitsToFloat() const
Converts APInt bits to a float.
Definition: APInt.h:1694
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition: APInt.h:455
bool ule(uint64_t RHS) const
Unsigned less or equal comparison.
Definition: APInt.h:1138
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition: APInt.h:807
void setAllBits()
Set every bit to 1.
Definition: APInt.h:1299
uint64_t VAL
Used to store the <= 64 bits integer value.
Definition: APInt.h:1890
bool ugt(uint64_t RHS) const
Unsigned greater than comparison.
Definition: APInt.h:1170
bool sge(int64_t RHS) const
Signed greater or equal comparison.
Definition: APInt.h:1225
bool getBoolValue() const
Convert APInt to a boolean value.
Definition: APInt.h:451
static APInt doubleToBits(double V)
Converts a double to APInt bits.
Definition: APInt.h:1702
bool isMask(unsigned numBits) const
Definition: APInt.h:468
APInt & operator=(APInt &&that)
Move assignment operator.
Definition: APInt.h:612
static WordType tcIncrement(WordType *dst, unsigned parts)
Increment a bignum in-place. Return the carry flag.
Definition: APInt.h:1867
APInt & operator^=(const APInt &RHS)
Bitwise XOR assignment operator.
Definition: APInt.h:713
bool isMaxSignedValue() const
Determine if this is the largest signed value.
Definition: APInt.h:385
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition: APInt.h:314
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition: APInt.h:1130
void setBits(unsigned loBit, unsigned hiBit)
Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
Definition: APInt.h:1347
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition: APInt.h:853
double bitsToDouble() const
Converts APInt bits to a double.
Definition: APInt.h:1680
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition: APInt.h:1237
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition: APInt.h:420
unsigned getActiveWords() const
Compute the number of active words in the value of this APInt.
Definition: APInt.h:1478
bool ne(const APInt &RHS) const
Inequality comparison.
Definition: APInt.h:1083
static bool isSameValue(const APInt &I1, const APInt &I2)
Determine if two APInts have the same value, after zero-extending one of them (if needed!...
Definition: APInt.h:533
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition: APInt.h:286
bool isSignBitSet() const
Determine if sign bit of this APInt is set.
Definition: APInt.h:321
const uint64_t * getRawData() const
This function returns a pointer to the internal storage of the APInt.
Definition: APInt.h:549
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition: APInt.h:1110
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition: APInt.h:276
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition: APInt.h:180
void setLowBits(unsigned loBits)
Set the bottom loBits bits.
Definition: APInt.h:1369
bool isIntN(unsigned N) const
Check if this APInt has an N-bits unsigned integer value.
Definition: APInt.h:412
unsigned countTrailingOnes() const
Definition: APInt.h:1621
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition: APInt.h:1217
std::optional< int64_t > trySExtValue() const
Get sign extended value if possible.
Definition: APInt.h:1534
APInt & operator&=(uint64_t RHS)
Bitwise AND assignment operator.
Definition: APInt.h:668
double roundToDouble(bool isSigned) const
Converts this APInt to a double value.
Definition: APInt.cpp:849
bool isOne() const
Determine if this is a value of 1.
Definition: APInt.h:369
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition: APInt.h:266
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition: APInt.h:219
void clearHighBits(unsigned hiBits)
Set top hiBits bits to 0.
Definition: APInt.h:1404
int64_t getSExtValue() const
Get sign extended value.
Definition: APInt.h:1522
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
Definition: APInt.h:838
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition: APInt.h:831
unsigned countr_one() const
Count the number of trailing one bits.
Definition: APInt.h:1615
static APInt getBitsSetWithWrap(unsigned numBits, unsigned loBit, unsigned hiBit)
Wrap version of getBitsSet.
Definition: APInt.h:250
bool isSignBitClear() const
Determine if sign bit of this APInt is clear.
Definition: APInt.h:328
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition: APInt.h:1201
void setBitVal(unsigned BitPosition, bool BitValue)
Set a given bit to a given value.
Definition: APInt.h:1323
void clearSignBit()
Set the sign bit to 0.
Definition: APInt.h:1411
bool isMaxValue() const
Determine if this is the largest unsigned value.
Definition: APInt.h:379
void toStringSigned(SmallVectorImpl< char > &Str, unsigned Radix=10) const
Considers the APInt to be signed and converts it into a string in the radix given.
Definition: APInt.h:1655
bool ult(uint64_t RHS) const
Unsigned less than comparison.
Definition: APInt.h:1099
bool operator!=(uint64_t Val) const
Inequality operator.
Definition: APInt.h:1075
An arbitrary precision integer that knows its signedness.
Definition: APSInt.h:23
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
This class provides support for dynamic arbitrary-precision arithmetic.
Definition: DynamicAPInt.h:44
FoldingSetNodeID - This class is used to gather all the unique data bits of a node.
Definition: FoldingSet.h:327
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
An opaque object representing a hash code.
Definition: Hashing.h:75
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
#define UINT64_MAX
Definition: DataTypes.h:77
std::error_code fromString(StringRef String, Metadata &HSAMetadata)
Converts String to HSAMetadata.
float RoundAPIntToFloat(const APInt &APIVal)
Converts the given APInt to a float value.
Definition: APInt.h:2269
const APInt abdu(const APInt &A, const APInt &B)
Determine the absolute difference of two APInts considered to be unsigned.
Definition: APInt.h:2222
const APInt abds(const APInt &A, const APInt &B)
Determine the absolute difference of two APInts considered to be signed.
Definition: APInt.h:2217
double RoundAPIntToDouble(const APInt &APIVal)
Converts the given APInt to a double value.
Definition: APInt.h:2257
const APInt & smin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be signed.
Definition: APInt.h:2197
const APInt & smax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be signed.
Definition: APInt.h:2202
const APInt & umin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be unsigned.
Definition: APInt.h:2207
APInt RoundFloatToAPInt(float Float, unsigned width)
Converts a float value into a APInt.
Definition: APInt.h:2288
APInt RoundDoubleToAPInt(double Double, unsigned width)
Converts the given double value into a APInt.
Definition: APInt.cpp:810
double RoundSignedAPIntToDouble(const APInt &APIVal)
Converts the given APInt to a double value.
Definition: APInt.h:2264
float RoundSignedAPIntToFloat(const APInt &APIVal)
Converts the given APInt to a float value.
Definition: APInt.h:2276
const APInt & umax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be unsigned.
Definition: APInt.h:2212
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
constexpr T rotr(T V, int R)
Definition: bit.h:407
int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition: bit.h:385
APInt operator&(APInt a, const APInt &b)
Definition: APInt.h:2072
APInt operator*(APInt a, uint64_t RHS)
Definition: APInt.h:2184
int countr_one(T Value)
Count the number of ones from the least significant bit to the first zero bit.
Definition: bit.h:307
bool operator!=(uint64_t V1, const APInt &V2)
Definition: APInt.h:2062
LLVM_ATTRIBUTE_ALWAYS_INLINE DynamicAPInt & operator+=(DynamicAPInt &A, int64_t B)
Definition: DynamicAPInt.h:516
LLVM_ATTRIBUTE_ALWAYS_INLINE DynamicAPInt & operator-=(DynamicAPInt &A, int64_t B)
Definition: DynamicAPInt.h:520
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition: MathExtras.h:296
APInt operator~(APInt v)
Unary bitwise complement operator.
Definition: APInt.h:2067
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition: bit.h:215
constexpr bool isShiftedMask_64(uint64_t Value)
Return true if the argument contains a non-empty sequence of ones with the remainder zero (64 bit ver...
Definition: MathExtras.h:285
LLVM_ATTRIBUTE_ALWAYS_INLINE DynamicAPInt & operator*=(DynamicAPInt &A, int64_t B)
Definition: DynamicAPInt.h:524
int countl_zero(T Val)
Count number of 0's from the most significant bit to the least stopping at the first 1.
Definition: bit.h:281
APInt operator^(APInt a, const APInt &b)
Definition: APInt.h:2112
constexpr bool isMask_64(uint64_t Value)
Return true if the argument is a non-empty sequence of ones starting at the least significant bit wit...
Definition: MathExtras.h:273
int countl_one(T Value)
Count the number of ones from the most significant bit to the first zero bit.
Definition: bit.h:294
ArrayRef(const T &OneElt) -> ArrayRef< T >
APInt operator-(APInt)
Definition: APInt.h:2137
constexpr int64_t SignExtend64(uint64_t x)
Sign-extend the number in the bottom B bits of X to a 64-bit integer.
Definition: MathExtras.h:573
APInt operator+(APInt a, const APInt &b)
Definition: APInt.h:2142
APInt operator|(APInt a, const APInt &b)
Definition: APInt.h:2092
T reverseBits(T Val)
Reverse the bits in Val.
Definition: MathExtras.h:122
constexpr T rotl(T V, int R)
Definition: bit.h:394
@ Keep
No function return thunk.
auto mask(ShuffFunc S, unsigned Length, OptArgs... args) -> MaskT
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
static APInt getTombstoneKey()
Definition: APInt.h:2374
static bool isEqual(const APInt &LHS, const APInt &RHS)
Definition: APInt.h:2382
static unsigned getHashValue(const APInt &Key)
An information struct used to provide DenseMap with the various necessary components for a given valu...
Definition: DenseMapInfo.h:52