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
203APInt& APInt::operator+=(uint64_t RHS) {
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
223APInt& APInt::operator-=(uint64_t RHS) {
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
266APInt& APInt::operator*=(uint64_t RHS) {
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
516uint64_t APInt::extractBitsAsZExtValue(unsigned numBits,
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) {
770 uint64_t Tmp1 = llvm::byteswap<uint64_t>(U.VAL);
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 // Take absolute value if IsSigned.
827 if (IsSigned) {
828 A = A.abs();
829 B = B.abs();
830 }
831
832 // Fast-path a common case.
833 if (A == B) return A;
834
835 // Corner cases: if either operand is zero, the other is the gcd.
836 if (!A) return B;
837 if (!B) return A;
838
839 // Count common powers of 2 and remove all other powers of 2.
840 unsigned Pow2;
841 {
842 unsigned Pow2_A = A.countr_zero();
843 unsigned Pow2_B = B.countr_zero();
844 if (Pow2_A > Pow2_B) {
845 A.lshrInPlace(Pow2_A - Pow2_B);
846 Pow2 = Pow2_B;
847 } else if (Pow2_B > Pow2_A) {
848 B.lshrInPlace(Pow2_B - Pow2_A);
849 Pow2 = Pow2_A;
850 } else {
851 Pow2 = Pow2_A;
852 }
853 }
854
855 // Both operands are odd multiples of 2^Pow_2:
856 //
857 // gcd(a, b) = gcd(|a - b| / 2^i, min(a, b))
858 //
859 // This is a modified version of Stein's algorithm, taking advantage of
860 // efficient countTrailingZeros().
861 while (A != B) {
862 if (A.ugt(B)) {
863 A -= B;
864 A.lshrInPlace(A.countr_zero() - Pow2);
865 } else {
866 B -= A;
867 B.lshrInPlace(B.countr_zero() - Pow2);
868 }
869 }
870
871 return A;
872}
873
874APInt llvm::APIntOps::RoundDoubleToAPInt(double Double, unsigned width) {
875 uint64_t I = bit_cast<uint64_t>(Double);
876
877 // Get the sign bit from the highest order bit
878 bool isNeg = I >> 63;
879
880 // Get the 11-bit exponent and adjust for the 1023 bit bias
881 int64_t exp = ((I >> 52) & 0x7ff) - 1023;
882
883 // If the exponent is negative, the value is < 0 so just return 0.
884 if (exp < 0)
885 return APInt(width, 0u);
886
887 // Extract the mantissa by clearing the top 12 bits (sign + exponent).
888 uint64_t mantissa = (I & (~0ULL >> 12)) | 1ULL << 52;
889
890 // If the exponent doesn't shift all bits out of the mantissa
891 if (exp < 52)
892 return isNeg ? -APInt(width, mantissa >> (52 - exp)) :
893 APInt(width, mantissa >> (52 - exp));
894
895 // If the client didn't provide enough bits for us to shift the mantissa into
896 // then the result is undefined, just return 0
897 if (width <= exp - 52)
898 return APInt(width, 0);
899
900 // Otherwise, we have to shift the mantissa bits up to the right location
901 APInt Tmp(width, mantissa);
902 Tmp <<= (unsigned)exp - 52;
903 return isNeg ? -Tmp : Tmp;
904}
905
906/// This function converts this APInt to a double.
907/// The layout for double is as following (IEEE Standard 754):
908/// --------------------------------------
909/// | Sign Exponent Fraction Bias |
910/// |-------------------------------------- |
911/// | 1[63] 11[62-52] 52[51-00] 1023 |
912/// --------------------------------------
913double APInt::roundToDouble(bool isSigned) const {
914 // Handle the simple case where the value is contained in one uint64_t.
915 // It is wrong to optimize getWord(0) to VAL; there might be more than one word.
917 if (isSigned) {
918 int64_t sext = SignExtend64(getWord(0), BitWidth);
919 return double(sext);
920 }
921 return double(getWord(0));
922 }
923
924 // Determine if the value is negative.
925 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
926
927 // Construct the absolute value if we're negative.
928 APInt Tmp(isNeg ? -(*this) : (*this));
929
930 // Figure out how many bits we're using.
931 unsigned n = Tmp.getActiveBits();
932
933 // The exponent (without bias normalization) is just the number of bits
934 // we are using. Note that the sign bit is gone since we constructed the
935 // absolute value.
936 uint64_t exp = n;
937
938 // Return infinity for exponent overflow
939 if (exp > 1023) {
940 if (!isSigned || !isNeg)
941 return std::numeric_limits<double>::infinity();
942 else
943 return -std::numeric_limits<double>::infinity();
944 }
945 exp += 1023; // Increment for 1023 bias
946
947 // Number of bits in mantissa is 52. To obtain the mantissa value, we must
948 // extract the high 52 bits from the correct words in pVal.
949 uint64_t mantissa;
950 unsigned hiWord = whichWord(n-1);
951 if (hiWord == 0) {
952 mantissa = Tmp.U.pVal[0];
953 if (n > 52)
954 mantissa >>= n - 52; // shift down, we want the top 52 bits.
955 } else {
956 assert(hiWord > 0 && "huh?");
957 uint64_t hibits = Tmp.U.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
958 uint64_t lobits = Tmp.U.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
959 mantissa = hibits | lobits;
960 }
961
962 // The leading bit of mantissa is implicit, so get rid of it.
963 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
964 uint64_t I = sign | (exp << 52) | mantissa;
965 return bit_cast<double>(I);
966}
967
968// Truncate to new width.
969APInt APInt::trunc(unsigned width) const {
970 assert(width <= BitWidth && "Invalid APInt Truncate request");
971
972 if (width <= APINT_BITS_PER_WORD)
973 return APInt(width, getRawData()[0], /*isSigned=*/false,
974 /*implicitTrunc=*/true);
975
976 if (width == BitWidth)
977 return *this;
978
979 APInt Result(getMemory(getNumWords(width)), width);
980
981 // Copy full words.
982 unsigned i;
983 for (i = 0; i != width / APINT_BITS_PER_WORD; i++)
984 Result.U.pVal[i] = U.pVal[i];
985
986 // Truncate and copy any partial word.
987 unsigned bits = (0 - width) % APINT_BITS_PER_WORD;
988 if (bits != 0)
989 Result.U.pVal[i] = U.pVal[i] << bits >> bits;
990
991 return Result;
992}
993
994// Truncate to new width with unsigned saturation.
995APInt APInt::truncUSat(unsigned width) const {
996 assert(width <= BitWidth && "Invalid APInt Truncate request");
997
998 // Can we just losslessly truncate it?
999 if (isIntN(width))
1000 return trunc(width);
1001 // If not, then just return the new limit.
1002 return APInt::getMaxValue(width);
1003}
1004
1005// Truncate to new width with signed saturation to signed result.
1006APInt APInt::truncSSat(unsigned width) const {
1007 assert(width <= BitWidth && "Invalid APInt Truncate request");
1008
1009 // Can we just losslessly truncate it?
1010 if (isSignedIntN(width))
1011 return trunc(width);
1012 // If not, then just return the new limits.
1013 return isNegative() ? APInt::getSignedMinValue(width)
1014 : APInt::getSignedMaxValue(width);
1015}
1016
1017// Truncate to new width with signed saturation to unsigned result.
1018APInt APInt::truncSSatU(unsigned width) const {
1019 assert(width <= BitWidth && "Invalid APInt Truncate request");
1020
1021 // Can we just losslessly truncate it?
1022 if (isIntN(width))
1023 return trunc(width);
1024 // If not, then just return the new limits.
1025 return isNegative() ? APInt::getZero(width) : APInt::getMaxValue(width);
1026}
1027
1028// Sign extend to a new width.
1029APInt APInt::sext(unsigned Width) const {
1030 assert(Width >= BitWidth && "Invalid APInt SignExtend request");
1031
1032 if (Width <= APINT_BITS_PER_WORD)
1033 return APInt(Width, SignExtend64(U.VAL, BitWidth), /*isSigned=*/true);
1034
1035 if (Width == BitWidth)
1036 return *this;
1037
1038 APInt Result(getMemory(getNumWords(Width)), Width);
1039
1040 // Copy words.
1041 std::memcpy(Result.U.pVal, getRawData(), getNumWords() * APINT_WORD_SIZE);
1042
1043 // Sign extend the last word since there may be unused bits in the input.
1044 Result.U.pVal[getNumWords() - 1] =
1045 SignExtend64(Result.U.pVal[getNumWords() - 1],
1046 ((BitWidth - 1) % APINT_BITS_PER_WORD) + 1);
1047
1048 // Fill with sign bits.
1049 std::memset(Result.U.pVal + getNumWords(), isNegative() ? -1 : 0,
1050 (Result.getNumWords() - getNumWords()) * APINT_WORD_SIZE);
1051 Result.clearUnusedBits();
1052 return Result;
1053}
1054
1055// Zero extend to a new width.
1056APInt APInt::zext(unsigned width) const {
1057 assert(width >= BitWidth && "Invalid APInt ZeroExtend request");
1058
1059 if (width <= APINT_BITS_PER_WORD)
1060 return APInt(width, U.VAL);
1061
1062 if (width == BitWidth)
1063 return *this;
1064
1065 APInt Result(getMemory(getNumWords(width)), width);
1066
1067 // Copy words.
1068 std::memcpy(Result.U.pVal, getRawData(), getNumWords() * APINT_WORD_SIZE);
1069
1070 // Zero remaining words.
1071 std::memset(Result.U.pVal + getNumWords(), 0,
1072 (Result.getNumWords() - getNumWords()) * APINT_WORD_SIZE);
1073
1074 return Result;
1075}
1076
1077APInt APInt::zextOrTrunc(unsigned width) const {
1078 if (BitWidth < width)
1079 return zext(width);
1080 if (BitWidth > width)
1081 return trunc(width);
1082 return *this;
1083}
1084
1085APInt APInt::sextOrTrunc(unsigned width) const {
1086 if (BitWidth < width)
1087 return sext(width);
1088 if (BitWidth > width)
1089 return trunc(width);
1090 return *this;
1091}
1092
1093/// Arithmetic right-shift this APInt by shiftAmt.
1094/// Arithmetic right-shift function.
1095void APInt::ashrInPlace(const APInt &shiftAmt) {
1096 ashrInPlace((unsigned)shiftAmt.getLimitedValue(BitWidth));
1097}
1098
1099/// Arithmetic right-shift this APInt by shiftAmt.
1100/// Arithmetic right-shift function.
1101void APInt::ashrSlowCase(unsigned ShiftAmt) {
1102 // Don't bother performing a no-op shift.
1103 if (!ShiftAmt)
1104 return;
1105
1106 // Save the original sign bit for later.
1107 bool Negative = isNegative();
1108
1109 // WordShift is the inter-part shift; BitShift is intra-part shift.
1110 unsigned WordShift = ShiftAmt / APINT_BITS_PER_WORD;
1111 unsigned BitShift = ShiftAmt % APINT_BITS_PER_WORD;
1112
1113 unsigned WordsToMove = getNumWords() - WordShift;
1114 if (WordsToMove != 0) {
1115 // Sign extend the last word to fill in the unused bits.
1116 U.pVal[getNumWords() - 1] = SignExtend64(
1117 U.pVal[getNumWords() - 1], ((BitWidth - 1) % APINT_BITS_PER_WORD) + 1);
1118
1119 // Fastpath for moving by whole words.
1120 if (BitShift == 0) {
1121 std::memmove(U.pVal, U.pVal + WordShift, WordsToMove * APINT_WORD_SIZE);
1122 } else {
1123 // Move the words containing significant bits.
1124 for (unsigned i = 0; i != WordsToMove - 1; ++i)
1125 U.pVal[i] = (U.pVal[i + WordShift] >> BitShift) |
1126 (U.pVal[i + WordShift + 1] << (APINT_BITS_PER_WORD - BitShift));
1127
1128 // Handle the last word which has no high bits to copy. Use an arithmetic
1129 // shift to preserve the sign bit.
1130 U.pVal[WordsToMove - 1] =
1131 (int64_t)U.pVal[WordShift + WordsToMove - 1] >> BitShift;
1132 }
1133 }
1134
1135 // Fill in the remainder based on the original sign.
1136 std::memset(U.pVal + WordsToMove, Negative ? -1 : 0,
1137 WordShift * APINT_WORD_SIZE);
1138 clearUnusedBits();
1139}
1140
1141/// Logical right-shift this APInt by shiftAmt.
1142/// Logical right-shift function.
1143void APInt::lshrInPlace(const APInt &shiftAmt) {
1144 lshrInPlace((unsigned)shiftAmt.getLimitedValue(BitWidth));
1145}
1146
1147/// Logical right-shift this APInt by shiftAmt.
1148/// Logical right-shift function.
1149void APInt::lshrSlowCase(unsigned ShiftAmt) {
1150 tcShiftRight(U.pVal, getNumWords(), ShiftAmt);
1151}
1152
1153/// Left-shift this APInt by shiftAmt.
1154/// Left-shift function.
1155APInt &APInt::operator<<=(const APInt &shiftAmt) {
1156 // It's undefined behavior in C to shift by BitWidth or greater.
1157 *this <<= (unsigned)shiftAmt.getLimitedValue(BitWidth);
1158 return *this;
1159}
1160
1161void APInt::shlSlowCase(unsigned ShiftAmt) {
1162 tcShiftLeft(U.pVal, getNumWords(), ShiftAmt);
1164}
1165
1166// Calculate the rotate amount modulo the bit width.
1167static unsigned rotateModulo(unsigned BitWidth, const APInt &rotateAmt) {
1168 if (LLVM_UNLIKELY(BitWidth == 0))
1169 return 0;
1170 unsigned rotBitWidth = rotateAmt.getBitWidth();
1171 APInt rot = rotateAmt;
1172 if (rotBitWidth < BitWidth) {
1173 // Extend the rotate APInt, so that the urem doesn't divide by 0.
1174 // e.g. APInt(1, 32) would give APInt(1, 0).
1175 rot = rotateAmt.zext(BitWidth);
1176 }
1177 rot = rot.urem(APInt(rot.getBitWidth(), BitWidth));
1178 return rot.getLimitedValue(BitWidth);
1179}
1180
1181APInt APInt::rotl(const APInt &rotateAmt) const {
1182 return rotl(rotateModulo(BitWidth, rotateAmt));
1183}
1184
1185APInt APInt::rotl(unsigned rotateAmt) const {
1186 if (LLVM_UNLIKELY(BitWidth == 0))
1187 return *this;
1188 rotateAmt %= BitWidth;
1189 if (rotateAmt == 0)
1190 return *this;
1191 return shl(rotateAmt) | lshr(BitWidth - rotateAmt);
1192}
1193
1194APInt APInt::rotr(const APInt &rotateAmt) const {
1195 return rotr(rotateModulo(BitWidth, rotateAmt));
1196}
1197
1198APInt APInt::rotr(unsigned rotateAmt) const {
1199 if (BitWidth == 0)
1200 return *this;
1201 rotateAmt %= BitWidth;
1202 if (rotateAmt == 0)
1203 return *this;
1204 return lshr(rotateAmt) | shl(BitWidth - rotateAmt);
1205}
1206
1207/// \returns the nearest log base 2 of this APInt. Ties round up.
1208///
1209/// NOTE: When we have a BitWidth of 1, we define:
1210///
1211/// log2(0) = UINT32_MAX
1212/// log2(1) = 0
1213///
1214/// to get around any mathematical concerns resulting from
1215/// referencing 2 in a space where 2 does no exist.
1216unsigned APInt::nearestLogBase2() const {
1217 // Special case when we have a bitwidth of 1. If VAL is 1, then we
1218 // get 0. If VAL is 0, we get WORDTYPE_MAX which gets truncated to
1219 // UINT32_MAX.
1220 if (BitWidth == 1)
1221 return U.VAL - 1;
1222
1223 // Handle the zero case.
1224 if (isZero())
1225 return UINT32_MAX;
1226
1227 // The non-zero case is handled by computing:
1228 //
1229 // nearestLogBase2(x) = logBase2(x) + x[logBase2(x)-1].
1230 //
1231 // where x[i] is referring to the value of the ith bit of x.
1232 unsigned lg = logBase2();
1233 return lg + unsigned((*this)[lg - 1]);
1234}
1235
1236// Square Root - this method computes and returns the square root of "this".
1237// Three mechanisms are used for computation. For small values (<= 5 bits),
1238// a table lookup is done. This gets some performance for common cases. For
1239// values using less than 52 bits, the value is converted to double and then
1240// the libc sqrt function is called. The result is rounded and then converted
1241// back to a uint64_t which is then used to construct the result. Finally,
1242// the Babylonian method for computing square roots is used.
1244
1245 // Determine the magnitude of the value.
1246 unsigned magnitude = getActiveBits();
1247
1248 // Use a fast table for some small values. This also gets rid of some
1249 // rounding errors in libc sqrt for small values.
1250 if (magnitude <= 5) {
1251 static const uint8_t results[32] = {
1252 /* 0 */ 0,
1253 /* 1- 3 */ 1, 1, 1,
1254 /* 4- 8 */ 2, 2, 2, 2, 2,
1255 /* 9-15 */ 3, 3, 3, 3, 3, 3, 3,
1256 /* 16-24 */ 4, 4, 4, 4, 4, 4, 4, 4, 4,
1257 /* 25-31 */ 5, 5, 5, 5, 5, 5, 5,
1258 };
1259 return APInt(BitWidth, results[ (isSingleWord() ? U.VAL : U.pVal[0]) ]);
1260 }
1261
1262 // If the magnitude of the value fits in less than 52 bits (the precision of
1263 // an IEEE double precision floating point value), then we can use the
1264 // libc sqrt function which will probably use a hardware sqrt computation.
1265 // This should be faster than the algorithm below.
1266 if (magnitude < 52) {
1267 return APInt(
1268 BitWidth,
1269 uint64_t(::floor(::sqrt(double(isSingleWord() ? U.VAL : U.pVal[0])))));
1270 }
1271
1272 // Okay, all the short cuts are exhausted. We must compute it. The following
1273 // is a classical Babylonian method for computing the square root. This code
1274 // was adapted to APInt from a wikipedia article on such computations.
1275 // See http://www.wikipedia.org/ and go to the page named
1276 // Calculate_an_integer_square_root.
1277 unsigned nbits = BitWidth, i = 4;
1278 APInt testy(BitWidth, 16);
1279 APInt x_old(BitWidth, 1);
1280 APInt x_new(BitWidth, 0);
1281 APInt two(BitWidth, 2);
1282
1283 // Select a good starting value using binary logarithms.
1284 for (;; i += 2, testy = testy.shl(2))
1285 if (i >= nbits || this->ule(testy)) {
1286 x_old = x_old.shl(i / 2);
1287 break;
1288 }
1289
1290 // Use the Babylonian method to arrive at the integer square root:
1291 for (;;) {
1292 x_new = (this->udiv(x_old) + x_old).udiv(two);
1293 if (x_old.ule(x_new))
1294 break;
1295 x_old = x_new;
1296 }
1297 return x_old;
1298}
1299
1300/// \returns the multiplicative inverse of an odd APInt modulo 2^BitWidth.
1302 assert((*this)[0] &&
1303 "multiplicative inverse is only defined for odd numbers!");
1304
1305 // Use Newton's method.
1306 APInt Factor = *this;
1307 APInt T;
1308 while (!(T = *this * Factor).isOne())
1309 Factor *= 2 - std::move(T);
1310 return Factor;
1311}
1312
1313/// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
1314/// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
1315/// variables here have the same names as in the algorithm. Comments explain
1316/// the algorithm and any deviation from it.
1317static void KnuthDiv(uint32_t *u, uint32_t *v, uint32_t *q, uint32_t* r,
1318 unsigned m, unsigned n) {
1319 assert(u && "Must provide dividend");
1320 assert(v && "Must provide divisor");
1321 assert(q && "Must provide quotient");
1322 assert(u != v && u != q && v != q && "Must use different memory");
1323 assert(n>1 && "n must be > 1");
1324
1325 // b denotes the base of the number system. In our case b is 2^32.
1326 const uint64_t b = uint64_t(1) << 32;
1327
1328// The DEBUG macros here tend to be spam in the debug output if you're not
1329// debugging this code. Disable them unless KNUTH_DEBUG is defined.
1330#ifdef KNUTH_DEBUG
1331#define DEBUG_KNUTH(X) LLVM_DEBUG(X)
1332#else
1333#define DEBUG_KNUTH(X) do {} while(false)
1334#endif
1335
1336 DEBUG_KNUTH(dbgs() << "KnuthDiv: m=" << m << " n=" << n << '\n');
1337 DEBUG_KNUTH(dbgs() << "KnuthDiv: original:");
1338 DEBUG_KNUTH(for (int i = m + n; i >= 0; i--) dbgs() << " " << u[i]);
1339 DEBUG_KNUTH(dbgs() << " by");
1340 DEBUG_KNUTH(for (int i = n; i > 0; i--) dbgs() << " " << v[i - 1]);
1341 DEBUG_KNUTH(dbgs() << '\n');
1342 // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
1343 // u and v by d. Note that we have taken Knuth's advice here to use a power
1344 // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
1345 // 2 allows us to shift instead of multiply and it is easy to determine the
1346 // shift amount from the leading zeros. We are basically normalizing the u
1347 // and v so that its high bits are shifted to the top of v's range without
1348 // overflow. Note that this can require an extra word in u so that u must
1349 // be of length m+n+1.
1350 unsigned shift = llvm::countl_zero(v[n - 1]);
1351 uint32_t v_carry = 0;
1352 uint32_t u_carry = 0;
1353 if (shift) {
1354 for (unsigned i = 0; i < m+n; ++i) {
1355 uint32_t u_tmp = u[i] >> (32 - shift);
1356 u[i] = (u[i] << shift) | u_carry;
1357 u_carry = u_tmp;
1358 }
1359 for (unsigned i = 0; i < n; ++i) {
1360 uint32_t v_tmp = v[i] >> (32 - shift);
1361 v[i] = (v[i] << shift) | v_carry;
1362 v_carry = v_tmp;
1363 }
1364 }
1365 u[m+n] = u_carry;
1366
1367 DEBUG_KNUTH(dbgs() << "KnuthDiv: normal:");
1368 DEBUG_KNUTH(for (int i = m + n; i >= 0; i--) dbgs() << " " << u[i]);
1369 DEBUG_KNUTH(dbgs() << " by");
1370 DEBUG_KNUTH(for (int i = n; i > 0; i--) dbgs() << " " << v[i - 1]);
1371 DEBUG_KNUTH(dbgs() << '\n');
1372
1373 // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
1374 int j = m;
1375 do {
1376 DEBUG_KNUTH(dbgs() << "KnuthDiv: quotient digit #" << j << '\n');
1377 // D3. [Calculate q'.].
1378 // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
1379 // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
1380 // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
1381 // qp by 1, increase rp by v[n-1], and repeat this test if rp < b. The test
1382 // on v[n-2] determines at high speed most of the cases in which the trial
1383 // value qp is one too large, and it eliminates all cases where qp is two
1384 // too large.
1385 uint64_t dividend = Make_64(u[j+n], u[j+n-1]);
1386 DEBUG_KNUTH(dbgs() << "KnuthDiv: dividend == " << dividend << '\n');
1387 uint64_t qp = dividend / v[n-1];
1388 uint64_t rp = dividend % v[n-1];
1389 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1390 qp--;
1391 rp += v[n-1];
1392 if (rp < b && (qp == b || qp*v[n-2] > b*rp + u[j+n-2]))
1393 qp--;
1394 }
1395 DEBUG_KNUTH(dbgs() << "KnuthDiv: qp == " << qp << ", rp == " << rp << '\n');
1396
1397 // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with
1398 // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation
1399 // consists of a simple multiplication by a one-place number, combined with
1400 // a subtraction.
1401 // The digits (u[j+n]...u[j]) should be kept positive; if the result of
1402 // this step is actually negative, (u[j+n]...u[j]) should be left as the
1403 // true value plus b**(n+1), namely as the b's complement of
1404 // the true value, and a "borrow" to the left should be remembered.
1405 int64_t borrow = 0;
1406 for (unsigned i = 0; i < n; ++i) {
1407 uint64_t p = qp * uint64_t(v[i]);
1408 int64_t subres = int64_t(u[j+i]) - borrow - Lo_32(p);
1409 u[j+i] = Lo_32(subres);
1410 borrow = Hi_32(p) - Hi_32(subres);
1411 DEBUG_KNUTH(dbgs() << "KnuthDiv: u[j+i] = " << u[j + i]
1412 << ", borrow = " << borrow << '\n');
1413 }
1414 bool isNeg = u[j+n] < borrow;
1415 u[j+n] -= Lo_32(borrow);
1416
1417 DEBUG_KNUTH(dbgs() << "KnuthDiv: after subtraction:");
1418 DEBUG_KNUTH(for (int i = m + n; i >= 0; i--) dbgs() << " " << u[i]);
1419 DEBUG_KNUTH(dbgs() << '\n');
1420
1421 // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
1422 // negative, go to step D6; otherwise go on to step D7.
1423 q[j] = Lo_32(qp);
1424 if (isNeg) {
1425 // D6. [Add back]. The probability that this step is necessary is very
1426 // small, on the order of only 2/b. Make sure that test data accounts for
1427 // this possibility. Decrease q[j] by 1
1428 q[j]--;
1429 // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]).
1430 // A carry will occur to the left of u[j+n], and it should be ignored
1431 // since it cancels with the borrow that occurred in D4.
1432 bool carry = false;
1433 for (unsigned i = 0; i < n; i++) {
1434 uint32_t limit = std::min(u[j+i],v[i]);
1435 u[j+i] += v[i] + carry;
1436 carry = u[j+i] < limit || (carry && u[j+i] == limit);
1437 }
1438 u[j+n] += carry;
1439 }
1440 DEBUG_KNUTH(dbgs() << "KnuthDiv: after correction:");
1441 DEBUG_KNUTH(for (int i = m + n; i >= 0; i--) dbgs() << " " << u[i]);
1442 DEBUG_KNUTH(dbgs() << "\nKnuthDiv: digit result = " << q[j] << '\n');
1443
1444 // D7. [Loop on j.] Decrease j by one. Now if j >= 0, go back to D3.
1445 } while (--j >= 0);
1446
1447 DEBUG_KNUTH(dbgs() << "KnuthDiv: quotient:");
1448 DEBUG_KNUTH(for (int i = m; i >= 0; i--) dbgs() << " " << q[i]);
1449 DEBUG_KNUTH(dbgs() << '\n');
1450
1451 // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
1452 // remainder may be obtained by dividing u[...] by d. If r is non-null we
1453 // compute the remainder (urem uses this).
1454 if (r) {
1455 // The value d is expressed by the "shift" value above since we avoided
1456 // multiplication by d by using a shift left. So, all we have to do is
1457 // shift right here.
1458 if (shift) {
1459 uint32_t carry = 0;
1460 DEBUG_KNUTH(dbgs() << "KnuthDiv: remainder:");
1461 for (int i = n-1; i >= 0; i--) {
1462 r[i] = (u[i] >> shift) | carry;
1463 carry = u[i] << (32 - shift);
1464 DEBUG_KNUTH(dbgs() << " " << r[i]);
1465 }
1466 } else {
1467 for (int i = n-1; i >= 0; i--) {
1468 r[i] = u[i];
1469 DEBUG_KNUTH(dbgs() << " " << r[i]);
1470 }
1471 }
1472 DEBUG_KNUTH(dbgs() << '\n');
1473 }
1474 DEBUG_KNUTH(dbgs() << '\n');
1475}
1476
1477void APInt::divide(const WordType *LHS, unsigned lhsWords, const WordType *RHS,
1478 unsigned rhsWords, WordType *Quotient, WordType *Remainder) {
1479 assert(lhsWords >= rhsWords && "Fractional result");
1480
1481 // First, compose the values into an array of 32-bit words instead of
1482 // 64-bit words. This is a necessity of both the "short division" algorithm
1483 // and the Knuth "classical algorithm" which requires there to be native
1484 // operations for +, -, and * on an m bit value with an m*2 bit result. We
1485 // can't use 64-bit operands here because we don't have native results of
1486 // 128-bits. Furthermore, casting the 64-bit values to 32-bit values won't
1487 // work on large-endian machines.
1488 unsigned n = rhsWords * 2;
1489 unsigned m = (lhsWords * 2) - n;
1490
1491 // Allocate space for the temporary values we need either on the stack, if
1492 // it will fit, or on the heap if it won't.
1493 uint32_t SPACE[128];
1494 uint32_t *U = nullptr;
1495 uint32_t *V = nullptr;
1496 uint32_t *Q = nullptr;
1497 uint32_t *R = nullptr;
1498 if ((Remainder?4:3)*n+2*m+1 <= 128) {
1499 U = &SPACE[0];
1500 V = &SPACE[m+n+1];
1501 Q = &SPACE[(m+n+1) + n];
1502 if (Remainder)
1503 R = &SPACE[(m+n+1) + n + (m+n)];
1504 } else {
1505 U = new uint32_t[m + n + 1];
1506 V = new uint32_t[n];
1507 Q = new uint32_t[m+n];
1508 if (Remainder)
1509 R = new uint32_t[n];
1510 }
1511
1512 // Initialize the dividend
1513 memset(U, 0, (m+n+1)*sizeof(uint32_t));
1514 for (unsigned i = 0; i < lhsWords; ++i) {
1515 uint64_t tmp = LHS[i];
1516 U[i * 2] = Lo_32(tmp);
1517 U[i * 2 + 1] = Hi_32(tmp);
1518 }
1519 U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
1520
1521 // Initialize the divisor
1522 memset(V, 0, (n)*sizeof(uint32_t));
1523 for (unsigned i = 0; i < rhsWords; ++i) {
1524 uint64_t tmp = RHS[i];
1525 V[i * 2] = Lo_32(tmp);
1526 V[i * 2 + 1] = Hi_32(tmp);
1527 }
1528
1529 // initialize the quotient and remainder
1530 memset(Q, 0, (m+n) * sizeof(uint32_t));
1531 if (Remainder)
1532 memset(R, 0, n * sizeof(uint32_t));
1533
1534 // Now, adjust m and n for the Knuth division. n is the number of words in
1535 // the divisor. m is the number of words by which the dividend exceeds the
1536 // divisor (i.e. m+n is the length of the dividend). These sizes must not
1537 // contain any zero words or the Knuth algorithm fails.
1538 for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
1539 n--;
1540 m++;
1541 }
1542 for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
1543 m--;
1544
1545 // If we're left with only a single word for the divisor, Knuth doesn't work
1546 // so we implement the short division algorithm here. This is much simpler
1547 // and faster because we are certain that we can divide a 64-bit quantity
1548 // by a 32-bit quantity at hardware speed and short division is simply a
1549 // series of such operations. This is just like doing short division but we
1550 // are using base 2^32 instead of base 10.
1551 assert(n != 0 && "Divide by zero?");
1552 if (n == 1) {
1553 uint32_t divisor = V[0];
1554 uint32_t remainder = 0;
1555 for (int i = m; i >= 0; i--) {
1556 uint64_t partial_dividend = Make_64(remainder, U[i]);
1557 if (partial_dividend == 0) {
1558 Q[i] = 0;
1559 remainder = 0;
1560 } else if (partial_dividend < divisor) {
1561 Q[i] = 0;
1562 remainder = Lo_32(partial_dividend);
1563 } else if (partial_dividend == divisor) {
1564 Q[i] = 1;
1565 remainder = 0;
1566 } else {
1567 Q[i] = Lo_32(partial_dividend / divisor);
1568 remainder = Lo_32(partial_dividend - (Q[i] * divisor));
1569 }
1570 }
1571 if (R)
1572 R[0] = remainder;
1573 } else {
1574 // Now we're ready to invoke the Knuth classical divide algorithm. In this
1575 // case n > 1.
1576 KnuthDiv(U, V, Q, R, m, n);
1577 }
1578
1579 // If the caller wants the quotient
1580 if (Quotient) {
1581 for (unsigned i = 0; i < lhsWords; ++i)
1582 Quotient[i] = Make_64(Q[i*2+1], Q[i*2]);
1583 }
1584
1585 // If the caller wants the remainder
1586 if (Remainder) {
1587 for (unsigned i = 0; i < rhsWords; ++i)
1588 Remainder[i] = Make_64(R[i*2+1], R[i*2]);
1589 }
1590
1591 // Clean up the memory we allocated.
1592 if (U != &SPACE[0]) {
1593 delete [] U;
1594 delete [] V;
1595 delete [] Q;
1596 delete [] R;
1597 }
1598}
1599
1600APInt APInt::udiv(const APInt &RHS) const {
1601 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1602
1603 // First, deal with the easy case
1604 if (isSingleWord()) {
1605 assert(RHS.U.VAL != 0 && "Divide by zero?");
1606 return APInt(BitWidth, U.VAL / RHS.U.VAL);
1607 }
1608
1609 // Get some facts about the LHS and RHS number of bits and words
1610 unsigned lhsWords = getNumWords(getActiveBits());
1611 unsigned rhsBits = RHS.getActiveBits();
1612 unsigned rhsWords = getNumWords(rhsBits);
1613 assert(rhsWords && "Divided by zero???");
1614
1615 // Deal with some degenerate cases
1616 if (!lhsWords)
1617 // 0 / X ===> 0
1618 return APInt(BitWidth, 0);
1619 if (rhsBits == 1)
1620 // X / 1 ===> X
1621 return *this;
1622 if (lhsWords < rhsWords || this->ult(RHS))
1623 // X / Y ===> 0, iff X < Y
1624 return APInt(BitWidth, 0);
1625 if (*this == RHS)
1626 // X / X ===> 1
1627 return APInt(BitWidth, 1);
1628 if (lhsWords == 1) // rhsWords is 1 if lhsWords is 1.
1629 // All high words are zero, just use native divide
1630 return APInt(BitWidth, this->U.pVal[0] / RHS.U.pVal[0]);
1631
1632 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1633 APInt Quotient(BitWidth, 0); // to hold result.
1634 divide(U.pVal, lhsWords, RHS.U.pVal, rhsWords, Quotient.U.pVal, nullptr);
1635 return Quotient;
1636}
1637
1638APInt APInt::udiv(uint64_t RHS) const {
1639 assert(RHS != 0 && "Divide by zero?");
1640
1641 // First, deal with the easy case
1642 if (isSingleWord())
1643 return APInt(BitWidth, U.VAL / RHS);
1644
1645 // Get some facts about the LHS words.
1646 unsigned lhsWords = getNumWords(getActiveBits());
1647
1648 // Deal with some degenerate cases
1649 if (!lhsWords)
1650 // 0 / X ===> 0
1651 return APInt(BitWidth, 0);
1652 if (RHS == 1)
1653 // X / 1 ===> X
1654 return *this;
1655 if (this->ult(RHS))
1656 // X / Y ===> 0, iff X < Y
1657 return APInt(BitWidth, 0);
1658 if (*this == RHS)
1659 // X / X ===> 1
1660 return APInt(BitWidth, 1);
1661 if (lhsWords == 1) // rhsWords is 1 if lhsWords is 1.
1662 // All high words are zero, just use native divide
1663 return APInt(BitWidth, this->U.pVal[0] / RHS);
1664
1665 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1666 APInt Quotient(BitWidth, 0); // to hold result.
1667 divide(U.pVal, lhsWords, &RHS, 1, Quotient.U.pVal, nullptr);
1668 return Quotient;
1669}
1670
1671APInt APInt::sdiv(const APInt &RHS) const {
1672 if (isNegative()) {
1673 if (RHS.isNegative())
1674 return (-(*this)).udiv(-RHS);
1675 return -((-(*this)).udiv(RHS));
1676 }
1677 if (RHS.isNegative())
1678 return -(this->udiv(-RHS));
1679 return this->udiv(RHS);
1680}
1681
1682APInt APInt::sdiv(int64_t RHS) const {
1683 if (isNegative()) {
1684 if (RHS < 0)
1685 return (-(*this)).udiv(-RHS);
1686 return -((-(*this)).udiv(RHS));
1687 }
1688 if (RHS < 0)
1689 return -(this->udiv(-RHS));
1690 return this->udiv(RHS);
1691}
1692
1693APInt APInt::urem(const APInt &RHS) const {
1694 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1695 if (isSingleWord()) {
1696 assert(RHS.U.VAL != 0 && "Remainder by zero?");
1697 return APInt(BitWidth, U.VAL % RHS.U.VAL);
1698 }
1699
1700 // Get some facts about the LHS
1701 unsigned lhsWords = getNumWords(getActiveBits());
1702
1703 // Get some facts about the RHS
1704 unsigned rhsBits = RHS.getActiveBits();
1705 unsigned rhsWords = getNumWords(rhsBits);
1706 assert(rhsWords && "Performing remainder operation by zero ???");
1707
1708 // Check the degenerate cases
1709 if (lhsWords == 0)
1710 // 0 % Y ===> 0
1711 return APInt(BitWidth, 0);
1712 if (rhsBits == 1)
1713 // X % 1 ===> 0
1714 return APInt(BitWidth, 0);
1715 if (lhsWords < rhsWords || this->ult(RHS))
1716 // X % Y ===> X, iff X < Y
1717 return *this;
1718 if (*this == RHS)
1719 // X % X == 0;
1720 return APInt(BitWidth, 0);
1721 if (lhsWords == 1)
1722 // All high words are zero, just use native remainder
1723 return APInt(BitWidth, U.pVal[0] % RHS.U.pVal[0]);
1724 if (RHS.isPowerOf2()) {
1725 // X % 2^w ===> X & (2^w - 1)
1726 APInt Result(*this);
1727 Result.clearBits(RHS.logBase2(), BitWidth);
1728 return Result;
1729 }
1730
1731 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1732 APInt Remainder(BitWidth, 0);
1733 divide(U.pVal, lhsWords, RHS.U.pVal, rhsWords, nullptr, Remainder.U.pVal);
1734 return Remainder;
1735}
1736
1737uint64_t APInt::urem(uint64_t RHS) const {
1738 assert(RHS != 0 && "Remainder by zero?");
1739
1740 if (isSingleWord())
1741 return U.VAL % RHS;
1742
1743 // Get some facts about the LHS
1744 unsigned lhsWords = getNumWords(getActiveBits());
1745
1746 // Check the degenerate cases
1747 if (lhsWords == 0)
1748 // 0 % Y ===> 0
1749 return 0;
1750 if (RHS == 1)
1751 // X % 1 ===> 0
1752 return 0;
1753 if (this->ult(RHS))
1754 // X % Y ===> X, iff X < Y
1755 return getZExtValue();
1756 if (*this == RHS)
1757 // X % X == 0;
1758 return 0;
1759 if (lhsWords == 1)
1760 // All high words are zero, just use native remainder
1761 return U.pVal[0] % RHS;
1762 if (llvm::isPowerOf2_64(RHS))
1763 // X % 2^w ===> X & (2^w - 1)
1764 return U.pVal[0] & (RHS - 1);
1765
1766 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1767 uint64_t Remainder;
1768 divide(U.pVal, lhsWords, &RHS, 1, nullptr, &Remainder);
1769 return Remainder;
1770}
1771
1772APInt APInt::srem(const APInt &RHS) const {
1773 if (isNegative()) {
1774 if (RHS.isNegative())
1775 return -((-(*this)).urem(-RHS));
1776 return -((-(*this)).urem(RHS));
1777 }
1778 if (RHS.isNegative())
1779 return this->urem(-RHS);
1780 return this->urem(RHS);
1781}
1782
1783int64_t APInt::srem(int64_t RHS) const {
1784 if (isNegative()) {
1785 if (RHS < 0)
1786 return -((-(*this)).urem(-RHS));
1787 return -((-(*this)).urem(RHS));
1788 }
1789 if (RHS < 0)
1790 return this->urem(-RHS);
1791 return this->urem(RHS);
1792}
1793
1794void APInt::udivrem(const APInt &LHS, const APInt &RHS,
1795 APInt &Quotient, APInt &Remainder) {
1796 assert(LHS.BitWidth == RHS.BitWidth && "Bit widths must be the same");
1797 unsigned BitWidth = LHS.BitWidth;
1798
1799 // First, deal with the easy case
1800 if (LHS.isSingleWord()) {
1801 assert(RHS.U.VAL != 0 && "Divide by zero?");
1802 uint64_t QuotVal = LHS.U.VAL / RHS.U.VAL;
1803 uint64_t RemVal = LHS.U.VAL % RHS.U.VAL;
1804 Quotient = APInt(BitWidth, QuotVal);
1805 Remainder = APInt(BitWidth, RemVal);
1806 return;
1807 }
1808
1809 // Get some size facts about the dividend and divisor
1810 unsigned lhsWords = getNumWords(LHS.getActiveBits());
1811 unsigned rhsBits = RHS.getActiveBits();
1812 unsigned rhsWords = getNumWords(rhsBits);
1813 assert(rhsWords && "Performing divrem operation by zero ???");
1814
1815 // Check the degenerate cases
1816 if (lhsWords == 0) {
1817 Quotient = APInt(BitWidth, 0); // 0 / Y ===> 0
1818 Remainder = APInt(BitWidth, 0); // 0 % Y ===> 0
1819 return;
1820 }
1821
1822 if (rhsBits == 1) {
1823 Quotient = LHS; // X / 1 ===> X
1824 Remainder = APInt(BitWidth, 0); // X % 1 ===> 0
1825 }
1826
1827 if (lhsWords < rhsWords || LHS.ult(RHS)) {
1828 Remainder = LHS; // X % Y ===> X, iff X < Y
1829 Quotient = APInt(BitWidth, 0); // X / Y ===> 0, iff X < Y
1830 return;
1831 }
1832
1833 if (LHS == RHS) {
1834 Quotient = APInt(BitWidth, 1); // X / X ===> 1
1835 Remainder = APInt(BitWidth, 0); // X % X ===> 0;
1836 return;
1837 }
1838
1839 // Make sure there is enough space to hold the results.
1840 // NOTE: This assumes that reallocate won't affect any bits if it doesn't
1841 // change the size. This is necessary if Quotient or Remainder is aliased
1842 // with LHS or RHS.
1843 Quotient.reallocate(BitWidth);
1844 Remainder.reallocate(BitWidth);
1845
1846 if (lhsWords == 1) { // rhsWords is 1 if lhsWords is 1.
1847 // There is only one word to consider so use the native versions.
1848 uint64_t lhsValue = LHS.U.pVal[0];
1849 uint64_t rhsValue = RHS.U.pVal[0];
1850 Quotient = lhsValue / rhsValue;
1851 Remainder = lhsValue % rhsValue;
1852 return;
1853 }
1854
1855 // Okay, lets do it the long way
1856 divide(LHS.U.pVal, lhsWords, RHS.U.pVal, rhsWords, Quotient.U.pVal,
1857 Remainder.U.pVal);
1858 // Clear the rest of the Quotient and Remainder.
1859 std::memset(Quotient.U.pVal + lhsWords, 0,
1860 (getNumWords(BitWidth) - lhsWords) * APINT_WORD_SIZE);
1861 std::memset(Remainder.U.pVal + rhsWords, 0,
1862 (getNumWords(BitWidth) - rhsWords) * APINT_WORD_SIZE);
1863}
1864
1865void APInt::udivrem(const APInt &LHS, uint64_t RHS, APInt &Quotient,
1866 uint64_t &Remainder) {
1867 assert(RHS != 0 && "Divide by zero?");
1868 unsigned BitWidth = LHS.BitWidth;
1869
1870 // First, deal with the easy case
1871 if (LHS.isSingleWord()) {
1872 uint64_t QuotVal = LHS.U.VAL / RHS;
1873 Remainder = LHS.U.VAL % RHS;
1874 Quotient = APInt(BitWidth, QuotVal);
1875 return;
1876 }
1877
1878 // Get some size facts about the dividend and divisor
1879 unsigned lhsWords = getNumWords(LHS.getActiveBits());
1880
1881 // Check the degenerate cases
1882 if (lhsWords == 0) {
1883 Quotient = APInt(BitWidth, 0); // 0 / Y ===> 0
1884 Remainder = 0; // 0 % Y ===> 0
1885 return;
1886 }
1887
1888 if (RHS == 1) {
1889 Quotient = LHS; // X / 1 ===> X
1890 Remainder = 0; // X % 1 ===> 0
1891 return;
1892 }
1893
1894 if (LHS.ult(RHS)) {
1895 Remainder = LHS.getZExtValue(); // X % Y ===> X, iff X < Y
1896 Quotient = APInt(BitWidth, 0); // X / Y ===> 0, iff X < Y
1897 return;
1898 }
1899
1900 if (LHS == RHS) {
1901 Quotient = APInt(BitWidth, 1); // X / X ===> 1
1902 Remainder = 0; // X % X ===> 0;
1903 return;
1904 }
1905
1906 // Make sure there is enough space to hold the results.
1907 // NOTE: This assumes that reallocate won't affect any bits if it doesn't
1908 // change the size. This is necessary if Quotient is aliased with LHS.
1909 Quotient.reallocate(BitWidth);
1910
1911 if (lhsWords == 1) { // rhsWords is 1 if lhsWords is 1.
1912 // There is only one word to consider so use the native versions.
1913 uint64_t lhsValue = LHS.U.pVal[0];
1914 Quotient = lhsValue / RHS;
1915 Remainder = lhsValue % RHS;
1916 return;
1917 }
1918
1919 // Okay, lets do it the long way
1920 divide(LHS.U.pVal, lhsWords, &RHS, 1, Quotient.U.pVal, &Remainder);
1921 // Clear the rest of the Quotient.
1922 std::memset(Quotient.U.pVal + lhsWords, 0,
1923 (getNumWords(BitWidth) - lhsWords) * APINT_WORD_SIZE);
1924}
1925
1926void APInt::sdivrem(const APInt &LHS, const APInt &RHS,
1927 APInt &Quotient, APInt &Remainder) {
1928 if (LHS.isNegative()) {
1929 if (RHS.isNegative())
1930 APInt::udivrem(-LHS, -RHS, Quotient, Remainder);
1931 else {
1932 APInt::udivrem(-LHS, RHS, Quotient, Remainder);
1933 Quotient.negate();
1934 }
1935 Remainder.negate();
1936 } else if (RHS.isNegative()) {
1937 APInt::udivrem(LHS, -RHS, Quotient, Remainder);
1938 Quotient.negate();
1939 } else {
1940 APInt::udivrem(LHS, RHS, Quotient, Remainder);
1941 }
1942}
1943
1944void APInt::sdivrem(const APInt &LHS, int64_t RHS,
1945 APInt &Quotient, int64_t &Remainder) {
1946 uint64_t R = Remainder;
1947 if (LHS.isNegative()) {
1948 if (RHS < 0)
1949 APInt::udivrem(-LHS, -RHS, Quotient, R);
1950 else {
1951 APInt::udivrem(-LHS, RHS, Quotient, R);
1952 Quotient.negate();
1953 }
1954 R = -R;
1955 } else if (RHS < 0) {
1956 APInt::udivrem(LHS, -RHS, Quotient, R);
1957 Quotient.negate();
1958 } else {
1959 APInt::udivrem(LHS, RHS, Quotient, R);
1960 }
1961 Remainder = R;
1962}
1963
1964APInt APInt::sadd_ov(const APInt &RHS, bool &Overflow) const {
1965 APInt Res = *this+RHS;
1966 Overflow = isNonNegative() == RHS.isNonNegative() &&
1967 Res.isNonNegative() != isNonNegative();
1968 return Res;
1969}
1970
1971APInt APInt::uadd_ov(const APInt &RHS, bool &Overflow) const {
1972 APInt Res = *this+RHS;
1973 Overflow = Res.ult(RHS);
1974 return Res;
1975}
1976
1977APInt APInt::ssub_ov(const APInt &RHS, bool &Overflow) const {
1978 APInt Res = *this - RHS;
1979 Overflow = isNonNegative() != RHS.isNonNegative() &&
1980 Res.isNonNegative() != isNonNegative();
1981 return Res;
1982}
1983
1984APInt APInt::usub_ov(const APInt &RHS, bool &Overflow) const {
1985 APInt Res = *this-RHS;
1986 Overflow = Res.ugt(*this);
1987 return Res;
1988}
1989
1990APInt APInt::sdiv_ov(const APInt &RHS, bool &Overflow) const {
1991 // MININT/-1 --> overflow.
1992 Overflow = isMinSignedValue() && RHS.isAllOnes();
1993 return sdiv(RHS);
1994}
1995
1996APInt APInt::smul_ov(const APInt &RHS, bool &Overflow) const {
1997 APInt Res = *this * RHS;
1998
1999 if (RHS != 0)
2000 Overflow = Res.sdiv(RHS) != *this ||
2001 (isMinSignedValue() && RHS.isAllOnes());
2002 else
2003 Overflow = false;
2004 return Res;
2005}
2006
2007APInt APInt::umul_ov(const APInt &RHS, bool &Overflow) const {
2008 if (countl_zero() + RHS.countl_zero() + 2 <= BitWidth) {
2009 Overflow = true;
2010 return *this * RHS;
2011 }
2012
2013 APInt Res = lshr(1) * RHS;
2014 Overflow = Res.isNegative();
2015 Res <<= 1;
2016 if ((*this)[0]) {
2017 Res += RHS;
2018 if (Res.ult(RHS))
2019 Overflow = true;
2020 }
2021 return Res;
2022}
2023
2024APInt APInt::sshl_ov(const APInt &ShAmt, bool &Overflow) const {
2025 return sshl_ov(ShAmt.getLimitedValue(getBitWidth()), Overflow);
2026}
2027
2028APInt APInt::sshl_ov(unsigned ShAmt, bool &Overflow) const {
2029 Overflow = ShAmt >= getBitWidth();
2030 if (Overflow)
2031 return APInt(BitWidth, 0);
2032
2033 if (isNonNegative()) // Don't allow sign change.
2034 Overflow = ShAmt >= countl_zero();
2035 else
2036 Overflow = ShAmt >= countl_one();
2037
2038 return *this << ShAmt;
2039}
2040
2041APInt APInt::ushl_ov(const APInt &ShAmt, bool &Overflow) const {
2042 return ushl_ov(ShAmt.getLimitedValue(getBitWidth()), Overflow);
2043}
2044
2045APInt APInt::ushl_ov(unsigned ShAmt, bool &Overflow) const {
2046 Overflow = ShAmt >= getBitWidth();
2047 if (Overflow)
2048 return APInt(BitWidth, 0);
2049
2050 Overflow = ShAmt > countl_zero();
2051
2052 return *this << ShAmt;
2053}
2054
2055APInt APInt::sfloordiv_ov(const APInt &RHS, bool &Overflow) const {
2056 APInt quotient = sdiv_ov(RHS, Overflow);
2057 if ((quotient * RHS != *this) && (isNegative() != RHS.isNegative()))
2058 return quotient - 1;
2059 return quotient;
2060}
2061
2062APInt APInt::sadd_sat(const APInt &RHS) const {
2063 bool Overflow;
2064 APInt Res = sadd_ov(RHS, Overflow);
2065 if (!Overflow)
2066 return Res;
2067
2068 return isNegative() ? APInt::getSignedMinValue(BitWidth)
2069 : APInt::getSignedMaxValue(BitWidth);
2070}
2071
2072APInt APInt::uadd_sat(const APInt &RHS) const {
2073 bool Overflow;
2074 APInt Res = uadd_ov(RHS, Overflow);
2075 if (!Overflow)
2076 return Res;
2077
2078 return APInt::getMaxValue(BitWidth);
2079}
2080
2081APInt APInt::ssub_sat(const APInt &RHS) const {
2082 bool Overflow;
2083 APInt Res = ssub_ov(RHS, Overflow);
2084 if (!Overflow)
2085 return Res;
2086
2087 return isNegative() ? APInt::getSignedMinValue(BitWidth)
2088 : APInt::getSignedMaxValue(BitWidth);
2089}
2090
2091APInt APInt::usub_sat(const APInt &RHS) const {
2092 bool Overflow;
2093 APInt Res = usub_ov(RHS, Overflow);
2094 if (!Overflow)
2095 return Res;
2096
2097 return APInt(BitWidth, 0);
2098}
2099
2100APInt APInt::smul_sat(const APInt &RHS) const {
2101 bool Overflow;
2102 APInt Res = smul_ov(RHS, Overflow);
2103 if (!Overflow)
2104 return Res;
2105
2106 // The result is negative if one and only one of inputs is negative.
2107 bool ResIsNegative = isNegative() ^ RHS.isNegative();
2108
2109 return ResIsNegative ? APInt::getSignedMinValue(BitWidth)
2110 : APInt::getSignedMaxValue(BitWidth);
2111}
2112
2113APInt APInt::umul_sat(const APInt &RHS) const {
2114 bool Overflow;
2115 APInt Res = umul_ov(RHS, Overflow);
2116 if (!Overflow)
2117 return Res;
2118
2119 return APInt::getMaxValue(BitWidth);
2120}
2121
2122APInt APInt::sshl_sat(const APInt &RHS) const {
2123 return sshl_sat(RHS.getLimitedValue(getBitWidth()));
2124}
2125
2126APInt APInt::sshl_sat(unsigned RHS) const {
2127 bool Overflow;
2128 APInt Res = sshl_ov(RHS, Overflow);
2129 if (!Overflow)
2130 return Res;
2131
2132 return isNegative() ? APInt::getSignedMinValue(BitWidth)
2133 : APInt::getSignedMaxValue(BitWidth);
2134}
2135
2136APInt APInt::ushl_sat(const APInt &RHS) const {
2137 return ushl_sat(RHS.getLimitedValue(getBitWidth()));
2138}
2139
2140APInt APInt::ushl_sat(unsigned RHS) const {
2141 bool Overflow;
2142 APInt Res = ushl_ov(RHS, Overflow);
2143 if (!Overflow)
2144 return Res;
2145
2146 return APInt::getMaxValue(BitWidth);
2147}
2148
2149void APInt::fromString(unsigned numbits, StringRef str, uint8_t radix) {
2150 // Check our assumptions here
2151 assert(!str.empty() && "Invalid string length");
2152 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 ||
2153 radix == 36) &&
2154 "Radix should be 2, 8, 10, 16, or 36!");
2155
2156 StringRef::iterator p = str.begin();
2157 size_t slen = str.size();
2158 bool isNeg = *p == '-';
2159 if (*p == '-' || *p == '+') {
2160 p++;
2161 slen--;
2162 assert(slen && "String is only a sign, needs a value.");
2163 }
2164 assert((slen <= numbits || radix != 2) && "Insufficient bit width");
2165 assert(((slen-1)*3 <= numbits || radix != 8) && "Insufficient bit width");
2166 assert(((slen-1)*4 <= numbits || radix != 16) && "Insufficient bit width");
2167 assert((((slen-1)*64)/22 <= numbits || radix != 10) &&
2168 "Insufficient bit width");
2169
2170 // Allocate memory if needed
2171 if (isSingleWord())
2172 U.VAL = 0;
2173 else
2174 U.pVal = getClearedMemory(getNumWords());
2175
2176 // Figure out if we can shift instead of multiply
2177 unsigned shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0);
2178
2179 // Enter digit traversal loop
2180 for (StringRef::iterator e = str.end(); p != e; ++p) {
2181 unsigned digit = getDigit(*p, radix);
2182 assert(digit < radix && "Invalid character in digit string");
2183
2184 // Shift or multiply the value by the radix
2185 if (slen > 1) {
2186 if (shift)
2187 *this <<= shift;
2188 else
2189 *this *= radix;
2190 }
2191
2192 // Add in the digit we just interpreted
2193 *this += digit;
2194 }
2195 // If its negative, put it in two's complement form
2196 if (isNeg)
2197 this->negate();
2198}
2199
2200void APInt::toString(SmallVectorImpl<char> &Str, unsigned Radix, bool Signed,
2201 bool formatAsCLiteral, bool UpperCase,
2202 bool InsertSeparators) const {
2203 assert((Radix == 10 || Radix == 8 || Radix == 16 || Radix == 2 ||
2204 Radix == 36) &&
2205 "Radix should be 2, 8, 10, 16, or 36!");
2206
2207 const char *Prefix = "";
2208 if (formatAsCLiteral) {
2209 switch (Radix) {
2210 case 2:
2211 // Binary literals are a non-standard extension added in gcc 4.3:
2212 // http://gcc.gnu.org/onlinedocs/gcc-4.3.0/gcc/Binary-constants.html
2213 Prefix = "0b";
2214 break;
2215 case 8:
2216 Prefix = "0";
2217 break;
2218 case 10:
2219 break; // No prefix
2220 case 16:
2221 Prefix = "0x";
2222 break;
2223 default:
2224 llvm_unreachable("Invalid radix!");
2225 }
2226 }
2227
2228 // Number of digits in a group between separators.
2229 unsigned Grouping = (Radix == 8 || Radix == 10) ? 3 : 4;
2230
2231 // First, check for a zero value and just short circuit the logic below.
2232 if (isZero()) {
2233 while (*Prefix) {
2234 Str.push_back(*Prefix);
2235 ++Prefix;
2236 };
2237 Str.push_back('0');
2238 return;
2239 }
2240
2241 static const char BothDigits[] = "0123456789abcdefghijklmnopqrstuvwxyz"
2242 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
2243 const char *Digits = BothDigits + (UpperCase ? 36 : 0);
2244
2245 if (isSingleWord()) {
2246 char Buffer[65];
2247 char *BufPtr = std::end(Buffer);
2248
2249 uint64_t N;
2250 if (!Signed) {
2251 N = getZExtValue();
2252 } else {
2253 int64_t I = getSExtValue();
2254 if (I >= 0) {
2255 N = I;
2256 } else {
2257 Str.push_back('-');
2258 N = -(uint64_t)I;
2259 }
2260 }
2261
2262 while (*Prefix) {
2263 Str.push_back(*Prefix);
2264 ++Prefix;
2265 };
2266
2267 int Pos = 0;
2268 while (N) {
2269 if (InsertSeparators && Pos % Grouping == 0 && Pos > 0)
2270 *--BufPtr = '\'';
2271 *--BufPtr = Digits[N % Radix];
2272 N /= Radix;
2273 Pos++;
2274 }
2275 Str.append(BufPtr, std::end(Buffer));
2276 return;
2277 }
2278
2279 APInt Tmp(*this);
2280
2281 if (Signed && isNegative()) {
2282 // They want to print the signed version and it is a negative value
2283 // Flip the bits and add one to turn it into the equivalent positive
2284 // value and put a '-' in the result.
2285 Tmp.negate();
2286 Str.push_back('-');
2287 }
2288
2289 while (*Prefix) {
2290 Str.push_back(*Prefix);
2291 ++Prefix;
2292 }
2293
2294 // We insert the digits backward, then reverse them to get the right order.
2295 unsigned StartDig = Str.size();
2296
2297 // For the 2, 8 and 16 bit cases, we can just shift instead of divide
2298 // because the number of bits per digit (1, 3 and 4 respectively) divides
2299 // equally. We just shift until the value is zero.
2300 if (Radix == 2 || Radix == 8 || Radix == 16) {
2301 // Just shift tmp right for each digit width until it becomes zero
2302 unsigned ShiftAmt = (Radix == 16 ? 4 : (Radix == 8 ? 3 : 1));
2303 unsigned MaskAmt = Radix - 1;
2304
2305 int Pos = 0;
2306 while (Tmp.getBoolValue()) {
2307 unsigned Digit = unsigned(Tmp.getRawData()[0]) & MaskAmt;
2308 if (InsertSeparators && Pos % Grouping == 0 && Pos > 0)
2309 Str.push_back('\'');
2310
2311 Str.push_back(Digits[Digit]);
2312 Tmp.lshrInPlace(ShiftAmt);
2313 Pos++;
2314 }
2315 } else {
2316 int Pos = 0;
2317 while (Tmp.getBoolValue()) {
2318 uint64_t Digit;
2319 udivrem(Tmp, Radix, Tmp, Digit);
2320 assert(Digit < Radix && "divide failed");
2321 if (InsertSeparators && Pos % Grouping == 0 && Pos > 0)
2322 Str.push_back('\'');
2323
2324 Str.push_back(Digits[Digit]);
2325 Pos++;
2326 }
2327 }
2328
2329 // Reverse the digits before returning.
2330 std::reverse(Str.begin()+StartDig, Str.end());
2331}
2332
2333#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2335 SmallString<40> S, U;
2336 this->toStringUnsigned(U);
2337 this->toStringSigned(S);
2338 dbgs() << "APInt(" << BitWidth << "b, "
2339 << U << "u " << S << "s)\n";
2340}
2341#endif
2342
2343void APInt::print(raw_ostream &OS, bool isSigned) const {
2345 this->toString(S, 10, isSigned, /* formatAsCLiteral = */false);
2346 OS << S;
2347}
2348
2349// This implements a variety of operations on a representation of
2350// arbitrary precision, two's-complement, bignum integer values.
2351
2352// Assumed by lowHalf, highHalf, partMSB and partLSB. A fairly safe
2353// and unrestricting assumption.
2354static_assert(APInt::APINT_BITS_PER_WORD % 2 == 0,
2355 "Part width must be divisible by 2!");
2356
2357// Returns the integer part with the least significant BITS set.
2358// BITS cannot be zero.
2359static inline APInt::WordType lowBitMask(unsigned bits) {
2360 assert(bits != 0 && bits <= APInt::APINT_BITS_PER_WORD);
2361 return ~(APInt::WordType) 0 >> (APInt::APINT_BITS_PER_WORD - bits);
2362}
2363
2364/// Returns the value of the lower half of PART.
2366 return part & lowBitMask(APInt::APINT_BITS_PER_WORD / 2);
2367}
2368
2369/// Returns the value of the upper half of PART.
2371 return part >> (APInt::APINT_BITS_PER_WORD / 2);
2372}
2373
2374/// Sets the least significant part of a bignum to the input value, and zeroes
2375/// out higher parts.
2376void APInt::tcSet(WordType *dst, WordType part, unsigned parts) {
2377 assert(parts > 0);
2378 dst[0] = part;
2379 for (unsigned i = 1; i < parts; i++)
2380 dst[i] = 0;
2381}
2382
2383/// Assign one bignum to another.
2384void APInt::tcAssign(WordType *dst, const WordType *src, unsigned parts) {
2385 for (unsigned i = 0; i < parts; i++)
2386 dst[i] = src[i];
2387}
2388
2389/// Returns true if a bignum is zero, false otherwise.
2390bool APInt::tcIsZero(const WordType *src, unsigned parts) {
2391 for (unsigned i = 0; i < parts; i++)
2392 if (src[i])
2393 return false;
2394
2395 return true;
2396}
2397
2398/// Extract the given bit of a bignum; returns 0 or 1.
2399int APInt::tcExtractBit(const WordType *parts, unsigned bit) {
2400 return (parts[whichWord(bit)] & maskBit(bit)) != 0;
2401}
2402
2403/// Set the given bit of a bignum.
2404void APInt::tcSetBit(WordType *parts, unsigned bit) {
2405 parts[whichWord(bit)] |= maskBit(bit);
2406}
2407
2408/// Clears the given bit of a bignum.
2409void APInt::tcClearBit(WordType *parts, unsigned bit) {
2410 parts[whichWord(bit)] &= ~maskBit(bit);
2411}
2412
2413/// Returns the bit number of the least significant set bit of a number. If the
2414/// input number has no bits set UINT_MAX is returned.
2415unsigned APInt::tcLSB(const WordType *parts, unsigned n) {
2416 for (unsigned i = 0; i < n; i++) {
2417 if (parts[i] != 0) {
2418 unsigned lsb = llvm::countr_zero(parts[i]);
2419 return lsb + i * APINT_BITS_PER_WORD;
2420 }
2421 }
2422
2423 return UINT_MAX;
2424}
2425
2426/// Returns the bit number of the most significant set bit of a number.
2427/// If the input number has no bits set UINT_MAX is returned.
2428unsigned APInt::tcMSB(const WordType *parts, unsigned n) {
2429 do {
2430 --n;
2431
2432 if (parts[n] != 0) {
2433 static_assert(sizeof(parts[n]) <= sizeof(uint64_t));
2434 unsigned msb = llvm::Log2_64(parts[n]);
2435
2436 return msb + n * APINT_BITS_PER_WORD;
2437 }
2438 } while (n);
2439
2440 return UINT_MAX;
2441}
2442
2443/// Copy the bit vector of width srcBITS from SRC, starting at bit srcLSB, to
2444/// DST, of dstCOUNT parts, such that the bit srcLSB becomes the least
2445/// significant bit of DST. All high bits above srcBITS in DST are zero-filled.
2446/// */
2447void
2448APInt::tcExtract(WordType *dst, unsigned dstCount, const WordType *src,
2449 unsigned srcBits, unsigned srcLSB) {
2450 unsigned dstParts = (srcBits + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
2451 assert(dstParts <= dstCount);
2452
2453 unsigned firstSrcPart = srcLSB / APINT_BITS_PER_WORD;
2454 tcAssign(dst, src + firstSrcPart, dstParts);
2455
2456 unsigned shift = srcLSB % APINT_BITS_PER_WORD;
2457 tcShiftRight(dst, dstParts, shift);
2458
2459 // We now have (dstParts * APINT_BITS_PER_WORD - shift) bits from SRC
2460 // in DST. If this is less that srcBits, append the rest, else
2461 // clear the high bits.
2462 unsigned n = dstParts * APINT_BITS_PER_WORD - shift;
2463 if (n < srcBits) {
2464 WordType mask = lowBitMask (srcBits - n);
2465 dst[dstParts - 1] |= ((src[firstSrcPart + dstParts] & mask)
2466 << n % APINT_BITS_PER_WORD);
2467 } else if (n > srcBits) {
2468 if (srcBits % APINT_BITS_PER_WORD)
2469 dst[dstParts - 1] &= lowBitMask (srcBits % APINT_BITS_PER_WORD);
2470 }
2471
2472 // Clear high parts.
2473 while (dstParts < dstCount)
2474 dst[dstParts++] = 0;
2475}
2476
2477//// DST += RHS + C where C is zero or one. Returns the carry flag.
2479 WordType c, unsigned parts) {
2480 assert(c <= 1);
2481
2482 for (unsigned i = 0; i < parts; i++) {
2483 WordType l = dst[i];
2484 if (c) {
2485 dst[i] += rhs[i] + 1;
2486 c = (dst[i] <= l);
2487 } else {
2488 dst[i] += rhs[i];
2489 c = (dst[i] < l);
2490 }
2491 }
2492
2493 return c;
2494}
2495
2496/// This function adds a single "word" integer, src, to the multiple
2497/// "word" integer array, dst[]. dst[] is modified to reflect the addition and
2498/// 1 is returned if there is a carry out, otherwise 0 is returned.
2499/// @returns the carry of the addition.
2501 unsigned parts) {
2502 for (unsigned i = 0; i < parts; ++i) {
2503 dst[i] += src;
2504 if (dst[i] >= src)
2505 return 0; // No need to carry so exit early.
2506 src = 1; // Carry one to next digit.
2507 }
2508
2509 return 1;
2510}
2511
2512/// DST -= RHS + C where C is zero or one. Returns the carry flag.
2514 WordType c, unsigned parts) {
2515 assert(c <= 1);
2516
2517 for (unsigned i = 0; i < parts; i++) {
2518 WordType l = dst[i];
2519 if (c) {
2520 dst[i] -= rhs[i] + 1;
2521 c = (dst[i] >= l);
2522 } else {
2523 dst[i] -= rhs[i];
2524 c = (dst[i] > l);
2525 }
2526 }
2527
2528 return c;
2529}
2530
2531/// This function subtracts a single "word" (64-bit word), src, from
2532/// the multi-word integer array, dst[], propagating the borrowed 1 value until
2533/// no further borrowing is needed or it runs out of "words" in dst. The result
2534/// is 1 if "borrowing" exhausted the digits in dst, or 0 if dst was not
2535/// exhausted. In other words, if src > dst then this function returns 1,
2536/// otherwise 0.
2537/// @returns the borrow out of the subtraction
2539 unsigned parts) {
2540 for (unsigned i = 0; i < parts; ++i) {
2541 WordType Dst = dst[i];
2542 dst[i] -= src;
2543 if (src <= Dst)
2544 return 0; // No need to borrow so exit early.
2545 src = 1; // We have to "borrow 1" from next "word"
2546 }
2547
2548 return 1;
2549}
2550
2551/// Negate a bignum in-place.
2552void APInt::tcNegate(WordType *dst, unsigned parts) {
2553 tcComplement(dst, parts);
2554 tcIncrement(dst, parts);
2555}
2556
2557/// DST += SRC * MULTIPLIER + CARRY if add is true
2558/// DST = SRC * MULTIPLIER + CARRY if add is false
2559/// Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC
2560/// they must start at the same point, i.e. DST == SRC.
2561/// If DSTPARTS == SRCPARTS + 1 no overflow occurs and zero is
2562/// returned. Otherwise DST is filled with the least significant
2563/// DSTPARTS parts of the result, and if all of the omitted higher
2564/// parts were zero return zero, otherwise overflow occurred and
2565/// return one.
2567 WordType multiplier, WordType carry,
2568 unsigned srcParts, unsigned dstParts,
2569 bool add) {
2570 // Otherwise our writes of DST kill our later reads of SRC.
2571 assert(dst <= src || dst >= src + srcParts);
2572 assert(dstParts <= srcParts + 1);
2573
2574 // N loops; minimum of dstParts and srcParts.
2575 unsigned n = std::min(dstParts, srcParts);
2576
2577 for (unsigned i = 0; i < n; i++) {
2578 // [LOW, HIGH] = MULTIPLIER * SRC[i] + DST[i] + CARRY.
2579 // This cannot overflow, because:
2580 // (n - 1) * (n - 1) + 2 (n - 1) = (n - 1) * (n + 1)
2581 // which is less than n^2.
2582 WordType srcPart = src[i];
2583 WordType low, mid, high;
2584 if (multiplier == 0 || srcPart == 0) {
2585 low = carry;
2586 high = 0;
2587 } else {
2588 low = lowHalf(srcPart) * lowHalf(multiplier);
2589 high = highHalf(srcPart) * highHalf(multiplier);
2590
2591 mid = lowHalf(srcPart) * highHalf(multiplier);
2592 high += highHalf(mid);
2593 mid <<= APINT_BITS_PER_WORD / 2;
2594 if (low + mid < low)
2595 high++;
2596 low += mid;
2597
2598 mid = highHalf(srcPart) * lowHalf(multiplier);
2599 high += highHalf(mid);
2600 mid <<= APINT_BITS_PER_WORD / 2;
2601 if (low + mid < low)
2602 high++;
2603 low += mid;
2604
2605 // Now add carry.
2606 if (low + carry < low)
2607 high++;
2608 low += carry;
2609 }
2610
2611 if (add) {
2612 // And now DST[i], and store the new low part there.
2613 if (low + dst[i] < low)
2614 high++;
2615 dst[i] += low;
2616 } else {
2617 dst[i] = low;
2618 }
2619
2620 carry = high;
2621 }
2622
2623 if (srcParts < dstParts) {
2624 // Full multiplication, there is no overflow.
2625 assert(srcParts + 1 == dstParts);
2626 dst[srcParts] = carry;
2627 return 0;
2628 }
2629
2630 // We overflowed if there is carry.
2631 if (carry)
2632 return 1;
2633
2634 // We would overflow if any significant unwritten parts would be
2635 // non-zero. This is true if any remaining src parts are non-zero
2636 // and the multiplier is non-zero.
2637 if (multiplier)
2638 for (unsigned i = dstParts; i < srcParts; i++)
2639 if (src[i])
2640 return 1;
2641
2642 // We fitted in the narrow destination.
2643 return 0;
2644}
2645
2646/// DST = LHS * RHS, where DST has the same width as the operands and
2647/// is filled with the least significant parts of the result. Returns
2648/// one if overflow occurred, otherwise zero. DST must be disjoint
2649/// from both operands.
2651 const WordType *rhs, unsigned parts) {
2652 assert(dst != lhs && dst != rhs);
2653
2654 int overflow = 0;
2655
2656 for (unsigned i = 0; i < parts; i++) {
2657 // Don't accumulate on the first iteration so we don't need to initalize
2658 // dst to 0.
2659 overflow |=
2660 tcMultiplyPart(&dst[i], lhs, rhs[i], 0, parts, parts - i, i != 0);
2661 }
2662
2663 return overflow;
2664}
2665
2666/// DST = LHS * RHS, where DST has width the sum of the widths of the
2667/// operands. No overflow occurs. DST must be disjoint from both operands.
2669 const WordType *rhs, unsigned lhsParts,
2670 unsigned rhsParts) {
2671 // Put the narrower number on the LHS for less loops below.
2672 if (lhsParts > rhsParts)
2673 return tcFullMultiply (dst, rhs, lhs, rhsParts, lhsParts);
2674
2675 assert(dst != lhs && dst != rhs);
2676
2677 for (unsigned i = 0; i < lhsParts; i++) {
2678 // Don't accumulate on the first iteration so we don't need to initalize
2679 // dst to 0.
2680 tcMultiplyPart(&dst[i], rhs, lhs[i], 0, rhsParts, rhsParts + 1, i != 0);
2681 }
2682}
2683
2684// If RHS is zero LHS and REMAINDER are left unchanged, return one.
2685// Otherwise set LHS to LHS / RHS with the fractional part discarded,
2686// set REMAINDER to the remainder, return zero. i.e.
2687//
2688// OLD_LHS = RHS * LHS + REMAINDER
2689//
2690// SCRATCH is a bignum of the same size as the operands and result for
2691// use by the routine; its contents need not be initialized and are
2692// destroyed. LHS, REMAINDER and SCRATCH must be distinct.
2693int APInt::tcDivide(WordType *lhs, const WordType *rhs,
2694 WordType *remainder, WordType *srhs,
2695 unsigned parts) {
2696 assert(lhs != remainder && lhs != srhs && remainder != srhs);
2697
2698 unsigned shiftCount = tcMSB(rhs, parts) + 1;
2699 if (shiftCount == 0)
2700 return true;
2701
2702 shiftCount = parts * APINT_BITS_PER_WORD - shiftCount;
2703 unsigned n = shiftCount / APINT_BITS_PER_WORD;
2704 WordType mask = (WordType) 1 << (shiftCount % APINT_BITS_PER_WORD);
2705
2706 tcAssign(srhs, rhs, parts);
2707 tcShiftLeft(srhs, parts, shiftCount);
2708 tcAssign(remainder, lhs, parts);
2709 tcSet(lhs, 0, parts);
2710
2711 // Loop, subtracting SRHS if REMAINDER is greater and adding that to the
2712 // total.
2713 for (;;) {
2714 int compare = tcCompare(remainder, srhs, parts);
2715 if (compare >= 0) {
2716 tcSubtract(remainder, srhs, 0, parts);
2717 lhs[n] |= mask;
2718 }
2719
2720 if (shiftCount == 0)
2721 break;
2722 shiftCount--;
2723 tcShiftRight(srhs, parts, 1);
2724 if ((mask >>= 1) == 0) {
2725 mask = (WordType) 1 << (APINT_BITS_PER_WORD - 1);
2726 n--;
2727 }
2728 }
2729
2730 return false;
2731}
2732
2733/// Shift a bignum left Count bits in-place. Shifted in bits are zero. There are
2734/// no restrictions on Count.
2735void APInt::tcShiftLeft(WordType *Dst, unsigned Words, unsigned Count) {
2736 // Don't bother performing a no-op shift.
2737 if (!Count)
2738 return;
2739
2740 // WordShift is the inter-part shift; BitShift is the intra-part shift.
2741 unsigned WordShift = std::min(Count / APINT_BITS_PER_WORD, Words);
2742 unsigned BitShift = Count % APINT_BITS_PER_WORD;
2743
2744 // Fastpath for moving by whole words.
2745 if (BitShift == 0) {
2746 std::memmove(Dst + WordShift, Dst, (Words - WordShift) * APINT_WORD_SIZE);
2747 } else {
2748 while (Words-- > WordShift) {
2749 Dst[Words] = Dst[Words - WordShift] << BitShift;
2750 if (Words > WordShift)
2751 Dst[Words] |=
2752 Dst[Words - WordShift - 1] >> (APINT_BITS_PER_WORD - BitShift);
2753 }
2754 }
2755
2756 // Fill in the remainder with 0s.
2757 std::memset(Dst, 0, WordShift * APINT_WORD_SIZE);
2758}
2759
2760/// Shift a bignum right Count bits in-place. Shifted in bits are zero. There
2761/// are no restrictions on Count.
2762void APInt::tcShiftRight(WordType *Dst, unsigned Words, unsigned Count) {
2763 // Don't bother performing a no-op shift.
2764 if (!Count)
2765 return;
2766
2767 // WordShift is the inter-part shift; BitShift is the intra-part shift.
2768 unsigned WordShift = std::min(Count / APINT_BITS_PER_WORD, Words);
2769 unsigned BitShift = Count % APINT_BITS_PER_WORD;
2770
2771 unsigned WordsToMove = Words - WordShift;
2772 // Fastpath for moving by whole words.
2773 if (BitShift == 0) {
2774 std::memmove(Dst, Dst + WordShift, WordsToMove * APINT_WORD_SIZE);
2775 } else {
2776 for (unsigned i = 0; i != WordsToMove; ++i) {
2777 Dst[i] = Dst[i + WordShift] >> BitShift;
2778 if (i + 1 != WordsToMove)
2779 Dst[i] |= Dst[i + WordShift + 1] << (APINT_BITS_PER_WORD - BitShift);
2780 }
2781 }
2782
2783 // Fill in the remainder with 0s.
2784 std::memset(Dst + WordsToMove, 0, WordShift * APINT_WORD_SIZE);
2785}
2786
2787// Comparison (unsigned) of two bignums.
2788int APInt::tcCompare(const WordType *lhs, const WordType *rhs,
2789 unsigned parts) {
2790 while (parts) {
2791 parts--;
2792 if (lhs[parts] != rhs[parts])
2793 return (lhs[parts] > rhs[parts]) ? 1 : -1;
2794 }
2795
2796 return 0;
2797}
2798
2800 APInt::Rounding RM) {
2801 // Currently udivrem always rounds down.
2802 switch (RM) {
2805 return A.udiv(B);
2806 case APInt::Rounding::UP: {
2807 APInt Quo, Rem;
2808 APInt::udivrem(A, B, Quo, Rem);
2809 if (Rem.isZero())
2810 return Quo;
2811 return Quo + 1;
2812 }
2813 }
2814 llvm_unreachable("Unknown APInt::Rounding enum");
2815}
2816
2818 APInt::Rounding RM) {
2819 switch (RM) {
2821 case APInt::Rounding::UP: {
2822 APInt Quo, Rem;
2823 APInt::sdivrem(A, B, Quo, Rem);
2824 if (Rem.isZero())
2825 return Quo;
2826 // This algorithm deals with arbitrary rounding mode used by sdivrem.
2827 // We want to check whether the non-integer part of the mathematical value
2828 // is negative or not. If the non-integer part is negative, we need to round
2829 // down from Quo; otherwise, if it's positive or 0, we return Quo, as it's
2830 // already rounded down.
2831 if (RM == APInt::Rounding::DOWN) {
2832 if (Rem.isNegative() != B.isNegative())
2833 return Quo - 1;
2834 return Quo;
2835 }
2836 if (Rem.isNegative() != B.isNegative())
2837 return Quo;
2838 return Quo + 1;
2839 }
2840 // Currently sdiv rounds towards zero.
2842 return A.sdiv(B);
2843 }
2844 llvm_unreachable("Unknown APInt::Rounding enum");
2845}
2846
2847std::optional<APInt>
2849 unsigned RangeWidth) {
2850 unsigned CoeffWidth = A.getBitWidth();
2851 assert(CoeffWidth == B.getBitWidth() && CoeffWidth == C.getBitWidth());
2852 assert(RangeWidth <= CoeffWidth &&
2853 "Value range width should be less than coefficient width");
2854 assert(RangeWidth > 1 && "Value range bit width should be > 1");
2855
2856 LLVM_DEBUG(dbgs() << __func__ << ": solving " << A << "x^2 + " << B
2857 << "x + " << C << ", rw:" << RangeWidth << '\n');
2858
2859 // Identify 0 as a (non)solution immediately.
2860 if (C.sextOrTrunc(RangeWidth).isZero()) {
2861 LLVM_DEBUG(dbgs() << __func__ << ": zero solution\n");
2862 return APInt(CoeffWidth, 0);
2863 }
2864
2865 // The result of APInt arithmetic has the same bit width as the operands,
2866 // so it can actually lose high bits. A product of two n-bit integers needs
2867 // 2n-1 bits to represent the full value.
2868 // The operation done below (on quadratic coefficients) that can produce
2869 // the largest value is the evaluation of the equation during bisection,
2870 // which needs 3 times the bitwidth of the coefficient, so the total number
2871 // of required bits is 3n.
2872 //
2873 // The purpose of this extension is to simulate the set Z of all integers,
2874 // where n+1 > n for all n in Z. In Z it makes sense to talk about positive
2875 // and negative numbers (not so much in a modulo arithmetic). The method
2876 // used to solve the equation is based on the standard formula for real
2877 // numbers, and uses the concepts of "positive" and "negative" with their
2878 // usual meanings.
2879 CoeffWidth *= 3;
2880 A = A.sext(CoeffWidth);
2881 B = B.sext(CoeffWidth);
2882 C = C.sext(CoeffWidth);
2883
2884 // Make A > 0 for simplicity. Negate cannot overflow at this point because
2885 // the bit width has increased.
2886 if (A.isNegative()) {
2887 A.negate();
2888 B.negate();
2889 C.negate();
2890 }
2891
2892 // Solving an equation q(x) = 0 with coefficients in modular arithmetic
2893 // is really solving a set of equations q(x) = kR for k = 0, 1, 2, ...,
2894 // and R = 2^BitWidth.
2895 // Since we're trying not only to find exact solutions, but also values
2896 // that "wrap around", such a set will always have a solution, i.e. an x
2897 // that satisfies at least one of the equations, or such that |q(x)|
2898 // exceeds kR, while |q(x-1)| for the same k does not.
2899 //
2900 // We need to find a value k, such that Ax^2 + Bx + C = kR will have a
2901 // positive solution n (in the above sense), and also such that the n
2902 // will be the least among all solutions corresponding to k = 0, 1, ...
2903 // (more precisely, the least element in the set
2904 // { n(k) | k is such that a solution n(k) exists }).
2905 //
2906 // Consider the parabola (over real numbers) that corresponds to the
2907 // quadratic equation. Since A > 0, the arms of the parabola will point
2908 // up. Picking different values of k will shift it up and down by R.
2909 //
2910 // We want to shift the parabola in such a way as to reduce the problem
2911 // of solving q(x) = kR to solving shifted_q(x) = 0.
2912 // (The interesting solutions are the ceilings of the real number
2913 // solutions.)
2914 APInt R = APInt::getOneBitSet(CoeffWidth, RangeWidth);
2915 APInt TwoA = 2 * A;
2916 APInt SqrB = B * B;
2917 bool PickLow;
2918
2919 auto RoundUp = [] (const APInt &V, const APInt &A) -> APInt {
2920 assert(A.isStrictlyPositive());
2921 APInt T = V.abs().urem(A);
2922 if (T.isZero())
2923 return V;
2924 return V.isNegative() ? V+T : V+(A-T);
2925 };
2926
2927 // The vertex of the parabola is at -B/2A, but since A > 0, it's negative
2928 // iff B is positive.
2929 if (B.isNonNegative()) {
2930 // If B >= 0, the vertex it at a negative location (or at 0), so in
2931 // order to have a non-negative solution we need to pick k that makes
2932 // C-kR negative. To satisfy all the requirements for the solution
2933 // that we are looking for, it needs to be closest to 0 of all k.
2934 C = C.srem(R);
2935 if (C.isStrictlyPositive())
2936 C -= R;
2937 // Pick the greater solution.
2938 PickLow = false;
2939 } else {
2940 // If B < 0, the vertex is at a positive location. For any solution
2941 // to exist, the discriminant must be non-negative. This means that
2942 // C-kR <= B^2/4A is a necessary condition for k, i.e. there is a
2943 // lower bound on values of k: kR >= C - B^2/4A.
2944 APInt LowkR = C - SqrB.udiv(2*TwoA); // udiv because all values > 0.
2945 // Round LowkR up (towards +inf) to the nearest kR.
2946 LowkR = RoundUp(LowkR, R);
2947
2948 // If there exists k meeting the condition above, and such that
2949 // C-kR > 0, there will be two positive real number solutions of
2950 // q(x) = kR. Out of all such values of k, pick the one that makes
2951 // C-kR closest to 0, (i.e. pick maximum k such that C-kR > 0).
2952 // In other words, find maximum k such that LowkR <= kR < C.
2953 if (C.sgt(LowkR)) {
2954 // If LowkR < C, then such a k is guaranteed to exist because
2955 // LowkR itself is a multiple of R.
2956 C -= -RoundUp(-C, R); // C = C - RoundDown(C, R)
2957 // Pick the smaller solution.
2958 PickLow = true;
2959 } else {
2960 // If C-kR < 0 for all potential k's, it means that one solution
2961 // will be negative, while the other will be positive. The positive
2962 // solution will shift towards 0 if the parabola is moved up.
2963 // Pick the kR closest to the lower bound (i.e. make C-kR closest
2964 // to 0, or in other words, out of all parabolas that have solutions,
2965 // pick the one that is the farthest "up").
2966 // Since LowkR is itself a multiple of R, simply take C-LowkR.
2967 C -= LowkR;
2968 // Pick the greater solution.
2969 PickLow = false;
2970 }
2971 }
2972
2973 LLVM_DEBUG(dbgs() << __func__ << ": updated coefficients " << A << "x^2 + "
2974 << B << "x + " << C << ", rw:" << RangeWidth << '\n');
2975
2976 APInt D = SqrB - 4*A*C;
2977 assert(D.isNonNegative() && "Negative discriminant");
2978 APInt SQ = D.sqrtFloor();
2979
2980 APInt Q = SQ * SQ;
2981 bool InexactSQ = Q != D;
2982
2983 APInt X;
2984 APInt Rem;
2985
2986 // SQ is rounded down (i.e SQ * SQ <= D), so the roots may be inexact.
2987 // When using the quadratic formula directly, the calculated low root
2988 // may be greater than the exact one, since we would be subtracting SQ.
2989 // To make sure that the calculated root is not greater than the exact
2990 // one, subtract SQ+1 when calculating the low root (for inexact value
2991 // of SQ).
2992 if (PickLow)
2993 APInt::sdivrem(-B - (SQ+InexactSQ), TwoA, X, Rem);
2994 else
2995 APInt::sdivrem(-B + SQ, TwoA, X, Rem);
2996
2997 // The updated coefficients should be such that the (exact) solution is
2998 // positive. Since APInt division rounds towards 0, the calculated one
2999 // can be 0, but cannot be negative.
3000 assert(X.isNonNegative() && "Solution should be non-negative");
3001
3002 if (!InexactSQ && Rem.isZero()) {
3003 LLVM_DEBUG(dbgs() << __func__ << ": solution (root): " << X << '\n');
3004 return X;
3005 }
3006
3007 assert((SQ*SQ).sle(D) && "SQ = |_sqrt(D)_|, so SQ*SQ <= D");
3008 // The exact value of the square root of D should be between SQ and SQ+1.
3009 // This implies that the solution should be between that corresponding to
3010 // SQ (i.e. X) and that corresponding to SQ+1.
3011 //
3012 // The calculated X cannot be greater than the exact (real) solution.
3013 // Actually it must be strictly less than the exact solution, while
3014 // X+1 will be greater than or equal to it.
3015
3016 APInt VX = (A*X + B)*X + C;
3017 APInt VY = VX + TwoA*X + A + B;
3018 bool SignChange =
3019 VX.isNegative() != VY.isNegative() || VX.isZero() != VY.isZero();
3020 // If the sign did not change between X and X+1, X is not a valid solution.
3021 // This could happen when the actual (exact) roots don't have an integer
3022 // between them, so they would both be contained between X and X+1.
3023 if (!SignChange) {
3024 LLVM_DEBUG(dbgs() << __func__ << ": no valid solution\n");
3025 return std::nullopt;
3026 }
3027
3028 X += 1;
3029 LLVM_DEBUG(dbgs() << __func__ << ": solution (wrap): " << X << '\n');
3030 return X;
3031}
3032
3033std::optional<unsigned>
3035 assert(A.getBitWidth() == B.getBitWidth() && "Must have the same bitwidth");
3036 if (A == B)
3037 return std::nullopt;
3038 return A.getBitWidth() - ((A ^ B).countl_zero() + 1);
3039}
3040
3041APInt llvm::APIntOps::ScaleBitMask(const APInt &A, unsigned NewBitWidth,
3042 bool MatchAllBits) {
3043 unsigned OldBitWidth = A.getBitWidth();
3044 assert((((OldBitWidth % NewBitWidth) == 0) ||
3045 ((NewBitWidth % OldBitWidth) == 0)) &&
3046 "One size should be a multiple of the other one. "
3047 "Can't do fractional scaling.");
3048
3049 // Check for matching bitwidths.
3050 if (OldBitWidth == NewBitWidth)
3051 return A;
3052
3053 APInt NewA = APInt::getZero(NewBitWidth);
3054
3055 // Check for null input.
3056 if (A.isZero())
3057 return NewA;
3058
3059 if (NewBitWidth > OldBitWidth) {
3060 // Repeat bits.
3061 unsigned Scale = NewBitWidth / OldBitWidth;
3062 for (unsigned i = 0; i != OldBitWidth; ++i)
3063 if (A[i])
3064 NewA.setBits(i * Scale, (i + 1) * Scale);
3065 } else {
3066 unsigned Scale = OldBitWidth / NewBitWidth;
3067 for (unsigned i = 0; i != NewBitWidth; ++i) {
3068 if (MatchAllBits) {
3069 if (A.extractBits(Scale, i * Scale).isAllOnes())
3070 NewA.setBit(i);
3071 } else {
3072 if (!A.extractBits(Scale, i * Scale).isZero())
3073 NewA.setBit(i);
3074 }
3075 }
3076 }
3077
3078 return NewA;
3079}
3080
3081/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
3082/// with the integer held in IntVal.
3083void llvm::StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
3084 unsigned StoreBytes) {
3085 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
3086 const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
3087
3089 // Little-endian host - the source is ordered from LSB to MSB. Order the
3090 // destination from LSB to MSB: Do a straight copy.
3091 memcpy(Dst, Src, StoreBytes);
3092 } else {
3093 // Big-endian host - the source is an array of 64 bit words ordered from
3094 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
3095 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
3096 while (StoreBytes > sizeof(uint64_t)) {
3097 StoreBytes -= sizeof(uint64_t);
3098 // May not be aligned so use memcpy.
3099 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
3100 Src += sizeof(uint64_t);
3101 }
3102
3103 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
3104 }
3105}
3106
3107/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
3108/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
3109void llvm::LoadIntFromMemory(APInt &IntVal, const uint8_t *Src,
3110 unsigned LoadBytes) {
3111 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
3112 uint8_t *Dst = reinterpret_cast<uint8_t *>(
3113 const_cast<uint64_t *>(IntVal.getRawData()));
3114
3116 // Little-endian host - the destination must be ordered from LSB to MSB.
3117 // The source is ordered from LSB to MSB: Do a straight copy.
3118 memcpy(Dst, Src, LoadBytes);
3119 else {
3120 // Big-endian - the destination is an array of 64 bit words ordered from
3121 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
3122 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
3123 // a word.
3124 while (LoadBytes > sizeof(uint64_t)) {
3125 LoadBytes -= sizeof(uint64_t);
3126 // May not be aligned so use memcpy.
3127 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
3128 Dst += sizeof(uint64_t);
3129 }
3130
3131 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
3132 }
3133}
3134
3135APInt APIntOps::avgFloorS(const APInt &C1, const APInt &C2) {
3136 // Return floor((C1 + C2) / 2)
3137 return (C1 & C2) + (C1 ^ C2).ashr(1);
3138}
3139
3140APInt APIntOps::avgFloorU(const APInt &C1, const APInt &C2) {
3141 // Return floor((C1 + C2) / 2)
3142 return (C1 & C2) + (C1 ^ C2).lshr(1);
3143}
3144
3145APInt APIntOps::avgCeilS(const APInt &C1, const APInt &C2) {
3146 // Return ceil((C1 + C2) / 2)
3147 return (C1 | C2) - (C1 ^ C2).ashr(1);
3148}
3149
3150APInt APIntOps::avgCeilU(const APInt &C1, const APInt &C2) {
3151 // Return ceil((C1 + C2) / 2)
3152 return (C1 | C2) - (C1 ^ C2).lshr(1);
3153}
3154
3155APInt APIntOps::mulhs(const APInt &C1, const APInt &C2) {
3156 assert(C1.getBitWidth() == C2.getBitWidth() && "Unequal bitwidths");
3157 unsigned FullWidth = C1.getBitWidth() * 2;
3158 APInt C1Ext = C1.sext(FullWidth);
3159 APInt C2Ext = C2.sext(FullWidth);
3160 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
3161}
3162
3163APInt APIntOps::mulhu(const APInt &C1, const APInt &C2) {
3164 assert(C1.getBitWidth() == C2.getBitWidth() && "Unequal bitwidths");
3165 unsigned FullWidth = C1.getBitWidth() * 2;
3166 APInt C1Ext = C1.zext(FullWidth);
3167 APInt C2Ext = C2.zext(FullWidth);
3168 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
3169}
3170
3172 assert(C1.getBitWidth() == C2.getBitWidth() && "Unequal bitwidths");
3173 unsigned FullWidth = C1.getBitWidth() * 2;
3174 APInt C1Ext = C1.sext(FullWidth);
3175 APInt C2Ext = C2.sext(FullWidth);
3176 return C1Ext * C2Ext;
3177}
3178
3180 assert(C1.getBitWidth() == C2.getBitWidth() && "Unequal bitwidths");
3181 unsigned FullWidth = C1.getBitWidth() * 2;
3182 APInt C1Ext = C1.zext(FullWidth);
3183 APInt C2Ext = C2.zext(FullWidth);
3184 return C1Ext * C2Ext;
3185}
3186
3187APInt APIntOps::pow(const APInt &X, int64_t N) {
3188 assert(N >= 0 && "negative exponents not supported.");
3189 APInt Acc = APInt(X.getBitWidth(), 1);
3190 if (N == 0)
3191 return Acc;
3192 APInt Base = X;
3193 int64_t RemainingExponent = N;
3194 while (RemainingExponent > 0) {
3195 while (RemainingExponent % 2 == 0) {
3196 Base *= Base;
3197 RemainingExponent /= 2;
3198 }
3199 --RemainingExponent;
3200 Acc *= Base;
3201 }
3202 return Acc;
3203}
3204
3206 const APInt &Shift) {
3207 assert(Hi.getBitWidth() == Lo.getBitWidth());
3208 unsigned ShiftAmt = rotateModulo(Hi.getBitWidth(), Shift);
3209 if (ShiftAmt == 0)
3210 return Hi;
3211 return Hi.shl(ShiftAmt) | Lo.lshr(Hi.getBitWidth() - ShiftAmt);
3212}
3213
3215 const APInt &Shift) {
3216 assert(Hi.getBitWidth() == Lo.getBitWidth());
3217 unsigned ShiftAmt = rotateModulo(Hi.getBitWidth(), Shift);
3218 if (ShiftAmt == 0)
3219 return Lo;
3220 return Hi.shl(Hi.getBitWidth() - ShiftAmt) | Lo.lshr(ShiftAmt);
3221}
3222
3223APInt llvm::APIntOps::clmul(const APInt &LHS, const APInt &RHS) {
3224 unsigned BW = LHS.getBitWidth();
3225 assert(BW == RHS.getBitWidth() && "Operand mismatch");
3226 APInt Result(BW, 0);
3227 for (unsigned I : seq(std::min(RHS.getActiveBits(), BW - LHS.countr_zero())))
3228 if (RHS[I])
3229 Result ^= LHS << I;
3230 return Result;
3231}
3232
3233APInt llvm::APIntOps::clmulr(const APInt &LHS, const APInt &RHS) {
3234 assert(LHS.getBitWidth() == RHS.getBitWidth());
3235 return clmul(LHS.reverseBits(), RHS.reverseBits()).reverseBits();
3236}
3237
3238APInt llvm::APIntOps::clmulh(const APInt &LHS, const APInt &RHS) {
3239 assert(LHS.getBitWidth() == RHS.getBitWidth());
3240 return clmulr(LHS, RHS).lshr(1);
3241}
3242
3243APInt llvm::APIntOps::pext(const APInt &Val, const APInt &Mask) {
3244 unsigned BW = Val.getBitWidth();
3245 assert(BW == Mask.getBitWidth() && "Operand mismatch");
3246 APInt Result = APInt::getZero(BW);
3247 for (unsigned I = 0, P = 0; I != BW; ++I)
3248 if (Mask[I])
3249 Result.setBitVal(P++, Val[I]);
3250 return Result;
3251}
3252
3253APInt llvm::APIntOps::pdep(const APInt &Val, const APInt &Mask) {
3254 unsigned BW = Val.getBitWidth();
3255 assert(BW == Mask.getBitWidth() && "Operand mismatch");
3256 APInt Result = APInt::getZero(BW);
3257 for (unsigned I = 0, P = 0; I != BW; ++I)
3258 if (Mask[I])
3259 Result.setBitVal(I, Val[P++]);
3260 return Result;
3261}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
static APInt::WordType lowHalf(APInt::WordType part)
Returns the value of the lower half of PART.
Definition APInt.cpp:2365
static unsigned rotateModulo(unsigned BitWidth, const APInt &rotateAmt)
Definition APInt.cpp:1167
static APInt::WordType highHalf(APInt::WordType part)
Returns the value of the upper half of PART.
Definition APInt.cpp:2370
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:2359
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:1317
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:857
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:2007
LLVM_ABI APInt usub_sat(const APInt &RHS) const
Definition APInt.cpp:2091
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1600
static LLVM_ABI void tcSetBit(WordType *, unsigned bit)
Set the given bit of a bignum. Zero-based.
Definition APInt.cpp:2404
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:2376
LLVM_ABI unsigned nearestLogBase2() const
Definition APInt.cpp:1216
static LLVM_ABI void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Dual division/remainder interface.
Definition APInt.cpp:1794
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:2399
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:1056
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:995
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:1926
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:2478
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:2448
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:1077
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:969
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:2024
LLVM_ABI APInt smul_sat(const APInt &RHS) const
Definition APInt.cpp:2100
LLVM_ABI APInt sadd_sat(const APInt &RHS) const
Definition APInt.cpp:2062
static LLVM_ABI int tcCompare(const WordType *, const WordType *, unsigned)
Comparison (unsigned) of two bignums.
Definition APInt.cpp:2788
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:1984
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:2343
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:1693
uint64_t WordType
Definition APInt.h:80
static LLVM_ABI void tcAssign(WordType *, const WordType *, unsigned)
Assign one bignum to another.
Definition APInt.cpp:2384
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:2762
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:2668
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:2055
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:1964
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:1671
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:1198
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:1971
static LLVM_ABI void tcClearBit(WordType *, unsigned bit)
Clear the given bit of a bignum. Zero-based.
Definition APInt.cpp:2409
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:1018
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:1990
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:2415
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:2735
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:2122
LLVM_ABI APInt sqrtFloor() const
Compute the floor of the square root of the unsigned value.
Definition APInt.cpp:1243
static constexpr WordType WORDTYPE_MAX
Definition APInt.h:94
LLVM_ABI APInt ushl_sat(const APInt &RHS) const
Definition APInt.cpp:2136
LLVM_ABI APInt ushl_ov(const APInt &Amt, bool &Overflow) const
Definition APInt.cpp:2041
static LLVM_ABI WordType tcSubtractPart(WordType *, WordType, unsigned)
DST -= RHS. Returns the carry flag.
Definition APInt.cpp:2538
static LLVM_ABI bool tcIsZero(const WordType *, unsigned)
Returns true if a bignum is zero, false otherwise.
Definition APInt.cpp:2390
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition APInt.cpp:1085
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:2428
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:2693
LLVM_DUMP_METHOD void dump() const
debug method
Definition APInt.cpp:2334
LLVM_ABI APInt rotl(unsigned rotateAmt) const
Rotate left by rotateAmt.
Definition APInt.cpp:1185
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:2566
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:2650
LLVM_ABI APInt uadd_sat(const APInt &RHS) const
Definition APInt.cpp:2072
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:2513
LLVM_ABI APInt multiplicativeInverse() const
Definition APInt.cpp:1301
static LLVM_ABI void tcNegate(WordType *, unsigned)
Negate a bignum in-place.
Definition APInt.cpp:2552
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:1772
LLVM_ABI APInt smul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1996
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:1029
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:2113
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:2500
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:1977
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:2081
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:1006
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:2200
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:211
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:3034
LLVM_ABI APInt clmulr(const APInt &LHS, const APInt &RHS)
Perform a reversed carry-less multiply.
Definition APInt.cpp:3233
LLVM_ABI APInt mulhu(const APInt &C1, const APInt &C2)
Performs (2*N)-bit multiplication on zero-extended operands.
Definition APInt.cpp:3163
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:2799
LLVM_ABI APInt avgCeilU(const APInt &C1, const APInt &C2)
Compute the ceil of the unsigned average of C1 and C2.
Definition APInt.cpp:3150
LLVM_ABI APInt muluExtended(const APInt &C1, const APInt &C2)
Performs (2*N)-bit multiplication on zero-extended operands.
Definition APInt.cpp:3179
LLVM_ABI APInt mulsExtended(const APInt &C1, const APInt &C2)
Performs (2*N)-bit multiplication on sign-extended operands.
Definition APInt.cpp:3171
LLVM_ABI APInt avgFloorU(const APInt &C1, const APInt &C2)
Compute the floor of the unsigned average of C1 and C2.
Definition APInt.cpp:3140
LLVM_ABI APInt pext(const APInt &Val, const APInt &Mask)
Perform a "compress" operation, also known as pext or bext.
Definition APInt.cpp:3243
LLVM_ABI APInt fshr(const APInt &Hi, const APInt &Lo, const APInt &Shift)
Perform a funnel shift right.
Definition APInt.cpp:3214
LLVM_ABI APInt mulhs(const APInt &C1, const APInt &C2)
Performs (2*N)-bit multiplication on sign-extended operands.
Definition APInt.cpp:3155
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:2817
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:3223
LLVM_ABI APInt pow(const APInt &X, int64_t N)
Compute X^N for N>=0.
Definition APInt.cpp:3187
LLVM_ABI APInt pdep(const APInt &Val, const APInt &Mask)
Perform an "expand" operation, also known as pdep or bdep.
Definition APInt.cpp:3253
LLVM_ABI APInt RoundDoubleToAPInt(double Double, unsigned width)
Converts the given double value into a APInt.
Definition APInt.cpp:874
LLVM_ABI APInt fshl(const APInt &Hi, const APInt &Lo, const APInt &Shift)
Perform a funnel shift left.
Definition APInt.cpp:3205
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:3041
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:2848
LLVM_ABI APInt clmulh(const APInt &LHS, const APInt &RHS)
Perform a carry-less multiply, and return high-bits.
Definition APInt.cpp:3238
LLVM_ABI APInt GreatestCommonDivisor(APInt A, APInt B, bool IsSigned=false)
Compute GCD of two APInt values.
Definition APInt.cpp:825
LLVM_ABI APInt avgFloorS(const APInt &C1, const APInt &C2)
Compute the floor of the signed average of C1 and C2.
Definition APInt.cpp:3135
LLVM_ABI APInt avgCeilS(const APInt &C1, const APInt &C2)
Compute the ceil of the signed average of C1 and C2.
Definition APInt.cpp:3145
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:3083
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:332
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:6165
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:567
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:3109
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...