blob: 1094a61cf1cbb0a6f9f448374efa8fa544f45bae [file] [log] [blame]
Zhou Shengdac63782007-02-06 03:00:16 +00001//===-- APInt.cpp - Implement APInt class ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Zhou Shengdac63782007-02-06 03:00:16 +00007//
8//===----------------------------------------------------------------------===//
9//
Reid Spencera41e93b2007-02-25 19:32:03 +000010// This file implements a class to represent arbitrary precision integer
11// constant values and provide a variety of arithmetic operations on them.
Zhou Shengdac63782007-02-06 03:00:16 +000012//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/ADT/APInt.h"
Mehdi Amini47b292d2016-04-16 07:51:28 +000016#include "llvm/ADT/ArrayRef.h"
Ted Kremenek5c75d542008-01-19 04:23:33 +000017#include "llvm/ADT/FoldingSet.h"
Chandler Carruth71bd7d12012-03-04 12:02:57 +000018#include "llvm/ADT/Hashing.h"
Chris Lattner17f71652008-08-17 07:19:36 +000019#include "llvm/ADT/SmallString.h"
Chandler Carruth71bd7d12012-03-04 12:02:57 +000020#include "llvm/ADT/StringRef.h"
Reid Spencera5e0d202007-02-24 03:58:46 +000021#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000022#include "llvm/Support/ErrorHandling.h"
Zhou Shengdac63782007-02-06 03:00:16 +000023#include "llvm/Support/MathExtras.h"
Chris Lattner0c19df42008-08-23 22:23:09 +000024#include "llvm/Support/raw_ostream.h"
Vassil Vassilev2ec8b152016-09-14 08:55:18 +000025#include <climits>
Chris Lattner17f71652008-08-17 07:19:36 +000026#include <cmath>
Zhou Shengdac63782007-02-06 03:00:16 +000027#include <cstdlib>
Chandler Carruthed0881b2012-12-03 16:50:05 +000028#include <cstring>
Zhou Shengdac63782007-02-06 03:00:16 +000029using namespace llvm;
30
Chandler Carruth64648262014-04-22 03:07:47 +000031#define DEBUG_TYPE "apint"
32
Reid Spencera41e93b2007-02-25 19:32:03 +000033/// A utility function for allocating memory, checking for allocation failures,
34/// and ensuring the contents are zeroed.
Chris Lattner77527f52009-01-21 18:09:24 +000035inline static uint64_t* getClearedMemory(unsigned numWords) {
Reid Spencera856b6e2007-02-18 18:38:44 +000036 uint64_t * result = new uint64_t[numWords];
37 assert(result && "APInt memory allocation fails!");
38 memset(result, 0, numWords * sizeof(uint64_t));
39 return result;
Zhou Sheng94b623a2007-02-06 06:04:53 +000040}
41
Eric Christopher820256b2009-08-21 04:06:45 +000042/// A utility function for allocating memory and checking for allocation
Reid Spencera41e93b2007-02-25 19:32:03 +000043/// failure. The content is not zeroed.
Chris Lattner77527f52009-01-21 18:09:24 +000044inline static uint64_t* getMemory(unsigned numWords) {
Reid Spencera856b6e2007-02-18 18:38:44 +000045 uint64_t * result = new uint64_t[numWords];
46 assert(result && "APInt memory allocation fails!");
47 return result;
48}
49
Erick Tryzelaardadb15712009-08-21 03:15:28 +000050/// A utility function that converts a character to a digit.
51inline static unsigned getDigit(char cdigit, uint8_t radix) {
Erick Tryzelaar60964092009-08-21 06:48:37 +000052 unsigned r;
53
Douglas Gregor663c0682011-09-14 15:54:46 +000054 if (radix == 16 || radix == 36) {
Erick Tryzelaar60964092009-08-21 06:48:37 +000055 r = cdigit - '0';
56 if (r <= 9)
57 return r;
58
59 r = cdigit - 'A';
Douglas Gregorc98ac852011-09-20 18:33:29 +000060 if (r <= radix - 11U)
Erick Tryzelaar60964092009-08-21 06:48:37 +000061 return r + 10;
62
63 r = cdigit - 'a';
Douglas Gregorc98ac852011-09-20 18:33:29 +000064 if (r <= radix - 11U)
Erick Tryzelaar60964092009-08-21 06:48:37 +000065 return r + 10;
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +000066
Douglas Gregore4e20f42011-09-20 18:11:52 +000067 radix = 10;
Erick Tryzelaardadb15712009-08-21 03:15:28 +000068 }
69
Erick Tryzelaar60964092009-08-21 06:48:37 +000070 r = cdigit - '0';
71 if (r < radix)
72 return r;
73
74 return -1U;
Erick Tryzelaardadb15712009-08-21 03:15:28 +000075}
76
77
Pawel Bylica68304012016-06-27 08:31:48 +000078void APInt::initSlowCase(uint64_t val, bool isSigned) {
Craig Topper0085ffb2017-03-20 01:29:52 +000079 VAL = 0;
Chris Lattner1ac3e252008-08-20 17:02:31 +000080 pVal = getClearedMemory(getNumWords());
81 pVal[0] = val;
Eric Christopher820256b2009-08-21 04:06:45 +000082 if (isSigned && int64_t(val) < 0)
Chris Lattner1ac3e252008-08-20 17:02:31 +000083 for (unsigned i = 1; i < getNumWords(); ++i)
84 pVal[i] = -1ULL;
Craig Topperf78a6f02017-03-01 21:06:18 +000085 clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +000086}
87
Chris Lattnerd57b7602008-10-11 22:07:19 +000088void APInt::initSlowCase(const APInt& that) {
Craig Topper0085ffb2017-03-20 01:29:52 +000089 VAL = 0;
Chris Lattnerd57b7602008-10-11 22:07:19 +000090 pVal = getMemory(getNumWords());
91 memcpy(pVal, that.pVal, getNumWords() * APINT_WORD_SIZE);
92}
93
Jeffrey Yasskin7a162882011-07-18 21:45:40 +000094void APInt::initFromArray(ArrayRef<uint64_t> bigVal) {
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +000095 assert(BitWidth && "Bitwidth too small");
Jeffrey Yasskin7a162882011-07-18 21:45:40 +000096 assert(bigVal.data() && "Null pointer detected!");
Zhou Shengdac63782007-02-06 03:00:16 +000097 if (isSingleWord())
Reid Spencerdf6cf5a2007-02-24 10:01:42 +000098 VAL = bigVal[0];
Zhou Shengdac63782007-02-06 03:00:16 +000099 else {
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000100 // Get memory, cleared to 0
Craig Topper0085ffb2017-03-20 01:29:52 +0000101 VAL = 0;
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000102 pVal = getClearedMemory(getNumWords());
103 // Calculate the number of words to copy
Jeffrey Yasskin7a162882011-07-18 21:45:40 +0000104 unsigned words = std::min<unsigned>(bigVal.size(), getNumWords());
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000105 // Copy the words from bigVal to pVal
Jeffrey Yasskin7a162882011-07-18 21:45:40 +0000106 memcpy(pVal, bigVal.data(), words * APINT_WORD_SIZE);
Zhou Shengdac63782007-02-06 03:00:16 +0000107 }
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000108 // Make sure unused high bits are cleared
109 clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000110}
111
Jeffrey Yasskin7a162882011-07-18 21:45:40 +0000112APInt::APInt(unsigned numBits, ArrayRef<uint64_t> bigVal)
Craig Topper0085ffb2017-03-20 01:29:52 +0000113 : BitWidth(numBits) {
Jeffrey Yasskin7a162882011-07-18 21:45:40 +0000114 initFromArray(bigVal);
115}
116
117APInt::APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[])
Craig Topper0085ffb2017-03-20 01:29:52 +0000118 : BitWidth(numBits) {
Jeffrey Yasskin7a162882011-07-18 21:45:40 +0000119 initFromArray(makeArrayRef(bigVal, numWords));
120}
121
Benjamin Kramer92d89982010-07-14 22:38:02 +0000122APInt::APInt(unsigned numbits, StringRef Str, uint8_t radix)
Craig Topper90377de2017-04-13 04:59:11 +0000123 : VAL(0), BitWidth(numbits) {
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000124 assert(BitWidth && "Bitwidth too small");
Daniel Dunbar3a1efd112009-08-13 02:33:34 +0000125 fromString(numbits, Str, radix);
Zhou Sheng3e8022d2007-02-07 06:14:53 +0000126}
127
Chris Lattner1ac3e252008-08-20 17:02:31 +0000128APInt& APInt::AssignSlowCase(const APInt& RHS) {
Reid Spencer7c16cd22007-02-26 23:38:21 +0000129 // Don't do anything for X = X
130 if (this == &RHS)
131 return *this;
132
Reid Spencer7c16cd22007-02-26 23:38:21 +0000133 if (BitWidth == RHS.getBitWidth()) {
Chris Lattner1ac3e252008-08-20 17:02:31 +0000134 // assume same bit-width single-word case is already handled
135 assert(!isSingleWord());
136 memcpy(pVal, RHS.pVal, getNumWords() * APINT_WORD_SIZE);
Reid Spencer7c16cd22007-02-26 23:38:21 +0000137 return *this;
138 }
139
Chris Lattner1ac3e252008-08-20 17:02:31 +0000140 if (isSingleWord()) {
141 // assume case where both are single words is already handled
142 assert(!RHS.isSingleWord());
143 VAL = 0;
144 pVal = getMemory(RHS.getNumWords());
145 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
Eric Christopher820256b2009-08-21 04:06:45 +0000146 } else if (getNumWords() == RHS.getNumWords())
Reid Spencer7c16cd22007-02-26 23:38:21 +0000147 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
148 else if (RHS.isSingleWord()) {
149 delete [] pVal;
Reid Spencera856b6e2007-02-18 18:38:44 +0000150 VAL = RHS.VAL;
Reid Spencer7c16cd22007-02-26 23:38:21 +0000151 } else {
152 delete [] pVal;
153 pVal = getMemory(RHS.getNumWords());
154 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
155 }
156 BitWidth = RHS.BitWidth;
157 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000158}
159
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000160/// This method 'profiles' an APInt for use with FoldingSet.
Ted Kremenek5c75d542008-01-19 04:23:33 +0000161void APInt::Profile(FoldingSetNodeID& ID) const {
Ted Kremenek901540f2008-02-19 20:50:41 +0000162 ID.AddInteger(BitWidth);
Eric Christopher820256b2009-08-21 04:06:45 +0000163
Ted Kremenek5c75d542008-01-19 04:23:33 +0000164 if (isSingleWord()) {
165 ID.AddInteger(VAL);
166 return;
167 }
168
Chris Lattner77527f52009-01-21 18:09:24 +0000169 unsigned NumWords = getNumWords();
Ted Kremenek5c75d542008-01-19 04:23:33 +0000170 for (unsigned i = 0; i < NumWords; ++i)
171 ID.AddInteger(pVal[i]);
172}
173
Zhou Shengdac63782007-02-06 03:00:16 +0000174/// @brief Prefix increment operator. Increments the APInt by one.
175APInt& APInt::operator++() {
Eric Christopher820256b2009-08-21 04:06:45 +0000176 if (isSingleWord())
Reid Spencer1d072122007-02-16 22:36:51 +0000177 ++VAL;
Zhou Shengdac63782007-02-06 03:00:16 +0000178 else
Craig Topper92fc4772017-04-13 04:36:06 +0000179 tcIncrement(pVal, getNumWords());
Reid Spencera41e93b2007-02-25 19:32:03 +0000180 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000181}
182
Zhou Shengdac63782007-02-06 03:00:16 +0000183/// @brief Prefix decrement operator. Decrements the APInt by one.
184APInt& APInt::operator--() {
Eric Christopher820256b2009-08-21 04:06:45 +0000185 if (isSingleWord())
Reid Spencera856b6e2007-02-18 18:38:44 +0000186 --VAL;
Zhou Shengdac63782007-02-06 03:00:16 +0000187 else
Craig Topper92fc4772017-04-13 04:36:06 +0000188 tcDecrement(pVal, getNumWords());
Reid Spencera41e93b2007-02-25 19:32:03 +0000189 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000190}
191
Reid Spencera41e93b2007-02-25 19:32:03 +0000192/// Adds the RHS APint to this APInt.
193/// @returns this, after addition of RHS.
Eric Christopher820256b2009-08-21 04:06:45 +0000194/// @brief Addition assignment operator.
Zhou Shengdac63782007-02-06 03:00:16 +0000195APInt& APInt::operator+=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000196 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Eric Christopher820256b2009-08-21 04:06:45 +0000197 if (isSingleWord())
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000198 VAL += RHS.VAL;
Craig Topper15e484a2017-04-02 06:59:43 +0000199 else
200 tcAdd(pVal, RHS.pVal, 0, getNumWords());
Reid Spencera41e93b2007-02-25 19:32:03 +0000201 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000202}
203
Pete Cooperfea21392016-07-22 20:55:46 +0000204APInt& APInt::operator+=(uint64_t RHS) {
205 if (isSingleWord())
206 VAL += RHS;
207 else
Craig Topper92fc4772017-04-13 04:36:06 +0000208 tcAddPart(pVal, RHS, getNumWords());
Pete Cooperfea21392016-07-22 20:55:46 +0000209 return clearUnusedBits();
210}
211
Reid Spencera41e93b2007-02-25 19:32:03 +0000212/// Subtracts the RHS APInt from this APInt
213/// @returns this, after subtraction
Eric Christopher820256b2009-08-21 04:06:45 +0000214/// @brief Subtraction assignment operator.
Zhou Shengdac63782007-02-06 03:00:16 +0000215APInt& APInt::operator-=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000216 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Eric Christopher820256b2009-08-21 04:06:45 +0000217 if (isSingleWord())
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000218 VAL -= RHS.VAL;
219 else
Craig Topper15e484a2017-04-02 06:59:43 +0000220 tcSubtract(pVal, RHS.pVal, 0, getNumWords());
Reid Spencera41e93b2007-02-25 19:32:03 +0000221 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000222}
223
Pete Cooperfea21392016-07-22 20:55:46 +0000224APInt& APInt::operator-=(uint64_t RHS) {
225 if (isSingleWord())
226 VAL -= RHS;
227 else
Craig Topper92fc4772017-04-13 04:36:06 +0000228 tcSubtractPart(pVal, RHS, getNumWords());
Pete Cooperfea21392016-07-22 20:55:46 +0000229 return clearUnusedBits();
230}
231
Dan Gohman4a618822010-02-10 16:03:48 +0000232/// Multiplies an integer array, x, by a uint64_t integer and places the result
Eric Christopher820256b2009-08-21 04:06:45 +0000233/// into dest.
Reid Spencera41e93b2007-02-25 19:32:03 +0000234/// @returns the carry out of the multiplication.
235/// @brief Multiply a multi-digit APInt by a single digit (64-bit) integer.
Chris Lattner77527f52009-01-21 18:09:24 +0000236static uint64_t mul_1(uint64_t dest[], uint64_t x[], unsigned len, uint64_t y) {
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000237 // Split y into high 32-bit part (hy) and low 32-bit part (ly)
Reid Spencer100502d2007-02-17 03:16:00 +0000238 uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
Reid Spencera41e93b2007-02-25 19:32:03 +0000239 uint64_t carry = 0;
240
241 // For each digit of x.
Chris Lattner77527f52009-01-21 18:09:24 +0000242 for (unsigned i = 0; i < len; ++i) {
Reid Spencera41e93b2007-02-25 19:32:03 +0000243 // Split x into high and low words
244 uint64_t lx = x[i] & 0xffffffffULL;
245 uint64_t hx = x[i] >> 32;
246 // hasCarry - A flag to indicate if there is a carry to the next digit.
Reid Spencer100502d2007-02-17 03:16:00 +0000247 // hasCarry == 0, no carry
248 // hasCarry == 1, has carry
249 // hasCarry == 2, no carry and the calculation result == 0.
250 uint8_t hasCarry = 0;
251 dest[i] = carry + lx * ly;
252 // Determine if the add above introduces carry.
253 hasCarry = (dest[i] < carry) ? 1 : 0;
254 carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
Eric Christopher820256b2009-08-21 04:06:45 +0000255 // The upper limit of carry can be (2^32 - 1)(2^32 - 1) +
Reid Spencer100502d2007-02-17 03:16:00 +0000256 // (2^32 - 1) + 2^32 = 2^64.
257 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
258
259 carry += (lx * hy) & 0xffffffffULL;
260 dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
Eric Christopher820256b2009-08-21 04:06:45 +0000261 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) +
Reid Spencer100502d2007-02-17 03:16:00 +0000262 (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
263 }
Reid Spencer100502d2007-02-17 03:16:00 +0000264 return carry;
265}
266
Eric Christopher820256b2009-08-21 04:06:45 +0000267/// Multiplies integer array x by integer array y and stores the result into
Reid Spencera41e93b2007-02-25 19:32:03 +0000268/// the integer array dest. Note that dest's size must be >= xlen + ylen.
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000269/// @brief Generalized multiplication of integer arrays.
Chris Lattner77527f52009-01-21 18:09:24 +0000270static void mul(uint64_t dest[], uint64_t x[], unsigned xlen, uint64_t y[],
271 unsigned ylen) {
Reid Spencer100502d2007-02-17 03:16:00 +0000272 dest[xlen] = mul_1(dest, x, xlen, y[0]);
Chris Lattner77527f52009-01-21 18:09:24 +0000273 for (unsigned i = 1; i < ylen; ++i) {
Reid Spencer100502d2007-02-17 03:16:00 +0000274 uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
Reid Spencer58a6a432007-02-21 08:21:52 +0000275 uint64_t carry = 0, lx = 0, hx = 0;
Chris Lattner77527f52009-01-21 18:09:24 +0000276 for (unsigned j = 0; j < xlen; ++j) {
Reid Spencer100502d2007-02-17 03:16:00 +0000277 lx = x[j] & 0xffffffffULL;
278 hx = x[j] >> 32;
279 // hasCarry - A flag to indicate if has carry.
280 // hasCarry == 0, no carry
281 // hasCarry == 1, has carry
282 // hasCarry == 2, no carry and the calculation result == 0.
283 uint8_t hasCarry = 0;
284 uint64_t resul = carry + lx * ly;
285 hasCarry = (resul < carry) ? 1 : 0;
286 carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
287 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
288
289 carry += (lx * hy) & 0xffffffffULL;
290 resul = (carry << 32) | (resul & 0xffffffffULL);
291 dest[i+j] += resul;
292 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
Eric Christopher820256b2009-08-21 04:06:45 +0000293 (carry >> 32) + (dest[i+j] < resul ? 1 : 0) +
Reid Spencer100502d2007-02-17 03:16:00 +0000294 ((lx * hy) >> 32) + hx * hy;
295 }
296 dest[i+xlen] = carry;
297 }
298}
299
Zhou Shengdac63782007-02-06 03:00:16 +0000300APInt& APInt::operator*=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000301 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer58a6a432007-02-21 08:21:52 +0000302 if (isSingleWord()) {
Reid Spencer4bb430c2007-02-20 20:42:10 +0000303 VAL *= RHS.VAL;
Reid Spencer58a6a432007-02-21 08:21:52 +0000304 clearUnusedBits();
305 return *this;
Zhou Shengdac63782007-02-06 03:00:16 +0000306 }
Reid Spencer58a6a432007-02-21 08:21:52 +0000307
308 // Get some bit facts about LHS and check for zero
Chris Lattner77527f52009-01-21 18:09:24 +0000309 unsigned lhsBits = getActiveBits();
310 unsigned lhsWords = !lhsBits ? 0 : whichWord(lhsBits - 1) + 1;
Eric Christopher820256b2009-08-21 04:06:45 +0000311 if (!lhsWords)
Reid Spencer58a6a432007-02-21 08:21:52 +0000312 // 0 * X ===> 0
313 return *this;
314
315 // Get some bit facts about RHS and check for zero
Chris Lattner77527f52009-01-21 18:09:24 +0000316 unsigned rhsBits = RHS.getActiveBits();
317 unsigned rhsWords = !rhsBits ? 0 : whichWord(rhsBits - 1) + 1;
Reid Spencer58a6a432007-02-21 08:21:52 +0000318 if (!rhsWords) {
319 // X * 0 ===> 0
Jay Foad25a5e4c2010-12-01 08:53:58 +0000320 clearAllBits();
Reid Spencer58a6a432007-02-21 08:21:52 +0000321 return *this;
322 }
323
324 // Allocate space for the result
Chris Lattner77527f52009-01-21 18:09:24 +0000325 unsigned destWords = rhsWords + lhsWords;
Reid Spencer58a6a432007-02-21 08:21:52 +0000326 uint64_t *dest = getMemory(destWords);
327
328 // Perform the long multiply
329 mul(dest, pVal, lhsWords, RHS.pVal, rhsWords);
330
331 // Copy result back into *this
Jay Foad25a5e4c2010-12-01 08:53:58 +0000332 clearAllBits();
Chris Lattner77527f52009-01-21 18:09:24 +0000333 unsigned wordsToCopy = destWords >= getNumWords() ? getNumWords() : destWords;
Reid Spencer58a6a432007-02-21 08:21:52 +0000334 memcpy(pVal, dest, wordsToCopy * APINT_WORD_SIZE);
Eli Friedman19546412011-10-07 23:40:49 +0000335 clearUnusedBits();
Reid Spencer58a6a432007-02-21 08:21:52 +0000336
337 // delete dest array and return
338 delete[] dest;
Zhou Shengdac63782007-02-06 03:00:16 +0000339 return *this;
340}
341
Craig Topperf496f9a2017-03-28 04:00:47 +0000342APInt& APInt::AndAssignSlowCase(const APInt& RHS) {
Craig Topperb2aaa5d2017-04-01 21:50:03 +0000343 tcAnd(pVal, RHS.pVal, getNumWords());
Zhou Shengdac63782007-02-06 03:00:16 +0000344 return *this;
345}
346
Craig Topperf496f9a2017-03-28 04:00:47 +0000347APInt& APInt::OrAssignSlowCase(const APInt& RHS) {
Craig Topperb2aaa5d2017-04-01 21:50:03 +0000348 tcOr(pVal, RHS.pVal, getNumWords());
Zhou Shengdac63782007-02-06 03:00:16 +0000349 return *this;
350}
351
Craig Topperf496f9a2017-03-28 04:00:47 +0000352APInt& APInt::XorAssignSlowCase(const APInt& RHS) {
Craig Topperb2aaa5d2017-04-01 21:50:03 +0000353 tcXor(pVal, RHS.pVal, getNumWords());
Craig Topper9028f052017-01-24 02:10:15 +0000354 return *this;
Zhou Shengdac63782007-02-06 03:00:16 +0000355}
356
Zhou Shengdac63782007-02-06 03:00:16 +0000357APInt APInt::operator*(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +0000358 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencera41e93b2007-02-25 19:32:03 +0000359 if (isSingleWord())
Reid Spenceraa8dcfe2007-02-26 07:44:38 +0000360 return APInt(BitWidth, VAL * RHS.VAL);
Reid Spencer4bb430c2007-02-20 20:42:10 +0000361 APInt Result(*this);
362 Result *= RHS;
Eli Friedman19546412011-10-07 23:40:49 +0000363 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000364}
365
Chris Lattner1ac3e252008-08-20 17:02:31 +0000366bool APInt::EqualSlowCase(const APInt& RHS) const {
Matthias Braun5117fcd2016-02-15 20:06:19 +0000367 return std::equal(pVal, pVal + getNumWords(), RHS.pVal);
Zhou Shengdac63782007-02-06 03:00:16 +0000368}
369
Chris Lattner1ac3e252008-08-20 17:02:31 +0000370bool APInt::EqualSlowCase(uint64_t Val) const {
Chris Lattner77527f52009-01-21 18:09:24 +0000371 unsigned n = getActiveBits();
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000372 if (n <= APINT_BITS_PER_WORD)
373 return pVal[0] == Val;
374 else
375 return false;
Zhou Shengdac63782007-02-06 03:00:16 +0000376}
377
Reid Spencer1d072122007-02-16 22:36:51 +0000378bool APInt::ult(const APInt& RHS) const {
379 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
380 if (isSingleWord())
381 return VAL < RHS.VAL;
Reid Spencera41e93b2007-02-25 19:32:03 +0000382
383 // Get active bit length of both operands
Chris Lattner77527f52009-01-21 18:09:24 +0000384 unsigned n1 = getActiveBits();
385 unsigned n2 = RHS.getActiveBits();
Reid Spencera41e93b2007-02-25 19:32:03 +0000386
387 // If magnitude of LHS is less than RHS, return true.
388 if (n1 < n2)
389 return true;
390
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000391 // If magnitude of RHS is greater than LHS, return false.
Reid Spencera41e93b2007-02-25 19:32:03 +0000392 if (n2 < n1)
393 return false;
394
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000395 // If they both fit in a word, just compare the low order word
Reid Spencera41e93b2007-02-25 19:32:03 +0000396 if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
397 return pVal[0] < RHS.pVal[0];
398
399 // Otherwise, compare all words
Chris Lattner77527f52009-01-21 18:09:24 +0000400 unsigned topWord = whichWord(std::max(n1,n2)-1);
Reid Spencer54abdcf2007-02-27 18:23:40 +0000401 for (int i = topWord; i >= 0; --i) {
Eric Christopher820256b2009-08-21 04:06:45 +0000402 if (pVal[i] > RHS.pVal[i])
Reid Spencer1d072122007-02-16 22:36:51 +0000403 return false;
Eric Christopher820256b2009-08-21 04:06:45 +0000404 if (pVal[i] < RHS.pVal[i])
Reid Spencera41e93b2007-02-25 19:32:03 +0000405 return true;
Zhou Shengdac63782007-02-06 03:00:16 +0000406 }
407 return false;
408}
409
Reid Spencer1d072122007-02-16 22:36:51 +0000410bool APInt::slt(const APInt& RHS) const {
411 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000412 if (isSingleWord()) {
David Majnemer5f1c0172016-06-24 20:51:47 +0000413 int64_t lhsSext = SignExtend64(VAL, BitWidth);
414 int64_t rhsSext = SignExtend64(RHS.VAL, BitWidth);
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000415 return lhsSext < rhsSext;
Reid Spencer1d072122007-02-16 22:36:51 +0000416 }
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000417
Reid Spencer54abdcf2007-02-27 18:23:40 +0000418 bool lhsNeg = isNegative();
Pete Cooperd6e6bf12016-05-26 17:40:07 +0000419 bool rhsNeg = RHS.isNegative();
Reid Spencera41e93b2007-02-25 19:32:03 +0000420
Pete Cooperd6e6bf12016-05-26 17:40:07 +0000421 // If the sign bits don't match, then (LHS < RHS) if LHS is negative
422 if (lhsNeg != rhsNeg)
423 return lhsNeg;
424
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000425 // Otherwise we can just use an unsigned comparison, because even negative
Pete Cooperd6e6bf12016-05-26 17:40:07 +0000426 // numbers compare correctly this way if both have the same signed-ness.
427 return ult(RHS);
Zhou Shengdac63782007-02-06 03:00:16 +0000428}
429
Jay Foad25a5e4c2010-12-01 08:53:58 +0000430void APInt::setBit(unsigned bitPosition) {
Eric Christopher820256b2009-08-21 04:06:45 +0000431 if (isSingleWord())
Reid Spencera41e93b2007-02-25 19:32:03 +0000432 VAL |= maskBit(bitPosition);
Eric Christopher820256b2009-08-21 04:06:45 +0000433 else
Reid Spencera41e93b2007-02-25 19:32:03 +0000434 pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
Zhou Shengdac63782007-02-06 03:00:16 +0000435}
436
Craig Topperbafdd032017-03-07 01:56:01 +0000437void APInt::setBitsSlowCase(unsigned loBit, unsigned hiBit) {
438 unsigned loWord = whichWord(loBit);
439 unsigned hiWord = whichWord(hiBit);
Simon Pilgrimaed35222017-02-24 10:15:29 +0000440
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000441 // Create an initial mask for the low word with zeros below loBit.
Craig Topperbafdd032017-03-07 01:56:01 +0000442 uint64_t loMask = UINT64_MAX << whichBit(loBit);
Simon Pilgrimaed35222017-02-24 10:15:29 +0000443
Craig Topperbafdd032017-03-07 01:56:01 +0000444 // If hiBit is not aligned, we need a high mask.
445 unsigned hiShiftAmt = whichBit(hiBit);
446 if (hiShiftAmt != 0) {
447 // Create a high mask with zeros above hiBit.
448 uint64_t hiMask = UINT64_MAX >> (APINT_BITS_PER_WORD - hiShiftAmt);
449 // If loWord and hiWord are equal, then we combine the masks. Otherwise,
450 // set the bits in hiWord.
451 if (hiWord == loWord)
452 loMask &= hiMask;
453 else
Simon Pilgrimaed35222017-02-24 10:15:29 +0000454 pVal[hiWord] |= hiMask;
Simon Pilgrimaed35222017-02-24 10:15:29 +0000455 }
Craig Topperbafdd032017-03-07 01:56:01 +0000456 // Apply the mask to the low word.
457 pVal[loWord] |= loMask;
458
459 // Fill any words between loWord and hiWord with all ones.
460 for (unsigned word = loWord + 1; word < hiWord; ++word)
461 pVal[word] = UINT64_MAX;
Simon Pilgrimaed35222017-02-24 10:15:29 +0000462}
463
Zhou Shengdac63782007-02-06 03:00:16 +0000464/// Set the given bit to 0 whose position is given as "bitPosition".
465/// @brief Set a given bit to 0.
Jay Foad25a5e4c2010-12-01 08:53:58 +0000466void APInt::clearBit(unsigned bitPosition) {
Eric Christopher820256b2009-08-21 04:06:45 +0000467 if (isSingleWord())
Reid Spencera856b6e2007-02-18 18:38:44 +0000468 VAL &= ~maskBit(bitPosition);
Eric Christopher820256b2009-08-21 04:06:45 +0000469 else
Reid Spencera856b6e2007-02-18 18:38:44 +0000470 pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
Zhou Shengdac63782007-02-06 03:00:16 +0000471}
472
Zhou Shengdac63782007-02-06 03:00:16 +0000473/// @brief Toggle every bit to its opposite value.
Craig Topperafc9e352017-03-27 17:10:21 +0000474void APInt::flipAllBitsSlowCase() {
Craig Toppera742cb52017-04-01 21:50:08 +0000475 tcComplement(pVal, getNumWords());
Craig Topperafc9e352017-03-27 17:10:21 +0000476 clearUnusedBits();
477}
Zhou Shengdac63782007-02-06 03:00:16 +0000478
Eric Christopher820256b2009-08-21 04:06:45 +0000479/// Toggle a given bit to its opposite value whose position is given
Zhou Shengdac63782007-02-06 03:00:16 +0000480/// as "bitPosition".
481/// @brief Toggles a given bit to its opposite value.
Jay Foad25a5e4c2010-12-01 08:53:58 +0000482void APInt::flipBit(unsigned bitPosition) {
Reid Spencer1d072122007-02-16 22:36:51 +0000483 assert(bitPosition < BitWidth && "Out of the bit-width range!");
Jay Foad25a5e4c2010-12-01 08:53:58 +0000484 if ((*this)[bitPosition]) clearBit(bitPosition);
485 else setBit(bitPosition);
Zhou Shengdac63782007-02-06 03:00:16 +0000486}
487
Simon Pilgrimb02667c2017-03-10 13:44:32 +0000488void APInt::insertBits(const APInt &subBits, unsigned bitPosition) {
489 unsigned subBitWidth = subBits.getBitWidth();
490 assert(0 < subBitWidth && (subBitWidth + bitPosition) <= BitWidth &&
491 "Illegal bit insertion");
492
493 // Insertion is a direct copy.
494 if (subBitWidth == BitWidth) {
495 *this = subBits;
496 return;
497 }
498
499 // Single word result can be done as a direct bitmask.
500 if (isSingleWord()) {
501 uint64_t mask = UINT64_MAX >> (APINT_BITS_PER_WORD - subBitWidth);
502 VAL &= ~(mask << bitPosition);
503 VAL |= (subBits.VAL << bitPosition);
504 return;
505 }
506
507 unsigned loBit = whichBit(bitPosition);
508 unsigned loWord = whichWord(bitPosition);
509 unsigned hi1Word = whichWord(bitPosition + subBitWidth - 1);
510
511 // Insertion within a single word can be done as a direct bitmask.
512 if (loWord == hi1Word) {
513 uint64_t mask = UINT64_MAX >> (APINT_BITS_PER_WORD - subBitWidth);
514 pVal[loWord] &= ~(mask << loBit);
515 pVal[loWord] |= (subBits.VAL << loBit);
516 return;
517 }
518
519 // Insert on word boundaries.
520 if (loBit == 0) {
521 // Direct copy whole words.
522 unsigned numWholeSubWords = subBitWidth / APINT_BITS_PER_WORD;
523 memcpy(pVal + loWord, subBits.getRawData(),
524 numWholeSubWords * APINT_WORD_SIZE);
525
526 // Mask+insert remaining bits.
527 unsigned remainingBits = subBitWidth % APINT_BITS_PER_WORD;
528 if (remainingBits != 0) {
529 uint64_t mask = UINT64_MAX >> (APINT_BITS_PER_WORD - remainingBits);
530 pVal[hi1Word] &= ~mask;
531 pVal[hi1Word] |= subBits.getWord(subBitWidth - 1);
532 }
533 return;
534 }
535
536 // General case - set/clear individual bits in dst based on src.
537 // TODO - there is scope for optimization here, but at the moment this code
538 // path is barely used so prefer readability over performance.
539 for (unsigned i = 0; i != subBitWidth; ++i) {
540 if (subBits[i])
541 setBit(bitPosition + i);
542 else
543 clearBit(bitPosition + i);
544 }
545}
546
Simon Pilgrim0f5fb5f2017-02-25 20:01:58 +0000547APInt APInt::extractBits(unsigned numBits, unsigned bitPosition) const {
548 assert(numBits > 0 && "Can't extract zero bits");
549 assert(bitPosition < BitWidth && (numBits + bitPosition) <= BitWidth &&
550 "Illegal bit extraction");
551
552 if (isSingleWord())
553 return APInt(numBits, VAL >> bitPosition);
554
555 unsigned loBit = whichBit(bitPosition);
556 unsigned loWord = whichWord(bitPosition);
557 unsigned hiWord = whichWord(bitPosition + numBits - 1);
558
559 // Single word result extracting bits from a single word source.
560 if (loWord == hiWord)
561 return APInt(numBits, pVal[loWord] >> loBit);
562
563 // Extracting bits that start on a source word boundary can be done
564 // as a fast memory copy.
565 if (loBit == 0)
566 return APInt(numBits, makeArrayRef(pVal + loWord, 1 + hiWord - loWord));
567
568 // General case - shift + copy source words directly into place.
569 APInt Result(numBits, 0);
570 unsigned NumSrcWords = getNumWords();
571 unsigned NumDstWords = Result.getNumWords();
572
573 for (unsigned word = 0; word < NumDstWords; ++word) {
574 uint64_t w0 = pVal[loWord + word];
575 uint64_t w1 =
576 (loWord + word + 1) < NumSrcWords ? pVal[loWord + word + 1] : 0;
577 Result.pVal[word] = (w0 >> loBit) | (w1 << (APINT_BITS_PER_WORD - loBit));
578 }
579
580 return Result.clearUnusedBits();
581}
582
Benjamin Kramer92d89982010-07-14 22:38:02 +0000583unsigned APInt::getBitsNeeded(StringRef str, uint8_t radix) {
Daniel Dunbar3a1efd112009-08-13 02:33:34 +0000584 assert(!str.empty() && "Invalid string length");
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +0000585 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 ||
Douglas Gregor663c0682011-09-14 15:54:46 +0000586 radix == 36) &&
587 "Radix should be 2, 8, 10, 16, or 36!");
Daniel Dunbar3a1efd112009-08-13 02:33:34 +0000588
589 size_t slen = str.size();
Reid Spencer9329e7b2007-04-13 19:19:07 +0000590
Eric Christopher43a1dec2009-08-21 04:10:31 +0000591 // Each computation below needs to know if it's negative.
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000592 StringRef::iterator p = str.begin();
Eric Christopher43a1dec2009-08-21 04:10:31 +0000593 unsigned isNegative = *p == '-';
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000594 if (*p == '-' || *p == '+') {
595 p++;
Reid Spencer9329e7b2007-04-13 19:19:07 +0000596 slen--;
Eric Christopher43a1dec2009-08-21 04:10:31 +0000597 assert(slen && "String is only a sign, needs a value.");
Reid Spencer9329e7b2007-04-13 19:19:07 +0000598 }
Eric Christopher43a1dec2009-08-21 04:10:31 +0000599
Reid Spencer9329e7b2007-04-13 19:19:07 +0000600 // For radixes of power-of-two values, the bits required is accurately and
601 // easily computed
602 if (radix == 2)
603 return slen + isNegative;
604 if (radix == 8)
605 return slen * 3 + isNegative;
606 if (radix == 16)
607 return slen * 4 + isNegative;
608
Douglas Gregor663c0682011-09-14 15:54:46 +0000609 // FIXME: base 36
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +0000610
Reid Spencer9329e7b2007-04-13 19:19:07 +0000611 // This is grossly inefficient but accurate. We could probably do something
612 // with a computation of roughly slen*64/20 and then adjust by the value of
613 // the first few digits. But, I'm not sure how accurate that could be.
614
615 // Compute a sufficient number of bits that is always large enough but might
Erick Tryzelaardadb15712009-08-21 03:15:28 +0000616 // be too large. This avoids the assertion in the constructor. This
617 // calculation doesn't work appropriately for the numbers 0-9, so just use 4
618 // bits in that case.
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +0000619 unsigned sufficient
Douglas Gregor663c0682011-09-14 15:54:46 +0000620 = radix == 10? (slen == 1 ? 4 : slen * 64/18)
621 : (slen == 1 ? 7 : slen * 16/3);
Reid Spencer9329e7b2007-04-13 19:19:07 +0000622
623 // Convert to the actual binary value.
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000624 APInt tmp(sufficient, StringRef(p, slen), radix);
Reid Spencer9329e7b2007-04-13 19:19:07 +0000625
Erick Tryzelaardadb15712009-08-21 03:15:28 +0000626 // Compute how many bits are required. If the log is infinite, assume we need
627 // just bit.
628 unsigned log = tmp.logBase2();
629 if (log == (unsigned)-1) {
630 return isNegative + 1;
631 } else {
632 return isNegative + log + 1;
633 }
Reid Spencer9329e7b2007-04-13 19:19:07 +0000634}
635
Chandler Carruth71bd7d12012-03-04 12:02:57 +0000636hash_code llvm::hash_value(const APInt &Arg) {
637 if (Arg.isSingleWord())
638 return hash_combine(Arg.VAL);
Reid Spencerb2bc9852007-02-26 21:02:27 +0000639
Chandler Carruth71bd7d12012-03-04 12:02:57 +0000640 return hash_combine_range(Arg.pVal, Arg.pVal + Arg.getNumWords());
Reid Spencerb2bc9852007-02-26 21:02:27 +0000641}
642
Benjamin Kramerb4b51502015-03-25 16:49:59 +0000643bool APInt::isSplat(unsigned SplatSizeInBits) const {
644 assert(getBitWidth() % SplatSizeInBits == 0 &&
645 "SplatSizeInBits must divide width!");
646 // We can check that all parts of an integer are equal by making use of a
647 // little trick: rotate and check if it's still the same value.
648 return *this == rotl(SplatSizeInBits);
649}
650
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000651/// This function returns the high "numBits" bits of this APInt.
Chris Lattner77527f52009-01-21 18:09:24 +0000652APInt APInt::getHiBits(unsigned numBits) const {
Craig Toppere7e35602017-03-31 18:48:14 +0000653 return this->lshr(BitWidth - numBits);
Zhou Shengdac63782007-02-06 03:00:16 +0000654}
655
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000656/// This function returns the low "numBits" bits of this APInt.
Chris Lattner77527f52009-01-21 18:09:24 +0000657APInt APInt::getLoBits(unsigned numBits) const {
Craig Toppere7e35602017-03-31 18:48:14 +0000658 APInt Result(getLowBitsSet(BitWidth, numBits));
659 Result &= *this;
660 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000661}
662
Chris Lattner77527f52009-01-21 18:09:24 +0000663unsigned APInt::countLeadingZerosSlowCase() const {
Matthias Brauna6be4e82016-02-15 20:06:22 +0000664 unsigned Count = 0;
665 for (int i = getNumWords()-1; i >= 0; --i) {
Craig Topper55229b72017-04-02 19:17:22 +0000666 uint64_t V = pVal[i];
Matthias Brauna6be4e82016-02-15 20:06:22 +0000667 if (V == 0)
Chris Lattner1ac3e252008-08-20 17:02:31 +0000668 Count += APINT_BITS_PER_WORD;
669 else {
Matthias Brauna6be4e82016-02-15 20:06:22 +0000670 Count += llvm::countLeadingZeros(V);
Chris Lattner1ac3e252008-08-20 17:02:31 +0000671 break;
Reid Spencer74cf82e2007-02-21 00:29:48 +0000672 }
Zhou Shengdac63782007-02-06 03:00:16 +0000673 }
Matthias Brauna6be4e82016-02-15 20:06:22 +0000674 // Adjust for unused bits in the most significant word (they are zero).
675 unsigned Mod = BitWidth % APINT_BITS_PER_WORD;
676 Count -= Mod > 0 ? APINT_BITS_PER_WORD - Mod : 0;
John McCalldf951bd2010-02-03 03:42:44 +0000677 return Count;
Zhou Shengdac63782007-02-06 03:00:16 +0000678}
679
Chris Lattner77527f52009-01-21 18:09:24 +0000680unsigned APInt::countLeadingOnes() const {
Reid Spencer31acef52007-02-27 21:59:26 +0000681 if (isSingleWord())
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000682 return llvm::countLeadingOnes(VAL << (APINT_BITS_PER_WORD - BitWidth));
Reid Spencer31acef52007-02-27 21:59:26 +0000683
Chris Lattner77527f52009-01-21 18:09:24 +0000684 unsigned highWordBits = BitWidth % APINT_BITS_PER_WORD;
Torok Edwinec39eb82009-01-27 18:06:03 +0000685 unsigned shift;
686 if (!highWordBits) {
687 highWordBits = APINT_BITS_PER_WORD;
688 shift = 0;
689 } else {
690 shift = APINT_BITS_PER_WORD - highWordBits;
691 }
Reid Spencer31acef52007-02-27 21:59:26 +0000692 int i = getNumWords() - 1;
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000693 unsigned Count = llvm::countLeadingOnes(pVal[i] << shift);
Reid Spencer31acef52007-02-27 21:59:26 +0000694 if (Count == highWordBits) {
695 for (i--; i >= 0; --i) {
696 if (pVal[i] == -1ULL)
697 Count += APINT_BITS_PER_WORD;
698 else {
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000699 Count += llvm::countLeadingOnes(pVal[i]);
Reid Spencer31acef52007-02-27 21:59:26 +0000700 break;
701 }
702 }
703 }
704 return Count;
705}
706
Chris Lattner77527f52009-01-21 18:09:24 +0000707unsigned APInt::countTrailingZeros() const {
Zhou Shengdac63782007-02-06 03:00:16 +0000708 if (isSingleWord())
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000709 return std::min(unsigned(llvm::countTrailingZeros(VAL)), BitWidth);
Chris Lattner77527f52009-01-21 18:09:24 +0000710 unsigned Count = 0;
711 unsigned i = 0;
Reid Spenceraa8dcfe2007-02-26 07:44:38 +0000712 for (; i < getNumWords() && pVal[i] == 0; ++i)
713 Count += APINT_BITS_PER_WORD;
714 if (i < getNumWords())
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000715 Count += llvm::countTrailingZeros(pVal[i]);
Chris Lattnerc2c4c742007-11-23 22:36:25 +0000716 return std::min(Count, BitWidth);
Zhou Shengdac63782007-02-06 03:00:16 +0000717}
718
Chris Lattner77527f52009-01-21 18:09:24 +0000719unsigned APInt::countTrailingOnesSlowCase() const {
720 unsigned Count = 0;
721 unsigned i = 0;
Dan Gohmanc354ebd2008-02-14 22:38:45 +0000722 for (; i < getNumWords() && pVal[i] == -1ULL; ++i)
Dan Gohman8b4fa9d2008-02-13 21:11:05 +0000723 Count += APINT_BITS_PER_WORD;
724 if (i < getNumWords())
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000725 Count += llvm::countTrailingOnes(pVal[i]);
Dan Gohman8b4fa9d2008-02-13 21:11:05 +0000726 return std::min(Count, BitWidth);
727}
728
Chris Lattner77527f52009-01-21 18:09:24 +0000729unsigned APInt::countPopulationSlowCase() const {
730 unsigned Count = 0;
731 for (unsigned i = 0; i < getNumWords(); ++i)
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000732 Count += llvm::countPopulation(pVal[i]);
Zhou Shengdac63782007-02-06 03:00:16 +0000733 return Count;
734}
735
Reid Spencer1d072122007-02-16 22:36:51 +0000736APInt APInt::byteSwap() const {
737 assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
738 if (BitWidth == 16)
Jeff Cohene06855e2007-03-20 20:42:36 +0000739 return APInt(BitWidth, ByteSwap_16(uint16_t(VAL)));
Richard Smith4f9a8082011-11-23 21:33:37 +0000740 if (BitWidth == 32)
Chris Lattner77527f52009-01-21 18:09:24 +0000741 return APInt(BitWidth, ByteSwap_32(unsigned(VAL)));
Richard Smith4f9a8082011-11-23 21:33:37 +0000742 if (BitWidth == 48) {
Chris Lattner77527f52009-01-21 18:09:24 +0000743 unsigned Tmp1 = unsigned(VAL >> 16);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000744 Tmp1 = ByteSwap_32(Tmp1);
Jeff Cohene06855e2007-03-20 20:42:36 +0000745 uint16_t Tmp2 = uint16_t(VAL);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000746 Tmp2 = ByteSwap_16(Tmp2);
Jeff Cohene06855e2007-03-20 20:42:36 +0000747 return APInt(BitWidth, (uint64_t(Tmp2) << 32) | Tmp1);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000748 }
Richard Smith4f9a8082011-11-23 21:33:37 +0000749 if (BitWidth == 64)
750 return APInt(BitWidth, ByteSwap_64(VAL));
751
752 APInt Result(getNumWords() * APINT_BITS_PER_WORD, 0);
753 for (unsigned I = 0, N = getNumWords(); I != N; ++I)
754 Result.pVal[I] = ByteSwap_64(pVal[N - I - 1]);
755 if (Result.BitWidth != BitWidth) {
Richard Smith55bd3752017-04-13 20:29:59 +0000756 Result.lshrInPlace(Result.BitWidth - BitWidth);
Richard Smith4f9a8082011-11-23 21:33:37 +0000757 Result.BitWidth = BitWidth;
758 }
759 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000760}
761
Matt Arsenault155dda92016-03-21 15:00:35 +0000762APInt APInt::reverseBits() const {
763 switch (BitWidth) {
764 case 64:
765 return APInt(BitWidth, llvm::reverseBits<uint64_t>(VAL));
766 case 32:
767 return APInt(BitWidth, llvm::reverseBits<uint32_t>(VAL));
768 case 16:
769 return APInt(BitWidth, llvm::reverseBits<uint16_t>(VAL));
770 case 8:
771 return APInt(BitWidth, llvm::reverseBits<uint8_t>(VAL));
772 default:
773 break;
774 }
775
776 APInt Val(*this);
777 APInt Reversed(*this);
778 int S = BitWidth - 1;
779
780 const APInt One(BitWidth, 1);
781
782 for ((Val = Val.lshr(1)); Val != 0; (Val = Val.lshr(1))) {
783 Reversed <<= 1;
784 Reversed |= (Val & One);
785 --S;
786 }
787
788 Reversed <<= S;
789 return Reversed;
790}
791
Craig Topper278ebd22017-04-01 20:30:57 +0000792APInt llvm::APIntOps::GreatestCommonDivisor(APInt A, APInt B) {
Richard Smith55bd3752017-04-13 20:29:59 +0000793 // Fast-path a common case.
794 if (A == B) return A;
795
796 // Corner cases: if either operand is zero, the other is the gcd.
797 if (!A) return B;
798 if (!B) return A;
799
800 // Count common powers of 2 and remove all other powers of 2.
801 unsigned Pow2;
802 {
803 unsigned Pow2_A = A.countTrailingZeros();
804 unsigned Pow2_B = B.countTrailingZeros();
805 if (Pow2_A > Pow2_B) {
806 A.lshrInPlace(Pow2_A - Pow2_B);
807 Pow2 = Pow2_B;
808 } else if (Pow2_B > Pow2_A) {
809 B.lshrInPlace(Pow2_B - Pow2_A);
810 Pow2 = Pow2_A;
811 } else {
812 Pow2 = Pow2_A;
813 }
Zhou Shengdac63782007-02-06 03:00:16 +0000814 }
Richard Smith55bd3752017-04-13 20:29:59 +0000815
816 // Both operands are odd multiples of 2^Pow_2:
817 //
818 // gcd(a, b) = gcd(|a - b| / 2^i, min(a, b))
819 //
820 // This is a modified version of Stein's algorithm, taking advantage of
821 // efficient countTrailingZeros().
822 while (A != B) {
823 if (A.ugt(B)) {
824 A -= B;
825 A.lshrInPlace(A.countTrailingZeros() - Pow2);
826 } else {
827 B -= A;
828 B.lshrInPlace(B.countTrailingZeros() - Pow2);
829 }
830 }
831
Zhou Shengdac63782007-02-06 03:00:16 +0000832 return A;
833}
Chris Lattner28cbd1d2007-02-06 05:38:37 +0000834
Chris Lattner77527f52009-01-21 18:09:24 +0000835APInt llvm::APIntOps::RoundDoubleToAPInt(double Double, unsigned width) {
Zhou Shengd707d632007-02-12 20:02:55 +0000836 union {
837 double D;
838 uint64_t I;
839 } T;
840 T.D = Double;
Reid Spencer974551a2007-02-27 01:28:10 +0000841
842 // Get the sign bit from the highest order bit
Zhou Shengd707d632007-02-12 20:02:55 +0000843 bool isNeg = T.I >> 63;
Reid Spencer974551a2007-02-27 01:28:10 +0000844
845 // Get the 11-bit exponent and adjust for the 1023 bit bias
Zhou Shengd707d632007-02-12 20:02:55 +0000846 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
Reid Spencer974551a2007-02-27 01:28:10 +0000847
848 // If the exponent is negative, the value is < 0 so just return 0.
Zhou Shengd707d632007-02-12 20:02:55 +0000849 if (exp < 0)
Reid Spencer66d0d572007-02-28 01:30:08 +0000850 return APInt(width, 0u);
Reid Spencer974551a2007-02-27 01:28:10 +0000851
852 // Extract the mantissa by clearing the top 12 bits (sign + exponent).
853 uint64_t mantissa = (T.I & (~0ULL >> 12)) | 1ULL << 52;
854
855 // If the exponent doesn't shift all bits out of the mantissa
Zhou Shengd707d632007-02-12 20:02:55 +0000856 if (exp < 52)
Eric Christopher820256b2009-08-21 04:06:45 +0000857 return isNeg ? -APInt(width, mantissa >> (52 - exp)) :
Reid Spencer54abdcf2007-02-27 18:23:40 +0000858 APInt(width, mantissa >> (52 - exp));
859
860 // If the client didn't provide enough bits for us to shift the mantissa into
861 // then the result is undefined, just return 0
862 if (width <= exp - 52)
863 return APInt(width, 0);
Reid Spencer974551a2007-02-27 01:28:10 +0000864
865 // Otherwise, we have to shift the mantissa bits up to the right location
Reid Spencer54abdcf2007-02-27 18:23:40 +0000866 APInt Tmp(width, mantissa);
Chris Lattner77527f52009-01-21 18:09:24 +0000867 Tmp = Tmp.shl((unsigned)exp - 52);
Zhou Shengd707d632007-02-12 20:02:55 +0000868 return isNeg ? -Tmp : Tmp;
869}
870
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000871/// This function converts this APInt to a double.
Zhou Shengd707d632007-02-12 20:02:55 +0000872/// The layout for double is as following (IEEE Standard 754):
873/// --------------------------------------
874/// | Sign Exponent Fraction Bias |
875/// |-------------------------------------- |
876/// | 1[63] 11[62-52] 52[51-00] 1023 |
Eric Christopher820256b2009-08-21 04:06:45 +0000877/// --------------------------------------
Reid Spencer1d072122007-02-16 22:36:51 +0000878double APInt::roundToDouble(bool isSigned) const {
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000879
880 // Handle the simple case where the value is contained in one uint64_t.
Dale Johannesen54be7852009-08-12 18:04:11 +0000881 // It is wrong to optimize getWord(0) to VAL; there might be more than one word.
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000882 if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
883 if (isSigned) {
David Majnemer03992262016-06-24 21:15:36 +0000884 int64_t sext = SignExtend64(getWord(0), BitWidth);
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000885 return double(sext);
886 } else
Dale Johannesen34c08bb2009-08-12 17:42:34 +0000887 return double(getWord(0));
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000888 }
889
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000890 // Determine if the value is negative.
Reid Spencer1d072122007-02-16 22:36:51 +0000891 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000892
893 // Construct the absolute value if we're negative.
Zhou Shengd707d632007-02-12 20:02:55 +0000894 APInt Tmp(isNeg ? -(*this) : (*this));
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000895
896 // Figure out how many bits we're using.
Chris Lattner77527f52009-01-21 18:09:24 +0000897 unsigned n = Tmp.getActiveBits();
Zhou Shengd707d632007-02-12 20:02:55 +0000898
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000899 // The exponent (without bias normalization) is just the number of bits
900 // we are using. Note that the sign bit is gone since we constructed the
901 // absolute value.
902 uint64_t exp = n;
Zhou Shengd707d632007-02-12 20:02:55 +0000903
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000904 // Return infinity for exponent overflow
905 if (exp > 1023) {
906 if (!isSigned || !isNeg)
Jeff Cohene06855e2007-03-20 20:42:36 +0000907 return std::numeric_limits<double>::infinity();
Eric Christopher820256b2009-08-21 04:06:45 +0000908 else
Jeff Cohene06855e2007-03-20 20:42:36 +0000909 return -std::numeric_limits<double>::infinity();
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000910 }
911 exp += 1023; // Increment for 1023 bias
912
913 // Number of bits in mantissa is 52. To obtain the mantissa value, we must
914 // extract the high 52 bits from the correct words in pVal.
Zhou Shengd707d632007-02-12 20:02:55 +0000915 uint64_t mantissa;
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000916 unsigned hiWord = whichWord(n-1);
917 if (hiWord == 0) {
918 mantissa = Tmp.pVal[0];
919 if (n > 52)
920 mantissa >>= n - 52; // shift down, we want the top 52 bits.
921 } else {
922 assert(hiWord > 0 && "huh?");
923 uint64_t hibits = Tmp.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
924 uint64_t lobits = Tmp.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
925 mantissa = hibits | lobits;
926 }
927
Zhou Shengd707d632007-02-12 20:02:55 +0000928 // The leading bit of mantissa is implicit, so get rid of it.
Reid Spencerfbd48a52007-02-18 00:44:22 +0000929 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
Zhou Shengd707d632007-02-12 20:02:55 +0000930 union {
931 double D;
932 uint64_t I;
933 } T;
934 T.I = sign | (exp << 52) | mantissa;
935 return T.D;
936}
937
Reid Spencer1d072122007-02-16 22:36:51 +0000938// Truncate to new width.
Jay Foad583abbc2010-12-07 08:25:19 +0000939APInt APInt::trunc(unsigned width) const {
Reid Spencer1d072122007-02-16 22:36:51 +0000940 assert(width < BitWidth && "Invalid APInt Truncate request");
Chris Lattner1ac3e252008-08-20 17:02:31 +0000941 assert(width && "Can't truncate to 0 bits");
Jay Foad583abbc2010-12-07 08:25:19 +0000942
943 if (width <= APINT_BITS_PER_WORD)
944 return APInt(width, getRawData()[0]);
945
946 APInt Result(getMemory(getNumWords(width)), width);
947
948 // Copy full words.
949 unsigned i;
950 for (i = 0; i != width / APINT_BITS_PER_WORD; i++)
951 Result.pVal[i] = pVal[i];
952
953 // Truncate and copy any partial word.
954 unsigned bits = (0 - width) % APINT_BITS_PER_WORD;
955 if (bits != 0)
956 Result.pVal[i] = pVal[i] << bits >> bits;
957
958 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +0000959}
960
961// Sign extend to a new width.
Jay Foad583abbc2010-12-07 08:25:19 +0000962APInt APInt::sext(unsigned width) const {
Reid Spencer1d072122007-02-16 22:36:51 +0000963 assert(width > BitWidth && "Invalid APInt SignExtend request");
Jay Foad583abbc2010-12-07 08:25:19 +0000964
965 if (width <= APINT_BITS_PER_WORD) {
966 uint64_t val = VAL << (APINT_BITS_PER_WORD - BitWidth);
967 val = (int64_t)val >> (width - BitWidth);
968 return APInt(width, val >> (APINT_BITS_PER_WORD - width));
Reid Spencerb6b5cc32007-02-25 23:44:53 +0000969 }
970
Jay Foad583abbc2010-12-07 08:25:19 +0000971 APInt Result(getMemory(getNumWords(width)), width);
Reid Spencerb6b5cc32007-02-25 23:44:53 +0000972
Jay Foad583abbc2010-12-07 08:25:19 +0000973 // Copy full words.
974 unsigned i;
975 uint64_t word = 0;
976 for (i = 0; i != BitWidth / APINT_BITS_PER_WORD; i++) {
977 word = getRawData()[i];
978 Result.pVal[i] = word;
Reid Spencerb6b5cc32007-02-25 23:44:53 +0000979 }
980
Jay Foad583abbc2010-12-07 08:25:19 +0000981 // Read and sign-extend any partial word.
982 unsigned bits = (0 - BitWidth) % APINT_BITS_PER_WORD;
983 if (bits != 0)
984 word = (int64_t)getRawData()[i] << bits >> bits;
985 else
986 word = (int64_t)word >> (APINT_BITS_PER_WORD - 1);
987
988 // Write remaining full words.
989 for (; i != width / APINT_BITS_PER_WORD; i++) {
990 Result.pVal[i] = word;
991 word = (int64_t)word >> (APINT_BITS_PER_WORD - 1);
Reid Spencerb6b5cc32007-02-25 23:44:53 +0000992 }
Jay Foad583abbc2010-12-07 08:25:19 +0000993
994 // Write any partial word.
995 bits = (0 - width) % APINT_BITS_PER_WORD;
996 if (bits != 0)
997 Result.pVal[i] = word << bits >> bits;
998
999 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +00001000}
1001
1002// Zero extend to a new width.
Jay Foad583abbc2010-12-07 08:25:19 +00001003APInt APInt::zext(unsigned width) const {
Reid Spencer1d072122007-02-16 22:36:51 +00001004 assert(width > BitWidth && "Invalid APInt ZeroExtend request");
Jay Foad583abbc2010-12-07 08:25:19 +00001005
1006 if (width <= APINT_BITS_PER_WORD)
1007 return APInt(width, VAL);
1008
1009 APInt Result(getMemory(getNumWords(width)), width);
1010
1011 // Copy words.
1012 unsigned i;
1013 for (i = 0; i != getNumWords(); i++)
1014 Result.pVal[i] = getRawData()[i];
1015
1016 // Zero remaining words.
1017 memset(&Result.pVal[i], 0, (Result.getNumWords() - i) * APINT_WORD_SIZE);
1018
1019 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +00001020}
1021
Jay Foad583abbc2010-12-07 08:25:19 +00001022APInt APInt::zextOrTrunc(unsigned width) const {
Reid Spencer742d1702007-03-01 17:15:32 +00001023 if (BitWidth < width)
1024 return zext(width);
1025 if (BitWidth > width)
1026 return trunc(width);
1027 return *this;
1028}
1029
Jay Foad583abbc2010-12-07 08:25:19 +00001030APInt APInt::sextOrTrunc(unsigned width) const {
Reid Spencer742d1702007-03-01 17:15:32 +00001031 if (BitWidth < width)
1032 return sext(width);
1033 if (BitWidth > width)
1034 return trunc(width);
1035 return *this;
1036}
1037
Rafael Espindolabb893fe2012-01-27 23:33:07 +00001038APInt APInt::zextOrSelf(unsigned width) const {
1039 if (BitWidth < width)
1040 return zext(width);
1041 return *this;
1042}
1043
1044APInt APInt::sextOrSelf(unsigned width) const {
1045 if (BitWidth < width)
1046 return sext(width);
1047 return *this;
1048}
1049
Zhou Shenge93db8f2007-02-09 07:48:24 +00001050/// Arithmetic right-shift this APInt by shiftAmt.
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001051/// @brief Arithmetic right-shift function.
Dan Gohman105c1d42008-02-29 01:40:47 +00001052APInt APInt::ashr(const APInt &shiftAmt) const {
Chris Lattner77527f52009-01-21 18:09:24 +00001053 return ashr((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001054}
1055
1056/// Arithmetic right-shift this APInt by shiftAmt.
1057/// @brief Arithmetic right-shift function.
Chris Lattner77527f52009-01-21 18:09:24 +00001058APInt APInt::ashr(unsigned shiftAmt) const {
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001059 assert(shiftAmt <= BitWidth && "Invalid shift amount");
Reid Spencer1825dd02007-03-02 22:39:11 +00001060 // Handle a degenerate case
1061 if (shiftAmt == 0)
1062 return *this;
1063
1064 // Handle single word shifts with built-in ashr
Reid Spencer522ca7c2007-02-25 01:56:07 +00001065 if (isSingleWord()) {
1066 if (shiftAmt == BitWidth)
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001067 return APInt(BitWidth, 0); // undefined
Jonathan Roelofs851b79d2016-08-10 19:50:14 +00001068 return APInt(BitWidth, SignExtend64(VAL, BitWidth) >> shiftAmt);
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001069 }
Reid Spencer522ca7c2007-02-25 01:56:07 +00001070
Reid Spencer1825dd02007-03-02 22:39:11 +00001071 // If all the bits were shifted out, the result is, technically, undefined.
1072 // We return -1 if it was negative, 0 otherwise. We check this early to avoid
1073 // issues in the algorithm below.
Chris Lattnerdad2d092007-05-03 18:15:36 +00001074 if (shiftAmt == BitWidth) {
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001075 if (isNegative())
Zhou Sheng1247c072008-06-05 13:27:38 +00001076 return APInt(BitWidth, -1ULL, true);
Reid Spencera41e93b2007-02-25 19:32:03 +00001077 else
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001078 return APInt(BitWidth, 0);
Chris Lattnerdad2d092007-05-03 18:15:36 +00001079 }
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001080
1081 // Create some space for the result.
1082 uint64_t * val = new uint64_t[getNumWords()];
1083
Reid Spencer1825dd02007-03-02 22:39:11 +00001084 // Compute some values needed by the following shift algorithms
Chris Lattner77527f52009-01-21 18:09:24 +00001085 unsigned wordShift = shiftAmt % APINT_BITS_PER_WORD; // bits to shift per word
1086 unsigned offset = shiftAmt / APINT_BITS_PER_WORD; // word offset for shift
1087 unsigned breakWord = getNumWords() - 1 - offset; // last word affected
1088 unsigned bitsInWord = whichBit(BitWidth); // how many bits in last word?
Reid Spencer1825dd02007-03-02 22:39:11 +00001089 if (bitsInWord == 0)
1090 bitsInWord = APINT_BITS_PER_WORD;
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001091
1092 // If we are shifting whole words, just move whole words
1093 if (wordShift == 0) {
Reid Spencer1825dd02007-03-02 22:39:11 +00001094 // Move the words containing significant bits
Chris Lattner77527f52009-01-21 18:09:24 +00001095 for (unsigned i = 0; i <= breakWord; ++i)
Reid Spencer1825dd02007-03-02 22:39:11 +00001096 val[i] = pVal[i+offset]; // move whole word
1097
1098 // Adjust the top significant word for sign bit fill, if negative
1099 if (isNegative())
1100 if (bitsInWord < APINT_BITS_PER_WORD)
1101 val[breakWord] |= ~0ULL << bitsInWord; // set high bits
1102 } else {
Eric Christopher820256b2009-08-21 04:06:45 +00001103 // Shift the low order words
Chris Lattner77527f52009-01-21 18:09:24 +00001104 for (unsigned i = 0; i < breakWord; ++i) {
Reid Spencer1825dd02007-03-02 22:39:11 +00001105 // This combines the shifted corresponding word with the low bits from
1106 // the next word (shifted into this word's high bits).
Eric Christopher820256b2009-08-21 04:06:45 +00001107 val[i] = (pVal[i+offset] >> wordShift) |
Reid Spencer1825dd02007-03-02 22:39:11 +00001108 (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift));
1109 }
1110
1111 // Shift the break word. In this case there are no bits from the next word
1112 // to include in this word.
1113 val[breakWord] = pVal[breakWord+offset] >> wordShift;
1114
Alp Tokercb402912014-01-24 17:20:08 +00001115 // Deal with sign extension in the break word, and possibly the word before
Reid Spencer1825dd02007-03-02 22:39:11 +00001116 // it.
Chris Lattnerdad2d092007-05-03 18:15:36 +00001117 if (isNegative()) {
Reid Spencer1825dd02007-03-02 22:39:11 +00001118 if (wordShift > bitsInWord) {
1119 if (breakWord > 0)
Eric Christopher820256b2009-08-21 04:06:45 +00001120 val[breakWord-1] |=
Reid Spencer1825dd02007-03-02 22:39:11 +00001121 ~0ULL << (APINT_BITS_PER_WORD - (wordShift - bitsInWord));
1122 val[breakWord] |= ~0ULL;
Eric Christopher820256b2009-08-21 04:06:45 +00001123 } else
Reid Spencer1825dd02007-03-02 22:39:11 +00001124 val[breakWord] |= (~0ULL << (bitsInWord - wordShift));
Chris Lattnerdad2d092007-05-03 18:15:36 +00001125 }
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001126 }
1127
Reid Spencer1825dd02007-03-02 22:39:11 +00001128 // Remaining words are 0 or -1, just assign them.
1129 uint64_t fillValue = (isNegative() ? -1ULL : 0);
Chris Lattner77527f52009-01-21 18:09:24 +00001130 for (unsigned i = breakWord+1; i < getNumWords(); ++i)
Reid Spencer1825dd02007-03-02 22:39:11 +00001131 val[i] = fillValue;
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001132 APInt Result(val, BitWidth);
1133 Result.clearUnusedBits();
1134 return Result;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001135}
1136
Zhou Shenge93db8f2007-02-09 07:48:24 +00001137/// Logical right-shift this APInt by shiftAmt.
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001138/// @brief Logical right-shift function.
Dan Gohman105c1d42008-02-29 01:40:47 +00001139APInt APInt::lshr(const APInt &shiftAmt) const {
Chris Lattner77527f52009-01-21 18:09:24 +00001140 return lshr((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001141}
1142
1143/// Logical right-shift this APInt by shiftAmt.
1144/// @brief Logical right-shift function.
Craig Topper9575d8f2017-04-17 21:43:43 +00001145void APInt::lshrInPlace(unsigned ShiftAmt) {
Chris Lattnerdad2d092007-05-03 18:15:36 +00001146 if (isSingleWord()) {
Craig Topper9575d8f2017-04-17 21:43:43 +00001147 if (ShiftAmt >= BitWidth)
Richard Smith55bd3752017-04-13 20:29:59 +00001148 VAL = 0;
Eric Christopher820256b2009-08-21 04:06:45 +00001149 else
Craig Topper9575d8f2017-04-17 21:43:43 +00001150 VAL >>= ShiftAmt;
Richard Smith55bd3752017-04-13 20:29:59 +00001151 return;
Chris Lattnerdad2d092007-05-03 18:15:36 +00001152 }
Reid Spencer522ca7c2007-02-25 01:56:07 +00001153
Craig Topper9575d8f2017-04-17 21:43:43 +00001154 return tcShiftRight(pVal, getNumWords(), ShiftAmt);
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001155}
1156
Zhou Shenge93db8f2007-02-09 07:48:24 +00001157/// Left-shift this APInt by shiftAmt.
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001158/// @brief Left-shift function.
Dan Gohman105c1d42008-02-29 01:40:47 +00001159APInt APInt::shl(const APInt &shiftAmt) const {
Nick Lewycky030c4502009-01-19 17:42:33 +00001160 // It's undefined behavior in C to shift by BitWidth or greater.
Chris Lattner77527f52009-01-21 18:09:24 +00001161 return shl((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001162}
1163
Craig Toppera8a4f0d2017-04-18 04:39:48 +00001164void APInt::shlSlowCase(unsigned ShiftAmt) {
1165 tcShiftLeft(pVal, getNumWords(), ShiftAmt);
1166 clearUnusedBits();
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001167}
1168
Joey Gouly51c0ae52017-02-07 11:58:22 +00001169// Calculate the rotate amount modulo the bit width.
1170static unsigned rotateModulo(unsigned BitWidth, const APInt &rotateAmt) {
1171 unsigned rotBitWidth = rotateAmt.getBitWidth();
1172 APInt rot = rotateAmt;
1173 if (rotBitWidth < BitWidth) {
1174 // Extend the rotate APInt, so that the urem doesn't divide by 0.
1175 // e.g. APInt(1, 32) would give APInt(1, 0).
1176 rot = rotateAmt.zext(BitWidth);
1177 }
1178 rot = rot.urem(APInt(rot.getBitWidth(), BitWidth));
1179 return rot.getLimitedValue(BitWidth);
1180}
1181
Dan Gohman105c1d42008-02-29 01:40:47 +00001182APInt APInt::rotl(const APInt &rotateAmt) const {
Joey Gouly51c0ae52017-02-07 11:58:22 +00001183 return rotl(rotateModulo(BitWidth, rotateAmt));
Dan Gohman105c1d42008-02-29 01:40:47 +00001184}
1185
Chris Lattner77527f52009-01-21 18:09:24 +00001186APInt APInt::rotl(unsigned rotateAmt) const {
Eli Friedman2aae94f2011-12-22 03:15:35 +00001187 rotateAmt %= BitWidth;
Reid Spencer98ed7db2007-05-14 00:15:28 +00001188 if (rotateAmt == 0)
1189 return *this;
Eli Friedman2aae94f2011-12-22 03:15:35 +00001190 return shl(rotateAmt) | lshr(BitWidth - rotateAmt);
Reid Spencer4c50b522007-05-13 23:44:59 +00001191}
1192
Dan Gohman105c1d42008-02-29 01:40:47 +00001193APInt APInt::rotr(const APInt &rotateAmt) const {
Joey Gouly51c0ae52017-02-07 11:58:22 +00001194 return rotr(rotateModulo(BitWidth, rotateAmt));
Dan Gohman105c1d42008-02-29 01:40:47 +00001195}
1196
Chris Lattner77527f52009-01-21 18:09:24 +00001197APInt APInt::rotr(unsigned rotateAmt) const {
Eli Friedman2aae94f2011-12-22 03:15:35 +00001198 rotateAmt %= BitWidth;
Reid Spencer98ed7db2007-05-14 00:15:28 +00001199 if (rotateAmt == 0)
1200 return *this;
Eli Friedman2aae94f2011-12-22 03:15:35 +00001201 return lshr(rotateAmt) | shl(BitWidth - rotateAmt);
Reid Spencer4c50b522007-05-13 23:44:59 +00001202}
Reid Spencerd99feaf2007-03-01 05:39:56 +00001203
1204// Square Root - this method computes and returns the square root of "this".
1205// Three mechanisms are used for computation. For small values (<= 5 bits),
1206// a table lookup is done. This gets some performance for common cases. For
1207// values using less than 52 bits, the value is converted to double and then
1208// the libc sqrt function is called. The result is rounded and then converted
1209// back to a uint64_t which is then used to construct the result. Finally,
Eric Christopher820256b2009-08-21 04:06:45 +00001210// the Babylonian method for computing square roots is used.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001211APInt APInt::sqrt() const {
1212
1213 // Determine the magnitude of the value.
Chris Lattner77527f52009-01-21 18:09:24 +00001214 unsigned magnitude = getActiveBits();
Reid Spencerd99feaf2007-03-01 05:39:56 +00001215
1216 // Use a fast table for some small values. This also gets rid of some
1217 // rounding errors in libc sqrt for small values.
1218 if (magnitude <= 5) {
Reid Spencer2f6ad4d2007-03-01 17:47:31 +00001219 static const uint8_t results[32] = {
Reid Spencerc8841d22007-03-01 06:23:32 +00001220 /* 0 */ 0,
1221 /* 1- 2 */ 1, 1,
Eric Christopher820256b2009-08-21 04:06:45 +00001222 /* 3- 6 */ 2, 2, 2, 2,
Reid Spencerc8841d22007-03-01 06:23:32 +00001223 /* 7-12 */ 3, 3, 3, 3, 3, 3,
1224 /* 13-20 */ 4, 4, 4, 4, 4, 4, 4, 4,
1225 /* 21-30 */ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
1226 /* 31 */ 6
1227 };
1228 return APInt(BitWidth, results[ (isSingleWord() ? VAL : pVal[0]) ]);
Reid Spencerd99feaf2007-03-01 05:39:56 +00001229 }
1230
1231 // If the magnitude of the value fits in less than 52 bits (the precision of
1232 // an IEEE double precision floating point value), then we can use the
1233 // libc sqrt function which will probably use a hardware sqrt computation.
1234 // This should be faster than the algorithm below.
Jeff Cohenb622c112007-03-05 00:00:42 +00001235 if (magnitude < 52) {
Eric Christopher820256b2009-08-21 04:06:45 +00001236 return APInt(BitWidth,
Reid Spencerd99feaf2007-03-01 05:39:56 +00001237 uint64_t(::round(::sqrt(double(isSingleWord()?VAL:pVal[0])))));
Jeff Cohenb622c112007-03-05 00:00:42 +00001238 }
Reid Spencerd99feaf2007-03-01 05:39:56 +00001239
1240 // Okay, all the short cuts are exhausted. We must compute it. The following
1241 // is a classical Babylonian method for computing the square root. This code
Sanjay Patel4cb54e02014-09-11 15:41:01 +00001242 // was adapted to APInt from a wikipedia article on such computations.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001243 // See http://www.wikipedia.org/ and go to the page named
Eric Christopher820256b2009-08-21 04:06:45 +00001244 // Calculate_an_integer_square_root.
Chris Lattner77527f52009-01-21 18:09:24 +00001245 unsigned nbits = BitWidth, i = 4;
Reid Spencerd99feaf2007-03-01 05:39:56 +00001246 APInt testy(BitWidth, 16);
1247 APInt x_old(BitWidth, 1);
1248 APInt x_new(BitWidth, 0);
1249 APInt two(BitWidth, 2);
1250
1251 // Select a good starting value using binary logarithms.
Eric Christopher820256b2009-08-21 04:06:45 +00001252 for (;; i += 2, testy = testy.shl(2))
Reid Spencerd99feaf2007-03-01 05:39:56 +00001253 if (i >= nbits || this->ule(testy)) {
1254 x_old = x_old.shl(i / 2);
1255 break;
1256 }
1257
Eric Christopher820256b2009-08-21 04:06:45 +00001258 // Use the Babylonian method to arrive at the integer square root:
Reid Spencerd99feaf2007-03-01 05:39:56 +00001259 for (;;) {
1260 x_new = (this->udiv(x_old) + x_old).udiv(two);
1261 if (x_old.ule(x_new))
1262 break;
1263 x_old = x_new;
1264 }
1265
1266 // Make sure we return the closest approximation
Eric Christopher820256b2009-08-21 04:06:45 +00001267 // NOTE: The rounding calculation below is correct. It will produce an
Reid Spencercf817562007-03-02 04:21:55 +00001268 // off-by-one discrepancy with results from pari/gp. That discrepancy has been
Eric Christopher820256b2009-08-21 04:06:45 +00001269 // determined to be a rounding issue with pari/gp as it begins to use a
Reid Spencercf817562007-03-02 04:21:55 +00001270 // floating point representation after 192 bits. There are no discrepancies
1271 // between this algorithm and pari/gp for bit widths < 192 bits.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001272 APInt square(x_old * x_old);
1273 APInt nextSquare((x_old + 1) * (x_old +1));
1274 if (this->ult(square))
1275 return x_old;
David Blaikie54c94622011-12-01 20:58:30 +00001276 assert(this->ule(nextSquare) && "Error in APInt::sqrt computation");
1277 APInt midpoint((nextSquare - square).udiv(two));
1278 APInt offset(*this - square);
1279 if (offset.ult(midpoint))
1280 return x_old;
Reid Spencerd99feaf2007-03-01 05:39:56 +00001281 return x_old + 1;
1282}
1283
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001284/// Computes the multiplicative inverse of this APInt for a given modulo. The
1285/// iterative extended Euclidean algorithm is used to solve for this value,
1286/// however we simplify it to speed up calculating only the inverse, and take
1287/// advantage of div+rem calculations. We also use some tricks to avoid copying
1288/// (potentially large) APInts around.
1289APInt APInt::multiplicativeInverse(const APInt& modulo) const {
1290 assert(ult(modulo) && "This APInt must be smaller than the modulo");
1291
1292 // Using the properties listed at the following web page (accessed 06/21/08):
1293 // http://www.numbertheory.org/php/euclid.html
1294 // (especially the properties numbered 3, 4 and 9) it can be proved that
1295 // BitWidth bits suffice for all the computations in the algorithm implemented
1296 // below. More precisely, this number of bits suffice if the multiplicative
1297 // inverse exists, but may not suffice for the general extended Euclidean
1298 // algorithm.
1299
1300 APInt r[2] = { modulo, *this };
1301 APInt t[2] = { APInt(BitWidth, 0), APInt(BitWidth, 1) };
1302 APInt q(BitWidth, 0);
Eric Christopher820256b2009-08-21 04:06:45 +00001303
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001304 unsigned i;
1305 for (i = 0; r[i^1] != 0; i ^= 1) {
1306 // An overview of the math without the confusing bit-flipping:
1307 // q = r[i-2] / r[i-1]
1308 // r[i] = r[i-2] % r[i-1]
1309 // t[i] = t[i-2] - t[i-1] * q
1310 udivrem(r[i], r[i^1], q, r[i]);
1311 t[i] -= t[i^1] * q;
1312 }
1313
1314 // If this APInt and the modulo are not coprime, there is no multiplicative
1315 // inverse, so return 0. We check this by looking at the next-to-last
1316 // remainder, which is the gcd(*this,modulo) as calculated by the Euclidean
1317 // algorithm.
1318 if (r[i] != 1)
1319 return APInt(BitWidth, 0);
1320
1321 // The next-to-last t is the multiplicative inverse. However, we are
1322 // interested in a positive inverse. Calcuate a positive one from a negative
1323 // one if necessary. A simple addition of the modulo suffices because
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00001324 // abs(t[i]) is known to be less than *this/2 (see the link above).
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001325 return t[i].isNegative() ? t[i] + modulo : t[i];
1326}
1327
Jay Foadfe0c6482009-04-30 10:15:35 +00001328/// Calculate the magic numbers required to implement a signed integer division
1329/// by a constant as a sequence of multiplies, adds and shifts. Requires that
1330/// the divisor not be 0, 1, or -1. Taken from "Hacker's Delight", Henry S.
1331/// Warren, Jr., chapter 10.
1332APInt::ms APInt::magic() const {
1333 const APInt& d = *this;
1334 unsigned p;
1335 APInt ad, anc, delta, q1, r1, q2, r2, t;
Jay Foadfe0c6482009-04-30 10:15:35 +00001336 APInt signedMin = APInt::getSignedMinValue(d.getBitWidth());
Jay Foadfe0c6482009-04-30 10:15:35 +00001337 struct ms mag;
Eric Christopher820256b2009-08-21 04:06:45 +00001338
Jay Foadfe0c6482009-04-30 10:15:35 +00001339 ad = d.abs();
1340 t = signedMin + (d.lshr(d.getBitWidth() - 1));
1341 anc = t - 1 - t.urem(ad); // absolute value of nc
1342 p = d.getBitWidth() - 1; // initialize p
1343 q1 = signedMin.udiv(anc); // initialize q1 = 2p/abs(nc)
1344 r1 = signedMin - q1*anc; // initialize r1 = rem(2p,abs(nc))
1345 q2 = signedMin.udiv(ad); // initialize q2 = 2p/abs(d)
1346 r2 = signedMin - q2*ad; // initialize r2 = rem(2p,abs(d))
1347 do {
1348 p = p + 1;
1349 q1 = q1<<1; // update q1 = 2p/abs(nc)
1350 r1 = r1<<1; // update r1 = rem(2p/abs(nc))
1351 if (r1.uge(anc)) { // must be unsigned comparison
1352 q1 = q1 + 1;
1353 r1 = r1 - anc;
1354 }
1355 q2 = q2<<1; // update q2 = 2p/abs(d)
1356 r2 = r2<<1; // update r2 = rem(2p/abs(d))
1357 if (r2.uge(ad)) { // must be unsigned comparison
1358 q2 = q2 + 1;
1359 r2 = r2 - ad;
1360 }
1361 delta = ad - r2;
Cameron Zwarich8731d0c2011-02-21 00:22:02 +00001362 } while (q1.ult(delta) || (q1 == delta && r1 == 0));
Eric Christopher820256b2009-08-21 04:06:45 +00001363
Jay Foadfe0c6482009-04-30 10:15:35 +00001364 mag.m = q2 + 1;
1365 if (d.isNegative()) mag.m = -mag.m; // resulting magic number
1366 mag.s = p - d.getBitWidth(); // resulting shift
1367 return mag;
1368}
1369
1370/// Calculate the magic numbers required to implement an unsigned integer
1371/// division by a constant as a sequence of multiplies, adds and shifts.
1372/// Requires that the divisor not be 0. Taken from "Hacker's Delight", Henry
1373/// S. Warren, Jr., chapter 10.
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001374/// LeadingZeros can be used to simplify the calculation if the upper bits
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001375/// of the divided value are known zero.
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001376APInt::mu APInt::magicu(unsigned LeadingZeros) const {
Jay Foadfe0c6482009-04-30 10:15:35 +00001377 const APInt& d = *this;
1378 unsigned p;
1379 APInt nc, delta, q1, r1, q2, r2;
1380 struct mu magu;
1381 magu.a = 0; // initialize "add" indicator
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001382 APInt allOnes = APInt::getAllOnesValue(d.getBitWidth()).lshr(LeadingZeros);
Jay Foadfe0c6482009-04-30 10:15:35 +00001383 APInt signedMin = APInt::getSignedMinValue(d.getBitWidth());
1384 APInt signedMax = APInt::getSignedMaxValue(d.getBitWidth());
1385
Benjamin Kramer3aab6a82012-07-11 18:31:59 +00001386 nc = allOnes - (allOnes - d).urem(d);
Jay Foadfe0c6482009-04-30 10:15:35 +00001387 p = d.getBitWidth() - 1; // initialize p
1388 q1 = signedMin.udiv(nc); // initialize q1 = 2p/nc
1389 r1 = signedMin - q1*nc; // initialize r1 = rem(2p,nc)
1390 q2 = signedMax.udiv(d); // initialize q2 = (2p-1)/d
1391 r2 = signedMax - q2*d; // initialize r2 = rem((2p-1),d)
1392 do {
1393 p = p + 1;
1394 if (r1.uge(nc - r1)) {
1395 q1 = q1 + q1 + 1; // update q1
1396 r1 = r1 + r1 - nc; // update r1
1397 }
1398 else {
1399 q1 = q1+q1; // update q1
1400 r1 = r1+r1; // update r1
1401 }
1402 if ((r2 + 1).uge(d - r2)) {
1403 if (q2.uge(signedMax)) magu.a = 1;
1404 q2 = q2+q2 + 1; // update q2
1405 r2 = r2+r2 + 1 - d; // update r2
1406 }
1407 else {
1408 if (q2.uge(signedMin)) magu.a = 1;
1409 q2 = q2+q2; // update q2
1410 r2 = r2+r2 + 1; // update r2
1411 }
1412 delta = d - 1 - r2;
1413 } while (p < d.getBitWidth()*2 &&
1414 (q1.ult(delta) || (q1 == delta && r1 == 0)));
1415 magu.m = q2 + 1; // resulting magic number
1416 magu.s = p - d.getBitWidth(); // resulting shift
1417 return magu;
1418}
1419
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001420/// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
1421/// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
1422/// variables here have the same names as in the algorithm. Comments explain
1423/// the algorithm and any deviation from it.
Chris Lattner77527f52009-01-21 18:09:24 +00001424static void KnuthDiv(unsigned *u, unsigned *v, unsigned *q, unsigned* r,
1425 unsigned m, unsigned n) {
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001426 assert(u && "Must provide dividend");
1427 assert(v && "Must provide divisor");
1428 assert(q && "Must provide quotient");
Yaron Keren39fc5a62015-03-26 19:45:19 +00001429 assert(u != v && u != q && v != q && "Must use different memory");
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001430 assert(n>1 && "n must be > 1");
1431
Yaron Keren39fc5a62015-03-26 19:45:19 +00001432 // b denotes the base of the number system. In our case b is 2^32.
George Burgess IV381fc0e2016-08-25 01:05:08 +00001433 const uint64_t b = uint64_t(1) << 32;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001434
David Greenef32fcb42010-01-05 01:28:52 +00001435 DEBUG(dbgs() << "KnuthDiv: m=" << m << " n=" << n << '\n');
1436 DEBUG(dbgs() << "KnuthDiv: original:");
1437 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
1438 DEBUG(dbgs() << " by");
1439 DEBUG(for (int i = n; i >0; i--) dbgs() << " " << v[i-1]);
1440 DEBUG(dbgs() << '\n');
Eric Christopher820256b2009-08-21 04:06:45 +00001441 // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
1442 // u and v by d. Note that we have taken Knuth's advice here to use a power
1443 // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
1444 // 2 allows us to shift instead of multiply and it is easy to determine the
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001445 // shift amount from the leading zeros. We are basically normalizing the u
1446 // and v so that its high bits are shifted to the top of v's range without
1447 // overflow. Note that this can require an extra word in u so that u must
1448 // be of length m+n+1.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001449 unsigned shift = countLeadingZeros(v[n-1]);
Chris Lattner77527f52009-01-21 18:09:24 +00001450 unsigned v_carry = 0;
1451 unsigned u_carry = 0;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001452 if (shift) {
Chris Lattner77527f52009-01-21 18:09:24 +00001453 for (unsigned i = 0; i < m+n; ++i) {
1454 unsigned u_tmp = u[i] >> (32 - shift);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001455 u[i] = (u[i] << shift) | u_carry;
1456 u_carry = u_tmp;
Reid Spencer100502d2007-02-17 03:16:00 +00001457 }
Chris Lattner77527f52009-01-21 18:09:24 +00001458 for (unsigned i = 0; i < n; ++i) {
1459 unsigned v_tmp = v[i] >> (32 - shift);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001460 v[i] = (v[i] << shift) | v_carry;
1461 v_carry = v_tmp;
1462 }
1463 }
1464 u[m+n] = u_carry;
Yaron Keren39fc5a62015-03-26 19:45:19 +00001465
David Greenef32fcb42010-01-05 01:28:52 +00001466 DEBUG(dbgs() << "KnuthDiv: normal:");
1467 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
1468 DEBUG(dbgs() << " by");
1469 DEBUG(for (int i = n; i >0; i--) dbgs() << " " << v[i-1]);
1470 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001471
1472 // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
1473 int j = m;
1474 do {
David Greenef32fcb42010-01-05 01:28:52 +00001475 DEBUG(dbgs() << "KnuthDiv: quotient digit #" << j << '\n');
Eric Christopher820256b2009-08-21 04:06:45 +00001476 // D3. [Calculate q'.].
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001477 // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
1478 // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
1479 // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
1480 // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test
1481 // on v[n-2] determines at high speed most of the cases in which the trial
Eric Christopher820256b2009-08-21 04:06:45 +00001482 // value qp is one too large, and it eliminates all cases where qp is two
1483 // too large.
Reid Spencercb292e42007-02-23 01:57:13 +00001484 uint64_t dividend = ((uint64_t(u[j+n]) << 32) + u[j+n-1]);
David Greenef32fcb42010-01-05 01:28:52 +00001485 DEBUG(dbgs() << "KnuthDiv: dividend == " << dividend << '\n');
Reid Spencercb292e42007-02-23 01:57:13 +00001486 uint64_t qp = dividend / v[n-1];
1487 uint64_t rp = dividend % v[n-1];
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001488 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1489 qp--;
1490 rp += v[n-1];
Reid Spencerdf6cf5a2007-02-24 10:01:42 +00001491 if (rp < b && (qp == b || qp*v[n-2] > b*rp + u[j+n-2]))
Reid Spencera5e0d202007-02-24 03:58:46 +00001492 qp--;
Reid Spencercb292e42007-02-23 01:57:13 +00001493 }
David Greenef32fcb42010-01-05 01:28:52 +00001494 DEBUG(dbgs() << "KnuthDiv: qp == " << qp << ", rp == " << rp << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001495
Reid Spencercb292e42007-02-23 01:57:13 +00001496 // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with
1497 // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation
1498 // consists of a simple multiplication by a one-place number, combined with
Eric Christopher820256b2009-08-21 04:06:45 +00001499 // a subtraction.
Yaron Keren39fc5a62015-03-26 19:45:19 +00001500 // The digits (u[j+n]...u[j]) should be kept positive; if the result of
1501 // this step is actually negative, (u[j+n]...u[j]) should be left as the
1502 // true value plus b**(n+1), namely as the b's complement of
1503 // the true value, and a "borrow" to the left should be remembered.
Pawel Bylica86ac4472015-04-24 07:38:39 +00001504 int64_t borrow = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001505 for (unsigned i = 0; i < n; ++i) {
Pawel Bylica86ac4472015-04-24 07:38:39 +00001506 uint64_t p = uint64_t(qp) * uint64_t(v[i]);
1507 int64_t subres = int64_t(u[j+i]) - borrow - (unsigned)p;
1508 u[j+i] = (unsigned)subres;
1509 borrow = (p >> 32) - (subres >> 32);
1510 DEBUG(dbgs() << "KnuthDiv: u[j+i] = " << u[j+i]
Daniel Dunbar763ace92009-07-13 05:27:30 +00001511 << ", borrow = " << borrow << '\n');
Reid Spencera5e0d202007-02-24 03:58:46 +00001512 }
Pawel Bylica86ac4472015-04-24 07:38:39 +00001513 bool isNeg = u[j+n] < borrow;
1514 u[j+n] -= (unsigned)borrow;
1515
David Greenef32fcb42010-01-05 01:28:52 +00001516 DEBUG(dbgs() << "KnuthDiv: after subtraction:");
1517 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
1518 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001519
Eric Christopher820256b2009-08-21 04:06:45 +00001520 // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001521 // negative, go to step D6; otherwise go on to step D7.
Chris Lattner77527f52009-01-21 18:09:24 +00001522 q[j] = (unsigned)qp;
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001523 if (isNeg) {
Eric Christopher820256b2009-08-21 04:06:45 +00001524 // D6. [Add back]. The probability that this step is necessary is very
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001525 // small, on the order of only 2/b. Make sure that test data accounts for
Eric Christopher820256b2009-08-21 04:06:45 +00001526 // this possibility. Decrease q[j] by 1
Reid Spencercb292e42007-02-23 01:57:13 +00001527 q[j]--;
Eric Christopher820256b2009-08-21 04:06:45 +00001528 // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]).
1529 // A carry will occur to the left of u[j+n], and it should be ignored
Reid Spencercb292e42007-02-23 01:57:13 +00001530 // since it cancels with the borrow that occurred in D4.
1531 bool carry = false;
Chris Lattner77527f52009-01-21 18:09:24 +00001532 for (unsigned i = 0; i < n; i++) {
1533 unsigned limit = std::min(u[j+i],v[i]);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001534 u[j+i] += v[i] + carry;
Reid Spencera5e0d202007-02-24 03:58:46 +00001535 carry = u[j+i] < limit || (carry && u[j+i] == limit);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001536 }
Reid Spencera5e0d202007-02-24 03:58:46 +00001537 u[j+n] += carry;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001538 }
David Greenef32fcb42010-01-05 01:28:52 +00001539 DEBUG(dbgs() << "KnuthDiv: after correction:");
Yaron Keren39fc5a62015-03-26 19:45:19 +00001540 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
David Greenef32fcb42010-01-05 01:28:52 +00001541 DEBUG(dbgs() << "\nKnuthDiv: digit result = " << q[j] << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001542
Reid Spencercb292e42007-02-23 01:57:13 +00001543 // D7. [Loop on j.] Decrease j by one. Now if j >= 0, go back to D3.
1544 } while (--j >= 0);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001545
David Greenef32fcb42010-01-05 01:28:52 +00001546 DEBUG(dbgs() << "KnuthDiv: quotient:");
1547 DEBUG(for (int i = m; i >=0; i--) dbgs() <<" " << q[i]);
1548 DEBUG(dbgs() << '\n');
Reid Spencera5e0d202007-02-24 03:58:46 +00001549
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001550 // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
1551 // remainder may be obtained by dividing u[...] by d. If r is non-null we
1552 // compute the remainder (urem uses this).
1553 if (r) {
1554 // The value d is expressed by the "shift" value above since we avoided
1555 // multiplication by d by using a shift left. So, all we have to do is
Simon Pilgrim0099beb2017-03-09 13:57:04 +00001556 // shift right here.
Reid Spencer468ad9112007-02-24 20:38:01 +00001557 if (shift) {
Chris Lattner77527f52009-01-21 18:09:24 +00001558 unsigned carry = 0;
David Greenef32fcb42010-01-05 01:28:52 +00001559 DEBUG(dbgs() << "KnuthDiv: remainder:");
Reid Spencer468ad9112007-02-24 20:38:01 +00001560 for (int i = n-1; i >= 0; i--) {
1561 r[i] = (u[i] >> shift) | carry;
1562 carry = u[i] << (32 - shift);
David Greenef32fcb42010-01-05 01:28:52 +00001563 DEBUG(dbgs() << " " << r[i]);
Reid Spencer468ad9112007-02-24 20:38:01 +00001564 }
1565 } else {
1566 for (int i = n-1; i >= 0; i--) {
1567 r[i] = u[i];
David Greenef32fcb42010-01-05 01:28:52 +00001568 DEBUG(dbgs() << " " << r[i]);
Reid Spencer468ad9112007-02-24 20:38:01 +00001569 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001570 }
David Greenef32fcb42010-01-05 01:28:52 +00001571 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001572 }
David Greenef32fcb42010-01-05 01:28:52 +00001573 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001574}
1575
Benjamin Kramerc321e532016-06-08 19:09:22 +00001576void APInt::divide(const APInt &LHS, unsigned lhsWords, const APInt &RHS,
1577 unsigned rhsWords, APInt *Quotient, APInt *Remainder) {
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001578 assert(lhsWords >= rhsWords && "Fractional result");
1579
Eric Christopher820256b2009-08-21 04:06:45 +00001580 // First, compose the values into an array of 32-bit words instead of
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001581 // 64-bit words. This is a necessity of both the "short division" algorithm
Dan Gohman4a618822010-02-10 16:03:48 +00001582 // and the Knuth "classical algorithm" which requires there to be native
Eric Christopher820256b2009-08-21 04:06:45 +00001583 // operations for +, -, and * on an m bit value with an m*2 bit result. We
1584 // can't use 64-bit operands here because we don't have native results of
1585 // 128-bits. Furthermore, casting the 64-bit values to 32-bit values won't
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001586 // work on large-endian machines.
Dan Gohmancff69532009-04-01 18:45:54 +00001587 uint64_t mask = ~0ull >> (sizeof(unsigned)*CHAR_BIT);
Chris Lattner77527f52009-01-21 18:09:24 +00001588 unsigned n = rhsWords * 2;
1589 unsigned m = (lhsWords * 2) - n;
Reid Spencer522ca7c2007-02-25 01:56:07 +00001590
1591 // Allocate space for the temporary values we need either on the stack, if
1592 // it will fit, or on the heap if it won't.
Chris Lattner77527f52009-01-21 18:09:24 +00001593 unsigned SPACE[128];
Craig Topperc10719f2014-04-07 04:17:22 +00001594 unsigned *U = nullptr;
1595 unsigned *V = nullptr;
1596 unsigned *Q = nullptr;
1597 unsigned *R = nullptr;
Reid Spencer522ca7c2007-02-25 01:56:07 +00001598 if ((Remainder?4:3)*n+2*m+1 <= 128) {
1599 U = &SPACE[0];
1600 V = &SPACE[m+n+1];
1601 Q = &SPACE[(m+n+1) + n];
1602 if (Remainder)
1603 R = &SPACE[(m+n+1) + n + (m+n)];
1604 } else {
Chris Lattner77527f52009-01-21 18:09:24 +00001605 U = new unsigned[m + n + 1];
1606 V = new unsigned[n];
1607 Q = new unsigned[m+n];
Reid Spencer522ca7c2007-02-25 01:56:07 +00001608 if (Remainder)
Chris Lattner77527f52009-01-21 18:09:24 +00001609 R = new unsigned[n];
Reid Spencer522ca7c2007-02-25 01:56:07 +00001610 }
1611
1612 // Initialize the dividend
Chris Lattner77527f52009-01-21 18:09:24 +00001613 memset(U, 0, (m+n+1)*sizeof(unsigned));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001614 for (unsigned i = 0; i < lhsWords; ++i) {
Reid Spencer867b4062007-02-22 00:58:45 +00001615 uint64_t tmp = (LHS.getNumWords() == 1 ? LHS.VAL : LHS.pVal[i]);
Chris Lattner77527f52009-01-21 18:09:24 +00001616 U[i * 2] = (unsigned)(tmp & mask);
Dan Gohmancff69532009-04-01 18:45:54 +00001617 U[i * 2 + 1] = (unsigned)(tmp >> (sizeof(unsigned)*CHAR_BIT));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001618 }
1619 U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
1620
Reid Spencer522ca7c2007-02-25 01:56:07 +00001621 // Initialize the divisor
Chris Lattner77527f52009-01-21 18:09:24 +00001622 memset(V, 0, (n)*sizeof(unsigned));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001623 for (unsigned i = 0; i < rhsWords; ++i) {
Reid Spencer867b4062007-02-22 00:58:45 +00001624 uint64_t tmp = (RHS.getNumWords() == 1 ? RHS.VAL : RHS.pVal[i]);
Chris Lattner77527f52009-01-21 18:09:24 +00001625 V[i * 2] = (unsigned)(tmp & mask);
Dan Gohmancff69532009-04-01 18:45:54 +00001626 V[i * 2 + 1] = (unsigned)(tmp >> (sizeof(unsigned)*CHAR_BIT));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001627 }
1628
Reid Spencer522ca7c2007-02-25 01:56:07 +00001629 // initialize the quotient and remainder
Chris Lattner77527f52009-01-21 18:09:24 +00001630 memset(Q, 0, (m+n) * sizeof(unsigned));
Reid Spencer522ca7c2007-02-25 01:56:07 +00001631 if (Remainder)
Chris Lattner77527f52009-01-21 18:09:24 +00001632 memset(R, 0, n * sizeof(unsigned));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001633
Eric Christopher820256b2009-08-21 04:06:45 +00001634 // Now, adjust m and n for the Knuth division. n is the number of words in
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001635 // the divisor. m is the number of words by which the dividend exceeds the
Eric Christopher820256b2009-08-21 04:06:45 +00001636 // divisor (i.e. m+n is the length of the dividend). These sizes must not
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001637 // contain any zero words or the Knuth algorithm fails.
1638 for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
1639 n--;
1640 m++;
1641 }
1642 for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
1643 m--;
1644
1645 // If we're left with only a single word for the divisor, Knuth doesn't work
1646 // so we implement the short division algorithm here. This is much simpler
1647 // and faster because we are certain that we can divide a 64-bit quantity
1648 // by a 32-bit quantity at hardware speed and short division is simply a
1649 // series of such operations. This is just like doing short division but we
1650 // are using base 2^32 instead of base 10.
1651 assert(n != 0 && "Divide by zero?");
1652 if (n == 1) {
Chris Lattner77527f52009-01-21 18:09:24 +00001653 unsigned divisor = V[0];
1654 unsigned remainder = 0;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001655 for (int i = m+n-1; i >= 0; i--) {
1656 uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i];
1657 if (partial_dividend == 0) {
1658 Q[i] = 0;
1659 remainder = 0;
1660 } else if (partial_dividend < divisor) {
1661 Q[i] = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001662 remainder = (unsigned)partial_dividend;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001663 } else if (partial_dividend == divisor) {
1664 Q[i] = 1;
1665 remainder = 0;
1666 } else {
Chris Lattner77527f52009-01-21 18:09:24 +00001667 Q[i] = (unsigned)(partial_dividend / divisor);
1668 remainder = (unsigned)(partial_dividend - (Q[i] * divisor));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001669 }
1670 }
1671 if (R)
1672 R[0] = remainder;
1673 } else {
1674 // Now we're ready to invoke the Knuth classical divide algorithm. In this
1675 // case n > 1.
1676 KnuthDiv(U, V, Q, R, m, n);
1677 }
1678
1679 // If the caller wants the quotient
1680 if (Quotient) {
1681 // Set up the Quotient value's memory.
1682 if (Quotient->BitWidth != LHS.BitWidth) {
1683 if (Quotient->isSingleWord())
1684 Quotient->VAL = 0;
1685 else
Reid Spencer7c16cd22007-02-26 23:38:21 +00001686 delete [] Quotient->pVal;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001687 Quotient->BitWidth = LHS.BitWidth;
1688 if (!Quotient->isSingleWord())
Reid Spencer58a6a432007-02-21 08:21:52 +00001689 Quotient->pVal = getClearedMemory(Quotient->getNumWords());
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001690 } else
Jay Foad25a5e4c2010-12-01 08:53:58 +00001691 Quotient->clearAllBits();
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001692
Eric Christopher820256b2009-08-21 04:06:45 +00001693 // The quotient is in Q. Reconstitute the quotient into Quotient's low
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001694 // order words.
Yaron Keren39fc5a62015-03-26 19:45:19 +00001695 // This case is currently dead as all users of divide() handle trivial cases
1696 // earlier.
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001697 if (lhsWords == 1) {
Eric Christopher820256b2009-08-21 04:06:45 +00001698 uint64_t tmp =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001699 uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2));
1700 if (Quotient->isSingleWord())
1701 Quotient->VAL = tmp;
1702 else
1703 Quotient->pVal[0] = tmp;
1704 } else {
1705 assert(!Quotient->isSingleWord() && "Quotient APInt not large enough");
1706 for (unsigned i = 0; i < lhsWords; ++i)
Eric Christopher820256b2009-08-21 04:06:45 +00001707 Quotient->pVal[i] =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001708 uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1709 }
1710 }
1711
1712 // If the caller wants the remainder
1713 if (Remainder) {
1714 // Set up the Remainder value's memory.
1715 if (Remainder->BitWidth != RHS.BitWidth) {
1716 if (Remainder->isSingleWord())
1717 Remainder->VAL = 0;
1718 else
Reid Spencer7c16cd22007-02-26 23:38:21 +00001719 delete [] Remainder->pVal;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001720 Remainder->BitWidth = RHS.BitWidth;
1721 if (!Remainder->isSingleWord())
Reid Spencer58a6a432007-02-21 08:21:52 +00001722 Remainder->pVal = getClearedMemory(Remainder->getNumWords());
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001723 } else
Jay Foad25a5e4c2010-12-01 08:53:58 +00001724 Remainder->clearAllBits();
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001725
1726 // The remainder is in R. Reconstitute the remainder into Remainder's low
1727 // order words.
1728 if (rhsWords == 1) {
Eric Christopher820256b2009-08-21 04:06:45 +00001729 uint64_t tmp =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001730 uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2));
1731 if (Remainder->isSingleWord())
1732 Remainder->VAL = tmp;
1733 else
1734 Remainder->pVal[0] = tmp;
1735 } else {
1736 assert(!Remainder->isSingleWord() && "Remainder APInt not large enough");
1737 for (unsigned i = 0; i < rhsWords; ++i)
Eric Christopher820256b2009-08-21 04:06:45 +00001738 Remainder->pVal[i] =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001739 uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1740 }
1741 }
1742
1743 // Clean up the memory we allocated.
Reid Spencer522ca7c2007-02-25 01:56:07 +00001744 if (U != &SPACE[0]) {
1745 delete [] U;
1746 delete [] V;
1747 delete [] Q;
1748 delete [] R;
1749 }
Reid Spencer100502d2007-02-17 03:16:00 +00001750}
1751
Reid Spencer1d072122007-02-16 22:36:51 +00001752APInt APInt::udiv(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +00001753 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer39867762007-02-17 02:07:07 +00001754
1755 // First, deal with the easy case
1756 if (isSingleWord()) {
1757 assert(RHS.VAL != 0 && "Divide by zero?");
1758 return APInt(BitWidth, VAL / RHS.VAL);
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001759 }
Reid Spencer39867762007-02-17 02:07:07 +00001760
Reid Spencer39867762007-02-17 02:07:07 +00001761 // Get some facts about the LHS and RHS number of bits and words
Chris Lattner77527f52009-01-21 18:09:24 +00001762 unsigned rhsBits = RHS.getActiveBits();
1763 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001764 assert(rhsWords && "Divided by zero???");
Chris Lattner77527f52009-01-21 18:09:24 +00001765 unsigned lhsBits = this->getActiveBits();
1766 unsigned lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001767
1768 // Deal with some degenerate cases
Eric Christopher820256b2009-08-21 04:06:45 +00001769 if (!lhsWords)
Reid Spencer58a6a432007-02-21 08:21:52 +00001770 // 0 / X ===> 0
Eric Christopher820256b2009-08-21 04:06:45 +00001771 return APInt(BitWidth, 0);
Reid Spencer58a6a432007-02-21 08:21:52 +00001772 else if (lhsWords < rhsWords || this->ult(RHS)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001773 // X / Y ===> 0, iff X < Y
Reid Spencer58a6a432007-02-21 08:21:52 +00001774 return APInt(BitWidth, 0);
1775 } else if (*this == RHS) {
1776 // X / X ===> 1
1777 return APInt(BitWidth, 1);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001778 } else if (lhsWords == 1 && rhsWords == 1) {
Reid Spencer39867762007-02-17 02:07:07 +00001779 // All high words are zero, just use native divide
Reid Spencer58a6a432007-02-21 08:21:52 +00001780 return APInt(BitWidth, this->pVal[0] / RHS.pVal[0]);
Reid Spencer39867762007-02-17 02:07:07 +00001781 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001782
1783 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1784 APInt Quotient(1,0); // to hold result.
Craig Topperc10719f2014-04-07 04:17:22 +00001785 divide(*this, lhsWords, RHS, rhsWords, &Quotient, nullptr);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001786 return Quotient;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001787}
1788
Jakub Staszak6605c602013-02-20 00:17:42 +00001789APInt APInt::sdiv(const APInt &RHS) const {
1790 if (isNegative()) {
1791 if (RHS.isNegative())
1792 return (-(*this)).udiv(-RHS);
1793 return -((-(*this)).udiv(RHS));
1794 }
1795 if (RHS.isNegative())
1796 return -(this->udiv(-RHS));
1797 return this->udiv(RHS);
1798}
1799
Reid Spencer1d072122007-02-16 22:36:51 +00001800APInt APInt::urem(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +00001801 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer39867762007-02-17 02:07:07 +00001802 if (isSingleWord()) {
1803 assert(RHS.VAL != 0 && "Remainder by zero?");
1804 return APInt(BitWidth, VAL % RHS.VAL);
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001805 }
Reid Spencer39867762007-02-17 02:07:07 +00001806
Reid Spencer58a6a432007-02-21 08:21:52 +00001807 // Get some facts about the LHS
Chris Lattner77527f52009-01-21 18:09:24 +00001808 unsigned lhsBits = getActiveBits();
1809 unsigned lhsWords = !lhsBits ? 0 : (whichWord(lhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001810
1811 // Get some facts about the RHS
Chris Lattner77527f52009-01-21 18:09:24 +00001812 unsigned rhsBits = RHS.getActiveBits();
1813 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001814 assert(rhsWords && "Performing remainder operation by zero ???");
1815
Reid Spencer39867762007-02-17 02:07:07 +00001816 // Check the degenerate cases
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001817 if (lhsWords == 0) {
Reid Spencer58a6a432007-02-21 08:21:52 +00001818 // 0 % Y ===> 0
1819 return APInt(BitWidth, 0);
1820 } else if (lhsWords < rhsWords || this->ult(RHS)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001821 // X % Y ===> X, iff X < Y
Reid Spencer58a6a432007-02-21 08:21:52 +00001822 return *this;
1823 } else if (*this == RHS) {
Reid Spencer39867762007-02-17 02:07:07 +00001824 // X % X == 0;
Reid Spencer58a6a432007-02-21 08:21:52 +00001825 return APInt(BitWidth, 0);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001826 } else if (lhsWords == 1) {
Reid Spencer39867762007-02-17 02:07:07 +00001827 // All high words are zero, just use native remainder
Reid Spencer58a6a432007-02-21 08:21:52 +00001828 return APInt(BitWidth, pVal[0] % RHS.pVal[0]);
Reid Spencer39867762007-02-17 02:07:07 +00001829 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001830
Reid Spencer4c50b522007-05-13 23:44:59 +00001831 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001832 APInt Remainder(1,0);
Craig Topperc10719f2014-04-07 04:17:22 +00001833 divide(*this, lhsWords, RHS, rhsWords, nullptr, &Remainder);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001834 return Remainder;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001835}
Reid Spencer100502d2007-02-17 03:16:00 +00001836
Jakub Staszak6605c602013-02-20 00:17:42 +00001837APInt APInt::srem(const APInt &RHS) const {
1838 if (isNegative()) {
1839 if (RHS.isNegative())
1840 return -((-(*this)).urem(-RHS));
1841 return -((-(*this)).urem(RHS));
1842 }
1843 if (RHS.isNegative())
1844 return this->urem(-RHS);
1845 return this->urem(RHS);
1846}
1847
Eric Christopher820256b2009-08-21 04:06:45 +00001848void APInt::udivrem(const APInt &LHS, const APInt &RHS,
Reid Spencer4c50b522007-05-13 23:44:59 +00001849 APInt &Quotient, APInt &Remainder) {
David Majnemer7f039202014-12-14 09:41:56 +00001850 assert(LHS.BitWidth == RHS.BitWidth && "Bit widths must be the same");
1851
1852 // First, deal with the easy case
1853 if (LHS.isSingleWord()) {
1854 assert(RHS.VAL != 0 && "Divide by zero?");
1855 uint64_t QuotVal = LHS.VAL / RHS.VAL;
1856 uint64_t RemVal = LHS.VAL % RHS.VAL;
1857 Quotient = APInt(LHS.BitWidth, QuotVal);
1858 Remainder = APInt(LHS.BitWidth, RemVal);
1859 return;
1860 }
1861
Reid Spencer4c50b522007-05-13 23:44:59 +00001862 // Get some size facts about the dividend and divisor
Chris Lattner77527f52009-01-21 18:09:24 +00001863 unsigned lhsBits = LHS.getActiveBits();
1864 unsigned lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
1865 unsigned rhsBits = RHS.getActiveBits();
1866 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer4c50b522007-05-13 23:44:59 +00001867
1868 // Check the degenerate cases
Eric Christopher820256b2009-08-21 04:06:45 +00001869 if (lhsWords == 0) {
Reid Spencer4c50b522007-05-13 23:44:59 +00001870 Quotient = 0; // 0 / Y ===> 0
1871 Remainder = 0; // 0 % Y ===> 0
1872 return;
Eric Christopher820256b2009-08-21 04:06:45 +00001873 }
1874
1875 if (lhsWords < rhsWords || LHS.ult(RHS)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001876 Remainder = LHS; // X % Y ===> X, iff X < Y
1877 Quotient = 0; // X / Y ===> 0, iff X < Y
Reid Spencer4c50b522007-05-13 23:44:59 +00001878 return;
Eric Christopher820256b2009-08-21 04:06:45 +00001879 }
1880
Reid Spencer4c50b522007-05-13 23:44:59 +00001881 if (LHS == RHS) {
1882 Quotient = 1; // X / X ===> 1
1883 Remainder = 0; // X % X ===> 0;
1884 return;
Eric Christopher820256b2009-08-21 04:06:45 +00001885 }
1886
Reid Spencer4c50b522007-05-13 23:44:59 +00001887 if (lhsWords == 1 && rhsWords == 1) {
1888 // There is only one word to consider so use the native versions.
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001889 uint64_t lhsValue = LHS.isSingleWord() ? LHS.VAL : LHS.pVal[0];
1890 uint64_t rhsValue = RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
1891 Quotient = APInt(LHS.getBitWidth(), lhsValue / rhsValue);
1892 Remainder = APInt(LHS.getBitWidth(), lhsValue % rhsValue);
Reid Spencer4c50b522007-05-13 23:44:59 +00001893 return;
1894 }
1895
1896 // Okay, lets do it the long way
1897 divide(LHS, lhsWords, RHS, rhsWords, &Quotient, &Remainder);
1898}
1899
Jakub Staszak6605c602013-02-20 00:17:42 +00001900void APInt::sdivrem(const APInt &LHS, const APInt &RHS,
1901 APInt &Quotient, APInt &Remainder) {
1902 if (LHS.isNegative()) {
1903 if (RHS.isNegative())
1904 APInt::udivrem(-LHS, -RHS, Quotient, Remainder);
1905 else {
1906 APInt::udivrem(-LHS, RHS, Quotient, Remainder);
1907 Quotient = -Quotient;
1908 }
1909 Remainder = -Remainder;
1910 } else if (RHS.isNegative()) {
1911 APInt::udivrem(LHS, -RHS, Quotient, Remainder);
1912 Quotient = -Quotient;
1913 } else {
1914 APInt::udivrem(LHS, RHS, Quotient, Remainder);
1915 }
1916}
1917
Chris Lattner2c819b02010-10-13 23:54:10 +00001918APInt APInt::sadd_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00001919 APInt Res = *this+RHS;
1920 Overflow = isNonNegative() == RHS.isNonNegative() &&
1921 Res.isNonNegative() != isNonNegative();
1922 return Res;
1923}
1924
Chris Lattner698661c2010-10-14 00:05:07 +00001925APInt APInt::uadd_ov(const APInt &RHS, bool &Overflow) const {
1926 APInt Res = *this+RHS;
1927 Overflow = Res.ult(RHS);
1928 return Res;
1929}
1930
Chris Lattner2c819b02010-10-13 23:54:10 +00001931APInt APInt::ssub_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00001932 APInt Res = *this - RHS;
1933 Overflow = isNonNegative() != RHS.isNonNegative() &&
1934 Res.isNonNegative() != isNonNegative();
1935 return Res;
1936}
1937
Chris Lattner698661c2010-10-14 00:05:07 +00001938APInt APInt::usub_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattnerb9681ad2010-10-14 00:30:00 +00001939 APInt Res = *this-RHS;
1940 Overflow = Res.ugt(*this);
Chris Lattner698661c2010-10-14 00:05:07 +00001941 return Res;
1942}
1943
Chris Lattner2c819b02010-10-13 23:54:10 +00001944APInt APInt::sdiv_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00001945 // MININT/-1 --> overflow.
1946 Overflow = isMinSignedValue() && RHS.isAllOnesValue();
1947 return sdiv(RHS);
1948}
1949
Chris Lattner2c819b02010-10-13 23:54:10 +00001950APInt APInt::smul_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00001951 APInt Res = *this * RHS;
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +00001952
Chris Lattner79bdd882010-10-13 23:46:33 +00001953 if (*this != 0 && RHS != 0)
1954 Overflow = Res.sdiv(RHS) != *this || Res.sdiv(*this) != RHS;
1955 else
1956 Overflow = false;
1957 return Res;
1958}
1959
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001960APInt APInt::umul_ov(const APInt &RHS, bool &Overflow) const {
1961 APInt Res = *this * RHS;
1962
1963 if (*this != 0 && RHS != 0)
1964 Overflow = Res.udiv(RHS) != *this || Res.udiv(*this) != RHS;
1965 else
1966 Overflow = false;
1967 return Res;
1968}
1969
David Majnemera2521382014-10-13 21:48:30 +00001970APInt APInt::sshl_ov(const APInt &ShAmt, bool &Overflow) const {
1971 Overflow = ShAmt.uge(getBitWidth());
Chris Lattner79bdd882010-10-13 23:46:33 +00001972 if (Overflow)
David Majnemera2521382014-10-13 21:48:30 +00001973 return APInt(BitWidth, 0);
Chris Lattner79bdd882010-10-13 23:46:33 +00001974
1975 if (isNonNegative()) // Don't allow sign change.
David Majnemera2521382014-10-13 21:48:30 +00001976 Overflow = ShAmt.uge(countLeadingZeros());
Chris Lattner79bdd882010-10-13 23:46:33 +00001977 else
David Majnemera2521382014-10-13 21:48:30 +00001978 Overflow = ShAmt.uge(countLeadingOnes());
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +00001979
Chris Lattner79bdd882010-10-13 23:46:33 +00001980 return *this << ShAmt;
1981}
1982
David Majnemera2521382014-10-13 21:48:30 +00001983APInt APInt::ushl_ov(const APInt &ShAmt, bool &Overflow) const {
1984 Overflow = ShAmt.uge(getBitWidth());
1985 if (Overflow)
1986 return APInt(BitWidth, 0);
1987
1988 Overflow = ShAmt.ugt(countLeadingZeros());
1989
1990 return *this << ShAmt;
1991}
1992
Chris Lattner79bdd882010-10-13 23:46:33 +00001993
1994
1995
Benjamin Kramer92d89982010-07-14 22:38:02 +00001996void APInt::fromString(unsigned numbits, StringRef str, uint8_t radix) {
Reid Spencer1ba83352007-02-21 03:55:44 +00001997 // Check our assumptions here
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00001998 assert(!str.empty() && "Invalid string length");
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +00001999 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 ||
Douglas Gregor663c0682011-09-14 15:54:46 +00002000 radix == 36) &&
2001 "Radix should be 2, 8, 10, 16, or 36!");
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00002002
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00002003 StringRef::iterator p = str.begin();
2004 size_t slen = str.size();
2005 bool isNeg = *p == '-';
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00002006 if (*p == '-' || *p == '+') {
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00002007 p++;
2008 slen--;
Eric Christopher43a1dec2009-08-21 04:10:31 +00002009 assert(slen && "String is only a sign, needs a value.");
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00002010 }
Chris Lattnerdad2d092007-05-03 18:15:36 +00002011 assert((slen <= numbits || radix != 2) && "Insufficient bit width");
Chris Lattnerb869a0a2009-04-25 18:34:04 +00002012 assert(((slen-1)*3 <= numbits || radix != 8) && "Insufficient bit width");
2013 assert(((slen-1)*4 <= numbits || radix != 16) && "Insufficient bit width");
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002014 assert((((slen-1)*64)/22 <= numbits || radix != 10) &&
2015 "Insufficient bit width");
Reid Spencer1ba83352007-02-21 03:55:44 +00002016
2017 // Allocate memory
2018 if (!isSingleWord())
2019 pVal = getClearedMemory(getNumWords());
2020
2021 // Figure out if we can shift instead of multiply
Chris Lattner77527f52009-01-21 18:09:24 +00002022 unsigned shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0);
Reid Spencer1ba83352007-02-21 03:55:44 +00002023
Craig Topperb7d8faa2017-04-02 06:59:38 +00002024 // Set up an APInt for the radix multiplier outside the loop so we don't
Reid Spencer1ba83352007-02-21 03:55:44 +00002025 // constantly construct/destruct it.
Reid Spencer1ba83352007-02-21 03:55:44 +00002026 APInt apradix(getBitWidth(), radix);
2027
2028 // Enter digit traversal loop
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00002029 for (StringRef::iterator e = str.end(); p != e; ++p) {
Erick Tryzelaardadb15712009-08-21 03:15:28 +00002030 unsigned digit = getDigit(*p, radix);
Erick Tryzelaar60964092009-08-21 06:48:37 +00002031 assert(digit < radix && "Invalid character in digit string");
Reid Spencer1ba83352007-02-21 03:55:44 +00002032
Reid Spencera93c9812007-05-16 19:18:22 +00002033 // Shift or multiply the value by the radix
Chris Lattnerb869a0a2009-04-25 18:34:04 +00002034 if (slen > 1) {
2035 if (shift)
2036 *this <<= shift;
2037 else
2038 *this *= apradix;
2039 }
Reid Spencer1ba83352007-02-21 03:55:44 +00002040
2041 // Add in the digit we just interpreted
Craig Topperb7d8faa2017-04-02 06:59:38 +00002042 *this += digit;
Reid Spencer100502d2007-02-17 03:16:00 +00002043 }
Reid Spencerb6b5cc32007-02-25 23:44:53 +00002044 // If its negative, put it in two's complement form
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00002045 if (isNeg) {
Jakub Staszak773be0c2013-03-20 23:56:19 +00002046 --(*this);
Jay Foad25a5e4c2010-12-01 08:53:58 +00002047 this->flipAllBits();
Reid Spencerb6b5cc32007-02-25 23:44:53 +00002048 }
Reid Spencer100502d2007-02-17 03:16:00 +00002049}
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002050
Chris Lattner17f71652008-08-17 07:19:36 +00002051void APInt::toString(SmallVectorImpl<char> &Str, unsigned Radix,
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002052 bool Signed, bool formatAsCLiteral) const {
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +00002053 assert((Radix == 10 || Radix == 8 || Radix == 16 || Radix == 2 ||
Douglas Gregor663c0682011-09-14 15:54:46 +00002054 Radix == 36) &&
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00002055 "Radix should be 2, 8, 10, 16, or 36!");
Eric Christopher820256b2009-08-21 04:06:45 +00002056
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002057 const char *Prefix = "";
2058 if (formatAsCLiteral) {
2059 switch (Radix) {
2060 case 2:
2061 // Binary literals are a non-standard extension added in gcc 4.3:
2062 // http://gcc.gnu.org/onlinedocs/gcc-4.3.0/gcc/Binary-constants.html
2063 Prefix = "0b";
2064 break;
2065 case 8:
2066 Prefix = "0";
2067 break;
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00002068 case 10:
2069 break; // No prefix
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002070 case 16:
2071 Prefix = "0x";
2072 break;
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00002073 default:
2074 llvm_unreachable("Invalid radix!");
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002075 }
2076 }
2077
Chris Lattner17f71652008-08-17 07:19:36 +00002078 // First, check for a zero value and just short circuit the logic below.
2079 if (*this == 0) {
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002080 while (*Prefix) {
2081 Str.push_back(*Prefix);
2082 ++Prefix;
2083 };
Chris Lattner17f71652008-08-17 07:19:36 +00002084 Str.push_back('0');
2085 return;
2086 }
Eric Christopher820256b2009-08-21 04:06:45 +00002087
Douglas Gregor663c0682011-09-14 15:54:46 +00002088 static const char Digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Eric Christopher820256b2009-08-21 04:06:45 +00002089
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002090 if (isSingleWord()) {
Chris Lattner17f71652008-08-17 07:19:36 +00002091 char Buffer[65];
2092 char *BufPtr = Buffer+65;
Eric Christopher820256b2009-08-21 04:06:45 +00002093
Chris Lattner17f71652008-08-17 07:19:36 +00002094 uint64_t N;
Chris Lattnerb91c9032010-08-18 00:33:47 +00002095 if (!Signed) {
Chris Lattner17f71652008-08-17 07:19:36 +00002096 N = getZExtValue();
Chris Lattnerb91c9032010-08-18 00:33:47 +00002097 } else {
2098 int64_t I = getSExtValue();
2099 if (I >= 0) {
2100 N = I;
2101 } else {
2102 Str.push_back('-');
2103 N = -(uint64_t)I;
2104 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002105 }
Eric Christopher820256b2009-08-21 04:06:45 +00002106
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002107 while (*Prefix) {
2108 Str.push_back(*Prefix);
2109 ++Prefix;
2110 };
2111
Chris Lattner17f71652008-08-17 07:19:36 +00002112 while (N) {
2113 *--BufPtr = Digits[N % Radix];
2114 N /= Radix;
2115 }
2116 Str.append(BufPtr, Buffer+65);
2117 return;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002118 }
2119
Chris Lattner17f71652008-08-17 07:19:36 +00002120 APInt Tmp(*this);
Eric Christopher820256b2009-08-21 04:06:45 +00002121
Chris Lattner17f71652008-08-17 07:19:36 +00002122 if (Signed && isNegative()) {
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002123 // They want to print the signed version and it is a negative value
2124 // Flip the bits and add one to turn it into the equivalent positive
2125 // value and put a '-' in the result.
Jay Foad25a5e4c2010-12-01 08:53:58 +00002126 Tmp.flipAllBits();
Jakub Staszak773be0c2013-03-20 23:56:19 +00002127 ++Tmp;
Chris Lattner17f71652008-08-17 07:19:36 +00002128 Str.push_back('-');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002129 }
Eric Christopher820256b2009-08-21 04:06:45 +00002130
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002131 while (*Prefix) {
2132 Str.push_back(*Prefix);
2133 ++Prefix;
2134 };
2135
Chris Lattner17f71652008-08-17 07:19:36 +00002136 // We insert the digits backward, then reverse them to get the right order.
2137 unsigned StartDig = Str.size();
Eric Christopher820256b2009-08-21 04:06:45 +00002138
2139 // For the 2, 8 and 16 bit cases, we can just shift instead of divide
2140 // because the number of bits per digit (1, 3 and 4 respectively) divides
Craig Topperd7ed50d2017-04-02 06:59:36 +00002141 // equally. We just shift until the value is zero.
Douglas Gregor663c0682011-09-14 15:54:46 +00002142 if (Radix == 2 || Radix == 8 || Radix == 16) {
Chris Lattner17f71652008-08-17 07:19:36 +00002143 // Just shift tmp right for each digit width until it becomes zero
2144 unsigned ShiftAmt = (Radix == 16 ? 4 : (Radix == 8 ? 3 : 1));
2145 unsigned MaskAmt = Radix - 1;
Eric Christopher820256b2009-08-21 04:06:45 +00002146
Chris Lattner17f71652008-08-17 07:19:36 +00002147 while (Tmp != 0) {
2148 unsigned Digit = unsigned(Tmp.getRawData()[0]) & MaskAmt;
2149 Str.push_back(Digits[Digit]);
2150 Tmp = Tmp.lshr(ShiftAmt);
2151 }
2152 } else {
Douglas Gregor663c0682011-09-14 15:54:46 +00002153 APInt divisor(Radix == 10? 4 : 8, Radix);
Chris Lattner17f71652008-08-17 07:19:36 +00002154 while (Tmp != 0) {
2155 APInt APdigit(1, 0);
2156 APInt tmp2(Tmp.getBitWidth(), 0);
Eric Christopher820256b2009-08-21 04:06:45 +00002157 divide(Tmp, Tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2,
Chris Lattner17f71652008-08-17 07:19:36 +00002158 &APdigit);
Chris Lattner77527f52009-01-21 18:09:24 +00002159 unsigned Digit = (unsigned)APdigit.getZExtValue();
Chris Lattner17f71652008-08-17 07:19:36 +00002160 assert(Digit < Radix && "divide failed");
2161 Str.push_back(Digits[Digit]);
2162 Tmp = tmp2;
2163 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002164 }
Eric Christopher820256b2009-08-21 04:06:45 +00002165
Chris Lattner17f71652008-08-17 07:19:36 +00002166 // Reverse the digits before returning.
2167 std::reverse(Str.begin()+StartDig, Str.end());
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002168}
2169
Pawel Bylica6eeeac72015-04-06 13:31:39 +00002170/// Returns the APInt as a std::string. Note that this is an inefficient method.
2171/// It is better to pass in a SmallVector/SmallString to the methods above.
Chris Lattner17f71652008-08-17 07:19:36 +00002172std::string APInt::toString(unsigned Radix = 10, bool Signed = true) const {
2173 SmallString<40> S;
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002174 toString(S, Radix, Signed, /* formatAsCLiteral = */false);
Daniel Dunbar8b0b1152009-08-19 20:07:03 +00002175 return S.str();
Reid Spencer1ba83352007-02-21 03:55:44 +00002176}
Chris Lattner6b695682007-08-16 15:56:55 +00002177
Matthias Braun8c209aa2017-01-28 02:02:38 +00002178#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Kereneb2a2542016-01-29 20:50:44 +00002179LLVM_DUMP_METHOD void APInt::dump() const {
Chris Lattner17f71652008-08-17 07:19:36 +00002180 SmallString<40> S, U;
2181 this->toStringUnsigned(U);
2182 this->toStringSigned(S);
David Greenef32fcb42010-01-05 01:28:52 +00002183 dbgs() << "APInt(" << BitWidth << "b, "
Davide Italiano5a473d22017-01-31 21:26:18 +00002184 << U << "u " << S << "s)\n";
Chris Lattner17f71652008-08-17 07:19:36 +00002185}
Matthias Braun8c209aa2017-01-28 02:02:38 +00002186#endif
Chris Lattner17f71652008-08-17 07:19:36 +00002187
Chris Lattner0c19df42008-08-23 22:23:09 +00002188void APInt::print(raw_ostream &OS, bool isSigned) const {
Chris Lattner17f71652008-08-17 07:19:36 +00002189 SmallString<40> S;
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002190 this->toString(S, 10, isSigned, /* formatAsCLiteral = */false);
Yaron Keren92e1b622015-03-18 10:17:07 +00002191 OS << S;
Chris Lattner17f71652008-08-17 07:19:36 +00002192}
2193
Chris Lattner6b695682007-08-16 15:56:55 +00002194// This implements a variety of operations on a representation of
2195// arbitrary precision, two's-complement, bignum integer values.
2196
Chris Lattner96cffa62009-08-23 23:11:28 +00002197// Assumed by lowHalf, highHalf, partMSB and partLSB. A fairly safe
2198// and unrestricting assumption.
Craig Topper55229b72017-04-02 19:17:22 +00002199static_assert(APInt::APINT_BITS_PER_WORD % 2 == 0,
2200 "Part width must be divisible by 2!");
Chris Lattner6b695682007-08-16 15:56:55 +00002201
2202/* Some handy functions local to this file. */
Chris Lattner6b695682007-08-16 15:56:55 +00002203
Craig Topper76f42462017-03-28 05:32:53 +00002204/* Returns the integer part with the least significant BITS set.
2205 BITS cannot be zero. */
Craig Topper55229b72017-04-02 19:17:22 +00002206static inline APInt::WordType lowBitMask(unsigned bits) {
2207 assert(bits != 0 && bits <= APInt::APINT_BITS_PER_WORD);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002208
Craig Topper55229b72017-04-02 19:17:22 +00002209 return ~(APInt::WordType) 0 >> (APInt::APINT_BITS_PER_WORD - bits);
Craig Topper76f42462017-03-28 05:32:53 +00002210}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002211
Craig Topper76f42462017-03-28 05:32:53 +00002212/* Returns the value of the lower half of PART. */
Craig Topper55229b72017-04-02 19:17:22 +00002213static inline APInt::WordType lowHalf(APInt::WordType part) {
2214 return part & lowBitMask(APInt::APINT_BITS_PER_WORD / 2);
Craig Topper76f42462017-03-28 05:32:53 +00002215}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002216
Craig Topper76f42462017-03-28 05:32:53 +00002217/* Returns the value of the upper half of PART. */
Craig Topper55229b72017-04-02 19:17:22 +00002218static inline APInt::WordType highHalf(APInt::WordType part) {
2219 return part >> (APInt::APINT_BITS_PER_WORD / 2);
Craig Topper76f42462017-03-28 05:32:53 +00002220}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002221
Craig Topper76f42462017-03-28 05:32:53 +00002222/* Returns the bit number of the most significant set bit of a part.
2223 If the input number has no bits set -1U is returned. */
Craig Topper55229b72017-04-02 19:17:22 +00002224static unsigned partMSB(APInt::WordType value) {
Craig Topper76f42462017-03-28 05:32:53 +00002225 return findLastSet(value, ZB_Max);
2226}
Chris Lattner6b695682007-08-16 15:56:55 +00002227
Craig Topper76f42462017-03-28 05:32:53 +00002228/* Returns the bit number of the least significant set bit of a
2229 part. If the input number has no bits set -1U is returned. */
Craig Topper55229b72017-04-02 19:17:22 +00002230static unsigned partLSB(APInt::WordType value) {
Craig Topper76f42462017-03-28 05:32:53 +00002231 return findFirstSet(value, ZB_Max);
Alexander Kornienkof00654e2015-06-23 09:49:53 +00002232}
Chris Lattner6b695682007-08-16 15:56:55 +00002233
2234/* Sets the least significant part of a bignum to the input value, and
2235 zeroes out higher parts. */
Craig Topper55229b72017-04-02 19:17:22 +00002236void APInt::tcSet(WordType *dst, WordType part, unsigned parts) {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002237 assert(parts > 0);
Neil Boothb6182162007-10-08 13:47:12 +00002238
Chris Lattner6b695682007-08-16 15:56:55 +00002239 dst[0] = part;
Craig Topperb0038162017-03-28 05:32:52 +00002240 for (unsigned i = 1; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002241 dst[i] = 0;
2242}
2243
2244/* Assign one bignum to another. */
Craig Topper55229b72017-04-02 19:17:22 +00002245void APInt::tcAssign(WordType *dst, const WordType *src, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002246 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002247 dst[i] = src[i];
2248}
2249
2250/* Returns true if a bignum is zero, false otherwise. */
Craig Topper55229b72017-04-02 19:17:22 +00002251bool APInt::tcIsZero(const WordType *src, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002252 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002253 if (src[i])
2254 return false;
2255
2256 return true;
2257}
2258
2259/* Extract the given bit of a bignum; returns 0 or 1. */
Craig Topper55229b72017-04-02 19:17:22 +00002260int APInt::tcExtractBit(const WordType *parts, unsigned bit) {
Craig Topper00b47ee2017-04-02 19:35:18 +00002261 return (parts[whichWord(bit)] & maskBit(bit)) != 0;
Chris Lattner6b695682007-08-16 15:56:55 +00002262}
2263
John McCalldcb9a7a2010-02-28 02:51:25 +00002264/* Set the given bit of a bignum. */
Craig Topper55229b72017-04-02 19:17:22 +00002265void APInt::tcSetBit(WordType *parts, unsigned bit) {
Craig Topper00b47ee2017-04-02 19:35:18 +00002266 parts[whichWord(bit)] |= maskBit(bit);
Chris Lattner6b695682007-08-16 15:56:55 +00002267}
2268
John McCalldcb9a7a2010-02-28 02:51:25 +00002269/* Clears the given bit of a bignum. */
Craig Topper55229b72017-04-02 19:17:22 +00002270void APInt::tcClearBit(WordType *parts, unsigned bit) {
Craig Topper00b47ee2017-04-02 19:35:18 +00002271 parts[whichWord(bit)] &= ~maskBit(bit);
John McCalldcb9a7a2010-02-28 02:51:25 +00002272}
2273
Neil Boothc8b650a2007-10-06 00:43:45 +00002274/* Returns the bit number of the least significant set bit of a
2275 number. If the input number has no bits set -1U is returned. */
Craig Topper55229b72017-04-02 19:17:22 +00002276unsigned APInt::tcLSB(const WordType *parts, unsigned n) {
Craig Topperb0038162017-03-28 05:32:52 +00002277 for (unsigned i = 0; i < n; i++) {
2278 if (parts[i] != 0) {
2279 unsigned lsb = partLSB(parts[i]);
Chris Lattner6b695682007-08-16 15:56:55 +00002280
Craig Topper55229b72017-04-02 19:17:22 +00002281 return lsb + i * APINT_BITS_PER_WORD;
Craig Topperb0038162017-03-28 05:32:52 +00002282 }
Chris Lattner6b695682007-08-16 15:56:55 +00002283 }
2284
2285 return -1U;
2286}
2287
Neil Boothc8b650a2007-10-06 00:43:45 +00002288/* Returns the bit number of the most significant set bit of a number.
2289 If the input number has no bits set -1U is returned. */
Craig Topper55229b72017-04-02 19:17:22 +00002290unsigned APInt::tcMSB(const WordType *parts, unsigned n) {
Chris Lattner6b695682007-08-16 15:56:55 +00002291 do {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002292 --n;
Chris Lattner6b695682007-08-16 15:56:55 +00002293
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002294 if (parts[n] != 0) {
Craig Topperb0038162017-03-28 05:32:52 +00002295 unsigned msb = partMSB(parts[n]);
Chris Lattner6b695682007-08-16 15:56:55 +00002296
Craig Topper55229b72017-04-02 19:17:22 +00002297 return msb + n * APINT_BITS_PER_WORD;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002298 }
Chris Lattner6b695682007-08-16 15:56:55 +00002299 } while (n);
2300
2301 return -1U;
2302}
2303
Neil Boothb6182162007-10-08 13:47:12 +00002304/* Copy the bit vector of width srcBITS from SRC, starting at bit
2305 srcLSB, to DST, of dstCOUNT parts, such that the bit srcLSB becomes
2306 the least significant bit of DST. All high bits above srcBITS in
2307 DST are zero-filled. */
2308void
Craig Topper55229b72017-04-02 19:17:22 +00002309APInt::tcExtract(WordType *dst, unsigned dstCount, const WordType *src,
Craig Topper6a8518082017-03-28 05:32:55 +00002310 unsigned srcBits, unsigned srcLSB) {
Craig Topper55229b72017-04-02 19:17:22 +00002311 unsigned dstParts = (srcBits + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002312 assert(dstParts <= dstCount);
Neil Boothb6182162007-10-08 13:47:12 +00002313
Craig Topper55229b72017-04-02 19:17:22 +00002314 unsigned firstSrcPart = srcLSB / APINT_BITS_PER_WORD;
Neil Boothb6182162007-10-08 13:47:12 +00002315 tcAssign (dst, src + firstSrcPart, dstParts);
2316
Craig Topper55229b72017-04-02 19:17:22 +00002317 unsigned shift = srcLSB % APINT_BITS_PER_WORD;
Neil Boothb6182162007-10-08 13:47:12 +00002318 tcShiftRight (dst, dstParts, shift);
2319
Craig Topper55229b72017-04-02 19:17:22 +00002320 /* We now have (dstParts * APINT_BITS_PER_WORD - shift) bits from SRC
Neil Boothb6182162007-10-08 13:47:12 +00002321 in DST. If this is less that srcBits, append the rest, else
2322 clear the high bits. */
Craig Topper55229b72017-04-02 19:17:22 +00002323 unsigned n = dstParts * APINT_BITS_PER_WORD - shift;
Neil Boothb6182162007-10-08 13:47:12 +00002324 if (n < srcBits) {
Craig Topper55229b72017-04-02 19:17:22 +00002325 WordType mask = lowBitMask (srcBits - n);
Neil Boothb6182162007-10-08 13:47:12 +00002326 dst[dstParts - 1] |= ((src[firstSrcPart + dstParts] & mask)
Craig Topper55229b72017-04-02 19:17:22 +00002327 << n % APINT_BITS_PER_WORD);
Neil Boothb6182162007-10-08 13:47:12 +00002328 } else if (n > srcBits) {
Craig Topper55229b72017-04-02 19:17:22 +00002329 if (srcBits % APINT_BITS_PER_WORD)
2330 dst[dstParts - 1] &= lowBitMask (srcBits % APINT_BITS_PER_WORD);
Neil Boothb6182162007-10-08 13:47:12 +00002331 }
2332
2333 /* Clear high parts. */
2334 while (dstParts < dstCount)
2335 dst[dstParts++] = 0;
2336}
2337
Chris Lattner6b695682007-08-16 15:56:55 +00002338/* DST += RHS + C where C is zero or one. Returns the carry flag. */
Craig Topper55229b72017-04-02 19:17:22 +00002339APInt::WordType APInt::tcAdd(WordType *dst, const WordType *rhs,
2340 WordType c, unsigned parts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002341 assert(c <= 1);
2342
Craig Topperb0038162017-03-28 05:32:52 +00002343 for (unsigned i = 0; i < parts; i++) {
Craig Topper55229b72017-04-02 19:17:22 +00002344 WordType l = dst[i];
Chris Lattner6b695682007-08-16 15:56:55 +00002345 if (c) {
2346 dst[i] += rhs[i] + 1;
2347 c = (dst[i] <= l);
2348 } else {
2349 dst[i] += rhs[i];
2350 c = (dst[i] < l);
2351 }
2352 }
2353
2354 return c;
2355}
2356
Craig Topper92fc4772017-04-13 04:36:06 +00002357/// This function adds a single "word" integer, src, to the multiple
2358/// "word" integer array, dst[]. dst[] is modified to reflect the addition and
2359/// 1 is returned if there is a carry out, otherwise 0 is returned.
2360/// @returns the carry of the addition.
2361APInt::WordType APInt::tcAddPart(WordType *dst, WordType src,
2362 unsigned parts) {
2363 for (unsigned i = 0; i < parts; ++i) {
2364 dst[i] += src;
2365 if (dst[i] >= src)
2366 return 0; // No need to carry so exit early.
2367 src = 1; // Carry one to next digit.
2368 }
2369
2370 return 1;
2371}
2372
Chris Lattner6b695682007-08-16 15:56:55 +00002373/* DST -= RHS + C where C is zero or one. Returns the carry flag. */
Craig Topper55229b72017-04-02 19:17:22 +00002374APInt::WordType APInt::tcSubtract(WordType *dst, const WordType *rhs,
2375 WordType c, unsigned parts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002376 assert(c <= 1);
2377
Craig Topperb0038162017-03-28 05:32:52 +00002378 for (unsigned i = 0; i < parts; i++) {
Craig Topper55229b72017-04-02 19:17:22 +00002379 WordType l = dst[i];
Chris Lattner6b695682007-08-16 15:56:55 +00002380 if (c) {
2381 dst[i] -= rhs[i] + 1;
2382 c = (dst[i] >= l);
2383 } else {
2384 dst[i] -= rhs[i];
2385 c = (dst[i] > l);
2386 }
2387 }
2388
2389 return c;
2390}
2391
Craig Topper92fc4772017-04-13 04:36:06 +00002392/// This function subtracts a single "word" (64-bit word), src, from
2393/// the multi-word integer array, dst[], propagating the borrowed 1 value until
2394/// no further borrowing is needed or it runs out of "words" in dst. The result
2395/// is 1 if "borrowing" exhausted the digits in dst, or 0 if dst was not
2396/// exhausted. In other words, if src > dst then this function returns 1,
2397/// otherwise 0.
2398/// @returns the borrow out of the subtraction
2399APInt::WordType APInt::tcSubtractPart(WordType *dst, WordType src,
2400 unsigned parts) {
2401 for (unsigned i = 0; i < parts; ++i) {
2402 WordType Dst = dst[i];
2403 dst[i] -= src;
2404 if (src <= Dst)
2405 return 0; // No need to borrow so exit early.
2406 src = 1; // We have to "borrow 1" from next "word"
2407 }
2408
2409 return 1;
2410}
2411
Chris Lattner6b695682007-08-16 15:56:55 +00002412/* Negate a bignum in-place. */
Craig Topper55229b72017-04-02 19:17:22 +00002413void APInt::tcNegate(WordType *dst, unsigned parts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002414 tcComplement(dst, parts);
2415 tcIncrement(dst, parts);
2416}
2417
Neil Boothc8b650a2007-10-06 00:43:45 +00002418/* DST += SRC * MULTIPLIER + CARRY if add is true
2419 DST = SRC * MULTIPLIER + CARRY if add is false
Chris Lattner6b695682007-08-16 15:56:55 +00002420
2421 Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC
2422 they must start at the same point, i.e. DST == SRC.
2423
2424 If DSTPARTS == SRCPARTS + 1 no overflow occurs and zero is
2425 returned. Otherwise DST is filled with the least significant
2426 DSTPARTS parts of the result, and if all of the omitted higher
2427 parts were zero return zero, otherwise overflow occurred and
2428 return one. */
Craig Topper55229b72017-04-02 19:17:22 +00002429int APInt::tcMultiplyPart(WordType *dst, const WordType *src,
2430 WordType multiplier, WordType carry,
Craig Topper6a8518082017-03-28 05:32:55 +00002431 unsigned srcParts, unsigned dstParts,
2432 bool add) {
Chris Lattner6b695682007-08-16 15:56:55 +00002433 /* Otherwise our writes of DST kill our later reads of SRC. */
2434 assert(dst <= src || dst >= src + srcParts);
2435 assert(dstParts <= srcParts + 1);
2436
2437 /* N loops; minimum of dstParts and srcParts. */
Craig Topperb0038162017-03-28 05:32:52 +00002438 unsigned n = dstParts < srcParts ? dstParts: srcParts;
Chris Lattner6b695682007-08-16 15:56:55 +00002439
Craig Topperb0038162017-03-28 05:32:52 +00002440 unsigned i;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002441 for (i = 0; i < n; i++) {
Craig Topper55229b72017-04-02 19:17:22 +00002442 WordType low, mid, high, srcPart;
Chris Lattner6b695682007-08-16 15:56:55 +00002443
2444 /* [ LOW, HIGH ] = MULTIPLIER * SRC[i] + DST[i] + CARRY.
2445
2446 This cannot overflow, because
2447
2448 (n - 1) * (n - 1) + 2 (n - 1) = (n - 1) * (n + 1)
2449
2450 which is less than n^2. */
2451
2452 srcPart = src[i];
2453
Craig Topper6a8518082017-03-28 05:32:55 +00002454 if (multiplier == 0 || srcPart == 0) {
Chris Lattner6b695682007-08-16 15:56:55 +00002455 low = carry;
2456 high = 0;
2457 } else {
2458 low = lowHalf(srcPart) * lowHalf(multiplier);
2459 high = highHalf(srcPart) * highHalf(multiplier);
2460
2461 mid = lowHalf(srcPart) * highHalf(multiplier);
2462 high += highHalf(mid);
Craig Topper55229b72017-04-02 19:17:22 +00002463 mid <<= APINT_BITS_PER_WORD / 2;
Chris Lattner6b695682007-08-16 15:56:55 +00002464 if (low + mid < low)
2465 high++;
2466 low += mid;
2467
2468 mid = highHalf(srcPart) * lowHalf(multiplier);
2469 high += highHalf(mid);
Craig Topper55229b72017-04-02 19:17:22 +00002470 mid <<= APINT_BITS_PER_WORD / 2;
Chris Lattner6b695682007-08-16 15:56:55 +00002471 if (low + mid < low)
2472 high++;
2473 low += mid;
2474
2475 /* Now add carry. */
2476 if (low + carry < low)
2477 high++;
2478 low += carry;
2479 }
2480
2481 if (add) {
2482 /* And now DST[i], and store the new low part there. */
2483 if (low + dst[i] < low)
2484 high++;
2485 dst[i] += low;
2486 } else
2487 dst[i] = low;
2488
2489 carry = high;
2490 }
2491
2492 if (i < dstParts) {
2493 /* Full multiplication, there is no overflow. */
2494 assert(i + 1 == dstParts);
2495 dst[i] = carry;
2496 return 0;
2497 } else {
2498 /* We overflowed if there is carry. */
2499 if (carry)
2500 return 1;
2501
2502 /* We would overflow if any significant unwritten parts would be
2503 non-zero. This is true if any remaining src parts are non-zero
2504 and the multiplier is non-zero. */
2505 if (multiplier)
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002506 for (; i < srcParts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002507 if (src[i])
2508 return 1;
2509
2510 /* We fitted in the narrow destination. */
2511 return 0;
2512 }
2513}
2514
2515/* DST = LHS * RHS, where DST has the same width as the operands and
2516 is filled with the least significant parts of the result. Returns
2517 one if overflow occurred, otherwise zero. DST must be disjoint
2518 from both operands. */
Craig Topper55229b72017-04-02 19:17:22 +00002519int APInt::tcMultiply(WordType *dst, const WordType *lhs,
2520 const WordType *rhs, unsigned parts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002521 assert(dst != lhs && dst != rhs);
2522
Craig Topperb0038162017-03-28 05:32:52 +00002523 int overflow = 0;
Chris Lattner6b695682007-08-16 15:56:55 +00002524 tcSet(dst, 0, parts);
2525
Craig Topperb0038162017-03-28 05:32:52 +00002526 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002527 overflow |= tcMultiplyPart(&dst[i], lhs, rhs[i], 0, parts,
2528 parts - i, true);
2529
2530 return overflow;
2531}
2532
Neil Booth0ea72a92007-10-06 00:24:48 +00002533/* DST = LHS * RHS, where DST has width the sum of the widths of the
2534 operands. No overflow occurs. DST must be disjoint from both
2535 operands. Returns the number of parts required to hold the
2536 result. */
Craig Topper55229b72017-04-02 19:17:22 +00002537unsigned APInt::tcFullMultiply(WordType *dst, const WordType *lhs,
2538 const WordType *rhs, unsigned lhsParts,
Craig Topper6a8518082017-03-28 05:32:55 +00002539 unsigned rhsParts) {
Neil Booth0ea72a92007-10-06 00:24:48 +00002540 /* Put the narrower number on the LHS for less loops below. */
2541 if (lhsParts > rhsParts) {
2542 return tcFullMultiply (dst, rhs, lhs, rhsParts, lhsParts);
2543 } else {
Neil Booth0ea72a92007-10-06 00:24:48 +00002544 assert(dst != lhs && dst != rhs);
Chris Lattner6b695682007-08-16 15:56:55 +00002545
Neil Booth0ea72a92007-10-06 00:24:48 +00002546 tcSet(dst, 0, rhsParts);
Chris Lattner6b695682007-08-16 15:56:55 +00002547
Craig Topperb0038162017-03-28 05:32:52 +00002548 for (unsigned i = 0; i < lhsParts; i++)
2549 tcMultiplyPart(&dst[i], rhs, lhs[i], 0, rhsParts, rhsParts + 1, true);
Chris Lattner6b695682007-08-16 15:56:55 +00002550
Craig Topperb0038162017-03-28 05:32:52 +00002551 unsigned n = lhsParts + rhsParts;
Neil Booth0ea72a92007-10-06 00:24:48 +00002552
2553 return n - (dst[n - 1] == 0);
2554 }
Chris Lattner6b695682007-08-16 15:56:55 +00002555}
2556
2557/* If RHS is zero LHS and REMAINDER are left unchanged, return one.
2558 Otherwise set LHS to LHS / RHS with the fractional part discarded,
2559 set REMAINDER to the remainder, return zero. i.e.
2560
2561 OLD_LHS = RHS * LHS + REMAINDER
2562
2563 SCRATCH is a bignum of the same size as the operands and result for
2564 use by the routine; its contents need not be initialized and are
2565 destroyed. LHS, REMAINDER and SCRATCH must be distinct.
2566*/
Craig Topper55229b72017-04-02 19:17:22 +00002567int APInt::tcDivide(WordType *lhs, const WordType *rhs,
2568 WordType *remainder, WordType *srhs,
Craig Topper6a8518082017-03-28 05:32:55 +00002569 unsigned parts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002570 assert(lhs != remainder && lhs != srhs && remainder != srhs);
2571
Craig Topperb0038162017-03-28 05:32:52 +00002572 unsigned shiftCount = tcMSB(rhs, parts) + 1;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002573 if (shiftCount == 0)
Chris Lattner6b695682007-08-16 15:56:55 +00002574 return true;
2575
Craig Topper55229b72017-04-02 19:17:22 +00002576 shiftCount = parts * APINT_BITS_PER_WORD - shiftCount;
2577 unsigned n = shiftCount / APINT_BITS_PER_WORD;
2578 WordType mask = (WordType) 1 << (shiftCount % APINT_BITS_PER_WORD);
Chris Lattner6b695682007-08-16 15:56:55 +00002579
2580 tcAssign(srhs, rhs, parts);
2581 tcShiftLeft(srhs, parts, shiftCount);
2582 tcAssign(remainder, lhs, parts);
2583 tcSet(lhs, 0, parts);
2584
2585 /* Loop, subtracting SRHS if REMAINDER is greater and adding that to
2586 the total. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002587 for (;;) {
Chris Lattner6b695682007-08-16 15:56:55 +00002588 int compare;
2589
2590 compare = tcCompare(remainder, srhs, parts);
2591 if (compare >= 0) {
2592 tcSubtract(remainder, srhs, 0, parts);
2593 lhs[n] |= mask;
2594 }
2595
2596 if (shiftCount == 0)
2597 break;
2598 shiftCount--;
2599 tcShiftRight(srhs, parts, 1);
Richard Trieu7a083812016-02-18 22:09:30 +00002600 if ((mask >>= 1) == 0) {
Craig Topper55229b72017-04-02 19:17:22 +00002601 mask = (WordType) 1 << (APINT_BITS_PER_WORD - 1);
Richard Trieu7a083812016-02-18 22:09:30 +00002602 n--;
2603 }
Chris Lattner6b695682007-08-16 15:56:55 +00002604 }
2605
2606 return false;
2607}
2608
Craig Toppera8a4f0d2017-04-18 04:39:48 +00002609/// Shift a bignum left Cound bits in-place. Shifted in bits are zero. There are
2610/// no restrictions on Count.
2611void APInt::tcShiftLeft(WordType *Dst, unsigned Words, unsigned Count) {
2612 // Don't bother performing a no-op shift.
2613 if (!Count)
2614 return;
Chris Lattner6b695682007-08-16 15:56:55 +00002615
Craig Toppera8a4f0d2017-04-18 04:39:48 +00002616 /* WordShift is the inter-part shift; BitShift is is intra-part shift. */
2617 unsigned WordShift = std::min(Count / APINT_BITS_PER_WORD, Words);
2618 unsigned BitShift = Count % APINT_BITS_PER_WORD;
Chris Lattner6b695682007-08-16 15:56:55 +00002619
Craig Toppera8a4f0d2017-04-18 04:39:48 +00002620 // Fastpath for moving by whole words.
2621 if (BitShift == 0) {
2622 std::memmove(Dst + WordShift, Dst, (Words - WordShift) * APINT_WORD_SIZE);
2623 } else {
2624 while (Words-- > WordShift) {
2625 Dst[Words] = Dst[Words - WordShift] << BitShift;
2626 if (Words > WordShift)
2627 Dst[Words] |=
2628 Dst[Words - WordShift - 1] >> (APINT_BITS_PER_WORD - BitShift);
Neil Boothb6182162007-10-08 13:47:12 +00002629 }
Neil Boothb6182162007-10-08 13:47:12 +00002630 }
Craig Toppera8a4f0d2017-04-18 04:39:48 +00002631
2632 // Fill in the remainder with 0s.
2633 std::memset(Dst, 0, WordShift * APINT_WORD_SIZE);
Chris Lattner6b695682007-08-16 15:56:55 +00002634}
2635
Craig Topper9575d8f2017-04-17 21:43:43 +00002636/// Shift a bignum right Count bits in-place. Shifted in bits are zero. There
2637/// are no restrictions on Count.
2638void APInt::tcShiftRight(WordType *Dst, unsigned Words, unsigned Count) {
2639 // Don't bother performing a no-op shift.
2640 if (!Count)
2641 return;
Chris Lattner6b695682007-08-16 15:56:55 +00002642
Craig Topper9575d8f2017-04-17 21:43:43 +00002643 // WordShift is the inter-part shift; BitShift is is intra-part shift.
2644 unsigned WordShift = std::min(Count / APINT_BITS_PER_WORD, Words);
2645 unsigned BitShift = Count % APINT_BITS_PER_WORD;
Chris Lattner6b695682007-08-16 15:56:55 +00002646
Craig Topper9575d8f2017-04-17 21:43:43 +00002647 unsigned WordsToMove = Words - WordShift;
2648 // Fastpath for moving by whole words.
2649 if (BitShift == 0) {
2650 std::memmove(Dst, Dst + WordShift, WordsToMove * APINT_WORD_SIZE);
2651 } else {
2652 for (unsigned i = 0; i != WordsToMove; ++i) {
2653 Dst[i] = Dst[i + WordShift] >> BitShift;
2654 if (i + 1 != WordsToMove)
2655 Dst[i] |= Dst[i + WordShift + 1] << (APINT_BITS_PER_WORD - BitShift);
Neil Boothb6182162007-10-08 13:47:12 +00002656 }
Chris Lattner6b695682007-08-16 15:56:55 +00002657 }
Craig Topper9575d8f2017-04-17 21:43:43 +00002658
2659 // Fill in the remainder with 0s.
2660 std::memset(Dst + WordsToMove, 0, WordShift * APINT_WORD_SIZE);
Chris Lattner6b695682007-08-16 15:56:55 +00002661}
2662
2663/* Bitwise and of two bignums. */
Craig Topper55229b72017-04-02 19:17:22 +00002664void APInt::tcAnd(WordType *dst, const WordType *rhs, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002665 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002666 dst[i] &= rhs[i];
2667}
2668
2669/* Bitwise inclusive or of two bignums. */
Craig Topper55229b72017-04-02 19:17:22 +00002670void APInt::tcOr(WordType *dst, const WordType *rhs, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002671 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002672 dst[i] |= rhs[i];
2673}
2674
2675/* Bitwise exclusive or of two bignums. */
Craig Topper55229b72017-04-02 19:17:22 +00002676void APInt::tcXor(WordType *dst, const WordType *rhs, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002677 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002678 dst[i] ^= rhs[i];
2679}
2680
2681/* Complement a bignum in-place. */
Craig Topper55229b72017-04-02 19:17:22 +00002682void APInt::tcComplement(WordType *dst, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002683 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002684 dst[i] = ~dst[i];
2685}
2686
2687/* Comparison (unsigned) of two bignums. */
Craig Topper55229b72017-04-02 19:17:22 +00002688int APInt::tcCompare(const WordType *lhs, const WordType *rhs,
Craig Topper6a8518082017-03-28 05:32:55 +00002689 unsigned parts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002690 while (parts) {
Craig Topper99cfe4f2017-04-01 21:50:06 +00002691 parts--;
2692 if (lhs[parts] == rhs[parts])
2693 continue;
Chris Lattner6b695682007-08-16 15:56:55 +00002694
Craig Topper68a3ed22017-04-01 21:50:10 +00002695 return (lhs[parts] > rhs[parts]) ? 1 : -1;
Craig Topper99cfe4f2017-04-01 21:50:06 +00002696 }
Chris Lattner6b695682007-08-16 15:56:55 +00002697
2698 return 0;
2699}
2700
Chris Lattner6b695682007-08-16 15:56:55 +00002701/* Set the least significant BITS bits of a bignum, clear the
2702 rest. */
Craig Topper55229b72017-04-02 19:17:22 +00002703void APInt::tcSetLeastSignificantBits(WordType *dst, unsigned parts,
Craig Topper6a8518082017-03-28 05:32:55 +00002704 unsigned bits) {
Craig Topperb0038162017-03-28 05:32:52 +00002705 unsigned i = 0;
Craig Topper55229b72017-04-02 19:17:22 +00002706 while (bits > APINT_BITS_PER_WORD) {
2707 dst[i++] = ~(WordType) 0;
2708 bits -= APINT_BITS_PER_WORD;
Chris Lattner6b695682007-08-16 15:56:55 +00002709 }
2710
2711 if (bits)
Craig Topper55229b72017-04-02 19:17:22 +00002712 dst[i++] = ~(WordType) 0 >> (APINT_BITS_PER_WORD - bits);
Chris Lattner6b695682007-08-16 15:56:55 +00002713
2714 while (i < parts)
2715 dst[i++] = 0;
2716}