blob: b6c8cbee66df8528636ecd7e532c80efa8108403 [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)
Craig Topper5e113742017-04-22 06:31:36 +000084 pVal[i] = WORD_MAX;
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
Craig Topperc67fe572017-04-19 17:01:58 +0000128void APInt::AssignSlowCase(const APInt& RHS) {
Reid Spencer7c16cd22007-02-26 23:38:21 +0000129 // Don't do anything for X = X
130 if (this == &RHS)
Craig Topperc67fe572017-04-19 17:01:58 +0000131 return;
Reid Spencer7c16cd22007-02-26 23:38:21 +0000132
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);
Craig Topperc67fe572017-04-19 17:01:58 +0000137 return;
Reid Spencer7c16cd22007-02-26 23:38:21 +0000138 }
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;
Craig Topperc67fe572017-04-19 17:01:58 +0000157 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 Topperc67fe572017-04-19 17:01:58 +0000342void 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}
345
Craig Topperc67fe572017-04-19 17:01:58 +0000346void APInt::OrAssignSlowCase(const APInt& RHS) {
Craig Topperb2aaa5d2017-04-01 21:50:03 +0000347 tcOr(pVal, RHS.pVal, getNumWords());
Zhou Shengdac63782007-02-06 03:00:16 +0000348}
349
Craig Topperc67fe572017-04-19 17:01:58 +0000350void APInt::XorAssignSlowCase(const APInt& RHS) {
Craig Topperb2aaa5d2017-04-01 21:50:03 +0000351 tcXor(pVal, RHS.pVal, getNumWords());
Zhou Shengdac63782007-02-06 03:00:16 +0000352}
353
Zhou Shengdac63782007-02-06 03:00:16 +0000354APInt APInt::operator*(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +0000355 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencera41e93b2007-02-25 19:32:03 +0000356 if (isSingleWord())
Reid Spenceraa8dcfe2007-02-26 07:44:38 +0000357 return APInt(BitWidth, VAL * RHS.VAL);
Reid Spencer4bb430c2007-02-20 20:42:10 +0000358 APInt Result(*this);
359 Result *= RHS;
Eli Friedman19546412011-10-07 23:40:49 +0000360 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000361}
362
Chris Lattner1ac3e252008-08-20 17:02:31 +0000363bool APInt::EqualSlowCase(const APInt& RHS) const {
Matthias Braun5117fcd2016-02-15 20:06:19 +0000364 return std::equal(pVal, pVal + getNumWords(), RHS.pVal);
Zhou Shengdac63782007-02-06 03:00:16 +0000365}
366
Craig Topper1dc8fc82017-04-21 16:13:15 +0000367int APInt::compare(const APInt& RHS) const {
Reid Spencer1d072122007-02-16 22:36:51 +0000368 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
369 if (isSingleWord())
Craig Topper1dc8fc82017-04-21 16:13:15 +0000370 return VAL < RHS.VAL ? -1 : VAL > RHS.VAL;
Reid Spencera41e93b2007-02-25 19:32:03 +0000371
Craig Topper1dc8fc82017-04-21 16:13:15 +0000372 return tcCompare(pVal, RHS.pVal, getNumWords());
Zhou Shengdac63782007-02-06 03:00:16 +0000373}
374
Craig Topper1dc8fc82017-04-21 16:13:15 +0000375int APInt::compareSigned(const APInt& RHS) const {
Reid Spencer1d072122007-02-16 22:36:51 +0000376 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000377 if (isSingleWord()) {
David Majnemer5f1c0172016-06-24 20:51:47 +0000378 int64_t lhsSext = SignExtend64(VAL, BitWidth);
379 int64_t rhsSext = SignExtend64(RHS.VAL, BitWidth);
Craig Topper1dc8fc82017-04-21 16:13:15 +0000380 return lhsSext < rhsSext ? -1 : lhsSext > rhsSext;
Reid Spencer1d072122007-02-16 22:36:51 +0000381 }
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000382
Reid Spencer54abdcf2007-02-27 18:23:40 +0000383 bool lhsNeg = isNegative();
Pete Cooperd6e6bf12016-05-26 17:40:07 +0000384 bool rhsNeg = RHS.isNegative();
Reid Spencera41e93b2007-02-25 19:32:03 +0000385
Pete Cooperd6e6bf12016-05-26 17:40:07 +0000386 // If the sign bits don't match, then (LHS < RHS) if LHS is negative
387 if (lhsNeg != rhsNeg)
Craig Topper1dc8fc82017-04-21 16:13:15 +0000388 return lhsNeg ? -1 : 1;
Pete Cooperd6e6bf12016-05-26 17:40:07 +0000389
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000390 // Otherwise we can just use an unsigned comparison, because even negative
Pete Cooperd6e6bf12016-05-26 17:40:07 +0000391 // numbers compare correctly this way if both have the same signed-ness.
Craig Topper1dc8fc82017-04-21 16:13:15 +0000392 return tcCompare(pVal, RHS.pVal, getNumWords());
Zhou Shengdac63782007-02-06 03:00:16 +0000393}
394
Craig Topperbafdd032017-03-07 01:56:01 +0000395void APInt::setBitsSlowCase(unsigned loBit, unsigned hiBit) {
396 unsigned loWord = whichWord(loBit);
397 unsigned hiWord = whichWord(hiBit);
Simon Pilgrimaed35222017-02-24 10:15:29 +0000398
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000399 // Create an initial mask for the low word with zeros below loBit.
Craig Topper5e113742017-04-22 06:31:36 +0000400 uint64_t loMask = WORD_MAX << whichBit(loBit);
Simon Pilgrimaed35222017-02-24 10:15:29 +0000401
Craig Topperbafdd032017-03-07 01:56:01 +0000402 // If hiBit is not aligned, we need a high mask.
403 unsigned hiShiftAmt = whichBit(hiBit);
404 if (hiShiftAmt != 0) {
405 // Create a high mask with zeros above hiBit.
Craig Topper5e113742017-04-22 06:31:36 +0000406 uint64_t hiMask = WORD_MAX >> (APINT_BITS_PER_WORD - hiShiftAmt);
Craig Topperbafdd032017-03-07 01:56:01 +0000407 // If loWord and hiWord are equal, then we combine the masks. Otherwise,
408 // set the bits in hiWord.
409 if (hiWord == loWord)
410 loMask &= hiMask;
411 else
Simon Pilgrimaed35222017-02-24 10:15:29 +0000412 pVal[hiWord] |= hiMask;
Simon Pilgrimaed35222017-02-24 10:15:29 +0000413 }
Craig Topperbafdd032017-03-07 01:56:01 +0000414 // Apply the mask to the low word.
415 pVal[loWord] |= loMask;
416
417 // Fill any words between loWord and hiWord with all ones.
418 for (unsigned word = loWord + 1; word < hiWord; ++word)
Craig Topper5e113742017-04-22 06:31:36 +0000419 pVal[word] = WORD_MAX;
Simon Pilgrimaed35222017-02-24 10:15:29 +0000420}
421
Zhou Shengdac63782007-02-06 03:00:16 +0000422/// @brief Toggle every bit to its opposite value.
Craig Topperafc9e352017-03-27 17:10:21 +0000423void APInt::flipAllBitsSlowCase() {
Craig Toppera742cb52017-04-01 21:50:08 +0000424 tcComplement(pVal, getNumWords());
Craig Topperafc9e352017-03-27 17:10:21 +0000425 clearUnusedBits();
426}
Zhou Shengdac63782007-02-06 03:00:16 +0000427
Eric Christopher820256b2009-08-21 04:06:45 +0000428/// Toggle a given bit to its opposite value whose position is given
Zhou Shengdac63782007-02-06 03:00:16 +0000429/// as "bitPosition".
430/// @brief Toggles a given bit to its opposite value.
Jay Foad25a5e4c2010-12-01 08:53:58 +0000431void APInt::flipBit(unsigned bitPosition) {
Reid Spencer1d072122007-02-16 22:36:51 +0000432 assert(bitPosition < BitWidth && "Out of the bit-width range!");
Jay Foad25a5e4c2010-12-01 08:53:58 +0000433 if ((*this)[bitPosition]) clearBit(bitPosition);
434 else setBit(bitPosition);
Zhou Shengdac63782007-02-06 03:00:16 +0000435}
436
Simon Pilgrimb02667c2017-03-10 13:44:32 +0000437void APInt::insertBits(const APInt &subBits, unsigned bitPosition) {
438 unsigned subBitWidth = subBits.getBitWidth();
439 assert(0 < subBitWidth && (subBitWidth + bitPosition) <= BitWidth &&
440 "Illegal bit insertion");
441
442 // Insertion is a direct copy.
443 if (subBitWidth == BitWidth) {
444 *this = subBits;
445 return;
446 }
447
448 // Single word result can be done as a direct bitmask.
449 if (isSingleWord()) {
Craig Topper5e113742017-04-22 06:31:36 +0000450 uint64_t mask = WORD_MAX >> (APINT_BITS_PER_WORD - subBitWidth);
Simon Pilgrimb02667c2017-03-10 13:44:32 +0000451 VAL &= ~(mask << bitPosition);
452 VAL |= (subBits.VAL << bitPosition);
453 return;
454 }
455
456 unsigned loBit = whichBit(bitPosition);
457 unsigned loWord = whichWord(bitPosition);
458 unsigned hi1Word = whichWord(bitPosition + subBitWidth - 1);
459
460 // Insertion within a single word can be done as a direct bitmask.
461 if (loWord == hi1Word) {
Craig Topper5e113742017-04-22 06:31:36 +0000462 uint64_t mask = WORD_MAX >> (APINT_BITS_PER_WORD - subBitWidth);
Simon Pilgrimb02667c2017-03-10 13:44:32 +0000463 pVal[loWord] &= ~(mask << loBit);
464 pVal[loWord] |= (subBits.VAL << loBit);
465 return;
466 }
467
468 // Insert on word boundaries.
469 if (loBit == 0) {
470 // Direct copy whole words.
471 unsigned numWholeSubWords = subBitWidth / APINT_BITS_PER_WORD;
472 memcpy(pVal + loWord, subBits.getRawData(),
473 numWholeSubWords * APINT_WORD_SIZE);
474
475 // Mask+insert remaining bits.
476 unsigned remainingBits = subBitWidth % APINT_BITS_PER_WORD;
477 if (remainingBits != 0) {
Craig Topper5e113742017-04-22 06:31:36 +0000478 uint64_t mask = WORD_MAX >> (APINT_BITS_PER_WORD - remainingBits);
Simon Pilgrimb02667c2017-03-10 13:44:32 +0000479 pVal[hi1Word] &= ~mask;
480 pVal[hi1Word] |= subBits.getWord(subBitWidth - 1);
481 }
482 return;
483 }
484
485 // General case - set/clear individual bits in dst based on src.
486 // TODO - there is scope for optimization here, but at the moment this code
487 // path is barely used so prefer readability over performance.
488 for (unsigned i = 0; i != subBitWidth; ++i) {
489 if (subBits[i])
490 setBit(bitPosition + i);
491 else
492 clearBit(bitPosition + i);
493 }
494}
495
Simon Pilgrim0f5fb5f2017-02-25 20:01:58 +0000496APInt APInt::extractBits(unsigned numBits, unsigned bitPosition) const {
497 assert(numBits > 0 && "Can't extract zero bits");
498 assert(bitPosition < BitWidth && (numBits + bitPosition) <= BitWidth &&
499 "Illegal bit extraction");
500
501 if (isSingleWord())
502 return APInt(numBits, VAL >> bitPosition);
503
504 unsigned loBit = whichBit(bitPosition);
505 unsigned loWord = whichWord(bitPosition);
506 unsigned hiWord = whichWord(bitPosition + numBits - 1);
507
508 // Single word result extracting bits from a single word source.
509 if (loWord == hiWord)
510 return APInt(numBits, pVal[loWord] >> loBit);
511
512 // Extracting bits that start on a source word boundary can be done
513 // as a fast memory copy.
514 if (loBit == 0)
515 return APInt(numBits, makeArrayRef(pVal + loWord, 1 + hiWord - loWord));
516
517 // General case - shift + copy source words directly into place.
518 APInt Result(numBits, 0);
519 unsigned NumSrcWords = getNumWords();
520 unsigned NumDstWords = Result.getNumWords();
521
522 for (unsigned word = 0; word < NumDstWords; ++word) {
523 uint64_t w0 = pVal[loWord + word];
524 uint64_t w1 =
525 (loWord + word + 1) < NumSrcWords ? pVal[loWord + word + 1] : 0;
526 Result.pVal[word] = (w0 >> loBit) | (w1 << (APINT_BITS_PER_WORD - loBit));
527 }
528
529 return Result.clearUnusedBits();
530}
531
Benjamin Kramer92d89982010-07-14 22:38:02 +0000532unsigned APInt::getBitsNeeded(StringRef str, uint8_t radix) {
Daniel Dunbar3a1efd112009-08-13 02:33:34 +0000533 assert(!str.empty() && "Invalid string length");
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +0000534 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 ||
Douglas Gregor663c0682011-09-14 15:54:46 +0000535 radix == 36) &&
536 "Radix should be 2, 8, 10, 16, or 36!");
Daniel Dunbar3a1efd112009-08-13 02:33:34 +0000537
538 size_t slen = str.size();
Reid Spencer9329e7b2007-04-13 19:19:07 +0000539
Eric Christopher43a1dec2009-08-21 04:10:31 +0000540 // Each computation below needs to know if it's negative.
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000541 StringRef::iterator p = str.begin();
Eric Christopher43a1dec2009-08-21 04:10:31 +0000542 unsigned isNegative = *p == '-';
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000543 if (*p == '-' || *p == '+') {
544 p++;
Reid Spencer9329e7b2007-04-13 19:19:07 +0000545 slen--;
Eric Christopher43a1dec2009-08-21 04:10:31 +0000546 assert(slen && "String is only a sign, needs a value.");
Reid Spencer9329e7b2007-04-13 19:19:07 +0000547 }
Eric Christopher43a1dec2009-08-21 04:10:31 +0000548
Reid Spencer9329e7b2007-04-13 19:19:07 +0000549 // For radixes of power-of-two values, the bits required is accurately and
550 // easily computed
551 if (radix == 2)
552 return slen + isNegative;
553 if (radix == 8)
554 return slen * 3 + isNegative;
555 if (radix == 16)
556 return slen * 4 + isNegative;
557
Douglas Gregor663c0682011-09-14 15:54:46 +0000558 // FIXME: base 36
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +0000559
Reid Spencer9329e7b2007-04-13 19:19:07 +0000560 // This is grossly inefficient but accurate. We could probably do something
561 // with a computation of roughly slen*64/20 and then adjust by the value of
562 // the first few digits. But, I'm not sure how accurate that could be.
563
564 // Compute a sufficient number of bits that is always large enough but might
Erick Tryzelaardadb15712009-08-21 03:15:28 +0000565 // be too large. This avoids the assertion in the constructor. This
566 // calculation doesn't work appropriately for the numbers 0-9, so just use 4
567 // bits in that case.
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +0000568 unsigned sufficient
Douglas Gregor663c0682011-09-14 15:54:46 +0000569 = radix == 10? (slen == 1 ? 4 : slen * 64/18)
570 : (slen == 1 ? 7 : slen * 16/3);
Reid Spencer9329e7b2007-04-13 19:19:07 +0000571
572 // Convert to the actual binary value.
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000573 APInt tmp(sufficient, StringRef(p, slen), radix);
Reid Spencer9329e7b2007-04-13 19:19:07 +0000574
Erick Tryzelaardadb15712009-08-21 03:15:28 +0000575 // Compute how many bits are required. If the log is infinite, assume we need
576 // just bit.
577 unsigned log = tmp.logBase2();
578 if (log == (unsigned)-1) {
579 return isNegative + 1;
580 } else {
581 return isNegative + log + 1;
582 }
Reid Spencer9329e7b2007-04-13 19:19:07 +0000583}
584
Chandler Carruth71bd7d12012-03-04 12:02:57 +0000585hash_code llvm::hash_value(const APInt &Arg) {
586 if (Arg.isSingleWord())
587 return hash_combine(Arg.VAL);
Reid Spencerb2bc9852007-02-26 21:02:27 +0000588
Chandler Carruth71bd7d12012-03-04 12:02:57 +0000589 return hash_combine_range(Arg.pVal, Arg.pVal + Arg.getNumWords());
Reid Spencerb2bc9852007-02-26 21:02:27 +0000590}
591
Benjamin Kramerb4b51502015-03-25 16:49:59 +0000592bool APInt::isSplat(unsigned SplatSizeInBits) const {
593 assert(getBitWidth() % SplatSizeInBits == 0 &&
594 "SplatSizeInBits must divide width!");
595 // We can check that all parts of an integer are equal by making use of a
596 // little trick: rotate and check if it's still the same value.
597 return *this == rotl(SplatSizeInBits);
598}
599
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000600/// This function returns the high "numBits" bits of this APInt.
Chris Lattner77527f52009-01-21 18:09:24 +0000601APInt APInt::getHiBits(unsigned numBits) const {
Craig Toppere7e35602017-03-31 18:48:14 +0000602 return this->lshr(BitWidth - numBits);
Zhou Shengdac63782007-02-06 03:00:16 +0000603}
604
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000605/// This function returns the low "numBits" bits of this APInt.
Chris Lattner77527f52009-01-21 18:09:24 +0000606APInt APInt::getLoBits(unsigned numBits) const {
Craig Toppere7e35602017-03-31 18:48:14 +0000607 APInt Result(getLowBitsSet(BitWidth, numBits));
608 Result &= *this;
609 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000610}
611
Craig Topper9881bd92017-05-02 06:32:27 +0000612/// Return a value containing V broadcasted over NewLen bits.
613APInt APInt::getSplat(unsigned NewLen, const APInt &V) {
614 assert(NewLen >= V.getBitWidth() && "Can't splat to smaller bit width!");
615
616 APInt Val = V.zextOrSelf(NewLen);
617 for (unsigned I = V.getBitWidth(); I < NewLen; I <<= 1)
618 Val |= Val << I;
619
620 return Val;
621}
622
Chris Lattner77527f52009-01-21 18:09:24 +0000623unsigned APInt::countLeadingZerosSlowCase() const {
Matthias Brauna6be4e82016-02-15 20:06:22 +0000624 unsigned Count = 0;
625 for (int i = getNumWords()-1; i >= 0; --i) {
Craig Topper55229b72017-04-02 19:17:22 +0000626 uint64_t V = pVal[i];
Matthias Brauna6be4e82016-02-15 20:06:22 +0000627 if (V == 0)
Chris Lattner1ac3e252008-08-20 17:02:31 +0000628 Count += APINT_BITS_PER_WORD;
629 else {
Matthias Brauna6be4e82016-02-15 20:06:22 +0000630 Count += llvm::countLeadingZeros(V);
Chris Lattner1ac3e252008-08-20 17:02:31 +0000631 break;
Reid Spencer74cf82e2007-02-21 00:29:48 +0000632 }
Zhou Shengdac63782007-02-06 03:00:16 +0000633 }
Matthias Brauna6be4e82016-02-15 20:06:22 +0000634 // Adjust for unused bits in the most significant word (they are zero).
635 unsigned Mod = BitWidth % APINT_BITS_PER_WORD;
636 Count -= Mod > 0 ? APINT_BITS_PER_WORD - Mod : 0;
John McCalldf951bd2010-02-03 03:42:44 +0000637 return Count;
Zhou Shengdac63782007-02-06 03:00:16 +0000638}
639
Chris Lattner77527f52009-01-21 18:09:24 +0000640unsigned APInt::countLeadingOnes() const {
Reid Spencer31acef52007-02-27 21:59:26 +0000641 if (isSingleWord())
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000642 return llvm::countLeadingOnes(VAL << (APINT_BITS_PER_WORD - BitWidth));
Reid Spencer31acef52007-02-27 21:59:26 +0000643
Chris Lattner77527f52009-01-21 18:09:24 +0000644 unsigned highWordBits = BitWidth % APINT_BITS_PER_WORD;
Torok Edwinec39eb82009-01-27 18:06:03 +0000645 unsigned shift;
646 if (!highWordBits) {
647 highWordBits = APINT_BITS_PER_WORD;
648 shift = 0;
649 } else {
650 shift = APINT_BITS_PER_WORD - highWordBits;
651 }
Reid Spencer31acef52007-02-27 21:59:26 +0000652 int i = getNumWords() - 1;
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000653 unsigned Count = llvm::countLeadingOnes(pVal[i] << shift);
Reid Spencer31acef52007-02-27 21:59:26 +0000654 if (Count == highWordBits) {
655 for (i--; i >= 0; --i) {
Craig Topper5e113742017-04-22 06:31:36 +0000656 if (pVal[i] == WORD_MAX)
Reid Spencer31acef52007-02-27 21:59:26 +0000657 Count += APINT_BITS_PER_WORD;
658 else {
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000659 Count += llvm::countLeadingOnes(pVal[i]);
Reid Spencer31acef52007-02-27 21:59:26 +0000660 break;
661 }
662 }
663 }
664 return Count;
665}
666
Chris Lattner77527f52009-01-21 18:09:24 +0000667unsigned APInt::countTrailingZeros() const {
Zhou Shengdac63782007-02-06 03:00:16 +0000668 if (isSingleWord())
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000669 return std::min(unsigned(llvm::countTrailingZeros(VAL)), BitWidth);
Chris Lattner77527f52009-01-21 18:09:24 +0000670 unsigned Count = 0;
671 unsigned i = 0;
Reid Spenceraa8dcfe2007-02-26 07:44:38 +0000672 for (; i < getNumWords() && pVal[i] == 0; ++i)
673 Count += APINT_BITS_PER_WORD;
674 if (i < getNumWords())
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000675 Count += llvm::countTrailingZeros(pVal[i]);
Chris Lattnerc2c4c742007-11-23 22:36:25 +0000676 return std::min(Count, BitWidth);
Zhou Shengdac63782007-02-06 03:00:16 +0000677}
678
Chris Lattner77527f52009-01-21 18:09:24 +0000679unsigned APInt::countTrailingOnesSlowCase() const {
680 unsigned Count = 0;
681 unsigned i = 0;
Craig Topper5e113742017-04-22 06:31:36 +0000682 for (; i < getNumWords() && pVal[i] == WORD_MAX; ++i)
Dan Gohman8b4fa9d2008-02-13 21:11:05 +0000683 Count += APINT_BITS_PER_WORD;
684 if (i < getNumWords())
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000685 Count += llvm::countTrailingOnes(pVal[i]);
Craig Topper3a29e3b82017-04-22 19:59:11 +0000686 assert(Count <= BitWidth);
687 return Count;
Dan Gohman8b4fa9d2008-02-13 21:11:05 +0000688}
689
Chris Lattner77527f52009-01-21 18:09:24 +0000690unsigned APInt::countPopulationSlowCase() const {
691 unsigned Count = 0;
692 for (unsigned i = 0; i < getNumWords(); ++i)
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000693 Count += llvm::countPopulation(pVal[i]);
Zhou Shengdac63782007-02-06 03:00:16 +0000694 return Count;
695}
696
Craig Topperbaa392e2017-04-20 02:11:27 +0000697bool APInt::intersectsSlowCase(const APInt &RHS) const {
698 for (unsigned i = 0, e = getNumWords(); i != e; ++i)
699 if ((pVal[i] & RHS.pVal[i]) != 0)
700 return true;
701
702 return false;
703}
704
Craig Toppera8129a12017-04-20 16:17:13 +0000705bool APInt::isSubsetOfSlowCase(const APInt &RHS) const {
706 for (unsigned i = 0, e = getNumWords(); i != e; ++i)
707 if ((pVal[i] & ~RHS.pVal[i]) != 0)
708 return false;
709
710 return true;
711}
712
Reid Spencer1d072122007-02-16 22:36:51 +0000713APInt APInt::byteSwap() const {
714 assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
715 if (BitWidth == 16)
Jeff Cohene06855e2007-03-20 20:42:36 +0000716 return APInt(BitWidth, ByteSwap_16(uint16_t(VAL)));
Richard Smith4f9a8082011-11-23 21:33:37 +0000717 if (BitWidth == 32)
Chris Lattner77527f52009-01-21 18:09:24 +0000718 return APInt(BitWidth, ByteSwap_32(unsigned(VAL)));
Richard Smith4f9a8082011-11-23 21:33:37 +0000719 if (BitWidth == 48) {
Chris Lattner77527f52009-01-21 18:09:24 +0000720 unsigned Tmp1 = unsigned(VAL >> 16);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000721 Tmp1 = ByteSwap_32(Tmp1);
Jeff Cohene06855e2007-03-20 20:42:36 +0000722 uint16_t Tmp2 = uint16_t(VAL);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000723 Tmp2 = ByteSwap_16(Tmp2);
Jeff Cohene06855e2007-03-20 20:42:36 +0000724 return APInt(BitWidth, (uint64_t(Tmp2) << 32) | Tmp1);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000725 }
Richard Smith4f9a8082011-11-23 21:33:37 +0000726 if (BitWidth == 64)
727 return APInt(BitWidth, ByteSwap_64(VAL));
728
729 APInt Result(getNumWords() * APINT_BITS_PER_WORD, 0);
730 for (unsigned I = 0, N = getNumWords(); I != N; ++I)
731 Result.pVal[I] = ByteSwap_64(pVal[N - I - 1]);
732 if (Result.BitWidth != BitWidth) {
Richard Smith55bd3752017-04-13 20:29:59 +0000733 Result.lshrInPlace(Result.BitWidth - BitWidth);
Richard Smith4f9a8082011-11-23 21:33:37 +0000734 Result.BitWidth = BitWidth;
735 }
736 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000737}
738
Matt Arsenault155dda92016-03-21 15:00:35 +0000739APInt APInt::reverseBits() const {
740 switch (BitWidth) {
741 case 64:
742 return APInt(BitWidth, llvm::reverseBits<uint64_t>(VAL));
743 case 32:
744 return APInt(BitWidth, llvm::reverseBits<uint32_t>(VAL));
745 case 16:
746 return APInt(BitWidth, llvm::reverseBits<uint16_t>(VAL));
747 case 8:
748 return APInt(BitWidth, llvm::reverseBits<uint8_t>(VAL));
749 default:
750 break;
751 }
752
753 APInt Val(*this);
Craig Topper9eaef072017-04-18 05:02:21 +0000754 APInt Reversed(BitWidth, 0);
755 unsigned S = BitWidth;
Matt Arsenault155dda92016-03-21 15:00:35 +0000756
Craig Topper9eaef072017-04-18 05:02:21 +0000757 for (; Val != 0; Val.lshrInPlace(1)) {
Matt Arsenault155dda92016-03-21 15:00:35 +0000758 Reversed <<= 1;
Craig Topper9eaef072017-04-18 05:02:21 +0000759 Reversed |= Val[0];
Matt Arsenault155dda92016-03-21 15:00:35 +0000760 --S;
761 }
762
763 Reversed <<= S;
764 return Reversed;
765}
766
Craig Topper278ebd22017-04-01 20:30:57 +0000767APInt llvm::APIntOps::GreatestCommonDivisor(APInt A, APInt B) {
Richard Smith55bd3752017-04-13 20:29:59 +0000768 // Fast-path a common case.
769 if (A == B) return A;
770
771 // Corner cases: if either operand is zero, the other is the gcd.
772 if (!A) return B;
773 if (!B) return A;
774
775 // Count common powers of 2 and remove all other powers of 2.
776 unsigned Pow2;
777 {
778 unsigned Pow2_A = A.countTrailingZeros();
779 unsigned Pow2_B = B.countTrailingZeros();
780 if (Pow2_A > Pow2_B) {
781 A.lshrInPlace(Pow2_A - Pow2_B);
782 Pow2 = Pow2_B;
783 } else if (Pow2_B > Pow2_A) {
784 B.lshrInPlace(Pow2_B - Pow2_A);
785 Pow2 = Pow2_A;
786 } else {
787 Pow2 = Pow2_A;
788 }
Zhou Shengdac63782007-02-06 03:00:16 +0000789 }
Richard Smith55bd3752017-04-13 20:29:59 +0000790
791 // Both operands are odd multiples of 2^Pow_2:
792 //
793 // gcd(a, b) = gcd(|a - b| / 2^i, min(a, b))
794 //
795 // This is a modified version of Stein's algorithm, taking advantage of
796 // efficient countTrailingZeros().
797 while (A != B) {
798 if (A.ugt(B)) {
799 A -= B;
800 A.lshrInPlace(A.countTrailingZeros() - Pow2);
801 } else {
802 B -= A;
803 B.lshrInPlace(B.countTrailingZeros() - Pow2);
804 }
805 }
806
Zhou Shengdac63782007-02-06 03:00:16 +0000807 return A;
808}
Chris Lattner28cbd1d2007-02-06 05:38:37 +0000809
Chris Lattner77527f52009-01-21 18:09:24 +0000810APInt llvm::APIntOps::RoundDoubleToAPInt(double Double, unsigned width) {
Zhou Shengd707d632007-02-12 20:02:55 +0000811 union {
812 double D;
813 uint64_t I;
814 } T;
815 T.D = Double;
Reid Spencer974551a2007-02-27 01:28:10 +0000816
817 // Get the sign bit from the highest order bit
Zhou Shengd707d632007-02-12 20:02:55 +0000818 bool isNeg = T.I >> 63;
Reid Spencer974551a2007-02-27 01:28:10 +0000819
820 // Get the 11-bit exponent and adjust for the 1023 bit bias
Zhou Shengd707d632007-02-12 20:02:55 +0000821 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
Reid Spencer974551a2007-02-27 01:28:10 +0000822
823 // If the exponent is negative, the value is < 0 so just return 0.
Zhou Shengd707d632007-02-12 20:02:55 +0000824 if (exp < 0)
Reid Spencer66d0d572007-02-28 01:30:08 +0000825 return APInt(width, 0u);
Reid Spencer974551a2007-02-27 01:28:10 +0000826
827 // Extract the mantissa by clearing the top 12 bits (sign + exponent).
828 uint64_t mantissa = (T.I & (~0ULL >> 12)) | 1ULL << 52;
829
830 // If the exponent doesn't shift all bits out of the mantissa
Zhou Shengd707d632007-02-12 20:02:55 +0000831 if (exp < 52)
Eric Christopher820256b2009-08-21 04:06:45 +0000832 return isNeg ? -APInt(width, mantissa >> (52 - exp)) :
Reid Spencer54abdcf2007-02-27 18:23:40 +0000833 APInt(width, mantissa >> (52 - exp));
834
835 // If the client didn't provide enough bits for us to shift the mantissa into
836 // then the result is undefined, just return 0
837 if (width <= exp - 52)
838 return APInt(width, 0);
Reid Spencer974551a2007-02-27 01:28:10 +0000839
840 // Otherwise, we have to shift the mantissa bits up to the right location
Reid Spencer54abdcf2007-02-27 18:23:40 +0000841 APInt Tmp(width, mantissa);
Craig Topper24e71012017-04-28 03:36:24 +0000842 Tmp <<= (unsigned)exp - 52;
Zhou Shengd707d632007-02-12 20:02:55 +0000843 return isNeg ? -Tmp : Tmp;
844}
845
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000846/// This function converts this APInt to a double.
Zhou Shengd707d632007-02-12 20:02:55 +0000847/// The layout for double is as following (IEEE Standard 754):
848/// --------------------------------------
849/// | Sign Exponent Fraction Bias |
850/// |-------------------------------------- |
851/// | 1[63] 11[62-52] 52[51-00] 1023 |
Eric Christopher820256b2009-08-21 04:06:45 +0000852/// --------------------------------------
Reid Spencer1d072122007-02-16 22:36:51 +0000853double APInt::roundToDouble(bool isSigned) const {
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000854
855 // Handle the simple case where the value is contained in one uint64_t.
Dale Johannesen54be7852009-08-12 18:04:11 +0000856 // It is wrong to optimize getWord(0) to VAL; there might be more than one word.
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000857 if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
858 if (isSigned) {
David Majnemer03992262016-06-24 21:15:36 +0000859 int64_t sext = SignExtend64(getWord(0), BitWidth);
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000860 return double(sext);
861 } else
Dale Johannesen34c08bb2009-08-12 17:42:34 +0000862 return double(getWord(0));
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000863 }
864
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000865 // Determine if the value is negative.
Reid Spencer1d072122007-02-16 22:36:51 +0000866 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000867
868 // Construct the absolute value if we're negative.
Zhou Shengd707d632007-02-12 20:02:55 +0000869 APInt Tmp(isNeg ? -(*this) : (*this));
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000870
871 // Figure out how many bits we're using.
Chris Lattner77527f52009-01-21 18:09:24 +0000872 unsigned n = Tmp.getActiveBits();
Zhou Shengd707d632007-02-12 20:02:55 +0000873
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000874 // The exponent (without bias normalization) is just the number of bits
875 // we are using. Note that the sign bit is gone since we constructed the
876 // absolute value.
877 uint64_t exp = n;
Zhou Shengd707d632007-02-12 20:02:55 +0000878
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000879 // Return infinity for exponent overflow
880 if (exp > 1023) {
881 if (!isSigned || !isNeg)
Jeff Cohene06855e2007-03-20 20:42:36 +0000882 return std::numeric_limits<double>::infinity();
Eric Christopher820256b2009-08-21 04:06:45 +0000883 else
Jeff Cohene06855e2007-03-20 20:42:36 +0000884 return -std::numeric_limits<double>::infinity();
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000885 }
886 exp += 1023; // Increment for 1023 bias
887
888 // Number of bits in mantissa is 52. To obtain the mantissa value, we must
889 // extract the high 52 bits from the correct words in pVal.
Zhou Shengd707d632007-02-12 20:02:55 +0000890 uint64_t mantissa;
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000891 unsigned hiWord = whichWord(n-1);
892 if (hiWord == 0) {
893 mantissa = Tmp.pVal[0];
894 if (n > 52)
895 mantissa >>= n - 52; // shift down, we want the top 52 bits.
896 } else {
897 assert(hiWord > 0 && "huh?");
898 uint64_t hibits = Tmp.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
899 uint64_t lobits = Tmp.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
900 mantissa = hibits | lobits;
901 }
902
Zhou Shengd707d632007-02-12 20:02:55 +0000903 // The leading bit of mantissa is implicit, so get rid of it.
Reid Spencerfbd48a52007-02-18 00:44:22 +0000904 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
Zhou Shengd707d632007-02-12 20:02:55 +0000905 union {
906 double D;
907 uint64_t I;
908 } T;
909 T.I = sign | (exp << 52) | mantissa;
910 return T.D;
911}
912
Reid Spencer1d072122007-02-16 22:36:51 +0000913// Truncate to new width.
Jay Foad583abbc2010-12-07 08:25:19 +0000914APInt APInt::trunc(unsigned width) const {
Reid Spencer1d072122007-02-16 22:36:51 +0000915 assert(width < BitWidth && "Invalid APInt Truncate request");
Chris Lattner1ac3e252008-08-20 17:02:31 +0000916 assert(width && "Can't truncate to 0 bits");
Jay Foad583abbc2010-12-07 08:25:19 +0000917
918 if (width <= APINT_BITS_PER_WORD)
919 return APInt(width, getRawData()[0]);
920
921 APInt Result(getMemory(getNumWords(width)), width);
922
923 // Copy full words.
924 unsigned i;
925 for (i = 0; i != width / APINT_BITS_PER_WORD; i++)
926 Result.pVal[i] = pVal[i];
927
928 // Truncate and copy any partial word.
929 unsigned bits = (0 - width) % APINT_BITS_PER_WORD;
930 if (bits != 0)
931 Result.pVal[i] = pVal[i] << bits >> bits;
932
933 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +0000934}
935
936// Sign extend to a new width.
Craig Topper1dec2812017-04-24 17:37:10 +0000937APInt APInt::sext(unsigned Width) const {
938 assert(Width > BitWidth && "Invalid APInt SignExtend request");
Jay Foad583abbc2010-12-07 08:25:19 +0000939
Craig Topper1dec2812017-04-24 17:37:10 +0000940 if (Width <= APINT_BITS_PER_WORD)
941 return APInt(Width, SignExtend64(VAL, BitWidth));
Reid Spencerb6b5cc32007-02-25 23:44:53 +0000942
Craig Topper1dec2812017-04-24 17:37:10 +0000943 APInt Result(getMemory(getNumWords(Width)), Width);
Reid Spencerb6b5cc32007-02-25 23:44:53 +0000944
Craig Topper1dec2812017-04-24 17:37:10 +0000945 // Copy words.
946 std::memcpy(Result.pVal, getRawData(), getNumWords() * APINT_WORD_SIZE);
Reid Spencerb6b5cc32007-02-25 23:44:53 +0000947
Craig Topper1dec2812017-04-24 17:37:10 +0000948 // Sign extend the last word since there may be unused bits in the input.
949 Result.pVal[getNumWords() - 1] =
950 SignExtend64(Result.pVal[getNumWords() - 1],
951 ((BitWidth - 1) % APINT_BITS_PER_WORD) + 1);
Jay Foad583abbc2010-12-07 08:25:19 +0000952
Craig Topper1dec2812017-04-24 17:37:10 +0000953 // Fill with sign bits.
954 std::memset(Result.pVal + getNumWords(), isNegative() ? -1 : 0,
955 (Result.getNumWords() - getNumWords()) * APINT_WORD_SIZE);
956 Result.clearUnusedBits();
Jay Foad583abbc2010-12-07 08:25:19 +0000957 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +0000958}
959
960// Zero extend to a new width.
Jay Foad583abbc2010-12-07 08:25:19 +0000961APInt APInt::zext(unsigned width) const {
Reid Spencer1d072122007-02-16 22:36:51 +0000962 assert(width > BitWidth && "Invalid APInt ZeroExtend request");
Jay Foad583abbc2010-12-07 08:25:19 +0000963
964 if (width <= APINT_BITS_PER_WORD)
965 return APInt(width, VAL);
966
967 APInt Result(getMemory(getNumWords(width)), width);
968
969 // Copy words.
Craig Topper1dec2812017-04-24 17:37:10 +0000970 std::memcpy(Result.pVal, getRawData(), getNumWords() * APINT_WORD_SIZE);
Jay Foad583abbc2010-12-07 08:25:19 +0000971
972 // Zero remaining words.
Craig Topper1dec2812017-04-24 17:37:10 +0000973 std::memset(Result.pVal + getNumWords(), 0,
974 (Result.getNumWords() - getNumWords()) * APINT_WORD_SIZE);
Jay Foad583abbc2010-12-07 08:25:19 +0000975
976 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +0000977}
978
Jay Foad583abbc2010-12-07 08:25:19 +0000979APInt APInt::zextOrTrunc(unsigned width) const {
Reid Spencer742d1702007-03-01 17:15:32 +0000980 if (BitWidth < width)
981 return zext(width);
982 if (BitWidth > width)
983 return trunc(width);
984 return *this;
985}
986
Jay Foad583abbc2010-12-07 08:25:19 +0000987APInt APInt::sextOrTrunc(unsigned width) const {
Reid Spencer742d1702007-03-01 17:15:32 +0000988 if (BitWidth < width)
989 return sext(width);
990 if (BitWidth > width)
991 return trunc(width);
992 return *this;
993}
994
Rafael Espindolabb893fe2012-01-27 23:33:07 +0000995APInt APInt::zextOrSelf(unsigned width) const {
996 if (BitWidth < width)
997 return zext(width);
998 return *this;
999}
1000
1001APInt APInt::sextOrSelf(unsigned width) const {
1002 if (BitWidth < width)
1003 return sext(width);
1004 return *this;
1005}
1006
Zhou Shenge93db8f2007-02-09 07:48:24 +00001007/// Arithmetic right-shift this APInt by shiftAmt.
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001008/// @brief Arithmetic right-shift function.
Craig Topper8b373262017-04-24 17:18:47 +00001009void APInt::ashrInPlace(const APInt &shiftAmt) {
1010 ashrInPlace((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001011}
1012
1013/// Arithmetic right-shift this APInt by shiftAmt.
1014/// @brief Arithmetic right-shift function.
Craig Topper8b373262017-04-24 17:18:47 +00001015void APInt::ashrSlowCase(unsigned ShiftAmt) {
1016 // Don't bother performing a no-op shift.
1017 if (!ShiftAmt)
1018 return;
Reid Spencer1825dd02007-03-02 22:39:11 +00001019
Craig Topper8b373262017-04-24 17:18:47 +00001020 // Save the original sign bit for later.
1021 bool Negative = isNegative();
Reid Spencer522ca7c2007-02-25 01:56:07 +00001022
Craig Topper8b373262017-04-24 17:18:47 +00001023 // WordShift is the inter-part shift; BitShift is is intra-part shift.
1024 unsigned WordShift = ShiftAmt / APINT_BITS_PER_WORD;
1025 unsigned BitShift = ShiftAmt % APINT_BITS_PER_WORD;
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001026
Craig Topper8b373262017-04-24 17:18:47 +00001027 unsigned WordsToMove = getNumWords() - WordShift;
1028 if (WordsToMove != 0) {
1029 // Sign extend the last word to fill in the unused bits.
1030 pVal[getNumWords() - 1] = SignExtend64(
1031 pVal[getNumWords() - 1], ((BitWidth - 1) % APINT_BITS_PER_WORD) + 1);
Renato Golincc4a9122017-04-23 12:02:07 +00001032
Craig Topper8b373262017-04-24 17:18:47 +00001033 // Fastpath for moving by whole words.
1034 if (BitShift == 0) {
1035 std::memmove(pVal, pVal + WordShift, WordsToMove * APINT_WORD_SIZE);
1036 } else {
1037 // Move the words containing significant bits.
1038 for (unsigned i = 0; i != WordsToMove - 1; ++i)
1039 pVal[i] = (pVal[i + WordShift] >> BitShift) |
1040 (pVal[i + WordShift + 1] << (APINT_BITS_PER_WORD - BitShift));
Renato Golincc4a9122017-04-23 12:02:07 +00001041
Craig Topper8b373262017-04-24 17:18:47 +00001042 // Handle the last word which has no high bits to copy.
1043 pVal[WordsToMove - 1] = pVal[WordShift + WordsToMove - 1] >> BitShift;
1044 // Sign extend one more time.
1045 pVal[WordsToMove - 1] =
1046 SignExtend64(pVal[WordsToMove - 1], APINT_BITS_PER_WORD - BitShift);
Chris Lattnerdad2d092007-05-03 18:15:36 +00001047 }
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001048 }
1049
Craig Topper8b373262017-04-24 17:18:47 +00001050 // Fill in the remainder based on the original sign.
1051 std::memset(pVal + WordsToMove, Negative ? -1 : 0,
1052 WordShift * APINT_WORD_SIZE);
1053 clearUnusedBits();
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001054}
1055
Zhou Shenge93db8f2007-02-09 07:48:24 +00001056/// Logical right-shift this APInt by shiftAmt.
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001057/// @brief Logical right-shift function.
Craig Topperfc947bc2017-04-18 17:14:21 +00001058void APInt::lshrInPlace(const APInt &shiftAmt) {
1059 lshrInPlace((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001060}
1061
1062/// Logical right-shift this APInt by shiftAmt.
1063/// @brief Logical right-shift function.
Craig Topperae8bd672017-04-18 19:13:27 +00001064void APInt::lshrSlowCase(unsigned ShiftAmt) {
Craig Topperfc947bc2017-04-18 17:14:21 +00001065 tcShiftRight(pVal, getNumWords(), ShiftAmt);
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001066}
1067
Zhou Shenge93db8f2007-02-09 07:48:24 +00001068/// Left-shift this APInt by shiftAmt.
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001069/// @brief Left-shift function.
Craig Topper24e71012017-04-28 03:36:24 +00001070APInt &APInt::operator<<=(const APInt &shiftAmt) {
Nick Lewycky030c4502009-01-19 17:42:33 +00001071 // It's undefined behavior in C to shift by BitWidth or greater.
Craig Topper24e71012017-04-28 03:36:24 +00001072 *this <<= (unsigned)shiftAmt.getLimitedValue(BitWidth);
1073 return *this;
Dan Gohman105c1d42008-02-29 01:40:47 +00001074}
1075
Craig Toppera8a4f0d2017-04-18 04:39:48 +00001076void APInt::shlSlowCase(unsigned ShiftAmt) {
1077 tcShiftLeft(pVal, getNumWords(), ShiftAmt);
1078 clearUnusedBits();
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001079}
1080
Joey Gouly51c0ae52017-02-07 11:58:22 +00001081// Calculate the rotate amount modulo the bit width.
1082static unsigned rotateModulo(unsigned BitWidth, const APInt &rotateAmt) {
1083 unsigned rotBitWidth = rotateAmt.getBitWidth();
1084 APInt rot = rotateAmt;
1085 if (rotBitWidth < BitWidth) {
1086 // Extend the rotate APInt, so that the urem doesn't divide by 0.
1087 // e.g. APInt(1, 32) would give APInt(1, 0).
1088 rot = rotateAmt.zext(BitWidth);
1089 }
1090 rot = rot.urem(APInt(rot.getBitWidth(), BitWidth));
1091 return rot.getLimitedValue(BitWidth);
1092}
1093
Dan Gohman105c1d42008-02-29 01:40:47 +00001094APInt APInt::rotl(const APInt &rotateAmt) const {
Joey Gouly51c0ae52017-02-07 11:58:22 +00001095 return rotl(rotateModulo(BitWidth, rotateAmt));
Dan Gohman105c1d42008-02-29 01:40:47 +00001096}
1097
Chris Lattner77527f52009-01-21 18:09:24 +00001098APInt APInt::rotl(unsigned rotateAmt) const {
Eli Friedman2aae94f2011-12-22 03:15:35 +00001099 rotateAmt %= BitWidth;
Reid Spencer98ed7db2007-05-14 00:15:28 +00001100 if (rotateAmt == 0)
1101 return *this;
Eli Friedman2aae94f2011-12-22 03:15:35 +00001102 return shl(rotateAmt) | lshr(BitWidth - rotateAmt);
Reid Spencer4c50b522007-05-13 23:44:59 +00001103}
1104
Dan Gohman105c1d42008-02-29 01:40:47 +00001105APInt APInt::rotr(const APInt &rotateAmt) const {
Joey Gouly51c0ae52017-02-07 11:58:22 +00001106 return rotr(rotateModulo(BitWidth, rotateAmt));
Dan Gohman105c1d42008-02-29 01:40:47 +00001107}
1108
Chris Lattner77527f52009-01-21 18:09:24 +00001109APInt APInt::rotr(unsigned rotateAmt) const {
Eli Friedman2aae94f2011-12-22 03:15:35 +00001110 rotateAmt %= BitWidth;
Reid Spencer98ed7db2007-05-14 00:15:28 +00001111 if (rotateAmt == 0)
1112 return *this;
Eli Friedman2aae94f2011-12-22 03:15:35 +00001113 return lshr(rotateAmt) | shl(BitWidth - rotateAmt);
Reid Spencer4c50b522007-05-13 23:44:59 +00001114}
Reid Spencerd99feaf2007-03-01 05:39:56 +00001115
1116// Square Root - this method computes and returns the square root of "this".
1117// Three mechanisms are used for computation. For small values (<= 5 bits),
1118// a table lookup is done. This gets some performance for common cases. For
1119// values using less than 52 bits, the value is converted to double and then
1120// the libc sqrt function is called. The result is rounded and then converted
1121// back to a uint64_t which is then used to construct the result. Finally,
Eric Christopher820256b2009-08-21 04:06:45 +00001122// the Babylonian method for computing square roots is used.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001123APInt APInt::sqrt() const {
1124
1125 // Determine the magnitude of the value.
Chris Lattner77527f52009-01-21 18:09:24 +00001126 unsigned magnitude = getActiveBits();
Reid Spencerd99feaf2007-03-01 05:39:56 +00001127
1128 // Use a fast table for some small values. This also gets rid of some
1129 // rounding errors in libc sqrt for small values.
1130 if (magnitude <= 5) {
Reid Spencer2f6ad4d2007-03-01 17:47:31 +00001131 static const uint8_t results[32] = {
Reid Spencerc8841d22007-03-01 06:23:32 +00001132 /* 0 */ 0,
1133 /* 1- 2 */ 1, 1,
Eric Christopher820256b2009-08-21 04:06:45 +00001134 /* 3- 6 */ 2, 2, 2, 2,
Reid Spencerc8841d22007-03-01 06:23:32 +00001135 /* 7-12 */ 3, 3, 3, 3, 3, 3,
1136 /* 13-20 */ 4, 4, 4, 4, 4, 4, 4, 4,
1137 /* 21-30 */ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
1138 /* 31 */ 6
1139 };
1140 return APInt(BitWidth, results[ (isSingleWord() ? VAL : pVal[0]) ]);
Reid Spencerd99feaf2007-03-01 05:39:56 +00001141 }
1142
1143 // If the magnitude of the value fits in less than 52 bits (the precision of
1144 // an IEEE double precision floating point value), then we can use the
1145 // libc sqrt function which will probably use a hardware sqrt computation.
1146 // This should be faster than the algorithm below.
Jeff Cohenb622c112007-03-05 00:00:42 +00001147 if (magnitude < 52) {
Eric Christopher820256b2009-08-21 04:06:45 +00001148 return APInt(BitWidth,
Reid Spencerd99feaf2007-03-01 05:39:56 +00001149 uint64_t(::round(::sqrt(double(isSingleWord()?VAL:pVal[0])))));
Jeff Cohenb622c112007-03-05 00:00:42 +00001150 }
Reid Spencerd99feaf2007-03-01 05:39:56 +00001151
1152 // Okay, all the short cuts are exhausted. We must compute it. The following
1153 // is a classical Babylonian method for computing the square root. This code
Sanjay Patel4cb54e02014-09-11 15:41:01 +00001154 // was adapted to APInt from a wikipedia article on such computations.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001155 // See http://www.wikipedia.org/ and go to the page named
Eric Christopher820256b2009-08-21 04:06:45 +00001156 // Calculate_an_integer_square_root.
Chris Lattner77527f52009-01-21 18:09:24 +00001157 unsigned nbits = BitWidth, i = 4;
Reid Spencerd99feaf2007-03-01 05:39:56 +00001158 APInt testy(BitWidth, 16);
1159 APInt x_old(BitWidth, 1);
1160 APInt x_new(BitWidth, 0);
1161 APInt two(BitWidth, 2);
1162
1163 // Select a good starting value using binary logarithms.
Eric Christopher820256b2009-08-21 04:06:45 +00001164 for (;; i += 2, testy = testy.shl(2))
Reid Spencerd99feaf2007-03-01 05:39:56 +00001165 if (i >= nbits || this->ule(testy)) {
1166 x_old = x_old.shl(i / 2);
1167 break;
1168 }
1169
Eric Christopher820256b2009-08-21 04:06:45 +00001170 // Use the Babylonian method to arrive at the integer square root:
Reid Spencerd99feaf2007-03-01 05:39:56 +00001171 for (;;) {
1172 x_new = (this->udiv(x_old) + x_old).udiv(two);
1173 if (x_old.ule(x_new))
1174 break;
1175 x_old = x_new;
1176 }
1177
1178 // Make sure we return the closest approximation
Eric Christopher820256b2009-08-21 04:06:45 +00001179 // NOTE: The rounding calculation below is correct. It will produce an
Reid Spencercf817562007-03-02 04:21:55 +00001180 // off-by-one discrepancy with results from pari/gp. That discrepancy has been
Eric Christopher820256b2009-08-21 04:06:45 +00001181 // determined to be a rounding issue with pari/gp as it begins to use a
Reid Spencercf817562007-03-02 04:21:55 +00001182 // floating point representation after 192 bits. There are no discrepancies
1183 // between this algorithm and pari/gp for bit widths < 192 bits.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001184 APInt square(x_old * x_old);
1185 APInt nextSquare((x_old + 1) * (x_old +1));
1186 if (this->ult(square))
1187 return x_old;
David Blaikie54c94622011-12-01 20:58:30 +00001188 assert(this->ule(nextSquare) && "Error in APInt::sqrt computation");
1189 APInt midpoint((nextSquare - square).udiv(two));
1190 APInt offset(*this - square);
1191 if (offset.ult(midpoint))
1192 return x_old;
Reid Spencerd99feaf2007-03-01 05:39:56 +00001193 return x_old + 1;
1194}
1195
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001196/// Computes the multiplicative inverse of this APInt for a given modulo. The
1197/// iterative extended Euclidean algorithm is used to solve for this value,
1198/// however we simplify it to speed up calculating only the inverse, and take
1199/// advantage of div+rem calculations. We also use some tricks to avoid copying
1200/// (potentially large) APInts around.
1201APInt APInt::multiplicativeInverse(const APInt& modulo) const {
1202 assert(ult(modulo) && "This APInt must be smaller than the modulo");
1203
1204 // Using the properties listed at the following web page (accessed 06/21/08):
1205 // http://www.numbertheory.org/php/euclid.html
1206 // (especially the properties numbered 3, 4 and 9) it can be proved that
1207 // BitWidth bits suffice for all the computations in the algorithm implemented
1208 // below. More precisely, this number of bits suffice if the multiplicative
1209 // inverse exists, but may not suffice for the general extended Euclidean
1210 // algorithm.
1211
1212 APInt r[2] = { modulo, *this };
1213 APInt t[2] = { APInt(BitWidth, 0), APInt(BitWidth, 1) };
1214 APInt q(BitWidth, 0);
Eric Christopher820256b2009-08-21 04:06:45 +00001215
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001216 unsigned i;
1217 for (i = 0; r[i^1] != 0; i ^= 1) {
1218 // An overview of the math without the confusing bit-flipping:
1219 // q = r[i-2] / r[i-1]
1220 // r[i] = r[i-2] % r[i-1]
1221 // t[i] = t[i-2] - t[i-1] * q
1222 udivrem(r[i], r[i^1], q, r[i]);
1223 t[i] -= t[i^1] * q;
1224 }
1225
1226 // If this APInt and the modulo are not coprime, there is no multiplicative
1227 // inverse, so return 0. We check this by looking at the next-to-last
1228 // remainder, which is the gcd(*this,modulo) as calculated by the Euclidean
1229 // algorithm.
1230 if (r[i] != 1)
1231 return APInt(BitWidth, 0);
1232
1233 // The next-to-last t is the multiplicative inverse. However, we are
1234 // interested in a positive inverse. Calcuate a positive one from a negative
1235 // one if necessary. A simple addition of the modulo suffices because
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00001236 // abs(t[i]) is known to be less than *this/2 (see the link above).
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001237 return t[i].isNegative() ? t[i] + modulo : t[i];
1238}
1239
Jay Foadfe0c6482009-04-30 10:15:35 +00001240/// Calculate the magic numbers required to implement a signed integer division
1241/// by a constant as a sequence of multiplies, adds and shifts. Requires that
1242/// the divisor not be 0, 1, or -1. Taken from "Hacker's Delight", Henry S.
1243/// Warren, Jr., chapter 10.
1244APInt::ms APInt::magic() const {
1245 const APInt& d = *this;
1246 unsigned p;
1247 APInt ad, anc, delta, q1, r1, q2, r2, t;
Jay Foadfe0c6482009-04-30 10:15:35 +00001248 APInt signedMin = APInt::getSignedMinValue(d.getBitWidth());
Jay Foadfe0c6482009-04-30 10:15:35 +00001249 struct ms mag;
Eric Christopher820256b2009-08-21 04:06:45 +00001250
Jay Foadfe0c6482009-04-30 10:15:35 +00001251 ad = d.abs();
1252 t = signedMin + (d.lshr(d.getBitWidth() - 1));
1253 anc = t - 1 - t.urem(ad); // absolute value of nc
1254 p = d.getBitWidth() - 1; // initialize p
1255 q1 = signedMin.udiv(anc); // initialize q1 = 2p/abs(nc)
1256 r1 = signedMin - q1*anc; // initialize r1 = rem(2p,abs(nc))
1257 q2 = signedMin.udiv(ad); // initialize q2 = 2p/abs(d)
1258 r2 = signedMin - q2*ad; // initialize r2 = rem(2p,abs(d))
1259 do {
1260 p = p + 1;
1261 q1 = q1<<1; // update q1 = 2p/abs(nc)
1262 r1 = r1<<1; // update r1 = rem(2p/abs(nc))
1263 if (r1.uge(anc)) { // must be unsigned comparison
1264 q1 = q1 + 1;
1265 r1 = r1 - anc;
1266 }
1267 q2 = q2<<1; // update q2 = 2p/abs(d)
1268 r2 = r2<<1; // update r2 = rem(2p/abs(d))
1269 if (r2.uge(ad)) { // must be unsigned comparison
1270 q2 = q2 + 1;
1271 r2 = r2 - ad;
1272 }
1273 delta = ad - r2;
Cameron Zwarich8731d0c2011-02-21 00:22:02 +00001274 } while (q1.ult(delta) || (q1 == delta && r1 == 0));
Eric Christopher820256b2009-08-21 04:06:45 +00001275
Jay Foadfe0c6482009-04-30 10:15:35 +00001276 mag.m = q2 + 1;
1277 if (d.isNegative()) mag.m = -mag.m; // resulting magic number
1278 mag.s = p - d.getBitWidth(); // resulting shift
1279 return mag;
1280}
1281
1282/// Calculate the magic numbers required to implement an unsigned integer
1283/// division by a constant as a sequence of multiplies, adds and shifts.
1284/// Requires that the divisor not be 0. Taken from "Hacker's Delight", Henry
1285/// S. Warren, Jr., chapter 10.
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001286/// LeadingZeros can be used to simplify the calculation if the upper bits
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001287/// of the divided value are known zero.
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001288APInt::mu APInt::magicu(unsigned LeadingZeros) const {
Jay Foadfe0c6482009-04-30 10:15:35 +00001289 const APInt& d = *this;
1290 unsigned p;
1291 APInt nc, delta, q1, r1, q2, r2;
1292 struct mu magu;
1293 magu.a = 0; // initialize "add" indicator
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001294 APInt allOnes = APInt::getAllOnesValue(d.getBitWidth()).lshr(LeadingZeros);
Jay Foadfe0c6482009-04-30 10:15:35 +00001295 APInt signedMin = APInt::getSignedMinValue(d.getBitWidth());
1296 APInt signedMax = APInt::getSignedMaxValue(d.getBitWidth());
1297
Benjamin Kramer3aab6a82012-07-11 18:31:59 +00001298 nc = allOnes - (allOnes - d).urem(d);
Jay Foadfe0c6482009-04-30 10:15:35 +00001299 p = d.getBitWidth() - 1; // initialize p
1300 q1 = signedMin.udiv(nc); // initialize q1 = 2p/nc
1301 r1 = signedMin - q1*nc; // initialize r1 = rem(2p,nc)
1302 q2 = signedMax.udiv(d); // initialize q2 = (2p-1)/d
1303 r2 = signedMax - q2*d; // initialize r2 = rem((2p-1),d)
1304 do {
1305 p = p + 1;
1306 if (r1.uge(nc - r1)) {
1307 q1 = q1 + q1 + 1; // update q1
1308 r1 = r1 + r1 - nc; // update r1
1309 }
1310 else {
1311 q1 = q1+q1; // update q1
1312 r1 = r1+r1; // update r1
1313 }
1314 if ((r2 + 1).uge(d - r2)) {
1315 if (q2.uge(signedMax)) magu.a = 1;
1316 q2 = q2+q2 + 1; // update q2
1317 r2 = r2+r2 + 1 - d; // update r2
1318 }
1319 else {
1320 if (q2.uge(signedMin)) magu.a = 1;
1321 q2 = q2+q2; // update q2
1322 r2 = r2+r2 + 1; // update r2
1323 }
1324 delta = d - 1 - r2;
1325 } while (p < d.getBitWidth()*2 &&
1326 (q1.ult(delta) || (q1 == delta && r1 == 0)));
1327 magu.m = q2 + 1; // resulting magic number
1328 magu.s = p - d.getBitWidth(); // resulting shift
1329 return magu;
1330}
1331
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001332/// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
1333/// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
1334/// variables here have the same names as in the algorithm. Comments explain
1335/// the algorithm and any deviation from it.
Chris Lattner77527f52009-01-21 18:09:24 +00001336static void KnuthDiv(unsigned *u, unsigned *v, unsigned *q, unsigned* r,
1337 unsigned m, unsigned n) {
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001338 assert(u && "Must provide dividend");
1339 assert(v && "Must provide divisor");
1340 assert(q && "Must provide quotient");
Yaron Keren39fc5a62015-03-26 19:45:19 +00001341 assert(u != v && u != q && v != q && "Must use different memory");
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001342 assert(n>1 && "n must be > 1");
1343
Yaron Keren39fc5a62015-03-26 19:45:19 +00001344 // b denotes the base of the number system. In our case b is 2^32.
George Burgess IV381fc0e2016-08-25 01:05:08 +00001345 const uint64_t b = uint64_t(1) << 32;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001346
David Greenef32fcb42010-01-05 01:28:52 +00001347 DEBUG(dbgs() << "KnuthDiv: m=" << m << " n=" << n << '\n');
1348 DEBUG(dbgs() << "KnuthDiv: original:");
1349 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
1350 DEBUG(dbgs() << " by");
1351 DEBUG(for (int i = n; i >0; i--) dbgs() << " " << v[i-1]);
1352 DEBUG(dbgs() << '\n');
Eric Christopher820256b2009-08-21 04:06:45 +00001353 // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
1354 // u and v by d. Note that we have taken Knuth's advice here to use a power
1355 // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
1356 // 2 allows us to shift instead of multiply and it is easy to determine the
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001357 // shift amount from the leading zeros. We are basically normalizing the u
1358 // and v so that its high bits are shifted to the top of v's range without
1359 // overflow. Note that this can require an extra word in u so that u must
1360 // be of length m+n+1.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001361 unsigned shift = countLeadingZeros(v[n-1]);
Chris Lattner77527f52009-01-21 18:09:24 +00001362 unsigned v_carry = 0;
1363 unsigned u_carry = 0;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001364 if (shift) {
Chris Lattner77527f52009-01-21 18:09:24 +00001365 for (unsigned i = 0; i < m+n; ++i) {
1366 unsigned u_tmp = u[i] >> (32 - shift);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001367 u[i] = (u[i] << shift) | u_carry;
1368 u_carry = u_tmp;
Reid Spencer100502d2007-02-17 03:16:00 +00001369 }
Chris Lattner77527f52009-01-21 18:09:24 +00001370 for (unsigned i = 0; i < n; ++i) {
1371 unsigned v_tmp = v[i] >> (32 - shift);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001372 v[i] = (v[i] << shift) | v_carry;
1373 v_carry = v_tmp;
1374 }
1375 }
1376 u[m+n] = u_carry;
Yaron Keren39fc5a62015-03-26 19:45:19 +00001377
David Greenef32fcb42010-01-05 01:28:52 +00001378 DEBUG(dbgs() << "KnuthDiv: normal:");
1379 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
1380 DEBUG(dbgs() << " by");
1381 DEBUG(for (int i = n; i >0; i--) dbgs() << " " << v[i-1]);
1382 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001383
1384 // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
1385 int j = m;
1386 do {
David Greenef32fcb42010-01-05 01:28:52 +00001387 DEBUG(dbgs() << "KnuthDiv: quotient digit #" << j << '\n');
Eric Christopher820256b2009-08-21 04:06:45 +00001388 // D3. [Calculate q'.].
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001389 // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
1390 // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
1391 // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
1392 // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test
1393 // on v[n-2] determines at high speed most of the cases in which the trial
Eric Christopher820256b2009-08-21 04:06:45 +00001394 // value qp is one too large, and it eliminates all cases where qp is two
1395 // too large.
Reid Spencercb292e42007-02-23 01:57:13 +00001396 uint64_t dividend = ((uint64_t(u[j+n]) << 32) + u[j+n-1]);
David Greenef32fcb42010-01-05 01:28:52 +00001397 DEBUG(dbgs() << "KnuthDiv: dividend == " << dividend << '\n');
Reid Spencercb292e42007-02-23 01:57:13 +00001398 uint64_t qp = dividend / v[n-1];
1399 uint64_t rp = dividend % v[n-1];
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001400 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1401 qp--;
1402 rp += v[n-1];
Reid Spencerdf6cf5a2007-02-24 10:01:42 +00001403 if (rp < b && (qp == b || qp*v[n-2] > b*rp + u[j+n-2]))
Reid Spencera5e0d202007-02-24 03:58:46 +00001404 qp--;
Reid Spencercb292e42007-02-23 01:57:13 +00001405 }
David Greenef32fcb42010-01-05 01:28:52 +00001406 DEBUG(dbgs() << "KnuthDiv: qp == " << qp << ", rp == " << rp << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001407
Reid Spencercb292e42007-02-23 01:57:13 +00001408 // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with
1409 // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation
1410 // consists of a simple multiplication by a one-place number, combined with
Eric Christopher820256b2009-08-21 04:06:45 +00001411 // a subtraction.
Yaron Keren39fc5a62015-03-26 19:45:19 +00001412 // The digits (u[j+n]...u[j]) should be kept positive; if the result of
1413 // this step is actually negative, (u[j+n]...u[j]) should be left as the
1414 // true value plus b**(n+1), namely as the b's complement of
1415 // the true value, and a "borrow" to the left should be remembered.
Pawel Bylica86ac4472015-04-24 07:38:39 +00001416 int64_t borrow = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001417 for (unsigned i = 0; i < n; ++i) {
Pawel Bylica86ac4472015-04-24 07:38:39 +00001418 uint64_t p = uint64_t(qp) * uint64_t(v[i]);
1419 int64_t subres = int64_t(u[j+i]) - borrow - (unsigned)p;
1420 u[j+i] = (unsigned)subres;
1421 borrow = (p >> 32) - (subres >> 32);
1422 DEBUG(dbgs() << "KnuthDiv: u[j+i] = " << u[j+i]
Daniel Dunbar763ace92009-07-13 05:27:30 +00001423 << ", borrow = " << borrow << '\n');
Reid Spencera5e0d202007-02-24 03:58:46 +00001424 }
Pawel Bylica86ac4472015-04-24 07:38:39 +00001425 bool isNeg = u[j+n] < borrow;
1426 u[j+n] -= (unsigned)borrow;
1427
David Greenef32fcb42010-01-05 01:28:52 +00001428 DEBUG(dbgs() << "KnuthDiv: after subtraction:");
1429 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
1430 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001431
Eric Christopher820256b2009-08-21 04:06:45 +00001432 // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001433 // negative, go to step D6; otherwise go on to step D7.
Chris Lattner77527f52009-01-21 18:09:24 +00001434 q[j] = (unsigned)qp;
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001435 if (isNeg) {
Eric Christopher820256b2009-08-21 04:06:45 +00001436 // D6. [Add back]. The probability that this step is necessary is very
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001437 // small, on the order of only 2/b. Make sure that test data accounts for
Eric Christopher820256b2009-08-21 04:06:45 +00001438 // this possibility. Decrease q[j] by 1
Reid Spencercb292e42007-02-23 01:57:13 +00001439 q[j]--;
Eric Christopher820256b2009-08-21 04:06:45 +00001440 // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]).
1441 // A carry will occur to the left of u[j+n], and it should be ignored
Reid Spencercb292e42007-02-23 01:57:13 +00001442 // since it cancels with the borrow that occurred in D4.
1443 bool carry = false;
Chris Lattner77527f52009-01-21 18:09:24 +00001444 for (unsigned i = 0; i < n; i++) {
1445 unsigned limit = std::min(u[j+i],v[i]);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001446 u[j+i] += v[i] + carry;
Reid Spencera5e0d202007-02-24 03:58:46 +00001447 carry = u[j+i] < limit || (carry && u[j+i] == limit);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001448 }
Reid Spencera5e0d202007-02-24 03:58:46 +00001449 u[j+n] += carry;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001450 }
David Greenef32fcb42010-01-05 01:28:52 +00001451 DEBUG(dbgs() << "KnuthDiv: after correction:");
Yaron Keren39fc5a62015-03-26 19:45:19 +00001452 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
David Greenef32fcb42010-01-05 01:28:52 +00001453 DEBUG(dbgs() << "\nKnuthDiv: digit result = " << q[j] << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001454
Reid Spencercb292e42007-02-23 01:57:13 +00001455 // D7. [Loop on j.] Decrease j by one. Now if j >= 0, go back to D3.
1456 } while (--j >= 0);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001457
David Greenef32fcb42010-01-05 01:28:52 +00001458 DEBUG(dbgs() << "KnuthDiv: quotient:");
1459 DEBUG(for (int i = m; i >=0; i--) dbgs() <<" " << q[i]);
1460 DEBUG(dbgs() << '\n');
Reid Spencera5e0d202007-02-24 03:58:46 +00001461
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001462 // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
1463 // remainder may be obtained by dividing u[...] by d. If r is non-null we
1464 // compute the remainder (urem uses this).
1465 if (r) {
1466 // The value d is expressed by the "shift" value above since we avoided
1467 // multiplication by d by using a shift left. So, all we have to do is
Simon Pilgrim0099beb2017-03-09 13:57:04 +00001468 // shift right here.
Reid Spencer468ad9112007-02-24 20:38:01 +00001469 if (shift) {
Chris Lattner77527f52009-01-21 18:09:24 +00001470 unsigned carry = 0;
David Greenef32fcb42010-01-05 01:28:52 +00001471 DEBUG(dbgs() << "KnuthDiv: remainder:");
Reid Spencer468ad9112007-02-24 20:38:01 +00001472 for (int i = n-1; i >= 0; i--) {
1473 r[i] = (u[i] >> shift) | carry;
1474 carry = u[i] << (32 - shift);
David Greenef32fcb42010-01-05 01:28:52 +00001475 DEBUG(dbgs() << " " << r[i]);
Reid Spencer468ad9112007-02-24 20:38:01 +00001476 }
1477 } else {
1478 for (int i = n-1; i >= 0; i--) {
1479 r[i] = u[i];
David Greenef32fcb42010-01-05 01:28:52 +00001480 DEBUG(dbgs() << " " << r[i]);
Reid Spencer468ad9112007-02-24 20:38:01 +00001481 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001482 }
David Greenef32fcb42010-01-05 01:28:52 +00001483 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001484 }
David Greenef32fcb42010-01-05 01:28:52 +00001485 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001486}
1487
Benjamin Kramerc321e532016-06-08 19:09:22 +00001488void APInt::divide(const APInt &LHS, unsigned lhsWords, const APInt &RHS,
1489 unsigned rhsWords, APInt *Quotient, APInt *Remainder) {
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001490 assert(lhsWords >= rhsWords && "Fractional result");
1491
Eric Christopher820256b2009-08-21 04:06:45 +00001492 // First, compose the values into an array of 32-bit words instead of
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001493 // 64-bit words. This is a necessity of both the "short division" algorithm
Dan Gohman4a618822010-02-10 16:03:48 +00001494 // and the Knuth "classical algorithm" which requires there to be native
Eric Christopher820256b2009-08-21 04:06:45 +00001495 // operations for +, -, and * on an m bit value with an m*2 bit result. We
1496 // can't use 64-bit operands here because we don't have native results of
1497 // 128-bits. Furthermore, casting the 64-bit values to 32-bit values won't
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001498 // work on large-endian machines.
Dan Gohmancff69532009-04-01 18:45:54 +00001499 uint64_t mask = ~0ull >> (sizeof(unsigned)*CHAR_BIT);
Chris Lattner77527f52009-01-21 18:09:24 +00001500 unsigned n = rhsWords * 2;
1501 unsigned m = (lhsWords * 2) - n;
Reid Spencer522ca7c2007-02-25 01:56:07 +00001502
1503 // Allocate space for the temporary values we need either on the stack, if
1504 // it will fit, or on the heap if it won't.
Chris Lattner77527f52009-01-21 18:09:24 +00001505 unsigned SPACE[128];
Craig Topperc10719f2014-04-07 04:17:22 +00001506 unsigned *U = nullptr;
1507 unsigned *V = nullptr;
1508 unsigned *Q = nullptr;
1509 unsigned *R = nullptr;
Reid Spencer522ca7c2007-02-25 01:56:07 +00001510 if ((Remainder?4:3)*n+2*m+1 <= 128) {
1511 U = &SPACE[0];
1512 V = &SPACE[m+n+1];
1513 Q = &SPACE[(m+n+1) + n];
1514 if (Remainder)
1515 R = &SPACE[(m+n+1) + n + (m+n)];
1516 } else {
Chris Lattner77527f52009-01-21 18:09:24 +00001517 U = new unsigned[m + n + 1];
1518 V = new unsigned[n];
1519 Q = new unsigned[m+n];
Reid Spencer522ca7c2007-02-25 01:56:07 +00001520 if (Remainder)
Chris Lattner77527f52009-01-21 18:09:24 +00001521 R = new unsigned[n];
Reid Spencer522ca7c2007-02-25 01:56:07 +00001522 }
1523
1524 // Initialize the dividend
Chris Lattner77527f52009-01-21 18:09:24 +00001525 memset(U, 0, (m+n+1)*sizeof(unsigned));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001526 for (unsigned i = 0; i < lhsWords; ++i) {
Reid Spencer867b4062007-02-22 00:58:45 +00001527 uint64_t tmp = (LHS.getNumWords() == 1 ? LHS.VAL : LHS.pVal[i]);
Chris Lattner77527f52009-01-21 18:09:24 +00001528 U[i * 2] = (unsigned)(tmp & mask);
Dan Gohmancff69532009-04-01 18:45:54 +00001529 U[i * 2 + 1] = (unsigned)(tmp >> (sizeof(unsigned)*CHAR_BIT));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001530 }
1531 U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
1532
Reid Spencer522ca7c2007-02-25 01:56:07 +00001533 // Initialize the divisor
Chris Lattner77527f52009-01-21 18:09:24 +00001534 memset(V, 0, (n)*sizeof(unsigned));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001535 for (unsigned i = 0; i < rhsWords; ++i) {
Reid Spencer867b4062007-02-22 00:58:45 +00001536 uint64_t tmp = (RHS.getNumWords() == 1 ? RHS.VAL : RHS.pVal[i]);
Chris Lattner77527f52009-01-21 18:09:24 +00001537 V[i * 2] = (unsigned)(tmp & mask);
Dan Gohmancff69532009-04-01 18:45:54 +00001538 V[i * 2 + 1] = (unsigned)(tmp >> (sizeof(unsigned)*CHAR_BIT));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001539 }
1540
Reid Spencer522ca7c2007-02-25 01:56:07 +00001541 // initialize the quotient and remainder
Chris Lattner77527f52009-01-21 18:09:24 +00001542 memset(Q, 0, (m+n) * sizeof(unsigned));
Reid Spencer522ca7c2007-02-25 01:56:07 +00001543 if (Remainder)
Chris Lattner77527f52009-01-21 18:09:24 +00001544 memset(R, 0, n * sizeof(unsigned));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001545
Eric Christopher820256b2009-08-21 04:06:45 +00001546 // Now, adjust m and n for the Knuth division. n is the number of words in
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001547 // the divisor. m is the number of words by which the dividend exceeds the
Eric Christopher820256b2009-08-21 04:06:45 +00001548 // divisor (i.e. m+n is the length of the dividend). These sizes must not
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001549 // contain any zero words or the Knuth algorithm fails.
1550 for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
1551 n--;
1552 m++;
1553 }
1554 for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
1555 m--;
1556
1557 // If we're left with only a single word for the divisor, Knuth doesn't work
1558 // so we implement the short division algorithm here. This is much simpler
1559 // and faster because we are certain that we can divide a 64-bit quantity
1560 // by a 32-bit quantity at hardware speed and short division is simply a
1561 // series of such operations. This is just like doing short division but we
1562 // are using base 2^32 instead of base 10.
1563 assert(n != 0 && "Divide by zero?");
1564 if (n == 1) {
Chris Lattner77527f52009-01-21 18:09:24 +00001565 unsigned divisor = V[0];
1566 unsigned remainder = 0;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001567 for (int i = m+n-1; i >= 0; i--) {
1568 uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i];
1569 if (partial_dividend == 0) {
1570 Q[i] = 0;
1571 remainder = 0;
1572 } else if (partial_dividend < divisor) {
1573 Q[i] = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001574 remainder = (unsigned)partial_dividend;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001575 } else if (partial_dividend == divisor) {
1576 Q[i] = 1;
1577 remainder = 0;
1578 } else {
Chris Lattner77527f52009-01-21 18:09:24 +00001579 Q[i] = (unsigned)(partial_dividend / divisor);
1580 remainder = (unsigned)(partial_dividend - (Q[i] * divisor));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001581 }
1582 }
1583 if (R)
1584 R[0] = remainder;
1585 } else {
1586 // Now we're ready to invoke the Knuth classical divide algorithm. In this
1587 // case n > 1.
1588 KnuthDiv(U, V, Q, R, m, n);
1589 }
1590
1591 // If the caller wants the quotient
1592 if (Quotient) {
1593 // Set up the Quotient value's memory.
1594 if (Quotient->BitWidth != LHS.BitWidth) {
1595 if (Quotient->isSingleWord())
1596 Quotient->VAL = 0;
1597 else
Reid Spencer7c16cd22007-02-26 23:38:21 +00001598 delete [] Quotient->pVal;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001599 Quotient->BitWidth = LHS.BitWidth;
1600 if (!Quotient->isSingleWord())
Reid Spencer58a6a432007-02-21 08:21:52 +00001601 Quotient->pVal = getClearedMemory(Quotient->getNumWords());
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001602 } else
Jay Foad25a5e4c2010-12-01 08:53:58 +00001603 Quotient->clearAllBits();
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001604
Eric Christopher820256b2009-08-21 04:06:45 +00001605 // The quotient is in Q. Reconstitute the quotient into Quotient's low
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001606 // order words.
Yaron Keren39fc5a62015-03-26 19:45:19 +00001607 // This case is currently dead as all users of divide() handle trivial cases
1608 // earlier.
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001609 if (lhsWords == 1) {
Eric Christopher820256b2009-08-21 04:06:45 +00001610 uint64_t tmp =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001611 uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2));
1612 if (Quotient->isSingleWord())
1613 Quotient->VAL = tmp;
1614 else
1615 Quotient->pVal[0] = tmp;
1616 } else {
1617 assert(!Quotient->isSingleWord() && "Quotient APInt not large enough");
1618 for (unsigned i = 0; i < lhsWords; ++i)
Eric Christopher820256b2009-08-21 04:06:45 +00001619 Quotient->pVal[i] =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001620 uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1621 }
1622 }
1623
1624 // If the caller wants the remainder
1625 if (Remainder) {
1626 // Set up the Remainder value's memory.
1627 if (Remainder->BitWidth != RHS.BitWidth) {
1628 if (Remainder->isSingleWord())
1629 Remainder->VAL = 0;
1630 else
Reid Spencer7c16cd22007-02-26 23:38:21 +00001631 delete [] Remainder->pVal;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001632 Remainder->BitWidth = RHS.BitWidth;
1633 if (!Remainder->isSingleWord())
Reid Spencer58a6a432007-02-21 08:21:52 +00001634 Remainder->pVal = getClearedMemory(Remainder->getNumWords());
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001635 } else
Jay Foad25a5e4c2010-12-01 08:53:58 +00001636 Remainder->clearAllBits();
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001637
1638 // The remainder is in R. Reconstitute the remainder into Remainder's low
1639 // order words.
1640 if (rhsWords == 1) {
Eric Christopher820256b2009-08-21 04:06:45 +00001641 uint64_t tmp =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001642 uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2));
1643 if (Remainder->isSingleWord())
1644 Remainder->VAL = tmp;
1645 else
1646 Remainder->pVal[0] = tmp;
1647 } else {
1648 assert(!Remainder->isSingleWord() && "Remainder APInt not large enough");
1649 for (unsigned i = 0; i < rhsWords; ++i)
Eric Christopher820256b2009-08-21 04:06:45 +00001650 Remainder->pVal[i] =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001651 uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1652 }
1653 }
1654
1655 // Clean up the memory we allocated.
Reid Spencer522ca7c2007-02-25 01:56:07 +00001656 if (U != &SPACE[0]) {
1657 delete [] U;
1658 delete [] V;
1659 delete [] Q;
1660 delete [] R;
1661 }
Reid Spencer100502d2007-02-17 03:16:00 +00001662}
1663
Reid Spencer1d072122007-02-16 22:36:51 +00001664APInt APInt::udiv(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +00001665 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer39867762007-02-17 02:07:07 +00001666
1667 // First, deal with the easy case
1668 if (isSingleWord()) {
1669 assert(RHS.VAL != 0 && "Divide by zero?");
1670 return APInt(BitWidth, VAL / RHS.VAL);
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001671 }
Reid Spencer39867762007-02-17 02:07:07 +00001672
Reid Spencer39867762007-02-17 02:07:07 +00001673 // Get some facts about the LHS and RHS number of bits and words
Chris Lattner77527f52009-01-21 18:09:24 +00001674 unsigned rhsBits = RHS.getActiveBits();
1675 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001676 assert(rhsWords && "Divided by zero???");
Chris Lattner77527f52009-01-21 18:09:24 +00001677 unsigned lhsBits = this->getActiveBits();
1678 unsigned lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001679
1680 // Deal with some degenerate cases
Eric Christopher820256b2009-08-21 04:06:45 +00001681 if (!lhsWords)
Reid Spencer58a6a432007-02-21 08:21:52 +00001682 // 0 / X ===> 0
Eric Christopher820256b2009-08-21 04:06:45 +00001683 return APInt(BitWidth, 0);
Reid Spencer58a6a432007-02-21 08:21:52 +00001684 else if (lhsWords < rhsWords || this->ult(RHS)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001685 // X / Y ===> 0, iff X < Y
Reid Spencer58a6a432007-02-21 08:21:52 +00001686 return APInt(BitWidth, 0);
1687 } else if (*this == RHS) {
1688 // X / X ===> 1
1689 return APInt(BitWidth, 1);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001690 } else if (lhsWords == 1 && rhsWords == 1) {
Reid Spencer39867762007-02-17 02:07:07 +00001691 // All high words are zero, just use native divide
Reid Spencer58a6a432007-02-21 08:21:52 +00001692 return APInt(BitWidth, this->pVal[0] / RHS.pVal[0]);
Reid Spencer39867762007-02-17 02:07:07 +00001693 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001694
1695 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1696 APInt Quotient(1,0); // to hold result.
Craig Topperc10719f2014-04-07 04:17:22 +00001697 divide(*this, lhsWords, RHS, rhsWords, &Quotient, nullptr);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001698 return Quotient;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001699}
1700
Jakub Staszak6605c602013-02-20 00:17:42 +00001701APInt APInt::sdiv(const APInt &RHS) const {
1702 if (isNegative()) {
1703 if (RHS.isNegative())
1704 return (-(*this)).udiv(-RHS);
1705 return -((-(*this)).udiv(RHS));
1706 }
1707 if (RHS.isNegative())
1708 return -(this->udiv(-RHS));
1709 return this->udiv(RHS);
1710}
1711
Reid Spencer1d072122007-02-16 22:36:51 +00001712APInt APInt::urem(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +00001713 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer39867762007-02-17 02:07:07 +00001714 if (isSingleWord()) {
1715 assert(RHS.VAL != 0 && "Remainder by zero?");
1716 return APInt(BitWidth, VAL % RHS.VAL);
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001717 }
Reid Spencer39867762007-02-17 02:07:07 +00001718
Reid Spencer58a6a432007-02-21 08:21:52 +00001719 // Get some facts about the LHS
Chris Lattner77527f52009-01-21 18:09:24 +00001720 unsigned lhsBits = getActiveBits();
1721 unsigned lhsWords = !lhsBits ? 0 : (whichWord(lhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001722
1723 // Get some facts about the RHS
Chris Lattner77527f52009-01-21 18:09:24 +00001724 unsigned rhsBits = RHS.getActiveBits();
1725 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001726 assert(rhsWords && "Performing remainder operation by zero ???");
1727
Reid Spencer39867762007-02-17 02:07:07 +00001728 // Check the degenerate cases
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001729 if (lhsWords == 0) {
Reid Spencer58a6a432007-02-21 08:21:52 +00001730 // 0 % Y ===> 0
1731 return APInt(BitWidth, 0);
1732 } else if (lhsWords < rhsWords || this->ult(RHS)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001733 // X % Y ===> X, iff X < Y
Reid Spencer58a6a432007-02-21 08:21:52 +00001734 return *this;
1735 } else if (*this == RHS) {
Reid Spencer39867762007-02-17 02:07:07 +00001736 // X % X == 0;
Reid Spencer58a6a432007-02-21 08:21:52 +00001737 return APInt(BitWidth, 0);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001738 } else if (lhsWords == 1) {
Reid Spencer39867762007-02-17 02:07:07 +00001739 // All high words are zero, just use native remainder
Reid Spencer58a6a432007-02-21 08:21:52 +00001740 return APInt(BitWidth, pVal[0] % RHS.pVal[0]);
Reid Spencer39867762007-02-17 02:07:07 +00001741 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001742
Reid Spencer4c50b522007-05-13 23:44:59 +00001743 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001744 APInt Remainder(1,0);
Craig Topperc10719f2014-04-07 04:17:22 +00001745 divide(*this, lhsWords, RHS, rhsWords, nullptr, &Remainder);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001746 return Remainder;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001747}
Reid Spencer100502d2007-02-17 03:16:00 +00001748
Jakub Staszak6605c602013-02-20 00:17:42 +00001749APInt APInt::srem(const APInt &RHS) const {
1750 if (isNegative()) {
1751 if (RHS.isNegative())
1752 return -((-(*this)).urem(-RHS));
1753 return -((-(*this)).urem(RHS));
1754 }
1755 if (RHS.isNegative())
1756 return this->urem(-RHS);
1757 return this->urem(RHS);
1758}
1759
Eric Christopher820256b2009-08-21 04:06:45 +00001760void APInt::udivrem(const APInt &LHS, const APInt &RHS,
Reid Spencer4c50b522007-05-13 23:44:59 +00001761 APInt &Quotient, APInt &Remainder) {
David Majnemer7f039202014-12-14 09:41:56 +00001762 assert(LHS.BitWidth == RHS.BitWidth && "Bit widths must be the same");
1763
1764 // First, deal with the easy case
1765 if (LHS.isSingleWord()) {
1766 assert(RHS.VAL != 0 && "Divide by zero?");
1767 uint64_t QuotVal = LHS.VAL / RHS.VAL;
1768 uint64_t RemVal = LHS.VAL % RHS.VAL;
1769 Quotient = APInt(LHS.BitWidth, QuotVal);
1770 Remainder = APInt(LHS.BitWidth, RemVal);
1771 return;
1772 }
1773
Reid Spencer4c50b522007-05-13 23:44:59 +00001774 // Get some size facts about the dividend and divisor
Chris Lattner77527f52009-01-21 18:09:24 +00001775 unsigned lhsBits = LHS.getActiveBits();
1776 unsigned lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
1777 unsigned rhsBits = RHS.getActiveBits();
1778 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer4c50b522007-05-13 23:44:59 +00001779
1780 // Check the degenerate cases
Eric Christopher820256b2009-08-21 04:06:45 +00001781 if (lhsWords == 0) {
Reid Spencer4c50b522007-05-13 23:44:59 +00001782 Quotient = 0; // 0 / Y ===> 0
1783 Remainder = 0; // 0 % Y ===> 0
1784 return;
Eric Christopher820256b2009-08-21 04:06:45 +00001785 }
1786
1787 if (lhsWords < rhsWords || LHS.ult(RHS)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001788 Remainder = LHS; // X % Y ===> X, iff X < Y
1789 Quotient = 0; // X / Y ===> 0, iff X < Y
Reid Spencer4c50b522007-05-13 23:44:59 +00001790 return;
Eric Christopher820256b2009-08-21 04:06:45 +00001791 }
1792
Reid Spencer4c50b522007-05-13 23:44:59 +00001793 if (LHS == RHS) {
1794 Quotient = 1; // X / X ===> 1
1795 Remainder = 0; // X % X ===> 0;
1796 return;
Eric Christopher820256b2009-08-21 04:06:45 +00001797 }
1798
Reid Spencer4c50b522007-05-13 23:44:59 +00001799 if (lhsWords == 1 && rhsWords == 1) {
1800 // There is only one word to consider so use the native versions.
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001801 uint64_t lhsValue = LHS.isSingleWord() ? LHS.VAL : LHS.pVal[0];
1802 uint64_t rhsValue = RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
1803 Quotient = APInt(LHS.getBitWidth(), lhsValue / rhsValue);
1804 Remainder = APInt(LHS.getBitWidth(), lhsValue % rhsValue);
Reid Spencer4c50b522007-05-13 23:44:59 +00001805 return;
1806 }
1807
1808 // Okay, lets do it the long way
1809 divide(LHS, lhsWords, RHS, rhsWords, &Quotient, &Remainder);
1810}
1811
Jakub Staszak6605c602013-02-20 00:17:42 +00001812void APInt::sdivrem(const APInt &LHS, const APInt &RHS,
1813 APInt &Quotient, APInt &Remainder) {
1814 if (LHS.isNegative()) {
1815 if (RHS.isNegative())
1816 APInt::udivrem(-LHS, -RHS, Quotient, Remainder);
1817 else {
1818 APInt::udivrem(-LHS, RHS, Quotient, Remainder);
1819 Quotient = -Quotient;
1820 }
1821 Remainder = -Remainder;
1822 } else if (RHS.isNegative()) {
1823 APInt::udivrem(LHS, -RHS, Quotient, Remainder);
1824 Quotient = -Quotient;
1825 } else {
1826 APInt::udivrem(LHS, RHS, Quotient, Remainder);
1827 }
1828}
1829
Chris Lattner2c819b02010-10-13 23:54:10 +00001830APInt APInt::sadd_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00001831 APInt Res = *this+RHS;
1832 Overflow = isNonNegative() == RHS.isNonNegative() &&
1833 Res.isNonNegative() != isNonNegative();
1834 return Res;
1835}
1836
Chris Lattner698661c2010-10-14 00:05:07 +00001837APInt APInt::uadd_ov(const APInt &RHS, bool &Overflow) const {
1838 APInt Res = *this+RHS;
1839 Overflow = Res.ult(RHS);
1840 return Res;
1841}
1842
Chris Lattner2c819b02010-10-13 23:54:10 +00001843APInt APInt::ssub_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00001844 APInt Res = *this - RHS;
1845 Overflow = isNonNegative() != RHS.isNonNegative() &&
1846 Res.isNonNegative() != isNonNegative();
1847 return Res;
1848}
1849
Chris Lattner698661c2010-10-14 00:05:07 +00001850APInt APInt::usub_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattnerb9681ad2010-10-14 00:30:00 +00001851 APInt Res = *this-RHS;
1852 Overflow = Res.ugt(*this);
Chris Lattner698661c2010-10-14 00:05:07 +00001853 return Res;
1854}
1855
Chris Lattner2c819b02010-10-13 23:54:10 +00001856APInt APInt::sdiv_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00001857 // MININT/-1 --> overflow.
1858 Overflow = isMinSignedValue() && RHS.isAllOnesValue();
1859 return sdiv(RHS);
1860}
1861
Chris Lattner2c819b02010-10-13 23:54:10 +00001862APInt APInt::smul_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00001863 APInt Res = *this * RHS;
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +00001864
Chris Lattner79bdd882010-10-13 23:46:33 +00001865 if (*this != 0 && RHS != 0)
1866 Overflow = Res.sdiv(RHS) != *this || Res.sdiv(*this) != RHS;
1867 else
1868 Overflow = false;
1869 return Res;
1870}
1871
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001872APInt APInt::umul_ov(const APInt &RHS, bool &Overflow) const {
1873 APInt Res = *this * RHS;
1874
1875 if (*this != 0 && RHS != 0)
1876 Overflow = Res.udiv(RHS) != *this || Res.udiv(*this) != RHS;
1877 else
1878 Overflow = false;
1879 return Res;
1880}
1881
David Majnemera2521382014-10-13 21:48:30 +00001882APInt APInt::sshl_ov(const APInt &ShAmt, bool &Overflow) const {
1883 Overflow = ShAmt.uge(getBitWidth());
Chris Lattner79bdd882010-10-13 23:46:33 +00001884 if (Overflow)
David Majnemera2521382014-10-13 21:48:30 +00001885 return APInt(BitWidth, 0);
Chris Lattner79bdd882010-10-13 23:46:33 +00001886
1887 if (isNonNegative()) // Don't allow sign change.
David Majnemera2521382014-10-13 21:48:30 +00001888 Overflow = ShAmt.uge(countLeadingZeros());
Chris Lattner79bdd882010-10-13 23:46:33 +00001889 else
David Majnemera2521382014-10-13 21:48:30 +00001890 Overflow = ShAmt.uge(countLeadingOnes());
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +00001891
Chris Lattner79bdd882010-10-13 23:46:33 +00001892 return *this << ShAmt;
1893}
1894
David Majnemera2521382014-10-13 21:48:30 +00001895APInt APInt::ushl_ov(const APInt &ShAmt, bool &Overflow) const {
1896 Overflow = ShAmt.uge(getBitWidth());
1897 if (Overflow)
1898 return APInt(BitWidth, 0);
1899
1900 Overflow = ShAmt.ugt(countLeadingZeros());
1901
1902 return *this << ShAmt;
1903}
1904
Chris Lattner79bdd882010-10-13 23:46:33 +00001905
1906
1907
Benjamin Kramer92d89982010-07-14 22:38:02 +00001908void APInt::fromString(unsigned numbits, StringRef str, uint8_t radix) {
Reid Spencer1ba83352007-02-21 03:55:44 +00001909 // Check our assumptions here
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00001910 assert(!str.empty() && "Invalid string length");
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +00001911 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 ||
Douglas Gregor663c0682011-09-14 15:54:46 +00001912 radix == 36) &&
1913 "Radix should be 2, 8, 10, 16, or 36!");
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00001914
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00001915 StringRef::iterator p = str.begin();
1916 size_t slen = str.size();
1917 bool isNeg = *p == '-';
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00001918 if (*p == '-' || *p == '+') {
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00001919 p++;
1920 slen--;
Eric Christopher43a1dec2009-08-21 04:10:31 +00001921 assert(slen && "String is only a sign, needs a value.");
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00001922 }
Chris Lattnerdad2d092007-05-03 18:15:36 +00001923 assert((slen <= numbits || radix != 2) && "Insufficient bit width");
Chris Lattnerb869a0a2009-04-25 18:34:04 +00001924 assert(((slen-1)*3 <= numbits || radix != 8) && "Insufficient bit width");
1925 assert(((slen-1)*4 <= numbits || radix != 16) && "Insufficient bit width");
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001926 assert((((slen-1)*64)/22 <= numbits || radix != 10) &&
1927 "Insufficient bit width");
Reid Spencer1ba83352007-02-21 03:55:44 +00001928
1929 // Allocate memory
1930 if (!isSingleWord())
1931 pVal = getClearedMemory(getNumWords());
1932
1933 // Figure out if we can shift instead of multiply
Chris Lattner77527f52009-01-21 18:09:24 +00001934 unsigned shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0);
Reid Spencer1ba83352007-02-21 03:55:44 +00001935
Craig Topperb7d8faa2017-04-02 06:59:38 +00001936 // Set up an APInt for the radix multiplier outside the loop so we don't
Reid Spencer1ba83352007-02-21 03:55:44 +00001937 // constantly construct/destruct it.
Reid Spencer1ba83352007-02-21 03:55:44 +00001938 APInt apradix(getBitWidth(), radix);
1939
1940 // Enter digit traversal loop
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00001941 for (StringRef::iterator e = str.end(); p != e; ++p) {
Erick Tryzelaardadb15712009-08-21 03:15:28 +00001942 unsigned digit = getDigit(*p, radix);
Erick Tryzelaar60964092009-08-21 06:48:37 +00001943 assert(digit < radix && "Invalid character in digit string");
Reid Spencer1ba83352007-02-21 03:55:44 +00001944
Reid Spencera93c9812007-05-16 19:18:22 +00001945 // Shift or multiply the value by the radix
Chris Lattnerb869a0a2009-04-25 18:34:04 +00001946 if (slen > 1) {
1947 if (shift)
1948 *this <<= shift;
1949 else
1950 *this *= apradix;
1951 }
Reid Spencer1ba83352007-02-21 03:55:44 +00001952
1953 // Add in the digit we just interpreted
Craig Topperb7d8faa2017-04-02 06:59:38 +00001954 *this += digit;
Reid Spencer100502d2007-02-17 03:16:00 +00001955 }
Reid Spencerb6b5cc32007-02-25 23:44:53 +00001956 // If its negative, put it in two's complement form
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001957 if (isNeg) {
Jakub Staszak773be0c2013-03-20 23:56:19 +00001958 --(*this);
Jay Foad25a5e4c2010-12-01 08:53:58 +00001959 this->flipAllBits();
Reid Spencerb6b5cc32007-02-25 23:44:53 +00001960 }
Reid Spencer100502d2007-02-17 03:16:00 +00001961}
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001962
Chris Lattner17f71652008-08-17 07:19:36 +00001963void APInt::toString(SmallVectorImpl<char> &Str, unsigned Radix,
Ted Kremenekb05f02e2011-06-15 00:51:55 +00001964 bool Signed, bool formatAsCLiteral) const {
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +00001965 assert((Radix == 10 || Radix == 8 || Radix == 16 || Radix == 2 ||
Douglas Gregor663c0682011-09-14 15:54:46 +00001966 Radix == 36) &&
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00001967 "Radix should be 2, 8, 10, 16, or 36!");
Eric Christopher820256b2009-08-21 04:06:45 +00001968
Ted Kremenekb05f02e2011-06-15 00:51:55 +00001969 const char *Prefix = "";
1970 if (formatAsCLiteral) {
1971 switch (Radix) {
1972 case 2:
1973 // Binary literals are a non-standard extension added in gcc 4.3:
1974 // http://gcc.gnu.org/onlinedocs/gcc-4.3.0/gcc/Binary-constants.html
1975 Prefix = "0b";
1976 break;
1977 case 8:
1978 Prefix = "0";
1979 break;
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00001980 case 10:
1981 break; // No prefix
Ted Kremenekb05f02e2011-06-15 00:51:55 +00001982 case 16:
1983 Prefix = "0x";
1984 break;
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00001985 default:
1986 llvm_unreachable("Invalid radix!");
Ted Kremenekb05f02e2011-06-15 00:51:55 +00001987 }
1988 }
1989
Chris Lattner17f71652008-08-17 07:19:36 +00001990 // First, check for a zero value and just short circuit the logic below.
1991 if (*this == 0) {
Ted Kremenekb05f02e2011-06-15 00:51:55 +00001992 while (*Prefix) {
1993 Str.push_back(*Prefix);
1994 ++Prefix;
1995 };
Chris Lattner17f71652008-08-17 07:19:36 +00001996 Str.push_back('0');
1997 return;
1998 }
Eric Christopher820256b2009-08-21 04:06:45 +00001999
Douglas Gregor663c0682011-09-14 15:54:46 +00002000 static const char Digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Eric Christopher820256b2009-08-21 04:06:45 +00002001
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002002 if (isSingleWord()) {
Chris Lattner17f71652008-08-17 07:19:36 +00002003 char Buffer[65];
2004 char *BufPtr = Buffer+65;
Eric Christopher820256b2009-08-21 04:06:45 +00002005
Chris Lattner17f71652008-08-17 07:19:36 +00002006 uint64_t N;
Chris Lattnerb91c9032010-08-18 00:33:47 +00002007 if (!Signed) {
Chris Lattner17f71652008-08-17 07:19:36 +00002008 N = getZExtValue();
Chris Lattnerb91c9032010-08-18 00:33:47 +00002009 } else {
2010 int64_t I = getSExtValue();
2011 if (I >= 0) {
2012 N = I;
2013 } else {
2014 Str.push_back('-');
2015 N = -(uint64_t)I;
2016 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002017 }
Eric Christopher820256b2009-08-21 04:06:45 +00002018
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002019 while (*Prefix) {
2020 Str.push_back(*Prefix);
2021 ++Prefix;
2022 };
2023
Chris Lattner17f71652008-08-17 07:19:36 +00002024 while (N) {
2025 *--BufPtr = Digits[N % Radix];
2026 N /= Radix;
2027 }
2028 Str.append(BufPtr, Buffer+65);
2029 return;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002030 }
2031
Chris Lattner17f71652008-08-17 07:19:36 +00002032 APInt Tmp(*this);
Eric Christopher820256b2009-08-21 04:06:45 +00002033
Chris Lattner17f71652008-08-17 07:19:36 +00002034 if (Signed && isNegative()) {
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002035 // They want to print the signed version and it is a negative value
2036 // Flip the bits and add one to turn it into the equivalent positive
2037 // value and put a '-' in the result.
Jay Foad25a5e4c2010-12-01 08:53:58 +00002038 Tmp.flipAllBits();
Jakub Staszak773be0c2013-03-20 23:56:19 +00002039 ++Tmp;
Chris Lattner17f71652008-08-17 07:19:36 +00002040 Str.push_back('-');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002041 }
Eric Christopher820256b2009-08-21 04:06:45 +00002042
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002043 while (*Prefix) {
2044 Str.push_back(*Prefix);
2045 ++Prefix;
2046 };
2047
Chris Lattner17f71652008-08-17 07:19:36 +00002048 // We insert the digits backward, then reverse them to get the right order.
2049 unsigned StartDig = Str.size();
Eric Christopher820256b2009-08-21 04:06:45 +00002050
2051 // For the 2, 8 and 16 bit cases, we can just shift instead of divide
2052 // because the number of bits per digit (1, 3 and 4 respectively) divides
Craig Topperd7ed50d2017-04-02 06:59:36 +00002053 // equally. We just shift until the value is zero.
Douglas Gregor663c0682011-09-14 15:54:46 +00002054 if (Radix == 2 || Radix == 8 || Radix == 16) {
Chris Lattner17f71652008-08-17 07:19:36 +00002055 // Just shift tmp right for each digit width until it becomes zero
2056 unsigned ShiftAmt = (Radix == 16 ? 4 : (Radix == 8 ? 3 : 1));
2057 unsigned MaskAmt = Radix - 1;
Eric Christopher820256b2009-08-21 04:06:45 +00002058
Chris Lattner17f71652008-08-17 07:19:36 +00002059 while (Tmp != 0) {
2060 unsigned Digit = unsigned(Tmp.getRawData()[0]) & MaskAmt;
2061 Str.push_back(Digits[Digit]);
Craig Topperfc947bc2017-04-18 17:14:21 +00002062 Tmp.lshrInPlace(ShiftAmt);
Chris Lattner17f71652008-08-17 07:19:36 +00002063 }
2064 } else {
Douglas Gregor663c0682011-09-14 15:54:46 +00002065 APInt divisor(Radix == 10? 4 : 8, Radix);
Chris Lattner17f71652008-08-17 07:19:36 +00002066 while (Tmp != 0) {
2067 APInt APdigit(1, 0);
2068 APInt tmp2(Tmp.getBitWidth(), 0);
Eric Christopher820256b2009-08-21 04:06:45 +00002069 divide(Tmp, Tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2,
Chris Lattner17f71652008-08-17 07:19:36 +00002070 &APdigit);
Chris Lattner77527f52009-01-21 18:09:24 +00002071 unsigned Digit = (unsigned)APdigit.getZExtValue();
Chris Lattner17f71652008-08-17 07:19:36 +00002072 assert(Digit < Radix && "divide failed");
2073 Str.push_back(Digits[Digit]);
2074 Tmp = tmp2;
2075 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002076 }
Eric Christopher820256b2009-08-21 04:06:45 +00002077
Chris Lattner17f71652008-08-17 07:19:36 +00002078 // Reverse the digits before returning.
2079 std::reverse(Str.begin()+StartDig, Str.end());
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002080}
2081
Pawel Bylica6eeeac72015-04-06 13:31:39 +00002082/// Returns the APInt as a std::string. Note that this is an inefficient method.
2083/// It is better to pass in a SmallVector/SmallString to the methods above.
Chris Lattner17f71652008-08-17 07:19:36 +00002084std::string APInt::toString(unsigned Radix = 10, bool Signed = true) const {
2085 SmallString<40> S;
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002086 toString(S, Radix, Signed, /* formatAsCLiteral = */false);
Daniel Dunbar8b0b1152009-08-19 20:07:03 +00002087 return S.str();
Reid Spencer1ba83352007-02-21 03:55:44 +00002088}
Chris Lattner6b695682007-08-16 15:56:55 +00002089
Matthias Braun8c209aa2017-01-28 02:02:38 +00002090#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Kereneb2a2542016-01-29 20:50:44 +00002091LLVM_DUMP_METHOD void APInt::dump() const {
Chris Lattner17f71652008-08-17 07:19:36 +00002092 SmallString<40> S, U;
2093 this->toStringUnsigned(U);
2094 this->toStringSigned(S);
David Greenef32fcb42010-01-05 01:28:52 +00002095 dbgs() << "APInt(" << BitWidth << "b, "
Davide Italiano5a473d22017-01-31 21:26:18 +00002096 << U << "u " << S << "s)\n";
Chris Lattner17f71652008-08-17 07:19:36 +00002097}
Matthias Braun8c209aa2017-01-28 02:02:38 +00002098#endif
Chris Lattner17f71652008-08-17 07:19:36 +00002099
Chris Lattner0c19df42008-08-23 22:23:09 +00002100void APInt::print(raw_ostream &OS, bool isSigned) const {
Chris Lattner17f71652008-08-17 07:19:36 +00002101 SmallString<40> S;
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002102 this->toString(S, 10, isSigned, /* formatAsCLiteral = */false);
Yaron Keren92e1b622015-03-18 10:17:07 +00002103 OS << S;
Chris Lattner17f71652008-08-17 07:19:36 +00002104}
2105
Chris Lattner6b695682007-08-16 15:56:55 +00002106// This implements a variety of operations on a representation of
2107// arbitrary precision, two's-complement, bignum integer values.
2108
Chris Lattner96cffa62009-08-23 23:11:28 +00002109// Assumed by lowHalf, highHalf, partMSB and partLSB. A fairly safe
2110// and unrestricting assumption.
Craig Topper55229b72017-04-02 19:17:22 +00002111static_assert(APInt::APINT_BITS_PER_WORD % 2 == 0,
2112 "Part width must be divisible by 2!");
Chris Lattner6b695682007-08-16 15:56:55 +00002113
2114/* Some handy functions local to this file. */
Chris Lattner6b695682007-08-16 15:56:55 +00002115
Craig Topper76f42462017-03-28 05:32:53 +00002116/* Returns the integer part with the least significant BITS set.
2117 BITS cannot be zero. */
Craig Topper55229b72017-04-02 19:17:22 +00002118static inline APInt::WordType lowBitMask(unsigned bits) {
2119 assert(bits != 0 && bits <= APInt::APINT_BITS_PER_WORD);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002120
Craig Topper55229b72017-04-02 19:17:22 +00002121 return ~(APInt::WordType) 0 >> (APInt::APINT_BITS_PER_WORD - bits);
Craig Topper76f42462017-03-28 05:32:53 +00002122}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002123
Craig Topper76f42462017-03-28 05:32:53 +00002124/* Returns the value of the lower half of PART. */
Craig Topper55229b72017-04-02 19:17:22 +00002125static inline APInt::WordType lowHalf(APInt::WordType part) {
2126 return part & lowBitMask(APInt::APINT_BITS_PER_WORD / 2);
Craig Topper76f42462017-03-28 05:32:53 +00002127}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002128
Craig Topper76f42462017-03-28 05:32:53 +00002129/* Returns the value of the upper half of PART. */
Craig Topper55229b72017-04-02 19:17:22 +00002130static inline APInt::WordType highHalf(APInt::WordType part) {
2131 return part >> (APInt::APINT_BITS_PER_WORD / 2);
Craig Topper76f42462017-03-28 05:32:53 +00002132}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002133
Craig Topper76f42462017-03-28 05:32:53 +00002134/* Returns the bit number of the most significant set bit of a part.
2135 If the input number has no bits set -1U is returned. */
Craig Topper55229b72017-04-02 19:17:22 +00002136static unsigned partMSB(APInt::WordType value) {
Craig Topper76f42462017-03-28 05:32:53 +00002137 return findLastSet(value, ZB_Max);
2138}
Chris Lattner6b695682007-08-16 15:56:55 +00002139
Craig Topper76f42462017-03-28 05:32:53 +00002140/* Returns the bit number of the least significant set bit of a
2141 part. If the input number has no bits set -1U is returned. */
Craig Topper55229b72017-04-02 19:17:22 +00002142static unsigned partLSB(APInt::WordType value) {
Craig Topper76f42462017-03-28 05:32:53 +00002143 return findFirstSet(value, ZB_Max);
Alexander Kornienkof00654e2015-06-23 09:49:53 +00002144}
Chris Lattner6b695682007-08-16 15:56:55 +00002145
2146/* Sets the least significant part of a bignum to the input value, and
2147 zeroes out higher parts. */
Craig Topper55229b72017-04-02 19:17:22 +00002148void APInt::tcSet(WordType *dst, WordType part, unsigned parts) {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002149 assert(parts > 0);
Neil Boothb6182162007-10-08 13:47:12 +00002150
Chris Lattner6b695682007-08-16 15:56:55 +00002151 dst[0] = part;
Craig Topperb0038162017-03-28 05:32:52 +00002152 for (unsigned i = 1; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002153 dst[i] = 0;
2154}
2155
2156/* Assign one bignum to another. */
Craig Topper55229b72017-04-02 19:17:22 +00002157void APInt::tcAssign(WordType *dst, const WordType *src, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002158 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002159 dst[i] = src[i];
2160}
2161
2162/* Returns true if a bignum is zero, false otherwise. */
Craig Topper55229b72017-04-02 19:17:22 +00002163bool APInt::tcIsZero(const WordType *src, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002164 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002165 if (src[i])
2166 return false;
2167
2168 return true;
2169}
2170
2171/* Extract the given bit of a bignum; returns 0 or 1. */
Craig Topper55229b72017-04-02 19:17:22 +00002172int APInt::tcExtractBit(const WordType *parts, unsigned bit) {
Craig Topper00b47ee2017-04-02 19:35:18 +00002173 return (parts[whichWord(bit)] & maskBit(bit)) != 0;
Chris Lattner6b695682007-08-16 15:56:55 +00002174}
2175
John McCalldcb9a7a2010-02-28 02:51:25 +00002176/* Set the given bit of a bignum. */
Craig Topper55229b72017-04-02 19:17:22 +00002177void APInt::tcSetBit(WordType *parts, unsigned bit) {
Craig Topper00b47ee2017-04-02 19:35:18 +00002178 parts[whichWord(bit)] |= maskBit(bit);
Chris Lattner6b695682007-08-16 15:56:55 +00002179}
2180
John McCalldcb9a7a2010-02-28 02:51:25 +00002181/* Clears the given bit of a bignum. */
Craig Topper55229b72017-04-02 19:17:22 +00002182void APInt::tcClearBit(WordType *parts, unsigned bit) {
Craig Topper00b47ee2017-04-02 19:35:18 +00002183 parts[whichWord(bit)] &= ~maskBit(bit);
John McCalldcb9a7a2010-02-28 02:51:25 +00002184}
2185
Neil Boothc8b650a2007-10-06 00:43:45 +00002186/* Returns the bit number of the least significant set bit of a
2187 number. If the input number has no bits set -1U is returned. */
Craig Topper55229b72017-04-02 19:17:22 +00002188unsigned APInt::tcLSB(const WordType *parts, unsigned n) {
Craig Topperb0038162017-03-28 05:32:52 +00002189 for (unsigned i = 0; i < n; i++) {
2190 if (parts[i] != 0) {
2191 unsigned lsb = partLSB(parts[i]);
Chris Lattner6b695682007-08-16 15:56:55 +00002192
Craig Topper55229b72017-04-02 19:17:22 +00002193 return lsb + i * APINT_BITS_PER_WORD;
Craig Topperb0038162017-03-28 05:32:52 +00002194 }
Chris Lattner6b695682007-08-16 15:56:55 +00002195 }
2196
2197 return -1U;
2198}
2199
Neil Boothc8b650a2007-10-06 00:43:45 +00002200/* Returns the bit number of the most significant set bit of a number.
2201 If the input number has no bits set -1U is returned. */
Craig Topper55229b72017-04-02 19:17:22 +00002202unsigned APInt::tcMSB(const WordType *parts, unsigned n) {
Chris Lattner6b695682007-08-16 15:56:55 +00002203 do {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002204 --n;
Chris Lattner6b695682007-08-16 15:56:55 +00002205
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002206 if (parts[n] != 0) {
Craig Topperb0038162017-03-28 05:32:52 +00002207 unsigned msb = partMSB(parts[n]);
Chris Lattner6b695682007-08-16 15:56:55 +00002208
Craig Topper55229b72017-04-02 19:17:22 +00002209 return msb + n * APINT_BITS_PER_WORD;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002210 }
Chris Lattner6b695682007-08-16 15:56:55 +00002211 } while (n);
2212
2213 return -1U;
2214}
2215
Neil Boothb6182162007-10-08 13:47:12 +00002216/* Copy the bit vector of width srcBITS from SRC, starting at bit
2217 srcLSB, to DST, of dstCOUNT parts, such that the bit srcLSB becomes
2218 the least significant bit of DST. All high bits above srcBITS in
2219 DST are zero-filled. */
2220void
Craig Topper55229b72017-04-02 19:17:22 +00002221APInt::tcExtract(WordType *dst, unsigned dstCount, const WordType *src,
Craig Topper6a8518082017-03-28 05:32:55 +00002222 unsigned srcBits, unsigned srcLSB) {
Craig Topper55229b72017-04-02 19:17:22 +00002223 unsigned dstParts = (srcBits + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002224 assert(dstParts <= dstCount);
Neil Boothb6182162007-10-08 13:47:12 +00002225
Craig Topper55229b72017-04-02 19:17:22 +00002226 unsigned firstSrcPart = srcLSB / APINT_BITS_PER_WORD;
Neil Boothb6182162007-10-08 13:47:12 +00002227 tcAssign (dst, src + firstSrcPart, dstParts);
2228
Craig Topper55229b72017-04-02 19:17:22 +00002229 unsigned shift = srcLSB % APINT_BITS_PER_WORD;
Neil Boothb6182162007-10-08 13:47:12 +00002230 tcShiftRight (dst, dstParts, shift);
2231
Craig Topper55229b72017-04-02 19:17:22 +00002232 /* We now have (dstParts * APINT_BITS_PER_WORD - shift) bits from SRC
Neil Boothb6182162007-10-08 13:47:12 +00002233 in DST. If this is less that srcBits, append the rest, else
2234 clear the high bits. */
Craig Topper55229b72017-04-02 19:17:22 +00002235 unsigned n = dstParts * APINT_BITS_PER_WORD - shift;
Neil Boothb6182162007-10-08 13:47:12 +00002236 if (n < srcBits) {
Craig Topper55229b72017-04-02 19:17:22 +00002237 WordType mask = lowBitMask (srcBits - n);
Neil Boothb6182162007-10-08 13:47:12 +00002238 dst[dstParts - 1] |= ((src[firstSrcPart + dstParts] & mask)
Craig Topper55229b72017-04-02 19:17:22 +00002239 << n % APINT_BITS_PER_WORD);
Neil Boothb6182162007-10-08 13:47:12 +00002240 } else if (n > srcBits) {
Craig Topper55229b72017-04-02 19:17:22 +00002241 if (srcBits % APINT_BITS_PER_WORD)
2242 dst[dstParts - 1] &= lowBitMask (srcBits % APINT_BITS_PER_WORD);
Neil Boothb6182162007-10-08 13:47:12 +00002243 }
2244
2245 /* Clear high parts. */
2246 while (dstParts < dstCount)
2247 dst[dstParts++] = 0;
2248}
2249
Chris Lattner6b695682007-08-16 15:56:55 +00002250/* DST += RHS + C where C is zero or one. Returns the carry flag. */
Craig Topper55229b72017-04-02 19:17:22 +00002251APInt::WordType APInt::tcAdd(WordType *dst, const WordType *rhs,
2252 WordType c, unsigned parts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002253 assert(c <= 1);
2254
Craig Topperb0038162017-03-28 05:32:52 +00002255 for (unsigned i = 0; i < parts; i++) {
Craig Topper55229b72017-04-02 19:17:22 +00002256 WordType l = dst[i];
Chris Lattner6b695682007-08-16 15:56:55 +00002257 if (c) {
2258 dst[i] += rhs[i] + 1;
2259 c = (dst[i] <= l);
2260 } else {
2261 dst[i] += rhs[i];
2262 c = (dst[i] < l);
2263 }
2264 }
2265
2266 return c;
2267}
2268
Craig Topper92fc4772017-04-13 04:36:06 +00002269/// This function adds a single "word" integer, src, to the multiple
2270/// "word" integer array, dst[]. dst[] is modified to reflect the addition and
2271/// 1 is returned if there is a carry out, otherwise 0 is returned.
2272/// @returns the carry of the addition.
2273APInt::WordType APInt::tcAddPart(WordType *dst, WordType src,
2274 unsigned parts) {
2275 for (unsigned i = 0; i < parts; ++i) {
2276 dst[i] += src;
2277 if (dst[i] >= src)
2278 return 0; // No need to carry so exit early.
2279 src = 1; // Carry one to next digit.
2280 }
2281
2282 return 1;
2283}
2284
Chris Lattner6b695682007-08-16 15:56:55 +00002285/* DST -= RHS + C where C is zero or one. Returns the carry flag. */
Craig Topper55229b72017-04-02 19:17:22 +00002286APInt::WordType APInt::tcSubtract(WordType *dst, const WordType *rhs,
2287 WordType c, unsigned parts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002288 assert(c <= 1);
2289
Craig Topperb0038162017-03-28 05:32:52 +00002290 for (unsigned i = 0; i < parts; i++) {
Craig Topper55229b72017-04-02 19:17:22 +00002291 WordType l = dst[i];
Chris Lattner6b695682007-08-16 15:56:55 +00002292 if (c) {
2293 dst[i] -= rhs[i] + 1;
2294 c = (dst[i] >= l);
2295 } else {
2296 dst[i] -= rhs[i];
2297 c = (dst[i] > l);
2298 }
2299 }
2300
2301 return c;
2302}
2303
Craig Topper92fc4772017-04-13 04:36:06 +00002304/// This function subtracts a single "word" (64-bit word), src, from
2305/// the multi-word integer array, dst[], propagating the borrowed 1 value until
2306/// no further borrowing is needed or it runs out of "words" in dst. The result
2307/// is 1 if "borrowing" exhausted the digits in dst, or 0 if dst was not
2308/// exhausted. In other words, if src > dst then this function returns 1,
2309/// otherwise 0.
2310/// @returns the borrow out of the subtraction
2311APInt::WordType APInt::tcSubtractPart(WordType *dst, WordType src,
2312 unsigned parts) {
2313 for (unsigned i = 0; i < parts; ++i) {
2314 WordType Dst = dst[i];
2315 dst[i] -= src;
2316 if (src <= Dst)
2317 return 0; // No need to borrow so exit early.
2318 src = 1; // We have to "borrow 1" from next "word"
2319 }
2320
2321 return 1;
2322}
2323
Chris Lattner6b695682007-08-16 15:56:55 +00002324/* Negate a bignum in-place. */
Craig Topper55229b72017-04-02 19:17:22 +00002325void APInt::tcNegate(WordType *dst, unsigned parts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002326 tcComplement(dst, parts);
2327 tcIncrement(dst, parts);
2328}
2329
Neil Boothc8b650a2007-10-06 00:43:45 +00002330/* DST += SRC * MULTIPLIER + CARRY if add is true
2331 DST = SRC * MULTIPLIER + CARRY if add is false
Chris Lattner6b695682007-08-16 15:56:55 +00002332
2333 Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC
2334 they must start at the same point, i.e. DST == SRC.
2335
2336 If DSTPARTS == SRCPARTS + 1 no overflow occurs and zero is
2337 returned. Otherwise DST is filled with the least significant
2338 DSTPARTS parts of the result, and if all of the omitted higher
2339 parts were zero return zero, otherwise overflow occurred and
2340 return one. */
Craig Topper55229b72017-04-02 19:17:22 +00002341int APInt::tcMultiplyPart(WordType *dst, const WordType *src,
2342 WordType multiplier, WordType carry,
Craig Topper6a8518082017-03-28 05:32:55 +00002343 unsigned srcParts, unsigned dstParts,
2344 bool add) {
Chris Lattner6b695682007-08-16 15:56:55 +00002345 /* Otherwise our writes of DST kill our later reads of SRC. */
2346 assert(dst <= src || dst >= src + srcParts);
2347 assert(dstParts <= srcParts + 1);
2348
2349 /* N loops; minimum of dstParts and srcParts. */
Craig Topperb0038162017-03-28 05:32:52 +00002350 unsigned n = dstParts < srcParts ? dstParts: srcParts;
Chris Lattner6b695682007-08-16 15:56:55 +00002351
Craig Topperb0038162017-03-28 05:32:52 +00002352 unsigned i;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002353 for (i = 0; i < n; i++) {
Craig Topper55229b72017-04-02 19:17:22 +00002354 WordType low, mid, high, srcPart;
Chris Lattner6b695682007-08-16 15:56:55 +00002355
2356 /* [ LOW, HIGH ] = MULTIPLIER * SRC[i] + DST[i] + CARRY.
2357
2358 This cannot overflow, because
2359
2360 (n - 1) * (n - 1) + 2 (n - 1) = (n - 1) * (n + 1)
2361
2362 which is less than n^2. */
2363
2364 srcPart = src[i];
2365
Craig Topper6a8518082017-03-28 05:32:55 +00002366 if (multiplier == 0 || srcPart == 0) {
Chris Lattner6b695682007-08-16 15:56:55 +00002367 low = carry;
2368 high = 0;
2369 } else {
2370 low = lowHalf(srcPart) * lowHalf(multiplier);
2371 high = highHalf(srcPart) * highHalf(multiplier);
2372
2373 mid = lowHalf(srcPart) * highHalf(multiplier);
2374 high += highHalf(mid);
Craig Topper55229b72017-04-02 19:17:22 +00002375 mid <<= APINT_BITS_PER_WORD / 2;
Chris Lattner6b695682007-08-16 15:56:55 +00002376 if (low + mid < low)
2377 high++;
2378 low += mid;
2379
2380 mid = highHalf(srcPart) * lowHalf(multiplier);
2381 high += highHalf(mid);
Craig Topper55229b72017-04-02 19:17:22 +00002382 mid <<= APINT_BITS_PER_WORD / 2;
Chris Lattner6b695682007-08-16 15:56:55 +00002383 if (low + mid < low)
2384 high++;
2385 low += mid;
2386
2387 /* Now add carry. */
2388 if (low + carry < low)
2389 high++;
2390 low += carry;
2391 }
2392
2393 if (add) {
2394 /* And now DST[i], and store the new low part there. */
2395 if (low + dst[i] < low)
2396 high++;
2397 dst[i] += low;
2398 } else
2399 dst[i] = low;
2400
2401 carry = high;
2402 }
2403
2404 if (i < dstParts) {
2405 /* Full multiplication, there is no overflow. */
2406 assert(i + 1 == dstParts);
2407 dst[i] = carry;
2408 return 0;
2409 } else {
2410 /* We overflowed if there is carry. */
2411 if (carry)
2412 return 1;
2413
2414 /* We would overflow if any significant unwritten parts would be
2415 non-zero. This is true if any remaining src parts are non-zero
2416 and the multiplier is non-zero. */
2417 if (multiplier)
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002418 for (; i < srcParts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002419 if (src[i])
2420 return 1;
2421
2422 /* We fitted in the narrow destination. */
2423 return 0;
2424 }
2425}
2426
2427/* DST = LHS * RHS, where DST has the same width as the operands and
2428 is filled with the least significant parts of the result. Returns
2429 one if overflow occurred, otherwise zero. DST must be disjoint
2430 from both operands. */
Craig Topper55229b72017-04-02 19:17:22 +00002431int APInt::tcMultiply(WordType *dst, const WordType *lhs,
2432 const WordType *rhs, unsigned parts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002433 assert(dst != lhs && dst != rhs);
2434
Craig Topperb0038162017-03-28 05:32:52 +00002435 int overflow = 0;
Chris Lattner6b695682007-08-16 15:56:55 +00002436 tcSet(dst, 0, parts);
2437
Craig Topperb0038162017-03-28 05:32:52 +00002438 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002439 overflow |= tcMultiplyPart(&dst[i], lhs, rhs[i], 0, parts,
2440 parts - i, true);
2441
2442 return overflow;
2443}
2444
Neil Booth0ea72a92007-10-06 00:24:48 +00002445/* DST = LHS * RHS, where DST has width the sum of the widths of the
2446 operands. No overflow occurs. DST must be disjoint from both
2447 operands. Returns the number of parts required to hold the
2448 result. */
Craig Topper55229b72017-04-02 19:17:22 +00002449unsigned APInt::tcFullMultiply(WordType *dst, const WordType *lhs,
2450 const WordType *rhs, unsigned lhsParts,
Craig Topper6a8518082017-03-28 05:32:55 +00002451 unsigned rhsParts) {
Neil Booth0ea72a92007-10-06 00:24:48 +00002452 /* Put the narrower number on the LHS for less loops below. */
2453 if (lhsParts > rhsParts) {
2454 return tcFullMultiply (dst, rhs, lhs, rhsParts, lhsParts);
2455 } else {
Neil Booth0ea72a92007-10-06 00:24:48 +00002456 assert(dst != lhs && dst != rhs);
Chris Lattner6b695682007-08-16 15:56:55 +00002457
Neil Booth0ea72a92007-10-06 00:24:48 +00002458 tcSet(dst, 0, rhsParts);
Chris Lattner6b695682007-08-16 15:56:55 +00002459
Craig Topperb0038162017-03-28 05:32:52 +00002460 for (unsigned i = 0; i < lhsParts; i++)
2461 tcMultiplyPart(&dst[i], rhs, lhs[i], 0, rhsParts, rhsParts + 1, true);
Chris Lattner6b695682007-08-16 15:56:55 +00002462
Craig Topperb0038162017-03-28 05:32:52 +00002463 unsigned n = lhsParts + rhsParts;
Neil Booth0ea72a92007-10-06 00:24:48 +00002464
2465 return n - (dst[n - 1] == 0);
2466 }
Chris Lattner6b695682007-08-16 15:56:55 +00002467}
2468
2469/* If RHS is zero LHS and REMAINDER are left unchanged, return one.
2470 Otherwise set LHS to LHS / RHS with the fractional part discarded,
2471 set REMAINDER to the remainder, return zero. i.e.
2472
2473 OLD_LHS = RHS * LHS + REMAINDER
2474
2475 SCRATCH is a bignum of the same size as the operands and result for
2476 use by the routine; its contents need not be initialized and are
2477 destroyed. LHS, REMAINDER and SCRATCH must be distinct.
2478*/
Craig Topper55229b72017-04-02 19:17:22 +00002479int APInt::tcDivide(WordType *lhs, const WordType *rhs,
2480 WordType *remainder, WordType *srhs,
Craig Topper6a8518082017-03-28 05:32:55 +00002481 unsigned parts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002482 assert(lhs != remainder && lhs != srhs && remainder != srhs);
2483
Craig Topperb0038162017-03-28 05:32:52 +00002484 unsigned shiftCount = tcMSB(rhs, parts) + 1;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002485 if (shiftCount == 0)
Chris Lattner6b695682007-08-16 15:56:55 +00002486 return true;
2487
Craig Topper55229b72017-04-02 19:17:22 +00002488 shiftCount = parts * APINT_BITS_PER_WORD - shiftCount;
2489 unsigned n = shiftCount / APINT_BITS_PER_WORD;
2490 WordType mask = (WordType) 1 << (shiftCount % APINT_BITS_PER_WORD);
Chris Lattner6b695682007-08-16 15:56:55 +00002491
2492 tcAssign(srhs, rhs, parts);
2493 tcShiftLeft(srhs, parts, shiftCount);
2494 tcAssign(remainder, lhs, parts);
2495 tcSet(lhs, 0, parts);
2496
2497 /* Loop, subtracting SRHS if REMAINDER is greater and adding that to
2498 the total. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002499 for (;;) {
Chris Lattner6b695682007-08-16 15:56:55 +00002500 int compare;
2501
2502 compare = tcCompare(remainder, srhs, parts);
2503 if (compare >= 0) {
2504 tcSubtract(remainder, srhs, 0, parts);
2505 lhs[n] |= mask;
2506 }
2507
2508 if (shiftCount == 0)
2509 break;
2510 shiftCount--;
2511 tcShiftRight(srhs, parts, 1);
Richard Trieu7a083812016-02-18 22:09:30 +00002512 if ((mask >>= 1) == 0) {
Craig Topper55229b72017-04-02 19:17:22 +00002513 mask = (WordType) 1 << (APINT_BITS_PER_WORD - 1);
Richard Trieu7a083812016-02-18 22:09:30 +00002514 n--;
2515 }
Chris Lattner6b695682007-08-16 15:56:55 +00002516 }
2517
2518 return false;
2519}
2520
Craig Toppera8a4f0d2017-04-18 04:39:48 +00002521/// Shift a bignum left Cound bits in-place. Shifted in bits are zero. There are
2522/// no restrictions on Count.
2523void APInt::tcShiftLeft(WordType *Dst, unsigned Words, unsigned Count) {
2524 // Don't bother performing a no-op shift.
2525 if (!Count)
2526 return;
Chris Lattner6b695682007-08-16 15:56:55 +00002527
Craig Topperc6b05682017-04-24 17:00:22 +00002528 // WordShift is the inter-part shift; BitShift is the intra-part shift.
Craig Toppera8a4f0d2017-04-18 04:39:48 +00002529 unsigned WordShift = std::min(Count / APINT_BITS_PER_WORD, Words);
2530 unsigned BitShift = Count % APINT_BITS_PER_WORD;
Chris Lattner6b695682007-08-16 15:56:55 +00002531
Craig Toppera8a4f0d2017-04-18 04:39:48 +00002532 // Fastpath for moving by whole words.
2533 if (BitShift == 0) {
2534 std::memmove(Dst + WordShift, Dst, (Words - WordShift) * APINT_WORD_SIZE);
2535 } else {
2536 while (Words-- > WordShift) {
2537 Dst[Words] = Dst[Words - WordShift] << BitShift;
2538 if (Words > WordShift)
2539 Dst[Words] |=
2540 Dst[Words - WordShift - 1] >> (APINT_BITS_PER_WORD - BitShift);
Neil Boothb6182162007-10-08 13:47:12 +00002541 }
Neil Boothb6182162007-10-08 13:47:12 +00002542 }
Craig Toppera8a4f0d2017-04-18 04:39:48 +00002543
2544 // Fill in the remainder with 0s.
2545 std::memset(Dst, 0, WordShift * APINT_WORD_SIZE);
Chris Lattner6b695682007-08-16 15:56:55 +00002546}
2547
Craig Topper9575d8f2017-04-17 21:43:43 +00002548/// Shift a bignum right Count bits in-place. Shifted in bits are zero. There
2549/// are no restrictions on Count.
2550void APInt::tcShiftRight(WordType *Dst, unsigned Words, unsigned Count) {
2551 // Don't bother performing a no-op shift.
2552 if (!Count)
2553 return;
Chris Lattner6b695682007-08-16 15:56:55 +00002554
Craig Topperc6b05682017-04-24 17:00:22 +00002555 // WordShift is the inter-part shift; BitShift is the intra-part shift.
Craig Topper9575d8f2017-04-17 21:43:43 +00002556 unsigned WordShift = std::min(Count / APINT_BITS_PER_WORD, Words);
2557 unsigned BitShift = Count % APINT_BITS_PER_WORD;
Chris Lattner6b695682007-08-16 15:56:55 +00002558
Craig Topper9575d8f2017-04-17 21:43:43 +00002559 unsigned WordsToMove = Words - WordShift;
2560 // Fastpath for moving by whole words.
2561 if (BitShift == 0) {
2562 std::memmove(Dst, Dst + WordShift, WordsToMove * APINT_WORD_SIZE);
2563 } else {
2564 for (unsigned i = 0; i != WordsToMove; ++i) {
2565 Dst[i] = Dst[i + WordShift] >> BitShift;
2566 if (i + 1 != WordsToMove)
2567 Dst[i] |= Dst[i + WordShift + 1] << (APINT_BITS_PER_WORD - BitShift);
Neil Boothb6182162007-10-08 13:47:12 +00002568 }
Chris Lattner6b695682007-08-16 15:56:55 +00002569 }
Craig Topper9575d8f2017-04-17 21:43:43 +00002570
2571 // Fill in the remainder with 0s.
2572 std::memset(Dst + WordsToMove, 0, WordShift * APINT_WORD_SIZE);
Chris Lattner6b695682007-08-16 15:56:55 +00002573}
2574
2575/* Bitwise and of two bignums. */
Craig Topper55229b72017-04-02 19:17:22 +00002576void APInt::tcAnd(WordType *dst, const WordType *rhs, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002577 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002578 dst[i] &= rhs[i];
2579}
2580
2581/* Bitwise inclusive or of two bignums. */
Craig Topper55229b72017-04-02 19:17:22 +00002582void APInt::tcOr(WordType *dst, const WordType *rhs, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002583 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002584 dst[i] |= rhs[i];
2585}
2586
2587/* Bitwise exclusive or of two bignums. */
Craig Topper55229b72017-04-02 19:17:22 +00002588void APInt::tcXor(WordType *dst, const WordType *rhs, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002589 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002590 dst[i] ^= rhs[i];
2591}
2592
2593/* Complement a bignum in-place. */
Craig Topper55229b72017-04-02 19:17:22 +00002594void APInt::tcComplement(WordType *dst, unsigned parts) {
Craig Topperb0038162017-03-28 05:32:52 +00002595 for (unsigned i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002596 dst[i] = ~dst[i];
2597}
2598
2599/* Comparison (unsigned) of two bignums. */
Craig Topper55229b72017-04-02 19:17:22 +00002600int APInt::tcCompare(const WordType *lhs, const WordType *rhs,
Craig Topper6a8518082017-03-28 05:32:55 +00002601 unsigned parts) {
Chris Lattner6b695682007-08-16 15:56:55 +00002602 while (parts) {
Craig Topper99cfe4f2017-04-01 21:50:06 +00002603 parts--;
Craig Topper1dc8fc82017-04-21 16:13:15 +00002604 if (lhs[parts] != rhs[parts])
2605 return (lhs[parts] > rhs[parts]) ? 1 : -1;
Craig Topper99cfe4f2017-04-01 21:50:06 +00002606 }
Chris Lattner6b695682007-08-16 15:56:55 +00002607
2608 return 0;
2609}
2610
Chris Lattner6b695682007-08-16 15:56:55 +00002611/* Set the least significant BITS bits of a bignum, clear the
2612 rest. */
Craig Topper55229b72017-04-02 19:17:22 +00002613void APInt::tcSetLeastSignificantBits(WordType *dst, unsigned parts,
Craig Topper6a8518082017-03-28 05:32:55 +00002614 unsigned bits) {
Craig Topperb0038162017-03-28 05:32:52 +00002615 unsigned i = 0;
Craig Topper55229b72017-04-02 19:17:22 +00002616 while (bits > APINT_BITS_PER_WORD) {
2617 dst[i++] = ~(WordType) 0;
2618 bits -= APINT_BITS_PER_WORD;
Chris Lattner6b695682007-08-16 15:56:55 +00002619 }
2620
2621 if (bits)
Craig Topper55229b72017-04-02 19:17:22 +00002622 dst[i++] = ~(WordType) 0 >> (APINT_BITS_PER_WORD - bits);
Chris Lattner6b695682007-08-16 15:56:55 +00002623
2624 while (i < parts)
2625 dst[i++] = 0;
2626}