blob: 0cbb93b0ca3b1342e8470dcaea2d2a5da032bce7 [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"
Vassil Vassilev2ec8b152016-09-14 08:55:18 +000025#include <climits>
Chris Lattner17f71652008-08-17 07:19:36 +000026#include <cmath>
Zhou Shengdac63782007-02-06 03:00:16 +000027#include <cstdlib>
Chandler Carruthed0881b2012-12-03 16:50:05 +000028#include <cstring>
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
Joerg Sonnenbergerd7baada2017-01-05 17:59:22 +0000208/// no further borrowing is needed or it runs out of "digits" in x. The result
Reid Spencera856b6e2007-02-18 18:38:44 +0000209/// 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
Pete Cooperfea21392016-07-22 20:55:46 +0000263APInt& APInt::operator+=(uint64_t RHS) {
264 if (isSingleWord())
265 VAL += RHS;
266 else
267 add_1(pVal, pVal, getNumWords(), RHS);
268 return clearUnusedBits();
269}
270
Eric Christopher820256b2009-08-21 04:06:45 +0000271/// Subtracts the integer array y from the integer array x
Reid Spencera41e93b2007-02-25 19:32:03 +0000272/// @returns returns the borrow out.
273/// @brief Generalized subtraction of 64-bit integer arrays.
Eric Christopher820256b2009-08-21 04:06:45 +0000274static bool sub(uint64_t *dest, const uint64_t *x, const uint64_t *y,
Chris Lattner77527f52009-01-21 18:09:24 +0000275 unsigned len) {
Reid Spencer1ba83352007-02-21 03:55:44 +0000276 bool borrow = false;
Chris Lattner77527f52009-01-21 18:09:24 +0000277 for (unsigned i = 0; i < len; ++i) {
Reid Spencer1ba83352007-02-21 03:55:44 +0000278 uint64_t x_tmp = borrow ? x[i] - 1 : x[i];
279 borrow = y[i] > x_tmp || (borrow && x[i] == 0);
280 dest[i] = x_tmp - y[i];
Reid Spencer100502d2007-02-17 03:16:00 +0000281 }
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000282 return borrow;
Reid Spencer100502d2007-02-17 03:16:00 +0000283}
284
Reid Spencera41e93b2007-02-25 19:32:03 +0000285/// Subtracts the RHS APInt from this APInt
286/// @returns this, after subtraction
Eric Christopher820256b2009-08-21 04:06:45 +0000287/// @brief Subtraction assignment operator.
Zhou Shengdac63782007-02-06 03:00:16 +0000288APInt& APInt::operator-=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000289 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Eric Christopher820256b2009-08-21 04:06:45 +0000290 if (isSingleWord())
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000291 VAL -= RHS.VAL;
292 else
293 sub(pVal, pVal, RHS.pVal, getNumWords());
Reid Spencera41e93b2007-02-25 19:32:03 +0000294 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000295}
296
Pete Cooperfea21392016-07-22 20:55:46 +0000297APInt& APInt::operator-=(uint64_t RHS) {
298 if (isSingleWord())
299 VAL -= RHS;
300 else
301 sub_1(pVal, getNumWords(), RHS);
302 return clearUnusedBits();
303}
304
Dan Gohman4a618822010-02-10 16:03:48 +0000305/// Multiplies an integer array, x, by a uint64_t integer and places the result
Eric Christopher820256b2009-08-21 04:06:45 +0000306/// into dest.
Reid Spencera41e93b2007-02-25 19:32:03 +0000307/// @returns the carry out of the multiplication.
308/// @brief Multiply a multi-digit APInt by a single digit (64-bit) integer.
Chris Lattner77527f52009-01-21 18:09:24 +0000309static uint64_t mul_1(uint64_t dest[], uint64_t x[], unsigned len, uint64_t y) {
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000310 // Split y into high 32-bit part (hy) and low 32-bit part (ly)
Reid Spencer100502d2007-02-17 03:16:00 +0000311 uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
Reid Spencera41e93b2007-02-25 19:32:03 +0000312 uint64_t carry = 0;
313
314 // For each digit of x.
Chris Lattner77527f52009-01-21 18:09:24 +0000315 for (unsigned i = 0; i < len; ++i) {
Reid Spencera41e93b2007-02-25 19:32:03 +0000316 // Split x into high and low words
317 uint64_t lx = x[i] & 0xffffffffULL;
318 uint64_t hx = x[i] >> 32;
319 // hasCarry - A flag to indicate if there is a carry to the next digit.
Reid Spencer100502d2007-02-17 03:16:00 +0000320 // hasCarry == 0, no carry
321 // hasCarry == 1, has carry
322 // hasCarry == 2, no carry and the calculation result == 0.
323 uint8_t hasCarry = 0;
324 dest[i] = carry + lx * ly;
325 // Determine if the add above introduces carry.
326 hasCarry = (dest[i] < carry) ? 1 : 0;
327 carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
Eric Christopher820256b2009-08-21 04:06:45 +0000328 // The upper limit of carry can be (2^32 - 1)(2^32 - 1) +
Reid Spencer100502d2007-02-17 03:16:00 +0000329 // (2^32 - 1) + 2^32 = 2^64.
330 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
331
332 carry += (lx * hy) & 0xffffffffULL;
333 dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
Eric Christopher820256b2009-08-21 04:06:45 +0000334 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) +
Reid Spencer100502d2007-02-17 03:16:00 +0000335 (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
336 }
Reid Spencer100502d2007-02-17 03:16:00 +0000337 return carry;
338}
339
Eric Christopher820256b2009-08-21 04:06:45 +0000340/// Multiplies integer array x by integer array y and stores the result into
Reid Spencera41e93b2007-02-25 19:32:03 +0000341/// the integer array dest. Note that dest's size must be >= xlen + ylen.
342/// @brief Generalized multiplicate of integer arrays.
Chris Lattner77527f52009-01-21 18:09:24 +0000343static void mul(uint64_t dest[], uint64_t x[], unsigned xlen, uint64_t y[],
344 unsigned ylen) {
Reid Spencer100502d2007-02-17 03:16:00 +0000345 dest[xlen] = mul_1(dest, x, xlen, y[0]);
Chris Lattner77527f52009-01-21 18:09:24 +0000346 for (unsigned i = 1; i < ylen; ++i) {
Reid Spencer100502d2007-02-17 03:16:00 +0000347 uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
Reid Spencer58a6a432007-02-21 08:21:52 +0000348 uint64_t carry = 0, lx = 0, hx = 0;
Chris Lattner77527f52009-01-21 18:09:24 +0000349 for (unsigned j = 0; j < xlen; ++j) {
Reid Spencer100502d2007-02-17 03:16:00 +0000350 lx = x[j] & 0xffffffffULL;
351 hx = x[j] >> 32;
352 // hasCarry - A flag to indicate if has carry.
353 // hasCarry == 0, no carry
354 // hasCarry == 1, has carry
355 // hasCarry == 2, no carry and the calculation result == 0.
356 uint8_t hasCarry = 0;
357 uint64_t resul = carry + lx * ly;
358 hasCarry = (resul < carry) ? 1 : 0;
359 carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
360 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
361
362 carry += (lx * hy) & 0xffffffffULL;
363 resul = (carry << 32) | (resul & 0xffffffffULL);
364 dest[i+j] += resul;
365 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
Eric Christopher820256b2009-08-21 04:06:45 +0000366 (carry >> 32) + (dest[i+j] < resul ? 1 : 0) +
Reid Spencer100502d2007-02-17 03:16:00 +0000367 ((lx * hy) >> 32) + hx * hy;
368 }
369 dest[i+xlen] = carry;
370 }
371}
372
Zhou Shengdac63782007-02-06 03:00:16 +0000373APInt& APInt::operator*=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000374 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer58a6a432007-02-21 08:21:52 +0000375 if (isSingleWord()) {
Reid Spencer4bb430c2007-02-20 20:42:10 +0000376 VAL *= RHS.VAL;
Reid Spencer58a6a432007-02-21 08:21:52 +0000377 clearUnusedBits();
378 return *this;
Zhou Shengdac63782007-02-06 03:00:16 +0000379 }
Reid Spencer58a6a432007-02-21 08:21:52 +0000380
381 // Get some bit facts about LHS and check for zero
Chris Lattner77527f52009-01-21 18:09:24 +0000382 unsigned lhsBits = getActiveBits();
383 unsigned lhsWords = !lhsBits ? 0 : whichWord(lhsBits - 1) + 1;
Eric Christopher820256b2009-08-21 04:06:45 +0000384 if (!lhsWords)
Reid Spencer58a6a432007-02-21 08:21:52 +0000385 // 0 * X ===> 0
386 return *this;
387
388 // Get some bit facts about RHS and check for zero
Chris Lattner77527f52009-01-21 18:09:24 +0000389 unsigned rhsBits = RHS.getActiveBits();
390 unsigned rhsWords = !rhsBits ? 0 : whichWord(rhsBits - 1) + 1;
Reid Spencer58a6a432007-02-21 08:21:52 +0000391 if (!rhsWords) {
392 // X * 0 ===> 0
Jay Foad25a5e4c2010-12-01 08:53:58 +0000393 clearAllBits();
Reid Spencer58a6a432007-02-21 08:21:52 +0000394 return *this;
395 }
396
397 // Allocate space for the result
Chris Lattner77527f52009-01-21 18:09:24 +0000398 unsigned destWords = rhsWords + lhsWords;
Reid Spencer58a6a432007-02-21 08:21:52 +0000399 uint64_t *dest = getMemory(destWords);
400
401 // Perform the long multiply
402 mul(dest, pVal, lhsWords, RHS.pVal, rhsWords);
403
404 // Copy result back into *this
Jay Foad25a5e4c2010-12-01 08:53:58 +0000405 clearAllBits();
Chris Lattner77527f52009-01-21 18:09:24 +0000406 unsigned wordsToCopy = destWords >= getNumWords() ? getNumWords() : destWords;
Reid Spencer58a6a432007-02-21 08:21:52 +0000407 memcpy(pVal, dest, wordsToCopy * APINT_WORD_SIZE);
Eli Friedman19546412011-10-07 23:40:49 +0000408 clearUnusedBits();
Reid Spencer58a6a432007-02-21 08:21:52 +0000409
410 // delete dest array and return
411 delete[] dest;
Zhou Shengdac63782007-02-06 03:00:16 +0000412 return *this;
413}
414
Zhou Shengdac63782007-02-06 03:00:16 +0000415APInt& APInt::operator&=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000416 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengdac63782007-02-06 03:00:16 +0000417 if (isSingleWord()) {
Reid Spencera856b6e2007-02-18 18:38:44 +0000418 VAL &= RHS.VAL;
419 return *this;
Zhou Shengdac63782007-02-06 03:00:16 +0000420 }
Chris Lattner77527f52009-01-21 18:09:24 +0000421 unsigned numWords = getNumWords();
422 for (unsigned i = 0; i < numWords; ++i)
Reid Spencera856b6e2007-02-18 18:38:44 +0000423 pVal[i] &= RHS.pVal[i];
Zhou Shengdac63782007-02-06 03:00:16 +0000424 return *this;
425}
426
Zhou Shengdac63782007-02-06 03:00:16 +0000427APInt& APInt::operator|=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000428 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengdac63782007-02-06 03:00:16 +0000429 if (isSingleWord()) {
Reid Spencera856b6e2007-02-18 18:38:44 +0000430 VAL |= RHS.VAL;
431 return *this;
Zhou Shengdac63782007-02-06 03:00:16 +0000432 }
Chris Lattner77527f52009-01-21 18:09:24 +0000433 unsigned numWords = getNumWords();
434 for (unsigned i = 0; i < numWords; ++i)
Reid Spencera856b6e2007-02-18 18:38:44 +0000435 pVal[i] |= RHS.pVal[i];
Zhou Shengdac63782007-02-06 03:00:16 +0000436 return *this;
437}
438
Zhou Shengdac63782007-02-06 03:00:16 +0000439APInt& APInt::operator^=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000440 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Zhou Shengdac63782007-02-06 03:00:16 +0000441 if (isSingleWord()) {
Reid Spenceree0a6852007-02-18 06:39:42 +0000442 VAL ^= RHS.VAL;
443 return *this;
Eric Christopher820256b2009-08-21 04:06:45 +0000444 }
Chris Lattner77527f52009-01-21 18:09:24 +0000445 unsigned numWords = getNumWords();
446 for (unsigned i = 0; i < numWords; ++i)
Reid Spencera856b6e2007-02-18 18:38:44 +0000447 pVal[i] ^= RHS.pVal[i];
Craig Topper9028f052017-01-24 02:10:15 +0000448 return *this;
Zhou Shengdac63782007-02-06 03:00:16 +0000449}
450
Chris Lattner1ac3e252008-08-20 17:02:31 +0000451APInt APInt::AndSlowCase(const APInt& RHS) const {
Chris Lattner77527f52009-01-21 18:09:24 +0000452 unsigned numWords = getNumWords();
Reid Spencera41e93b2007-02-25 19:32:03 +0000453 uint64_t* val = getMemory(numWords);
Chris Lattner77527f52009-01-21 18:09:24 +0000454 for (unsigned i = 0; i < numWords; ++i)
Reid Spencera41e93b2007-02-25 19:32:03 +0000455 val[i] = pVal[i] & RHS.pVal[i];
456 return APInt(val, getBitWidth());
Zhou Shengdac63782007-02-06 03:00:16 +0000457}
458
Chris Lattner1ac3e252008-08-20 17:02:31 +0000459APInt APInt::OrSlowCase(const APInt& RHS) const {
Chris Lattner77527f52009-01-21 18:09:24 +0000460 unsigned numWords = getNumWords();
Reid Spencera41e93b2007-02-25 19:32:03 +0000461 uint64_t *val = getMemory(numWords);
Chris Lattner77527f52009-01-21 18:09:24 +0000462 for (unsigned i = 0; i < numWords; ++i)
Reid Spencera41e93b2007-02-25 19:32:03 +0000463 val[i] = pVal[i] | RHS.pVal[i];
464 return APInt(val, getBitWidth());
Zhou Shengdac63782007-02-06 03:00:16 +0000465}
466
Chris Lattner1ac3e252008-08-20 17:02:31 +0000467APInt APInt::XorSlowCase(const APInt& RHS) const {
Chris Lattner77527f52009-01-21 18:09:24 +0000468 unsigned numWords = getNumWords();
Reid Spencera41e93b2007-02-25 19:32:03 +0000469 uint64_t *val = getMemory(numWords);
Chris Lattner77527f52009-01-21 18:09:24 +0000470 for (unsigned i = 0; i < numWords; ++i)
Reid Spencera41e93b2007-02-25 19:32:03 +0000471 val[i] = pVal[i] ^ RHS.pVal[i];
472
Craig Topper9028f052017-01-24 02:10:15 +0000473 return APInt(val, getBitWidth());
Zhou Shengdac63782007-02-06 03:00:16 +0000474}
475
Zhou Shengdac63782007-02-06 03:00:16 +0000476APInt APInt::operator*(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +0000477 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencera41e93b2007-02-25 19:32:03 +0000478 if (isSingleWord())
Reid Spenceraa8dcfe2007-02-26 07:44:38 +0000479 return APInt(BitWidth, VAL * RHS.VAL);
Reid Spencer4bb430c2007-02-20 20:42:10 +0000480 APInt Result(*this);
481 Result *= RHS;
Eli Friedman19546412011-10-07 23:40:49 +0000482 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000483}
484
Chris Lattner1ac3e252008-08-20 17:02:31 +0000485bool APInt::EqualSlowCase(const APInt& RHS) const {
Matthias Braun5117fcd2016-02-15 20:06:19 +0000486 return std::equal(pVal, pVal + getNumWords(), RHS.pVal);
Zhou Shengdac63782007-02-06 03:00:16 +0000487}
488
Chris Lattner1ac3e252008-08-20 17:02:31 +0000489bool APInt::EqualSlowCase(uint64_t Val) const {
Chris Lattner77527f52009-01-21 18:09:24 +0000490 unsigned n = getActiveBits();
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000491 if (n <= APINT_BITS_PER_WORD)
492 return pVal[0] == Val;
493 else
494 return false;
Zhou Shengdac63782007-02-06 03:00:16 +0000495}
496
Reid Spencer1d072122007-02-16 22:36:51 +0000497bool APInt::ult(const APInt& RHS) const {
498 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
499 if (isSingleWord())
500 return VAL < RHS.VAL;
Reid Spencera41e93b2007-02-25 19:32:03 +0000501
502 // Get active bit length of both operands
Chris Lattner77527f52009-01-21 18:09:24 +0000503 unsigned n1 = getActiveBits();
504 unsigned n2 = RHS.getActiveBits();
Reid Spencera41e93b2007-02-25 19:32:03 +0000505
506 // If magnitude of LHS is less than RHS, return true.
507 if (n1 < n2)
508 return true;
509
510 // If magnitude of RHS is greather than LHS, return false.
511 if (n2 < n1)
512 return false;
513
514 // If they bot fit in a word, just compare the low order word
515 if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
516 return pVal[0] < RHS.pVal[0];
517
518 // Otherwise, compare all words
Chris Lattner77527f52009-01-21 18:09:24 +0000519 unsigned topWord = whichWord(std::max(n1,n2)-1);
Reid Spencer54abdcf2007-02-27 18:23:40 +0000520 for (int i = topWord; i >= 0; --i) {
Eric Christopher820256b2009-08-21 04:06:45 +0000521 if (pVal[i] > RHS.pVal[i])
Reid Spencer1d072122007-02-16 22:36:51 +0000522 return false;
Eric Christopher820256b2009-08-21 04:06:45 +0000523 if (pVal[i] < RHS.pVal[i])
Reid Spencera41e93b2007-02-25 19:32:03 +0000524 return true;
Zhou Shengdac63782007-02-06 03:00:16 +0000525 }
526 return false;
527}
528
Reid Spencer1d072122007-02-16 22:36:51 +0000529bool APInt::slt(const APInt& RHS) const {
530 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000531 if (isSingleWord()) {
David Majnemer5f1c0172016-06-24 20:51:47 +0000532 int64_t lhsSext = SignExtend64(VAL, BitWidth);
533 int64_t rhsSext = SignExtend64(RHS.VAL, BitWidth);
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000534 return lhsSext < rhsSext;
Reid Spencer1d072122007-02-16 22:36:51 +0000535 }
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000536
Reid Spencer54abdcf2007-02-27 18:23:40 +0000537 bool lhsNeg = isNegative();
Pete Cooperd6e6bf12016-05-26 17:40:07 +0000538 bool rhsNeg = RHS.isNegative();
Reid Spencera41e93b2007-02-25 19:32:03 +0000539
Pete Cooperd6e6bf12016-05-26 17:40:07 +0000540 // If the sign bits don't match, then (LHS < RHS) if LHS is negative
541 if (lhsNeg != rhsNeg)
542 return lhsNeg;
543
544 // Otherwise we can just use an unsigned comparision, because even negative
545 // numbers compare correctly this way if both have the same signed-ness.
546 return ult(RHS);
Zhou Shengdac63782007-02-06 03:00:16 +0000547}
548
Jay Foad25a5e4c2010-12-01 08:53:58 +0000549void APInt::setBit(unsigned bitPosition) {
Eric Christopher820256b2009-08-21 04:06:45 +0000550 if (isSingleWord())
Reid Spencera41e93b2007-02-25 19:32:03 +0000551 VAL |= maskBit(bitPosition);
Eric Christopher820256b2009-08-21 04:06:45 +0000552 else
Reid Spencera41e93b2007-02-25 19:32:03 +0000553 pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
Zhou Shengdac63782007-02-06 03:00:16 +0000554}
555
Zhou Shengdac63782007-02-06 03:00:16 +0000556/// Set the given bit to 0 whose position is given as "bitPosition".
557/// @brief Set a given bit to 0.
Jay Foad25a5e4c2010-12-01 08:53:58 +0000558void APInt::clearBit(unsigned bitPosition) {
Eric Christopher820256b2009-08-21 04:06:45 +0000559 if (isSingleWord())
Reid Spencera856b6e2007-02-18 18:38:44 +0000560 VAL &= ~maskBit(bitPosition);
Eric Christopher820256b2009-08-21 04:06:45 +0000561 else
Reid Spencera856b6e2007-02-18 18:38:44 +0000562 pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
Zhou Shengdac63782007-02-06 03:00:16 +0000563}
564
Zhou Shengdac63782007-02-06 03:00:16 +0000565/// @brief Toggle every bit to its opposite value.
Zhou Shengdac63782007-02-06 03:00:16 +0000566
Eric Christopher820256b2009-08-21 04:06:45 +0000567/// Toggle a given bit to its opposite value whose position is given
Zhou Shengdac63782007-02-06 03:00:16 +0000568/// as "bitPosition".
569/// @brief Toggles a given bit to its opposite value.
Jay Foad25a5e4c2010-12-01 08:53:58 +0000570void APInt::flipBit(unsigned bitPosition) {
Reid Spencer1d072122007-02-16 22:36:51 +0000571 assert(bitPosition < BitWidth && "Out of the bit-width range!");
Jay Foad25a5e4c2010-12-01 08:53:58 +0000572 if ((*this)[bitPosition]) clearBit(bitPosition);
573 else setBit(bitPosition);
Zhou Shengdac63782007-02-06 03:00:16 +0000574}
575
Benjamin Kramer92d89982010-07-14 22:38:02 +0000576unsigned APInt::getBitsNeeded(StringRef str, uint8_t radix) {
Daniel Dunbar3a1efd112009-08-13 02:33:34 +0000577 assert(!str.empty() && "Invalid string length");
Douglas Gregor663c0682011-09-14 15:54:46 +0000578 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 ||
579 radix == 36) &&
580 "Radix should be 2, 8, 10, 16, or 36!");
Daniel Dunbar3a1efd112009-08-13 02:33:34 +0000581
582 size_t slen = str.size();
Reid Spencer9329e7b2007-04-13 19:19:07 +0000583
Eric Christopher43a1dec2009-08-21 04:10:31 +0000584 // Each computation below needs to know if it's negative.
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000585 StringRef::iterator p = str.begin();
Eric Christopher43a1dec2009-08-21 04:10:31 +0000586 unsigned isNegative = *p == '-';
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000587 if (*p == '-' || *p == '+') {
588 p++;
Reid Spencer9329e7b2007-04-13 19:19:07 +0000589 slen--;
Eric Christopher43a1dec2009-08-21 04:10:31 +0000590 assert(slen && "String is only a sign, needs a value.");
Reid Spencer9329e7b2007-04-13 19:19:07 +0000591 }
Eric Christopher43a1dec2009-08-21 04:10:31 +0000592
Reid Spencer9329e7b2007-04-13 19:19:07 +0000593 // For radixes of power-of-two values, the bits required is accurately and
594 // easily computed
595 if (radix == 2)
596 return slen + isNegative;
597 if (radix == 8)
598 return slen * 3 + isNegative;
599 if (radix == 16)
600 return slen * 4 + isNegative;
601
Douglas Gregor663c0682011-09-14 15:54:46 +0000602 // FIXME: base 36
603
Reid Spencer9329e7b2007-04-13 19:19:07 +0000604 // This is grossly inefficient but accurate. We could probably do something
605 // with a computation of roughly slen*64/20 and then adjust by the value of
606 // the first few digits. But, I'm not sure how accurate that could be.
607
608 // Compute a sufficient number of bits that is always large enough but might
Erick Tryzelaardadb15712009-08-21 03:15:28 +0000609 // be too large. This avoids the assertion in the constructor. This
610 // calculation doesn't work appropriately for the numbers 0-9, so just use 4
611 // bits in that case.
Douglas Gregor663c0682011-09-14 15:54:46 +0000612 unsigned sufficient
613 = radix == 10? (slen == 1 ? 4 : slen * 64/18)
614 : (slen == 1 ? 7 : slen * 16/3);
Reid Spencer9329e7b2007-04-13 19:19:07 +0000615
616 // Convert to the actual binary value.
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000617 APInt tmp(sufficient, StringRef(p, slen), radix);
Reid Spencer9329e7b2007-04-13 19:19:07 +0000618
Erick Tryzelaardadb15712009-08-21 03:15:28 +0000619 // Compute how many bits are required. If the log is infinite, assume we need
620 // just bit.
621 unsigned log = tmp.logBase2();
622 if (log == (unsigned)-1) {
623 return isNegative + 1;
624 } else {
625 return isNegative + log + 1;
626 }
Reid Spencer9329e7b2007-04-13 19:19:07 +0000627}
628
Chandler Carruth71bd7d12012-03-04 12:02:57 +0000629hash_code llvm::hash_value(const APInt &Arg) {
630 if (Arg.isSingleWord())
631 return hash_combine(Arg.VAL);
Reid Spencerb2bc9852007-02-26 21:02:27 +0000632
Chandler Carruth71bd7d12012-03-04 12:02:57 +0000633 return hash_combine_range(Arg.pVal, Arg.pVal + Arg.getNumWords());
Reid Spencerb2bc9852007-02-26 21:02:27 +0000634}
635
Benjamin Kramerb4b51502015-03-25 16:49:59 +0000636bool APInt::isSplat(unsigned SplatSizeInBits) const {
637 assert(getBitWidth() % SplatSizeInBits == 0 &&
638 "SplatSizeInBits must divide width!");
639 // We can check that all parts of an integer are equal by making use of a
640 // little trick: rotate and check if it's still the same value.
641 return *this == rotl(SplatSizeInBits);
642}
643
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000644/// This function returns the high "numBits" bits of this APInt.
Chris Lattner77527f52009-01-21 18:09:24 +0000645APInt APInt::getHiBits(unsigned numBits) const {
Reid Spencer1d072122007-02-16 22:36:51 +0000646 return APIntOps::lshr(*this, BitWidth - numBits);
Zhou Shengdac63782007-02-06 03:00:16 +0000647}
648
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000649/// This function returns the low "numBits" bits of this APInt.
Chris Lattner77527f52009-01-21 18:09:24 +0000650APInt APInt::getLoBits(unsigned numBits) const {
Eric Christopher820256b2009-08-21 04:06:45 +0000651 return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits),
Reid Spencer1d072122007-02-16 22:36:51 +0000652 BitWidth - numBits);
Zhou Shengdac63782007-02-06 03:00:16 +0000653}
654
Chris Lattner77527f52009-01-21 18:09:24 +0000655unsigned APInt::countLeadingZerosSlowCase() const {
Matthias Brauna6be4e82016-02-15 20:06:22 +0000656 unsigned Count = 0;
657 for (int i = getNumWords()-1; i >= 0; --i) {
658 integerPart V = pVal[i];
659 if (V == 0)
Chris Lattner1ac3e252008-08-20 17:02:31 +0000660 Count += APINT_BITS_PER_WORD;
661 else {
Matthias Brauna6be4e82016-02-15 20:06:22 +0000662 Count += llvm::countLeadingZeros(V);
Chris Lattner1ac3e252008-08-20 17:02:31 +0000663 break;
Reid Spencer74cf82e2007-02-21 00:29:48 +0000664 }
Zhou Shengdac63782007-02-06 03:00:16 +0000665 }
Matthias Brauna6be4e82016-02-15 20:06:22 +0000666 // Adjust for unused bits in the most significant word (they are zero).
667 unsigned Mod = BitWidth % APINT_BITS_PER_WORD;
668 Count -= Mod > 0 ? APINT_BITS_PER_WORD - Mod : 0;
John McCalldf951bd2010-02-03 03:42:44 +0000669 return Count;
Zhou Shengdac63782007-02-06 03:00:16 +0000670}
671
Chris Lattner77527f52009-01-21 18:09:24 +0000672unsigned APInt::countLeadingOnes() const {
Reid Spencer31acef52007-02-27 21:59:26 +0000673 if (isSingleWord())
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000674 return llvm::countLeadingOnes(VAL << (APINT_BITS_PER_WORD - BitWidth));
Reid Spencer31acef52007-02-27 21:59:26 +0000675
Chris Lattner77527f52009-01-21 18:09:24 +0000676 unsigned highWordBits = BitWidth % APINT_BITS_PER_WORD;
Torok Edwinec39eb82009-01-27 18:06:03 +0000677 unsigned shift;
678 if (!highWordBits) {
679 highWordBits = APINT_BITS_PER_WORD;
680 shift = 0;
681 } else {
682 shift = APINT_BITS_PER_WORD - highWordBits;
683 }
Reid Spencer31acef52007-02-27 21:59:26 +0000684 int i = getNumWords() - 1;
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000685 unsigned Count = llvm::countLeadingOnes(pVal[i] << shift);
Reid Spencer31acef52007-02-27 21:59:26 +0000686 if (Count == highWordBits) {
687 for (i--; i >= 0; --i) {
688 if (pVal[i] == -1ULL)
689 Count += APINT_BITS_PER_WORD;
690 else {
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000691 Count += llvm::countLeadingOnes(pVal[i]);
Reid Spencer31acef52007-02-27 21:59:26 +0000692 break;
693 }
694 }
695 }
696 return Count;
697}
698
Chris Lattner77527f52009-01-21 18:09:24 +0000699unsigned APInt::countTrailingZeros() const {
Zhou Shengdac63782007-02-06 03:00:16 +0000700 if (isSingleWord())
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000701 return std::min(unsigned(llvm::countTrailingZeros(VAL)), BitWidth);
Chris Lattner77527f52009-01-21 18:09:24 +0000702 unsigned Count = 0;
703 unsigned i = 0;
Reid Spenceraa8dcfe2007-02-26 07:44:38 +0000704 for (; i < getNumWords() && pVal[i] == 0; ++i)
705 Count += APINT_BITS_PER_WORD;
706 if (i < getNumWords())
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000707 Count += llvm::countTrailingZeros(pVal[i]);
Chris Lattnerc2c4c742007-11-23 22:36:25 +0000708 return std::min(Count, BitWidth);
Zhou Shengdac63782007-02-06 03:00:16 +0000709}
710
Chris Lattner77527f52009-01-21 18:09:24 +0000711unsigned APInt::countTrailingOnesSlowCase() const {
712 unsigned Count = 0;
713 unsigned i = 0;
Dan Gohmanc354ebd2008-02-14 22:38:45 +0000714 for (; i < getNumWords() && pVal[i] == -1ULL; ++i)
Dan Gohman8b4fa9d2008-02-13 21:11:05 +0000715 Count += APINT_BITS_PER_WORD;
716 if (i < getNumWords())
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000717 Count += llvm::countTrailingOnes(pVal[i]);
Dan Gohman8b4fa9d2008-02-13 21:11:05 +0000718 return std::min(Count, BitWidth);
719}
720
Chris Lattner77527f52009-01-21 18:09:24 +0000721unsigned APInt::countPopulationSlowCase() const {
722 unsigned Count = 0;
723 for (unsigned i = 0; i < getNumWords(); ++i)
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000724 Count += llvm::countPopulation(pVal[i]);
Zhou Shengdac63782007-02-06 03:00:16 +0000725 return Count;
726}
727
Richard Smith4f9a8082011-11-23 21:33:37 +0000728/// Perform a logical right-shift from Src to Dst, which must be equal or
729/// non-overlapping, of Words words, by Shift, which must be less than 64.
730static void lshrNear(uint64_t *Dst, uint64_t *Src, unsigned Words,
731 unsigned Shift) {
732 uint64_t Carry = 0;
733 for (int I = Words - 1; I >= 0; --I) {
734 uint64_t Tmp = Src[I];
735 Dst[I] = (Tmp >> Shift) | Carry;
736 Carry = Tmp << (64 - Shift);
737 }
738}
739
Reid Spencer1d072122007-02-16 22:36:51 +0000740APInt APInt::byteSwap() const {
741 assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
742 if (BitWidth == 16)
Jeff Cohene06855e2007-03-20 20:42:36 +0000743 return APInt(BitWidth, ByteSwap_16(uint16_t(VAL)));
Richard Smith4f9a8082011-11-23 21:33:37 +0000744 if (BitWidth == 32)
Chris Lattner77527f52009-01-21 18:09:24 +0000745 return APInt(BitWidth, ByteSwap_32(unsigned(VAL)));
Richard Smith4f9a8082011-11-23 21:33:37 +0000746 if (BitWidth == 48) {
Chris Lattner77527f52009-01-21 18:09:24 +0000747 unsigned Tmp1 = unsigned(VAL >> 16);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000748 Tmp1 = ByteSwap_32(Tmp1);
Jeff Cohene06855e2007-03-20 20:42:36 +0000749 uint16_t Tmp2 = uint16_t(VAL);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000750 Tmp2 = ByteSwap_16(Tmp2);
Jeff Cohene06855e2007-03-20 20:42:36 +0000751 return APInt(BitWidth, (uint64_t(Tmp2) << 32) | Tmp1);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000752 }
Richard Smith4f9a8082011-11-23 21:33:37 +0000753 if (BitWidth == 64)
754 return APInt(BitWidth, ByteSwap_64(VAL));
755
756 APInt Result(getNumWords() * APINT_BITS_PER_WORD, 0);
757 for (unsigned I = 0, N = getNumWords(); I != N; ++I)
758 Result.pVal[I] = ByteSwap_64(pVal[N - I - 1]);
759 if (Result.BitWidth != BitWidth) {
760 lshrNear(Result.pVal, Result.pVal, getNumWords(),
761 Result.BitWidth - BitWidth);
762 Result.BitWidth = BitWidth;
763 }
764 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000765}
766
Matt Arsenault155dda92016-03-21 15:00:35 +0000767APInt APInt::reverseBits() const {
768 switch (BitWidth) {
769 case 64:
770 return APInt(BitWidth, llvm::reverseBits<uint64_t>(VAL));
771 case 32:
772 return APInt(BitWidth, llvm::reverseBits<uint32_t>(VAL));
773 case 16:
774 return APInt(BitWidth, llvm::reverseBits<uint16_t>(VAL));
775 case 8:
776 return APInt(BitWidth, llvm::reverseBits<uint8_t>(VAL));
777 default:
778 break;
779 }
780
781 APInt Val(*this);
782 APInt Reversed(*this);
783 int S = BitWidth - 1;
784
785 const APInt One(BitWidth, 1);
786
787 for ((Val = Val.lshr(1)); Val != 0; (Val = Val.lshr(1))) {
788 Reversed <<= 1;
789 Reversed |= (Val & One);
790 --S;
791 }
792
793 Reversed <<= S;
794 return Reversed;
795}
796
Eric Christopher820256b2009-08-21 04:06:45 +0000797APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1,
Zhou Shengfbf61ea2007-02-08 14:35:19 +0000798 const APInt& API2) {
Zhou Shengdac63782007-02-06 03:00:16 +0000799 APInt A = API1, B = API2;
800 while (!!B) {
801 APInt T = B;
Reid Spencer1d072122007-02-16 22:36:51 +0000802 B = APIntOps::urem(A, B);
Zhou Shengdac63782007-02-06 03:00:16 +0000803 A = T;
804 }
805 return A;
806}
Chris Lattner28cbd1d2007-02-06 05:38:37 +0000807
Chris Lattner77527f52009-01-21 18:09:24 +0000808APInt llvm::APIntOps::RoundDoubleToAPInt(double Double, unsigned width) {
Zhou Shengd707d632007-02-12 20:02:55 +0000809 union {
810 double D;
811 uint64_t I;
812 } T;
813 T.D = Double;
Reid Spencer974551a2007-02-27 01:28:10 +0000814
815 // Get the sign bit from the highest order bit
Zhou Shengd707d632007-02-12 20:02:55 +0000816 bool isNeg = T.I >> 63;
Reid Spencer974551a2007-02-27 01:28:10 +0000817
818 // Get the 11-bit exponent and adjust for the 1023 bit bias
Zhou Shengd707d632007-02-12 20:02:55 +0000819 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
Reid Spencer974551a2007-02-27 01:28:10 +0000820
821 // If the exponent is negative, the value is < 0 so just return 0.
Zhou Shengd707d632007-02-12 20:02:55 +0000822 if (exp < 0)
Reid Spencer66d0d572007-02-28 01:30:08 +0000823 return APInt(width, 0u);
Reid Spencer974551a2007-02-27 01:28:10 +0000824
825 // Extract the mantissa by clearing the top 12 bits (sign + exponent).
826 uint64_t mantissa = (T.I & (~0ULL >> 12)) | 1ULL << 52;
827
828 // If the exponent doesn't shift all bits out of the mantissa
Zhou Shengd707d632007-02-12 20:02:55 +0000829 if (exp < 52)
Eric Christopher820256b2009-08-21 04:06:45 +0000830 return isNeg ? -APInt(width, mantissa >> (52 - exp)) :
Reid Spencer54abdcf2007-02-27 18:23:40 +0000831 APInt(width, mantissa >> (52 - exp));
832
833 // If the client didn't provide enough bits for us to shift the mantissa into
834 // then the result is undefined, just return 0
835 if (width <= exp - 52)
836 return APInt(width, 0);
Reid Spencer974551a2007-02-27 01:28:10 +0000837
838 // Otherwise, we have to shift the mantissa bits up to the right location
Reid Spencer54abdcf2007-02-27 18:23:40 +0000839 APInt Tmp(width, mantissa);
Chris Lattner77527f52009-01-21 18:09:24 +0000840 Tmp = Tmp.shl((unsigned)exp - 52);
Zhou Shengd707d632007-02-12 20:02:55 +0000841 return isNeg ? -Tmp : Tmp;
842}
843
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000844/// This function converts this APInt to a double.
Zhou Shengd707d632007-02-12 20:02:55 +0000845/// The layout for double is as following (IEEE Standard 754):
846/// --------------------------------------
847/// | Sign Exponent Fraction Bias |
848/// |-------------------------------------- |
849/// | 1[63] 11[62-52] 52[51-00] 1023 |
Eric Christopher820256b2009-08-21 04:06:45 +0000850/// --------------------------------------
Reid Spencer1d072122007-02-16 22:36:51 +0000851double APInt::roundToDouble(bool isSigned) const {
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000852
853 // Handle the simple case where the value is contained in one uint64_t.
Dale Johannesen54be7852009-08-12 18:04:11 +0000854 // It is wrong to optimize getWord(0) to VAL; there might be more than one word.
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000855 if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
856 if (isSigned) {
David Majnemer03992262016-06-24 21:15:36 +0000857 int64_t sext = SignExtend64(getWord(0), BitWidth);
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000858 return double(sext);
859 } else
Dale Johannesen34c08bb2009-08-12 17:42:34 +0000860 return double(getWord(0));
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000861 }
862
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000863 // Determine if the value is negative.
Reid Spencer1d072122007-02-16 22:36:51 +0000864 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000865
866 // Construct the absolute value if we're negative.
Zhou Shengd707d632007-02-12 20:02:55 +0000867 APInt Tmp(isNeg ? -(*this) : (*this));
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000868
869 // Figure out how many bits we're using.
Chris Lattner77527f52009-01-21 18:09:24 +0000870 unsigned n = Tmp.getActiveBits();
Zhou Shengd707d632007-02-12 20:02:55 +0000871
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000872 // The exponent (without bias normalization) is just the number of bits
873 // we are using. Note that the sign bit is gone since we constructed the
874 // absolute value.
875 uint64_t exp = n;
Zhou Shengd707d632007-02-12 20:02:55 +0000876
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000877 // Return infinity for exponent overflow
878 if (exp > 1023) {
879 if (!isSigned || !isNeg)
Jeff Cohene06855e2007-03-20 20:42:36 +0000880 return std::numeric_limits<double>::infinity();
Eric Christopher820256b2009-08-21 04:06:45 +0000881 else
Jeff Cohene06855e2007-03-20 20:42:36 +0000882 return -std::numeric_limits<double>::infinity();
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000883 }
884 exp += 1023; // Increment for 1023 bias
885
886 // Number of bits in mantissa is 52. To obtain the mantissa value, we must
887 // extract the high 52 bits from the correct words in pVal.
Zhou Shengd707d632007-02-12 20:02:55 +0000888 uint64_t mantissa;
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000889 unsigned hiWord = whichWord(n-1);
890 if (hiWord == 0) {
891 mantissa = Tmp.pVal[0];
892 if (n > 52)
893 mantissa >>= n - 52; // shift down, we want the top 52 bits.
894 } else {
895 assert(hiWord > 0 && "huh?");
896 uint64_t hibits = Tmp.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
897 uint64_t lobits = Tmp.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
898 mantissa = hibits | lobits;
899 }
900
Zhou Shengd707d632007-02-12 20:02:55 +0000901 // The leading bit of mantissa is implicit, so get rid of it.
Reid Spencerfbd48a52007-02-18 00:44:22 +0000902 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
Zhou Shengd707d632007-02-12 20:02:55 +0000903 union {
904 double D;
905 uint64_t I;
906 } T;
907 T.I = sign | (exp << 52) | mantissa;
908 return T.D;
909}
910
Reid Spencer1d072122007-02-16 22:36:51 +0000911// Truncate to new width.
Jay Foad583abbc2010-12-07 08:25:19 +0000912APInt APInt::trunc(unsigned width) const {
Reid Spencer1d072122007-02-16 22:36:51 +0000913 assert(width < BitWidth && "Invalid APInt Truncate request");
Chris Lattner1ac3e252008-08-20 17:02:31 +0000914 assert(width && "Can't truncate to 0 bits");
Jay Foad583abbc2010-12-07 08:25:19 +0000915
916 if (width <= APINT_BITS_PER_WORD)
917 return APInt(width, getRawData()[0]);
918
919 APInt Result(getMemory(getNumWords(width)), width);
920
921 // Copy full words.
922 unsigned i;
923 for (i = 0; i != width / APINT_BITS_PER_WORD; i++)
924 Result.pVal[i] = pVal[i];
925
926 // Truncate and copy any partial word.
927 unsigned bits = (0 - width) % APINT_BITS_PER_WORD;
928 if (bits != 0)
929 Result.pVal[i] = pVal[i] << bits >> bits;
930
931 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +0000932}
933
934// Sign extend to a new width.
Jay Foad583abbc2010-12-07 08:25:19 +0000935APInt APInt::sext(unsigned width) const {
Reid Spencer1d072122007-02-16 22:36:51 +0000936 assert(width > BitWidth && "Invalid APInt SignExtend request");
Jay Foad583abbc2010-12-07 08:25:19 +0000937
938 if (width <= APINT_BITS_PER_WORD) {
939 uint64_t val = VAL << (APINT_BITS_PER_WORD - BitWidth);
940 val = (int64_t)val >> (width - BitWidth);
941 return APInt(width, val >> (APINT_BITS_PER_WORD - width));
Reid Spencerb6b5cc32007-02-25 23:44:53 +0000942 }
943
Jay Foad583abbc2010-12-07 08:25:19 +0000944 APInt Result(getMemory(getNumWords(width)), width);
Reid Spencerb6b5cc32007-02-25 23:44:53 +0000945
Jay Foad583abbc2010-12-07 08:25:19 +0000946 // Copy full words.
947 unsigned i;
948 uint64_t word = 0;
949 for (i = 0; i != BitWidth / APINT_BITS_PER_WORD; i++) {
950 word = getRawData()[i];
951 Result.pVal[i] = word;
Reid Spencerb6b5cc32007-02-25 23:44:53 +0000952 }
953
Jay Foad583abbc2010-12-07 08:25:19 +0000954 // Read and sign-extend any partial word.
955 unsigned bits = (0 - BitWidth) % APINT_BITS_PER_WORD;
956 if (bits != 0)
957 word = (int64_t)getRawData()[i] << bits >> bits;
958 else
959 word = (int64_t)word >> (APINT_BITS_PER_WORD - 1);
960
961 // Write remaining full words.
962 for (; i != width / APINT_BITS_PER_WORD; i++) {
963 Result.pVal[i] = word;
964 word = (int64_t)word >> (APINT_BITS_PER_WORD - 1);
Reid Spencerb6b5cc32007-02-25 23:44:53 +0000965 }
Jay Foad583abbc2010-12-07 08:25:19 +0000966
967 // Write any partial word.
968 bits = (0 - width) % APINT_BITS_PER_WORD;
969 if (bits != 0)
970 Result.pVal[i] = word << bits >> bits;
971
972 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +0000973}
974
975// Zero extend to a new width.
Jay Foad583abbc2010-12-07 08:25:19 +0000976APInt APInt::zext(unsigned width) const {
Reid Spencer1d072122007-02-16 22:36:51 +0000977 assert(width > BitWidth && "Invalid APInt ZeroExtend request");
Jay Foad583abbc2010-12-07 08:25:19 +0000978
979 if (width <= APINT_BITS_PER_WORD)
980 return APInt(width, VAL);
981
982 APInt Result(getMemory(getNumWords(width)), width);
983
984 // Copy words.
985 unsigned i;
986 for (i = 0; i != getNumWords(); i++)
987 Result.pVal[i] = getRawData()[i];
988
989 // Zero remaining words.
990 memset(&Result.pVal[i], 0, (Result.getNumWords() - i) * APINT_WORD_SIZE);
991
992 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +0000993}
994
Jay Foad583abbc2010-12-07 08:25:19 +0000995APInt APInt::zextOrTrunc(unsigned width) const {
Reid Spencer742d1702007-03-01 17:15:32 +0000996 if (BitWidth < width)
997 return zext(width);
998 if (BitWidth > width)
999 return trunc(width);
1000 return *this;
1001}
1002
Jay Foad583abbc2010-12-07 08:25:19 +00001003APInt APInt::sextOrTrunc(unsigned width) const {
Reid Spencer742d1702007-03-01 17:15:32 +00001004 if (BitWidth < width)
1005 return sext(width);
1006 if (BitWidth > width)
1007 return trunc(width);
1008 return *this;
1009}
1010
Rafael Espindolabb893fe2012-01-27 23:33:07 +00001011APInt APInt::zextOrSelf(unsigned width) const {
1012 if (BitWidth < width)
1013 return zext(width);
1014 return *this;
1015}
1016
1017APInt APInt::sextOrSelf(unsigned width) const {
1018 if (BitWidth < width)
1019 return sext(width);
1020 return *this;
1021}
1022
Zhou Shenge93db8f2007-02-09 07:48:24 +00001023/// Arithmetic right-shift this APInt by shiftAmt.
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001024/// @brief Arithmetic right-shift function.
Dan Gohman105c1d42008-02-29 01:40:47 +00001025APInt APInt::ashr(const APInt &shiftAmt) const {
Chris Lattner77527f52009-01-21 18:09:24 +00001026 return ashr((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001027}
1028
1029/// Arithmetic right-shift this APInt by shiftAmt.
1030/// @brief Arithmetic right-shift function.
Chris Lattner77527f52009-01-21 18:09:24 +00001031APInt APInt::ashr(unsigned shiftAmt) const {
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001032 assert(shiftAmt <= BitWidth && "Invalid shift amount");
Reid Spencer1825dd02007-03-02 22:39:11 +00001033 // Handle a degenerate case
1034 if (shiftAmt == 0)
1035 return *this;
1036
1037 // Handle single word shifts with built-in ashr
Reid Spencer522ca7c2007-02-25 01:56:07 +00001038 if (isSingleWord()) {
1039 if (shiftAmt == BitWidth)
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001040 return APInt(BitWidth, 0); // undefined
Jonathan Roelofs851b79d2016-08-10 19:50:14 +00001041 return APInt(BitWidth, SignExtend64(VAL, BitWidth) >> shiftAmt);
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001042 }
Reid Spencer522ca7c2007-02-25 01:56:07 +00001043
Reid Spencer1825dd02007-03-02 22:39:11 +00001044 // If all the bits were shifted out, the result is, technically, undefined.
1045 // We return -1 if it was negative, 0 otherwise. We check this early to avoid
1046 // issues in the algorithm below.
Chris Lattnerdad2d092007-05-03 18:15:36 +00001047 if (shiftAmt == BitWidth) {
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001048 if (isNegative())
Zhou Sheng1247c072008-06-05 13:27:38 +00001049 return APInt(BitWidth, -1ULL, true);
Reid Spencera41e93b2007-02-25 19:32:03 +00001050 else
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001051 return APInt(BitWidth, 0);
Chris Lattnerdad2d092007-05-03 18:15:36 +00001052 }
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001053
1054 // Create some space for the result.
1055 uint64_t * val = new uint64_t[getNumWords()];
1056
Reid Spencer1825dd02007-03-02 22:39:11 +00001057 // Compute some values needed by the following shift algorithms
Chris Lattner77527f52009-01-21 18:09:24 +00001058 unsigned wordShift = shiftAmt % APINT_BITS_PER_WORD; // bits to shift per word
1059 unsigned offset = shiftAmt / APINT_BITS_PER_WORD; // word offset for shift
1060 unsigned breakWord = getNumWords() - 1 - offset; // last word affected
1061 unsigned bitsInWord = whichBit(BitWidth); // how many bits in last word?
Reid Spencer1825dd02007-03-02 22:39:11 +00001062 if (bitsInWord == 0)
1063 bitsInWord = APINT_BITS_PER_WORD;
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001064
1065 // If we are shifting whole words, just move whole words
1066 if (wordShift == 0) {
Reid Spencer1825dd02007-03-02 22:39:11 +00001067 // Move the words containing significant bits
Chris Lattner77527f52009-01-21 18:09:24 +00001068 for (unsigned i = 0; i <= breakWord; ++i)
Reid Spencer1825dd02007-03-02 22:39:11 +00001069 val[i] = pVal[i+offset]; // move whole word
1070
1071 // Adjust the top significant word for sign bit fill, if negative
1072 if (isNegative())
1073 if (bitsInWord < APINT_BITS_PER_WORD)
1074 val[breakWord] |= ~0ULL << bitsInWord; // set high bits
1075 } else {
Eric Christopher820256b2009-08-21 04:06:45 +00001076 // Shift the low order words
Chris Lattner77527f52009-01-21 18:09:24 +00001077 for (unsigned i = 0; i < breakWord; ++i) {
Reid Spencer1825dd02007-03-02 22:39:11 +00001078 // This combines the shifted corresponding word with the low bits from
1079 // the next word (shifted into this word's high bits).
Eric Christopher820256b2009-08-21 04:06:45 +00001080 val[i] = (pVal[i+offset] >> wordShift) |
Reid Spencer1825dd02007-03-02 22:39:11 +00001081 (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift));
1082 }
1083
1084 // Shift the break word. In this case there are no bits from the next word
1085 // to include in this word.
1086 val[breakWord] = pVal[breakWord+offset] >> wordShift;
1087
Alp Tokercb402912014-01-24 17:20:08 +00001088 // Deal with sign extension in the break word, and possibly the word before
Reid Spencer1825dd02007-03-02 22:39:11 +00001089 // it.
Chris Lattnerdad2d092007-05-03 18:15:36 +00001090 if (isNegative()) {
Reid Spencer1825dd02007-03-02 22:39:11 +00001091 if (wordShift > bitsInWord) {
1092 if (breakWord > 0)
Eric Christopher820256b2009-08-21 04:06:45 +00001093 val[breakWord-1] |=
Reid Spencer1825dd02007-03-02 22:39:11 +00001094 ~0ULL << (APINT_BITS_PER_WORD - (wordShift - bitsInWord));
1095 val[breakWord] |= ~0ULL;
Eric Christopher820256b2009-08-21 04:06:45 +00001096 } else
Reid Spencer1825dd02007-03-02 22:39:11 +00001097 val[breakWord] |= (~0ULL << (bitsInWord - wordShift));
Chris Lattnerdad2d092007-05-03 18:15:36 +00001098 }
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001099 }
1100
Reid Spencer1825dd02007-03-02 22:39:11 +00001101 // Remaining words are 0 or -1, just assign them.
1102 uint64_t fillValue = (isNegative() ? -1ULL : 0);
Chris Lattner77527f52009-01-21 18:09:24 +00001103 for (unsigned i = breakWord+1; i < getNumWords(); ++i)
Reid Spencer1825dd02007-03-02 22:39:11 +00001104 val[i] = fillValue;
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001105 APInt Result(val, BitWidth);
1106 Result.clearUnusedBits();
1107 return Result;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001108}
1109
Zhou Shenge93db8f2007-02-09 07:48:24 +00001110/// Logical right-shift this APInt by shiftAmt.
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001111/// @brief Logical right-shift function.
Dan Gohman105c1d42008-02-29 01:40:47 +00001112APInt APInt::lshr(const APInt &shiftAmt) const {
Chris Lattner77527f52009-01-21 18:09:24 +00001113 return lshr((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001114}
1115
1116/// Logical right-shift this APInt by shiftAmt.
1117/// @brief Logical right-shift function.
Chris Lattner77527f52009-01-21 18:09:24 +00001118APInt APInt::lshr(unsigned shiftAmt) const {
Chris Lattnerdad2d092007-05-03 18:15:36 +00001119 if (isSingleWord()) {
Ahmed Charles0dca5d82012-02-24 19:06:15 +00001120 if (shiftAmt >= BitWidth)
Reid Spencer522ca7c2007-02-25 01:56:07 +00001121 return APInt(BitWidth, 0);
Eric Christopher820256b2009-08-21 04:06:45 +00001122 else
Reid Spencer522ca7c2007-02-25 01:56:07 +00001123 return APInt(BitWidth, this->VAL >> shiftAmt);
Chris Lattnerdad2d092007-05-03 18:15:36 +00001124 }
Reid Spencer522ca7c2007-02-25 01:56:07 +00001125
Reid Spencer44eef162007-02-26 01:19:48 +00001126 // If all the bits were shifted out, the result is 0. This avoids issues
1127 // with shifting by the size of the integer type, which produces undefined
1128 // results. We define these "undefined results" to always be 0.
Chad Rosier3d464d82012-06-08 18:04:52 +00001129 if (shiftAmt >= BitWidth)
Reid Spencer44eef162007-02-26 01:19:48 +00001130 return APInt(BitWidth, 0);
1131
Reid Spencerfffdf102007-05-17 06:26:29 +00001132 // If none of the bits are shifted out, the result is *this. This avoids
Eric Christopher820256b2009-08-21 04:06:45 +00001133 // issues with shifting by the size of the integer type, which produces
Reid Spencerfffdf102007-05-17 06:26:29 +00001134 // undefined results in the code below. This is also an optimization.
1135 if (shiftAmt == 0)
1136 return *this;
1137
Reid Spencer44eef162007-02-26 01:19:48 +00001138 // Create some space for the result.
1139 uint64_t * val = new uint64_t[getNumWords()];
1140
1141 // If we are shifting less than a word, compute the shift with a simple carry
1142 if (shiftAmt < APINT_BITS_PER_WORD) {
Richard Smith4f9a8082011-11-23 21:33:37 +00001143 lshrNear(val, pVal, getNumWords(), shiftAmt);
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001144 APInt Result(val, BitWidth);
1145 Result.clearUnusedBits();
1146 return Result;
Reid Spencera41e93b2007-02-25 19:32:03 +00001147 }
1148
Reid Spencer44eef162007-02-26 01:19:48 +00001149 // Compute some values needed by the remaining shift algorithms
Chris Lattner77527f52009-01-21 18:09:24 +00001150 unsigned wordShift = shiftAmt % APINT_BITS_PER_WORD;
1151 unsigned offset = shiftAmt / APINT_BITS_PER_WORD;
Reid Spencer44eef162007-02-26 01:19:48 +00001152
1153 // If we are shifting whole words, just move whole words
1154 if (wordShift == 0) {
Chris Lattner77527f52009-01-21 18:09:24 +00001155 for (unsigned i = 0; i < getNumWords() - offset; ++i)
Reid Spencer44eef162007-02-26 01:19:48 +00001156 val[i] = pVal[i+offset];
Chris Lattner77527f52009-01-21 18:09:24 +00001157 for (unsigned i = getNumWords()-offset; i < getNumWords(); i++)
Reid Spencer44eef162007-02-26 01:19:48 +00001158 val[i] = 0;
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001159 APInt Result(val, BitWidth);
1160 Result.clearUnusedBits();
1161 return Result;
Reid Spencer44eef162007-02-26 01:19:48 +00001162 }
1163
Eric Christopher820256b2009-08-21 04:06:45 +00001164 // Shift the low order words
Chris Lattner77527f52009-01-21 18:09:24 +00001165 unsigned breakWord = getNumWords() - offset -1;
1166 for (unsigned i = 0; i < breakWord; ++i)
Reid Spencerd99feaf2007-03-01 05:39:56 +00001167 val[i] = (pVal[i+offset] >> wordShift) |
1168 (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift));
Reid Spencer44eef162007-02-26 01:19:48 +00001169 // Shift the break word.
1170 val[breakWord] = pVal[breakWord+offset] >> wordShift;
1171
1172 // Remaining words are 0
Chris Lattner77527f52009-01-21 18:09:24 +00001173 for (unsigned i = breakWord+1; i < getNumWords(); ++i)
Reid Spencer44eef162007-02-26 01:19:48 +00001174 val[i] = 0;
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001175 APInt Result(val, BitWidth);
1176 Result.clearUnusedBits();
1177 return Result;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001178}
1179
Zhou Shenge93db8f2007-02-09 07:48:24 +00001180/// Left-shift this APInt by shiftAmt.
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001181/// @brief Left-shift function.
Dan Gohman105c1d42008-02-29 01:40:47 +00001182APInt APInt::shl(const APInt &shiftAmt) const {
Nick Lewycky030c4502009-01-19 17:42:33 +00001183 // It's undefined behavior in C to shift by BitWidth or greater.
Chris Lattner77527f52009-01-21 18:09:24 +00001184 return shl((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001185}
1186
Chris Lattner77527f52009-01-21 18:09:24 +00001187APInt APInt::shlSlowCase(unsigned shiftAmt) const {
Reid Spencera5c84d92007-02-25 00:56:44 +00001188 // If all the bits were shifted out, the result is 0. This avoids issues
1189 // with shifting by the size of the integer type, which produces undefined
1190 // results. We define these "undefined results" to always be 0.
1191 if (shiftAmt == BitWidth)
1192 return APInt(BitWidth, 0);
1193
Reid Spencer81ee0202007-05-12 18:01:57 +00001194 // If none of the bits are shifted out, the result is *this. This avoids a
1195 // lshr by the words size in the loop below which can produce incorrect
1196 // results. It also avoids the expensive computation below for a common case.
1197 if (shiftAmt == 0)
1198 return *this;
1199
Reid Spencera5c84d92007-02-25 00:56:44 +00001200 // Create some space for the result.
1201 uint64_t * val = new uint64_t[getNumWords()];
1202
1203 // If we are shifting less than a word, do it the easy way
1204 if (shiftAmt < APINT_BITS_PER_WORD) {
1205 uint64_t carry = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001206 for (unsigned i = 0; i < getNumWords(); i++) {
Reid Spencera5c84d92007-02-25 00:56:44 +00001207 val[i] = pVal[i] << shiftAmt | carry;
1208 carry = pVal[i] >> (APINT_BITS_PER_WORD - shiftAmt);
1209 }
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001210 APInt Result(val, BitWidth);
1211 Result.clearUnusedBits();
1212 return Result;
Reid Spencer632ebdf2007-02-24 20:19:37 +00001213 }
1214
Reid Spencera5c84d92007-02-25 00:56:44 +00001215 // Compute some values needed by the remaining shift algorithms
Chris Lattner77527f52009-01-21 18:09:24 +00001216 unsigned wordShift = shiftAmt % APINT_BITS_PER_WORD;
1217 unsigned offset = shiftAmt / APINT_BITS_PER_WORD;
Reid Spencera5c84d92007-02-25 00:56:44 +00001218
1219 // If we are shifting whole words, just move whole words
1220 if (wordShift == 0) {
Chris Lattner77527f52009-01-21 18:09:24 +00001221 for (unsigned i = 0; i < offset; i++)
Reid Spencera5c84d92007-02-25 00:56:44 +00001222 val[i] = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001223 for (unsigned i = offset; i < getNumWords(); i++)
Reid Spencera5c84d92007-02-25 00:56:44 +00001224 val[i] = pVal[i-offset];
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001225 APInt Result(val, BitWidth);
1226 Result.clearUnusedBits();
1227 return Result;
Reid Spencer632ebdf2007-02-24 20:19:37 +00001228 }
Reid Spencera5c84d92007-02-25 00:56:44 +00001229
1230 // Copy whole words from this to Result.
Chris Lattner77527f52009-01-21 18:09:24 +00001231 unsigned i = getNumWords() - 1;
Reid Spencera5c84d92007-02-25 00:56:44 +00001232 for (; i > offset; --i)
1233 val[i] = pVal[i-offset] << wordShift |
1234 pVal[i-offset-1] >> (APINT_BITS_PER_WORD - wordShift);
Reid Spencerab0e08a2007-02-25 01:08:58 +00001235 val[offset] = pVal[0] << wordShift;
Reid Spencera5c84d92007-02-25 00:56:44 +00001236 for (i = 0; i < offset; ++i)
1237 val[i] = 0;
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001238 APInt Result(val, BitWidth);
1239 Result.clearUnusedBits();
1240 return Result;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001241}
1242
Dan Gohman105c1d42008-02-29 01:40:47 +00001243APInt APInt::rotl(const APInt &rotateAmt) const {
Chris Lattner77527f52009-01-21 18:09:24 +00001244 return rotl((unsigned)rotateAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001245}
1246
Chris Lattner77527f52009-01-21 18:09:24 +00001247APInt APInt::rotl(unsigned rotateAmt) const {
Eli Friedman2aae94f2011-12-22 03:15:35 +00001248 rotateAmt %= BitWidth;
Reid Spencer98ed7db2007-05-14 00:15:28 +00001249 if (rotateAmt == 0)
1250 return *this;
Eli Friedman2aae94f2011-12-22 03:15:35 +00001251 return shl(rotateAmt) | lshr(BitWidth - rotateAmt);
Reid Spencer4c50b522007-05-13 23:44:59 +00001252}
1253
Dan Gohman105c1d42008-02-29 01:40:47 +00001254APInt APInt::rotr(const APInt &rotateAmt) const {
Chris Lattner77527f52009-01-21 18:09:24 +00001255 return rotr((unsigned)rotateAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001256}
1257
Chris Lattner77527f52009-01-21 18:09:24 +00001258APInt APInt::rotr(unsigned rotateAmt) const {
Eli Friedman2aae94f2011-12-22 03:15:35 +00001259 rotateAmt %= BitWidth;
Reid Spencer98ed7db2007-05-14 00:15:28 +00001260 if (rotateAmt == 0)
1261 return *this;
Eli Friedman2aae94f2011-12-22 03:15:35 +00001262 return lshr(rotateAmt) | shl(BitWidth - rotateAmt);
Reid Spencer4c50b522007-05-13 23:44:59 +00001263}
Reid Spencerd99feaf2007-03-01 05:39:56 +00001264
1265// Square Root - this method computes and returns the square root of "this".
1266// Three mechanisms are used for computation. For small values (<= 5 bits),
1267// a table lookup is done. This gets some performance for common cases. For
1268// values using less than 52 bits, the value is converted to double and then
1269// the libc sqrt function is called. The result is rounded and then converted
1270// back to a uint64_t which is then used to construct the result. Finally,
Eric Christopher820256b2009-08-21 04:06:45 +00001271// the Babylonian method for computing square roots is used.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001272APInt APInt::sqrt() const {
1273
1274 // Determine the magnitude of the value.
Chris Lattner77527f52009-01-21 18:09:24 +00001275 unsigned magnitude = getActiveBits();
Reid Spencerd99feaf2007-03-01 05:39:56 +00001276
1277 // Use a fast table for some small values. This also gets rid of some
1278 // rounding errors in libc sqrt for small values.
1279 if (magnitude <= 5) {
Reid Spencer2f6ad4d2007-03-01 17:47:31 +00001280 static const uint8_t results[32] = {
Reid Spencerc8841d22007-03-01 06:23:32 +00001281 /* 0 */ 0,
1282 /* 1- 2 */ 1, 1,
Eric Christopher820256b2009-08-21 04:06:45 +00001283 /* 3- 6 */ 2, 2, 2, 2,
Reid Spencerc8841d22007-03-01 06:23:32 +00001284 /* 7-12 */ 3, 3, 3, 3, 3, 3,
1285 /* 13-20 */ 4, 4, 4, 4, 4, 4, 4, 4,
1286 /* 21-30 */ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
1287 /* 31 */ 6
1288 };
1289 return APInt(BitWidth, results[ (isSingleWord() ? VAL : pVal[0]) ]);
Reid Spencerd99feaf2007-03-01 05:39:56 +00001290 }
1291
1292 // If the magnitude of the value fits in less than 52 bits (the precision of
1293 // an IEEE double precision floating point value), then we can use the
1294 // libc sqrt function which will probably use a hardware sqrt computation.
1295 // This should be faster than the algorithm below.
Jeff Cohenb622c112007-03-05 00:00:42 +00001296 if (magnitude < 52) {
Eric Christopher820256b2009-08-21 04:06:45 +00001297 return APInt(BitWidth,
Reid Spencerd99feaf2007-03-01 05:39:56 +00001298 uint64_t(::round(::sqrt(double(isSingleWord()?VAL:pVal[0])))));
Jeff Cohenb622c112007-03-05 00:00:42 +00001299 }
Reid Spencerd99feaf2007-03-01 05:39:56 +00001300
1301 // Okay, all the short cuts are exhausted. We must compute it. The following
1302 // is a classical Babylonian method for computing the square root. This code
Sanjay Patel4cb54e02014-09-11 15:41:01 +00001303 // was adapted to APInt from a wikipedia article on such computations.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001304 // See http://www.wikipedia.org/ and go to the page named
Eric Christopher820256b2009-08-21 04:06:45 +00001305 // Calculate_an_integer_square_root.
Chris Lattner77527f52009-01-21 18:09:24 +00001306 unsigned nbits = BitWidth, i = 4;
Reid Spencerd99feaf2007-03-01 05:39:56 +00001307 APInt testy(BitWidth, 16);
1308 APInt x_old(BitWidth, 1);
1309 APInt x_new(BitWidth, 0);
1310 APInt two(BitWidth, 2);
1311
1312 // Select a good starting value using binary logarithms.
Eric Christopher820256b2009-08-21 04:06:45 +00001313 for (;; i += 2, testy = testy.shl(2))
Reid Spencerd99feaf2007-03-01 05:39:56 +00001314 if (i >= nbits || this->ule(testy)) {
1315 x_old = x_old.shl(i / 2);
1316 break;
1317 }
1318
Eric Christopher820256b2009-08-21 04:06:45 +00001319 // Use the Babylonian method to arrive at the integer square root:
Reid Spencerd99feaf2007-03-01 05:39:56 +00001320 for (;;) {
1321 x_new = (this->udiv(x_old) + x_old).udiv(two);
1322 if (x_old.ule(x_new))
1323 break;
1324 x_old = x_new;
1325 }
1326
1327 // Make sure we return the closest approximation
Eric Christopher820256b2009-08-21 04:06:45 +00001328 // NOTE: The rounding calculation below is correct. It will produce an
Reid Spencercf817562007-03-02 04:21:55 +00001329 // off-by-one discrepancy with results from pari/gp. That discrepancy has been
Eric Christopher820256b2009-08-21 04:06:45 +00001330 // determined to be a rounding issue with pari/gp as it begins to use a
Reid Spencercf817562007-03-02 04:21:55 +00001331 // floating point representation after 192 bits. There are no discrepancies
1332 // between this algorithm and pari/gp for bit widths < 192 bits.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001333 APInt square(x_old * x_old);
1334 APInt nextSquare((x_old + 1) * (x_old +1));
1335 if (this->ult(square))
1336 return x_old;
David Blaikie54c94622011-12-01 20:58:30 +00001337 assert(this->ule(nextSquare) && "Error in APInt::sqrt computation");
1338 APInt midpoint((nextSquare - square).udiv(two));
1339 APInt offset(*this - square);
1340 if (offset.ult(midpoint))
1341 return x_old;
Reid Spencerd99feaf2007-03-01 05:39:56 +00001342 return x_old + 1;
1343}
1344
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001345/// Computes the multiplicative inverse of this APInt for a given modulo. The
1346/// iterative extended Euclidean algorithm is used to solve for this value,
1347/// however we simplify it to speed up calculating only the inverse, and take
1348/// advantage of div+rem calculations. We also use some tricks to avoid copying
1349/// (potentially large) APInts around.
1350APInt APInt::multiplicativeInverse(const APInt& modulo) const {
1351 assert(ult(modulo) && "This APInt must be smaller than the modulo");
1352
1353 // Using the properties listed at the following web page (accessed 06/21/08):
1354 // http://www.numbertheory.org/php/euclid.html
1355 // (especially the properties numbered 3, 4 and 9) it can be proved that
1356 // BitWidth bits suffice for all the computations in the algorithm implemented
1357 // below. More precisely, this number of bits suffice if the multiplicative
1358 // inverse exists, but may not suffice for the general extended Euclidean
1359 // algorithm.
1360
1361 APInt r[2] = { modulo, *this };
1362 APInt t[2] = { APInt(BitWidth, 0), APInt(BitWidth, 1) };
1363 APInt q(BitWidth, 0);
Eric Christopher820256b2009-08-21 04:06:45 +00001364
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001365 unsigned i;
1366 for (i = 0; r[i^1] != 0; i ^= 1) {
1367 // An overview of the math without the confusing bit-flipping:
1368 // q = r[i-2] / r[i-1]
1369 // r[i] = r[i-2] % r[i-1]
1370 // t[i] = t[i-2] - t[i-1] * q
1371 udivrem(r[i], r[i^1], q, r[i]);
1372 t[i] -= t[i^1] * q;
1373 }
1374
1375 // If this APInt and the modulo are not coprime, there is no multiplicative
1376 // inverse, so return 0. We check this by looking at the next-to-last
1377 // remainder, which is the gcd(*this,modulo) as calculated by the Euclidean
1378 // algorithm.
1379 if (r[i] != 1)
1380 return APInt(BitWidth, 0);
1381
1382 // The next-to-last t is the multiplicative inverse. However, we are
1383 // interested in a positive inverse. Calcuate a positive one from a negative
1384 // one if necessary. A simple addition of the modulo suffices because
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00001385 // abs(t[i]) is known to be less than *this/2 (see the link above).
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001386 return t[i].isNegative() ? t[i] + modulo : t[i];
1387}
1388
Jay Foadfe0c6482009-04-30 10:15:35 +00001389/// Calculate the magic numbers required to implement a signed integer division
1390/// by a constant as a sequence of multiplies, adds and shifts. Requires that
1391/// the divisor not be 0, 1, or -1. Taken from "Hacker's Delight", Henry S.
1392/// Warren, Jr., chapter 10.
1393APInt::ms APInt::magic() const {
1394 const APInt& d = *this;
1395 unsigned p;
1396 APInt ad, anc, delta, q1, r1, q2, r2, t;
Jay Foadfe0c6482009-04-30 10:15:35 +00001397 APInt signedMin = APInt::getSignedMinValue(d.getBitWidth());
Jay Foadfe0c6482009-04-30 10:15:35 +00001398 struct ms mag;
Eric Christopher820256b2009-08-21 04:06:45 +00001399
Jay Foadfe0c6482009-04-30 10:15:35 +00001400 ad = d.abs();
1401 t = signedMin + (d.lshr(d.getBitWidth() - 1));
1402 anc = t - 1 - t.urem(ad); // absolute value of nc
1403 p = d.getBitWidth() - 1; // initialize p
1404 q1 = signedMin.udiv(anc); // initialize q1 = 2p/abs(nc)
1405 r1 = signedMin - q1*anc; // initialize r1 = rem(2p,abs(nc))
1406 q2 = signedMin.udiv(ad); // initialize q2 = 2p/abs(d)
1407 r2 = signedMin - q2*ad; // initialize r2 = rem(2p,abs(d))
1408 do {
1409 p = p + 1;
1410 q1 = q1<<1; // update q1 = 2p/abs(nc)
1411 r1 = r1<<1; // update r1 = rem(2p/abs(nc))
1412 if (r1.uge(anc)) { // must be unsigned comparison
1413 q1 = q1 + 1;
1414 r1 = r1 - anc;
1415 }
1416 q2 = q2<<1; // update q2 = 2p/abs(d)
1417 r2 = r2<<1; // update r2 = rem(2p/abs(d))
1418 if (r2.uge(ad)) { // must be unsigned comparison
1419 q2 = q2 + 1;
1420 r2 = r2 - ad;
1421 }
1422 delta = ad - r2;
Cameron Zwarich8731d0c2011-02-21 00:22:02 +00001423 } while (q1.ult(delta) || (q1 == delta && r1 == 0));
Eric Christopher820256b2009-08-21 04:06:45 +00001424
Jay Foadfe0c6482009-04-30 10:15:35 +00001425 mag.m = q2 + 1;
1426 if (d.isNegative()) mag.m = -mag.m; // resulting magic number
1427 mag.s = p - d.getBitWidth(); // resulting shift
1428 return mag;
1429}
1430
1431/// Calculate the magic numbers required to implement an unsigned integer
1432/// division by a constant as a sequence of multiplies, adds and shifts.
1433/// Requires that the divisor not be 0. Taken from "Hacker's Delight", Henry
1434/// S. Warren, Jr., chapter 10.
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001435/// LeadingZeros can be used to simplify the calculation if the upper bits
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001436/// of the divided value are known zero.
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001437APInt::mu APInt::magicu(unsigned LeadingZeros) const {
Jay Foadfe0c6482009-04-30 10:15:35 +00001438 const APInt& d = *this;
1439 unsigned p;
1440 APInt nc, delta, q1, r1, q2, r2;
1441 struct mu magu;
1442 magu.a = 0; // initialize "add" indicator
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001443 APInt allOnes = APInt::getAllOnesValue(d.getBitWidth()).lshr(LeadingZeros);
Jay Foadfe0c6482009-04-30 10:15:35 +00001444 APInt signedMin = APInt::getSignedMinValue(d.getBitWidth());
1445 APInt signedMax = APInt::getSignedMaxValue(d.getBitWidth());
1446
Benjamin Kramer3aab6a82012-07-11 18:31:59 +00001447 nc = allOnes - (allOnes - d).urem(d);
Jay Foadfe0c6482009-04-30 10:15:35 +00001448 p = d.getBitWidth() - 1; // initialize p
1449 q1 = signedMin.udiv(nc); // initialize q1 = 2p/nc
1450 r1 = signedMin - q1*nc; // initialize r1 = rem(2p,nc)
1451 q2 = signedMax.udiv(d); // initialize q2 = (2p-1)/d
1452 r2 = signedMax - q2*d; // initialize r2 = rem((2p-1),d)
1453 do {
1454 p = p + 1;
1455 if (r1.uge(nc - r1)) {
1456 q1 = q1 + q1 + 1; // update q1
1457 r1 = r1 + r1 - nc; // update r1
1458 }
1459 else {
1460 q1 = q1+q1; // update q1
1461 r1 = r1+r1; // update r1
1462 }
1463 if ((r2 + 1).uge(d - r2)) {
1464 if (q2.uge(signedMax)) magu.a = 1;
1465 q2 = q2+q2 + 1; // update q2
1466 r2 = r2+r2 + 1 - d; // update r2
1467 }
1468 else {
1469 if (q2.uge(signedMin)) magu.a = 1;
1470 q2 = q2+q2; // update q2
1471 r2 = r2+r2 + 1; // update r2
1472 }
1473 delta = d - 1 - r2;
1474 } while (p < d.getBitWidth()*2 &&
1475 (q1.ult(delta) || (q1 == delta && r1 == 0)));
1476 magu.m = q2 + 1; // resulting magic number
1477 magu.s = p - d.getBitWidth(); // resulting shift
1478 return magu;
1479}
1480
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001481/// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
1482/// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
1483/// variables here have the same names as in the algorithm. Comments explain
1484/// the algorithm and any deviation from it.
Chris Lattner77527f52009-01-21 18:09:24 +00001485static void KnuthDiv(unsigned *u, unsigned *v, unsigned *q, unsigned* r,
1486 unsigned m, unsigned n) {
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001487 assert(u && "Must provide dividend");
1488 assert(v && "Must provide divisor");
1489 assert(q && "Must provide quotient");
Yaron Keren39fc5a62015-03-26 19:45:19 +00001490 assert(u != v && u != q && v != q && "Must use different memory");
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001491 assert(n>1 && "n must be > 1");
1492
Yaron Keren39fc5a62015-03-26 19:45:19 +00001493 // b denotes the base of the number system. In our case b is 2^32.
George Burgess IV381fc0e2016-08-25 01:05:08 +00001494 const uint64_t b = uint64_t(1) << 32;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001495
David Greenef32fcb42010-01-05 01:28:52 +00001496 DEBUG(dbgs() << "KnuthDiv: m=" << m << " n=" << n << '\n');
1497 DEBUG(dbgs() << "KnuthDiv: original:");
1498 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
1499 DEBUG(dbgs() << " by");
1500 DEBUG(for (int i = n; i >0; i--) dbgs() << " " << v[i-1]);
1501 DEBUG(dbgs() << '\n');
Eric Christopher820256b2009-08-21 04:06:45 +00001502 // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
1503 // u and v by d. Note that we have taken Knuth's advice here to use a power
1504 // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
1505 // 2 allows us to shift instead of multiply and it is easy to determine the
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001506 // shift amount from the leading zeros. We are basically normalizing the u
1507 // and v so that its high bits are shifted to the top of v's range without
1508 // overflow. Note that this can require an extra word in u so that u must
1509 // be of length m+n+1.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001510 unsigned shift = countLeadingZeros(v[n-1]);
Chris Lattner77527f52009-01-21 18:09:24 +00001511 unsigned v_carry = 0;
1512 unsigned u_carry = 0;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001513 if (shift) {
Chris Lattner77527f52009-01-21 18:09:24 +00001514 for (unsigned i = 0; i < m+n; ++i) {
1515 unsigned u_tmp = u[i] >> (32 - shift);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001516 u[i] = (u[i] << shift) | u_carry;
1517 u_carry = u_tmp;
Reid Spencer100502d2007-02-17 03:16:00 +00001518 }
Chris Lattner77527f52009-01-21 18:09:24 +00001519 for (unsigned i = 0; i < n; ++i) {
1520 unsigned v_tmp = v[i] >> (32 - shift);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001521 v[i] = (v[i] << shift) | v_carry;
1522 v_carry = v_tmp;
1523 }
1524 }
1525 u[m+n] = u_carry;
Yaron Keren39fc5a62015-03-26 19:45:19 +00001526
David Greenef32fcb42010-01-05 01:28:52 +00001527 DEBUG(dbgs() << "KnuthDiv: normal:");
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');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001532
1533 // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
1534 int j = m;
1535 do {
David Greenef32fcb42010-01-05 01:28:52 +00001536 DEBUG(dbgs() << "KnuthDiv: quotient digit #" << j << '\n');
Eric Christopher820256b2009-08-21 04:06:45 +00001537 // D3. [Calculate q'.].
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001538 // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
1539 // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
1540 // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
1541 // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test
1542 // on v[n-2] determines at high speed most of the cases in which the trial
Eric Christopher820256b2009-08-21 04:06:45 +00001543 // value qp is one too large, and it eliminates all cases where qp is two
1544 // too large.
Reid Spencercb292e42007-02-23 01:57:13 +00001545 uint64_t dividend = ((uint64_t(u[j+n]) << 32) + u[j+n-1]);
David Greenef32fcb42010-01-05 01:28:52 +00001546 DEBUG(dbgs() << "KnuthDiv: dividend == " << dividend << '\n');
Reid Spencercb292e42007-02-23 01:57:13 +00001547 uint64_t qp = dividend / v[n-1];
1548 uint64_t rp = dividend % v[n-1];
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001549 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1550 qp--;
1551 rp += v[n-1];
Reid Spencerdf6cf5a2007-02-24 10:01:42 +00001552 if (rp < b && (qp == b || qp*v[n-2] > b*rp + u[j+n-2]))
Reid Spencera5e0d202007-02-24 03:58:46 +00001553 qp--;
Reid Spencercb292e42007-02-23 01:57:13 +00001554 }
David Greenef32fcb42010-01-05 01:28:52 +00001555 DEBUG(dbgs() << "KnuthDiv: qp == " << qp << ", rp == " << rp << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001556
Reid Spencercb292e42007-02-23 01:57:13 +00001557 // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with
1558 // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation
1559 // consists of a simple multiplication by a one-place number, combined with
Eric Christopher820256b2009-08-21 04:06:45 +00001560 // a subtraction.
Yaron Keren39fc5a62015-03-26 19:45:19 +00001561 // The digits (u[j+n]...u[j]) should be kept positive; if the result of
1562 // this step is actually negative, (u[j+n]...u[j]) should be left as the
1563 // true value plus b**(n+1), namely as the b's complement of
1564 // the true value, and a "borrow" to the left should be remembered.
Pawel Bylica86ac4472015-04-24 07:38:39 +00001565 int64_t borrow = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001566 for (unsigned i = 0; i < n; ++i) {
Pawel Bylica86ac4472015-04-24 07:38:39 +00001567 uint64_t p = uint64_t(qp) * uint64_t(v[i]);
1568 int64_t subres = int64_t(u[j+i]) - borrow - (unsigned)p;
1569 u[j+i] = (unsigned)subres;
1570 borrow = (p >> 32) - (subres >> 32);
1571 DEBUG(dbgs() << "KnuthDiv: u[j+i] = " << u[j+i]
Daniel Dunbar763ace92009-07-13 05:27:30 +00001572 << ", borrow = " << borrow << '\n');
Reid Spencera5e0d202007-02-24 03:58:46 +00001573 }
Pawel Bylica86ac4472015-04-24 07:38:39 +00001574 bool isNeg = u[j+n] < borrow;
1575 u[j+n] -= (unsigned)borrow;
1576
David Greenef32fcb42010-01-05 01:28:52 +00001577 DEBUG(dbgs() << "KnuthDiv: after subtraction:");
1578 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
1579 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001580
Eric Christopher820256b2009-08-21 04:06:45 +00001581 // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001582 // negative, go to step D6; otherwise go on to step D7.
Chris Lattner77527f52009-01-21 18:09:24 +00001583 q[j] = (unsigned)qp;
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001584 if (isNeg) {
Eric Christopher820256b2009-08-21 04:06:45 +00001585 // D6. [Add back]. The probability that this step is necessary is very
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001586 // small, on the order of only 2/b. Make sure that test data accounts for
Eric Christopher820256b2009-08-21 04:06:45 +00001587 // this possibility. Decrease q[j] by 1
Reid Spencercb292e42007-02-23 01:57:13 +00001588 q[j]--;
Eric Christopher820256b2009-08-21 04:06:45 +00001589 // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]).
1590 // A carry will occur to the left of u[j+n], and it should be ignored
Reid Spencercb292e42007-02-23 01:57:13 +00001591 // since it cancels with the borrow that occurred in D4.
1592 bool carry = false;
Chris Lattner77527f52009-01-21 18:09:24 +00001593 for (unsigned i = 0; i < n; i++) {
1594 unsigned limit = std::min(u[j+i],v[i]);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001595 u[j+i] += v[i] + carry;
Reid Spencera5e0d202007-02-24 03:58:46 +00001596 carry = u[j+i] < limit || (carry && u[j+i] == limit);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001597 }
Reid Spencera5e0d202007-02-24 03:58:46 +00001598 u[j+n] += carry;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001599 }
David Greenef32fcb42010-01-05 01:28:52 +00001600 DEBUG(dbgs() << "KnuthDiv: after correction:");
Yaron Keren39fc5a62015-03-26 19:45:19 +00001601 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
David Greenef32fcb42010-01-05 01:28:52 +00001602 DEBUG(dbgs() << "\nKnuthDiv: digit result = " << q[j] << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001603
Reid Spencercb292e42007-02-23 01:57:13 +00001604 // D7. [Loop on j.] Decrease j by one. Now if j >= 0, go back to D3.
1605 } while (--j >= 0);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001606
David Greenef32fcb42010-01-05 01:28:52 +00001607 DEBUG(dbgs() << "KnuthDiv: quotient:");
1608 DEBUG(for (int i = m; i >=0; i--) dbgs() <<" " << q[i]);
1609 DEBUG(dbgs() << '\n');
Reid Spencera5e0d202007-02-24 03:58:46 +00001610
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001611 // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
1612 // remainder may be obtained by dividing u[...] by d. If r is non-null we
1613 // compute the remainder (urem uses this).
1614 if (r) {
1615 // The value d is expressed by the "shift" value above since we avoided
1616 // multiplication by d by using a shift left. So, all we have to do is
1617 // shift right here. In order to mak
Reid Spencer468ad9112007-02-24 20:38:01 +00001618 if (shift) {
Chris Lattner77527f52009-01-21 18:09:24 +00001619 unsigned carry = 0;
David Greenef32fcb42010-01-05 01:28:52 +00001620 DEBUG(dbgs() << "KnuthDiv: remainder:");
Reid Spencer468ad9112007-02-24 20:38:01 +00001621 for (int i = n-1; i >= 0; i--) {
1622 r[i] = (u[i] >> shift) | carry;
1623 carry = u[i] << (32 - shift);
David Greenef32fcb42010-01-05 01:28:52 +00001624 DEBUG(dbgs() << " " << r[i]);
Reid Spencer468ad9112007-02-24 20:38:01 +00001625 }
1626 } else {
1627 for (int i = n-1; i >= 0; i--) {
1628 r[i] = u[i];
David Greenef32fcb42010-01-05 01:28:52 +00001629 DEBUG(dbgs() << " " << r[i]);
Reid Spencer468ad9112007-02-24 20:38:01 +00001630 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001631 }
David Greenef32fcb42010-01-05 01:28:52 +00001632 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001633 }
David Greenef32fcb42010-01-05 01:28:52 +00001634 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001635}
1636
Benjamin Kramerc321e532016-06-08 19:09:22 +00001637void APInt::divide(const APInt &LHS, unsigned lhsWords, const APInt &RHS,
1638 unsigned rhsWords, APInt *Quotient, APInt *Remainder) {
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001639 assert(lhsWords >= rhsWords && "Fractional result");
1640
Eric Christopher820256b2009-08-21 04:06:45 +00001641 // First, compose the values into an array of 32-bit words instead of
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001642 // 64-bit words. This is a necessity of both the "short division" algorithm
Dan Gohman4a618822010-02-10 16:03:48 +00001643 // and the Knuth "classical algorithm" which requires there to be native
Eric Christopher820256b2009-08-21 04:06:45 +00001644 // operations for +, -, and * on an m bit value with an m*2 bit result. We
1645 // can't use 64-bit operands here because we don't have native results of
1646 // 128-bits. Furthermore, casting the 64-bit values to 32-bit values won't
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001647 // work on large-endian machines.
Dan Gohmancff69532009-04-01 18:45:54 +00001648 uint64_t mask = ~0ull >> (sizeof(unsigned)*CHAR_BIT);
Chris Lattner77527f52009-01-21 18:09:24 +00001649 unsigned n = rhsWords * 2;
1650 unsigned m = (lhsWords * 2) - n;
Reid Spencer522ca7c2007-02-25 01:56:07 +00001651
1652 // Allocate space for the temporary values we need either on the stack, if
1653 // it will fit, or on the heap if it won't.
Chris Lattner77527f52009-01-21 18:09:24 +00001654 unsigned SPACE[128];
Craig Topperc10719f2014-04-07 04:17:22 +00001655 unsigned *U = nullptr;
1656 unsigned *V = nullptr;
1657 unsigned *Q = nullptr;
1658 unsigned *R = nullptr;
Reid Spencer522ca7c2007-02-25 01:56:07 +00001659 if ((Remainder?4:3)*n+2*m+1 <= 128) {
1660 U = &SPACE[0];
1661 V = &SPACE[m+n+1];
1662 Q = &SPACE[(m+n+1) + n];
1663 if (Remainder)
1664 R = &SPACE[(m+n+1) + n + (m+n)];
1665 } else {
Chris Lattner77527f52009-01-21 18:09:24 +00001666 U = new unsigned[m + n + 1];
1667 V = new unsigned[n];
1668 Q = new unsigned[m+n];
Reid Spencer522ca7c2007-02-25 01:56:07 +00001669 if (Remainder)
Chris Lattner77527f52009-01-21 18:09:24 +00001670 R = new unsigned[n];
Reid Spencer522ca7c2007-02-25 01:56:07 +00001671 }
1672
1673 // Initialize the dividend
Chris Lattner77527f52009-01-21 18:09:24 +00001674 memset(U, 0, (m+n+1)*sizeof(unsigned));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001675 for (unsigned i = 0; i < lhsWords; ++i) {
Reid Spencer867b4062007-02-22 00:58:45 +00001676 uint64_t tmp = (LHS.getNumWords() == 1 ? LHS.VAL : LHS.pVal[i]);
Chris Lattner77527f52009-01-21 18:09:24 +00001677 U[i * 2] = (unsigned)(tmp & mask);
Dan Gohmancff69532009-04-01 18:45:54 +00001678 U[i * 2 + 1] = (unsigned)(tmp >> (sizeof(unsigned)*CHAR_BIT));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001679 }
1680 U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
1681
Reid Spencer522ca7c2007-02-25 01:56:07 +00001682 // Initialize the divisor
Chris Lattner77527f52009-01-21 18:09:24 +00001683 memset(V, 0, (n)*sizeof(unsigned));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001684 for (unsigned i = 0; i < rhsWords; ++i) {
Reid Spencer867b4062007-02-22 00:58:45 +00001685 uint64_t tmp = (RHS.getNumWords() == 1 ? RHS.VAL : RHS.pVal[i]);
Chris Lattner77527f52009-01-21 18:09:24 +00001686 V[i * 2] = (unsigned)(tmp & mask);
Dan Gohmancff69532009-04-01 18:45:54 +00001687 V[i * 2 + 1] = (unsigned)(tmp >> (sizeof(unsigned)*CHAR_BIT));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001688 }
1689
Reid Spencer522ca7c2007-02-25 01:56:07 +00001690 // initialize the quotient and remainder
Chris Lattner77527f52009-01-21 18:09:24 +00001691 memset(Q, 0, (m+n) * sizeof(unsigned));
Reid Spencer522ca7c2007-02-25 01:56:07 +00001692 if (Remainder)
Chris Lattner77527f52009-01-21 18:09:24 +00001693 memset(R, 0, n * sizeof(unsigned));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001694
Eric Christopher820256b2009-08-21 04:06:45 +00001695 // Now, adjust m and n for the Knuth division. n is the number of words in
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001696 // the divisor. m is the number of words by which the dividend exceeds the
Eric Christopher820256b2009-08-21 04:06:45 +00001697 // divisor (i.e. m+n is the length of the dividend). These sizes must not
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001698 // contain any zero words or the Knuth algorithm fails.
1699 for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
1700 n--;
1701 m++;
1702 }
1703 for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
1704 m--;
1705
1706 // If we're left with only a single word for the divisor, Knuth doesn't work
1707 // so we implement the short division algorithm here. This is much simpler
1708 // and faster because we are certain that we can divide a 64-bit quantity
1709 // by a 32-bit quantity at hardware speed and short division is simply a
1710 // series of such operations. This is just like doing short division but we
1711 // are using base 2^32 instead of base 10.
1712 assert(n != 0 && "Divide by zero?");
1713 if (n == 1) {
Chris Lattner77527f52009-01-21 18:09:24 +00001714 unsigned divisor = V[0];
1715 unsigned remainder = 0;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001716 for (int i = m+n-1; i >= 0; i--) {
1717 uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i];
1718 if (partial_dividend == 0) {
1719 Q[i] = 0;
1720 remainder = 0;
1721 } else if (partial_dividend < divisor) {
1722 Q[i] = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001723 remainder = (unsigned)partial_dividend;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001724 } else if (partial_dividend == divisor) {
1725 Q[i] = 1;
1726 remainder = 0;
1727 } else {
Chris Lattner77527f52009-01-21 18:09:24 +00001728 Q[i] = (unsigned)(partial_dividend / divisor);
1729 remainder = (unsigned)(partial_dividend - (Q[i] * divisor));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001730 }
1731 }
1732 if (R)
1733 R[0] = remainder;
1734 } else {
1735 // Now we're ready to invoke the Knuth classical divide algorithm. In this
1736 // case n > 1.
1737 KnuthDiv(U, V, Q, R, m, n);
1738 }
1739
1740 // If the caller wants the quotient
1741 if (Quotient) {
1742 // Set up the Quotient value's memory.
1743 if (Quotient->BitWidth != LHS.BitWidth) {
1744 if (Quotient->isSingleWord())
1745 Quotient->VAL = 0;
1746 else
Reid Spencer7c16cd22007-02-26 23:38:21 +00001747 delete [] Quotient->pVal;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001748 Quotient->BitWidth = LHS.BitWidth;
1749 if (!Quotient->isSingleWord())
Reid Spencer58a6a432007-02-21 08:21:52 +00001750 Quotient->pVal = getClearedMemory(Quotient->getNumWords());
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001751 } else
Jay Foad25a5e4c2010-12-01 08:53:58 +00001752 Quotient->clearAllBits();
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001753
Eric Christopher820256b2009-08-21 04:06:45 +00001754 // The quotient is in Q. Reconstitute the quotient into Quotient's low
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001755 // order words.
Yaron Keren39fc5a62015-03-26 19:45:19 +00001756 // This case is currently dead as all users of divide() handle trivial cases
1757 // earlier.
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001758 if (lhsWords == 1) {
Eric Christopher820256b2009-08-21 04:06:45 +00001759 uint64_t tmp =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001760 uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2));
1761 if (Quotient->isSingleWord())
1762 Quotient->VAL = tmp;
1763 else
1764 Quotient->pVal[0] = tmp;
1765 } else {
1766 assert(!Quotient->isSingleWord() && "Quotient APInt not large enough");
1767 for (unsigned i = 0; i < lhsWords; ++i)
Eric Christopher820256b2009-08-21 04:06:45 +00001768 Quotient->pVal[i] =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001769 uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1770 }
1771 }
1772
1773 // If the caller wants the remainder
1774 if (Remainder) {
1775 // Set up the Remainder value's memory.
1776 if (Remainder->BitWidth != RHS.BitWidth) {
1777 if (Remainder->isSingleWord())
1778 Remainder->VAL = 0;
1779 else
Reid Spencer7c16cd22007-02-26 23:38:21 +00001780 delete [] Remainder->pVal;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001781 Remainder->BitWidth = RHS.BitWidth;
1782 if (!Remainder->isSingleWord())
Reid Spencer58a6a432007-02-21 08:21:52 +00001783 Remainder->pVal = getClearedMemory(Remainder->getNumWords());
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001784 } else
Jay Foad25a5e4c2010-12-01 08:53:58 +00001785 Remainder->clearAllBits();
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001786
1787 // The remainder is in R. Reconstitute the remainder into Remainder's low
1788 // order words.
1789 if (rhsWords == 1) {
Eric Christopher820256b2009-08-21 04:06:45 +00001790 uint64_t tmp =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001791 uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2));
1792 if (Remainder->isSingleWord())
1793 Remainder->VAL = tmp;
1794 else
1795 Remainder->pVal[0] = tmp;
1796 } else {
1797 assert(!Remainder->isSingleWord() && "Remainder APInt not large enough");
1798 for (unsigned i = 0; i < rhsWords; ++i)
Eric Christopher820256b2009-08-21 04:06:45 +00001799 Remainder->pVal[i] =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001800 uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1801 }
1802 }
1803
1804 // Clean up the memory we allocated.
Reid Spencer522ca7c2007-02-25 01:56:07 +00001805 if (U != &SPACE[0]) {
1806 delete [] U;
1807 delete [] V;
1808 delete [] Q;
1809 delete [] R;
1810 }
Reid Spencer100502d2007-02-17 03:16:00 +00001811}
1812
Reid Spencer1d072122007-02-16 22:36:51 +00001813APInt APInt::udiv(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +00001814 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer39867762007-02-17 02:07:07 +00001815
1816 // First, deal with the easy case
1817 if (isSingleWord()) {
1818 assert(RHS.VAL != 0 && "Divide by zero?");
1819 return APInt(BitWidth, VAL / RHS.VAL);
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001820 }
Reid Spencer39867762007-02-17 02:07:07 +00001821
Reid Spencer39867762007-02-17 02:07:07 +00001822 // Get some facts about the LHS and RHS number of bits and words
Chris Lattner77527f52009-01-21 18:09:24 +00001823 unsigned rhsBits = RHS.getActiveBits();
1824 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001825 assert(rhsWords && "Divided by zero???");
Chris Lattner77527f52009-01-21 18:09:24 +00001826 unsigned lhsBits = this->getActiveBits();
1827 unsigned lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001828
1829 // Deal with some degenerate cases
Eric Christopher820256b2009-08-21 04:06:45 +00001830 if (!lhsWords)
Reid Spencer58a6a432007-02-21 08:21:52 +00001831 // 0 / X ===> 0
Eric Christopher820256b2009-08-21 04:06:45 +00001832 return APInt(BitWidth, 0);
Reid Spencer58a6a432007-02-21 08:21:52 +00001833 else if (lhsWords < rhsWords || this->ult(RHS)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001834 // X / Y ===> 0, iff X < Y
Reid Spencer58a6a432007-02-21 08:21:52 +00001835 return APInt(BitWidth, 0);
1836 } else if (*this == RHS) {
1837 // X / X ===> 1
1838 return APInt(BitWidth, 1);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001839 } else if (lhsWords == 1 && rhsWords == 1) {
Reid Spencer39867762007-02-17 02:07:07 +00001840 // All high words are zero, just use native divide
Reid Spencer58a6a432007-02-21 08:21:52 +00001841 return APInt(BitWidth, this->pVal[0] / RHS.pVal[0]);
Reid Spencer39867762007-02-17 02:07:07 +00001842 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001843
1844 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1845 APInt Quotient(1,0); // to hold result.
Craig Topperc10719f2014-04-07 04:17:22 +00001846 divide(*this, lhsWords, RHS, rhsWords, &Quotient, nullptr);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001847 return Quotient;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001848}
1849
Jakub Staszak6605c602013-02-20 00:17:42 +00001850APInt APInt::sdiv(const APInt &RHS) const {
1851 if (isNegative()) {
1852 if (RHS.isNegative())
1853 return (-(*this)).udiv(-RHS);
1854 return -((-(*this)).udiv(RHS));
1855 }
1856 if (RHS.isNegative())
1857 return -(this->udiv(-RHS));
1858 return this->udiv(RHS);
1859}
1860
Reid Spencer1d072122007-02-16 22:36:51 +00001861APInt APInt::urem(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +00001862 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer39867762007-02-17 02:07:07 +00001863 if (isSingleWord()) {
1864 assert(RHS.VAL != 0 && "Remainder by zero?");
1865 return APInt(BitWidth, VAL % RHS.VAL);
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001866 }
Reid Spencer39867762007-02-17 02:07:07 +00001867
Reid Spencer58a6a432007-02-21 08:21:52 +00001868 // Get some facts about the LHS
Chris Lattner77527f52009-01-21 18:09:24 +00001869 unsigned lhsBits = getActiveBits();
1870 unsigned lhsWords = !lhsBits ? 0 : (whichWord(lhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001871
1872 // Get some facts about the RHS
Chris Lattner77527f52009-01-21 18:09:24 +00001873 unsigned rhsBits = RHS.getActiveBits();
1874 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001875 assert(rhsWords && "Performing remainder operation by zero ???");
1876
Reid Spencer39867762007-02-17 02:07:07 +00001877 // Check the degenerate cases
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001878 if (lhsWords == 0) {
Reid Spencer58a6a432007-02-21 08:21:52 +00001879 // 0 % Y ===> 0
1880 return APInt(BitWidth, 0);
1881 } else if (lhsWords < rhsWords || this->ult(RHS)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001882 // X % Y ===> X, iff X < Y
Reid Spencer58a6a432007-02-21 08:21:52 +00001883 return *this;
1884 } else if (*this == RHS) {
Reid Spencer39867762007-02-17 02:07:07 +00001885 // X % X == 0;
Reid Spencer58a6a432007-02-21 08:21:52 +00001886 return APInt(BitWidth, 0);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001887 } else if (lhsWords == 1) {
Reid Spencer39867762007-02-17 02:07:07 +00001888 // All high words are zero, just use native remainder
Reid Spencer58a6a432007-02-21 08:21:52 +00001889 return APInt(BitWidth, pVal[0] % RHS.pVal[0]);
Reid Spencer39867762007-02-17 02:07:07 +00001890 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001891
Reid Spencer4c50b522007-05-13 23:44:59 +00001892 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001893 APInt Remainder(1,0);
Craig Topperc10719f2014-04-07 04:17:22 +00001894 divide(*this, lhsWords, RHS, rhsWords, nullptr, &Remainder);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001895 return Remainder;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001896}
Reid Spencer100502d2007-02-17 03:16:00 +00001897
Jakub Staszak6605c602013-02-20 00:17:42 +00001898APInt APInt::srem(const APInt &RHS) const {
1899 if (isNegative()) {
1900 if (RHS.isNegative())
1901 return -((-(*this)).urem(-RHS));
1902 return -((-(*this)).urem(RHS));
1903 }
1904 if (RHS.isNegative())
1905 return this->urem(-RHS);
1906 return this->urem(RHS);
1907}
1908
Eric Christopher820256b2009-08-21 04:06:45 +00001909void APInt::udivrem(const APInt &LHS, const APInt &RHS,
Reid Spencer4c50b522007-05-13 23:44:59 +00001910 APInt &Quotient, APInt &Remainder) {
David Majnemer7f039202014-12-14 09:41:56 +00001911 assert(LHS.BitWidth == RHS.BitWidth && "Bit widths must be the same");
1912
1913 // First, deal with the easy case
1914 if (LHS.isSingleWord()) {
1915 assert(RHS.VAL != 0 && "Divide by zero?");
1916 uint64_t QuotVal = LHS.VAL / RHS.VAL;
1917 uint64_t RemVal = LHS.VAL % RHS.VAL;
1918 Quotient = APInt(LHS.BitWidth, QuotVal);
1919 Remainder = APInt(LHS.BitWidth, RemVal);
1920 return;
1921 }
1922
Reid Spencer4c50b522007-05-13 23:44:59 +00001923 // Get some size facts about the dividend and divisor
Chris Lattner77527f52009-01-21 18:09:24 +00001924 unsigned lhsBits = LHS.getActiveBits();
1925 unsigned lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
1926 unsigned rhsBits = RHS.getActiveBits();
1927 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer4c50b522007-05-13 23:44:59 +00001928
1929 // Check the degenerate cases
Eric Christopher820256b2009-08-21 04:06:45 +00001930 if (lhsWords == 0) {
Reid Spencer4c50b522007-05-13 23:44:59 +00001931 Quotient = 0; // 0 / Y ===> 0
1932 Remainder = 0; // 0 % Y ===> 0
1933 return;
Eric Christopher820256b2009-08-21 04:06:45 +00001934 }
1935
1936 if (lhsWords < rhsWords || LHS.ult(RHS)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001937 Remainder = LHS; // X % Y ===> X, iff X < Y
1938 Quotient = 0; // X / Y ===> 0, iff X < Y
Reid Spencer4c50b522007-05-13 23:44:59 +00001939 return;
Eric Christopher820256b2009-08-21 04:06:45 +00001940 }
1941
Reid Spencer4c50b522007-05-13 23:44:59 +00001942 if (LHS == RHS) {
1943 Quotient = 1; // X / X ===> 1
1944 Remainder = 0; // X % X ===> 0;
1945 return;
Eric Christopher820256b2009-08-21 04:06:45 +00001946 }
1947
Reid Spencer4c50b522007-05-13 23:44:59 +00001948 if (lhsWords == 1 && rhsWords == 1) {
1949 // There is only one word to consider so use the native versions.
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001950 uint64_t lhsValue = LHS.isSingleWord() ? LHS.VAL : LHS.pVal[0];
1951 uint64_t rhsValue = RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
1952 Quotient = APInt(LHS.getBitWidth(), lhsValue / rhsValue);
1953 Remainder = APInt(LHS.getBitWidth(), lhsValue % rhsValue);
Reid Spencer4c50b522007-05-13 23:44:59 +00001954 return;
1955 }
1956
1957 // Okay, lets do it the long way
1958 divide(LHS, lhsWords, RHS, rhsWords, &Quotient, &Remainder);
1959}
1960
Jakub Staszak6605c602013-02-20 00:17:42 +00001961void APInt::sdivrem(const APInt &LHS, const APInt &RHS,
1962 APInt &Quotient, APInt &Remainder) {
1963 if (LHS.isNegative()) {
1964 if (RHS.isNegative())
1965 APInt::udivrem(-LHS, -RHS, Quotient, Remainder);
1966 else {
1967 APInt::udivrem(-LHS, RHS, Quotient, Remainder);
1968 Quotient = -Quotient;
1969 }
1970 Remainder = -Remainder;
1971 } else if (RHS.isNegative()) {
1972 APInt::udivrem(LHS, -RHS, Quotient, Remainder);
1973 Quotient = -Quotient;
1974 } else {
1975 APInt::udivrem(LHS, RHS, Quotient, Remainder);
1976 }
1977}
1978
Chris Lattner2c819b02010-10-13 23:54:10 +00001979APInt APInt::sadd_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00001980 APInt Res = *this+RHS;
1981 Overflow = isNonNegative() == RHS.isNonNegative() &&
1982 Res.isNonNegative() != isNonNegative();
1983 return Res;
1984}
1985
Chris Lattner698661c2010-10-14 00:05:07 +00001986APInt APInt::uadd_ov(const APInt &RHS, bool &Overflow) const {
1987 APInt Res = *this+RHS;
1988 Overflow = Res.ult(RHS);
1989 return Res;
1990}
1991
Chris Lattner2c819b02010-10-13 23:54:10 +00001992APInt APInt::ssub_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00001993 APInt Res = *this - RHS;
1994 Overflow = isNonNegative() != RHS.isNonNegative() &&
1995 Res.isNonNegative() != isNonNegative();
1996 return Res;
1997}
1998
Chris Lattner698661c2010-10-14 00:05:07 +00001999APInt APInt::usub_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattnerb9681ad2010-10-14 00:30:00 +00002000 APInt Res = *this-RHS;
2001 Overflow = Res.ugt(*this);
Chris Lattner698661c2010-10-14 00:05:07 +00002002 return Res;
2003}
2004
Chris Lattner2c819b02010-10-13 23:54:10 +00002005APInt APInt::sdiv_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00002006 // MININT/-1 --> overflow.
2007 Overflow = isMinSignedValue() && RHS.isAllOnesValue();
2008 return sdiv(RHS);
2009}
2010
Chris Lattner2c819b02010-10-13 23:54:10 +00002011APInt APInt::smul_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00002012 APInt Res = *this * RHS;
2013
2014 if (*this != 0 && RHS != 0)
2015 Overflow = Res.sdiv(RHS) != *this || Res.sdiv(*this) != RHS;
2016 else
2017 Overflow = false;
2018 return Res;
2019}
2020
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00002021APInt APInt::umul_ov(const APInt &RHS, bool &Overflow) const {
2022 APInt Res = *this * RHS;
2023
2024 if (*this != 0 && RHS != 0)
2025 Overflow = Res.udiv(RHS) != *this || Res.udiv(*this) != RHS;
2026 else
2027 Overflow = false;
2028 return Res;
2029}
2030
David Majnemera2521382014-10-13 21:48:30 +00002031APInt APInt::sshl_ov(const APInt &ShAmt, bool &Overflow) const {
2032 Overflow = ShAmt.uge(getBitWidth());
Chris Lattner79bdd882010-10-13 23:46:33 +00002033 if (Overflow)
David Majnemera2521382014-10-13 21:48:30 +00002034 return APInt(BitWidth, 0);
Chris Lattner79bdd882010-10-13 23:46:33 +00002035
2036 if (isNonNegative()) // Don't allow sign change.
David Majnemera2521382014-10-13 21:48:30 +00002037 Overflow = ShAmt.uge(countLeadingZeros());
Chris Lattner79bdd882010-10-13 23:46:33 +00002038 else
David Majnemera2521382014-10-13 21:48:30 +00002039 Overflow = ShAmt.uge(countLeadingOnes());
Chris Lattner79bdd882010-10-13 23:46:33 +00002040
2041 return *this << ShAmt;
2042}
2043
David Majnemera2521382014-10-13 21:48:30 +00002044APInt APInt::ushl_ov(const APInt &ShAmt, bool &Overflow) const {
2045 Overflow = ShAmt.uge(getBitWidth());
2046 if (Overflow)
2047 return APInt(BitWidth, 0);
2048
2049 Overflow = ShAmt.ugt(countLeadingZeros());
2050
2051 return *this << ShAmt;
2052}
2053
Chris Lattner79bdd882010-10-13 23:46:33 +00002054
2055
2056
Benjamin Kramer92d89982010-07-14 22:38:02 +00002057void APInt::fromString(unsigned numbits, StringRef str, uint8_t radix) {
Reid Spencer1ba83352007-02-21 03:55:44 +00002058 // Check our assumptions here
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00002059 assert(!str.empty() && "Invalid string length");
Douglas Gregor663c0682011-09-14 15:54:46 +00002060 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 ||
2061 radix == 36) &&
2062 "Radix should be 2, 8, 10, 16, or 36!");
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00002063
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00002064 StringRef::iterator p = str.begin();
2065 size_t slen = str.size();
2066 bool isNeg = *p == '-';
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00002067 if (*p == '-' || *p == '+') {
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00002068 p++;
2069 slen--;
Eric Christopher43a1dec2009-08-21 04:10:31 +00002070 assert(slen && "String is only a sign, needs a value.");
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00002071 }
Chris Lattnerdad2d092007-05-03 18:15:36 +00002072 assert((slen <= numbits || radix != 2) && "Insufficient bit width");
Chris Lattnerb869a0a2009-04-25 18:34:04 +00002073 assert(((slen-1)*3 <= numbits || radix != 8) && "Insufficient bit width");
2074 assert(((slen-1)*4 <= numbits || radix != 16) && "Insufficient bit width");
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002075 assert((((slen-1)*64)/22 <= numbits || radix != 10) &&
2076 "Insufficient bit width");
Reid Spencer1ba83352007-02-21 03:55:44 +00002077
2078 // Allocate memory
2079 if (!isSingleWord())
2080 pVal = getClearedMemory(getNumWords());
2081
2082 // Figure out if we can shift instead of multiply
Chris Lattner77527f52009-01-21 18:09:24 +00002083 unsigned shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0);
Reid Spencer1ba83352007-02-21 03:55:44 +00002084
2085 // Set up an APInt for the digit to add outside the loop so we don't
2086 // constantly construct/destruct it.
2087 APInt apdigit(getBitWidth(), 0);
2088 APInt apradix(getBitWidth(), radix);
2089
2090 // Enter digit traversal loop
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00002091 for (StringRef::iterator e = str.end(); p != e; ++p) {
Erick Tryzelaardadb15712009-08-21 03:15:28 +00002092 unsigned digit = getDigit(*p, radix);
Erick Tryzelaar60964092009-08-21 06:48:37 +00002093 assert(digit < radix && "Invalid character in digit string");
Reid Spencer1ba83352007-02-21 03:55:44 +00002094
Reid Spencera93c9812007-05-16 19:18:22 +00002095 // Shift or multiply the value by the radix
Chris Lattnerb869a0a2009-04-25 18:34:04 +00002096 if (slen > 1) {
2097 if (shift)
2098 *this <<= shift;
2099 else
2100 *this *= apradix;
2101 }
Reid Spencer1ba83352007-02-21 03:55:44 +00002102
2103 // Add in the digit we just interpreted
Reid Spencer632ebdf2007-02-24 20:19:37 +00002104 if (apdigit.isSingleWord())
2105 apdigit.VAL = digit;
2106 else
2107 apdigit.pVal[0] = digit;
Reid Spencer1ba83352007-02-21 03:55:44 +00002108 *this += apdigit;
Reid Spencer100502d2007-02-17 03:16:00 +00002109 }
Reid Spencerb6b5cc32007-02-25 23:44:53 +00002110 // If its negative, put it in two's complement form
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00002111 if (isNeg) {
Jakub Staszak773be0c2013-03-20 23:56:19 +00002112 --(*this);
Jay Foad25a5e4c2010-12-01 08:53:58 +00002113 this->flipAllBits();
Reid Spencerb6b5cc32007-02-25 23:44:53 +00002114 }
Reid Spencer100502d2007-02-17 03:16:00 +00002115}
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002116
Chris Lattner17f71652008-08-17 07:19:36 +00002117void APInt::toString(SmallVectorImpl<char> &Str, unsigned Radix,
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002118 bool Signed, bool formatAsCLiteral) const {
Douglas Gregor663c0682011-09-14 15:54:46 +00002119 assert((Radix == 10 || Radix == 8 || Radix == 16 || Radix == 2 ||
2120 Radix == 36) &&
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00002121 "Radix should be 2, 8, 10, 16, or 36!");
Eric Christopher820256b2009-08-21 04:06:45 +00002122
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002123 const char *Prefix = "";
2124 if (formatAsCLiteral) {
2125 switch (Radix) {
2126 case 2:
2127 // Binary literals are a non-standard extension added in gcc 4.3:
2128 // http://gcc.gnu.org/onlinedocs/gcc-4.3.0/gcc/Binary-constants.html
2129 Prefix = "0b";
2130 break;
2131 case 8:
2132 Prefix = "0";
2133 break;
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00002134 case 10:
2135 break; // No prefix
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002136 case 16:
2137 Prefix = "0x";
2138 break;
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00002139 default:
2140 llvm_unreachable("Invalid radix!");
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002141 }
2142 }
2143
Chris Lattner17f71652008-08-17 07:19:36 +00002144 // First, check for a zero value and just short circuit the logic below.
2145 if (*this == 0) {
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002146 while (*Prefix) {
2147 Str.push_back(*Prefix);
2148 ++Prefix;
2149 };
Chris Lattner17f71652008-08-17 07:19:36 +00002150 Str.push_back('0');
2151 return;
2152 }
Eric Christopher820256b2009-08-21 04:06:45 +00002153
Douglas Gregor663c0682011-09-14 15:54:46 +00002154 static const char Digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Eric Christopher820256b2009-08-21 04:06:45 +00002155
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002156 if (isSingleWord()) {
Chris Lattner17f71652008-08-17 07:19:36 +00002157 char Buffer[65];
2158 char *BufPtr = Buffer+65;
Eric Christopher820256b2009-08-21 04:06:45 +00002159
Chris Lattner17f71652008-08-17 07:19:36 +00002160 uint64_t N;
Chris Lattnerb91c9032010-08-18 00:33:47 +00002161 if (!Signed) {
Chris Lattner17f71652008-08-17 07:19:36 +00002162 N = getZExtValue();
Chris Lattnerb91c9032010-08-18 00:33:47 +00002163 } else {
2164 int64_t I = getSExtValue();
2165 if (I >= 0) {
2166 N = I;
2167 } else {
2168 Str.push_back('-');
2169 N = -(uint64_t)I;
2170 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002171 }
Eric Christopher820256b2009-08-21 04:06:45 +00002172
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002173 while (*Prefix) {
2174 Str.push_back(*Prefix);
2175 ++Prefix;
2176 };
2177
Chris Lattner17f71652008-08-17 07:19:36 +00002178 while (N) {
2179 *--BufPtr = Digits[N % Radix];
2180 N /= Radix;
2181 }
2182 Str.append(BufPtr, Buffer+65);
2183 return;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002184 }
2185
Chris Lattner17f71652008-08-17 07:19:36 +00002186 APInt Tmp(*this);
Eric Christopher820256b2009-08-21 04:06:45 +00002187
Chris Lattner17f71652008-08-17 07:19:36 +00002188 if (Signed && isNegative()) {
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002189 // They want to print the signed version and it is a negative value
2190 // Flip the bits and add one to turn it into the equivalent positive
2191 // value and put a '-' in the result.
Jay Foad25a5e4c2010-12-01 08:53:58 +00002192 Tmp.flipAllBits();
Jakub Staszak773be0c2013-03-20 23:56:19 +00002193 ++Tmp;
Chris Lattner17f71652008-08-17 07:19:36 +00002194 Str.push_back('-');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002195 }
Eric Christopher820256b2009-08-21 04:06:45 +00002196
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002197 while (*Prefix) {
2198 Str.push_back(*Prefix);
2199 ++Prefix;
2200 };
2201
Chris Lattner17f71652008-08-17 07:19:36 +00002202 // We insert the digits backward, then reverse them to get the right order.
2203 unsigned StartDig = Str.size();
Eric Christopher820256b2009-08-21 04:06:45 +00002204
2205 // For the 2, 8 and 16 bit cases, we can just shift instead of divide
2206 // because the number of bits per digit (1, 3 and 4 respectively) divides
Chris Lattner17f71652008-08-17 07:19:36 +00002207 // equaly. We just shift until the value is zero.
Douglas Gregor663c0682011-09-14 15:54:46 +00002208 if (Radix == 2 || Radix == 8 || Radix == 16) {
Chris Lattner17f71652008-08-17 07:19:36 +00002209 // Just shift tmp right for each digit width until it becomes zero
2210 unsigned ShiftAmt = (Radix == 16 ? 4 : (Radix == 8 ? 3 : 1));
2211 unsigned MaskAmt = Radix - 1;
Eric Christopher820256b2009-08-21 04:06:45 +00002212
Chris Lattner17f71652008-08-17 07:19:36 +00002213 while (Tmp != 0) {
2214 unsigned Digit = unsigned(Tmp.getRawData()[0]) & MaskAmt;
2215 Str.push_back(Digits[Digit]);
2216 Tmp = Tmp.lshr(ShiftAmt);
2217 }
2218 } else {
Douglas Gregor663c0682011-09-14 15:54:46 +00002219 APInt divisor(Radix == 10? 4 : 8, Radix);
Chris Lattner17f71652008-08-17 07:19:36 +00002220 while (Tmp != 0) {
2221 APInt APdigit(1, 0);
2222 APInt tmp2(Tmp.getBitWidth(), 0);
Eric Christopher820256b2009-08-21 04:06:45 +00002223 divide(Tmp, Tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2,
Chris Lattner17f71652008-08-17 07:19:36 +00002224 &APdigit);
Chris Lattner77527f52009-01-21 18:09:24 +00002225 unsigned Digit = (unsigned)APdigit.getZExtValue();
Chris Lattner17f71652008-08-17 07:19:36 +00002226 assert(Digit < Radix && "divide failed");
2227 Str.push_back(Digits[Digit]);
2228 Tmp = tmp2;
2229 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002230 }
Eric Christopher820256b2009-08-21 04:06:45 +00002231
Chris Lattner17f71652008-08-17 07:19:36 +00002232 // Reverse the digits before returning.
2233 std::reverse(Str.begin()+StartDig, Str.end());
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002234}
2235
Pawel Bylica6eeeac72015-04-06 13:31:39 +00002236/// Returns the APInt as a std::string. Note that this is an inefficient method.
2237/// It is better to pass in a SmallVector/SmallString to the methods above.
Chris Lattner17f71652008-08-17 07:19:36 +00002238std::string APInt::toString(unsigned Radix = 10, bool Signed = true) const {
2239 SmallString<40> S;
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002240 toString(S, Radix, Signed, /* formatAsCLiteral = */false);
Daniel Dunbar8b0b1152009-08-19 20:07:03 +00002241 return S.str();
Reid Spencer1ba83352007-02-21 03:55:44 +00002242}
Chris Lattner6b695682007-08-16 15:56:55 +00002243
Matthias Braun8c209aa2017-01-28 02:02:38 +00002244#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Kereneb2a2542016-01-29 20:50:44 +00002245LLVM_DUMP_METHOD void APInt::dump() const {
Chris Lattner17f71652008-08-17 07:19:36 +00002246 SmallString<40> S, U;
2247 this->toStringUnsigned(U);
2248 this->toStringSigned(S);
David Greenef32fcb42010-01-05 01:28:52 +00002249 dbgs() << "APInt(" << BitWidth << "b, "
Davide Italiano5a473d22017-01-31 21:26:18 +00002250 << U << "u " << S << "s)\n";
Chris Lattner17f71652008-08-17 07:19:36 +00002251}
Matthias Braun8c209aa2017-01-28 02:02:38 +00002252#endif
Chris Lattner17f71652008-08-17 07:19:36 +00002253
Chris Lattner0c19df42008-08-23 22:23:09 +00002254void APInt::print(raw_ostream &OS, bool isSigned) const {
Chris Lattner17f71652008-08-17 07:19:36 +00002255 SmallString<40> S;
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002256 this->toString(S, 10, isSigned, /* formatAsCLiteral = */false);
Yaron Keren92e1b622015-03-18 10:17:07 +00002257 OS << S;
Chris Lattner17f71652008-08-17 07:19:36 +00002258}
2259
Chris Lattner6b695682007-08-16 15:56:55 +00002260// This implements a variety of operations on a representation of
2261// arbitrary precision, two's-complement, bignum integer values.
2262
Chris Lattner96cffa62009-08-23 23:11:28 +00002263// Assumed by lowHalf, highHalf, partMSB and partLSB. A fairly safe
2264// and unrestricting assumption.
Benjamin Kramer7000ca32014-10-12 17:56:40 +00002265static_assert(integerPartWidth % 2 == 0, "Part width must be divisible by 2!");
Chris Lattner6b695682007-08-16 15:56:55 +00002266
2267/* Some handy functions local to this file. */
2268namespace {
2269
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002270 /* Returns the integer part with the least significant BITS set.
2271 BITS cannot be zero. */
Dan Gohmanf4bc7822008-04-10 21:11:47 +00002272 static inline integerPart
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002273 lowBitMask(unsigned int bits)
2274 {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002275 assert(bits != 0 && bits <= integerPartWidth);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002276
2277 return ~(integerPart) 0 >> (integerPartWidth - bits);
2278 }
2279
Neil Boothc8b650a2007-10-06 00:43:45 +00002280 /* Returns the value of the lower half of PART. */
Dan Gohmanf4bc7822008-04-10 21:11:47 +00002281 static inline integerPart
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002282 lowHalf(integerPart part)
2283 {
2284 return part & lowBitMask(integerPartWidth / 2);
2285 }
2286
Neil Boothc8b650a2007-10-06 00:43:45 +00002287 /* Returns the value of the upper half of PART. */
Dan Gohmanf4bc7822008-04-10 21:11:47 +00002288 static inline integerPart
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002289 highHalf(integerPart part)
2290 {
2291 return part >> (integerPartWidth / 2);
2292 }
2293
Neil Boothc8b650a2007-10-06 00:43:45 +00002294 /* Returns the bit number of the most significant set bit of a part.
2295 If the input number has no bits set -1U is returned. */
Dan Gohmanf4bc7822008-04-10 21:11:47 +00002296 static unsigned int
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002297 partMSB(integerPart value)
Chris Lattner6b695682007-08-16 15:56:55 +00002298 {
Benjamin Kramerb565f892013-06-01 11:26:39 +00002299 return findLastSet(value, ZB_Max);
Chris Lattner6b695682007-08-16 15:56:55 +00002300 }
2301
Neil Boothc8b650a2007-10-06 00:43:45 +00002302 /* Returns the bit number of the least significant set bit of a
2303 part. If the input number has no bits set -1U is returned. */
Dan Gohmanf4bc7822008-04-10 21:11:47 +00002304 static unsigned int
Chris Lattner6b695682007-08-16 15:56:55 +00002305 partLSB(integerPart value)
2306 {
Benjamin Kramerb565f892013-06-01 11:26:39 +00002307 return findFirstSet(value, ZB_Max);
Chris Lattner6b695682007-08-16 15:56:55 +00002308 }
Alexander Kornienkof00654e2015-06-23 09:49:53 +00002309}
Chris Lattner6b695682007-08-16 15:56:55 +00002310
2311/* Sets the least significant part of a bignum to the input value, and
2312 zeroes out higher parts. */
2313void
2314APInt::tcSet(integerPart *dst, integerPart part, unsigned int parts)
2315{
2316 unsigned int i;
2317
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002318 assert(parts > 0);
Neil Boothb6182162007-10-08 13:47:12 +00002319
Chris Lattner6b695682007-08-16 15:56:55 +00002320 dst[0] = part;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002321 for (i = 1; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002322 dst[i] = 0;
2323}
2324
2325/* Assign one bignum to another. */
2326void
2327APInt::tcAssign(integerPart *dst, const integerPart *src, unsigned int parts)
2328{
2329 unsigned int i;
2330
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002331 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002332 dst[i] = src[i];
2333}
2334
2335/* Returns true if a bignum is zero, false otherwise. */
2336bool
2337APInt::tcIsZero(const integerPart *src, unsigned int parts)
2338{
2339 unsigned int i;
2340
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002341 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002342 if (src[i])
2343 return false;
2344
2345 return true;
2346}
2347
2348/* Extract the given bit of a bignum; returns 0 or 1. */
2349int
2350APInt::tcExtractBit(const integerPart *parts, unsigned int bit)
2351{
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002352 return (parts[bit / integerPartWidth] &
2353 ((integerPart) 1 << bit % integerPartWidth)) != 0;
Chris Lattner6b695682007-08-16 15:56:55 +00002354}
2355
John McCalldcb9a7a2010-02-28 02:51:25 +00002356/* Set the given bit of a bignum. */
Chris Lattner6b695682007-08-16 15:56:55 +00002357void
2358APInt::tcSetBit(integerPart *parts, unsigned int bit)
2359{
2360 parts[bit / integerPartWidth] |= (integerPart) 1 << (bit % integerPartWidth);
2361}
2362
John McCalldcb9a7a2010-02-28 02:51:25 +00002363/* Clears the given bit of a bignum. */
2364void
2365APInt::tcClearBit(integerPart *parts, unsigned int bit)
2366{
2367 parts[bit / integerPartWidth] &=
2368 ~((integerPart) 1 << (bit % integerPartWidth));
2369}
2370
Neil Boothc8b650a2007-10-06 00:43:45 +00002371/* Returns the bit number of the least significant set bit of a
2372 number. If the input number has no bits set -1U is returned. */
Chris Lattner6b695682007-08-16 15:56:55 +00002373unsigned int
2374APInt::tcLSB(const integerPart *parts, unsigned int n)
2375{
2376 unsigned int i, lsb;
2377
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002378 for (i = 0; i < n; i++) {
Chris Lattner6b695682007-08-16 15:56:55 +00002379 if (parts[i] != 0) {
2380 lsb = partLSB(parts[i]);
2381
2382 return lsb + i * integerPartWidth;
2383 }
2384 }
2385
2386 return -1U;
2387}
2388
Neil Boothc8b650a2007-10-06 00:43:45 +00002389/* Returns the bit number of the most significant set bit of a number.
2390 If the input number has no bits set -1U is returned. */
Chris Lattner6b695682007-08-16 15:56:55 +00002391unsigned int
2392APInt::tcMSB(const integerPart *parts, unsigned int n)
2393{
2394 unsigned int msb;
2395
2396 do {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002397 --n;
Chris Lattner6b695682007-08-16 15:56:55 +00002398
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002399 if (parts[n] != 0) {
2400 msb = partMSB(parts[n]);
Chris Lattner6b695682007-08-16 15:56:55 +00002401
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002402 return msb + n * integerPartWidth;
2403 }
Chris Lattner6b695682007-08-16 15:56:55 +00002404 } while (n);
2405
2406 return -1U;
2407}
2408
Neil Boothb6182162007-10-08 13:47:12 +00002409/* Copy the bit vector of width srcBITS from SRC, starting at bit
2410 srcLSB, to DST, of dstCOUNT parts, such that the bit srcLSB becomes
2411 the least significant bit of DST. All high bits above srcBITS in
2412 DST are zero-filled. */
2413void
Evan Chengdb338f32009-05-21 23:47:47 +00002414APInt::tcExtract(integerPart *dst, unsigned int dstCount,const integerPart *src,
Neil Boothb6182162007-10-08 13:47:12 +00002415 unsigned int srcBits, unsigned int srcLSB)
2416{
2417 unsigned int firstSrcPart, dstParts, shift, n;
2418
2419 dstParts = (srcBits + integerPartWidth - 1) / integerPartWidth;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002420 assert(dstParts <= dstCount);
Neil Boothb6182162007-10-08 13:47:12 +00002421
2422 firstSrcPart = srcLSB / integerPartWidth;
2423 tcAssign (dst, src + firstSrcPart, dstParts);
2424
2425 shift = srcLSB % integerPartWidth;
2426 tcShiftRight (dst, dstParts, shift);
2427
2428 /* We now have (dstParts * integerPartWidth - shift) bits from SRC
2429 in DST. If this is less that srcBits, append the rest, else
2430 clear the high bits. */
2431 n = dstParts * integerPartWidth - shift;
2432 if (n < srcBits) {
2433 integerPart mask = lowBitMask (srcBits - n);
2434 dst[dstParts - 1] |= ((src[firstSrcPart + dstParts] & mask)
2435 << n % integerPartWidth);
2436 } else if (n > srcBits) {
Neil Booth7e74b172007-10-12 15:31:31 +00002437 if (srcBits % integerPartWidth)
2438 dst[dstParts - 1] &= lowBitMask (srcBits % integerPartWidth);
Neil Boothb6182162007-10-08 13:47:12 +00002439 }
2440
2441 /* Clear high parts. */
2442 while (dstParts < dstCount)
2443 dst[dstParts++] = 0;
2444}
2445
Chris Lattner6b695682007-08-16 15:56:55 +00002446/* DST += RHS + C where C is zero or one. Returns the carry flag. */
2447integerPart
2448APInt::tcAdd(integerPart *dst, const integerPart *rhs,
2449 integerPart c, unsigned int parts)
2450{
2451 unsigned int i;
2452
2453 assert(c <= 1);
2454
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002455 for (i = 0; i < parts; i++) {
Chris Lattner6b695682007-08-16 15:56:55 +00002456 integerPart l;
2457
2458 l = dst[i];
2459 if (c) {
2460 dst[i] += rhs[i] + 1;
2461 c = (dst[i] <= l);
2462 } else {
2463 dst[i] += rhs[i];
2464 c = (dst[i] < l);
2465 }
2466 }
2467
2468 return c;
2469}
2470
2471/* DST -= RHS + C where C is zero or one. Returns the carry flag. */
2472integerPart
2473APInt::tcSubtract(integerPart *dst, const integerPart *rhs,
2474 integerPart c, unsigned int parts)
2475{
2476 unsigned int i;
2477
2478 assert(c <= 1);
2479
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002480 for (i = 0; i < parts; i++) {
Chris Lattner6b695682007-08-16 15:56:55 +00002481 integerPart l;
2482
2483 l = dst[i];
2484 if (c) {
2485 dst[i] -= rhs[i] + 1;
2486 c = (dst[i] >= l);
2487 } else {
2488 dst[i] -= rhs[i];
2489 c = (dst[i] > l);
2490 }
2491 }
2492
2493 return c;
2494}
2495
2496/* Negate a bignum in-place. */
2497void
2498APInt::tcNegate(integerPart *dst, unsigned int parts)
2499{
2500 tcComplement(dst, parts);
2501 tcIncrement(dst, parts);
2502}
2503
Neil Boothc8b650a2007-10-06 00:43:45 +00002504/* DST += SRC * MULTIPLIER + CARRY if add is true
2505 DST = SRC * MULTIPLIER + CARRY if add is false
Chris Lattner6b695682007-08-16 15:56:55 +00002506
2507 Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC
2508 they must start at the same point, i.e. DST == SRC.
2509
2510 If DSTPARTS == SRCPARTS + 1 no overflow occurs and zero is
2511 returned. Otherwise DST is filled with the least significant
2512 DSTPARTS parts of the result, and if all of the omitted higher
2513 parts were zero return zero, otherwise overflow occurred and
2514 return one. */
2515int
2516APInt::tcMultiplyPart(integerPart *dst, const integerPart *src,
2517 integerPart multiplier, integerPart carry,
2518 unsigned int srcParts, unsigned int dstParts,
2519 bool add)
2520{
2521 unsigned int i, n;
2522
2523 /* Otherwise our writes of DST kill our later reads of SRC. */
2524 assert(dst <= src || dst >= src + srcParts);
2525 assert(dstParts <= srcParts + 1);
2526
2527 /* N loops; minimum of dstParts and srcParts. */
2528 n = dstParts < srcParts ? dstParts: srcParts;
2529
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002530 for (i = 0; i < n; i++) {
Chris Lattner6b695682007-08-16 15:56:55 +00002531 integerPart low, mid, high, srcPart;
2532
2533 /* [ LOW, HIGH ] = MULTIPLIER * SRC[i] + DST[i] + CARRY.
2534
2535 This cannot overflow, because
2536
2537 (n - 1) * (n - 1) + 2 (n - 1) = (n - 1) * (n + 1)
2538
2539 which is less than n^2. */
2540
2541 srcPart = src[i];
2542
2543 if (multiplier == 0 || srcPart == 0) {
2544 low = carry;
2545 high = 0;
2546 } else {
2547 low = lowHalf(srcPart) * lowHalf(multiplier);
2548 high = highHalf(srcPart) * highHalf(multiplier);
2549
2550 mid = lowHalf(srcPart) * highHalf(multiplier);
2551 high += highHalf(mid);
2552 mid <<= integerPartWidth / 2;
2553 if (low + mid < low)
2554 high++;
2555 low += mid;
2556
2557 mid = highHalf(srcPart) * lowHalf(multiplier);
2558 high += highHalf(mid);
2559 mid <<= integerPartWidth / 2;
2560 if (low + mid < low)
2561 high++;
2562 low += mid;
2563
2564 /* Now add carry. */
2565 if (low + carry < low)
2566 high++;
2567 low += carry;
2568 }
2569
2570 if (add) {
2571 /* And now DST[i], and store the new low part there. */
2572 if (low + dst[i] < low)
2573 high++;
2574 dst[i] += low;
2575 } else
2576 dst[i] = low;
2577
2578 carry = high;
2579 }
2580
2581 if (i < dstParts) {
2582 /* Full multiplication, there is no overflow. */
2583 assert(i + 1 == dstParts);
2584 dst[i] = carry;
2585 return 0;
2586 } else {
2587 /* We overflowed if there is carry. */
2588 if (carry)
2589 return 1;
2590
2591 /* We would overflow if any significant unwritten parts would be
2592 non-zero. This is true if any remaining src parts are non-zero
2593 and the multiplier is non-zero. */
2594 if (multiplier)
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002595 for (; i < srcParts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002596 if (src[i])
2597 return 1;
2598
2599 /* We fitted in the narrow destination. */
2600 return 0;
2601 }
2602}
2603
2604/* DST = LHS * RHS, where DST has the same width as the operands and
2605 is filled with the least significant parts of the result. Returns
2606 one if overflow occurred, otherwise zero. DST must be disjoint
2607 from both operands. */
2608int
2609APInt::tcMultiply(integerPart *dst, const integerPart *lhs,
2610 const integerPart *rhs, unsigned int parts)
2611{
2612 unsigned int i;
2613 int overflow;
2614
2615 assert(dst != lhs && dst != rhs);
2616
2617 overflow = 0;
2618 tcSet(dst, 0, parts);
2619
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002620 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002621 overflow |= tcMultiplyPart(&dst[i], lhs, rhs[i], 0, parts,
2622 parts - i, true);
2623
2624 return overflow;
2625}
2626
Neil Booth0ea72a92007-10-06 00:24:48 +00002627/* DST = LHS * RHS, where DST has width the sum of the widths of the
2628 operands. No overflow occurs. DST must be disjoint from both
2629 operands. Returns the number of parts required to hold the
2630 result. */
2631unsigned int
Chris Lattner6b695682007-08-16 15:56:55 +00002632APInt::tcFullMultiply(integerPart *dst, const integerPart *lhs,
Neil Booth0ea72a92007-10-06 00:24:48 +00002633 const integerPart *rhs, unsigned int lhsParts,
2634 unsigned int rhsParts)
Chris Lattner6b695682007-08-16 15:56:55 +00002635{
Neil Booth0ea72a92007-10-06 00:24:48 +00002636 /* Put the narrower number on the LHS for less loops below. */
2637 if (lhsParts > rhsParts) {
2638 return tcFullMultiply (dst, rhs, lhs, rhsParts, lhsParts);
2639 } else {
2640 unsigned int n;
Chris Lattner6b695682007-08-16 15:56:55 +00002641
Neil Booth0ea72a92007-10-06 00:24:48 +00002642 assert(dst != lhs && dst != rhs);
Chris Lattner6b695682007-08-16 15:56:55 +00002643
Neil Booth0ea72a92007-10-06 00:24:48 +00002644 tcSet(dst, 0, rhsParts);
Chris Lattner6b695682007-08-16 15:56:55 +00002645
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002646 for (n = 0; n < lhsParts; n++)
Neil Booth0ea72a92007-10-06 00:24:48 +00002647 tcMultiplyPart(&dst[n], rhs, lhs[n], 0, rhsParts, rhsParts + 1, true);
Chris Lattner6b695682007-08-16 15:56:55 +00002648
Neil Booth0ea72a92007-10-06 00:24:48 +00002649 n = lhsParts + rhsParts;
2650
2651 return n - (dst[n - 1] == 0);
2652 }
Chris Lattner6b695682007-08-16 15:56:55 +00002653}
2654
2655/* If RHS is zero LHS and REMAINDER are left unchanged, return one.
2656 Otherwise set LHS to LHS / RHS with the fractional part discarded,
2657 set REMAINDER to the remainder, return zero. i.e.
2658
2659 OLD_LHS = RHS * LHS + REMAINDER
2660
2661 SCRATCH is a bignum of the same size as the operands and result for
2662 use by the routine; its contents need not be initialized and are
2663 destroyed. LHS, REMAINDER and SCRATCH must be distinct.
2664*/
2665int
2666APInt::tcDivide(integerPart *lhs, const integerPart *rhs,
2667 integerPart *remainder, integerPart *srhs,
2668 unsigned int parts)
2669{
2670 unsigned int n, shiftCount;
2671 integerPart mask;
2672
2673 assert(lhs != remainder && lhs != srhs && remainder != srhs);
2674
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002675 shiftCount = tcMSB(rhs, parts) + 1;
2676 if (shiftCount == 0)
Chris Lattner6b695682007-08-16 15:56:55 +00002677 return true;
2678
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002679 shiftCount = parts * integerPartWidth - shiftCount;
Chris Lattner6b695682007-08-16 15:56:55 +00002680 n = shiftCount / integerPartWidth;
2681 mask = (integerPart) 1 << (shiftCount % integerPartWidth);
2682
2683 tcAssign(srhs, rhs, parts);
2684 tcShiftLeft(srhs, parts, shiftCount);
2685 tcAssign(remainder, lhs, parts);
2686 tcSet(lhs, 0, parts);
2687
2688 /* Loop, subtracting SRHS if REMAINDER is greater and adding that to
2689 the total. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002690 for (;;) {
Chris Lattner6b695682007-08-16 15:56:55 +00002691 int compare;
2692
2693 compare = tcCompare(remainder, srhs, parts);
2694 if (compare >= 0) {
2695 tcSubtract(remainder, srhs, 0, parts);
2696 lhs[n] |= mask;
2697 }
2698
2699 if (shiftCount == 0)
2700 break;
2701 shiftCount--;
2702 tcShiftRight(srhs, parts, 1);
Richard Trieu7a083812016-02-18 22:09:30 +00002703 if ((mask >>= 1) == 0) {
2704 mask = (integerPart) 1 << (integerPartWidth - 1);
2705 n--;
2706 }
Chris Lattner6b695682007-08-16 15:56:55 +00002707 }
2708
2709 return false;
2710}
2711
2712/* Shift a bignum left COUNT bits in-place. Shifted in bits are zero.
2713 There are no restrictions on COUNT. */
2714void
2715APInt::tcShiftLeft(integerPart *dst, unsigned int parts, unsigned int count)
2716{
Neil Boothb6182162007-10-08 13:47:12 +00002717 if (count) {
2718 unsigned int jump, shift;
Chris Lattner6b695682007-08-16 15:56:55 +00002719
Neil Boothb6182162007-10-08 13:47:12 +00002720 /* Jump is the inter-part jump; shift is is intra-part shift. */
2721 jump = count / integerPartWidth;
2722 shift = count % integerPartWidth;
Chris Lattner6b695682007-08-16 15:56:55 +00002723
Neil Boothb6182162007-10-08 13:47:12 +00002724 while (parts > jump) {
2725 integerPart part;
Chris Lattner6b695682007-08-16 15:56:55 +00002726
Neil Boothb6182162007-10-08 13:47:12 +00002727 parts--;
Chris Lattner6b695682007-08-16 15:56:55 +00002728
Neil Boothb6182162007-10-08 13:47:12 +00002729 /* dst[i] comes from the two parts src[i - jump] and, if we have
2730 an intra-part shift, src[i - jump - 1]. */
2731 part = dst[parts - jump];
2732 if (shift) {
2733 part <<= shift;
Chris Lattner6b695682007-08-16 15:56:55 +00002734 if (parts >= jump + 1)
2735 part |= dst[parts - jump - 1] >> (integerPartWidth - shift);
2736 }
2737
Neil Boothb6182162007-10-08 13:47:12 +00002738 dst[parts] = part;
2739 }
Chris Lattner6b695682007-08-16 15:56:55 +00002740
Neil Boothb6182162007-10-08 13:47:12 +00002741 while (parts > 0)
2742 dst[--parts] = 0;
2743 }
Chris Lattner6b695682007-08-16 15:56:55 +00002744}
2745
2746/* Shift a bignum right COUNT bits in-place. Shifted in bits are
2747 zero. There are no restrictions on COUNT. */
2748void
2749APInt::tcShiftRight(integerPart *dst, unsigned int parts, unsigned int count)
2750{
Neil Boothb6182162007-10-08 13:47:12 +00002751 if (count) {
2752 unsigned int i, jump, shift;
Chris Lattner6b695682007-08-16 15:56:55 +00002753
Neil Boothb6182162007-10-08 13:47:12 +00002754 /* Jump is the inter-part jump; shift is is intra-part shift. */
2755 jump = count / integerPartWidth;
2756 shift = count % integerPartWidth;
Chris Lattner6b695682007-08-16 15:56:55 +00002757
Neil Boothb6182162007-10-08 13:47:12 +00002758 /* Perform the shift. This leaves the most significant COUNT bits
2759 of the result at zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002760 for (i = 0; i < parts; i++) {
Neil Boothb6182162007-10-08 13:47:12 +00002761 integerPart part;
Chris Lattner6b695682007-08-16 15:56:55 +00002762
Neil Boothb6182162007-10-08 13:47:12 +00002763 if (i + jump >= parts) {
2764 part = 0;
2765 } else {
2766 part = dst[i + jump];
2767 if (shift) {
2768 part >>= shift;
2769 if (i + jump + 1 < parts)
2770 part |= dst[i + jump + 1] << (integerPartWidth - shift);
2771 }
Chris Lattner6b695682007-08-16 15:56:55 +00002772 }
Chris Lattner6b695682007-08-16 15:56:55 +00002773
Neil Boothb6182162007-10-08 13:47:12 +00002774 dst[i] = part;
2775 }
Chris Lattner6b695682007-08-16 15:56:55 +00002776 }
2777}
2778
2779/* Bitwise and of two bignums. */
2780void
2781APInt::tcAnd(integerPart *dst, const integerPart *rhs, unsigned int parts)
2782{
2783 unsigned int i;
2784
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002785 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002786 dst[i] &= rhs[i];
2787}
2788
2789/* Bitwise inclusive or of two bignums. */
2790void
2791APInt::tcOr(integerPart *dst, const integerPart *rhs, unsigned int parts)
2792{
2793 unsigned int i;
2794
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002795 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002796 dst[i] |= rhs[i];
2797}
2798
2799/* Bitwise exclusive or of two bignums. */
2800void
2801APInt::tcXor(integerPart *dst, const integerPart *rhs, unsigned int parts)
2802{
2803 unsigned int i;
2804
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002805 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002806 dst[i] ^= rhs[i];
2807}
2808
2809/* Complement a bignum in-place. */
2810void
2811APInt::tcComplement(integerPart *dst, unsigned int parts)
2812{
2813 unsigned int i;
2814
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002815 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002816 dst[i] = ~dst[i];
2817}
2818
2819/* Comparison (unsigned) of two bignums. */
2820int
2821APInt::tcCompare(const integerPart *lhs, const integerPart *rhs,
2822 unsigned int parts)
2823{
2824 while (parts) {
2825 parts--;
2826 if (lhs[parts] == rhs[parts])
2827 continue;
2828
2829 if (lhs[parts] > rhs[parts])
2830 return 1;
2831 else
2832 return -1;
2833 }
2834
2835 return 0;
2836}
2837
2838/* Increment a bignum in-place, return the carry flag. */
2839integerPart
2840APInt::tcIncrement(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 if (++dst[i] != 0)
2846 break;
2847
2848 return i == parts;
2849}
2850
Michael Gottesman9d406f42013-05-28 19:50:20 +00002851/* Decrement a bignum in-place, return the borrow flag. */
2852integerPart
2853APInt::tcDecrement(integerPart *dst, unsigned int parts) {
2854 for (unsigned int i = 0; i < parts; i++) {
2855 // If the current word is non-zero, then the decrement has no effect on the
2856 // higher-order words of the integer and no borrow can occur. Exit early.
2857 if (dst[i]--)
2858 return 0;
2859 }
2860 // If every word was zero, then there is a borrow.
2861 return 1;
2862}
2863
2864
Chris Lattner6b695682007-08-16 15:56:55 +00002865/* Set the least significant BITS bits of a bignum, clear the
2866 rest. */
2867void
2868APInt::tcSetLeastSignificantBits(integerPart *dst, unsigned int parts,
2869 unsigned int bits)
2870{
2871 unsigned int i;
2872
2873 i = 0;
2874 while (bits > integerPartWidth) {
2875 dst[i++] = ~(integerPart) 0;
2876 bits -= integerPartWidth;
2877 }
2878
2879 if (bits)
2880 dst[i++] = ~(integerPart) 0 >> (integerPartWidth - bits);
2881
2882 while (i < parts)
2883 dst[i++] = 0;
2884}