blob: 9d43ae4f16be59f308a6fbd354379786da16dca9 [file] [log] [blame]
Zhou Shengfd43dcf2007-02-06 03:00:16 +00001//===-- APInt.cpp - Implement APInt class ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Sheng Zhou and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements a class to represent arbitrary precision integral
11// constant values.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/ADT/APInt.h"
16#include "llvm/DerivedTypes.h"
17#include "llvm/Support/MathExtras.h"
Zhou Shenga3832fd2007-02-07 06:14:53 +000018#include <cstring>
Zhou Shengfd43dcf2007-02-06 03:00:16 +000019#include <cstdlib>
20using namespace llvm;
21
Reid Spenceraf0e9562007-02-18 18:38:44 +000022// A utility function for allocating memory, checking for allocation failures,
23// and ensuring the contents is zeroed.
24inline static uint64_t* getClearedMemory(uint32_t numWords) {
25 uint64_t * result = new uint64_t[numWords];
26 assert(result && "APInt memory allocation fails!");
27 memset(result, 0, numWords * sizeof(uint64_t));
28 return result;
Zhou Sheng353815d2007-02-06 06:04:53 +000029}
30
Reid Spenceraf0e9562007-02-18 18:38:44 +000031// A utility function for allocating memory and checking for allocation failure.
32inline static uint64_t* getMemory(uint32_t numWords) {
33 uint64_t * result = new uint64_t[numWords];
34 assert(result && "APInt memory allocation fails!");
35 return result;
36}
37
38APInt::APInt(uint32_t numBits, uint64_t val)
Reid Spencer9c0696f2007-02-20 08:51:03 +000039 : BitWidth(numBits), pVal(0) {
Reid Spencere81d2da2007-02-16 22:36:51 +000040 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
41 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
Zhou Shengfd43dcf2007-02-06 03:00:16 +000042 if (isSingleWord())
Reid Spencere81d2da2007-02-16 22:36:51 +000043 VAL = val & (~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - BitWidth));
Zhou Shengfd43dcf2007-02-06 03:00:16 +000044 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +000045 pVal = getClearedMemory(getNumWords());
Zhou Shengfd43dcf2007-02-06 03:00:16 +000046 pVal[0] = val;
47 }
48}
49
Reid Spenceraf0e9562007-02-18 18:38:44 +000050APInt::APInt(uint32_t numBits, uint32_t numWords, uint64_t bigVal[])
Reid Spencer9c0696f2007-02-20 08:51:03 +000051 : BitWidth(numBits), pVal(0) {
Reid Spencere81d2da2007-02-16 22:36:51 +000052 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
53 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
Zhou Shengfd43dcf2007-02-06 03:00:16 +000054 assert(bigVal && "Null pointer detected!");
55 if (isSingleWord())
Reid Spencere81d2da2007-02-16 22:36:51 +000056 VAL = bigVal[0] & (~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - BitWidth));
Zhou Shengfd43dcf2007-02-06 03:00:16 +000057 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +000058 pVal = getMemory(getNumWords());
Zhou Shengfd43dcf2007-02-06 03:00:16 +000059 // Calculate the actual length of bigVal[].
Reid Spenceraf0e9562007-02-18 18:38:44 +000060 uint32_t maxN = std::max<uint32_t>(numWords, getNumWords());
61 uint32_t minN = std::min<uint32_t>(numWords, getNumWords());
Reid Spencera58f0582007-02-18 20:09:41 +000062 memcpy(pVal, bigVal, (minN - 1) * APINT_WORD_SIZE);
Reid Spencer443b5702007-02-18 00:44:22 +000063 pVal[minN-1] = bigVal[minN-1] &
64 (~uint64_t(0ULL) >>
65 (APINT_BITS_PER_WORD - BitWidth % APINT_BITS_PER_WORD));
Zhou Shenga3832fd2007-02-07 06:14:53 +000066 if (maxN == getNumWords())
Reid Spencera58f0582007-02-18 20:09:41 +000067 memset(pVal+numWords, 0, (getNumWords() - numWords) * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +000068 }
69}
70
Zhou Shenga3832fd2007-02-07 06:14:53 +000071/// @brief Create a new APInt by translating the char array represented
72/// integer value.
Reid Spenceraf0e9562007-02-18 18:38:44 +000073APInt::APInt(uint32_t numbits, const char StrStart[], uint32_t slen,
Reid Spencer9c0696f2007-02-20 08:51:03 +000074 uint8_t radix)
75 : BitWidth(numbits), pVal(0) {
Reid Spencere81d2da2007-02-16 22:36:51 +000076 fromString(numbits, StrStart, slen, radix);
Zhou Shenga3832fd2007-02-07 06:14:53 +000077}
78
79/// @brief Create a new APInt by translating the string represented
80/// integer value.
Reid Spencer9c0696f2007-02-20 08:51:03 +000081APInt::APInt(uint32_t numbits, const std::string& Val, uint8_t radix)
82 : BitWidth(numbits), pVal(0) {
Zhou Shenga3832fd2007-02-07 06:14:53 +000083 assert(!Val.empty() && "String empty?");
Reid Spencere81d2da2007-02-16 22:36:51 +000084 fromString(numbits, Val.c_str(), Val.size(), radix);
Zhou Shenga3832fd2007-02-07 06:14:53 +000085}
86
Reid Spencera58f0582007-02-18 20:09:41 +000087/// @brief Copy constructor
Zhou Shengfd43dcf2007-02-06 03:00:16 +000088APInt::APInt(const APInt& APIVal)
Reid Spencer9c0696f2007-02-20 08:51:03 +000089 : BitWidth(APIVal.BitWidth), pVal(0) {
Reid Spenceraf0e9562007-02-18 18:38:44 +000090 if (isSingleWord())
91 VAL = APIVal.VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +000092 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +000093 pVal = getMemory(getNumWords());
Reid Spencera58f0582007-02-18 20:09:41 +000094 memcpy(pVal, APIVal.pVal, getNumWords() * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +000095 }
96}
97
98APInt::~APInt() {
Reid Spencer9c0696f2007-02-20 08:51:03 +000099 if (!isSingleWord() && pVal)
100 delete[] pVal;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000101}
102
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000103/// @brief Copy assignment operator. Create a new object from the given
104/// APInt one by initialization.
105APInt& APInt::operator=(const APInt& RHS) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000106 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
107 if (isSingleWord())
Reid Spenceraf0e9562007-02-18 18:38:44 +0000108 VAL = RHS.VAL;
109 else
Reid Spencera58f0582007-02-18 20:09:41 +0000110 memcpy(pVal, RHS.pVal, getNumWords() * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000111 return *this;
112}
113
114/// @brief Assignment operator. Assigns a common case integer value to
115/// the APInt.
116APInt& APInt::operator=(uint64_t RHS) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000117 if (isSingleWord())
118 VAL = RHS;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000119 else {
120 pVal[0] = RHS;
Reid Spencera58f0582007-02-18 20:09:41 +0000121 memset(pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000122 }
123 return *this;
124}
125
Reid Spenceraf0e9562007-02-18 18:38:44 +0000126/// add_1 - This function adds a single "digit" integer, y, to the multiple
127/// "digit" integer array, x[]. x[] is modified to reflect the addition and
128/// 1 is returned if there is a carry out, otherwise 0 is returned.
Reid Spencer5e0a8512007-02-17 03:16:00 +0000129/// @returns the carry of the addition.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000130static uint64_t add_1(uint64_t dest[],
131 uint64_t x[], uint32_t len,
132 uint64_t y) {
133 for (uint32_t i = 0; i < len; ++i) {
Reid Spencerf2c521c2007-02-18 06:39:42 +0000134 dest[i] = y + x[i];
135 if (dest[i] < y)
136 y = 1;
137 else {
138 y = 0;
139 break;
140 }
Reid Spencer5e0a8512007-02-17 03:16:00 +0000141 }
Reid Spencerf2c521c2007-02-18 06:39:42 +0000142 return y;
Reid Spencer5e0a8512007-02-17 03:16:00 +0000143}
144
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000145/// @brief Prefix increment operator. Increments the APInt by one.
146APInt& APInt::operator++() {
Reid Spencere81d2da2007-02-16 22:36:51 +0000147 if (isSingleWord())
148 ++VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000149 else
Zhou Shenga3832fd2007-02-07 06:14:53 +0000150 add_1(pVal, pVal, getNumWords(), 1);
Reid Spencere81d2da2007-02-16 22:36:51 +0000151 clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000152 return *this;
153}
154
Reid Spenceraf0e9562007-02-18 18:38:44 +0000155/// sub_1 - This function subtracts a single "digit" (64-bit word), y, from
156/// the multi-digit integer array, x[], propagating the borrowed 1 value until
157/// no further borrowing is neeeded or it runs out of "digits" in x. The result
158/// is 1 if "borrowing" exhausted the digits in x, or 0 if x was not exhausted.
159/// In other words, if y > x then this function returns 1, otherwise 0.
160static uint64_t sub_1(uint64_t x[], uint32_t len,
161 uint64_t y) {
162 for (uint32_t i = 0; i < len; ++i) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000163 uint64_t X = x[i];
Reid Spencerf2c521c2007-02-18 06:39:42 +0000164 x[i] -= y;
165 if (y > X)
Reid Spenceraf0e9562007-02-18 18:38:44 +0000166 y = 1; // We have to "borrow 1" from next "digit"
Reid Spencer5e0a8512007-02-17 03:16:00 +0000167 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000168 y = 0; // No need to borrow
169 break; // Remaining digits are unchanged so exit early
Reid Spencer5e0a8512007-02-17 03:16:00 +0000170 }
171 }
Reid Spencerf2c521c2007-02-18 06:39:42 +0000172 return y;
Reid Spencer5e0a8512007-02-17 03:16:00 +0000173}
174
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000175/// @brief Prefix decrement operator. Decrements the APInt by one.
176APInt& APInt::operator--() {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000177 if (isSingleWord())
178 --VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000179 else
Zhou Shenga3832fd2007-02-07 06:14:53 +0000180 sub_1(pVal, getNumWords(), 1);
Reid Spencere81d2da2007-02-16 22:36:51 +0000181 clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000182 return *this;
183}
184
Reid Spencer5e0a8512007-02-17 03:16:00 +0000185/// add - This function adds the integer array x[] by integer array
186/// y[] and returns the carry.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000187static uint64_t add(uint64_t dest[], uint64_t x[],
188 uint64_t y[], uint32_t len) {
189 uint32_t carry = 0;
190 for (uint32_t i = 0; i< len; ++i) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000191 carry += x[i];
192 dest[i] = carry + y[i];
193 carry = carry < x[i] ? 1 : (dest[i] < carry ? 1 : 0);
194 }
195 return carry;
196}
197
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000198/// @brief Addition assignment operator. Adds this APInt by the given APInt&
199/// RHS and assigns the result to this APInt.
200APInt& APInt::operator+=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000201 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000202 if (isSingleWord()) VAL += RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
203 else {
Zhou Shenga3832fd2007-02-07 06:14:53 +0000204 if (RHS.isSingleWord()) add_1(pVal, pVal, getNumWords(), RHS.VAL);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000205 else {
Zhou Shenga3832fd2007-02-07 06:14:53 +0000206 if (getNumWords() <= RHS.getNumWords())
207 add(pVal, pVal, RHS.pVal, getNumWords());
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000208 else {
Zhou Shenga3832fd2007-02-07 06:14:53 +0000209 uint64_t carry = add(pVal, pVal, RHS.pVal, RHS.getNumWords());
210 add_1(pVal + RHS.getNumWords(), pVal + RHS.getNumWords(),
211 getNumWords() - RHS.getNumWords(), carry);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000212 }
213 }
214 }
Reid Spencere81d2da2007-02-16 22:36:51 +0000215 clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000216 return *this;
217}
218
Reid Spencer5e0a8512007-02-17 03:16:00 +0000219/// sub - This function subtracts the integer array x[] by
220/// integer array y[], and returns the borrow-out carry.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000221static uint64_t sub(uint64_t dest[], uint64_t x[],
222 uint64_t y[], uint32_t len) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000223 // Carry indicator.
224 uint64_t cy = 0;
225
Reid Spenceraf0e9562007-02-18 18:38:44 +0000226 for (uint32_t i = 0; i < len; ++i) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000227 uint64_t Y = y[i], X = x[i];
228 Y += cy;
229
230 cy = Y < cy ? 1 : 0;
231 Y = X - Y;
232 cy += Y > X ? 1 : 0;
233 dest[i] = Y;
234 }
235 return cy;
236}
237
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000238/// @brief Subtraction assignment operator. Subtracts this APInt by the given
239/// APInt &RHS and assigns the result to this APInt.
240APInt& APInt::operator-=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000241 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000242 if (isSingleWord())
243 VAL -= RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
244 else {
245 if (RHS.isSingleWord())
Zhou Shenga3832fd2007-02-07 06:14:53 +0000246 sub_1(pVal, getNumWords(), RHS.VAL);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000247 else {
Zhou Shenga3832fd2007-02-07 06:14:53 +0000248 if (RHS.getNumWords() < getNumWords()) {
249 uint64_t carry = sub(pVal, pVal, RHS.pVal, RHS.getNumWords());
Reid Spencerf2c521c2007-02-18 06:39:42 +0000250 sub_1(pVal + RHS.getNumWords(), getNumWords() - RHS.getNumWords(),
251 carry);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000252 }
253 else
Zhou Shenga3832fd2007-02-07 06:14:53 +0000254 sub(pVal, pVal, RHS.pVal, getNumWords());
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000255 }
256 }
Reid Spencere81d2da2007-02-16 22:36:51 +0000257 clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000258 return *this;
259}
260
Reid Spencer5e0a8512007-02-17 03:16:00 +0000261/// mul_1 - This function performs the multiplication operation on a
262/// large integer (represented as an integer array) and a uint64_t integer.
263/// @returns the carry of the multiplication.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000264static uint64_t mul_1(uint64_t dest[],
265 uint64_t x[], uint32_t len,
266 uint64_t y) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000267 // Split y into high 32-bit part and low 32-bit part.
268 uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
269 uint64_t carry = 0, lx, hx;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000270 for (uint32_t i = 0; i < len; ++i) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000271 lx = x[i] & 0xffffffffULL;
272 hx = x[i] >> 32;
273 // hasCarry - A flag to indicate if has carry.
274 // hasCarry == 0, no carry
275 // hasCarry == 1, has carry
276 // hasCarry == 2, no carry and the calculation result == 0.
277 uint8_t hasCarry = 0;
278 dest[i] = carry + lx * ly;
279 // Determine if the add above introduces carry.
280 hasCarry = (dest[i] < carry) ? 1 : 0;
281 carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
282 // The upper limit of carry can be (2^32 - 1)(2^32 - 1) +
283 // (2^32 - 1) + 2^32 = 2^64.
284 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
285
286 carry += (lx * hy) & 0xffffffffULL;
287 dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
288 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) +
289 (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
290 }
291
292 return carry;
293}
294
295/// mul - This function multiplies integer array x[] by integer array y[] and
296/// stores the result into integer array dest[].
297/// Note the array dest[]'s size should no less than xlen + ylen.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000298static void mul(uint64_t dest[], uint64_t x[], uint32_t xlen,
299 uint64_t y[], uint32_t ylen) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000300 dest[xlen] = mul_1(dest, x, xlen, y[0]);
301
Reid Spenceraf0e9562007-02-18 18:38:44 +0000302 for (uint32_t i = 1; i < ylen; ++i) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000303 uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
304 uint64_t carry = 0, lx, hx;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000305 for (uint32_t j = 0; j < xlen; ++j) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000306 lx = x[j] & 0xffffffffULL;
307 hx = x[j] >> 32;
308 // hasCarry - A flag to indicate if has carry.
309 // hasCarry == 0, no carry
310 // hasCarry == 1, has carry
311 // hasCarry == 2, no carry and the calculation result == 0.
312 uint8_t hasCarry = 0;
313 uint64_t resul = carry + lx * ly;
314 hasCarry = (resul < carry) ? 1 : 0;
315 carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
316 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
317
318 carry += (lx * hy) & 0xffffffffULL;
319 resul = (carry << 32) | (resul & 0xffffffffULL);
320 dest[i+j] += resul;
321 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
322 (carry >> 32) + (dest[i+j] < resul ? 1 : 0) +
323 ((lx * hy) >> 32) + hx * hy;
324 }
325 dest[i+xlen] = carry;
326 }
327}
328
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000329/// @brief Multiplication assignment operator. Multiplies this APInt by the
330/// given APInt& RHS and assigns the result to this APInt.
331APInt& APInt::operator*=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000332 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer61eb1802007-02-20 20:42:10 +0000333 if (isSingleWord())
334 VAL *= RHS.VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000335 else {
336 // one-based first non-zero bit position.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000337 uint32_t first = getActiveBits();
338 uint32_t xlen = !first ? 0 : whichWord(first - 1) + 1;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000339 if (!xlen)
340 return *this;
341 else if (RHS.isSingleWord())
342 mul_1(pVal, pVal, xlen, RHS.VAL);
343 else {
Reid Spencere81d2da2007-02-16 22:36:51 +0000344 first = RHS.getActiveBits();
Reid Spenceraf0e9562007-02-18 18:38:44 +0000345 uint32_t ylen = !first ? 0 : whichWord(first - 1) + 1;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000346 if (!ylen) {
Reid Spencera58f0582007-02-18 20:09:41 +0000347 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000348 return *this;
349 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000350 uint64_t *dest = getMemory(xlen+ylen);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000351 mul(dest, pVal, xlen, RHS.pVal, ylen);
Zhou Shenga3832fd2007-02-07 06:14:53 +0000352 memcpy(pVal, dest, ((xlen + ylen >= getNumWords()) ?
Reid Spencera58f0582007-02-18 20:09:41 +0000353 getNumWords() : xlen + ylen) * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000354 delete[] dest;
355 }
356 }
Reid Spencere81d2da2007-02-16 22:36:51 +0000357 clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000358 return *this;
359}
360
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000361/// @brief Bitwise AND assignment operator. Performs bitwise AND operation on
362/// this APInt and the given APInt& RHS, assigns the result to this APInt.
363APInt& APInt::operator&=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000364 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000365 if (isSingleWord()) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000366 VAL &= RHS.VAL;
367 return *this;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000368 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000369 uint32_t numWords = getNumWords();
370 for (uint32_t i = 0; i < numWords; ++i)
371 pVal[i] &= RHS.pVal[i];
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000372 return *this;
373}
374
375/// @brief Bitwise OR assignment operator. Performs bitwise OR operation on
376/// this APInt and the given APInt& RHS, assigns the result to this APInt.
377APInt& APInt::operator|=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000378 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000379 if (isSingleWord()) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000380 VAL |= RHS.VAL;
381 return *this;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000382 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000383 uint32_t numWords = getNumWords();
384 for (uint32_t i = 0; i < numWords; ++i)
385 pVal[i] |= RHS.pVal[i];
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000386 return *this;
387}
388
389/// @brief Bitwise XOR assignment operator. Performs bitwise XOR operation on
390/// this APInt and the given APInt& RHS, assigns the result to this APInt.
391APInt& APInt::operator^=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000392 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000393 if (isSingleWord()) {
Reid Spencerf2c521c2007-02-18 06:39:42 +0000394 VAL ^= RHS.VAL;
395 return *this;
396 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000397 uint32_t numWords = getNumWords();
398 for (uint32_t i = 0; i < numWords; ++i)
399 pVal[i] ^= RHS.pVal[i];
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000400 return *this;
401}
402
403/// @brief Bitwise AND operator. Performs bitwise AND operation on this APInt
404/// and the given APInt& RHS.
405APInt APInt::operator&(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000406 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spenceraf0e9562007-02-18 18:38:44 +0000407 if (isSingleWord())
408 return APInt(getBitWidth(), VAL & RHS.VAL);
409
410 APInt Result(*this);
411 uint32_t numWords = getNumWords();
412 for (uint32_t i = 0; i < numWords; ++i)
413 Result.pVal[i] &= RHS.pVal[i];
414 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000415}
416
417/// @brief Bitwise OR operator. Performs bitwise OR operation on this APInt
418/// and the given APInt& RHS.
419APInt APInt::operator|(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000420 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spenceraf0e9562007-02-18 18:38:44 +0000421 if (isSingleWord())
422 return APInt(getBitWidth(), VAL | RHS.VAL);
423 APInt Result(*this);
424 uint32_t numWords = getNumWords();
425 for (uint32_t i = 0; i < numWords; ++i)
426 Result.pVal[i] |= RHS.pVal[i];
427 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000428}
429
430/// @brief Bitwise XOR operator. Performs bitwise XOR operation on this APInt
431/// and the given APInt& RHS.
432APInt APInt::operator^(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000433 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spenceraf0e9562007-02-18 18:38:44 +0000434 if (isSingleWord())
435 return APInt(getBitWidth(), VAL ^ RHS.VAL);
436 APInt Result(*this);
437 uint32_t numWords = getNumWords();
438 for (uint32_t i = 0; i < numWords; ++i)
439 Result.pVal[i] ^= RHS.pVal[i];
440 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000441}
442
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000443/// @brief Logical negation operator. Performs logical negation operation on
444/// this APInt.
445bool APInt::operator !() const {
446 if (isSingleWord())
447 return !VAL;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000448
449 for (uint32_t i = 0; i < getNumWords(); ++i)
450 if (pVal[i])
451 return false;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000452 return true;
453}
454
455/// @brief Multiplication operator. Multiplies this APInt by the given APInt&
456/// RHS.
457APInt APInt::operator*(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000458 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer61eb1802007-02-20 20:42:10 +0000459 APInt Result(*this);
460 Result *= RHS;
461 Result.clearUnusedBits();
462 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000463}
464
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000465/// @brief Addition operator. Adds this APInt by the given APInt& RHS.
466APInt APInt::operator+(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000467 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000468 APInt API(*this);
469 API += RHS;
Reid Spencere81d2da2007-02-16 22:36:51 +0000470 API.clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000471 return API;
472}
473
474/// @brief Subtraction operator. Subtracts this APInt by the given APInt& RHS
475APInt APInt::operator-(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000476 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000477 APInt API(*this);
478 API -= RHS;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000479 return API;
480}
481
482/// @brief Array-indexing support.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000483bool APInt::operator[](uint32_t bitPosition) const {
Zhou Shengff4304f2007-02-09 07:48:24 +0000484 return (maskBit(bitPosition) & (isSingleWord() ?
485 VAL : pVal[whichWord(bitPosition)])) != 0;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000486}
487
488/// @brief Equality operator. Compare this APInt with the given APInt& RHS
489/// for the validity of the equality relationship.
490bool APInt::operator==(const APInt& RHS) const {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000491 uint32_t n1 = getActiveBits();
492 uint32_t n2 = RHS.getActiveBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000493 if (n1 != n2) return false;
494 else if (isSingleWord())
495 return VAL == (RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0]);
496 else {
Reid Spencer443b5702007-02-18 00:44:22 +0000497 if (n1 <= APINT_BITS_PER_WORD)
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000498 return pVal[0] == (RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0]);
499 for (int i = whichWord(n1 - 1); i >= 0; --i)
500 if (pVal[i] != RHS.pVal[i]) return false;
501 }
502 return true;
503}
504
Zhou Shenga3832fd2007-02-07 06:14:53 +0000505/// @brief Equality operator. Compare this APInt with the given uint64_t value
506/// for the validity of the equality relationship.
507bool APInt::operator==(uint64_t Val) const {
508 if (isSingleWord())
509 return VAL == Val;
510 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000511 uint32_t n = getActiveBits();
Reid Spencer443b5702007-02-18 00:44:22 +0000512 if (n <= APINT_BITS_PER_WORD)
Zhou Shenga3832fd2007-02-07 06:14:53 +0000513 return pVal[0] == Val;
514 else
515 return false;
516 }
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000517}
518
Reid Spencere81d2da2007-02-16 22:36:51 +0000519/// @brief Unsigned less than comparison
520bool APInt::ult(const APInt& RHS) const {
521 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
522 if (isSingleWord())
523 return VAL < RHS.VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000524 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000525 uint32_t n1 = getActiveBits();
526 uint32_t n2 = RHS.getActiveBits();
Reid Spencere81d2da2007-02-16 22:36:51 +0000527 if (n1 < n2)
528 return true;
529 else if (n2 < n1)
530 return false;
Reid Spencer443b5702007-02-18 00:44:22 +0000531 else if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
Reid Spencere81d2da2007-02-16 22:36:51 +0000532 return pVal[0] < RHS.pVal[0];
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000533 for (int i = whichWord(n1 - 1); i >= 0; --i) {
534 if (pVal[i] > RHS.pVal[i]) return false;
535 else if (pVal[i] < RHS.pVal[i]) return true;
536 }
537 }
538 return false;
539}
540
Reid Spencere81d2da2007-02-16 22:36:51 +0000541/// @brief Signed less than comparison
542bool APInt::slt(const APInt& RHS) const {
543 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
Reid Spencera58f0582007-02-18 20:09:41 +0000544 if (isSingleWord()) {
545 int64_t lhsSext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
546 int64_t rhsSext = (int64_t(RHS.VAL) << (64-BitWidth)) >> (64-BitWidth);
547 return lhsSext < rhsSext;
Reid Spencere81d2da2007-02-16 22:36:51 +0000548 }
Reid Spencera58f0582007-02-18 20:09:41 +0000549
550 APInt lhs(*this);
551 APInt rhs(*this);
552 bool lhsNegative = false;
553 bool rhsNegative = false;
554 if (lhs[BitWidth-1]) {
555 lhsNegative = true;
556 lhs.flip();
557 lhs++;
558 }
559 if (rhs[BitWidth-1]) {
560 rhsNegative = true;
561 rhs.flip();
562 rhs++;
563 }
564 if (lhsNegative)
565 if (rhsNegative)
566 return !lhs.ult(rhs);
567 else
568 return true;
569 else if (rhsNegative)
570 return false;
571 else
572 return lhs.ult(rhs);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000573}
574
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000575/// Set the given bit to 1 whose poition is given as "bitPosition".
576/// @brief Set a given bit to 1.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000577APInt& APInt::set(uint32_t bitPosition) {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000578 if (isSingleWord()) VAL |= maskBit(bitPosition);
579 else pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
580 return *this;
581}
582
583/// @brief Set every bit to 1.
584APInt& APInt::set() {
Reid Spencer443b5702007-02-18 00:44:22 +0000585 if (isSingleWord())
586 VAL = ~0ULL >> (APINT_BITS_PER_WORD - BitWidth);
Zhou Shengb04973e2007-02-15 06:36:31 +0000587 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000588 for (uint32_t i = 0; i < getNumWords() - 1; ++i)
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000589 pVal[i] = -1ULL;
Reid Spencer443b5702007-02-18 00:44:22 +0000590 pVal[getNumWords() - 1] = ~0ULL >>
591 (APINT_BITS_PER_WORD - BitWidth % APINT_BITS_PER_WORD);
Zhou Shengb04973e2007-02-15 06:36:31 +0000592 }
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000593 return *this;
594}
595
596/// Set the given bit to 0 whose position is given as "bitPosition".
597/// @brief Set a given bit to 0.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000598APInt& APInt::clear(uint32_t bitPosition) {
599 if (isSingleWord())
600 VAL &= ~maskBit(bitPosition);
601 else
602 pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000603 return *this;
604}
605
606/// @brief Set every bit to 0.
607APInt& APInt::clear() {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000608 if (isSingleWord())
609 VAL = 0;
Zhou Shenga3832fd2007-02-07 06:14:53 +0000610 else
Reid Spencera58f0582007-02-18 20:09:41 +0000611 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000612 return *this;
613}
614
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000615/// @brief Bitwise NOT operator. Performs a bitwise logical NOT operation on
616/// this APInt.
617APInt APInt::operator~() const {
618 APInt API(*this);
619 API.flip();
620 return API;
621}
622
623/// @brief Toggle every bit to its opposite value.
624APInt& APInt::flip() {
Reid Spencer443b5702007-02-18 00:44:22 +0000625 if (isSingleWord()) VAL = (~(VAL <<
626 (APINT_BITS_PER_WORD - BitWidth))) >> (APINT_BITS_PER_WORD - BitWidth);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000627 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000628 uint32_t i = 0;
Zhou Shenga3832fd2007-02-07 06:14:53 +0000629 for (; i < getNumWords() - 1; ++i)
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000630 pVal[i] = ~pVal[i];
Reid Spenceraf0e9562007-02-18 18:38:44 +0000631 uint32_t offset =
Reid Spencer443b5702007-02-18 00:44:22 +0000632 APINT_BITS_PER_WORD - (BitWidth - APINT_BITS_PER_WORD * (i - 1));
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000633 pVal[i] = (~(pVal[i] << offset)) >> offset;
634 }
635 return *this;
636}
637
638/// Toggle a given bit to its opposite value whose position is given
639/// as "bitPosition".
640/// @brief Toggles a given bit to its opposite value.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000641APInt& APInt::flip(uint32_t bitPosition) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000642 assert(bitPosition < BitWidth && "Out of the bit-width range!");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000643 if ((*this)[bitPosition]) clear(bitPosition);
644 else set(bitPosition);
645 return *this;
646}
647
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000648/// getMaxValue - This function returns the largest value
649/// for an APInt of the specified bit-width and if isSign == true,
650/// it should be largest signed value, otherwise unsigned value.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000651APInt APInt::getMaxValue(uint32_t numBits, bool isSign) {
Reid Spencerf99a0ac2007-02-18 22:29:05 +0000652 APInt Result(numBits, 0);
653 Result.set();
654 if (isSign)
655 Result.clear(numBits - 1);
656 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000657}
658
659/// getMinValue - This function returns the smallest value for
660/// an APInt of the given bit-width and if isSign == true,
661/// it should be smallest signed value, otherwise zero.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000662APInt APInt::getMinValue(uint32_t numBits, bool isSign) {
Reid Spencerf99a0ac2007-02-18 22:29:05 +0000663 APInt Result(numBits, 0);
664 if (isSign)
665 Result.set(numBits - 1);
666 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000667}
668
669/// getAllOnesValue - This function returns an all-ones value for
670/// an APInt of the specified bit-width.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000671APInt APInt::getAllOnesValue(uint32_t numBits) {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000672 return getMaxValue(numBits, false);
673}
674
675/// getNullValue - This function creates an '0' value for an
676/// APInt of the specified bit-width.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000677APInt APInt::getNullValue(uint32_t numBits) {
Zhou Shengb04973e2007-02-15 06:36:31 +0000678 return getMinValue(numBits, false);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000679}
680
681/// HiBits - This function returns the high "numBits" bits of this APInt.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000682APInt APInt::getHiBits(uint32_t numBits) const {
Reid Spencere81d2da2007-02-16 22:36:51 +0000683 return APIntOps::lshr(*this, BitWidth - numBits);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000684}
685
686/// LoBits - This function returns the low "numBits" bits of this APInt.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000687APInt APInt::getLoBits(uint32_t numBits) const {
Reid Spencere81d2da2007-02-16 22:36:51 +0000688 return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits),
689 BitWidth - numBits);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000690}
691
Reid Spencere81d2da2007-02-16 22:36:51 +0000692bool APInt::isPowerOf2() const {
693 return (!!*this) && !(*this & (*this - APInt(BitWidth,1)));
694}
695
696/// countLeadingZeros - This function is a APInt version corresponding to
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000697/// llvm/include/llvm/Support/MathExtras.h's function
Reid Spencere81d2da2007-02-16 22:36:51 +0000698/// countLeadingZeros_{32, 64}. It performs platform optimal form of counting
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000699/// the number of zeros from the most significant bit to the first one bit.
700/// @returns numWord() * 64 if the value is zero.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000701uint32_t APInt::countLeadingZeros() const {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000702 if (isSingleWord())
Reid Spencer443b5702007-02-18 00:44:22 +0000703 return CountLeadingZeros_64(VAL) - (APINT_BITS_PER_WORD - BitWidth);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000704 uint32_t Count = 0;
705 for (uint32_t i = getNumWords(); i > 0u; --i) {
706 uint32_t tmp = CountLeadingZeros_64(pVal[i-1]);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000707 Count += tmp;
Reid Spencer443b5702007-02-18 00:44:22 +0000708 if (tmp != APINT_BITS_PER_WORD)
709 if (i == getNumWords())
710 Count -= (APINT_BITS_PER_WORD - whichBit(BitWidth));
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000711 break;
712 }
713 return Count;
714}
715
Reid Spencere81d2da2007-02-16 22:36:51 +0000716/// countTrailingZeros - This function is a APInt version corresponding to
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000717/// llvm/include/llvm/Support/MathExtras.h's function
Reid Spencere81d2da2007-02-16 22:36:51 +0000718/// countTrailingZeros_{32, 64}. It performs platform optimal form of counting
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000719/// the number of zeros from the least significant bit to the first one bit.
720/// @returns numWord() * 64 if the value is zero.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000721uint32_t APInt::countTrailingZeros() const {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000722 if (isSingleWord())
Reid Spencer443b5702007-02-18 00:44:22 +0000723 return CountTrailingZeros_64(VAL);
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000724 APInt Tmp( ~(*this) & ((*this) - APInt(BitWidth,1)) );
Reid Spencere81d2da2007-02-16 22:36:51 +0000725 return getNumWords() * APINT_BITS_PER_WORD - Tmp.countLeadingZeros();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000726}
727
Reid Spencere81d2da2007-02-16 22:36:51 +0000728/// countPopulation - This function is a APInt version corresponding to
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000729/// llvm/include/llvm/Support/MathExtras.h's function
Reid Spencere81d2da2007-02-16 22:36:51 +0000730/// countPopulation_{32, 64}. It counts the number of set bits in a value.
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000731/// @returns 0 if the value is zero.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000732uint32_t APInt::countPopulation() const {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000733 if (isSingleWord())
734 return CountPopulation_64(VAL);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000735 uint32_t Count = 0;
736 for (uint32_t i = 0; i < getNumWords(); ++i)
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000737 Count += CountPopulation_64(pVal[i]);
738 return Count;
739}
740
741
Reid Spencere81d2da2007-02-16 22:36:51 +0000742/// byteSwap - This function returns a byte-swapped representation of the
Zhou Shengff4304f2007-02-09 07:48:24 +0000743/// this APInt.
Reid Spencere81d2da2007-02-16 22:36:51 +0000744APInt APInt::byteSwap() const {
745 assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
746 if (BitWidth == 16)
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000747 return APInt(BitWidth, ByteSwap_16(VAL));
Reid Spencere81d2da2007-02-16 22:36:51 +0000748 else if (BitWidth == 32)
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000749 return APInt(BitWidth, ByteSwap_32(VAL));
Reid Spencere81d2da2007-02-16 22:36:51 +0000750 else if (BitWidth == 48) {
Zhou Shengb04973e2007-02-15 06:36:31 +0000751 uint64_t Tmp1 = ((VAL >> 32) << 16) | (VAL & 0xFFFF);
752 Tmp1 = ByteSwap_32(Tmp1);
753 uint64_t Tmp2 = (VAL >> 16) & 0xFFFF;
754 Tmp2 = ByteSwap_16(Tmp2);
755 return
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000756 APInt(BitWidth,
757 (Tmp1 & 0xff) | ((Tmp1<<16) & 0xffff00000000ULL) | (Tmp2 << 16));
Reid Spencere81d2da2007-02-16 22:36:51 +0000758 } else if (BitWidth == 64)
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000759 return APInt(BitWidth, ByteSwap_64(VAL));
Zhou Shengb04973e2007-02-15 06:36:31 +0000760 else {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000761 APInt Result(BitWidth, 0);
Zhou Shengb04973e2007-02-15 06:36:31 +0000762 char *pByte = (char*)Result.pVal;
Reid Spencera58f0582007-02-18 20:09:41 +0000763 for (uint32_t i = 0; i < BitWidth / APINT_WORD_SIZE / 2; ++i) {
Zhou Shengb04973e2007-02-15 06:36:31 +0000764 char Tmp = pByte[i];
Reid Spencera58f0582007-02-18 20:09:41 +0000765 pByte[i] = pByte[BitWidth / APINT_WORD_SIZE - 1 - i];
766 pByte[BitWidth / APINT_WORD_SIZE - i - 1] = Tmp;
Zhou Shengb04973e2007-02-15 06:36:31 +0000767 }
768 return Result;
769 }
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000770}
771
772/// GreatestCommonDivisor - This function returns the greatest common
773/// divisor of the two APInt values using Enclid's algorithm.
Zhou Sheng0b706b12007-02-08 14:35:19 +0000774APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1,
775 const APInt& API2) {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000776 APInt A = API1, B = API2;
777 while (!!B) {
778 APInt T = B;
Reid Spencere81d2da2007-02-16 22:36:51 +0000779 B = APIntOps::urem(A, B);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000780 A = T;
781 }
782 return A;
783}
Chris Lattner6ad4c142007-02-06 05:38:37 +0000784
Zhou Shengd93f00c2007-02-12 20:02:55 +0000785/// DoubleRoundToAPInt - This function convert a double value to
786/// a APInt value.
Reid Spencere81d2da2007-02-16 22:36:51 +0000787APInt llvm::APIntOps::RoundDoubleToAPInt(double Double) {
Zhou Shengd93f00c2007-02-12 20:02:55 +0000788 union {
789 double D;
790 uint64_t I;
791 } T;
792 T.D = Double;
793 bool isNeg = T.I >> 63;
794 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
795 if (exp < 0)
Reid Spencere81d2da2007-02-16 22:36:51 +0000796 return APInt(64ull, 0u);
Zhou Shengd93f00c2007-02-12 20:02:55 +0000797 uint64_t mantissa = ((T.I << 12) >> 12) | (1ULL << 52);
798 if (exp < 52)
Reid Spencere81d2da2007-02-16 22:36:51 +0000799 return isNeg ? -APInt(64u, mantissa >> (52 - exp)) :
800 APInt(64u, mantissa >> (52 - exp));
801 APInt Tmp(exp + 1, mantissa);
802 Tmp = Tmp.shl(exp - 52);
Zhou Shengd93f00c2007-02-12 20:02:55 +0000803 return isNeg ? -Tmp : Tmp;
804}
805
Reid Spencerdb3faa62007-02-13 22:41:58 +0000806/// RoundToDouble - This function convert this APInt to a double.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000807/// The layout for double is as following (IEEE Standard 754):
808/// --------------------------------------
809/// | Sign Exponent Fraction Bias |
810/// |-------------------------------------- |
811/// | 1[63] 11[62-52] 52[51-00] 1023 |
812/// --------------------------------------
Reid Spencere81d2da2007-02-16 22:36:51 +0000813double APInt::roundToDouble(bool isSigned) const {
Reid Spencer9c0696f2007-02-20 08:51:03 +0000814
815 // Handle the simple case where the value is contained in one uint64_t.
Reid Spencera58f0582007-02-18 20:09:41 +0000816 if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
817 if (isSigned) {
818 int64_t sext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
819 return double(sext);
820 } else
821 return double(VAL);
822 }
823
Reid Spencer9c0696f2007-02-20 08:51:03 +0000824 // Determine if the value is negative.
Reid Spencere81d2da2007-02-16 22:36:51 +0000825 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
Reid Spencer9c0696f2007-02-20 08:51:03 +0000826
827 // Construct the absolute value if we're negative.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000828 APInt Tmp(isNeg ? -(*this) : (*this));
Reid Spencer9c0696f2007-02-20 08:51:03 +0000829
830 // Figure out how many bits we're using.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000831 uint32_t n = Tmp.getActiveBits();
Zhou Shengd93f00c2007-02-12 20:02:55 +0000832
Reid Spencer9c0696f2007-02-20 08:51:03 +0000833 // The exponent (without bias normalization) is just the number of bits
834 // we are using. Note that the sign bit is gone since we constructed the
835 // absolute value.
836 uint64_t exp = n;
Zhou Shengd93f00c2007-02-12 20:02:55 +0000837
Reid Spencer9c0696f2007-02-20 08:51:03 +0000838 // Return infinity for exponent overflow
839 if (exp > 1023) {
840 if (!isSigned || !isNeg)
Reid Spencer61eb1802007-02-20 20:42:10 +0000841 return double(1.0E300 * 1.0E300); // positive infinity
Reid Spencer9c0696f2007-02-20 08:51:03 +0000842 else
Reid Spencer61eb1802007-02-20 20:42:10 +0000843 return double(-1.0E300 * 1.0E300); // negative infinity
Reid Spencer9c0696f2007-02-20 08:51:03 +0000844 }
845 exp += 1023; // Increment for 1023 bias
846
847 // Number of bits in mantissa is 52. To obtain the mantissa value, we must
848 // extract the high 52 bits from the correct words in pVal.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000849 uint64_t mantissa;
Reid Spencer9c0696f2007-02-20 08:51:03 +0000850 unsigned hiWord = whichWord(n-1);
851 if (hiWord == 0) {
852 mantissa = Tmp.pVal[0];
853 if (n > 52)
854 mantissa >>= n - 52; // shift down, we want the top 52 bits.
855 } else {
856 assert(hiWord > 0 && "huh?");
857 uint64_t hibits = Tmp.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
858 uint64_t lobits = Tmp.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
859 mantissa = hibits | lobits;
860 }
861
Zhou Shengd93f00c2007-02-12 20:02:55 +0000862 // The leading bit of mantissa is implicit, so get rid of it.
Reid Spencer443b5702007-02-18 00:44:22 +0000863 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
Zhou Shengd93f00c2007-02-12 20:02:55 +0000864 union {
865 double D;
866 uint64_t I;
867 } T;
868 T.I = sign | (exp << 52) | mantissa;
869 return T.D;
870}
871
Reid Spencere81d2da2007-02-16 22:36:51 +0000872// Truncate to new width.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000873void APInt::trunc(uint32_t width) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000874 assert(width < BitWidth && "Invalid APInt Truncate request");
875}
876
877// Sign extend to a new width.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000878void APInt::sext(uint32_t width) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000879 assert(width > BitWidth && "Invalid APInt SignExtend request");
880}
881
882// Zero extend to a new width.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000883void APInt::zext(uint32_t width) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000884 assert(width > BitWidth && "Invalid APInt ZeroExtend request");
885}
886
Zhou Shengff4304f2007-02-09 07:48:24 +0000887/// Arithmetic right-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +0000888/// @brief Arithmetic right-shift function.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000889APInt APInt::ashr(uint32_t shiftAmt) const {
Zhou Shengff4304f2007-02-09 07:48:24 +0000890 APInt API(*this);
Zhou Sheng0b706b12007-02-08 14:35:19 +0000891 if (API.isSingleWord())
Reid Spencer443b5702007-02-18 00:44:22 +0000892 API.VAL =
893 (((int64_t(API.VAL) << (APINT_BITS_PER_WORD - API.BitWidth)) >>
894 (APINT_BITS_PER_WORD - API.BitWidth)) >> shiftAmt) &
895 (~uint64_t(0UL) >> (APINT_BITS_PER_WORD - API.BitWidth));
Zhou Sheng0b706b12007-02-08 14:35:19 +0000896 else {
Reid Spencere81d2da2007-02-16 22:36:51 +0000897 if (shiftAmt >= API.BitWidth) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000898 memset(API.pVal, API[API.BitWidth-1] ? 1 : 0,
Reid Spencera58f0582007-02-18 20:09:41 +0000899 (API.getNumWords()-1) * APINT_WORD_SIZE);
Reid Spencer443b5702007-02-18 00:44:22 +0000900 API.pVal[API.getNumWords() - 1] =
901 ~uint64_t(0UL) >>
902 (APINT_BITS_PER_WORD - API.BitWidth % APINT_BITS_PER_WORD);
Zhou Sheng0b706b12007-02-08 14:35:19 +0000903 } else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000904 uint32_t i = 0;
Reid Spencere81d2da2007-02-16 22:36:51 +0000905 for (; i < API.BitWidth - shiftAmt; ++i)
Zhou Sheng0b706b12007-02-08 14:35:19 +0000906 if (API[i+shiftAmt])
907 API.set(i);
908 else
909 API.clear(i);
Reid Spencere81d2da2007-02-16 22:36:51 +0000910 for (; i < API.BitWidth; ++i)
911 if (API[API.BitWidth-1])
Zhou Shengb04973e2007-02-15 06:36:31 +0000912 API.set(i);
913 else API.clear(i);
Zhou Sheng0b706b12007-02-08 14:35:19 +0000914 }
915 }
916 return API;
917}
918
Zhou Shengff4304f2007-02-09 07:48:24 +0000919/// Logical right-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +0000920/// @brief Logical right-shift function.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000921APInt APInt::lshr(uint32_t shiftAmt) const {
Zhou Shengff4304f2007-02-09 07:48:24 +0000922 APInt API(*this);
Zhou Sheng0b706b12007-02-08 14:35:19 +0000923 if (API.isSingleWord())
924 API.VAL >>= shiftAmt;
925 else {
Reid Spencere81d2da2007-02-16 22:36:51 +0000926 if (shiftAmt >= API.BitWidth)
Reid Spencera58f0582007-02-18 20:09:41 +0000927 memset(API.pVal, 0, API.getNumWords() * APINT_WORD_SIZE);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000928 uint32_t i = 0;
Reid Spencere81d2da2007-02-16 22:36:51 +0000929 for (i = 0; i < API.BitWidth - shiftAmt; ++i)
Zhou Sheng0b706b12007-02-08 14:35:19 +0000930 if (API[i+shiftAmt]) API.set(i);
931 else API.clear(i);
Reid Spencere81d2da2007-02-16 22:36:51 +0000932 for (; i < API.BitWidth; ++i)
Zhou Sheng0b706b12007-02-08 14:35:19 +0000933 API.clear(i);
934 }
935 return API;
936}
937
Zhou Shengff4304f2007-02-09 07:48:24 +0000938/// Left-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +0000939/// @brief Left-shift function.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000940APInt APInt::shl(uint32_t shiftAmt) const {
Zhou Shengff4304f2007-02-09 07:48:24 +0000941 APInt API(*this);
Zhou Shengd93f00c2007-02-12 20:02:55 +0000942 if (API.isSingleWord())
943 API.VAL <<= shiftAmt;
Reid Spencere81d2da2007-02-16 22:36:51 +0000944 else if (shiftAmt >= API.BitWidth)
Reid Spencera58f0582007-02-18 20:09:41 +0000945 memset(API.pVal, 0, API.getNumWords() * APINT_WORD_SIZE);
Zhou Shengd93f00c2007-02-12 20:02:55 +0000946 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000947 if (uint32_t offset = shiftAmt / APINT_BITS_PER_WORD) {
948 for (uint32_t i = API.getNumWords() - 1; i > offset - 1; --i)
Zhou Shengd93f00c2007-02-12 20:02:55 +0000949 API.pVal[i] = API.pVal[i-offset];
Reid Spencera58f0582007-02-18 20:09:41 +0000950 memset(API.pVal, 0, offset * APINT_WORD_SIZE);
Zhou Sheng0b706b12007-02-08 14:35:19 +0000951 }
Reid Spencer443b5702007-02-18 00:44:22 +0000952 shiftAmt %= APINT_BITS_PER_WORD;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000953 uint32_t i;
Zhou Shengd93f00c2007-02-12 20:02:55 +0000954 for (i = API.getNumWords() - 1; i > 0; --i)
955 API.pVal[i] = (API.pVal[i] << shiftAmt) |
Reid Spencer443b5702007-02-18 00:44:22 +0000956 (API.pVal[i-1] >> (APINT_BITS_PER_WORD - shiftAmt));
Zhou Shengd93f00c2007-02-12 20:02:55 +0000957 API.pVal[i] <<= shiftAmt;
Zhou Sheng0b706b12007-02-08 14:35:19 +0000958 }
Reid Spencere81d2da2007-02-16 22:36:51 +0000959 API.clearUnusedBits();
Zhou Sheng0b706b12007-02-08 14:35:19 +0000960 return API;
961}
962
Reid Spencer9c0696f2007-02-20 08:51:03 +0000963#if 0
Reid Spencer5e0a8512007-02-17 03:16:00 +0000964/// subMul - This function substracts x[len-1:0] * y from
965/// dest[offset+len-1:offset], and returns the most significant
966/// word of the product, minus the borrow-out from the subtraction.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000967static uint32_t subMul(uint32_t dest[], uint32_t offset,
968 uint32_t x[], uint32_t len, uint32_t y) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000969 uint64_t yl = (uint64_t) y & 0xffffffffL;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000970 uint32_t carry = 0;
971 uint32_t j = 0;
Reid Spencer5e0a8512007-02-17 03:16:00 +0000972 do {
Reid Spencerc72f2802007-02-17 22:38:07 +0000973 uint64_t prod = ((uint64_t) x[j] & 0xffffffffUL) * yl;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000974 uint32_t prod_low = (uint32_t) prod;
975 uint32_t prod_high = (uint32_t) (prod >> 32);
Reid Spencer5e0a8512007-02-17 03:16:00 +0000976 prod_low += carry;
977 carry = (prod_low < carry ? 1 : 0) + prod_high;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000978 uint32_t x_j = dest[offset+j];
Reid Spencer5e0a8512007-02-17 03:16:00 +0000979 prod_low = x_j - prod_low;
980 if (prod_low > x_j) ++carry;
981 dest[offset+j] = prod_low;
982 } while (++j < len);
983 return carry;
984}
985
986/// unitDiv - This function divides N by D,
987/// and returns (remainder << 32) | quotient.
988/// Assumes (N >> 32) < D.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000989static uint64_t unitDiv(uint64_t N, uint32_t D) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000990 uint64_t q, r; // q: quotient, r: remainder.
991 uint64_t a1 = N >> 32; // a1: high 32-bit part of N.
992 uint64_t a0 = N & 0xffffffffL; // a0: low 32-bit part of N
993 if (a1 < ((D - a1 - (a0 >> 31)) & 0xffffffffL)) {
994 q = N / D;
995 r = N % D;
996 }
997 else {
998 // Compute c1*2^32 + c0 = a1*2^32 + a0 - 2^31*d
999 uint64_t c = N - ((uint64_t) D << 31);
1000 // Divide (c1*2^32 + c0) by d
1001 q = c / D;
1002 r = c % D;
1003 // Add 2^31 to quotient
1004 q += 1 << 31;
1005 }
1006
1007 return (r << 32) | (q & 0xFFFFFFFFl);
1008}
1009
Reid Spencer9c0696f2007-02-20 08:51:03 +00001010#endif
1011
Reid Spencer5e0a8512007-02-17 03:16:00 +00001012/// div - This is basically Knuth's formulation of the classical algorithm.
1013/// Correspondance with Knuth's notation:
1014/// Knuth's u[0:m+n] == zds[nx:0].
1015/// Knuth's v[1:n] == y[ny-1:0]
1016/// Knuth's n == ny.
1017/// Knuth's m == nx-ny.
1018/// Our nx == Knuth's m+n.
1019/// Could be re-implemented using gmp's mpn_divrem:
1020/// zds[nx] = mpn_divrem (&zds[ny], 0, zds, nx, y, ny).
Reid Spencer9c0696f2007-02-20 08:51:03 +00001021
1022/// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
1023/// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
1024/// variables here have the same names as in the algorithm. Comments explain
1025/// the algorithm and any deviation from it.
1026static void KnuthDiv(uint32_t *u, uint32_t *v, uint32_t *q, uint32_t* r,
1027 uint32_t m, uint32_t n) {
1028 assert(u && "Must provide dividend");
1029 assert(v && "Must provide divisor");
1030 assert(q && "Must provide quotient");
1031 assert(n>1 && "n must be > 1");
1032
1033 // Knuth uses the value b as the base of the number system. In our case b
1034 // is 2^31 so we just set it to -1u.
1035 uint64_t b = uint64_t(1) << 32;
1036
1037 // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
1038 // u and v by d. Note that we have taken Knuth's advice here to use a power
1039 // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
1040 // 2 allows us to shift instead of multiply and it is easy to determine the
1041 // shift amount from the leading zeros. We are basically normalizing the u
1042 // and v so that its high bits are shifted to the top of v's range without
1043 // overflow. Note that this can require an extra word in u so that u must
1044 // be of length m+n+1.
1045 uint32_t shift = CountLeadingZeros_32(v[n-1]);
1046 uint32_t v_carry = 0;
1047 uint32_t u_carry = 0;
1048 if (shift) {
1049 for (uint32_t i = 0; i < m+n; ++i) {
1050 uint32_t u_tmp = u[i] >> (32 - shift);
1051 u[i] = (u[i] << shift) | u_carry;
1052 u_carry = u_tmp;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001053 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001054 for (uint32_t i = 0; i < n; ++i) {
1055 uint32_t v_tmp = v[i] >> (32 - shift);
1056 v[i] = (v[i] << shift) | v_carry;
1057 v_carry = v_tmp;
1058 }
1059 }
1060 u[m+n] = u_carry;
1061
1062 // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
1063 int j = m;
1064 do {
1065 // D3. [Calculate q'.].
1066 // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
1067 // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
1068 // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
1069 // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test
1070 // on v[n-2] determines at high speed most of the cases in which the trial
1071 // value qp is one too large, and it eliminates all cases where qp is two
1072 // too large.
1073 uint64_t qp = ((uint64_t(u[j+n]) << 32) | uint64_t(u[j+n-1])) / v[n-1];
1074 uint64_t rp = ((uint64_t(u[j+n]) << 32) | uint64_t(u[j+n-1])) % v[n-1];
1075 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1076 qp--;
1077 rp += v[n-1];
1078 }
1079 if (rp < b)
1080 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1081 qp--;
1082 rp += v[n-1];
1083 }
1084
1085 // D4. [Multiply and subtract.] Replace u with u - q*v (for each word).
1086 uint32_t borrow = 0;
1087 for (uint32_t i = 0; i < n; i++) {
1088 uint32_t save = u[j+i];
1089 u[j+i] = uint64_t(u[j+i]) - (qp * v[i]) - borrow;
1090 if (u[j+i] > save) {
1091 borrow = 1;
1092 u[j+i+1] += b;
1093 } else {
1094 borrow = 0;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001095 }
1096 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001097 if (borrow)
1098 u[j+n] += 1;
1099
1100 // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
1101 // negative, go to step D6; otherwise go on to step D7.
1102 q[j] = qp;
1103 if (borrow) {
1104 // D6. [Add back]. The probability that this step is necessary is very
1105 // small, on the order of only 2/b. Make sure that test data accounts for
1106 // this possibility. Decreate qj by 1 and add v[...] to u[...]. A carry
1107 // will occur to the left of u[j+n], and it should be ignored since it
1108 // cancels with the borrow that occurred in D4.
1109 uint32_t carry = 0;
1110 for (uint32_t i = 0; i < n; i++) {
1111 uint32_t save = u[j+i];
1112 u[j+i] += v[i] + carry;
1113 carry = u[j+i] < save;
1114 }
1115 }
1116
1117 // D7. [Loop on j.] Decreate j by one. Now if j >= 0, go back to D3.
1118 j--;
1119 } while (j >= 0);
1120
1121 // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
1122 // remainder may be obtained by dividing u[...] by d. If r is non-null we
1123 // compute the remainder (urem uses this).
1124 if (r) {
1125 // The value d is expressed by the "shift" value above since we avoided
1126 // multiplication by d by using a shift left. So, all we have to do is
1127 // shift right here. In order to mak
1128 uint32_t mask = ~0u >> (32 - shift);
1129 uint32_t carry = 0;
1130 for (int i = n-1; i >= 0; i--) {
1131 uint32_t save = u[i] & mask;
1132 r[i] = (u[i] >> shift) | carry;
1133 carry = save;
1134 }
1135 }
1136}
1137
1138// This function makes calling KnuthDiv a little more convenient. It uses
1139// APInt parameters instead of uint32_t* parameters. It can also divide APInt
1140// values of different widths.
1141void APInt::divide(const APInt LHS, uint32_t lhsWords,
1142 const APInt &RHS, uint32_t rhsWords,
1143 APInt *Quotient, APInt *Remainder)
1144{
1145 assert(lhsWords >= rhsWords && "Fractional result");
1146
1147 // First, compose the values into an array of 32-bit words instead of
1148 // 64-bit words. This is a necessity of both the "short division" algorithm
1149 // and the the Knuth "classical algorithm" which requires there to be native
1150 // operations for +, -, and * on an m bit value with an m*2 bit result. We
1151 // can't use 64-bit operands here because we don't have native results of
1152 // 128-bits. Furthremore, casting the 64-bit values to 32-bit values won't
1153 // work on large-endian machines.
1154 uint64_t mask = ~0ull >> (sizeof(uint32_t)*8);
1155 uint32_t n = rhsWords * 2;
1156 uint32_t m = (lhsWords * 2) - n;
1157 // FIXME: allocate space on stack if m and n are sufficiently small.
1158 uint32_t *U = new uint32_t[m + n + 1];
1159 memset(U, 0, (m+n+1)*sizeof(uint32_t));
1160 for (unsigned i = 0; i < lhsWords; ++i) {
1161 uint64_t tmp = (lhsWords == 1 ? LHS.VAL : LHS.pVal[i]);
1162 U[i * 2] = tmp & mask;
1163 U[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1164 }
1165 U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
1166
1167 uint32_t *V = new uint32_t[n];
1168 memset(V, 0, (n)*sizeof(uint32_t));
1169 for (unsigned i = 0; i < rhsWords; ++i) {
1170 uint64_t tmp = (rhsWords == 1 ? RHS.VAL : RHS.pVal[i]);
1171 V[i * 2] = tmp & mask;
1172 V[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1173 }
1174
1175 // Set up the quotient and remainder
1176 uint32_t *Q = new uint32_t[m+n];
1177 memset(Q, 0, (m+n) * sizeof(uint32_t));
1178 uint32_t *R = 0;
1179 if (Remainder) {
1180 R = new uint32_t[n];
1181 memset(R, 0, n * sizeof(uint32_t));
1182 }
1183
1184 // Now, adjust m and n for the Knuth division. n is the number of words in
1185 // the divisor. m is the number of words by which the dividend exceeds the
1186 // divisor (i.e. m+n is the length of the dividend). These sizes must not
1187 // contain any zero words or the Knuth algorithm fails.
1188 for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
1189 n--;
1190 m++;
1191 }
1192 for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
1193 m--;
1194
1195 // If we're left with only a single word for the divisor, Knuth doesn't work
1196 // so we implement the short division algorithm here. This is much simpler
1197 // and faster because we are certain that we can divide a 64-bit quantity
1198 // by a 32-bit quantity at hardware speed and short division is simply a
1199 // series of such operations. This is just like doing short division but we
1200 // are using base 2^32 instead of base 10.
1201 assert(n != 0 && "Divide by zero?");
1202 if (n == 1) {
1203 uint32_t divisor = V[0];
1204 uint32_t remainder = 0;
1205 for (int i = m+n-1; i >= 0; i--) {
1206 uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i];
1207 if (partial_dividend == 0) {
1208 Q[i] = 0;
1209 remainder = 0;
1210 } else if (partial_dividend < divisor) {
1211 Q[i] = 0;
1212 remainder = partial_dividend;
1213 } else if (partial_dividend == divisor) {
1214 Q[i] = 1;
1215 remainder = 0;
1216 } else {
1217 Q[i] = partial_dividend / divisor;
1218 remainder = partial_dividend - (Q[i] * divisor);
1219 }
1220 }
1221 if (R)
1222 R[0] = remainder;
1223 } else {
1224 // Now we're ready to invoke the Knuth classical divide algorithm. In this
1225 // case n > 1.
1226 KnuthDiv(U, V, Q, R, m, n);
1227 }
1228
1229 // If the caller wants the quotient
1230 if (Quotient) {
1231 // Set up the Quotient value's memory.
1232 if (Quotient->BitWidth != LHS.BitWidth) {
1233 if (Quotient->isSingleWord())
1234 Quotient->VAL = 0;
1235 else
1236 delete Quotient->pVal;
1237 Quotient->BitWidth = LHS.BitWidth;
1238 if (!Quotient->isSingleWord())
1239 Quotient->pVal = getClearedMemory(lhsWords);
1240 } else
1241 Quotient->clear();
1242
1243 // The quotient is in Q. Reconstitute the quotient into Quotient's low
1244 // order words.
1245 if (lhsWords == 1) {
1246 uint64_t tmp =
1247 uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2));
1248 if (Quotient->isSingleWord())
1249 Quotient->VAL = tmp;
1250 else
1251 Quotient->pVal[0] = tmp;
1252 } else {
1253 assert(!Quotient->isSingleWord() && "Quotient APInt not large enough");
1254 for (unsigned i = 0; i < lhsWords; ++i)
1255 Quotient->pVal[i] =
1256 uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1257 }
1258 }
1259
1260 // If the caller wants the remainder
1261 if (Remainder) {
1262 // Set up the Remainder value's memory.
1263 if (Remainder->BitWidth != RHS.BitWidth) {
1264 if (Remainder->isSingleWord())
1265 Remainder->VAL = 0;
1266 else
1267 delete Remainder->pVal;
1268 Remainder->BitWidth = RHS.BitWidth;
1269 if (!Remainder->isSingleWord())
1270 Remainder->pVal = getClearedMemory(rhsWords);
1271 } else
1272 Remainder->clear();
1273
1274 // The remainder is in R. Reconstitute the remainder into Remainder's low
1275 // order words.
1276 if (rhsWords == 1) {
1277 uint64_t tmp =
1278 uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2));
1279 if (Remainder->isSingleWord())
1280 Remainder->VAL = tmp;
1281 else
1282 Remainder->pVal[0] = tmp;
1283 } else {
1284 assert(!Remainder->isSingleWord() && "Remainder APInt not large enough");
1285 for (unsigned i = 0; i < rhsWords; ++i)
1286 Remainder->pVal[i] =
1287 uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1288 }
1289 }
1290
1291 // Clean up the memory we allocated.
1292 delete [] U;
1293 delete [] V;
1294 delete [] Q;
1295 delete [] R;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001296}
1297
Zhou Shengff4304f2007-02-09 07:48:24 +00001298/// Unsigned divide this APInt by APInt RHS.
Zhou Sheng0b706b12007-02-08 14:35:19 +00001299/// @brief Unsigned division function for APInt.
Reid Spencere81d2da2007-02-16 22:36:51 +00001300APInt APInt::udiv(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +00001301 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer71bd08f2007-02-17 02:07:07 +00001302
1303 // First, deal with the easy case
1304 if (isSingleWord()) {
1305 assert(RHS.VAL != 0 && "Divide by zero?");
1306 return APInt(BitWidth, VAL / RHS.VAL);
Zhou Sheng0b706b12007-02-08 14:35:19 +00001307 }
Reid Spencer71bd08f2007-02-17 02:07:07 +00001308
Reid Spencer71bd08f2007-02-17 02:07:07 +00001309 // Get some facts about the LHS and RHS number of bits and words
Reid Spenceraf0e9562007-02-18 18:38:44 +00001310 uint32_t rhsBits = RHS.getActiveBits();
1311 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001312 assert(rhsWords && "Divided by zero???");
Reid Spencer9c0696f2007-02-20 08:51:03 +00001313 uint32_t lhsBits = this->getActiveBits();
Reid Spenceraf0e9562007-02-18 18:38:44 +00001314 uint32_t lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001315
Reid Spencer9c0696f2007-02-20 08:51:03 +00001316 // Make a temporary to hold the result
1317 APInt Result(*this);
1318
Reid Spencer71bd08f2007-02-17 02:07:07 +00001319 // Deal with some degenerate cases
1320 if (!lhsWords)
1321 return Result; // 0 / X == 0
Reid Spencer9c0696f2007-02-20 08:51:03 +00001322 else if (lhsWords < rhsWords || Result.ult(RHS)) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001323 // X / Y with X < Y == 0
Reid Spencera58f0582007-02-18 20:09:41 +00001324 memset(Result.pVal, 0, Result.getNumWords() * APINT_WORD_SIZE);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001325 return Result;
1326 } else if (Result == RHS) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001327 // X / X == 1
Reid Spencera58f0582007-02-18 20:09:41 +00001328 memset(Result.pVal, 0, Result.getNumWords() * APINT_WORD_SIZE);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001329 Result.pVal[0] = 1;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001330 return Result;
1331 } else if (lhsWords == 1 && rhsWords == 1) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001332 // All high words are zero, just use native divide
1333 Result.pVal[0] /= RHS.pVal[0];
Reid Spencer9c0696f2007-02-20 08:51:03 +00001334 return Result;
Reid Spencer71bd08f2007-02-17 02:07:07 +00001335 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001336
1337 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1338 APInt Quotient(1,0); // to hold result.
1339 divide(*this, lhsWords, RHS, rhsWords, &Quotient, 0);
1340 return Quotient;
Zhou Sheng0b706b12007-02-08 14:35:19 +00001341}
1342
1343/// Unsigned remainder operation on APInt.
1344/// @brief Function for unsigned remainder operation.
Reid Spencere81d2da2007-02-16 22:36:51 +00001345APInt APInt::urem(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +00001346 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer71bd08f2007-02-17 02:07:07 +00001347 if (isSingleWord()) {
1348 assert(RHS.VAL != 0 && "Remainder by zero?");
1349 return APInt(BitWidth, VAL % RHS.VAL);
Zhou Sheng0b706b12007-02-08 14:35:19 +00001350 }
Reid Spencer71bd08f2007-02-17 02:07:07 +00001351
1352 // Make a temporary to hold the result
1353 APInt Result(*this);
1354
1355 // Get some facts about the RHS
Reid Spenceraf0e9562007-02-18 18:38:44 +00001356 uint32_t rhsBits = RHS.getActiveBits();
1357 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001358 assert(rhsWords && "Performing remainder operation by zero ???");
1359
1360 // Get some facts about the LHS
Reid Spenceraf0e9562007-02-18 18:38:44 +00001361 uint32_t lhsBits = Result.getActiveBits();
1362 uint32_t lhsWords = !lhsBits ? 0 : (Result.whichWord(lhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001363
1364 // Check the degenerate cases
Reid Spencer9c0696f2007-02-20 08:51:03 +00001365 if (lhsWords == 0) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001366 // 0 % Y == 0
Reid Spencera58f0582007-02-18 20:09:41 +00001367 memset(Result.pVal, 0, Result.getNumWords() * APINT_WORD_SIZE);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001368 return Result;
1369 } else if (lhsWords < rhsWords || Result.ult(RHS)) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001370 // X % Y == X iff X < Y
1371 return Result;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001372 } else if (Result == RHS) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001373 // X % X == 0;
Reid Spencera58f0582007-02-18 20:09:41 +00001374 memset(Result.pVal, 0, Result.getNumWords() * APINT_WORD_SIZE);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001375 return Result;
1376 } else if (lhsWords == 1) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001377 // All high words are zero, just use native remainder
1378 Result.pVal[0] %= RHS.pVal[0];
Reid Spencer9c0696f2007-02-20 08:51:03 +00001379 return Result;
Reid Spencer71bd08f2007-02-17 02:07:07 +00001380 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001381
1382 // We have to compute it the hard way. Invoke the Knute divide algorithm.
1383 APInt Remainder(1,0);
1384 divide(*this, lhsWords, RHS, rhsWords, 0, &Remainder);
1385 return Remainder;
Zhou Sheng0b706b12007-02-08 14:35:19 +00001386}
Reid Spencer5e0a8512007-02-17 03:16:00 +00001387
1388/// @brief Converts a char array into an integer.
Reid Spenceraf0e9562007-02-18 18:38:44 +00001389void APInt::fromString(uint32_t numbits, const char *StrStart, uint32_t slen,
Reid Spencer5e0a8512007-02-17 03:16:00 +00001390 uint8_t radix) {
1391 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1392 "Radix should be 2, 8, 10, or 16!");
1393 assert(StrStart && "String is null?");
Reid Spenceraf0e9562007-02-18 18:38:44 +00001394 uint32_t size = 0;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001395 // If the radix is a power of 2, read the input
1396 // from most significant to least significant.
1397 if ((radix & (radix - 1)) == 0) {
Reid Spenceraf0e9562007-02-18 18:38:44 +00001398 uint32_t nextBitPos = 0;
1399 uint32_t bits_per_digit = radix / 8 + 2;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001400 uint64_t resDigit = 0;
1401 BitWidth = slen * bits_per_digit;
1402 if (getNumWords() > 1)
Reid Spenceraf0e9562007-02-18 18:38:44 +00001403 pVal = getMemory(getNumWords());
Reid Spencer5e0a8512007-02-17 03:16:00 +00001404 for (int i = slen - 1; i >= 0; --i) {
Reid Spencer443b5702007-02-18 00:44:22 +00001405 uint64_t digit = StrStart[i] - '0';
Reid Spencer5e0a8512007-02-17 03:16:00 +00001406 resDigit |= digit << nextBitPos;
1407 nextBitPos += bits_per_digit;
Reid Spencer443b5702007-02-18 00:44:22 +00001408 if (nextBitPos >= APINT_BITS_PER_WORD) {
Reid Spencer5e0a8512007-02-17 03:16:00 +00001409 if (isSingleWord()) {
1410 VAL = resDigit;
1411 break;
1412 }
1413 pVal[size++] = resDigit;
Reid Spencer443b5702007-02-18 00:44:22 +00001414 nextBitPos -= APINT_BITS_PER_WORD;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001415 resDigit = digit >> (bits_per_digit - nextBitPos);
1416 }
1417 }
1418 if (!isSingleWord() && size <= getNumWords())
1419 pVal[size] = resDigit;
1420 } else { // General case. The radix is not a power of 2.
1421 // For 10-radix, the max value of 64-bit integer is 18446744073709551615,
1422 // and its digits number is 20.
Reid Spenceraf0e9562007-02-18 18:38:44 +00001423 const uint32_t chars_per_word = 20;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001424 if (slen < chars_per_word ||
1425 (slen == chars_per_word && // In case the value <= 2^64 - 1
1426 strcmp(StrStart, "18446744073709551615") <= 0)) {
Reid Spencer443b5702007-02-18 00:44:22 +00001427 BitWidth = APINT_BITS_PER_WORD;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001428 VAL = strtoull(StrStart, 0, 10);
1429 } else { // In case the value > 2^64 - 1
Reid Spencer443b5702007-02-18 00:44:22 +00001430 BitWidth = (slen / chars_per_word + 1) * APINT_BITS_PER_WORD;
Reid Spenceraf0e9562007-02-18 18:38:44 +00001431 pVal = getClearedMemory(getNumWords());
1432 uint32_t str_pos = 0;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001433 while (str_pos < slen) {
Reid Spenceraf0e9562007-02-18 18:38:44 +00001434 uint32_t chunk = slen - str_pos;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001435 if (chunk > chars_per_word - 1)
1436 chunk = chars_per_word - 1;
Reid Spencer443b5702007-02-18 00:44:22 +00001437 uint64_t resDigit = StrStart[str_pos++] - '0';
Reid Spencer5e0a8512007-02-17 03:16:00 +00001438 uint64_t big_base = radix;
1439 while (--chunk > 0) {
Reid Spencer443b5702007-02-18 00:44:22 +00001440 resDigit = resDigit * radix + StrStart[str_pos++] - '0';
Reid Spencer5e0a8512007-02-17 03:16:00 +00001441 big_base *= radix;
1442 }
1443
1444 uint64_t carry;
1445 if (!size)
1446 carry = resDigit;
1447 else {
1448 carry = mul_1(pVal, pVal, size, big_base);
1449 carry += add_1(pVal, pVal, size, resDigit);
1450 }
1451
1452 if (carry) pVal[size++] = carry;
1453 }
1454 }
1455 }
1456}
Reid Spencer9c0696f2007-02-20 08:51:03 +00001457
1458/// to_string - This function translates the APInt into a string.
1459std::string APInt::toString(uint8_t radix, bool wantSigned) const {
1460 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1461 "Radix should be 2, 8, 10, or 16!");
1462 static const char *digits[] = {
1463 "0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"
1464 };
1465 std::string result;
1466 uint32_t bits_used = getActiveBits();
1467 if (isSingleWord()) {
1468 char buf[65];
1469 const char *format = (radix == 10 ? (wantSigned ? "%lld" : "%llu") :
1470 (radix == 16 ? "%llX" : (radix == 8 ? "%llo" : 0)));
1471 if (format) {
1472 if (wantSigned) {
1473 int64_t sextVal = (int64_t(VAL) << (APINT_BITS_PER_WORD-BitWidth)) >>
1474 (APINT_BITS_PER_WORD-BitWidth);
1475 sprintf(buf, format, sextVal);
1476 } else
1477 sprintf(buf, format, VAL);
1478 } else {
1479 memset(buf, 0, 65);
1480 uint64_t v = VAL;
1481 while (bits_used) {
1482 uint32_t bit = v & 1;
1483 bits_used--;
1484 buf[bits_used] = digits[bit][0];
1485 v >>=1;
1486 }
1487 }
1488 result = buf;
1489 return result;
1490 }
1491
1492 if (radix != 10) {
1493 uint64_t mask = radix - 1;
1494 uint32_t shift = (radix == 16 ? 4 : radix == 8 ? 3 : 1);
1495 uint32_t nibbles = APINT_BITS_PER_WORD / shift;
1496 for (uint32_t i = 0; i < getNumWords(); ++i) {
1497 uint64_t value = pVal[i];
1498 for (uint32_t j = 0; j < nibbles; ++j) {
1499 result.insert(0, digits[ value & mask ]);
1500 value >>= shift;
1501 }
1502 }
1503 return result;
1504 }
1505
1506 APInt tmp(*this);
1507 APInt divisor(4, radix);
1508 APInt zero(tmp.getBitWidth(), 0);
1509 size_t insert_at = 0;
1510 if (wantSigned && tmp[BitWidth-1]) {
1511 // They want to print the signed version and it is a negative value
1512 // Flip the bits and add one to turn it into the equivalent positive
1513 // value and put a '-' in the result.
1514 tmp.flip();
1515 tmp++;
1516 result = "-";
1517 insert_at = 1;
1518 }
1519 if (tmp == 0)
1520 result = "0";
1521 else while (tmp.ne(zero)) {
1522 APInt APdigit(1,0);
1523 divide(tmp, tmp.getNumWords(), divisor, divisor.getNumWords(), 0, &APdigit);
1524 uint32_t digit = APdigit.getValue();
1525 assert(digit < radix && "urem failed");
1526 result.insert(insert_at,digits[digit]);
1527 APInt tmp2(tmp.getBitWidth(), 0);
1528 divide(tmp, tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2, 0);
1529 tmp = tmp2;
1530 }
1531
1532 return result;
1533}
1534