blob: 367c75be1af61a6e667b90576b4dc5cd8baeebf1 [file] [log] [blame]
Zhou Shengfd43dcf2007-02-06 03:00:16 +00001//===-- APInt.cpp - Implement APInt class ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Shengfd43dcf2007-02-06 03:00:16 +00007//
8//===----------------------------------------------------------------------===//
9//
Reid Spencer5d0d05c2007-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 Shengfd43dcf2007-02-06 03:00:16 +000012//
13//===----------------------------------------------------------------------===//
14
Reid Spencer9d6c9192007-02-24 03:58:46 +000015#define DEBUG_TYPE "apint"
Zhou Shengfd43dcf2007-02-06 03:00:16 +000016#include "llvm/ADT/APInt.h"
Ted Kremeneke420deb2008-01-19 04:23:33 +000017#include "llvm/ADT/FoldingSet.h"
Chris Lattnerfad86b02008-08-17 07:19:36 +000018#include "llvm/ADT/SmallString.h"
Reid Spencer9d6c9192007-02-24 03:58:46 +000019#include "llvm/Support/Debug.h"
Zhou Shengfd43dcf2007-02-06 03:00:16 +000020#include "llvm/Support/MathExtras.h"
Chris Lattner944fac72008-08-23 22:23:09 +000021#include "llvm/Support/raw_ostream.h"
Chris Lattnerfad86b02008-08-17 07:19:36 +000022#include <cmath>
Jeff Cohen09dfd8e2007-03-20 20:42:36 +000023#include <limits>
Zhou Shenga3832fd2007-02-07 06:14:53 +000024#include <cstring>
Zhou Shengfd43dcf2007-02-06 03:00:16 +000025#include <cstdlib>
26using namespace llvm;
27
Reid Spencer5d0d05c2007-02-25 19:32:03 +000028/// A utility function for allocating memory, checking for allocation failures,
29/// and ensuring the contents are zeroed.
Chris Lattner455e9ab2009-01-21 18:09:24 +000030inline static uint64_t* getClearedMemory(unsigned numWords) {
Reid Spenceraf0e9562007-02-18 18:38:44 +000031 uint64_t * result = new uint64_t[numWords];
32 assert(result && "APInt memory allocation fails!");
33 memset(result, 0, numWords * sizeof(uint64_t));
34 return result;
Zhou Sheng353815d2007-02-06 06:04:53 +000035}
36
Reid Spencer5d0d05c2007-02-25 19:32:03 +000037/// A utility function for allocating memory and checking for allocation
38/// failure. The content is not zeroed.
Chris Lattner455e9ab2009-01-21 18:09:24 +000039inline static uint64_t* getMemory(unsigned numWords) {
Reid Spenceraf0e9562007-02-18 18:38:44 +000040 uint64_t * result = new uint64_t[numWords];
41 assert(result && "APInt memory allocation fails!");
42 return result;
43}
44
Chris Lattner455e9ab2009-01-21 18:09:24 +000045void APInt::initSlowCase(unsigned numBits, uint64_t val, bool isSigned) {
Chris Lattner98f8ccf2008-08-20 17:02:31 +000046 pVal = getClearedMemory(getNumWords());
47 pVal[0] = val;
48 if (isSigned && int64_t(val) < 0)
49 for (unsigned i = 1; i < getNumWords(); ++i)
50 pVal[i] = -1ULL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +000051}
52
Chris Lattner119c30b2008-10-11 22:07:19 +000053void APInt::initSlowCase(const APInt& that) {
54 pVal = getMemory(getNumWords());
55 memcpy(pVal, that.pVal, getNumWords() * APINT_WORD_SIZE);
56}
57
58
Chris Lattner455e9ab2009-01-21 18:09:24 +000059APInt::APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[])
Chris Lattner944fac72008-08-23 22:23:09 +000060 : BitWidth(numBits), VAL(0) {
Chris Lattner98f8ccf2008-08-20 17:02:31 +000061 assert(BitWidth && "bitwidth too small");
Zhou Shengfd43dcf2007-02-06 03:00:16 +000062 assert(bigVal && "Null pointer detected!");
63 if (isSingleWord())
Reid Spencer610fad82007-02-24 10:01:42 +000064 VAL = bigVal[0];
Zhou Shengfd43dcf2007-02-06 03:00:16 +000065 else {
Reid Spencer610fad82007-02-24 10:01:42 +000066 // Get memory, cleared to 0
67 pVal = getClearedMemory(getNumWords());
68 // Calculate the number of words to copy
Chris Lattner455e9ab2009-01-21 18:09:24 +000069 unsigned words = std::min<unsigned>(numWords, getNumWords());
Reid Spencer610fad82007-02-24 10:01:42 +000070 // Copy the words from bigVal to pVal
71 memcpy(pVal, bigVal, words * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +000072 }
Reid Spencer610fad82007-02-24 10:01:42 +000073 // Make sure unused high bits are cleared
74 clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +000075}
76
Chris Lattner455e9ab2009-01-21 18:09:24 +000077APInt::APInt(unsigned numbits, const char StrStart[], unsigned slen,
Reid Spencer9c0696f2007-02-20 08:51:03 +000078 uint8_t radix)
Reid Spencer385f7542007-02-21 03:55:44 +000079 : BitWidth(numbits), VAL(0) {
Chris Lattner98f8ccf2008-08-20 17:02:31 +000080 assert(BitWidth && "bitwidth too small");
Reid Spencere81d2da2007-02-16 22:36:51 +000081 fromString(numbits, StrStart, slen, radix);
Zhou Shenga3832fd2007-02-07 06:14:53 +000082}
83
Chris Lattner98f8ccf2008-08-20 17:02:31 +000084APInt& APInt::AssignSlowCase(const APInt& RHS) {
Reid Spencer9ac44112007-02-26 23:38:21 +000085 // Don't do anything for X = X
86 if (this == &RHS)
87 return *this;
88
Reid Spencer9ac44112007-02-26 23:38:21 +000089 if (BitWidth == RHS.getBitWidth()) {
Chris Lattner98f8ccf2008-08-20 17:02:31 +000090 // assume same bit-width single-word case is already handled
91 assert(!isSingleWord());
92 memcpy(pVal, RHS.pVal, getNumWords() * APINT_WORD_SIZE);
Reid Spencer9ac44112007-02-26 23:38:21 +000093 return *this;
94 }
95
Chris Lattner98f8ccf2008-08-20 17:02:31 +000096 if (isSingleWord()) {
97 // assume case where both are single words is already handled
98 assert(!RHS.isSingleWord());
99 VAL = 0;
100 pVal = getMemory(RHS.getNumWords());
101 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
102 } else if (getNumWords() == RHS.getNumWords())
Reid Spencer9ac44112007-02-26 23:38:21 +0000103 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
104 else if (RHS.isSingleWord()) {
105 delete [] pVal;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000106 VAL = RHS.VAL;
Reid Spencer9ac44112007-02-26 23:38:21 +0000107 } else {
108 delete [] pVal;
109 pVal = getMemory(RHS.getNumWords());
110 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
111 }
112 BitWidth = RHS.BitWidth;
113 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000114}
115
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000116APInt& APInt::operator=(uint64_t RHS) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000117 if (isSingleWord())
118 VAL = RHS;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000119 else {
120 pVal[0] = RHS;
Reid Spencera58f0582007-02-18 20:09:41 +0000121 memset(pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000122 }
Reid Spencer9ac44112007-02-26 23:38:21 +0000123 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000124}
125
Ted Kremeneke420deb2008-01-19 04:23:33 +0000126/// Profile - This method 'profiles' an APInt for use with FoldingSet.
127void APInt::Profile(FoldingSetNodeID& ID) const {
Ted Kremeneka795aca2008-02-19 20:50:41 +0000128 ID.AddInteger(BitWidth);
129
Ted Kremeneke420deb2008-01-19 04:23:33 +0000130 if (isSingleWord()) {
131 ID.AddInteger(VAL);
132 return;
133 }
134
Chris Lattner455e9ab2009-01-21 18:09:24 +0000135 unsigned NumWords = getNumWords();
Ted Kremeneke420deb2008-01-19 04:23:33 +0000136 for (unsigned i = 0; i < NumWords; ++i)
137 ID.AddInteger(pVal[i]);
138}
139
Reid Spenceraf0e9562007-02-18 18:38:44 +0000140/// add_1 - This function adds a single "digit" integer, y, to the multiple
141/// "digit" integer array, x[]. x[] is modified to reflect the addition and
142/// 1 is returned if there is a carry out, otherwise 0 is returned.
Reid Spencer5e0a8512007-02-17 03:16:00 +0000143/// @returns the carry of the addition.
Chris Lattner455e9ab2009-01-21 18:09:24 +0000144static bool add_1(uint64_t dest[], uint64_t x[], unsigned len, uint64_t y) {
145 for (unsigned i = 0; i < len; ++i) {
Reid Spencerf2c521c2007-02-18 06:39:42 +0000146 dest[i] = y + x[i];
147 if (dest[i] < y)
Reid Spencer610fad82007-02-24 10:01:42 +0000148 y = 1; // Carry one to next digit.
Reid Spencerf2c521c2007-02-18 06:39:42 +0000149 else {
Reid Spencer610fad82007-02-24 10:01:42 +0000150 y = 0; // No need to carry so exit early
Reid Spencerf2c521c2007-02-18 06:39:42 +0000151 break;
152 }
Reid Spencer5e0a8512007-02-17 03:16:00 +0000153 }
Reid Spencerf2c521c2007-02-18 06:39:42 +0000154 return y;
Reid Spencer5e0a8512007-02-17 03:16:00 +0000155}
156
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000157/// @brief Prefix increment operator. Increments the APInt by one.
158APInt& APInt::operator++() {
Reid Spencere81d2da2007-02-16 22:36:51 +0000159 if (isSingleWord())
160 ++VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000161 else
Zhou Shenga3832fd2007-02-07 06:14:53 +0000162 add_1(pVal, pVal, getNumWords(), 1);
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000163 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000164}
165
Reid Spenceraf0e9562007-02-18 18:38:44 +0000166/// sub_1 - This function subtracts a single "digit" (64-bit word), y, from
167/// the multi-digit integer array, x[], propagating the borrowed 1 value until
168/// no further borrowing is neeeded or it runs out of "digits" in x. The result
169/// is 1 if "borrowing" exhausted the digits in x, or 0 if x was not exhausted.
170/// In other words, if y > x then this function returns 1, otherwise 0.
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000171/// @returns the borrow out of the subtraction
Chris Lattner455e9ab2009-01-21 18:09:24 +0000172static bool sub_1(uint64_t x[], unsigned len, uint64_t y) {
173 for (unsigned i = 0; i < len; ++i) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000174 uint64_t X = x[i];
Reid Spencerf2c521c2007-02-18 06:39:42 +0000175 x[i] -= y;
176 if (y > X)
Reid Spenceraf0e9562007-02-18 18:38:44 +0000177 y = 1; // We have to "borrow 1" from next "digit"
Reid Spencer5e0a8512007-02-17 03:16:00 +0000178 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000179 y = 0; // No need to borrow
180 break; // Remaining digits are unchanged so exit early
Reid Spencer5e0a8512007-02-17 03:16:00 +0000181 }
182 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000183 return bool(y);
Reid Spencer5e0a8512007-02-17 03:16:00 +0000184}
185
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000186/// @brief Prefix decrement operator. Decrements the APInt by one.
187APInt& APInt::operator--() {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000188 if (isSingleWord())
189 --VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000190 else
Zhou Shenga3832fd2007-02-07 06:14:53 +0000191 sub_1(pVal, getNumWords(), 1);
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000192 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000193}
194
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000195/// add - This function adds the integer array x to the integer array Y and
196/// places the result in dest.
197/// @returns the carry out from the addition
198/// @brief General addition of 64-bit integer arrays
Reid Spencer9d6c9192007-02-24 03:58:46 +0000199static bool add(uint64_t *dest, const uint64_t *x, const uint64_t *y,
Chris Lattner455e9ab2009-01-21 18:09:24 +0000200 unsigned len) {
Reid Spencer9d6c9192007-02-24 03:58:46 +0000201 bool carry = false;
Chris Lattner455e9ab2009-01-21 18:09:24 +0000202 for (unsigned i = 0; i< len; ++i) {
Reid Spencer92904632007-02-23 01:57:13 +0000203 uint64_t limit = std::min(x[i],y[i]); // must come first in case dest == x
Reid Spencer54362ca2007-02-20 23:40:25 +0000204 dest[i] = x[i] + y[i] + carry;
Reid Spencer60c0a6a2007-02-21 05:44:56 +0000205 carry = dest[i] < limit || (carry && dest[i] == limit);
Reid Spencer5e0a8512007-02-17 03:16:00 +0000206 }
207 return carry;
208}
209
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000210/// Adds the RHS APint to this APInt.
211/// @returns this, after addition of RHS.
212/// @brief Addition assignment operator.
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000213APInt& APInt::operator+=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000214 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer54362ca2007-02-20 23:40:25 +0000215 if (isSingleWord())
216 VAL += RHS.VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000217 else {
Reid Spencer54362ca2007-02-20 23:40:25 +0000218 add(pVal, pVal, RHS.pVal, getNumWords());
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000219 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000220 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000221}
222
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000223/// Subtracts the integer array y from the integer array x
224/// @returns returns the borrow out.
225/// @brief Generalized subtraction of 64-bit integer arrays.
Reid Spencer9d6c9192007-02-24 03:58:46 +0000226static bool sub(uint64_t *dest, const uint64_t *x, const uint64_t *y,
Chris Lattner455e9ab2009-01-21 18:09:24 +0000227 unsigned len) {
Reid Spencer385f7542007-02-21 03:55:44 +0000228 bool borrow = false;
Chris Lattner455e9ab2009-01-21 18:09:24 +0000229 for (unsigned i = 0; i < len; ++i) {
Reid Spencer385f7542007-02-21 03:55:44 +0000230 uint64_t x_tmp = borrow ? x[i] - 1 : x[i];
231 borrow = y[i] > x_tmp || (borrow && x[i] == 0);
232 dest[i] = x_tmp - y[i];
Reid Spencer5e0a8512007-02-17 03:16:00 +0000233 }
Reid Spencer54362ca2007-02-20 23:40:25 +0000234 return borrow;
Reid Spencer5e0a8512007-02-17 03:16:00 +0000235}
236
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000237/// Subtracts the RHS APInt from this APInt
238/// @returns this, after subtraction
239/// @brief Subtraction assignment operator.
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000240APInt& APInt::operator-=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000241 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000242 if (isSingleWord())
Reid Spencer54362ca2007-02-20 23:40:25 +0000243 VAL -= RHS.VAL;
244 else
245 sub(pVal, pVal, RHS.pVal, getNumWords());
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000246 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000247}
248
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000249/// Multiplies an integer array, x by a a uint64_t integer and places the result
250/// into dest.
251/// @returns the carry out of the multiplication.
252/// @brief Multiply a multi-digit APInt by a single digit (64-bit) integer.
Chris Lattner455e9ab2009-01-21 18:09:24 +0000253static uint64_t mul_1(uint64_t dest[], uint64_t x[], unsigned len, uint64_t y) {
Reid Spencer610fad82007-02-24 10:01:42 +0000254 // Split y into high 32-bit part (hy) and low 32-bit part (ly)
Reid Spencer5e0a8512007-02-17 03:16:00 +0000255 uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000256 uint64_t carry = 0;
257
258 // For each digit of x.
Chris Lattner455e9ab2009-01-21 18:09:24 +0000259 for (unsigned i = 0; i < len; ++i) {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000260 // Split x into high and low words
261 uint64_t lx = x[i] & 0xffffffffULL;
262 uint64_t hx = x[i] >> 32;
263 // hasCarry - A flag to indicate if there is a carry to the next digit.
Reid Spencer5e0a8512007-02-17 03:16:00 +0000264 // hasCarry == 0, no carry
265 // hasCarry == 1, has carry
266 // hasCarry == 2, no carry and the calculation result == 0.
267 uint8_t hasCarry = 0;
268 dest[i] = carry + lx * ly;
269 // Determine if the add above introduces carry.
270 hasCarry = (dest[i] < carry) ? 1 : 0;
271 carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
272 // The upper limit of carry can be (2^32 - 1)(2^32 - 1) +
273 // (2^32 - 1) + 2^32 = 2^64.
274 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
275
276 carry += (lx * hy) & 0xffffffffULL;
277 dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
278 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) +
279 (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
280 }
Reid Spencer5e0a8512007-02-17 03:16:00 +0000281 return carry;
282}
283
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000284/// Multiplies integer array x by integer array y and stores the result into
285/// the integer array dest. Note that dest's size must be >= xlen + ylen.
286/// @brief Generalized multiplicate of integer arrays.
Chris Lattner455e9ab2009-01-21 18:09:24 +0000287static void mul(uint64_t dest[], uint64_t x[], unsigned xlen, uint64_t y[],
288 unsigned ylen) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000289 dest[xlen] = mul_1(dest, x, xlen, y[0]);
Chris Lattner455e9ab2009-01-21 18:09:24 +0000290 for (unsigned i = 1; i < ylen; ++i) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000291 uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
Reid Spencere0cdd332007-02-21 08:21:52 +0000292 uint64_t carry = 0, lx = 0, hx = 0;
Chris Lattner455e9ab2009-01-21 18:09:24 +0000293 for (unsigned j = 0; j < xlen; ++j) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000294 lx = x[j] & 0xffffffffULL;
295 hx = x[j] >> 32;
296 // hasCarry - A flag to indicate if has carry.
297 // hasCarry == 0, no carry
298 // hasCarry == 1, has carry
299 // hasCarry == 2, no carry and the calculation result == 0.
300 uint8_t hasCarry = 0;
301 uint64_t resul = carry + lx * ly;
302 hasCarry = (resul < carry) ? 1 : 0;
303 carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
304 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
305
306 carry += (lx * hy) & 0xffffffffULL;
307 resul = (carry << 32) | (resul & 0xffffffffULL);
308 dest[i+j] += resul;
309 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
310 (carry >> 32) + (dest[i+j] < resul ? 1 : 0) +
311 ((lx * hy) >> 32) + hx * hy;
312 }
313 dest[i+xlen] = carry;
314 }
315}
316
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000317APInt& APInt::operator*=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000318 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencere0cdd332007-02-21 08:21:52 +0000319 if (isSingleWord()) {
Reid Spencer61eb1802007-02-20 20:42:10 +0000320 VAL *= RHS.VAL;
Reid Spencere0cdd332007-02-21 08:21:52 +0000321 clearUnusedBits();
322 return *this;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000323 }
Reid Spencere0cdd332007-02-21 08:21:52 +0000324
325 // Get some bit facts about LHS and check for zero
Chris Lattner455e9ab2009-01-21 18:09:24 +0000326 unsigned lhsBits = getActiveBits();
327 unsigned lhsWords = !lhsBits ? 0 : whichWord(lhsBits - 1) + 1;
Reid Spencere0cdd332007-02-21 08:21:52 +0000328 if (!lhsWords)
329 // 0 * X ===> 0
330 return *this;
331
332 // Get some bit facts about RHS and check for zero
Chris Lattner455e9ab2009-01-21 18:09:24 +0000333 unsigned rhsBits = RHS.getActiveBits();
334 unsigned rhsWords = !rhsBits ? 0 : whichWord(rhsBits - 1) + 1;
Reid Spencere0cdd332007-02-21 08:21:52 +0000335 if (!rhsWords) {
336 // X * 0 ===> 0
337 clear();
338 return *this;
339 }
340
341 // Allocate space for the result
Chris Lattner455e9ab2009-01-21 18:09:24 +0000342 unsigned destWords = rhsWords + lhsWords;
Reid Spencere0cdd332007-02-21 08:21:52 +0000343 uint64_t *dest = getMemory(destWords);
344
345 // Perform the long multiply
346 mul(dest, pVal, lhsWords, RHS.pVal, rhsWords);
347
348 // Copy result back into *this
349 clear();
Chris Lattner455e9ab2009-01-21 18:09:24 +0000350 unsigned wordsToCopy = destWords >= getNumWords() ? getNumWords() : destWords;
Reid Spencere0cdd332007-02-21 08:21:52 +0000351 memcpy(pVal, dest, wordsToCopy * APINT_WORD_SIZE);
352
353 // delete dest array and return
354 delete[] dest;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000355 return *this;
356}
357
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000358APInt& APInt::operator&=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000359 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000360 if (isSingleWord()) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000361 VAL &= RHS.VAL;
362 return *this;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000363 }
Chris Lattner455e9ab2009-01-21 18:09:24 +0000364 unsigned numWords = getNumWords();
365 for (unsigned i = 0; i < numWords; ++i)
Reid Spenceraf0e9562007-02-18 18:38:44 +0000366 pVal[i] &= RHS.pVal[i];
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000367 return *this;
368}
369
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000370APInt& APInt::operator|=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000371 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000372 if (isSingleWord()) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000373 VAL |= RHS.VAL;
374 return *this;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000375 }
Chris Lattner455e9ab2009-01-21 18:09:24 +0000376 unsigned numWords = getNumWords();
377 for (unsigned i = 0; i < numWords; ++i)
Reid Spenceraf0e9562007-02-18 18:38:44 +0000378 pVal[i] |= RHS.pVal[i];
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000379 return *this;
380}
381
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000382APInt& APInt::operator^=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000383 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000384 if (isSingleWord()) {
Reid Spencerf2c521c2007-02-18 06:39:42 +0000385 VAL ^= RHS.VAL;
Reid Spencer54362ca2007-02-20 23:40:25 +0000386 this->clearUnusedBits();
Reid Spencerf2c521c2007-02-18 06:39:42 +0000387 return *this;
388 }
Chris Lattner455e9ab2009-01-21 18:09:24 +0000389 unsigned numWords = getNumWords();
390 for (unsigned i = 0; i < numWords; ++i)
Reid Spenceraf0e9562007-02-18 18:38:44 +0000391 pVal[i] ^= RHS.pVal[i];
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000392 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000393}
394
Chris Lattner98f8ccf2008-08-20 17:02:31 +0000395APInt APInt::AndSlowCase(const APInt& RHS) const {
Chris Lattner455e9ab2009-01-21 18:09:24 +0000396 unsigned numWords = getNumWords();
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000397 uint64_t* val = getMemory(numWords);
Chris Lattner455e9ab2009-01-21 18:09:24 +0000398 for (unsigned i = 0; i < numWords; ++i)
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000399 val[i] = pVal[i] & RHS.pVal[i];
400 return APInt(val, getBitWidth());
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000401}
402
Chris Lattner98f8ccf2008-08-20 17:02:31 +0000403APInt APInt::OrSlowCase(const APInt& RHS) const {
Chris Lattner455e9ab2009-01-21 18:09:24 +0000404 unsigned numWords = getNumWords();
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000405 uint64_t *val = getMemory(numWords);
Chris Lattner455e9ab2009-01-21 18:09:24 +0000406 for (unsigned i = 0; i < numWords; ++i)
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000407 val[i] = pVal[i] | RHS.pVal[i];
408 return APInt(val, getBitWidth());
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000409}
410
Chris Lattner98f8ccf2008-08-20 17:02:31 +0000411APInt APInt::XorSlowCase(const APInt& RHS) const {
Chris Lattner455e9ab2009-01-21 18:09:24 +0000412 unsigned numWords = getNumWords();
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000413 uint64_t *val = getMemory(numWords);
Chris Lattner455e9ab2009-01-21 18:09:24 +0000414 for (unsigned i = 0; i < numWords; ++i)
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000415 val[i] = pVal[i] ^ RHS.pVal[i];
416
417 // 0^0==1 so clear the high bits in case they got set.
418 return APInt(val, getBitWidth()).clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000419}
420
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000421bool APInt::operator !() const {
422 if (isSingleWord())
423 return !VAL;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000424
Chris Lattner455e9ab2009-01-21 18:09:24 +0000425 for (unsigned i = 0; i < getNumWords(); ++i)
Reid Spenceraf0e9562007-02-18 18:38:44 +0000426 if (pVal[i])
427 return false;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000428 return true;
429}
430
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000431APInt APInt::operator*(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000432 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000433 if (isSingleWord())
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000434 return APInt(BitWidth, VAL * RHS.VAL);
Reid Spencer61eb1802007-02-20 20:42:10 +0000435 APInt Result(*this);
436 Result *= RHS;
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000437 return Result.clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000438}
439
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000440APInt APInt::operator+(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000441 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000442 if (isSingleWord())
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000443 return APInt(BitWidth, VAL + RHS.VAL);
Reid Spencer54362ca2007-02-20 23:40:25 +0000444 APInt Result(BitWidth, 0);
445 add(Result.pVal, this->pVal, RHS.pVal, getNumWords());
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000446 return Result.clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000447}
448
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000449APInt APInt::operator-(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000450 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000451 if (isSingleWord())
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000452 return APInt(BitWidth, VAL - RHS.VAL);
Reid Spencer54362ca2007-02-20 23:40:25 +0000453 APInt Result(BitWidth, 0);
454 sub(Result.pVal, this->pVal, RHS.pVal, getNumWords());
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000455 return Result.clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000456}
457
Chris Lattner455e9ab2009-01-21 18:09:24 +0000458bool APInt::operator[](unsigned bitPosition) const {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000459 return (maskBit(bitPosition) &
460 (isSingleWord() ? VAL : pVal[whichWord(bitPosition)])) != 0;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000461}
462
Chris Lattner98f8ccf2008-08-20 17:02:31 +0000463bool APInt::EqualSlowCase(const APInt& RHS) const {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000464 // Get some facts about the number of bits used in the two operands.
Chris Lattner455e9ab2009-01-21 18:09:24 +0000465 unsigned n1 = getActiveBits();
466 unsigned n2 = RHS.getActiveBits();
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000467
468 // If the number of bits isn't the same, they aren't equal
Reid Spencer54362ca2007-02-20 23:40:25 +0000469 if (n1 != n2)
470 return false;
471
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000472 // If the number of bits fits in a word, we only need to compare the low word.
Reid Spencer54362ca2007-02-20 23:40:25 +0000473 if (n1 <= APINT_BITS_PER_WORD)
474 return pVal[0] == RHS.pVal[0];
475
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000476 // Otherwise, compare everything
Reid Spencer54362ca2007-02-20 23:40:25 +0000477 for (int i = whichWord(n1 - 1); i >= 0; --i)
478 if (pVal[i] != RHS.pVal[i])
479 return false;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000480 return true;
481}
482
Chris Lattner98f8ccf2008-08-20 17:02:31 +0000483bool APInt::EqualSlowCase(uint64_t Val) const {
Chris Lattner455e9ab2009-01-21 18:09:24 +0000484 unsigned n = getActiveBits();
Reid Spencer54362ca2007-02-20 23:40:25 +0000485 if (n <= APINT_BITS_PER_WORD)
486 return pVal[0] == Val;
487 else
488 return false;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000489}
490
Reid Spencere81d2da2007-02-16 22:36:51 +0000491bool APInt::ult(const APInt& RHS) const {
492 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
493 if (isSingleWord())
494 return VAL < RHS.VAL;
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000495
496 // Get active bit length of both operands
Chris Lattner455e9ab2009-01-21 18:09:24 +0000497 unsigned n1 = getActiveBits();
498 unsigned n2 = RHS.getActiveBits();
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000499
500 // If magnitude of LHS is less than RHS, return true.
501 if (n1 < n2)
502 return true;
503
504 // If magnitude of RHS is greather than LHS, return false.
505 if (n2 < n1)
506 return false;
507
508 // If they bot fit in a word, just compare the low order word
509 if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
510 return pVal[0] < RHS.pVal[0];
511
512 // Otherwise, compare all words
Chris Lattner455e9ab2009-01-21 18:09:24 +0000513 unsigned topWord = whichWord(std::max(n1,n2)-1);
Reid Spencer1fa111e2007-02-27 18:23:40 +0000514 for (int i = topWord; i >= 0; --i) {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000515 if (pVal[i] > RHS.pVal[i])
Reid Spencere81d2da2007-02-16 22:36:51 +0000516 return false;
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000517 if (pVal[i] < RHS.pVal[i])
518 return true;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000519 }
520 return false;
521}
522
Reid Spencere81d2da2007-02-16 22:36:51 +0000523bool APInt::slt(const APInt& RHS) const {
524 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
Reid Spencera58f0582007-02-18 20:09:41 +0000525 if (isSingleWord()) {
526 int64_t lhsSext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
527 int64_t rhsSext = (int64_t(RHS.VAL) << (64-BitWidth)) >> (64-BitWidth);
528 return lhsSext < rhsSext;
Reid Spencere81d2da2007-02-16 22:36:51 +0000529 }
Reid Spencera58f0582007-02-18 20:09:41 +0000530
531 APInt lhs(*this);
Reid Spencer1fa111e2007-02-27 18:23:40 +0000532 APInt rhs(RHS);
533 bool lhsNeg = isNegative();
534 bool rhsNeg = rhs.isNegative();
535 if (lhsNeg) {
536 // Sign bit is set so perform two's complement to make it positive
Reid Spencera58f0582007-02-18 20:09:41 +0000537 lhs.flip();
538 lhs++;
539 }
Reid Spencer1fa111e2007-02-27 18:23:40 +0000540 if (rhsNeg) {
541 // Sign bit is set so perform two's complement to make it positive
Reid Spencera58f0582007-02-18 20:09:41 +0000542 rhs.flip();
543 rhs++;
544 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000545
546 // Now we have unsigned values to compare so do the comparison if necessary
547 // based on the negativeness of the values.
Reid Spencer1fa111e2007-02-27 18:23:40 +0000548 if (lhsNeg)
549 if (rhsNeg)
550 return lhs.ugt(rhs);
Reid Spencera58f0582007-02-18 20:09:41 +0000551 else
552 return true;
Reid Spencer1fa111e2007-02-27 18:23:40 +0000553 else if (rhsNeg)
Reid Spencera58f0582007-02-18 20:09:41 +0000554 return false;
555 else
556 return lhs.ult(rhs);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000557}
558
Chris Lattner455e9ab2009-01-21 18:09:24 +0000559APInt& APInt::set(unsigned bitPosition) {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000560 if (isSingleWord())
561 VAL |= maskBit(bitPosition);
562 else
563 pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000564 return *this;
565}
566
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000567/// Set the given bit to 0 whose position is given as "bitPosition".
568/// @brief Set a given bit to 0.
Chris Lattner455e9ab2009-01-21 18:09:24 +0000569APInt& APInt::clear(unsigned bitPosition) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000570 if (isSingleWord())
571 VAL &= ~maskBit(bitPosition);
572 else
573 pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000574 return *this;
575}
576
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000577/// @brief Toggle every bit to its opposite value.
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000578
579/// Toggle a given bit to its opposite value whose position is given
580/// as "bitPosition".
581/// @brief Toggles a given bit to its opposite value.
Chris Lattner455e9ab2009-01-21 18:09:24 +0000582APInt& APInt::flip(unsigned bitPosition) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000583 assert(bitPosition < BitWidth && "Out of the bit-width range!");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000584 if ((*this)[bitPosition]) clear(bitPosition);
585 else set(bitPosition);
586 return *this;
587}
588
Chris Lattner455e9ab2009-01-21 18:09:24 +0000589unsigned APInt::getBitsNeeded(const char* str, unsigned slen, uint8_t radix) {
Reid Spencer57ae4f52007-04-13 19:19:07 +0000590 assert(str != 0 && "Invalid value string");
591 assert(slen > 0 && "Invalid string length");
592
593 // Each computation below needs to know if its negative
Chris Lattner455e9ab2009-01-21 18:09:24 +0000594 unsigned isNegative = str[0] == '-';
Reid Spencer57ae4f52007-04-13 19:19:07 +0000595 if (isNegative) {
596 slen--;
597 str++;
598 }
599 // For radixes of power-of-two values, the bits required is accurately and
600 // easily computed
601 if (radix == 2)
602 return slen + isNegative;
603 if (radix == 8)
604 return slen * 3 + isNegative;
605 if (radix == 16)
606 return slen * 4 + isNegative;
607
608 // Otherwise it must be radix == 10, the hard case
609 assert(radix == 10 && "Invalid radix");
610
611 // This is grossly inefficient but accurate. We could probably do something
612 // with a computation of roughly slen*64/20 and then adjust by the value of
613 // the first few digits. But, I'm not sure how accurate that could be.
614
615 // Compute a sufficient number of bits that is always large enough but might
616 // be too large. This avoids the assertion in the constructor.
Chris Lattner455e9ab2009-01-21 18:09:24 +0000617 unsigned sufficient = slen*64/18;
Reid Spencer57ae4f52007-04-13 19:19:07 +0000618
619 // Convert to the actual binary value.
620 APInt tmp(sufficient, str, slen, radix);
621
622 // Compute how many bits are required.
Reid Spencer0468ab32007-04-14 00:00:10 +0000623 return isNegative + tmp.logBase2() + 1;
Reid Spencer57ae4f52007-04-13 19:19:07 +0000624}
625
Reid Spencer794f4722007-02-26 21:02:27 +0000626uint64_t APInt::getHashValue() const {
Reid Spencer9ac44112007-02-26 23:38:21 +0000627 // Put the bit width into the low order bits.
628 uint64_t hash = BitWidth;
Reid Spencer794f4722007-02-26 21:02:27 +0000629
630 // Add the sum of the words to the hash.
631 if (isSingleWord())
Reid Spencer9ac44112007-02-26 23:38:21 +0000632 hash += VAL << 6; // clear separation of up to 64 bits
Reid Spencer794f4722007-02-26 21:02:27 +0000633 else
Chris Lattner455e9ab2009-01-21 18:09:24 +0000634 for (unsigned i = 0; i < getNumWords(); ++i)
Reid Spencer9ac44112007-02-26 23:38:21 +0000635 hash += pVal[i] << 6; // clear sepration of up to 64 bits
Reid Spencer794f4722007-02-26 21:02:27 +0000636 return hash;
637}
638
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000639/// HiBits - This function returns the high "numBits" bits of this APInt.
Chris Lattner455e9ab2009-01-21 18:09:24 +0000640APInt APInt::getHiBits(unsigned numBits) const {
Reid Spencere81d2da2007-02-16 22:36:51 +0000641 return APIntOps::lshr(*this, BitWidth - numBits);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000642}
643
644/// LoBits - This function returns the low "numBits" bits of this APInt.
Chris Lattner455e9ab2009-01-21 18:09:24 +0000645APInt APInt::getLoBits(unsigned numBits) const {
Reid Spencere81d2da2007-02-16 22:36:51 +0000646 return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits),
647 BitWidth - numBits);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000648}
649
Reid Spencere81d2da2007-02-16 22:36:51 +0000650bool APInt::isPowerOf2() const {
651 return (!!*this) && !(*this & (*this - APInt(BitWidth,1)));
652}
653
Chris Lattner455e9ab2009-01-21 18:09:24 +0000654unsigned APInt::countLeadingZerosSlowCase() const {
655 unsigned Count = 0;
656 for (unsigned i = getNumWords(); i > 0u; --i) {
Chris Lattner98f8ccf2008-08-20 17:02:31 +0000657 if (pVal[i-1] == 0)
658 Count += APINT_BITS_PER_WORD;
659 else {
660 Count += CountLeadingZeros_64(pVal[i-1]);
661 break;
Reid Spencere549c492007-02-21 00:29:48 +0000662 }
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000663 }
Chris Lattner455e9ab2009-01-21 18:09:24 +0000664 unsigned remainder = BitWidth % APINT_BITS_PER_WORD;
Reid Spencerab2b2c82007-02-22 00:22:00 +0000665 if (remainder)
666 Count -= APINT_BITS_PER_WORD - remainder;
Chris Lattner9e513ac2007-11-23 22:42:31 +0000667 return std::min(Count, BitWidth);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000668}
669
Chris Lattner455e9ab2009-01-21 18:09:24 +0000670static unsigned countLeadingOnes_64(uint64_t V, unsigned skip) {
671 unsigned Count = 0;
Reid Spencer681dcd12007-02-27 21:59:26 +0000672 if (skip)
673 V <<= skip;
674 while (V && (V & (1ULL << 63))) {
675 Count++;
676 V <<= 1;
677 }
678 return Count;
679}
680
Chris Lattner455e9ab2009-01-21 18:09:24 +0000681unsigned APInt::countLeadingOnes() const {
Reid Spencer681dcd12007-02-27 21:59:26 +0000682 if (isSingleWord())
683 return countLeadingOnes_64(VAL, APINT_BITS_PER_WORD - BitWidth);
684
Chris Lattner455e9ab2009-01-21 18:09:24 +0000685 unsigned highWordBits = BitWidth % APINT_BITS_PER_WORD;
686 unsigned shift = (highWordBits == 0 ? 0 : APINT_BITS_PER_WORD - highWordBits);
Reid Spencer681dcd12007-02-27 21:59:26 +0000687 int i = getNumWords() - 1;
Chris Lattner455e9ab2009-01-21 18:09:24 +0000688 unsigned Count = countLeadingOnes_64(pVal[i], shift);
Reid Spencer681dcd12007-02-27 21:59:26 +0000689 if (Count == highWordBits) {
690 for (i--; i >= 0; --i) {
691 if (pVal[i] == -1ULL)
692 Count += APINT_BITS_PER_WORD;
693 else {
694 Count += countLeadingOnes_64(pVal[i], 0);
695 break;
696 }
697 }
698 }
699 return Count;
700}
701
Chris Lattner455e9ab2009-01-21 18:09:24 +0000702unsigned APInt::countTrailingZeros() const {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000703 if (isSingleWord())
Chris Lattner455e9ab2009-01-21 18:09:24 +0000704 return std::min(unsigned(CountTrailingZeros_64(VAL)), BitWidth);
705 unsigned Count = 0;
706 unsigned i = 0;
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000707 for (; i < getNumWords() && pVal[i] == 0; ++i)
708 Count += APINT_BITS_PER_WORD;
709 if (i < getNumWords())
710 Count += CountTrailingZeros_64(pVal[i]);
Chris Lattner5e557122007-11-23 22:36:25 +0000711 return std::min(Count, BitWidth);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000712}
713
Chris Lattner455e9ab2009-01-21 18:09:24 +0000714unsigned APInt::countTrailingOnesSlowCase() const {
715 unsigned Count = 0;
716 unsigned i = 0;
Dan Gohman5a0e7b42008-02-14 22:38:45 +0000717 for (; i < getNumWords() && pVal[i] == -1ULL; ++i)
Dan Gohman42dd77f2008-02-13 21:11:05 +0000718 Count += APINT_BITS_PER_WORD;
719 if (i < getNumWords())
720 Count += CountTrailingOnes_64(pVal[i]);
721 return std::min(Count, BitWidth);
722}
723
Chris Lattner455e9ab2009-01-21 18:09:24 +0000724unsigned APInt::countPopulationSlowCase() const {
725 unsigned Count = 0;
726 for (unsigned i = 0; i < getNumWords(); ++i)
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000727 Count += CountPopulation_64(pVal[i]);
728 return Count;
729}
730
Reid Spencere81d2da2007-02-16 22:36:51 +0000731APInt APInt::byteSwap() const {
732 assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
733 if (BitWidth == 16)
Jeff Cohen09dfd8e2007-03-20 20:42:36 +0000734 return APInt(BitWidth, ByteSwap_16(uint16_t(VAL)));
Reid Spencere81d2da2007-02-16 22:36:51 +0000735 else if (BitWidth == 32)
Chris Lattner455e9ab2009-01-21 18:09:24 +0000736 return APInt(BitWidth, ByteSwap_32(unsigned(VAL)));
Reid Spencere81d2da2007-02-16 22:36:51 +0000737 else if (BitWidth == 48) {
Chris Lattner455e9ab2009-01-21 18:09:24 +0000738 unsigned Tmp1 = unsigned(VAL >> 16);
Zhou Shengb04973e2007-02-15 06:36:31 +0000739 Tmp1 = ByteSwap_32(Tmp1);
Jeff Cohen09dfd8e2007-03-20 20:42:36 +0000740 uint16_t Tmp2 = uint16_t(VAL);
Zhou Shengb04973e2007-02-15 06:36:31 +0000741 Tmp2 = ByteSwap_16(Tmp2);
Jeff Cohen09dfd8e2007-03-20 20:42:36 +0000742 return APInt(BitWidth, (uint64_t(Tmp2) << 32) | Tmp1);
Reid Spencere81d2da2007-02-16 22:36:51 +0000743 } else if (BitWidth == 64)
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000744 return APInt(BitWidth, ByteSwap_64(VAL));
Zhou Shengb04973e2007-02-15 06:36:31 +0000745 else {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000746 APInt Result(BitWidth, 0);
Zhou Shengb04973e2007-02-15 06:36:31 +0000747 char *pByte = (char*)Result.pVal;
Chris Lattner455e9ab2009-01-21 18:09:24 +0000748 for (unsigned i = 0; i < BitWidth / APINT_WORD_SIZE / 2; ++i) {
Zhou Shengb04973e2007-02-15 06:36:31 +0000749 char Tmp = pByte[i];
Reid Spencera58f0582007-02-18 20:09:41 +0000750 pByte[i] = pByte[BitWidth / APINT_WORD_SIZE - 1 - i];
751 pByte[BitWidth / APINT_WORD_SIZE - i - 1] = Tmp;
Zhou Shengb04973e2007-02-15 06:36:31 +0000752 }
753 return Result;
754 }
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000755}
756
Zhou Sheng0b706b12007-02-08 14:35:19 +0000757APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1,
758 const APInt& API2) {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000759 APInt A = API1, B = API2;
760 while (!!B) {
761 APInt T = B;
Reid Spencere81d2da2007-02-16 22:36:51 +0000762 B = APIntOps::urem(A, B);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000763 A = T;
764 }
765 return A;
766}
Chris Lattner6ad4c142007-02-06 05:38:37 +0000767
Chris Lattner455e9ab2009-01-21 18:09:24 +0000768APInt llvm::APIntOps::RoundDoubleToAPInt(double Double, unsigned width) {
Zhou Shengd93f00c2007-02-12 20:02:55 +0000769 union {
770 double D;
771 uint64_t I;
772 } T;
773 T.D = Double;
Reid Spencer30f44f32007-02-27 01:28:10 +0000774
775 // Get the sign bit from the highest order bit
Zhou Shengd93f00c2007-02-12 20:02:55 +0000776 bool isNeg = T.I >> 63;
Reid Spencer30f44f32007-02-27 01:28:10 +0000777
778 // Get the 11-bit exponent and adjust for the 1023 bit bias
Zhou Shengd93f00c2007-02-12 20:02:55 +0000779 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
Reid Spencer30f44f32007-02-27 01:28:10 +0000780
781 // If the exponent is negative, the value is < 0 so just return 0.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000782 if (exp < 0)
Reid Spencerff605762007-02-28 01:30:08 +0000783 return APInt(width, 0u);
Reid Spencer30f44f32007-02-27 01:28:10 +0000784
785 // Extract the mantissa by clearing the top 12 bits (sign + exponent).
786 uint64_t mantissa = (T.I & (~0ULL >> 12)) | 1ULL << 52;
787
788 // If the exponent doesn't shift all bits out of the mantissa
Zhou Shengd93f00c2007-02-12 20:02:55 +0000789 if (exp < 52)
Reid Spencer1fa111e2007-02-27 18:23:40 +0000790 return isNeg ? -APInt(width, mantissa >> (52 - exp)) :
791 APInt(width, mantissa >> (52 - exp));
792
793 // If the client didn't provide enough bits for us to shift the mantissa into
794 // then the result is undefined, just return 0
795 if (width <= exp - 52)
796 return APInt(width, 0);
Reid Spencer30f44f32007-02-27 01:28:10 +0000797
798 // Otherwise, we have to shift the mantissa bits up to the right location
Reid Spencer1fa111e2007-02-27 18:23:40 +0000799 APInt Tmp(width, mantissa);
Chris Lattner455e9ab2009-01-21 18:09:24 +0000800 Tmp = Tmp.shl((unsigned)exp - 52);
Zhou Shengd93f00c2007-02-12 20:02:55 +0000801 return isNeg ? -Tmp : Tmp;
802}
803
Reid Spencerdb3faa62007-02-13 22:41:58 +0000804/// RoundToDouble - This function convert this APInt to a double.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000805/// The layout for double is as following (IEEE Standard 754):
806/// --------------------------------------
807/// | Sign Exponent Fraction Bias |
808/// |-------------------------------------- |
809/// | 1[63] 11[62-52] 52[51-00] 1023 |
810/// --------------------------------------
Reid Spencere81d2da2007-02-16 22:36:51 +0000811double APInt::roundToDouble(bool isSigned) const {
Reid Spencer9c0696f2007-02-20 08:51:03 +0000812
813 // Handle the simple case where the value is contained in one uint64_t.
Reid Spencera58f0582007-02-18 20:09:41 +0000814 if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
815 if (isSigned) {
816 int64_t sext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
817 return double(sext);
818 } else
819 return double(VAL);
820 }
821
Reid Spencer9c0696f2007-02-20 08:51:03 +0000822 // Determine if the value is negative.
Reid Spencere81d2da2007-02-16 22:36:51 +0000823 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
Reid Spencer9c0696f2007-02-20 08:51:03 +0000824
825 // Construct the absolute value if we're negative.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000826 APInt Tmp(isNeg ? -(*this) : (*this));
Reid Spencer9c0696f2007-02-20 08:51:03 +0000827
828 // Figure out how many bits we're using.
Chris Lattner455e9ab2009-01-21 18:09:24 +0000829 unsigned n = Tmp.getActiveBits();
Zhou Shengd93f00c2007-02-12 20:02:55 +0000830
Reid Spencer9c0696f2007-02-20 08:51:03 +0000831 // The exponent (without bias normalization) is just the number of bits
832 // we are using. Note that the sign bit is gone since we constructed the
833 // absolute value.
834 uint64_t exp = n;
Zhou Shengd93f00c2007-02-12 20:02:55 +0000835
Reid Spencer9c0696f2007-02-20 08:51:03 +0000836 // Return infinity for exponent overflow
837 if (exp > 1023) {
838 if (!isSigned || !isNeg)
Jeff Cohen09dfd8e2007-03-20 20:42:36 +0000839 return std::numeric_limits<double>::infinity();
Reid Spencer9c0696f2007-02-20 08:51:03 +0000840 else
Jeff Cohen09dfd8e2007-03-20 20:42:36 +0000841 return -std::numeric_limits<double>::infinity();
Reid Spencer9c0696f2007-02-20 08:51:03 +0000842 }
843 exp += 1023; // Increment for 1023 bias
844
845 // Number of bits in mantissa is 52. To obtain the mantissa value, we must
846 // extract the high 52 bits from the correct words in pVal.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000847 uint64_t mantissa;
Reid Spencer9c0696f2007-02-20 08:51:03 +0000848 unsigned hiWord = whichWord(n-1);
849 if (hiWord == 0) {
850 mantissa = Tmp.pVal[0];
851 if (n > 52)
852 mantissa >>= n - 52; // shift down, we want the top 52 bits.
853 } else {
854 assert(hiWord > 0 && "huh?");
855 uint64_t hibits = Tmp.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
856 uint64_t lobits = Tmp.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
857 mantissa = hibits | lobits;
858 }
859
Zhou Shengd93f00c2007-02-12 20:02:55 +0000860 // The leading bit of mantissa is implicit, so get rid of it.
Reid Spencer443b5702007-02-18 00:44:22 +0000861 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
Zhou Shengd93f00c2007-02-12 20:02:55 +0000862 union {
863 double D;
864 uint64_t I;
865 } T;
866 T.I = sign | (exp << 52) | mantissa;
867 return T.D;
868}
869
Reid Spencere81d2da2007-02-16 22:36:51 +0000870// Truncate to new width.
Chris Lattner455e9ab2009-01-21 18:09:24 +0000871APInt &APInt::trunc(unsigned width) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000872 assert(width < BitWidth && "Invalid APInt Truncate request");
Chris Lattner98f8ccf2008-08-20 17:02:31 +0000873 assert(width && "Can't truncate to 0 bits");
Chris Lattner455e9ab2009-01-21 18:09:24 +0000874 unsigned wordsBefore = getNumWords();
Reid Spencer9eec2412007-02-25 23:44:53 +0000875 BitWidth = width;
Chris Lattner455e9ab2009-01-21 18:09:24 +0000876 unsigned wordsAfter = getNumWords();
Reid Spencer9eec2412007-02-25 23:44:53 +0000877 if (wordsBefore != wordsAfter) {
878 if (wordsAfter == 1) {
879 uint64_t *tmp = pVal;
880 VAL = pVal[0];
Reid Spencer9ac44112007-02-26 23:38:21 +0000881 delete [] tmp;
Reid Spencer9eec2412007-02-25 23:44:53 +0000882 } else {
883 uint64_t *newVal = getClearedMemory(wordsAfter);
Chris Lattner455e9ab2009-01-21 18:09:24 +0000884 for (unsigned i = 0; i < wordsAfter; ++i)
Reid Spencer9eec2412007-02-25 23:44:53 +0000885 newVal[i] = pVal[i];
Reid Spencer9ac44112007-02-26 23:38:21 +0000886 delete [] pVal;
Reid Spencer9eec2412007-02-25 23:44:53 +0000887 pVal = newVal;
888 }
889 }
Reid Spencer94900772007-02-28 17:34:32 +0000890 return clearUnusedBits();
Reid Spencere81d2da2007-02-16 22:36:51 +0000891}
892
893// Sign extend to a new width.
Chris Lattner455e9ab2009-01-21 18:09:24 +0000894APInt &APInt::sext(unsigned width) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000895 assert(width > BitWidth && "Invalid APInt SignExtend request");
Reid Spencer9eec2412007-02-25 23:44:53 +0000896 // If the sign bit isn't set, this is the same as zext.
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000897 if (!isNegative()) {
Reid Spencer9eec2412007-02-25 23:44:53 +0000898 zext(width);
Reid Spencer94900772007-02-28 17:34:32 +0000899 return *this;
Reid Spencer9eec2412007-02-25 23:44:53 +0000900 }
901
902 // The sign bit is set. First, get some facts
Chris Lattner455e9ab2009-01-21 18:09:24 +0000903 unsigned wordsBefore = getNumWords();
904 unsigned wordBits = BitWidth % APINT_BITS_PER_WORD;
Reid Spencer9eec2412007-02-25 23:44:53 +0000905 BitWidth = width;
Chris Lattner455e9ab2009-01-21 18:09:24 +0000906 unsigned wordsAfter = getNumWords();
Reid Spencer9eec2412007-02-25 23:44:53 +0000907
908 // Mask the high order word appropriately
909 if (wordsBefore == wordsAfter) {
Chris Lattner455e9ab2009-01-21 18:09:24 +0000910 unsigned newWordBits = width % APINT_BITS_PER_WORD;
Reid Spencer9eec2412007-02-25 23:44:53 +0000911 // The extension is contained to the wordsBefore-1th word.
Reid Spencer36184ed2007-03-02 01:19:42 +0000912 uint64_t mask = ~0ULL;
913 if (newWordBits)
914 mask >>= APINT_BITS_PER_WORD - newWordBits;
915 mask <<= wordBits;
Reid Spencer9eec2412007-02-25 23:44:53 +0000916 if (wordsBefore == 1)
917 VAL |= mask;
918 else
919 pVal[wordsBefore-1] |= mask;
Reid Spencer295e40a2007-03-01 23:30:25 +0000920 return clearUnusedBits();
Reid Spencer9eec2412007-02-25 23:44:53 +0000921 }
922
Reid Spencerf30b1882007-02-25 23:54:00 +0000923 uint64_t mask = wordBits == 0 ? 0 : ~0ULL << wordBits;
Reid Spencer9eec2412007-02-25 23:44:53 +0000924 uint64_t *newVal = getMemory(wordsAfter);
925 if (wordsBefore == 1)
926 newVal[0] = VAL | mask;
927 else {
Chris Lattner455e9ab2009-01-21 18:09:24 +0000928 for (unsigned i = 0; i < wordsBefore; ++i)
Reid Spencer9eec2412007-02-25 23:44:53 +0000929 newVal[i] = pVal[i];
930 newVal[wordsBefore-1] |= mask;
931 }
Chris Lattner455e9ab2009-01-21 18:09:24 +0000932 for (unsigned i = wordsBefore; i < wordsAfter; i++)
Reid Spencer9eec2412007-02-25 23:44:53 +0000933 newVal[i] = -1ULL;
934 if (wordsBefore != 1)
Reid Spencer9ac44112007-02-26 23:38:21 +0000935 delete [] pVal;
Reid Spencer9eec2412007-02-25 23:44:53 +0000936 pVal = newVal;
Reid Spencer94900772007-02-28 17:34:32 +0000937 return clearUnusedBits();
Reid Spencere81d2da2007-02-16 22:36:51 +0000938}
939
940// Zero extend to a new width.
Chris Lattner455e9ab2009-01-21 18:09:24 +0000941APInt &APInt::zext(unsigned width) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000942 assert(width > BitWidth && "Invalid APInt ZeroExtend request");
Chris Lattner455e9ab2009-01-21 18:09:24 +0000943 unsigned wordsBefore = getNumWords();
Reid Spencer9eec2412007-02-25 23:44:53 +0000944 BitWidth = width;
Chris Lattner455e9ab2009-01-21 18:09:24 +0000945 unsigned wordsAfter = getNumWords();
Reid Spencer9eec2412007-02-25 23:44:53 +0000946 if (wordsBefore != wordsAfter) {
947 uint64_t *newVal = getClearedMemory(wordsAfter);
948 if (wordsBefore == 1)
949 newVal[0] = VAL;
950 else
Chris Lattner455e9ab2009-01-21 18:09:24 +0000951 for (unsigned i = 0; i < wordsBefore; ++i)
Reid Spencer9eec2412007-02-25 23:44:53 +0000952 newVal[i] = pVal[i];
953 if (wordsBefore != 1)
Reid Spencer9ac44112007-02-26 23:38:21 +0000954 delete [] pVal;
Reid Spencer9eec2412007-02-25 23:44:53 +0000955 pVal = newVal;
956 }
Reid Spencer94900772007-02-28 17:34:32 +0000957 return *this;
Reid Spencere81d2da2007-02-16 22:36:51 +0000958}
959
Chris Lattner455e9ab2009-01-21 18:09:24 +0000960APInt &APInt::zextOrTrunc(unsigned width) {
Reid Spencer68e23002007-03-01 17:15:32 +0000961 if (BitWidth < width)
962 return zext(width);
963 if (BitWidth > width)
964 return trunc(width);
965 return *this;
966}
967
Chris Lattner455e9ab2009-01-21 18:09:24 +0000968APInt &APInt::sextOrTrunc(unsigned width) {
Reid Spencer68e23002007-03-01 17:15:32 +0000969 if (BitWidth < width)
970 return sext(width);
971 if (BitWidth > width)
972 return trunc(width);
973 return *this;
974}
975
Zhou Shengff4304f2007-02-09 07:48:24 +0000976/// Arithmetic right-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +0000977/// @brief Arithmetic right-shift function.
Dan Gohmancf609572008-02-29 01:40:47 +0000978APInt APInt::ashr(const APInt &shiftAmt) const {
Chris Lattner455e9ab2009-01-21 18:09:24 +0000979 return ashr((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohmancf609572008-02-29 01:40:47 +0000980}
981
982/// Arithmetic right-shift this APInt by shiftAmt.
983/// @brief Arithmetic right-shift function.
Chris Lattner455e9ab2009-01-21 18:09:24 +0000984APInt APInt::ashr(unsigned shiftAmt) const {
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000985 assert(shiftAmt <= BitWidth && "Invalid shift amount");
Reid Spencer46f9c942007-03-02 22:39:11 +0000986 // Handle a degenerate case
987 if (shiftAmt == 0)
988 return *this;
989
990 // Handle single word shifts with built-in ashr
Reid Spencer24c4a8f2007-02-25 01:56:07 +0000991 if (isSingleWord()) {
992 if (shiftAmt == BitWidth)
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000993 return APInt(BitWidth, 0); // undefined
994 else {
Chris Lattner455e9ab2009-01-21 18:09:24 +0000995 unsigned SignBit = APINT_BITS_PER_WORD - BitWidth;
Reid Spencer24c4a8f2007-02-25 01:56:07 +0000996 return APInt(BitWidth,
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000997 (((int64_t(VAL) << SignBit) >> SignBit) >> shiftAmt));
998 }
Zhou Sheng0b706b12007-02-08 14:35:19 +0000999 }
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001000
Reid Spencer46f9c942007-03-02 22:39:11 +00001001 // If all the bits were shifted out, the result is, technically, undefined.
1002 // We return -1 if it was negative, 0 otherwise. We check this early to avoid
1003 // issues in the algorithm below.
Chris Lattnera5ae15e2007-05-03 18:15:36 +00001004 if (shiftAmt == BitWidth) {
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001005 if (isNegative())
Zhou Shengbfde7d62008-06-05 13:27:38 +00001006 return APInt(BitWidth, -1ULL, true);
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001007 else
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001008 return APInt(BitWidth, 0);
Chris Lattnera5ae15e2007-05-03 18:15:36 +00001009 }
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001010
1011 // Create some space for the result.
1012 uint64_t * val = new uint64_t[getNumWords()];
1013
Reid Spencer46f9c942007-03-02 22:39:11 +00001014 // Compute some values needed by the following shift algorithms
Chris Lattner455e9ab2009-01-21 18:09:24 +00001015 unsigned wordShift = shiftAmt % APINT_BITS_PER_WORD; // bits to shift per word
1016 unsigned offset = shiftAmt / APINT_BITS_PER_WORD; // word offset for shift
1017 unsigned breakWord = getNumWords() - 1 - offset; // last word affected
1018 unsigned bitsInWord = whichBit(BitWidth); // how many bits in last word?
Reid Spencer46f9c942007-03-02 22:39:11 +00001019 if (bitsInWord == 0)
1020 bitsInWord = APINT_BITS_PER_WORD;
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001021
1022 // If we are shifting whole words, just move whole words
1023 if (wordShift == 0) {
Reid Spencer46f9c942007-03-02 22:39:11 +00001024 // Move the words containing significant bits
Chris Lattner455e9ab2009-01-21 18:09:24 +00001025 for (unsigned i = 0; i <= breakWord; ++i)
Reid Spencer46f9c942007-03-02 22:39:11 +00001026 val[i] = pVal[i+offset]; // move whole word
1027
1028 // Adjust the top significant word for sign bit fill, if negative
1029 if (isNegative())
1030 if (bitsInWord < APINT_BITS_PER_WORD)
1031 val[breakWord] |= ~0ULL << bitsInWord; // set high bits
1032 } else {
1033 // Shift the low order words
Chris Lattner455e9ab2009-01-21 18:09:24 +00001034 for (unsigned i = 0; i < breakWord; ++i) {
Reid Spencer46f9c942007-03-02 22:39:11 +00001035 // This combines the shifted corresponding word with the low bits from
1036 // the next word (shifted into this word's high bits).
1037 val[i] = (pVal[i+offset] >> wordShift) |
1038 (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift));
1039 }
1040
1041 // Shift the break word. In this case there are no bits from the next word
1042 // to include in this word.
1043 val[breakWord] = pVal[breakWord+offset] >> wordShift;
1044
1045 // Deal with sign extenstion in the break word, and possibly the word before
1046 // it.
Chris Lattnera5ae15e2007-05-03 18:15:36 +00001047 if (isNegative()) {
Reid Spencer46f9c942007-03-02 22:39:11 +00001048 if (wordShift > bitsInWord) {
1049 if (breakWord > 0)
1050 val[breakWord-1] |=
1051 ~0ULL << (APINT_BITS_PER_WORD - (wordShift - bitsInWord));
1052 val[breakWord] |= ~0ULL;
1053 } else
1054 val[breakWord] |= (~0ULL << (bitsInWord - wordShift));
Chris Lattnera5ae15e2007-05-03 18:15:36 +00001055 }
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001056 }
1057
Reid Spencer46f9c942007-03-02 22:39:11 +00001058 // Remaining words are 0 or -1, just assign them.
1059 uint64_t fillValue = (isNegative() ? -1ULL : 0);
Chris Lattner455e9ab2009-01-21 18:09:24 +00001060 for (unsigned i = breakWord+1; i < getNumWords(); ++i)
Reid Spencer46f9c942007-03-02 22:39:11 +00001061 val[i] = fillValue;
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001062 return APInt(val, BitWidth).clearUnusedBits();
Zhou Sheng0b706b12007-02-08 14:35:19 +00001063}
1064
Zhou Shengff4304f2007-02-09 07:48:24 +00001065/// Logical right-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +00001066/// @brief Logical right-shift function.
Dan Gohmancf609572008-02-29 01:40:47 +00001067APInt APInt::lshr(const APInt &shiftAmt) const {
Chris Lattner455e9ab2009-01-21 18:09:24 +00001068 return lshr((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohmancf609572008-02-29 01:40:47 +00001069}
1070
1071/// Logical right-shift this APInt by shiftAmt.
1072/// @brief Logical right-shift function.
Chris Lattner455e9ab2009-01-21 18:09:24 +00001073APInt APInt::lshr(unsigned shiftAmt) const {
Chris Lattnera5ae15e2007-05-03 18:15:36 +00001074 if (isSingleWord()) {
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001075 if (shiftAmt == BitWidth)
1076 return APInt(BitWidth, 0);
1077 else
1078 return APInt(BitWidth, this->VAL >> shiftAmt);
Chris Lattnera5ae15e2007-05-03 18:15:36 +00001079 }
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001080
Reid Spencerba81c2b2007-02-26 01:19:48 +00001081 // If all the bits were shifted out, the result is 0. This avoids issues
1082 // with shifting by the size of the integer type, which produces undefined
1083 // results. We define these "undefined results" to always be 0.
1084 if (shiftAmt == BitWidth)
1085 return APInt(BitWidth, 0);
1086
Reid Spencer02ae8b72007-05-17 06:26:29 +00001087 // If none of the bits are shifted out, the result is *this. This avoids
Nick Lewycky4bd47872009-01-19 17:42:33 +00001088 // issues with shifting by the size of the integer type, which produces
Reid Spencer02ae8b72007-05-17 06:26:29 +00001089 // undefined results in the code below. This is also an optimization.
1090 if (shiftAmt == 0)
1091 return *this;
1092
Reid Spencerba81c2b2007-02-26 01:19:48 +00001093 // Create some space for the result.
1094 uint64_t * val = new uint64_t[getNumWords()];
1095
1096 // If we are shifting less than a word, compute the shift with a simple carry
1097 if (shiftAmt < APINT_BITS_PER_WORD) {
1098 uint64_t carry = 0;
1099 for (int i = getNumWords()-1; i >= 0; --i) {
Reid Spenceraf8fb192007-03-01 05:39:56 +00001100 val[i] = (pVal[i] >> shiftAmt) | carry;
Reid Spencerba81c2b2007-02-26 01:19:48 +00001101 carry = pVal[i] << (APINT_BITS_PER_WORD - shiftAmt);
1102 }
1103 return APInt(val, BitWidth).clearUnusedBits();
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001104 }
1105
Reid Spencerba81c2b2007-02-26 01:19:48 +00001106 // Compute some values needed by the remaining shift algorithms
Chris Lattner455e9ab2009-01-21 18:09:24 +00001107 unsigned wordShift = shiftAmt % APINT_BITS_PER_WORD;
1108 unsigned offset = shiftAmt / APINT_BITS_PER_WORD;
Reid Spencerba81c2b2007-02-26 01:19:48 +00001109
1110 // If we are shifting whole words, just move whole words
1111 if (wordShift == 0) {
Chris Lattner455e9ab2009-01-21 18:09:24 +00001112 for (unsigned i = 0; i < getNumWords() - offset; ++i)
Reid Spencerba81c2b2007-02-26 01:19:48 +00001113 val[i] = pVal[i+offset];
Chris Lattner455e9ab2009-01-21 18:09:24 +00001114 for (unsigned i = getNumWords()-offset; i < getNumWords(); i++)
Reid Spencerba81c2b2007-02-26 01:19:48 +00001115 val[i] = 0;
1116 return APInt(val,BitWidth).clearUnusedBits();
1117 }
1118
1119 // Shift the low order words
Chris Lattner455e9ab2009-01-21 18:09:24 +00001120 unsigned breakWord = getNumWords() - offset -1;
1121 for (unsigned i = 0; i < breakWord; ++i)
Reid Spenceraf8fb192007-03-01 05:39:56 +00001122 val[i] = (pVal[i+offset] >> wordShift) |
1123 (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift));
Reid Spencerba81c2b2007-02-26 01:19:48 +00001124 // Shift the break word.
1125 val[breakWord] = pVal[breakWord+offset] >> wordShift;
1126
1127 // Remaining words are 0
Chris Lattner455e9ab2009-01-21 18:09:24 +00001128 for (unsigned i = breakWord+1; i < getNumWords(); ++i)
Reid Spencerba81c2b2007-02-26 01:19:48 +00001129 val[i] = 0;
1130 return APInt(val, BitWidth).clearUnusedBits();
Zhou Sheng0b706b12007-02-08 14:35:19 +00001131}
1132
Zhou Shengff4304f2007-02-09 07:48:24 +00001133/// Left-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +00001134/// @brief Left-shift function.
Dan Gohmancf609572008-02-29 01:40:47 +00001135APInt APInt::shl(const APInt &shiftAmt) const {
Nick Lewycky4bd47872009-01-19 17:42:33 +00001136 // It's undefined behavior in C to shift by BitWidth or greater.
Chris Lattner455e9ab2009-01-21 18:09:24 +00001137 return shl((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohmancf609572008-02-29 01:40:47 +00001138}
1139
Chris Lattner455e9ab2009-01-21 18:09:24 +00001140APInt APInt::shlSlowCase(unsigned shiftAmt) const {
Reid Spencer87553802007-02-25 00:56:44 +00001141 // If all the bits were shifted out, the result is 0. This avoids issues
1142 // with shifting by the size of the integer type, which produces undefined
1143 // results. We define these "undefined results" to always be 0.
1144 if (shiftAmt == BitWidth)
1145 return APInt(BitWidth, 0);
1146
Reid Spencer92c72832007-05-12 18:01:57 +00001147 // If none of the bits are shifted out, the result is *this. This avoids a
1148 // lshr by the words size in the loop below which can produce incorrect
1149 // results. It also avoids the expensive computation below for a common case.
1150 if (shiftAmt == 0)
1151 return *this;
1152
Reid Spencer87553802007-02-25 00:56:44 +00001153 // Create some space for the result.
1154 uint64_t * val = new uint64_t[getNumWords()];
1155
1156 // If we are shifting less than a word, do it the easy way
1157 if (shiftAmt < APINT_BITS_PER_WORD) {
1158 uint64_t carry = 0;
Chris Lattner455e9ab2009-01-21 18:09:24 +00001159 for (unsigned i = 0; i < getNumWords(); i++) {
Reid Spencer87553802007-02-25 00:56:44 +00001160 val[i] = pVal[i] << shiftAmt | carry;
1161 carry = pVal[i] >> (APINT_BITS_PER_WORD - shiftAmt);
1162 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001163 return APInt(val, BitWidth).clearUnusedBits();
Reid Spencer5bce8542007-02-24 20:19:37 +00001164 }
1165
Reid Spencer87553802007-02-25 00:56:44 +00001166 // Compute some values needed by the remaining shift algorithms
Chris Lattner455e9ab2009-01-21 18:09:24 +00001167 unsigned wordShift = shiftAmt % APINT_BITS_PER_WORD;
1168 unsigned offset = shiftAmt / APINT_BITS_PER_WORD;
Reid Spencer87553802007-02-25 00:56:44 +00001169
1170 // If we are shifting whole words, just move whole words
1171 if (wordShift == 0) {
Chris Lattner455e9ab2009-01-21 18:09:24 +00001172 for (unsigned i = 0; i < offset; i++)
Reid Spencer87553802007-02-25 00:56:44 +00001173 val[i] = 0;
Chris Lattner455e9ab2009-01-21 18:09:24 +00001174 for (unsigned i = offset; i < getNumWords(); i++)
Reid Spencer87553802007-02-25 00:56:44 +00001175 val[i] = pVal[i-offset];
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001176 return APInt(val,BitWidth).clearUnusedBits();
Reid Spencer5bce8542007-02-24 20:19:37 +00001177 }
Reid Spencer87553802007-02-25 00:56:44 +00001178
1179 // Copy whole words from this to Result.
Chris Lattner455e9ab2009-01-21 18:09:24 +00001180 unsigned i = getNumWords() - 1;
Reid Spencer87553802007-02-25 00:56:44 +00001181 for (; i > offset; --i)
1182 val[i] = pVal[i-offset] << wordShift |
1183 pVal[i-offset-1] >> (APINT_BITS_PER_WORD - wordShift);
Reid Spencer438d71e2007-02-25 01:08:58 +00001184 val[offset] = pVal[0] << wordShift;
Reid Spencer87553802007-02-25 00:56:44 +00001185 for (i = 0; i < offset; ++i)
1186 val[i] = 0;
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001187 return APInt(val, BitWidth).clearUnusedBits();
Zhou Sheng0b706b12007-02-08 14:35:19 +00001188}
1189
Dan Gohmancf609572008-02-29 01:40:47 +00001190APInt APInt::rotl(const APInt &rotateAmt) const {
Chris Lattner455e9ab2009-01-21 18:09:24 +00001191 return rotl((unsigned)rotateAmt.getLimitedValue(BitWidth));
Dan Gohmancf609572008-02-29 01:40:47 +00001192}
1193
Chris Lattner455e9ab2009-01-21 18:09:24 +00001194APInt APInt::rotl(unsigned rotateAmt) const {
Reid Spencer69944e82007-05-14 00:15:28 +00001195 if (rotateAmt == 0)
1196 return *this;
Reid Spencer19dc32a2007-05-13 23:44:59 +00001197 // Don't get too fancy, just use existing shift/or facilities
1198 APInt hi(*this);
1199 APInt lo(*this);
1200 hi.shl(rotateAmt);
1201 lo.lshr(BitWidth - rotateAmt);
1202 return hi | lo;
1203}
1204
Dan Gohmancf609572008-02-29 01:40:47 +00001205APInt APInt::rotr(const APInt &rotateAmt) const {
Chris Lattner455e9ab2009-01-21 18:09:24 +00001206 return rotr((unsigned)rotateAmt.getLimitedValue(BitWidth));
Dan Gohmancf609572008-02-29 01:40:47 +00001207}
1208
Chris Lattner455e9ab2009-01-21 18:09:24 +00001209APInt APInt::rotr(unsigned rotateAmt) const {
Reid Spencer69944e82007-05-14 00:15:28 +00001210 if (rotateAmt == 0)
1211 return *this;
Reid Spencer19dc32a2007-05-13 23:44:59 +00001212 // Don't get too fancy, just use existing shift/or facilities
1213 APInt hi(*this);
1214 APInt lo(*this);
1215 lo.lshr(rotateAmt);
1216 hi.shl(BitWidth - rotateAmt);
1217 return hi | lo;
1218}
Reid Spenceraf8fb192007-03-01 05:39:56 +00001219
1220// Square Root - this method computes and returns the square root of "this".
1221// Three mechanisms are used for computation. For small values (<= 5 bits),
1222// a table lookup is done. This gets some performance for common cases. For
1223// values using less than 52 bits, the value is converted to double and then
1224// the libc sqrt function is called. The result is rounded and then converted
1225// back to a uint64_t which is then used to construct the result. Finally,
1226// the Babylonian method for computing square roots is used.
1227APInt APInt::sqrt() const {
1228
1229 // Determine the magnitude of the value.
Chris Lattner455e9ab2009-01-21 18:09:24 +00001230 unsigned magnitude = getActiveBits();
Reid Spenceraf8fb192007-03-01 05:39:56 +00001231
1232 // Use a fast table for some small values. This also gets rid of some
1233 // rounding errors in libc sqrt for small values.
1234 if (magnitude <= 5) {
Reid Spencer4e1e87f2007-03-01 17:47:31 +00001235 static const uint8_t results[32] = {
Reid Spencerb5ca2cd2007-03-01 06:23:32 +00001236 /* 0 */ 0,
1237 /* 1- 2 */ 1, 1,
1238 /* 3- 6 */ 2, 2, 2, 2,
1239 /* 7-12 */ 3, 3, 3, 3, 3, 3,
1240 /* 13-20 */ 4, 4, 4, 4, 4, 4, 4, 4,
1241 /* 21-30 */ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
1242 /* 31 */ 6
1243 };
1244 return APInt(BitWidth, results[ (isSingleWord() ? VAL : pVal[0]) ]);
Reid Spenceraf8fb192007-03-01 05:39:56 +00001245 }
1246
1247 // If the magnitude of the value fits in less than 52 bits (the precision of
1248 // an IEEE double precision floating point value), then we can use the
1249 // libc sqrt function which will probably use a hardware sqrt computation.
1250 // This should be faster than the algorithm below.
Jeff Cohenca5183d2007-03-05 00:00:42 +00001251 if (magnitude < 52) {
1252#ifdef _MSC_VER
1253 // Amazingly, VC++ doesn't have round().
1254 return APInt(BitWidth,
1255 uint64_t(::sqrt(double(isSingleWord()?VAL:pVal[0]))) + 0.5);
1256#else
Reid Spenceraf8fb192007-03-01 05:39:56 +00001257 return APInt(BitWidth,
1258 uint64_t(::round(::sqrt(double(isSingleWord()?VAL:pVal[0])))));
Jeff Cohenca5183d2007-03-05 00:00:42 +00001259#endif
1260 }
Reid Spenceraf8fb192007-03-01 05:39:56 +00001261
1262 // Okay, all the short cuts are exhausted. We must compute it. The following
1263 // is a classical Babylonian method for computing the square root. This code
1264 // was adapted to APINt from a wikipedia article on such computations.
1265 // See http://www.wikipedia.org/ and go to the page named
1266 // Calculate_an_integer_square_root.
Chris Lattner455e9ab2009-01-21 18:09:24 +00001267 unsigned nbits = BitWidth, i = 4;
Reid Spenceraf8fb192007-03-01 05:39:56 +00001268 APInt testy(BitWidth, 16);
1269 APInt x_old(BitWidth, 1);
1270 APInt x_new(BitWidth, 0);
1271 APInt two(BitWidth, 2);
1272
1273 // Select a good starting value using binary logarithms.
1274 for (;; i += 2, testy = testy.shl(2))
1275 if (i >= nbits || this->ule(testy)) {
1276 x_old = x_old.shl(i / 2);
1277 break;
1278 }
1279
1280 // Use the Babylonian method to arrive at the integer square root:
1281 for (;;) {
1282 x_new = (this->udiv(x_old) + x_old).udiv(two);
1283 if (x_old.ule(x_new))
1284 break;
1285 x_old = x_new;
1286 }
1287
1288 // Make sure we return the closest approximation
Reid Spencerf09aef72007-03-02 04:21:55 +00001289 // NOTE: The rounding calculation below is correct. It will produce an
1290 // off-by-one discrepancy with results from pari/gp. That discrepancy has been
1291 // determined to be a rounding issue with pari/gp as it begins to use a
1292 // floating point representation after 192 bits. There are no discrepancies
1293 // between this algorithm and pari/gp for bit widths < 192 bits.
Reid Spenceraf8fb192007-03-01 05:39:56 +00001294 APInt square(x_old * x_old);
1295 APInt nextSquare((x_old + 1) * (x_old +1));
1296 if (this->ult(square))
1297 return x_old;
Reid Spencerf09aef72007-03-02 04:21:55 +00001298 else if (this->ule(nextSquare)) {
1299 APInt midpoint((nextSquare - square).udiv(two));
1300 APInt offset(*this - square);
1301 if (offset.ult(midpoint))
Reid Spenceraf8fb192007-03-01 05:39:56 +00001302 return x_old;
Reid Spencerf09aef72007-03-02 04:21:55 +00001303 else
1304 return x_old + 1;
1305 } else
Reid Spenceraf8fb192007-03-01 05:39:56 +00001306 assert(0 && "Error in APInt::sqrt computation");
1307 return x_old + 1;
1308}
1309
Wojciech Matyjewicz300c6c52008-06-23 19:39:50 +00001310/// Computes the multiplicative inverse of this APInt for a given modulo. The
1311/// iterative extended Euclidean algorithm is used to solve for this value,
1312/// however we simplify it to speed up calculating only the inverse, and take
1313/// advantage of div+rem calculations. We also use some tricks to avoid copying
1314/// (potentially large) APInts around.
1315APInt APInt::multiplicativeInverse(const APInt& modulo) const {
1316 assert(ult(modulo) && "This APInt must be smaller than the modulo");
1317
1318 // Using the properties listed at the following web page (accessed 06/21/08):
1319 // http://www.numbertheory.org/php/euclid.html
1320 // (especially the properties numbered 3, 4 and 9) it can be proved that
1321 // BitWidth bits suffice for all the computations in the algorithm implemented
1322 // below. More precisely, this number of bits suffice if the multiplicative
1323 // inverse exists, but may not suffice for the general extended Euclidean
1324 // algorithm.
1325
1326 APInt r[2] = { modulo, *this };
1327 APInt t[2] = { APInt(BitWidth, 0), APInt(BitWidth, 1) };
1328 APInt q(BitWidth, 0);
1329
1330 unsigned i;
1331 for (i = 0; r[i^1] != 0; i ^= 1) {
1332 // An overview of the math without the confusing bit-flipping:
1333 // q = r[i-2] / r[i-1]
1334 // r[i] = r[i-2] % r[i-1]
1335 // t[i] = t[i-2] - t[i-1] * q
1336 udivrem(r[i], r[i^1], q, r[i]);
1337 t[i] -= t[i^1] * q;
1338 }
1339
1340 // If this APInt and the modulo are not coprime, there is no multiplicative
1341 // inverse, so return 0. We check this by looking at the next-to-last
1342 // remainder, which is the gcd(*this,modulo) as calculated by the Euclidean
1343 // algorithm.
1344 if (r[i] != 1)
1345 return APInt(BitWidth, 0);
1346
1347 // The next-to-last t is the multiplicative inverse. However, we are
1348 // interested in a positive inverse. Calcuate a positive one from a negative
1349 // one if necessary. A simple addition of the modulo suffices because
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00001350 // abs(t[i]) is known to be less than *this/2 (see the link above).
Wojciech Matyjewicz300c6c52008-06-23 19:39:50 +00001351 return t[i].isNegative() ? t[i] + modulo : t[i];
1352}
1353
Reid Spencer9c0696f2007-02-20 08:51:03 +00001354/// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
1355/// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
1356/// variables here have the same names as in the algorithm. Comments explain
1357/// the algorithm and any deviation from it.
Chris Lattner455e9ab2009-01-21 18:09:24 +00001358static void KnuthDiv(unsigned *u, unsigned *v, unsigned *q, unsigned* r,
1359 unsigned m, unsigned n) {
Reid Spencer9c0696f2007-02-20 08:51:03 +00001360 assert(u && "Must provide dividend");
1361 assert(v && "Must provide divisor");
1362 assert(q && "Must provide quotient");
Reid Spencer9d6c9192007-02-24 03:58:46 +00001363 assert(u != v && u != q && v != q && "Must us different memory");
Reid Spencer9c0696f2007-02-20 08:51:03 +00001364 assert(n>1 && "n must be > 1");
1365
1366 // Knuth uses the value b as the base of the number system. In our case b
1367 // is 2^31 so we just set it to -1u.
1368 uint64_t b = uint64_t(1) << 32;
1369
Chris Lattnerfad86b02008-08-17 07:19:36 +00001370#if 0
Reid Spencer9d6c9192007-02-24 03:58:46 +00001371 DEBUG(cerr << "KnuthDiv: m=" << m << " n=" << n << '\n');
1372 DEBUG(cerr << "KnuthDiv: original:");
1373 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << std::setbase(16) << u[i]);
1374 DEBUG(cerr << " by");
1375 DEBUG(for (int i = n; i >0; i--) cerr << " " << std::setbase(16) << v[i-1]);
1376 DEBUG(cerr << '\n');
Chris Lattnerfad86b02008-08-17 07:19:36 +00001377#endif
Reid Spencer9c0696f2007-02-20 08:51:03 +00001378 // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
1379 // u and v by d. Note that we have taken Knuth's advice here to use a power
1380 // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
1381 // 2 allows us to shift instead of multiply and it is easy to determine the
1382 // shift amount from the leading zeros. We are basically normalizing the u
1383 // and v so that its high bits are shifted to the top of v's range without
1384 // overflow. Note that this can require an extra word in u so that u must
1385 // be of length m+n+1.
Chris Lattner455e9ab2009-01-21 18:09:24 +00001386 unsigned shift = CountLeadingZeros_32(v[n-1]);
1387 unsigned v_carry = 0;
1388 unsigned u_carry = 0;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001389 if (shift) {
Chris Lattner455e9ab2009-01-21 18:09:24 +00001390 for (unsigned i = 0; i < m+n; ++i) {
1391 unsigned u_tmp = u[i] >> (32 - shift);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001392 u[i] = (u[i] << shift) | u_carry;
1393 u_carry = u_tmp;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001394 }
Chris Lattner455e9ab2009-01-21 18:09:24 +00001395 for (unsigned i = 0; i < n; ++i) {
1396 unsigned v_tmp = v[i] >> (32 - shift);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001397 v[i] = (v[i] << shift) | v_carry;
1398 v_carry = v_tmp;
1399 }
1400 }
1401 u[m+n] = u_carry;
Chris Lattnerfad86b02008-08-17 07:19:36 +00001402#if 0
Reid Spencer9d6c9192007-02-24 03:58:46 +00001403 DEBUG(cerr << "KnuthDiv: normal:");
1404 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << std::setbase(16) << u[i]);
1405 DEBUG(cerr << " by");
1406 DEBUG(for (int i = n; i >0; i--) cerr << " " << std::setbase(16) << v[i-1]);
1407 DEBUG(cerr << '\n');
Chris Lattnerfad86b02008-08-17 07:19:36 +00001408#endif
Reid Spencer9c0696f2007-02-20 08:51:03 +00001409
1410 // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
1411 int j = m;
1412 do {
Reid Spencer9d6c9192007-02-24 03:58:46 +00001413 DEBUG(cerr << "KnuthDiv: quotient digit #" << j << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001414 // D3. [Calculate q'.].
1415 // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
1416 // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
1417 // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
1418 // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test
1419 // on v[n-2] determines at high speed most of the cases in which the trial
1420 // value qp is one too large, and it eliminates all cases where qp is two
1421 // too large.
Reid Spencer92904632007-02-23 01:57:13 +00001422 uint64_t dividend = ((uint64_t(u[j+n]) << 32) + u[j+n-1]);
Reid Spencer9d6c9192007-02-24 03:58:46 +00001423 DEBUG(cerr << "KnuthDiv: dividend == " << dividend << '\n');
Reid Spencer92904632007-02-23 01:57:13 +00001424 uint64_t qp = dividend / v[n-1];
1425 uint64_t rp = dividend % v[n-1];
Reid Spencer9c0696f2007-02-20 08:51:03 +00001426 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1427 qp--;
1428 rp += v[n-1];
Reid Spencer610fad82007-02-24 10:01:42 +00001429 if (rp < b && (qp == b || qp*v[n-2] > b*rp + u[j+n-2]))
Reid Spencer9d6c9192007-02-24 03:58:46 +00001430 qp--;
Reid Spencer92904632007-02-23 01:57:13 +00001431 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001432 DEBUG(cerr << "KnuthDiv: qp == " << qp << ", rp == " << rp << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001433
Reid Spencer92904632007-02-23 01:57:13 +00001434 // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with
1435 // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation
1436 // consists of a simple multiplication by a one-place number, combined with
Reid Spencer610fad82007-02-24 10:01:42 +00001437 // a subtraction.
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001438 bool isNeg = false;
Chris Lattner455e9ab2009-01-21 18:09:24 +00001439 for (unsigned i = 0; i < n; ++i) {
Reid Spencer610fad82007-02-24 10:01:42 +00001440 uint64_t u_tmp = uint64_t(u[j+i]) | (uint64_t(u[j+i+1]) << 32);
Reid Spencer9d6c9192007-02-24 03:58:46 +00001441 uint64_t subtrahend = uint64_t(qp) * uint64_t(v[i]);
Reid Spencer610fad82007-02-24 10:01:42 +00001442 bool borrow = subtrahend > u_tmp;
Reid Spencer9d6c9192007-02-24 03:58:46 +00001443 DEBUG(cerr << "KnuthDiv: u_tmp == " << u_tmp
Reid Spencer610fad82007-02-24 10:01:42 +00001444 << ", subtrahend == " << subtrahend
1445 << ", borrow = " << borrow << '\n');
Reid Spencer9d6c9192007-02-24 03:58:46 +00001446
Reid Spencer610fad82007-02-24 10:01:42 +00001447 uint64_t result = u_tmp - subtrahend;
Chris Lattner455e9ab2009-01-21 18:09:24 +00001448 unsigned k = j + i;
1449 u[k++] = (unsigned)(result & (b-1)); // subtract low word
1450 u[k++] = (unsigned)(result >> 32); // subtract high word
Reid Spencer610fad82007-02-24 10:01:42 +00001451 while (borrow && k <= m+n) { // deal with borrow to the left
1452 borrow = u[k] == 0;
1453 u[k]--;
1454 k++;
1455 }
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001456 isNeg |= borrow;
Reid Spencer610fad82007-02-24 10:01:42 +00001457 DEBUG(cerr << "KnuthDiv: u[j+i] == " << u[j+i] << ", u[j+i+1] == " <<
1458 u[j+i+1] << '\n');
Reid Spencer9d6c9192007-02-24 03:58:46 +00001459 }
1460 DEBUG(cerr << "KnuthDiv: after subtraction:");
1461 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << u[i]);
1462 DEBUG(cerr << '\n');
Reid Spencer610fad82007-02-24 10:01:42 +00001463 // The digits (u[j+n]...u[j]) should be kept positive; if the result of
1464 // this step is actually negative, (u[j+n]...u[j]) should be left as the
1465 // true value plus b**(n+1), namely as the b's complement of
Reid Spencer92904632007-02-23 01:57:13 +00001466 // the true value, and a "borrow" to the left should be remembered.
1467 //
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001468 if (isNeg) {
Reid Spencer610fad82007-02-24 10:01:42 +00001469 bool carry = true; // true because b's complement is "complement + 1"
Chris Lattner455e9ab2009-01-21 18:09:24 +00001470 for (unsigned i = 0; i <= m+n; ++i) {
Reid Spencer610fad82007-02-24 10:01:42 +00001471 u[i] = ~u[i] + carry; // b's complement
1472 carry = carry && u[i] == 0;
Reid Spencer9d6c9192007-02-24 03:58:46 +00001473 }
Reid Spencer92904632007-02-23 01:57:13 +00001474 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001475 DEBUG(cerr << "KnuthDiv: after complement:");
1476 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << u[i]);
1477 DEBUG(cerr << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001478
1479 // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
1480 // negative, go to step D6; otherwise go on to step D7.
Chris Lattner455e9ab2009-01-21 18:09:24 +00001481 q[j] = (unsigned)qp;
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001482 if (isNeg) {
Reid Spencer9c0696f2007-02-20 08:51:03 +00001483 // D6. [Add back]. The probability that this step is necessary is very
1484 // small, on the order of only 2/b. Make sure that test data accounts for
Reid Spencer92904632007-02-23 01:57:13 +00001485 // this possibility. Decrease q[j] by 1
1486 q[j]--;
1487 // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]).
1488 // A carry will occur to the left of u[j+n], and it should be ignored
1489 // since it cancels with the borrow that occurred in D4.
1490 bool carry = false;
Chris Lattner455e9ab2009-01-21 18:09:24 +00001491 for (unsigned i = 0; i < n; i++) {
1492 unsigned limit = std::min(u[j+i],v[i]);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001493 u[j+i] += v[i] + carry;
Reid Spencer9d6c9192007-02-24 03:58:46 +00001494 carry = u[j+i] < limit || (carry && u[j+i] == limit);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001495 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001496 u[j+n] += carry;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001497 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001498 DEBUG(cerr << "KnuthDiv: after correction:");
1499 DEBUG(for (int i = m+n; i >=0; i--) cerr <<" " << u[i]);
1500 DEBUG(cerr << "\nKnuthDiv: digit result = " << q[j] << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001501
Reid Spencer92904632007-02-23 01:57:13 +00001502 // D7. [Loop on j.] Decrease j by one. Now if j >= 0, go back to D3.
1503 } while (--j >= 0);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001504
Reid Spencer9d6c9192007-02-24 03:58:46 +00001505 DEBUG(cerr << "KnuthDiv: quotient:");
1506 DEBUG(for (int i = m; i >=0; i--) cerr <<" " << q[i]);
1507 DEBUG(cerr << '\n');
1508
Reid Spencer9c0696f2007-02-20 08:51:03 +00001509 // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
1510 // remainder may be obtained by dividing u[...] by d. If r is non-null we
1511 // compute the remainder (urem uses this).
1512 if (r) {
1513 // The value d is expressed by the "shift" value above since we avoided
1514 // multiplication by d by using a shift left. So, all we have to do is
1515 // shift right here. In order to mak
Reid Spencer1050ec52007-02-24 20:38:01 +00001516 if (shift) {
Chris Lattner455e9ab2009-01-21 18:09:24 +00001517 unsigned carry = 0;
Reid Spencer1050ec52007-02-24 20:38:01 +00001518 DEBUG(cerr << "KnuthDiv: remainder:");
1519 for (int i = n-1; i >= 0; i--) {
1520 r[i] = (u[i] >> shift) | carry;
1521 carry = u[i] << (32 - shift);
1522 DEBUG(cerr << " " << r[i]);
1523 }
1524 } else {
1525 for (int i = n-1; i >= 0; i--) {
1526 r[i] = u[i];
1527 DEBUG(cerr << " " << r[i]);
1528 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001529 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001530 DEBUG(cerr << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001531 }
Chris Lattnerfad86b02008-08-17 07:19:36 +00001532#if 0
Reid Spencer9d6c9192007-02-24 03:58:46 +00001533 DEBUG(cerr << std::setbase(10) << '\n');
Chris Lattnerfad86b02008-08-17 07:19:36 +00001534#endif
Reid Spencer9c0696f2007-02-20 08:51:03 +00001535}
1536
Chris Lattner455e9ab2009-01-21 18:09:24 +00001537void APInt::divide(const APInt LHS, unsigned lhsWords,
1538 const APInt &RHS, unsigned rhsWords,
Reid Spencer9c0696f2007-02-20 08:51:03 +00001539 APInt *Quotient, APInt *Remainder)
1540{
1541 assert(lhsWords >= rhsWords && "Fractional result");
1542
1543 // First, compose the values into an array of 32-bit words instead of
1544 // 64-bit words. This is a necessity of both the "short division" algorithm
1545 // and the the Knuth "classical algorithm" which requires there to be native
1546 // operations for +, -, and * on an m bit value with an m*2 bit result. We
1547 // can't use 64-bit operands here because we don't have native results of
1548 // 128-bits. Furthremore, casting the 64-bit values to 32-bit values won't
1549 // work on large-endian machines.
Chris Lattner455e9ab2009-01-21 18:09:24 +00001550 uint64_t mask = ~0ull >> (sizeof(unsigned)*8);
1551 unsigned n = rhsWords * 2;
1552 unsigned m = (lhsWords * 2) - n;
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001553
1554 // Allocate space for the temporary values we need either on the stack, if
1555 // it will fit, or on the heap if it won't.
Chris Lattner455e9ab2009-01-21 18:09:24 +00001556 unsigned SPACE[128];
1557 unsigned *U = 0;
1558 unsigned *V = 0;
1559 unsigned *Q = 0;
1560 unsigned *R = 0;
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001561 if ((Remainder?4:3)*n+2*m+1 <= 128) {
1562 U = &SPACE[0];
1563 V = &SPACE[m+n+1];
1564 Q = &SPACE[(m+n+1) + n];
1565 if (Remainder)
1566 R = &SPACE[(m+n+1) + n + (m+n)];
1567 } else {
Chris Lattner455e9ab2009-01-21 18:09:24 +00001568 U = new unsigned[m + n + 1];
1569 V = new unsigned[n];
1570 Q = new unsigned[m+n];
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001571 if (Remainder)
Chris Lattner455e9ab2009-01-21 18:09:24 +00001572 R = new unsigned[n];
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001573 }
1574
1575 // Initialize the dividend
Chris Lattner455e9ab2009-01-21 18:09:24 +00001576 memset(U, 0, (m+n+1)*sizeof(unsigned));
Reid Spencer9c0696f2007-02-20 08:51:03 +00001577 for (unsigned i = 0; i < lhsWords; ++i) {
Reid Spencer15aab8a2007-02-22 00:58:45 +00001578 uint64_t tmp = (LHS.getNumWords() == 1 ? LHS.VAL : LHS.pVal[i]);
Chris Lattner455e9ab2009-01-21 18:09:24 +00001579 U[i * 2] = (unsigned)(tmp & mask);
1580 U[i * 2 + 1] = (unsigned)(tmp >> (sizeof(unsigned)*8));
Reid Spencer9c0696f2007-02-20 08:51:03 +00001581 }
1582 U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
1583
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001584 // Initialize the divisor
Chris Lattner455e9ab2009-01-21 18:09:24 +00001585 memset(V, 0, (n)*sizeof(unsigned));
Reid Spencer9c0696f2007-02-20 08:51:03 +00001586 for (unsigned i = 0; i < rhsWords; ++i) {
Reid Spencer15aab8a2007-02-22 00:58:45 +00001587 uint64_t tmp = (RHS.getNumWords() == 1 ? RHS.VAL : RHS.pVal[i]);
Chris Lattner455e9ab2009-01-21 18:09:24 +00001588 V[i * 2] = (unsigned)(tmp & mask);
1589 V[i * 2 + 1] = (unsigned)(tmp >> (sizeof(unsigned)*8));
Reid Spencer9c0696f2007-02-20 08:51:03 +00001590 }
1591
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001592 // initialize the quotient and remainder
Chris Lattner455e9ab2009-01-21 18:09:24 +00001593 memset(Q, 0, (m+n) * sizeof(unsigned));
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001594 if (Remainder)
Chris Lattner455e9ab2009-01-21 18:09:24 +00001595 memset(R, 0, n * sizeof(unsigned));
Reid Spencer9c0696f2007-02-20 08:51:03 +00001596
1597 // Now, adjust m and n for the Knuth division. n is the number of words in
1598 // the divisor. m is the number of words by which the dividend exceeds the
1599 // divisor (i.e. m+n is the length of the dividend). These sizes must not
1600 // contain any zero words or the Knuth algorithm fails.
1601 for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
1602 n--;
1603 m++;
1604 }
1605 for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
1606 m--;
1607
1608 // If we're left with only a single word for the divisor, Knuth doesn't work
1609 // so we implement the short division algorithm here. This is much simpler
1610 // and faster because we are certain that we can divide a 64-bit quantity
1611 // by a 32-bit quantity at hardware speed and short division is simply a
1612 // series of such operations. This is just like doing short division but we
1613 // are using base 2^32 instead of base 10.
1614 assert(n != 0 && "Divide by zero?");
1615 if (n == 1) {
Chris Lattner455e9ab2009-01-21 18:09:24 +00001616 unsigned divisor = V[0];
1617 unsigned remainder = 0;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001618 for (int i = m+n-1; i >= 0; i--) {
1619 uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i];
1620 if (partial_dividend == 0) {
1621 Q[i] = 0;
1622 remainder = 0;
1623 } else if (partial_dividend < divisor) {
1624 Q[i] = 0;
Chris Lattner455e9ab2009-01-21 18:09:24 +00001625 remainder = (unsigned)partial_dividend;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001626 } else if (partial_dividend == divisor) {
1627 Q[i] = 1;
1628 remainder = 0;
1629 } else {
Chris Lattner455e9ab2009-01-21 18:09:24 +00001630 Q[i] = (unsigned)(partial_dividend / divisor);
1631 remainder = (unsigned)(partial_dividend - (Q[i] * divisor));
Reid Spencer9c0696f2007-02-20 08:51:03 +00001632 }
1633 }
1634 if (R)
1635 R[0] = remainder;
1636 } else {
1637 // Now we're ready to invoke the Knuth classical divide algorithm. In this
1638 // case n > 1.
1639 KnuthDiv(U, V, Q, R, m, n);
1640 }
1641
1642 // If the caller wants the quotient
1643 if (Quotient) {
1644 // Set up the Quotient value's memory.
1645 if (Quotient->BitWidth != LHS.BitWidth) {
1646 if (Quotient->isSingleWord())
1647 Quotient->VAL = 0;
1648 else
Reid Spencer9ac44112007-02-26 23:38:21 +00001649 delete [] Quotient->pVal;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001650 Quotient->BitWidth = LHS.BitWidth;
1651 if (!Quotient->isSingleWord())
Reid Spencere0cdd332007-02-21 08:21:52 +00001652 Quotient->pVal = getClearedMemory(Quotient->getNumWords());
Reid Spencer9c0696f2007-02-20 08:51:03 +00001653 } else
1654 Quotient->clear();
1655
1656 // The quotient is in Q. Reconstitute the quotient into Quotient's low
1657 // order words.
1658 if (lhsWords == 1) {
1659 uint64_t tmp =
1660 uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2));
1661 if (Quotient->isSingleWord())
1662 Quotient->VAL = tmp;
1663 else
1664 Quotient->pVal[0] = tmp;
1665 } else {
1666 assert(!Quotient->isSingleWord() && "Quotient APInt not large enough");
1667 for (unsigned i = 0; i < lhsWords; ++i)
1668 Quotient->pVal[i] =
1669 uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1670 }
1671 }
1672
1673 // If the caller wants the remainder
1674 if (Remainder) {
1675 // Set up the Remainder value's memory.
1676 if (Remainder->BitWidth != RHS.BitWidth) {
1677 if (Remainder->isSingleWord())
1678 Remainder->VAL = 0;
1679 else
Reid Spencer9ac44112007-02-26 23:38:21 +00001680 delete [] Remainder->pVal;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001681 Remainder->BitWidth = RHS.BitWidth;
1682 if (!Remainder->isSingleWord())
Reid Spencere0cdd332007-02-21 08:21:52 +00001683 Remainder->pVal = getClearedMemory(Remainder->getNumWords());
Reid Spencer9c0696f2007-02-20 08:51:03 +00001684 } else
1685 Remainder->clear();
1686
1687 // The remainder is in R. Reconstitute the remainder into Remainder's low
1688 // order words.
1689 if (rhsWords == 1) {
1690 uint64_t tmp =
1691 uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2));
1692 if (Remainder->isSingleWord())
1693 Remainder->VAL = tmp;
1694 else
1695 Remainder->pVal[0] = tmp;
1696 } else {
1697 assert(!Remainder->isSingleWord() && "Remainder APInt not large enough");
1698 for (unsigned i = 0; i < rhsWords; ++i)
1699 Remainder->pVal[i] =
1700 uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1701 }
1702 }
1703
1704 // Clean up the memory we allocated.
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001705 if (U != &SPACE[0]) {
1706 delete [] U;
1707 delete [] V;
1708 delete [] Q;
1709 delete [] R;
1710 }
Reid Spencer5e0a8512007-02-17 03:16:00 +00001711}
1712
Reid Spencere81d2da2007-02-16 22:36:51 +00001713APInt APInt::udiv(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +00001714 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer71bd08f2007-02-17 02:07:07 +00001715
1716 // First, deal with the easy case
1717 if (isSingleWord()) {
1718 assert(RHS.VAL != 0 && "Divide by zero?");
1719 return APInt(BitWidth, VAL / RHS.VAL);
Zhou Sheng0b706b12007-02-08 14:35:19 +00001720 }
Reid Spencer71bd08f2007-02-17 02:07:07 +00001721
Reid Spencer71bd08f2007-02-17 02:07:07 +00001722 // Get some facts about the LHS and RHS number of bits and words
Chris Lattner455e9ab2009-01-21 18:09:24 +00001723 unsigned rhsBits = RHS.getActiveBits();
1724 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001725 assert(rhsWords && "Divided by zero???");
Chris Lattner455e9ab2009-01-21 18:09:24 +00001726 unsigned lhsBits = this->getActiveBits();
1727 unsigned lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001728
1729 // Deal with some degenerate cases
1730 if (!lhsWords)
Reid Spencere0cdd332007-02-21 08:21:52 +00001731 // 0 / X ===> 0
1732 return APInt(BitWidth, 0);
1733 else if (lhsWords < rhsWords || this->ult(RHS)) {
1734 // X / Y ===> 0, iff X < Y
1735 return APInt(BitWidth, 0);
1736 } else if (*this == RHS) {
1737 // X / X ===> 1
1738 return APInt(BitWidth, 1);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001739 } else if (lhsWords == 1 && rhsWords == 1) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001740 // All high words are zero, just use native divide
Reid Spencere0cdd332007-02-21 08:21:52 +00001741 return APInt(BitWidth, this->pVal[0] / RHS.pVal[0]);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001742 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001743
1744 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1745 APInt Quotient(1,0); // to hold result.
1746 divide(*this, lhsWords, RHS, rhsWords, &Quotient, 0);
1747 return Quotient;
Zhou Sheng0b706b12007-02-08 14:35:19 +00001748}
1749
Reid Spencere81d2da2007-02-16 22:36:51 +00001750APInt APInt::urem(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +00001751 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer71bd08f2007-02-17 02:07:07 +00001752 if (isSingleWord()) {
1753 assert(RHS.VAL != 0 && "Remainder by zero?");
1754 return APInt(BitWidth, VAL % RHS.VAL);
Zhou Sheng0b706b12007-02-08 14:35:19 +00001755 }
Reid Spencer71bd08f2007-02-17 02:07:07 +00001756
Reid Spencere0cdd332007-02-21 08:21:52 +00001757 // Get some facts about the LHS
Chris Lattner455e9ab2009-01-21 18:09:24 +00001758 unsigned lhsBits = getActiveBits();
1759 unsigned lhsWords = !lhsBits ? 0 : (whichWord(lhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001760
1761 // Get some facts about the RHS
Chris Lattner455e9ab2009-01-21 18:09:24 +00001762 unsigned rhsBits = RHS.getActiveBits();
1763 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001764 assert(rhsWords && "Performing remainder operation by zero ???");
1765
Reid Spencer71bd08f2007-02-17 02:07:07 +00001766 // Check the degenerate cases
Reid Spencer9c0696f2007-02-20 08:51:03 +00001767 if (lhsWords == 0) {
Reid Spencere0cdd332007-02-21 08:21:52 +00001768 // 0 % Y ===> 0
1769 return APInt(BitWidth, 0);
1770 } else if (lhsWords < rhsWords || this->ult(RHS)) {
1771 // X % Y ===> X, iff X < Y
1772 return *this;
1773 } else if (*this == RHS) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001774 // X % X == 0;
Reid Spencere0cdd332007-02-21 08:21:52 +00001775 return APInt(BitWidth, 0);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001776 } else if (lhsWords == 1) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001777 // All high words are zero, just use native remainder
Reid Spencere0cdd332007-02-21 08:21:52 +00001778 return APInt(BitWidth, pVal[0] % RHS.pVal[0]);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001779 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001780
Reid Spencer19dc32a2007-05-13 23:44:59 +00001781 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
Reid Spencer9c0696f2007-02-20 08:51:03 +00001782 APInt Remainder(1,0);
1783 divide(*this, lhsWords, RHS, rhsWords, 0, &Remainder);
1784 return Remainder;
Zhou Sheng0b706b12007-02-08 14:35:19 +00001785}
Reid Spencer5e0a8512007-02-17 03:16:00 +00001786
Reid Spencer19dc32a2007-05-13 23:44:59 +00001787void APInt::udivrem(const APInt &LHS, const APInt &RHS,
1788 APInt &Quotient, APInt &Remainder) {
1789 // Get some size facts about the dividend and divisor
Chris Lattner455e9ab2009-01-21 18:09:24 +00001790 unsigned lhsBits = LHS.getActiveBits();
1791 unsigned lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
1792 unsigned rhsBits = RHS.getActiveBits();
1793 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer19dc32a2007-05-13 23:44:59 +00001794
1795 // Check the degenerate cases
1796 if (lhsWords == 0) {
1797 Quotient = 0; // 0 / Y ===> 0
1798 Remainder = 0; // 0 % Y ===> 0
1799 return;
1800 }
1801
1802 if (lhsWords < rhsWords || LHS.ult(RHS)) {
1803 Quotient = 0; // X / Y ===> 0, iff X < Y
1804 Remainder = LHS; // X % Y ===> X, iff X < Y
1805 return;
1806 }
1807
1808 if (LHS == RHS) {
1809 Quotient = 1; // X / X ===> 1
1810 Remainder = 0; // X % X ===> 0;
1811 return;
1812 }
1813
1814 if (lhsWords == 1 && rhsWords == 1) {
1815 // There is only one word to consider so use the native versions.
Wojciech Matyjewicz300c6c52008-06-23 19:39:50 +00001816 uint64_t lhsValue = LHS.isSingleWord() ? LHS.VAL : LHS.pVal[0];
1817 uint64_t rhsValue = RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
1818 Quotient = APInt(LHS.getBitWidth(), lhsValue / rhsValue);
1819 Remainder = APInt(LHS.getBitWidth(), lhsValue % rhsValue);
Reid Spencer19dc32a2007-05-13 23:44:59 +00001820 return;
1821 }
1822
1823 // Okay, lets do it the long way
1824 divide(LHS, lhsWords, RHS, rhsWords, &Quotient, &Remainder);
1825}
1826
Chris Lattner455e9ab2009-01-21 18:09:24 +00001827void APInt::fromString(unsigned numbits, const char *str, unsigned slen,
Reid Spencer5e0a8512007-02-17 03:16:00 +00001828 uint8_t radix) {
Reid Spencer385f7542007-02-21 03:55:44 +00001829 // Check our assumptions here
Reid Spencer5e0a8512007-02-17 03:16:00 +00001830 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1831 "Radix should be 2, 8, 10, or 16!");
Reid Spencer385f7542007-02-21 03:55:44 +00001832 assert(str && "String is null?");
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001833 bool isNeg = str[0] == '-';
1834 if (isNeg)
Reid Spencer9eec2412007-02-25 23:44:53 +00001835 str++, slen--;
Chris Lattnera5ae15e2007-05-03 18:15:36 +00001836 assert((slen <= numbits || radix != 2) && "Insufficient bit width");
1837 assert((slen*3 <= numbits || radix != 8) && "Insufficient bit width");
1838 assert((slen*4 <= numbits || radix != 16) && "Insufficient bit width");
1839 assert(((slen*64)/22 <= numbits || radix != 10) && "Insufficient bit width");
Reid Spencer385f7542007-02-21 03:55:44 +00001840
1841 // Allocate memory
1842 if (!isSingleWord())
1843 pVal = getClearedMemory(getNumWords());
1844
1845 // Figure out if we can shift instead of multiply
Chris Lattner455e9ab2009-01-21 18:09:24 +00001846 unsigned shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0);
Reid Spencer385f7542007-02-21 03:55:44 +00001847
1848 // Set up an APInt for the digit to add outside the loop so we don't
1849 // constantly construct/destruct it.
1850 APInt apdigit(getBitWidth(), 0);
1851 APInt apradix(getBitWidth(), radix);
1852
1853 // Enter digit traversal loop
1854 for (unsigned i = 0; i < slen; i++) {
1855 // Get a digit
Chris Lattner455e9ab2009-01-21 18:09:24 +00001856 unsigned digit = 0;
Reid Spencer385f7542007-02-21 03:55:44 +00001857 char cdigit = str[i];
Reid Spencer6551dcd2007-05-16 19:18:22 +00001858 if (radix == 16) {
1859 if (!isxdigit(cdigit))
1860 assert(0 && "Invalid hex digit in string");
1861 if (isdigit(cdigit))
1862 digit = cdigit - '0';
1863 else if (cdigit >= 'a')
Reid Spencer385f7542007-02-21 03:55:44 +00001864 digit = cdigit - 'a' + 10;
1865 else if (cdigit >= 'A')
1866 digit = cdigit - 'A' + 10;
1867 else
Reid Spencer6551dcd2007-05-16 19:18:22 +00001868 assert(0 && "huh? we shouldn't get here");
1869 } else if (isdigit(cdigit)) {
1870 digit = cdigit - '0';
Bill Wendlingf7a91e62008-03-16 20:05:52 +00001871 assert((radix == 10 ||
1872 (radix == 8 && digit != 8 && digit != 9) ||
1873 (radix == 2 && (digit == 0 || digit == 1))) &&
1874 "Invalid digit in string for given radix");
Reid Spencer6551dcd2007-05-16 19:18:22 +00001875 } else {
Reid Spencer385f7542007-02-21 03:55:44 +00001876 assert(0 && "Invalid character in digit string");
Reid Spencer6551dcd2007-05-16 19:18:22 +00001877 }
Reid Spencer385f7542007-02-21 03:55:44 +00001878
Reid Spencer6551dcd2007-05-16 19:18:22 +00001879 // Shift or multiply the value by the radix
Reid Spencer385f7542007-02-21 03:55:44 +00001880 if (shift)
Reid Spencer6551dcd2007-05-16 19:18:22 +00001881 *this <<= shift;
Reid Spencer385f7542007-02-21 03:55:44 +00001882 else
1883 *this *= apradix;
1884
1885 // Add in the digit we just interpreted
Reid Spencer5bce8542007-02-24 20:19:37 +00001886 if (apdigit.isSingleWord())
1887 apdigit.VAL = digit;
1888 else
1889 apdigit.pVal[0] = digit;
Reid Spencer385f7542007-02-21 03:55:44 +00001890 *this += apdigit;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001891 }
Reid Spencer9eec2412007-02-25 23:44:53 +00001892 // If its negative, put it in two's complement form
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001893 if (isNeg) {
1894 (*this)--;
Reid Spencer9eec2412007-02-25 23:44:53 +00001895 this->flip();
Reid Spencer9eec2412007-02-25 23:44:53 +00001896 }
Reid Spencer5e0a8512007-02-17 03:16:00 +00001897}
Reid Spencer9c0696f2007-02-20 08:51:03 +00001898
Chris Lattnerfad86b02008-08-17 07:19:36 +00001899void APInt::toString(SmallVectorImpl<char> &Str, unsigned Radix,
1900 bool Signed) const {
1901 assert((Radix == 10 || Radix == 8 || Radix == 16 || Radix == 2) &&
Reid Spencer9c0696f2007-02-20 08:51:03 +00001902 "Radix should be 2, 8, 10, or 16!");
Chris Lattnerfad86b02008-08-17 07:19:36 +00001903
1904 // First, check for a zero value and just short circuit the logic below.
1905 if (*this == 0) {
1906 Str.push_back('0');
1907 return;
1908 }
1909
1910 static const char Digits[] = "0123456789ABCDEF";
1911
Reid Spencer9c0696f2007-02-20 08:51:03 +00001912 if (isSingleWord()) {
Chris Lattnerfad86b02008-08-17 07:19:36 +00001913 char Buffer[65];
1914 char *BufPtr = Buffer+65;
1915
1916 uint64_t N;
1917 if (Signed) {
1918 int64_t I = getSExtValue();
1919 if (I < 0) {
1920 Str.push_back('-');
1921 I = -I;
1922 }
1923 N = I;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001924 } else {
Chris Lattnerfad86b02008-08-17 07:19:36 +00001925 N = getZExtValue();
Reid Spencer9c0696f2007-02-20 08:51:03 +00001926 }
Chris Lattnerfad86b02008-08-17 07:19:36 +00001927
1928 while (N) {
1929 *--BufPtr = Digits[N % Radix];
1930 N /= Radix;
1931 }
1932 Str.append(BufPtr, Buffer+65);
1933 return;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001934 }
1935
Chris Lattnerfad86b02008-08-17 07:19:36 +00001936 APInt Tmp(*this);
1937
1938 if (Signed && isNegative()) {
Reid Spencer9c0696f2007-02-20 08:51:03 +00001939 // They want to print the signed version and it is a negative value
1940 // Flip the bits and add one to turn it into the equivalent positive
1941 // value and put a '-' in the result.
Chris Lattnerfad86b02008-08-17 07:19:36 +00001942 Tmp.flip();
1943 Tmp++;
1944 Str.push_back('-');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001945 }
Chris Lattnerfad86b02008-08-17 07:19:36 +00001946
1947 // We insert the digits backward, then reverse them to get the right order.
1948 unsigned StartDig = Str.size();
1949
1950 // For the 2, 8 and 16 bit cases, we can just shift instead of divide
1951 // because the number of bits per digit (1, 3 and 4 respectively) divides
1952 // equaly. We just shift until the value is zero.
1953 if (Radix != 10) {
1954 // Just shift tmp right for each digit width until it becomes zero
1955 unsigned ShiftAmt = (Radix == 16 ? 4 : (Radix == 8 ? 3 : 1));
1956 unsigned MaskAmt = Radix - 1;
1957
1958 while (Tmp != 0) {
1959 unsigned Digit = unsigned(Tmp.getRawData()[0]) & MaskAmt;
1960 Str.push_back(Digits[Digit]);
1961 Tmp = Tmp.lshr(ShiftAmt);
1962 }
1963 } else {
1964 APInt divisor(4, 10);
1965 while (Tmp != 0) {
1966 APInt APdigit(1, 0);
1967 APInt tmp2(Tmp.getBitWidth(), 0);
1968 divide(Tmp, Tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2,
1969 &APdigit);
Chris Lattner455e9ab2009-01-21 18:09:24 +00001970 unsigned Digit = (unsigned)APdigit.getZExtValue();
Chris Lattnerfad86b02008-08-17 07:19:36 +00001971 assert(Digit < Radix && "divide failed");
1972 Str.push_back(Digits[Digit]);
1973 Tmp = tmp2;
1974 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001975 }
Chris Lattnerfad86b02008-08-17 07:19:36 +00001976
1977 // Reverse the digits before returning.
1978 std::reverse(Str.begin()+StartDig, Str.end());
Reid Spencer9c0696f2007-02-20 08:51:03 +00001979}
1980
Chris Lattnerfad86b02008-08-17 07:19:36 +00001981/// toString - This returns the APInt as a std::string. Note that this is an
1982/// inefficient method. It is better to pass in a SmallVector/SmallString
1983/// to the methods above.
1984std::string APInt::toString(unsigned Radix = 10, bool Signed = true) const {
1985 SmallString<40> S;
1986 toString(S, Radix, Signed);
1987 return S.c_str();
Reid Spencer385f7542007-02-21 03:55:44 +00001988}
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00001989
Chris Lattnerfad86b02008-08-17 07:19:36 +00001990
1991void APInt::dump() const {
1992 SmallString<40> S, U;
1993 this->toStringUnsigned(U);
1994 this->toStringSigned(S);
1995 fprintf(stderr, "APInt(%db, %su %ss)", BitWidth, U.c_str(), S.c_str());
1996}
1997
Chris Lattner944fac72008-08-23 22:23:09 +00001998void APInt::print(raw_ostream &OS, bool isSigned) const {
Chris Lattnerfad86b02008-08-17 07:19:36 +00001999 SmallString<40> S;
2000 this->toString(S, 10, isSigned);
2001 OS << S.c_str();
2002}
2003
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002004// This implements a variety of operations on a representation of
2005// arbitrary precision, two's-complement, bignum integer values.
2006
2007/* Assumed by lowHalf, highHalf, partMSB and partLSB. A fairly safe
2008 and unrestricting assumption. */
Chris Lattner9f17eb02008-08-17 04:58:58 +00002009#define COMPILE_TIME_ASSERT(cond) extern int CTAssert[(cond) ? 1 : -1]
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002010COMPILE_TIME_ASSERT(integerPartWidth % 2 == 0);
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002011
2012/* Some handy functions local to this file. */
2013namespace {
2014
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002015 /* Returns the integer part with the least significant BITS set.
2016 BITS cannot be zero. */
Dan Gohman3bd659b2008-04-10 21:11:47 +00002017 static inline integerPart
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002018 lowBitMask(unsigned int bits)
2019 {
2020 assert (bits != 0 && bits <= integerPartWidth);
2021
2022 return ~(integerPart) 0 >> (integerPartWidth - bits);
2023 }
2024
Neil Booth055c0b32007-10-06 00:43:45 +00002025 /* Returns the value of the lower half of PART. */
Dan Gohman3bd659b2008-04-10 21:11:47 +00002026 static inline integerPart
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002027 lowHalf(integerPart part)
2028 {
2029 return part & lowBitMask(integerPartWidth / 2);
2030 }
2031
Neil Booth055c0b32007-10-06 00:43:45 +00002032 /* Returns the value of the upper half of PART. */
Dan Gohman3bd659b2008-04-10 21:11:47 +00002033 static inline integerPart
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002034 highHalf(integerPart part)
2035 {
2036 return part >> (integerPartWidth / 2);
2037 }
2038
Neil Booth055c0b32007-10-06 00:43:45 +00002039 /* Returns the bit number of the most significant set bit of a part.
2040 If the input number has no bits set -1U is returned. */
Dan Gohman3bd659b2008-04-10 21:11:47 +00002041 static unsigned int
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002042 partMSB(integerPart value)
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002043 {
2044 unsigned int n, msb;
2045
2046 if (value == 0)
2047 return -1U;
2048
2049 n = integerPartWidth / 2;
2050
2051 msb = 0;
2052 do {
2053 if (value >> n) {
2054 value >>= n;
2055 msb += n;
2056 }
2057
2058 n >>= 1;
2059 } while (n);
2060
2061 return msb;
2062 }
2063
Neil Booth055c0b32007-10-06 00:43:45 +00002064 /* Returns the bit number of the least significant set bit of a
2065 part. If the input number has no bits set -1U is returned. */
Dan Gohman3bd659b2008-04-10 21:11:47 +00002066 static unsigned int
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002067 partLSB(integerPart value)
2068 {
2069 unsigned int n, lsb;
2070
2071 if (value == 0)
2072 return -1U;
2073
2074 lsb = integerPartWidth - 1;
2075 n = integerPartWidth / 2;
2076
2077 do {
2078 if (value << n) {
2079 value <<= n;
2080 lsb -= n;
2081 }
2082
2083 n >>= 1;
2084 } while (n);
2085
2086 return lsb;
2087 }
2088}
2089
2090/* Sets the least significant part of a bignum to the input value, and
2091 zeroes out higher parts. */
2092void
2093APInt::tcSet(integerPart *dst, integerPart part, unsigned int parts)
2094{
2095 unsigned int i;
2096
Neil Booth68e53ad2007-10-08 13:47:12 +00002097 assert (parts > 0);
2098
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002099 dst[0] = part;
2100 for(i = 1; i < parts; i++)
2101 dst[i] = 0;
2102}
2103
2104/* Assign one bignum to another. */
2105void
2106APInt::tcAssign(integerPart *dst, const integerPart *src, unsigned int parts)
2107{
2108 unsigned int i;
2109
2110 for(i = 0; i < parts; i++)
2111 dst[i] = src[i];
2112}
2113
2114/* Returns true if a bignum is zero, false otherwise. */
2115bool
2116APInt::tcIsZero(const integerPart *src, unsigned int parts)
2117{
2118 unsigned int i;
2119
2120 for(i = 0; i < parts; i++)
2121 if (src[i])
2122 return false;
2123
2124 return true;
2125}
2126
2127/* Extract the given bit of a bignum; returns 0 or 1. */
2128int
2129APInt::tcExtractBit(const integerPart *parts, unsigned int bit)
2130{
2131 return(parts[bit / integerPartWidth]
2132 & ((integerPart) 1 << bit % integerPartWidth)) != 0;
2133}
2134
2135/* Set the given bit of a bignum. */
2136void
2137APInt::tcSetBit(integerPart *parts, unsigned int bit)
2138{
2139 parts[bit / integerPartWidth] |= (integerPart) 1 << (bit % integerPartWidth);
2140}
2141
Neil Booth055c0b32007-10-06 00:43:45 +00002142/* Returns the bit number of the least significant set bit of a
2143 number. If the input number has no bits set -1U is returned. */
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002144unsigned int
2145APInt::tcLSB(const integerPart *parts, unsigned int n)
2146{
2147 unsigned int i, lsb;
2148
2149 for(i = 0; i < n; i++) {
2150 if (parts[i] != 0) {
2151 lsb = partLSB(parts[i]);
2152
2153 return lsb + i * integerPartWidth;
2154 }
2155 }
2156
2157 return -1U;
2158}
2159
Neil Booth055c0b32007-10-06 00:43:45 +00002160/* Returns the bit number of the most significant set bit of a number.
2161 If the input number has no bits set -1U is returned. */
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002162unsigned int
2163APInt::tcMSB(const integerPart *parts, unsigned int n)
2164{
2165 unsigned int msb;
2166
2167 do {
2168 --n;
2169
2170 if (parts[n] != 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002171 msb = partMSB(parts[n]);
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002172
2173 return msb + n * integerPartWidth;
2174 }
2175 } while (n);
2176
2177 return -1U;
2178}
2179
Neil Booth68e53ad2007-10-08 13:47:12 +00002180/* Copy the bit vector of width srcBITS from SRC, starting at bit
2181 srcLSB, to DST, of dstCOUNT parts, such that the bit srcLSB becomes
2182 the least significant bit of DST. All high bits above srcBITS in
2183 DST are zero-filled. */
2184void
2185APInt::tcExtract(integerPart *dst, unsigned int dstCount, const integerPart *src,
2186 unsigned int srcBits, unsigned int srcLSB)
2187{
2188 unsigned int firstSrcPart, dstParts, shift, n;
2189
2190 dstParts = (srcBits + integerPartWidth - 1) / integerPartWidth;
2191 assert (dstParts <= dstCount);
2192
2193 firstSrcPart = srcLSB / integerPartWidth;
2194 tcAssign (dst, src + firstSrcPart, dstParts);
2195
2196 shift = srcLSB % integerPartWidth;
2197 tcShiftRight (dst, dstParts, shift);
2198
2199 /* We now have (dstParts * integerPartWidth - shift) bits from SRC
2200 in DST. If this is less that srcBits, append the rest, else
2201 clear the high bits. */
2202 n = dstParts * integerPartWidth - shift;
2203 if (n < srcBits) {
2204 integerPart mask = lowBitMask (srcBits - n);
2205 dst[dstParts - 1] |= ((src[firstSrcPart + dstParts] & mask)
2206 << n % integerPartWidth);
2207 } else if (n > srcBits) {
Neil Booth1e8390d2007-10-12 15:31:31 +00002208 if (srcBits % integerPartWidth)
2209 dst[dstParts - 1] &= lowBitMask (srcBits % integerPartWidth);
Neil Booth68e53ad2007-10-08 13:47:12 +00002210 }
2211
2212 /* Clear high parts. */
2213 while (dstParts < dstCount)
2214 dst[dstParts++] = 0;
2215}
2216
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002217/* DST += RHS + C where C is zero or one. Returns the carry flag. */
2218integerPart
2219APInt::tcAdd(integerPart *dst, const integerPart *rhs,
2220 integerPart c, unsigned int parts)
2221{
2222 unsigned int i;
2223
2224 assert(c <= 1);
2225
2226 for(i = 0; i < parts; i++) {
2227 integerPart l;
2228
2229 l = dst[i];
2230 if (c) {
2231 dst[i] += rhs[i] + 1;
2232 c = (dst[i] <= l);
2233 } else {
2234 dst[i] += rhs[i];
2235 c = (dst[i] < l);
2236 }
2237 }
2238
2239 return c;
2240}
2241
2242/* DST -= RHS + C where C is zero or one. Returns the carry flag. */
2243integerPart
2244APInt::tcSubtract(integerPart *dst, const integerPart *rhs,
2245 integerPart c, unsigned int parts)
2246{
2247 unsigned int i;
2248
2249 assert(c <= 1);
2250
2251 for(i = 0; i < parts; i++) {
2252 integerPart l;
2253
2254 l = dst[i];
2255 if (c) {
2256 dst[i] -= rhs[i] + 1;
2257 c = (dst[i] >= l);
2258 } else {
2259 dst[i] -= rhs[i];
2260 c = (dst[i] > l);
2261 }
2262 }
2263
2264 return c;
2265}
2266
2267/* Negate a bignum in-place. */
2268void
2269APInt::tcNegate(integerPart *dst, unsigned int parts)
2270{
2271 tcComplement(dst, parts);
2272 tcIncrement(dst, parts);
2273}
2274
Neil Booth055c0b32007-10-06 00:43:45 +00002275/* DST += SRC * MULTIPLIER + CARRY if add is true
2276 DST = SRC * MULTIPLIER + CARRY if add is false
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002277
2278 Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC
2279 they must start at the same point, i.e. DST == SRC.
2280
2281 If DSTPARTS == SRCPARTS + 1 no overflow occurs and zero is
2282 returned. Otherwise DST is filled with the least significant
2283 DSTPARTS parts of the result, and if all of the omitted higher
2284 parts were zero return zero, otherwise overflow occurred and
2285 return one. */
2286int
2287APInt::tcMultiplyPart(integerPart *dst, const integerPart *src,
2288 integerPart multiplier, integerPart carry,
2289 unsigned int srcParts, unsigned int dstParts,
2290 bool add)
2291{
2292 unsigned int i, n;
2293
2294 /* Otherwise our writes of DST kill our later reads of SRC. */
2295 assert(dst <= src || dst >= src + srcParts);
2296 assert(dstParts <= srcParts + 1);
2297
2298 /* N loops; minimum of dstParts and srcParts. */
2299 n = dstParts < srcParts ? dstParts: srcParts;
2300
2301 for(i = 0; i < n; i++) {
2302 integerPart low, mid, high, srcPart;
2303
2304 /* [ LOW, HIGH ] = MULTIPLIER * SRC[i] + DST[i] + CARRY.
2305
2306 This cannot overflow, because
2307
2308 (n - 1) * (n - 1) + 2 (n - 1) = (n - 1) * (n + 1)
2309
2310 which is less than n^2. */
2311
2312 srcPart = src[i];
2313
2314 if (multiplier == 0 || srcPart == 0) {
2315 low = carry;
2316 high = 0;
2317 } else {
2318 low = lowHalf(srcPart) * lowHalf(multiplier);
2319 high = highHalf(srcPart) * highHalf(multiplier);
2320
2321 mid = lowHalf(srcPart) * highHalf(multiplier);
2322 high += highHalf(mid);
2323 mid <<= integerPartWidth / 2;
2324 if (low + mid < low)
2325 high++;
2326 low += mid;
2327
2328 mid = highHalf(srcPart) * lowHalf(multiplier);
2329 high += highHalf(mid);
2330 mid <<= integerPartWidth / 2;
2331 if (low + mid < low)
2332 high++;
2333 low += mid;
2334
2335 /* Now add carry. */
2336 if (low + carry < low)
2337 high++;
2338 low += carry;
2339 }
2340
2341 if (add) {
2342 /* And now DST[i], and store the new low part there. */
2343 if (low + dst[i] < low)
2344 high++;
2345 dst[i] += low;
2346 } else
2347 dst[i] = low;
2348
2349 carry = high;
2350 }
2351
2352 if (i < dstParts) {
2353 /* Full multiplication, there is no overflow. */
2354 assert(i + 1 == dstParts);
2355 dst[i] = carry;
2356 return 0;
2357 } else {
2358 /* We overflowed if there is carry. */
2359 if (carry)
2360 return 1;
2361
2362 /* We would overflow if any significant unwritten parts would be
2363 non-zero. This is true if any remaining src parts are non-zero
2364 and the multiplier is non-zero. */
2365 if (multiplier)
2366 for(; i < srcParts; i++)
2367 if (src[i])
2368 return 1;
2369
2370 /* We fitted in the narrow destination. */
2371 return 0;
2372 }
2373}
2374
2375/* DST = LHS * RHS, where DST has the same width as the operands and
2376 is filled with the least significant parts of the result. Returns
2377 one if overflow occurred, otherwise zero. DST must be disjoint
2378 from both operands. */
2379int
2380APInt::tcMultiply(integerPart *dst, const integerPart *lhs,
2381 const integerPart *rhs, unsigned int parts)
2382{
2383 unsigned int i;
2384 int overflow;
2385
2386 assert(dst != lhs && dst != rhs);
2387
2388 overflow = 0;
2389 tcSet(dst, 0, parts);
2390
2391 for(i = 0; i < parts; i++)
2392 overflow |= tcMultiplyPart(&dst[i], lhs, rhs[i], 0, parts,
2393 parts - i, true);
2394
2395 return overflow;
2396}
2397
Neil Booth978661d2007-10-06 00:24:48 +00002398/* DST = LHS * RHS, where DST has width the sum of the widths of the
2399 operands. No overflow occurs. DST must be disjoint from both
2400 operands. Returns the number of parts required to hold the
2401 result. */
2402unsigned int
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002403APInt::tcFullMultiply(integerPart *dst, const integerPart *lhs,
Neil Booth978661d2007-10-06 00:24:48 +00002404 const integerPart *rhs, unsigned int lhsParts,
2405 unsigned int rhsParts)
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002406{
Neil Booth978661d2007-10-06 00:24:48 +00002407 /* Put the narrower number on the LHS for less loops below. */
2408 if (lhsParts > rhsParts) {
2409 return tcFullMultiply (dst, rhs, lhs, rhsParts, lhsParts);
2410 } else {
2411 unsigned int n;
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002412
Neil Booth978661d2007-10-06 00:24:48 +00002413 assert(dst != lhs && dst != rhs);
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002414
Neil Booth978661d2007-10-06 00:24:48 +00002415 tcSet(dst, 0, rhsParts);
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002416
Neil Booth978661d2007-10-06 00:24:48 +00002417 for(n = 0; n < lhsParts; n++)
2418 tcMultiplyPart(&dst[n], rhs, lhs[n], 0, rhsParts, rhsParts + 1, true);
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002419
Neil Booth978661d2007-10-06 00:24:48 +00002420 n = lhsParts + rhsParts;
2421
2422 return n - (dst[n - 1] == 0);
2423 }
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002424}
2425
2426/* If RHS is zero LHS and REMAINDER are left unchanged, return one.
2427 Otherwise set LHS to LHS / RHS with the fractional part discarded,
2428 set REMAINDER to the remainder, return zero. i.e.
2429
2430 OLD_LHS = RHS * LHS + REMAINDER
2431
2432 SCRATCH is a bignum of the same size as the operands and result for
2433 use by the routine; its contents need not be initialized and are
2434 destroyed. LHS, REMAINDER and SCRATCH must be distinct.
2435*/
2436int
2437APInt::tcDivide(integerPart *lhs, const integerPart *rhs,
2438 integerPart *remainder, integerPart *srhs,
2439 unsigned int parts)
2440{
2441 unsigned int n, shiftCount;
2442 integerPart mask;
2443
2444 assert(lhs != remainder && lhs != srhs && remainder != srhs);
2445
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002446 shiftCount = tcMSB(rhs, parts) + 1;
2447 if (shiftCount == 0)
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002448 return true;
2449
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002450 shiftCount = parts * integerPartWidth - shiftCount;
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002451 n = shiftCount / integerPartWidth;
2452 mask = (integerPart) 1 << (shiftCount % integerPartWidth);
2453
2454 tcAssign(srhs, rhs, parts);
2455 tcShiftLeft(srhs, parts, shiftCount);
2456 tcAssign(remainder, lhs, parts);
2457 tcSet(lhs, 0, parts);
2458
2459 /* Loop, subtracting SRHS if REMAINDER is greater and adding that to
2460 the total. */
2461 for(;;) {
2462 int compare;
2463
2464 compare = tcCompare(remainder, srhs, parts);
2465 if (compare >= 0) {
2466 tcSubtract(remainder, srhs, 0, parts);
2467 lhs[n] |= mask;
2468 }
2469
2470 if (shiftCount == 0)
2471 break;
2472 shiftCount--;
2473 tcShiftRight(srhs, parts, 1);
2474 if ((mask >>= 1) == 0)
2475 mask = (integerPart) 1 << (integerPartWidth - 1), n--;
2476 }
2477
2478 return false;
2479}
2480
2481/* Shift a bignum left COUNT bits in-place. Shifted in bits are zero.
2482 There are no restrictions on COUNT. */
2483void
2484APInt::tcShiftLeft(integerPart *dst, unsigned int parts, unsigned int count)
2485{
Neil Booth68e53ad2007-10-08 13:47:12 +00002486 if (count) {
2487 unsigned int jump, shift;
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002488
Neil Booth68e53ad2007-10-08 13:47:12 +00002489 /* Jump is the inter-part jump; shift is is intra-part shift. */
2490 jump = count / integerPartWidth;
2491 shift = count % integerPartWidth;
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002492
Neil Booth68e53ad2007-10-08 13:47:12 +00002493 while (parts > jump) {
2494 integerPart part;
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002495
Neil Booth68e53ad2007-10-08 13:47:12 +00002496 parts--;
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002497
Neil Booth68e53ad2007-10-08 13:47:12 +00002498 /* dst[i] comes from the two parts src[i - jump] and, if we have
2499 an intra-part shift, src[i - jump - 1]. */
2500 part = dst[parts - jump];
2501 if (shift) {
2502 part <<= shift;
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002503 if (parts >= jump + 1)
2504 part |= dst[parts - jump - 1] >> (integerPartWidth - shift);
2505 }
2506
Neil Booth68e53ad2007-10-08 13:47:12 +00002507 dst[parts] = part;
2508 }
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002509
Neil Booth68e53ad2007-10-08 13:47:12 +00002510 while (parts > 0)
2511 dst[--parts] = 0;
2512 }
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002513}
2514
2515/* Shift a bignum right COUNT bits in-place. Shifted in bits are
2516 zero. There are no restrictions on COUNT. */
2517void
2518APInt::tcShiftRight(integerPart *dst, unsigned int parts, unsigned int count)
2519{
Neil Booth68e53ad2007-10-08 13:47:12 +00002520 if (count) {
2521 unsigned int i, jump, shift;
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002522
Neil Booth68e53ad2007-10-08 13:47:12 +00002523 /* Jump is the inter-part jump; shift is is intra-part shift. */
2524 jump = count / integerPartWidth;
2525 shift = count % integerPartWidth;
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002526
Neil Booth68e53ad2007-10-08 13:47:12 +00002527 /* Perform the shift. This leaves the most significant COUNT bits
2528 of the result at zero. */
2529 for(i = 0; i < parts; i++) {
2530 integerPart part;
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002531
Neil Booth68e53ad2007-10-08 13:47:12 +00002532 if (i + jump >= parts) {
2533 part = 0;
2534 } else {
2535 part = dst[i + jump];
2536 if (shift) {
2537 part >>= shift;
2538 if (i + jump + 1 < parts)
2539 part |= dst[i + jump + 1] << (integerPartWidth - shift);
2540 }
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002541 }
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002542
Neil Booth68e53ad2007-10-08 13:47:12 +00002543 dst[i] = part;
2544 }
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002545 }
2546}
2547
2548/* Bitwise and of two bignums. */
2549void
2550APInt::tcAnd(integerPart *dst, const integerPart *rhs, unsigned int parts)
2551{
2552 unsigned int i;
2553
2554 for(i = 0; i < parts; i++)
2555 dst[i] &= rhs[i];
2556}
2557
2558/* Bitwise inclusive or of two bignums. */
2559void
2560APInt::tcOr(integerPart *dst, const integerPart *rhs, unsigned int parts)
2561{
2562 unsigned int i;
2563
2564 for(i = 0; i < parts; i++)
2565 dst[i] |= rhs[i];
2566}
2567
2568/* Bitwise exclusive or of two bignums. */
2569void
2570APInt::tcXor(integerPart *dst, const integerPart *rhs, unsigned int parts)
2571{
2572 unsigned int i;
2573
2574 for(i = 0; i < parts; i++)
2575 dst[i] ^= rhs[i];
2576}
2577
2578/* Complement a bignum in-place. */
2579void
2580APInt::tcComplement(integerPart *dst, unsigned int parts)
2581{
2582 unsigned int i;
2583
2584 for(i = 0; i < parts; i++)
2585 dst[i] = ~dst[i];
2586}
2587
2588/* Comparison (unsigned) of two bignums. */
2589int
2590APInt::tcCompare(const integerPart *lhs, const integerPart *rhs,
2591 unsigned int parts)
2592{
2593 while (parts) {
2594 parts--;
2595 if (lhs[parts] == rhs[parts])
2596 continue;
2597
2598 if (lhs[parts] > rhs[parts])
2599 return 1;
2600 else
2601 return -1;
2602 }
2603
2604 return 0;
2605}
2606
2607/* Increment a bignum in-place, return the carry flag. */
2608integerPart
2609APInt::tcIncrement(integerPart *dst, unsigned int parts)
2610{
2611 unsigned int i;
2612
2613 for(i = 0; i < parts; i++)
2614 if (++dst[i] != 0)
2615 break;
2616
2617 return i == parts;
2618}
2619
2620/* Set the least significant BITS bits of a bignum, clear the
2621 rest. */
2622void
2623APInt::tcSetLeastSignificantBits(integerPart *dst, unsigned int parts,
2624 unsigned int bits)
2625{
2626 unsigned int i;
2627
2628 i = 0;
2629 while (bits > integerPartWidth) {
2630 dst[i++] = ~(integerPart) 0;
2631 bits -= integerPartWidth;
2632 }
2633
2634 if (bits)
2635 dst[i++] = ~(integerPart) 0 >> (integerPartWidth - bits);
2636
2637 while (i < parts)
2638 dst[i++] = 0;
2639}