blob: ae7cc439d3d9287bb2dfe51d8e51d5d57713700c [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>
Reid Spencer385f7542007-02-21 03:55:44 +000020#ifndef NDEBUG
21#include <iostream>
22#include <iomanip>
23#endif
24
Zhou Shengfd43dcf2007-02-06 03:00:16 +000025using namespace llvm;
26
Reid Spenceraf0e9562007-02-18 18:38:44 +000027// A utility function for allocating memory, checking for allocation failures,
28// and ensuring the contents is zeroed.
29inline static uint64_t* getClearedMemory(uint32_t numWords) {
30 uint64_t * result = new uint64_t[numWords];
31 assert(result && "APInt memory allocation fails!");
32 memset(result, 0, numWords * sizeof(uint64_t));
33 return result;
Zhou Sheng353815d2007-02-06 06:04:53 +000034}
35
Reid Spenceraf0e9562007-02-18 18:38:44 +000036// A utility function for allocating memory and checking for allocation failure.
37inline static uint64_t* getMemory(uint32_t numWords) {
38 uint64_t * result = new uint64_t[numWords];
39 assert(result && "APInt memory allocation fails!");
40 return result;
41}
42
43APInt::APInt(uint32_t numBits, uint64_t val)
Reid Spencer385f7542007-02-21 03:55:44 +000044 : BitWidth(numBits), VAL(0) {
Reid Spencere81d2da2007-02-16 22:36:51 +000045 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
46 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
Zhou Shengfd43dcf2007-02-06 03:00:16 +000047 if (isSingleWord())
Reid Spencere81d2da2007-02-16 22:36:51 +000048 VAL = val & (~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - BitWidth));
Zhou Shengfd43dcf2007-02-06 03:00:16 +000049 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +000050 pVal = getClearedMemory(getNumWords());
Zhou Shengfd43dcf2007-02-06 03:00:16 +000051 pVal[0] = val;
52 }
53}
54
Reid Spenceraf0e9562007-02-18 18:38:44 +000055APInt::APInt(uint32_t numBits, uint32_t numWords, uint64_t bigVal[])
Reid Spencer385f7542007-02-21 03:55:44 +000056 : BitWidth(numBits), VAL(0) {
Reid Spencere81d2da2007-02-16 22:36:51 +000057 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
58 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
Zhou Shengfd43dcf2007-02-06 03:00:16 +000059 assert(bigVal && "Null pointer detected!");
60 if (isSingleWord())
Reid Spencere81d2da2007-02-16 22:36:51 +000061 VAL = bigVal[0] & (~uint64_t(0ULL) >> (APINT_BITS_PER_WORD - BitWidth));
Zhou Shengfd43dcf2007-02-06 03:00:16 +000062 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +000063 pVal = getMemory(getNumWords());
Zhou Shengfd43dcf2007-02-06 03:00:16 +000064 // Calculate the actual length of bigVal[].
Reid Spenceraf0e9562007-02-18 18:38:44 +000065 uint32_t maxN = std::max<uint32_t>(numWords, getNumWords());
66 uint32_t minN = std::min<uint32_t>(numWords, getNumWords());
Reid Spencera58f0582007-02-18 20:09:41 +000067 memcpy(pVal, bigVal, (minN - 1) * APINT_WORD_SIZE);
Reid Spencer443b5702007-02-18 00:44:22 +000068 pVal[minN-1] = bigVal[minN-1] &
69 (~uint64_t(0ULL) >>
70 (APINT_BITS_PER_WORD - BitWidth % APINT_BITS_PER_WORD));
Zhou Shenga3832fd2007-02-07 06:14:53 +000071 if (maxN == getNumWords())
Reid Spencera58f0582007-02-18 20:09:41 +000072 memset(pVal+numWords, 0, (getNumWords() - numWords) * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +000073 }
74}
75
Zhou Shenga3832fd2007-02-07 06:14:53 +000076/// @brief Create a new APInt by translating the char array represented
77/// integer value.
Reid Spenceraf0e9562007-02-18 18:38:44 +000078APInt::APInt(uint32_t numbits, const char StrStart[], uint32_t slen,
Reid Spencer9c0696f2007-02-20 08:51:03 +000079 uint8_t radix)
Reid Spencer385f7542007-02-21 03:55:44 +000080 : BitWidth(numbits), VAL(0) {
Reid Spencere81d2da2007-02-16 22:36:51 +000081 fromString(numbits, StrStart, slen, radix);
Zhou Shenga3832fd2007-02-07 06:14:53 +000082}
83
84/// @brief Create a new APInt by translating the string represented
85/// integer value.
Reid Spencer9c0696f2007-02-20 08:51:03 +000086APInt::APInt(uint32_t numbits, const std::string& Val, uint8_t radix)
Reid Spencer385f7542007-02-21 03:55:44 +000087 : BitWidth(numbits), VAL(0) {
Zhou Shenga3832fd2007-02-07 06:14:53 +000088 assert(!Val.empty() && "String empty?");
Reid Spencere81d2da2007-02-16 22:36:51 +000089 fromString(numbits, Val.c_str(), Val.size(), radix);
Zhou Shenga3832fd2007-02-07 06:14:53 +000090}
91
Reid Spencera58f0582007-02-18 20:09:41 +000092/// @brief Copy constructor
Reid Spencer54362ca2007-02-20 23:40:25 +000093APInt::APInt(const APInt& that)
Reid Spencer385f7542007-02-21 03:55:44 +000094 : BitWidth(that.BitWidth), VAL(0) {
Reid Spenceraf0e9562007-02-18 18:38:44 +000095 if (isSingleWord())
Reid Spencer54362ca2007-02-20 23:40:25 +000096 VAL = that.VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +000097 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +000098 pVal = getMemory(getNumWords());
Reid Spencer54362ca2007-02-20 23:40:25 +000099 memcpy(pVal, that.pVal, getNumWords() * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000100 }
101}
102
103APInt::~APInt() {
Reid Spencer9c0696f2007-02-20 08:51:03 +0000104 if (!isSingleWord() && pVal)
105 delete[] pVal;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000106}
107
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000108/// @brief Copy assignment operator. Create a new object from the given
109/// APInt one by initialization.
110APInt& APInt::operator=(const APInt& RHS) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000111 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
112 if (isSingleWord())
Reid Spenceraf0e9562007-02-18 18:38:44 +0000113 VAL = RHS.VAL;
114 else
Reid Spencera58f0582007-02-18 20:09:41 +0000115 memcpy(pVal, RHS.pVal, getNumWords() * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000116 return *this;
117}
118
119/// @brief Assignment operator. Assigns a common case integer value to
120/// the APInt.
121APInt& APInt::operator=(uint64_t RHS) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000122 if (isSingleWord())
123 VAL = RHS;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000124 else {
125 pVal[0] = RHS;
Reid Spencera58f0582007-02-18 20:09:41 +0000126 memset(pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000127 }
128 return *this;
129}
130
Reid Spenceraf0e9562007-02-18 18:38:44 +0000131/// add_1 - This function adds a single "digit" integer, y, to the multiple
132/// "digit" integer array, x[]. x[] is modified to reflect the addition and
133/// 1 is returned if there is a carry out, otherwise 0 is returned.
Reid Spencer5e0a8512007-02-17 03:16:00 +0000134/// @returns the carry of the addition.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000135static uint64_t add_1(uint64_t dest[],
136 uint64_t x[], uint32_t len,
137 uint64_t y) {
138 for (uint32_t i = 0; i < len; ++i) {
Reid Spencerf2c521c2007-02-18 06:39:42 +0000139 dest[i] = y + x[i];
140 if (dest[i] < y)
141 y = 1;
142 else {
143 y = 0;
144 break;
145 }
Reid Spencer5e0a8512007-02-17 03:16:00 +0000146 }
Reid Spencerf2c521c2007-02-18 06:39:42 +0000147 return y;
Reid Spencer5e0a8512007-02-17 03:16:00 +0000148}
149
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000150/// @brief Prefix increment operator. Increments the APInt by one.
151APInt& APInt::operator++() {
Reid Spencere81d2da2007-02-16 22:36:51 +0000152 if (isSingleWord())
153 ++VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000154 else
Zhou Shenga3832fd2007-02-07 06:14:53 +0000155 add_1(pVal, pVal, getNumWords(), 1);
Reid Spencere81d2da2007-02-16 22:36:51 +0000156 clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000157 return *this;
158}
159
Reid Spenceraf0e9562007-02-18 18:38:44 +0000160/// sub_1 - This function subtracts a single "digit" (64-bit word), y, from
161/// the multi-digit integer array, x[], propagating the borrowed 1 value until
162/// no further borrowing is neeeded or it runs out of "digits" in x. The result
163/// is 1 if "borrowing" exhausted the digits in x, or 0 if x was not exhausted.
164/// In other words, if y > x then this function returns 1, otherwise 0.
165static uint64_t sub_1(uint64_t x[], uint32_t len,
166 uint64_t y) {
167 for (uint32_t i = 0; i < len; ++i) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000168 uint64_t X = x[i];
Reid Spencerf2c521c2007-02-18 06:39:42 +0000169 x[i] -= y;
170 if (y > X)
Reid Spenceraf0e9562007-02-18 18:38:44 +0000171 y = 1; // We have to "borrow 1" from next "digit"
Reid Spencer5e0a8512007-02-17 03:16:00 +0000172 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000173 y = 0; // No need to borrow
174 break; // Remaining digits are unchanged so exit early
Reid Spencer5e0a8512007-02-17 03:16:00 +0000175 }
176 }
Reid Spencerf2c521c2007-02-18 06:39:42 +0000177 return y;
Reid Spencer5e0a8512007-02-17 03:16:00 +0000178}
179
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000180/// @brief Prefix decrement operator. Decrements the APInt by one.
181APInt& APInt::operator--() {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000182 if (isSingleWord())
183 --VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000184 else
Zhou Shenga3832fd2007-02-07 06:14:53 +0000185 sub_1(pVal, getNumWords(), 1);
Reid Spencere81d2da2007-02-16 22:36:51 +0000186 clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000187 return *this;
188}
189
Reid Spencer5e0a8512007-02-17 03:16:00 +0000190/// add - This function adds the integer array x[] by integer array
191/// y[] and returns the carry.
Reid Spencer385f7542007-02-21 03:55:44 +0000192static uint64_t add(uint64_t dest[], uint64_t x[], uint64_t y[], uint32_t len) {
Reid Spencer54362ca2007-02-20 23:40:25 +0000193 uint64_t carry = 0;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000194 for (uint32_t i = 0; i< len; ++i) {
Reid Spencer54362ca2007-02-20 23:40:25 +0000195 dest[i] = x[i] + y[i] + carry;
Reid Spencer60c0a6a2007-02-21 05:44:56 +0000196 uint64_t limit = std::min(x[i],y[i]);
197 carry = dest[i] < limit || (carry && dest[i] == limit);
Reid Spencer5e0a8512007-02-17 03:16:00 +0000198 }
199 return carry;
200}
201
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000202/// @brief Addition assignment operator. Adds this APInt by the given APInt&
203/// RHS and assigns the result to this APInt.
204APInt& APInt::operator+=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000205 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer54362ca2007-02-20 23:40:25 +0000206 if (isSingleWord())
207 VAL += RHS.VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000208 else {
Reid Spencer54362ca2007-02-20 23:40:25 +0000209 add(pVal, pVal, RHS.pVal, getNumWords());
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000210 }
Reid Spencere81d2da2007-02-16 22:36:51 +0000211 clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000212 return *this;
213}
214
Reid Spencer5e0a8512007-02-17 03:16:00 +0000215/// sub - This function subtracts the integer array x[] by
216/// integer array y[], and returns the borrow-out carry.
Reid Spencer385f7542007-02-21 03:55:44 +0000217static uint64_t sub(uint64_t *dest, const uint64_t *x, const uint64_t *y,
218 uint32_t len) {
219 bool borrow = false;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000220 for (uint32_t i = 0; i < len; ++i) {
Reid Spencer385f7542007-02-21 03:55:44 +0000221 uint64_t x_tmp = borrow ? x[i] - 1 : x[i];
222 borrow = y[i] > x_tmp || (borrow && x[i] == 0);
223 dest[i] = x_tmp - y[i];
Reid Spencer5e0a8512007-02-17 03:16:00 +0000224 }
Reid Spencer54362ca2007-02-20 23:40:25 +0000225 return borrow;
Reid Spencer5e0a8512007-02-17 03:16:00 +0000226}
227
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000228/// @brief Subtraction assignment operator. Subtracts this APInt by the given
229/// APInt &RHS and assigns the result to this APInt.
230APInt& APInt::operator-=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000231 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000232 if (isSingleWord())
Reid Spencer54362ca2007-02-20 23:40:25 +0000233 VAL -= RHS.VAL;
234 else
235 sub(pVal, pVal, RHS.pVal, getNumWords());
Reid Spencere81d2da2007-02-16 22:36:51 +0000236 clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000237 return *this;
238}
239
Reid Spencer5e0a8512007-02-17 03:16:00 +0000240/// mul_1 - This function performs the multiplication operation on a
241/// large integer (represented as an integer array) and a uint64_t integer.
242/// @returns the carry of the multiplication.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000243static uint64_t mul_1(uint64_t dest[],
244 uint64_t x[], uint32_t len,
245 uint64_t y) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000246 // Split y into high 32-bit part and low 32-bit part.
247 uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
248 uint64_t carry = 0, lx, hx;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000249 for (uint32_t i = 0; i < len; ++i) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000250 lx = x[i] & 0xffffffffULL;
251 hx = x[i] >> 32;
252 // hasCarry - A flag to indicate if has carry.
253 // hasCarry == 0, no carry
254 // hasCarry == 1, has carry
255 // hasCarry == 2, no carry and the calculation result == 0.
256 uint8_t hasCarry = 0;
257 dest[i] = carry + lx * ly;
258 // Determine if the add above introduces carry.
259 hasCarry = (dest[i] < carry) ? 1 : 0;
260 carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
261 // The upper limit of carry can be (2^32 - 1)(2^32 - 1) +
262 // (2^32 - 1) + 2^32 = 2^64.
263 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
264
265 carry += (lx * hy) & 0xffffffffULL;
266 dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
267 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) +
268 (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
269 }
270
271 return carry;
272}
273
274/// mul - This function multiplies integer array x[] by integer array y[] and
275/// stores the result into integer array dest[].
276/// Note the array dest[]'s size should no less than xlen + ylen.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000277static void mul(uint64_t dest[], uint64_t x[], uint32_t xlen,
278 uint64_t y[], uint32_t ylen) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000279 dest[xlen] = mul_1(dest, x, xlen, y[0]);
280
Reid Spenceraf0e9562007-02-18 18:38:44 +0000281 for (uint32_t i = 1; i < ylen; ++i) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000282 uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
283 uint64_t carry = 0, lx, hx;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000284 for (uint32_t j = 0; j < xlen; ++j) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000285 lx = x[j] & 0xffffffffULL;
286 hx = x[j] >> 32;
287 // hasCarry - A flag to indicate if has carry.
288 // hasCarry == 0, no carry
289 // hasCarry == 1, has carry
290 // hasCarry == 2, no carry and the calculation result == 0.
291 uint8_t hasCarry = 0;
292 uint64_t resul = carry + lx * ly;
293 hasCarry = (resul < carry) ? 1 : 0;
294 carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
295 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
296
297 carry += (lx * hy) & 0xffffffffULL;
298 resul = (carry << 32) | (resul & 0xffffffffULL);
299 dest[i+j] += resul;
300 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
301 (carry >> 32) + (dest[i+j] < resul ? 1 : 0) +
302 ((lx * hy) >> 32) + hx * hy;
303 }
304 dest[i+xlen] = carry;
305 }
306}
307
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000308/// @brief Multiplication assignment operator. Multiplies this APInt by the
309/// given APInt& RHS and assigns the result to this APInt.
310APInt& APInt::operator*=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000311 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer54362ca2007-02-20 23:40:25 +0000312 if (isSingleWord())
Reid Spencer61eb1802007-02-20 20:42:10 +0000313 VAL *= RHS.VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000314 else {
315 // one-based first non-zero bit position.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000316 uint32_t first = getActiveBits();
317 uint32_t xlen = !first ? 0 : whichWord(first - 1) + 1;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000318 if (!xlen)
319 return *this;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000320 else {
Reid Spencere81d2da2007-02-16 22:36:51 +0000321 first = RHS.getActiveBits();
Reid Spenceraf0e9562007-02-18 18:38:44 +0000322 uint32_t ylen = !first ? 0 : whichWord(first - 1) + 1;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000323 if (!ylen) {
Reid Spencera58f0582007-02-18 20:09:41 +0000324 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000325 return *this;
326 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000327 uint64_t *dest = getMemory(xlen+ylen);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000328 mul(dest, pVal, xlen, RHS.pVal, ylen);
Zhou Shenga3832fd2007-02-07 06:14:53 +0000329 memcpy(pVal, dest, ((xlen + ylen >= getNumWords()) ?
Reid Spencera58f0582007-02-18 20:09:41 +0000330 getNumWords() : xlen + ylen) * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000331 delete[] dest;
332 }
333 }
Reid Spencere81d2da2007-02-16 22:36:51 +0000334 clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000335 return *this;
336}
337
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000338/// @brief Bitwise AND assignment operator. Performs bitwise AND operation on
339/// this APInt and the given APInt& RHS, assigns the result to this APInt.
340APInt& APInt::operator&=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000341 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000342 if (isSingleWord()) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000343 VAL &= RHS.VAL;
344 return *this;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000345 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000346 uint32_t numWords = getNumWords();
347 for (uint32_t i = 0; i < numWords; ++i)
348 pVal[i] &= RHS.pVal[i];
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000349 return *this;
350}
351
352/// @brief Bitwise OR assignment operator. Performs bitwise OR operation on
353/// this APInt and the given APInt& RHS, assigns the result to this APInt.
354APInt& APInt::operator|=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000355 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000356 if (isSingleWord()) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000357 VAL |= RHS.VAL;
358 return *this;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000359 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000360 uint32_t numWords = getNumWords();
361 for (uint32_t i = 0; i < numWords; ++i)
362 pVal[i] |= RHS.pVal[i];
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000363 return *this;
364}
365
366/// @brief Bitwise XOR assignment operator. Performs bitwise XOR operation on
367/// this APInt and the given APInt& RHS, assigns the result to this APInt.
368APInt& APInt::operator^=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000369 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000370 if (isSingleWord()) {
Reid Spencerf2c521c2007-02-18 06:39:42 +0000371 VAL ^= RHS.VAL;
Reid Spencer54362ca2007-02-20 23:40:25 +0000372 this->clearUnusedBits();
Reid Spencerf2c521c2007-02-18 06:39:42 +0000373 return *this;
374 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000375 uint32_t numWords = getNumWords();
376 for (uint32_t i = 0; i < numWords; ++i)
377 pVal[i] ^= RHS.pVal[i];
Reid Spencer54362ca2007-02-20 23:40:25 +0000378 this->clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000379 return *this;
380}
381
382/// @brief Bitwise AND operator. Performs bitwise AND operation on this APInt
383/// and the given APInt& RHS.
384APInt APInt::operator&(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000385 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spenceraf0e9562007-02-18 18:38:44 +0000386 if (isSingleWord())
387 return APInt(getBitWidth(), VAL & RHS.VAL);
388
389 APInt Result(*this);
390 uint32_t numWords = getNumWords();
391 for (uint32_t i = 0; i < numWords; ++i)
392 Result.pVal[i] &= RHS.pVal[i];
393 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000394}
395
396/// @brief Bitwise OR operator. Performs bitwise OR operation on this APInt
397/// and the given APInt& RHS.
398APInt APInt::operator|(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000399 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spenceraf0e9562007-02-18 18:38:44 +0000400 if (isSingleWord())
401 return APInt(getBitWidth(), VAL | RHS.VAL);
Reid Spencer54362ca2007-02-20 23:40:25 +0000402
Reid Spenceraf0e9562007-02-18 18:38:44 +0000403 APInt Result(*this);
404 uint32_t numWords = getNumWords();
405 for (uint32_t i = 0; i < numWords; ++i)
406 Result.pVal[i] |= RHS.pVal[i];
407 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000408}
409
410/// @brief Bitwise XOR operator. Performs bitwise XOR operation on this APInt
411/// and the given APInt& RHS.
412APInt APInt::operator^(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000413 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer54362ca2007-02-20 23:40:25 +0000414 if (isSingleWord()) {
415 APInt Result(BitWidth, VAL ^ RHS.VAL);
416 Result.clearUnusedBits();
417 return Result;
418 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000419 APInt Result(*this);
420 uint32_t numWords = getNumWords();
421 for (uint32_t i = 0; i < numWords; ++i)
422 Result.pVal[i] ^= RHS.pVal[i];
423 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000424}
425
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000426/// @brief Logical negation operator. Performs logical negation operation on
427/// this APInt.
428bool APInt::operator !() const {
429 if (isSingleWord())
430 return !VAL;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000431
432 for (uint32_t i = 0; i < getNumWords(); ++i)
433 if (pVal[i])
434 return false;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000435 return true;
436}
437
438/// @brief Multiplication operator. Multiplies this APInt by the given APInt&
439/// RHS.
440APInt APInt::operator*(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000441 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer54362ca2007-02-20 23:40:25 +0000442 if (isSingleWord()) {
443 APInt Result(BitWidth, VAL * RHS.VAL);
444 Result.clearUnusedBits();
445 return Result;
446 }
Reid Spencer61eb1802007-02-20 20:42:10 +0000447 APInt Result(*this);
448 Result *= RHS;
449 Result.clearUnusedBits();
450 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000451}
452
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000453/// @brief Addition operator. Adds this APInt by the given APInt& RHS.
454APInt APInt::operator+(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000455 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer54362ca2007-02-20 23:40:25 +0000456 if (isSingleWord()) {
457 APInt Result(BitWidth, VAL + RHS.VAL);
458 Result.clearUnusedBits();
459 return Result;
460 }
461 APInt Result(BitWidth, 0);
462 add(Result.pVal, this->pVal, RHS.pVal, getNumWords());
463 Result.clearUnusedBits();
464 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000465}
466
467/// @brief Subtraction operator. Subtracts this APInt by the given APInt& RHS
468APInt APInt::operator-(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000469 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer54362ca2007-02-20 23:40:25 +0000470 if (isSingleWord()) {
471 APInt Result(BitWidth, VAL - RHS.VAL);
472 Result.clearUnusedBits();
473 return Result;
474 }
475 APInt Result(BitWidth, 0);
476 sub(Result.pVal, this->pVal, RHS.pVal, getNumWords());
477 Result.clearUnusedBits();
478 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000479}
480
481/// @brief Array-indexing support.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000482bool APInt::operator[](uint32_t bitPosition) const {
Zhou Shengff4304f2007-02-09 07:48:24 +0000483 return (maskBit(bitPosition) & (isSingleWord() ?
484 VAL : pVal[whichWord(bitPosition)])) != 0;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000485}
486
487/// @brief Equality operator. Compare this APInt with the given APInt& RHS
488/// for the validity of the equality relationship.
489bool APInt::operator==(const APInt& RHS) const {
Reid Spencer54362ca2007-02-20 23:40:25 +0000490 if (isSingleWord())
491 return VAL == RHS.VAL;
492
Reid Spenceraf0e9562007-02-18 18:38:44 +0000493 uint32_t n1 = getActiveBits();
494 uint32_t n2 = RHS.getActiveBits();
Reid Spencer54362ca2007-02-20 23:40:25 +0000495 if (n1 != n2)
496 return false;
497
498 if (n1 <= APINT_BITS_PER_WORD)
499 return pVal[0] == RHS.pVal[0];
500
501 for (int i = whichWord(n1 - 1); i >= 0; --i)
502 if (pVal[i] != RHS.pVal[i])
503 return false;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000504 return true;
505}
506
Zhou Shenga3832fd2007-02-07 06:14:53 +0000507/// @brief Equality operator. Compare this APInt with the given uint64_t value
508/// for the validity of the equality relationship.
509bool APInt::operator==(uint64_t Val) const {
510 if (isSingleWord())
511 return VAL == Val;
Reid Spencer54362ca2007-02-20 23:40:25 +0000512
513 uint32_t n = getActiveBits();
514 if (n <= APINT_BITS_PER_WORD)
515 return pVal[0] == Val;
516 else
517 return false;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000518}
519
Reid Spencere81d2da2007-02-16 22:36:51 +0000520/// @brief Unsigned less than comparison
521bool APInt::ult(const APInt& RHS) const {
522 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
523 if (isSingleWord())
524 return VAL < RHS.VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000525 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000526 uint32_t n1 = getActiveBits();
527 uint32_t n2 = RHS.getActiveBits();
Reid Spencere81d2da2007-02-16 22:36:51 +0000528 if (n1 < n2)
529 return true;
530 else if (n2 < n1)
531 return false;
Reid Spencer443b5702007-02-18 00:44:22 +0000532 else if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
Reid Spencere81d2da2007-02-16 22:36:51 +0000533 return pVal[0] < RHS.pVal[0];
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000534 for (int i = whichWord(n1 - 1); i >= 0; --i) {
535 if (pVal[i] > RHS.pVal[i]) return false;
536 else if (pVal[i] < RHS.pVal[i]) return true;
537 }
538 }
539 return false;
540}
541
Reid Spencere81d2da2007-02-16 22:36:51 +0000542/// @brief Signed less than comparison
543bool APInt::slt(const APInt& RHS) const {
544 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
Reid Spencera58f0582007-02-18 20:09:41 +0000545 if (isSingleWord()) {
546 int64_t lhsSext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
547 int64_t rhsSext = (int64_t(RHS.VAL) << (64-BitWidth)) >> (64-BitWidth);
548 return lhsSext < rhsSext;
Reid Spencere81d2da2007-02-16 22:36:51 +0000549 }
Reid Spencera58f0582007-02-18 20:09:41 +0000550
551 APInt lhs(*this);
552 APInt rhs(*this);
553 bool lhsNegative = false;
554 bool rhsNegative = false;
555 if (lhs[BitWidth-1]) {
556 lhsNegative = true;
557 lhs.flip();
558 lhs++;
559 }
560 if (rhs[BitWidth-1]) {
561 rhsNegative = true;
562 rhs.flip();
563 rhs++;
564 }
565 if (lhsNegative)
566 if (rhsNegative)
567 return !lhs.ult(rhs);
568 else
569 return true;
570 else if (rhsNegative)
571 return false;
572 else
573 return lhs.ult(rhs);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000574}
575
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000576/// Set the given bit to 1 whose poition is given as "bitPosition".
577/// @brief Set a given bit to 1.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000578APInt& APInt::set(uint32_t bitPosition) {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000579 if (isSingleWord()) VAL |= maskBit(bitPosition);
580 else pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
581 return *this;
582}
583
584/// @brief Set every bit to 1.
585APInt& APInt::set() {
Reid Spencer443b5702007-02-18 00:44:22 +0000586 if (isSingleWord())
587 VAL = ~0ULL >> (APINT_BITS_PER_WORD - BitWidth);
Zhou Shengb04973e2007-02-15 06:36:31 +0000588 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000589 for (uint32_t i = 0; i < getNumWords() - 1; ++i)
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000590 pVal[i] = -1ULL;
Reid Spencer443b5702007-02-18 00:44:22 +0000591 pVal[getNumWords() - 1] = ~0ULL >>
592 (APINT_BITS_PER_WORD - BitWidth % APINT_BITS_PER_WORD);
Zhou Shengb04973e2007-02-15 06:36:31 +0000593 }
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000594 return *this;
595}
596
597/// Set the given bit to 0 whose position is given as "bitPosition".
598/// @brief Set a given bit to 0.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000599APInt& APInt::clear(uint32_t bitPosition) {
600 if (isSingleWord())
601 VAL &= ~maskBit(bitPosition);
602 else
603 pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000604 return *this;
605}
606
607/// @brief Set every bit to 0.
608APInt& APInt::clear() {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000609 if (isSingleWord())
610 VAL = 0;
Zhou Shenga3832fd2007-02-07 06:14:53 +0000611 else
Reid Spencera58f0582007-02-18 20:09:41 +0000612 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000613 return *this;
614}
615
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000616/// @brief Bitwise NOT operator. Performs a bitwise logical NOT operation on
617/// this APInt.
618APInt APInt::operator~() const {
619 APInt API(*this);
620 API.flip();
621 return API;
622}
623
624/// @brief Toggle every bit to its opposite value.
625APInt& APInt::flip() {
Reid Spencer443b5702007-02-18 00:44:22 +0000626 if (isSingleWord()) VAL = (~(VAL <<
627 (APINT_BITS_PER_WORD - BitWidth))) >> (APINT_BITS_PER_WORD - BitWidth);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000628 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000629 uint32_t i = 0;
Zhou Shenga3832fd2007-02-07 06:14:53 +0000630 for (; i < getNumWords() - 1; ++i)
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000631 pVal[i] = ~pVal[i];
Reid Spenceraf0e9562007-02-18 18:38:44 +0000632 uint32_t offset =
Reid Spencer443b5702007-02-18 00:44:22 +0000633 APINT_BITS_PER_WORD - (BitWidth - APINT_BITS_PER_WORD * (i - 1));
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000634 pVal[i] = (~(pVal[i] << offset)) >> offset;
635 }
636 return *this;
637}
638
639/// Toggle a given bit to its opposite value whose position is given
640/// as "bitPosition".
641/// @brief Toggles a given bit to its opposite value.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000642APInt& APInt::flip(uint32_t bitPosition) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000643 assert(bitPosition < BitWidth && "Out of the bit-width range!");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000644 if ((*this)[bitPosition]) clear(bitPosition);
645 else set(bitPosition);
646 return *this;
647}
648
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000649/// getMaxValue - This function returns the largest value
650/// for an APInt of the specified bit-width and if isSign == true,
651/// it should be largest signed value, otherwise unsigned value.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000652APInt APInt::getMaxValue(uint32_t numBits, bool isSign) {
Reid Spencerf99a0ac2007-02-18 22:29:05 +0000653 APInt Result(numBits, 0);
654 Result.set();
655 if (isSign)
656 Result.clear(numBits - 1);
657 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000658}
659
660/// getMinValue - This function returns the smallest value for
661/// an APInt of the given bit-width and if isSign == true,
662/// it should be smallest signed value, otherwise zero.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000663APInt APInt::getMinValue(uint32_t numBits, bool isSign) {
Reid Spencerf99a0ac2007-02-18 22:29:05 +0000664 APInt Result(numBits, 0);
665 if (isSign)
666 Result.set(numBits - 1);
667 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000668}
669
670/// getAllOnesValue - This function returns an all-ones value for
671/// an APInt of the specified bit-width.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000672APInt APInt::getAllOnesValue(uint32_t numBits) {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000673 return getMaxValue(numBits, false);
674}
675
676/// getNullValue - This function creates an '0' value for an
677/// APInt of the specified bit-width.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000678APInt APInt::getNullValue(uint32_t numBits) {
Zhou Shengb04973e2007-02-15 06:36:31 +0000679 return getMinValue(numBits, false);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000680}
681
682/// HiBits - This function returns the high "numBits" bits of this APInt.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000683APInt APInt::getHiBits(uint32_t numBits) const {
Reid Spencere81d2da2007-02-16 22:36:51 +0000684 return APIntOps::lshr(*this, BitWidth - numBits);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000685}
686
687/// LoBits - This function returns the low "numBits" bits of this APInt.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000688APInt APInt::getLoBits(uint32_t numBits) const {
Reid Spencere81d2da2007-02-16 22:36:51 +0000689 return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits),
690 BitWidth - numBits);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000691}
692
Reid Spencere81d2da2007-02-16 22:36:51 +0000693bool APInt::isPowerOf2() const {
694 return (!!*this) && !(*this & (*this - APInt(BitWidth,1)));
695}
696
697/// countLeadingZeros - This function is a APInt version corresponding to
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000698/// llvm/include/llvm/Support/MathExtras.h's function
Reid Spencere81d2da2007-02-16 22:36:51 +0000699/// countLeadingZeros_{32, 64}. It performs platform optimal form of counting
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000700/// the number of zeros from the most significant bit to the first one bit.
701/// @returns numWord() * 64 if the value is zero.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000702uint32_t APInt::countLeadingZeros() const {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000703 uint32_t Count = 0;
Reid Spencere549c492007-02-21 00:29:48 +0000704 if (isSingleWord())
705 Count = CountLeadingZeros_64(VAL);
706 else {
707 for (uint32_t i = getNumWords(); i > 0u; --i) {
708 if (pVal[i-1] == 0)
709 Count += APINT_BITS_PER_WORD;
710 else {
711 Count += CountLeadingZeros_64(pVal[i-1]);
712 break;
713 }
714 }
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000715 }
Reid Spencere549c492007-02-21 00:29:48 +0000716 return Count - (APINT_BITS_PER_WORD - (BitWidth % APINT_BITS_PER_WORD));
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000717}
718
Reid Spencere81d2da2007-02-16 22:36:51 +0000719/// countTrailingZeros - This function is a APInt version corresponding to
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000720/// llvm/include/llvm/Support/MathExtras.h's function
Reid Spencere81d2da2007-02-16 22:36:51 +0000721/// countTrailingZeros_{32, 64}. It performs platform optimal form of counting
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000722/// the number of zeros from the least significant bit to the first one bit.
723/// @returns numWord() * 64 if the value is zero.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000724uint32_t APInt::countTrailingZeros() const {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000725 if (isSingleWord())
Reid Spencer443b5702007-02-18 00:44:22 +0000726 return CountTrailingZeros_64(VAL);
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000727 APInt Tmp( ~(*this) & ((*this) - APInt(BitWidth,1)) );
Reid Spencere81d2da2007-02-16 22:36:51 +0000728 return getNumWords() * APINT_BITS_PER_WORD - Tmp.countLeadingZeros();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000729}
730
Reid Spencere81d2da2007-02-16 22:36:51 +0000731/// countPopulation - This function is a APInt version corresponding to
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000732/// llvm/include/llvm/Support/MathExtras.h's function
Reid Spencere81d2da2007-02-16 22:36:51 +0000733/// countPopulation_{32, 64}. It counts the number of set bits in a value.
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000734/// @returns 0 if the value is zero.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000735uint32_t APInt::countPopulation() const {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000736 if (isSingleWord())
737 return CountPopulation_64(VAL);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000738 uint32_t Count = 0;
739 for (uint32_t i = 0; i < getNumWords(); ++i)
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000740 Count += CountPopulation_64(pVal[i]);
741 return Count;
742}
743
744
Reid Spencere81d2da2007-02-16 22:36:51 +0000745/// byteSwap - This function returns a byte-swapped representation of the
Zhou Shengff4304f2007-02-09 07:48:24 +0000746/// this APInt.
Reid Spencere81d2da2007-02-16 22:36:51 +0000747APInt APInt::byteSwap() const {
748 assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
749 if (BitWidth == 16)
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000750 return APInt(BitWidth, ByteSwap_16(VAL));
Reid Spencere81d2da2007-02-16 22:36:51 +0000751 else if (BitWidth == 32)
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000752 return APInt(BitWidth, ByteSwap_32(VAL));
Reid Spencere81d2da2007-02-16 22:36:51 +0000753 else if (BitWidth == 48) {
Zhou Shengb04973e2007-02-15 06:36:31 +0000754 uint64_t Tmp1 = ((VAL >> 32) << 16) | (VAL & 0xFFFF);
755 Tmp1 = ByteSwap_32(Tmp1);
756 uint64_t Tmp2 = (VAL >> 16) & 0xFFFF;
757 Tmp2 = ByteSwap_16(Tmp2);
758 return
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000759 APInt(BitWidth,
760 (Tmp1 & 0xff) | ((Tmp1<<16) & 0xffff00000000ULL) | (Tmp2 << 16));
Reid Spencere81d2da2007-02-16 22:36:51 +0000761 } else if (BitWidth == 64)
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000762 return APInt(BitWidth, ByteSwap_64(VAL));
Zhou Shengb04973e2007-02-15 06:36:31 +0000763 else {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000764 APInt Result(BitWidth, 0);
Zhou Shengb04973e2007-02-15 06:36:31 +0000765 char *pByte = (char*)Result.pVal;
Reid Spencera58f0582007-02-18 20:09:41 +0000766 for (uint32_t i = 0; i < BitWidth / APINT_WORD_SIZE / 2; ++i) {
Zhou Shengb04973e2007-02-15 06:36:31 +0000767 char Tmp = pByte[i];
Reid Spencera58f0582007-02-18 20:09:41 +0000768 pByte[i] = pByte[BitWidth / APINT_WORD_SIZE - 1 - i];
769 pByte[BitWidth / APINT_WORD_SIZE - i - 1] = Tmp;
Zhou Shengb04973e2007-02-15 06:36:31 +0000770 }
771 return Result;
772 }
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000773}
774
775/// GreatestCommonDivisor - This function returns the greatest common
776/// divisor of the two APInt values using Enclid's algorithm.
Zhou Sheng0b706b12007-02-08 14:35:19 +0000777APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1,
778 const APInt& API2) {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000779 APInt A = API1, B = API2;
780 while (!!B) {
781 APInt T = B;
Reid Spencere81d2da2007-02-16 22:36:51 +0000782 B = APIntOps::urem(A, B);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000783 A = T;
784 }
785 return A;
786}
Chris Lattner6ad4c142007-02-06 05:38:37 +0000787
Zhou Shengd93f00c2007-02-12 20:02:55 +0000788/// DoubleRoundToAPInt - This function convert a double value to
789/// a APInt value.
Reid Spencere81d2da2007-02-16 22:36:51 +0000790APInt llvm::APIntOps::RoundDoubleToAPInt(double Double) {
Zhou Shengd93f00c2007-02-12 20:02:55 +0000791 union {
792 double D;
793 uint64_t I;
794 } T;
795 T.D = Double;
796 bool isNeg = T.I >> 63;
797 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
798 if (exp < 0)
Reid Spencere81d2da2007-02-16 22:36:51 +0000799 return APInt(64ull, 0u);
Zhou Shengd93f00c2007-02-12 20:02:55 +0000800 uint64_t mantissa = ((T.I << 12) >> 12) | (1ULL << 52);
801 if (exp < 52)
Reid Spencere81d2da2007-02-16 22:36:51 +0000802 return isNeg ? -APInt(64u, mantissa >> (52 - exp)) :
803 APInt(64u, mantissa >> (52 - exp));
804 APInt Tmp(exp + 1, mantissa);
805 Tmp = Tmp.shl(exp - 52);
Zhou Shengd93f00c2007-02-12 20:02:55 +0000806 return isNeg ? -Tmp : Tmp;
807}
808
Reid Spencerdb3faa62007-02-13 22:41:58 +0000809/// RoundToDouble - This function convert this APInt to a double.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000810/// The layout for double is as following (IEEE Standard 754):
811/// --------------------------------------
812/// | Sign Exponent Fraction Bias |
813/// |-------------------------------------- |
814/// | 1[63] 11[62-52] 52[51-00] 1023 |
815/// --------------------------------------
Reid Spencere81d2da2007-02-16 22:36:51 +0000816double APInt::roundToDouble(bool isSigned) const {
Reid Spencer9c0696f2007-02-20 08:51:03 +0000817
818 // Handle the simple case where the value is contained in one uint64_t.
Reid Spencera58f0582007-02-18 20:09:41 +0000819 if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
820 if (isSigned) {
821 int64_t sext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
822 return double(sext);
823 } else
824 return double(VAL);
825 }
826
Reid Spencer9c0696f2007-02-20 08:51:03 +0000827 // Determine if the value is negative.
Reid Spencere81d2da2007-02-16 22:36:51 +0000828 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
Reid Spencer9c0696f2007-02-20 08:51:03 +0000829
830 // Construct the absolute value if we're negative.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000831 APInt Tmp(isNeg ? -(*this) : (*this));
Reid Spencer9c0696f2007-02-20 08:51:03 +0000832
833 // Figure out how many bits we're using.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000834 uint32_t n = Tmp.getActiveBits();
Zhou Shengd93f00c2007-02-12 20:02:55 +0000835
Reid Spencer9c0696f2007-02-20 08:51:03 +0000836 // The exponent (without bias normalization) is just the number of bits
837 // we are using. Note that the sign bit is gone since we constructed the
838 // absolute value.
839 uint64_t exp = n;
Zhou Shengd93f00c2007-02-12 20:02:55 +0000840
Reid Spencer9c0696f2007-02-20 08:51:03 +0000841 // Return infinity for exponent overflow
842 if (exp > 1023) {
843 if (!isSigned || !isNeg)
Reid Spencer61eb1802007-02-20 20:42:10 +0000844 return double(1.0E300 * 1.0E300); // positive infinity
Reid Spencer9c0696f2007-02-20 08:51:03 +0000845 else
Reid Spencer61eb1802007-02-20 20:42:10 +0000846 return double(-1.0E300 * 1.0E300); // negative infinity
Reid Spencer9c0696f2007-02-20 08:51:03 +0000847 }
848 exp += 1023; // Increment for 1023 bias
849
850 // Number of bits in mantissa is 52. To obtain the mantissa value, we must
851 // extract the high 52 bits from the correct words in pVal.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000852 uint64_t mantissa;
Reid Spencer9c0696f2007-02-20 08:51:03 +0000853 unsigned hiWord = whichWord(n-1);
854 if (hiWord == 0) {
855 mantissa = Tmp.pVal[0];
856 if (n > 52)
857 mantissa >>= n - 52; // shift down, we want the top 52 bits.
858 } else {
859 assert(hiWord > 0 && "huh?");
860 uint64_t hibits = Tmp.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
861 uint64_t lobits = Tmp.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
862 mantissa = hibits | lobits;
863 }
864
Zhou Shengd93f00c2007-02-12 20:02:55 +0000865 // The leading bit of mantissa is implicit, so get rid of it.
Reid Spencer443b5702007-02-18 00:44:22 +0000866 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
Zhou Shengd93f00c2007-02-12 20:02:55 +0000867 union {
868 double D;
869 uint64_t I;
870 } T;
871 T.I = sign | (exp << 52) | mantissa;
872 return T.D;
873}
874
Reid Spencere81d2da2007-02-16 22:36:51 +0000875// Truncate to new width.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000876void APInt::trunc(uint32_t width) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000877 assert(width < BitWidth && "Invalid APInt Truncate request");
878}
879
880// Sign extend to a new width.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000881void APInt::sext(uint32_t width) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000882 assert(width > BitWidth && "Invalid APInt SignExtend request");
883}
884
885// Zero extend to a new width.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000886void APInt::zext(uint32_t width) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000887 assert(width > BitWidth && "Invalid APInt ZeroExtend request");
888}
889
Zhou Shengff4304f2007-02-09 07:48:24 +0000890/// Arithmetic right-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +0000891/// @brief Arithmetic right-shift function.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000892APInt APInt::ashr(uint32_t shiftAmt) const {
Zhou Shengff4304f2007-02-09 07:48:24 +0000893 APInt API(*this);
Zhou Sheng0b706b12007-02-08 14:35:19 +0000894 if (API.isSingleWord())
Reid Spencer443b5702007-02-18 00:44:22 +0000895 API.VAL =
896 (((int64_t(API.VAL) << (APINT_BITS_PER_WORD - API.BitWidth)) >>
897 (APINT_BITS_PER_WORD - API.BitWidth)) >> shiftAmt) &
898 (~uint64_t(0UL) >> (APINT_BITS_PER_WORD - API.BitWidth));
Zhou Sheng0b706b12007-02-08 14:35:19 +0000899 else {
Reid Spencere81d2da2007-02-16 22:36:51 +0000900 if (shiftAmt >= API.BitWidth) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000901 memset(API.pVal, API[API.BitWidth-1] ? 1 : 0,
Reid Spencera58f0582007-02-18 20:09:41 +0000902 (API.getNumWords()-1) * APINT_WORD_SIZE);
Reid Spencer443b5702007-02-18 00:44:22 +0000903 API.pVal[API.getNumWords() - 1] =
904 ~uint64_t(0UL) >>
905 (APINT_BITS_PER_WORD - API.BitWidth % APINT_BITS_PER_WORD);
Zhou Sheng0b706b12007-02-08 14:35:19 +0000906 } else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000907 uint32_t i = 0;
Reid Spencere81d2da2007-02-16 22:36:51 +0000908 for (; i < API.BitWidth - shiftAmt; ++i)
Zhou Sheng0b706b12007-02-08 14:35:19 +0000909 if (API[i+shiftAmt])
910 API.set(i);
911 else
912 API.clear(i);
Reid Spencere81d2da2007-02-16 22:36:51 +0000913 for (; i < API.BitWidth; ++i)
914 if (API[API.BitWidth-1])
Zhou Shengb04973e2007-02-15 06:36:31 +0000915 API.set(i);
916 else API.clear(i);
Zhou Sheng0b706b12007-02-08 14:35:19 +0000917 }
918 }
919 return API;
920}
921
Zhou Shengff4304f2007-02-09 07:48:24 +0000922/// Logical right-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +0000923/// @brief Logical right-shift function.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000924APInt APInt::lshr(uint32_t shiftAmt) const {
Zhou Shengff4304f2007-02-09 07:48:24 +0000925 APInt API(*this);
Zhou Sheng0b706b12007-02-08 14:35:19 +0000926 if (API.isSingleWord())
927 API.VAL >>= shiftAmt;
928 else {
Reid Spencere81d2da2007-02-16 22:36:51 +0000929 if (shiftAmt >= API.BitWidth)
Reid Spencera58f0582007-02-18 20:09:41 +0000930 memset(API.pVal, 0, API.getNumWords() * APINT_WORD_SIZE);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000931 uint32_t i = 0;
Reid Spencere81d2da2007-02-16 22:36:51 +0000932 for (i = 0; i < API.BitWidth - shiftAmt; ++i)
Zhou Sheng0b706b12007-02-08 14:35:19 +0000933 if (API[i+shiftAmt]) API.set(i);
934 else API.clear(i);
Reid Spencere81d2da2007-02-16 22:36:51 +0000935 for (; i < API.BitWidth; ++i)
Zhou Sheng0b706b12007-02-08 14:35:19 +0000936 API.clear(i);
937 }
938 return API;
939}
940
Zhou Shengff4304f2007-02-09 07:48:24 +0000941/// Left-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +0000942/// @brief Left-shift function.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000943APInt APInt::shl(uint32_t shiftAmt) const {
Zhou Shengff4304f2007-02-09 07:48:24 +0000944 APInt API(*this);
Zhou Shengd93f00c2007-02-12 20:02:55 +0000945 if (API.isSingleWord())
946 API.VAL <<= shiftAmt;
Reid Spencere81d2da2007-02-16 22:36:51 +0000947 else if (shiftAmt >= API.BitWidth)
Reid Spencera58f0582007-02-18 20:09:41 +0000948 memset(API.pVal, 0, API.getNumWords() * APINT_WORD_SIZE);
Zhou Shengd93f00c2007-02-12 20:02:55 +0000949 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000950 if (uint32_t offset = shiftAmt / APINT_BITS_PER_WORD) {
951 for (uint32_t i = API.getNumWords() - 1; i > offset - 1; --i)
Zhou Shengd93f00c2007-02-12 20:02:55 +0000952 API.pVal[i] = API.pVal[i-offset];
Reid Spencera58f0582007-02-18 20:09:41 +0000953 memset(API.pVal, 0, offset * APINT_WORD_SIZE);
Zhou Sheng0b706b12007-02-08 14:35:19 +0000954 }
Reid Spencer443b5702007-02-18 00:44:22 +0000955 shiftAmt %= APINT_BITS_PER_WORD;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000956 uint32_t i;
Zhou Shengd93f00c2007-02-12 20:02:55 +0000957 for (i = API.getNumWords() - 1; i > 0; --i)
958 API.pVal[i] = (API.pVal[i] << shiftAmt) |
Reid Spencer443b5702007-02-18 00:44:22 +0000959 (API.pVal[i-1] >> (APINT_BITS_PER_WORD - shiftAmt));
Zhou Shengd93f00c2007-02-12 20:02:55 +0000960 API.pVal[i] <<= shiftAmt;
Zhou Sheng0b706b12007-02-08 14:35:19 +0000961 }
Reid Spencere81d2da2007-02-16 22:36:51 +0000962 API.clearUnusedBits();
Zhou Sheng0b706b12007-02-08 14:35:19 +0000963 return API;
964}
965
Reid Spencer9c0696f2007-02-20 08:51:03 +0000966#if 0
Reid Spencer5e0a8512007-02-17 03:16:00 +0000967/// subMul - This function substracts x[len-1:0] * y from
968/// dest[offset+len-1:offset], and returns the most significant
969/// word of the product, minus the borrow-out from the subtraction.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000970static uint32_t subMul(uint32_t dest[], uint32_t offset,
971 uint32_t x[], uint32_t len, uint32_t y) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000972 uint64_t yl = (uint64_t) y & 0xffffffffL;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000973 uint32_t carry = 0;
974 uint32_t j = 0;
Reid Spencer5e0a8512007-02-17 03:16:00 +0000975 do {
Reid Spencerc72f2802007-02-17 22:38:07 +0000976 uint64_t prod = ((uint64_t) x[j] & 0xffffffffUL) * yl;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000977 uint32_t prod_low = (uint32_t) prod;
978 uint32_t prod_high = (uint32_t) (prod >> 32);
Reid Spencer5e0a8512007-02-17 03:16:00 +0000979 prod_low += carry;
980 carry = (prod_low < carry ? 1 : 0) + prod_high;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000981 uint32_t x_j = dest[offset+j];
Reid Spencer5e0a8512007-02-17 03:16:00 +0000982 prod_low = x_j - prod_low;
983 if (prod_low > x_j) ++carry;
984 dest[offset+j] = prod_low;
985 } while (++j < len);
986 return carry;
987}
988
989/// unitDiv - This function divides N by D,
990/// and returns (remainder << 32) | quotient.
991/// Assumes (N >> 32) < D.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000992static uint64_t unitDiv(uint64_t N, uint32_t D) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000993 uint64_t q, r; // q: quotient, r: remainder.
994 uint64_t a1 = N >> 32; // a1: high 32-bit part of N.
995 uint64_t a0 = N & 0xffffffffL; // a0: low 32-bit part of N
996 if (a1 < ((D - a1 - (a0 >> 31)) & 0xffffffffL)) {
997 q = N / D;
998 r = N % D;
999 }
1000 else {
1001 // Compute c1*2^32 + c0 = a1*2^32 + a0 - 2^31*d
1002 uint64_t c = N - ((uint64_t) D << 31);
1003 // Divide (c1*2^32 + c0) by d
1004 q = c / D;
1005 r = c % D;
1006 // Add 2^31 to quotient
1007 q += 1 << 31;
1008 }
1009
1010 return (r << 32) | (q & 0xFFFFFFFFl);
1011}
1012
Reid Spencer9c0696f2007-02-20 08:51:03 +00001013#endif
1014
Reid Spencer5e0a8512007-02-17 03:16:00 +00001015/// div - This is basically Knuth's formulation of the classical algorithm.
1016/// Correspondance with Knuth's notation:
1017/// Knuth's u[0:m+n] == zds[nx:0].
1018/// Knuth's v[1:n] == y[ny-1:0]
1019/// Knuth's n == ny.
1020/// Knuth's m == nx-ny.
1021/// Our nx == Knuth's m+n.
1022/// Could be re-implemented using gmp's mpn_divrem:
1023/// zds[nx] = mpn_divrem (&zds[ny], 0, zds, nx, y, ny).
Reid Spencer9c0696f2007-02-20 08:51:03 +00001024
1025/// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
1026/// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
1027/// variables here have the same names as in the algorithm. Comments explain
1028/// the algorithm and any deviation from it.
1029static void KnuthDiv(uint32_t *u, uint32_t *v, uint32_t *q, uint32_t* r,
1030 uint32_t m, uint32_t n) {
1031 assert(u && "Must provide dividend");
1032 assert(v && "Must provide divisor");
1033 assert(q && "Must provide quotient");
1034 assert(n>1 && "n must be > 1");
1035
1036 // Knuth uses the value b as the base of the number system. In our case b
1037 // is 2^31 so we just set it to -1u.
1038 uint64_t b = uint64_t(1) << 32;
1039
1040 // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
1041 // u and v by d. Note that we have taken Knuth's advice here to use a power
1042 // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
1043 // 2 allows us to shift instead of multiply and it is easy to determine the
1044 // shift amount from the leading zeros. We are basically normalizing the u
1045 // and v so that its high bits are shifted to the top of v's range without
1046 // overflow. Note that this can require an extra word in u so that u must
1047 // be of length m+n+1.
1048 uint32_t shift = CountLeadingZeros_32(v[n-1]);
1049 uint32_t v_carry = 0;
1050 uint32_t u_carry = 0;
1051 if (shift) {
1052 for (uint32_t i = 0; i < m+n; ++i) {
1053 uint32_t u_tmp = u[i] >> (32 - shift);
1054 u[i] = (u[i] << shift) | u_carry;
1055 u_carry = u_tmp;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001056 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001057 for (uint32_t i = 0; i < n; ++i) {
1058 uint32_t v_tmp = v[i] >> (32 - shift);
1059 v[i] = (v[i] << shift) | v_carry;
1060 v_carry = v_tmp;
1061 }
1062 }
1063 u[m+n] = u_carry;
1064
1065 // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
1066 int j = m;
1067 do {
1068 // D3. [Calculate q'.].
1069 // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
1070 // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
1071 // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
1072 // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test
1073 // on v[n-2] determines at high speed most of the cases in which the trial
1074 // value qp is one too large, and it eliminates all cases where qp is two
1075 // too large.
1076 uint64_t qp = ((uint64_t(u[j+n]) << 32) | uint64_t(u[j+n-1])) / v[n-1];
1077 uint64_t rp = ((uint64_t(u[j+n]) << 32) | uint64_t(u[j+n-1])) % v[n-1];
1078 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1079 qp--;
1080 rp += v[n-1];
1081 }
1082 if (rp < b)
1083 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1084 qp--;
1085 rp += v[n-1];
1086 }
1087
1088 // D4. [Multiply and subtract.] Replace u with u - q*v (for each word).
1089 uint32_t borrow = 0;
1090 for (uint32_t i = 0; i < n; i++) {
1091 uint32_t save = u[j+i];
1092 u[j+i] = uint64_t(u[j+i]) - (qp * v[i]) - borrow;
1093 if (u[j+i] > save) {
1094 borrow = 1;
1095 u[j+i+1] += b;
1096 } else {
1097 borrow = 0;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001098 }
1099 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001100 if (borrow)
1101 u[j+n] += 1;
1102
1103 // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
1104 // negative, go to step D6; otherwise go on to step D7.
1105 q[j] = qp;
1106 if (borrow) {
1107 // D6. [Add back]. The probability that this step is necessary is very
1108 // small, on the order of only 2/b. Make sure that test data accounts for
1109 // this possibility. Decreate qj by 1 and add v[...] to u[...]. A carry
1110 // will occur to the left of u[j+n], and it should be ignored since it
1111 // cancels with the borrow that occurred in D4.
1112 uint32_t carry = 0;
1113 for (uint32_t i = 0; i < n; i++) {
1114 uint32_t save = u[j+i];
1115 u[j+i] += v[i] + carry;
1116 carry = u[j+i] < save;
1117 }
1118 }
1119
1120 // D7. [Loop on j.] Decreate j by one. Now if j >= 0, go back to D3.
1121 j--;
1122 } while (j >= 0);
1123
1124 // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
1125 // remainder may be obtained by dividing u[...] by d. If r is non-null we
1126 // compute the remainder (urem uses this).
1127 if (r) {
1128 // The value d is expressed by the "shift" value above since we avoided
1129 // multiplication by d by using a shift left. So, all we have to do is
1130 // shift right here. In order to mak
1131 uint32_t mask = ~0u >> (32 - shift);
1132 uint32_t carry = 0;
1133 for (int i = n-1; i >= 0; i--) {
1134 uint32_t save = u[i] & mask;
1135 r[i] = (u[i] >> shift) | carry;
1136 carry = save;
1137 }
1138 }
1139}
1140
1141// This function makes calling KnuthDiv a little more convenient. It uses
1142// APInt parameters instead of uint32_t* parameters. It can also divide APInt
1143// values of different widths.
1144void APInt::divide(const APInt LHS, uint32_t lhsWords,
1145 const APInt &RHS, uint32_t rhsWords,
1146 APInt *Quotient, APInt *Remainder)
1147{
1148 assert(lhsWords >= rhsWords && "Fractional result");
1149
1150 // First, compose the values into an array of 32-bit words instead of
1151 // 64-bit words. This is a necessity of both the "short division" algorithm
1152 // and the the Knuth "classical algorithm" which requires there to be native
1153 // operations for +, -, and * on an m bit value with an m*2 bit result. We
1154 // can't use 64-bit operands here because we don't have native results of
1155 // 128-bits. Furthremore, casting the 64-bit values to 32-bit values won't
1156 // work on large-endian machines.
1157 uint64_t mask = ~0ull >> (sizeof(uint32_t)*8);
1158 uint32_t n = rhsWords * 2;
1159 uint32_t m = (lhsWords * 2) - n;
1160 // FIXME: allocate space on stack if m and n are sufficiently small.
1161 uint32_t *U = new uint32_t[m + n + 1];
1162 memset(U, 0, (m+n+1)*sizeof(uint32_t));
1163 for (unsigned i = 0; i < lhsWords; ++i) {
1164 uint64_t tmp = (lhsWords == 1 ? LHS.VAL : LHS.pVal[i]);
1165 U[i * 2] = tmp & mask;
1166 U[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1167 }
1168 U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
1169
1170 uint32_t *V = new uint32_t[n];
1171 memset(V, 0, (n)*sizeof(uint32_t));
1172 for (unsigned i = 0; i < rhsWords; ++i) {
1173 uint64_t tmp = (rhsWords == 1 ? RHS.VAL : RHS.pVal[i]);
1174 V[i * 2] = tmp & mask;
1175 V[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1176 }
1177
1178 // Set up the quotient and remainder
1179 uint32_t *Q = new uint32_t[m+n];
1180 memset(Q, 0, (m+n) * sizeof(uint32_t));
1181 uint32_t *R = 0;
1182 if (Remainder) {
1183 R = new uint32_t[n];
1184 memset(R, 0, n * sizeof(uint32_t));
1185 }
1186
1187 // Now, adjust m and n for the Knuth division. n is the number of words in
1188 // the divisor. m is the number of words by which the dividend exceeds the
1189 // divisor (i.e. m+n is the length of the dividend). These sizes must not
1190 // contain any zero words or the Knuth algorithm fails.
1191 for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
1192 n--;
1193 m++;
1194 }
1195 for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
1196 m--;
1197
1198 // If we're left with only a single word for the divisor, Knuth doesn't work
1199 // so we implement the short division algorithm here. This is much simpler
1200 // and faster because we are certain that we can divide a 64-bit quantity
1201 // by a 32-bit quantity at hardware speed and short division is simply a
1202 // series of such operations. This is just like doing short division but we
1203 // are using base 2^32 instead of base 10.
1204 assert(n != 0 && "Divide by zero?");
1205 if (n == 1) {
1206 uint32_t divisor = V[0];
1207 uint32_t remainder = 0;
1208 for (int i = m+n-1; i >= 0; i--) {
1209 uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i];
1210 if (partial_dividend == 0) {
1211 Q[i] = 0;
1212 remainder = 0;
1213 } else if (partial_dividend < divisor) {
1214 Q[i] = 0;
1215 remainder = partial_dividend;
1216 } else if (partial_dividend == divisor) {
1217 Q[i] = 1;
1218 remainder = 0;
1219 } else {
1220 Q[i] = partial_dividend / divisor;
1221 remainder = partial_dividend - (Q[i] * divisor);
1222 }
1223 }
1224 if (R)
1225 R[0] = remainder;
1226 } else {
1227 // Now we're ready to invoke the Knuth classical divide algorithm. In this
1228 // case n > 1.
1229 KnuthDiv(U, V, Q, R, m, n);
1230 }
1231
1232 // If the caller wants the quotient
1233 if (Quotient) {
1234 // Set up the Quotient value's memory.
1235 if (Quotient->BitWidth != LHS.BitWidth) {
1236 if (Quotient->isSingleWord())
1237 Quotient->VAL = 0;
1238 else
1239 delete Quotient->pVal;
1240 Quotient->BitWidth = LHS.BitWidth;
1241 if (!Quotient->isSingleWord())
1242 Quotient->pVal = getClearedMemory(lhsWords);
1243 } else
1244 Quotient->clear();
1245
1246 // The quotient is in Q. Reconstitute the quotient into Quotient's low
1247 // order words.
1248 if (lhsWords == 1) {
1249 uint64_t tmp =
1250 uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2));
1251 if (Quotient->isSingleWord())
1252 Quotient->VAL = tmp;
1253 else
1254 Quotient->pVal[0] = tmp;
1255 } else {
1256 assert(!Quotient->isSingleWord() && "Quotient APInt not large enough");
1257 for (unsigned i = 0; i < lhsWords; ++i)
1258 Quotient->pVal[i] =
1259 uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1260 }
1261 }
1262
1263 // If the caller wants the remainder
1264 if (Remainder) {
1265 // Set up the Remainder value's memory.
1266 if (Remainder->BitWidth != RHS.BitWidth) {
1267 if (Remainder->isSingleWord())
1268 Remainder->VAL = 0;
1269 else
1270 delete Remainder->pVal;
1271 Remainder->BitWidth = RHS.BitWidth;
1272 if (!Remainder->isSingleWord())
1273 Remainder->pVal = getClearedMemory(rhsWords);
1274 } else
1275 Remainder->clear();
1276
1277 // The remainder is in R. Reconstitute the remainder into Remainder's low
1278 // order words.
1279 if (rhsWords == 1) {
1280 uint64_t tmp =
1281 uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2));
1282 if (Remainder->isSingleWord())
1283 Remainder->VAL = tmp;
1284 else
1285 Remainder->pVal[0] = tmp;
1286 } else {
1287 assert(!Remainder->isSingleWord() && "Remainder APInt not large enough");
1288 for (unsigned i = 0; i < rhsWords; ++i)
1289 Remainder->pVal[i] =
1290 uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1291 }
1292 }
1293
1294 // Clean up the memory we allocated.
1295 delete [] U;
1296 delete [] V;
1297 delete [] Q;
1298 delete [] R;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001299}
1300
Zhou Shengff4304f2007-02-09 07:48:24 +00001301/// Unsigned divide this APInt by APInt RHS.
Zhou Sheng0b706b12007-02-08 14:35:19 +00001302/// @brief Unsigned division function for APInt.
Reid Spencere81d2da2007-02-16 22:36:51 +00001303APInt APInt::udiv(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +00001304 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer71bd08f2007-02-17 02:07:07 +00001305
1306 // First, deal with the easy case
1307 if (isSingleWord()) {
1308 assert(RHS.VAL != 0 && "Divide by zero?");
1309 return APInt(BitWidth, VAL / RHS.VAL);
Zhou Sheng0b706b12007-02-08 14:35:19 +00001310 }
Reid Spencer71bd08f2007-02-17 02:07:07 +00001311
Reid Spencer71bd08f2007-02-17 02:07:07 +00001312 // Get some facts about the LHS and RHS number of bits and words
Reid Spenceraf0e9562007-02-18 18:38:44 +00001313 uint32_t rhsBits = RHS.getActiveBits();
1314 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001315 assert(rhsWords && "Divided by zero???");
Reid Spencer9c0696f2007-02-20 08:51:03 +00001316 uint32_t lhsBits = this->getActiveBits();
Reid Spenceraf0e9562007-02-18 18:38:44 +00001317 uint32_t lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001318
Reid Spencer9c0696f2007-02-20 08:51:03 +00001319 // Make a temporary to hold the result
1320 APInt Result(*this);
1321
Reid Spencer71bd08f2007-02-17 02:07:07 +00001322 // Deal with some degenerate cases
1323 if (!lhsWords)
1324 return Result; // 0 / X == 0
Reid Spencer9c0696f2007-02-20 08:51:03 +00001325 else if (lhsWords < rhsWords || Result.ult(RHS)) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001326 // X / Y with X < Y == 0
Reid Spencera58f0582007-02-18 20:09:41 +00001327 memset(Result.pVal, 0, Result.getNumWords() * APINT_WORD_SIZE);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001328 return Result;
1329 } else if (Result == RHS) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001330 // X / X == 1
Reid Spencera58f0582007-02-18 20:09:41 +00001331 memset(Result.pVal, 0, Result.getNumWords() * APINT_WORD_SIZE);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001332 Result.pVal[0] = 1;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001333 return Result;
1334 } else if (lhsWords == 1 && rhsWords == 1) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001335 // All high words are zero, just use native divide
1336 Result.pVal[0] /= RHS.pVal[0];
Reid Spencer9c0696f2007-02-20 08:51:03 +00001337 return Result;
Reid Spencer71bd08f2007-02-17 02:07:07 +00001338 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001339
1340 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1341 APInt Quotient(1,0); // to hold result.
1342 divide(*this, lhsWords, RHS, rhsWords, &Quotient, 0);
1343 return Quotient;
Zhou Sheng0b706b12007-02-08 14:35:19 +00001344}
1345
1346/// Unsigned remainder operation on APInt.
1347/// @brief Function for unsigned remainder operation.
Reid Spencere81d2da2007-02-16 22:36:51 +00001348APInt APInt::urem(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +00001349 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer71bd08f2007-02-17 02:07:07 +00001350 if (isSingleWord()) {
1351 assert(RHS.VAL != 0 && "Remainder by zero?");
1352 return APInt(BitWidth, VAL % RHS.VAL);
Zhou Sheng0b706b12007-02-08 14:35:19 +00001353 }
Reid Spencer71bd08f2007-02-17 02:07:07 +00001354
1355 // Make a temporary to hold the result
1356 APInt Result(*this);
1357
1358 // Get some facts about the RHS
Reid Spenceraf0e9562007-02-18 18:38:44 +00001359 uint32_t rhsBits = RHS.getActiveBits();
1360 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001361 assert(rhsWords && "Performing remainder operation by zero ???");
1362
1363 // Get some facts about the LHS
Reid Spenceraf0e9562007-02-18 18:38:44 +00001364 uint32_t lhsBits = Result.getActiveBits();
1365 uint32_t lhsWords = !lhsBits ? 0 : (Result.whichWord(lhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001366
1367 // Check the degenerate cases
Reid Spencer9c0696f2007-02-20 08:51:03 +00001368 if (lhsWords == 0) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001369 // 0 % Y == 0
Reid Spencera58f0582007-02-18 20:09:41 +00001370 memset(Result.pVal, 0, Result.getNumWords() * APINT_WORD_SIZE);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001371 return Result;
1372 } else if (lhsWords < rhsWords || Result.ult(RHS)) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001373 // X % Y == X iff X < Y
1374 return Result;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001375 } else if (Result == RHS) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001376 // X % X == 0;
Reid Spencera58f0582007-02-18 20:09:41 +00001377 memset(Result.pVal, 0, Result.getNumWords() * APINT_WORD_SIZE);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001378 return Result;
1379 } else if (lhsWords == 1) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001380 // All high words are zero, just use native remainder
1381 Result.pVal[0] %= RHS.pVal[0];
Reid Spencer9c0696f2007-02-20 08:51:03 +00001382 return Result;
Reid Spencer71bd08f2007-02-17 02:07:07 +00001383 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001384
1385 // We have to compute it the hard way. Invoke the Knute divide algorithm.
1386 APInt Remainder(1,0);
1387 divide(*this, lhsWords, RHS, rhsWords, 0, &Remainder);
1388 return Remainder;
Zhou Sheng0b706b12007-02-08 14:35:19 +00001389}
Reid Spencer5e0a8512007-02-17 03:16:00 +00001390
1391/// @brief Converts a char array into an integer.
Reid Spencer385f7542007-02-21 03:55:44 +00001392void APInt::fromString(uint32_t numbits, const char *str, uint32_t slen,
Reid Spencer5e0a8512007-02-17 03:16:00 +00001393 uint8_t radix) {
Reid Spencer385f7542007-02-21 03:55:44 +00001394 // Check our assumptions here
Reid Spencer5e0a8512007-02-17 03:16:00 +00001395 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1396 "Radix should be 2, 8, 10, or 16!");
Reid Spencer385f7542007-02-21 03:55:44 +00001397 assert(str && "String is null?");
1398 assert(slen <= numbits || radix != 2 && "Insufficient bit width");
1399 assert(slen*3 <= numbits || radix != 8 && "Insufficient bit width");
1400 assert(slen*4 <= numbits || radix != 16 && "Insufficient bit width");
1401 assert((slen*64)/20 <= numbits || radix != 10 && "Insufficient bit width");
1402
1403 // Allocate memory
1404 if (!isSingleWord())
1405 pVal = getClearedMemory(getNumWords());
1406
1407 // Figure out if we can shift instead of multiply
1408 uint32_t shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0);
1409
1410 // Set up an APInt for the digit to add outside the loop so we don't
1411 // constantly construct/destruct it.
1412 APInt apdigit(getBitWidth(), 0);
1413 APInt apradix(getBitWidth(), radix);
1414
1415 // Enter digit traversal loop
1416 for (unsigned i = 0; i < slen; i++) {
1417 // Get a digit
1418 uint32_t digit = 0;
1419 char cdigit = str[i];
1420 if (isdigit(cdigit))
1421 digit = cdigit - '0';
1422 else if (isxdigit(cdigit))
1423 if (cdigit >= 'a')
1424 digit = cdigit - 'a' + 10;
1425 else if (cdigit >= 'A')
1426 digit = cdigit - 'A' + 10;
1427 else
1428 assert(0 && "huh?");
1429 else
1430 assert(0 && "Invalid character in digit string");
1431
1432 // Shift or multiple the value by the radix
1433 if (shift)
1434 this->shl(shift);
1435 else
1436 *this *= apradix;
1437
1438 // Add in the digit we just interpreted
1439 apdigit.pVal[0] = digit;
1440 *this += apdigit;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001441 }
1442}
Reid Spencer9c0696f2007-02-20 08:51:03 +00001443
1444/// to_string - This function translates the APInt into a string.
1445std::string APInt::toString(uint8_t radix, bool wantSigned) const {
1446 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1447 "Radix should be 2, 8, 10, or 16!");
1448 static const char *digits[] = {
1449 "0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"
1450 };
1451 std::string result;
1452 uint32_t bits_used = getActiveBits();
1453 if (isSingleWord()) {
1454 char buf[65];
1455 const char *format = (radix == 10 ? (wantSigned ? "%lld" : "%llu") :
1456 (radix == 16 ? "%llX" : (radix == 8 ? "%llo" : 0)));
1457 if (format) {
1458 if (wantSigned) {
1459 int64_t sextVal = (int64_t(VAL) << (APINT_BITS_PER_WORD-BitWidth)) >>
1460 (APINT_BITS_PER_WORD-BitWidth);
1461 sprintf(buf, format, sextVal);
1462 } else
1463 sprintf(buf, format, VAL);
1464 } else {
1465 memset(buf, 0, 65);
1466 uint64_t v = VAL;
1467 while (bits_used) {
1468 uint32_t bit = v & 1;
1469 bits_used--;
1470 buf[bits_used] = digits[bit][0];
1471 v >>=1;
1472 }
1473 }
1474 result = buf;
1475 return result;
1476 }
1477
1478 if (radix != 10) {
1479 uint64_t mask = radix - 1;
1480 uint32_t shift = (radix == 16 ? 4 : radix == 8 ? 3 : 1);
1481 uint32_t nibbles = APINT_BITS_PER_WORD / shift;
1482 for (uint32_t i = 0; i < getNumWords(); ++i) {
1483 uint64_t value = pVal[i];
1484 for (uint32_t j = 0; j < nibbles; ++j) {
1485 result.insert(0, digits[ value & mask ]);
1486 value >>= shift;
1487 }
1488 }
1489 return result;
1490 }
1491
1492 APInt tmp(*this);
1493 APInt divisor(4, radix);
1494 APInt zero(tmp.getBitWidth(), 0);
1495 size_t insert_at = 0;
1496 if (wantSigned && tmp[BitWidth-1]) {
1497 // They want to print the signed version and it is a negative value
1498 // Flip the bits and add one to turn it into the equivalent positive
1499 // value and put a '-' in the result.
1500 tmp.flip();
1501 tmp++;
1502 result = "-";
1503 insert_at = 1;
1504 }
Reid Spencere549c492007-02-21 00:29:48 +00001505 if (tmp == APInt(tmp.getBitWidth(), 0))
Reid Spencer9c0696f2007-02-20 08:51:03 +00001506 result = "0";
1507 else while (tmp.ne(zero)) {
1508 APInt APdigit(1,0);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001509 APInt tmp2(tmp.getBitWidth(), 0);
Reid Spencer385f7542007-02-21 03:55:44 +00001510 divide(tmp, tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2,
1511 &APdigit);
1512 uint32_t digit = APdigit.getValue();
1513 assert(digit < radix && "divide failed");
1514 result.insert(insert_at,digits[digit]);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001515 tmp = tmp2;
1516 }
1517
1518 return result;
1519}
1520
Reid Spencer385f7542007-02-21 03:55:44 +00001521#ifndef NDEBUG
1522void APInt::dump() const
1523{
1524 std::cerr << "APInt(" << BitWidth << ")=" << std::setbase(16);
1525 if (isSingleWord())
1526 std::cerr << VAL;
1527 else for (unsigned i = getNumWords(); i > 0; i--) {
1528 std::cerr << pVal[i-1] << " ";
1529 }
1530 std::cerr << " (" << this->toString(10, false) << ")\n" << std::setbase(10);
1531}
1532#endif