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