source: webkit/trunk/JavaScriptCore/kjs/JSArray.cpp@ 37048

Last change on this file since 37048 was 36779, checked in by [email protected], 17 years ago

JavaScriptCore:

2008-09-22 Sam Weinig <[email protected]>

Reviewed by Darin Adler.

Patch for https://bugs.webkit.org/show_bug.cgi?id=20982
Speed up the apply method of functions by special-casing array and 'arguments' objects

1% speedup on v8-raytrace.

Test: fast/js/function-apply.html

  • kjs/Arguments.cpp: (JSC::Arguments::fillArgList):
  • kjs/Arguments.h:
  • kjs/FunctionPrototype.cpp: (JSC::functionProtoFuncApply):
  • kjs/JSArray.cpp: (JSC::JSArray::fillArgList):
  • kjs/JSArray.h:

LayoutTests:

2008-09-22 Sam Weinig <[email protected]>

Reviewed by Darin Adler.

Test for https://bugs.webkit.org/show_bug.cgi?id=20982

  • fast/js/function-apply-expected.txt: Added.
  • fast/js/function-apply.html: Added.
  • fast/js/resources/function-apply.js: Added.
  • Property svn:eol-style set to native
File size: 33.9 KB
Line 
1/*
2 * Copyright (C) 1999-2000 Harri Porten ([email protected])
3 * Copyright (C) 2003, 2007, 2008 Apple Inc. All rights reserved.
4 * Copyright (C) 2003 Peter Kelly ([email protected])
5 * Copyright (C) 2006 Alexey Proskuryakov ([email protected])
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 *
21 */
22
23#include "config.h"
24#include "JSArray.h"
25
26#include "ArrayPrototype.h"
27#include "PropertyNameArray.h"
28#include <wtf/AVLTree.h>
29#include <wtf/Assertions.h>
30#include <operations.h>
31
32#define CHECK_ARRAY_CONSISTENCY 0
33
34using namespace std;
35
36namespace JSC {
37
38ASSERT_CLASS_FITS_IN_CELL(JSArray);
39
40// Overview of JSArray
41//
42// Properties of JSArray objects may be stored in one of three locations:
43// * The regular JSObject property map.
44// * A storage vector.
45// * A sparse map of array entries.
46//
47// Properties with non-numeric identifiers, with identifiers that are not representable
48// as an unsigned integer, or where the value is greater than MAX_ARRAY_INDEX
49// (specifically, this is only one property - the value 0xFFFFFFFFU as an unsigned 32-bit
50// integer) are not considered array indices and will be stored in the JSObject property map.
51//
52// All properties with a numeric identifer, representable as an unsigned integer i,
53// where (i <= MAX_ARRAY_INDEX), are an array index and will be stored in either the
54// storage vector or the sparse map. An array index i will be handled in the following
55// fashion:
56//
57// * Where (i < MIN_SPARSE_ARRAY_INDEX) the value will be stored in the storage vector.
58// * Where (MIN_SPARSE_ARRAY_INDEX <= i <= MAX_STORAGE_VECTOR_INDEX) the value will either
59// be stored in the storage vector or in the sparse array, depending on the density of
60// data that would be stored in the vector (a vector being used where at least
61// (1 / minDensityMultiplier) of the entries would be populated).
62// * Where (MAX_STORAGE_VECTOR_INDEX < i <= MAX_ARRAY_INDEX) the value will always be stored
63// in the sparse array.
64
65// The definition of MAX_STORAGE_VECTOR_LENGTH is dependant on the definition storageSize
66// function below - the MAX_STORAGE_VECTOR_LENGTH limit is defined such that the storage
67// size calculation cannot overflow. (sizeof(ArrayStorage) - sizeof(JSValue*)) +
68// (vectorLength * sizeof(JSValue*)) must be <= 0xFFFFFFFFU (which is maximum value of size_t).
69#define MAX_STORAGE_VECTOR_LENGTH static_cast<unsigned>((0xFFFFFFFFU - (sizeof(ArrayStorage) - sizeof(JSValue*))) / sizeof(JSValue*))
70
71// These values have to be macros to be used in max() and min() without introducing
72// a PIC branch in Mach-O binaries, see <rdar://problem/5971391>.
73#define MIN_SPARSE_ARRAY_INDEX 10000U
74#define MAX_STORAGE_VECTOR_INDEX (MAX_STORAGE_VECTOR_LENGTH - 1)
75// 0xFFFFFFFF is a bit weird -- is not an array index even though it's an integer.
76#define MAX_ARRAY_INDEX 0xFFFFFFFEU
77
78// Our policy for when to use a vector and when to use a sparse map.
79// For all array indices under MIN_SPARSE_ARRAY_INDEX, we always use a vector.
80// When indices greater than MIN_SPARSE_ARRAY_INDEX are involved, we use a vector
81// as long as it is 1/8 full. If more sparse than that, we use a map.
82static const unsigned minDensityMultiplier = 8;
83
84const ClassInfo JSArray::info = {"Array", 0, 0, 0};
85
86static inline size_t storageSize(unsigned vectorLength)
87{
88 ASSERT(vectorLength <= MAX_STORAGE_VECTOR_LENGTH);
89
90 // MAX_STORAGE_VECTOR_LENGTH is defined such that provided (vectorLength <= MAX_STORAGE_VECTOR_LENGTH)
91 // - as asserted above - the following calculation cannot overflow.
92 size_t size = (sizeof(ArrayStorage) - sizeof(JSValue*)) + (vectorLength * sizeof(JSValue*));
93 // Assertion to detect integer overflow in previous calculation (should not be possible, provided that
94 // MAX_STORAGE_VECTOR_LENGTH is correctly defined).
95 ASSERT(((size - (sizeof(ArrayStorage) - sizeof(JSValue*))) / sizeof(JSValue*) == vectorLength) && (size >= (sizeof(ArrayStorage) - sizeof(JSValue*))));
96
97 return size;
98}
99
100static inline unsigned increasedVectorLength(unsigned newLength)
101{
102 ASSERT(newLength <= MAX_STORAGE_VECTOR_LENGTH);
103
104 // Mathematically equivalent to:
105 // increasedLength = (newLength * 3 + 1) / 2;
106 // or:
107 // increasedLength = (unsigned)ceil(newLength * 1.5));
108 // This form is not prone to internal overflow.
109 unsigned increasedLength = newLength + (newLength >> 1) + (newLength & 1);
110 ASSERT(increasedLength >= newLength);
111
112 return min(increasedLength, MAX_STORAGE_VECTOR_LENGTH);
113}
114
115static inline bool isDenseEnoughForVector(unsigned length, unsigned numValues)
116{
117 return length / minDensityMultiplier <= numValues;
118}
119
120#if !CHECK_ARRAY_CONSISTENCY
121
122inline void JSArray::checkConsistency(ConsistencyCheckType)
123{
124}
125
126#endif
127
128JSArray::JSArray(PassRefPtr<StructureID> structureID)
129 : JSObject(structureID)
130{
131 unsigned initialCapacity = 0;
132
133 m_storage = static_cast<ArrayStorage*>(fastZeroedMalloc(storageSize(initialCapacity)));
134 m_fastAccessCutoff = 0;
135 m_storage->m_vectorLength = initialCapacity;
136 m_storage->m_length = 0;
137
138 checkConsistency();
139}
140
141JSArray::JSArray(PassRefPtr<StructureID> structure, unsigned initialLength)
142 : JSObject(structure)
143{
144 unsigned initialCapacity = min(initialLength, MIN_SPARSE_ARRAY_INDEX);
145
146 m_storage = static_cast<ArrayStorage*>(fastZeroedMalloc(storageSize(initialCapacity)));
147 m_fastAccessCutoff = 0;
148 m_storage->m_vectorLength = initialCapacity;
149 m_storage->m_length = initialLength;
150
151 Heap::heap(this)->reportExtraMemoryCost(initialCapacity * sizeof(JSValue*));
152
153 checkConsistency();
154}
155
156JSArray::JSArray(ExecState* exec, PassRefPtr<StructureID> structure, const ArgList& list)
157 : JSObject(structure)
158{
159 unsigned length = list.size();
160
161 m_fastAccessCutoff = length;
162
163 ArrayStorage* storage = static_cast<ArrayStorage*>(fastMalloc(storageSize(length)));
164
165 storage->m_vectorLength = length;
166 storage->m_numValuesInVector = length;
167 storage->m_sparseValueMap = 0;
168 storage->m_length = length;
169
170 size_t i = 0;
171 ArgList::const_iterator end = list.end();
172 for (ArgList::const_iterator it = list.begin(); it != end; ++it, ++i)
173 storage->m_vector[i] = (*it).jsValue(exec);
174
175 m_storage = storage;
176
177 // When the array is created non-empty, its cells are filled, so it's really no worse than
178 // a property map. Therefore don't report extra memory cost.
179
180 checkConsistency();
181}
182
183JSArray::~JSArray()
184{
185 checkConsistency(DestructorConsistencyCheck);
186
187 delete m_storage->m_sparseValueMap;
188 fastFree(m_storage);
189}
190
191bool JSArray::getOwnPropertySlot(ExecState* exec, unsigned i, PropertySlot& slot)
192{
193 ArrayStorage* storage = m_storage;
194
195 if (i >= storage->m_length) {
196 if (i > MAX_ARRAY_INDEX)
197 return getOwnPropertySlot(exec, Identifier::from(exec, i), slot);
198 return false;
199 }
200
201 if (i < storage->m_vectorLength) {
202 JSValue*& valueSlot = storage->m_vector[i];
203 if (valueSlot) {
204 slot.setValueSlot(&valueSlot);
205 return true;
206 }
207 } else if (SparseArrayValueMap* map = storage->m_sparseValueMap) {
208 if (i >= MIN_SPARSE_ARRAY_INDEX) {
209 SparseArrayValueMap::iterator it = map->find(i);
210 if (it != map->end()) {
211 slot.setValueSlot(&it->second);
212 return true;
213 }
214 }
215 }
216
217 return false;
218}
219
220bool JSArray::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
221{
222 if (propertyName == exec->propertyNames().length) {
223 slot.setValue(jsNumber(exec, length()));
224 return true;
225 }
226
227 bool isArrayIndex;
228 unsigned i = propertyName.toArrayIndex(&isArrayIndex);
229 if (isArrayIndex)
230 return JSArray::getOwnPropertySlot(exec, i, slot);
231
232 return JSObject::getOwnPropertySlot(exec, propertyName, slot);
233}
234
235// ECMA 15.4.5.1
236void JSArray::put(ExecState* exec, const Identifier& propertyName, JSValue* value, PutPropertySlot& slot)
237{
238 bool isArrayIndex;
239 unsigned i = propertyName.toArrayIndex(&isArrayIndex);
240 if (isArrayIndex) {
241 put(exec, i, value);
242 return;
243 }
244
245 if (propertyName == exec->propertyNames().length) {
246 unsigned newLength = value->toUInt32(exec);
247 if (value->toNumber(exec) != static_cast<double>(newLength)) {
248 throwError(exec, RangeError, "Invalid array length.");
249 return;
250 }
251 setLength(newLength);
252 return;
253 }
254
255 JSObject::put(exec, propertyName, value, slot);
256}
257
258void JSArray::put(ExecState* exec, unsigned i, JSValue* value)
259{
260 checkConsistency();
261
262 unsigned length = m_storage->m_length;
263 if (i >= length && i <= MAX_ARRAY_INDEX) {
264 length = i + 1;
265 m_storage->m_length = length;
266 }
267
268 if (i < m_storage->m_vectorLength) {
269 JSValue*& valueSlot = m_storage->m_vector[i];
270 if (valueSlot) {
271 valueSlot = value;
272 checkConsistency();
273 return;
274 }
275 valueSlot = value;
276 if (++m_storage->m_numValuesInVector == m_storage->m_length)
277 m_fastAccessCutoff = m_storage->m_length;
278 checkConsistency();
279 return;
280 }
281
282 putSlowCase(exec, i, value);
283}
284
285NEVER_INLINE void JSArray::putSlowCase(ExecState* exec, unsigned i, JSValue* value)
286{
287 ArrayStorage* storage = m_storage;
288 SparseArrayValueMap* map = storage->m_sparseValueMap;
289
290 if (i >= MIN_SPARSE_ARRAY_INDEX) {
291 if (i > MAX_ARRAY_INDEX) {
292 PutPropertySlot slot;
293 put(exec, Identifier::from(exec, i), value, slot);
294 return;
295 }
296
297 // We miss some cases where we could compact the storage, such as a large array that is being filled from the end
298 // (which will only be compacted as we reach indices that are less than cutoff) - but this makes the check much faster.
299 if ((i > MAX_STORAGE_VECTOR_INDEX) || !isDenseEnoughForVector(i + 1, storage->m_numValuesInVector + 1)) {
300 if (!map) {
301 map = new SparseArrayValueMap;
302 storage->m_sparseValueMap = map;
303 }
304 map->set(i, value);
305 return;
306 }
307 }
308
309 // We have decided that we'll put the new item into the vector.
310 // Fast case is when there is no sparse map, so we can increase the vector size without moving values from it.
311 if (!map || map->isEmpty()) {
312 if (increaseVectorLength(i + 1)) {
313 storage = m_storage;
314 storage->m_vector[i] = value;
315 if (++storage->m_numValuesInVector == storage->m_length)
316 m_fastAccessCutoff = storage->m_length;
317 checkConsistency();
318 } else
319 throwOutOfMemoryError(exec);
320 return;
321 }
322
323 // Decide how many values it would be best to move from the map.
324 unsigned newNumValuesInVector = storage->m_numValuesInVector + 1;
325 unsigned newVectorLength = increasedVectorLength(i + 1);
326 for (unsigned j = max(storage->m_vectorLength, MIN_SPARSE_ARRAY_INDEX); j < newVectorLength; ++j)
327 newNumValuesInVector += map->contains(j);
328 if (i >= MIN_SPARSE_ARRAY_INDEX)
329 newNumValuesInVector -= map->contains(i);
330 if (isDenseEnoughForVector(newVectorLength, newNumValuesInVector)) {
331 unsigned proposedNewNumValuesInVector = newNumValuesInVector;
332 // If newVectorLength is already the maximum - MAX_STORAGE_VECTOR_LENGTH - then do not attempt to grow any further.
333 while (newVectorLength < MAX_STORAGE_VECTOR_LENGTH) {
334 unsigned proposedNewVectorLength = increasedVectorLength(newVectorLength + 1);
335 for (unsigned j = max(newVectorLength, MIN_SPARSE_ARRAY_INDEX); j < proposedNewVectorLength; ++j)
336 proposedNewNumValuesInVector += map->contains(j);
337 if (!isDenseEnoughForVector(proposedNewVectorLength, proposedNewNumValuesInVector))
338 break;
339 newVectorLength = proposedNewVectorLength;
340 newNumValuesInVector = proposedNewNumValuesInVector;
341 }
342 }
343
344 storage = static_cast<ArrayStorage*>(tryFastRealloc(storage, storageSize(newVectorLength)));
345 if (!storage) {
346 throwOutOfMemoryError(exec);
347 return;
348 }
349
350 unsigned vectorLength = storage->m_vectorLength;
351 if (newNumValuesInVector == storage->m_numValuesInVector + 1) {
352 for (unsigned j = vectorLength; j < newVectorLength; ++j)
353 storage->m_vector[j] = 0;
354 if (i > MIN_SPARSE_ARRAY_INDEX)
355 map->remove(i);
356 } else {
357 for (unsigned j = vectorLength; j < max(vectorLength, MIN_SPARSE_ARRAY_INDEX); ++j)
358 storage->m_vector[j] = 0;
359 for (unsigned j = max(vectorLength, MIN_SPARSE_ARRAY_INDEX); j < newVectorLength; ++j)
360 storage->m_vector[j] = map->take(j);
361 }
362
363 storage->m_vector[i] = value;
364
365 storage->m_vectorLength = newVectorLength;
366 storage->m_numValuesInVector = newNumValuesInVector;
367
368 m_storage = storage;
369
370 checkConsistency();
371}
372
373bool JSArray::deleteProperty(ExecState* exec, const Identifier& propertyName)
374{
375 bool isArrayIndex;
376 unsigned i = propertyName.toArrayIndex(&isArrayIndex);
377 if (isArrayIndex)
378 return deleteProperty(exec, i);
379
380 if (propertyName == exec->propertyNames().length)
381 return false;
382
383 return JSObject::deleteProperty(exec, propertyName);
384}
385
386bool JSArray::deleteProperty(ExecState* exec, unsigned i)
387{
388 checkConsistency();
389
390 ArrayStorage* storage = m_storage;
391
392 if (i < storage->m_vectorLength) {
393 JSValue*& valueSlot = storage->m_vector[i];
394 if (!valueSlot) {
395 checkConsistency();
396 return false;
397 }
398 valueSlot = 0;
399 --storage->m_numValuesInVector;
400 if (m_fastAccessCutoff > i)
401 m_fastAccessCutoff = i;
402 checkConsistency();
403 return true;
404 }
405
406 if (SparseArrayValueMap* map = storage->m_sparseValueMap) {
407 if (i >= MIN_SPARSE_ARRAY_INDEX) {
408 SparseArrayValueMap::iterator it = map->find(i);
409 if (it != map->end()) {
410 map->remove(it);
411 checkConsistency();
412 return true;
413 }
414 }
415 }
416
417 checkConsistency();
418
419 if (i > MAX_ARRAY_INDEX)
420 return deleteProperty(exec, Identifier::from(exec, i));
421
422 return false;
423}
424
425void JSArray::getPropertyNames(ExecState* exec, PropertyNameArray& propertyNames)
426{
427 // FIXME: Filling PropertyNameArray with an identifier for every integer
428 // is incredibly inefficient for large arrays. We need a different approach,
429 // which almost certainly means a different structure for PropertyNameArray.
430
431 ArrayStorage* storage = m_storage;
432
433 unsigned usedVectorLength = min(storage->m_length, storage->m_vectorLength);
434 for (unsigned i = 0; i < usedVectorLength; ++i) {
435 if (storage->m_vector[i])
436 propertyNames.add(Identifier::from(exec, i));
437 }
438
439 if (SparseArrayValueMap* map = storage->m_sparseValueMap) {
440 SparseArrayValueMap::iterator end = map->end();
441 for (SparseArrayValueMap::iterator it = map->begin(); it != end; ++it)
442 propertyNames.add(Identifier::from(exec, it->first));
443 }
444
445 JSObject::getPropertyNames(exec, propertyNames);
446}
447
448bool JSArray::increaseVectorLength(unsigned newLength)
449{
450 // This function leaves the array in an internally inconsistent state, because it does not move any values from sparse value map
451 // to the vector. Callers have to account for that, because they can do it more efficiently.
452
453 ArrayStorage* storage = m_storage;
454
455 unsigned vectorLength = storage->m_vectorLength;
456 ASSERT(newLength > vectorLength);
457 ASSERT(newLength <= MAX_STORAGE_VECTOR_INDEX);
458 unsigned newVectorLength = increasedVectorLength(newLength);
459
460 storage = static_cast<ArrayStorage*>(tryFastRealloc(storage, storageSize(newVectorLength)));
461 if (!storage)
462 return false;
463
464 storage->m_vectorLength = newVectorLength;
465
466 for (unsigned i = vectorLength; i < newVectorLength; ++i)
467 storage->m_vector[i] = 0;
468
469 m_storage = storage;
470 return true;
471}
472
473void JSArray::setLength(unsigned newLength)
474{
475 checkConsistency();
476
477 ArrayStorage* storage = m_storage;
478
479 unsigned length = m_storage->m_length;
480
481 if (newLength < length) {
482 if (m_fastAccessCutoff > newLength)
483 m_fastAccessCutoff = newLength;
484
485 unsigned usedVectorLength = min(length, storage->m_vectorLength);
486 for (unsigned i = newLength; i < usedVectorLength; ++i) {
487 JSValue*& valueSlot = storage->m_vector[i];
488 bool hadValue = valueSlot;
489 valueSlot = 0;
490 storage->m_numValuesInVector -= hadValue;
491 }
492
493 if (SparseArrayValueMap* map = storage->m_sparseValueMap) {
494 SparseArrayValueMap copy = *map;
495 SparseArrayValueMap::iterator end = copy.end();
496 for (SparseArrayValueMap::iterator it = copy.begin(); it != end; ++it) {
497 if (it->first >= newLength)
498 map->remove(it->first);
499 }
500 if (map->isEmpty()) {
501 delete map;
502 storage->m_sparseValueMap = 0;
503 }
504 }
505 }
506
507 m_storage->m_length = newLength;
508
509 checkConsistency();
510}
511
512JSValue* JSArray::pop()
513{
514 checkConsistency();
515
516 unsigned length = m_storage->m_length;
517 if (!length)
518 return jsUndefined();
519
520 --length;
521
522 JSValue* result;
523
524 if (m_fastAccessCutoff > length) {
525 JSValue*& valueSlot = m_storage->m_vector[length];
526 result = valueSlot;
527 ASSERT(result);
528 valueSlot = 0;
529 --m_storage->m_numValuesInVector;
530 m_fastAccessCutoff = length;
531 } else if (length < m_storage->m_vectorLength) {
532 JSValue*& valueSlot = m_storage->m_vector[length];
533 result = valueSlot;
534 valueSlot = 0;
535 if (result)
536 --m_storage->m_numValuesInVector;
537 else
538 result = jsUndefined();
539 } else {
540 result = jsUndefined();
541 if (SparseArrayValueMap* map = m_storage->m_sparseValueMap) {
542 SparseArrayValueMap::iterator it = map->find(length);
543 if (it != map->end()) {
544 result = it->second;
545 map->remove(it);
546 if (map->isEmpty()) {
547 delete map;
548 m_storage->m_sparseValueMap = 0;
549 }
550 }
551 }
552 }
553
554 m_storage->m_length = length;
555
556 checkConsistency();
557
558 return result;
559}
560
561void JSArray::push(ExecState* exec, JSValue* value)
562{
563 checkConsistency();
564
565 if (m_storage->m_length < m_storage->m_vectorLength) {
566 ASSERT(!m_storage->m_vector[m_storage->m_length]);
567 m_storage->m_vector[m_storage->m_length] = value;
568 if (++m_storage->m_numValuesInVector == ++m_storage->m_length)
569 m_fastAccessCutoff = m_storage->m_length;
570 checkConsistency();
571 return;
572 }
573
574 if (m_storage->m_length < MIN_SPARSE_ARRAY_INDEX) {
575 SparseArrayValueMap* map = m_storage->m_sparseValueMap;
576 if (!map || map->isEmpty()) {
577 if (increaseVectorLength(m_storage->m_length + 1)) {
578 m_storage->m_vector[m_storage->m_length] = value;
579 if (++m_storage->m_numValuesInVector == ++m_storage->m_length)
580 m_fastAccessCutoff = m_storage->m_length;
581 checkConsistency();
582 return;
583 }
584 checkConsistency();
585 throwOutOfMemoryError(exec);
586 return;
587 }
588 }
589
590 putSlowCase(exec, m_storage->m_length++, value);
591}
592
593void JSArray::mark()
594{
595 JSObject::mark();
596
597 ArrayStorage* storage = m_storage;
598
599 unsigned usedVectorLength = min(storage->m_length, storage->m_vectorLength);
600 for (unsigned i = 0; i < usedVectorLength; ++i) {
601 JSValue* value = storage->m_vector[i];
602 if (value && !value->marked())
603 value->mark();
604 }
605
606 if (SparseArrayValueMap* map = storage->m_sparseValueMap) {
607 SparseArrayValueMap::iterator end = map->end();
608 for (SparseArrayValueMap::iterator it = map->begin(); it != end; ++it) {
609 JSValue* value = it->second;
610 if (!value->marked())
611 value->mark();
612 }
613 }
614}
615
616typedef std::pair<JSValue*, UString> ArrayQSortPair;
617
618static int compareByStringPairForQSort(const void* a, const void* b)
619{
620 const ArrayQSortPair* va = static_cast<const ArrayQSortPair*>(a);
621 const ArrayQSortPair* vb = static_cast<const ArrayQSortPair*>(b);
622 return compare(va->second, vb->second);
623}
624
625void JSArray::sort(ExecState* exec)
626{
627 unsigned lengthNotIncludingUndefined = compactForSorting();
628 if (m_storage->m_sparseValueMap) {
629 throwOutOfMemoryError(exec);
630 return;
631 }
632
633 if (!lengthNotIncludingUndefined)
634 return;
635
636 // Converting JavaScript values to strings can be expensive, so we do it once up front and sort based on that.
637 // This is a considerable improvement over doing it twice per comparison, though it requires a large temporary
638 // buffer. Besides, this protects us from crashing if some objects have custom toString methods that return
639 // random or otherwise changing results, effectively making compare function inconsistent.
640
641 Vector<ArrayQSortPair> values(lengthNotIncludingUndefined);
642 if (!values.begin()) {
643 throwOutOfMemoryError(exec);
644 return;
645 }
646
647 for (size_t i = 0; i < lengthNotIncludingUndefined; i++) {
648 JSValue* value = m_storage->m_vector[i];
649 ASSERT(!value->isUndefined());
650 values[i].first = value;
651 }
652
653 // FIXME: While calling these toString functions, the array could be mutated.
654 // In that case, objects pointed to by values in this vector might get garbage-collected!
655
656 // FIXME: The following loop continues to call toString on subsequent values even after
657 // a toString call raises an exception.
658
659 for (size_t i = 0; i < lengthNotIncludingUndefined; i++)
660 values[i].second = values[i].first->toString(exec);
661
662 if (exec->hadException())
663 return;
664
665 // FIXME: Since we sort by string value, a fast algorithm might be to use a radix sort. That would be O(N) rather
666 // than O(N log N).
667
668#if HAVE(MERGESORT)
669 mergesort(values.begin(), values.size(), sizeof(ArrayQSortPair), compareByStringPairForQSort);
670#else
671 // FIXME: The qsort library function is likely to not be a stable sort.
672 // ECMAScript-262 does not specify a stable sort, but in practice, browsers perform a stable sort.
673 qsort(values.begin(), values.size(), sizeof(ArrayQSortPair), compareByStringPairForQSort);
674#endif
675
676 // FIXME: If the toString function changed the length of the array, this might be
677 // modifying the vector incorrectly.
678
679 for (size_t i = 0; i < lengthNotIncludingUndefined; i++)
680 m_storage->m_vector[i] = values[i].first;
681
682 checkConsistency(SortConsistencyCheck);
683}
684
685struct AVLTreeNodeForArrayCompare {
686 JSValue* value;
687
688 // Child pointers. The high bit of gt is robbed and used as the
689 // balance factor sign. The high bit of lt is robbed and used as
690 // the magnitude of the balance factor.
691 int32_t gt;
692 int32_t lt;
693};
694
695struct AVLTreeAbstractorForArrayCompare {
696 typedef int32_t handle; // Handle is an index into m_nodes vector.
697 typedef JSValue* key;
698 typedef int32_t size;
699
700 Vector<AVLTreeNodeForArrayCompare> m_nodes;
701 ExecState* m_exec;
702 JSValue* m_compareFunction;
703 CallType m_compareCallType;
704 const CallData* m_compareCallData;
705 JSValue* m_globalThisValue;
706
707 handle get_less(handle h) { return m_nodes[h].lt & 0x7FFFFFFF; }
708 void set_less(handle h, handle lh) { m_nodes[h].lt &= 0x80000000; m_nodes[h].lt |= lh; }
709 handle get_greater(handle h) { return m_nodes[h].gt & 0x7FFFFFFF; }
710 void set_greater(handle h, handle gh) { m_nodes[h].gt &= 0x80000000; m_nodes[h].gt |= gh; }
711
712 int get_balance_factor(handle h)
713 {
714 if (m_nodes[h].gt & 0x80000000)
715 return -1;
716 return static_cast<unsigned>(m_nodes[h].lt) >> 31;
717 }
718
719 void set_balance_factor(handle h, int bf)
720 {
721 if (bf == 0) {
722 m_nodes[h].lt &= 0x7FFFFFFF;
723 m_nodes[h].gt &= 0x7FFFFFFF;
724 } else {
725 m_nodes[h].lt |= 0x80000000;
726 if (bf < 0)
727 m_nodes[h].gt |= 0x80000000;
728 else
729 m_nodes[h].gt &= 0x7FFFFFFF;
730 }
731 }
732
733 int compare_key_key(key va, key vb)
734 {
735 ASSERT(!va->isUndefined());
736 ASSERT(!vb->isUndefined());
737
738 if (m_exec->hadException())
739 return 1;
740
741 ArgList arguments;
742 arguments.append(va);
743 arguments.append(vb);
744 double compareResult = call(m_exec, m_compareFunction, m_compareCallType, *m_compareCallData, m_globalThisValue, arguments)->toNumber(m_exec);
745 return (compareResult < 0) ? -1 : 1; // Not passing equality through, because we need to store all values, even if equivalent.
746 }
747
748 int compare_key_node(key k, handle h) { return compare_key_key(k, m_nodes[h].value); }
749 int compare_node_node(handle h1, handle h2) { return compare_key_key(m_nodes[h1].value, m_nodes[h2].value); }
750
751 static handle null() { return 0x7FFFFFFF; }
752};
753
754void JSArray::sort(ExecState* exec, JSValue* compareFunction, CallType callType, const CallData& callData)
755{
756 checkConsistency();
757
758 // FIXME: This ignores exceptions raised in the compare function or in toNumber.
759
760 // The maximum tree depth is compiled in - but the caller is clearly up to no good
761 // if a larger array is passed.
762 ASSERT(m_storage->m_length <= static_cast<unsigned>(std::numeric_limits<int>::max()));
763 if (m_storage->m_length > static_cast<unsigned>(std::numeric_limits<int>::max()))
764 return;
765
766 if (!m_storage->m_length)
767 return;
768
769 unsigned usedVectorLength = min(m_storage->m_length, m_storage->m_vectorLength);
770
771 AVLTree<AVLTreeAbstractorForArrayCompare, 44> tree; // Depth 44 is enough for 2^31 items
772 tree.abstractor().m_exec = exec;
773 tree.abstractor().m_compareFunction = compareFunction;
774 tree.abstractor().m_compareCallType = callType;
775 tree.abstractor().m_compareCallData = &callData;
776 tree.abstractor().m_globalThisValue = exec->globalThisValue();
777 tree.abstractor().m_nodes.resize(usedVectorLength + (m_storage->m_sparseValueMap ? m_storage->m_sparseValueMap->size() : 0));
778
779 if (!tree.abstractor().m_nodes.begin()) {
780 throwOutOfMemoryError(exec);
781 return;
782 }
783
784 // FIXME: If the compare function modifies the array, the vector, map, etc. could be modified
785 // right out from under us while we're building the tree here.
786
787 unsigned numDefined = 0;
788 unsigned numUndefined = 0;
789
790 // Iterate over the array, ignoring missing values, counting undefined ones, and inserting all other ones into the tree.
791 for (; numDefined < usedVectorLength; ++numDefined) {
792 JSValue* v = m_storage->m_vector[numDefined];
793 if (!v || v->isUndefined())
794 break;
795 tree.abstractor().m_nodes[numDefined].value = v;
796 tree.insert(numDefined);
797 }
798 for (unsigned i = numDefined; i < usedVectorLength; ++i) {
799 if (JSValue* v = m_storage->m_vector[i]) {
800 if (v->isUndefined())
801 ++numUndefined;
802 else {
803 tree.abstractor().m_nodes[numDefined].value = v;
804 tree.insert(numDefined);
805 ++numDefined;
806 }
807 }
808 }
809
810 unsigned newUsedVectorLength = numDefined + numUndefined;
811
812 if (SparseArrayValueMap* map = m_storage->m_sparseValueMap) {
813 newUsedVectorLength += map->size();
814 if (newUsedVectorLength > m_storage->m_vectorLength) {
815 // Check that it is possible to allocate an array large enough to hold all the entries.
816 if ((newUsedVectorLength > MAX_STORAGE_VECTOR_LENGTH) || !increaseVectorLength(newUsedVectorLength)) {
817 throwOutOfMemoryError(exec);
818 return;
819 }
820 }
821
822 SparseArrayValueMap::iterator end = map->end();
823 for (SparseArrayValueMap::iterator it = map->begin(); it != end; ++it) {
824 tree.abstractor().m_nodes[numDefined].value = it->second;
825 tree.insert(numDefined);
826 ++numDefined;
827 }
828
829 delete map;
830 m_storage->m_sparseValueMap = 0;
831 }
832
833 ASSERT(tree.abstractor().m_nodes.size() >= numDefined);
834
835 // FIXME: If the compare function changed the length of the array, the following might be
836 // modifying the vector incorrectly.
837
838 // Copy the values back into m_storage.
839 AVLTree<AVLTreeAbstractorForArrayCompare, 44>::Iterator iter;
840 iter.start_iter_least(tree);
841 for (unsigned i = 0; i < numDefined; ++i) {
842 m_storage->m_vector[i] = tree.abstractor().m_nodes[*iter].value;
843 ++iter;
844 }
845
846 // Put undefined values back in.
847 for (unsigned i = numDefined; i < newUsedVectorLength; ++i)
848 m_storage->m_vector[i] = jsUndefined();
849
850 // Ensure that unused values in the vector are zeroed out.
851 for (unsigned i = newUsedVectorLength; i < usedVectorLength; ++i)
852 m_storage->m_vector[i] = 0;
853
854 m_fastAccessCutoff = newUsedVectorLength;
855 m_storage->m_numValuesInVector = newUsedVectorLength;
856
857 checkConsistency(SortConsistencyCheck);
858}
859
860void JSArray::fillArgList(ExecState* exec, ArgList& args)
861{
862 unsigned fastAccessLength = min(m_storage->m_length, m_fastAccessCutoff);
863 unsigned i = 0;
864 for (; i < fastAccessLength; ++i)
865 args.append(getIndex(i));
866 for (; i < m_storage->m_length; ++i)
867 args.append(get(exec, i));
868}
869
870unsigned JSArray::compactForSorting()
871{
872 checkConsistency();
873
874 ArrayStorage* storage = m_storage;
875
876 unsigned usedVectorLength = min(m_storage->m_length, storage->m_vectorLength);
877
878 unsigned numDefined = 0;
879 unsigned numUndefined = 0;
880
881 for (; numDefined < usedVectorLength; ++numDefined) {
882 JSValue* v = storage->m_vector[numDefined];
883 if (!v || v->isUndefined())
884 break;
885 }
886 for (unsigned i = numDefined; i < usedVectorLength; ++i) {
887 if (JSValue* v = storage->m_vector[i]) {
888 if (v->isUndefined())
889 ++numUndefined;
890 else
891 storage->m_vector[numDefined++] = v;
892 }
893 }
894
895 unsigned newUsedVectorLength = numDefined + numUndefined;
896
897 if (SparseArrayValueMap* map = storage->m_sparseValueMap) {
898 newUsedVectorLength += map->size();
899 if (newUsedVectorLength > storage->m_vectorLength) {
900 // Check that it is possible to allocate an array large enough to hold all the entries - if not,
901 // exception is thrown by caller.
902 if ((newUsedVectorLength > MAX_STORAGE_VECTOR_LENGTH) || !increaseVectorLength(newUsedVectorLength))
903 return 0;
904 storage = m_storage;
905 }
906
907 SparseArrayValueMap::iterator end = map->end();
908 for (SparseArrayValueMap::iterator it = map->begin(); it != end; ++it)
909 storage->m_vector[numDefined++] = it->second;
910
911 delete map;
912 storage->m_sparseValueMap = 0;
913 }
914
915 for (unsigned i = numDefined; i < newUsedVectorLength; ++i)
916 storage->m_vector[i] = jsUndefined();
917 for (unsigned i = newUsedVectorLength; i < usedVectorLength; ++i)
918 storage->m_vector[i] = 0;
919
920 m_fastAccessCutoff = newUsedVectorLength;
921 storage->m_numValuesInVector = newUsedVectorLength;
922
923 checkConsistency(SortConsistencyCheck);
924
925 return numDefined;
926}
927
928void* JSArray::lazyCreationData()
929{
930 return m_storage->lazyCreationData;
931}
932
933void JSArray::setLazyCreationData(void* d)
934{
935 m_storage->lazyCreationData = d;
936}
937
938#if CHECK_ARRAY_CONSISTENCY
939
940void JSArray::checkConsistency(ConsistencyCheckType type)
941{
942 ASSERT(m_storage);
943 if (type == SortConsistencyCheck)
944 ASSERT(!m_storage->m_sparseValueMap);
945
946 ASSERT(m_fastAccessCutoff <= m_storage->m_length);
947 ASSERT(m_fastAccessCutoff <= m_storage->m_numValuesInVector);
948
949 unsigned numValuesInVector = 0;
950 for (unsigned i = 0; i < m_storage->m_vectorLength; ++i) {
951 if (JSValue* value = m_storage->m_vector[i]) {
952 ASSERT(i < m_storage->m_length);
953 if (type != DestructorConsistencyCheck)
954 value->type(); // Likely to crash if the object was deallocated.
955 ++numValuesInVector;
956 } else {
957 ASSERT(i >= m_fastAccessCutoff);
958 if (type == SortConsistencyCheck)
959 ASSERT(i >= m_storage->m_numValuesInVector);
960 }
961 }
962 ASSERT(numValuesInVector == m_storage->m_numValuesInVector);
963
964 if (m_storage->m_sparseValueMap) {
965 SparseArrayValueMap::iterator end = m_storage->m_sparseValueMap->end();
966 for (SparseArrayValueMap::iterator it = m_storage->m_sparseValueMap->begin(); it != end; ++it) {
967 unsigned index = it->first;
968 ASSERT(index < m_storage->m_length);
969 ASSERT(index >= m_storage->m_vectorLength);
970 ASSERT(index <= MAX_ARRAY_INDEX);
971 ASSERT(it->second);
972 if (type != DestructorConsistencyCheck)
973 it->second->type(); // Likely to crash if the object was deallocated.
974 }
975 }
976}
977
978#endif
979
980JSArray* constructEmptyArray(ExecState* exec)
981{
982 return new (exec) JSArray(exec->lexicalGlobalObject()->arrayStructure());
983}
984
985JSArray* constructEmptyArray(ExecState* exec, unsigned initialLength)
986{
987 return new (exec) JSArray(exec->lexicalGlobalObject()->arrayStructure(), initialLength);
988}
989
990JSArray* constructArray(ExecState* exec, JSValue* singleItemValue)
991{
992 ArgList values;
993 values.append(singleItemValue);
994 return new (exec) JSArray(exec, exec->lexicalGlobalObject()->arrayStructure(), values);
995}
996
997JSArray* constructArray(ExecState* exec, const ArgList& values)
998{
999 return new (exec) JSArray(exec, exec->lexicalGlobalObject()->arrayStructure(), values);
1000}
1001
1002} // namespace JSC
Note: See TracBrowser for help on using the repository browser.