blob: 167d56955e90048069cc882c526e27e0f3411199 [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"
Reid Spencer9d6c9192007-02-24 03:58:46 +000018#include "llvm/Support/Debug.h"
Zhou Shengfd43dcf2007-02-06 03:00:16 +000019#include "llvm/Support/MathExtras.h"
Jeff Cohenca5183d2007-03-05 00:00:42 +000020#include <math.h>
Jeff Cohen09dfd8e2007-03-20 20:42:36 +000021#include <limits>
Zhou Shenga3832fd2007-02-07 06:14:53 +000022#include <cstring>
Zhou Shengfd43dcf2007-02-06 03:00:16 +000023#include <cstdlib>
Reid Spencer385f7542007-02-21 03:55:44 +000024#include <iomanip>
Reid Spencer385f7542007-02-21 03:55:44 +000025
Zhou Shengfd43dcf2007-02-06 03:00:16 +000026using namespace llvm;
27
Reid Spencer9af18872007-12-11 06:53:58 +000028/// This enumeration just provides for internal constants used in this
29/// translation unit.
30enum {
31 MIN_INT_BITS = 1, ///< Minimum number of bits that can be specified
32 ///< Note that this must remain synchronized with IntegerType::MIN_INT_BITS
33 MAX_INT_BITS = (1<<23)-1 ///< Maximum number of bits that can be specified
34 ///< Note that this must remain synchronized with IntegerType::MAX_INT_BITS
35};
36
Reid Spencer5d0d05c2007-02-25 19:32:03 +000037/// A utility function for allocating memory, checking for allocation failures,
38/// and ensuring the contents are zeroed.
Reid Spenceraf0e9562007-02-18 18:38:44 +000039inline static uint64_t* getClearedMemory(uint32_t numWords) {
40 uint64_t * result = new uint64_t[numWords];
41 assert(result && "APInt memory allocation fails!");
42 memset(result, 0, numWords * sizeof(uint64_t));
43 return result;
Zhou Sheng353815d2007-02-06 06:04:53 +000044}
45
Reid Spencer5d0d05c2007-02-25 19:32:03 +000046/// A utility function for allocating memory and checking for allocation
47/// failure. The content is not zeroed.
Reid Spenceraf0e9562007-02-18 18:38:44 +000048inline static uint64_t* getMemory(uint32_t numWords) {
49 uint64_t * result = new uint64_t[numWords];
50 assert(result && "APInt memory allocation fails!");
51 return result;
52}
53
Reid Spenceradf2a202007-03-19 21:19:02 +000054APInt::APInt(uint32_t numBits, uint64_t val, bool isSigned)
Reid Spencer3a341372007-03-19 20:37:47 +000055 : BitWidth(numBits), VAL(0) {
Reid Spencer9af18872007-12-11 06:53:58 +000056 assert(BitWidth >= MIN_INT_BITS && "bitwidth too small");
57 assert(BitWidth <= MAX_INT_BITS && "bitwidth too large");
Reid Spencer5d0d05c2007-02-25 19:32:03 +000058 if (isSingleWord())
59 VAL = val;
Zhou Shengfd43dcf2007-02-06 03:00:16 +000060 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +000061 pVal = getClearedMemory(getNumWords());
Zhou Shengfd43dcf2007-02-06 03:00:16 +000062 pVal[0] = val;
Reid Spencer3a341372007-03-19 20:37:47 +000063 if (isSigned && int64_t(val) < 0)
64 for (unsigned i = 1; i < getNumWords(); ++i)
65 pVal[i] = -1ULL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +000066 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +000067 clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +000068}
69
Dale Johannesen910993e2007-09-21 22:09:37 +000070APInt::APInt(uint32_t numBits, uint32_t numWords, const uint64_t bigVal[])
Reid Spencer385f7542007-02-21 03:55:44 +000071 : BitWidth(numBits), VAL(0) {
Reid Spencer9af18872007-12-11 06:53:58 +000072 assert(BitWidth >= MIN_INT_BITS && "bitwidth too small");
73 assert(BitWidth <= MAX_INT_BITS && "bitwidth too large");
Zhou Shengfd43dcf2007-02-06 03:00:16 +000074 assert(bigVal && "Null pointer detected!");
75 if (isSingleWord())
Reid Spencer610fad82007-02-24 10:01:42 +000076 VAL = bigVal[0];
Zhou Shengfd43dcf2007-02-06 03:00:16 +000077 else {
Reid Spencer610fad82007-02-24 10:01:42 +000078 // Get memory, cleared to 0
79 pVal = getClearedMemory(getNumWords());
80 // Calculate the number of words to copy
81 uint32_t words = std::min<uint32_t>(numWords, getNumWords());
82 // Copy the words from bigVal to pVal
83 memcpy(pVal, bigVal, words * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +000084 }
Reid Spencer610fad82007-02-24 10:01:42 +000085 // Make sure unused high bits are cleared
86 clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +000087}
88
Reid Spenceraf0e9562007-02-18 18:38:44 +000089APInt::APInt(uint32_t numbits, const char StrStart[], uint32_t slen,
Reid Spencer9c0696f2007-02-20 08:51:03 +000090 uint8_t radix)
Reid Spencer385f7542007-02-21 03:55:44 +000091 : BitWidth(numbits), VAL(0) {
Reid Spencer9af18872007-12-11 06:53:58 +000092 assert(BitWidth >= MIN_INT_BITS && "bitwidth too small");
93 assert(BitWidth <= MAX_INT_BITS && "bitwidth too large");
Reid Spencere81d2da2007-02-16 22:36:51 +000094 fromString(numbits, StrStart, slen, radix);
Zhou Shenga3832fd2007-02-07 06:14:53 +000095}
96
Reid Spencer9c0696f2007-02-20 08:51:03 +000097APInt::APInt(uint32_t numbits, const std::string& Val, uint8_t radix)
Reid Spencer385f7542007-02-21 03:55:44 +000098 : BitWidth(numbits), VAL(0) {
Reid Spencer9af18872007-12-11 06:53:58 +000099 assert(BitWidth >= MIN_INT_BITS && "bitwidth too small");
100 assert(BitWidth <= MAX_INT_BITS && "bitwidth too large");
Zhou Shenga3832fd2007-02-07 06:14:53 +0000101 assert(!Val.empty() && "String empty?");
Evan Cheng48e8c802008-05-02 21:15:08 +0000102 fromString(numbits, Val.c_str(), (uint32_t)Val.size(), radix);
Zhou Shenga3832fd2007-02-07 06:14:53 +0000103}
104
Reid Spencer54362ca2007-02-20 23:40:25 +0000105APInt::APInt(const APInt& that)
Reid Spencer385f7542007-02-21 03:55:44 +0000106 : BitWidth(that.BitWidth), VAL(0) {
Reid Spencer9af18872007-12-11 06:53:58 +0000107 assert(BitWidth >= MIN_INT_BITS && "bitwidth too small");
108 assert(BitWidth <= MAX_INT_BITS && "bitwidth too large");
Reid Spenceraf0e9562007-02-18 18:38:44 +0000109 if (isSingleWord())
Reid Spencer54362ca2007-02-20 23:40:25 +0000110 VAL = that.VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000111 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000112 pVal = getMemory(getNumWords());
Reid Spencer54362ca2007-02-20 23:40:25 +0000113 memcpy(pVal, that.pVal, getNumWords() * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000114 }
115}
116
117APInt::~APInt() {
Reid Spencer9c0696f2007-02-20 08:51:03 +0000118 if (!isSingleWord() && pVal)
Reid Spencer9ac44112007-02-26 23:38:21 +0000119 delete [] pVal;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000120}
121
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000122APInt& APInt::operator=(const APInt& RHS) {
Reid Spencer9ac44112007-02-26 23:38:21 +0000123 // Don't do anything for X = X
124 if (this == &RHS)
125 return *this;
126
127 // If the bitwidths are the same, we can avoid mucking with memory
128 if (BitWidth == RHS.getBitWidth()) {
129 if (isSingleWord())
130 VAL = RHS.VAL;
131 else
132 memcpy(pVal, RHS.pVal, getNumWords() * APINT_WORD_SIZE);
133 return *this;
134 }
135
136 if (isSingleWord())
137 if (RHS.isSingleWord())
138 VAL = RHS.VAL;
139 else {
140 VAL = 0;
141 pVal = getMemory(RHS.getNumWords());
142 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
143 }
144 else if (getNumWords() == RHS.getNumWords())
145 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
146 else if (RHS.isSingleWord()) {
147 delete [] pVal;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000148 VAL = RHS.VAL;
Reid Spencer9ac44112007-02-26 23:38:21 +0000149 } else {
150 delete [] pVal;
151 pVal = getMemory(RHS.getNumWords());
152 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
153 }
154 BitWidth = RHS.BitWidth;
155 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000156}
157
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000158APInt& APInt::operator=(uint64_t RHS) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000159 if (isSingleWord())
160 VAL = RHS;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000161 else {
162 pVal[0] = RHS;
Reid Spencera58f0582007-02-18 20:09:41 +0000163 memset(pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000164 }
Reid Spencer9ac44112007-02-26 23:38:21 +0000165 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000166}
167
Ted Kremeneke420deb2008-01-19 04:23:33 +0000168/// Profile - This method 'profiles' an APInt for use with FoldingSet.
169void APInt::Profile(FoldingSetNodeID& ID) const {
Ted Kremeneka795aca2008-02-19 20:50:41 +0000170 ID.AddInteger(BitWidth);
171
Ted Kremeneke420deb2008-01-19 04:23:33 +0000172 if (isSingleWord()) {
173 ID.AddInteger(VAL);
174 return;
175 }
176
177 uint32_t NumWords = getNumWords();
178 for (unsigned i = 0; i < NumWords; ++i)
179 ID.AddInteger(pVal[i]);
180}
181
Reid Spenceraf0e9562007-02-18 18:38:44 +0000182/// add_1 - This function adds a single "digit" integer, y, to the multiple
183/// "digit" integer array, x[]. x[] is modified to reflect the addition and
184/// 1 is returned if there is a carry out, otherwise 0 is returned.
Reid Spencer5e0a8512007-02-17 03:16:00 +0000185/// @returns the carry of the addition.
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000186static bool add_1(uint64_t dest[], uint64_t x[], uint32_t len, uint64_t y) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000187 for (uint32_t i = 0; i < len; ++i) {
Reid Spencerf2c521c2007-02-18 06:39:42 +0000188 dest[i] = y + x[i];
189 if (dest[i] < y)
Reid Spencer610fad82007-02-24 10:01:42 +0000190 y = 1; // Carry one to next digit.
Reid Spencerf2c521c2007-02-18 06:39:42 +0000191 else {
Reid Spencer610fad82007-02-24 10:01:42 +0000192 y = 0; // No need to carry so exit early
Reid Spencerf2c521c2007-02-18 06:39:42 +0000193 break;
194 }
Reid Spencer5e0a8512007-02-17 03:16:00 +0000195 }
Reid Spencerf2c521c2007-02-18 06:39:42 +0000196 return y;
Reid Spencer5e0a8512007-02-17 03:16:00 +0000197}
198
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000199/// @brief Prefix increment operator. Increments the APInt by one.
200APInt& APInt::operator++() {
Reid Spencere81d2da2007-02-16 22:36:51 +0000201 if (isSingleWord())
202 ++VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000203 else
Zhou Shenga3832fd2007-02-07 06:14:53 +0000204 add_1(pVal, pVal, getNumWords(), 1);
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000205 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000206}
207
Reid Spenceraf0e9562007-02-18 18:38:44 +0000208/// sub_1 - This function subtracts a single "digit" (64-bit word), y, from
209/// the multi-digit integer array, x[], propagating the borrowed 1 value until
210/// no further borrowing is neeeded or it runs out of "digits" in x. The result
211/// is 1 if "borrowing" exhausted the digits in x, or 0 if x was not exhausted.
212/// In other words, if y > x then this function returns 1, otherwise 0.
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000213/// @returns the borrow out of the subtraction
214static bool sub_1(uint64_t x[], uint32_t len, uint64_t y) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000215 for (uint32_t i = 0; i < len; ++i) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000216 uint64_t X = x[i];
Reid Spencerf2c521c2007-02-18 06:39:42 +0000217 x[i] -= y;
218 if (y > X)
Reid Spenceraf0e9562007-02-18 18:38:44 +0000219 y = 1; // We have to "borrow 1" from next "digit"
Reid Spencer5e0a8512007-02-17 03:16:00 +0000220 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000221 y = 0; // No need to borrow
222 break; // Remaining digits are unchanged so exit early
Reid Spencer5e0a8512007-02-17 03:16:00 +0000223 }
224 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000225 return bool(y);
Reid Spencer5e0a8512007-02-17 03:16:00 +0000226}
227
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000228/// @brief Prefix decrement operator. Decrements the APInt by one.
229APInt& APInt::operator--() {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000230 if (isSingleWord())
231 --VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000232 else
Zhou Shenga3832fd2007-02-07 06:14:53 +0000233 sub_1(pVal, getNumWords(), 1);
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000234 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000235}
236
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000237/// add - This function adds the integer array x to the integer array Y and
238/// places the result in dest.
239/// @returns the carry out from the addition
240/// @brief General addition of 64-bit integer arrays
Reid Spencer9d6c9192007-02-24 03:58:46 +0000241static bool add(uint64_t *dest, const uint64_t *x, const uint64_t *y,
242 uint32_t len) {
243 bool carry = false;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000244 for (uint32_t i = 0; i< len; ++i) {
Reid Spencer92904632007-02-23 01:57:13 +0000245 uint64_t limit = std::min(x[i],y[i]); // must come first in case dest == x
Reid Spencer54362ca2007-02-20 23:40:25 +0000246 dest[i] = x[i] + y[i] + carry;
Reid Spencer60c0a6a2007-02-21 05:44:56 +0000247 carry = dest[i] < limit || (carry && dest[i] == limit);
Reid Spencer5e0a8512007-02-17 03:16:00 +0000248 }
249 return carry;
250}
251
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000252/// Adds the RHS APint to this APInt.
253/// @returns this, after addition of RHS.
254/// @brief Addition assignment operator.
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000255APInt& APInt::operator+=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000256 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer54362ca2007-02-20 23:40:25 +0000257 if (isSingleWord())
258 VAL += RHS.VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000259 else {
Reid Spencer54362ca2007-02-20 23:40:25 +0000260 add(pVal, pVal, RHS.pVal, getNumWords());
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000261 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000262 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000263}
264
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000265/// Subtracts the integer array y from the integer array x
266/// @returns returns the borrow out.
267/// @brief Generalized subtraction of 64-bit integer arrays.
Reid Spencer9d6c9192007-02-24 03:58:46 +0000268static bool sub(uint64_t *dest, const uint64_t *x, const uint64_t *y,
269 uint32_t len) {
Reid Spencer385f7542007-02-21 03:55:44 +0000270 bool borrow = false;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000271 for (uint32_t i = 0; i < len; ++i) {
Reid Spencer385f7542007-02-21 03:55:44 +0000272 uint64_t x_tmp = borrow ? x[i] - 1 : x[i];
273 borrow = y[i] > x_tmp || (borrow && x[i] == 0);
274 dest[i] = x_tmp - y[i];
Reid Spencer5e0a8512007-02-17 03:16:00 +0000275 }
Reid Spencer54362ca2007-02-20 23:40:25 +0000276 return borrow;
Reid Spencer5e0a8512007-02-17 03:16:00 +0000277}
278
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000279/// Subtracts the RHS APInt from this APInt
280/// @returns this, after subtraction
281/// @brief Subtraction assignment operator.
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000282APInt& APInt::operator-=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000283 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000284 if (isSingleWord())
Reid Spencer54362ca2007-02-20 23:40:25 +0000285 VAL -= RHS.VAL;
286 else
287 sub(pVal, pVal, RHS.pVal, getNumWords());
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000288 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000289}
290
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000291/// Multiplies an integer array, x by a a uint64_t integer and places the result
292/// into dest.
293/// @returns the carry out of the multiplication.
294/// @brief Multiply a multi-digit APInt by a single digit (64-bit) integer.
Reid Spencer610fad82007-02-24 10:01:42 +0000295static uint64_t mul_1(uint64_t dest[], uint64_t x[], uint32_t len, uint64_t y) {
296 // Split y into high 32-bit part (hy) and low 32-bit part (ly)
Reid Spencer5e0a8512007-02-17 03:16:00 +0000297 uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000298 uint64_t carry = 0;
299
300 // For each digit of x.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000301 for (uint32_t i = 0; i < len; ++i) {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000302 // Split x into high and low words
303 uint64_t lx = x[i] & 0xffffffffULL;
304 uint64_t hx = x[i] >> 32;
305 // hasCarry - A flag to indicate if there is a carry to the next digit.
Reid Spencer5e0a8512007-02-17 03:16:00 +0000306 // hasCarry == 0, no carry
307 // hasCarry == 1, has carry
308 // hasCarry == 2, no carry and the calculation result == 0.
309 uint8_t hasCarry = 0;
310 dest[i] = carry + lx * ly;
311 // Determine if the add above introduces carry.
312 hasCarry = (dest[i] < carry) ? 1 : 0;
313 carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
314 // The upper limit of carry can be (2^32 - 1)(2^32 - 1) +
315 // (2^32 - 1) + 2^32 = 2^64.
316 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
317
318 carry += (lx * hy) & 0xffffffffULL;
319 dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
320 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) +
321 (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
322 }
Reid Spencer5e0a8512007-02-17 03:16:00 +0000323 return carry;
324}
325
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000326/// Multiplies integer array x by integer array y and stores the result into
327/// the integer array dest. Note that dest's size must be >= xlen + ylen.
328/// @brief Generalized multiplicate of integer arrays.
Reid Spencer610fad82007-02-24 10:01:42 +0000329static void mul(uint64_t dest[], uint64_t x[], uint32_t xlen, uint64_t y[],
330 uint32_t ylen) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000331 dest[xlen] = mul_1(dest, x, xlen, y[0]);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000332 for (uint32_t i = 1; i < ylen; ++i) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000333 uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
Reid Spencere0cdd332007-02-21 08:21:52 +0000334 uint64_t carry = 0, lx = 0, hx = 0;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000335 for (uint32_t j = 0; j < xlen; ++j) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000336 lx = x[j] & 0xffffffffULL;
337 hx = x[j] >> 32;
338 // hasCarry - A flag to indicate if has carry.
339 // hasCarry == 0, no carry
340 // hasCarry == 1, has carry
341 // hasCarry == 2, no carry and the calculation result == 0.
342 uint8_t hasCarry = 0;
343 uint64_t resul = carry + lx * ly;
344 hasCarry = (resul < carry) ? 1 : 0;
345 carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
346 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
347
348 carry += (lx * hy) & 0xffffffffULL;
349 resul = (carry << 32) | (resul & 0xffffffffULL);
350 dest[i+j] += resul;
351 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
352 (carry >> 32) + (dest[i+j] < resul ? 1 : 0) +
353 ((lx * hy) >> 32) + hx * hy;
354 }
355 dest[i+xlen] = carry;
356 }
357}
358
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000359APInt& APInt::operator*=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000360 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencere0cdd332007-02-21 08:21:52 +0000361 if (isSingleWord()) {
Reid Spencer61eb1802007-02-20 20:42:10 +0000362 VAL *= RHS.VAL;
Reid Spencere0cdd332007-02-21 08:21:52 +0000363 clearUnusedBits();
364 return *this;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000365 }
Reid Spencere0cdd332007-02-21 08:21:52 +0000366
367 // Get some bit facts about LHS and check for zero
368 uint32_t lhsBits = getActiveBits();
369 uint32_t lhsWords = !lhsBits ? 0 : whichWord(lhsBits - 1) + 1;
370 if (!lhsWords)
371 // 0 * X ===> 0
372 return *this;
373
374 // Get some bit facts about RHS and check for zero
375 uint32_t rhsBits = RHS.getActiveBits();
376 uint32_t rhsWords = !rhsBits ? 0 : whichWord(rhsBits - 1) + 1;
377 if (!rhsWords) {
378 // X * 0 ===> 0
379 clear();
380 return *this;
381 }
382
383 // Allocate space for the result
384 uint32_t destWords = rhsWords + lhsWords;
385 uint64_t *dest = getMemory(destWords);
386
387 // Perform the long multiply
388 mul(dest, pVal, lhsWords, RHS.pVal, rhsWords);
389
390 // Copy result back into *this
391 clear();
392 uint32_t wordsToCopy = destWords >= getNumWords() ? getNumWords() : destWords;
393 memcpy(pVal, dest, wordsToCopy * APINT_WORD_SIZE);
394
395 // delete dest array and return
396 delete[] dest;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000397 return *this;
398}
399
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000400APInt& APInt::operator&=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000401 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000402 if (isSingleWord()) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000403 VAL &= RHS.VAL;
404 return *this;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000405 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000406 uint32_t numWords = getNumWords();
407 for (uint32_t i = 0; i < numWords; ++i)
408 pVal[i] &= RHS.pVal[i];
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000409 return *this;
410}
411
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000412APInt& APInt::operator|=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000413 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000414 if (isSingleWord()) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000415 VAL |= RHS.VAL;
416 return *this;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000417 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000418 uint32_t numWords = getNumWords();
419 for (uint32_t i = 0; i < numWords; ++i)
420 pVal[i] |= RHS.pVal[i];
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000421 return *this;
422}
423
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000424APInt& APInt::operator^=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000425 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000426 if (isSingleWord()) {
Reid Spencerf2c521c2007-02-18 06:39:42 +0000427 VAL ^= RHS.VAL;
Reid Spencer54362ca2007-02-20 23:40:25 +0000428 this->clearUnusedBits();
Reid Spencerf2c521c2007-02-18 06:39:42 +0000429 return *this;
430 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000431 uint32_t numWords = getNumWords();
432 for (uint32_t i = 0; i < numWords; ++i)
433 pVal[i] ^= RHS.pVal[i];
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000434 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000435}
436
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000437APInt APInt::operator&(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000438 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spenceraf0e9562007-02-18 18:38:44 +0000439 if (isSingleWord())
440 return APInt(getBitWidth(), VAL & RHS.VAL);
441
Reid Spenceraf0e9562007-02-18 18:38:44 +0000442 uint32_t numWords = getNumWords();
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000443 uint64_t* val = getMemory(numWords);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000444 for (uint32_t i = 0; i < numWords; ++i)
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000445 val[i] = pVal[i] & RHS.pVal[i];
446 return APInt(val, getBitWidth());
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 Spenceraf0e9562007-02-18 18:38:44 +0000451 if (isSingleWord())
452 return APInt(getBitWidth(), VAL | RHS.VAL);
Reid Spencer54362ca2007-02-20 23:40:25 +0000453
Reid Spenceraf0e9562007-02-18 18:38:44 +0000454 uint32_t numWords = getNumWords();
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000455 uint64_t *val = getMemory(numWords);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000456 for (uint32_t i = 0; i < numWords; ++i)
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000457 val[i] = pVal[i] | RHS.pVal[i];
458 return APInt(val, getBitWidth());
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000459}
460
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000461APInt APInt::operator^(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000462 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000463 if (isSingleWord())
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000464 return APInt(BitWidth, VAL ^ RHS.VAL);
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000465
Reid Spenceraf0e9562007-02-18 18:38:44 +0000466 uint32_t numWords = getNumWords();
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000467 uint64_t *val = getMemory(numWords);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000468 for (uint32_t i = 0; i < numWords; ++i)
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000469 val[i] = pVal[i] ^ RHS.pVal[i];
470
471 // 0^0==1 so clear the high bits in case they got set.
472 return APInt(val, getBitWidth()).clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000473}
474
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000475bool APInt::operator !() const {
476 if (isSingleWord())
477 return !VAL;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000478
479 for (uint32_t i = 0; i < getNumWords(); ++i)
480 if (pVal[i])
481 return false;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000482 return true;
483}
484
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000485APInt APInt::operator*(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000486 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000487 if (isSingleWord())
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000488 return APInt(BitWidth, VAL * RHS.VAL);
Reid Spencer61eb1802007-02-20 20:42:10 +0000489 APInt Result(*this);
490 Result *= RHS;
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000491 return Result.clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000492}
493
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000494APInt APInt::operator+(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000495 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000496 if (isSingleWord())
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000497 return APInt(BitWidth, VAL + RHS.VAL);
Reid Spencer54362ca2007-02-20 23:40:25 +0000498 APInt Result(BitWidth, 0);
499 add(Result.pVal, this->pVal, RHS.pVal, getNumWords());
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000500 return Result.clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000501}
502
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000503APInt APInt::operator-(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000504 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000505 if (isSingleWord())
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000506 return APInt(BitWidth, VAL - RHS.VAL);
Reid Spencer54362ca2007-02-20 23:40:25 +0000507 APInt Result(BitWidth, 0);
508 sub(Result.pVal, this->pVal, RHS.pVal, getNumWords());
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000509 return Result.clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000510}
511
Reid Spenceraf0e9562007-02-18 18:38:44 +0000512bool APInt::operator[](uint32_t bitPosition) const {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000513 return (maskBit(bitPosition) &
514 (isSingleWord() ? VAL : pVal[whichWord(bitPosition)])) != 0;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000515}
516
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000517bool APInt::operator==(const APInt& RHS) const {
Reid Spencer9ac44112007-02-26 23:38:21 +0000518 assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths");
Reid Spencer54362ca2007-02-20 23:40:25 +0000519 if (isSingleWord())
520 return VAL == RHS.VAL;
521
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000522 // Get some facts about the number of bits used in the two operands.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000523 uint32_t n1 = getActiveBits();
524 uint32_t n2 = RHS.getActiveBits();
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000525
526 // If the number of bits isn't the same, they aren't equal
Reid Spencer54362ca2007-02-20 23:40:25 +0000527 if (n1 != n2)
528 return false;
529
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000530 // If the number of bits fits in a word, we only need to compare the low word.
Reid Spencer54362ca2007-02-20 23:40:25 +0000531 if (n1 <= APINT_BITS_PER_WORD)
532 return pVal[0] == RHS.pVal[0];
533
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000534 // Otherwise, compare everything
Reid Spencer54362ca2007-02-20 23:40:25 +0000535 for (int i = whichWord(n1 - 1); i >= 0; --i)
536 if (pVal[i] != RHS.pVal[i])
537 return false;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000538 return true;
539}
540
Zhou Shenga3832fd2007-02-07 06:14:53 +0000541bool APInt::operator==(uint64_t Val) const {
542 if (isSingleWord())
543 return VAL == Val;
Reid Spencer54362ca2007-02-20 23:40:25 +0000544
545 uint32_t n = getActiveBits();
546 if (n <= APINT_BITS_PER_WORD)
547 return pVal[0] == Val;
548 else
549 return false;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000550}
551
Reid Spencere81d2da2007-02-16 22:36:51 +0000552bool APInt::ult(const APInt& RHS) const {
553 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
554 if (isSingleWord())
555 return VAL < RHS.VAL;
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000556
557 // Get active bit length of both operands
558 uint32_t n1 = getActiveBits();
559 uint32_t n2 = RHS.getActiveBits();
560
561 // If magnitude of LHS is less than RHS, return true.
562 if (n1 < n2)
563 return true;
564
565 // If magnitude of RHS is greather than LHS, return false.
566 if (n2 < n1)
567 return false;
568
569 // If they bot fit in a word, just compare the low order word
570 if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
571 return pVal[0] < RHS.pVal[0];
572
573 // Otherwise, compare all words
Reid Spencer1fa111e2007-02-27 18:23:40 +0000574 uint32_t topWord = whichWord(std::max(n1,n2)-1);
575 for (int i = topWord; i >= 0; --i) {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000576 if (pVal[i] > RHS.pVal[i])
Reid Spencere81d2da2007-02-16 22:36:51 +0000577 return false;
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000578 if (pVal[i] < RHS.pVal[i])
579 return true;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000580 }
581 return false;
582}
583
Reid Spencere81d2da2007-02-16 22:36:51 +0000584bool APInt::slt(const APInt& RHS) const {
585 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
Reid Spencera58f0582007-02-18 20:09:41 +0000586 if (isSingleWord()) {
587 int64_t lhsSext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
588 int64_t rhsSext = (int64_t(RHS.VAL) << (64-BitWidth)) >> (64-BitWidth);
589 return lhsSext < rhsSext;
Reid Spencere81d2da2007-02-16 22:36:51 +0000590 }
Reid Spencera58f0582007-02-18 20:09:41 +0000591
592 APInt lhs(*this);
Reid Spencer1fa111e2007-02-27 18:23:40 +0000593 APInt rhs(RHS);
594 bool lhsNeg = isNegative();
595 bool rhsNeg = rhs.isNegative();
596 if (lhsNeg) {
597 // Sign bit is set so perform two's complement to make it positive
Reid Spencera58f0582007-02-18 20:09:41 +0000598 lhs.flip();
599 lhs++;
600 }
Reid Spencer1fa111e2007-02-27 18:23:40 +0000601 if (rhsNeg) {
602 // Sign bit is set so perform two's complement to make it positive
Reid Spencera58f0582007-02-18 20:09:41 +0000603 rhs.flip();
604 rhs++;
605 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000606
607 // Now we have unsigned values to compare so do the comparison if necessary
608 // based on the negativeness of the values.
Reid Spencer1fa111e2007-02-27 18:23:40 +0000609 if (lhsNeg)
610 if (rhsNeg)
611 return lhs.ugt(rhs);
Reid Spencera58f0582007-02-18 20:09:41 +0000612 else
613 return true;
Reid Spencer1fa111e2007-02-27 18:23:40 +0000614 else if (rhsNeg)
Reid Spencera58f0582007-02-18 20:09:41 +0000615 return false;
616 else
617 return lhs.ult(rhs);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000618}
619
Reid Spenceraf0e9562007-02-18 18:38:44 +0000620APInt& APInt::set(uint32_t bitPosition) {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000621 if (isSingleWord())
622 VAL |= maskBit(bitPosition);
623 else
624 pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000625 return *this;
626}
627
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000628APInt& APInt::set() {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000629 if (isSingleWord()) {
630 VAL = -1ULL;
631 return clearUnusedBits();
Zhou Shengb04973e2007-02-15 06:36:31 +0000632 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000633
634 // Set all the bits in all the words.
Zhou Sheng6dbe2332007-03-21 04:34:37 +0000635 for (uint32_t i = 0; i < getNumWords(); ++i)
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000636 pVal[i] = -1ULL;
637 // Clear the unused ones
638 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000639}
640
641/// Set the given bit to 0 whose position is given as "bitPosition".
642/// @brief Set a given bit to 0.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000643APInt& APInt::clear(uint32_t bitPosition) {
644 if (isSingleWord())
645 VAL &= ~maskBit(bitPosition);
646 else
647 pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000648 return *this;
649}
650
651/// @brief Set every bit to 0.
652APInt& APInt::clear() {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000653 if (isSingleWord())
654 VAL = 0;
Zhou Shenga3832fd2007-02-07 06:14:53 +0000655 else
Reid Spencera58f0582007-02-18 20:09:41 +0000656 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000657 return *this;
658}
659
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000660/// @brief Bitwise NOT operator. Performs a bitwise logical NOT operation on
661/// this APInt.
662APInt APInt::operator~() const {
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000663 APInt Result(*this);
664 Result.flip();
665 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000666}
667
668/// @brief Toggle every bit to its opposite value.
669APInt& APInt::flip() {
Reid Spencer9eec2412007-02-25 23:44:53 +0000670 if (isSingleWord()) {
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000671 VAL ^= -1ULL;
Reid Spencer9eec2412007-02-25 23:44:53 +0000672 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000673 }
Reid Spencer9eec2412007-02-25 23:44:53 +0000674 for (uint32_t i = 0; i < getNumWords(); ++i)
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000675 pVal[i] ^= -1ULL;
Reid Spencer9eec2412007-02-25 23:44:53 +0000676 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000677}
678
679/// Toggle a given bit to its opposite value whose position is given
680/// as "bitPosition".
681/// @brief Toggles a given bit to its opposite value.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000682APInt& APInt::flip(uint32_t bitPosition) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000683 assert(bitPosition < BitWidth && "Out of the bit-width range!");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000684 if ((*this)[bitPosition]) clear(bitPosition);
685 else set(bitPosition);
686 return *this;
687}
688
Reid Spencer57ae4f52007-04-13 19:19:07 +0000689uint32_t APInt::getBitsNeeded(const char* str, uint32_t slen, uint8_t radix) {
690 assert(str != 0 && "Invalid value string");
691 assert(slen > 0 && "Invalid string length");
692
693 // Each computation below needs to know if its negative
694 uint32_t isNegative = str[0] == '-';
695 if (isNegative) {
696 slen--;
697 str++;
698 }
699 // For radixes of power-of-two values, the bits required is accurately and
700 // easily computed
701 if (radix == 2)
702 return slen + isNegative;
703 if (radix == 8)
704 return slen * 3 + isNegative;
705 if (radix == 16)
706 return slen * 4 + isNegative;
707
708 // Otherwise it must be radix == 10, the hard case
709 assert(radix == 10 && "Invalid radix");
710
711 // This is grossly inefficient but accurate. We could probably do something
712 // with a computation of roughly slen*64/20 and then adjust by the value of
713 // the first few digits. But, I'm not sure how accurate that could be.
714
715 // Compute a sufficient number of bits that is always large enough but might
716 // be too large. This avoids the assertion in the constructor.
717 uint32_t sufficient = slen*64/18;
718
719 // Convert to the actual binary value.
720 APInt tmp(sufficient, str, slen, radix);
721
722 // Compute how many bits are required.
Reid Spencer0468ab32007-04-14 00:00:10 +0000723 return isNegative + tmp.logBase2() + 1;
Reid Spencer57ae4f52007-04-13 19:19:07 +0000724}
725
Reid Spencer794f4722007-02-26 21:02:27 +0000726uint64_t APInt::getHashValue() const {
Reid Spencer9ac44112007-02-26 23:38:21 +0000727 // Put the bit width into the low order bits.
728 uint64_t hash = BitWidth;
Reid Spencer794f4722007-02-26 21:02:27 +0000729
730 // Add the sum of the words to the hash.
731 if (isSingleWord())
Reid Spencer9ac44112007-02-26 23:38:21 +0000732 hash += VAL << 6; // clear separation of up to 64 bits
Reid Spencer794f4722007-02-26 21:02:27 +0000733 else
734 for (uint32_t i = 0; i < getNumWords(); ++i)
Reid Spencer9ac44112007-02-26 23:38:21 +0000735 hash += pVal[i] << 6; // clear sepration of up to 64 bits
Reid Spencer794f4722007-02-26 21:02:27 +0000736 return hash;
737}
738
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000739/// HiBits - This function returns the high "numBits" bits of this APInt.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000740APInt APInt::getHiBits(uint32_t numBits) const {
Reid Spencere81d2da2007-02-16 22:36:51 +0000741 return APIntOps::lshr(*this, BitWidth - numBits);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000742}
743
744/// LoBits - This function returns the low "numBits" bits of this APInt.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000745APInt APInt::getLoBits(uint32_t numBits) const {
Reid Spencere81d2da2007-02-16 22:36:51 +0000746 return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits),
747 BitWidth - numBits);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000748}
749
Reid Spencere81d2da2007-02-16 22:36:51 +0000750bool APInt::isPowerOf2() const {
751 return (!!*this) && !(*this & (*this - APInt(BitWidth,1)));
752}
753
Reid Spenceraf0e9562007-02-18 18:38:44 +0000754uint32_t APInt::countLeadingZeros() const {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000755 uint32_t Count = 0;
Reid Spencere549c492007-02-21 00:29:48 +0000756 if (isSingleWord())
757 Count = CountLeadingZeros_64(VAL);
758 else {
759 for (uint32_t i = getNumWords(); i > 0u; --i) {
760 if (pVal[i-1] == 0)
761 Count += APINT_BITS_PER_WORD;
762 else {
763 Count += CountLeadingZeros_64(pVal[i-1]);
764 break;
765 }
766 }
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000767 }
Reid Spencerab2b2c82007-02-22 00:22:00 +0000768 uint32_t remainder = BitWidth % APINT_BITS_PER_WORD;
769 if (remainder)
770 Count -= APINT_BITS_PER_WORD - remainder;
Chris Lattner9e513ac2007-11-23 22:42:31 +0000771 return std::min(Count, BitWidth);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000772}
773
Reid Spencer681dcd12007-02-27 21:59:26 +0000774static uint32_t countLeadingOnes_64(uint64_t V, uint32_t skip) {
775 uint32_t Count = 0;
776 if (skip)
777 V <<= skip;
778 while (V && (V & (1ULL << 63))) {
779 Count++;
780 V <<= 1;
781 }
782 return Count;
783}
784
785uint32_t APInt::countLeadingOnes() const {
786 if (isSingleWord())
787 return countLeadingOnes_64(VAL, APINT_BITS_PER_WORD - BitWidth);
788
789 uint32_t highWordBits = BitWidth % APINT_BITS_PER_WORD;
790 uint32_t shift = (highWordBits == 0 ? 0 : APINT_BITS_PER_WORD - highWordBits);
791 int i = getNumWords() - 1;
792 uint32_t Count = countLeadingOnes_64(pVal[i], shift);
793 if (Count == highWordBits) {
794 for (i--; i >= 0; --i) {
795 if (pVal[i] == -1ULL)
796 Count += APINT_BITS_PER_WORD;
797 else {
798 Count += countLeadingOnes_64(pVal[i], 0);
799 break;
800 }
801 }
802 }
803 return Count;
804}
805
Reid Spenceraf0e9562007-02-18 18:38:44 +0000806uint32_t APInt::countTrailingZeros() const {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000807 if (isSingleWord())
Anton Korobeynikov97d37262007-12-24 11:16:47 +0000808 return std::min(uint32_t(CountTrailingZeros_64(VAL)), BitWidth);
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000809 uint32_t Count = 0;
810 uint32_t i = 0;
811 for (; i < getNumWords() && pVal[i] == 0; ++i)
812 Count += APINT_BITS_PER_WORD;
813 if (i < getNumWords())
814 Count += CountTrailingZeros_64(pVal[i]);
Chris Lattner5e557122007-11-23 22:36:25 +0000815 return std::min(Count, BitWidth);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000816}
817
Dan Gohman42dd77f2008-02-13 21:11:05 +0000818uint32_t APInt::countTrailingOnes() const {
819 if (isSingleWord())
820 return std::min(uint32_t(CountTrailingOnes_64(VAL)), BitWidth);
821 uint32_t Count = 0;
822 uint32_t i = 0;
Dan Gohman5a0e7b42008-02-14 22:38:45 +0000823 for (; i < getNumWords() && pVal[i] == -1ULL; ++i)
Dan Gohman42dd77f2008-02-13 21:11:05 +0000824 Count += APINT_BITS_PER_WORD;
825 if (i < getNumWords())
826 Count += CountTrailingOnes_64(pVal[i]);
827 return std::min(Count, BitWidth);
828}
829
Reid Spenceraf0e9562007-02-18 18:38:44 +0000830uint32_t APInt::countPopulation() const {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000831 if (isSingleWord())
832 return CountPopulation_64(VAL);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000833 uint32_t Count = 0;
834 for (uint32_t i = 0; i < getNumWords(); ++i)
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000835 Count += CountPopulation_64(pVal[i]);
836 return Count;
837}
838
Reid Spencere81d2da2007-02-16 22:36:51 +0000839APInt APInt::byteSwap() const {
840 assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
841 if (BitWidth == 16)
Jeff Cohen09dfd8e2007-03-20 20:42:36 +0000842 return APInt(BitWidth, ByteSwap_16(uint16_t(VAL)));
Reid Spencere81d2da2007-02-16 22:36:51 +0000843 else if (BitWidth == 32)
Jeff Cohen09dfd8e2007-03-20 20:42:36 +0000844 return APInt(BitWidth, ByteSwap_32(uint32_t(VAL)));
Reid Spencere81d2da2007-02-16 22:36:51 +0000845 else if (BitWidth == 48) {
Jeff Cohen09dfd8e2007-03-20 20:42:36 +0000846 uint32_t Tmp1 = uint32_t(VAL >> 16);
Zhou Shengb04973e2007-02-15 06:36:31 +0000847 Tmp1 = ByteSwap_32(Tmp1);
Jeff Cohen09dfd8e2007-03-20 20:42:36 +0000848 uint16_t Tmp2 = uint16_t(VAL);
Zhou Shengb04973e2007-02-15 06:36:31 +0000849 Tmp2 = ByteSwap_16(Tmp2);
Jeff Cohen09dfd8e2007-03-20 20:42:36 +0000850 return APInt(BitWidth, (uint64_t(Tmp2) << 32) | Tmp1);
Reid Spencere81d2da2007-02-16 22:36:51 +0000851 } else if (BitWidth == 64)
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000852 return APInt(BitWidth, ByteSwap_64(VAL));
Zhou Shengb04973e2007-02-15 06:36:31 +0000853 else {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000854 APInt Result(BitWidth, 0);
Zhou Shengb04973e2007-02-15 06:36:31 +0000855 char *pByte = (char*)Result.pVal;
Reid Spencera58f0582007-02-18 20:09:41 +0000856 for (uint32_t i = 0; i < BitWidth / APINT_WORD_SIZE / 2; ++i) {
Zhou Shengb04973e2007-02-15 06:36:31 +0000857 char Tmp = pByte[i];
Reid Spencera58f0582007-02-18 20:09:41 +0000858 pByte[i] = pByte[BitWidth / APINT_WORD_SIZE - 1 - i];
859 pByte[BitWidth / APINT_WORD_SIZE - i - 1] = Tmp;
Zhou Shengb04973e2007-02-15 06:36:31 +0000860 }
861 return Result;
862 }
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000863}
864
Zhou Sheng0b706b12007-02-08 14:35:19 +0000865APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1,
866 const APInt& API2) {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000867 APInt A = API1, B = API2;
868 while (!!B) {
869 APInt T = B;
Reid Spencere81d2da2007-02-16 22:36:51 +0000870 B = APIntOps::urem(A, B);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000871 A = T;
872 }
873 return A;
874}
Chris Lattner6ad4c142007-02-06 05:38:37 +0000875
Reid Spencer1fa111e2007-02-27 18:23:40 +0000876APInt llvm::APIntOps::RoundDoubleToAPInt(double Double, uint32_t width) {
Zhou Shengd93f00c2007-02-12 20:02:55 +0000877 union {
878 double D;
879 uint64_t I;
880 } T;
881 T.D = Double;
Reid Spencer30f44f32007-02-27 01:28:10 +0000882
883 // Get the sign bit from the highest order bit
Zhou Shengd93f00c2007-02-12 20:02:55 +0000884 bool isNeg = T.I >> 63;
Reid Spencer30f44f32007-02-27 01:28:10 +0000885
886 // Get the 11-bit exponent and adjust for the 1023 bit bias
Zhou Shengd93f00c2007-02-12 20:02:55 +0000887 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
Reid Spencer30f44f32007-02-27 01:28:10 +0000888
889 // If the exponent is negative, the value is < 0 so just return 0.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000890 if (exp < 0)
Reid Spencerff605762007-02-28 01:30:08 +0000891 return APInt(width, 0u);
Reid Spencer30f44f32007-02-27 01:28:10 +0000892
893 // Extract the mantissa by clearing the top 12 bits (sign + exponent).
894 uint64_t mantissa = (T.I & (~0ULL >> 12)) | 1ULL << 52;
895
896 // If the exponent doesn't shift all bits out of the mantissa
Zhou Shengd93f00c2007-02-12 20:02:55 +0000897 if (exp < 52)
Reid Spencer1fa111e2007-02-27 18:23:40 +0000898 return isNeg ? -APInt(width, mantissa >> (52 - exp)) :
899 APInt(width, mantissa >> (52 - exp));
900
901 // If the client didn't provide enough bits for us to shift the mantissa into
902 // then the result is undefined, just return 0
903 if (width <= exp - 52)
904 return APInt(width, 0);
Reid Spencer30f44f32007-02-27 01:28:10 +0000905
906 // Otherwise, we have to shift the mantissa bits up to the right location
Reid Spencer1fa111e2007-02-27 18:23:40 +0000907 APInt Tmp(width, mantissa);
Evan Cheng48e8c802008-05-02 21:15:08 +0000908 Tmp = Tmp.shl((uint32_t)exp - 52);
Zhou Shengd93f00c2007-02-12 20:02:55 +0000909 return isNeg ? -Tmp : Tmp;
910}
911
Reid Spencerdb3faa62007-02-13 22:41:58 +0000912/// RoundToDouble - This function convert this APInt to a double.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000913/// The layout for double is as following (IEEE Standard 754):
914/// --------------------------------------
915/// | Sign Exponent Fraction Bias |
916/// |-------------------------------------- |
917/// | 1[63] 11[62-52] 52[51-00] 1023 |
918/// --------------------------------------
Reid Spencere81d2da2007-02-16 22:36:51 +0000919double APInt::roundToDouble(bool isSigned) const {
Reid Spencer9c0696f2007-02-20 08:51:03 +0000920
921 // Handle the simple case where the value is contained in one uint64_t.
Reid Spencera58f0582007-02-18 20:09:41 +0000922 if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
923 if (isSigned) {
924 int64_t sext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
925 return double(sext);
926 } else
927 return double(VAL);
928 }
929
Reid Spencer9c0696f2007-02-20 08:51:03 +0000930 // Determine if the value is negative.
Reid Spencere81d2da2007-02-16 22:36:51 +0000931 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
Reid Spencer9c0696f2007-02-20 08:51:03 +0000932
933 // Construct the absolute value if we're negative.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000934 APInt Tmp(isNeg ? -(*this) : (*this));
Reid Spencer9c0696f2007-02-20 08:51:03 +0000935
936 // Figure out how many bits we're using.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000937 uint32_t n = Tmp.getActiveBits();
Zhou Shengd93f00c2007-02-12 20:02:55 +0000938
Reid Spencer9c0696f2007-02-20 08:51:03 +0000939 // The exponent (without bias normalization) is just the number of bits
940 // we are using. Note that the sign bit is gone since we constructed the
941 // absolute value.
942 uint64_t exp = n;
Zhou Shengd93f00c2007-02-12 20:02:55 +0000943
Reid Spencer9c0696f2007-02-20 08:51:03 +0000944 // Return infinity for exponent overflow
945 if (exp > 1023) {
946 if (!isSigned || !isNeg)
Jeff Cohen09dfd8e2007-03-20 20:42:36 +0000947 return std::numeric_limits<double>::infinity();
Reid Spencer9c0696f2007-02-20 08:51:03 +0000948 else
Jeff Cohen09dfd8e2007-03-20 20:42:36 +0000949 return -std::numeric_limits<double>::infinity();
Reid Spencer9c0696f2007-02-20 08:51:03 +0000950 }
951 exp += 1023; // Increment for 1023 bias
952
953 // Number of bits in mantissa is 52. To obtain the mantissa value, we must
954 // extract the high 52 bits from the correct words in pVal.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000955 uint64_t mantissa;
Reid Spencer9c0696f2007-02-20 08:51:03 +0000956 unsigned hiWord = whichWord(n-1);
957 if (hiWord == 0) {
958 mantissa = Tmp.pVal[0];
959 if (n > 52)
960 mantissa >>= n - 52; // shift down, we want the top 52 bits.
961 } else {
962 assert(hiWord > 0 && "huh?");
963 uint64_t hibits = Tmp.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
964 uint64_t lobits = Tmp.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
965 mantissa = hibits | lobits;
966 }
967
Zhou Shengd93f00c2007-02-12 20:02:55 +0000968 // The leading bit of mantissa is implicit, so get rid of it.
Reid Spencer443b5702007-02-18 00:44:22 +0000969 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
Zhou Shengd93f00c2007-02-12 20:02:55 +0000970 union {
971 double D;
972 uint64_t I;
973 } T;
974 T.I = sign | (exp << 52) | mantissa;
975 return T.D;
976}
977
Reid Spencere81d2da2007-02-16 22:36:51 +0000978// Truncate to new width.
Reid Spencer94900772007-02-28 17:34:32 +0000979APInt &APInt::trunc(uint32_t width) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000980 assert(width < BitWidth && "Invalid APInt Truncate request");
Reid Spencer9af18872007-12-11 06:53:58 +0000981 assert(width >= MIN_INT_BITS && "Can't truncate to 0 bits");
Reid Spencer9eec2412007-02-25 23:44:53 +0000982 uint32_t wordsBefore = getNumWords();
983 BitWidth = width;
984 uint32_t wordsAfter = getNumWords();
985 if (wordsBefore != wordsAfter) {
986 if (wordsAfter == 1) {
987 uint64_t *tmp = pVal;
988 VAL = pVal[0];
Reid Spencer9ac44112007-02-26 23:38:21 +0000989 delete [] tmp;
Reid Spencer9eec2412007-02-25 23:44:53 +0000990 } else {
991 uint64_t *newVal = getClearedMemory(wordsAfter);
992 for (uint32_t i = 0; i < wordsAfter; ++i)
993 newVal[i] = pVal[i];
Reid Spencer9ac44112007-02-26 23:38:21 +0000994 delete [] pVal;
Reid Spencer9eec2412007-02-25 23:44:53 +0000995 pVal = newVal;
996 }
997 }
Reid Spencer94900772007-02-28 17:34:32 +0000998 return clearUnusedBits();
Reid Spencere81d2da2007-02-16 22:36:51 +0000999}
1000
1001// Sign extend to a new width.
Reid Spencer94900772007-02-28 17:34:32 +00001002APInt &APInt::sext(uint32_t width) {
Reid Spencere81d2da2007-02-16 22:36:51 +00001003 assert(width > BitWidth && "Invalid APInt SignExtend request");
Reid Spencer9af18872007-12-11 06:53:58 +00001004 assert(width <= MAX_INT_BITS && "Too many bits");
Reid Spencer9eec2412007-02-25 23:44:53 +00001005 // If the sign bit isn't set, this is the same as zext.
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001006 if (!isNegative()) {
Reid Spencer9eec2412007-02-25 23:44:53 +00001007 zext(width);
Reid Spencer94900772007-02-28 17:34:32 +00001008 return *this;
Reid Spencer9eec2412007-02-25 23:44:53 +00001009 }
1010
1011 // The sign bit is set. First, get some facts
1012 uint32_t wordsBefore = getNumWords();
1013 uint32_t wordBits = BitWidth % APINT_BITS_PER_WORD;
1014 BitWidth = width;
1015 uint32_t wordsAfter = getNumWords();
1016
1017 // Mask the high order word appropriately
1018 if (wordsBefore == wordsAfter) {
1019 uint32_t newWordBits = width % APINT_BITS_PER_WORD;
1020 // The extension is contained to the wordsBefore-1th word.
Reid Spencer36184ed2007-03-02 01:19:42 +00001021 uint64_t mask = ~0ULL;
1022 if (newWordBits)
1023 mask >>= APINT_BITS_PER_WORD - newWordBits;
1024 mask <<= wordBits;
Reid Spencer9eec2412007-02-25 23:44:53 +00001025 if (wordsBefore == 1)
1026 VAL |= mask;
1027 else
1028 pVal[wordsBefore-1] |= mask;
Reid Spencer295e40a2007-03-01 23:30:25 +00001029 return clearUnusedBits();
Reid Spencer9eec2412007-02-25 23:44:53 +00001030 }
1031
Reid Spencerf30b1882007-02-25 23:54:00 +00001032 uint64_t mask = wordBits == 0 ? 0 : ~0ULL << wordBits;
Reid Spencer9eec2412007-02-25 23:44:53 +00001033 uint64_t *newVal = getMemory(wordsAfter);
1034 if (wordsBefore == 1)
1035 newVal[0] = VAL | mask;
1036 else {
1037 for (uint32_t i = 0; i < wordsBefore; ++i)
1038 newVal[i] = pVal[i];
1039 newVal[wordsBefore-1] |= mask;
1040 }
1041 for (uint32_t i = wordsBefore; i < wordsAfter; i++)
1042 newVal[i] = -1ULL;
1043 if (wordsBefore != 1)
Reid Spencer9ac44112007-02-26 23:38:21 +00001044 delete [] pVal;
Reid Spencer9eec2412007-02-25 23:44:53 +00001045 pVal = newVal;
Reid Spencer94900772007-02-28 17:34:32 +00001046 return clearUnusedBits();
Reid Spencere81d2da2007-02-16 22:36:51 +00001047}
1048
1049// Zero extend to a new width.
Reid Spencer94900772007-02-28 17:34:32 +00001050APInt &APInt::zext(uint32_t width) {
Reid Spencere81d2da2007-02-16 22:36:51 +00001051 assert(width > BitWidth && "Invalid APInt ZeroExtend request");
Reid Spencer9af18872007-12-11 06:53:58 +00001052 assert(width <= MAX_INT_BITS && "Too many bits");
Reid Spencer9eec2412007-02-25 23:44:53 +00001053 uint32_t wordsBefore = getNumWords();
1054 BitWidth = width;
1055 uint32_t wordsAfter = getNumWords();
1056 if (wordsBefore != wordsAfter) {
1057 uint64_t *newVal = getClearedMemory(wordsAfter);
1058 if (wordsBefore == 1)
1059 newVal[0] = VAL;
1060 else
1061 for (uint32_t i = 0; i < wordsBefore; ++i)
1062 newVal[i] = pVal[i];
1063 if (wordsBefore != 1)
Reid Spencer9ac44112007-02-26 23:38:21 +00001064 delete [] pVal;
Reid Spencer9eec2412007-02-25 23:44:53 +00001065 pVal = newVal;
1066 }
Reid Spencer94900772007-02-28 17:34:32 +00001067 return *this;
Reid Spencere81d2da2007-02-16 22:36:51 +00001068}
1069
Reid Spencer68e23002007-03-01 17:15:32 +00001070APInt &APInt::zextOrTrunc(uint32_t width) {
1071 if (BitWidth < width)
1072 return zext(width);
1073 if (BitWidth > width)
1074 return trunc(width);
1075 return *this;
1076}
1077
1078APInt &APInt::sextOrTrunc(uint32_t width) {
1079 if (BitWidth < width)
1080 return sext(width);
1081 if (BitWidth > width)
1082 return trunc(width);
1083 return *this;
1084}
1085
Zhou Shengff4304f2007-02-09 07:48:24 +00001086/// Arithmetic right-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +00001087/// @brief Arithmetic right-shift function.
Dan Gohmancf609572008-02-29 01:40:47 +00001088APInt APInt::ashr(const APInt &shiftAmt) const {
Evan Cheng48e8c802008-05-02 21:15:08 +00001089 return ashr((uint32_t)shiftAmt.getLimitedValue(BitWidth));
Dan Gohmancf609572008-02-29 01:40:47 +00001090}
1091
1092/// Arithmetic right-shift this APInt by shiftAmt.
1093/// @brief Arithmetic right-shift function.
Reid Spenceraf0e9562007-02-18 18:38:44 +00001094APInt APInt::ashr(uint32_t shiftAmt) const {
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001095 assert(shiftAmt <= BitWidth && "Invalid shift amount");
Reid Spencer46f9c942007-03-02 22:39:11 +00001096 // Handle a degenerate case
1097 if (shiftAmt == 0)
1098 return *this;
1099
1100 // Handle single word shifts with built-in ashr
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001101 if (isSingleWord()) {
1102 if (shiftAmt == BitWidth)
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001103 return APInt(BitWidth, 0); // undefined
1104 else {
1105 uint32_t SignBit = APINT_BITS_PER_WORD - BitWidth;
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001106 return APInt(BitWidth,
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001107 (((int64_t(VAL) << SignBit) >> SignBit) >> shiftAmt));
1108 }
Zhou Sheng0b706b12007-02-08 14:35:19 +00001109 }
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001110
Reid Spencer46f9c942007-03-02 22:39:11 +00001111 // If all the bits were shifted out, the result is, technically, undefined.
1112 // We return -1 if it was negative, 0 otherwise. We check this early to avoid
1113 // issues in the algorithm below.
Chris Lattnera5ae15e2007-05-03 18:15:36 +00001114 if (shiftAmt == BitWidth) {
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001115 if (isNegative())
Zhou Shengbfde7d62008-06-05 13:27:38 +00001116 return APInt(BitWidth, -1ULL, true);
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001117 else
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001118 return APInt(BitWidth, 0);
Chris Lattnera5ae15e2007-05-03 18:15:36 +00001119 }
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001120
1121 // Create some space for the result.
1122 uint64_t * val = new uint64_t[getNumWords()];
1123
Reid Spencer46f9c942007-03-02 22:39:11 +00001124 // Compute some values needed by the following shift algorithms
1125 uint32_t wordShift = shiftAmt % APINT_BITS_PER_WORD; // bits to shift per word
1126 uint32_t offset = shiftAmt / APINT_BITS_PER_WORD; // word offset for shift
1127 uint32_t breakWord = getNumWords() - 1 - offset; // last word affected
1128 uint32_t bitsInWord = whichBit(BitWidth); // how many bits in last word?
1129 if (bitsInWord == 0)
1130 bitsInWord = APINT_BITS_PER_WORD;
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001131
1132 // If we are shifting whole words, just move whole words
1133 if (wordShift == 0) {
Reid Spencer46f9c942007-03-02 22:39:11 +00001134 // Move the words containing significant bits
1135 for (uint32_t i = 0; i <= breakWord; ++i)
1136 val[i] = pVal[i+offset]; // move whole word
1137
1138 // Adjust the top significant word for sign bit fill, if negative
1139 if (isNegative())
1140 if (bitsInWord < APINT_BITS_PER_WORD)
1141 val[breakWord] |= ~0ULL << bitsInWord; // set high bits
1142 } else {
1143 // Shift the low order words
1144 for (uint32_t i = 0; i < breakWord; ++i) {
1145 // This combines the shifted corresponding word with the low bits from
1146 // the next word (shifted into this word's high bits).
1147 val[i] = (pVal[i+offset] >> wordShift) |
1148 (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift));
1149 }
1150
1151 // Shift the break word. In this case there are no bits from the next word
1152 // to include in this word.
1153 val[breakWord] = pVal[breakWord+offset] >> wordShift;
1154
1155 // Deal with sign extenstion in the break word, and possibly the word before
1156 // it.
Chris Lattnera5ae15e2007-05-03 18:15:36 +00001157 if (isNegative()) {
Reid Spencer46f9c942007-03-02 22:39:11 +00001158 if (wordShift > bitsInWord) {
1159 if (breakWord > 0)
1160 val[breakWord-1] |=
1161 ~0ULL << (APINT_BITS_PER_WORD - (wordShift - bitsInWord));
1162 val[breakWord] |= ~0ULL;
1163 } else
1164 val[breakWord] |= (~0ULL << (bitsInWord - wordShift));
Chris Lattnera5ae15e2007-05-03 18:15:36 +00001165 }
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001166 }
1167
Reid Spencer46f9c942007-03-02 22:39:11 +00001168 // Remaining words are 0 or -1, just assign them.
1169 uint64_t fillValue = (isNegative() ? -1ULL : 0);
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001170 for (uint32_t i = breakWord+1; i < getNumWords(); ++i)
Reid Spencer46f9c942007-03-02 22:39:11 +00001171 val[i] = fillValue;
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001172 return APInt(val, BitWidth).clearUnusedBits();
Zhou Sheng0b706b12007-02-08 14:35:19 +00001173}
1174
Zhou Shengff4304f2007-02-09 07:48:24 +00001175/// Logical right-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +00001176/// @brief Logical right-shift function.
Dan Gohmancf609572008-02-29 01:40:47 +00001177APInt APInt::lshr(const APInt &shiftAmt) const {
Evan Cheng48e8c802008-05-02 21:15:08 +00001178 return lshr((uint32_t)shiftAmt.getLimitedValue(BitWidth));
Dan Gohmancf609572008-02-29 01:40:47 +00001179}
1180
1181/// Logical right-shift this APInt by shiftAmt.
1182/// @brief Logical right-shift function.
Reid Spenceraf0e9562007-02-18 18:38:44 +00001183APInt APInt::lshr(uint32_t shiftAmt) const {
Chris Lattnera5ae15e2007-05-03 18:15:36 +00001184 if (isSingleWord()) {
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001185 if (shiftAmt == BitWidth)
1186 return APInt(BitWidth, 0);
1187 else
1188 return APInt(BitWidth, this->VAL >> shiftAmt);
Chris Lattnera5ae15e2007-05-03 18:15:36 +00001189 }
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001190
Reid Spencerba81c2b2007-02-26 01:19:48 +00001191 // If all the bits were shifted out, the result is 0. This avoids issues
1192 // with shifting by the size of the integer type, which produces undefined
1193 // results. We define these "undefined results" to always be 0.
1194 if (shiftAmt == BitWidth)
1195 return APInt(BitWidth, 0);
1196
Reid Spencer02ae8b72007-05-17 06:26:29 +00001197 // If none of the bits are shifted out, the result is *this. This avoids
1198 // issues with shifting byt he size of the integer type, which produces
1199 // undefined results in the code below. This is also an optimization.
1200 if (shiftAmt == 0)
1201 return *this;
1202
Reid Spencerba81c2b2007-02-26 01:19:48 +00001203 // Create some space for the result.
1204 uint64_t * val = new uint64_t[getNumWords()];
1205
1206 // If we are shifting less than a word, compute the shift with a simple carry
1207 if (shiftAmt < APINT_BITS_PER_WORD) {
1208 uint64_t carry = 0;
1209 for (int i = getNumWords()-1; i >= 0; --i) {
Reid Spenceraf8fb192007-03-01 05:39:56 +00001210 val[i] = (pVal[i] >> shiftAmt) | carry;
Reid Spencerba81c2b2007-02-26 01:19:48 +00001211 carry = pVal[i] << (APINT_BITS_PER_WORD - shiftAmt);
1212 }
1213 return APInt(val, BitWidth).clearUnusedBits();
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001214 }
1215
Reid Spencerba81c2b2007-02-26 01:19:48 +00001216 // Compute some values needed by the remaining shift algorithms
1217 uint32_t wordShift = shiftAmt % APINT_BITS_PER_WORD;
1218 uint32_t offset = shiftAmt / APINT_BITS_PER_WORD;
1219
1220 // If we are shifting whole words, just move whole words
1221 if (wordShift == 0) {
1222 for (uint32_t i = 0; i < getNumWords() - offset; ++i)
1223 val[i] = pVal[i+offset];
1224 for (uint32_t i = getNumWords()-offset; i < getNumWords(); i++)
1225 val[i] = 0;
1226 return APInt(val,BitWidth).clearUnusedBits();
1227 }
1228
1229 // Shift the low order words
1230 uint32_t breakWord = getNumWords() - offset -1;
1231 for (uint32_t i = 0; i < breakWord; ++i)
Reid Spenceraf8fb192007-03-01 05:39:56 +00001232 val[i] = (pVal[i+offset] >> wordShift) |
1233 (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift));
Reid Spencerba81c2b2007-02-26 01:19:48 +00001234 // Shift the break word.
1235 val[breakWord] = pVal[breakWord+offset] >> wordShift;
1236
1237 // Remaining words are 0
1238 for (uint32_t i = breakWord+1; i < getNumWords(); ++i)
1239 val[i] = 0;
1240 return APInt(val, BitWidth).clearUnusedBits();
Zhou Sheng0b706b12007-02-08 14:35:19 +00001241}
1242
Zhou Shengff4304f2007-02-09 07:48:24 +00001243/// Left-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +00001244/// @brief Left-shift function.
Dan Gohmancf609572008-02-29 01:40:47 +00001245APInt APInt::shl(const APInt &shiftAmt) const {
1246 // It's undefined behavior in C to shift by BitWidth or greater, but
Evan Cheng48e8c802008-05-02 21:15:08 +00001247 return shl((uint32_t)shiftAmt.getLimitedValue(BitWidth));
Dan Gohmancf609572008-02-29 01:40:47 +00001248}
1249
1250/// Left-shift this APInt by shiftAmt.
1251/// @brief Left-shift function.
Reid Spenceraf0e9562007-02-18 18:38:44 +00001252APInt APInt::shl(uint32_t shiftAmt) const {
Reid Spencer5bce8542007-02-24 20:19:37 +00001253 assert(shiftAmt <= BitWidth && "Invalid shift amount");
Reid Spencer87553802007-02-25 00:56:44 +00001254 if (isSingleWord()) {
Reid Spencer5bce8542007-02-24 20:19:37 +00001255 if (shiftAmt == BitWidth)
Reid Spencer87553802007-02-25 00:56:44 +00001256 return APInt(BitWidth, 0); // avoid undefined shift results
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001257 return APInt(BitWidth, VAL << shiftAmt);
Zhou Sheng0b706b12007-02-08 14:35:19 +00001258 }
Reid Spencer5bce8542007-02-24 20:19:37 +00001259
Reid Spencer87553802007-02-25 00:56:44 +00001260 // If all the bits were shifted out, the result is 0. This avoids issues
1261 // with shifting by the size of the integer type, which produces undefined
1262 // results. We define these "undefined results" to always be 0.
1263 if (shiftAmt == BitWidth)
1264 return APInt(BitWidth, 0);
1265
Reid Spencer92c72832007-05-12 18:01:57 +00001266 // If none of the bits are shifted out, the result is *this. This avoids a
1267 // lshr by the words size in the loop below which can produce incorrect
1268 // results. It also avoids the expensive computation below for a common case.
1269 if (shiftAmt == 0)
1270 return *this;
1271
Reid Spencer87553802007-02-25 00:56:44 +00001272 // Create some space for the result.
1273 uint64_t * val = new uint64_t[getNumWords()];
1274
1275 // If we are shifting less than a word, do it the easy way
1276 if (shiftAmt < APINT_BITS_PER_WORD) {
1277 uint64_t carry = 0;
Reid Spencer87553802007-02-25 00:56:44 +00001278 for (uint32_t i = 0; i < getNumWords(); i++) {
1279 val[i] = pVal[i] << shiftAmt | carry;
1280 carry = pVal[i] >> (APINT_BITS_PER_WORD - shiftAmt);
1281 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001282 return APInt(val, BitWidth).clearUnusedBits();
Reid Spencer5bce8542007-02-24 20:19:37 +00001283 }
1284
Reid Spencer87553802007-02-25 00:56:44 +00001285 // Compute some values needed by the remaining shift algorithms
1286 uint32_t wordShift = shiftAmt % APINT_BITS_PER_WORD;
1287 uint32_t offset = shiftAmt / APINT_BITS_PER_WORD;
1288
1289 // If we are shifting whole words, just move whole words
1290 if (wordShift == 0) {
1291 for (uint32_t i = 0; i < offset; i++)
1292 val[i] = 0;
1293 for (uint32_t i = offset; i < getNumWords(); i++)
1294 val[i] = pVal[i-offset];
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001295 return APInt(val,BitWidth).clearUnusedBits();
Reid Spencer5bce8542007-02-24 20:19:37 +00001296 }
Reid Spencer87553802007-02-25 00:56:44 +00001297
1298 // Copy whole words from this to Result.
1299 uint32_t i = getNumWords() - 1;
1300 for (; i > offset; --i)
1301 val[i] = pVal[i-offset] << wordShift |
1302 pVal[i-offset-1] >> (APINT_BITS_PER_WORD - wordShift);
Reid Spencer438d71e2007-02-25 01:08:58 +00001303 val[offset] = pVal[0] << wordShift;
Reid Spencer87553802007-02-25 00:56:44 +00001304 for (i = 0; i < offset; ++i)
1305 val[i] = 0;
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001306 return APInt(val, BitWidth).clearUnusedBits();
Zhou Sheng0b706b12007-02-08 14:35:19 +00001307}
1308
Dan Gohmancf609572008-02-29 01:40:47 +00001309APInt APInt::rotl(const APInt &rotateAmt) const {
Evan Cheng48e8c802008-05-02 21:15:08 +00001310 return rotl((uint32_t)rotateAmt.getLimitedValue(BitWidth));
Dan Gohmancf609572008-02-29 01:40:47 +00001311}
1312
Reid Spencer19dc32a2007-05-13 23:44:59 +00001313APInt APInt::rotl(uint32_t rotateAmt) const {
Reid Spencer69944e82007-05-14 00:15:28 +00001314 if (rotateAmt == 0)
1315 return *this;
Reid Spencer19dc32a2007-05-13 23:44:59 +00001316 // Don't get too fancy, just use existing shift/or facilities
1317 APInt hi(*this);
1318 APInt lo(*this);
1319 hi.shl(rotateAmt);
1320 lo.lshr(BitWidth - rotateAmt);
1321 return hi | lo;
1322}
1323
Dan Gohmancf609572008-02-29 01:40:47 +00001324APInt APInt::rotr(const APInt &rotateAmt) const {
Evan Cheng48e8c802008-05-02 21:15:08 +00001325 return rotr((uint32_t)rotateAmt.getLimitedValue(BitWidth));
Dan Gohmancf609572008-02-29 01:40:47 +00001326}
1327
Reid Spencer19dc32a2007-05-13 23:44:59 +00001328APInt APInt::rotr(uint32_t rotateAmt) const {
Reid Spencer69944e82007-05-14 00:15:28 +00001329 if (rotateAmt == 0)
1330 return *this;
Reid Spencer19dc32a2007-05-13 23:44:59 +00001331 // Don't get too fancy, just use existing shift/or facilities
1332 APInt hi(*this);
1333 APInt lo(*this);
1334 lo.lshr(rotateAmt);
1335 hi.shl(BitWidth - rotateAmt);
1336 return hi | lo;
1337}
Reid Spenceraf8fb192007-03-01 05:39:56 +00001338
1339// Square Root - this method computes and returns the square root of "this".
1340// Three mechanisms are used for computation. For small values (<= 5 bits),
1341// a table lookup is done. This gets some performance for common cases. For
1342// values using less than 52 bits, the value is converted to double and then
1343// the libc sqrt function is called. The result is rounded and then converted
1344// back to a uint64_t which is then used to construct the result. Finally,
1345// the Babylonian method for computing square roots is used.
1346APInt APInt::sqrt() const {
1347
1348 // Determine the magnitude of the value.
1349 uint32_t magnitude = getActiveBits();
1350
1351 // Use a fast table for some small values. This also gets rid of some
1352 // rounding errors in libc sqrt for small values.
1353 if (magnitude <= 5) {
Reid Spencer4e1e87f2007-03-01 17:47:31 +00001354 static const uint8_t results[32] = {
Reid Spencerb5ca2cd2007-03-01 06:23:32 +00001355 /* 0 */ 0,
1356 /* 1- 2 */ 1, 1,
1357 /* 3- 6 */ 2, 2, 2, 2,
1358 /* 7-12 */ 3, 3, 3, 3, 3, 3,
1359 /* 13-20 */ 4, 4, 4, 4, 4, 4, 4, 4,
1360 /* 21-30 */ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
1361 /* 31 */ 6
1362 };
1363 return APInt(BitWidth, results[ (isSingleWord() ? VAL : pVal[0]) ]);
Reid Spenceraf8fb192007-03-01 05:39:56 +00001364 }
1365
1366 // If the magnitude of the value fits in less than 52 bits (the precision of
1367 // an IEEE double precision floating point value), then we can use the
1368 // libc sqrt function which will probably use a hardware sqrt computation.
1369 // This should be faster than the algorithm below.
Jeff Cohenca5183d2007-03-05 00:00:42 +00001370 if (magnitude < 52) {
1371#ifdef _MSC_VER
1372 // Amazingly, VC++ doesn't have round().
1373 return APInt(BitWidth,
1374 uint64_t(::sqrt(double(isSingleWord()?VAL:pVal[0]))) + 0.5);
1375#else
Reid Spenceraf8fb192007-03-01 05:39:56 +00001376 return APInt(BitWidth,
1377 uint64_t(::round(::sqrt(double(isSingleWord()?VAL:pVal[0])))));
Jeff Cohenca5183d2007-03-05 00:00:42 +00001378#endif
1379 }
Reid Spenceraf8fb192007-03-01 05:39:56 +00001380
1381 // Okay, all the short cuts are exhausted. We must compute it. The following
1382 // is a classical Babylonian method for computing the square root. This code
1383 // was adapted to APINt from a wikipedia article on such computations.
1384 // See http://www.wikipedia.org/ and go to the page named
1385 // Calculate_an_integer_square_root.
1386 uint32_t nbits = BitWidth, i = 4;
1387 APInt testy(BitWidth, 16);
1388 APInt x_old(BitWidth, 1);
1389 APInt x_new(BitWidth, 0);
1390 APInt two(BitWidth, 2);
1391
1392 // Select a good starting value using binary logarithms.
1393 for (;; i += 2, testy = testy.shl(2))
1394 if (i >= nbits || this->ule(testy)) {
1395 x_old = x_old.shl(i / 2);
1396 break;
1397 }
1398
1399 // Use the Babylonian method to arrive at the integer square root:
1400 for (;;) {
1401 x_new = (this->udiv(x_old) + x_old).udiv(two);
1402 if (x_old.ule(x_new))
1403 break;
1404 x_old = x_new;
1405 }
1406
1407 // Make sure we return the closest approximation
Reid Spencerf09aef72007-03-02 04:21:55 +00001408 // NOTE: The rounding calculation below is correct. It will produce an
1409 // off-by-one discrepancy with results from pari/gp. That discrepancy has been
1410 // determined to be a rounding issue with pari/gp as it begins to use a
1411 // floating point representation after 192 bits. There are no discrepancies
1412 // between this algorithm and pari/gp for bit widths < 192 bits.
Reid Spenceraf8fb192007-03-01 05:39:56 +00001413 APInt square(x_old * x_old);
1414 APInt nextSquare((x_old + 1) * (x_old +1));
1415 if (this->ult(square))
1416 return x_old;
Reid Spencerf09aef72007-03-02 04:21:55 +00001417 else if (this->ule(nextSquare)) {
1418 APInt midpoint((nextSquare - square).udiv(two));
1419 APInt offset(*this - square);
1420 if (offset.ult(midpoint))
Reid Spenceraf8fb192007-03-01 05:39:56 +00001421 return x_old;
Reid Spencerf09aef72007-03-02 04:21:55 +00001422 else
1423 return x_old + 1;
1424 } else
Reid Spenceraf8fb192007-03-01 05:39:56 +00001425 assert(0 && "Error in APInt::sqrt computation");
1426 return x_old + 1;
1427}
1428
Wojciech Matyjewicz300c6c52008-06-23 19:39:50 +00001429/// Computes the multiplicative inverse of this APInt for a given modulo. The
1430/// iterative extended Euclidean algorithm is used to solve for this value,
1431/// however we simplify it to speed up calculating only the inverse, and take
1432/// advantage of div+rem calculations. We also use some tricks to avoid copying
1433/// (potentially large) APInts around.
1434APInt APInt::multiplicativeInverse(const APInt& modulo) const {
1435 assert(ult(modulo) && "This APInt must be smaller than the modulo");
1436
1437 // Using the properties listed at the following web page (accessed 06/21/08):
1438 // http://www.numbertheory.org/php/euclid.html
1439 // (especially the properties numbered 3, 4 and 9) it can be proved that
1440 // BitWidth bits suffice for all the computations in the algorithm implemented
1441 // below. More precisely, this number of bits suffice if the multiplicative
1442 // inverse exists, but may not suffice for the general extended Euclidean
1443 // algorithm.
1444
1445 APInt r[2] = { modulo, *this };
1446 APInt t[2] = { APInt(BitWidth, 0), APInt(BitWidth, 1) };
1447 APInt q(BitWidth, 0);
1448
1449 unsigned i;
1450 for (i = 0; r[i^1] != 0; i ^= 1) {
1451 // An overview of the math without the confusing bit-flipping:
1452 // q = r[i-2] / r[i-1]
1453 // r[i] = r[i-2] % r[i-1]
1454 // t[i] = t[i-2] - t[i-1] * q
1455 udivrem(r[i], r[i^1], q, r[i]);
1456 t[i] -= t[i^1] * q;
1457 }
1458
1459 // If this APInt and the modulo are not coprime, there is no multiplicative
1460 // inverse, so return 0. We check this by looking at the next-to-last
1461 // remainder, which is the gcd(*this,modulo) as calculated by the Euclidean
1462 // algorithm.
1463 if (r[i] != 1)
1464 return APInt(BitWidth, 0);
1465
1466 // The next-to-last t is the multiplicative inverse. However, we are
1467 // interested in a positive inverse. Calcuate a positive one from a negative
1468 // one if necessary. A simple addition of the modulo suffices because
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00001469 // abs(t[i]) is known to be less than *this/2 (see the link above).
Wojciech Matyjewicz300c6c52008-06-23 19:39:50 +00001470 return t[i].isNegative() ? t[i] + modulo : t[i];
1471}
1472
Reid Spencer9c0696f2007-02-20 08:51:03 +00001473/// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
1474/// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
1475/// variables here have the same names as in the algorithm. Comments explain
1476/// the algorithm and any deviation from it.
1477static void KnuthDiv(uint32_t *u, uint32_t *v, uint32_t *q, uint32_t* r,
1478 uint32_t m, uint32_t n) {
1479 assert(u && "Must provide dividend");
1480 assert(v && "Must provide divisor");
1481 assert(q && "Must provide quotient");
Reid Spencer9d6c9192007-02-24 03:58:46 +00001482 assert(u != v && u != q && v != q && "Must us different memory");
Reid Spencer9c0696f2007-02-20 08:51:03 +00001483 assert(n>1 && "n must be > 1");
1484
1485 // Knuth uses the value b as the base of the number system. In our case b
1486 // is 2^31 so we just set it to -1u.
1487 uint64_t b = uint64_t(1) << 32;
1488
Reid Spencer9d6c9192007-02-24 03:58:46 +00001489 DEBUG(cerr << "KnuthDiv: m=" << m << " n=" << n << '\n');
1490 DEBUG(cerr << "KnuthDiv: original:");
1491 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << std::setbase(16) << u[i]);
1492 DEBUG(cerr << " by");
1493 DEBUG(for (int i = n; i >0; i--) cerr << " " << std::setbase(16) << v[i-1]);
1494 DEBUG(cerr << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001495 // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
1496 // u and v by d. Note that we have taken Knuth's advice here to use a power
1497 // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
1498 // 2 allows us to shift instead of multiply and it is easy to determine the
1499 // shift amount from the leading zeros. We are basically normalizing the u
1500 // and v so that its high bits are shifted to the top of v's range without
1501 // overflow. Note that this can require an extra word in u so that u must
1502 // be of length m+n+1.
1503 uint32_t shift = CountLeadingZeros_32(v[n-1]);
1504 uint32_t v_carry = 0;
1505 uint32_t u_carry = 0;
1506 if (shift) {
1507 for (uint32_t i = 0; i < m+n; ++i) {
1508 uint32_t u_tmp = u[i] >> (32 - shift);
1509 u[i] = (u[i] << shift) | u_carry;
1510 u_carry = u_tmp;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001511 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001512 for (uint32_t i = 0; i < n; ++i) {
1513 uint32_t v_tmp = v[i] >> (32 - shift);
1514 v[i] = (v[i] << shift) | v_carry;
1515 v_carry = v_tmp;
1516 }
1517 }
1518 u[m+n] = u_carry;
Reid Spencer9d6c9192007-02-24 03:58:46 +00001519 DEBUG(cerr << "KnuthDiv: normal:");
1520 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << std::setbase(16) << u[i]);
1521 DEBUG(cerr << " by");
1522 DEBUG(for (int i = n; i >0; i--) cerr << " " << std::setbase(16) << v[i-1]);
1523 DEBUG(cerr << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001524
1525 // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
1526 int j = m;
1527 do {
Reid Spencer9d6c9192007-02-24 03:58:46 +00001528 DEBUG(cerr << "KnuthDiv: quotient digit #" << j << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001529 // D3. [Calculate q'.].
1530 // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
1531 // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
1532 // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
1533 // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test
1534 // on v[n-2] determines at high speed most of the cases in which the trial
1535 // value qp is one too large, and it eliminates all cases where qp is two
1536 // too large.
Reid Spencer92904632007-02-23 01:57:13 +00001537 uint64_t dividend = ((uint64_t(u[j+n]) << 32) + u[j+n-1]);
Reid Spencer9d6c9192007-02-24 03:58:46 +00001538 DEBUG(cerr << "KnuthDiv: dividend == " << dividend << '\n');
Reid Spencer92904632007-02-23 01:57:13 +00001539 uint64_t qp = dividend / v[n-1];
1540 uint64_t rp = dividend % v[n-1];
Reid Spencer9c0696f2007-02-20 08:51:03 +00001541 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1542 qp--;
1543 rp += v[n-1];
Reid Spencer610fad82007-02-24 10:01:42 +00001544 if (rp < b && (qp == b || qp*v[n-2] > b*rp + u[j+n-2]))
Reid Spencer9d6c9192007-02-24 03:58:46 +00001545 qp--;
Reid Spencer92904632007-02-23 01:57:13 +00001546 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001547 DEBUG(cerr << "KnuthDiv: qp == " << qp << ", rp == " << rp << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001548
Reid Spencer92904632007-02-23 01:57:13 +00001549 // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with
1550 // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation
1551 // consists of a simple multiplication by a one-place number, combined with
Reid Spencer610fad82007-02-24 10:01:42 +00001552 // a subtraction.
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001553 bool isNeg = false;
Reid Spencer92904632007-02-23 01:57:13 +00001554 for (uint32_t i = 0; i < n; ++i) {
Reid Spencer610fad82007-02-24 10:01:42 +00001555 uint64_t u_tmp = uint64_t(u[j+i]) | (uint64_t(u[j+i+1]) << 32);
Reid Spencer9d6c9192007-02-24 03:58:46 +00001556 uint64_t subtrahend = uint64_t(qp) * uint64_t(v[i]);
Reid Spencer610fad82007-02-24 10:01:42 +00001557 bool borrow = subtrahend > u_tmp;
Reid Spencer9d6c9192007-02-24 03:58:46 +00001558 DEBUG(cerr << "KnuthDiv: u_tmp == " << u_tmp
Reid Spencer610fad82007-02-24 10:01:42 +00001559 << ", subtrahend == " << subtrahend
1560 << ", borrow = " << borrow << '\n');
Reid Spencer9d6c9192007-02-24 03:58:46 +00001561
Reid Spencer610fad82007-02-24 10:01:42 +00001562 uint64_t result = u_tmp - subtrahend;
1563 uint32_t k = j + i;
Evan Cheng48e8c802008-05-02 21:15:08 +00001564 u[k++] = (uint32_t)(result & (b-1)); // subtract low word
1565 u[k++] = (uint32_t)(result >> 32); // subtract high word
Reid Spencer610fad82007-02-24 10:01:42 +00001566 while (borrow && k <= m+n) { // deal with borrow to the left
1567 borrow = u[k] == 0;
1568 u[k]--;
1569 k++;
1570 }
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001571 isNeg |= borrow;
Reid Spencer610fad82007-02-24 10:01:42 +00001572 DEBUG(cerr << "KnuthDiv: u[j+i] == " << u[j+i] << ", u[j+i+1] == " <<
1573 u[j+i+1] << '\n');
Reid Spencer9d6c9192007-02-24 03:58:46 +00001574 }
1575 DEBUG(cerr << "KnuthDiv: after subtraction:");
1576 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << u[i]);
1577 DEBUG(cerr << '\n');
Reid Spencer610fad82007-02-24 10:01:42 +00001578 // The digits (u[j+n]...u[j]) should be kept positive; if the result of
1579 // this step is actually negative, (u[j+n]...u[j]) should be left as the
1580 // true value plus b**(n+1), namely as the b's complement of
Reid Spencer92904632007-02-23 01:57:13 +00001581 // the true value, and a "borrow" to the left should be remembered.
1582 //
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001583 if (isNeg) {
Reid Spencer610fad82007-02-24 10:01:42 +00001584 bool carry = true; // true because b's complement is "complement + 1"
1585 for (uint32_t i = 0; i <= m+n; ++i) {
1586 u[i] = ~u[i] + carry; // b's complement
1587 carry = carry && u[i] == 0;
Reid Spencer9d6c9192007-02-24 03:58:46 +00001588 }
Reid Spencer92904632007-02-23 01:57:13 +00001589 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001590 DEBUG(cerr << "KnuthDiv: after complement:");
1591 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << u[i]);
1592 DEBUG(cerr << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001593
1594 // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
1595 // negative, go to step D6; otherwise go on to step D7.
Evan Cheng48e8c802008-05-02 21:15:08 +00001596 q[j] = (uint32_t)qp;
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001597 if (isNeg) {
Reid Spencer9c0696f2007-02-20 08:51:03 +00001598 // D6. [Add back]. The probability that this step is necessary is very
1599 // small, on the order of only 2/b. Make sure that test data accounts for
Reid Spencer92904632007-02-23 01:57:13 +00001600 // this possibility. Decrease q[j] by 1
1601 q[j]--;
1602 // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]).
1603 // A carry will occur to the left of u[j+n], and it should be ignored
1604 // since it cancels with the borrow that occurred in D4.
1605 bool carry = false;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001606 for (uint32_t i = 0; i < n; i++) {
Reid Spencer9d6c9192007-02-24 03:58:46 +00001607 uint32_t limit = std::min(u[j+i],v[i]);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001608 u[j+i] += v[i] + carry;
Reid Spencer9d6c9192007-02-24 03:58:46 +00001609 carry = u[j+i] < limit || (carry && u[j+i] == limit);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001610 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001611 u[j+n] += carry;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001612 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001613 DEBUG(cerr << "KnuthDiv: after correction:");
1614 DEBUG(for (int i = m+n; i >=0; i--) cerr <<" " << u[i]);
1615 DEBUG(cerr << "\nKnuthDiv: digit result = " << q[j] << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001616
Reid Spencer92904632007-02-23 01:57:13 +00001617 // D7. [Loop on j.] Decrease j by one. Now if j >= 0, go back to D3.
1618 } while (--j >= 0);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001619
Reid Spencer9d6c9192007-02-24 03:58:46 +00001620 DEBUG(cerr << "KnuthDiv: quotient:");
1621 DEBUG(for (int i = m; i >=0; i--) cerr <<" " << q[i]);
1622 DEBUG(cerr << '\n');
1623
Reid Spencer9c0696f2007-02-20 08:51:03 +00001624 // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
1625 // remainder may be obtained by dividing u[...] by d. If r is non-null we
1626 // compute the remainder (urem uses this).
1627 if (r) {
1628 // The value d is expressed by the "shift" value above since we avoided
1629 // multiplication by d by using a shift left. So, all we have to do is
1630 // shift right here. In order to mak
Reid Spencer1050ec52007-02-24 20:38:01 +00001631 if (shift) {
1632 uint32_t carry = 0;
1633 DEBUG(cerr << "KnuthDiv: remainder:");
1634 for (int i = n-1; i >= 0; i--) {
1635 r[i] = (u[i] >> shift) | carry;
1636 carry = u[i] << (32 - shift);
1637 DEBUG(cerr << " " << r[i]);
1638 }
1639 } else {
1640 for (int i = n-1; i >= 0; i--) {
1641 r[i] = u[i];
1642 DEBUG(cerr << " " << r[i]);
1643 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001644 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001645 DEBUG(cerr << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001646 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001647 DEBUG(cerr << std::setbase(10) << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001648}
1649
Reid Spencer9c0696f2007-02-20 08:51:03 +00001650void APInt::divide(const APInt LHS, uint32_t lhsWords,
1651 const APInt &RHS, uint32_t rhsWords,
1652 APInt *Quotient, APInt *Remainder)
1653{
1654 assert(lhsWords >= rhsWords && "Fractional result");
1655
1656 // First, compose the values into an array of 32-bit words instead of
1657 // 64-bit words. This is a necessity of both the "short division" algorithm
1658 // and the the Knuth "classical algorithm" which requires there to be native
1659 // operations for +, -, and * on an m bit value with an m*2 bit result. We
1660 // can't use 64-bit operands here because we don't have native results of
1661 // 128-bits. Furthremore, casting the 64-bit values to 32-bit values won't
1662 // work on large-endian machines.
1663 uint64_t mask = ~0ull >> (sizeof(uint32_t)*8);
1664 uint32_t n = rhsWords * 2;
1665 uint32_t m = (lhsWords * 2) - n;
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001666
1667 // Allocate space for the temporary values we need either on the stack, if
1668 // it will fit, or on the heap if it won't.
1669 uint32_t SPACE[128];
1670 uint32_t *U = 0;
1671 uint32_t *V = 0;
1672 uint32_t *Q = 0;
1673 uint32_t *R = 0;
1674 if ((Remainder?4:3)*n+2*m+1 <= 128) {
1675 U = &SPACE[0];
1676 V = &SPACE[m+n+1];
1677 Q = &SPACE[(m+n+1) + n];
1678 if (Remainder)
1679 R = &SPACE[(m+n+1) + n + (m+n)];
1680 } else {
1681 U = new uint32_t[m + n + 1];
1682 V = new uint32_t[n];
1683 Q = new uint32_t[m+n];
1684 if (Remainder)
1685 R = new uint32_t[n];
1686 }
1687
1688 // Initialize the dividend
Reid Spencer9c0696f2007-02-20 08:51:03 +00001689 memset(U, 0, (m+n+1)*sizeof(uint32_t));
1690 for (unsigned i = 0; i < lhsWords; ++i) {
Reid Spencer15aab8a2007-02-22 00:58:45 +00001691 uint64_t tmp = (LHS.getNumWords() == 1 ? LHS.VAL : LHS.pVal[i]);
Evan Cheng48e8c802008-05-02 21:15:08 +00001692 U[i * 2] = (uint32_t)(tmp & mask);
1693 U[i * 2 + 1] = (uint32_t)(tmp >> (sizeof(uint32_t)*8));
Reid Spencer9c0696f2007-02-20 08:51:03 +00001694 }
1695 U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
1696
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001697 // Initialize the divisor
Reid Spencer9c0696f2007-02-20 08:51:03 +00001698 memset(V, 0, (n)*sizeof(uint32_t));
1699 for (unsigned i = 0; i < rhsWords; ++i) {
Reid Spencer15aab8a2007-02-22 00:58:45 +00001700 uint64_t tmp = (RHS.getNumWords() == 1 ? RHS.VAL : RHS.pVal[i]);
Evan Cheng48e8c802008-05-02 21:15:08 +00001701 V[i * 2] = (uint32_t)(tmp & mask);
1702 V[i * 2 + 1] = (uint32_t)(tmp >> (sizeof(uint32_t)*8));
Reid Spencer9c0696f2007-02-20 08:51:03 +00001703 }
1704
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001705 // initialize the quotient and remainder
Reid Spencer9c0696f2007-02-20 08:51:03 +00001706 memset(Q, 0, (m+n) * sizeof(uint32_t));
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001707 if (Remainder)
Reid Spencer9c0696f2007-02-20 08:51:03 +00001708 memset(R, 0, n * sizeof(uint32_t));
Reid Spencer9c0696f2007-02-20 08:51:03 +00001709
1710 // Now, adjust m and n for the Knuth division. n is the number of words in
1711 // the divisor. m is the number of words by which the dividend exceeds the
1712 // divisor (i.e. m+n is the length of the dividend). These sizes must not
1713 // contain any zero words or the Knuth algorithm fails.
1714 for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
1715 n--;
1716 m++;
1717 }
1718 for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
1719 m--;
1720
1721 // If we're left with only a single word for the divisor, Knuth doesn't work
1722 // so we implement the short division algorithm here. This is much simpler
1723 // and faster because we are certain that we can divide a 64-bit quantity
1724 // by a 32-bit quantity at hardware speed and short division is simply a
1725 // series of such operations. This is just like doing short division but we
1726 // are using base 2^32 instead of base 10.
1727 assert(n != 0 && "Divide by zero?");
1728 if (n == 1) {
1729 uint32_t divisor = V[0];
1730 uint32_t remainder = 0;
1731 for (int i = m+n-1; i >= 0; i--) {
1732 uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i];
1733 if (partial_dividend == 0) {
1734 Q[i] = 0;
1735 remainder = 0;
1736 } else if (partial_dividend < divisor) {
1737 Q[i] = 0;
Evan Cheng48e8c802008-05-02 21:15:08 +00001738 remainder = (uint32_t)partial_dividend;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001739 } else if (partial_dividend == divisor) {
1740 Q[i] = 1;
1741 remainder = 0;
1742 } else {
Evan Cheng48e8c802008-05-02 21:15:08 +00001743 Q[i] = (uint32_t)(partial_dividend / divisor);
1744 remainder = (uint32_t)(partial_dividend - (Q[i] * divisor));
Reid Spencer9c0696f2007-02-20 08:51:03 +00001745 }
1746 }
1747 if (R)
1748 R[0] = remainder;
1749 } else {
1750 // Now we're ready to invoke the Knuth classical divide algorithm. In this
1751 // case n > 1.
1752 KnuthDiv(U, V, Q, R, m, n);
1753 }
1754
1755 // If the caller wants the quotient
1756 if (Quotient) {
1757 // Set up the Quotient value's memory.
1758 if (Quotient->BitWidth != LHS.BitWidth) {
1759 if (Quotient->isSingleWord())
1760 Quotient->VAL = 0;
1761 else
Reid Spencer9ac44112007-02-26 23:38:21 +00001762 delete [] Quotient->pVal;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001763 Quotient->BitWidth = LHS.BitWidth;
1764 if (!Quotient->isSingleWord())
Reid Spencere0cdd332007-02-21 08:21:52 +00001765 Quotient->pVal = getClearedMemory(Quotient->getNumWords());
Reid Spencer9c0696f2007-02-20 08:51:03 +00001766 } else
1767 Quotient->clear();
1768
1769 // The quotient is in Q. Reconstitute the quotient into Quotient's low
1770 // order words.
1771 if (lhsWords == 1) {
1772 uint64_t tmp =
1773 uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2));
1774 if (Quotient->isSingleWord())
1775 Quotient->VAL = tmp;
1776 else
1777 Quotient->pVal[0] = tmp;
1778 } else {
1779 assert(!Quotient->isSingleWord() && "Quotient APInt not large enough");
1780 for (unsigned i = 0; i < lhsWords; ++i)
1781 Quotient->pVal[i] =
1782 uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1783 }
1784 }
1785
1786 // If the caller wants the remainder
1787 if (Remainder) {
1788 // Set up the Remainder value's memory.
1789 if (Remainder->BitWidth != RHS.BitWidth) {
1790 if (Remainder->isSingleWord())
1791 Remainder->VAL = 0;
1792 else
Reid Spencer9ac44112007-02-26 23:38:21 +00001793 delete [] Remainder->pVal;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001794 Remainder->BitWidth = RHS.BitWidth;
1795 if (!Remainder->isSingleWord())
Reid Spencere0cdd332007-02-21 08:21:52 +00001796 Remainder->pVal = getClearedMemory(Remainder->getNumWords());
Reid Spencer9c0696f2007-02-20 08:51:03 +00001797 } else
1798 Remainder->clear();
1799
1800 // The remainder is in R. Reconstitute the remainder into Remainder's low
1801 // order words.
1802 if (rhsWords == 1) {
1803 uint64_t tmp =
1804 uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2));
1805 if (Remainder->isSingleWord())
1806 Remainder->VAL = tmp;
1807 else
1808 Remainder->pVal[0] = tmp;
1809 } else {
1810 assert(!Remainder->isSingleWord() && "Remainder APInt not large enough");
1811 for (unsigned i = 0; i < rhsWords; ++i)
1812 Remainder->pVal[i] =
1813 uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1814 }
1815 }
1816
1817 // Clean up the memory we allocated.
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001818 if (U != &SPACE[0]) {
1819 delete [] U;
1820 delete [] V;
1821 delete [] Q;
1822 delete [] R;
1823 }
Reid Spencer5e0a8512007-02-17 03:16:00 +00001824}
1825
Reid Spencere81d2da2007-02-16 22:36:51 +00001826APInt APInt::udiv(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +00001827 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer71bd08f2007-02-17 02:07:07 +00001828
1829 // First, deal with the easy case
1830 if (isSingleWord()) {
1831 assert(RHS.VAL != 0 && "Divide by zero?");
1832 return APInt(BitWidth, VAL / RHS.VAL);
Zhou Sheng0b706b12007-02-08 14:35:19 +00001833 }
Reid Spencer71bd08f2007-02-17 02:07:07 +00001834
Reid Spencer71bd08f2007-02-17 02:07:07 +00001835 // Get some facts about the LHS and RHS number of bits and words
Reid Spenceraf0e9562007-02-18 18:38:44 +00001836 uint32_t rhsBits = RHS.getActiveBits();
1837 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001838 assert(rhsWords && "Divided by zero???");
Reid Spencer9c0696f2007-02-20 08:51:03 +00001839 uint32_t lhsBits = this->getActiveBits();
Reid Spenceraf0e9562007-02-18 18:38:44 +00001840 uint32_t lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001841
1842 // Deal with some degenerate cases
1843 if (!lhsWords)
Reid Spencere0cdd332007-02-21 08:21:52 +00001844 // 0 / X ===> 0
1845 return APInt(BitWidth, 0);
1846 else if (lhsWords < rhsWords || this->ult(RHS)) {
1847 // X / Y ===> 0, iff X < Y
1848 return APInt(BitWidth, 0);
1849 } else if (*this == RHS) {
1850 // X / X ===> 1
1851 return APInt(BitWidth, 1);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001852 } else if (lhsWords == 1 && rhsWords == 1) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001853 // All high words are zero, just use native divide
Reid Spencere0cdd332007-02-21 08:21:52 +00001854 return APInt(BitWidth, this->pVal[0] / RHS.pVal[0]);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001855 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001856
1857 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1858 APInt Quotient(1,0); // to hold result.
1859 divide(*this, lhsWords, RHS, rhsWords, &Quotient, 0);
1860 return Quotient;
Zhou Sheng0b706b12007-02-08 14:35:19 +00001861}
1862
Reid Spencere81d2da2007-02-16 22:36:51 +00001863APInt APInt::urem(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +00001864 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer71bd08f2007-02-17 02:07:07 +00001865 if (isSingleWord()) {
1866 assert(RHS.VAL != 0 && "Remainder by zero?");
1867 return APInt(BitWidth, VAL % RHS.VAL);
Zhou Sheng0b706b12007-02-08 14:35:19 +00001868 }
Reid Spencer71bd08f2007-02-17 02:07:07 +00001869
Reid Spencere0cdd332007-02-21 08:21:52 +00001870 // Get some facts about the LHS
1871 uint32_t lhsBits = getActiveBits();
1872 uint32_t lhsWords = !lhsBits ? 0 : (whichWord(lhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001873
1874 // Get some facts about the RHS
Reid Spenceraf0e9562007-02-18 18:38:44 +00001875 uint32_t rhsBits = RHS.getActiveBits();
1876 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001877 assert(rhsWords && "Performing remainder operation by zero ???");
1878
Reid Spencer71bd08f2007-02-17 02:07:07 +00001879 // Check the degenerate cases
Reid Spencer9c0696f2007-02-20 08:51:03 +00001880 if (lhsWords == 0) {
Reid Spencere0cdd332007-02-21 08:21:52 +00001881 // 0 % Y ===> 0
1882 return APInt(BitWidth, 0);
1883 } else if (lhsWords < rhsWords || this->ult(RHS)) {
1884 // X % Y ===> X, iff X < Y
1885 return *this;
1886 } else if (*this == RHS) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001887 // X % X == 0;
Reid Spencere0cdd332007-02-21 08:21:52 +00001888 return APInt(BitWidth, 0);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001889 } else if (lhsWords == 1) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001890 // All high words are zero, just use native remainder
Reid Spencere0cdd332007-02-21 08:21:52 +00001891 return APInt(BitWidth, pVal[0] % RHS.pVal[0]);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001892 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001893
Reid Spencer19dc32a2007-05-13 23:44:59 +00001894 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
Reid Spencer9c0696f2007-02-20 08:51:03 +00001895 APInt Remainder(1,0);
1896 divide(*this, lhsWords, RHS, rhsWords, 0, &Remainder);
1897 return Remainder;
Zhou Sheng0b706b12007-02-08 14:35:19 +00001898}
Reid Spencer5e0a8512007-02-17 03:16:00 +00001899
Reid Spencer19dc32a2007-05-13 23:44:59 +00001900void APInt::udivrem(const APInt &LHS, const APInt &RHS,
1901 APInt &Quotient, APInt &Remainder) {
1902 // Get some size facts about the dividend and divisor
1903 uint32_t lhsBits = LHS.getActiveBits();
1904 uint32_t lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
1905 uint32_t rhsBits = RHS.getActiveBits();
1906 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
1907
1908 // Check the degenerate cases
1909 if (lhsWords == 0) {
1910 Quotient = 0; // 0 / Y ===> 0
1911 Remainder = 0; // 0 % Y ===> 0
1912 return;
1913 }
1914
1915 if (lhsWords < rhsWords || LHS.ult(RHS)) {
1916 Quotient = 0; // X / Y ===> 0, iff X < Y
1917 Remainder = LHS; // X % Y ===> X, iff X < Y
1918 return;
1919 }
1920
1921 if (LHS == RHS) {
1922 Quotient = 1; // X / X ===> 1
1923 Remainder = 0; // X % X ===> 0;
1924 return;
1925 }
1926
1927 if (lhsWords == 1 && rhsWords == 1) {
1928 // There is only one word to consider so use the native versions.
Wojciech Matyjewicz300c6c52008-06-23 19:39:50 +00001929 uint64_t lhsValue = LHS.isSingleWord() ? LHS.VAL : LHS.pVal[0];
1930 uint64_t rhsValue = RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
1931 Quotient = APInt(LHS.getBitWidth(), lhsValue / rhsValue);
1932 Remainder = APInt(LHS.getBitWidth(), lhsValue % rhsValue);
Reid Spencer19dc32a2007-05-13 23:44:59 +00001933 return;
1934 }
1935
1936 // Okay, lets do it the long way
1937 divide(LHS, lhsWords, RHS, rhsWords, &Quotient, &Remainder);
1938}
1939
Reid Spencer385f7542007-02-21 03:55:44 +00001940void APInt::fromString(uint32_t numbits, const char *str, uint32_t slen,
Reid Spencer5e0a8512007-02-17 03:16:00 +00001941 uint8_t radix) {
Reid Spencer385f7542007-02-21 03:55:44 +00001942 // Check our assumptions here
Reid Spencer5e0a8512007-02-17 03:16:00 +00001943 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1944 "Radix should be 2, 8, 10, or 16!");
Reid Spencer385f7542007-02-21 03:55:44 +00001945 assert(str && "String is null?");
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001946 bool isNeg = str[0] == '-';
1947 if (isNeg)
Reid Spencer9eec2412007-02-25 23:44:53 +00001948 str++, slen--;
Chris Lattnera5ae15e2007-05-03 18:15:36 +00001949 assert((slen <= numbits || radix != 2) && "Insufficient bit width");
1950 assert((slen*3 <= numbits || radix != 8) && "Insufficient bit width");
1951 assert((slen*4 <= numbits || radix != 16) && "Insufficient bit width");
1952 assert(((slen*64)/22 <= numbits || radix != 10) && "Insufficient bit width");
Reid Spencer385f7542007-02-21 03:55:44 +00001953
1954 // Allocate memory
1955 if (!isSingleWord())
1956 pVal = getClearedMemory(getNumWords());
1957
1958 // Figure out if we can shift instead of multiply
1959 uint32_t shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0);
1960
1961 // Set up an APInt for the digit to add outside the loop so we don't
1962 // constantly construct/destruct it.
1963 APInt apdigit(getBitWidth(), 0);
1964 APInt apradix(getBitWidth(), radix);
1965
1966 // Enter digit traversal loop
1967 for (unsigned i = 0; i < slen; i++) {
1968 // Get a digit
1969 uint32_t digit = 0;
1970 char cdigit = str[i];
Reid Spencer6551dcd2007-05-16 19:18:22 +00001971 if (radix == 16) {
1972 if (!isxdigit(cdigit))
1973 assert(0 && "Invalid hex digit in string");
1974 if (isdigit(cdigit))
1975 digit = cdigit - '0';
1976 else if (cdigit >= 'a')
Reid Spencer385f7542007-02-21 03:55:44 +00001977 digit = cdigit - 'a' + 10;
1978 else if (cdigit >= 'A')
1979 digit = cdigit - 'A' + 10;
1980 else
Reid Spencer6551dcd2007-05-16 19:18:22 +00001981 assert(0 && "huh? we shouldn't get here");
1982 } else if (isdigit(cdigit)) {
1983 digit = cdigit - '0';
Bill Wendlingf7a91e62008-03-16 20:05:52 +00001984 assert((radix == 10 ||
1985 (radix == 8 && digit != 8 && digit != 9) ||
1986 (radix == 2 && (digit == 0 || digit == 1))) &&
1987 "Invalid digit in string for given radix");
Reid Spencer6551dcd2007-05-16 19:18:22 +00001988 } else {
Reid Spencer385f7542007-02-21 03:55:44 +00001989 assert(0 && "Invalid character in digit string");
Reid Spencer6551dcd2007-05-16 19:18:22 +00001990 }
Reid Spencer385f7542007-02-21 03:55:44 +00001991
Reid Spencer6551dcd2007-05-16 19:18:22 +00001992 // Shift or multiply the value by the radix
Reid Spencer385f7542007-02-21 03:55:44 +00001993 if (shift)
Reid Spencer6551dcd2007-05-16 19:18:22 +00001994 *this <<= shift;
Reid Spencer385f7542007-02-21 03:55:44 +00001995 else
1996 *this *= apradix;
1997
1998 // Add in the digit we just interpreted
Reid Spencer5bce8542007-02-24 20:19:37 +00001999 if (apdigit.isSingleWord())
2000 apdigit.VAL = digit;
2001 else
2002 apdigit.pVal[0] = digit;
Reid Spencer385f7542007-02-21 03:55:44 +00002003 *this += apdigit;
Reid Spencer5e0a8512007-02-17 03:16:00 +00002004 }
Reid Spencer9eec2412007-02-25 23:44:53 +00002005 // If its negative, put it in two's complement form
Reid Spencer47fbe9e2007-02-26 07:44:38 +00002006 if (isNeg) {
2007 (*this)--;
Reid Spencer9eec2412007-02-25 23:44:53 +00002008 this->flip();
Reid Spencer9eec2412007-02-25 23:44:53 +00002009 }
Reid Spencer5e0a8512007-02-17 03:16:00 +00002010}
Reid Spencer9c0696f2007-02-20 08:51:03 +00002011
Reid Spencer9c0696f2007-02-20 08:51:03 +00002012std::string APInt::toString(uint8_t radix, bool wantSigned) const {
2013 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
2014 "Radix should be 2, 8, 10, or 16!");
Dan Gohmancfbb2f02008-03-25 21:45:14 +00002015 static const char *const digits[] = {
Reid Spencer9c0696f2007-02-20 08:51:03 +00002016 "0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"
2017 };
2018 std::string result;
2019 uint32_t bits_used = getActiveBits();
2020 if (isSingleWord()) {
2021 char buf[65];
2022 const char *format = (radix == 10 ? (wantSigned ? "%lld" : "%llu") :
2023 (radix == 16 ? "%llX" : (radix == 8 ? "%llo" : 0)));
2024 if (format) {
2025 if (wantSigned) {
2026 int64_t sextVal = (int64_t(VAL) << (APINT_BITS_PER_WORD-BitWidth)) >>
2027 (APINT_BITS_PER_WORD-BitWidth);
2028 sprintf(buf, format, sextVal);
2029 } else
2030 sprintf(buf, format, VAL);
2031 } else {
2032 memset(buf, 0, 65);
2033 uint64_t v = VAL;
2034 while (bits_used) {
Evan Cheng48e8c802008-05-02 21:15:08 +00002035 uint32_t bit = (uint32_t)v & 1;
Reid Spencer9c0696f2007-02-20 08:51:03 +00002036 bits_used--;
2037 buf[bits_used] = digits[bit][0];
2038 v >>=1;
2039 }
2040 }
2041 result = buf;
2042 return result;
2043 }
2044
2045 if (radix != 10) {
Reid Spencerfb0709a2007-05-17 19:23:02 +00002046 // For the 2, 8 and 16 bit cases, we can just shift instead of divide
2047 // because the number of bits per digit (1,3 and 4 respectively) divides
2048 // equaly. We just shift until there value is zero.
2049
2050 // First, check for a zero value and just short circuit the logic below.
2051 if (*this == 0)
2052 result = "0";
2053 else {
2054 APInt tmp(*this);
2055 size_t insert_at = 0;
2056 if (wantSigned && this->isNegative()) {
2057 // They want to print the signed version and it is a negative value
2058 // Flip the bits and add one to turn it into the equivalent positive
2059 // value and put a '-' in the result.
2060 tmp.flip();
2061 tmp++;
2062 result = "-";
2063 insert_at = 1;
2064 }
2065 // Just shift tmp right for each digit width until it becomes zero
2066 uint32_t shift = (radix == 16 ? 4 : (radix == 8 ? 3 : 1));
2067 uint64_t mask = radix - 1;
2068 APInt zero(tmp.getBitWidth(), 0);
2069 while (tmp.ne(zero)) {
Evan Cheng48e8c802008-05-02 21:15:08 +00002070 unsigned digit =
2071 (unsigned)((tmp.isSingleWord() ? tmp.VAL : tmp.pVal[0]) & mask);
Reid Spencerfb0709a2007-05-17 19:23:02 +00002072 result.insert(insert_at, digits[digit]);
Reid Spencer20a4c232007-05-19 00:29:55 +00002073 tmp = tmp.lshr(shift);
Reid Spencer9c0696f2007-02-20 08:51:03 +00002074 }
2075 }
2076 return result;
2077 }
2078
2079 APInt tmp(*this);
2080 APInt divisor(4, radix);
2081 APInt zero(tmp.getBitWidth(), 0);
2082 size_t insert_at = 0;
2083 if (wantSigned && tmp[BitWidth-1]) {
2084 // They want to print the signed version and it is a negative value
2085 // Flip the bits and add one to turn it into the equivalent positive
2086 // value and put a '-' in the result.
2087 tmp.flip();
2088 tmp++;
2089 result = "-";
2090 insert_at = 1;
2091 }
Dan Gohman95df6b32008-06-21 22:03:12 +00002092 if (tmp == zero)
Reid Spencer9c0696f2007-02-20 08:51:03 +00002093 result = "0";
2094 else while (tmp.ne(zero)) {
2095 APInt APdigit(1,0);
Reid Spencer9c0696f2007-02-20 08:51:03 +00002096 APInt tmp2(tmp.getBitWidth(), 0);
Reid Spencer385f7542007-02-21 03:55:44 +00002097 divide(tmp, tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2,
2098 &APdigit);
Evan Cheng48e8c802008-05-02 21:15:08 +00002099 uint32_t digit = (uint32_t)APdigit.getZExtValue();
Reid Spencer385f7542007-02-21 03:55:44 +00002100 assert(digit < radix && "divide failed");
2101 result.insert(insert_at,digits[digit]);
Reid Spencer9c0696f2007-02-20 08:51:03 +00002102 tmp = tmp2;
2103 }
2104
2105 return result;
2106}
2107
Reid Spencer385f7542007-02-21 03:55:44 +00002108void APInt::dump() const
2109{
Reid Spencer610fad82007-02-24 10:01:42 +00002110 cerr << "APInt(" << BitWidth << ")=" << std::setbase(16);
Reid Spencer385f7542007-02-21 03:55:44 +00002111 if (isSingleWord())
Reid Spencer610fad82007-02-24 10:01:42 +00002112 cerr << VAL;
Reid Spencer385f7542007-02-21 03:55:44 +00002113 else for (unsigned i = getNumWords(); i > 0; i--) {
Reid Spencer610fad82007-02-24 10:01:42 +00002114 cerr << pVal[i-1] << " ";
Reid Spencer385f7542007-02-21 03:55:44 +00002115 }
Chris Lattner9132a2b2007-08-23 05:15:32 +00002116 cerr << " U(" << this->toStringUnsigned(10) << ") S("
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002117 << this->toStringSigned(10) << ")" << std::setbase(10);
Reid Spencer385f7542007-02-21 03:55:44 +00002118}
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002119
2120// This implements a variety of operations on a representation of
2121// arbitrary precision, two's-complement, bignum integer values.
2122
2123/* Assumed by lowHalf, highHalf, partMSB and partLSB. A fairly safe
2124 and unrestricting assumption. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002125COMPILE_TIME_ASSERT(integerPartWidth % 2 == 0);
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002126
2127/* Some handy functions local to this file. */
2128namespace {
2129
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002130 /* Returns the integer part with the least significant BITS set.
2131 BITS cannot be zero. */
Dan Gohman3bd659b2008-04-10 21:11:47 +00002132 static inline integerPart
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002133 lowBitMask(unsigned int bits)
2134 {
2135 assert (bits != 0 && bits <= integerPartWidth);
2136
2137 return ~(integerPart) 0 >> (integerPartWidth - bits);
2138 }
2139
Neil Booth055c0b32007-10-06 00:43:45 +00002140 /* Returns the value of the lower half of PART. */
Dan Gohman3bd659b2008-04-10 21:11:47 +00002141 static inline integerPart
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002142 lowHalf(integerPart part)
2143 {
2144 return part & lowBitMask(integerPartWidth / 2);
2145 }
2146
Neil Booth055c0b32007-10-06 00:43:45 +00002147 /* Returns the value of the upper half of PART. */
Dan Gohman3bd659b2008-04-10 21:11:47 +00002148 static inline integerPart
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002149 highHalf(integerPart part)
2150 {
2151 return part >> (integerPartWidth / 2);
2152 }
2153
Neil Booth055c0b32007-10-06 00:43:45 +00002154 /* Returns the bit number of the most significant set bit of a part.
2155 If the input number has no bits set -1U is returned. */
Dan Gohman3bd659b2008-04-10 21:11:47 +00002156 static unsigned int
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002157 partMSB(integerPart value)
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002158 {
2159 unsigned int n, msb;
2160
2161 if (value == 0)
2162 return -1U;
2163
2164 n = integerPartWidth / 2;
2165
2166 msb = 0;
2167 do {
2168 if (value >> n) {
2169 value >>= n;
2170 msb += n;
2171 }
2172
2173 n >>= 1;
2174 } while (n);
2175
2176 return msb;
2177 }
2178
Neil Booth055c0b32007-10-06 00:43:45 +00002179 /* Returns the bit number of the least significant set bit of a
2180 part. If the input number has no bits set -1U is returned. */
Dan Gohman3bd659b2008-04-10 21:11:47 +00002181 static unsigned int
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002182 partLSB(integerPart value)
2183 {
2184 unsigned int n, lsb;
2185
2186 if (value == 0)
2187 return -1U;
2188
2189 lsb = integerPartWidth - 1;
2190 n = integerPartWidth / 2;
2191
2192 do {
2193 if (value << n) {
2194 value <<= n;
2195 lsb -= n;
2196 }
2197
2198 n >>= 1;
2199 } while (n);
2200
2201 return lsb;
2202 }
2203}
2204
2205/* Sets the least significant part of a bignum to the input value, and
2206 zeroes out higher parts. */
2207void
2208APInt::tcSet(integerPart *dst, integerPart part, unsigned int parts)
2209{
2210 unsigned int i;
2211
Neil Booth68e53ad2007-10-08 13:47:12 +00002212 assert (parts > 0);
2213
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002214 dst[0] = part;
2215 for(i = 1; i < parts; i++)
2216 dst[i] = 0;
2217}
2218
2219/* Assign one bignum to another. */
2220void
2221APInt::tcAssign(integerPart *dst, const integerPart *src, unsigned int parts)
2222{
2223 unsigned int i;
2224
2225 for(i = 0; i < parts; i++)
2226 dst[i] = src[i];
2227}
2228
2229/* Returns true if a bignum is zero, false otherwise. */
2230bool
2231APInt::tcIsZero(const integerPart *src, unsigned int parts)
2232{
2233 unsigned int i;
2234
2235 for(i = 0; i < parts; i++)
2236 if (src[i])
2237 return false;
2238
2239 return true;
2240}
2241
2242/* Extract the given bit of a bignum; returns 0 or 1. */
2243int
2244APInt::tcExtractBit(const integerPart *parts, unsigned int bit)
2245{
2246 return(parts[bit / integerPartWidth]
2247 & ((integerPart) 1 << bit % integerPartWidth)) != 0;
2248}
2249
2250/* Set the given bit of a bignum. */
2251void
2252APInt::tcSetBit(integerPart *parts, unsigned int bit)
2253{
2254 parts[bit / integerPartWidth] |= (integerPart) 1 << (bit % integerPartWidth);
2255}
2256
Neil Booth055c0b32007-10-06 00:43:45 +00002257/* Returns the bit number of the least significant set bit of a
2258 number. If the input number has no bits set -1U is returned. */
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002259unsigned int
2260APInt::tcLSB(const integerPart *parts, unsigned int n)
2261{
2262 unsigned int i, lsb;
2263
2264 for(i = 0; i < n; i++) {
2265 if (parts[i] != 0) {
2266 lsb = partLSB(parts[i]);
2267
2268 return lsb + i * integerPartWidth;
2269 }
2270 }
2271
2272 return -1U;
2273}
2274
Neil Booth055c0b32007-10-06 00:43:45 +00002275/* Returns the bit number of the most significant set bit of a number.
2276 If the input number has no bits set -1U is returned. */
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002277unsigned int
2278APInt::tcMSB(const integerPart *parts, unsigned int n)
2279{
2280 unsigned int msb;
2281
2282 do {
2283 --n;
2284
2285 if (parts[n] != 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002286 msb = partMSB(parts[n]);
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002287
2288 return msb + n * integerPartWidth;
2289 }
2290 } while (n);
2291
2292 return -1U;
2293}
2294
Neil Booth68e53ad2007-10-08 13:47:12 +00002295/* Copy the bit vector of width srcBITS from SRC, starting at bit
2296 srcLSB, to DST, of dstCOUNT parts, such that the bit srcLSB becomes
2297 the least significant bit of DST. All high bits above srcBITS in
2298 DST are zero-filled. */
2299void
2300APInt::tcExtract(integerPart *dst, unsigned int dstCount, const integerPart *src,
2301 unsigned int srcBits, unsigned int srcLSB)
2302{
2303 unsigned int firstSrcPart, dstParts, shift, n;
2304
2305 dstParts = (srcBits + integerPartWidth - 1) / integerPartWidth;
2306 assert (dstParts <= dstCount);
2307
2308 firstSrcPart = srcLSB / integerPartWidth;
2309 tcAssign (dst, src + firstSrcPart, dstParts);
2310
2311 shift = srcLSB % integerPartWidth;
2312 tcShiftRight (dst, dstParts, shift);
2313
2314 /* We now have (dstParts * integerPartWidth - shift) bits from SRC
2315 in DST. If this is less that srcBits, append the rest, else
2316 clear the high bits. */
2317 n = dstParts * integerPartWidth - shift;
2318 if (n < srcBits) {
2319 integerPart mask = lowBitMask (srcBits - n);
2320 dst[dstParts - 1] |= ((src[firstSrcPart + dstParts] & mask)
2321 << n % integerPartWidth);
2322 } else if (n > srcBits) {
Neil Booth1e8390d2007-10-12 15:31:31 +00002323 if (srcBits % integerPartWidth)
2324 dst[dstParts - 1] &= lowBitMask (srcBits % integerPartWidth);
Neil Booth68e53ad2007-10-08 13:47:12 +00002325 }
2326
2327 /* Clear high parts. */
2328 while (dstParts < dstCount)
2329 dst[dstParts++] = 0;
2330}
2331
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002332/* DST += RHS + C where C is zero or one. Returns the carry flag. */
2333integerPart
2334APInt::tcAdd(integerPart *dst, const integerPart *rhs,
2335 integerPart c, unsigned int parts)
2336{
2337 unsigned int i;
2338
2339 assert(c <= 1);
2340
2341 for(i = 0; i < parts; i++) {
2342 integerPart l;
2343
2344 l = dst[i];
2345 if (c) {
2346 dst[i] += rhs[i] + 1;
2347 c = (dst[i] <= l);
2348 } else {
2349 dst[i] += rhs[i];
2350 c = (dst[i] < l);
2351 }
2352 }
2353
2354 return c;
2355}
2356
2357/* DST -= RHS + C where C is zero or one. Returns the carry flag. */
2358integerPart
2359APInt::tcSubtract(integerPart *dst, const integerPart *rhs,
2360 integerPart c, unsigned int parts)
2361{
2362 unsigned int i;
2363
2364 assert(c <= 1);
2365
2366 for(i = 0; i < parts; i++) {
2367 integerPart l;
2368
2369 l = dst[i];
2370 if (c) {
2371 dst[i] -= rhs[i] + 1;
2372 c = (dst[i] >= l);
2373 } else {
2374 dst[i] -= rhs[i];
2375 c = (dst[i] > l);
2376 }
2377 }
2378
2379 return c;
2380}
2381
2382/* Negate a bignum in-place. */
2383void
2384APInt::tcNegate(integerPart *dst, unsigned int parts)
2385{
2386 tcComplement(dst, parts);
2387 tcIncrement(dst, parts);
2388}
2389
Neil Booth055c0b32007-10-06 00:43:45 +00002390/* DST += SRC * MULTIPLIER + CARRY if add is true
2391 DST = SRC * MULTIPLIER + CARRY if add is false
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002392
2393 Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC
2394 they must start at the same point, i.e. DST == SRC.
2395
2396 If DSTPARTS == SRCPARTS + 1 no overflow occurs and zero is
2397 returned. Otherwise DST is filled with the least significant
2398 DSTPARTS parts of the result, and if all of the omitted higher
2399 parts were zero return zero, otherwise overflow occurred and
2400 return one. */
2401int
2402APInt::tcMultiplyPart(integerPart *dst, const integerPart *src,
2403 integerPart multiplier, integerPart carry,
2404 unsigned int srcParts, unsigned int dstParts,
2405 bool add)
2406{
2407 unsigned int i, n;
2408
2409 /* Otherwise our writes of DST kill our later reads of SRC. */
2410 assert(dst <= src || dst >= src + srcParts);
2411 assert(dstParts <= srcParts + 1);
2412
2413 /* N loops; minimum of dstParts and srcParts. */
2414 n = dstParts < srcParts ? dstParts: srcParts;
2415
2416 for(i = 0; i < n; i++) {
2417 integerPart low, mid, high, srcPart;
2418
2419 /* [ LOW, HIGH ] = MULTIPLIER * SRC[i] + DST[i] + CARRY.
2420
2421 This cannot overflow, because
2422
2423 (n - 1) * (n - 1) + 2 (n - 1) = (n - 1) * (n + 1)
2424
2425 which is less than n^2. */
2426
2427 srcPart = src[i];
2428
2429 if (multiplier == 0 || srcPart == 0) {
2430 low = carry;
2431 high = 0;
2432 } else {
2433 low = lowHalf(srcPart) * lowHalf(multiplier);
2434 high = highHalf(srcPart) * highHalf(multiplier);
2435
2436 mid = lowHalf(srcPart) * highHalf(multiplier);
2437 high += highHalf(mid);
2438 mid <<= integerPartWidth / 2;
2439 if (low + mid < low)
2440 high++;
2441 low += mid;
2442
2443 mid = highHalf(srcPart) * lowHalf(multiplier);
2444 high += highHalf(mid);
2445 mid <<= integerPartWidth / 2;
2446 if (low + mid < low)
2447 high++;
2448 low += mid;
2449
2450 /* Now add carry. */
2451 if (low + carry < low)
2452 high++;
2453 low += carry;
2454 }
2455
2456 if (add) {
2457 /* And now DST[i], and store the new low part there. */
2458 if (low + dst[i] < low)
2459 high++;
2460 dst[i] += low;
2461 } else
2462 dst[i] = low;
2463
2464 carry = high;
2465 }
2466
2467 if (i < dstParts) {
2468 /* Full multiplication, there is no overflow. */
2469 assert(i + 1 == dstParts);
2470 dst[i] = carry;
2471 return 0;
2472 } else {
2473 /* We overflowed if there is carry. */
2474 if (carry)
2475 return 1;
2476
2477 /* We would overflow if any significant unwritten parts would be
2478 non-zero. This is true if any remaining src parts are non-zero
2479 and the multiplier is non-zero. */
2480 if (multiplier)
2481 for(; i < srcParts; i++)
2482 if (src[i])
2483 return 1;
2484
2485 /* We fitted in the narrow destination. */
2486 return 0;
2487 }
2488}
2489
2490/* DST = LHS * RHS, where DST has the same width as the operands and
2491 is filled with the least significant parts of the result. Returns
2492 one if overflow occurred, otherwise zero. DST must be disjoint
2493 from both operands. */
2494int
2495APInt::tcMultiply(integerPart *dst, const integerPart *lhs,
2496 const integerPart *rhs, unsigned int parts)
2497{
2498 unsigned int i;
2499 int overflow;
2500
2501 assert(dst != lhs && dst != rhs);
2502
2503 overflow = 0;
2504 tcSet(dst, 0, parts);
2505
2506 for(i = 0; i < parts; i++)
2507 overflow |= tcMultiplyPart(&dst[i], lhs, rhs[i], 0, parts,
2508 parts - i, true);
2509
2510 return overflow;
2511}
2512
Neil Booth978661d2007-10-06 00:24:48 +00002513/* DST = LHS * RHS, where DST has width the sum of the widths of the
2514 operands. No overflow occurs. DST must be disjoint from both
2515 operands. Returns the number of parts required to hold the
2516 result. */
2517unsigned int
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002518APInt::tcFullMultiply(integerPart *dst, const integerPart *lhs,
Neil Booth978661d2007-10-06 00:24:48 +00002519 const integerPart *rhs, unsigned int lhsParts,
2520 unsigned int rhsParts)
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002521{
Neil Booth978661d2007-10-06 00:24:48 +00002522 /* Put the narrower number on the LHS for less loops below. */
2523 if (lhsParts > rhsParts) {
2524 return tcFullMultiply (dst, rhs, lhs, rhsParts, lhsParts);
2525 } else {
2526 unsigned int n;
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002527
Neil Booth978661d2007-10-06 00:24:48 +00002528 assert(dst != lhs && dst != rhs);
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002529
Neil Booth978661d2007-10-06 00:24:48 +00002530 tcSet(dst, 0, rhsParts);
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002531
Neil Booth978661d2007-10-06 00:24:48 +00002532 for(n = 0; n < lhsParts; n++)
2533 tcMultiplyPart(&dst[n], rhs, lhs[n], 0, rhsParts, rhsParts + 1, true);
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002534
Neil Booth978661d2007-10-06 00:24:48 +00002535 n = lhsParts + rhsParts;
2536
2537 return n - (dst[n - 1] == 0);
2538 }
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002539}
2540
2541/* If RHS is zero LHS and REMAINDER are left unchanged, return one.
2542 Otherwise set LHS to LHS / RHS with the fractional part discarded,
2543 set REMAINDER to the remainder, return zero. i.e.
2544
2545 OLD_LHS = RHS * LHS + REMAINDER
2546
2547 SCRATCH is a bignum of the same size as the operands and result for
2548 use by the routine; its contents need not be initialized and are
2549 destroyed. LHS, REMAINDER and SCRATCH must be distinct.
2550*/
2551int
2552APInt::tcDivide(integerPart *lhs, const integerPart *rhs,
2553 integerPart *remainder, integerPart *srhs,
2554 unsigned int parts)
2555{
2556 unsigned int n, shiftCount;
2557 integerPart mask;
2558
2559 assert(lhs != remainder && lhs != srhs && remainder != srhs);
2560
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002561 shiftCount = tcMSB(rhs, parts) + 1;
2562 if (shiftCount == 0)
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002563 return true;
2564
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002565 shiftCount = parts * integerPartWidth - shiftCount;
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002566 n = shiftCount / integerPartWidth;
2567 mask = (integerPart) 1 << (shiftCount % integerPartWidth);
2568
2569 tcAssign(srhs, rhs, parts);
2570 tcShiftLeft(srhs, parts, shiftCount);
2571 tcAssign(remainder, lhs, parts);
2572 tcSet(lhs, 0, parts);
2573
2574 /* Loop, subtracting SRHS if REMAINDER is greater and adding that to
2575 the total. */
2576 for(;;) {
2577 int compare;
2578
2579 compare = tcCompare(remainder, srhs, parts);
2580 if (compare >= 0) {
2581 tcSubtract(remainder, srhs, 0, parts);
2582 lhs[n] |= mask;
2583 }
2584
2585 if (shiftCount == 0)
2586 break;
2587 shiftCount--;
2588 tcShiftRight(srhs, parts, 1);
2589 if ((mask >>= 1) == 0)
2590 mask = (integerPart) 1 << (integerPartWidth - 1), n--;
2591 }
2592
2593 return false;
2594}
2595
2596/* Shift a bignum left COUNT bits in-place. Shifted in bits are zero.
2597 There are no restrictions on COUNT. */
2598void
2599APInt::tcShiftLeft(integerPart *dst, unsigned int parts, unsigned int count)
2600{
Neil Booth68e53ad2007-10-08 13:47:12 +00002601 if (count) {
2602 unsigned int jump, shift;
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002603
Neil Booth68e53ad2007-10-08 13:47:12 +00002604 /* Jump is the inter-part jump; shift is is intra-part shift. */
2605 jump = count / integerPartWidth;
2606 shift = count % integerPartWidth;
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002607
Neil Booth68e53ad2007-10-08 13:47:12 +00002608 while (parts > jump) {
2609 integerPart part;
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002610
Neil Booth68e53ad2007-10-08 13:47:12 +00002611 parts--;
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002612
Neil Booth68e53ad2007-10-08 13:47:12 +00002613 /* dst[i] comes from the two parts src[i - jump] and, if we have
2614 an intra-part shift, src[i - jump - 1]. */
2615 part = dst[parts - jump];
2616 if (shift) {
2617 part <<= shift;
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002618 if (parts >= jump + 1)
2619 part |= dst[parts - jump - 1] >> (integerPartWidth - shift);
2620 }
2621
Neil Booth68e53ad2007-10-08 13:47:12 +00002622 dst[parts] = part;
2623 }
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002624
Neil Booth68e53ad2007-10-08 13:47:12 +00002625 while (parts > 0)
2626 dst[--parts] = 0;
2627 }
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002628}
2629
2630/* Shift a bignum right COUNT bits in-place. Shifted in bits are
2631 zero. There are no restrictions on COUNT. */
2632void
2633APInt::tcShiftRight(integerPart *dst, unsigned int parts, unsigned int count)
2634{
Neil Booth68e53ad2007-10-08 13:47:12 +00002635 if (count) {
2636 unsigned int i, jump, shift;
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002637
Neil Booth68e53ad2007-10-08 13:47:12 +00002638 /* Jump is the inter-part jump; shift is is intra-part shift. */
2639 jump = count / integerPartWidth;
2640 shift = count % integerPartWidth;
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002641
Neil Booth68e53ad2007-10-08 13:47:12 +00002642 /* Perform the shift. This leaves the most significant COUNT bits
2643 of the result at zero. */
2644 for(i = 0; i < parts; i++) {
2645 integerPart part;
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002646
Neil Booth68e53ad2007-10-08 13:47:12 +00002647 if (i + jump >= parts) {
2648 part = 0;
2649 } else {
2650 part = dst[i + jump];
2651 if (shift) {
2652 part >>= shift;
2653 if (i + jump + 1 < parts)
2654 part |= dst[i + jump + 1] << (integerPartWidth - shift);
2655 }
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002656 }
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002657
Neil Booth68e53ad2007-10-08 13:47:12 +00002658 dst[i] = part;
2659 }
Chris Lattnerfe8e14a2007-08-16 15:56:55 +00002660 }
2661}
2662
2663/* Bitwise and of two bignums. */
2664void
2665APInt::tcAnd(integerPart *dst, const integerPart *rhs, unsigned int parts)
2666{
2667 unsigned int i;
2668
2669 for(i = 0; i < parts; i++)
2670 dst[i] &= rhs[i];
2671}
2672
2673/* Bitwise inclusive or of two bignums. */
2674void
2675APInt::tcOr(integerPart *dst, const integerPart *rhs, unsigned int parts)
2676{
2677 unsigned int i;
2678
2679 for(i = 0; i < parts; i++)
2680 dst[i] |= rhs[i];
2681}
2682
2683/* Bitwise exclusive or of two bignums. */
2684void
2685APInt::tcXor(integerPart *dst, const integerPart *rhs, unsigned int parts)
2686{
2687 unsigned int i;
2688
2689 for(i = 0; i < parts; i++)
2690 dst[i] ^= rhs[i];
2691}
2692
2693/* Complement a bignum in-place. */
2694void
2695APInt::tcComplement(integerPart *dst, unsigned int parts)
2696{
2697 unsigned int i;
2698
2699 for(i = 0; i < parts; i++)
2700 dst[i] = ~dst[i];
2701}
2702
2703/* Comparison (unsigned) of two bignums. */
2704int
2705APInt::tcCompare(const integerPart *lhs, const integerPart *rhs,
2706 unsigned int parts)
2707{
2708 while (parts) {
2709 parts--;
2710 if (lhs[parts] == rhs[parts])
2711 continue;
2712
2713 if (lhs[parts] > rhs[parts])
2714 return 1;
2715 else
2716 return -1;
2717 }
2718
2719 return 0;
2720}
2721
2722/* Increment a bignum in-place, return the carry flag. */
2723integerPart
2724APInt::tcIncrement(integerPart *dst, unsigned int parts)
2725{
2726 unsigned int i;
2727
2728 for(i = 0; i < parts; i++)
2729 if (++dst[i] != 0)
2730 break;
2731
2732 return i == parts;
2733}
2734
2735/* Set the least significant BITS bits of a bignum, clear the
2736 rest. */
2737void
2738APInt::tcSetLeastSignificantBits(integerPart *dst, unsigned int parts,
2739 unsigned int bits)
2740{
2741 unsigned int i;
2742
2743 i = 0;
2744 while (bits > integerPartWidth) {
2745 dst[i++] = ~(integerPart) 0;
2746 bits -= integerPartWidth;
2747 }
2748
2749 if (bits)
2750 dst[i++] = ~(integerPart) 0 >> (integerPartWidth - bits);
2751
2752 while (i < parts)
2753 dst[i++] = 0;
2754}