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