blob: 71f5e11d5d98aa440bd7d813f5e19e6e304c6868 [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;
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +000066
Douglas Gregore4e20f42011-09-20 18:11:52 +000067 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) {
Craig Topper0085ffb2017-03-20 01:29:52 +000079 VAL = 0;
Chris Lattner1ac3e252008-08-20 17:02:31 +000080 pVal = getClearedMemory(getNumWords());
81 pVal[0] = val;
Eric Christopher820256b2009-08-21 04:06:45 +000082 if (isSigned && int64_t(val) < 0)
Chris Lattner1ac3e252008-08-20 17:02:31 +000083 for (unsigned i = 1; i < getNumWords(); ++i)
84 pVal[i] = -1ULL;
Craig Topperf78a6f02017-03-01 21:06:18 +000085 clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +000086}
87
Chris Lattnerd57b7602008-10-11 22:07:19 +000088void APInt::initSlowCase(const APInt& that) {
Craig Topper0085ffb2017-03-20 01:29:52 +000089 VAL = 0;
Chris Lattnerd57b7602008-10-11 22:07:19 +000090 pVal = getMemory(getNumWords());
91 memcpy(pVal, that.pVal, getNumWords() * APINT_WORD_SIZE);
92}
93
Jeffrey Yasskin7a162882011-07-18 21:45:40 +000094void APInt::initFromArray(ArrayRef<uint64_t> bigVal) {
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +000095 assert(BitWidth && "Bitwidth too small");
Jeffrey Yasskin7a162882011-07-18 21:45:40 +000096 assert(bigVal.data() && "Null pointer detected!");
Zhou Shengdac63782007-02-06 03:00:16 +000097 if (isSingleWord())
Reid Spencerdf6cf5a2007-02-24 10:01:42 +000098 VAL = bigVal[0];
Zhou Shengdac63782007-02-06 03:00:16 +000099 else {
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000100 // Get memory, cleared to 0
Craig Topper0085ffb2017-03-20 01:29:52 +0000101 VAL = 0;
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000102 pVal = getClearedMemory(getNumWords());
103 // Calculate the number of words to copy
Jeffrey Yasskin7a162882011-07-18 21:45:40 +0000104 unsigned words = std::min<unsigned>(bigVal.size(), getNumWords());
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000105 // Copy the words from bigVal to pVal
Jeffrey Yasskin7a162882011-07-18 21:45:40 +0000106 memcpy(pVal, bigVal.data(), words * APINT_WORD_SIZE);
Zhou Shengdac63782007-02-06 03:00:16 +0000107 }
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000108 // Make sure unused high bits are cleared
109 clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000110}
111
Jeffrey Yasskin7a162882011-07-18 21:45:40 +0000112APInt::APInt(unsigned numBits, ArrayRef<uint64_t> bigVal)
Craig Topper0085ffb2017-03-20 01:29:52 +0000113 : BitWidth(numBits) {
Jeffrey Yasskin7a162882011-07-18 21:45:40 +0000114 initFromArray(bigVal);
115}
116
117APInt::APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[])
Craig Topper0085ffb2017-03-20 01:29:52 +0000118 : BitWidth(numBits) {
Jeffrey Yasskin7a162882011-07-18 21:45:40 +0000119 initFromArray(makeArrayRef(bigVal, numWords));
120}
121
Benjamin Kramer92d89982010-07-14 22:38:02 +0000122APInt::APInt(unsigned numbits, StringRef Str, uint8_t radix)
Reid Spencer1ba83352007-02-21 03:55:44 +0000123 : BitWidth(numbits), VAL(0) {
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000124 assert(BitWidth && "Bitwidth too small");
Daniel Dunbar3a1efd112009-08-13 02:33:34 +0000125 fromString(numbits, Str, radix);
Zhou Sheng3e8022d2007-02-07 06:14:53 +0000126}
127
Chris Lattner1ac3e252008-08-20 17:02:31 +0000128APInt& APInt::AssignSlowCase(const APInt& RHS) {
Reid Spencer7c16cd22007-02-26 23:38:21 +0000129 // Don't do anything for X = X
130 if (this == &RHS)
131 return *this;
132
Reid Spencer7c16cd22007-02-26 23:38:21 +0000133 if (BitWidth == RHS.getBitWidth()) {
Chris Lattner1ac3e252008-08-20 17:02:31 +0000134 // assume same bit-width single-word case is already handled
135 assert(!isSingleWord());
136 memcpy(pVal, RHS.pVal, getNumWords() * APINT_WORD_SIZE);
Reid Spencer7c16cd22007-02-26 23:38:21 +0000137 return *this;
138 }
139
Chris Lattner1ac3e252008-08-20 17:02:31 +0000140 if (isSingleWord()) {
141 // assume case where both are single words is already handled
142 assert(!RHS.isSingleWord());
143 VAL = 0;
144 pVal = getMemory(RHS.getNumWords());
145 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
Eric Christopher820256b2009-08-21 04:06:45 +0000146 } else if (getNumWords() == RHS.getNumWords())
Reid Spencer7c16cd22007-02-26 23:38:21 +0000147 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
148 else if (RHS.isSingleWord()) {
149 delete [] pVal;
Reid Spencera856b6e2007-02-18 18:38:44 +0000150 VAL = RHS.VAL;
Reid Spencer7c16cd22007-02-26 23:38:21 +0000151 } else {
152 delete [] pVal;
153 pVal = getMemory(RHS.getNumWords());
154 memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE);
155 }
156 BitWidth = RHS.BitWidth;
157 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000158}
159
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000160/// This method 'profiles' an APInt for use with FoldingSet.
Ted Kremenek5c75d542008-01-19 04:23:33 +0000161void APInt::Profile(FoldingSetNodeID& ID) const {
Ted Kremenek901540f2008-02-19 20:50:41 +0000162 ID.AddInteger(BitWidth);
Eric Christopher820256b2009-08-21 04:06:45 +0000163
Ted Kremenek5c75d542008-01-19 04:23:33 +0000164 if (isSingleWord()) {
165 ID.AddInteger(VAL);
166 return;
167 }
168
Chris Lattner77527f52009-01-21 18:09:24 +0000169 unsigned NumWords = getNumWords();
Ted Kremenek5c75d542008-01-19 04:23:33 +0000170 for (unsigned i = 0; i < NumWords; ++i)
171 ID.AddInteger(pVal[i]);
172}
173
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000174/// This function adds a single "digit" integer, y, to the multiple
Reid Spencera856b6e2007-02-18 18:38:44 +0000175/// "digit" integer array, x[]. x[] is modified to reflect the addition and
176/// 1 is returned if there is a carry out, otherwise 0 is returned.
Reid Spencer100502d2007-02-17 03:16:00 +0000177/// @returns the carry of the addition.
Chris Lattner77527f52009-01-21 18:09:24 +0000178static bool add_1(uint64_t dest[], uint64_t x[], unsigned len, uint64_t y) {
179 for (unsigned i = 0; i < len; ++i) {
Reid Spenceree0a6852007-02-18 06:39:42 +0000180 dest[i] = y + x[i];
181 if (dest[i] < y)
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000182 y = 1; // Carry one to next digit.
Reid Spenceree0a6852007-02-18 06:39:42 +0000183 else {
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000184 y = 0; // No need to carry so exit early
Reid Spenceree0a6852007-02-18 06:39:42 +0000185 break;
186 }
Reid Spencer100502d2007-02-17 03:16:00 +0000187 }
Reid Spenceree0a6852007-02-18 06:39:42 +0000188 return y;
Reid Spencer100502d2007-02-17 03:16:00 +0000189}
190
Zhou Shengdac63782007-02-06 03:00:16 +0000191/// @brief Prefix increment operator. Increments the APInt by one.
192APInt& APInt::operator++() {
Eric Christopher820256b2009-08-21 04:06:45 +0000193 if (isSingleWord())
Reid Spencer1d072122007-02-16 22:36:51 +0000194 ++VAL;
Zhou Shengdac63782007-02-06 03:00:16 +0000195 else
Zhou Sheng3e8022d2007-02-07 06:14:53 +0000196 add_1(pVal, pVal, getNumWords(), 1);
Reid Spencera41e93b2007-02-25 19:32:03 +0000197 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000198}
199
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000200/// This function subtracts a single "digit" (64-bit word), y, from
Eric Christopher820256b2009-08-21 04:06:45 +0000201/// the multi-digit integer array, x[], propagating the borrowed 1 value until
Joerg Sonnenbergerd7baada2017-01-05 17:59:22 +0000202/// no further borrowing is needed or it runs out of "digits" in x. The result
Reid Spencera856b6e2007-02-18 18:38:44 +0000203/// is 1 if "borrowing" exhausted the digits in x, or 0 if x was not exhausted.
204/// In other words, if y > x then this function returns 1, otherwise 0.
Reid Spencera41e93b2007-02-25 19:32:03 +0000205/// @returns the borrow out of the subtraction
Chris Lattner77527f52009-01-21 18:09:24 +0000206static bool sub_1(uint64_t x[], unsigned len, uint64_t y) {
207 for (unsigned i = 0; i < len; ++i) {
Reid Spencer100502d2007-02-17 03:16:00 +0000208 uint64_t X = x[i];
Reid Spenceree0a6852007-02-18 06:39:42 +0000209 x[i] -= y;
Eric Christopher820256b2009-08-21 04:06:45 +0000210 if (y > X)
Reid Spencera856b6e2007-02-18 18:38:44 +0000211 y = 1; // We have to "borrow 1" from next "digit"
Reid Spencer100502d2007-02-17 03:16:00 +0000212 else {
Reid Spencera856b6e2007-02-18 18:38:44 +0000213 y = 0; // No need to borrow
214 break; // Remaining digits are unchanged so exit early
Reid Spencer100502d2007-02-17 03:16:00 +0000215 }
216 }
Reid Spencera41e93b2007-02-25 19:32:03 +0000217 return bool(y);
Reid Spencer100502d2007-02-17 03:16:00 +0000218}
219
Zhou Shengdac63782007-02-06 03:00:16 +0000220/// @brief Prefix decrement operator. Decrements the APInt by one.
221APInt& APInt::operator--() {
Eric Christopher820256b2009-08-21 04:06:45 +0000222 if (isSingleWord())
Reid Spencera856b6e2007-02-18 18:38:44 +0000223 --VAL;
Zhou Shengdac63782007-02-06 03:00:16 +0000224 else
Zhou Sheng3e8022d2007-02-07 06:14:53 +0000225 sub_1(pVal, getNumWords(), 1);
Reid Spencera41e93b2007-02-25 19:32:03 +0000226 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000227}
228
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000229/// This function adds the integer array x to the integer array Y and
Eric Christopher820256b2009-08-21 04:06:45 +0000230/// places the result in dest.
Reid Spencera41e93b2007-02-25 19:32:03 +0000231/// @returns the carry out from the addition
232/// @brief General addition of 64-bit integer arrays
Eric Christopher820256b2009-08-21 04:06:45 +0000233static bool add(uint64_t *dest, const uint64_t *x, const uint64_t *y,
Chris Lattner77527f52009-01-21 18:09:24 +0000234 unsigned len) {
Reid Spencera5e0d202007-02-24 03:58:46 +0000235 bool carry = false;
Chris Lattner77527f52009-01-21 18:09:24 +0000236 for (unsigned i = 0; i< len; ++i) {
Reid Spencercb292e42007-02-23 01:57:13 +0000237 uint64_t limit = std::min(x[i],y[i]); // must come first in case dest == x
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000238 dest[i] = x[i] + y[i] + carry;
Reid Spencerdb2abec2007-02-21 05:44:56 +0000239 carry = dest[i] < limit || (carry && dest[i] == limit);
Reid Spencer100502d2007-02-17 03:16:00 +0000240 }
241 return carry;
242}
243
Reid Spencera41e93b2007-02-25 19:32:03 +0000244/// Adds the RHS APint to this APInt.
245/// @returns this, after addition of RHS.
Eric Christopher820256b2009-08-21 04:06:45 +0000246/// @brief Addition assignment operator.
Zhou Shengdac63782007-02-06 03:00:16 +0000247APInt& APInt::operator+=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000248 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Eric Christopher820256b2009-08-21 04:06:45 +0000249 if (isSingleWord())
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000250 VAL += RHS.VAL;
Zhou Shengdac63782007-02-06 03:00:16 +0000251 else {
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000252 add(pVal, pVal, RHS.pVal, getNumWords());
Zhou Shengdac63782007-02-06 03:00:16 +0000253 }
Reid Spencera41e93b2007-02-25 19:32:03 +0000254 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000255}
256
Pete Cooperfea21392016-07-22 20:55:46 +0000257APInt& APInt::operator+=(uint64_t RHS) {
258 if (isSingleWord())
259 VAL += RHS;
260 else
261 add_1(pVal, pVal, getNumWords(), RHS);
262 return clearUnusedBits();
263}
264
Eric Christopher820256b2009-08-21 04:06:45 +0000265/// Subtracts the integer array y from the integer array x
Reid Spencera41e93b2007-02-25 19:32:03 +0000266/// @returns returns the borrow out.
267/// @brief Generalized subtraction of 64-bit integer arrays.
Eric Christopher820256b2009-08-21 04:06:45 +0000268static bool sub(uint64_t *dest, const uint64_t *x, const uint64_t *y,
Chris Lattner77527f52009-01-21 18:09:24 +0000269 unsigned len) {
Reid Spencer1ba83352007-02-21 03:55:44 +0000270 bool borrow = false;
Chris Lattner77527f52009-01-21 18:09:24 +0000271 for (unsigned i = 0; i < len; ++i) {
Reid Spencer1ba83352007-02-21 03:55:44 +0000272 uint64_t x_tmp = borrow ? x[i] - 1 : x[i];
273 borrow = y[i] > x_tmp || (borrow && x[i] == 0);
274 dest[i] = x_tmp - y[i];
Reid Spencer100502d2007-02-17 03:16:00 +0000275 }
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000276 return borrow;
Reid Spencer100502d2007-02-17 03:16:00 +0000277}
278
Reid Spencera41e93b2007-02-25 19:32:03 +0000279/// Subtracts the RHS APInt from this APInt
280/// @returns this, after subtraction
Eric Christopher820256b2009-08-21 04:06:45 +0000281/// @brief Subtraction assignment operator.
Zhou Shengdac63782007-02-06 03:00:16 +0000282APInt& APInt::operator-=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000283 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Eric Christopher820256b2009-08-21 04:06:45 +0000284 if (isSingleWord())
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000285 VAL -= RHS.VAL;
286 else
287 sub(pVal, pVal, RHS.pVal, getNumWords());
Reid Spencera41e93b2007-02-25 19:32:03 +0000288 return clearUnusedBits();
Zhou Shengdac63782007-02-06 03:00:16 +0000289}
290
Pete Cooperfea21392016-07-22 20:55:46 +0000291APInt& APInt::operator-=(uint64_t RHS) {
292 if (isSingleWord())
293 VAL -= RHS;
294 else
295 sub_1(pVal, getNumWords(), RHS);
296 return clearUnusedBits();
297}
298
Dan Gohman4a618822010-02-10 16:03:48 +0000299/// Multiplies an integer array, x, by a uint64_t integer and places the result
Eric Christopher820256b2009-08-21 04:06:45 +0000300/// into dest.
Reid Spencera41e93b2007-02-25 19:32:03 +0000301/// @returns the carry out of the multiplication.
302/// @brief Multiply a multi-digit APInt by a single digit (64-bit) integer.
Chris Lattner77527f52009-01-21 18:09:24 +0000303static uint64_t mul_1(uint64_t dest[], uint64_t x[], unsigned len, uint64_t y) {
Reid Spencerdf6cf5a2007-02-24 10:01:42 +0000304 // Split y into high 32-bit part (hy) and low 32-bit part (ly)
Reid Spencer100502d2007-02-17 03:16:00 +0000305 uint64_t ly = y & 0xffffffffULL, hy = y >> 32;
Reid Spencera41e93b2007-02-25 19:32:03 +0000306 uint64_t carry = 0;
307
308 // For each digit of x.
Chris Lattner77527f52009-01-21 18:09:24 +0000309 for (unsigned i = 0; i < len; ++i) {
Reid Spencera41e93b2007-02-25 19:32:03 +0000310 // Split x into high and low words
311 uint64_t lx = x[i] & 0xffffffffULL;
312 uint64_t hx = x[i] >> 32;
313 // hasCarry - A flag to indicate if there is a carry to the next digit.
Reid Spencer100502d2007-02-17 03:16:00 +0000314 // hasCarry == 0, no carry
315 // hasCarry == 1, has carry
316 // hasCarry == 2, no carry and the calculation result == 0.
317 uint8_t hasCarry = 0;
318 dest[i] = carry + lx * ly;
319 // Determine if the add above introduces carry.
320 hasCarry = (dest[i] < carry) ? 1 : 0;
321 carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0);
Eric Christopher820256b2009-08-21 04:06:45 +0000322 // The upper limit of carry can be (2^32 - 1)(2^32 - 1) +
Reid Spencer100502d2007-02-17 03:16:00 +0000323 // (2^32 - 1) + 2^32 = 2^64.
324 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
325
326 carry += (lx * hy) & 0xffffffffULL;
327 dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL);
Eric Christopher820256b2009-08-21 04:06:45 +0000328 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) +
Reid Spencer100502d2007-02-17 03:16:00 +0000329 (carry >> 32) + ((lx * hy) >> 32) + hx * hy;
330 }
Reid Spencer100502d2007-02-17 03:16:00 +0000331 return carry;
332}
333
Eric Christopher820256b2009-08-21 04:06:45 +0000334/// Multiplies integer array x by integer array y and stores the result into
Reid Spencera41e93b2007-02-25 19:32:03 +0000335/// the integer array dest. Note that dest's size must be >= xlen + ylen.
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000336/// @brief Generalized multiplication of integer arrays.
Chris Lattner77527f52009-01-21 18:09:24 +0000337static void mul(uint64_t dest[], uint64_t x[], unsigned xlen, uint64_t y[],
338 unsigned ylen) {
Reid Spencer100502d2007-02-17 03:16:00 +0000339 dest[xlen] = mul_1(dest, x, xlen, y[0]);
Chris Lattner77527f52009-01-21 18:09:24 +0000340 for (unsigned i = 1; i < ylen; ++i) {
Reid Spencer100502d2007-02-17 03:16:00 +0000341 uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32;
Reid Spencer58a6a432007-02-21 08:21:52 +0000342 uint64_t carry = 0, lx = 0, hx = 0;
Chris Lattner77527f52009-01-21 18:09:24 +0000343 for (unsigned j = 0; j < xlen; ++j) {
Reid Spencer100502d2007-02-17 03:16:00 +0000344 lx = x[j] & 0xffffffffULL;
345 hx = x[j] >> 32;
346 // hasCarry - A flag to indicate if has carry.
347 // hasCarry == 0, no carry
348 // hasCarry == 1, has carry
349 // hasCarry == 2, no carry and the calculation result == 0.
350 uint8_t hasCarry = 0;
351 uint64_t resul = carry + lx * ly;
352 hasCarry = (resul < carry) ? 1 : 0;
353 carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32);
354 hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0);
355
356 carry += (lx * hy) & 0xffffffffULL;
357 resul = (carry << 32) | (resul & 0xffffffffULL);
358 dest[i+j] += resul;
359 carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+
Eric Christopher820256b2009-08-21 04:06:45 +0000360 (carry >> 32) + (dest[i+j] < resul ? 1 : 0) +
Reid Spencer100502d2007-02-17 03:16:00 +0000361 ((lx * hy) >> 32) + hx * hy;
362 }
363 dest[i+xlen] = carry;
364 }
365}
366
Zhou Shengdac63782007-02-06 03:00:16 +0000367APInt& APInt::operator*=(const APInt& RHS) {
Reid Spencera32372d12007-02-17 00:18:01 +0000368 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer58a6a432007-02-21 08:21:52 +0000369 if (isSingleWord()) {
Reid Spencer4bb430c2007-02-20 20:42:10 +0000370 VAL *= RHS.VAL;
Reid Spencer58a6a432007-02-21 08:21:52 +0000371 clearUnusedBits();
372 return *this;
Zhou Shengdac63782007-02-06 03:00:16 +0000373 }
Reid Spencer58a6a432007-02-21 08:21:52 +0000374
375 // Get some bit facts about LHS and check for zero
Chris Lattner77527f52009-01-21 18:09:24 +0000376 unsigned lhsBits = getActiveBits();
377 unsigned lhsWords = !lhsBits ? 0 : whichWord(lhsBits - 1) + 1;
Eric Christopher820256b2009-08-21 04:06:45 +0000378 if (!lhsWords)
Reid Spencer58a6a432007-02-21 08:21:52 +0000379 // 0 * X ===> 0
380 return *this;
381
382 // Get some bit facts about RHS and check for zero
Chris Lattner77527f52009-01-21 18:09:24 +0000383 unsigned rhsBits = RHS.getActiveBits();
384 unsigned rhsWords = !rhsBits ? 0 : whichWord(rhsBits - 1) + 1;
Reid Spencer58a6a432007-02-21 08:21:52 +0000385 if (!rhsWords) {
386 // X * 0 ===> 0
Jay Foad25a5e4c2010-12-01 08:53:58 +0000387 clearAllBits();
Reid Spencer58a6a432007-02-21 08:21:52 +0000388 return *this;
389 }
390
391 // Allocate space for the result
Chris Lattner77527f52009-01-21 18:09:24 +0000392 unsigned destWords = rhsWords + lhsWords;
Reid Spencer58a6a432007-02-21 08:21:52 +0000393 uint64_t *dest = getMemory(destWords);
394
395 // Perform the long multiply
396 mul(dest, pVal, lhsWords, RHS.pVal, rhsWords);
397
398 // Copy result back into *this
Jay Foad25a5e4c2010-12-01 08:53:58 +0000399 clearAllBits();
Chris Lattner77527f52009-01-21 18:09:24 +0000400 unsigned wordsToCopy = destWords >= getNumWords() ? getNumWords() : destWords;
Reid Spencer58a6a432007-02-21 08:21:52 +0000401 memcpy(pVal, dest, wordsToCopy * APINT_WORD_SIZE);
Eli Friedman19546412011-10-07 23:40:49 +0000402 clearUnusedBits();
Reid Spencer58a6a432007-02-21 08:21:52 +0000403
404 // delete dest array and return
405 delete[] dest;
Zhou Shengdac63782007-02-06 03:00:16 +0000406 return *this;
407}
408
Craig Topperf496f9a2017-03-28 04:00:47 +0000409APInt& APInt::AndAssignSlowCase(const APInt& RHS) {
Chris Lattner77527f52009-01-21 18:09:24 +0000410 unsigned numWords = getNumWords();
411 for (unsigned i = 0; i < numWords; ++i)
Reid Spencera856b6e2007-02-18 18:38:44 +0000412 pVal[i] &= RHS.pVal[i];
Zhou Shengdac63782007-02-06 03:00:16 +0000413 return *this;
414}
415
Craig Topperf496f9a2017-03-28 04:00:47 +0000416APInt& APInt::OrAssignSlowCase(const APInt& RHS) {
Chris Lattner77527f52009-01-21 18:09:24 +0000417 unsigned numWords = getNumWords();
418 for (unsigned i = 0; i < numWords; ++i)
Reid Spencera856b6e2007-02-18 18:38:44 +0000419 pVal[i] |= RHS.pVal[i];
Zhou Shengdac63782007-02-06 03:00:16 +0000420 return *this;
421}
422
Craig Topperf496f9a2017-03-28 04:00:47 +0000423APInt& APInt::XorAssignSlowCase(const APInt& RHS) {
Chris Lattner77527f52009-01-21 18:09:24 +0000424 unsigned numWords = getNumWords();
425 for (unsigned i = 0; i < numWords; ++i)
Reid Spencera856b6e2007-02-18 18:38:44 +0000426 pVal[i] ^= RHS.pVal[i];
Craig Topper9028f052017-01-24 02:10:15 +0000427 return *this;
Zhou Shengdac63782007-02-06 03:00:16 +0000428}
429
Zhou Shengdac63782007-02-06 03:00:16 +0000430APInt APInt::operator*(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +0000431 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencera41e93b2007-02-25 19:32:03 +0000432 if (isSingleWord())
Reid Spenceraa8dcfe2007-02-26 07:44:38 +0000433 return APInt(BitWidth, VAL * RHS.VAL);
Reid Spencer4bb430c2007-02-20 20:42:10 +0000434 APInt Result(*this);
435 Result *= RHS;
Eli Friedman19546412011-10-07 23:40:49 +0000436 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000437}
438
Chris Lattner1ac3e252008-08-20 17:02:31 +0000439bool APInt::EqualSlowCase(const APInt& RHS) const {
Matthias Braun5117fcd2016-02-15 20:06:19 +0000440 return std::equal(pVal, pVal + getNumWords(), RHS.pVal);
Zhou Shengdac63782007-02-06 03:00:16 +0000441}
442
Chris Lattner1ac3e252008-08-20 17:02:31 +0000443bool APInt::EqualSlowCase(uint64_t Val) const {
Chris Lattner77527f52009-01-21 18:09:24 +0000444 unsigned n = getActiveBits();
Reid Spencer7a6a8d52007-02-20 23:40:25 +0000445 if (n <= APINT_BITS_PER_WORD)
446 return pVal[0] == Val;
447 else
448 return false;
Zhou Shengdac63782007-02-06 03:00:16 +0000449}
450
Reid Spencer1d072122007-02-16 22:36:51 +0000451bool APInt::ult(const APInt& RHS) const {
452 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
453 if (isSingleWord())
454 return VAL < RHS.VAL;
Reid Spencera41e93b2007-02-25 19:32:03 +0000455
456 // Get active bit length of both operands
Chris Lattner77527f52009-01-21 18:09:24 +0000457 unsigned n1 = getActiveBits();
458 unsigned n2 = RHS.getActiveBits();
Reid Spencera41e93b2007-02-25 19:32:03 +0000459
460 // If magnitude of LHS is less than RHS, return true.
461 if (n1 < n2)
462 return true;
463
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000464 // If magnitude of RHS is greater than LHS, return false.
Reid Spencera41e93b2007-02-25 19:32:03 +0000465 if (n2 < n1)
466 return false;
467
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000468 // If they both fit in a word, just compare the low order word
Reid Spencera41e93b2007-02-25 19:32:03 +0000469 if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD)
470 return pVal[0] < RHS.pVal[0];
471
472 // Otherwise, compare all words
Chris Lattner77527f52009-01-21 18:09:24 +0000473 unsigned topWord = whichWord(std::max(n1,n2)-1);
Reid Spencer54abdcf2007-02-27 18:23:40 +0000474 for (int i = topWord; i >= 0; --i) {
Eric Christopher820256b2009-08-21 04:06:45 +0000475 if (pVal[i] > RHS.pVal[i])
Reid Spencer1d072122007-02-16 22:36:51 +0000476 return false;
Eric Christopher820256b2009-08-21 04:06:45 +0000477 if (pVal[i] < RHS.pVal[i])
Reid Spencera41e93b2007-02-25 19:32:03 +0000478 return true;
Zhou Shengdac63782007-02-06 03:00:16 +0000479 }
480 return false;
481}
482
Reid Spencer1d072122007-02-16 22:36:51 +0000483bool APInt::slt(const APInt& RHS) const {
484 assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison");
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000485 if (isSingleWord()) {
David Majnemer5f1c0172016-06-24 20:51:47 +0000486 int64_t lhsSext = SignExtend64(VAL, BitWidth);
487 int64_t rhsSext = SignExtend64(RHS.VAL, BitWidth);
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000488 return lhsSext < rhsSext;
Reid Spencer1d072122007-02-16 22:36:51 +0000489 }
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000490
Reid Spencer54abdcf2007-02-27 18:23:40 +0000491 bool lhsNeg = isNegative();
Pete Cooperd6e6bf12016-05-26 17:40:07 +0000492 bool rhsNeg = RHS.isNegative();
Reid Spencera41e93b2007-02-25 19:32:03 +0000493
Pete Cooperd6e6bf12016-05-26 17:40:07 +0000494 // If the sign bits don't match, then (LHS < RHS) if LHS is negative
495 if (lhsNeg != rhsNeg)
496 return lhsNeg;
497
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000498 // Otherwise we can just use an unsigned comparison, because even negative
Pete Cooperd6e6bf12016-05-26 17:40:07 +0000499 // numbers compare correctly this way if both have the same signed-ness.
500 return ult(RHS);
Zhou Shengdac63782007-02-06 03:00:16 +0000501}
502
Jay Foad25a5e4c2010-12-01 08:53:58 +0000503void APInt::setBit(unsigned bitPosition) {
Eric Christopher820256b2009-08-21 04:06:45 +0000504 if (isSingleWord())
Reid Spencera41e93b2007-02-25 19:32:03 +0000505 VAL |= maskBit(bitPosition);
Eric Christopher820256b2009-08-21 04:06:45 +0000506 else
Reid Spencera41e93b2007-02-25 19:32:03 +0000507 pVal[whichWord(bitPosition)] |= maskBit(bitPosition);
Zhou Shengdac63782007-02-06 03:00:16 +0000508}
509
Craig Topperbafdd032017-03-07 01:56:01 +0000510void APInt::setBitsSlowCase(unsigned loBit, unsigned hiBit) {
511 unsigned loWord = whichWord(loBit);
512 unsigned hiWord = whichWord(hiBit);
Simon Pilgrimaed35222017-02-24 10:15:29 +0000513
Simon Pilgrim0099beb2017-03-09 13:57:04 +0000514 // Create an initial mask for the low word with zeros below loBit.
Craig Topperbafdd032017-03-07 01:56:01 +0000515 uint64_t loMask = UINT64_MAX << whichBit(loBit);
Simon Pilgrimaed35222017-02-24 10:15:29 +0000516
Craig Topperbafdd032017-03-07 01:56:01 +0000517 // If hiBit is not aligned, we need a high mask.
518 unsigned hiShiftAmt = whichBit(hiBit);
519 if (hiShiftAmt != 0) {
520 // Create a high mask with zeros above hiBit.
521 uint64_t hiMask = UINT64_MAX >> (APINT_BITS_PER_WORD - hiShiftAmt);
522 // If loWord and hiWord are equal, then we combine the masks. Otherwise,
523 // set the bits in hiWord.
524 if (hiWord == loWord)
525 loMask &= hiMask;
526 else
Simon Pilgrimaed35222017-02-24 10:15:29 +0000527 pVal[hiWord] |= hiMask;
Simon Pilgrimaed35222017-02-24 10:15:29 +0000528 }
Craig Topperbafdd032017-03-07 01:56:01 +0000529 // Apply the mask to the low word.
530 pVal[loWord] |= loMask;
531
532 // Fill any words between loWord and hiWord with all ones.
533 for (unsigned word = loWord + 1; word < hiWord; ++word)
534 pVal[word] = UINT64_MAX;
Simon Pilgrimaed35222017-02-24 10:15:29 +0000535}
536
Zhou Shengdac63782007-02-06 03:00:16 +0000537/// Set the given bit to 0 whose position is given as "bitPosition".
538/// @brief Set a given bit to 0.
Jay Foad25a5e4c2010-12-01 08:53:58 +0000539void APInt::clearBit(unsigned bitPosition) {
Eric Christopher820256b2009-08-21 04:06:45 +0000540 if (isSingleWord())
Reid Spencera856b6e2007-02-18 18:38:44 +0000541 VAL &= ~maskBit(bitPosition);
Eric Christopher820256b2009-08-21 04:06:45 +0000542 else
Reid Spencera856b6e2007-02-18 18:38:44 +0000543 pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition);
Zhou Shengdac63782007-02-06 03:00:16 +0000544}
545
Zhou Shengdac63782007-02-06 03:00:16 +0000546/// @brief Toggle every bit to its opposite value.
Craig Topperafc9e352017-03-27 17:10:21 +0000547void APInt::flipAllBitsSlowCase() {
548 for (unsigned i = 0; i < getNumWords(); ++i)
549 pVal[i] ^= UINT64_MAX;
550 clearUnusedBits();
551}
Zhou Shengdac63782007-02-06 03:00:16 +0000552
Eric Christopher820256b2009-08-21 04:06:45 +0000553/// Toggle a given bit to its opposite value whose position is given
Zhou Shengdac63782007-02-06 03:00:16 +0000554/// as "bitPosition".
555/// @brief Toggles a given bit to its opposite value.
Jay Foad25a5e4c2010-12-01 08:53:58 +0000556void APInt::flipBit(unsigned bitPosition) {
Reid Spencer1d072122007-02-16 22:36:51 +0000557 assert(bitPosition < BitWidth && "Out of the bit-width range!");
Jay Foad25a5e4c2010-12-01 08:53:58 +0000558 if ((*this)[bitPosition]) clearBit(bitPosition);
559 else setBit(bitPosition);
Zhou Shengdac63782007-02-06 03:00:16 +0000560}
561
Simon Pilgrimb02667c2017-03-10 13:44:32 +0000562void APInt::insertBits(const APInt &subBits, unsigned bitPosition) {
563 unsigned subBitWidth = subBits.getBitWidth();
564 assert(0 < subBitWidth && (subBitWidth + bitPosition) <= BitWidth &&
565 "Illegal bit insertion");
566
567 // Insertion is a direct copy.
568 if (subBitWidth == BitWidth) {
569 *this = subBits;
570 return;
571 }
572
573 // Single word result can be done as a direct bitmask.
574 if (isSingleWord()) {
575 uint64_t mask = UINT64_MAX >> (APINT_BITS_PER_WORD - subBitWidth);
576 VAL &= ~(mask << bitPosition);
577 VAL |= (subBits.VAL << bitPosition);
578 return;
579 }
580
581 unsigned loBit = whichBit(bitPosition);
582 unsigned loWord = whichWord(bitPosition);
583 unsigned hi1Word = whichWord(bitPosition + subBitWidth - 1);
584
585 // Insertion within a single word can be done as a direct bitmask.
586 if (loWord == hi1Word) {
587 uint64_t mask = UINT64_MAX >> (APINT_BITS_PER_WORD - subBitWidth);
588 pVal[loWord] &= ~(mask << loBit);
589 pVal[loWord] |= (subBits.VAL << loBit);
590 return;
591 }
592
593 // Insert on word boundaries.
594 if (loBit == 0) {
595 // Direct copy whole words.
596 unsigned numWholeSubWords = subBitWidth / APINT_BITS_PER_WORD;
597 memcpy(pVal + loWord, subBits.getRawData(),
598 numWholeSubWords * APINT_WORD_SIZE);
599
600 // Mask+insert remaining bits.
601 unsigned remainingBits = subBitWidth % APINT_BITS_PER_WORD;
602 if (remainingBits != 0) {
603 uint64_t mask = UINT64_MAX >> (APINT_BITS_PER_WORD - remainingBits);
604 pVal[hi1Word] &= ~mask;
605 pVal[hi1Word] |= subBits.getWord(subBitWidth - 1);
606 }
607 return;
608 }
609
610 // General case - set/clear individual bits in dst based on src.
611 // TODO - there is scope for optimization here, but at the moment this code
612 // path is barely used so prefer readability over performance.
613 for (unsigned i = 0; i != subBitWidth; ++i) {
614 if (subBits[i])
615 setBit(bitPosition + i);
616 else
617 clearBit(bitPosition + i);
618 }
619}
620
Simon Pilgrim0f5fb5f2017-02-25 20:01:58 +0000621APInt APInt::extractBits(unsigned numBits, unsigned bitPosition) const {
622 assert(numBits > 0 && "Can't extract zero bits");
623 assert(bitPosition < BitWidth && (numBits + bitPosition) <= BitWidth &&
624 "Illegal bit extraction");
625
626 if (isSingleWord())
627 return APInt(numBits, VAL >> bitPosition);
628
629 unsigned loBit = whichBit(bitPosition);
630 unsigned loWord = whichWord(bitPosition);
631 unsigned hiWord = whichWord(bitPosition + numBits - 1);
632
633 // Single word result extracting bits from a single word source.
634 if (loWord == hiWord)
635 return APInt(numBits, pVal[loWord] >> loBit);
636
637 // Extracting bits that start on a source word boundary can be done
638 // as a fast memory copy.
639 if (loBit == 0)
640 return APInt(numBits, makeArrayRef(pVal + loWord, 1 + hiWord - loWord));
641
642 // General case - shift + copy source words directly into place.
643 APInt Result(numBits, 0);
644 unsigned NumSrcWords = getNumWords();
645 unsigned NumDstWords = Result.getNumWords();
646
647 for (unsigned word = 0; word < NumDstWords; ++word) {
648 uint64_t w0 = pVal[loWord + word];
649 uint64_t w1 =
650 (loWord + word + 1) < NumSrcWords ? pVal[loWord + word + 1] : 0;
651 Result.pVal[word] = (w0 >> loBit) | (w1 << (APINT_BITS_PER_WORD - loBit));
652 }
653
654 return Result.clearUnusedBits();
655}
656
Benjamin Kramer92d89982010-07-14 22:38:02 +0000657unsigned APInt::getBitsNeeded(StringRef str, uint8_t radix) {
Daniel Dunbar3a1efd112009-08-13 02:33:34 +0000658 assert(!str.empty() && "Invalid string length");
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +0000659 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 ||
Douglas Gregor663c0682011-09-14 15:54:46 +0000660 radix == 36) &&
661 "Radix should be 2, 8, 10, 16, or 36!");
Daniel Dunbar3a1efd112009-08-13 02:33:34 +0000662
663 size_t slen = str.size();
Reid Spencer9329e7b2007-04-13 19:19:07 +0000664
Eric Christopher43a1dec2009-08-21 04:10:31 +0000665 // Each computation below needs to know if it's negative.
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000666 StringRef::iterator p = str.begin();
Eric Christopher43a1dec2009-08-21 04:10:31 +0000667 unsigned isNegative = *p == '-';
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000668 if (*p == '-' || *p == '+') {
669 p++;
Reid Spencer9329e7b2007-04-13 19:19:07 +0000670 slen--;
Eric Christopher43a1dec2009-08-21 04:10:31 +0000671 assert(slen && "String is only a sign, needs a value.");
Reid Spencer9329e7b2007-04-13 19:19:07 +0000672 }
Eric Christopher43a1dec2009-08-21 04:10:31 +0000673
Reid Spencer9329e7b2007-04-13 19:19:07 +0000674 // For radixes of power-of-two values, the bits required is accurately and
675 // easily computed
676 if (radix == 2)
677 return slen + isNegative;
678 if (radix == 8)
679 return slen * 3 + isNegative;
680 if (radix == 16)
681 return slen * 4 + isNegative;
682
Douglas Gregor663c0682011-09-14 15:54:46 +0000683 // FIXME: base 36
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +0000684
Reid Spencer9329e7b2007-04-13 19:19:07 +0000685 // This is grossly inefficient but accurate. We could probably do something
686 // with a computation of roughly slen*64/20 and then adjust by the value of
687 // the first few digits. But, I'm not sure how accurate that could be.
688
689 // Compute a sufficient number of bits that is always large enough but might
Erick Tryzelaardadb15712009-08-21 03:15:28 +0000690 // be too large. This avoids the assertion in the constructor. This
691 // calculation doesn't work appropriately for the numbers 0-9, so just use 4
692 // bits in that case.
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +0000693 unsigned sufficient
Douglas Gregor663c0682011-09-14 15:54:46 +0000694 = radix == 10? (slen == 1 ? 4 : slen * 64/18)
695 : (slen == 1 ? 7 : slen * 16/3);
Reid Spencer9329e7b2007-04-13 19:19:07 +0000696
697 // Convert to the actual binary value.
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +0000698 APInt tmp(sufficient, StringRef(p, slen), radix);
Reid Spencer9329e7b2007-04-13 19:19:07 +0000699
Erick Tryzelaardadb15712009-08-21 03:15:28 +0000700 // Compute how many bits are required. If the log is infinite, assume we need
701 // just bit.
702 unsigned log = tmp.logBase2();
703 if (log == (unsigned)-1) {
704 return isNegative + 1;
705 } else {
706 return isNegative + log + 1;
707 }
Reid Spencer9329e7b2007-04-13 19:19:07 +0000708}
709
Chandler Carruth71bd7d12012-03-04 12:02:57 +0000710hash_code llvm::hash_value(const APInt &Arg) {
711 if (Arg.isSingleWord())
712 return hash_combine(Arg.VAL);
Reid Spencerb2bc9852007-02-26 21:02:27 +0000713
Chandler Carruth71bd7d12012-03-04 12:02:57 +0000714 return hash_combine_range(Arg.pVal, Arg.pVal + Arg.getNumWords());
Reid Spencerb2bc9852007-02-26 21:02:27 +0000715}
716
Benjamin Kramerb4b51502015-03-25 16:49:59 +0000717bool APInt::isSplat(unsigned SplatSizeInBits) const {
718 assert(getBitWidth() % SplatSizeInBits == 0 &&
719 "SplatSizeInBits must divide width!");
720 // We can check that all parts of an integer are equal by making use of a
721 // little trick: rotate and check if it's still the same value.
722 return *this == rotl(SplatSizeInBits);
723}
724
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000725/// This function returns the high "numBits" bits of this APInt.
Chris Lattner77527f52009-01-21 18:09:24 +0000726APInt APInt::getHiBits(unsigned numBits) const {
Reid Spencer1d072122007-02-16 22:36:51 +0000727 return APIntOps::lshr(*this, BitWidth - numBits);
Zhou Shengdac63782007-02-06 03:00:16 +0000728}
729
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000730/// This function returns the low "numBits" bits of this APInt.
Chris Lattner77527f52009-01-21 18:09:24 +0000731APInt APInt::getLoBits(unsigned numBits) const {
Eric Christopher820256b2009-08-21 04:06:45 +0000732 return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits),
Reid Spencer1d072122007-02-16 22:36:51 +0000733 BitWidth - numBits);
Zhou Shengdac63782007-02-06 03:00:16 +0000734}
735
Chris Lattner77527f52009-01-21 18:09:24 +0000736unsigned APInt::countLeadingZerosSlowCase() const {
Matthias Brauna6be4e82016-02-15 20:06:22 +0000737 unsigned Count = 0;
738 for (int i = getNumWords()-1; i >= 0; --i) {
739 integerPart V = pVal[i];
740 if (V == 0)
Chris Lattner1ac3e252008-08-20 17:02:31 +0000741 Count += APINT_BITS_PER_WORD;
742 else {
Matthias Brauna6be4e82016-02-15 20:06:22 +0000743 Count += llvm::countLeadingZeros(V);
Chris Lattner1ac3e252008-08-20 17:02:31 +0000744 break;
Reid Spencer74cf82e2007-02-21 00:29:48 +0000745 }
Zhou Shengdac63782007-02-06 03:00:16 +0000746 }
Matthias Brauna6be4e82016-02-15 20:06:22 +0000747 // Adjust for unused bits in the most significant word (they are zero).
748 unsigned Mod = BitWidth % APINT_BITS_PER_WORD;
749 Count -= Mod > 0 ? APINT_BITS_PER_WORD - Mod : 0;
John McCalldf951bd2010-02-03 03:42:44 +0000750 return Count;
Zhou Shengdac63782007-02-06 03:00:16 +0000751}
752
Chris Lattner77527f52009-01-21 18:09:24 +0000753unsigned APInt::countLeadingOnes() const {
Reid Spencer31acef52007-02-27 21:59:26 +0000754 if (isSingleWord())
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000755 return llvm::countLeadingOnes(VAL << (APINT_BITS_PER_WORD - BitWidth));
Reid Spencer31acef52007-02-27 21:59:26 +0000756
Chris Lattner77527f52009-01-21 18:09:24 +0000757 unsigned highWordBits = BitWidth % APINT_BITS_PER_WORD;
Torok Edwinec39eb82009-01-27 18:06:03 +0000758 unsigned shift;
759 if (!highWordBits) {
760 highWordBits = APINT_BITS_PER_WORD;
761 shift = 0;
762 } else {
763 shift = APINT_BITS_PER_WORD - highWordBits;
764 }
Reid Spencer31acef52007-02-27 21:59:26 +0000765 int i = getNumWords() - 1;
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000766 unsigned Count = llvm::countLeadingOnes(pVal[i] << shift);
Reid Spencer31acef52007-02-27 21:59:26 +0000767 if (Count == highWordBits) {
768 for (i--; i >= 0; --i) {
769 if (pVal[i] == -1ULL)
770 Count += APINT_BITS_PER_WORD;
771 else {
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000772 Count += llvm::countLeadingOnes(pVal[i]);
Reid Spencer31acef52007-02-27 21:59:26 +0000773 break;
774 }
775 }
776 }
777 return Count;
778}
779
Chris Lattner77527f52009-01-21 18:09:24 +0000780unsigned APInt::countTrailingZeros() const {
Zhou Shengdac63782007-02-06 03:00:16 +0000781 if (isSingleWord())
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000782 return std::min(unsigned(llvm::countTrailingZeros(VAL)), BitWidth);
Chris Lattner77527f52009-01-21 18:09:24 +0000783 unsigned Count = 0;
784 unsigned i = 0;
Reid Spenceraa8dcfe2007-02-26 07:44:38 +0000785 for (; i < getNumWords() && pVal[i] == 0; ++i)
786 Count += APINT_BITS_PER_WORD;
787 if (i < getNumWords())
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000788 Count += llvm::countTrailingZeros(pVal[i]);
Chris Lattnerc2c4c742007-11-23 22:36:25 +0000789 return std::min(Count, BitWidth);
Zhou Shengdac63782007-02-06 03:00:16 +0000790}
791
Chris Lattner77527f52009-01-21 18:09:24 +0000792unsigned APInt::countTrailingOnesSlowCase() const {
793 unsigned Count = 0;
794 unsigned i = 0;
Dan Gohmanc354ebd2008-02-14 22:38:45 +0000795 for (; i < getNumWords() && pVal[i] == -1ULL; ++i)
Dan Gohman8b4fa9d2008-02-13 21:11:05 +0000796 Count += APINT_BITS_PER_WORD;
797 if (i < getNumWords())
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000798 Count += llvm::countTrailingOnes(pVal[i]);
Dan Gohman8b4fa9d2008-02-13 21:11:05 +0000799 return std::min(Count, BitWidth);
800}
801
Chris Lattner77527f52009-01-21 18:09:24 +0000802unsigned APInt::countPopulationSlowCase() const {
803 unsigned Count = 0;
804 for (unsigned i = 0; i < getNumWords(); ++i)
Benjamin Kramer5f6a9072015-02-12 15:35:40 +0000805 Count += llvm::countPopulation(pVal[i]);
Zhou Shengdac63782007-02-06 03:00:16 +0000806 return Count;
807}
808
Richard Smith4f9a8082011-11-23 21:33:37 +0000809/// Perform a logical right-shift from Src to Dst, which must be equal or
810/// non-overlapping, of Words words, by Shift, which must be less than 64.
811static void lshrNear(uint64_t *Dst, uint64_t *Src, unsigned Words,
812 unsigned Shift) {
813 uint64_t Carry = 0;
814 for (int I = Words - 1; I >= 0; --I) {
815 uint64_t Tmp = Src[I];
816 Dst[I] = (Tmp >> Shift) | Carry;
817 Carry = Tmp << (64 - Shift);
818 }
819}
820
Reid Spencer1d072122007-02-16 22:36:51 +0000821APInt APInt::byteSwap() const {
822 assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!");
823 if (BitWidth == 16)
Jeff Cohene06855e2007-03-20 20:42:36 +0000824 return APInt(BitWidth, ByteSwap_16(uint16_t(VAL)));
Richard Smith4f9a8082011-11-23 21:33:37 +0000825 if (BitWidth == 32)
Chris Lattner77527f52009-01-21 18:09:24 +0000826 return APInt(BitWidth, ByteSwap_32(unsigned(VAL)));
Richard Smith4f9a8082011-11-23 21:33:37 +0000827 if (BitWidth == 48) {
Chris Lattner77527f52009-01-21 18:09:24 +0000828 unsigned Tmp1 = unsigned(VAL >> 16);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000829 Tmp1 = ByteSwap_32(Tmp1);
Jeff Cohene06855e2007-03-20 20:42:36 +0000830 uint16_t Tmp2 = uint16_t(VAL);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000831 Tmp2 = ByteSwap_16(Tmp2);
Jeff Cohene06855e2007-03-20 20:42:36 +0000832 return APInt(BitWidth, (uint64_t(Tmp2) << 32) | Tmp1);
Zhou Shengcfa2ac02007-02-15 06:36:31 +0000833 }
Richard Smith4f9a8082011-11-23 21:33:37 +0000834 if (BitWidth == 64)
835 return APInt(BitWidth, ByteSwap_64(VAL));
836
837 APInt Result(getNumWords() * APINT_BITS_PER_WORD, 0);
838 for (unsigned I = 0, N = getNumWords(); I != N; ++I)
839 Result.pVal[I] = ByteSwap_64(pVal[N - I - 1]);
840 if (Result.BitWidth != BitWidth) {
841 lshrNear(Result.pVal, Result.pVal, getNumWords(),
842 Result.BitWidth - BitWidth);
843 Result.BitWidth = BitWidth;
844 }
845 return Result;
Zhou Shengdac63782007-02-06 03:00:16 +0000846}
847
Matt Arsenault155dda92016-03-21 15:00:35 +0000848APInt APInt::reverseBits() const {
849 switch (BitWidth) {
850 case 64:
851 return APInt(BitWidth, llvm::reverseBits<uint64_t>(VAL));
852 case 32:
853 return APInt(BitWidth, llvm::reverseBits<uint32_t>(VAL));
854 case 16:
855 return APInt(BitWidth, llvm::reverseBits<uint16_t>(VAL));
856 case 8:
857 return APInt(BitWidth, llvm::reverseBits<uint8_t>(VAL));
858 default:
859 break;
860 }
861
862 APInt Val(*this);
863 APInt Reversed(*this);
864 int S = BitWidth - 1;
865
866 const APInt One(BitWidth, 1);
867
868 for ((Val = Val.lshr(1)); Val != 0; (Val = Val.lshr(1))) {
869 Reversed <<= 1;
870 Reversed |= (Val & One);
871 --S;
872 }
873
874 Reversed <<= S;
875 return Reversed;
876}
877
Eric Christopher820256b2009-08-21 04:06:45 +0000878APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1,
Zhou Shengfbf61ea2007-02-08 14:35:19 +0000879 const APInt& API2) {
Zhou Shengdac63782007-02-06 03:00:16 +0000880 APInt A = API1, B = API2;
881 while (!!B) {
882 APInt T = B;
Reid Spencer1d072122007-02-16 22:36:51 +0000883 B = APIntOps::urem(A, B);
Zhou Shengdac63782007-02-06 03:00:16 +0000884 A = T;
885 }
886 return A;
887}
Chris Lattner28cbd1d2007-02-06 05:38:37 +0000888
Chris Lattner77527f52009-01-21 18:09:24 +0000889APInt llvm::APIntOps::RoundDoubleToAPInt(double Double, unsigned width) {
Zhou Shengd707d632007-02-12 20:02:55 +0000890 union {
891 double D;
892 uint64_t I;
893 } T;
894 T.D = Double;
Reid Spencer974551a2007-02-27 01:28:10 +0000895
896 // Get the sign bit from the highest order bit
Zhou Shengd707d632007-02-12 20:02:55 +0000897 bool isNeg = T.I >> 63;
Reid Spencer974551a2007-02-27 01:28:10 +0000898
899 // Get the 11-bit exponent and adjust for the 1023 bit bias
Zhou Shengd707d632007-02-12 20:02:55 +0000900 int64_t exp = ((T.I >> 52) & 0x7ff) - 1023;
Reid Spencer974551a2007-02-27 01:28:10 +0000901
902 // If the exponent is negative, the value is < 0 so just return 0.
Zhou Shengd707d632007-02-12 20:02:55 +0000903 if (exp < 0)
Reid Spencer66d0d572007-02-28 01:30:08 +0000904 return APInt(width, 0u);
Reid Spencer974551a2007-02-27 01:28:10 +0000905
906 // Extract the mantissa by clearing the top 12 bits (sign + exponent).
907 uint64_t mantissa = (T.I & (~0ULL >> 12)) | 1ULL << 52;
908
909 // If the exponent doesn't shift all bits out of the mantissa
Zhou Shengd707d632007-02-12 20:02:55 +0000910 if (exp < 52)
Eric Christopher820256b2009-08-21 04:06:45 +0000911 return isNeg ? -APInt(width, mantissa >> (52 - exp)) :
Reid Spencer54abdcf2007-02-27 18:23:40 +0000912 APInt(width, mantissa >> (52 - exp));
913
914 // If the client didn't provide enough bits for us to shift the mantissa into
915 // then the result is undefined, just return 0
916 if (width <= exp - 52)
917 return APInt(width, 0);
Reid Spencer974551a2007-02-27 01:28:10 +0000918
919 // Otherwise, we have to shift the mantissa bits up to the right location
Reid Spencer54abdcf2007-02-27 18:23:40 +0000920 APInt Tmp(width, mantissa);
Chris Lattner77527f52009-01-21 18:09:24 +0000921 Tmp = Tmp.shl((unsigned)exp - 52);
Zhou Shengd707d632007-02-12 20:02:55 +0000922 return isNeg ? -Tmp : Tmp;
923}
924
Pawel Bylica6eeeac72015-04-06 13:31:39 +0000925/// This function converts this APInt to a double.
Zhou Shengd707d632007-02-12 20:02:55 +0000926/// The layout for double is as following (IEEE Standard 754):
927/// --------------------------------------
928/// | Sign Exponent Fraction Bias |
929/// |-------------------------------------- |
930/// | 1[63] 11[62-52] 52[51-00] 1023 |
Eric Christopher820256b2009-08-21 04:06:45 +0000931/// --------------------------------------
Reid Spencer1d072122007-02-16 22:36:51 +0000932double APInt::roundToDouble(bool isSigned) const {
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000933
934 // Handle the simple case where the value is contained in one uint64_t.
Dale Johannesen54be7852009-08-12 18:04:11 +0000935 // It is wrong to optimize getWord(0) to VAL; there might be more than one word.
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000936 if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) {
937 if (isSigned) {
David Majnemer03992262016-06-24 21:15:36 +0000938 int64_t sext = SignExtend64(getWord(0), BitWidth);
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000939 return double(sext);
940 } else
Dale Johannesen34c08bb2009-08-12 17:42:34 +0000941 return double(getWord(0));
Reid Spencerbe4ddf62007-02-18 20:09:41 +0000942 }
943
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000944 // Determine if the value is negative.
Reid Spencer1d072122007-02-16 22:36:51 +0000945 bool isNeg = isSigned ? (*this)[BitWidth-1] : false;
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000946
947 // Construct the absolute value if we're negative.
Zhou Shengd707d632007-02-12 20:02:55 +0000948 APInt Tmp(isNeg ? -(*this) : (*this));
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000949
950 // Figure out how many bits we're using.
Chris Lattner77527f52009-01-21 18:09:24 +0000951 unsigned n = Tmp.getActiveBits();
Zhou Shengd707d632007-02-12 20:02:55 +0000952
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000953 // The exponent (without bias normalization) is just the number of bits
954 // we are using. Note that the sign bit is gone since we constructed the
955 // absolute value.
956 uint64_t exp = n;
Zhou Shengd707d632007-02-12 20:02:55 +0000957
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000958 // Return infinity for exponent overflow
959 if (exp > 1023) {
960 if (!isSigned || !isNeg)
Jeff Cohene06855e2007-03-20 20:42:36 +0000961 return std::numeric_limits<double>::infinity();
Eric Christopher820256b2009-08-21 04:06:45 +0000962 else
Jeff Cohene06855e2007-03-20 20:42:36 +0000963 return -std::numeric_limits<double>::infinity();
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000964 }
965 exp += 1023; // Increment for 1023 bias
966
967 // Number of bits in mantissa is 52. To obtain the mantissa value, we must
968 // extract the high 52 bits from the correct words in pVal.
Zhou Shengd707d632007-02-12 20:02:55 +0000969 uint64_t mantissa;
Reid Spencerfb77b2b2007-02-20 08:51:03 +0000970 unsigned hiWord = whichWord(n-1);
971 if (hiWord == 0) {
972 mantissa = Tmp.pVal[0];
973 if (n > 52)
974 mantissa >>= n - 52; // shift down, we want the top 52 bits.
975 } else {
976 assert(hiWord > 0 && "huh?");
977 uint64_t hibits = Tmp.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD);
978 uint64_t lobits = Tmp.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD);
979 mantissa = hibits | lobits;
980 }
981
Zhou Shengd707d632007-02-12 20:02:55 +0000982 // The leading bit of mantissa is implicit, so get rid of it.
Reid Spencerfbd48a52007-02-18 00:44:22 +0000983 uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0;
Zhou Shengd707d632007-02-12 20:02:55 +0000984 union {
985 double D;
986 uint64_t I;
987 } T;
988 T.I = sign | (exp << 52) | mantissa;
989 return T.D;
990}
991
Reid Spencer1d072122007-02-16 22:36:51 +0000992// Truncate to new width.
Jay Foad583abbc2010-12-07 08:25:19 +0000993APInt APInt::trunc(unsigned width) const {
Reid Spencer1d072122007-02-16 22:36:51 +0000994 assert(width < BitWidth && "Invalid APInt Truncate request");
Chris Lattner1ac3e252008-08-20 17:02:31 +0000995 assert(width && "Can't truncate to 0 bits");
Jay Foad583abbc2010-12-07 08:25:19 +0000996
997 if (width <= APINT_BITS_PER_WORD)
998 return APInt(width, getRawData()[0]);
999
1000 APInt Result(getMemory(getNumWords(width)), width);
1001
1002 // Copy full words.
1003 unsigned i;
1004 for (i = 0; i != width / APINT_BITS_PER_WORD; i++)
1005 Result.pVal[i] = pVal[i];
1006
1007 // Truncate and copy any partial word.
1008 unsigned bits = (0 - width) % APINT_BITS_PER_WORD;
1009 if (bits != 0)
1010 Result.pVal[i] = pVal[i] << bits >> bits;
1011
1012 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +00001013}
1014
1015// Sign extend to a new width.
Jay Foad583abbc2010-12-07 08:25:19 +00001016APInt APInt::sext(unsigned width) const {
Reid Spencer1d072122007-02-16 22:36:51 +00001017 assert(width > BitWidth && "Invalid APInt SignExtend request");
Jay Foad583abbc2010-12-07 08:25:19 +00001018
1019 if (width <= APINT_BITS_PER_WORD) {
1020 uint64_t val = VAL << (APINT_BITS_PER_WORD - BitWidth);
1021 val = (int64_t)val >> (width - BitWidth);
1022 return APInt(width, val >> (APINT_BITS_PER_WORD - width));
Reid Spencerb6b5cc32007-02-25 23:44:53 +00001023 }
1024
Jay Foad583abbc2010-12-07 08:25:19 +00001025 APInt Result(getMemory(getNumWords(width)), width);
Reid Spencerb6b5cc32007-02-25 23:44:53 +00001026
Jay Foad583abbc2010-12-07 08:25:19 +00001027 // Copy full words.
1028 unsigned i;
1029 uint64_t word = 0;
1030 for (i = 0; i != BitWidth / APINT_BITS_PER_WORD; i++) {
1031 word = getRawData()[i];
1032 Result.pVal[i] = word;
Reid Spencerb6b5cc32007-02-25 23:44:53 +00001033 }
1034
Jay Foad583abbc2010-12-07 08:25:19 +00001035 // Read and sign-extend any partial word.
1036 unsigned bits = (0 - BitWidth) % APINT_BITS_PER_WORD;
1037 if (bits != 0)
1038 word = (int64_t)getRawData()[i] << bits >> bits;
1039 else
1040 word = (int64_t)word >> (APINT_BITS_PER_WORD - 1);
1041
1042 // Write remaining full words.
1043 for (; i != width / APINT_BITS_PER_WORD; i++) {
1044 Result.pVal[i] = word;
1045 word = (int64_t)word >> (APINT_BITS_PER_WORD - 1);
Reid Spencerb6b5cc32007-02-25 23:44:53 +00001046 }
Jay Foad583abbc2010-12-07 08:25:19 +00001047
1048 // Write any partial word.
1049 bits = (0 - width) % APINT_BITS_PER_WORD;
1050 if (bits != 0)
1051 Result.pVal[i] = word << bits >> bits;
1052
1053 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +00001054}
1055
1056// Zero extend to a new width.
Jay Foad583abbc2010-12-07 08:25:19 +00001057APInt APInt::zext(unsigned width) const {
Reid Spencer1d072122007-02-16 22:36:51 +00001058 assert(width > BitWidth && "Invalid APInt ZeroExtend request");
Jay Foad583abbc2010-12-07 08:25:19 +00001059
1060 if (width <= APINT_BITS_PER_WORD)
1061 return APInt(width, VAL);
1062
1063 APInt Result(getMemory(getNumWords(width)), width);
1064
1065 // Copy words.
1066 unsigned i;
1067 for (i = 0; i != getNumWords(); i++)
1068 Result.pVal[i] = getRawData()[i];
1069
1070 // Zero remaining words.
1071 memset(&Result.pVal[i], 0, (Result.getNumWords() - i) * APINT_WORD_SIZE);
1072
1073 return Result;
Reid Spencer1d072122007-02-16 22:36:51 +00001074}
1075
Jay Foad583abbc2010-12-07 08:25:19 +00001076APInt APInt::zextOrTrunc(unsigned width) const {
Reid Spencer742d1702007-03-01 17:15:32 +00001077 if (BitWidth < width)
1078 return zext(width);
1079 if (BitWidth > width)
1080 return trunc(width);
1081 return *this;
1082}
1083
Jay Foad583abbc2010-12-07 08:25:19 +00001084APInt APInt::sextOrTrunc(unsigned width) const {
Reid Spencer742d1702007-03-01 17:15:32 +00001085 if (BitWidth < width)
1086 return sext(width);
1087 if (BitWidth > width)
1088 return trunc(width);
1089 return *this;
1090}
1091
Rafael Espindolabb893fe2012-01-27 23:33:07 +00001092APInt APInt::zextOrSelf(unsigned width) const {
1093 if (BitWidth < width)
1094 return zext(width);
1095 return *this;
1096}
1097
1098APInt APInt::sextOrSelf(unsigned width) const {
1099 if (BitWidth < width)
1100 return sext(width);
1101 return *this;
1102}
1103
Zhou Shenge93db8f2007-02-09 07:48:24 +00001104/// Arithmetic right-shift this APInt by shiftAmt.
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001105/// @brief Arithmetic right-shift function.
Dan Gohman105c1d42008-02-29 01:40:47 +00001106APInt APInt::ashr(const APInt &shiftAmt) const {
Chris Lattner77527f52009-01-21 18:09:24 +00001107 return ashr((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001108}
1109
1110/// Arithmetic right-shift this APInt by shiftAmt.
1111/// @brief Arithmetic right-shift function.
Chris Lattner77527f52009-01-21 18:09:24 +00001112APInt APInt::ashr(unsigned shiftAmt) const {
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001113 assert(shiftAmt <= BitWidth && "Invalid shift amount");
Reid Spencer1825dd02007-03-02 22:39:11 +00001114 // Handle a degenerate case
1115 if (shiftAmt == 0)
1116 return *this;
1117
1118 // Handle single word shifts with built-in ashr
Reid Spencer522ca7c2007-02-25 01:56:07 +00001119 if (isSingleWord()) {
1120 if (shiftAmt == BitWidth)
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001121 return APInt(BitWidth, 0); // undefined
Jonathan Roelofs851b79d2016-08-10 19:50:14 +00001122 return APInt(BitWidth, SignExtend64(VAL, BitWidth) >> shiftAmt);
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001123 }
Reid Spencer522ca7c2007-02-25 01:56:07 +00001124
Reid Spencer1825dd02007-03-02 22:39:11 +00001125 // If all the bits were shifted out, the result is, technically, undefined.
1126 // We return -1 if it was negative, 0 otherwise. We check this early to avoid
1127 // issues in the algorithm below.
Chris Lattnerdad2d092007-05-03 18:15:36 +00001128 if (shiftAmt == BitWidth) {
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001129 if (isNegative())
Zhou Sheng1247c072008-06-05 13:27:38 +00001130 return APInt(BitWidth, -1ULL, true);
Reid Spencera41e93b2007-02-25 19:32:03 +00001131 else
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001132 return APInt(BitWidth, 0);
Chris Lattnerdad2d092007-05-03 18:15:36 +00001133 }
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001134
1135 // Create some space for the result.
1136 uint64_t * val = new uint64_t[getNumWords()];
1137
Reid Spencer1825dd02007-03-02 22:39:11 +00001138 // Compute some values needed by the following shift algorithms
Chris Lattner77527f52009-01-21 18:09:24 +00001139 unsigned wordShift = shiftAmt % APINT_BITS_PER_WORD; // bits to shift per word
1140 unsigned offset = shiftAmt / APINT_BITS_PER_WORD; // word offset for shift
1141 unsigned breakWord = getNumWords() - 1 - offset; // last word affected
1142 unsigned bitsInWord = whichBit(BitWidth); // how many bits in last word?
Reid Spencer1825dd02007-03-02 22:39:11 +00001143 if (bitsInWord == 0)
1144 bitsInWord = APINT_BITS_PER_WORD;
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001145
1146 // If we are shifting whole words, just move whole words
1147 if (wordShift == 0) {
Reid Spencer1825dd02007-03-02 22:39:11 +00001148 // Move the words containing significant bits
Chris Lattner77527f52009-01-21 18:09:24 +00001149 for (unsigned i = 0; i <= breakWord; ++i)
Reid Spencer1825dd02007-03-02 22:39:11 +00001150 val[i] = pVal[i+offset]; // move whole word
1151
1152 // Adjust the top significant word for sign bit fill, if negative
1153 if (isNegative())
1154 if (bitsInWord < APINT_BITS_PER_WORD)
1155 val[breakWord] |= ~0ULL << bitsInWord; // set high bits
1156 } else {
Eric Christopher820256b2009-08-21 04:06:45 +00001157 // Shift the low order words
Chris Lattner77527f52009-01-21 18:09:24 +00001158 for (unsigned i = 0; i < breakWord; ++i) {
Reid Spencer1825dd02007-03-02 22:39:11 +00001159 // This combines the shifted corresponding word with the low bits from
1160 // the next word (shifted into this word's high bits).
Eric Christopher820256b2009-08-21 04:06:45 +00001161 val[i] = (pVal[i+offset] >> wordShift) |
Reid Spencer1825dd02007-03-02 22:39:11 +00001162 (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift));
1163 }
1164
1165 // Shift the break word. In this case there are no bits from the next word
1166 // to include in this word.
1167 val[breakWord] = pVal[breakWord+offset] >> wordShift;
1168
Alp Tokercb402912014-01-24 17:20:08 +00001169 // Deal with sign extension in the break word, and possibly the word before
Reid Spencer1825dd02007-03-02 22:39:11 +00001170 // it.
Chris Lattnerdad2d092007-05-03 18:15:36 +00001171 if (isNegative()) {
Reid Spencer1825dd02007-03-02 22:39:11 +00001172 if (wordShift > bitsInWord) {
1173 if (breakWord > 0)
Eric Christopher820256b2009-08-21 04:06:45 +00001174 val[breakWord-1] |=
Reid Spencer1825dd02007-03-02 22:39:11 +00001175 ~0ULL << (APINT_BITS_PER_WORD - (wordShift - bitsInWord));
1176 val[breakWord] |= ~0ULL;
Eric Christopher820256b2009-08-21 04:06:45 +00001177 } else
Reid Spencer1825dd02007-03-02 22:39:11 +00001178 val[breakWord] |= (~0ULL << (bitsInWord - wordShift));
Chris Lattnerdad2d092007-05-03 18:15:36 +00001179 }
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001180 }
1181
Reid Spencer1825dd02007-03-02 22:39:11 +00001182 // Remaining words are 0 or -1, just assign them.
1183 uint64_t fillValue = (isNegative() ? -1ULL : 0);
Chris Lattner77527f52009-01-21 18:09:24 +00001184 for (unsigned i = breakWord+1; i < getNumWords(); ++i)
Reid Spencer1825dd02007-03-02 22:39:11 +00001185 val[i] = fillValue;
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001186 APInt Result(val, BitWidth);
1187 Result.clearUnusedBits();
1188 return Result;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001189}
1190
Zhou Shenge93db8f2007-02-09 07:48:24 +00001191/// Logical right-shift this APInt by shiftAmt.
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001192/// @brief Logical right-shift function.
Dan Gohman105c1d42008-02-29 01:40:47 +00001193APInt APInt::lshr(const APInt &shiftAmt) const {
Chris Lattner77527f52009-01-21 18:09:24 +00001194 return lshr((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001195}
1196
1197/// Logical right-shift this APInt by shiftAmt.
1198/// @brief Logical right-shift function.
Chris Lattner77527f52009-01-21 18:09:24 +00001199APInt APInt::lshr(unsigned shiftAmt) const {
Chris Lattnerdad2d092007-05-03 18:15:36 +00001200 if (isSingleWord()) {
Ahmed Charles0dca5d82012-02-24 19:06:15 +00001201 if (shiftAmt >= BitWidth)
Reid Spencer522ca7c2007-02-25 01:56:07 +00001202 return APInt(BitWidth, 0);
Eric Christopher820256b2009-08-21 04:06:45 +00001203 else
Reid Spencer522ca7c2007-02-25 01:56:07 +00001204 return APInt(BitWidth, this->VAL >> shiftAmt);
Chris Lattnerdad2d092007-05-03 18:15:36 +00001205 }
Reid Spencer522ca7c2007-02-25 01:56:07 +00001206
Reid Spencer44eef162007-02-26 01:19:48 +00001207 // If all the bits were shifted out, the result is 0. This avoids issues
1208 // with shifting by the size of the integer type, which produces undefined
1209 // results. We define these "undefined results" to always be 0.
Chad Rosier3d464d82012-06-08 18:04:52 +00001210 if (shiftAmt >= BitWidth)
Reid Spencer44eef162007-02-26 01:19:48 +00001211 return APInt(BitWidth, 0);
1212
Reid Spencerfffdf102007-05-17 06:26:29 +00001213 // If none of the bits are shifted out, the result is *this. This avoids
Eric Christopher820256b2009-08-21 04:06:45 +00001214 // issues with shifting by the size of the integer type, which produces
Reid Spencerfffdf102007-05-17 06:26:29 +00001215 // undefined results in the code below. This is also an optimization.
1216 if (shiftAmt == 0)
1217 return *this;
1218
Reid Spencer44eef162007-02-26 01:19:48 +00001219 // Create some space for the result.
1220 uint64_t * val = new uint64_t[getNumWords()];
1221
1222 // If we are shifting less than a word, compute the shift with a simple carry
1223 if (shiftAmt < APINT_BITS_PER_WORD) {
Richard Smith4f9a8082011-11-23 21:33:37 +00001224 lshrNear(val, pVal, getNumWords(), shiftAmt);
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001225 APInt Result(val, BitWidth);
1226 Result.clearUnusedBits();
1227 return Result;
Reid Spencera41e93b2007-02-25 19:32:03 +00001228 }
1229
Reid Spencer44eef162007-02-26 01:19:48 +00001230 // Compute some values needed by the remaining shift algorithms
Chris Lattner77527f52009-01-21 18:09:24 +00001231 unsigned wordShift = shiftAmt % APINT_BITS_PER_WORD;
1232 unsigned offset = shiftAmt / APINT_BITS_PER_WORD;
Reid Spencer44eef162007-02-26 01:19:48 +00001233
1234 // If we are shifting whole words, just move whole words
1235 if (wordShift == 0) {
Chris Lattner77527f52009-01-21 18:09:24 +00001236 for (unsigned i = 0; i < getNumWords() - offset; ++i)
Reid Spencer44eef162007-02-26 01:19:48 +00001237 val[i] = pVal[i+offset];
Chris Lattner77527f52009-01-21 18:09:24 +00001238 for (unsigned i = getNumWords()-offset; i < getNumWords(); i++)
Reid Spencer44eef162007-02-26 01:19:48 +00001239 val[i] = 0;
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001240 APInt Result(val, BitWidth);
1241 Result.clearUnusedBits();
1242 return Result;
Reid Spencer44eef162007-02-26 01:19:48 +00001243 }
1244
Eric Christopher820256b2009-08-21 04:06:45 +00001245 // Shift the low order words
Chris Lattner77527f52009-01-21 18:09:24 +00001246 unsigned breakWord = getNumWords() - offset -1;
1247 for (unsigned i = 0; i < breakWord; ++i)
Reid Spencerd99feaf2007-03-01 05:39:56 +00001248 val[i] = (pVal[i+offset] >> wordShift) |
1249 (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift));
Reid Spencer44eef162007-02-26 01:19:48 +00001250 // Shift the break word.
1251 val[breakWord] = pVal[breakWord+offset] >> wordShift;
1252
1253 // Remaining words are 0
Chris Lattner77527f52009-01-21 18:09:24 +00001254 for (unsigned i = breakWord+1; i < getNumWords(); ++i)
Reid Spencer44eef162007-02-26 01:19:48 +00001255 val[i] = 0;
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001256 APInt Result(val, BitWidth);
1257 Result.clearUnusedBits();
1258 return Result;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001259}
1260
Zhou Shenge93db8f2007-02-09 07:48:24 +00001261/// Left-shift this APInt by shiftAmt.
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001262/// @brief Left-shift function.
Dan Gohman105c1d42008-02-29 01:40:47 +00001263APInt APInt::shl(const APInt &shiftAmt) const {
Nick Lewycky030c4502009-01-19 17:42:33 +00001264 // It's undefined behavior in C to shift by BitWidth or greater.
Chris Lattner77527f52009-01-21 18:09:24 +00001265 return shl((unsigned)shiftAmt.getLimitedValue(BitWidth));
Dan Gohman105c1d42008-02-29 01:40:47 +00001266}
1267
Chris Lattner77527f52009-01-21 18:09:24 +00001268APInt APInt::shlSlowCase(unsigned shiftAmt) const {
Reid Spencera5c84d92007-02-25 00:56:44 +00001269 // If all the bits were shifted out, the result is 0. This avoids issues
1270 // with shifting by the size of the integer type, which produces undefined
1271 // results. We define these "undefined results" to always be 0.
1272 if (shiftAmt == BitWidth)
1273 return APInt(BitWidth, 0);
1274
Reid Spencer81ee0202007-05-12 18:01:57 +00001275 // If none of the bits are shifted out, the result is *this. This avoids a
1276 // lshr by the words size in the loop below which can produce incorrect
1277 // results. It also avoids the expensive computation below for a common case.
1278 if (shiftAmt == 0)
1279 return *this;
1280
Reid Spencera5c84d92007-02-25 00:56:44 +00001281 // Create some space for the result.
1282 uint64_t * val = new uint64_t[getNumWords()];
1283
1284 // If we are shifting less than a word, do it the easy way
1285 if (shiftAmt < APINT_BITS_PER_WORD) {
1286 uint64_t carry = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001287 for (unsigned i = 0; i < getNumWords(); i++) {
Reid Spencera5c84d92007-02-25 00:56:44 +00001288 val[i] = pVal[i] << shiftAmt | carry;
1289 carry = pVal[i] >> (APINT_BITS_PER_WORD - shiftAmt);
1290 }
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001291 APInt Result(val, BitWidth);
1292 Result.clearUnusedBits();
1293 return Result;
Reid Spencer632ebdf2007-02-24 20:19:37 +00001294 }
1295
Reid Spencera5c84d92007-02-25 00:56:44 +00001296 // Compute some values needed by the remaining shift algorithms
Chris Lattner77527f52009-01-21 18:09:24 +00001297 unsigned wordShift = shiftAmt % APINT_BITS_PER_WORD;
1298 unsigned offset = shiftAmt / APINT_BITS_PER_WORD;
Reid Spencera5c84d92007-02-25 00:56:44 +00001299
1300 // If we are shifting whole words, just move whole words
1301 if (wordShift == 0) {
Chris Lattner77527f52009-01-21 18:09:24 +00001302 for (unsigned i = 0; i < offset; i++)
Reid Spencera5c84d92007-02-25 00:56:44 +00001303 val[i] = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001304 for (unsigned i = offset; i < getNumWords(); i++)
Reid Spencera5c84d92007-02-25 00:56:44 +00001305 val[i] = pVal[i-offset];
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001306 APInt Result(val, BitWidth);
1307 Result.clearUnusedBits();
1308 return Result;
Reid Spencer632ebdf2007-02-24 20:19:37 +00001309 }
Reid Spencera5c84d92007-02-25 00:56:44 +00001310
1311 // Copy whole words from this to Result.
Chris Lattner77527f52009-01-21 18:09:24 +00001312 unsigned i = getNumWords() - 1;
Reid Spencera5c84d92007-02-25 00:56:44 +00001313 for (; i > offset; --i)
1314 val[i] = pVal[i-offset] << wordShift |
1315 pVal[i-offset-1] >> (APINT_BITS_PER_WORD - wordShift);
Reid Spencerab0e08a2007-02-25 01:08:58 +00001316 val[offset] = pVal[0] << wordShift;
Reid Spencera5c84d92007-02-25 00:56:44 +00001317 for (i = 0; i < offset; ++i)
1318 val[i] = 0;
Benjamin Kramerf9a29752014-10-10 10:18:12 +00001319 APInt Result(val, BitWidth);
1320 Result.clearUnusedBits();
1321 return Result;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001322}
1323
Joey Gouly51c0ae52017-02-07 11:58:22 +00001324// Calculate the rotate amount modulo the bit width.
1325static unsigned rotateModulo(unsigned BitWidth, const APInt &rotateAmt) {
1326 unsigned rotBitWidth = rotateAmt.getBitWidth();
1327 APInt rot = rotateAmt;
1328 if (rotBitWidth < BitWidth) {
1329 // Extend the rotate APInt, so that the urem doesn't divide by 0.
1330 // e.g. APInt(1, 32) would give APInt(1, 0).
1331 rot = rotateAmt.zext(BitWidth);
1332 }
1333 rot = rot.urem(APInt(rot.getBitWidth(), BitWidth));
1334 return rot.getLimitedValue(BitWidth);
1335}
1336
Dan Gohman105c1d42008-02-29 01:40:47 +00001337APInt APInt::rotl(const APInt &rotateAmt) const {
Joey Gouly51c0ae52017-02-07 11:58:22 +00001338 return rotl(rotateModulo(BitWidth, rotateAmt));
Dan Gohman105c1d42008-02-29 01:40:47 +00001339}
1340
Chris Lattner77527f52009-01-21 18:09:24 +00001341APInt APInt::rotl(unsigned rotateAmt) const {
Eli Friedman2aae94f2011-12-22 03:15:35 +00001342 rotateAmt %= BitWidth;
Reid Spencer98ed7db2007-05-14 00:15:28 +00001343 if (rotateAmt == 0)
1344 return *this;
Eli Friedman2aae94f2011-12-22 03:15:35 +00001345 return shl(rotateAmt) | lshr(BitWidth - rotateAmt);
Reid Spencer4c50b522007-05-13 23:44:59 +00001346}
1347
Dan Gohman105c1d42008-02-29 01:40:47 +00001348APInt APInt::rotr(const APInt &rotateAmt) const {
Joey Gouly51c0ae52017-02-07 11:58:22 +00001349 return rotr(rotateModulo(BitWidth, rotateAmt));
Dan Gohman105c1d42008-02-29 01:40:47 +00001350}
1351
Chris Lattner77527f52009-01-21 18:09:24 +00001352APInt APInt::rotr(unsigned rotateAmt) const {
Eli Friedman2aae94f2011-12-22 03:15:35 +00001353 rotateAmt %= BitWidth;
Reid Spencer98ed7db2007-05-14 00:15:28 +00001354 if (rotateAmt == 0)
1355 return *this;
Eli Friedman2aae94f2011-12-22 03:15:35 +00001356 return lshr(rotateAmt) | shl(BitWidth - rotateAmt);
Reid Spencer4c50b522007-05-13 23:44:59 +00001357}
Reid Spencerd99feaf2007-03-01 05:39:56 +00001358
1359// Square Root - this method computes and returns the square root of "this".
1360// Three mechanisms are used for computation. For small values (<= 5 bits),
1361// a table lookup is done. This gets some performance for common cases. For
1362// values using less than 52 bits, the value is converted to double and then
1363// the libc sqrt function is called. The result is rounded and then converted
1364// back to a uint64_t which is then used to construct the result. Finally,
Eric Christopher820256b2009-08-21 04:06:45 +00001365// the Babylonian method for computing square roots is used.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001366APInt APInt::sqrt() const {
1367
1368 // Determine the magnitude of the value.
Chris Lattner77527f52009-01-21 18:09:24 +00001369 unsigned magnitude = getActiveBits();
Reid Spencerd99feaf2007-03-01 05:39:56 +00001370
1371 // Use a fast table for some small values. This also gets rid of some
1372 // rounding errors in libc sqrt for small values.
1373 if (magnitude <= 5) {
Reid Spencer2f6ad4d2007-03-01 17:47:31 +00001374 static const uint8_t results[32] = {
Reid Spencerc8841d22007-03-01 06:23:32 +00001375 /* 0 */ 0,
1376 /* 1- 2 */ 1, 1,
Eric Christopher820256b2009-08-21 04:06:45 +00001377 /* 3- 6 */ 2, 2, 2, 2,
Reid Spencerc8841d22007-03-01 06:23:32 +00001378 /* 7-12 */ 3, 3, 3, 3, 3, 3,
1379 /* 13-20 */ 4, 4, 4, 4, 4, 4, 4, 4,
1380 /* 21-30 */ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
1381 /* 31 */ 6
1382 };
1383 return APInt(BitWidth, results[ (isSingleWord() ? VAL : pVal[0]) ]);
Reid Spencerd99feaf2007-03-01 05:39:56 +00001384 }
1385
1386 // If the magnitude of the value fits in less than 52 bits (the precision of
1387 // an IEEE double precision floating point value), then we can use the
1388 // libc sqrt function which will probably use a hardware sqrt computation.
1389 // This should be faster than the algorithm below.
Jeff Cohenb622c112007-03-05 00:00:42 +00001390 if (magnitude < 52) {
Eric Christopher820256b2009-08-21 04:06:45 +00001391 return APInt(BitWidth,
Reid Spencerd99feaf2007-03-01 05:39:56 +00001392 uint64_t(::round(::sqrt(double(isSingleWord()?VAL:pVal[0])))));
Jeff Cohenb622c112007-03-05 00:00:42 +00001393 }
Reid Spencerd99feaf2007-03-01 05:39:56 +00001394
1395 // Okay, all the short cuts are exhausted. We must compute it. The following
1396 // is a classical Babylonian method for computing the square root. This code
Sanjay Patel4cb54e02014-09-11 15:41:01 +00001397 // was adapted to APInt from a wikipedia article on such computations.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001398 // See http://www.wikipedia.org/ and go to the page named
Eric Christopher820256b2009-08-21 04:06:45 +00001399 // Calculate_an_integer_square_root.
Chris Lattner77527f52009-01-21 18:09:24 +00001400 unsigned nbits = BitWidth, i = 4;
Reid Spencerd99feaf2007-03-01 05:39:56 +00001401 APInt testy(BitWidth, 16);
1402 APInt x_old(BitWidth, 1);
1403 APInt x_new(BitWidth, 0);
1404 APInt two(BitWidth, 2);
1405
1406 // Select a good starting value using binary logarithms.
Eric Christopher820256b2009-08-21 04:06:45 +00001407 for (;; i += 2, testy = testy.shl(2))
Reid Spencerd99feaf2007-03-01 05:39:56 +00001408 if (i >= nbits || this->ule(testy)) {
1409 x_old = x_old.shl(i / 2);
1410 break;
1411 }
1412
Eric Christopher820256b2009-08-21 04:06:45 +00001413 // Use the Babylonian method to arrive at the integer square root:
Reid Spencerd99feaf2007-03-01 05:39:56 +00001414 for (;;) {
1415 x_new = (this->udiv(x_old) + x_old).udiv(two);
1416 if (x_old.ule(x_new))
1417 break;
1418 x_old = x_new;
1419 }
1420
1421 // Make sure we return the closest approximation
Eric Christopher820256b2009-08-21 04:06:45 +00001422 // NOTE: The rounding calculation below is correct. It will produce an
Reid Spencercf817562007-03-02 04:21:55 +00001423 // off-by-one discrepancy with results from pari/gp. That discrepancy has been
Eric Christopher820256b2009-08-21 04:06:45 +00001424 // determined to be a rounding issue with pari/gp as it begins to use a
Reid Spencercf817562007-03-02 04:21:55 +00001425 // floating point representation after 192 bits. There are no discrepancies
1426 // between this algorithm and pari/gp for bit widths < 192 bits.
Reid Spencerd99feaf2007-03-01 05:39:56 +00001427 APInt square(x_old * x_old);
1428 APInt nextSquare((x_old + 1) * (x_old +1));
1429 if (this->ult(square))
1430 return x_old;
David Blaikie54c94622011-12-01 20:58:30 +00001431 assert(this->ule(nextSquare) && "Error in APInt::sqrt computation");
1432 APInt midpoint((nextSquare - square).udiv(two));
1433 APInt offset(*this - square);
1434 if (offset.ult(midpoint))
1435 return x_old;
Reid Spencerd99feaf2007-03-01 05:39:56 +00001436 return x_old + 1;
1437}
1438
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001439/// Computes the multiplicative inverse of this APInt for a given modulo. The
1440/// iterative extended Euclidean algorithm is used to solve for this value,
1441/// however we simplify it to speed up calculating only the inverse, and take
1442/// advantage of div+rem calculations. We also use some tricks to avoid copying
1443/// (potentially large) APInts around.
1444APInt APInt::multiplicativeInverse(const APInt& modulo) const {
1445 assert(ult(modulo) && "This APInt must be smaller than the modulo");
1446
1447 // Using the properties listed at the following web page (accessed 06/21/08):
1448 // http://www.numbertheory.org/php/euclid.html
1449 // (especially the properties numbered 3, 4 and 9) it can be proved that
1450 // BitWidth bits suffice for all the computations in the algorithm implemented
1451 // below. More precisely, this number of bits suffice if the multiplicative
1452 // inverse exists, but may not suffice for the general extended Euclidean
1453 // algorithm.
1454
1455 APInt r[2] = { modulo, *this };
1456 APInt t[2] = { APInt(BitWidth, 0), APInt(BitWidth, 1) };
1457 APInt q(BitWidth, 0);
Eric Christopher820256b2009-08-21 04:06:45 +00001458
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001459 unsigned i;
1460 for (i = 0; r[i^1] != 0; i ^= 1) {
1461 // An overview of the math without the confusing bit-flipping:
1462 // q = r[i-2] / r[i-1]
1463 // r[i] = r[i-2] % r[i-1]
1464 // t[i] = t[i-2] - t[i-1] * q
1465 udivrem(r[i], r[i^1], q, r[i]);
1466 t[i] -= t[i^1] * q;
1467 }
1468
1469 // If this APInt and the modulo are not coprime, there is no multiplicative
1470 // inverse, so return 0. We check this by looking at the next-to-last
1471 // remainder, which is the gcd(*this,modulo) as calculated by the Euclidean
1472 // algorithm.
1473 if (r[i] != 1)
1474 return APInt(BitWidth, 0);
1475
1476 // The next-to-last t is the multiplicative inverse. However, we are
1477 // interested in a positive inverse. Calcuate a positive one from a negative
1478 // one if necessary. A simple addition of the modulo suffices because
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00001479 // abs(t[i]) is known to be less than *this/2 (see the link above).
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00001480 return t[i].isNegative() ? t[i] + modulo : t[i];
1481}
1482
Jay Foadfe0c6482009-04-30 10:15:35 +00001483/// Calculate the magic numbers required to implement a signed integer division
1484/// by a constant as a sequence of multiplies, adds and shifts. Requires that
1485/// the divisor not be 0, 1, or -1. Taken from "Hacker's Delight", Henry S.
1486/// Warren, Jr., chapter 10.
1487APInt::ms APInt::magic() const {
1488 const APInt& d = *this;
1489 unsigned p;
1490 APInt ad, anc, delta, q1, r1, q2, r2, t;
Jay Foadfe0c6482009-04-30 10:15:35 +00001491 APInt signedMin = APInt::getSignedMinValue(d.getBitWidth());
Jay Foadfe0c6482009-04-30 10:15:35 +00001492 struct ms mag;
Eric Christopher820256b2009-08-21 04:06:45 +00001493
Jay Foadfe0c6482009-04-30 10:15:35 +00001494 ad = d.abs();
1495 t = signedMin + (d.lshr(d.getBitWidth() - 1));
1496 anc = t - 1 - t.urem(ad); // absolute value of nc
1497 p = d.getBitWidth() - 1; // initialize p
1498 q1 = signedMin.udiv(anc); // initialize q1 = 2p/abs(nc)
1499 r1 = signedMin - q1*anc; // initialize r1 = rem(2p,abs(nc))
1500 q2 = signedMin.udiv(ad); // initialize q2 = 2p/abs(d)
1501 r2 = signedMin - q2*ad; // initialize r2 = rem(2p,abs(d))
1502 do {
1503 p = p + 1;
1504 q1 = q1<<1; // update q1 = 2p/abs(nc)
1505 r1 = r1<<1; // update r1 = rem(2p/abs(nc))
1506 if (r1.uge(anc)) { // must be unsigned comparison
1507 q1 = q1 + 1;
1508 r1 = r1 - anc;
1509 }
1510 q2 = q2<<1; // update q2 = 2p/abs(d)
1511 r2 = r2<<1; // update r2 = rem(2p/abs(d))
1512 if (r2.uge(ad)) { // must be unsigned comparison
1513 q2 = q2 + 1;
1514 r2 = r2 - ad;
1515 }
1516 delta = ad - r2;
Cameron Zwarich8731d0c2011-02-21 00:22:02 +00001517 } while (q1.ult(delta) || (q1 == delta && r1 == 0));
Eric Christopher820256b2009-08-21 04:06:45 +00001518
Jay Foadfe0c6482009-04-30 10:15:35 +00001519 mag.m = q2 + 1;
1520 if (d.isNegative()) mag.m = -mag.m; // resulting magic number
1521 mag.s = p - d.getBitWidth(); // resulting shift
1522 return mag;
1523}
1524
1525/// Calculate the magic numbers required to implement an unsigned integer
1526/// division by a constant as a sequence of multiplies, adds and shifts.
1527/// Requires that the divisor not be 0. Taken from "Hacker's Delight", Henry
1528/// S. Warren, Jr., chapter 10.
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001529/// LeadingZeros can be used to simplify the calculation if the upper bits
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001530/// of the divided value are known zero.
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001531APInt::mu APInt::magicu(unsigned LeadingZeros) const {
Jay Foadfe0c6482009-04-30 10:15:35 +00001532 const APInt& d = *this;
1533 unsigned p;
1534 APInt nc, delta, q1, r1, q2, r2;
1535 struct mu magu;
1536 magu.a = 0; // initialize "add" indicator
Benjamin Kramer09a51ba2011-03-17 20:39:06 +00001537 APInt allOnes = APInt::getAllOnesValue(d.getBitWidth()).lshr(LeadingZeros);
Jay Foadfe0c6482009-04-30 10:15:35 +00001538 APInt signedMin = APInt::getSignedMinValue(d.getBitWidth());
1539 APInt signedMax = APInt::getSignedMaxValue(d.getBitWidth());
1540
Benjamin Kramer3aab6a82012-07-11 18:31:59 +00001541 nc = allOnes - (allOnes - d).urem(d);
Jay Foadfe0c6482009-04-30 10:15:35 +00001542 p = d.getBitWidth() - 1; // initialize p
1543 q1 = signedMin.udiv(nc); // initialize q1 = 2p/nc
1544 r1 = signedMin - q1*nc; // initialize r1 = rem(2p,nc)
1545 q2 = signedMax.udiv(d); // initialize q2 = (2p-1)/d
1546 r2 = signedMax - q2*d; // initialize r2 = rem((2p-1),d)
1547 do {
1548 p = p + 1;
1549 if (r1.uge(nc - r1)) {
1550 q1 = q1 + q1 + 1; // update q1
1551 r1 = r1 + r1 - nc; // update r1
1552 }
1553 else {
1554 q1 = q1+q1; // update q1
1555 r1 = r1+r1; // update r1
1556 }
1557 if ((r2 + 1).uge(d - r2)) {
1558 if (q2.uge(signedMax)) magu.a = 1;
1559 q2 = q2+q2 + 1; // update q2
1560 r2 = r2+r2 + 1 - d; // update r2
1561 }
1562 else {
1563 if (q2.uge(signedMin)) magu.a = 1;
1564 q2 = q2+q2; // update q2
1565 r2 = r2+r2 + 1; // update r2
1566 }
1567 delta = d - 1 - r2;
1568 } while (p < d.getBitWidth()*2 &&
1569 (q1.ult(delta) || (q1 == delta && r1 == 0)));
1570 magu.m = q2 + 1; // resulting magic number
1571 magu.s = p - d.getBitWidth(); // resulting shift
1572 return magu;
1573}
1574
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001575/// Implementation of Knuth's Algorithm D (Division of nonnegative integers)
1576/// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The
1577/// variables here have the same names as in the algorithm. Comments explain
1578/// the algorithm and any deviation from it.
Chris Lattner77527f52009-01-21 18:09:24 +00001579static void KnuthDiv(unsigned *u, unsigned *v, unsigned *q, unsigned* r,
1580 unsigned m, unsigned n) {
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001581 assert(u && "Must provide dividend");
1582 assert(v && "Must provide divisor");
1583 assert(q && "Must provide quotient");
Yaron Keren39fc5a62015-03-26 19:45:19 +00001584 assert(u != v && u != q && v != q && "Must use different memory");
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001585 assert(n>1 && "n must be > 1");
1586
Yaron Keren39fc5a62015-03-26 19:45:19 +00001587 // b denotes the base of the number system. In our case b is 2^32.
George Burgess IV381fc0e2016-08-25 01:05:08 +00001588 const uint64_t b = uint64_t(1) << 32;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001589
David Greenef32fcb42010-01-05 01:28:52 +00001590 DEBUG(dbgs() << "KnuthDiv: m=" << m << " n=" << n << '\n');
1591 DEBUG(dbgs() << "KnuthDiv: original:");
1592 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
1593 DEBUG(dbgs() << " by");
1594 DEBUG(for (int i = n; i >0; i--) dbgs() << " " << v[i-1]);
1595 DEBUG(dbgs() << '\n');
Eric Christopher820256b2009-08-21 04:06:45 +00001596 // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of
1597 // u and v by d. Note that we have taken Knuth's advice here to use a power
1598 // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of
1599 // 2 allows us to shift instead of multiply and it is easy to determine the
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001600 // shift amount from the leading zeros. We are basically normalizing the u
1601 // and v so that its high bits are shifted to the top of v's range without
1602 // overflow. Note that this can require an extra word in u so that u must
1603 // be of length m+n+1.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001604 unsigned shift = countLeadingZeros(v[n-1]);
Chris Lattner77527f52009-01-21 18:09:24 +00001605 unsigned v_carry = 0;
1606 unsigned u_carry = 0;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001607 if (shift) {
Chris Lattner77527f52009-01-21 18:09:24 +00001608 for (unsigned i = 0; i < m+n; ++i) {
1609 unsigned u_tmp = u[i] >> (32 - shift);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001610 u[i] = (u[i] << shift) | u_carry;
1611 u_carry = u_tmp;
Reid Spencer100502d2007-02-17 03:16:00 +00001612 }
Chris Lattner77527f52009-01-21 18:09:24 +00001613 for (unsigned i = 0; i < n; ++i) {
1614 unsigned v_tmp = v[i] >> (32 - shift);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001615 v[i] = (v[i] << shift) | v_carry;
1616 v_carry = v_tmp;
1617 }
1618 }
1619 u[m+n] = u_carry;
Yaron Keren39fc5a62015-03-26 19:45:19 +00001620
David Greenef32fcb42010-01-05 01:28:52 +00001621 DEBUG(dbgs() << "KnuthDiv: normal:");
1622 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
1623 DEBUG(dbgs() << " by");
1624 DEBUG(for (int i = n; i >0; i--) dbgs() << " " << v[i-1]);
1625 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001626
1627 // D2. [Initialize j.] Set j to m. This is the loop counter over the places.
1628 int j = m;
1629 do {
David Greenef32fcb42010-01-05 01:28:52 +00001630 DEBUG(dbgs() << "KnuthDiv: quotient digit #" << j << '\n');
Eric Christopher820256b2009-08-21 04:06:45 +00001631 // D3. [Calculate q'.].
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001632 // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q')
1633 // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r')
1634 // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease
1635 // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test
1636 // on v[n-2] determines at high speed most of the cases in which the trial
Eric Christopher820256b2009-08-21 04:06:45 +00001637 // value qp is one too large, and it eliminates all cases where qp is two
1638 // too large.
Reid Spencercb292e42007-02-23 01:57:13 +00001639 uint64_t dividend = ((uint64_t(u[j+n]) << 32) + u[j+n-1]);
David Greenef32fcb42010-01-05 01:28:52 +00001640 DEBUG(dbgs() << "KnuthDiv: dividend == " << dividend << '\n');
Reid Spencercb292e42007-02-23 01:57:13 +00001641 uint64_t qp = dividend / v[n-1];
1642 uint64_t rp = dividend % v[n-1];
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001643 if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) {
1644 qp--;
1645 rp += v[n-1];
Reid Spencerdf6cf5a2007-02-24 10:01:42 +00001646 if (rp < b && (qp == b || qp*v[n-2] > b*rp + u[j+n-2]))
Reid Spencera5e0d202007-02-24 03:58:46 +00001647 qp--;
Reid Spencercb292e42007-02-23 01:57:13 +00001648 }
David Greenef32fcb42010-01-05 01:28:52 +00001649 DEBUG(dbgs() << "KnuthDiv: qp == " << qp << ", rp == " << rp << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001650
Reid Spencercb292e42007-02-23 01:57:13 +00001651 // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with
1652 // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation
1653 // consists of a simple multiplication by a one-place number, combined with
Eric Christopher820256b2009-08-21 04:06:45 +00001654 // a subtraction.
Yaron Keren39fc5a62015-03-26 19:45:19 +00001655 // The digits (u[j+n]...u[j]) should be kept positive; if the result of
1656 // this step is actually negative, (u[j+n]...u[j]) should be left as the
1657 // true value plus b**(n+1), namely as the b's complement of
1658 // the true value, and a "borrow" to the left should be remembered.
Pawel Bylica86ac4472015-04-24 07:38:39 +00001659 int64_t borrow = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001660 for (unsigned i = 0; i < n; ++i) {
Pawel Bylica86ac4472015-04-24 07:38:39 +00001661 uint64_t p = uint64_t(qp) * uint64_t(v[i]);
1662 int64_t subres = int64_t(u[j+i]) - borrow - (unsigned)p;
1663 u[j+i] = (unsigned)subres;
1664 borrow = (p >> 32) - (subres >> 32);
1665 DEBUG(dbgs() << "KnuthDiv: u[j+i] = " << u[j+i]
Daniel Dunbar763ace92009-07-13 05:27:30 +00001666 << ", borrow = " << borrow << '\n');
Reid Spencera5e0d202007-02-24 03:58:46 +00001667 }
Pawel Bylica86ac4472015-04-24 07:38:39 +00001668 bool isNeg = u[j+n] < borrow;
1669 u[j+n] -= (unsigned)borrow;
1670
David Greenef32fcb42010-01-05 01:28:52 +00001671 DEBUG(dbgs() << "KnuthDiv: after subtraction:");
1672 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
1673 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001674
Eric Christopher820256b2009-08-21 04:06:45 +00001675 // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001676 // negative, go to step D6; otherwise go on to step D7.
Chris Lattner77527f52009-01-21 18:09:24 +00001677 q[j] = (unsigned)qp;
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00001678 if (isNeg) {
Eric Christopher820256b2009-08-21 04:06:45 +00001679 // D6. [Add back]. The probability that this step is necessary is very
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001680 // small, on the order of only 2/b. Make sure that test data accounts for
Eric Christopher820256b2009-08-21 04:06:45 +00001681 // this possibility. Decrease q[j] by 1
Reid Spencercb292e42007-02-23 01:57:13 +00001682 q[j]--;
Eric Christopher820256b2009-08-21 04:06:45 +00001683 // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]).
1684 // A carry will occur to the left of u[j+n], and it should be ignored
Reid Spencercb292e42007-02-23 01:57:13 +00001685 // since it cancels with the borrow that occurred in D4.
1686 bool carry = false;
Chris Lattner77527f52009-01-21 18:09:24 +00001687 for (unsigned i = 0; i < n; i++) {
1688 unsigned limit = std::min(u[j+i],v[i]);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001689 u[j+i] += v[i] + carry;
Reid Spencera5e0d202007-02-24 03:58:46 +00001690 carry = u[j+i] < limit || (carry && u[j+i] == limit);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001691 }
Reid Spencera5e0d202007-02-24 03:58:46 +00001692 u[j+n] += carry;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001693 }
David Greenef32fcb42010-01-05 01:28:52 +00001694 DEBUG(dbgs() << "KnuthDiv: after correction:");
Yaron Keren39fc5a62015-03-26 19:45:19 +00001695 DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]);
David Greenef32fcb42010-01-05 01:28:52 +00001696 DEBUG(dbgs() << "\nKnuthDiv: digit result = " << q[j] << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001697
Reid Spencercb292e42007-02-23 01:57:13 +00001698 // D7. [Loop on j.] Decrease j by one. Now if j >= 0, go back to D3.
1699 } while (--j >= 0);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001700
David Greenef32fcb42010-01-05 01:28:52 +00001701 DEBUG(dbgs() << "KnuthDiv: quotient:");
1702 DEBUG(for (int i = m; i >=0; i--) dbgs() <<" " << q[i]);
1703 DEBUG(dbgs() << '\n');
Reid Spencera5e0d202007-02-24 03:58:46 +00001704
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001705 // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired
1706 // remainder may be obtained by dividing u[...] by d. If r is non-null we
1707 // compute the remainder (urem uses this).
1708 if (r) {
1709 // The value d is expressed by the "shift" value above since we avoided
1710 // multiplication by d by using a shift left. So, all we have to do is
Simon Pilgrim0099beb2017-03-09 13:57:04 +00001711 // shift right here.
Reid Spencer468ad9112007-02-24 20:38:01 +00001712 if (shift) {
Chris Lattner77527f52009-01-21 18:09:24 +00001713 unsigned carry = 0;
David Greenef32fcb42010-01-05 01:28:52 +00001714 DEBUG(dbgs() << "KnuthDiv: remainder:");
Reid Spencer468ad9112007-02-24 20:38:01 +00001715 for (int i = n-1; i >= 0; i--) {
1716 r[i] = (u[i] >> shift) | carry;
1717 carry = u[i] << (32 - shift);
David Greenef32fcb42010-01-05 01:28:52 +00001718 DEBUG(dbgs() << " " << r[i]);
Reid Spencer468ad9112007-02-24 20:38:01 +00001719 }
1720 } else {
1721 for (int i = n-1; i >= 0; i--) {
1722 r[i] = u[i];
David Greenef32fcb42010-01-05 01:28:52 +00001723 DEBUG(dbgs() << " " << r[i]);
Reid Spencer468ad9112007-02-24 20:38:01 +00001724 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001725 }
David Greenef32fcb42010-01-05 01:28:52 +00001726 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001727 }
David Greenef32fcb42010-01-05 01:28:52 +00001728 DEBUG(dbgs() << '\n');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001729}
1730
Benjamin Kramerc321e532016-06-08 19:09:22 +00001731void APInt::divide(const APInt &LHS, unsigned lhsWords, const APInt &RHS,
1732 unsigned rhsWords, APInt *Quotient, APInt *Remainder) {
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001733 assert(lhsWords >= rhsWords && "Fractional result");
1734
Eric Christopher820256b2009-08-21 04:06:45 +00001735 // First, compose the values into an array of 32-bit words instead of
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001736 // 64-bit words. This is a necessity of both the "short division" algorithm
Dan Gohman4a618822010-02-10 16:03:48 +00001737 // and the Knuth "classical algorithm" which requires there to be native
Eric Christopher820256b2009-08-21 04:06:45 +00001738 // operations for +, -, and * on an m bit value with an m*2 bit result. We
1739 // can't use 64-bit operands here because we don't have native results of
1740 // 128-bits. Furthermore, casting the 64-bit values to 32-bit values won't
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001741 // work on large-endian machines.
Dan Gohmancff69532009-04-01 18:45:54 +00001742 uint64_t mask = ~0ull >> (sizeof(unsigned)*CHAR_BIT);
Chris Lattner77527f52009-01-21 18:09:24 +00001743 unsigned n = rhsWords * 2;
1744 unsigned m = (lhsWords * 2) - n;
Reid Spencer522ca7c2007-02-25 01:56:07 +00001745
1746 // Allocate space for the temporary values we need either on the stack, if
1747 // it will fit, or on the heap if it won't.
Chris Lattner77527f52009-01-21 18:09:24 +00001748 unsigned SPACE[128];
Craig Topperc10719f2014-04-07 04:17:22 +00001749 unsigned *U = nullptr;
1750 unsigned *V = nullptr;
1751 unsigned *Q = nullptr;
1752 unsigned *R = nullptr;
Reid Spencer522ca7c2007-02-25 01:56:07 +00001753 if ((Remainder?4:3)*n+2*m+1 <= 128) {
1754 U = &SPACE[0];
1755 V = &SPACE[m+n+1];
1756 Q = &SPACE[(m+n+1) + n];
1757 if (Remainder)
1758 R = &SPACE[(m+n+1) + n + (m+n)];
1759 } else {
Chris Lattner77527f52009-01-21 18:09:24 +00001760 U = new unsigned[m + n + 1];
1761 V = new unsigned[n];
1762 Q = new unsigned[m+n];
Reid Spencer522ca7c2007-02-25 01:56:07 +00001763 if (Remainder)
Chris Lattner77527f52009-01-21 18:09:24 +00001764 R = new unsigned[n];
Reid Spencer522ca7c2007-02-25 01:56:07 +00001765 }
1766
1767 // Initialize the dividend
Chris Lattner77527f52009-01-21 18:09:24 +00001768 memset(U, 0, (m+n+1)*sizeof(unsigned));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001769 for (unsigned i = 0; i < lhsWords; ++i) {
Reid Spencer867b4062007-02-22 00:58:45 +00001770 uint64_t tmp = (LHS.getNumWords() == 1 ? LHS.VAL : LHS.pVal[i]);
Chris Lattner77527f52009-01-21 18:09:24 +00001771 U[i * 2] = (unsigned)(tmp & mask);
Dan Gohmancff69532009-04-01 18:45:54 +00001772 U[i * 2 + 1] = (unsigned)(tmp >> (sizeof(unsigned)*CHAR_BIT));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001773 }
1774 U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm.
1775
Reid Spencer522ca7c2007-02-25 01:56:07 +00001776 // Initialize the divisor
Chris Lattner77527f52009-01-21 18:09:24 +00001777 memset(V, 0, (n)*sizeof(unsigned));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001778 for (unsigned i = 0; i < rhsWords; ++i) {
Reid Spencer867b4062007-02-22 00:58:45 +00001779 uint64_t tmp = (RHS.getNumWords() == 1 ? RHS.VAL : RHS.pVal[i]);
Chris Lattner77527f52009-01-21 18:09:24 +00001780 V[i * 2] = (unsigned)(tmp & mask);
Dan Gohmancff69532009-04-01 18:45:54 +00001781 V[i * 2 + 1] = (unsigned)(tmp >> (sizeof(unsigned)*CHAR_BIT));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001782 }
1783
Reid Spencer522ca7c2007-02-25 01:56:07 +00001784 // initialize the quotient and remainder
Chris Lattner77527f52009-01-21 18:09:24 +00001785 memset(Q, 0, (m+n) * sizeof(unsigned));
Reid Spencer522ca7c2007-02-25 01:56:07 +00001786 if (Remainder)
Chris Lattner77527f52009-01-21 18:09:24 +00001787 memset(R, 0, n * sizeof(unsigned));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001788
Eric Christopher820256b2009-08-21 04:06:45 +00001789 // Now, adjust m and n for the Knuth division. n is the number of words in
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001790 // the divisor. m is the number of words by which the dividend exceeds the
Eric Christopher820256b2009-08-21 04:06:45 +00001791 // divisor (i.e. m+n is the length of the dividend). These sizes must not
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001792 // contain any zero words or the Knuth algorithm fails.
1793 for (unsigned i = n; i > 0 && V[i-1] == 0; i--) {
1794 n--;
1795 m++;
1796 }
1797 for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--)
1798 m--;
1799
1800 // If we're left with only a single word for the divisor, Knuth doesn't work
1801 // so we implement the short division algorithm here. This is much simpler
1802 // and faster because we are certain that we can divide a 64-bit quantity
1803 // by a 32-bit quantity at hardware speed and short division is simply a
1804 // series of such operations. This is just like doing short division but we
1805 // are using base 2^32 instead of base 10.
1806 assert(n != 0 && "Divide by zero?");
1807 if (n == 1) {
Chris Lattner77527f52009-01-21 18:09:24 +00001808 unsigned divisor = V[0];
1809 unsigned remainder = 0;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001810 for (int i = m+n-1; i >= 0; i--) {
1811 uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i];
1812 if (partial_dividend == 0) {
1813 Q[i] = 0;
1814 remainder = 0;
1815 } else if (partial_dividend < divisor) {
1816 Q[i] = 0;
Chris Lattner77527f52009-01-21 18:09:24 +00001817 remainder = (unsigned)partial_dividend;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001818 } else if (partial_dividend == divisor) {
1819 Q[i] = 1;
1820 remainder = 0;
1821 } else {
Chris Lattner77527f52009-01-21 18:09:24 +00001822 Q[i] = (unsigned)(partial_dividend / divisor);
1823 remainder = (unsigned)(partial_dividend - (Q[i] * divisor));
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001824 }
1825 }
1826 if (R)
1827 R[0] = remainder;
1828 } else {
1829 // Now we're ready to invoke the Knuth classical divide algorithm. In this
1830 // case n > 1.
1831 KnuthDiv(U, V, Q, R, m, n);
1832 }
1833
1834 // If the caller wants the quotient
1835 if (Quotient) {
1836 // Set up the Quotient value's memory.
1837 if (Quotient->BitWidth != LHS.BitWidth) {
1838 if (Quotient->isSingleWord())
1839 Quotient->VAL = 0;
1840 else
Reid Spencer7c16cd22007-02-26 23:38:21 +00001841 delete [] Quotient->pVal;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001842 Quotient->BitWidth = LHS.BitWidth;
1843 if (!Quotient->isSingleWord())
Reid Spencer58a6a432007-02-21 08:21:52 +00001844 Quotient->pVal = getClearedMemory(Quotient->getNumWords());
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001845 } else
Jay Foad25a5e4c2010-12-01 08:53:58 +00001846 Quotient->clearAllBits();
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001847
Eric Christopher820256b2009-08-21 04:06:45 +00001848 // The quotient is in Q. Reconstitute the quotient into Quotient's low
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001849 // order words.
Yaron Keren39fc5a62015-03-26 19:45:19 +00001850 // This case is currently dead as all users of divide() handle trivial cases
1851 // earlier.
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001852 if (lhsWords == 1) {
Eric Christopher820256b2009-08-21 04:06:45 +00001853 uint64_t tmp =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001854 uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2));
1855 if (Quotient->isSingleWord())
1856 Quotient->VAL = tmp;
1857 else
1858 Quotient->pVal[0] = tmp;
1859 } else {
1860 assert(!Quotient->isSingleWord() && "Quotient APInt not large enough");
1861 for (unsigned i = 0; i < lhsWords; ++i)
Eric Christopher820256b2009-08-21 04:06:45 +00001862 Quotient->pVal[i] =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001863 uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1864 }
1865 }
1866
1867 // If the caller wants the remainder
1868 if (Remainder) {
1869 // Set up the Remainder value's memory.
1870 if (Remainder->BitWidth != RHS.BitWidth) {
1871 if (Remainder->isSingleWord())
1872 Remainder->VAL = 0;
1873 else
Reid Spencer7c16cd22007-02-26 23:38:21 +00001874 delete [] Remainder->pVal;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001875 Remainder->BitWidth = RHS.BitWidth;
1876 if (!Remainder->isSingleWord())
Reid Spencer58a6a432007-02-21 08:21:52 +00001877 Remainder->pVal = getClearedMemory(Remainder->getNumWords());
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001878 } else
Jay Foad25a5e4c2010-12-01 08:53:58 +00001879 Remainder->clearAllBits();
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001880
1881 // The remainder is in R. Reconstitute the remainder into Remainder's low
1882 // order words.
1883 if (rhsWords == 1) {
Eric Christopher820256b2009-08-21 04:06:45 +00001884 uint64_t tmp =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001885 uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2));
1886 if (Remainder->isSingleWord())
1887 Remainder->VAL = tmp;
1888 else
1889 Remainder->pVal[0] = tmp;
1890 } else {
1891 assert(!Remainder->isSingleWord() && "Remainder APInt not large enough");
1892 for (unsigned i = 0; i < rhsWords; ++i)
Eric Christopher820256b2009-08-21 04:06:45 +00001893 Remainder->pVal[i] =
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001894 uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2));
1895 }
1896 }
1897
1898 // Clean up the memory we allocated.
Reid Spencer522ca7c2007-02-25 01:56:07 +00001899 if (U != &SPACE[0]) {
1900 delete [] U;
1901 delete [] V;
1902 delete [] Q;
1903 delete [] R;
1904 }
Reid Spencer100502d2007-02-17 03:16:00 +00001905}
1906
Reid Spencer1d072122007-02-16 22:36:51 +00001907APInt APInt::udiv(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +00001908 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer39867762007-02-17 02:07:07 +00001909
1910 // First, deal with the easy case
1911 if (isSingleWord()) {
1912 assert(RHS.VAL != 0 && "Divide by zero?");
1913 return APInt(BitWidth, VAL / RHS.VAL);
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001914 }
Reid Spencer39867762007-02-17 02:07:07 +00001915
Reid Spencer39867762007-02-17 02:07:07 +00001916 // Get some facts about the LHS and RHS number of bits and words
Chris Lattner77527f52009-01-21 18:09:24 +00001917 unsigned rhsBits = RHS.getActiveBits();
1918 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001919 assert(rhsWords && "Divided by zero???");
Chris Lattner77527f52009-01-21 18:09:24 +00001920 unsigned lhsBits = this->getActiveBits();
1921 unsigned lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001922
1923 // Deal with some degenerate cases
Eric Christopher820256b2009-08-21 04:06:45 +00001924 if (!lhsWords)
Reid Spencer58a6a432007-02-21 08:21:52 +00001925 // 0 / X ===> 0
Eric Christopher820256b2009-08-21 04:06:45 +00001926 return APInt(BitWidth, 0);
Reid Spencer58a6a432007-02-21 08:21:52 +00001927 else if (lhsWords < rhsWords || this->ult(RHS)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001928 // X / Y ===> 0, iff X < Y
Reid Spencer58a6a432007-02-21 08:21:52 +00001929 return APInt(BitWidth, 0);
1930 } else if (*this == RHS) {
1931 // X / X ===> 1
1932 return APInt(BitWidth, 1);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001933 } else if (lhsWords == 1 && rhsWords == 1) {
Reid Spencer39867762007-02-17 02:07:07 +00001934 // All high words are zero, just use native divide
Reid Spencer58a6a432007-02-21 08:21:52 +00001935 return APInt(BitWidth, this->pVal[0] / RHS.pVal[0]);
Reid Spencer39867762007-02-17 02:07:07 +00001936 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001937
1938 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
1939 APInt Quotient(1,0); // to hold result.
Craig Topperc10719f2014-04-07 04:17:22 +00001940 divide(*this, lhsWords, RHS, rhsWords, &Quotient, nullptr);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001941 return Quotient;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001942}
1943
Jakub Staszak6605c602013-02-20 00:17:42 +00001944APInt APInt::sdiv(const APInt &RHS) const {
1945 if (isNegative()) {
1946 if (RHS.isNegative())
1947 return (-(*this)).udiv(-RHS);
1948 return -((-(*this)).udiv(RHS));
1949 }
1950 if (RHS.isNegative())
1951 return -(this->udiv(-RHS));
1952 return this->udiv(RHS);
1953}
1954
Reid Spencer1d072122007-02-16 22:36:51 +00001955APInt APInt::urem(const APInt& RHS) const {
Reid Spencera32372d12007-02-17 00:18:01 +00001956 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
Reid Spencer39867762007-02-17 02:07:07 +00001957 if (isSingleWord()) {
1958 assert(RHS.VAL != 0 && "Remainder by zero?");
1959 return APInt(BitWidth, VAL % RHS.VAL);
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001960 }
Reid Spencer39867762007-02-17 02:07:07 +00001961
Reid Spencer58a6a432007-02-21 08:21:52 +00001962 // Get some facts about the LHS
Chris Lattner77527f52009-01-21 18:09:24 +00001963 unsigned lhsBits = getActiveBits();
1964 unsigned lhsWords = !lhsBits ? 0 : (whichWord(lhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001965
1966 // Get some facts about the RHS
Chris Lattner77527f52009-01-21 18:09:24 +00001967 unsigned rhsBits = RHS.getActiveBits();
1968 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer39867762007-02-17 02:07:07 +00001969 assert(rhsWords && "Performing remainder operation by zero ???");
1970
Reid Spencer39867762007-02-17 02:07:07 +00001971 // Check the degenerate cases
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001972 if (lhsWords == 0) {
Reid Spencer58a6a432007-02-21 08:21:52 +00001973 // 0 % Y ===> 0
1974 return APInt(BitWidth, 0);
1975 } else if (lhsWords < rhsWords || this->ult(RHS)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001976 // X % Y ===> X, iff X < Y
Reid Spencer58a6a432007-02-21 08:21:52 +00001977 return *this;
1978 } else if (*this == RHS) {
Reid Spencer39867762007-02-17 02:07:07 +00001979 // X % X == 0;
Reid Spencer58a6a432007-02-21 08:21:52 +00001980 return APInt(BitWidth, 0);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001981 } else if (lhsWords == 1) {
Reid Spencer39867762007-02-17 02:07:07 +00001982 // All high words are zero, just use native remainder
Reid Spencer58a6a432007-02-21 08:21:52 +00001983 return APInt(BitWidth, pVal[0] % RHS.pVal[0]);
Reid Spencer39867762007-02-17 02:07:07 +00001984 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001985
Reid Spencer4c50b522007-05-13 23:44:59 +00001986 // We have to compute it the hard way. Invoke the Knuth divide algorithm.
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001987 APInt Remainder(1,0);
Craig Topperc10719f2014-04-07 04:17:22 +00001988 divide(*this, lhsWords, RHS, rhsWords, nullptr, &Remainder);
Reid Spencerfb77b2b2007-02-20 08:51:03 +00001989 return Remainder;
Zhou Shengfbf61ea2007-02-08 14:35:19 +00001990}
Reid Spencer100502d2007-02-17 03:16:00 +00001991
Jakub Staszak6605c602013-02-20 00:17:42 +00001992APInt APInt::srem(const APInt &RHS) const {
1993 if (isNegative()) {
1994 if (RHS.isNegative())
1995 return -((-(*this)).urem(-RHS));
1996 return -((-(*this)).urem(RHS));
1997 }
1998 if (RHS.isNegative())
1999 return this->urem(-RHS);
2000 return this->urem(RHS);
2001}
2002
Eric Christopher820256b2009-08-21 04:06:45 +00002003void APInt::udivrem(const APInt &LHS, const APInt &RHS,
Reid Spencer4c50b522007-05-13 23:44:59 +00002004 APInt &Quotient, APInt &Remainder) {
David Majnemer7f039202014-12-14 09:41:56 +00002005 assert(LHS.BitWidth == RHS.BitWidth && "Bit widths must be the same");
2006
2007 // First, deal with the easy case
2008 if (LHS.isSingleWord()) {
2009 assert(RHS.VAL != 0 && "Divide by zero?");
2010 uint64_t QuotVal = LHS.VAL / RHS.VAL;
2011 uint64_t RemVal = LHS.VAL % RHS.VAL;
2012 Quotient = APInt(LHS.BitWidth, QuotVal);
2013 Remainder = APInt(LHS.BitWidth, RemVal);
2014 return;
2015 }
2016
Reid Spencer4c50b522007-05-13 23:44:59 +00002017 // Get some size facts about the dividend and divisor
Chris Lattner77527f52009-01-21 18:09:24 +00002018 unsigned lhsBits = LHS.getActiveBits();
2019 unsigned lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1);
2020 unsigned rhsBits = RHS.getActiveBits();
2021 unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1);
Reid Spencer4c50b522007-05-13 23:44:59 +00002022
2023 // Check the degenerate cases
Eric Christopher820256b2009-08-21 04:06:45 +00002024 if (lhsWords == 0) {
Reid Spencer4c50b522007-05-13 23:44:59 +00002025 Quotient = 0; // 0 / Y ===> 0
2026 Remainder = 0; // 0 % Y ===> 0
2027 return;
Eric Christopher820256b2009-08-21 04:06:45 +00002028 }
2029
2030 if (lhsWords < rhsWords || LHS.ult(RHS)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002031 Remainder = LHS; // X % Y ===> X, iff X < Y
2032 Quotient = 0; // X / Y ===> 0, iff X < Y
Reid Spencer4c50b522007-05-13 23:44:59 +00002033 return;
Eric Christopher820256b2009-08-21 04:06:45 +00002034 }
2035
Reid Spencer4c50b522007-05-13 23:44:59 +00002036 if (LHS == RHS) {
2037 Quotient = 1; // X / X ===> 1
2038 Remainder = 0; // X % X ===> 0;
2039 return;
Eric Christopher820256b2009-08-21 04:06:45 +00002040 }
2041
Reid Spencer4c50b522007-05-13 23:44:59 +00002042 if (lhsWords == 1 && rhsWords == 1) {
2043 // There is only one word to consider so use the native versions.
Wojciech Matyjewicz41b744d2008-06-23 19:39:50 +00002044 uint64_t lhsValue = LHS.isSingleWord() ? LHS.VAL : LHS.pVal[0];
2045 uint64_t rhsValue = RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0];
2046 Quotient = APInt(LHS.getBitWidth(), lhsValue / rhsValue);
2047 Remainder = APInt(LHS.getBitWidth(), lhsValue % rhsValue);
Reid Spencer4c50b522007-05-13 23:44:59 +00002048 return;
2049 }
2050
2051 // Okay, lets do it the long way
2052 divide(LHS, lhsWords, RHS, rhsWords, &Quotient, &Remainder);
2053}
2054
Jakub Staszak6605c602013-02-20 00:17:42 +00002055void APInt::sdivrem(const APInt &LHS, const APInt &RHS,
2056 APInt &Quotient, APInt &Remainder) {
2057 if (LHS.isNegative()) {
2058 if (RHS.isNegative())
2059 APInt::udivrem(-LHS, -RHS, Quotient, Remainder);
2060 else {
2061 APInt::udivrem(-LHS, RHS, Quotient, Remainder);
2062 Quotient = -Quotient;
2063 }
2064 Remainder = -Remainder;
2065 } else if (RHS.isNegative()) {
2066 APInt::udivrem(LHS, -RHS, Quotient, Remainder);
2067 Quotient = -Quotient;
2068 } else {
2069 APInt::udivrem(LHS, RHS, Quotient, Remainder);
2070 }
2071}
2072
Chris Lattner2c819b02010-10-13 23:54:10 +00002073APInt APInt::sadd_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00002074 APInt Res = *this+RHS;
2075 Overflow = isNonNegative() == RHS.isNonNegative() &&
2076 Res.isNonNegative() != isNonNegative();
2077 return Res;
2078}
2079
Chris Lattner698661c2010-10-14 00:05:07 +00002080APInt APInt::uadd_ov(const APInt &RHS, bool &Overflow) const {
2081 APInt Res = *this+RHS;
2082 Overflow = Res.ult(RHS);
2083 return Res;
2084}
2085
Chris Lattner2c819b02010-10-13 23:54:10 +00002086APInt APInt::ssub_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00002087 APInt Res = *this - RHS;
2088 Overflow = isNonNegative() != RHS.isNonNegative() &&
2089 Res.isNonNegative() != isNonNegative();
2090 return Res;
2091}
2092
Chris Lattner698661c2010-10-14 00:05:07 +00002093APInt APInt::usub_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattnerb9681ad2010-10-14 00:30:00 +00002094 APInt Res = *this-RHS;
2095 Overflow = Res.ugt(*this);
Chris Lattner698661c2010-10-14 00:05:07 +00002096 return Res;
2097}
2098
Chris Lattner2c819b02010-10-13 23:54:10 +00002099APInt APInt::sdiv_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00002100 // MININT/-1 --> overflow.
2101 Overflow = isMinSignedValue() && RHS.isAllOnesValue();
2102 return sdiv(RHS);
2103}
2104
Chris Lattner2c819b02010-10-13 23:54:10 +00002105APInt APInt::smul_ov(const APInt &RHS, bool &Overflow) const {
Chris Lattner79bdd882010-10-13 23:46:33 +00002106 APInt Res = *this * RHS;
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +00002107
Chris Lattner79bdd882010-10-13 23:46:33 +00002108 if (*this != 0 && RHS != 0)
2109 Overflow = Res.sdiv(RHS) != *this || Res.sdiv(*this) != RHS;
2110 else
2111 Overflow = false;
2112 return Res;
2113}
2114
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00002115APInt APInt::umul_ov(const APInt &RHS, bool &Overflow) const {
2116 APInt Res = *this * RHS;
2117
2118 if (*this != 0 && RHS != 0)
2119 Overflow = Res.udiv(RHS) != *this || Res.udiv(*this) != RHS;
2120 else
2121 Overflow = false;
2122 return Res;
2123}
2124
David Majnemera2521382014-10-13 21:48:30 +00002125APInt APInt::sshl_ov(const APInt &ShAmt, bool &Overflow) const {
2126 Overflow = ShAmt.uge(getBitWidth());
Chris Lattner79bdd882010-10-13 23:46:33 +00002127 if (Overflow)
David Majnemera2521382014-10-13 21:48:30 +00002128 return APInt(BitWidth, 0);
Chris Lattner79bdd882010-10-13 23:46:33 +00002129
2130 if (isNonNegative()) // Don't allow sign change.
David Majnemera2521382014-10-13 21:48:30 +00002131 Overflow = ShAmt.uge(countLeadingZeros());
Chris Lattner79bdd882010-10-13 23:46:33 +00002132 else
David Majnemera2521382014-10-13 21:48:30 +00002133 Overflow = ShAmt.uge(countLeadingOnes());
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +00002134
Chris Lattner79bdd882010-10-13 23:46:33 +00002135 return *this << ShAmt;
2136}
2137
David Majnemera2521382014-10-13 21:48:30 +00002138APInt APInt::ushl_ov(const APInt &ShAmt, bool &Overflow) const {
2139 Overflow = ShAmt.uge(getBitWidth());
2140 if (Overflow)
2141 return APInt(BitWidth, 0);
2142
2143 Overflow = ShAmt.ugt(countLeadingZeros());
2144
2145 return *this << ShAmt;
2146}
2147
Chris Lattner79bdd882010-10-13 23:46:33 +00002148
2149
2150
Benjamin Kramer92d89982010-07-14 22:38:02 +00002151void APInt::fromString(unsigned numbits, StringRef str, uint8_t radix) {
Reid Spencer1ba83352007-02-21 03:55:44 +00002152 // Check our assumptions here
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00002153 assert(!str.empty() && "Invalid string length");
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +00002154 assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 ||
Douglas Gregor663c0682011-09-14 15:54:46 +00002155 radix == 36) &&
2156 "Radix should be 2, 8, 10, 16, or 36!");
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00002157
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00002158 StringRef::iterator p = str.begin();
2159 size_t slen = str.size();
2160 bool isNeg = *p == '-';
Erick Tryzelaar1264bcb2009-08-21 03:15:14 +00002161 if (*p == '-' || *p == '+') {
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00002162 p++;
2163 slen--;
Eric Christopher43a1dec2009-08-21 04:10:31 +00002164 assert(slen && "String is only a sign, needs a value.");
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00002165 }
Chris Lattnerdad2d092007-05-03 18:15:36 +00002166 assert((slen <= numbits || radix != 2) && "Insufficient bit width");
Chris Lattnerb869a0a2009-04-25 18:34:04 +00002167 assert(((slen-1)*3 <= numbits || radix != 8) && "Insufficient bit width");
2168 assert(((slen-1)*4 <= numbits || radix != 16) && "Insufficient bit width");
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002169 assert((((slen-1)*64)/22 <= numbits || radix != 10) &&
2170 "Insufficient bit width");
Reid Spencer1ba83352007-02-21 03:55:44 +00002171
2172 // Allocate memory
2173 if (!isSingleWord())
2174 pVal = getClearedMemory(getNumWords());
2175
2176 // Figure out if we can shift instead of multiply
Chris Lattner77527f52009-01-21 18:09:24 +00002177 unsigned shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0);
Reid Spencer1ba83352007-02-21 03:55:44 +00002178
2179 // Set up an APInt for the digit to add outside the loop so we don't
2180 // constantly construct/destruct it.
2181 APInt apdigit(getBitWidth(), 0);
2182 APInt apradix(getBitWidth(), radix);
2183
2184 // Enter digit traversal loop
Daniel Dunbar3a1efd112009-08-13 02:33:34 +00002185 for (StringRef::iterator e = str.end(); p != e; ++p) {
Erick Tryzelaardadb15712009-08-21 03:15:28 +00002186 unsigned digit = getDigit(*p, radix);
Erick Tryzelaar60964092009-08-21 06:48:37 +00002187 assert(digit < radix && "Invalid character in digit string");
Reid Spencer1ba83352007-02-21 03:55:44 +00002188
Reid Spencera93c9812007-05-16 19:18:22 +00002189 // Shift or multiply the value by the radix
Chris Lattnerb869a0a2009-04-25 18:34:04 +00002190 if (slen > 1) {
2191 if (shift)
2192 *this <<= shift;
2193 else
2194 *this *= apradix;
2195 }
Reid Spencer1ba83352007-02-21 03:55:44 +00002196
2197 // Add in the digit we just interpreted
Reid Spencer632ebdf2007-02-24 20:19:37 +00002198 if (apdigit.isSingleWord())
2199 apdigit.VAL = digit;
2200 else
2201 apdigit.pVal[0] = digit;
Reid Spencer1ba83352007-02-21 03:55:44 +00002202 *this += apdigit;
Reid Spencer100502d2007-02-17 03:16:00 +00002203 }
Reid Spencerb6b5cc32007-02-25 23:44:53 +00002204 // If its negative, put it in two's complement form
Reid Spenceraa8dcfe2007-02-26 07:44:38 +00002205 if (isNeg) {
Jakub Staszak773be0c2013-03-20 23:56:19 +00002206 --(*this);
Jay Foad25a5e4c2010-12-01 08:53:58 +00002207 this->flipAllBits();
Reid Spencerb6b5cc32007-02-25 23:44:53 +00002208 }
Reid Spencer100502d2007-02-17 03:16:00 +00002209}
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002210
Chris Lattner17f71652008-08-17 07:19:36 +00002211void APInt::toString(SmallVectorImpl<char> &Str, unsigned Radix,
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002212 bool Signed, bool formatAsCLiteral) const {
Simon Pilgrim4c0ea9d2017-02-23 16:07:04 +00002213 assert((Radix == 10 || Radix == 8 || Radix == 16 || Radix == 2 ||
Douglas Gregor663c0682011-09-14 15:54:46 +00002214 Radix == 36) &&
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00002215 "Radix should be 2, 8, 10, 16, or 36!");
Eric Christopher820256b2009-08-21 04:06:45 +00002216
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002217 const char *Prefix = "";
2218 if (formatAsCLiteral) {
2219 switch (Radix) {
2220 case 2:
2221 // Binary literals are a non-standard extension added in gcc 4.3:
2222 // http://gcc.gnu.org/onlinedocs/gcc-4.3.0/gcc/Binary-constants.html
2223 Prefix = "0b";
2224 break;
2225 case 8:
2226 Prefix = "0";
2227 break;
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00002228 case 10:
2229 break; // No prefix
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002230 case 16:
2231 Prefix = "0x";
2232 break;
Dylan Noblesmith1c419ff2011-12-16 20:36:31 +00002233 default:
2234 llvm_unreachable("Invalid radix!");
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002235 }
2236 }
2237
Chris Lattner17f71652008-08-17 07:19:36 +00002238 // First, check for a zero value and just short circuit the logic below.
2239 if (*this == 0) {
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002240 while (*Prefix) {
2241 Str.push_back(*Prefix);
2242 ++Prefix;
2243 };
Chris Lattner17f71652008-08-17 07:19:36 +00002244 Str.push_back('0');
2245 return;
2246 }
Eric Christopher820256b2009-08-21 04:06:45 +00002247
Douglas Gregor663c0682011-09-14 15:54:46 +00002248 static const char Digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Eric Christopher820256b2009-08-21 04:06:45 +00002249
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002250 if (isSingleWord()) {
Chris Lattner17f71652008-08-17 07:19:36 +00002251 char Buffer[65];
2252 char *BufPtr = Buffer+65;
Eric Christopher820256b2009-08-21 04:06:45 +00002253
Chris Lattner17f71652008-08-17 07:19:36 +00002254 uint64_t N;
Chris Lattnerb91c9032010-08-18 00:33:47 +00002255 if (!Signed) {
Chris Lattner17f71652008-08-17 07:19:36 +00002256 N = getZExtValue();
Chris Lattnerb91c9032010-08-18 00:33:47 +00002257 } else {
2258 int64_t I = getSExtValue();
2259 if (I >= 0) {
2260 N = I;
2261 } else {
2262 Str.push_back('-');
2263 N = -(uint64_t)I;
2264 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002265 }
Eric Christopher820256b2009-08-21 04:06:45 +00002266
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002267 while (*Prefix) {
2268 Str.push_back(*Prefix);
2269 ++Prefix;
2270 };
2271
Chris Lattner17f71652008-08-17 07:19:36 +00002272 while (N) {
2273 *--BufPtr = Digits[N % Radix];
2274 N /= Radix;
2275 }
2276 Str.append(BufPtr, Buffer+65);
2277 return;
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002278 }
2279
Chris Lattner17f71652008-08-17 07:19:36 +00002280 APInt Tmp(*this);
Eric Christopher820256b2009-08-21 04:06:45 +00002281
Chris Lattner17f71652008-08-17 07:19:36 +00002282 if (Signed && isNegative()) {
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002283 // They want to print the signed version and it is a negative value
2284 // Flip the bits and add one to turn it into the equivalent positive
2285 // value and put a '-' in the result.
Jay Foad25a5e4c2010-12-01 08:53:58 +00002286 Tmp.flipAllBits();
Jakub Staszak773be0c2013-03-20 23:56:19 +00002287 ++Tmp;
Chris Lattner17f71652008-08-17 07:19:36 +00002288 Str.push_back('-');
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002289 }
Eric Christopher820256b2009-08-21 04:06:45 +00002290
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002291 while (*Prefix) {
2292 Str.push_back(*Prefix);
2293 ++Prefix;
2294 };
2295
Chris Lattner17f71652008-08-17 07:19:36 +00002296 // We insert the digits backward, then reverse them to get the right order.
2297 unsigned StartDig = Str.size();
Eric Christopher820256b2009-08-21 04:06:45 +00002298
2299 // For the 2, 8 and 16 bit cases, we can just shift instead of divide
2300 // because the number of bits per digit (1, 3 and 4 respectively) divides
Chris Lattner17f71652008-08-17 07:19:36 +00002301 // equaly. We just shift until the value is zero.
Douglas Gregor663c0682011-09-14 15:54:46 +00002302 if (Radix == 2 || Radix == 8 || Radix == 16) {
Chris Lattner17f71652008-08-17 07:19:36 +00002303 // Just shift tmp right for each digit width until it becomes zero
2304 unsigned ShiftAmt = (Radix == 16 ? 4 : (Radix == 8 ? 3 : 1));
2305 unsigned MaskAmt = Radix - 1;
Eric Christopher820256b2009-08-21 04:06:45 +00002306
Chris Lattner17f71652008-08-17 07:19:36 +00002307 while (Tmp != 0) {
2308 unsigned Digit = unsigned(Tmp.getRawData()[0]) & MaskAmt;
2309 Str.push_back(Digits[Digit]);
2310 Tmp = Tmp.lshr(ShiftAmt);
2311 }
2312 } else {
Douglas Gregor663c0682011-09-14 15:54:46 +00002313 APInt divisor(Radix == 10? 4 : 8, Radix);
Chris Lattner17f71652008-08-17 07:19:36 +00002314 while (Tmp != 0) {
2315 APInt APdigit(1, 0);
2316 APInt tmp2(Tmp.getBitWidth(), 0);
Eric Christopher820256b2009-08-21 04:06:45 +00002317 divide(Tmp, Tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2,
Chris Lattner17f71652008-08-17 07:19:36 +00002318 &APdigit);
Chris Lattner77527f52009-01-21 18:09:24 +00002319 unsigned Digit = (unsigned)APdigit.getZExtValue();
Chris Lattner17f71652008-08-17 07:19:36 +00002320 assert(Digit < Radix && "divide failed");
2321 Str.push_back(Digits[Digit]);
2322 Tmp = tmp2;
2323 }
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002324 }
Eric Christopher820256b2009-08-21 04:06:45 +00002325
Chris Lattner17f71652008-08-17 07:19:36 +00002326 // Reverse the digits before returning.
2327 std::reverse(Str.begin()+StartDig, Str.end());
Reid Spencerfb77b2b2007-02-20 08:51:03 +00002328}
2329
Pawel Bylica6eeeac72015-04-06 13:31:39 +00002330/// Returns the APInt as a std::string. Note that this is an inefficient method.
2331/// It is better to pass in a SmallVector/SmallString to the methods above.
Chris Lattner17f71652008-08-17 07:19:36 +00002332std::string APInt::toString(unsigned Radix = 10, bool Signed = true) const {
2333 SmallString<40> S;
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002334 toString(S, Radix, Signed, /* formatAsCLiteral = */false);
Daniel Dunbar8b0b1152009-08-19 20:07:03 +00002335 return S.str();
Reid Spencer1ba83352007-02-21 03:55:44 +00002336}
Chris Lattner6b695682007-08-16 15:56:55 +00002337
Matthias Braun8c209aa2017-01-28 02:02:38 +00002338#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Kereneb2a2542016-01-29 20:50:44 +00002339LLVM_DUMP_METHOD void APInt::dump() const {
Chris Lattner17f71652008-08-17 07:19:36 +00002340 SmallString<40> S, U;
2341 this->toStringUnsigned(U);
2342 this->toStringSigned(S);
David Greenef32fcb42010-01-05 01:28:52 +00002343 dbgs() << "APInt(" << BitWidth << "b, "
Davide Italiano5a473d22017-01-31 21:26:18 +00002344 << U << "u " << S << "s)\n";
Chris Lattner17f71652008-08-17 07:19:36 +00002345}
Matthias Braun8c209aa2017-01-28 02:02:38 +00002346#endif
Chris Lattner17f71652008-08-17 07:19:36 +00002347
Chris Lattner0c19df42008-08-23 22:23:09 +00002348void APInt::print(raw_ostream &OS, bool isSigned) const {
Chris Lattner17f71652008-08-17 07:19:36 +00002349 SmallString<40> S;
Ted Kremenekb05f02e2011-06-15 00:51:55 +00002350 this->toString(S, 10, isSigned, /* formatAsCLiteral = */false);
Yaron Keren92e1b622015-03-18 10:17:07 +00002351 OS << S;
Chris Lattner17f71652008-08-17 07:19:36 +00002352}
2353
Chris Lattner6b695682007-08-16 15:56:55 +00002354// This implements a variety of operations on a representation of
2355// arbitrary precision, two's-complement, bignum integer values.
2356
Chris Lattner96cffa62009-08-23 23:11:28 +00002357// Assumed by lowHalf, highHalf, partMSB and partLSB. A fairly safe
2358// and unrestricting assumption.
Benjamin Kramer7000ca32014-10-12 17:56:40 +00002359static_assert(integerPartWidth % 2 == 0, "Part width must be divisible by 2!");
Chris Lattner6b695682007-08-16 15:56:55 +00002360
2361/* Some handy functions local to this file. */
2362namespace {
2363
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002364 /* Returns the integer part with the least significant BITS set.
2365 BITS cannot be zero. */
Dan Gohmanf4bc7822008-04-10 21:11:47 +00002366 static inline integerPart
Craig Topper592b1342017-03-28 05:32:48 +00002367 lowBitMask(unsigned bits)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002368 {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002369 assert(bits != 0 && bits <= integerPartWidth);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002370
2371 return ~(integerPart) 0 >> (integerPartWidth - bits);
2372 }
2373
Neil Boothc8b650a2007-10-06 00:43:45 +00002374 /* Returns the value of the lower half of PART. */
Dan Gohmanf4bc7822008-04-10 21:11:47 +00002375 static inline integerPart
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002376 lowHalf(integerPart part)
2377 {
2378 return part & lowBitMask(integerPartWidth / 2);
2379 }
2380
Neil Boothc8b650a2007-10-06 00:43:45 +00002381 /* Returns the value of the upper half of PART. */
Dan Gohmanf4bc7822008-04-10 21:11:47 +00002382 static inline integerPart
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002383 highHalf(integerPart part)
2384 {
2385 return part >> (integerPartWidth / 2);
2386 }
2387
Neil Boothc8b650a2007-10-06 00:43:45 +00002388 /* Returns the bit number of the most significant set bit of a part.
2389 If the input number has no bits set -1U is returned. */
Craig Topper592b1342017-03-28 05:32:48 +00002390 static unsigned
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002391 partMSB(integerPart value)
Chris Lattner6b695682007-08-16 15:56:55 +00002392 {
Benjamin Kramerb565f892013-06-01 11:26:39 +00002393 return findLastSet(value, ZB_Max);
Chris Lattner6b695682007-08-16 15:56:55 +00002394 }
2395
Neil Boothc8b650a2007-10-06 00:43:45 +00002396 /* Returns the bit number of the least significant set bit of a
2397 part. If the input number has no bits set -1U is returned. */
Craig Topper592b1342017-03-28 05:32:48 +00002398 static unsigned
Chris Lattner6b695682007-08-16 15:56:55 +00002399 partLSB(integerPart value)
2400 {
Benjamin Kramerb565f892013-06-01 11:26:39 +00002401 return findFirstSet(value, ZB_Max);
Chris Lattner6b695682007-08-16 15:56:55 +00002402 }
Alexander Kornienkof00654e2015-06-23 09:49:53 +00002403}
Chris Lattner6b695682007-08-16 15:56:55 +00002404
2405/* Sets the least significant part of a bignum to the input value, and
2406 zeroes out higher parts. */
2407void
Craig Topper592b1342017-03-28 05:32:48 +00002408APInt::tcSet(integerPart *dst, integerPart part, unsigned parts)
Chris Lattner6b695682007-08-16 15:56:55 +00002409{
2410 unsigned int i;
2411
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002412 assert(parts > 0);
Neil Boothb6182162007-10-08 13:47:12 +00002413
Chris Lattner6b695682007-08-16 15:56:55 +00002414 dst[0] = part;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002415 for (i = 1; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002416 dst[i] = 0;
2417}
2418
2419/* Assign one bignum to another. */
2420void
Craig Topper592b1342017-03-28 05:32:48 +00002421APInt::tcAssign(integerPart *dst, const integerPart *src, unsigned parts)
Chris Lattner6b695682007-08-16 15:56:55 +00002422{
2423 unsigned int i;
2424
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002425 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002426 dst[i] = src[i];
2427}
2428
2429/* Returns true if a bignum is zero, false otherwise. */
2430bool
Craig Topper592b1342017-03-28 05:32:48 +00002431APInt::tcIsZero(const integerPart *src, unsigned parts)
Chris Lattner6b695682007-08-16 15:56:55 +00002432{
2433 unsigned int i;
2434
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002435 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002436 if (src[i])
2437 return false;
2438
2439 return true;
2440}
2441
2442/* Extract the given bit of a bignum; returns 0 or 1. */
2443int
Craig Topper592b1342017-03-28 05:32:48 +00002444APInt::tcExtractBit(const integerPart *parts, unsigned bit)
Chris Lattner6b695682007-08-16 15:56:55 +00002445{
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002446 return (parts[bit / integerPartWidth] &
2447 ((integerPart) 1 << bit % integerPartWidth)) != 0;
Chris Lattner6b695682007-08-16 15:56:55 +00002448}
2449
John McCalldcb9a7a2010-02-28 02:51:25 +00002450/* Set the given bit of a bignum. */
Chris Lattner6b695682007-08-16 15:56:55 +00002451void
Craig Topper592b1342017-03-28 05:32:48 +00002452APInt::tcSetBit(integerPart *parts, unsigned bit)
Chris Lattner6b695682007-08-16 15:56:55 +00002453{
2454 parts[bit / integerPartWidth] |= (integerPart) 1 << (bit % integerPartWidth);
2455}
2456
John McCalldcb9a7a2010-02-28 02:51:25 +00002457/* Clears the given bit of a bignum. */
2458void
Craig Topper592b1342017-03-28 05:32:48 +00002459APInt::tcClearBit(integerPart *parts, unsigned bit)
John McCalldcb9a7a2010-02-28 02:51:25 +00002460{
2461 parts[bit / integerPartWidth] &=
2462 ~((integerPart) 1 << (bit % integerPartWidth));
2463}
2464
Neil Boothc8b650a2007-10-06 00:43:45 +00002465/* Returns the bit number of the least significant set bit of a
2466 number. If the input number has no bits set -1U is returned. */
Craig Topper592b1342017-03-28 05:32:48 +00002467unsigned
2468APInt::tcLSB(const integerPart *parts, unsigned n)
Chris Lattner6b695682007-08-16 15:56:55 +00002469{
2470 unsigned int i, lsb;
2471
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002472 for (i = 0; i < n; i++) {
Chris Lattner6b695682007-08-16 15:56:55 +00002473 if (parts[i] != 0) {
2474 lsb = partLSB(parts[i]);
2475
2476 return lsb + i * integerPartWidth;
2477 }
2478 }
2479
2480 return -1U;
2481}
2482
Neil Boothc8b650a2007-10-06 00:43:45 +00002483/* Returns the bit number of the most significant set bit of a number.
2484 If the input number has no bits set -1U is returned. */
Craig Topper592b1342017-03-28 05:32:48 +00002485unsigned
2486APInt::tcMSB(const integerPart *parts, unsigned n)
Chris Lattner6b695682007-08-16 15:56:55 +00002487{
2488 unsigned int msb;
2489
2490 do {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002491 --n;
Chris Lattner6b695682007-08-16 15:56:55 +00002492
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002493 if (parts[n] != 0) {
2494 msb = partMSB(parts[n]);
Chris Lattner6b695682007-08-16 15:56:55 +00002495
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002496 return msb + n * integerPartWidth;
2497 }
Chris Lattner6b695682007-08-16 15:56:55 +00002498 } while (n);
2499
2500 return -1U;
2501}
2502
Neil Boothb6182162007-10-08 13:47:12 +00002503/* Copy the bit vector of width srcBITS from SRC, starting at bit
2504 srcLSB, to DST, of dstCOUNT parts, such that the bit srcLSB becomes
2505 the least significant bit of DST. All high bits above srcBITS in
2506 DST are zero-filled. */
2507void
Craig Topper592b1342017-03-28 05:32:48 +00002508APInt::tcExtract(integerPart *dst, unsigned dstCount,const integerPart *src,
2509 unsigned srcBits, unsigned srcLSB)
Neil Boothb6182162007-10-08 13:47:12 +00002510{
2511 unsigned int firstSrcPart, dstParts, shift, n;
2512
2513 dstParts = (srcBits + integerPartWidth - 1) / integerPartWidth;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002514 assert(dstParts <= dstCount);
Neil Boothb6182162007-10-08 13:47:12 +00002515
2516 firstSrcPart = srcLSB / integerPartWidth;
2517 tcAssign (dst, src + firstSrcPart, dstParts);
2518
2519 shift = srcLSB % integerPartWidth;
2520 tcShiftRight (dst, dstParts, shift);
2521
2522 /* We now have (dstParts * integerPartWidth - shift) bits from SRC
2523 in DST. If this is less that srcBits, append the rest, else
2524 clear the high bits. */
2525 n = dstParts * integerPartWidth - shift;
2526 if (n < srcBits) {
2527 integerPart mask = lowBitMask (srcBits - n);
2528 dst[dstParts - 1] |= ((src[firstSrcPart + dstParts] & mask)
2529 << n % integerPartWidth);
2530 } else if (n > srcBits) {
Neil Booth7e74b172007-10-12 15:31:31 +00002531 if (srcBits % integerPartWidth)
2532 dst[dstParts - 1] &= lowBitMask (srcBits % integerPartWidth);
Neil Boothb6182162007-10-08 13:47:12 +00002533 }
2534
2535 /* Clear high parts. */
2536 while (dstParts < dstCount)
2537 dst[dstParts++] = 0;
2538}
2539
Chris Lattner6b695682007-08-16 15:56:55 +00002540/* DST += RHS + C where C is zero or one. Returns the carry flag. */
2541integerPart
2542APInt::tcAdd(integerPart *dst, const integerPart *rhs,
Craig Topper592b1342017-03-28 05:32:48 +00002543 integerPart c, unsigned parts)
Chris Lattner6b695682007-08-16 15:56:55 +00002544{
2545 unsigned int i;
2546
2547 assert(c <= 1);
2548
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002549 for (i = 0; i < parts; i++) {
Chris Lattner6b695682007-08-16 15:56:55 +00002550 integerPart l;
2551
2552 l = dst[i];
2553 if (c) {
2554 dst[i] += rhs[i] + 1;
2555 c = (dst[i] <= l);
2556 } else {
2557 dst[i] += rhs[i];
2558 c = (dst[i] < l);
2559 }
2560 }
2561
2562 return c;
2563}
2564
2565/* DST -= RHS + C where C is zero or one. Returns the carry flag. */
2566integerPart
2567APInt::tcSubtract(integerPart *dst, const integerPart *rhs,
Craig Topper592b1342017-03-28 05:32:48 +00002568 integerPart c, unsigned parts)
Chris Lattner6b695682007-08-16 15:56:55 +00002569{
2570 unsigned int i;
2571
2572 assert(c <= 1);
2573
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002574 for (i = 0; i < parts; i++) {
Chris Lattner6b695682007-08-16 15:56:55 +00002575 integerPart l;
2576
2577 l = dst[i];
2578 if (c) {
2579 dst[i] -= rhs[i] + 1;
2580 c = (dst[i] >= l);
2581 } else {
2582 dst[i] -= rhs[i];
2583 c = (dst[i] > l);
2584 }
2585 }
2586
2587 return c;
2588}
2589
2590/* Negate a bignum in-place. */
2591void
Craig Topper592b1342017-03-28 05:32:48 +00002592APInt::tcNegate(integerPart *dst, unsigned parts)
Chris Lattner6b695682007-08-16 15:56:55 +00002593{
2594 tcComplement(dst, parts);
2595 tcIncrement(dst, parts);
2596}
2597
Neil Boothc8b650a2007-10-06 00:43:45 +00002598/* DST += SRC * MULTIPLIER + CARRY if add is true
2599 DST = SRC * MULTIPLIER + CARRY if add is false
Chris Lattner6b695682007-08-16 15:56:55 +00002600
2601 Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC
2602 they must start at the same point, i.e. DST == SRC.
2603
2604 If DSTPARTS == SRCPARTS + 1 no overflow occurs and zero is
2605 returned. Otherwise DST is filled with the least significant
2606 DSTPARTS parts of the result, and if all of the omitted higher
2607 parts were zero return zero, otherwise overflow occurred and
2608 return one. */
2609int
2610APInt::tcMultiplyPart(integerPart *dst, const integerPart *src,
2611 integerPart multiplier, integerPart carry,
Craig Topper592b1342017-03-28 05:32:48 +00002612 unsigned srcParts, unsigned dstParts,
Chris Lattner6b695682007-08-16 15:56:55 +00002613 bool add)
2614{
2615 unsigned int i, n;
2616
2617 /* Otherwise our writes of DST kill our later reads of SRC. */
2618 assert(dst <= src || dst >= src + srcParts);
2619 assert(dstParts <= srcParts + 1);
2620
2621 /* N loops; minimum of dstParts and srcParts. */
2622 n = dstParts < srcParts ? dstParts: srcParts;
2623
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002624 for (i = 0; i < n; i++) {
Chris Lattner6b695682007-08-16 15:56:55 +00002625 integerPart low, mid, high, srcPart;
2626
2627 /* [ LOW, HIGH ] = MULTIPLIER * SRC[i] + DST[i] + CARRY.
2628
2629 This cannot overflow, because
2630
2631 (n - 1) * (n - 1) + 2 (n - 1) = (n - 1) * (n + 1)
2632
2633 which is less than n^2. */
2634
2635 srcPart = src[i];
2636
2637 if (multiplier == 0 || srcPart == 0) {
2638 low = carry;
2639 high = 0;
2640 } else {
2641 low = lowHalf(srcPart) * lowHalf(multiplier);
2642 high = highHalf(srcPart) * highHalf(multiplier);
2643
2644 mid = lowHalf(srcPart) * highHalf(multiplier);
2645 high += highHalf(mid);
2646 mid <<= integerPartWidth / 2;
2647 if (low + mid < low)
2648 high++;
2649 low += mid;
2650
2651 mid = highHalf(srcPart) * lowHalf(multiplier);
2652 high += highHalf(mid);
2653 mid <<= integerPartWidth / 2;
2654 if (low + mid < low)
2655 high++;
2656 low += mid;
2657
2658 /* Now add carry. */
2659 if (low + carry < low)
2660 high++;
2661 low += carry;
2662 }
2663
2664 if (add) {
2665 /* And now DST[i], and store the new low part there. */
2666 if (low + dst[i] < low)
2667 high++;
2668 dst[i] += low;
2669 } else
2670 dst[i] = low;
2671
2672 carry = high;
2673 }
2674
2675 if (i < dstParts) {
2676 /* Full multiplication, there is no overflow. */
2677 assert(i + 1 == dstParts);
2678 dst[i] = carry;
2679 return 0;
2680 } else {
2681 /* We overflowed if there is carry. */
2682 if (carry)
2683 return 1;
2684
2685 /* We would overflow if any significant unwritten parts would be
2686 non-zero. This is true if any remaining src parts are non-zero
2687 and the multiplier is non-zero. */
2688 if (multiplier)
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002689 for (; i < srcParts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002690 if (src[i])
2691 return 1;
2692
2693 /* We fitted in the narrow destination. */
2694 return 0;
2695 }
2696}
2697
2698/* DST = LHS * RHS, where DST has the same width as the operands and
2699 is filled with the least significant parts of the result. Returns
2700 one if overflow occurred, otherwise zero. DST must be disjoint
2701 from both operands. */
2702int
2703APInt::tcMultiply(integerPart *dst, const integerPart *lhs,
Craig Topper592b1342017-03-28 05:32:48 +00002704 const integerPart *rhs, unsigned parts)
Chris Lattner6b695682007-08-16 15:56:55 +00002705{
2706 unsigned int i;
2707 int overflow;
2708
2709 assert(dst != lhs && dst != rhs);
2710
2711 overflow = 0;
2712 tcSet(dst, 0, parts);
2713
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002714 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002715 overflow |= tcMultiplyPart(&dst[i], lhs, rhs[i], 0, parts,
2716 parts - i, true);
2717
2718 return overflow;
2719}
2720
Neil Booth0ea72a92007-10-06 00:24:48 +00002721/* DST = LHS * RHS, where DST has width the sum of the widths of the
2722 operands. No overflow occurs. DST must be disjoint from both
2723 operands. Returns the number of parts required to hold the
2724 result. */
Craig Topper592b1342017-03-28 05:32:48 +00002725unsigned
Chris Lattner6b695682007-08-16 15:56:55 +00002726APInt::tcFullMultiply(integerPart *dst, const integerPart *lhs,
Craig Topper592b1342017-03-28 05:32:48 +00002727 const integerPart *rhs, unsigned lhsParts,
2728 unsigned rhsParts)
Chris Lattner6b695682007-08-16 15:56:55 +00002729{
Neil Booth0ea72a92007-10-06 00:24:48 +00002730 /* Put the narrower number on the LHS for less loops below. */
2731 if (lhsParts > rhsParts) {
2732 return tcFullMultiply (dst, rhs, lhs, rhsParts, lhsParts);
2733 } else {
2734 unsigned int n;
Chris Lattner6b695682007-08-16 15:56:55 +00002735
Neil Booth0ea72a92007-10-06 00:24:48 +00002736 assert(dst != lhs && dst != rhs);
Chris Lattner6b695682007-08-16 15:56:55 +00002737
Neil Booth0ea72a92007-10-06 00:24:48 +00002738 tcSet(dst, 0, rhsParts);
Chris Lattner6b695682007-08-16 15:56:55 +00002739
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002740 for (n = 0; n < lhsParts; n++)
Neil Booth0ea72a92007-10-06 00:24:48 +00002741 tcMultiplyPart(&dst[n], rhs, lhs[n], 0, rhsParts, rhsParts + 1, true);
Chris Lattner6b695682007-08-16 15:56:55 +00002742
Neil Booth0ea72a92007-10-06 00:24:48 +00002743 n = lhsParts + rhsParts;
2744
2745 return n - (dst[n - 1] == 0);
2746 }
Chris Lattner6b695682007-08-16 15:56:55 +00002747}
2748
2749/* If RHS is zero LHS and REMAINDER are left unchanged, return one.
2750 Otherwise set LHS to LHS / RHS with the fractional part discarded,
2751 set REMAINDER to the remainder, return zero. i.e.
2752
2753 OLD_LHS = RHS * LHS + REMAINDER
2754
2755 SCRATCH is a bignum of the same size as the operands and result for
2756 use by the routine; its contents need not be initialized and are
2757 destroyed. LHS, REMAINDER and SCRATCH must be distinct.
2758*/
2759int
2760APInt::tcDivide(integerPart *lhs, const integerPart *rhs,
2761 integerPart *remainder, integerPart *srhs,
Craig Topper592b1342017-03-28 05:32:48 +00002762 unsigned parts)
Chris Lattner6b695682007-08-16 15:56:55 +00002763{
2764 unsigned int n, shiftCount;
2765 integerPart mask;
2766
2767 assert(lhs != remainder && lhs != srhs && remainder != srhs);
2768
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002769 shiftCount = tcMSB(rhs, parts) + 1;
2770 if (shiftCount == 0)
Chris Lattner6b695682007-08-16 15:56:55 +00002771 return true;
2772
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002773 shiftCount = parts * integerPartWidth - shiftCount;
Chris Lattner6b695682007-08-16 15:56:55 +00002774 n = shiftCount / integerPartWidth;
2775 mask = (integerPart) 1 << (shiftCount % integerPartWidth);
2776
2777 tcAssign(srhs, rhs, parts);
2778 tcShiftLeft(srhs, parts, shiftCount);
2779 tcAssign(remainder, lhs, parts);
2780 tcSet(lhs, 0, parts);
2781
2782 /* Loop, subtracting SRHS if REMAINDER is greater and adding that to
2783 the total. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002784 for (;;) {
Chris Lattner6b695682007-08-16 15:56:55 +00002785 int compare;
2786
2787 compare = tcCompare(remainder, srhs, parts);
2788 if (compare >= 0) {
2789 tcSubtract(remainder, srhs, 0, parts);
2790 lhs[n] |= mask;
2791 }
2792
2793 if (shiftCount == 0)
2794 break;
2795 shiftCount--;
2796 tcShiftRight(srhs, parts, 1);
Richard Trieu7a083812016-02-18 22:09:30 +00002797 if ((mask >>= 1) == 0) {
2798 mask = (integerPart) 1 << (integerPartWidth - 1);
2799 n--;
2800 }
Chris Lattner6b695682007-08-16 15:56:55 +00002801 }
2802
2803 return false;
2804}
2805
2806/* Shift a bignum left COUNT bits in-place. Shifted in bits are zero.
2807 There are no restrictions on COUNT. */
2808void
Craig Topper592b1342017-03-28 05:32:48 +00002809APInt::tcShiftLeft(integerPart *dst, unsigned parts, unsigned count)
Chris Lattner6b695682007-08-16 15:56:55 +00002810{
Neil Boothb6182162007-10-08 13:47:12 +00002811 if (count) {
2812 unsigned int jump, shift;
Chris Lattner6b695682007-08-16 15:56:55 +00002813
Neil Boothb6182162007-10-08 13:47:12 +00002814 /* Jump is the inter-part jump; shift is is intra-part shift. */
2815 jump = count / integerPartWidth;
2816 shift = count % integerPartWidth;
Chris Lattner6b695682007-08-16 15:56:55 +00002817
Neil Boothb6182162007-10-08 13:47:12 +00002818 while (parts > jump) {
2819 integerPart part;
Chris Lattner6b695682007-08-16 15:56:55 +00002820
Neil Boothb6182162007-10-08 13:47:12 +00002821 parts--;
Chris Lattner6b695682007-08-16 15:56:55 +00002822
Neil Boothb6182162007-10-08 13:47:12 +00002823 /* dst[i] comes from the two parts src[i - jump] and, if we have
2824 an intra-part shift, src[i - jump - 1]. */
2825 part = dst[parts - jump];
2826 if (shift) {
2827 part <<= shift;
Chris Lattner6b695682007-08-16 15:56:55 +00002828 if (parts >= jump + 1)
2829 part |= dst[parts - jump - 1] >> (integerPartWidth - shift);
2830 }
2831
Neil Boothb6182162007-10-08 13:47:12 +00002832 dst[parts] = part;
2833 }
Chris Lattner6b695682007-08-16 15:56:55 +00002834
Neil Boothb6182162007-10-08 13:47:12 +00002835 while (parts > 0)
2836 dst[--parts] = 0;
2837 }
Chris Lattner6b695682007-08-16 15:56:55 +00002838}
2839
2840/* Shift a bignum right COUNT bits in-place. Shifted in bits are
2841 zero. There are no restrictions on COUNT. */
2842void
Craig Topper592b1342017-03-28 05:32:48 +00002843APInt::tcShiftRight(integerPart *dst, unsigned parts, unsigned count)
Chris Lattner6b695682007-08-16 15:56:55 +00002844{
Neil Boothb6182162007-10-08 13:47:12 +00002845 if (count) {
2846 unsigned int i, jump, shift;
Chris Lattner6b695682007-08-16 15:56:55 +00002847
Neil Boothb6182162007-10-08 13:47:12 +00002848 /* Jump is the inter-part jump; shift is is intra-part shift. */
2849 jump = count / integerPartWidth;
2850 shift = count % integerPartWidth;
Chris Lattner6b695682007-08-16 15:56:55 +00002851
Neil Boothb6182162007-10-08 13:47:12 +00002852 /* Perform the shift. This leaves the most significant COUNT bits
2853 of the result at zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002854 for (i = 0; i < parts; i++) {
Neil Boothb6182162007-10-08 13:47:12 +00002855 integerPart part;
Chris Lattner6b695682007-08-16 15:56:55 +00002856
Neil Boothb6182162007-10-08 13:47:12 +00002857 if (i + jump >= parts) {
2858 part = 0;
2859 } else {
2860 part = dst[i + jump];
2861 if (shift) {
2862 part >>= shift;
2863 if (i + jump + 1 < parts)
2864 part |= dst[i + jump + 1] << (integerPartWidth - shift);
2865 }
Chris Lattner6b695682007-08-16 15:56:55 +00002866 }
Chris Lattner6b695682007-08-16 15:56:55 +00002867
Neil Boothb6182162007-10-08 13:47:12 +00002868 dst[i] = part;
2869 }
Chris Lattner6b695682007-08-16 15:56:55 +00002870 }
2871}
2872
2873/* Bitwise and of two bignums. */
2874void
Craig Topper592b1342017-03-28 05:32:48 +00002875APInt::tcAnd(integerPart *dst, const integerPart *rhs, unsigned parts)
Chris Lattner6b695682007-08-16 15:56:55 +00002876{
2877 unsigned int i;
2878
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002879 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002880 dst[i] &= rhs[i];
2881}
2882
2883/* Bitwise inclusive or of two bignums. */
2884void
Craig Topper592b1342017-03-28 05:32:48 +00002885APInt::tcOr(integerPart *dst, const integerPart *rhs, unsigned parts)
Chris Lattner6b695682007-08-16 15:56:55 +00002886{
2887 unsigned int i;
2888
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002889 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002890 dst[i] |= rhs[i];
2891}
2892
2893/* Bitwise exclusive or of two bignums. */
2894void
Craig Topper592b1342017-03-28 05:32:48 +00002895APInt::tcXor(integerPart *dst, const integerPart *rhs, unsigned parts)
Chris Lattner6b695682007-08-16 15:56:55 +00002896{
2897 unsigned int i;
2898
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002899 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002900 dst[i] ^= rhs[i];
2901}
2902
2903/* Complement a bignum in-place. */
2904void
Craig Topper592b1342017-03-28 05:32:48 +00002905APInt::tcComplement(integerPart *dst, unsigned parts)
Chris Lattner6b695682007-08-16 15:56:55 +00002906{
2907 unsigned int i;
2908
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002909 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002910 dst[i] = ~dst[i];
2911}
2912
2913/* Comparison (unsigned) of two bignums. */
2914int
2915APInt::tcCompare(const integerPart *lhs, const integerPart *rhs,
Craig Topper592b1342017-03-28 05:32:48 +00002916 unsigned parts)
Chris Lattner6b695682007-08-16 15:56:55 +00002917{
2918 while (parts) {
2919 parts--;
2920 if (lhs[parts] == rhs[parts])
2921 continue;
2922
2923 if (lhs[parts] > rhs[parts])
2924 return 1;
2925 else
2926 return -1;
2927 }
2928
2929 return 0;
2930}
2931
2932/* Increment a bignum in-place, return the carry flag. */
2933integerPart
Craig Topper592b1342017-03-28 05:32:48 +00002934APInt::tcIncrement(integerPart *dst, unsigned parts)
Chris Lattner6b695682007-08-16 15:56:55 +00002935{
2936 unsigned int i;
2937
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002938 for (i = 0; i < parts; i++)
Chris Lattner6b695682007-08-16 15:56:55 +00002939 if (++dst[i] != 0)
2940 break;
2941
2942 return i == parts;
2943}
2944
Michael Gottesman9d406f42013-05-28 19:50:20 +00002945/* Decrement a bignum in-place, return the borrow flag. */
2946integerPart
Craig Topper592b1342017-03-28 05:32:48 +00002947APInt::tcDecrement(integerPart *dst, unsigned parts) {
2948 for (unsigned i = 0; i < parts; i++) {
Michael Gottesman9d406f42013-05-28 19:50:20 +00002949 // If the current word is non-zero, then the decrement has no effect on the
2950 // higher-order words of the integer and no borrow can occur. Exit early.
2951 if (dst[i]--)
2952 return 0;
2953 }
2954 // If every word was zero, then there is a borrow.
2955 return 1;
2956}
2957
2958
Chris Lattner6b695682007-08-16 15:56:55 +00002959/* Set the least significant BITS bits of a bignum, clear the
2960 rest. */
2961void
Craig Topper592b1342017-03-28 05:32:48 +00002962APInt::tcSetLeastSignificantBits(integerPart *dst, unsigned parts,
2963 unsigned bits)
Chris Lattner6b695682007-08-16 15:56:55 +00002964{
2965 unsigned int i;
2966
2967 i = 0;
2968 while (bits > integerPartWidth) {
2969 dst[i++] = ~(integerPart) 0;
2970 bits -= integerPartWidth;
2971 }
2972
2973 if (bits)
2974 dst[i++] = ~(integerPart) 0 >> (integerPartWidth - bits);
2975
2976 while (i < parts)
2977 dst[i++] = 0;
2978}