1 // Copyright 2017 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 // Parts of the implementation below:
6
7 // Copyright (c) 2014 the Dart project authors. Please see the AUTHORS file [1]
8 // for details. All rights reserved. Use of this source code is governed by a
9 // BSD-style license that can be found in the LICENSE file [2].
10 //
11 // [1] https://github.com/dart-lang/sdk/blob/master/AUTHORS
12 // [2] https://github.com/dart-lang/sdk/blob/master/LICENSE
13
14 // Copyright 2009 The Go Authors. All rights reserved.
15 // Use of this source code is governed by a BSD-style
16 // license that can be found in the LICENSE file [3].
17 //
18 // [3] https://golang.org/LICENSE
19
20 #include "src/objects/bigint.h"
21
22 #include "src/execution/isolate-inl.h"
23 #include "src/heap/factory.h"
24 #include "src/heap/heap-write-barrier-inl.h"
25 #include "src/numbers/conversions.h"
26 #include "src/numbers/double.h"
27 #include "src/objects/heap-number-inl.h"
28 #include "src/objects/instance-type-inl.h"
29 #include "src/objects/objects-inl.h"
30 #include "src/objects/smi.h"
31
32 namespace v8 {
33 namespace internal {
34
35 // The MutableBigInt class is an implementation detail designed to prevent
36 // accidental mutation of a BigInt after its construction. Step-by-step
37 // construction of a BigInt must happen in terms of MutableBigInt, the
38 // final result is then passed through MutableBigInt::MakeImmutable and not
39 // modified further afterwards.
40 // Many of the functions in this class use arguments of type {BigIntBase},
41 // indicating that they will be used in a read-only capacity, and both
42 // {BigInt} and {MutableBigInt} objects can be passed in.
43 class MutableBigInt : public FreshlyAllocatedBigInt {
44 public:
45 // Bottleneck for converting MutableBigInts to BigInts.
46 static MaybeHandle<BigInt> MakeImmutable(MaybeHandle<MutableBigInt> maybe);
47 template <typename Isolate = v8::internal::Isolate>
48 static Handle<BigInt> MakeImmutable(Handle<MutableBigInt> result);
49
50 static void Canonicalize(MutableBigInt result);
51
52 // Allocation helpers.
53 template <typename LocalIsolate>
54 static MaybeHandle<MutableBigInt> New(
55 LocalIsolate* isolate, int length,
56 AllocationType allocation = AllocationType::kYoung);
57 static Handle<BigInt> NewFromInt(Isolate* isolate, int value);
58 static Handle<BigInt> NewFromDouble(Isolate* isolate, double value);
59 void InitializeDigits(int length, byte value = 0);
60 static Handle<MutableBigInt> Copy(Isolate* isolate,
61 Handle<BigIntBase> source);
62 template <typename LocalIsolate>
Zero(LocalIsolate * isolate,AllocationType allocation=AllocationType::kYoung)63 static Handle<BigInt> Zero(
64 LocalIsolate* isolate,
65 AllocationType allocation = AllocationType::kYoung) {
66 // TODO(jkummerow): Consider caching a canonical zero-BigInt.
67 return MakeImmutable<LocalIsolate>(
68 New(isolate, 0, allocation).ToHandleChecked());
69 }
70
Cast(Handle<FreshlyAllocatedBigInt> bigint)71 static Handle<MutableBigInt> Cast(Handle<FreshlyAllocatedBigInt> bigint) {
72 SLOW_DCHECK(bigint->IsBigInt());
73 return Handle<MutableBigInt>::cast(bigint);
74 }
cast(Object o)75 static MutableBigInt cast(Object o) {
76 SLOW_DCHECK(o.IsBigInt());
77 return MutableBigInt(o.ptr());
78 }
unchecked_cast(Object o)79 static MutableBigInt unchecked_cast(Object o) {
80 return MutableBigInt(o.ptr());
81 }
82
83 // Internal helpers.
84 static MaybeHandle<MutableBigInt> BitwiseAnd(Isolate* isolate,
85 Handle<BigInt> x,
86 Handle<BigInt> y);
87 static MaybeHandle<MutableBigInt> BitwiseXor(Isolate* isolate,
88 Handle<BigInt> x,
89 Handle<BigInt> y);
90 static MaybeHandle<MutableBigInt> BitwiseOr(Isolate* isolate,
91 Handle<BigInt> x,
92 Handle<BigInt> y);
93
94 static Handle<BigInt> TruncateToNBits(Isolate* isolate, int n,
95 Handle<BigInt> x);
96 static Handle<BigInt> TruncateAndSubFromPowerOfTwo(Isolate* isolate, int n,
97 Handle<BigInt> x,
98 bool result_sign);
99
100 static MaybeHandle<BigInt> AbsoluteAdd(Isolate* isolate, Handle<BigInt> x,
101 Handle<BigInt> y, bool result_sign);
102
103 static void AbsoluteAdd(MutableBigInt result, BigInt x, BigInt y);
104
105 static Handle<BigInt> AbsoluteSub(Isolate* isolate, Handle<BigInt> x,
106 Handle<BigInt> y, bool result_sign);
107 static void AbsoluteSub(MutableBigInt result, BigInt x, BigInt y);
108
109 static MaybeHandle<MutableBigInt> AbsoluteAddOne(
110 Isolate* isolate, Handle<BigIntBase> x, bool sign,
111 MutableBigInt result_storage = MutableBigInt());
112 static Handle<MutableBigInt> AbsoluteSubOne(Isolate* isolate,
113 Handle<BigIntBase> x);
114 static MaybeHandle<MutableBigInt> AbsoluteSubOne(Isolate* isolate,
115 Handle<BigIntBase> x,
116 int result_length);
117
118 enum ExtraDigitsHandling { kCopy, kSkip };
119 enum SymmetricOp { kSymmetric, kNotSymmetric };
120 static inline Handle<MutableBigInt> AbsoluteBitwiseOp(
121 Isolate* isolate, Handle<BigIntBase> x, Handle<BigIntBase> y,
122 MutableBigInt result_storage, ExtraDigitsHandling extra_digits,
123 SymmetricOp symmetric,
124 const std::function<digit_t(digit_t, digit_t)>& op);
125 static Handle<MutableBigInt> AbsoluteAnd(
126 Isolate* isolate, Handle<BigIntBase> x, Handle<BigIntBase> y,
127 MutableBigInt result_storage = MutableBigInt());
128 static Handle<MutableBigInt> AbsoluteAndNot(
129 Isolate* isolate, Handle<BigIntBase> x, Handle<BigIntBase> y,
130 MutableBigInt result_storage = MutableBigInt());
131 static Handle<MutableBigInt> AbsoluteOr(
132 Isolate* isolate, Handle<BigIntBase> x, Handle<BigIntBase> y,
133 MutableBigInt result_storage = MutableBigInt());
134 static Handle<MutableBigInt> AbsoluteXor(
135 Isolate* isolate, Handle<BigIntBase> x, Handle<BigIntBase> y,
136 MutableBigInt result_storage = MutableBigInt());
137
138 static int AbsoluteCompare(Handle<BigIntBase> x, Handle<BigIntBase> y);
139
140 static int AbsoluteCompare(BigIntBase x, BigIntBase y);
141
142 static void MultiplyAccumulate(Handle<BigIntBase> multiplicand,
143 digit_t multiplier,
144 Handle<MutableBigInt> accumulator,
145 int accumulator_index);
146 static void InternalMultiplyAdd(BigIntBase source, digit_t factor,
147 digit_t summand, int n, MutableBigInt result);
148 void InplaceMultiplyAdd(uintptr_t factor, uintptr_t summand);
149
150 // Specialized helpers for Divide/Remainder.
151 static void AbsoluteDivSmall(Isolate* isolate, Handle<BigIntBase> x,
152 digit_t divisor, Handle<MutableBigInt>* quotient,
153 digit_t* remainder);
154 static bool AbsoluteDivLarge(Isolate* isolate, Handle<BigIntBase> dividend,
155 Handle<BigIntBase> divisor,
156 Handle<MutableBigInt>* quotient,
157 Handle<MutableBigInt>* remainder);
158 static bool ProductGreaterThan(digit_t factor1, digit_t factor2, digit_t high,
159 digit_t low);
160 digit_t InplaceAdd(Handle<BigIntBase> summand, int start_index);
161 digit_t InplaceSub(Handle<BigIntBase> subtrahend, int start_index);
162 void InplaceRightShift(int shift);
163 enum SpecialLeftShiftMode {
164 kSameSizeResult,
165 kAlwaysAddOneDigit,
166 };
167 static MaybeHandle<MutableBigInt> SpecialLeftShift(Isolate* isolate,
168 Handle<BigIntBase> x,
169 int shift,
170 SpecialLeftShiftMode mode);
171
172 // Specialized helpers for shift operations.
173 static MaybeHandle<BigInt> LeftShiftByAbsolute(Isolate* isolate,
174 Handle<BigIntBase> x,
175 Handle<BigIntBase> y);
176 static Handle<BigInt> RightShiftByAbsolute(Isolate* isolate,
177 Handle<BigIntBase> x,
178 Handle<BigIntBase> y);
179 static Handle<BigInt> RightShiftByMaximum(Isolate* isolate, bool sign);
180 static Maybe<digit_t> ToShiftAmount(Handle<BigIntBase> x);
181
182 static MaybeHandle<String> ToStringBasePowerOfTwo(Isolate* isolate,
183 Handle<BigIntBase> x,
184 int radix,
185 ShouldThrow should_throw);
186 static MaybeHandle<String> ToStringGeneric(Isolate* isolate,
187 Handle<BigIntBase> x, int radix,
188 ShouldThrow should_throw);
189
190 static double ToDouble(Handle<BigIntBase> x);
191 enum Rounding { kRoundDown, kTie, kRoundUp };
192 static Rounding DecideRounding(Handle<BigIntBase> x, int mantissa_bits_unset,
193 int digit_index, uint64_t current_digit);
194
195 // Returns the least significant 64 bits, simulating two's complement
196 // representation.
197 static uint64_t GetRawBits(BigIntBase x, bool* lossless);
198
199 // Digit arithmetic helpers.
200 static inline digit_t digit_add(digit_t a, digit_t b, digit_t* carry);
201 static inline digit_t digit_sub(digit_t a, digit_t b, digit_t* borrow);
202 static inline digit_t digit_mul(digit_t a, digit_t b, digit_t* high);
203 static inline digit_t digit_div(digit_t high, digit_t low, digit_t divisor,
204 digit_t* remainder);
205 static digit_t digit_pow(digit_t base, digit_t exponent);
digit_ismax(digit_t x)206 static inline bool digit_ismax(digit_t x) {
207 return static_cast<digit_t>(~x) == 0;
208 }
209
210 // Internal field setters. Non-mutable BigInts don't have these.
211 #include "src/objects/object-macros.h"
set_sign(bool new_sign)212 inline void set_sign(bool new_sign) {
213 int32_t bitfield = RELAXED_READ_INT32_FIELD(*this, kBitfieldOffset);
214 bitfield = SignBits::update(bitfield, new_sign);
215 RELAXED_WRITE_INT32_FIELD(*this, kBitfieldOffset, bitfield);
216 }
synchronized_set_length(int new_length)217 inline void synchronized_set_length(int new_length) {
218 int32_t bitfield = RELAXED_READ_INT32_FIELD(*this, kBitfieldOffset);
219 bitfield = LengthBits::update(bitfield, new_length);
220 RELEASE_WRITE_INT32_FIELD(*this, kBitfieldOffset, bitfield);
221 }
initialize_bitfield(bool sign,int length)222 inline void initialize_bitfield(bool sign, int length) {
223 int32_t bitfield = LengthBits::encode(length) | SignBits::encode(sign);
224 WriteField<int32_t>(kBitfieldOffset, bitfield);
225 }
set_digit(int n,digit_t value)226 inline void set_digit(int n, digit_t value) {
227 SLOW_DCHECK(0 <= n && n < length());
228 WriteField<digit_t>(kDigitsOffset + n * kDigitSize, value);
229 }
230
231 void set_64_bits(uint64_t bits);
232
IsMutableBigInt() const233 bool IsMutableBigInt() const { return IsBigInt(); }
234
235 NEVER_READ_ONLY_SPACE
236
237 OBJECT_CONSTRUCTORS(MutableBigInt, FreshlyAllocatedBigInt);
238 };
239
OBJECT_CONSTRUCTORS_IMPL(MutableBigInt,FreshlyAllocatedBigInt)240 OBJECT_CONSTRUCTORS_IMPL(MutableBigInt, FreshlyAllocatedBigInt)
241 NEVER_READ_ONLY_SPACE_IMPL(MutableBigInt)
242
243 #include "src/objects/object-macros-undef.h"
244
245 template <typename T, typename Isolate>
246 MaybeHandle<T> ThrowBigIntTooBig(Isolate* isolate) {
247 // If the result of a BigInt computation is truncated to 64 bit, Turbofan
248 // can sometimes truncate intermediate results already, which can prevent
249 // those from exceeding the maximum length, effectively preventing a
250 // RangeError from being thrown. As this is a performance optimization, this
251 // behavior is accepted. To prevent the correctness fuzzer from detecting this
252 // difference, we crash the program.
253 if (FLAG_correctness_fuzzer_suppressions) {
254 FATAL("Aborting on invalid BigInt length");
255 }
256 THROW_NEW_ERROR(isolate, NewRangeError(MessageTemplate::kBigIntTooBig), T);
257 }
258
259 template <typename LocalIsolate>
New(LocalIsolate * isolate,int length,AllocationType allocation)260 MaybeHandle<MutableBigInt> MutableBigInt::New(LocalIsolate* isolate, int length,
261 AllocationType allocation) {
262 if (length > BigInt::kMaxLength) {
263 return ThrowBigIntTooBig<MutableBigInt>(isolate);
264 }
265 Handle<MutableBigInt> result =
266 Cast(isolate->factory()->NewBigInt(length, allocation));
267 result->initialize_bitfield(false, length);
268 #if DEBUG
269 result->InitializeDigits(length, 0xBF);
270 #endif
271 return result;
272 }
273
NewFromInt(Isolate * isolate,int value)274 Handle<BigInt> MutableBigInt::NewFromInt(Isolate* isolate, int value) {
275 if (value == 0) return Zero(isolate);
276 Handle<MutableBigInt> result = Cast(isolate->factory()->NewBigInt(1));
277 bool sign = value < 0;
278 result->initialize_bitfield(sign, 1);
279 if (!sign) {
280 result->set_digit(0, value);
281 } else {
282 if (value == kMinInt) {
283 STATIC_ASSERT(kMinInt == -kMaxInt - 1);
284 result->set_digit(0, static_cast<BigInt::digit_t>(kMaxInt) + 1);
285 } else {
286 result->set_digit(0, -value);
287 }
288 }
289 return MakeImmutable(result);
290 }
291
NewFromDouble(Isolate * isolate,double value)292 Handle<BigInt> MutableBigInt::NewFromDouble(Isolate* isolate, double value) {
293 DCHECK_EQ(value, std::floor(value));
294 if (value == 0) return Zero(isolate);
295
296 bool sign = value < 0; // -0 was already handled above.
297 uint64_t double_bits = bit_cast<uint64_t>(value);
298 int raw_exponent =
299 static_cast<int>(double_bits >> Double::kPhysicalSignificandSize) & 0x7FF;
300 DCHECK_NE(raw_exponent, 0x7FF);
301 DCHECK_GE(raw_exponent, 0x3FF);
302 int exponent = raw_exponent - 0x3FF;
303 int digits = exponent / kDigitBits + 1;
304 Handle<MutableBigInt> result = Cast(isolate->factory()->NewBigInt(digits));
305 result->initialize_bitfield(sign, digits);
306
307 // We construct a BigInt from the double {value} by shifting its mantissa
308 // according to its exponent and mapping the bit pattern onto digits.
309 //
310 // <----------- bitlength = exponent + 1 ----------->
311 // <----- 52 ------> <------ trailing zeroes ------>
312 // mantissa: 1yyyyyyyyyyyyyyyyy 0000000000000000000000000000000
313 // digits: 0001xxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx
314 // <--> <------>
315 // msd_topbit kDigitBits
316 //
317 uint64_t mantissa =
318 (double_bits & Double::kSignificandMask) | Double::kHiddenBit;
319 const int kMantissaTopBit = Double::kSignificandSize - 1; // 0-indexed.
320 // 0-indexed position of most significant bit in the most significant digit.
321 int msd_topbit = exponent % kDigitBits;
322 // Number of unused bits in {mantissa}. We'll keep them shifted to the
323 // left (i.e. most significant part) of the underlying uint64_t.
324 int remaining_mantissa_bits = 0;
325 // Next digit under construction.
326 digit_t digit;
327
328 // First, build the MSD by shifting the mantissa appropriately.
329 if (msd_topbit < kMantissaTopBit) {
330 remaining_mantissa_bits = kMantissaTopBit - msd_topbit;
331 digit = mantissa >> remaining_mantissa_bits;
332 mantissa = mantissa << (64 - remaining_mantissa_bits);
333 } else {
334 DCHECK_GE(msd_topbit, kMantissaTopBit);
335 digit = mantissa << (msd_topbit - kMantissaTopBit);
336 mantissa = 0;
337 }
338 result->set_digit(digits - 1, digit);
339 // Then fill in the rest of the digits.
340 for (int digit_index = digits - 2; digit_index >= 0; digit_index--) {
341 if (remaining_mantissa_bits > 0) {
342 remaining_mantissa_bits -= kDigitBits;
343 if (sizeof(digit) == 4) {
344 digit = mantissa >> 32;
345 mantissa = mantissa << 32;
346 } else {
347 DCHECK_EQ(sizeof(digit), 8);
348 digit = mantissa;
349 mantissa = 0;
350 }
351 } else {
352 digit = 0;
353 }
354 result->set_digit(digit_index, digit);
355 }
356 return MakeImmutable(result);
357 }
358
Copy(Isolate * isolate,Handle<BigIntBase> source)359 Handle<MutableBigInt> MutableBigInt::Copy(Isolate* isolate,
360 Handle<BigIntBase> source) {
361 int length = source->length();
362 // Allocating a BigInt of the same length as an existing BigInt cannot throw.
363 Handle<MutableBigInt> result = New(isolate, length).ToHandleChecked();
364 memcpy(reinterpret_cast<void*>(result->address() + BigIntBase::kHeaderSize),
365 reinterpret_cast<void*>(source->address() + BigIntBase::kHeaderSize),
366 BigInt::SizeFor(length) - BigIntBase::kHeaderSize);
367 return result;
368 }
369
InitializeDigits(int length,byte value)370 void MutableBigInt::InitializeDigits(int length, byte value) {
371 memset(reinterpret_cast<void*>(ptr() + kDigitsOffset - kHeapObjectTag), value,
372 length * kDigitSize);
373 }
374
MakeImmutable(MaybeHandle<MutableBigInt> maybe)375 MaybeHandle<BigInt> MutableBigInt::MakeImmutable(
376 MaybeHandle<MutableBigInt> maybe) {
377 Handle<MutableBigInt> result;
378 if (!maybe.ToHandle(&result)) return MaybeHandle<BigInt>();
379 return MakeImmutable(result);
380 }
381
382 template <typename LocalIsolate>
MakeImmutable(Handle<MutableBigInt> result)383 Handle<BigInt> MutableBigInt::MakeImmutable(Handle<MutableBigInt> result) {
384 MutableBigInt::Canonicalize(*result);
385 return Handle<BigInt>::cast(result);
386 }
387
Canonicalize(MutableBigInt result)388 void MutableBigInt::Canonicalize(MutableBigInt result) {
389 // Check if we need to right-trim any leading zero-digits.
390 int old_length = result.length();
391 int new_length = old_length;
392 while (new_length > 0 && result.digit(new_length - 1) == 0) new_length--;
393 int to_trim = old_length - new_length;
394 if (to_trim != 0) {
395 int size_delta = to_trim * MutableBigInt::kDigitSize;
396 Address new_end = result.address() + BigInt::SizeFor(new_length);
397 Heap* heap = result.GetHeap();
398 if (!heap->IsLargeObject(result)) {
399 // We do not create a filler for objects in large object space.
400 // TODO(hpayer): We should shrink the large object page if the size
401 // of the object changed significantly.
402 heap->CreateFillerObjectAt(new_end, size_delta, ClearRecordedSlots::kNo);
403 }
404 result.synchronized_set_length(new_length);
405
406 // Canonicalize -0n.
407 if (new_length == 0) {
408 result.set_sign(false);
409 // TODO(jkummerow): If we cache a canonical 0n, return that here.
410 }
411 }
412 DCHECK_IMPLIES(result.length() > 0,
413 result.digit(result.length() - 1) != 0); // MSD is non-zero.
414 }
415
416 template <typename LocalIsolate>
Zero(LocalIsolate * isolate,AllocationType allocation)417 Handle<BigInt> BigInt::Zero(LocalIsolate* isolate, AllocationType allocation) {
418 return MutableBigInt::Zero(isolate, allocation);
419 }
420 template Handle<BigInt> BigInt::Zero(Isolate* isolate,
421 AllocationType allocation);
422 template Handle<BigInt> BigInt::Zero(LocalIsolate* isolate,
423 AllocationType allocation);
424
UnaryMinus(Isolate * isolate,Handle<BigInt> x)425 Handle<BigInt> BigInt::UnaryMinus(Isolate* isolate, Handle<BigInt> x) {
426 // Special case: There is no -0n.
427 if (x->is_zero()) {
428 return x;
429 }
430 Handle<MutableBigInt> result = MutableBigInt::Copy(isolate, x);
431 result->set_sign(!x->sign());
432 return MutableBigInt::MakeImmutable(result);
433 }
434
BitwiseNot(Isolate * isolate,Handle<BigInt> x)435 MaybeHandle<BigInt> BigInt::BitwiseNot(Isolate* isolate, Handle<BigInt> x) {
436 MaybeHandle<MutableBigInt> result;
437 if (x->sign()) {
438 // ~(-x) == ~(~(x-1)) == x-1
439 result = MutableBigInt::AbsoluteSubOne(isolate, x, x->length());
440 } else {
441 // ~x == -x-1 == -(x+1)
442 result = MutableBigInt::AbsoluteAddOne(isolate, x, true);
443 }
444 return MutableBigInt::MakeImmutable(result);
445 }
446
Exponentiate(Isolate * isolate,Handle<BigInt> base,Handle<BigInt> exponent)447 MaybeHandle<BigInt> BigInt::Exponentiate(Isolate* isolate, Handle<BigInt> base,
448 Handle<BigInt> exponent) {
449 // 1. If exponent is < 0, throw a RangeError exception.
450 if (exponent->sign()) {
451 THROW_NEW_ERROR(isolate,
452 NewRangeError(MessageTemplate::kBigIntNegativeExponent),
453 BigInt);
454 }
455 // 2. If base is 0n and exponent is 0n, return 1n.
456 if (exponent->is_zero()) {
457 return MutableBigInt::NewFromInt(isolate, 1);
458 }
459 // 3. Return a BigInt representing the mathematical value of base raised
460 // to the power exponent.
461 if (base->is_zero()) return base;
462 if (base->length() == 1 && base->digit(0) == 1) {
463 // (-1) ** even_number == 1.
464 if (base->sign() && (exponent->digit(0) & 1) == 0) {
465 return UnaryMinus(isolate, base);
466 }
467 // (-1) ** odd_number == -1; 1 ** anything == 1.
468 return base;
469 }
470 // For all bases >= 2, very large exponents would lead to unrepresentable
471 // results.
472 STATIC_ASSERT(kMaxLengthBits < std::numeric_limits<digit_t>::max());
473 if (exponent->length() > 1) {
474 return ThrowBigIntTooBig<BigInt>(isolate);
475 }
476 digit_t exp_value = exponent->digit(0);
477 if (exp_value == 1) return base;
478 if (exp_value >= kMaxLengthBits) {
479 return ThrowBigIntTooBig<BigInt>(isolate);
480 }
481 STATIC_ASSERT(kMaxLengthBits <= kMaxInt);
482 int n = static_cast<int>(exp_value);
483 if (base->length() == 1 && base->digit(0) == 2) {
484 // Fast path for 2^n.
485 int needed_digits = 1 + (n / kDigitBits);
486 Handle<MutableBigInt> result;
487 if (!MutableBigInt::New(isolate, needed_digits).ToHandle(&result)) {
488 return MaybeHandle<BigInt>();
489 }
490 result->InitializeDigits(needed_digits);
491 // All bits are zero. Now set the n-th bit.
492 digit_t msd = static_cast<digit_t>(1) << (n % kDigitBits);
493 result->set_digit(needed_digits - 1, msd);
494 // Result is negative for odd powers of -2n.
495 if (base->sign()) result->set_sign((n & 1) != 0);
496 return MutableBigInt::MakeImmutable(result);
497 }
498 Handle<BigInt> result;
499 Handle<BigInt> running_square = base;
500 // This implicitly sets the result's sign correctly.
501 if (n & 1) result = base;
502 n >>= 1;
503 for (; n != 0; n >>= 1) {
504 MaybeHandle<BigInt> maybe_result =
505 Multiply(isolate, running_square, running_square);
506 if (!maybe_result.ToHandle(&running_square)) return maybe_result;
507 if (n & 1) {
508 if (result.is_null()) {
509 result = running_square;
510 } else {
511 maybe_result = Multiply(isolate, result, running_square);
512 if (!maybe_result.ToHandle(&result)) return maybe_result;
513 }
514 }
515 }
516 return result;
517 }
518
Multiply(Isolate * isolate,Handle<BigInt> x,Handle<BigInt> y)519 MaybeHandle<BigInt> BigInt::Multiply(Isolate* isolate, Handle<BigInt> x,
520 Handle<BigInt> y) {
521 if (x->is_zero()) return x;
522 if (y->is_zero()) return y;
523 int result_length = x->length() + y->length();
524 Handle<MutableBigInt> result;
525 if (!MutableBigInt::New(isolate, result_length).ToHandle(&result)) {
526 return MaybeHandle<BigInt>();
527 }
528 result->InitializeDigits(result_length);
529 uintptr_t work_estimate = 0;
530 for (int i = 0; i < x->length(); i++) {
531 MutableBigInt::MultiplyAccumulate(y, x->digit(i), result, i);
532
533 // Multiplication can take a long time. Check for interrupt requests
534 // every now and then (roughly every 10-20 of milliseconds -- rarely
535 // enough not to create noticeable overhead, frequently enough not to
536 // appear frozen).
537 work_estimate += y->length();
538 if (work_estimate > 5000000) {
539 work_estimate = 0;
540 StackLimitCheck interrupt_check(isolate);
541 if (interrupt_check.InterruptRequested() &&
542 isolate->stack_guard()->HandleInterrupts().IsException(isolate)) {
543 return MaybeHandle<BigInt>();
544 }
545 }
546 }
547 result->set_sign(x->sign() != y->sign());
548 return MutableBigInt::MakeImmutable(result);
549 }
550
Divide(Isolate * isolate,Handle<BigInt> x,Handle<BigInt> y)551 MaybeHandle<BigInt> BigInt::Divide(Isolate* isolate, Handle<BigInt> x,
552 Handle<BigInt> y) {
553 // 1. If y is 0n, throw a RangeError exception.
554 if (y->is_zero()) {
555 THROW_NEW_ERROR(isolate, NewRangeError(MessageTemplate::kBigIntDivZero),
556 BigInt);
557 }
558 // 2. Let quotient be the mathematical value of x divided by y.
559 // 3. Return a BigInt representing quotient rounded towards 0 to the next
560 // integral value.
561 if (MutableBigInt::AbsoluteCompare(x, y) < 0) {
562 return Zero(isolate);
563 }
564 Handle<MutableBigInt> quotient;
565 bool result_sign = x->sign() != y->sign();
566 if (y->length() == 1) {
567 digit_t divisor = y->digit(0);
568 if (divisor == 1) {
569 return result_sign == x->sign() ? x : UnaryMinus(isolate, x);
570 }
571 digit_t remainder;
572 MutableBigInt::AbsoluteDivSmall(isolate, x, divisor, "ient, &remainder);
573 } else {
574 if (!MutableBigInt::AbsoluteDivLarge(isolate, x, y, "ient, nullptr)) {
575 return MaybeHandle<BigInt>();
576 }
577 }
578 quotient->set_sign(x->sign() != y->sign());
579 return MutableBigInt::MakeImmutable(quotient);
580 }
581
Remainder(Isolate * isolate,Handle<BigInt> x,Handle<BigInt> y)582 MaybeHandle<BigInt> BigInt::Remainder(Isolate* isolate, Handle<BigInt> x,
583 Handle<BigInt> y) {
584 // 1. If y is 0n, throw a RangeError exception.
585 if (y->is_zero()) {
586 THROW_NEW_ERROR(isolate, NewRangeError(MessageTemplate::kBigIntDivZero),
587 BigInt);
588 }
589 // 2. Return the BigInt representing x modulo y.
590 // See https://github.com/tc39/proposal-bigint/issues/84 though.
591 if (MutableBigInt::AbsoluteCompare(x, y) < 0) return x;
592 Handle<MutableBigInt> remainder;
593 if (y->length() == 1) {
594 digit_t divisor = y->digit(0);
595 if (divisor == 1) return Zero(isolate);
596 digit_t remainder_digit;
597 MutableBigInt::AbsoluteDivSmall(isolate, x, divisor, nullptr,
598 &remainder_digit);
599 if (remainder_digit == 0) {
600 return Zero(isolate);
601 }
602 remainder = MutableBigInt::New(isolate, 1).ToHandleChecked();
603 remainder->set_digit(0, remainder_digit);
604 } else {
605 if (!MutableBigInt::AbsoluteDivLarge(isolate, x, y, nullptr, &remainder)) {
606 return MaybeHandle<BigInt>();
607 }
608 }
609 remainder->set_sign(x->sign());
610 return MutableBigInt::MakeImmutable(remainder);
611 }
612
Add(Isolate * isolate,Handle<BigInt> x,Handle<BigInt> y)613 MaybeHandle<BigInt> BigInt::Add(Isolate* isolate, Handle<BigInt> x,
614 Handle<BigInt> y) {
615 bool xsign = x->sign();
616 if (xsign == y->sign()) {
617 // x + y == x + y
618 // -x + -y == -(x + y)
619 return MutableBigInt::AbsoluteAdd(isolate, x, y, xsign);
620 }
621 // x + -y == x - y == -(y - x)
622 // -x + y == y - x == -(x - y)
623 if (MutableBigInt::AbsoluteCompare(x, y) >= 0) {
624 return MutableBigInt::AbsoluteSub(isolate, x, y, xsign);
625 }
626 return MutableBigInt::AbsoluteSub(isolate, y, x, !xsign);
627 }
628
Subtract(Isolate * isolate,Handle<BigInt> x,Handle<BigInt> y)629 MaybeHandle<BigInt> BigInt::Subtract(Isolate* isolate, Handle<BigInt> x,
630 Handle<BigInt> y) {
631 bool xsign = x->sign();
632 if (xsign != y->sign()) {
633 // x - (-y) == x + y
634 // (-x) - y == -(x + y)
635 return MutableBigInt::AbsoluteAdd(isolate, x, y, xsign);
636 }
637 // x - y == -(y - x)
638 // (-x) - (-y) == y - x == -(x - y)
639 if (MutableBigInt::AbsoluteCompare(x, y) >= 0) {
640 return MutableBigInt::AbsoluteSub(isolate, x, y, xsign);
641 }
642 return MutableBigInt::AbsoluteSub(isolate, y, x, !xsign);
643 }
644
LeftShift(Isolate * isolate,Handle<BigInt> x,Handle<BigInt> y)645 MaybeHandle<BigInt> BigInt::LeftShift(Isolate* isolate, Handle<BigInt> x,
646 Handle<BigInt> y) {
647 if (y->is_zero() || x->is_zero()) return x;
648 if (y->sign()) return MutableBigInt::RightShiftByAbsolute(isolate, x, y);
649 return MutableBigInt::LeftShiftByAbsolute(isolate, x, y);
650 }
651
SignedRightShift(Isolate * isolate,Handle<BigInt> x,Handle<BigInt> y)652 MaybeHandle<BigInt> BigInt::SignedRightShift(Isolate* isolate, Handle<BigInt> x,
653 Handle<BigInt> y) {
654 if (y->is_zero() || x->is_zero()) return x;
655 if (y->sign()) return MutableBigInt::LeftShiftByAbsolute(isolate, x, y);
656 return MutableBigInt::RightShiftByAbsolute(isolate, x, y);
657 }
658
UnsignedRightShift(Isolate * isolate,Handle<BigInt> x,Handle<BigInt> y)659 MaybeHandle<BigInt> BigInt::UnsignedRightShift(Isolate* isolate,
660 Handle<BigInt> x,
661 Handle<BigInt> y) {
662 THROW_NEW_ERROR(isolate, NewTypeError(MessageTemplate::kBigIntShr), BigInt);
663 }
664
665 namespace {
666
667 // Produces comparison result for {left_negative} == sign(x) != sign(y).
UnequalSign(bool left_negative)668 ComparisonResult UnequalSign(bool left_negative) {
669 return left_negative ? ComparisonResult::kLessThan
670 : ComparisonResult::kGreaterThan;
671 }
672
673 // Produces result for |x| > |y|, with {both_negative} == sign(x) == sign(y);
AbsoluteGreater(bool both_negative)674 ComparisonResult AbsoluteGreater(bool both_negative) {
675 return both_negative ? ComparisonResult::kLessThan
676 : ComparisonResult::kGreaterThan;
677 }
678
679 // Produces result for |x| < |y|, with {both_negative} == sign(x) == sign(y).
AbsoluteLess(bool both_negative)680 ComparisonResult AbsoluteLess(bool both_negative) {
681 return both_negative ? ComparisonResult::kGreaterThan
682 : ComparisonResult::kLessThan;
683 }
684
685 } // namespace
686
687 // (Never returns kUndefined.)
CompareToBigInt(Handle<BigInt> x,Handle<BigInt> y)688 ComparisonResult BigInt::CompareToBigInt(Handle<BigInt> x, Handle<BigInt> y) {
689 bool x_sign = x->sign();
690 if (x_sign != y->sign()) return UnequalSign(x_sign);
691
692 int result = MutableBigInt::AbsoluteCompare(x, y);
693 if (result > 0) return AbsoluteGreater(x_sign);
694 if (result < 0) return AbsoluteLess(x_sign);
695 return ComparisonResult::kEqual;
696 }
697
EqualToBigInt(BigInt x,BigInt y)698 bool BigInt::EqualToBigInt(BigInt x, BigInt y) {
699 if (x.sign() != y.sign()) return false;
700 if (x.length() != y.length()) return false;
701 for (int i = 0; i < x.length(); i++) {
702 if (x.digit(i) != y.digit(i)) return false;
703 }
704 return true;
705 }
706
BitwiseAnd(Isolate * isolate,Handle<BigInt> x,Handle<BigInt> y)707 MaybeHandle<BigInt> BigInt::BitwiseAnd(Isolate* isolate, Handle<BigInt> x,
708 Handle<BigInt> y) {
709 return MutableBigInt::MakeImmutable(MutableBigInt::BitwiseAnd(isolate, x, y));
710 }
711
BitwiseAnd(Isolate * isolate,Handle<BigInt> x,Handle<BigInt> y)712 MaybeHandle<MutableBigInt> MutableBigInt::BitwiseAnd(Isolate* isolate,
713 Handle<BigInt> x,
714 Handle<BigInt> y) {
715 if (!x->sign() && !y->sign()) {
716 return AbsoluteAnd(isolate, x, y);
717 } else if (x->sign() && y->sign()) {
718 int result_length = std::max(x->length(), y->length()) + 1;
719 // (-x) & (-y) == ~(x-1) & ~(y-1) == ~((x-1) | (y-1))
720 // == -(((x-1) | (y-1)) + 1)
721 Handle<MutableBigInt> result;
722 if (!AbsoluteSubOne(isolate, x, result_length).ToHandle(&result)) {
723 return MaybeHandle<MutableBigInt>();
724 }
725 Handle<MutableBigInt> y_1 = AbsoluteSubOne(isolate, y);
726 result = AbsoluteOr(isolate, result, y_1, *result);
727 return AbsoluteAddOne(isolate, result, true, *result);
728 } else {
729 DCHECK(x->sign() != y->sign());
730 // Assume that x is the positive BigInt.
731 if (x->sign()) std::swap(x, y);
732 // x & (-y) == x & ~(y-1) == x &~ (y-1)
733 Handle<MutableBigInt> y_1 = AbsoluteSubOne(isolate, y);
734 return AbsoluteAndNot(isolate, x, y_1);
735 }
736 }
737
BitwiseXor(Isolate * isolate,Handle<BigInt> x,Handle<BigInt> y)738 MaybeHandle<BigInt> BigInt::BitwiseXor(Isolate* isolate, Handle<BigInt> x,
739 Handle<BigInt> y) {
740 return MutableBigInt::MakeImmutable(MutableBigInt::BitwiseXor(isolate, x, y));
741 }
742
BitwiseXor(Isolate * isolate,Handle<BigInt> x,Handle<BigInt> y)743 MaybeHandle<MutableBigInt> MutableBigInt::BitwiseXor(Isolate* isolate,
744 Handle<BigInt> x,
745 Handle<BigInt> y) {
746 if (!x->sign() && !y->sign()) {
747 return AbsoluteXor(isolate, x, y);
748 } else if (x->sign() && y->sign()) {
749 int result_length = std::max(x->length(), y->length());
750 // (-x) ^ (-y) == ~(x-1) ^ ~(y-1) == (x-1) ^ (y-1)
751 Handle<MutableBigInt> result =
752 AbsoluteSubOne(isolate, x, result_length).ToHandleChecked();
753 Handle<MutableBigInt> y_1 = AbsoluteSubOne(isolate, y);
754 return AbsoluteXor(isolate, result, y_1, *result);
755 } else {
756 DCHECK(x->sign() != y->sign());
757 int result_length = std::max(x->length(), y->length()) + 1;
758 // Assume that x is the positive BigInt.
759 if (x->sign()) std::swap(x, y);
760 // x ^ (-y) == x ^ ~(y-1) == ~(x ^ (y-1)) == -((x ^ (y-1)) + 1)
761 Handle<MutableBigInt> result;
762 if (!AbsoluteSubOne(isolate, y, result_length).ToHandle(&result)) {
763 return MaybeHandle<MutableBigInt>();
764 }
765 result = AbsoluteXor(isolate, result, x, *result);
766 return AbsoluteAddOne(isolate, result, true, *result);
767 }
768 }
769
BitwiseOr(Isolate * isolate,Handle<BigInt> x,Handle<BigInt> y)770 MaybeHandle<BigInt> BigInt::BitwiseOr(Isolate* isolate, Handle<BigInt> x,
771 Handle<BigInt> y) {
772 return MutableBigInt::MakeImmutable(MutableBigInt::BitwiseOr(isolate, x, y));
773 }
774
BitwiseOr(Isolate * isolate,Handle<BigInt> x,Handle<BigInt> y)775 MaybeHandle<MutableBigInt> MutableBigInt::BitwiseOr(Isolate* isolate,
776 Handle<BigInt> x,
777 Handle<BigInt> y) {
778 int result_length = std::max(x->length(), y->length());
779 if (!x->sign() && !y->sign()) {
780 return AbsoluteOr(isolate, x, y);
781 } else if (x->sign() && y->sign()) {
782 // (-x) | (-y) == ~(x-1) | ~(y-1) == ~((x-1) & (y-1))
783 // == -(((x-1) & (y-1)) + 1)
784 Handle<MutableBigInt> result =
785 AbsoluteSubOne(isolate, x, result_length).ToHandleChecked();
786 Handle<MutableBigInt> y_1 = AbsoluteSubOne(isolate, y);
787 result = AbsoluteAnd(isolate, result, y_1, *result);
788 return AbsoluteAddOne(isolate, result, true, *result);
789 } else {
790 DCHECK(x->sign() != y->sign());
791 // Assume that x is the positive BigInt.
792 if (x->sign()) std::swap(x, y);
793 // x | (-y) == x | ~(y-1) == ~((y-1) &~ x) == -(((y-1) &~ x) + 1)
794 Handle<MutableBigInt> result =
795 AbsoluteSubOne(isolate, y, result_length).ToHandleChecked();
796 result = AbsoluteAndNot(isolate, result, x, *result);
797 return AbsoluteAddOne(isolate, result, true, *result);
798 }
799 }
800
Increment(Isolate * isolate,Handle<BigInt> x)801 MaybeHandle<BigInt> BigInt::Increment(Isolate* isolate, Handle<BigInt> x) {
802 if (x->sign()) {
803 Handle<MutableBigInt> result = MutableBigInt::AbsoluteSubOne(isolate, x);
804 result->set_sign(true);
805 return MutableBigInt::MakeImmutable(result);
806 } else {
807 return MutableBigInt::MakeImmutable(
808 MutableBigInt::AbsoluteAddOne(isolate, x, false));
809 }
810 }
811
Decrement(Isolate * isolate,Handle<BigInt> x)812 MaybeHandle<BigInt> BigInt::Decrement(Isolate* isolate, Handle<BigInt> x) {
813 MaybeHandle<MutableBigInt> result;
814 if (x->sign()) {
815 result = MutableBigInt::AbsoluteAddOne(isolate, x, true);
816 } else if (x->is_zero()) {
817 // TODO(jkummerow): Consider caching a canonical -1n BigInt.
818 return MutableBigInt::NewFromInt(isolate, -1);
819 } else {
820 result = MutableBigInt::AbsoluteSubOne(isolate, x);
821 }
822 return MutableBigInt::MakeImmutable(result);
823 }
824
CompareToString(Isolate * isolate,Handle<BigInt> x,Handle<String> y)825 Maybe<ComparisonResult> BigInt::CompareToString(Isolate* isolate,
826 Handle<BigInt> x,
827 Handle<String> y) {
828 // a. Let ny be StringToBigInt(y);
829 MaybeHandle<BigInt> maybe_ny = StringToBigInt(isolate, y);
830 // b. If ny is NaN, return undefined.
831 Handle<BigInt> ny;
832 if (!maybe_ny.ToHandle(&ny)) {
833 if (isolate->has_pending_exception()) {
834 return Nothing<ComparisonResult>();
835 } else {
836 return Just(ComparisonResult::kUndefined);
837 }
838 }
839 // c. Return BigInt::lessThan(x, ny).
840 return Just(CompareToBigInt(x, ny));
841 }
842
EqualToString(Isolate * isolate,Handle<BigInt> x,Handle<String> y)843 Maybe<bool> BigInt::EqualToString(Isolate* isolate, Handle<BigInt> x,
844 Handle<String> y) {
845 // a. Let n be StringToBigInt(y).
846 MaybeHandle<BigInt> maybe_n = StringToBigInt(isolate, y);
847 // b. If n is NaN, return false.
848 Handle<BigInt> n;
849 if (!maybe_n.ToHandle(&n)) {
850 if (isolate->has_pending_exception()) {
851 return Nothing<bool>();
852 } else {
853 return Just(false);
854 }
855 }
856 // c. Return the result of x == n.
857 return Just(EqualToBigInt(*x, *n));
858 }
859
EqualToNumber(Handle<BigInt> x,Handle<Object> y)860 bool BigInt::EqualToNumber(Handle<BigInt> x, Handle<Object> y) {
861 DCHECK(y->IsNumber());
862 // a. If x or y are any of NaN, +∞, or -∞, return false.
863 // b. If the mathematical value of x is equal to the mathematical value of y,
864 // return true, otherwise return false.
865 if (y->IsSmi()) {
866 int value = Smi::ToInt(*y);
867 if (value == 0) return x->is_zero();
868 // Any multi-digit BigInt is bigger than a Smi.
869 STATIC_ASSERT(sizeof(digit_t) >= sizeof(value));
870 return (x->length() == 1) && (x->sign() == (value < 0)) &&
871 (x->digit(0) ==
872 static_cast<digit_t>(std::abs(static_cast<int64_t>(value))));
873 }
874 DCHECK(y->IsHeapNumber());
875 double value = Handle<HeapNumber>::cast(y)->value();
876 return CompareToDouble(x, value) == ComparisonResult::kEqual;
877 }
878
CompareToNumber(Handle<BigInt> x,Handle<Object> y)879 ComparisonResult BigInt::CompareToNumber(Handle<BigInt> x, Handle<Object> y) {
880 DCHECK(y->IsNumber());
881 if (y->IsSmi()) {
882 bool x_sign = x->sign();
883 int y_value = Smi::ToInt(*y);
884 bool y_sign = (y_value < 0);
885 if (x_sign != y_sign) return UnequalSign(x_sign);
886
887 if (x->is_zero()) {
888 DCHECK(!y_sign);
889 return y_value == 0 ? ComparisonResult::kEqual
890 : ComparisonResult::kLessThan;
891 }
892 // Any multi-digit BigInt is bigger than a Smi.
893 STATIC_ASSERT(sizeof(digit_t) >= sizeof(y_value));
894 if (x->length() > 1) return AbsoluteGreater(x_sign);
895
896 digit_t abs_value = std::abs(static_cast<int64_t>(y_value));
897 digit_t x_digit = x->digit(0);
898 if (x_digit > abs_value) return AbsoluteGreater(x_sign);
899 if (x_digit < abs_value) return AbsoluteLess(x_sign);
900 return ComparisonResult::kEqual;
901 }
902 DCHECK(y->IsHeapNumber());
903 double value = Handle<HeapNumber>::cast(y)->value();
904 return CompareToDouble(x, value);
905 }
906
CompareToDouble(Handle<BigInt> x,double y)907 ComparisonResult BigInt::CompareToDouble(Handle<BigInt> x, double y) {
908 if (std::isnan(y)) return ComparisonResult::kUndefined;
909 if (y == V8_INFINITY) return ComparisonResult::kLessThan;
910 if (y == -V8_INFINITY) return ComparisonResult::kGreaterThan;
911 bool x_sign = x->sign();
912 // Note that this is different from the double's sign bit for -0. That's
913 // intentional because -0 must be treated like 0.
914 bool y_sign = (y < 0);
915 if (x_sign != y_sign) return UnequalSign(x_sign);
916 if (y == 0) {
917 DCHECK(!x_sign);
918 return x->is_zero() ? ComparisonResult::kEqual
919 : ComparisonResult::kGreaterThan;
920 }
921 if (x->is_zero()) {
922 DCHECK(!y_sign);
923 return ComparisonResult::kLessThan;
924 }
925 uint64_t double_bits = bit_cast<uint64_t>(y);
926 int raw_exponent =
927 static_cast<int>(double_bits >> Double::kPhysicalSignificandSize) & 0x7FF;
928 uint64_t mantissa = double_bits & Double::kSignificandMask;
929 // Non-finite doubles are handled above.
930 DCHECK_NE(raw_exponent, 0x7FF);
931 int exponent = raw_exponent - 0x3FF;
932 if (exponent < 0) {
933 // The absolute value of the double is less than 1. Only 0n has an
934 // absolute value smaller than that, but we've already covered that case.
935 DCHECK(!x->is_zero());
936 return AbsoluteGreater(x_sign);
937 }
938 int x_length = x->length();
939 digit_t x_msd = x->digit(x_length - 1);
940 int msd_leading_zeros = base::bits::CountLeadingZeros(x_msd);
941 int x_bitlength = x_length * kDigitBits - msd_leading_zeros;
942 int y_bitlength = exponent + 1;
943 if (x_bitlength < y_bitlength) return AbsoluteLess(x_sign);
944 if (x_bitlength > y_bitlength) return AbsoluteGreater(x_sign);
945
946 // At this point, we know that signs and bit lengths (i.e. position of
947 // the most significant bit in exponent-free representation) are identical.
948 // {x} is not zero, {y} is finite and not denormal.
949 // Now we virtually convert the double to an integer by shifting its
950 // mantissa according to its exponent, so it will align with the BigInt {x},
951 // and then we compare them bit for bit until we find a difference or the
952 // least significant bit.
953 // <----- 52 ------> <-- virtual trailing zeroes -->
954 // y / mantissa: 1yyyyyyyyyyyyyyyyy 0000000000000000000000000000000
955 // x / digits: 0001xxxx xxxxxxxx xxxxxxxx ...
956 // <--> <------>
957 // msd_topbit kDigitBits
958 //
959 mantissa |= Double::kHiddenBit;
960 const int kMantissaTopBit = 52; // 0-indexed.
961 // 0-indexed position of {x}'s most significant bit within the {msd}.
962 int msd_topbit = kDigitBits - 1 - msd_leading_zeros;
963 DCHECK_EQ(msd_topbit, (x_bitlength - 1) % kDigitBits);
964 // Shifted chunk of {mantissa} for comparing with {digit}.
965 digit_t compare_mantissa;
966 // Number of unprocessed bits in {mantissa}. We'll keep them shifted to
967 // the left (i.e. most significant part) of the underlying uint64_t.
968 int remaining_mantissa_bits = 0;
969
970 // First, compare the most significant digit against the beginning of
971 // the mantissa.
972 if (msd_topbit < kMantissaTopBit) {
973 remaining_mantissa_bits = (kMantissaTopBit - msd_topbit);
974 compare_mantissa = mantissa >> remaining_mantissa_bits;
975 mantissa = mantissa << (64 - remaining_mantissa_bits);
976 } else {
977 DCHECK_GE(msd_topbit, kMantissaTopBit);
978 compare_mantissa = mantissa << (msd_topbit - kMantissaTopBit);
979 mantissa = 0;
980 }
981 if (x_msd > compare_mantissa) return AbsoluteGreater(x_sign);
982 if (x_msd < compare_mantissa) return AbsoluteLess(x_sign);
983
984 // Then, compare additional digits against any remaining mantissa bits.
985 for (int digit_index = x_length - 2; digit_index >= 0; digit_index--) {
986 if (remaining_mantissa_bits > 0) {
987 remaining_mantissa_bits -= kDigitBits;
988 if (sizeof(mantissa) != sizeof(x_msd)) {
989 compare_mantissa = mantissa >> (64 - kDigitBits);
990 // "& 63" to appease compilers. kDigitBits is 32 here anyway.
991 mantissa = mantissa << (kDigitBits & 63);
992 } else {
993 compare_mantissa = mantissa;
994 mantissa = 0;
995 }
996 } else {
997 compare_mantissa = 0;
998 }
999 digit_t digit = x->digit(digit_index);
1000 if (digit > compare_mantissa) return AbsoluteGreater(x_sign);
1001 if (digit < compare_mantissa) return AbsoluteLess(x_sign);
1002 }
1003
1004 // Integer parts are equal; check whether {y} has a fractional part.
1005 if (mantissa != 0) {
1006 DCHECK_GT(remaining_mantissa_bits, 0);
1007 return AbsoluteLess(x_sign);
1008 }
1009 return ComparisonResult::kEqual;
1010 }
1011
ToString(Isolate * isolate,Handle<BigInt> bigint,int radix,ShouldThrow should_throw)1012 MaybeHandle<String> BigInt::ToString(Isolate* isolate, Handle<BigInt> bigint,
1013 int radix, ShouldThrow should_throw) {
1014 if (bigint->is_zero()) {
1015 return isolate->factory()->zero_string();
1016 }
1017 if (base::bits::IsPowerOfTwo(radix)) {
1018 return MutableBigInt::ToStringBasePowerOfTwo(isolate, bigint, radix,
1019 should_throw);
1020 }
1021 return MutableBigInt::ToStringGeneric(isolate, bigint, radix, should_throw);
1022 }
1023
FromNumber(Isolate * isolate,Handle<Object> number)1024 MaybeHandle<BigInt> BigInt::FromNumber(Isolate* isolate,
1025 Handle<Object> number) {
1026 DCHECK(number->IsNumber());
1027 if (number->IsSmi()) {
1028 return MutableBigInt::NewFromInt(isolate, Smi::ToInt(*number));
1029 }
1030 double value = HeapNumber::cast(*number).value();
1031 if (!std::isfinite(value) || (DoubleToInteger(value) != value)) {
1032 THROW_NEW_ERROR(isolate,
1033 NewRangeError(MessageTemplate::kBigIntFromNumber, number),
1034 BigInt);
1035 }
1036 return MutableBigInt::NewFromDouble(isolate, value);
1037 }
1038
FromObject(Isolate * isolate,Handle<Object> obj)1039 MaybeHandle<BigInt> BigInt::FromObject(Isolate* isolate, Handle<Object> obj) {
1040 if (obj->IsJSReceiver()) {
1041 ASSIGN_RETURN_ON_EXCEPTION(
1042 isolate, obj,
1043 JSReceiver::ToPrimitive(Handle<JSReceiver>::cast(obj),
1044 ToPrimitiveHint::kNumber),
1045 BigInt);
1046 }
1047
1048 if (obj->IsBoolean()) {
1049 return MutableBigInt::NewFromInt(isolate, obj->BooleanValue(isolate));
1050 }
1051 if (obj->IsBigInt()) {
1052 return Handle<BigInt>::cast(obj);
1053 }
1054 if (obj->IsString()) {
1055 Handle<BigInt> n;
1056 if (!StringToBigInt(isolate, Handle<String>::cast(obj)).ToHandle(&n)) {
1057 if (isolate->has_pending_exception()) {
1058 return MaybeHandle<BigInt>();
1059 } else {
1060 THROW_NEW_ERROR(isolate,
1061 NewSyntaxError(MessageTemplate::kBigIntFromObject, obj),
1062 BigInt);
1063 }
1064 }
1065 return n;
1066 }
1067
1068 THROW_NEW_ERROR(
1069 isolate, NewTypeError(MessageTemplate::kBigIntFromObject, obj), BigInt);
1070 }
1071
ToNumber(Isolate * isolate,Handle<BigInt> x)1072 Handle<Object> BigInt::ToNumber(Isolate* isolate, Handle<BigInt> x) {
1073 if (x->is_zero()) return Handle<Smi>(Smi::zero(), isolate);
1074 if (x->length() == 1 && x->digit(0) < Smi::kMaxValue) {
1075 int value = static_cast<int>(x->digit(0));
1076 if (x->sign()) value = -value;
1077 return Handle<Smi>(Smi::FromInt(value), isolate);
1078 }
1079 double result = MutableBigInt::ToDouble(x);
1080 return isolate->factory()->NewHeapNumber(result);
1081 }
1082
ToDouble(Handle<BigIntBase> x)1083 double MutableBigInt::ToDouble(Handle<BigIntBase> x) {
1084 if (x->is_zero()) return 0.0;
1085 int x_length = x->length();
1086 digit_t x_msd = x->digit(x_length - 1);
1087 int msd_leading_zeros = base::bits::CountLeadingZeros(x_msd);
1088 int x_bitlength = x_length * kDigitBits - msd_leading_zeros;
1089 if (x_bitlength > 1024) return x->sign() ? -V8_INFINITY : V8_INFINITY;
1090 uint64_t exponent = x_bitlength - 1;
1091 // We need the most significant bit shifted to the position of a double's
1092 // "hidden bit". We also need to hide that MSB, so we shift it out.
1093 uint64_t current_digit = x_msd;
1094 int digit_index = x_length - 1;
1095 int shift = msd_leading_zeros + 1 + (64 - kDigitBits);
1096 DCHECK_LE(1, shift);
1097 DCHECK_LE(shift, 64);
1098 uint64_t mantissa = (shift == 64) ? 0 : current_digit << shift;
1099 mantissa >>= 12;
1100 int mantissa_bits_unset = shift - 12;
1101 // If not all mantissa bits are defined yet, get more digits as needed.
1102 if (mantissa_bits_unset >= kDigitBits && digit_index > 0) {
1103 digit_index--;
1104 current_digit = static_cast<uint64_t>(x->digit(digit_index));
1105 mantissa |= (current_digit << (mantissa_bits_unset - kDigitBits));
1106 mantissa_bits_unset -= kDigitBits;
1107 }
1108 if (mantissa_bits_unset > 0 && digit_index > 0) {
1109 DCHECK_LT(mantissa_bits_unset, kDigitBits);
1110 digit_index--;
1111 current_digit = static_cast<uint64_t>(x->digit(digit_index));
1112 mantissa |= (current_digit >> (kDigitBits - mantissa_bits_unset));
1113 mantissa_bits_unset -= kDigitBits;
1114 }
1115 // If there are unconsumed digits left, we may have to round.
1116 Rounding rounding =
1117 DecideRounding(x, mantissa_bits_unset, digit_index, current_digit);
1118 if (rounding == kRoundUp || (rounding == kTie && (mantissa & 1) == 1)) {
1119 mantissa++;
1120 // Incrementing the mantissa can overflow the mantissa bits. In that case
1121 // the new mantissa will be all zero (plus hidden bit).
1122 if ((mantissa >> Double::kPhysicalSignificandSize) != 0) {
1123 mantissa = 0;
1124 exponent++;
1125 // Incrementing the exponent can overflow too.
1126 if (exponent > 1023) {
1127 return x->sign() ? -V8_INFINITY : V8_INFINITY;
1128 }
1129 }
1130 }
1131 // Assemble the result.
1132 uint64_t sign_bit = x->sign() ? (static_cast<uint64_t>(1) << 63) : 0;
1133 exponent = (exponent + 0x3FF) << Double::kPhysicalSignificandSize;
1134 uint64_t double_bits = sign_bit | exponent | mantissa;
1135 return bit_cast<double>(double_bits);
1136 }
1137
1138 // This is its own function to simplify control flow. The meaning of the
1139 // parameters is defined by {ToDouble}'s local variable usage.
DecideRounding(Handle<BigIntBase> x,int mantissa_bits_unset,int digit_index,uint64_t current_digit)1140 MutableBigInt::Rounding MutableBigInt::DecideRounding(Handle<BigIntBase> x,
1141 int mantissa_bits_unset,
1142 int digit_index,
1143 uint64_t current_digit) {
1144 if (mantissa_bits_unset > 0) return kRoundDown;
1145 int top_unconsumed_bit;
1146 if (mantissa_bits_unset < 0) {
1147 // There are unconsumed bits in {current_digit}.
1148 top_unconsumed_bit = -mantissa_bits_unset - 1;
1149 } else {
1150 DCHECK_EQ(mantissa_bits_unset, 0);
1151 // {current_digit} fit the mantissa exactly; look at the next digit.
1152 if (digit_index == 0) return kRoundDown;
1153 digit_index--;
1154 current_digit = static_cast<uint64_t>(x->digit(digit_index));
1155 top_unconsumed_bit = kDigitBits - 1;
1156 }
1157 // If the most significant remaining bit is 0, round down.
1158 uint64_t bitmask = static_cast<uint64_t>(1) << top_unconsumed_bit;
1159 if ((current_digit & bitmask) == 0) {
1160 return kRoundDown;
1161 }
1162 // If any other remaining bit is set, round up.
1163 bitmask -= 1;
1164 if ((current_digit & bitmask) != 0) return kRoundUp;
1165 while (digit_index > 0) {
1166 digit_index--;
1167 if (x->digit(digit_index) != 0) return kRoundUp;
1168 }
1169 return kTie;
1170 }
1171
BigIntShortPrint(std::ostream & os)1172 void BigInt::BigIntShortPrint(std::ostream& os) {
1173 if (sign()) os << "-";
1174 int len = length();
1175 if (len == 0) {
1176 os << "0";
1177 return;
1178 }
1179 if (len > 1) os << "...";
1180 os << digit(0);
1181 }
1182
1183 // Internal helpers.
1184
AbsoluteAdd(MutableBigInt result,BigInt x,BigInt y)1185 void MutableBigInt::AbsoluteAdd(MutableBigInt result, BigInt x, BigInt y) {
1186 DisallowHeapAllocation no_gc;
1187 digit_t carry = 0;
1188 int i = 0;
1189 for (; i < y.length(); i++) {
1190 digit_t new_carry = 0;
1191 digit_t sum = digit_add(x.digit(i), y.digit(i), &new_carry);
1192 sum = digit_add(sum, carry, &new_carry);
1193 result.set_digit(i, sum);
1194 carry = new_carry;
1195 }
1196 for (; i < x.length(); i++) {
1197 digit_t new_carry = 0;
1198 digit_t sum = digit_add(x.digit(i), carry, &new_carry);
1199 result.set_digit(i, sum);
1200 carry = new_carry;
1201 }
1202 result.set_digit(i, carry);
1203 }
1204
AbsoluteAdd(Isolate * isolate,Handle<BigInt> x,Handle<BigInt> y,bool result_sign)1205 MaybeHandle<BigInt> MutableBigInt::AbsoluteAdd(Isolate* isolate,
1206 Handle<BigInt> x,
1207 Handle<BigInt> y,
1208 bool result_sign) {
1209 if (x->length() < y->length()) return AbsoluteAdd(isolate, y, x, result_sign);
1210 if (x->is_zero()) {
1211 DCHECK(y->is_zero());
1212 return x;
1213 }
1214 if (y->is_zero()) {
1215 return result_sign == x->sign() ? x : BigInt::UnaryMinus(isolate, x);
1216 }
1217 Handle<MutableBigInt> result;
1218 if (!New(isolate, x->length() + 1).ToHandle(&result)) {
1219 return MaybeHandle<BigInt>();
1220 }
1221
1222 AbsoluteAdd(*result, *x, *y);
1223
1224 result->set_sign(result_sign);
1225 return MakeImmutable(result);
1226 }
1227
AbsoluteSub(Isolate * isolate,Handle<BigInt> x,Handle<BigInt> y,bool result_sign)1228 Handle<BigInt> MutableBigInt::AbsoluteSub(Isolate* isolate, Handle<BigInt> x,
1229 Handle<BigInt> y, bool result_sign) {
1230 DCHECK(x->length() >= y->length());
1231 SLOW_DCHECK(AbsoluteCompare(x, y) >= 0);
1232 if (x->is_zero()) {
1233 DCHECK(y->is_zero());
1234 return x;
1235 }
1236 if (y->is_zero()) {
1237 return result_sign == x->sign() ? x : BigInt::UnaryMinus(isolate, x);
1238 }
1239 Handle<MutableBigInt> result = New(isolate, x->length()).ToHandleChecked();
1240
1241 AbsoluteSub(*result, *x, *y);
1242
1243 result->set_sign(result_sign);
1244 return MakeImmutable(result);
1245 }
1246
AbsoluteSub(MutableBigInt result,BigInt x,BigInt y)1247 void MutableBigInt::AbsoluteSub(MutableBigInt result, BigInt x, BigInt y) {
1248 DisallowHeapAllocation no_gc;
1249 digit_t borrow = 0;
1250 int i = 0;
1251 for (; i < y.length(); i++) {
1252 digit_t new_borrow = 0;
1253 digit_t difference = digit_sub(x.digit(i), y.digit(i), &new_borrow);
1254 difference = digit_sub(difference, borrow, &new_borrow);
1255 result.set_digit(i, difference);
1256 borrow = new_borrow;
1257 }
1258 for (; i < x.length(); i++) {
1259 digit_t new_borrow = 0;
1260 digit_t difference = digit_sub(x.digit(i), borrow, &new_borrow);
1261 result.set_digit(i, difference);
1262 borrow = new_borrow;
1263 }
1264 DCHECK_EQ(0, borrow);
1265 }
1266
1267 // Adds 1 to the absolute value of {x} and sets the result's sign to {sign}.
1268 // {result_storage} is optional; if present, it will be used to store the
1269 // result, otherwise a new BigInt will be allocated for the result.
1270 // {result_storage} and {x} may refer to the same BigInt for in-place
1271 // modification.
AbsoluteAddOne(Isolate * isolate,Handle<BigIntBase> x,bool sign,MutableBigInt result_storage)1272 MaybeHandle<MutableBigInt> MutableBigInt::AbsoluteAddOne(
1273 Isolate* isolate, Handle<BigIntBase> x, bool sign,
1274 MutableBigInt result_storage) {
1275 int input_length = x->length();
1276 // The addition will overflow into a new digit if all existing digits are
1277 // at maximum.
1278 bool will_overflow = true;
1279 for (int i = 0; i < input_length; i++) {
1280 if (!digit_ismax(x->digit(i))) {
1281 will_overflow = false;
1282 break;
1283 }
1284 }
1285 int result_length = input_length + will_overflow;
1286 Handle<MutableBigInt> result(result_storage, isolate);
1287 if (result_storage.is_null()) {
1288 if (!New(isolate, result_length).ToHandle(&result)) {
1289 return MaybeHandle<MutableBigInt>();
1290 }
1291 } else {
1292 DCHECK(result->length() == result_length);
1293 }
1294 digit_t carry = 1;
1295 for (int i = 0; i < input_length; i++) {
1296 digit_t new_carry = 0;
1297 result->set_digit(i, digit_add(x->digit(i), carry, &new_carry));
1298 carry = new_carry;
1299 }
1300 if (result_length > input_length) {
1301 result->set_digit(input_length, carry);
1302 } else {
1303 DCHECK_EQ(carry, 0);
1304 }
1305 result->set_sign(sign);
1306 return result;
1307 }
1308
1309 // Subtracts 1 from the absolute value of {x}. {x} must not be zero.
AbsoluteSubOne(Isolate * isolate,Handle<BigIntBase> x)1310 Handle<MutableBigInt> MutableBigInt::AbsoluteSubOne(Isolate* isolate,
1311 Handle<BigIntBase> x) {
1312 DCHECK(!x->is_zero());
1313 // Requesting a result length identical to an existing BigInt's length
1314 // cannot overflow the limit.
1315 return AbsoluteSubOne(isolate, x, x->length()).ToHandleChecked();
1316 }
1317
1318 // Like the above, but you can specify that the allocated result should have
1319 // length {result_length}, which must be at least as large as {x->length()}.
AbsoluteSubOne(Isolate * isolate,Handle<BigIntBase> x,int result_length)1320 MaybeHandle<MutableBigInt> MutableBigInt::AbsoluteSubOne(Isolate* isolate,
1321 Handle<BigIntBase> x,
1322 int result_length) {
1323 DCHECK(!x->is_zero());
1324 DCHECK(result_length >= x->length());
1325 Handle<MutableBigInt> result;
1326 if (!New(isolate, result_length).ToHandle(&result)) {
1327 return MaybeHandle<MutableBigInt>();
1328 }
1329 int length = x->length();
1330 digit_t borrow = 1;
1331 for (int i = 0; i < length; i++) {
1332 digit_t new_borrow = 0;
1333 result->set_digit(i, digit_sub(x->digit(i), borrow, &new_borrow));
1334 borrow = new_borrow;
1335 }
1336 DCHECK_EQ(borrow, 0);
1337 for (int i = length; i < result_length; i++) {
1338 result->set_digit(i, borrow);
1339 }
1340 return result;
1341 }
1342
1343 // Helper for Absolute{And,AndNot,Or,Xor}.
1344 // Performs the given binary {op} on digit pairs of {x} and {y}; when the
1345 // end of the shorter of the two is reached, {extra_digits} configures how
1346 // remaining digits in the longer input (if {symmetric} == kSymmetric, in
1347 // {x} otherwise) are handled: copied to the result or ignored.
1348 // If {result_storage} is non-nullptr, it will be used for the result and
1349 // any extra digits in it will be zeroed out, otherwise a new BigInt (with
1350 // the same length as the longer input) will be allocated.
1351 // {result_storage} may alias {x} or {y} for in-place modification.
1352 // Example:
1353 // y: [ y2 ][ y1 ][ y0 ]
1354 // x: [ x3 ][ x2 ][ x1 ][ x0 ]
1355 // | | | |
1356 // (kCopy) (op) (op) (op)
1357 // | | | |
1358 // v v v v
1359 // result_storage: [ 0 ][ x3 ][ r2 ][ r1 ][ r0 ]
AbsoluteBitwiseOp(Isolate * isolate,Handle<BigIntBase> x,Handle<BigIntBase> y,MutableBigInt result_storage,ExtraDigitsHandling extra_digits,SymmetricOp symmetric,const std::function<digit_t (digit_t,digit_t)> & op)1360 inline Handle<MutableBigInt> MutableBigInt::AbsoluteBitwiseOp(
1361 Isolate* isolate, Handle<BigIntBase> x, Handle<BigIntBase> y,
1362 MutableBigInt result_storage, ExtraDigitsHandling extra_digits,
1363 SymmetricOp symmetric, const std::function<digit_t(digit_t, digit_t)>& op) {
1364 int x_length = x->length();
1365 int y_length = y->length();
1366 int num_pairs = y_length;
1367 if (x_length < y_length) {
1368 num_pairs = x_length;
1369 if (symmetric == kSymmetric) {
1370 std::swap(x, y);
1371 std::swap(x_length, y_length);
1372 }
1373 }
1374 DCHECK(num_pairs == std::min(x_length, y_length));
1375 Handle<MutableBigInt> result(result_storage, isolate);
1376 int result_length = extra_digits == kCopy ? x_length : num_pairs;
1377 if (result_storage.is_null()) {
1378 result = New(isolate, result_length).ToHandleChecked();
1379 } else {
1380 DCHECK(result_storage.length() >= result_length);
1381 result_length = result_storage.length();
1382 }
1383 int i = 0;
1384 for (; i < num_pairs; i++) {
1385 result->set_digit(i, op(x->digit(i), y->digit(i)));
1386 }
1387 if (extra_digits == kCopy) {
1388 for (; i < x_length; i++) {
1389 result->set_digit(i, x->digit(i));
1390 }
1391 }
1392 for (; i < result_length; i++) {
1393 result->set_digit(i, 0);
1394 }
1395 return result;
1396 }
1397
1398 // If {result_storage} is non-nullptr, it will be used for the result,
1399 // otherwise a new BigInt of appropriate length will be allocated.
1400 // {result_storage} may alias {x} or {y} for in-place modification.
AbsoluteAnd(Isolate * isolate,Handle<BigIntBase> x,Handle<BigIntBase> y,MutableBigInt result_storage)1401 Handle<MutableBigInt> MutableBigInt::AbsoluteAnd(Isolate* isolate,
1402 Handle<BigIntBase> x,
1403 Handle<BigIntBase> y,
1404 MutableBigInt result_storage) {
1405 return AbsoluteBitwiseOp(isolate, x, y, result_storage, kSkip, kSymmetric,
1406 [](digit_t a, digit_t b) { return a & b; });
1407 }
1408
1409 // If {result_storage} is non-nullptr, it will be used for the result,
1410 // otherwise a new BigInt of appropriate length will be allocated.
1411 // {result_storage} may alias {x} or {y} for in-place modification.
AbsoluteAndNot(Isolate * isolate,Handle<BigIntBase> x,Handle<BigIntBase> y,MutableBigInt result_storage)1412 Handle<MutableBigInt> MutableBigInt::AbsoluteAndNot(
1413 Isolate* isolate, Handle<BigIntBase> x, Handle<BigIntBase> y,
1414 MutableBigInt result_storage) {
1415 return AbsoluteBitwiseOp(isolate, x, y, result_storage, kCopy, kNotSymmetric,
1416 [](digit_t a, digit_t b) { return a & ~b; });
1417 }
1418
1419 // If {result_storage} is non-nullptr, it will be used for the result,
1420 // otherwise a new BigInt of appropriate length will be allocated.
1421 // {result_storage} may alias {x} or {y} for in-place modification.
AbsoluteOr(Isolate * isolate,Handle<BigIntBase> x,Handle<BigIntBase> y,MutableBigInt result_storage)1422 Handle<MutableBigInt> MutableBigInt::AbsoluteOr(Isolate* isolate,
1423 Handle<BigIntBase> x,
1424 Handle<BigIntBase> y,
1425 MutableBigInt result_storage) {
1426 return AbsoluteBitwiseOp(isolate, x, y, result_storage, kCopy, kSymmetric,
1427 [](digit_t a, digit_t b) { return a | b; });
1428 }
1429
1430 // If {result_storage} is non-nullptr, it will be used for the result,
1431 // otherwise a new BigInt of appropriate length will be allocated.
1432 // {result_storage} may alias {x} or {y} for in-place modification.
AbsoluteXor(Isolate * isolate,Handle<BigIntBase> x,Handle<BigIntBase> y,MutableBigInt result_storage)1433 Handle<MutableBigInt> MutableBigInt::AbsoluteXor(Isolate* isolate,
1434 Handle<BigIntBase> x,
1435 Handle<BigIntBase> y,
1436 MutableBigInt result_storage) {
1437 return AbsoluteBitwiseOp(isolate, x, y, result_storage, kCopy, kSymmetric,
1438 [](digit_t a, digit_t b) { return a ^ b; });
1439 }
1440
1441 // Returns a positive value if abs(x) > abs(y), a negative value if
1442 // abs(x) < abs(y), or zero if abs(x) == abs(y).
AbsoluteCompare(Handle<BigIntBase> x,Handle<BigIntBase> y)1443 int MutableBigInt::AbsoluteCompare(Handle<BigIntBase> x, Handle<BigIntBase> y) {
1444 return MutableBigInt::AbsoluteCompare(*x, *y);
1445 }
1446
AbsoluteCompare(BigIntBase x,BigIntBase y)1447 int MutableBigInt::AbsoluteCompare(BigIntBase x, BigIntBase y) {
1448 DisallowHeapAllocation no_gc;
1449 int diff = x.length() - y.length();
1450 if (diff != 0) return diff;
1451 int i = x.length() - 1;
1452 while (i >= 0 && x.digit(i) == y.digit(i)) i--;
1453 if (i < 0) return 0;
1454 return x.digit(i) > y.digit(i) ? 1 : -1;
1455 }
1456
1457 // Multiplies {multiplicand} with {multiplier} and adds the result to
1458 // {accumulator}, starting at {accumulator_index} for the least-significant
1459 // digit.
1460 // Callers must ensure that {accumulator} is big enough to hold the result.
MultiplyAccumulate(Handle<BigIntBase> multiplicand,digit_t multiplier,Handle<MutableBigInt> accumulator,int accumulator_index)1461 void MutableBigInt::MultiplyAccumulate(Handle<BigIntBase> multiplicand,
1462 digit_t multiplier,
1463 Handle<MutableBigInt> accumulator,
1464 int accumulator_index) {
1465 // This is a minimum requirement; the DCHECK in the second loop below
1466 // will enforce more as needed.
1467 DCHECK(accumulator->length() > multiplicand->length() + accumulator_index);
1468 if (multiplier == 0L) return;
1469 digit_t carry = 0;
1470 digit_t high = 0;
1471 for (int i = 0; i < multiplicand->length(); i++, accumulator_index++) {
1472 digit_t acc = accumulator->digit(accumulator_index);
1473 digit_t new_carry = 0;
1474 // Add last round's carryovers.
1475 acc = digit_add(acc, high, &new_carry);
1476 acc = digit_add(acc, carry, &new_carry);
1477 // Compute this round's multiplication.
1478 digit_t m_digit = multiplicand->digit(i);
1479 digit_t low = digit_mul(multiplier, m_digit, &high);
1480 acc = digit_add(acc, low, &new_carry);
1481 // Store result and prepare for next round.
1482 accumulator->set_digit(accumulator_index, acc);
1483 carry = new_carry;
1484 }
1485 for (; carry != 0 || high != 0; accumulator_index++) {
1486 DCHECK(accumulator_index < accumulator->length());
1487 digit_t acc = accumulator->digit(accumulator_index);
1488 digit_t new_carry = 0;
1489 acc = digit_add(acc, high, &new_carry);
1490 high = 0;
1491 acc = digit_add(acc, carry, &new_carry);
1492 accumulator->set_digit(accumulator_index, acc);
1493 carry = new_carry;
1494 }
1495 }
1496
1497 // Multiplies {source} with {factor} and adds {summand} to the result.
1498 // {result} and {source} may be the same BigInt for inplace modification.
InternalMultiplyAdd(BigIntBase source,digit_t factor,digit_t summand,int n,MutableBigInt result)1499 void MutableBigInt::InternalMultiplyAdd(BigIntBase source, digit_t factor,
1500 digit_t summand, int n,
1501 MutableBigInt result) {
1502 DCHECK(source.length() >= n);
1503 DCHECK(result.length() >= n);
1504 digit_t carry = summand;
1505 digit_t high = 0;
1506 for (int i = 0; i < n; i++) {
1507 digit_t current = source.digit(i);
1508 digit_t new_carry = 0;
1509 // Compute this round's multiplication.
1510 digit_t new_high = 0;
1511 current = digit_mul(current, factor, &new_high);
1512 // Add last round's carryovers.
1513 current = digit_add(current, high, &new_carry);
1514 current = digit_add(current, carry, &new_carry);
1515 // Store result and prepare for next round.
1516 result.set_digit(i, current);
1517 carry = new_carry;
1518 high = new_high;
1519 }
1520 if (result.length() > n) {
1521 result.set_digit(n++, carry + high);
1522 // Current callers don't pass in such large results, but let's be robust.
1523 while (n < result.length()) {
1524 result.set_digit(n++, 0);
1525 }
1526 } else {
1527 CHECK_EQ(carry + high, 0);
1528 }
1529 }
1530
1531 // Multiplies {x} with {factor} and then adds {summand} to it.
InplaceMultiplyAdd(FreshlyAllocatedBigInt x,uintptr_t factor,uintptr_t summand)1532 void BigInt::InplaceMultiplyAdd(FreshlyAllocatedBigInt x, uintptr_t factor,
1533 uintptr_t summand) {
1534 STATIC_ASSERT(sizeof(factor) == sizeof(digit_t));
1535 STATIC_ASSERT(sizeof(summand) == sizeof(digit_t));
1536 MutableBigInt bigint = MutableBigInt::cast(x);
1537 MutableBigInt::InternalMultiplyAdd(bigint, factor, summand, bigint.length(),
1538 bigint);
1539 }
1540
1541 // Divides {x} by {divisor}, returning the result in {quotient} and {remainder}.
1542 // Mathematically, the contract is:
1543 // quotient = (x - remainder) / divisor, with 0 <= remainder < divisor.
1544 // If {quotient} is an empty handle, an appropriately sized BigInt will be
1545 // allocated for it; otherwise the caller must ensure that it is big enough.
1546 // {quotient} can be the same as {x} for an in-place division. {quotient} can
1547 // also be nullptr if the caller is only interested in the remainder.
AbsoluteDivSmall(Isolate * isolate,Handle<BigIntBase> x,digit_t divisor,Handle<MutableBigInt> * quotient,digit_t * remainder)1548 void MutableBigInt::AbsoluteDivSmall(Isolate* isolate, Handle<BigIntBase> x,
1549 digit_t divisor,
1550 Handle<MutableBigInt>* quotient,
1551 digit_t* remainder) {
1552 DCHECK_NE(divisor, 0);
1553 DCHECK(!x->is_zero()); // Callers check anyway, no need to handle this.
1554 *remainder = 0;
1555 int length = x->length();
1556 if (quotient != nullptr) {
1557 if ((*quotient).is_null()) {
1558 *quotient = New(isolate, length).ToHandleChecked();
1559 }
1560 for (int i = length - 1; i >= 0; i--) {
1561 digit_t q = digit_div(*remainder, x->digit(i), divisor, remainder);
1562 (*quotient)->set_digit(i, q);
1563 }
1564 } else {
1565 for (int i = length - 1; i >= 0; i--) {
1566 digit_div(*remainder, x->digit(i), divisor, remainder);
1567 }
1568 }
1569 }
1570
1571 // Divides {dividend} by {divisor}, returning the result in {quotient} and
1572 // {remainder}. Mathematically, the contract is:
1573 // quotient = (dividend - remainder) / divisor, with 0 <= remainder < divisor.
1574 // Both {quotient} and {remainder} are optional, for callers that are only
1575 // interested in one of them.
1576 // See Knuth, Volume 2, section 4.3.1, Algorithm D.
AbsoluteDivLarge(Isolate * isolate,Handle<BigIntBase> dividend,Handle<BigIntBase> divisor,Handle<MutableBigInt> * quotient,Handle<MutableBigInt> * remainder)1577 bool MutableBigInt::AbsoluteDivLarge(Isolate* isolate,
1578 Handle<BigIntBase> dividend,
1579 Handle<BigIntBase> divisor,
1580 Handle<MutableBigInt>* quotient,
1581 Handle<MutableBigInt>* remainder) {
1582 DCHECK_GE(divisor->length(), 2);
1583 DCHECK(dividend->length() >= divisor->length());
1584 // The unusual variable names inside this function are consistent with
1585 // Knuth's book, as well as with Go's implementation of this algorithm.
1586 // Maintaining this consistency is probably more useful than trying to
1587 // come up with more descriptive names for them.
1588 int n = divisor->length();
1589 int m = dividend->length() - n;
1590
1591 // The quotient to be computed.
1592 Handle<MutableBigInt> q;
1593 if (quotient != nullptr) q = New(isolate, m + 1).ToHandleChecked();
1594 // In each iteration, {qhatv} holds {divisor} * {current quotient digit}.
1595 // "v" is the book's name for {divisor}, "qhat" the current quotient digit.
1596 Handle<MutableBigInt> qhatv;
1597 if (!New(isolate, n + 1).ToHandle(&qhatv)) return false;
1598
1599 // D1.
1600 // Left-shift inputs so that the divisor's MSB is set. This is necessary
1601 // to prevent the digit-wise divisions (see digit_div call below) from
1602 // overflowing (they take a two digits wide input, and return a one digit
1603 // result).
1604 int shift = base::bits::CountLeadingZeros(divisor->digit(n - 1));
1605 if (shift > 0) {
1606 divisor = SpecialLeftShift(isolate, divisor, shift, kSameSizeResult)
1607 .ToHandleChecked();
1608 }
1609 // Holds the (continuously updated) remaining part of the dividend, which
1610 // eventually becomes the remainder.
1611 Handle<MutableBigInt> u;
1612 if (!SpecialLeftShift(isolate, dividend, shift, kAlwaysAddOneDigit)
1613 .ToHandle(&u)) {
1614 return false;
1615 }
1616
1617 // D2.
1618 // Iterate over the dividend's digit (like the "grad school" algorithm).
1619 // {vn1} is the divisor's most significant digit.
1620 digit_t vn1 = divisor->digit(n - 1);
1621 uintptr_t work_estimate = 0;
1622 for (int j = m; j >= 0; j--) {
1623 // D3.
1624 // Estimate the current iteration's quotient digit (see Knuth for details).
1625 // {qhat} is the current quotient digit.
1626 digit_t qhat = std::numeric_limits<digit_t>::max();
1627 // {ujn} is the dividend's most significant remaining digit.
1628 digit_t ujn = u->digit(j + n);
1629 if (ujn != vn1) {
1630 // {rhat} is the current iteration's remainder.
1631 digit_t rhat = 0;
1632 // Estimate the current quotient digit by dividing the most significant
1633 // digits of dividend and divisor. The result will not be too small,
1634 // but could be a bit too large.
1635 qhat = digit_div(ujn, u->digit(j + n - 1), vn1, &rhat);
1636
1637 // Decrement the quotient estimate as needed by looking at the next
1638 // digit, i.e. by testing whether
1639 // qhat * v_{n-2} > (rhat << kDigitBits) + u_{j+n-2}.
1640 digit_t vn2 = divisor->digit(n - 2);
1641 digit_t ujn2 = u->digit(j + n - 2);
1642 while (ProductGreaterThan(qhat, vn2, rhat, ujn2)) {
1643 qhat--;
1644 digit_t prev_rhat = rhat;
1645 rhat += vn1;
1646 // v[n-1] >= 0, so this tests for overflow.
1647 if (rhat < prev_rhat) break;
1648 }
1649 }
1650
1651 // D4.
1652 // Multiply the divisor with the current quotient digit, and subtract
1653 // it from the dividend. If there was "borrow", then the quotient digit
1654 // was one too high, so we must correct it and undo one subtraction of
1655 // the (shifted) divisor.
1656 InternalMultiplyAdd(*divisor, qhat, 0, n, *qhatv);
1657 digit_t c = u->InplaceSub(qhatv, j);
1658 if (c != 0) {
1659 c = u->InplaceAdd(divisor, j);
1660 u->set_digit(j + n, u->digit(j + n) + c);
1661 qhat--;
1662 }
1663
1664 if (quotient != nullptr) q->set_digit(j, qhat);
1665
1666 // Division can take a long time. Check for interrupt requests every
1667 // now and then (roughly every 10-20 of milliseconds -- rarely enough
1668 // not to create noticeable overhead, frequently enough not to appear
1669 // frozen).
1670 work_estimate += n;
1671 if (work_estimate > 5000000) {
1672 work_estimate = 0;
1673 StackLimitCheck interrupt_check(isolate);
1674 if (interrupt_check.InterruptRequested() &&
1675 isolate->stack_guard()->HandleInterrupts().IsException(isolate)) {
1676 return false;
1677 }
1678 }
1679 }
1680 if (quotient != nullptr) {
1681 *quotient = q; // Caller will right-trim.
1682 }
1683 if (remainder != nullptr) {
1684 u->InplaceRightShift(shift);
1685 *remainder = u;
1686 }
1687 return true;
1688 }
1689
1690 // Returns whether (factor1 * factor2) > (high << kDigitBits) + low.
ProductGreaterThan(digit_t factor1,digit_t factor2,digit_t high,digit_t low)1691 bool MutableBigInt::ProductGreaterThan(digit_t factor1, digit_t factor2,
1692 digit_t high, digit_t low) {
1693 digit_t result_high;
1694 digit_t result_low = digit_mul(factor1, factor2, &result_high);
1695 return result_high > high || (result_high == high && result_low > low);
1696 }
1697
1698 // Adds {summand} onto {this}, starting with {summand}'s 0th digit
1699 // at {this}'s {start_index}'th digit. Returns the "carry" (0 or 1).
InplaceAdd(Handle<BigIntBase> summand,int start_index)1700 BigInt::digit_t MutableBigInt::InplaceAdd(Handle<BigIntBase> summand,
1701 int start_index) {
1702 digit_t carry = 0;
1703 int n = summand->length();
1704 DCHECK(length() >= start_index + n);
1705 for (int i = 0; i < n; i++) {
1706 digit_t new_carry = 0;
1707 digit_t sum =
1708 digit_add(digit(start_index + i), summand->digit(i), &new_carry);
1709 sum = digit_add(sum, carry, &new_carry);
1710 set_digit(start_index + i, sum);
1711 carry = new_carry;
1712 }
1713 return carry;
1714 }
1715
1716 // Subtracts {subtrahend} from {this}, starting with {subtrahend}'s 0th digit
1717 // at {this}'s {start_index}-th digit. Returns the "borrow" (0 or 1).
InplaceSub(Handle<BigIntBase> subtrahend,int start_index)1718 BigInt::digit_t MutableBigInt::InplaceSub(Handle<BigIntBase> subtrahend,
1719 int start_index) {
1720 digit_t borrow = 0;
1721 int n = subtrahend->length();
1722 DCHECK(length() >= start_index + n);
1723 for (int i = 0; i < n; i++) {
1724 digit_t new_borrow = 0;
1725 digit_t difference =
1726 digit_sub(digit(start_index + i), subtrahend->digit(i), &new_borrow);
1727 difference = digit_sub(difference, borrow, &new_borrow);
1728 set_digit(start_index + i, difference);
1729 borrow = new_borrow;
1730 }
1731 return borrow;
1732 }
1733
InplaceRightShift(int shift)1734 void MutableBigInt::InplaceRightShift(int shift) {
1735 DCHECK_GE(shift, 0);
1736 DCHECK_LT(shift, kDigitBits);
1737 DCHECK_GT(length(), 0);
1738 DCHECK_EQ(digit(0) & ((static_cast<digit_t>(1) << shift) - 1), 0);
1739 if (shift == 0) return;
1740 digit_t carry = digit(0) >> shift;
1741 int last = length() - 1;
1742 for (int i = 0; i < last; i++) {
1743 digit_t d = digit(i + 1);
1744 set_digit(i, (d << (kDigitBits - shift)) | carry);
1745 carry = d >> shift;
1746 }
1747 set_digit(last, carry);
1748 }
1749
1750 // Always copies the input, even when {shift} == 0.
1751 // {shift} must be less than kDigitBits, {x} must be non-zero.
SpecialLeftShift(Isolate * isolate,Handle<BigIntBase> x,int shift,SpecialLeftShiftMode mode)1752 MaybeHandle<MutableBigInt> MutableBigInt::SpecialLeftShift(
1753 Isolate* isolate, Handle<BigIntBase> x, int shift,
1754 SpecialLeftShiftMode mode) {
1755 DCHECK_GE(shift, 0);
1756 DCHECK_LT(shift, kDigitBits);
1757 DCHECK_GT(x->length(), 0);
1758 int n = x->length();
1759 int result_length = mode == kAlwaysAddOneDigit ? n + 1 : n;
1760 Handle<MutableBigInt> result;
1761 if (!New(isolate, result_length).ToHandle(&result)) {
1762 return MaybeHandle<MutableBigInt>();
1763 }
1764 if (shift == 0) {
1765 for (int i = 0; i < n; i++) result->set_digit(i, x->digit(i));
1766 if (mode == kAlwaysAddOneDigit) result->set_digit(n, 0);
1767 return result;
1768 }
1769 DCHECK_GT(shift, 0);
1770 digit_t carry = 0;
1771 for (int i = 0; i < n; i++) {
1772 digit_t d = x->digit(i);
1773 result->set_digit(i, (d << shift) | carry);
1774 carry = d >> (kDigitBits - shift);
1775 }
1776 if (mode == kAlwaysAddOneDigit) {
1777 result->set_digit(n, carry);
1778 } else {
1779 DCHECK_EQ(mode, kSameSizeResult);
1780 DCHECK_EQ(carry, 0);
1781 }
1782 return result;
1783 }
1784
LeftShiftByAbsolute(Isolate * isolate,Handle<BigIntBase> x,Handle<BigIntBase> y)1785 MaybeHandle<BigInt> MutableBigInt::LeftShiftByAbsolute(Isolate* isolate,
1786 Handle<BigIntBase> x,
1787 Handle<BigIntBase> y) {
1788 Maybe<digit_t> maybe_shift = ToShiftAmount(y);
1789 if (maybe_shift.IsNothing()) {
1790 return ThrowBigIntTooBig<BigInt>(isolate);
1791 }
1792 digit_t shift = maybe_shift.FromJust();
1793 int digit_shift = static_cast<int>(shift / kDigitBits);
1794 int bits_shift = static_cast<int>(shift % kDigitBits);
1795 int length = x->length();
1796 bool grow = bits_shift != 0 &&
1797 (x->digit(length - 1) >> (kDigitBits - bits_shift)) != 0;
1798 int result_length = length + digit_shift + grow;
1799 if (result_length > kMaxLength) {
1800 return ThrowBigIntTooBig<BigInt>(isolate);
1801 }
1802 Handle<MutableBigInt> result;
1803 if (!New(isolate, result_length).ToHandle(&result)) {
1804 return MaybeHandle<BigInt>();
1805 }
1806 if (bits_shift == 0) {
1807 int i = 0;
1808 for (; i < digit_shift; i++) result->set_digit(i, 0ul);
1809 for (; i < result_length; i++) {
1810 result->set_digit(i, x->digit(i - digit_shift));
1811 }
1812 } else {
1813 digit_t carry = 0;
1814 for (int i = 0; i < digit_shift; i++) result->set_digit(i, 0ul);
1815 for (int i = 0; i < length; i++) {
1816 digit_t d = x->digit(i);
1817 result->set_digit(i + digit_shift, (d << bits_shift) | carry);
1818 carry = d >> (kDigitBits - bits_shift);
1819 }
1820 if (grow) {
1821 result->set_digit(length + digit_shift, carry);
1822 } else {
1823 DCHECK_EQ(carry, 0);
1824 }
1825 }
1826 result->set_sign(x->sign());
1827 return MakeImmutable(result);
1828 }
1829
RightShiftByAbsolute(Isolate * isolate,Handle<BigIntBase> x,Handle<BigIntBase> y)1830 Handle<BigInt> MutableBigInt::RightShiftByAbsolute(Isolate* isolate,
1831 Handle<BigIntBase> x,
1832 Handle<BigIntBase> y) {
1833 int length = x->length();
1834 bool sign = x->sign();
1835 Maybe<digit_t> maybe_shift = ToShiftAmount(y);
1836 if (maybe_shift.IsNothing()) {
1837 return RightShiftByMaximum(isolate, sign);
1838 }
1839 digit_t shift = maybe_shift.FromJust();
1840 int digit_shift = static_cast<int>(shift / kDigitBits);
1841 int bits_shift = static_cast<int>(shift % kDigitBits);
1842 int result_length = length - digit_shift;
1843 if (result_length <= 0) {
1844 return RightShiftByMaximum(isolate, sign);
1845 }
1846 // For negative numbers, round down if any bit was shifted out (so that e.g.
1847 // -5n >> 1n == -3n and not -2n). Check now whether this will happen and
1848 // whether it can cause overflow into a new digit. If we allocate the result
1849 // large enough up front, it avoids having to do a second allocation later.
1850 bool must_round_down = false;
1851 if (sign) {
1852 const digit_t mask = (static_cast<digit_t>(1) << bits_shift) - 1;
1853 if ((x->digit(digit_shift) & mask) != 0) {
1854 must_round_down = true;
1855 } else {
1856 for (int i = 0; i < digit_shift; i++) {
1857 if (x->digit(i) != 0) {
1858 must_round_down = true;
1859 break;
1860 }
1861 }
1862 }
1863 }
1864 // If bits_shift is non-zero, it frees up bits, preventing overflow.
1865 if (must_round_down && bits_shift == 0) {
1866 // Overflow cannot happen if the most significant digit has unset bits.
1867 digit_t msd = x->digit(length - 1);
1868 bool rounding_can_overflow = digit_ismax(msd);
1869 if (rounding_can_overflow) result_length++;
1870 }
1871
1872 DCHECK_LE(result_length, length);
1873 Handle<MutableBigInt> result = New(isolate, result_length).ToHandleChecked();
1874 if (bits_shift == 0) {
1875 // Zero out any overflow digit (see "rounding_can_overflow" above).
1876 result->set_digit(result_length - 1, 0);
1877 for (int i = digit_shift; i < length; i++) {
1878 result->set_digit(i - digit_shift, x->digit(i));
1879 }
1880 } else {
1881 digit_t carry = x->digit(digit_shift) >> bits_shift;
1882 int last = length - digit_shift - 1;
1883 for (int i = 0; i < last; i++) {
1884 digit_t d = x->digit(i + digit_shift + 1);
1885 result->set_digit(i, (d << (kDigitBits - bits_shift)) | carry);
1886 carry = d >> bits_shift;
1887 }
1888 result->set_digit(last, carry);
1889 }
1890
1891 if (sign) {
1892 result->set_sign(true);
1893 if (must_round_down) {
1894 // Since the result is negative, rounding down means adding one to
1895 // its absolute value. This cannot overflow.
1896 result = AbsoluteAddOne(isolate, result, true, *result).ToHandleChecked();
1897 }
1898 }
1899 return MakeImmutable(result);
1900 }
1901
RightShiftByMaximum(Isolate * isolate,bool sign)1902 Handle<BigInt> MutableBigInt::RightShiftByMaximum(Isolate* isolate, bool sign) {
1903 if (sign) {
1904 // TODO(jkummerow): Consider caching a canonical -1n BigInt.
1905 return NewFromInt(isolate, -1);
1906 } else {
1907 return Zero(isolate);
1908 }
1909 }
1910
1911 // Returns the value of {x} if it is less than the maximum bit length of
1912 // a BigInt, or Nothing otherwise.
ToShiftAmount(Handle<BigIntBase> x)1913 Maybe<BigInt::digit_t> MutableBigInt::ToShiftAmount(Handle<BigIntBase> x) {
1914 if (x->length() > 1) return Nothing<digit_t>();
1915 digit_t value = x->digit(0);
1916 STATIC_ASSERT(kMaxLengthBits < std::numeric_limits<digit_t>::max());
1917 if (value > kMaxLengthBits) return Nothing<digit_t>();
1918 return Just(value);
1919 }
1920
1921 // Lookup table for the maximum number of bits required per character of a
1922 // base-N string representation of a number. To increase accuracy, the array
1923 // value is the actual value multiplied by 32. To generate this table:
1924 // for (var i = 0; i <= 36; i++) { print(Math.ceil(Math.log2(i) * 32) + ","); }
1925 constexpr uint8_t kMaxBitsPerChar[] = {
1926 0, 0, 32, 51, 64, 75, 83, 90, 96, // 0..8
1927 102, 107, 111, 115, 119, 122, 126, 128, // 9..16
1928 131, 134, 136, 139, 141, 143, 145, 147, // 17..24
1929 149, 151, 153, 154, 156, 158, 159, 160, // 25..32
1930 162, 163, 165, 166, // 33..36
1931 };
1932
1933 static const int kBitsPerCharTableShift = 5;
1934 static const size_t kBitsPerCharTableMultiplier = 1u << kBitsPerCharTableShift;
1935
1936 template <typename LocalIsolate>
AllocateFor(LocalIsolate * isolate,int radix,int charcount,ShouldThrow should_throw,AllocationType allocation)1937 MaybeHandle<FreshlyAllocatedBigInt> BigInt::AllocateFor(
1938 LocalIsolate* isolate, int radix, int charcount, ShouldThrow should_throw,
1939 AllocationType allocation) {
1940 DCHECK(2 <= radix && radix <= 36);
1941 DCHECK_GE(charcount, 0);
1942 size_t bits_per_char = kMaxBitsPerChar[radix];
1943 size_t chars = static_cast<size_t>(charcount);
1944 const int roundup = kBitsPerCharTableMultiplier - 1;
1945 if (chars <= (std::numeric_limits<size_t>::max() - roundup) / bits_per_char) {
1946 size_t bits_min = bits_per_char * chars;
1947 // Divide by 32 (see table), rounding up.
1948 bits_min = (bits_min + roundup) >> kBitsPerCharTableShift;
1949 if (bits_min <= static_cast<size_t>(kMaxInt)) {
1950 // Divide by kDigitsBits, rounding up.
1951 int length = static_cast<int>((bits_min + kDigitBits - 1) / kDigitBits);
1952 if (length <= kMaxLength) {
1953 Handle<MutableBigInt> result =
1954 MutableBigInt::New(isolate, length, allocation).ToHandleChecked();
1955 result->InitializeDigits(length);
1956 return result;
1957 }
1958 }
1959 }
1960 // All the overflow/maximum checks above fall through to here.
1961 if (should_throw == kThrowOnError) {
1962 return ThrowBigIntTooBig<FreshlyAllocatedBigInt>(isolate);
1963 } else {
1964 return MaybeHandle<FreshlyAllocatedBigInt>();
1965 }
1966 }
1967 template MaybeHandle<FreshlyAllocatedBigInt> BigInt::AllocateFor(
1968 Isolate* isolate, int radix, int charcount, ShouldThrow should_throw,
1969 AllocationType allocation);
1970 template MaybeHandle<FreshlyAllocatedBigInt> BigInt::AllocateFor(
1971 LocalIsolate* isolate, int radix, int charcount, ShouldThrow should_throw,
1972 AllocationType allocation);
1973
1974 template <typename LocalIsolate>
Finalize(Handle<FreshlyAllocatedBigInt> x,bool sign)1975 Handle<BigInt> BigInt::Finalize(Handle<FreshlyAllocatedBigInt> x, bool sign) {
1976 Handle<MutableBigInt> bigint = Handle<MutableBigInt>::cast(x);
1977 bigint->set_sign(sign);
1978 return MutableBigInt::MakeImmutable<Isolate>(bigint);
1979 }
1980
1981 template Handle<BigInt> BigInt::Finalize<Isolate>(
1982 Handle<FreshlyAllocatedBigInt>, bool);
1983 template Handle<BigInt> BigInt::Finalize<LocalIsolate>(
1984 Handle<FreshlyAllocatedBigInt>, bool);
1985
1986 // The serialization format MUST NOT CHANGE without updating the format
1987 // version in value-serializer.cc!
GetBitfieldForSerialization() const1988 uint32_t BigInt::GetBitfieldForSerialization() const {
1989 // In order to make the serialization format the same on 32/64 bit builds,
1990 // we convert the length-in-digits to length-in-bytes for serialization.
1991 // Being able to do this depends on having enough LengthBits:
1992 STATIC_ASSERT(kMaxLength * kDigitSize <= LengthBits::kMax);
1993 int bytelength = length() * kDigitSize;
1994 return SignBits::encode(sign()) | LengthBits::encode(bytelength);
1995 }
1996
DigitsByteLengthForBitfield(uint32_t bitfield)1997 int BigInt::DigitsByteLengthForBitfield(uint32_t bitfield) {
1998 return LengthBits::decode(bitfield);
1999 }
2000
2001 // The serialization format MUST NOT CHANGE without updating the format
2002 // version in value-serializer.cc!
SerializeDigits(uint8_t * storage)2003 void BigInt::SerializeDigits(uint8_t* storage) {
2004 void* digits =
2005 reinterpret_cast<void*>(ptr() + kDigitsOffset - kHeapObjectTag);
2006 #if defined(V8_TARGET_LITTLE_ENDIAN)
2007 int bytelength = length() * kDigitSize;
2008 memcpy(storage, digits, bytelength);
2009 #elif defined(V8_TARGET_BIG_ENDIAN)
2010 digit_t* digit_storage = reinterpret_cast<digit_t*>(storage);
2011 const digit_t* digit = reinterpret_cast<const digit_t*>(digits);
2012 for (int i = 0; i < length(); i++) {
2013 *digit_storage = ByteReverse(*digit);
2014 digit_storage++;
2015 digit++;
2016 }
2017 #endif // V8_TARGET_BIG_ENDIAN
2018 }
2019
2020 // The serialization format MUST NOT CHANGE without updating the format
2021 // version in value-serializer.cc!
FromSerializedDigits(Isolate * isolate,uint32_t bitfield,Vector<const uint8_t> digits_storage)2022 MaybeHandle<BigInt> BigInt::FromSerializedDigits(
2023 Isolate* isolate, uint32_t bitfield, Vector<const uint8_t> digits_storage) {
2024 int bytelength = LengthBits::decode(bitfield);
2025 DCHECK(digits_storage.length() == bytelength);
2026 bool sign = SignBits::decode(bitfield);
2027 int length = (bytelength + kDigitSize - 1) / kDigitSize; // Round up.
2028 Handle<MutableBigInt> result =
2029 MutableBigInt::Cast(isolate->factory()->NewBigInt(length));
2030 result->initialize_bitfield(sign, length);
2031 void* digits =
2032 reinterpret_cast<void*>(result->ptr() + kDigitsOffset - kHeapObjectTag);
2033 #if defined(V8_TARGET_LITTLE_ENDIAN)
2034 memcpy(digits, digits_storage.begin(), bytelength);
2035 void* padding_start =
2036 reinterpret_cast<void*>(reinterpret_cast<Address>(digits) + bytelength);
2037 memset(padding_start, 0, length * kDigitSize - bytelength);
2038 #elif defined(V8_TARGET_BIG_ENDIAN)
2039 digit_t* digit = reinterpret_cast<digit_t*>(digits);
2040 const digit_t* digit_storage =
2041 reinterpret_cast<const digit_t*>(digits_storage.begin());
2042 for (int i = 0; i < bytelength / kDigitSize; i++) {
2043 *digit = ByteReverse(*digit_storage);
2044 digit_storage++;
2045 digit++;
2046 }
2047 if (bytelength % kDigitSize) {
2048 *digit = 0;
2049 byte* digit_byte = reinterpret_cast<byte*>(digit);
2050 digit_byte += sizeof(*digit) - 1;
2051 const byte* digit_storage_byte =
2052 reinterpret_cast<const byte*>(digit_storage);
2053 for (int i = 0; i < bytelength % kDigitSize; i++) {
2054 *digit_byte = *digit_storage_byte;
2055 digit_byte--;
2056 digit_storage_byte++;
2057 }
2058 }
2059 #endif // V8_TARGET_BIG_ENDIAN
2060 return MutableBigInt::MakeImmutable(result);
2061 }
2062
2063 static const char kConversionChars[] = "0123456789abcdefghijklmnopqrstuvwxyz";
2064
ToStringBasePowerOfTwo(Isolate * isolate,Handle<BigIntBase> x,int radix,ShouldThrow should_throw)2065 MaybeHandle<String> MutableBigInt::ToStringBasePowerOfTwo(
2066 Isolate* isolate, Handle<BigIntBase> x, int radix,
2067 ShouldThrow should_throw) {
2068 STATIC_ASSERT(base::bits::IsPowerOfTwo(kDigitBits));
2069 DCHECK(base::bits::IsPowerOfTwo(radix));
2070 DCHECK(radix >= 2 && radix <= 32);
2071 DCHECK(!x->is_zero());
2072
2073 const int length = x->length();
2074 const bool sign = x->sign();
2075 const int bits_per_char = base::bits::CountTrailingZeros(radix);
2076 const int char_mask = radix - 1;
2077 // Compute the length of the resulting string: divide the bit length of the
2078 // BigInt by the number of bits representable per character (rounding up).
2079 const digit_t msd = x->digit(length - 1);
2080 const int msd_leading_zeros = base::bits::CountLeadingZeros(msd);
2081 const size_t bit_length = length * kDigitBits - msd_leading_zeros;
2082 const size_t chars_required =
2083 (bit_length + bits_per_char - 1) / bits_per_char + sign;
2084
2085 if (chars_required > String::kMaxLength) {
2086 if (should_throw == kThrowOnError) {
2087 THROW_NEW_ERROR(isolate, NewInvalidStringLengthError(), String);
2088 } else {
2089 return MaybeHandle<String>();
2090 }
2091 }
2092
2093 Handle<SeqOneByteString> result =
2094 isolate->factory()
2095 ->NewRawOneByteString(static_cast<int>(chars_required))
2096 .ToHandleChecked();
2097 DisallowHeapAllocation no_gc;
2098 uint8_t* buffer = result->GetChars(no_gc);
2099 // Print the number into the string, starting from the last position.
2100 int pos = static_cast<int>(chars_required - 1);
2101 digit_t digit = 0;
2102 // Keeps track of how many unprocessed bits there are in {digit}.
2103 int available_bits = 0;
2104 for (int i = 0; i < length - 1; i++) {
2105 digit_t new_digit = x->digit(i);
2106 // Take any leftover bits from the last iteration into account.
2107 int current = (digit | (new_digit << available_bits)) & char_mask;
2108 buffer[pos--] = kConversionChars[current];
2109 int consumed_bits = bits_per_char - available_bits;
2110 digit = new_digit >> consumed_bits;
2111 available_bits = kDigitBits - consumed_bits;
2112 while (available_bits >= bits_per_char) {
2113 buffer[pos--] = kConversionChars[digit & char_mask];
2114 digit >>= bits_per_char;
2115 available_bits -= bits_per_char;
2116 }
2117 }
2118 // Take any leftover bits from the last iteration into account.
2119 int current = (digit | (msd << available_bits)) & char_mask;
2120 buffer[pos--] = kConversionChars[current];
2121 digit = msd >> (bits_per_char - available_bits);
2122 while (digit != 0) {
2123 buffer[pos--] = kConversionChars[digit & char_mask];
2124 digit >>= bits_per_char;
2125 }
2126 if (sign) buffer[pos--] = '-';
2127 DCHECK_EQ(pos, -1);
2128 return result;
2129 }
2130
ToStringGeneric(Isolate * isolate,Handle<BigIntBase> x,int radix,ShouldThrow should_throw)2131 MaybeHandle<String> MutableBigInt::ToStringGeneric(Isolate* isolate,
2132 Handle<BigIntBase> x,
2133 int radix,
2134 ShouldThrow should_throw) {
2135 DCHECK(radix >= 2 && radix <= 36);
2136 DCHECK(!x->is_zero());
2137 Heap* heap = isolate->heap();
2138
2139 const int length = x->length();
2140 const bool sign = x->sign();
2141
2142 // Compute (an overapproximation of) the length of the resulting string:
2143 // Divide bit length of the BigInt by bits representable per character.
2144 const size_t bit_length =
2145 length * kDigitBits - base::bits::CountLeadingZeros(x->digit(length - 1));
2146 // Maximum number of bits we can represent with one character. We'll use this
2147 // to find an appropriate chunk size below.
2148 const uint8_t max_bits_per_char = kMaxBitsPerChar[radix];
2149 // For estimating result length, we have to be pessimistic and work with
2150 // the minimum number of bits one character can represent.
2151 const uint8_t min_bits_per_char = max_bits_per_char - 1;
2152 // Perform the following computation with uint64_t to avoid overflows.
2153 uint64_t chars_required = bit_length;
2154 chars_required *= kBitsPerCharTableMultiplier;
2155 chars_required += min_bits_per_char - 1; // Round up.
2156 chars_required /= min_bits_per_char;
2157 chars_required += sign;
2158
2159 if (chars_required > String::kMaxLength) {
2160 if (should_throw == kThrowOnError) {
2161 THROW_NEW_ERROR(isolate, NewInvalidStringLengthError(), String);
2162 } else {
2163 return MaybeHandle<String>();
2164 }
2165 }
2166 Handle<SeqOneByteString> result =
2167 isolate->factory()
2168 ->NewRawOneByteString(static_cast<int>(chars_required))
2169 .ToHandleChecked();
2170
2171 #if DEBUG
2172 // Zap the string first.
2173 {
2174 DisallowHeapAllocation no_gc;
2175 uint8_t* chars = result->GetChars(no_gc);
2176 for (int i = 0; i < static_cast<int>(chars_required); i++) chars[i] = '?';
2177 }
2178 #endif
2179
2180 // We assemble the result string in reverse order, and then reverse it.
2181 // TODO(jkummerow): Consider building the string from the right, and
2182 // left-shifting it if the length estimate was too large.
2183 int pos = 0;
2184
2185 digit_t last_digit;
2186 if (length == 1) {
2187 last_digit = x->digit(0);
2188 } else {
2189 int chunk_chars =
2190 kDigitBits * kBitsPerCharTableMultiplier / max_bits_per_char;
2191 digit_t chunk_divisor = digit_pow(radix, chunk_chars);
2192 // By construction of chunk_chars, there can't have been overflow.
2193 DCHECK_NE(chunk_divisor, 0);
2194 int nonzero_digit = length - 1;
2195 DCHECK_NE(x->digit(nonzero_digit), 0);
2196 // {rest} holds the part of the BigInt that we haven't looked at yet.
2197 // Not to be confused with "remainder"!
2198 Handle<MutableBigInt> rest;
2199 // In the first round, divide the input, allocating a new BigInt for
2200 // the result == rest; from then on divide the rest in-place.
2201 Handle<BigIntBase>* dividend = &x;
2202 uintptr_t work_estimate = 0;
2203 do {
2204 digit_t chunk;
2205 AbsoluteDivSmall(isolate, *dividend, chunk_divisor, &rest, &chunk);
2206 DCHECK(!rest.is_null());
2207 dividend = reinterpret_cast<Handle<BigIntBase>*>(&rest);
2208 DisallowHeapAllocation no_gc;
2209 uint8_t* chars = result->GetChars(no_gc);
2210 for (int i = 0; i < chunk_chars; i++) {
2211 chars[pos++] = kConversionChars[chunk % radix];
2212 chunk /= radix;
2213 }
2214 DCHECK_EQ(chunk, 0);
2215 if (rest->digit(nonzero_digit) == 0) nonzero_digit--;
2216 // We can never clear more than one digit per iteration, because
2217 // chunk_divisor is smaller than max digit value.
2218 DCHECK_GT(rest->digit(nonzero_digit), 0);
2219
2220 // String formatting can take a long time. Check for interrupt requests
2221 // every now and then (roughly every 10-20 of milliseconds -- rarely
2222 // enough not to create noticeable overhead, frequently enough not to
2223 // appear frozen).
2224 work_estimate += length;
2225 if (work_estimate > 500000) {
2226 work_estimate = 0;
2227 StackLimitCheck interrupt_check(isolate);
2228 if (interrupt_check.InterruptRequested()) {
2229 {
2230 AllowHeapAllocation might_throw;
2231 if (isolate->stack_guard()->HandleInterrupts().IsException(
2232 isolate)) {
2233 return MaybeHandle<String>();
2234 }
2235 }
2236 // If there was an interrupt request but no termination, reload
2237 // the raw characters pointer (as the string might have moved).
2238 chars = result->GetChars(no_gc);
2239 }
2240 }
2241 } while (nonzero_digit > 0);
2242 last_digit = rest->digit(0);
2243 }
2244 DisallowHeapAllocation no_gc;
2245 uint8_t* chars = result->GetChars(no_gc);
2246 do {
2247 chars[pos++] = kConversionChars[last_digit % radix];
2248 last_digit /= radix;
2249 } while (last_digit > 0);
2250 DCHECK_GE(pos, 1);
2251 DCHECK(pos <= static_cast<int>(chars_required));
2252 // Remove leading zeroes.
2253 while (pos > 1 && chars[pos - 1] == '0') pos--;
2254 if (sign) chars[pos++] = '-';
2255 // Trim any over-allocation (which can happen due to conservative estimates).
2256 if (pos < static_cast<int>(chars_required)) {
2257 result->synchronized_set_length(pos);
2258 int string_size =
2259 SeqOneByteString::SizeFor(static_cast<int>(chars_required));
2260 int needed_size = SeqOneByteString::SizeFor(pos);
2261 if (needed_size < string_size) {
2262 Address new_end = result->address() + needed_size;
2263 heap->CreateFillerObjectAt(new_end, (string_size - needed_size),
2264 ClearRecordedSlots::kNo);
2265 }
2266 }
2267 // Reverse the string.
2268 for (int i = 0, j = pos - 1; i < j; i++, j--) {
2269 uint8_t tmp = chars[i];
2270 chars[i] = chars[j];
2271 chars[j] = tmp;
2272 }
2273 #if DEBUG
2274 // Verify that all characters have been written.
2275 DCHECK(result->length() == pos);
2276 for (int i = 0; i < pos; i++) DCHECK_NE(chars[i], '?');
2277 #endif
2278 return result;
2279 }
2280
AsIntN(Isolate * isolate,uint64_t n,Handle<BigInt> x)2281 Handle<BigInt> BigInt::AsIntN(Isolate* isolate, uint64_t n, Handle<BigInt> x) {
2282 if (x->is_zero()) return x;
2283 if (n == 0) return MutableBigInt::Zero(isolate);
2284 uint64_t needed_length = (n + kDigitBits - 1) / kDigitBits;
2285 uint64_t x_length = static_cast<uint64_t>(x->length());
2286 // If {x} has less than {n} bits, return it directly.
2287 if (x_length < needed_length) return x;
2288 DCHECK_LE(needed_length, kMaxInt);
2289 digit_t top_digit = x->digit(static_cast<int>(needed_length) - 1);
2290 digit_t compare_digit = static_cast<digit_t>(1) << ((n - 1) % kDigitBits);
2291 if (x_length == needed_length && top_digit < compare_digit) return x;
2292 // Otherwise we have to truncate (which is a no-op in the special case
2293 // of x == -2^(n-1)), and determine the right sign. We also might have
2294 // to subtract from 2^n to simulate having two's complement representation.
2295 // In most cases, the result's sign is x->sign() xor "(n-1)th bit present".
2296 // The only exception is when x is negative, has the (n-1)th bit, and all
2297 // its bits below (n-1) are zero. In that case, the result is the minimum
2298 // n-bit integer (example: asIntN(3, -12n) => -4n).
2299 bool has_bit = (top_digit & compare_digit) == compare_digit;
2300 DCHECK_LE(n, kMaxInt);
2301 int N = static_cast<int>(n);
2302 if (!has_bit) {
2303 return MutableBigInt::TruncateToNBits(isolate, N, x);
2304 }
2305 if (!x->sign()) {
2306 return MutableBigInt::TruncateAndSubFromPowerOfTwo(isolate, N, x, true);
2307 }
2308 // Negative numbers must subtract from 2^n, except for the special case
2309 // described above.
2310 if ((top_digit & (compare_digit - 1)) == 0) {
2311 for (int i = static_cast<int>(needed_length) - 2; i >= 0; i--) {
2312 if (x->digit(i) != 0) {
2313 return MutableBigInt::TruncateAndSubFromPowerOfTwo(isolate, N, x,
2314 false);
2315 }
2316 }
2317 // Truncation is no-op if x == -2^(n-1).
2318 if (x_length == needed_length && top_digit == compare_digit) return x;
2319 return MutableBigInt::TruncateToNBits(isolate, N, x);
2320 }
2321 return MutableBigInt::TruncateAndSubFromPowerOfTwo(isolate, N, x, false);
2322 }
2323
AsUintN(Isolate * isolate,uint64_t n,Handle<BigInt> x)2324 MaybeHandle<BigInt> BigInt::AsUintN(Isolate* isolate, uint64_t n,
2325 Handle<BigInt> x) {
2326 if (x->is_zero()) return x;
2327 if (n == 0) return MutableBigInt::Zero(isolate);
2328 // If {x} is negative, simulate two's complement representation.
2329 if (x->sign()) {
2330 if (n > kMaxLengthBits) {
2331 return ThrowBigIntTooBig<BigInt>(isolate);
2332 }
2333 return MutableBigInt::TruncateAndSubFromPowerOfTwo(
2334 isolate, static_cast<int>(n), x, false);
2335 }
2336 // If {x} is positive and has up to {n} bits, return it directly.
2337 if (n >= kMaxLengthBits) return x;
2338 STATIC_ASSERT(kMaxLengthBits < kMaxInt - kDigitBits);
2339 int needed_length = static_cast<int>((n + kDigitBits - 1) / kDigitBits);
2340 if (x->length() < needed_length) return x;
2341 int bits_in_top_digit = n % kDigitBits;
2342 if (x->length() == needed_length) {
2343 if (bits_in_top_digit == 0) return x;
2344 digit_t top_digit = x->digit(needed_length - 1);
2345 if ((top_digit >> bits_in_top_digit) == 0) return x;
2346 }
2347 // Otherwise, truncate.
2348 DCHECK_LE(n, kMaxInt);
2349 return MutableBigInt::TruncateToNBits(isolate, static_cast<int>(n), x);
2350 }
2351
TruncateToNBits(Isolate * isolate,int n,Handle<BigInt> x)2352 Handle<BigInt> MutableBigInt::TruncateToNBits(Isolate* isolate, int n,
2353 Handle<BigInt> x) {
2354 // Only call this when there's something to do.
2355 DCHECK_NE(n, 0);
2356 DCHECK_GT(x->length(), n / kDigitBits);
2357
2358 int needed_digits = (n + (kDigitBits - 1)) / kDigitBits;
2359 DCHECK_LE(needed_digits, x->length());
2360 Handle<MutableBigInt> result = New(isolate, needed_digits).ToHandleChecked();
2361
2362 // Copy all digits except the MSD.
2363 int last = needed_digits - 1;
2364 for (int i = 0; i < last; i++) {
2365 result->set_digit(i, x->digit(i));
2366 }
2367
2368 // The MSD might contain extra bits that we don't want.
2369 digit_t msd = x->digit(last);
2370 if (n % kDigitBits != 0) {
2371 int drop = kDigitBits - (n % kDigitBits);
2372 msd = (msd << drop) >> drop;
2373 }
2374 result->set_digit(last, msd);
2375 result->set_sign(x->sign());
2376 return MakeImmutable(result);
2377 }
2378
2379 // Subtracts the least significant n bits of abs(x) from 2^n.
TruncateAndSubFromPowerOfTwo(Isolate * isolate,int n,Handle<BigInt> x,bool result_sign)2380 Handle<BigInt> MutableBigInt::TruncateAndSubFromPowerOfTwo(Isolate* isolate,
2381 int n,
2382 Handle<BigInt> x,
2383 bool result_sign) {
2384 DCHECK_NE(n, 0);
2385 DCHECK_LE(n, kMaxLengthBits);
2386
2387 int needed_digits = (n + (kDigitBits - 1)) / kDigitBits;
2388 DCHECK_LE(needed_digits, kMaxLength); // Follows from n <= kMaxLengthBits.
2389 Handle<MutableBigInt> result = New(isolate, needed_digits).ToHandleChecked();
2390
2391 // Process all digits except the MSD.
2392 int i = 0;
2393 int last = needed_digits - 1;
2394 int x_length = x->length();
2395 digit_t borrow = 0;
2396 // Take digits from {x} unless its length is exhausted.
2397 int limit = std::min(last, x_length);
2398 for (; i < limit; i++) {
2399 digit_t new_borrow = 0;
2400 digit_t difference = digit_sub(0, x->digit(i), &new_borrow);
2401 difference = digit_sub(difference, borrow, &new_borrow);
2402 result->set_digit(i, difference);
2403 borrow = new_borrow;
2404 }
2405 // Then simulate leading zeroes in {x} as needed.
2406 for (; i < last; i++) {
2407 digit_t new_borrow = 0;
2408 digit_t difference = digit_sub(0, borrow, &new_borrow);
2409 result->set_digit(i, difference);
2410 borrow = new_borrow;
2411 }
2412
2413 // The MSD might contain extra bits that we don't want.
2414 digit_t msd = last < x_length ? x->digit(last) : 0;
2415 int msd_bits_consumed = n % kDigitBits;
2416 digit_t result_msd;
2417 if (msd_bits_consumed == 0) {
2418 digit_t new_borrow = 0;
2419 result_msd = digit_sub(0, msd, &new_borrow);
2420 result_msd = digit_sub(result_msd, borrow, &new_borrow);
2421 } else {
2422 int drop = kDigitBits - msd_bits_consumed;
2423 msd = (msd << drop) >> drop;
2424 digit_t minuend_msd = static_cast<digit_t>(1) << (kDigitBits - drop);
2425 digit_t new_borrow = 0;
2426 result_msd = digit_sub(minuend_msd, msd, &new_borrow);
2427 result_msd = digit_sub(result_msd, borrow, &new_borrow);
2428 DCHECK_EQ(new_borrow, 0); // result < 2^n.
2429 // If all subtracted bits were zero, we have to get rid of the
2430 // materialized minuend_msd again.
2431 result_msd &= (minuend_msd - 1);
2432 }
2433 result->set_digit(last, result_msd);
2434 result->set_sign(result_sign);
2435 return MakeImmutable(result);
2436 }
2437
FromInt64(Isolate * isolate,int64_t n)2438 Handle<BigInt> BigInt::FromInt64(Isolate* isolate, int64_t n) {
2439 if (n == 0) return MutableBigInt::Zero(isolate);
2440 STATIC_ASSERT(kDigitBits == 64 || kDigitBits == 32);
2441 int length = 64 / kDigitBits;
2442 Handle<MutableBigInt> result =
2443 MutableBigInt::Cast(isolate->factory()->NewBigInt(length));
2444 bool sign = n < 0;
2445 result->initialize_bitfield(sign, length);
2446 uint64_t absolute;
2447 if (!sign) {
2448 absolute = static_cast<uint64_t>(n);
2449 } else {
2450 if (n == std::numeric_limits<int64_t>::min()) {
2451 absolute = static_cast<uint64_t>(std::numeric_limits<int64_t>::max()) + 1;
2452 } else {
2453 absolute = static_cast<uint64_t>(-n);
2454 }
2455 }
2456 result->set_64_bits(absolute);
2457 return MutableBigInt::MakeImmutable(result);
2458 }
2459
FromUint64(Isolate * isolate,uint64_t n)2460 Handle<BigInt> BigInt::FromUint64(Isolate* isolate, uint64_t n) {
2461 if (n == 0) return MutableBigInt::Zero(isolate);
2462 STATIC_ASSERT(kDigitBits == 64 || kDigitBits == 32);
2463 int length = 64 / kDigitBits;
2464 Handle<MutableBigInt> result =
2465 MutableBigInt::Cast(isolate->factory()->NewBigInt(length));
2466 result->initialize_bitfield(false, length);
2467 result->set_64_bits(n);
2468 return MutableBigInt::MakeImmutable(result);
2469 }
2470
FromWords64(Isolate * isolate,int sign_bit,int words64_count,const uint64_t * words)2471 MaybeHandle<BigInt> BigInt::FromWords64(Isolate* isolate, int sign_bit,
2472 int words64_count,
2473 const uint64_t* words) {
2474 if (words64_count < 0 || words64_count > kMaxLength / (64 / kDigitBits)) {
2475 return ThrowBigIntTooBig<BigInt>(isolate);
2476 }
2477 if (words64_count == 0) return MutableBigInt::Zero(isolate);
2478 STATIC_ASSERT(kDigitBits == 64 || kDigitBits == 32);
2479 int length = (64 / kDigitBits) * words64_count;
2480 DCHECK_GT(length, 0);
2481 if (kDigitBits == 32 && words[words64_count - 1] <= (1ULL << 32)) length--;
2482
2483 Handle<MutableBigInt> result;
2484 if (!MutableBigInt::New(isolate, length).ToHandle(&result)) {
2485 return MaybeHandle<BigInt>();
2486 }
2487
2488 result->set_sign(sign_bit);
2489 if (kDigitBits == 64) {
2490 for (int i = 0; i < length; ++i) {
2491 result->set_digit(i, static_cast<digit_t>(words[i]));
2492 }
2493 } else {
2494 for (int i = 0; i < length; i += 2) {
2495 digit_t lo = static_cast<digit_t>(words[i / 2]);
2496 digit_t hi = static_cast<digit_t>(words[i / 2] >> 32);
2497 result->set_digit(i, lo);
2498 if (i + 1 < length) result->set_digit(i + 1, hi);
2499 }
2500 }
2501
2502 return MutableBigInt::MakeImmutable(result);
2503 }
2504
Words64Count()2505 int BigInt::Words64Count() {
2506 STATIC_ASSERT(kDigitBits == 64 || kDigitBits == 32);
2507 return length() / (64 / kDigitBits) +
2508 (kDigitBits == 32 && length() % 2 == 1 ? 1 : 0);
2509 }
2510
ToWordsArray64(int * sign_bit,int * words64_count,uint64_t * words)2511 void BigInt::ToWordsArray64(int* sign_bit, int* words64_count,
2512 uint64_t* words) {
2513 DCHECK_NE(sign_bit, nullptr);
2514 DCHECK_NE(words64_count, nullptr);
2515 *sign_bit = sign();
2516 int available_words = *words64_count;
2517 *words64_count = Words64Count();
2518 if (available_words == 0) return;
2519 DCHECK_NE(words, nullptr);
2520
2521 int len = length();
2522 if (kDigitBits == 64) {
2523 for (int i = 0; i < len && i < available_words; ++i) words[i] = digit(i);
2524 } else {
2525 for (int i = 0; i < len && available_words > 0; i += 2) {
2526 uint64_t lo = digit(i);
2527 uint64_t hi = (i + 1) < len ? digit(i + 1) : 0;
2528 words[i / 2] = lo | (hi << 32);
2529 available_words--;
2530 }
2531 }
2532 }
2533
GetRawBits(BigIntBase x,bool * lossless)2534 uint64_t MutableBigInt::GetRawBits(BigIntBase x, bool* lossless) {
2535 if (lossless != nullptr) *lossless = true;
2536 if (x.is_zero()) return 0;
2537 int len = x.length();
2538 STATIC_ASSERT(kDigitBits == 64 || kDigitBits == 32);
2539 if (lossless != nullptr && len > 64 / kDigitBits) *lossless = false;
2540 uint64_t raw = static_cast<uint64_t>(x.digit(0));
2541 if (kDigitBits == 32 && len > 1) {
2542 raw |= static_cast<uint64_t>(x.digit(1)) << 32;
2543 }
2544 // Simulate two's complement. MSVC dislikes "-raw".
2545 return x.sign() ? ((~raw) + 1u) : raw;
2546 }
2547
AsInt64(bool * lossless)2548 int64_t BigInt::AsInt64(bool* lossless) {
2549 uint64_t raw = MutableBigInt::GetRawBits(*this, lossless);
2550 int64_t result = static_cast<int64_t>(raw);
2551 if (lossless != nullptr && (result < 0) != sign()) *lossless = false;
2552 return result;
2553 }
2554
AsUint64(bool * lossless)2555 uint64_t BigInt::AsUint64(bool* lossless) {
2556 uint64_t result = MutableBigInt::GetRawBits(*this, lossless);
2557 if (lossless != nullptr && sign()) *lossless = false;
2558 return result;
2559 }
2560
2561 // Digit arithmetic helpers.
2562
2563 #if V8_TARGET_ARCH_32_BIT
2564 #define HAVE_TWODIGIT_T 1
2565 using twodigit_t = uint64_t;
2566 #elif defined(__SIZEOF_INT128__)
2567 // Both Clang and GCC support this on x64.
2568 #define HAVE_TWODIGIT_T 1
2569 using twodigit_t = __uint128_t;
2570 #endif
2571
2572 // {carry} must point to an initialized digit_t and will either be incremented
2573 // by one or left alone.
digit_add(digit_t a,digit_t b,digit_t * carry)2574 inline BigInt::digit_t MutableBigInt::digit_add(digit_t a, digit_t b,
2575 digit_t* carry) {
2576 #if HAVE_TWODIGIT_T
2577 twodigit_t result = static_cast<twodigit_t>(a) + static_cast<twodigit_t>(b);
2578 *carry += result >> kDigitBits;
2579 return static_cast<digit_t>(result);
2580 #else
2581 digit_t result = a + b;
2582 if (result < a) *carry += 1;
2583 return result;
2584 #endif
2585 }
2586
2587 // {borrow} must point to an initialized digit_t and will either be incremented
2588 // by one or left alone.
digit_sub(digit_t a,digit_t b,digit_t * borrow)2589 inline BigInt::digit_t MutableBigInt::digit_sub(digit_t a, digit_t b,
2590 digit_t* borrow) {
2591 #if HAVE_TWODIGIT_T
2592 twodigit_t result = static_cast<twodigit_t>(a) - static_cast<twodigit_t>(b);
2593 *borrow += (result >> kDigitBits) & 1;
2594 return static_cast<digit_t>(result);
2595 #else
2596 digit_t result = a - b;
2597 if (result > a) *borrow += 1;
2598 return static_cast<digit_t>(result);
2599 #endif
2600 }
2601
2602 // Returns the low half of the result. High half is in {high}.
digit_mul(digit_t a,digit_t b,digit_t * high)2603 inline BigInt::digit_t MutableBigInt::digit_mul(digit_t a, digit_t b,
2604 digit_t* high) {
2605 #if HAVE_TWODIGIT_T
2606 twodigit_t result = static_cast<twodigit_t>(a) * static_cast<twodigit_t>(b);
2607 *high = result >> kDigitBits;
2608 return static_cast<digit_t>(result);
2609 #else
2610 // Multiply in half-pointer-sized chunks.
2611 // For inputs [AH AL]*[BH BL], the result is:
2612 //
2613 // [AL*BL] // r_low
2614 // + [AL*BH] // r_mid1
2615 // + [AH*BL] // r_mid2
2616 // + [AH*BH] // r_high
2617 // = [R4 R3 R2 R1] // high = [R4 R3], low = [R2 R1]
2618 //
2619 // Where of course we must be careful with carries between the columns.
2620 digit_t a_low = a & kHalfDigitMask;
2621 digit_t a_high = a >> kHalfDigitBits;
2622 digit_t b_low = b & kHalfDigitMask;
2623 digit_t b_high = b >> kHalfDigitBits;
2624
2625 digit_t r_low = a_low * b_low;
2626 digit_t r_mid1 = a_low * b_high;
2627 digit_t r_mid2 = a_high * b_low;
2628 digit_t r_high = a_high * b_high;
2629
2630 digit_t carry = 0;
2631 digit_t low = digit_add(r_low, r_mid1 << kHalfDigitBits, &carry);
2632 low = digit_add(low, r_mid2 << kHalfDigitBits, &carry);
2633 *high =
2634 (r_mid1 >> kHalfDigitBits) + (r_mid2 >> kHalfDigitBits) + r_high + carry;
2635 return low;
2636 #endif
2637 }
2638
2639 // Returns the quotient.
2640 // quotient = (high << kDigitBits + low - remainder) / divisor
digit_div(digit_t high,digit_t low,digit_t divisor,digit_t * remainder)2641 BigInt::digit_t MutableBigInt::digit_div(digit_t high, digit_t low,
2642 digit_t divisor, digit_t* remainder) {
2643 DCHECK(high < divisor);
2644 #if V8_TARGET_ARCH_X64 && (__GNUC__ || __clang__)
2645 digit_t quotient;
2646 digit_t rem;
2647 __asm__("divq %[divisor]"
2648 // Outputs: {quotient} will be in rax, {rem} in rdx.
2649 : "=a"(quotient), "=d"(rem)
2650 // Inputs: put {high} into rdx, {low} into rax, and {divisor} into
2651 // any register or stack slot.
2652 : "d"(high), "a"(low), [divisor] "rm"(divisor));
2653 *remainder = rem;
2654 return quotient;
2655 #elif V8_TARGET_ARCH_IA32 && (__GNUC__ || __clang__)
2656 digit_t quotient;
2657 digit_t rem;
2658 __asm__("divl %[divisor]"
2659 // Outputs: {quotient} will be in eax, {rem} in edx.
2660 : "=a"(quotient), "=d"(rem)
2661 // Inputs: put {high} into edx, {low} into eax, and {divisor} into
2662 // any register or stack slot.
2663 : "d"(high), "a"(low), [divisor] "rm"(divisor));
2664 *remainder = rem;
2665 return quotient;
2666 #else
2667 static const digit_t kHalfDigitBase = 1ull << kHalfDigitBits;
2668 // Adapted from Warren, Hacker's Delight, p. 152.
2669 int s = base::bits::CountLeadingZeros(divisor);
2670 DCHECK_NE(s, kDigitBits); // {divisor} is not 0.
2671 divisor <<= s;
2672
2673 digit_t vn1 = divisor >> kHalfDigitBits;
2674 digit_t vn0 = divisor & kHalfDigitMask;
2675 // {s} can be 0. {low >> kDigitBits} would be undefined behavior, so
2676 // we mask the shift amount with {kShiftMask}, and the result with
2677 // {s_zero_mask} which is 0 if s == 0 and all 1-bits otherwise.
2678 STATIC_ASSERT(sizeof(intptr_t) == sizeof(digit_t));
2679 const int kShiftMask = kDigitBits - 1;
2680 digit_t s_zero_mask =
2681 static_cast<digit_t>(static_cast<intptr_t>(-s) >> (kDigitBits - 1));
2682 digit_t un32 =
2683 (high << s) | ((low >> ((kDigitBits - s) & kShiftMask)) & s_zero_mask);
2684 digit_t un10 = low << s;
2685 digit_t un1 = un10 >> kHalfDigitBits;
2686 digit_t un0 = un10 & kHalfDigitMask;
2687 digit_t q1 = un32 / vn1;
2688 digit_t rhat = un32 - q1 * vn1;
2689
2690 while (q1 >= kHalfDigitBase || q1 * vn0 > rhat * kHalfDigitBase + un1) {
2691 q1--;
2692 rhat += vn1;
2693 if (rhat >= kHalfDigitBase) break;
2694 }
2695
2696 digit_t un21 = un32 * kHalfDigitBase + un1 - q1 * divisor;
2697 digit_t q0 = un21 / vn1;
2698 rhat = un21 - q0 * vn1;
2699
2700 while (q0 >= kHalfDigitBase || q0 * vn0 > rhat * kHalfDigitBase + un0) {
2701 q0--;
2702 rhat += vn1;
2703 if (rhat >= kHalfDigitBase) break;
2704 }
2705
2706 *remainder = (un21 * kHalfDigitBase + un0 - q0 * divisor) >> s;
2707 return q1 * kHalfDigitBase + q0;
2708 #endif
2709 }
2710
2711 // Raises {base} to the power of {exponent}. Does not check for overflow.
digit_pow(digit_t base,digit_t exponent)2712 BigInt::digit_t MutableBigInt::digit_pow(digit_t base, digit_t exponent) {
2713 digit_t result = 1ull;
2714 while (exponent > 0) {
2715 if (exponent & 1) {
2716 result *= base;
2717 }
2718 exponent >>= 1;
2719 base *= base;
2720 }
2721 return result;
2722 }
2723
2724 #undef HAVE_TWODIGIT_T
2725
set_64_bits(uint64_t bits)2726 void MutableBigInt::set_64_bits(uint64_t bits) {
2727 STATIC_ASSERT(kDigitBits == 64 || kDigitBits == 32);
2728 if (kDigitBits == 64) {
2729 set_digit(0, static_cast<digit_t>(bits));
2730 } else {
2731 set_digit(0, static_cast<digit_t>(bits & 0xFFFFFFFFu));
2732 set_digit(1, static_cast<digit_t>(bits >> 32));
2733 }
2734 }
2735
2736 #ifdef OBJECT_PRINT
BigIntBasePrint(std::ostream & os)2737 void BigIntBase::BigIntBasePrint(std::ostream& os) {
2738 DisallowHeapAllocation no_gc;
2739 PrintHeader(os, "BigInt");
2740 int len = length();
2741 os << "\n- length: " << len;
2742 os << "\n- sign: " << sign();
2743 if (len > 0) {
2744 os << "\n- digits:";
2745 for (int i = 0; i < len; i++) {
2746 os << "\n 0x" << std::hex << digit(i);
2747 }
2748 }
2749 os << std::dec << "\n";
2750 }
2751 #endif // OBJECT_PRINT
2752
MutableBigInt_AbsoluteAddAndCanonicalize(Address result_addr,Address x_addr,Address y_addr)2753 void MutableBigInt_AbsoluteAddAndCanonicalize(Address result_addr,
2754 Address x_addr, Address y_addr) {
2755 BigInt x = BigInt::cast(Object(x_addr));
2756 BigInt y = BigInt::cast(Object(y_addr));
2757 MutableBigInt result = MutableBigInt::cast(Object(result_addr));
2758
2759 MutableBigInt::AbsoluteAdd(result, x, y);
2760 MutableBigInt::Canonicalize(result);
2761 }
2762
MutableBigInt_AbsoluteCompare(Address x_addr,Address y_addr)2763 int32_t MutableBigInt_AbsoluteCompare(Address x_addr, Address y_addr) {
2764 BigInt x = BigInt::cast(Object(x_addr));
2765 BigInt y = BigInt::cast(Object(y_addr));
2766
2767 return MutableBigInt::AbsoluteCompare(x, y);
2768 }
2769
MutableBigInt_AbsoluteSubAndCanonicalize(Address result_addr,Address x_addr,Address y_addr)2770 void MutableBigInt_AbsoluteSubAndCanonicalize(Address result_addr,
2771 Address x_addr, Address y_addr) {
2772 BigInt x = BigInt::cast(Object(x_addr));
2773 BigInt y = BigInt::cast(Object(y_addr));
2774 MutableBigInt result = MutableBigInt::cast(Object(result_addr));
2775
2776 MutableBigInt::AbsoluteSub(result, x, y);
2777 MutableBigInt::Canonicalize(result);
2778 }
2779
2780 } // namespace internal
2781 } // namespace v8
2782