bigint.h 11 KB
Newer Older
1 2 3 4 5 6 7 8 9
// Copyright 2017 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef V8_OBJECTS_BIGINT_H_
#define V8_OBJECTS_BIGINT_H_

#include "src/globals.h"
#include "src/objects.h"
10
#include "src/objects/heap-object.h"
11 12 13 14 15 16 17 18
#include "src/utils.h"

// Has to be the last include (doesn't have include guards):
#include "src/objects/object-macros.h"

namespace v8 {
namespace internal {

19
class BigInt;
20 21
class ValueDeserializer;
class ValueSerializer;
22

23 24
// BigIntBase is just the raw data object underlying a BigInt. Use with care!
// Most code should be using BigInts instead.
25
class BigIntBase : public HeapObjectPtr {
26 27
 public:
  inline int length() const {
28
    int32_t bitfield = RELAXED_READ_INT32_FIELD(this, kBitfieldOffset);
29 30 31 32 33
    return LengthBits::decode(static_cast<uint32_t>(bitfield));
  }

  // For use by the GC.
  inline int synchronized_length() const {
34
    int32_t bitfield = ACQUIRE_READ_INT32_FIELD(this, kBitfieldOffset);
35 36 37
    return LengthBits::decode(static_cast<uint32_t>(bitfield));
  }

38 39 40
  static inline BigIntBase unchecked_cast(ObjectPtr o) {
    return bit_cast<BigIntBase>(o);
  }
41 42 43 44 45 46

  // The maximum kMaxLengthBits that the current implementation supports
  // would be kMaxInt - kSystemPointerSize * kBitsPerByte - 1.
  // Since we want a platform independent limit, choose a nice round number
  // somewhere below that maximum.
  static const int kMaxLengthBits = 1 << 30;  // ~1 billion.
47 48
  static const int kMaxLength =
      kMaxLengthBits / (kSystemPointerSize * kBitsPerByte);
49

50 51
  // Sign and length are stored in the same bitfield.  Since the GC needs to be
  // able to read the length concurrently, the getters and setters are atomic.
52
  static const int kLengthFieldBits = 30;
53
  STATIC_ASSERT(kMaxLength <= ((1 << kLengthFieldBits) - 1));
54 55 56
  class SignBits : public BitField<bool, 0, 1> {};
  class LengthBits : public BitField<int, SignBits::kNext, kLengthFieldBits> {};
  STATIC_ASSERT(LengthBits::kNext <= 32);
57

58 59 60 61 62 63 64 65 66 67
  // Layout description.
#define BIGINT_FIELDS(V)                                                  \
  V(kBitfieldOffset, kInt32Size)                                          \
  V(kOptionalPaddingOffset, POINTER_SIZE_PADDING(kOptionalPaddingOffset)) \
  /* Header size. */                                                      \
  V(kHeaderSize, 0)                                                       \
  V(kDigitsOffset, 0)

  DEFINE_FIELD_OFFSET_CONSTANTS(HeapObject::kHeaderSize, BIGINT_FIELDS)
#undef BIGINT_FIELDS
68

69
 private:
70
  friend class ::v8::internal::BigInt;  // MSVC wants full namespace.
71 72 73 74 75
  friend class MutableBigInt;

  typedef uintptr_t digit_t;
  static const int kDigitSize = sizeof(digit_t);
  // kMaxLength definition assumes this:
76
  STATIC_ASSERT(kDigitSize == kSystemPointerSize);
77 78 79 80 81 82 83

  static const int kDigitBits = kDigitSize * kBitsPerByte;
  static const int kHalfDigitBits = kDigitBits / 2;
  static const digit_t kHalfDigitMask = (1ull << kHalfDigitBits) - 1;

  // sign() == true means negative.
  inline bool sign() const {
84
    int32_t bitfield = RELAXED_READ_INT32_FIELD(this, kBitfieldOffset);
85 86 87 88 89
    return SignBits::decode(static_cast<uint32_t>(bitfield));
  }

  inline digit_t digit(int n) const {
    SLOW_DCHECK(0 <= n && n < length());
90
    Address address = FIELD_ADDR(this, kDigitsOffset + n * kDigitSize);
91
    return *reinterpret_cast<digit_t*>(address);
92 93 94 95
  }

  bool is_zero() const { return length() == 0; }

96 97 98 99
  // Only serves to make macros happy; other code should use IsBigInt.
  bool IsBigIntBase() const { return true; }

  OBJECT_CONSTRUCTORS(BigIntBase, HeapObjectPtr);
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
};

class FreshlyAllocatedBigInt : public BigIntBase {
  // This class is essentially the publicly accessible abstract version of
  // MutableBigInt (which is a hidden implementation detail). It serves as
  // the return type of Factory::NewBigInt, and makes it possible to enforce
  // casting restrictions:
  // - FreshlyAllocatedBigInt can be cast explicitly to MutableBigInt
  //   (with MutableBigInt::Cast) for initialization.
  // - MutableBigInt can be cast/converted explicitly to BigInt
  //   (with MutableBigInt::MakeImmutable); is afterwards treated as readonly.
  // - No accidental implicit casting is possible from BigInt to MutableBigInt
  //   (and no explicit operator is provided either).

 public:
115 116 117 118
  inline static FreshlyAllocatedBigInt cast(Object* object);
  inline static FreshlyAllocatedBigInt unchecked_cast(ObjectPtr o) {
    return bit_cast<FreshlyAllocatedBigInt>(o);
  }
119

120 121 122 123 124 125 126 127 128
  // Clear uninitialized padding space.
  inline void clear_padding() {
    if (FIELD_SIZE(kOptionalPaddingOffset)) {
      DCHECK_EQ(4, FIELD_SIZE(kOptionalPaddingOffset));
      memset(reinterpret_cast<void*>(address() + kOptionalPaddingOffset), 0,
             FIELD_SIZE(kOptionalPaddingOffset));
    }
  }

129
 private:
130 131 132 133
  // Only serves to make macros happy; other code should use IsBigInt.
  bool IsFreshlyAllocatedBigInt() const { return true; }

  OBJECT_CONSTRUCTORS(FreshlyAllocatedBigInt, BigIntBase);
134 135
};

136
// Arbitrary precision integers in JavaScript.
137
class V8_EXPORT_PRIVATE BigInt : public BigIntBase {
138
 public:
139 140 141
  // Implementation of the Spec methods, see:
  // https://tc39.github.io/proposal-bigint/#sec-numeric-types
  // Sections 1.1.1 through 1.1.19.
142 143 144
  static Handle<BigInt> UnaryMinus(Isolate* isolate, Handle<BigInt> x);
  static MaybeHandle<BigInt> BitwiseNot(Isolate* isolate, Handle<BigInt> x);
  static MaybeHandle<BigInt> Exponentiate(Isolate* isolate, Handle<BigInt> base,
145
                                          Handle<BigInt> exponent);
146 147 148 149 150 151 152 153 154 155 156 157 158 159
  static MaybeHandle<BigInt> Multiply(Isolate* isolate, Handle<BigInt> x,
                                      Handle<BigInt> y);
  static MaybeHandle<BigInt> Divide(Isolate* isolate, Handle<BigInt> x,
                                    Handle<BigInt> y);
  static MaybeHandle<BigInt> Remainder(Isolate* isolate, Handle<BigInt> x,
                                       Handle<BigInt> y);
  static MaybeHandle<BigInt> Add(Isolate* isolate, Handle<BigInt> x,
                                 Handle<BigInt> y);
  static MaybeHandle<BigInt> Subtract(Isolate* isolate, Handle<BigInt> x,
                                      Handle<BigInt> y);
  static MaybeHandle<BigInt> LeftShift(Isolate* isolate, Handle<BigInt> x,
                                       Handle<BigInt> y);
  static MaybeHandle<BigInt> SignedRightShift(Isolate* isolate,
                                              Handle<BigInt> x,
160
                                              Handle<BigInt> y);
161 162
  static MaybeHandle<BigInt> UnsignedRightShift(Isolate* isolate,
                                                Handle<BigInt> x,
163
                                                Handle<BigInt> y);
164 165
  // More convenient version of "bool LessThan(x, y)".
  static ComparisonResult CompareToBigInt(Handle<BigInt> x, Handle<BigInt> y);
166
  static bool EqualToBigInt(BigInt x, BigInt y);
167 168 169 170 171 172
  static MaybeHandle<BigInt> BitwiseAnd(Isolate* isolate, Handle<BigInt> x,
                                        Handle<BigInt> y);
  static MaybeHandle<BigInt> BitwiseXor(Isolate* isolate, Handle<BigInt> x,
                                        Handle<BigInt> y);
  static MaybeHandle<BigInt> BitwiseOr(Isolate* isolate, Handle<BigInt> x,
                                       Handle<BigInt> y);
173

174
  // Other parts of the public interface.
175 176
  static MaybeHandle<BigInt> Increment(Isolate* isolate, Handle<BigInt> x);
  static MaybeHandle<BigInt> Decrement(Isolate* isolate, Handle<BigInt> x);
177

178 179 180
  bool ToBoolean() { return !is_zero(); }
  uint32_t Hash() {
    // TODO(jkummerow): Improve this. At least use length and sign.
181
    return is_zero() ? 0 : ComputeLongHash(static_cast<uint64_t>(digit(0)));
182 183
  }

184 185
  static bool EqualToString(Isolate* isolate, Handle<BigInt> x,
                            Handle<String> y);
186
  static bool EqualToNumber(Handle<BigInt> x, Handle<Object> y);
187 188
  static ComparisonResult CompareToString(Isolate* isolate, Handle<BigInt> x,
                                          Handle<String> y);
189 190 191 192
  static ComparisonResult CompareToNumber(Handle<BigInt> x, Handle<Object> y);
  // Exposed for tests, do not call directly. Use CompareToNumber() instead.
  static ComparisonResult CompareToDouble(Handle<BigInt> x, double y);

193 194 195
  static Handle<BigInt> AsIntN(Isolate* isolate, uint64_t n, Handle<BigInt> x);
  static MaybeHandle<BigInt> AsUintN(Isolate* isolate, uint64_t n,
                                     Handle<BigInt> x);
196

197 198
  static Handle<BigInt> FromInt64(Isolate* isolate, int64_t n);
  static Handle<BigInt> FromUint64(Isolate* isolate, uint64_t n);
199 200 201
  static MaybeHandle<BigInt> FromWords64(Isolate* isolate, int sign_bit,
                                         int words64_count,
                                         const uint64_t* words);
202 203
  int64_t AsInt64(bool* lossless = nullptr);
  uint64_t AsUint64(bool* lossless = nullptr);
204 205
  int Words64Count();
  void ToWordsArray64(int* sign_bit, int* words64_count, uint64_t* words);
206

207
  DECL_CAST2(BigInt)
208 209
  DECL_VERIFIER(BigInt)
  DECL_PRINTER(BigInt)
210
  void BigIntShortPrint(std::ostream& os);
211

212 213 214 215
  inline static int SizeFor(int length) {
    return kHeaderSize + length * kDigitSize;
  }

216
  static MaybeHandle<String> ToString(Isolate* isolate, Handle<BigInt> bigint,
217 218
                                      int radix = 10,
                                      ShouldThrow should_throw = kThrowOnError);
219 220 221
  // "The Number value for x", see:
  // https://tc39.github.io/ecma262/#sec-ecmascript-language-types-number-type
  // Returns a Smi or HeapNumber.
222
  static Handle<Object> ToNumber(Isolate* isolate, Handle<BigInt> x);
223

224 225 226 227 228 229 230
  // ECMAScript's NumberToBigInt
  static MaybeHandle<BigInt> FromNumber(Isolate* isolate,
                                        Handle<Object> number);

  // ECMAScript's ToBigInt (throws for Number input)
  static MaybeHandle<BigInt> FromObject(Isolate* isolate, Handle<Object> obj);

231
  class BodyDescriptor;
232 233

 private:
234
  friend class StringToBigIntHelper;
235 236
  friend class ValueDeserializer;
  friend class ValueSerializer;
237

238
  // Special functions for StringToBigIntHelper:
239 240
  static Handle<BigInt> Zero(Isolate* isolate);
  static MaybeHandle<FreshlyAllocatedBigInt> AllocateFor(
241 242
      Isolate* isolate, int radix, int charcount, ShouldThrow should_throw,
      PretenureFlag pretenure);
243 244 245
  static void InplaceMultiplyAdd(Handle<FreshlyAllocatedBigInt> x,
                                 uintptr_t factor, uintptr_t summand);
  static Handle<BigInt> Finalize(Handle<FreshlyAllocatedBigInt> x, bool sign);
246

247 248 249 250 251 252
  // Special functions for ValueSerializer/ValueDeserializer:
  uint32_t GetBitfieldForSerialization() const;
  static int DigitsByteLengthForBitfield(uint32_t bitfield);
  // Expects {storage} to have a length of at least
  // {DigitsByteLengthForBitfield(GetBitfieldForSerialization())}.
  void SerializeDigits(uint8_t* storage);
253
  V8_WARN_UNUSED_RESULT static MaybeHandle<BigInt> FromSerializedDigits(
254 255 256
      Isolate* isolate, uint32_t bitfield, Vector<const uint8_t> digits_storage,
      PretenureFlag pretenure);

257
  OBJECT_CONSTRUCTORS(BigInt, BigIntBase);
258 259 260 261 262 263 264 265
};

}  // namespace internal
}  // namespace v8

#include "src/objects/object-macros-undef.h"

#endif  // V8_OBJECTS_BIGINT_H_