blob: 66eee99c6ec2b01279861c1508d72f6d168fb8c0 [file] [log] [blame]
Zhou Shengdac63782007-02-06 03:00:16 +00001//===-- APInt.cpp - Implement APInt class ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Zhou Shengdac63782007-02-06 03:00:16 +00007//
8//===----------------------------------------------------------------------===//
9//
Reid Spencera41e93b2007-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 Shengdac63782007-02-06 03:00:16 +000012//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/ADT/APInt.h"
Mehdi Amini47b292d2016-04-16 07:51:28 +000016#include "llvm/ADT/ArrayRef.h"
Ted Kremenek5c75d542008-01-19 04:23:33 +000017#include "llvm/ADT/FoldingSet.h"
Chandler Carruth71bd7d12012-03-04 12:02:57 +000018#include "llvm/ADT/Hashing.h"
Chris Lattner17f71652008-08-17 07:19:36 +000019#include "llvm/ADT/SmallString.h"
Chandler Carruth71bd7d12012-03-04 12:02:57 +000020#include "llvm/ADT/StringRef.h"
Reid Spencera5e0d202007-02-24 03:58:46 +000021#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000022#include "llvm/Support/ErrorHandling.h"
Zhou Shengdac63782007-02-06 03:00:16 +000023#include "llvm/Support/MathExtras.h"
Chris Lattner0c19df42008-08-23 22:23:09 +000024#include "llvm/Support/raw_ostream.h"
Chris Lattner17f71652008-08-17 07:19:36 +000025#include <cmath>
Zhou Shengdac63782007-02-06 03:00:16 +000026#include <cstdlib>
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include <cstring>
28#include <limits>
Zhou Shengdac63782007-02-06 03:00:16 +000029using namespace llvm;
30
Chandler Carruth64648262014-04-22 03:07:47 +000031#define DEBUG_TYPE "apint"
32
Reid Spencera41e93b2007-02-25 19:32:03 +000033/// A utility function for allocating memory, checking for allocation failures,
34/// and ensuring the contents are zeroed.
Chris Lattner77527f52009-01-21 18:09:24 +000035inline static uint64_t* getClearedMemory(unsigned numWords) {
Reid Spencera856b6e2007-02-18 18:38:44 +000036 uint64_t * result = new uint64_t[numWords];
37 assert(result && "APInt memory allocation fails!");
38 memset(result, 0, numWords * sizeof(uint64_t));
39 return result;
Zhou Sheng94b623a2007-02-06 06:04:53 +000040}
41
Eric Christopher820256b2009-08-21 04:06:45 +000042/// A utility function for allocating memory and checking for allocation
Reid Spencera41e93b2007-02-25 19:32:03 +000043/// failure. The content is not zeroed.
Chris Lattner77527f52009-01-21 18:09:24 +000044inline static uint64_t* getMemory(unsigned numWords) {
Reid Spencera856b6e2007-02-18 18:38:44 +000045 uint64_t * result = new uint64_t[numWords];
46 assert(result && "APInt memory allocation fails!");
47 return result;
48}
49
Erick Tryzelaardadb15712009-08-21 03:15:28 +000050/// A utility function that converts a character to a digit.
51inline static unsigned getDigit(char cdigit, uint8_t radix) {
Erick Tryzelaar60964092009-08-21 06:48:37 +000052 unsigned r;
53
Douglas Gregor663c0682011-09-14 15:54:46 +000054 if (radix == 16 || radix == 36) {
Erick Tryzelaar60964092009-08-21 06:48:37 +000055 r = cdigit - '0';
56 if (r <= 9)
57 return r;
58
59 r = cdigit - 'A';
Douglas Gregorc98ac852011-09-20 18:33:29 +000060 if (r <= radix - 11U)
Erick Tryzelaar60964092009-08-21 06:48:37 +000061 return r + 10;
62
63 r = cdigit - 'a';
Douglas Gregorc98ac852011-09-20 18:33:29 +000064 if (r <= radix - 11U)
Erick Tryzelaar60964092009-08-21 06:48:37 +000065 return r + 10;
Douglas Gregore4e20f42011-09-20 18:11:52 +000066
67 radix = 10;
Erick Tryzelaardadb15712009-08-21 03:15:28 +000068 }
69
Erick Tryzelaar60964092009-08-21 06:48:37 +000070 r = cdigit - '0';
71 if (r < radix)
72 return r;
73
74 return -1U;
Erick Tryzelaardadb15712009-08-21 03:15:28 +000075}
76
77
Pawel Bylica68304012016-06-27 08:31:48 +000078void APInt::initSlowCase(uint64_t val, bool isSigned) {
Chris Lattner1ac3e252008-08-20 17:02:31 +000079 pVal = getClearedMemory(getNumWords());
80 pVal[0] = val;
Eric Christopher820256b2009-08-21 04:06:45 +000081 if (isSigned && int64_t(val) < 0)
Chris Lattner1ac3e252008-08-20 17:02:31 +000082 for (unsigned i = 1; i < getNumWords(); ++i)
83 pVal[i] = -1ULL;
Zhou Shengdac63782007-02-06 03:00:16 +000084}
85
Chris Lattnerd57b7602008-10-11 22:07:19 +000086void APInt::initSlowCase(const APInt& that) {
87 pVal = getMemory(getNumWords());
88 memcpy(pVal, that.pVal, getNumWords() * APINT_WORD_SIZE);
89}
90
Jeffrey Yasskin7a162882011-07-18 21:45:40 +000091void APInt::initFromArray(ArrayRef<uint64_t> bigVal) {
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +000092 assert(BitWidth && "Bitwidth too small");
Jeffrey Yasskin7a162882011-07-18 21:45:40 +000093 assert(bigVal.data() && "Null pointer detected!");
Zhou Shengdac63782007-02-06 03:00:16 +000094 if (isSingleWord())
Reid Spencerdf6cf5a2007-02-24 10:01:42 +000095 VAL = bigVal[0];
Zhou Shengdac63782007-02-06 03:00:16 +000096 else {
Reid Spencerdf6cf5a2007-02-24 10:01:42 +000097 // Get memory, cleared to 0
98 pVal = getClearedMemory(getNumWords());
99 // Calculate the number of words to copy
Jeffrey Yasskin7a162882011-07-18 21:45:40 +0000100 unsigned words = std::min<unsigned>(bigVal.size(), getNumWords());
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000101 // Copy the words from bigVal to pVal
Jeffrey Yasskin7a162882011-07-18 21:45:40 +0000102 memcpy(pVal, bigVal.data(), words * APINT_WORD_SIZE);
Zhou Shengdac63782007-02-06 03:00:16 +0000103 }
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000104 // Make sure unused high bits are cleared
105 clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000106}
107
Jeffrey Yasskin7a162882011-07-18 21:45:40 +0000108APInt::APInt(unsigned numBits, ArrayRef<uint64_t> bigVal)
109 : BitWidth(numBits), VAL(0) {
110 initFromArray(bigVal);
111}
112
113APInt::APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[])
114 : BitWidth(numBits), VAL(0) {
115 initFromArray(makeArrayRef(bigVal, numWords));
116}
117
Benjamin Kramer92d89982010-07-14 22:38:02 +0000118APInt::APInt(unsigned numbits, StringRef Str, uint8_t radix)
Reid Spencer1ba83352007-02-21 03:55:44 +0000119 : BitWidth(numbits), VAL(0) {
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000120 assert(BitWidth && "Bitwidth too small");
Daniel Dunbar3a1efd112009-08-13 02:33:34 +0000121 fromString(numbits, Str, radix);
Zhou Sheng3e8022d2007-02-07 06:14:53 +0000122}
123
Chris Lattner1ac3e252008-08-20 17:02:31 +0000124APInt& APInt::AssignSlowCase(const APInt& RHS) {
Reid Spencer7c16cd22007-02-26 23:38:21 +0000125 // Don't do anything for X = X
126 if (this == &RHS)
127 return *this;
128
Reid Spencer7c16cd22007-02-26 23:38:21 +0000129 if (BitWidth == RHS.getBitWidth()) {
Chris Lattner1ac3e252008-08-20 17:02:31 +0000130 // assume same bit-width single-word case is already handled
131 assert(!isSingleWord());
132 memcpy(pVal, RHS.pVal, getNumWords() * APINT_WORD_SIZE);
Reid Spencer7c16cd22007-02-26 23:38:21 +0000133 return *this;
134 }
135
Chris Lattner1ac3e252008-08-20 17:02:31 +0000136 if (isSingleWord()) {
137 // assume case where both are single words is already handled
138 assert(!RHS.isSingleWord());
139 VAL = 0;
140 pVal = getMemory(RHS.getNumWords());
141 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
Eric Christopher820256b2009-08-21 04:06:45 +0000142 } else if (getNumWords() == RHS.getNumWords())
Reid Spencer7c16cd22007-02-26 23:38:21 +0000143 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
144 else if (RHS.isSingleWord()) {
145 delete [] pVal;
Reid Spencera856b6e2007-02-18 18:38:44 +0000146 VAL = RHS.VAL;
Reid Spencer7c16cd22007-02-26 23:38:21 +0000147 } else {
148 delete [] pVal;
149 pVal = getMemory(RHS.getNumWords());
150 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
151 }
152 BitWidth = RHS.BitWidth;
153 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000154}
155
Zhou Shengdac63782007-02-06 03:00:16 +0000156APInt& APInt::operator=(uint64_t RHS) {
Eric Christopher820256b2009-08-21 04:06:45 +0000157 if (isSingleWord())
Reid Spencer1d072122007-02-16 22:36:51 +0000158 VAL = RHS;
Zhou Shengdac63782007-02-06 03:00:16 +0000159 else {
160 pVal[0] = RHS;
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000161 memset(pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
Zhou Shengdac63782007-02-06 03:00:16 +0000162 }
Reid Spencer7c16cd22007-02-26 23:38:21 +0000163 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000164}
165
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000166/// This method 'profiles' an APInt for use with FoldingSet.
Ted Kremenek5c75d542008-01-19 04:23:33 +0000167void APInt::Profile(FoldingSetNodeID& ID) const {
Ted Kremenek901540f2008-02-19 20:50:41 +0000168 ID.AddInteger(BitWidth);
Eric Christopher820256b2009-08-21 04:06:45 +0000169
Ted Kremenek5c75d542008-01-19 04:23:33 +0000170 if (isSingleWord()) {
171 ID.AddInteger(VAL);
172 return;
173 }
174
Chris Lattner77527f52009-01-21 18:09:24 +0000175 unsigned NumWords = getNumWords();
Ted Kremenek5c75d542008-01-19 04:23:33 +0000176 for (unsigned i = 0; i < NumWords; ++i)
177 ID.AddInteger(pVal[i]);
178}
179
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000180/// This function adds a single "digit" integer, y, to the multiple
Reid Spencera856b6e2007-02-18 18:38:44 +0000181/// "digit" integer array, x[]. x[] is modified to reflect the addition and
182/// 1 is returned if there is a carry out, otherwise 0 is returned.
Reid Spencer100502d2007-02-17 03:16:00 +0000183/// @returns the carry of the addition.
Chris Lattner77527f52009-01-21 18:09:24 +0000184static bool add_1(uint64_t dest[], uint64_t x[], unsigned len, uint64_t y) {
185 for (unsigned i = 0; i < len; ++i) {
Reid Spenceree0a6852007-02-18 06:39:42 +0000186 dest[i] = y + x[i];
187 if (dest[i] < y)
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000188 y = 1; // Carry one to next digit.
Reid Spenceree0a6852007-02-18 06:39:42 +0000189 else {
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000190 y = 0; // No need to carry so exit early
Reid Spenceree0a6852007-02-18 06:39:42 +0000191 break;
192 }
Reid Spencer100502d2007-02-17 03:16:00 +0000193 }
Reid Spenceree0a6852007-02-18 06:39:42 +0000194 return y;
Reid Spencer100502d2007-02-17 03:16:00 +0000195}
196
Zhou Shengdac63782007-02-06 03:00:16 +0000197/// @brief Prefix increment operator. Increments the APInt by one.
198APInt& APInt::operator++() {
Eric Christopher820256b2009-08-21 04:06:45 +0000199 if (isSingleWord())
Reid Spencer1d072122007-02-16 22:36:51 +0000200 ++VAL;
Zhou Shengdac63782007-02-06 03:00:16 +0000201 else
Zhou Sheng3e8022d2007-02-07 06:14:53 +0000202 add_1(pVal, pVal, getNumWords(), 1);
Reid Spencera41e93b2007-02-25 19:32:03 +0000203 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000204}
205
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000206/// This function subtracts a single "digit" (64-bit word), y, from
Eric Christopher820256b2009-08-21 04:06:45 +0000207/// the multi-digit integer array, x[], propagating the borrowed 1 value until
Reid Spencera856b6e2007-02-18 18:38:44 +0000208/// no further borrowing is neeeded or it runs out of "digits" in x. The result
209/// is 1 if "borrowing" exhausted the digits in x, or 0 if x was not exhausted.
210/// In other words, if y > x then this function returns 1, otherwise 0.
Reid Spencera41e93b2007-02-25 19:32:03 +0000211/// @returns the borrow out of the subtraction
Chris Lattner77527f52009-01-21 18:09:24 +0000212static bool sub_1(uint64_t x[], unsigned len, uint64_t y) {
213 for (unsigned i = 0; i < len; ++i) {
Reid Spencer100502d2007-02-17 03:16:00 +0000214 uint64_t X = x[i];
Reid Spenceree0a6852007-02-18 06:39:42 +0000215 x[i] -= y;
Eric Christopher820256b2009-08-21 04:06:45 +0000216 if (y > X)
Reid Spencera856b6e2007-02-18 18:38:44 +0000217 y = 1; // We have to "borrow 1" from next "digit"
Reid Spencer100502d2007-02-17 03:16:00 +0000218 else {
Reid Spencera856b6e2007-02-18 18:38:44 +0000219 y = 0; // No need to borrow
220 break; // Remaining digits are unchanged so exit early
Reid Spencer100502d2007-02-17 03:16:00 +0000221 }
222 }
Reid Spencera41e93b2007-02-25 19:32:03 +0000223 return bool(y);
Reid Spencer100502d2007-02-17 03:16:00 +0000224}
225
Zhou Shengdac63782007-02-06 03:00:16 +0000226/// @brief Prefix decrement operator. Decrements the APInt by one.
227APInt& APInt::operator--() {
Eric Christopher820256b2009-08-21 04:06:45 +0000228 if (isSingleWord())
Reid Spencera856b6e2007-02-18 18:38:44 +0000229 --VAL;
Zhou Shengdac63782007-02-06 03:00:16 +0000230 else
Zhou Sheng3e8022d2007-02-07 06:14:53 +0000231 sub_1(pVal, getNumWords(), 1);
Reid Spencera41e93b2007-02-25 19:32:03 +0000232 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000233}
234
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000235/// This function adds the integer array x to the integer array Y and
Eric Christopher820256b2009-08-21 04:06:45 +0000236/// places the result in dest.
Reid Spencera41e93b2007-02-25 19:32:03 +0000237/// @returns the carry out from the addition
238/// @brief General addition of 64-bit integer arrays
Eric Christopher820256b2009-08-21 04:06:45 +0000239static bool add(uint64_t *dest, const uint64_t *x, const uint64_t *y,
Chris Lattner77527f52009-01-21 18:09:24 +0000240 unsigned len) {
Reid Spencera5e0d202007-02-24 03:58:46 +0000241 bool carry = false;
Chris Lattner77527f52009-01-21 18:09:24 +0000242 for (unsigned i = 0; i< len; ++i) {
Reid Spencercb292e42007-02-23 01:57:13 +0000243 uint64_t limit = std::min(x[i],y[i]); // must come first in case dest == x
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000244 dest[i] = x[i] + y[i] + carry;
Reid Spencerdb2abec2007-02-21 05:44:56 +0000245 carry = dest[i] < limit || (carry && dest[i] == limit);
Reid Spencer100502d2007-02-17 03:16:00 +0000246 }
247 return carry;
248}
249
Reid Spencera41e93b2007-02-25 19:32:03 +0000250/// Adds the RHS APint to this APInt.
251/// @returns this, after addition of RHS.
Eric Christopher820256b2009-08-21 04:06:45 +0000252/// @brief Addition assignment operator.
Zhou Shengdac63782007-02-06 03:00:16 +0000253APInt& APInt::operator+=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000254 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Eric Christopher820256b2009-08-21 04:06:45 +0000255 if (isSingleWord())
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000256 VAL += RHS.VAL;
Zhou Shengdac63782007-02-06 03:00:16 +0000257 else {
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000258 add(pVal, pVal, RHS.pVal, getNumWords());
Zhou Shengdac63782007-02-06 03:00:16 +0000259 }
Reid Spencera41e93b2007-02-25 19:32:03 +0000260 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000261}
262
Eric Christopher820256b2009-08-21 04:06:45 +0000263/// Subtracts the integer array y from the integer array x
Reid Spencera41e93b2007-02-25 19:32:03 +0000264/// @returns returns the borrow out.
265/// @brief Generalized subtraction of 64-bit integer arrays.
Eric Christopher820256b2009-08-21 04:06:45 +0000266static bool sub(uint64_t *dest, const uint64_t *x, const uint64_t *y,
Chris Lattner77527f52009-01-21 18:09:24 +0000267 unsigned len) {
Reid Spencer1ba83352007-02-21 03:55:44 +0000268 bool borrow = false;
Chris Lattner77527f52009-01-21 18:09:24 +0000269 for (unsigned i = 0; i < len; ++i) {
Reid Spencer1ba83352007-02-21 03:55:44 +0000270 uint64_t x_tmp = borrow ? x[i] - 1 : x[i];
271 borrow = y[i] > x_tmp || (borrow && x[i] == 0);
272 dest[i] = x_tmp - y[i];
Reid Spencer100502d2007-02-17 03:16:00 +0000273 }
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000274 return borrow;
Reid Spencer100502d2007-02-17 03:16:00 +0000275}
276
Reid Spencera41e93b2007-02-25 19:32:03 +0000277/// Subtracts the RHS APInt from this APInt
278/// @returns this, after subtraction
Eric Christopher820256b2009-08-21 04:06:45 +0000279/// @brief Subtraction assignment operator.
Zhou Shengdac63782007-02-06 03:00:16 +0000280APInt& APInt::operator-=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000281 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Eric Christopher820256b2009-08-21 04:06:45 +0000282 if (isSingleWord())
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000283 VAL -= RHS.VAL;
284 else
285 sub(pVal, pVal, RHS.pVal, getNumWords());
Reid Spencera41e93b2007-02-25 19:32:03 +0000286 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000287}
288
Dan Gohman4a618822010-02-10 16:03:48 +0000289/// Multiplies an integer array, x, by a uint64_t integer and places the result
Eric Christopher820256b2009-08-21 04:06:45 +0000290/// into dest.
Reid Spencera41e93b2007-02-25 19:32:03 +0000291/// @returns the carry out of the multiplication.
292/// @brief Multiply a multi-digit APInt by a single digit (64-bit) integer.
Chris Lattner77527f52009-01-21 18:09:24 +0000293static uint64_t mul_1(uint64_t dest[], uint64_t x[], unsigned len, uint64_t y) {
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000294 // Split y into high 32-bit part (hy) and low 32-bit part (ly)
Reid Spencer100502d2007-02-17 03:16:00 +0000295 uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
Reid Spencera41e93b2007-02-25 19:32:03 +0000296 uint64_t carry = 0;
297
298 // For each digit of x.
Chris Lattner77527f52009-01-21 18:09:24 +0000299 for (unsigned i = 0; i < len; ++i) {
Reid Spencera41e93b2007-02-25 19:32:03 +0000300 // Split x into high and low words
301 uint64_t lx = x[i] & 0xffffffffULL;
302 uint64_t hx = x[i] >> 32;
303 // hasCarry - A flag to indicate if there is a carry to the next digit.
Reid Spencer100502d2007-02-17 03:16:00 +0000304 // hasCarry == 0, no carry
305 // hasCarry == 1, has carry
306 // hasCarry == 2, no carry and the calculation result == 0.
307 uint8_t hasCarry = 0;
308 dest[i] = carry + lx * ly;
309 // Determine if the add above introduces carry.
310 hasCarry = (dest[i] < carry) ? 1 : 0;
311 carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
Eric Christopher820256b2009-08-21 04:06:45 +0000312 // The upper limit of carry can be (2^32 - 1)(2^32 - 1) +
Reid Spencer100502d2007-02-17 03:16:00 +0000313 // (2^32 - 1) + 2^32 = 2^64.
314 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
315
316 carry += (lx * hy) & 0xffffffffULL;
317 dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
Eric Christopher820256b2009-08-21 04:06:45 +0000318 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) +
Reid Spencer100502d2007-02-17 03:16:00 +0000319 (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
320 }
Reid Spencer100502d2007-02-17 03:16:00 +0000321 return carry;
322}
323
Eric Christopher820256b2009-08-21 04:06:45 +0000324/// Multiplies integer array x by integer array y and stores the result into
Reid Spencera41e93b2007-02-25 19:32:03 +0000325/// the integer array dest. Note that dest's size must be >= xlen + ylen.
326/// @brief Generalized multiplicate of integer arrays.
Chris Lattner77527f52009-01-21 18:09:24 +0000327static void mul(uint64_t dest[], uint64_t x[], unsigned xlen, uint64_t y[],
328 unsigned ylen) {
Reid Spencer100502d2007-02-17 03:16:00 +0000329 dest[xlen] = mul_1(dest, x, xlen, y[0]);
Chris Lattner77527f52009-01-21 18:09:24 +0000330 for (unsigned i = 1; i < ylen; ++i) {
Reid Spencer100502d2007-02-17 03:16:00 +0000331 uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
Reid Spencer58a6a432007-02-21 08:21:52 +0000332 uint64_t carry = 0, lx = 0, hx = 0;
Chris Lattner77527f52009-01-21 18:09:24 +0000333 for (unsigned j = 0; j < xlen; ++j) {
Reid Spencer100502d2007-02-17 03:16:00 +0000334 lx = x[j] & 0xffffffffULL;
335 hx = x[j] >> 32;
336 // hasCarry - A flag to indicate if has carry.
337 // hasCarry == 0, no carry
338 // hasCarry == 1, has carry
339 // hasCarry == 2, no carry and the calculation result == 0.
340 uint8_t hasCarry = 0;
341 uint64_t resul = carry + lx * ly;
342 hasCarry = (resul < carry) ? 1 : 0;
343 carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
344 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
345
346 carry += (lx * hy) & 0xffffffffULL;
347 resul = (carry << 32) | (resul & 0xffffffffULL);
348 dest[i+j] += resul;
349 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
Eric Christopher820256b2009-08-21 04:06:45 +0000350 (carry >> 32) + (dest[i+j] < resul ? 1 : 0) +
Reid Spencer100502d2007-02-17 03:16:00 +0000351 ((lx * hy) >> 32) + hx * hy;
352 }
353 dest[i+xlen] = carry;
354 }
355}
356
Zhou Shengdac63782007-02-06 03:00:16 +0000357APInt& APInt::operator*=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000358 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer58a6a432007-02-21 08:21:52 +0000359 if (isSingleWord()) {
Reid Spencer4bb430c2007-02-20 20:42:10 +0000360 VAL *= RHS.VAL;
Reid Spencer58a6a432007-02-21 08:21:52 +0000361 clearUnusedBits();
362 return *this;
Zhou Shengdac63782007-02-06 03:00:16 +0000363 }
Reid Spencer58a6a432007-02-21 08:21:52 +0000364
365 // Get some bit facts about LHS and check for zero
Chris Lattner77527f52009-01-21 18:09:24 +0000366 unsigned lhsBits = getActiveBits();
367 unsigned lhsWords = !lhsBits ? 0 : whichWord(lhsBits - 1) + 1;
Eric Christopher820256b2009-08-21 04:06:45 +0000368 if (!lhsWords)
Reid Spencer58a6a432007-02-21 08:21:52 +0000369 // 0 * X ===> 0
370 return *this;
371
372 // Get some bit facts about RHS and check for zero
Chris Lattner77527f52009-01-21 18:09:24 +0000373 unsigned rhsBits = RHS.getActiveBits();
374 unsigned rhsWords = !rhsBits ? 0 : whichWord(rhsBits - 1) + 1;
Reid Spencer58a6a432007-02-21 08:21:52 +0000375 if (!rhsWords) {
376 // X * 0 ===> 0
Jay Foad25a5e4c2010-12-01 08:53:58 +0000377 clearAllBits();
Reid Spencer58a6a432007-02-21 08:21:52 +0000378 return *this;
379 }
380
381 // Allocate space for the result
Chris Lattner77527f52009-01-21 18:09:24 +0000382 unsigned destWords = rhsWords + lhsWords;
Reid Spencer58a6a432007-02-21 08:21:52 +0000383 uint64_t *dest = getMemory(destWords);
384
385 // Perform the long multiply
386 mul(dest, pVal, lhsWords, RHS.pVal, rhsWords);
387
388 // Copy result back into *this
Jay Foad25a5e4c2010-12-01 08:53:58 +0000389 clearAllBits();
Chris Lattner77527f52009-01-21 18:09:24 +0000390 unsigned wordsToCopy = destWords >= getNumWords() ? getNumWords() : destWords;
Reid Spencer58a6a432007-02-21 08:21:52 +0000391 memcpy(pVal, dest, wordsToCopy * APINT_WORD_SIZE);
Eli Friedman19546412011-10-07 23:40:49 +0000392 clearUnusedBits();
Reid Spencer58a6a432007-02-21 08:21:52 +0000393
394 // delete dest array and return
395 delete[] dest;
Zhou Shengdac63782007-02-06 03:00:16 +0000396 return *this;
397}
398
Zhou Shengdac63782007-02-06 03:00:16 +0000399APInt& APInt::operator&=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000400 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengdac63782007-02-06 03:00:16 +0000401 if (isSingleWord()) {
Reid Spencera856b6e2007-02-18 18:38:44 +0000402 VAL &= RHS.VAL;
403 return *this;
Zhou Shengdac63782007-02-06 03:00:16 +0000404 }
Chris Lattner77527f52009-01-21 18:09:24 +0000405 unsigned numWords = getNumWords();
406 for (unsigned i = 0; i < numWords; ++i)
Reid Spencera856b6e2007-02-18 18:38:44 +0000407 pVal[i] &= RHS.pVal[i];
Zhou Shengdac63782007-02-06 03:00:16 +0000408 return *this;
409}
410
Zhou Shengdac63782007-02-06 03:00:16 +0000411APInt& APInt::operator|=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000412 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengdac63782007-02-06 03:00:16 +0000413 if (isSingleWord()) {
Reid Spencera856b6e2007-02-18 18:38:44 +0000414 VAL |= RHS.VAL;
415 return *this;
Zhou Shengdac63782007-02-06 03:00:16 +0000416 }
Chris Lattner77527f52009-01-21 18:09:24 +0000417 unsigned numWords = getNumWords();
418 for (unsigned i = 0; i < numWords; ++i)
Reid Spencera856b6e2007-02-18 18:38:44 +0000419 pVal[i] |= RHS.pVal[i];
Zhou Shengdac63782007-02-06 03:00:16 +0000420 return *this;
421}
422
Zhou Shengdac63782007-02-06 03:00:16 +0000423APInt& APInt::operator^=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000424 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengdac63782007-02-06 03:00:16 +0000425 if (isSingleWord()) {
Reid Spenceree0a6852007-02-18 06:39:42 +0000426 VAL ^= RHS.VAL;
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000427 this->clearUnusedBits();
Reid Spenceree0a6852007-02-18 06:39:42 +0000428 return *this;
Eric Christopher820256b2009-08-21 04:06:45 +0000429 }
Chris Lattner77527f52009-01-21 18:09:24 +0000430 unsigned numWords = getNumWords();
431 for (unsigned i = 0; i < numWords; ++i)
Reid Spencera856b6e2007-02-18 18:38:44 +0000432 pVal[i] ^= RHS.pVal[i];
Reid Spencera41e93b2007-02-25 19:32:03 +0000433 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000434}
435
Chris Lattner1ac3e252008-08-20 17:02:31 +0000436APInt APInt::AndSlowCase(const APInt& RHS) const {
Chris Lattner77527f52009-01-21 18:09:24 +0000437 unsigned numWords = getNumWords();
Reid Spencera41e93b2007-02-25 19:32:03 +0000438 uint64_t* val = getMemory(numWords);
Chris Lattner77527f52009-01-21 18:09:24 +0000439 for (unsigned i = 0; i < numWords; ++i)
Reid Spencera41e93b2007-02-25 19:32:03 +0000440 val[i] = pVal[i] & RHS.pVal[i];
441 return APInt(val, getBitWidth());
Zhou Shengdac63782007-02-06 03:00:16 +0000442}
443
Chris Lattner1ac3e252008-08-20 17:02:31 +0000444APInt APInt::OrSlowCase(const APInt& RHS) const {
Chris Lattner77527f52009-01-21 18:09:24 +0000445 unsigned numWords = getNumWords();
Reid Spencera41e93b2007-02-25 19:32:03 +0000446 uint64_t *val = getMemory(numWords);
Chris Lattner77527f52009-01-21 18:09:24 +0000447 for (unsigned i = 0; i < numWords; ++i)
Reid Spencera41e93b2007-02-25 19:32:03 +0000448 val[i] = pVal[i] | RHS.pVal[i];
449 return APInt(val, getBitWidth());
Zhou Shengdac63782007-02-06 03:00:16 +0000450}
451
Chris Lattner1ac3e252008-08-20 17:02:31 +0000452APInt APInt::XorSlowCase(const APInt& RHS) const {
Chris Lattner77527f52009-01-21 18:09:24 +0000453 unsigned numWords = getNumWords();
Reid Spencera41e93b2007-02-25 19:32:03 +0000454 uint64_t *val = getMemory(numWords);
Chris Lattner77527f52009-01-21 18:09:24 +0000455 for (unsigned i = 0; i < numWords; ++i)
Reid Spencera41e93b2007-02-25 19:32:03 +0000456 val[i] = pVal[i] ^ RHS.pVal[i];
457
Benjamin Kramerf9a29752014-10-10 10:18:12 +0000458 APInt Result(val, getBitWidth());
Reid Spencera41e93b2007-02-25 19:32:03 +0000459 // 0^0==1 so clear the high bits in case they got set.
Benjamin Kramerf9a29752014-10-10 10:18:12 +0000460 Result.clearUnusedBits();
461 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000462}
463
Zhou Shengdac63782007-02-06 03:00:16 +0000464APInt APInt::operator*(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +0000465 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencera41e93b2007-02-25 19:32:03 +0000466 if (isSingleWord())
Reid Spenceraa8dcfe2007-02-26 07:44:38 +0000467 return APInt(BitWidth, VAL * RHS.VAL);
Reid Spencer4bb430c2007-02-20 20:42:10 +0000468 APInt Result(*this);
469 Result *= RHS;
Eli Friedman19546412011-10-07 23:40:49 +0000470 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000471}
472
Zhou Shengdac63782007-02-06 03:00:16 +0000473APInt APInt::operator+(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +0000474 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencera41e93b2007-02-25 19:32:03 +0000475 if (isSingleWord())
Reid Spenceraa8dcfe2007-02-26 07:44:38 +0000476 return APInt(BitWidth, VAL + RHS.VAL);
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000477 APInt Result(BitWidth, 0);
478 add(Result.pVal, this->pVal, RHS.pVal, getNumWords());
Benjamin Kramerf9a29752014-10-10 10:18:12 +0000479 Result.clearUnusedBits();
480 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000481}
482
Pete Cooper18e91022016-05-27 03:42:17 +0000483APInt APInt::operator+(uint64_t RHS) const {
484 if (isSingleWord())
485 return APInt(BitWidth, VAL + RHS);
486 APInt Result(*this);
487 add_1(Result.pVal, Result.pVal, getNumWords(), RHS);
488 Result.clearUnusedBits();
489 return Result;
490}
491
Zhou Shengdac63782007-02-06 03:00:16 +0000492APInt APInt::operator-(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +0000493 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencera41e93b2007-02-25 19:32:03 +0000494 if (isSingleWord())
Reid Spenceraa8dcfe2007-02-26 07:44:38 +0000495 return APInt(BitWidth, VAL - RHS.VAL);
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000496 APInt Result(BitWidth, 0);
497 sub(Result.pVal, this->pVal, RHS.pVal, getNumWords());
Benjamin Kramerf9a29752014-10-10 10:18:12 +0000498 Result.clearUnusedBits();
499 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000500}
501
Pete Cooper18e91022016-05-27 03:42:17 +0000502APInt APInt::operator-(uint64_t RHS) const {
503 if (isSingleWord())
504 return APInt(BitWidth, VAL - RHS);
505 APInt Result(*this);
506 sub_1(Result.pVal, getNumWords(), RHS);
507 Result.clearUnusedBits();
508 return Result;
509}
510
Chris Lattner1ac3e252008-08-20 17:02:31 +0000511bool APInt::EqualSlowCase(const APInt& RHS) const {
Matthias Braun5117fcd2016-02-15 20:06:19 +0000512 return std::equal(pVal, pVal + getNumWords(), RHS.pVal);
Zhou Shengdac63782007-02-06 03:00:16 +0000513}
514
Chris Lattner1ac3e252008-08-20 17:02:31 +0000515bool APInt::EqualSlowCase(uint64_t Val) const {
Chris Lattner77527f52009-01-21 18:09:24 +0000516 unsigned n = getActiveBits();
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000517 if (n <= APINT_BITS_PER_WORD)
518 return pVal[0] == Val;
519 else
520 return false;
Zhou Shengdac63782007-02-06 03:00:16 +0000521}
522
Reid Spencer1d072122007-02-16 22:36:51 +0000523bool APInt::ult(const APInt& RHS) const {
524 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
525 if (isSingleWord())
526 return VAL < RHS.VAL;
Reid Spencera41e93b2007-02-25 19:32:03 +0000527
528 // Get active bit length of both operands
Chris Lattner77527f52009-01-21 18:09:24 +0000529 unsigned n1 = getActiveBits();
530 unsigned n2 = RHS.getActiveBits();
Reid Spencera41e93b2007-02-25 19:32:03 +0000531
532 // If magnitude of LHS is less than RHS, return true.
533 if (n1 < n2)
534 return true;
535
536 // If magnitude of RHS is greather than LHS, return false.
537 if (n2 < n1)
538 return false;
539
540 // If they bot fit in a word, just compare the low order word
541 if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
542 return pVal[0] < RHS.pVal[0];
543
544 // Otherwise, compare all words
Chris Lattner77527f52009-01-21 18:09:24 +0000545 unsigned topWord = whichWord(std::max(n1,n2)-1);
Reid Spencer54abdcf2007-02-27 18:23:40 +0000546 for (int i = topWord; i >= 0; --i) {
Eric Christopher820256b2009-08-21 04:06:45 +0000547 if (pVal[i] > RHS.pVal[i])
Reid Spencer1d072122007-02-16 22:36:51 +0000548 return false;
Eric Christopher820256b2009-08-21 04:06:45 +0000549 if (pVal[i] < RHS.pVal[i])
Reid Spencera41e93b2007-02-25 19:32:03 +0000550 return true;
Zhou Shengdac63782007-02-06 03:00:16 +0000551 }
552 return false;
553}
554
Reid Spencer1d072122007-02-16 22:36:51 +0000555bool APInt::slt(const APInt& RHS) const {
556 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000557 if (isSingleWord()) {
David Majnemer5f1c0172016-06-24 20:51:47 +0000558 int64_t lhsSext = SignExtend64(VAL, BitWidth);
559 int64_t rhsSext = SignExtend64(RHS.VAL, BitWidth);
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000560 return lhsSext < rhsSext;
Reid Spencer1d072122007-02-16 22:36:51 +0000561 }
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000562
Reid Spencer54abdcf2007-02-27 18:23:40 +0000563 bool lhsNeg = isNegative();
Pete Cooperd6e6bf12016-05-26 17:40:07 +0000564 bool rhsNeg = RHS.isNegative();
Reid Spencera41e93b2007-02-25 19:32:03 +0000565
Pete Cooperd6e6bf12016-05-26 17:40:07 +0000566 // If the sign bits don't match, then (LHS < RHS) if LHS is negative
567 if (lhsNeg != rhsNeg)
568 return lhsNeg;
569
570 // Otherwise we can just use an unsigned comparision, because even negative
571 // numbers compare correctly this way if both have the same signed-ness.
572 return ult(RHS);
Zhou Shengdac63782007-02-06 03:00:16 +0000573}
574
Jay Foad25a5e4c2010-12-01 08:53:58 +0000575void APInt::setBit(unsigned bitPosition) {
Eric Christopher820256b2009-08-21 04:06:45 +0000576 if (isSingleWord())
Reid Spencera41e93b2007-02-25 19:32:03 +0000577 VAL |= maskBit(bitPosition);
Eric Christopher820256b2009-08-21 04:06:45 +0000578 else
Reid Spencera41e93b2007-02-25 19:32:03 +0000579 pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
Zhou Shengdac63782007-02-06 03:00:16 +0000580}
581
Zhou Shengdac63782007-02-06 03:00:16 +0000582/// Set the given bit to 0 whose position is given as "bitPosition".
583/// @brief Set a given bit to 0.
Jay Foad25a5e4c2010-12-01 08:53:58 +0000584void APInt::clearBit(unsigned bitPosition) {
Eric Christopher820256b2009-08-21 04:06:45 +0000585 if (isSingleWord())
Reid Spencera856b6e2007-02-18 18:38:44 +0000586 VAL &= ~maskBit(bitPosition);
Eric Christopher820256b2009-08-21 04:06:45 +0000587 else
Reid Spencera856b6e2007-02-18 18:38:44 +0000588 pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
Zhou Shengdac63782007-02-06 03:00:16 +0000589}
590
Zhou Shengdac63782007-02-06 03:00:16 +0000591/// @brief Toggle every bit to its opposite value.
Zhou Shengdac63782007-02-06 03:00:16 +0000592
Eric Christopher820256b2009-08-21 04:06:45 +0000593/// Toggle a given bit to its opposite value whose position is given
Zhou Shengdac63782007-02-06 03:00:16 +0000594/// as "bitPosition".
595/// @brief Toggles a given bit to its opposite value.
Jay Foad25a5e4c2010-12-01 08:53:58 +0000596void APInt::flipBit(unsigned bitPosition) {
Reid Spencer1d072122007-02-16 22:36:51 +0000597 assert(bitPosition < BitWidth && "Out of the bit-width range!");
Jay Foad25a5e4c2010-12-01 08:53:58 +0000598 if ((*this)[bitPosition]) clearBit(bitPosition);
599 else setBit(bitPosition);
Zhou Shengdac63782007-02-06 03:00:16 +0000600}
601
Benjamin Kramer92d89982010-07-14 22:38:02 +0000602unsigned APInt::getBitsNeeded(StringRef str, uint8_t radix) {
Daniel Dunbar3a1efd112009-08-13 02:33:34 +0000603 assert(!str.empty() && "Invalid string length");
Douglas Gregor663c0682011-09-14 15:54:46 +0000604 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 ||
605 radix == 36) &&
606 "Radix should be 2, 8, 10, 16, or 36!");
Daniel Dunbar3a1efd112009-08-13 02:33:34 +0000607
608 size_t slen = str.size();
Reid Spencer9329e7b2007-04-13 19:19:07 +0000609
Eric Christopher43a1dec2009-08-21 04:10:31 +0000610 // Each computation below needs to know if it's negative.
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000611 StringRef::iterator p = str.begin();
Eric Christopher43a1dec2009-08-21 04:10:31 +0000612 unsigned isNegative = *p == '-';
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000613 if (*p == '-' || *p == '+') {
614 p++;
Reid Spencer9329e7b2007-04-13 19:19:07 +0000615 slen--;
Eric Christopher43a1dec2009-08-21 04:10:31 +0000616 assert(slen && "String is only a sign, needs a value.");
Reid Spencer9329e7b2007-04-13 19:19:07 +0000617 }
Eric Christopher43a1dec2009-08-21 04:10:31 +0000618
Reid Spencer9329e7b2007-04-13 19:19:07 +0000619 // For radixes of power-of-two values, the bits required is accurately and
620 // easily computed
621 if (radix == 2)
622 return slen + isNegative;
623 if (radix == 8)
624 return slen * 3 + isNegative;
625 if (radix == 16)
626 return slen * 4 + isNegative;
627
Douglas Gregor663c0682011-09-14 15:54:46 +0000628 // FIXME: base 36
629
Reid Spencer9329e7b2007-04-13 19:19:07 +0000630 // This is grossly inefficient but accurate. We could probably do something
631 // with a computation of roughly slen*64/20 and then adjust by the value of
632 // the first few digits. But, I'm not sure how accurate that could be.
633
634 // Compute a sufficient number of bits that is always large enough but might
Erick Tryzelaardadb15712009-08-21 03:15:28 +0000635 // be too large. This avoids the assertion in the constructor. This
636 // calculation doesn't work appropriately for the numbers 0-9, so just use 4
637 // bits in that case.
Douglas Gregor663c0682011-09-14 15:54:46 +0000638 unsigned sufficient
639 = radix == 10? (slen == 1 ? 4 : slen * 64/18)
640 : (slen == 1 ? 7 : slen * 16/3);
Reid Spencer9329e7b2007-04-13 19:19:07 +0000641
642 // Convert to the actual binary value.
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000643 APInt tmp(sufficient, StringRef(p, slen), radix);
Reid Spencer9329e7b2007-04-13 19:19:07 +0000644
Erick Tryzelaardadb15712009-08-21 03:15:28 +0000645 // Compute how many bits are required. If the log is infinite, assume we need
646 // just bit.
647 unsigned log = tmp.logBase2();
648 if (log == (unsigned)-1) {
649 return isNegative + 1;
650 } else {
651 return isNegative + log + 1;
652 }
Reid Spencer9329e7b2007-04-13 19:19:07 +0000653}
654
Chandler Carruth71bd7d12012-03-04 12:02:57 +0000655hash_code llvm::hash_value(const APInt &Arg) {
656 if (Arg.isSingleWord())
657 return hash_combine(Arg.VAL);
Reid Spencerb2bc9852007-02-26 21:02:27 +0000658
Chandler Carruth71bd7d12012-03-04 12:02:57 +0000659 return hash_combine_range(Arg.pVal, Arg.pVal + Arg.getNumWords());
Reid Spencerb2bc9852007-02-26 21:02:27 +0000660}
661
Benjamin Kramerb4b51502015-03-25 16:49:59 +0000662bool APInt::isSplat(unsigned SplatSizeInBits) const {
663 assert(getBitWidth() % SplatSizeInBits == 0 &&
664 "SplatSizeInBits must divide width!");
665 // We can check that all parts of an integer are equal by making use of a
666 // little trick: rotate and check if it's still the same value.
667 return *this == rotl(SplatSizeInBits);
668}
669
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000670/// This function returns the high "numBits" bits of this APInt.
Chris Lattner77527f52009-01-21 18:09:24 +0000671APInt APInt::getHiBits(unsigned numBits) const {
Reid Spencer1d072122007-02-16 22:36:51 +0000672 return APIntOps::lshr(*this, BitWidth - numBits);
Zhou Shengdac63782007-02-06 03:00:16 +0000673}
674
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000675/// This function returns the low "numBits" bits of this APInt.
Chris Lattner77527f52009-01-21 18:09:24 +0000676APInt APInt::getLoBits(unsigned numBits) const {
Eric Christopher820256b2009-08-21 04:06:45 +0000677 return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits),
Reid Spencer1d072122007-02-16 22:36:51 +0000678 BitWidth - numBits);
Zhou Shengdac63782007-02-06 03:00:16 +0000679}
680
Chris Lattner77527f52009-01-21 18:09:24 +0000681unsigned APInt::countLeadingZerosSlowCase() const {
Matthias Brauna6be4e82016-02-15 20:06:22 +0000682 unsigned Count = 0;
683 for (int i = getNumWords()-1; i >= 0; --i) {
684 integerPart V = pVal[i];
685 if (V == 0)
Chris Lattner1ac3e252008-08-20 17:02:31 +0000686 Count += APINT_BITS_PER_WORD;
687 else {
Matthias Brauna6be4e82016-02-15 20:06:22 +0000688 Count += llvm::countLeadingZeros(V);
Chris Lattner1ac3e252008-08-20 17:02:31 +0000689 break;
Reid Spencer74cf82e2007-02-21 00:29:48 +0000690 }
Zhou Shengdac63782007-02-06 03:00:16 +0000691 }
Matthias Brauna6be4e82016-02-15 20:06:22 +0000692 // Adjust for unused bits in the most significant word (they are zero).
693 unsigned Mod = BitWidth % APINT_BITS_PER_WORD;
694 Count -= Mod > 0 ? APINT_BITS_PER_WORD - Mod : 0;
John McCalldf951bd2010-02-03 03:42:44 +0000695 return Count;
Zhou Shengdac63782007-02-06 03:00:16 +0000696}
697
Chris Lattner77527f52009-01-21 18:09:24 +0000698unsigned APInt::countLeadingOnes() const {
Reid Spencer31acef52007-02-27 21:59:26 +0000699 if (isSingleWord())
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000700 return llvm::countLeadingOnes(VAL << (APINT_BITS_PER_WORD - BitWidth));
Reid Spencer31acef52007-02-27 21:59:26 +0000701
Chris Lattner77527f52009-01-21 18:09:24 +0000702 unsigned highWordBits = BitWidth % APINT_BITS_PER_WORD;
Torok Edwinec39eb82009-01-27 18:06:03 +0000703 unsigned shift;
704 if (!highWordBits) {
705 highWordBits = APINT_BITS_PER_WORD;
706 shift = 0;
707 } else {
708 shift = APINT_BITS_PER_WORD - highWordBits;
709 }
Reid Spencer31acef52007-02-27 21:59:26 +0000710 int i = getNumWords() - 1;
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000711 unsigned Count = llvm::countLeadingOnes(pVal[i] << shift);
Reid Spencer31acef52007-02-27 21:59:26 +0000712 if (Count == highWordBits) {
713 for (i--; i >= 0; --i) {
714 if (pVal[i] == -1ULL)
715 Count += APINT_BITS_PER_WORD;
716 else {
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000717 Count += llvm::countLeadingOnes(pVal[i]);
Reid Spencer31acef52007-02-27 21:59:26 +0000718 break;
719 }
720 }
721 }
722 return Count;
723}
724
Chris Lattner77527f52009-01-21 18:09:24 +0000725unsigned APInt::countTrailingZeros() const {
Zhou Shengdac63782007-02-06 03:00:16 +0000726 if (isSingleWord())
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000727 return std::min(unsigned(llvm::countTrailingZeros(VAL)), BitWidth);
Chris Lattner77527f52009-01-21 18:09:24 +0000728 unsigned Count = 0;
729 unsigned i = 0;
Reid Spenceraa8dcfe2007-02-26 07:44:38 +0000730 for (; i < getNumWords() && pVal[i] == 0; ++i)
731 Count += APINT_BITS_PER_WORD;
732 if (i < getNumWords())
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000733 Count += llvm::countTrailingZeros(pVal[i]);
Chris Lattnerc2c4c742007-11-23 22:36:25 +0000734 return std::min(Count, BitWidth);
Zhou Shengdac63782007-02-06 03:00:16 +0000735}
736
Chris Lattner77527f52009-01-21 18:09:24 +0000737unsigned APInt::countTrailingOnesSlowCase() const {
738 unsigned Count = 0;
739 unsigned i = 0;
Dan Gohmanc354ebd2008-02-14 22:38:45 +0000740 for (; i < getNumWords() && pVal[i] == -1ULL; ++i)
Dan Gohman8b4fa9d2008-02-13 21:11:05 +0000741 Count += APINT_BITS_PER_WORD;
742 if (i < getNumWords())
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000743 Count += llvm::countTrailingOnes(pVal[i]);
Dan Gohman8b4fa9d2008-02-13 21:11:05 +0000744 return std::min(Count, BitWidth);
745}
746
Chris Lattner77527f52009-01-21 18:09:24 +0000747unsigned APInt::countPopulationSlowCase() const {
748 unsigned Count = 0;
749 for (unsigned i = 0; i < getNumWords(); ++i)
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000750 Count += llvm::countPopulation(pVal[i]);
Zhou Shengdac63782007-02-06 03:00:16 +0000751 return Count;
752}
753
Richard Smith4f9a8082011-11-23 21:33:37 +0000754/// Perform a logical right-shift from Src to Dst, which must be equal or
755/// non-overlapping, of Words words, by Shift, which must be less than 64.
756static void lshrNear(uint64_t *Dst, uint64_t *Src, unsigned Words,
757 unsigned Shift) {
758 uint64_t Carry = 0;
759 for (int I = Words - 1; I >= 0; --I) {
760 uint64_t Tmp = Src[I];
761 Dst[I] = (Tmp >> Shift) | Carry;
762 Carry = Tmp << (64 - Shift);
763 }
764}
765
Reid Spencer1d072122007-02-16 22:36:51 +0000766APInt APInt::byteSwap() const {
767 assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
768 if (BitWidth == 16)
Jeff Cohene06855e2007-03-20 20:42:36 +0000769 return APInt(BitWidth, ByteSwap_16(uint16_t(VAL)));
Richard Smith4f9a8082011-11-23 21:33:37 +0000770 if (BitWidth == 32)
Chris Lattner77527f52009-01-21 18:09:24 +0000771 return APInt(BitWidth, ByteSwap_32(unsigned(VAL)));
Richard Smith4f9a8082011-11-23 21:33:37 +0000772 if (BitWidth == 48) {
Chris Lattner77527f52009-01-21 18:09:24 +0000773 unsigned Tmp1 = unsigned(VAL >> 16);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000774 Tmp1 = ByteSwap_32(Tmp1);
Jeff Cohene06855e2007-03-20 20:42:36 +0000775 uint16_t Tmp2 = uint16_t(VAL);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000776 Tmp2 = ByteSwap_16(Tmp2);
Jeff Cohene06855e2007-03-20 20:42:36 +0000777 return APInt(BitWidth, (uint64_t(Tmp2) << 32) | Tmp1);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000778 }
Richard Smith4f9a8082011-11-23 21:33:37 +0000779 if (BitWidth == 64)
780 return APInt(BitWidth, ByteSwap_64(VAL));
781
782 APInt Result(getNumWords() * APINT_BITS_PER_WORD, 0);
783 for (unsigned I = 0, N = getNumWords(); I != N; ++I)
784 Result.pVal[I] = ByteSwap_64(pVal[N - I - 1]);
785 if (Result.BitWidth != BitWidth) {
786 lshrNear(Result.pVal, Result.pVal, getNumWords(),
787 Result.BitWidth - BitWidth);
788 Result.BitWidth = BitWidth;
789 }
790 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000791}
792
Matt Arsenault155dda92016-03-21 15:00:35 +0000793APInt APInt::reverseBits() const {
794 switch (BitWidth) {
795 case 64:
796 return APInt(BitWidth, llvm::reverseBits<uint64_t>(VAL));
797 case 32:
798 return APInt(BitWidth, llvm::reverseBits<uint32_t>(VAL));
799 case 16:
800 return APInt(BitWidth, llvm::reverseBits<uint16_t>(VAL));
801 case 8:
802 return APInt(BitWidth, llvm::reverseBits<uint8_t>(VAL));
803 default:
804 break;
805 }
806
807 APInt Val(*this);
808 APInt Reversed(*this);
809 int S = BitWidth - 1;
810
811 const APInt One(BitWidth, 1);
812
813 for ((Val = Val.lshr(1)); Val != 0; (Val = Val.lshr(1))) {
814 Reversed <<= 1;
815 Reversed |= (Val & One);
816 --S;
817 }
818
819 Reversed <<= S;
820 return Reversed;
821}
822
Eric Christopher820256b2009-08-21 04:06:45 +0000823APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1,
Zhou Shengfbf61ea2007-02-08 14:35:19 +0000824 const APInt& API2) {
Zhou Shengdac63782007-02-06 03:00:16 +0000825 APInt A = API1, B = API2;
826 while (!!B) {
827 APInt T = B;
Reid Spencer1d072122007-02-16 22:36:51 +0000828 B = APIntOps::urem(A, B);
Zhou Shengdac63782007-02-06 03:00:16 +0000829 A = T;
830 }
831 return A;
832}
Chris Lattner28cbd1d2007-02-06 05:38:37 +0000833
Chris Lattner77527f52009-01-21 18:09:24 +0000834APInt llvm::APIntOps::RoundDoubleToAPInt(double Double, unsigned width) {
Zhou Shengd707d632007-02-12 20:02:55 +0000835 union {
836 double D;
837 uint64_t I;
838 } T;
839 T.D = Double;
Reid Spencer974551a2007-02-27 01:28:10 +0000840
841 // Get the sign bit from the highest order bit
Zhou Shengd707d632007-02-12 20:02:55 +0000842 bool isNeg = T.I >> 63;
Reid Spencer974551a2007-02-27 01:28:10 +0000843
844 // Get the 11-bit exponent and adjust for the 1023 bit bias
Zhou Shengd707d632007-02-12 20:02:55 +0000845 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
Reid Spencer974551a2007-02-27 01:28:10 +0000846
847 // If the exponent is negative, the value is < 0 so just return 0.
Zhou Shengd707d632007-02-12 20:02:55 +0000848 if (exp < 0)
Reid Spencer66d0d572007-02-28 01:30:08 +0000849 return APInt(width, 0u);
Reid Spencer974551a2007-02-27 01:28:10 +0000850
851 // Extract the mantissa by clearing the top 12 bits (sign + exponent).
852 uint64_t mantissa = (T.I & (~0ULL >> 12)) | 1ULL << 52;
853
854 // If the exponent doesn't shift all bits out of the mantissa
Zhou Shengd707d632007-02-12 20:02:55 +0000855 if (exp < 52)
Eric Christopher820256b2009-08-21 04:06:45 +0000856 return isNeg ? -APInt(width, mantissa >> (52 - exp)) :
Reid Spencer54abdcf2007-02-27 18:23:40 +0000857 APInt(width, mantissa >> (52 - exp));
858
859 // If the client didn't provide enough bits for us to shift the mantissa into
860 // then the result is undefined, just return 0
861 if (width <= exp - 52)
862 return APInt(width, 0);
Reid Spencer974551a2007-02-27 01:28:10 +0000863
864 // Otherwise, we have to shift the mantissa bits up to the right location
Reid Spencer54abdcf2007-02-27 18:23:40 +0000865 APInt Tmp(width, mantissa);
Chris Lattner77527f52009-01-21 18:09:24 +0000866 Tmp = Tmp.shl((unsigned)exp - 52);
Zhou Shengd707d632007-02-12 20:02:55 +0000867 return isNeg ? -Tmp : Tmp;
868}
869
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000870/// This function converts this APInt to a double.
Zhou Shengd707d632007-02-12 20:02:55 +0000871/// The layout for double is as following (IEEE Standard 754):
872/// --------------------------------------
873/// | Sign Exponent Fraction Bias |
874/// |-------------------------------------- |
875/// | 1[63] 11[62-52] 52[51-00] 1023 |
Eric Christopher820256b2009-08-21 04:06:45 +0000876/// --------------------------------------
Reid Spencer1d072122007-02-16 22:36:51 +0000877double APInt::roundToDouble(bool isSigned) const {
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000878
879 // Handle the simple case where the value is contained in one uint64_t.
Dale Johannesen54be7852009-08-12 18:04:11 +0000880 // It is wrong to optimize getWord(0) to VAL; there might be more than one word.
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000881 if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
882 if (isSigned) {
David Majnemer03992262016-06-24 21:15:36 +0000883 int64_t sext = SignExtend64(getWord(0), BitWidth);
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000884 return double(sext);
885 } else
Dale Johannesen34c08bb2009-08-12 17:42:34 +0000886 return double(getWord(0));
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000887 }
888
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000889 // Determine if the value is negative.
Reid Spencer1d072122007-02-16 22:36:51 +0000890 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000891
892 // Construct the absolute value if we're negative.
Zhou Shengd707d632007-02-12 20:02:55 +0000893 APInt Tmp(isNeg ? -(*this) : (*this));
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000894
895 // Figure out how many bits we're using.
Chris Lattner77527f52009-01-21 18:09:24 +0000896 unsigned n = Tmp.getActiveBits();
Zhou Shengd707d632007-02-12 20:02:55 +0000897
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000898 // The exponent (without bias normalization) is just the number of bits
899 // we are using. Note that the sign bit is gone since we constructed the
900 // absolute value.
901 uint64_t exp = n;
Zhou Shengd707d632007-02-12 20:02:55 +0000902
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000903 // Return infinity for exponent overflow
904 if (exp > 1023) {
905 if (!isSigned || !isNeg)
Jeff Cohene06855e2007-03-20 20:42:36 +0000906 return std::numeric_limits<double>::infinity();
Eric Christopher820256b2009-08-21 04:06:45 +0000907 else
Jeff Cohene06855e2007-03-20 20:42:36 +0000908 return -std::numeric_limits<double>::infinity();
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000909 }
910 exp += 1023; // Increment for 1023 bias
911
912 // Number of bits in mantissa is 52. To obtain the mantissa value, we must
913 // extract the high 52 bits from the correct words in pVal.
Zhou Shengd707d632007-02-12 20:02:55 +0000914 uint64_t mantissa;
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000915 unsigned hiWord = whichWord(n-1);
916 if (hiWord == 0) {
917 mantissa = Tmp.pVal[0];
918 if (n > 52)
919 mantissa >>= n - 52; // shift down, we want the top 52 bits.
920 } else {
921 assert(hiWord > 0 && "huh?");
922 uint64_t hibits = Tmp.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
923 uint64_t lobits = Tmp.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
924 mantissa = hibits | lobits;
925 }
926
Zhou Shengd707d632007-02-12 20:02:55 +0000927 // The leading bit of mantissa is implicit, so get rid of it.
Reid Spencerfbd48a52007-02-18 00:44:22 +0000928 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
Zhou Shengd707d632007-02-12 20:02:55 +0000929 union {
930 double D;
931 uint64_t I;
932 } T;
933 T.I = sign | (exp << 52) | mantissa;
934 return T.D;
935}
936
Reid Spencer1d072122007-02-16 22:36:51 +0000937// Truncate to new width.
Jay Foad583abbc2010-12-07 08:25:19 +0000938APInt APInt::trunc(unsigned width) const {
Reid Spencer1d072122007-02-16 22:36:51 +0000939 assert(width < BitWidth && "Invalid APInt Truncate request");
Chris Lattner1ac3e252008-08-20 17:02:31 +0000940 assert(width && "Can't truncate to 0 bits");
Jay Foad583abbc2010-12-07 08:25:19 +0000941
942 if (width <= APINT_BITS_PER_WORD)
943 return APInt(width, getRawData()[0]);
944
945 APInt Result(getMemory(getNumWords(width)), width);
946
947 // Copy full words.
948 unsigned i;
949 for (i = 0; i != width / APINT_BITS_PER_WORD; i++)
950 Result.pVal[i] = pVal[i];
951
952 // Truncate and copy any partial word.
953 unsigned bits = (0 - width) % APINT_BITS_PER_WORD;
954 if (bits != 0)
955 Result.pVal[i] = pVal[i] << bits >> bits;
956
957 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +0000958}
959
960// Sign extend to a new width.
Jay Foad583abbc2010-12-07 08:25:19 +0000961APInt APInt::sext(unsigned width) const {
Reid Spencer1d072122007-02-16 22:36:51 +0000962 assert(width > BitWidth && "Invalid APInt SignExtend request");
Jay Foad583abbc2010-12-07 08:25:19 +0000963
964 if (width <= APINT_BITS_PER_WORD) {
965 uint64_t val = VAL << (APINT_BITS_PER_WORD - BitWidth);
966 val = (int64_t)val >> (width - BitWidth);
967 return APInt(width, val >> (APINT_BITS_PER_WORD - width));
Reid Spencerb6b5cc32007-02-25 23:44:53 +0000968 }
969
Jay Foad583abbc2010-12-07 08:25:19 +0000970 APInt Result(getMemory(getNumWords(width)), width);
Reid Spencerb6b5cc32007-02-25 23:44:53 +0000971
Jay Foad583abbc2010-12-07 08:25:19 +0000972 // Copy full words.
973 unsigned i;
974 uint64_t word = 0;
975 for (i = 0; i != BitWidth / APINT_BITS_PER_WORD; i++) {
976 word = getRawData()[i];
977 Result.pVal[i] = word;
Reid Spencerb6b5cc32007-02-25 23:44:53 +0000978 }
979
Jay Foad583abbc2010-12-07 08:25:19 +0000980 // Read and sign-extend any partial word.
981 unsigned bits = (0 - BitWidth) % APINT_BITS_PER_WORD;
982 if (bits != 0)
983 word = (int64_t)getRawData()[i] << bits >> bits;
984 else
985 word = (int64_t)word >> (APINT_BITS_PER_WORD - 1);
986
987 // Write remaining full words.
988 for (; i != width / APINT_BITS_PER_WORD; i++) {
989 Result.pVal[i] = word;
990 word = (int64_t)word >> (APINT_BITS_PER_WORD - 1);
Reid Spencerb6b5cc32007-02-25 23:44:53 +0000991 }
Jay Foad583abbc2010-12-07 08:25:19 +0000992
993 // Write any partial word.
994 bits = (0 - width) % APINT_BITS_PER_WORD;
995 if (bits != 0)
996 Result.pVal[i] = word << bits >> bits;
997
998 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +0000999}
1000
1001// Zero extend to a new width.
Jay Foad583abbc2010-12-07 08:25:19 +00001002APInt APInt::zext(unsigned width) const {
Reid Spencer1d072122007-02-16 22:36:51 +00001003 assert(width > BitWidth && "Invalid APInt ZeroExtend request");
Jay Foad583abbc2010-12-07 08:25:19 +00001004
1005 if (width <= APINT_BITS_PER_WORD)
1006 return APInt(width, VAL);
1007
1008 APInt Result(getMemory(getNumWords(width)), width);
1009
1010 // Copy words.
1011 unsigned i;
1012 for (i = 0; i != getNumWords(); i++)
1013 Result.pVal[i] = getRawData()[i];
1014
1015 // Zero remaining words.
1016 memset(&Result.pVal[i], 0, (Result.getNumWords() - i) * APINT_WORD_SIZE);
1017
1018 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +00001019}
1020
Jay Foad583abbc2010-12-07 08:25:19 +00001021APInt APInt::zextOrTrunc(unsigned width) const {
Reid Spencer742d1702007-03-01 17:15:32 +00001022 if (BitWidth < width)
1023 return zext(width);
1024 if (BitWidth > width)
1025 return trunc(width);
1026 return *this;
1027}
1028
Jay Foad583abbc2010-12-07 08:25:19 +00001029APInt APInt::sextOrTrunc(unsigned width) const {
Reid Spencer742d1702007-03-01 17:15:32 +00001030 if (BitWidth < width)
1031 return sext(width);
1032 if (BitWidth > width)
1033 return trunc(width);
1034 return *this;
1035}
1036
Rafael Espindolabb893fe2012-01-27 23:33:07 +00001037APInt APInt::zextOrSelf(unsigned width) const {
1038 if (BitWidth < width)
1039 return zext(width);
1040 return *this;
1041}
1042
1043APInt APInt::sextOrSelf(unsigned width) const {
1044 if (BitWidth < width)
1045 return sext(width);
1046 return *this;
1047}
1048
Zhou Shenge93db8f2007-02-09 07:48:24 +00001049/// Arithmetic right-shift this APInt by shiftAmt.
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001050/// @brief Arithmetic right-shift function.
Dan Gohman105c1d42008-02-29 01:40:47 +00001051APInt APInt::ashr(const APInt &shiftAmt) const {
Chris Lattner77527f52009-01-21 18:09:24 +00001052 return ashr((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001053}
1054
1055/// Arithmetic right-shift this APInt by shiftAmt.
1056/// @brief Arithmetic right-shift function.
Chris Lattner77527f52009-01-21 18:09:24 +00001057APInt APInt::ashr(unsigned shiftAmt) const {
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001058 assert(shiftAmt <= BitWidth && "Invalid shift amount");
Reid Spencer1825dd02007-03-02 22:39:11 +00001059 // Handle a degenerate case
1060 if (shiftAmt == 0)
1061 return *this;
1062
1063 // Handle single word shifts with built-in ashr
Reid Spencer522ca7c2007-02-25 01:56:07 +00001064 if (isSingleWord()) {
1065 if (shiftAmt == BitWidth)
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001066 return APInt(BitWidth, 0); // undefined
1067 else {
Chris Lattner77527f52009-01-21 18:09:24 +00001068 unsigned SignBit = APINT_BITS_PER_WORD - BitWidth;
Eric Christopher820256b2009-08-21 04:06:45 +00001069 return APInt(BitWidth,
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001070 (((int64_t(VAL) << SignBit) >> SignBit) >> shiftAmt));
1071 }
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001072 }
Reid Spencer522ca7c2007-02-25 01:56:07 +00001073
Reid Spencer1825dd02007-03-02 22:39:11 +00001074 // If all the bits were shifted out, the result is, technically, undefined.
1075 // We return -1 if it was negative, 0 otherwise. We check this early to avoid
1076 // issues in the algorithm below.
Chris Lattnerdad2d092007-05-03 18:15:36 +00001077 if (shiftAmt == BitWidth) {
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001078 if (isNegative())
Zhou Sheng1247c072008-06-05 13:27:38 +00001079 return APInt(BitWidth, -1ULL, true);
Reid Spencera41e93b2007-02-25 19:32:03 +00001080 else
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001081 return APInt(BitWidth, 0);
Chris Lattnerdad2d092007-05-03 18:15:36 +00001082 }
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001083
1084 // Create some space for the result.
1085 uint64_t * val = new uint64_t[getNumWords()];
1086
Reid Spencer1825dd02007-03-02 22:39:11 +00001087 // Compute some values needed by the following shift algorithms
Chris Lattner77527f52009-01-21 18:09:24 +00001088 unsigned wordShift = shiftAmt % APINT_BITS_PER_WORD; // bits to shift per word
1089 unsigned offset = shiftAmt / APINT_BITS_PER_WORD; // word offset for shift
1090 unsigned breakWord = getNumWords() - 1 - offset; // last word affected
1091 unsigned bitsInWord = whichBit(BitWidth); // how many bits in last word?
Reid Spencer1825dd02007-03-02 22:39:11 +00001092 if (bitsInWord == 0)
1093 bitsInWord = APINT_BITS_PER_WORD;
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001094
1095 // If we are shifting whole words, just move whole words
1096 if (wordShift == 0) {
Reid Spencer1825dd02007-03-02 22:39:11 +00001097 // Move the words containing significant bits
Chris Lattner77527f52009-01-21 18:09:24 +00001098 for (unsigned i = 0; i <= breakWord; ++i)
Reid Spencer1825dd02007-03-02 22:39:11 +00001099 val[i] = pVal[i+offset]; // move whole word
1100
1101 // Adjust the top significant word for sign bit fill, if negative
1102 if (isNegative())
1103 if (bitsInWord < APINT_BITS_PER_WORD)
1104 val[breakWord] |= ~0ULL << bitsInWord; // set high bits
1105 } else {
Eric Christopher820256b2009-08-21 04:06:45 +00001106 // Shift the low order words
Chris Lattner77527f52009-01-21 18:09:24 +00001107 for (unsigned i = 0; i < breakWord; ++i) {
Reid Spencer1825dd02007-03-02 22:39:11 +00001108 // This combines the shifted corresponding word with the low bits from
1109 // the next word (shifted into this word's high bits).
Eric Christopher820256b2009-08-21 04:06:45 +00001110 val[i] = (pVal[i+offset] >> wordShift) |
Reid Spencer1825dd02007-03-02 22:39:11 +00001111 (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift));
1112 }
1113
1114 // Shift the break word. In this case there are no bits from the next word
1115 // to include in this word.
1116 val[breakWord] = pVal[breakWord+offset] >> wordShift;
1117
Alp Tokercb402912014-01-24 17:20:08 +00001118 // Deal with sign extension in the break word, and possibly the word before
Reid Spencer1825dd02007-03-02 22:39:11 +00001119 // it.
Chris Lattnerdad2d092007-05-03 18:15:36 +00001120 if (isNegative()) {
Reid Spencer1825dd02007-03-02 22:39:11 +00001121 if (wordShift > bitsInWord) {
1122 if (breakWord > 0)
Eric Christopher820256b2009-08-21 04:06:45 +00001123 val[breakWord-1] |=
Reid Spencer1825dd02007-03-02 22:39:11 +00001124 ~0ULL << (APINT_BITS_PER_WORD - (wordShift - bitsInWord));
1125 val[breakWord] |= ~0ULL;
Eric Christopher820256b2009-08-21 04:06:45 +00001126 } else
Reid Spencer1825dd02007-03-02 22:39:11 +00001127 val[breakWord] |= (~0ULL << (bitsInWord - wordShift));
Chris Lattnerdad2d092007-05-03 18:15:36 +00001128 }
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001129 }
1130
Reid Spencer1825dd02007-03-02 22:39:11 +00001131 // Remaining words are 0 or -1, just assign them.
1132 uint64_t fillValue = (isNegative() ? -1ULL : 0);
Chris Lattner77527f52009-01-21 18:09:24 +00001133 for (unsigned i = breakWord+1; i < getNumWords(); ++i)
Reid Spencer1825dd02007-03-02 22:39:11 +00001134 val[i] = fillValue;
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001135 APInt Result(val, BitWidth);
1136 Result.clearUnusedBits();
1137 return Result;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001138}
1139
Zhou Shenge93db8f2007-02-09 07:48:24 +00001140/// Logical right-shift this APInt by shiftAmt.
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001141/// @brief Logical right-shift function.
Dan Gohman105c1d42008-02-29 01:40:47 +00001142APInt APInt::lshr(const APInt &shiftAmt) const {
Chris Lattner77527f52009-01-21 18:09:24 +00001143 return lshr((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001144}
1145
1146/// Logical right-shift this APInt by shiftAmt.
1147/// @brief Logical right-shift function.
Chris Lattner77527f52009-01-21 18:09:24 +00001148APInt APInt::lshr(unsigned shiftAmt) const {
Chris Lattnerdad2d092007-05-03 18:15:36 +00001149 if (isSingleWord()) {
Ahmed Charles0dca5d82012-02-24 19:06:15 +00001150 if (shiftAmt >= BitWidth)
Reid Spencer522ca7c2007-02-25 01:56:07 +00001151 return APInt(BitWidth, 0);
Eric Christopher820256b2009-08-21 04:06:45 +00001152 else
Reid Spencer522ca7c2007-02-25 01:56:07 +00001153 return APInt(BitWidth, this->VAL >> shiftAmt);
Chris Lattnerdad2d092007-05-03 18:15:36 +00001154 }
Reid Spencer522ca7c2007-02-25 01:56:07 +00001155
Reid Spencer44eef162007-02-26 01:19:48 +00001156 // If all the bits were shifted out, the result is 0. This avoids issues
1157 // with shifting by the size of the integer type, which produces undefined
1158 // results. We define these "undefined results" to always be 0.
Chad Rosier3d464d82012-06-08 18:04:52 +00001159 if (shiftAmt >= BitWidth)
Reid Spencer44eef162007-02-26 01:19:48 +00001160 return APInt(BitWidth, 0);
1161
Reid Spencerfffdf102007-05-17 06:26:29 +00001162 // If none of the bits are shifted out, the result is *this. This avoids
Eric Christopher820256b2009-08-21 04:06:45 +00001163 // issues with shifting by the size of the integer type, which produces
Reid Spencerfffdf102007-05-17 06:26:29 +00001164 // undefined results in the code below. This is also an optimization.
1165 if (shiftAmt == 0)
1166 return *this;
1167
Reid Spencer44eef162007-02-26 01:19:48 +00001168 // Create some space for the result.
1169 uint64_t * val = new uint64_t[getNumWords()];
1170
1171 // If we are shifting less than a word, compute the shift with a simple carry
1172 if (shiftAmt < APINT_BITS_PER_WORD) {
Richard Smith4f9a8082011-11-23 21:33:37 +00001173 lshrNear(val, pVal, getNumWords(), shiftAmt);
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001174 APInt Result(val, BitWidth);
1175 Result.clearUnusedBits();
1176 return Result;
Reid Spencera41e93b2007-02-25 19:32:03 +00001177 }
1178
Reid Spencer44eef162007-02-26 01:19:48 +00001179 // Compute some values needed by the remaining shift algorithms
Chris Lattner77527f52009-01-21 18:09:24 +00001180 unsigned wordShift = shiftAmt % APINT_BITS_PER_WORD;
1181 unsigned offset = shiftAmt / APINT_BITS_PER_WORD;
Reid Spencer44eef162007-02-26 01:19:48 +00001182
1183 // If we are shifting whole words, just move whole words
1184 if (wordShift == 0) {
Chris Lattner77527f52009-01-21 18:09:24 +00001185 for (unsigned i = 0; i < getNumWords() - offset; ++i)
Reid Spencer44eef162007-02-26 01:19:48 +00001186 val[i] = pVal[i+offset];
Chris Lattner77527f52009-01-21 18:09:24 +00001187 for (unsigned i = getNumWords()-offset; i < getNumWords(); i++)
Reid Spencer44eef162007-02-26 01:19:48 +00001188 val[i] = 0;
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001189 APInt Result(val, BitWidth);
1190 Result.clearUnusedBits();
1191 return Result;
Reid Spencer44eef162007-02-26 01:19:48 +00001192 }
1193
Eric Christopher820256b2009-08-21 04:06:45 +00001194 // Shift the low order words
Chris Lattner77527f52009-01-21 18:09:24 +00001195 unsigned breakWord = getNumWords() - offset -1;
1196 for (unsigned i = 0; i < breakWord; ++i)
Reid Spencerd99feaf2007-03-01 05:39:56 +00001197 val[i] = (pVal[i+offset] >> wordShift) |
1198 (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift));
Reid Spencer44eef162007-02-26 01:19:48 +00001199 // Shift the break word.
1200 val[breakWord] = pVal[breakWord+offset] >> wordShift;
1201
1202 // Remaining words are 0
Chris Lattner77527f52009-01-21 18:09:24 +00001203 for (unsigned i = breakWord+1; i < getNumWords(); ++i)
Reid Spencer44eef162007-02-26 01:19:48 +00001204 val[i] = 0;
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001205 APInt Result(val, BitWidth);
1206 Result.clearUnusedBits();
1207 return Result;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001208}
1209
Zhou Shenge93db8f2007-02-09 07:48:24 +00001210/// Left-shift this APInt by shiftAmt.
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001211/// @brief Left-shift function.
Dan Gohman105c1d42008-02-29 01:40:47 +00001212APInt APInt::shl(const APInt &shiftAmt) const {
Nick Lewycky030c4502009-01-19 17:42:33 +00001213 // It's undefined behavior in C to shift by BitWidth or greater.
Chris Lattner77527f52009-01-21 18:09:24 +00001214 return shl((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001215}
1216
Chris Lattner77527f52009-01-21 18:09:24 +00001217APInt APInt::shlSlowCase(unsigned shiftAmt) const {
Reid Spencera5c84d92007-02-25 00:56:44 +00001218 // If all the bits were shifted out, the result is 0. This avoids issues
1219 // with shifting by the size of the integer type, which produces undefined
1220 // results. We define these "undefined results" to always be 0.
1221 if (shiftAmt == BitWidth)
1222 return APInt(BitWidth, 0);
1223
Reid Spencer81ee0202007-05-12 18:01:57 +00001224 // If none of the bits are shifted out, the result is *this. This avoids a
1225 // lshr by the words size in the loop below which can produce incorrect
1226 // results. It also avoids the expensive computation below for a common case.
1227 if (shiftAmt == 0)
1228 return *this;
1229
Reid Spencera5c84d92007-02-25 00:56:44 +00001230 // Create some space for the result.
1231 uint64_t * val = new uint64_t[getNumWords()];
1232
1233 // If we are shifting less than a word, do it the easy way
1234 if (shiftAmt < APINT_BITS_PER_WORD) {
1235 uint64_t carry = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001236 for (unsigned i = 0; i < getNumWords(); i++) {
Reid Spencera5c84d92007-02-25 00:56:44 +00001237 val[i] = pVal[i] << shiftAmt | carry;
1238 carry = pVal[i] >> (APINT_BITS_PER_WORD - shiftAmt);
1239 }
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001240 APInt Result(val, BitWidth);
1241 Result.clearUnusedBits();
1242 return Result;
Reid Spencer632ebdf2007-02-24 20:19:37 +00001243 }
1244
Reid Spencera5c84d92007-02-25 00:56:44 +00001245 // Compute some values needed by the remaining shift algorithms
Chris Lattner77527f52009-01-21 18:09:24 +00001246 unsigned wordShift = shiftAmt % APINT_BITS_PER_WORD;
1247 unsigned offset = shiftAmt / APINT_BITS_PER_WORD;
Reid Spencera5c84d92007-02-25 00:56:44 +00001248
1249 // If we are shifting whole words, just move whole words
1250 if (wordShift == 0) {
Chris Lattner77527f52009-01-21 18:09:24 +00001251 for (unsigned i = 0; i < offset; i++)
Reid Spencera5c84d92007-02-25 00:56:44 +00001252 val[i] = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001253 for (unsigned i = offset; i < getNumWords(); i++)
Reid Spencera5c84d92007-02-25 00:56:44 +00001254 val[i] = pVal[i-offset];
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001255 APInt Result(val, BitWidth);
1256 Result.clearUnusedBits();
1257 return Result;
Reid Spencer632ebdf2007-02-24 20:19:37 +00001258 }
Reid Spencera5c84d92007-02-25 00:56:44 +00001259
1260 // Copy whole words from this to Result.
Chris Lattner77527f52009-01-21 18:09:24 +00001261 unsigned i = getNumWords() - 1;
Reid Spencera5c84d92007-02-25 00:56:44 +00001262 for (; i > offset; --i)
1263 val[i] = pVal[i-offset] << wordShift |
1264 pVal[i-offset-1] >> (APINT_BITS_PER_WORD - wordShift);
Reid Spencerab0e08a2007-02-25 01:08:58 +00001265 val[offset] = pVal[0] << wordShift;
Reid Spencera5c84d92007-02-25 00:56:44 +00001266 for (i = 0; i < offset; ++i)
1267 val[i] = 0;
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001268 APInt Result(val, BitWidth);
1269 Result.clearUnusedBits();
1270 return Result;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001271}
1272
Dan Gohman105c1d42008-02-29 01:40:47 +00001273APInt APInt::rotl(const APInt &rotateAmt) const {
Chris Lattner77527f52009-01-21 18:09:24 +00001274 return rotl((unsigned)rotateAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001275}
1276
Chris Lattner77527f52009-01-21 18:09:24 +00001277APInt APInt::rotl(unsigned rotateAmt) const {
Eli Friedman2aae94f2011-12-22 03:15:35 +00001278 rotateAmt %= BitWidth;
Reid Spencer98ed7db2007-05-14 00:15:28 +00001279 if (rotateAmt == 0)
1280 return *this;
Eli Friedman2aae94f2011-12-22 03:15:35 +00001281 return shl(rotateAmt) | lshr(BitWidth - rotateAmt);
Reid Spencer4c50b522007-05-13 23:44:59 +00001282}
1283
Dan Gohman105c1d42008-02-29 01:40:47 +00001284APInt APInt::rotr(const APInt &rotateAmt) const {
Chris Lattner77527f52009-01-21 18:09:24 +00001285 return rotr((unsigned)rotateAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001286}
1287
Chris Lattner77527f52009-01-21 18:09:24 +00001288APInt APInt::rotr(unsigned rotateAmt) const {
Eli Friedman2aae94f2011-12-22 03:15:35 +00001289 rotateAmt %= BitWidth;
Reid Spencer98ed7db2007-05-14 00:15:28 +00001290 if (rotateAmt == 0)
1291 return *this;
Eli Friedman2aae94f2011-12-22 03:15:35 +00001292 return lshr(rotateAmt) | shl(BitWidth - rotateAmt);
Reid Spencer4c50b522007-05-13 23:44:59 +00001293}
Reid Spencerd99feaf2007-03-01 05:39:56 +00001294
1295// Square Root - this method computes and returns the square root of "this".
1296// Three mechanisms are used for computation. For small values (<= 5 bits),
1297// a table lookup is done. This gets some performance for common cases. For
1298// values using less than 52 bits, the value is converted to double and then
1299// the libc sqrt function is called. The result is rounded and then converted
1300// back to a uint64_t which is then used to construct the result. Finally,
Eric Christopher820256b2009-08-21 04:06:45 +00001301// the Babylonian method for computing square roots is used.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001302APInt APInt::sqrt() const {
1303
1304 // Determine the magnitude of the value.
Chris Lattner77527f52009-01-21 18:09:24 +00001305 unsigned magnitude = getActiveBits();
Reid Spencerd99feaf2007-03-01 05:39:56 +00001306
1307 // Use a fast table for some small values. This also gets rid of some
1308 // rounding errors in libc sqrt for small values.
1309 if (magnitude <= 5) {
Reid Spencer2f6ad4d2007-03-01 17:47:31 +00001310 static const uint8_t results[32] = {
Reid Spencerc8841d22007-03-01 06:23:32 +00001311 /* 0 */ 0,
1312 /* 1- 2 */ 1, 1,
Eric Christopher820256b2009-08-21 04:06:45 +00001313 /* 3- 6 */ 2, 2, 2, 2,
Reid Spencerc8841d22007-03-01 06:23:32 +00001314 /* 7-12 */ 3, 3, 3, 3, 3, 3,
1315 /* 13-20 */ 4, 4, 4, 4, 4, 4, 4, 4,
1316 /* 21-30 */ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
1317 /* 31 */ 6
1318 };
1319 return APInt(BitWidth, results[ (isSingleWord() ? VAL : pVal[0]) ]);
Reid Spencerd99feaf2007-03-01 05:39:56 +00001320 }
1321
1322 // If the magnitude of the value fits in less than 52 bits (the precision of
1323 // an IEEE double precision floating point value), then we can use the
1324 // libc sqrt function which will probably use a hardware sqrt computation.
1325 // This should be faster than the algorithm below.
Jeff Cohenb622c112007-03-05 00:00:42 +00001326 if (magnitude < 52) {
Eric Christopher820256b2009-08-21 04:06:45 +00001327 return APInt(BitWidth,
Reid Spencerd99feaf2007-03-01 05:39:56 +00001328 uint64_t(::round(::sqrt(double(isSingleWord()?VAL:pVal[0])))));
Jeff Cohenb622c112007-03-05 00:00:42 +00001329 }
Reid Spencerd99feaf2007-03-01 05:39:56 +00001330
1331 // Okay, all the short cuts are exhausted. We must compute it. The following
1332 // is a classical Babylonian method for computing the square root. This code
Sanjay Patel4cb54e02014-09-11 15:41:01 +00001333 // was adapted to APInt from a wikipedia article on such computations.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001334 // See http://www.wikipedia.org/ and go to the page named
Eric Christopher820256b2009-08-21 04:06:45 +00001335 // Calculate_an_integer_square_root.
Chris Lattner77527f52009-01-21 18:09:24 +00001336 unsigned nbits = BitWidth, i = 4;
Reid Spencerd99feaf2007-03-01 05:39:56 +00001337 APInt testy(BitWidth, 16);
1338 APInt x_old(BitWidth, 1);
1339 APInt x_new(BitWidth, 0);
1340 APInt two(BitWidth, 2);
1341
1342 // Select a good starting value using binary logarithms.
Eric Christopher820256b2009-08-21 04:06:45 +00001343 for (;; i += 2, testy = testy.shl(2))
Reid Spencerd99feaf2007-03-01 05:39:56 +00001344 if (i >= nbits || this->ule(testy)) {
1345 x_old = x_old.shl(i / 2);
1346 break;
1347 }
1348
Eric Christopher820256b2009-08-21 04:06:45 +00001349 // Use the Babylonian method to arrive at the integer square root:
Reid Spencerd99feaf2007-03-01 05:39:56 +00001350 for (;;) {
1351 x_new = (this->udiv(x_old) + x_old).udiv(two);
1352 if (x_old.ule(x_new))
1353 break;
1354 x_old = x_new;
1355 }
1356
1357 // Make sure we return the closest approximation
Eric Christopher820256b2009-08-21 04:06:45 +00001358 // NOTE: The rounding calculation below is correct. It will produce an
Reid Spencercf817562007-03-02 04:21:55 +00001359 // off-by-one discrepancy with results from pari/gp. That discrepancy has been
Eric Christopher820256b2009-08-21 04:06:45 +00001360 // determined to be a rounding issue with pari/gp as it begins to use a
Reid Spencercf817562007-03-02 04:21:55 +00001361 // floating point representation after 192 bits. There are no discrepancies
1362 // between this algorithm and pari/gp for bit widths < 192 bits.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001363 APInt square(x_old * x_old);
1364 APInt nextSquare((x_old + 1) * (x_old +1));
1365 if (this->ult(square))
1366 return x_old;
David Blaikie54c94622011-12-01 20:58:30 +00001367 assert(this->ule(nextSquare) && "Error in APInt::sqrt computation");
1368 APInt midpoint((nextSquare - square).udiv(two));
1369 APInt offset(*this - square);
1370 if (offset.ult(midpoint))
1371 return x_old;
Reid Spencerd99feaf2007-03-01 05:39:56 +00001372 return x_old + 1;
1373}
1374
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001375/// Computes the multiplicative inverse of this APInt for a given modulo. The
1376/// iterative extended Euclidean algorithm is used to solve for this value,
1377/// however we simplify it to speed up calculating only the inverse, and take
1378/// advantage of div+rem calculations. We also use some tricks to avoid copying
1379/// (potentially large) APInts around.
1380APInt APInt::multiplicativeInverse(const APInt& modulo) const {
1381 assert(ult(modulo) && "This APInt must be smaller than the modulo");
1382
1383 // Using the properties listed at the following web page (accessed 06/21/08):
1384 // http://www.numbertheory.org/php/euclid.html
1385 // (especially the properties numbered 3, 4 and 9) it can be proved that
1386 // BitWidth bits suffice for all the computations in the algorithm implemented
1387 // below. More precisely, this number of bits suffice if the multiplicative
1388 // inverse exists, but may not suffice for the general extended Euclidean
1389 // algorithm.
1390
1391 APInt r[2] = { modulo, *this };
1392 APInt t[2] = { APInt(BitWidth, 0), APInt(BitWidth, 1) };
1393 APInt q(BitWidth, 0);
Eric Christopher820256b2009-08-21 04:06:45 +00001394
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001395 unsigned i;
1396 for (i = 0; r[i^1] != 0; i ^= 1) {
1397 // An overview of the math without the confusing bit-flipping:
1398 // q = r[i-2] / r[i-1]
1399 // r[i] = r[i-2] % r[i-1]
1400 // t[i] = t[i-2] - t[i-1] * q
1401 udivrem(r[i], r[i^1], q, r[i]);
1402 t[i] -= t[i^1] * q;
1403 }
1404
1405 // If this APInt and the modulo are not coprime, there is no multiplicative
1406 // inverse, so return 0. We check this by looking at the next-to-last
1407 // remainder, which is the gcd(*this,modulo) as calculated by the Euclidean
1408 // algorithm.
1409 if (r[i] != 1)
1410 return APInt(BitWidth, 0);
1411
1412 // The next-to-last t is the multiplicative inverse. However, we are
1413 // interested in a positive inverse. Calcuate a positive one from a negative
1414 // one if necessary. A simple addition of the modulo suffices because
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00001415 // abs(t[i]) is known to be less than *this/2 (see the link above).
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001416 return t[i].isNegative() ? t[i] + modulo : t[i];
1417}
1418
Jay Foadfe0c6482009-04-30 10:15:35 +00001419/// Calculate the magic numbers required to implement a signed integer division
1420/// by a constant as a sequence of multiplies, adds and shifts. Requires that
1421/// the divisor not be 0, 1, or -1. Taken from "Hacker's Delight", Henry S.
1422/// Warren, Jr., chapter 10.
1423APInt::ms APInt::magic() const {
1424 const APInt& d = *this;
1425 unsigned p;
1426 APInt ad, anc, delta, q1, r1, q2, r2, t;
Jay Foadfe0c6482009-04-30 10:15:35 +00001427 APInt signedMin = APInt::getSignedMinValue(d.getBitWidth());
Jay Foadfe0c6482009-04-30 10:15:35 +00001428 struct ms mag;
Eric Christopher820256b2009-08-21 04:06:45 +00001429
Jay Foadfe0c6482009-04-30 10:15:35 +00001430 ad = d.abs();
1431 t = signedMin + (d.lshr(d.getBitWidth() - 1));
1432 anc = t - 1 - t.urem(ad); // absolute value of nc
1433 p = d.getBitWidth() - 1; // initialize p
1434 q1 = signedMin.udiv(anc); // initialize q1 = 2p/abs(nc)
1435 r1 = signedMin - q1*anc; // initialize r1 = rem(2p,abs(nc))
1436 q2 = signedMin.udiv(ad); // initialize q2 = 2p/abs(d)
1437 r2 = signedMin - q2*ad; // initialize r2 = rem(2p,abs(d))
1438 do {
1439 p = p + 1;
1440 q1 = q1<<1; // update q1 = 2p/abs(nc)
1441 r1 = r1<<1; // update r1 = rem(2p/abs(nc))
1442 if (r1.uge(anc)) { // must be unsigned comparison
1443 q1 = q1 + 1;
1444 r1 = r1 - anc;
1445 }
1446 q2 = q2<<1; // update q2 = 2p/abs(d)
1447 r2 = r2<<1; // update r2 = rem(2p/abs(d))
1448 if (r2.uge(ad)) { // must be unsigned comparison
1449 q2 = q2 + 1;
1450 r2 = r2 - ad;
1451 }
1452 delta = ad - r2;
Cameron Zwarich8731d0c2011-02-21 00:22:02 +00001453 } while (q1.ult(delta) || (q1 == delta && r1 == 0));
Eric Christopher820256b2009-08-21 04:06:45 +00001454
Jay Foadfe0c6482009-04-30 10:15:35 +00001455 mag.m = q2 + 1;
1456 if (d.isNegative()) mag.m = -mag.m; // resulting magic number
1457 mag.s = p - d.getBitWidth(); // resulting shift
1458 return mag;
1459}
1460
1461/// Calculate the magic numbers required to implement an unsigned integer
1462/// division by a constant as a sequence of multiplies, adds and shifts.
1463/// Requires that the divisor not be 0. Taken from "Hacker's Delight", Henry
1464/// S. Warren, Jr., chapter 10.
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001465/// LeadingZeros can be used to simplify the calculation if the upper bits
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001466/// of the divided value are known zero.
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001467APInt::mu APInt::magicu(unsigned LeadingZeros) const {
Jay Foadfe0c6482009-04-30 10:15:35 +00001468 const APInt& d = *this;
1469 unsigned p;
1470 APInt nc, delta, q1, r1, q2, r2;
1471 struct mu magu;
1472 magu.a = 0; // initialize "add" indicator
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001473 APInt allOnes = APInt::getAllOnesValue(d.getBitWidth()).lshr(LeadingZeros);
Jay Foadfe0c6482009-04-30 10:15:35 +00001474 APInt signedMin = APInt::getSignedMinValue(d.getBitWidth());
1475 APInt signedMax = APInt::getSignedMaxValue(d.getBitWidth());
1476
Benjamin Kramer3aab6a82012-07-11 18:31:59 +00001477 nc = allOnes - (allOnes - d).urem(d);
Jay Foadfe0c6482009-04-30 10:15:35 +00001478 p = d.getBitWidth() - 1; // initialize p
1479 q1 = signedMin.udiv(nc); // initialize q1 = 2p/nc
1480 r1 = signedMin - q1*nc; // initialize r1 = rem(2p,nc)
1481 q2 = signedMax.udiv(d); // initialize q2 = (2p-1)/d
1482 r2 = signedMax - q2*d; // initialize r2 = rem((2p-1),d)
1483 do {
1484 p = p + 1;
1485 if (r1.uge(nc - r1)) {
1486 q1 = q1 + q1 + 1; // update q1
1487 r1 = r1 + r1 - nc; // update r1
1488 }
1489 else {
1490 q1 = q1+q1; // update q1
1491 r1 = r1+r1; // update r1
1492 }
1493 if ((r2 + 1).uge(d - r2)) {
1494 if (q2.uge(signedMax)) magu.a = 1;
1495 q2 = q2+q2 + 1; // update q2
1496 r2 = r2+r2 + 1 - d; // update r2
1497 }
1498 else {
1499 if (q2.uge(signedMin)) magu.a = 1;
1500 q2 = q2+q2; // update q2
1501 r2 = r2+r2 + 1; // update r2
1502 }
1503 delta = d - 1 - r2;
1504 } while (p < d.getBitWidth()*2 &&
1505 (q1.ult(delta) || (q1 == delta && r1 == 0)));
1506 magu.m = q2 + 1; // resulting magic number
1507 magu.s = p - d.getBitWidth(); // resulting shift
1508 return magu;
1509}
1510
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001511/// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
1512/// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
1513/// variables here have the same names as in the algorithm. Comments explain
1514/// the algorithm and any deviation from it.
Chris Lattner77527f52009-01-21 18:09:24 +00001515static void KnuthDiv(unsigned *u, unsigned *v, unsigned *q, unsigned* r,
1516 unsigned m, unsigned n) {
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001517 assert(u && "Must provide dividend");
1518 assert(v && "Must provide divisor");
1519 assert(q && "Must provide quotient");
Yaron Keren39fc5a62015-03-26 19:45:19 +00001520 assert(u != v && u != q && v != q && "Must use different memory");
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001521 assert(n>1 && "n must be > 1");
1522
Yaron Keren39fc5a62015-03-26 19:45:19 +00001523 // b denotes the base of the number system. In our case b is 2^32.
1524 LLVM_CONSTEXPR uint64_t b = uint64_t(1) << 32;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001525
David Greenef32fcb42010-01-05 01:28:52 +00001526 DEBUG(dbgs() << "KnuthDiv: m=" << m << " n=" << n << '\n');
1527 DEBUG(dbgs() << "KnuthDiv: original:");
1528 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
1529 DEBUG(dbgs() << " by");
1530 DEBUG(for (int i = n; i >0; i--) dbgs() << " " << v[i-1]);
1531 DEBUG(dbgs() << '\n');
Eric Christopher820256b2009-08-21 04:06:45 +00001532 // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
1533 // u and v by d. Note that we have taken Knuth's advice here to use a power
1534 // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
1535 // 2 allows us to shift instead of multiply and it is easy to determine the
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001536 // shift amount from the leading zeros. We are basically normalizing the u
1537 // and v so that its high bits are shifted to the top of v's range without
1538 // overflow. Note that this can require an extra word in u so that u must
1539 // be of length m+n+1.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001540 unsigned shift = countLeadingZeros(v[n-1]);
Chris Lattner77527f52009-01-21 18:09:24 +00001541 unsigned v_carry = 0;
1542 unsigned u_carry = 0;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001543 if (shift) {
Chris Lattner77527f52009-01-21 18:09:24 +00001544 for (unsigned i = 0; i < m+n; ++i) {
1545 unsigned u_tmp = u[i] >> (32 - shift);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001546 u[i] = (u[i] << shift) | u_carry;
1547 u_carry = u_tmp;
Reid Spencer100502d2007-02-17 03:16:00 +00001548 }
Chris Lattner77527f52009-01-21 18:09:24 +00001549 for (unsigned i = 0; i < n; ++i) {
1550 unsigned v_tmp = v[i] >> (32 - shift);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001551 v[i] = (v[i] << shift) | v_carry;
1552 v_carry = v_tmp;
1553 }
1554 }
1555 u[m+n] = u_carry;
Yaron Keren39fc5a62015-03-26 19:45:19 +00001556
David Greenef32fcb42010-01-05 01:28:52 +00001557 DEBUG(dbgs() << "KnuthDiv: normal:");
1558 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
1559 DEBUG(dbgs() << " by");
1560 DEBUG(for (int i = n; i >0; i--) dbgs() << " " << v[i-1]);
1561 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001562
1563 // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
1564 int j = m;
1565 do {
David Greenef32fcb42010-01-05 01:28:52 +00001566 DEBUG(dbgs() << "KnuthDiv: quotient digit #" << j << '\n');
Eric Christopher820256b2009-08-21 04:06:45 +00001567 // D3. [Calculate q'.].
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001568 // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
1569 // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
1570 // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
1571 // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test
1572 // on v[n-2] determines at high speed most of the cases in which the trial
Eric Christopher820256b2009-08-21 04:06:45 +00001573 // value qp is one too large, and it eliminates all cases where qp is two
1574 // too large.
Reid Spencercb292e42007-02-23 01:57:13 +00001575 uint64_t dividend = ((uint64_t(u[j+n]) << 32) + u[j+n-1]);
David Greenef32fcb42010-01-05 01:28:52 +00001576 DEBUG(dbgs() << "KnuthDiv: dividend == " << dividend << '\n');
Reid Spencercb292e42007-02-23 01:57:13 +00001577 uint64_t qp = dividend / v[n-1];
1578 uint64_t rp = dividend % v[n-1];
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001579 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1580 qp--;
1581 rp += v[n-1];
Reid Spencerdf6cf5a2007-02-24 10:01:42 +00001582 if (rp < b && (qp == b || qp*v[n-2] > b*rp + u[j+n-2]))
Reid Spencera5e0d202007-02-24 03:58:46 +00001583 qp--;
Reid Spencercb292e42007-02-23 01:57:13 +00001584 }
David Greenef32fcb42010-01-05 01:28:52 +00001585 DEBUG(dbgs() << "KnuthDiv: qp == " << qp << ", rp == " << rp << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001586
Reid Spencercb292e42007-02-23 01:57:13 +00001587 // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with
1588 // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation
1589 // consists of a simple multiplication by a one-place number, combined with
Eric Christopher820256b2009-08-21 04:06:45 +00001590 // a subtraction.
Yaron Keren39fc5a62015-03-26 19:45:19 +00001591 // The digits (u[j+n]...u[j]) should be kept positive; if the result of
1592 // this step is actually negative, (u[j+n]...u[j]) should be left as the
1593 // true value plus b**(n+1), namely as the b's complement of
1594 // the true value, and a "borrow" to the left should be remembered.
Pawel Bylica86ac4472015-04-24 07:38:39 +00001595 int64_t borrow = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001596 for (unsigned i = 0; i < n; ++i) {
Pawel Bylica86ac4472015-04-24 07:38:39 +00001597 uint64_t p = uint64_t(qp) * uint64_t(v[i]);
1598 int64_t subres = int64_t(u[j+i]) - borrow - (unsigned)p;
1599 u[j+i] = (unsigned)subres;
1600 borrow = (p >> 32) - (subres >> 32);
1601 DEBUG(dbgs() << "KnuthDiv: u[j+i] = " << u[j+i]
Daniel Dunbar763ace92009-07-13 05:27:30 +00001602 << ", borrow = " << borrow << '\n');
Reid Spencera5e0d202007-02-24 03:58:46 +00001603 }
Pawel Bylica86ac4472015-04-24 07:38:39 +00001604 bool isNeg = u[j+n] < borrow;
1605 u[j+n] -= (unsigned)borrow;
1606
David Greenef32fcb42010-01-05 01:28:52 +00001607 DEBUG(dbgs() << "KnuthDiv: after subtraction:");
1608 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
1609 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001610
Eric Christopher820256b2009-08-21 04:06:45 +00001611 // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001612 // negative, go to step D6; otherwise go on to step D7.
Chris Lattner77527f52009-01-21 18:09:24 +00001613 q[j] = (unsigned)qp;
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001614 if (isNeg) {
Eric Christopher820256b2009-08-21 04:06:45 +00001615 // D6. [Add back]. The probability that this step is necessary is very
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001616 // small, on the order of only 2/b. Make sure that test data accounts for
Eric Christopher820256b2009-08-21 04:06:45 +00001617 // this possibility. Decrease q[j] by 1
Reid Spencercb292e42007-02-23 01:57:13 +00001618 q[j]--;
Eric Christopher820256b2009-08-21 04:06:45 +00001619 // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]).
1620 // A carry will occur to the left of u[j+n], and it should be ignored
Reid Spencercb292e42007-02-23 01:57:13 +00001621 // since it cancels with the borrow that occurred in D4.
1622 bool carry = false;
Chris Lattner77527f52009-01-21 18:09:24 +00001623 for (unsigned i = 0; i < n; i++) {
1624 unsigned limit = std::min(u[j+i],v[i]);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001625 u[j+i] += v[i] + carry;
Reid Spencera5e0d202007-02-24 03:58:46 +00001626 carry = u[j+i] < limit || (carry && u[j+i] == limit);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001627 }
Reid Spencera5e0d202007-02-24 03:58:46 +00001628 u[j+n] += carry;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001629 }
David Greenef32fcb42010-01-05 01:28:52 +00001630 DEBUG(dbgs() << "KnuthDiv: after correction:");
Yaron Keren39fc5a62015-03-26 19:45:19 +00001631 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
David Greenef32fcb42010-01-05 01:28:52 +00001632 DEBUG(dbgs() << "\nKnuthDiv: digit result = " << q[j] << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001633
Reid Spencercb292e42007-02-23 01:57:13 +00001634 // D7. [Loop on j.] Decrease j by one. Now if j >= 0, go back to D3.
1635 } while (--j >= 0);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001636
David Greenef32fcb42010-01-05 01:28:52 +00001637 DEBUG(dbgs() << "KnuthDiv: quotient:");
1638 DEBUG(for (int i = m; i >=0; i--) dbgs() <<" " << q[i]);
1639 DEBUG(dbgs() << '\n');
Reid Spencera5e0d202007-02-24 03:58:46 +00001640
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001641 // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
1642 // remainder may be obtained by dividing u[...] by d. If r is non-null we
1643 // compute the remainder (urem uses this).
1644 if (r) {
1645 // The value d is expressed by the "shift" value above since we avoided
1646 // multiplication by d by using a shift left. So, all we have to do is
1647 // shift right here. In order to mak
Reid Spencer468ad9112007-02-24 20:38:01 +00001648 if (shift) {
Chris Lattner77527f52009-01-21 18:09:24 +00001649 unsigned carry = 0;
David Greenef32fcb42010-01-05 01:28:52 +00001650 DEBUG(dbgs() << "KnuthDiv: remainder:");
Reid Spencer468ad9112007-02-24 20:38:01 +00001651 for (int i = n-1; i >= 0; i--) {
1652 r[i] = (u[i] >> shift) | carry;
1653 carry = u[i] << (32 - shift);
David Greenef32fcb42010-01-05 01:28:52 +00001654 DEBUG(dbgs() << " " << r[i]);
Reid Spencer468ad9112007-02-24 20:38:01 +00001655 }
1656 } else {
1657 for (int i = n-1; i >= 0; i--) {
1658 r[i] = u[i];
David Greenef32fcb42010-01-05 01:28:52 +00001659 DEBUG(dbgs() << " " << r[i]);
Reid Spencer468ad9112007-02-24 20:38:01 +00001660 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001661 }
David Greenef32fcb42010-01-05 01:28:52 +00001662 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001663 }
David Greenef32fcb42010-01-05 01:28:52 +00001664 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001665}
1666
Benjamin Kramerc321e532016-06-08 19:09:22 +00001667void APInt::divide(const APInt &LHS, unsigned lhsWords, const APInt &RHS,
1668 unsigned rhsWords, APInt *Quotient, APInt *Remainder) {
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001669 assert(lhsWords >= rhsWords && "Fractional result");
1670
Eric Christopher820256b2009-08-21 04:06:45 +00001671 // First, compose the values into an array of 32-bit words instead of
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001672 // 64-bit words. This is a necessity of both the "short division" algorithm
Dan Gohman4a618822010-02-10 16:03:48 +00001673 // and the Knuth "classical algorithm" which requires there to be native
Eric Christopher820256b2009-08-21 04:06:45 +00001674 // operations for +, -, and * on an m bit value with an m*2 bit result. We
1675 // can't use 64-bit operands here because we don't have native results of
1676 // 128-bits. Furthermore, casting the 64-bit values to 32-bit values won't
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001677 // work on large-endian machines.
Dan Gohmancff69532009-04-01 18:45:54 +00001678 uint64_t mask = ~0ull >> (sizeof(unsigned)*CHAR_BIT);
Chris Lattner77527f52009-01-21 18:09:24 +00001679 unsigned n = rhsWords * 2;
1680 unsigned m = (lhsWords * 2) - n;
Reid Spencer522ca7c2007-02-25 01:56:07 +00001681
1682 // Allocate space for the temporary values we need either on the stack, if
1683 // it will fit, or on the heap if it won't.
Chris Lattner77527f52009-01-21 18:09:24 +00001684 unsigned SPACE[128];
Craig Topperc10719f2014-04-07 04:17:22 +00001685 unsigned *U = nullptr;
1686 unsigned *V = nullptr;
1687 unsigned *Q = nullptr;
1688 unsigned *R = nullptr;
Reid Spencer522ca7c2007-02-25 01:56:07 +00001689 if ((Remainder?4:3)*n+2*m+1 <= 128) {
1690 U = &SPACE[0];
1691 V = &SPACE[m+n+1];
1692 Q = &SPACE[(m+n+1) + n];
1693 if (Remainder)
1694 R = &SPACE[(m+n+1) + n + (m+n)];
1695 } else {
Chris Lattner77527f52009-01-21 18:09:24 +00001696 U = new unsigned[m + n + 1];
1697 V = new unsigned[n];
1698 Q = new unsigned[m+n];
Reid Spencer522ca7c2007-02-25 01:56:07 +00001699 if (Remainder)
Chris Lattner77527f52009-01-21 18:09:24 +00001700 R = new unsigned[n];
Reid Spencer522ca7c2007-02-25 01:56:07 +00001701 }
1702
1703 // Initialize the dividend
Chris Lattner77527f52009-01-21 18:09:24 +00001704 memset(U, 0, (m+n+1)*sizeof(unsigned));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001705 for (unsigned i = 0; i < lhsWords; ++i) {
Reid Spencer867b4062007-02-22 00:58:45 +00001706 uint64_t tmp = (LHS.getNumWords() == 1 ? LHS.VAL : LHS.pVal[i]);
Chris Lattner77527f52009-01-21 18:09:24 +00001707 U[i * 2] = (unsigned)(tmp & mask);
Dan Gohmancff69532009-04-01 18:45:54 +00001708 U[i * 2 + 1] = (unsigned)(tmp >> (sizeof(unsigned)*CHAR_BIT));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001709 }
1710 U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
1711
Reid Spencer522ca7c2007-02-25 01:56:07 +00001712 // Initialize the divisor
Chris Lattner77527f52009-01-21 18:09:24 +00001713 memset(V, 0, (n)*sizeof(unsigned));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001714 for (unsigned i = 0; i < rhsWords; ++i) {
Reid Spencer867b4062007-02-22 00:58:45 +00001715 uint64_t tmp = (RHS.getNumWords() == 1 ? RHS.VAL : RHS.pVal[i]);
Chris Lattner77527f52009-01-21 18:09:24 +00001716 V[i * 2] = (unsigned)(tmp & mask);
Dan Gohmancff69532009-04-01 18:45:54 +00001717 V[i * 2 + 1] = (unsigned)(tmp >> (sizeof(unsigned)*CHAR_BIT));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001718 }
1719
Reid Spencer522ca7c2007-02-25 01:56:07 +00001720 // initialize the quotient and remainder
Chris Lattner77527f52009-01-21 18:09:24 +00001721 memset(Q, 0, (m+n) * sizeof(unsigned));
Reid Spencer522ca7c2007-02-25 01:56:07 +00001722 if (Remainder)
Chris Lattner77527f52009-01-21 18:09:24 +00001723 memset(R, 0, n * sizeof(unsigned));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001724
Eric Christopher820256b2009-08-21 04:06:45 +00001725 // Now, adjust m and n for the Knuth division. n is the number of words in
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001726 // the divisor. m is the number of words by which the dividend exceeds the
Eric Christopher820256b2009-08-21 04:06:45 +00001727 // divisor (i.e. m+n is the length of the dividend). These sizes must not
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001728 // contain any zero words or the Knuth algorithm fails.
1729 for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
1730 n--;
1731 m++;
1732 }
1733 for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
1734 m--;
1735
1736 // If we're left with only a single word for the divisor, Knuth doesn't work
1737 // so we implement the short division algorithm here. This is much simpler
1738 // and faster because we are certain that we can divide a 64-bit quantity
1739 // by a 32-bit quantity at hardware speed and short division is simply a
1740 // series of such operations. This is just like doing short division but we
1741 // are using base 2^32 instead of base 10.
1742 assert(n != 0 && "Divide by zero?");
1743 if (n == 1) {
Chris Lattner77527f52009-01-21 18:09:24 +00001744 unsigned divisor = V[0];
1745 unsigned remainder = 0;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001746 for (int i = m+n-1; i >= 0; i--) {
1747 uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i];
1748 if (partial_dividend == 0) {
1749 Q[i] = 0;
1750 remainder = 0;
1751 } else if (partial_dividend < divisor) {
1752 Q[i] = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001753 remainder = (unsigned)partial_dividend;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001754 } else if (partial_dividend == divisor) {
1755 Q[i] = 1;
1756 remainder = 0;
1757 } else {
Chris Lattner77527f52009-01-21 18:09:24 +00001758 Q[i] = (unsigned)(partial_dividend / divisor);
1759 remainder = (unsigned)(partial_dividend - (Q[i] * divisor));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001760 }
1761 }
1762 if (R)
1763 R[0] = remainder;
1764 } else {
1765 // Now we're ready to invoke the Knuth classical divide algorithm. In this
1766 // case n > 1.
1767 KnuthDiv(U, V, Q, R, m, n);
1768 }
1769
1770 // If the caller wants the quotient
1771 if (Quotient) {
1772 // Set up the Quotient value's memory.
1773 if (Quotient->BitWidth != LHS.BitWidth) {
1774 if (Quotient->isSingleWord())
1775 Quotient->VAL = 0;
1776 else
Reid Spencer7c16cd22007-02-26 23:38:21 +00001777 delete [] Quotient->pVal;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001778 Quotient->BitWidth = LHS.BitWidth;
1779 if (!Quotient->isSingleWord())
Reid Spencer58a6a432007-02-21 08:21:52 +00001780 Quotient->pVal = getClearedMemory(Quotient->getNumWords());
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001781 } else
Jay Foad25a5e4c2010-12-01 08:53:58 +00001782 Quotient->clearAllBits();
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001783
Eric Christopher820256b2009-08-21 04:06:45 +00001784 // The quotient is in Q. Reconstitute the quotient into Quotient's low
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001785 // order words.
Yaron Keren39fc5a62015-03-26 19:45:19 +00001786 // This case is currently dead as all users of divide() handle trivial cases
1787 // earlier.
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001788 if (lhsWords == 1) {
Eric Christopher820256b2009-08-21 04:06:45 +00001789 uint64_t tmp =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001790 uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2));
1791 if (Quotient->isSingleWord())
1792 Quotient->VAL = tmp;
1793 else
1794 Quotient->pVal[0] = tmp;
1795 } else {
1796 assert(!Quotient->isSingleWord() && "Quotient APInt not large enough");
1797 for (unsigned i = 0; i < lhsWords; ++i)
Eric Christopher820256b2009-08-21 04:06:45 +00001798 Quotient->pVal[i] =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001799 uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1800 }
1801 }
1802
1803 // If the caller wants the remainder
1804 if (Remainder) {
1805 // Set up the Remainder value's memory.
1806 if (Remainder->BitWidth != RHS.BitWidth) {
1807 if (Remainder->isSingleWord())
1808 Remainder->VAL = 0;
1809 else
Reid Spencer7c16cd22007-02-26 23:38:21 +00001810 delete [] Remainder->pVal;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001811 Remainder->BitWidth = RHS.BitWidth;
1812 if (!Remainder->isSingleWord())
Reid Spencer58a6a432007-02-21 08:21:52 +00001813 Remainder->pVal = getClearedMemory(Remainder->getNumWords());
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001814 } else
Jay Foad25a5e4c2010-12-01 08:53:58 +00001815 Remainder->clearAllBits();
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001816
1817 // The remainder is in R. Reconstitute the remainder into Remainder's low
1818 // order words.
1819 if (rhsWords == 1) {
Eric Christopher820256b2009-08-21 04:06:45 +00001820 uint64_t tmp =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001821 uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2));
1822 if (Remainder->isSingleWord())
1823 Remainder->VAL = tmp;
1824 else
1825 Remainder->pVal[0] = tmp;
1826 } else {
1827 assert(!Remainder->isSingleWord() && "Remainder APInt not large enough");
1828 for (unsigned i = 0; i < rhsWords; ++i)
Eric Christopher820256b2009-08-21 04:06:45 +00001829 Remainder->pVal[i] =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001830 uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1831 }
1832 }
1833
1834 // Clean up the memory we allocated.
Reid Spencer522ca7c2007-02-25 01:56:07 +00001835 if (U != &SPACE[0]) {
1836 delete [] U;
1837 delete [] V;
1838 delete [] Q;
1839 delete [] R;
1840 }
Reid Spencer100502d2007-02-17 03:16:00 +00001841}
1842
Reid Spencer1d072122007-02-16 22:36:51 +00001843APInt APInt::udiv(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +00001844 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer39867762007-02-17 02:07:07 +00001845
1846 // First, deal with the easy case
1847 if (isSingleWord()) {
1848 assert(RHS.VAL != 0 && "Divide by zero?");
1849 return APInt(BitWidth, VAL / RHS.VAL);
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001850 }
Reid Spencer39867762007-02-17 02:07:07 +00001851
Reid Spencer39867762007-02-17 02:07:07 +00001852 // Get some facts about the LHS and RHS number of bits and words
Chris Lattner77527f52009-01-21 18:09:24 +00001853 unsigned rhsBits = RHS.getActiveBits();
1854 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001855 assert(rhsWords && "Divided by zero???");
Chris Lattner77527f52009-01-21 18:09:24 +00001856 unsigned lhsBits = this->getActiveBits();
1857 unsigned lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001858
1859 // Deal with some degenerate cases
Eric Christopher820256b2009-08-21 04:06:45 +00001860 if (!lhsWords)
Reid Spencer58a6a432007-02-21 08:21:52 +00001861 // 0 / X ===> 0
Eric Christopher820256b2009-08-21 04:06:45 +00001862 return APInt(BitWidth, 0);
Reid Spencer58a6a432007-02-21 08:21:52 +00001863 else if (lhsWords < rhsWords || this->ult(RHS)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001864 // X / Y ===> 0, iff X < Y
Reid Spencer58a6a432007-02-21 08:21:52 +00001865 return APInt(BitWidth, 0);
1866 } else if (*this == RHS) {
1867 // X / X ===> 1
1868 return APInt(BitWidth, 1);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001869 } else if (lhsWords == 1 && rhsWords == 1) {
Reid Spencer39867762007-02-17 02:07:07 +00001870 // All high words are zero, just use native divide
Reid Spencer58a6a432007-02-21 08:21:52 +00001871 return APInt(BitWidth, this->pVal[0] / RHS.pVal[0]);
Reid Spencer39867762007-02-17 02:07:07 +00001872 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001873
1874 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1875 APInt Quotient(1,0); // to hold result.
Craig Topperc10719f2014-04-07 04:17:22 +00001876 divide(*this, lhsWords, RHS, rhsWords, &Quotient, nullptr);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001877 return Quotient;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001878}
1879
Jakub Staszak6605c602013-02-20 00:17:42 +00001880APInt APInt::sdiv(const APInt &RHS) const {
1881 if (isNegative()) {
1882 if (RHS.isNegative())
1883 return (-(*this)).udiv(-RHS);
1884 return -((-(*this)).udiv(RHS));
1885 }
1886 if (RHS.isNegative())
1887 return -(this->udiv(-RHS));
1888 return this->udiv(RHS);
1889}
1890
Reid Spencer1d072122007-02-16 22:36:51 +00001891APInt APInt::urem(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +00001892 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer39867762007-02-17 02:07:07 +00001893 if (isSingleWord()) {
1894 assert(RHS.VAL != 0 && "Remainder by zero?");
1895 return APInt(BitWidth, VAL % RHS.VAL);
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001896 }
Reid Spencer39867762007-02-17 02:07:07 +00001897
Reid Spencer58a6a432007-02-21 08:21:52 +00001898 // Get some facts about the LHS
Chris Lattner77527f52009-01-21 18:09:24 +00001899 unsigned lhsBits = getActiveBits();
1900 unsigned lhsWords = !lhsBits ? 0 : (whichWord(lhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001901
1902 // Get some facts about the RHS
Chris Lattner77527f52009-01-21 18:09:24 +00001903 unsigned rhsBits = RHS.getActiveBits();
1904 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001905 assert(rhsWords && "Performing remainder operation by zero ???");
1906
Reid Spencer39867762007-02-17 02:07:07 +00001907 // Check the degenerate cases
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001908 if (lhsWords == 0) {
Reid Spencer58a6a432007-02-21 08:21:52 +00001909 // 0 % Y ===> 0
1910 return APInt(BitWidth, 0);
1911 } else if (lhsWords < rhsWords || this->ult(RHS)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001912 // X % Y ===> X, iff X < Y
Reid Spencer58a6a432007-02-21 08:21:52 +00001913 return *this;
1914 } else if (*this == RHS) {
Reid Spencer39867762007-02-17 02:07:07 +00001915 // X % X == 0;
Reid Spencer58a6a432007-02-21 08:21:52 +00001916 return APInt(BitWidth, 0);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001917 } else if (lhsWords == 1) {
Reid Spencer39867762007-02-17 02:07:07 +00001918 // All high words are zero, just use native remainder
Reid Spencer58a6a432007-02-21 08:21:52 +00001919 return APInt(BitWidth, pVal[0] % RHS.pVal[0]);
Reid Spencer39867762007-02-17 02:07:07 +00001920 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001921
Reid Spencer4c50b522007-05-13 23:44:59 +00001922 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001923 APInt Remainder(1,0);
Craig Topperc10719f2014-04-07 04:17:22 +00001924 divide(*this, lhsWords, RHS, rhsWords, nullptr, &Remainder);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001925 return Remainder;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001926}
Reid Spencer100502d2007-02-17 03:16:00 +00001927
Jakub Staszak6605c602013-02-20 00:17:42 +00001928APInt APInt::srem(const APInt &RHS) const {
1929 if (isNegative()) {
1930 if (RHS.isNegative())
1931 return -((-(*this)).urem(-RHS));
1932 return -((-(*this)).urem(RHS));
1933 }
1934 if (RHS.isNegative())
1935 return this->urem(-RHS);
1936 return this->urem(RHS);
1937}
1938
Eric Christopher820256b2009-08-21 04:06:45 +00001939void APInt::udivrem(const APInt &LHS, const APInt &RHS,
Reid Spencer4c50b522007-05-13 23:44:59 +00001940 APInt &Quotient, APInt &Remainder) {
David Majnemer7f039202014-12-14 09:41:56 +00001941 assert(LHS.BitWidth == RHS.BitWidth && "Bit widths must be the same");
1942
1943 // First, deal with the easy case
1944 if (LHS.isSingleWord()) {
1945 assert(RHS.VAL != 0 && "Divide by zero?");
1946 uint64_t QuotVal = LHS.VAL / RHS.VAL;
1947 uint64_t RemVal = LHS.VAL % RHS.VAL;
1948 Quotient = APInt(LHS.BitWidth, QuotVal);
1949 Remainder = APInt(LHS.BitWidth, RemVal);
1950 return;
1951 }
1952
Reid Spencer4c50b522007-05-13 23:44:59 +00001953 // Get some size facts about the dividend and divisor
Chris Lattner77527f52009-01-21 18:09:24 +00001954 unsigned lhsBits = LHS.getActiveBits();
1955 unsigned lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
1956 unsigned rhsBits = RHS.getActiveBits();
1957 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer4c50b522007-05-13 23:44:59 +00001958
1959 // Check the degenerate cases
Eric Christopher820256b2009-08-21 04:06:45 +00001960 if (lhsWords == 0) {
Reid Spencer4c50b522007-05-13 23:44:59 +00001961 Quotient = 0; // 0 / Y ===> 0
1962 Remainder = 0; // 0 % Y ===> 0
1963 return;
Eric Christopher820256b2009-08-21 04:06:45 +00001964 }
1965
1966 if (lhsWords < rhsWords || LHS.ult(RHS)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001967 Remainder = LHS; // X % Y ===> X, iff X < Y
1968 Quotient = 0; // X / Y ===> 0, iff X < Y
Reid Spencer4c50b522007-05-13 23:44:59 +00001969 return;
Eric Christopher820256b2009-08-21 04:06:45 +00001970 }
1971
Reid Spencer4c50b522007-05-13 23:44:59 +00001972 if (LHS == RHS) {
1973 Quotient = 1; // X / X ===> 1
1974 Remainder = 0; // X % X ===> 0;
1975 return;
Eric Christopher820256b2009-08-21 04:06:45 +00001976 }
1977
Reid Spencer4c50b522007-05-13 23:44:59 +00001978 if (lhsWords == 1 && rhsWords == 1) {
1979 // There is only one word to consider so use the native versions.
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001980 uint64_t lhsValue = LHS.isSingleWord() ? LHS.VAL : LHS.pVal[0];
1981 uint64_t rhsValue = RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
1982 Quotient = APInt(LHS.getBitWidth(), lhsValue / rhsValue);
1983 Remainder = APInt(LHS.getBitWidth(), lhsValue % rhsValue);
Reid Spencer4c50b522007-05-13 23:44:59 +00001984 return;
1985 }
1986
1987 // Okay, lets do it the long way
1988 divide(LHS, lhsWords, RHS, rhsWords, &Quotient, &Remainder);
1989}
1990
Jakub Staszak6605c602013-02-20 00:17:42 +00001991void APInt::sdivrem(const APInt &LHS, const APInt &RHS,
1992 APInt &Quotient, APInt &Remainder) {
1993 if (LHS.isNegative()) {
1994 if (RHS.isNegative())
1995 APInt::udivrem(-LHS, -RHS, Quotient, Remainder);
1996 else {
1997 APInt::udivrem(-LHS, RHS, Quotient, Remainder);
1998 Quotient = -Quotient;
1999 }
2000 Remainder = -Remainder;
2001 } else if (RHS.isNegative()) {
2002 APInt::udivrem(LHS, -RHS, Quotient, Remainder);
2003 Quotient = -Quotient;
2004 } else {
2005 APInt::udivrem(LHS, RHS, Quotient, Remainder);
2006 }
2007}
2008
Chris Lattner2c819b02010-10-13 23:54:10 +00002009APInt APInt::sadd_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00002010 APInt Res = *this+RHS;
2011 Overflow = isNonNegative() == RHS.isNonNegative() &&
2012 Res.isNonNegative() != isNonNegative();
2013 return Res;
2014}
2015
Chris Lattner698661c2010-10-14 00:05:07 +00002016APInt APInt::uadd_ov(const APInt &RHS, bool &Overflow) const {
2017 APInt Res = *this+RHS;
2018 Overflow = Res.ult(RHS);
2019 return Res;
2020}
2021
Chris Lattner2c819b02010-10-13 23:54:10 +00002022APInt APInt::ssub_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00002023 APInt Res = *this - RHS;
2024 Overflow = isNonNegative() != RHS.isNonNegative() &&
2025 Res.isNonNegative() != isNonNegative();
2026 return Res;
2027}
2028
Chris Lattner698661c2010-10-14 00:05:07 +00002029APInt APInt::usub_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattnerb9681ad2010-10-14 00:30:00 +00002030 APInt Res = *this-RHS;
2031 Overflow = Res.ugt(*this);
Chris Lattner698661c2010-10-14 00:05:07 +00002032 return Res;
2033}
2034
Chris Lattner2c819b02010-10-13 23:54:10 +00002035APInt APInt::sdiv_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00002036 // MININT/-1 --> overflow.
2037 Overflow = isMinSignedValue() && RHS.isAllOnesValue();
2038 return sdiv(RHS);
2039}
2040
Chris Lattner2c819b02010-10-13 23:54:10 +00002041APInt APInt::smul_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00002042 APInt Res = *this * RHS;
2043
2044 if (*this != 0 && RHS != 0)
2045 Overflow = Res.sdiv(RHS) != *this || Res.sdiv(*this) != RHS;
2046 else
2047 Overflow = false;
2048 return Res;
2049}
2050
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00002051APInt APInt::umul_ov(const APInt &RHS, bool &Overflow) const {
2052 APInt Res = *this * RHS;
2053
2054 if (*this != 0 && RHS != 0)
2055 Overflow = Res.udiv(RHS) != *this || Res.udiv(*this) != RHS;
2056 else
2057 Overflow = false;
2058 return Res;
2059}
2060
David Majnemera2521382014-10-13 21:48:30 +00002061APInt APInt::sshl_ov(const APInt &ShAmt, bool &Overflow) const {
2062 Overflow = ShAmt.uge(getBitWidth());
Chris Lattner79bdd882010-10-13 23:46:33 +00002063 if (Overflow)
David Majnemera2521382014-10-13 21:48:30 +00002064 return APInt(BitWidth, 0);
Chris Lattner79bdd882010-10-13 23:46:33 +00002065
2066 if (isNonNegative()) // Don't allow sign change.
David Majnemera2521382014-10-13 21:48:30 +00002067 Overflow = ShAmt.uge(countLeadingZeros());
Chris Lattner79bdd882010-10-13 23:46:33 +00002068 else
David Majnemera2521382014-10-13 21:48:30 +00002069 Overflow = ShAmt.uge(countLeadingOnes());
Chris Lattner79bdd882010-10-13 23:46:33 +00002070
2071 return *this << ShAmt;
2072}
2073
David Majnemera2521382014-10-13 21:48:30 +00002074APInt APInt::ushl_ov(const APInt &ShAmt, bool &Overflow) const {
2075 Overflow = ShAmt.uge(getBitWidth());
2076 if (Overflow)
2077 return APInt(BitWidth, 0);
2078
2079 Overflow = ShAmt.ugt(countLeadingZeros());
2080
2081 return *this << ShAmt;
2082}
2083
Chris Lattner79bdd882010-10-13 23:46:33 +00002084
2085
2086
Benjamin Kramer92d89982010-07-14 22:38:02 +00002087void APInt::fromString(unsigned numbits, StringRef str, uint8_t radix) {
Reid Spencer1ba83352007-02-21 03:55:44 +00002088 // Check our assumptions here
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00002089 assert(!str.empty() && "Invalid string length");
Douglas Gregor663c0682011-09-14 15:54:46 +00002090 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 ||
2091 radix == 36) &&
2092 "Radix should be 2, 8, 10, 16, or 36!");
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00002093
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00002094 StringRef::iterator p = str.begin();
2095 size_t slen = str.size();
2096 bool isNeg = *p == '-';
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00002097 if (*p == '-' || *p == '+') {
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00002098 p++;
2099 slen--;
Eric Christopher43a1dec2009-08-21 04:10:31 +00002100 assert(slen && "String is only a sign, needs a value.");
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00002101 }
Chris Lattnerdad2d092007-05-03 18:15:36 +00002102 assert((slen <= numbits || radix != 2) && "Insufficient bit width");
Chris Lattnerb869a0a2009-04-25 18:34:04 +00002103 assert(((slen-1)*3 <= numbits || radix != 8) && "Insufficient bit width");
2104 assert(((slen-1)*4 <= numbits || radix != 16) && "Insufficient bit width");
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002105 assert((((slen-1)*64)/22 <= numbits || radix != 10) &&
2106 "Insufficient bit width");
Reid Spencer1ba83352007-02-21 03:55:44 +00002107
2108 // Allocate memory
2109 if (!isSingleWord())
2110 pVal = getClearedMemory(getNumWords());
2111
2112 // Figure out if we can shift instead of multiply
Chris Lattner77527f52009-01-21 18:09:24 +00002113 unsigned shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0);
Reid Spencer1ba83352007-02-21 03:55:44 +00002114
2115 // Set up an APInt for the digit to add outside the loop so we don't
2116 // constantly construct/destruct it.
2117 APInt apdigit(getBitWidth(), 0);
2118 APInt apradix(getBitWidth(), radix);
2119
2120 // Enter digit traversal loop
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00002121 for (StringRef::iterator e = str.end(); p != e; ++p) {
Erick Tryzelaardadb15712009-08-21 03:15:28 +00002122 unsigned digit = getDigit(*p, radix);
Erick Tryzelaar60964092009-08-21 06:48:37 +00002123 assert(digit < radix && "Invalid character in digit string");
Reid Spencer1ba83352007-02-21 03:55:44 +00002124
Reid Spencera93c9812007-05-16 19:18:22 +00002125 // Shift or multiply the value by the radix
Chris Lattnerb869a0a2009-04-25 18:34:04 +00002126 if (slen > 1) {
2127 if (shift)
2128 *this <<= shift;
2129 else
2130 *this *= apradix;
2131 }
Reid Spencer1ba83352007-02-21 03:55:44 +00002132
2133 // Add in the digit we just interpreted
Reid Spencer632ebdf2007-02-24 20:19:37 +00002134 if (apdigit.isSingleWord())
2135 apdigit.VAL = digit;
2136 else
2137 apdigit.pVal[0] = digit;
Reid Spencer1ba83352007-02-21 03:55:44 +00002138 *this += apdigit;
Reid Spencer100502d2007-02-17 03:16:00 +00002139 }
Reid Spencerb6b5cc32007-02-25 23:44:53 +00002140 // If its negative, put it in two's complement form
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00002141 if (isNeg) {
Jakub Staszak773be0c2013-03-20 23:56:19 +00002142 --(*this);
Jay Foad25a5e4c2010-12-01 08:53:58 +00002143 this->flipAllBits();
Reid Spencerb6b5cc32007-02-25 23:44:53 +00002144 }
Reid Spencer100502d2007-02-17 03:16:00 +00002145}
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002146
Chris Lattner17f71652008-08-17 07:19:36 +00002147void APInt::toString(SmallVectorImpl<char> &Str, unsigned Radix,
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002148 bool Signed, bool formatAsCLiteral) const {
Douglas Gregor663c0682011-09-14 15:54:46 +00002149 assert((Radix == 10 || Radix == 8 || Radix == 16 || Radix == 2 ||
2150 Radix == 36) &&
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00002151 "Radix should be 2, 8, 10, 16, or 36!");
Eric Christopher820256b2009-08-21 04:06:45 +00002152
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002153 const char *Prefix = "";
2154 if (formatAsCLiteral) {
2155 switch (Radix) {
2156 case 2:
2157 // Binary literals are a non-standard extension added in gcc 4.3:
2158 // http://gcc.gnu.org/onlinedocs/gcc-4.3.0/gcc/Binary-constants.html
2159 Prefix = "0b";
2160 break;
2161 case 8:
2162 Prefix = "0";
2163 break;
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00002164 case 10:
2165 break; // No prefix
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002166 case 16:
2167 Prefix = "0x";
2168 break;
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00002169 default:
2170 llvm_unreachable("Invalid radix!");
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002171 }
2172 }
2173
Chris Lattner17f71652008-08-17 07:19:36 +00002174 // First, check for a zero value and just short circuit the logic below.
2175 if (*this == 0) {
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002176 while (*Prefix) {
2177 Str.push_back(*Prefix);
2178 ++Prefix;
2179 };
Chris Lattner17f71652008-08-17 07:19:36 +00002180 Str.push_back('0');
2181 return;
2182 }
Eric Christopher820256b2009-08-21 04:06:45 +00002183
Douglas Gregor663c0682011-09-14 15:54:46 +00002184 static const char Digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Eric Christopher820256b2009-08-21 04:06:45 +00002185
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002186 if (isSingleWord()) {
Chris Lattner17f71652008-08-17 07:19:36 +00002187 char Buffer[65];
2188 char *BufPtr = Buffer+65;
Eric Christopher820256b2009-08-21 04:06:45 +00002189
Chris Lattner17f71652008-08-17 07:19:36 +00002190 uint64_t N;
Chris Lattnerb91c9032010-08-18 00:33:47 +00002191 if (!Signed) {
Chris Lattner17f71652008-08-17 07:19:36 +00002192 N = getZExtValue();
Chris Lattnerb91c9032010-08-18 00:33:47 +00002193 } else {
2194 int64_t I = getSExtValue();
2195 if (I >= 0) {
2196 N = I;
2197 } else {
2198 Str.push_back('-');
2199 N = -(uint64_t)I;
2200 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002201 }
Eric Christopher820256b2009-08-21 04:06:45 +00002202
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002203 while (*Prefix) {
2204 Str.push_back(*Prefix);
2205 ++Prefix;
2206 };
2207
Chris Lattner17f71652008-08-17 07:19:36 +00002208 while (N) {
2209 *--BufPtr = Digits[N % Radix];
2210 N /= Radix;
2211 }
2212 Str.append(BufPtr, Buffer+65);
2213 return;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002214 }
2215
Chris Lattner17f71652008-08-17 07:19:36 +00002216 APInt Tmp(*this);
Eric Christopher820256b2009-08-21 04:06:45 +00002217
Chris Lattner17f71652008-08-17 07:19:36 +00002218 if (Signed && isNegative()) {
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002219 // They want to print the signed version and it is a negative value
2220 // Flip the bits and add one to turn it into the equivalent positive
2221 // value and put a '-' in the result.
Jay Foad25a5e4c2010-12-01 08:53:58 +00002222 Tmp.flipAllBits();
Jakub Staszak773be0c2013-03-20 23:56:19 +00002223 ++Tmp;
Chris Lattner17f71652008-08-17 07:19:36 +00002224 Str.push_back('-');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002225 }
Eric Christopher820256b2009-08-21 04:06:45 +00002226
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002227 while (*Prefix) {
2228 Str.push_back(*Prefix);
2229 ++Prefix;
2230 };
2231
Chris Lattner17f71652008-08-17 07:19:36 +00002232 // We insert the digits backward, then reverse them to get the right order.
2233 unsigned StartDig = Str.size();
Eric Christopher820256b2009-08-21 04:06:45 +00002234
2235 // For the 2, 8 and 16 bit cases, we can just shift instead of divide
2236 // because the number of bits per digit (1, 3 and 4 respectively) divides
Chris Lattner17f71652008-08-17 07:19:36 +00002237 // equaly. We just shift until the value is zero.
Douglas Gregor663c0682011-09-14 15:54:46 +00002238 if (Radix == 2 || Radix == 8 || Radix == 16) {
Chris Lattner17f71652008-08-17 07:19:36 +00002239 // Just shift tmp right for each digit width until it becomes zero
2240 unsigned ShiftAmt = (Radix == 16 ? 4 : (Radix == 8 ? 3 : 1));
2241 unsigned MaskAmt = Radix - 1;
Eric Christopher820256b2009-08-21 04:06:45 +00002242
Chris Lattner17f71652008-08-17 07:19:36 +00002243 while (Tmp != 0) {
2244 unsigned Digit = unsigned(Tmp.getRawData()[0]) & MaskAmt;
2245 Str.push_back(Digits[Digit]);
2246 Tmp = Tmp.lshr(ShiftAmt);
2247 }
2248 } else {
Douglas Gregor663c0682011-09-14 15:54:46 +00002249 APInt divisor(Radix == 10? 4 : 8, Radix);
Chris Lattner17f71652008-08-17 07:19:36 +00002250 while (Tmp != 0) {
2251 APInt APdigit(1, 0);
2252 APInt tmp2(Tmp.getBitWidth(), 0);
Eric Christopher820256b2009-08-21 04:06:45 +00002253 divide(Tmp, Tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2,
Chris Lattner17f71652008-08-17 07:19:36 +00002254 &APdigit);
Chris Lattner77527f52009-01-21 18:09:24 +00002255 unsigned Digit = (unsigned)APdigit.getZExtValue();
Chris Lattner17f71652008-08-17 07:19:36 +00002256 assert(Digit < Radix && "divide failed");
2257 Str.push_back(Digits[Digit]);
2258 Tmp = tmp2;
2259 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002260 }
Eric Christopher820256b2009-08-21 04:06:45 +00002261
Chris Lattner17f71652008-08-17 07:19:36 +00002262 // Reverse the digits before returning.
2263 std::reverse(Str.begin()+StartDig, Str.end());
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002264}
2265
Pawel Bylica6eeeac72015-04-06 13:31:39 +00002266/// Returns the APInt as a std::string. Note that this is an inefficient method.
2267/// It is better to pass in a SmallVector/SmallString to the methods above.
Chris Lattner17f71652008-08-17 07:19:36 +00002268std::string APInt::toString(unsigned Radix = 10, bool Signed = true) const {
2269 SmallString<40> S;
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002270 toString(S, Radix, Signed, /* formatAsCLiteral = */false);
Daniel Dunbar8b0b1152009-08-19 20:07:03 +00002271 return S.str();
Reid Spencer1ba83352007-02-21 03:55:44 +00002272}
Chris Lattner6b695682007-08-16 15:56:55 +00002273
Chris Lattner17f71652008-08-17 07:19:36 +00002274
Yaron Kereneb2a2542016-01-29 20:50:44 +00002275LLVM_DUMP_METHOD void APInt::dump() const {
Chris Lattner17f71652008-08-17 07:19:36 +00002276 SmallString<40> S, U;
2277 this->toStringUnsigned(U);
2278 this->toStringSigned(S);
David Greenef32fcb42010-01-05 01:28:52 +00002279 dbgs() << "APInt(" << BitWidth << "b, "
Yaron Keren09fb7c62015-03-10 07:33:23 +00002280 << U << "u " << S << "s)";
Chris Lattner17f71652008-08-17 07:19:36 +00002281}
2282
Chris Lattner0c19df42008-08-23 22:23:09 +00002283void APInt::print(raw_ostream &OS, bool isSigned) const {
Chris Lattner17f71652008-08-17 07:19:36 +00002284 SmallString<40> S;
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002285 this->toString(S, 10, isSigned, /* formatAsCLiteral = */false);
Yaron Keren92e1b622015-03-18 10:17:07 +00002286 OS << S;
Chris Lattner17f71652008-08-17 07:19:36 +00002287}
2288
Chris Lattner6b695682007-08-16 15:56:55 +00002289// This implements a variety of operations on a representation of
2290// arbitrary precision, two's-complement, bignum integer values.
2291
Chris Lattner96cffa62009-08-23 23:11:28 +00002292// Assumed by lowHalf, highHalf, partMSB and partLSB. A fairly safe
2293// and unrestricting assumption.
Benjamin Kramer7000ca32014-10-12 17:56:40 +00002294static_assert(integerPartWidth % 2 == 0, "Part width must be divisible by 2!");
Chris Lattner6b695682007-08-16 15:56:55 +00002295
2296/* Some handy functions local to this file. */
2297namespace {
2298
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002299 /* Returns the integer part with the least significant BITS set.
2300 BITS cannot be zero. */
Dan Gohmanf4bc7822008-04-10 21:11:47 +00002301 static inline integerPart
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002302 lowBitMask(unsigned int bits)
2303 {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002304 assert(bits != 0 && bits <= integerPartWidth);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002305
2306 return ~(integerPart) 0 >> (integerPartWidth - bits);
2307 }
2308
Neil Boothc8b650a2007-10-06 00:43:45 +00002309 /* Returns the value of the lower half of PART. */
Dan Gohmanf4bc7822008-04-10 21:11:47 +00002310 static inline integerPart
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002311 lowHalf(integerPart part)
2312 {
2313 return part & lowBitMask(integerPartWidth / 2);
2314 }
2315
Neil Boothc8b650a2007-10-06 00:43:45 +00002316 /* Returns the value of the upper half of PART. */
Dan Gohmanf4bc7822008-04-10 21:11:47 +00002317 static inline integerPart
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002318 highHalf(integerPart part)
2319 {
2320 return part >> (integerPartWidth / 2);
2321 }
2322
Neil Boothc8b650a2007-10-06 00:43:45 +00002323 /* Returns the bit number of the most significant set bit of a part.
2324 If the input number has no bits set -1U is returned. */
Dan Gohmanf4bc7822008-04-10 21:11:47 +00002325 static unsigned int
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002326 partMSB(integerPart value)
Chris Lattner6b695682007-08-16 15:56:55 +00002327 {
Benjamin Kramerb565f892013-06-01 11:26:39 +00002328 return findLastSet(value, ZB_Max);
Chris Lattner6b695682007-08-16 15:56:55 +00002329 }
2330
Neil Boothc8b650a2007-10-06 00:43:45 +00002331 /* Returns the bit number of the least significant set bit of a
2332 part. If the input number has no bits set -1U is returned. */
Dan Gohmanf4bc7822008-04-10 21:11:47 +00002333 static unsigned int
Chris Lattner6b695682007-08-16 15:56:55 +00002334 partLSB(integerPart value)
2335 {
Benjamin Kramerb565f892013-06-01 11:26:39 +00002336 return findFirstSet(value, ZB_Max);
Chris Lattner6b695682007-08-16 15:56:55 +00002337 }
Alexander Kornienkof00654e2015-06-23 09:49:53 +00002338}
Chris Lattner6b695682007-08-16 15:56:55 +00002339
2340/* Sets the least significant part of a bignum to the input value, and
2341 zeroes out higher parts. */
2342void
2343APInt::tcSet(integerPart *dst, integerPart part, unsigned int parts)
2344{
2345 unsigned int i;
2346
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002347 assert(parts > 0);
Neil Boothb6182162007-10-08 13:47:12 +00002348
Chris Lattner6b695682007-08-16 15:56:55 +00002349 dst[0] = part;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002350 for (i = 1; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002351 dst[i] = 0;
2352}
2353
2354/* Assign one bignum to another. */
2355void
2356APInt::tcAssign(integerPart *dst, const integerPart *src, unsigned int parts)
2357{
2358 unsigned int i;
2359
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002360 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002361 dst[i] = src[i];
2362}
2363
2364/* Returns true if a bignum is zero, false otherwise. */
2365bool
2366APInt::tcIsZero(const integerPart *src, unsigned int parts)
2367{
2368 unsigned int i;
2369
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002370 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002371 if (src[i])
2372 return false;
2373
2374 return true;
2375}
2376
2377/* Extract the given bit of a bignum; returns 0 or 1. */
2378int
2379APInt::tcExtractBit(const integerPart *parts, unsigned int bit)
2380{
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002381 return (parts[bit / integerPartWidth] &
2382 ((integerPart) 1 << bit % integerPartWidth)) != 0;
Chris Lattner6b695682007-08-16 15:56:55 +00002383}
2384
John McCalldcb9a7a2010-02-28 02:51:25 +00002385/* Set the given bit of a bignum. */
Chris Lattner6b695682007-08-16 15:56:55 +00002386void
2387APInt::tcSetBit(integerPart *parts, unsigned int bit)
2388{
2389 parts[bit / integerPartWidth] |= (integerPart) 1 << (bit % integerPartWidth);
2390}
2391
John McCalldcb9a7a2010-02-28 02:51:25 +00002392/* Clears the given bit of a bignum. */
2393void
2394APInt::tcClearBit(integerPart *parts, unsigned int bit)
2395{
2396 parts[bit / integerPartWidth] &=
2397 ~((integerPart) 1 << (bit % integerPartWidth));
2398}
2399
Neil Boothc8b650a2007-10-06 00:43:45 +00002400/* Returns the bit number of the least significant set bit of a
2401 number. If the input number has no bits set -1U is returned. */
Chris Lattner6b695682007-08-16 15:56:55 +00002402unsigned int
2403APInt::tcLSB(const integerPart *parts, unsigned int n)
2404{
2405 unsigned int i, lsb;
2406
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002407 for (i = 0; i < n; i++) {
Chris Lattner6b695682007-08-16 15:56:55 +00002408 if (parts[i] != 0) {
2409 lsb = partLSB(parts[i]);
2410
2411 return lsb + i * integerPartWidth;
2412 }
2413 }
2414
2415 return -1U;
2416}
2417
Neil Boothc8b650a2007-10-06 00:43:45 +00002418/* Returns the bit number of the most significant set bit of a number.
2419 If the input number has no bits set -1U is returned. */
Chris Lattner6b695682007-08-16 15:56:55 +00002420unsigned int
2421APInt::tcMSB(const integerPart *parts, unsigned int n)
2422{
2423 unsigned int msb;
2424
2425 do {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002426 --n;
Chris Lattner6b695682007-08-16 15:56:55 +00002427
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002428 if (parts[n] != 0) {
2429 msb = partMSB(parts[n]);
Chris Lattner6b695682007-08-16 15:56:55 +00002430
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002431 return msb + n * integerPartWidth;
2432 }
Chris Lattner6b695682007-08-16 15:56:55 +00002433 } while (n);
2434
2435 return -1U;
2436}
2437
Neil Boothb6182162007-10-08 13:47:12 +00002438/* Copy the bit vector of width srcBITS from SRC, starting at bit
2439 srcLSB, to DST, of dstCOUNT parts, such that the bit srcLSB becomes
2440 the least significant bit of DST. All high bits above srcBITS in
2441 DST are zero-filled. */
2442void
Evan Chengdb338f32009-05-21 23:47:47 +00002443APInt::tcExtract(integerPart *dst, unsigned int dstCount,const integerPart *src,
Neil Boothb6182162007-10-08 13:47:12 +00002444 unsigned int srcBits, unsigned int srcLSB)
2445{
2446 unsigned int firstSrcPart, dstParts, shift, n;
2447
2448 dstParts = (srcBits + integerPartWidth - 1) / integerPartWidth;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002449 assert(dstParts <= dstCount);
Neil Boothb6182162007-10-08 13:47:12 +00002450
2451 firstSrcPart = srcLSB / integerPartWidth;
2452 tcAssign (dst, src + firstSrcPart, dstParts);
2453
2454 shift = srcLSB % integerPartWidth;
2455 tcShiftRight (dst, dstParts, shift);
2456
2457 /* We now have (dstParts * integerPartWidth - shift) bits from SRC
2458 in DST. If this is less that srcBits, append the rest, else
2459 clear the high bits. */
2460 n = dstParts * integerPartWidth - shift;
2461 if (n < srcBits) {
2462 integerPart mask = lowBitMask (srcBits - n);
2463 dst[dstParts - 1] |= ((src[firstSrcPart + dstParts] & mask)
2464 << n % integerPartWidth);
2465 } else if (n > srcBits) {
Neil Booth7e74b172007-10-12 15:31:31 +00002466 if (srcBits % integerPartWidth)
2467 dst[dstParts - 1] &= lowBitMask (srcBits % integerPartWidth);
Neil Boothb6182162007-10-08 13:47:12 +00002468 }
2469
2470 /* Clear high parts. */
2471 while (dstParts < dstCount)
2472 dst[dstParts++] = 0;
2473}
2474
Chris Lattner6b695682007-08-16 15:56:55 +00002475/* DST += RHS + C where C is zero or one. Returns the carry flag. */
2476integerPart
2477APInt::tcAdd(integerPart *dst, const integerPart *rhs,
2478 integerPart c, unsigned int parts)
2479{
2480 unsigned int i;
2481
2482 assert(c <= 1);
2483
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002484 for (i = 0; i < parts; i++) {
Chris Lattner6b695682007-08-16 15:56:55 +00002485 integerPart l;
2486
2487 l = dst[i];
2488 if (c) {
2489 dst[i] += rhs[i] + 1;
2490 c = (dst[i] <= l);
2491 } else {
2492 dst[i] += rhs[i];
2493 c = (dst[i] < l);
2494 }
2495 }
2496
2497 return c;
2498}
2499
2500/* DST -= RHS + C where C is zero or one. Returns the carry flag. */
2501integerPart
2502APInt::tcSubtract(integerPart *dst, const integerPart *rhs,
2503 integerPart c, unsigned int parts)
2504{
2505 unsigned int i;
2506
2507 assert(c <= 1);
2508
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002509 for (i = 0; i < parts; i++) {
Chris Lattner6b695682007-08-16 15:56:55 +00002510 integerPart l;
2511
2512 l = dst[i];
2513 if (c) {
2514 dst[i] -= rhs[i] + 1;
2515 c = (dst[i] >= l);
2516 } else {
2517 dst[i] -= rhs[i];
2518 c = (dst[i] > l);
2519 }
2520 }
2521
2522 return c;
2523}
2524
2525/* Negate a bignum in-place. */
2526void
2527APInt::tcNegate(integerPart *dst, unsigned int parts)
2528{
2529 tcComplement(dst, parts);
2530 tcIncrement(dst, parts);
2531}
2532
Neil Boothc8b650a2007-10-06 00:43:45 +00002533/* DST += SRC * MULTIPLIER + CARRY if add is true
2534 DST = SRC * MULTIPLIER + CARRY if add is false
Chris Lattner6b695682007-08-16 15:56:55 +00002535
2536 Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC
2537 they must start at the same point, i.e. DST == SRC.
2538
2539 If DSTPARTS == SRCPARTS + 1 no overflow occurs and zero is
2540 returned. Otherwise DST is filled with the least significant
2541 DSTPARTS parts of the result, and if all of the omitted higher
2542 parts were zero return zero, otherwise overflow occurred and
2543 return one. */
2544int
2545APInt::tcMultiplyPart(integerPart *dst, const integerPart *src,
2546 integerPart multiplier, integerPart carry,
2547 unsigned int srcParts, unsigned int dstParts,
2548 bool add)
2549{
2550 unsigned int i, n;
2551
2552 /* Otherwise our writes of DST kill our later reads of SRC. */
2553 assert(dst <= src || dst >= src + srcParts);
2554 assert(dstParts <= srcParts + 1);
2555
2556 /* N loops; minimum of dstParts and srcParts. */
2557 n = dstParts < srcParts ? dstParts: srcParts;
2558
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002559 for (i = 0; i < n; i++) {
Chris Lattner6b695682007-08-16 15:56:55 +00002560 integerPart low, mid, high, srcPart;
2561
2562 /* [ LOW, HIGH ] = MULTIPLIER * SRC[i] + DST[i] + CARRY.
2563
2564 This cannot overflow, because
2565
2566 (n - 1) * (n - 1) + 2 (n - 1) = (n - 1) * (n + 1)
2567
2568 which is less than n^2. */
2569
2570 srcPart = src[i];
2571
2572 if (multiplier == 0 || srcPart == 0) {
2573 low = carry;
2574 high = 0;
2575 } else {
2576 low = lowHalf(srcPart) * lowHalf(multiplier);
2577 high = highHalf(srcPart) * highHalf(multiplier);
2578
2579 mid = lowHalf(srcPart) * highHalf(multiplier);
2580 high += highHalf(mid);
2581 mid <<= integerPartWidth / 2;
2582 if (low + mid < low)
2583 high++;
2584 low += mid;
2585
2586 mid = highHalf(srcPart) * lowHalf(multiplier);
2587 high += highHalf(mid);
2588 mid <<= integerPartWidth / 2;
2589 if (low + mid < low)
2590 high++;
2591 low += mid;
2592
2593 /* Now add carry. */
2594 if (low + carry < low)
2595 high++;
2596 low += carry;
2597 }
2598
2599 if (add) {
2600 /* And now DST[i], and store the new low part there. */
2601 if (low + dst[i] < low)
2602 high++;
2603 dst[i] += low;
2604 } else
2605 dst[i] = low;
2606
2607 carry = high;
2608 }
2609
2610 if (i < dstParts) {
2611 /* Full multiplication, there is no overflow. */
2612 assert(i + 1 == dstParts);
2613 dst[i] = carry;
2614 return 0;
2615 } else {
2616 /* We overflowed if there is carry. */
2617 if (carry)
2618 return 1;
2619
2620 /* We would overflow if any significant unwritten parts would be
2621 non-zero. This is true if any remaining src parts are non-zero
2622 and the multiplier is non-zero. */
2623 if (multiplier)
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002624 for (; i < srcParts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002625 if (src[i])
2626 return 1;
2627
2628 /* We fitted in the narrow destination. */
2629 return 0;
2630 }
2631}
2632
2633/* DST = LHS * RHS, where DST has the same width as the operands and
2634 is filled with the least significant parts of the result. Returns
2635 one if overflow occurred, otherwise zero. DST must be disjoint
2636 from both operands. */
2637int
2638APInt::tcMultiply(integerPart *dst, const integerPart *lhs,
2639 const integerPart *rhs, unsigned int parts)
2640{
2641 unsigned int i;
2642 int overflow;
2643
2644 assert(dst != lhs && dst != rhs);
2645
2646 overflow = 0;
2647 tcSet(dst, 0, parts);
2648
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002649 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002650 overflow |= tcMultiplyPart(&dst[i], lhs, rhs[i], 0, parts,
2651 parts - i, true);
2652
2653 return overflow;
2654}
2655
Neil Booth0ea72a92007-10-06 00:24:48 +00002656/* DST = LHS * RHS, where DST has width the sum of the widths of the
2657 operands. No overflow occurs. DST must be disjoint from both
2658 operands. Returns the number of parts required to hold the
2659 result. */
2660unsigned int
Chris Lattner6b695682007-08-16 15:56:55 +00002661APInt::tcFullMultiply(integerPart *dst, const integerPart *lhs,
Neil Booth0ea72a92007-10-06 00:24:48 +00002662 const integerPart *rhs, unsigned int lhsParts,
2663 unsigned int rhsParts)
Chris Lattner6b695682007-08-16 15:56:55 +00002664{
Neil Booth0ea72a92007-10-06 00:24:48 +00002665 /* Put the narrower number on the LHS for less loops below. */
2666 if (lhsParts > rhsParts) {
2667 return tcFullMultiply (dst, rhs, lhs, rhsParts, lhsParts);
2668 } else {
2669 unsigned int n;
Chris Lattner6b695682007-08-16 15:56:55 +00002670
Neil Booth0ea72a92007-10-06 00:24:48 +00002671 assert(dst != lhs && dst != rhs);
Chris Lattner6b695682007-08-16 15:56:55 +00002672
Neil Booth0ea72a92007-10-06 00:24:48 +00002673 tcSet(dst, 0, rhsParts);
Chris Lattner6b695682007-08-16 15:56:55 +00002674
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002675 for (n = 0; n < lhsParts; n++)
Neil Booth0ea72a92007-10-06 00:24:48 +00002676 tcMultiplyPart(&dst[n], rhs, lhs[n], 0, rhsParts, rhsParts + 1, true);
Chris Lattner6b695682007-08-16 15:56:55 +00002677
Neil Booth0ea72a92007-10-06 00:24:48 +00002678 n = lhsParts + rhsParts;
2679
2680 return n - (dst[n - 1] == 0);
2681 }
Chris Lattner6b695682007-08-16 15:56:55 +00002682}
2683
2684/* If RHS is zero LHS and REMAINDER are left unchanged, return one.
2685 Otherwise set LHS to LHS / RHS with the fractional part discarded,
2686 set REMAINDER to the remainder, return zero. i.e.
2687
2688 OLD_LHS = RHS * LHS + REMAINDER
2689
2690 SCRATCH is a bignum of the same size as the operands and result for
2691 use by the routine; its contents need not be initialized and are
2692 destroyed. LHS, REMAINDER and SCRATCH must be distinct.
2693*/
2694int
2695APInt::tcDivide(integerPart *lhs, const integerPart *rhs,
2696 integerPart *remainder, integerPart *srhs,
2697 unsigned int parts)
2698{
2699 unsigned int n, shiftCount;
2700 integerPart mask;
2701
2702 assert(lhs != remainder && lhs != srhs && remainder != srhs);
2703
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002704 shiftCount = tcMSB(rhs, parts) + 1;
2705 if (shiftCount == 0)
Chris Lattner6b695682007-08-16 15:56:55 +00002706 return true;
2707
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002708 shiftCount = parts * integerPartWidth - shiftCount;
Chris Lattner6b695682007-08-16 15:56:55 +00002709 n = shiftCount / integerPartWidth;
2710 mask = (integerPart) 1 << (shiftCount % integerPartWidth);
2711
2712 tcAssign(srhs, rhs, parts);
2713 tcShiftLeft(srhs, parts, shiftCount);
2714 tcAssign(remainder, lhs, parts);
2715 tcSet(lhs, 0, parts);
2716
2717 /* Loop, subtracting SRHS if REMAINDER is greater and adding that to
2718 the total. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002719 for (;;) {
Chris Lattner6b695682007-08-16 15:56:55 +00002720 int compare;
2721
2722 compare = tcCompare(remainder, srhs, parts);
2723 if (compare >= 0) {
2724 tcSubtract(remainder, srhs, 0, parts);
2725 lhs[n] |= mask;
2726 }
2727
2728 if (shiftCount == 0)
2729 break;
2730 shiftCount--;
2731 tcShiftRight(srhs, parts, 1);
Richard Trieu7a083812016-02-18 22:09:30 +00002732 if ((mask >>= 1) == 0) {
2733 mask = (integerPart) 1 << (integerPartWidth - 1);
2734 n--;
2735 }
Chris Lattner6b695682007-08-16 15:56:55 +00002736 }
2737
2738 return false;
2739}
2740
2741/* Shift a bignum left COUNT bits in-place. Shifted in bits are zero.
2742 There are no restrictions on COUNT. */
2743void
2744APInt::tcShiftLeft(integerPart *dst, unsigned int parts, unsigned int count)
2745{
Neil Boothb6182162007-10-08 13:47:12 +00002746 if (count) {
2747 unsigned int jump, shift;
Chris Lattner6b695682007-08-16 15:56:55 +00002748
Neil Boothb6182162007-10-08 13:47:12 +00002749 /* Jump is the inter-part jump; shift is is intra-part shift. */
2750 jump = count / integerPartWidth;
2751 shift = count % integerPartWidth;
Chris Lattner6b695682007-08-16 15:56:55 +00002752
Neil Boothb6182162007-10-08 13:47:12 +00002753 while (parts > jump) {
2754 integerPart part;
Chris Lattner6b695682007-08-16 15:56:55 +00002755
Neil Boothb6182162007-10-08 13:47:12 +00002756 parts--;
Chris Lattner6b695682007-08-16 15:56:55 +00002757
Neil Boothb6182162007-10-08 13:47:12 +00002758 /* dst[i] comes from the two parts src[i - jump] and, if we have
2759 an intra-part shift, src[i - jump - 1]. */
2760 part = dst[parts - jump];
2761 if (shift) {
2762 part <<= shift;
Chris Lattner6b695682007-08-16 15:56:55 +00002763 if (parts >= jump + 1)
2764 part |= dst[parts - jump - 1] >> (integerPartWidth - shift);
2765 }
2766
Neil Boothb6182162007-10-08 13:47:12 +00002767 dst[parts] = part;
2768 }
Chris Lattner6b695682007-08-16 15:56:55 +00002769
Neil Boothb6182162007-10-08 13:47:12 +00002770 while (parts > 0)
2771 dst[--parts] = 0;
2772 }
Chris Lattner6b695682007-08-16 15:56:55 +00002773}
2774
2775/* Shift a bignum right COUNT bits in-place. Shifted in bits are
2776 zero. There are no restrictions on COUNT. */
2777void
2778APInt::tcShiftRight(integerPart *dst, unsigned int parts, unsigned int count)
2779{
Neil Boothb6182162007-10-08 13:47:12 +00002780 if (count) {
2781 unsigned int i, jump, shift;
Chris Lattner6b695682007-08-16 15:56:55 +00002782
Neil Boothb6182162007-10-08 13:47:12 +00002783 /* Jump is the inter-part jump; shift is is intra-part shift. */
2784 jump = count / integerPartWidth;
2785 shift = count % integerPartWidth;
Chris Lattner6b695682007-08-16 15:56:55 +00002786
Neil Boothb6182162007-10-08 13:47:12 +00002787 /* Perform the shift. This leaves the most significant COUNT bits
2788 of the result at zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002789 for (i = 0; i < parts; i++) {
Neil Boothb6182162007-10-08 13:47:12 +00002790 integerPart part;
Chris Lattner6b695682007-08-16 15:56:55 +00002791
Neil Boothb6182162007-10-08 13:47:12 +00002792 if (i + jump >= parts) {
2793 part = 0;
2794 } else {
2795 part = dst[i + jump];
2796 if (shift) {
2797 part >>= shift;
2798 if (i + jump + 1 < parts)
2799 part |= dst[i + jump + 1] << (integerPartWidth - shift);
2800 }
Chris Lattner6b695682007-08-16 15:56:55 +00002801 }
Chris Lattner6b695682007-08-16 15:56:55 +00002802
Neil Boothb6182162007-10-08 13:47:12 +00002803 dst[i] = part;
2804 }
Chris Lattner6b695682007-08-16 15:56:55 +00002805 }
2806}
2807
2808/* Bitwise and of two bignums. */
2809void
2810APInt::tcAnd(integerPart *dst, const integerPart *rhs, unsigned int parts)
2811{
2812 unsigned int i;
2813
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002814 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002815 dst[i] &= rhs[i];
2816}
2817
2818/* Bitwise inclusive or of two bignums. */
2819void
2820APInt::tcOr(integerPart *dst, const integerPart *rhs, unsigned int parts)
2821{
2822 unsigned int i;
2823
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002824 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002825 dst[i] |= rhs[i];
2826}
2827
2828/* Bitwise exclusive or of two bignums. */
2829void
2830APInt::tcXor(integerPart *dst, const integerPart *rhs, unsigned int parts)
2831{
2832 unsigned int i;
2833
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002834 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002835 dst[i] ^= rhs[i];
2836}
2837
2838/* Complement a bignum in-place. */
2839void
2840APInt::tcComplement(integerPart *dst, unsigned int parts)
2841{
2842 unsigned int i;
2843
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002844 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002845 dst[i] = ~dst[i];
2846}
2847
2848/* Comparison (unsigned) of two bignums. */
2849int
2850APInt::tcCompare(const integerPart *lhs, const integerPart *rhs,
2851 unsigned int parts)
2852{
2853 while (parts) {
2854 parts--;
2855 if (lhs[parts] == rhs[parts])
2856 continue;
2857
2858 if (lhs[parts] > rhs[parts])
2859 return 1;
2860 else
2861 return -1;
2862 }
2863
2864 return 0;
2865}
2866
2867/* Increment a bignum in-place, return the carry flag. */
2868integerPart
2869APInt::tcIncrement(integerPart *dst, unsigned int parts)
2870{
2871 unsigned int i;
2872
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002873 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002874 if (++dst[i] != 0)
2875 break;
2876
2877 return i == parts;
2878}
2879
Michael Gottesman9d406f42013-05-28 19:50:20 +00002880/* Decrement a bignum in-place, return the borrow flag. */
2881integerPart
2882APInt::tcDecrement(integerPart *dst, unsigned int parts) {
2883 for (unsigned int i = 0; i < parts; i++) {
2884 // If the current word is non-zero, then the decrement has no effect on the
2885 // higher-order words of the integer and no borrow can occur. Exit early.
2886 if (dst[i]--)
2887 return 0;
2888 }
2889 // If every word was zero, then there is a borrow.
2890 return 1;
2891}
2892
2893
Chris Lattner6b695682007-08-16 15:56:55 +00002894/* Set the least significant BITS bits of a bignum, clear the
2895 rest. */
2896void
2897APInt::tcSetLeastSignificantBits(integerPart *dst, unsigned int parts,
2898 unsigned int bits)
2899{
2900 unsigned int i;
2901
2902 i = 0;
2903 while (bits > integerPartWidth) {
2904 dst[i++] = ~(integerPart) 0;
2905 bits -= integerPartWidth;
2906 }
2907
2908 if (bits)
2909 dst[i++] = ~(integerPart) 0 >> (integerPartWidth - bits);
2910
2911 while (i < parts)
2912 dst[i++] = 0;
2913}