deps: V8: backport 1361b2a49d02

Original commit message:

    [strings] improve array index hash distribution

    Previously, the hashes stored in a Name's raw_hash_field for decimal
    numeric strings (potential array indices) consist of the literal
    integer value along with the length of the string. This means
    consecutive numeric strings can have consecutive hash values, which
    can lead to O(n^2) probing for insertion in the worst case when e.g.
    a non-numeric string happen to land in the these buckets.

    This patch adds a build-time flag v8_enable_seeded_array_index_hash that
    scrambles the 24-bit array-index value stored in a Name's raw_hash_field
    to improve the distribution.

    x ^= x >> kShift; x = (x * m1) & kMask;    // round 1
    x ^= x >> kShift; x = (x * m2) & kMask;    // round 2
    x ^= x >> kShift;                          // finalize

    To decode, apply the same steps with the modular inverses of m1 and m2
    in reverse order.

    x ^= x >> kShift; x = (x * m2_inv) & kMask;    // round 1
    x ^= x >> kShift; x = (x * m1_inv) & kMask;    // round 2
    x ^= x >> kShift;                              // finalize

    where kShift = kArrayIndexValueBits / 2, kMask = kArrayIndexValueMask,
    m1, m2 (both odd) are the lower bits of the rapidhash secrets, m1_inv,
    m2_inv (modular inverses) are precomputed modular inverse of m1 and m2.
    The pre-computed values are appended to the hash_seed ByteArray in
    ReadOnlyRoots and accessed in generated code to reduce overhead.
    In call sites that don't already have access to the seeds, we read them
    from the current isolate group/isolate's read only roots.

    To consolidate the code that encode/decode these hashes, this patch
    adds MakeArrayIndexHash/DecodeArrayIndexFromHashField in C++ and CSA
    that perform seeding/unseeding if enabled, and updates places where
    encoding/decoding of array index is needed to use them.

    Bug: 477515021
    Change-Id: I350afe511951a54c4378396538152cc56565fd55
    Reviewed-on: https://chromium-review.googlesource.com/c/v8/v8/+/7564330
    Reviewed-by: Leszek Swirski <leszeks@chromium.org>
    Commit-Queue: Joyee Cheung <joyee@igalia.com>
    Cr-Commit-Position: refs/heads/main@{#105596}

Refs: https://github.com/v8/v8/commit/1361b2a49d020a718dc5495713eae0fa67d697b9
Co-authored-by: Joyee Cheung <joyeec9h3@gmail.com>
PR-URL: https://github.com/nodejs-private/node-private/pull/828
This commit is contained in:
Joyee CheungandJoyee Cheung authored and Juan José Arboleda committed 2026-03-20 13:24:06 -05:00
1 parent 045013366f
commit 87521e99d1
22 files changed
+397 -50

No files matched your search

+1 -1
View File
@@ -38,7 +38,7 @@
# Reset this number to 0 on major V8 upgrades.
# Increment by one for each non-official patch applied to deps/v8.
'v8_embedder_string': '-node.43',
'v8_embedder_string': '-node.44',
##### V8 defaults for Node.js #####
+6
View File
@@ -230,6 +230,11 @@ v8_flag(
default = False,
)
v8_flag(
name = "v8_enable_seeded_array_index_hash",
default = False,
)
selects.config_setting_group(
name = "enable_drumbrake_x64",
match_all = [
@@ -485,6 +490,7 @@ v8_config(
"v8_enable_webassembly": "V8_ENABLE_WEBASSEMBLY",
"v8_enable_drumbrake": "V8_ENABLE_DRUMBRAKE",
"v8_enable_drumbrake_tracing": "V8_ENABLE_DRUMBRAKE_TRACING",
"v8_enable_seeded_array_index_hash": "V8_ENABLE_SEEDED_ARRAY_INDEX_HASH",
"v8_jitless": "V8_JITLESS",
"v8_enable_vtunejit": "ENABLE_VTUNE_JIT_INTERFACE",
},
+6
View File
@@ -518,6 +518,9 @@ declare_args() {
# Use a hard-coded secret value when hashing.
v8_use_default_hasher_secret = true
# Enable seeded array index hash.
v8_enable_seeded_array_index_hash = false
}
# Derived defaults.
@@ -1209,6 +1212,9 @@ config("features") {
if (v8_enable_lite_mode) {
defines += [ "V8_LITE_MODE" ]
}
if (v8_enable_seeded_array_index_hash) {
defines += [ "V8_ENABLE_SEEDED_ARRAY_INDEX_HASH" ]
}
if (v8_enable_gdbjit) {
defines += [ "ENABLE_GDB_JIT_INTERFACE" ]
}
+2 -1
View File
@@ -83,7 +83,8 @@ bool AstRawString::AsArrayIndex(uint32_t* index) const {
// can't be convertible to an array index.
if (!IsIntegerIndex()) return false;
if (length() <= Name::kMaxCachedArrayIndexLength) {
*index = Name::ArrayIndexValueBits::decode(raw_hash_field_);
*index = StringHasher::DecodeArrayIndexFromHashField(
raw_hash_field_, HashSeed(GetReadOnlyRoots()));
return true;
}
// Might be an index, but too big to cache it. Do the slow conversion. This
+2 -2
View File
@@ -299,7 +299,7 @@ transitioning javascript builtin NumberParseFloat(
const hash: NameHash = s.raw_hash_field;
if (IsIntegerIndex(hash) &&
hash.array_index_length < kMaxCachedArrayIndexLength) {
const arrayIndex: uint32 = hash.array_index_value;
const arrayIndex: uint32 = DecodeArrayIndexFromHashField(hash);
return SmiFromUint32(arrayIndex);
}
// Fall back to the runtime to convert string to a number.
@@ -350,7 +350,7 @@ transitioning builtin ParseInt(
const hash: NameHash = s.raw_hash_field;
if (IsIntegerIndex(hash) &&
hash.array_index_length < kMaxCachedArrayIndexLength) {
const arrayIndex: uint32 = hash.array_index_value;
const arrayIndex: uint32 = DecodeArrayIndexFromHashField(hash);
return SmiFromUint32(arrayIndex);
}
// Fall back to the runtime.
+2 -2
View File
@@ -1517,8 +1517,8 @@ builtin WasmStringToDouble(s: String): float64 {
const hash: NameHash = s.raw_hash_field;
if (IsIntegerIndex(hash) &&
hash.array_index_length < kMaxCachedArrayIndexLength) {
const arrayIndex: int32 = Signed(hash.array_index_value);
return Convert<float64>(arrayIndex);
const arrayIndex: uint32 = DecodeArrayIndexFromHashField(hash);
return Convert<float64>(Signed(arrayIndex));
}
return StringToFloat64(Flatten(s));
}
+53 -5
View File
@@ -2546,6 +2546,56 @@ TNode<Uint32T> CodeStubAssembler::LoadJSReceiverIdentityHash(
return var_hash.value();
}
#ifdef V8_ENABLE_SEEDED_ARRAY_INDEX_HASH
// Mirror C++ StringHasher::SeedArrayIndexValue.
TNode<Uint32T> CodeStubAssembler::SeedArrayIndexValue(TNode<Uint32T> value) {
// Load m1 and m2 from the hash seed byte array. In the compiled code
// these will always come from the read-only roots.
TNode<ByteArray> hash_seed = CAST(LoadRoot(RootIndex::kHashSeed));
intptr_t base_offset = OFFSET_OF_DATA_START(ByteArray) - kHeapObjectTag;
TNode<Uint32T> m1 = Load<Uint32T>(
hash_seed, IntPtrConstant(base_offset + HashSeed::kDerivedM1Offset));
TNode<Uint32T> m2 = Load<Uint32T>(
hash_seed, IntPtrConstant(base_offset + HashSeed::kDerivedM2Offset));
TNode<Word32T> x = value;
// 2-round xorshift-multiply.
x = Word32Xor(x, Word32Shr(x, Uint32Constant(Name::kArrayIndexHashShift)));
x = Word32And(Uint32Mul(Unsigned(x), m1),
Uint32Constant(Name::kArrayIndexValueMask));
x = Word32Xor(x, Word32Shr(x, Uint32Constant(Name::kArrayIndexHashShift)));
x = Word32And(Uint32Mul(Unsigned(x), m2),
Uint32Constant(Name::kArrayIndexValueMask));
x = Word32Xor(x, Word32Shr(x, Uint32Constant(Name::kArrayIndexHashShift)));
return Unsigned(x);
}
// Mirror C++ StringHasher::UnseedArrayIndexValue.
TNode<Uint32T> CodeStubAssembler::UnseedArrayIndexValue(TNode<Uint32T> value) {
// Load m1_inv and m2_inv from the hash seed byte array. In the compiled code
// these will always come from the read-only roots.
TNode<ByteArray> hash_seed = CAST(LoadRoot(RootIndex::kHashSeed));
intptr_t base_offset = OFFSET_OF_DATA_START(ByteArray) - kHeapObjectTag;
TNode<Uint32T> m1_inv = Load<Uint32T>(
hash_seed, IntPtrConstant(base_offset + HashSeed::kDerivedM1InvOffset));
TNode<Uint32T> m2_inv = Load<Uint32T>(
hash_seed, IntPtrConstant(base_offset + HashSeed::kDerivedM2InvOffset));
TNode<Word32T> x = value;
// 2-round xorshift-multiply (inverse).
// Xorshift is an involution when kShift is at least half of the value width.
x = Word32Xor(x, Word32Shr(x, Uint32Constant(Name::kArrayIndexHashShift)));
x = Word32And(Uint32Mul(Unsigned(x), m2_inv),
Uint32Constant(Name::kArrayIndexValueMask));
x = Word32Xor(x, Word32Shr(x, Uint32Constant(Name::kArrayIndexHashShift)));
x = Word32And(Uint32Mul(Unsigned(x), m1_inv),
Uint32Constant(Name::kArrayIndexValueMask));
x = Word32Xor(x, Word32Shr(x, Uint32Constant(Name::kArrayIndexHashShift)));
return Unsigned(x);
}
#endif // V8_ENABLE_SEEDED_ARRAY_INDEX_HASH
TNode<Uint32T> CodeStubAssembler::LoadNameHashAssumeComputed(TNode<Name> name) {
TNode<Uint32T> hash_field = LoadNameRawHash(name);
CSA_DCHECK(this, IsClearWord32(hash_field, Name::kHashNotComputedMask));
@@ -8983,8 +9033,7 @@ TNode<Number> CodeStubAssembler::StringToNumber(TNode<String> input) {
GotoIf(IsSetWord32(raw_hash_field, Name::kDoesNotContainCachedArrayIndexMask),
&runtime);
var_result = SmiTag(Signed(
DecodeWordFromWord32<String::ArrayIndexValueBits>(raw_hash_field)));
var_result = SmiFromUint32(DecodeArrayIndexFromHashField(raw_hash_field));
Goto(&end);
BIND(&runtime);
@@ -9902,9 +9951,8 @@ void CodeStubAssembler::TryToName(TNode<Object> key, Label* if_keyisindex,
BIND(&if_has_cached_index);
{
TNode<IntPtrT> index =
Signed(DecodeWordFromWord32<String::ArrayIndexValueBits>(
raw_hash_field));
TNode<IntPtrT> index = Signed(ChangeUint32ToWord(
DecodeArrayIndexFromHashField(raw_hash_field)));
CSA_DCHECK(this, IntPtrLessThan(index, IntPtrConstant(INT_MAX)));
*var_index = index;
Goto(if_keyisindex);
+6
View File
@@ -4614,6 +4614,12 @@ class V8_EXPORT_PRIVATE CodeStubAssembler
return WordEqual(WordAnd(flags, IntPtrConstant(mask)), IntPtrConstant(0));
}
#ifdef V8_ENABLE_SEEDED_ARRAY_INDEX_HASH
// Mirror C++ StringHasher::SeedArrayIndexValue and UnseedArrayIndexValue.
TNode<Uint32T> SeedArrayIndexValue(TNode<Uint32T> value);
TNode<Uint32T> UnseedArrayIndexValue(TNode<Uint32T> value);
#endif // V8_ENABLE_SEEDED_ARRAY_INDEX_HASH
private:
friend class CodeStubArguments;
+2 -1
View File
@@ -1094,7 +1094,8 @@ inline Handle<String> FactoryBase<Impl>::SmiToString(Tagged<Smi> number,
if (raw->raw_hash_field() == String::kEmptyHashField &&
number.value() >= 0) {
uint32_t raw_hash_field = StringHasher::MakeArrayIndexHash(
static_cast<uint32_t>(number.value()), raw->length());
static_cast<uint32_t>(number.value()), raw->length(),
HashSeed(read_only_roots()));
raw->set_raw_hash_field(raw_hash_field);
}
}
+2 -1
View File
@@ -3949,7 +3949,8 @@ Handle<String> Factory::SizeToString(size_t value, bool check_cache) {
if (value <= JSArray::kMaxArrayIndex &&
raw->raw_hash_field() == String::kEmptyHashField) {
uint32_t raw_hash_field = StringHasher::MakeArrayIndexHash(
static_cast<uint32_t>(value), raw->length());
static_cast<uint32_t>(value), raw->length(),
HashSeed(read_only_roots()));
raw->set_raw_hash_field(raw_hash_field);
}
}
+7
View File
@@ -26,6 +26,13 @@ inline HashSeed HashSeed::Default() { return HashSeed(kDefaultData); }
inline uint64_t HashSeed::seed() const { return data_->seed; }
inline const uint64_t* HashSeed::secret() const { return data_->secrets; }
#ifdef V8_ENABLE_SEEDED_ARRAY_INDEX_HASH
inline uint32_t HashSeed::m1() const { return data_->m1; }
inline uint32_t HashSeed::m1_inv() const { return data_->m1_inv; }
inline uint32_t HashSeed::m2() const { return data_->m2; }
inline uint32_t HashSeed::m2_inv() const { return data_->m2_inv; }
#endif // V8_ENABLE_SEEDED_ARRAY_INDEX_HASH
} // namespace internal
} // namespace v8
+59 -4
View File
@@ -17,16 +17,66 @@ namespace internal {
namespace {
static constexpr HashSeed::Data kDefaultSeed = {
0,
{RAPIDHASH_DEFAULT_SECRET[0], RAPIDHASH_DEFAULT_SECRET[1],
RAPIDHASH_DEFAULT_SECRET[2]}};
#ifdef V8_ENABLE_SEEDED_ARRAY_INDEX_HASH
// Calculate the modular inverse using Newton's method.
constexpr uint32_t modular_inverse(uint32_t m) {
uint32_t x = (3 * m) ^ 2; // 5 correct bits
x = x * (2 - m * x); // 10 correct bits
x = x * (2 - m * x); // 20 correct bits
x = x * (2 - m * x); // 40 correct bits
return x;
}
constexpr uint32_t truncate_for_derived_secrets(uint64_t s) {
return static_cast<uint32_t>(s) & Name::kArrayIndexValueMask;
}
// Derive a multiplier from a rapidhash secret and ensure it's odd.
constexpr uint32_t derive_multiplier(uint64_t secret) {
return truncate_for_derived_secrets(secret) | 1;
}
// Compute the modular inverse of the derived multiplier.
constexpr uint32_t derive_multiplier_inverse(uint64_t secret) {
return truncate_for_derived_secrets(
modular_inverse(derive_multiplier(secret)));
}
constexpr bool is_modular_inverse(uint32_t m, uint32_t m_inv) {
return ((m * m_inv) & Name::kArrayIndexValueMask) == 1;
}
constexpr void DeriveSecretsForArrayIndexHash(HashSeed::Data* data) {
data->m1 = derive_multiplier(data->secrets[0]);
data->m1_inv = derive_multiplier_inverse(data->secrets[0]);
data->m2 = derive_multiplier(data->secrets[1]);
data->m2_inv = derive_multiplier_inverse(data->secrets[1]);
}
#endif // V8_ENABLE_SEEDED_ARRAY_INDEX_HASH
static constexpr HashSeed::Data kDefaultSeed = [] {
HashSeed::Data d{};
d.seed = 0;
d.secrets[0] = RAPIDHASH_DEFAULT_SECRET[0];
d.secrets[1] = RAPIDHASH_DEFAULT_SECRET[1];
d.secrets[2] = RAPIDHASH_DEFAULT_SECRET[2];
#ifdef V8_ENABLE_SEEDED_ARRAY_INDEX_HASH
DeriveSecretsForArrayIndexHash(&d);
#endif // V8_ENABLE_SEEDED_ARRAY_INDEX_HASH
return d;
}();
} // anonymous namespace
static_assert(HashSeed::kSecretsCount == arraysize(RAPIDHASH_DEFAULT_SECRET));
const HashSeed::Data* const HashSeed::kDefaultData = &kDefaultSeed;
#ifdef V8_ENABLE_SEEDED_ARRAY_INDEX_HASH
// Compile-time verification that m * m_inv === 1 for the derived secrets.
static_assert(is_modular_inverse(kDefaultSeed.m1, kDefaultSeed.m1_inv));
static_assert(is_modular_inverse(kDefaultSeed.m2, kDefaultSeed.m2_inv));
#endif // V8_ENABLE_SEEDED_ARRAY_INDEX_HASH
// static
void HashSeed::InitializeRoots(Isolate* isolate) {
DCHECK(!isolate->heap()->deserialization_complete());
@@ -48,6 +98,11 @@ void HashSeed::InitializeRoots(Isolate* isolate) {
#else
data->seed = seed;
rapidhash_make_secret(seed, data->secrets);
#ifdef V8_ENABLE_SEEDED_ARRAY_INDEX_HASH
DeriveSecretsForArrayIndexHash(data);
DCHECK(is_modular_inverse(data->m1, data->m1_inv));
DCHECK(is_modular_inverse(data->m2, data->m2_inv));
#endif // V8_ENABLE_SEEDED_ARRAY_INDEX_HASH
#endif // V8_USE_DEFAULT_HASHER_SECRET
}
+23 -1
View File
@@ -46,10 +46,32 @@ class V8_EXPORT_PRIVATE HashSeed {
// RAPIDHASH_DEFAULT_SECRET. Otherwise they are derived from the seed
// using rapidhash_make_secret().
uint64_t secrets[kSecretsCount];
#ifdef V8_ENABLE_SEEDED_ARRAY_INDEX_HASH
// Additional precomputed secrets for seeding the array index value hashes.
uint32_t m1; // lower kArrayIndexValueBits bits of secret[0], must be odd
uint32_t m1_inv; // modular inverse of m1 mod 2^kArrayIndexValueBits
uint32_t m2; // lower kArrayIndexValueBits bits of secret[1], must be odd
uint32_t m2_inv; // modular inverse of m2 mod 2^kArrayIndexValueBits
#endif // V8_ENABLE_SEEDED_ARRAY_INDEX_HASH
};
static constexpr int kTotalSize = sizeof(Data);
#ifdef V8_ENABLE_SEEDED_ARRAY_INDEX_HASH
// Byte offsets from the data start, for CSA that loads fields at raw
// offsets from the ByteArray data start.
static constexpr int kDerivedM1Offset = offsetof(Data, m1);
static constexpr int kDerivedM1InvOffset = offsetof(Data, m1_inv);
static constexpr int kDerivedM2Offset = offsetof(Data, m2);
static constexpr int kDerivedM2InvOffset = offsetof(Data, m2_inv);
inline uint32_t m1() const;
inline uint32_t m1_inv() const;
inline uint32_t m2() const;
inline uint32_t m2_inv() const;
#endif // V8_ENABLE_SEEDED_ARRAY_INDEX_HASH
// Generates a hash seed (from --hash-seed or the RNG) and writes it
// together with derived secrets into the isolate's hash_seed in
// its read-only roots.
@@ -59,7 +81,7 @@ class V8_EXPORT_PRIVATE HashSeed {
// Pointer into the Data overlaying the ByteArray data (either
// points to read-only roots or to kDefaultData).
const Data* data_;
HashSeed(const Data* data) : data_(data) {}
explicit HashSeed(const Data* data) : data_(data) {}
// Points to the static constexpr default seed.
static const Data* const kDefaultData;
+13 -1
View File
@@ -161,7 +161,19 @@ V8_OBJECT class Name : public PrimitiveHeapObject {
// For strings which are array indexes the hash value has the string length
// mixed into the hash, mainly to avoid a hash value of zero which would be
// the case for the string '0'. 24 bits are used for the array index value.
static const int kArrayIndexValueBits = 24;
static constexpr int kArrayIndexValueBits = 24;
// Mask for extracting the lower kArrayIndexValueBits of a value.
static constexpr uint32_t kArrayIndexValueMask =
(1u << kArrayIndexValueBits) - 1;
#ifdef V8_ENABLE_SEEDED_ARRAY_INDEX_HASH
// Half-width shift used by the seeded xorshift-multiply mixing.
static constexpr int kArrayIndexHashShift = kArrayIndexValueBits / 2;
// The shift must be at least the half width for the xorshift to be an
// involution.
static_assert(kArrayIndexHashShift * 2 >= kArrayIndexValueBits,
"kArrayIndexHashShift must be at least half of "
"kArrayIndexValueBits");
#endif // V8_ENABLE_SEEDED_ARRAY_INDEX_HASH
static const int kArrayIndexLengthBits =
kBitsPerInt - kArrayIndexValueBits - HashFieldTypeBits::kSize;
+41 -2
View File
@@ -56,6 +56,11 @@ macro ContainsCachedArrayIndex(hash: uint32): bool {
return (hash & kDoesNotContainCachedArrayIndexMask) == 0;
}
@if(V8_ENABLE_SEEDED_ARRAY_INDEX_HASH)
extern macro SeedArrayIndexValue(uint32): uint32;
@if(V8_ENABLE_SEEDED_ARRAY_INDEX_HASH)
extern macro UnseedArrayIndexValue(uint32): uint32;
const kArrayIndexValueBitsShift: uint32 = kNofHashBitFields;
const kArrayIndexLengthBitsShift: uint32 =
kNofHashBitFields + kArrayIndexValueBits;
@@ -73,8 +78,10 @@ macro IsIntegerIndex(hash: NameHash): bool {
return hash.hash_field_type == HashFieldType::kIntegerIndex;
}
macro MakeArrayIndexHash(value: uint32, length: uint32): NameHash {
// This is in sync with StringHasher::MakeArrayIndexHash.
// This is in sync with the private StringHasher::MakeArrayIndexHash without
// seeding. Do not call directly, use the @export MakeArrayIndexHash wrapper
// below.
macro MakeArrayIndexHashRaw(value: uint32, length: uint32): NameHash {
dcheck(length <= kMaxArrayIndexSize);
const one: uint32 = 1;
dcheck(TenToThe(kMaxCachedArrayIndexLength) < (one << kArrayIndexValueBits));
@@ -88,3 +95,35 @@ macro MakeArrayIndexHash(value: uint32, length: uint32): NameHash {
dcheck(IsIntegerIndex(hash));
return hash;
}
// This is in sync with the private StringHasher::DecodeArrayIndexFromHashField
// without seeding. Do not call directly, use the @export
// DecodeArrayIndexFromHashField wrapper below.
macro DecodeArrayIndexFromHashFieldRaw(rawHashField: uint32): uint32 {
const hash: NameHash = %RawDownCast<NameHash>(rawHashField);
dcheck(ContainsCachedArrayIndex(rawHashField) || IsIntegerIndex(hash));
return hash.array_index_value;
}
// Mirror C++ public StringHasher::MakeArrayIndexHash.
@export
macro MakeArrayIndexHash(value: uint32, length: uint32): NameHash {
@if(V8_ENABLE_SEEDED_ARRAY_INDEX_HASH) {
return MakeArrayIndexHashRaw(SeedArrayIndexValue(value), length);
}
@ifnot(V8_ENABLE_SEEDED_ARRAY_INDEX_HASH) {
return MakeArrayIndexHashRaw(value, length);
}
}
// Mirror C++ public StringHasher::DecodeArrayIndexFromHashField.
@export
macro DecodeArrayIndexFromHashField(rawHashField: uint32): uint32 {
const value: uint32 = DecodeArrayIndexFromHashFieldRaw(rawHashField);
@if(V8_ENABLE_SEEDED_ARRAY_INDEX_HASH) {
return UnseedArrayIndexValue(value);
}
@ifnot(V8_ENABLE_SEEDED_ARRAY_INDEX_HASH) {
return value;
}
}
+4 -2
View File
@@ -1596,7 +1596,8 @@ bool String::AsArrayIndex(uint32_t* index) {
DisallowGarbageCollection no_gc;
uint32_t field = raw_hash_field();
if (ContainsCachedArrayIndex(field)) {
*index = ArrayIndexValueBits::decode(field);
*index = StringHasher::DecodeArrayIndexFromHashField(
field, HashSeed(EarlyGetReadOnlyRoots()));
return true;
}
if (IsHashFieldComputed(field) && !IsIntegerIndex(field)) {
@@ -1608,7 +1609,8 @@ bool String::AsArrayIndex(uint32_t* index) {
bool String::AsIntegerIndex(size_t* index) {
uint32_t field = raw_hash_field();
if (ContainsCachedArrayIndex(field)) {
*index = ArrayIndexValueBits::decode(field);
*index = StringHasher::DecodeArrayIndexFromHashField(
field, HashSeed(EarlyGetReadOnlyRoots()));
return true;
}
if (IsHashFieldComputed(field) && !IsIntegerIndex(field)) {
+2 -1
View File
@@ -598,7 +598,8 @@ Address StringTable::Data::TryStringToIndexOrLookupExisting(
// String could be an array index.
if (Name::ContainsCachedArrayIndex(raw_hash_field)) {
return Smi::FromInt(String::ArrayIndexValueBits::decode(raw_hash_field))
return Smi::FromInt(StringHasher::DecodeArrayIndexFromHashField(
raw_hash_field, seed))
.ptr();
}
+4 -2
View File
@@ -1884,7 +1884,8 @@ bool String::SlowAsArrayIndex(uint32_t* index) {
if (length <= kMaxCachedArrayIndexLength) {
uint32_t field = EnsureRawHash(); // Force computation of hash code.
if (!IsIntegerIndex(field)) return false;
*index = ArrayIndexValueBits::decode(field);
*index = StringHasher::DecodeArrayIndexFromHashField(
field, HashSeed(EarlyGetReadOnlyRoots()));
return true;
}
if (length == 0 || length > kMaxArrayIndexSize) return false;
@@ -1898,7 +1899,8 @@ bool String::SlowAsIntegerIndex(size_t* index) {
if (length <= kMaxCachedArrayIndexLength) {
uint32_t field = EnsureRawHash(); // Force computation of hash code.
if (!IsIntegerIndex(field)) return false;
*index = ArrayIndexValueBits::decode(field);
*index = StringHasher::DecodeArrayIndexFromHashField(
field, HashSeed(EarlyGetReadOnlyRoots()));
return true;
}
if (length == 0 || length > kMaxIntegerIndexSize) return false;
+61 -2
View File
@@ -10,6 +10,7 @@
// Comment inserted to prevent header reordering.
#include <type_traits>
#include "src/common/globals.h"
#include "src/objects/name-inl.h"
#include "src/objects/string-inl.h"
#include "src/strings/char-predicates-inl.h"
@@ -67,6 +68,64 @@ uint32_t StringHasher::MakeArrayIndexHash(uint32_t value, uint32_t length) {
return value;
}
uint32_t StringHasher::DecodeArrayIndexFromHashField(uint32_t raw_hash_field) {
DCHECK(String::ContainsCachedArrayIndex(raw_hash_field) ||
String::IsIntegerIndex(raw_hash_field));
return String::ArrayIndexValueBits::decode(raw_hash_field);
}
#ifdef V8_ENABLE_SEEDED_ARRAY_INDEX_HASH
uint32_t StringHasher::SeedArrayIndexValue(uint32_t value,
const HashSeed seed) {
uint32_t m1 = seed.m1();
uint32_t m2 = seed.m2();
constexpr uint32_t kShift = Name::kArrayIndexHashShift;
constexpr uint32_t kMask = Name::kArrayIndexValueMask;
// 2-round xorshift-multiply.
uint32_t x = value;
x ^= x >> kShift;
x = (x * m1) & kMask;
x ^= x >> kShift;
x = (x * m2) & kMask;
x ^= x >> kShift;
return x;
}
uint32_t StringHasher::UnseedArrayIndexValue(uint32_t value,
const HashSeed seed) {
uint32_t m1_inv = seed.m1_inv();
uint32_t m2_inv = seed.m2_inv();
uint32_t x = value;
constexpr uint32_t kShift = Name::kArrayIndexHashShift;
constexpr uint32_t kMask = Name::kArrayIndexValueMask;
// 2-round xorshift-multiply.
// Xorshift is an involution when kShift is at least half of the value width.
x ^= x >> kShift;
x = (x * m2_inv) & kMask;
x ^= x >> kShift;
x = (x * m1_inv) & kMask;
x ^= x >> kShift;
return x;
}
#endif // V8_ENABLE_SEEDED_ARRAY_INDEX_HASH
uint32_t StringHasher::MakeArrayIndexHash(
uint32_t value, uint32_t length, [[maybe_unused]] const HashSeed seed) {
#ifdef V8_ENABLE_SEEDED_ARRAY_INDEX_HASH
value = SeedArrayIndexValue(value, seed);
#endif
return MakeArrayIndexHash(value, length);
}
uint32_t StringHasher::DecodeArrayIndexFromHashField(
uint32_t raw_hash_field, [[maybe_unused]] const HashSeed seed) {
uint32_t value = DecodeArrayIndexFromHashField(raw_hash_field);
#ifdef V8_ENABLE_SEEDED_ARRAY_INDEX_HASH
value = UnseedArrayIndexValue(value, seed);
#endif
return value;
}
template <typename char_t>
uint32_t StringHasher::HashSequentialString(const char_t* chars_raw,
uint32_t length,
@@ -106,7 +165,7 @@ uint32_t StringHasher::HashSequentialString(const char_t* chars_raw,
// done.
if (!needs_overflow_check) {
DCHECK_EQ(i, length);
return MakeArrayIndexHash(index, length);
return MakeArrayIndexHash(index, length, seed);
}
// Otherwise, the last character needs to be checked for both being
// digit, and the result being in bounds of the maximum array index.
@@ -118,7 +177,7 @@ uint32_t StringHasher::HashSequentialString(const char_t* chars_raw,
goto non_index_hash;
}
if (TryAddArrayIndexChar(&index, c)) {
return MakeArrayIndexHash(index, length);
return MakeArrayIndexHash(index, length, seed);
}
// If the range check fails, this falls through into the integer index
// check.
+48 -3
View File
@@ -40,10 +40,23 @@ class V8_EXPORT_PRIVATE StringHasher final {
uint32_t length,
const HashSeed seed);
// Calculated hash value for a string consisting of 1 to
// Calculate the hash value for a string consisting of 1 to
// String::kMaxArrayIndexSize digits with no leading zeros (except "0").
// value is represented decimal value.
static V8_INLINE uint32_t MakeArrayIndexHash(uint32_t value, uint32_t length);
//
// The entire hash field consists of (from least significant bit to most):
// - HashFieldType::kIntegerIndex
// - kArrayIndexValueBits::kSize bits containing the hash value
// - The length of the decimal string
//
// When V8_ENABLE_SEEDED_ARRAY_INDEX_HASH is enabled, the numeric value
// is scrambled using secrets derived from the hash seed. When it's disabled
// the public overloads ignore the seed, whose retrieval should be optimized
// away in common configurations.
static V8_INLINE uint32_t MakeArrayIndexHash(uint32_t value, uint32_t length,
const HashSeed seed);
// Decode array index value from raw hash field and reverse seeding, if any.
static V8_INLINE uint32_t
DecodeArrayIndexFromHashField(uint32_t raw_hash_field, const HashSeed seed);
// No string is allowed to have a hash of zero. That value is reserved
// for internal properties. If the hash calculation yields zero then we
@@ -51,6 +64,38 @@ class V8_EXPORT_PRIVATE StringHasher final {
static const int kZeroHash = 27;
static V8_INLINE uint32_t GetTrivialHash(uint32_t length);
private:
// Raw encode/decode without seeding. Use the public overloads above.
static V8_INLINE uint32_t MakeArrayIndexHash(uint32_t value, uint32_t length);
static V8_INLINE uint32_t
DecodeArrayIndexFromHashField(uint32_t raw_hash_field);
#ifdef V8_ENABLE_SEEDED_ARRAY_INDEX_HASH
// When V8_ENABLE_SEEDED_ARRAY_INDEX_HASH is enabled, the numeric value
// will be scrambled with 2 rounds of xorshift-multiply.
//
// x ^= x >> kShift; x = (x * m1) & kMask; // round 1
// x ^= x >> kShift; x = (x * m2) & kMask; // round 2
// x ^= x >> kShift; // finalize
//
// To decode, apply the same steps with the modular inverses of m1 and m2 in
// reverse order.
//
// x ^= x >> kShift; x = (x * m2_inv) & kMask; // round 1
// x ^= x >> kShift; x = (x * m1_inv) & kMask; // round 2
// x ^= x >> kShift; // finalize
//
// where kShift = kArrayIndexValueBits / 2, kMask = kArrayIndexValueMask,
// m1, m2 (both odd) are derived from the Isolate's rapidhash secrets.
// m1_inv, m2_inv (modular inverses) are precomputed so that
// UnseedArrayIndexValue can quickly recover the original value.
static V8_INLINE uint32_t SeedArrayIndexValue(uint32_t value,
const HashSeed seed);
// Decode array index value from seeded raw hash field.
static V8_INLINE uint32_t UnseedArrayIndexValue(uint32_t value,
const HashSeed seed);
#endif // V8_ENABLE_SEEDED_ARRAY_INDEX_HASH
};
// Useful for std containers that require something ()'able.
+5
View File
@@ -90,6 +90,11 @@ class BuildFlags : public base::ContextualClass<BuildFlags> {
build_flags_["V8_ENABLE_DRUMBRAKE"] = true;
#else
build_flags_["V8_ENABLE_DRUMBRAKE"] = false;
#endif
#ifdef V8_ENABLE_SEEDED_ARRAY_INDEX_HASH
build_flags_["V8_ENABLE_SEEDED_ARRAY_INDEX_HASH"] = true;
#else
build_flags_["V8_ENABLE_SEEDED_ARRAY_INDEX_HASH"] = false;
#endif
}
static bool GetFlag(const std::string& name, const char* production) {
+48 -19
View File
@@ -1854,38 +1854,67 @@ TEST(HashArrayIndexStrings) {
v8::HandleScope scope(CcTest::isolate());
i::Isolate* isolate = CcTest::i_isolate();
CHECK_EQ(Name::HashBits::decode(
StringHasher::MakeArrayIndexHash(0 /* value */, 1 /* length */)),
i::HashSeed seed(isolate);
CHECK_EQ(Name::HashBits::decode(StringHasher::MakeArrayIndexHash(
0 /* value */, 1 /* length */, seed)),
isolate->factory()->zero_string()->hash());
CHECK_EQ(Name::HashBits::decode(
StringHasher::MakeArrayIndexHash(1 /* value */, 1 /* length */)),
CHECK_EQ(Name::HashBits::decode(StringHasher::MakeArrayIndexHash(
1 /* value */, 1 /* length */, seed)),
isolate->factory()->one_string()->hash());
CHECK_EQ(0u, StringHasher::DecodeArrayIndexFromHashField(
isolate->factory()->zero_string()->raw_hash_field(), seed));
CHECK_EQ(1u, StringHasher::DecodeArrayIndexFromHashField(
isolate->factory()->one_string()->raw_hash_field(), seed));
IndexData tests[] = {
{"", false, 0, false, 0},
{"123no", false, 0, false, 0},
{"12345", true, 12345, true, 12345},
{"12345678", true, 12345678, true, 12345678},
{"4294967294", true, 4294967294u, true, 4294967294u},
{"", false, 0, false, 0},
{"123no", false, 0, false, 0},
{"12345", true, 12345, true, 12345},
{"12345678", true, 12345678, true, 12345678},
{"1000000", true, 1000000, true, 1000000},
{"9999999", true, 9999999, true, 9999999},
{"10000000", true, 10000000, true, 10000000},
{"16777215", true, 16777215, true, 16777215}, // max cached index
{"99999999", true, 99999999, true, 99999999},
{"4294967294", true, 4294967294u, true, 4294967294u},
#if V8_TARGET_ARCH_32_BIT
{"4294967295", false, 0, false, 0}, // Valid length but not index.
{"4294967296", false, 0, false, 0},
{"9007199254740991", false, 0, false, 0},
{"4294967295", false, 0, false, 0}, // Valid length but not index.
{"4294967296", false, 0, false, 0},
{"9007199254740991", false, 0, false, 0},
#else
{"4294967295", false, 0, true, 4294967295u},
{"4294967296", false, 0, true, 4294967296ull},
{"9007199254740991", false, 0, true, 9007199254740991ull},
{"4294967295", false, 0, true, 4294967295u},
{"4294967296", false, 0, true, 4294967296ull},
{"9007199254740991", false, 0, true, 9007199254740991ull},
#endif
{"9007199254740992", false, 0, false, 0},
{"18446744073709551615", false, 0, false, 0},
{"18446744073709551616", false, 0, false, 0}
};
{"9007199254740992", false, 0, false, 0},
{"18446744073709551615", false, 0, false, 0},
{"18446744073709551616", false, 0, false, 0}};
for (int i = 0, n = arraysize(tests); i < n; i++) {
TestString(isolate, tests[i]);
}
}
TEST(ArrayIndexHashRoundTrip) {
CcTest::InitializeVM();
LocalContext context;
v8::HandleScope scope(CcTest::isolate());
i::Isolate* isolate = CcTest::i_isolate();
i::HashSeed seed(isolate);
constexpr uint32_t max_value = (1u << Name::kArrayIndexValueBits) - 1;
for (uint32_t value = 0; value <= max_value; value++) {
uint32_t length =
value == 0 ? 1 : static_cast<uint32_t>(std::log10(value)) + 1;
uint32_t raw_hash_field =
StringHasher::MakeArrayIndexHash(value, length, seed);
uint32_t decoded =
StringHasher::DecodeArrayIndexFromHashField(raw_hash_field, seed);
CHECK_EQ(value, decoded);
}
}
TEST(StringEquals) {
v8::Isolate* isolate = CcTest::isolate();
v8::HandleScope scope(isolate);