Skip to content

Commit 5eb574b

Browse files
committed
[JSC] JSON.parse should build arrays without going through the generic array initialization
https://bugs.webkit.org/show_bug.cgi?id=329699 rdar://191501869 Reviewed by Sosuke Suzuki. In this patch, we optimize materializeArray in JSON parser. It now allocates the butterfly, fills the elements and the unused tail of the vector with plain stores, and only then wraps it with JSArray::createWithButterfly, instead of going through tryCreateUninitializedRestricted, ObjectInitializationScope and a barriered copy. Butterfly::clearRange fills ranges of up to eight slots with direct stores, and MarkedVector::append no longer takes its slow path for a value that is not a cell once the buffer is out of line. Tests: JSTests/stress/json-parse-array-vector-tail-no-double-shape.js JSTests/stress/json-parse-array-vector-tail.js * JSTests/stress/json-parse-array-vector-tail-no-double-shape.js: Added. * JSTests/stress/json-parse-array-vector-tail.js: Added. (shouldBe): (checkTail): (run): * Source/JavaScriptCore/runtime/ButterflyInlines.h: (JSC::Butterfly::clearRange): * Source/JavaScriptCore/runtime/JSArray.cpp: (JSC::JSArray::tryCreateUninitializedRestrictedButterfly): * Source/JavaScriptCore/runtime/JSArrayInlines.h: (JSC::JSArray::tryCreate): * Source/JavaScriptCore/runtime/LiteralParser.cpp: (JSC::reviverMode>::materializeArray): * Source/JavaScriptCore/runtime/MarkedVector.cpp: (JSC::MarkedVectorBase::slowAppend): * Source/JavaScriptCore/runtime/MarkedVector.h: (JSC::MarkedVector::append): * Source/JavaScriptCore/runtime/Structure.h: (JSC::Structure::outOfLineCapacity): Canonical link: https://commits.webkit.org/325396@main
1 parent 305e6c8 commit 5eb574b

9 files changed

Lines changed: 139 additions & 38 deletions

File tree

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
//@ runDefault("--allowDoubleShape=0")
2+
3+
load("./json-parse-array-vector-tail.js", "caller relative");
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
function shouldBe(actual, expected) {
2+
if (!Object.is(actual, expected))
3+
throw new Error("bad value: " + actual + " expected: " + expected);
4+
}
5+
6+
var allowDoubleShape = $vm.allowDoubleShape();
7+
8+
// Growing the length within the vector capacity exposes the unused slots past the parsed
9+
// elements without rewriting them, so each of them has to read back as a hole.
10+
function checkTail(array, length) {
11+
for (var extra = 1; extra <= 16; ++extra) {
12+
array.length = length + extra;
13+
for (var i = length; i < length + extra; ++i) {
14+
shouldBe(i in array, false);
15+
shouldBe(array[i], undefined);
16+
}
17+
}
18+
array.length = length;
19+
}
20+
21+
var doubleMode = allowDoubleShape ? "ArrayWithDouble" : "ArrayWithContiguous";
22+
var kinds = [
23+
{ element: i => String(i), value: i => i, mode: () => "ArrayWithInt32" },
24+
{ element: i => String(i + 0.5), value: i => i + 0.5, mode: () => doubleMode },
25+
{ element: i => String(i % 2 ? i + 0.5 : i), value: i => i % 2 ? i + 0.5 : i, mode: length => length > 1 ? doubleMode : "ArrayWithInt32" },
26+
{ element: i => '"' + i + '"', value: i => String(i), mode: () => "ArrayWithContiguous" },
27+
{ element: i => i % 2 ? "null" : String(i), value: i => i % 2 ? null : i, mode: length => length > 1 ? "ArrayWithContiguous" : "ArrayWithInt32" },
28+
];
29+
30+
var lengths = [];
31+
for (var length = 1; length <= 40; ++length)
32+
lengths.push(length);
33+
lengths.push(63, 64, 65, 127, 128, 129, 1000);
34+
35+
function run(expectedModes) {
36+
for (var iteration = 0; iteration < 20; ++iteration) {
37+
// Reused butterflies still hold earlier elements, so an uncleared slot reads back as a value
38+
// instead of as the zero that a fresh page would show.
39+
fullGC();
40+
for (var kind of kinds) {
41+
for (var length of lengths) {
42+
var source = "[" + Array.from({ length }, (_, i) => kind.element(i)).join(",") + "]";
43+
var array = JSON.parse(source);
44+
// Any other access first could let the JIT convert the array to a more general shape.
45+
if (expectedModes)
46+
shouldBe($vm.indexingMode(array), kind.mode(length));
47+
shouldBe(array.length, length);
48+
for (var i = 0; i < length; ++i)
49+
shouldBe(array[i], kind.value(i));
50+
checkTail(array, length);
51+
}
52+
}
53+
}
54+
}
55+
56+
run(!$vm.isHavingABadTime(globalThis));
57+
58+
// Once an indexed accessor on Array.prototype makes the global object have a bad time, arrays are
59+
// allocated with array storage, where the slots past the parsed elements must still be holes.
60+
Object.defineProperty(Array.prototype, "100000", { get() { return "bad"; }, configurable: true });
61+
run(false);

‎Source/JavaScriptCore/runtime/ButterflyInlines.h‎

Lines changed: 34 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -312,21 +312,43 @@ ALWAYS_INLINE void Butterfly::clearRange(IndexingType indexingType, Butterfly* b
312312
{
313313
ASSERT(end >= start);
314314

315-
if (size_t remaining = end - start) {
316-
// 32-bit, non-Darwin builds don't use `remaining`.
317-
UNUSED_VARIABLE(remaining);
318-
if (hasDouble(indexingType)) {
315+
size_t remaining = end - start;
316+
if (!remaining)
317+
return;
318+
319+
EncodedJSValue* dst = std::bit_cast<EncodedJSValue*>(butterfly->contiguous().data() + start);
320+
EncodedJSValue pattern = hasDouble(indexingType) ? std::bit_cast<EncodedJSValue>(PNaN) : 0;
321+
if (remaining == 1) {
322+
dst[0] = pattern;
323+
return;
324+
}
325+
if (remaining <= 4) {
326+
dst[0] = pattern;
327+
dst[1] = pattern;
328+
dst[remaining - 2] = pattern;
329+
dst[remaining - 1] = pattern;
330+
return;
331+
}
332+
if (remaining <= 8) {
333+
dst[0] = pattern;
334+
dst[1] = pattern;
335+
dst[2] = pattern;
336+
dst[3] = pattern;
337+
dst[remaining - 4] = pattern;
338+
dst[remaining - 3] = pattern;
339+
dst[remaining - 2] = pattern;
340+
dst[remaining - 1] = pattern;
341+
return;
342+
}
343+
if (hasDouble(indexingType)) {
319344
#if OS(DARWIN)
320-
constexpr double pattern = PNaN;
321-
memset_pattern8(static_cast<void*>(butterfly->contiguous().data() + start), &pattern, sizeof(double) * remaining);
345+
memset_pattern8(dst, &pattern, sizeof(EncodedJSValue) * remaining);
322346
#else
323-
for (unsigned i = start; i < end; ++i)
324-
butterfly->contiguousDouble().atUnsafe(i) = PNaN;
347+
for (size_t i = 0; i < remaining; ++i)
348+
dst[i] = pattern;
325349
#endif
326-
} else {
327-
memset(static_cast<void*>(butterfly->contiguous().data() + start), 0, sizeof(JSValue) * remaining);
328-
}
329-
}
350+
} else
351+
zeroSpan(unsafeMakeSpan(dst, remaining));
330352
}
331353

332354
} // namespace JSC

‎Source/JavaScriptCore/runtime/JSArray.cpp‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ Butterfly* JSArray::tryCreateUninitializedRestrictedButterfly(VM& vm, GCDeferral
116116
|| hasDouble(indexingType)
117117
|| hasContiguous(indexingType));
118118

119-
unsigned vectorLength = Butterfly::optimalContiguousVectorLength(structure, initialLength);
119+
unsigned vectorLength = Butterfly::optimalContiguousVectorLength(outOfLineStorage, initialLength);
120120
void* temp = vm.auxiliarySpace().allocate(
121121
vm,
122122
Butterfly::totalSize(0, outOfLineStorage, true, vectorLength * sizeof(EncodedJSValue)),
@@ -132,7 +132,7 @@ Butterfly* JSArray::tryCreateUninitializedRestrictedButterfly(VM& vm, GCDeferral
132132
indexingType == ArrayWithSlowPutArrayStorage
133133
|| indexingType == ArrayWithArrayStorage);
134134
static constexpr unsigned indexBias = 0;
135-
unsigned vectorLength = ArrayStorage::optimalVectorLength(indexBias, structure, initialLength);
135+
unsigned vectorLength = ArrayStorage::optimalVectorLength(indexBias, outOfLineStorage, initialLength);
136136
void* temp = vm.auxiliarySpace().allocate(
137137
vm,
138138
Butterfly::totalSize(indexBias, outOfLineStorage, true, ArrayStorage::sizeFor(vectorLength)),

‎Source/JavaScriptCore/runtime/JSArrayInlines.h‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ inline JSArray* JSArray::tryCreate(VM& vm, Structure* structure, unsigned initia
5353
if (vectorLengthHint > MAX_STORAGE_VECTOR_LENGTH) [[unlikely]]
5454
return nullptr;
5555

56-
unsigned vectorLength = Butterfly::optimalContiguousVectorLength(structure, vectorLengthHint);
56+
unsigned vectorLength = Butterfly::optimalContiguousVectorLength(outOfLineStorage, vectorLengthHint);
5757
void* temp = vm.auxiliarySpace().allocate(
5858
vm,
5959
Butterfly::totalSize(0, outOfLineStorage, true, vectorLength * sizeof(EncodedJSValue)),

‎Source/JavaScriptCore/runtime/LiteralParser.cpp‎

Lines changed: 29 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1545,32 +1545,43 @@ JSArray* LiteralParser<CharType, reviverMode>::materializeArray(VM& vm, unsigned
15451545
break;
15461546
}
15471547

1548-
{
1549-
ObjectInitializationScope initializationScope(vm);
1550-
Structure* structure = m_globalObject->arrayStructureForIndexingTypeDuringAllocation(indexingType);
1551-
if (JSArray* array = JSArray::tryCreateUninitializedRestricted(initializationScope, structure, length)) [[likely]] {
1552-
// The structure can have a different shape than requested, for example when double arrays are disabled.
1553-
IndexingType shape = array->indexingType() & IndexingShapeMask;
1554-
if (shape == DoubleShape) {
1548+
Structure* structure = m_globalObject->arrayStructureForIndexingTypeDuringAllocation(indexingType);
1549+
IndexingType actualIndexingType = structure->indexingType();
1550+
if (!hasAnyArrayStorage(actualIndexingType) && length <= MAX_STORAGE_VECTOR_LENGTH) [[likely]] {
1551+
ASSERT(!structure->outOfLineCapacity());
1552+
unsigned vectorLength = Butterfly::optimalContiguousVectorLength(static_cast<size_t>(0), length);
1553+
void* memory = vm.auxiliarySpace().allocate(
1554+
vm,
1555+
Butterfly::totalSize(0, 0, true, vectorLength * sizeof(EncodedJSValue)),
1556+
nullptr, AllocationFailureMode::ReturnNull);
1557+
if (memory) [[likely]] {
1558+
Butterfly* butterfly = Butterfly::fromBase(memory, 0, 0);
1559+
butterfly->setVectorLength(vectorLength);
1560+
butterfly->setPublicLength(length);
1561+
if (hasDouble(actualIndexingType)) {
15551562
// JSON has no NaN, so every element can be stored as a double.
1556-
double* data = array->butterfly()->contiguousDouble().data();
1563+
double* data = butterfly->contiguousDouble().data();
15571564
for (unsigned i = 0; i < length; ++i)
15581565
data[i] = values[i].asNumber();
1559-
} else if (shape == Int32Shape)
1560-
memcpy(std::bit_cast<JSValue*>(array->butterfly()->contiguous().data()), values, length * sizeof(JSValue));
1561-
else if (shape == ContiguousShape) {
1562-
gcSafeMemcpy(std::bit_cast<JSValue*>(array->butterfly()->contiguous().data()), values, length * sizeof(JSValue));
1563-
vm.writeBarrier(array);
15641566
} else {
1565-
for (unsigned i = 0; i < length; ++i)
1566-
array->initializeIndex(initializationScope, i, values[i]);
1567+
JSValue* dst = std::bit_cast<JSValue*>(butterfly->contiguous().data());
1568+
if (length == 1)
1569+
dst[0] = values[0];
1570+
else if (length <= 4) {
1571+
dst[0] = values[0];
1572+
dst[1] = values[1];
1573+
dst[length - 2] = values[length - 2];
1574+
dst[length - 1] = values[length - 1];
1575+
} else
1576+
memcpySpan(unsafeMakeSpan(dst, length), unsafeMakeSpan(values, length));
15671577
}
1568-
return array;
1578+
Butterfly::clearRange(actualIndexingType, butterfly, length, vectorLength);
1579+
return JSArray::createWithButterfly(vm, nullptr, structure, butterfly);
15691580
}
15701581
}
15711582

1572-
// Lengths beyond what a contiguous vector can hold, and allocation failures, grow an empty array
1573-
// instead so that they report out of memory rather than crashing.
1583+
// Array storage shapes take the general path, and so do lengths beyond what a contiguous vector
1584+
// can hold and allocation failures, which have to report out of memory rather than crash.
15741585
JSArray* array = constructEmptyArray(m_globalObject, nullptr);
15751586
RETURN_IF_EXCEPTION(scope, nullptr);
15761587
for (unsigned i = 0; i < length; ++i) {

‎Source/JavaScriptCore/runtime/MarkedVector.cpp‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,7 @@ auto MarkedVectorBase::expandCapacity(unsigned newCapacity) -> Status
195195
return Status::Success;
196196
}
197197

198-
auto MarkedVectorBase::slowAppend(JSValue v) -> Status
198+
NEVER_INLINE auto MarkedVectorBase::slowAppend(JSValue v) -> Status
199199
{
200200
ASSERT(m_size <= m_capacity);
201201
if (m_size == m_capacity) {

‎Source/JavaScriptCore/runtime/MarkedVector.h‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -378,11 +378,15 @@ class MarkedVector : public OverflowHandler, public MarkedVectorBase {
378378
m_size = 0;
379379
}
380380

381-
void append(T v)
381+
ALWAYS_INLINE void append(T v)
382382
{
383383
ASSERT(m_size <= m_capacity);
384-
if (m_size == m_capacity || (mallocBase() && !m_markSet)) {
385-
if (slowAppend<T>(v) == Status::Overflowed)
384+
// Only a value that refers to a cell needs this out of line storage to be marked.
385+
bool needsMarking = true;
386+
if constexpr (std::is_same_v<T, JSValue>)
387+
needsMarking = v.isCell();
388+
if (m_size == m_capacity || (!m_markSet && needsMarking && mallocBase())) [[unlikely]] {
389+
if (slowAppend<T>(v) == Status::Overflowed) [[unlikely]]
386390
this->overflowed();
387391
return;
388392
}

‎Source/JavaScriptCore/runtime/Structure.h‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -513,7 +513,7 @@ class Structure : public JSCell {
513513
// changed between the new and old structure. So, it's important to keep this simple because
514514
// it's on a fast path.
515515

516-
if (!outOfLineSize)
516+
if (!outOfLineSize) [[likely]]
517517
return 0;
518518

519519
if (outOfLineSize <= initialOutOfLineCapacity)

0 commit comments

Comments
 (0)