blob: 4a2a620eab4dd878c9983c28ad79c38b9afadf5d [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"
Ted Kremenek5c75d542008-01-19 04:23:33 +000016#include "llvm/ADT/FoldingSet.h"
Chandler Carruth71bd7d12012-03-04 12:02:57 +000017#include "llvm/ADT/Hashing.h"
Chris Lattner17f71652008-08-17 07:19:36 +000018#include "llvm/ADT/SmallString.h"
Chandler Carruth71bd7d12012-03-04 12:02:57 +000019#include "llvm/ADT/StringRef.h"
Reid Spencera5e0d202007-02-24 03:58:46 +000020#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000021#include "llvm/Support/ErrorHandling.h"
Zhou Shengdac63782007-02-06 03:00:16 +000022#include "llvm/Support/MathExtras.h"
Chris Lattner0c19df42008-08-23 22:23:09 +000023#include "llvm/Support/raw_ostream.h"
Chris Lattner17f71652008-08-17 07:19:36 +000024#include <cmath>
Zhou Shengdac63782007-02-06 03:00:16 +000025#include <cstdlib>
Chandler Carruthed0881b2012-12-03 16:50:05 +000026#include <cstring>
27#include <limits>
Zhou Shengdac63782007-02-06 03:00:16 +000028using namespace llvm;
29
Chandler Carruth64648262014-04-22 03:07:47 +000030#define DEBUG_TYPE "apint"
31
Reid Spencera41e93b2007-02-25 19:32:03 +000032/// A utility function for allocating memory, checking for allocation failures,
33/// and ensuring the contents are zeroed.
Chris Lattner77527f52009-01-21 18:09:24 +000034inline static uint64_t* getClearedMemory(unsigned numWords) {
Reid Spencera856b6e2007-02-18 18:38:44 +000035 uint64_t * result = new uint64_t[numWords];
36 assert(result && "APInt memory allocation fails!");
37 memset(result, 0, numWords * sizeof(uint64_t));
38 return result;
Zhou Sheng94b623a2007-02-06 06:04:53 +000039}
40
Eric Christopher820256b2009-08-21 04:06:45 +000041/// A utility function for allocating memory and checking for allocation
Reid Spencera41e93b2007-02-25 19:32:03 +000042/// failure. The content is not zeroed.
Chris Lattner77527f52009-01-21 18:09:24 +000043inline static uint64_t* getMemory(unsigned numWords) {
Reid Spencera856b6e2007-02-18 18:38:44 +000044 uint64_t * result = new uint64_t[numWords];
45 assert(result && "APInt memory allocation fails!");
46 return result;
47}
48
Erick Tryzelaardadb15712009-08-21 03:15:28 +000049/// A utility function that converts a character to a digit.
50inline static unsigned getDigit(char cdigit, uint8_t radix) {
Erick Tryzelaar60964092009-08-21 06:48:37 +000051 unsigned r;
52
Douglas Gregor663c0682011-09-14 15:54:46 +000053 if (radix == 16 || radix == 36) {
Erick Tryzelaar60964092009-08-21 06:48:37 +000054 r = cdigit - '0';
55 if (r <= 9)
56 return r;
57
58 r = cdigit - 'A';
Douglas Gregorc98ac852011-09-20 18:33:29 +000059 if (r <= radix - 11U)
Erick Tryzelaar60964092009-08-21 06:48:37 +000060 return r + 10;
61
62 r = cdigit - 'a';
Douglas Gregorc98ac852011-09-20 18:33:29 +000063 if (r <= radix - 11U)
Erick Tryzelaar60964092009-08-21 06:48:37 +000064 return r + 10;
Douglas Gregore4e20f42011-09-20 18:11:52 +000065
66 radix = 10;
Erick Tryzelaardadb15712009-08-21 03:15:28 +000067 }
68
Erick Tryzelaar60964092009-08-21 06:48:37 +000069 r = cdigit - '0';
70 if (r < radix)
71 return r;
72
73 return -1U;
Erick Tryzelaardadb15712009-08-21 03:15:28 +000074}
75
76
Chris Lattner77527f52009-01-21 18:09:24 +000077void APInt::initSlowCase(unsigned numBits, uint64_t val, bool isSigned) {
Chris Lattner1ac3e252008-08-20 17:02:31 +000078 pVal = getClearedMemory(getNumWords());
79 pVal[0] = val;
Eric Christopher820256b2009-08-21 04:06:45 +000080 if (isSigned && int64_t(val) < 0)
Chris Lattner1ac3e252008-08-20 17:02:31 +000081 for (unsigned i = 1; i < getNumWords(); ++i)
82 pVal[i] = -1ULL;
Zhou Shengdac63782007-02-06 03:00:16 +000083}
84
Chris Lattnerd57b7602008-10-11 22:07:19 +000085void APInt::initSlowCase(const APInt& that) {
86 pVal = getMemory(getNumWords());
87 memcpy(pVal, that.pVal, getNumWords() * APINT_WORD_SIZE);
88}
89
Jeffrey Yasskin7a162882011-07-18 21:45:40 +000090void APInt::initFromArray(ArrayRef<uint64_t> bigVal) {
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +000091 assert(BitWidth && "Bitwidth too small");
Jeffrey Yasskin7a162882011-07-18 21:45:40 +000092 assert(bigVal.data() && "Null pointer detected!");
Zhou Shengdac63782007-02-06 03:00:16 +000093 if (isSingleWord())
Reid Spencerdf6cf5a2007-02-24 10:01:42 +000094 VAL = bigVal[0];
Zhou Shengdac63782007-02-06 03:00:16 +000095 else {
Reid Spencerdf6cf5a2007-02-24 10:01:42 +000096 // Get memory, cleared to 0
97 pVal = getClearedMemory(getNumWords());
98 // Calculate the number of words to copy
Jeffrey Yasskin7a162882011-07-18 21:45:40 +000099 unsigned words = std::min<unsigned>(bigVal.size(), getNumWords());
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000100 // Copy the words from bigVal to pVal
Jeffrey Yasskin7a162882011-07-18 21:45:40 +0000101 memcpy(pVal, bigVal.data(), words * APINT_WORD_SIZE);
Zhou Shengdac63782007-02-06 03:00:16 +0000102 }
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000103 // Make sure unused high bits are cleared
104 clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000105}
106
Jeffrey Yasskin7a162882011-07-18 21:45:40 +0000107APInt::APInt(unsigned numBits, ArrayRef<uint64_t> bigVal)
108 : BitWidth(numBits), VAL(0) {
109 initFromArray(bigVal);
110}
111
112APInt::APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[])
113 : BitWidth(numBits), VAL(0) {
114 initFromArray(makeArrayRef(bigVal, numWords));
115}
116
Benjamin Kramer92d89982010-07-14 22:38:02 +0000117APInt::APInt(unsigned numbits, StringRef Str, uint8_t radix)
Reid Spencer1ba83352007-02-21 03:55:44 +0000118 : BitWidth(numbits), VAL(0) {
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000119 assert(BitWidth && "Bitwidth too small");
Daniel Dunbar3a1efd112009-08-13 02:33:34 +0000120 fromString(numbits, Str, radix);
Zhou Sheng3e8022d2007-02-07 06:14:53 +0000121}
122
Chris Lattner1ac3e252008-08-20 17:02:31 +0000123APInt& APInt::AssignSlowCase(const APInt& RHS) {
Reid Spencer7c16cd22007-02-26 23:38:21 +0000124 // Don't do anything for X = X
125 if (this == &RHS)
126 return *this;
127
Reid Spencer7c16cd22007-02-26 23:38:21 +0000128 if (BitWidth == RHS.getBitWidth()) {
Chris Lattner1ac3e252008-08-20 17:02:31 +0000129 // assume same bit-width single-word case is already handled
130 assert(!isSingleWord());
131 memcpy(pVal, RHS.pVal, getNumWords() * APINT_WORD_SIZE);
Reid Spencer7c16cd22007-02-26 23:38:21 +0000132 return *this;
133 }
134
Chris Lattner1ac3e252008-08-20 17:02:31 +0000135 if (isSingleWord()) {
136 // assume case where both are single words is already handled
137 assert(!RHS.isSingleWord());
138 VAL = 0;
139 pVal = getMemory(RHS.getNumWords());
140 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
Eric Christopher820256b2009-08-21 04:06:45 +0000141 } else if (getNumWords() == RHS.getNumWords())
Reid Spencer7c16cd22007-02-26 23:38:21 +0000142 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
143 else if (RHS.isSingleWord()) {
144 delete [] pVal;
Reid Spencera856b6e2007-02-18 18:38:44 +0000145 VAL = RHS.VAL;
Reid Spencer7c16cd22007-02-26 23:38:21 +0000146 } else {
147 delete [] pVal;
148 pVal = getMemory(RHS.getNumWords());
149 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
150 }
151 BitWidth = RHS.BitWidth;
152 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000153}
154
Zhou Shengdac63782007-02-06 03:00:16 +0000155APInt& APInt::operator=(uint64_t RHS) {
Eric Christopher820256b2009-08-21 04:06:45 +0000156 if (isSingleWord())
Reid Spencer1d072122007-02-16 22:36:51 +0000157 VAL = RHS;
Zhou Shengdac63782007-02-06 03:00:16 +0000158 else {
159 pVal[0] = RHS;
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000160 memset(pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
Zhou Shengdac63782007-02-06 03:00:16 +0000161 }
Reid Spencer7c16cd22007-02-26 23:38:21 +0000162 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000163}
164
Ted Kremenek5c75d542008-01-19 04:23:33 +0000165/// Profile - This method 'profiles' an APInt for use with FoldingSet.
166void APInt::Profile(FoldingSetNodeID& ID) const {
Ted Kremenek901540f2008-02-19 20:50:41 +0000167 ID.AddInteger(BitWidth);
Eric Christopher820256b2009-08-21 04:06:45 +0000168
Ted Kremenek5c75d542008-01-19 04:23:33 +0000169 if (isSingleWord()) {
170 ID.AddInteger(VAL);
171 return;
172 }
173
Chris Lattner77527f52009-01-21 18:09:24 +0000174 unsigned NumWords = getNumWords();
Ted Kremenek5c75d542008-01-19 04:23:33 +0000175 for (unsigned i = 0; i < NumWords; ++i)
176 ID.AddInteger(pVal[i]);
177}
178
Eric Christopher820256b2009-08-21 04:06:45 +0000179/// add_1 - This function adds a single "digit" integer, y, to the multiple
Reid Spencera856b6e2007-02-18 18:38:44 +0000180/// "digit" integer array, x[]. x[] is modified to reflect the addition and
181/// 1 is returned if there is a carry out, otherwise 0 is returned.
Reid Spencer100502d2007-02-17 03:16:00 +0000182/// @returns the carry of the addition.
Chris Lattner77527f52009-01-21 18:09:24 +0000183static bool add_1(uint64_t dest[], uint64_t x[], unsigned len, uint64_t y) {
184 for (unsigned i = 0; i < len; ++i) {
Reid Spenceree0a6852007-02-18 06:39:42 +0000185 dest[i] = y + x[i];
186 if (dest[i] < y)
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000187 y = 1; // Carry one to next digit.
Reid Spenceree0a6852007-02-18 06:39:42 +0000188 else {
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000189 y = 0; // No need to carry so exit early
Reid Spenceree0a6852007-02-18 06:39:42 +0000190 break;
191 }
Reid Spencer100502d2007-02-17 03:16:00 +0000192 }
Reid Spenceree0a6852007-02-18 06:39:42 +0000193 return y;
Reid Spencer100502d2007-02-17 03:16:00 +0000194}
195
Zhou Shengdac63782007-02-06 03:00:16 +0000196/// @brief Prefix increment operator. Increments the APInt by one.
197APInt& APInt::operator++() {
Eric Christopher820256b2009-08-21 04:06:45 +0000198 if (isSingleWord())
Reid Spencer1d072122007-02-16 22:36:51 +0000199 ++VAL;
Zhou Shengdac63782007-02-06 03:00:16 +0000200 else
Zhou Sheng3e8022d2007-02-07 06:14:53 +0000201 add_1(pVal, pVal, getNumWords(), 1);
Reid Spencera41e93b2007-02-25 19:32:03 +0000202 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000203}
204
Eric Christopher820256b2009-08-21 04:06:45 +0000205/// sub_1 - This function subtracts a single "digit" (64-bit word), y, from
206/// the multi-digit integer array, x[], propagating the borrowed 1 value until
Reid Spencera856b6e2007-02-18 18:38:44 +0000207/// no further borrowing is neeeded or it runs out of "digits" in x. The result
208/// is 1 if "borrowing" exhausted the digits in x, or 0 if x was not exhausted.
209/// In other words, if y > x then this function returns 1, otherwise 0.
Reid Spencera41e93b2007-02-25 19:32:03 +0000210/// @returns the borrow out of the subtraction
Chris Lattner77527f52009-01-21 18:09:24 +0000211static bool sub_1(uint64_t x[], unsigned len, uint64_t y) {
212 for (unsigned i = 0; i < len; ++i) {
Reid Spencer100502d2007-02-17 03:16:00 +0000213 uint64_t X = x[i];
Reid Spenceree0a6852007-02-18 06:39:42 +0000214 x[i] -= y;
Eric Christopher820256b2009-08-21 04:06:45 +0000215 if (y > X)
Reid Spencera856b6e2007-02-18 18:38:44 +0000216 y = 1; // We have to "borrow 1" from next "digit"
Reid Spencer100502d2007-02-17 03:16:00 +0000217 else {
Reid Spencera856b6e2007-02-18 18:38:44 +0000218 y = 0; // No need to borrow
219 break; // Remaining digits are unchanged so exit early
Reid Spencer100502d2007-02-17 03:16:00 +0000220 }
221 }
Reid Spencera41e93b2007-02-25 19:32:03 +0000222 return bool(y);
Reid Spencer100502d2007-02-17 03:16:00 +0000223}
224
Zhou Shengdac63782007-02-06 03:00:16 +0000225/// @brief Prefix decrement operator. Decrements the APInt by one.
226APInt& APInt::operator--() {
Eric Christopher820256b2009-08-21 04:06:45 +0000227 if (isSingleWord())
Reid Spencera856b6e2007-02-18 18:38:44 +0000228 --VAL;
Zhou Shengdac63782007-02-06 03:00:16 +0000229 else
Zhou Sheng3e8022d2007-02-07 06:14:53 +0000230 sub_1(pVal, getNumWords(), 1);
Reid Spencera41e93b2007-02-25 19:32:03 +0000231 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000232}
233
Reid Spencera41e93b2007-02-25 19:32:03 +0000234/// add - This function adds the integer array x to the integer array Y and
Eric Christopher820256b2009-08-21 04:06:45 +0000235/// places the result in dest.
Reid Spencera41e93b2007-02-25 19:32:03 +0000236/// @returns the carry out from the addition
237/// @brief General addition of 64-bit integer arrays
Eric Christopher820256b2009-08-21 04:06:45 +0000238static bool add(uint64_t *dest, const uint64_t *x, const uint64_t *y,
Chris Lattner77527f52009-01-21 18:09:24 +0000239 unsigned len) {
Reid Spencera5e0d202007-02-24 03:58:46 +0000240 bool carry = false;
Chris Lattner77527f52009-01-21 18:09:24 +0000241 for (unsigned i = 0; i< len; ++i) {
Reid Spencercb292e42007-02-23 01:57:13 +0000242 uint64_t limit = std::min(x[i],y[i]); // must come first in case dest == x
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000243 dest[i] = x[i] + y[i] + carry;
Reid Spencerdb2abec2007-02-21 05:44:56 +0000244 carry = dest[i] < limit || (carry && dest[i] == limit);
Reid Spencer100502d2007-02-17 03:16:00 +0000245 }
246 return carry;
247}
248
Reid Spencera41e93b2007-02-25 19:32:03 +0000249/// Adds the RHS APint to this APInt.
250/// @returns this, after addition of RHS.
Eric Christopher820256b2009-08-21 04:06:45 +0000251/// @brief Addition assignment operator.
Zhou Shengdac63782007-02-06 03:00:16 +0000252APInt& APInt::operator+=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000253 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Eric Christopher820256b2009-08-21 04:06:45 +0000254 if (isSingleWord())
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000255 VAL += RHS.VAL;
Zhou Shengdac63782007-02-06 03:00:16 +0000256 else {
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000257 add(pVal, pVal, RHS.pVal, getNumWords());
Zhou Shengdac63782007-02-06 03:00:16 +0000258 }
Reid Spencera41e93b2007-02-25 19:32:03 +0000259 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000260}
261
Eric Christopher820256b2009-08-21 04:06:45 +0000262/// Subtracts the integer array y from the integer array x
Reid Spencera41e93b2007-02-25 19:32:03 +0000263/// @returns returns the borrow out.
264/// @brief Generalized subtraction of 64-bit integer arrays.
Eric Christopher820256b2009-08-21 04:06:45 +0000265static bool sub(uint64_t *dest, const uint64_t *x, const uint64_t *y,
Chris Lattner77527f52009-01-21 18:09:24 +0000266 unsigned len) {
Reid Spencer1ba83352007-02-21 03:55:44 +0000267 bool borrow = false;
Chris Lattner77527f52009-01-21 18:09:24 +0000268 for (unsigned i = 0; i < len; ++i) {
Reid Spencer1ba83352007-02-21 03:55:44 +0000269 uint64_t x_tmp = borrow ? x[i] - 1 : x[i];
270 borrow = y[i] > x_tmp || (borrow && x[i] == 0);
271 dest[i] = x_tmp - y[i];
Reid Spencer100502d2007-02-17 03:16:00 +0000272 }
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000273 return borrow;
Reid Spencer100502d2007-02-17 03:16:00 +0000274}
275
Reid Spencera41e93b2007-02-25 19:32:03 +0000276/// Subtracts the RHS APInt from this APInt
277/// @returns this, after subtraction
Eric Christopher820256b2009-08-21 04:06:45 +0000278/// @brief Subtraction assignment operator.
Zhou Shengdac63782007-02-06 03:00:16 +0000279APInt& APInt::operator-=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000280 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Eric Christopher820256b2009-08-21 04:06:45 +0000281 if (isSingleWord())
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000282 VAL -= RHS.VAL;
283 else
284 sub(pVal, pVal, RHS.pVal, getNumWords());
Reid Spencera41e93b2007-02-25 19:32:03 +0000285 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000286}
287
Dan Gohman4a618822010-02-10 16:03:48 +0000288/// Multiplies an integer array, x, by a uint64_t integer and places the result
Eric Christopher820256b2009-08-21 04:06:45 +0000289/// into dest.
Reid Spencera41e93b2007-02-25 19:32:03 +0000290/// @returns the carry out of the multiplication.
291/// @brief Multiply a multi-digit APInt by a single digit (64-bit) integer.
Chris Lattner77527f52009-01-21 18:09:24 +0000292static uint64_t mul_1(uint64_t dest[], uint64_t x[], unsigned len, uint64_t y) {
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000293 // Split y into high 32-bit part (hy) and low 32-bit part (ly)
Reid Spencer100502d2007-02-17 03:16:00 +0000294 uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
Reid Spencera41e93b2007-02-25 19:32:03 +0000295 uint64_t carry = 0;
296
297 // For each digit of x.
Chris Lattner77527f52009-01-21 18:09:24 +0000298 for (unsigned i = 0; i < len; ++i) {
Reid Spencera41e93b2007-02-25 19:32:03 +0000299 // Split x into high and low words
300 uint64_t lx = x[i] & 0xffffffffULL;
301 uint64_t hx = x[i] >> 32;
302 // hasCarry - A flag to indicate if there is a carry to the next digit.
Reid Spencer100502d2007-02-17 03:16:00 +0000303 // hasCarry == 0, no carry
304 // hasCarry == 1, has carry
305 // hasCarry == 2, no carry and the calculation result == 0.
306 uint8_t hasCarry = 0;
307 dest[i] = carry + lx * ly;
308 // Determine if the add above introduces carry.
309 hasCarry = (dest[i] < carry) ? 1 : 0;
310 carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
Eric Christopher820256b2009-08-21 04:06:45 +0000311 // The upper limit of carry can be (2^32 - 1)(2^32 - 1) +
Reid Spencer100502d2007-02-17 03:16:00 +0000312 // (2^32 - 1) + 2^32 = 2^64.
313 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
314
315 carry += (lx * hy) & 0xffffffffULL;
316 dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
Eric Christopher820256b2009-08-21 04:06:45 +0000317 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) +
Reid Spencer100502d2007-02-17 03:16:00 +0000318 (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
319 }
Reid Spencer100502d2007-02-17 03:16:00 +0000320 return carry;
321}
322
Eric Christopher820256b2009-08-21 04:06:45 +0000323/// Multiplies integer array x by integer array y and stores the result into
Reid Spencera41e93b2007-02-25 19:32:03 +0000324/// the integer array dest. Note that dest's size must be >= xlen + ylen.
325/// @brief Generalized multiplicate of integer arrays.
Chris Lattner77527f52009-01-21 18:09:24 +0000326static void mul(uint64_t dest[], uint64_t x[], unsigned xlen, uint64_t y[],
327 unsigned ylen) {
Reid Spencer100502d2007-02-17 03:16:00 +0000328 dest[xlen] = mul_1(dest, x, xlen, y[0]);
Chris Lattner77527f52009-01-21 18:09:24 +0000329 for (unsigned i = 1; i < ylen; ++i) {
Reid Spencer100502d2007-02-17 03:16:00 +0000330 uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
Reid Spencer58a6a432007-02-21 08:21:52 +0000331 uint64_t carry = 0, lx = 0, hx = 0;
Chris Lattner77527f52009-01-21 18:09:24 +0000332 for (unsigned j = 0; j < xlen; ++j) {
Reid Spencer100502d2007-02-17 03:16:00 +0000333 lx = x[j] & 0xffffffffULL;
334 hx = x[j] >> 32;
335 // hasCarry - A flag to indicate if has carry.
336 // hasCarry == 0, no carry
337 // hasCarry == 1, has carry
338 // hasCarry == 2, no carry and the calculation result == 0.
339 uint8_t hasCarry = 0;
340 uint64_t resul = carry + lx * ly;
341 hasCarry = (resul < carry) ? 1 : 0;
342 carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
343 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
344
345 carry += (lx * hy) & 0xffffffffULL;
346 resul = (carry << 32) | (resul & 0xffffffffULL);
347 dest[i+j] += resul;
348 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
Eric Christopher820256b2009-08-21 04:06:45 +0000349 (carry >> 32) + (dest[i+j] < resul ? 1 : 0) +
Reid Spencer100502d2007-02-17 03:16:00 +0000350 ((lx * hy) >> 32) + hx * hy;
351 }
352 dest[i+xlen] = carry;
353 }
354}
355
Zhou Shengdac63782007-02-06 03:00:16 +0000356APInt& APInt::operator*=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000357 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer58a6a432007-02-21 08:21:52 +0000358 if (isSingleWord()) {
Reid Spencer4bb430c2007-02-20 20:42:10 +0000359 VAL *= RHS.VAL;
Reid Spencer58a6a432007-02-21 08:21:52 +0000360 clearUnusedBits();
361 return *this;
Zhou Shengdac63782007-02-06 03:00:16 +0000362 }
Reid Spencer58a6a432007-02-21 08:21:52 +0000363
364 // Get some bit facts about LHS and check for zero
Chris Lattner77527f52009-01-21 18:09:24 +0000365 unsigned lhsBits = getActiveBits();
366 unsigned lhsWords = !lhsBits ? 0 : whichWord(lhsBits - 1) + 1;
Eric Christopher820256b2009-08-21 04:06:45 +0000367 if (!lhsWords)
Reid Spencer58a6a432007-02-21 08:21:52 +0000368 // 0 * X ===> 0
369 return *this;
370
371 // Get some bit facts about RHS and check for zero
Chris Lattner77527f52009-01-21 18:09:24 +0000372 unsigned rhsBits = RHS.getActiveBits();
373 unsigned rhsWords = !rhsBits ? 0 : whichWord(rhsBits - 1) + 1;
Reid Spencer58a6a432007-02-21 08:21:52 +0000374 if (!rhsWords) {
375 // X * 0 ===> 0
Jay Foad25a5e4c2010-12-01 08:53:58 +0000376 clearAllBits();
Reid Spencer58a6a432007-02-21 08:21:52 +0000377 return *this;
378 }
379
380 // Allocate space for the result
Chris Lattner77527f52009-01-21 18:09:24 +0000381 unsigned destWords = rhsWords + lhsWords;
Reid Spencer58a6a432007-02-21 08:21:52 +0000382 uint64_t *dest = getMemory(destWords);
383
384 // Perform the long multiply
385 mul(dest, pVal, lhsWords, RHS.pVal, rhsWords);
386
387 // Copy result back into *this
Jay Foad25a5e4c2010-12-01 08:53:58 +0000388 clearAllBits();
Chris Lattner77527f52009-01-21 18:09:24 +0000389 unsigned wordsToCopy = destWords >= getNumWords() ? getNumWords() : destWords;
Reid Spencer58a6a432007-02-21 08:21:52 +0000390 memcpy(pVal, dest, wordsToCopy * APINT_WORD_SIZE);
Eli Friedman19546412011-10-07 23:40:49 +0000391 clearUnusedBits();
Reid Spencer58a6a432007-02-21 08:21:52 +0000392
393 // delete dest array and return
394 delete[] dest;
Zhou Shengdac63782007-02-06 03:00:16 +0000395 return *this;
396}
397
Zhou Shengdac63782007-02-06 03:00:16 +0000398APInt& APInt::operator&=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000399 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengdac63782007-02-06 03:00:16 +0000400 if (isSingleWord()) {
Reid Spencera856b6e2007-02-18 18:38:44 +0000401 VAL &= RHS.VAL;
402 return *this;
Zhou Shengdac63782007-02-06 03:00:16 +0000403 }
Chris Lattner77527f52009-01-21 18:09:24 +0000404 unsigned numWords = getNumWords();
405 for (unsigned i = 0; i < numWords; ++i)
Reid Spencera856b6e2007-02-18 18:38:44 +0000406 pVal[i] &= RHS.pVal[i];
Zhou Shengdac63782007-02-06 03:00:16 +0000407 return *this;
408}
409
Zhou Shengdac63782007-02-06 03:00:16 +0000410APInt& APInt::operator|=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000411 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengdac63782007-02-06 03:00:16 +0000412 if (isSingleWord()) {
Reid Spencera856b6e2007-02-18 18:38:44 +0000413 VAL |= RHS.VAL;
414 return *this;
Zhou Shengdac63782007-02-06 03:00:16 +0000415 }
Chris Lattner77527f52009-01-21 18:09:24 +0000416 unsigned numWords = getNumWords();
417 for (unsigned i = 0; i < numWords; ++i)
Reid Spencera856b6e2007-02-18 18:38:44 +0000418 pVal[i] |= RHS.pVal[i];
Zhou Shengdac63782007-02-06 03:00:16 +0000419 return *this;
420}
421
Zhou Shengdac63782007-02-06 03:00:16 +0000422APInt& APInt::operator^=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000423 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengdac63782007-02-06 03:00:16 +0000424 if (isSingleWord()) {
Reid Spenceree0a6852007-02-18 06:39:42 +0000425 VAL ^= RHS.VAL;
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000426 this->clearUnusedBits();
Reid Spenceree0a6852007-02-18 06:39:42 +0000427 return *this;
Eric Christopher820256b2009-08-21 04:06:45 +0000428 }
Chris Lattner77527f52009-01-21 18:09:24 +0000429 unsigned numWords = getNumWords();
430 for (unsigned i = 0; i < numWords; ++i)
Reid Spencera856b6e2007-02-18 18:38:44 +0000431 pVal[i] ^= RHS.pVal[i];
Reid Spencera41e93b2007-02-25 19:32:03 +0000432 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000433}
434
Chris Lattner1ac3e252008-08-20 17:02:31 +0000435APInt APInt::AndSlowCase(const APInt& RHS) const {
Chris Lattner77527f52009-01-21 18:09:24 +0000436 unsigned numWords = getNumWords();
Reid Spencera41e93b2007-02-25 19:32:03 +0000437 uint64_t* val = getMemory(numWords);
Chris Lattner77527f52009-01-21 18:09:24 +0000438 for (unsigned i = 0; i < numWords; ++i)
Reid Spencera41e93b2007-02-25 19:32:03 +0000439 val[i] = pVal[i] & RHS.pVal[i];
440 return APInt(val, getBitWidth());
Zhou Shengdac63782007-02-06 03:00:16 +0000441}
442
Chris Lattner1ac3e252008-08-20 17:02:31 +0000443APInt APInt::OrSlowCase(const APInt& RHS) const {
Chris Lattner77527f52009-01-21 18:09:24 +0000444 unsigned numWords = getNumWords();
Reid Spencera41e93b2007-02-25 19:32:03 +0000445 uint64_t *val = getMemory(numWords);
Chris Lattner77527f52009-01-21 18:09:24 +0000446 for (unsigned i = 0; i < numWords; ++i)
Reid Spencera41e93b2007-02-25 19:32:03 +0000447 val[i] = pVal[i] | RHS.pVal[i];
448 return APInt(val, getBitWidth());
Zhou Shengdac63782007-02-06 03:00:16 +0000449}
450
Chris Lattner1ac3e252008-08-20 17:02:31 +0000451APInt APInt::XorSlowCase(const APInt& RHS) const {
Chris Lattner77527f52009-01-21 18:09:24 +0000452 unsigned numWords = getNumWords();
Reid Spencera41e93b2007-02-25 19:32:03 +0000453 uint64_t *val = getMemory(numWords);
Chris Lattner77527f52009-01-21 18:09:24 +0000454 for (unsigned i = 0; i < numWords; ++i)
Reid Spencera41e93b2007-02-25 19:32:03 +0000455 val[i] = pVal[i] ^ RHS.pVal[i];
456
Benjamin Kramerf9a29752014-10-10 10:18:12 +0000457 APInt Result(val, getBitWidth());
Reid Spencera41e93b2007-02-25 19:32:03 +0000458 // 0^0==1 so clear the high bits in case they got set.
Benjamin Kramerf9a29752014-10-10 10:18:12 +0000459 Result.clearUnusedBits();
460 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000461}
462
Zhou Shengdac63782007-02-06 03:00:16 +0000463APInt APInt::operator*(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +0000464 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencera41e93b2007-02-25 19:32:03 +0000465 if (isSingleWord())
Reid Spenceraa8dcfe2007-02-26 07:44:38 +0000466 return APInt(BitWidth, VAL * RHS.VAL);
Reid Spencer4bb430c2007-02-20 20:42:10 +0000467 APInt Result(*this);
468 Result *= RHS;
Eli Friedman19546412011-10-07 23:40:49 +0000469 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000470}
471
Zhou Shengdac63782007-02-06 03:00:16 +0000472APInt APInt::operator+(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +0000473 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencera41e93b2007-02-25 19:32:03 +0000474 if (isSingleWord())
Reid Spenceraa8dcfe2007-02-26 07:44:38 +0000475 return APInt(BitWidth, VAL + RHS.VAL);
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000476 APInt Result(BitWidth, 0);
477 add(Result.pVal, this->pVal, RHS.pVal, getNumWords());
Benjamin Kramerf9a29752014-10-10 10:18:12 +0000478 Result.clearUnusedBits();
479 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000480}
481
Zhou Shengdac63782007-02-06 03:00:16 +0000482APInt APInt::operator-(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +0000483 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencera41e93b2007-02-25 19:32:03 +0000484 if (isSingleWord())
Reid Spenceraa8dcfe2007-02-26 07:44:38 +0000485 return APInt(BitWidth, VAL - RHS.VAL);
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000486 APInt Result(BitWidth, 0);
487 sub(Result.pVal, this->pVal, RHS.pVal, getNumWords());
Benjamin Kramerf9a29752014-10-10 10:18:12 +0000488 Result.clearUnusedBits();
489 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000490}
491
Chris Lattner1ac3e252008-08-20 17:02:31 +0000492bool APInt::EqualSlowCase(const APInt& RHS) const {
Reid Spencera41e93b2007-02-25 19:32:03 +0000493 // Get some facts about the number of bits used in the two operands.
Chris Lattner77527f52009-01-21 18:09:24 +0000494 unsigned n1 = getActiveBits();
495 unsigned n2 = RHS.getActiveBits();
Reid Spencera41e93b2007-02-25 19:32:03 +0000496
497 // If the number of bits isn't the same, they aren't equal
Eric Christopher820256b2009-08-21 04:06:45 +0000498 if (n1 != n2)
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000499 return false;
500
Reid Spencera41e93b2007-02-25 19:32:03 +0000501 // If the number of bits fits in a word, we only need to compare the low word.
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000502 if (n1 <= APINT_BITS_PER_WORD)
503 return pVal[0] == RHS.pVal[0];
504
Reid Spencera41e93b2007-02-25 19:32:03 +0000505 // Otherwise, compare everything
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000506 for (int i = whichWord(n1 - 1); i >= 0; --i)
Eric Christopher820256b2009-08-21 04:06:45 +0000507 if (pVal[i] != RHS.pVal[i])
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000508 return false;
Zhou Shengdac63782007-02-06 03:00:16 +0000509 return true;
510}
511
Chris Lattner1ac3e252008-08-20 17:02:31 +0000512bool APInt::EqualSlowCase(uint64_t Val) const {
Chris Lattner77527f52009-01-21 18:09:24 +0000513 unsigned n = getActiveBits();
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000514 if (n <= APINT_BITS_PER_WORD)
515 return pVal[0] == Val;
516 else
517 return false;
Zhou Shengdac63782007-02-06 03:00:16 +0000518}
519
Reid Spencer1d072122007-02-16 22:36:51 +0000520bool APInt::ult(const APInt& RHS) const {
521 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
522 if (isSingleWord())
523 return VAL < RHS.VAL;
Reid Spencera41e93b2007-02-25 19:32:03 +0000524
525 // Get active bit length of both operands
Chris Lattner77527f52009-01-21 18:09:24 +0000526 unsigned n1 = getActiveBits();
527 unsigned n2 = RHS.getActiveBits();
Reid Spencera41e93b2007-02-25 19:32:03 +0000528
529 // If magnitude of LHS is less than RHS, return true.
530 if (n1 < n2)
531 return true;
532
533 // If magnitude of RHS is greather than LHS, return false.
534 if (n2 < n1)
535 return false;
536
537 // If they bot fit in a word, just compare the low order word
538 if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
539 return pVal[0] < RHS.pVal[0];
540
541 // Otherwise, compare all words
Chris Lattner77527f52009-01-21 18:09:24 +0000542 unsigned topWord = whichWord(std::max(n1,n2)-1);
Reid Spencer54abdcf2007-02-27 18:23:40 +0000543 for (int i = topWord; i >= 0; --i) {
Eric Christopher820256b2009-08-21 04:06:45 +0000544 if (pVal[i] > RHS.pVal[i])
Reid Spencer1d072122007-02-16 22:36:51 +0000545 return false;
Eric Christopher820256b2009-08-21 04:06:45 +0000546 if (pVal[i] < RHS.pVal[i])
Reid Spencera41e93b2007-02-25 19:32:03 +0000547 return true;
Zhou Shengdac63782007-02-06 03:00:16 +0000548 }
549 return false;
550}
551
Reid Spencer1d072122007-02-16 22:36:51 +0000552bool APInt::slt(const APInt& RHS) const {
553 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000554 if (isSingleWord()) {
555 int64_t lhsSext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
556 int64_t rhsSext = (int64_t(RHS.VAL) << (64-BitWidth)) >> (64-BitWidth);
557 return lhsSext < rhsSext;
Reid Spencer1d072122007-02-16 22:36:51 +0000558 }
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000559
560 APInt lhs(*this);
Reid Spencer54abdcf2007-02-27 18:23:40 +0000561 APInt rhs(RHS);
562 bool lhsNeg = isNegative();
563 bool rhsNeg = rhs.isNegative();
564 if (lhsNeg) {
565 // Sign bit is set so perform two's complement to make it positive
Jay Foad25a5e4c2010-12-01 08:53:58 +0000566 lhs.flipAllBits();
Jakub Staszak773be0c2013-03-20 23:56:19 +0000567 ++lhs;
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000568 }
Reid Spencer54abdcf2007-02-27 18:23:40 +0000569 if (rhsNeg) {
570 // Sign bit is set so perform two's complement to make it positive
Jay Foad25a5e4c2010-12-01 08:53:58 +0000571 rhs.flipAllBits();
Jakub Staszak773be0c2013-03-20 23:56:19 +0000572 ++rhs;
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000573 }
Reid Spencera41e93b2007-02-25 19:32:03 +0000574
575 // Now we have unsigned values to compare so do the comparison if necessary
576 // based on the negativeness of the values.
Reid Spencer54abdcf2007-02-27 18:23:40 +0000577 if (lhsNeg)
578 if (rhsNeg)
579 return lhs.ugt(rhs);
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000580 else
581 return true;
Reid Spencer54abdcf2007-02-27 18:23:40 +0000582 else if (rhsNeg)
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000583 return false;
Eric Christopher820256b2009-08-21 04:06:45 +0000584 else
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000585 return lhs.ult(rhs);
Zhou Shengdac63782007-02-06 03:00:16 +0000586}
587
Jay Foad25a5e4c2010-12-01 08:53:58 +0000588void APInt::setBit(unsigned bitPosition) {
Eric Christopher820256b2009-08-21 04:06:45 +0000589 if (isSingleWord())
Reid Spencera41e93b2007-02-25 19:32:03 +0000590 VAL |= maskBit(bitPosition);
Eric Christopher820256b2009-08-21 04:06:45 +0000591 else
Reid Spencera41e93b2007-02-25 19:32:03 +0000592 pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
Zhou Shengdac63782007-02-06 03:00:16 +0000593}
594
Zhou Shengdac63782007-02-06 03:00:16 +0000595/// Set the given bit to 0 whose position is given as "bitPosition".
596/// @brief Set a given bit to 0.
Jay Foad25a5e4c2010-12-01 08:53:58 +0000597void APInt::clearBit(unsigned bitPosition) {
Eric Christopher820256b2009-08-21 04:06:45 +0000598 if (isSingleWord())
Reid Spencera856b6e2007-02-18 18:38:44 +0000599 VAL &= ~maskBit(bitPosition);
Eric Christopher820256b2009-08-21 04:06:45 +0000600 else
Reid Spencera856b6e2007-02-18 18:38:44 +0000601 pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
Zhou Shengdac63782007-02-06 03:00:16 +0000602}
603
Zhou Shengdac63782007-02-06 03:00:16 +0000604/// @brief Toggle every bit to its opposite value.
Zhou Shengdac63782007-02-06 03:00:16 +0000605
Eric Christopher820256b2009-08-21 04:06:45 +0000606/// Toggle a given bit to its opposite value whose position is given
Zhou Shengdac63782007-02-06 03:00:16 +0000607/// as "bitPosition".
608/// @brief Toggles a given bit to its opposite value.
Jay Foad25a5e4c2010-12-01 08:53:58 +0000609void APInt::flipBit(unsigned bitPosition) {
Reid Spencer1d072122007-02-16 22:36:51 +0000610 assert(bitPosition < BitWidth && "Out of the bit-width range!");
Jay Foad25a5e4c2010-12-01 08:53:58 +0000611 if ((*this)[bitPosition]) clearBit(bitPosition);
612 else setBit(bitPosition);
Zhou Shengdac63782007-02-06 03:00:16 +0000613}
614
Benjamin Kramer92d89982010-07-14 22:38:02 +0000615unsigned APInt::getBitsNeeded(StringRef str, uint8_t radix) {
Daniel Dunbar3a1efd112009-08-13 02:33:34 +0000616 assert(!str.empty() && "Invalid string length");
Douglas Gregor663c0682011-09-14 15:54:46 +0000617 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 ||
618 radix == 36) &&
619 "Radix should be 2, 8, 10, 16, or 36!");
Daniel Dunbar3a1efd112009-08-13 02:33:34 +0000620
621 size_t slen = str.size();
Reid Spencer9329e7b2007-04-13 19:19:07 +0000622
Eric Christopher43a1dec2009-08-21 04:10:31 +0000623 // Each computation below needs to know if it's negative.
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000624 StringRef::iterator p = str.begin();
Eric Christopher43a1dec2009-08-21 04:10:31 +0000625 unsigned isNegative = *p == '-';
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000626 if (*p == '-' || *p == '+') {
627 p++;
Reid Spencer9329e7b2007-04-13 19:19:07 +0000628 slen--;
Eric Christopher43a1dec2009-08-21 04:10:31 +0000629 assert(slen && "String is only a sign, needs a value.");
Reid Spencer9329e7b2007-04-13 19:19:07 +0000630 }
Eric Christopher43a1dec2009-08-21 04:10:31 +0000631
Reid Spencer9329e7b2007-04-13 19:19:07 +0000632 // For radixes of power-of-two values, the bits required is accurately and
633 // easily computed
634 if (radix == 2)
635 return slen + isNegative;
636 if (radix == 8)
637 return slen * 3 + isNegative;
638 if (radix == 16)
639 return slen * 4 + isNegative;
640
Douglas Gregor663c0682011-09-14 15:54:46 +0000641 // FIXME: base 36
642
Reid Spencer9329e7b2007-04-13 19:19:07 +0000643 // This is grossly inefficient but accurate. We could probably do something
644 // with a computation of roughly slen*64/20 and then adjust by the value of
645 // the first few digits. But, I'm not sure how accurate that could be.
646
647 // Compute a sufficient number of bits that is always large enough but might
Erick Tryzelaardadb15712009-08-21 03:15:28 +0000648 // be too large. This avoids the assertion in the constructor. This
649 // calculation doesn't work appropriately for the numbers 0-9, so just use 4
650 // bits in that case.
Douglas Gregor663c0682011-09-14 15:54:46 +0000651 unsigned sufficient
652 = radix == 10? (slen == 1 ? 4 : slen * 64/18)
653 : (slen == 1 ? 7 : slen * 16/3);
Reid Spencer9329e7b2007-04-13 19:19:07 +0000654
655 // Convert to the actual binary value.
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000656 APInt tmp(sufficient, StringRef(p, slen), radix);
Reid Spencer9329e7b2007-04-13 19:19:07 +0000657
Erick Tryzelaardadb15712009-08-21 03:15:28 +0000658 // Compute how many bits are required. If the log is infinite, assume we need
659 // just bit.
660 unsigned log = tmp.logBase2();
661 if (log == (unsigned)-1) {
662 return isNegative + 1;
663 } else {
664 return isNegative + log + 1;
665 }
Reid Spencer9329e7b2007-04-13 19:19:07 +0000666}
667
Chandler Carruth71bd7d12012-03-04 12:02:57 +0000668hash_code llvm::hash_value(const APInt &Arg) {
669 if (Arg.isSingleWord())
670 return hash_combine(Arg.VAL);
Reid Spencerb2bc9852007-02-26 21:02:27 +0000671
Chandler Carruth71bd7d12012-03-04 12:02:57 +0000672 return hash_combine_range(Arg.pVal, Arg.pVal + Arg.getNumWords());
Reid Spencerb2bc9852007-02-26 21:02:27 +0000673}
674
Zhou Shengdac63782007-02-06 03:00:16 +0000675/// HiBits - This function returns the high "numBits" bits of this APInt.
Chris Lattner77527f52009-01-21 18:09:24 +0000676APInt APInt::getHiBits(unsigned numBits) const {
Reid Spencer1d072122007-02-16 22:36:51 +0000677 return APIntOps::lshr(*this, BitWidth - numBits);
Zhou Shengdac63782007-02-06 03:00:16 +0000678}
679
680/// LoBits - This function returns the low "numBits" bits of this APInt.
Chris Lattner77527f52009-01-21 18:09:24 +0000681APInt APInt::getLoBits(unsigned numBits) const {
Eric Christopher820256b2009-08-21 04:06:45 +0000682 return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits),
Reid Spencer1d072122007-02-16 22:36:51 +0000683 BitWidth - numBits);
Zhou Shengdac63782007-02-06 03:00:16 +0000684}
685
Chris Lattner77527f52009-01-21 18:09:24 +0000686unsigned APInt::countLeadingZerosSlowCase() const {
John McCalldf951bd2010-02-03 03:42:44 +0000687 // Treat the most significand word differently because it might have
688 // meaningless bits set beyond the precision.
689 unsigned BitsInMSW = BitWidth % APINT_BITS_PER_WORD;
690 integerPart MSWMask;
691 if (BitsInMSW) MSWMask = (integerPart(1) << BitsInMSW) - 1;
692 else {
693 MSWMask = ~integerPart(0);
694 BitsInMSW = APINT_BITS_PER_WORD;
695 }
696
697 unsigned i = getNumWords();
698 integerPart MSW = pVal[i-1] & MSWMask;
699 if (MSW)
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000700 return llvm::countLeadingZeros(MSW) - (APINT_BITS_PER_WORD - BitsInMSW);
John McCalldf951bd2010-02-03 03:42:44 +0000701
702 unsigned Count = BitsInMSW;
703 for (--i; i > 0u; --i) {
Chris Lattner1ac3e252008-08-20 17:02:31 +0000704 if (pVal[i-1] == 0)
705 Count += APINT_BITS_PER_WORD;
706 else {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000707 Count += llvm::countLeadingZeros(pVal[i-1]);
Chris Lattner1ac3e252008-08-20 17:02:31 +0000708 break;
Reid Spencer74cf82e2007-02-21 00:29:48 +0000709 }
Zhou Shengdac63782007-02-06 03:00:16 +0000710 }
John McCalldf951bd2010-02-03 03:42:44 +0000711 return Count;
Zhou Shengdac63782007-02-06 03:00:16 +0000712}
713
Chris Lattner77527f52009-01-21 18:09:24 +0000714unsigned APInt::countLeadingOnes() const {
Reid Spencer31acef52007-02-27 21:59:26 +0000715 if (isSingleWord())
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000716 return llvm::countLeadingOnes(VAL << (APINT_BITS_PER_WORD - BitWidth));
Reid Spencer31acef52007-02-27 21:59:26 +0000717
Chris Lattner77527f52009-01-21 18:09:24 +0000718 unsigned highWordBits = BitWidth % APINT_BITS_PER_WORD;
Torok Edwinec39eb82009-01-27 18:06:03 +0000719 unsigned shift;
720 if (!highWordBits) {
721 highWordBits = APINT_BITS_PER_WORD;
722 shift = 0;
723 } else {
724 shift = APINT_BITS_PER_WORD - highWordBits;
725 }
Reid Spencer31acef52007-02-27 21:59:26 +0000726 int i = getNumWords() - 1;
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000727 unsigned Count = llvm::countLeadingOnes(pVal[i] << shift);
Reid Spencer31acef52007-02-27 21:59:26 +0000728 if (Count == highWordBits) {
729 for (i--; i >= 0; --i) {
730 if (pVal[i] == -1ULL)
731 Count += APINT_BITS_PER_WORD;
732 else {
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000733 Count += llvm::countLeadingOnes(pVal[i]);
Reid Spencer31acef52007-02-27 21:59:26 +0000734 break;
735 }
736 }
737 }
738 return Count;
739}
740
Chris Lattner77527f52009-01-21 18:09:24 +0000741unsigned APInt::countTrailingZeros() const {
Zhou Shengdac63782007-02-06 03:00:16 +0000742 if (isSingleWord())
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000743 return std::min(unsigned(llvm::countTrailingZeros(VAL)), BitWidth);
Chris Lattner77527f52009-01-21 18:09:24 +0000744 unsigned Count = 0;
745 unsigned i = 0;
Reid Spenceraa8dcfe2007-02-26 07:44:38 +0000746 for (; i < getNumWords() && pVal[i] == 0; ++i)
747 Count += APINT_BITS_PER_WORD;
748 if (i < getNumWords())
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000749 Count += llvm::countTrailingZeros(pVal[i]);
Chris Lattnerc2c4c742007-11-23 22:36:25 +0000750 return std::min(Count, BitWidth);
Zhou Shengdac63782007-02-06 03:00:16 +0000751}
752
Chris Lattner77527f52009-01-21 18:09:24 +0000753unsigned APInt::countTrailingOnesSlowCase() const {
754 unsigned Count = 0;
755 unsigned i = 0;
Dan Gohmanc354ebd2008-02-14 22:38:45 +0000756 for (; i < getNumWords() && pVal[i] == -1ULL; ++i)
Dan Gohman8b4fa9d2008-02-13 21:11:05 +0000757 Count += APINT_BITS_PER_WORD;
758 if (i < getNumWords())
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000759 Count += llvm::countTrailingOnes(pVal[i]);
Dan Gohman8b4fa9d2008-02-13 21:11:05 +0000760 return std::min(Count, BitWidth);
761}
762
Chris Lattner77527f52009-01-21 18:09:24 +0000763unsigned APInt::countPopulationSlowCase() const {
764 unsigned Count = 0;
765 for (unsigned i = 0; i < getNumWords(); ++i)
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000766 Count += llvm::countPopulation(pVal[i]);
Zhou Shengdac63782007-02-06 03:00:16 +0000767 return Count;
768}
769
Richard Smith4f9a8082011-11-23 21:33:37 +0000770/// Perform a logical right-shift from Src to Dst, which must be equal or
771/// non-overlapping, of Words words, by Shift, which must be less than 64.
772static void lshrNear(uint64_t *Dst, uint64_t *Src, unsigned Words,
773 unsigned Shift) {
774 uint64_t Carry = 0;
775 for (int I = Words - 1; I >= 0; --I) {
776 uint64_t Tmp = Src[I];
777 Dst[I] = (Tmp >> Shift) | Carry;
778 Carry = Tmp << (64 - Shift);
779 }
780}
781
Reid Spencer1d072122007-02-16 22:36:51 +0000782APInt APInt::byteSwap() const {
783 assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
784 if (BitWidth == 16)
Jeff Cohene06855e2007-03-20 20:42:36 +0000785 return APInt(BitWidth, ByteSwap_16(uint16_t(VAL)));
Richard Smith4f9a8082011-11-23 21:33:37 +0000786 if (BitWidth == 32)
Chris Lattner77527f52009-01-21 18:09:24 +0000787 return APInt(BitWidth, ByteSwap_32(unsigned(VAL)));
Richard Smith4f9a8082011-11-23 21:33:37 +0000788 if (BitWidth == 48) {
Chris Lattner77527f52009-01-21 18:09:24 +0000789 unsigned Tmp1 = unsigned(VAL >> 16);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000790 Tmp1 = ByteSwap_32(Tmp1);
Jeff Cohene06855e2007-03-20 20:42:36 +0000791 uint16_t Tmp2 = uint16_t(VAL);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000792 Tmp2 = ByteSwap_16(Tmp2);
Jeff Cohene06855e2007-03-20 20:42:36 +0000793 return APInt(BitWidth, (uint64_t(Tmp2) << 32) | Tmp1);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000794 }
Richard Smith4f9a8082011-11-23 21:33:37 +0000795 if (BitWidth == 64)
796 return APInt(BitWidth, ByteSwap_64(VAL));
797
798 APInt Result(getNumWords() * APINT_BITS_PER_WORD, 0);
799 for (unsigned I = 0, N = getNumWords(); I != N; ++I)
800 Result.pVal[I] = ByteSwap_64(pVal[N - I - 1]);
801 if (Result.BitWidth != BitWidth) {
802 lshrNear(Result.pVal, Result.pVal, getNumWords(),
803 Result.BitWidth - BitWidth);
804 Result.BitWidth = BitWidth;
805 }
806 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000807}
808
Eric Christopher820256b2009-08-21 04:06:45 +0000809APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1,
Zhou Shengfbf61ea2007-02-08 14:35:19 +0000810 const APInt& API2) {
Zhou Shengdac63782007-02-06 03:00:16 +0000811 APInt A = API1, B = API2;
812 while (!!B) {
813 APInt T = B;
Reid Spencer1d072122007-02-16 22:36:51 +0000814 B = APIntOps::urem(A, B);
Zhou Shengdac63782007-02-06 03:00:16 +0000815 A = T;
816 }
817 return A;
818}
Chris Lattner28cbd1d2007-02-06 05:38:37 +0000819
Chris Lattner77527f52009-01-21 18:09:24 +0000820APInt llvm::APIntOps::RoundDoubleToAPInt(double Double, unsigned width) {
Zhou Shengd707d632007-02-12 20:02:55 +0000821 union {
822 double D;
823 uint64_t I;
824 } T;
825 T.D = Double;
Reid Spencer974551a2007-02-27 01:28:10 +0000826
827 // Get the sign bit from the highest order bit
Zhou Shengd707d632007-02-12 20:02:55 +0000828 bool isNeg = T.I >> 63;
Reid Spencer974551a2007-02-27 01:28:10 +0000829
830 // Get the 11-bit exponent and adjust for the 1023 bit bias
Zhou Shengd707d632007-02-12 20:02:55 +0000831 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
Reid Spencer974551a2007-02-27 01:28:10 +0000832
833 // If the exponent is negative, the value is < 0 so just return 0.
Zhou Shengd707d632007-02-12 20:02:55 +0000834 if (exp < 0)
Reid Spencer66d0d572007-02-28 01:30:08 +0000835 return APInt(width, 0u);
Reid Spencer974551a2007-02-27 01:28:10 +0000836
837 // Extract the mantissa by clearing the top 12 bits (sign + exponent).
838 uint64_t mantissa = (T.I & (~0ULL >> 12)) | 1ULL << 52;
839
840 // If the exponent doesn't shift all bits out of the mantissa
Zhou Shengd707d632007-02-12 20:02:55 +0000841 if (exp < 52)
Eric Christopher820256b2009-08-21 04:06:45 +0000842 return isNeg ? -APInt(width, mantissa >> (52 - exp)) :
Reid Spencer54abdcf2007-02-27 18:23:40 +0000843 APInt(width, mantissa >> (52 - exp));
844
845 // If the client didn't provide enough bits for us to shift the mantissa into
846 // then the result is undefined, just return 0
847 if (width <= exp - 52)
848 return APInt(width, 0);
Reid Spencer974551a2007-02-27 01:28:10 +0000849
850 // Otherwise, we have to shift the mantissa bits up to the right location
Reid Spencer54abdcf2007-02-27 18:23:40 +0000851 APInt Tmp(width, mantissa);
Chris Lattner77527f52009-01-21 18:09:24 +0000852 Tmp = Tmp.shl((unsigned)exp - 52);
Zhou Shengd707d632007-02-12 20:02:55 +0000853 return isNeg ? -Tmp : Tmp;
854}
855
Dale Johannesen54be7852009-08-12 18:04:11 +0000856/// RoundToDouble - This function converts this APInt to a double.
Zhou Shengd707d632007-02-12 20:02:55 +0000857/// The layout for double is as following (IEEE Standard 754):
858/// --------------------------------------
859/// | Sign Exponent Fraction Bias |
860/// |-------------------------------------- |
861/// | 1[63] 11[62-52] 52[51-00] 1023 |
Eric Christopher820256b2009-08-21 04:06:45 +0000862/// --------------------------------------
Reid Spencer1d072122007-02-16 22:36:51 +0000863double APInt::roundToDouble(bool isSigned) const {
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000864
865 // Handle the simple case where the value is contained in one uint64_t.
Dale Johannesen54be7852009-08-12 18:04:11 +0000866 // It is wrong to optimize getWord(0) to VAL; there might be more than one word.
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000867 if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
868 if (isSigned) {
Dale Johannesen34c08bb2009-08-12 17:42:34 +0000869 int64_t sext = (int64_t(getWord(0)) << (64-BitWidth)) >> (64-BitWidth);
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000870 return double(sext);
871 } else
Dale Johannesen34c08bb2009-08-12 17:42:34 +0000872 return double(getWord(0));
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000873 }
874
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000875 // Determine if the value is negative.
Reid Spencer1d072122007-02-16 22:36:51 +0000876 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000877
878 // Construct the absolute value if we're negative.
Zhou Shengd707d632007-02-12 20:02:55 +0000879 APInt Tmp(isNeg ? -(*this) : (*this));
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000880
881 // Figure out how many bits we're using.
Chris Lattner77527f52009-01-21 18:09:24 +0000882 unsigned n = Tmp.getActiveBits();
Zhou Shengd707d632007-02-12 20:02:55 +0000883
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000884 // The exponent (without bias normalization) is just the number of bits
885 // we are using. Note that the sign bit is gone since we constructed the
886 // absolute value.
887 uint64_t exp = n;
Zhou Shengd707d632007-02-12 20:02:55 +0000888
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000889 // Return infinity for exponent overflow
890 if (exp > 1023) {
891 if (!isSigned || !isNeg)
Jeff Cohene06855e2007-03-20 20:42:36 +0000892 return std::numeric_limits<double>::infinity();
Eric Christopher820256b2009-08-21 04:06:45 +0000893 else
Jeff Cohene06855e2007-03-20 20:42:36 +0000894 return -std::numeric_limits<double>::infinity();
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000895 }
896 exp += 1023; // Increment for 1023 bias
897
898 // Number of bits in mantissa is 52. To obtain the mantissa value, we must
899 // extract the high 52 bits from the correct words in pVal.
Zhou Shengd707d632007-02-12 20:02:55 +0000900 uint64_t mantissa;
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000901 unsigned hiWord = whichWord(n-1);
902 if (hiWord == 0) {
903 mantissa = Tmp.pVal[0];
904 if (n > 52)
905 mantissa >>= n - 52; // shift down, we want the top 52 bits.
906 } else {
907 assert(hiWord > 0 && "huh?");
908 uint64_t hibits = Tmp.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
909 uint64_t lobits = Tmp.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
910 mantissa = hibits | lobits;
911 }
912
Zhou Shengd707d632007-02-12 20:02:55 +0000913 // The leading bit of mantissa is implicit, so get rid of it.
Reid Spencerfbd48a52007-02-18 00:44:22 +0000914 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
Zhou Shengd707d632007-02-12 20:02:55 +0000915 union {
916 double D;
917 uint64_t I;
918 } T;
919 T.I = sign | (exp << 52) | mantissa;
920 return T.D;
921}
922
Reid Spencer1d072122007-02-16 22:36:51 +0000923// Truncate to new width.
Jay Foad583abbc2010-12-07 08:25:19 +0000924APInt APInt::trunc(unsigned width) const {
Reid Spencer1d072122007-02-16 22:36:51 +0000925 assert(width < BitWidth && "Invalid APInt Truncate request");
Chris Lattner1ac3e252008-08-20 17:02:31 +0000926 assert(width && "Can't truncate to 0 bits");
Jay Foad583abbc2010-12-07 08:25:19 +0000927
928 if (width <= APINT_BITS_PER_WORD)
929 return APInt(width, getRawData()[0]);
930
931 APInt Result(getMemory(getNumWords(width)), width);
932
933 // Copy full words.
934 unsigned i;
935 for (i = 0; i != width / APINT_BITS_PER_WORD; i++)
936 Result.pVal[i] = pVal[i];
937
938 // Truncate and copy any partial word.
939 unsigned bits = (0 - width) % APINT_BITS_PER_WORD;
940 if (bits != 0)
941 Result.pVal[i] = pVal[i] << bits >> bits;
942
943 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +0000944}
945
946// Sign extend to a new width.
Jay Foad583abbc2010-12-07 08:25:19 +0000947APInt APInt::sext(unsigned width) const {
Reid Spencer1d072122007-02-16 22:36:51 +0000948 assert(width > BitWidth && "Invalid APInt SignExtend request");
Jay Foad583abbc2010-12-07 08:25:19 +0000949
950 if (width <= APINT_BITS_PER_WORD) {
951 uint64_t val = VAL << (APINT_BITS_PER_WORD - BitWidth);
952 val = (int64_t)val >> (width - BitWidth);
953 return APInt(width, val >> (APINT_BITS_PER_WORD - width));
Reid Spencerb6b5cc32007-02-25 23:44:53 +0000954 }
955
Jay Foad583abbc2010-12-07 08:25:19 +0000956 APInt Result(getMemory(getNumWords(width)), width);
Reid Spencerb6b5cc32007-02-25 23:44:53 +0000957
Jay Foad583abbc2010-12-07 08:25:19 +0000958 // Copy full words.
959 unsigned i;
960 uint64_t word = 0;
961 for (i = 0; i != BitWidth / APINT_BITS_PER_WORD; i++) {
962 word = getRawData()[i];
963 Result.pVal[i] = word;
Reid Spencerb6b5cc32007-02-25 23:44:53 +0000964 }
965
Jay Foad583abbc2010-12-07 08:25:19 +0000966 // Read and sign-extend any partial word.
967 unsigned bits = (0 - BitWidth) % APINT_BITS_PER_WORD;
968 if (bits != 0)
969 word = (int64_t)getRawData()[i] << bits >> bits;
970 else
971 word = (int64_t)word >> (APINT_BITS_PER_WORD - 1);
972
973 // Write remaining full words.
974 for (; i != width / APINT_BITS_PER_WORD; i++) {
975 Result.pVal[i] = word;
976 word = (int64_t)word >> (APINT_BITS_PER_WORD - 1);
Reid Spencerb6b5cc32007-02-25 23:44:53 +0000977 }
Jay Foad583abbc2010-12-07 08:25:19 +0000978
979 // Write any partial word.
980 bits = (0 - width) % APINT_BITS_PER_WORD;
981 if (bits != 0)
982 Result.pVal[i] = word << bits >> bits;
983
984 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +0000985}
986
987// Zero extend to a new width.
Jay Foad583abbc2010-12-07 08:25:19 +0000988APInt APInt::zext(unsigned width) const {
Reid Spencer1d072122007-02-16 22:36:51 +0000989 assert(width > BitWidth && "Invalid APInt ZeroExtend request");
Jay Foad583abbc2010-12-07 08:25:19 +0000990
991 if (width <= APINT_BITS_PER_WORD)
992 return APInt(width, VAL);
993
994 APInt Result(getMemory(getNumWords(width)), width);
995
996 // Copy words.
997 unsigned i;
998 for (i = 0; i != getNumWords(); i++)
999 Result.pVal[i] = getRawData()[i];
1000
1001 // Zero remaining words.
1002 memset(&Result.pVal[i], 0, (Result.getNumWords() - i) * APINT_WORD_SIZE);
1003
1004 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +00001005}
1006
Jay Foad583abbc2010-12-07 08:25:19 +00001007APInt APInt::zextOrTrunc(unsigned width) const {
Reid Spencer742d1702007-03-01 17:15:32 +00001008 if (BitWidth < width)
1009 return zext(width);
1010 if (BitWidth > width)
1011 return trunc(width);
1012 return *this;
1013}
1014
Jay Foad583abbc2010-12-07 08:25:19 +00001015APInt APInt::sextOrTrunc(unsigned width) const {
Reid Spencer742d1702007-03-01 17:15:32 +00001016 if (BitWidth < width)
1017 return sext(width);
1018 if (BitWidth > width)
1019 return trunc(width);
1020 return *this;
1021}
1022
Rafael Espindolabb893fe2012-01-27 23:33:07 +00001023APInt APInt::zextOrSelf(unsigned width) const {
1024 if (BitWidth < width)
1025 return zext(width);
1026 return *this;
1027}
1028
1029APInt APInt::sextOrSelf(unsigned width) const {
1030 if (BitWidth < width)
1031 return sext(width);
1032 return *this;
1033}
1034
Zhou Shenge93db8f2007-02-09 07:48:24 +00001035/// Arithmetic right-shift this APInt by shiftAmt.
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001036/// @brief Arithmetic right-shift function.
Dan Gohman105c1d42008-02-29 01:40:47 +00001037APInt APInt::ashr(const APInt &shiftAmt) const {
Chris Lattner77527f52009-01-21 18:09:24 +00001038 return ashr((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001039}
1040
1041/// Arithmetic right-shift this APInt by shiftAmt.
1042/// @brief Arithmetic right-shift function.
Chris Lattner77527f52009-01-21 18:09:24 +00001043APInt APInt::ashr(unsigned shiftAmt) const {
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001044 assert(shiftAmt <= BitWidth && "Invalid shift amount");
Reid Spencer1825dd02007-03-02 22:39:11 +00001045 // Handle a degenerate case
1046 if (shiftAmt == 0)
1047 return *this;
1048
1049 // Handle single word shifts with built-in ashr
Reid Spencer522ca7c2007-02-25 01:56:07 +00001050 if (isSingleWord()) {
1051 if (shiftAmt == BitWidth)
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001052 return APInt(BitWidth, 0); // undefined
1053 else {
Chris Lattner77527f52009-01-21 18:09:24 +00001054 unsigned SignBit = APINT_BITS_PER_WORD - BitWidth;
Eric Christopher820256b2009-08-21 04:06:45 +00001055 return APInt(BitWidth,
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001056 (((int64_t(VAL) << SignBit) >> SignBit) >> shiftAmt));
1057 }
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001058 }
Reid Spencer522ca7c2007-02-25 01:56:07 +00001059
Reid Spencer1825dd02007-03-02 22:39:11 +00001060 // If all the bits were shifted out, the result is, technically, undefined.
1061 // We return -1 if it was negative, 0 otherwise. We check this early to avoid
1062 // issues in the algorithm below.
Chris Lattnerdad2d092007-05-03 18:15:36 +00001063 if (shiftAmt == BitWidth) {
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001064 if (isNegative())
Zhou Sheng1247c072008-06-05 13:27:38 +00001065 return APInt(BitWidth, -1ULL, true);
Reid Spencera41e93b2007-02-25 19:32:03 +00001066 else
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001067 return APInt(BitWidth, 0);
Chris Lattnerdad2d092007-05-03 18:15:36 +00001068 }
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001069
1070 // Create some space for the result.
1071 uint64_t * val = new uint64_t[getNumWords()];
1072
Reid Spencer1825dd02007-03-02 22:39:11 +00001073 // Compute some values needed by the following shift algorithms
Chris Lattner77527f52009-01-21 18:09:24 +00001074 unsigned wordShift = shiftAmt % APINT_BITS_PER_WORD; // bits to shift per word
1075 unsigned offset = shiftAmt / APINT_BITS_PER_WORD; // word offset for shift
1076 unsigned breakWord = getNumWords() - 1 - offset; // last word affected
1077 unsigned bitsInWord = whichBit(BitWidth); // how many bits in last word?
Reid Spencer1825dd02007-03-02 22:39:11 +00001078 if (bitsInWord == 0)
1079 bitsInWord = APINT_BITS_PER_WORD;
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001080
1081 // If we are shifting whole words, just move whole words
1082 if (wordShift == 0) {
Reid Spencer1825dd02007-03-02 22:39:11 +00001083 // Move the words containing significant bits
Chris Lattner77527f52009-01-21 18:09:24 +00001084 for (unsigned i = 0; i <= breakWord; ++i)
Reid Spencer1825dd02007-03-02 22:39:11 +00001085 val[i] = pVal[i+offset]; // move whole word
1086
1087 // Adjust the top significant word for sign bit fill, if negative
1088 if (isNegative())
1089 if (bitsInWord < APINT_BITS_PER_WORD)
1090 val[breakWord] |= ~0ULL << bitsInWord; // set high bits
1091 } else {
Eric Christopher820256b2009-08-21 04:06:45 +00001092 // Shift the low order words
Chris Lattner77527f52009-01-21 18:09:24 +00001093 for (unsigned i = 0; i < breakWord; ++i) {
Reid Spencer1825dd02007-03-02 22:39:11 +00001094 // This combines the shifted corresponding word with the low bits from
1095 // the next word (shifted into this word's high bits).
Eric Christopher820256b2009-08-21 04:06:45 +00001096 val[i] = (pVal[i+offset] >> wordShift) |
Reid Spencer1825dd02007-03-02 22:39:11 +00001097 (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift));
1098 }
1099
1100 // Shift the break word. In this case there are no bits from the next word
1101 // to include in this word.
1102 val[breakWord] = pVal[breakWord+offset] >> wordShift;
1103
Alp Tokercb402912014-01-24 17:20:08 +00001104 // Deal with sign extension in the break word, and possibly the word before
Reid Spencer1825dd02007-03-02 22:39:11 +00001105 // it.
Chris Lattnerdad2d092007-05-03 18:15:36 +00001106 if (isNegative()) {
Reid Spencer1825dd02007-03-02 22:39:11 +00001107 if (wordShift > bitsInWord) {
1108 if (breakWord > 0)
Eric Christopher820256b2009-08-21 04:06:45 +00001109 val[breakWord-1] |=
Reid Spencer1825dd02007-03-02 22:39:11 +00001110 ~0ULL << (APINT_BITS_PER_WORD - (wordShift - bitsInWord));
1111 val[breakWord] |= ~0ULL;
Eric Christopher820256b2009-08-21 04:06:45 +00001112 } else
Reid Spencer1825dd02007-03-02 22:39:11 +00001113 val[breakWord] |= (~0ULL << (bitsInWord - wordShift));
Chris Lattnerdad2d092007-05-03 18:15:36 +00001114 }
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001115 }
1116
Reid Spencer1825dd02007-03-02 22:39:11 +00001117 // Remaining words are 0 or -1, just assign them.
1118 uint64_t fillValue = (isNegative() ? -1ULL : 0);
Chris Lattner77527f52009-01-21 18:09:24 +00001119 for (unsigned i = breakWord+1; i < getNumWords(); ++i)
Reid Spencer1825dd02007-03-02 22:39:11 +00001120 val[i] = fillValue;
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001121 APInt Result(val, BitWidth);
1122 Result.clearUnusedBits();
1123 return Result;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001124}
1125
Zhou Shenge93db8f2007-02-09 07:48:24 +00001126/// Logical right-shift this APInt by shiftAmt.
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001127/// @brief Logical right-shift function.
Dan Gohman105c1d42008-02-29 01:40:47 +00001128APInt APInt::lshr(const APInt &shiftAmt) const {
Chris Lattner77527f52009-01-21 18:09:24 +00001129 return lshr((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001130}
1131
1132/// Logical right-shift this APInt by shiftAmt.
1133/// @brief Logical right-shift function.
Chris Lattner77527f52009-01-21 18:09:24 +00001134APInt APInt::lshr(unsigned shiftAmt) const {
Chris Lattnerdad2d092007-05-03 18:15:36 +00001135 if (isSingleWord()) {
Ahmed Charles0dca5d82012-02-24 19:06:15 +00001136 if (shiftAmt >= BitWidth)
Reid Spencer522ca7c2007-02-25 01:56:07 +00001137 return APInt(BitWidth, 0);
Eric Christopher820256b2009-08-21 04:06:45 +00001138 else
Reid Spencer522ca7c2007-02-25 01:56:07 +00001139 return APInt(BitWidth, this->VAL >> shiftAmt);
Chris Lattnerdad2d092007-05-03 18:15:36 +00001140 }
Reid Spencer522ca7c2007-02-25 01:56:07 +00001141
Reid Spencer44eef162007-02-26 01:19:48 +00001142 // If all the bits were shifted out, the result is 0. This avoids issues
1143 // with shifting by the size of the integer type, which produces undefined
1144 // results. We define these "undefined results" to always be 0.
Chad Rosier3d464d82012-06-08 18:04:52 +00001145 if (shiftAmt >= BitWidth)
Reid Spencer44eef162007-02-26 01:19:48 +00001146 return APInt(BitWidth, 0);
1147
Reid Spencerfffdf102007-05-17 06:26:29 +00001148 // If none of the bits are shifted out, the result is *this. This avoids
Eric Christopher820256b2009-08-21 04:06:45 +00001149 // issues with shifting by the size of the integer type, which produces
Reid Spencerfffdf102007-05-17 06:26:29 +00001150 // undefined results in the code below. This is also an optimization.
1151 if (shiftAmt == 0)
1152 return *this;
1153
Reid Spencer44eef162007-02-26 01:19:48 +00001154 // Create some space for the result.
1155 uint64_t * val = new uint64_t[getNumWords()];
1156
1157 // If we are shifting less than a word, compute the shift with a simple carry
1158 if (shiftAmt < APINT_BITS_PER_WORD) {
Richard Smith4f9a8082011-11-23 21:33:37 +00001159 lshrNear(val, pVal, getNumWords(), shiftAmt);
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001160 APInt Result(val, BitWidth);
1161 Result.clearUnusedBits();
1162 return Result;
Reid Spencera41e93b2007-02-25 19:32:03 +00001163 }
1164
Reid Spencer44eef162007-02-26 01:19:48 +00001165 // Compute some values needed by the remaining shift algorithms
Chris Lattner77527f52009-01-21 18:09:24 +00001166 unsigned wordShift = shiftAmt % APINT_BITS_PER_WORD;
1167 unsigned offset = shiftAmt / APINT_BITS_PER_WORD;
Reid Spencer44eef162007-02-26 01:19:48 +00001168
1169 // If we are shifting whole words, just move whole words
1170 if (wordShift == 0) {
Chris Lattner77527f52009-01-21 18:09:24 +00001171 for (unsigned i = 0; i < getNumWords() - offset; ++i)
Reid Spencer44eef162007-02-26 01:19:48 +00001172 val[i] = pVal[i+offset];
Chris Lattner77527f52009-01-21 18:09:24 +00001173 for (unsigned i = getNumWords()-offset; i < getNumWords(); i++)
Reid Spencer44eef162007-02-26 01:19:48 +00001174 val[i] = 0;
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001175 APInt Result(val, BitWidth);
1176 Result.clearUnusedBits();
1177 return Result;
Reid Spencer44eef162007-02-26 01:19:48 +00001178 }
1179
Eric Christopher820256b2009-08-21 04:06:45 +00001180 // Shift the low order words
Chris Lattner77527f52009-01-21 18:09:24 +00001181 unsigned breakWord = getNumWords() - offset -1;
1182 for (unsigned i = 0; i < breakWord; ++i)
Reid Spencerd99feaf2007-03-01 05:39:56 +00001183 val[i] = (pVal[i+offset] >> wordShift) |
1184 (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift));
Reid Spencer44eef162007-02-26 01:19:48 +00001185 // Shift the break word.
1186 val[breakWord] = pVal[breakWord+offset] >> wordShift;
1187
1188 // Remaining words are 0
Chris Lattner77527f52009-01-21 18:09:24 +00001189 for (unsigned i = breakWord+1; i < getNumWords(); ++i)
Reid Spencer44eef162007-02-26 01:19:48 +00001190 val[i] = 0;
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001191 APInt Result(val, BitWidth);
1192 Result.clearUnusedBits();
1193 return Result;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001194}
1195
Zhou Shenge93db8f2007-02-09 07:48:24 +00001196/// Left-shift this APInt by shiftAmt.
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001197/// @brief Left-shift function.
Dan Gohman105c1d42008-02-29 01:40:47 +00001198APInt APInt::shl(const APInt &shiftAmt) const {
Nick Lewycky030c4502009-01-19 17:42:33 +00001199 // It's undefined behavior in C to shift by BitWidth or greater.
Chris Lattner77527f52009-01-21 18:09:24 +00001200 return shl((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001201}
1202
Chris Lattner77527f52009-01-21 18:09:24 +00001203APInt APInt::shlSlowCase(unsigned shiftAmt) const {
Reid Spencera5c84d92007-02-25 00:56:44 +00001204 // If all the bits were shifted out, the result is 0. This avoids issues
1205 // with shifting by the size of the integer type, which produces undefined
1206 // results. We define these "undefined results" to always be 0.
1207 if (shiftAmt == BitWidth)
1208 return APInt(BitWidth, 0);
1209
Reid Spencer81ee0202007-05-12 18:01:57 +00001210 // If none of the bits are shifted out, the result is *this. This avoids a
1211 // lshr by the words size in the loop below which can produce incorrect
1212 // results. It also avoids the expensive computation below for a common case.
1213 if (shiftAmt == 0)
1214 return *this;
1215
Reid Spencera5c84d92007-02-25 00:56:44 +00001216 // Create some space for the result.
1217 uint64_t * val = new uint64_t[getNumWords()];
1218
1219 // If we are shifting less than a word, do it the easy way
1220 if (shiftAmt < APINT_BITS_PER_WORD) {
1221 uint64_t carry = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001222 for (unsigned i = 0; i < getNumWords(); i++) {
Reid Spencera5c84d92007-02-25 00:56:44 +00001223 val[i] = pVal[i] << shiftAmt | carry;
1224 carry = pVal[i] >> (APINT_BITS_PER_WORD - shiftAmt);
1225 }
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001226 APInt Result(val, BitWidth);
1227 Result.clearUnusedBits();
1228 return Result;
Reid Spencer632ebdf2007-02-24 20:19:37 +00001229 }
1230
Reid Spencera5c84d92007-02-25 00:56:44 +00001231 // Compute some values needed by the remaining shift algorithms
Chris Lattner77527f52009-01-21 18:09:24 +00001232 unsigned wordShift = shiftAmt % APINT_BITS_PER_WORD;
1233 unsigned offset = shiftAmt / APINT_BITS_PER_WORD;
Reid Spencera5c84d92007-02-25 00:56:44 +00001234
1235 // If we are shifting whole words, just move whole words
1236 if (wordShift == 0) {
Chris Lattner77527f52009-01-21 18:09:24 +00001237 for (unsigned i = 0; i < offset; i++)
Reid Spencera5c84d92007-02-25 00:56:44 +00001238 val[i] = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001239 for (unsigned i = offset; i < getNumWords(); i++)
Reid Spencera5c84d92007-02-25 00:56:44 +00001240 val[i] = pVal[i-offset];
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001241 APInt Result(val, BitWidth);
1242 Result.clearUnusedBits();
1243 return Result;
Reid Spencer632ebdf2007-02-24 20:19:37 +00001244 }
Reid Spencera5c84d92007-02-25 00:56:44 +00001245
1246 // Copy whole words from this to Result.
Chris Lattner77527f52009-01-21 18:09:24 +00001247 unsigned i = getNumWords() - 1;
Reid Spencera5c84d92007-02-25 00:56:44 +00001248 for (; i > offset; --i)
1249 val[i] = pVal[i-offset] << wordShift |
1250 pVal[i-offset-1] >> (APINT_BITS_PER_WORD - wordShift);
Reid Spencerab0e08a2007-02-25 01:08:58 +00001251 val[offset] = pVal[0] << wordShift;
Reid Spencera5c84d92007-02-25 00:56:44 +00001252 for (i = 0; i < offset; ++i)
1253 val[i] = 0;
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001254 APInt Result(val, BitWidth);
1255 Result.clearUnusedBits();
1256 return Result;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001257}
1258
Dan Gohman105c1d42008-02-29 01:40:47 +00001259APInt APInt::rotl(const APInt &rotateAmt) const {
Chris Lattner77527f52009-01-21 18:09:24 +00001260 return rotl((unsigned)rotateAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001261}
1262
Chris Lattner77527f52009-01-21 18:09:24 +00001263APInt APInt::rotl(unsigned rotateAmt) const {
Eli Friedman2aae94f2011-12-22 03:15:35 +00001264 rotateAmt %= BitWidth;
Reid Spencer98ed7db2007-05-14 00:15:28 +00001265 if (rotateAmt == 0)
1266 return *this;
Eli Friedman2aae94f2011-12-22 03:15:35 +00001267 return shl(rotateAmt) | lshr(BitWidth - rotateAmt);
Reid Spencer4c50b522007-05-13 23:44:59 +00001268}
1269
Dan Gohman105c1d42008-02-29 01:40:47 +00001270APInt APInt::rotr(const APInt &rotateAmt) const {
Chris Lattner77527f52009-01-21 18:09:24 +00001271 return rotr((unsigned)rotateAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001272}
1273
Chris Lattner77527f52009-01-21 18:09:24 +00001274APInt APInt::rotr(unsigned rotateAmt) const {
Eli Friedman2aae94f2011-12-22 03:15:35 +00001275 rotateAmt %= BitWidth;
Reid Spencer98ed7db2007-05-14 00:15:28 +00001276 if (rotateAmt == 0)
1277 return *this;
Eli Friedman2aae94f2011-12-22 03:15:35 +00001278 return lshr(rotateAmt) | shl(BitWidth - rotateAmt);
Reid Spencer4c50b522007-05-13 23:44:59 +00001279}
Reid Spencerd99feaf2007-03-01 05:39:56 +00001280
1281// Square Root - this method computes and returns the square root of "this".
1282// Three mechanisms are used for computation. For small values (<= 5 bits),
1283// a table lookup is done. This gets some performance for common cases. For
1284// values using less than 52 bits, the value is converted to double and then
1285// the libc sqrt function is called. The result is rounded and then converted
1286// back to a uint64_t which is then used to construct the result. Finally,
Eric Christopher820256b2009-08-21 04:06:45 +00001287// the Babylonian method for computing square roots is used.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001288APInt APInt::sqrt() const {
1289
1290 // Determine the magnitude of the value.
Chris Lattner77527f52009-01-21 18:09:24 +00001291 unsigned magnitude = getActiveBits();
Reid Spencerd99feaf2007-03-01 05:39:56 +00001292
1293 // Use a fast table for some small values. This also gets rid of some
1294 // rounding errors in libc sqrt for small values.
1295 if (magnitude <= 5) {
Reid Spencer2f6ad4d2007-03-01 17:47:31 +00001296 static const uint8_t results[32] = {
Reid Spencerc8841d22007-03-01 06:23:32 +00001297 /* 0 */ 0,
1298 /* 1- 2 */ 1, 1,
Eric Christopher820256b2009-08-21 04:06:45 +00001299 /* 3- 6 */ 2, 2, 2, 2,
Reid Spencerc8841d22007-03-01 06:23:32 +00001300 /* 7-12 */ 3, 3, 3, 3, 3, 3,
1301 /* 13-20 */ 4, 4, 4, 4, 4, 4, 4, 4,
1302 /* 21-30 */ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
1303 /* 31 */ 6
1304 };
1305 return APInt(BitWidth, results[ (isSingleWord() ? VAL : pVal[0]) ]);
Reid Spencerd99feaf2007-03-01 05:39:56 +00001306 }
1307
1308 // If the magnitude of the value fits in less than 52 bits (the precision of
1309 // an IEEE double precision floating point value), then we can use the
1310 // libc sqrt function which will probably use a hardware sqrt computation.
1311 // This should be faster than the algorithm below.
Jeff Cohenb622c112007-03-05 00:00:42 +00001312 if (magnitude < 52) {
Eric Christopher820256b2009-08-21 04:06:45 +00001313 return APInt(BitWidth,
Reid Spencerd99feaf2007-03-01 05:39:56 +00001314 uint64_t(::round(::sqrt(double(isSingleWord()?VAL:pVal[0])))));
Jeff Cohenb622c112007-03-05 00:00:42 +00001315 }
Reid Spencerd99feaf2007-03-01 05:39:56 +00001316
1317 // Okay, all the short cuts are exhausted. We must compute it. The following
1318 // is a classical Babylonian method for computing the square root. This code
Sanjay Patel4cb54e02014-09-11 15:41:01 +00001319 // was adapted to APInt from a wikipedia article on such computations.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001320 // See http://www.wikipedia.org/ and go to the page named
Eric Christopher820256b2009-08-21 04:06:45 +00001321 // Calculate_an_integer_square_root.
Chris Lattner77527f52009-01-21 18:09:24 +00001322 unsigned nbits = BitWidth, i = 4;
Reid Spencerd99feaf2007-03-01 05:39:56 +00001323 APInt testy(BitWidth, 16);
1324 APInt x_old(BitWidth, 1);
1325 APInt x_new(BitWidth, 0);
1326 APInt two(BitWidth, 2);
1327
1328 // Select a good starting value using binary logarithms.
Eric Christopher820256b2009-08-21 04:06:45 +00001329 for (;; i += 2, testy = testy.shl(2))
Reid Spencerd99feaf2007-03-01 05:39:56 +00001330 if (i >= nbits || this->ule(testy)) {
1331 x_old = x_old.shl(i / 2);
1332 break;
1333 }
1334
Eric Christopher820256b2009-08-21 04:06:45 +00001335 // Use the Babylonian method to arrive at the integer square root:
Reid Spencerd99feaf2007-03-01 05:39:56 +00001336 for (;;) {
1337 x_new = (this->udiv(x_old) + x_old).udiv(two);
1338 if (x_old.ule(x_new))
1339 break;
1340 x_old = x_new;
1341 }
1342
1343 // Make sure we return the closest approximation
Eric Christopher820256b2009-08-21 04:06:45 +00001344 // NOTE: The rounding calculation below is correct. It will produce an
Reid Spencercf817562007-03-02 04:21:55 +00001345 // off-by-one discrepancy with results from pari/gp. That discrepancy has been
Eric Christopher820256b2009-08-21 04:06:45 +00001346 // determined to be a rounding issue with pari/gp as it begins to use a
Reid Spencercf817562007-03-02 04:21:55 +00001347 // floating point representation after 192 bits. There are no discrepancies
1348 // between this algorithm and pari/gp for bit widths < 192 bits.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001349 APInt square(x_old * x_old);
1350 APInt nextSquare((x_old + 1) * (x_old +1));
1351 if (this->ult(square))
1352 return x_old;
David Blaikie54c94622011-12-01 20:58:30 +00001353 assert(this->ule(nextSquare) && "Error in APInt::sqrt computation");
1354 APInt midpoint((nextSquare - square).udiv(two));
1355 APInt offset(*this - square);
1356 if (offset.ult(midpoint))
1357 return x_old;
Reid Spencerd99feaf2007-03-01 05:39:56 +00001358 return x_old + 1;
1359}
1360
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001361/// Computes the multiplicative inverse of this APInt for a given modulo. The
1362/// iterative extended Euclidean algorithm is used to solve for this value,
1363/// however we simplify it to speed up calculating only the inverse, and take
1364/// advantage of div+rem calculations. We also use some tricks to avoid copying
1365/// (potentially large) APInts around.
1366APInt APInt::multiplicativeInverse(const APInt& modulo) const {
1367 assert(ult(modulo) && "This APInt must be smaller than the modulo");
1368
1369 // Using the properties listed at the following web page (accessed 06/21/08):
1370 // http://www.numbertheory.org/php/euclid.html
1371 // (especially the properties numbered 3, 4 and 9) it can be proved that
1372 // BitWidth bits suffice for all the computations in the algorithm implemented
1373 // below. More precisely, this number of bits suffice if the multiplicative
1374 // inverse exists, but may not suffice for the general extended Euclidean
1375 // algorithm.
1376
1377 APInt r[2] = { modulo, *this };
1378 APInt t[2] = { APInt(BitWidth, 0), APInt(BitWidth, 1) };
1379 APInt q(BitWidth, 0);
Eric Christopher820256b2009-08-21 04:06:45 +00001380
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001381 unsigned i;
1382 for (i = 0; r[i^1] != 0; i ^= 1) {
1383 // An overview of the math without the confusing bit-flipping:
1384 // q = r[i-2] / r[i-1]
1385 // r[i] = r[i-2] % r[i-1]
1386 // t[i] = t[i-2] - t[i-1] * q
1387 udivrem(r[i], r[i^1], q, r[i]);
1388 t[i] -= t[i^1] * q;
1389 }
1390
1391 // If this APInt and the modulo are not coprime, there is no multiplicative
1392 // inverse, so return 0. We check this by looking at the next-to-last
1393 // remainder, which is the gcd(*this,modulo) as calculated by the Euclidean
1394 // algorithm.
1395 if (r[i] != 1)
1396 return APInt(BitWidth, 0);
1397
1398 // The next-to-last t is the multiplicative inverse. However, we are
1399 // interested in a positive inverse. Calcuate a positive one from a negative
1400 // one if necessary. A simple addition of the modulo suffices because
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00001401 // abs(t[i]) is known to be less than *this/2 (see the link above).
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001402 return t[i].isNegative() ? t[i] + modulo : t[i];
1403}
1404
Jay Foadfe0c6482009-04-30 10:15:35 +00001405/// Calculate the magic numbers required to implement a signed integer division
1406/// by a constant as a sequence of multiplies, adds and shifts. Requires that
1407/// the divisor not be 0, 1, or -1. Taken from "Hacker's Delight", Henry S.
1408/// Warren, Jr., chapter 10.
1409APInt::ms APInt::magic() const {
1410 const APInt& d = *this;
1411 unsigned p;
1412 APInt ad, anc, delta, q1, r1, q2, r2, t;
Jay Foadfe0c6482009-04-30 10:15:35 +00001413 APInt signedMin = APInt::getSignedMinValue(d.getBitWidth());
Jay Foadfe0c6482009-04-30 10:15:35 +00001414 struct ms mag;
Eric Christopher820256b2009-08-21 04:06:45 +00001415
Jay Foadfe0c6482009-04-30 10:15:35 +00001416 ad = d.abs();
1417 t = signedMin + (d.lshr(d.getBitWidth() - 1));
1418 anc = t - 1 - t.urem(ad); // absolute value of nc
1419 p = d.getBitWidth() - 1; // initialize p
1420 q1 = signedMin.udiv(anc); // initialize q1 = 2p/abs(nc)
1421 r1 = signedMin - q1*anc; // initialize r1 = rem(2p,abs(nc))
1422 q2 = signedMin.udiv(ad); // initialize q2 = 2p/abs(d)
1423 r2 = signedMin - q2*ad; // initialize r2 = rem(2p,abs(d))
1424 do {
1425 p = p + 1;
1426 q1 = q1<<1; // update q1 = 2p/abs(nc)
1427 r1 = r1<<1; // update r1 = rem(2p/abs(nc))
1428 if (r1.uge(anc)) { // must be unsigned comparison
1429 q1 = q1 + 1;
1430 r1 = r1 - anc;
1431 }
1432 q2 = q2<<1; // update q2 = 2p/abs(d)
1433 r2 = r2<<1; // update r2 = rem(2p/abs(d))
1434 if (r2.uge(ad)) { // must be unsigned comparison
1435 q2 = q2 + 1;
1436 r2 = r2 - ad;
1437 }
1438 delta = ad - r2;
Cameron Zwarich8731d0c2011-02-21 00:22:02 +00001439 } while (q1.ult(delta) || (q1 == delta && r1 == 0));
Eric Christopher820256b2009-08-21 04:06:45 +00001440
Jay Foadfe0c6482009-04-30 10:15:35 +00001441 mag.m = q2 + 1;
1442 if (d.isNegative()) mag.m = -mag.m; // resulting magic number
1443 mag.s = p - d.getBitWidth(); // resulting shift
1444 return mag;
1445}
1446
1447/// Calculate the magic numbers required to implement an unsigned integer
1448/// division by a constant as a sequence of multiplies, adds and shifts.
1449/// Requires that the divisor not be 0. Taken from "Hacker's Delight", Henry
1450/// S. Warren, Jr., chapter 10.
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001451/// LeadingZeros can be used to simplify the calculation if the upper bits
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001452/// of the divided value are known zero.
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001453APInt::mu APInt::magicu(unsigned LeadingZeros) const {
Jay Foadfe0c6482009-04-30 10:15:35 +00001454 const APInt& d = *this;
1455 unsigned p;
1456 APInt nc, delta, q1, r1, q2, r2;
1457 struct mu magu;
1458 magu.a = 0; // initialize "add" indicator
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001459 APInt allOnes = APInt::getAllOnesValue(d.getBitWidth()).lshr(LeadingZeros);
Jay Foadfe0c6482009-04-30 10:15:35 +00001460 APInt signedMin = APInt::getSignedMinValue(d.getBitWidth());
1461 APInt signedMax = APInt::getSignedMaxValue(d.getBitWidth());
1462
Benjamin Kramer3aab6a82012-07-11 18:31:59 +00001463 nc = allOnes - (allOnes - d).urem(d);
Jay Foadfe0c6482009-04-30 10:15:35 +00001464 p = d.getBitWidth() - 1; // initialize p
1465 q1 = signedMin.udiv(nc); // initialize q1 = 2p/nc
1466 r1 = signedMin - q1*nc; // initialize r1 = rem(2p,nc)
1467 q2 = signedMax.udiv(d); // initialize q2 = (2p-1)/d
1468 r2 = signedMax - q2*d; // initialize r2 = rem((2p-1),d)
1469 do {
1470 p = p + 1;
1471 if (r1.uge(nc - r1)) {
1472 q1 = q1 + q1 + 1; // update q1
1473 r1 = r1 + r1 - nc; // update r1
1474 }
1475 else {
1476 q1 = q1+q1; // update q1
1477 r1 = r1+r1; // update r1
1478 }
1479 if ((r2 + 1).uge(d - r2)) {
1480 if (q2.uge(signedMax)) magu.a = 1;
1481 q2 = q2+q2 + 1; // update q2
1482 r2 = r2+r2 + 1 - d; // update r2
1483 }
1484 else {
1485 if (q2.uge(signedMin)) magu.a = 1;
1486 q2 = q2+q2; // update q2
1487 r2 = r2+r2 + 1; // update r2
1488 }
1489 delta = d - 1 - r2;
1490 } while (p < d.getBitWidth()*2 &&
1491 (q1.ult(delta) || (q1 == delta && r1 == 0)));
1492 magu.m = q2 + 1; // resulting magic number
1493 magu.s = p - d.getBitWidth(); // resulting shift
1494 return magu;
1495}
1496
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001497/// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
1498/// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
1499/// variables here have the same names as in the algorithm. Comments explain
1500/// the algorithm and any deviation from it.
Chris Lattner77527f52009-01-21 18:09:24 +00001501static void KnuthDiv(unsigned *u, unsigned *v, unsigned *q, unsigned* r,
1502 unsigned m, unsigned n) {
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001503 assert(u && "Must provide dividend");
1504 assert(v && "Must provide divisor");
1505 assert(q && "Must provide quotient");
Reid Spencera5e0d202007-02-24 03:58:46 +00001506 assert(u != v && u != q && v != q && "Must us different memory");
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001507 assert(n>1 && "n must be > 1");
1508
1509 // Knuth uses the value b as the base of the number system. In our case b
1510 // is 2^31 so we just set it to -1u.
1511 uint64_t b = uint64_t(1) << 32;
1512
Chris Lattner17f71652008-08-17 07:19:36 +00001513#if 0
David Greenef32fcb42010-01-05 01:28:52 +00001514 DEBUG(dbgs() << "KnuthDiv: m=" << m << " n=" << n << '\n');
1515 DEBUG(dbgs() << "KnuthDiv: original:");
1516 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
1517 DEBUG(dbgs() << " by");
1518 DEBUG(for (int i = n; i >0; i--) dbgs() << " " << v[i-1]);
1519 DEBUG(dbgs() << '\n');
Chris Lattner17f71652008-08-17 07:19:36 +00001520#endif
Eric Christopher820256b2009-08-21 04:06:45 +00001521 // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
1522 // u and v by d. Note that we have taken Knuth's advice here to use a power
1523 // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
1524 // 2 allows us to shift instead of multiply and it is easy to determine the
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001525 // shift amount from the leading zeros. We are basically normalizing the u
1526 // and v so that its high bits are shifted to the top of v's range without
1527 // overflow. Note that this can require an extra word in u so that u must
1528 // be of length m+n+1.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001529 unsigned shift = countLeadingZeros(v[n-1]);
Chris Lattner77527f52009-01-21 18:09:24 +00001530 unsigned v_carry = 0;
1531 unsigned u_carry = 0;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001532 if (shift) {
Chris Lattner77527f52009-01-21 18:09:24 +00001533 for (unsigned i = 0; i < m+n; ++i) {
1534 unsigned u_tmp = u[i] >> (32 - shift);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001535 u[i] = (u[i] << shift) | u_carry;
1536 u_carry = u_tmp;
Reid Spencer100502d2007-02-17 03:16:00 +00001537 }
Chris Lattner77527f52009-01-21 18:09:24 +00001538 for (unsigned i = 0; i < n; ++i) {
1539 unsigned v_tmp = v[i] >> (32 - shift);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001540 v[i] = (v[i] << shift) | v_carry;
1541 v_carry = v_tmp;
1542 }
1543 }
1544 u[m+n] = u_carry;
Chris Lattner17f71652008-08-17 07:19:36 +00001545#if 0
David Greenef32fcb42010-01-05 01:28:52 +00001546 DEBUG(dbgs() << "KnuthDiv: normal:");
1547 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
1548 DEBUG(dbgs() << " by");
1549 DEBUG(for (int i = n; i >0; i--) dbgs() << " " << v[i-1]);
1550 DEBUG(dbgs() << '\n');
Chris Lattner17f71652008-08-17 07:19:36 +00001551#endif
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001552
1553 // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
1554 int j = m;
1555 do {
David Greenef32fcb42010-01-05 01:28:52 +00001556 DEBUG(dbgs() << "KnuthDiv: quotient digit #" << j << '\n');
Eric Christopher820256b2009-08-21 04:06:45 +00001557 // D3. [Calculate q'.].
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001558 // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
1559 // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
1560 // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
1561 // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test
1562 // on v[n-2] determines at high speed most of the cases in which the trial
Eric Christopher820256b2009-08-21 04:06:45 +00001563 // value qp is one too large, and it eliminates all cases where qp is two
1564 // too large.
Reid Spencercb292e42007-02-23 01:57:13 +00001565 uint64_t dividend = ((uint64_t(u[j+n]) << 32) + u[j+n-1]);
David Greenef32fcb42010-01-05 01:28:52 +00001566 DEBUG(dbgs() << "KnuthDiv: dividend == " << dividend << '\n');
Reid Spencercb292e42007-02-23 01:57:13 +00001567 uint64_t qp = dividend / v[n-1];
1568 uint64_t rp = dividend % v[n-1];
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001569 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1570 qp--;
1571 rp += v[n-1];
Reid Spencerdf6cf5a2007-02-24 10:01:42 +00001572 if (rp < b && (qp == b || qp*v[n-2] > b*rp + u[j+n-2]))
Reid Spencera5e0d202007-02-24 03:58:46 +00001573 qp--;
Reid Spencercb292e42007-02-23 01:57:13 +00001574 }
David Greenef32fcb42010-01-05 01:28:52 +00001575 DEBUG(dbgs() << "KnuthDiv: qp == " << qp << ", rp == " << rp << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001576
Reid Spencercb292e42007-02-23 01:57:13 +00001577 // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with
1578 // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation
1579 // consists of a simple multiplication by a one-place number, combined with
Eric Christopher820256b2009-08-21 04:06:45 +00001580 // a subtraction.
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001581 bool isNeg = false;
Chris Lattner77527f52009-01-21 18:09:24 +00001582 for (unsigned i = 0; i < n; ++i) {
Reid Spencerdf6cf5a2007-02-24 10:01:42 +00001583 uint64_t u_tmp = uint64_t(u[j+i]) | (uint64_t(u[j+i+1]) << 32);
Reid Spencera5e0d202007-02-24 03:58:46 +00001584 uint64_t subtrahend = uint64_t(qp) * uint64_t(v[i]);
Reid Spencerdf6cf5a2007-02-24 10:01:42 +00001585 bool borrow = subtrahend > u_tmp;
David Greenef32fcb42010-01-05 01:28:52 +00001586 DEBUG(dbgs() << "KnuthDiv: u_tmp == " << u_tmp
Daniel Dunbar763ace92009-07-13 05:27:30 +00001587 << ", subtrahend == " << subtrahend
1588 << ", borrow = " << borrow << '\n');
Reid Spencera5e0d202007-02-24 03:58:46 +00001589
Reid Spencerdf6cf5a2007-02-24 10:01:42 +00001590 uint64_t result = u_tmp - subtrahend;
Chris Lattner77527f52009-01-21 18:09:24 +00001591 unsigned k = j + i;
1592 u[k++] = (unsigned)(result & (b-1)); // subtract low word
1593 u[k++] = (unsigned)(result >> 32); // subtract high word
Reid Spencerdf6cf5a2007-02-24 10:01:42 +00001594 while (borrow && k <= m+n) { // deal with borrow to the left
1595 borrow = u[k] == 0;
1596 u[k]--;
1597 k++;
1598 }
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001599 isNeg |= borrow;
David Greenef32fcb42010-01-05 01:28:52 +00001600 DEBUG(dbgs() << "KnuthDiv: u[j+i] == " << u[j+i] << ", u[j+i+1] == " <<
Eric Christopher820256b2009-08-21 04:06:45 +00001601 u[j+i+1] << '\n');
Reid Spencera5e0d202007-02-24 03:58:46 +00001602 }
David Greenef32fcb42010-01-05 01:28:52 +00001603 DEBUG(dbgs() << "KnuthDiv: after subtraction:");
1604 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
1605 DEBUG(dbgs() << '\n');
Eric Christopher820256b2009-08-21 04:06:45 +00001606 // The digits (u[j+n]...u[j]) should be kept positive; if the result of
1607 // this step is actually negative, (u[j+n]...u[j]) should be left as the
Reid Spencerdf6cf5a2007-02-24 10:01:42 +00001608 // true value plus b**(n+1), namely as the b's complement of
Reid Spencercb292e42007-02-23 01:57:13 +00001609 // the true value, and a "borrow" to the left should be remembered.
1610 //
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001611 if (isNeg) {
Reid Spencerdf6cf5a2007-02-24 10:01:42 +00001612 bool carry = true; // true because b's complement is "complement + 1"
Chris Lattner77527f52009-01-21 18:09:24 +00001613 for (unsigned i = 0; i <= m+n; ++i) {
Reid Spencerdf6cf5a2007-02-24 10:01:42 +00001614 u[i] = ~u[i] + carry; // b's complement
1615 carry = carry && u[i] == 0;
Reid Spencera5e0d202007-02-24 03:58:46 +00001616 }
Reid Spencercb292e42007-02-23 01:57:13 +00001617 }
David Greenef32fcb42010-01-05 01:28:52 +00001618 DEBUG(dbgs() << "KnuthDiv: after complement:");
1619 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
1620 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001621
Eric Christopher820256b2009-08-21 04:06:45 +00001622 // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001623 // negative, go to step D6; otherwise go on to step D7.
Chris Lattner77527f52009-01-21 18:09:24 +00001624 q[j] = (unsigned)qp;
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001625 if (isNeg) {
Eric Christopher820256b2009-08-21 04:06:45 +00001626 // D6. [Add back]. The probability that this step is necessary is very
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001627 // small, on the order of only 2/b. Make sure that test data accounts for
Eric Christopher820256b2009-08-21 04:06:45 +00001628 // this possibility. Decrease q[j] by 1
Reid Spencercb292e42007-02-23 01:57:13 +00001629 q[j]--;
Eric Christopher820256b2009-08-21 04:06:45 +00001630 // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]).
1631 // A carry will occur to the left of u[j+n], and it should be ignored
Reid Spencercb292e42007-02-23 01:57:13 +00001632 // since it cancels with the borrow that occurred in D4.
1633 bool carry = false;
Chris Lattner77527f52009-01-21 18:09:24 +00001634 for (unsigned i = 0; i < n; i++) {
1635 unsigned limit = std::min(u[j+i],v[i]);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001636 u[j+i] += v[i] + carry;
Reid Spencera5e0d202007-02-24 03:58:46 +00001637 carry = u[j+i] < limit || (carry && u[j+i] == limit);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001638 }
Reid Spencera5e0d202007-02-24 03:58:46 +00001639 u[j+n] += carry;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001640 }
David Greenef32fcb42010-01-05 01:28:52 +00001641 DEBUG(dbgs() << "KnuthDiv: after correction:");
1642 DEBUG(for (int i = m+n; i >=0; i--) dbgs() <<" " << u[i]);
1643 DEBUG(dbgs() << "\nKnuthDiv: digit result = " << q[j] << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001644
Reid Spencercb292e42007-02-23 01:57:13 +00001645 // D7. [Loop on j.] Decrease j by one. Now if j >= 0, go back to D3.
1646 } while (--j >= 0);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001647
David Greenef32fcb42010-01-05 01:28:52 +00001648 DEBUG(dbgs() << "KnuthDiv: quotient:");
1649 DEBUG(for (int i = m; i >=0; i--) dbgs() <<" " << q[i]);
1650 DEBUG(dbgs() << '\n');
Reid Spencera5e0d202007-02-24 03:58:46 +00001651
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001652 // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
1653 // remainder may be obtained by dividing u[...] by d. If r is non-null we
1654 // compute the remainder (urem uses this).
1655 if (r) {
1656 // The value d is expressed by the "shift" value above since we avoided
1657 // multiplication by d by using a shift left. So, all we have to do is
1658 // shift right here. In order to mak
Reid Spencer468ad9112007-02-24 20:38:01 +00001659 if (shift) {
Chris Lattner77527f52009-01-21 18:09:24 +00001660 unsigned carry = 0;
David Greenef32fcb42010-01-05 01:28:52 +00001661 DEBUG(dbgs() << "KnuthDiv: remainder:");
Reid Spencer468ad9112007-02-24 20:38:01 +00001662 for (int i = n-1; i >= 0; i--) {
1663 r[i] = (u[i] >> shift) | carry;
1664 carry = u[i] << (32 - shift);
David Greenef32fcb42010-01-05 01:28:52 +00001665 DEBUG(dbgs() << " " << r[i]);
Reid Spencer468ad9112007-02-24 20:38:01 +00001666 }
1667 } else {
1668 for (int i = n-1; i >= 0; i--) {
1669 r[i] = u[i];
David Greenef32fcb42010-01-05 01:28:52 +00001670 DEBUG(dbgs() << " " << r[i]);
Reid Spencer468ad9112007-02-24 20:38:01 +00001671 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001672 }
David Greenef32fcb42010-01-05 01:28:52 +00001673 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001674 }
Chris Lattner17f71652008-08-17 07:19:36 +00001675#if 0
David Greenef32fcb42010-01-05 01:28:52 +00001676 DEBUG(dbgs() << '\n');
Chris Lattner17f71652008-08-17 07:19:36 +00001677#endif
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001678}
1679
Chris Lattner77527f52009-01-21 18:09:24 +00001680void APInt::divide(const APInt LHS, unsigned lhsWords,
1681 const APInt &RHS, unsigned rhsWords,
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001682 APInt *Quotient, APInt *Remainder)
1683{
1684 assert(lhsWords >= rhsWords && "Fractional result");
1685
Eric Christopher820256b2009-08-21 04:06:45 +00001686 // First, compose the values into an array of 32-bit words instead of
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001687 // 64-bit words. This is a necessity of both the "short division" algorithm
Dan Gohman4a618822010-02-10 16:03:48 +00001688 // and the Knuth "classical algorithm" which requires there to be native
Eric Christopher820256b2009-08-21 04:06:45 +00001689 // operations for +, -, and * on an m bit value with an m*2 bit result. We
1690 // can't use 64-bit operands here because we don't have native results of
1691 // 128-bits. Furthermore, casting the 64-bit values to 32-bit values won't
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001692 // work on large-endian machines.
Dan Gohmancff69532009-04-01 18:45:54 +00001693 uint64_t mask = ~0ull >> (sizeof(unsigned)*CHAR_BIT);
Chris Lattner77527f52009-01-21 18:09:24 +00001694 unsigned n = rhsWords * 2;
1695 unsigned m = (lhsWords * 2) - n;
Reid Spencer522ca7c2007-02-25 01:56:07 +00001696
1697 // Allocate space for the temporary values we need either on the stack, if
1698 // it will fit, or on the heap if it won't.
Chris Lattner77527f52009-01-21 18:09:24 +00001699 unsigned SPACE[128];
Craig Topperc10719f2014-04-07 04:17:22 +00001700 unsigned *U = nullptr;
1701 unsigned *V = nullptr;
1702 unsigned *Q = nullptr;
1703 unsigned *R = nullptr;
Reid Spencer522ca7c2007-02-25 01:56:07 +00001704 if ((Remainder?4:3)*n+2*m+1 <= 128) {
1705 U = &SPACE[0];
1706 V = &SPACE[m+n+1];
1707 Q = &SPACE[(m+n+1) + n];
1708 if (Remainder)
1709 R = &SPACE[(m+n+1) + n + (m+n)];
1710 } else {
Chris Lattner77527f52009-01-21 18:09:24 +00001711 U = new unsigned[m + n + 1];
1712 V = new unsigned[n];
1713 Q = new unsigned[m+n];
Reid Spencer522ca7c2007-02-25 01:56:07 +00001714 if (Remainder)
Chris Lattner77527f52009-01-21 18:09:24 +00001715 R = new unsigned[n];
Reid Spencer522ca7c2007-02-25 01:56:07 +00001716 }
1717
1718 // Initialize the dividend
Chris Lattner77527f52009-01-21 18:09:24 +00001719 memset(U, 0, (m+n+1)*sizeof(unsigned));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001720 for (unsigned i = 0; i < lhsWords; ++i) {
Reid Spencer867b4062007-02-22 00:58:45 +00001721 uint64_t tmp = (LHS.getNumWords() == 1 ? LHS.VAL : LHS.pVal[i]);
Chris Lattner77527f52009-01-21 18:09:24 +00001722 U[i * 2] = (unsigned)(tmp & mask);
Dan Gohmancff69532009-04-01 18:45:54 +00001723 U[i * 2 + 1] = (unsigned)(tmp >> (sizeof(unsigned)*CHAR_BIT));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001724 }
1725 U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
1726
Reid Spencer522ca7c2007-02-25 01:56:07 +00001727 // Initialize the divisor
Chris Lattner77527f52009-01-21 18:09:24 +00001728 memset(V, 0, (n)*sizeof(unsigned));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001729 for (unsigned i = 0; i < rhsWords; ++i) {
Reid Spencer867b4062007-02-22 00:58:45 +00001730 uint64_t tmp = (RHS.getNumWords() == 1 ? RHS.VAL : RHS.pVal[i]);
Chris Lattner77527f52009-01-21 18:09:24 +00001731 V[i * 2] = (unsigned)(tmp & mask);
Dan Gohmancff69532009-04-01 18:45:54 +00001732 V[i * 2 + 1] = (unsigned)(tmp >> (sizeof(unsigned)*CHAR_BIT));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001733 }
1734
Reid Spencer522ca7c2007-02-25 01:56:07 +00001735 // initialize the quotient and remainder
Chris Lattner77527f52009-01-21 18:09:24 +00001736 memset(Q, 0, (m+n) * sizeof(unsigned));
Reid Spencer522ca7c2007-02-25 01:56:07 +00001737 if (Remainder)
Chris Lattner77527f52009-01-21 18:09:24 +00001738 memset(R, 0, n * sizeof(unsigned));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001739
Eric Christopher820256b2009-08-21 04:06:45 +00001740 // Now, adjust m and n for the Knuth division. n is the number of words in
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001741 // the divisor. m is the number of words by which the dividend exceeds the
Eric Christopher820256b2009-08-21 04:06:45 +00001742 // divisor (i.e. m+n is the length of the dividend). These sizes must not
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001743 // contain any zero words or the Knuth algorithm fails.
1744 for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
1745 n--;
1746 m++;
1747 }
1748 for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
1749 m--;
1750
1751 // If we're left with only a single word for the divisor, Knuth doesn't work
1752 // so we implement the short division algorithm here. This is much simpler
1753 // and faster because we are certain that we can divide a 64-bit quantity
1754 // by a 32-bit quantity at hardware speed and short division is simply a
1755 // series of such operations. This is just like doing short division but we
1756 // are using base 2^32 instead of base 10.
1757 assert(n != 0 && "Divide by zero?");
1758 if (n == 1) {
Chris Lattner77527f52009-01-21 18:09:24 +00001759 unsigned divisor = V[0];
1760 unsigned remainder = 0;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001761 for (int i = m+n-1; i >= 0; i--) {
1762 uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i];
1763 if (partial_dividend == 0) {
1764 Q[i] = 0;
1765 remainder = 0;
1766 } else if (partial_dividend < divisor) {
1767 Q[i] = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001768 remainder = (unsigned)partial_dividend;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001769 } else if (partial_dividend == divisor) {
1770 Q[i] = 1;
1771 remainder = 0;
1772 } else {
Chris Lattner77527f52009-01-21 18:09:24 +00001773 Q[i] = (unsigned)(partial_dividend / divisor);
1774 remainder = (unsigned)(partial_dividend - (Q[i] * divisor));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001775 }
1776 }
1777 if (R)
1778 R[0] = remainder;
1779 } else {
1780 // Now we're ready to invoke the Knuth classical divide algorithm. In this
1781 // case n > 1.
1782 KnuthDiv(U, V, Q, R, m, n);
1783 }
1784
1785 // If the caller wants the quotient
1786 if (Quotient) {
1787 // Set up the Quotient value's memory.
1788 if (Quotient->BitWidth != LHS.BitWidth) {
1789 if (Quotient->isSingleWord())
1790 Quotient->VAL = 0;
1791 else
Reid Spencer7c16cd22007-02-26 23:38:21 +00001792 delete [] Quotient->pVal;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001793 Quotient->BitWidth = LHS.BitWidth;
1794 if (!Quotient->isSingleWord())
Reid Spencer58a6a432007-02-21 08:21:52 +00001795 Quotient->pVal = getClearedMemory(Quotient->getNumWords());
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001796 } else
Jay Foad25a5e4c2010-12-01 08:53:58 +00001797 Quotient->clearAllBits();
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001798
Eric Christopher820256b2009-08-21 04:06:45 +00001799 // The quotient is in Q. Reconstitute the quotient into Quotient's low
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001800 // order words.
1801 if (lhsWords == 1) {
Eric Christopher820256b2009-08-21 04:06:45 +00001802 uint64_t tmp =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001803 uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2));
1804 if (Quotient->isSingleWord())
1805 Quotient->VAL = tmp;
1806 else
1807 Quotient->pVal[0] = tmp;
1808 } else {
1809 assert(!Quotient->isSingleWord() && "Quotient APInt not large enough");
1810 for (unsigned i = 0; i < lhsWords; ++i)
Eric Christopher820256b2009-08-21 04:06:45 +00001811 Quotient->pVal[i] =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001812 uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1813 }
1814 }
1815
1816 // If the caller wants the remainder
1817 if (Remainder) {
1818 // Set up the Remainder value's memory.
1819 if (Remainder->BitWidth != RHS.BitWidth) {
1820 if (Remainder->isSingleWord())
1821 Remainder->VAL = 0;
1822 else
Reid Spencer7c16cd22007-02-26 23:38:21 +00001823 delete [] Remainder->pVal;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001824 Remainder->BitWidth = RHS.BitWidth;
1825 if (!Remainder->isSingleWord())
Reid Spencer58a6a432007-02-21 08:21:52 +00001826 Remainder->pVal = getClearedMemory(Remainder->getNumWords());
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001827 } else
Jay Foad25a5e4c2010-12-01 08:53:58 +00001828 Remainder->clearAllBits();
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001829
1830 // The remainder is in R. Reconstitute the remainder into Remainder's low
1831 // order words.
1832 if (rhsWords == 1) {
Eric Christopher820256b2009-08-21 04:06:45 +00001833 uint64_t tmp =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001834 uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2));
1835 if (Remainder->isSingleWord())
1836 Remainder->VAL = tmp;
1837 else
1838 Remainder->pVal[0] = tmp;
1839 } else {
1840 assert(!Remainder->isSingleWord() && "Remainder APInt not large enough");
1841 for (unsigned i = 0; i < rhsWords; ++i)
Eric Christopher820256b2009-08-21 04:06:45 +00001842 Remainder->pVal[i] =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001843 uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1844 }
1845 }
1846
1847 // Clean up the memory we allocated.
Reid Spencer522ca7c2007-02-25 01:56:07 +00001848 if (U != &SPACE[0]) {
1849 delete [] U;
1850 delete [] V;
1851 delete [] Q;
1852 delete [] R;
1853 }
Reid Spencer100502d2007-02-17 03:16:00 +00001854}
1855
Reid Spencer1d072122007-02-16 22:36:51 +00001856APInt APInt::udiv(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +00001857 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer39867762007-02-17 02:07:07 +00001858
1859 // First, deal with the easy case
1860 if (isSingleWord()) {
1861 assert(RHS.VAL != 0 && "Divide by zero?");
1862 return APInt(BitWidth, VAL / RHS.VAL);
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001863 }
Reid Spencer39867762007-02-17 02:07:07 +00001864
Reid Spencer39867762007-02-17 02:07:07 +00001865 // Get some facts about the LHS and RHS number of bits and words
Chris Lattner77527f52009-01-21 18:09:24 +00001866 unsigned rhsBits = RHS.getActiveBits();
1867 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001868 assert(rhsWords && "Divided by zero???");
Chris Lattner77527f52009-01-21 18:09:24 +00001869 unsigned lhsBits = this->getActiveBits();
1870 unsigned lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001871
1872 // Deal with some degenerate cases
Eric Christopher820256b2009-08-21 04:06:45 +00001873 if (!lhsWords)
Reid Spencer58a6a432007-02-21 08:21:52 +00001874 // 0 / X ===> 0
Eric Christopher820256b2009-08-21 04:06:45 +00001875 return APInt(BitWidth, 0);
Reid Spencer58a6a432007-02-21 08:21:52 +00001876 else if (lhsWords < rhsWords || this->ult(RHS)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001877 // X / Y ===> 0, iff X < Y
Reid Spencer58a6a432007-02-21 08:21:52 +00001878 return APInt(BitWidth, 0);
1879 } else if (*this == RHS) {
1880 // X / X ===> 1
1881 return APInt(BitWidth, 1);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001882 } else if (lhsWords == 1 && rhsWords == 1) {
Reid Spencer39867762007-02-17 02:07:07 +00001883 // All high words are zero, just use native divide
Reid Spencer58a6a432007-02-21 08:21:52 +00001884 return APInt(BitWidth, this->pVal[0] / RHS.pVal[0]);
Reid Spencer39867762007-02-17 02:07:07 +00001885 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001886
1887 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1888 APInt Quotient(1,0); // to hold result.
Craig Topperc10719f2014-04-07 04:17:22 +00001889 divide(*this, lhsWords, RHS, rhsWords, &Quotient, nullptr);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001890 return Quotient;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001891}
1892
Jakub Staszak6605c602013-02-20 00:17:42 +00001893APInt APInt::sdiv(const APInt &RHS) const {
1894 if (isNegative()) {
1895 if (RHS.isNegative())
1896 return (-(*this)).udiv(-RHS);
1897 return -((-(*this)).udiv(RHS));
1898 }
1899 if (RHS.isNegative())
1900 return -(this->udiv(-RHS));
1901 return this->udiv(RHS);
1902}
1903
Reid Spencer1d072122007-02-16 22:36:51 +00001904APInt APInt::urem(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +00001905 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer39867762007-02-17 02:07:07 +00001906 if (isSingleWord()) {
1907 assert(RHS.VAL != 0 && "Remainder by zero?");
1908 return APInt(BitWidth, VAL % RHS.VAL);
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001909 }
Reid Spencer39867762007-02-17 02:07:07 +00001910
Reid Spencer58a6a432007-02-21 08:21:52 +00001911 // Get some facts about the LHS
Chris Lattner77527f52009-01-21 18:09:24 +00001912 unsigned lhsBits = getActiveBits();
1913 unsigned lhsWords = !lhsBits ? 0 : (whichWord(lhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001914
1915 // Get some facts about the RHS
Chris Lattner77527f52009-01-21 18:09:24 +00001916 unsigned rhsBits = RHS.getActiveBits();
1917 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001918 assert(rhsWords && "Performing remainder operation by zero ???");
1919
Reid Spencer39867762007-02-17 02:07:07 +00001920 // Check the degenerate cases
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001921 if (lhsWords == 0) {
Reid Spencer58a6a432007-02-21 08:21:52 +00001922 // 0 % Y ===> 0
1923 return APInt(BitWidth, 0);
1924 } else if (lhsWords < rhsWords || this->ult(RHS)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001925 // X % Y ===> X, iff X < Y
Reid Spencer58a6a432007-02-21 08:21:52 +00001926 return *this;
1927 } else if (*this == RHS) {
Reid Spencer39867762007-02-17 02:07:07 +00001928 // X % X == 0;
Reid Spencer58a6a432007-02-21 08:21:52 +00001929 return APInt(BitWidth, 0);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001930 } else if (lhsWords == 1) {
Reid Spencer39867762007-02-17 02:07:07 +00001931 // All high words are zero, just use native remainder
Reid Spencer58a6a432007-02-21 08:21:52 +00001932 return APInt(BitWidth, pVal[0] % RHS.pVal[0]);
Reid Spencer39867762007-02-17 02:07:07 +00001933 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001934
Reid Spencer4c50b522007-05-13 23:44:59 +00001935 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001936 APInt Remainder(1,0);
Craig Topperc10719f2014-04-07 04:17:22 +00001937 divide(*this, lhsWords, RHS, rhsWords, nullptr, &Remainder);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001938 return Remainder;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001939}
Reid Spencer100502d2007-02-17 03:16:00 +00001940
Jakub Staszak6605c602013-02-20 00:17:42 +00001941APInt APInt::srem(const APInt &RHS) const {
1942 if (isNegative()) {
1943 if (RHS.isNegative())
1944 return -((-(*this)).urem(-RHS));
1945 return -((-(*this)).urem(RHS));
1946 }
1947 if (RHS.isNegative())
1948 return this->urem(-RHS);
1949 return this->urem(RHS);
1950}
1951
Eric Christopher820256b2009-08-21 04:06:45 +00001952void APInt::udivrem(const APInt &LHS, const APInt &RHS,
Reid Spencer4c50b522007-05-13 23:44:59 +00001953 APInt &Quotient, APInt &Remainder) {
David Majnemer7f039202014-12-14 09:41:56 +00001954 assert(LHS.BitWidth == RHS.BitWidth && "Bit widths must be the same");
1955
1956 // First, deal with the easy case
1957 if (LHS.isSingleWord()) {
1958 assert(RHS.VAL != 0 && "Divide by zero?");
1959 uint64_t QuotVal = LHS.VAL / RHS.VAL;
1960 uint64_t RemVal = LHS.VAL % RHS.VAL;
1961 Quotient = APInt(LHS.BitWidth, QuotVal);
1962 Remainder = APInt(LHS.BitWidth, RemVal);
1963 return;
1964 }
1965
Reid Spencer4c50b522007-05-13 23:44:59 +00001966 // Get some size facts about the dividend and divisor
Chris Lattner77527f52009-01-21 18:09:24 +00001967 unsigned lhsBits = LHS.getActiveBits();
1968 unsigned lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
1969 unsigned rhsBits = RHS.getActiveBits();
1970 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer4c50b522007-05-13 23:44:59 +00001971
1972 // Check the degenerate cases
Eric Christopher820256b2009-08-21 04:06:45 +00001973 if (lhsWords == 0) {
Reid Spencer4c50b522007-05-13 23:44:59 +00001974 Quotient = 0; // 0 / Y ===> 0
1975 Remainder = 0; // 0 % Y ===> 0
1976 return;
Eric Christopher820256b2009-08-21 04:06:45 +00001977 }
1978
1979 if (lhsWords < rhsWords || LHS.ult(RHS)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001980 Remainder = LHS; // X % Y ===> X, iff X < Y
1981 Quotient = 0; // X / Y ===> 0, iff X < Y
Reid Spencer4c50b522007-05-13 23:44:59 +00001982 return;
Eric Christopher820256b2009-08-21 04:06:45 +00001983 }
1984
Reid Spencer4c50b522007-05-13 23:44:59 +00001985 if (LHS == RHS) {
1986 Quotient = 1; // X / X ===> 1
1987 Remainder = 0; // X % X ===> 0;
1988 return;
Eric Christopher820256b2009-08-21 04:06:45 +00001989 }
1990
Reid Spencer4c50b522007-05-13 23:44:59 +00001991 if (lhsWords == 1 && rhsWords == 1) {
1992 // There is only one word to consider so use the native versions.
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001993 uint64_t lhsValue = LHS.isSingleWord() ? LHS.VAL : LHS.pVal[0];
1994 uint64_t rhsValue = RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
1995 Quotient = APInt(LHS.getBitWidth(), lhsValue / rhsValue);
1996 Remainder = APInt(LHS.getBitWidth(), lhsValue % rhsValue);
Reid Spencer4c50b522007-05-13 23:44:59 +00001997 return;
1998 }
1999
2000 // Okay, lets do it the long way
2001 divide(LHS, lhsWords, RHS, rhsWords, &Quotient, &Remainder);
2002}
2003
Jakub Staszak6605c602013-02-20 00:17:42 +00002004void APInt::sdivrem(const APInt &LHS, const APInt &RHS,
2005 APInt &Quotient, APInt &Remainder) {
2006 if (LHS.isNegative()) {
2007 if (RHS.isNegative())
2008 APInt::udivrem(-LHS, -RHS, Quotient, Remainder);
2009 else {
2010 APInt::udivrem(-LHS, RHS, Quotient, Remainder);
2011 Quotient = -Quotient;
2012 }
2013 Remainder = -Remainder;
2014 } else if (RHS.isNegative()) {
2015 APInt::udivrem(LHS, -RHS, Quotient, Remainder);
2016 Quotient = -Quotient;
2017 } else {
2018 APInt::udivrem(LHS, RHS, Quotient, Remainder);
2019 }
2020}
2021
Chris Lattner2c819b02010-10-13 23:54:10 +00002022APInt APInt::sadd_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00002023 APInt Res = *this+RHS;
2024 Overflow = isNonNegative() == RHS.isNonNegative() &&
2025 Res.isNonNegative() != isNonNegative();
2026 return Res;
2027}
2028
Chris Lattner698661c2010-10-14 00:05:07 +00002029APInt APInt::uadd_ov(const APInt &RHS, bool &Overflow) const {
2030 APInt Res = *this+RHS;
2031 Overflow = Res.ult(RHS);
2032 return Res;
2033}
2034
Chris Lattner2c819b02010-10-13 23:54:10 +00002035APInt APInt::ssub_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00002036 APInt Res = *this - RHS;
2037 Overflow = isNonNegative() != RHS.isNonNegative() &&
2038 Res.isNonNegative() != isNonNegative();
2039 return Res;
2040}
2041
Chris Lattner698661c2010-10-14 00:05:07 +00002042APInt APInt::usub_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattnerb9681ad2010-10-14 00:30:00 +00002043 APInt Res = *this-RHS;
2044 Overflow = Res.ugt(*this);
Chris Lattner698661c2010-10-14 00:05:07 +00002045 return Res;
2046}
2047
Chris Lattner2c819b02010-10-13 23:54:10 +00002048APInt APInt::sdiv_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00002049 // MININT/-1 --> overflow.
2050 Overflow = isMinSignedValue() && RHS.isAllOnesValue();
2051 return sdiv(RHS);
2052}
2053
Chris Lattner2c819b02010-10-13 23:54:10 +00002054APInt APInt::smul_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00002055 APInt Res = *this * RHS;
2056
2057 if (*this != 0 && RHS != 0)
2058 Overflow = Res.sdiv(RHS) != *this || Res.sdiv(*this) != RHS;
2059 else
2060 Overflow = false;
2061 return Res;
2062}
2063
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00002064APInt APInt::umul_ov(const APInt &RHS, bool &Overflow) const {
2065 APInt Res = *this * RHS;
2066
2067 if (*this != 0 && RHS != 0)
2068 Overflow = Res.udiv(RHS) != *this || Res.udiv(*this) != RHS;
2069 else
2070 Overflow = false;
2071 return Res;
2072}
2073
David Majnemera2521382014-10-13 21:48:30 +00002074APInt APInt::sshl_ov(const APInt &ShAmt, bool &Overflow) const {
2075 Overflow = ShAmt.uge(getBitWidth());
Chris Lattner79bdd882010-10-13 23:46:33 +00002076 if (Overflow)
David Majnemera2521382014-10-13 21:48:30 +00002077 return APInt(BitWidth, 0);
Chris Lattner79bdd882010-10-13 23:46:33 +00002078
2079 if (isNonNegative()) // Don't allow sign change.
David Majnemera2521382014-10-13 21:48:30 +00002080 Overflow = ShAmt.uge(countLeadingZeros());
Chris Lattner79bdd882010-10-13 23:46:33 +00002081 else
David Majnemera2521382014-10-13 21:48:30 +00002082 Overflow = ShAmt.uge(countLeadingOnes());
Chris Lattner79bdd882010-10-13 23:46:33 +00002083
2084 return *this << ShAmt;
2085}
2086
David Majnemera2521382014-10-13 21:48:30 +00002087APInt APInt::ushl_ov(const APInt &ShAmt, bool &Overflow) const {
2088 Overflow = ShAmt.uge(getBitWidth());
2089 if (Overflow)
2090 return APInt(BitWidth, 0);
2091
2092 Overflow = ShAmt.ugt(countLeadingZeros());
2093
2094 return *this << ShAmt;
2095}
2096
Chris Lattner79bdd882010-10-13 23:46:33 +00002097
2098
2099
Benjamin Kramer92d89982010-07-14 22:38:02 +00002100void APInt::fromString(unsigned numbits, StringRef str, uint8_t radix) {
Reid Spencer1ba83352007-02-21 03:55:44 +00002101 // Check our assumptions here
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00002102 assert(!str.empty() && "Invalid string length");
Douglas Gregor663c0682011-09-14 15:54:46 +00002103 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 ||
2104 radix == 36) &&
2105 "Radix should be 2, 8, 10, 16, or 36!");
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00002106
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00002107 StringRef::iterator p = str.begin();
2108 size_t slen = str.size();
2109 bool isNeg = *p == '-';
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00002110 if (*p == '-' || *p == '+') {
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00002111 p++;
2112 slen--;
Eric Christopher43a1dec2009-08-21 04:10:31 +00002113 assert(slen && "String is only a sign, needs a value.");
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00002114 }
Chris Lattnerdad2d092007-05-03 18:15:36 +00002115 assert((slen <= numbits || radix != 2) && "Insufficient bit width");
Chris Lattnerb869a0a2009-04-25 18:34:04 +00002116 assert(((slen-1)*3 <= numbits || radix != 8) && "Insufficient bit width");
2117 assert(((slen-1)*4 <= numbits || radix != 16) && "Insufficient bit width");
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002118 assert((((slen-1)*64)/22 <= numbits || radix != 10) &&
2119 "Insufficient bit width");
Reid Spencer1ba83352007-02-21 03:55:44 +00002120
2121 // Allocate memory
2122 if (!isSingleWord())
2123 pVal = getClearedMemory(getNumWords());
2124
2125 // Figure out if we can shift instead of multiply
Chris Lattner77527f52009-01-21 18:09:24 +00002126 unsigned shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0);
Reid Spencer1ba83352007-02-21 03:55:44 +00002127
2128 // Set up an APInt for the digit to add outside the loop so we don't
2129 // constantly construct/destruct it.
2130 APInt apdigit(getBitWidth(), 0);
2131 APInt apradix(getBitWidth(), radix);
2132
2133 // Enter digit traversal loop
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00002134 for (StringRef::iterator e = str.end(); p != e; ++p) {
Erick Tryzelaardadb15712009-08-21 03:15:28 +00002135 unsigned digit = getDigit(*p, radix);
Erick Tryzelaar60964092009-08-21 06:48:37 +00002136 assert(digit < radix && "Invalid character in digit string");
Reid Spencer1ba83352007-02-21 03:55:44 +00002137
Reid Spencera93c9812007-05-16 19:18:22 +00002138 // Shift or multiply the value by the radix
Chris Lattnerb869a0a2009-04-25 18:34:04 +00002139 if (slen > 1) {
2140 if (shift)
2141 *this <<= shift;
2142 else
2143 *this *= apradix;
2144 }
Reid Spencer1ba83352007-02-21 03:55:44 +00002145
2146 // Add in the digit we just interpreted
Reid Spencer632ebdf2007-02-24 20:19:37 +00002147 if (apdigit.isSingleWord())
2148 apdigit.VAL = digit;
2149 else
2150 apdigit.pVal[0] = digit;
Reid Spencer1ba83352007-02-21 03:55:44 +00002151 *this += apdigit;
Reid Spencer100502d2007-02-17 03:16:00 +00002152 }
Reid Spencerb6b5cc32007-02-25 23:44:53 +00002153 // If its negative, put it in two's complement form
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00002154 if (isNeg) {
Jakub Staszak773be0c2013-03-20 23:56:19 +00002155 --(*this);
Jay Foad25a5e4c2010-12-01 08:53:58 +00002156 this->flipAllBits();
Reid Spencerb6b5cc32007-02-25 23:44:53 +00002157 }
Reid Spencer100502d2007-02-17 03:16:00 +00002158}
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002159
Chris Lattner17f71652008-08-17 07:19:36 +00002160void APInt::toString(SmallVectorImpl<char> &Str, unsigned Radix,
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002161 bool Signed, bool formatAsCLiteral) const {
Douglas Gregor663c0682011-09-14 15:54:46 +00002162 assert((Radix == 10 || Radix == 8 || Radix == 16 || Radix == 2 ||
2163 Radix == 36) &&
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00002164 "Radix should be 2, 8, 10, 16, or 36!");
Eric Christopher820256b2009-08-21 04:06:45 +00002165
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002166 const char *Prefix = "";
2167 if (formatAsCLiteral) {
2168 switch (Radix) {
2169 case 2:
2170 // Binary literals are a non-standard extension added in gcc 4.3:
2171 // http://gcc.gnu.org/onlinedocs/gcc-4.3.0/gcc/Binary-constants.html
2172 Prefix = "0b";
2173 break;
2174 case 8:
2175 Prefix = "0";
2176 break;
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00002177 case 10:
2178 break; // No prefix
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002179 case 16:
2180 Prefix = "0x";
2181 break;
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00002182 default:
2183 llvm_unreachable("Invalid radix!");
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002184 }
2185 }
2186
Chris Lattner17f71652008-08-17 07:19:36 +00002187 // First, check for a zero value and just short circuit the logic below.
2188 if (*this == 0) {
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002189 while (*Prefix) {
2190 Str.push_back(*Prefix);
2191 ++Prefix;
2192 };
Chris Lattner17f71652008-08-17 07:19:36 +00002193 Str.push_back('0');
2194 return;
2195 }
Eric Christopher820256b2009-08-21 04:06:45 +00002196
Douglas Gregor663c0682011-09-14 15:54:46 +00002197 static const char Digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Eric Christopher820256b2009-08-21 04:06:45 +00002198
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002199 if (isSingleWord()) {
Chris Lattner17f71652008-08-17 07:19:36 +00002200 char Buffer[65];
2201 char *BufPtr = Buffer+65;
Eric Christopher820256b2009-08-21 04:06:45 +00002202
Chris Lattner17f71652008-08-17 07:19:36 +00002203 uint64_t N;
Chris Lattnerb91c9032010-08-18 00:33:47 +00002204 if (!Signed) {
Chris Lattner17f71652008-08-17 07:19:36 +00002205 N = getZExtValue();
Chris Lattnerb91c9032010-08-18 00:33:47 +00002206 } else {
2207 int64_t I = getSExtValue();
2208 if (I >= 0) {
2209 N = I;
2210 } else {
2211 Str.push_back('-');
2212 N = -(uint64_t)I;
2213 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002214 }
Eric Christopher820256b2009-08-21 04:06:45 +00002215
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002216 while (*Prefix) {
2217 Str.push_back(*Prefix);
2218 ++Prefix;
2219 };
2220
Chris Lattner17f71652008-08-17 07:19:36 +00002221 while (N) {
2222 *--BufPtr = Digits[N % Radix];
2223 N /= Radix;
2224 }
2225 Str.append(BufPtr, Buffer+65);
2226 return;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002227 }
2228
Chris Lattner17f71652008-08-17 07:19:36 +00002229 APInt Tmp(*this);
Eric Christopher820256b2009-08-21 04:06:45 +00002230
Chris Lattner17f71652008-08-17 07:19:36 +00002231 if (Signed && isNegative()) {
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002232 // They want to print the signed version and it is a negative value
2233 // Flip the bits and add one to turn it into the equivalent positive
2234 // value and put a '-' in the result.
Jay Foad25a5e4c2010-12-01 08:53:58 +00002235 Tmp.flipAllBits();
Jakub Staszak773be0c2013-03-20 23:56:19 +00002236 ++Tmp;
Chris Lattner17f71652008-08-17 07:19:36 +00002237 Str.push_back('-');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002238 }
Eric Christopher820256b2009-08-21 04:06:45 +00002239
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002240 while (*Prefix) {
2241 Str.push_back(*Prefix);
2242 ++Prefix;
2243 };
2244
Chris Lattner17f71652008-08-17 07:19:36 +00002245 // We insert the digits backward, then reverse them to get the right order.
2246 unsigned StartDig = Str.size();
Eric Christopher820256b2009-08-21 04:06:45 +00002247
2248 // For the 2, 8 and 16 bit cases, we can just shift instead of divide
2249 // because the number of bits per digit (1, 3 and 4 respectively) divides
Chris Lattner17f71652008-08-17 07:19:36 +00002250 // equaly. We just shift until the value is zero.
Douglas Gregor663c0682011-09-14 15:54:46 +00002251 if (Radix == 2 || Radix == 8 || Radix == 16) {
Chris Lattner17f71652008-08-17 07:19:36 +00002252 // Just shift tmp right for each digit width until it becomes zero
2253 unsigned ShiftAmt = (Radix == 16 ? 4 : (Radix == 8 ? 3 : 1));
2254 unsigned MaskAmt = Radix - 1;
Eric Christopher820256b2009-08-21 04:06:45 +00002255
Chris Lattner17f71652008-08-17 07:19:36 +00002256 while (Tmp != 0) {
2257 unsigned Digit = unsigned(Tmp.getRawData()[0]) & MaskAmt;
2258 Str.push_back(Digits[Digit]);
2259 Tmp = Tmp.lshr(ShiftAmt);
2260 }
2261 } else {
Douglas Gregor663c0682011-09-14 15:54:46 +00002262 APInt divisor(Radix == 10? 4 : 8, Radix);
Chris Lattner17f71652008-08-17 07:19:36 +00002263 while (Tmp != 0) {
2264 APInt APdigit(1, 0);
2265 APInt tmp2(Tmp.getBitWidth(), 0);
Eric Christopher820256b2009-08-21 04:06:45 +00002266 divide(Tmp, Tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2,
Chris Lattner17f71652008-08-17 07:19:36 +00002267 &APdigit);
Chris Lattner77527f52009-01-21 18:09:24 +00002268 unsigned Digit = (unsigned)APdigit.getZExtValue();
Chris Lattner17f71652008-08-17 07:19:36 +00002269 assert(Digit < Radix && "divide failed");
2270 Str.push_back(Digits[Digit]);
2271 Tmp = tmp2;
2272 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002273 }
Eric Christopher820256b2009-08-21 04:06:45 +00002274
Chris Lattner17f71652008-08-17 07:19:36 +00002275 // Reverse the digits before returning.
2276 std::reverse(Str.begin()+StartDig, Str.end());
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002277}
2278
Chris Lattner17f71652008-08-17 07:19:36 +00002279/// toString - This returns the APInt as a std::string. Note that this is an
2280/// inefficient method. It is better to pass in a SmallVector/SmallString
2281/// to the methods above.
2282std::string APInt::toString(unsigned Radix = 10, bool Signed = true) const {
2283 SmallString<40> S;
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002284 toString(S, Radix, Signed, /* formatAsCLiteral = */false);
Daniel Dunbar8b0b1152009-08-19 20:07:03 +00002285 return S.str();
Reid Spencer1ba83352007-02-21 03:55:44 +00002286}
Chris Lattner6b695682007-08-16 15:56:55 +00002287
Chris Lattner17f71652008-08-17 07:19:36 +00002288
2289void APInt::dump() const {
2290 SmallString<40> S, U;
2291 this->toStringUnsigned(U);
2292 this->toStringSigned(S);
David Greenef32fcb42010-01-05 01:28:52 +00002293 dbgs() << "APInt(" << BitWidth << "b, "
Yaron Keren09fb7c62015-03-10 07:33:23 +00002294 << U << "u " << S << "s)";
Chris Lattner17f71652008-08-17 07:19:36 +00002295}
2296
Chris Lattner0c19df42008-08-23 22:23:09 +00002297void APInt::print(raw_ostream &OS, bool isSigned) const {
Chris Lattner17f71652008-08-17 07:19:36 +00002298 SmallString<40> S;
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002299 this->toString(S, 10, isSigned, /* formatAsCLiteral = */false);
Daniel Dunbar8b0b1152009-08-19 20:07:03 +00002300 OS << S.str();
Chris Lattner17f71652008-08-17 07:19:36 +00002301}
2302
Chris Lattner6b695682007-08-16 15:56:55 +00002303// This implements a variety of operations on a representation of
2304// arbitrary precision, two's-complement, bignum integer values.
2305
Chris Lattner96cffa62009-08-23 23:11:28 +00002306// Assumed by lowHalf, highHalf, partMSB and partLSB. A fairly safe
2307// and unrestricting assumption.
Benjamin Kramer7000ca32014-10-12 17:56:40 +00002308static_assert(integerPartWidth % 2 == 0, "Part width must be divisible by 2!");
Chris Lattner6b695682007-08-16 15:56:55 +00002309
2310/* Some handy functions local to this file. */
2311namespace {
2312
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002313 /* Returns the integer part with the least significant BITS set.
2314 BITS cannot be zero. */
Dan Gohmanf4bc7822008-04-10 21:11:47 +00002315 static inline integerPart
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002316 lowBitMask(unsigned int bits)
2317 {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002318 assert(bits != 0 && bits <= integerPartWidth);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002319
2320 return ~(integerPart) 0 >> (integerPartWidth - bits);
2321 }
2322
Neil Boothc8b650a2007-10-06 00:43:45 +00002323 /* Returns the value of the lower half of PART. */
Dan Gohmanf4bc7822008-04-10 21:11:47 +00002324 static inline integerPart
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002325 lowHalf(integerPart part)
2326 {
2327 return part & lowBitMask(integerPartWidth / 2);
2328 }
2329
Neil Boothc8b650a2007-10-06 00:43:45 +00002330 /* Returns the value of the upper half of PART. */
Dan Gohmanf4bc7822008-04-10 21:11:47 +00002331 static inline integerPart
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002332 highHalf(integerPart part)
2333 {
2334 return part >> (integerPartWidth / 2);
2335 }
2336
Neil Boothc8b650a2007-10-06 00:43:45 +00002337 /* Returns the bit number of the most significant set bit of a part.
2338 If the input number has no bits set -1U is returned. */
Dan Gohmanf4bc7822008-04-10 21:11:47 +00002339 static unsigned int
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002340 partMSB(integerPart value)
Chris Lattner6b695682007-08-16 15:56:55 +00002341 {
Benjamin Kramerb565f892013-06-01 11:26:39 +00002342 return findLastSet(value, ZB_Max);
Chris Lattner6b695682007-08-16 15:56:55 +00002343 }
2344
Neil Boothc8b650a2007-10-06 00:43:45 +00002345 /* Returns the bit number of the least significant set bit of a
2346 part. If the input number has no bits set -1U is returned. */
Dan Gohmanf4bc7822008-04-10 21:11:47 +00002347 static unsigned int
Chris Lattner6b695682007-08-16 15:56:55 +00002348 partLSB(integerPart value)
2349 {
Benjamin Kramerb565f892013-06-01 11:26:39 +00002350 return findFirstSet(value, ZB_Max);
Chris Lattner6b695682007-08-16 15:56:55 +00002351 }
2352}
2353
2354/* Sets the least significant part of a bignum to the input value, and
2355 zeroes out higher parts. */
2356void
2357APInt::tcSet(integerPart *dst, integerPart part, unsigned int parts)
2358{
2359 unsigned int i;
2360
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002361 assert(parts > 0);
Neil Boothb6182162007-10-08 13:47:12 +00002362
Chris Lattner6b695682007-08-16 15:56:55 +00002363 dst[0] = part;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002364 for (i = 1; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002365 dst[i] = 0;
2366}
2367
2368/* Assign one bignum to another. */
2369void
2370APInt::tcAssign(integerPart *dst, const integerPart *src, unsigned int parts)
2371{
2372 unsigned int i;
2373
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002374 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002375 dst[i] = src[i];
2376}
2377
2378/* Returns true if a bignum is zero, false otherwise. */
2379bool
2380APInt::tcIsZero(const integerPart *src, unsigned int parts)
2381{
2382 unsigned int i;
2383
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002384 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002385 if (src[i])
2386 return false;
2387
2388 return true;
2389}
2390
2391/* Extract the given bit of a bignum; returns 0 or 1. */
2392int
2393APInt::tcExtractBit(const integerPart *parts, unsigned int bit)
2394{
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002395 return (parts[bit / integerPartWidth] &
2396 ((integerPart) 1 << bit % integerPartWidth)) != 0;
Chris Lattner6b695682007-08-16 15:56:55 +00002397}
2398
John McCalldcb9a7a2010-02-28 02:51:25 +00002399/* Set the given bit of a bignum. */
Chris Lattner6b695682007-08-16 15:56:55 +00002400void
2401APInt::tcSetBit(integerPart *parts, unsigned int bit)
2402{
2403 parts[bit / integerPartWidth] |= (integerPart) 1 << (bit % integerPartWidth);
2404}
2405
John McCalldcb9a7a2010-02-28 02:51:25 +00002406/* Clears the given bit of a bignum. */
2407void
2408APInt::tcClearBit(integerPart *parts, unsigned int bit)
2409{
2410 parts[bit / integerPartWidth] &=
2411 ~((integerPart) 1 << (bit % integerPartWidth));
2412}
2413
Neil Boothc8b650a2007-10-06 00:43:45 +00002414/* Returns the bit number of the least significant set bit of a
2415 number. If the input number has no bits set -1U is returned. */
Chris Lattner6b695682007-08-16 15:56:55 +00002416unsigned int
2417APInt::tcLSB(const integerPart *parts, unsigned int n)
2418{
2419 unsigned int i, lsb;
2420
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002421 for (i = 0; i < n; i++) {
Chris Lattner6b695682007-08-16 15:56:55 +00002422 if (parts[i] != 0) {
2423 lsb = partLSB(parts[i]);
2424
2425 return lsb + i * integerPartWidth;
2426 }
2427 }
2428
2429 return -1U;
2430}
2431
Neil Boothc8b650a2007-10-06 00:43:45 +00002432/* Returns the bit number of the most significant set bit of a number.
2433 If the input number has no bits set -1U is returned. */
Chris Lattner6b695682007-08-16 15:56:55 +00002434unsigned int
2435APInt::tcMSB(const integerPart *parts, unsigned int n)
2436{
2437 unsigned int msb;
2438
2439 do {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002440 --n;
Chris Lattner6b695682007-08-16 15:56:55 +00002441
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002442 if (parts[n] != 0) {
2443 msb = partMSB(parts[n]);
Chris Lattner6b695682007-08-16 15:56:55 +00002444
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002445 return msb + n * integerPartWidth;
2446 }
Chris Lattner6b695682007-08-16 15:56:55 +00002447 } while (n);
2448
2449 return -1U;
2450}
2451
Neil Boothb6182162007-10-08 13:47:12 +00002452/* Copy the bit vector of width srcBITS from SRC, starting at bit
2453 srcLSB, to DST, of dstCOUNT parts, such that the bit srcLSB becomes
2454 the least significant bit of DST. All high bits above srcBITS in
2455 DST are zero-filled. */
2456void
Evan Chengdb338f32009-05-21 23:47:47 +00002457APInt::tcExtract(integerPart *dst, unsigned int dstCount,const integerPart *src,
Neil Boothb6182162007-10-08 13:47:12 +00002458 unsigned int srcBits, unsigned int srcLSB)
2459{
2460 unsigned int firstSrcPart, dstParts, shift, n;
2461
2462 dstParts = (srcBits + integerPartWidth - 1) / integerPartWidth;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002463 assert(dstParts <= dstCount);
Neil Boothb6182162007-10-08 13:47:12 +00002464
2465 firstSrcPart = srcLSB / integerPartWidth;
2466 tcAssign (dst, src + firstSrcPart, dstParts);
2467
2468 shift = srcLSB % integerPartWidth;
2469 tcShiftRight (dst, dstParts, shift);
2470
2471 /* We now have (dstParts * integerPartWidth - shift) bits from SRC
2472 in DST. If this is less that srcBits, append the rest, else
2473 clear the high bits. */
2474 n = dstParts * integerPartWidth - shift;
2475 if (n < srcBits) {
2476 integerPart mask = lowBitMask (srcBits - n);
2477 dst[dstParts - 1] |= ((src[firstSrcPart + dstParts] & mask)
2478 << n % integerPartWidth);
2479 } else if (n > srcBits) {
Neil Booth7e74b172007-10-12 15:31:31 +00002480 if (srcBits % integerPartWidth)
2481 dst[dstParts - 1] &= lowBitMask (srcBits % integerPartWidth);
Neil Boothb6182162007-10-08 13:47:12 +00002482 }
2483
2484 /* Clear high parts. */
2485 while (dstParts < dstCount)
2486 dst[dstParts++] = 0;
2487}
2488
Chris Lattner6b695682007-08-16 15:56:55 +00002489/* DST += RHS + C where C is zero or one. Returns the carry flag. */
2490integerPart
2491APInt::tcAdd(integerPart *dst, const integerPart *rhs,
2492 integerPart c, unsigned int parts)
2493{
2494 unsigned int i;
2495
2496 assert(c <= 1);
2497
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002498 for (i = 0; i < parts; i++) {
Chris Lattner6b695682007-08-16 15:56:55 +00002499 integerPart l;
2500
2501 l = dst[i];
2502 if (c) {
2503 dst[i] += rhs[i] + 1;
2504 c = (dst[i] <= l);
2505 } else {
2506 dst[i] += rhs[i];
2507 c = (dst[i] < l);
2508 }
2509 }
2510
2511 return c;
2512}
2513
2514/* DST -= RHS + C where C is zero or one. Returns the carry flag. */
2515integerPart
2516APInt::tcSubtract(integerPart *dst, const integerPart *rhs,
2517 integerPart c, unsigned int parts)
2518{
2519 unsigned int i;
2520
2521 assert(c <= 1);
2522
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002523 for (i = 0; i < parts; i++) {
Chris Lattner6b695682007-08-16 15:56:55 +00002524 integerPart l;
2525
2526 l = dst[i];
2527 if (c) {
2528 dst[i] -= rhs[i] + 1;
2529 c = (dst[i] >= l);
2530 } else {
2531 dst[i] -= rhs[i];
2532 c = (dst[i] > l);
2533 }
2534 }
2535
2536 return c;
2537}
2538
2539/* Negate a bignum in-place. */
2540void
2541APInt::tcNegate(integerPart *dst, unsigned int parts)
2542{
2543 tcComplement(dst, parts);
2544 tcIncrement(dst, parts);
2545}
2546
Neil Boothc8b650a2007-10-06 00:43:45 +00002547/* DST += SRC * MULTIPLIER + CARRY if add is true
2548 DST = SRC * MULTIPLIER + CARRY if add is false
Chris Lattner6b695682007-08-16 15:56:55 +00002549
2550 Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC
2551 they must start at the same point, i.e. DST == SRC.
2552
2553 If DSTPARTS == SRCPARTS + 1 no overflow occurs and zero is
2554 returned. Otherwise DST is filled with the least significant
2555 DSTPARTS parts of the result, and if all of the omitted higher
2556 parts were zero return zero, otherwise overflow occurred and
2557 return one. */
2558int
2559APInt::tcMultiplyPart(integerPart *dst, const integerPart *src,
2560 integerPart multiplier, integerPart carry,
2561 unsigned int srcParts, unsigned int dstParts,
2562 bool add)
2563{
2564 unsigned int i, n;
2565
2566 /* Otherwise our writes of DST kill our later reads of SRC. */
2567 assert(dst <= src || dst >= src + srcParts);
2568 assert(dstParts <= srcParts + 1);
2569
2570 /* N loops; minimum of dstParts and srcParts. */
2571 n = dstParts < srcParts ? dstParts: srcParts;
2572
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002573 for (i = 0; i < n; i++) {
Chris Lattner6b695682007-08-16 15:56:55 +00002574 integerPart low, mid, high, srcPart;
2575
2576 /* [ LOW, HIGH ] = MULTIPLIER * SRC[i] + DST[i] + CARRY.
2577
2578 This cannot overflow, because
2579
2580 (n - 1) * (n - 1) + 2 (n - 1) = (n - 1) * (n + 1)
2581
2582 which is less than n^2. */
2583
2584 srcPart = src[i];
2585
2586 if (multiplier == 0 || srcPart == 0) {
2587 low = carry;
2588 high = 0;
2589 } else {
2590 low = lowHalf(srcPart) * lowHalf(multiplier);
2591 high = highHalf(srcPart) * highHalf(multiplier);
2592
2593 mid = lowHalf(srcPart) * highHalf(multiplier);
2594 high += highHalf(mid);
2595 mid <<= integerPartWidth / 2;
2596 if (low + mid < low)
2597 high++;
2598 low += mid;
2599
2600 mid = highHalf(srcPart) * lowHalf(multiplier);
2601 high += highHalf(mid);
2602 mid <<= integerPartWidth / 2;
2603 if (low + mid < low)
2604 high++;
2605 low += mid;
2606
2607 /* Now add carry. */
2608 if (low + carry < low)
2609 high++;
2610 low += carry;
2611 }
2612
2613 if (add) {
2614 /* And now DST[i], and store the new low part there. */
2615 if (low + dst[i] < low)
2616 high++;
2617 dst[i] += low;
2618 } else
2619 dst[i] = low;
2620
2621 carry = high;
2622 }
2623
2624 if (i < dstParts) {
2625 /* Full multiplication, there is no overflow. */
2626 assert(i + 1 == dstParts);
2627 dst[i] = carry;
2628 return 0;
2629 } else {
2630 /* We overflowed if there is carry. */
2631 if (carry)
2632 return 1;
2633
2634 /* We would overflow if any significant unwritten parts would be
2635 non-zero. This is true if any remaining src parts are non-zero
2636 and the multiplier is non-zero. */
2637 if (multiplier)
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002638 for (; i < srcParts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002639 if (src[i])
2640 return 1;
2641
2642 /* We fitted in the narrow destination. */
2643 return 0;
2644 }
2645}
2646
2647/* DST = LHS * RHS, where DST has the same width as the operands and
2648 is filled with the least significant parts of the result. Returns
2649 one if overflow occurred, otherwise zero. DST must be disjoint
2650 from both operands. */
2651int
2652APInt::tcMultiply(integerPart *dst, const integerPart *lhs,
2653 const integerPart *rhs, unsigned int parts)
2654{
2655 unsigned int i;
2656 int overflow;
2657
2658 assert(dst != lhs && dst != rhs);
2659
2660 overflow = 0;
2661 tcSet(dst, 0, parts);
2662
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002663 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002664 overflow |= tcMultiplyPart(&dst[i], lhs, rhs[i], 0, parts,
2665 parts - i, true);
2666
2667 return overflow;
2668}
2669
Neil Booth0ea72a92007-10-06 00:24:48 +00002670/* DST = LHS * RHS, where DST has width the sum of the widths of the
2671 operands. No overflow occurs. DST must be disjoint from both
2672 operands. Returns the number of parts required to hold the
2673 result. */
2674unsigned int
Chris Lattner6b695682007-08-16 15:56:55 +00002675APInt::tcFullMultiply(integerPart *dst, const integerPart *lhs,
Neil Booth0ea72a92007-10-06 00:24:48 +00002676 const integerPart *rhs, unsigned int lhsParts,
2677 unsigned int rhsParts)
Chris Lattner6b695682007-08-16 15:56:55 +00002678{
Neil Booth0ea72a92007-10-06 00:24:48 +00002679 /* Put the narrower number on the LHS for less loops below. */
2680 if (lhsParts > rhsParts) {
2681 return tcFullMultiply (dst, rhs, lhs, rhsParts, lhsParts);
2682 } else {
2683 unsigned int n;
Chris Lattner6b695682007-08-16 15:56:55 +00002684
Neil Booth0ea72a92007-10-06 00:24:48 +00002685 assert(dst != lhs && dst != rhs);
Chris Lattner6b695682007-08-16 15:56:55 +00002686
Neil Booth0ea72a92007-10-06 00:24:48 +00002687 tcSet(dst, 0, rhsParts);
Chris Lattner6b695682007-08-16 15:56:55 +00002688
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002689 for (n = 0; n < lhsParts; n++)
Neil Booth0ea72a92007-10-06 00:24:48 +00002690 tcMultiplyPart(&dst[n], rhs, lhs[n], 0, rhsParts, rhsParts + 1, true);
Chris Lattner6b695682007-08-16 15:56:55 +00002691
Neil Booth0ea72a92007-10-06 00:24:48 +00002692 n = lhsParts + rhsParts;
2693
2694 return n - (dst[n - 1] == 0);
2695 }
Chris Lattner6b695682007-08-16 15:56:55 +00002696}
2697
2698/* If RHS is zero LHS and REMAINDER are left unchanged, return one.
2699 Otherwise set LHS to LHS / RHS with the fractional part discarded,
2700 set REMAINDER to the remainder, return zero. i.e.
2701
2702 OLD_LHS = RHS * LHS + REMAINDER
2703
2704 SCRATCH is a bignum of the same size as the operands and result for
2705 use by the routine; its contents need not be initialized and are
2706 destroyed. LHS, REMAINDER and SCRATCH must be distinct.
2707*/
2708int
2709APInt::tcDivide(integerPart *lhs, const integerPart *rhs,
2710 integerPart *remainder, integerPart *srhs,
2711 unsigned int parts)
2712{
2713 unsigned int n, shiftCount;
2714 integerPart mask;
2715
2716 assert(lhs != remainder && lhs != srhs && remainder != srhs);
2717
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002718 shiftCount = tcMSB(rhs, parts) + 1;
2719 if (shiftCount == 0)
Chris Lattner6b695682007-08-16 15:56:55 +00002720 return true;
2721
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002722 shiftCount = parts * integerPartWidth - shiftCount;
Chris Lattner6b695682007-08-16 15:56:55 +00002723 n = shiftCount / integerPartWidth;
2724 mask = (integerPart) 1 << (shiftCount % integerPartWidth);
2725
2726 tcAssign(srhs, rhs, parts);
2727 tcShiftLeft(srhs, parts, shiftCount);
2728 tcAssign(remainder, lhs, parts);
2729 tcSet(lhs, 0, parts);
2730
2731 /* Loop, subtracting SRHS if REMAINDER is greater and adding that to
2732 the total. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002733 for (;;) {
Chris Lattner6b695682007-08-16 15:56:55 +00002734 int compare;
2735
2736 compare = tcCompare(remainder, srhs, parts);
2737 if (compare >= 0) {
2738 tcSubtract(remainder, srhs, 0, parts);
2739 lhs[n] |= mask;
2740 }
2741
2742 if (shiftCount == 0)
2743 break;
2744 shiftCount--;
2745 tcShiftRight(srhs, parts, 1);
2746 if ((mask >>= 1) == 0)
2747 mask = (integerPart) 1 << (integerPartWidth - 1), n--;
2748 }
2749
2750 return false;
2751}
2752
2753/* Shift a bignum left COUNT bits in-place. Shifted in bits are zero.
2754 There are no restrictions on COUNT. */
2755void
2756APInt::tcShiftLeft(integerPart *dst, unsigned int parts, unsigned int count)
2757{
Neil Boothb6182162007-10-08 13:47:12 +00002758 if (count) {
2759 unsigned int jump, shift;
Chris Lattner6b695682007-08-16 15:56:55 +00002760
Neil Boothb6182162007-10-08 13:47:12 +00002761 /* Jump is the inter-part jump; shift is is intra-part shift. */
2762 jump = count / integerPartWidth;
2763 shift = count % integerPartWidth;
Chris Lattner6b695682007-08-16 15:56:55 +00002764
Neil Boothb6182162007-10-08 13:47:12 +00002765 while (parts > jump) {
2766 integerPart part;
Chris Lattner6b695682007-08-16 15:56:55 +00002767
Neil Boothb6182162007-10-08 13:47:12 +00002768 parts--;
Chris Lattner6b695682007-08-16 15:56:55 +00002769
Neil Boothb6182162007-10-08 13:47:12 +00002770 /* dst[i] comes from the two parts src[i - jump] and, if we have
2771 an intra-part shift, src[i - jump - 1]. */
2772 part = dst[parts - jump];
2773 if (shift) {
2774 part <<= shift;
Chris Lattner6b695682007-08-16 15:56:55 +00002775 if (parts >= jump + 1)
2776 part |= dst[parts - jump - 1] >> (integerPartWidth - shift);
2777 }
2778
Neil Boothb6182162007-10-08 13:47:12 +00002779 dst[parts] = part;
2780 }
Chris Lattner6b695682007-08-16 15:56:55 +00002781
Neil Boothb6182162007-10-08 13:47:12 +00002782 while (parts > 0)
2783 dst[--parts] = 0;
2784 }
Chris Lattner6b695682007-08-16 15:56:55 +00002785}
2786
2787/* Shift a bignum right COUNT bits in-place. Shifted in bits are
2788 zero. There are no restrictions on COUNT. */
2789void
2790APInt::tcShiftRight(integerPart *dst, unsigned int parts, unsigned int count)
2791{
Neil Boothb6182162007-10-08 13:47:12 +00002792 if (count) {
2793 unsigned int i, jump, shift;
Chris Lattner6b695682007-08-16 15:56:55 +00002794
Neil Boothb6182162007-10-08 13:47:12 +00002795 /* Jump is the inter-part jump; shift is is intra-part shift. */
2796 jump = count / integerPartWidth;
2797 shift = count % integerPartWidth;
Chris Lattner6b695682007-08-16 15:56:55 +00002798
Neil Boothb6182162007-10-08 13:47:12 +00002799 /* Perform the shift. This leaves the most significant COUNT bits
2800 of the result at zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002801 for (i = 0; i < parts; i++) {
Neil Boothb6182162007-10-08 13:47:12 +00002802 integerPart part;
Chris Lattner6b695682007-08-16 15:56:55 +00002803
Neil Boothb6182162007-10-08 13:47:12 +00002804 if (i + jump >= parts) {
2805 part = 0;
2806 } else {
2807 part = dst[i + jump];
2808 if (shift) {
2809 part >>= shift;
2810 if (i + jump + 1 < parts)
2811 part |= dst[i + jump + 1] << (integerPartWidth - shift);
2812 }
Chris Lattner6b695682007-08-16 15:56:55 +00002813 }
Chris Lattner6b695682007-08-16 15:56:55 +00002814
Neil Boothb6182162007-10-08 13:47:12 +00002815 dst[i] = part;
2816 }
Chris Lattner6b695682007-08-16 15:56:55 +00002817 }
2818}
2819
2820/* Bitwise and of two bignums. */
2821void
2822APInt::tcAnd(integerPart *dst, const integerPart *rhs, unsigned int parts)
2823{
2824 unsigned int i;
2825
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002826 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002827 dst[i] &= rhs[i];
2828}
2829
2830/* Bitwise inclusive or of two bignums. */
2831void
2832APInt::tcOr(integerPart *dst, const integerPart *rhs, unsigned int parts)
2833{
2834 unsigned int i;
2835
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002836 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002837 dst[i] |= rhs[i];
2838}
2839
2840/* Bitwise exclusive or of two bignums. */
2841void
2842APInt::tcXor(integerPart *dst, const integerPart *rhs, unsigned int parts)
2843{
2844 unsigned int i;
2845
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002846 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002847 dst[i] ^= rhs[i];
2848}
2849
2850/* Complement a bignum in-place. */
2851void
2852APInt::tcComplement(integerPart *dst, unsigned int parts)
2853{
2854 unsigned int i;
2855
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002856 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002857 dst[i] = ~dst[i];
2858}
2859
2860/* Comparison (unsigned) of two bignums. */
2861int
2862APInt::tcCompare(const integerPart *lhs, const integerPart *rhs,
2863 unsigned int parts)
2864{
2865 while (parts) {
2866 parts--;
2867 if (lhs[parts] == rhs[parts])
2868 continue;
2869
2870 if (lhs[parts] > rhs[parts])
2871 return 1;
2872 else
2873 return -1;
2874 }
2875
2876 return 0;
2877}
2878
2879/* Increment a bignum in-place, return the carry flag. */
2880integerPart
2881APInt::tcIncrement(integerPart *dst, unsigned int parts)
2882{
2883 unsigned int i;
2884
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002885 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002886 if (++dst[i] != 0)
2887 break;
2888
2889 return i == parts;
2890}
2891
Michael Gottesman9d406f42013-05-28 19:50:20 +00002892/* Decrement a bignum in-place, return the borrow flag. */
2893integerPart
2894APInt::tcDecrement(integerPart *dst, unsigned int parts) {
2895 for (unsigned int i = 0; i < parts; i++) {
2896 // If the current word is non-zero, then the decrement has no effect on the
2897 // higher-order words of the integer and no borrow can occur. Exit early.
2898 if (dst[i]--)
2899 return 0;
2900 }
2901 // If every word was zero, then there is a borrow.
2902 return 1;
2903}
2904
2905
Chris Lattner6b695682007-08-16 15:56:55 +00002906/* Set the least significant BITS bits of a bignum, clear the
2907 rest. */
2908void
2909APInt::tcSetLeastSignificantBits(integerPart *dst, unsigned int parts,
2910 unsigned int bits)
2911{
2912 unsigned int i;
2913
2914 i = 0;
2915 while (bits > integerPartWidth) {
2916 dst[i++] = ~(integerPart) 0;
2917 bits -= integerPartWidth;
2918 }
2919
2920 if (bits)
2921 dst[i++] = ~(integerPart) 0 >> (integerPartWidth - bits);
2922
2923 while (i < parts)
2924 dst[i++] = 0;
2925}