LLVM 23.0.0git
APInt.cpp
Go to the documentation of this file.
1//===-- APInt.cpp - Implement APInt class ---------------------------------===//
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// This file implements a class to represent arbitrary precision integer
10// constant values and provide a variety of arithmetic operations on them.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/ADT/APInt.h"
15#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/FoldingSet.h"
17#include "llvm/ADT/Hashing.h"
18#include "llvm/ADT/Sequence.h"
20#include "llvm/ADT/StringRef.h"
21#include "llvm/ADT/bit.h"
23#include "llvm/Support/Debug.h"
27#include <cmath>
28#include <optional>
29
30using namespace llvm;
31
32#define DEBUG_TYPE "apint"
33
34/// A utility function for allocating memory, checking for allocation failures,
35/// and ensuring the contents are zeroed.
36inline static uint64_t* getClearedMemory(unsigned numWords) {
37 return new uint64_t[numWords]();
38}
39
40/// A utility function for allocating memory and checking for allocation
41/// failure. The content is not zeroed.
42inline static uint64_t* getMemory(unsigned numWords) {
43 return new uint64_t[numWords];
44}
45
46/// A utility function that converts a character to a digit.
47inline static unsigned getDigit(char cdigit, uint8_t radix) {
48 unsigned r;
49
50 if (radix == 16 || radix == 36) {
51 r = cdigit - '0';
52 if (r <= 9)
53 return r;
54
55 r = cdigit - 'A';
56 if (r <= radix - 11U)
57 return r + 10;
58
59 r = cdigit - 'a';
60 if (r <= radix - 11U)
61 return r + 10;
62
63 radix = 10;
64 }
65
66 r = cdigit - '0';
67 if (r < radix)
68 return r;
69
70 return UINT_MAX;
71}
72
73
74void APInt::initSlowCase(uint64_t val, bool isSigned) {
75 if (isSigned && int64_t(val) < 0) {
76 U.pVal = getMemory(getNumWords());
77 U.pVal[0] = val;
78 memset(&U.pVal[1], 0xFF, APINT_WORD_SIZE * (getNumWords() - 1));
79 clearUnusedBits();
80 } else {
81 U.pVal = getClearedMemory(getNumWords());
82 U.pVal[0] = val;
83 }
84}
85
86void APInt::initSlowCase(const APInt& that) {
87 U.pVal = getMemory(getNumWords());
88 memcpy(U.pVal, that.U.pVal, getNumWords() * APINT_WORD_SIZE);
89}
90
91void APInt::initFromArray(ArrayRef<uint64_t> bigVal) {
92 assert(bigVal.data() && "Null pointer detected!");
93 if (isSingleWord())
94 U.VAL = bigVal[0];
95 else {
96 // Get memory, cleared to 0
97 U.pVal = getClearedMemory(getNumWords());
98 // Calculate the number of words to copy
99 unsigned words = std::min<unsigned>(bigVal.size(), getNumWords());
100 // Copy the words from bigVal to pVal
101 memcpy(U.pVal, bigVal.data(), words * APINT_WORD_SIZE);
102 }
103 // Make sure unused high bits are cleared
104 clearUnusedBits();
105}
106
107APInt::APInt(unsigned numBits, ArrayRef<uint64_t> bigVal) : BitWidth(numBits) {
108 initFromArray(bigVal);
109}
110
111APInt::APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[])
112 : BitWidth(numBits) {
113 initFromArray(ArrayRef(bigVal, numWords));
114}
115
116APInt::APInt(unsigned numbits, StringRef Str, uint8_t radix)
117 : BitWidth(numbits) {
118 fromString(numbits, Str, radix);
119}
120
121void APInt::reallocate(unsigned NewBitWidth) {
122 // If the number of words is the same we can just change the width and stop.
123 if (getNumWords() == getNumWords(NewBitWidth)) {
124 BitWidth = NewBitWidth;
125 return;
126 }
127
128 // If we have an allocation, delete it.
129 if (!isSingleWord())
130 delete [] U.pVal;
131
132 // Update BitWidth.
133 BitWidth = NewBitWidth;
134
135 // If we are supposed to have an allocation, create it.
136 if (!isSingleWord())
137 U.pVal = getMemory(getNumWords());
138}
139
140void APInt::assignSlowCase(const APInt &RHS) {
141 // Don't do anything for X = X
142 if (this == &RHS)
143 return;
144
145 // Adjust the bit width and handle allocations as necessary.
146 reallocate(RHS.getBitWidth());
147
148 // Copy the data.
149 if (isSingleWord())
150 U.VAL = RHS.U.VAL;
151 else
152 memcpy(U.pVal, RHS.U.pVal, getNumWords() * APINT_WORD_SIZE);
153}
154
155/// This method 'profiles' an APInt for use with FoldingSet.
157 ID.AddInteger(BitWidth);
158
159 if (isSingleWord()) {
160 ID.AddInteger(U.VAL);
161 return;
162 }
163
164 unsigned NumWords = getNumWords();
165 for (unsigned i = 0; i < NumWords; ++i)
166 ID.AddInteger(U.pVal[i]);
167}
168
170 if (isZero())
171 return true;
172 const unsigned TrailingZeroes = countr_zero();
173 const unsigned MinimumTrailingZeroes = Log2(A);
174 return TrailingZeroes >= MinimumTrailingZeroes;
175}
176
177/// Prefix increment operator. Increments the APInt by one.
179 if (isSingleWord())
180 ++U.VAL;
181 else
182 tcIncrement(U.pVal, getNumWords());
183 return clearUnusedBits();
184}
185
186/// Prefix decrement operator. Decrements the APInt by one.
188 if (isSingleWord())
189 --U.VAL;
190 else
191 tcDecrement(U.pVal, getNumWords());
192 return clearUnusedBits();
193}
194
195/// Adds the RHS APInt to this APInt.
196/// @returns this, after addition of RHS.
197/// Addition assignment operator.
199 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
200 if (isSingleWord())
201 U.VAL += RHS.U.VAL;
202 else
203 tcAdd(U.pVal, RHS.U.pVal, 0, getNumWords());
204 return clearUnusedBits();
205}
206
208 if (isSingleWord())
209 U.VAL += RHS;
210 else
211 tcAddPart(U.pVal, RHS, getNumWords());
212 return clearUnusedBits();
213}
214
215/// Subtracts the RHS APInt from this APInt
216/// @returns this, after subtraction
217/// Subtraction assignment operator.
219 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
220 if (isSingleWord())
221 U.VAL -= RHS.U.VAL;
222 else
223 tcSubtract(U.pVal, RHS.U.pVal, 0, getNumWords());
224 return clearUnusedBits();
225}
226
228 if (isSingleWord())
229 U.VAL -= RHS;
230 else
231 tcSubtractPart(U.pVal, RHS, getNumWords());
232 return clearUnusedBits();
233}
234
235APInt APInt::operator*(const APInt& RHS) const {
236 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
237 if (isSingleWord())
238 return APInt(BitWidth, U.VAL * RHS.U.VAL, /*isSigned=*/false,
239 /*implicitTrunc=*/true);
240
242 tcMultiply(Result.U.pVal, U.pVal, RHS.U.pVal, getNumWords());
243 Result.clearUnusedBits();
244 return Result;
245}
246
247void APInt::andAssignSlowCase(const APInt &RHS) {
248 WordType *dst = U.pVal, *rhs = RHS.U.pVal;
249 for (size_t i = 0, e = getNumWords(); i != e; ++i)
250 dst[i] &= rhs[i];
251}
252
253void APInt::orAssignSlowCase(const APInt &RHS) {
254 WordType *dst = U.pVal, *rhs = RHS.U.pVal;
255 for (size_t i = 0, e = getNumWords(); i != e; ++i)
256 dst[i] |= rhs[i];
257}
258
259void APInt::xorAssignSlowCase(const APInt &RHS) {
260 WordType *dst = U.pVal, *rhs = RHS.U.pVal;
261 for (size_t i = 0, e = getNumWords(); i != e; ++i)
262 dst[i] ^= rhs[i];
263}
264
266 *this = *this * RHS;
267 return *this;
268}
269
271 if (isSingleWord()) {
272 U.VAL *= RHS;
273 } else {
274 unsigned NumWords = getNumWords();
275 tcMultiplyPart(U.pVal, U.pVal, RHS, 0, NumWords, NumWords, false);
276 }
277 return clearUnusedBits();
278}
279
280bool APInt::equalSlowCase(const APInt &RHS) const {
281 return std::equal(U.pVal, U.pVal + getNumWords(), RHS.U.pVal);
282}
283
284int APInt::compare(const APInt& RHS) const {
285 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
286 if (isSingleWord())
287 return U.VAL < RHS.U.VAL ? -1 : U.VAL > RHS.U.VAL;
288
289 return tcCompare(U.pVal, RHS.U.pVal, getNumWords());
290}
291
292int APInt::compareSigned(const APInt& RHS) const {
293 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
294 if (isSingleWord()) {
295 int64_t lhsSext = SignExtend64(U.VAL, BitWidth);
296 int64_t rhsSext = SignExtend64(RHS.U.VAL, BitWidth);
297 return lhsSext < rhsSext ? -1 : lhsSext > rhsSext;
298 }
299
300 bool lhsNeg = isNegative();
301 bool rhsNeg = RHS.isNegative();
302
303 // If the sign bits don't match, then (LHS < RHS) if LHS is negative
304 if (lhsNeg != rhsNeg)
305 return lhsNeg ? -1 : 1;
306
307 // Otherwise we can just use an unsigned comparison, because even negative
308 // numbers compare correctly this way if both have the same signed-ness.
309 return tcCompare(U.pVal, RHS.U.pVal, getNumWords());
310}
311
312void APInt::setBitsSlowCase(unsigned loBit, unsigned hiBit) {
313 unsigned loWord = whichWord(loBit);
314 unsigned hiWord = whichWord(hiBit);
315
316 // Create an initial mask for the low word with zeros below loBit.
317 uint64_t loMask = WORDTYPE_MAX << whichBit(loBit);
318
319 // If hiBit is not aligned, we need a high mask.
320 unsigned hiShiftAmt = whichBit(hiBit);
321 if (hiShiftAmt != 0) {
322 // Create a high mask with zeros above hiBit.
323 uint64_t hiMask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - hiShiftAmt);
324 // If loWord and hiWord are equal, then we combine the masks. Otherwise,
325 // set the bits in hiWord.
326 if (hiWord == loWord)
327 loMask &= hiMask;
328 else
329 U.pVal[hiWord] |= hiMask;
330 }
331 // Apply the mask to the low word.
332 U.pVal[loWord] |= loMask;
333
334 // Fill any words between loWord and hiWord with all ones.
335 for (unsigned word = loWord + 1; word < hiWord; ++word)
336 U.pVal[word] = WORDTYPE_MAX;
337}
338
339void APInt::clearBitsSlowCase(unsigned LoBit, unsigned HiBit) {
340 unsigned LoWord = whichWord(LoBit);
341 unsigned HiWord = whichWord(HiBit);
342
343 // Create an initial mask for the low word with ones below loBit.
344 uint64_t LoMask = ~(WORDTYPE_MAX << whichBit(LoBit));
345
346 // If HiBit is not aligned, we need a high mask.
347 unsigned HiShiftAmt = whichBit(HiBit);
348 if (HiShiftAmt != 0) {
349 // Create a high mask with ones above HiBit.
350 uint64_t HiMask = ~(WORDTYPE_MAX >> (APINT_BITS_PER_WORD - HiShiftAmt));
351 // If LoWord and HiWord are equal, then we combine the masks. Otherwise,
352 // clear the bits in HiWord.
353 if (HiWord == LoWord)
354 LoMask |= HiMask;
355 else
356 U.pVal[HiWord] &= HiMask;
357 }
358 // Apply the mask to the low word.
359 U.pVal[LoWord] &= LoMask;
360
361 // Fill any words between LoWord and HiWord with all zeros.
362 for (unsigned Word = LoWord + 1; Word < HiWord; ++Word)
363 U.pVal[Word] = 0;
364}
365
366// Complement a bignum in-place.
367static void tcComplement(APInt::WordType *dst, unsigned parts) {
368 for (unsigned i = 0; i < parts; i++)
369 dst[i] = ~dst[i];
370}
371
372/// Toggle every bit to its opposite value.
373void APInt::flipAllBitsSlowCase() {
374 tcComplement(U.pVal, getNumWords());
375 clearUnusedBits();
376}
377
378/// Concatenate the bits from "NewLSB" onto the bottom of *this. This is
379/// equivalent to:
380/// (this->zext(NewWidth) << NewLSB.getBitWidth()) | NewLSB.zext(NewWidth)
381/// In the slow case, we know the result is large.
382APInt APInt::concatSlowCase(const APInt &NewLSB) const {
383 unsigned NewWidth = getBitWidth() + NewLSB.getBitWidth();
384 APInt Result = NewLSB.zext(NewWidth);
385 Result.insertBits(*this, NewLSB.getBitWidth());
386 return Result;
387}
388
389/// Toggle a given bit to its opposite value whose position is given
390/// as "bitPosition".
391/// Toggles a given bit to its opposite value.
392void APInt::flipBit(unsigned bitPosition) {
393 assert(bitPosition < BitWidth && "Out of the bit-width range!");
394 setBitVal(bitPosition, !(*this)[bitPosition]);
395}
396
397void APInt::insertBits(const APInt &subBits, unsigned bitPosition) {
398 unsigned subBitWidth = subBits.getBitWidth();
399 assert((subBitWidth + bitPosition) <= BitWidth && "Illegal bit insertion");
400
401 // inserting no bits is a noop.
402 if (subBitWidth == 0)
403 return;
404
405 // Insertion is a direct copy.
406 if (subBitWidth == BitWidth) {
407 *this = subBits;
408 return;
409 }
410
411 // Single word result can be done as a direct bitmask.
412 if (isSingleWord()) {
413 uint64_t mask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - subBitWidth);
414 U.VAL &= ~(mask << bitPosition);
415 U.VAL |= (subBits.U.VAL << bitPosition);
416 return;
417 }
418
419 unsigned loBit = whichBit(bitPosition);
420 unsigned loWord = whichWord(bitPosition);
421 unsigned hi1Word = whichWord(bitPosition + subBitWidth - 1);
422
423 // Insertion within a single word can be done as a direct bitmask.
424 if (loWord == hi1Word) {
425 uint64_t mask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - subBitWidth);
426 U.pVal[loWord] &= ~(mask << loBit);
427 U.pVal[loWord] |= (subBits.U.VAL << loBit);
428 return;
429 }
430
431 // Insert on word boundaries.
432 if (loBit == 0) {
433 // Direct copy whole words.
434 unsigned numWholeSubWords = subBitWidth / APINT_BITS_PER_WORD;
435 memcpy(U.pVal + loWord, subBits.getRawData(),
436 numWholeSubWords * APINT_WORD_SIZE);
437
438 // Mask+insert remaining bits.
439 unsigned remainingBits = subBitWidth % APINT_BITS_PER_WORD;
440 if (remainingBits != 0) {
441 uint64_t mask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - remainingBits);
442 U.pVal[hi1Word] &= ~mask;
443 U.pVal[hi1Word] |= subBits.getWord(subBitWidth - 1);
444 }
445 return;
446 }
447
448 // General case - set/clear individual bits in dst based on src.
449 // TODO - there is scope for optimization here, but at the moment this code
450 // path is barely used so prefer readability over performance.
451 for (unsigned i = 0; i != subBitWidth; ++i)
452 setBitVal(bitPosition + i, subBits[i]);
453}
454
455void APInt::insertBits(uint64_t subBits, unsigned bitPosition, unsigned numBits) {
456 uint64_t maskBits = maskTrailingOnes<uint64_t>(numBits);
457 subBits &= maskBits;
458 if (isSingleWord()) {
459 U.VAL &= ~(maskBits << bitPosition);
460 U.VAL |= subBits << bitPosition;
461 return;
462 }
463
464 unsigned loBit = whichBit(bitPosition);
465 unsigned loWord = whichWord(bitPosition);
466 unsigned hiWord = whichWord(bitPosition + numBits - 1);
467 if (loWord == hiWord) {
468 U.pVal[loWord] &= ~(maskBits << loBit);
469 U.pVal[loWord] |= subBits << loBit;
470 return;
471 }
472
473 static_assert(8 * sizeof(WordType) <= 64, "This code assumes only two words affected");
474 unsigned wordBits = 8 * sizeof(WordType);
475 U.pVal[loWord] &= ~(maskBits << loBit);
476 U.pVal[loWord] |= subBits << loBit;
477
478 U.pVal[hiWord] &= ~(maskBits >> (wordBits - loBit));
479 U.pVal[hiWord] |= subBits >> (wordBits - loBit);
480}
481
482APInt APInt::extractBits(unsigned numBits, unsigned bitPosition) const {
483 assert(bitPosition < BitWidth && (numBits + bitPosition) <= BitWidth &&
484 "Illegal bit extraction");
485
486 if (isSingleWord())
487 return APInt(numBits, U.VAL >> bitPosition, /*isSigned=*/false,
488 /*implicitTrunc=*/true);
489
490 unsigned loBit = whichBit(bitPosition);
491 unsigned loWord = whichWord(bitPosition);
492 unsigned hiWord = whichWord(bitPosition + numBits - 1);
493
494 // Single word result extracting bits from a single word source.
495 if (loWord == hiWord)
496 return APInt(numBits, U.pVal[loWord] >> loBit, /*isSigned=*/false,
497 /*implicitTrunc=*/true);
498
499 // Extracting bits that start on a source word boundary can be done
500 // as a fast memory copy.
501 if (loBit == 0)
502 return APInt(numBits, ArrayRef(U.pVal + loWord, 1 + hiWord - loWord));
503
504 // General case - shift + copy source words directly into place.
505 APInt Result(numBits, 0);
506 unsigned NumSrcWords = getNumWords();
507 unsigned NumDstWords = Result.getNumWords();
508
509 uint64_t *DestPtr = Result.isSingleWord() ? &Result.U.VAL : Result.U.pVal;
510 for (unsigned word = 0; word < NumDstWords; ++word) {
511 uint64_t w0 = U.pVal[loWord + word];
512 uint64_t w1 =
513 (loWord + word + 1) < NumSrcWords ? U.pVal[loWord + word + 1] : 0;
514 DestPtr[word] = (w0 >> loBit) | (w1 << (APINT_BITS_PER_WORD - loBit));
515 }
516
517 return Result.clearUnusedBits();
518}
519
521 unsigned bitPosition) const {
522 assert(bitPosition < BitWidth && (numBits + bitPosition) <= BitWidth &&
523 "Illegal bit extraction");
524 assert(numBits <= 64 && "Illegal bit extraction");
525
526 uint64_t maskBits = maskTrailingOnes<uint64_t>(numBits);
527 if (isSingleWord())
528 return (U.VAL >> bitPosition) & maskBits;
529
530 static_assert(APINT_BITS_PER_WORD >= 64,
531 "This code assumes only two words affected");
532 unsigned loBit = whichBit(bitPosition);
533 unsigned loWord = whichWord(bitPosition);
534 unsigned hiWord = whichWord(bitPosition + numBits - 1);
535 if (loWord == hiWord)
536 return (U.pVal[loWord] >> loBit) & maskBits;
537
538 uint64_t retBits = U.pVal[loWord] >> loBit;
539 retBits |= U.pVal[hiWord] << (APINT_BITS_PER_WORD - loBit);
540 retBits &= maskBits;
541 return retBits;
542}
543
545 assert(!Str.empty() && "Invalid string length");
546 size_t StrLen = Str.size();
547
548 // Each computation below needs to know if it's negative.
549 unsigned IsNegative = false;
550 if (Str[0] == '-' || Str[0] == '+') {
551 IsNegative = Str[0] == '-';
552 StrLen--;
553 assert(StrLen && "String is only a sign, needs a value.");
554 }
555
556 // For radixes of power-of-two values, the bits required is accurately and
557 // easily computed.
558 if (Radix == 2)
559 return StrLen + IsNegative;
560 if (Radix == 8)
561 return StrLen * 3 + IsNegative;
562 if (Radix == 16)
563 return StrLen * 4 + IsNegative;
564
565 // Compute a sufficient number of bits that is always large enough but might
566 // be too large. This avoids the assertion in the constructor. This
567 // calculation doesn't work appropriately for the numbers 0-9, so just use 4
568 // bits in that case.
569 if (Radix == 10)
570 return (StrLen == 1 ? 4 : StrLen * 64 / 18) + IsNegative;
571
572 assert(Radix == 36);
573 return (StrLen == 1 ? 7 : StrLen * 16 / 3) + IsNegative;
574}
575
577 // Compute a sufficient number of bits that is always large enough but might
578 // be too large.
579 unsigned sufficient = getSufficientBitsNeeded(str, radix);
580
581 // For bases 2, 8, and 16, the sufficient number of bits is exact and we can
582 // return the value directly. For bases 10 and 36, we need to do extra work.
583 if (radix == 2 || radix == 8 || radix == 16)
584 return sufficient;
585
586 // This is grossly inefficient but accurate. We could probably do something
587 // with a computation of roughly slen*64/20 and then adjust by the value of
588 // the first few digits. But, I'm not sure how accurate that could be.
589 size_t slen = str.size();
590
591 // Each computation below needs to know if it's negative.
592 StringRef::iterator p = str.begin();
593 unsigned isNegative = *p == '-';
594 if (*p == '-' || *p == '+') {
595 p++;
596 slen--;
597 assert(slen && "String is only a sign, needs a value.");
598 }
599
600
601 // Convert to the actual binary value.
602 APInt tmp(sufficient, StringRef(p, slen), radix);
603
604 // Compute how many bits are required. If the log is infinite, assume we need
605 // just bit. If the log is exact and value is negative, then the value is
606 // MinSignedValue with (log + 1) bits.
607 unsigned log = tmp.logBase2();
608 if (log == (unsigned)-1) {
609 return isNegative + 1;
610 } else if (isNegative && tmp.isPowerOf2()) {
611 return isNegative + log;
612 } else {
613 return isNegative + log + 1;
614 }
615}
616
618 if (Arg.isSingleWord())
619 return hash_combine(Arg.BitWidth, Arg.U.VAL);
620
621 return hash_combine(
622 Arg.BitWidth,
623 hash_combine_range(Arg.U.pVal, Arg.U.pVal + Arg.getNumWords()));
624}
625
627 return static_cast<unsigned>(hash_value(Key));
628}
629
630bool APInt::isSplat(unsigned SplatSizeInBits) const {
631 assert(getBitWidth() % SplatSizeInBits == 0 &&
632 "SplatSizeInBits must divide width!");
633 // We can check that all parts of an integer are equal by making use of a
634 // little trick: rotate and check if it's still the same value.
635 return *this == rotl(SplatSizeInBits);
636}
637
638/// This function returns the high "numBits" bits of this APInt.
639APInt APInt::getHiBits(unsigned numBits) const {
640 return this->lshr(BitWidth - numBits);
641}
642
643/// This function returns the low "numBits" bits of this APInt.
644APInt APInt::getLoBits(unsigned numBits) const {
645 APInt Result(getLowBitsSet(BitWidth, numBits));
646 Result &= *this;
647 return Result;
648}
649
650/// Return a value containing V broadcasted over NewLen bits.
651APInt APInt::getSplat(unsigned NewLen, const APInt &V) {
652 assert(NewLen >= V.getBitWidth() && "Can't splat to smaller bit width!");
653
654 APInt Val = V.zext(NewLen);
655 for (unsigned I = V.getBitWidth(); I < NewLen; I <<= 1)
656 Val |= Val << I;
657
658 return Val;
659}
660
661unsigned APInt::countLeadingZerosSlowCase() const {
662 unsigned Count = 0;
663 for (int i = getNumWords() - 1; i >= 0; --i) {
664 uint64_t V = U.pVal[i];
665 if (V == 0)
667 else {
669 break;
670 }
671 }
672 // Adjust for unused bits in the most significant word (they are zero).
673 unsigned Mod = BitWidth % APINT_BITS_PER_WORD;
674 Count -= Mod > 0 ? APINT_BITS_PER_WORD - Mod : 0;
675 return Count;
676}
677
678unsigned APInt::countLeadingOnesSlowCase() const {
679 unsigned highWordBits = BitWidth % APINT_BITS_PER_WORD;
680 unsigned shift;
681 if (!highWordBits) {
682 highWordBits = APINT_BITS_PER_WORD;
683 shift = 0;
684 } else {
685 shift = APINT_BITS_PER_WORD - highWordBits;
686 }
687 int i = getNumWords() - 1;
688 unsigned Count = llvm::countl_one(U.pVal[i] << shift);
689 if (Count == highWordBits) {
690 for (i--; i >= 0; --i) {
691 if (U.pVal[i] == WORDTYPE_MAX)
693 else {
694 Count += llvm::countl_one(U.pVal[i]);
695 break;
696 }
697 }
698 }
699 return Count;
700}
701
702unsigned APInt::countTrailingZerosSlowCase() const {
703 unsigned Count = 0;
704 unsigned i = 0;
705 for (; i < getNumWords() && U.pVal[i] == 0; ++i)
707 if (i < getNumWords())
708 Count += llvm::countr_zero(U.pVal[i]);
709 return std::min(Count, BitWidth);
710}
711
712unsigned APInt::countTrailingOnesSlowCase() const {
713 unsigned Count = 0;
714 unsigned i = 0;
715 for (; i < getNumWords() && U.pVal[i] == WORDTYPE_MAX; ++i)
717 if (i < getNumWords())
718 Count += llvm::countr_one(U.pVal[i]);
719 assert(Count <= BitWidth);
720 return Count;
721}
722
723unsigned APInt::countPopulationSlowCase() const {
724 unsigned Count = 0;
725 for (unsigned i = 0; i < getNumWords(); ++i)
726 Count += llvm::popcount(U.pVal[i]);
727 return Count;
728}
729
730bool APInt::isPowerOf2SlowCase() const {
731 unsigned Count = 0;
732 for (unsigned i = 0; i < getNumWords(); ++i) {
733 Count += llvm::popcount(U.pVal[i]);
734 if (Count > 1)
735 return false;
736 }
737 return Count == 1;
738}
739
740bool APInt::intersectsSlowCase(const APInt &RHS) const {
741 for (unsigned i = 0, e = getNumWords(); i != e; ++i)
742 if ((U.pVal[i] & RHS.U.pVal[i]) != 0)
743 return true;
744
745 return false;
746}
747
748bool APInt::isSubsetOfSlowCase(const APInt &RHS) const {
749 for (unsigned i = 0, e = getNumWords(); i != e; ++i)
750 if ((U.pVal[i] & ~RHS.U.pVal[i]) != 0)
751 return false;
752
753 return true;
754}
755
756bool APInt::isInverseOfSlowCase(const APInt &RHS) const {
757 const unsigned Last = getNumWords() - 1;
758 for (unsigned I = 0; I != Last; ++I)
759 if ((U.pVal[I] ^ RHS.U.pVal[I]) != WORDTYPE_MAX)
760 return false;
761
762 unsigned TailBits = BitWidth - Last * APINT_BITS_PER_WORD;
763 WordType TailMask = llvm::maskTrailingOnes<WordType>(TailBits);
764 return (U.pVal[Last] ^ RHS.U.pVal[Last]) == TailMask;
765}
766
768 assert(BitWidth >= 16 && BitWidth % 8 == 0 && "Cannot byteswap!");
769 if (BitWidth == 16)
770 return APInt(BitWidth, llvm::byteswap<uint16_t>(U.VAL));
771 if (BitWidth == 32)
772 return APInt(BitWidth, llvm::byteswap<uint32_t>(U.VAL));
773 if (BitWidth <= 64) {
775 Tmp1 >>= (64 - BitWidth);
776 return APInt(BitWidth, Tmp1);
777 }
778
780 for (unsigned I = 0, N = getNumWords(); I != N; ++I)
781 Result.U.pVal[I] = llvm::byteswap<uint64_t>(U.pVal[N - I - 1]);
782 if (Result.BitWidth != BitWidth) {
783 Result.lshrInPlace(Result.BitWidth - BitWidth);
784 Result.BitWidth = BitWidth;
785 }
786 return Result;
787}
788
790 if (isSingleWord()) {
791 switch (BitWidth) {
792 case 64:
793 return APInt(BitWidth, llvm::reverseBits<uint64_t>(U.VAL));
794 case 32:
795 return APInt(BitWidth, llvm::reverseBits<uint32_t>(U.VAL));
796 case 16:
797 return APInt(BitWidth, llvm::reverseBits<uint16_t>(U.VAL));
798 case 8:
799 return APInt(BitWidth, llvm::reverseBits<uint8_t>(U.VAL));
800 case 1: // fallthrough
801 case 0:
802 return *this;
803 default:
804 return APInt(BitWidth,
805 llvm::reverseBits<uint64_t>(U.VAL) >> (64 - BitWidth));
806 }
807 }
808
809 APInt Result(BitWidth, 0);
810 unsigned NumWords = getNumWords();
811 unsigned ExcessBits = NumWords * APINT_BITS_PER_WORD - BitWidth;
812 if (ExcessBits == 0) {
813 // Fast path. No cross-word shift needed.
814 for (unsigned I = 0; I < NumWords; ++I)
815 Result.U.pVal[I] = llvm::reverseBits<uint64_t>(U.pVal[NumWords - 1 - I]);
816 return Result;
817 }
818 // Holds reversed bits of the previous (more significant) word.
819 uint64_t PrevRev = llvm::reverseBits<uint64_t>(U.pVal[NumWords - 1]);
820 for (unsigned I = 0; I < NumWords - 1; ++I) {
821 uint64_t CurrRev = llvm::reverseBits<uint64_t>(U.pVal[NumWords - 2 - I]);
822 Result.U.pVal[I] = (PrevRev >> ExcessBits) | (CurrRev << (64 - ExcessBits));
823 PrevRev = CurrRev;
824 }
825 Result.U.pVal[NumWords - 1] = PrevRev >> ExcessBits;
826 return Result;
827}
828
830 // Fast-path a common case.
831 if (A == B) return A;
832
833 // Corner cases: if either operand is zero, the other is the gcd.
834 if (!A) return B;
835 if (!B) return A;
836
837 // Count common powers of 2 and remove all other powers of 2.
838 unsigned Pow2;
839 {
840 unsigned Pow2_A = A.countr_zero();
841 unsigned Pow2_B = B.countr_zero();
842 if (Pow2_A > Pow2_B) {
843 A.lshrInPlace(Pow2_A - Pow2_B);
844 Pow2 = Pow2_B;
845 } else if (Pow2_B > Pow2_A) {
846 B.lshrInPlace(Pow2_B - Pow2_A);
847 Pow2 = Pow2_A;
848 } else {
849 Pow2 = Pow2_A;
850 }
851 }
852
853 // Both operands are odd multiples of 2^Pow_2:
854 //
855 // gcd(a, b) = gcd(|a - b| / 2^i, min(a, b))
856 //
857 // This is a modified version of Stein's algorithm, taking advantage of
858 // efficient countTrailingZeros().
859 while (A != B) {
860 if (A.ugt(B)) {
861 A -= B;
862 A.lshrInPlace(A.countr_zero() - Pow2);
863 } else {
864 B -= A;
865 B.lshrInPlace(B.countr_zero() - Pow2);
866 }
867 }
868
869 return A;
870}
871
872APInt llvm::APIntOps::RoundDoubleToAPInt(double Double, unsigned width) {
873 uint64_t I = bit_cast<uint64_t>(Double);
874
875 // Get the sign bit from the highest order bit
876 bool isNeg = I >> 63;
877
878 // Get the 11-bit exponent and adjust for the 1023 bit bias
879 int64_t exp = ((I >> 52) & 0x7ff) - 1023;
880
881 // If the exponent is negative, the value is < 0 so just return 0.
882 if (exp < 0)
883 return APInt(width, 0u);
884
885 // Extract the mantissa by clearing the top 12 bits (sign + exponent).
886 uint64_t mantissa = (I & (~0ULL >> 12)) | 1ULL << 52;
887
888 // If the exponent doesn't shift all bits out of the mantissa
889 if (exp < 52)
890 return isNeg ? -APInt(width, mantissa >> (52 - exp)) :
891 APInt(width, mantissa >> (52 - exp));
892
893 // If the client didn't provide enough bits for us to shift the mantissa into
894 // then the result is undefined, just return 0
895 if (width <= exp - 52)
896 return APInt(width, 0);
897
898 // Otherwise, we have to shift the mantissa bits up to the right location
899 APInt Tmp(width, mantissa);
900 Tmp <<= (unsigned)exp - 52;
901 return isNeg ? -Tmp : Tmp;
902}
903
904/// This function converts this APInt to a double.
905/// The layout for double is as following (IEEE Standard 754):
906/// --------------------------------------
907/// | Sign Exponent Fraction Bias |
908/// |-------------------------------------- |
909/// | 1[63] 11[62-52] 52[51-00] 1023 |
910/// --------------------------------------
911double APInt::roundToDouble(bool isSigned) const {
912 // Handle the simple case where the value is contained in one uint64_t.
913 // It is wrong to optimize getWord(0) to VAL; there might be more than one word.
915 if (isSigned) {
916 int64_t sext = SignExtend64(getWord(0), BitWidth);
917 return double(sext);
918 }
919 return double(getWord(0));
920 }
921
922 // Determine if the value is negative.
923 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
924
925 // Construct the absolute value if we're negative.
926 APInt Tmp(isNeg ? -(*this) : (*this));
927
928 // Figure out how many bits we're using.
929 unsigned n = Tmp.getActiveBits();
930
931 // The exponent (without bias normalization) is just the number of bits
932 // we are using. Note that the sign bit is gone since we constructed the
933 // absolute value.
934 uint64_t exp = n;
935
936 // Return infinity for exponent overflow
937 if (exp > 1023) {
938 if (!isSigned || !isNeg)
939 return std::numeric_limits<double>::infinity();
940 else
941 return -std::numeric_limits<double>::infinity();
942 }
943 exp += 1023; // Increment for 1023 bias
944
945 // Number of bits in mantissa is 52. To obtain the mantissa value, we must
946 // extract the high 52 bits from the correct words in pVal.
947 uint64_t mantissa;
948 unsigned hiWord = whichWord(n-1);
949 if (hiWord == 0) {
950 mantissa = Tmp.U.pVal[0];
951 if (n > 52)
952 mantissa >>= n - 52; // shift down, we want the top 52 bits.
953 } else {
954 assert(hiWord > 0 && "huh?");
955 uint64_t hibits = Tmp.U.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
956 uint64_t lobits = Tmp.U.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
957 mantissa = hibits | lobits;
958 }
959
960 // The leading bit of mantissa is implicit, so get rid of it.
961 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
962 uint64_t I = sign | (exp << 52) | mantissa;
963 return bit_cast<double>(I);
964}
965
966// Truncate to new width.
967APInt APInt::trunc(unsigned width) const {
968 assert(width <= BitWidth && "Invalid APInt Truncate request");
969
970 if (width <= APINT_BITS_PER_WORD)
971 return APInt(width, getRawData()[0], /*isSigned=*/false,
972 /*implicitTrunc=*/true);
973
974 if (width == BitWidth)
975 return *this;
976
977 APInt Result(getMemory(getNumWords(width)), width);
978
979 // Copy full words.
980 unsigned i;
981 for (i = 0; i != width / APINT_BITS_PER_WORD; i++)
982 Result.U.pVal[i] = U.pVal[i];
983
984 // Truncate and copy any partial word.
985 unsigned bits = (0 - width) % APINT_BITS_PER_WORD;
986 if (bits != 0)
987 Result.U.pVal[i] = U.pVal[i] << bits >> bits;
988
989 return Result;
990}
991
992// Truncate to new width with unsigned saturation.
993APInt APInt::truncUSat(unsigned width) const {
994 assert(width <= BitWidth && "Invalid APInt Truncate request");
995
996 // Can we just losslessly truncate it?
997 if (isIntN(width))
998 return trunc(width);
999 // If not, then just return the new limit.
1000 return APInt::getMaxValue(width);
1001}
1002
1003// Truncate to new width with signed saturation to signed result.
1004APInt APInt::truncSSat(unsigned width) const {
1005 assert(width <= BitWidth && "Invalid APInt Truncate request");
1006
1007 // Can we just losslessly truncate it?
1008 if (isSignedIntN(width))
1009 return trunc(width);
1010 // If not, then just return the new limits.
1011 return isNegative() ? APInt::getSignedMinValue(width)
1012 : APInt::getSignedMaxValue(width);
1013}
1014
1015// Truncate to new width with signed saturation to unsigned result.
1016APInt APInt::truncSSatU(unsigned width) const {
1017 assert(width <= BitWidth && "Invalid APInt Truncate request");
1018
1019 // Can we just losslessly truncate it?
1020 if (isIntN(width))
1021 return trunc(width);
1022 // If not, then just return the new limits.
1023 return isNegative() ? APInt::getZero(width) : APInt::getMaxValue(width);
1024}
1025
1026// Sign extend to a new width.
1027APInt APInt::sext(unsigned Width) const {
1028 assert(Width >= BitWidth && "Invalid APInt SignExtend request");
1029
1030 if (Width <= APINT_BITS_PER_WORD)
1031 return APInt(Width, SignExtend64(U.VAL, BitWidth), /*isSigned=*/true);
1032
1033 if (Width == BitWidth)
1034 return *this;
1035
1036 APInt Result(getMemory(getNumWords(Width)), Width);
1037
1038 // Copy words.
1039 std::memcpy(Result.U.pVal, getRawData(), getNumWords() * APINT_WORD_SIZE);
1040
1041 // Sign extend the last word since there may be unused bits in the input.
1042 Result.U.pVal[getNumWords() - 1] =
1043 SignExtend64(Result.U.pVal[getNumWords() - 1],
1044 ((BitWidth - 1) % APINT_BITS_PER_WORD) + 1);
1045
1046 // Fill with sign bits.
1047 std::memset(Result.U.pVal + getNumWords(), isNegative() ? -1 : 0,
1048 (Result.getNumWords() - getNumWords()) * APINT_WORD_SIZE);
1049 Result.clearUnusedBits();
1050 return Result;
1051}
1052
1053// Zero extend to a new width.
1054APInt APInt::zext(unsigned width) const {
1055 assert(width >= BitWidth && "Invalid APInt ZeroExtend request");
1056
1057 if (width <= APINT_BITS_PER_WORD)
1058 return APInt(width, U.VAL);
1059
1060 if (width == BitWidth)
1061 return *this;
1062
1063 APInt Result(getMemory(getNumWords(width)), width);
1064
1065 // Copy words.
1066 std::memcpy(Result.U.pVal, getRawData(), getNumWords() * APINT_WORD_SIZE);
1067
1068 // Zero remaining words.
1069 std::memset(Result.U.pVal + getNumWords(), 0,
1070 (Result.getNumWords() - getNumWords()) * APINT_WORD_SIZE);
1071
1072 return Result;
1073}
1074
1075APInt APInt::zextOrTrunc(unsigned width) const {
1076 if (BitWidth < width)
1077 return zext(width);
1078 if (BitWidth > width)
1079 return trunc(width);
1080 return *this;
1081}
1082
1083APInt APInt::sextOrTrunc(unsigned width) const {
1084 if (BitWidth < width)
1085 return sext(width);
1086 if (BitWidth > width)
1087 return trunc(width);
1088 return *this;
1089}
1090
1091/// Arithmetic right-shift this APInt by shiftAmt.
1092/// Arithmetic right-shift function.
1093void APInt::ashrInPlace(const APInt &shiftAmt) {
1094 ashrInPlace((unsigned)shiftAmt.getLimitedValue(BitWidth));
1095}
1096
1097/// Arithmetic right-shift this APInt by shiftAmt.
1098/// Arithmetic right-shift function.
1099void APInt::ashrSlowCase(unsigned ShiftAmt) {
1100 // Don't bother performing a no-op shift.
1101 if (!ShiftAmt)
1102 return;
1103
1104 // Save the original sign bit for later.
1105 bool Negative = isNegative();
1106
1107 // WordShift is the inter-part shift; BitShift is intra-part shift.
1108 unsigned WordShift = ShiftAmt / APINT_BITS_PER_WORD;
1109 unsigned BitShift = ShiftAmt % APINT_BITS_PER_WORD;
1110
1111 unsigned WordsToMove = getNumWords() - WordShift;
1112 if (WordsToMove != 0) {
1113 // Sign extend the last word to fill in the unused bits.
1114 U.pVal[getNumWords() - 1] = SignExtend64(
1115 U.pVal[getNumWords() - 1], ((BitWidth - 1) % APINT_BITS_PER_WORD) + 1);
1116
1117 // Fastpath for moving by whole words.
1118 if (BitShift == 0) {
1119 std::memmove(U.pVal, U.pVal + WordShift, WordsToMove * APINT_WORD_SIZE);
1120 } else {
1121 // Move the words containing significant bits.
1122 for (unsigned i = 0; i != WordsToMove - 1; ++i)
1123 U.pVal[i] = (U.pVal[i + WordShift] >> BitShift) |
1124 (U.pVal[i + WordShift + 1] << (APINT_BITS_PER_WORD - BitShift));
1125
1126 // Handle the last word which has no high bits to copy. Use an arithmetic
1127 // shift to preserve the sign bit.
1128 U.pVal[WordsToMove - 1] =
1129 (int64_t)U.pVal[WordShift + WordsToMove - 1] >> BitShift;
1130 }
1131 }
1132
1133 // Fill in the remainder based on the original sign.
1134 std::memset(U.pVal + WordsToMove, Negative ? -1 : 0,
1135 WordShift * APINT_WORD_SIZE);
1136 clearUnusedBits();
1137}
1138
1139/// Logical right-shift this APInt by shiftAmt.
1140/// Logical right-shift function.
1141void APInt::lshrInPlace(const APInt &shiftAmt) {
1142 lshrInPlace((unsigned)shiftAmt.getLimitedValue(BitWidth));
1143}
1144
1145/// Logical right-shift this APInt by shiftAmt.
1146/// Logical right-shift function.
1147void APInt::lshrSlowCase(unsigned ShiftAmt) {
1148 tcShiftRight(U.pVal, getNumWords(), ShiftAmt);
1149}
1150
1151/// Left-shift this APInt by shiftAmt.
1152/// Left-shift function.
1153APInt &APInt::operator<<=(const APInt &shiftAmt) {
1154 // It's undefined behavior in C to shift by BitWidth or greater.
1155 *this <<= (unsigned)shiftAmt.getLimitedValue(BitWidth);
1156 return *this;
1157}
1158
1159void APInt::shlSlowCase(unsigned ShiftAmt) {
1160 tcShiftLeft(U.pVal, getNumWords(), ShiftAmt);
1162}
1163
1164// Calculate the rotate amount modulo the bit width.
1165static unsigned rotateModulo(unsigned BitWidth, const APInt &rotateAmt) {
1166 if (LLVM_UNLIKELY(BitWidth == 0))
1167 return 0;
1168 unsigned rotBitWidth = rotateAmt.getBitWidth();
1169 APInt rot = rotateAmt;
1170 if (rotBitWidth < BitWidth) {
1171 // Extend the rotate APInt, so that the urem doesn't divide by 0.
1172 // e.g. APInt(1, 32) would give APInt(1, 0).
1173 rot = rotateAmt.zext(BitWidth);
1174 }
1175 rot = rot.urem(APInt(rot.getBitWidth(), BitWidth));
1176 return rot.getLimitedValue(BitWidth);
1177}
1178
1179APInt APInt::rotl(const APInt &rotateAmt) const {
1180 return rotl(rotateModulo(BitWidth, rotateAmt));
1181}
1182
1183APInt APInt::rotl(unsigned rotateAmt) const {
1184 if (LLVM_UNLIKELY(BitWidth == 0))
1185 return *this;
1186 rotateAmt %= BitWidth;
1187 if (rotateAmt == 0)
1188 return *this;
1189 return shl(rotateAmt) | lshr(BitWidth - rotateAmt);
1190}
1191
1192APInt APInt::rotr(const APInt &rotateAmt) const {
1193 return rotr(rotateModulo(BitWidth, rotateAmt));
1194}
1195
1196APInt APInt::rotr(unsigned rotateAmt) const {
1197 if (BitWidth == 0)
1198 return *this;
1199 rotateAmt %= BitWidth;
1200 if (rotateAmt == 0)
1201 return *this;
1202 return lshr(rotateAmt) | shl(BitWidth - rotateAmt);
1203}
1204
1205/// \returns the nearest log base 2 of this APInt. Ties round up.
1206///
1207/// NOTE: When we have a BitWidth of 1, we define:
1208///
1209/// log2(0) = UINT32_MAX
1210/// log2(1) = 0
1211///
1212/// to get around any mathematical concerns resulting from
1213/// referencing 2 in a space where 2 does no exist.
1214unsigned APInt::nearestLogBase2() const {
1215 // Special case when we have a bitwidth of 1. If VAL is 1, then we
1216 // get 0. If VAL is 0, we get WORDTYPE_MAX which gets truncated to
1217 // UINT32_MAX.
1218 if (BitWidth == 1)
1219 return U.VAL - 1;
1220
1221 // Handle the zero case.
1222 if (isZero())
1223 return UINT32_MAX;
1224
1225 // The non-zero case is handled by computing:
1226 //
1227 // nearestLogBase2(x) = logBase2(x) + x[logBase2(x)-1].
1228 //
1229 // where x[i] is referring to the value of the ith bit of x.
1230 unsigned lg = logBase2();
1231 return lg + unsigned((*this)[lg - 1]);
1232}
1233
1234// Square Root - this method computes and returns the square root of "this".
1235// Three mechanisms are used for computation. For small values (<= 5 bits),
1236// a table lookup is done. This gets some performance for common cases. For
1237// values using less than 52 bits, the value is converted to double and then
1238// the libc sqrt function is called. The result is rounded and then converted
1239// back to a uint64_t which is then used to construct the result. Finally,
1240// the Babylonian method for computing square roots is used.
1242
1243 // Determine the magnitude of the value.
1244 unsigned magnitude = getActiveBits();
1245
1246 // Use a fast table for some small values. This also gets rid of some
1247 // rounding errors in libc sqrt for small values.
1248 if (magnitude <= 5) {
1249 static const uint8_t results[32] = {
1250 /* 0 */ 0,
1251 /* 1- 2 */ 1, 1,
1252 /* 3- 6 */ 2, 2, 2, 2,
1253 /* 7-12 */ 3, 3, 3, 3, 3, 3,
1254 /* 13-20 */ 4, 4, 4, 4, 4, 4, 4, 4,
1255 /* 21-30 */ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
1256 /* 31 */ 6
1257 };
1258 return APInt(BitWidth, results[ (isSingleWord() ? U.VAL : U.pVal[0]) ]);
1259 }
1260
1261 // If the magnitude of the value fits in less than 52 bits (the precision of
1262 // an IEEE double precision floating point value), then we can use the
1263 // libc sqrt function which will probably use a hardware sqrt computation.
1264 // This should be faster than the algorithm below.
1265 if (magnitude < 52) {
1266 return APInt(BitWidth,
1267 uint64_t(::round(::sqrt(double(isSingleWord() ? U.VAL
1268 : U.pVal[0])))));
1269 }
1270
1271 // Okay, all the short cuts are exhausted. We must compute it. The following
1272 // is a classical Babylonian method for computing the square root. This code
1273 // was adapted to APInt from a wikipedia article on such computations.
1274 // See http://www.wikipedia.org/ and go to the page named
1275 // Calculate_an_integer_square_root.
1276 unsigned nbits = BitWidth, i = 4;
1277 APInt testy(BitWidth, 16);
1278 APInt x_old(BitWidth, 1);
1279 APInt x_new(BitWidth, 0);
1280 APInt two(BitWidth, 2);
1281
1282 // Select a good starting value using binary logarithms.
1283 for (;; i += 2, testy = testy.shl(2))
1284 if (i >= nbits || this->ule(testy)) {
1285 x_old = x_old.shl(i / 2);
1286 break;
1287 }
1288
1289 // Use the Babylonian method to arrive at the integer square root:
1290 for (;;) {
1291 x_new = (this->udiv(x_old) + x_old).udiv(two);
1292 if (x_old.ule(x_new))
1293 break;
1294 x_old = x_new;
1295 }
1296
1297 // Make sure we return the closest approximation
1298 // NOTE: The rounding calculation below is correct. It will produce an
1299 // off-by-one discrepancy with results from pari/gp. That discrepancy has been
1300 // determined to be a rounding issue with pari/gp as it begins to use a
1301 // floating point representation after 192 bits. There are no discrepancies
1302 // between this algorithm and pari/gp for bit widths < 192 bits.
1303 APInt square(x_old * x_old);
1304 APInt nextSquare((x_old + 1) * (x_old +1));
1305 if (this->ult(square))
1306 return x_old;
1307 assert(this->ule(nextSquare) && "Error in APInt::sqrt computation");
1308 APInt midpoint((nextSquare - square).udiv(two));
1309 APInt offset(*this - square);
1310 if (offset.ult(midpoint))
1311 return x_old;
1312 return x_old + 1;
1313}
1314
1315/// \returns the multiplicative inverse of an odd APInt modulo 2^BitWidth.
1317 assert((*this)[0] &&
1318 "multiplicative inverse is only defined for odd numbers!");
1319
1320 // Use Newton's method.
1321 APInt Factor = *this;
1322 APInt T;
1323 while (!(T = *this * Factor).isOne())
1324 Factor *= 2 - std::move(T);
1325 return Factor;
1326}
1327
1328/// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
1329/// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
1330/// variables here have the same names as in the algorithm. Comments explain
1331/// the algorithm and any deviation from it.
1332static void KnuthDiv(uint32_t *u, uint32_t *v, uint32_t *q, uint32_t* r,
1333 unsigned m, unsigned n) {
1334 assert(u && "Must provide dividend");
1335 assert(v && "Must provide divisor");
1336 assert(q && "Must provide quotient");
1337 assert(u != v && u != q && v != q && "Must use different memory");
1338 assert(n>1 && "n must be > 1");
1339
1340 // b denotes the base of the number system. In our case b is 2^32.
1341 const uint64_t b = uint64_t(1) << 32;
1342
1343// The DEBUG macros here tend to be spam in the debug output if you're not
1344// debugging this code. Disable them unless KNUTH_DEBUG is defined.
1345#ifdef KNUTH_DEBUG
1346#define DEBUG_KNUTH(X) LLVM_DEBUG(X)
1347#else
1348#define DEBUG_KNUTH(X) do {} while(false)
1349#endif
1350
1351 DEBUG_KNUTH(dbgs() << "KnuthDiv: m=" << m << " n=" << n << '\n');
1352 DEBUG_KNUTH(dbgs() << "KnuthDiv: original:");
1353 DEBUG_KNUTH(for (int i = m + n; i >= 0; i--) dbgs() << " " << u[i]);
1354 DEBUG_KNUTH(dbgs() << " by");
1355 DEBUG_KNUTH(for (int i = n; i > 0; i--) dbgs() << " " << v[i - 1]);
1356 DEBUG_KNUTH(dbgs() << '\n');
1357 // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
1358 // u and v by d. Note that we have taken Knuth's advice here to use a power
1359 // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
1360 // 2 allows us to shift instead of multiply and it is easy to determine the
1361 // shift amount from the leading zeros. We are basically normalizing the u
1362 // and v so that its high bits are shifted to the top of v's range without
1363 // overflow. Note that this can require an extra word in u so that u must
1364 // be of length m+n+1.
1365 unsigned shift = llvm::countl_zero(v[n - 1]);
1366 uint32_t v_carry = 0;
1367 uint32_t u_carry = 0;
1368 if (shift) {
1369 for (unsigned i = 0; i < m+n; ++i) {
1370 uint32_t u_tmp = u[i] >> (32 - shift);
1371 u[i] = (u[i] << shift) | u_carry;
1372 u_carry = u_tmp;
1373 }
1374 for (unsigned i = 0; i < n; ++i) {
1375 uint32_t v_tmp = v[i] >> (32 - shift);
1376 v[i] = (v[i] << shift) | v_carry;
1377 v_carry = v_tmp;
1378 }
1379 }
1380 u[m+n] = u_carry;
1381
1382 DEBUG_KNUTH(dbgs() << "KnuthDiv: normal:");
1383 DEBUG_KNUTH(for (int i = m + n; i >= 0; i--) dbgs() << " " << u[i]);
1384 DEBUG_KNUTH(dbgs() << " by");
1385 DEBUG_KNUTH(for (int i = n; i > 0; i--) dbgs() << " " << v[i - 1]);
1386 DEBUG_KNUTH(dbgs() << '\n');
1387
1388 // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
1389 int j = m;
1390 do {
1391 DEBUG_KNUTH(dbgs() << "KnuthDiv: quotient digit #" << j << '\n');
1392 // D3. [Calculate q'.].
1393 // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
1394 // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
1395 // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
1396 // qp by 1, increase rp by v[n-1], and repeat this test if rp < b. The test
1397 // on v[n-2] determines at high speed most of the cases in which the trial
1398 // value qp is one too large, and it eliminates all cases where qp is two
1399 // too large.
1400 uint64_t dividend = Make_64(u[j+n], u[j+n-1]);
1401 DEBUG_KNUTH(dbgs() << "KnuthDiv: dividend == " << dividend << '\n');
1402 uint64_t qp = dividend / v[n-1];
1403 uint64_t rp = dividend % v[n-1];
1404 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1405 qp--;
1406 rp += v[n-1];
1407 if (rp < b && (qp == b || qp*v[n-2] > b*rp + u[j+n-2]))
1408 qp--;
1409 }
1410 DEBUG_KNUTH(dbgs() << "KnuthDiv: qp == " << qp << ", rp == " << rp << '\n');
1411
1412 // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with
1413 // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation
1414 // consists of a simple multiplication by a one-place number, combined with
1415 // a subtraction.
1416 // The digits (u[j+n]...u[j]) should be kept positive; if the result of
1417 // this step is actually negative, (u[j+n]...u[j]) should be left as the
1418 // true value plus b**(n+1), namely as the b's complement of
1419 // the true value, and a "borrow" to the left should be remembered.
1420 int64_t borrow = 0;
1421 for (unsigned i = 0; i < n; ++i) {
1422 uint64_t p = qp * uint64_t(v[i]);
1423 int64_t subres = int64_t(u[j+i]) - borrow - Lo_32(p);
1424 u[j+i] = Lo_32(subres);
1425 borrow = Hi_32(p) - Hi_32(subres);
1426 DEBUG_KNUTH(dbgs() << "KnuthDiv: u[j+i] = " << u[j + i]
1427 << ", borrow = " << borrow << '\n');
1428 }
1429 bool isNeg = u[j+n] < borrow;
1430 u[j+n] -= Lo_32(borrow);
1431
1432 DEBUG_KNUTH(dbgs() << "KnuthDiv: after subtraction:");
1433 DEBUG_KNUTH(for (int i = m + n; i >= 0; i--) dbgs() << " " << u[i]);
1434 DEBUG_KNUTH(dbgs() << '\n');
1435
1436 // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
1437 // negative, go to step D6; otherwise go on to step D7.
1438 q[j] = Lo_32(qp);
1439 if (isNeg) {
1440 // D6. [Add back]. The probability that this step is necessary is very
1441 // small, on the order of only 2/b. Make sure that test data accounts for
1442 // this possibility. Decrease q[j] by 1
1443 q[j]--;
1444 // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]).
1445 // A carry will occur to the left of u[j+n], and it should be ignored
1446 // since it cancels with the borrow that occurred in D4.
1447 bool carry = false;
1448 for (unsigned i = 0; i < n; i++) {
1449 uint32_t limit = std::min(u[j+i],v[i]);
1450 u[j+i] += v[i] + carry;
1451 carry = u[j+i] < limit || (carry && u[j+i] == limit);
1452 }
1453 u[j+n] += carry;
1454 }
1455 DEBUG_KNUTH(dbgs() << "KnuthDiv: after correction:");
1456 DEBUG_KNUTH(for (int i = m + n; i >= 0; i--) dbgs() << " " << u[i]);
1457 DEBUG_KNUTH(dbgs() << "\nKnuthDiv: digit result = " << q[j] << '\n');
1458
1459 // D7. [Loop on j.] Decrease j by one. Now if j >= 0, go back to D3.
1460 } while (--j >= 0);
1461
1462 DEBUG_KNUTH(dbgs() << "KnuthDiv: quotient:");
1463 DEBUG_KNUTH(for (int i = m; i >= 0; i--) dbgs() << " " << q[i]);
1464 DEBUG_KNUTH(dbgs() << '\n');
1465
1466 // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
1467 // remainder may be obtained by dividing u[...] by d. If r is non-null we
1468 // compute the remainder (urem uses this).
1469 if (r) {
1470 // The value d is expressed by the "shift" value above since we avoided
1471 // multiplication by d by using a shift left. So, all we have to do is
1472 // shift right here.
1473 if (shift) {
1474 uint32_t carry = 0;
1475 DEBUG_KNUTH(dbgs() << "KnuthDiv: remainder:");
1476 for (int i = n-1; i >= 0; i--) {
1477 r[i] = (u[i] >> shift) | carry;
1478 carry = u[i] << (32 - shift);
1479 DEBUG_KNUTH(dbgs() << " " << r[i]);
1480 }
1481 } else {
1482 for (int i = n-1; i >= 0; i--) {
1483 r[i] = u[i];
1484 DEBUG_KNUTH(dbgs() << " " << r[i]);
1485 }
1486 }
1487 DEBUG_KNUTH(dbgs() << '\n');
1488 }
1489 DEBUG_KNUTH(dbgs() << '\n');
1490}
1491
1492void APInt::divide(const WordType *LHS, unsigned lhsWords, const WordType *RHS,
1493 unsigned rhsWords, WordType *Quotient, WordType *Remainder) {
1494 assert(lhsWords >= rhsWords && "Fractional result");
1495
1496 // First, compose the values into an array of 32-bit words instead of
1497 // 64-bit words. This is a necessity of both the "short division" algorithm
1498 // and the Knuth "classical algorithm" which requires there to be native
1499 // operations for +, -, and * on an m bit value with an m*2 bit result. We
1500 // can't use 64-bit operands here because we don't have native results of
1501 // 128-bits. Furthermore, casting the 64-bit values to 32-bit values won't
1502 // work on large-endian machines.
1503 unsigned n = rhsWords * 2;
1504 unsigned m = (lhsWords * 2) - n;
1505
1506 // Allocate space for the temporary values we need either on the stack, if
1507 // it will fit, or on the heap if it won't.
1508 uint32_t SPACE[128];
1509 uint32_t *U = nullptr;
1510 uint32_t *V = nullptr;
1511 uint32_t *Q = nullptr;
1512 uint32_t *R = nullptr;
1513 if ((Remainder?4:3)*n+2*m+1 <= 128) {
1514 U = &SPACE[0];
1515 V = &SPACE[m+n+1];
1516 Q = &SPACE[(m+n+1) + n];
1517 if (Remainder)
1518 R = &SPACE[(m+n+1) + n + (m+n)];
1519 } else {
1520 U = new uint32_t[m + n + 1];
1521 V = new uint32_t[n];
1522 Q = new uint32_t[m+n];
1523 if (Remainder)
1524 R = new uint32_t[n];
1525 }
1526
1527 // Initialize the dividend
1528 memset(U, 0, (m+n+1)*sizeof(uint32_t));
1529 for (unsigned i = 0; i < lhsWords; ++i) {
1530 uint64_t tmp = LHS[i];
1531 U[i * 2] = Lo_32(tmp);
1532 U[i * 2 + 1] = Hi_32(tmp);
1533 }
1534 U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
1535
1536 // Initialize the divisor
1537 memset(V, 0, (n)*sizeof(uint32_t));
1538 for (unsigned i = 0; i < rhsWords; ++i) {
1539 uint64_t tmp = RHS[i];
1540 V[i * 2] = Lo_32(tmp);
1541 V[i * 2 + 1] = Hi_32(tmp);
1542 }
1543
1544 // initialize the quotient and remainder
1545 memset(Q, 0, (m+n) * sizeof(uint32_t));
1546 if (Remainder)
1547 memset(R, 0, n * sizeof(uint32_t));
1548
1549 // Now, adjust m and n for the Knuth division. n is the number of words in
1550 // the divisor. m is the number of words by which the dividend exceeds the
1551 // divisor (i.e. m+n is the length of the dividend). These sizes must not
1552 // contain any zero words or the Knuth algorithm fails.
1553 for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
1554 n--;
1555 m++;
1556 }
1557 for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
1558 m--;
1559
1560 // If we're left with only a single word for the divisor, Knuth doesn't work
1561 // so we implement the short division algorithm here. This is much simpler
1562 // and faster because we are certain that we can divide a 64-bit quantity
1563 // by a 32-bit quantity at hardware speed and short division is simply a
1564 // series of such operations. This is just like doing short division but we
1565 // are using base 2^32 instead of base 10.
1566 assert(n != 0 && "Divide by zero?");
1567 if (n == 1) {
1568 uint32_t divisor = V[0];
1569 uint32_t remainder = 0;
1570 for (int i = m; i >= 0; i--) {
1571 uint64_t partial_dividend = Make_64(remainder, U[i]);
1572 if (partial_dividend == 0) {
1573 Q[i] = 0;
1574 remainder = 0;
1575 } else if (partial_dividend < divisor) {
1576 Q[i] = 0;
1577 remainder = Lo_32(partial_dividend);
1578 } else if (partial_dividend == divisor) {
1579 Q[i] = 1;
1580 remainder = 0;
1581 } else {
1582 Q[i] = Lo_32(partial_dividend / divisor);
1583 remainder = Lo_32(partial_dividend - (Q[i] * divisor));
1584 }
1585 }
1586 if (R)
1587 R[0] = remainder;
1588 } else {
1589 // Now we're ready to invoke the Knuth classical divide algorithm. In this
1590 // case n > 1.
1591 KnuthDiv(U, V, Q, R, m, n);
1592 }
1593
1594 // If the caller wants the quotient
1595 if (Quotient) {
1596 for (unsigned i = 0; i < lhsWords; ++i)
1597 Quotient[i] = Make_64(Q[i*2+1], Q[i*2]);
1598 }
1599
1600 // If the caller wants the remainder
1601 if (Remainder) {
1602 for (unsigned i = 0; i < rhsWords; ++i)
1603 Remainder[i] = Make_64(R[i*2+1], R[i*2]);
1604 }
1605
1606 // Clean up the memory we allocated.
1607 if (U != &SPACE[0]) {
1608 delete [] U;
1609 delete [] V;
1610 delete [] Q;
1611 delete [] R;
1612 }
1613}
1614
1615APInt APInt::udiv(const APInt &RHS) const {
1616 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1617
1618 // First, deal with the easy case
1619 if (isSingleWord()) {
1620 assert(RHS.U.VAL != 0 && "Divide by zero?");
1621 return APInt(BitWidth, U.VAL / RHS.U.VAL);
1622 }
1623
1624 // Get some facts about the LHS and RHS number of bits and words
1625 unsigned lhsWords = getNumWords(getActiveBits());
1626 unsigned rhsBits = RHS.getActiveBits();
1627 unsigned rhsWords = getNumWords(rhsBits);
1628 assert(rhsWords && "Divided by zero???");
1629
1630 // Deal with some degenerate cases
1631 if (!lhsWords)
1632 // 0 / X ===> 0
1633 return APInt(BitWidth, 0);
1634 if (rhsBits == 1)
1635 // X / 1 ===> X
1636 return *this;
1637 if (lhsWords < rhsWords || this->ult(RHS))
1638 // X / Y ===> 0, iff X < Y
1639 return APInt(BitWidth, 0);
1640 if (*this == RHS)
1641 // X / X ===> 1
1642 return APInt(BitWidth, 1);
1643 if (lhsWords == 1) // rhsWords is 1 if lhsWords is 1.
1644 // All high words are zero, just use native divide
1645 return APInt(BitWidth, this->U.pVal[0] / RHS.U.pVal[0]);
1646
1647 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1648 APInt Quotient(BitWidth, 0); // to hold result.
1649 divide(U.pVal, lhsWords, RHS.U.pVal, rhsWords, Quotient.U.pVal, nullptr);
1650 return Quotient;
1651}
1652
1654 assert(RHS != 0 && "Divide by zero?");
1655
1656 // First, deal with the easy case
1657 if (isSingleWord())
1658 return APInt(BitWidth, U.VAL / RHS);
1659
1660 // Get some facts about the LHS words.
1661 unsigned lhsWords = getNumWords(getActiveBits());
1662
1663 // Deal with some degenerate cases
1664 if (!lhsWords)
1665 // 0 / X ===> 0
1666 return APInt(BitWidth, 0);
1667 if (RHS == 1)
1668 // X / 1 ===> X
1669 return *this;
1670 if (this->ult(RHS))
1671 // X / Y ===> 0, iff X < Y
1672 return APInt(BitWidth, 0);
1673 if (*this == RHS)
1674 // X / X ===> 1
1675 return APInt(BitWidth, 1);
1676 if (lhsWords == 1) // rhsWords is 1 if lhsWords is 1.
1677 // All high words are zero, just use native divide
1678 return APInt(BitWidth, this->U.pVal[0] / RHS);
1679
1680 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1681 APInt Quotient(BitWidth, 0); // to hold result.
1682 divide(U.pVal, lhsWords, &RHS, 1, Quotient.U.pVal, nullptr);
1683 return Quotient;
1684}
1685
1686APInt APInt::sdiv(const APInt &RHS) const {
1687 if (isNegative()) {
1688 if (RHS.isNegative())
1689 return (-(*this)).udiv(-RHS);
1690 return -((-(*this)).udiv(RHS));
1691 }
1692 if (RHS.isNegative())
1693 return -(this->udiv(-RHS));
1694 return this->udiv(RHS);
1695}
1696
1697APInt APInt::sdiv(int64_t RHS) const {
1698 if (isNegative()) {
1699 if (RHS < 0)
1700 return (-(*this)).udiv(-RHS);
1701 return -((-(*this)).udiv(RHS));
1702 }
1703 if (RHS < 0)
1704 return -(this->udiv(-RHS));
1705 return this->udiv(RHS);
1706}
1708APInt APInt::urem(const APInt &RHS) const {
1709 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1710 if (isSingleWord()) {
1711 assert(RHS.U.VAL != 0 && "Remainder by zero?");
1712 return APInt(BitWidth, U.VAL % RHS.U.VAL);
1713 }
1714
1715 // Get some facts about the LHS
1716 unsigned lhsWords = getNumWords(getActiveBits());
1717
1718 // Get some facts about the RHS
1719 unsigned rhsBits = RHS.getActiveBits();
1720 unsigned rhsWords = getNumWords(rhsBits);
1721 assert(rhsWords && "Performing remainder operation by zero ???");
1722
1723 // Check the degenerate cases
1724 if (lhsWords == 0)
1725 // 0 % Y ===> 0
1726 return APInt(BitWidth, 0);
1727 if (rhsBits == 1)
1728 // X % 1 ===> 0
1729 return APInt(BitWidth, 0);
1730 if (lhsWords < rhsWords || this->ult(RHS))
1731 // X % Y ===> X, iff X < Y
1732 return *this;
1733 if (*this == RHS)
1734 // X % X == 0;
1735 return APInt(BitWidth, 0);
1736 if (lhsWords == 1)
1737 // All high words are zero, just use native remainder
1738 return APInt(BitWidth, U.pVal[0] % RHS.U.pVal[0]);
1739 if (RHS.isPowerOf2()) {
1740 // X % 2^w ===> X & (2^w - 1)
1741 APInt Result(*this);
1742 Result.clearBits(RHS.logBase2(), BitWidth);
1743 return Result;
1744 }
1745
1746 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1747 APInt Remainder(BitWidth, 0);
1748 divide(U.pVal, lhsWords, RHS.U.pVal, rhsWords, nullptr, Remainder.U.pVal);
1749 return Remainder;
1750}
1751
1753 assert(RHS != 0 && "Remainder by zero?");
1754
1755 if (isSingleWord())
1756 return U.VAL % RHS;
1757
1758 // Get some facts about the LHS
1759 unsigned lhsWords = getNumWords(getActiveBits());
1760
1761 // Check the degenerate cases
1762 if (lhsWords == 0)
1763 // 0 % Y ===> 0
1764 return 0;
1765 if (RHS == 1)
1766 // X % 1 ===> 0
1767 return 0;
1768 if (this->ult(RHS))
1769 // X % Y ===> X, iff X < Y
1770 return getZExtValue();
1771 if (*this == RHS)
1772 // X % X == 0;
1773 return 0;
1774 if (lhsWords == 1)
1775 // All high words are zero, just use native remainder
1776 return U.pVal[0] % RHS;
1777 if (llvm::isPowerOf2_64(RHS))
1778 // X % 2^w ===> X & (2^w - 1)
1779 return U.pVal[0] & (RHS - 1);
1780
1781 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1782 uint64_t Remainder;
1783 divide(U.pVal, lhsWords, &RHS, 1, nullptr, &Remainder);
1784 return Remainder;
1785}
1786
1787APInt APInt::srem(const APInt &RHS) const {
1788 if (isNegative()) {
1789 if (RHS.isNegative())
1790 return -((-(*this)).urem(-RHS));
1791 return -((-(*this)).urem(RHS));
1792 }
1793 if (RHS.isNegative())
1794 return this->urem(-RHS);
1795 return this->urem(RHS);
1796}
1797
1798int64_t APInt::srem(int64_t RHS) const {
1799 if (isNegative()) {
1800 if (RHS < 0)
1801 return -((-(*this)).urem(-RHS));
1802 return -((-(*this)).urem(RHS));
1803 }
1804 if (RHS < 0)
1805 return this->urem(-RHS);
1806 return this->urem(RHS);
1807}
1808
1809void APInt::udivrem(const APInt &LHS, const APInt &RHS,
1810 APInt &Quotient, APInt &Remainder) {
1811 assert(LHS.BitWidth == RHS.BitWidth && "Bit widths must be the same");
1812 unsigned BitWidth = LHS.BitWidth;
1813
1814 // First, deal with the easy case
1815 if (LHS.isSingleWord()) {
1816 assert(RHS.U.VAL != 0 && "Divide by zero?");
1817 uint64_t QuotVal = LHS.U.VAL / RHS.U.VAL;
1818 uint64_t RemVal = LHS.U.VAL % RHS.U.VAL;
1819 Quotient = APInt(BitWidth, QuotVal);
1820 Remainder = APInt(BitWidth, RemVal);
1821 return;
1822 }
1823
1824 // Get some size facts about the dividend and divisor
1825 unsigned lhsWords = getNumWords(LHS.getActiveBits());
1826 unsigned rhsBits = RHS.getActiveBits();
1827 unsigned rhsWords = getNumWords(rhsBits);
1828 assert(rhsWords && "Performing divrem operation by zero ???");
1829
1830 // Check the degenerate cases
1831 if (lhsWords == 0) {
1832 Quotient = APInt(BitWidth, 0); // 0 / Y ===> 0
1833 Remainder = APInt(BitWidth, 0); // 0 % Y ===> 0
1834 return;
1835 }
1836
1837 if (rhsBits == 1) {
1838 Quotient = LHS; // X / 1 ===> X
1839 Remainder = APInt(BitWidth, 0); // X % 1 ===> 0
1840 }
1841
1842 if (lhsWords < rhsWords || LHS.ult(RHS)) {
1843 Remainder = LHS; // X % Y ===> X, iff X < Y
1844 Quotient = APInt(BitWidth, 0); // X / Y ===> 0, iff X < Y
1845 return;
1846 }
1847
1848 if (LHS == RHS) {
1849 Quotient = APInt(BitWidth, 1); // X / X ===> 1
1850 Remainder = APInt(BitWidth, 0); // X % X ===> 0;
1851 return;
1852 }
1853
1854 // Make sure there is enough space to hold the results.
1855 // NOTE: This assumes that reallocate won't affect any bits if it doesn't
1856 // change the size. This is necessary if Quotient or Remainder is aliased
1857 // with LHS or RHS.
1858 Quotient.reallocate(BitWidth);
1859 Remainder.reallocate(BitWidth);
1860
1861 if (lhsWords == 1) { // rhsWords is 1 if lhsWords is 1.
1862 // There is only one word to consider so use the native versions.
1863 uint64_t lhsValue = LHS.U.pVal[0];
1864 uint64_t rhsValue = RHS.U.pVal[0];
1865 Quotient = lhsValue / rhsValue;
1866 Remainder = lhsValue % rhsValue;
1867 return;
1868 }
1869
1870 // Okay, lets do it the long way
1871 divide(LHS.U.pVal, lhsWords, RHS.U.pVal, rhsWords, Quotient.U.pVal,
1872 Remainder.U.pVal);
1873 // Clear the rest of the Quotient and Remainder.
1874 std::memset(Quotient.U.pVal + lhsWords, 0,
1875 (getNumWords(BitWidth) - lhsWords) * APINT_WORD_SIZE);
1876 std::memset(Remainder.U.pVal + rhsWords, 0,
1877 (getNumWords(BitWidth) - rhsWords) * APINT_WORD_SIZE);
1878}
1879
1880void APInt::udivrem(const APInt &LHS, uint64_t RHS, APInt &Quotient,
1881 uint64_t &Remainder) {
1882 assert(RHS != 0 && "Divide by zero?");
1883 unsigned BitWidth = LHS.BitWidth;
1884
1885 // First, deal with the easy case
1886 if (LHS.isSingleWord()) {
1887 uint64_t QuotVal = LHS.U.VAL / RHS;
1888 Remainder = LHS.U.VAL % RHS;
1889 Quotient = APInt(BitWidth, QuotVal);
1890 return;
1891 }
1892
1893 // Get some size facts about the dividend and divisor
1894 unsigned lhsWords = getNumWords(LHS.getActiveBits());
1895
1896 // Check the degenerate cases
1897 if (lhsWords == 0) {
1898 Quotient = APInt(BitWidth, 0); // 0 / Y ===> 0
1899 Remainder = 0; // 0 % Y ===> 0
1900 return;
1901 }
1902
1903 if (RHS == 1) {
1904 Quotient = LHS; // X / 1 ===> X
1905 Remainder = 0; // X % 1 ===> 0
1906 return;
1907 }
1908
1909 if (LHS.ult(RHS)) {
1910 Remainder = LHS.getZExtValue(); // X % Y ===> X, iff X < Y
1911 Quotient = APInt(BitWidth, 0); // X / Y ===> 0, iff X < Y
1912 return;
1913 }
1914
1915 if (LHS == RHS) {
1916 Quotient = APInt(BitWidth, 1); // X / X ===> 1
1917 Remainder = 0; // X % X ===> 0;
1918 return;
1919 }
1920
1921 // Make sure there is enough space to hold the results.
1922 // NOTE: This assumes that reallocate won't affect any bits if it doesn't
1923 // change the size. This is necessary if Quotient is aliased with LHS.
1924 Quotient.reallocate(BitWidth);
1925
1926 if (lhsWords == 1) { // rhsWords is 1 if lhsWords is 1.
1927 // There is only one word to consider so use the native versions.
1928 uint64_t lhsValue = LHS.U.pVal[0];
1929 Quotient = lhsValue / RHS;
1930 Remainder = lhsValue % RHS;
1931 return;
1932 }
1933
1934 // Okay, lets do it the long way
1935 divide(LHS.U.pVal, lhsWords, &RHS, 1, Quotient.U.pVal, &Remainder);
1936 // Clear the rest of the Quotient.
1937 std::memset(Quotient.U.pVal + lhsWords, 0,
1938 (getNumWords(BitWidth) - lhsWords) * APINT_WORD_SIZE);
1939}
1940
1941void APInt::sdivrem(const APInt &LHS, const APInt &RHS,
1942 APInt &Quotient, APInt &Remainder) {
1943 if (LHS.isNegative()) {
1944 if (RHS.isNegative())
1945 APInt::udivrem(-LHS, -RHS, Quotient, Remainder);
1946 else {
1947 APInt::udivrem(-LHS, RHS, Quotient, Remainder);
1948 Quotient.negate();
1949 }
1950 Remainder.negate();
1951 } else if (RHS.isNegative()) {
1952 APInt::udivrem(LHS, -RHS, Quotient, Remainder);
1953 Quotient.negate();
1954 } else {
1955 APInt::udivrem(LHS, RHS, Quotient, Remainder);
1956 }
1957}
1958
1959void APInt::sdivrem(const APInt &LHS, int64_t RHS,
1960 APInt &Quotient, int64_t &Remainder) {
1961 uint64_t R = Remainder;
1962 if (LHS.isNegative()) {
1963 if (RHS < 0)
1964 APInt::udivrem(-LHS, -RHS, Quotient, R);
1965 else {
1966 APInt::udivrem(-LHS, RHS, Quotient, R);
1967 Quotient.negate();
1968 }
1969 R = -R;
1970 } else if (RHS < 0) {
1971 APInt::udivrem(LHS, -RHS, Quotient, R);
1972 Quotient.negate();
1973 } else {
1974 APInt::udivrem(LHS, RHS, Quotient, R);
1975 }
1976 Remainder = R;
1977}
1978
1979APInt APInt::sadd_ov(const APInt &RHS, bool &Overflow) const {
1980 APInt Res = *this+RHS;
1981 Overflow = isNonNegative() == RHS.isNonNegative() &&
1982 Res.isNonNegative() != isNonNegative();
1983 return Res;
1984}
1985
1986APInt APInt::uadd_ov(const APInt &RHS, bool &Overflow) const {
1987 APInt Res = *this+RHS;
1988 Overflow = Res.ult(RHS);
1989 return Res;
1990}
1991
1992APInt APInt::ssub_ov(const APInt &RHS, bool &Overflow) const {
1993 APInt Res = *this - RHS;
1994 Overflow = isNonNegative() != RHS.isNonNegative() &&
1995 Res.isNonNegative() != isNonNegative();
1996 return Res;
1997}
1998
1999APInt APInt::usub_ov(const APInt &RHS, bool &Overflow) const {
2000 APInt Res = *this-RHS;
2001 Overflow = Res.ugt(*this);
2002 return Res;
2003}
2004
2005APInt APInt::sdiv_ov(const APInt &RHS, bool &Overflow) const {
2006 // MININT/-1 --> overflow.
2007 Overflow = isMinSignedValue() && RHS.isAllOnes();
2008 return sdiv(RHS);
2009}
2010
2011APInt APInt::smul_ov(const APInt &RHS, bool &Overflow) const {
2012 APInt Res = *this * RHS;
2013
2014 if (RHS != 0)
2015 Overflow = Res.sdiv(RHS) != *this ||
2016 (isMinSignedValue() && RHS.isAllOnes());
2017 else
2018 Overflow = false;
2019 return Res;
2020}
2021
2022APInt APInt::umul_ov(const APInt &RHS, bool &Overflow) const {
2023 if (countl_zero() + RHS.countl_zero() + 2 <= BitWidth) {
2024 Overflow = true;
2025 return *this * RHS;
2026 }
2027
2028 APInt Res = lshr(1) * RHS;
2029 Overflow = Res.isNegative();
2030 Res <<= 1;
2031 if ((*this)[0]) {
2032 Res += RHS;
2033 if (Res.ult(RHS))
2034 Overflow = true;
2035 }
2036 return Res;
2037}
2038
2039APInt APInt::sshl_ov(const APInt &ShAmt, bool &Overflow) const {
2040 return sshl_ov(ShAmt.getLimitedValue(getBitWidth()), Overflow);
2041}
2042
2043APInt APInt::sshl_ov(unsigned ShAmt, bool &Overflow) const {
2044 Overflow = ShAmt >= getBitWidth();
2045 if (Overflow)
2046 return APInt(BitWidth, 0);
2047
2048 if (isNonNegative()) // Don't allow sign change.
2049 Overflow = ShAmt >= countl_zero();
2050 else
2051 Overflow = ShAmt >= countl_one();
2052
2053 return *this << ShAmt;
2054}
2055
2056APInt APInt::ushl_ov(const APInt &ShAmt, bool &Overflow) const {
2057 return ushl_ov(ShAmt.getLimitedValue(getBitWidth()), Overflow);
2058}
2059
2060APInt APInt::ushl_ov(unsigned ShAmt, bool &Overflow) const {
2061 Overflow = ShAmt >= getBitWidth();
2062 if (Overflow)
2063 return APInt(BitWidth, 0);
2064
2065 Overflow = ShAmt > countl_zero();
2066
2067 return *this << ShAmt;
2068}
2069
2070APInt APInt::sfloordiv_ov(const APInt &RHS, bool &Overflow) const {
2071 APInt quotient = sdiv_ov(RHS, Overflow);
2072 if ((quotient * RHS != *this) && (isNegative() != RHS.isNegative()))
2073 return quotient - 1;
2074 return quotient;
2075}
2076
2077APInt APInt::sadd_sat(const APInt &RHS) const {
2078 bool Overflow;
2079 APInt Res = sadd_ov(RHS, Overflow);
2080 if (!Overflow)
2081 return Res;
2082
2083 return isNegative() ? APInt::getSignedMinValue(BitWidth)
2084 : APInt::getSignedMaxValue(BitWidth);
2085}
2086
2087APInt APInt::uadd_sat(const APInt &RHS) const {
2088 bool Overflow;
2089 APInt Res = uadd_ov(RHS, Overflow);
2090 if (!Overflow)
2091 return Res;
2092
2093 return APInt::getMaxValue(BitWidth);
2094}
2095
2096APInt APInt::ssub_sat(const APInt &RHS) const {
2097 bool Overflow;
2098 APInt Res = ssub_ov(RHS, Overflow);
2099 if (!Overflow)
2100 return Res;
2101
2102 return isNegative() ? APInt::getSignedMinValue(BitWidth)
2103 : APInt::getSignedMaxValue(BitWidth);
2104}
2105
2106APInt APInt::usub_sat(const APInt &RHS) const {
2107 bool Overflow;
2108 APInt Res = usub_ov(RHS, Overflow);
2109 if (!Overflow)
2110 return Res;
2111
2112 return APInt(BitWidth, 0);
2113}
2114
2115APInt APInt::smul_sat(const APInt &RHS) const {
2116 bool Overflow;
2117 APInt Res = smul_ov(RHS, Overflow);
2118 if (!Overflow)
2119 return Res;
2120
2121 // The result is negative if one and only one of inputs is negative.
2122 bool ResIsNegative = isNegative() ^ RHS.isNegative();
2123
2124 return ResIsNegative ? APInt::getSignedMinValue(BitWidth)
2125 : APInt::getSignedMaxValue(BitWidth);
2126}
2127
2128APInt APInt::umul_sat(const APInt &RHS) const {
2129 bool Overflow;
2130 APInt Res = umul_ov(RHS, Overflow);
2131 if (!Overflow)
2132 return Res;
2133
2134 return APInt::getMaxValue(BitWidth);
2135}
2136
2137APInt APInt::sshl_sat(const APInt &RHS) const {
2138 return sshl_sat(RHS.getLimitedValue(getBitWidth()));
2139}
2140
2141APInt APInt::sshl_sat(unsigned RHS) const {
2142 bool Overflow;
2143 APInt Res = sshl_ov(RHS, Overflow);
2144 if (!Overflow)
2145 return Res;
2146
2147 return isNegative() ? APInt::getSignedMinValue(BitWidth)
2148 : APInt::getSignedMaxValue(BitWidth);
2149}
2150
2151APInt APInt::ushl_sat(const APInt &RHS) const {
2152 return ushl_sat(RHS.getLimitedValue(getBitWidth()));
2153}
2154
2155APInt APInt::ushl_sat(unsigned RHS) const {
2156 bool Overflow;
2157 APInt Res = ushl_ov(RHS, Overflow);
2158 if (!Overflow)
2159 return Res;
2160
2161 return APInt::getMaxValue(BitWidth);
2162}
2163
2164void APInt::fromString(unsigned numbits, StringRef str, uint8_t radix) {
2165 // Check our assumptions here
2166 assert(!str.empty() && "Invalid string length");
2167 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 ||
2168 radix == 36) &&
2169 "Radix should be 2, 8, 10, 16, or 36!");
2170
2171 StringRef::iterator p = str.begin();
2172 size_t slen = str.size();
2173 bool isNeg = *p == '-';
2174 if (*p == '-' || *p == '+') {
2175 p++;
2176 slen--;
2177 assert(slen && "String is only a sign, needs a value.");
2178 }
2179 assert((slen <= numbits || radix != 2) && "Insufficient bit width");
2180 assert(((slen-1)*3 <= numbits || radix != 8) && "Insufficient bit width");
2181 assert(((slen-1)*4 <= numbits || radix != 16) && "Insufficient bit width");
2182 assert((((slen-1)*64)/22 <= numbits || radix != 10) &&
2183 "Insufficient bit width");
2184
2185 // Allocate memory if needed
2186 if (isSingleWord())
2187 U.VAL = 0;
2188 else
2189 U.pVal = getClearedMemory(getNumWords());
2190
2191 // Figure out if we can shift instead of multiply
2192 unsigned shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0);
2193
2194 // Enter digit traversal loop
2195 for (StringRef::iterator e = str.end(); p != e; ++p) {
2196 unsigned digit = getDigit(*p, radix);
2197 assert(digit < radix && "Invalid character in digit string");
2198
2199 // Shift or multiply the value by the radix
2200 if (slen > 1) {
2201 if (shift)
2202 *this <<= shift;
2203 else
2204 *this *= radix;
2205 }
2206
2207 // Add in the digit we just interpreted
2208 *this += digit;
2209 }
2210 // If its negative, put it in two's complement form
2211 if (isNeg)
2212 this->negate();
2213}
2214
2215void APInt::toString(SmallVectorImpl<char> &Str, unsigned Radix, bool Signed,
2216 bool formatAsCLiteral, bool UpperCase,
2217 bool InsertSeparators) const {
2218 assert((Radix == 10 || Radix == 8 || Radix == 16 || Radix == 2 ||
2219 Radix == 36) &&
2220 "Radix should be 2, 8, 10, 16, or 36!");
2221
2222 const char *Prefix = "";
2223 if (formatAsCLiteral) {
2224 switch (Radix) {
2225 case 2:
2226 // Binary literals are a non-standard extension added in gcc 4.3:
2227 // http://gcc.gnu.org/onlinedocs/gcc-4.3.0/gcc/Binary-constants.html
2228 Prefix = "0b";
2229 break;
2230 case 8:
2231 Prefix = "0";
2232 break;
2233 case 10:
2234 break; // No prefix
2235 case 16:
2236 Prefix = "0x";
2237 break;
2238 default:
2239 llvm_unreachable("Invalid radix!");
2240 }
2241 }
2242
2243 // Number of digits in a group between separators.
2244 unsigned Grouping = (Radix == 8 || Radix == 10) ? 3 : 4;
2245
2246 // First, check for a zero value and just short circuit the logic below.
2247 if (isZero()) {
2248 while (*Prefix) {
2249 Str.push_back(*Prefix);
2250 ++Prefix;
2251 };
2252 Str.push_back('0');
2253 return;
2254 }
2255
2256 static const char BothDigits[] = "0123456789abcdefghijklmnopqrstuvwxyz"
2257 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
2258 const char *Digits = BothDigits + (UpperCase ? 36 : 0);
2259
2260 if (isSingleWord()) {
2261 char Buffer[65];
2262 char *BufPtr = std::end(Buffer);
2263
2264 uint64_t N;
2265 if (!Signed) {
2266 N = getZExtValue();
2267 } else {
2268 int64_t I = getSExtValue();
2269 if (I >= 0) {
2270 N = I;
2271 } else {
2272 Str.push_back('-');
2273 N = -(uint64_t)I;
2274 }
2275 }
2276
2277 while (*Prefix) {
2278 Str.push_back(*Prefix);
2279 ++Prefix;
2280 };
2281
2282 int Pos = 0;
2283 while (N) {
2284 if (InsertSeparators && Pos % Grouping == 0 && Pos > 0)
2285 *--BufPtr = '\'';
2286 *--BufPtr = Digits[N % Radix];
2287 N /= Radix;
2288 Pos++;
2289 }
2290 Str.append(BufPtr, std::end(Buffer));
2291 return;
2292 }
2293
2294 APInt Tmp(*this);
2295
2296 if (Signed && isNegative()) {
2297 // They want to print the signed version and it is a negative value
2298 // Flip the bits and add one to turn it into the equivalent positive
2299 // value and put a '-' in the result.
2300 Tmp.negate();
2301 Str.push_back('-');
2302 }
2303
2304 while (*Prefix) {
2305 Str.push_back(*Prefix);
2306 ++Prefix;
2307 }
2308
2309 // We insert the digits backward, then reverse them to get the right order.
2310 unsigned StartDig = Str.size();
2311
2312 // For the 2, 8 and 16 bit cases, we can just shift instead of divide
2313 // because the number of bits per digit (1, 3 and 4 respectively) divides
2314 // equally. We just shift until the value is zero.
2315 if (Radix == 2 || Radix == 8 || Radix == 16) {
2316 // Just shift tmp right for each digit width until it becomes zero
2317 unsigned ShiftAmt = (Radix == 16 ? 4 : (Radix == 8 ? 3 : 1));
2318 unsigned MaskAmt = Radix - 1;
2319
2320 int Pos = 0;
2321 while (Tmp.getBoolValue()) {
2322 unsigned Digit = unsigned(Tmp.getRawData()[0]) & MaskAmt;
2323 if (InsertSeparators && Pos % Grouping == 0 && Pos > 0)
2324 Str.push_back('\'');
2325
2326 Str.push_back(Digits[Digit]);
2327 Tmp.lshrInPlace(ShiftAmt);
2328 Pos++;
2329 }
2330 } else {
2331 int Pos = 0;
2332 while (Tmp.getBoolValue()) {
2333 uint64_t Digit;
2334 udivrem(Tmp, Radix, Tmp, Digit);
2335 assert(Digit < Radix && "divide failed");
2336 if (InsertSeparators && Pos % Grouping == 0 && Pos > 0)
2337 Str.push_back('\'');
2338
2339 Str.push_back(Digits[Digit]);
2340 Pos++;
2341 }
2342 }
2343
2344 // Reverse the digits before returning.
2345 std::reverse(Str.begin()+StartDig, Str.end());
2346}
2347
2348#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2350 SmallString<40> S, U;
2351 this->toStringUnsigned(U);
2352 this->toStringSigned(S);
2353 dbgs() << "APInt(" << BitWidth << "b, "
2354 << U << "u " << S << "s)\n";
2355}
2356#endif
2357
2358void APInt::print(raw_ostream &OS, bool isSigned) const {
2360 this->toString(S, 10, isSigned, /* formatAsCLiteral = */false);
2361 OS << S;
2362}
2363
2364// This implements a variety of operations on a representation of
2365// arbitrary precision, two's-complement, bignum integer values.
2366
2367// Assumed by lowHalf, highHalf, partMSB and partLSB. A fairly safe
2368// and unrestricting assumption.
2369static_assert(APInt::APINT_BITS_PER_WORD % 2 == 0,
2370 "Part width must be divisible by 2!");
2371
2372// Returns the integer part with the least significant BITS set.
2373// BITS cannot be zero.
2374static inline APInt::WordType lowBitMask(unsigned bits) {
2375 assert(bits != 0 && bits <= APInt::APINT_BITS_PER_WORD);
2376 return ~(APInt::WordType) 0 >> (APInt::APINT_BITS_PER_WORD - bits);
2377}
2378
2379/// Returns the value of the lower half of PART.
2381 return part & lowBitMask(APInt::APINT_BITS_PER_WORD / 2);
2382}
2383
2384/// Returns the value of the upper half of PART.
2386 return part >> (APInt::APINT_BITS_PER_WORD / 2);
2387}
2388
2389/// Sets the least significant part of a bignum to the input value, and zeroes
2390/// out higher parts.
2391void APInt::tcSet(WordType *dst, WordType part, unsigned parts) {
2392 assert(parts > 0);
2393 dst[0] = part;
2394 for (unsigned i = 1; i < parts; i++)
2395 dst[i] = 0;
2396}
2397
2398/// Assign one bignum to another.
2399void APInt::tcAssign(WordType *dst, const WordType *src, unsigned parts) {
2400 for (unsigned i = 0; i < parts; i++)
2401 dst[i] = src[i];
2402}
2403
2404/// Returns true if a bignum is zero, false otherwise.
2405bool APInt::tcIsZero(const WordType *src, unsigned parts) {
2406 for (unsigned i = 0; i < parts; i++)
2407 if (src[i])
2408 return false;
2409
2410 return true;
2411}
2412
2413/// Extract the given bit of a bignum; returns 0 or 1.
2414int APInt::tcExtractBit(const WordType *parts, unsigned bit) {
2415 return (parts[whichWord(bit)] & maskBit(bit)) != 0;
2416}
2417
2418/// Set the given bit of a bignum.
2419void APInt::tcSetBit(WordType *parts, unsigned bit) {
2420 parts[whichWord(bit)] |= maskBit(bit);
2421}
2422
2423/// Clears the given bit of a bignum.
2424void APInt::tcClearBit(WordType *parts, unsigned bit) {
2425 parts[whichWord(bit)] &= ~maskBit(bit);
2426}
2427
2428/// Returns the bit number of the least significant set bit of a number. If the
2429/// input number has no bits set UINT_MAX is returned.
2430unsigned APInt::tcLSB(const WordType *parts, unsigned n) {
2431 for (unsigned i = 0; i < n; i++) {
2432 if (parts[i] != 0) {
2433 unsigned lsb = llvm::countr_zero(parts[i]);
2434 return lsb + i * APINT_BITS_PER_WORD;
2435 }
2436 }
2437
2438 return UINT_MAX;
2439}
2440
2441/// Returns the bit number of the most significant set bit of a number.
2442/// If the input number has no bits set UINT_MAX is returned.
2443unsigned APInt::tcMSB(const WordType *parts, unsigned n) {
2444 do {
2445 --n;
2446
2447 if (parts[n] != 0) {
2448 static_assert(sizeof(parts[n]) <= sizeof(uint64_t));
2449 unsigned msb = llvm::Log2_64(parts[n]);
2450
2451 return msb + n * APINT_BITS_PER_WORD;
2452 }
2453 } while (n);
2454
2455 return UINT_MAX;
2456}
2457
2458/// Copy the bit vector of width srcBITS from SRC, starting at bit srcLSB, to
2459/// DST, of dstCOUNT parts, such that the bit srcLSB becomes the least
2460/// significant bit of DST. All high bits above srcBITS in DST are zero-filled.
2461/// */
2462void
2463APInt::tcExtract(WordType *dst, unsigned dstCount, const WordType *src,
2464 unsigned srcBits, unsigned srcLSB) {
2465 unsigned dstParts = (srcBits + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
2466 assert(dstParts <= dstCount);
2467
2468 unsigned firstSrcPart = srcLSB / APINT_BITS_PER_WORD;
2469 tcAssign(dst, src + firstSrcPart, dstParts);
2470
2471 unsigned shift = srcLSB % APINT_BITS_PER_WORD;
2472 tcShiftRight(dst, dstParts, shift);
2473
2474 // We now have (dstParts * APINT_BITS_PER_WORD - shift) bits from SRC
2475 // in DST. If this is less that srcBits, append the rest, else
2476 // clear the high bits.
2477 unsigned n = dstParts * APINT_BITS_PER_WORD - shift;
2478 if (n < srcBits) {
2479 WordType mask = lowBitMask (srcBits - n);
2480 dst[dstParts - 1] |= ((src[firstSrcPart + dstParts] & mask)
2481 << n % APINT_BITS_PER_WORD);
2482 } else if (n > srcBits) {
2483 if (srcBits % APINT_BITS_PER_WORD)
2484 dst[dstParts - 1] &= lowBitMask (srcBits % APINT_BITS_PER_WORD);
2485 }
2486
2487 // Clear high parts.
2488 while (dstParts < dstCount)
2489 dst[dstParts++] = 0;
2490}
2491
2492//// DST += RHS + C where C is zero or one. Returns the carry flag.
2494 WordType c, unsigned parts) {
2495 assert(c <= 1);
2496
2497 for (unsigned i = 0; i < parts; i++) {
2498 WordType l = dst[i];
2499 if (c) {
2500 dst[i] += rhs[i] + 1;
2501 c = (dst[i] <= l);
2502 } else {
2503 dst[i] += rhs[i];
2504 c = (dst[i] < l);
2505 }
2506 }
2507
2508 return c;
2509}
2510
2511/// This function adds a single "word" integer, src, to the multiple
2512/// "word" integer array, dst[]. dst[] is modified to reflect the addition and
2513/// 1 is returned if there is a carry out, otherwise 0 is returned.
2514/// @returns the carry of the addition.
2516 unsigned parts) {
2517 for (unsigned i = 0; i < parts; ++i) {
2518 dst[i] += src;
2519 if (dst[i] >= src)
2520 return 0; // No need to carry so exit early.
2521 src = 1; // Carry one to next digit.
2522 }
2523
2524 return 1;
2525}
2526
2527/// DST -= RHS + C where C is zero or one. Returns the carry flag.
2529 WordType c, unsigned parts) {
2530 assert(c <= 1);
2531
2532 for (unsigned i = 0; i < parts; i++) {
2533 WordType l = dst[i];
2534 if (c) {
2535 dst[i] -= rhs[i] + 1;
2536 c = (dst[i] >= l);
2537 } else {
2538 dst[i] -= rhs[i];
2539 c = (dst[i] > l);
2540 }
2541 }
2542
2543 return c;
2544}
2545
2546/// This function subtracts a single "word" (64-bit word), src, from
2547/// the multi-word integer array, dst[], propagating the borrowed 1 value until
2548/// no further borrowing is needed or it runs out of "words" in dst. The result
2549/// is 1 if "borrowing" exhausted the digits in dst, or 0 if dst was not
2550/// exhausted. In other words, if src > dst then this function returns 1,
2551/// otherwise 0.
2552/// @returns the borrow out of the subtraction
2554 unsigned parts) {
2555 for (unsigned i = 0; i < parts; ++i) {
2556 WordType Dst = dst[i];
2557 dst[i] -= src;
2558 if (src <= Dst)
2559 return 0; // No need to borrow so exit early.
2560 src = 1; // We have to "borrow 1" from next "word"
2561 }
2562
2563 return 1;
2564}
2565
2566/// Negate a bignum in-place.
2567void APInt::tcNegate(WordType *dst, unsigned parts) {
2568 tcComplement(dst, parts);
2569 tcIncrement(dst, parts);
2570}
2571
2572/// DST += SRC * MULTIPLIER + CARRY if add is true
2573/// DST = SRC * MULTIPLIER + CARRY if add is false
2574/// Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC
2575/// they must start at the same point, i.e. DST == SRC.
2576/// If DSTPARTS == SRCPARTS + 1 no overflow occurs and zero is
2577/// returned. Otherwise DST is filled with the least significant
2578/// DSTPARTS parts of the result, and if all of the omitted higher
2579/// parts were zero return zero, otherwise overflow occurred and
2580/// return one.
2582 WordType multiplier, WordType carry,
2583 unsigned srcParts, unsigned dstParts,
2584 bool add) {
2585 // Otherwise our writes of DST kill our later reads of SRC.
2586 assert(dst <= src || dst >= src + srcParts);
2587 assert(dstParts <= srcParts + 1);
2588
2589 // N loops; minimum of dstParts and srcParts.
2590 unsigned n = std::min(dstParts, srcParts);
2591
2592 for (unsigned i = 0; i < n; i++) {
2593 // [LOW, HIGH] = MULTIPLIER * SRC[i] + DST[i] + CARRY.
2594 // This cannot overflow, because:
2595 // (n - 1) * (n - 1) + 2 (n - 1) = (n - 1) * (n + 1)
2596 // which is less than n^2.
2597 WordType srcPart = src[i];
2598 WordType low, mid, high;
2599 if (multiplier == 0 || srcPart == 0) {
2600 low = carry;
2601 high = 0;
2602 } else {
2603 low = lowHalf(srcPart) * lowHalf(multiplier);
2604 high = highHalf(srcPart) * highHalf(multiplier);
2605
2606 mid = lowHalf(srcPart) * highHalf(multiplier);
2607 high += highHalf(mid);
2608 mid <<= APINT_BITS_PER_WORD / 2;
2609 if (low + mid < low)
2610 high++;
2611 low += mid;
2612
2613 mid = highHalf(srcPart) * lowHalf(multiplier);
2614 high += highHalf(mid);
2615 mid <<= APINT_BITS_PER_WORD / 2;
2616 if (low + mid < low)
2617 high++;
2618 low += mid;
2619
2620 // Now add carry.
2621 if (low + carry < low)
2622 high++;
2623 low += carry;
2624 }
2625
2626 if (add) {
2627 // And now DST[i], and store the new low part there.
2628 if (low + dst[i] < low)
2629 high++;
2630 dst[i] += low;
2631 } else {
2632 dst[i] = low;
2633 }
2634
2635 carry = high;
2636 }
2637
2638 if (srcParts < dstParts) {
2639 // Full multiplication, there is no overflow.
2640 assert(srcParts + 1 == dstParts);
2641 dst[srcParts] = carry;
2642 return 0;
2643 }
2644
2645 // We overflowed if there is carry.
2646 if (carry)
2647 return 1;
2648
2649 // We would overflow if any significant unwritten parts would be
2650 // non-zero. This is true if any remaining src parts are non-zero
2651 // and the multiplier is non-zero.
2652 if (multiplier)
2653 for (unsigned i = dstParts; i < srcParts; i++)
2654 if (src[i])
2655 return 1;
2656
2657 // We fitted in the narrow destination.
2658 return 0;
2659}
2660
2661/// DST = LHS * RHS, where DST has the same width as the operands and
2662/// is filled with the least significant parts of the result. Returns
2663/// one if overflow occurred, otherwise zero. DST must be disjoint
2664/// from both operands.
2666 const WordType *rhs, unsigned parts) {
2667 assert(dst != lhs && dst != rhs);
2668
2669 int overflow = 0;
2670
2671 for (unsigned i = 0; i < parts; i++) {
2672 // Don't accumulate on the first iteration so we don't need to initalize
2673 // dst to 0.
2674 overflow |=
2675 tcMultiplyPart(&dst[i], lhs, rhs[i], 0, parts, parts - i, i != 0);
2676 }
2677
2678 return overflow;
2679}
2680
2681/// DST = LHS * RHS, where DST has width the sum of the widths of the
2682/// operands. No overflow occurs. DST must be disjoint from both operands.
2684 const WordType *rhs, unsigned lhsParts,
2685 unsigned rhsParts) {
2686 // Put the narrower number on the LHS for less loops below.
2687 if (lhsParts > rhsParts)
2688 return tcFullMultiply (dst, rhs, lhs, rhsParts, lhsParts);
2689
2690 assert(dst != lhs && dst != rhs);
2691
2692 for (unsigned i = 0; i < lhsParts; i++) {
2693 // Don't accumulate on the first iteration so we don't need to initalize
2694 // dst to 0.
2695 tcMultiplyPart(&dst[i], rhs, lhs[i], 0, rhsParts, rhsParts + 1, i != 0);
2696 }
2697}
2698
2699// If RHS is zero LHS and REMAINDER are left unchanged, return one.
2700// Otherwise set LHS to LHS / RHS with the fractional part discarded,
2701// set REMAINDER to the remainder, return zero. i.e.
2702//
2703// OLD_LHS = RHS * LHS + REMAINDER
2704//
2705// SCRATCH is a bignum of the same size as the operands and result for
2706// use by the routine; its contents need not be initialized and are
2707// destroyed. LHS, REMAINDER and SCRATCH must be distinct.
2708int APInt::tcDivide(WordType *lhs, const WordType *rhs,
2709 WordType *remainder, WordType *srhs,
2710 unsigned parts) {
2711 assert(lhs != remainder && lhs != srhs && remainder != srhs);
2712
2713 unsigned shiftCount = tcMSB(rhs, parts) + 1;
2714 if (shiftCount == 0)
2715 return true;
2716
2717 shiftCount = parts * APINT_BITS_PER_WORD - shiftCount;
2718 unsigned n = shiftCount / APINT_BITS_PER_WORD;
2719 WordType mask = (WordType) 1 << (shiftCount % APINT_BITS_PER_WORD);
2720
2721 tcAssign(srhs, rhs, parts);
2722 tcShiftLeft(srhs, parts, shiftCount);
2723 tcAssign(remainder, lhs, parts);
2724 tcSet(lhs, 0, parts);
2725
2726 // Loop, subtracting SRHS if REMAINDER is greater and adding that to the
2727 // total.
2728 for (;;) {
2729 int compare = tcCompare(remainder, srhs, parts);
2730 if (compare >= 0) {
2731 tcSubtract(remainder, srhs, 0, parts);
2732 lhs[n] |= mask;
2733 }
2734
2735 if (shiftCount == 0)
2736 break;
2737 shiftCount--;
2738 tcShiftRight(srhs, parts, 1);
2739 if ((mask >>= 1) == 0) {
2740 mask = (WordType) 1 << (APINT_BITS_PER_WORD - 1);
2741 n--;
2742 }
2743 }
2744
2745 return false;
2746}
2747
2748/// Shift a bignum left Count bits in-place. Shifted in bits are zero. There are
2749/// no restrictions on Count.
2750void APInt::tcShiftLeft(WordType *Dst, unsigned Words, unsigned Count) {
2751 // Don't bother performing a no-op shift.
2752 if (!Count)
2753 return;
2754
2755 // WordShift is the inter-part shift; BitShift is the intra-part shift.
2756 unsigned WordShift = std::min(Count / APINT_BITS_PER_WORD, Words);
2757 unsigned BitShift = Count % APINT_BITS_PER_WORD;
2758
2759 // Fastpath for moving by whole words.
2760 if (BitShift == 0) {
2761 std::memmove(Dst + WordShift, Dst, (Words - WordShift) * APINT_WORD_SIZE);
2762 } else {
2763 while (Words-- > WordShift) {
2764 Dst[Words] = Dst[Words - WordShift] << BitShift;
2765 if (Words > WordShift)
2766 Dst[Words] |=
2767 Dst[Words - WordShift - 1] >> (APINT_BITS_PER_WORD - BitShift);
2768 }
2769 }
2770
2771 // Fill in the remainder with 0s.
2772 std::memset(Dst, 0, WordShift * APINT_WORD_SIZE);
2773}
2774
2775/// Shift a bignum right Count bits in-place. Shifted in bits are zero. There
2776/// are no restrictions on Count.
2777void APInt::tcShiftRight(WordType *Dst, unsigned Words, unsigned Count) {
2778 // Don't bother performing a no-op shift.
2779 if (!Count)
2780 return;
2781
2782 // WordShift is the inter-part shift; BitShift is the intra-part shift.
2783 unsigned WordShift = std::min(Count / APINT_BITS_PER_WORD, Words);
2784 unsigned BitShift = Count % APINT_BITS_PER_WORD;
2785
2786 unsigned WordsToMove = Words - WordShift;
2787 // Fastpath for moving by whole words.
2788 if (BitShift == 0) {
2789 std::memmove(Dst, Dst + WordShift, WordsToMove * APINT_WORD_SIZE);
2790 } else {
2791 for (unsigned i = 0; i != WordsToMove; ++i) {
2792 Dst[i] = Dst[i + WordShift] >> BitShift;
2793 if (i + 1 != WordsToMove)
2794 Dst[i] |= Dst[i + WordShift + 1] << (APINT_BITS_PER_WORD - BitShift);
2795 }
2796 }
2797
2798 // Fill in the remainder with 0s.
2799 std::memset(Dst + WordsToMove, 0, WordShift * APINT_WORD_SIZE);
2800}
2801
2802// Comparison (unsigned) of two bignums.
2803int APInt::tcCompare(const WordType *lhs, const WordType *rhs,
2804 unsigned parts) {
2805 while (parts) {
2806 parts--;
2807 if (lhs[parts] != rhs[parts])
2808 return (lhs[parts] > rhs[parts]) ? 1 : -1;
2809 }
2810
2811 return 0;
2812}
2813
2815 APInt::Rounding RM) {
2816 // Currently udivrem always rounds down.
2817 switch (RM) {
2820 return A.udiv(B);
2821 case APInt::Rounding::UP: {
2822 APInt Quo, Rem;
2823 APInt::udivrem(A, B, Quo, Rem);
2824 if (Rem.isZero())
2825 return Quo;
2826 return Quo + 1;
2827 }
2828 }
2829 llvm_unreachable("Unknown APInt::Rounding enum");
2830}
2831
2833 APInt::Rounding RM) {
2834 switch (RM) {
2836 case APInt::Rounding::UP: {
2837 APInt Quo, Rem;
2838 APInt::sdivrem(A, B, Quo, Rem);
2839 if (Rem.isZero())
2840 return Quo;
2841 // This algorithm deals with arbitrary rounding mode used by sdivrem.
2842 // We want to check whether the non-integer part of the mathematical value
2843 // is negative or not. If the non-integer part is negative, we need to round
2844 // down from Quo; otherwise, if it's positive or 0, we return Quo, as it's
2845 // already rounded down.
2846 if (RM == APInt::Rounding::DOWN) {
2847 if (Rem.isNegative() != B.isNegative())
2848 return Quo - 1;
2849 return Quo;
2850 }
2851 if (Rem.isNegative() != B.isNegative())
2852 return Quo;
2853 return Quo + 1;
2854 }
2855 // Currently sdiv rounds towards zero.
2857 return A.sdiv(B);
2858 }
2859 llvm_unreachable("Unknown APInt::Rounding enum");
2860}
2861
2862std::optional<APInt>
2864 unsigned RangeWidth) {
2865 unsigned CoeffWidth = A.getBitWidth();
2866 assert(CoeffWidth == B.getBitWidth() && CoeffWidth == C.getBitWidth());
2867 assert(RangeWidth <= CoeffWidth &&
2868 "Value range width should be less than coefficient width");
2869 assert(RangeWidth > 1 && "Value range bit width should be > 1");
2870
2871 LLVM_DEBUG(dbgs() << __func__ << ": solving " << A << "x^2 + " << B
2872 << "x + " << C << ", rw:" << RangeWidth << '\n');
2873
2874 // Identify 0 as a (non)solution immediately.
2875 if (C.sextOrTrunc(RangeWidth).isZero()) {
2876 LLVM_DEBUG(dbgs() << __func__ << ": zero solution\n");
2877 return APInt(CoeffWidth, 0);
2878 }
2879
2880 // The result of APInt arithmetic has the same bit width as the operands,
2881 // so it can actually lose high bits. A product of two n-bit integers needs
2882 // 2n-1 bits to represent the full value.
2883 // The operation done below (on quadratic coefficients) that can produce
2884 // the largest value is the evaluation of the equation during bisection,
2885 // which needs 3 times the bitwidth of the coefficient, so the total number
2886 // of required bits is 3n.
2887 //
2888 // The purpose of this extension is to simulate the set Z of all integers,
2889 // where n+1 > n for all n in Z. In Z it makes sense to talk about positive
2890 // and negative numbers (not so much in a modulo arithmetic). The method
2891 // used to solve the equation is based on the standard formula for real
2892 // numbers, and uses the concepts of "positive" and "negative" with their
2893 // usual meanings.
2894 CoeffWidth *= 3;
2895 A = A.sext(CoeffWidth);
2896 B = B.sext(CoeffWidth);
2897 C = C.sext(CoeffWidth);
2898
2899 // Make A > 0 for simplicity. Negate cannot overflow at this point because
2900 // the bit width has increased.
2901 if (A.isNegative()) {
2902 A.negate();
2903 B.negate();
2904 C.negate();
2905 }
2906
2907 // Solving an equation q(x) = 0 with coefficients in modular arithmetic
2908 // is really solving a set of equations q(x) = kR for k = 0, 1, 2, ...,
2909 // and R = 2^BitWidth.
2910 // Since we're trying not only to find exact solutions, but also values
2911 // that "wrap around", such a set will always have a solution, i.e. an x
2912 // that satisfies at least one of the equations, or such that |q(x)|
2913 // exceeds kR, while |q(x-1)| for the same k does not.
2914 //
2915 // We need to find a value k, such that Ax^2 + Bx + C = kR will have a
2916 // positive solution n (in the above sense), and also such that the n
2917 // will be the least among all solutions corresponding to k = 0, 1, ...
2918 // (more precisely, the least element in the set
2919 // { n(k) | k is such that a solution n(k) exists }).
2920 //
2921 // Consider the parabola (over real numbers) that corresponds to the
2922 // quadratic equation. Since A > 0, the arms of the parabola will point
2923 // up. Picking different values of k will shift it up and down by R.
2924 //
2925 // We want to shift the parabola in such a way as to reduce the problem
2926 // of solving q(x) = kR to solving shifted_q(x) = 0.
2927 // (The interesting solutions are the ceilings of the real number
2928 // solutions.)
2929 APInt R = APInt::getOneBitSet(CoeffWidth, RangeWidth);
2930 APInt TwoA = 2 * A;
2931 APInt SqrB = B * B;
2932 bool PickLow;
2933
2934 auto RoundUp = [] (const APInt &V, const APInt &A) -> APInt {
2935 assert(A.isStrictlyPositive());
2936 APInt T = V.abs().urem(A);
2937 if (T.isZero())
2938 return V;
2939 return V.isNegative() ? V+T : V+(A-T);
2940 };
2941
2942 // The vertex of the parabola is at -B/2A, but since A > 0, it's negative
2943 // iff B is positive.
2944 if (B.isNonNegative()) {
2945 // If B >= 0, the vertex it at a negative location (or at 0), so in
2946 // order to have a non-negative solution we need to pick k that makes
2947 // C-kR negative. To satisfy all the requirements for the solution
2948 // that we are looking for, it needs to be closest to 0 of all k.
2949 C = C.srem(R);
2950 if (C.isStrictlyPositive())
2951 C -= R;
2952 // Pick the greater solution.
2953 PickLow = false;
2954 } else {
2955 // If B < 0, the vertex is at a positive location. For any solution
2956 // to exist, the discriminant must be non-negative. This means that
2957 // C-kR <= B^2/4A is a necessary condition for k, i.e. there is a
2958 // lower bound on values of k: kR >= C - B^2/4A.
2959 APInt LowkR = C - SqrB.udiv(2*TwoA); // udiv because all values > 0.
2960 // Round LowkR up (towards +inf) to the nearest kR.
2961 LowkR = RoundUp(LowkR, R);
2962
2963 // If there exists k meeting the condition above, and such that
2964 // C-kR > 0, there will be two positive real number solutions of
2965 // q(x) = kR. Out of all such values of k, pick the one that makes
2966 // C-kR closest to 0, (i.e. pick maximum k such that C-kR > 0).
2967 // In other words, find maximum k such that LowkR <= kR < C.
2968 if (C.sgt(LowkR)) {
2969 // If LowkR < C, then such a k is guaranteed to exist because
2970 // LowkR itself is a multiple of R.
2971 C -= -RoundUp(-C, R); // C = C - RoundDown(C, R)
2972 // Pick the smaller solution.
2973 PickLow = true;
2974 } else {
2975 // If C-kR < 0 for all potential k's, it means that one solution
2976 // will be negative, while the other will be positive. The positive
2977 // solution will shift towards 0 if the parabola is moved up.
2978 // Pick the kR closest to the lower bound (i.e. make C-kR closest
2979 // to 0, or in other words, out of all parabolas that have solutions,
2980 // pick the one that is the farthest "up").
2981 // Since LowkR is itself a multiple of R, simply take C-LowkR.
2982 C -= LowkR;
2983 // Pick the greater solution.
2984 PickLow = false;
2985 }
2986 }
2987
2988 LLVM_DEBUG(dbgs() << __func__ << ": updated coefficients " << A << "x^2 + "
2989 << B << "x + " << C << ", rw:" << RangeWidth << '\n');
2990
2991 APInt D = SqrB - 4*A*C;
2992 assert(D.isNonNegative() && "Negative discriminant");
2993 APInt SQ = D.sqrt();
2994
2995 APInt Q = SQ * SQ;
2996 bool InexactSQ = Q != D;
2997 // The calculated SQ may actually be greater than the exact (non-integer)
2998 // value. If that's the case, decrement SQ to get a value that is lower.
2999 if (Q.sgt(D))
3000 SQ -= 1;
3001
3002 APInt X;
3003 APInt Rem;
3004
3005 // SQ is rounded down (i.e SQ * SQ <= D), so the roots may be inexact.
3006 // When using the quadratic formula directly, the calculated low root
3007 // may be greater than the exact one, since we would be subtracting SQ.
3008 // To make sure that the calculated root is not greater than the exact
3009 // one, subtract SQ+1 when calculating the low root (for inexact value
3010 // of SQ).
3011 if (PickLow)
3012 APInt::sdivrem(-B - (SQ+InexactSQ), TwoA, X, Rem);
3013 else
3014 APInt::sdivrem(-B + SQ, TwoA, X, Rem);
3015
3016 // The updated coefficients should be such that the (exact) solution is
3017 // positive. Since APInt division rounds towards 0, the calculated one
3018 // can be 0, but cannot be negative.
3019 assert(X.isNonNegative() && "Solution should be non-negative");
3020
3021 if (!InexactSQ && Rem.isZero()) {
3022 LLVM_DEBUG(dbgs() << __func__ << ": solution (root): " << X << '\n');
3023 return X;
3024 }
3025
3026 assert((SQ*SQ).sle(D) && "SQ = |_sqrt(D)_|, so SQ*SQ <= D");
3027 // The exact value of the square root of D should be between SQ and SQ+1.
3028 // This implies that the solution should be between that corresponding to
3029 // SQ (i.e. X) and that corresponding to SQ+1.
3030 //
3031 // The calculated X cannot be greater than the exact (real) solution.
3032 // Actually it must be strictly less than the exact solution, while
3033 // X+1 will be greater than or equal to it.
3034
3035 APInt VX = (A*X + B)*X + C;
3036 APInt VY = VX + TwoA*X + A + B;
3037 bool SignChange =
3038 VX.isNegative() != VY.isNegative() || VX.isZero() != VY.isZero();
3039 // If the sign did not change between X and X+1, X is not a valid solution.
3040 // This could happen when the actual (exact) roots don't have an integer
3041 // between them, so they would both be contained between X and X+1.
3042 if (!SignChange) {
3043 LLVM_DEBUG(dbgs() << __func__ << ": no valid solution\n");
3044 return std::nullopt;
3045 }
3046
3047 X += 1;
3048 LLVM_DEBUG(dbgs() << __func__ << ": solution (wrap): " << X << '\n');
3049 return X;
3050}
3051
3052std::optional<unsigned>
3054 assert(A.getBitWidth() == B.getBitWidth() && "Must have the same bitwidth");
3055 if (A == B)
3056 return std::nullopt;
3057 return A.getBitWidth() - ((A ^ B).countl_zero() + 1);
3058}
3059
3060APInt llvm::APIntOps::ScaleBitMask(const APInt &A, unsigned NewBitWidth,
3061 bool MatchAllBits) {
3062 unsigned OldBitWidth = A.getBitWidth();
3063 assert((((OldBitWidth % NewBitWidth) == 0) ||
3064 ((NewBitWidth % OldBitWidth) == 0)) &&
3065 "One size should be a multiple of the other one. "
3066 "Can't do fractional scaling.");
3067
3068 // Check for matching bitwidths.
3069 if (OldBitWidth == NewBitWidth)
3070 return A;
3071
3072 APInt NewA = APInt::getZero(NewBitWidth);
3073
3074 // Check for null input.
3075 if (A.isZero())
3076 return NewA;
3077
3078 if (NewBitWidth > OldBitWidth) {
3079 // Repeat bits.
3080 unsigned Scale = NewBitWidth / OldBitWidth;
3081 for (unsigned i = 0; i != OldBitWidth; ++i)
3082 if (A[i])
3083 NewA.setBits(i * Scale, (i + 1) * Scale);
3084 } else {
3085 unsigned Scale = OldBitWidth / NewBitWidth;
3086 for (unsigned i = 0; i != NewBitWidth; ++i) {
3087 if (MatchAllBits) {
3088 if (A.extractBits(Scale, i * Scale).isAllOnes())
3089 NewA.setBit(i);
3090 } else {
3091 if (!A.extractBits(Scale, i * Scale).isZero())
3092 NewA.setBit(i);
3093 }
3094 }
3095 }
3096
3097 return NewA;
3098}
3099
3100/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
3101/// with the integer held in IntVal.
3102void llvm::StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
3103 unsigned StoreBytes) {
3104 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
3105 const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
3106
3108 // Little-endian host - the source is ordered from LSB to MSB. Order the
3109 // destination from LSB to MSB: Do a straight copy.
3110 memcpy(Dst, Src, StoreBytes);
3111 } else {
3112 // Big-endian host - the source is an array of 64 bit words ordered from
3113 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
3114 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
3115 while (StoreBytes > sizeof(uint64_t)) {
3116 StoreBytes -= sizeof(uint64_t);
3117 // May not be aligned so use memcpy.
3118 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
3119 Src += sizeof(uint64_t);
3120 }
3121
3122 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
3123 }
3124}
3125
3126/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
3127/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
3128void llvm::LoadIntFromMemory(APInt &IntVal, const uint8_t *Src,
3129 unsigned LoadBytes) {
3130 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
3131 uint8_t *Dst = reinterpret_cast<uint8_t *>(
3132 const_cast<uint64_t *>(IntVal.getRawData()));
3133
3135 // Little-endian host - the destination must be ordered from LSB to MSB.
3136 // The source is ordered from LSB to MSB: Do a straight copy.
3137 memcpy(Dst, Src, LoadBytes);
3138 else {
3139 // Big-endian - the destination is an array of 64 bit words ordered from
3140 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
3141 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
3142 // a word.
3143 while (LoadBytes > sizeof(uint64_t)) {
3144 LoadBytes -= sizeof(uint64_t);
3145 // May not be aligned so use memcpy.
3146 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
3147 Dst += sizeof(uint64_t);
3148 }
3149
3150 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
3151 }
3152}
3153
3154APInt APIntOps::avgFloorS(const APInt &C1, const APInt &C2) {
3155 // Return floor((C1 + C2) / 2)
3156 return (C1 & C2) + (C1 ^ C2).ashr(1);
3157}
3158
3159APInt APIntOps::avgFloorU(const APInt &C1, const APInt &C2) {
3160 // Return floor((C1 + C2) / 2)
3161 return (C1 & C2) + (C1 ^ C2).lshr(1);
3162}
3163
3164APInt APIntOps::avgCeilS(const APInt &C1, const APInt &C2) {
3165 // Return ceil((C1 + C2) / 2)
3166 return (C1 | C2) - (C1 ^ C2).ashr(1);
3167}
3168
3169APInt APIntOps::avgCeilU(const APInt &C1, const APInt &C2) {
3170 // Return ceil((C1 + C2) / 2)
3171 return (C1 | C2) - (C1 ^ C2).lshr(1);
3172}
3173
3174APInt APIntOps::mulhs(const APInt &C1, const APInt &C2) {
3175 assert(C1.getBitWidth() == C2.getBitWidth() && "Unequal bitwidths");
3176 unsigned FullWidth = C1.getBitWidth() * 2;
3177 APInt C1Ext = C1.sext(FullWidth);
3178 APInt C2Ext = C2.sext(FullWidth);
3179 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
3180}
3181
3182APInt APIntOps::mulhu(const APInt &C1, const APInt &C2) {
3183 assert(C1.getBitWidth() == C2.getBitWidth() && "Unequal bitwidths");
3184 unsigned FullWidth = C1.getBitWidth() * 2;
3185 APInt C1Ext = C1.zext(FullWidth);
3186 APInt C2Ext = C2.zext(FullWidth);
3187 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
3188}
3189
3191 assert(C1.getBitWidth() == C2.getBitWidth() && "Unequal bitwidths");
3192 unsigned FullWidth = C1.getBitWidth() * 2;
3193 APInt C1Ext = C1.sext(FullWidth);
3194 APInt C2Ext = C2.sext(FullWidth);
3195 return C1Ext * C2Ext;
3196}
3197
3199 assert(C1.getBitWidth() == C2.getBitWidth() && "Unequal bitwidths");
3200 unsigned FullWidth = C1.getBitWidth() * 2;
3201 APInt C1Ext = C1.zext(FullWidth);
3202 APInt C2Ext = C2.zext(FullWidth);
3203 return C1Ext * C2Ext;
3204}
3205
3206APInt APIntOps::pow(const APInt &X, int64_t N) {
3207 assert(N >= 0 && "negative exponents not supported.");
3208 APInt Acc = APInt(X.getBitWidth(), 1);
3209 if (N == 0)
3210 return Acc;
3211 APInt Base = X;
3212 int64_t RemainingExponent = N;
3213 while (RemainingExponent > 0) {
3214 while (RemainingExponent % 2 == 0) {
3215 Base *= Base;
3216 RemainingExponent /= 2;
3217 }
3218 --RemainingExponent;
3219 Acc *= Base;
3220 }
3221 return Acc;
3222}
3223
3225 const APInt &Shift) {
3226 assert(Hi.getBitWidth() == Lo.getBitWidth());
3227 unsigned ShiftAmt = rotateModulo(Hi.getBitWidth(), Shift);
3228 if (ShiftAmt == 0)
3229 return Hi;
3230 return Hi.shl(ShiftAmt) | Lo.lshr(Hi.getBitWidth() - ShiftAmt);
3231}
3232
3234 const APInt &Shift) {
3235 assert(Hi.getBitWidth() == Lo.getBitWidth());
3236 unsigned ShiftAmt = rotateModulo(Hi.getBitWidth(), Shift);
3237 if (ShiftAmt == 0)
3238 return Lo;
3239 return Hi.shl(Hi.getBitWidth() - ShiftAmt) | Lo.lshr(ShiftAmt);
3240}
3241
3242APInt llvm::APIntOps::clmul(const APInt &LHS, const APInt &RHS) {
3243 unsigned BW = LHS.getBitWidth();
3244 assert(BW == RHS.getBitWidth() && "Operand mismatch");
3245 APInt Result(BW, 0);
3246 for (unsigned I : seq(std::min(RHS.getActiveBits(), BW - LHS.countr_zero())))
3247 if (RHS[I])
3248 Result ^= LHS << I;
3249 return Result;
3250}
3251
3252APInt llvm::APIntOps::clmulr(const APInt &LHS, const APInt &RHS) {
3253 assert(LHS.getBitWidth() == RHS.getBitWidth());
3254 return clmul(LHS.reverseBits(), RHS.reverseBits()).reverseBits();
3255}
3256
3257APInt llvm::APIntOps::clmulh(const APInt &LHS, const APInt &RHS) {
3258 assert(LHS.getBitWidth() == RHS.getBitWidth());
3259 return clmulr(LHS, RHS).lshr(1);
3260}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static APInt::WordType lowHalf(APInt::WordType part)
Returns the value of the lower half of PART.
Definition APInt.cpp:2380
static unsigned rotateModulo(unsigned BitWidth, const APInt &rotateAmt)
Definition APInt.cpp:1165
static APInt::WordType highHalf(APInt::WordType part)
Returns the value of the upper half of PART.
Definition APInt.cpp:2385
static void tcComplement(APInt::WordType *dst, unsigned parts)
Definition APInt.cpp:367
#define DEBUG_KNUTH(X)
static unsigned getDigit(char cdigit, uint8_t radix)
A utility function that converts a character to a digit.
Definition APInt.cpp:47
static APInt::WordType lowBitMask(unsigned bits)
Definition APInt.cpp:2374
static uint64_t * getMemory(unsigned numWords)
A utility function for allocating memory and checking for allocation failure.
Definition APInt.cpp:42
static void KnuthDiv(uint32_t *u, uint32_t *v, uint32_t *q, uint32_t *r, unsigned m, unsigned n)
Implementation of Knuth's Algorithm D (Division of nonnegative integers) from "Art of Computer Progra...
Definition APInt.cpp:1332
static uint64_t * getClearedMemory(unsigned numWords)
A utility function for allocating memory, checking for allocation failures, and ensuring the contents...
Definition APInt.cpp:36
This file implements a class to represent arbitrary precision integral constant values and operations...
#define X(NUM, ENUM, NAME)
Definition ELF.h:851
static constexpr unsigned long long mask(BlockVerifier::State S)
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_UNLIKELY(EXPR)
Definition Compiler.h:336
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:661
static bool isNeg(Value *V)
Returns true if the operation is a negation of V, and it works for both integers and floats.
This file defines a hash set that can be used to remove duplication of nodes in a graph.
#define I(x, y, z)
Definition MD5.cpp:57
#define T
static uint64_t clearUnusedBits(uint64_t Val, unsigned Size)
Provides some synthesis utilities to produce sequences of values.
This file defines the SmallString class.
#define LLVM_DEBUG(...)
Definition Debug.h:114
Value * RHS
Value * LHS
This file implements the C++20 <bit> header.
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:2022
LLVM_ABI APInt usub_sat(const APInt &RHS) const
Definition APInt.cpp:2106
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1615
static LLVM_ABI void tcSetBit(WordType *, unsigned bit)
Set the given bit of a bignum. Zero-based.
Definition APInt.cpp:2419
static LLVM_ABI void tcSet(WordType *, WordType, unsigned)
Sets the least significant part of a bignum to the input value, and zeroes out higher parts.
Definition APInt.cpp:2391
LLVM_ABI unsigned nearestLogBase2() const
Definition APInt.cpp:1214
static LLVM_ABI void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Dual division/remainder interface.
Definition APInt.cpp:1809
LLVM_ABI APInt getLoBits(unsigned numBits) const
Compute an APInt containing numBits lowbits from this APInt.
Definition APInt.cpp:644
static LLVM_ABI int tcExtractBit(const WordType *, unsigned bit)
Extract the given bit of a bignum; returns 0 or 1. Zero-based.
Definition APInt.cpp:2414
LLVM_ABI bool isAligned(Align A) const
Checks if this APInt -interpreted as an address- is aligned to the provided value.
Definition APInt.cpp:169
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1054
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:424
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1563
LLVM_ABI APInt truncUSat(unsigned width) const
Truncate to new width with unsigned saturation.
Definition APInt.cpp:993
uint64_t * pVal
Used to store the >64 bits integer value.
Definition APInt.h:1962
static LLVM_ABI void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Definition APInt.cpp:1941
static LLVM_ABI WordType tcAdd(WordType *, const WordType *, WordType carry, unsigned)
DST += RHS + CARRY where CARRY is zero or one. Returns the carry flag.
Definition APInt.cpp:2493
static LLVM_ABI void tcExtract(WordType *, unsigned dstCount, const WordType *, unsigned srcBits, unsigned srcLSB)
Copy the bit vector of width srcBITS from SRC, starting at bit srcLSB, to DST, of dstCOUNT parts,...
Definition APInt.cpp:2463
LLVM_ABI uint64_t extractBitsAsZExtValue(unsigned numBits, unsigned bitPosition) const
Definition APInt.cpp:520
LLVM_ABI APInt getHiBits(unsigned numBits) const
Compute an APInt containing numBits highbits from this APInt.
Definition APInt.cpp:639
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition APInt.cpp:1075
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1535
static LLVM_ABI unsigned getSufficientBitsNeeded(StringRef Str, uint8_t Radix)
Get the bits that are sufficient to represent the string value.
Definition APInt.cpp:544
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:967
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:207
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1353
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:1714
LLVM_ABI APInt sshl_ov(const APInt &Amt, bool &Overflow) const
Definition APInt.cpp:2039
LLVM_ABI APInt smul_sat(const APInt &RHS) const
Definition APInt.cpp:2115
LLVM_ABI APInt sadd_sat(const APInt &RHS) const
Definition APInt.cpp:2077
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1208
static LLVM_ABI int tcCompare(const WordType *, const WordType *, unsigned)
Comparison (unsigned) of two bignums.
Definition APInt.cpp:2803
LLVM_ABI APInt & operator++()
Prefix increment operator.
Definition APInt.cpp:178
LLVM_ABI APInt usub_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1999
APInt(unsigned numBits, uint64_t val, bool isSigned=false, bool implicitTrunc=false)
Create a new APInt of numBits width, initialized as val.
Definition APInt.h:111
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1189
LLVM_ABI void print(raw_ostream &OS, bool isSigned) const
Definition APInt.cpp:2358
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:381
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1708
uint64_t WordType
Definition APInt.h:80
static LLVM_ABI void tcAssign(WordType *, const WordType *, unsigned)
Assign one bignum to another.
Definition APInt.cpp:2399
static constexpr unsigned APINT_WORD_SIZE
Byte size of a word.
Definition APInt.h:83
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1511
static LLVM_ABI void tcShiftRight(WordType *, unsigned Words, unsigned Count)
Shift a bignum right Count bits.
Definition APInt.cpp:2777
static LLVM_ABI void tcFullMultiply(WordType *, const WordType *, const WordType *, unsigned, unsigned)
DST = LHS * RHS, where DST has width the sum of the widths of the operands.
Definition APInt.cpp:2683
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1118
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:210
LLVM_ABI APInt sfloordiv_ov(const APInt &RHS, bool &Overflow) const
Signed integer floor division operation.
Definition APInt.cpp:2070
bool isSingleWord() const
Determine if this APInt just has one word to store value.
Definition APInt.h:323
unsigned getNumWords() const
Get the number of words.
Definition APInt.h:1518
APInt()
Default constructor that creates an APInt with a 1-bit zero value.
Definition APInt.h:174
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:330
LLVM_ABI APInt sadd_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1979
APInt & operator<<=(unsigned ShiftAmt)
Left-shift assignment function.
Definition APInt.h:792
LLVM_ABI APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
Definition APInt.cpp:1686
double roundToDouble() const
Converts this unsigned APInt to a double value.
Definition APInt.h:1735
LLVM_ABI APInt rotr(unsigned rotateAmt) const
Rotate right by rotateAmt.
Definition APInt.cpp:1196
LLVM_ABI APInt reverseBits() const
Definition APInt.cpp:789
void ashrInPlace(unsigned ShiftAmt)
Arithmetic right-shift this APInt by ShiftAmt in place.
Definition APInt.h:841
LLVM_ABI APInt uadd_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1986
static LLVM_ABI void tcClearBit(WordType *, unsigned bit)
Clear the given bit of a bignum. Zero-based.
Definition APInt.cpp:2424
void negate()
Negate this APInt in place.
Definition APInt.h:1491
static WordType tcDecrement(WordType *dst, unsigned parts)
Decrement a bignum in-place. Return the borrow flag.
Definition APInt.h:1941
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1662
LLVM_ABI bool isSplat(unsigned SplatSizeInBits) const
Check if the APInt consists of a repeated bit pattern.
Definition APInt.cpp:630
LLVM_ABI APInt truncSSatU(unsigned width) const
Truncate to new width with signed saturation to unsigned result.
Definition APInt.cpp:1016
LLVM_ABI APInt & operator-=(const APInt &RHS)
Subtraction assignment operator.
Definition APInt.cpp:218
bool isSignedIntN(unsigned N) const
Check if this APInt has an N-bits signed integer value.
Definition APInt.h:436
LLVM_ABI APInt sdiv_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:2005
LLVM_ABI APInt operator*(const APInt &RHS) const
Multiplication operator.
Definition APInt.cpp:235
static LLVM_ABI unsigned tcLSB(const WordType *, unsigned n)
Returns the bit number of the least or most significant set bit of a number.
Definition APInt.cpp:2430
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1621
static LLVM_ABI void tcShiftLeft(WordType *, unsigned Words, unsigned Count)
Shift a bignum left Count bits.
Definition APInt.cpp:2750
static LLVM_ABI APInt getSplat(unsigned NewLen, const APInt &V)
Return a value containing V broadcasted over NewLen bits.
Definition APInt.cpp:651
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:220
LLVM_ABI APInt sshl_sat(const APInt &RHS) const
Definition APInt.cpp:2137
static constexpr WordType WORDTYPE_MAX
Definition APInt.h:94
LLVM_ABI APInt ushl_sat(const APInt &RHS) const
Definition APInt.cpp:2151
LLVM_ABI APInt ushl_ov(const APInt &Amt, bool &Overflow) const
Definition APInt.cpp:2056
static LLVM_ABI WordType tcSubtractPart(WordType *, WordType, unsigned)
DST -= RHS. Returns the carry flag.
Definition APInt.cpp:2553
static LLVM_ABI bool tcIsZero(const WordType *, unsigned)
Returns true if a bignum is zero, false otherwise.
Definition APInt.cpp:2405
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition APInt.cpp:1083
static LLVM_ABI unsigned tcMSB(const WordType *parts, unsigned n)
Returns the bit number of the most significant set bit of a number.
Definition APInt.cpp:2443
static LLVM_ABI int tcDivide(WordType *lhs, const WordType *rhs, WordType *remainder, WordType *scratch, unsigned parts)
If RHS is zero LHS and REMAINDER are left unchanged, return one.
Definition APInt.cpp:2708
LLVM_DUMP_METHOD void dump() const
debug method
Definition APInt.cpp:2349
LLVM_ABI APInt rotl(unsigned rotateAmt) const
Rotate left by rotateAmt.
Definition APInt.cpp:1183
unsigned countl_one() const
Count the number of leading one bits.
Definition APInt.h:1638
LLVM_ABI void insertBits(const APInt &SubBits, unsigned bitPosition)
Insert the bits from a smaller APInt starting at bitPosition.
Definition APInt.cpp:397
unsigned logBase2() const
Definition APInt.h:1784
static LLVM_ABI int tcMultiplyPart(WordType *dst, const WordType *src, WordType multiplier, WordType carry, unsigned srcParts, unsigned dstParts, bool add)
DST += SRC * MULTIPLIER + PART if add is true DST = SRC * MULTIPLIER + PART if add is false.
Definition APInt.cpp:2581
static constexpr unsigned APINT_BITS_PER_WORD
Bits in a word.
Definition APInt.h:86
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:476
static LLVM_ABI int tcMultiply(WordType *, const WordType *, const WordType *, unsigned)
DST = LHS * RHS, where DST has the same width as the operands and is filled with the least significan...
Definition APInt.cpp:2665
LLVM_ABI APInt uadd_sat(const APInt &RHS) const
Definition APInt.cpp:2087
LLVM_ABI APInt & operator*=(const APInt &RHS)
Multiplication assignment operator.
Definition APInt.cpp:265
uint64_t VAL
Used to store the <= 64 bits integer value.
Definition APInt.h:1961
static LLVM_ABI unsigned getBitsNeeded(StringRef str, uint8_t radix)
Get bits required for string value.
Definition APInt.cpp:576
static LLVM_ABI WordType tcSubtract(WordType *, const WordType *, WordType carry, unsigned)
DST -= RHS + CARRY where CARRY is zero or one. Returns the carry flag.
Definition APInt.cpp:2528
LLVM_ABI APInt multiplicativeInverse() const
Definition APInt.cpp:1316
static LLVM_ABI void tcNegate(WordType *, unsigned)
Negate a bignum in-place.
Definition APInt.cpp:2567
bool getBoolValue() const
Convert APInt to a boolean value.
Definition APInt.h:472
LLVM_ABI APInt srem(const APInt &RHS) const
Function for signed remainder operation.
Definition APInt.cpp:1787
LLVM_ABI APInt smul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:2011
static WordType tcIncrement(WordType *dst, unsigned parts)
Increment a bignum in-place. Return the carry flag.
Definition APInt.h:1936
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:335
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1157
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1027
void setBits(unsigned loBit, unsigned hiBit)
Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
Definition APInt.h:1390
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:880
LLVM_ABI APInt byteSwap() const
Definition APInt.cpp:767
LLVM_ABI APInt umul_sat(const APInt &RHS) const
Definition APInt.cpp:2128
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:441
LLVM_ABI APInt & operator+=(const APInt &RHS)
Addition assignment operator.
Definition APInt.cpp:198
LLVM_ABI void flipBit(unsigned bitPosition)
Toggles a given bit to its opposite value.
Definition APInt.cpp:392
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:307
static LLVM_ABI WordType tcAddPart(WordType *, WordType, unsigned)
DST += RHS. Returns the carry flag.
Definition APInt.cpp:2515
const uint64_t * getRawData() const
This function returns a pointer to the internal storage of the APInt.
Definition APInt.h:576
LLVM_ABI void Profile(FoldingSetNodeID &id) const
Used to insert APInt objects, or objects that contain APInt objects, into FoldingSets.
Definition APInt.cpp:156
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:201
LLVM_ABI APInt extractBits(unsigned numBits, unsigned bitPosition) const
Return an APInt with the extracted bits [bitPosition,bitPosition+numBits).
Definition APInt.cpp:482
bool isIntN(unsigned N) const
Check if this APInt has an N-bits unsigned integer value.
Definition APInt.h:433
LLVM_ABI APInt ssub_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1992
LLVM_ABI APInt & operator--()
Prefix decrement operator.
Definition APInt.cpp:187
bool isOne() const
Determine if this is a value of 1.
Definition APInt.h:390
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:240
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1585
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
Definition APInt.h:865
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:858
LLVM_ABI APInt sqrt() const
Compute the square root.
Definition APInt.cpp:1241
void setBitVal(unsigned BitPosition, bool BitValue)
Set a given bit to a given value.
Definition APInt.h:1366
LLVM_ABI APInt ssub_sat(const APInt &RHS) const
Definition APInt.cpp:2096
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:1720
LLVM_ABI APInt truncSSat(unsigned width) const
Truncate to new width with signed saturation to signed result.
Definition APInt.cpp:1004
LLVM_ABI void toString(SmallVectorImpl< char > &Str, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false) const
Converts an APInt to a string and append it to Str.
Definition APInt.cpp:2215
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
const T * data() const
Definition ArrayRef.h:139
FoldingSetNodeID - This class is used to gather all the unique data bits of a node.
Definition FoldingSet.h:209
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
const char * iterator
Definition StringRef.h:59
constexpr bool empty() const
empty - Check if the string is empty.
Definition StringRef.h:140
iterator begin() const
Definition StringRef.h:113
constexpr size_t size() const
size - Get the string size.
Definition StringRef.h:143
iterator end() const
Definition StringRef.h:115
An opaque object representing a hash code.
Definition Hashing.h:76
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI std::optional< unsigned > GetMostSignificantDifferentBit(const APInt &A, const APInt &B)
Compare two values, and if they are different, return the position of the most significant bit that i...
Definition APInt.cpp:3053
LLVM_ABI APInt clmulr(const APInt &LHS, const APInt &RHS)
Perform a reversed carry-less multiply.
Definition APInt.cpp:3252
LLVM_ABI APInt mulhu(const APInt &C1, const APInt &C2)
Performs (2*N)-bit multiplication on zero-extended operands.
Definition APInt.cpp:3182
LLVM_ABI APInt RoundingUDiv(const APInt &A, const APInt &B, APInt::Rounding RM)
Return A unsign-divided by B, rounded by the given rounding mode.
Definition APInt.cpp:2814
LLVM_ABI APInt avgCeilU(const APInt &C1, const APInt &C2)
Compute the ceil of the unsigned average of C1 and C2.
Definition APInt.cpp:3169
LLVM_ABI APInt muluExtended(const APInt &C1, const APInt &C2)
Performs (2*N)-bit multiplication on zero-extended operands.
Definition APInt.cpp:3198
LLVM_ABI APInt mulsExtended(const APInt &C1, const APInt &C2)
Performs (2*N)-bit multiplication on sign-extended operands.
Definition APInt.cpp:3190
LLVM_ABI APInt avgFloorU(const APInt &C1, const APInt &C2)
Compute the floor of the unsigned average of C1 and C2.
Definition APInt.cpp:3159
LLVM_ABI APInt fshr(const APInt &Hi, const APInt &Lo, const APInt &Shift)
Perform a funnel shift right.
Definition APInt.cpp:3233
LLVM_ABI APInt mulhs(const APInt &C1, const APInt &C2)
Performs (2*N)-bit multiplication on sign-extended operands.
Definition APInt.cpp:3174
LLVM_ABI APInt RoundingSDiv(const APInt &A, const APInt &B, APInt::Rounding RM)
Return A sign-divided by B, rounded by the given rounding mode.
Definition APInt.cpp:2832
LLVM_ABI APInt clmul(const APInt &LHS, const APInt &RHS)
Perform a carry-less multiply, also known as XOR multiplication, and return low-bits.
Definition APInt.cpp:3242
LLVM_ABI APInt pow(const APInt &X, int64_t N)
Compute X^N for N>=0.
Definition APInt.cpp:3206
LLVM_ABI APInt RoundDoubleToAPInt(double Double, unsigned width)
Converts the given double value into a APInt.
Definition APInt.cpp:872
LLVM_ABI APInt fshl(const APInt &Hi, const APInt &Lo, const APInt &Shift)
Perform a funnel shift left.
Definition APInt.cpp:3224
LLVM_ABI APInt ScaleBitMask(const APInt &A, unsigned NewBitWidth, bool MatchAllBits=false)
Splat/Merge neighboring bits to widen/narrow the bitmask represented by.
Definition APInt.cpp:3060
LLVM_ABI std::optional< APInt > SolveQuadraticEquationWrap(APInt A, APInt B, APInt C, unsigned RangeWidth)
Let q(n) = An^2 + Bn + C, and BW = bit width of the value range (e.g.
Definition APInt.cpp:2863
LLVM_ABI APInt clmulh(const APInt &LHS, const APInt &RHS)
Perform a carry-less multiply, and return high-bits.
Definition APInt.cpp:3257
LLVM_ABI APInt avgFloorS(const APInt &C1, const APInt &C2)
Compute the floor of the signed average of C1 and C2.
Definition APInt.cpp:3154
LLVM_ABI APInt avgCeilS(const APInt &C1, const APInt &C2)
Compute the ceil of the signed average of C1 and C2.
Definition APInt.cpp:3164
LLVM_ABI APInt GreatestCommonDivisor(APInt A, APInt B)
Compute GCD of two unsigned APInt values.
Definition APInt.cpp:829
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
support::ulittle32_t Word
Definition IRSymtab.h:53
constexpr double e
constexpr bool IsLittleEndianHost
This is an optimization pass for GlobalISel generic memory operations.
hash_code hash_value(const FixedPointSemantics &Val)
LLVM_ABI void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst, unsigned StoreBytes)
StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst with the integer held in In...
Definition APInt.cpp:3102
int countr_one(T Value)
Count the number of ones from the least significant bit to the first zero bit.
Definition bit.h:315
constexpr T byteswap(T V) noexcept
Reverses the bytes in the given integer value V.
Definition bit.h:102
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:284
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:156
unsigned Log2_64(uint64_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:337
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:204
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:263
constexpr uint32_t Hi_32(uint64_t Value)
Return the high 32 bits of a 64 bit value.
Definition MathExtras.h:150
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
int countl_one(T Value)
Count the number of ones from the most significant bit to the first zero bit.
Definition bit.h:302
constexpr uint32_t Lo_32(uint64_t Value)
Return the low 32 bits of a 64 bit value.
Definition MathExtras.h:155
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
To bit_cast(const From &from) noexcept
Definition bit.h:90
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
constexpr T reverseBits(T Val)
Reverse the bits in Val.
Definition MathExtras.h:118
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:572
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:197
auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:305
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Definition Hashing.h:592
constexpr T maskTrailingOnes(unsigned N)
Create a bitmask with the N right-most bits set to 1, and all other bits set to 0.
Definition MathExtras.h:77
constexpr uint64_t Make_64(uint32_t High, uint32_t Low)
Make a 64-bit integer from a high / low pair of 32-bit integers.
Definition MathExtras.h:160
LLVM_ABI void LoadIntFromMemory(APInt &IntVal, const uint8_t *Src, unsigned LoadBytes)
LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting from Src into IntVal,...
Definition APInt.cpp:3128
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition Hashing.h:466
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
An information struct used to provide DenseMap with the various necessary components for a given valu...
static uint64_t round(uint64_t Acc, uint64_t Input)
Definition xxhash.cpp:80