2 * Copyright (C) 1999-2000 Harri Porten (porten@kde.org)
3 * Copyright (C) 2003, 2007, 2008, 2009 Apple Inc. All rights reserved.
4 * Copyright (C) 2003 Peter Kelly (pmk@post.com)
5 * Copyright (C) 2006 Alexey Proskuryakov (ap@nypop.com)
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.
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.
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
26 #include "ArrayPrototype.h"
27 #include "CachedCall.h"
29 #include "Executable.h"
30 #include "PropertyNameArray.h"
31 #include <wtf/AVLTree.h>
32 #include <wtf/Assertions.h>
33 #include <wtf/OwnPtr.h>
34 #include <Operations.h>
41 ASSERT_CLASS_FITS_IN_CELL(JSArray);
43 // Overview of JSArray
45 // Properties of JSArray objects may be stored in one of three locations:
46 // * The regular JSObject property map.
47 // * A storage vector.
48 // * A sparse map of array entries.
50 // Properties with non-numeric identifiers, with identifiers that are not representable
51 // as an unsigned integer, or where the value is greater than MAX_ARRAY_INDEX
52 // (specifically, this is only one property - the value 0xFFFFFFFFU as an unsigned 32-bit
53 // integer) are not considered array indices and will be stored in the JSObject property map.
55 // All properties with a numeric identifer, representable as an unsigned integer i,
56 // where (i <= MAX_ARRAY_INDEX), are an array index and will be stored in either the
57 // storage vector or the sparse map. An array index i will be handled in the following
60 // * Where (i < MIN_SPARSE_ARRAY_INDEX) the value will be stored in the storage vector.
61 // * Where (MIN_SPARSE_ARRAY_INDEX <= i <= MAX_STORAGE_VECTOR_INDEX) the value will either
62 // be stored in the storage vector or in the sparse array, depending on the density of
63 // data that would be stored in the vector (a vector being used where at least
64 // (1 / minDensityMultiplier) of the entries would be populated).
65 // * Where (MAX_STORAGE_VECTOR_INDEX < i <= MAX_ARRAY_INDEX) the value will always be stored
66 // in the sparse array.
68 // The definition of MAX_STORAGE_VECTOR_LENGTH is dependant on the definition storageSize
69 // function below - the MAX_STORAGE_VECTOR_LENGTH limit is defined such that the storage
70 // size calculation cannot overflow. (sizeof(ArrayStorage) - sizeof(JSValue)) +
71 // (vectorLength * sizeof(JSValue)) must be <= 0xFFFFFFFFU (which is maximum value of size_t).
72 #define MAX_STORAGE_VECTOR_LENGTH static_cast<unsigned>((0xFFFFFFFFU - (sizeof(ArrayStorage) - sizeof(JSValue))) / sizeof(JSValue))
74 // These values have to be macros to be used in max() and min() without introducing
75 // a PIC branch in Mach-O binaries, see <rdar://problem/5971391>.
76 #define MIN_SPARSE_ARRAY_INDEX 10000U
77 #define MAX_STORAGE_VECTOR_INDEX (MAX_STORAGE_VECTOR_LENGTH - 1)
78 // 0xFFFFFFFF is a bit weird -- is not an array index even though it's an integer.
79 #define MAX_ARRAY_INDEX 0xFFFFFFFEU
81 // The value BASE_VECTOR_LEN is the maximum number of vector elements we'll allocate
82 // for an array that was created with a sepcified length (e.g. a = new Array(123))
83 #define BASE_VECTOR_LEN 4U
85 // The upper bound to the size we'll grow a zero length array when the first element
87 #define FIRST_VECTOR_GROW 4U
89 // Our policy for when to use a vector and when to use a sparse map.
90 // For all array indices under MIN_SPARSE_ARRAY_INDEX, we always use a vector.
91 // When indices greater than MIN_SPARSE_ARRAY_INDEX are involved, we use a vector
92 // as long as it is 1/8 full. If more sparse than that, we use a map.
93 static const unsigned minDensityMultiplier = 8;
95 const ClassInfo JSArray::info = {"Array", 0, 0, 0};
97 // We keep track of the size of the last array after it was grown. We use this
98 // as a simple heuristic for as the value to grow the next array from size 0.
99 // This value is capped by the constant FIRST_VECTOR_GROW defined above.
100 static unsigned lastArraySize = 0;
102 static inline size_t storageSize(unsigned vectorLength)
104 ASSERT(vectorLength <= MAX_STORAGE_VECTOR_LENGTH);
106 // MAX_STORAGE_VECTOR_LENGTH is defined such that provided (vectorLength <= MAX_STORAGE_VECTOR_LENGTH)
107 // - as asserted above - the following calculation cannot overflow.
108 size_t size = (sizeof(ArrayStorage) - sizeof(JSValue)) + (vectorLength * sizeof(JSValue));
109 // Assertion to detect integer overflow in previous calculation (should not be possible, provided that
110 // MAX_STORAGE_VECTOR_LENGTH is correctly defined).
111 ASSERT(((size - (sizeof(ArrayStorage) - sizeof(JSValue))) / sizeof(JSValue) == vectorLength) && (size >= (sizeof(ArrayStorage) - sizeof(JSValue))));
116 static inline bool isDenseEnoughForVector(unsigned length, unsigned numValues)
118 return length / minDensityMultiplier <= numValues;
121 #if !CHECK_ARRAY_CONSISTENCY
123 inline void JSArray::checkConsistency(ConsistencyCheckType)
129 JSArray::JSArray(VPtrStealingHackType)
130 : JSObject(createStructure(jsNull()))
132 unsigned initialCapacity = 0;
134 m_storage = static_cast<ArrayStorage*>(fastZeroedMalloc(storageSize(initialCapacity)));
135 m_storage->m_allocBase = m_storage;
137 m_vectorLength = initialCapacity;
141 // It's not safe to call Heap::heap(this) in order to report extra memory
142 // cost here, because the VPtrStealingHackType JSArray is not allocated on
143 // the heap. For the same reason, it's OK not to report extra cost.
146 JSArray::JSArray(NonNullPassRefPtr<Structure> structure)
147 : JSObject(structure)
149 unsigned initialCapacity = 0;
151 m_storage = static_cast<ArrayStorage*>(fastZeroedMalloc(storageSize(initialCapacity)));
152 m_storage->m_allocBase = m_storage;
154 m_vectorLength = initialCapacity;
158 Heap::heap(this)->reportExtraMemoryCost(storageSize(0));
161 JSArray::JSArray(NonNullPassRefPtr<Structure> structure, unsigned initialLength, ArrayCreationMode creationMode)
162 : JSObject(structure)
164 unsigned initialCapacity;
165 if (creationMode == CreateCompact)
166 initialCapacity = initialLength;
168 initialCapacity = min(BASE_VECTOR_LEN, MIN_SPARSE_ARRAY_INDEX);
170 m_storage = static_cast<ArrayStorage*>(fastMalloc(storageSize(initialCapacity)));
171 m_storage->m_allocBase = m_storage;
172 m_storage->m_length = initialLength;
174 m_vectorLength = initialCapacity;
175 m_storage->m_sparseValueMap = 0;
176 m_storage->subclassData = 0;
177 m_storage->reportedMapCapacity = 0;
179 if (creationMode == CreateCompact) {
180 #if CHECK_ARRAY_CONSISTENCY
181 m_storage->m_inCompactInitialization = !!initialCapacity;
183 m_storage->m_length = 0;
184 m_storage->m_numValuesInVector = initialCapacity;
186 #if CHECK_ARRAY_CONSISTENCY
187 storage->m_inCompactInitialization = false;
189 m_storage->m_length = initialLength;
190 m_storage->m_numValuesInVector = 0;
191 JSValue* vector = m_storage->m_vector;
192 for (size_t i = 0; i < initialCapacity; ++i)
193 vector[i] = JSValue();
198 Heap::heap(this)->reportExtraMemoryCost(storageSize(initialCapacity));
201 JSArray::JSArray(NonNullPassRefPtr<Structure> structure, const ArgList& list)
202 : JSObject(structure)
204 unsigned initialCapacity = list.size();
205 unsigned initialStorage;
207 // If the ArgList is empty, allocate space for 3 entries. This value empirically
208 // works well for benchmarks.
209 if (!initialCapacity)
212 initialStorage = initialCapacity;
214 m_storage = static_cast<ArrayStorage*>(fastMalloc(storageSize(initialStorage)));
215 m_storage->m_allocBase = m_storage;
217 m_storage->m_length = initialCapacity;
218 m_vectorLength = initialStorage;
219 m_storage->m_numValuesInVector = initialCapacity;
220 m_storage->m_sparseValueMap = 0;
221 m_storage->subclassData = 0;
222 m_storage->reportedMapCapacity = 0;
223 #if CHECK_ARRAY_CONSISTENCY
224 m_storage->m_inCompactInitialization = false;
228 JSValue* vector = m_storage->m_vector;
229 ArgList::const_iterator end = list.end();
230 for (ArgList::const_iterator it = list.begin(); it != end; ++it, ++i)
232 for (; i < initialStorage; i++)
233 vector[i] = JSValue();
237 Heap::heap(this)->reportExtraMemoryCost(storageSize(initialStorage));
242 ASSERT(vptr() == JSGlobalData::jsArrayVPtr);
243 checkConsistency(DestructorConsistencyCheck);
245 delete m_storage->m_sparseValueMap;
246 fastFree(m_storage->m_allocBase);
249 bool JSArray::getOwnPropertySlot(ExecState* exec, unsigned i, PropertySlot& slot)
251 ArrayStorage* storage = m_storage;
253 if (i >= storage->m_length) {
254 if (i > MAX_ARRAY_INDEX)
255 return getOwnPropertySlot(exec, Identifier::from(exec, i), slot);
259 if (i < m_vectorLength) {
260 JSValue& valueSlot = storage->m_vector[i];
262 slot.setValueSlot(&valueSlot);
265 } else if (SparseArrayValueMap* map = storage->m_sparseValueMap) {
266 if (i >= MIN_SPARSE_ARRAY_INDEX) {
267 SparseArrayValueMap::iterator it = map->find(i);
268 if (it != map->end()) {
269 slot.setValueSlot(&it->second);
275 return JSObject::getOwnPropertySlot(exec, Identifier::from(exec, i), slot);
278 bool JSArray::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
280 if (propertyName == exec->propertyNames().length) {
281 slot.setValue(jsNumber(length()));
286 unsigned i = propertyName.toArrayIndex(isArrayIndex);
288 return JSArray::getOwnPropertySlot(exec, i, slot);
290 return JSObject::getOwnPropertySlot(exec, propertyName, slot);
293 bool JSArray::getOwnPropertyDescriptor(ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor)
295 if (propertyName == exec->propertyNames().length) {
296 descriptor.setDescriptor(jsNumber(length()), DontDelete | DontEnum);
300 ArrayStorage* storage = m_storage;
303 unsigned i = propertyName.toArrayIndex(isArrayIndex);
305 if (i >= storage->m_length)
307 if (i < m_vectorLength) {
308 JSValue& value = storage->m_vector[i];
310 descriptor.setDescriptor(value, 0);
313 } else if (SparseArrayValueMap* map = storage->m_sparseValueMap) {
314 if (i >= MIN_SPARSE_ARRAY_INDEX) {
315 SparseArrayValueMap::iterator it = map->find(i);
316 if (it != map->end()) {
317 descriptor.setDescriptor(it->second, 0);
323 return JSObject::getOwnPropertyDescriptor(exec, propertyName, descriptor);
327 void JSArray::put(ExecState* exec, const Identifier& propertyName, JSValue value, PutPropertySlot& slot)
330 unsigned i = propertyName.toArrayIndex(isArrayIndex);
336 if (propertyName == exec->propertyNames().length) {
337 unsigned newLength = value.toUInt32(exec);
338 if (value.toNumber(exec) != static_cast<double>(newLength)) {
339 throwError(exec, createRangeError(exec, "Invalid array length."));
342 setLength(newLength);
346 JSObject::put(exec, propertyName, value, slot);
349 void JSArray::put(ExecState* exec, unsigned i, JSValue value)
353 ArrayStorage* storage = m_storage;
355 unsigned length = storage->m_length;
356 if (i >= length && i <= MAX_ARRAY_INDEX) {
358 storage->m_length = length;
361 if (i < m_vectorLength) {
362 JSValue& valueSlot = storage->m_vector[i];
369 ++storage->m_numValuesInVector;
374 putSlowCase(exec, i, value);
377 NEVER_INLINE void JSArray::putSlowCase(ExecState* exec, unsigned i, JSValue value)
379 ArrayStorage* storage = m_storage;
381 SparseArrayValueMap* map = storage->m_sparseValueMap;
383 if (i >= MIN_SPARSE_ARRAY_INDEX) {
384 if (i > MAX_ARRAY_INDEX) {
385 PutPropertySlot slot;
386 put(exec, Identifier::from(exec, i), value, slot);
390 // We miss some cases where we could compact the storage, such as a large array that is being filled from the end
391 // (which will only be compacted as we reach indices that are less than MIN_SPARSE_ARRAY_INDEX) - but this makes the check much faster.
392 if ((i > MAX_STORAGE_VECTOR_INDEX) || !isDenseEnoughForVector(i + 1, storage->m_numValuesInVector + 1)) {
394 map = new SparseArrayValueMap;
395 storage->m_sparseValueMap = map;
398 pair<SparseArrayValueMap::iterator, bool> result = map->add(i, value);
399 if (!result.second) { // pre-existing entry
400 result.first->second = value;
404 size_t capacity = map->capacity();
405 if (capacity != storage->reportedMapCapacity) {
406 Heap::heap(this)->reportExtraMemoryCost((capacity - storage->reportedMapCapacity) * (sizeof(unsigned) + sizeof(JSValue)));
407 storage->reportedMapCapacity = capacity;
413 // We have decided that we'll put the new item into the vector.
414 // Fast case is when there is no sparse map, so we can increase the vector size without moving values from it.
415 if (!map || map->isEmpty()) {
416 if (increaseVectorLength(i + 1)) {
418 storage->m_vector[i] = value;
419 ++storage->m_numValuesInVector;
422 throwOutOfMemoryError(exec);
426 // Decide how many values it would be best to move from the map.
427 unsigned newNumValuesInVector = storage->m_numValuesInVector + 1;
428 unsigned newVectorLength = getNewVectorLength(i + 1);
429 for (unsigned j = max(m_vectorLength, MIN_SPARSE_ARRAY_INDEX); j < newVectorLength; ++j)
430 newNumValuesInVector += map->contains(j);
431 if (i >= MIN_SPARSE_ARRAY_INDEX)
432 newNumValuesInVector -= map->contains(i);
433 if (isDenseEnoughForVector(newVectorLength, newNumValuesInVector)) {
434 unsigned needLength = max(i + 1, storage->m_length);
435 unsigned proposedNewNumValuesInVector = newNumValuesInVector;
436 // If newVectorLength is already the maximum - MAX_STORAGE_VECTOR_LENGTH - then do not attempt to grow any further.
437 while ((newVectorLength < needLength) && (newVectorLength < MAX_STORAGE_VECTOR_LENGTH)) {
438 unsigned proposedNewVectorLength = getNewVectorLength(newVectorLength + 1);
439 for (unsigned j = max(newVectorLength, MIN_SPARSE_ARRAY_INDEX); j < proposedNewVectorLength; ++j)
440 proposedNewNumValuesInVector += map->contains(j);
441 if (!isDenseEnoughForVector(proposedNewVectorLength, proposedNewNumValuesInVector))
443 newVectorLength = proposedNewVectorLength;
444 newNumValuesInVector = proposedNewNumValuesInVector;
448 void* baseStorage = storage->m_allocBase;
450 if (!tryFastRealloc(baseStorage, storageSize(newVectorLength + m_indexBias)).getValue(baseStorage)) {
451 throwOutOfMemoryError(exec);
455 m_storage = reinterpret_cast_ptr<ArrayStorage*>(static_cast<char*>(baseStorage) + m_indexBias * sizeof(JSValue));
456 m_storage->m_allocBase = baseStorage;
459 unsigned vectorLength = m_vectorLength;
460 JSValue* vector = storage->m_vector;
462 if (newNumValuesInVector == storage->m_numValuesInVector + 1) {
463 for (unsigned j = vectorLength; j < newVectorLength; ++j)
464 vector[j] = JSValue();
465 if (i > MIN_SPARSE_ARRAY_INDEX)
468 for (unsigned j = vectorLength; j < max(vectorLength, MIN_SPARSE_ARRAY_INDEX); ++j)
469 vector[j] = JSValue();
470 for (unsigned j = max(vectorLength, MIN_SPARSE_ARRAY_INDEX); j < newVectorLength; ++j)
471 vector[j] = map->take(j);
474 ASSERT(i < newVectorLength);
476 m_vectorLength = newVectorLength;
477 storage->m_numValuesInVector = newNumValuesInVector;
479 storage->m_vector[i] = value;
483 Heap::heap(this)->reportExtraMemoryCost(storageSize(newVectorLength) - storageSize(vectorLength));
486 bool JSArray::deleteProperty(ExecState* exec, const Identifier& propertyName)
489 unsigned i = propertyName.toArrayIndex(isArrayIndex);
491 return deleteProperty(exec, i);
493 if (propertyName == exec->propertyNames().length)
496 return JSObject::deleteProperty(exec, propertyName);
499 bool JSArray::deleteProperty(ExecState* exec, unsigned i)
503 ArrayStorage* storage = m_storage;
505 if (i < m_vectorLength) {
506 JSValue& valueSlot = storage->m_vector[i];
511 valueSlot = JSValue();
512 --storage->m_numValuesInVector;
517 if (SparseArrayValueMap* map = storage->m_sparseValueMap) {
518 if (i >= MIN_SPARSE_ARRAY_INDEX) {
519 SparseArrayValueMap::iterator it = map->find(i);
520 if (it != map->end()) {
530 if (i > MAX_ARRAY_INDEX)
531 return deleteProperty(exec, Identifier::from(exec, i));
536 void JSArray::getOwnPropertyNames(ExecState* exec, PropertyNameArray& propertyNames, EnumerationMode mode)
538 // FIXME: Filling PropertyNameArray with an identifier for every integer
539 // is incredibly inefficient for large arrays. We need a different approach,
540 // which almost certainly means a different structure for PropertyNameArray.
542 ArrayStorage* storage = m_storage;
544 unsigned usedVectorLength = min(storage->m_length, m_vectorLength);
545 for (unsigned i = 0; i < usedVectorLength; ++i) {
546 if (storage->m_vector[i])
547 propertyNames.add(Identifier::from(exec, i));
550 if (SparseArrayValueMap* map = storage->m_sparseValueMap) {
551 SparseArrayValueMap::iterator end = map->end();
552 for (SparseArrayValueMap::iterator it = map->begin(); it != end; ++it)
553 propertyNames.add(Identifier::from(exec, it->first));
556 if (mode == IncludeDontEnumProperties)
557 propertyNames.add(exec->propertyNames().length);
559 JSObject::getOwnPropertyNames(exec, propertyNames, mode);
562 ALWAYS_INLINE unsigned JSArray::getNewVectorLength(unsigned desiredLength)
564 ASSERT(desiredLength <= MAX_STORAGE_VECTOR_LENGTH);
566 unsigned increasedLength;
567 unsigned maxInitLength = min(m_storage->m_length, 100000U);
569 if (desiredLength < maxInitLength)
570 increasedLength = maxInitLength;
571 else if (!m_vectorLength)
572 increasedLength = max(desiredLength, lastArraySize);
574 // Mathematically equivalent to:
575 // increasedLength = (newLength * 3 + 1) / 2;
577 // increasedLength = (unsigned)ceil(newLength * 1.5));
578 // This form is not prone to internal overflow.
579 increasedLength = desiredLength + (desiredLength >> 1) + (desiredLength & 1);
582 ASSERT(increasedLength >= desiredLength);
584 lastArraySize = min(increasedLength, FIRST_VECTOR_GROW);
586 return min(increasedLength, MAX_STORAGE_VECTOR_LENGTH);
589 bool JSArray::increaseVectorLength(unsigned newLength)
591 // This function leaves the array in an internally inconsistent state, because it does not move any values from sparse value map
592 // to the vector. Callers have to account for that, because they can do it more efficiently.
594 ArrayStorage* storage = m_storage;
596 unsigned vectorLength = m_vectorLength;
597 ASSERT(newLength > vectorLength);
598 ASSERT(newLength <= MAX_STORAGE_VECTOR_INDEX);
599 unsigned newVectorLength = getNewVectorLength(newLength);
600 void* baseStorage = storage->m_allocBase;
602 if (!tryFastRealloc(baseStorage, storageSize(newVectorLength + m_indexBias)).getValue(baseStorage))
605 storage = m_storage = reinterpret_cast_ptr<ArrayStorage*>(static_cast<char*>(baseStorage) + m_indexBias * sizeof(JSValue));
606 m_storage->m_allocBase = baseStorage;
608 JSValue* vector = storage->m_vector;
609 for (unsigned i = vectorLength; i < newVectorLength; ++i)
610 vector[i] = JSValue();
612 m_vectorLength = newVectorLength;
614 Heap::heap(this)->reportExtraMemoryCost(storageSize(newVectorLength) - storageSize(vectorLength));
619 bool JSArray::increaseVectorPrefixLength(unsigned newLength)
621 // This function leaves the array in an internally inconsistent state, because it does not move any values from sparse value map
622 // to the vector. Callers have to account for that, because they can do it more efficiently.
624 ArrayStorage* storage = m_storage;
626 unsigned vectorLength = m_vectorLength;
627 ASSERT(newLength > vectorLength);
628 ASSERT(newLength <= MAX_STORAGE_VECTOR_INDEX);
629 unsigned newVectorLength = getNewVectorLength(newLength);
631 void* newBaseStorage = fastMalloc(storageSize(newVectorLength + m_indexBias));
635 m_indexBias += newVectorLength - newLength;
637 m_storage = reinterpret_cast_ptr<ArrayStorage*>(static_cast<char*>(newBaseStorage) + m_indexBias * sizeof(JSValue));
639 memcpy(m_storage, storage, storageSize(0));
640 memcpy(&m_storage->m_vector[newLength - m_vectorLength], &storage->m_vector[0], vectorLength * sizeof(JSValue));
642 m_storage->m_allocBase = newBaseStorage;
643 m_vectorLength = newLength;
645 fastFree(storage->m_allocBase);
647 Heap::heap(this)->reportExtraMemoryCost(storageSize(newVectorLength) - storageSize(vectorLength));
653 void JSArray::setLength(unsigned newLength)
655 ArrayStorage* storage = m_storage;
657 #if CHECK_ARRAY_CONSISTENCY
658 if (!storage->m_inCompactInitialization)
661 storage->m_inCompactInitialization = false;
664 unsigned length = storage->m_length;
666 if (newLength < length) {
667 unsigned usedVectorLength = min(length, m_vectorLength);
668 for (unsigned i = newLength; i < usedVectorLength; ++i) {
669 JSValue& valueSlot = storage->m_vector[i];
670 bool hadValue = valueSlot;
671 valueSlot = JSValue();
672 storage->m_numValuesInVector -= hadValue;
675 if (SparseArrayValueMap* map = storage->m_sparseValueMap) {
676 SparseArrayValueMap copy = *map;
677 SparseArrayValueMap::iterator end = copy.end();
678 for (SparseArrayValueMap::iterator it = copy.begin(); it != end; ++it) {
679 if (it->first >= newLength)
680 map->remove(it->first);
682 if (map->isEmpty()) {
684 storage->m_sparseValueMap = 0;
689 storage->m_length = newLength;
694 JSValue JSArray::pop()
698 ArrayStorage* storage = m_storage;
700 unsigned length = storage->m_length;
702 return jsUndefined();
708 if (length < m_vectorLength) {
709 JSValue& valueSlot = storage->m_vector[length];
711 --storage->m_numValuesInVector;
713 valueSlot = JSValue();
715 result = jsUndefined();
717 result = jsUndefined();
718 if (SparseArrayValueMap* map = storage->m_sparseValueMap) {
719 SparseArrayValueMap::iterator it = map->find(length);
720 if (it != map->end()) {
723 if (map->isEmpty()) {
725 storage->m_sparseValueMap = 0;
731 storage->m_length = length;
738 void JSArray::push(ExecState* exec, JSValue value)
742 ArrayStorage* storage = m_storage;
744 if (storage->m_length < m_vectorLength) {
745 storage->m_vector[storage->m_length] = value;
746 ++storage->m_numValuesInVector;
752 if (storage->m_length < MIN_SPARSE_ARRAY_INDEX) {
753 SparseArrayValueMap* map = storage->m_sparseValueMap;
754 if (!map || map->isEmpty()) {
755 if (increaseVectorLength(storage->m_length + 1)) {
757 storage->m_vector[storage->m_length] = value;
758 ++storage->m_numValuesInVector;
764 throwOutOfMemoryError(exec);
769 putSlowCase(exec, storage->m_length++, value);
772 void JSArray::shiftCount(ExecState* exec, int count)
776 ArrayStorage* storage = m_storage;
778 unsigned oldLength = storage->m_length;
783 if (oldLength != storage->m_numValuesInVector) {
784 // If m_length and m_numValuesInVector aren't the same, we have a sparse vector
785 // which means we need to go through each entry looking for the the "empty"
786 // slots and then fill them with possible properties. See ECMA spec.
787 // 15.4.4.9 steps 11 through 13.
788 for (unsigned i = count; i < oldLength; ++i) {
789 if ((i >= m_vectorLength) || (!m_storage->m_vector[i])) {
790 PropertySlot slot(this);
791 JSValue p = prototype();
792 if ((!p.isNull()) && (asObject(p)->getPropertySlot(exec, i, slot)))
793 put(exec, i, slot.getValue(exec, i));
797 storage = m_storage; // The put() above could have grown the vector and realloc'ed storage.
799 // Need to decrement numValuesInvector based on number of real entries
800 for (unsigned i = 0; i < (unsigned)count; ++i)
801 if ((i < m_vectorLength) && (storage->m_vector[i]))
802 --storage->m_numValuesInVector;
804 storage->m_numValuesInVector -= count;
806 storage->m_length -= count;
808 if (m_vectorLength) {
809 count = min(m_vectorLength, (unsigned)count);
811 m_vectorLength -= count;
813 if (m_vectorLength) {
814 char* newBaseStorage = reinterpret_cast<char*>(storage) + count * sizeof(JSValue);
815 memmove(newBaseStorage, storage, storageSize(0));
816 m_storage = reinterpret_cast_ptr<ArrayStorage*>(newBaseStorage);
818 m_indexBias += count;
823 void JSArray::unshiftCount(ExecState* exec, int count)
825 ArrayStorage* storage = m_storage;
827 ASSERT(m_indexBias >= 0);
830 unsigned length = storage->m_length;
832 if (length != storage->m_numValuesInVector) {
833 // If m_length and m_numValuesInVector aren't the same, we have a sparse vector
834 // which means we need to go through each entry looking for the the "empty"
835 // slots and then fill them with possible properties. See ECMA spec.
836 // 15.4.4.13 steps 8 through 10.
837 for (unsigned i = 0; i < length; ++i) {
838 if ((i >= m_vectorLength) || (!m_storage->m_vector[i])) {
839 PropertySlot slot(this);
840 JSValue p = prototype();
841 if ((!p.isNull()) && (asObject(p)->getPropertySlot(exec, i, slot)))
842 put(exec, i, slot.getValue(exec, i));
847 storage = m_storage; // The put() above could have grown the vector and realloc'ed storage.
849 if (m_indexBias >= count) {
850 m_indexBias -= count;
851 char* newBaseStorage = reinterpret_cast<char*>(storage) - count * sizeof(JSValue);
852 memmove(newBaseStorage, storage, storageSize(0));
853 m_storage = reinterpret_cast_ptr<ArrayStorage*>(newBaseStorage);
854 m_vectorLength += count;
855 } else if (!increaseVectorPrefixLength(m_vectorLength + count)) {
856 throwOutOfMemoryError(exec);
860 JSValue* vector = m_storage->m_vector;
861 for (int i = 0; i < count; i++)
862 vector[i] = JSValue();
865 void JSArray::markChildren(MarkStack& markStack)
867 markChildrenDirect(markStack);
870 static int compareNumbersForQSort(const void* a, const void* b)
872 double da = static_cast<const JSValue*>(a)->uncheckedGetNumber();
873 double db = static_cast<const JSValue*>(b)->uncheckedGetNumber();
874 return (da > db) - (da < db);
877 static int compareByStringPairForQSort(const void* a, const void* b)
879 const ValueStringPair* va = static_cast<const ValueStringPair*>(a);
880 const ValueStringPair* vb = static_cast<const ValueStringPair*>(b);
881 return codePointCompare(va->second, vb->second);
884 void JSArray::sortNumeric(ExecState* exec, JSValue compareFunction, CallType callType, const CallData& callData)
886 ArrayStorage* storage = m_storage;
888 unsigned lengthNotIncludingUndefined = compactForSorting();
889 if (storage->m_sparseValueMap) {
890 throwOutOfMemoryError(exec);
894 if (!lengthNotIncludingUndefined)
897 bool allValuesAreNumbers = true;
898 size_t size = storage->m_numValuesInVector;
899 for (size_t i = 0; i < size; ++i) {
900 if (!storage->m_vector[i].isNumber()) {
901 allValuesAreNumbers = false;
906 if (!allValuesAreNumbers)
907 return sort(exec, compareFunction, callType, callData);
909 // For numeric comparison, which is fast, qsort is faster than mergesort. We
910 // also don't require mergesort's stability, since there's no user visible
911 // side-effect from swapping the order of equal primitive values.
912 qsort(storage->m_vector, size, sizeof(JSValue), compareNumbersForQSort);
914 checkConsistency(SortConsistencyCheck);
917 void JSArray::sort(ExecState* exec)
919 ArrayStorage* storage = m_storage;
921 unsigned lengthNotIncludingUndefined = compactForSorting();
922 if (storage->m_sparseValueMap) {
923 throwOutOfMemoryError(exec);
927 if (!lengthNotIncludingUndefined)
930 // Converting JavaScript values to strings can be expensive, so we do it once up front and sort based on that.
931 // This is a considerable improvement over doing it twice per comparison, though it requires a large temporary
932 // buffer. Besides, this protects us from crashing if some objects have custom toString methods that return
933 // random or otherwise changing results, effectively making compare function inconsistent.
935 Vector<ValueStringPair> values(lengthNotIncludingUndefined);
936 if (!values.begin()) {
937 throwOutOfMemoryError(exec);
941 Heap::heap(this)->pushTempSortVector(&values);
943 for (size_t i = 0; i < lengthNotIncludingUndefined; i++) {
944 JSValue value = storage->m_vector[i];
945 ASSERT(!value.isUndefined());
946 values[i].first = value;
949 // FIXME: The following loop continues to call toString on subsequent values even after
950 // a toString call raises an exception.
952 for (size_t i = 0; i < lengthNotIncludingUndefined; i++)
953 values[i].second = values[i].first.toString(exec);
955 if (exec->hadException()) {
956 Heap::heap(this)->popTempSortVector(&values);
960 // FIXME: Since we sort by string value, a fast algorithm might be to use a radix sort. That would be O(N) rather
964 mergesort(values.begin(), values.size(), sizeof(ValueStringPair), compareByStringPairForQSort);
966 // FIXME: The qsort library function is likely to not be a stable sort.
967 // ECMAScript-262 does not specify a stable sort, but in practice, browsers perform a stable sort.
968 qsort(values.begin(), values.size(), sizeof(ValueStringPair), compareByStringPairForQSort);
971 // If the toString function changed the length of the array or vector storage,
972 // increase the length to handle the orignal number of actual values.
973 if (m_vectorLength < lengthNotIncludingUndefined)
974 increaseVectorLength(lengthNotIncludingUndefined);
975 if (storage->m_length < lengthNotIncludingUndefined)
976 storage->m_length = lengthNotIncludingUndefined;
978 for (size_t i = 0; i < lengthNotIncludingUndefined; i++)
979 storage->m_vector[i] = values[i].first;
981 Heap::heap(this)->popTempSortVector(&values);
983 checkConsistency(SortConsistencyCheck);
986 struct AVLTreeNodeForArrayCompare {
989 // Child pointers. The high bit of gt is robbed and used as the
990 // balance factor sign. The high bit of lt is robbed and used as
991 // the magnitude of the balance factor.
996 struct AVLTreeAbstractorForArrayCompare {
997 typedef int32_t handle; // Handle is an index into m_nodes vector.
999 typedef int32_t size;
1001 Vector<AVLTreeNodeForArrayCompare> m_nodes;
1003 JSValue m_compareFunction;
1004 CallType m_compareCallType;
1005 const CallData* m_compareCallData;
1006 JSValue m_globalThisValue;
1007 OwnPtr<CachedCall> m_cachedCall;
1009 handle get_less(handle h) { return m_nodes[h].lt & 0x7FFFFFFF; }
1010 void set_less(handle h, handle lh) { m_nodes[h].lt &= 0x80000000; m_nodes[h].lt |= lh; }
1011 handle get_greater(handle h) { return m_nodes[h].gt & 0x7FFFFFFF; }
1012 void set_greater(handle h, handle gh) { m_nodes[h].gt &= 0x80000000; m_nodes[h].gt |= gh; }
1014 int get_balance_factor(handle h)
1016 if (m_nodes[h].gt & 0x80000000)
1018 return static_cast<unsigned>(m_nodes[h].lt) >> 31;
1021 void set_balance_factor(handle h, int bf)
1024 m_nodes[h].lt &= 0x7FFFFFFF;
1025 m_nodes[h].gt &= 0x7FFFFFFF;
1027 m_nodes[h].lt |= 0x80000000;
1029 m_nodes[h].gt |= 0x80000000;
1031 m_nodes[h].gt &= 0x7FFFFFFF;
1035 int compare_key_key(key va, key vb)
1037 ASSERT(!va.isUndefined());
1038 ASSERT(!vb.isUndefined());
1040 if (m_exec->hadException())
1043 double compareResult;
1045 m_cachedCall->setThis(m_globalThisValue);
1046 m_cachedCall->setArgument(0, va);
1047 m_cachedCall->setArgument(1, vb);
1048 compareResult = m_cachedCall->call().toNumber(m_cachedCall->newCallFrame(m_exec));
1050 MarkedArgumentBuffer arguments;
1051 arguments.append(va);
1052 arguments.append(vb);
1053 compareResult = call(m_exec, m_compareFunction, m_compareCallType, *m_compareCallData, m_globalThisValue, arguments).toNumber(m_exec);
1055 return (compareResult < 0) ? -1 : 1; // Not passing equality through, because we need to store all values, even if equivalent.
1058 int compare_key_node(key k, handle h) { return compare_key_key(k, m_nodes[h].value); }
1059 int compare_node_node(handle h1, handle h2) { return compare_key_key(m_nodes[h1].value, m_nodes[h2].value); }
1061 static handle null() { return 0x7FFFFFFF; }
1064 void JSArray::sort(ExecState* exec, JSValue compareFunction, CallType callType, const CallData& callData)
1068 ArrayStorage* storage = m_storage;
1070 // FIXME: This ignores exceptions raised in the compare function or in toNumber.
1072 // The maximum tree depth is compiled in - but the caller is clearly up to no good
1073 // if a larger array is passed.
1074 ASSERT(storage->m_length <= static_cast<unsigned>(std::numeric_limits<int>::max()));
1075 if (storage->m_length > static_cast<unsigned>(std::numeric_limits<int>::max()))
1078 unsigned usedVectorLength = min(storage->m_length, m_vectorLength);
1079 unsigned nodeCount = usedVectorLength + (storage->m_sparseValueMap ? storage->m_sparseValueMap->size() : 0);
1084 AVLTree<AVLTreeAbstractorForArrayCompare, 44> tree; // Depth 44 is enough for 2^31 items
1085 tree.abstractor().m_exec = exec;
1086 tree.abstractor().m_compareFunction = compareFunction;
1087 tree.abstractor().m_compareCallType = callType;
1088 tree.abstractor().m_compareCallData = &callData;
1089 tree.abstractor().m_globalThisValue = exec->globalThisValue();
1090 tree.abstractor().m_nodes.grow(nodeCount);
1092 if (callType == CallTypeJS)
1093 tree.abstractor().m_cachedCall = adoptPtr(new CachedCall(exec, asFunction(compareFunction), 2));
1095 if (!tree.abstractor().m_nodes.begin()) {
1096 throwOutOfMemoryError(exec);
1100 // FIXME: If the compare function modifies the array, the vector, map, etc. could be modified
1101 // right out from under us while we're building the tree here.
1103 unsigned numDefined = 0;
1104 unsigned numUndefined = 0;
1106 // Iterate over the array, ignoring missing values, counting undefined ones, and inserting all other ones into the tree.
1107 for (; numDefined < usedVectorLength; ++numDefined) {
1108 JSValue v = storage->m_vector[numDefined];
1109 if (!v || v.isUndefined())
1111 tree.abstractor().m_nodes[numDefined].value = v;
1112 tree.insert(numDefined);
1114 for (unsigned i = numDefined; i < usedVectorLength; ++i) {
1115 JSValue v = storage->m_vector[i];
1117 if (v.isUndefined())
1120 tree.abstractor().m_nodes[numDefined].value = v;
1121 tree.insert(numDefined);
1127 unsigned newUsedVectorLength = numDefined + numUndefined;
1129 if (SparseArrayValueMap* map = storage->m_sparseValueMap) {
1130 newUsedVectorLength += map->size();
1131 if (newUsedVectorLength > m_vectorLength) {
1132 // Check that it is possible to allocate an array large enough to hold all the entries.
1133 if ((newUsedVectorLength > MAX_STORAGE_VECTOR_LENGTH) || !increaseVectorLength(newUsedVectorLength)) {
1134 throwOutOfMemoryError(exec);
1139 storage = m_storage;
1141 SparseArrayValueMap::iterator end = map->end();
1142 for (SparseArrayValueMap::iterator it = map->begin(); it != end; ++it) {
1143 tree.abstractor().m_nodes[numDefined].value = it->second;
1144 tree.insert(numDefined);
1149 storage->m_sparseValueMap = 0;
1152 ASSERT(tree.abstractor().m_nodes.size() >= numDefined);
1154 // FIXME: If the compare function changed the length of the array, the following might be
1155 // modifying the vector incorrectly.
1157 // Copy the values back into m_storage.
1158 AVLTree<AVLTreeAbstractorForArrayCompare, 44>::Iterator iter;
1159 iter.start_iter_least(tree);
1160 for (unsigned i = 0; i < numDefined; ++i) {
1161 storage->m_vector[i] = tree.abstractor().m_nodes[*iter].value;
1165 // Put undefined values back in.
1166 for (unsigned i = numDefined; i < newUsedVectorLength; ++i)
1167 storage->m_vector[i] = jsUndefined();
1169 // Ensure that unused values in the vector are zeroed out.
1170 for (unsigned i = newUsedVectorLength; i < usedVectorLength; ++i)
1171 storage->m_vector[i] = JSValue();
1173 storage->m_numValuesInVector = newUsedVectorLength;
1175 checkConsistency(SortConsistencyCheck);
1178 void JSArray::fillArgList(ExecState* exec, MarkedArgumentBuffer& args)
1180 ArrayStorage* storage = m_storage;
1182 JSValue* vector = storage->m_vector;
1183 unsigned vectorEnd = min(storage->m_length, m_vectorLength);
1185 for (; i < vectorEnd; ++i) {
1186 JSValue& v = vector[i];
1192 for (; i < storage->m_length; ++i)
1193 args.append(get(exec, i));
1196 void JSArray::copyToRegisters(ExecState* exec, Register* buffer, uint32_t maxSize)
1198 ASSERT(m_storage->m_length >= maxSize);
1199 UNUSED_PARAM(maxSize);
1200 JSValue* vector = m_storage->m_vector;
1201 unsigned vectorEnd = min(maxSize, m_vectorLength);
1203 for (; i < vectorEnd; ++i) {
1204 JSValue& v = vector[i];
1210 for (; i < maxSize; ++i)
1211 buffer[i] = get(exec, i);
1214 unsigned JSArray::compactForSorting()
1218 ArrayStorage* storage = m_storage;
1220 unsigned usedVectorLength = min(storage->m_length, m_vectorLength);
1222 unsigned numDefined = 0;
1223 unsigned numUndefined = 0;
1225 for (; numDefined < usedVectorLength; ++numDefined) {
1226 JSValue v = storage->m_vector[numDefined];
1227 if (!v || v.isUndefined())
1230 for (unsigned i = numDefined; i < usedVectorLength; ++i) {
1231 JSValue v = storage->m_vector[i];
1233 if (v.isUndefined())
1236 storage->m_vector[numDefined++] = v;
1240 unsigned newUsedVectorLength = numDefined + numUndefined;
1242 if (SparseArrayValueMap* map = storage->m_sparseValueMap) {
1243 newUsedVectorLength += map->size();
1244 if (newUsedVectorLength > m_vectorLength) {
1245 // Check that it is possible to allocate an array large enough to hold all the entries - if not,
1246 // exception is thrown by caller.
1247 if ((newUsedVectorLength > MAX_STORAGE_VECTOR_LENGTH) || !increaseVectorLength(newUsedVectorLength))
1250 storage = m_storage;
1253 SparseArrayValueMap::iterator end = map->end();
1254 for (SparseArrayValueMap::iterator it = map->begin(); it != end; ++it)
1255 storage->m_vector[numDefined++] = it->second;
1258 storage->m_sparseValueMap = 0;
1261 for (unsigned i = numDefined; i < newUsedVectorLength; ++i)
1262 storage->m_vector[i] = jsUndefined();
1263 for (unsigned i = newUsedVectorLength; i < usedVectorLength; ++i)
1264 storage->m_vector[i] = JSValue();
1266 storage->m_numValuesInVector = newUsedVectorLength;
1268 checkConsistency(SortConsistencyCheck);
1273 void* JSArray::subclassData() const
1275 return m_storage->subclassData;
1278 void JSArray::setSubclassData(void* d)
1280 m_storage->subclassData = d;
1283 #if CHECK_ARRAY_CONSISTENCY
1285 void JSArray::checkConsistency(ConsistencyCheckType type)
1287 ArrayStorage* storage = m_storage;
1290 if (type == SortConsistencyCheck)
1291 ASSERT(!storage->m_sparseValueMap);
1293 unsigned numValuesInVector = 0;
1294 for (unsigned i = 0; i < m_vectorLength; ++i) {
1295 if (JSValue value = storage->m_vector[i]) {
1296 ASSERT(i < storage->m_length);
1297 if (type != DestructorConsistencyCheck)
1298 value.isUndefined(); // Likely to crash if the object was deallocated.
1299 ++numValuesInVector;
1301 if (type == SortConsistencyCheck)
1302 ASSERT(i >= storage->m_numValuesInVector);
1305 ASSERT(numValuesInVector == storage->m_numValuesInVector);
1306 ASSERT(numValuesInVector <= storage->m_length);
1308 if (storage->m_sparseValueMap) {
1309 SparseArrayValueMap::iterator end = storage->m_sparseValueMap->end();
1310 for (SparseArrayValueMap::iterator it = storage->m_sparseValueMap->begin(); it != end; ++it) {
1311 unsigned index = it->first;
1312 ASSERT(index < storage->m_length);
1313 ASSERT(index >= storage->m_vectorLength);
1314 ASSERT(index <= MAX_ARRAY_INDEX);
1316 if (type != DestructorConsistencyCheck)
1317 it->second.isUndefined(); // Likely to crash if the object was deallocated.