elements.cc 174 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
2 3
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
4

5
#include "src/elements.h"
6

7 8
#include "src/arguments.h"
#include "src/conversions.h"
9
#include "src/factory.h"
10
#include "src/isolate-inl.h"
11
#include "src/messages.h"
12
#include "src/objects-inl.h"
13
#include "src/utils.h"
14 15 16 17 18 19 20 21

// 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)
22 23 24 25 26
//     - FastSmiOrObjectElementsAccessor
//       - FastPackedSmiElementsAccessor
//       - FastHoleySmiElementsAccessor
//       - FastPackedObjectElementsAccessor
//       - FastHoleyObjectElementsAccessor
27
//     - FastDoubleElementsAccessor
28 29
//       - FastPackedDoubleElementsAccessor
//       - FastHoleyDoubleElementsAccessor
30 31 32 33 34 35 36 37 38 39
//   - TypedElementsAccessor: template, with instantiations:
//     - FixedUint8ElementsAccessor
//     - FixedInt8ElementsAccessor
//     - FixedUint16ElementsAccessor
//     - FixedInt16ElementsAccessor
//     - FixedUint32ElementsAccessor
//     - FixedInt32ElementsAccessor
//     - FixedFloat32ElementsAccessor
//     - FixedFloat64ElementsAccessor
//     - FixedUint8ClampedElementsAccessor
40
//   - DictionaryElementsAccessor
41
//   - SloppyArgumentsElementsAccessor
42 43
//     - FastSloppyArgumentsElementsAccessor
//     - SlowSloppyArgumentsElementsAccessor
44 45 46
//   - StringWrapperElementsAccessor
//     - FastStringWrapperElementsAccessor
//     - SlowStringWrapperElementsAccessor
47

48 49 50 51
namespace v8 {
namespace internal {


52 53 54
namespace {


55 56
static const int kPackedSizeNotKnown = -1;

cbruni's avatar
cbruni committed
57 58
enum Where { AT_START, AT_END };

59

60 61 62 63 64
// 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.
65 66 67 68 69 70 71 72 73 74 75 76 77
#define ELEMENTS_LIST(V)                                                      \
  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)                                                         \
  V(DictionaryElementsAccessor, DICTIONARY_ELEMENTS, SeededNumberDictionary)  \
  V(FastSloppyArgumentsElementsAccessor, FAST_SLOPPY_ARGUMENTS_ELEMENTS,      \
    FixedArray)                                                               \
  V(SlowSloppyArgumentsElementsAccessor, SLOW_SLOPPY_ARGUMENTS_ELEMENTS,      \
    FixedArray)                                                               \
78 79 80 81
  V(FastStringWrapperElementsAccessor, FAST_STRING_WRAPPER_ELEMENTS,          \
    FixedArray)                                                               \
  V(SlowStringWrapperElementsAccessor, SLOW_STRING_WRAPPER_ELEMENTS,          \
    FixedArray)                                                               \
82 83 84 85 86 87 88 89 90
  V(FixedUint8ElementsAccessor, UINT8_ELEMENTS, FixedUint8Array)              \
  V(FixedInt8ElementsAccessor, INT8_ELEMENTS, FixedInt8Array)                 \
  V(FixedUint16ElementsAccessor, UINT16_ELEMENTS, FixedUint16Array)           \
  V(FixedInt16ElementsAccessor, INT16_ELEMENTS, FixedInt16Array)              \
  V(FixedUint32ElementsAccessor, UINT32_ELEMENTS, FixedUint32Array)           \
  V(FixedInt32ElementsAccessor, INT32_ELEMENTS, FixedInt32Array)              \
  V(FixedFloat32ElementsAccessor, FLOAT32_ELEMENTS, FixedFloat32Array)        \
  V(FixedFloat64ElementsAccessor, FLOAT64_ELEMENTS, FixedFloat64Array)        \
  V(FixedUint8ClampedElementsAccessor, UINT8_CLAMPED_ELEMENTS,                \
91
    FixedUint8ClampedArray)
92 93 94 95 96 97 98 99

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

#define ELEMENTS_TRAITS(Class, KindParam, Store)               \
template<> class ElementsKindTraits<KindParam> {               \
100
 public:   /* NOLINT */                                        \
101 102 103 104 105 106 107
  static const ElementsKind Kind = KindParam;                  \
  typedef Store BackingStore;                                  \
};
ELEMENTS_LIST(ELEMENTS_TRAITS)
#undef ELEMENTS_TRAITS


108
MUST_USE_RESULT
109
MaybeHandle<Object> ThrowArrayLengthRangeError(Isolate* isolate) {
110
  THROW_NEW_ERROR(isolate, NewRangeError(MessageTemplate::kInvalidArrayLength),
111
                  Object);
112 113
}

114

115 116 117 118
void CopyObjectToObjectElements(FixedArrayBase* from_base,
                                ElementsKind from_kind, uint32_t from_start,
                                FixedArrayBase* to_base, ElementsKind to_kind,
                                uint32_t to_start, int raw_copy_size) {
119
  DCHECK(to_base->map() !=
120
      from_base->GetIsolate()->heap()->fixed_cow_array_map());
121
  DisallowHeapAllocation no_allocation;
122 123
  int copy_size = raw_copy_size;
  if (raw_copy_size < 0) {
124
    DCHECK(raw_copy_size == ElementsAccessor::kCopyToEnd ||
125
           raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole);
126 127
    copy_size = Min(from_base->length() - from_start,
                    to_base->length() - to_start);
128
    if (raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole) {
129
      int start = to_start + copy_size;
130
      int length = to_base->length() - start;
131
      if (length > 0) {
132
        Heap* heap = from_base->GetHeap();
133
        MemsetPointer(FixedArray::cast(to_base)->data_start() + start,
134
                      heap->the_hole_value(), length);
135 136
      }
    }
137
  }
138
  DCHECK((copy_size + static_cast<int>(to_start)) <= to_base->length() &&
139
         (copy_size + static_cast<int>(from_start)) <= from_base->length());
140
  if (copy_size == 0) return;
141 142
  FixedArray* from = FixedArray::cast(from_base);
  FixedArray* to = FixedArray::cast(to_base);
143
  DCHECK(IsFastSmiOrObjectElementsKind(from_kind));
144
  DCHECK(IsFastSmiOrObjectElementsKind(to_kind));
145 146

  WriteBarrierMode write_barrier_mode =
147
      (IsFastObjectElementsKind(from_kind) && IsFastObjectElementsKind(to_kind))
148 149 150 151 152
          ? UPDATE_WRITE_BARRIER
          : SKIP_WRITE_BARRIER;
  for (int i = 0; i < copy_size; i++) {
    Object* value = from->get(from_start + i);
    to->set(to_start + i, value, write_barrier_mode);
153 154 155 156
  }
}


157 158 159
static void CopyDictionaryToObjectElements(
    FixedArrayBase* from_base, uint32_t from_start, FixedArrayBase* to_base,
    ElementsKind to_kind, uint32_t to_start, int raw_copy_size) {
160
  DisallowHeapAllocation no_allocation;
161
  SeededNumberDictionary* from = SeededNumberDictionary::cast(from_base);
162 163
  int copy_size = raw_copy_size;
  if (raw_copy_size < 0) {
164
    DCHECK(raw_copy_size == ElementsAccessor::kCopyToEnd ||
165 166 167
           raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole);
    copy_size = from->max_number_key() + 1 - from_start;
    if (raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole) {
168
      int start = to_start + copy_size;
169
      int length = to_base->length() - start;
170 171
      if (length > 0) {
        Heap* heap = from->GetHeap();
172
        MemsetPointer(FixedArray::cast(to_base)->data_start() + start,
173
                      heap->the_hole_value(), length);
174 175 176
      }
    }
  }
177 178
  DCHECK(to_base != from_base);
  DCHECK(IsFastSmiOrObjectElementsKind(to_kind));
179
  if (copy_size == 0) return;
180
  FixedArray* to = FixedArray::cast(to_base);
181 182 183 184
  uint32_t to_length = to->length();
  if (to_start + copy_size > to_length) {
    copy_size = to_length - to_start;
  }
185 186 187
  WriteBarrierMode write_barrier_mode = IsFastObjectElementsKind(to_kind)
                                            ? UPDATE_WRITE_BARRIER
                                            : SKIP_WRITE_BARRIER;
188
  Isolate* isolate = from->GetIsolate();
189
  for (int i = 0; i < copy_size; i++) {
190
    int entry = from->FindEntry(isolate, i + from_start);
191 192
    if (entry != SeededNumberDictionary::kNotFound) {
      Object* value = from->ValueAt(entry);
193
      DCHECK(!value->IsTheHole(isolate));
194
      to->set(i + to_start, value, write_barrier_mode);
195
    } else {
196
      to->set_the_hole(isolate, i + to_start);
197 198
    }
  }
199 200 201
}


202 203 204 205
// NOTE: this method violates the handlified function signature convention:
// raw pointer parameters in the function that allocates.
// See ElementsAccessorBase::CopyElements() for details.
static void CopyDoubleToObjectElements(FixedArrayBase* from_base,
206
                                       uint32_t from_start,
207
                                       FixedArrayBase* to_base,
208
                                       uint32_t to_start, int raw_copy_size) {
209 210
  int copy_size = raw_copy_size;
  if (raw_copy_size < 0) {
211
    DisallowHeapAllocation no_allocation;
212
    DCHECK(raw_copy_size == ElementsAccessor::kCopyToEnd ||
213
           raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole);
214 215
    copy_size = Min(from_base->length() - from_start,
                    to_base->length() - to_start);
216
    if (raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole) {
217 218 219 220
      // 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;
221
      int length = to_base->length() - start;
222
      if (length > 0) {
223
        Heap* heap = from_base->GetHeap();
224
        MemsetPointer(FixedArray::cast(to_base)->data_start() + start,
225
                      heap->the_hole_value(), length);
226 227
      }
    }
228
  }
229

230
  DCHECK((copy_size + static_cast<int>(to_start)) <= to_base->length() &&
231
         (copy_size + static_cast<int>(from_start)) <= from_base->length());
232
  if (copy_size == 0) return;
233 234 235

  // From here on, the code below could actually allocate. Therefore the raw
  // values are wrapped into handles.
236
  Isolate* isolate = from_base->GetIsolate();
237 238
  Handle<FixedDoubleArray> from(FixedDoubleArray::cast(from_base), isolate);
  Handle<FixedArray> to(FixedArray::cast(to_base), isolate);
239

240 241 242
  // Use an outer loop to not waste too much time on creating HandleScopes.
  // On the other hand we might overflow a single handle scope depending on
  // the copy_size.
243 244
  int offset = 0;
  while (offset < copy_size) {
245
    HandleScope scope(isolate);
246 247
    offset += 100;
    for (int i = offset - 100; i < offset && i < copy_size; ++i) {
248 249
      Handle<Object> value =
          FixedDoubleArray::get(*from, i + from_start, isolate);
250
      to->set(i + to_start, *value, UPDATE_WRITE_BARRIER);
251 252 253 254 255
    }
  }
}


256
static void CopyDoubleToDoubleElements(FixedArrayBase* from_base,
257
                                       uint32_t from_start,
258 259
                                       FixedArrayBase* to_base,
                                       uint32_t to_start, int raw_copy_size) {
260
  DisallowHeapAllocation no_allocation;
261 262
  int copy_size = raw_copy_size;
  if (raw_copy_size < 0) {
263
    DCHECK(raw_copy_size == ElementsAccessor::kCopyToEnd ||
264
           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
      for (int i = to_start + copy_size; i < to_base->length(); ++i) {
269
        FixedDoubleArray::cast(to_base)->set_the_hole(i);
270 271
      }
    }
272
  }
273
  DCHECK((copy_size + static_cast<int>(to_start)) <= to_base->length() &&
274
         (copy_size + static_cast<int>(from_start)) <= from_base->length());
275
  if (copy_size == 0) return;
276 277
  FixedDoubleArray* from = FixedDoubleArray::cast(from_base);
  FixedDoubleArray* to = FixedDoubleArray::cast(to_base);
278 279 280 281
  Address to_address = to->address() + FixedDoubleArray::kHeaderSize;
  Address from_address = from->address() + FixedDoubleArray::kHeaderSize;
  to_address += kDoubleSize * to_start;
  from_address += kDoubleSize * from_start;
282
  int words_per_double = (kDoubleSize / kPointerSize);
283 284
  CopyWords(reinterpret_cast<Object**>(to_address),
            reinterpret_cast<Object**>(from_address),
285
            static_cast<size_t>(words_per_double * copy_size));
286 287 288
}


289
static void CopySmiToDoubleElements(FixedArrayBase* from_base,
290
                                    uint32_t from_start,
291
                                    FixedArrayBase* to_base, uint32_t to_start,
292
                                    int raw_copy_size) {
293
  DisallowHeapAllocation no_allocation;
294 295
  int copy_size = raw_copy_size;
  if (raw_copy_size < 0) {
296
    DCHECK(raw_copy_size == ElementsAccessor::kCopyToEnd ||
297
           raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole);
298
    copy_size = from_base->length() - from_start;
299
    if (raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole) {
300
      for (int i = to_start + copy_size; i < to_base->length(); ++i) {
301
        FixedDoubleArray::cast(to_base)->set_the_hole(i);
302 303 304
      }
    }
  }
305
  DCHECK((copy_size + static_cast<int>(to_start)) <= to_base->length() &&
306
         (copy_size + static_cast<int>(from_start)) <= from_base->length());
307
  if (copy_size == 0) return;
308 309 310
  FixedArray* from = FixedArray::cast(from_base);
  FixedDoubleArray* to = FixedDoubleArray::cast(to_base);
  Object* the_hole = from->GetHeap()->the_hole_value();
311 312 313
  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);
314
    if (hole_or_smi == the_hole) {
315 316 317 318 319 320 321 322
      to->set_the_hole(to_start);
    } else {
      to->set(to_start, Smi::cast(hole_or_smi)->value());
    }
  }
}


323
static void CopyPackedSmiToDoubleElements(FixedArrayBase* from_base,
324
                                          uint32_t from_start,
325 326
                                          FixedArrayBase* to_base,
                                          uint32_t to_start, int packed_size,
327
                                          int raw_copy_size) {
328
  DisallowHeapAllocation no_allocation;
329 330 331
  int copy_size = raw_copy_size;
  uint32_t to_end;
  if (raw_copy_size < 0) {
332
    DCHECK(raw_copy_size == ElementsAccessor::kCopyToEnd ||
333
           raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole);
334
    copy_size = packed_size - from_start;
335
    if (raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole) {
336
      to_end = to_base->length();
337
      for (uint32_t i = to_start + copy_size; i < to_end; ++i) {
338
        FixedDoubleArray::cast(to_base)->set_the_hole(i);
339
      }
340 341 342 343 344 345
    } else {
      to_end = to_start + static_cast<uint32_t>(copy_size);
    }
  } else {
    to_end = to_start + static_cast<uint32_t>(copy_size);
  }
346 347 348
  DCHECK(static_cast<int>(to_end) <= to_base->length());
  DCHECK(packed_size >= 0 && packed_size <= copy_size);
  DCHECK((copy_size + static_cast<int>(to_start)) <= to_base->length() &&
349
         (copy_size + static_cast<int>(from_start)) <= from_base->length());
350
  if (copy_size == 0) return;
351 352
  FixedArray* from = FixedArray::cast(from_base);
  FixedDoubleArray* to = FixedDoubleArray::cast(to_base);
353 354 355
  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);
356
    DCHECK(!smi->IsTheHole(from->GetIsolate()));
357 358 359 360 361
    to->set(to_start, Smi::cast(smi)->value());
  }
}


362
static void CopyObjectToDoubleElements(FixedArrayBase* from_base,
363
                                       uint32_t from_start,
364 365
                                       FixedArrayBase* to_base,
                                       uint32_t to_start, int raw_copy_size) {
366
  DisallowHeapAllocation no_allocation;
367 368
  int copy_size = raw_copy_size;
  if (raw_copy_size < 0) {
369
    DCHECK(raw_copy_size == ElementsAccessor::kCopyToEnd ||
370
           raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole);
371
    copy_size = from_base->length() - from_start;
372
    if (raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole) {
373
      for (int i = to_start + copy_size; i < to_base->length(); ++i) {
374
        FixedDoubleArray::cast(to_base)->set_the_hole(i);
375 376 377
      }
    }
  }
378
  DCHECK((copy_size + static_cast<int>(to_start)) <= to_base->length() &&
379
         (copy_size + static_cast<int>(from_start)) <= from_base->length());
380
  if (copy_size == 0) return;
381 382 383
  FixedArray* from = FixedArray::cast(from_base);
  FixedDoubleArray* to = FixedDoubleArray::cast(to_base);
  Object* the_hole = from->GetHeap()->the_hole_value();
384 385 386
  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);
387
    if (hole_or_object == the_hole) {
388
      to->set_the_hole(to_start);
389
    } else {
390
      to->set(to_start, hole_or_object->Number());
391 392 393 394 395
    }
  }
}


396
static void CopyDictionaryToDoubleElements(FixedArrayBase* from_base,
397
                                           uint32_t from_start,
398
                                           FixedArrayBase* to_base,
399 400
                                           uint32_t to_start,
                                           int raw_copy_size) {
401
  DisallowHeapAllocation no_allocation;
402
  SeededNumberDictionary* from = SeededNumberDictionary::cast(from_base);
403 404
  int copy_size = raw_copy_size;
  if (copy_size < 0) {
405
    DCHECK(copy_size == ElementsAccessor::kCopyToEnd ||
406 407 408
           copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole);
    copy_size = from->max_number_key() + 1 - from_start;
    if (raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole) {
409
      for (int i = to_start + copy_size; i < to_base->length(); ++i) {
410
        FixedDoubleArray::cast(to_base)->set_the_hole(i);
411 412 413 414
      }
    }
  }
  if (copy_size == 0) return;
415
  FixedDoubleArray* to = FixedDoubleArray::cast(to_base);
416 417 418 419
  uint32_t to_length = to->length();
  if (to_start + copy_size > to_length) {
    copy_size = to_length - to_start;
  }
420
  Isolate* isolate = from->GetIsolate();
421
  for (int i = 0; i < copy_size; i++) {
422
    int entry = from->FindEntry(isolate, i + from_start);
423 424 425 426 427 428 429 430
    if (entry != SeededNumberDictionary::kNotFound) {
      to->set(i + to_start, from->ValueAt(entry)->Number());
    } else {
      to->set_the_hole(i + to_start);
    }
  }
}

431 432
static void TraceTopFrame(Isolate* isolate) {
  StackFrameIterator it(isolate);
433 434 435 436 437 438
  if (it.done()) {
    PrintF("unknown location (no JavaScript frames present)");
    return;
  }
  StackFrame* raw_frame = it.frame();
  if (raw_frame->is_internal()) {
439 440
    Code* apply_builtin =
        isolate->builtins()->builtin(Builtins::kFunctionPrototypeApply);
441 442 443 444 445 446
    if (raw_frame->unchecked_code() == apply_builtin) {
      PrintF("apply from ");
      it.Advance();
      raw_frame = it.frame();
    }
  }
447
  JavaScriptFrame::PrintTop(isolate, stdout, false, true);
448 449
}

450 451 452 453 454
static void SortIndices(
    Handle<FixedArray> indices, uint32_t sort_size,
    WriteBarrierMode write_barrier_mode = UPDATE_WRITE_BARRIER) {
  struct {
    bool operator()(Object* a, Object* b) {
455 456 457 458
      if (a->IsSmi() || !a->IsUndefined(HeapObject::cast(a)->GetIsolate())) {
        if (!b->IsSmi() && b->IsUndefined(HeapObject::cast(b)->GetIsolate())) {
          return true;
        }
459 460
        return a->Number() < b->Number();
      }
461
      return !b->IsSmi() && b->IsUndefined(HeapObject::cast(b)->GetIsolate());
462 463 464 465 466 467 468 469 470 471
    }
  } cmp;
  Object** start =
      reinterpret_cast<Object**>(indices->GetFirstElementAddress());
  std::sort(start, start + sort_size, cmp);
  if (write_barrier_mode != SKIP_WRITE_BARRIER) {
    FIXED_ARRAY_ELEMENTS_WRITE_BARRIER(indices->GetIsolate()->heap(), *indices,
                                       0, sort_size);
  }
}
472

473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
static Maybe<bool> IncludesValueSlowPath(Isolate* isolate,
                                         Handle<JSObject> receiver,
                                         Handle<Object> value,
                                         uint32_t start_from, uint32_t length) {
  bool search_for_hole = value->IsUndefined(isolate);
  for (uint32_t k = start_from; k < length; ++k) {
    LookupIterator it(isolate, receiver, k);
    if (!it.IsFound()) {
      if (search_for_hole) return Just(true);
      continue;
    }
    Handle<Object> element_k;
    ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, element_k,
                                     Object::GetProperty(&it), Nothing<bool>());

    if (value->SameValueZero(*element_k)) return Just(true);
  }

  return Just(false);
}

494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
static Maybe<int64_t> IndexOfValueSlowPath(Isolate* isolate,
                                           Handle<JSObject> receiver,
                                           Handle<Object> value,
                                           uint32_t start_from,
                                           uint32_t length) {
  for (uint32_t k = start_from; k < length; ++k) {
    LookupIterator it(isolate, receiver, k);
    if (!it.IsFound()) {
      continue;
    }
    Handle<Object> element_k;
    ASSIGN_RETURN_ON_EXCEPTION_VALUE(
        isolate, element_k, Object::GetProperty(&it), Nothing<int64_t>());

    if (value->StrictEquals(*element_k)) return Just<int64_t>(k);
  }

  return Just<int64_t>(-1);
}

514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
// 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).
531
template <typename Subclass, typename ElementsTraitsParam>
532
class ElementsAccessorBase : public ElementsAccessor {
533
 public:
534 535 536 537 538 539
  explicit ElementsAccessorBase(const char* name)
      : ElementsAccessor(name) { }

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

540
  static ElementsKind kind() { return ElementsTraits::Kind; }
541

542
  static void ValidateContents(Handle<JSObject> holder, int length) {
543 544
  }

545 546
  static void ValidateImpl(Handle<JSObject> holder) {
    Handle<FixedArrayBase> fixed_array_base(holder->elements());
547 548
    if (!fixed_array_base->IsHeapObject()) return;
    // Arrays that have been shifted in place can't be verified.
549
    if (fixed_array_base->IsFiller()) return;
550 551
    int length = 0;
    if (holder->IsJSArray()) {
552
      Object* length_obj = Handle<JSArray>::cast(holder)->length();
553 554 555 556 557 558
      if (length_obj->IsSmi()) {
        length = Smi::cast(length_obj)->value();
      }
    } else {
      length = fixed_array_base->length();
    }
559
    Subclass::ValidateContents(holder, length);
560 561
  }

562
  void Validate(Handle<JSObject> holder) final {
563
    DisallowHeapAllocation no_gc;
564
    Subclass::ValidateImpl(holder);
565 566
  }

567 568 569
  static bool IsPackedImpl(JSObject* holder, FixedArrayBase* backing_store,
                           uint32_t start, uint32_t end) {
    DisallowHeapAllocation no_gc;
570
    if (IsFastPackedElementsKind(kind())) return true;
571
    Isolate* isolate = backing_store->GetIsolate();
572
    for (uint32_t i = start; i < end; i++) {
573 574
      if (!Subclass::HasElementImpl(isolate, holder, i, backing_store,
                                    ALL_PROPERTIES)) {
575 576 577 578 579 580
        return false;
      }
    }
    return true;
  }

581 582 583
  static void TryTransitionResultArrayToPacked(Handle<JSArray> array) {
    if (!IsHoleyElementsKind(kind())) return;
    Handle<FixedArrayBase> backing_store(array->elements());
584 585
    int length = Smi::cast(array->length())->value();
    if (!Subclass::IsPackedImpl(*array, *backing_store, 0, length)) {
586 587 588 589 590 591 592 593 594 595 596 597
      return;
    }
    ElementsKind packed_kind = GetPackedElementsKind(kind());
    Handle<Map> new_map =
        JSObject::GetElementsTransitionMap(array, packed_kind);
    JSObject::MigrateToMap(array, new_map);
    if (FLAG_trace_elements_transitions) {
      JSObject::PrintElementsTransition(stdout, array, kind(), backing_store,
                                        packed_kind, backing_store);
    }
  }

598 599
  bool HasElement(JSObject* holder, uint32_t index,
                  FixedArrayBase* backing_store, PropertyFilter filter) final {
600 601
    return Subclass::HasElementImpl(holder->GetIsolate(), holder, index,
                                    backing_store, filter);
602 603
  }

604 605
  static bool HasElementImpl(Isolate* isolate, JSObject* holder, uint32_t index,
                             FixedArrayBase* backing_store,
606
                             PropertyFilter filter = ALL_PROPERTIES) {
607 608
    return Subclass::GetEntryForIndexImpl(isolate, holder, backing_store, index,
                                          filter) != kMaxUInt32;
609 610
  }

611
  bool HasAccessors(JSObject* holder) final {
612
    return Subclass::HasAccessorsImpl(holder, holder->elements());
613 614 615 616 617 618 619
  }

  static bool HasAccessorsImpl(JSObject* holder,
                               FixedArrayBase* backing_store) {
    return false;
  }

620
  Handle<Object> Get(Handle<JSObject> holder, uint32_t entry) final {
621
    return Subclass::GetInternalImpl(holder, entry);
622 623
  }

624 625 626
  static Handle<Object> GetInternalImpl(Handle<JSObject> holder,
                                        uint32_t entry) {
    return Subclass::GetImpl(holder->GetIsolate(), holder->elements(), entry);
627 628
  }

629 630
  static Handle<Object> GetImpl(Isolate* isolate, FixedArrayBase* backing_store,
                                uint32_t entry) {
631 632
    uint32_t index = GetIndexForEntryImpl(backing_store, entry);
    return handle(BackingStore::cast(backing_store)->get(index), isolate);
633 634
  }

635
  void Set(Handle<JSObject> holder, uint32_t entry, Object* value) final {
636
    Subclass::SetImpl(holder, entry, value);
637 638
  }

639 640 641
  void Reconfigure(Handle<JSObject> object, Handle<FixedArrayBase> store,
                   uint32_t entry, Handle<Object> value,
                   PropertyAttributes attributes) final {
642
    Subclass::ReconfigureImpl(object, store, entry, value, attributes);
643 644 645
  }

  static void ReconfigureImpl(Handle<JSObject> object,
646
                              Handle<FixedArrayBase> store, uint32_t entry,
647 648 649 650 651
                              Handle<Object> value,
                              PropertyAttributes attributes) {
    UNREACHABLE();
  }

652 653
  void Add(Handle<JSObject> object, uint32_t index, Handle<Object> value,
           PropertyAttributes attributes, uint32_t new_capacity) final {
654
    Subclass::AddImpl(object, index, value, attributes, new_capacity);
655 656
  }

657
  static void AddImpl(Handle<JSObject> object, uint32_t index,
658 659 660 661 662
                      Handle<Object> value, PropertyAttributes attributes,
                      uint32_t new_capacity) {
    UNREACHABLE();
  }

663 664
  uint32_t Push(Handle<JSArray> receiver, Arguments* args,
                uint32_t push_size) final {
665
    return Subclass::PushImpl(receiver, args, push_size);
666 667
  }

668
  static uint32_t PushImpl(Handle<JSArray> receiver, Arguments* args,
669
                           uint32_t push_sized) {
670 671 672
    UNREACHABLE();
  }

673
  uint32_t Unshift(Handle<JSArray> receiver, Arguments* args,
674
                   uint32_t unshift_size) final {
675
    return Subclass::UnshiftImpl(receiver, args, unshift_size);
676 677
  }

678
  static uint32_t UnshiftImpl(Handle<JSArray> receiver, Arguments* args,
679 680 681 682
                              uint32_t unshift_size) {
    UNREACHABLE();
  }

683 684
  Handle<JSObject> Slice(Handle<JSObject> receiver, uint32_t start,
                         uint32_t end) final {
685
    return Subclass::SliceImpl(receiver, start, end);
686 687
  }

688 689 690 691 692 693 694
  Handle<JSObject> Slice(Handle<JSObject> receiver, uint32_t start,
                         uint32_t end, Handle<JSObject> result) final {
    return Subclass::SliceWithResultImpl(receiver, start, end, result);
  }

  static Handle<JSObject> SliceImpl(Handle<JSObject> receiver, uint32_t start,
                                    uint32_t end) {
695
    UNREACHABLE();
696 697 698 699 700 701
  }

  static Handle<JSObject> SliceWithResultImpl(Handle<JSObject> receiver,
                                              uint32_t start, uint32_t end,
                                              Handle<JSObject> result) {
    UNREACHABLE();
702 703
  }

704
  Handle<JSArray> Splice(Handle<JSArray> receiver, uint32_t start,
705 706
                         uint32_t delete_count, Arguments* args,
                         uint32_t add_count) final {
707
    return Subclass::SpliceImpl(receiver, start, delete_count, args, add_count);
708 709 710 711
  }

  static Handle<JSArray> SpliceImpl(Handle<JSArray> receiver,
                                    uint32_t start, uint32_t delete_count,
712
                                    Arguments* args, uint32_t add_count) {
713 714 715
    UNREACHABLE();
  }

716
  Handle<Object> Pop(Handle<JSArray> receiver) final {
717
    return Subclass::PopImpl(receiver);
cbruni's avatar
cbruni committed
718 719
  }

720
  static Handle<Object> PopImpl(Handle<JSArray> receiver) {
cbruni's avatar
cbruni committed
721 722
    UNREACHABLE();
  }
723

724
  Handle<Object> Shift(Handle<JSArray> receiver) final {
725
    return Subclass::ShiftImpl(receiver);
726 727
  }

728
  static Handle<Object> ShiftImpl(Handle<JSArray> receiver) {
729 730 731
    UNREACHABLE();
  }

732
  void SetLength(Handle<JSArray> array, uint32_t length) final {
733 734
    Subclass::SetLengthImpl(array->GetIsolate(), array, length,
                            handle(array->elements()));
735 736
  }

737 738
  static void SetLengthImpl(Isolate* isolate, Handle<JSArray> array,
                            uint32_t length,
739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
                            Handle<FixedArrayBase> backing_store) {
    DCHECK(!array->SetLengthWouldNormalize(length));
    DCHECK(IsFastElementsKind(array->GetElementsKind()));
    uint32_t old_length = 0;
    CHECK(array->length()->ToArrayIndex(&old_length));

    if (old_length < length) {
      ElementsKind kind = array->GetElementsKind();
      if (!IsFastHoleyElementsKind(kind)) {
        kind = GetHoleyElementsKind(kind);
        JSObject::TransitionElementsKind(array, kind);
      }
    }

    // Check whether the backing store should be shrunk.
    uint32_t capacity = backing_store->length();
755
    old_length = Min(old_length, capacity);
756 757 758
    if (length == 0) {
      array->initialize_elements();
    } else if (length <= capacity) {
759
      if (IsFastSmiOrObjectElementsKind(kind())) {
760 761 762 763
        JSObject::EnsureWritableFastElements(array);
        if (array->elements() != *backing_store) {
          backing_store = handle(array->elements(), isolate);
        }
764
      }
765
      if (2 * length + JSObject::kMinAddedElementsCapacity <= capacity) {
766
        // If more than half the elements won't be used, trim the array.
767 768 769 770 771 772 773
        // Do not trim from short arrays to prevent frequent trimming on
        // repeated pop operations.
        // Leave some space to allow for subsequent push operations.
        int elements_to_trim = length + 1 == old_length
                                   ? (capacity - length) / 2
                                   : capacity - length;
        isolate->heap()->RightTrimFixedArray(*backing_store, elements_to_trim);
774 775
      } else {
        // Otherwise, fill the unused tail with holes.
776
        BackingStore::cast(*backing_store)->FillWithHoles(length, old_length);
777 778 779 780
      }
    } else {
      // Check whether the backing store should be expanded.
      capacity = Max(length, JSObject::NewElementsCapacity(capacity));
781
      Subclass::GrowCapacityAndConvertImpl(array, capacity);
782 783 784 785 786
    }

    array->set_length(Smi::FromInt(length));
    JSObject::ValidateElements(array);
  }
787

788 789 790 791 792 793 794 795 796
  uint32_t NumberOfElements(JSObject* receiver) final {
    return Subclass::NumberOfElementsImpl(receiver, receiver->elements());
  }

  static uint32_t NumberOfElementsImpl(JSObject* receiver,
                                       FixedArrayBase* backing_store) {
    UNREACHABLE();
  }

797
  static uint32_t GetMaxIndex(JSObject* receiver, FixedArrayBase* elements) {
798
    if (receiver->IsJSArray()) {
799
      DCHECK(JSArray::cast(receiver)->length()->IsSmi());
800 801 802
      return static_cast<uint32_t>(
          Smi::cast(JSArray::cast(receiver)->length())->value());
    }
803
    return Subclass::GetCapacityImpl(receiver, elements);
804 805
  }

806 807 808 809 810
  static uint32_t GetMaxNumberOfEntries(JSObject* receiver,
                                        FixedArrayBase* elements) {
    return Subclass::GetMaxIndex(receiver, elements);
  }

811 812 813
  static Handle<FixedArrayBase> ConvertElementsWithCapacity(
      Handle<JSObject> object, Handle<FixedArrayBase> old_elements,
      ElementsKind from_kind, uint32_t capacity) {
814
    return ConvertElementsWithCapacity(
815
        object, old_elements, from_kind, capacity, 0, 0,
816 817 818 819 820 821
        ElementsAccessor::kCopyToEndAndInitializeToHole);
  }

  static Handle<FixedArrayBase> ConvertElementsWithCapacity(
      Handle<JSObject> object, Handle<FixedArrayBase> old_elements,
      ElementsKind from_kind, uint32_t capacity, int copy_size) {
822 823 824 825 826 827 828 829
    return ConvertElementsWithCapacity(object, old_elements, from_kind,
                                       capacity, 0, 0, copy_size);
  }

  static Handle<FixedArrayBase> ConvertElementsWithCapacity(
      Handle<JSObject> object, Handle<FixedArrayBase> old_elements,
      ElementsKind from_kind, uint32_t capacity, uint32_t src_index,
      uint32_t dst_index, int copy_size) {
830
    Isolate* isolate = object->GetIsolate();
831
    Handle<FixedArrayBase> new_elements;
832
    if (IsFastDoubleElementsKind(kind())) {
833
      new_elements = isolate->factory()->NewFixedDoubleArray(capacity);
834
    } else {
835
      new_elements = isolate->factory()->NewUninitializedFixedArray(capacity);
836 837
    }

838
    int packed_size = kPackedSizeNotKnown;
839
    if (IsFastPackedElementsKind(from_kind) && object->IsJSArray()) {
840
      packed_size = Smi::cast(JSArray::cast(*object)->length())->value();
841 842
    }

843 844
    Subclass::CopyElementsImpl(*old_elements, src_index, *new_elements,
                               from_kind, dst_index, packed_size, copy_size);
845 846

    return new_elements;
847 848
  }

849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
  static void TransitionElementsKindImpl(Handle<JSObject> object,
                                         Handle<Map> to_map) {
    Handle<Map> from_map = handle(object->map());
    ElementsKind from_kind = from_map->elements_kind();
    ElementsKind to_kind = to_map->elements_kind();
    if (IsFastHoleyElementsKind(from_kind)) {
      to_kind = GetHoleyElementsKind(to_kind);
    }
    if (from_kind != to_kind) {
      // This method should never be called for any other case.
      DCHECK(IsFastElementsKind(from_kind));
      DCHECK(IsFastElementsKind(to_kind));
      DCHECK_NE(TERMINAL_FAST_ELEMENTS_KIND, from_kind);

      Handle<FixedArrayBase> from_elements(object->elements());
      if (object->elements() == object->GetHeap()->empty_fixed_array() ||
          IsFastDoubleElementsKind(from_kind) ==
              IsFastDoubleElementsKind(to_kind)) {
        // No change is needed to the elements() buffer, the transition
        // only requires a map change.
        JSObject::MigrateToMap(object, to_map);
      } else {
        DCHECK((IsFastSmiElementsKind(from_kind) &&
                IsFastDoubleElementsKind(to_kind)) ||
               (IsFastDoubleElementsKind(from_kind) &&
                IsFastObjectElementsKind(to_kind)));
        uint32_t capacity = static_cast<uint32_t>(object->elements()->length());
        Handle<FixedArrayBase> elements = ConvertElementsWithCapacity(
            object, from_elements, from_kind, capacity);
        JSObject::SetMapAndElements(object, to_map, elements);
      }
      if (FLAG_trace_elements_transitions) {
        JSObject::PrintElementsTransition(stdout, object, from_kind,
                                          from_elements, to_kind,
                                          handle(object->elements()));
      }
    }
  }

888
  static void GrowCapacityAndConvertImpl(Handle<JSObject> object,
889
                                         uint32_t capacity) {
890 891 892 893 894 895 896 897 898 899 900 901 902 903
    ElementsKind from_kind = object->GetElementsKind();
    if (IsFastSmiOrObjectElementsKind(from_kind)) {
      // Array optimizations rely on the prototype lookups of Array objects
      // always returning undefined. If there is a store to the initial
      // prototype object, make sure all of these optimizations are invalidated.
      object->GetIsolate()->UpdateArrayProtectorOnSetLength(object);
    }
    Handle<FixedArrayBase> old_elements(object->elements());
    // This method should only be called if there's a reason to update the
    // elements.
    DCHECK(IsFastDoubleElementsKind(from_kind) !=
               IsFastDoubleElementsKind(kind()) ||
           IsDictionaryElementsKind(from_kind) ||
           static_cast<uint32_t>(old_elements->length()) < capacity);
904 905 906 907 908 909 910
    Subclass::BasicGrowCapacityAndConvertImpl(object, old_elements, from_kind,
                                              kind(), capacity);
  }

  static void BasicGrowCapacityAndConvertImpl(
      Handle<JSObject> object, Handle<FixedArrayBase> old_elements,
      ElementsKind from_kind, ElementsKind to_kind, uint32_t capacity) {
911 912 913 914 915 916 917 918 919 920 921 922 923 924
    Handle<FixedArrayBase> elements =
        ConvertElementsWithCapacity(object, old_elements, from_kind, capacity);

    if (IsHoleyElementsKind(from_kind)) to_kind = GetHoleyElementsKind(to_kind);
    Handle<Map> new_map = JSObject::GetElementsTransitionMap(object, to_kind);
    JSObject::SetMapAndElements(object, new_map, elements);

    // Transition through the allocation site as well if present.
    JSObject::UpdateAllocationSite(object, to_kind);

    if (FLAG_trace_elements_transitions) {
      JSObject::PrintElementsTransition(stdout, object, from_kind, old_elements,
                                        to_kind, elements);
    }
925 926
  }

927 928 929 930
  void TransitionElementsKind(Handle<JSObject> object, Handle<Map> map) final {
    Subclass::TransitionElementsKindImpl(object, map);
  }

931 932
  void GrowCapacityAndConvert(Handle<JSObject> object,
                              uint32_t capacity) final {
933
    Subclass::GrowCapacityAndConvertImpl(object, capacity);
934 935
  }

936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
  bool GrowCapacity(Handle<JSObject> object, uint32_t index) final {
    // This function is intended to be called from optimized code. We don't
    // want to trigger lazy deopts there, so refuse to handle cases that would.
    if (object->map()->is_prototype_map() ||
        object->WouldConvertToSlowElements(index)) {
      return false;
    }
    Handle<FixedArrayBase> old_elements(object->elements());
    uint32_t new_capacity = JSObject::NewElementsCapacity(index + 1);
    DCHECK(static_cast<uint32_t>(old_elements->length()) < new_capacity);
    Handle<FixedArrayBase> elements =
        ConvertElementsWithCapacity(object, old_elements, kind(), new_capacity);

    DCHECK_EQ(object->GetElementsKind(), kind());
    // Transition through the allocation site as well if present.
    if (JSObject::UpdateAllocationSite<AllocationSiteUpdateMode::kCheckOnly>(
            object, kind())) {
      return false;
    }

    object->set_elements(*elements);
    return true;
  }

960
  void Delete(Handle<JSObject> obj, uint32_t entry) final {
961
    Subclass::DeleteImpl(obj, entry);
962
  }
963

964 965 966
  static void CopyElementsImpl(FixedArrayBase* from, uint32_t from_start,
                               FixedArrayBase* to, ElementsKind from_kind,
                               uint32_t to_start, int packed_size,
967
                               int copy_size) {
968
    UNREACHABLE();
969 970
  }

971 972 973
  void CopyElements(JSObject* from_holder, uint32_t from_start,
                    ElementsKind from_kind, Handle<FixedArrayBase> to,
                    uint32_t to_start, int copy_size) final {
974 975 976 977 978 979 980 981
    int packed_size = kPackedSizeNotKnown;
    bool is_packed = IsFastPackedElementsKind(from_kind) &&
        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;
982 983
      }
    }
984
    FixedArrayBase* from = from_holder->elements();
985
    // NOTE: the Subclass::CopyElementsImpl() methods
986 987 988 989 990 991 992 993
    // violate the handlified function signature convention:
    // raw pointer parameters in the function that allocates. This is done
    // intentionally to avoid ArrayConcat() builtin performance degradation.
    //
    // Details: The idea is that allocations actually happen only in case of
    // copying from object with fast double elements to object with object
    // elements. In all the other cases there are no allocations performed and
    // handle creation causes noticeable performance degradation of the builtin.
994 995
    Subclass::CopyElementsImpl(from, from_start, *to, from_kind, to_start,
                               packed_size, copy_size);
996 997
  }

998 999 1000 1001 1002 1003
  void CopyElements(Handle<FixedArrayBase> source, ElementsKind source_kind,
                    Handle<FixedArrayBase> destination, int size) {
    Subclass::CopyElementsImpl(*source, 0, *destination, source_kind, 0,
                               kPackedSizeNotKnown, size);
  }

1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
  Object* CopyElements(Handle<JSReceiver> source, Handle<JSObject> destination,
                       size_t length) final {
    return Subclass::CopyElementsHandleImpl(source, destination, length);
  }

  static Object* CopyElementsHandleImpl(Handle<JSReceiver> source,
                                        Handle<JSObject> destination,
                                        size_t length) {
    UNREACHABLE();
  }

1015
  Handle<SeededNumberDictionary> Normalize(Handle<JSObject> object) final {
1016
    return Subclass::NormalizeImpl(object, handle(object->elements()));
1017 1018 1019 1020 1021 1022 1023
  }

  static Handle<SeededNumberDictionary> NormalizeImpl(
      Handle<JSObject> object, Handle<FixedArrayBase> elements) {
    UNREACHABLE();
  }

1024 1025 1026 1027
  Maybe<bool> CollectValuesOrEntries(Isolate* isolate, Handle<JSObject> object,
                                     Handle<FixedArray> values_or_entries,
                                     bool get_entries, int* nof_items,
                                     PropertyFilter filter) {
1028
    return Subclass::CollectValuesOrEntriesImpl(
1029 1030 1031 1032 1033 1034 1035 1036
        isolate, object, values_or_entries, get_entries, nof_items, filter);
  }

  static Maybe<bool> CollectValuesOrEntriesImpl(
      Isolate* isolate, Handle<JSObject> object,
      Handle<FixedArray> values_or_entries, bool get_entries, int* nof_items,
      PropertyFilter filter) {
    int count = 0;
1037 1038
    KeyAccumulator accumulator(isolate, KeyCollectionMode::kOwnOnly,
                               ALL_PROPERTIES);
1039
    Subclass::CollectElementIndicesImpl(
1040
        object, handle(object->elements(), isolate), &accumulator);
1041 1042 1043 1044 1045 1046 1047 1048
    Handle<FixedArray> keys = accumulator.GetKeys();

    for (int i = 0; i < keys->length(); ++i) {
      Handle<Object> key(keys->get(i), isolate);
      Handle<Object> value;
      uint32_t index;
      if (!key->ToUint32(&index)) continue;

1049
      uint32_t entry = Subclass::GetEntryForIndexImpl(
1050
          isolate, *object, object->elements(), index, filter);
1051 1052
      if (entry == kMaxUInt32) continue;

1053
      PropertyDetails details = Subclass::GetDetailsImpl(*object, entry);
1054 1055

      if (details.kind() == kData) {
1056
        value = Subclass::GetImpl(isolate, object->elements(), entry);
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
      } else {
        LookupIterator it(isolate, object, index, LookupIterator::OWN);
        ASSIGN_RETURN_ON_EXCEPTION_VALUE(
            isolate, value, Object::GetProperty(&it), Nothing<bool>());
      }
      if (get_entries) {
        value = MakeEntryPair(isolate, index, value);
      }
      values_or_entries->set(count++, *value);
    }

    *nof_items = count;
    return Just(true);
  }

1072 1073
  void CollectElementIndices(Handle<JSObject> object,
                             Handle<FixedArrayBase> backing_store,
1074 1075 1076
                             KeyAccumulator* keys) final {
    if (keys->filter() & ONLY_ALL_CAN_READ) return;
    Subclass::CollectElementIndicesImpl(object, backing_store, keys);
1077 1078
  }

1079 1080
  static void CollectElementIndicesImpl(Handle<JSObject> object,
                                        Handle<FixedArrayBase> backing_store,
1081
                                        KeyAccumulator* keys) {
1082
    DCHECK_NE(DICTIONARY_ELEMENTS, kind());
1083
    // Non-dictionary elements can't have all-can-read accessors.
1084
    uint32_t length = Subclass::GetMaxIndex(*object, *backing_store);
1085
    PropertyFilter filter = keys->filter();
1086 1087
    Isolate* isolate = keys->isolate();
    Factory* factory = isolate->factory();
1088
    for (uint32_t i = 0; i < length; i++) {
1089 1090
      if (Subclass::HasElementImpl(isolate, *object, i, *backing_store,
                                   filter)) {
1091
        keys->AddKey(factory->NewNumberFromUint(i));
1092 1093 1094 1095
      }
    }
  }

1096 1097 1098
  static Handle<FixedArray> DirectCollectElementIndicesImpl(
      Isolate* isolate, Handle<JSObject> object,
      Handle<FixedArrayBase> backing_store, GetKeysConversion convert,
1099 1100
      PropertyFilter filter, Handle<FixedArray> list, uint32_t* nof_indices,
      uint32_t insertion_index = 0) {
1101
    uint32_t length = Subclass::GetMaxIndex(*object, *backing_store);
1102
    for (uint32_t i = 0; i < length; i++) {
1103 1104
      if (Subclass::HasElementImpl(isolate, *object, i, *backing_store,
                                   filter)) {
1105
        if (convert == GetKeysConversion::kConvertToString) {
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
          Handle<String> index_string = isolate->factory()->Uint32ToString(i);
          list->set(insertion_index, *index_string);
        } else {
          list->set(insertion_index, Smi::FromInt(i), SKIP_WRITE_BARRIER);
        }
        insertion_index++;
      }
    }
    *nof_indices = insertion_index;
    return list;
  }

1118 1119 1120 1121
  MaybeHandle<FixedArray> PrependElementIndices(
      Handle<JSObject> object, Handle<FixedArrayBase> backing_store,
      Handle<FixedArray> keys, GetKeysConversion convert,
      PropertyFilter filter) final {
1122 1123
    return Subclass::PrependElementIndicesImpl(object, backing_store, keys,
                                               convert, filter);
1124 1125
  }

1126
  static MaybeHandle<FixedArray> PrependElementIndicesImpl(
1127 1128 1129 1130 1131 1132
      Handle<JSObject> object, Handle<FixedArrayBase> backing_store,
      Handle<FixedArray> keys, GetKeysConversion convert,
      PropertyFilter filter) {
    Isolate* isolate = object->GetIsolate();
    uint32_t nof_property_keys = keys->length();
    uint32_t initial_list_length =
1133
        Subclass::GetMaxNumberOfEntries(*object, *backing_store);
1134

1135
    initial_list_length += nof_property_keys;
1136 1137 1138 1139 1140
    if (initial_list_length > FixedArray::kMaxLength ||
        initial_list_length < nof_property_keys) {
      return isolate->Throw<FixedArray>(isolate->factory()->NewRangeError(
          MessageTemplate::kInvalidArrayLength));
    }
1141 1142

    // Collect the element indices into a new list.
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
    MaybeHandle<FixedArray> raw_array =
        isolate->factory()->TryNewFixedArray(initial_list_length);
    Handle<FixedArray> combined_keys;

    // If we have a holey backing store try to precisely estimate the backing
    // store size as a last emergency measure if we cannot allocate the big
    // array.
    if (!raw_array.ToHandle(&combined_keys)) {
      if (IsHoleyElementsKind(kind())) {
        // If we overestimate the result list size we might end up in the
        // large-object space which doesn't free memory on shrinking the list.
        // Hence we try to estimate the final size for holey backing stores more
        // precisely here.
        initial_list_length =
            Subclass::NumberOfElementsImpl(*object, *backing_store);
        initial_list_length += nof_property_keys;
      }
      combined_keys = isolate->factory()->NewFixedArray(initial_list_length);
    }

1163
    uint32_t nof_indices = 0;
1164 1165
    bool needs_sorting = IsDictionaryElementsKind(kind()) ||
                         IsSloppyArgumentsElementsKind(kind());
1166
    combined_keys = Subclass::DirectCollectElementIndicesImpl(
1167 1168 1169
        isolate, object, backing_store,
        needs_sorting ? GetKeysConversion::kKeepNumbers : convert, filter,
        combined_keys, &nof_indices);
1170

1171
    if (needs_sorting) {
1172
      SortIndices(combined_keys, nof_indices);
1173 1174
      // Indices from dictionary elements should only be converted after
      // sorting.
1175
      if (convert == GetKeysConversion::kConvertToString) {
1176 1177
        for (uint32_t i = 0; i < nof_indices; i++) {
          Handle<Object> index_string = isolate->factory()->Uint32ToString(
1178
              combined_keys->get(i)->Number());
1179 1180 1181 1182 1183 1184 1185 1186 1187
          combined_keys->set(i, *index_string);
        }
      }
    }

    // Copy over the passed-in property keys.
    CopyObjectToObjectElements(*keys, FAST_ELEMENTS, 0, *combined_keys,
                               FAST_ELEMENTS, nof_indices, nof_property_keys);

1188 1189
    // For holey elements and arguments we might have to shrink the collected
    // keys since the estimates might be off.
1190
    if (IsHoleyElementsKind(kind()) || IsSloppyArgumentsElementsKind(kind())) {
1191 1192 1193 1194 1195 1196 1197 1198
      // Shrink combined_keys to the final size.
      int final_size = nof_indices + nof_property_keys;
      DCHECK_LE(final_size, combined_keys->length());
      combined_keys->Shrink(final_size);
    }

    return combined_keys;
  }
1199

1200 1201 1202
  void AddElementsToKeyAccumulator(Handle<JSObject> receiver,
                                   KeyAccumulator* accumulator,
                                   AddKeyConversion convert) final {
1203
    Subclass::AddElementsToKeyAccumulatorImpl(receiver, accumulator, convert);
1204 1205
  }

1206 1207
  static uint32_t GetCapacityImpl(JSObject* holder,
                                  FixedArrayBase* backing_store) {
1208
    return backing_store->length();
1209 1210
  }

1211
  uint32_t GetCapacity(JSObject* holder, FixedArrayBase* backing_store) final {
1212
    return Subclass::GetCapacityImpl(holder, backing_store);
1213 1214
  }

1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
  static Object* FillImpl(Isolate* isolate, Handle<JSObject> receiver,
                          Handle<Object> obj_value, uint32_t start,
                          uint32_t end) {
    UNREACHABLE();
  }

  Object* Fill(Isolate* isolate, Handle<JSObject> receiver,
               Handle<Object> obj_value, uint32_t start, uint32_t end) {
    return Subclass::FillImpl(isolate, receiver, obj_value, start, end);
  }

1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
  static Maybe<bool> IncludesValueImpl(Isolate* isolate,
                                       Handle<JSObject> receiver,
                                       Handle<Object> value,
                                       uint32_t start_from, uint32_t length) {
    return IncludesValueSlowPath(isolate, receiver, value, start_from, length);
  }

  Maybe<bool> IncludesValue(Isolate* isolate, Handle<JSObject> receiver,
                            Handle<Object> value, uint32_t start_from,
                            uint32_t length) final {
    return Subclass::IncludesValueImpl(isolate, receiver, value, start_from,
                                       length);
  }

1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253
  static Maybe<int64_t> IndexOfValueImpl(Isolate* isolate,
                                         Handle<JSObject> receiver,
                                         Handle<Object> value,
                                         uint32_t start_from, uint32_t length) {
    return IndexOfValueSlowPath(isolate, receiver, value, start_from, length);
  }

  Maybe<int64_t> IndexOfValue(Isolate* isolate, Handle<JSObject> receiver,
                              Handle<Object> value, uint32_t start_from,
                              uint32_t length) final {
    return Subclass::IndexOfValueImpl(isolate, receiver, value, start_from,
                                      length);
  }

1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
  static Maybe<int64_t> LastIndexOfValueImpl(Isolate* isolate,
                                             Handle<JSObject> receiver,
                                             Handle<Object> value,
                                             uint32_t start_from) {
    UNREACHABLE();
  }

  Maybe<int64_t> LastIndexOfValue(Isolate* isolate, Handle<JSObject> receiver,
                                  Handle<Object> value,
                                  uint32_t start_from) final {
    return Subclass::LastIndexOfValueImpl(isolate, receiver, value, start_from);
  }

1267 1268 1269 1270
  static void ReverseImpl(JSObject* receiver) { UNREACHABLE(); }

  void Reverse(JSObject* receiver) final { Subclass::ReverseImpl(receiver); }

1271 1272 1273
  static uint32_t GetIndexForEntryImpl(FixedArrayBase* backing_store,
                                       uint32_t entry) {
    return entry;
1274 1275
  }

1276
  static uint32_t GetEntryForIndexImpl(Isolate* isolate, JSObject* holder,
1277
                                       FixedArrayBase* backing_store,
1278
                                       uint32_t index, PropertyFilter filter) {
1279
    uint32_t length = Subclass::GetMaxIndex(holder, backing_store);
1280
    if (IsHoleyElementsKind(kind())) {
1281
      return index < length &&
1282 1283
                     !BackingStore::cast(backing_store)
                          ->is_the_hole(isolate, index)
1284 1285 1286 1287 1288
                 ? index
                 : kMaxUInt32;
    } else {
      return index < length ? index : kMaxUInt32;
    }
1289 1290
  }

1291 1292
  uint32_t GetEntryForIndex(Isolate* isolate, JSObject* holder,
                            FixedArrayBase* backing_store,
1293
                            uint32_t index) final {
1294
    return Subclass::GetEntryForIndexImpl(isolate, holder, backing_store, index,
1295
                                          ALL_PROPERTIES);
1296 1297 1298
  }

  static PropertyDetails GetDetailsImpl(FixedArrayBase* backing_store,
1299
                                        uint32_t entry) {
1300
    return PropertyDetails(kData, NONE, 0, PropertyCellType::kNoCell);
1301 1302
  }

1303
  static PropertyDetails GetDetailsImpl(JSObject* holder, uint32_t entry) {
1304
    return PropertyDetails(kData, NONE, 0, PropertyCellType::kNoCell);
1305 1306 1307
  }

  PropertyDetails GetDetails(JSObject* holder, uint32_t entry) final {
1308
    return Subclass::GetDetailsImpl(holder, entry);
1309 1310
  }

1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
  Handle<FixedArray> CreateListFromArray(Isolate* isolate,
                                         Handle<JSArray> array) final {
    return Subclass::CreateListFromArrayImpl(isolate, array);
  };

  static Handle<FixedArray> CreateListFromArrayImpl(Isolate* isolate,
                                                    Handle<JSArray> array) {
    UNREACHABLE();
  }

1321 1322 1323 1324 1325
 private:
  DISALLOW_COPY_AND_ASSIGN(ElementsAccessorBase);
};


1326 1327 1328 1329 1330 1331 1332 1333
class DictionaryElementsAccessor
    : public ElementsAccessorBase<DictionaryElementsAccessor,
                                  ElementsKindTraits<DICTIONARY_ELEMENTS> > {
 public:
  explicit DictionaryElementsAccessor(const char* name)
      : ElementsAccessorBase<DictionaryElementsAccessor,
                             ElementsKindTraits<DICTIONARY_ELEMENTS> >(name) {}

1334 1335 1336 1337 1338 1339 1340
  static uint32_t GetMaxIndex(JSObject* receiver, FixedArrayBase* elements) {
    // We cannot properly estimate this for dictionaries.
    UNREACHABLE();
  }

  static uint32_t GetMaxNumberOfEntries(JSObject* receiver,
                                        FixedArrayBase* backing_store) {
1341 1342 1343 1344 1345
    return NumberOfElementsImpl(receiver, backing_store);
  }

  static uint32_t NumberOfElementsImpl(JSObject* receiver,
                                       FixedArrayBase* backing_store) {
1346 1347
    SeededNumberDictionary* dict = SeededNumberDictionary::cast(backing_store);
    return dict->NumberOfElements();
1348 1349
  }

1350 1351
  static void SetLengthImpl(Isolate* isolate, Handle<JSArray> array,
                            uint32_t length,
1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
                            Handle<FixedArrayBase> backing_store) {
    Handle<SeededNumberDictionary> dict =
        Handle<SeededNumberDictionary>::cast(backing_store);
    int capacity = dict->Capacity();
    uint32_t old_length = 0;
    CHECK(array->length()->ToArrayLength(&old_length));
    if (length < old_length) {
      if (dict->requires_slow_elements()) {
        // Find last non-deletable element in range of elements to be
        // deleted and adjust range accordingly.
1362
        for (int entry = 0; entry < capacity; entry++) {
1363
          DisallowHeapAllocation no_gc;
1364 1365 1366
          Object* index = dict->KeyAt(entry);
          if (index->IsNumber()) {
            uint32_t number = static_cast<uint32_t>(index->Number());
1367
            if (length <= number && number < old_length) {
1368
              PropertyDetails details = dict->DetailsAt(entry);
1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
              if (!details.IsConfigurable()) length = number + 1;
            }
          }
        }
      }

      if (length == 0) {
        // Flush the backing store.
        JSObject::ResetElements(array);
      } else {
        DisallowHeapAllocation no_gc;
        // Remove elements that should be deleted.
        int removed_entries = 0;
        Handle<Object> the_hole_value = isolate->factory()->the_hole_value();
1383 1384 1385 1386
        for (int entry = 0; entry < capacity; entry++) {
          Object* index = dict->KeyAt(entry);
          if (index->IsNumber()) {
            uint32_t number = static_cast<uint32_t>(index->Number());
1387
            if (length <= number && number < old_length) {
1388
              dict->SetEntry(entry, the_hole_value, the_hole_value);
1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410
              removed_entries++;
            }
          }
        }

        // Update the number of elements.
        dict->ElementsRemoved(removed_entries);
      }
    }

    Handle<Object> length_obj = isolate->factory()->NewNumberFromUint(length);
    array->set_length(*length_obj);
  }

  static void CopyElementsImpl(FixedArrayBase* from, uint32_t from_start,
                               FixedArrayBase* to, ElementsKind from_kind,
                               uint32_t to_start, int packed_size,
                               int copy_size) {
    UNREACHABLE();
  }


1411 1412
  static void DeleteImpl(Handle<JSObject> obj, uint32_t entry) {
    // TODO(verwaest): Remove reliance on index in Shrink.
1413 1414
    Handle<SeededNumberDictionary> dict(
        SeededNumberDictionary::cast(obj->elements()));
1415 1416
    uint32_t index = GetIndexForEntryImpl(*dict, entry);
    Handle<Object> result = SeededNumberDictionary::DeleteProperty(dict, entry);
1417
    USE(result);
1418
    DCHECK(result->IsTrue(dict->GetIsolate()));
1419 1420
    Handle<FixedArray> new_elements =
        SeededNumberDictionary::Shrink(dict, index);
1421
    obj->set_elements(*new_elements);
1422 1423
  }

1424 1425
  static bool HasAccessorsImpl(JSObject* holder,
                               FixedArrayBase* backing_store) {
1426
    DisallowHeapAllocation no_gc;
1427 1428 1429
    SeededNumberDictionary* dict = SeededNumberDictionary::cast(backing_store);
    if (!dict->requires_slow_elements()) return false;
    int capacity = dict->Capacity();
1430
    Isolate* isolate = dict->GetIsolate();
1431 1432
    for (int i = 0; i < capacity; i++) {
      Object* key = dict->KeyAt(i);
1433
      if (!dict->IsKey(isolate, key)) continue;
1434 1435
      DCHECK(!dict->IsDeleted(i));
      PropertyDetails details = dict->DetailsAt(i);
1436
      if (details.kind() == kAccessor) return true;
1437 1438 1439 1440
    }
    return false;
  }

1441 1442 1443 1444 1445
  static Object* GetRaw(FixedArrayBase* store, uint32_t entry) {
    SeededNumberDictionary* backing_store = SeededNumberDictionary::cast(store);
    return backing_store->ValueAt(entry);
  }

1446 1447 1448
  static Handle<Object> GetImpl(Isolate* isolate, FixedArrayBase* backing_store,
                                uint32_t entry) {
    return handle(GetRaw(backing_store, entry), isolate);
1449 1450 1451
  }

  static inline void SetImpl(Handle<JSObject> holder, uint32_t entry,
1452
                             Object* value) {
1453 1454 1455 1456 1457 1458
    SetImpl(holder->elements(), entry, value);
  }

  static inline void SetImpl(FixedArrayBase* backing_store, uint32_t entry,
                             Object* value) {
    SeededNumberDictionary::cast(backing_store)->ValueAtPut(entry, value);
1459 1460 1461
  }

  static void ReconfigureImpl(Handle<JSObject> object,
1462
                              Handle<FixedArrayBase> store, uint32_t entry,
1463 1464 1465
                              Handle<Object> value,
                              PropertyAttributes attributes) {
    SeededNumberDictionary* dictionary = SeededNumberDictionary::cast(*store);
1466
    if (attributes != NONE) object->RequireSlowElements(dictionary);
1467 1468
    dictionary->ValueAtPut(entry, *value);
    PropertyDetails details = dictionary->DetailsAt(entry);
1469
    details = PropertyDetails(kData, attributes, details.dictionary_index(),
1470
                              PropertyCellType::kNoCell);
1471
    dictionary->DetailsAtPut(entry, details);
1472 1473
  }

1474
  static void AddImpl(Handle<JSObject> object, uint32_t index,
1475 1476
                      Handle<Object> value, PropertyAttributes attributes,
                      uint32_t new_capacity) {
1477
    PropertyDetails details(kData, attributes, 0, PropertyCellType::kNoCell);
1478
    Handle<SeededNumberDictionary> dictionary =
1479
        object->HasFastElements() || object->HasFastStringWrapperElements()
1480 1481 1482
            ? JSObject::NormalizeElements(object)
            : handle(SeededNumberDictionary::cast(object->elements()));
    Handle<SeededNumberDictionary> new_dictionary =
1483 1484
        SeededNumberDictionary::AddNumberEntry(dictionary, index, value,
                                               details, object);
1485
    if (attributes != NONE) object->RequireSlowElements(*new_dictionary);
1486 1487 1488 1489
    if (dictionary.is_identical_to(new_dictionary)) return;
    object->set_elements(*new_dictionary);
  }

1490 1491
  static bool HasEntryImpl(Isolate* isolate, FixedArrayBase* store,
                           uint32_t entry) {
1492 1493
    DisallowHeapAllocation no_gc;
    SeededNumberDictionary* dict = SeededNumberDictionary::cast(store);
1494
    Object* index = dict->KeyAt(entry);
1495
    return !index->IsTheHole(isolate);
1496 1497
  }

1498
  static uint32_t GetIndexForEntryImpl(FixedArrayBase* store, uint32_t entry) {
1499 1500 1501
    DisallowHeapAllocation no_gc;
    SeededNumberDictionary* dict = SeededNumberDictionary::cast(store);
    uint32_t result = 0;
1502
    CHECK(dict->KeyAt(entry)->ToArrayIndex(&result));
1503 1504 1505
    return result;
  }

1506 1507 1508
  static uint32_t GetEntryForIndexImpl(Isolate* isolate, JSObject* holder,
                                       FixedArrayBase* store, uint32_t index,
                                       PropertyFilter filter) {
1509
    DisallowHeapAllocation no_gc;
1510
    SeededNumberDictionary* dictionary = SeededNumberDictionary::cast(store);
1511
    int entry = dictionary->FindEntry(isolate, index);
1512
    if (entry == SeededNumberDictionary::kNotFound) return kMaxUInt32;
1513
    if (filter != ALL_PROPERTIES) {
1514 1515 1516 1517 1518
      PropertyDetails details = dictionary->DetailsAt(entry);
      PropertyAttributes attr = details.attributes();
      if ((attr & filter) != 0) return kMaxUInt32;
    }
    return static_cast<uint32_t>(entry);
1519 1520
  }

1521 1522 1523 1524
  static PropertyDetails GetDetailsImpl(JSObject* holder, uint32_t entry) {
    return GetDetailsImpl(holder->elements(), entry);
  }

1525
  static PropertyDetails GetDetailsImpl(FixedArrayBase* backing_store,
1526 1527
                                        uint32_t entry) {
    return SeededNumberDictionary::cast(backing_store)->DetailsAt(entry);
1528
  }
1529

1530 1531
  static uint32_t FilterKey(Handle<SeededNumberDictionary> dictionary,
                            int entry, Object* raw_key, PropertyFilter filter) {
1532
    DCHECK(!dictionary->IsDeleted(entry));
1533 1534 1535 1536 1537
    DCHECK(raw_key->IsNumber());
    DCHECK_LE(raw_key->Number(), kMaxUInt32);
    PropertyDetails details = dictionary->DetailsAt(entry);
    PropertyAttributes attr = details.attributes();
    if ((attr & filter) != 0) return kMaxUInt32;
1538
    return static_cast<uint32_t>(raw_key->Number());
1539 1540
  }

1541 1542
  static uint32_t GetKeyForEntryImpl(Isolate* isolate,
                                     Handle<SeededNumberDictionary> dictionary,
1543 1544 1545
                                     int entry, PropertyFilter filter) {
    DisallowHeapAllocation no_gc;
    Object* raw_key = dictionary->KeyAt(entry);
1546
    if (!dictionary->IsKey(isolate, raw_key)) return kMaxUInt32;
1547 1548 1549
    return FilterKey(dictionary, entry, raw_key, filter);
  }

1550 1551
  static void CollectElementIndicesImpl(Handle<JSObject> object,
                                        Handle<FixedArrayBase> backing_store,
1552 1553
                                        KeyAccumulator* keys) {
    if (keys->filter() & SKIP_STRINGS) return;
1554
    Isolate* isolate = keys->isolate();
1555 1556 1557
    Handle<SeededNumberDictionary> dictionary =
        Handle<SeededNumberDictionary>::cast(backing_store);
    int capacity = dictionary->Capacity();
1558 1559
    Handle<FixedArray> elements = isolate->factory()->NewFixedArray(
        GetMaxNumberOfEntries(*object, *backing_store));
1560
    int insertion_index = 0;
1561
    PropertyFilter filter = keys->filter();
1562
    for (int i = 0; i < capacity; i++) {
1563 1564 1565 1566
      Object* raw_key = dictionary->KeyAt(i);
      if (!dictionary->IsKey(isolate, raw_key)) continue;
      uint32_t key = FilterKey(dictionary, i, raw_key, filter);
      if (key == kMaxUInt32) {
1567
        keys->AddShadowingKey(raw_key);
1568 1569 1570
        continue;
      }
      elements->set(insertion_index, raw_key);
1571 1572 1573 1574 1575
      insertion_index++;
    }
    SortIndices(elements, insertion_index);
    for (int i = 0; i < insertion_index; i++) {
      keys->AddKey(elements->get(i));
1576 1577
    }
  }
1578

1579 1580 1581
  static Handle<FixedArray> DirectCollectElementIndicesImpl(
      Isolate* isolate, Handle<JSObject> object,
      Handle<FixedArrayBase> backing_store, GetKeysConversion convert,
1582 1583
      PropertyFilter filter, Handle<FixedArray> list, uint32_t* nof_indices,
      uint32_t insertion_index = 0) {
1584 1585
    if (filter & SKIP_STRINGS) return list;
    if (filter & ONLY_ALL_CAN_READ) return list;
1586

1587 1588 1589 1590
    Handle<SeededNumberDictionary> dictionary =
        Handle<SeededNumberDictionary>::cast(backing_store);
    uint32_t capacity = dictionary->Capacity();
    for (uint32_t i = 0; i < capacity; i++) {
1591
      uint32_t key = GetKeyForEntryImpl(isolate, dictionary, i, filter);
1592 1593 1594 1595 1596 1597 1598 1599 1600
      if (key == kMaxUInt32) continue;
      Handle<Object> index = isolate->factory()->NewNumberFromUint(key);
      list->set(insertion_index, *index);
      insertion_index++;
    }
    *nof_indices = insertion_index;
    return list;
  }

1601 1602 1603
  static void AddElementsToKeyAccumulatorImpl(Handle<JSObject> receiver,
                                              KeyAccumulator* accumulator,
                                              AddKeyConversion convert) {
1604 1605 1606
    Isolate* isolate = accumulator->isolate();
    Handle<Object> undefined = isolate->factory()->undefined_value();
    Handle<Object> the_hole = isolate->factory()->the_hole_value();
1607 1608
    Handle<SeededNumberDictionary> dictionary(
        SeededNumberDictionary::cast(receiver->elements()), isolate);
1609 1610 1611
    int capacity = dictionary->Capacity();
    for (int i = 0; i < capacity; i++) {
      Object* k = dictionary->KeyAt(i);
1612 1613
      if (k == *undefined) continue;
      if (k == *the_hole) continue;
1614 1615
      if (dictionary->IsDeleted(i)) continue;
      Object* value = dictionary->ValueAt(i);
1616
      DCHECK(!value->IsTheHole(isolate));
1617 1618 1619 1620 1621
      DCHECK(!value->IsAccessorPair());
      DCHECK(!value->IsAccessorInfo());
      accumulator->AddKey(value, convert);
    }
  }
1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645

  static bool IncludesValueFastPath(Isolate* isolate, Handle<JSObject> receiver,
                                    Handle<Object> value, uint32_t start_from,
                                    uint32_t length, Maybe<bool>* result) {
    DisallowHeapAllocation no_gc;
    SeededNumberDictionary* dictionary =
        SeededNumberDictionary::cast(receiver->elements());
    int capacity = dictionary->Capacity();
    Object* the_hole = isolate->heap()->the_hole_value();
    Object* undefined = isolate->heap()->undefined_value();

    // Scan for accessor properties. If accessors are present, then elements
    // must be accessed in order via the slow path.
    bool found = false;
    for (int i = 0; i < capacity; ++i) {
      Object* k = dictionary->KeyAt(i);
      if (k == the_hole) continue;
      if (k == undefined) continue;

      uint32_t index;
      if (!k->ToArrayIndex(&index) || index < start_from || index >= length) {
        continue;
      }

1646
      if (dictionary->DetailsAt(i).kind() == kAccessor) {
1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679
        // Restart from beginning in slow path, otherwise we may observably
        // access getters out of order
        return false;
      } else if (!found) {
        Object* element_k = dictionary->ValueAt(i);
        if (value->SameValueZero(element_k)) found = true;
      }
    }

    *result = Just(found);
    return true;
  }

  static Maybe<bool> IncludesValueImpl(Isolate* isolate,
                                       Handle<JSObject> receiver,
                                       Handle<Object> value,
                                       uint32_t start_from, uint32_t length) {
    DCHECK(JSObject::PrototypeHasNoElements(isolate, *receiver));
    bool search_for_hole = value->IsUndefined(isolate);

    if (!search_for_hole) {
      Maybe<bool> result = Nothing<bool>();
      if (DictionaryElementsAccessor::IncludesValueFastPath(
              isolate, receiver, value, start_from, length, &result)) {
        return result;
      }
    }

    Handle<SeededNumberDictionary> dictionary(
        SeededNumberDictionary::cast(receiver->elements()), isolate);
    // Iterate through entire range, as accessing elements out of order is
    // observable
    for (uint32_t k = start_from; k < length; ++k) {
1680
      int entry = dictionary->FindEntry(isolate, k);
1681 1682 1683 1684 1685
      if (entry == SeededNumberDictionary::kNotFound) {
        if (search_for_hole) return Just(true);
        continue;
      }

1686
      PropertyDetails details = GetDetailsImpl(*dictionary, entry);
1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705
      switch (details.kind()) {
        case kData: {
          Object* element_k = dictionary->ValueAt(entry);
          if (value->SameValueZero(element_k)) return Just(true);
          break;
        }
        case kAccessor: {
          LookupIterator it(isolate, receiver, k,
                            LookupIterator::OWN_SKIP_INTERCEPTOR);
          DCHECK(it.IsFound());
          DCHECK_EQ(it.state(), LookupIterator::ACCESSOR);
          Handle<Object> element_k;

          ASSIGN_RETURN_ON_EXCEPTION_VALUE(
              isolate, element_k, JSObject::GetPropertyWithAccessor(&it),
              Nothing<bool>());

          if (value->SameValueZero(*element_k)) return Just(true);

1706
          // Bailout to slow path if elements on prototype changed
1707 1708 1709 1710
          if (!JSObject::PrototypeHasNoElements(isolate, *receiver)) {
            return IncludesValueSlowPath(isolate, receiver, value, k + 1,
                                         length);
          }
1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727

          // Continue if elements unchanged
          if (*dictionary == receiver->elements()) continue;

          // Otherwise, bailout or update elements
          if (receiver->GetElementsKind() != DICTIONARY_ELEMENTS) {
            if (receiver->map()->GetInitialElements() == receiver->elements()) {
              // If switched to initial elements, return true if searching for
              // undefined, and false otherwise.
              return Just(search_for_hole);
            }
            // Otherwise, switch to slow path.
            return IncludesValueSlowPath(isolate, receiver, value, k + 1,
                                         length);
          }
          dictionary = handle(
              SeededNumberDictionary::cast(receiver->elements()), isolate);
1728 1729 1730 1731 1732 1733
          break;
        }
      }
    }
    return Just(false);
  }
1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745

  static Maybe<int64_t> IndexOfValueImpl(Isolate* isolate,
                                         Handle<JSObject> receiver,
                                         Handle<Object> value,
                                         uint32_t start_from, uint32_t length) {
    DCHECK(JSObject::PrototypeHasNoElements(isolate, *receiver));

    Handle<SeededNumberDictionary> dictionary(
        SeededNumberDictionary::cast(receiver->elements()), isolate);
    // Iterate through entire range, as accessing elements out of order is
    // observable.
    for (uint32_t k = start_from; k < length; ++k) {
1746
      int entry = dictionary->FindEntry(isolate, k);
1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795
      if (entry == SeededNumberDictionary::kNotFound) {
        continue;
      }

      PropertyDetails details = GetDetailsImpl(*dictionary, entry);
      switch (details.kind()) {
        case kData: {
          Object* element_k = dictionary->ValueAt(entry);
          if (value->StrictEquals(element_k)) {
            return Just<int64_t>(k);
          }
          break;
        }
        case kAccessor: {
          LookupIterator it(isolate, receiver, k,
                            LookupIterator::OWN_SKIP_INTERCEPTOR);
          DCHECK(it.IsFound());
          DCHECK_EQ(it.state(), LookupIterator::ACCESSOR);
          Handle<Object> element_k;

          ASSIGN_RETURN_ON_EXCEPTION_VALUE(
              isolate, element_k, JSObject::GetPropertyWithAccessor(&it),
              Nothing<int64_t>());

          if (value->StrictEquals(*element_k)) return Just<int64_t>(k);

          // Bailout to slow path if elements on prototype changed.
          if (!JSObject::PrototypeHasNoElements(isolate, *receiver)) {
            return IndexOfValueSlowPath(isolate, receiver, value, k + 1,
                                        length);
          }

          // Continue if elements unchanged.
          if (*dictionary == receiver->elements()) continue;

          // Otherwise, bailout or update elements.
          if (receiver->GetElementsKind() != DICTIONARY_ELEMENTS) {
            // Otherwise, switch to slow path.
            return IndexOfValueSlowPath(isolate, receiver, value, k + 1,
                                        length);
          }
          dictionary = handle(
              SeededNumberDictionary::cast(receiver->elements()), isolate);
          break;
        }
      }
    }
    return Just<int64_t>(-1);
  }
1796 1797
};

1798

1799
// Super class for all fast element arrays.
1800 1801
template <typename Subclass, typename KindTraits>
class FastElementsAccessor : public ElementsAccessorBase<Subclass, KindTraits> {
1802 1803
 public:
  explicit FastElementsAccessor(const char* name)
1804
      : ElementsAccessorBase<Subclass, KindTraits>(name) {}
1805

1806
  typedef typename KindTraits::BackingStore BackingStore;
1807

1808 1809 1810
  static Handle<SeededNumberDictionary> NormalizeImpl(
      Handle<JSObject> object, Handle<FixedArrayBase> store) {
    Isolate* isolate = store->GetIsolate();
1811
    ElementsKind kind = Subclass::kind();
1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826

    // Ensure that notifications fire if the array or object prototypes are
    // normalizing.
    if (IsFastSmiOrObjectElementsKind(kind)) {
      isolate->UpdateArrayProtectorOnNormalizeElements(object);
    }

    int capacity = object->GetFastElementsUsage();
    Handle<SeededNumberDictionary> dictionary =
        SeededNumberDictionary::New(isolate, capacity);

    PropertyDetails details = PropertyDetails::Empty();
    int j = 0;
    for (int i = 0; j < capacity; i++) {
      if (IsHoleyElementsKind(kind)) {
1827
        if (BackingStore::cast(*store)->is_the_hole(isolate, i)) continue;
1828
      }
1829
      Handle<Object> value = Subclass::GetImpl(isolate, *store, i);
1830 1831
      dictionary = SeededNumberDictionary::AddNumberEntry(dictionary, i, value,
                                                          details, object);
1832 1833 1834 1835 1836
      j++;
    }
    return dictionary;
  }

1837 1838 1839
  static void DeleteAtEnd(Handle<JSObject> obj,
                          Handle<BackingStore> backing_store, uint32_t entry) {
    uint32_t length = static_cast<uint32_t>(backing_store->length());
1840
    Isolate* isolate = obj->GetIsolate();
1841
    for (; entry > 0; entry--) {
1842
      if (!backing_store->is_the_hole(isolate, entry - 1)) break;
1843 1844
    }
    if (entry == 0) {
1845
      FixedArray* empty = isolate->heap()->empty_fixed_array();
1846 1847 1848
      // Dynamically ask for the elements kind here since we manually redirect
      // the operations for argument backing stores.
      if (obj->GetElementsKind() == FAST_SLOPPY_ARGUMENTS_ELEMENTS) {
1849
        SloppyArgumentsElements::cast(obj->elements())->set_arguments(empty);
1850 1851 1852 1853 1854 1855
      } else {
        obj->set_elements(empty);
      }
      return;
    }

1856
    isolate->heap()->RightTrimFixedArray(*backing_store, length - entry);
1857 1858
  }

1859
  static void DeleteCommon(Handle<JSObject> obj, uint32_t entry,
1860
                           Handle<FixedArrayBase> store) {
1861 1862 1863
    DCHECK(obj->HasFastSmiOrObjectElements() || obj->HasFastDoubleElements() ||
           obj->HasFastArgumentsElements() ||
           obj->HasFastStringWrapperElements());
1864
    Handle<BackingStore> backing_store = Handle<BackingStore>::cast(store);
1865 1866 1867 1868 1869 1870
    if (!obj->IsJSArray() &&
        entry == static_cast<uint32_t>(store->length()) - 1) {
      DeleteAtEnd(obj, backing_store, entry);
      return;
    }

1871
    Isolate* isolate = obj->GetIsolate();
1872
    backing_store->set_the_hole(isolate, entry);
1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884

    // TODO(verwaest): Move this out of elements.cc.
    // If an old space backing store is larger than a certain size and
    // has too few used values, normalize it.
    const int kMinLengthForSparsenessCheck = 64;
    if (backing_store->length() < kMinLengthForSparsenessCheck) return;
    if (backing_store->GetHeap()->InNewSpace(*backing_store)) return;
    uint32_t length = 0;
    if (obj->IsJSArray()) {
      JSArray::cast(*obj)->length()->ToArrayLength(&length);
    } else {
      length = static_cast<uint32_t>(store->length());
1885
    }
1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907

    // To avoid doing the check on every delete, use a counter-based heuristic.
    const int kLengthFraction = 16;
    // The above constant must be large enough to ensure that we check for
    // normalization frequently enough. At a minimum, it should be large
    // enough to reliably hit the "window" of remaining elements count where
    // normalization would be beneficial.
    STATIC_ASSERT(kLengthFraction >=
                  SeededNumberDictionary::kEntrySize *
                      SeededNumberDictionary::kPreferFastElementsSizeFactor);
    size_t current_counter = isolate->elements_deletion_counter();
    if (current_counter < length / kLengthFraction) {
      isolate->set_elements_deletion_counter(current_counter + 1);
      return;
    }
    // Reset the counter whenever the full check is performed.
    isolate->set_elements_deletion_counter(0);

    if (!obj->IsJSArray()) {
      uint32_t i;
      for (i = entry + 1; i < length; i++) {
        if (!backing_store->is_the_hole(isolate, i)) break;
1908
      }
1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923
      if (i == length) {
        DeleteAtEnd(obj, backing_store, entry);
        return;
      }
    }
    int num_used = 0;
    for (int i = 0; i < backing_store->length(); ++i) {
      if (!backing_store->is_the_hole(isolate, i)) {
        ++num_used;
        // Bail out if a number dictionary wouldn't be able to save much space.
        if (SeededNumberDictionary::kPreferFastElementsSizeFactor *
                SeededNumberDictionary::ComputeCapacity(num_used) *
                SeededNumberDictionary::kEntrySize >
            static_cast<uint32_t>(backing_store->length())) {
          return;
1924
        }
1925 1926
      }
    }
1927
    JSObject::NormalizeElements(obj);
1928 1929
  }

1930
  static void ReconfigureImpl(Handle<JSObject> object,
1931
                              Handle<FixedArrayBase> store, uint32_t entry,
1932 1933 1934 1935
                              Handle<Object> value,
                              PropertyAttributes attributes) {
    Handle<SeededNumberDictionary> dictionary =
        JSObject::NormalizeElements(object);
1936 1937
    entry = dictionary->FindEntry(entry);
    DictionaryElementsAccessor::ReconfigureImpl(object, dictionary, entry,
1938
                                                value, attributes);
1939 1940
  }

1941
  static void AddImpl(Handle<JSObject> object, uint32_t index,
1942 1943 1944 1945
                      Handle<Object> value, PropertyAttributes attributes,
                      uint32_t new_capacity) {
    DCHECK_EQ(NONE, attributes);
    ElementsKind from_kind = object->GetElementsKind();
1946
    ElementsKind to_kind = Subclass::kind();
1947 1948 1949
    if (IsDictionaryElementsKind(from_kind) ||
        IsFastDoubleElementsKind(from_kind) !=
            IsFastDoubleElementsKind(to_kind) ||
1950 1951 1952
        Subclass::GetCapacityImpl(*object, object->elements()) !=
            new_capacity) {
      Subclass::GrowCapacityAndConvertImpl(object, new_capacity);
1953
    } else {
1954
      if (IsFastElementsKind(from_kind) && from_kind != to_kind) {
1955 1956 1957 1958 1959 1960 1961
        JSObject::TransitionElementsKind(object, to_kind);
      }
      if (IsFastSmiOrObjectElementsKind(from_kind)) {
        DCHECK(IsFastSmiOrObjectElementsKind(to_kind));
        JSObject::EnsureWritableFastElements(object);
      }
    }
1962
    Subclass::SetImpl(object, index, *value);
1963 1964
  }

1965
  static void DeleteImpl(Handle<JSObject> obj, uint32_t entry) {
1966 1967 1968 1969 1970 1971 1972
    ElementsKind kind = KindTraits::Kind;
    if (IsFastPackedElementsKind(kind)) {
      JSObject::TransitionElementsKind(obj, GetHoleyElementsKind(kind));
    }
    if (IsFastSmiOrObjectElementsKind(KindTraits::Kind)) {
      JSObject::EnsureWritableFastElements(obj);
    }
1973
    DeleteCommon(obj, entry, handle(obj->elements()));
1974 1975
  }

1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990
  static bool HasEntryImpl(Isolate* isolate, FixedArrayBase* backing_store,
                           uint32_t entry) {
    return !BackingStore::cast(backing_store)->is_the_hole(isolate, entry);
  }

  static uint32_t NumberOfElementsImpl(JSObject* receiver,
                                       FixedArrayBase* backing_store) {
    uint32_t max_index = Subclass::GetMaxIndex(receiver, backing_store);
    if (IsFastPackedElementsKind(Subclass::kind())) return max_index;
    Isolate* isolate = receiver->GetIsolate();
    uint32_t count = 0;
    for (uint32_t i = 0; i < max_index; i++) {
      if (Subclass::HasEntryImpl(isolate, backing_store, i)) count++;
    }
    return count;
1991 1992
  }

1993 1994 1995
  static void AddElementsToKeyAccumulatorImpl(Handle<JSObject> receiver,
                                              KeyAccumulator* accumulator,
                                              AddKeyConversion convert) {
1996 1997
    Isolate* isolate = accumulator->isolate();
    Handle<FixedArrayBase> elements(receiver->elements(), isolate);
1998
    uint32_t length = Subclass::GetMaxNumberOfEntries(*receiver, *elements);
1999 2000
    for (uint32_t i = 0; i < length; i++) {
      if (IsFastPackedElementsKind(KindTraits::Kind) ||
2001
          HasEntryImpl(isolate, *elements, i)) {
2002
        accumulator->AddKey(Subclass::GetImpl(isolate, *elements, i), convert);
2003 2004 2005 2006
      }
    }
  }

2007
  static void ValidateContents(Handle<JSObject> holder, int length) {
2008
#if DEBUG
2009
    Isolate* isolate = holder->GetIsolate();
2010
    Heap* heap = isolate->heap();
2011 2012
    HandleScope scope(isolate);
    Handle<FixedArrayBase> elements(holder->elements(), isolate);
2013
    Map* map = elements->map();
2014 2015 2016 2017 2018 2019 2020 2021
    if (IsFastSmiOrObjectElementsKind(KindTraits::Kind)) {
      DCHECK_NE(map, heap->fixed_double_array_map());
    } else if (IsFastDoubleElementsKind(KindTraits::Kind)) {
      DCHECK_NE(map, heap->fixed_cow_array_map());
      if (map == heap->fixed_array_map()) DCHECK_EQ(0, length);
    } else {
      UNREACHABLE();
    }
2022
    if (length == 0) return;  // nothing to do!
2023
#if ENABLE_SLOW_DCHECKS
2024
    DisallowHeapAllocation no_gc;
2025
    Handle<BackingStore> backing_store = Handle<BackingStore>::cast(elements);
2026 2027
    if (IsFastSmiElementsKind(KindTraits::Kind)) {
      for (int i = 0; i < length; i++) {
2028
        DCHECK(BackingStore::get(*backing_store, i, isolate)->IsSmi() ||
2029
               (IsFastHoleyElementsKind(KindTraits::Kind) &&
2030
                backing_store->is_the_hole(isolate, i)));
2031
      }
2032 2033 2034
    } else if (KindTraits::Kind == FAST_ELEMENTS ||
               KindTraits::Kind == FAST_DOUBLE_ELEMENTS) {
      for (int i = 0; i < length; i++) {
2035
        DCHECK(!backing_store->is_the_hole(isolate, i));
2036 2037 2038
      }
    } else {
      DCHECK(IsFastHoleyElementsKind(KindTraits::Kind));
2039
    }
2040
#endif
2041 2042
#endif
  }
2043

2044
  static Handle<Object> PopImpl(Handle<JSArray> receiver) {
2045
    return Subclass::RemoveElement(receiver, AT_END);
2046 2047
  }

2048
  static Handle<Object> ShiftImpl(Handle<JSArray> receiver) {
2049
    return Subclass::RemoveElement(receiver, AT_START);
cbruni's avatar
cbruni committed
2050 2051
  }

2052
  static uint32_t PushImpl(Handle<JSArray> receiver,
2053
                           Arguments* args, uint32_t push_size) {
2054
    Handle<FixedArrayBase> backing_store(receiver->elements());
2055 2056
    return Subclass::AddArguments(receiver, backing_store, args, push_size,
                                  AT_END);
2057
  }
2058

2059 2060
  static uint32_t UnshiftImpl(Handle<JSArray> receiver,
                              Arguments* args, uint32_t unshift_size) {
2061
    Handle<FixedArrayBase> backing_store(receiver->elements());
2062 2063
    return Subclass::AddArguments(receiver, backing_store, args, unshift_size,
                                  AT_START);
2064 2065
  }

2066 2067
  static Handle<JSObject> SliceImpl(Handle<JSObject> receiver, uint32_t start,
                                    uint32_t end) {
2068
    Isolate* isolate = receiver->GetIsolate();
2069 2070
    Handle<FixedArrayBase> backing_store(receiver->elements(), isolate);
    int result_len = end < start ? 0u : end - start;
2071 2072 2073
    Handle<JSArray> result_array = isolate->factory()->NewJSArray(
        KindTraits::Kind, result_len, result_len);
    DisallowHeapAllocation no_gc;
2074 2075 2076 2077
    Subclass::CopyElementsImpl(*backing_store, start, result_array->elements(),
                               KindTraits::Kind, 0, kPackedSizeNotKnown,
                               result_len);
    Subclass::TryTransitionResultArrayToPacked(result_array);
2078 2079 2080
    return result_array;
  }

2081 2082
  static Handle<JSArray> SpliceImpl(Handle<JSArray> receiver,
                                    uint32_t start, uint32_t delete_count,
2083
                                    Arguments* args, uint32_t add_count) {
2084 2085
    Isolate* isolate = receiver->GetIsolate();
    Heap* heap = isolate->heap();
cbruni's avatar
cbruni committed
2086 2087
    uint32_t length = Smi::cast(receiver->length())->value();
    uint32_t new_length = length - delete_count + add_count;
2088

2089 2090 2091 2092 2093 2094 2095 2096 2097
    ElementsKind kind = KindTraits::Kind;
    if (new_length <= static_cast<uint32_t>(receiver->elements()->length()) &&
        IsFastSmiOrObjectElementsKind(kind)) {
      HandleScope scope(isolate);
      JSObject::EnsureWritableFastElements(receiver);
    }

    Handle<FixedArrayBase> backing_store(receiver->elements(), isolate);

2098 2099
    if (new_length == 0) {
      receiver->set_elements(heap->empty_fixed_array());
2100
      receiver->set_length(Smi::kZero);
2101 2102 2103 2104
      return isolate->factory()->NewJSArrayWithElements(
          backing_store, KindTraits::Kind, delete_count);
    }

cbruni's avatar
cbruni committed
2105
    // Construct the result array which holds the deleted elements.
2106 2107 2108 2109
    Handle<JSArray> deleted_elements = isolate->factory()->NewJSArray(
        KindTraits::Kind, delete_count, delete_count);
    if (delete_count > 0) {
      DisallowHeapAllocation no_gc;
2110 2111 2112
      Subclass::CopyElementsImpl(*backing_store, start,
                                 deleted_elements->elements(), KindTraits::Kind,
                                 0, kPackedSizeNotKnown, delete_count);
2113 2114
    }

cbruni's avatar
cbruni committed
2115
    // Delete and move elements to make space for add_count new elements.
2116
    if (add_count < delete_count) {
2117 2118
      Subclass::SpliceShrinkStep(isolate, receiver, backing_store, start,
                                 delete_count, add_count, length, new_length);
2119
    } else if (add_count > delete_count) {
2120 2121 2122
      backing_store =
          Subclass::SpliceGrowStep(isolate, receiver, backing_store, start,
                                   delete_count, add_count, length, new_length);
2123 2124
    }

cbruni's avatar
cbruni committed
2125
    // Copy over the arguments.
2126
    Subclass::CopyArguments(args, backing_store, add_count, 3, start);
2127 2128

    receiver->set_length(Smi::FromInt(new_length));
2129
    Subclass::TryTransitionResultArrayToPacked(deleted_elements);
2130 2131 2132
    return deleted_elements;
  }

2133 2134 2135 2136
  static Maybe<bool> CollectValuesOrEntriesImpl(
      Isolate* isolate, Handle<JSObject> object,
      Handle<FixedArray> values_or_entries, bool get_entries, int* nof_items,
      PropertyFilter filter) {
2137 2138
    Handle<BackingStore> elements(BackingStore::cast(object->elements()),
                                  isolate);
2139
    int count = 0;
2140
    uint32_t length = elements->length();
2141
    for (uint32_t index = 0; index < length; ++index) {
2142
      if (!HasEntryImpl(isolate, *elements, index)) continue;
2143
      Handle<Object> value = Subclass::GetImpl(isolate, *elements, index);
2144 2145 2146 2147 2148 2149 2150 2151 2152
      if (get_entries) {
        value = MakeEntryPair(isolate, index, value);
      }
      values_or_entries->set(count++, *value);
    }
    *nof_items = count;
    return Just(true);
  }

2153 2154 2155 2156 2157 2158
  static void MoveElements(Isolate* isolate, Handle<JSArray> receiver,
                           Handle<FixedArrayBase> backing_store, int dst_index,
                           int src_index, int len, int hole_start,
                           int hole_end) {
    Heap* heap = isolate->heap();
    Handle<BackingStore> dst_elms = Handle<BackingStore>::cast(backing_store);
2159 2160
    if (len > JSArray::kMaxCopyElements && dst_index == 0 &&
        heap->CanMoveObjectStart(*dst_elms)) {
2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183
      // Update all the copies of this backing_store handle.
      *dst_elms.location() =
          BackingStore::cast(heap->LeftTrimFixedArray(*dst_elms, src_index));
      receiver->set_elements(*dst_elms);
      // Adjust the hole offset as the array has been shrunk.
      hole_end -= src_index;
      DCHECK_LE(hole_start, backing_store->length());
      DCHECK_LE(hole_end, backing_store->length());
    } else if (len != 0) {
      if (IsFastDoubleElementsKind(KindTraits::Kind)) {
        MemMove(dst_elms->data_start() + dst_index,
                dst_elms->data_start() + src_index, len * kDoubleSize);
      } else {
        DisallowHeapAllocation no_gc;
        heap->MoveElements(FixedArray::cast(*dst_elms), dst_index, src_index,
                           len);
      }
    }
    if (hole_start != hole_end) {
      dst_elms->FillWithHoles(hole_start, hole_end);
    }
  }

2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333
  static Maybe<bool> IncludesValueImpl(Isolate* isolate,
                                       Handle<JSObject> receiver,
                                       Handle<Object> search_value,
                                       uint32_t start_from, uint32_t length) {
    DCHECK(JSObject::PrototypeHasNoElements(isolate, *receiver));
    DisallowHeapAllocation no_gc;
    FixedArrayBase* elements_base = receiver->elements();
    Object* the_hole = isolate->heap()->the_hole_value();
    Object* undefined = isolate->heap()->undefined_value();
    Object* value = *search_value;

    // Elements beyond the capacity of the backing store treated as undefined.
    if (value == undefined &&
        static_cast<uint32_t>(elements_base->length()) < length) {
      return Just(true);
    }

    if (start_from >= length) return Just(false);

    length = std::min(static_cast<uint32_t>(elements_base->length()), length);

    if (!value->IsNumber()) {
      if (value == undefined) {
        // Only FAST_ELEMENTS, FAST_HOLEY_ELEMENTS, FAST_HOLEY_SMI_ELEMENTS, and
        // FAST_HOLEY_DOUBLE_ELEMENTS can have `undefined` as a value.
        if (!IsFastObjectElementsKind(Subclass::kind()) &&
            !IsFastHoleyElementsKind(Subclass::kind())) {
          return Just(false);
        }

        // Search for `undefined` or The Hole in FAST_ELEMENTS,
        // FAST_HOLEY_ELEMENTS or FAST_HOLEY_SMI_ELEMENTS
        if (IsFastSmiOrObjectElementsKind(Subclass::kind())) {
          auto elements = FixedArray::cast(receiver->elements());

          for (uint32_t k = start_from; k < length; ++k) {
            Object* element_k = elements->get(k);

            if (IsFastHoleyElementsKind(Subclass::kind()) &&
                element_k == the_hole) {
              return Just(true);
            }
            if (IsFastObjectElementsKind(Subclass::kind()) &&
                element_k == undefined) {
              return Just(true);
            }
          }
          return Just(false);
        } else {
          // Seach for The Hole in FAST_HOLEY_DOUBLE_ELEMENTS
          DCHECK_EQ(Subclass::kind(), FAST_HOLEY_DOUBLE_ELEMENTS);
          auto elements = FixedDoubleArray::cast(receiver->elements());

          for (uint32_t k = start_from; k < length; ++k) {
            if (IsFastHoleyElementsKind(Subclass::kind()) &&
                elements->is_the_hole(k)) {
              return Just(true);
            }
          }
          return Just(false);
        }
      } else if (!IsFastObjectElementsKind(Subclass::kind())) {
        // Search for non-number, non-Undefined value, with either
        // FAST_SMI_ELEMENTS, FAST_DOUBLE_ELEMENTS, FAST_HOLEY_SMI_ELEMENTS or
        // FAST_HOLEY_DOUBLE_ELEMENTS. Guaranteed to return false, since these
        // elements kinds can only contain Number values or undefined.
        return Just(false);
      } else {
        // Search for non-number, non-Undefined value with either
        // FAST_ELEMENTS or FAST_HOLEY_ELEMENTS.
        DCHECK(IsFastObjectElementsKind(Subclass::kind()));
        auto elements = FixedArray::cast(receiver->elements());

        for (uint32_t k = start_from; k < length; ++k) {
          Object* element_k = elements->get(k);
          if (IsFastHoleyElementsKind(Subclass::kind()) &&
              element_k == the_hole) {
            continue;
          }

          if (value->SameValueZero(element_k)) return Just(true);
        }
        return Just(false);
      }
    } else {
      if (!value->IsNaN()) {
        double search_value = value->Number();
        if (IsFastDoubleElementsKind(Subclass::kind())) {
          // Search for non-NaN Number in FAST_DOUBLE_ELEMENTS or
          // FAST_HOLEY_DOUBLE_ELEMENTS --- Skip TheHole, and trust UCOMISD or
          // similar operation for result.
          auto elements = FixedDoubleArray::cast(receiver->elements());

          for (uint32_t k = start_from; k < length; ++k) {
            if (IsFastHoleyElementsKind(Subclass::kind()) &&
                elements->is_the_hole(k)) {
              continue;
            }
            if (elements->get_scalar(k) == search_value) return Just(true);
          }
          return Just(false);
        } else {
          // Search for non-NaN Number in FAST_ELEMENTS, FAST_HOLEY_ELEMENTS,
          // FAST_SMI_ELEMENTS or FAST_HOLEY_SMI_ELEMENTS --- Skip non-Numbers,
          // and trust UCOMISD or similar operation for result
          auto elements = FixedArray::cast(receiver->elements());

          for (uint32_t k = start_from; k < length; ++k) {
            Object* element_k = elements->get(k);
            if (element_k->IsNumber() && element_k->Number() == search_value) {
              return Just(true);
            }
          }
          return Just(false);
        }
      } else {
        // Search for NaN --- NaN cannot be represented with Smi elements, so
        // abort if ElementsKind is FAST_SMI_ELEMENTS or FAST_HOLEY_SMI_ELEMENTS
        if (IsFastSmiElementsKind(Subclass::kind())) return Just(false);

        if (IsFastDoubleElementsKind(Subclass::kind())) {
          // Search for NaN in FAST_DOUBLE_ELEMENTS or
          // FAST_HOLEY_DOUBLE_ELEMENTS --- Skip The Hole and trust
          // std::isnan(elementK) for result
          auto elements = FixedDoubleArray::cast(receiver->elements());

          for (uint32_t k = start_from; k < length; ++k) {
            if (IsFastHoleyElementsKind(Subclass::kind()) &&
                elements->is_the_hole(k)) {
              continue;
            }
            if (std::isnan(elements->get_scalar(k))) return Just(true);
          }
          return Just(false);
        } else {
          // Search for NaN in FAST_ELEMENTS, FAST_HOLEY_ELEMENTS,
          // FAST_SMI_ELEMENTS or FAST_HOLEY_SMI_ELEMENTS. Return true if
          // elementK->IsHeapNumber() && std::isnan(elementK->Number())
          DCHECK(IsFastSmiOrObjectElementsKind(Subclass::kind()));
          auto elements = FixedArray::cast(receiver->elements());

          for (uint32_t k = start_from; k < length; ++k) {
            if (elements->get(k)->IsNaN()) return Just(true);
          }
          return Just(false);
        }
      }
    }
  }

2334 2335 2336 2337 2338 2339 2340
  static Handle<FixedArray> CreateListFromArrayImpl(Isolate* isolate,
                                                    Handle<JSArray> array) {
    uint32_t length = 0;
    array->length()->ToArrayLength(&length);
    Handle<FixedArray> result = isolate->factory()->NewFixedArray(length);
    Handle<FixedArrayBase> elements(array->elements(), isolate);
    for (uint32_t i = 0; i < length; i++) {
2341
      if (!Subclass::HasElementImpl(isolate, *array, i, *elements)) continue;
2342 2343 2344 2345 2346 2347 2348 2349 2350 2351
      Handle<Object> value;
      value = Subclass::GetImpl(isolate, *elements, i);
      if (value->IsName()) {
        value = isolate->factory()->InternalizeName(Handle<Name>::cast(value));
      }
      result->set(i, *value);
    }
    return result;
  }

2352
 private:
2353 2354 2355
  // SpliceShrinkStep might modify the backing_store.
  static void SpliceShrinkStep(Isolate* isolate, Handle<JSArray> receiver,
                               Handle<FixedArrayBase> backing_store,
cbruni's avatar
cbruni committed
2356 2357 2358
                               uint32_t start, uint32_t delete_count,
                               uint32_t add_count, uint32_t len,
                               uint32_t new_length) {
2359 2360
    const int move_left_count = len - delete_count - start;
    const int move_left_dst_index = start + add_count;
2361 2362 2363
    Subclass::MoveElements(isolate, receiver, backing_store,
                           move_left_dst_index, start + delete_count,
                           move_left_count, new_length, len);
cbruni's avatar
cbruni committed
2364 2365
  }

2366
  // SpliceGrowStep might modify the backing_store.
cbruni's avatar
cbruni committed
2367
  static Handle<FixedArrayBase> SpliceGrowStep(
2368 2369 2370 2371
      Isolate* isolate, Handle<JSArray> receiver,
      Handle<FixedArrayBase> backing_store, uint32_t start,
      uint32_t delete_count, uint32_t add_count, uint32_t length,
      uint32_t new_length) {
cbruni's avatar
cbruni committed
2372 2373 2374 2375
    // Check we do not overflow the new_length.
    DCHECK((add_count - delete_count) <= (Smi::kMaxValue - length));
    // Check if backing_store is big enough.
    if (new_length <= static_cast<uint32_t>(backing_store->length())) {
2376 2377 2378
      Subclass::MoveElements(isolate, receiver, backing_store,
                             start + add_count, start + delete_count,
                             (length - delete_count - start), 0, 0);
2379
      // MoveElements updates the backing_store in-place.
cbruni's avatar
cbruni committed
2380
      return backing_store;
2381
    }
cbruni's avatar
cbruni committed
2382 2383 2384
    // New backing storage is needed.
    int capacity = JSObject::NewElementsCapacity(new_length);
    // Partially copy all elements up to start.
2385 2386
    Handle<FixedArrayBase> new_elms = Subclass::ConvertElementsWithCapacity(
        receiver, backing_store, KindTraits::Kind, capacity, start);
cbruni's avatar
cbruni committed
2387
    // Copy the trailing elements after start + delete_count
2388 2389 2390 2391
    Subclass::CopyElementsImpl(*backing_store, start + delete_count, *new_elms,
                               KindTraits::Kind, start + add_count,
                               kPackedSizeNotKnown,
                               ElementsAccessor::kCopyToEndAndInitializeToHole);
cbruni's avatar
cbruni committed
2392 2393
    receiver->set_elements(*new_elms);
    return new_elms;
2394 2395
  }

cbruni's avatar
cbruni committed
2396 2397
  static Handle<Object> RemoveElement(Handle<JSArray> receiver,
                                      Where remove_position) {
2398
    Isolate* isolate = receiver->GetIsolate();
2399 2400 2401 2402 2403 2404
    ElementsKind kind = KindTraits::Kind;
    if (IsFastSmiOrObjectElementsKind(kind)) {
      HandleScope scope(isolate);
      JSObject::EnsureWritableFastElements(receiver);
    }
    Handle<FixedArrayBase> backing_store(receiver->elements(), isolate);
cbruni's avatar
cbruni committed
2405 2406 2407 2408 2409
    uint32_t length =
        static_cast<uint32_t>(Smi::cast(receiver->length())->value());
    DCHECK(length > 0);
    int new_length = length - 1;
    int remove_index = remove_position == AT_START ? 0 : new_length;
2410 2411
    Handle<Object> result =
        Subclass::GetImpl(isolate, *backing_store, remove_index);
cbruni's avatar
cbruni committed
2412
    if (remove_position == AT_START) {
2413 2414
      Subclass::MoveElements(isolate, receiver, backing_store, 0, 1, new_length,
                             0, 0);
cbruni's avatar
cbruni committed
2415
    }
2416
    Subclass::SetLengthImpl(isolate, receiver, new_length, backing_store);
2417

2418
    if (IsHoleyElementsKind(kind) && result->IsTheHole(isolate)) {
2419
      return isolate->factory()->undefined_value();
cbruni's avatar
cbruni committed
2420 2421 2422 2423 2424 2425 2426
    }
    return result;
  }

  static uint32_t AddArguments(Handle<JSArray> receiver,
                               Handle<FixedArrayBase> backing_store,
                               Arguments* args, uint32_t add_size,
2427
                               Where add_position) {
cbruni's avatar
cbruni committed
2428
    uint32_t length = Smi::cast(receiver->length())->value();
2429
    DCHECK(0 < add_size);
cbruni's avatar
cbruni committed
2430 2431 2432 2433 2434 2435
    uint32_t elms_len = backing_store->length();
    // Check we do not overflow the new_length.
    DCHECK(add_size <= static_cast<uint32_t>(Smi::kMaxValue - length));
    uint32_t new_length = length + add_size;

    if (new_length > elms_len) {
2436
      // New backing storage is needed.
cbruni's avatar
cbruni committed
2437 2438
      uint32_t capacity = JSObject::NewElementsCapacity(new_length);
      // If we add arguments to the start we have to shift the existing objects.
2439
      int copy_dst_index = add_position == AT_START ? add_size : 0;
cbruni's avatar
cbruni committed
2440
      // Copy over all objects to a new backing_store.
2441
      backing_store = Subclass::ConvertElementsWithCapacity(
cbruni's avatar
cbruni committed
2442 2443 2444
          receiver, backing_store, KindTraits::Kind, capacity, 0,
          copy_dst_index, ElementsAccessor::kCopyToEndAndInitializeToHole);
      receiver->set_elements(*backing_store);
2445
    } else if (add_position == AT_START) {
cbruni's avatar
cbruni committed
2446 2447 2448
      // If the backing store has enough capacity and we add elements to the
      // start we have to shift the existing objects.
      Isolate* isolate = receiver->GetIsolate();
2449 2450
      Subclass::MoveElements(isolate, receiver, backing_store, add_size, 0,
                             length, 0, 0);
cbruni's avatar
cbruni committed
2451
    }
2452

2453
    int insertion_index = add_position == AT_START ? 0 : length;
cbruni's avatar
cbruni committed
2454
    // Copy the arguments to the start.
2455
    Subclass::CopyArguments(args, backing_store, add_size, 1, insertion_index);
cbruni's avatar
cbruni committed
2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468
    // Set the length.
    receiver->set_length(Smi::FromInt(new_length));
    return new_length;
  }

  static void CopyArguments(Arguments* args, Handle<FixedArrayBase> dst_store,
                            uint32_t copy_size, uint32_t src_index,
                            uint32_t dst_index) {
    // Add the provided values.
    DisallowHeapAllocation no_gc;
    FixedArrayBase* raw_backing_store = *dst_store;
    WriteBarrierMode mode = raw_backing_store->GetWriteBarrierMode(no_gc);
    for (uint32_t i = 0; i < copy_size; i++) {
2469
      Object* argument = (*args)[src_index + i];
2470
      DCHECK(!argument->IsTheHole(raw_backing_store->GetIsolate()));
2471
      Subclass::SetImpl(raw_backing_store, dst_index + i, argument, mode);
2472 2473
    }
  }
2474 2475
};

2476
template <typename Subclass, typename KindTraits>
2477
class FastSmiOrObjectElementsAccessor
2478
    : public FastElementsAccessor<Subclass, KindTraits> {
2479 2480
 public:
  explicit FastSmiOrObjectElementsAccessor(const char* name)
2481
      : FastElementsAccessor<Subclass, KindTraits>(name) {}
2482

2483 2484 2485 2486 2487
  static inline void SetImpl(Handle<JSObject> holder, uint32_t entry,
                             Object* value) {
    SetImpl(holder->elements(), entry, value);
  }

2488 2489 2490 2491 2492 2493 2494 2495 2496 2497
  static inline void SetImpl(FixedArrayBase* backing_store, uint32_t entry,
                             Object* value) {
    FixedArray::cast(backing_store)->set(entry, value);
  }

  static inline void SetImpl(FixedArrayBase* backing_store, uint32_t entry,
                             Object* value, WriteBarrierMode mode) {
    FixedArray::cast(backing_store)->set(entry, value, mode);
  }

2498
  static Object* GetRaw(FixedArray* backing_store, uint32_t entry) {
2499
    uint32_t index = Subclass::GetIndexForEntryImpl(backing_store, entry);
2500 2501 2502
    return backing_store->get(index);
  }

2503 2504 2505 2506 2507 2508 2509 2510
  // NOTE: this method violates the handlified function signature convention:
  // raw pointer parameters in the function that allocates.
  // See ElementsAccessor::CopyElements() for details.
  // This method could actually allocate if copying from double elements to
  // object elements.
  static void CopyElementsImpl(FixedArrayBase* from, uint32_t from_start,
                               FixedArrayBase* to, ElementsKind from_kind,
                               uint32_t to_start, int packed_size,
2511
                               int copy_size) {
2512
    DisallowHeapAllocation no_gc;
2513 2514 2515 2516 2517 2518
    ElementsKind to_kind = KindTraits::Kind;
    switch (from_kind) {
      case FAST_SMI_ELEMENTS:
      case FAST_HOLEY_SMI_ELEMENTS:
      case FAST_ELEMENTS:
      case FAST_HOLEY_ELEMENTS:
2519
        CopyObjectToObjectElements(from, from_kind, from_start, to, to_kind,
2520
                                   to_start, copy_size);
2521
        break;
2522
      case FAST_DOUBLE_ELEMENTS:
2523 2524
      case FAST_HOLEY_DOUBLE_ELEMENTS: {
        AllowHeapAllocation allow_allocation;
2525 2526
        DCHECK(IsFastObjectElementsKind(to_kind));
        CopyDoubleToObjectElements(from, from_start, to, to_start, copy_size);
2527
        break;
2528
      }
2529
      case DICTIONARY_ELEMENTS:
2530 2531
        CopyDictionaryToObjectElements(from, from_start, to, to_kind, to_start,
                                       copy_size);
2532
        break;
2533 2534
      case FAST_SLOPPY_ARGUMENTS_ELEMENTS:
      case SLOW_SLOPPY_ARGUMENTS_ELEMENTS:
2535 2536
      case FAST_STRING_WRAPPER_ELEMENTS:
      case SLOW_STRING_WRAPPER_ELEMENTS:
2537
#define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) case TYPE##_ELEMENTS:
2538 2539
      TYPED_ARRAYS(TYPED_ARRAY_CASE)
#undef TYPED_ARRAY_CASE
2540 2541 2542 2543 2544 2545
      // This function is currently only used for JSArrays with non-zero
      // length.
      UNREACHABLE();
      break;
      case NO_ELEMENTS:
        break;  // Nothing to do.
2546 2547
    }
  }
2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574

  static Maybe<int64_t> IndexOfValueImpl(Isolate* isolate,
                                         Handle<JSObject> receiver,
                                         Handle<Object> search_value,
                                         uint32_t start_from, uint32_t length) {
    DCHECK(JSObject::PrototypeHasNoElements(isolate, *receiver));
    DisallowHeapAllocation no_gc;
    FixedArrayBase* elements_base = receiver->elements();
    Object* value = *search_value;

    if (start_from >= length) return Just<int64_t>(-1);

    length = std::min(static_cast<uint32_t>(elements_base->length()), length);

    // Only FAST_{,HOLEY_}ELEMENTS can store non-numbers.
    if (!value->IsNumber() && !IsFastObjectElementsKind(Subclass::kind())) {
      return Just<int64_t>(-1);
    }
    // NaN can never be found by strict equality.
    if (value->IsNaN()) return Just<int64_t>(-1);

    FixedArray* elements = FixedArray::cast(receiver->elements());
    for (uint32_t k = start_from; k < length; ++k) {
      if (value->StrictEquals(elements->get(k))) return Just<int64_t>(k);
    }
    return Just<int64_t>(-1);
  }
2575
};
2576

2577

2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598
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) {}
2599 2600 2601
};


2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624
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) {}
};

2625
template <typename Subclass, typename KindTraits>
2626
class FastDoubleElementsAccessor
2627
    : public FastElementsAccessor<Subclass, KindTraits> {
2628 2629
 public:
  explicit FastDoubleElementsAccessor(const char* name)
2630
      : FastElementsAccessor<Subclass, KindTraits>(name) {}
2631

2632 2633
  static Handle<Object> GetImpl(Isolate* isolate, FixedArrayBase* backing_store,
                                uint32_t entry) {
2634 2635 2636 2637 2638 2639 2640 2641 2642
    return FixedDoubleArray::get(FixedDoubleArray::cast(backing_store), entry,
                                 isolate);
  }

  static inline void SetImpl(Handle<JSObject> holder, uint32_t entry,
                             Object* value) {
    SetImpl(holder->elements(), entry, value);
  }

2643 2644 2645 2646 2647 2648 2649 2650 2651 2652
  static inline void SetImpl(FixedArrayBase* backing_store, uint32_t entry,
                             Object* value) {
    FixedDoubleArray::cast(backing_store)->set(entry, value->Number());
  }

  static inline void SetImpl(FixedArrayBase* backing_store, uint32_t entry,
                             Object* value, WriteBarrierMode mode) {
    FixedDoubleArray::cast(backing_store)->set(entry, value->Number());
  }

2653 2654 2655
  static void CopyElementsImpl(FixedArrayBase* from, uint32_t from_start,
                               FixedArrayBase* to, ElementsKind from_kind,
                               uint32_t to_start, int packed_size,
2656
                               int copy_size) {
2657
    DisallowHeapAllocation no_allocation;
2658
    switch (from_kind) {
2659
      case FAST_SMI_ELEMENTS:
2660
        CopyPackedSmiToDoubleElements(from, from_start, to, to_start,
2661
                                      packed_size, copy_size);
2662
        break;
2663
      case FAST_HOLEY_SMI_ELEMENTS:
2664
        CopySmiToDoubleElements(from, from_start, to, to_start, copy_size);
2665
        break;
2666
      case FAST_DOUBLE_ELEMENTS:
2667
      case FAST_HOLEY_DOUBLE_ELEMENTS:
2668
        CopyDoubleToDoubleElements(from, from_start, to, to_start, copy_size);
2669 2670 2671
        break;
      case FAST_ELEMENTS:
      case FAST_HOLEY_ELEMENTS:
2672
        CopyObjectToDoubleElements(from, from_start, to, to_start, copy_size);
2673 2674
        break;
      case DICTIONARY_ELEMENTS:
2675
        CopyDictionaryToDoubleElements(from, from_start, to, to_start,
2676
                                       copy_size);
2677
        break;
2678 2679
      case FAST_SLOPPY_ARGUMENTS_ELEMENTS:
      case SLOW_SLOPPY_ARGUMENTS_ELEMENTS:
2680 2681 2682 2683
      case FAST_STRING_WRAPPER_ELEMENTS:
      case SLOW_STRING_WRAPPER_ELEMENTS:
      case NO_ELEMENTS:
#define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) case TYPE##_ELEMENTS:
2684 2685
      TYPED_ARRAYS(TYPED_ARRAY_CASE)
#undef TYPED_ARRAY_CASE
2686 2687 2688 2689
      // This function is currently only used for JSArrays with non-zero
      // length.
      UNREACHABLE();
      break;
2690 2691
    }
  }
2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703

  static Maybe<int64_t> IndexOfValueImpl(Isolate* isolate,
                                         Handle<JSObject> receiver,
                                         Handle<Object> search_value,
                                         uint32_t start_from, uint32_t length) {
    DCHECK(JSObject::PrototypeHasNoElements(isolate, *receiver));
    DisallowHeapAllocation no_gc;
    FixedArrayBase* elements_base = receiver->elements();
    Object* value = *search_value;

    length = std::min(static_cast<uint32_t>(elements_base->length()), length);

2704 2705
    if (start_from >= length) return Just<int64_t>(-1);

2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724
    if (!value->IsNumber()) {
      return Just<int64_t>(-1);
    }
    if (value->IsNaN()) {
      return Just<int64_t>(-1);
    }
    double numeric_search_value = value->Number();
    FixedDoubleArray* elements = FixedDoubleArray::cast(receiver->elements());

    for (uint32_t k = start_from; k < length; ++k) {
      if (elements->is_the_hole(k)) {
        continue;
      }
      if (elements->get_scalar(k) == numeric_search_value) {
        return Just<int64_t>(k);
      }
    }
    return Just<int64_t>(-1);
  }
2725
};
2726

2727

2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748
class FastPackedDoubleElementsAccessor
    : public FastDoubleElementsAccessor<
        FastPackedDoubleElementsAccessor,
        ElementsKindTraits<FAST_DOUBLE_ELEMENTS> > {
 public:
  explicit FastPackedDoubleElementsAccessor(const char* name)
      : FastDoubleElementsAccessor<
          FastPackedDoubleElementsAccessor,
          ElementsKindTraits<FAST_DOUBLE_ELEMENTS> >(name) {}
};


class FastHoleyDoubleElementsAccessor
    : public FastDoubleElementsAccessor<
        FastHoleyDoubleElementsAccessor,
        ElementsKindTraits<FAST_HOLEY_DOUBLE_ELEMENTS> > {
 public:
  explicit FastHoleyDoubleElementsAccessor(const char* name)
      : FastDoubleElementsAccessor<
          FastHoleyDoubleElementsAccessor,
          ElementsKindTraits<FAST_HOLEY_DOUBLE_ELEMENTS> >(name) {}
2749 2750 2751 2752
};


// Super class for all external element arrays.
2753
template <ElementsKind Kind, typename ctype>
2754
class TypedElementsAccessor
2755 2756
    : public ElementsAccessorBase<TypedElementsAccessor<Kind, ctype>,
                                  ElementsKindTraits<Kind>> {
2757
 public:
2758
  explicit TypedElementsAccessor(const char* name)
2759
      : ElementsAccessorBase<AccessorClass,
2760
                             ElementsKindTraits<Kind> >(name) {}
2761

2762
  typedef typename ElementsKindTraits<Kind>::BackingStore BackingStore;
2763
  typedef TypedElementsAccessor<Kind, ctype> AccessorClass;
2764

2765 2766 2767 2768 2769
  static inline void SetImpl(Handle<JSObject> holder, uint32_t entry,
                             Object* value) {
    SetImpl(holder->elements(), entry, value);
  }

2770 2771 2772 2773 2774 2775 2776 2777 2778 2779
  static inline void SetImpl(FixedArrayBase* backing_store, uint32_t entry,
                             Object* value) {
    BackingStore::cast(backing_store)->SetValue(entry, value);
  }

  static inline void SetImpl(FixedArrayBase* backing_store, uint32_t entry,
                             Object* value, WriteBarrierMode mode) {
    BackingStore::cast(backing_store)->SetValue(entry, value);
  }

2780 2781
  static Handle<Object> GetImpl(Isolate* isolate, FixedArrayBase* backing_store,
                                uint32_t entry) {
2782 2783 2784 2785
    return BackingStore::get(BackingStore::cast(backing_store), entry);
  }

  static PropertyDetails GetDetailsImpl(JSObject* holder, uint32_t entry) {
2786
    return PropertyDetails(kData, DONT_DELETE, 0, PropertyCellType::kNoCell);
2787
  }
2788

2789
  static PropertyDetails GetDetailsImpl(FixedArrayBase* backing_store,
2790
                                        uint32_t entry) {
2791
    return PropertyDetails(kData, DONT_DELETE, 0, PropertyCellType::kNoCell);
2792 2793
  }

2794 2795
  static bool HasElementImpl(Isolate* isolate, JSObject* holder, uint32_t index,
                             FixedArrayBase* backing_store,
2796
                             PropertyFilter filter) {
2797
    return index < AccessorClass::GetCapacityImpl(holder, backing_store);
2798 2799
  }

2800 2801 2802 2803 2804
  static bool HasAccessorsImpl(JSObject* holder,
                               FixedArrayBase* backing_store) {
    return false;
  }

2805 2806
  static void SetLengthImpl(Isolate* isolate, Handle<JSArray> array,
                            uint32_t length,
2807
                            Handle<FixedArrayBase> backing_store) {
2808 2809 2810 2811
    // External arrays do not support changing their length.
    UNREACHABLE();
  }

2812
  static void DeleteImpl(Handle<JSObject> obj, uint32_t entry) {
2813
    UNREACHABLE();
2814
  }
2815

2816 2817 2818 2819 2820
  static uint32_t GetIndexForEntryImpl(FixedArrayBase* backing_store,
                                       uint32_t entry) {
    return entry;
  }

2821
  static uint32_t GetEntryForIndexImpl(Isolate* isolate, JSObject* holder,
2822
                                       FixedArrayBase* backing_store,
2823
                                       uint32_t index, PropertyFilter filter) {
2824 2825
    return index < AccessorClass::GetCapacityImpl(holder, backing_store)
               ? index
2826
               : kMaxUInt32;
2827
  }
2828

2829 2830 2831 2832 2833
  static bool WasNeutered(JSObject* holder) {
    JSArrayBufferView* view = JSArrayBufferView::cast(holder);
    return view->WasNeutered();
  }

2834 2835
  static uint32_t GetCapacityImpl(JSObject* holder,
                                  FixedArrayBase* backing_store) {
2836
    if (WasNeutered(holder)) return 0;
2837 2838
    return backing_store->length();
  }
2839

2840 2841 2842 2843 2844
  static uint32_t NumberOfElementsImpl(JSObject* receiver,
                                       FixedArrayBase* backing_store) {
    return AccessorClass::GetCapacityImpl(receiver, backing_store);
  }

2845 2846 2847
  static void AddElementsToKeyAccumulatorImpl(Handle<JSObject> receiver,
                                              KeyAccumulator* accumulator,
                                              AddKeyConversion convert) {
2848
    Isolate* isolate = receiver->GetIsolate();
2849
    Handle<FixedArrayBase> elements(receiver->elements());
2850 2851
    uint32_t length = AccessorClass::GetCapacityImpl(*receiver, *elements);
    for (uint32_t i = 0; i < length; i++) {
2852
      Handle<Object> value = AccessorClass::GetImpl(isolate, *elements, i);
2853 2854 2855
      accumulator->AddKey(value, convert);
    }
  }
2856 2857 2858 2859 2860 2861 2862 2863 2864 2865

  static Maybe<bool> CollectValuesOrEntriesImpl(
      Isolate* isolate, Handle<JSObject> object,
      Handle<FixedArray> values_or_entries, bool get_entries, int* nof_items,
      PropertyFilter filter) {
    int count = 0;
    if ((filter & ONLY_CONFIGURABLE) == 0) {
      Handle<FixedArrayBase> elements(object->elements());
      uint32_t length = AccessorClass::GetCapacityImpl(*object, *elements);
      for (uint32_t index = 0; index < length; ++index) {
2866 2867
        Handle<Object> value =
            AccessorClass::GetImpl(isolate, *elements, index);
2868 2869 2870 2871 2872 2873 2874 2875 2876
        if (get_entries) {
          value = MakeEntryPair(isolate, index, value);
        }
        values_or_entries->set(count++, *value);
      }
    }
    *nof_items = count;
    return Just(true);
  }
2877

2878 2879 2880 2881 2882
  static Object* FillImpl(Isolate* isolate, Handle<JSObject> receiver,
                          Handle<Object> obj_value, uint32_t start,
                          uint32_t end) {
    Handle<JSTypedArray> array = Handle<JSTypedArray>::cast(receiver);
    DCHECK(!array->WasNeutered());
2883
    DCHECK(obj_value->IsNumber());
2884

2885
    ctype value;
2886
    if (obj_value->IsSmi()) {
2887
      value = BackingStore::from(Smi::cast(*obj_value)->value());
2888
    } else {
2889
      DCHECK(obj_value->IsHeapNumber());
2890
      value = BackingStore::from(HeapNumber::cast(*obj_value)->value());
2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904
    }

    // Ensure indexes are within array bounds
    DCHECK_LE(0, start);
    DCHECK_LE(start, end);
    DCHECK_LE(end, array->length_value());

    DisallowHeapAllocation no_gc;
    BackingStore* elements = BackingStore::cast(receiver->elements());
    ctype* data = static_cast<ctype*>(elements->DataPtr());
    std::fill(data + start, data + end, value);
    return *array;
  }

2905 2906 2907 2908 2909
  static Maybe<bool> IncludesValueImpl(Isolate* isolate,
                                       Handle<JSObject> receiver,
                                       Handle<Object> value,
                                       uint32_t start_from, uint32_t length) {
    DisallowHeapAllocation no_gc;
2910

2911 2912 2913 2914 2915 2916
    // TODO(caitp): return Just(false) here when implementing strict throwing on
    // neutered views.
    if (WasNeutered(*receiver)) {
      return Just(value->IsUndefined(isolate) && length > start_from);
    }

2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937
    BackingStore* elements = BackingStore::cast(receiver->elements());
    if (value->IsUndefined(isolate) &&
        length > static_cast<uint32_t>(elements->length())) {
      return Just(true);
    }
    if (!value->IsNumber()) return Just(false);

    double search_value = value->Number();

    if (!std::isfinite(search_value)) {
      // Integral types cannot represent +Inf or NaN
      if (AccessorClass::kind() < FLOAT32_ELEMENTS ||
          AccessorClass::kind() > FLOAT64_ELEMENTS) {
        return Just(false);
      }
    } else if (search_value < std::numeric_limits<ctype>::lowest() ||
               search_value > std::numeric_limits<ctype>::max()) {
      // Return false if value can't be represented in this space
      return Just(false);
    }

2938 2939 2940 2941 2942 2943
    // Prototype has no elements, and not searching for the hole --- limit
    // search to backing store length.
    if (static_cast<uint32_t>(elements->length()) < length) {
      length = elements->length();
    }

2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957
    if (!std::isnan(search_value)) {
      for (uint32_t k = start_from; k < length; ++k) {
        double element_k = elements->get_scalar(k);
        if (element_k == search_value) return Just(true);
      }
      return Just(false);
    } else {
      for (uint32_t k = start_from; k < length; ++k) {
        double element_k = elements->get_scalar(k);
        if (std::isnan(element_k)) return Just(true);
      }
      return Just(false);
    }
  }
2958 2959 2960 2961 2962 2963 2964

  static Maybe<int64_t> IndexOfValueImpl(Isolate* isolate,
                                         Handle<JSObject> receiver,
                                         Handle<Object> value,
                                         uint32_t start_from, uint32_t length) {
    DisallowHeapAllocation no_gc;

2965 2966
    if (WasNeutered(*receiver)) return Just<int64_t>(-1);

2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004
    BackingStore* elements = BackingStore::cast(receiver->elements());
    if (!value->IsNumber()) return Just<int64_t>(-1);

    double search_value = value->Number();

    if (!std::isfinite(search_value)) {
      // Integral types cannot represent +Inf or NaN.
      if (AccessorClass::kind() < FLOAT32_ELEMENTS ||
          AccessorClass::kind() > FLOAT64_ELEMENTS) {
        return Just<int64_t>(-1);
      }
    } else if (search_value < std::numeric_limits<ctype>::lowest() ||
               search_value > std::numeric_limits<ctype>::max()) {
      // Return false if value can't be represented in this ElementsKind.
      return Just<int64_t>(-1);
    }

    // Prototype has no elements, and not searching for the hole --- limit
    // search to backing store length.
    if (static_cast<uint32_t>(elements->length()) < length) {
      length = elements->length();
    }

    if (std::isnan(search_value)) {
      return Just<int64_t>(-1);
    }

    ctype typed_search_value = static_cast<ctype>(search_value);
    if (static_cast<double>(typed_search_value) != search_value) {
      return Just<int64_t>(-1);  // Loss of precision.
    }

    for (uint32_t k = start_from; k < length; ++k) {
      ctype element_k = elements->get_scalar(k);
      if (element_k == typed_search_value) return Just<int64_t>(k);
    }
    return Just<int64_t>(-1);
  }
3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045

  static Maybe<int64_t> LastIndexOfValueImpl(Isolate* isolate,
                                             Handle<JSObject> receiver,
                                             Handle<Object> value,
                                             uint32_t start_from) {
    DisallowHeapAllocation no_gc;
    DCHECK(!WasNeutered(*receiver));

    if (!value->IsNumber()) return Just<int64_t>(-1);
    BackingStore* elements = BackingStore::cast(receiver->elements());

    double search_value = value->Number();

    if (!std::isfinite(search_value)) {
      if (std::is_integral<ctype>::value) {
        // Integral types cannot represent +Inf or NaN.
        return Just<int64_t>(-1);
      } else if (std::isnan(search_value)) {
        // Strict Equality Comparison of NaN is always false.
        return Just<int64_t>(-1);
      }
    } else if (search_value < std::numeric_limits<ctype>::lowest() ||
               search_value > std::numeric_limits<ctype>::max()) {
      // Return -1 if value can't be represented in this ElementsKind.
      return Just<int64_t>(-1);
    }

    ctype typed_search_value = static_cast<ctype>(search_value);
    if (static_cast<double>(typed_search_value) != search_value) {
      return Just<int64_t>(-1);  // Loss of precision.
    }

    DCHECK_LT(start_from, elements->length());

    uint32_t k = start_from;
    do {
      ctype element_k = elements->get_scalar(k);
      if (element_k == typed_search_value) return Just<int64_t>(k);
    } while (k-- != 0);
    return Just<int64_t>(-1);
  }
3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058

  static void ReverseImpl(JSObject* receiver) {
    DisallowHeapAllocation no_gc;
    DCHECK(!WasNeutered(receiver));

    BackingStore* elements = BackingStore::cast(receiver->elements());

    uint32_t len = elements->length();
    if (len == 0) return;

    ctype* data = static_cast<ctype*>(elements->DataPtr());
    std::reverse(data, data + len);
  }
3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083

  static Handle<JSObject> SliceWithResultImpl(Handle<JSObject> receiver,
                                              uint32_t start, uint32_t end,
                                              Handle<JSObject> result) {
    Isolate* isolate = receiver->GetIsolate();
    DCHECK(!WasNeutered(*receiver));
    DCHECK(result->IsJSTypedArray());
    DCHECK(!WasNeutered(*result));
    DCHECK_LE(start, end);

    Handle<JSTypedArray> array = Handle<JSTypedArray>::cast(receiver);
    Handle<JSTypedArray> result_array = Handle<JSTypedArray>::cast(result);
    DCHECK_LE(end, array->length_value());

    // Fast path for the same type result array
    if (result_array->type() == array->type()) {
      int64_t element_size = array->element_size();
      int64_t count = end - start;

      DisallowHeapAllocation no_gc;
      BackingStore* src_elements = BackingStore::cast(receiver->elements());
      BackingStore* result_elements =
          BackingStore::cast(result_array->elements());

      DCHECK_LE(count, result_elements->length());
3084 3085
      uint8_t* src =
          static_cast<uint8_t*>(src_elements->DataPtr()) + start * element_size;
3086
      uint8_t* result = static_cast<uint8_t*>(result_elements->DataPtr());
3087 3088 3089 3090 3091 3092 3093 3094 3095 3096
      if (array->buffer() != result_array->buffer()) {
        std::memcpy(result, src, count * element_size);
      } else {
        // The spec defines the copy-step iteratively, which means that we
        // cannot use memcpy if the buffer is shared.
        uint8_t* end = src + count * element_size;
        while (src < end) {
          *result++ = *src++;
        }
      }
3097 3098 3099 3100 3101 3102 3103 3104 3105
      return result_array;
    }

    // If the types of the two typed arrays are different, properly convert
    // elements
    Handle<BackingStore> from(BackingStore::cast(array->elements()), isolate);
    ElementsAccessor* result_accessor = result_array->GetElementsAccessor();
    for (uint32_t i = start; i < end; i++) {
      Handle<Object> elem = AccessorClass::GetImpl(isolate, *from, i);
3106
      result_accessor->Set(result_array, i - start, *elem);
3107 3108 3109
    }
    return result_array;
  }
3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140

  static bool HasSimpleRepresentation(InstanceType type) {
    return !(type == FIXED_FLOAT32_ARRAY_TYPE ||
             type == FIXED_FLOAT64_ARRAY_TYPE ||
             type == FIXED_UINT8_CLAMPED_ARRAY_TYPE);
  }

  template <typename SourceTraits>
  static void CopyBetweenBackingStores(FixedTypedArrayBase* source,
                                       BackingStore* dest, size_t length) {
    FixedTypedArray<SourceTraits>* source_fta =
        FixedTypedArray<SourceTraits>::cast(source);
    for (uint32_t i = 0; i < length; i++) {
      typename SourceTraits::ElementType elem = source_fta->get_scalar(i);
      dest->set(i, dest->from(elem));
    }
  }

  static void CopyElementsHandleFromTypedArray(Handle<JSTypedArray> source,
                                               Handle<JSTypedArray> destination,
                                               size_t length) {
    // The source is a typed array, so we know we don't need to do ToNumber
    // side-effects, as the source elements will always be a number or
    // undefined.
    DisallowHeapAllocation no_gc;

    Handle<FixedTypedArrayBase> source_elements(
        FixedTypedArrayBase::cast(source->elements()));
    Handle<BackingStore> destination_elements(
        BackingStore::cast(destination->elements()));

3141
    DCHECK_GE(destination->length(), source->length());
3142 3143 3144 3145 3146 3147 3148 3149
    DCHECK(source->length()->IsSmi());
    DCHECK_EQ(Smi::FromInt(static_cast<int>(length)), source->length());

    InstanceType source_type = source_elements->map()->instance_type();
    InstanceType destination_type =
        destination_elements->map()->instance_type();

    bool same_type = source_type == destination_type;
3150
    bool same_size = source->element_size() == destination->element_size();
3151 3152 3153
    bool both_are_simple = HasSimpleRepresentation(source_type) &&
                           HasSimpleRepresentation(destination_type);

3154 3155 3156 3157 3158
    // We assume the source and destination don't overlap, even though they
    // can share the same buffer. This is always true for newly allocated
    // TypedArrays.
    uint8_t* source_data = static_cast<uint8_t*>(source_elements->DataPtr());
    uint8_t* dest_data = static_cast<uint8_t*>(destination_elements->DataPtr());
3159 3160
    size_t source_byte_length = NumberToSize(source->byte_length());
    size_t dest_byte_length = NumberToSize(destination->byte_length());
3161 3162 3163
    CHECK(dest_data + dest_byte_length <= source_data ||
          source_data + source_byte_length <= dest_data);

3164 3165 3166 3167 3168
    // We can simply copy the backing store if the types are the same, or if
    // we are converting e.g. Uint8 <-> Int8, as the binary representation
    // will be the same. This is not the case for floats or clamped Uint8,
    // which have special conversion operations.
    if (same_type || (same_size && both_are_simple)) {
3169 3170
      size_t element_size = source->element_size();
      std::memcpy(dest_data, source_data, length * element_size);
3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188
    } else {
      // We use scalar accessors below to avoid boxing/unboxing, so there are
      // no allocations.
      switch (source->GetElementsKind()) {
#define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size)   \
  case TYPE##_ELEMENTS:                                   \
    CopyBetweenBackingStores<Type##ArrayTraits>(          \
        *source_elements, *destination_elements, length); \
    break;
        TYPED_ARRAYS(TYPED_ARRAY_CASE)
        default:
          UNREACHABLE();
          break;
      }
#undef TYPED_ARRAY_CASE
    }
  }

3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202
  static bool HoleyPrototypeLookupRequired(Isolate* isolate,
                                           Handle<JSArray> source) {
    Object* source_proto = source->map()->prototype();
    // Null prototypes are OK - we don't need to do prototype chain lookups on
    // them.
    if (source_proto->IsNull(isolate)) return false;
    if (source_proto->IsJSProxy()) return true;
    DCHECK(source_proto->IsJSObject());
    if (!isolate->is_initial_array_prototype(JSObject::cast(source_proto))) {
      return true;
    }
    return !isolate->IsFastArrayConstructorPrototypeChainIntact();
  }

3203 3204 3205
  static bool TryCopyElementsHandleFastNumber(Handle<JSArray> source,
                                              Handle<JSTypedArray> destination,
                                              size_t length) {
3206
    Isolate* isolate = source->GetIsolate();
3207
    DisallowHeapAllocation no_gc;
3208 3209
    DisallowJavascriptExecution no_js(isolate);

3210 3211 3212
    ElementsKind kind = source->GetElementsKind();
    BackingStore* dest = BackingStore::cast(destination->elements());

3213 3214 3215 3216 3217 3218 3219 3220 3221 3222
    // When we find the hole, we normally have to look up the element on the
    // prototype chain, which is not handled here and we return false instead.
    // When the array has the original array prototype, and that prototype has
    // not been changed in a way that would affect lookups, we can just convert
    // the hole into undefined.
    if (HoleyPrototypeLookupRequired(isolate, source)) return false;

    Object* undefined = isolate->heap()->undefined_value();

    // Fastpath for packed Smi kind.
3223 3224 3225 3226 3227 3228 3229 3230 3231 3232
    if (kind == FAST_SMI_ELEMENTS) {
      FixedArray* source_store = FixedArray::cast(source->elements());

      for (uint32_t i = 0; i < length; i++) {
        Object* elem = source_store->get(i);
        DCHECK(elem->IsSmi());
        int int_value = Smi::cast(elem)->value();
        dest->set(i, dest->from(int_value));
      }
      return true;
3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245
    } else if (kind == FAST_HOLEY_SMI_ELEMENTS) {
      FixedArray* source_store = FixedArray::cast(source->elements());
      for (uint32_t i = 0; i < length; i++) {
        if (source_store->is_the_hole(isolate, i)) {
          dest->SetValue(i, undefined);
        } else {
          Object* elem = source_store->get(i);
          DCHECK(elem->IsSmi());
          int int_value = Smi::cast(elem)->value();
          dest->set(i, dest->from(int_value));
        }
      }
      return true;
3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258
    } else if (kind == FAST_DOUBLE_ELEMENTS) {
      // Fastpath for packed double kind. We avoid boxing and then immediately
      // unboxing the double here by using get_scalar.
      FixedDoubleArray* source_store =
          FixedDoubleArray::cast(source->elements());

      for (uint32_t i = 0; i < length; i++) {
        // Use the from_double conversion for this specific TypedArray type,
        // rather than relying on C++ to convert elem.
        double elem = source_store->get_scalar(i);
        dest->set(i, dest->from(elem));
      }
      return true;
3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270
    } else if (kind == FAST_HOLEY_DOUBLE_ELEMENTS) {
      FixedDoubleArray* source_store =
          FixedDoubleArray::cast(source->elements());
      for (uint32_t i = 0; i < length; i++) {
        if (source_store->is_the_hole(i)) {
          dest->SetValue(i, undefined);
        } else {
          double elem = source_store->get_scalar(i);
          dest->set(i, dest->from(elem));
        }
      }
      return true;
3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295
    }
    return false;
  }

  static Object* CopyElementsHandleSlow(Handle<JSReceiver> source,
                                        Handle<JSTypedArray> destination,
                                        size_t length) {
    Isolate* isolate = source->GetIsolate();
    Handle<BackingStore> destination_elements(
        BackingStore::cast(destination->elements()));
    for (uint32_t i = 0; i < length; i++) {
      LookupIterator it(isolate, source, i, source);
      Handle<Object> elem;
      ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, elem,
                                         Object::GetProperty(&it));
      ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, elem, Object::ToNumber(elem));
      // We don't need to check for buffer neutering here, because the
      // source cannot be a TypedArray.
      // The spec says we store the length, then get each element, so we don't
      // need to check changes to length.
      destination_elements->SetValue(i, *elem);
    }
    return Smi::kZero;
  }

3296 3297 3298
  // This doesn't guarantee that the destination array will be completely
  // filled. The caller must do this by passing a source with equal length, if
  // that is required.
3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323
  static Object* CopyElementsHandleImpl(Handle<JSReceiver> source,
                                        Handle<JSObject> destination,
                                        size_t length) {
    Handle<JSTypedArray> destination_ta =
        Handle<JSTypedArray>::cast(destination);

    // All conversions from TypedArrays can be done without allocation.
    if (source->IsJSTypedArray()) {
      Handle<JSTypedArray> source_ta = Handle<JSTypedArray>::cast(source);
      CopyElementsHandleFromTypedArray(source_ta, destination_ta, length);
      return Smi::kZero;
    }

    // Fast cases for packed numbers kinds where we don't need to allocate.
    if (source->IsJSArray()) {
      Handle<JSArray> source_array = Handle<JSArray>::cast(source);
      if (TryCopyElementsHandleFastNumber(source_array, destination_ta,
                                          length)) {
        return Smi::kZero;
      }
    }
    // Final generic case that handles prototype chain lookups, getters, proxies
    // and observable side effects via valueOf, etc.
    return CopyElementsHandleSlow(source, destination_ta, length);
  }
3324
};
3325

3326 3327
#define FIXED_ELEMENTS_ACCESSOR(Type, type, TYPE, ctype, size) \
  typedef TypedElementsAccessor<TYPE##_ELEMENTS, ctype>        \
3328
      Fixed##Type##ElementsAccessor;
3329

3330 3331
TYPED_ARRAYS(FIXED_ELEMENTS_ACCESSOR)
#undef FIXED_ELEMENTS_ACCESSOR
3332

3333
template <typename Subclass, typename ArgumentsAccessor, typename KindTraits>
3334
class SloppyArgumentsElementsAccessor
3335
    : public ElementsAccessorBase<Subclass, KindTraits> {
3336 3337
 public:
  explicit SloppyArgumentsElementsAccessor(const char* name)
3338
      : ElementsAccessorBase<Subclass, KindTraits>(name) {
3339 3340
    USE(KindTraits::Kind);
  }
3341

3342 3343 3344 3345 3346 3347
  static void ConvertArgumentsStoreResult(
      Isolate* isolate, Handle<SloppyArgumentsElements> elements,
      Handle<Object> result) {
    UNREACHABLE();
  }

3348 3349
  static Handle<Object> GetImpl(Isolate* isolate, FixedArrayBase* parameters,
                                uint32_t entry) {
3350 3351 3352
    Handle<SloppyArgumentsElements> elements(
        SloppyArgumentsElements::cast(parameters), isolate);
    uint32_t length = elements->parameter_map_length();
3353
    if (entry < length) {
3354
      // Read context mapped entry.
3355
      DisallowHeapAllocation no_gc;
3356 3357 3358
      Object* probe = elements->get_mapped_entry(entry);
      DCHECK(!probe->IsTheHole(isolate));
      Context* context = elements->context();
3359
      int context_entry = Smi::cast(probe)->value();
3360
      DCHECK(!context->get(context_entry)->IsTheHole(isolate));
3361
      return handle(context->get(context_entry), isolate);
3362
    } else {
3363
      // Entry is not context mapped, defer to the arguments.
3364
      Handle<Object> result = ArgumentsAccessor::GetImpl(
3365 3366
          isolate, elements->arguments(), entry - length);
      return Subclass::ConvertArgumentsStoreResult(isolate, elements, result);
3367 3368
    }
  }
3369

3370 3371 3372 3373 3374
  static void TransitionElementsKindImpl(Handle<JSObject> object,
                                         Handle<Map> map) {
    UNREACHABLE();
  }

3375 3376
  static void GrowCapacityAndConvertImpl(Handle<JSObject> object,
                                         uint32_t capacity) {
3377
    UNREACHABLE();
3378 3379
  }

3380 3381 3382 3383 3384
  static inline void SetImpl(Handle<JSObject> holder, uint32_t entry,
                             Object* value) {
    SetImpl(holder->elements(), entry, value);
  }

3385 3386
  static inline void SetImpl(FixedArrayBase* store, uint32_t entry,
                             Object* value) {
3387 3388
    SloppyArgumentsElements* elements = SloppyArgumentsElements::cast(store);
    uint32_t length = elements->parameter_map_length();
3389
    if (entry < length) {
3390 3391 3392 3393 3394
      // Store context mapped entry.
      DisallowHeapAllocation no_gc;
      Object* probe = elements->get_mapped_entry(entry);
      DCHECK(!probe->IsTheHole(store->GetIsolate()));
      Context* context = elements->context();
3395
      int context_entry = Smi::cast(probe)->value();
3396
      DCHECK(!context->get(context_entry)->IsTheHole(store->GetIsolate()));
3397
      context->set(context_entry, value);
3398
    } else {
3399 3400
      //  Entry is not context mapped defer to arguments.
      FixedArray* arguments = elements->arguments();
3401 3402 3403
      Object* current = ArgumentsAccessor::GetRaw(arguments, entry - length);
      if (current->IsAliasedArgumentsEntry()) {
        AliasedArgumentsEntry* alias = AliasedArgumentsEntry::cast(current);
3404
        Context* context = elements->context();
3405
        int context_entry = alias->aliased_context_slot();
3406
        DCHECK(!context->get(context_entry)->IsTheHole(store->GetIsolate()));
3407 3408 3409 3410
        context->set(context_entry, value);
      } else {
        ArgumentsAccessor::SetImpl(arguments, entry - length, value);
      }
3411 3412 3413
    }
  }

3414 3415
  static void SetLengthImpl(Isolate* isolate, Handle<JSArray> array,
                            uint32_t length,
3416 3417 3418
                            Handle<FixedArrayBase> parameter_map) {
    // Sloppy arguments objects are not arrays.
    UNREACHABLE();
3419 3420
  }

3421 3422 3423 3424
  static uint32_t GetCapacityImpl(JSObject* holder, FixedArrayBase* store) {
    SloppyArgumentsElements* elements = SloppyArgumentsElements::cast(store);
    FixedArray* arguments = elements->arguments();
    return elements->parameter_map_length() +
3425
           ArgumentsAccessor::GetCapacityImpl(holder, arguments);
3426 3427
  }

3428 3429
  static uint32_t GetMaxNumberOfEntries(JSObject* holder,
                                        FixedArrayBase* backing_store) {
3430 3431 3432 3433
    SloppyArgumentsElements* elements =
        SloppyArgumentsElements::cast(backing_store);
    FixedArrayBase* arguments = elements->arguments();
    return elements->parameter_map_length() +
3434 3435 3436
           ArgumentsAccessor::GetMaxNumberOfEntries(holder, arguments);
  }

3437 3438
  static uint32_t NumberOfElementsImpl(JSObject* receiver,
                                       FixedArrayBase* backing_store) {
3439 3440 3441 3442
    Isolate* isolate = receiver->GetIsolate();
    SloppyArgumentsElements* elements =
        SloppyArgumentsElements::cast(backing_store);
    FixedArrayBase* arguments = elements->arguments();
3443
    uint32_t nof_elements = 0;
3444
    uint32_t length = elements->parameter_map_length();
3445
    for (uint32_t entry = 0; entry < length; entry++) {
3446
      if (HasParameterMapArg(isolate, elements, entry)) nof_elements++;
3447 3448 3449 3450 3451
    }
    return nof_elements +
           ArgumentsAccessor::NumberOfElementsImpl(receiver, arguments);
  }

3452 3453 3454
  static void AddElementsToKeyAccumulatorImpl(Handle<JSObject> receiver,
                                              KeyAccumulator* accumulator,
                                              AddKeyConversion convert) {
3455 3456 3457
    Isolate* isolate = accumulator->isolate();
    Handle<FixedArrayBase> elements(receiver->elements(), isolate);
    uint32_t length = GetCapacityImpl(*receiver, *elements);
3458
    for (uint32_t entry = 0; entry < length; entry++) {
3459
      if (!HasEntryImpl(isolate, *elements, entry)) continue;
3460
      Handle<Object> value = GetImpl(isolate, *elements, entry);
3461 3462 3463 3464
      accumulator->AddKey(value, convert);
    }
  }

3465 3466
  static bool HasEntryImpl(Isolate* isolate, FixedArrayBase* parameters,
                           uint32_t entry) {
3467 3468 3469
    SloppyArgumentsElements* elements =
        SloppyArgumentsElements::cast(parameters);
    uint32_t length = elements->parameter_map_length();
3470
    if (entry < length) {
3471
      return HasParameterMapArg(isolate, elements, entry);
3472
    }
3473
    FixedArrayBase* arguments = elements->arguments();
3474
    return ArgumentsAccessor::HasEntryImpl(isolate, arguments, entry - length);
3475 3476
  }

3477 3478
  static bool HasAccessorsImpl(JSObject* holder,
                               FixedArrayBase* backing_store) {
3479 3480 3481
    SloppyArgumentsElements* elements =
        SloppyArgumentsElements::cast(backing_store);
    FixedArray* arguments = elements->arguments();
3482 3483 3484
    return ArgumentsAccessor::HasAccessorsImpl(holder, arguments);
  }

3485 3486
  static uint32_t GetIndexForEntryImpl(FixedArrayBase* parameters,
                                       uint32_t entry) {
3487 3488 3489
    SloppyArgumentsElements* elements =
        SloppyArgumentsElements::cast(parameters);
    uint32_t length = elements->parameter_map_length();
3490
    if (entry < length) return entry;
3491
    FixedArray* arguments = elements->arguments();
3492
    return ArgumentsAccessor::GetIndexForEntryImpl(arguments, entry - length);
3493 3494
  }

3495
  static uint32_t GetEntryForIndexImpl(Isolate* isolate, JSObject* holder,
3496
                                       FixedArrayBase* parameters,
3497
                                       uint32_t index, PropertyFilter filter) {
3498 3499 3500 3501
    SloppyArgumentsElements* elements =
        SloppyArgumentsElements::cast(parameters);
    if (HasParameterMapArg(isolate, elements, index)) return index;
    FixedArray* arguments = elements->arguments();
3502 3503
    uint32_t entry = ArgumentsAccessor::GetEntryForIndexImpl(
        isolate, holder, arguments, index, filter);
3504
    if (entry == kMaxUInt32) return kMaxUInt32;
3505 3506
    // Arguments entries could overlap with the dictionary entries, hence offset
    // them by the number of context mapped entries.
3507
    return elements->parameter_map_length() + entry;
3508 3509
  }

3510
  static PropertyDetails GetDetailsImpl(JSObject* holder, uint32_t entry) {
3511 3512 3513
    SloppyArgumentsElements* elements =
        SloppyArgumentsElements::cast(holder->elements());
    uint32_t length = elements->parameter_map_length();
3514
    if (entry < length) {
3515
      return PropertyDetails(kData, NONE, 0, PropertyCellType::kNoCell);
3516
    }
3517
    FixedArray* arguments = elements->arguments();
3518
    return ArgumentsAccessor::GetDetailsImpl(arguments, entry - length);
3519
  }
3520

3521 3522 3523 3524
  static bool HasParameterMapArg(Isolate* isolate,
                                 SloppyArgumentsElements* elements,
                                 uint32_t index) {
    uint32_t length = elements->parameter_map_length();
3525
    if (index >= length) return false;
3526
    return !elements->get_mapped_entry(index)->IsTheHole(isolate);
3527
  }
3528

3529
  static void DeleteImpl(Handle<JSObject> obj, uint32_t entry) {
3530 3531
    Handle<SloppyArgumentsElements> elements(
        SloppyArgumentsElements::cast(obj->elements()));
3532
    uint32_t length = elements->parameter_map_length();
3533 3534 3535 3536 3537 3538 3539
    uint32_t delete_or_entry = entry;
    if (entry < length) {
      delete_or_entry = kMaxUInt32;
    }
    Subclass::SloppyDeleteImpl(obj, elements, delete_or_entry);
    // SloppyDeleteImpl allocates a new dictionary elements store. For making
    // heap verification happy we postpone clearing out the mapped entry.
3540
    if (entry < length) {
3541
      elements->set_mapped_entry(entry, obj->GetHeap()->the_hole_value());
3542 3543
    }
  }
3544

3545 3546 3547 3548 3549 3550 3551
  static void SloppyDeleteImpl(Handle<JSObject> obj,
                               Handle<SloppyArgumentsElements> elements,
                               uint32_t entry) {
    // Implemented in subclasses.
    UNREACHABLE();
  }

3552 3553
  static void CollectElementIndicesImpl(Handle<JSObject> object,
                                        Handle<FixedArrayBase> backing_store,
3554
                                        KeyAccumulator* keys) {
3555 3556 3557 3558 3559
    Isolate* isolate = keys->isolate();
    uint32_t nof_indices = 0;
    Handle<FixedArray> indices = isolate->factory()->NewFixedArray(
        GetCapacityImpl(*object, *backing_store));
    DirectCollectElementIndicesImpl(isolate, object, backing_store,
3560 3561
                                    GetKeysConversion::kKeepNumbers,
                                    ENUMERABLE_STRINGS, indices, &nof_indices);
3562 3563 3564
    SortIndices(indices, nof_indices);
    for (uint32_t i = 0; i < nof_indices; i++) {
      keys->AddKey(indices->get(i));
3565 3566 3567 3568 3569 3570 3571 3572
    }
  }

  static Handle<FixedArray> DirectCollectElementIndicesImpl(
      Isolate* isolate, Handle<JSObject> object,
      Handle<FixedArrayBase> backing_store, GetKeysConversion convert,
      PropertyFilter filter, Handle<FixedArray> list, uint32_t* nof_indices,
      uint32_t insertion_index = 0) {
3573 3574 3575
    Handle<SloppyArgumentsElements> elements =
        Handle<SloppyArgumentsElements>::cast(backing_store);
    uint32_t length = elements->parameter_map_length();
3576 3577

    for (uint32_t i = 0; i < length; ++i) {
3578
      if (elements->get_mapped_entry(i)->IsTheHole(isolate)) continue;
3579
      if (convert == GetKeysConversion::kConvertToString) {
3580 3581 3582 3583 3584 3585 3586 3587
        Handle<String> index_string = isolate->factory()->Uint32ToString(i);
        list->set(insertion_index, *index_string);
      } else {
        list->set(insertion_index, Smi::FromInt(i), SKIP_WRITE_BARRIER);
      }
      insertion_index++;
    }

3588
    Handle<FixedArray> store(elements->arguments(), isolate);
3589 3590 3591 3592
    return ArgumentsAccessor::DirectCollectElementIndicesImpl(
        isolate, object, store, convert, filter, list, nof_indices,
        insertion_index);
  }
3593 3594 3595 3596 3597 3598 3599

  static Maybe<bool> IncludesValueImpl(Isolate* isolate,
                                       Handle<JSObject> object,
                                       Handle<Object> value,
                                       uint32_t start_from, uint32_t length) {
    DCHECK(JSObject::PrototypeHasNoElements(isolate, *object));
    Handle<Map> original_map = handle(object->map(), isolate);
3600 3601
    Handle<SloppyArgumentsElements> elements(
        SloppyArgumentsElements::cast(object->elements()), isolate);
3602 3603 3604
    bool search_for_hole = value->IsUndefined(isolate);

    for (uint32_t k = start_from; k < length; ++k) {
3605 3606
      uint32_t entry =
          GetEntryForIndexImpl(isolate, *object, *elements, k, ALL_PROPERTIES);
3607 3608 3609 3610 3611
      if (entry == kMaxUInt32) {
        if (search_for_hole) return Just(true);
        continue;
      }

3612
      Handle<Object> element_k = Subclass::GetImpl(isolate, *elements, entry);
3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633

      if (element_k->IsAccessorPair()) {
        LookupIterator it(isolate, object, k, LookupIterator::OWN);
        DCHECK(it.IsFound());
        DCHECK_EQ(it.state(), LookupIterator::ACCESSOR);
        ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, element_k,
                                         Object::GetPropertyWithAccessor(&it),
                                         Nothing<bool>());

        if (value->SameValueZero(*element_k)) return Just(true);

        if (object->map() != *original_map) {
          // Some mutation occurred in accessor. Abort "fast" path
          return IncludesValueSlowPath(isolate, object, value, k + 1, length);
        }
      } else if (value->SameValueZero(*element_k)) {
        return Just(true);
      }
    }
    return Just(false);
  }
3634 3635 3636 3637 3638 3639 3640

  static Maybe<int64_t> IndexOfValueImpl(Isolate* isolate,
                                         Handle<JSObject> object,
                                         Handle<Object> value,
                                         uint32_t start_from, uint32_t length) {
    DCHECK(JSObject::PrototypeHasNoElements(isolate, *object));
    Handle<Map> original_map = handle(object->map(), isolate);
3641 3642
    Handle<SloppyArgumentsElements> elements(
        SloppyArgumentsElements::cast(object->elements()), isolate);
3643 3644

    for (uint32_t k = start_from; k < length; ++k) {
3645 3646
      uint32_t entry =
          GetEntryForIndexImpl(isolate, *object, *elements, k, ALL_PROPERTIES);
3647 3648 3649 3650
      if (entry == kMaxUInt32) {
        continue;
      }

3651
      Handle<Object> element_k = Subclass::GetImpl(isolate, *elements, entry);
3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674

      if (element_k->IsAccessorPair()) {
        LookupIterator it(isolate, object, k, LookupIterator::OWN);
        DCHECK(it.IsFound());
        DCHECK_EQ(it.state(), LookupIterator::ACCESSOR);
        ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, element_k,
                                         Object::GetPropertyWithAccessor(&it),
                                         Nothing<int64_t>());

        if (value->StrictEquals(*element_k)) {
          return Just<int64_t>(k);
        }

        if (object->map() != *original_map) {
          // Some mutation occurred in accessor. Abort "fast" path.
          return IndexOfValueSlowPath(isolate, object, value, k + 1, length);
        }
      } else if (value->StrictEquals(*element_k)) {
        return Just<int64_t>(k);
      }
    }
    return Just<int64_t>(-1);
  }
3675 3676 3677
};


3678 3679 3680 3681 3682 3683 3684 3685 3686 3687
class SlowSloppyArgumentsElementsAccessor
    : public SloppyArgumentsElementsAccessor<
          SlowSloppyArgumentsElementsAccessor, DictionaryElementsAccessor,
          ElementsKindTraits<SLOW_SLOPPY_ARGUMENTS_ELEMENTS> > {
 public:
  explicit SlowSloppyArgumentsElementsAccessor(const char* name)
      : SloppyArgumentsElementsAccessor<
            SlowSloppyArgumentsElementsAccessor, DictionaryElementsAccessor,
            ElementsKindTraits<SLOW_SLOPPY_ARGUMENTS_ELEMENTS> >(name) {}

3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701
  static Handle<Object> ConvertArgumentsStoreResult(
      Isolate* isolate, Handle<SloppyArgumentsElements> elements,
      Handle<Object> result) {
    // Elements of the arguments object in slow mode might be slow aliases.
    if (result->IsAliasedArgumentsEntry()) {
      DisallowHeapAllocation no_gc;
      AliasedArgumentsEntry* alias = AliasedArgumentsEntry::cast(*result);
      Context* context = elements->context();
      int context_entry = alias->aliased_context_slot();
      DCHECK(!context->get(context_entry)->IsTheHole(isolate));
      return handle(context->get(context_entry), isolate);
    }
    return result;
  }
3702 3703 3704 3705 3706
  static void SloppyDeleteImpl(Handle<JSObject> obj,
                               Handle<SloppyArgumentsElements> elements,
                               uint32_t entry) {
    // No need to delete a context mapped entry from the arguments elements.
    if (entry == kMaxUInt32) return;
3707
    Isolate* isolate = obj->GetIsolate();
3708
    Handle<SeededNumberDictionary> dict(
3709
        SeededNumberDictionary::cast(elements->arguments()), isolate);
3710 3711
    // TODO(verwaest): Remove reliance on index in Shrink.
    uint32_t index = GetIndexForEntryImpl(*dict, entry);
3712 3713 3714
    int length = elements->parameter_map_length();
    Handle<Object> result =
        SeededNumberDictionary::DeleteProperty(dict, entry - length);
3715
    USE(result);
3716
    DCHECK(result->IsTrue(isolate));
3717 3718
    Handle<FixedArray> new_elements =
        SeededNumberDictionary::Shrink(dict, index);
3719
    elements->set_arguments(*new_elements);
3720 3721
  }

3722
  static void AddImpl(Handle<JSObject> object, uint32_t index,
3723 3724
                      Handle<Object> value, PropertyAttributes attributes,
                      uint32_t new_capacity) {
3725 3726 3727 3728 3729
    Isolate* isolate = object->GetIsolate();
    Handle<SloppyArgumentsElements> elements(
        SloppyArgumentsElements::cast(object->elements()), isolate);
    Handle<FixedArrayBase> old_arguments(
        FixedArrayBase::cast(elements->arguments()), isolate);
3730
    Handle<SeededNumberDictionary> dictionary =
3731 3732
        old_arguments->IsSeededNumberDictionary()
            ? Handle<SeededNumberDictionary>::cast(old_arguments)
3733
            : JSObject::NormalizeElements(object);
3734
    PropertyDetails details(kData, attributes, 0, PropertyCellType::kNoCell);
3735
    Handle<SeededNumberDictionary> new_dictionary =
3736 3737
        SeededNumberDictionary::AddNumberEntry(dictionary, index, value,
                                               details, object);
3738
    if (attributes != NONE) object->RequireSlowElements(*new_dictionary);
3739
    if (*dictionary != *new_dictionary) {
3740
      elements->set_arguments(*new_dictionary);
3741 3742 3743 3744
    }
  }

  static void ReconfigureImpl(Handle<JSObject> object,
3745
                              Handle<FixedArrayBase> store, uint32_t entry,
3746 3747
                              Handle<Object> value,
                              PropertyAttributes attributes) {
3748
    Isolate* isolate = store->GetIsolate();
3749 3750 3751
    Handle<SloppyArgumentsElements> elements =
        Handle<SloppyArgumentsElements>::cast(store);
    uint32_t length = elements->parameter_map_length();
3752
    if (entry < length) {
3753
      Object* probe = elements->get_mapped_entry(entry);
3754
      DCHECK(!probe->IsTheHole(isolate));
3755
      Context* context = elements->context();
3756
      int context_entry = Smi::cast(probe)->value();
3757
      DCHECK(!context->get(context_entry)->IsTheHole(isolate));
3758
      context->set(context_entry, *value);
3759 3760

      // Redefining attributes of an aliased element destroys fast aliasing.
3761
      elements->set_mapped_entry(entry, isolate->heap()->the_hole_value());
3762 3763
      // For elements that are still writable we re-establish slow aliasing.
      if ((attributes & READ_ONLY) == 0) {
3764
        value = isolate->factory()->NewAliasedArgumentsEntry(context_entry);
3765 3766
      }

3767
      PropertyDetails details(kData, attributes, 0, PropertyCellType::kNoCell);
3768
      Handle<SeededNumberDictionary> arguments(
3769
          SeededNumberDictionary::cast(elements->arguments()), isolate);
3770
      arguments = SeededNumberDictionary::AddNumberEntry(
3771
          arguments, entry, value, details, object);
3772 3773 3774 3775
      // If the attributes were NONE, we would have called set rather than
      // reconfigure.
      DCHECK_NE(NONE, attributes);
      object->RequireSlowElements(*arguments);
3776
      elements->set_arguments(*arguments);
3777
    } else {
3778
      Handle<FixedArrayBase> arguments(elements->arguments(), isolate);
3779
      DictionaryElementsAccessor::ReconfigureImpl(
3780
          object, arguments, entry - length, value, attributes);
3781 3782 3783 3784 3785
    }
  }
};


3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796
class FastSloppyArgumentsElementsAccessor
    : public SloppyArgumentsElementsAccessor<
          FastSloppyArgumentsElementsAccessor, FastHoleyObjectElementsAccessor,
          ElementsKindTraits<FAST_SLOPPY_ARGUMENTS_ELEMENTS> > {
 public:
  explicit FastSloppyArgumentsElementsAccessor(const char* name)
      : SloppyArgumentsElementsAccessor<
            FastSloppyArgumentsElementsAccessor,
            FastHoleyObjectElementsAccessor,
            ElementsKindTraits<FAST_SLOPPY_ARGUMENTS_ELEMENTS> >(name) {}

3797 3798 3799 3800 3801 3802 3803
  static Handle<Object> ConvertArgumentsStoreResult(
      Isolate* isolate, Handle<SloppyArgumentsElements> paramtere_map,
      Handle<Object> result) {
    DCHECK(!result->IsAliasedArgumentsEntry());
    return result;
  }

3804
  static Handle<FixedArray> GetArguments(Isolate* isolate,
3805 3806 3807
                                         FixedArrayBase* store) {
    SloppyArgumentsElements* elements = SloppyArgumentsElements::cast(store);
    return Handle<FixedArray>(elements->arguments(), isolate);
3808 3809
  }

3810 3811
  static Handle<JSObject> SliceImpl(Handle<JSObject> receiver, uint32_t start,
                                    uint32_t end) {
3812 3813 3814 3815 3816 3817 3818 3819 3820
    Isolate* isolate = receiver->GetIsolate();
    uint32_t result_len = end < start ? 0u : end - start;
    Handle<JSArray> result_array = isolate->factory()->NewJSArray(
        FAST_HOLEY_ELEMENTS, result_len, result_len);
    DisallowHeapAllocation no_gc;
    FixedArray* elements = FixedArray::cast(result_array->elements());
    FixedArray* parameters = FixedArray::cast(receiver->elements());
    uint32_t insertion_index = 0;
    for (uint32_t i = start; i < end; i++) {
3821 3822 3823
      uint32_t entry = GetEntryForIndexImpl(isolate, *receiver, parameters, i,
                                            ALL_PROPERTIES);
      if (entry != kMaxUInt32 && HasEntryImpl(isolate, parameters, entry)) {
3824
        elements->set(insertion_index, *GetImpl(isolate, parameters, entry));
3825
      } else {
3826
        elements->set_the_hole(isolate, insertion_index);
3827 3828 3829 3830 3831 3832
      }
      insertion_index++;
    }
    return result_array;
  }

3833 3834
  static Handle<SeededNumberDictionary> NormalizeImpl(
      Handle<JSObject> object, Handle<FixedArrayBase> elements) {
3835 3836
    Handle<FixedArray> arguments =
        GetArguments(elements->GetIsolate(), *elements);
3837 3838 3839
    return FastHoleyObjectElementsAccessor::NormalizeImpl(object, arguments);
  }

3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861
  static Handle<SeededNumberDictionary> NormalizeArgumentsElements(
      Handle<JSObject> object, Handle<SloppyArgumentsElements> elements,
      uint32_t* entry) {
    Handle<SeededNumberDictionary> dictionary =
        JSObject::NormalizeElements(object);
    elements->set_arguments(*dictionary);
    // kMaxUInt32 indicates that a context mapped element got deleted. In this
    // case we only normalize the elements (aka. migrate to SLOW_SLOPPY).
    if (*entry == kMaxUInt32) return dictionary;
    uint32_t length = elements->parameter_map_length();
    if (*entry >= length) {
      *entry = dictionary->FindEntry(*entry - length) + length;
    }
    return dictionary;
  }

  static void SloppyDeleteImpl(Handle<JSObject> obj,
                               Handle<SloppyArgumentsElements> elements,
                               uint32_t entry) {
    // Always normalize element on deleting an entry.
    NormalizeArgumentsElements(obj, elements, &entry);
    SlowSloppyArgumentsElementsAccessor::SloppyDeleteImpl(obj, elements, entry);
3862 3863
  }

3864
  static void AddImpl(Handle<JSObject> object, uint32_t index,
3865 3866 3867
                      Handle<Object> value, PropertyAttributes attributes,
                      uint32_t new_capacity) {
    DCHECK_EQ(NONE, attributes);
3868 3869 3870 3871 3872 3873
    Isolate* isolate = object->GetIsolate();
    Handle<SloppyArgumentsElements> elements(
        SloppyArgumentsElements::cast(object->elements()), isolate);
    Handle<FixedArray> old_arguments(elements->arguments(), isolate);
    if (old_arguments->IsSeededNumberDictionary() ||
        static_cast<uint32_t>(old_arguments->length()) < new_capacity) {
3874 3875
      GrowCapacityAndConvertImpl(object, new_capacity);
    }
3876
    FixedArray* arguments = elements->arguments();
3877 3878 3879 3880 3881 3882
    // For fast holey objects, the entry equals the index. The code above made
    // sure that there's enough space to store the value. We cannot convert
    // index to entry explicitly since the slot still contains the hole, so the
    // current EntryForIndex would indicate that it is "absent" by returning
    // kMaxUInt32.
    FastHoleyObjectElementsAccessor::SetImpl(arguments, index, *value);
3883
  }
3884

3885
  static void ReconfigureImpl(Handle<JSObject> object,
3886
                              Handle<FixedArrayBase> store, uint32_t entry,
3887 3888
                              Handle<Object> value,
                              PropertyAttributes attributes) {
3889 3890 3891 3892
    DCHECK_EQ(object->elements(), *store);
    Handle<SloppyArgumentsElements> elements(
        SloppyArgumentsElements::cast(*store));
    NormalizeArgumentsElements(object, elements, &entry);
3893
    SlowSloppyArgumentsElementsAccessor::ReconfigureImpl(object, store, entry,
3894
                                                         value, attributes);
3895
  }
3896

3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913
  static void CopyElementsImpl(FixedArrayBase* from, uint32_t from_start,
                               FixedArrayBase* to, ElementsKind from_kind,
                               uint32_t to_start, int packed_size,
                               int copy_size) {
    DCHECK(!to->IsDictionary());
    if (from_kind == SLOW_SLOPPY_ARGUMENTS_ELEMENTS) {
      CopyDictionaryToObjectElements(from, from_start, to, FAST_HOLEY_ELEMENTS,
                                     to_start, copy_size);
    } else {
      DCHECK_EQ(FAST_SLOPPY_ARGUMENTS_ELEMENTS, from_kind);
      CopyObjectToObjectElements(from, FAST_HOLEY_ELEMENTS, from_start, to,
                                 FAST_HOLEY_ELEMENTS, to_start, copy_size);
    }
  }

  static void GrowCapacityAndConvertImpl(Handle<JSObject> object,
                                         uint32_t capacity) {
3914 3915 3916 3917 3918
    Isolate* isolate = object->GetIsolate();
    Handle<SloppyArgumentsElements> elements(
        SloppyArgumentsElements::cast(object->elements()), isolate);
    Handle<FixedArray> old_arguments(FixedArray::cast(elements->arguments()),
                                     isolate);
3919 3920 3921 3922
    ElementsKind from_kind = object->GetElementsKind();
    // This method should only be called if there's a reason to update the
    // elements.
    DCHECK(from_kind == SLOW_SLOPPY_ARGUMENTS_ELEMENTS ||
3923 3924 3925
           static_cast<uint32_t>(old_arguments->length()) < capacity);
    Handle<FixedArrayBase> arguments =
        ConvertElementsWithCapacity(object, old_arguments, from_kind, capacity);
3926 3927 3928
    Handle<Map> new_map = JSObject::GetElementsTransitionMap(
        object, FAST_SLOPPY_ARGUMENTS_ELEMENTS);
    JSObject::MigrateToMap(object, new_map);
3929
    elements->set_arguments(FixedArray::cast(*arguments));
3930 3931 3932 3933
    JSObject::ValidateElements(object);
  }
};

3934
template <typename Subclass, typename BackingStoreAccessor, typename KindTraits>
3935
class StringWrapperElementsAccessor
3936
    : public ElementsAccessorBase<Subclass, KindTraits> {
3937 3938
 public:
  explicit StringWrapperElementsAccessor(const char* name)
3939
      : ElementsAccessorBase<Subclass, KindTraits>(name) {
3940 3941 3942
    USE(KindTraits::Kind);
  }

3943 3944 3945 3946 3947
  static Handle<Object> GetInternalImpl(Handle<JSObject> holder,
                                        uint32_t entry) {
    return GetImpl(holder, entry);
  }

3948 3949 3950 3951 3952 3953 3954 3955
  static Handle<Object> GetImpl(Handle<JSObject> holder, uint32_t entry) {
    Isolate* isolate = holder->GetIsolate();
    Handle<String> string(GetString(*holder), isolate);
    uint32_t length = static_cast<uint32_t>(string->length());
    if (entry < length) {
      return isolate->factory()->LookupSingleCharacterStringFromCode(
          String::Flatten(string)->Get(entry));
    }
3956 3957 3958 3959 3960 3961 3962
    return BackingStoreAccessor::GetImpl(isolate, holder->elements(),
                                         entry - length);
  }

  static Handle<Object> GetImpl(Isolate* isolate, FixedArrayBase* elements,
                                uint32_t entry) {
    UNREACHABLE();
3963 3964 3965 3966 3967 3968 3969
  }

  static PropertyDetails GetDetailsImpl(JSObject* holder, uint32_t entry) {
    uint32_t length = static_cast<uint32_t>(GetString(holder)->length());
    if (entry < length) {
      PropertyAttributes attributes =
          static_cast<PropertyAttributes>(READ_ONLY | DONT_DELETE);
3970
      return PropertyDetails(kData, attributes, 0, PropertyCellType::kNoCell);
3971 3972 3973 3974
    }
    return BackingStoreAccessor::GetDetailsImpl(holder, entry - length);
  }

3975
  static uint32_t GetEntryForIndexImpl(Isolate* isolate, JSObject* holder,
3976 3977 3978 3979 3980
                                       FixedArrayBase* backing_store,
                                       uint32_t index, PropertyFilter filter) {
    uint32_t length = static_cast<uint32_t>(GetString(holder)->length());
    if (index < length) return index;
    uint32_t backing_store_entry = BackingStoreAccessor::GetEntryForIndexImpl(
3981
        isolate, holder, backing_store, index, filter);
3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006
    if (backing_store_entry == kMaxUInt32) return kMaxUInt32;
    DCHECK(backing_store_entry < kMaxUInt32 - length);
    return backing_store_entry + length;
  }

  static void DeleteImpl(Handle<JSObject> holder, uint32_t entry) {
    uint32_t length = static_cast<uint32_t>(GetString(*holder)->length());
    if (entry < length) {
      return;  // String contents can't be deleted.
    }
    BackingStoreAccessor::DeleteImpl(holder, entry - length);
  }

  static void SetImpl(Handle<JSObject> holder, uint32_t entry, Object* value) {
    uint32_t length = static_cast<uint32_t>(GetString(*holder)->length());
    if (entry < length) {
      return;  // String contents are read-only.
    }
    BackingStoreAccessor::SetImpl(holder->elements(), entry - length, value);
  }

  static void AddImpl(Handle<JSObject> object, uint32_t index,
                      Handle<Object> value, PropertyAttributes attributes,
                      uint32_t new_capacity) {
    DCHECK(index >= static_cast<uint32_t>(GetString(*object)->length()));
4007 4008 4009 4010 4011 4012
    // Explicitly grow fast backing stores if needed. Dictionaries know how to
    // extend their capacity themselves.
    if (KindTraits::Kind == FAST_STRING_WRAPPER_ELEMENTS &&
        (object->GetElementsKind() == SLOW_STRING_WRAPPER_ELEMENTS ||
         BackingStoreAccessor::GetCapacityImpl(*object, object->elements()) !=
             new_capacity)) {
4013
      GrowCapacityAndConvertImpl(object, new_capacity);
4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049
    }
    BackingStoreAccessor::AddImpl(object, index, value, attributes,
                                  new_capacity);
  }

  static void ReconfigureImpl(Handle<JSObject> object,
                              Handle<FixedArrayBase> store, uint32_t entry,
                              Handle<Object> value,
                              PropertyAttributes attributes) {
    uint32_t length = static_cast<uint32_t>(GetString(*object)->length());
    if (entry < length) {
      return;  // String contents can't be reconfigured.
    }
    BackingStoreAccessor::ReconfigureImpl(object, store, entry - length, value,
                                          attributes);
  }

  static void AddElementsToKeyAccumulatorImpl(Handle<JSObject> receiver,
                                              KeyAccumulator* accumulator,
                                              AddKeyConversion convert) {
    Isolate* isolate = receiver->GetIsolate();
    Handle<String> string(GetString(*receiver), isolate);
    string = String::Flatten(string);
    uint32_t length = static_cast<uint32_t>(string->length());
    for (uint32_t i = 0; i < length; i++) {
      accumulator->AddKey(
          isolate->factory()->LookupSingleCharacterStringFromCode(
              string->Get(i)),
          convert);
    }
    BackingStoreAccessor::AddElementsToKeyAccumulatorImpl(receiver, accumulator,
                                                          convert);
  }

  static void CollectElementIndicesImpl(Handle<JSObject> object,
                                        Handle<FixedArrayBase> backing_store,
4050
                                        KeyAccumulator* keys) {
4051
    uint32_t length = GetString(*object)->length();
4052
    Factory* factory = keys->isolate()->factory();
4053
    for (uint32_t i = 0; i < length; i++) {
4054
      keys->AddKey(factory->NewNumberFromUint(i));
4055
    }
4056 4057
    BackingStoreAccessor::CollectElementIndicesImpl(object, backing_store,
                                                    keys);
4058 4059
  }

4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072
  static void GrowCapacityAndConvertImpl(Handle<JSObject> object,
                                         uint32_t capacity) {
    Handle<FixedArrayBase> old_elements(object->elements());
    ElementsKind from_kind = object->GetElementsKind();
    // This method should only be called if there's a reason to update the
    // elements.
    DCHECK(from_kind == SLOW_STRING_WRAPPER_ELEMENTS ||
           static_cast<uint32_t>(old_elements->length()) < capacity);
    Subclass::BasicGrowCapacityAndConvertImpl(object, old_elements, from_kind,
                                              FAST_STRING_WRAPPER_ELEMENTS,
                                              capacity);
  }

4073 4074 4075 4076
  static void CopyElementsImpl(FixedArrayBase* from, uint32_t from_start,
                               FixedArrayBase* to, ElementsKind from_kind,
                               uint32_t to_start, int packed_size,
                               int copy_size) {
4077 4078 4079 4080 4081 4082 4083 4084 4085
    DCHECK(!to->IsDictionary());
    if (from_kind == SLOW_STRING_WRAPPER_ELEMENTS) {
      CopyDictionaryToObjectElements(from, from_start, to, FAST_HOLEY_ELEMENTS,
                                     to_start, copy_size);
    } else {
      DCHECK_EQ(FAST_STRING_WRAPPER_ELEMENTS, from_kind);
      CopyObjectToObjectElements(from, FAST_HOLEY_ELEMENTS, from_start, to,
                                 FAST_HOLEY_ELEMENTS, to_start, copy_size);
    }
4086 4087
  }

4088 4089 4090 4091 4092 4093 4094
  static uint32_t NumberOfElementsImpl(JSObject* object,
                                       FixedArrayBase* backing_store) {
    uint32_t length = GetString(object)->length();
    return length +
           BackingStoreAccessor::NumberOfElementsImpl(object, backing_store);
  }

4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112
 private:
  static String* GetString(JSObject* holder) {
    DCHECK(holder->IsJSValue());
    JSValue* js_value = JSValue::cast(holder);
    DCHECK(js_value->value()->IsString());
    return String::cast(js_value->value());
  }
};

class FastStringWrapperElementsAccessor
    : public StringWrapperElementsAccessor<
          FastStringWrapperElementsAccessor, FastHoleyObjectElementsAccessor,
          ElementsKindTraits<FAST_STRING_WRAPPER_ELEMENTS>> {
 public:
  explicit FastStringWrapperElementsAccessor(const char* name)
      : StringWrapperElementsAccessor<
            FastStringWrapperElementsAccessor, FastHoleyObjectElementsAccessor,
            ElementsKindTraits<FAST_STRING_WRAPPER_ELEMENTS>>(name) {}
4113 4114 4115 4116 4117

  static Handle<SeededNumberDictionary> NormalizeImpl(
      Handle<JSObject> object, Handle<FixedArrayBase> elements) {
    return FastHoleyObjectElementsAccessor::NormalizeImpl(object, elements);
  }
4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128
};

class SlowStringWrapperElementsAccessor
    : public StringWrapperElementsAccessor<
          SlowStringWrapperElementsAccessor, DictionaryElementsAccessor,
          ElementsKindTraits<SLOW_STRING_WRAPPER_ELEMENTS>> {
 public:
  explicit SlowStringWrapperElementsAccessor(const char* name)
      : StringWrapperElementsAccessor<
            SlowStringWrapperElementsAccessor, DictionaryElementsAccessor,
            ElementsKindTraits<SLOW_STRING_WRAPPER_ELEMENTS>>(name) {}
4129 4130 4131 4132 4133

  static bool HasAccessorsImpl(JSObject* holder,
                               FixedArrayBase* backing_store) {
    return DictionaryElementsAccessor::HasAccessorsImpl(holder, backing_store);
  }
4134
};
4135

4136 4137 4138
}  // namespace


4139
void CheckArrayAbuse(Handle<JSObject> obj, const char* op, uint32_t index,
4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157
                     bool allow_appending) {
  DisallowHeapAllocation no_allocation;
  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);
      uint32_t compare_length = static_cast<uint32_t>(int32_length);
      if (allow_appending) compare_length++;
4158
      if (index >= compare_length) {
4159 4160
        PrintF("[OOB %s %s (%s length = %d, element accessed = %d) in ",
               elements_type, op, elements_type, static_cast<int>(int32_length),
4161
               static_cast<int>(index));
4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175
        TraceTopFrame(obj->GetIsolate());
        PrintF("]\n");
      }
    } else {
      PrintF("[%s elements length not integer value in ", elements_type);
      TraceTopFrame(obj->GetIsolate());
      PrintF("]\n");
    }
  } else {
    PrintF("[%s elements length not a number in ", elements_type);
    TraceTopFrame(obj->GetIsolate());
    PrintF("]\n");
  }
}
4176 4177


4178 4179
MaybeHandle<Object> ArrayConstructInitializeElements(Handle<JSArray> array,
                                                     Arguments* args) {
4180 4181 4182 4183 4184
  if (args->length() == 0) {
    // Optimize the case where there are no parameters passed.
    JSArray::Initialize(array, JSArray::kPreallocatedArrayElements);
    return array;

4185
  } else if (args->length() == 1 && args->at(0)->IsNumber()) {
4186
    uint32_t length;
4187
    if (!args->at(0)->ToArrayLength(&length)) {
4188 4189 4190 4191 4192
      return ThrowArrayLengthRangeError(array->GetIsolate());
    }

    // Optimize the case where there is one argument and the argument is a small
    // smi.
4193
    if (length > 0 && length < JSArray::kInitialMaxFastElementArray) {
4194 4195 4196 4197 4198 4199
      ElementsKind elements_kind = array->GetElementsKind();
      JSArray::Initialize(array, length, length);

      if (!IsFastHoleyElementsKind(elements_kind)) {
        elements_kind = GetHoleyElementsKind(elements_kind);
        JSObject::TransitionElementsKind(array, elements_kind);
4200
      }
4201 4202
    } else if (length == 0) {
      JSArray::Initialize(array, JSArray::kPreallocatedArrayElements);
4203 4204 4205 4206
    } else {
      // Take the argument as the length.
      JSArray::Initialize(array, 0);
      JSArray::SetLength(array, length);
4207
    }
4208
    return array;
4209 4210
  }

4211 4212
  Factory* factory = array->GetIsolate()->factory();

4213 4214
  // Set length and elements on the array.
  int number_of_elements = args->length();
4215 4216
  JSObject::EnsureCanContainElements(
      array, args, 0, number_of_elements, ALLOW_CONVERTED_DOUBLE_ELEMENTS);
4217 4218 4219

  // Allocate an appropriately typed elements array.
  ElementsKind elements_kind = array->GetElementsKind();
4220
  Handle<FixedArrayBase> elms;
4221
  if (IsFastDoubleElementsKind(elements_kind)) {
4222 4223
    elms = Handle<FixedArrayBase>::cast(
        factory->NewFixedDoubleArray(number_of_elements));
4224
  } else {
4225 4226
    elms = Handle<FixedArrayBase>::cast(
        factory->NewFixedArrayWithHoles(number_of_elements));
4227 4228 4229
  }

  // Fill in the content
4230
  switch (elements_kind) {
4231 4232
    case FAST_HOLEY_SMI_ELEMENTS:
    case FAST_SMI_ELEMENTS: {
4233
      Handle<FixedArray> smi_elms = Handle<FixedArray>::cast(elms);
4234 4235
      for (int entry = 0; entry < number_of_elements; entry++) {
        smi_elms->set(entry, (*args)[entry], SKIP_WRITE_BARRIER);
4236 4237 4238 4239 4240
      }
      break;
    }
    case FAST_HOLEY_ELEMENTS:
    case FAST_ELEMENTS: {
4241
      DisallowHeapAllocation no_gc;
4242
      WriteBarrierMode mode = elms->GetWriteBarrierMode(no_gc);
4243
      Handle<FixedArray> object_elms = Handle<FixedArray>::cast(elms);
4244 4245
      for (int entry = 0; entry < number_of_elements; entry++) {
        object_elms->set(entry, (*args)[entry], mode);
4246 4247 4248 4249 4250
      }
      break;
    }
    case FAST_HOLEY_DOUBLE_ELEMENTS:
    case FAST_DOUBLE_ELEMENTS: {
4251 4252
      Handle<FixedDoubleArray> double_elms =
          Handle<FixedDoubleArray>::cast(elms);
4253 4254
      for (int entry = 0; entry < number_of_elements; entry++) {
        double_elms->set(entry, (*args)[entry]->Number());
4255 4256 4257 4258 4259 4260 4261 4262
      }
      break;
    }
    default:
      UNREACHABLE();
      break;
  }

4263
  array->set_elements(*elms);
4264 4265 4266 4267
  array->set_length(Smi::FromInt(number_of_elements));
  return array;
}

4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290

void ElementsAccessor::InitializeOncePerProcess() {
  static ElementsAccessor* accessor_array[] = {
#define ACCESSOR_ARRAY(Class, Kind, Store) new Class(#Kind),
      ELEMENTS_LIST(ACCESSOR_ARRAY)
#undef ACCESSOR_ARRAY
  };

  STATIC_ASSERT((sizeof(accessor_array) / sizeof(*accessor_array)) ==
                kElementsKindCount);

  elements_accessors_ = accessor_array;
}


void ElementsAccessor::TearDown() {
  if (elements_accessors_ == NULL) return;
#define ACCESSOR_DELETE(Class, Kind, Store) delete elements_accessors_[Kind];
  ELEMENTS_LIST(ACCESSOR_DELETE)
#undef ACCESSOR_DELETE
  elements_accessors_ = NULL;
}

4291
Handle<JSArray> ElementsAccessor::Concat(Isolate* isolate, Arguments* args,
4292 4293
                                         uint32_t concat_size,
                                         uint32_t result_len) {
4294
  ElementsKind result_elements_kind = GetInitialFastElementsKind();
4295
  bool has_raw_doubles = false;
4296 4297
  {
    DisallowHeapAllocation no_gc;
4298
    bool is_holey = false;
4299
    for (uint32_t i = 0; i < concat_size; i++) {
4300 4301
      Object* arg = (*args)[i];
      ElementsKind arg_kind = JSArray::cast(arg)->GetElementsKind();
4302
      has_raw_doubles = has_raw_doubles || IsFastDoubleElementsKind(arg_kind);
4303
      is_holey = is_holey || IsFastHoleyElementsKind(arg_kind);
4304 4305
      result_elements_kind =
          GetMoreGeneralElementsKind(result_elements_kind, arg_kind);
4306 4307
    }
    if (is_holey) {
4308
      result_elements_kind = GetHoleyElementsKind(result_elements_kind);
4309 4310 4311 4312 4313 4314
    }
  }

  // If a double array is concatted into a fast elements array, the fast
  // elements array needs to be initialized to contain proper holes, since
  // boxing doubles may cause incremental marking.
4315 4316 4317 4318 4319
  bool requires_double_boxing =
      has_raw_doubles && !IsFastDoubleElementsKind(result_elements_kind);
  ArrayStorageAllocationMode mode = requires_double_boxing
                                        ? INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE
                                        : DONT_INITIALIZE_ARRAY_ELEMENTS;
4320
  Handle<JSArray> result_array = isolate->factory()->NewJSArray(
4321
      result_elements_kind, result_len, result_len, mode);
4322
  if (result_len == 0) return result_array;
4323 4324

  uint32_t insertion_index = 0;
4325
  Handle<FixedArrayBase> storage(result_array->elements(), isolate);
4326
  ElementsAccessor* accessor = ElementsAccessor::ForKind(result_elements_kind);
4327 4328 4329 4330
  for (uint32_t i = 0; i < concat_size; i++) {
    // It is crucial to keep |array| in a raw pointer form to avoid
    // performance degradation.
    JSArray* array = JSArray::cast((*args)[i]);
4331 4332 4333 4334 4335 4336
    uint32_t len = 0;
    array->length()->ToArrayLength(&len);
    if (len == 0) continue;
    ElementsKind from_kind = array->GetElementsKind();
    accessor->CopyElements(array, 0, from_kind, storage, insertion_index, len);
    insertion_index += len;
4337 4338
  }

4339
  DCHECK_EQ(insertion_index, result_len);
4340 4341 4342
  return result_array;
}

4343
ElementsAccessor** ElementsAccessor::elements_accessors_ = NULL;
4344 4345
}  // namespace internal
}  // namespace v8