1009b1c42SEd Schouten //===-- APInt.cpp - Implement APInt class ---------------------------------===//
2009b1c42SEd Schouten //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6009b1c42SEd Schouten //
7009b1c42SEd Schouten //===----------------------------------------------------------------------===//
8009b1c42SEd Schouten //
9009b1c42SEd Schouten // This file implements a class to represent arbitrary precision integer
10009b1c42SEd Schouten // constant values and provide a variety of arithmetic operations on them.
11009b1c42SEd Schouten //
12009b1c42SEd Schouten //===----------------------------------------------------------------------===//
13009b1c42SEd Schouten
14009b1c42SEd Schouten #include "llvm/ADT/APInt.h"
1501095a5dSDimitry Andric #include "llvm/ADT/ArrayRef.h"
16009b1c42SEd Schouten #include "llvm/ADT/FoldingSet.h"
1763faed5bSDimitry Andric #include "llvm/ADT/Hashing.h"
18009b1c42SEd Schouten #include "llvm/ADT/SmallString.h"
1963faed5bSDimitry Andric #include "llvm/ADT/StringRef.h"
20d8e91e46SDimitry Andric #include "llvm/ADT/bit.h"
21eb11fae6SDimitry Andric #include "llvm/Config/llvm-config.h"
227fa27ce4SDimitry Andric #include "llvm/Support/Alignment.h"
23009b1c42SEd Schouten #include "llvm/Support/Debug.h"
2459850d08SRoman Divacky #include "llvm/Support/ErrorHandling.h"
25009b1c42SEd Schouten #include "llvm/Support/MathExtras.h"
26009b1c42SEd Schouten #include "llvm/Support/raw_ostream.h"
27009b1c42SEd Schouten #include <cmath>
28e3b55780SDimitry Andric #include <optional>
29e3b55780SDimitry Andric
30009b1c42SEd Schouten using namespace llvm;
31009b1c42SEd Schouten
325ca98fd9SDimitry Andric #define DEBUG_TYPE "apint"
335ca98fd9SDimitry Andric
34009b1c42SEd Schouten /// A utility function for allocating memory, checking for allocation failures,
35009b1c42SEd Schouten /// and ensuring the contents are zeroed.
getClearedMemory(unsigned numWords)36009b1c42SEd Schouten inline static uint64_t* getClearedMemory(unsigned numWords) {
37009b1c42SEd Schouten uint64_t *result = new uint64_t[numWords];
38009b1c42SEd Schouten memset(result, 0, numWords * sizeof(uint64_t));
39009b1c42SEd Schouten return result;
40009b1c42SEd Schouten }
41009b1c42SEd Schouten
42009b1c42SEd Schouten /// A utility function for allocating memory and checking for allocation
43009b1c42SEd Schouten /// failure. The content is not zeroed.
getMemory(unsigned numWords)44009b1c42SEd Schouten inline static uint64_t* getMemory(unsigned numWords) {
45eb11fae6SDimitry Andric return new uint64_t[numWords];
46009b1c42SEd Schouten }
47009b1c42SEd Schouten
4859850d08SRoman Divacky /// A utility function that converts a character to a digit.
getDigit(char cdigit,uint8_t radix)4959850d08SRoman Divacky inline static unsigned getDigit(char cdigit, uint8_t radix) {
5059850d08SRoman Divacky unsigned r;
5159850d08SRoman Divacky
5230815c53SDimitry Andric if (radix == 16 || radix == 36) {
5359850d08SRoman Divacky r = cdigit - '0';
5459850d08SRoman Divacky if (r <= 9)
5559850d08SRoman Divacky return r;
5659850d08SRoman Divacky
5759850d08SRoman Divacky r = cdigit - 'A';
5830815c53SDimitry Andric if (r <= radix - 11U)
5959850d08SRoman Divacky return r + 10;
6059850d08SRoman Divacky
6159850d08SRoman Divacky r = cdigit - 'a';
6230815c53SDimitry Andric if (r <= radix - 11U)
6359850d08SRoman Divacky return r + 10;
6430815c53SDimitry Andric
6530815c53SDimitry Andric radix = 10;
6659850d08SRoman Divacky }
6759850d08SRoman Divacky
6859850d08SRoman Divacky r = cdigit - '0';
6959850d08SRoman Divacky if (r < radix)
7059850d08SRoman Divacky return r;
7159850d08SRoman Divacky
727fa27ce4SDimitry Andric return UINT_MAX;
7359850d08SRoman Divacky }
7459850d08SRoman Divacky
7559850d08SRoman Divacky
initSlowCase(uint64_t val,bool isSigned)7601095a5dSDimitry Andric void APInt::initSlowCase(uint64_t val, bool isSigned) {
77148779dfSDimitry Andric U.pVal = getClearedMemory(getNumWords());
78148779dfSDimitry Andric U.pVal[0] = val;
79009b1c42SEd Schouten if (isSigned && int64_t(val) < 0)
80009b1c42SEd Schouten for (unsigned i = 1; i < getNumWords(); ++i)
81d8e91e46SDimitry Andric U.pVal[i] = WORDTYPE_MAX;
8271d5a254SDimitry Andric clearUnusedBits();
83009b1c42SEd Schouten }
84009b1c42SEd Schouten
initSlowCase(const APInt & that)85009b1c42SEd Schouten void APInt::initSlowCase(const APInt& that) {
86148779dfSDimitry Andric U.pVal = getMemory(getNumWords());
87148779dfSDimitry Andric memcpy(U.pVal, that.U.pVal, getNumWords() * APINT_WORD_SIZE);
88009b1c42SEd Schouten }
89009b1c42SEd Schouten
initFromArray(ArrayRef<uint64_t> bigVal)9030815c53SDimitry Andric void APInt::initFromArray(ArrayRef<uint64_t> bigVal) {
9130815c53SDimitry Andric assert(bigVal.data() && "Null pointer detected!");
92009b1c42SEd Schouten if (isSingleWord())
93148779dfSDimitry Andric U.VAL = bigVal[0];
94009b1c42SEd Schouten else {
95009b1c42SEd Schouten // Get memory, cleared to 0
96148779dfSDimitry Andric U.pVal = getClearedMemory(getNumWords());
97009b1c42SEd Schouten // Calculate the number of words to copy
9830815c53SDimitry Andric unsigned words = std::min<unsigned>(bigVal.size(), getNumWords());
99009b1c42SEd Schouten // Copy the words from bigVal to pVal
100148779dfSDimitry Andric memcpy(U.pVal, bigVal.data(), words * APINT_WORD_SIZE);
101009b1c42SEd Schouten }
102009b1c42SEd Schouten // Make sure unused high bits are cleared
103009b1c42SEd Schouten clearUnusedBits();
104009b1c42SEd Schouten }
105009b1c42SEd Schouten
APInt(unsigned numBits,ArrayRef<uint64_t> bigVal)106c0981da4SDimitry Andric APInt::APInt(unsigned numBits, ArrayRef<uint64_t> bigVal) : BitWidth(numBits) {
10730815c53SDimitry Andric initFromArray(bigVal);
10830815c53SDimitry Andric }
10930815c53SDimitry Andric
APInt(unsigned numBits,unsigned numWords,const uint64_t bigVal[])11030815c53SDimitry Andric APInt::APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[])
11171d5a254SDimitry Andric : BitWidth(numBits) {
112e3b55780SDimitry Andric initFromArray(ArrayRef(bigVal, numWords));
11330815c53SDimitry Andric }
11430815c53SDimitry Andric
APInt(unsigned numbits,StringRef Str,uint8_t radix)115f3d15b0bSRoman Divacky APInt::APInt(unsigned numbits, StringRef Str, uint8_t radix)
116148779dfSDimitry Andric : BitWidth(numbits) {
11759850d08SRoman Divacky fromString(numbits, Str, radix);
118009b1c42SEd Schouten }
119009b1c42SEd Schouten
reallocate(unsigned NewBitWidth)1206b3f41edSDimitry Andric void APInt::reallocate(unsigned NewBitWidth) {
1216b3f41edSDimitry Andric // If the number of words is the same we can just change the width and stop.
1226b3f41edSDimitry Andric if (getNumWords() == getNumWords(NewBitWidth)) {
1236b3f41edSDimitry Andric BitWidth = NewBitWidth;
1246b3f41edSDimitry Andric return;
1256b3f41edSDimitry Andric }
1266b3f41edSDimitry Andric
1276b3f41edSDimitry Andric // If we have an allocation, delete it.
1286b3f41edSDimitry Andric if (!isSingleWord())
1296b3f41edSDimitry Andric delete [] U.pVal;
1306b3f41edSDimitry Andric
1316b3f41edSDimitry Andric // Update BitWidth.
1326b3f41edSDimitry Andric BitWidth = NewBitWidth;
1336b3f41edSDimitry Andric
1346b3f41edSDimitry Andric // If we are supposed to have an allocation, create it.
1356b3f41edSDimitry Andric if (!isSingleWord())
1366b3f41edSDimitry Andric U.pVal = getMemory(getNumWords());
1376b3f41edSDimitry Andric }
1386b3f41edSDimitry Andric
assignSlowCase(const APInt & RHS)139c0981da4SDimitry Andric void APInt::assignSlowCase(const APInt &RHS) {
140009b1c42SEd Schouten // Don't do anything for X = X
141009b1c42SEd Schouten if (this == &RHS)
142d99dafe2SDimitry Andric return;
143009b1c42SEd Schouten
1446b3f41edSDimitry Andric // Adjust the bit width and handle allocations as necessary.
1456b3f41edSDimitry Andric reallocate(RHS.getBitWidth());
146009b1c42SEd Schouten
1476b3f41edSDimitry Andric // Copy the data.
1486b3f41edSDimitry Andric if (isSingleWord())
149148779dfSDimitry Andric U.VAL = RHS.U.VAL;
1506b3f41edSDimitry Andric else
1516b3f41edSDimitry Andric memcpy(U.pVal, RHS.U.pVal, getNumWords() * APINT_WORD_SIZE);
152009b1c42SEd Schouten }
153009b1c42SEd Schouten
1545a5ac124SDimitry Andric /// This method 'profiles' an APInt for use with FoldingSet.
Profile(FoldingSetNodeID & ID) const155009b1c42SEd Schouten void APInt::Profile(FoldingSetNodeID& ID) const {
156009b1c42SEd Schouten ID.AddInteger(BitWidth);
157009b1c42SEd Schouten
158009b1c42SEd Schouten if (isSingleWord()) {
159148779dfSDimitry Andric ID.AddInteger(U.VAL);
160009b1c42SEd Schouten return;
161009b1c42SEd Schouten }
162009b1c42SEd Schouten
163009b1c42SEd Schouten unsigned NumWords = getNumWords();
164009b1c42SEd Schouten for (unsigned i = 0; i < NumWords; ++i)
165148779dfSDimitry Andric ID.AddInteger(U.pVal[i]);
166009b1c42SEd Schouten }
167009b1c42SEd Schouten
isAligned(Align A) const1687fa27ce4SDimitry Andric bool APInt::isAligned(Align A) const {
1697fa27ce4SDimitry Andric if (isZero())
1707fa27ce4SDimitry Andric return true;
1717fa27ce4SDimitry Andric const unsigned TrailingZeroes = countr_zero();
1727fa27ce4SDimitry Andric const unsigned MinimumTrailingZeroes = Log2(A);
1737fa27ce4SDimitry Andric return TrailingZeroes >= MinimumTrailingZeroes;
1747fa27ce4SDimitry Andric }
1757fa27ce4SDimitry Andric
176eb11fae6SDimitry Andric /// Prefix increment operator. Increments the APInt by one.
operator ++()177009b1c42SEd Schouten APInt& APInt::operator++() {
178009b1c42SEd Schouten if (isSingleWord())
179148779dfSDimitry Andric ++U.VAL;
180009b1c42SEd Schouten else
181148779dfSDimitry Andric tcIncrement(U.pVal, getNumWords());
182009b1c42SEd Schouten return clearUnusedBits();
183009b1c42SEd Schouten }
184009b1c42SEd Schouten
185eb11fae6SDimitry Andric /// Prefix decrement operator. Decrements the APInt by one.
operator --()186009b1c42SEd Schouten APInt& APInt::operator--() {
187009b1c42SEd Schouten if (isSingleWord())
188148779dfSDimitry Andric --U.VAL;
189009b1c42SEd Schouten else
190148779dfSDimitry Andric tcDecrement(U.pVal, getNumWords());
191009b1c42SEd Schouten return clearUnusedBits();
192009b1c42SEd Schouten }
193009b1c42SEd Schouten
194706b4fc4SDimitry Andric /// Adds the RHS APInt to this APInt.
195009b1c42SEd Schouten /// @returns this, after addition of RHS.
196eb11fae6SDimitry Andric /// Addition assignment operator.
operator +=(const APInt & RHS)197009b1c42SEd Schouten APInt& APInt::operator+=(const APInt& RHS) {
198009b1c42SEd Schouten assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
199009b1c42SEd Schouten if (isSingleWord())
200148779dfSDimitry Andric U.VAL += RHS.U.VAL;
20171d5a254SDimitry Andric else
202148779dfSDimitry Andric tcAdd(U.pVal, RHS.U.pVal, 0, getNumWords());
203009b1c42SEd Schouten return clearUnusedBits();
204009b1c42SEd Schouten }
205009b1c42SEd Schouten
operator +=(uint64_t RHS)206b915e9e0SDimitry Andric APInt& APInt::operator+=(uint64_t RHS) {
207b915e9e0SDimitry Andric if (isSingleWord())
208148779dfSDimitry Andric U.VAL += RHS;
209b915e9e0SDimitry Andric else
210148779dfSDimitry Andric tcAddPart(U.pVal, RHS, getNumWords());
211b915e9e0SDimitry Andric return clearUnusedBits();
212b915e9e0SDimitry Andric }
213b915e9e0SDimitry Andric
214009b1c42SEd Schouten /// Subtracts the RHS APInt from this APInt
215009b1c42SEd Schouten /// @returns this, after subtraction
216eb11fae6SDimitry Andric /// Subtraction assignment operator.
operator -=(const APInt & RHS)217009b1c42SEd Schouten APInt& APInt::operator-=(const APInt& RHS) {
218009b1c42SEd Schouten assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
219009b1c42SEd Schouten if (isSingleWord())
220148779dfSDimitry Andric U.VAL -= RHS.U.VAL;
221009b1c42SEd Schouten else
222148779dfSDimitry Andric tcSubtract(U.pVal, RHS.U.pVal, 0, getNumWords());
223009b1c42SEd Schouten return clearUnusedBits();
224009b1c42SEd Schouten }
225009b1c42SEd Schouten
operator -=(uint64_t RHS)226b915e9e0SDimitry Andric APInt& APInt::operator-=(uint64_t RHS) {
227b915e9e0SDimitry Andric if (isSingleWord())
228148779dfSDimitry Andric U.VAL -= RHS;
229b915e9e0SDimitry Andric else
230148779dfSDimitry Andric tcSubtractPart(U.pVal, RHS, getNumWords());
231b915e9e0SDimitry Andric return clearUnusedBits();
232b915e9e0SDimitry Andric }
233b915e9e0SDimitry Andric
operator *(const APInt & RHS) const234c46e6a59SDimitry Andric APInt APInt::operator*(const APInt& RHS) const {
235009b1c42SEd Schouten assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
236c46e6a59SDimitry Andric if (isSingleWord())
237c46e6a59SDimitry Andric return APInt(BitWidth, U.VAL * RHS.U.VAL);
238009b1c42SEd Schouten
239c46e6a59SDimitry Andric APInt Result(getMemory(getNumWords()), getBitWidth());
240c46e6a59SDimitry Andric tcMultiply(Result.U.pVal, U.pVal, RHS.U.pVal, getNumWords());
241c46e6a59SDimitry Andric Result.clearUnusedBits();
242c46e6a59SDimitry Andric return Result;
243009b1c42SEd Schouten }
244009b1c42SEd Schouten
andAssignSlowCase(const APInt & RHS)245c0981da4SDimitry Andric void APInt::andAssignSlowCase(const APInt &RHS) {
246c0981da4SDimitry Andric WordType *dst = U.pVal, *rhs = RHS.U.pVal;
247c0981da4SDimitry Andric for (size_t i = 0, e = getNumWords(); i != e; ++i)
248c0981da4SDimitry Andric dst[i] &= rhs[i];
249009b1c42SEd Schouten }
250009b1c42SEd Schouten
orAssignSlowCase(const APInt & RHS)251c0981da4SDimitry Andric void APInt::orAssignSlowCase(const APInt &RHS) {
252c0981da4SDimitry Andric WordType *dst = U.pVal, *rhs = RHS.U.pVal;
253c0981da4SDimitry Andric for (size_t i = 0, e = getNumWords(); i != e; ++i)
254c0981da4SDimitry Andric dst[i] |= rhs[i];
255009b1c42SEd Schouten }
256009b1c42SEd Schouten
xorAssignSlowCase(const APInt & RHS)257c0981da4SDimitry Andric void APInt::xorAssignSlowCase(const APInt &RHS) {
258c0981da4SDimitry Andric WordType *dst = U.pVal, *rhs = RHS.U.pVal;
259c0981da4SDimitry Andric for (size_t i = 0, e = getNumWords(); i != e; ++i)
260c0981da4SDimitry Andric dst[i] ^= rhs[i];
261009b1c42SEd Schouten }
262009b1c42SEd Schouten
operator *=(const APInt & RHS)263c46e6a59SDimitry Andric APInt &APInt::operator*=(const APInt &RHS) {
264c46e6a59SDimitry Andric *this = *this * RHS;
265c46e6a59SDimitry Andric return *this;
266c46e6a59SDimitry Andric }
267c46e6a59SDimitry Andric
operator *=(uint64_t RHS)268c46e6a59SDimitry Andric APInt& APInt::operator*=(uint64_t RHS) {
269c46e6a59SDimitry Andric if (isSingleWord()) {
270c46e6a59SDimitry Andric U.VAL *= RHS;
271c46e6a59SDimitry Andric } else {
272c46e6a59SDimitry Andric unsigned NumWords = getNumWords();
273c46e6a59SDimitry Andric tcMultiplyPart(U.pVal, U.pVal, RHS, 0, NumWords, NumWords, false);
274c46e6a59SDimitry Andric }
275c46e6a59SDimitry Andric return clearUnusedBits();
276009b1c42SEd Schouten }
277009b1c42SEd Schouten
equalSlowCase(const APInt & RHS) const278c0981da4SDimitry Andric bool APInt::equalSlowCase(const APInt &RHS) const {
279148779dfSDimitry Andric return std::equal(U.pVal, U.pVal + getNumWords(), RHS.U.pVal);
280009b1c42SEd Schouten }
281009b1c42SEd Schouten
compare(const APInt & RHS) const28212f3ca4cSDimitry Andric int APInt::compare(const APInt& RHS) const {
283009b1c42SEd Schouten assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
284009b1c42SEd Schouten if (isSingleWord())
285148779dfSDimitry Andric return U.VAL < RHS.U.VAL ? -1 : U.VAL > RHS.U.VAL;
286009b1c42SEd Schouten
287148779dfSDimitry Andric return tcCompare(U.pVal, RHS.U.pVal, getNumWords());
288009b1c42SEd Schouten }
289009b1c42SEd Schouten
compareSigned(const APInt & RHS) const29012f3ca4cSDimitry Andric int APInt::compareSigned(const APInt& RHS) const {
291009b1c42SEd Schouten assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
292009b1c42SEd Schouten if (isSingleWord()) {
293148779dfSDimitry Andric int64_t lhsSext = SignExtend64(U.VAL, BitWidth);
294148779dfSDimitry Andric int64_t rhsSext = SignExtend64(RHS.U.VAL, BitWidth);
29512f3ca4cSDimitry Andric return lhsSext < rhsSext ? -1 : lhsSext > rhsSext;
296009b1c42SEd Schouten }
297009b1c42SEd Schouten
298009b1c42SEd Schouten bool lhsNeg = isNegative();
29901095a5dSDimitry Andric bool rhsNeg = RHS.isNegative();
300009b1c42SEd Schouten
30101095a5dSDimitry Andric // If the sign bits don't match, then (LHS < RHS) if LHS is negative
30201095a5dSDimitry Andric if (lhsNeg != rhsNeg)
30312f3ca4cSDimitry Andric return lhsNeg ? -1 : 1;
30401095a5dSDimitry Andric
30571d5a254SDimitry Andric // Otherwise we can just use an unsigned comparison, because even negative
30601095a5dSDimitry Andric // numbers compare correctly this way if both have the same signed-ness.
307148779dfSDimitry Andric return tcCompare(U.pVal, RHS.U.pVal, getNumWords());
308009b1c42SEd Schouten }
309009b1c42SEd Schouten
setBitsSlowCase(unsigned loBit,unsigned hiBit)31071d5a254SDimitry Andric void APInt::setBitsSlowCase(unsigned loBit, unsigned hiBit) {
31171d5a254SDimitry Andric unsigned loWord = whichWord(loBit);
31271d5a254SDimitry Andric unsigned hiWord = whichWord(hiBit);
31371d5a254SDimitry Andric
31471d5a254SDimitry Andric // Create an initial mask for the low word with zeros below loBit.
315d8e91e46SDimitry Andric uint64_t loMask = WORDTYPE_MAX << whichBit(loBit);
31671d5a254SDimitry Andric
31771d5a254SDimitry Andric // If hiBit is not aligned, we need a high mask.
31871d5a254SDimitry Andric unsigned hiShiftAmt = whichBit(hiBit);
31971d5a254SDimitry Andric if (hiShiftAmt != 0) {
32071d5a254SDimitry Andric // Create a high mask with zeros above hiBit.
321d8e91e46SDimitry Andric uint64_t hiMask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - hiShiftAmt);
32271d5a254SDimitry Andric // If loWord and hiWord are equal, then we combine the masks. Otherwise,
32371d5a254SDimitry Andric // set the bits in hiWord.
32471d5a254SDimitry Andric if (hiWord == loWord)
32571d5a254SDimitry Andric loMask &= hiMask;
32671d5a254SDimitry Andric else
327148779dfSDimitry Andric U.pVal[hiWord] |= hiMask;
32871d5a254SDimitry Andric }
32971d5a254SDimitry Andric // Apply the mask to the low word.
330148779dfSDimitry Andric U.pVal[loWord] |= loMask;
33171d5a254SDimitry Andric
33271d5a254SDimitry Andric // Fill any words between loWord and hiWord with all ones.
33371d5a254SDimitry Andric for (unsigned word = loWord + 1; word < hiWord; ++word)
334d8e91e46SDimitry Andric U.pVal[word] = WORDTYPE_MAX;
33571d5a254SDimitry Andric }
33671d5a254SDimitry Andric
337c0981da4SDimitry Andric // Complement a bignum in-place.
tcComplement(APInt::WordType * dst,unsigned parts)338c0981da4SDimitry Andric static void tcComplement(APInt::WordType *dst, unsigned parts) {
339c0981da4SDimitry Andric for (unsigned i = 0; i < parts; i++)
340c0981da4SDimitry Andric dst[i] = ~dst[i];
341c0981da4SDimitry Andric }
342c0981da4SDimitry Andric
343eb11fae6SDimitry Andric /// Toggle every bit to its opposite value.
flipAllBitsSlowCase()34471d5a254SDimitry Andric void APInt::flipAllBitsSlowCase() {
345148779dfSDimitry Andric tcComplement(U.pVal, getNumWords());
34671d5a254SDimitry Andric clearUnusedBits();
34771d5a254SDimitry Andric }
348009b1c42SEd Schouten
349c0981da4SDimitry Andric /// Concatenate the bits from "NewLSB" onto the bottom of *this. This is
350c0981da4SDimitry Andric /// equivalent to:
351c0981da4SDimitry Andric /// (this->zext(NewWidth) << NewLSB.getBitWidth()) | NewLSB.zext(NewWidth)
352c0981da4SDimitry Andric /// In the slow case, we know the result is large.
concatSlowCase(const APInt & NewLSB) const353c0981da4SDimitry Andric APInt APInt::concatSlowCase(const APInt &NewLSB) const {
354c0981da4SDimitry Andric unsigned NewWidth = getBitWidth() + NewLSB.getBitWidth();
355145449b1SDimitry Andric APInt Result = NewLSB.zext(NewWidth);
356c0981da4SDimitry Andric Result.insertBits(*this, NewLSB.getBitWidth());
357c0981da4SDimitry Andric return Result;
358c0981da4SDimitry Andric }
359c0981da4SDimitry Andric
360009b1c42SEd Schouten /// Toggle a given bit to its opposite value whose position is given
361009b1c42SEd Schouten /// as "bitPosition".
362eb11fae6SDimitry Andric /// Toggles a given bit to its opposite value.
flipBit(unsigned bitPosition)363cf099d11SDimitry Andric void APInt::flipBit(unsigned bitPosition) {
364009b1c42SEd Schouten assert(bitPosition < BitWidth && "Out of the bit-width range!");
365b60736ecSDimitry Andric setBitVal(bitPosition, !(*this)[bitPosition]);
366009b1c42SEd Schouten }
367009b1c42SEd Schouten
insertBits(const APInt & subBits,unsigned bitPosition)36871d5a254SDimitry Andric void APInt::insertBits(const APInt &subBits, unsigned bitPosition) {
36971d5a254SDimitry Andric unsigned subBitWidth = subBits.getBitWidth();
370c0981da4SDimitry Andric assert((subBitWidth + bitPosition) <= BitWidth && "Illegal bit insertion");
371c0981da4SDimitry Andric
372c0981da4SDimitry Andric // inserting no bits is a noop.
373c0981da4SDimitry Andric if (subBitWidth == 0)
374c0981da4SDimitry Andric return;
37571d5a254SDimitry Andric
37671d5a254SDimitry Andric // Insertion is a direct copy.
37771d5a254SDimitry Andric if (subBitWidth == BitWidth) {
37871d5a254SDimitry Andric *this = subBits;
37971d5a254SDimitry Andric return;
38071d5a254SDimitry Andric }
38171d5a254SDimitry Andric
38271d5a254SDimitry Andric // Single word result can be done as a direct bitmask.
38371d5a254SDimitry Andric if (isSingleWord()) {
384d8e91e46SDimitry Andric uint64_t mask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - subBitWidth);
385148779dfSDimitry Andric U.VAL &= ~(mask << bitPosition);
386148779dfSDimitry Andric U.VAL |= (subBits.U.VAL << bitPosition);
38771d5a254SDimitry Andric return;
38871d5a254SDimitry Andric }
38971d5a254SDimitry Andric
39071d5a254SDimitry Andric unsigned loBit = whichBit(bitPosition);
39171d5a254SDimitry Andric unsigned loWord = whichWord(bitPosition);
39271d5a254SDimitry Andric unsigned hi1Word = whichWord(bitPosition + subBitWidth - 1);
39371d5a254SDimitry Andric
39471d5a254SDimitry Andric // Insertion within a single word can be done as a direct bitmask.
39571d5a254SDimitry Andric if (loWord == hi1Word) {
396d8e91e46SDimitry Andric uint64_t mask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - subBitWidth);
397148779dfSDimitry Andric U.pVal[loWord] &= ~(mask << loBit);
398148779dfSDimitry Andric U.pVal[loWord] |= (subBits.U.VAL << loBit);
39971d5a254SDimitry Andric return;
40071d5a254SDimitry Andric }
40171d5a254SDimitry Andric
40271d5a254SDimitry Andric // Insert on word boundaries.
40371d5a254SDimitry Andric if (loBit == 0) {
40471d5a254SDimitry Andric // Direct copy whole words.
40571d5a254SDimitry Andric unsigned numWholeSubWords = subBitWidth / APINT_BITS_PER_WORD;
406148779dfSDimitry Andric memcpy(U.pVal + loWord, subBits.getRawData(),
40771d5a254SDimitry Andric numWholeSubWords * APINT_WORD_SIZE);
40871d5a254SDimitry Andric
40971d5a254SDimitry Andric // Mask+insert remaining bits.
41071d5a254SDimitry Andric unsigned remainingBits = subBitWidth % APINT_BITS_PER_WORD;
41171d5a254SDimitry Andric if (remainingBits != 0) {
412d8e91e46SDimitry Andric uint64_t mask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - remainingBits);
413148779dfSDimitry Andric U.pVal[hi1Word] &= ~mask;
414148779dfSDimitry Andric U.pVal[hi1Word] |= subBits.getWord(subBitWidth - 1);
41571d5a254SDimitry Andric }
41671d5a254SDimitry Andric return;
41771d5a254SDimitry Andric }
41871d5a254SDimitry Andric
41971d5a254SDimitry Andric // General case - set/clear individual bits in dst based on src.
42071d5a254SDimitry Andric // TODO - there is scope for optimization here, but at the moment this code
42171d5a254SDimitry Andric // path is barely used so prefer readability over performance.
422b60736ecSDimitry Andric for (unsigned i = 0; i != subBitWidth; ++i)
423b60736ecSDimitry Andric setBitVal(bitPosition + i, subBits[i]);
42471d5a254SDimitry Andric }
42571d5a254SDimitry Andric
insertBits(uint64_t subBits,unsigned bitPosition,unsigned numBits)4261d5ae102SDimitry Andric void APInt::insertBits(uint64_t subBits, unsigned bitPosition, unsigned numBits) {
4271d5ae102SDimitry Andric uint64_t maskBits = maskTrailingOnes<uint64_t>(numBits);
4281d5ae102SDimitry Andric subBits &= maskBits;
4291d5ae102SDimitry Andric if (isSingleWord()) {
4301d5ae102SDimitry Andric U.VAL &= ~(maskBits << bitPosition);
4311d5ae102SDimitry Andric U.VAL |= subBits << bitPosition;
4321d5ae102SDimitry Andric return;
4331d5ae102SDimitry Andric }
4341d5ae102SDimitry Andric
4351d5ae102SDimitry Andric unsigned loBit = whichBit(bitPosition);
4361d5ae102SDimitry Andric unsigned loWord = whichWord(bitPosition);
4371d5ae102SDimitry Andric unsigned hiWord = whichWord(bitPosition + numBits - 1);
4381d5ae102SDimitry Andric if (loWord == hiWord) {
4391d5ae102SDimitry Andric U.pVal[loWord] &= ~(maskBits << loBit);
4401d5ae102SDimitry Andric U.pVal[loWord] |= subBits << loBit;
4411d5ae102SDimitry Andric return;
4421d5ae102SDimitry Andric }
4431d5ae102SDimitry Andric
4441d5ae102SDimitry Andric static_assert(8 * sizeof(WordType) <= 64, "This code assumes only two words affected");
4451d5ae102SDimitry Andric unsigned wordBits = 8 * sizeof(WordType);
4461d5ae102SDimitry Andric U.pVal[loWord] &= ~(maskBits << loBit);
4471d5ae102SDimitry Andric U.pVal[loWord] |= subBits << loBit;
4481d5ae102SDimitry Andric
4491d5ae102SDimitry Andric U.pVal[hiWord] &= ~(maskBits >> (wordBits - loBit));
4501d5ae102SDimitry Andric U.pVal[hiWord] |= subBits >> (wordBits - loBit);
4511d5ae102SDimitry Andric }
4521d5ae102SDimitry Andric
extractBits(unsigned numBits,unsigned bitPosition) const45371d5a254SDimitry Andric APInt APInt::extractBits(unsigned numBits, unsigned bitPosition) const {
45471d5a254SDimitry Andric assert(bitPosition < BitWidth && (numBits + bitPosition) <= BitWidth &&
45571d5a254SDimitry Andric "Illegal bit extraction");
45671d5a254SDimitry Andric
45771d5a254SDimitry Andric if (isSingleWord())
458148779dfSDimitry Andric return APInt(numBits, U.VAL >> bitPosition);
45971d5a254SDimitry Andric
46071d5a254SDimitry Andric unsigned loBit = whichBit(bitPosition);
46171d5a254SDimitry Andric unsigned loWord = whichWord(bitPosition);
46271d5a254SDimitry Andric unsigned hiWord = whichWord(bitPosition + numBits - 1);
46371d5a254SDimitry Andric
46471d5a254SDimitry Andric // Single word result extracting bits from a single word source.
46571d5a254SDimitry Andric if (loWord == hiWord)
466148779dfSDimitry Andric return APInt(numBits, U.pVal[loWord] >> loBit);
46771d5a254SDimitry Andric
46871d5a254SDimitry Andric // Extracting bits that start on a source word boundary can be done
46971d5a254SDimitry Andric // as a fast memory copy.
47071d5a254SDimitry Andric if (loBit == 0)
471e3b55780SDimitry Andric return APInt(numBits, ArrayRef(U.pVal + loWord, 1 + hiWord - loWord));
47271d5a254SDimitry Andric
47371d5a254SDimitry Andric // General case - shift + copy source words directly into place.
47471d5a254SDimitry Andric APInt Result(numBits, 0);
47571d5a254SDimitry Andric unsigned NumSrcWords = getNumWords();
47671d5a254SDimitry Andric unsigned NumDstWords = Result.getNumWords();
47771d5a254SDimitry Andric
478eb11fae6SDimitry Andric uint64_t *DestPtr = Result.isSingleWord() ? &Result.U.VAL : Result.U.pVal;
47971d5a254SDimitry Andric for (unsigned word = 0; word < NumDstWords; ++word) {
480148779dfSDimitry Andric uint64_t w0 = U.pVal[loWord + word];
48171d5a254SDimitry Andric uint64_t w1 =
482148779dfSDimitry Andric (loWord + word + 1) < NumSrcWords ? U.pVal[loWord + word + 1] : 0;
483eb11fae6SDimitry Andric DestPtr[word] = (w0 >> loBit) | (w1 << (APINT_BITS_PER_WORD - loBit));
48471d5a254SDimitry Andric }
48571d5a254SDimitry Andric
48671d5a254SDimitry Andric return Result.clearUnusedBits();
48771d5a254SDimitry Andric }
48871d5a254SDimitry Andric
extractBitsAsZExtValue(unsigned numBits,unsigned bitPosition) const4891d5ae102SDimitry Andric uint64_t APInt::extractBitsAsZExtValue(unsigned numBits,
4901d5ae102SDimitry Andric unsigned bitPosition) const {
4911d5ae102SDimitry Andric assert(bitPosition < BitWidth && (numBits + bitPosition) <= BitWidth &&
4921d5ae102SDimitry Andric "Illegal bit extraction");
4931d5ae102SDimitry Andric assert(numBits <= 64 && "Illegal bit extraction");
4941d5ae102SDimitry Andric
4951d5ae102SDimitry Andric uint64_t maskBits = maskTrailingOnes<uint64_t>(numBits);
4961d5ae102SDimitry Andric if (isSingleWord())
4971d5ae102SDimitry Andric return (U.VAL >> bitPosition) & maskBits;
4981d5ae102SDimitry Andric
4991d5ae102SDimitry Andric unsigned loBit = whichBit(bitPosition);
5001d5ae102SDimitry Andric unsigned loWord = whichWord(bitPosition);
5011d5ae102SDimitry Andric unsigned hiWord = whichWord(bitPosition + numBits - 1);
5021d5ae102SDimitry Andric if (loWord == hiWord)
5031d5ae102SDimitry Andric return (U.pVal[loWord] >> loBit) & maskBits;
5041d5ae102SDimitry Andric
5051d5ae102SDimitry Andric static_assert(8 * sizeof(WordType) <= 64, "This code assumes only two words affected");
5061d5ae102SDimitry Andric unsigned wordBits = 8 * sizeof(WordType);
5071d5ae102SDimitry Andric uint64_t retBits = U.pVal[loWord] >> loBit;
5081d5ae102SDimitry Andric retBits |= U.pVal[hiWord] << (wordBits - loBit);
5091d5ae102SDimitry Andric retBits &= maskBits;
5101d5ae102SDimitry Andric return retBits;
5111d5ae102SDimitry Andric }
5121d5ae102SDimitry Andric
getSufficientBitsNeeded(StringRef Str,uint8_t Radix)513145449b1SDimitry Andric unsigned APInt::getSufficientBitsNeeded(StringRef Str, uint8_t Radix) {
514145449b1SDimitry Andric assert(!Str.empty() && "Invalid string length");
515145449b1SDimitry Andric size_t StrLen = Str.size();
516009b1c42SEd Schouten
517145449b1SDimitry Andric // Each computation below needs to know if it's negative.
518145449b1SDimitry Andric unsigned IsNegative = false;
519145449b1SDimitry Andric if (Str[0] == '-' || Str[0] == '+') {
520145449b1SDimitry Andric IsNegative = Str[0] == '-';
521145449b1SDimitry Andric StrLen--;
522145449b1SDimitry Andric assert(StrLen && "String is only a sign, needs a value.");
523145449b1SDimitry Andric }
524145449b1SDimitry Andric
525145449b1SDimitry Andric // For radixes of power-of-two values, the bits required is accurately and
526145449b1SDimitry Andric // easily computed.
527145449b1SDimitry Andric if (Radix == 2)
528145449b1SDimitry Andric return StrLen + IsNegative;
529145449b1SDimitry Andric if (Radix == 8)
530145449b1SDimitry Andric return StrLen * 3 + IsNegative;
531145449b1SDimitry Andric if (Radix == 16)
532145449b1SDimitry Andric return StrLen * 4 + IsNegative;
533145449b1SDimitry Andric
534145449b1SDimitry Andric // Compute a sufficient number of bits that is always large enough but might
535145449b1SDimitry Andric // be too large. This avoids the assertion in the constructor. This
536145449b1SDimitry Andric // calculation doesn't work appropriately for the numbers 0-9, so just use 4
537145449b1SDimitry Andric // bits in that case.
538145449b1SDimitry Andric if (Radix == 10)
539145449b1SDimitry Andric return (StrLen == 1 ? 4 : StrLen * 64 / 18) + IsNegative;
540145449b1SDimitry Andric
541145449b1SDimitry Andric assert(Radix == 36);
542145449b1SDimitry Andric return (StrLen == 1 ? 7 : StrLen * 16 / 3) + IsNegative;
543145449b1SDimitry Andric }
544145449b1SDimitry Andric
getBitsNeeded(StringRef str,uint8_t radix)545145449b1SDimitry Andric unsigned APInt::getBitsNeeded(StringRef str, uint8_t radix) {
546145449b1SDimitry Andric // Compute a sufficient number of bits that is always large enough but might
547145449b1SDimitry Andric // be too large.
548145449b1SDimitry Andric unsigned sufficient = getSufficientBitsNeeded(str, radix);
549145449b1SDimitry Andric
550145449b1SDimitry Andric // For bases 2, 8, and 16, the sufficient number of bits is exact and we can
551145449b1SDimitry Andric // return the value directly. For bases 10 and 36, we need to do extra work.
552145449b1SDimitry Andric if (radix == 2 || radix == 8 || radix == 16)
553145449b1SDimitry Andric return sufficient;
554145449b1SDimitry Andric
555145449b1SDimitry Andric // This is grossly inefficient but accurate. We could probably do something
556145449b1SDimitry Andric // with a computation of roughly slen*64/20 and then adjust by the value of
557145449b1SDimitry Andric // the first few digits. But, I'm not sure how accurate that could be.
55859850d08SRoman Divacky size_t slen = str.size();
55959850d08SRoman Divacky
56059850d08SRoman Divacky // Each computation below needs to know if it's negative.
56159850d08SRoman Divacky StringRef::iterator p = str.begin();
56259850d08SRoman Divacky unsigned isNegative = *p == '-';
56359850d08SRoman Divacky if (*p == '-' || *p == '+') {
56459850d08SRoman Divacky p++;
565009b1c42SEd Schouten slen--;
56659850d08SRoman Divacky assert(slen && "String is only a sign, needs a value.");
567009b1c42SEd Schouten }
56859850d08SRoman Divacky
569009b1c42SEd Schouten
570009b1c42SEd Schouten // Convert to the actual binary value.
57159850d08SRoman Divacky APInt tmp(sufficient, StringRef(p, slen), radix);
572009b1c42SEd Schouten
57359850d08SRoman Divacky // Compute how many bits are required. If the log is infinite, assume we need
574e6d15924SDimitry Andric // just bit. If the log is exact and value is negative, then the value is
575e6d15924SDimitry Andric // MinSignedValue with (log + 1) bits.
57659850d08SRoman Divacky unsigned log = tmp.logBase2();
57759850d08SRoman Divacky if (log == (unsigned)-1) {
57859850d08SRoman Divacky return isNegative + 1;
579e6d15924SDimitry Andric } else if (isNegative && tmp.isPowerOf2()) {
580e6d15924SDimitry Andric return isNegative + log;
58159850d08SRoman Divacky } else {
58259850d08SRoman Divacky return isNegative + log + 1;
58359850d08SRoman Divacky }
584009b1c42SEd Schouten }
585009b1c42SEd Schouten
hash_value(const APInt & Arg)58663faed5bSDimitry Andric hash_code llvm::hash_value(const APInt &Arg) {
58763faed5bSDimitry Andric if (Arg.isSingleWord())
588cfca06d7SDimitry Andric return hash_combine(Arg.BitWidth, Arg.U.VAL);
589009b1c42SEd Schouten
590cfca06d7SDimitry Andric return hash_combine(
591cfca06d7SDimitry Andric Arg.BitWidth,
592cfca06d7SDimitry Andric hash_combine_range(Arg.U.pVal, Arg.U.pVal + Arg.getNumWords()));
593009b1c42SEd Schouten }
594009b1c42SEd Schouten
getHashValue(const APInt & Key)595c0981da4SDimitry Andric unsigned DenseMapInfo<APInt, void>::getHashValue(const APInt &Key) {
596344a3780SDimitry Andric return static_cast<unsigned>(hash_value(Key));
597344a3780SDimitry Andric }
598344a3780SDimitry Andric
isSplat(unsigned SplatSizeInBits) const5995a5ac124SDimitry Andric bool APInt::isSplat(unsigned SplatSizeInBits) const {
6005a5ac124SDimitry Andric assert(getBitWidth() % SplatSizeInBits == 0 &&
6015a5ac124SDimitry Andric "SplatSizeInBits must divide width!");
6025a5ac124SDimitry Andric // We can check that all parts of an integer are equal by making use of a
6035a5ac124SDimitry Andric // little trick: rotate and check if it's still the same value.
6045a5ac124SDimitry Andric return *this == rotl(SplatSizeInBits);
6055a5ac124SDimitry Andric }
6065a5ac124SDimitry Andric
6075a5ac124SDimitry Andric /// This function returns the high "numBits" bits of this APInt.
getHiBits(unsigned numBits) const608009b1c42SEd Schouten APInt APInt::getHiBits(unsigned numBits) const {
60971d5a254SDimitry Andric return this->lshr(BitWidth - numBits);
610009b1c42SEd Schouten }
611009b1c42SEd Schouten
6125a5ac124SDimitry Andric /// This function returns the low "numBits" bits of this APInt.
getLoBits(unsigned numBits) const613009b1c42SEd Schouten APInt APInt::getLoBits(unsigned numBits) const {
61471d5a254SDimitry Andric APInt Result(getLowBitsSet(BitWidth, numBits));
61571d5a254SDimitry Andric Result &= *this;
61671d5a254SDimitry Andric return Result;
617009b1c42SEd Schouten }
618009b1c42SEd Schouten
619a303c417SDimitry Andric /// Return a value containing V broadcasted over NewLen bits.
getSplat(unsigned NewLen,const APInt & V)620a303c417SDimitry Andric APInt APInt::getSplat(unsigned NewLen, const APInt &V) {
621a303c417SDimitry Andric assert(NewLen >= V.getBitWidth() && "Can't splat to smaller bit width!");
622a303c417SDimitry Andric
623145449b1SDimitry Andric APInt Val = V.zext(NewLen);
624a303c417SDimitry Andric for (unsigned I = V.getBitWidth(); I < NewLen; I <<= 1)
625a303c417SDimitry Andric Val |= Val << I;
626a303c417SDimitry Andric
627a303c417SDimitry Andric return Val;
628a303c417SDimitry Andric }
629a303c417SDimitry Andric
countLeadingZerosSlowCase() const630009b1c42SEd Schouten unsigned APInt::countLeadingZerosSlowCase() const {
63101095a5dSDimitry Andric unsigned Count = 0;
63201095a5dSDimitry Andric for (int i = getNumWords()-1; i >= 0; --i) {
633148779dfSDimitry Andric uint64_t V = U.pVal[i];
63401095a5dSDimitry Andric if (V == 0)
635009b1c42SEd Schouten Count += APINT_BITS_PER_WORD;
636009b1c42SEd Schouten else {
6377fa27ce4SDimitry Andric Count += llvm::countl_zero(V);
638009b1c42SEd Schouten break;
639009b1c42SEd Schouten }
640009b1c42SEd Schouten }
64101095a5dSDimitry Andric // Adjust for unused bits in the most significant word (they are zero).
64201095a5dSDimitry Andric unsigned Mod = BitWidth % APINT_BITS_PER_WORD;
64301095a5dSDimitry Andric Count -= Mod > 0 ? APINT_BITS_PER_WORD - Mod : 0;
6446fe5c7aaSRoman Divacky return Count;
645009b1c42SEd Schouten }
646009b1c42SEd Schouten
countLeadingOnesSlowCase() const64708bbd35aSDimitry Andric unsigned APInt::countLeadingOnesSlowCase() const {
648009b1c42SEd Schouten unsigned highWordBits = BitWidth % APINT_BITS_PER_WORD;
649009b1c42SEd Schouten unsigned shift;
650009b1c42SEd Schouten if (!highWordBits) {
651009b1c42SEd Schouten highWordBits = APINT_BITS_PER_WORD;
652009b1c42SEd Schouten shift = 0;
653009b1c42SEd Schouten } else {
654009b1c42SEd Schouten shift = APINT_BITS_PER_WORD - highWordBits;
655009b1c42SEd Schouten }
656009b1c42SEd Schouten int i = getNumWords() - 1;
6577fa27ce4SDimitry Andric unsigned Count = llvm::countl_one(U.pVal[i] << shift);
658009b1c42SEd Schouten if (Count == highWordBits) {
659009b1c42SEd Schouten for (i--; i >= 0; --i) {
660d8e91e46SDimitry Andric if (U.pVal[i] == WORDTYPE_MAX)
661009b1c42SEd Schouten Count += APINT_BITS_PER_WORD;
662009b1c42SEd Schouten else {
6637fa27ce4SDimitry Andric Count += llvm::countl_one(U.pVal[i]);
664009b1c42SEd Schouten break;
665009b1c42SEd Schouten }
666009b1c42SEd Schouten }
667009b1c42SEd Schouten }
668009b1c42SEd Schouten return Count;
669009b1c42SEd Schouten }
670009b1c42SEd Schouten
countTrailingZerosSlowCase() const67108bbd35aSDimitry Andric unsigned APInt::countTrailingZerosSlowCase() const {
672009b1c42SEd Schouten unsigned Count = 0;
673009b1c42SEd Schouten unsigned i = 0;
674148779dfSDimitry Andric for (; i < getNumWords() && U.pVal[i] == 0; ++i)
675009b1c42SEd Schouten Count += APINT_BITS_PER_WORD;
676009b1c42SEd Schouten if (i < getNumWords())
6777fa27ce4SDimitry Andric Count += llvm::countr_zero(U.pVal[i]);
678009b1c42SEd Schouten return std::min(Count, BitWidth);
679009b1c42SEd Schouten }
680009b1c42SEd Schouten
countTrailingOnesSlowCase() const681009b1c42SEd Schouten unsigned APInt::countTrailingOnesSlowCase() const {
682009b1c42SEd Schouten unsigned Count = 0;
683009b1c42SEd Schouten unsigned i = 0;
684d8e91e46SDimitry Andric for (; i < getNumWords() && U.pVal[i] == WORDTYPE_MAX; ++i)
685009b1c42SEd Schouten Count += APINT_BITS_PER_WORD;
686009b1c42SEd Schouten if (i < getNumWords())
6877fa27ce4SDimitry Andric Count += llvm::countr_one(U.pVal[i]);
68812f3ca4cSDimitry Andric assert(Count <= BitWidth);
68912f3ca4cSDimitry Andric return Count;
690009b1c42SEd Schouten }
691009b1c42SEd Schouten
countPopulationSlowCase() const692009b1c42SEd Schouten unsigned APInt::countPopulationSlowCase() const {
693009b1c42SEd Schouten unsigned Count = 0;
694009b1c42SEd Schouten for (unsigned i = 0; i < getNumWords(); ++i)
695e3b55780SDimitry Andric Count += llvm::popcount(U.pVal[i]);
696009b1c42SEd Schouten return Count;
697009b1c42SEd Schouten }
698009b1c42SEd Schouten
intersectsSlowCase(const APInt & RHS) const699d99dafe2SDimitry Andric bool APInt::intersectsSlowCase(const APInt &RHS) const {
700d99dafe2SDimitry Andric for (unsigned i = 0, e = getNumWords(); i != e; ++i)
701148779dfSDimitry Andric if ((U.pVal[i] & RHS.U.pVal[i]) != 0)
702d99dafe2SDimitry Andric return true;
703d99dafe2SDimitry Andric
704d99dafe2SDimitry Andric return false;
705d99dafe2SDimitry Andric }
706d99dafe2SDimitry Andric
isSubsetOfSlowCase(const APInt & RHS) const707d99dafe2SDimitry Andric bool APInt::isSubsetOfSlowCase(const APInt &RHS) const {
708d99dafe2SDimitry Andric for (unsigned i = 0, e = getNumWords(); i != e; ++i)
709148779dfSDimitry Andric if ((U.pVal[i] & ~RHS.U.pVal[i]) != 0)
710d99dafe2SDimitry Andric return false;
711d99dafe2SDimitry Andric
712d99dafe2SDimitry Andric return true;
713d99dafe2SDimitry Andric }
714d99dafe2SDimitry Andric
byteSwap() const715009b1c42SEd Schouten APInt APInt::byteSwap() const {
716cfca06d7SDimitry Andric assert(BitWidth >= 16 && BitWidth % 8 == 0 && "Cannot byteswap!");
717009b1c42SEd Schouten if (BitWidth == 16)
7187fa27ce4SDimitry Andric return APInt(BitWidth, llvm::byteswap<uint16_t>(U.VAL));
71963faed5bSDimitry Andric if (BitWidth == 32)
7207fa27ce4SDimitry Andric return APInt(BitWidth, llvm::byteswap<uint32_t>(U.VAL));
721cfca06d7SDimitry Andric if (BitWidth <= 64) {
7227fa27ce4SDimitry Andric uint64_t Tmp1 = llvm::byteswap<uint64_t>(U.VAL);
723cfca06d7SDimitry Andric Tmp1 >>= (64 - BitWidth);
724cfca06d7SDimitry Andric return APInt(BitWidth, Tmp1);
72563faed5bSDimitry Andric }
72663faed5bSDimitry Andric
72763faed5bSDimitry Andric APInt Result(getNumWords() * APINT_BITS_PER_WORD, 0);
72863faed5bSDimitry Andric for (unsigned I = 0, N = getNumWords(); I != N; ++I)
7297fa27ce4SDimitry Andric Result.U.pVal[I] = llvm::byteswap<uint64_t>(U.pVal[N - I - 1]);
73063faed5bSDimitry Andric if (Result.BitWidth != BitWidth) {
73171d5a254SDimitry Andric Result.lshrInPlace(Result.BitWidth - BitWidth);
73263faed5bSDimitry Andric Result.BitWidth = BitWidth;
733009b1c42SEd Schouten }
734009b1c42SEd Schouten return Result;
735009b1c42SEd Schouten }
736009b1c42SEd Schouten
reverseBits() const73701095a5dSDimitry Andric APInt APInt::reverseBits() const {
73801095a5dSDimitry Andric switch (BitWidth) {
73901095a5dSDimitry Andric case 64:
740148779dfSDimitry Andric return APInt(BitWidth, llvm::reverseBits<uint64_t>(U.VAL));
74101095a5dSDimitry Andric case 32:
742148779dfSDimitry Andric return APInt(BitWidth, llvm::reverseBits<uint32_t>(U.VAL));
74301095a5dSDimitry Andric case 16:
744148779dfSDimitry Andric return APInt(BitWidth, llvm::reverseBits<uint16_t>(U.VAL));
74501095a5dSDimitry Andric case 8:
746148779dfSDimitry Andric return APInt(BitWidth, llvm::reverseBits<uint8_t>(U.VAL));
747c0981da4SDimitry Andric case 0:
748c0981da4SDimitry Andric return *this;
74901095a5dSDimitry Andric default:
75001095a5dSDimitry Andric break;
75101095a5dSDimitry Andric }
75201095a5dSDimitry Andric
75301095a5dSDimitry Andric APInt Val(*this);
754d99dafe2SDimitry Andric APInt Reversed(BitWidth, 0);
755d99dafe2SDimitry Andric unsigned S = BitWidth;
75601095a5dSDimitry Andric
757d99dafe2SDimitry Andric for (; Val != 0; Val.lshrInPlace(1)) {
75801095a5dSDimitry Andric Reversed <<= 1;
759d99dafe2SDimitry Andric Reversed |= Val[0];
76001095a5dSDimitry Andric --S;
76101095a5dSDimitry Andric }
76201095a5dSDimitry Andric
76301095a5dSDimitry Andric Reversed <<= S;
76401095a5dSDimitry Andric return Reversed;
76501095a5dSDimitry Andric }
76601095a5dSDimitry Andric
GreatestCommonDivisor(APInt A,APInt B)76771d5a254SDimitry Andric APInt llvm::APIntOps::GreatestCommonDivisor(APInt A, APInt B) {
76871d5a254SDimitry Andric // Fast-path a common case.
76971d5a254SDimitry Andric if (A == B) return A;
77071d5a254SDimitry Andric
77171d5a254SDimitry Andric // Corner cases: if either operand is zero, the other is the gcd.
77271d5a254SDimitry Andric if (!A) return B;
77371d5a254SDimitry Andric if (!B) return A;
77471d5a254SDimitry Andric
77571d5a254SDimitry Andric // Count common powers of 2 and remove all other powers of 2.
77671d5a254SDimitry Andric unsigned Pow2;
77771d5a254SDimitry Andric {
7787fa27ce4SDimitry Andric unsigned Pow2_A = A.countr_zero();
7797fa27ce4SDimitry Andric unsigned Pow2_B = B.countr_zero();
78071d5a254SDimitry Andric if (Pow2_A > Pow2_B) {
78171d5a254SDimitry Andric A.lshrInPlace(Pow2_A - Pow2_B);
78271d5a254SDimitry Andric Pow2 = Pow2_B;
78371d5a254SDimitry Andric } else if (Pow2_B > Pow2_A) {
78471d5a254SDimitry Andric B.lshrInPlace(Pow2_B - Pow2_A);
78571d5a254SDimitry Andric Pow2 = Pow2_A;
78671d5a254SDimitry Andric } else {
78771d5a254SDimitry Andric Pow2 = Pow2_A;
788009b1c42SEd Schouten }
78971d5a254SDimitry Andric }
79071d5a254SDimitry Andric
79171d5a254SDimitry Andric // Both operands are odd multiples of 2^Pow_2:
79271d5a254SDimitry Andric //
79371d5a254SDimitry Andric // gcd(a, b) = gcd(|a - b| / 2^i, min(a, b))
79471d5a254SDimitry Andric //
79571d5a254SDimitry Andric // This is a modified version of Stein's algorithm, taking advantage of
79671d5a254SDimitry Andric // efficient countTrailingZeros().
79771d5a254SDimitry Andric while (A != B) {
79871d5a254SDimitry Andric if (A.ugt(B)) {
79971d5a254SDimitry Andric A -= B;
8007fa27ce4SDimitry Andric A.lshrInPlace(A.countr_zero() - Pow2);
80171d5a254SDimitry Andric } else {
80271d5a254SDimitry Andric B -= A;
8037fa27ce4SDimitry Andric B.lshrInPlace(B.countr_zero() - Pow2);
80471d5a254SDimitry Andric }
80571d5a254SDimitry Andric }
80671d5a254SDimitry Andric
807009b1c42SEd Schouten return A;
808009b1c42SEd Schouten }
809009b1c42SEd Schouten
RoundDoubleToAPInt(double Double,unsigned width)810009b1c42SEd Schouten APInt llvm::APIntOps::RoundDoubleToAPInt(double Double, unsigned width) {
811d8e91e46SDimitry Andric uint64_t I = bit_cast<uint64_t>(Double);
812009b1c42SEd Schouten
813009b1c42SEd Schouten // Get the sign bit from the highest order bit
814d8e91e46SDimitry Andric bool isNeg = I >> 63;
815009b1c42SEd Schouten
816009b1c42SEd Schouten // Get the 11-bit exponent and adjust for the 1023 bit bias
817d8e91e46SDimitry Andric int64_t exp = ((I >> 52) & 0x7ff) - 1023;
818009b1c42SEd Schouten
819009b1c42SEd Schouten // If the exponent is negative, the value is < 0 so just return 0.
820009b1c42SEd Schouten if (exp < 0)
821009b1c42SEd Schouten return APInt(width, 0u);
822009b1c42SEd Schouten
823009b1c42SEd Schouten // Extract the mantissa by clearing the top 12 bits (sign + exponent).
824d8e91e46SDimitry Andric uint64_t mantissa = (I & (~0ULL >> 12)) | 1ULL << 52;
825009b1c42SEd Schouten
826009b1c42SEd Schouten // If the exponent doesn't shift all bits out of the mantissa
827009b1c42SEd Schouten if (exp < 52)
828009b1c42SEd Schouten return isNeg ? -APInt(width, mantissa >> (52 - exp)) :
829009b1c42SEd Schouten APInt(width, mantissa >> (52 - exp));
830009b1c42SEd Schouten
831009b1c42SEd Schouten // If the client didn't provide enough bits for us to shift the mantissa into
832009b1c42SEd Schouten // then the result is undefined, just return 0
833009b1c42SEd Schouten if (width <= exp - 52)
834009b1c42SEd Schouten return APInt(width, 0);
835009b1c42SEd Schouten
836009b1c42SEd Schouten // Otherwise, we have to shift the mantissa bits up to the right location
837009b1c42SEd Schouten APInt Tmp(width, mantissa);
838a303c417SDimitry Andric Tmp <<= (unsigned)exp - 52;
839009b1c42SEd Schouten return isNeg ? -Tmp : Tmp;
840009b1c42SEd Schouten }
841009b1c42SEd Schouten
8425a5ac124SDimitry Andric /// This function converts this APInt to a double.
843009b1c42SEd Schouten /// The layout for double is as following (IEEE Standard 754):
844009b1c42SEd Schouten /// --------------------------------------
845009b1c42SEd Schouten /// | Sign Exponent Fraction Bias |
846009b1c42SEd Schouten /// |-------------------------------------- |
847009b1c42SEd Schouten /// | 1[63] 11[62-52] 52[51-00] 1023 |
848009b1c42SEd Schouten /// --------------------------------------
roundToDouble(bool isSigned) const849009b1c42SEd Schouten double APInt::roundToDouble(bool isSigned) const {
850009b1c42SEd Schouten
851009b1c42SEd Schouten // Handle the simple case where the value is contained in one uint64_t.
85259850d08SRoman Divacky // It is wrong to optimize getWord(0) to VAL; there might be more than one word.
853009b1c42SEd Schouten if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
854009b1c42SEd Schouten if (isSigned) {
85501095a5dSDimitry Andric int64_t sext = SignExtend64(getWord(0), BitWidth);
856009b1c42SEd Schouten return double(sext);
857009b1c42SEd Schouten } else
85859850d08SRoman Divacky return double(getWord(0));
859009b1c42SEd Schouten }
860009b1c42SEd Schouten
861009b1c42SEd Schouten // Determine if the value is negative.
862009b1c42SEd Schouten bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
863009b1c42SEd Schouten
864009b1c42SEd Schouten // Construct the absolute value if we're negative.
865009b1c42SEd Schouten APInt Tmp(isNeg ? -(*this) : (*this));
866009b1c42SEd Schouten
867009b1c42SEd Schouten // Figure out how many bits we're using.
868009b1c42SEd Schouten unsigned n = Tmp.getActiveBits();
869009b1c42SEd Schouten
870009b1c42SEd Schouten // The exponent (without bias normalization) is just the number of bits
871009b1c42SEd Schouten // we are using. Note that the sign bit is gone since we constructed the
872009b1c42SEd Schouten // absolute value.
873009b1c42SEd Schouten uint64_t exp = n;
874009b1c42SEd Schouten
875009b1c42SEd Schouten // Return infinity for exponent overflow
876009b1c42SEd Schouten if (exp > 1023) {
877009b1c42SEd Schouten if (!isSigned || !isNeg)
878009b1c42SEd Schouten return std::numeric_limits<double>::infinity();
879009b1c42SEd Schouten else
880009b1c42SEd Schouten return -std::numeric_limits<double>::infinity();
881009b1c42SEd Schouten }
882009b1c42SEd Schouten exp += 1023; // Increment for 1023 bias
883009b1c42SEd Schouten
884009b1c42SEd Schouten // Number of bits in mantissa is 52. To obtain the mantissa value, we must
885009b1c42SEd Schouten // extract the high 52 bits from the correct words in pVal.
886009b1c42SEd Schouten uint64_t mantissa;
887009b1c42SEd Schouten unsigned hiWord = whichWord(n-1);
888009b1c42SEd Schouten if (hiWord == 0) {
889148779dfSDimitry Andric mantissa = Tmp.U.pVal[0];
890009b1c42SEd Schouten if (n > 52)
891009b1c42SEd Schouten mantissa >>= n - 52; // shift down, we want the top 52 bits.
892009b1c42SEd Schouten } else {
893009b1c42SEd Schouten assert(hiWord > 0 && "huh?");
894148779dfSDimitry Andric uint64_t hibits = Tmp.U.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
895148779dfSDimitry Andric uint64_t lobits = Tmp.U.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
896009b1c42SEd Schouten mantissa = hibits | lobits;
897009b1c42SEd Schouten }
898009b1c42SEd Schouten
899009b1c42SEd Schouten // The leading bit of mantissa is implicit, so get rid of it.
900009b1c42SEd Schouten uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
901d8e91e46SDimitry Andric uint64_t I = sign | (exp << 52) | mantissa;
902d8e91e46SDimitry Andric return bit_cast<double>(I);
903009b1c42SEd Schouten }
904009b1c42SEd Schouten
905009b1c42SEd Schouten // Truncate to new width.
trunc(unsigned width) const906cf099d11SDimitry Andric APInt APInt::trunc(unsigned width) const {
907145449b1SDimitry Andric assert(width <= BitWidth && "Invalid APInt Truncate request");
908cf099d11SDimitry Andric
909cf099d11SDimitry Andric if (width <= APINT_BITS_PER_WORD)
910cf099d11SDimitry Andric return APInt(width, getRawData()[0]);
911cf099d11SDimitry Andric
912145449b1SDimitry Andric if (width == BitWidth)
913145449b1SDimitry Andric return *this;
914145449b1SDimitry Andric
915cf099d11SDimitry Andric APInt Result(getMemory(getNumWords(width)), width);
916cf099d11SDimitry Andric
917cf099d11SDimitry Andric // Copy full words.
918cf099d11SDimitry Andric unsigned i;
919cf099d11SDimitry Andric for (i = 0; i != width / APINT_BITS_PER_WORD; i++)
920148779dfSDimitry Andric Result.U.pVal[i] = U.pVal[i];
921cf099d11SDimitry Andric
922cf099d11SDimitry Andric // Truncate and copy any partial word.
923cf099d11SDimitry Andric unsigned bits = (0 - width) % APINT_BITS_PER_WORD;
924cf099d11SDimitry Andric if (bits != 0)
925148779dfSDimitry Andric Result.U.pVal[i] = U.pVal[i] << bits >> bits;
926cf099d11SDimitry Andric
927cf099d11SDimitry Andric return Result;
928009b1c42SEd Schouten }
929009b1c42SEd Schouten
930706b4fc4SDimitry Andric // Truncate to new width with unsigned saturation.
truncUSat(unsigned width) const931706b4fc4SDimitry Andric APInt APInt::truncUSat(unsigned width) const {
932145449b1SDimitry Andric assert(width <= BitWidth && "Invalid APInt Truncate request");
933706b4fc4SDimitry Andric
934706b4fc4SDimitry Andric // Can we just losslessly truncate it?
935706b4fc4SDimitry Andric if (isIntN(width))
936706b4fc4SDimitry Andric return trunc(width);
937706b4fc4SDimitry Andric // If not, then just return the new limit.
938706b4fc4SDimitry Andric return APInt::getMaxValue(width);
939706b4fc4SDimitry Andric }
940706b4fc4SDimitry Andric
941706b4fc4SDimitry Andric // Truncate to new width with signed saturation.
truncSSat(unsigned width) const942706b4fc4SDimitry Andric APInt APInt::truncSSat(unsigned width) const {
943145449b1SDimitry Andric assert(width <= BitWidth && "Invalid APInt Truncate request");
944706b4fc4SDimitry Andric
945706b4fc4SDimitry Andric // Can we just losslessly truncate it?
946706b4fc4SDimitry Andric if (isSignedIntN(width))
947706b4fc4SDimitry Andric return trunc(width);
948706b4fc4SDimitry Andric // If not, then just return the new limits.
949706b4fc4SDimitry Andric return isNegative() ? APInt::getSignedMinValue(width)
950706b4fc4SDimitry Andric : APInt::getSignedMaxValue(width);
951706b4fc4SDimitry Andric }
952706b4fc4SDimitry Andric
953009b1c42SEd Schouten // Sign extend to a new width.
sext(unsigned Width) const95412f3ca4cSDimitry Andric APInt APInt::sext(unsigned Width) const {
955145449b1SDimitry Andric assert(Width >= BitWidth && "Invalid APInt SignExtend request");
956cf099d11SDimitry Andric
95712f3ca4cSDimitry Andric if (Width <= APINT_BITS_PER_WORD)
958148779dfSDimitry Andric return APInt(Width, SignExtend64(U.VAL, BitWidth));
959009b1c42SEd Schouten
960145449b1SDimitry Andric if (Width == BitWidth)
961145449b1SDimitry Andric return *this;
962145449b1SDimitry Andric
96312f3ca4cSDimitry Andric APInt Result(getMemory(getNumWords(Width)), Width);
964009b1c42SEd Schouten
96512f3ca4cSDimitry Andric // Copy words.
966148779dfSDimitry Andric std::memcpy(Result.U.pVal, getRawData(), getNumWords() * APINT_WORD_SIZE);
967cf099d11SDimitry Andric
96812f3ca4cSDimitry Andric // Sign extend the last word since there may be unused bits in the input.
969148779dfSDimitry Andric Result.U.pVal[getNumWords() - 1] =
970148779dfSDimitry Andric SignExtend64(Result.U.pVal[getNumWords() - 1],
97112f3ca4cSDimitry Andric ((BitWidth - 1) % APINT_BITS_PER_WORD) + 1);
972cf099d11SDimitry Andric
97312f3ca4cSDimitry Andric // Fill with sign bits.
974148779dfSDimitry Andric std::memset(Result.U.pVal + getNumWords(), isNegative() ? -1 : 0,
97512f3ca4cSDimitry Andric (Result.getNumWords() - getNumWords()) * APINT_WORD_SIZE);
97612f3ca4cSDimitry Andric Result.clearUnusedBits();
977cf099d11SDimitry Andric return Result;
978009b1c42SEd Schouten }
979009b1c42SEd Schouten
980009b1c42SEd Schouten // Zero extend to a new width.
zext(unsigned width) const981cf099d11SDimitry Andric APInt APInt::zext(unsigned width) const {
982145449b1SDimitry Andric assert(width >= BitWidth && "Invalid APInt ZeroExtend request");
983cf099d11SDimitry Andric
984cf099d11SDimitry Andric if (width <= APINT_BITS_PER_WORD)
985148779dfSDimitry Andric return APInt(width, U.VAL);
986cf099d11SDimitry Andric
987145449b1SDimitry Andric if (width == BitWidth)
988145449b1SDimitry Andric return *this;
989145449b1SDimitry Andric
990cf099d11SDimitry Andric APInt Result(getMemory(getNumWords(width)), width);
991cf099d11SDimitry Andric
992cf099d11SDimitry Andric // Copy words.
993148779dfSDimitry Andric std::memcpy(Result.U.pVal, getRawData(), getNumWords() * APINT_WORD_SIZE);
994cf099d11SDimitry Andric
995cf099d11SDimitry Andric // Zero remaining words.
996148779dfSDimitry Andric std::memset(Result.U.pVal + getNumWords(), 0,
99712f3ca4cSDimitry Andric (Result.getNumWords() - getNumWords()) * APINT_WORD_SIZE);
998cf099d11SDimitry Andric
999cf099d11SDimitry Andric return Result;
1000009b1c42SEd Schouten }
1001009b1c42SEd Schouten
zextOrTrunc(unsigned width) const1002cf099d11SDimitry Andric APInt APInt::zextOrTrunc(unsigned width) const {
1003009b1c42SEd Schouten if (BitWidth < width)
1004009b1c42SEd Schouten return zext(width);
1005009b1c42SEd Schouten if (BitWidth > width)
1006009b1c42SEd Schouten return trunc(width);
1007009b1c42SEd Schouten return *this;
1008009b1c42SEd Schouten }
1009009b1c42SEd Schouten
sextOrTrunc(unsigned width) const1010cf099d11SDimitry Andric APInt APInt::sextOrTrunc(unsigned width) const {
1011009b1c42SEd Schouten if (BitWidth < width)
1012009b1c42SEd Schouten return sext(width);
1013009b1c42SEd Schouten if (BitWidth > width)
1014009b1c42SEd Schouten return trunc(width);
1015009b1c42SEd Schouten return *this;
1016009b1c42SEd Schouten }
1017009b1c42SEd Schouten
1018009b1c42SEd Schouten /// Arithmetic right-shift this APInt by shiftAmt.
1019eb11fae6SDimitry Andric /// Arithmetic right-shift function.
ashrInPlace(const APInt & shiftAmt)102012f3ca4cSDimitry Andric void APInt::ashrInPlace(const APInt &shiftAmt) {
102112f3ca4cSDimitry Andric ashrInPlace((unsigned)shiftAmt.getLimitedValue(BitWidth));
1022009b1c42SEd Schouten }
1023009b1c42SEd Schouten
1024009b1c42SEd Schouten /// Arithmetic right-shift this APInt by shiftAmt.
1025eb11fae6SDimitry Andric /// Arithmetic right-shift function.
ashrSlowCase(unsigned ShiftAmt)102612f3ca4cSDimitry Andric void APInt::ashrSlowCase(unsigned ShiftAmt) {
102712f3ca4cSDimitry Andric // Don't bother performing a no-op shift.
102812f3ca4cSDimitry Andric if (!ShiftAmt)
102912f3ca4cSDimitry Andric return;
1030009b1c42SEd Schouten
103112f3ca4cSDimitry Andric // Save the original sign bit for later.
103212f3ca4cSDimitry Andric bool Negative = isNegative();
1033009b1c42SEd Schouten
1034eb11fae6SDimitry Andric // WordShift is the inter-part shift; BitShift is intra-part shift.
103512f3ca4cSDimitry Andric unsigned WordShift = ShiftAmt / APINT_BITS_PER_WORD;
103612f3ca4cSDimitry Andric unsigned BitShift = ShiftAmt % APINT_BITS_PER_WORD;
1037009b1c42SEd Schouten
103812f3ca4cSDimitry Andric unsigned WordsToMove = getNumWords() - WordShift;
103912f3ca4cSDimitry Andric if (WordsToMove != 0) {
104012f3ca4cSDimitry Andric // Sign extend the last word to fill in the unused bits.
1041148779dfSDimitry Andric U.pVal[getNumWords() - 1] = SignExtend64(
1042148779dfSDimitry Andric U.pVal[getNumWords() - 1], ((BitWidth - 1) % APINT_BITS_PER_WORD) + 1);
1043009b1c42SEd Schouten
104412f3ca4cSDimitry Andric // Fastpath for moving by whole words.
104512f3ca4cSDimitry Andric if (BitShift == 0) {
1046148779dfSDimitry Andric std::memmove(U.pVal, U.pVal + WordShift, WordsToMove * APINT_WORD_SIZE);
1047009b1c42SEd Schouten } else {
104812f3ca4cSDimitry Andric // Move the words containing significant bits.
104912f3ca4cSDimitry Andric for (unsigned i = 0; i != WordsToMove - 1; ++i)
1050148779dfSDimitry Andric U.pVal[i] = (U.pVal[i + WordShift] >> BitShift) |
1051148779dfSDimitry Andric (U.pVal[i + WordShift + 1] << (APINT_BITS_PER_WORD - BitShift));
1052009b1c42SEd Schouten
105312f3ca4cSDimitry Andric // Handle the last word which has no high bits to copy.
1054148779dfSDimitry Andric U.pVal[WordsToMove - 1] = U.pVal[WordShift + WordsToMove - 1] >> BitShift;
105512f3ca4cSDimitry Andric // Sign extend one more time.
1056148779dfSDimitry Andric U.pVal[WordsToMove - 1] =
1057148779dfSDimitry Andric SignExtend64(U.pVal[WordsToMove - 1], APINT_BITS_PER_WORD - BitShift);
1058009b1c42SEd Schouten }
1059009b1c42SEd Schouten }
1060009b1c42SEd Schouten
106112f3ca4cSDimitry Andric // Fill in the remainder based on the original sign.
1062148779dfSDimitry Andric std::memset(U.pVal + WordsToMove, Negative ? -1 : 0,
106312f3ca4cSDimitry Andric WordShift * APINT_WORD_SIZE);
106412f3ca4cSDimitry Andric clearUnusedBits();
1065009b1c42SEd Schouten }
1066009b1c42SEd Schouten
1067009b1c42SEd Schouten /// Logical right-shift this APInt by shiftAmt.
1068eb11fae6SDimitry Andric /// Logical right-shift function.
lshrInPlace(const APInt & shiftAmt)1069d99dafe2SDimitry Andric void APInt::lshrInPlace(const APInt &shiftAmt) {
1070d99dafe2SDimitry Andric lshrInPlace((unsigned)shiftAmt.getLimitedValue(BitWidth));
107171d5a254SDimitry Andric }
107271d5a254SDimitry Andric
1073009b1c42SEd Schouten /// Logical right-shift this APInt by shiftAmt.
1074eb11fae6SDimitry Andric /// Logical right-shift function.
lshrSlowCase(unsigned ShiftAmt)1075d99dafe2SDimitry Andric void APInt::lshrSlowCase(unsigned ShiftAmt) {
1076148779dfSDimitry Andric tcShiftRight(U.pVal, getNumWords(), ShiftAmt);
1077009b1c42SEd Schouten }
1078009b1c42SEd Schouten
1079009b1c42SEd Schouten /// Left-shift this APInt by shiftAmt.
1080eb11fae6SDimitry Andric /// Left-shift function.
operator <<=(const APInt & shiftAmt)1081a303c417SDimitry Andric APInt &APInt::operator<<=(const APInt &shiftAmt) {
1082009b1c42SEd Schouten // It's undefined behavior in C to shift by BitWidth or greater.
1083a303c417SDimitry Andric *this <<= (unsigned)shiftAmt.getLimitedValue(BitWidth);
1084a303c417SDimitry Andric return *this;
1085009b1c42SEd Schouten }
1086009b1c42SEd Schouten
shlSlowCase(unsigned ShiftAmt)1087d99dafe2SDimitry Andric void APInt::shlSlowCase(unsigned ShiftAmt) {
1088148779dfSDimitry Andric tcShiftLeft(U.pVal, getNumWords(), ShiftAmt);
1089d99dafe2SDimitry Andric clearUnusedBits();
1090009b1c42SEd Schouten }
1091009b1c42SEd Schouten
109271d5a254SDimitry Andric // Calculate the rotate amount modulo the bit width.
rotateModulo(unsigned BitWidth,const APInt & rotateAmt)109371d5a254SDimitry Andric static unsigned rotateModulo(unsigned BitWidth, const APInt &rotateAmt) {
1094c0981da4SDimitry Andric if (LLVM_UNLIKELY(BitWidth == 0))
1095c0981da4SDimitry Andric return 0;
109671d5a254SDimitry Andric unsigned rotBitWidth = rotateAmt.getBitWidth();
109771d5a254SDimitry Andric APInt rot = rotateAmt;
109871d5a254SDimitry Andric if (rotBitWidth < BitWidth) {
109971d5a254SDimitry Andric // Extend the rotate APInt, so that the urem doesn't divide by 0.
110071d5a254SDimitry Andric // e.g. APInt(1, 32) would give APInt(1, 0).
110171d5a254SDimitry Andric rot = rotateAmt.zext(BitWidth);
110271d5a254SDimitry Andric }
110371d5a254SDimitry Andric rot = rot.urem(APInt(rot.getBitWidth(), BitWidth));
110471d5a254SDimitry Andric return rot.getLimitedValue(BitWidth);
110571d5a254SDimitry Andric }
110671d5a254SDimitry Andric
rotl(const APInt & rotateAmt) const1107009b1c42SEd Schouten APInt APInt::rotl(const APInt &rotateAmt) const {
110871d5a254SDimitry Andric return rotl(rotateModulo(BitWidth, rotateAmt));
1109009b1c42SEd Schouten }
1110009b1c42SEd Schouten
rotl(unsigned rotateAmt) const1111009b1c42SEd Schouten APInt APInt::rotl(unsigned rotateAmt) const {
1112c0981da4SDimitry Andric if (LLVM_UNLIKELY(BitWidth == 0))
1113c0981da4SDimitry Andric return *this;
111463faed5bSDimitry Andric rotateAmt %= BitWidth;
1115009b1c42SEd Schouten if (rotateAmt == 0)
1116009b1c42SEd Schouten return *this;
111763faed5bSDimitry Andric return shl(rotateAmt) | lshr(BitWidth - rotateAmt);
1118009b1c42SEd Schouten }
1119009b1c42SEd Schouten
rotr(const APInt & rotateAmt) const1120009b1c42SEd Schouten APInt APInt::rotr(const APInt &rotateAmt) const {
112171d5a254SDimitry Andric return rotr(rotateModulo(BitWidth, rotateAmt));
1122009b1c42SEd Schouten }
1123009b1c42SEd Schouten
rotr(unsigned rotateAmt) const1124009b1c42SEd Schouten APInt APInt::rotr(unsigned rotateAmt) const {
1125c0981da4SDimitry Andric if (BitWidth == 0)
1126c0981da4SDimitry Andric return *this;
112763faed5bSDimitry Andric rotateAmt %= BitWidth;
1128009b1c42SEd Schouten if (rotateAmt == 0)
1129009b1c42SEd Schouten return *this;
113063faed5bSDimitry Andric return lshr(rotateAmt) | shl(BitWidth - rotateAmt);
1131009b1c42SEd Schouten }
1132009b1c42SEd Schouten
1133c0981da4SDimitry Andric /// \returns the nearest log base 2 of this APInt. Ties round up.
1134c0981da4SDimitry Andric ///
1135c0981da4SDimitry Andric /// NOTE: When we have a BitWidth of 1, we define:
1136c0981da4SDimitry Andric ///
1137c0981da4SDimitry Andric /// log2(0) = UINT32_MAX
1138c0981da4SDimitry Andric /// log2(1) = 0
1139c0981da4SDimitry Andric ///
1140c0981da4SDimitry Andric /// to get around any mathematical concerns resulting from
1141c0981da4SDimitry Andric /// referencing 2 in a space where 2 does no exist.
nearestLogBase2() const1142c0981da4SDimitry Andric unsigned APInt::nearestLogBase2() const {
1143c0981da4SDimitry Andric // Special case when we have a bitwidth of 1. If VAL is 1, then we
1144c0981da4SDimitry Andric // get 0. If VAL is 0, we get WORDTYPE_MAX which gets truncated to
1145c0981da4SDimitry Andric // UINT32_MAX.
1146c0981da4SDimitry Andric if (BitWidth == 1)
1147c0981da4SDimitry Andric return U.VAL - 1;
1148c0981da4SDimitry Andric
1149c0981da4SDimitry Andric // Handle the zero case.
1150c0981da4SDimitry Andric if (isZero())
1151c0981da4SDimitry Andric return UINT32_MAX;
1152c0981da4SDimitry Andric
1153c0981da4SDimitry Andric // The non-zero case is handled by computing:
1154c0981da4SDimitry Andric //
1155c0981da4SDimitry Andric // nearestLogBase2(x) = logBase2(x) + x[logBase2(x)-1].
1156c0981da4SDimitry Andric //
1157c0981da4SDimitry Andric // where x[i] is referring to the value of the ith bit of x.
1158c0981da4SDimitry Andric unsigned lg = logBase2();
1159c0981da4SDimitry Andric return lg + unsigned((*this)[lg - 1]);
1160c0981da4SDimitry Andric }
1161c0981da4SDimitry Andric
1162009b1c42SEd Schouten // Square Root - this method computes and returns the square root of "this".
1163009b1c42SEd Schouten // Three mechanisms are used for computation. For small values (<= 5 bits),
1164009b1c42SEd Schouten // a table lookup is done. This gets some performance for common cases. For
1165009b1c42SEd Schouten // values using less than 52 bits, the value is converted to double and then
1166009b1c42SEd Schouten // the libc sqrt function is called. The result is rounded and then converted
1167009b1c42SEd Schouten // back to a uint64_t which is then used to construct the result. Finally,
1168009b1c42SEd Schouten // the Babylonian method for computing square roots is used.
sqrt() const1169009b1c42SEd Schouten APInt APInt::sqrt() const {
1170009b1c42SEd Schouten
1171009b1c42SEd Schouten // Determine the magnitude of the value.
1172009b1c42SEd Schouten unsigned magnitude = getActiveBits();
1173009b1c42SEd Schouten
1174009b1c42SEd Schouten // Use a fast table for some small values. This also gets rid of some
1175009b1c42SEd Schouten // rounding errors in libc sqrt for small values.
1176009b1c42SEd Schouten if (magnitude <= 5) {
1177009b1c42SEd Schouten static const uint8_t results[32] = {
1178009b1c42SEd Schouten /* 0 */ 0,
1179009b1c42SEd Schouten /* 1- 2 */ 1, 1,
1180009b1c42SEd Schouten /* 3- 6 */ 2, 2, 2, 2,
1181009b1c42SEd Schouten /* 7-12 */ 3, 3, 3, 3, 3, 3,
1182009b1c42SEd Schouten /* 13-20 */ 4, 4, 4, 4, 4, 4, 4, 4,
1183009b1c42SEd Schouten /* 21-30 */ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
1184009b1c42SEd Schouten /* 31 */ 6
1185009b1c42SEd Schouten };
1186148779dfSDimitry Andric return APInt(BitWidth, results[ (isSingleWord() ? U.VAL : U.pVal[0]) ]);
1187009b1c42SEd Schouten }
1188009b1c42SEd Schouten
1189009b1c42SEd Schouten // If the magnitude of the value fits in less than 52 bits (the precision of
1190009b1c42SEd Schouten // an IEEE double precision floating point value), then we can use the
1191009b1c42SEd Schouten // libc sqrt function which will probably use a hardware sqrt computation.
1192009b1c42SEd Schouten // This should be faster than the algorithm below.
1193009b1c42SEd Schouten if (magnitude < 52) {
1194009b1c42SEd Schouten return APInt(BitWidth,
1195148779dfSDimitry Andric uint64_t(::round(::sqrt(double(isSingleWord() ? U.VAL
1196148779dfSDimitry Andric : U.pVal[0])))));
1197009b1c42SEd Schouten }
1198009b1c42SEd Schouten
1199009b1c42SEd Schouten // Okay, all the short cuts are exhausted. We must compute it. The following
1200009b1c42SEd Schouten // is a classical Babylonian method for computing the square root. This code
120167c32a98SDimitry Andric // was adapted to APInt from a wikipedia article on such computations.
1202009b1c42SEd Schouten // See http://www.wikipedia.org/ and go to the page named
1203009b1c42SEd Schouten // Calculate_an_integer_square_root.
1204009b1c42SEd Schouten unsigned nbits = BitWidth, i = 4;
1205009b1c42SEd Schouten APInt testy(BitWidth, 16);
1206009b1c42SEd Schouten APInt x_old(BitWidth, 1);
1207009b1c42SEd Schouten APInt x_new(BitWidth, 0);
1208009b1c42SEd Schouten APInt two(BitWidth, 2);
1209009b1c42SEd Schouten
1210009b1c42SEd Schouten // Select a good starting value using binary logarithms.
1211009b1c42SEd Schouten for (;; i += 2, testy = testy.shl(2))
1212009b1c42SEd Schouten if (i >= nbits || this->ule(testy)) {
1213009b1c42SEd Schouten x_old = x_old.shl(i / 2);
1214009b1c42SEd Schouten break;
1215009b1c42SEd Schouten }
1216009b1c42SEd Schouten
1217009b1c42SEd Schouten // Use the Babylonian method to arrive at the integer square root:
1218009b1c42SEd Schouten for (;;) {
1219009b1c42SEd Schouten x_new = (this->udiv(x_old) + x_old).udiv(two);
1220009b1c42SEd Schouten if (x_old.ule(x_new))
1221009b1c42SEd Schouten break;
1222009b1c42SEd Schouten x_old = x_new;
1223009b1c42SEd Schouten }
1224009b1c42SEd Schouten
1225009b1c42SEd Schouten // Make sure we return the closest approximation
1226009b1c42SEd Schouten // NOTE: The rounding calculation below is correct. It will produce an
1227009b1c42SEd Schouten // off-by-one discrepancy with results from pari/gp. That discrepancy has been
1228009b1c42SEd Schouten // determined to be a rounding issue with pari/gp as it begins to use a
1229009b1c42SEd Schouten // floating point representation after 192 bits. There are no discrepancies
1230009b1c42SEd Schouten // between this algorithm and pari/gp for bit widths < 192 bits.
1231009b1c42SEd Schouten APInt square(x_old * x_old);
1232009b1c42SEd Schouten APInt nextSquare((x_old + 1) * (x_old +1));
1233009b1c42SEd Schouten if (this->ult(square))
1234009b1c42SEd Schouten return x_old;
123563faed5bSDimitry Andric assert(this->ule(nextSquare) && "Error in APInt::sqrt computation");
1236009b1c42SEd Schouten APInt midpoint((nextSquare - square).udiv(two));
1237009b1c42SEd Schouten APInt offset(*this - square);
1238009b1c42SEd Schouten if (offset.ult(midpoint))
1239009b1c42SEd Schouten return x_old;
1240009b1c42SEd Schouten return x_old + 1;
1241009b1c42SEd Schouten }
1242009b1c42SEd Schouten
1243ac9a064cSDimitry Andric /// \returns the multiplicative inverse of an odd APInt modulo 2^BitWidth.
multiplicativeInverse() const1244ac9a064cSDimitry Andric APInt APInt::multiplicativeInverse() const {
1245ac9a064cSDimitry Andric assert((*this)[0] &&
1246ac9a064cSDimitry Andric "multiplicative inverse is only defined for odd numbers!");
1247009b1c42SEd Schouten
1248ac9a064cSDimitry Andric // Use Newton's method.
1249ac9a064cSDimitry Andric APInt Factor = *this;
1250ac9a064cSDimitry Andric APInt T;
1251ac9a064cSDimitry Andric while (!(T = *this * Factor).isOne())
1252ac9a064cSDimitry Andric Factor *= 2 - std::move(T);
1253ac9a064cSDimitry Andric return Factor;
1254009b1c42SEd Schouten }
1255009b1c42SEd Schouten
1256009b1c42SEd Schouten /// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
1257009b1c42SEd Schouten /// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
1258009b1c42SEd Schouten /// variables here have the same names as in the algorithm. Comments explain
1259009b1c42SEd Schouten /// the algorithm and any deviation from it.
KnuthDiv(uint32_t * u,uint32_t * v,uint32_t * q,uint32_t * r,unsigned m,unsigned n)12606b3f41edSDimitry Andric static void KnuthDiv(uint32_t *u, uint32_t *v, uint32_t *q, uint32_t* r,
1261009b1c42SEd Schouten unsigned m, unsigned n) {
1262009b1c42SEd Schouten assert(u && "Must provide dividend");
1263009b1c42SEd Schouten assert(v && "Must provide divisor");
1264009b1c42SEd Schouten assert(q && "Must provide quotient");
12655a5ac124SDimitry Andric assert(u != v && u != q && v != q && "Must use different memory");
1266009b1c42SEd Schouten assert(n>1 && "n must be > 1");
1267009b1c42SEd Schouten
12685a5ac124SDimitry Andric // b denotes the base of the number system. In our case b is 2^32.
1269b915e9e0SDimitry Andric const uint64_t b = uint64_t(1) << 32;
1270009b1c42SEd Schouten
1271044eb2f6SDimitry Andric // The DEBUG macros here tend to be spam in the debug output if you're not
1272044eb2f6SDimitry Andric // debugging this code. Disable them unless KNUTH_DEBUG is defined.
1273d8e91e46SDimitry Andric #ifdef KNUTH_DEBUG
1274d8e91e46SDimitry Andric #define DEBUG_KNUTH(X) LLVM_DEBUG(X)
1275d8e91e46SDimitry Andric #else
1276d8e91e46SDimitry Andric #define DEBUG_KNUTH(X) do {} while(false)
1277044eb2f6SDimitry Andric #endif
1278044eb2f6SDimitry Andric
1279d8e91e46SDimitry Andric DEBUG_KNUTH(dbgs() << "KnuthDiv: m=" << m << " n=" << n << '\n');
1280d8e91e46SDimitry Andric DEBUG_KNUTH(dbgs() << "KnuthDiv: original:");
1281d8e91e46SDimitry Andric DEBUG_KNUTH(for (int i = m + n; i >= 0; i--) dbgs() << " " << u[i]);
1282d8e91e46SDimitry Andric DEBUG_KNUTH(dbgs() << " by");
1283d8e91e46SDimitry Andric DEBUG_KNUTH(for (int i = n; i > 0; i--) dbgs() << " " << v[i - 1]);
1284d8e91e46SDimitry Andric DEBUG_KNUTH(dbgs() << '\n');
1285009b1c42SEd Schouten // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
1286009b1c42SEd Schouten // u and v by d. Note that we have taken Knuth's advice here to use a power
1287009b1c42SEd Schouten // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
1288009b1c42SEd Schouten // 2 allows us to shift instead of multiply and it is easy to determine the
1289009b1c42SEd Schouten // shift amount from the leading zeros. We are basically normalizing the u
1290009b1c42SEd Schouten // and v so that its high bits are shifted to the top of v's range without
1291009b1c42SEd Schouten // overflow. Note that this can require an extra word in u so that u must
1292009b1c42SEd Schouten // be of length m+n+1.
12937fa27ce4SDimitry Andric unsigned shift = llvm::countl_zero(v[n - 1]);
12946b3f41edSDimitry Andric uint32_t v_carry = 0;
12956b3f41edSDimitry Andric uint32_t u_carry = 0;
1296009b1c42SEd Schouten if (shift) {
1297009b1c42SEd Schouten for (unsigned i = 0; i < m+n; ++i) {
12986b3f41edSDimitry Andric uint32_t u_tmp = u[i] >> (32 - shift);
1299009b1c42SEd Schouten u[i] = (u[i] << shift) | u_carry;
1300009b1c42SEd Schouten u_carry = u_tmp;
1301009b1c42SEd Schouten }
1302009b1c42SEd Schouten for (unsigned i = 0; i < n; ++i) {
13036b3f41edSDimitry Andric uint32_t v_tmp = v[i] >> (32 - shift);
1304009b1c42SEd Schouten v[i] = (v[i] << shift) | v_carry;
1305009b1c42SEd Schouten v_carry = v_tmp;
1306009b1c42SEd Schouten }
1307009b1c42SEd Schouten }
1308009b1c42SEd Schouten u[m+n] = u_carry;
13095a5ac124SDimitry Andric
1310d8e91e46SDimitry Andric DEBUG_KNUTH(dbgs() << "KnuthDiv: normal:");
1311d8e91e46SDimitry Andric DEBUG_KNUTH(for (int i = m + n; i >= 0; i--) dbgs() << " " << u[i]);
1312d8e91e46SDimitry Andric DEBUG_KNUTH(dbgs() << " by");
1313d8e91e46SDimitry Andric DEBUG_KNUTH(for (int i = n; i > 0; i--) dbgs() << " " << v[i - 1]);
1314d8e91e46SDimitry Andric DEBUG_KNUTH(dbgs() << '\n');
1315009b1c42SEd Schouten
1316009b1c42SEd Schouten // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
1317009b1c42SEd Schouten int j = m;
1318009b1c42SEd Schouten do {
1319d8e91e46SDimitry Andric DEBUG_KNUTH(dbgs() << "KnuthDiv: quotient digit #" << j << '\n');
1320009b1c42SEd Schouten // D3. [Calculate q'.].
1321009b1c42SEd Schouten // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
1322009b1c42SEd Schouten // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
1323009b1c42SEd Schouten // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
13246b3f41edSDimitry Andric // qp by 1, increase rp by v[n-1], and repeat this test if rp < b. The test
1325009b1c42SEd Schouten // on v[n-2] determines at high speed most of the cases in which the trial
1326009b1c42SEd Schouten // value qp is one too large, and it eliminates all cases where qp is two
1327009b1c42SEd Schouten // too large.
13286b3f41edSDimitry Andric uint64_t dividend = Make_64(u[j+n], u[j+n-1]);
1329d8e91e46SDimitry Andric DEBUG_KNUTH(dbgs() << "KnuthDiv: dividend == " << dividend << '\n');
1330009b1c42SEd Schouten uint64_t qp = dividend / v[n-1];
1331009b1c42SEd Schouten uint64_t rp = dividend % v[n-1];
1332009b1c42SEd Schouten if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1333009b1c42SEd Schouten qp--;
1334009b1c42SEd Schouten rp += v[n-1];
1335009b1c42SEd Schouten if (rp < b && (qp == b || qp*v[n-2] > b*rp + u[j+n-2]))
1336009b1c42SEd Schouten qp--;
1337009b1c42SEd Schouten }
1338d8e91e46SDimitry Andric DEBUG_KNUTH(dbgs() << "KnuthDiv: qp == " << qp << ", rp == " << rp << '\n');
1339009b1c42SEd Schouten
1340009b1c42SEd Schouten // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with
1341009b1c42SEd Schouten // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation
1342009b1c42SEd Schouten // consists of a simple multiplication by a one-place number, combined with
1343009b1c42SEd Schouten // a subtraction.
1344009b1c42SEd Schouten // The digits (u[j+n]...u[j]) should be kept positive; if the result of
1345009b1c42SEd Schouten // this step is actually negative, (u[j+n]...u[j]) should be left as the
1346009b1c42SEd Schouten // true value plus b**(n+1), namely as the b's complement of
1347009b1c42SEd Schouten // the true value, and a "borrow" to the left should be remembered.
13485a5ac124SDimitry Andric int64_t borrow = 0;
13495a5ac124SDimitry Andric for (unsigned i = 0; i < n; ++i) {
13505a5ac124SDimitry Andric uint64_t p = uint64_t(qp) * uint64_t(v[i]);
13516b3f41edSDimitry Andric int64_t subres = int64_t(u[j+i]) - borrow - Lo_32(p);
13526b3f41edSDimitry Andric u[j+i] = Lo_32(subres);
13536b3f41edSDimitry Andric borrow = Hi_32(p) - Hi_32(subres);
1354d8e91e46SDimitry Andric DEBUG_KNUTH(dbgs() << "KnuthDiv: u[j+i] = " << u[j + i]
13555a5ac124SDimitry Andric << ", borrow = " << borrow << '\n');
1356009b1c42SEd Schouten }
13575a5ac124SDimitry Andric bool isNeg = u[j+n] < borrow;
13586b3f41edSDimitry Andric u[j+n] -= Lo_32(borrow);
13595a5ac124SDimitry Andric
1360d8e91e46SDimitry Andric DEBUG_KNUTH(dbgs() << "KnuthDiv: after subtraction:");
1361d8e91e46SDimitry Andric DEBUG_KNUTH(for (int i = m + n; i >= 0; i--) dbgs() << " " << u[i]);
1362d8e91e46SDimitry Andric DEBUG_KNUTH(dbgs() << '\n');
1363009b1c42SEd Schouten
1364009b1c42SEd Schouten // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
1365009b1c42SEd Schouten // negative, go to step D6; otherwise go on to step D7.
13666b3f41edSDimitry Andric q[j] = Lo_32(qp);
1367009b1c42SEd Schouten if (isNeg) {
1368009b1c42SEd Schouten // D6. [Add back]. The probability that this step is necessary is very
1369009b1c42SEd Schouten // small, on the order of only 2/b. Make sure that test data accounts for
1370009b1c42SEd Schouten // this possibility. Decrease q[j] by 1
1371009b1c42SEd Schouten q[j]--;
1372009b1c42SEd Schouten // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]).
1373009b1c42SEd Schouten // A carry will occur to the left of u[j+n], and it should be ignored
1374009b1c42SEd Schouten // since it cancels with the borrow that occurred in D4.
1375009b1c42SEd Schouten bool carry = false;
1376009b1c42SEd Schouten for (unsigned i = 0; i < n; i++) {
13776b3f41edSDimitry Andric uint32_t limit = std::min(u[j+i],v[i]);
1378009b1c42SEd Schouten u[j+i] += v[i] + carry;
1379009b1c42SEd Schouten carry = u[j+i] < limit || (carry && u[j+i] == limit);
1380009b1c42SEd Schouten }
1381009b1c42SEd Schouten u[j+n] += carry;
1382009b1c42SEd Schouten }
1383d8e91e46SDimitry Andric DEBUG_KNUTH(dbgs() << "KnuthDiv: after correction:");
1384d8e91e46SDimitry Andric DEBUG_KNUTH(for (int i = m + n; i >= 0; i--) dbgs() << " " << u[i]);
1385d8e91e46SDimitry Andric DEBUG_KNUTH(dbgs() << "\nKnuthDiv: digit result = " << q[j] << '\n');
1386009b1c42SEd Schouten
1387009b1c42SEd Schouten // D7. [Loop on j.] Decrease j by one. Now if j >= 0, go back to D3.
1388009b1c42SEd Schouten } while (--j >= 0);
1389009b1c42SEd Schouten
1390d8e91e46SDimitry Andric DEBUG_KNUTH(dbgs() << "KnuthDiv: quotient:");
1391d8e91e46SDimitry Andric DEBUG_KNUTH(for (int i = m; i >= 0; i--) dbgs() << " " << q[i]);
1392d8e91e46SDimitry Andric DEBUG_KNUTH(dbgs() << '\n');
1393009b1c42SEd Schouten
1394009b1c42SEd Schouten // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
1395009b1c42SEd Schouten // remainder may be obtained by dividing u[...] by d. If r is non-null we
1396009b1c42SEd Schouten // compute the remainder (urem uses this).
1397009b1c42SEd Schouten if (r) {
1398009b1c42SEd Schouten // The value d is expressed by the "shift" value above since we avoided
1399009b1c42SEd Schouten // multiplication by d by using a shift left. So, all we have to do is
140071d5a254SDimitry Andric // shift right here.
1401009b1c42SEd Schouten if (shift) {
14026b3f41edSDimitry Andric uint32_t carry = 0;
1403d8e91e46SDimitry Andric DEBUG_KNUTH(dbgs() << "KnuthDiv: remainder:");
1404009b1c42SEd Schouten for (int i = n-1; i >= 0; i--) {
1405009b1c42SEd Schouten r[i] = (u[i] >> shift) | carry;
1406009b1c42SEd Schouten carry = u[i] << (32 - shift);
1407d8e91e46SDimitry Andric DEBUG_KNUTH(dbgs() << " " << r[i]);
1408009b1c42SEd Schouten }
1409009b1c42SEd Schouten } else {
1410009b1c42SEd Schouten for (int i = n-1; i >= 0; i--) {
1411009b1c42SEd Schouten r[i] = u[i];
1412d8e91e46SDimitry Andric DEBUG_KNUTH(dbgs() << " " << r[i]);
1413009b1c42SEd Schouten }
1414009b1c42SEd Schouten }
1415d8e91e46SDimitry Andric DEBUG_KNUTH(dbgs() << '\n');
1416009b1c42SEd Schouten }
1417d8e91e46SDimitry Andric DEBUG_KNUTH(dbgs() << '\n');
1418009b1c42SEd Schouten }
1419009b1c42SEd Schouten
divide(const WordType * LHS,unsigned lhsWords,const WordType * RHS,unsigned rhsWords,WordType * Quotient,WordType * Remainder)1420b5630dbaSDimitry Andric void APInt::divide(const WordType *LHS, unsigned lhsWords, const WordType *RHS,
1421b5630dbaSDimitry Andric unsigned rhsWords, WordType *Quotient, WordType *Remainder) {
1422009b1c42SEd Schouten assert(lhsWords >= rhsWords && "Fractional result");
1423009b1c42SEd Schouten
1424009b1c42SEd Schouten // First, compose the values into an array of 32-bit words instead of
1425009b1c42SEd Schouten // 64-bit words. This is a necessity of both the "short division" algorithm
14266fe5c7aaSRoman Divacky // and the Knuth "classical algorithm" which requires there to be native
1427009b1c42SEd Schouten // operations for +, -, and * on an m bit value with an m*2 bit result. We
1428009b1c42SEd Schouten // can't use 64-bit operands here because we don't have native results of
1429009b1c42SEd Schouten // 128-bits. Furthermore, casting the 64-bit values to 32-bit values won't
1430009b1c42SEd Schouten // work on large-endian machines.
1431009b1c42SEd Schouten unsigned n = rhsWords * 2;
1432009b1c42SEd Schouten unsigned m = (lhsWords * 2) - n;
1433009b1c42SEd Schouten
1434009b1c42SEd Schouten // Allocate space for the temporary values we need either on the stack, if
1435009b1c42SEd Schouten // it will fit, or on the heap if it won't.
14366b3f41edSDimitry Andric uint32_t SPACE[128];
14376b3f41edSDimitry Andric uint32_t *U = nullptr;
14386b3f41edSDimitry Andric uint32_t *V = nullptr;
14396b3f41edSDimitry Andric uint32_t *Q = nullptr;
14406b3f41edSDimitry Andric uint32_t *R = nullptr;
1441009b1c42SEd Schouten if ((Remainder?4:3)*n+2*m+1 <= 128) {
1442009b1c42SEd Schouten U = &SPACE[0];
1443009b1c42SEd Schouten V = &SPACE[m+n+1];
1444009b1c42SEd Schouten Q = &SPACE[(m+n+1) + n];
1445009b1c42SEd Schouten if (Remainder)
1446009b1c42SEd Schouten R = &SPACE[(m+n+1) + n + (m+n)];
1447009b1c42SEd Schouten } else {
14486b3f41edSDimitry Andric U = new uint32_t[m + n + 1];
14496b3f41edSDimitry Andric V = new uint32_t[n];
14506b3f41edSDimitry Andric Q = new uint32_t[m+n];
1451009b1c42SEd Schouten if (Remainder)
14526b3f41edSDimitry Andric R = new uint32_t[n];
1453009b1c42SEd Schouten }
1454009b1c42SEd Schouten
1455009b1c42SEd Schouten // Initialize the dividend
14566b3f41edSDimitry Andric memset(U, 0, (m+n+1)*sizeof(uint32_t));
1457009b1c42SEd Schouten for (unsigned i = 0; i < lhsWords; ++i) {
1458b5630dbaSDimitry Andric uint64_t tmp = LHS[i];
14596b3f41edSDimitry Andric U[i * 2] = Lo_32(tmp);
14606b3f41edSDimitry Andric U[i * 2 + 1] = Hi_32(tmp);
1461009b1c42SEd Schouten }
1462009b1c42SEd Schouten U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
1463009b1c42SEd Schouten
1464009b1c42SEd Schouten // Initialize the divisor
14656b3f41edSDimitry Andric memset(V, 0, (n)*sizeof(uint32_t));
1466009b1c42SEd Schouten for (unsigned i = 0; i < rhsWords; ++i) {
1467b5630dbaSDimitry Andric uint64_t tmp = RHS[i];
14686b3f41edSDimitry Andric V[i * 2] = Lo_32(tmp);
14696b3f41edSDimitry Andric V[i * 2 + 1] = Hi_32(tmp);
1470009b1c42SEd Schouten }
1471009b1c42SEd Schouten
1472009b1c42SEd Schouten // initialize the quotient and remainder
14736b3f41edSDimitry Andric memset(Q, 0, (m+n) * sizeof(uint32_t));
1474009b1c42SEd Schouten if (Remainder)
14756b3f41edSDimitry Andric memset(R, 0, n * sizeof(uint32_t));
1476009b1c42SEd Schouten
1477009b1c42SEd Schouten // Now, adjust m and n for the Knuth division. n is the number of words in
1478009b1c42SEd Schouten // the divisor. m is the number of words by which the dividend exceeds the
1479009b1c42SEd Schouten // divisor (i.e. m+n is the length of the dividend). These sizes must not
1480009b1c42SEd Schouten // contain any zero words or the Knuth algorithm fails.
1481009b1c42SEd Schouten for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
1482009b1c42SEd Schouten n--;
1483009b1c42SEd Schouten m++;
1484009b1c42SEd Schouten }
1485009b1c42SEd Schouten for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
1486009b1c42SEd Schouten m--;
1487009b1c42SEd Schouten
1488009b1c42SEd Schouten // If we're left with only a single word for the divisor, Knuth doesn't work
1489009b1c42SEd Schouten // so we implement the short division algorithm here. This is much simpler
1490009b1c42SEd Schouten // and faster because we are certain that we can divide a 64-bit quantity
1491009b1c42SEd Schouten // by a 32-bit quantity at hardware speed and short division is simply a
1492009b1c42SEd Schouten // series of such operations. This is just like doing short division but we
1493009b1c42SEd Schouten // are using base 2^32 instead of base 10.
1494009b1c42SEd Schouten assert(n != 0 && "Divide by zero?");
1495009b1c42SEd Schouten if (n == 1) {
14966b3f41edSDimitry Andric uint32_t divisor = V[0];
14976b3f41edSDimitry Andric uint32_t remainder = 0;
14986b3f41edSDimitry Andric for (int i = m; i >= 0; i--) {
14996b3f41edSDimitry Andric uint64_t partial_dividend = Make_64(remainder, U[i]);
1500009b1c42SEd Schouten if (partial_dividend == 0) {
1501009b1c42SEd Schouten Q[i] = 0;
1502009b1c42SEd Schouten remainder = 0;
1503009b1c42SEd Schouten } else if (partial_dividend < divisor) {
1504009b1c42SEd Schouten Q[i] = 0;
15056b3f41edSDimitry Andric remainder = Lo_32(partial_dividend);
1506009b1c42SEd Schouten } else if (partial_dividend == divisor) {
1507009b1c42SEd Schouten Q[i] = 1;
1508009b1c42SEd Schouten remainder = 0;
1509009b1c42SEd Schouten } else {
15106b3f41edSDimitry Andric Q[i] = Lo_32(partial_dividend / divisor);
15116b3f41edSDimitry Andric remainder = Lo_32(partial_dividend - (Q[i] * divisor));
1512009b1c42SEd Schouten }
1513009b1c42SEd Schouten }
1514009b1c42SEd Schouten if (R)
1515009b1c42SEd Schouten R[0] = remainder;
1516009b1c42SEd Schouten } else {
1517009b1c42SEd Schouten // Now we're ready to invoke the Knuth classical divide algorithm. In this
1518009b1c42SEd Schouten // case n > 1.
1519009b1c42SEd Schouten KnuthDiv(U, V, Q, R, m, n);
1520009b1c42SEd Schouten }
1521009b1c42SEd Schouten
1522009b1c42SEd Schouten // If the caller wants the quotient
1523009b1c42SEd Schouten if (Quotient) {
1524009b1c42SEd Schouten for (unsigned i = 0; i < lhsWords; ++i)
1525b5630dbaSDimitry Andric Quotient[i] = Make_64(Q[i*2+1], Q[i*2]);
1526009b1c42SEd Schouten }
1527009b1c42SEd Schouten
1528009b1c42SEd Schouten // If the caller wants the remainder
1529009b1c42SEd Schouten if (Remainder) {
1530009b1c42SEd Schouten for (unsigned i = 0; i < rhsWords; ++i)
1531b5630dbaSDimitry Andric Remainder[i] = Make_64(R[i*2+1], R[i*2]);
1532009b1c42SEd Schouten }
1533009b1c42SEd Schouten
1534009b1c42SEd Schouten // Clean up the memory we allocated.
1535009b1c42SEd Schouten if (U != &SPACE[0]) {
1536009b1c42SEd Schouten delete [] U;
1537009b1c42SEd Schouten delete [] V;
1538009b1c42SEd Schouten delete [] Q;
1539009b1c42SEd Schouten delete [] R;
1540009b1c42SEd Schouten }
1541009b1c42SEd Schouten }
1542009b1c42SEd Schouten
udiv(const APInt & RHS) const1543009b1c42SEd Schouten APInt APInt::udiv(const APInt &RHS) const {
1544009b1c42SEd Schouten assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1545009b1c42SEd Schouten
1546009b1c42SEd Schouten // First, deal with the easy case
1547009b1c42SEd Schouten if (isSingleWord()) {
1548148779dfSDimitry Andric assert(RHS.U.VAL != 0 && "Divide by zero?");
1549148779dfSDimitry Andric return APInt(BitWidth, U.VAL / RHS.U.VAL);
1550009b1c42SEd Schouten }
1551009b1c42SEd Schouten
1552009b1c42SEd Schouten // Get some facts about the LHS and RHS number of bits and words
15536b3f41edSDimitry Andric unsigned lhsWords = getNumWords(getActiveBits());
1554009b1c42SEd Schouten unsigned rhsBits = RHS.getActiveBits();
15556b3f41edSDimitry Andric unsigned rhsWords = getNumWords(rhsBits);
1556009b1c42SEd Schouten assert(rhsWords && "Divided by zero???");
1557009b1c42SEd Schouten
1558009b1c42SEd Schouten // Deal with some degenerate cases
1559009b1c42SEd Schouten if (!lhsWords)
1560009b1c42SEd Schouten // 0 / X ===> 0
1561009b1c42SEd Schouten return APInt(BitWidth, 0);
15626b3f41edSDimitry Andric if (rhsBits == 1)
15636b3f41edSDimitry Andric // X / 1 ===> X
15646b3f41edSDimitry Andric return *this;
15656b3f41edSDimitry Andric if (lhsWords < rhsWords || this->ult(RHS))
1566009b1c42SEd Schouten // X / Y ===> 0, iff X < Y
1567009b1c42SEd Schouten return APInt(BitWidth, 0);
15686b3f41edSDimitry Andric if (*this == RHS)
1569009b1c42SEd Schouten // X / X ===> 1
1570009b1c42SEd Schouten return APInt(BitWidth, 1);
15716b3f41edSDimitry Andric if (lhsWords == 1) // rhsWords is 1 if lhsWords is 1.
1572009b1c42SEd Schouten // All high words are zero, just use native divide
1573148779dfSDimitry Andric return APInt(BitWidth, this->U.pVal[0] / RHS.U.pVal[0]);
1574009b1c42SEd Schouten
1575009b1c42SEd Schouten // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1576b5630dbaSDimitry Andric APInt Quotient(BitWidth, 0); // to hold result.
1577b5630dbaSDimitry Andric divide(U.pVal, lhsWords, RHS.U.pVal, rhsWords, Quotient.U.pVal, nullptr);
1578b5630dbaSDimitry Andric return Quotient;
1579b5630dbaSDimitry Andric }
1580b5630dbaSDimitry Andric
udiv(uint64_t RHS) const1581b5630dbaSDimitry Andric APInt APInt::udiv(uint64_t RHS) const {
1582b5630dbaSDimitry Andric assert(RHS != 0 && "Divide by zero?");
1583b5630dbaSDimitry Andric
1584b5630dbaSDimitry Andric // First, deal with the easy case
1585b5630dbaSDimitry Andric if (isSingleWord())
1586b5630dbaSDimitry Andric return APInt(BitWidth, U.VAL / RHS);
1587b5630dbaSDimitry Andric
1588b5630dbaSDimitry Andric // Get some facts about the LHS words.
1589b5630dbaSDimitry Andric unsigned lhsWords = getNumWords(getActiveBits());
1590b5630dbaSDimitry Andric
1591b5630dbaSDimitry Andric // Deal with some degenerate cases
1592b5630dbaSDimitry Andric if (!lhsWords)
1593b5630dbaSDimitry Andric // 0 / X ===> 0
1594b5630dbaSDimitry Andric return APInt(BitWidth, 0);
1595b5630dbaSDimitry Andric if (RHS == 1)
1596b5630dbaSDimitry Andric // X / 1 ===> X
1597b5630dbaSDimitry Andric return *this;
1598b5630dbaSDimitry Andric if (this->ult(RHS))
1599b5630dbaSDimitry Andric // X / Y ===> 0, iff X < Y
1600b5630dbaSDimitry Andric return APInt(BitWidth, 0);
1601b5630dbaSDimitry Andric if (*this == RHS)
1602b5630dbaSDimitry Andric // X / X ===> 1
1603b5630dbaSDimitry Andric return APInt(BitWidth, 1);
1604b5630dbaSDimitry Andric if (lhsWords == 1) // rhsWords is 1 if lhsWords is 1.
1605b5630dbaSDimitry Andric // All high words are zero, just use native divide
1606b5630dbaSDimitry Andric return APInt(BitWidth, this->U.pVal[0] / RHS);
1607b5630dbaSDimitry Andric
1608b5630dbaSDimitry Andric // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1609b5630dbaSDimitry Andric APInt Quotient(BitWidth, 0); // to hold result.
1610b5630dbaSDimitry Andric divide(U.pVal, lhsWords, &RHS, 1, Quotient.U.pVal, nullptr);
1611009b1c42SEd Schouten return Quotient;
1612009b1c42SEd Schouten }
1613009b1c42SEd Schouten
sdiv(const APInt & RHS) const16144a16efa3SDimitry Andric APInt APInt::sdiv(const APInt &RHS) const {
16154a16efa3SDimitry Andric if (isNegative()) {
16164a16efa3SDimitry Andric if (RHS.isNegative())
16174a16efa3SDimitry Andric return (-(*this)).udiv(-RHS);
16184a16efa3SDimitry Andric return -((-(*this)).udiv(RHS));
16194a16efa3SDimitry Andric }
16204a16efa3SDimitry Andric if (RHS.isNegative())
16214a16efa3SDimitry Andric return -(this->udiv(-RHS));
16224a16efa3SDimitry Andric return this->udiv(RHS);
16234a16efa3SDimitry Andric }
16244a16efa3SDimitry Andric
sdiv(int64_t RHS) const1625b5630dbaSDimitry Andric APInt APInt::sdiv(int64_t RHS) const {
1626b5630dbaSDimitry Andric if (isNegative()) {
1627b5630dbaSDimitry Andric if (RHS < 0)
1628b5630dbaSDimitry Andric return (-(*this)).udiv(-RHS);
1629b5630dbaSDimitry Andric return -((-(*this)).udiv(RHS));
1630b5630dbaSDimitry Andric }
1631b5630dbaSDimitry Andric if (RHS < 0)
1632b5630dbaSDimitry Andric return -(this->udiv(-RHS));
1633b5630dbaSDimitry Andric return this->udiv(RHS);
1634b5630dbaSDimitry Andric }
1635b5630dbaSDimitry Andric
urem(const APInt & RHS) const1636009b1c42SEd Schouten APInt APInt::urem(const APInt &RHS) const {
1637009b1c42SEd Schouten assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
1638009b1c42SEd Schouten if (isSingleWord()) {
1639148779dfSDimitry Andric assert(RHS.U.VAL != 0 && "Remainder by zero?");
1640148779dfSDimitry Andric return APInt(BitWidth, U.VAL % RHS.U.VAL);
1641009b1c42SEd Schouten }
1642009b1c42SEd Schouten
1643009b1c42SEd Schouten // Get some facts about the LHS
16446b3f41edSDimitry Andric unsigned lhsWords = getNumWords(getActiveBits());
1645009b1c42SEd Schouten
1646009b1c42SEd Schouten // Get some facts about the RHS
1647009b1c42SEd Schouten unsigned rhsBits = RHS.getActiveBits();
16486b3f41edSDimitry Andric unsigned rhsWords = getNumWords(rhsBits);
1649009b1c42SEd Schouten assert(rhsWords && "Performing remainder operation by zero ???");
1650009b1c42SEd Schouten
1651009b1c42SEd Schouten // Check the degenerate cases
16526b3f41edSDimitry Andric if (lhsWords == 0)
1653009b1c42SEd Schouten // 0 % Y ===> 0
1654009b1c42SEd Schouten return APInt(BitWidth, 0);
16556b3f41edSDimitry Andric if (rhsBits == 1)
16566b3f41edSDimitry Andric // X % 1 ===> 0
16576b3f41edSDimitry Andric return APInt(BitWidth, 0);
16586b3f41edSDimitry Andric if (lhsWords < rhsWords || this->ult(RHS))
1659009b1c42SEd Schouten // X % Y ===> X, iff X < Y
1660009b1c42SEd Schouten return *this;
16616b3f41edSDimitry Andric if (*this == RHS)
1662009b1c42SEd Schouten // X % X == 0;
1663009b1c42SEd Schouten return APInt(BitWidth, 0);
16646b3f41edSDimitry Andric if (lhsWords == 1)
1665009b1c42SEd Schouten // All high words are zero, just use native remainder
1666148779dfSDimitry Andric return APInt(BitWidth, U.pVal[0] % RHS.U.pVal[0]);
1667009b1c42SEd Schouten
1668009b1c42SEd Schouten // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1669b5630dbaSDimitry Andric APInt Remainder(BitWidth, 0);
1670b5630dbaSDimitry Andric divide(U.pVal, lhsWords, RHS.U.pVal, rhsWords, nullptr, Remainder.U.pVal);
1671b5630dbaSDimitry Andric return Remainder;
1672b5630dbaSDimitry Andric }
1673b5630dbaSDimitry Andric
urem(uint64_t RHS) const1674b5630dbaSDimitry Andric uint64_t APInt::urem(uint64_t RHS) const {
1675b5630dbaSDimitry Andric assert(RHS != 0 && "Remainder by zero?");
1676b5630dbaSDimitry Andric
1677b5630dbaSDimitry Andric if (isSingleWord())
1678b5630dbaSDimitry Andric return U.VAL % RHS;
1679b5630dbaSDimitry Andric
1680b5630dbaSDimitry Andric // Get some facts about the LHS
1681b5630dbaSDimitry Andric unsigned lhsWords = getNumWords(getActiveBits());
1682b5630dbaSDimitry Andric
1683b5630dbaSDimitry Andric // Check the degenerate cases
1684b5630dbaSDimitry Andric if (lhsWords == 0)
1685b5630dbaSDimitry Andric // 0 % Y ===> 0
1686b5630dbaSDimitry Andric return 0;
1687b5630dbaSDimitry Andric if (RHS == 1)
1688b5630dbaSDimitry Andric // X % 1 ===> 0
1689b5630dbaSDimitry Andric return 0;
1690b5630dbaSDimitry Andric if (this->ult(RHS))
1691b5630dbaSDimitry Andric // X % Y ===> X, iff X < Y
1692b5630dbaSDimitry Andric return getZExtValue();
1693b5630dbaSDimitry Andric if (*this == RHS)
1694b5630dbaSDimitry Andric // X % X == 0;
1695b5630dbaSDimitry Andric return 0;
1696b5630dbaSDimitry Andric if (lhsWords == 1)
1697b5630dbaSDimitry Andric // All high words are zero, just use native remainder
1698b5630dbaSDimitry Andric return U.pVal[0] % RHS;
1699b5630dbaSDimitry Andric
1700b5630dbaSDimitry Andric // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1701b5630dbaSDimitry Andric uint64_t Remainder;
1702b5630dbaSDimitry Andric divide(U.pVal, lhsWords, &RHS, 1, nullptr, &Remainder);
1703009b1c42SEd Schouten return Remainder;
1704009b1c42SEd Schouten }
1705009b1c42SEd Schouten
srem(const APInt & RHS) const17064a16efa3SDimitry Andric APInt APInt::srem(const APInt &RHS) const {
17074a16efa3SDimitry Andric if (isNegative()) {
17084a16efa3SDimitry Andric if (RHS.isNegative())
17094a16efa3SDimitry Andric return -((-(*this)).urem(-RHS));
17104a16efa3SDimitry Andric return -((-(*this)).urem(RHS));
17114a16efa3SDimitry Andric }
17124a16efa3SDimitry Andric if (RHS.isNegative())
17134a16efa3SDimitry Andric return this->urem(-RHS);
17144a16efa3SDimitry Andric return this->urem(RHS);
17154a16efa3SDimitry Andric }
17164a16efa3SDimitry Andric
srem(int64_t RHS) const1717b5630dbaSDimitry Andric int64_t APInt::srem(int64_t RHS) const {
1718b5630dbaSDimitry Andric if (isNegative()) {
1719b5630dbaSDimitry Andric if (RHS < 0)
1720b5630dbaSDimitry Andric return -((-(*this)).urem(-RHS));
1721b5630dbaSDimitry Andric return -((-(*this)).urem(RHS));
1722b5630dbaSDimitry Andric }
1723b5630dbaSDimitry Andric if (RHS < 0)
1724b5630dbaSDimitry Andric return this->urem(-RHS);
1725b5630dbaSDimitry Andric return this->urem(RHS);
1726b5630dbaSDimitry Andric }
1727b5630dbaSDimitry Andric
udivrem(const APInt & LHS,const APInt & RHS,APInt & Quotient,APInt & Remainder)1728009b1c42SEd Schouten void APInt::udivrem(const APInt &LHS, const APInt &RHS,
1729009b1c42SEd Schouten APInt &Quotient, APInt &Remainder) {
173067c32a98SDimitry Andric assert(LHS.BitWidth == RHS.BitWidth && "Bit widths must be the same");
17316b3f41edSDimitry Andric unsigned BitWidth = LHS.BitWidth;
173267c32a98SDimitry Andric
173367c32a98SDimitry Andric // First, deal with the easy case
173467c32a98SDimitry Andric if (LHS.isSingleWord()) {
1735148779dfSDimitry Andric assert(RHS.U.VAL != 0 && "Divide by zero?");
1736148779dfSDimitry Andric uint64_t QuotVal = LHS.U.VAL / RHS.U.VAL;
1737148779dfSDimitry Andric uint64_t RemVal = LHS.U.VAL % RHS.U.VAL;
17386b3f41edSDimitry Andric Quotient = APInt(BitWidth, QuotVal);
17396b3f41edSDimitry Andric Remainder = APInt(BitWidth, RemVal);
174067c32a98SDimitry Andric return;
174167c32a98SDimitry Andric }
174267c32a98SDimitry Andric
1743009b1c42SEd Schouten // Get some size facts about the dividend and divisor
17446b3f41edSDimitry Andric unsigned lhsWords = getNumWords(LHS.getActiveBits());
1745009b1c42SEd Schouten unsigned rhsBits = RHS.getActiveBits();
17466b3f41edSDimitry Andric unsigned rhsWords = getNumWords(rhsBits);
17476b3f41edSDimitry Andric assert(rhsWords && "Performing divrem operation by zero ???");
1748009b1c42SEd Schouten
1749009b1c42SEd Schouten // Check the degenerate cases
1750009b1c42SEd Schouten if (lhsWords == 0) {
1751eb11fae6SDimitry Andric Quotient = APInt(BitWidth, 0); // 0 / Y ===> 0
1752eb11fae6SDimitry Andric Remainder = APInt(BitWidth, 0); // 0 % Y ===> 0
1753009b1c42SEd Schouten return;
1754009b1c42SEd Schouten }
1755009b1c42SEd Schouten
17566b3f41edSDimitry Andric if (rhsBits == 1) {
17576b3f41edSDimitry Andric Quotient = LHS; // X / 1 ===> X
1758eb11fae6SDimitry Andric Remainder = APInt(BitWidth, 0); // X % 1 ===> 0
17596b3f41edSDimitry Andric }
17606b3f41edSDimitry Andric
1761009b1c42SEd Schouten if (lhsWords < rhsWords || LHS.ult(RHS)) {
1762009b1c42SEd Schouten Remainder = LHS; // X % Y ===> X, iff X < Y
1763eb11fae6SDimitry Andric Quotient = APInt(BitWidth, 0); // X / Y ===> 0, iff X < Y
1764009b1c42SEd Schouten return;
1765009b1c42SEd Schouten }
1766009b1c42SEd Schouten
1767009b1c42SEd Schouten if (LHS == RHS) {
1768eb11fae6SDimitry Andric Quotient = APInt(BitWidth, 1); // X / X ===> 1
1769eb11fae6SDimitry Andric Remainder = APInt(BitWidth, 0); // X % X ===> 0;
1770009b1c42SEd Schouten return;
1771009b1c42SEd Schouten }
1772009b1c42SEd Schouten
1773b5630dbaSDimitry Andric // Make sure there is enough space to hold the results.
1774b5630dbaSDimitry Andric // NOTE: This assumes that reallocate won't affect any bits if it doesn't
1775b5630dbaSDimitry Andric // change the size. This is necessary if Quotient or Remainder is aliased
1776b5630dbaSDimitry Andric // with LHS or RHS.
1777b5630dbaSDimitry Andric Quotient.reallocate(BitWidth);
1778b5630dbaSDimitry Andric Remainder.reallocate(BitWidth);
1779b5630dbaSDimitry Andric
17806b3f41edSDimitry Andric if (lhsWords == 1) { // rhsWords is 1 if lhsWords is 1.
1781009b1c42SEd Schouten // There is only one word to consider so use the native versions.
17826b3f41edSDimitry Andric uint64_t lhsValue = LHS.U.pVal[0];
17836b3f41edSDimitry Andric uint64_t rhsValue = RHS.U.pVal[0];
17846b3f41edSDimitry Andric Quotient = lhsValue / rhsValue;
17856b3f41edSDimitry Andric Remainder = lhsValue % rhsValue;
1786009b1c42SEd Schouten return;
1787009b1c42SEd Schouten }
1788009b1c42SEd Schouten
1789009b1c42SEd Schouten // Okay, lets do it the long way
1790b5630dbaSDimitry Andric divide(LHS.U.pVal, lhsWords, RHS.U.pVal, rhsWords, Quotient.U.pVal,
1791b5630dbaSDimitry Andric Remainder.U.pVal);
1792b5630dbaSDimitry Andric // Clear the rest of the Quotient and Remainder.
1793b5630dbaSDimitry Andric std::memset(Quotient.U.pVal + lhsWords, 0,
1794b5630dbaSDimitry Andric (getNumWords(BitWidth) - lhsWords) * APINT_WORD_SIZE);
1795b5630dbaSDimitry Andric std::memset(Remainder.U.pVal + rhsWords, 0,
1796b5630dbaSDimitry Andric (getNumWords(BitWidth) - rhsWords) * APINT_WORD_SIZE);
1797b5630dbaSDimitry Andric }
1798b5630dbaSDimitry Andric
udivrem(const APInt & LHS,uint64_t RHS,APInt & Quotient,uint64_t & Remainder)1799b5630dbaSDimitry Andric void APInt::udivrem(const APInt &LHS, uint64_t RHS, APInt &Quotient,
1800b5630dbaSDimitry Andric uint64_t &Remainder) {
1801b5630dbaSDimitry Andric assert(RHS != 0 && "Divide by zero?");
1802b5630dbaSDimitry Andric unsigned BitWidth = LHS.BitWidth;
1803b5630dbaSDimitry Andric
1804b5630dbaSDimitry Andric // First, deal with the easy case
1805b5630dbaSDimitry Andric if (LHS.isSingleWord()) {
1806b5630dbaSDimitry Andric uint64_t QuotVal = LHS.U.VAL / RHS;
1807b5630dbaSDimitry Andric Remainder = LHS.U.VAL % RHS;
1808b5630dbaSDimitry Andric Quotient = APInt(BitWidth, QuotVal);
1809b5630dbaSDimitry Andric return;
1810b5630dbaSDimitry Andric }
1811b5630dbaSDimitry Andric
1812b5630dbaSDimitry Andric // Get some size facts about the dividend and divisor
1813b5630dbaSDimitry Andric unsigned lhsWords = getNumWords(LHS.getActiveBits());
1814b5630dbaSDimitry Andric
1815b5630dbaSDimitry Andric // Check the degenerate cases
1816b5630dbaSDimitry Andric if (lhsWords == 0) {
1817eb11fae6SDimitry Andric Quotient = APInt(BitWidth, 0); // 0 / Y ===> 0
1818b5630dbaSDimitry Andric Remainder = 0; // 0 % Y ===> 0
1819b5630dbaSDimitry Andric return;
1820b5630dbaSDimitry Andric }
1821b5630dbaSDimitry Andric
1822b5630dbaSDimitry Andric if (RHS == 1) {
1823b5630dbaSDimitry Andric Quotient = LHS; // X / 1 ===> X
1824b5630dbaSDimitry Andric Remainder = 0; // X % 1 ===> 0
1825eb11fae6SDimitry Andric return;
1826b5630dbaSDimitry Andric }
1827b5630dbaSDimitry Andric
1828b5630dbaSDimitry Andric if (LHS.ult(RHS)) {
1829b5630dbaSDimitry Andric Remainder = LHS.getZExtValue(); // X % Y ===> X, iff X < Y
1830eb11fae6SDimitry Andric Quotient = APInt(BitWidth, 0); // X / Y ===> 0, iff X < Y
1831b5630dbaSDimitry Andric return;
1832b5630dbaSDimitry Andric }
1833b5630dbaSDimitry Andric
1834b5630dbaSDimitry Andric if (LHS == RHS) {
1835eb11fae6SDimitry Andric Quotient = APInt(BitWidth, 1); // X / X ===> 1
1836b5630dbaSDimitry Andric Remainder = 0; // X % X ===> 0;
1837b5630dbaSDimitry Andric return;
1838b5630dbaSDimitry Andric }
1839b5630dbaSDimitry Andric
1840b5630dbaSDimitry Andric // Make sure there is enough space to hold the results.
1841b5630dbaSDimitry Andric // NOTE: This assumes that reallocate won't affect any bits if it doesn't
1842b5630dbaSDimitry Andric // change the size. This is necessary if Quotient is aliased with LHS.
1843b5630dbaSDimitry Andric Quotient.reallocate(BitWidth);
1844b5630dbaSDimitry Andric
1845b5630dbaSDimitry Andric if (lhsWords == 1) { // rhsWords is 1 if lhsWords is 1.
1846b5630dbaSDimitry Andric // There is only one word to consider so use the native versions.
1847b5630dbaSDimitry Andric uint64_t lhsValue = LHS.U.pVal[0];
1848b5630dbaSDimitry Andric Quotient = lhsValue / RHS;
1849b5630dbaSDimitry Andric Remainder = lhsValue % RHS;
1850b5630dbaSDimitry Andric return;
1851b5630dbaSDimitry Andric }
1852b5630dbaSDimitry Andric
1853b5630dbaSDimitry Andric // Okay, lets do it the long way
1854b5630dbaSDimitry Andric divide(LHS.U.pVal, lhsWords, &RHS, 1, Quotient.U.pVal, &Remainder);
1855b5630dbaSDimitry Andric // Clear the rest of the Quotient.
1856b5630dbaSDimitry Andric std::memset(Quotient.U.pVal + lhsWords, 0,
1857b5630dbaSDimitry Andric (getNumWords(BitWidth) - lhsWords) * APINT_WORD_SIZE);
1858009b1c42SEd Schouten }
1859009b1c42SEd Schouten
sdivrem(const APInt & LHS,const APInt & RHS,APInt & Quotient,APInt & Remainder)18604a16efa3SDimitry Andric void APInt::sdivrem(const APInt &LHS, const APInt &RHS,
18614a16efa3SDimitry Andric APInt &Quotient, APInt &Remainder) {
18624a16efa3SDimitry Andric if (LHS.isNegative()) {
18634a16efa3SDimitry Andric if (RHS.isNegative())
18644a16efa3SDimitry Andric APInt::udivrem(-LHS, -RHS, Quotient, Remainder);
18654a16efa3SDimitry Andric else {
18664a16efa3SDimitry Andric APInt::udivrem(-LHS, RHS, Quotient, Remainder);
18676b3f41edSDimitry Andric Quotient.negate();
18684a16efa3SDimitry Andric }
18696b3f41edSDimitry Andric Remainder.negate();
18704a16efa3SDimitry Andric } else if (RHS.isNegative()) {
18714a16efa3SDimitry Andric APInt::udivrem(LHS, -RHS, Quotient, Remainder);
18726b3f41edSDimitry Andric Quotient.negate();
18734a16efa3SDimitry Andric } else {
18744a16efa3SDimitry Andric APInt::udivrem(LHS, RHS, Quotient, Remainder);
18754a16efa3SDimitry Andric }
18764a16efa3SDimitry Andric }
18774a16efa3SDimitry Andric
sdivrem(const APInt & LHS,int64_t RHS,APInt & Quotient,int64_t & Remainder)1878b5630dbaSDimitry Andric void APInt::sdivrem(const APInt &LHS, int64_t RHS,
1879b5630dbaSDimitry Andric APInt &Quotient, int64_t &Remainder) {
1880b5630dbaSDimitry Andric uint64_t R = Remainder;
1881b5630dbaSDimitry Andric if (LHS.isNegative()) {
1882b5630dbaSDimitry Andric if (RHS < 0)
1883b5630dbaSDimitry Andric APInt::udivrem(-LHS, -RHS, Quotient, R);
1884b5630dbaSDimitry Andric else {
1885b5630dbaSDimitry Andric APInt::udivrem(-LHS, RHS, Quotient, R);
1886b5630dbaSDimitry Andric Quotient.negate();
1887b5630dbaSDimitry Andric }
1888b5630dbaSDimitry Andric R = -R;
1889b5630dbaSDimitry Andric } else if (RHS < 0) {
1890b5630dbaSDimitry Andric APInt::udivrem(LHS, -RHS, Quotient, R);
1891b5630dbaSDimitry Andric Quotient.negate();
1892b5630dbaSDimitry Andric } else {
1893b5630dbaSDimitry Andric APInt::udivrem(LHS, RHS, Quotient, R);
1894b5630dbaSDimitry Andric }
1895b5630dbaSDimitry Andric Remainder = R;
1896b5630dbaSDimitry Andric }
1897b5630dbaSDimitry Andric
sadd_ov(const APInt & RHS,bool & Overflow) const1898cf099d11SDimitry Andric APInt APInt::sadd_ov(const APInt &RHS, bool &Overflow) const {
1899cf099d11SDimitry Andric APInt Res = *this+RHS;
1900cf099d11SDimitry Andric Overflow = isNonNegative() == RHS.isNonNegative() &&
1901cf099d11SDimitry Andric Res.isNonNegative() != isNonNegative();
1902cf099d11SDimitry Andric return Res;
1903cf099d11SDimitry Andric }
1904cf099d11SDimitry Andric
uadd_ov(const APInt & RHS,bool & Overflow) const1905cf099d11SDimitry Andric APInt APInt::uadd_ov(const APInt &RHS, bool &Overflow) const {
1906cf099d11SDimitry Andric APInt Res = *this+RHS;
1907cf099d11SDimitry Andric Overflow = Res.ult(RHS);
1908cf099d11SDimitry Andric return Res;
1909cf099d11SDimitry Andric }
1910cf099d11SDimitry Andric
ssub_ov(const APInt & RHS,bool & Overflow) const1911cf099d11SDimitry Andric APInt APInt::ssub_ov(const APInt &RHS, bool &Overflow) const {
1912cf099d11SDimitry Andric APInt Res = *this - RHS;
1913cf099d11SDimitry Andric Overflow = isNonNegative() != RHS.isNonNegative() &&
1914cf099d11SDimitry Andric Res.isNonNegative() != isNonNegative();
1915cf099d11SDimitry Andric return Res;
1916cf099d11SDimitry Andric }
1917cf099d11SDimitry Andric
usub_ov(const APInt & RHS,bool & Overflow) const1918cf099d11SDimitry Andric APInt APInt::usub_ov(const APInt &RHS, bool &Overflow) const {
1919cf099d11SDimitry Andric APInt Res = *this-RHS;
1920cf099d11SDimitry Andric Overflow = Res.ugt(*this);
1921cf099d11SDimitry Andric return Res;
1922cf099d11SDimitry Andric }
1923cf099d11SDimitry Andric
sdiv_ov(const APInt & RHS,bool & Overflow) const1924cf099d11SDimitry Andric APInt APInt::sdiv_ov(const APInt &RHS, bool &Overflow) const {
1925cf099d11SDimitry Andric // MININT/-1 --> overflow.
1926c0981da4SDimitry Andric Overflow = isMinSignedValue() && RHS.isAllOnes();
1927cf099d11SDimitry Andric return sdiv(RHS);
1928cf099d11SDimitry Andric }
1929cf099d11SDimitry Andric
smul_ov(const APInt & RHS,bool & Overflow) const1930cf099d11SDimitry Andric APInt APInt::smul_ov(const APInt &RHS, bool &Overflow) const {
1931cf099d11SDimitry Andric APInt Res = *this * RHS;
1932cf099d11SDimitry Andric
1933c0981da4SDimitry Andric if (RHS != 0)
1934c0981da4SDimitry Andric Overflow = Res.sdiv(RHS) != *this ||
1935c0981da4SDimitry Andric (isMinSignedValue() && RHS.isAllOnes());
1936cf099d11SDimitry Andric else
1937cf099d11SDimitry Andric Overflow = false;
1938cf099d11SDimitry Andric return Res;
1939cf099d11SDimitry Andric }
1940cf099d11SDimitry Andric
umul_ov(const APInt & RHS,bool & Overflow) const19416b943ff3SDimitry Andric APInt APInt::umul_ov(const APInt &RHS, bool &Overflow) const {
19427fa27ce4SDimitry Andric if (countl_zero() + RHS.countl_zero() + 2 <= BitWidth) {
1943e6d15924SDimitry Andric Overflow = true;
1944e6d15924SDimitry Andric return *this * RHS;
1945e6d15924SDimitry Andric }
19466b943ff3SDimitry Andric
1947e6d15924SDimitry Andric APInt Res = lshr(1) * RHS;
1948e6d15924SDimitry Andric Overflow = Res.isNegative();
1949e6d15924SDimitry Andric Res <<= 1;
1950e6d15924SDimitry Andric if ((*this)[0]) {
1951e6d15924SDimitry Andric Res += RHS;
1952e6d15924SDimitry Andric if (Res.ult(RHS))
1953e6d15924SDimitry Andric Overflow = true;
1954e6d15924SDimitry Andric }
19556b943ff3SDimitry Andric return Res;
19566b943ff3SDimitry Andric }
19576b943ff3SDimitry Andric
sshl_ov(const APInt & ShAmt,bool & Overflow) const195867c32a98SDimitry Andric APInt APInt::sshl_ov(const APInt &ShAmt, bool &Overflow) const {
19597fa27ce4SDimitry Andric return sshl_ov(ShAmt.getLimitedValue(getBitWidth()), Overflow);
19607fa27ce4SDimitry Andric }
19617fa27ce4SDimitry Andric
sshl_ov(unsigned ShAmt,bool & Overflow) const19627fa27ce4SDimitry Andric APInt APInt::sshl_ov(unsigned ShAmt, bool &Overflow) const {
19637fa27ce4SDimitry Andric Overflow = ShAmt >= getBitWidth();
1964cf099d11SDimitry Andric if (Overflow)
196567c32a98SDimitry Andric return APInt(BitWidth, 0);
1966cf099d11SDimitry Andric
1967cf099d11SDimitry Andric if (isNonNegative()) // Don't allow sign change.
19687fa27ce4SDimitry Andric Overflow = ShAmt >= countl_zero();
1969cf099d11SDimitry Andric else
19707fa27ce4SDimitry Andric Overflow = ShAmt >= countl_one();
197167c32a98SDimitry Andric
197267c32a98SDimitry Andric return *this << ShAmt;
197367c32a98SDimitry Andric }
197467c32a98SDimitry Andric
ushl_ov(const APInt & ShAmt,bool & Overflow) const197567c32a98SDimitry Andric APInt APInt::ushl_ov(const APInt &ShAmt, bool &Overflow) const {
19767fa27ce4SDimitry Andric return ushl_ov(ShAmt.getLimitedValue(getBitWidth()), Overflow);
19777fa27ce4SDimitry Andric }
19787fa27ce4SDimitry Andric
ushl_ov(unsigned ShAmt,bool & Overflow) const19797fa27ce4SDimitry Andric APInt APInt::ushl_ov(unsigned ShAmt, bool &Overflow) const {
19807fa27ce4SDimitry Andric Overflow = ShAmt >= getBitWidth();
198167c32a98SDimitry Andric if (Overflow)
198267c32a98SDimitry Andric return APInt(BitWidth, 0);
198367c32a98SDimitry Andric
19847fa27ce4SDimitry Andric Overflow = ShAmt > countl_zero();
1985cf099d11SDimitry Andric
1986cf099d11SDimitry Andric return *this << ShAmt;
1987cf099d11SDimitry Andric }
1988cf099d11SDimitry Andric
sfloordiv_ov(const APInt & RHS,bool & Overflow) const1989ac9a064cSDimitry Andric APInt APInt::sfloordiv_ov(const APInt &RHS, bool &Overflow) const {
1990ac9a064cSDimitry Andric APInt quotient = sdiv_ov(RHS, Overflow);
1991ac9a064cSDimitry Andric if ((quotient * RHS != *this) && (isNegative() != RHS.isNegative()))
1992ac9a064cSDimitry Andric return quotient - 1;
1993ac9a064cSDimitry Andric return quotient;
1994ac9a064cSDimitry Andric }
1995ac9a064cSDimitry Andric
sadd_sat(const APInt & RHS) const1996d8e91e46SDimitry Andric APInt APInt::sadd_sat(const APInt &RHS) const {
1997d8e91e46SDimitry Andric bool Overflow;
1998d8e91e46SDimitry Andric APInt Res = sadd_ov(RHS, Overflow);
1999d8e91e46SDimitry Andric if (!Overflow)
2000d8e91e46SDimitry Andric return Res;
2001cf099d11SDimitry Andric
2002d8e91e46SDimitry Andric return isNegative() ? APInt::getSignedMinValue(BitWidth)
2003d8e91e46SDimitry Andric : APInt::getSignedMaxValue(BitWidth);
2004d8e91e46SDimitry Andric }
2005d8e91e46SDimitry Andric
uadd_sat(const APInt & RHS) const2006d8e91e46SDimitry Andric APInt APInt::uadd_sat(const APInt &RHS) const {
2007d8e91e46SDimitry Andric bool Overflow;
2008d8e91e46SDimitry Andric APInt Res = uadd_ov(RHS, Overflow);
2009d8e91e46SDimitry Andric if (!Overflow)
2010d8e91e46SDimitry Andric return Res;
2011d8e91e46SDimitry Andric
2012d8e91e46SDimitry Andric return APInt::getMaxValue(BitWidth);
2013d8e91e46SDimitry Andric }
2014d8e91e46SDimitry Andric
ssub_sat(const APInt & RHS) const2015d8e91e46SDimitry Andric APInt APInt::ssub_sat(const APInt &RHS) const {
2016d8e91e46SDimitry Andric bool Overflow;
2017d8e91e46SDimitry Andric APInt Res = ssub_ov(RHS, Overflow);
2018d8e91e46SDimitry Andric if (!Overflow)
2019d8e91e46SDimitry Andric return Res;
2020d8e91e46SDimitry Andric
2021d8e91e46SDimitry Andric return isNegative() ? APInt::getSignedMinValue(BitWidth)
2022d8e91e46SDimitry Andric : APInt::getSignedMaxValue(BitWidth);
2023d8e91e46SDimitry Andric }
2024d8e91e46SDimitry Andric
usub_sat(const APInt & RHS) const2025d8e91e46SDimitry Andric APInt APInt::usub_sat(const APInt &RHS) const {
2026d8e91e46SDimitry Andric bool Overflow;
2027d8e91e46SDimitry Andric APInt Res = usub_ov(RHS, Overflow);
2028d8e91e46SDimitry Andric if (!Overflow)
2029d8e91e46SDimitry Andric return Res;
2030d8e91e46SDimitry Andric
2031d8e91e46SDimitry Andric return APInt(BitWidth, 0);
2032d8e91e46SDimitry Andric }
2033cf099d11SDimitry Andric
smul_sat(const APInt & RHS) const2034706b4fc4SDimitry Andric APInt APInt::smul_sat(const APInt &RHS) const {
2035706b4fc4SDimitry Andric bool Overflow;
2036706b4fc4SDimitry Andric APInt Res = smul_ov(RHS, Overflow);
2037706b4fc4SDimitry Andric if (!Overflow)
2038706b4fc4SDimitry Andric return Res;
2039706b4fc4SDimitry Andric
2040706b4fc4SDimitry Andric // The result is negative if one and only one of inputs is negative.
2041706b4fc4SDimitry Andric bool ResIsNegative = isNegative() ^ RHS.isNegative();
2042706b4fc4SDimitry Andric
2043706b4fc4SDimitry Andric return ResIsNegative ? APInt::getSignedMinValue(BitWidth)
2044706b4fc4SDimitry Andric : APInt::getSignedMaxValue(BitWidth);
2045706b4fc4SDimitry Andric }
2046706b4fc4SDimitry Andric
umul_sat(const APInt & RHS) const2047706b4fc4SDimitry Andric APInt APInt::umul_sat(const APInt &RHS) const {
2048706b4fc4SDimitry Andric bool Overflow;
2049706b4fc4SDimitry Andric APInt Res = umul_ov(RHS, Overflow);
2050706b4fc4SDimitry Andric if (!Overflow)
2051706b4fc4SDimitry Andric return Res;
2052706b4fc4SDimitry Andric
2053706b4fc4SDimitry Andric return APInt::getMaxValue(BitWidth);
2054706b4fc4SDimitry Andric }
2055706b4fc4SDimitry Andric
sshl_sat(const APInt & RHS) const2056706b4fc4SDimitry Andric APInt APInt::sshl_sat(const APInt &RHS) const {
20577fa27ce4SDimitry Andric return sshl_sat(RHS.getLimitedValue(getBitWidth()));
20587fa27ce4SDimitry Andric }
20597fa27ce4SDimitry Andric
sshl_sat(unsigned RHS) const20607fa27ce4SDimitry Andric APInt APInt::sshl_sat(unsigned RHS) const {
2061706b4fc4SDimitry Andric bool Overflow;
2062706b4fc4SDimitry Andric APInt Res = sshl_ov(RHS, Overflow);
2063706b4fc4SDimitry Andric if (!Overflow)
2064706b4fc4SDimitry Andric return Res;
2065706b4fc4SDimitry Andric
2066706b4fc4SDimitry Andric return isNegative() ? APInt::getSignedMinValue(BitWidth)
2067706b4fc4SDimitry Andric : APInt::getSignedMaxValue(BitWidth);
2068706b4fc4SDimitry Andric }
2069706b4fc4SDimitry Andric
ushl_sat(const APInt & RHS) const2070706b4fc4SDimitry Andric APInt APInt::ushl_sat(const APInt &RHS) const {
20717fa27ce4SDimitry Andric return ushl_sat(RHS.getLimitedValue(getBitWidth()));
20727fa27ce4SDimitry Andric }
20737fa27ce4SDimitry Andric
ushl_sat(unsigned RHS) const20747fa27ce4SDimitry Andric APInt APInt::ushl_sat(unsigned RHS) const {
2075706b4fc4SDimitry Andric bool Overflow;
2076706b4fc4SDimitry Andric APInt Res = ushl_ov(RHS, Overflow);
2077706b4fc4SDimitry Andric if (!Overflow)
2078706b4fc4SDimitry Andric return Res;
2079706b4fc4SDimitry Andric
2080706b4fc4SDimitry Andric return APInt::getMaxValue(BitWidth);
2081706b4fc4SDimitry Andric }
2082cf099d11SDimitry Andric
fromString(unsigned numbits,StringRef str,uint8_t radix)2083f3d15b0bSRoman Divacky void APInt::fromString(unsigned numbits, StringRef str, uint8_t radix) {
2084009b1c42SEd Schouten // Check our assumptions here
208559850d08SRoman Divacky assert(!str.empty() && "Invalid string length");
208630815c53SDimitry Andric assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 ||
208730815c53SDimitry Andric radix == 36) &&
208830815c53SDimitry Andric "Radix should be 2, 8, 10, 16, or 36!");
208959850d08SRoman Divacky
209059850d08SRoman Divacky StringRef::iterator p = str.begin();
209159850d08SRoman Divacky size_t slen = str.size();
209259850d08SRoman Divacky bool isNeg = *p == '-';
209359850d08SRoman Divacky if (*p == '-' || *p == '+') {
209459850d08SRoman Divacky p++;
209559850d08SRoman Divacky slen--;
209659850d08SRoman Divacky assert(slen && "String is only a sign, needs a value.");
209759850d08SRoman Divacky }
2098009b1c42SEd Schouten assert((slen <= numbits || radix != 2) && "Insufficient bit width");
2099009b1c42SEd Schouten assert(((slen-1)*3 <= numbits || radix != 8) && "Insufficient bit width");
2100009b1c42SEd Schouten assert(((slen-1)*4 <= numbits || radix != 16) && "Insufficient bit width");
2101104bd817SRoman Divacky assert((((slen-1)*64)/22 <= numbits || radix != 10) &&
2102104bd817SRoman Divacky "Insufficient bit width");
2103009b1c42SEd Schouten
2104148779dfSDimitry Andric // Allocate memory if needed
2105148779dfSDimitry Andric if (isSingleWord())
2106148779dfSDimitry Andric U.VAL = 0;
2107148779dfSDimitry Andric else
2108148779dfSDimitry Andric U.pVal = getClearedMemory(getNumWords());
2109009b1c42SEd Schouten
2110009b1c42SEd Schouten // Figure out if we can shift instead of multiply
2111009b1c42SEd Schouten unsigned shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0);
2112009b1c42SEd Schouten
2113009b1c42SEd Schouten // Enter digit traversal loop
211459850d08SRoman Divacky for (StringRef::iterator e = str.end(); p != e; ++p) {
211559850d08SRoman Divacky unsigned digit = getDigit(*p, radix);
211659850d08SRoman Divacky assert(digit < radix && "Invalid character in digit string");
2117009b1c42SEd Schouten
2118009b1c42SEd Schouten // Shift or multiply the value by the radix
2119009b1c42SEd Schouten if (slen > 1) {
2120009b1c42SEd Schouten if (shift)
2121009b1c42SEd Schouten *this <<= shift;
2122009b1c42SEd Schouten else
2123c46e6a59SDimitry Andric *this *= radix;
2124009b1c42SEd Schouten }
2125009b1c42SEd Schouten
2126009b1c42SEd Schouten // Add in the digit we just interpreted
212771d5a254SDimitry Andric *this += digit;
2128009b1c42SEd Schouten }
2129009b1c42SEd Schouten // If its negative, put it in two's complement form
21306b3f41edSDimitry Andric if (isNeg)
21316b3f41edSDimitry Andric this->negate();
2132009b1c42SEd Schouten }
2133009b1c42SEd Schouten
toString(SmallVectorImpl<char> & Str,unsigned Radix,bool Signed,bool formatAsCLiteral,bool UpperCase,bool InsertSeparators) const21347fa27ce4SDimitry Andric void APInt::toString(SmallVectorImpl<char> &Str, unsigned Radix, bool Signed,
2135ac9a064cSDimitry Andric bool formatAsCLiteral, bool UpperCase,
2136ac9a064cSDimitry Andric bool InsertSeparators) const {
213730815c53SDimitry Andric assert((Radix == 10 || Radix == 8 || Radix == 16 || Radix == 2 ||
213830815c53SDimitry Andric Radix == 36) &&
213963faed5bSDimitry Andric "Radix should be 2, 8, 10, 16, or 36!");
2140009b1c42SEd Schouten
2141411bd29eSDimitry Andric const char *Prefix = "";
2142411bd29eSDimitry Andric if (formatAsCLiteral) {
2143411bd29eSDimitry Andric switch (Radix) {
2144411bd29eSDimitry Andric case 2:
2145411bd29eSDimitry Andric // Binary literals are a non-standard extension added in gcc 4.3:
2146411bd29eSDimitry Andric // http://gcc.gnu.org/onlinedocs/gcc-4.3.0/gcc/Binary-constants.html
2147411bd29eSDimitry Andric Prefix = "0b";
2148411bd29eSDimitry Andric break;
2149411bd29eSDimitry Andric case 8:
2150411bd29eSDimitry Andric Prefix = "0";
2151411bd29eSDimitry Andric break;
215263faed5bSDimitry Andric case 10:
215363faed5bSDimitry Andric break; // No prefix
2154411bd29eSDimitry Andric case 16:
2155411bd29eSDimitry Andric Prefix = "0x";
2156411bd29eSDimitry Andric break;
215763faed5bSDimitry Andric default:
215863faed5bSDimitry Andric llvm_unreachable("Invalid radix!");
2159411bd29eSDimitry Andric }
2160411bd29eSDimitry Andric }
2161411bd29eSDimitry Andric
2162ac9a064cSDimitry Andric // Number of digits in a group between separators.
2163ac9a064cSDimitry Andric unsigned Grouping = (Radix == 8 || Radix == 10) ? 3 : 4;
2164ac9a064cSDimitry Andric
2165009b1c42SEd Schouten // First, check for a zero value and just short circuit the logic below.
2166c0981da4SDimitry Andric if (isZero()) {
2167411bd29eSDimitry Andric while (*Prefix) {
2168411bd29eSDimitry Andric Str.push_back(*Prefix);
2169411bd29eSDimitry Andric ++Prefix;
2170411bd29eSDimitry Andric };
2171009b1c42SEd Schouten Str.push_back('0');
2172009b1c42SEd Schouten return;
2173009b1c42SEd Schouten }
2174009b1c42SEd Schouten
21757fa27ce4SDimitry Andric static const char BothDigits[] = "0123456789abcdefghijklmnopqrstuvwxyz"
21767fa27ce4SDimitry Andric "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
21777fa27ce4SDimitry Andric const char *Digits = BothDigits + (UpperCase ? 36 : 0);
2178009b1c42SEd Schouten
2179009b1c42SEd Schouten if (isSingleWord()) {
2180009b1c42SEd Schouten char Buffer[65];
2181ab44ce3dSDimitry Andric char *BufPtr = std::end(Buffer);
2182009b1c42SEd Schouten
2183009b1c42SEd Schouten uint64_t N;
2184d39c594dSDimitry Andric if (!Signed) {
2185d39c594dSDimitry Andric N = getZExtValue();
2186d39c594dSDimitry Andric } else {
2187009b1c42SEd Schouten int64_t I = getSExtValue();
2188d39c594dSDimitry Andric if (I >= 0) {
2189009b1c42SEd Schouten N = I;
2190009b1c42SEd Schouten } else {
2191d39c594dSDimitry Andric Str.push_back('-');
2192d39c594dSDimitry Andric N = -(uint64_t)I;
2193d39c594dSDimitry Andric }
2194009b1c42SEd Schouten }
2195009b1c42SEd Schouten
2196411bd29eSDimitry Andric while (*Prefix) {
2197411bd29eSDimitry Andric Str.push_back(*Prefix);
2198411bd29eSDimitry Andric ++Prefix;
2199411bd29eSDimitry Andric };
2200411bd29eSDimitry Andric
2201ac9a064cSDimitry Andric int Pos = 0;
2202009b1c42SEd Schouten while (N) {
2203ac9a064cSDimitry Andric if (InsertSeparators && Pos % Grouping == 0 && Pos > 0)
2204ac9a064cSDimitry Andric *--BufPtr = '\'';
2205009b1c42SEd Schouten *--BufPtr = Digits[N % Radix];
2206009b1c42SEd Schouten N /= Radix;
2207ac9a064cSDimitry Andric Pos++;
2208009b1c42SEd Schouten }
2209ab44ce3dSDimitry Andric Str.append(BufPtr, std::end(Buffer));
2210009b1c42SEd Schouten return;
2211009b1c42SEd Schouten }
2212009b1c42SEd Schouten
2213009b1c42SEd Schouten APInt Tmp(*this);
2214009b1c42SEd Schouten
2215009b1c42SEd Schouten if (Signed && isNegative()) {
2216009b1c42SEd Schouten // They want to print the signed version and it is a negative value
2217009b1c42SEd Schouten // Flip the bits and add one to turn it into the equivalent positive
2218009b1c42SEd Schouten // value and put a '-' in the result.
22196b3f41edSDimitry Andric Tmp.negate();
2220009b1c42SEd Schouten Str.push_back('-');
2221009b1c42SEd Schouten }
2222009b1c42SEd Schouten
2223411bd29eSDimitry Andric while (*Prefix) {
2224411bd29eSDimitry Andric Str.push_back(*Prefix);
2225411bd29eSDimitry Andric ++Prefix;
2226411bd29eSDimitry Andric };
2227411bd29eSDimitry Andric
2228009b1c42SEd Schouten // We insert the digits backward, then reverse them to get the right order.
2229009b1c42SEd Schouten unsigned StartDig = Str.size();
2230009b1c42SEd Schouten
2231009b1c42SEd Schouten // For the 2, 8 and 16 bit cases, we can just shift instead of divide
2232009b1c42SEd Schouten // because the number of bits per digit (1, 3 and 4 respectively) divides
223371d5a254SDimitry Andric // equally. We just shift until the value is zero.
223430815c53SDimitry Andric if (Radix == 2 || Radix == 8 || Radix == 16) {
2235009b1c42SEd Schouten // Just shift tmp right for each digit width until it becomes zero
2236009b1c42SEd Schouten unsigned ShiftAmt = (Radix == 16 ? 4 : (Radix == 8 ? 3 : 1));
2237009b1c42SEd Schouten unsigned MaskAmt = Radix - 1;
2238009b1c42SEd Schouten
2239ac9a064cSDimitry Andric int Pos = 0;
22406b3f41edSDimitry Andric while (Tmp.getBoolValue()) {
2241009b1c42SEd Schouten unsigned Digit = unsigned(Tmp.getRawData()[0]) & MaskAmt;
2242ac9a064cSDimitry Andric if (InsertSeparators && Pos % Grouping == 0 && Pos > 0)
2243ac9a064cSDimitry Andric Str.push_back('\'');
2244ac9a064cSDimitry Andric
2245009b1c42SEd Schouten Str.push_back(Digits[Digit]);
2246d99dafe2SDimitry Andric Tmp.lshrInPlace(ShiftAmt);
2247ac9a064cSDimitry Andric Pos++;
2248009b1c42SEd Schouten }
2249009b1c42SEd Schouten } else {
2250ac9a064cSDimitry Andric int Pos = 0;
22516b3f41edSDimitry Andric while (Tmp.getBoolValue()) {
2252b5630dbaSDimitry Andric uint64_t Digit;
2253b5630dbaSDimitry Andric udivrem(Tmp, Radix, Tmp, Digit);
2254009b1c42SEd Schouten assert(Digit < Radix && "divide failed");
2255ac9a064cSDimitry Andric if (InsertSeparators && Pos % Grouping == 0 && Pos > 0)
2256ac9a064cSDimitry Andric Str.push_back('\'');
2257ac9a064cSDimitry Andric
2258009b1c42SEd Schouten Str.push_back(Digits[Digit]);
2259ac9a064cSDimitry Andric Pos++;
2260009b1c42SEd Schouten }
2261009b1c42SEd Schouten }
2262009b1c42SEd Schouten
2263009b1c42SEd Schouten // Reverse the digits before returning.
2264009b1c42SEd Schouten std::reverse(Str.begin()+StartDig, Str.end());
2265009b1c42SEd Schouten }
2266009b1c42SEd Schouten
226771d5a254SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const226801095a5dSDimitry Andric LLVM_DUMP_METHOD void APInt::dump() const {
2269009b1c42SEd Schouten SmallString<40> S, U;
2270009b1c42SEd Schouten this->toStringUnsigned(U);
2271009b1c42SEd Schouten this->toStringSigned(S);
2272829000e0SRoman Divacky dbgs() << "APInt(" << BitWidth << "b, "
227371d5a254SDimitry Andric << U << "u " << S << "s)\n";
2274009b1c42SEd Schouten }
227571d5a254SDimitry Andric #endif
2276009b1c42SEd Schouten
print(raw_ostream & OS,bool isSigned) const2277009b1c42SEd Schouten void APInt::print(raw_ostream &OS, bool isSigned) const {
2278009b1c42SEd Schouten SmallString<40> S;
2279411bd29eSDimitry Andric this->toString(S, 10, isSigned, /* formatAsCLiteral = */false);
22805a5ac124SDimitry Andric OS << S;
228118f153bdSEd Schouten }
228218f153bdSEd Schouten
2283009b1c42SEd Schouten // This implements a variety of operations on a representation of
2284009b1c42SEd Schouten // arbitrary precision, two's-complement, bignum integer values.
2285009b1c42SEd Schouten
228659850d08SRoman Divacky // Assumed by lowHalf, highHalf, partMSB and partLSB. A fairly safe
228759850d08SRoman Divacky // and unrestricting assumption.
228871d5a254SDimitry Andric static_assert(APInt::APINT_BITS_PER_WORD % 2 == 0,
228971d5a254SDimitry Andric "Part width must be divisible by 2!");
2290009b1c42SEd Schouten
2291c0981da4SDimitry Andric // Returns the integer part with the least significant BITS set.
2292c0981da4SDimitry Andric // BITS cannot be zero.
lowBitMask(unsigned bits)229371d5a254SDimitry Andric static inline APInt::WordType lowBitMask(unsigned bits) {
229471d5a254SDimitry Andric assert(bits != 0 && bits <= APInt::APINT_BITS_PER_WORD);
229571d5a254SDimitry Andric return ~(APInt::WordType) 0 >> (APInt::APINT_BITS_PER_WORD - bits);
2296009b1c42SEd Schouten }
2297009b1c42SEd Schouten
2298c0981da4SDimitry Andric /// Returns the value of the lower half of PART.
lowHalf(APInt::WordType part)229971d5a254SDimitry Andric static inline APInt::WordType lowHalf(APInt::WordType part) {
230071d5a254SDimitry Andric return part & lowBitMask(APInt::APINT_BITS_PER_WORD / 2);
2301009b1c42SEd Schouten }
2302009b1c42SEd Schouten
2303c0981da4SDimitry Andric /// Returns the value of the upper half of PART.
highHalf(APInt::WordType part)230471d5a254SDimitry Andric static inline APInt::WordType highHalf(APInt::WordType part) {
230571d5a254SDimitry Andric return part >> (APInt::APINT_BITS_PER_WORD / 2);
2306009b1c42SEd Schouten }
2307009b1c42SEd Schouten
2308c0981da4SDimitry Andric /// Sets the least significant part of a bignum to the input value, and zeroes
2309c0981da4SDimitry Andric /// out higher parts.
tcSet(WordType * dst,WordType part,unsigned parts)231071d5a254SDimitry Andric void APInt::tcSet(WordType *dst, WordType part, unsigned parts) {
2311009b1c42SEd Schouten assert(parts > 0);
2312009b1c42SEd Schouten dst[0] = part;
231371d5a254SDimitry Andric for (unsigned i = 1; i < parts; i++)
2314009b1c42SEd Schouten dst[i] = 0;
2315009b1c42SEd Schouten }
2316009b1c42SEd Schouten
2317c0981da4SDimitry Andric /// Assign one bignum to another.
tcAssign(WordType * dst,const WordType * src,unsigned parts)231871d5a254SDimitry Andric void APInt::tcAssign(WordType *dst, const WordType *src, unsigned parts) {
231971d5a254SDimitry Andric for (unsigned i = 0; i < parts; i++)
2320009b1c42SEd Schouten dst[i] = src[i];
2321009b1c42SEd Schouten }
2322009b1c42SEd Schouten
2323c0981da4SDimitry Andric /// Returns true if a bignum is zero, false otherwise.
tcIsZero(const WordType * src,unsigned parts)232471d5a254SDimitry Andric bool APInt::tcIsZero(const WordType *src, unsigned parts) {
232571d5a254SDimitry Andric for (unsigned i = 0; i < parts; i++)
2326009b1c42SEd Schouten if (src[i])
2327009b1c42SEd Schouten return false;
2328009b1c42SEd Schouten
2329009b1c42SEd Schouten return true;
2330009b1c42SEd Schouten }
2331009b1c42SEd Schouten
2332c0981da4SDimitry Andric /// Extract the given bit of a bignum; returns 0 or 1.
tcExtractBit(const WordType * parts,unsigned bit)233371d5a254SDimitry Andric int APInt::tcExtractBit(const WordType *parts, unsigned bit) {
233471d5a254SDimitry Andric return (parts[whichWord(bit)] & maskBit(bit)) != 0;
2335009b1c42SEd Schouten }
2336009b1c42SEd Schouten
2337c0981da4SDimitry Andric /// Set the given bit of a bignum.
tcSetBit(WordType * parts,unsigned bit)233871d5a254SDimitry Andric void APInt::tcSetBit(WordType *parts, unsigned bit) {
233971d5a254SDimitry Andric parts[whichWord(bit)] |= maskBit(bit);
234067a71b31SRoman Divacky }
234167a71b31SRoman Divacky
2342c0981da4SDimitry Andric /// Clears the given bit of a bignum.
tcClearBit(WordType * parts,unsigned bit)234371d5a254SDimitry Andric void APInt::tcClearBit(WordType *parts, unsigned bit) {
234471d5a254SDimitry Andric parts[whichWord(bit)] &= ~maskBit(bit);
2345009b1c42SEd Schouten }
2346009b1c42SEd Schouten
2347c0981da4SDimitry Andric /// Returns the bit number of the least significant set bit of a number. If the
23487fa27ce4SDimitry Andric /// input number has no bits set UINT_MAX is returned.
tcLSB(const WordType * parts,unsigned n)234971d5a254SDimitry Andric unsigned APInt::tcLSB(const WordType *parts, unsigned n) {
235071d5a254SDimitry Andric for (unsigned i = 0; i < n; i++) {
2351009b1c42SEd Schouten if (parts[i] != 0) {
23527fa27ce4SDimitry Andric unsigned lsb = llvm::countr_zero(parts[i]);
235371d5a254SDimitry Andric return lsb + i * APINT_BITS_PER_WORD;
2354009b1c42SEd Schouten }
2355009b1c42SEd Schouten }
2356009b1c42SEd Schouten
23577fa27ce4SDimitry Andric return UINT_MAX;
2358009b1c42SEd Schouten }
2359009b1c42SEd Schouten
2360c0981da4SDimitry Andric /// Returns the bit number of the most significant set bit of a number.
23617fa27ce4SDimitry Andric /// If the input number has no bits set UINT_MAX is returned.
tcMSB(const WordType * parts,unsigned n)236271d5a254SDimitry Andric unsigned APInt::tcMSB(const WordType *parts, unsigned n) {
2363009b1c42SEd Schouten do {
2364009b1c42SEd Schouten --n;
2365009b1c42SEd Schouten
2366009b1c42SEd Schouten if (parts[n] != 0) {
23677fa27ce4SDimitry Andric static_assert(sizeof(parts[n]) <= sizeof(uint64_t));
23687fa27ce4SDimitry Andric unsigned msb = llvm::Log2_64(parts[n]);
2369009b1c42SEd Schouten
237071d5a254SDimitry Andric return msb + n * APINT_BITS_PER_WORD;
2371009b1c42SEd Schouten }
2372009b1c42SEd Schouten } while (n);
2373009b1c42SEd Schouten
23747fa27ce4SDimitry Andric return UINT_MAX;
2375009b1c42SEd Schouten }
2376009b1c42SEd Schouten
2377c0981da4SDimitry Andric /// Copy the bit vector of width srcBITS from SRC, starting at bit srcLSB, to
2378c0981da4SDimitry Andric /// DST, of dstCOUNT parts, such that the bit srcLSB becomes the least
2379c0981da4SDimitry Andric /// significant bit of DST. All high bits above srcBITS in DST are zero-filled.
2380c0981da4SDimitry Andric /// */
2381009b1c42SEd Schouten void
tcExtract(WordType * dst,unsigned dstCount,const WordType * src,unsigned srcBits,unsigned srcLSB)238271d5a254SDimitry Andric APInt::tcExtract(WordType *dst, unsigned dstCount, const WordType *src,
238371d5a254SDimitry Andric unsigned srcBits, unsigned srcLSB) {
238471d5a254SDimitry Andric unsigned dstParts = (srcBits + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
2385009b1c42SEd Schouten assert(dstParts <= dstCount);
2386009b1c42SEd Schouten
238771d5a254SDimitry Andric unsigned firstSrcPart = srcLSB / APINT_BITS_PER_WORD;
2388009b1c42SEd Schouten tcAssign(dst, src + firstSrcPart, dstParts);
2389009b1c42SEd Schouten
239071d5a254SDimitry Andric unsigned shift = srcLSB % APINT_BITS_PER_WORD;
2391009b1c42SEd Schouten tcShiftRight(dst, dstParts, shift);
2392009b1c42SEd Schouten
2393c0981da4SDimitry Andric // We now have (dstParts * APINT_BITS_PER_WORD - shift) bits from SRC
2394c0981da4SDimitry Andric // in DST. If this is less that srcBits, append the rest, else
2395c0981da4SDimitry Andric // clear the high bits.
239671d5a254SDimitry Andric unsigned n = dstParts * APINT_BITS_PER_WORD - shift;
2397009b1c42SEd Schouten if (n < srcBits) {
239871d5a254SDimitry Andric WordType mask = lowBitMask (srcBits - n);
2399009b1c42SEd Schouten dst[dstParts - 1] |= ((src[firstSrcPart + dstParts] & mask)
240071d5a254SDimitry Andric << n % APINT_BITS_PER_WORD);
2401009b1c42SEd Schouten } else if (n > srcBits) {
240271d5a254SDimitry Andric if (srcBits % APINT_BITS_PER_WORD)
240371d5a254SDimitry Andric dst[dstParts - 1] &= lowBitMask (srcBits % APINT_BITS_PER_WORD);
2404009b1c42SEd Schouten }
2405009b1c42SEd Schouten
2406c0981da4SDimitry Andric // Clear high parts.
2407009b1c42SEd Schouten while (dstParts < dstCount)
2408009b1c42SEd Schouten dst[dstParts++] = 0;
2409009b1c42SEd Schouten }
2410009b1c42SEd Schouten
2411c0981da4SDimitry Andric //// DST += RHS + C where C is zero or one. Returns the carry flag.
tcAdd(WordType * dst,const WordType * rhs,WordType c,unsigned parts)241271d5a254SDimitry Andric APInt::WordType APInt::tcAdd(WordType *dst, const WordType *rhs,
241371d5a254SDimitry Andric WordType c, unsigned parts) {
2414009b1c42SEd Schouten assert(c <= 1);
2415009b1c42SEd Schouten
241671d5a254SDimitry Andric for (unsigned i = 0; i < parts; i++) {
241771d5a254SDimitry Andric WordType l = dst[i];
2418009b1c42SEd Schouten if (c) {
2419009b1c42SEd Schouten dst[i] += rhs[i] + 1;
2420009b1c42SEd Schouten c = (dst[i] <= l);
2421009b1c42SEd Schouten } else {
2422009b1c42SEd Schouten dst[i] += rhs[i];
2423009b1c42SEd Schouten c = (dst[i] < l);
2424009b1c42SEd Schouten }
2425009b1c42SEd Schouten }
2426009b1c42SEd Schouten
2427009b1c42SEd Schouten return c;
2428009b1c42SEd Schouten }
2429009b1c42SEd Schouten
243071d5a254SDimitry Andric /// This function adds a single "word" integer, src, to the multiple
243171d5a254SDimitry Andric /// "word" integer array, dst[]. dst[] is modified to reflect the addition and
243271d5a254SDimitry Andric /// 1 is returned if there is a carry out, otherwise 0 is returned.
243371d5a254SDimitry Andric /// @returns the carry of the addition.
tcAddPart(WordType * dst,WordType src,unsigned parts)243471d5a254SDimitry Andric APInt::WordType APInt::tcAddPart(WordType *dst, WordType src,
243571d5a254SDimitry Andric unsigned parts) {
243671d5a254SDimitry Andric for (unsigned i = 0; i < parts; ++i) {
243771d5a254SDimitry Andric dst[i] += src;
243871d5a254SDimitry Andric if (dst[i] >= src)
243971d5a254SDimitry Andric return 0; // No need to carry so exit early.
244071d5a254SDimitry Andric src = 1; // Carry one to next digit.
244171d5a254SDimitry Andric }
2442009b1c42SEd Schouten
244371d5a254SDimitry Andric return 1;
244471d5a254SDimitry Andric }
244571d5a254SDimitry Andric
2446c0981da4SDimitry Andric /// DST -= RHS + C where C is zero or one. Returns the carry flag.
tcSubtract(WordType * dst,const WordType * rhs,WordType c,unsigned parts)244771d5a254SDimitry Andric APInt::WordType APInt::tcSubtract(WordType *dst, const WordType *rhs,
244871d5a254SDimitry Andric WordType c, unsigned parts) {
2449009b1c42SEd Schouten assert(c <= 1);
2450009b1c42SEd Schouten
245171d5a254SDimitry Andric for (unsigned i = 0; i < parts; i++) {
245271d5a254SDimitry Andric WordType l = dst[i];
2453009b1c42SEd Schouten if (c) {
2454009b1c42SEd Schouten dst[i] -= rhs[i] + 1;
2455009b1c42SEd Schouten c = (dst[i] >= l);
2456009b1c42SEd Schouten } else {
2457009b1c42SEd Schouten dst[i] -= rhs[i];
2458009b1c42SEd Schouten c = (dst[i] > l);
2459009b1c42SEd Schouten }
2460009b1c42SEd Schouten }
2461009b1c42SEd Schouten
2462009b1c42SEd Schouten return c;
2463009b1c42SEd Schouten }
2464009b1c42SEd Schouten
246571d5a254SDimitry Andric /// This function subtracts a single "word" (64-bit word), src, from
246671d5a254SDimitry Andric /// the multi-word integer array, dst[], propagating the borrowed 1 value until
246771d5a254SDimitry Andric /// no further borrowing is needed or it runs out of "words" in dst. The result
246871d5a254SDimitry Andric /// is 1 if "borrowing" exhausted the digits in dst, or 0 if dst was not
246971d5a254SDimitry Andric /// exhausted. In other words, if src > dst then this function returns 1,
247071d5a254SDimitry Andric /// otherwise 0.
247171d5a254SDimitry Andric /// @returns the borrow out of the subtraction
tcSubtractPart(WordType * dst,WordType src,unsigned parts)247271d5a254SDimitry Andric APInt::WordType APInt::tcSubtractPart(WordType *dst, WordType src,
247371d5a254SDimitry Andric unsigned parts) {
247471d5a254SDimitry Andric for (unsigned i = 0; i < parts; ++i) {
247571d5a254SDimitry Andric WordType Dst = dst[i];
247671d5a254SDimitry Andric dst[i] -= src;
247771d5a254SDimitry Andric if (src <= Dst)
247871d5a254SDimitry Andric return 0; // No need to borrow so exit early.
247971d5a254SDimitry Andric src = 1; // We have to "borrow 1" from next "word"
248071d5a254SDimitry Andric }
248171d5a254SDimitry Andric
248271d5a254SDimitry Andric return 1;
248371d5a254SDimitry Andric }
248471d5a254SDimitry Andric
2485c0981da4SDimitry Andric /// Negate a bignum in-place.
tcNegate(WordType * dst,unsigned parts)248671d5a254SDimitry Andric void APInt::tcNegate(WordType *dst, unsigned parts) {
2487009b1c42SEd Schouten tcComplement(dst, parts);
2488009b1c42SEd Schouten tcIncrement(dst, parts);
2489009b1c42SEd Schouten }
2490009b1c42SEd Schouten
2491c0981da4SDimitry Andric /// DST += SRC * MULTIPLIER + CARRY if add is true
2492c0981da4SDimitry Andric /// DST = SRC * MULTIPLIER + CARRY if add is false
2493c0981da4SDimitry Andric /// Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC
2494c0981da4SDimitry Andric /// they must start at the same point, i.e. DST == SRC.
2495c0981da4SDimitry Andric /// If DSTPARTS == SRCPARTS + 1 no overflow occurs and zero is
2496c0981da4SDimitry Andric /// returned. Otherwise DST is filled with the least significant
2497c0981da4SDimitry Andric /// DSTPARTS parts of the result, and if all of the omitted higher
2498c0981da4SDimitry Andric /// parts were zero return zero, otherwise overflow occurred and
2499c0981da4SDimitry Andric /// return one.
tcMultiplyPart(WordType * dst,const WordType * src,WordType multiplier,WordType carry,unsigned srcParts,unsigned dstParts,bool add)250071d5a254SDimitry Andric int APInt::tcMultiplyPart(WordType *dst, const WordType *src,
250171d5a254SDimitry Andric WordType multiplier, WordType carry,
250271d5a254SDimitry Andric unsigned srcParts, unsigned dstParts,
250371d5a254SDimitry Andric bool add) {
2504c0981da4SDimitry Andric // Otherwise our writes of DST kill our later reads of SRC.
2505009b1c42SEd Schouten assert(dst <= src || dst >= src + srcParts);
2506009b1c42SEd Schouten assert(dstParts <= srcParts + 1);
2507009b1c42SEd Schouten
2508c0981da4SDimitry Andric // N loops; minimum of dstParts and srcParts.
2509c46e6a59SDimitry Andric unsigned n = std::min(dstParts, srcParts);
2510009b1c42SEd Schouten
2511c46e6a59SDimitry Andric for (unsigned i = 0; i < n; i++) {
2512c0981da4SDimitry Andric // [LOW, HIGH] = MULTIPLIER * SRC[i] + DST[i] + CARRY.
2513c0981da4SDimitry Andric // This cannot overflow, because:
2514c0981da4SDimitry Andric // (n - 1) * (n - 1) + 2 (n - 1) = (n - 1) * (n + 1)
2515c0981da4SDimitry Andric // which is less than n^2.
2516c0981da4SDimitry Andric WordType srcPart = src[i];
2517c0981da4SDimitry Andric WordType low, mid, high;
2518009b1c42SEd Schouten if (multiplier == 0 || srcPart == 0) {
2519009b1c42SEd Schouten low = carry;
2520009b1c42SEd Schouten high = 0;
2521009b1c42SEd Schouten } else {
2522009b1c42SEd Schouten low = lowHalf(srcPart) * lowHalf(multiplier);
2523009b1c42SEd Schouten high = highHalf(srcPart) * highHalf(multiplier);
2524009b1c42SEd Schouten
2525009b1c42SEd Schouten mid = lowHalf(srcPart) * highHalf(multiplier);
2526009b1c42SEd Schouten high += highHalf(mid);
252771d5a254SDimitry Andric mid <<= APINT_BITS_PER_WORD / 2;
2528009b1c42SEd Schouten if (low + mid < low)
2529009b1c42SEd Schouten high++;
2530009b1c42SEd Schouten low += mid;
2531009b1c42SEd Schouten
2532009b1c42SEd Schouten mid = highHalf(srcPart) * lowHalf(multiplier);
2533009b1c42SEd Schouten high += highHalf(mid);
253471d5a254SDimitry Andric mid <<= APINT_BITS_PER_WORD / 2;
2535009b1c42SEd Schouten if (low + mid < low)
2536009b1c42SEd Schouten high++;
2537009b1c42SEd Schouten low += mid;
2538009b1c42SEd Schouten
2539c0981da4SDimitry Andric // Now add carry.
2540009b1c42SEd Schouten if (low + carry < low)
2541009b1c42SEd Schouten high++;
2542009b1c42SEd Schouten low += carry;
2543009b1c42SEd Schouten }
2544009b1c42SEd Schouten
2545009b1c42SEd Schouten if (add) {
2546c0981da4SDimitry Andric // And now DST[i], and store the new low part there.
2547009b1c42SEd Schouten if (low + dst[i] < low)
2548009b1c42SEd Schouten high++;
2549009b1c42SEd Schouten dst[i] += low;
2550009b1c42SEd Schouten } else
2551009b1c42SEd Schouten dst[i] = low;
2552009b1c42SEd Schouten
2553009b1c42SEd Schouten carry = high;
2554009b1c42SEd Schouten }
2555009b1c42SEd Schouten
2556c46e6a59SDimitry Andric if (srcParts < dstParts) {
2557c0981da4SDimitry Andric // Full multiplication, there is no overflow.
2558c46e6a59SDimitry Andric assert(srcParts + 1 == dstParts);
2559c46e6a59SDimitry Andric dst[srcParts] = carry;
2560009b1c42SEd Schouten return 0;
2561c46e6a59SDimitry Andric }
2562c46e6a59SDimitry Andric
2563c0981da4SDimitry Andric // We overflowed if there is carry.
2564009b1c42SEd Schouten if (carry)
2565009b1c42SEd Schouten return 1;
2566009b1c42SEd Schouten
2567c0981da4SDimitry Andric // We would overflow if any significant unwritten parts would be
2568c0981da4SDimitry Andric // non-zero. This is true if any remaining src parts are non-zero
2569c0981da4SDimitry Andric // and the multiplier is non-zero.
2570009b1c42SEd Schouten if (multiplier)
2571c46e6a59SDimitry Andric for (unsigned i = dstParts; i < srcParts; i++)
2572009b1c42SEd Schouten if (src[i])
2573009b1c42SEd Schouten return 1;
2574009b1c42SEd Schouten
2575c0981da4SDimitry Andric // We fitted in the narrow destination.
2576009b1c42SEd Schouten return 0;
2577009b1c42SEd Schouten }
2578009b1c42SEd Schouten
2579c0981da4SDimitry Andric /// DST = LHS * RHS, where DST has the same width as the operands and
2580c0981da4SDimitry Andric /// is filled with the least significant parts of the result. Returns
2581c0981da4SDimitry Andric /// one if overflow occurred, otherwise zero. DST must be disjoint
2582c0981da4SDimitry Andric /// from both operands.
tcMultiply(WordType * dst,const WordType * lhs,const WordType * rhs,unsigned parts)258371d5a254SDimitry Andric int APInt::tcMultiply(WordType *dst, const WordType *lhs,
258471d5a254SDimitry Andric const WordType *rhs, unsigned parts) {
2585009b1c42SEd Schouten assert(dst != lhs && dst != rhs);
2586009b1c42SEd Schouten
258771d5a254SDimitry Andric int overflow = 0;
2588009b1c42SEd Schouten
2589ac9a064cSDimitry Andric for (unsigned i = 0; i < parts; i++) {
2590ac9a064cSDimitry Andric // Don't accumulate on the first iteration so we don't need to initalize
2591ac9a064cSDimitry Andric // dst to 0.
2592ac9a064cSDimitry Andric overflow |=
2593ac9a064cSDimitry Andric tcMultiplyPart(&dst[i], lhs, rhs[i], 0, parts, parts - i, i != 0);
2594ac9a064cSDimitry Andric }
2595009b1c42SEd Schouten
2596009b1c42SEd Schouten return overflow;
2597009b1c42SEd Schouten }
2598009b1c42SEd Schouten
25996b3f41edSDimitry Andric /// DST = LHS * RHS, where DST has width the sum of the widths of the
26006b3f41edSDimitry Andric /// operands. No overflow occurs. DST must be disjoint from both operands.
tcFullMultiply(WordType * dst,const WordType * lhs,const WordType * rhs,unsigned lhsParts,unsigned rhsParts)26016b3f41edSDimitry Andric void APInt::tcFullMultiply(WordType *dst, const WordType *lhs,
260271d5a254SDimitry Andric const WordType *rhs, unsigned lhsParts,
260371d5a254SDimitry Andric unsigned rhsParts) {
2604c0981da4SDimitry Andric // Put the narrower number on the LHS for less loops below.
2605c46e6a59SDimitry Andric if (lhsParts > rhsParts)
2606009b1c42SEd Schouten return tcFullMultiply (dst, rhs, lhs, rhsParts, lhsParts);
2607c46e6a59SDimitry Andric
2608009b1c42SEd Schouten assert(dst != lhs && dst != rhs);
2609009b1c42SEd Schouten
2610ac9a064cSDimitry Andric for (unsigned i = 0; i < lhsParts; i++) {
2611ac9a064cSDimitry Andric // Don't accumulate on the first iteration so we don't need to initalize
2612ac9a064cSDimitry Andric // dst to 0.
2613ac9a064cSDimitry Andric tcMultiplyPart(&dst[i], rhs, lhs[i], 0, rhsParts, rhsParts + 1, i != 0);
2614ac9a064cSDimitry Andric }
2615009b1c42SEd Schouten }
2616009b1c42SEd Schouten
2617c0981da4SDimitry Andric // If RHS is zero LHS and REMAINDER are left unchanged, return one.
2618c0981da4SDimitry Andric // Otherwise set LHS to LHS / RHS with the fractional part discarded,
2619c0981da4SDimitry Andric // set REMAINDER to the remainder, return zero. i.e.
2620c0981da4SDimitry Andric //
2621c0981da4SDimitry Andric // OLD_LHS = RHS * LHS + REMAINDER
2622c0981da4SDimitry Andric //
2623c0981da4SDimitry Andric // SCRATCH is a bignum of the same size as the operands and result for
2624c0981da4SDimitry Andric // use by the routine; its contents need not be initialized and are
2625c0981da4SDimitry Andric // destroyed. LHS, REMAINDER and SCRATCH must be distinct.
tcDivide(WordType * lhs,const WordType * rhs,WordType * remainder,WordType * srhs,unsigned parts)262671d5a254SDimitry Andric int APInt::tcDivide(WordType *lhs, const WordType *rhs,
262771d5a254SDimitry Andric WordType *remainder, WordType *srhs,
262871d5a254SDimitry Andric unsigned parts) {
2629009b1c42SEd Schouten assert(lhs != remainder && lhs != srhs && remainder != srhs);
2630009b1c42SEd Schouten
263171d5a254SDimitry Andric unsigned shiftCount = tcMSB(rhs, parts) + 1;
2632009b1c42SEd Schouten if (shiftCount == 0)
2633009b1c42SEd Schouten return true;
2634009b1c42SEd Schouten
263571d5a254SDimitry Andric shiftCount = parts * APINT_BITS_PER_WORD - shiftCount;
263671d5a254SDimitry Andric unsigned n = shiftCount / APINT_BITS_PER_WORD;
263771d5a254SDimitry Andric WordType mask = (WordType) 1 << (shiftCount % APINT_BITS_PER_WORD);
2638009b1c42SEd Schouten
2639009b1c42SEd Schouten tcAssign(srhs, rhs, parts);
2640009b1c42SEd Schouten tcShiftLeft(srhs, parts, shiftCount);
2641009b1c42SEd Schouten tcAssign(remainder, lhs, parts);
2642009b1c42SEd Schouten tcSet(lhs, 0, parts);
2643009b1c42SEd Schouten
2644c0981da4SDimitry Andric // Loop, subtracting SRHS if REMAINDER is greater and adding that to the
2645c0981da4SDimitry Andric // total.
2646009b1c42SEd Schouten for (;;) {
26476b3f41edSDimitry Andric int compare = tcCompare(remainder, srhs, parts);
2648009b1c42SEd Schouten if (compare >= 0) {
2649009b1c42SEd Schouten tcSubtract(remainder, srhs, 0, parts);
2650009b1c42SEd Schouten lhs[n] |= mask;
2651009b1c42SEd Schouten }
2652009b1c42SEd Schouten
2653009b1c42SEd Schouten if (shiftCount == 0)
2654009b1c42SEd Schouten break;
2655009b1c42SEd Schouten shiftCount--;
2656009b1c42SEd Schouten tcShiftRight(srhs, parts, 1);
265701095a5dSDimitry Andric if ((mask >>= 1) == 0) {
265871d5a254SDimitry Andric mask = (WordType) 1 << (APINT_BITS_PER_WORD - 1);
265901095a5dSDimitry Andric n--;
266001095a5dSDimitry Andric }
2661009b1c42SEd Schouten }
2662009b1c42SEd Schouten
2663009b1c42SEd Schouten return false;
2664009b1c42SEd Schouten }
2665009b1c42SEd Schouten
2666ac9a064cSDimitry Andric /// Shift a bignum left Count bits in-place. Shifted in bits are zero. There are
2667d99dafe2SDimitry Andric /// no restrictions on Count.
tcShiftLeft(WordType * Dst,unsigned Words,unsigned Count)2668d99dafe2SDimitry Andric void APInt::tcShiftLeft(WordType *Dst, unsigned Words, unsigned Count) {
2669d99dafe2SDimitry Andric // Don't bother performing a no-op shift.
2670d99dafe2SDimitry Andric if (!Count)
2671d99dafe2SDimitry Andric return;
2672009b1c42SEd Schouten
267312f3ca4cSDimitry Andric // WordShift is the inter-part shift; BitShift is the intra-part shift.
2674d99dafe2SDimitry Andric unsigned WordShift = std::min(Count / APINT_BITS_PER_WORD, Words);
2675d99dafe2SDimitry Andric unsigned BitShift = Count % APINT_BITS_PER_WORD;
2676009b1c42SEd Schouten
2677d99dafe2SDimitry Andric // Fastpath for moving by whole words.
2678d99dafe2SDimitry Andric if (BitShift == 0) {
2679d99dafe2SDimitry Andric std::memmove(Dst + WordShift, Dst, (Words - WordShift) * APINT_WORD_SIZE);
2680009b1c42SEd Schouten } else {
2681d99dafe2SDimitry Andric while (Words-- > WordShift) {
2682d99dafe2SDimitry Andric Dst[Words] = Dst[Words - WordShift] << BitShift;
2683d99dafe2SDimitry Andric if (Words > WordShift)
2684d99dafe2SDimitry Andric Dst[Words] |=
2685d99dafe2SDimitry Andric Dst[Words - WordShift - 1] >> (APINT_BITS_PER_WORD - BitShift);
2686009b1c42SEd Schouten }
2687009b1c42SEd Schouten }
2688009b1c42SEd Schouten
2689d99dafe2SDimitry Andric // Fill in the remainder with 0s.
2690d99dafe2SDimitry Andric std::memset(Dst, 0, WordShift * APINT_WORD_SIZE);
2691d99dafe2SDimitry Andric }
2692d99dafe2SDimitry Andric
2693d99dafe2SDimitry Andric /// Shift a bignum right Count bits in-place. Shifted in bits are zero. There
2694d99dafe2SDimitry Andric /// are no restrictions on Count.
tcShiftRight(WordType * Dst,unsigned Words,unsigned Count)2695d99dafe2SDimitry Andric void APInt::tcShiftRight(WordType *Dst, unsigned Words, unsigned Count) {
2696d99dafe2SDimitry Andric // Don't bother performing a no-op shift.
2697d99dafe2SDimitry Andric if (!Count)
2698d99dafe2SDimitry Andric return;
2699d99dafe2SDimitry Andric
270012f3ca4cSDimitry Andric // WordShift is the inter-part shift; BitShift is the intra-part shift.
2701d99dafe2SDimitry Andric unsigned WordShift = std::min(Count / APINT_BITS_PER_WORD, Words);
2702d99dafe2SDimitry Andric unsigned BitShift = Count % APINT_BITS_PER_WORD;
2703d99dafe2SDimitry Andric
2704d99dafe2SDimitry Andric unsigned WordsToMove = Words - WordShift;
2705d99dafe2SDimitry Andric // Fastpath for moving by whole words.
2706d99dafe2SDimitry Andric if (BitShift == 0) {
2707d99dafe2SDimitry Andric std::memmove(Dst, Dst + WordShift, WordsToMove * APINT_WORD_SIZE);
2708d99dafe2SDimitry Andric } else {
2709d99dafe2SDimitry Andric for (unsigned i = 0; i != WordsToMove; ++i) {
2710d99dafe2SDimitry Andric Dst[i] = Dst[i + WordShift] >> BitShift;
2711d99dafe2SDimitry Andric if (i + 1 != WordsToMove)
2712d99dafe2SDimitry Andric Dst[i] |= Dst[i + WordShift + 1] << (APINT_BITS_PER_WORD - BitShift);
2713009b1c42SEd Schouten }
2714009b1c42SEd Schouten }
2715d99dafe2SDimitry Andric
2716d99dafe2SDimitry Andric // Fill in the remainder with 0s.
2717d99dafe2SDimitry Andric std::memset(Dst + WordsToMove, 0, WordShift * APINT_WORD_SIZE);
2718009b1c42SEd Schouten }
2719009b1c42SEd Schouten
2720c0981da4SDimitry Andric // Comparison (unsigned) of two bignums.
tcCompare(const WordType * lhs,const WordType * rhs,unsigned parts)272171d5a254SDimitry Andric int APInt::tcCompare(const WordType *lhs, const WordType *rhs,
272271d5a254SDimitry Andric unsigned parts) {
2723009b1c42SEd Schouten while (parts) {
2724009b1c42SEd Schouten parts--;
272512f3ca4cSDimitry Andric if (lhs[parts] != rhs[parts])
272671d5a254SDimitry Andric return (lhs[parts] > rhs[parts]) ? 1 : -1;
2727009b1c42SEd Schouten }
2728009b1c42SEd Schouten
2729009b1c42SEd Schouten return 0;
2730009b1c42SEd Schouten }
2731009b1c42SEd Schouten
RoundingUDiv(const APInt & A,const APInt & B,APInt::Rounding RM)2732eb11fae6SDimitry Andric APInt llvm::APIntOps::RoundingUDiv(const APInt &A, const APInt &B,
2733eb11fae6SDimitry Andric APInt::Rounding RM) {
2734eb11fae6SDimitry Andric // Currently udivrem always rounds down.
2735eb11fae6SDimitry Andric switch (RM) {
2736eb11fae6SDimitry Andric case APInt::Rounding::DOWN:
2737eb11fae6SDimitry Andric case APInt::Rounding::TOWARD_ZERO:
2738eb11fae6SDimitry Andric return A.udiv(B);
2739eb11fae6SDimitry Andric case APInt::Rounding::UP: {
2740eb11fae6SDimitry Andric APInt Quo, Rem;
2741eb11fae6SDimitry Andric APInt::udivrem(A, B, Quo, Rem);
2742c0981da4SDimitry Andric if (Rem.isZero())
2743eb11fae6SDimitry Andric return Quo;
2744eb11fae6SDimitry Andric return Quo + 1;
2745eb11fae6SDimitry Andric }
2746eb11fae6SDimitry Andric }
2747eb11fae6SDimitry Andric llvm_unreachable("Unknown APInt::Rounding enum");
2748eb11fae6SDimitry Andric }
2749eb11fae6SDimitry Andric
RoundingSDiv(const APInt & A,const APInt & B,APInt::Rounding RM)2750eb11fae6SDimitry Andric APInt llvm::APIntOps::RoundingSDiv(const APInt &A, const APInt &B,
2751eb11fae6SDimitry Andric APInt::Rounding RM) {
2752eb11fae6SDimitry Andric switch (RM) {
2753eb11fae6SDimitry Andric case APInt::Rounding::DOWN:
2754eb11fae6SDimitry Andric case APInt::Rounding::UP: {
2755eb11fae6SDimitry Andric APInt Quo, Rem;
2756eb11fae6SDimitry Andric APInt::sdivrem(A, B, Quo, Rem);
2757c0981da4SDimitry Andric if (Rem.isZero())
2758eb11fae6SDimitry Andric return Quo;
2759eb11fae6SDimitry Andric // This algorithm deals with arbitrary rounding mode used by sdivrem.
2760eb11fae6SDimitry Andric // We want to check whether the non-integer part of the mathematical value
2761eb11fae6SDimitry Andric // is negative or not. If the non-integer part is negative, we need to round
2762eb11fae6SDimitry Andric // down from Quo; otherwise, if it's positive or 0, we return Quo, as it's
2763eb11fae6SDimitry Andric // already rounded down.
2764eb11fae6SDimitry Andric if (RM == APInt::Rounding::DOWN) {
2765eb11fae6SDimitry Andric if (Rem.isNegative() != B.isNegative())
2766eb11fae6SDimitry Andric return Quo - 1;
2767eb11fae6SDimitry Andric return Quo;
2768eb11fae6SDimitry Andric }
2769eb11fae6SDimitry Andric if (Rem.isNegative() != B.isNegative())
2770eb11fae6SDimitry Andric return Quo;
2771eb11fae6SDimitry Andric return Quo + 1;
2772eb11fae6SDimitry Andric }
2773706b4fc4SDimitry Andric // Currently sdiv rounds towards zero.
2774eb11fae6SDimitry Andric case APInt::Rounding::TOWARD_ZERO:
2775eb11fae6SDimitry Andric return A.sdiv(B);
2776eb11fae6SDimitry Andric }
2777eb11fae6SDimitry Andric llvm_unreachable("Unknown APInt::Rounding enum");
2778eb11fae6SDimitry Andric }
2779d8e91e46SDimitry Andric
2780e3b55780SDimitry Andric std::optional<APInt>
SolveQuadraticEquationWrap(APInt A,APInt B,APInt C,unsigned RangeWidth)2781d8e91e46SDimitry Andric llvm::APIntOps::SolveQuadraticEquationWrap(APInt A, APInt B, APInt C,
2782d8e91e46SDimitry Andric unsigned RangeWidth) {
2783d8e91e46SDimitry Andric unsigned CoeffWidth = A.getBitWidth();
2784d8e91e46SDimitry Andric assert(CoeffWidth == B.getBitWidth() && CoeffWidth == C.getBitWidth());
2785d8e91e46SDimitry Andric assert(RangeWidth <= CoeffWidth &&
2786d8e91e46SDimitry Andric "Value range width should be less than coefficient width");
2787d8e91e46SDimitry Andric assert(RangeWidth > 1 && "Value range bit width should be > 1");
2788d8e91e46SDimitry Andric
2789d8e91e46SDimitry Andric LLVM_DEBUG(dbgs() << __func__ << ": solving " << A << "x^2 + " << B
2790d8e91e46SDimitry Andric << "x + " << C << ", rw:" << RangeWidth << '\n');
2791d8e91e46SDimitry Andric
2792d8e91e46SDimitry Andric // Identify 0 as a (non)solution immediately.
2793c0981da4SDimitry Andric if (C.sextOrTrunc(RangeWidth).isZero()) {
2794d8e91e46SDimitry Andric LLVM_DEBUG(dbgs() << __func__ << ": zero solution\n");
2795d8e91e46SDimitry Andric return APInt(CoeffWidth, 0);
2796d8e91e46SDimitry Andric }
2797d8e91e46SDimitry Andric
2798d8e91e46SDimitry Andric // The result of APInt arithmetic has the same bit width as the operands,
2799d8e91e46SDimitry Andric // so it can actually lose high bits. A product of two n-bit integers needs
2800d8e91e46SDimitry Andric // 2n-1 bits to represent the full value.
2801d8e91e46SDimitry Andric // The operation done below (on quadratic coefficients) that can produce
2802d8e91e46SDimitry Andric // the largest value is the evaluation of the equation during bisection,
2803d8e91e46SDimitry Andric // which needs 3 times the bitwidth of the coefficient, so the total number
2804d8e91e46SDimitry Andric // of required bits is 3n.
2805d8e91e46SDimitry Andric //
2806d8e91e46SDimitry Andric // The purpose of this extension is to simulate the set Z of all integers,
2807d8e91e46SDimitry Andric // where n+1 > n for all n in Z. In Z it makes sense to talk about positive
2808d8e91e46SDimitry Andric // and negative numbers (not so much in a modulo arithmetic). The method
2809d8e91e46SDimitry Andric // used to solve the equation is based on the standard formula for real
2810d8e91e46SDimitry Andric // numbers, and uses the concepts of "positive" and "negative" with their
2811d8e91e46SDimitry Andric // usual meanings.
2812d8e91e46SDimitry Andric CoeffWidth *= 3;
2813d8e91e46SDimitry Andric A = A.sext(CoeffWidth);
2814d8e91e46SDimitry Andric B = B.sext(CoeffWidth);
2815d8e91e46SDimitry Andric C = C.sext(CoeffWidth);
2816d8e91e46SDimitry Andric
2817d8e91e46SDimitry Andric // Make A > 0 for simplicity. Negate cannot overflow at this point because
2818d8e91e46SDimitry Andric // the bit width has increased.
2819d8e91e46SDimitry Andric if (A.isNegative()) {
2820d8e91e46SDimitry Andric A.negate();
2821d8e91e46SDimitry Andric B.negate();
2822d8e91e46SDimitry Andric C.negate();
2823d8e91e46SDimitry Andric }
2824d8e91e46SDimitry Andric
2825d8e91e46SDimitry Andric // Solving an equation q(x) = 0 with coefficients in modular arithmetic
2826d8e91e46SDimitry Andric // is really solving a set of equations q(x) = kR for k = 0, 1, 2, ...,
2827d8e91e46SDimitry Andric // and R = 2^BitWidth.
2828d8e91e46SDimitry Andric // Since we're trying not only to find exact solutions, but also values
2829d8e91e46SDimitry Andric // that "wrap around", such a set will always have a solution, i.e. an x
2830d8e91e46SDimitry Andric // that satisfies at least one of the equations, or such that |q(x)|
2831d8e91e46SDimitry Andric // exceeds kR, while |q(x-1)| for the same k does not.
2832d8e91e46SDimitry Andric //
2833d8e91e46SDimitry Andric // We need to find a value k, such that Ax^2 + Bx + C = kR will have a
2834d8e91e46SDimitry Andric // positive solution n (in the above sense), and also such that the n
2835d8e91e46SDimitry Andric // will be the least among all solutions corresponding to k = 0, 1, ...
2836d8e91e46SDimitry Andric // (more precisely, the least element in the set
2837d8e91e46SDimitry Andric // { n(k) | k is such that a solution n(k) exists }).
2838d8e91e46SDimitry Andric //
2839d8e91e46SDimitry Andric // Consider the parabola (over real numbers) that corresponds to the
2840d8e91e46SDimitry Andric // quadratic equation. Since A > 0, the arms of the parabola will point
2841d8e91e46SDimitry Andric // up. Picking different values of k will shift it up and down by R.
2842d8e91e46SDimitry Andric //
2843d8e91e46SDimitry Andric // We want to shift the parabola in such a way as to reduce the problem
2844d8e91e46SDimitry Andric // of solving q(x) = kR to solving shifted_q(x) = 0.
2845d8e91e46SDimitry Andric // (The interesting solutions are the ceilings of the real number
2846d8e91e46SDimitry Andric // solutions.)
2847d8e91e46SDimitry Andric APInt R = APInt::getOneBitSet(CoeffWidth, RangeWidth);
2848d8e91e46SDimitry Andric APInt TwoA = 2 * A;
2849d8e91e46SDimitry Andric APInt SqrB = B * B;
2850d8e91e46SDimitry Andric bool PickLow;
2851d8e91e46SDimitry Andric
2852d8e91e46SDimitry Andric auto RoundUp = [] (const APInt &V, const APInt &A) -> APInt {
2853d8e91e46SDimitry Andric assert(A.isStrictlyPositive());
2854d8e91e46SDimitry Andric APInt T = V.abs().urem(A);
2855c0981da4SDimitry Andric if (T.isZero())
2856d8e91e46SDimitry Andric return V;
2857d8e91e46SDimitry Andric return V.isNegative() ? V+T : V+(A-T);
2858d8e91e46SDimitry Andric };
2859d8e91e46SDimitry Andric
2860d8e91e46SDimitry Andric // The vertex of the parabola is at -B/2A, but since A > 0, it's negative
2861d8e91e46SDimitry Andric // iff B is positive.
2862d8e91e46SDimitry Andric if (B.isNonNegative()) {
2863d8e91e46SDimitry Andric // If B >= 0, the vertex it at a negative location (or at 0), so in
2864d8e91e46SDimitry Andric // order to have a non-negative solution we need to pick k that makes
2865d8e91e46SDimitry Andric // C-kR negative. To satisfy all the requirements for the solution
2866d8e91e46SDimitry Andric // that we are looking for, it needs to be closest to 0 of all k.
2867d8e91e46SDimitry Andric C = C.srem(R);
2868d8e91e46SDimitry Andric if (C.isStrictlyPositive())
2869d8e91e46SDimitry Andric C -= R;
2870d8e91e46SDimitry Andric // Pick the greater solution.
2871d8e91e46SDimitry Andric PickLow = false;
2872d8e91e46SDimitry Andric } else {
2873d8e91e46SDimitry Andric // If B < 0, the vertex is at a positive location. For any solution
2874d8e91e46SDimitry Andric // to exist, the discriminant must be non-negative. This means that
2875d8e91e46SDimitry Andric // C-kR <= B^2/4A is a necessary condition for k, i.e. there is a
2876d8e91e46SDimitry Andric // lower bound on values of k: kR >= C - B^2/4A.
2877d8e91e46SDimitry Andric APInt LowkR = C - SqrB.udiv(2*TwoA); // udiv because all values > 0.
2878d8e91e46SDimitry Andric // Round LowkR up (towards +inf) to the nearest kR.
2879d8e91e46SDimitry Andric LowkR = RoundUp(LowkR, R);
2880d8e91e46SDimitry Andric
2881d8e91e46SDimitry Andric // If there exists k meeting the condition above, and such that
2882d8e91e46SDimitry Andric // C-kR > 0, there will be two positive real number solutions of
2883d8e91e46SDimitry Andric // q(x) = kR. Out of all such values of k, pick the one that makes
2884d8e91e46SDimitry Andric // C-kR closest to 0, (i.e. pick maximum k such that C-kR > 0).
2885d8e91e46SDimitry Andric // In other words, find maximum k such that LowkR <= kR < C.
2886d8e91e46SDimitry Andric if (C.sgt(LowkR)) {
2887d8e91e46SDimitry Andric // If LowkR < C, then such a k is guaranteed to exist because
2888d8e91e46SDimitry Andric // LowkR itself is a multiple of R.
2889d8e91e46SDimitry Andric C -= -RoundUp(-C, R); // C = C - RoundDown(C, R)
2890d8e91e46SDimitry Andric // Pick the smaller solution.
2891d8e91e46SDimitry Andric PickLow = true;
2892d8e91e46SDimitry Andric } else {
2893d8e91e46SDimitry Andric // If C-kR < 0 for all potential k's, it means that one solution
2894d8e91e46SDimitry Andric // will be negative, while the other will be positive. The positive
2895d8e91e46SDimitry Andric // solution will shift towards 0 if the parabola is moved up.
2896d8e91e46SDimitry Andric // Pick the kR closest to the lower bound (i.e. make C-kR closest
2897d8e91e46SDimitry Andric // to 0, or in other words, out of all parabolas that have solutions,
2898d8e91e46SDimitry Andric // pick the one that is the farthest "up").
2899d8e91e46SDimitry Andric // Since LowkR is itself a multiple of R, simply take C-LowkR.
2900d8e91e46SDimitry Andric C -= LowkR;
2901d8e91e46SDimitry Andric // Pick the greater solution.
2902d8e91e46SDimitry Andric PickLow = false;
2903d8e91e46SDimitry Andric }
2904d8e91e46SDimitry Andric }
2905d8e91e46SDimitry Andric
2906d8e91e46SDimitry Andric LLVM_DEBUG(dbgs() << __func__ << ": updated coefficients " << A << "x^2 + "
2907d8e91e46SDimitry Andric << B << "x + " << C << ", rw:" << RangeWidth << '\n');
2908d8e91e46SDimitry Andric
2909d8e91e46SDimitry Andric APInt D = SqrB - 4*A*C;
2910d8e91e46SDimitry Andric assert(D.isNonNegative() && "Negative discriminant");
2911d8e91e46SDimitry Andric APInt SQ = D.sqrt();
2912d8e91e46SDimitry Andric
2913d8e91e46SDimitry Andric APInt Q = SQ * SQ;
2914d8e91e46SDimitry Andric bool InexactSQ = Q != D;
2915d8e91e46SDimitry Andric // The calculated SQ may actually be greater than the exact (non-integer)
2916706b4fc4SDimitry Andric // value. If that's the case, decrement SQ to get a value that is lower.
2917d8e91e46SDimitry Andric if (Q.sgt(D))
2918d8e91e46SDimitry Andric SQ -= 1;
2919d8e91e46SDimitry Andric
2920d8e91e46SDimitry Andric APInt X;
2921d8e91e46SDimitry Andric APInt Rem;
2922d8e91e46SDimitry Andric
2923d8e91e46SDimitry Andric // SQ is rounded down (i.e SQ * SQ <= D), so the roots may be inexact.
2924d8e91e46SDimitry Andric // When using the quadratic formula directly, the calculated low root
2925d8e91e46SDimitry Andric // may be greater than the exact one, since we would be subtracting SQ.
2926d8e91e46SDimitry Andric // To make sure that the calculated root is not greater than the exact
2927d8e91e46SDimitry Andric // one, subtract SQ+1 when calculating the low root (for inexact value
2928d8e91e46SDimitry Andric // of SQ).
2929d8e91e46SDimitry Andric if (PickLow)
2930d8e91e46SDimitry Andric APInt::sdivrem(-B - (SQ+InexactSQ), TwoA, X, Rem);
2931d8e91e46SDimitry Andric else
2932d8e91e46SDimitry Andric APInt::sdivrem(-B + SQ, TwoA, X, Rem);
2933d8e91e46SDimitry Andric
2934d8e91e46SDimitry Andric // The updated coefficients should be such that the (exact) solution is
2935d8e91e46SDimitry Andric // positive. Since APInt division rounds towards 0, the calculated one
2936d8e91e46SDimitry Andric // can be 0, but cannot be negative.
2937d8e91e46SDimitry Andric assert(X.isNonNegative() && "Solution should be non-negative");
2938d8e91e46SDimitry Andric
2939c0981da4SDimitry Andric if (!InexactSQ && Rem.isZero()) {
2940d8e91e46SDimitry Andric LLVM_DEBUG(dbgs() << __func__ << ": solution (root): " << X << '\n');
2941d8e91e46SDimitry Andric return X;
2942d8e91e46SDimitry Andric }
2943d8e91e46SDimitry Andric
2944d8e91e46SDimitry Andric assert((SQ*SQ).sle(D) && "SQ = |_sqrt(D)_|, so SQ*SQ <= D");
2945d8e91e46SDimitry Andric // The exact value of the square root of D should be between SQ and SQ+1.
2946d8e91e46SDimitry Andric // This implies that the solution should be between that corresponding to
2947d8e91e46SDimitry Andric // SQ (i.e. X) and that corresponding to SQ+1.
2948d8e91e46SDimitry Andric //
2949d8e91e46SDimitry Andric // The calculated X cannot be greater than the exact (real) solution.
2950d8e91e46SDimitry Andric // Actually it must be strictly less than the exact solution, while
2951d8e91e46SDimitry Andric // X+1 will be greater than or equal to it.
2952d8e91e46SDimitry Andric
2953d8e91e46SDimitry Andric APInt VX = (A*X + B)*X + C;
2954d8e91e46SDimitry Andric APInt VY = VX + TwoA*X + A + B;
2955c0981da4SDimitry Andric bool SignChange =
2956c0981da4SDimitry Andric VX.isNegative() != VY.isNegative() || VX.isZero() != VY.isZero();
2957d8e91e46SDimitry Andric // If the sign did not change between X and X+1, X is not a valid solution.
2958d8e91e46SDimitry Andric // This could happen when the actual (exact) roots don't have an integer
2959d8e91e46SDimitry Andric // between them, so they would both be contained between X and X+1.
2960d8e91e46SDimitry Andric if (!SignChange) {
2961d8e91e46SDimitry Andric LLVM_DEBUG(dbgs() << __func__ << ": no valid solution\n");
2962e3b55780SDimitry Andric return std::nullopt;
2963d8e91e46SDimitry Andric }
2964d8e91e46SDimitry Andric
2965d8e91e46SDimitry Andric X += 1;
2966d8e91e46SDimitry Andric LLVM_DEBUG(dbgs() << __func__ << ": solution (wrap): " << X << '\n');
2967d8e91e46SDimitry Andric return X;
2968d8e91e46SDimitry Andric }
2969e6d15924SDimitry Andric
2970e3b55780SDimitry Andric std::optional<unsigned>
GetMostSignificantDifferentBit(const APInt & A,const APInt & B)2971706b4fc4SDimitry Andric llvm::APIntOps::GetMostSignificantDifferentBit(const APInt &A, const APInt &B) {
2972706b4fc4SDimitry Andric assert(A.getBitWidth() == B.getBitWidth() && "Must have the same bitwidth");
2973706b4fc4SDimitry Andric if (A == B)
2974e3b55780SDimitry Andric return std::nullopt;
29757fa27ce4SDimitry Andric return A.getBitWidth() - ((A ^ B).countl_zero() + 1);
2976706b4fc4SDimitry Andric }
2977706b4fc4SDimitry Andric
ScaleBitMask(const APInt & A,unsigned NewBitWidth,bool MatchAllBits)2978145449b1SDimitry Andric APInt llvm::APIntOps::ScaleBitMask(const APInt &A, unsigned NewBitWidth,
2979145449b1SDimitry Andric bool MatchAllBits) {
2980c0981da4SDimitry Andric unsigned OldBitWidth = A.getBitWidth();
2981c0981da4SDimitry Andric assert((((OldBitWidth % NewBitWidth) == 0) ||
2982c0981da4SDimitry Andric ((NewBitWidth % OldBitWidth) == 0)) &&
2983c0981da4SDimitry Andric "One size should be a multiple of the other one. "
2984c0981da4SDimitry Andric "Can't do fractional scaling.");
2985c0981da4SDimitry Andric
2986c0981da4SDimitry Andric // Check for matching bitwidths.
2987c0981da4SDimitry Andric if (OldBitWidth == NewBitWidth)
2988c0981da4SDimitry Andric return A;
2989c0981da4SDimitry Andric
2990c0981da4SDimitry Andric APInt NewA = APInt::getZero(NewBitWidth);
2991c0981da4SDimitry Andric
2992c0981da4SDimitry Andric // Check for null input.
2993c0981da4SDimitry Andric if (A.isZero())
2994c0981da4SDimitry Andric return NewA;
2995c0981da4SDimitry Andric
2996c0981da4SDimitry Andric if (NewBitWidth > OldBitWidth) {
2997c0981da4SDimitry Andric // Repeat bits.
2998c0981da4SDimitry Andric unsigned Scale = NewBitWidth / OldBitWidth;
2999c0981da4SDimitry Andric for (unsigned i = 0; i != OldBitWidth; ++i)
3000c0981da4SDimitry Andric if (A[i])
3001c0981da4SDimitry Andric NewA.setBits(i * Scale, (i + 1) * Scale);
3002c0981da4SDimitry Andric } else {
3003c0981da4SDimitry Andric unsigned Scale = OldBitWidth / NewBitWidth;
3004145449b1SDimitry Andric for (unsigned i = 0; i != NewBitWidth; ++i) {
3005145449b1SDimitry Andric if (MatchAllBits) {
3006145449b1SDimitry Andric if (A.extractBits(Scale, i * Scale).isAllOnes())
3007145449b1SDimitry Andric NewA.setBit(i);
3008145449b1SDimitry Andric } else {
3009c0981da4SDimitry Andric if (!A.extractBits(Scale, i * Scale).isZero())
3010c0981da4SDimitry Andric NewA.setBit(i);
3011c0981da4SDimitry Andric }
3012145449b1SDimitry Andric }
3013145449b1SDimitry Andric }
3014c0981da4SDimitry Andric
3015c0981da4SDimitry Andric return NewA;
3016c0981da4SDimitry Andric }
3017c0981da4SDimitry Andric
3018e6d15924SDimitry Andric /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
3019e6d15924SDimitry Andric /// with the integer held in IntVal.
StoreIntToMemory(const APInt & IntVal,uint8_t * Dst,unsigned StoreBytes)3020e6d15924SDimitry Andric void llvm::StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
3021e6d15924SDimitry Andric unsigned StoreBytes) {
3022e6d15924SDimitry Andric assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
3023e6d15924SDimitry Andric const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
3024e6d15924SDimitry Andric
3025e6d15924SDimitry Andric if (sys::IsLittleEndianHost) {
3026e6d15924SDimitry Andric // Little-endian host - the source is ordered from LSB to MSB. Order the
3027e6d15924SDimitry Andric // destination from LSB to MSB: Do a straight copy.
3028e6d15924SDimitry Andric memcpy(Dst, Src, StoreBytes);
3029e6d15924SDimitry Andric } else {
3030e6d15924SDimitry Andric // Big-endian host - the source is an array of 64 bit words ordered from
3031e6d15924SDimitry Andric // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
3032e6d15924SDimitry Andric // from MSB to LSB: Reverse the word order, but not the bytes in a word.
3033e6d15924SDimitry Andric while (StoreBytes > sizeof(uint64_t)) {
3034e6d15924SDimitry Andric StoreBytes -= sizeof(uint64_t);
3035e6d15924SDimitry Andric // May not be aligned so use memcpy.
3036e6d15924SDimitry Andric memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
3037e6d15924SDimitry Andric Src += sizeof(uint64_t);
3038e6d15924SDimitry Andric }
3039e6d15924SDimitry Andric
3040e6d15924SDimitry Andric memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
3041e6d15924SDimitry Andric }
3042e6d15924SDimitry Andric }
3043e6d15924SDimitry Andric
3044e6d15924SDimitry Andric /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
3045e6d15924SDimitry Andric /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
LoadIntFromMemory(APInt & IntVal,const uint8_t * Src,unsigned LoadBytes)3046cfca06d7SDimitry Andric void llvm::LoadIntFromMemory(APInt &IntVal, const uint8_t *Src,
3047cfca06d7SDimitry Andric unsigned LoadBytes) {
3048e6d15924SDimitry Andric assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
3049e6d15924SDimitry Andric uint8_t *Dst = reinterpret_cast<uint8_t *>(
3050e6d15924SDimitry Andric const_cast<uint64_t *>(IntVal.getRawData()));
3051e6d15924SDimitry Andric
3052e6d15924SDimitry Andric if (sys::IsLittleEndianHost)
3053e6d15924SDimitry Andric // Little-endian host - the destination must be ordered from LSB to MSB.
3054e6d15924SDimitry Andric // The source is ordered from LSB to MSB: Do a straight copy.
3055e6d15924SDimitry Andric memcpy(Dst, Src, LoadBytes);
3056e6d15924SDimitry Andric else {
3057e6d15924SDimitry Andric // Big-endian - the destination is an array of 64 bit words ordered from
3058e6d15924SDimitry Andric // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
3059e6d15924SDimitry Andric // ordered from MSB to LSB: Reverse the word order, but not the bytes in
3060e6d15924SDimitry Andric // a word.
3061e6d15924SDimitry Andric while (LoadBytes > sizeof(uint64_t)) {
3062e6d15924SDimitry Andric LoadBytes -= sizeof(uint64_t);
3063e6d15924SDimitry Andric // May not be aligned so use memcpy.
3064e6d15924SDimitry Andric memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
3065e6d15924SDimitry Andric Dst += sizeof(uint64_t);
3066e6d15924SDimitry Andric }
3067e6d15924SDimitry Andric
3068e6d15924SDimitry Andric memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
3069e6d15924SDimitry Andric }
3070e6d15924SDimitry Andric }
3071ac9a064cSDimitry Andric
avgFloorS(const APInt & C1,const APInt & C2)3072ac9a064cSDimitry Andric APInt APIntOps::avgFloorS(const APInt &C1, const APInt &C2) {
3073ac9a064cSDimitry Andric // Return floor((C1 + C2) / 2)
3074ac9a064cSDimitry Andric return (C1 & C2) + (C1 ^ C2).ashr(1);
3075ac9a064cSDimitry Andric }
3076ac9a064cSDimitry Andric
avgFloorU(const APInt & C1,const APInt & C2)3077ac9a064cSDimitry Andric APInt APIntOps::avgFloorU(const APInt &C1, const APInt &C2) {
3078ac9a064cSDimitry Andric // Return floor((C1 + C2) / 2)
3079ac9a064cSDimitry Andric return (C1 & C2) + (C1 ^ C2).lshr(1);
3080ac9a064cSDimitry Andric }
3081ac9a064cSDimitry Andric
avgCeilS(const APInt & C1,const APInt & C2)3082ac9a064cSDimitry Andric APInt APIntOps::avgCeilS(const APInt &C1, const APInt &C2) {
3083ac9a064cSDimitry Andric // Return ceil((C1 + C2) / 2)
3084ac9a064cSDimitry Andric return (C1 | C2) - (C1 ^ C2).ashr(1);
3085ac9a064cSDimitry Andric }
3086ac9a064cSDimitry Andric
avgCeilU(const APInt & C1,const APInt & C2)3087ac9a064cSDimitry Andric APInt APIntOps::avgCeilU(const APInt &C1, const APInt &C2) {
3088ac9a064cSDimitry Andric // Return ceil((C1 + C2) / 2)
3089ac9a064cSDimitry Andric return (C1 | C2) - (C1 ^ C2).lshr(1);
3090ac9a064cSDimitry Andric }
3091ac9a064cSDimitry Andric
mulhs(const APInt & C1,const APInt & C2)3092ac9a064cSDimitry Andric APInt APIntOps::mulhs(const APInt &C1, const APInt &C2) {
3093ac9a064cSDimitry Andric assert(C1.getBitWidth() == C2.getBitWidth() && "Unequal bitwidths");
3094ac9a064cSDimitry Andric unsigned FullWidth = C1.getBitWidth() * 2;
3095ac9a064cSDimitry Andric APInt C1Ext = C1.sext(FullWidth);
3096ac9a064cSDimitry Andric APInt C2Ext = C2.sext(FullWidth);
3097ac9a064cSDimitry Andric return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
3098ac9a064cSDimitry Andric }
3099ac9a064cSDimitry Andric
mulhu(const APInt & C1,const APInt & C2)3100ac9a064cSDimitry Andric APInt APIntOps::mulhu(const APInt &C1, const APInt &C2) {
3101ac9a064cSDimitry Andric assert(C1.getBitWidth() == C2.getBitWidth() && "Unequal bitwidths");
3102ac9a064cSDimitry Andric unsigned FullWidth = C1.getBitWidth() * 2;
3103ac9a064cSDimitry Andric APInt C1Ext = C1.zext(FullWidth);
3104ac9a064cSDimitry Andric APInt C2Ext = C2.zext(FullWidth);
3105ac9a064cSDimitry Andric return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
3106ac9a064cSDimitry Andric }
3107