elements.cc 77.9 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "v8.h"

30
#include "arguments.h"
31 32
#include "objects.h"
#include "elements.h"
33
#include "utils.h"
34
#include "v8conversions.h"
35 36 37 38 39 40 41 42

// Each concrete ElementsAccessor can handle exactly one ElementsKind,
// several abstract ElementsAccessor classes are used to allow sharing
// common code.
//
// Inheritance hierarchy:
// - ElementsAccessorBase                        (abstract)
//   - FastElementsAccessor                      (abstract)
43 44 45 46 47
//     - FastSmiOrObjectElementsAccessor
//       - FastPackedSmiElementsAccessor
//       - FastHoleySmiElementsAccessor
//       - FastPackedObjectElementsAccessor
//       - FastHoleyObjectElementsAccessor
48
//     - FastDoubleElementsAccessor
49 50
//       - FastPackedDoubleElementsAccessor
//       - FastHoleyDoubleElementsAccessor
51 52 53 54 55 56 57 58 59 60 61 62 63 64
//   - ExternalElementsAccessor                  (abstract)
//     - ExternalByteElementsAccessor
//     - ExternalUnsignedByteElementsAccessor
//     - ExternalShortElementsAccessor
//     - ExternalUnsignedShortElementsAccessor
//     - ExternalIntElementsAccessor
//     - ExternalUnsignedIntElementsAccessor
//     - ExternalFloatElementsAccessor
//     - ExternalDoubleElementsAccessor
//     - PixelElementsAccessor
//   - DictionaryElementsAccessor
//   - NonStrictArgumentsElementsAccessor


65 66 67 68
namespace v8 {
namespace internal {


69 70 71
static const int kPackedSizeNotKnown = -1;


72 73 74 75 76 77
// First argument in list is the accessor class, the second argument is the
// accessor ElementsKind, and the third is the backing store class.  Use the
// fast element handler for smi-only arrays.  The implementation is currently
// identical.  Note that the order must match that of the ElementsKind enum for
// the |accessor_array[]| below to work.
#define ELEMENTS_LIST(V)                                                \
78 79 80 81 82 83 84 85 86
  V(FastPackedSmiElementsAccessor, FAST_SMI_ELEMENTS, FixedArray)       \
  V(FastHoleySmiElementsAccessor, FAST_HOLEY_SMI_ELEMENTS,              \
    FixedArray)                                                         \
  V(FastPackedObjectElementsAccessor, FAST_ELEMENTS, FixedArray)        \
  V(FastHoleyObjectElementsAccessor, FAST_HOLEY_ELEMENTS, FixedArray)   \
  V(FastPackedDoubleElementsAccessor, FAST_DOUBLE_ELEMENTS,             \
    FixedDoubleArray)                                                   \
  V(FastHoleyDoubleElementsAccessor, FAST_HOLEY_DOUBLE_ELEMENTS,        \
    FixedDoubleArray)                                                   \
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
  V(DictionaryElementsAccessor, DICTIONARY_ELEMENTS,                    \
    SeededNumberDictionary)                                             \
  V(NonStrictArgumentsElementsAccessor, NON_STRICT_ARGUMENTS_ELEMENTS,  \
    FixedArray)                                                         \
  V(ExternalByteElementsAccessor, EXTERNAL_BYTE_ELEMENTS,               \
    ExternalByteArray)                                                  \
  V(ExternalUnsignedByteElementsAccessor,                               \
    EXTERNAL_UNSIGNED_BYTE_ELEMENTS, ExternalUnsignedByteArray)         \
  V(ExternalShortElementsAccessor, EXTERNAL_SHORT_ELEMENTS,             \
    ExternalShortArray)                                                 \
  V(ExternalUnsignedShortElementsAccessor,                              \
    EXTERNAL_UNSIGNED_SHORT_ELEMENTS, ExternalUnsignedShortArray)       \
  V(ExternalIntElementsAccessor, EXTERNAL_INT_ELEMENTS,                 \
    ExternalIntArray)                                                   \
  V(ExternalUnsignedIntElementsAccessor,                                \
    EXTERNAL_UNSIGNED_INT_ELEMENTS, ExternalUnsignedIntArray)           \
  V(ExternalFloatElementsAccessor,                                      \
    EXTERNAL_FLOAT_ELEMENTS, ExternalFloatArray)                        \
  V(ExternalDoubleElementsAccessor,                                     \
    EXTERNAL_DOUBLE_ELEMENTS, ExternalDoubleArray)                      \
  V(PixelElementsAccessor, EXTERNAL_PIXEL_ELEMENTS, ExternalPixelArray)


template<ElementsKind Kind> class ElementsKindTraits {
 public:
  typedef FixedArrayBase BackingStore;
};

#define ELEMENTS_TRAITS(Class, KindParam, Store)               \
template<> class ElementsKindTraits<KindParam> {               \
117
  public:                                                      \
118 119 120 121 122 123 124
  static const ElementsKind Kind = KindParam;                  \
  typedef Store BackingStore;                                  \
};
ELEMENTS_LIST(ELEMENTS_TRAITS)
#undef ELEMENTS_TRAITS


125 126 127
ElementsAccessor** ElementsAccessor::elements_accessors_;


128
static bool HasKey(FixedArray* array, Object* key) {
129 130 131 132 133 134 135 136 137 138 139 140 141
  int len0 = array->length();
  for (int i = 0; i < len0; i++) {
    Object* element = array->get(i);
    if (element->IsSmi() && element == key) return true;
    if (element->IsString() &&
        key->IsString() && String::cast(element)->Equals(String::cast(key))) {
      return true;
    }
  }
  return false;
}


142 143 144 145 146 147 148 149
static Failure* ThrowArrayLengthRangeError(Heap* heap) {
  HandleScope scope(heap->isolate());
  return heap->isolate()->Throw(
      *heap->isolate()->factory()->NewRangeError("invalid_array_length",
          HandleVector<Object>(NULL, 0)));
}


150
static void CopyObjectToObjectElements(FixedArrayBase* from_base,
151 152
                                       ElementsKind from_kind,
                                       uint32_t from_start,
153
                                       FixedArrayBase* to_base,
154 155 156
                                       ElementsKind to_kind,
                                       uint32_t to_start,
                                       int raw_copy_size) {
157
  ASSERT(to_base->map() != HEAP->fixed_cow_array_map());
158
  AssertNoAllocation no_allocation;
159 160 161 162
  int copy_size = raw_copy_size;
  if (raw_copy_size < 0) {
    ASSERT(raw_copy_size == ElementsAccessor::kCopyToEnd ||
           raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole);
163 164
    copy_size = Min(from_base->length() - from_start,
                    to_base->length() - to_start);
165
    if (raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole) {
166
      int start = to_start + copy_size;
167
      int length = to_base->length() - start;
168
      if (length > 0) {
169 170 171
        Heap* heap = from_base->GetHeap();
        MemsetPointer(FixedArray::cast(to_base)->data_start() + start,
                      heap->the_hole_value(), length);
172 173
      }
    }
174
  }
175 176
  ASSERT((copy_size + static_cast<int>(to_start)) <= to_base->length() &&
         (copy_size + static_cast<int>(from_start)) <= from_base->length());
177
  if (copy_size == 0) return;
178 179
  FixedArray* from = FixedArray::cast(from_base);
  FixedArray* to = FixedArray::cast(to_base);
180 181
  ASSERT(IsFastSmiOrObjectElementsKind(from_kind));
  ASSERT(IsFastSmiOrObjectElementsKind(to_kind));
182 183 184 185
  Address to_address = to->address() + FixedArray::kHeaderSize;
  Address from_address = from->address() + FixedArray::kHeaderSize;
  CopyWords(reinterpret_cast<Object**>(to_address) + to_start,
            reinterpret_cast<Object**>(from_address) + from_start,
186
            copy_size);
187 188
  if (IsFastObjectElementsKind(from_kind) &&
      IsFastObjectElementsKind(to_kind)) {
189 190 191 192
    Heap* heap = from->GetHeap();
    if (!heap->InNewSpace(to)) {
      heap->RecordWrites(to->address(),
                         to->OffsetOfElementAt(to_start),
193 194
                         copy_size);
    }
195
    heap->incremental_marking()->RecordWrites(to);
196 197 198 199
  }
}


200
static void CopyDictionaryToObjectElements(FixedArrayBase* from_base,
201
                                           uint32_t from_start,
202
                                           FixedArrayBase* to_base,
203 204
                                           ElementsKind to_kind,
                                           uint32_t to_start,
205
                                           int raw_copy_size) {
206
  SeededNumberDictionary* from = SeededNumberDictionary::cast(from_base);
207
  AssertNoAllocation no_allocation;
208 209 210 211 212 213 214
  int copy_size = raw_copy_size;
  Heap* heap = from->GetHeap();
  if (raw_copy_size < 0) {
    ASSERT(raw_copy_size == ElementsAccessor::kCopyToEnd ||
           raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole);
    copy_size = from->max_number_key() + 1 - from_start;
    if (raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole) {
215
      int start = to_start + copy_size;
216
      int length = to_base->length() - start;
217 218
      if (length > 0) {
        Heap* heap = from->GetHeap();
219 220
        MemsetPointer(FixedArray::cast(to_base)->data_start() + start,
                      heap->the_hole_value(), length);
221 222 223
      }
    }
  }
224
  ASSERT(to_base != from_base);
225
  ASSERT(IsFastSmiOrObjectElementsKind(to_kind));
226
  if (copy_size == 0) return;
227
  FixedArray* to = FixedArray::cast(to_base);
228 229 230 231
  uint32_t to_length = to->length();
  if (to_start + copy_size > to_length) {
    copy_size = to_length - to_start;
  }
232 233 234 235 236 237 238 239 240 241
  for (int i = 0; i < copy_size; i++) {
    int entry = from->FindEntry(i + from_start);
    if (entry != SeededNumberDictionary::kNotFound) {
      Object* value = from->ValueAt(entry);
      ASSERT(!value->IsTheHole());
      to->set(i + to_start, value, SKIP_WRITE_BARRIER);
    } else {
      to->set_the_hole(i + to_start);
    }
  }
242
  if (IsFastObjectElementsKind(to_kind)) {
243 244 245 246
    if (!heap->InNewSpace(to)) {
      heap->RecordWrites(to->address(),
                         to->OffsetOfElementAt(to_start),
                         copy_size);
247
    }
248
    heap->incremental_marking()->RecordWrites(to);
249 250 251 252 253
  }
}


MUST_USE_RESULT static MaybeObject* CopyDoubleToObjectElements(
254
    FixedArrayBase* from_base,
255
    uint32_t from_start,
256
    FixedArrayBase* to_base,
257 258
    ElementsKind to_kind,
    uint32_t to_start,
259
    int raw_copy_size) {
260
  ASSERT(IsFastSmiOrObjectElementsKind(to_kind));
261 262 263 264
  int copy_size = raw_copy_size;
  if (raw_copy_size < 0) {
    ASSERT(raw_copy_size == ElementsAccessor::kCopyToEnd ||
           raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole);
265 266
    copy_size = Min(from_base->length() - from_start,
                    to_base->length() - to_start);
267
    if (raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole) {
268 269 270 271
      // Also initialize the area that will be copied over since HeapNumber
      // allocation below can cause an incremental marking step, requiring all
      // existing heap objects to be propertly initialized.
      int start = to_start;
272
      int length = to_base->length() - start;
273
      if (length > 0) {
274 275 276
        Heap* heap = from_base->GetHeap();
        MemsetPointer(FixedArray::cast(to_base)->data_start() + start,
                      heap->the_hole_value(), length);
277 278
      }
    }
279
  }
280 281 282 283 284
  ASSERT((copy_size + static_cast<int>(to_start)) <= to_base->length() &&
         (copy_size + static_cast<int>(from_start)) <= from_base->length());
  if (copy_size == 0) return from_base;
  FixedDoubleArray* from = FixedDoubleArray::cast(from_base);
  FixedArray* to = FixedArray::cast(to_base);
285
  for (int i = 0; i < copy_size; ++i) {
286
    if (IsFastSmiElementsKind(to_kind)) {
287 288 289
      UNIMPLEMENTED();
      return Failure::Exception();
    } else {
290
      MaybeObject* maybe_value = from->get(i + from_start);
291
      Object* value;
292 293
      ASSERT(IsFastObjectElementsKind(to_kind));
      // Because Double -> Object elements transitions allocate HeapObjects
294 295 296 297 298 299
      // iteratively, the allocate must succeed within a single GC cycle,
      // otherwise the retry after the GC will also fail. In order to ensure
      // that no GC is triggered, allocate HeapNumbers from old space if they
      // can't be taken from new space.
      if (!maybe_value->ToObject(&value)) {
        ASSERT(maybe_value->IsRetryAfterGC() || maybe_value->IsOutOfMemory());
300
        Heap* heap = from->GetHeap();
301
        MaybeObject* maybe_value_object =
302
            heap->AllocateHeapNumber(from->get_scalar(i + from_start),
303 304 305
                                     TENURED);
        if (!maybe_value_object->ToObject(&value)) return maybe_value_object;
      }
306
      to->set(i + to_start, value, UPDATE_WRITE_BARRIER);
307 308
    }
  }
309
  return to;
310 311 312
}


313
static void CopyDoubleToDoubleElements(FixedArrayBase* from_base,
314
                                       uint32_t from_start,
315
                                       FixedArrayBase* to_base,
316
                                       uint32_t to_start,
317 318 319 320 321
                                       int raw_copy_size) {
  int copy_size = raw_copy_size;
  if (raw_copy_size < 0) {
    ASSERT(raw_copy_size == ElementsAccessor::kCopyToEnd ||
           raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole);
322 323
    copy_size = Min(from_base->length() - from_start,
                    to_base->length() - to_start);
324
    if (raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole) {
325 326
      for (int i = to_start + copy_size; i < to_base->length(); ++i) {
        FixedDoubleArray::cast(to_base)->set_the_hole(i);
327 328
      }
    }
329
  }
330 331
  ASSERT((copy_size + static_cast<int>(to_start)) <= to_base->length() &&
         (copy_size + static_cast<int>(from_start)) <= from_base->length());
332
  if (copy_size == 0) return;
333 334
  FixedDoubleArray* from = FixedDoubleArray::cast(from_base);
  FixedDoubleArray* to = FixedDoubleArray::cast(to_base);
335 336 337 338
  Address to_address = to->address() + FixedDoubleArray::kHeaderSize;
  Address from_address = from->address() + FixedDoubleArray::kHeaderSize;
  to_address += kDoubleSize * to_start;
  from_address += kDoubleSize * from_start;
339
  int words_per_double = (kDoubleSize / kPointerSize);
340 341
  CopyWords(reinterpret_cast<Object**>(to_address),
            reinterpret_cast<Object**>(from_address),
342 343 344 345
            words_per_double * copy_size);
}


346
static void CopySmiToDoubleElements(FixedArrayBase* from_base,
347
                                    uint32_t from_start,
348
                                    FixedArrayBase* to_base,
349 350 351 352 353 354
                                    uint32_t to_start,
                                    int raw_copy_size) {
  int copy_size = raw_copy_size;
  if (raw_copy_size < 0) {
    ASSERT(raw_copy_size == ElementsAccessor::kCopyToEnd ||
           raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole);
355
    copy_size = from_base->length() - from_start;
356
    if (raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole) {
357 358
      for (int i = to_start + copy_size; i < to_base->length(); ++i) {
        FixedDoubleArray::cast(to_base)->set_the_hole(i);
359 360 361
      }
    }
  }
362 363
  ASSERT((copy_size + static_cast<int>(to_start)) <= to_base->length() &&
         (copy_size + static_cast<int>(from_start)) <= from_base->length());
364
  if (copy_size == 0) return;
365 366
  FixedArray* from = FixedArray::cast(from_base);
  FixedDoubleArray* to = FixedDoubleArray::cast(to_base);
367 368 369 370 371 372 373 374 375 376 377 378 379
  Object* the_hole = from->GetHeap()->the_hole_value();
  for (uint32_t from_end = from_start + static_cast<uint32_t>(copy_size);
       from_start < from_end; from_start++, to_start++) {
    Object* hole_or_smi = from->get(from_start);
    if (hole_or_smi == the_hole) {
      to->set_the_hole(to_start);
    } else {
      to->set(to_start, Smi::cast(hole_or_smi)->value());
    }
  }
}


380
static void CopyPackedSmiToDoubleElements(FixedArrayBase* from_base,
381
                                          uint32_t from_start,
382
                                          FixedArrayBase* to_base,
383 384 385 386 387 388 389 390
                                          uint32_t to_start,
                                          int packed_size,
                                          int raw_copy_size) {
  int copy_size = raw_copy_size;
  uint32_t to_end;
  if (raw_copy_size < 0) {
    ASSERT(raw_copy_size == ElementsAccessor::kCopyToEnd ||
           raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole);
391
    copy_size = packed_size - from_start;
392
    if (raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole) {
393
      to_end = to_base->length();
394
      for (uint32_t i = to_start + copy_size; i < to_end; ++i) {
395
        FixedDoubleArray::cast(to_base)->set_the_hole(i);
396
      }
397 398 399 400 401 402
    } else {
      to_end = to_start + static_cast<uint32_t>(copy_size);
    }
  } else {
    to_end = to_start + static_cast<uint32_t>(copy_size);
  }
403
  ASSERT(static_cast<int>(to_end) <= to_base->length());
404
  ASSERT(packed_size >= 0 && packed_size <= copy_size);
405 406
  ASSERT((copy_size + static_cast<int>(to_start)) <= to_base->length() &&
         (copy_size + static_cast<int>(from_start)) <= from_base->length());
407
  if (copy_size == 0) return;
408 409
  FixedArray* from = FixedArray::cast(from_base);
  FixedDoubleArray* to = FixedDoubleArray::cast(to_base);
410 411 412 413 414 415 416 417 418
  for (uint32_t from_end = from_start + static_cast<uint32_t>(packed_size);
       from_start < from_end; from_start++, to_start++) {
    Object* smi = from->get(from_start);
    ASSERT(!smi->IsTheHole());
    to->set(to_start, Smi::cast(smi)->value());
  }
}


419
static void CopyObjectToDoubleElements(FixedArrayBase* from_base,
420
                                       uint32_t from_start,
421
                                       FixedArrayBase* to_base,
422 423 424 425 426 427
                                       uint32_t to_start,
                                       int raw_copy_size) {
  int copy_size = raw_copy_size;
  if (raw_copy_size < 0) {
    ASSERT(raw_copy_size == ElementsAccessor::kCopyToEnd ||
           raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole);
428
    copy_size = from_base->length() - from_start;
429
    if (raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole) {
430 431
      for (int i = to_start + copy_size; i < to_base->length(); ++i) {
        FixedDoubleArray::cast(to_base)->set_the_hole(i);
432 433 434
      }
    }
  }
435 436
  ASSERT((copy_size + static_cast<int>(to_start)) <= to_base->length() &&
         (copy_size + static_cast<int>(from_start)) <= from_base->length());
437
  if (copy_size == 0) return;
438 439
  FixedArray* from = FixedArray::cast(from_base);
  FixedDoubleArray* to = FixedDoubleArray::cast(to_base);
440 441 442 443 444 445
  Object* the_hole = from->GetHeap()->the_hole_value();
  for (uint32_t from_end = from_start + copy_size;
       from_start < from_end; from_start++, to_start++) {
    Object* hole_or_object = from->get(from_start);
    if (hole_or_object == the_hole) {
      to->set_the_hole(to_start);
446
    } else {
447
      to->set(to_start, hole_or_object->Number());
448 449 450 451 452
    }
  }
}


453
static void CopyDictionaryToDoubleElements(FixedArrayBase* from_base,
454
                                           uint32_t from_start,
455
                                           FixedArrayBase* to_base,
456 457
                                           uint32_t to_start,
                                           int raw_copy_size) {
458
  SeededNumberDictionary* from = SeededNumberDictionary::cast(from_base);
459 460 461 462 463 464
  int copy_size = raw_copy_size;
  if (copy_size < 0) {
    ASSERT(copy_size == ElementsAccessor::kCopyToEnd ||
           copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole);
    copy_size = from->max_number_key() + 1 - from_start;
    if (raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole) {
465 466
      for (int i = to_start + copy_size; i < to_base->length(); ++i) {
        FixedDoubleArray::cast(to_base)->set_the_hole(i);
467 468 469 470
      }
    }
  }
  if (copy_size == 0) return;
471
  FixedDoubleArray* to = FixedDoubleArray::cast(to_base);
472 473 474 475
  uint32_t to_length = to->length();
  if (to_start + copy_size > to_length) {
    copy_size = to_length - to_start;
  }
476 477 478 479 480 481 482 483 484 485 486
  for (int i = 0; i < copy_size; i++) {
    int entry = from->FindEntry(i + from_start);
    if (entry != SeededNumberDictionary::kNotFound) {
      to->set(i + to_start, from->ValueAt(entry)->Number());
    } else {
      to->set_the_hole(i + to_start);
    }
  }
}


487 488
static void TraceTopFrame(Isolate* isolate) {
  StackFrameIterator it(isolate);
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
  if (it.done()) {
    PrintF("unknown location (no JavaScript frames present)");
    return;
  }
  StackFrame* raw_frame = it.frame();
  if (raw_frame->is_internal()) {
    Isolate* isolate = Isolate::Current();
    Code* apply_builtin = isolate->builtins()->builtin(
        Builtins::kFunctionApply);
    if (raw_frame->unchecked_code() == apply_builtin) {
      PrintF("apply from ");
      it.Advance();
      raw_frame = it.frame();
    }
  }
504
  JavaScriptFrame::PrintTop(isolate, stdout, false, true);
505 506 507
}


508 509
void CheckArrayAbuse(JSObject* obj, const char* op, uint32_t key,
                     bool allow_appending) {
510 511 512 513 514 515 516 517 518 519 520 521 522 523
  Object* raw_length = NULL;
  const char* elements_type = "array";
  if (obj->IsJSArray()) {
    JSArray* array = JSArray::cast(obj);
    raw_length = array->length();
  } else {
    raw_length = Smi::FromInt(obj->elements()->length());
    elements_type = "object";
  }

  if (raw_length->IsNumber()) {
    double n = raw_length->Number();
    if (FastI2D(FastD2UI(n)) == n) {
      int32_t int32_length = DoubleToInt32(n);
524 525 526
      uint32_t compare_length = static_cast<uint32_t>(int32_length);
      if (allow_appending) compare_length++;
      if (key >= compare_length) {
527 528 529 530
        PrintF("[OOB %s %s (%s length = %d, element accessed = %d) in ",
               elements_type, op, elements_type,
               static_cast<int>(int32_length),
               static_cast<int>(key));
531
        TraceTopFrame(obj->GetIsolate());
532 533 534 535
        PrintF("]\n");
      }
    } else {
      PrintF("[%s elements length not integer value in ", elements_type);
536
      TraceTopFrame(obj->GetIsolate());
537 538 539 540
      PrintF("]\n");
    }
  } else {
    PrintF("[%s elements length not a number in ", elements_type);
541
    TraceTopFrame(obj->GetIsolate());
542 543 544 545 546
    PrintF("]\n");
  }
}


547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
// Base class for element handler implementations. Contains the
// the common logic for objects with different ElementsKinds.
// Subclasses must specialize method for which the element
// implementation differs from the base class implementation.
//
// This class is intended to be used in the following way:
//
//   class SomeElementsAccessor :
//       public ElementsAccessorBase<SomeElementsAccessor,
//                                   BackingStoreClass> {
//     ...
//   }
//
// This is an example of the Curiously Recurring Template Pattern (see
// http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern).  We use
// CRTP to guarantee aggressive compile time optimizations (i.e.  inlining and
// specialization of SomeElementsAccessor methods).
564 565
template <typename ElementsAccessorSubclass,
          typename ElementsTraitsParam>
566
class ElementsAccessorBase : public ElementsAccessor {
567
 protected:
568 569 570 571 572 573 574
  explicit ElementsAccessorBase(const char* name)
      : ElementsAccessor(name) { }

  typedef ElementsTraitsParam ElementsTraits;
  typedef typename ElementsTraitsParam::BackingStore BackingStore;

  virtual ElementsKind kind() const { return ElementsTraits::Kind; }
575

576 577 578 579 580 581 582 583 584 585 586
  static void ValidateContents(JSObject* holder, int length) {
  }

  static void ValidateImpl(JSObject* holder) {
    FixedArrayBase* fixed_array_base = holder->elements();
    // When objects are first allocated, its elements are Failures.
    if (fixed_array_base->IsFailure()) return;
    if (!fixed_array_base->IsHeapObject()) return;
    Map* map = fixed_array_base->map();
    // Arrays that have been shifted in place can't be verified.
    Heap* heap = holder->GetHeap();
587 588
    if (map == heap->one_pointer_filler_map() ||
        map == heap->two_pointer_filler_map() ||
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
        map == heap->free_space_map()) {
      return;
    }
    int length = 0;
    if (holder->IsJSArray()) {
      Object* length_obj = JSArray::cast(holder)->length();
      if (length_obj->IsSmi()) {
        length = Smi::cast(length_obj)->value();
      }
    } else {
      length = fixed_array_base->length();
    }
    ElementsAccessorSubclass::ValidateContents(holder, length);
  }

  virtual void Validate(JSObject* holder) {
    ElementsAccessorSubclass::ValidateImpl(holder);
  }

608 609 610
  static bool HasElementImpl(Object* receiver,
                             JSObject* holder,
                             uint32_t key,
611
                             FixedArrayBase* backing_store) {
612 613
    return ElementsAccessorSubclass::GetAttributesImpl(
        receiver, holder, key, backing_store) != ABSENT;
614 615 616 617 618 619 620 621 622 623
  }

  virtual bool HasElement(Object* receiver,
                          JSObject* holder,
                          uint32_t key,
                          FixedArrayBase* backing_store) {
    if (backing_store == NULL) {
      backing_store = holder->elements();
    }
    return ElementsAccessorSubclass::HasElementImpl(
624
        receiver, holder, key, backing_store);
625 626
  }

627 628 629 630
  MUST_USE_RESULT virtual MaybeObject* Get(Object* receiver,
                                           JSObject* holder,
                                           uint32_t key,
                                           FixedArrayBase* backing_store) {
631 632 633
    if (backing_store == NULL) {
      backing_store = holder->elements();
    }
634

635 636 637 638 639 640 641 642
    if (!IsExternalArrayElementsKind(ElementsTraits::Kind) &&
        FLAG_trace_js_array_abuse) {
      CheckArrayAbuse(holder, "elements read", key);
    }

    if (IsExternalArrayElementsKind(ElementsTraits::Kind) &&
        FLAG_trace_external_array_abuse) {
      CheckArrayAbuse(holder, "external elements read", key);
643 644
    }

645
    return ElementsAccessorSubclass::GetImpl(
646
        receiver, holder, key, backing_store);
647 648
  }

649 650 651
  MUST_USE_RESULT static MaybeObject* GetImpl(Object* receiver,
                                              JSObject* obj,
                                              uint32_t key,
652
                                              FixedArrayBase* backing_store) {
653
    return (key < ElementsAccessorSubclass::GetCapacityImpl(backing_store))
654
           ? BackingStore::cast(backing_store)->get(key)
655
           : backing_store->GetHeap()->the_hole_value();
656 657
  }

658 659 660 661 662 663 664 665 666
  MUST_USE_RESULT virtual PropertyAttributes GetAttributes(
      Object* receiver,
      JSObject* holder,
      uint32_t key,
      FixedArrayBase* backing_store) {
    if (backing_store == NULL) {
      backing_store = holder->elements();
    }
    return ElementsAccessorSubclass::GetAttributesImpl(
667
        receiver, holder, key, backing_store);
668 669 670 671 672 673
  }

  MUST_USE_RESULT static PropertyAttributes GetAttributesImpl(
        Object* receiver,
        JSObject* obj,
        uint32_t key,
674
        FixedArrayBase* backing_store) {
675 676 677
    if (key >= ElementsAccessorSubclass::GetCapacityImpl(backing_store)) {
      return ABSENT;
    }
678
    return BackingStore::cast(backing_store)->is_the_hole(key) ? ABSENT : NONE;
679 680
  }

681 682 683 684 685 686 687 688 689
  MUST_USE_RESULT virtual PropertyType GetType(
      Object* receiver,
      JSObject* holder,
      uint32_t key,
      FixedArrayBase* backing_store) {
    if (backing_store == NULL) {
      backing_store = holder->elements();
    }
    return ElementsAccessorSubclass::GetTypeImpl(
690
        receiver, holder, key, backing_store);
691 692 693 694 695 696
  }

  MUST_USE_RESULT static PropertyType GetTypeImpl(
        Object* receiver,
        JSObject* obj,
        uint32_t key,
697
        FixedArrayBase* backing_store) {
698 699 700
    if (key >= ElementsAccessorSubclass::GetCapacityImpl(backing_store)) {
      return NONEXISTENT;
    }
701 702
    return BackingStore::cast(backing_store)->is_the_hole(key)
        ? NONEXISTENT : FIELD;
703 704 705 706 707 708 709 710 711 712 713
  }

  MUST_USE_RESULT virtual AccessorPair* GetAccessorPair(
      Object* receiver,
      JSObject* holder,
      uint32_t key,
      FixedArrayBase* backing_store) {
    if (backing_store == NULL) {
      backing_store = holder->elements();
    }
    return ElementsAccessorSubclass::GetAccessorPairImpl(
714
        receiver, holder, key, backing_store);
715 716 717 718 719 720
  }

  MUST_USE_RESULT static AccessorPair* GetAccessorPairImpl(
        Object* receiver,
        JSObject* obj,
        uint32_t key,
721
        FixedArrayBase* backing_store) {
722 723 724
    return NULL;
  }

725 726
  MUST_USE_RESULT virtual MaybeObject* SetLength(JSArray* array,
                                                 Object* length) {
727
    return ElementsAccessorSubclass::SetLengthImpl(
728
        array, length, array->elements());
729 730
  }

731 732 733
  MUST_USE_RESULT static MaybeObject* SetLengthImpl(
      JSObject* obj,
      Object* length,
734
      FixedArrayBase* backing_store);
735

736 737 738 739
  MUST_USE_RESULT virtual MaybeObject* SetCapacityAndLength(
      JSArray* array,
      int capacity,
      int length) {
740 741 742 743 744 745
    return ElementsAccessorSubclass::SetFastElementsCapacityAndLength(
        array,
        capacity,
        length);
  }

746 747 748 749
  MUST_USE_RESULT static MaybeObject* SetFastElementsCapacityAndLength(
      JSObject* obj,
      int capacity,
      int length) {
750 751 752 753
    UNIMPLEMENTED();
    return obj;
  }

754 755 756
  MUST_USE_RESULT virtual MaybeObject* Delete(JSObject* obj,
                                              uint32_t key,
                                              JSReceiver::DeleteMode mode) = 0;
757

758 759 760
  MUST_USE_RESULT static MaybeObject* CopyElementsImpl(FixedArrayBase* from,
                                                       uint32_t from_start,
                                                       FixedArrayBase* to,
761
                                                       ElementsKind from_kind,
762
                                                       uint32_t to_start,
763
                                                       int packed_size,
764
                                                       int copy_size) {
765 766 767 768
    UNREACHABLE();
    return NULL;
  }

769 770
  MUST_USE_RESULT virtual MaybeObject* CopyElements(JSObject* from_holder,
                                                    uint32_t from_start,
771
                                                    ElementsKind from_kind,
772 773 774 775
                                                    FixedArrayBase* to,
                                                    uint32_t to_start,
                                                    int copy_size,
                                                    FixedArrayBase* from) {
776
    int packed_size = kPackedSizeNotKnown;
777 778 779
    if (from == NULL) {
      from = from_holder->elements();
    }
780 781

    if (from_holder) {
782
      bool is_packed = IsFastPackedElementsKind(from_kind) &&
783 784 785 786 787 788 789 790
          from_holder->IsJSArray();
      if (is_packed) {
        packed_size = Smi::cast(JSArray::cast(from_holder)->length())->value();
        if (copy_size >= 0 && packed_size > copy_size) {
          packed_size = copy_size;
        }
      }
    }
791
    return ElementsAccessorSubclass::CopyElementsImpl(
792
        from, from_start, to, from_kind, to_start, packed_size, copy_size);
793 794
  }

795 796 797 798 799
  MUST_USE_RESULT virtual MaybeObject* AddElementsToFixedArray(
      Object* receiver,
      JSObject* holder,
      FixedArray* to,
      FixedArrayBase* from) {
800
    int len0 = to->length();
801 802 803
#ifdef DEBUG
    if (FLAG_enable_slow_asserts) {
      for (int i = 0; i < len0; i++) {
804
        ASSERT(!to->get(i)->IsTheHole());
805 806 807
      }
    }
#endif
808 809 810
    if (from == NULL) {
      from = holder->elements();
    }
811 812

    // Optimize if 'other' is empty.
813
    // We cannot optimize if 'this' is empty, as other may have holes.
814
    uint32_t len1 = ElementsAccessorSubclass::GetCapacityImpl(from);
815
    if (len1 == 0) return to;
816 817

    // Compute how many elements are not in other.
818
    uint32_t extra = 0;
819
    for (uint32_t y = 0; y < len1; y++) {
820
      uint32_t key = ElementsAccessorSubclass::GetKeyForIndexImpl(from, y);
821
      if (ElementsAccessorSubclass::HasElementImpl(
822
              receiver, holder, key, from)) {
823
        MaybeObject* maybe_value =
824
            ElementsAccessorSubclass::GetImpl(receiver, holder, key, from);
825
        Object* value;
826
        if (!maybe_value->To(&value)) return maybe_value;
827 828 829 830 831
        ASSERT(!value->IsTheHole());
        if (!HasKey(to, value)) {
          extra++;
        }
      }
832 833
    }

834
    if (extra == 0) return to;
835 836 837

    // Allocate the result
    FixedArray* result;
838 839
    MaybeObject* maybe_obj = from->GetHeap()->AllocateFixedArray(len0 + extra);
    if (!maybe_obj->To(&result)) return maybe_obj;
840 841 842 843 844 845

    // Fill in the content
    {
      AssertNoAllocation no_gc;
      WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
      for (int i = 0; i < len0; i++) {
846
        Object* e = to->get(i);
847 848 849 850
        ASSERT(e->IsString() || e->IsNumber());
        result->set(i, e, mode);
      }
    }
851
    // Fill in the extra values.
852
    uint32_t index = 0;
853
    for (uint32_t y = 0; y < len1; y++) {
854
      uint32_t key =
855
          ElementsAccessorSubclass::GetKeyForIndexImpl(from, y);
856
      if (ElementsAccessorSubclass::HasElementImpl(
857
              receiver, holder, key, from)) {
858
        MaybeObject* maybe_value =
859
            ElementsAccessorSubclass::GetImpl(receiver, holder, key, from);
860
        Object* value;
861
        if (!maybe_value->To(&value)) return maybe_value;
862 863 864 865
        if (!value->IsTheHole() && !HasKey(to, value)) {
          result->set(len0 + index, value);
          index++;
        }
866 867 868 869 870 871
      }
    }
    ASSERT(extra == index);
    return result;
  }

872
 protected:
873
  static uint32_t GetCapacityImpl(FixedArrayBase* backing_store) {
874
    return backing_store->length();
875 876
  }

877
  virtual uint32_t GetCapacity(FixedArrayBase* backing_store) {
878
    return ElementsAccessorSubclass::GetCapacityImpl(backing_store);
879 880
  }

881
  static uint32_t GetKeyForIndexImpl(FixedArrayBase* backing_store,
882
                                     uint32_t index) {
883 884 885 886
    return index;
  }

  virtual uint32_t GetKeyForIndex(FixedArrayBase* backing_store,
887
                                  uint32_t index) {
888
    return ElementsAccessorSubclass::GetKeyForIndexImpl(backing_store, index);
889 890 891 892 893 894 895
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(ElementsAccessorBase);
};


896 897
// Super class for all fast element arrays.
template<typename FastElementsAccessorSubclass,
898
         typename KindTraits,
899
         int ElementSize>
900
class FastElementsAccessor
901
    : public ElementsAccessorBase<FastElementsAccessorSubclass, KindTraits> {
902 903 904
 public:
  explicit FastElementsAccessor(const char* name)
      : ElementsAccessorBase<FastElementsAccessorSubclass,
905
                             KindTraits>(name) {}
906
 protected:
907
  friend class ElementsAccessorBase<FastElementsAccessorSubclass, KindTraits>;
908
  friend class NonStrictArgumentsElementsAccessor;
909 910

  typedef typename KindTraits::BackingStore BackingStore;
911 912 913

  // Adjusts the length of the fast backing store or returns the new length or
  // undefined in case conversion to a slow backing store should be performed.
914
  static MaybeObject* SetLengthWithoutNormalize(FixedArrayBase* backing_store,
915 916 917 918
                                                JSArray* array,
                                                Object* length_object,
                                                uint32_t length) {
    uint32_t old_capacity = backing_store->length();
919
    Object* old_length = array->length();
920 921
    bool same_or_smaller_size = old_length->IsSmi() &&
        static_cast<uint32_t>(Smi::cast(old_length)->value()) >= length;
922 923
    ElementsKind kind = array->GetElementsKind();

924
    if (!same_or_smaller_size && IsFastElementsKind(kind) &&
925 926 927 928 929
        !IsFastHoleyElementsKind(kind)) {
      kind = GetHoleyElementsKind(kind);
      MaybeObject* maybe_obj = array->TransitionElementsKind(kind);
      if (maybe_obj->IsFailure()) return maybe_obj;
    }
930 931 932

    // Check whether the backing store should be shrunk.
    if (length <= old_capacity) {
933
      if (array->HasFastSmiOrObjectElements()) {
934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
        MaybeObject* maybe_obj = array->EnsureWritableFastElements();
        if (!maybe_obj->To(&backing_store)) return maybe_obj;
      }
      if (2 * length <= old_capacity) {
        // If more than half the elements won't be used, trim the array.
        if (length == 0) {
          array->initialize_elements();
        } else {
          backing_store->set_length(length);
          Address filler_start = backing_store->address() +
              BackingStore::OffsetOfElementAt(length);
          int filler_size = (old_capacity - length) * ElementSize;
          array->GetHeap()->CreateFillerObjectAt(filler_start, filler_size);
        }
      } else {
        // Otherwise, fill the unused tail with holes.
950
        int old_length = FastD2IChecked(array->length()->Number());
951
        for (int i = length; i < old_length; i++) {
952
          BackingStore::cast(backing_store)->set_the_hole(i);
953 954 955 956 957 958 959 960 961 962 963 964
        }
      }
      return length_object;
    }

    // Check whether the backing store should be expanded.
    uint32_t min = JSObject::NewElementsCapacity(old_capacity);
    uint32_t new_capacity = length > min ? length : min;
    if (!array->ShouldConvertToSlowElements(new_capacity)) {
      MaybeObject* result = FastElementsAccessorSubclass::
          SetFastElementsCapacityAndLength(array, new_capacity, length);
      if (result->IsFailure()) return result;
965
      array->ValidateElements();
966 967 968 969 970 971
      return length_object;
    }

    // Request conversion to slow elements.
    return array->GetHeap()->undefined_value();
  }
972

973
  static MaybeObject* DeleteCommon(JSObject* obj,
974 975 976 977
                                   uint32_t key,
                                   JSReceiver::DeleteMode mode) {
    ASSERT(obj->HasFastSmiOrObjectElements() ||
           obj->HasFastDoubleElements() ||
978
           obj->HasFastArgumentsElements());
979
    Heap* heap = obj->GetHeap();
980 981 982 983 984 985 986 987 988
    Object* elements = obj->elements();
    if (elements == heap->empty_fixed_array()) {
      return heap->true_value();
    }
    typename KindTraits::BackingStore* backing_store =
        KindTraits::BackingStore::cast(elements);
    bool is_non_strict_arguments_elements_map =
        backing_store->map() == heap->non_strict_arguments_elements_map();
    if (is_non_strict_arguments_elements_map) {
989 990
      backing_store = KindTraits::BackingStore::cast(
          FixedArray::cast(backing_store)->get(1));
991 992 993 994 995
    }
    uint32_t length = static_cast<uint32_t>(
        obj->IsJSArray()
        ? Smi::cast(JSArray::cast(obj)->length())->value()
        : backing_store->length());
996
    if (key < length) {
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
      if (!is_non_strict_arguments_elements_map) {
        ElementsKind kind = KindTraits::Kind;
        if (IsFastPackedElementsKind(kind)) {
          MaybeObject* transitioned =
              obj->TransitionElementsKind(GetHoleyElementsKind(kind));
          if (transitioned->IsFailure()) return transitioned;
        }
        if (IsFastSmiOrObjectElementsKind(KindTraits::Kind)) {
          Object* writable;
          MaybeObject* maybe = obj->EnsureWritableFastElements();
          if (!maybe->ToObject(&writable)) return maybe;
          backing_store = KindTraits::BackingStore::cast(writable);
        }
      }
1011
      backing_store->set_the_hole(key);
1012 1013 1014 1015 1016 1017 1018
      // If an old space backing store is larger than a certain size and
      // has too few used values, normalize it.
      // To avoid doing the check on every delete we require at least
      // one adjacent hole to the value being deleted.
      const int kMinLengthForSparsenessCheck = 64;
      if (backing_store->length() >= kMinLengthForSparsenessCheck &&
          !heap->InNewSpace(backing_store) &&
1019 1020
          ((key > 0 && backing_store->is_the_hole(key - 1)) ||
           (key + 1 < length && backing_store->is_the_hole(key + 1)))) {
1021 1022
        int num_used = 0;
        for (int i = 0; i < backing_store->length(); ++i) {
1023
          if (!backing_store->is_the_hole(i)) ++num_used;
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
          // Bail out early if more than 1/4 is used.
          if (4 * num_used > backing_store->length()) break;
        }
        if (4 * num_used <= backing_store->length()) {
          MaybeObject* result = obj->NormalizeElements();
          if (result->IsFailure()) return result;
        }
      }
    }
    return heap->true_value();
  }

1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
  virtual MaybeObject* Delete(JSObject* obj,
                              uint32_t key,
                              JSReceiver::DeleteMode mode) {
    return DeleteCommon(obj, key, mode);
  }

  static bool HasElementImpl(
      Object* receiver,
      JSObject* holder,
      uint32_t key,
1046
      FixedArrayBase* backing_store) {
1047 1048 1049
    if (key >= static_cast<uint32_t>(backing_store->length())) {
      return false;
    }
1050
    return !BackingStore::cast(backing_store)->is_the_hole(key);
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
  }

  static void ValidateContents(JSObject* holder, int length) {
#if DEBUG
    FixedArrayBase* elements = holder->elements();
    Heap* heap = elements->GetHeap();
    Map* map = elements->map();
    ASSERT((IsFastSmiOrObjectElementsKind(KindTraits::Kind) &&
            (map == heap->fixed_array_map() ||
             map == heap->fixed_cow_array_map())) ||
           (IsFastDoubleElementsKind(KindTraits::Kind) ==
            ((map == heap->fixed_array_map() && length == 0) ||
             map == heap->fixed_double_array_map())));
    for (int i = 0; i < length; i++) {
      typename KindTraits::BackingStore* backing_store =
          KindTraits::BackingStore::cast(elements);
      ASSERT((!IsFastSmiElementsKind(KindTraits::Kind) ||
              static_cast<Object*>(backing_store->get(i))->IsSmi()) ||
             (IsFastHoleyElementsKind(KindTraits::Kind) ==
              backing_store->is_the_hole(i)));
    }
#endif
  }
};


1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
static inline ElementsKind ElementsKindForArray(FixedArrayBase* array) {
  switch (array->map()->instance_type()) {
    case FIXED_ARRAY_TYPE:
      if (array->IsDictionary()) {
        return DICTIONARY_ELEMENTS;
      } else {
        return FAST_HOLEY_ELEMENTS;
      }
    case FIXED_DOUBLE_ARRAY_TYPE:
      return FAST_HOLEY_DOUBLE_ELEMENTS;
    case EXTERNAL_BYTE_ARRAY_TYPE:
      return EXTERNAL_BYTE_ELEMENTS;
    case EXTERNAL_UNSIGNED_BYTE_ARRAY_TYPE:
      return EXTERNAL_UNSIGNED_BYTE_ELEMENTS;
    case EXTERNAL_SHORT_ARRAY_TYPE:
      return EXTERNAL_SHORT_ELEMENTS;
    case EXTERNAL_UNSIGNED_SHORT_ARRAY_TYPE:
      return EXTERNAL_UNSIGNED_SHORT_ELEMENTS;
    case EXTERNAL_INT_ARRAY_TYPE:
      return EXTERNAL_INT_ELEMENTS;
    case EXTERNAL_UNSIGNED_INT_ARRAY_TYPE:
      return EXTERNAL_UNSIGNED_INT_ELEMENTS;
    case EXTERNAL_FLOAT_ARRAY_TYPE:
      return EXTERNAL_FLOAT_ELEMENTS;
    case EXTERNAL_DOUBLE_ARRAY_TYPE:
      return EXTERNAL_DOUBLE_ELEMENTS;
    case EXTERNAL_PIXEL_ARRAY_TYPE:
      return EXTERNAL_PIXEL_ELEMENTS;
    default:
      UNREACHABLE();
  }
  return FAST_HOLEY_ELEMENTS;
}


1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
template<typename FastElementsAccessorSubclass,
         typename KindTraits>
class FastSmiOrObjectElementsAccessor
    : public FastElementsAccessor<FastElementsAccessorSubclass,
                                  KindTraits,
                                  kPointerSize> {
 public:
  explicit FastSmiOrObjectElementsAccessor(const char* name)
      : FastElementsAccessor<FastElementsAccessorSubclass,
                             KindTraits,
                             kPointerSize>(name) {}

1124 1125 1126
  static MaybeObject* CopyElementsImpl(FixedArrayBase* from,
                                       uint32_t from_start,
                                       FixedArrayBase* to,
1127
                                       ElementsKind from_kind,
1128
                                       uint32_t to_start,
1129
                                       int packed_size,
1130
                                       int copy_size) {
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
    ElementsKind to_kind = KindTraits::Kind;
    switch (from_kind) {
      case FAST_SMI_ELEMENTS:
      case FAST_HOLEY_SMI_ELEMENTS:
      case FAST_ELEMENTS:
      case FAST_HOLEY_ELEMENTS:
        CopyObjectToObjectElements(
            from, from_kind, from_start, to, to_kind, to_start, copy_size);
        return to->GetHeap()->undefined_value();
      case FAST_DOUBLE_ELEMENTS:
      case FAST_HOLEY_DOUBLE_ELEMENTS:
        return CopyDoubleToObjectElements(
            from, from_start, to, to_kind, to_start, copy_size);
      case DICTIONARY_ELEMENTS:
        CopyDictionaryToObjectElements(
            from, from_start, to, to_kind, to_start, copy_size);
        return to->GetHeap()->undefined_value();
      case NON_STRICT_ARGUMENTS_ELEMENTS: {
        // TODO(verwaest): This is a temporary hack to support extending
        // NON_STRICT_ARGUMENTS_ELEMENTS in SetFastElementsCapacityAndLength.
        // This case should be UNREACHABLE().
        FixedArray* parameter_map = FixedArray::cast(from);
        FixedArrayBase* arguments = FixedArrayBase::cast(parameter_map->get(1));
        ElementsKind from_kind = ElementsKindForArray(arguments);
        return CopyElementsImpl(arguments, from_start, to, from_kind,
                                to_start, packed_size, copy_size);
1157
      }
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
      case EXTERNAL_BYTE_ELEMENTS:
      case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
      case EXTERNAL_SHORT_ELEMENTS:
      case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
      case EXTERNAL_INT_ELEMENTS:
      case EXTERNAL_UNSIGNED_INT_ELEMENTS:
      case EXTERNAL_FLOAT_ELEMENTS:
      case EXTERNAL_DOUBLE_ELEMENTS:
      case EXTERNAL_PIXEL_ELEMENTS:
        UNREACHABLE();
1168
    }
1169
    return NULL;
1170 1171 1172
  }


1173 1174 1175
  static MaybeObject* SetFastElementsCapacityAndLength(JSObject* obj,
                                                       uint32_t capacity,
                                                       uint32_t length) {
1176 1177 1178 1179
    JSObject::SetFastElementsCapacitySmiMode set_capacity_mode =
        obj->HasFastSmiElements()
            ? JSObject::kAllowSmiElements
            : JSObject::kDontAllowSmiElements;
1180 1181 1182 1183
    return obj->SetFastElementsCapacityAndLength(capacity,
                                                 length,
                                                 set_capacity_mode);
  }
1184
};
1185

1186

1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
class FastPackedSmiElementsAccessor
    : public FastSmiOrObjectElementsAccessor<
        FastPackedSmiElementsAccessor,
        ElementsKindTraits<FAST_SMI_ELEMENTS> > {
 public:
  explicit FastPackedSmiElementsAccessor(const char* name)
      : FastSmiOrObjectElementsAccessor<
          FastPackedSmiElementsAccessor,
          ElementsKindTraits<FAST_SMI_ELEMENTS> >(name) {}
};


class FastHoleySmiElementsAccessor
    : public FastSmiOrObjectElementsAccessor<
        FastHoleySmiElementsAccessor,
        ElementsKindTraits<FAST_HOLEY_SMI_ELEMENTS> > {
 public:
  explicit FastHoleySmiElementsAccessor(const char* name)
      : FastSmiOrObjectElementsAccessor<
          FastHoleySmiElementsAccessor,
          ElementsKindTraits<FAST_HOLEY_SMI_ELEMENTS> >(name) {}
1208 1209 1210
};


1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
class FastPackedObjectElementsAccessor
    : public FastSmiOrObjectElementsAccessor<
        FastPackedObjectElementsAccessor,
        ElementsKindTraits<FAST_ELEMENTS> > {
 public:
  explicit FastPackedObjectElementsAccessor(const char* name)
      : FastSmiOrObjectElementsAccessor<
          FastPackedObjectElementsAccessor,
          ElementsKindTraits<FAST_ELEMENTS> >(name) {}
};


class FastHoleyObjectElementsAccessor
    : public FastSmiOrObjectElementsAccessor<
        FastHoleyObjectElementsAccessor,
        ElementsKindTraits<FAST_HOLEY_ELEMENTS> > {
 public:
  explicit FastHoleyObjectElementsAccessor(const char* name)
      : FastSmiOrObjectElementsAccessor<
          FastHoleyObjectElementsAccessor,
          ElementsKindTraits<FAST_HOLEY_ELEMENTS> >(name) {}
};


template<typename FastElementsAccessorSubclass,
         typename KindTraits>
1237
class FastDoubleElementsAccessor
1238 1239
    : public FastElementsAccessor<FastElementsAccessorSubclass,
                                  KindTraits,
1240
                                  kDoubleSize> {
1241 1242
 public:
  explicit FastDoubleElementsAccessor(const char* name)
1243 1244
      : FastElementsAccessor<FastElementsAccessorSubclass,
                             KindTraits,
1245 1246
                             kDoubleSize>(name) {}

1247 1248 1249
  static MaybeObject* SetFastElementsCapacityAndLength(JSObject* obj,
                                                       uint32_t capacity,
                                                       uint32_t length) {
1250 1251
    return obj->SetFastDoubleElementsCapacityAndLength(capacity,
                                                       length);
1252 1253
  }

1254
 protected:
1255 1256 1257
  static MaybeObject* CopyElementsImpl(FixedArrayBase* from,
                                       uint32_t from_start,
                                       FixedArrayBase* to,
1258
                                       ElementsKind from_kind,
1259
                                       uint32_t to_start,
1260
                                       int packed_size,
1261
                                       int copy_size) {
1262
    switch (from_kind) {
1263
      case FAST_SMI_ELEMENTS:
1264 1265 1266
        CopyPackedSmiToDoubleElements(
            from, from_start, to, to_start, packed_size, copy_size);
        break;
1267
      case FAST_HOLEY_SMI_ELEMENTS:
1268 1269
        CopySmiToDoubleElements(from, from_start, to, to_start, copy_size);
        break;
1270
      case FAST_DOUBLE_ELEMENTS:
1271
      case FAST_HOLEY_DOUBLE_ELEMENTS:
1272
        CopyDoubleToDoubleElements(from, from_start, to, to_start, copy_size);
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
        break;
      case FAST_ELEMENTS:
      case FAST_HOLEY_ELEMENTS:
        CopyObjectToDoubleElements(from, from_start, to, to_start, copy_size);
        break;
      case DICTIONARY_ELEMENTS:
        CopyDictionaryToDoubleElements(
            from, from_start, to, to_start, copy_size);
        break;
      case NON_STRICT_ARGUMENTS_ELEMENTS:
      case EXTERNAL_BYTE_ELEMENTS:
      case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
      case EXTERNAL_SHORT_ELEMENTS:
      case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
      case EXTERNAL_INT_ELEMENTS:
      case EXTERNAL_UNSIGNED_INT_ELEMENTS:
      case EXTERNAL_FLOAT_ELEMENTS:
      case EXTERNAL_DOUBLE_ELEMENTS:
      case EXTERNAL_PIXEL_ELEMENTS:
1292 1293 1294 1295
        UNREACHABLE();
    }
    return to->GetHeap()->undefined_value();
  }
1296
};
1297

1298

1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
class FastPackedDoubleElementsAccessor
    : public FastDoubleElementsAccessor<
        FastPackedDoubleElementsAccessor,
        ElementsKindTraits<FAST_DOUBLE_ELEMENTS> > {
 public:
  friend class ElementsAccessorBase<FastPackedDoubleElementsAccessor,
                                    ElementsKindTraits<FAST_DOUBLE_ELEMENTS> >;
  explicit FastPackedDoubleElementsAccessor(const char* name)
      : FastDoubleElementsAccessor<
          FastPackedDoubleElementsAccessor,
          ElementsKindTraits<FAST_DOUBLE_ELEMENTS> >(name) {}
};


class FastHoleyDoubleElementsAccessor
    : public FastDoubleElementsAccessor<
        FastHoleyDoubleElementsAccessor,
        ElementsKindTraits<FAST_HOLEY_DOUBLE_ELEMENTS> > {
 public:
  friend class ElementsAccessorBase<
    FastHoleyDoubleElementsAccessor,
    ElementsKindTraits<FAST_HOLEY_DOUBLE_ELEMENTS> >;
  explicit FastHoleyDoubleElementsAccessor(const char* name)
      : FastDoubleElementsAccessor<
          FastHoleyDoubleElementsAccessor,
          ElementsKindTraits<FAST_HOLEY_DOUBLE_ELEMENTS> >(name) {}
1325 1326 1327 1328 1329
};


// Super class for all external element arrays.
template<typename ExternalElementsAccessorSubclass,
1330
         ElementsKind Kind>
1331 1332
class ExternalElementsAccessor
    : public ElementsAccessorBase<ExternalElementsAccessorSubclass,
1333
                                  ElementsKindTraits<Kind> > {
1334 1335 1336
 public:
  explicit ExternalElementsAccessor(const char* name)
      : ElementsAccessorBase<ExternalElementsAccessorSubclass,
1337
                             ElementsKindTraits<Kind> >(name) {}
1338

1339
 protected:
1340 1341
  typedef typename ElementsKindTraits<Kind>::BackingStore BackingStore;

1342
  friend class ElementsAccessorBase<ExternalElementsAccessorSubclass,
1343
                                    ElementsKindTraits<Kind> >;
1344

1345 1346 1347
  MUST_USE_RESULT static MaybeObject* GetImpl(Object* receiver,
                                              JSObject* obj,
                                              uint32_t key,
1348
                                              FixedArrayBase* backing_store) {
1349 1350
    return
        key < ExternalElementsAccessorSubclass::GetCapacityImpl(backing_store)
1351
        ? BackingStore::cast(backing_store)->get(key)
1352
        : backing_store->GetHeap()->undefined_value();
1353
  }
1354

1355 1356 1357 1358
  MUST_USE_RESULT static PropertyAttributes GetAttributesImpl(
      Object* receiver,
      JSObject* obj,
      uint32_t key,
1359
      FixedArrayBase* backing_store) {
1360 1361
    return
        key < ExternalElementsAccessorSubclass::GetCapacityImpl(backing_store)
1362 1363 1364 1365 1366 1367 1368
          ? NONE : ABSENT;
  }

  MUST_USE_RESULT static PropertyType GetTypeImpl(
      Object* receiver,
      JSObject* obj,
      uint32_t key,
1369
      FixedArrayBase* backing_store) {
1370 1371 1372
    return
        key < ExternalElementsAccessorSubclass::GetCapacityImpl(backing_store)
          ? FIELD : NONEXISTENT;
1373 1374
  }

1375 1376 1377
  MUST_USE_RESULT static MaybeObject* SetLengthImpl(
      JSObject* obj,
      Object* length,
1378
      FixedArrayBase* backing_store) {
1379 1380 1381 1382 1383
    // External arrays do not support changing their length.
    UNREACHABLE();
    return obj;
  }

1384 1385 1386
  MUST_USE_RESULT virtual MaybeObject* Delete(JSObject* obj,
                                              uint32_t key,
                                              JSReceiver::DeleteMode mode) {
1387 1388 1389
    // External arrays always ignore deletes.
    return obj->GetHeap()->true_value();
  }
1390

1391
  static bool HasElementImpl(Object* receiver,
1392
                             JSObject* holder,
1393
                             uint32_t key,
1394
                             FixedArrayBase* backing_store) {
1395 1396 1397 1398
    uint32_t capacity =
        ExternalElementsAccessorSubclass::GetCapacityImpl(backing_store);
    return key < capacity;
  }
1399 1400 1401 1402 1403
};


class ExternalByteElementsAccessor
    : public ExternalElementsAccessor<ExternalByteElementsAccessor,
1404
                                      EXTERNAL_BYTE_ELEMENTS> {
1405 1406 1407
 public:
  explicit ExternalByteElementsAccessor(const char* name)
      : ExternalElementsAccessor<ExternalByteElementsAccessor,
1408
                                 EXTERNAL_BYTE_ELEMENTS>(name) {}
1409 1410 1411 1412 1413
};


class ExternalUnsignedByteElementsAccessor
    : public ExternalElementsAccessor<ExternalUnsignedByteElementsAccessor,
1414
                                      EXTERNAL_UNSIGNED_BYTE_ELEMENTS> {
1415 1416 1417
 public:
  explicit ExternalUnsignedByteElementsAccessor(const char* name)
      : ExternalElementsAccessor<ExternalUnsignedByteElementsAccessor,
1418
                                 EXTERNAL_UNSIGNED_BYTE_ELEMENTS>(name) {}
1419 1420 1421 1422 1423
};


class ExternalShortElementsAccessor
    : public ExternalElementsAccessor<ExternalShortElementsAccessor,
1424
                                      EXTERNAL_SHORT_ELEMENTS> {
1425 1426 1427
 public:
  explicit ExternalShortElementsAccessor(const char* name)
      : ExternalElementsAccessor<ExternalShortElementsAccessor,
1428
                                 EXTERNAL_SHORT_ELEMENTS>(name) {}
1429 1430 1431 1432 1433
};


class ExternalUnsignedShortElementsAccessor
    : public ExternalElementsAccessor<ExternalUnsignedShortElementsAccessor,
1434
                                      EXTERNAL_UNSIGNED_SHORT_ELEMENTS> {
1435 1436 1437
 public:
  explicit ExternalUnsignedShortElementsAccessor(const char* name)
      : ExternalElementsAccessor<ExternalUnsignedShortElementsAccessor,
1438
                                 EXTERNAL_UNSIGNED_SHORT_ELEMENTS>(name) {}
1439 1440 1441 1442 1443
};


class ExternalIntElementsAccessor
    : public ExternalElementsAccessor<ExternalIntElementsAccessor,
1444
                                      EXTERNAL_INT_ELEMENTS> {
1445 1446 1447
 public:
  explicit ExternalIntElementsAccessor(const char* name)
      : ExternalElementsAccessor<ExternalIntElementsAccessor,
1448
                                 EXTERNAL_INT_ELEMENTS>(name) {}
1449 1450 1451 1452 1453
};


class ExternalUnsignedIntElementsAccessor
    : public ExternalElementsAccessor<ExternalUnsignedIntElementsAccessor,
1454
                                      EXTERNAL_UNSIGNED_INT_ELEMENTS> {
1455 1456 1457
 public:
  explicit ExternalUnsignedIntElementsAccessor(const char* name)
      : ExternalElementsAccessor<ExternalUnsignedIntElementsAccessor,
1458
                                 EXTERNAL_UNSIGNED_INT_ELEMENTS>(name) {}
1459 1460 1461 1462 1463
};


class ExternalFloatElementsAccessor
    : public ExternalElementsAccessor<ExternalFloatElementsAccessor,
1464
                                      EXTERNAL_FLOAT_ELEMENTS> {
1465 1466 1467
 public:
  explicit ExternalFloatElementsAccessor(const char* name)
      : ExternalElementsAccessor<ExternalFloatElementsAccessor,
1468
                                 EXTERNAL_FLOAT_ELEMENTS>(name) {}
1469 1470 1471 1472 1473
};


class ExternalDoubleElementsAccessor
    : public ExternalElementsAccessor<ExternalDoubleElementsAccessor,
1474
                                      EXTERNAL_DOUBLE_ELEMENTS> {
1475 1476 1477
 public:
  explicit ExternalDoubleElementsAccessor(const char* name)
      : ExternalElementsAccessor<ExternalDoubleElementsAccessor,
1478
                                 EXTERNAL_DOUBLE_ELEMENTS>(name) {}
1479 1480 1481 1482 1483
};


class PixelElementsAccessor
    : public ExternalElementsAccessor<PixelElementsAccessor,
1484
                                      EXTERNAL_PIXEL_ELEMENTS> {
1485 1486 1487
 public:
  explicit PixelElementsAccessor(const char* name)
      : ExternalElementsAccessor<PixelElementsAccessor,
1488
                                 EXTERNAL_PIXEL_ELEMENTS>(name) {}
1489 1490 1491 1492 1493
};


class DictionaryElementsAccessor
    : public ElementsAccessorBase<DictionaryElementsAccessor,
1494
                                  ElementsKindTraits<DICTIONARY_ELEMENTS> > {
1495
 public:
1496 1497
  explicit DictionaryElementsAccessor(const char* name)
      : ElementsAccessorBase<DictionaryElementsAccessor,
1498
                             ElementsKindTraits<DICTIONARY_ELEMENTS> >(name) {}
1499

1500 1501
  // Adjusts the length of the dictionary backing store and returns the new
  // length according to ES5 section 15.4.5.2 behavior.
1502
  MUST_USE_RESULT static MaybeObject* SetLengthWithoutNormalize(
1503
      FixedArrayBase* store,
1504 1505 1506
      JSArray* array,
      Object* length_object,
      uint32_t length) {
1507
    SeededNumberDictionary* dict = SeededNumberDictionary::cast(store);
1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531
    Heap* heap = array->GetHeap();
    int capacity = dict->Capacity();
    uint32_t new_length = length;
    uint32_t old_length = static_cast<uint32_t>(array->length()->Number());
    if (new_length < old_length) {
      // Find last non-deletable element in range of elements to be
      // deleted and adjust range accordingly.
      for (int i = 0; i < capacity; i++) {
        Object* key = dict->KeyAt(i);
        if (key->IsNumber()) {
          uint32_t number = static_cast<uint32_t>(key->Number());
          if (new_length <= number && number < old_length) {
            PropertyDetails details = dict->DetailsAt(i);
            if (details.IsDontDelete()) new_length = number + 1;
          }
        }
      }
      if (new_length != length) {
        MaybeObject* maybe_object = heap->NumberFromUint32(new_length);
        if (!maybe_object->To(&length_object)) return maybe_object;
      }
    }

    if (new_length == 0) {
1532 1533 1534 1535 1536 1537 1538
      // If the length of a slow array is reset to zero, we clear
      // the array and flush backing storage. This has the added
      // benefit that the array returns to fast mode.
      Object* obj;
      MaybeObject* maybe_obj = array->ResetElements();
      if (!maybe_obj->ToObject(&obj)) return maybe_obj;
    } else {
1539 1540 1541 1542 1543 1544 1545 1546 1547 1548
      // Remove elements that should be deleted.
      int removed_entries = 0;
      Object* the_hole_value = heap->the_hole_value();
      for (int i = 0; i < capacity; i++) {
        Object* key = dict->KeyAt(i);
        if (key->IsNumber()) {
          uint32_t number = static_cast<uint32_t>(key->Number());
          if (new_length <= number && number < old_length) {
            dict->SetEntry(i, the_hole_value, the_hole_value);
            removed_entries++;
1549 1550 1551
          }
        }
      }
1552 1553 1554

      // Update the number of elements.
      dict->ElementsRemoved(removed_entries);
1555 1556 1557 1558
    }
    return length_object;
  }

1559 1560 1561 1562
  MUST_USE_RESULT static MaybeObject* DeleteCommon(
      JSObject* obj,
      uint32_t key,
      JSReceiver::DeleteMode mode) {
1563 1564 1565 1566
    Isolate* isolate = obj->GetIsolate();
    Heap* heap = isolate->heap();
    FixedArray* backing_store = FixedArray::cast(obj->elements());
    bool is_arguments =
1567
        (obj->GetElementsKind() == NON_STRICT_ARGUMENTS_ELEMENTS);
1568 1569 1570
    if (is_arguments) {
      backing_store = FixedArray::cast(backing_store->get(1));
    }
1571 1572
    SeededNumberDictionary* dictionary =
        SeededNumberDictionary::cast(backing_store);
1573
    int entry = dictionary->FindEntry(key);
1574
    if (entry != SeededNumberDictionary::kNotFound) {
1575
      Object* result = dictionary->DeleteProperty(entry, mode);
1576 1577 1578 1579
      if (result == heap->false_value()) {
        if (mode == JSObject::STRICT_DELETION) {
          // Deleting a non-configurable property in strict mode.
          HandleScope scope(isolate);
1580
          Handle<Object> holder(obj, isolate);
1581 1582 1583 1584 1585 1586
          Handle<Object> name = isolate->factory()->NewNumberFromUint(key);
          Handle<Object> args[2] = { name, holder };
          Handle<Object> error =
              isolate->factory()->NewTypeError("strict_delete_property",
                                               HandleVector(args, 2));
          return isolate->Throw(*error);
1587
        }
1588
        return heap->false_value();
1589
      }
1590 1591 1592 1593 1594 1595 1596 1597 1598
      MaybeObject* maybe_elements = dictionary->Shrink(key);
      FixedArray* new_elements = NULL;
      if (!maybe_elements->To(&new_elements)) {
        return maybe_elements;
      }
      if (is_arguments) {
        FixedArray::cast(obj->elements())->set(1, new_elements);
      } else {
        obj->set_elements(new_elements);
1599 1600 1601 1602 1603
      }
    }
    return heap->true_value();
  }

1604 1605 1606
  MUST_USE_RESULT static MaybeObject* CopyElementsImpl(FixedArrayBase* from,
                                                       uint32_t from_start,
                                                       FixedArrayBase* to,
1607
                                                       ElementsKind from_kind,
1608
                                                       uint32_t to_start,
1609
                                                       int packed_size,
1610
                                                       int copy_size) {
1611 1612
    UNREACHABLE();
    return NULL;
1613 1614 1615
  }


1616 1617
 protected:
  friend class ElementsAccessorBase<DictionaryElementsAccessor,
1618
                                    ElementsKindTraits<DICTIONARY_ELEMENTS> >;
1619

1620 1621 1622
  MUST_USE_RESULT virtual MaybeObject* Delete(JSObject* obj,
                                              uint32_t key,
                                              JSReceiver::DeleteMode mode) {
1623
    return DeleteCommon(obj, key, mode);
1624 1625
  }

1626 1627 1628 1629
  MUST_USE_RESULT static MaybeObject* GetImpl(
      Object* receiver,
      JSObject* obj,
      uint32_t key,
1630 1631
      FixedArrayBase* store) {
    SeededNumberDictionary* backing_store = SeededNumberDictionary::cast(store);
1632
    int entry = backing_store->FindEntry(key);
1633
    if (entry != SeededNumberDictionary::kNotFound) {
1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645
      Object* element = backing_store->ValueAt(entry);
      PropertyDetails details = backing_store->DetailsAt(entry);
      if (details.type() == CALLBACKS) {
        return obj->GetElementWithCallback(receiver,
                                           element,
                                           key,
                                           obj);
      } else {
        return element;
      }
    }
    return obj->GetHeap()->the_hole_value();
1646
  }
1647

1648 1649 1650 1651
  MUST_USE_RESULT static PropertyAttributes GetAttributesImpl(
      Object* receiver,
      JSObject* obj,
      uint32_t key,
1652 1653 1654 1655
      FixedArrayBase* backing_store) {
    SeededNumberDictionary* dictionary =
        SeededNumberDictionary::cast(backing_store);
    int entry = dictionary->FindEntry(key);
1656
    if (entry != SeededNumberDictionary::kNotFound) {
1657
      return dictionary->DetailsAt(entry).attributes();
1658 1659 1660 1661
    }
    return ABSENT;
  }

1662 1663 1664 1665
  MUST_USE_RESULT static PropertyType GetTypeImpl(
      Object* receiver,
      JSObject* obj,
      uint32_t key,
1666 1667
      FixedArrayBase* store) {
    SeededNumberDictionary* backing_store = SeededNumberDictionary::cast(store);
1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678
    int entry = backing_store->FindEntry(key);
    if (entry != SeededNumberDictionary::kNotFound) {
      return backing_store->DetailsAt(entry).type();
    }
    return NONEXISTENT;
  }

  MUST_USE_RESULT static AccessorPair* GetAccessorPairImpl(
      Object* receiver,
      JSObject* obj,
      uint32_t key,
1679 1680
      FixedArrayBase* store) {
    SeededNumberDictionary* backing_store = SeededNumberDictionary::cast(store);
1681 1682 1683 1684 1685 1686 1687 1688 1689
    int entry = backing_store->FindEntry(key);
    if (entry != SeededNumberDictionary::kNotFound &&
        backing_store->DetailsAt(entry).type() == CALLBACKS &&
        backing_store->ValueAt(entry)->IsAccessorPair()) {
      return AccessorPair::cast(backing_store->ValueAt(entry));
    }
    return NULL;
  }

1690
  static bool HasElementImpl(Object* receiver,
1691
                             JSObject* holder,
1692
                             uint32_t key,
1693 1694
                             FixedArrayBase* backing_store) {
    return SeededNumberDictionary::cast(backing_store)->FindEntry(key) !=
1695 1696 1697
        SeededNumberDictionary::kNotFound;
  }

1698
  static uint32_t GetKeyForIndexImpl(FixedArrayBase* store,
1699
                                     uint32_t index) {
1700
    SeededNumberDictionary* dict = SeededNumberDictionary::cast(store);
1701 1702
    Object* key = dict->KeyAt(index);
    return Smi::cast(key)->value();
1703
  }
1704 1705 1706
};


1707 1708 1709
class NonStrictArgumentsElementsAccessor : public ElementsAccessorBase<
    NonStrictArgumentsElementsAccessor,
    ElementsKindTraits<NON_STRICT_ARGUMENTS_ELEMENTS> > {
1710 1711
 public:
  explicit NonStrictArgumentsElementsAccessor(const char* name)
1712 1713 1714
      : ElementsAccessorBase<
          NonStrictArgumentsElementsAccessor,
          ElementsKindTraits<NON_STRICT_ARGUMENTS_ELEMENTS> >(name) {}
1715
 protected:
1716 1717 1718
  friend class ElementsAccessorBase<
      NonStrictArgumentsElementsAccessor,
      ElementsKindTraits<NON_STRICT_ARGUMENTS_ELEMENTS> >;
1719

1720 1721 1722
  MUST_USE_RESULT static MaybeObject* GetImpl(Object* receiver,
                                              JSObject* obj,
                                              uint32_t key,
1723 1724
                                              FixedArrayBase* parameters) {
    FixedArray* parameter_map = FixedArray::cast(parameters);
1725
    Object* probe = GetParameterMapArg(obj, parameter_map, key);
1726
    if (!probe->IsTheHole()) {
1727 1728 1729 1730 1731 1732 1733
      Context* context = Context::cast(parameter_map->get(0));
      int context_index = Smi::cast(probe)->value();
      ASSERT(!context->get(context_index)->IsTheHole());
      return context->get(context_index);
    } else {
      // Object is not mapped, defer to the arguments.
      FixedArray* arguments = FixedArray::cast(parameter_map->get(1));
1734
      MaybeObject* maybe_result = ElementsAccessor::ForArray(arguments)->Get(
1735
          receiver, obj, key, arguments);
1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747
      Object* result;
      if (!maybe_result->ToObject(&result)) return maybe_result;
      // Elements of the arguments object in slow mode might be slow aliases.
      if (result->IsAliasedArgumentsEntry()) {
        AliasedArgumentsEntry* entry = AliasedArgumentsEntry::cast(result);
        Context* context = Context::cast(parameter_map->get(0));
        int context_index = entry->aliased_context_slot();
        ASSERT(!context->get(context_index)->IsTheHole());
        return context->get(context_index);
      } else {
        return result;
      }
1748 1749
    }
  }
1750

1751 1752 1753 1754
  MUST_USE_RESULT static PropertyAttributes GetAttributesImpl(
      Object* receiver,
      JSObject* obj,
      uint32_t key,
1755 1756
      FixedArrayBase* backing_store) {
    FixedArray* parameter_map = FixedArray::cast(backing_store);
1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767
    Object* probe = GetParameterMapArg(obj, parameter_map, key);
    if (!probe->IsTheHole()) {
      return NONE;
    } else {
      // If not aliased, check the arguments.
      FixedArray* arguments = FixedArray::cast(parameter_map->get(1));
      return ElementsAccessor::ForArray(arguments)->GetAttributes(
          receiver, obj, key, arguments);
    }
  }

1768 1769 1770 1771
  MUST_USE_RESULT static PropertyType GetTypeImpl(
      Object* receiver,
      JSObject* obj,
      uint32_t key,
1772 1773
      FixedArrayBase* parameters) {
    FixedArray* parameter_map = FixedArray::cast(parameters);
1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788
    Object* probe = GetParameterMapArg(obj, parameter_map, key);
    if (!probe->IsTheHole()) {
      return FIELD;
    } else {
      // If not aliased, check the arguments.
      FixedArray* arguments = FixedArray::cast(parameter_map->get(1));
      return ElementsAccessor::ForArray(arguments)->GetType(
          receiver, obj, key, arguments);
    }
  }

  MUST_USE_RESULT static AccessorPair* GetAccessorPairImpl(
      Object* receiver,
      JSObject* obj,
      uint32_t key,
1789 1790
      FixedArrayBase* parameters) {
    FixedArray* parameter_map = FixedArray::cast(parameters);
1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801
    Object* probe = GetParameterMapArg(obj, parameter_map, key);
    if (!probe->IsTheHole()) {
      return NULL;
    } else {
      // If not aliased, check the arguments.
      FixedArray* arguments = FixedArray::cast(parameter_map->get(1));
      return ElementsAccessor::ForArray(arguments)->GetAccessorPair(
          receiver, obj, key, arguments);
    }
  }

1802 1803 1804
  MUST_USE_RESULT static MaybeObject* SetLengthImpl(
      JSObject* obj,
      Object* length,
1805
      FixedArrayBase* parameter_map) {
1806 1807 1808 1809 1810 1811
    // TODO(mstarzinger): This was never implemented but will be used once we
    // correctly implement [[DefineOwnProperty]] on arrays.
    UNIMPLEMENTED();
    return obj;
  }

1812 1813 1814
  MUST_USE_RESULT virtual MaybeObject* Delete(JSObject* obj,
                                              uint32_t key,
                                              JSReceiver::DeleteMode mode) {
1815
    FixedArray* parameter_map = FixedArray::cast(obj->elements());
1816
    Object* probe = GetParameterMapArg(obj, parameter_map, key);
1817
    if (!probe->IsTheHole()) {
1818 1819 1820
      // TODO(kmillikin): We could check if this was the last aliased
      // parameter, and revert to normal elements in that case.  That
      // would enable GC of the context.
1821
      parameter_map->set_the_hole(key + 2);
1822 1823 1824
    } else {
      FixedArray* arguments = FixedArray::cast(parameter_map->get(1));
      if (arguments->IsDictionary()) {
1825
        return DictionaryElementsAccessor::DeleteCommon(obj, key, mode);
1826
      } else {
1827 1828 1829 1830
        // It's difficult to access the version of DeleteCommon that is declared
        // in the templatized super class, call the concrete implementation in
        // the class for the most generalized ElementsKind subclass.
        return FastHoleyObjectElementsAccessor::DeleteCommon(obj, key, mode);
1831 1832 1833 1834
      }
    }
    return obj->GetHeap()->true_value();
  }
1835

1836 1837 1838
  MUST_USE_RESULT static MaybeObject* CopyElementsImpl(FixedArrayBase* from,
                                                       uint32_t from_start,
                                                       FixedArrayBase* to,
1839
                                                       ElementsKind from_kind,
1840
                                                       uint32_t to_start,
1841
                                                       int packed_size,
1842
                                                       int copy_size) {
1843 1844
    UNREACHABLE();
    return NULL;
1845 1846
  }

1847 1848
  static uint32_t GetCapacityImpl(FixedArrayBase* backing_store) {
    FixedArray* parameter_map = FixedArray::cast(backing_store);
1849 1850 1851
    FixedArrayBase* arguments = FixedArrayBase::cast(parameter_map->get(1));
    return Max(static_cast<uint32_t>(parameter_map->length() - 2),
               ForArray(arguments)->GetCapacity(arguments));
1852 1853
  }

1854
  static uint32_t GetKeyForIndexImpl(FixedArrayBase* dict,
1855
                                     uint32_t index) {
1856 1857 1858
    return index;
  }

1859
  static bool HasElementImpl(Object* receiver,
1860
                             JSObject* holder,
1861
                             uint32_t key,
1862 1863
                             FixedArrayBase* parameters) {
    FixedArray* parameter_map = FixedArray::cast(parameters);
1864
    Object* probe = GetParameterMapArg(holder, parameter_map, key);
1865 1866 1867
    if (!probe->IsTheHole()) {
      return true;
    } else {
1868 1869
      FixedArrayBase* arguments =
          FixedArrayBase::cast(FixedArray::cast(parameter_map)->get(1));
1870
      ElementsAccessor* accessor = ElementsAccessor::ForArray(arguments);
1871
      return !accessor->Get(receiver, holder, key, arguments)->IsTheHole();
1872 1873 1874 1875
    }
  }

 private:
1876 1877
  static Object* GetParameterMapArg(JSObject* holder,
                                    FixedArray* parameter_map,
1878
                                    uint32_t key) {
1879 1880 1881
    uint32_t length = holder->IsJSArray()
        ? Smi::cast(JSArray::cast(holder)->length())->value()
        : parameter_map->length();
1882
    return key < (length - 2)
1883 1884
        ? parameter_map->get(key + 2)
        : parameter_map->GetHeap()->the_hole_value();
1885
  }
1886 1887 1888
};


1889
ElementsAccessor* ElementsAccessor::ForArray(FixedArrayBase* array) {
1890
  return elements_accessors_[ElementsKindForArray(array)];
1891 1892 1893
}


1894 1895
void ElementsAccessor::InitializeOncePerProcess() {
  static ElementsAccessor* accessor_array[] = {
1896
#define ACCESSOR_ARRAY(Class, Kind, Store) new Class(#Kind),
1897 1898
    ELEMENTS_LIST(ACCESSOR_ARRAY)
#undef ACCESSOR_ARRAY
1899 1900
  };

1901 1902 1903
  STATIC_ASSERT((sizeof(accessor_array) / sizeof(*accessor_array)) ==
                kElementsKindCount);

1904 1905 1906 1907
  elements_accessors_ = accessor_array;
}


1908 1909 1910 1911 1912 1913 1914 1915
void ElementsAccessor::TearDown() {
#define ACCESSOR_DELETE(Class, Kind, Store) delete elements_accessors_[Kind];
  ELEMENTS_LIST(ACCESSOR_DELETE)
#undef ACCESSOR_DELETE
  elements_accessors_ = NULL;
}


1916
template <typename ElementsAccessorSubclass, typename ElementsKindTraits>
1917 1918
MUST_USE_RESULT MaybeObject* ElementsAccessorBase<ElementsAccessorSubclass,
                                                  ElementsKindTraits>::
1919 1920
    SetLengthImpl(JSObject* obj,
                  Object* length,
1921
                  FixedArrayBase* backing_store) {
1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948
  JSArray* array = JSArray::cast(obj);

  // Fast case: The new length fits into a Smi.
  MaybeObject* maybe_smi_length = length->ToSmi();
  Object* smi_length = Smi::FromInt(0);
  if (maybe_smi_length->ToObject(&smi_length) && smi_length->IsSmi()) {
    const int value = Smi::cast(smi_length)->value();
    if (value >= 0) {
      Object* new_length;
      MaybeObject* result = ElementsAccessorSubclass::
          SetLengthWithoutNormalize(backing_store, array, smi_length, value);
      if (!result->ToObject(&new_length)) return result;
      ASSERT(new_length->IsSmi() || new_length->IsUndefined());
      if (new_length->IsSmi()) {
        array->set_length(Smi::cast(new_length));
        return array;
      }
    } else {
      return ThrowArrayLengthRangeError(array->GetHeap());
    }
  }

  // Slow case: The new length does not fit into a Smi or conversion
  // to slow elements is needed for other reasons.
  if (length->IsNumber()) {
    uint32_t value;
    if (length->ToArrayIndex(&value)) {
1949
      SeededNumberDictionary* dictionary;
1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969
      MaybeObject* maybe_object = array->NormalizeElements();
      if (!maybe_object->To(&dictionary)) return maybe_object;
      Object* new_length;
      MaybeObject* result = DictionaryElementsAccessor::
          SetLengthWithoutNormalize(dictionary, array, length, value);
      if (!result->ToObject(&new_length)) return result;
      ASSERT(new_length->IsNumber());
      array->set_length(new_length);
      return array;
    } else {
      return ThrowArrayLengthRangeError(array->GetHeap());
    }
  }

  // Fall-back case: The new length is not a number so make the array
  // size one and set only element to length.
  FixedArray* new_backing_store;
  MaybeObject* maybe_obj = array->GetHeap()->AllocateFixedArray(1);
  if (!maybe_obj->To(&new_backing_store)) return maybe_obj;
  new_backing_store->set(0, length);
1970 1971 1972
  { MaybeObject* result = array->SetContent(new_backing_store);
    if (result->IsFailure()) return result;
  }
1973 1974 1975 1976
  return array;
}


1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072
MUST_USE_RESULT MaybeObject* ArrayConstructInitializeElements(
    JSArray* array, Arguments* args) {
  Heap* heap = array->GetIsolate()->heap();

  // Optimize the case where there is one argument and the argument is a
  // small smi.
  if (args->length() == 1) {
    Object* obj = (*args)[0];
    if (obj->IsSmi()) {
      int len = Smi::cast(obj)->value();
      if (len > 0 && len < JSObject::kInitialMaxFastElementArray) {
        ElementsKind elements_kind = array->GetElementsKind();
        MaybeObject* maybe_array = array->Initialize(len, len);
        if (maybe_array->IsFailure()) return maybe_array;

        if (!IsFastHoleyElementsKind(elements_kind)) {
          elements_kind = GetHoleyElementsKind(elements_kind);
          maybe_array = array->TransitionElementsKind(elements_kind);
          if (maybe_array->IsFailure()) return maybe_array;
        }

        return array;
      } else if (len == 0) {
        return array->Initialize(JSArray::kPreallocatedArrayElements);
      }
    }

    // Take the argument as the length.
    MaybeObject* maybe_obj = array->Initialize(0);
    if (!maybe_obj->To(&obj)) return maybe_obj;

    return array->SetElementsLength((*args)[0]);
  }

  // Optimize the case where there are no parameters passed.
  if (args->length() == 0) {
    return array->Initialize(JSArray::kPreallocatedArrayElements);
  }

  // Set length and elements on the array.
  int number_of_elements = args->length();
  MaybeObject* maybe_object =
      array->EnsureCanContainElements(args, 0, number_of_elements,
                                      ALLOW_CONVERTED_DOUBLE_ELEMENTS);
  if (maybe_object->IsFailure()) return maybe_object;

  // Allocate an appropriately typed elements array.
  MaybeObject* maybe_elms;
  ElementsKind elements_kind = array->GetElementsKind();
  if (IsFastDoubleElementsKind(elements_kind)) {
    maybe_elms = heap->AllocateUninitializedFixedDoubleArray(
        number_of_elements);
  } else {
    maybe_elms = heap->AllocateFixedArrayWithHoles(number_of_elements);
  }
  FixedArrayBase* elms;
  if (!maybe_elms->To(&elms)) return maybe_elms;

  // Fill in the content
  switch (array->GetElementsKind()) {
    case FAST_HOLEY_SMI_ELEMENTS:
    case FAST_SMI_ELEMENTS: {
      FixedArray* smi_elms = FixedArray::cast(elms);
      for (int index = 0; index < number_of_elements; index++) {
        smi_elms->set(index, (*args)[index], SKIP_WRITE_BARRIER);
      }
      break;
    }
    case FAST_HOLEY_ELEMENTS:
    case FAST_ELEMENTS: {
      AssertNoAllocation no_gc;
      WriteBarrierMode mode = elms->GetWriteBarrierMode(no_gc);
      FixedArray* object_elms = FixedArray::cast(elms);
      for (int index = 0; index < number_of_elements; index++) {
        object_elms->set(index, (*args)[index], mode);
      }
      break;
    }
    case FAST_HOLEY_DOUBLE_ELEMENTS:
    case FAST_DOUBLE_ELEMENTS: {
      FixedDoubleArray* double_elms = FixedDoubleArray::cast(elms);
      for (int index = 0; index < number_of_elements; index++) {
        double_elms->set(index, (*args)[index]->Number());
      }
      break;
    }
    default:
      UNREACHABLE();
      break;
  }

  array->set_elements(elms);
  array->set_length(Smi::FromInt(number_of_elements));
  return array;
}

2073
} }  // namespace v8::internal