xref: /freebsd-src/contrib/llvm-project/llvm/lib/Support/APInt.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
10b57cec5SDimitry Andric //===-- APInt.cpp - Implement APInt class ---------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file implements a class to represent arbitrary precision integer
100b57cec5SDimitry Andric // constant values and provide a variety of arithmetic operations on them.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
130b57cec5SDimitry Andric 
140b57cec5SDimitry Andric #include "llvm/ADT/APInt.h"
150b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
160b57cec5SDimitry Andric #include "llvm/ADT/FoldingSet.h"
170b57cec5SDimitry Andric #include "llvm/ADT/Hashing.h"
180b57cec5SDimitry Andric #include "llvm/ADT/SmallString.h"
190b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
200b57cec5SDimitry Andric #include "llvm/ADT/bit.h"
210b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h"
2206c3fb27SDimitry Andric #include "llvm/Support/Alignment.h"
230b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
240b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
250b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
260b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
270b57cec5SDimitry Andric #include <cmath>
28bdd1243dSDimitry Andric #include <optional>
29bdd1243dSDimitry Andric 
300b57cec5SDimitry Andric using namespace llvm;
310b57cec5SDimitry Andric 
320b57cec5SDimitry Andric #define DEBUG_TYPE "apint"
330b57cec5SDimitry Andric 
340b57cec5SDimitry Andric /// A utility function for allocating memory, checking for allocation failures,
350b57cec5SDimitry Andric /// and ensuring the contents are zeroed.
360b57cec5SDimitry Andric inline static uint64_t* getClearedMemory(unsigned numWords) {
370b57cec5SDimitry Andric   uint64_t *result = new uint64_t[numWords];
380b57cec5SDimitry Andric   memset(result, 0, numWords * sizeof(uint64_t));
390b57cec5SDimitry Andric   return result;
400b57cec5SDimitry Andric }
410b57cec5SDimitry Andric 
420b57cec5SDimitry Andric /// A utility function for allocating memory and checking for allocation
430b57cec5SDimitry Andric /// failure.  The content is not zeroed.
440b57cec5SDimitry Andric inline static uint64_t* getMemory(unsigned numWords) {
450b57cec5SDimitry Andric   return new uint64_t[numWords];
460b57cec5SDimitry Andric }
470b57cec5SDimitry Andric 
480b57cec5SDimitry Andric /// A utility function that converts a character to a digit.
490b57cec5SDimitry Andric inline static unsigned getDigit(char cdigit, uint8_t radix) {
500b57cec5SDimitry Andric   unsigned r;
510b57cec5SDimitry Andric 
520b57cec5SDimitry Andric   if (radix == 16 || radix == 36) {
530b57cec5SDimitry Andric     r = cdigit - '0';
540b57cec5SDimitry Andric     if (r <= 9)
550b57cec5SDimitry Andric       return r;
560b57cec5SDimitry Andric 
570b57cec5SDimitry Andric     r = cdigit - 'A';
580b57cec5SDimitry Andric     if (r <= radix - 11U)
590b57cec5SDimitry Andric       return r + 10;
600b57cec5SDimitry Andric 
610b57cec5SDimitry Andric     r = cdigit - 'a';
620b57cec5SDimitry Andric     if (r <= radix - 11U)
630b57cec5SDimitry Andric       return r + 10;
640b57cec5SDimitry Andric 
650b57cec5SDimitry Andric     radix = 10;
660b57cec5SDimitry Andric   }
670b57cec5SDimitry Andric 
680b57cec5SDimitry Andric   r = cdigit - '0';
690b57cec5SDimitry Andric   if (r < radix)
700b57cec5SDimitry Andric     return r;
710b57cec5SDimitry Andric 
7206c3fb27SDimitry Andric   return UINT_MAX;
730b57cec5SDimitry Andric }
740b57cec5SDimitry Andric 
750b57cec5SDimitry Andric 
760b57cec5SDimitry Andric void APInt::initSlowCase(uint64_t val, bool isSigned) {
770b57cec5SDimitry Andric   U.pVal = getClearedMemory(getNumWords());
780b57cec5SDimitry Andric   U.pVal[0] = val;
790b57cec5SDimitry Andric   if (isSigned && int64_t(val) < 0)
800b57cec5SDimitry Andric     for (unsigned i = 1; i < getNumWords(); ++i)
810b57cec5SDimitry Andric       U.pVal[i] = WORDTYPE_MAX;
820b57cec5SDimitry Andric   clearUnusedBits();
830b57cec5SDimitry Andric }
840b57cec5SDimitry Andric 
850b57cec5SDimitry Andric void APInt::initSlowCase(const APInt& that) {
860b57cec5SDimitry Andric   U.pVal = getMemory(getNumWords());
870b57cec5SDimitry Andric   memcpy(U.pVal, that.U.pVal, getNumWords() * APINT_WORD_SIZE);
880b57cec5SDimitry Andric }
890b57cec5SDimitry Andric 
900b57cec5SDimitry Andric void APInt::initFromArray(ArrayRef<uint64_t> bigVal) {
910b57cec5SDimitry Andric   assert(bigVal.data() && "Null pointer detected!");
920b57cec5SDimitry Andric   if (isSingleWord())
930b57cec5SDimitry Andric     U.VAL = bigVal[0];
940b57cec5SDimitry Andric   else {
950b57cec5SDimitry Andric     // Get memory, cleared to 0
960b57cec5SDimitry Andric     U.pVal = getClearedMemory(getNumWords());
970b57cec5SDimitry Andric     // Calculate the number of words to copy
980b57cec5SDimitry Andric     unsigned words = std::min<unsigned>(bigVal.size(), getNumWords());
990b57cec5SDimitry Andric     // Copy the words from bigVal to pVal
1000b57cec5SDimitry Andric     memcpy(U.pVal, bigVal.data(), words * APINT_WORD_SIZE);
1010b57cec5SDimitry Andric   }
1020b57cec5SDimitry Andric   // Make sure unused high bits are cleared
1030b57cec5SDimitry Andric   clearUnusedBits();
1040b57cec5SDimitry Andric }
1050b57cec5SDimitry Andric 
106349cc55cSDimitry Andric APInt::APInt(unsigned numBits, ArrayRef<uint64_t> bigVal) : BitWidth(numBits) {
1070b57cec5SDimitry Andric   initFromArray(bigVal);
1080b57cec5SDimitry Andric }
1090b57cec5SDimitry Andric 
1100b57cec5SDimitry Andric APInt::APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[])
1110b57cec5SDimitry Andric     : BitWidth(numBits) {
112bdd1243dSDimitry Andric   initFromArray(ArrayRef(bigVal, numWords));
1130b57cec5SDimitry Andric }
1140b57cec5SDimitry Andric 
1150b57cec5SDimitry Andric APInt::APInt(unsigned numbits, StringRef Str, uint8_t radix)
1160b57cec5SDimitry Andric     : BitWidth(numbits) {
1170b57cec5SDimitry Andric   fromString(numbits, Str, radix);
1180b57cec5SDimitry Andric }
1190b57cec5SDimitry Andric 
1200b57cec5SDimitry Andric void APInt::reallocate(unsigned NewBitWidth) {
1210b57cec5SDimitry Andric   // If the number of words is the same we can just change the width and stop.
1220b57cec5SDimitry Andric   if (getNumWords() == getNumWords(NewBitWidth)) {
1230b57cec5SDimitry Andric     BitWidth = NewBitWidth;
1240b57cec5SDimitry Andric     return;
1250b57cec5SDimitry Andric   }
1260b57cec5SDimitry Andric 
1270b57cec5SDimitry Andric   // If we have an allocation, delete it.
1280b57cec5SDimitry Andric   if (!isSingleWord())
1290b57cec5SDimitry Andric     delete [] U.pVal;
1300b57cec5SDimitry Andric 
1310b57cec5SDimitry Andric   // Update BitWidth.
1320b57cec5SDimitry Andric   BitWidth = NewBitWidth;
1330b57cec5SDimitry Andric 
1340b57cec5SDimitry Andric   // If we are supposed to have an allocation, create it.
1350b57cec5SDimitry Andric   if (!isSingleWord())
1360b57cec5SDimitry Andric     U.pVal = getMemory(getNumWords());
1370b57cec5SDimitry Andric }
1380b57cec5SDimitry Andric 
139349cc55cSDimitry Andric void APInt::assignSlowCase(const APInt &RHS) {
1400b57cec5SDimitry Andric   // Don't do anything for X = X
1410b57cec5SDimitry Andric   if (this == &RHS)
1420b57cec5SDimitry Andric     return;
1430b57cec5SDimitry Andric 
1440b57cec5SDimitry Andric   // Adjust the bit width and handle allocations as necessary.
1450b57cec5SDimitry Andric   reallocate(RHS.getBitWidth());
1460b57cec5SDimitry Andric 
1470b57cec5SDimitry Andric   // Copy the data.
1480b57cec5SDimitry Andric   if (isSingleWord())
1490b57cec5SDimitry Andric     U.VAL = RHS.U.VAL;
1500b57cec5SDimitry Andric   else
1510b57cec5SDimitry Andric     memcpy(U.pVal, RHS.U.pVal, getNumWords() * APINT_WORD_SIZE);
1520b57cec5SDimitry Andric }
1530b57cec5SDimitry Andric 
1540b57cec5SDimitry Andric /// This method 'profiles' an APInt for use with FoldingSet.
1550b57cec5SDimitry Andric void APInt::Profile(FoldingSetNodeID& ID) const {
1560b57cec5SDimitry Andric   ID.AddInteger(BitWidth);
1570b57cec5SDimitry Andric 
1580b57cec5SDimitry Andric   if (isSingleWord()) {
1590b57cec5SDimitry Andric     ID.AddInteger(U.VAL);
1600b57cec5SDimitry Andric     return;
1610b57cec5SDimitry Andric   }
1620b57cec5SDimitry Andric 
1630b57cec5SDimitry Andric   unsigned NumWords = getNumWords();
1640b57cec5SDimitry Andric   for (unsigned i = 0; i < NumWords; ++i)
1650b57cec5SDimitry Andric     ID.AddInteger(U.pVal[i]);
1660b57cec5SDimitry Andric }
1670b57cec5SDimitry Andric 
16806c3fb27SDimitry Andric bool APInt::isAligned(Align A) const {
16906c3fb27SDimitry Andric   if (isZero())
17006c3fb27SDimitry Andric     return true;
17106c3fb27SDimitry Andric   const unsigned TrailingZeroes = countr_zero();
17206c3fb27SDimitry Andric   const unsigned MinimumTrailingZeroes = Log2(A);
17306c3fb27SDimitry Andric   return TrailingZeroes >= MinimumTrailingZeroes;
17406c3fb27SDimitry Andric }
17506c3fb27SDimitry Andric 
1760b57cec5SDimitry Andric /// Prefix increment operator. Increments the APInt by one.
1770b57cec5SDimitry Andric APInt& APInt::operator++() {
1780b57cec5SDimitry Andric   if (isSingleWord())
1790b57cec5SDimitry Andric     ++U.VAL;
1800b57cec5SDimitry Andric   else
1810b57cec5SDimitry Andric     tcIncrement(U.pVal, getNumWords());
1820b57cec5SDimitry Andric   return clearUnusedBits();
1830b57cec5SDimitry Andric }
1840b57cec5SDimitry Andric 
1850b57cec5SDimitry Andric /// Prefix decrement operator. Decrements the APInt by one.
1860b57cec5SDimitry Andric APInt& APInt::operator--() {
1870b57cec5SDimitry Andric   if (isSingleWord())
1880b57cec5SDimitry Andric     --U.VAL;
1890b57cec5SDimitry Andric   else
1900b57cec5SDimitry Andric     tcDecrement(U.pVal, getNumWords());
1910b57cec5SDimitry Andric   return clearUnusedBits();
1920b57cec5SDimitry Andric }
1930b57cec5SDimitry Andric 
194480093f4SDimitry Andric /// Adds the RHS APInt to this APInt.
1950b57cec5SDimitry Andric /// @returns this, after addition of RHS.
1960b57cec5SDimitry Andric /// Addition assignment operator.
1970b57cec5SDimitry Andric APInt& APInt::operator+=(const APInt& RHS) {
1980b57cec5SDimitry Andric   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1990b57cec5SDimitry Andric   if (isSingleWord())
2000b57cec5SDimitry Andric     U.VAL += RHS.U.VAL;
2010b57cec5SDimitry Andric   else
2020b57cec5SDimitry Andric     tcAdd(U.pVal, RHS.U.pVal, 0, getNumWords());
2030b57cec5SDimitry Andric   return clearUnusedBits();
2040b57cec5SDimitry Andric }
2050b57cec5SDimitry Andric 
2060b57cec5SDimitry Andric APInt& APInt::operator+=(uint64_t RHS) {
2070b57cec5SDimitry Andric   if (isSingleWord())
2080b57cec5SDimitry Andric     U.VAL += RHS;
2090b57cec5SDimitry Andric   else
2100b57cec5SDimitry Andric     tcAddPart(U.pVal, RHS, getNumWords());
2110b57cec5SDimitry Andric   return clearUnusedBits();
2120b57cec5SDimitry Andric }
2130b57cec5SDimitry Andric 
2140b57cec5SDimitry Andric /// Subtracts the RHS APInt from this APInt
2150b57cec5SDimitry Andric /// @returns this, after subtraction
2160b57cec5SDimitry Andric /// Subtraction assignment operator.
2170b57cec5SDimitry Andric APInt& APInt::operator-=(const APInt& RHS) {
2180b57cec5SDimitry Andric   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
2190b57cec5SDimitry Andric   if (isSingleWord())
2200b57cec5SDimitry Andric     U.VAL -= RHS.U.VAL;
2210b57cec5SDimitry Andric   else
2220b57cec5SDimitry Andric     tcSubtract(U.pVal, RHS.U.pVal, 0, getNumWords());
2230b57cec5SDimitry Andric   return clearUnusedBits();
2240b57cec5SDimitry Andric }
2250b57cec5SDimitry Andric 
2260b57cec5SDimitry Andric APInt& APInt::operator-=(uint64_t RHS) {
2270b57cec5SDimitry Andric   if (isSingleWord())
2280b57cec5SDimitry Andric     U.VAL -= RHS;
2290b57cec5SDimitry Andric   else
2300b57cec5SDimitry Andric     tcSubtractPart(U.pVal, RHS, getNumWords());
2310b57cec5SDimitry Andric   return clearUnusedBits();
2320b57cec5SDimitry Andric }
2330b57cec5SDimitry Andric 
2340b57cec5SDimitry Andric APInt APInt::operator*(const APInt& RHS) const {
2350b57cec5SDimitry Andric   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
2360b57cec5SDimitry Andric   if (isSingleWord())
2370b57cec5SDimitry Andric     return APInt(BitWidth, U.VAL * RHS.U.VAL);
2380b57cec5SDimitry Andric 
2390b57cec5SDimitry Andric   APInt Result(getMemory(getNumWords()), getBitWidth());
2400b57cec5SDimitry Andric   tcMultiply(Result.U.pVal, U.pVal, RHS.U.pVal, getNumWords());
2410b57cec5SDimitry Andric   Result.clearUnusedBits();
2420b57cec5SDimitry Andric   return Result;
2430b57cec5SDimitry Andric }
2440b57cec5SDimitry Andric 
245349cc55cSDimitry Andric void APInt::andAssignSlowCase(const APInt &RHS) {
246349cc55cSDimitry Andric   WordType *dst = U.pVal, *rhs = RHS.U.pVal;
247349cc55cSDimitry Andric   for (size_t i = 0, e = getNumWords(); i != e; ++i)
248349cc55cSDimitry Andric     dst[i] &= rhs[i];
2490b57cec5SDimitry Andric }
2500b57cec5SDimitry Andric 
251349cc55cSDimitry Andric void APInt::orAssignSlowCase(const APInt &RHS) {
252349cc55cSDimitry Andric   WordType *dst = U.pVal, *rhs = RHS.U.pVal;
253349cc55cSDimitry Andric   for (size_t i = 0, e = getNumWords(); i != e; ++i)
254349cc55cSDimitry Andric     dst[i] |= rhs[i];
2550b57cec5SDimitry Andric }
2560b57cec5SDimitry Andric 
257349cc55cSDimitry Andric void APInt::xorAssignSlowCase(const APInt &RHS) {
258349cc55cSDimitry Andric   WordType *dst = U.pVal, *rhs = RHS.U.pVal;
259349cc55cSDimitry Andric   for (size_t i = 0, e = getNumWords(); i != e; ++i)
260349cc55cSDimitry Andric     dst[i] ^= rhs[i];
2610b57cec5SDimitry Andric }
2620b57cec5SDimitry Andric 
2630b57cec5SDimitry Andric APInt &APInt::operator*=(const APInt &RHS) {
2640b57cec5SDimitry Andric   *this = *this * RHS;
2650b57cec5SDimitry Andric   return *this;
2660b57cec5SDimitry Andric }
2670b57cec5SDimitry Andric 
2680b57cec5SDimitry Andric APInt& APInt::operator*=(uint64_t RHS) {
2690b57cec5SDimitry Andric   if (isSingleWord()) {
2700b57cec5SDimitry Andric     U.VAL *= RHS;
2710b57cec5SDimitry Andric   } else {
2720b57cec5SDimitry Andric     unsigned NumWords = getNumWords();
2730b57cec5SDimitry Andric     tcMultiplyPart(U.pVal, U.pVal, RHS, 0, NumWords, NumWords, false);
2740b57cec5SDimitry Andric   }
2750b57cec5SDimitry Andric   return clearUnusedBits();
2760b57cec5SDimitry Andric }
2770b57cec5SDimitry Andric 
278349cc55cSDimitry Andric bool APInt::equalSlowCase(const APInt &RHS) const {
2790b57cec5SDimitry Andric   return std::equal(U.pVal, U.pVal + getNumWords(), RHS.U.pVal);
2800b57cec5SDimitry Andric }
2810b57cec5SDimitry Andric 
2820b57cec5SDimitry Andric int APInt::compare(const APInt& RHS) const {
2830b57cec5SDimitry Andric   assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
2840b57cec5SDimitry Andric   if (isSingleWord())
2850b57cec5SDimitry Andric     return U.VAL < RHS.U.VAL ? -1 : U.VAL > RHS.U.VAL;
2860b57cec5SDimitry Andric 
2870b57cec5SDimitry Andric   return tcCompare(U.pVal, RHS.U.pVal, getNumWords());
2880b57cec5SDimitry Andric }
2890b57cec5SDimitry Andric 
2900b57cec5SDimitry Andric int APInt::compareSigned(const APInt& RHS) const {
2910b57cec5SDimitry Andric   assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
2920b57cec5SDimitry Andric   if (isSingleWord()) {
2930b57cec5SDimitry Andric     int64_t lhsSext = SignExtend64(U.VAL, BitWidth);
2940b57cec5SDimitry Andric     int64_t rhsSext = SignExtend64(RHS.U.VAL, BitWidth);
2950b57cec5SDimitry Andric     return lhsSext < rhsSext ? -1 : lhsSext > rhsSext;
2960b57cec5SDimitry Andric   }
2970b57cec5SDimitry Andric 
2980b57cec5SDimitry Andric   bool lhsNeg = isNegative();
2990b57cec5SDimitry Andric   bool rhsNeg = RHS.isNegative();
3000b57cec5SDimitry Andric 
3010b57cec5SDimitry Andric   // If the sign bits don't match, then (LHS < RHS) if LHS is negative
3020b57cec5SDimitry Andric   if (lhsNeg != rhsNeg)
3030b57cec5SDimitry Andric     return lhsNeg ? -1 : 1;
3040b57cec5SDimitry Andric 
3050b57cec5SDimitry Andric   // Otherwise we can just use an unsigned comparison, because even negative
3060b57cec5SDimitry Andric   // numbers compare correctly this way if both have the same signed-ness.
3070b57cec5SDimitry Andric   return tcCompare(U.pVal, RHS.U.pVal, getNumWords());
3080b57cec5SDimitry Andric }
3090b57cec5SDimitry Andric 
3100b57cec5SDimitry Andric void APInt::setBitsSlowCase(unsigned loBit, unsigned hiBit) {
3110b57cec5SDimitry Andric   unsigned loWord = whichWord(loBit);
3120b57cec5SDimitry Andric   unsigned hiWord = whichWord(hiBit);
3130b57cec5SDimitry Andric 
3140b57cec5SDimitry Andric   // Create an initial mask for the low word with zeros below loBit.
3150b57cec5SDimitry Andric   uint64_t loMask = WORDTYPE_MAX << whichBit(loBit);
3160b57cec5SDimitry Andric 
3170b57cec5SDimitry Andric   // If hiBit is not aligned, we need a high mask.
3180b57cec5SDimitry Andric   unsigned hiShiftAmt = whichBit(hiBit);
3190b57cec5SDimitry Andric   if (hiShiftAmt != 0) {
3200b57cec5SDimitry Andric     // Create a high mask with zeros above hiBit.
3210b57cec5SDimitry Andric     uint64_t hiMask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - hiShiftAmt);
3220b57cec5SDimitry Andric     // If loWord and hiWord are equal, then we combine the masks. Otherwise,
3230b57cec5SDimitry Andric     // set the bits in hiWord.
3240b57cec5SDimitry Andric     if (hiWord == loWord)
3250b57cec5SDimitry Andric       loMask &= hiMask;
3260b57cec5SDimitry Andric     else
3270b57cec5SDimitry Andric       U.pVal[hiWord] |= hiMask;
3280b57cec5SDimitry Andric   }
3290b57cec5SDimitry Andric   // Apply the mask to the low word.
3300b57cec5SDimitry Andric   U.pVal[loWord] |= loMask;
3310b57cec5SDimitry Andric 
3320b57cec5SDimitry Andric   // Fill any words between loWord and hiWord with all ones.
3330b57cec5SDimitry Andric   for (unsigned word = loWord + 1; word < hiWord; ++word)
3340b57cec5SDimitry Andric     U.pVal[word] = WORDTYPE_MAX;
3350b57cec5SDimitry Andric }
3360b57cec5SDimitry Andric 
337349cc55cSDimitry Andric // Complement a bignum in-place.
338349cc55cSDimitry Andric static void tcComplement(APInt::WordType *dst, unsigned parts) {
339349cc55cSDimitry Andric   for (unsigned i = 0; i < parts; i++)
340349cc55cSDimitry Andric     dst[i] = ~dst[i];
341349cc55cSDimitry Andric }
342349cc55cSDimitry Andric 
3430b57cec5SDimitry Andric /// Toggle every bit to its opposite value.
3440b57cec5SDimitry Andric void APInt::flipAllBitsSlowCase() {
3450b57cec5SDimitry Andric   tcComplement(U.pVal, getNumWords());
3460b57cec5SDimitry Andric   clearUnusedBits();
3470b57cec5SDimitry Andric }
3480b57cec5SDimitry Andric 
349349cc55cSDimitry Andric /// Concatenate the bits from "NewLSB" onto the bottom of *this.  This is
350349cc55cSDimitry Andric /// equivalent to:
351349cc55cSDimitry Andric ///   (this->zext(NewWidth) << NewLSB.getBitWidth()) | NewLSB.zext(NewWidth)
352349cc55cSDimitry Andric /// In the slow case, we know the result is large.
353349cc55cSDimitry Andric APInt APInt::concatSlowCase(const APInt &NewLSB) const {
354349cc55cSDimitry Andric   unsigned NewWidth = getBitWidth() + NewLSB.getBitWidth();
35581ad6265SDimitry Andric   APInt Result = NewLSB.zext(NewWidth);
356349cc55cSDimitry Andric   Result.insertBits(*this, NewLSB.getBitWidth());
357349cc55cSDimitry Andric   return Result;
358349cc55cSDimitry Andric }
359349cc55cSDimitry Andric 
3600b57cec5SDimitry Andric /// Toggle a given bit to its opposite value whose position is given
3610b57cec5SDimitry Andric /// as "bitPosition".
3620b57cec5SDimitry Andric /// Toggles a given bit to its opposite value.
3630b57cec5SDimitry Andric void APInt::flipBit(unsigned bitPosition) {
3640b57cec5SDimitry Andric   assert(bitPosition < BitWidth && "Out of the bit-width range!");
365e8d8bef9SDimitry Andric   setBitVal(bitPosition, !(*this)[bitPosition]);
3660b57cec5SDimitry Andric }
3670b57cec5SDimitry Andric 
3680b57cec5SDimitry Andric void APInt::insertBits(const APInt &subBits, unsigned bitPosition) {
3690b57cec5SDimitry Andric   unsigned subBitWidth = subBits.getBitWidth();
370349cc55cSDimitry Andric   assert((subBitWidth + bitPosition) <= BitWidth && "Illegal bit insertion");
371349cc55cSDimitry Andric 
372349cc55cSDimitry Andric   // inserting no bits is a noop.
373349cc55cSDimitry Andric   if (subBitWidth == 0)
374349cc55cSDimitry Andric     return;
3750b57cec5SDimitry Andric 
3760b57cec5SDimitry Andric   // Insertion is a direct copy.
3770b57cec5SDimitry Andric   if (subBitWidth == BitWidth) {
3780b57cec5SDimitry Andric     *this = subBits;
3790b57cec5SDimitry Andric     return;
3800b57cec5SDimitry Andric   }
3810b57cec5SDimitry Andric 
3820b57cec5SDimitry Andric   // Single word result can be done as a direct bitmask.
3830b57cec5SDimitry Andric   if (isSingleWord()) {
3840b57cec5SDimitry Andric     uint64_t mask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - subBitWidth);
3850b57cec5SDimitry Andric     U.VAL &= ~(mask << bitPosition);
3860b57cec5SDimitry Andric     U.VAL |= (subBits.U.VAL << bitPosition);
3870b57cec5SDimitry Andric     return;
3880b57cec5SDimitry Andric   }
3890b57cec5SDimitry Andric 
3900b57cec5SDimitry Andric   unsigned loBit = whichBit(bitPosition);
3910b57cec5SDimitry Andric   unsigned loWord = whichWord(bitPosition);
3920b57cec5SDimitry Andric   unsigned hi1Word = whichWord(bitPosition + subBitWidth - 1);
3930b57cec5SDimitry Andric 
3940b57cec5SDimitry Andric   // Insertion within a single word can be done as a direct bitmask.
3950b57cec5SDimitry Andric   if (loWord == hi1Word) {
3960b57cec5SDimitry Andric     uint64_t mask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - subBitWidth);
3970b57cec5SDimitry Andric     U.pVal[loWord] &= ~(mask << loBit);
3980b57cec5SDimitry Andric     U.pVal[loWord] |= (subBits.U.VAL << loBit);
3990b57cec5SDimitry Andric     return;
4000b57cec5SDimitry Andric   }
4010b57cec5SDimitry Andric 
4020b57cec5SDimitry Andric   // Insert on word boundaries.
4030b57cec5SDimitry Andric   if (loBit == 0) {
4040b57cec5SDimitry Andric     // Direct copy whole words.
4050b57cec5SDimitry Andric     unsigned numWholeSubWords = subBitWidth / APINT_BITS_PER_WORD;
4060b57cec5SDimitry Andric     memcpy(U.pVal + loWord, subBits.getRawData(),
4070b57cec5SDimitry Andric            numWholeSubWords * APINT_WORD_SIZE);
4080b57cec5SDimitry Andric 
4090b57cec5SDimitry Andric     // Mask+insert remaining bits.
4100b57cec5SDimitry Andric     unsigned remainingBits = subBitWidth % APINT_BITS_PER_WORD;
4110b57cec5SDimitry Andric     if (remainingBits != 0) {
4120b57cec5SDimitry Andric       uint64_t mask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - remainingBits);
4130b57cec5SDimitry Andric       U.pVal[hi1Word] &= ~mask;
4140b57cec5SDimitry Andric       U.pVal[hi1Word] |= subBits.getWord(subBitWidth - 1);
4150b57cec5SDimitry Andric     }
4160b57cec5SDimitry Andric     return;
4170b57cec5SDimitry Andric   }
4180b57cec5SDimitry Andric 
4190b57cec5SDimitry Andric   // General case - set/clear individual bits in dst based on src.
4200b57cec5SDimitry Andric   // TODO - there is scope for optimization here, but at the moment this code
4210b57cec5SDimitry Andric   // path is barely used so prefer readability over performance.
422e8d8bef9SDimitry Andric   for (unsigned i = 0; i != subBitWidth; ++i)
423e8d8bef9SDimitry Andric     setBitVal(bitPosition + i, subBits[i]);
4240b57cec5SDimitry Andric }
4250b57cec5SDimitry Andric 
4268bcb0991SDimitry Andric void APInt::insertBits(uint64_t subBits, unsigned bitPosition, unsigned numBits) {
4278bcb0991SDimitry Andric   uint64_t maskBits = maskTrailingOnes<uint64_t>(numBits);
4288bcb0991SDimitry Andric   subBits &= maskBits;
4298bcb0991SDimitry Andric   if (isSingleWord()) {
4308bcb0991SDimitry Andric     U.VAL &= ~(maskBits << bitPosition);
4318bcb0991SDimitry Andric     U.VAL |= subBits << bitPosition;
4328bcb0991SDimitry Andric     return;
4338bcb0991SDimitry Andric   }
4348bcb0991SDimitry Andric 
4358bcb0991SDimitry Andric   unsigned loBit = whichBit(bitPosition);
4368bcb0991SDimitry Andric   unsigned loWord = whichWord(bitPosition);
4378bcb0991SDimitry Andric   unsigned hiWord = whichWord(bitPosition + numBits - 1);
4388bcb0991SDimitry Andric   if (loWord == hiWord) {
4398bcb0991SDimitry Andric     U.pVal[loWord] &= ~(maskBits << loBit);
4408bcb0991SDimitry Andric     U.pVal[loWord] |= subBits << loBit;
4418bcb0991SDimitry Andric     return;
4428bcb0991SDimitry Andric   }
4438bcb0991SDimitry Andric 
4448bcb0991SDimitry Andric   static_assert(8 * sizeof(WordType) <= 64, "This code assumes only two words affected");
4458bcb0991SDimitry Andric   unsigned wordBits = 8 * sizeof(WordType);
4468bcb0991SDimitry Andric   U.pVal[loWord] &= ~(maskBits << loBit);
4478bcb0991SDimitry Andric   U.pVal[loWord] |= subBits << loBit;
4488bcb0991SDimitry Andric 
4498bcb0991SDimitry Andric   U.pVal[hiWord] &= ~(maskBits >> (wordBits - loBit));
4508bcb0991SDimitry Andric   U.pVal[hiWord] |= subBits >> (wordBits - loBit);
4518bcb0991SDimitry Andric }
4528bcb0991SDimitry Andric 
4530b57cec5SDimitry Andric APInt APInt::extractBits(unsigned numBits, unsigned bitPosition) const {
4540b57cec5SDimitry Andric   assert(bitPosition < BitWidth && (numBits + bitPosition) <= BitWidth &&
4550b57cec5SDimitry Andric          "Illegal bit extraction");
4560b57cec5SDimitry Andric 
4570b57cec5SDimitry Andric   if (isSingleWord())
4580b57cec5SDimitry Andric     return APInt(numBits, U.VAL >> bitPosition);
4590b57cec5SDimitry Andric 
4600b57cec5SDimitry Andric   unsigned loBit = whichBit(bitPosition);
4610b57cec5SDimitry Andric   unsigned loWord = whichWord(bitPosition);
4620b57cec5SDimitry Andric   unsigned hiWord = whichWord(bitPosition + numBits - 1);
4630b57cec5SDimitry Andric 
4640b57cec5SDimitry Andric   // Single word result extracting bits from a single word source.
4650b57cec5SDimitry Andric   if (loWord == hiWord)
4660b57cec5SDimitry Andric     return APInt(numBits, U.pVal[loWord] >> loBit);
4670b57cec5SDimitry Andric 
4680b57cec5SDimitry Andric   // Extracting bits that start on a source word boundary can be done
4690b57cec5SDimitry Andric   // as a fast memory copy.
4700b57cec5SDimitry Andric   if (loBit == 0)
471bdd1243dSDimitry Andric     return APInt(numBits, ArrayRef(U.pVal + loWord, 1 + hiWord - loWord));
4720b57cec5SDimitry Andric 
4730b57cec5SDimitry Andric   // General case - shift + copy source words directly into place.
4740b57cec5SDimitry Andric   APInt Result(numBits, 0);
4750b57cec5SDimitry Andric   unsigned NumSrcWords = getNumWords();
4760b57cec5SDimitry Andric   unsigned NumDstWords = Result.getNumWords();
4770b57cec5SDimitry Andric 
4780b57cec5SDimitry Andric   uint64_t *DestPtr = Result.isSingleWord() ? &Result.U.VAL : Result.U.pVal;
4790b57cec5SDimitry Andric   for (unsigned word = 0; word < NumDstWords; ++word) {
4800b57cec5SDimitry Andric     uint64_t w0 = U.pVal[loWord + word];
4810b57cec5SDimitry Andric     uint64_t w1 =
4820b57cec5SDimitry Andric         (loWord + word + 1) < NumSrcWords ? U.pVal[loWord + word + 1] : 0;
4830b57cec5SDimitry Andric     DestPtr[word] = (w0 >> loBit) | (w1 << (APINT_BITS_PER_WORD - loBit));
4840b57cec5SDimitry Andric   }
4850b57cec5SDimitry Andric 
4860b57cec5SDimitry Andric   return Result.clearUnusedBits();
4870b57cec5SDimitry Andric }
4880b57cec5SDimitry Andric 
4898bcb0991SDimitry Andric uint64_t APInt::extractBitsAsZExtValue(unsigned numBits,
4908bcb0991SDimitry Andric                                        unsigned bitPosition) const {
4918bcb0991SDimitry Andric   assert(bitPosition < BitWidth && (numBits + bitPosition) <= BitWidth &&
4928bcb0991SDimitry Andric          "Illegal bit extraction");
4938bcb0991SDimitry Andric   assert(numBits <= 64 && "Illegal bit extraction");
4948bcb0991SDimitry Andric 
4958bcb0991SDimitry Andric   uint64_t maskBits = maskTrailingOnes<uint64_t>(numBits);
4968bcb0991SDimitry Andric   if (isSingleWord())
4978bcb0991SDimitry Andric     return (U.VAL >> bitPosition) & maskBits;
4988bcb0991SDimitry Andric 
4998bcb0991SDimitry Andric   unsigned loBit = whichBit(bitPosition);
5008bcb0991SDimitry Andric   unsigned loWord = whichWord(bitPosition);
5018bcb0991SDimitry Andric   unsigned hiWord = whichWord(bitPosition + numBits - 1);
5028bcb0991SDimitry Andric   if (loWord == hiWord)
5038bcb0991SDimitry Andric     return (U.pVal[loWord] >> loBit) & maskBits;
5048bcb0991SDimitry Andric 
5058bcb0991SDimitry Andric   static_assert(8 * sizeof(WordType) <= 64, "This code assumes only two words affected");
5068bcb0991SDimitry Andric   unsigned wordBits = 8 * sizeof(WordType);
5078bcb0991SDimitry Andric   uint64_t retBits = U.pVal[loWord] >> loBit;
5088bcb0991SDimitry Andric   retBits |= U.pVal[hiWord] << (wordBits - loBit);
5098bcb0991SDimitry Andric   retBits &= maskBits;
5108bcb0991SDimitry Andric   return retBits;
5118bcb0991SDimitry Andric }
5128bcb0991SDimitry Andric 
51381ad6265SDimitry Andric unsigned APInt::getSufficientBitsNeeded(StringRef Str, uint8_t Radix) {
51481ad6265SDimitry Andric   assert(!Str.empty() && "Invalid string length");
51581ad6265SDimitry Andric   size_t StrLen = Str.size();
5160b57cec5SDimitry Andric 
51781ad6265SDimitry Andric   // Each computation below needs to know if it's negative.
51881ad6265SDimitry Andric   unsigned IsNegative = false;
51981ad6265SDimitry Andric   if (Str[0] == '-' || Str[0] == '+') {
52081ad6265SDimitry Andric     IsNegative = Str[0] == '-';
52181ad6265SDimitry Andric     StrLen--;
52281ad6265SDimitry Andric     assert(StrLen && "String is only a sign, needs a value.");
52381ad6265SDimitry Andric   }
52481ad6265SDimitry Andric 
52581ad6265SDimitry Andric   // For radixes of power-of-two values, the bits required is accurately and
52681ad6265SDimitry Andric   // easily computed.
52781ad6265SDimitry Andric   if (Radix == 2)
52881ad6265SDimitry Andric     return StrLen + IsNegative;
52981ad6265SDimitry Andric   if (Radix == 8)
53081ad6265SDimitry Andric     return StrLen * 3 + IsNegative;
53181ad6265SDimitry Andric   if (Radix == 16)
53281ad6265SDimitry Andric     return StrLen * 4 + IsNegative;
53381ad6265SDimitry Andric 
53481ad6265SDimitry Andric   // Compute a sufficient number of bits that is always large enough but might
53581ad6265SDimitry Andric   // be too large. This avoids the assertion in the constructor. This
53681ad6265SDimitry Andric   // calculation doesn't work appropriately for the numbers 0-9, so just use 4
53781ad6265SDimitry Andric   // bits in that case.
53881ad6265SDimitry Andric   if (Radix == 10)
53981ad6265SDimitry Andric     return (StrLen == 1 ? 4 : StrLen * 64 / 18) + IsNegative;
54081ad6265SDimitry Andric 
54181ad6265SDimitry Andric   assert(Radix == 36);
54281ad6265SDimitry Andric   return (StrLen == 1 ? 7 : StrLen * 16 / 3) + IsNegative;
54381ad6265SDimitry Andric }
54481ad6265SDimitry Andric 
54581ad6265SDimitry Andric unsigned APInt::getBitsNeeded(StringRef str, uint8_t radix) {
54681ad6265SDimitry Andric   // Compute a sufficient number of bits that is always large enough but might
54781ad6265SDimitry Andric   // be too large.
54881ad6265SDimitry Andric   unsigned sufficient = getSufficientBitsNeeded(str, radix);
54981ad6265SDimitry Andric 
55081ad6265SDimitry Andric   // For bases 2, 8, and 16, the sufficient number of bits is exact and we can
55181ad6265SDimitry Andric   // return the value directly. For bases 10 and 36, we need to do extra work.
55281ad6265SDimitry Andric   if (radix == 2 || radix == 8 || radix == 16)
55381ad6265SDimitry Andric     return sufficient;
55481ad6265SDimitry Andric 
55581ad6265SDimitry Andric   // This is grossly inefficient but accurate. We could probably do something
55681ad6265SDimitry Andric   // with a computation of roughly slen*64/20 and then adjust by the value of
55781ad6265SDimitry Andric   // the first few digits. But, I'm not sure how accurate that could be.
5580b57cec5SDimitry Andric   size_t slen = str.size();
5590b57cec5SDimitry Andric 
5600b57cec5SDimitry Andric   // Each computation below needs to know if it's negative.
5610b57cec5SDimitry Andric   StringRef::iterator p = str.begin();
5620b57cec5SDimitry Andric   unsigned isNegative = *p == '-';
5630b57cec5SDimitry Andric   if (*p == '-' || *p == '+') {
5640b57cec5SDimitry Andric     p++;
5650b57cec5SDimitry Andric     slen--;
5660b57cec5SDimitry Andric     assert(slen && "String is only a sign, needs a value.");
5670b57cec5SDimitry Andric   }
5680b57cec5SDimitry Andric 
5690b57cec5SDimitry Andric 
5700b57cec5SDimitry Andric   // Convert to the actual binary value.
5710b57cec5SDimitry Andric   APInt tmp(sufficient, StringRef(p, slen), radix);
5720b57cec5SDimitry Andric 
5730b57cec5SDimitry Andric   // Compute how many bits are required. If the log is infinite, assume we need
5740b57cec5SDimitry Andric   // just bit. If the log is exact and value is negative, then the value is
5750b57cec5SDimitry Andric   // MinSignedValue with (log + 1) bits.
5760b57cec5SDimitry Andric   unsigned log = tmp.logBase2();
5770b57cec5SDimitry Andric   if (log == (unsigned)-1) {
5780b57cec5SDimitry Andric     return isNegative + 1;
5790b57cec5SDimitry Andric   } else if (isNegative && tmp.isPowerOf2()) {
5800b57cec5SDimitry Andric     return isNegative + log;
5810b57cec5SDimitry Andric   } else {
5820b57cec5SDimitry Andric     return isNegative + log + 1;
5830b57cec5SDimitry Andric   }
5840b57cec5SDimitry Andric }
5850b57cec5SDimitry Andric 
5860b57cec5SDimitry Andric hash_code llvm::hash_value(const APInt &Arg) {
5870b57cec5SDimitry Andric   if (Arg.isSingleWord())
5885ffd83dbSDimitry Andric     return hash_combine(Arg.BitWidth, Arg.U.VAL);
5890b57cec5SDimitry Andric 
5905ffd83dbSDimitry Andric   return hash_combine(
5915ffd83dbSDimitry Andric       Arg.BitWidth,
5925ffd83dbSDimitry Andric       hash_combine_range(Arg.U.pVal, Arg.U.pVal + Arg.getNumWords()));
5930b57cec5SDimitry Andric }
5940b57cec5SDimitry Andric 
595349cc55cSDimitry Andric unsigned DenseMapInfo<APInt, void>::getHashValue(const APInt &Key) {
596fe6060f1SDimitry Andric   return static_cast<unsigned>(hash_value(Key));
597fe6060f1SDimitry Andric }
598fe6060f1SDimitry Andric 
5990b57cec5SDimitry Andric bool APInt::isSplat(unsigned SplatSizeInBits) const {
6000b57cec5SDimitry Andric   assert(getBitWidth() % SplatSizeInBits == 0 &&
6010b57cec5SDimitry Andric          "SplatSizeInBits must divide width!");
6020b57cec5SDimitry Andric   // We can check that all parts of an integer are equal by making use of a
6030b57cec5SDimitry Andric   // little trick: rotate and check if it's still the same value.
6040b57cec5SDimitry Andric   return *this == rotl(SplatSizeInBits);
6050b57cec5SDimitry Andric }
6060b57cec5SDimitry Andric 
6070b57cec5SDimitry Andric /// This function returns the high "numBits" bits of this APInt.
6080b57cec5SDimitry Andric APInt APInt::getHiBits(unsigned numBits) const {
6090b57cec5SDimitry Andric   return this->lshr(BitWidth - numBits);
6100b57cec5SDimitry Andric }
6110b57cec5SDimitry Andric 
6120b57cec5SDimitry Andric /// This function returns the low "numBits" bits of this APInt.
6130b57cec5SDimitry Andric APInt APInt::getLoBits(unsigned numBits) const {
6140b57cec5SDimitry Andric   APInt Result(getLowBitsSet(BitWidth, numBits));
6150b57cec5SDimitry Andric   Result &= *this;
6160b57cec5SDimitry Andric   return Result;
6170b57cec5SDimitry Andric }
6180b57cec5SDimitry Andric 
6190b57cec5SDimitry Andric /// Return a value containing V broadcasted over NewLen bits.
6200b57cec5SDimitry Andric APInt APInt::getSplat(unsigned NewLen, const APInt &V) {
6210b57cec5SDimitry Andric   assert(NewLen >= V.getBitWidth() && "Can't splat to smaller bit width!");
6220b57cec5SDimitry Andric 
62381ad6265SDimitry Andric   APInt Val = V.zext(NewLen);
6240b57cec5SDimitry Andric   for (unsigned I = V.getBitWidth(); I < NewLen; I <<= 1)
6250b57cec5SDimitry Andric     Val |= Val << I;
6260b57cec5SDimitry Andric 
6270b57cec5SDimitry Andric   return Val;
6280b57cec5SDimitry Andric }
6290b57cec5SDimitry Andric 
6300b57cec5SDimitry Andric unsigned APInt::countLeadingZerosSlowCase() const {
6310b57cec5SDimitry Andric   unsigned Count = 0;
6320b57cec5SDimitry Andric   for (int i = getNumWords()-1; i >= 0; --i) {
6330b57cec5SDimitry Andric     uint64_t V = U.pVal[i];
6340b57cec5SDimitry Andric     if (V == 0)
6350b57cec5SDimitry Andric       Count += APINT_BITS_PER_WORD;
6360b57cec5SDimitry Andric     else {
63706c3fb27SDimitry Andric       Count += llvm::countl_zero(V);
6380b57cec5SDimitry Andric       break;
6390b57cec5SDimitry Andric     }
6400b57cec5SDimitry Andric   }
6410b57cec5SDimitry Andric   // Adjust for unused bits in the most significant word (they are zero).
6420b57cec5SDimitry Andric   unsigned Mod = BitWidth % APINT_BITS_PER_WORD;
6430b57cec5SDimitry Andric   Count -= Mod > 0 ? APINT_BITS_PER_WORD - Mod : 0;
6440b57cec5SDimitry Andric   return Count;
6450b57cec5SDimitry Andric }
6460b57cec5SDimitry Andric 
6470b57cec5SDimitry Andric unsigned APInt::countLeadingOnesSlowCase() const {
6480b57cec5SDimitry Andric   unsigned highWordBits = BitWidth % APINT_BITS_PER_WORD;
6490b57cec5SDimitry Andric   unsigned shift;
6500b57cec5SDimitry Andric   if (!highWordBits) {
6510b57cec5SDimitry Andric     highWordBits = APINT_BITS_PER_WORD;
6520b57cec5SDimitry Andric     shift = 0;
6530b57cec5SDimitry Andric   } else {
6540b57cec5SDimitry Andric     shift = APINT_BITS_PER_WORD - highWordBits;
6550b57cec5SDimitry Andric   }
6560b57cec5SDimitry Andric   int i = getNumWords() - 1;
65706c3fb27SDimitry Andric   unsigned Count = llvm::countl_one(U.pVal[i] << shift);
6580b57cec5SDimitry Andric   if (Count == highWordBits) {
6590b57cec5SDimitry Andric     for (i--; i >= 0; --i) {
6600b57cec5SDimitry Andric       if (U.pVal[i] == WORDTYPE_MAX)
6610b57cec5SDimitry Andric         Count += APINT_BITS_PER_WORD;
6620b57cec5SDimitry Andric       else {
66306c3fb27SDimitry Andric         Count += llvm::countl_one(U.pVal[i]);
6640b57cec5SDimitry Andric         break;
6650b57cec5SDimitry Andric       }
6660b57cec5SDimitry Andric     }
6670b57cec5SDimitry Andric   }
6680b57cec5SDimitry Andric   return Count;
6690b57cec5SDimitry Andric }
6700b57cec5SDimitry Andric 
6710b57cec5SDimitry Andric unsigned APInt::countTrailingZerosSlowCase() const {
6720b57cec5SDimitry Andric   unsigned Count = 0;
6730b57cec5SDimitry Andric   unsigned i = 0;
6740b57cec5SDimitry Andric   for (; i < getNumWords() && U.pVal[i] == 0; ++i)
6750b57cec5SDimitry Andric     Count += APINT_BITS_PER_WORD;
6760b57cec5SDimitry Andric   if (i < getNumWords())
67706c3fb27SDimitry Andric     Count += llvm::countr_zero(U.pVal[i]);
6780b57cec5SDimitry Andric   return std::min(Count, BitWidth);
6790b57cec5SDimitry Andric }
6800b57cec5SDimitry Andric 
6810b57cec5SDimitry Andric unsigned APInt::countTrailingOnesSlowCase() const {
6820b57cec5SDimitry Andric   unsigned Count = 0;
6830b57cec5SDimitry Andric   unsigned i = 0;
6840b57cec5SDimitry Andric   for (; i < getNumWords() && U.pVal[i] == WORDTYPE_MAX; ++i)
6850b57cec5SDimitry Andric     Count += APINT_BITS_PER_WORD;
6860b57cec5SDimitry Andric   if (i < getNumWords())
68706c3fb27SDimitry Andric     Count += llvm::countr_one(U.pVal[i]);
6880b57cec5SDimitry Andric   assert(Count <= BitWidth);
6890b57cec5SDimitry Andric   return Count;
6900b57cec5SDimitry Andric }
6910b57cec5SDimitry Andric 
6920b57cec5SDimitry Andric unsigned APInt::countPopulationSlowCase() const {
6930b57cec5SDimitry Andric   unsigned Count = 0;
6940b57cec5SDimitry Andric   for (unsigned i = 0; i < getNumWords(); ++i)
695bdd1243dSDimitry Andric     Count += llvm::popcount(U.pVal[i]);
6960b57cec5SDimitry Andric   return Count;
6970b57cec5SDimitry Andric }
6980b57cec5SDimitry Andric 
6990b57cec5SDimitry Andric bool APInt::intersectsSlowCase(const APInt &RHS) const {
7000b57cec5SDimitry Andric   for (unsigned i = 0, e = getNumWords(); i != e; ++i)
7010b57cec5SDimitry Andric     if ((U.pVal[i] & RHS.U.pVal[i]) != 0)
7020b57cec5SDimitry Andric       return true;
7030b57cec5SDimitry Andric 
7040b57cec5SDimitry Andric   return false;
7050b57cec5SDimitry Andric }
7060b57cec5SDimitry Andric 
7070b57cec5SDimitry Andric bool APInt::isSubsetOfSlowCase(const APInt &RHS) const {
7080b57cec5SDimitry Andric   for (unsigned i = 0, e = getNumWords(); i != e; ++i)
7090b57cec5SDimitry Andric     if ((U.pVal[i] & ~RHS.U.pVal[i]) != 0)
7100b57cec5SDimitry Andric       return false;
7110b57cec5SDimitry Andric 
7120b57cec5SDimitry Andric   return true;
7130b57cec5SDimitry Andric }
7140b57cec5SDimitry Andric 
7150b57cec5SDimitry Andric APInt APInt::byteSwap() const {
7165ffd83dbSDimitry Andric   assert(BitWidth >= 16 && BitWidth % 8 == 0 && "Cannot byteswap!");
7170b57cec5SDimitry Andric   if (BitWidth == 16)
71806c3fb27SDimitry Andric     return APInt(BitWidth, llvm::byteswap<uint16_t>(U.VAL));
7190b57cec5SDimitry Andric   if (BitWidth == 32)
72006c3fb27SDimitry Andric     return APInt(BitWidth, llvm::byteswap<uint32_t>(U.VAL));
7215ffd83dbSDimitry Andric   if (BitWidth <= 64) {
72206c3fb27SDimitry Andric     uint64_t Tmp1 = llvm::byteswap<uint64_t>(U.VAL);
7235ffd83dbSDimitry Andric     Tmp1 >>= (64 - BitWidth);
7245ffd83dbSDimitry Andric     return APInt(BitWidth, Tmp1);
7250b57cec5SDimitry Andric   }
7260b57cec5SDimitry Andric 
7270b57cec5SDimitry Andric   APInt Result(getNumWords() * APINT_BITS_PER_WORD, 0);
7280b57cec5SDimitry Andric   for (unsigned I = 0, N = getNumWords(); I != N; ++I)
72906c3fb27SDimitry Andric     Result.U.pVal[I] = llvm::byteswap<uint64_t>(U.pVal[N - I - 1]);
7300b57cec5SDimitry Andric   if (Result.BitWidth != BitWidth) {
7310b57cec5SDimitry Andric     Result.lshrInPlace(Result.BitWidth - BitWidth);
7320b57cec5SDimitry Andric     Result.BitWidth = BitWidth;
7330b57cec5SDimitry Andric   }
7340b57cec5SDimitry Andric   return Result;
7350b57cec5SDimitry Andric }
7360b57cec5SDimitry Andric 
7370b57cec5SDimitry Andric APInt APInt::reverseBits() const {
7380b57cec5SDimitry Andric   switch (BitWidth) {
7390b57cec5SDimitry Andric   case 64:
7400b57cec5SDimitry Andric     return APInt(BitWidth, llvm::reverseBits<uint64_t>(U.VAL));
7410b57cec5SDimitry Andric   case 32:
7420b57cec5SDimitry Andric     return APInt(BitWidth, llvm::reverseBits<uint32_t>(U.VAL));
7430b57cec5SDimitry Andric   case 16:
7440b57cec5SDimitry Andric     return APInt(BitWidth, llvm::reverseBits<uint16_t>(U.VAL));
7450b57cec5SDimitry Andric   case 8:
7460b57cec5SDimitry Andric     return APInt(BitWidth, llvm::reverseBits<uint8_t>(U.VAL));
747349cc55cSDimitry Andric   case 0:
748349cc55cSDimitry Andric     return *this;
7490b57cec5SDimitry Andric   default:
7500b57cec5SDimitry Andric     break;
7510b57cec5SDimitry Andric   }
7520b57cec5SDimitry Andric 
7530b57cec5SDimitry Andric   APInt Val(*this);
7540b57cec5SDimitry Andric   APInt Reversed(BitWidth, 0);
7550b57cec5SDimitry Andric   unsigned S = BitWidth;
7560b57cec5SDimitry Andric 
7570b57cec5SDimitry Andric   for (; Val != 0; Val.lshrInPlace(1)) {
7580b57cec5SDimitry Andric     Reversed <<= 1;
7590b57cec5SDimitry Andric     Reversed |= Val[0];
7600b57cec5SDimitry Andric     --S;
7610b57cec5SDimitry Andric   }
7620b57cec5SDimitry Andric 
7630b57cec5SDimitry Andric   Reversed <<= S;
7640b57cec5SDimitry Andric   return Reversed;
7650b57cec5SDimitry Andric }
7660b57cec5SDimitry Andric 
7670b57cec5SDimitry Andric APInt llvm::APIntOps::GreatestCommonDivisor(APInt A, APInt B) {
7680b57cec5SDimitry Andric   // Fast-path a common case.
7690b57cec5SDimitry Andric   if (A == B) return A;
7700b57cec5SDimitry Andric 
7710b57cec5SDimitry Andric   // Corner cases: if either operand is zero, the other is the gcd.
7720b57cec5SDimitry Andric   if (!A) return B;
7730b57cec5SDimitry Andric   if (!B) return A;
7740b57cec5SDimitry Andric 
7750b57cec5SDimitry Andric   // Count common powers of 2 and remove all other powers of 2.
7760b57cec5SDimitry Andric   unsigned Pow2;
7770b57cec5SDimitry Andric   {
77806c3fb27SDimitry Andric     unsigned Pow2_A = A.countr_zero();
77906c3fb27SDimitry Andric     unsigned Pow2_B = B.countr_zero();
7800b57cec5SDimitry Andric     if (Pow2_A > Pow2_B) {
7810b57cec5SDimitry Andric       A.lshrInPlace(Pow2_A - Pow2_B);
7820b57cec5SDimitry Andric       Pow2 = Pow2_B;
7830b57cec5SDimitry Andric     } else if (Pow2_B > Pow2_A) {
7840b57cec5SDimitry Andric       B.lshrInPlace(Pow2_B - Pow2_A);
7850b57cec5SDimitry Andric       Pow2 = Pow2_A;
7860b57cec5SDimitry Andric     } else {
7870b57cec5SDimitry Andric       Pow2 = Pow2_A;
7880b57cec5SDimitry Andric     }
7890b57cec5SDimitry Andric   }
7900b57cec5SDimitry Andric 
7910b57cec5SDimitry Andric   // Both operands are odd multiples of 2^Pow_2:
7920b57cec5SDimitry Andric   //
7930b57cec5SDimitry Andric   //   gcd(a, b) = gcd(|a - b| / 2^i, min(a, b))
7940b57cec5SDimitry Andric   //
7950b57cec5SDimitry Andric   // This is a modified version of Stein's algorithm, taking advantage of
7960b57cec5SDimitry Andric   // efficient countTrailingZeros().
7970b57cec5SDimitry Andric   while (A != B) {
7980b57cec5SDimitry Andric     if (A.ugt(B)) {
7990b57cec5SDimitry Andric       A -= B;
80006c3fb27SDimitry Andric       A.lshrInPlace(A.countr_zero() - Pow2);
8010b57cec5SDimitry Andric     } else {
8020b57cec5SDimitry Andric       B -= A;
80306c3fb27SDimitry Andric       B.lshrInPlace(B.countr_zero() - Pow2);
8040b57cec5SDimitry Andric     }
8050b57cec5SDimitry Andric   }
8060b57cec5SDimitry Andric 
8070b57cec5SDimitry Andric   return A;
8080b57cec5SDimitry Andric }
8090b57cec5SDimitry Andric 
8100b57cec5SDimitry Andric APInt llvm::APIntOps::RoundDoubleToAPInt(double Double, unsigned width) {
8110b57cec5SDimitry Andric   uint64_t I = bit_cast<uint64_t>(Double);
8120b57cec5SDimitry Andric 
8130b57cec5SDimitry Andric   // Get the sign bit from the highest order bit
8140b57cec5SDimitry Andric   bool isNeg = I >> 63;
8150b57cec5SDimitry Andric 
8160b57cec5SDimitry Andric   // Get the 11-bit exponent and adjust for the 1023 bit bias
8170b57cec5SDimitry Andric   int64_t exp = ((I >> 52) & 0x7ff) - 1023;
8180b57cec5SDimitry Andric 
8190b57cec5SDimitry Andric   // If the exponent is negative, the value is < 0 so just return 0.
8200b57cec5SDimitry Andric   if (exp < 0)
8210b57cec5SDimitry Andric     return APInt(width, 0u);
8220b57cec5SDimitry Andric 
8230b57cec5SDimitry Andric   // Extract the mantissa by clearing the top 12 bits (sign + exponent).
8240b57cec5SDimitry Andric   uint64_t mantissa = (I & (~0ULL >> 12)) | 1ULL << 52;
8250b57cec5SDimitry Andric 
8260b57cec5SDimitry Andric   // If the exponent doesn't shift all bits out of the mantissa
8270b57cec5SDimitry Andric   if (exp < 52)
8280b57cec5SDimitry Andric     return isNeg ? -APInt(width, mantissa >> (52 - exp)) :
8290b57cec5SDimitry Andric                     APInt(width, mantissa >> (52 - exp));
8300b57cec5SDimitry Andric 
8310b57cec5SDimitry Andric   // If the client didn't provide enough bits for us to shift the mantissa into
8320b57cec5SDimitry Andric   // then the result is undefined, just return 0
8330b57cec5SDimitry Andric   if (width <= exp - 52)
8340b57cec5SDimitry Andric     return APInt(width, 0);
8350b57cec5SDimitry Andric 
8360b57cec5SDimitry Andric   // Otherwise, we have to shift the mantissa bits up to the right location
8370b57cec5SDimitry Andric   APInt Tmp(width, mantissa);
8380b57cec5SDimitry Andric   Tmp <<= (unsigned)exp - 52;
8390b57cec5SDimitry Andric   return isNeg ? -Tmp : Tmp;
8400b57cec5SDimitry Andric }
8410b57cec5SDimitry Andric 
8420b57cec5SDimitry Andric /// This function converts this APInt to a double.
8430b57cec5SDimitry Andric /// The layout for double is as following (IEEE Standard 754):
8440b57cec5SDimitry Andric ///  --------------------------------------
8450b57cec5SDimitry Andric /// |  Sign    Exponent    Fraction    Bias |
8460b57cec5SDimitry Andric /// |-------------------------------------- |
8470b57cec5SDimitry Andric /// |  1[63]   11[62-52]   52[51-00]   1023 |
8480b57cec5SDimitry Andric ///  --------------------------------------
8490b57cec5SDimitry Andric double APInt::roundToDouble(bool isSigned) const {
8500b57cec5SDimitry Andric 
8510b57cec5SDimitry Andric   // Handle the simple case where the value is contained in one uint64_t.
8520b57cec5SDimitry Andric   // It is wrong to optimize getWord(0) to VAL; there might be more than one word.
8530b57cec5SDimitry Andric   if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
8540b57cec5SDimitry Andric     if (isSigned) {
8550b57cec5SDimitry Andric       int64_t sext = SignExtend64(getWord(0), BitWidth);
8560b57cec5SDimitry Andric       return double(sext);
8570b57cec5SDimitry Andric     } else
8580b57cec5SDimitry Andric       return double(getWord(0));
8590b57cec5SDimitry Andric   }
8600b57cec5SDimitry Andric 
8610b57cec5SDimitry Andric   // Determine if the value is negative.
8620b57cec5SDimitry Andric   bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
8630b57cec5SDimitry Andric 
8640b57cec5SDimitry Andric   // Construct the absolute value if we're negative.
8650b57cec5SDimitry Andric   APInt Tmp(isNeg ? -(*this) : (*this));
8660b57cec5SDimitry Andric 
8670b57cec5SDimitry Andric   // Figure out how many bits we're using.
8680b57cec5SDimitry Andric   unsigned n = Tmp.getActiveBits();
8690b57cec5SDimitry Andric 
8700b57cec5SDimitry Andric   // The exponent (without bias normalization) is just the number of bits
8710b57cec5SDimitry Andric   // we are using. Note that the sign bit is gone since we constructed the
8720b57cec5SDimitry Andric   // absolute value.
8730b57cec5SDimitry Andric   uint64_t exp = n;
8740b57cec5SDimitry Andric 
8750b57cec5SDimitry Andric   // Return infinity for exponent overflow
8760b57cec5SDimitry Andric   if (exp > 1023) {
8770b57cec5SDimitry Andric     if (!isSigned || !isNeg)
8780b57cec5SDimitry Andric       return std::numeric_limits<double>::infinity();
8790b57cec5SDimitry Andric     else
8800b57cec5SDimitry Andric       return -std::numeric_limits<double>::infinity();
8810b57cec5SDimitry Andric   }
8820b57cec5SDimitry Andric   exp += 1023; // Increment for 1023 bias
8830b57cec5SDimitry Andric 
8840b57cec5SDimitry Andric   // Number of bits in mantissa is 52. To obtain the mantissa value, we must
8850b57cec5SDimitry Andric   // extract the high 52 bits from the correct words in pVal.
8860b57cec5SDimitry Andric   uint64_t mantissa;
8870b57cec5SDimitry Andric   unsigned hiWord = whichWord(n-1);
8880b57cec5SDimitry Andric   if (hiWord == 0) {
8890b57cec5SDimitry Andric     mantissa = Tmp.U.pVal[0];
8900b57cec5SDimitry Andric     if (n > 52)
8910b57cec5SDimitry Andric       mantissa >>= n - 52; // shift down, we want the top 52 bits.
8920b57cec5SDimitry Andric   } else {
8930b57cec5SDimitry Andric     assert(hiWord > 0 && "huh?");
8940b57cec5SDimitry Andric     uint64_t hibits = Tmp.U.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
8950b57cec5SDimitry Andric     uint64_t lobits = Tmp.U.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
8960b57cec5SDimitry Andric     mantissa = hibits | lobits;
8970b57cec5SDimitry Andric   }
8980b57cec5SDimitry Andric 
8990b57cec5SDimitry Andric   // The leading bit of mantissa is implicit, so get rid of it.
9000b57cec5SDimitry Andric   uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
9010b57cec5SDimitry Andric   uint64_t I = sign | (exp << 52) | mantissa;
9020b57cec5SDimitry Andric   return bit_cast<double>(I);
9030b57cec5SDimitry Andric }
9040b57cec5SDimitry Andric 
9050b57cec5SDimitry Andric // Truncate to new width.
9060b57cec5SDimitry Andric APInt APInt::trunc(unsigned width) const {
90781ad6265SDimitry Andric   assert(width <= BitWidth && "Invalid APInt Truncate request");
9080b57cec5SDimitry Andric 
9090b57cec5SDimitry Andric   if (width <= APINT_BITS_PER_WORD)
9100b57cec5SDimitry Andric     return APInt(width, getRawData()[0]);
9110b57cec5SDimitry Andric 
91281ad6265SDimitry Andric   if (width == BitWidth)
91381ad6265SDimitry Andric     return *this;
91481ad6265SDimitry Andric 
9150b57cec5SDimitry Andric   APInt Result(getMemory(getNumWords(width)), width);
9160b57cec5SDimitry Andric 
9170b57cec5SDimitry Andric   // Copy full words.
9180b57cec5SDimitry Andric   unsigned i;
9190b57cec5SDimitry Andric   for (i = 0; i != width / APINT_BITS_PER_WORD; i++)
9200b57cec5SDimitry Andric     Result.U.pVal[i] = U.pVal[i];
9210b57cec5SDimitry Andric 
9220b57cec5SDimitry Andric   // Truncate and copy any partial word.
9230b57cec5SDimitry Andric   unsigned bits = (0 - width) % APINT_BITS_PER_WORD;
9240b57cec5SDimitry Andric   if (bits != 0)
9250b57cec5SDimitry Andric     Result.U.pVal[i] = U.pVal[i] << bits >> bits;
9260b57cec5SDimitry Andric 
9270b57cec5SDimitry Andric   return Result;
9280b57cec5SDimitry Andric }
9290b57cec5SDimitry Andric 
930480093f4SDimitry Andric // Truncate to new width with unsigned saturation.
931480093f4SDimitry Andric APInt APInt::truncUSat(unsigned width) const {
93281ad6265SDimitry Andric   assert(width <= BitWidth && "Invalid APInt Truncate request");
933480093f4SDimitry Andric 
934480093f4SDimitry Andric   // Can we just losslessly truncate it?
935480093f4SDimitry Andric   if (isIntN(width))
936480093f4SDimitry Andric     return trunc(width);
937480093f4SDimitry Andric   // If not, then just return the new limit.
938480093f4SDimitry Andric   return APInt::getMaxValue(width);
939480093f4SDimitry Andric }
940480093f4SDimitry Andric 
941480093f4SDimitry Andric // Truncate to new width with signed saturation.
942480093f4SDimitry Andric APInt APInt::truncSSat(unsigned width) const {
94381ad6265SDimitry Andric   assert(width <= BitWidth && "Invalid APInt Truncate request");
944480093f4SDimitry Andric 
945480093f4SDimitry Andric   // Can we just losslessly truncate it?
946480093f4SDimitry Andric   if (isSignedIntN(width))
947480093f4SDimitry Andric     return trunc(width);
948480093f4SDimitry Andric   // If not, then just return the new limits.
949480093f4SDimitry Andric   return isNegative() ? APInt::getSignedMinValue(width)
950480093f4SDimitry Andric                       : APInt::getSignedMaxValue(width);
951480093f4SDimitry Andric }
952480093f4SDimitry Andric 
9530b57cec5SDimitry Andric // Sign extend to a new width.
9540b57cec5SDimitry Andric APInt APInt::sext(unsigned Width) const {
95581ad6265SDimitry Andric   assert(Width >= BitWidth && "Invalid APInt SignExtend request");
9560b57cec5SDimitry Andric 
9570b57cec5SDimitry Andric   if (Width <= APINT_BITS_PER_WORD)
9580b57cec5SDimitry Andric     return APInt(Width, SignExtend64(U.VAL, BitWidth));
9590b57cec5SDimitry Andric 
96081ad6265SDimitry Andric   if (Width == BitWidth)
96181ad6265SDimitry Andric     return *this;
96281ad6265SDimitry Andric 
9630b57cec5SDimitry Andric   APInt Result(getMemory(getNumWords(Width)), Width);
9640b57cec5SDimitry Andric 
9650b57cec5SDimitry Andric   // Copy words.
9660b57cec5SDimitry Andric   std::memcpy(Result.U.pVal, getRawData(), getNumWords() * APINT_WORD_SIZE);
9670b57cec5SDimitry Andric 
9680b57cec5SDimitry Andric   // Sign extend the last word since there may be unused bits in the input.
9690b57cec5SDimitry Andric   Result.U.pVal[getNumWords() - 1] =
9700b57cec5SDimitry Andric       SignExtend64(Result.U.pVal[getNumWords() - 1],
9710b57cec5SDimitry Andric                    ((BitWidth - 1) % APINT_BITS_PER_WORD) + 1);
9720b57cec5SDimitry Andric 
9730b57cec5SDimitry Andric   // Fill with sign bits.
9740b57cec5SDimitry Andric   std::memset(Result.U.pVal + getNumWords(), isNegative() ? -1 : 0,
9750b57cec5SDimitry Andric               (Result.getNumWords() - getNumWords()) * APINT_WORD_SIZE);
9760b57cec5SDimitry Andric   Result.clearUnusedBits();
9770b57cec5SDimitry Andric   return Result;
9780b57cec5SDimitry Andric }
9790b57cec5SDimitry Andric 
9800b57cec5SDimitry Andric //  Zero extend to a new width.
9810b57cec5SDimitry Andric APInt APInt::zext(unsigned width) const {
98281ad6265SDimitry Andric   assert(width >= BitWidth && "Invalid APInt ZeroExtend request");
9830b57cec5SDimitry Andric 
9840b57cec5SDimitry Andric   if (width <= APINT_BITS_PER_WORD)
9850b57cec5SDimitry Andric     return APInt(width, U.VAL);
9860b57cec5SDimitry Andric 
98781ad6265SDimitry Andric   if (width == BitWidth)
98881ad6265SDimitry Andric     return *this;
98981ad6265SDimitry Andric 
9900b57cec5SDimitry Andric   APInt Result(getMemory(getNumWords(width)), width);
9910b57cec5SDimitry Andric 
9920b57cec5SDimitry Andric   // Copy words.
9930b57cec5SDimitry Andric   std::memcpy(Result.U.pVal, getRawData(), getNumWords() * APINT_WORD_SIZE);
9940b57cec5SDimitry Andric 
9950b57cec5SDimitry Andric   // Zero remaining words.
9960b57cec5SDimitry Andric   std::memset(Result.U.pVal + getNumWords(), 0,
9970b57cec5SDimitry Andric               (Result.getNumWords() - getNumWords()) * APINT_WORD_SIZE);
9980b57cec5SDimitry Andric 
9990b57cec5SDimitry Andric   return Result;
10000b57cec5SDimitry Andric }
10010b57cec5SDimitry Andric 
10020b57cec5SDimitry Andric APInt APInt::zextOrTrunc(unsigned width) const {
10030b57cec5SDimitry Andric   if (BitWidth < width)
10040b57cec5SDimitry Andric     return zext(width);
10050b57cec5SDimitry Andric   if (BitWidth > width)
10060b57cec5SDimitry Andric     return trunc(width);
10070b57cec5SDimitry Andric   return *this;
10080b57cec5SDimitry Andric }
10090b57cec5SDimitry Andric 
10100b57cec5SDimitry Andric APInt APInt::sextOrTrunc(unsigned width) const {
10110b57cec5SDimitry Andric   if (BitWidth < width)
10120b57cec5SDimitry Andric     return sext(width);
10130b57cec5SDimitry Andric   if (BitWidth > width)
10140b57cec5SDimitry Andric     return trunc(width);
10150b57cec5SDimitry Andric   return *this;
10160b57cec5SDimitry Andric }
10170b57cec5SDimitry Andric 
10180b57cec5SDimitry Andric /// Arithmetic right-shift this APInt by shiftAmt.
10190b57cec5SDimitry Andric /// Arithmetic right-shift function.
10200b57cec5SDimitry Andric void APInt::ashrInPlace(const APInt &shiftAmt) {
10210b57cec5SDimitry Andric   ashrInPlace((unsigned)shiftAmt.getLimitedValue(BitWidth));
10220b57cec5SDimitry Andric }
10230b57cec5SDimitry Andric 
10240b57cec5SDimitry Andric /// Arithmetic right-shift this APInt by shiftAmt.
10250b57cec5SDimitry Andric /// Arithmetic right-shift function.
10260b57cec5SDimitry Andric void APInt::ashrSlowCase(unsigned ShiftAmt) {
10270b57cec5SDimitry Andric   // Don't bother performing a no-op shift.
10280b57cec5SDimitry Andric   if (!ShiftAmt)
10290b57cec5SDimitry Andric     return;
10300b57cec5SDimitry Andric 
10310b57cec5SDimitry Andric   // Save the original sign bit for later.
10320b57cec5SDimitry Andric   bool Negative = isNegative();
10330b57cec5SDimitry Andric 
10340b57cec5SDimitry Andric   // WordShift is the inter-part shift; BitShift is intra-part shift.
10350b57cec5SDimitry Andric   unsigned WordShift = ShiftAmt / APINT_BITS_PER_WORD;
10360b57cec5SDimitry Andric   unsigned BitShift = ShiftAmt % APINT_BITS_PER_WORD;
10370b57cec5SDimitry Andric 
10380b57cec5SDimitry Andric   unsigned WordsToMove = getNumWords() - WordShift;
10390b57cec5SDimitry Andric   if (WordsToMove != 0) {
10400b57cec5SDimitry Andric     // Sign extend the last word to fill in the unused bits.
10410b57cec5SDimitry Andric     U.pVal[getNumWords() - 1] = SignExtend64(
10420b57cec5SDimitry Andric         U.pVal[getNumWords() - 1], ((BitWidth - 1) % APINT_BITS_PER_WORD) + 1);
10430b57cec5SDimitry Andric 
10440b57cec5SDimitry Andric     // Fastpath for moving by whole words.
10450b57cec5SDimitry Andric     if (BitShift == 0) {
10460b57cec5SDimitry Andric       std::memmove(U.pVal, U.pVal + WordShift, WordsToMove * APINT_WORD_SIZE);
10470b57cec5SDimitry Andric     } else {
10480b57cec5SDimitry Andric       // Move the words containing significant bits.
10490b57cec5SDimitry Andric       for (unsigned i = 0; i != WordsToMove - 1; ++i)
10500b57cec5SDimitry Andric         U.pVal[i] = (U.pVal[i + WordShift] >> BitShift) |
10510b57cec5SDimitry Andric                     (U.pVal[i + WordShift + 1] << (APINT_BITS_PER_WORD - BitShift));
10520b57cec5SDimitry Andric 
10530b57cec5SDimitry Andric       // Handle the last word which has no high bits to copy.
10540b57cec5SDimitry Andric       U.pVal[WordsToMove - 1] = U.pVal[WordShift + WordsToMove - 1] >> BitShift;
10550b57cec5SDimitry Andric       // Sign extend one more time.
10560b57cec5SDimitry Andric       U.pVal[WordsToMove - 1] =
10570b57cec5SDimitry Andric           SignExtend64(U.pVal[WordsToMove - 1], APINT_BITS_PER_WORD - BitShift);
10580b57cec5SDimitry Andric     }
10590b57cec5SDimitry Andric   }
10600b57cec5SDimitry Andric 
10610b57cec5SDimitry Andric   // Fill in the remainder based on the original sign.
10620b57cec5SDimitry Andric   std::memset(U.pVal + WordsToMove, Negative ? -1 : 0,
10630b57cec5SDimitry Andric               WordShift * APINT_WORD_SIZE);
10640b57cec5SDimitry Andric   clearUnusedBits();
10650b57cec5SDimitry Andric }
10660b57cec5SDimitry Andric 
10670b57cec5SDimitry Andric /// Logical right-shift this APInt by shiftAmt.
10680b57cec5SDimitry Andric /// Logical right-shift function.
10690b57cec5SDimitry Andric void APInt::lshrInPlace(const APInt &shiftAmt) {
10700b57cec5SDimitry Andric   lshrInPlace((unsigned)shiftAmt.getLimitedValue(BitWidth));
10710b57cec5SDimitry Andric }
10720b57cec5SDimitry Andric 
10730b57cec5SDimitry Andric /// Logical right-shift this APInt by shiftAmt.
10740b57cec5SDimitry Andric /// Logical right-shift function.
10750b57cec5SDimitry Andric void APInt::lshrSlowCase(unsigned ShiftAmt) {
10760b57cec5SDimitry Andric   tcShiftRight(U.pVal, getNumWords(), ShiftAmt);
10770b57cec5SDimitry Andric }
10780b57cec5SDimitry Andric 
10790b57cec5SDimitry Andric /// Left-shift this APInt by shiftAmt.
10800b57cec5SDimitry Andric /// Left-shift function.
10810b57cec5SDimitry Andric APInt &APInt::operator<<=(const APInt &shiftAmt) {
10820b57cec5SDimitry Andric   // It's undefined behavior in C to shift by BitWidth or greater.
10830b57cec5SDimitry Andric   *this <<= (unsigned)shiftAmt.getLimitedValue(BitWidth);
10840b57cec5SDimitry Andric   return *this;
10850b57cec5SDimitry Andric }
10860b57cec5SDimitry Andric 
10870b57cec5SDimitry Andric void APInt::shlSlowCase(unsigned ShiftAmt) {
10880b57cec5SDimitry Andric   tcShiftLeft(U.pVal, getNumWords(), ShiftAmt);
10890b57cec5SDimitry Andric   clearUnusedBits();
10900b57cec5SDimitry Andric }
10910b57cec5SDimitry Andric 
10920b57cec5SDimitry Andric // Calculate the rotate amount modulo the bit width.
10930b57cec5SDimitry Andric static unsigned rotateModulo(unsigned BitWidth, const APInt &rotateAmt) {
1094349cc55cSDimitry Andric   if (LLVM_UNLIKELY(BitWidth == 0))
1095349cc55cSDimitry Andric     return 0;
10960b57cec5SDimitry Andric   unsigned rotBitWidth = rotateAmt.getBitWidth();
10970b57cec5SDimitry Andric   APInt rot = rotateAmt;
10980b57cec5SDimitry Andric   if (rotBitWidth < BitWidth) {
10990b57cec5SDimitry Andric     // Extend the rotate APInt, so that the urem doesn't divide by 0.
11000b57cec5SDimitry Andric     // e.g. APInt(1, 32) would give APInt(1, 0).
11010b57cec5SDimitry Andric     rot = rotateAmt.zext(BitWidth);
11020b57cec5SDimitry Andric   }
11030b57cec5SDimitry Andric   rot = rot.urem(APInt(rot.getBitWidth(), BitWidth));
11040b57cec5SDimitry Andric   return rot.getLimitedValue(BitWidth);
11050b57cec5SDimitry Andric }
11060b57cec5SDimitry Andric 
11070b57cec5SDimitry Andric APInt APInt::rotl(const APInt &rotateAmt) const {
11080b57cec5SDimitry Andric   return rotl(rotateModulo(BitWidth, rotateAmt));
11090b57cec5SDimitry Andric }
11100b57cec5SDimitry Andric 
11110b57cec5SDimitry Andric APInt APInt::rotl(unsigned rotateAmt) const {
1112349cc55cSDimitry Andric   if (LLVM_UNLIKELY(BitWidth == 0))
1113349cc55cSDimitry Andric     return *this;
11140b57cec5SDimitry Andric   rotateAmt %= BitWidth;
11150b57cec5SDimitry Andric   if (rotateAmt == 0)
11160b57cec5SDimitry Andric     return *this;
11170b57cec5SDimitry Andric   return shl(rotateAmt) | lshr(BitWidth - rotateAmt);
11180b57cec5SDimitry Andric }
11190b57cec5SDimitry Andric 
11200b57cec5SDimitry Andric APInt APInt::rotr(const APInt &rotateAmt) const {
11210b57cec5SDimitry Andric   return rotr(rotateModulo(BitWidth, rotateAmt));
11220b57cec5SDimitry Andric }
11230b57cec5SDimitry Andric 
11240b57cec5SDimitry Andric APInt APInt::rotr(unsigned rotateAmt) const {
1125349cc55cSDimitry Andric   if (BitWidth == 0)
1126349cc55cSDimitry Andric     return *this;
11270b57cec5SDimitry Andric   rotateAmt %= BitWidth;
11280b57cec5SDimitry Andric   if (rotateAmt == 0)
11290b57cec5SDimitry Andric     return *this;
11300b57cec5SDimitry Andric   return lshr(rotateAmt) | shl(BitWidth - rotateAmt);
11310b57cec5SDimitry Andric }
11320b57cec5SDimitry Andric 
1133349cc55cSDimitry Andric /// \returns the nearest log base 2 of this APInt. Ties round up.
1134349cc55cSDimitry Andric ///
1135349cc55cSDimitry Andric /// NOTE: When we have a BitWidth of 1, we define:
1136349cc55cSDimitry Andric ///
1137349cc55cSDimitry Andric ///   log2(0) = UINT32_MAX
1138349cc55cSDimitry Andric ///   log2(1) = 0
1139349cc55cSDimitry Andric ///
1140349cc55cSDimitry Andric /// to get around any mathematical concerns resulting from
1141349cc55cSDimitry Andric /// referencing 2 in a space where 2 does no exist.
1142349cc55cSDimitry Andric unsigned APInt::nearestLogBase2() const {
1143349cc55cSDimitry Andric   // Special case when we have a bitwidth of 1. If VAL is 1, then we
1144349cc55cSDimitry Andric   // get 0. If VAL is 0, we get WORDTYPE_MAX which gets truncated to
1145349cc55cSDimitry Andric   // UINT32_MAX.
1146349cc55cSDimitry Andric   if (BitWidth == 1)
1147349cc55cSDimitry Andric     return U.VAL - 1;
1148349cc55cSDimitry Andric 
1149349cc55cSDimitry Andric   // Handle the zero case.
1150349cc55cSDimitry Andric   if (isZero())
1151349cc55cSDimitry Andric     return UINT32_MAX;
1152349cc55cSDimitry Andric 
1153349cc55cSDimitry Andric   // The non-zero case is handled by computing:
1154349cc55cSDimitry Andric   //
1155349cc55cSDimitry Andric   //   nearestLogBase2(x) = logBase2(x) + x[logBase2(x)-1].
1156349cc55cSDimitry Andric   //
1157349cc55cSDimitry Andric   // where x[i] is referring to the value of the ith bit of x.
1158349cc55cSDimitry Andric   unsigned lg = logBase2();
1159349cc55cSDimitry Andric   return lg + unsigned((*this)[lg - 1]);
1160349cc55cSDimitry Andric }
1161349cc55cSDimitry Andric 
11620b57cec5SDimitry Andric // Square Root - this method computes and returns the square root of "this".
11630b57cec5SDimitry Andric // Three mechanisms are used for computation. For small values (<= 5 bits),
11640b57cec5SDimitry Andric // a table lookup is done. This gets some performance for common cases. For
11650b57cec5SDimitry Andric // values using less than 52 bits, the value is converted to double and then
11660b57cec5SDimitry Andric // the libc sqrt function is called. The result is rounded and then converted
11670b57cec5SDimitry Andric // back to a uint64_t which is then used to construct the result. Finally,
11680b57cec5SDimitry Andric // the Babylonian method for computing square roots is used.
11690b57cec5SDimitry Andric APInt APInt::sqrt() const {
11700b57cec5SDimitry Andric 
11710b57cec5SDimitry Andric   // Determine the magnitude of the value.
11720b57cec5SDimitry Andric   unsigned magnitude = getActiveBits();
11730b57cec5SDimitry Andric 
11740b57cec5SDimitry Andric   // Use a fast table for some small values. This also gets rid of some
11750b57cec5SDimitry Andric   // rounding errors in libc sqrt for small values.
11760b57cec5SDimitry Andric   if (magnitude <= 5) {
11770b57cec5SDimitry Andric     static const uint8_t results[32] = {
11780b57cec5SDimitry Andric       /*     0 */ 0,
11790b57cec5SDimitry Andric       /*  1- 2 */ 1, 1,
11800b57cec5SDimitry Andric       /*  3- 6 */ 2, 2, 2, 2,
11810b57cec5SDimitry Andric       /*  7-12 */ 3, 3, 3, 3, 3, 3,
11820b57cec5SDimitry Andric       /* 13-20 */ 4, 4, 4, 4, 4, 4, 4, 4,
11830b57cec5SDimitry Andric       /* 21-30 */ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
11840b57cec5SDimitry Andric       /*    31 */ 6
11850b57cec5SDimitry Andric     };
11860b57cec5SDimitry Andric     return APInt(BitWidth, results[ (isSingleWord() ? U.VAL : U.pVal[0]) ]);
11870b57cec5SDimitry Andric   }
11880b57cec5SDimitry Andric 
11890b57cec5SDimitry Andric   // If the magnitude of the value fits in less than 52 bits (the precision of
11900b57cec5SDimitry Andric   // an IEEE double precision floating point value), then we can use the
11910b57cec5SDimitry Andric   // libc sqrt function which will probably use a hardware sqrt computation.
11920b57cec5SDimitry Andric   // This should be faster than the algorithm below.
11930b57cec5SDimitry Andric   if (magnitude < 52) {
11940b57cec5SDimitry Andric     return APInt(BitWidth,
11950b57cec5SDimitry Andric                  uint64_t(::round(::sqrt(double(isSingleWord() ? U.VAL
11960b57cec5SDimitry Andric                                                                : U.pVal[0])))));
11970b57cec5SDimitry Andric   }
11980b57cec5SDimitry Andric 
11990b57cec5SDimitry Andric   // Okay, all the short cuts are exhausted. We must compute it. The following
12000b57cec5SDimitry Andric   // is a classical Babylonian method for computing the square root. This code
12010b57cec5SDimitry Andric   // was adapted to APInt from a wikipedia article on such computations.
12020b57cec5SDimitry Andric   // See http://www.wikipedia.org/ and go to the page named
12030b57cec5SDimitry Andric   // Calculate_an_integer_square_root.
12040b57cec5SDimitry Andric   unsigned nbits = BitWidth, i = 4;
12050b57cec5SDimitry Andric   APInt testy(BitWidth, 16);
12060b57cec5SDimitry Andric   APInt x_old(BitWidth, 1);
12070b57cec5SDimitry Andric   APInt x_new(BitWidth, 0);
12080b57cec5SDimitry Andric   APInt two(BitWidth, 2);
12090b57cec5SDimitry Andric 
12100b57cec5SDimitry Andric   // Select a good starting value using binary logarithms.
12110b57cec5SDimitry Andric   for (;; i += 2, testy = testy.shl(2))
12120b57cec5SDimitry Andric     if (i >= nbits || this->ule(testy)) {
12130b57cec5SDimitry Andric       x_old = x_old.shl(i / 2);
12140b57cec5SDimitry Andric       break;
12150b57cec5SDimitry Andric     }
12160b57cec5SDimitry Andric 
12170b57cec5SDimitry Andric   // Use the Babylonian method to arrive at the integer square root:
12180b57cec5SDimitry Andric   for (;;) {
12190b57cec5SDimitry Andric     x_new = (this->udiv(x_old) + x_old).udiv(two);
12200b57cec5SDimitry Andric     if (x_old.ule(x_new))
12210b57cec5SDimitry Andric       break;
12220b57cec5SDimitry Andric     x_old = x_new;
12230b57cec5SDimitry Andric   }
12240b57cec5SDimitry Andric 
12250b57cec5SDimitry Andric   // Make sure we return the closest approximation
12260b57cec5SDimitry Andric   // NOTE: The rounding calculation below is correct. It will produce an
12270b57cec5SDimitry Andric   // off-by-one discrepancy with results from pari/gp. That discrepancy has been
12280b57cec5SDimitry Andric   // determined to be a rounding issue with pari/gp as it begins to use a
12290b57cec5SDimitry Andric   // floating point representation after 192 bits. There are no discrepancies
12300b57cec5SDimitry Andric   // between this algorithm and pari/gp for bit widths < 192 bits.
12310b57cec5SDimitry Andric   APInt square(x_old * x_old);
12320b57cec5SDimitry Andric   APInt nextSquare((x_old + 1) * (x_old +1));
12330b57cec5SDimitry Andric   if (this->ult(square))
12340b57cec5SDimitry Andric     return x_old;
12350b57cec5SDimitry Andric   assert(this->ule(nextSquare) && "Error in APInt::sqrt computation");
12360b57cec5SDimitry Andric   APInt midpoint((nextSquare - square).udiv(two));
12370b57cec5SDimitry Andric   APInt offset(*this - square);
12380b57cec5SDimitry Andric   if (offset.ult(midpoint))
12390b57cec5SDimitry Andric     return x_old;
12400b57cec5SDimitry Andric   return x_old + 1;
12410b57cec5SDimitry Andric }
12420b57cec5SDimitry Andric 
1243*0fca6ea1SDimitry Andric /// \returns the multiplicative inverse of an odd APInt modulo 2^BitWidth.
1244*0fca6ea1SDimitry Andric APInt APInt::multiplicativeInverse() const {
1245*0fca6ea1SDimitry Andric   assert((*this)[0] &&
1246*0fca6ea1SDimitry Andric          "multiplicative inverse is only defined for odd numbers!");
12470b57cec5SDimitry Andric 
1248*0fca6ea1SDimitry Andric   // Use Newton's method.
1249*0fca6ea1SDimitry Andric   APInt Factor = *this;
1250*0fca6ea1SDimitry Andric   APInt T;
1251*0fca6ea1SDimitry Andric   while (!(T = *this * Factor).isOne())
1252*0fca6ea1SDimitry Andric     Factor *= 2 - std::move(T);
1253*0fca6ea1SDimitry Andric   return Factor;
12540b57cec5SDimitry Andric }
12550b57cec5SDimitry Andric 
12560b57cec5SDimitry Andric /// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
12570b57cec5SDimitry Andric /// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
12580b57cec5SDimitry Andric /// variables here have the same names as in the algorithm. Comments explain
12590b57cec5SDimitry Andric /// the algorithm and any deviation from it.
12600b57cec5SDimitry Andric static void KnuthDiv(uint32_t *u, uint32_t *v, uint32_t *q, uint32_t* r,
12610b57cec5SDimitry Andric                      unsigned m, unsigned n) {
12620b57cec5SDimitry Andric   assert(u && "Must provide dividend");
12630b57cec5SDimitry Andric   assert(v && "Must provide divisor");
12640b57cec5SDimitry Andric   assert(q && "Must provide quotient");
12650b57cec5SDimitry Andric   assert(u != v && u != q && v != q && "Must use different memory");
12660b57cec5SDimitry Andric   assert(n>1 && "n must be > 1");
12670b57cec5SDimitry Andric 
12680b57cec5SDimitry Andric   // b denotes the base of the number system. In our case b is 2^32.
12690b57cec5SDimitry Andric   const uint64_t b = uint64_t(1) << 32;
12700b57cec5SDimitry Andric 
12710b57cec5SDimitry Andric // The DEBUG macros here tend to be spam in the debug output if you're not
12720b57cec5SDimitry Andric // debugging this code. Disable them unless KNUTH_DEBUG is defined.
12730b57cec5SDimitry Andric #ifdef KNUTH_DEBUG
12740b57cec5SDimitry Andric #define DEBUG_KNUTH(X) LLVM_DEBUG(X)
12750b57cec5SDimitry Andric #else
12760b57cec5SDimitry Andric #define DEBUG_KNUTH(X) do {} while(false)
12770b57cec5SDimitry Andric #endif
12780b57cec5SDimitry Andric 
12790b57cec5SDimitry Andric   DEBUG_KNUTH(dbgs() << "KnuthDiv: m=" << m << " n=" << n << '\n');
12800b57cec5SDimitry Andric   DEBUG_KNUTH(dbgs() << "KnuthDiv: original:");
12810b57cec5SDimitry Andric   DEBUG_KNUTH(for (int i = m + n; i >= 0; i--) dbgs() << " " << u[i]);
12820b57cec5SDimitry Andric   DEBUG_KNUTH(dbgs() << " by");
12830b57cec5SDimitry Andric   DEBUG_KNUTH(for (int i = n; i > 0; i--) dbgs() << " " << v[i - 1]);
12840b57cec5SDimitry Andric   DEBUG_KNUTH(dbgs() << '\n');
12850b57cec5SDimitry Andric   // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
12860b57cec5SDimitry Andric   // u and v by d. Note that we have taken Knuth's advice here to use a power
12870b57cec5SDimitry Andric   // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
12880b57cec5SDimitry Andric   // 2 allows us to shift instead of multiply and it is easy to determine the
12890b57cec5SDimitry Andric   // shift amount from the leading zeros.  We are basically normalizing the u
12900b57cec5SDimitry Andric   // and v so that its high bits are shifted to the top of v's range without
12910b57cec5SDimitry Andric   // overflow. Note that this can require an extra word in u so that u must
12920b57cec5SDimitry Andric   // be of length m+n+1.
129306c3fb27SDimitry Andric   unsigned shift = llvm::countl_zero(v[n - 1]);
12940b57cec5SDimitry Andric   uint32_t v_carry = 0;
12950b57cec5SDimitry Andric   uint32_t u_carry = 0;
12960b57cec5SDimitry Andric   if (shift) {
12970b57cec5SDimitry Andric     for (unsigned i = 0; i < m+n; ++i) {
12980b57cec5SDimitry Andric       uint32_t u_tmp = u[i] >> (32 - shift);
12990b57cec5SDimitry Andric       u[i] = (u[i] << shift) | u_carry;
13000b57cec5SDimitry Andric       u_carry = u_tmp;
13010b57cec5SDimitry Andric     }
13020b57cec5SDimitry Andric     for (unsigned i = 0; i < n; ++i) {
13030b57cec5SDimitry Andric       uint32_t v_tmp = v[i] >> (32 - shift);
13040b57cec5SDimitry Andric       v[i] = (v[i] << shift) | v_carry;
13050b57cec5SDimitry Andric       v_carry = v_tmp;
13060b57cec5SDimitry Andric     }
13070b57cec5SDimitry Andric   }
13080b57cec5SDimitry Andric   u[m+n] = u_carry;
13090b57cec5SDimitry Andric 
13100b57cec5SDimitry Andric   DEBUG_KNUTH(dbgs() << "KnuthDiv:   normal:");
13110b57cec5SDimitry Andric   DEBUG_KNUTH(for (int i = m + n; i >= 0; i--) dbgs() << " " << u[i]);
13120b57cec5SDimitry Andric   DEBUG_KNUTH(dbgs() << " by");
13130b57cec5SDimitry Andric   DEBUG_KNUTH(for (int i = n; i > 0; i--) dbgs() << " " << v[i - 1]);
13140b57cec5SDimitry Andric   DEBUG_KNUTH(dbgs() << '\n');
13150b57cec5SDimitry Andric 
13160b57cec5SDimitry Andric   // D2. [Initialize j.]  Set j to m. This is the loop counter over the places.
13170b57cec5SDimitry Andric   int j = m;
13180b57cec5SDimitry Andric   do {
13190b57cec5SDimitry Andric     DEBUG_KNUTH(dbgs() << "KnuthDiv: quotient digit #" << j << '\n');
13200b57cec5SDimitry Andric     // D3. [Calculate q'.].
13210b57cec5SDimitry Andric     //     Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
13220b57cec5SDimitry Andric     //     Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
13230b57cec5SDimitry Andric     // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
13240b57cec5SDimitry Andric     // qp by 1, increase rp by v[n-1], and repeat this test if rp < b. The test
13250b57cec5SDimitry Andric     // on v[n-2] determines at high speed most of the cases in which the trial
13260b57cec5SDimitry Andric     // value qp is one too large, and it eliminates all cases where qp is two
13270b57cec5SDimitry Andric     // too large.
13280b57cec5SDimitry Andric     uint64_t dividend = Make_64(u[j+n], u[j+n-1]);
13290b57cec5SDimitry Andric     DEBUG_KNUTH(dbgs() << "KnuthDiv: dividend == " << dividend << '\n');
13300b57cec5SDimitry Andric     uint64_t qp = dividend / v[n-1];
13310b57cec5SDimitry Andric     uint64_t rp = dividend % v[n-1];
13320b57cec5SDimitry Andric     if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
13330b57cec5SDimitry Andric       qp--;
13340b57cec5SDimitry Andric       rp += v[n-1];
13350b57cec5SDimitry Andric       if (rp < b && (qp == b || qp*v[n-2] > b*rp + u[j+n-2]))
13360b57cec5SDimitry Andric         qp--;
13370b57cec5SDimitry Andric     }
13380b57cec5SDimitry Andric     DEBUG_KNUTH(dbgs() << "KnuthDiv: qp == " << qp << ", rp == " << rp << '\n');
13390b57cec5SDimitry Andric 
13400b57cec5SDimitry Andric     // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with
13410b57cec5SDimitry Andric     // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation
13420b57cec5SDimitry Andric     // consists of a simple multiplication by a one-place number, combined with
13430b57cec5SDimitry Andric     // a subtraction.
13440b57cec5SDimitry Andric     // The digits (u[j+n]...u[j]) should be kept positive; if the result of
13450b57cec5SDimitry Andric     // this step is actually negative, (u[j+n]...u[j]) should be left as the
13460b57cec5SDimitry Andric     // true value plus b**(n+1), namely as the b's complement of
13470b57cec5SDimitry Andric     // the true value, and a "borrow" to the left should be remembered.
13480b57cec5SDimitry Andric     int64_t borrow = 0;
13490b57cec5SDimitry Andric     for (unsigned i = 0; i < n; ++i) {
13500b57cec5SDimitry Andric       uint64_t p = uint64_t(qp) * uint64_t(v[i]);
13510b57cec5SDimitry Andric       int64_t subres = int64_t(u[j+i]) - borrow - Lo_32(p);
13520b57cec5SDimitry Andric       u[j+i] = Lo_32(subres);
13530b57cec5SDimitry Andric       borrow = Hi_32(p) - Hi_32(subres);
13540b57cec5SDimitry Andric       DEBUG_KNUTH(dbgs() << "KnuthDiv: u[j+i] = " << u[j + i]
13550b57cec5SDimitry Andric                         << ", borrow = " << borrow << '\n');
13560b57cec5SDimitry Andric     }
13570b57cec5SDimitry Andric     bool isNeg = u[j+n] < borrow;
13580b57cec5SDimitry Andric     u[j+n] -= Lo_32(borrow);
13590b57cec5SDimitry Andric 
13600b57cec5SDimitry Andric     DEBUG_KNUTH(dbgs() << "KnuthDiv: after subtraction:");
13610b57cec5SDimitry Andric     DEBUG_KNUTH(for (int i = m + n; i >= 0; i--) dbgs() << " " << u[i]);
13620b57cec5SDimitry Andric     DEBUG_KNUTH(dbgs() << '\n');
13630b57cec5SDimitry Andric 
13640b57cec5SDimitry Andric     // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
13650b57cec5SDimitry Andric     // negative, go to step D6; otherwise go on to step D7.
13660b57cec5SDimitry Andric     q[j] = Lo_32(qp);
13670b57cec5SDimitry Andric     if (isNeg) {
13680b57cec5SDimitry Andric       // D6. [Add back]. The probability that this step is necessary is very
13690b57cec5SDimitry Andric       // small, on the order of only 2/b. Make sure that test data accounts for
13700b57cec5SDimitry Andric       // this possibility. Decrease q[j] by 1
13710b57cec5SDimitry Andric       q[j]--;
13720b57cec5SDimitry Andric       // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]).
13730b57cec5SDimitry Andric       // A carry will occur to the left of u[j+n], and it should be ignored
13740b57cec5SDimitry Andric       // since it cancels with the borrow that occurred in D4.
13750b57cec5SDimitry Andric       bool carry = false;
13760b57cec5SDimitry Andric       for (unsigned i = 0; i < n; i++) {
13770b57cec5SDimitry Andric         uint32_t limit = std::min(u[j+i],v[i]);
13780b57cec5SDimitry Andric         u[j+i] += v[i] + carry;
13790b57cec5SDimitry Andric         carry = u[j+i] < limit || (carry && u[j+i] == limit);
13800b57cec5SDimitry Andric       }
13810b57cec5SDimitry Andric       u[j+n] += carry;
13820b57cec5SDimitry Andric     }
13830b57cec5SDimitry Andric     DEBUG_KNUTH(dbgs() << "KnuthDiv: after correction:");
13840b57cec5SDimitry Andric     DEBUG_KNUTH(for (int i = m + n; i >= 0; i--) dbgs() << " " << u[i]);
13850b57cec5SDimitry Andric     DEBUG_KNUTH(dbgs() << "\nKnuthDiv: digit result = " << q[j] << '\n');
13860b57cec5SDimitry Andric 
13870b57cec5SDimitry Andric     // D7. [Loop on j.]  Decrease j by one. Now if j >= 0, go back to D3.
13880b57cec5SDimitry Andric   } while (--j >= 0);
13890b57cec5SDimitry Andric 
13900b57cec5SDimitry Andric   DEBUG_KNUTH(dbgs() << "KnuthDiv: quotient:");
13910b57cec5SDimitry Andric   DEBUG_KNUTH(for (int i = m; i >= 0; i--) dbgs() << " " << q[i]);
13920b57cec5SDimitry Andric   DEBUG_KNUTH(dbgs() << '\n');
13930b57cec5SDimitry Andric 
13940b57cec5SDimitry Andric   // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
13950b57cec5SDimitry Andric   // remainder may be obtained by dividing u[...] by d. If r is non-null we
13960b57cec5SDimitry Andric   // compute the remainder (urem uses this).
13970b57cec5SDimitry Andric   if (r) {
13980b57cec5SDimitry Andric     // The value d is expressed by the "shift" value above since we avoided
13990b57cec5SDimitry Andric     // multiplication by d by using a shift left. So, all we have to do is
14000b57cec5SDimitry Andric     // shift right here.
14010b57cec5SDimitry Andric     if (shift) {
14020b57cec5SDimitry Andric       uint32_t carry = 0;
14030b57cec5SDimitry Andric       DEBUG_KNUTH(dbgs() << "KnuthDiv: remainder:");
14040b57cec5SDimitry Andric       for (int i = n-1; i >= 0; i--) {
14050b57cec5SDimitry Andric         r[i] = (u[i] >> shift) | carry;
14060b57cec5SDimitry Andric         carry = u[i] << (32 - shift);
14070b57cec5SDimitry Andric         DEBUG_KNUTH(dbgs() << " " << r[i]);
14080b57cec5SDimitry Andric       }
14090b57cec5SDimitry Andric     } else {
14100b57cec5SDimitry Andric       for (int i = n-1; i >= 0; i--) {
14110b57cec5SDimitry Andric         r[i] = u[i];
14120b57cec5SDimitry Andric         DEBUG_KNUTH(dbgs() << " " << r[i]);
14130b57cec5SDimitry Andric       }
14140b57cec5SDimitry Andric     }
14150b57cec5SDimitry Andric     DEBUG_KNUTH(dbgs() << '\n');
14160b57cec5SDimitry Andric   }
14170b57cec5SDimitry Andric   DEBUG_KNUTH(dbgs() << '\n');
14180b57cec5SDimitry Andric }
14190b57cec5SDimitry Andric 
14200b57cec5SDimitry Andric void APInt::divide(const WordType *LHS, unsigned lhsWords, const WordType *RHS,
14210b57cec5SDimitry Andric                    unsigned rhsWords, WordType *Quotient, WordType *Remainder) {
14220b57cec5SDimitry Andric   assert(lhsWords >= rhsWords && "Fractional result");
14230b57cec5SDimitry Andric 
14240b57cec5SDimitry Andric   // First, compose the values into an array of 32-bit words instead of
14250b57cec5SDimitry Andric   // 64-bit words. This is a necessity of both the "short division" algorithm
14260b57cec5SDimitry Andric   // and the Knuth "classical algorithm" which requires there to be native
14270b57cec5SDimitry Andric   // operations for +, -, and * on an m bit value with an m*2 bit result. We
14280b57cec5SDimitry Andric   // can't use 64-bit operands here because we don't have native results of
14290b57cec5SDimitry Andric   // 128-bits. Furthermore, casting the 64-bit values to 32-bit values won't
14300b57cec5SDimitry Andric   // work on large-endian machines.
14310b57cec5SDimitry Andric   unsigned n = rhsWords * 2;
14320b57cec5SDimitry Andric   unsigned m = (lhsWords * 2) - n;
14330b57cec5SDimitry Andric 
14340b57cec5SDimitry Andric   // Allocate space for the temporary values we need either on the stack, if
14350b57cec5SDimitry Andric   // it will fit, or on the heap if it won't.
14360b57cec5SDimitry Andric   uint32_t SPACE[128];
14370b57cec5SDimitry Andric   uint32_t *U = nullptr;
14380b57cec5SDimitry Andric   uint32_t *V = nullptr;
14390b57cec5SDimitry Andric   uint32_t *Q = nullptr;
14400b57cec5SDimitry Andric   uint32_t *R = nullptr;
14410b57cec5SDimitry Andric   if ((Remainder?4:3)*n+2*m+1 <= 128) {
14420b57cec5SDimitry Andric     U = &SPACE[0];
14430b57cec5SDimitry Andric     V = &SPACE[m+n+1];
14440b57cec5SDimitry Andric     Q = &SPACE[(m+n+1) + n];
14450b57cec5SDimitry Andric     if (Remainder)
14460b57cec5SDimitry Andric       R = &SPACE[(m+n+1) + n + (m+n)];
14470b57cec5SDimitry Andric   } else {
14480b57cec5SDimitry Andric     U = new uint32_t[m + n + 1];
14490b57cec5SDimitry Andric     V = new uint32_t[n];
14500b57cec5SDimitry Andric     Q = new uint32_t[m+n];
14510b57cec5SDimitry Andric     if (Remainder)
14520b57cec5SDimitry Andric       R = new uint32_t[n];
14530b57cec5SDimitry Andric   }
14540b57cec5SDimitry Andric 
14550b57cec5SDimitry Andric   // Initialize the dividend
14560b57cec5SDimitry Andric   memset(U, 0, (m+n+1)*sizeof(uint32_t));
14570b57cec5SDimitry Andric   for (unsigned i = 0; i < lhsWords; ++i) {
14580b57cec5SDimitry Andric     uint64_t tmp = LHS[i];
14590b57cec5SDimitry Andric     U[i * 2] = Lo_32(tmp);
14600b57cec5SDimitry Andric     U[i * 2 + 1] = Hi_32(tmp);
14610b57cec5SDimitry Andric   }
14620b57cec5SDimitry Andric   U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
14630b57cec5SDimitry Andric 
14640b57cec5SDimitry Andric   // Initialize the divisor
14650b57cec5SDimitry Andric   memset(V, 0, (n)*sizeof(uint32_t));
14660b57cec5SDimitry Andric   for (unsigned i = 0; i < rhsWords; ++i) {
14670b57cec5SDimitry Andric     uint64_t tmp = RHS[i];
14680b57cec5SDimitry Andric     V[i * 2] = Lo_32(tmp);
14690b57cec5SDimitry Andric     V[i * 2 + 1] = Hi_32(tmp);
14700b57cec5SDimitry Andric   }
14710b57cec5SDimitry Andric 
14720b57cec5SDimitry Andric   // initialize the quotient and remainder
14730b57cec5SDimitry Andric   memset(Q, 0, (m+n) * sizeof(uint32_t));
14740b57cec5SDimitry Andric   if (Remainder)
14750b57cec5SDimitry Andric     memset(R, 0, n * sizeof(uint32_t));
14760b57cec5SDimitry Andric 
14770b57cec5SDimitry Andric   // Now, adjust m and n for the Knuth division. n is the number of words in
14780b57cec5SDimitry Andric   // the divisor. m is the number of words by which the dividend exceeds the
14790b57cec5SDimitry Andric   // divisor (i.e. m+n is the length of the dividend). These sizes must not
14800b57cec5SDimitry Andric   // contain any zero words or the Knuth algorithm fails.
14810b57cec5SDimitry Andric   for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
14820b57cec5SDimitry Andric     n--;
14830b57cec5SDimitry Andric     m++;
14840b57cec5SDimitry Andric   }
14850b57cec5SDimitry Andric   for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
14860b57cec5SDimitry Andric     m--;
14870b57cec5SDimitry Andric 
14880b57cec5SDimitry Andric   // If we're left with only a single word for the divisor, Knuth doesn't work
14890b57cec5SDimitry Andric   // so we implement the short division algorithm here. This is much simpler
14900b57cec5SDimitry Andric   // and faster because we are certain that we can divide a 64-bit quantity
14910b57cec5SDimitry Andric   // by a 32-bit quantity at hardware speed and short division is simply a
14920b57cec5SDimitry Andric   // series of such operations. This is just like doing short division but we
14930b57cec5SDimitry Andric   // are using base 2^32 instead of base 10.
14940b57cec5SDimitry Andric   assert(n != 0 && "Divide by zero?");
14950b57cec5SDimitry Andric   if (n == 1) {
14960b57cec5SDimitry Andric     uint32_t divisor = V[0];
14970b57cec5SDimitry Andric     uint32_t remainder = 0;
14980b57cec5SDimitry Andric     for (int i = m; i >= 0; i--) {
14990b57cec5SDimitry Andric       uint64_t partial_dividend = Make_64(remainder, U[i]);
15000b57cec5SDimitry Andric       if (partial_dividend == 0) {
15010b57cec5SDimitry Andric         Q[i] = 0;
15020b57cec5SDimitry Andric         remainder = 0;
15030b57cec5SDimitry Andric       } else if (partial_dividend < divisor) {
15040b57cec5SDimitry Andric         Q[i] = 0;
15050b57cec5SDimitry Andric         remainder = Lo_32(partial_dividend);
15060b57cec5SDimitry Andric       } else if (partial_dividend == divisor) {
15070b57cec5SDimitry Andric         Q[i] = 1;
15080b57cec5SDimitry Andric         remainder = 0;
15090b57cec5SDimitry Andric       } else {
15100b57cec5SDimitry Andric         Q[i] = Lo_32(partial_dividend / divisor);
15110b57cec5SDimitry Andric         remainder = Lo_32(partial_dividend - (Q[i] * divisor));
15120b57cec5SDimitry Andric       }
15130b57cec5SDimitry Andric     }
15140b57cec5SDimitry Andric     if (R)
15150b57cec5SDimitry Andric       R[0] = remainder;
15160b57cec5SDimitry Andric   } else {
15170b57cec5SDimitry Andric     // Now we're ready to invoke the Knuth classical divide algorithm. In this
15180b57cec5SDimitry Andric     // case n > 1.
15190b57cec5SDimitry Andric     KnuthDiv(U, V, Q, R, m, n);
15200b57cec5SDimitry Andric   }
15210b57cec5SDimitry Andric 
15220b57cec5SDimitry Andric   // If the caller wants the quotient
15230b57cec5SDimitry Andric   if (Quotient) {
15240b57cec5SDimitry Andric     for (unsigned i = 0; i < lhsWords; ++i)
15250b57cec5SDimitry Andric       Quotient[i] = Make_64(Q[i*2+1], Q[i*2]);
15260b57cec5SDimitry Andric   }
15270b57cec5SDimitry Andric 
15280b57cec5SDimitry Andric   // If the caller wants the remainder
15290b57cec5SDimitry Andric   if (Remainder) {
15300b57cec5SDimitry Andric     for (unsigned i = 0; i < rhsWords; ++i)
15310b57cec5SDimitry Andric       Remainder[i] = Make_64(R[i*2+1], R[i*2]);
15320b57cec5SDimitry Andric   }
15330b57cec5SDimitry Andric 
15340b57cec5SDimitry Andric   // Clean up the memory we allocated.
15350b57cec5SDimitry Andric   if (U != &SPACE[0]) {
15360b57cec5SDimitry Andric     delete [] U;
15370b57cec5SDimitry Andric     delete [] V;
15380b57cec5SDimitry Andric     delete [] Q;
15390b57cec5SDimitry Andric     delete [] R;
15400b57cec5SDimitry Andric   }
15410b57cec5SDimitry Andric }
15420b57cec5SDimitry Andric 
15430b57cec5SDimitry Andric APInt APInt::udiv(const APInt &RHS) const {
15440b57cec5SDimitry Andric   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
15450b57cec5SDimitry Andric 
15460b57cec5SDimitry Andric   // First, deal with the easy case
15470b57cec5SDimitry Andric   if (isSingleWord()) {
15480b57cec5SDimitry Andric     assert(RHS.U.VAL != 0 && "Divide by zero?");
15490b57cec5SDimitry Andric     return APInt(BitWidth, U.VAL / RHS.U.VAL);
15500b57cec5SDimitry Andric   }
15510b57cec5SDimitry Andric 
15520b57cec5SDimitry Andric   // Get some facts about the LHS and RHS number of bits and words
15530b57cec5SDimitry Andric   unsigned lhsWords = getNumWords(getActiveBits());
15540b57cec5SDimitry Andric   unsigned rhsBits  = RHS.getActiveBits();
15550b57cec5SDimitry Andric   unsigned rhsWords = getNumWords(rhsBits);
15560b57cec5SDimitry Andric   assert(rhsWords && "Divided by zero???");
15570b57cec5SDimitry Andric 
15580b57cec5SDimitry Andric   // Deal with some degenerate cases
15590b57cec5SDimitry Andric   if (!lhsWords)
15600b57cec5SDimitry Andric     // 0 / X ===> 0
15610b57cec5SDimitry Andric     return APInt(BitWidth, 0);
15620b57cec5SDimitry Andric   if (rhsBits == 1)
15630b57cec5SDimitry Andric     // X / 1 ===> X
15640b57cec5SDimitry Andric     return *this;
15650b57cec5SDimitry Andric   if (lhsWords < rhsWords || this->ult(RHS))
15660b57cec5SDimitry Andric     // X / Y ===> 0, iff X < Y
15670b57cec5SDimitry Andric     return APInt(BitWidth, 0);
15680b57cec5SDimitry Andric   if (*this == RHS)
15690b57cec5SDimitry Andric     // X / X ===> 1
15700b57cec5SDimitry Andric     return APInt(BitWidth, 1);
15710b57cec5SDimitry Andric   if (lhsWords == 1) // rhsWords is 1 if lhsWords is 1.
15720b57cec5SDimitry Andric     // All high words are zero, just use native divide
15730b57cec5SDimitry Andric     return APInt(BitWidth, this->U.pVal[0] / RHS.U.pVal[0]);
15740b57cec5SDimitry Andric 
15750b57cec5SDimitry Andric   // We have to compute it the hard way. Invoke the Knuth divide algorithm.
15760b57cec5SDimitry Andric   APInt Quotient(BitWidth, 0); // to hold result.
15770b57cec5SDimitry Andric   divide(U.pVal, lhsWords, RHS.U.pVal, rhsWords, Quotient.U.pVal, nullptr);
15780b57cec5SDimitry Andric   return Quotient;
15790b57cec5SDimitry Andric }
15800b57cec5SDimitry Andric 
15810b57cec5SDimitry Andric APInt APInt::udiv(uint64_t RHS) const {
15820b57cec5SDimitry Andric   assert(RHS != 0 && "Divide by zero?");
15830b57cec5SDimitry Andric 
15840b57cec5SDimitry Andric   // First, deal with the easy case
15850b57cec5SDimitry Andric   if (isSingleWord())
15860b57cec5SDimitry Andric     return APInt(BitWidth, U.VAL / RHS);
15870b57cec5SDimitry Andric 
15880b57cec5SDimitry Andric   // Get some facts about the LHS words.
15890b57cec5SDimitry Andric   unsigned lhsWords = getNumWords(getActiveBits());
15900b57cec5SDimitry Andric 
15910b57cec5SDimitry Andric   // Deal with some degenerate cases
15920b57cec5SDimitry Andric   if (!lhsWords)
15930b57cec5SDimitry Andric     // 0 / X ===> 0
15940b57cec5SDimitry Andric     return APInt(BitWidth, 0);
15950b57cec5SDimitry Andric   if (RHS == 1)
15960b57cec5SDimitry Andric     // X / 1 ===> X
15970b57cec5SDimitry Andric     return *this;
15980b57cec5SDimitry Andric   if (this->ult(RHS))
15990b57cec5SDimitry Andric     // X / Y ===> 0, iff X < Y
16000b57cec5SDimitry Andric     return APInt(BitWidth, 0);
16010b57cec5SDimitry Andric   if (*this == RHS)
16020b57cec5SDimitry Andric     // X / X ===> 1
16030b57cec5SDimitry Andric     return APInt(BitWidth, 1);
16040b57cec5SDimitry Andric   if (lhsWords == 1) // rhsWords is 1 if lhsWords is 1.
16050b57cec5SDimitry Andric     // All high words are zero, just use native divide
16060b57cec5SDimitry Andric     return APInt(BitWidth, this->U.pVal[0] / RHS);
16070b57cec5SDimitry Andric 
16080b57cec5SDimitry Andric   // We have to compute it the hard way. Invoke the Knuth divide algorithm.
16090b57cec5SDimitry Andric   APInt Quotient(BitWidth, 0); // to hold result.
16100b57cec5SDimitry Andric   divide(U.pVal, lhsWords, &RHS, 1, Quotient.U.pVal, nullptr);
16110b57cec5SDimitry Andric   return Quotient;
16120b57cec5SDimitry Andric }
16130b57cec5SDimitry Andric 
16140b57cec5SDimitry Andric APInt APInt::sdiv(const APInt &RHS) const {
16150b57cec5SDimitry Andric   if (isNegative()) {
16160b57cec5SDimitry Andric     if (RHS.isNegative())
16170b57cec5SDimitry Andric       return (-(*this)).udiv(-RHS);
16180b57cec5SDimitry Andric     return -((-(*this)).udiv(RHS));
16190b57cec5SDimitry Andric   }
16200b57cec5SDimitry Andric   if (RHS.isNegative())
16210b57cec5SDimitry Andric     return -(this->udiv(-RHS));
16220b57cec5SDimitry Andric   return this->udiv(RHS);
16230b57cec5SDimitry Andric }
16240b57cec5SDimitry Andric 
16250b57cec5SDimitry Andric APInt APInt::sdiv(int64_t RHS) const {
16260b57cec5SDimitry Andric   if (isNegative()) {
16270b57cec5SDimitry Andric     if (RHS < 0)
16280b57cec5SDimitry Andric       return (-(*this)).udiv(-RHS);
16290b57cec5SDimitry Andric     return -((-(*this)).udiv(RHS));
16300b57cec5SDimitry Andric   }
16310b57cec5SDimitry Andric   if (RHS < 0)
16320b57cec5SDimitry Andric     return -(this->udiv(-RHS));
16330b57cec5SDimitry Andric   return this->udiv(RHS);
16340b57cec5SDimitry Andric }
16350b57cec5SDimitry Andric 
16360b57cec5SDimitry Andric APInt APInt::urem(const APInt &RHS) const {
16370b57cec5SDimitry Andric   assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
16380b57cec5SDimitry Andric   if (isSingleWord()) {
16390b57cec5SDimitry Andric     assert(RHS.U.VAL != 0 && "Remainder by zero?");
16400b57cec5SDimitry Andric     return APInt(BitWidth, U.VAL % RHS.U.VAL);
16410b57cec5SDimitry Andric   }
16420b57cec5SDimitry Andric 
16430b57cec5SDimitry Andric   // Get some facts about the LHS
16440b57cec5SDimitry Andric   unsigned lhsWords = getNumWords(getActiveBits());
16450b57cec5SDimitry Andric 
16460b57cec5SDimitry Andric   // Get some facts about the RHS
16470b57cec5SDimitry Andric   unsigned rhsBits = RHS.getActiveBits();
16480b57cec5SDimitry Andric   unsigned rhsWords = getNumWords(rhsBits);
16490b57cec5SDimitry Andric   assert(rhsWords && "Performing remainder operation by zero ???");
16500b57cec5SDimitry Andric 
16510b57cec5SDimitry Andric   // Check the degenerate cases
16520b57cec5SDimitry Andric   if (lhsWords == 0)
16530b57cec5SDimitry Andric     // 0 % Y ===> 0
16540b57cec5SDimitry Andric     return APInt(BitWidth, 0);
16550b57cec5SDimitry Andric   if (rhsBits == 1)
16560b57cec5SDimitry Andric     // X % 1 ===> 0
16570b57cec5SDimitry Andric     return APInt(BitWidth, 0);
16580b57cec5SDimitry Andric   if (lhsWords < rhsWords || this->ult(RHS))
16590b57cec5SDimitry Andric     // X % Y ===> X, iff X < Y
16600b57cec5SDimitry Andric     return *this;
16610b57cec5SDimitry Andric   if (*this == RHS)
16620b57cec5SDimitry Andric     // X % X == 0;
16630b57cec5SDimitry Andric     return APInt(BitWidth, 0);
16640b57cec5SDimitry Andric   if (lhsWords == 1)
16650b57cec5SDimitry Andric     // All high words are zero, just use native remainder
16660b57cec5SDimitry Andric     return APInt(BitWidth, U.pVal[0] % RHS.U.pVal[0]);
16670b57cec5SDimitry Andric 
16680b57cec5SDimitry Andric   // We have to compute it the hard way. Invoke the Knuth divide algorithm.
16690b57cec5SDimitry Andric   APInt Remainder(BitWidth, 0);
16700b57cec5SDimitry Andric   divide(U.pVal, lhsWords, RHS.U.pVal, rhsWords, nullptr, Remainder.U.pVal);
16710b57cec5SDimitry Andric   return Remainder;
16720b57cec5SDimitry Andric }
16730b57cec5SDimitry Andric 
16740b57cec5SDimitry Andric uint64_t APInt::urem(uint64_t RHS) const {
16750b57cec5SDimitry Andric   assert(RHS != 0 && "Remainder by zero?");
16760b57cec5SDimitry Andric 
16770b57cec5SDimitry Andric   if (isSingleWord())
16780b57cec5SDimitry Andric     return U.VAL % RHS;
16790b57cec5SDimitry Andric 
16800b57cec5SDimitry Andric   // Get some facts about the LHS
16810b57cec5SDimitry Andric   unsigned lhsWords = getNumWords(getActiveBits());
16820b57cec5SDimitry Andric 
16830b57cec5SDimitry Andric   // Check the degenerate cases
16840b57cec5SDimitry Andric   if (lhsWords == 0)
16850b57cec5SDimitry Andric     // 0 % Y ===> 0
16860b57cec5SDimitry Andric     return 0;
16870b57cec5SDimitry Andric   if (RHS == 1)
16880b57cec5SDimitry Andric     // X % 1 ===> 0
16890b57cec5SDimitry Andric     return 0;
16900b57cec5SDimitry Andric   if (this->ult(RHS))
16910b57cec5SDimitry Andric     // X % Y ===> X, iff X < Y
16920b57cec5SDimitry Andric     return getZExtValue();
16930b57cec5SDimitry Andric   if (*this == RHS)
16940b57cec5SDimitry Andric     // X % X == 0;
16950b57cec5SDimitry Andric     return 0;
16960b57cec5SDimitry Andric   if (lhsWords == 1)
16970b57cec5SDimitry Andric     // All high words are zero, just use native remainder
16980b57cec5SDimitry Andric     return U.pVal[0] % RHS;
16990b57cec5SDimitry Andric 
17000b57cec5SDimitry Andric   // We have to compute it the hard way. Invoke the Knuth divide algorithm.
17010b57cec5SDimitry Andric   uint64_t Remainder;
17020b57cec5SDimitry Andric   divide(U.pVal, lhsWords, &RHS, 1, nullptr, &Remainder);
17030b57cec5SDimitry Andric   return Remainder;
17040b57cec5SDimitry Andric }
17050b57cec5SDimitry Andric 
17060b57cec5SDimitry Andric APInt APInt::srem(const APInt &RHS) const {
17070b57cec5SDimitry Andric   if (isNegative()) {
17080b57cec5SDimitry Andric     if (RHS.isNegative())
17090b57cec5SDimitry Andric       return -((-(*this)).urem(-RHS));
17100b57cec5SDimitry Andric     return -((-(*this)).urem(RHS));
17110b57cec5SDimitry Andric   }
17120b57cec5SDimitry Andric   if (RHS.isNegative())
17130b57cec5SDimitry Andric     return this->urem(-RHS);
17140b57cec5SDimitry Andric   return this->urem(RHS);
17150b57cec5SDimitry Andric }
17160b57cec5SDimitry Andric 
17170b57cec5SDimitry Andric int64_t APInt::srem(int64_t RHS) const {
17180b57cec5SDimitry Andric   if (isNegative()) {
17190b57cec5SDimitry Andric     if (RHS < 0)
17200b57cec5SDimitry Andric       return -((-(*this)).urem(-RHS));
17210b57cec5SDimitry Andric     return -((-(*this)).urem(RHS));
17220b57cec5SDimitry Andric   }
17230b57cec5SDimitry Andric   if (RHS < 0)
17240b57cec5SDimitry Andric     return this->urem(-RHS);
17250b57cec5SDimitry Andric   return this->urem(RHS);
17260b57cec5SDimitry Andric }
17270b57cec5SDimitry Andric 
17280b57cec5SDimitry Andric void APInt::udivrem(const APInt &LHS, const APInt &RHS,
17290b57cec5SDimitry Andric                     APInt &Quotient, APInt &Remainder) {
17300b57cec5SDimitry Andric   assert(LHS.BitWidth == RHS.BitWidth && "Bit widths must be the same");
17310b57cec5SDimitry Andric   unsigned BitWidth = LHS.BitWidth;
17320b57cec5SDimitry Andric 
17330b57cec5SDimitry Andric   // First, deal with the easy case
17340b57cec5SDimitry Andric   if (LHS.isSingleWord()) {
17350b57cec5SDimitry Andric     assert(RHS.U.VAL != 0 && "Divide by zero?");
17360b57cec5SDimitry Andric     uint64_t QuotVal = LHS.U.VAL / RHS.U.VAL;
17370b57cec5SDimitry Andric     uint64_t RemVal = LHS.U.VAL % RHS.U.VAL;
17380b57cec5SDimitry Andric     Quotient = APInt(BitWidth, QuotVal);
17390b57cec5SDimitry Andric     Remainder = APInt(BitWidth, RemVal);
17400b57cec5SDimitry Andric     return;
17410b57cec5SDimitry Andric   }
17420b57cec5SDimitry Andric 
17430b57cec5SDimitry Andric   // Get some size facts about the dividend and divisor
17440b57cec5SDimitry Andric   unsigned lhsWords = getNumWords(LHS.getActiveBits());
17450b57cec5SDimitry Andric   unsigned rhsBits  = RHS.getActiveBits();
17460b57cec5SDimitry Andric   unsigned rhsWords = getNumWords(rhsBits);
17470b57cec5SDimitry Andric   assert(rhsWords && "Performing divrem operation by zero ???");
17480b57cec5SDimitry Andric 
17490b57cec5SDimitry Andric   // Check the degenerate cases
17500b57cec5SDimitry Andric   if (lhsWords == 0) {
17510b57cec5SDimitry Andric     Quotient = APInt(BitWidth, 0);    // 0 / Y ===> 0
17520b57cec5SDimitry Andric     Remainder = APInt(BitWidth, 0);   // 0 % Y ===> 0
17530b57cec5SDimitry Andric     return;
17540b57cec5SDimitry Andric   }
17550b57cec5SDimitry Andric 
17560b57cec5SDimitry Andric   if (rhsBits == 1) {
17570b57cec5SDimitry Andric     Quotient = LHS;                   // X / 1 ===> X
17580b57cec5SDimitry Andric     Remainder = APInt(BitWidth, 0);   // X % 1 ===> 0
17590b57cec5SDimitry Andric   }
17600b57cec5SDimitry Andric 
17610b57cec5SDimitry Andric   if (lhsWords < rhsWords || LHS.ult(RHS)) {
17620b57cec5SDimitry Andric     Remainder = LHS;                  // X % Y ===> X, iff X < Y
17630b57cec5SDimitry Andric     Quotient = APInt(BitWidth, 0);    // X / Y ===> 0, iff X < Y
17640b57cec5SDimitry Andric     return;
17650b57cec5SDimitry Andric   }
17660b57cec5SDimitry Andric 
17670b57cec5SDimitry Andric   if (LHS == RHS) {
17680b57cec5SDimitry Andric     Quotient  = APInt(BitWidth, 1);   // X / X ===> 1
17690b57cec5SDimitry Andric     Remainder = APInt(BitWidth, 0);   // X % X ===> 0;
17700b57cec5SDimitry Andric     return;
17710b57cec5SDimitry Andric   }
17720b57cec5SDimitry Andric 
17730b57cec5SDimitry Andric   // Make sure there is enough space to hold the results.
17740b57cec5SDimitry Andric   // NOTE: This assumes that reallocate won't affect any bits if it doesn't
17750b57cec5SDimitry Andric   // change the size. This is necessary if Quotient or Remainder is aliased
17760b57cec5SDimitry Andric   // with LHS or RHS.
17770b57cec5SDimitry Andric   Quotient.reallocate(BitWidth);
17780b57cec5SDimitry Andric   Remainder.reallocate(BitWidth);
17790b57cec5SDimitry Andric 
17800b57cec5SDimitry Andric   if (lhsWords == 1) { // rhsWords is 1 if lhsWords is 1.
17810b57cec5SDimitry Andric     // There is only one word to consider so use the native versions.
17820b57cec5SDimitry Andric     uint64_t lhsValue = LHS.U.pVal[0];
17830b57cec5SDimitry Andric     uint64_t rhsValue = RHS.U.pVal[0];
17840b57cec5SDimitry Andric     Quotient = lhsValue / rhsValue;
17850b57cec5SDimitry Andric     Remainder = lhsValue % rhsValue;
17860b57cec5SDimitry Andric     return;
17870b57cec5SDimitry Andric   }
17880b57cec5SDimitry Andric 
17890b57cec5SDimitry Andric   // Okay, lets do it the long way
17900b57cec5SDimitry Andric   divide(LHS.U.pVal, lhsWords, RHS.U.pVal, rhsWords, Quotient.U.pVal,
17910b57cec5SDimitry Andric          Remainder.U.pVal);
17920b57cec5SDimitry Andric   // Clear the rest of the Quotient and Remainder.
17930b57cec5SDimitry Andric   std::memset(Quotient.U.pVal + lhsWords, 0,
17940b57cec5SDimitry Andric               (getNumWords(BitWidth) - lhsWords) * APINT_WORD_SIZE);
17950b57cec5SDimitry Andric   std::memset(Remainder.U.pVal + rhsWords, 0,
17960b57cec5SDimitry Andric               (getNumWords(BitWidth) - rhsWords) * APINT_WORD_SIZE);
17970b57cec5SDimitry Andric }
17980b57cec5SDimitry Andric 
17990b57cec5SDimitry Andric void APInt::udivrem(const APInt &LHS, uint64_t RHS, APInt &Quotient,
18000b57cec5SDimitry Andric                     uint64_t &Remainder) {
18010b57cec5SDimitry Andric   assert(RHS != 0 && "Divide by zero?");
18020b57cec5SDimitry Andric   unsigned BitWidth = LHS.BitWidth;
18030b57cec5SDimitry Andric 
18040b57cec5SDimitry Andric   // First, deal with the easy case
18050b57cec5SDimitry Andric   if (LHS.isSingleWord()) {
18060b57cec5SDimitry Andric     uint64_t QuotVal = LHS.U.VAL / RHS;
18070b57cec5SDimitry Andric     Remainder = LHS.U.VAL % RHS;
18080b57cec5SDimitry Andric     Quotient = APInt(BitWidth, QuotVal);
18090b57cec5SDimitry Andric     return;
18100b57cec5SDimitry Andric   }
18110b57cec5SDimitry Andric 
18120b57cec5SDimitry Andric   // Get some size facts about the dividend and divisor
18130b57cec5SDimitry Andric   unsigned lhsWords = getNumWords(LHS.getActiveBits());
18140b57cec5SDimitry Andric 
18150b57cec5SDimitry Andric   // Check the degenerate cases
18160b57cec5SDimitry Andric   if (lhsWords == 0) {
18170b57cec5SDimitry Andric     Quotient = APInt(BitWidth, 0);    // 0 / Y ===> 0
18180b57cec5SDimitry Andric     Remainder = 0;                    // 0 % Y ===> 0
18190b57cec5SDimitry Andric     return;
18200b57cec5SDimitry Andric   }
18210b57cec5SDimitry Andric 
18220b57cec5SDimitry Andric   if (RHS == 1) {
18230b57cec5SDimitry Andric     Quotient = LHS;                   // X / 1 ===> X
18240b57cec5SDimitry Andric     Remainder = 0;                    // X % 1 ===> 0
18250b57cec5SDimitry Andric     return;
18260b57cec5SDimitry Andric   }
18270b57cec5SDimitry Andric 
18280b57cec5SDimitry Andric   if (LHS.ult(RHS)) {
18290b57cec5SDimitry Andric     Remainder = LHS.getZExtValue();   // X % Y ===> X, iff X < Y
18300b57cec5SDimitry Andric     Quotient = APInt(BitWidth, 0);    // X / Y ===> 0, iff X < Y
18310b57cec5SDimitry Andric     return;
18320b57cec5SDimitry Andric   }
18330b57cec5SDimitry Andric 
18340b57cec5SDimitry Andric   if (LHS == RHS) {
18350b57cec5SDimitry Andric     Quotient  = APInt(BitWidth, 1);   // X / X ===> 1
18360b57cec5SDimitry Andric     Remainder = 0;                    // X % X ===> 0;
18370b57cec5SDimitry Andric     return;
18380b57cec5SDimitry Andric   }
18390b57cec5SDimitry Andric 
18400b57cec5SDimitry Andric   // Make sure there is enough space to hold the results.
18410b57cec5SDimitry Andric   // NOTE: This assumes that reallocate won't affect any bits if it doesn't
18420b57cec5SDimitry Andric   // change the size. This is necessary if Quotient is aliased with LHS.
18430b57cec5SDimitry Andric   Quotient.reallocate(BitWidth);
18440b57cec5SDimitry Andric 
18450b57cec5SDimitry Andric   if (lhsWords == 1) { // rhsWords is 1 if lhsWords is 1.
18460b57cec5SDimitry Andric     // There is only one word to consider so use the native versions.
18470b57cec5SDimitry Andric     uint64_t lhsValue = LHS.U.pVal[0];
18480b57cec5SDimitry Andric     Quotient = lhsValue / RHS;
18490b57cec5SDimitry Andric     Remainder = lhsValue % RHS;
18500b57cec5SDimitry Andric     return;
18510b57cec5SDimitry Andric   }
18520b57cec5SDimitry Andric 
18530b57cec5SDimitry Andric   // Okay, lets do it the long way
18540b57cec5SDimitry Andric   divide(LHS.U.pVal, lhsWords, &RHS, 1, Quotient.U.pVal, &Remainder);
18550b57cec5SDimitry Andric   // Clear the rest of the Quotient.
18560b57cec5SDimitry Andric   std::memset(Quotient.U.pVal + lhsWords, 0,
18570b57cec5SDimitry Andric               (getNumWords(BitWidth) - lhsWords) * APINT_WORD_SIZE);
18580b57cec5SDimitry Andric }
18590b57cec5SDimitry Andric 
18600b57cec5SDimitry Andric void APInt::sdivrem(const APInt &LHS, const APInt &RHS,
18610b57cec5SDimitry Andric                     APInt &Quotient, APInt &Remainder) {
18620b57cec5SDimitry Andric   if (LHS.isNegative()) {
18630b57cec5SDimitry Andric     if (RHS.isNegative())
18640b57cec5SDimitry Andric       APInt::udivrem(-LHS, -RHS, Quotient, Remainder);
18650b57cec5SDimitry Andric     else {
18660b57cec5SDimitry Andric       APInt::udivrem(-LHS, RHS, Quotient, Remainder);
18670b57cec5SDimitry Andric       Quotient.negate();
18680b57cec5SDimitry Andric     }
18690b57cec5SDimitry Andric     Remainder.negate();
18700b57cec5SDimitry Andric   } else if (RHS.isNegative()) {
18710b57cec5SDimitry Andric     APInt::udivrem(LHS, -RHS, Quotient, Remainder);
18720b57cec5SDimitry Andric     Quotient.negate();
18730b57cec5SDimitry Andric   } else {
18740b57cec5SDimitry Andric     APInt::udivrem(LHS, RHS, Quotient, Remainder);
18750b57cec5SDimitry Andric   }
18760b57cec5SDimitry Andric }
18770b57cec5SDimitry Andric 
18780b57cec5SDimitry Andric void APInt::sdivrem(const APInt &LHS, int64_t RHS,
18790b57cec5SDimitry Andric                     APInt &Quotient, int64_t &Remainder) {
18800b57cec5SDimitry Andric   uint64_t R = Remainder;
18810b57cec5SDimitry Andric   if (LHS.isNegative()) {
18820b57cec5SDimitry Andric     if (RHS < 0)
18830b57cec5SDimitry Andric       APInt::udivrem(-LHS, -RHS, Quotient, R);
18840b57cec5SDimitry Andric     else {
18850b57cec5SDimitry Andric       APInt::udivrem(-LHS, RHS, Quotient, R);
18860b57cec5SDimitry Andric       Quotient.negate();
18870b57cec5SDimitry Andric     }
18880b57cec5SDimitry Andric     R = -R;
18890b57cec5SDimitry Andric   } else if (RHS < 0) {
18900b57cec5SDimitry Andric     APInt::udivrem(LHS, -RHS, Quotient, R);
18910b57cec5SDimitry Andric     Quotient.negate();
18920b57cec5SDimitry Andric   } else {
18930b57cec5SDimitry Andric     APInt::udivrem(LHS, RHS, Quotient, R);
18940b57cec5SDimitry Andric   }
18950b57cec5SDimitry Andric   Remainder = R;
18960b57cec5SDimitry Andric }
18970b57cec5SDimitry Andric 
18980b57cec5SDimitry Andric APInt APInt::sadd_ov(const APInt &RHS, bool &Overflow) const {
18990b57cec5SDimitry Andric   APInt Res = *this+RHS;
19000b57cec5SDimitry Andric   Overflow = isNonNegative() == RHS.isNonNegative() &&
19010b57cec5SDimitry Andric              Res.isNonNegative() != isNonNegative();
19020b57cec5SDimitry Andric   return Res;
19030b57cec5SDimitry Andric }
19040b57cec5SDimitry Andric 
19050b57cec5SDimitry Andric APInt APInt::uadd_ov(const APInt &RHS, bool &Overflow) const {
19060b57cec5SDimitry Andric   APInt Res = *this+RHS;
19070b57cec5SDimitry Andric   Overflow = Res.ult(RHS);
19080b57cec5SDimitry Andric   return Res;
19090b57cec5SDimitry Andric }
19100b57cec5SDimitry Andric 
19110b57cec5SDimitry Andric APInt APInt::ssub_ov(const APInt &RHS, bool &Overflow) const {
19120b57cec5SDimitry Andric   APInt Res = *this - RHS;
19130b57cec5SDimitry Andric   Overflow = isNonNegative() != RHS.isNonNegative() &&
19140b57cec5SDimitry Andric              Res.isNonNegative() != isNonNegative();
19150b57cec5SDimitry Andric   return Res;
19160b57cec5SDimitry Andric }
19170b57cec5SDimitry Andric 
19180b57cec5SDimitry Andric APInt APInt::usub_ov(const APInt &RHS, bool &Overflow) const {
19190b57cec5SDimitry Andric   APInt Res = *this-RHS;
19200b57cec5SDimitry Andric   Overflow = Res.ugt(*this);
19210b57cec5SDimitry Andric   return Res;
19220b57cec5SDimitry Andric }
19230b57cec5SDimitry Andric 
19240b57cec5SDimitry Andric APInt APInt::sdiv_ov(const APInt &RHS, bool &Overflow) const {
19250b57cec5SDimitry Andric   // MININT/-1  -->  overflow.
1926349cc55cSDimitry Andric   Overflow = isMinSignedValue() && RHS.isAllOnes();
19270b57cec5SDimitry Andric   return sdiv(RHS);
19280b57cec5SDimitry Andric }
19290b57cec5SDimitry Andric 
19300b57cec5SDimitry Andric APInt APInt::smul_ov(const APInt &RHS, bool &Overflow) const {
19310b57cec5SDimitry Andric   APInt Res = *this * RHS;
19320b57cec5SDimitry Andric 
1933349cc55cSDimitry Andric   if (RHS != 0)
1934349cc55cSDimitry Andric     Overflow = Res.sdiv(RHS) != *this ||
1935349cc55cSDimitry Andric                (isMinSignedValue() && RHS.isAllOnes());
19360b57cec5SDimitry Andric   else
19370b57cec5SDimitry Andric     Overflow = false;
19380b57cec5SDimitry Andric   return Res;
19390b57cec5SDimitry Andric }
19400b57cec5SDimitry Andric 
19410b57cec5SDimitry Andric APInt APInt::umul_ov(const APInt &RHS, bool &Overflow) const {
194206c3fb27SDimitry Andric   if (countl_zero() + RHS.countl_zero() + 2 <= BitWidth) {
19430b57cec5SDimitry Andric     Overflow = true;
19440b57cec5SDimitry Andric     return *this * RHS;
19450b57cec5SDimitry Andric   }
19460b57cec5SDimitry Andric 
19470b57cec5SDimitry Andric   APInt Res = lshr(1) * RHS;
19480b57cec5SDimitry Andric   Overflow = Res.isNegative();
19490b57cec5SDimitry Andric   Res <<= 1;
19500b57cec5SDimitry Andric   if ((*this)[0]) {
19510b57cec5SDimitry Andric     Res += RHS;
19520b57cec5SDimitry Andric     if (Res.ult(RHS))
19530b57cec5SDimitry Andric       Overflow = true;
19540b57cec5SDimitry Andric   }
19550b57cec5SDimitry Andric   return Res;
19560b57cec5SDimitry Andric }
19570b57cec5SDimitry Andric 
19580b57cec5SDimitry Andric APInt APInt::sshl_ov(const APInt &ShAmt, bool &Overflow) const {
195906c3fb27SDimitry Andric   return sshl_ov(ShAmt.getLimitedValue(getBitWidth()), Overflow);
196006c3fb27SDimitry Andric }
196106c3fb27SDimitry Andric 
196206c3fb27SDimitry Andric APInt APInt::sshl_ov(unsigned ShAmt, bool &Overflow) const {
196306c3fb27SDimitry Andric   Overflow = ShAmt >= getBitWidth();
19640b57cec5SDimitry Andric   if (Overflow)
19650b57cec5SDimitry Andric     return APInt(BitWidth, 0);
19660b57cec5SDimitry Andric 
19670b57cec5SDimitry Andric   if (isNonNegative()) // Don't allow sign change.
196806c3fb27SDimitry Andric     Overflow = ShAmt >= countl_zero();
19690b57cec5SDimitry Andric   else
197006c3fb27SDimitry Andric     Overflow = ShAmt >= countl_one();
19710b57cec5SDimitry Andric 
19720b57cec5SDimitry Andric   return *this << ShAmt;
19730b57cec5SDimitry Andric }
19740b57cec5SDimitry Andric 
19750b57cec5SDimitry Andric APInt APInt::ushl_ov(const APInt &ShAmt, bool &Overflow) const {
197606c3fb27SDimitry Andric   return ushl_ov(ShAmt.getLimitedValue(getBitWidth()), Overflow);
197706c3fb27SDimitry Andric }
197806c3fb27SDimitry Andric 
197906c3fb27SDimitry Andric APInt APInt::ushl_ov(unsigned ShAmt, bool &Overflow) const {
198006c3fb27SDimitry Andric   Overflow = ShAmt >= getBitWidth();
19810b57cec5SDimitry Andric   if (Overflow)
19820b57cec5SDimitry Andric     return APInt(BitWidth, 0);
19830b57cec5SDimitry Andric 
198406c3fb27SDimitry Andric   Overflow = ShAmt > countl_zero();
19850b57cec5SDimitry Andric 
19860b57cec5SDimitry Andric   return *this << ShAmt;
19870b57cec5SDimitry Andric }
19880b57cec5SDimitry Andric 
1989*0fca6ea1SDimitry Andric APInt APInt::sfloordiv_ov(const APInt &RHS, bool &Overflow) const {
1990*0fca6ea1SDimitry Andric   APInt quotient = sdiv_ov(RHS, Overflow);
1991*0fca6ea1SDimitry Andric   if ((quotient * RHS != *this) && (isNegative() != RHS.isNegative()))
1992*0fca6ea1SDimitry Andric     return quotient - 1;
1993*0fca6ea1SDimitry Andric   return quotient;
1994*0fca6ea1SDimitry Andric }
1995*0fca6ea1SDimitry Andric 
19960b57cec5SDimitry Andric APInt APInt::sadd_sat(const APInt &RHS) const {
19970b57cec5SDimitry Andric   bool Overflow;
19980b57cec5SDimitry Andric   APInt Res = sadd_ov(RHS, Overflow);
19990b57cec5SDimitry Andric   if (!Overflow)
20000b57cec5SDimitry Andric     return Res;
20010b57cec5SDimitry Andric 
20020b57cec5SDimitry Andric   return isNegative() ? APInt::getSignedMinValue(BitWidth)
20030b57cec5SDimitry Andric                       : APInt::getSignedMaxValue(BitWidth);
20040b57cec5SDimitry Andric }
20050b57cec5SDimitry Andric 
20060b57cec5SDimitry Andric APInt APInt::uadd_sat(const APInt &RHS) const {
20070b57cec5SDimitry Andric   bool Overflow;
20080b57cec5SDimitry Andric   APInt Res = uadd_ov(RHS, Overflow);
20090b57cec5SDimitry Andric   if (!Overflow)
20100b57cec5SDimitry Andric     return Res;
20110b57cec5SDimitry Andric 
20120b57cec5SDimitry Andric   return APInt::getMaxValue(BitWidth);
20130b57cec5SDimitry Andric }
20140b57cec5SDimitry Andric 
20150b57cec5SDimitry Andric APInt APInt::ssub_sat(const APInt &RHS) const {
20160b57cec5SDimitry Andric   bool Overflow;
20170b57cec5SDimitry Andric   APInt Res = ssub_ov(RHS, Overflow);
20180b57cec5SDimitry Andric   if (!Overflow)
20190b57cec5SDimitry Andric     return Res;
20200b57cec5SDimitry Andric 
20210b57cec5SDimitry Andric   return isNegative() ? APInt::getSignedMinValue(BitWidth)
20220b57cec5SDimitry Andric                       : APInt::getSignedMaxValue(BitWidth);
20230b57cec5SDimitry Andric }
20240b57cec5SDimitry Andric 
20250b57cec5SDimitry Andric APInt APInt::usub_sat(const APInt &RHS) const {
20260b57cec5SDimitry Andric   bool Overflow;
20270b57cec5SDimitry Andric   APInt Res = usub_ov(RHS, Overflow);
20280b57cec5SDimitry Andric   if (!Overflow)
20290b57cec5SDimitry Andric     return Res;
20300b57cec5SDimitry Andric 
20310b57cec5SDimitry Andric   return APInt(BitWidth, 0);
20320b57cec5SDimitry Andric }
20330b57cec5SDimitry Andric 
2034480093f4SDimitry Andric APInt APInt::smul_sat(const APInt &RHS) const {
2035480093f4SDimitry Andric   bool Overflow;
2036480093f4SDimitry Andric   APInt Res = smul_ov(RHS, Overflow);
2037480093f4SDimitry Andric   if (!Overflow)
2038480093f4SDimitry Andric     return Res;
2039480093f4SDimitry Andric 
2040480093f4SDimitry Andric   // The result is negative if one and only one of inputs is negative.
2041480093f4SDimitry Andric   bool ResIsNegative = isNegative() ^ RHS.isNegative();
2042480093f4SDimitry Andric 
2043480093f4SDimitry Andric   return ResIsNegative ? APInt::getSignedMinValue(BitWidth)
2044480093f4SDimitry Andric                        : APInt::getSignedMaxValue(BitWidth);
2045480093f4SDimitry Andric }
2046480093f4SDimitry Andric 
2047480093f4SDimitry Andric APInt APInt::umul_sat(const APInt &RHS) const {
2048480093f4SDimitry Andric   bool Overflow;
2049480093f4SDimitry Andric   APInt Res = umul_ov(RHS, Overflow);
2050480093f4SDimitry Andric   if (!Overflow)
2051480093f4SDimitry Andric     return Res;
2052480093f4SDimitry Andric 
2053480093f4SDimitry Andric   return APInt::getMaxValue(BitWidth);
2054480093f4SDimitry Andric }
2055480093f4SDimitry Andric 
2056480093f4SDimitry Andric APInt APInt::sshl_sat(const APInt &RHS) const {
205706c3fb27SDimitry Andric   return sshl_sat(RHS.getLimitedValue(getBitWidth()));
205806c3fb27SDimitry Andric }
205906c3fb27SDimitry Andric 
206006c3fb27SDimitry Andric APInt APInt::sshl_sat(unsigned RHS) const {
2061480093f4SDimitry Andric   bool Overflow;
2062480093f4SDimitry Andric   APInt Res = sshl_ov(RHS, Overflow);
2063480093f4SDimitry Andric   if (!Overflow)
2064480093f4SDimitry Andric     return Res;
2065480093f4SDimitry Andric 
2066480093f4SDimitry Andric   return isNegative() ? APInt::getSignedMinValue(BitWidth)
2067480093f4SDimitry Andric                       : APInt::getSignedMaxValue(BitWidth);
2068480093f4SDimitry Andric }
2069480093f4SDimitry Andric 
2070480093f4SDimitry Andric APInt APInt::ushl_sat(const APInt &RHS) const {
207106c3fb27SDimitry Andric   return ushl_sat(RHS.getLimitedValue(getBitWidth()));
207206c3fb27SDimitry Andric }
207306c3fb27SDimitry Andric 
207406c3fb27SDimitry Andric APInt APInt::ushl_sat(unsigned RHS) const {
2075480093f4SDimitry Andric   bool Overflow;
2076480093f4SDimitry Andric   APInt Res = ushl_ov(RHS, Overflow);
2077480093f4SDimitry Andric   if (!Overflow)
2078480093f4SDimitry Andric     return Res;
2079480093f4SDimitry Andric 
2080480093f4SDimitry Andric   return APInt::getMaxValue(BitWidth);
2081480093f4SDimitry Andric }
20820b57cec5SDimitry Andric 
20830b57cec5SDimitry Andric void APInt::fromString(unsigned numbits, StringRef str, uint8_t radix) {
20840b57cec5SDimitry Andric   // Check our assumptions here
20850b57cec5SDimitry Andric   assert(!str.empty() && "Invalid string length");
20860b57cec5SDimitry Andric   assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 ||
20870b57cec5SDimitry Andric           radix == 36) &&
20880b57cec5SDimitry Andric          "Radix should be 2, 8, 10, 16, or 36!");
20890b57cec5SDimitry Andric 
20900b57cec5SDimitry Andric   StringRef::iterator p = str.begin();
20910b57cec5SDimitry Andric   size_t slen = str.size();
20920b57cec5SDimitry Andric   bool isNeg = *p == '-';
20930b57cec5SDimitry Andric   if (*p == '-' || *p == '+') {
20940b57cec5SDimitry Andric     p++;
20950b57cec5SDimitry Andric     slen--;
20960b57cec5SDimitry Andric     assert(slen && "String is only a sign, needs a value.");
20970b57cec5SDimitry Andric   }
20980b57cec5SDimitry Andric   assert((slen <= numbits || radix != 2) && "Insufficient bit width");
20990b57cec5SDimitry Andric   assert(((slen-1)*3 <= numbits || radix != 8) && "Insufficient bit width");
21000b57cec5SDimitry Andric   assert(((slen-1)*4 <= numbits || radix != 16) && "Insufficient bit width");
21010b57cec5SDimitry Andric   assert((((slen-1)*64)/22 <= numbits || radix != 10) &&
21020b57cec5SDimitry Andric          "Insufficient bit width");
21030b57cec5SDimitry Andric 
21040b57cec5SDimitry Andric   // Allocate memory if needed
21050b57cec5SDimitry Andric   if (isSingleWord())
21060b57cec5SDimitry Andric     U.VAL = 0;
21070b57cec5SDimitry Andric   else
21080b57cec5SDimitry Andric     U.pVal = getClearedMemory(getNumWords());
21090b57cec5SDimitry Andric 
21100b57cec5SDimitry Andric   // Figure out if we can shift instead of multiply
21110b57cec5SDimitry Andric   unsigned shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0);
21120b57cec5SDimitry Andric 
21130b57cec5SDimitry Andric   // Enter digit traversal loop
21140b57cec5SDimitry Andric   for (StringRef::iterator e = str.end(); p != e; ++p) {
21150b57cec5SDimitry Andric     unsigned digit = getDigit(*p, radix);
21160b57cec5SDimitry Andric     assert(digit < radix && "Invalid character in digit string");
21170b57cec5SDimitry Andric 
21180b57cec5SDimitry Andric     // Shift or multiply the value by the radix
21190b57cec5SDimitry Andric     if (slen > 1) {
21200b57cec5SDimitry Andric       if (shift)
21210b57cec5SDimitry Andric         *this <<= shift;
21220b57cec5SDimitry Andric       else
21230b57cec5SDimitry Andric         *this *= radix;
21240b57cec5SDimitry Andric     }
21250b57cec5SDimitry Andric 
21260b57cec5SDimitry Andric     // Add in the digit we just interpreted
21270b57cec5SDimitry Andric     *this += digit;
21280b57cec5SDimitry Andric   }
21290b57cec5SDimitry Andric   // If its negative, put it in two's complement form
21300b57cec5SDimitry Andric   if (isNeg)
21310b57cec5SDimitry Andric     this->negate();
21320b57cec5SDimitry Andric }
21330b57cec5SDimitry Andric 
213406c3fb27SDimitry Andric void APInt::toString(SmallVectorImpl<char> &Str, unsigned Radix, bool Signed,
2135*0fca6ea1SDimitry Andric                      bool formatAsCLiteral, bool UpperCase,
2136*0fca6ea1SDimitry Andric                      bool InsertSeparators) const {
21370b57cec5SDimitry Andric   assert((Radix == 10 || Radix == 8 || Radix == 16 || Radix == 2 ||
21380b57cec5SDimitry Andric           Radix == 36) &&
21390b57cec5SDimitry Andric          "Radix should be 2, 8, 10, 16, or 36!");
21400b57cec5SDimitry Andric 
21410b57cec5SDimitry Andric   const char *Prefix = "";
21420b57cec5SDimitry Andric   if (formatAsCLiteral) {
21430b57cec5SDimitry Andric     switch (Radix) {
21440b57cec5SDimitry Andric       case 2:
21450b57cec5SDimitry Andric         // Binary literals are a non-standard extension added in gcc 4.3:
21460b57cec5SDimitry Andric         // http://gcc.gnu.org/onlinedocs/gcc-4.3.0/gcc/Binary-constants.html
21470b57cec5SDimitry Andric         Prefix = "0b";
21480b57cec5SDimitry Andric         break;
21490b57cec5SDimitry Andric       case 8:
21500b57cec5SDimitry Andric         Prefix = "0";
21510b57cec5SDimitry Andric         break;
21520b57cec5SDimitry Andric       case 10:
21530b57cec5SDimitry Andric         break; // No prefix
21540b57cec5SDimitry Andric       case 16:
21550b57cec5SDimitry Andric         Prefix = "0x";
21560b57cec5SDimitry Andric         break;
21570b57cec5SDimitry Andric       default:
21580b57cec5SDimitry Andric         llvm_unreachable("Invalid radix!");
21590b57cec5SDimitry Andric     }
21600b57cec5SDimitry Andric   }
21610b57cec5SDimitry Andric 
2162*0fca6ea1SDimitry Andric   // Number of digits in a group between separators.
2163*0fca6ea1SDimitry Andric   unsigned Grouping = (Radix == 8 || Radix == 10) ? 3 : 4;
2164*0fca6ea1SDimitry Andric 
21650b57cec5SDimitry Andric   // First, check for a zero value and just short circuit the logic below.
2166349cc55cSDimitry Andric   if (isZero()) {
21670b57cec5SDimitry Andric     while (*Prefix) {
21680b57cec5SDimitry Andric       Str.push_back(*Prefix);
21690b57cec5SDimitry Andric       ++Prefix;
21700b57cec5SDimitry Andric     };
21710b57cec5SDimitry Andric     Str.push_back('0');
21720b57cec5SDimitry Andric     return;
21730b57cec5SDimitry Andric   }
21740b57cec5SDimitry Andric 
217506c3fb27SDimitry Andric   static const char BothDigits[] = "0123456789abcdefghijklmnopqrstuvwxyz"
217606c3fb27SDimitry Andric                                    "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
217706c3fb27SDimitry Andric   const char *Digits = BothDigits + (UpperCase ? 36 : 0);
21780b57cec5SDimitry Andric 
21790b57cec5SDimitry Andric   if (isSingleWord()) {
21800b57cec5SDimitry Andric     char Buffer[65];
21810b57cec5SDimitry Andric     char *BufPtr = std::end(Buffer);
21820b57cec5SDimitry Andric 
21830b57cec5SDimitry Andric     uint64_t N;
21840b57cec5SDimitry Andric     if (!Signed) {
21850b57cec5SDimitry Andric       N = getZExtValue();
21860b57cec5SDimitry Andric     } else {
21870b57cec5SDimitry Andric       int64_t I = getSExtValue();
21880b57cec5SDimitry Andric       if (I >= 0) {
21890b57cec5SDimitry Andric         N = I;
21900b57cec5SDimitry Andric       } else {
21910b57cec5SDimitry Andric         Str.push_back('-');
21920b57cec5SDimitry Andric         N = -(uint64_t)I;
21930b57cec5SDimitry Andric       }
21940b57cec5SDimitry Andric     }
21950b57cec5SDimitry Andric 
21960b57cec5SDimitry Andric     while (*Prefix) {
21970b57cec5SDimitry Andric       Str.push_back(*Prefix);
21980b57cec5SDimitry Andric       ++Prefix;
21990b57cec5SDimitry Andric     };
22000b57cec5SDimitry Andric 
2201*0fca6ea1SDimitry Andric     int Pos = 0;
22020b57cec5SDimitry Andric     while (N) {
2203*0fca6ea1SDimitry Andric       if (InsertSeparators && Pos % Grouping == 0 && Pos > 0)
2204*0fca6ea1SDimitry Andric         *--BufPtr = '\'';
22050b57cec5SDimitry Andric       *--BufPtr = Digits[N % Radix];
22060b57cec5SDimitry Andric       N /= Radix;
2207*0fca6ea1SDimitry Andric       Pos++;
22080b57cec5SDimitry Andric     }
22090b57cec5SDimitry Andric     Str.append(BufPtr, std::end(Buffer));
22100b57cec5SDimitry Andric     return;
22110b57cec5SDimitry Andric   }
22120b57cec5SDimitry Andric 
22130b57cec5SDimitry Andric   APInt Tmp(*this);
22140b57cec5SDimitry Andric 
22150b57cec5SDimitry Andric   if (Signed && isNegative()) {
22160b57cec5SDimitry Andric     // They want to print the signed version and it is a negative value
22170b57cec5SDimitry Andric     // Flip the bits and add one to turn it into the equivalent positive
22180b57cec5SDimitry Andric     // value and put a '-' in the result.
22190b57cec5SDimitry Andric     Tmp.negate();
22200b57cec5SDimitry Andric     Str.push_back('-');
22210b57cec5SDimitry Andric   }
22220b57cec5SDimitry Andric 
22230b57cec5SDimitry Andric   while (*Prefix) {
22240b57cec5SDimitry Andric     Str.push_back(*Prefix);
22250b57cec5SDimitry Andric     ++Prefix;
22260b57cec5SDimitry Andric   };
22270b57cec5SDimitry Andric 
22280b57cec5SDimitry Andric   // We insert the digits backward, then reverse them to get the right order.
22290b57cec5SDimitry Andric   unsigned StartDig = Str.size();
22300b57cec5SDimitry Andric 
22310b57cec5SDimitry Andric   // For the 2, 8 and 16 bit cases, we can just shift instead of divide
22320b57cec5SDimitry Andric   // because the number of bits per digit (1, 3 and 4 respectively) divides
22330b57cec5SDimitry Andric   // equally.  We just shift until the value is zero.
22340b57cec5SDimitry Andric   if (Radix == 2 || Radix == 8 || Radix == 16) {
22350b57cec5SDimitry Andric     // Just shift tmp right for each digit width until it becomes zero
22360b57cec5SDimitry Andric     unsigned ShiftAmt = (Radix == 16 ? 4 : (Radix == 8 ? 3 : 1));
22370b57cec5SDimitry Andric     unsigned MaskAmt = Radix - 1;
22380b57cec5SDimitry Andric 
2239*0fca6ea1SDimitry Andric     int Pos = 0;
22400b57cec5SDimitry Andric     while (Tmp.getBoolValue()) {
22410b57cec5SDimitry Andric       unsigned Digit = unsigned(Tmp.getRawData()[0]) & MaskAmt;
2242*0fca6ea1SDimitry Andric       if (InsertSeparators && Pos % Grouping == 0 && Pos > 0)
2243*0fca6ea1SDimitry Andric         Str.push_back('\'');
2244*0fca6ea1SDimitry Andric 
22450b57cec5SDimitry Andric       Str.push_back(Digits[Digit]);
22460b57cec5SDimitry Andric       Tmp.lshrInPlace(ShiftAmt);
2247*0fca6ea1SDimitry Andric       Pos++;
22480b57cec5SDimitry Andric     }
22490b57cec5SDimitry Andric   } else {
2250*0fca6ea1SDimitry Andric     int Pos = 0;
22510b57cec5SDimitry Andric     while (Tmp.getBoolValue()) {
22520b57cec5SDimitry Andric       uint64_t Digit;
22530b57cec5SDimitry Andric       udivrem(Tmp, Radix, Tmp, Digit);
22540b57cec5SDimitry Andric       assert(Digit < Radix && "divide failed");
2255*0fca6ea1SDimitry Andric       if (InsertSeparators && Pos % Grouping == 0 && Pos > 0)
2256*0fca6ea1SDimitry Andric         Str.push_back('\'');
2257*0fca6ea1SDimitry Andric 
22580b57cec5SDimitry Andric       Str.push_back(Digits[Digit]);
2259*0fca6ea1SDimitry Andric       Pos++;
22600b57cec5SDimitry Andric     }
22610b57cec5SDimitry Andric   }
22620b57cec5SDimitry Andric 
22630b57cec5SDimitry Andric   // Reverse the digits before returning.
22640b57cec5SDimitry Andric   std::reverse(Str.begin()+StartDig, Str.end());
22650b57cec5SDimitry Andric }
22660b57cec5SDimitry Andric 
22670b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
22680b57cec5SDimitry Andric LLVM_DUMP_METHOD void APInt::dump() const {
22690b57cec5SDimitry Andric   SmallString<40> S, U;
22700b57cec5SDimitry Andric   this->toStringUnsigned(U);
22710b57cec5SDimitry Andric   this->toStringSigned(S);
22720b57cec5SDimitry Andric   dbgs() << "APInt(" << BitWidth << "b, "
22730b57cec5SDimitry Andric          << U << "u " << S << "s)\n";
22740b57cec5SDimitry Andric }
22750b57cec5SDimitry Andric #endif
22760b57cec5SDimitry Andric 
22770b57cec5SDimitry Andric void APInt::print(raw_ostream &OS, bool isSigned) const {
22780b57cec5SDimitry Andric   SmallString<40> S;
22790b57cec5SDimitry Andric   this->toString(S, 10, isSigned, /* formatAsCLiteral = */false);
22800b57cec5SDimitry Andric   OS << S;
22810b57cec5SDimitry Andric }
22820b57cec5SDimitry Andric 
22830b57cec5SDimitry Andric // This implements a variety of operations on a representation of
22840b57cec5SDimitry Andric // arbitrary precision, two's-complement, bignum integer values.
22850b57cec5SDimitry Andric 
22860b57cec5SDimitry Andric // Assumed by lowHalf, highHalf, partMSB and partLSB.  A fairly safe
22870b57cec5SDimitry Andric // and unrestricting assumption.
22880b57cec5SDimitry Andric static_assert(APInt::APINT_BITS_PER_WORD % 2 == 0,
22890b57cec5SDimitry Andric               "Part width must be divisible by 2!");
22900b57cec5SDimitry Andric 
2291349cc55cSDimitry Andric // Returns the integer part with the least significant BITS set.
2292349cc55cSDimitry Andric // BITS cannot be zero.
22930b57cec5SDimitry Andric static inline APInt::WordType lowBitMask(unsigned bits) {
22940b57cec5SDimitry Andric   assert(bits != 0 && bits <= APInt::APINT_BITS_PER_WORD);
22950b57cec5SDimitry Andric   return ~(APInt::WordType) 0 >> (APInt::APINT_BITS_PER_WORD - bits);
22960b57cec5SDimitry Andric }
22970b57cec5SDimitry Andric 
2298349cc55cSDimitry Andric /// Returns the value of the lower half of PART.
22990b57cec5SDimitry Andric static inline APInt::WordType lowHalf(APInt::WordType part) {
23000b57cec5SDimitry Andric   return part & lowBitMask(APInt::APINT_BITS_PER_WORD / 2);
23010b57cec5SDimitry Andric }
23020b57cec5SDimitry Andric 
2303349cc55cSDimitry Andric /// Returns the value of the upper half of PART.
23040b57cec5SDimitry Andric static inline APInt::WordType highHalf(APInt::WordType part) {
23050b57cec5SDimitry Andric   return part >> (APInt::APINT_BITS_PER_WORD / 2);
23060b57cec5SDimitry Andric }
23070b57cec5SDimitry Andric 
2308349cc55cSDimitry Andric /// Sets the least significant part of a bignum to the input value, and zeroes
2309349cc55cSDimitry Andric /// out higher parts.
23100b57cec5SDimitry Andric void APInt::tcSet(WordType *dst, WordType part, unsigned parts) {
23110b57cec5SDimitry Andric   assert(parts > 0);
23120b57cec5SDimitry Andric   dst[0] = part;
23130b57cec5SDimitry Andric   for (unsigned i = 1; i < parts; i++)
23140b57cec5SDimitry Andric     dst[i] = 0;
23150b57cec5SDimitry Andric }
23160b57cec5SDimitry Andric 
2317349cc55cSDimitry Andric /// Assign one bignum to another.
23180b57cec5SDimitry Andric void APInt::tcAssign(WordType *dst, const WordType *src, unsigned parts) {
23190b57cec5SDimitry Andric   for (unsigned i = 0; i < parts; i++)
23200b57cec5SDimitry Andric     dst[i] = src[i];
23210b57cec5SDimitry Andric }
23220b57cec5SDimitry Andric 
2323349cc55cSDimitry Andric /// Returns true if a bignum is zero, false otherwise.
23240b57cec5SDimitry Andric bool APInt::tcIsZero(const WordType *src, unsigned parts) {
23250b57cec5SDimitry Andric   for (unsigned i = 0; i < parts; i++)
23260b57cec5SDimitry Andric     if (src[i])
23270b57cec5SDimitry Andric       return false;
23280b57cec5SDimitry Andric 
23290b57cec5SDimitry Andric   return true;
23300b57cec5SDimitry Andric }
23310b57cec5SDimitry Andric 
2332349cc55cSDimitry Andric /// Extract the given bit of a bignum; returns 0 or 1.
23330b57cec5SDimitry Andric int APInt::tcExtractBit(const WordType *parts, unsigned bit) {
23340b57cec5SDimitry Andric   return (parts[whichWord(bit)] & maskBit(bit)) != 0;
23350b57cec5SDimitry Andric }
23360b57cec5SDimitry Andric 
2337349cc55cSDimitry Andric /// Set the given bit of a bignum.
23380b57cec5SDimitry Andric void APInt::tcSetBit(WordType *parts, unsigned bit) {
23390b57cec5SDimitry Andric   parts[whichWord(bit)] |= maskBit(bit);
23400b57cec5SDimitry Andric }
23410b57cec5SDimitry Andric 
2342349cc55cSDimitry Andric /// Clears the given bit of a bignum.
23430b57cec5SDimitry Andric void APInt::tcClearBit(WordType *parts, unsigned bit) {
23440b57cec5SDimitry Andric   parts[whichWord(bit)] &= ~maskBit(bit);
23450b57cec5SDimitry Andric }
23460b57cec5SDimitry Andric 
2347349cc55cSDimitry Andric /// Returns the bit number of the least significant set bit of a number.  If the
234806c3fb27SDimitry Andric /// input number has no bits set UINT_MAX is returned.
23490b57cec5SDimitry Andric unsigned APInt::tcLSB(const WordType *parts, unsigned n) {
23500b57cec5SDimitry Andric   for (unsigned i = 0; i < n; i++) {
23510b57cec5SDimitry Andric     if (parts[i] != 0) {
235206c3fb27SDimitry Andric       unsigned lsb = llvm::countr_zero(parts[i]);
23530b57cec5SDimitry Andric       return lsb + i * APINT_BITS_PER_WORD;
23540b57cec5SDimitry Andric     }
23550b57cec5SDimitry Andric   }
23560b57cec5SDimitry Andric 
235706c3fb27SDimitry Andric   return UINT_MAX;
23580b57cec5SDimitry Andric }
23590b57cec5SDimitry Andric 
2360349cc55cSDimitry Andric /// Returns the bit number of the most significant set bit of a number.
236106c3fb27SDimitry Andric /// If the input number has no bits set UINT_MAX is returned.
23620b57cec5SDimitry Andric unsigned APInt::tcMSB(const WordType *parts, unsigned n) {
23630b57cec5SDimitry Andric   do {
23640b57cec5SDimitry Andric     --n;
23650b57cec5SDimitry Andric 
23660b57cec5SDimitry Andric     if (parts[n] != 0) {
236706c3fb27SDimitry Andric       static_assert(sizeof(parts[n]) <= sizeof(uint64_t));
236806c3fb27SDimitry Andric       unsigned msb = llvm::Log2_64(parts[n]);
23690b57cec5SDimitry Andric 
23700b57cec5SDimitry Andric       return msb + n * APINT_BITS_PER_WORD;
23710b57cec5SDimitry Andric     }
23720b57cec5SDimitry Andric   } while (n);
23730b57cec5SDimitry Andric 
237406c3fb27SDimitry Andric   return UINT_MAX;
23750b57cec5SDimitry Andric }
23760b57cec5SDimitry Andric 
2377349cc55cSDimitry Andric /// Copy the bit vector of width srcBITS from SRC, starting at bit srcLSB, to
2378349cc55cSDimitry Andric /// DST, of dstCOUNT parts, such that the bit srcLSB becomes the least
2379349cc55cSDimitry Andric /// significant bit of DST.  All high bits above srcBITS in DST are zero-filled.
2380349cc55cSDimitry Andric /// */
23810b57cec5SDimitry Andric void
23820b57cec5SDimitry Andric APInt::tcExtract(WordType *dst, unsigned dstCount, const WordType *src,
23830b57cec5SDimitry Andric                  unsigned srcBits, unsigned srcLSB) {
23840b57cec5SDimitry Andric   unsigned dstParts = (srcBits + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
23850b57cec5SDimitry Andric   assert(dstParts <= dstCount);
23860b57cec5SDimitry Andric 
23870b57cec5SDimitry Andric   unsigned firstSrcPart = srcLSB / APINT_BITS_PER_WORD;
23880b57cec5SDimitry Andric   tcAssign(dst, src + firstSrcPart, dstParts);
23890b57cec5SDimitry Andric 
23900b57cec5SDimitry Andric   unsigned shift = srcLSB % APINT_BITS_PER_WORD;
23910b57cec5SDimitry Andric   tcShiftRight(dst, dstParts, shift);
23920b57cec5SDimitry Andric 
2393349cc55cSDimitry Andric   // We now have (dstParts * APINT_BITS_PER_WORD - shift) bits from SRC
2394349cc55cSDimitry Andric   // in DST.  If this is less that srcBits, append the rest, else
2395349cc55cSDimitry Andric   // clear the high bits.
23960b57cec5SDimitry Andric   unsigned n = dstParts * APINT_BITS_PER_WORD - shift;
23970b57cec5SDimitry Andric   if (n < srcBits) {
23980b57cec5SDimitry Andric     WordType mask = lowBitMask (srcBits - n);
23990b57cec5SDimitry Andric     dst[dstParts - 1] |= ((src[firstSrcPart + dstParts] & mask)
24000b57cec5SDimitry Andric                           << n % APINT_BITS_PER_WORD);
24010b57cec5SDimitry Andric   } else if (n > srcBits) {
24020b57cec5SDimitry Andric     if (srcBits % APINT_BITS_PER_WORD)
24030b57cec5SDimitry Andric       dst[dstParts - 1] &= lowBitMask (srcBits % APINT_BITS_PER_WORD);
24040b57cec5SDimitry Andric   }
24050b57cec5SDimitry Andric 
2406349cc55cSDimitry Andric   // Clear high parts.
24070b57cec5SDimitry Andric   while (dstParts < dstCount)
24080b57cec5SDimitry Andric     dst[dstParts++] = 0;
24090b57cec5SDimitry Andric }
24100b57cec5SDimitry Andric 
2411349cc55cSDimitry Andric //// DST += RHS + C where C is zero or one.  Returns the carry flag.
24120b57cec5SDimitry Andric APInt::WordType APInt::tcAdd(WordType *dst, const WordType *rhs,
24130b57cec5SDimitry Andric                              WordType c, unsigned parts) {
24140b57cec5SDimitry Andric   assert(c <= 1);
24150b57cec5SDimitry Andric 
24160b57cec5SDimitry Andric   for (unsigned i = 0; i < parts; i++) {
24170b57cec5SDimitry Andric     WordType l = dst[i];
24180b57cec5SDimitry Andric     if (c) {
24190b57cec5SDimitry Andric       dst[i] += rhs[i] + 1;
24200b57cec5SDimitry Andric       c = (dst[i] <= l);
24210b57cec5SDimitry Andric     } else {
24220b57cec5SDimitry Andric       dst[i] += rhs[i];
24230b57cec5SDimitry Andric       c = (dst[i] < l);
24240b57cec5SDimitry Andric     }
24250b57cec5SDimitry Andric   }
24260b57cec5SDimitry Andric 
24270b57cec5SDimitry Andric   return c;
24280b57cec5SDimitry Andric }
24290b57cec5SDimitry Andric 
24300b57cec5SDimitry Andric /// This function adds a single "word" integer, src, to the multiple
24310b57cec5SDimitry Andric /// "word" integer array, dst[]. dst[] is modified to reflect the addition and
24320b57cec5SDimitry Andric /// 1 is returned if there is a carry out, otherwise 0 is returned.
24330b57cec5SDimitry Andric /// @returns the carry of the addition.
24340b57cec5SDimitry Andric APInt::WordType APInt::tcAddPart(WordType *dst, WordType src,
24350b57cec5SDimitry Andric                                  unsigned parts) {
24360b57cec5SDimitry Andric   for (unsigned i = 0; i < parts; ++i) {
24370b57cec5SDimitry Andric     dst[i] += src;
24380b57cec5SDimitry Andric     if (dst[i] >= src)
24390b57cec5SDimitry Andric       return 0; // No need to carry so exit early.
24400b57cec5SDimitry Andric     src = 1; // Carry one to next digit.
24410b57cec5SDimitry Andric   }
24420b57cec5SDimitry Andric 
24430b57cec5SDimitry Andric   return 1;
24440b57cec5SDimitry Andric }
24450b57cec5SDimitry Andric 
2446349cc55cSDimitry Andric /// DST -= RHS + C where C is zero or one.  Returns the carry flag.
24470b57cec5SDimitry Andric APInt::WordType APInt::tcSubtract(WordType *dst, const WordType *rhs,
24480b57cec5SDimitry Andric                                   WordType c, unsigned parts) {
24490b57cec5SDimitry Andric   assert(c <= 1);
24500b57cec5SDimitry Andric 
24510b57cec5SDimitry Andric   for (unsigned i = 0; i < parts; i++) {
24520b57cec5SDimitry Andric     WordType l = dst[i];
24530b57cec5SDimitry Andric     if (c) {
24540b57cec5SDimitry Andric       dst[i] -= rhs[i] + 1;
24550b57cec5SDimitry Andric       c = (dst[i] >= l);
24560b57cec5SDimitry Andric     } else {
24570b57cec5SDimitry Andric       dst[i] -= rhs[i];
24580b57cec5SDimitry Andric       c = (dst[i] > l);
24590b57cec5SDimitry Andric     }
24600b57cec5SDimitry Andric   }
24610b57cec5SDimitry Andric 
24620b57cec5SDimitry Andric   return c;
24630b57cec5SDimitry Andric }
24640b57cec5SDimitry Andric 
24650b57cec5SDimitry Andric /// This function subtracts a single "word" (64-bit word), src, from
24660b57cec5SDimitry Andric /// the multi-word integer array, dst[], propagating the borrowed 1 value until
24670b57cec5SDimitry Andric /// no further borrowing is needed or it runs out of "words" in dst.  The result
24680b57cec5SDimitry Andric /// is 1 if "borrowing" exhausted the digits in dst, or 0 if dst was not
24690b57cec5SDimitry Andric /// exhausted. In other words, if src > dst then this function returns 1,
24700b57cec5SDimitry Andric /// otherwise 0.
24710b57cec5SDimitry Andric /// @returns the borrow out of the subtraction
24720b57cec5SDimitry Andric APInt::WordType APInt::tcSubtractPart(WordType *dst, WordType src,
24730b57cec5SDimitry Andric                                       unsigned parts) {
24740b57cec5SDimitry Andric   for (unsigned i = 0; i < parts; ++i) {
24750b57cec5SDimitry Andric     WordType Dst = dst[i];
24760b57cec5SDimitry Andric     dst[i] -= src;
24770b57cec5SDimitry Andric     if (src <= Dst)
24780b57cec5SDimitry Andric       return 0; // No need to borrow so exit early.
24790b57cec5SDimitry Andric     src = 1; // We have to "borrow 1" from next "word"
24800b57cec5SDimitry Andric   }
24810b57cec5SDimitry Andric 
24820b57cec5SDimitry Andric   return 1;
24830b57cec5SDimitry Andric }
24840b57cec5SDimitry Andric 
2485349cc55cSDimitry Andric /// Negate a bignum in-place.
24860b57cec5SDimitry Andric void APInt::tcNegate(WordType *dst, unsigned parts) {
24870b57cec5SDimitry Andric   tcComplement(dst, parts);
24880b57cec5SDimitry Andric   tcIncrement(dst, parts);
24890b57cec5SDimitry Andric }
24900b57cec5SDimitry Andric 
2491349cc55cSDimitry Andric /// DST += SRC * MULTIPLIER + CARRY   if add is true
2492349cc55cSDimitry Andric /// DST  = SRC * MULTIPLIER + CARRY   if add is false
2493349cc55cSDimitry Andric /// Requires 0 <= DSTPARTS <= SRCPARTS + 1.  If DST overlaps SRC
2494349cc55cSDimitry Andric /// they must start at the same point, i.e. DST == SRC.
2495349cc55cSDimitry Andric /// If DSTPARTS == SRCPARTS + 1 no overflow occurs and zero is
2496349cc55cSDimitry Andric /// returned.  Otherwise DST is filled with the least significant
2497349cc55cSDimitry Andric /// DSTPARTS parts of the result, and if all of the omitted higher
2498349cc55cSDimitry Andric /// parts were zero return zero, otherwise overflow occurred and
2499349cc55cSDimitry Andric /// return one.
25000b57cec5SDimitry Andric int APInt::tcMultiplyPart(WordType *dst, const WordType *src,
25010b57cec5SDimitry Andric                           WordType multiplier, WordType carry,
25020b57cec5SDimitry Andric                           unsigned srcParts, unsigned dstParts,
25030b57cec5SDimitry Andric                           bool add) {
2504349cc55cSDimitry Andric   // Otherwise our writes of DST kill our later reads of SRC.
25050b57cec5SDimitry Andric   assert(dst <= src || dst >= src + srcParts);
25060b57cec5SDimitry Andric   assert(dstParts <= srcParts + 1);
25070b57cec5SDimitry Andric 
2508349cc55cSDimitry Andric   // N loops; minimum of dstParts and srcParts.
25090b57cec5SDimitry Andric   unsigned n = std::min(dstParts, srcParts);
25100b57cec5SDimitry Andric 
25110b57cec5SDimitry Andric   for (unsigned i = 0; i < n; i++) {
2512349cc55cSDimitry Andric     // [LOW, HIGH] = MULTIPLIER * SRC[i] + DST[i] + CARRY.
2513349cc55cSDimitry Andric     // This cannot overflow, because:
2514349cc55cSDimitry Andric     //   (n - 1) * (n - 1) + 2 (n - 1) = (n - 1) * (n + 1)
2515349cc55cSDimitry Andric     // which is less than n^2.
2516349cc55cSDimitry Andric     WordType srcPart = src[i];
2517349cc55cSDimitry Andric     WordType low, mid, high;
25180b57cec5SDimitry Andric     if (multiplier == 0 || srcPart == 0) {
25190b57cec5SDimitry Andric       low = carry;
25200b57cec5SDimitry Andric       high = 0;
25210b57cec5SDimitry Andric     } else {
25220b57cec5SDimitry Andric       low = lowHalf(srcPart) * lowHalf(multiplier);
25230b57cec5SDimitry Andric       high = highHalf(srcPart) * highHalf(multiplier);
25240b57cec5SDimitry Andric 
25250b57cec5SDimitry Andric       mid = lowHalf(srcPart) * highHalf(multiplier);
25260b57cec5SDimitry Andric       high += highHalf(mid);
25270b57cec5SDimitry Andric       mid <<= APINT_BITS_PER_WORD / 2;
25280b57cec5SDimitry Andric       if (low + mid < low)
25290b57cec5SDimitry Andric         high++;
25300b57cec5SDimitry Andric       low += mid;
25310b57cec5SDimitry Andric 
25320b57cec5SDimitry Andric       mid = highHalf(srcPart) * lowHalf(multiplier);
25330b57cec5SDimitry Andric       high += highHalf(mid);
25340b57cec5SDimitry Andric       mid <<= APINT_BITS_PER_WORD / 2;
25350b57cec5SDimitry Andric       if (low + mid < low)
25360b57cec5SDimitry Andric         high++;
25370b57cec5SDimitry Andric       low += mid;
25380b57cec5SDimitry Andric 
2539349cc55cSDimitry Andric       // Now add carry.
25400b57cec5SDimitry Andric       if (low + carry < low)
25410b57cec5SDimitry Andric         high++;
25420b57cec5SDimitry Andric       low += carry;
25430b57cec5SDimitry Andric     }
25440b57cec5SDimitry Andric 
25450b57cec5SDimitry Andric     if (add) {
2546349cc55cSDimitry Andric       // And now DST[i], and store the new low part there.
25470b57cec5SDimitry Andric       if (low + dst[i] < low)
25480b57cec5SDimitry Andric         high++;
25490b57cec5SDimitry Andric       dst[i] += low;
25500b57cec5SDimitry Andric     } else
25510b57cec5SDimitry Andric       dst[i] = low;
25520b57cec5SDimitry Andric 
25530b57cec5SDimitry Andric     carry = high;
25540b57cec5SDimitry Andric   }
25550b57cec5SDimitry Andric 
25560b57cec5SDimitry Andric   if (srcParts < dstParts) {
2557349cc55cSDimitry Andric     // Full multiplication, there is no overflow.
25580b57cec5SDimitry Andric     assert(srcParts + 1 == dstParts);
25590b57cec5SDimitry Andric     dst[srcParts] = carry;
25600b57cec5SDimitry Andric     return 0;
25610b57cec5SDimitry Andric   }
25620b57cec5SDimitry Andric 
2563349cc55cSDimitry Andric   // We overflowed if there is carry.
25640b57cec5SDimitry Andric   if (carry)
25650b57cec5SDimitry Andric     return 1;
25660b57cec5SDimitry Andric 
2567349cc55cSDimitry Andric   // We would overflow if any significant unwritten parts would be
2568349cc55cSDimitry Andric   // non-zero.  This is true if any remaining src parts are non-zero
2569349cc55cSDimitry Andric   // and the multiplier is non-zero.
25700b57cec5SDimitry Andric   if (multiplier)
25710b57cec5SDimitry Andric     for (unsigned i = dstParts; i < srcParts; i++)
25720b57cec5SDimitry Andric       if (src[i])
25730b57cec5SDimitry Andric         return 1;
25740b57cec5SDimitry Andric 
2575349cc55cSDimitry Andric   // We fitted in the narrow destination.
25760b57cec5SDimitry Andric   return 0;
25770b57cec5SDimitry Andric }
25780b57cec5SDimitry Andric 
2579349cc55cSDimitry Andric /// DST = LHS * RHS, where DST has the same width as the operands and
2580349cc55cSDimitry Andric /// is filled with the least significant parts of the result.  Returns
2581349cc55cSDimitry Andric /// one if overflow occurred, otherwise zero.  DST must be disjoint
2582349cc55cSDimitry Andric /// from both operands.
25830b57cec5SDimitry Andric int APInt::tcMultiply(WordType *dst, const WordType *lhs,
25840b57cec5SDimitry Andric                       const WordType *rhs, unsigned parts) {
25850b57cec5SDimitry Andric   assert(dst != lhs && dst != rhs);
25860b57cec5SDimitry Andric 
25870b57cec5SDimitry Andric   int overflow = 0;
25880b57cec5SDimitry Andric 
2589*0fca6ea1SDimitry Andric   for (unsigned i = 0; i < parts; i++) {
2590*0fca6ea1SDimitry Andric     // Don't accumulate on the first iteration so we don't need to initalize
2591*0fca6ea1SDimitry Andric     // dst to 0.
2592*0fca6ea1SDimitry Andric     overflow |=
2593*0fca6ea1SDimitry Andric         tcMultiplyPart(&dst[i], lhs, rhs[i], 0, parts, parts - i, i != 0);
2594*0fca6ea1SDimitry Andric   }
25950b57cec5SDimitry Andric 
25960b57cec5SDimitry Andric   return overflow;
25970b57cec5SDimitry Andric }
25980b57cec5SDimitry Andric 
25990b57cec5SDimitry Andric /// DST = LHS * RHS, where DST has width the sum of the widths of the
26000b57cec5SDimitry Andric /// operands. No overflow occurs. DST must be disjoint from both operands.
26010b57cec5SDimitry Andric void APInt::tcFullMultiply(WordType *dst, const WordType *lhs,
26020b57cec5SDimitry Andric                            const WordType *rhs, unsigned lhsParts,
26030b57cec5SDimitry Andric                            unsigned rhsParts) {
2604349cc55cSDimitry Andric   // Put the narrower number on the LHS for less loops below.
26050b57cec5SDimitry Andric   if (lhsParts > rhsParts)
26060b57cec5SDimitry Andric     return tcFullMultiply (dst, rhs, lhs, rhsParts, lhsParts);
26070b57cec5SDimitry Andric 
26080b57cec5SDimitry Andric   assert(dst != lhs && dst != rhs);
26090b57cec5SDimitry Andric 
2610*0fca6ea1SDimitry Andric   for (unsigned i = 0; i < lhsParts; i++) {
2611*0fca6ea1SDimitry Andric     // Don't accumulate on the first iteration so we don't need to initalize
2612*0fca6ea1SDimitry Andric     // dst to 0.
2613*0fca6ea1SDimitry Andric     tcMultiplyPart(&dst[i], rhs, lhs[i], 0, rhsParts, rhsParts + 1, i != 0);
2614*0fca6ea1SDimitry Andric   }
26150b57cec5SDimitry Andric }
26160b57cec5SDimitry Andric 
2617349cc55cSDimitry Andric // If RHS is zero LHS and REMAINDER are left unchanged, return one.
2618349cc55cSDimitry Andric // Otherwise set LHS to LHS / RHS with the fractional part discarded,
2619349cc55cSDimitry Andric // set REMAINDER to the remainder, return zero.  i.e.
2620349cc55cSDimitry Andric //
2621349cc55cSDimitry Andric //   OLD_LHS = RHS * LHS + REMAINDER
2622349cc55cSDimitry Andric //
2623349cc55cSDimitry Andric // SCRATCH is a bignum of the same size as the operands and result for
2624349cc55cSDimitry Andric // use by the routine; its contents need not be initialized and are
2625349cc55cSDimitry Andric // destroyed.  LHS, REMAINDER and SCRATCH must be distinct.
26260b57cec5SDimitry Andric int APInt::tcDivide(WordType *lhs, const WordType *rhs,
26270b57cec5SDimitry Andric                     WordType *remainder, WordType *srhs,
26280b57cec5SDimitry Andric                     unsigned parts) {
26290b57cec5SDimitry Andric   assert(lhs != remainder && lhs != srhs && remainder != srhs);
26300b57cec5SDimitry Andric 
26310b57cec5SDimitry Andric   unsigned shiftCount = tcMSB(rhs, parts) + 1;
26320b57cec5SDimitry Andric   if (shiftCount == 0)
26330b57cec5SDimitry Andric     return true;
26340b57cec5SDimitry Andric 
26350b57cec5SDimitry Andric   shiftCount = parts * APINT_BITS_PER_WORD - shiftCount;
26360b57cec5SDimitry Andric   unsigned n = shiftCount / APINT_BITS_PER_WORD;
26370b57cec5SDimitry Andric   WordType mask = (WordType) 1 << (shiftCount % APINT_BITS_PER_WORD);
26380b57cec5SDimitry Andric 
26390b57cec5SDimitry Andric   tcAssign(srhs, rhs, parts);
26400b57cec5SDimitry Andric   tcShiftLeft(srhs, parts, shiftCount);
26410b57cec5SDimitry Andric   tcAssign(remainder, lhs, parts);
26420b57cec5SDimitry Andric   tcSet(lhs, 0, parts);
26430b57cec5SDimitry Andric 
2644349cc55cSDimitry Andric   // Loop, subtracting SRHS if REMAINDER is greater and adding that to the
2645349cc55cSDimitry Andric   // total.
26460b57cec5SDimitry Andric   for (;;) {
26470b57cec5SDimitry Andric     int compare = tcCompare(remainder, srhs, parts);
26480b57cec5SDimitry Andric     if (compare >= 0) {
26490b57cec5SDimitry Andric       tcSubtract(remainder, srhs, 0, parts);
26500b57cec5SDimitry Andric       lhs[n] |= mask;
26510b57cec5SDimitry Andric     }
26520b57cec5SDimitry Andric 
26530b57cec5SDimitry Andric     if (shiftCount == 0)
26540b57cec5SDimitry Andric       break;
26550b57cec5SDimitry Andric     shiftCount--;
26560b57cec5SDimitry Andric     tcShiftRight(srhs, parts, 1);
26570b57cec5SDimitry Andric     if ((mask >>= 1) == 0) {
26580b57cec5SDimitry Andric       mask = (WordType) 1 << (APINT_BITS_PER_WORD - 1);
26590b57cec5SDimitry Andric       n--;
26600b57cec5SDimitry Andric     }
26610b57cec5SDimitry Andric   }
26620b57cec5SDimitry Andric 
26630b57cec5SDimitry Andric   return false;
26640b57cec5SDimitry Andric }
26650b57cec5SDimitry Andric 
2666*0fca6ea1SDimitry Andric /// Shift a bignum left Count bits in-place. Shifted in bits are zero. There are
26670b57cec5SDimitry Andric /// no restrictions on Count.
26680b57cec5SDimitry Andric void APInt::tcShiftLeft(WordType *Dst, unsigned Words, unsigned Count) {
26690b57cec5SDimitry Andric   // Don't bother performing a no-op shift.
26700b57cec5SDimitry Andric   if (!Count)
26710b57cec5SDimitry Andric     return;
26720b57cec5SDimitry Andric 
26730b57cec5SDimitry Andric   // WordShift is the inter-part shift; BitShift is the intra-part shift.
26740b57cec5SDimitry Andric   unsigned WordShift = std::min(Count / APINT_BITS_PER_WORD, Words);
26750b57cec5SDimitry Andric   unsigned BitShift = Count % APINT_BITS_PER_WORD;
26760b57cec5SDimitry Andric 
26770b57cec5SDimitry Andric   // Fastpath for moving by whole words.
26780b57cec5SDimitry Andric   if (BitShift == 0) {
26790b57cec5SDimitry Andric     std::memmove(Dst + WordShift, Dst, (Words - WordShift) * APINT_WORD_SIZE);
26800b57cec5SDimitry Andric   } else {
26810b57cec5SDimitry Andric     while (Words-- > WordShift) {
26820b57cec5SDimitry Andric       Dst[Words] = Dst[Words - WordShift] << BitShift;
26830b57cec5SDimitry Andric       if (Words > WordShift)
26840b57cec5SDimitry Andric         Dst[Words] |=
26850b57cec5SDimitry Andric           Dst[Words - WordShift - 1] >> (APINT_BITS_PER_WORD - BitShift);
26860b57cec5SDimitry Andric     }
26870b57cec5SDimitry Andric   }
26880b57cec5SDimitry Andric 
26890b57cec5SDimitry Andric   // Fill in the remainder with 0s.
26900b57cec5SDimitry Andric   std::memset(Dst, 0, WordShift * APINT_WORD_SIZE);
26910b57cec5SDimitry Andric }
26920b57cec5SDimitry Andric 
26930b57cec5SDimitry Andric /// Shift a bignum right Count bits in-place. Shifted in bits are zero. There
26940b57cec5SDimitry Andric /// are no restrictions on Count.
26950b57cec5SDimitry Andric void APInt::tcShiftRight(WordType *Dst, unsigned Words, unsigned Count) {
26960b57cec5SDimitry Andric   // Don't bother performing a no-op shift.
26970b57cec5SDimitry Andric   if (!Count)
26980b57cec5SDimitry Andric     return;
26990b57cec5SDimitry Andric 
27000b57cec5SDimitry Andric   // WordShift is the inter-part shift; BitShift is the intra-part shift.
27010b57cec5SDimitry Andric   unsigned WordShift = std::min(Count / APINT_BITS_PER_WORD, Words);
27020b57cec5SDimitry Andric   unsigned BitShift = Count % APINT_BITS_PER_WORD;
27030b57cec5SDimitry Andric 
27040b57cec5SDimitry Andric   unsigned WordsToMove = Words - WordShift;
27050b57cec5SDimitry Andric   // Fastpath for moving by whole words.
27060b57cec5SDimitry Andric   if (BitShift == 0) {
27070b57cec5SDimitry Andric     std::memmove(Dst, Dst + WordShift, WordsToMove * APINT_WORD_SIZE);
27080b57cec5SDimitry Andric   } else {
27090b57cec5SDimitry Andric     for (unsigned i = 0; i != WordsToMove; ++i) {
27100b57cec5SDimitry Andric       Dst[i] = Dst[i + WordShift] >> BitShift;
27110b57cec5SDimitry Andric       if (i + 1 != WordsToMove)
27120b57cec5SDimitry Andric         Dst[i] |= Dst[i + WordShift + 1] << (APINT_BITS_PER_WORD - BitShift);
27130b57cec5SDimitry Andric     }
27140b57cec5SDimitry Andric   }
27150b57cec5SDimitry Andric 
27160b57cec5SDimitry Andric   // Fill in the remainder with 0s.
27170b57cec5SDimitry Andric   std::memset(Dst + WordsToMove, 0, WordShift * APINT_WORD_SIZE);
27180b57cec5SDimitry Andric }
27190b57cec5SDimitry Andric 
2720349cc55cSDimitry Andric // Comparison (unsigned) of two bignums.
27210b57cec5SDimitry Andric int APInt::tcCompare(const WordType *lhs, const WordType *rhs,
27220b57cec5SDimitry Andric                      unsigned parts) {
27230b57cec5SDimitry Andric   while (parts) {
27240b57cec5SDimitry Andric     parts--;
27250b57cec5SDimitry Andric     if (lhs[parts] != rhs[parts])
27260b57cec5SDimitry Andric       return (lhs[parts] > rhs[parts]) ? 1 : -1;
27270b57cec5SDimitry Andric   }
27280b57cec5SDimitry Andric 
27290b57cec5SDimitry Andric   return 0;
27300b57cec5SDimitry Andric }
27310b57cec5SDimitry Andric 
27320b57cec5SDimitry Andric APInt llvm::APIntOps::RoundingUDiv(const APInt &A, const APInt &B,
27330b57cec5SDimitry Andric                                    APInt::Rounding RM) {
27340b57cec5SDimitry Andric   // Currently udivrem always rounds down.
27350b57cec5SDimitry Andric   switch (RM) {
27360b57cec5SDimitry Andric   case APInt::Rounding::DOWN:
27370b57cec5SDimitry Andric   case APInt::Rounding::TOWARD_ZERO:
27380b57cec5SDimitry Andric     return A.udiv(B);
27390b57cec5SDimitry Andric   case APInt::Rounding::UP: {
27400b57cec5SDimitry Andric     APInt Quo, Rem;
27410b57cec5SDimitry Andric     APInt::udivrem(A, B, Quo, Rem);
2742349cc55cSDimitry Andric     if (Rem.isZero())
27430b57cec5SDimitry Andric       return Quo;
27440b57cec5SDimitry Andric     return Quo + 1;
27450b57cec5SDimitry Andric   }
27460b57cec5SDimitry Andric   }
27470b57cec5SDimitry Andric   llvm_unreachable("Unknown APInt::Rounding enum");
27480b57cec5SDimitry Andric }
27490b57cec5SDimitry Andric 
27500b57cec5SDimitry Andric APInt llvm::APIntOps::RoundingSDiv(const APInt &A, const APInt &B,
27510b57cec5SDimitry Andric                                    APInt::Rounding RM) {
27520b57cec5SDimitry Andric   switch (RM) {
27530b57cec5SDimitry Andric   case APInt::Rounding::DOWN:
27540b57cec5SDimitry Andric   case APInt::Rounding::UP: {
27550b57cec5SDimitry Andric     APInt Quo, Rem;
27560b57cec5SDimitry Andric     APInt::sdivrem(A, B, Quo, Rem);
2757349cc55cSDimitry Andric     if (Rem.isZero())
27580b57cec5SDimitry Andric       return Quo;
27590b57cec5SDimitry Andric     // This algorithm deals with arbitrary rounding mode used by sdivrem.
27600b57cec5SDimitry Andric     // We want to check whether the non-integer part of the mathematical value
27610b57cec5SDimitry Andric     // is negative or not. If the non-integer part is negative, we need to round
27620b57cec5SDimitry Andric     // down from Quo; otherwise, if it's positive or 0, we return Quo, as it's
27630b57cec5SDimitry Andric     // already rounded down.
27640b57cec5SDimitry Andric     if (RM == APInt::Rounding::DOWN) {
27650b57cec5SDimitry Andric       if (Rem.isNegative() != B.isNegative())
27660b57cec5SDimitry Andric         return Quo - 1;
27670b57cec5SDimitry Andric       return Quo;
27680b57cec5SDimitry Andric     }
27690b57cec5SDimitry Andric     if (Rem.isNegative() != B.isNegative())
27700b57cec5SDimitry Andric       return Quo;
27710b57cec5SDimitry Andric     return Quo + 1;
27720b57cec5SDimitry Andric   }
2773480093f4SDimitry Andric   // Currently sdiv rounds towards zero.
27740b57cec5SDimitry Andric   case APInt::Rounding::TOWARD_ZERO:
27750b57cec5SDimitry Andric     return A.sdiv(B);
27760b57cec5SDimitry Andric   }
27770b57cec5SDimitry Andric   llvm_unreachable("Unknown APInt::Rounding enum");
27780b57cec5SDimitry Andric }
27790b57cec5SDimitry Andric 
2780bdd1243dSDimitry Andric std::optional<APInt>
27810b57cec5SDimitry Andric llvm::APIntOps::SolveQuadraticEquationWrap(APInt A, APInt B, APInt C,
27820b57cec5SDimitry Andric                                            unsigned RangeWidth) {
27830b57cec5SDimitry Andric   unsigned CoeffWidth = A.getBitWidth();
27840b57cec5SDimitry Andric   assert(CoeffWidth == B.getBitWidth() && CoeffWidth == C.getBitWidth());
27850b57cec5SDimitry Andric   assert(RangeWidth <= CoeffWidth &&
27860b57cec5SDimitry Andric          "Value range width should be less than coefficient width");
27870b57cec5SDimitry Andric   assert(RangeWidth > 1 && "Value range bit width should be > 1");
27880b57cec5SDimitry Andric 
27890b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << __func__ << ": solving " << A << "x^2 + " << B
27900b57cec5SDimitry Andric                     << "x + " << C << ", rw:" << RangeWidth << '\n');
27910b57cec5SDimitry Andric 
27920b57cec5SDimitry Andric   // Identify 0 as a (non)solution immediately.
2793349cc55cSDimitry Andric   if (C.sextOrTrunc(RangeWidth).isZero()) {
27940b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << __func__ << ": zero solution\n");
27950b57cec5SDimitry Andric     return APInt(CoeffWidth, 0);
27960b57cec5SDimitry Andric   }
27970b57cec5SDimitry Andric 
27980b57cec5SDimitry Andric   // The result of APInt arithmetic has the same bit width as the operands,
27990b57cec5SDimitry Andric   // so it can actually lose high bits. A product of two n-bit integers needs
28000b57cec5SDimitry Andric   // 2n-1 bits to represent the full value.
28010b57cec5SDimitry Andric   // The operation done below (on quadratic coefficients) that can produce
28020b57cec5SDimitry Andric   // the largest value is the evaluation of the equation during bisection,
28030b57cec5SDimitry Andric   // which needs 3 times the bitwidth of the coefficient, so the total number
28040b57cec5SDimitry Andric   // of required bits is 3n.
28050b57cec5SDimitry Andric   //
28060b57cec5SDimitry Andric   // The purpose of this extension is to simulate the set Z of all integers,
28070b57cec5SDimitry Andric   // where n+1 > n for all n in Z. In Z it makes sense to talk about positive
28080b57cec5SDimitry Andric   // and negative numbers (not so much in a modulo arithmetic). The method
28090b57cec5SDimitry Andric   // used to solve the equation is based on the standard formula for real
28100b57cec5SDimitry Andric   // numbers, and uses the concepts of "positive" and "negative" with their
28110b57cec5SDimitry Andric   // usual meanings.
28120b57cec5SDimitry Andric   CoeffWidth *= 3;
28130b57cec5SDimitry Andric   A = A.sext(CoeffWidth);
28140b57cec5SDimitry Andric   B = B.sext(CoeffWidth);
28150b57cec5SDimitry Andric   C = C.sext(CoeffWidth);
28160b57cec5SDimitry Andric 
28170b57cec5SDimitry Andric   // Make A > 0 for simplicity. Negate cannot overflow at this point because
28180b57cec5SDimitry Andric   // the bit width has increased.
28190b57cec5SDimitry Andric   if (A.isNegative()) {
28200b57cec5SDimitry Andric     A.negate();
28210b57cec5SDimitry Andric     B.negate();
28220b57cec5SDimitry Andric     C.negate();
28230b57cec5SDimitry Andric   }
28240b57cec5SDimitry Andric 
28250b57cec5SDimitry Andric   // Solving an equation q(x) = 0 with coefficients in modular arithmetic
28260b57cec5SDimitry Andric   // is really solving a set of equations q(x) = kR for k = 0, 1, 2, ...,
28270b57cec5SDimitry Andric   // and R = 2^BitWidth.
28280b57cec5SDimitry Andric   // Since we're trying not only to find exact solutions, but also values
28290b57cec5SDimitry Andric   // that "wrap around", such a set will always have a solution, i.e. an x
28300b57cec5SDimitry Andric   // that satisfies at least one of the equations, or such that |q(x)|
28310b57cec5SDimitry Andric   // exceeds kR, while |q(x-1)| for the same k does not.
28320b57cec5SDimitry Andric   //
28330b57cec5SDimitry Andric   // We need to find a value k, such that Ax^2 + Bx + C = kR will have a
28340b57cec5SDimitry Andric   // positive solution n (in the above sense), and also such that the n
28350b57cec5SDimitry Andric   // will be the least among all solutions corresponding to k = 0, 1, ...
28360b57cec5SDimitry Andric   // (more precisely, the least element in the set
28370b57cec5SDimitry Andric   //   { n(k) | k is such that a solution n(k) exists }).
28380b57cec5SDimitry Andric   //
28390b57cec5SDimitry Andric   // Consider the parabola (over real numbers) that corresponds to the
28400b57cec5SDimitry Andric   // quadratic equation. Since A > 0, the arms of the parabola will point
28410b57cec5SDimitry Andric   // up. Picking different values of k will shift it up and down by R.
28420b57cec5SDimitry Andric   //
28430b57cec5SDimitry Andric   // We want to shift the parabola in such a way as to reduce the problem
28440b57cec5SDimitry Andric   // of solving q(x) = kR to solving shifted_q(x) = 0.
28450b57cec5SDimitry Andric   // (The interesting solutions are the ceilings of the real number
28460b57cec5SDimitry Andric   // solutions.)
28470b57cec5SDimitry Andric   APInt R = APInt::getOneBitSet(CoeffWidth, RangeWidth);
28480b57cec5SDimitry Andric   APInt TwoA = 2 * A;
28490b57cec5SDimitry Andric   APInt SqrB = B * B;
28500b57cec5SDimitry Andric   bool PickLow;
28510b57cec5SDimitry Andric 
28520b57cec5SDimitry Andric   auto RoundUp = [] (const APInt &V, const APInt &A) -> APInt {
28530b57cec5SDimitry Andric     assert(A.isStrictlyPositive());
28540b57cec5SDimitry Andric     APInt T = V.abs().urem(A);
2855349cc55cSDimitry Andric     if (T.isZero())
28560b57cec5SDimitry Andric       return V;
28570b57cec5SDimitry Andric     return V.isNegative() ? V+T : V+(A-T);
28580b57cec5SDimitry Andric   };
28590b57cec5SDimitry Andric 
28600b57cec5SDimitry Andric   // The vertex of the parabola is at -B/2A, but since A > 0, it's negative
28610b57cec5SDimitry Andric   // iff B is positive.
28620b57cec5SDimitry Andric   if (B.isNonNegative()) {
28630b57cec5SDimitry Andric     // If B >= 0, the vertex it at a negative location (or at 0), so in
28640b57cec5SDimitry Andric     // order to have a non-negative solution we need to pick k that makes
28650b57cec5SDimitry Andric     // C-kR negative. To satisfy all the requirements for the solution
28660b57cec5SDimitry Andric     // that we are looking for, it needs to be closest to 0 of all k.
28670b57cec5SDimitry Andric     C = C.srem(R);
28680b57cec5SDimitry Andric     if (C.isStrictlyPositive())
28690b57cec5SDimitry Andric       C -= R;
28700b57cec5SDimitry Andric     // Pick the greater solution.
28710b57cec5SDimitry Andric     PickLow = false;
28720b57cec5SDimitry Andric   } else {
28730b57cec5SDimitry Andric     // If B < 0, the vertex is at a positive location. For any solution
28740b57cec5SDimitry Andric     // to exist, the discriminant must be non-negative. This means that
28750b57cec5SDimitry Andric     // C-kR <= B^2/4A is a necessary condition for k, i.e. there is a
28760b57cec5SDimitry Andric     // lower bound on values of k: kR >= C - B^2/4A.
28770b57cec5SDimitry Andric     APInt LowkR = C - SqrB.udiv(2*TwoA); // udiv because all values > 0.
28780b57cec5SDimitry Andric     // Round LowkR up (towards +inf) to the nearest kR.
28790b57cec5SDimitry Andric     LowkR = RoundUp(LowkR, R);
28800b57cec5SDimitry Andric 
28810b57cec5SDimitry Andric     // If there exists k meeting the condition above, and such that
28820b57cec5SDimitry Andric     // C-kR > 0, there will be two positive real number solutions of
28830b57cec5SDimitry Andric     // q(x) = kR. Out of all such values of k, pick the one that makes
28840b57cec5SDimitry Andric     // C-kR closest to 0, (i.e. pick maximum k such that C-kR > 0).
28850b57cec5SDimitry Andric     // In other words, find maximum k such that LowkR <= kR < C.
28860b57cec5SDimitry Andric     if (C.sgt(LowkR)) {
28870b57cec5SDimitry Andric       // If LowkR < C, then such a k is guaranteed to exist because
28880b57cec5SDimitry Andric       // LowkR itself is a multiple of R.
28890b57cec5SDimitry Andric       C -= -RoundUp(-C, R);      // C = C - RoundDown(C, R)
28900b57cec5SDimitry Andric       // Pick the smaller solution.
28910b57cec5SDimitry Andric       PickLow = true;
28920b57cec5SDimitry Andric     } else {
28930b57cec5SDimitry Andric       // If C-kR < 0 for all potential k's, it means that one solution
28940b57cec5SDimitry Andric       // will be negative, while the other will be positive. The positive
28950b57cec5SDimitry Andric       // solution will shift towards 0 if the parabola is moved up.
28960b57cec5SDimitry Andric       // Pick the kR closest to the lower bound (i.e. make C-kR closest
28970b57cec5SDimitry Andric       // to 0, or in other words, out of all parabolas that have solutions,
28980b57cec5SDimitry Andric       // pick the one that is the farthest "up").
28990b57cec5SDimitry Andric       // Since LowkR is itself a multiple of R, simply take C-LowkR.
29000b57cec5SDimitry Andric       C -= LowkR;
29010b57cec5SDimitry Andric       // Pick the greater solution.
29020b57cec5SDimitry Andric       PickLow = false;
29030b57cec5SDimitry Andric     }
29040b57cec5SDimitry Andric   }
29050b57cec5SDimitry Andric 
29060b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << __func__ << ": updated coefficients " << A << "x^2 + "
29070b57cec5SDimitry Andric                     << B << "x + " << C << ", rw:" << RangeWidth << '\n');
29080b57cec5SDimitry Andric 
29090b57cec5SDimitry Andric   APInt D = SqrB - 4*A*C;
29100b57cec5SDimitry Andric   assert(D.isNonNegative() && "Negative discriminant");
29110b57cec5SDimitry Andric   APInt SQ = D.sqrt();
29120b57cec5SDimitry Andric 
29130b57cec5SDimitry Andric   APInt Q = SQ * SQ;
29140b57cec5SDimitry Andric   bool InexactSQ = Q != D;
29150b57cec5SDimitry Andric   // The calculated SQ may actually be greater than the exact (non-integer)
2916480093f4SDimitry Andric   // value. If that's the case, decrement SQ to get a value that is lower.
29170b57cec5SDimitry Andric   if (Q.sgt(D))
29180b57cec5SDimitry Andric     SQ -= 1;
29190b57cec5SDimitry Andric 
29200b57cec5SDimitry Andric   APInt X;
29210b57cec5SDimitry Andric   APInt Rem;
29220b57cec5SDimitry Andric 
29230b57cec5SDimitry Andric   // SQ is rounded down (i.e SQ * SQ <= D), so the roots may be inexact.
29240b57cec5SDimitry Andric   // When using the quadratic formula directly, the calculated low root
29250b57cec5SDimitry Andric   // may be greater than the exact one, since we would be subtracting SQ.
29260b57cec5SDimitry Andric   // To make sure that the calculated root is not greater than the exact
29270b57cec5SDimitry Andric   // one, subtract SQ+1 when calculating the low root (for inexact value
29280b57cec5SDimitry Andric   // of SQ).
29290b57cec5SDimitry Andric   if (PickLow)
29300b57cec5SDimitry Andric     APInt::sdivrem(-B - (SQ+InexactSQ), TwoA, X, Rem);
29310b57cec5SDimitry Andric   else
29320b57cec5SDimitry Andric     APInt::sdivrem(-B + SQ, TwoA, X, Rem);
29330b57cec5SDimitry Andric 
29340b57cec5SDimitry Andric   // The updated coefficients should be such that the (exact) solution is
29350b57cec5SDimitry Andric   // positive. Since APInt division rounds towards 0, the calculated one
29360b57cec5SDimitry Andric   // can be 0, but cannot be negative.
29370b57cec5SDimitry Andric   assert(X.isNonNegative() && "Solution should be non-negative");
29380b57cec5SDimitry Andric 
2939349cc55cSDimitry Andric   if (!InexactSQ && Rem.isZero()) {
29400b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << __func__ << ": solution (root): " << X << '\n');
29410b57cec5SDimitry Andric     return X;
29420b57cec5SDimitry Andric   }
29430b57cec5SDimitry Andric 
29440b57cec5SDimitry Andric   assert((SQ*SQ).sle(D) && "SQ = |_sqrt(D)_|, so SQ*SQ <= D");
29450b57cec5SDimitry Andric   // The exact value of the square root of D should be between SQ and SQ+1.
29460b57cec5SDimitry Andric   // This implies that the solution should be between that corresponding to
29470b57cec5SDimitry Andric   // SQ (i.e. X) and that corresponding to SQ+1.
29480b57cec5SDimitry Andric   //
29490b57cec5SDimitry Andric   // The calculated X cannot be greater than the exact (real) solution.
29500b57cec5SDimitry Andric   // Actually it must be strictly less than the exact solution, while
29510b57cec5SDimitry Andric   // X+1 will be greater than or equal to it.
29520b57cec5SDimitry Andric 
29530b57cec5SDimitry Andric   APInt VX = (A*X + B)*X + C;
29540b57cec5SDimitry Andric   APInt VY = VX + TwoA*X + A + B;
2955349cc55cSDimitry Andric   bool SignChange =
2956349cc55cSDimitry Andric       VX.isNegative() != VY.isNegative() || VX.isZero() != VY.isZero();
29570b57cec5SDimitry Andric   // If the sign did not change between X and X+1, X is not a valid solution.
29580b57cec5SDimitry Andric   // This could happen when the actual (exact) roots don't have an integer
29590b57cec5SDimitry Andric   // between them, so they would both be contained between X and X+1.
29600b57cec5SDimitry Andric   if (!SignChange) {
29610b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << __func__ << ": no valid solution\n");
2962bdd1243dSDimitry Andric     return std::nullopt;
29630b57cec5SDimitry Andric   }
29640b57cec5SDimitry Andric 
29650b57cec5SDimitry Andric   X += 1;
29660b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << __func__ << ": solution (wrap): " << X << '\n');
29670b57cec5SDimitry Andric   return X;
29680b57cec5SDimitry Andric }
29690b57cec5SDimitry Andric 
2970bdd1243dSDimitry Andric std::optional<unsigned>
2971480093f4SDimitry Andric llvm::APIntOps::GetMostSignificantDifferentBit(const APInt &A, const APInt &B) {
2972480093f4SDimitry Andric   assert(A.getBitWidth() == B.getBitWidth() && "Must have the same bitwidth");
2973480093f4SDimitry Andric   if (A == B)
2974bdd1243dSDimitry Andric     return std::nullopt;
297506c3fb27SDimitry Andric   return A.getBitWidth() - ((A ^ B).countl_zero() + 1);
2976480093f4SDimitry Andric }
2977480093f4SDimitry Andric 
297881ad6265SDimitry Andric APInt llvm::APIntOps::ScaleBitMask(const APInt &A, unsigned NewBitWidth,
297981ad6265SDimitry Andric                                    bool MatchAllBits) {
2980349cc55cSDimitry Andric   unsigned OldBitWidth = A.getBitWidth();
2981349cc55cSDimitry Andric   assert((((OldBitWidth % NewBitWidth) == 0) ||
2982349cc55cSDimitry Andric           ((NewBitWidth % OldBitWidth) == 0)) &&
2983349cc55cSDimitry Andric          "One size should be a multiple of the other one. "
2984349cc55cSDimitry Andric          "Can't do fractional scaling.");
2985349cc55cSDimitry Andric 
2986349cc55cSDimitry Andric   // Check for matching bitwidths.
2987349cc55cSDimitry Andric   if (OldBitWidth == NewBitWidth)
2988349cc55cSDimitry Andric     return A;
2989349cc55cSDimitry Andric 
2990349cc55cSDimitry Andric   APInt NewA = APInt::getZero(NewBitWidth);
2991349cc55cSDimitry Andric 
2992349cc55cSDimitry Andric   // Check for null input.
2993349cc55cSDimitry Andric   if (A.isZero())
2994349cc55cSDimitry Andric     return NewA;
2995349cc55cSDimitry Andric 
2996349cc55cSDimitry Andric   if (NewBitWidth > OldBitWidth) {
2997349cc55cSDimitry Andric     // Repeat bits.
2998349cc55cSDimitry Andric     unsigned Scale = NewBitWidth / OldBitWidth;
2999349cc55cSDimitry Andric     for (unsigned i = 0; i != OldBitWidth; ++i)
3000349cc55cSDimitry Andric       if (A[i])
3001349cc55cSDimitry Andric         NewA.setBits(i * Scale, (i + 1) * Scale);
3002349cc55cSDimitry Andric   } else {
3003349cc55cSDimitry Andric     unsigned Scale = OldBitWidth / NewBitWidth;
300481ad6265SDimitry Andric     for (unsigned i = 0; i != NewBitWidth; ++i) {
300581ad6265SDimitry Andric       if (MatchAllBits) {
300681ad6265SDimitry Andric         if (A.extractBits(Scale, i * Scale).isAllOnes())
300781ad6265SDimitry Andric           NewA.setBit(i);
300881ad6265SDimitry Andric       } else {
3009349cc55cSDimitry Andric         if (!A.extractBits(Scale, i * Scale).isZero())
3010349cc55cSDimitry Andric           NewA.setBit(i);
3011349cc55cSDimitry Andric       }
301281ad6265SDimitry Andric     }
301381ad6265SDimitry Andric   }
3014349cc55cSDimitry Andric 
3015349cc55cSDimitry Andric   return NewA;
3016349cc55cSDimitry Andric }
3017349cc55cSDimitry Andric 
30180b57cec5SDimitry Andric /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
30190b57cec5SDimitry Andric /// with the integer held in IntVal.
30200b57cec5SDimitry Andric void llvm::StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
30210b57cec5SDimitry Andric                             unsigned StoreBytes) {
30220b57cec5SDimitry Andric   assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
30230b57cec5SDimitry Andric   const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
30240b57cec5SDimitry Andric 
30250b57cec5SDimitry Andric   if (sys::IsLittleEndianHost) {
30260b57cec5SDimitry Andric     // Little-endian host - the source is ordered from LSB to MSB.  Order the
30270b57cec5SDimitry Andric     // destination from LSB to MSB: Do a straight copy.
30280b57cec5SDimitry Andric     memcpy(Dst, Src, StoreBytes);
30290b57cec5SDimitry Andric   } else {
30300b57cec5SDimitry Andric     // Big-endian host - the source is an array of 64 bit words ordered from
30310b57cec5SDimitry Andric     // LSW to MSW.  Each word is ordered from MSB to LSB.  Order the destination
30320b57cec5SDimitry Andric     // from MSB to LSB: Reverse the word order, but not the bytes in a word.
30330b57cec5SDimitry Andric     while (StoreBytes > sizeof(uint64_t)) {
30340b57cec5SDimitry Andric       StoreBytes -= sizeof(uint64_t);
30350b57cec5SDimitry Andric       // May not be aligned so use memcpy.
30360b57cec5SDimitry Andric       memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
30370b57cec5SDimitry Andric       Src += sizeof(uint64_t);
30380b57cec5SDimitry Andric     }
30390b57cec5SDimitry Andric 
30400b57cec5SDimitry Andric     memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
30410b57cec5SDimitry Andric   }
30420b57cec5SDimitry Andric }
30430b57cec5SDimitry Andric 
30440b57cec5SDimitry Andric /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
30450b57cec5SDimitry Andric /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
30465ffd83dbSDimitry Andric void llvm::LoadIntFromMemory(APInt &IntVal, const uint8_t *Src,
30475ffd83dbSDimitry Andric                              unsigned LoadBytes) {
30480b57cec5SDimitry Andric   assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
30490b57cec5SDimitry Andric   uint8_t *Dst = reinterpret_cast<uint8_t *>(
30500b57cec5SDimitry Andric                    const_cast<uint64_t *>(IntVal.getRawData()));
30510b57cec5SDimitry Andric 
30520b57cec5SDimitry Andric   if (sys::IsLittleEndianHost)
30530b57cec5SDimitry Andric     // Little-endian host - the destination must be ordered from LSB to MSB.
30540b57cec5SDimitry Andric     // The source is ordered from LSB to MSB: Do a straight copy.
30550b57cec5SDimitry Andric     memcpy(Dst, Src, LoadBytes);
30560b57cec5SDimitry Andric   else {
30570b57cec5SDimitry Andric     // Big-endian - the destination is an array of 64 bit words ordered from
30580b57cec5SDimitry Andric     // LSW to MSW.  Each word must be ordered from MSB to LSB.  The source is
30590b57cec5SDimitry Andric     // ordered from MSB to LSB: Reverse the word order, but not the bytes in
30600b57cec5SDimitry Andric     // a word.
30610b57cec5SDimitry Andric     while (LoadBytes > sizeof(uint64_t)) {
30620b57cec5SDimitry Andric       LoadBytes -= sizeof(uint64_t);
30630b57cec5SDimitry Andric       // May not be aligned so use memcpy.
30640b57cec5SDimitry Andric       memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
30650b57cec5SDimitry Andric       Dst += sizeof(uint64_t);
30660b57cec5SDimitry Andric     }
30670b57cec5SDimitry Andric 
30680b57cec5SDimitry Andric     memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
30690b57cec5SDimitry Andric   }
30700b57cec5SDimitry Andric }
3071*0fca6ea1SDimitry Andric 
3072*0fca6ea1SDimitry Andric APInt APIntOps::avgFloorS(const APInt &C1, const APInt &C2) {
3073*0fca6ea1SDimitry Andric   // Return floor((C1 + C2) / 2)
3074*0fca6ea1SDimitry Andric   return (C1 & C2) + (C1 ^ C2).ashr(1);
3075*0fca6ea1SDimitry Andric }
3076*0fca6ea1SDimitry Andric 
3077*0fca6ea1SDimitry Andric APInt APIntOps::avgFloorU(const APInt &C1, const APInt &C2) {
3078*0fca6ea1SDimitry Andric   // Return floor((C1 + C2) / 2)
3079*0fca6ea1SDimitry Andric   return (C1 & C2) + (C1 ^ C2).lshr(1);
3080*0fca6ea1SDimitry Andric }
3081*0fca6ea1SDimitry Andric 
3082*0fca6ea1SDimitry Andric APInt APIntOps::avgCeilS(const APInt &C1, const APInt &C2) {
3083*0fca6ea1SDimitry Andric   // Return ceil((C1 + C2) / 2)
3084*0fca6ea1SDimitry Andric   return (C1 | C2) - (C1 ^ C2).ashr(1);
3085*0fca6ea1SDimitry Andric }
3086*0fca6ea1SDimitry Andric 
3087*0fca6ea1SDimitry Andric APInt APIntOps::avgCeilU(const APInt &C1, const APInt &C2) {
3088*0fca6ea1SDimitry Andric   // Return ceil((C1 + C2) / 2)
3089*0fca6ea1SDimitry Andric   return (C1 | C2) - (C1 ^ C2).lshr(1);
3090*0fca6ea1SDimitry Andric }
3091*0fca6ea1SDimitry Andric 
3092*0fca6ea1SDimitry Andric APInt APIntOps::mulhs(const APInt &C1, const APInt &C2) {
3093*0fca6ea1SDimitry Andric   assert(C1.getBitWidth() == C2.getBitWidth() && "Unequal bitwidths");
3094*0fca6ea1SDimitry Andric   unsigned FullWidth = C1.getBitWidth() * 2;
3095*0fca6ea1SDimitry Andric   APInt C1Ext = C1.sext(FullWidth);
3096*0fca6ea1SDimitry Andric   APInt C2Ext = C2.sext(FullWidth);
3097*0fca6ea1SDimitry Andric   return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
3098*0fca6ea1SDimitry Andric }
3099*0fca6ea1SDimitry Andric 
3100*0fca6ea1SDimitry Andric APInt APIntOps::mulhu(const APInt &C1, const APInt &C2) {
3101*0fca6ea1SDimitry Andric   assert(C1.getBitWidth() == C2.getBitWidth() && "Unequal bitwidths");
3102*0fca6ea1SDimitry Andric   unsigned FullWidth = C1.getBitWidth() * 2;
3103*0fca6ea1SDimitry Andric   APInt C1Ext = C1.zext(FullWidth);
3104*0fca6ea1SDimitry Andric   APInt C2Ext = C2.zext(FullWidth);
3105*0fca6ea1SDimitry Andric   return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
3106*0fca6ea1SDimitry Andric }
3107