blob: 6939c21b8136a6a92c935bf56d956083cd6a3d90 [file] [log] [blame]
Zhou Shengfd43dcf2007-02-06 03:00:16 +00001//===-- APInt.cpp - Implement APInt class ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Reid Spencer96d91372007-02-27 19:31:09 +00005// This file was developed by Sheng Zhou and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
Zhou Shengfd43dcf2007-02-06 03:00:16 +00007//
8//===----------------------------------------------------------------------===//
9//
Reid Spencer5d0d05c2007-02-25 19:32:03 +000010// This file implements a class to represent arbitrary precision integer
11// constant values and provide a variety of arithmetic operations on them.
Zhou Shengfd43dcf2007-02-06 03:00:16 +000012//
13//===----------------------------------------------------------------------===//
14
Reid Spencer9d6c9192007-02-24 03:58:46 +000015#define DEBUG_TYPE "apint"
Zhou Shengfd43dcf2007-02-06 03:00:16 +000016#include "llvm/ADT/APInt.h"
17#include "llvm/DerivedTypes.h"
Reid Spencer9d6c9192007-02-24 03:58:46 +000018#include "llvm/Support/Debug.h"
Zhou Shengfd43dcf2007-02-06 03:00:16 +000019#include "llvm/Support/MathExtras.h"
Zhou Shenga3832fd2007-02-07 06:14:53 +000020#include <cstring>
Zhou Shengfd43dcf2007-02-06 03:00:16 +000021#include <cstdlib>
Reid Spencer385f7542007-02-21 03:55:44 +000022#ifndef NDEBUG
Reid Spencer385f7542007-02-21 03:55:44 +000023#include <iomanip>
24#endif
25
Zhou Shengfd43dcf2007-02-06 03:00:16 +000026using namespace llvm;
27
Reid Spencer5d0d05c2007-02-25 19:32:03 +000028/// A utility function for allocating memory, checking for allocation failures,
29/// and ensuring the contents are zeroed.
Reid Spenceraf0e9562007-02-18 18:38:44 +000030inline static uint64_t* getClearedMemory(uint32_t numWords) {
31 uint64_t * result = new uint64_t[numWords];
32 assert(result && "APInt memory allocation fails!");
33 memset(result, 0, numWords * sizeof(uint64_t));
34 return result;
Zhou Sheng353815d2007-02-06 06:04:53 +000035}
36
Reid Spencer5d0d05c2007-02-25 19:32:03 +000037/// A utility function for allocating memory and checking for allocation
38/// failure. The content is not zeroed.
Reid Spenceraf0e9562007-02-18 18:38:44 +000039inline static uint64_t* getMemory(uint32_t numWords) {
40 uint64_t * result = new uint64_t[numWords];
41 assert(result && "APInt memory allocation fails!");
42 return result;
43}
44
45APInt::APInt(uint32_t numBits, uint64_t val)
Reid Spencer385f7542007-02-21 03:55:44 +000046 : BitWidth(numBits), VAL(0) {
Reid Spencere81d2da2007-02-16 22:36:51 +000047 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
48 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
Reid Spencer5d0d05c2007-02-25 19:32:03 +000049 if (isSingleWord())
50 VAL = val;
Zhou Shengfd43dcf2007-02-06 03:00:16 +000051 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +000052 pVal = getClearedMemory(getNumWords());
Zhou Shengfd43dcf2007-02-06 03:00:16 +000053 pVal[0] = val;
54 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +000055 clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +000056}
57
Reid Spenceraf0e9562007-02-18 18:38:44 +000058APInt::APInt(uint32_t numBits, uint32_t numWords, uint64_t bigVal[])
Reid Spencer385f7542007-02-21 03:55:44 +000059 : BitWidth(numBits), VAL(0) {
Reid Spencere81d2da2007-02-16 22:36:51 +000060 assert(BitWidth >= IntegerType::MIN_INT_BITS && "bitwidth too small");
61 assert(BitWidth <= IntegerType::MAX_INT_BITS && "bitwidth too large");
Zhou Shengfd43dcf2007-02-06 03:00:16 +000062 assert(bigVal && "Null pointer detected!");
63 if (isSingleWord())
Reid Spencer610fad82007-02-24 10:01:42 +000064 VAL = bigVal[0];
Zhou Shengfd43dcf2007-02-06 03:00:16 +000065 else {
Reid Spencer610fad82007-02-24 10:01:42 +000066 // Get memory, cleared to 0
67 pVal = getClearedMemory(getNumWords());
68 // Calculate the number of words to copy
69 uint32_t words = std::min<uint32_t>(numWords, getNumWords());
70 // Copy the words from bigVal to pVal
71 memcpy(pVal, bigVal, words * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +000072 }
Reid Spencer610fad82007-02-24 10:01:42 +000073 // Make sure unused high bits are cleared
74 clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +000075}
76
Reid Spenceraf0e9562007-02-18 18:38:44 +000077APInt::APInt(uint32_t numbits, const char StrStart[], uint32_t slen,
Reid Spencer9c0696f2007-02-20 08:51:03 +000078 uint8_t radix)
Reid Spencer385f7542007-02-21 03:55:44 +000079 : BitWidth(numbits), VAL(0) {
Reid Spencere81d2da2007-02-16 22:36:51 +000080 fromString(numbits, StrStart, slen, radix);
Zhou Shenga3832fd2007-02-07 06:14:53 +000081}
82
Reid Spencer9c0696f2007-02-20 08:51:03 +000083APInt::APInt(uint32_t numbits, const std::string& Val, uint8_t radix)
Reid Spencer385f7542007-02-21 03:55:44 +000084 : BitWidth(numbits), VAL(0) {
Zhou Shenga3832fd2007-02-07 06:14:53 +000085 assert(!Val.empty() && "String empty?");
Reid Spencere81d2da2007-02-16 22:36:51 +000086 fromString(numbits, Val.c_str(), Val.size(), radix);
Zhou Shenga3832fd2007-02-07 06:14:53 +000087}
88
Reid Spencer54362ca2007-02-20 23:40:25 +000089APInt::APInt(const APInt& that)
Reid Spencer385f7542007-02-21 03:55:44 +000090 : BitWidth(that.BitWidth), VAL(0) {
Reid Spenceraf0e9562007-02-18 18:38:44 +000091 if (isSingleWord())
Reid Spencer54362ca2007-02-20 23:40:25 +000092 VAL = that.VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +000093 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +000094 pVal = getMemory(getNumWords());
Reid Spencer54362ca2007-02-20 23:40:25 +000095 memcpy(pVal, that.pVal, getNumWords() * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +000096 }
97}
98
99APInt::~APInt() {
Reid Spencer9c0696f2007-02-20 08:51:03 +0000100 if (!isSingleWord() && pVal)
Reid Spencer9ac44112007-02-26 23:38:21 +0000101 delete [] pVal;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000102}
103
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000104APInt& APInt::operator=(const APInt& RHS) {
Reid Spencer9ac44112007-02-26 23:38:21 +0000105 // Don't do anything for X = X
106 if (this == &RHS)
107 return *this;
108
109 // If the bitwidths are the same, we can avoid mucking with memory
110 if (BitWidth == RHS.getBitWidth()) {
111 if (isSingleWord())
112 VAL = RHS.VAL;
113 else
114 memcpy(pVal, RHS.pVal, getNumWords() * APINT_WORD_SIZE);
115 return *this;
116 }
117
118 if (isSingleWord())
119 if (RHS.isSingleWord())
120 VAL = RHS.VAL;
121 else {
122 VAL = 0;
123 pVal = getMemory(RHS.getNumWords());
124 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
125 }
126 else if (getNumWords() == RHS.getNumWords())
127 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
128 else if (RHS.isSingleWord()) {
129 delete [] pVal;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000130 VAL = RHS.VAL;
Reid Spencer9ac44112007-02-26 23:38:21 +0000131 } else {
132 delete [] pVal;
133 pVal = getMemory(RHS.getNumWords());
134 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
135 }
136 BitWidth = RHS.BitWidth;
137 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000138}
139
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000140APInt& APInt::operator=(uint64_t RHS) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000141 if (isSingleWord())
142 VAL = RHS;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000143 else {
144 pVal[0] = RHS;
Reid Spencera58f0582007-02-18 20:09:41 +0000145 memset(pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000146 }
Reid Spencer9ac44112007-02-26 23:38:21 +0000147 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000148}
149
Reid Spenceraf0e9562007-02-18 18:38:44 +0000150/// add_1 - This function adds a single "digit" integer, y, to the multiple
151/// "digit" integer array, x[]. x[] is modified to reflect the addition and
152/// 1 is returned if there is a carry out, otherwise 0 is returned.
Reid Spencer5e0a8512007-02-17 03:16:00 +0000153/// @returns the carry of the addition.
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000154static bool add_1(uint64_t dest[], uint64_t x[], uint32_t len, uint64_t y) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000155 for (uint32_t i = 0; i < len; ++i) {
Reid Spencerf2c521c2007-02-18 06:39:42 +0000156 dest[i] = y + x[i];
157 if (dest[i] < y)
Reid Spencer610fad82007-02-24 10:01:42 +0000158 y = 1; // Carry one to next digit.
Reid Spencerf2c521c2007-02-18 06:39:42 +0000159 else {
Reid Spencer610fad82007-02-24 10:01:42 +0000160 y = 0; // No need to carry so exit early
Reid Spencerf2c521c2007-02-18 06:39:42 +0000161 break;
162 }
Reid Spencer5e0a8512007-02-17 03:16:00 +0000163 }
Reid Spencerf2c521c2007-02-18 06:39:42 +0000164 return y;
Reid Spencer5e0a8512007-02-17 03:16:00 +0000165}
166
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000167/// @brief Prefix increment operator. Increments the APInt by one.
168APInt& APInt::operator++() {
Reid Spencere81d2da2007-02-16 22:36:51 +0000169 if (isSingleWord())
170 ++VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000171 else
Zhou Shenga3832fd2007-02-07 06:14:53 +0000172 add_1(pVal, pVal, getNumWords(), 1);
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000173 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000174}
175
Reid Spenceraf0e9562007-02-18 18:38:44 +0000176/// sub_1 - This function subtracts a single "digit" (64-bit word), y, from
177/// the multi-digit integer array, x[], propagating the borrowed 1 value until
178/// no further borrowing is neeeded or it runs out of "digits" in x. The result
179/// is 1 if "borrowing" exhausted the digits in x, or 0 if x was not exhausted.
180/// In other words, if y > x then this function returns 1, otherwise 0.
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000181/// @returns the borrow out of the subtraction
182static bool sub_1(uint64_t x[], uint32_t len, uint64_t y) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000183 for (uint32_t i = 0; i < len; ++i) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000184 uint64_t X = x[i];
Reid Spencerf2c521c2007-02-18 06:39:42 +0000185 x[i] -= y;
186 if (y > X)
Reid Spenceraf0e9562007-02-18 18:38:44 +0000187 y = 1; // We have to "borrow 1" from next "digit"
Reid Spencer5e0a8512007-02-17 03:16:00 +0000188 else {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000189 y = 0; // No need to borrow
190 break; // Remaining digits are unchanged so exit early
Reid Spencer5e0a8512007-02-17 03:16:00 +0000191 }
192 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000193 return bool(y);
Reid Spencer5e0a8512007-02-17 03:16:00 +0000194}
195
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000196/// @brief Prefix decrement operator. Decrements the APInt by one.
197APInt& APInt::operator--() {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000198 if (isSingleWord())
199 --VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000200 else
Zhou Shenga3832fd2007-02-07 06:14:53 +0000201 sub_1(pVal, getNumWords(), 1);
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000202 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000203}
204
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000205/// add - This function adds the integer array x to the integer array Y and
206/// places the result in dest.
207/// @returns the carry out from the addition
208/// @brief General addition of 64-bit integer arrays
Reid Spencer9d6c9192007-02-24 03:58:46 +0000209static bool add(uint64_t *dest, const uint64_t *x, const uint64_t *y,
210 uint32_t len) {
211 bool carry = false;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000212 for (uint32_t i = 0; i< len; ++i) {
Reid Spencer92904632007-02-23 01:57:13 +0000213 uint64_t limit = std::min(x[i],y[i]); // must come first in case dest == x
Reid Spencer54362ca2007-02-20 23:40:25 +0000214 dest[i] = x[i] + y[i] + carry;
Reid Spencer60c0a6a2007-02-21 05:44:56 +0000215 carry = dest[i] < limit || (carry && dest[i] == limit);
Reid Spencer5e0a8512007-02-17 03:16:00 +0000216 }
217 return carry;
218}
219
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000220/// Adds the RHS APint to this APInt.
221/// @returns this, after addition of RHS.
222/// @brief Addition assignment operator.
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000223APInt& APInt::operator+=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000224 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer54362ca2007-02-20 23:40:25 +0000225 if (isSingleWord())
226 VAL += RHS.VAL;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000227 else {
Reid Spencer54362ca2007-02-20 23:40:25 +0000228 add(pVal, pVal, RHS.pVal, getNumWords());
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000229 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000230 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000231}
232
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000233/// Subtracts the integer array y from the integer array x
234/// @returns returns the borrow out.
235/// @brief Generalized subtraction of 64-bit integer arrays.
Reid Spencer9d6c9192007-02-24 03:58:46 +0000236static bool sub(uint64_t *dest, const uint64_t *x, const uint64_t *y,
237 uint32_t len) {
Reid Spencer385f7542007-02-21 03:55:44 +0000238 bool borrow = false;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000239 for (uint32_t i = 0; i < len; ++i) {
Reid Spencer385f7542007-02-21 03:55:44 +0000240 uint64_t x_tmp = borrow ? x[i] - 1 : x[i];
241 borrow = y[i] > x_tmp || (borrow && x[i] == 0);
242 dest[i] = x_tmp - y[i];
Reid Spencer5e0a8512007-02-17 03:16:00 +0000243 }
Reid Spencer54362ca2007-02-20 23:40:25 +0000244 return borrow;
Reid Spencer5e0a8512007-02-17 03:16:00 +0000245}
246
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000247/// Subtracts the RHS APInt from this APInt
248/// @returns this, after subtraction
249/// @brief Subtraction assignment operator.
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000250APInt& APInt::operator-=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000251 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000252 if (isSingleWord())
Reid Spencer54362ca2007-02-20 23:40:25 +0000253 VAL -= RHS.VAL;
254 else
255 sub(pVal, pVal, RHS.pVal, getNumWords());
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000256 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000257}
258
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000259/// Multiplies an integer array, x by a a uint64_t integer and places the result
260/// into dest.
261/// @returns the carry out of the multiplication.
262/// @brief Multiply a multi-digit APInt by a single digit (64-bit) integer.
Reid Spencer610fad82007-02-24 10:01:42 +0000263static uint64_t mul_1(uint64_t dest[], uint64_t x[], uint32_t len, uint64_t y) {
264 // Split y into high 32-bit part (hy) and low 32-bit part (ly)
Reid Spencer5e0a8512007-02-17 03:16:00 +0000265 uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000266 uint64_t carry = 0;
267
268 // For each digit of x.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000269 for (uint32_t i = 0; i < len; ++i) {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000270 // Split x into high and low words
271 uint64_t lx = x[i] & 0xffffffffULL;
272 uint64_t hx = x[i] >> 32;
273 // hasCarry - A flag to indicate if there is a carry to the next digit.
Reid Spencer5e0a8512007-02-17 03:16:00 +0000274 // 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 }
Reid Spencer5e0a8512007-02-17 03:16:00 +0000291 return carry;
292}
293
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000294/// Multiplies integer array x by integer array y and stores the result into
295/// the integer array dest. Note that dest's size must be >= xlen + ylen.
296/// @brief Generalized multiplicate of integer arrays.
Reid Spencer610fad82007-02-24 10:01:42 +0000297static void mul(uint64_t dest[], uint64_t x[], uint32_t xlen, uint64_t y[],
298 uint32_t ylen) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000299 dest[xlen] = mul_1(dest, x, xlen, y[0]);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000300 for (uint32_t i = 1; i < ylen; ++i) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000301 uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
Reid Spencere0cdd332007-02-21 08:21:52 +0000302 uint64_t carry = 0, lx = 0, hx = 0;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000303 for (uint32_t j = 0; j < xlen; ++j) {
Reid Spencer5e0a8512007-02-17 03:16:00 +0000304 lx = x[j] & 0xffffffffULL;
305 hx = x[j] >> 32;
306 // hasCarry - A flag to indicate if has carry.
307 // hasCarry == 0, no carry
308 // hasCarry == 1, has carry
309 // hasCarry == 2, no carry and the calculation result == 0.
310 uint8_t hasCarry = 0;
311 uint64_t resul = carry + lx * ly;
312 hasCarry = (resul < carry) ? 1 : 0;
313 carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
314 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
315
316 carry += (lx * hy) & 0xffffffffULL;
317 resul = (carry << 32) | (resul & 0xffffffffULL);
318 dest[i+j] += resul;
319 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
320 (carry >> 32) + (dest[i+j] < resul ? 1 : 0) +
321 ((lx * hy) >> 32) + hx * hy;
322 }
323 dest[i+xlen] = carry;
324 }
325}
326
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000327APInt& APInt::operator*=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000328 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencere0cdd332007-02-21 08:21:52 +0000329 if (isSingleWord()) {
Reid Spencer61eb1802007-02-20 20:42:10 +0000330 VAL *= RHS.VAL;
Reid Spencere0cdd332007-02-21 08:21:52 +0000331 clearUnusedBits();
332 return *this;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000333 }
Reid Spencere0cdd332007-02-21 08:21:52 +0000334
335 // Get some bit facts about LHS and check for zero
336 uint32_t lhsBits = getActiveBits();
337 uint32_t lhsWords = !lhsBits ? 0 : whichWord(lhsBits - 1) + 1;
338 if (!lhsWords)
339 // 0 * X ===> 0
340 return *this;
341
342 // Get some bit facts about RHS and check for zero
343 uint32_t rhsBits = RHS.getActiveBits();
344 uint32_t rhsWords = !rhsBits ? 0 : whichWord(rhsBits - 1) + 1;
345 if (!rhsWords) {
346 // X * 0 ===> 0
347 clear();
348 return *this;
349 }
350
351 // Allocate space for the result
352 uint32_t destWords = rhsWords + lhsWords;
353 uint64_t *dest = getMemory(destWords);
354
355 // Perform the long multiply
356 mul(dest, pVal, lhsWords, RHS.pVal, rhsWords);
357
358 // Copy result back into *this
359 clear();
360 uint32_t wordsToCopy = destWords >= getNumWords() ? getNumWords() : destWords;
361 memcpy(pVal, dest, wordsToCopy * APINT_WORD_SIZE);
362
363 // delete dest array and return
364 delete[] dest;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000365 return *this;
366}
367
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000368APInt& 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 Spenceraf0e9562007-02-18 18:38:44 +0000371 VAL &= RHS.VAL;
372 return *this;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000373 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000374 uint32_t numWords = getNumWords();
375 for (uint32_t i = 0; i < numWords; ++i)
376 pVal[i] &= RHS.pVal[i];
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000377 return *this;
378}
379
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000380APInt& APInt::operator|=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000381 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000382 if (isSingleWord()) {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000383 VAL |= RHS.VAL;
384 return *this;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000385 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000386 uint32_t numWords = getNumWords();
387 for (uint32_t i = 0; i < numWords; ++i)
388 pVal[i] |= RHS.pVal[i];
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000389 return *this;
390}
391
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000392APInt& APInt::operator^=(const APInt& RHS) {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000393 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000394 if (isSingleWord()) {
Reid Spencerf2c521c2007-02-18 06:39:42 +0000395 VAL ^= RHS.VAL;
Reid Spencer54362ca2007-02-20 23:40:25 +0000396 this->clearUnusedBits();
Reid Spencerf2c521c2007-02-18 06:39:42 +0000397 return *this;
398 }
Reid Spenceraf0e9562007-02-18 18:38:44 +0000399 uint32_t numWords = getNumWords();
400 for (uint32_t i = 0; i < numWords; ++i)
401 pVal[i] ^= RHS.pVal[i];
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000402 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000403}
404
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000405APInt 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
Reid Spenceraf0e9562007-02-18 18:38:44 +0000410 uint32_t numWords = getNumWords();
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000411 uint64_t* val = getMemory(numWords);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000412 for (uint32_t i = 0; i < numWords; ++i)
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000413 val[i] = pVal[i] & RHS.pVal[i];
414 return APInt(val, getBitWidth());
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000415}
416
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000417APInt APInt::operator|(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000418 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spenceraf0e9562007-02-18 18:38:44 +0000419 if (isSingleWord())
420 return APInt(getBitWidth(), VAL | RHS.VAL);
Reid Spencer54362ca2007-02-20 23:40:25 +0000421
Reid Spenceraf0e9562007-02-18 18:38:44 +0000422 uint32_t numWords = getNumWords();
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000423 uint64_t *val = getMemory(numWords);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000424 for (uint32_t i = 0; i < numWords; ++i)
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000425 val[i] = pVal[i] | RHS.pVal[i];
426 return APInt(val, getBitWidth());
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000427}
428
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000429APInt APInt::operator^(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000430 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000431 if (isSingleWord())
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000432 return APInt(BitWidth, VAL ^ RHS.VAL);
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000433
Reid Spenceraf0e9562007-02-18 18:38:44 +0000434 uint32_t numWords = getNumWords();
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000435 uint64_t *val = getMemory(numWords);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000436 for (uint32_t i = 0; i < numWords; ++i)
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000437 val[i] = pVal[i] ^ RHS.pVal[i];
438
439 // 0^0==1 so clear the high bits in case they got set.
440 return APInt(val, getBitWidth()).clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000441}
442
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000443bool APInt::operator !() const {
444 if (isSingleWord())
445 return !VAL;
Reid Spenceraf0e9562007-02-18 18:38:44 +0000446
447 for (uint32_t i = 0; i < getNumWords(); ++i)
448 if (pVal[i])
449 return false;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000450 return true;
451}
452
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000453APInt APInt::operator*(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000454 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000455 if (isSingleWord())
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000456 return APInt(BitWidth, VAL * RHS.VAL);
Reid Spencer61eb1802007-02-20 20:42:10 +0000457 APInt Result(*this);
458 Result *= RHS;
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000459 return Result.clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000460}
461
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000462APInt APInt::operator+(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000463 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000464 if (isSingleWord())
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000465 return APInt(BitWidth, VAL + RHS.VAL);
Reid Spencer54362ca2007-02-20 23:40:25 +0000466 APInt Result(BitWidth, 0);
467 add(Result.pVal, this->pVal, RHS.pVal, getNumWords());
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000468 return Result.clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000469}
470
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000471APInt APInt::operator-(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000472 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000473 if (isSingleWord())
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000474 return APInt(BitWidth, VAL - RHS.VAL);
Reid Spencer54362ca2007-02-20 23:40:25 +0000475 APInt Result(BitWidth, 0);
476 sub(Result.pVal, this->pVal, RHS.pVal, getNumWords());
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000477 return Result.clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000478}
479
Reid Spenceraf0e9562007-02-18 18:38:44 +0000480bool APInt::operator[](uint32_t bitPosition) const {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000481 return (maskBit(bitPosition) &
482 (isSingleWord() ? VAL : pVal[whichWord(bitPosition)])) != 0;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000483}
484
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000485bool APInt::operator==(const APInt& RHS) const {
Reid Spencer9ac44112007-02-26 23:38:21 +0000486 assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths");
Reid Spencer54362ca2007-02-20 23:40:25 +0000487 if (isSingleWord())
488 return VAL == RHS.VAL;
489
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000490 // Get some facts about the number of bits used in the two operands.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000491 uint32_t n1 = getActiveBits();
492 uint32_t n2 = RHS.getActiveBits();
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000493
494 // If the number of bits isn't the same, they aren't equal
Reid Spencer54362ca2007-02-20 23:40:25 +0000495 if (n1 != n2)
496 return false;
497
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000498 // If the number of bits fits in a word, we only need to compare the low word.
Reid Spencer54362ca2007-02-20 23:40:25 +0000499 if (n1 <= APINT_BITS_PER_WORD)
500 return pVal[0] == RHS.pVal[0];
501
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000502 // Otherwise, compare everything
Reid Spencer54362ca2007-02-20 23:40:25 +0000503 for (int i = whichWord(n1 - 1); i >= 0; --i)
504 if (pVal[i] != RHS.pVal[i])
505 return false;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000506 return true;
507}
508
Zhou Shenga3832fd2007-02-07 06:14:53 +0000509bool 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 +0000520bool APInt::ult(const APInt& RHS) const {
521 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
522 if (isSingleWord())
523 return VAL < RHS.VAL;
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000524
525 // Get active bit length of both operands
526 uint32_t n1 = getActiveBits();
527 uint32_t n2 = RHS.getActiveBits();
528
529 // If magnitude of LHS is less than RHS, return true.
530 if (n1 < n2)
531 return true;
532
533 // If magnitude of RHS is greather than LHS, return false.
534 if (n2 < n1)
535 return false;
536
537 // If they bot fit in a word, just compare the low order word
538 if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
539 return pVal[0] < RHS.pVal[0];
540
541 // Otherwise, compare all words
Reid Spencer1fa111e2007-02-27 18:23:40 +0000542 uint32_t topWord = whichWord(std::max(n1,n2)-1);
543 for (int i = topWord; i >= 0; --i) {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000544 if (pVal[i] > RHS.pVal[i])
Reid Spencere81d2da2007-02-16 22:36:51 +0000545 return false;
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000546 if (pVal[i] < RHS.pVal[i])
547 return true;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000548 }
549 return false;
550}
551
Reid Spencere81d2da2007-02-16 22:36:51 +0000552bool APInt::slt(const APInt& RHS) const {
553 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
Reid Spencera58f0582007-02-18 20:09:41 +0000554 if (isSingleWord()) {
555 int64_t lhsSext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
556 int64_t rhsSext = (int64_t(RHS.VAL) << (64-BitWidth)) >> (64-BitWidth);
557 return lhsSext < rhsSext;
Reid Spencere81d2da2007-02-16 22:36:51 +0000558 }
Reid Spencera58f0582007-02-18 20:09:41 +0000559
560 APInt lhs(*this);
Reid Spencer1fa111e2007-02-27 18:23:40 +0000561 APInt rhs(RHS);
562 bool lhsNeg = isNegative();
563 bool rhsNeg = rhs.isNegative();
564 if (lhsNeg) {
565 // Sign bit is set so perform two's complement to make it positive
Reid Spencera58f0582007-02-18 20:09:41 +0000566 lhs.flip();
567 lhs++;
568 }
Reid Spencer1fa111e2007-02-27 18:23:40 +0000569 if (rhsNeg) {
570 // Sign bit is set so perform two's complement to make it positive
Reid Spencera58f0582007-02-18 20:09:41 +0000571 rhs.flip();
572 rhs++;
573 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000574
575 // Now we have unsigned values to compare so do the comparison if necessary
576 // based on the negativeness of the values.
Reid Spencer1fa111e2007-02-27 18:23:40 +0000577 if (lhsNeg)
578 if (rhsNeg)
579 return lhs.ugt(rhs);
Reid Spencera58f0582007-02-18 20:09:41 +0000580 else
581 return true;
Reid Spencer1fa111e2007-02-27 18:23:40 +0000582 else if (rhsNeg)
Reid Spencera58f0582007-02-18 20:09:41 +0000583 return false;
584 else
585 return lhs.ult(rhs);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000586}
587
Reid Spenceraf0e9562007-02-18 18:38:44 +0000588APInt& APInt::set(uint32_t bitPosition) {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000589 if (isSingleWord())
590 VAL |= maskBit(bitPosition);
591 else
592 pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000593 return *this;
594}
595
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000596APInt& APInt::set() {
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000597 if (isSingleWord()) {
598 VAL = -1ULL;
599 return clearUnusedBits();
Zhou Shengb04973e2007-02-15 06:36:31 +0000600 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +0000601
602 // Set all the bits in all the words.
603 for (uint32_t i = 0; i < getNumWords() - 1; ++i)
604 pVal[i] = -1ULL;
605 // Clear the unused ones
606 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000607}
608
609/// Set the given bit to 0 whose position is given as "bitPosition".
610/// @brief Set a given bit to 0.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000611APInt& APInt::clear(uint32_t bitPosition) {
612 if (isSingleWord())
613 VAL &= ~maskBit(bitPosition);
614 else
615 pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000616 return *this;
617}
618
619/// @brief Set every bit to 0.
620APInt& APInt::clear() {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000621 if (isSingleWord())
622 VAL = 0;
Zhou Shenga3832fd2007-02-07 06:14:53 +0000623 else
Reid Spencera58f0582007-02-18 20:09:41 +0000624 memset(pVal, 0, getNumWords() * APINT_WORD_SIZE);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000625 return *this;
626}
627
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000628/// @brief Bitwise NOT operator. Performs a bitwise logical NOT operation on
629/// this APInt.
630APInt APInt::operator~() const {
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000631 APInt Result(*this);
632 Result.flip();
633 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000634}
635
636/// @brief Toggle every bit to its opposite value.
637APInt& APInt::flip() {
Reid Spencer9eec2412007-02-25 23:44:53 +0000638 if (isSingleWord()) {
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000639 VAL ^= -1ULL;
Reid Spencer9eec2412007-02-25 23:44:53 +0000640 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000641 }
Reid Spencer9eec2412007-02-25 23:44:53 +0000642 for (uint32_t i = 0; i < getNumWords(); ++i)
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000643 pVal[i] ^= -1ULL;
Reid Spencer9eec2412007-02-25 23:44:53 +0000644 return clearUnusedBits();
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000645}
646
647/// Toggle a given bit to its opposite value whose position is given
648/// as "bitPosition".
649/// @brief Toggles a given bit to its opposite value.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000650APInt& APInt::flip(uint32_t bitPosition) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000651 assert(bitPosition < BitWidth && "Out of the bit-width range!");
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000652 if ((*this)[bitPosition]) clear(bitPosition);
653 else set(bitPosition);
654 return *this;
655}
656
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000657/// getMaxValue - This function returns the largest value
658/// for an APInt of the specified bit-width and if isSign == true,
659/// it should be largest signed value, otherwise unsigned value.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000660APInt APInt::getMaxValue(uint32_t numBits, bool isSign) {
Reid Spencerf99a0ac2007-02-18 22:29:05 +0000661 APInt Result(numBits, 0);
662 Result.set();
663 if (isSign)
664 Result.clear(numBits - 1);
665 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000666}
667
668/// getMinValue - This function returns the smallest value for
669/// an APInt of the given bit-width and if isSign == true,
670/// it should be smallest signed value, otherwise zero.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000671APInt APInt::getMinValue(uint32_t numBits, bool isSign) {
Reid Spencerf99a0ac2007-02-18 22:29:05 +0000672 APInt Result(numBits, 0);
673 if (isSign)
674 Result.set(numBits - 1);
675 return Result;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000676}
677
678/// getAllOnesValue - This function returns an all-ones value for
679/// an APInt of the specified bit-width.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000680APInt APInt::getAllOnesValue(uint32_t numBits) {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000681 return getMaxValue(numBits, false);
682}
683
684/// getNullValue - This function creates an '0' value for an
685/// APInt of the specified bit-width.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000686APInt APInt::getNullValue(uint32_t numBits) {
Zhou Shengb04973e2007-02-15 06:36:31 +0000687 return getMinValue(numBits, false);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000688}
689
Reid Spencer794f4722007-02-26 21:02:27 +0000690uint64_t APInt::getHashValue() const {
Reid Spencer9ac44112007-02-26 23:38:21 +0000691 // Put the bit width into the low order bits.
692 uint64_t hash = BitWidth;
Reid Spencer794f4722007-02-26 21:02:27 +0000693
694 // Add the sum of the words to the hash.
695 if (isSingleWord())
Reid Spencer9ac44112007-02-26 23:38:21 +0000696 hash += VAL << 6; // clear separation of up to 64 bits
Reid Spencer794f4722007-02-26 21:02:27 +0000697 else
698 for (uint32_t i = 0; i < getNumWords(); ++i)
Reid Spencer9ac44112007-02-26 23:38:21 +0000699 hash += pVal[i] << 6; // clear sepration of up to 64 bits
Reid Spencer794f4722007-02-26 21:02:27 +0000700 return hash;
701}
702
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000703/// HiBits - This function returns the high "numBits" bits of this APInt.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000704APInt APInt::getHiBits(uint32_t numBits) const {
Reid Spencere81d2da2007-02-16 22:36:51 +0000705 return APIntOps::lshr(*this, BitWidth - numBits);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000706}
707
708/// LoBits - This function returns the low "numBits" bits of this APInt.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000709APInt APInt::getLoBits(uint32_t numBits) const {
Reid Spencere81d2da2007-02-16 22:36:51 +0000710 return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits),
711 BitWidth - numBits);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000712}
713
Reid Spencere81d2da2007-02-16 22:36:51 +0000714bool APInt::isPowerOf2() const {
715 return (!!*this) && !(*this & (*this - APInt(BitWidth,1)));
716}
717
Reid Spenceraf0e9562007-02-18 18:38:44 +0000718uint32_t APInt::countLeadingZeros() const {
Reid Spenceraf0e9562007-02-18 18:38:44 +0000719 uint32_t Count = 0;
Reid Spencere549c492007-02-21 00:29:48 +0000720 if (isSingleWord())
721 Count = CountLeadingZeros_64(VAL);
722 else {
723 for (uint32_t i = getNumWords(); i > 0u; --i) {
724 if (pVal[i-1] == 0)
725 Count += APINT_BITS_PER_WORD;
726 else {
727 Count += CountLeadingZeros_64(pVal[i-1]);
728 break;
729 }
730 }
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000731 }
Reid Spencerab2b2c82007-02-22 00:22:00 +0000732 uint32_t remainder = BitWidth % APINT_BITS_PER_WORD;
733 if (remainder)
734 Count -= APINT_BITS_PER_WORD - remainder;
735 return Count;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000736}
737
Reid Spenceraf0e9562007-02-18 18:38:44 +0000738uint32_t APInt::countTrailingZeros() const {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000739 if (isSingleWord())
Reid Spencer443b5702007-02-18 00:44:22 +0000740 return CountTrailingZeros_64(VAL);
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000741 uint32_t Count = 0;
742 uint32_t i = 0;
743 for (; i < getNumWords() && pVal[i] == 0; ++i)
744 Count += APINT_BITS_PER_WORD;
745 if (i < getNumWords())
746 Count += CountTrailingZeros_64(pVal[i]);
747 return Count;
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000748}
749
Reid Spenceraf0e9562007-02-18 18:38:44 +0000750uint32_t APInt::countPopulation() const {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000751 if (isSingleWord())
752 return CountPopulation_64(VAL);
Reid Spenceraf0e9562007-02-18 18:38:44 +0000753 uint32_t Count = 0;
754 for (uint32_t i = 0; i < getNumWords(); ++i)
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000755 Count += CountPopulation_64(pVal[i]);
756 return Count;
757}
758
Reid Spencere81d2da2007-02-16 22:36:51 +0000759APInt APInt::byteSwap() const {
760 assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
761 if (BitWidth == 16)
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000762 return APInt(BitWidth, ByteSwap_16(VAL));
Reid Spencere81d2da2007-02-16 22:36:51 +0000763 else if (BitWidth == 32)
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000764 return APInt(BitWidth, ByteSwap_32(VAL));
Reid Spencere81d2da2007-02-16 22:36:51 +0000765 else if (BitWidth == 48) {
Zhou Shengb04973e2007-02-15 06:36:31 +0000766 uint64_t Tmp1 = ((VAL >> 32) << 16) | (VAL & 0xFFFF);
767 Tmp1 = ByteSwap_32(Tmp1);
768 uint64_t Tmp2 = (VAL >> 16) & 0xFFFF;
769 Tmp2 = ByteSwap_16(Tmp2);
770 return
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000771 APInt(BitWidth,
772 (Tmp1 & 0xff) | ((Tmp1<<16) & 0xffff00000000ULL) | (Tmp2 << 16));
Reid Spencere81d2da2007-02-16 22:36:51 +0000773 } else if (BitWidth == 64)
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000774 return APInt(BitWidth, ByteSwap_64(VAL));
Zhou Shengb04973e2007-02-15 06:36:31 +0000775 else {
Reid Spencercd6f2bf2007-02-17 00:18:01 +0000776 APInt Result(BitWidth, 0);
Zhou Shengb04973e2007-02-15 06:36:31 +0000777 char *pByte = (char*)Result.pVal;
Reid Spencera58f0582007-02-18 20:09:41 +0000778 for (uint32_t i = 0; i < BitWidth / APINT_WORD_SIZE / 2; ++i) {
Zhou Shengb04973e2007-02-15 06:36:31 +0000779 char Tmp = pByte[i];
Reid Spencera58f0582007-02-18 20:09:41 +0000780 pByte[i] = pByte[BitWidth / APINT_WORD_SIZE - 1 - i];
781 pByte[BitWidth / APINT_WORD_SIZE - i - 1] = Tmp;
Zhou Shengb04973e2007-02-15 06:36:31 +0000782 }
783 return Result;
784 }
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000785}
786
Zhou Sheng0b706b12007-02-08 14:35:19 +0000787APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1,
788 const APInt& API2) {
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000789 APInt A = API1, B = API2;
790 while (!!B) {
791 APInt T = B;
Reid Spencere81d2da2007-02-16 22:36:51 +0000792 B = APIntOps::urem(A, B);
Zhou Shengfd43dcf2007-02-06 03:00:16 +0000793 A = T;
794 }
795 return A;
796}
Chris Lattner6ad4c142007-02-06 05:38:37 +0000797
Reid Spencer1fa111e2007-02-27 18:23:40 +0000798APInt llvm::APIntOps::RoundDoubleToAPInt(double Double, uint32_t width) {
Zhou Shengd93f00c2007-02-12 20:02:55 +0000799 union {
800 double D;
801 uint64_t I;
802 } T;
803 T.D = Double;
Reid Spencer30f44f32007-02-27 01:28:10 +0000804
805 // Get the sign bit from the highest order bit
Zhou Shengd93f00c2007-02-12 20:02:55 +0000806 bool isNeg = T.I >> 63;
Reid Spencer30f44f32007-02-27 01:28:10 +0000807
808 // Get the 11-bit exponent and adjust for the 1023 bit bias
Zhou Shengd93f00c2007-02-12 20:02:55 +0000809 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
Reid Spencer30f44f32007-02-27 01:28:10 +0000810
811 // If the exponent is negative, the value is < 0 so just return 0.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000812 if (exp < 0)
Reid Spencer30f44f32007-02-27 01:28:10 +0000813 return APInt(64u, 0u);
814
815 // Extract the mantissa by clearing the top 12 bits (sign + exponent).
816 uint64_t mantissa = (T.I & (~0ULL >> 12)) | 1ULL << 52;
817
818 // If the exponent doesn't shift all bits out of the mantissa
Zhou Shengd93f00c2007-02-12 20:02:55 +0000819 if (exp < 52)
Reid Spencer1fa111e2007-02-27 18:23:40 +0000820 return isNeg ? -APInt(width, mantissa >> (52 - exp)) :
821 APInt(width, mantissa >> (52 - exp));
822
823 // If the client didn't provide enough bits for us to shift the mantissa into
824 // then the result is undefined, just return 0
825 if (width <= exp - 52)
826 return APInt(width, 0);
Reid Spencer30f44f32007-02-27 01:28:10 +0000827
828 // Otherwise, we have to shift the mantissa bits up to the right location
Reid Spencer1fa111e2007-02-27 18:23:40 +0000829 APInt Tmp(width, mantissa);
Reid Spencere81d2da2007-02-16 22:36:51 +0000830 Tmp = Tmp.shl(exp - 52);
Zhou Shengd93f00c2007-02-12 20:02:55 +0000831 return isNeg ? -Tmp : Tmp;
832}
833
Reid Spencerdb3faa62007-02-13 22:41:58 +0000834/// RoundToDouble - This function convert this APInt to a double.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000835/// The layout for double is as following (IEEE Standard 754):
836/// --------------------------------------
837/// | Sign Exponent Fraction Bias |
838/// |-------------------------------------- |
839/// | 1[63] 11[62-52] 52[51-00] 1023 |
840/// --------------------------------------
Reid Spencere81d2da2007-02-16 22:36:51 +0000841double APInt::roundToDouble(bool isSigned) const {
Reid Spencer9c0696f2007-02-20 08:51:03 +0000842
843 // Handle the simple case where the value is contained in one uint64_t.
Reid Spencera58f0582007-02-18 20:09:41 +0000844 if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
845 if (isSigned) {
846 int64_t sext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth);
847 return double(sext);
848 } else
849 return double(VAL);
850 }
851
Reid Spencer9c0696f2007-02-20 08:51:03 +0000852 // Determine if the value is negative.
Reid Spencere81d2da2007-02-16 22:36:51 +0000853 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
Reid Spencer9c0696f2007-02-20 08:51:03 +0000854
855 // Construct the absolute value if we're negative.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000856 APInt Tmp(isNeg ? -(*this) : (*this));
Reid Spencer9c0696f2007-02-20 08:51:03 +0000857
858 // Figure out how many bits we're using.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000859 uint32_t n = Tmp.getActiveBits();
Zhou Shengd93f00c2007-02-12 20:02:55 +0000860
Reid Spencer9c0696f2007-02-20 08:51:03 +0000861 // The exponent (without bias normalization) is just the number of bits
862 // we are using. Note that the sign bit is gone since we constructed the
863 // absolute value.
864 uint64_t exp = n;
Zhou Shengd93f00c2007-02-12 20:02:55 +0000865
Reid Spencer9c0696f2007-02-20 08:51:03 +0000866 // Return infinity for exponent overflow
867 if (exp > 1023) {
868 if (!isSigned || !isNeg)
Reid Spencer61eb1802007-02-20 20:42:10 +0000869 return double(1.0E300 * 1.0E300); // positive infinity
Reid Spencer9c0696f2007-02-20 08:51:03 +0000870 else
Reid Spencer61eb1802007-02-20 20:42:10 +0000871 return double(-1.0E300 * 1.0E300); // negative infinity
Reid Spencer9c0696f2007-02-20 08:51:03 +0000872 }
873 exp += 1023; // Increment for 1023 bias
874
875 // Number of bits in mantissa is 52. To obtain the mantissa value, we must
876 // extract the high 52 bits from the correct words in pVal.
Zhou Shengd93f00c2007-02-12 20:02:55 +0000877 uint64_t mantissa;
Reid Spencer9c0696f2007-02-20 08:51:03 +0000878 unsigned hiWord = whichWord(n-1);
879 if (hiWord == 0) {
880 mantissa = Tmp.pVal[0];
881 if (n > 52)
882 mantissa >>= n - 52; // shift down, we want the top 52 bits.
883 } else {
884 assert(hiWord > 0 && "huh?");
885 uint64_t hibits = Tmp.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
886 uint64_t lobits = Tmp.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
887 mantissa = hibits | lobits;
888 }
889
Zhou Shengd93f00c2007-02-12 20:02:55 +0000890 // The leading bit of mantissa is implicit, so get rid of it.
Reid Spencer443b5702007-02-18 00:44:22 +0000891 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
Zhou Shengd93f00c2007-02-12 20:02:55 +0000892 union {
893 double D;
894 uint64_t I;
895 } T;
896 T.I = sign | (exp << 52) | mantissa;
897 return T.D;
898}
899
Reid Spencere81d2da2007-02-16 22:36:51 +0000900// Truncate to new width.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000901void APInt::trunc(uint32_t width) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000902 assert(width < BitWidth && "Invalid APInt Truncate request");
Reid Spencer9eec2412007-02-25 23:44:53 +0000903 assert(width >= IntegerType::MIN_INT_BITS && "Can't truncate to 0 bits");
904 uint32_t wordsBefore = getNumWords();
905 BitWidth = width;
906 uint32_t wordsAfter = getNumWords();
907 if (wordsBefore != wordsAfter) {
908 if (wordsAfter == 1) {
909 uint64_t *tmp = pVal;
910 VAL = pVal[0];
Reid Spencer9ac44112007-02-26 23:38:21 +0000911 delete [] tmp;
Reid Spencer9eec2412007-02-25 23:44:53 +0000912 } else {
913 uint64_t *newVal = getClearedMemory(wordsAfter);
914 for (uint32_t i = 0; i < wordsAfter; ++i)
915 newVal[i] = pVal[i];
Reid Spencer9ac44112007-02-26 23:38:21 +0000916 delete [] pVal;
Reid Spencer9eec2412007-02-25 23:44:53 +0000917 pVal = newVal;
918 }
919 }
920 clearUnusedBits();
Reid Spencere81d2da2007-02-16 22:36:51 +0000921}
922
923// Sign extend to a new width.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000924void APInt::sext(uint32_t width) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000925 assert(width > BitWidth && "Invalid APInt SignExtend request");
Reid Spencer9eec2412007-02-25 23:44:53 +0000926 assert(width <= IntegerType::MAX_INT_BITS && "Too many bits");
Reid Spencer9eec2412007-02-25 23:44:53 +0000927 // If the sign bit isn't set, this is the same as zext.
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000928 if (!isNegative()) {
Reid Spencer9eec2412007-02-25 23:44:53 +0000929 zext(width);
930 return;
931 }
932
933 // The sign bit is set. First, get some facts
934 uint32_t wordsBefore = getNumWords();
935 uint32_t wordBits = BitWidth % APINT_BITS_PER_WORD;
936 BitWidth = width;
937 uint32_t wordsAfter = getNumWords();
938
939 // Mask the high order word appropriately
940 if (wordsBefore == wordsAfter) {
941 uint32_t newWordBits = width % APINT_BITS_PER_WORD;
942 // The extension is contained to the wordsBefore-1th word.
943 uint64_t mask = (~0ULL >> (APINT_BITS_PER_WORD - newWordBits)) << wordBits;
944 if (wordsBefore == 1)
945 VAL |= mask;
946 else
947 pVal[wordsBefore-1] |= mask;
948 clearUnusedBits();
949 return;
950 }
951
Reid Spencerf30b1882007-02-25 23:54:00 +0000952 uint64_t mask = wordBits == 0 ? 0 : ~0ULL << wordBits;
Reid Spencer9eec2412007-02-25 23:44:53 +0000953 uint64_t *newVal = getMemory(wordsAfter);
954 if (wordsBefore == 1)
955 newVal[0] = VAL | mask;
956 else {
957 for (uint32_t i = 0; i < wordsBefore; ++i)
958 newVal[i] = pVal[i];
959 newVal[wordsBefore-1] |= mask;
960 }
961 for (uint32_t i = wordsBefore; i < wordsAfter; i++)
962 newVal[i] = -1ULL;
963 if (wordsBefore != 1)
Reid Spencer9ac44112007-02-26 23:38:21 +0000964 delete [] pVal;
Reid Spencer9eec2412007-02-25 23:44:53 +0000965 pVal = newVal;
966 clearUnusedBits();
Reid Spencere81d2da2007-02-16 22:36:51 +0000967}
968
969// Zero extend to a new width.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000970void APInt::zext(uint32_t width) {
Reid Spencere81d2da2007-02-16 22:36:51 +0000971 assert(width > BitWidth && "Invalid APInt ZeroExtend request");
Reid Spencer9eec2412007-02-25 23:44:53 +0000972 assert(width <= IntegerType::MAX_INT_BITS && "Too many bits");
973 uint32_t wordsBefore = getNumWords();
974 BitWidth = width;
975 uint32_t wordsAfter = getNumWords();
976 if (wordsBefore != wordsAfter) {
977 uint64_t *newVal = getClearedMemory(wordsAfter);
978 if (wordsBefore == 1)
979 newVal[0] = VAL;
980 else
981 for (uint32_t i = 0; i < wordsBefore; ++i)
982 newVal[i] = pVal[i];
983 if (wordsBefore != 1)
Reid Spencer9ac44112007-02-26 23:38:21 +0000984 delete [] pVal;
Reid Spencer9eec2412007-02-25 23:44:53 +0000985 pVal = newVal;
986 }
Reid Spencere81d2da2007-02-16 22:36:51 +0000987}
988
Zhou Shengff4304f2007-02-09 07:48:24 +0000989/// Arithmetic right-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +0000990/// @brief Arithmetic right-shift function.
Reid Spenceraf0e9562007-02-18 18:38:44 +0000991APInt APInt::ashr(uint32_t shiftAmt) const {
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000992 assert(shiftAmt <= BitWidth && "Invalid shift amount");
Reid Spencer24c4a8f2007-02-25 01:56:07 +0000993 if (isSingleWord()) {
994 if (shiftAmt == BitWidth)
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000995 return APInt(BitWidth, 0); // undefined
996 else {
997 uint32_t SignBit = APINT_BITS_PER_WORD - BitWidth;
Reid Spencer24c4a8f2007-02-25 01:56:07 +0000998 return APInt(BitWidth,
Reid Spencer47fbe9e2007-02-26 07:44:38 +0000999 (((int64_t(VAL) << SignBit) >> SignBit) >> shiftAmt));
1000 }
Zhou Sheng0b706b12007-02-08 14:35:19 +00001001 }
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001002
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001003 // If all the bits were shifted out, the result is 0 or -1. This avoids issues
1004 // with shifting by the size of the integer type, which produces undefined
1005 // results.
1006 if (shiftAmt == BitWidth)
1007 if (isNegative())
1008 return APInt(BitWidth, -1ULL);
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001009 else
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001010 return APInt(BitWidth, 0);
1011
1012 // Create some space for the result.
1013 uint64_t * val = new uint64_t[getNumWords()];
1014
1015 // If we are shifting less than a word, compute the shift with a simple carry
1016 if (shiftAmt < APINT_BITS_PER_WORD) {
1017 uint64_t carry = 0;
1018 for (int i = getNumWords()-1; i >= 0; --i) {
1019 val[i] = pVal[i] >> shiftAmt | carry;
1020 carry = pVal[i] << (APINT_BITS_PER_WORD - shiftAmt);
1021 }
1022 return APInt(val, BitWidth).clearUnusedBits();
1023 }
1024
1025 // Compute some values needed by the remaining shift algorithms
1026 uint32_t wordShift = shiftAmt % APINT_BITS_PER_WORD;
1027 uint32_t offset = shiftAmt / APINT_BITS_PER_WORD;
1028
1029 // If we are shifting whole words, just move whole words
1030 if (wordShift == 0) {
1031 for (uint32_t i = 0; i < getNumWords() - offset; ++i)
1032 val[i] = pVal[i+offset];
1033 for (uint32_t i = getNumWords()-offset; i < getNumWords(); i++)
1034 val[i] = (isNegative() ? -1ULL : 0);
1035 return APInt(val,BitWidth).clearUnusedBits();
1036 }
1037
1038 // Shift the low order words
1039 uint32_t breakWord = getNumWords() - offset -1;
1040 for (uint32_t i = 0; i < breakWord; ++i)
1041 val[i] = pVal[i+offset] >> wordShift |
1042 pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift);
1043 // Shift the break word.
1044 uint32_t SignBit = APINT_BITS_PER_WORD - (BitWidth % APINT_BITS_PER_WORD);
1045 val[breakWord] = uint64_t(
1046 (((int64_t(pVal[breakWord+offset]) << SignBit) >> SignBit) >> wordShift));
1047
1048 // Remaining words are 0 or -1
1049 for (uint32_t i = breakWord+1; i < getNumWords(); ++i)
1050 val[i] = (isNegative() ? -1ULL : 0);
1051 return APInt(val, BitWidth).clearUnusedBits();
Zhou Sheng0b706b12007-02-08 14:35:19 +00001052}
1053
Zhou Shengff4304f2007-02-09 07:48:24 +00001054/// Logical right-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +00001055/// @brief Logical right-shift function.
Reid Spenceraf0e9562007-02-18 18:38:44 +00001056APInt APInt::lshr(uint32_t shiftAmt) const {
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001057 if (isSingleWord())
1058 if (shiftAmt == BitWidth)
1059 return APInt(BitWidth, 0);
1060 else
1061 return APInt(BitWidth, this->VAL >> shiftAmt);
1062
Reid Spencerba81c2b2007-02-26 01:19:48 +00001063 // If all the bits were shifted out, the result is 0. This avoids issues
1064 // with shifting by the size of the integer type, which produces undefined
1065 // results. We define these "undefined results" to always be 0.
1066 if (shiftAmt == BitWidth)
1067 return APInt(BitWidth, 0);
1068
1069 // Create some space for the result.
1070 uint64_t * val = new uint64_t[getNumWords()];
1071
1072 // If we are shifting less than a word, compute the shift with a simple carry
1073 if (shiftAmt < APINT_BITS_PER_WORD) {
1074 uint64_t carry = 0;
1075 for (int i = getNumWords()-1; i >= 0; --i) {
1076 val[i] = pVal[i] >> shiftAmt | carry;
1077 carry = pVal[i] << (APINT_BITS_PER_WORD - shiftAmt);
1078 }
1079 return APInt(val, BitWidth).clearUnusedBits();
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001080 }
1081
Reid Spencerba81c2b2007-02-26 01:19:48 +00001082 // Compute some values needed by the remaining shift algorithms
1083 uint32_t wordShift = shiftAmt % APINT_BITS_PER_WORD;
1084 uint32_t offset = shiftAmt / APINT_BITS_PER_WORD;
1085
1086 // If we are shifting whole words, just move whole words
1087 if (wordShift == 0) {
1088 for (uint32_t i = 0; i < getNumWords() - offset; ++i)
1089 val[i] = pVal[i+offset];
1090 for (uint32_t i = getNumWords()-offset; i < getNumWords(); i++)
1091 val[i] = 0;
1092 return APInt(val,BitWidth).clearUnusedBits();
1093 }
1094
1095 // Shift the low order words
1096 uint32_t breakWord = getNumWords() - offset -1;
1097 for (uint32_t i = 0; i < breakWord; ++i)
1098 val[i] = pVal[i+offset] >> wordShift |
1099 pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift);
1100 // Shift the break word.
1101 val[breakWord] = pVal[breakWord+offset] >> wordShift;
1102
1103 // Remaining words are 0
1104 for (uint32_t i = breakWord+1; i < getNumWords(); ++i)
1105 val[i] = 0;
1106 return APInt(val, BitWidth).clearUnusedBits();
Zhou Sheng0b706b12007-02-08 14:35:19 +00001107}
1108
Zhou Shengff4304f2007-02-09 07:48:24 +00001109/// Left-shift this APInt by shiftAmt.
Zhou Sheng0b706b12007-02-08 14:35:19 +00001110/// @brief Left-shift function.
Reid Spenceraf0e9562007-02-18 18:38:44 +00001111APInt APInt::shl(uint32_t shiftAmt) const {
Reid Spencer5bce8542007-02-24 20:19:37 +00001112 assert(shiftAmt <= BitWidth && "Invalid shift amount");
Reid Spencer87553802007-02-25 00:56:44 +00001113 if (isSingleWord()) {
Reid Spencer5bce8542007-02-24 20:19:37 +00001114 if (shiftAmt == BitWidth)
Reid Spencer87553802007-02-25 00:56:44 +00001115 return APInt(BitWidth, 0); // avoid undefined shift results
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001116 return APInt(BitWidth, VAL << shiftAmt);
Zhou Sheng0b706b12007-02-08 14:35:19 +00001117 }
Reid Spencer5bce8542007-02-24 20:19:37 +00001118
Reid Spencer87553802007-02-25 00:56:44 +00001119 // If all the bits were shifted out, the result is 0. This avoids issues
1120 // with shifting by the size of the integer type, which produces undefined
1121 // results. We define these "undefined results" to always be 0.
1122 if (shiftAmt == BitWidth)
1123 return APInt(BitWidth, 0);
1124
1125 // Create some space for the result.
1126 uint64_t * val = new uint64_t[getNumWords()];
1127
1128 // If we are shifting less than a word, do it the easy way
1129 if (shiftAmt < APINT_BITS_PER_WORD) {
1130 uint64_t carry = 0;
Reid Spencer87553802007-02-25 00:56:44 +00001131 for (uint32_t i = 0; i < getNumWords(); i++) {
1132 val[i] = pVal[i] << shiftAmt | carry;
1133 carry = pVal[i] >> (APINT_BITS_PER_WORD - shiftAmt);
1134 }
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001135 return APInt(val, BitWidth).clearUnusedBits();
Reid Spencer5bce8542007-02-24 20:19:37 +00001136 }
1137
Reid Spencer87553802007-02-25 00:56:44 +00001138 // Compute some values needed by the remaining shift algorithms
1139 uint32_t wordShift = shiftAmt % APINT_BITS_PER_WORD;
1140 uint32_t offset = shiftAmt / APINT_BITS_PER_WORD;
1141
1142 // If we are shifting whole words, just move whole words
1143 if (wordShift == 0) {
1144 for (uint32_t i = 0; i < offset; i++)
1145 val[i] = 0;
1146 for (uint32_t i = offset; i < getNumWords(); i++)
1147 val[i] = pVal[i-offset];
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001148 return APInt(val,BitWidth).clearUnusedBits();
Reid Spencer5bce8542007-02-24 20:19:37 +00001149 }
Reid Spencer87553802007-02-25 00:56:44 +00001150
1151 // Copy whole words from this to Result.
1152 uint32_t i = getNumWords() - 1;
1153 for (; i > offset; --i)
1154 val[i] = pVal[i-offset] << wordShift |
1155 pVal[i-offset-1] >> (APINT_BITS_PER_WORD - wordShift);
Reid Spencer438d71e2007-02-25 01:08:58 +00001156 val[offset] = pVal[0] << wordShift;
Reid Spencer87553802007-02-25 00:56:44 +00001157 for (i = 0; i < offset; ++i)
1158 val[i] = 0;
Reid Spencer5d0d05c2007-02-25 19:32:03 +00001159 return APInt(val, BitWidth).clearUnusedBits();
Zhou Sheng0b706b12007-02-08 14:35:19 +00001160}
1161
Reid Spencer9c0696f2007-02-20 08:51:03 +00001162/// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
1163/// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
1164/// variables here have the same names as in the algorithm. Comments explain
1165/// the algorithm and any deviation from it.
1166static void KnuthDiv(uint32_t *u, uint32_t *v, uint32_t *q, uint32_t* r,
1167 uint32_t m, uint32_t n) {
1168 assert(u && "Must provide dividend");
1169 assert(v && "Must provide divisor");
1170 assert(q && "Must provide quotient");
Reid Spencer9d6c9192007-02-24 03:58:46 +00001171 assert(u != v && u != q && v != q && "Must us different memory");
Reid Spencer9c0696f2007-02-20 08:51:03 +00001172 assert(n>1 && "n must be > 1");
1173
1174 // Knuth uses the value b as the base of the number system. In our case b
1175 // is 2^31 so we just set it to -1u.
1176 uint64_t b = uint64_t(1) << 32;
1177
Reid Spencer9d6c9192007-02-24 03:58:46 +00001178 DEBUG(cerr << "KnuthDiv: m=" << m << " n=" << n << '\n');
1179 DEBUG(cerr << "KnuthDiv: original:");
1180 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << std::setbase(16) << u[i]);
1181 DEBUG(cerr << " by");
1182 DEBUG(for (int i = n; i >0; i--) cerr << " " << std::setbase(16) << v[i-1]);
1183 DEBUG(cerr << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001184 // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
1185 // u and v by d. Note that we have taken Knuth's advice here to use a power
1186 // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
1187 // 2 allows us to shift instead of multiply and it is easy to determine the
1188 // shift amount from the leading zeros. We are basically normalizing the u
1189 // and v so that its high bits are shifted to the top of v's range without
1190 // overflow. Note that this can require an extra word in u so that u must
1191 // be of length m+n+1.
1192 uint32_t shift = CountLeadingZeros_32(v[n-1]);
1193 uint32_t v_carry = 0;
1194 uint32_t u_carry = 0;
1195 if (shift) {
1196 for (uint32_t i = 0; i < m+n; ++i) {
1197 uint32_t u_tmp = u[i] >> (32 - shift);
1198 u[i] = (u[i] << shift) | u_carry;
1199 u_carry = u_tmp;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001200 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001201 for (uint32_t i = 0; i < n; ++i) {
1202 uint32_t v_tmp = v[i] >> (32 - shift);
1203 v[i] = (v[i] << shift) | v_carry;
1204 v_carry = v_tmp;
1205 }
1206 }
1207 u[m+n] = u_carry;
Reid Spencer9d6c9192007-02-24 03:58:46 +00001208 DEBUG(cerr << "KnuthDiv: normal:");
1209 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << std::setbase(16) << u[i]);
1210 DEBUG(cerr << " by");
1211 DEBUG(for (int i = n; i >0; i--) cerr << " " << std::setbase(16) << v[i-1]);
1212 DEBUG(cerr << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001213
1214 // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
1215 int j = m;
1216 do {
Reid Spencer9d6c9192007-02-24 03:58:46 +00001217 DEBUG(cerr << "KnuthDiv: quotient digit #" << j << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001218 // D3. [Calculate q'.].
1219 // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
1220 // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
1221 // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
1222 // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test
1223 // on v[n-2] determines at high speed most of the cases in which the trial
1224 // value qp is one too large, and it eliminates all cases where qp is two
1225 // too large.
Reid Spencer92904632007-02-23 01:57:13 +00001226 uint64_t dividend = ((uint64_t(u[j+n]) << 32) + u[j+n-1]);
Reid Spencer9d6c9192007-02-24 03:58:46 +00001227 DEBUG(cerr << "KnuthDiv: dividend == " << dividend << '\n');
Reid Spencer92904632007-02-23 01:57:13 +00001228 uint64_t qp = dividend / v[n-1];
1229 uint64_t rp = dividend % v[n-1];
Reid Spencer9c0696f2007-02-20 08:51:03 +00001230 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1231 qp--;
1232 rp += v[n-1];
Reid Spencer610fad82007-02-24 10:01:42 +00001233 if (rp < b && (qp == b || qp*v[n-2] > b*rp + u[j+n-2]))
Reid Spencer9d6c9192007-02-24 03:58:46 +00001234 qp--;
Reid Spencer92904632007-02-23 01:57:13 +00001235 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001236 DEBUG(cerr << "KnuthDiv: qp == " << qp << ", rp == " << rp << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001237
Reid Spencer92904632007-02-23 01:57:13 +00001238 // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with
1239 // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation
1240 // consists of a simple multiplication by a one-place number, combined with
Reid Spencer610fad82007-02-24 10:01:42 +00001241 // a subtraction.
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001242 bool isNeg = false;
Reid Spencer92904632007-02-23 01:57:13 +00001243 for (uint32_t i = 0; i < n; ++i) {
Reid Spencer610fad82007-02-24 10:01:42 +00001244 uint64_t u_tmp = uint64_t(u[j+i]) | (uint64_t(u[j+i+1]) << 32);
Reid Spencer9d6c9192007-02-24 03:58:46 +00001245 uint64_t subtrahend = uint64_t(qp) * uint64_t(v[i]);
Reid Spencer610fad82007-02-24 10:01:42 +00001246 bool borrow = subtrahend > u_tmp;
Reid Spencer9d6c9192007-02-24 03:58:46 +00001247 DEBUG(cerr << "KnuthDiv: u_tmp == " << u_tmp
Reid Spencer610fad82007-02-24 10:01:42 +00001248 << ", subtrahend == " << subtrahend
1249 << ", borrow = " << borrow << '\n');
Reid Spencer9d6c9192007-02-24 03:58:46 +00001250
Reid Spencer610fad82007-02-24 10:01:42 +00001251 uint64_t result = u_tmp - subtrahend;
1252 uint32_t k = j + i;
1253 u[k++] = result & (b-1); // subtract low word
1254 u[k++] = result >> 32; // subtract high word
1255 while (borrow && k <= m+n) { // deal with borrow to the left
1256 borrow = u[k] == 0;
1257 u[k]--;
1258 k++;
1259 }
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001260 isNeg |= borrow;
Reid Spencer610fad82007-02-24 10:01:42 +00001261 DEBUG(cerr << "KnuthDiv: u[j+i] == " << u[j+i] << ", u[j+i+1] == " <<
1262 u[j+i+1] << '\n');
Reid Spencer9d6c9192007-02-24 03:58:46 +00001263 }
1264 DEBUG(cerr << "KnuthDiv: after subtraction:");
1265 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << u[i]);
1266 DEBUG(cerr << '\n');
Reid Spencer610fad82007-02-24 10:01:42 +00001267 // The digits (u[j+n]...u[j]) should be kept positive; if the result of
1268 // this step is actually negative, (u[j+n]...u[j]) should be left as the
1269 // true value plus b**(n+1), namely as the b's complement of
Reid Spencer92904632007-02-23 01:57:13 +00001270 // the true value, and a "borrow" to the left should be remembered.
1271 //
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001272 if (isNeg) {
Reid Spencer610fad82007-02-24 10:01:42 +00001273 bool carry = true; // true because b's complement is "complement + 1"
1274 for (uint32_t i = 0; i <= m+n; ++i) {
1275 u[i] = ~u[i] + carry; // b's complement
1276 carry = carry && u[i] == 0;
Reid Spencer9d6c9192007-02-24 03:58:46 +00001277 }
Reid Spencer92904632007-02-23 01:57:13 +00001278 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001279 DEBUG(cerr << "KnuthDiv: after complement:");
1280 DEBUG(for (int i = m+n; i >=0; i--) cerr << " " << u[i]);
1281 DEBUG(cerr << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001282
1283 // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
1284 // negative, go to step D6; otherwise go on to step D7.
1285 q[j] = qp;
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001286 if (isNeg) {
Reid Spencer9c0696f2007-02-20 08:51:03 +00001287 // D6. [Add back]. The probability that this step is necessary is very
1288 // small, on the order of only 2/b. Make sure that test data accounts for
Reid Spencer92904632007-02-23 01:57:13 +00001289 // this possibility. Decrease q[j] by 1
1290 q[j]--;
1291 // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]).
1292 // A carry will occur to the left of u[j+n], and it should be ignored
1293 // since it cancels with the borrow that occurred in D4.
1294 bool carry = false;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001295 for (uint32_t i = 0; i < n; i++) {
Reid Spencer9d6c9192007-02-24 03:58:46 +00001296 uint32_t limit = std::min(u[j+i],v[i]);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001297 u[j+i] += v[i] + carry;
Reid Spencer9d6c9192007-02-24 03:58:46 +00001298 carry = u[j+i] < limit || (carry && u[j+i] == limit);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001299 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001300 u[j+n] += carry;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001301 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001302 DEBUG(cerr << "KnuthDiv: after correction:");
1303 DEBUG(for (int i = m+n; i >=0; i--) cerr <<" " << u[i]);
1304 DEBUG(cerr << "\nKnuthDiv: digit result = " << q[j] << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001305
Reid Spencer92904632007-02-23 01:57:13 +00001306 // D7. [Loop on j.] Decrease j by one. Now if j >= 0, go back to D3.
1307 } while (--j >= 0);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001308
Reid Spencer9d6c9192007-02-24 03:58:46 +00001309 DEBUG(cerr << "KnuthDiv: quotient:");
1310 DEBUG(for (int i = m; i >=0; i--) cerr <<" " << q[i]);
1311 DEBUG(cerr << '\n');
1312
Reid Spencer9c0696f2007-02-20 08:51:03 +00001313 // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
1314 // remainder may be obtained by dividing u[...] by d. If r is non-null we
1315 // compute the remainder (urem uses this).
1316 if (r) {
1317 // The value d is expressed by the "shift" value above since we avoided
1318 // multiplication by d by using a shift left. So, all we have to do is
1319 // shift right here. In order to mak
Reid Spencer1050ec52007-02-24 20:38:01 +00001320 if (shift) {
1321 uint32_t carry = 0;
1322 DEBUG(cerr << "KnuthDiv: remainder:");
1323 for (int i = n-1; i >= 0; i--) {
1324 r[i] = (u[i] >> shift) | carry;
1325 carry = u[i] << (32 - shift);
1326 DEBUG(cerr << " " << r[i]);
1327 }
1328 } else {
1329 for (int i = n-1; i >= 0; i--) {
1330 r[i] = u[i];
1331 DEBUG(cerr << " " << r[i]);
1332 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001333 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001334 DEBUG(cerr << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001335 }
Reid Spencer9d6c9192007-02-24 03:58:46 +00001336 DEBUG(cerr << std::setbase(10) << '\n');
Reid Spencer9c0696f2007-02-20 08:51:03 +00001337}
1338
Reid Spencer9c0696f2007-02-20 08:51:03 +00001339void APInt::divide(const APInt LHS, uint32_t lhsWords,
1340 const APInt &RHS, uint32_t rhsWords,
1341 APInt *Quotient, APInt *Remainder)
1342{
1343 assert(lhsWords >= rhsWords && "Fractional result");
1344
1345 // First, compose the values into an array of 32-bit words instead of
1346 // 64-bit words. This is a necessity of both the "short division" algorithm
1347 // and the the Knuth "classical algorithm" which requires there to be native
1348 // operations for +, -, and * on an m bit value with an m*2 bit result. We
1349 // can't use 64-bit operands here because we don't have native results of
1350 // 128-bits. Furthremore, casting the 64-bit values to 32-bit values won't
1351 // work on large-endian machines.
1352 uint64_t mask = ~0ull >> (sizeof(uint32_t)*8);
1353 uint32_t n = rhsWords * 2;
1354 uint32_t m = (lhsWords * 2) - n;
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001355
1356 // Allocate space for the temporary values we need either on the stack, if
1357 // it will fit, or on the heap if it won't.
1358 uint32_t SPACE[128];
1359 uint32_t *U = 0;
1360 uint32_t *V = 0;
1361 uint32_t *Q = 0;
1362 uint32_t *R = 0;
1363 if ((Remainder?4:3)*n+2*m+1 <= 128) {
1364 U = &SPACE[0];
1365 V = &SPACE[m+n+1];
1366 Q = &SPACE[(m+n+1) + n];
1367 if (Remainder)
1368 R = &SPACE[(m+n+1) + n + (m+n)];
1369 } else {
1370 U = new uint32_t[m + n + 1];
1371 V = new uint32_t[n];
1372 Q = new uint32_t[m+n];
1373 if (Remainder)
1374 R = new uint32_t[n];
1375 }
1376
1377 // Initialize the dividend
Reid Spencer9c0696f2007-02-20 08:51:03 +00001378 memset(U, 0, (m+n+1)*sizeof(uint32_t));
1379 for (unsigned i = 0; i < lhsWords; ++i) {
Reid Spencer15aab8a2007-02-22 00:58:45 +00001380 uint64_t tmp = (LHS.getNumWords() == 1 ? LHS.VAL : LHS.pVal[i]);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001381 U[i * 2] = tmp & mask;
1382 U[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1383 }
1384 U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
1385
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001386 // Initialize the divisor
Reid Spencer9c0696f2007-02-20 08:51:03 +00001387 memset(V, 0, (n)*sizeof(uint32_t));
1388 for (unsigned i = 0; i < rhsWords; ++i) {
Reid Spencer15aab8a2007-02-22 00:58:45 +00001389 uint64_t tmp = (RHS.getNumWords() == 1 ? RHS.VAL : RHS.pVal[i]);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001390 V[i * 2] = tmp & mask;
1391 V[i * 2 + 1] = tmp >> (sizeof(uint32_t)*8);
1392 }
1393
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001394 // initialize the quotient and remainder
Reid Spencer9c0696f2007-02-20 08:51:03 +00001395 memset(Q, 0, (m+n) * sizeof(uint32_t));
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001396 if (Remainder)
Reid Spencer9c0696f2007-02-20 08:51:03 +00001397 memset(R, 0, n * sizeof(uint32_t));
Reid Spencer9c0696f2007-02-20 08:51:03 +00001398
1399 // Now, adjust m and n for the Knuth division. n is the number of words in
1400 // the divisor. m is the number of words by which the dividend exceeds the
1401 // divisor (i.e. m+n is the length of the dividend). These sizes must not
1402 // contain any zero words or the Knuth algorithm fails.
1403 for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
1404 n--;
1405 m++;
1406 }
1407 for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
1408 m--;
1409
1410 // If we're left with only a single word for the divisor, Knuth doesn't work
1411 // so we implement the short division algorithm here. This is much simpler
1412 // and faster because we are certain that we can divide a 64-bit quantity
1413 // by a 32-bit quantity at hardware speed and short division is simply a
1414 // series of such operations. This is just like doing short division but we
1415 // are using base 2^32 instead of base 10.
1416 assert(n != 0 && "Divide by zero?");
1417 if (n == 1) {
1418 uint32_t divisor = V[0];
1419 uint32_t remainder = 0;
1420 for (int i = m+n-1; i >= 0; i--) {
1421 uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i];
1422 if (partial_dividend == 0) {
1423 Q[i] = 0;
1424 remainder = 0;
1425 } else if (partial_dividend < divisor) {
1426 Q[i] = 0;
1427 remainder = partial_dividend;
1428 } else if (partial_dividend == divisor) {
1429 Q[i] = 1;
1430 remainder = 0;
1431 } else {
1432 Q[i] = partial_dividend / divisor;
1433 remainder = partial_dividend - (Q[i] * divisor);
1434 }
1435 }
1436 if (R)
1437 R[0] = remainder;
1438 } else {
1439 // Now we're ready to invoke the Knuth classical divide algorithm. In this
1440 // case n > 1.
1441 KnuthDiv(U, V, Q, R, m, n);
1442 }
1443
1444 // If the caller wants the quotient
1445 if (Quotient) {
1446 // Set up the Quotient value's memory.
1447 if (Quotient->BitWidth != LHS.BitWidth) {
1448 if (Quotient->isSingleWord())
1449 Quotient->VAL = 0;
1450 else
Reid Spencer9ac44112007-02-26 23:38:21 +00001451 delete [] Quotient->pVal;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001452 Quotient->BitWidth = LHS.BitWidth;
1453 if (!Quotient->isSingleWord())
Reid Spencere0cdd332007-02-21 08:21:52 +00001454 Quotient->pVal = getClearedMemory(Quotient->getNumWords());
Reid Spencer9c0696f2007-02-20 08:51:03 +00001455 } else
1456 Quotient->clear();
1457
1458 // The quotient is in Q. Reconstitute the quotient into Quotient's low
1459 // order words.
1460 if (lhsWords == 1) {
1461 uint64_t tmp =
1462 uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2));
1463 if (Quotient->isSingleWord())
1464 Quotient->VAL = tmp;
1465 else
1466 Quotient->pVal[0] = tmp;
1467 } else {
1468 assert(!Quotient->isSingleWord() && "Quotient APInt not large enough");
1469 for (unsigned i = 0; i < lhsWords; ++i)
1470 Quotient->pVal[i] =
1471 uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1472 }
1473 }
1474
1475 // If the caller wants the remainder
1476 if (Remainder) {
1477 // Set up the Remainder value's memory.
1478 if (Remainder->BitWidth != RHS.BitWidth) {
1479 if (Remainder->isSingleWord())
1480 Remainder->VAL = 0;
1481 else
Reid Spencer9ac44112007-02-26 23:38:21 +00001482 delete [] Remainder->pVal;
Reid Spencer9c0696f2007-02-20 08:51:03 +00001483 Remainder->BitWidth = RHS.BitWidth;
1484 if (!Remainder->isSingleWord())
Reid Spencere0cdd332007-02-21 08:21:52 +00001485 Remainder->pVal = getClearedMemory(Remainder->getNumWords());
Reid Spencer9c0696f2007-02-20 08:51:03 +00001486 } else
1487 Remainder->clear();
1488
1489 // The remainder is in R. Reconstitute the remainder into Remainder's low
1490 // order words.
1491 if (rhsWords == 1) {
1492 uint64_t tmp =
1493 uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2));
1494 if (Remainder->isSingleWord())
1495 Remainder->VAL = tmp;
1496 else
1497 Remainder->pVal[0] = tmp;
1498 } else {
1499 assert(!Remainder->isSingleWord() && "Remainder APInt not large enough");
1500 for (unsigned i = 0; i < rhsWords; ++i)
1501 Remainder->pVal[i] =
1502 uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1503 }
1504 }
1505
1506 // Clean up the memory we allocated.
Reid Spencer24c4a8f2007-02-25 01:56:07 +00001507 if (U != &SPACE[0]) {
1508 delete [] U;
1509 delete [] V;
1510 delete [] Q;
1511 delete [] R;
1512 }
Reid Spencer5e0a8512007-02-17 03:16:00 +00001513}
1514
Reid Spencere81d2da2007-02-16 22:36:51 +00001515APInt APInt::udiv(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +00001516 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer71bd08f2007-02-17 02:07:07 +00001517
1518 // First, deal with the easy case
1519 if (isSingleWord()) {
1520 assert(RHS.VAL != 0 && "Divide by zero?");
1521 return APInt(BitWidth, VAL / RHS.VAL);
Zhou Sheng0b706b12007-02-08 14:35:19 +00001522 }
Reid Spencer71bd08f2007-02-17 02:07:07 +00001523
Reid Spencer71bd08f2007-02-17 02:07:07 +00001524 // Get some facts about the LHS and RHS number of bits and words
Reid Spenceraf0e9562007-02-18 18:38:44 +00001525 uint32_t rhsBits = RHS.getActiveBits();
1526 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001527 assert(rhsWords && "Divided by zero???");
Reid Spencer9c0696f2007-02-20 08:51:03 +00001528 uint32_t lhsBits = this->getActiveBits();
Reid Spenceraf0e9562007-02-18 18:38:44 +00001529 uint32_t lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001530
1531 // Deal with some degenerate cases
1532 if (!lhsWords)
Reid Spencere0cdd332007-02-21 08:21:52 +00001533 // 0 / X ===> 0
1534 return APInt(BitWidth, 0);
1535 else if (lhsWords < rhsWords || this->ult(RHS)) {
1536 // X / Y ===> 0, iff X < Y
1537 return APInt(BitWidth, 0);
1538 } else if (*this == RHS) {
1539 // X / X ===> 1
1540 return APInt(BitWidth, 1);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001541 } else if (lhsWords == 1 && rhsWords == 1) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001542 // All high words are zero, just use native divide
Reid Spencere0cdd332007-02-21 08:21:52 +00001543 return APInt(BitWidth, this->pVal[0] / RHS.pVal[0]);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001544 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001545
1546 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1547 APInt Quotient(1,0); // to hold result.
1548 divide(*this, lhsWords, RHS, rhsWords, &Quotient, 0);
1549 return Quotient;
Zhou Sheng0b706b12007-02-08 14:35:19 +00001550}
1551
Reid Spencere81d2da2007-02-16 22:36:51 +00001552APInt APInt::urem(const APInt& RHS) const {
Reid Spencercd6f2bf2007-02-17 00:18:01 +00001553 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer71bd08f2007-02-17 02:07:07 +00001554 if (isSingleWord()) {
1555 assert(RHS.VAL != 0 && "Remainder by zero?");
1556 return APInt(BitWidth, VAL % RHS.VAL);
Zhou Sheng0b706b12007-02-08 14:35:19 +00001557 }
Reid Spencer71bd08f2007-02-17 02:07:07 +00001558
Reid Spencere0cdd332007-02-21 08:21:52 +00001559 // Get some facts about the LHS
1560 uint32_t lhsBits = getActiveBits();
1561 uint32_t lhsWords = !lhsBits ? 0 : (whichWord(lhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001562
1563 // Get some facts about the RHS
Reid Spenceraf0e9562007-02-18 18:38:44 +00001564 uint32_t rhsBits = RHS.getActiveBits();
1565 uint32_t rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001566 assert(rhsWords && "Performing remainder operation by zero ???");
1567
Reid Spencer71bd08f2007-02-17 02:07:07 +00001568 // Check the degenerate cases
Reid Spencer9c0696f2007-02-20 08:51:03 +00001569 if (lhsWords == 0) {
Reid Spencere0cdd332007-02-21 08:21:52 +00001570 // 0 % Y ===> 0
1571 return APInt(BitWidth, 0);
1572 } else if (lhsWords < rhsWords || this->ult(RHS)) {
1573 // X % Y ===> X, iff X < Y
1574 return *this;
1575 } else if (*this == RHS) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001576 // X % X == 0;
Reid Spencere0cdd332007-02-21 08:21:52 +00001577 return APInt(BitWidth, 0);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001578 } else if (lhsWords == 1) {
Reid Spencer71bd08f2007-02-17 02:07:07 +00001579 // All high words are zero, just use native remainder
Reid Spencere0cdd332007-02-21 08:21:52 +00001580 return APInt(BitWidth, pVal[0] % RHS.pVal[0]);
Reid Spencer71bd08f2007-02-17 02:07:07 +00001581 }
Reid Spencer9c0696f2007-02-20 08:51:03 +00001582
1583 // We have to compute it the hard way. Invoke the Knute divide algorithm.
1584 APInt Remainder(1,0);
1585 divide(*this, lhsWords, RHS, rhsWords, 0, &Remainder);
1586 return Remainder;
Zhou Sheng0b706b12007-02-08 14:35:19 +00001587}
Reid Spencer5e0a8512007-02-17 03:16:00 +00001588
Reid Spencer385f7542007-02-21 03:55:44 +00001589void APInt::fromString(uint32_t numbits, const char *str, uint32_t slen,
Reid Spencer5e0a8512007-02-17 03:16:00 +00001590 uint8_t radix) {
Reid Spencer385f7542007-02-21 03:55:44 +00001591 // Check our assumptions here
Reid Spencer5e0a8512007-02-17 03:16:00 +00001592 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1593 "Radix should be 2, 8, 10, or 16!");
Reid Spencer385f7542007-02-21 03:55:44 +00001594 assert(str && "String is null?");
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001595 bool isNeg = str[0] == '-';
1596 if (isNeg)
Reid Spencer9eec2412007-02-25 23:44:53 +00001597 str++, slen--;
Reid Spencer385f7542007-02-21 03:55:44 +00001598 assert(slen <= numbits || radix != 2 && "Insufficient bit width");
1599 assert(slen*3 <= numbits || radix != 8 && "Insufficient bit width");
1600 assert(slen*4 <= numbits || radix != 16 && "Insufficient bit width");
1601 assert((slen*64)/20 <= numbits || radix != 10 && "Insufficient bit width");
1602
1603 // Allocate memory
1604 if (!isSingleWord())
1605 pVal = getClearedMemory(getNumWords());
1606
1607 // Figure out if we can shift instead of multiply
1608 uint32_t shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0);
1609
1610 // Set up an APInt for the digit to add outside the loop so we don't
1611 // constantly construct/destruct it.
1612 APInt apdigit(getBitWidth(), 0);
1613 APInt apradix(getBitWidth(), radix);
1614
1615 // Enter digit traversal loop
1616 for (unsigned i = 0; i < slen; i++) {
1617 // Get a digit
1618 uint32_t digit = 0;
1619 char cdigit = str[i];
1620 if (isdigit(cdigit))
1621 digit = cdigit - '0';
1622 else if (isxdigit(cdigit))
1623 if (cdigit >= 'a')
1624 digit = cdigit - 'a' + 10;
1625 else if (cdigit >= 'A')
1626 digit = cdigit - 'A' + 10;
1627 else
1628 assert(0 && "huh?");
1629 else
1630 assert(0 && "Invalid character in digit string");
1631
1632 // Shift or multiple the value by the radix
1633 if (shift)
1634 this->shl(shift);
1635 else
1636 *this *= apradix;
1637
1638 // Add in the digit we just interpreted
Reid Spencer5bce8542007-02-24 20:19:37 +00001639 if (apdigit.isSingleWord())
1640 apdigit.VAL = digit;
1641 else
1642 apdigit.pVal[0] = digit;
Reid Spencer385f7542007-02-21 03:55:44 +00001643 *this += apdigit;
Reid Spencer5e0a8512007-02-17 03:16:00 +00001644 }
Reid Spencer9eec2412007-02-25 23:44:53 +00001645 // If its negative, put it in two's complement form
Reid Spencer47fbe9e2007-02-26 07:44:38 +00001646 if (isNeg) {
1647 (*this)--;
Reid Spencer9eec2412007-02-25 23:44:53 +00001648 this->flip();
Reid Spencer9eec2412007-02-25 23:44:53 +00001649 }
Reid Spencer5e0a8512007-02-17 03:16:00 +00001650}
Reid Spencer9c0696f2007-02-20 08:51:03 +00001651
Reid Spencer9c0696f2007-02-20 08:51:03 +00001652std::string APInt::toString(uint8_t radix, bool wantSigned) const {
1653 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2) &&
1654 "Radix should be 2, 8, 10, or 16!");
1655 static const char *digits[] = {
1656 "0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"
1657 };
1658 std::string result;
1659 uint32_t bits_used = getActiveBits();
1660 if (isSingleWord()) {
1661 char buf[65];
1662 const char *format = (radix == 10 ? (wantSigned ? "%lld" : "%llu") :
1663 (radix == 16 ? "%llX" : (radix == 8 ? "%llo" : 0)));
1664 if (format) {
1665 if (wantSigned) {
1666 int64_t sextVal = (int64_t(VAL) << (APINT_BITS_PER_WORD-BitWidth)) >>
1667 (APINT_BITS_PER_WORD-BitWidth);
1668 sprintf(buf, format, sextVal);
1669 } else
1670 sprintf(buf, format, VAL);
1671 } else {
1672 memset(buf, 0, 65);
1673 uint64_t v = VAL;
1674 while (bits_used) {
1675 uint32_t bit = v & 1;
1676 bits_used--;
1677 buf[bits_used] = digits[bit][0];
1678 v >>=1;
1679 }
1680 }
1681 result = buf;
1682 return result;
1683 }
1684
1685 if (radix != 10) {
1686 uint64_t mask = radix - 1;
1687 uint32_t shift = (radix == 16 ? 4 : radix == 8 ? 3 : 1);
1688 uint32_t nibbles = APINT_BITS_PER_WORD / shift;
1689 for (uint32_t i = 0; i < getNumWords(); ++i) {
1690 uint64_t value = pVal[i];
1691 for (uint32_t j = 0; j < nibbles; ++j) {
1692 result.insert(0, digits[ value & mask ]);
1693 value >>= shift;
1694 }
1695 }
1696 return result;
1697 }
1698
1699 APInt tmp(*this);
1700 APInt divisor(4, radix);
1701 APInt zero(tmp.getBitWidth(), 0);
1702 size_t insert_at = 0;
1703 if (wantSigned && tmp[BitWidth-1]) {
1704 // They want to print the signed version and it is a negative value
1705 // Flip the bits and add one to turn it into the equivalent positive
1706 // value and put a '-' in the result.
1707 tmp.flip();
1708 tmp++;
1709 result = "-";
1710 insert_at = 1;
1711 }
Reid Spencere549c492007-02-21 00:29:48 +00001712 if (tmp == APInt(tmp.getBitWidth(), 0))
Reid Spencer9c0696f2007-02-20 08:51:03 +00001713 result = "0";
1714 else while (tmp.ne(zero)) {
1715 APInt APdigit(1,0);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001716 APInt tmp2(tmp.getBitWidth(), 0);
Reid Spencer385f7542007-02-21 03:55:44 +00001717 divide(tmp, tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2,
1718 &APdigit);
Reid Spencer794f4722007-02-26 21:02:27 +00001719 uint32_t digit = APdigit.getZExtValue();
Reid Spencer385f7542007-02-21 03:55:44 +00001720 assert(digit < radix && "divide failed");
1721 result.insert(insert_at,digits[digit]);
Reid Spencer9c0696f2007-02-20 08:51:03 +00001722 tmp = tmp2;
1723 }
1724
1725 return result;
1726}
1727
Reid Spencer385f7542007-02-21 03:55:44 +00001728#ifndef NDEBUG
1729void APInt::dump() const
1730{
Reid Spencer610fad82007-02-24 10:01:42 +00001731 cerr << "APInt(" << BitWidth << ")=" << std::setbase(16);
Reid Spencer385f7542007-02-21 03:55:44 +00001732 if (isSingleWord())
Reid Spencer610fad82007-02-24 10:01:42 +00001733 cerr << VAL;
Reid Spencer385f7542007-02-21 03:55:44 +00001734 else for (unsigned i = getNumWords(); i > 0; i--) {
Reid Spencer610fad82007-02-24 10:01:42 +00001735 cerr << pVal[i-1] << " ";
Reid Spencer385f7542007-02-21 03:55:44 +00001736 }
Reid Spencer610fad82007-02-24 10:01:42 +00001737 cerr << " (" << this->toString(10, false) << ")\n" << std::setbase(10);
Reid Spencer385f7542007-02-21 03:55:44 +00001738}
1739#endif