builtins.cc 55 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/v8.h"
6

7 8
#include "src/api.h"
#include "src/arguments.h"
9
#include "src/base/once.h"
10 11 12 13
#include "src/bootstrapper.h"
#include "src/builtins.h"
#include "src/cpu-profiler.h"
#include "src/gdb-jit.h"
14
#include "src/heap/mark-compact.h"
15
#include "src/heap-profiler.h"
16
#include "src/ic-inl.h"
17
#include "src/prototype.h"
18 19
#include "src/stub-cache.h"
#include "src/vm-state-inl.h"
20

21 22
namespace v8 {
namespace internal {
23

24 25 26 27 28 29
namespace {

// Arguments object passed to C++ builtins.
template <BuiltinExtraArguments extra_args>
class BuiltinArguments : public Arguments {
 public:
vitalyr@chromium.org's avatar
vitalyr@chromium.org committed
30 31 32
  BuiltinArguments(int length, Object** arguments)
      : Arguments(length, arguments) { }

33
  Object*& operator[] (int index) {
34
    DCHECK(index < length());
35 36 37 38
    return Arguments::operator[](index);
  }

  template <class S> Handle<S> at(int index) {
39
    DCHECK(index < length());
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
    return Arguments::at<S>(index);
  }

  Handle<Object> receiver() {
    return Arguments::at<Object>(0);
  }

  Handle<JSFunction> called_function() {
    STATIC_ASSERT(extra_args == NEEDS_CALLED_FUNCTION);
    return Arguments::at<JSFunction>(Arguments::length() - 1);
  }

  // Gets the total number of arguments including the receiver (but
  // excluding extra arguments).
  int length() const {
    STATIC_ASSERT(extra_args == NO_EXTRA_ARGUMENTS);
    return Arguments::length();
  }

#ifdef DEBUG
  void Verify() {
    // Check we have at least the receiver.
62
    DCHECK(Arguments::length() >= 1);
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
  }
#endif
};


// Specialize BuiltinArguments for the called function extra argument.

template <>
int BuiltinArguments<NEEDS_CALLED_FUNCTION>::length() const {
  return Arguments::length() - 1;
}

#ifdef DEBUG
template <>
void BuiltinArguments<NEEDS_CALLED_FUNCTION>::Verify() {
  // Check we have at least the receiver and the called function.
79
  DCHECK(Arguments::length() >= 2);
80 81 82 83 84 85 86 87 88 89 90 91 92
  // Make sure cast to JSFunction succeeds.
  called_function();
}
#endif


#define DEF_ARG_TYPE(name, spec)                      \
  typedef BuiltinArguments<spec> name##ArgumentsType;
BUILTIN_LIST_C(DEF_ARG_TYPE)
#undef DEF_ARG_TYPE

}  // namespace

93
// ----------------------------------------------------------------------------
94
// Support macro for defining builtins in C++.
95 96 97 98
// ----------------------------------------------------------------------------
//
// A builtin function is defined by writing:
//
99
//   BUILTIN(name) {
100 101 102
//     ...
//   }
//
103 104
// In the body of the builtin function the arguments can be accessed
// through the BuiltinArguments object args.
105

106
#ifdef DEBUG
107

108
#define BUILTIN(name)                                            \
109
  MUST_USE_RESULT static Object* Builtin_Impl_##name(            \
110
      name##ArgumentsType args, Isolate* isolate);               \
111
  MUST_USE_RESULT static Object* Builtin_##name(                 \
112 113 114 115 116
      int args_length, Object** args_object, Isolate* isolate) { \
    name##ArgumentsType args(args_length, args_object);          \
    args.Verify();                                               \
    return Builtin_Impl_##name(args, isolate);                   \
  }                                                              \
117
  MUST_USE_RESULT static Object* Builtin_Impl_##name(            \
118
      name##ArgumentsType args, Isolate* isolate)
119

120
#else  // For release mode.
121

122
#define BUILTIN(name)                                            \
123
  static Object* Builtin_impl##name(                             \
124
      name##ArgumentsType args, Isolate* isolate);               \
125
  static Object* Builtin_##name(                                 \
126 127 128 129
      int args_length, Object** args_object, Isolate* isolate) { \
    name##ArgumentsType args(args_length, args_object);          \
    return Builtin_impl##name(args, isolate);                    \
  }                                                              \
130
  static Object* Builtin_impl##name(                             \
131
      name##ArgumentsType args, Isolate* isolate)
132
#endif
133 134


135
#ifdef DEBUG
136
static inline bool CalledAsConstructor(Isolate* isolate) {
137 138 139
  // Calculate the result using a full stack frame iterator and check
  // that the state of the stack is as we assume it to be in the
  // code below.
140
  StackFrameIterator it(isolate);
141
  DCHECK(it.frame()->is_exit());
142 143
  it.Advance();
  StackFrame* frame = it.frame();
144
  bool reference_result = frame->is_construct();
145
  Address fp = Isolate::c_entry_fp(isolate->thread_local_top());
146 147 148 149 150 151 152 153 154 155 156 157
  // Because we know fp points to an exit frame we can use the relevant
  // part of ExitFrame::ComputeCallerState directly.
  const int kCallerOffset = ExitFrameConstants::kCallerFPOffset;
  Address caller_fp = Memory::Address_at(fp + kCallerOffset);
  // This inlines the part of StackFrame::ComputeType that grabs the
  // type of the current frame.  Note that StackFrame::ComputeType
  // has been specialized for each architecture so if any one of them
  // changes this code has to be changed as well.
  const int kMarkerOffset = StandardFrameConstants::kMarkerOffset;
  const Smi* kConstructMarker = Smi::FromInt(StackFrame::CONSTRUCT);
  Object* marker = Memory::Object_at(caller_fp + kMarkerOffset);
  bool result = (marker == kConstructMarker);
158
  DCHECK_EQ(result, reference_result);
159
  return result;
160
}
161
#endif
162

163

164 165
// ----------------------------------------------------------------------------

166
BUILTIN(Illegal) {
167
  UNREACHABLE();
168
  return isolate->heap()->undefined_value();  // Make compiler happy.
169 170 171
}


172
BUILTIN(EmptyFunction) {
173
  return isolate->heap()->undefined_value();
174 175 176
}


177 178
static void MoveDoubleElements(FixedDoubleArray* dst, int dst_index,
                               FixedDoubleArray* src, int src_index, int len) {
179
  if (len == 0) return;
180 181
  MemMove(dst->data_start() + dst_index, src->data_start() + src_index,
          len * kDoubleSize);
182 183 184
}


185
static bool ArrayPrototypeHasNoElements(Heap* heap,
186
                                        Context* native_context,
187
                                        JSObject* array_proto) {
188
  DisallowHeapAllocation no_gc;
189 190
  // This method depends on non writability of Object and Array prototype
  // fields.
191
  if (array_proto->elements() != heap->empty_fixed_array()) return false;
192
  // Object.prototype
193 194 195 196 197
  PrototypeIterator iter(heap->isolate(), array_proto);
  if (iter.IsAtEnd()) {
    return false;
  }
  array_proto = JSObject::cast(iter.GetCurrent());
198
  if (array_proto != native_context->initial_object_prototype()) return false;
199
  if (array_proto->elements() != heap->empty_fixed_array()) return false;
200 201
  iter.Advance();
  return iter.IsAtEnd();
202 203 204
}


205
// Returns empty handle if not applicable.
206
MUST_USE_RESULT
207
static inline MaybeHandle<FixedArrayBase> EnsureJSArrayWithWritableFastElements(
208 209 210 211
    Isolate* isolate,
    Handle<Object> receiver,
    Arguments* args,
    int first_added_arg) {
212
  if (!receiver->IsJSArray()) return MaybeHandle<FixedArrayBase>();
213
  Handle<JSArray> array = Handle<JSArray>::cast(receiver);
214
  // If there may be elements accessors in the prototype chain, the fast path
215 216
  // cannot be used if there arguments to add to the array.
  if (args != NULL && array->map()->DictionaryElementsInPrototypeChainOnly()) {
217 218
    return MaybeHandle<FixedArrayBase>();
  }
219 220
  if (array->map()->is_observed()) return MaybeHandle<FixedArrayBase>();
  if (!array->map()->is_extensible()) return MaybeHandle<FixedArrayBase>();
221
  Handle<FixedArrayBase> elms(array->elements(), isolate);
222
  Heap* heap = isolate->heap();
223 224
  Map* map = elms->map();
  if (map == heap->fixed_array_map()) {
225
    if (args == NULL || array->HasFastObjectElements()) return elms;
226
  } else if (map == heap->fixed_cow_array_map()) {
227 228
    elms = JSObject::EnsureWritableFastElements(array);
    if (args == NULL || array->HasFastObjectElements()) return elms;
229 230
  } else if (map == heap->fixed_double_array_map()) {
    if (args == NULL) return elms;
231
  } else {
232
    return MaybeHandle<FixedArrayBase>();
233
  }
234 235 236 237

  // Need to ensure that the arguments passed in args can be contained in
  // the array.
  int args_length = args->length();
238
  if (first_added_arg >= args_length) return handle(array->elements(), isolate);
239

240
  ElementsKind origin_kind = array->map()->elements_kind();
241
  DCHECK(!IsFastObjectElementsKind(origin_kind));
242
  ElementsKind target_kind = origin_kind;
243 244 245 246 247 248 249 250 251 252 253 254 255
  {
    DisallowHeapAllocation no_gc;
    int arg_count = args->length() - first_added_arg;
    Object** arguments = args->arguments() - first_added_arg - (arg_count - 1);
    for (int i = 0; i < arg_count; i++) {
      Object* arg = arguments[i];
      if (arg->IsHeapObject()) {
        if (arg->IsHeapNumber()) {
          target_kind = FAST_DOUBLE_ELEMENTS;
        } else {
          target_kind = FAST_ELEMENTS;
          break;
        }
256 257 258 259
      }
    }
  }
  if (target_kind != origin_kind) {
260
    JSObject::TransitionElementsKind(array, target_kind);
261
    return handle(array->elements(), isolate);
262 263
  }
  return elms;
264 265 266
}


267 268
static inline bool IsJSArrayFastElementMovingAllowed(Heap* heap,
                                                     JSArray* receiver) {
269
  if (!FLAG_clever_optimizations) return false;
270
  DisallowHeapAllocation no_gc;
271
  Context* native_context = heap->isolate()->context()->native_context();
272
  JSObject* array_proto =
273
      JSObject::cast(native_context->array_function()->prototype());
274 275
  PrototypeIterator iter(heap->isolate(), receiver);
  return iter.GetCurrent() == array_proto &&
276
         ArrayPrototypeHasNoElements(heap, native_context, array_proto);
277 278 279
}


280
MUST_USE_RESULT static Object* CallJsBuiltin(
281
    Isolate* isolate,
282 283
    const char* name,
    BuiltinArguments<NO_EXTRA_ARGUMENTS> args) {
284
  HandleScope handleScope(isolate);
285

286 287 288 289
  Handle<Object> js_builtin = Object::GetProperty(
      isolate,
      handle(isolate->native_context()->builtins(), isolate),
      name).ToHandleChecked();
290 291 292 293 294
  Handle<JSFunction> function = Handle<JSFunction>::cast(js_builtin);
  int argc = args.length() - 1;
  ScopedVector<Handle<Object> > argv(argc);
  for (int i = 0; i < argc; ++i) {
    argv[i] = args.at<Object>(i + 1);
295
  }
296 297 298 299 300 301 302 303
  Handle<Object> result;
  ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
      isolate, result,
      Execution::Call(isolate,
                      function,
                      args.receiver(),
                      argc,
                      argv.start()));
304 305 306 307
  return *result;
}


308
BUILTIN(ArrayPush) {
309 310
  HandleScope scope(isolate);
  Handle<Object> receiver = args.receiver();
311
  MaybeHandle<FixedArrayBase> maybe_elms_obj =
312
      EnsureJSArrayWithWritableFastElements(isolate, receiver, &args, 1);
313 314 315 316
  Handle<FixedArrayBase> elms_obj;
  if (!maybe_elms_obj.ToHandle(&elms_obj)) {
    return CallJsBuiltin(isolate, "ArrayPush", args);
  }
317 318

  Handle<JSArray> array = Handle<JSArray>::cast(receiver);
319 320 321 322 323
  int len = Smi::cast(array->length())->value();
  int to_add = args.length() - 1;
  if (to_add > 0 && JSArray::WouldChangeReadOnlyLength(array, len + to_add)) {
    return CallJsBuiltin(isolate, "ArrayPush", args);
  }
324
  DCHECK(!array->map()->is_observed());
325

326
  ElementsKind kind = array->GetElementsKind();
327

328
  if (IsFastSmiOrObjectElementsKind(kind)) {
329
    Handle<FixedArray> elms = Handle<FixedArray>::cast(elms_obj);
330 331
    if (to_add == 0) {
      return Smi::FromInt(len);
332
    }
333 334
    // Currently fixed arrays cannot grow too big, so
    // we should never hit this case.
335
    DCHECK(to_add <= (Smi::kMaxValue - len));
336

337
    int new_length = len + to_add;
338

339 340 341
    if (new_length > elms->length()) {
      // New backing storage is needed.
      int capacity = new_length + (new_length >> 1) + 16;
342 343
      Handle<FixedArray> new_elms =
          isolate->factory()->NewUninitializedFixedArray(capacity);
344

345
      ElementsAccessor* accessor = array->GetElementsAccessor();
346
      accessor->CopyElements(
347 348
          elms_obj, 0, kind, new_elms, 0,
          ElementsAccessor::kCopyToEndAndInitializeToHole);
349

350 351
      elms = new_elms;
    }
352

353
    // Add the provided values.
354
    DisallowHeapAllocation no_gc;
355 356 357 358
    WriteBarrierMode mode = elms->GetWriteBarrierMode(no_gc);
    for (int index = 0; index < to_add; index++) {
      elms->set(index + len, args[index + 1], mode);
    }
359

360 361
    if (*elms != array->elements()) {
      array->set_elements(*elms);
362 363 364 365 366 367 368 369 370 371 372 373
    }

    // Set the length.
    array->set_length(Smi::FromInt(new_length));
    return Smi::FromInt(new_length);
  } else {
    int elms_len = elms_obj->length();
    if (to_add == 0) {
      return Smi::FromInt(len);
    }
    // Currently fixed arrays cannot grow too big, so
    // we should never hit this case.
374
    DCHECK(to_add <= (Smi::kMaxValue - len));
375 376 377

    int new_length = len + to_add;

378
    Handle<FixedDoubleArray> new_elms;
379 380 381 382

    if (new_length > elms_len) {
      // New backing storage is needed.
      int capacity = new_length + (new_length >> 1) + 16;
383 384 385 386
      // Create new backing store; since capacity > 0, we can
      // safely cast to FixedDoubleArray.
      new_elms = Handle<FixedDoubleArray>::cast(
          isolate->factory()->NewFixedDoubleArray(capacity));
387

388
      ElementsAccessor* accessor = array->GetElementsAccessor();
389
      accessor->CopyElements(
390 391
          elms_obj, 0, kind, new_elms, 0,
          ElementsAccessor::kCopyToEndAndInitializeToHole);
392

393 394 395
    } else {
      // to_add is > 0 and new_length <= elms_len, so elms_obj cannot be the
      // empty_fixed_array.
396
      new_elms = Handle<FixedDoubleArray>::cast(elms_obj);
397 398 399
    }

    // Add the provided values.
400
    DisallowHeapAllocation no_gc;
401 402 403 404 405 406
    int index;
    for (index = 0; index < to_add; index++) {
      Object* arg = args[index + 1];
      new_elms->set(index + len, arg->Number());
    }

407 408
    if (*new_elms != array->elements()) {
      array->set_elements(*new_elms);
409 410 411 412 413 414
    }

    // Set the length.
    array->set_length(Smi::FromInt(new_length));
    return Smi::FromInt(new_length);
  }
415 416 417
}


418
BUILTIN(ArrayPop) {
419 420
  HandleScope scope(isolate);
  Handle<Object> receiver = args.receiver();
421
  MaybeHandle<FixedArrayBase> maybe_elms_obj =
422
      EnsureJSArrayWithWritableFastElements(isolate, receiver, NULL, 0);
423 424 425 426
  Handle<FixedArrayBase> elms_obj;
  if (!maybe_elms_obj.ToHandle(&elms_obj)) {
    return CallJsBuiltin(isolate, "ArrayPop", args);
  }
427 428

  Handle<JSArray> array = Handle<JSArray>::cast(receiver);
429
  DCHECK(!array->map()->is_observed());
430

431
  int len = Smi::cast(array->length())->value();
432
  if (len == 0) return isolate->heap()->undefined_value();
433

434 435
  ElementsAccessor* accessor = array->GetElementsAccessor();
  int new_length = len - 1;
436 437 438 439
  Handle<Object> element =
      accessor->Get(array, array, new_length, elms_obj).ToHandleChecked();
  if (element->IsTheHole()) {
    return CallJsBuiltin(isolate, "ArrayPop", args);
440
  }
441
  RETURN_FAILURE_ON_EXCEPTION(
442 443
      isolate,
      accessor->SetLength(array, handle(Smi::FromInt(new_length), isolate)));
444
  return *element;
445 446 447
}


448
BUILTIN(ArrayShift) {
449
  HandleScope scope(isolate);
450
  Heap* heap = isolate->heap();
451
  Handle<Object> receiver = args.receiver();
452
  MaybeHandle<FixedArrayBase> maybe_elms_obj =
453
      EnsureJSArrayWithWritableFastElements(isolate, receiver, NULL, 0);
454 455
  Handle<FixedArrayBase> elms_obj;
  if (!maybe_elms_obj.ToHandle(&elms_obj) ||
456 457
      !IsJSArrayFastElementMovingAllowed(heap,
                                         *Handle<JSArray>::cast(receiver))) {
458
    return CallJsBuiltin(isolate, "ArrayShift", args);
459
  }
460
  Handle<JSArray> array = Handle<JSArray>::cast(receiver);
461
  DCHECK(!array->map()->is_observed());
462

463
  int len = Smi::cast(array->length())->value();
464
  if (len == 0) return heap->undefined_value();
465

466
  // Get first element
467
  ElementsAccessor* accessor = array->GetElementsAccessor();
468 469
  Handle<Object> first =
    accessor->Get(array, array, 0, elms_obj).ToHandleChecked();
470
  if (first->IsTheHole()) {
471
    return CallJsBuiltin(isolate, "ArrayShift", args);
472
  }
473

474
  if (heap->CanMoveObjectStart(*elms_obj)) {
475
    array->set_elements(heap->LeftTrimFixedArray(*elms_obj, 1));
476 477
  } else {
    // Shift the elements.
478
    if (elms_obj->IsFixedArray()) {
479
      Handle<FixedArray> elms = Handle<FixedArray>::cast(elms_obj);
480
      DisallowHeapAllocation no_gc;
481
      heap->MoveElements(*elms, 0, 1, len - 1);
482 483
      elms->set(len - 1, heap->the_hole_value());
    } else {
484 485
      Handle<FixedDoubleArray> elms = Handle<FixedDoubleArray>::cast(elms_obj);
      MoveDoubleElements(*elms, 0, *elms, 1, len - 1);
486 487
      elms->set_the_hole(len - 1);
    }
488
  }
489 490 491 492

  // Set the length.
  array->set_length(Smi::FromInt(len - 1));

493
  return *first;
494 495 496
}


497
BUILTIN(ArrayUnshift) {
498
  HandleScope scope(isolate);
499
  Heap* heap = isolate->heap();
500
  Handle<Object> receiver = args.receiver();
501
  MaybeHandle<FixedArrayBase> maybe_elms_obj =
502
      EnsureJSArrayWithWritableFastElements(isolate, receiver, NULL, 0);
503 504
  Handle<FixedArrayBase> elms_obj;
  if (!maybe_elms_obj.ToHandle(&elms_obj) ||
505 506
      !IsJSArrayFastElementMovingAllowed(heap,
                                         *Handle<JSArray>::cast(receiver))) {
507
    return CallJsBuiltin(isolate, "ArrayUnshift", args);
508
  }
509
  Handle<JSArray> array = Handle<JSArray>::cast(receiver);
510
  DCHECK(!array->map()->is_observed());
511 512 513
  if (!array->HasFastSmiOrObjectElements()) {
    return CallJsBuiltin(isolate, "ArrayUnshift", args);
  }
514 515 516
  int len = Smi::cast(array->length())->value();
  int to_add = args.length() - 1;
  int new_length = len + to_add;
517 518
  // Currently fixed arrays cannot grow too big, so
  // we should never hit this case.
519
  DCHECK(to_add <= (Smi::kMaxValue - len));
520

521 522 523 524 525 526
  if (to_add > 0 && JSArray::WouldChangeReadOnlyLength(array, len + to_add)) {
    return CallJsBuiltin(isolate, "ArrayUnshift", args);
  }

  Handle<FixedArray> elms = Handle<FixedArray>::cast(elms_obj);

527 528
  JSObject::EnsureCanContainElements(array, &args, 1, to_add,
                                     DONT_ALLOW_DOUBLE_ELEMENTS);
529

530 531 532
  if (new_length > elms->length()) {
    // New backing storage is needed.
    int capacity = new_length + (new_length >> 1) + 16;
533 534
    Handle<FixedArray> new_elms =
        isolate->factory()->NewUninitializedFixedArray(capacity);
535

536 537
    ElementsKind kind = array->GetElementsKind();
    ElementsAccessor* accessor = array->GetElementsAccessor();
538
    accessor->CopyElements(
539 540
        elms, 0, kind, new_elms, to_add,
        ElementsAccessor::kCopyToEndAndInitializeToHole);
541

542
    elms = new_elms;
543
    array->set_elements(*elms);
544
  } else {
545
    DisallowHeapAllocation no_gc;
546
    heap->MoveElements(*elms, to_add, 0, len);
547 548 549
  }

  // Add the provided values.
550
  DisallowHeapAllocation no_gc;
551 552 553 554 555 556 557 558 559 560 561
  WriteBarrierMode mode = elms->GetWriteBarrierMode(no_gc);
  for (int i = 0; i < to_add; i++) {
    elms->set(i, args[i + 1], mode);
  }

  // Set the length.
  array->set_length(Smi::FromInt(new_length));
  return Smi::FromInt(new_length);
}


562
BUILTIN(ArraySlice) {
563
  HandleScope scope(isolate);
564
  Heap* heap = isolate->heap();
565
  Handle<Object> receiver = args.receiver();
566
  int len = -1;
567 568 569 570 571 572 573 574 575 576
  int relative_start = 0;
  int relative_end = 0;
  {
    DisallowHeapAllocation no_gc;
    if (receiver->IsJSArray()) {
      JSArray* array = JSArray::cast(*receiver);
      if (!IsJSArrayFastElementMovingAllowed(heap, array)) {
        AllowHeapAllocation allow_allocation;
        return CallJsBuiltin(isolate, "ArraySlice", args);
      }
577

578 579 580 581
      if (!array->HasFastElements()) {
        AllowHeapAllocation allow_allocation;
        return CallJsBuiltin(isolate, "ArraySlice", args);
      }
582

583
      len = Smi::cast(array->length())->value();
584
    } else {
585 586
      // Array.slice(arguments, ...) is quite a common idiom (notably more
      // than 50% of invocations in Web apps).  Treat it in C++ as well.
587 588
      Map* arguments_map =
          isolate->context()->native_context()->sloppy_arguments_map();
589 590 591 592 593 594 595 596 597

      bool is_arguments_object_with_fast_elements =
          receiver->IsJSObject() &&
          JSObject::cast(*receiver)->map() == arguments_map;
      if (!is_arguments_object_with_fast_elements) {
        AllowHeapAllocation allow_allocation;
        return CallJsBuiltin(isolate, "ArraySlice", args);
      }
      JSObject* object = JSObject::cast(*receiver);
598

599 600 601 602
      if (!object->HasFastElements()) {
        AllowHeapAllocation allow_allocation;
        return CallJsBuiltin(isolate, "ArraySlice", args);
      }
603

604 605 606 607 608 609 610 611
      Object* len_obj = object->InObjectPropertyAt(Heap::kArgumentsLengthIndex);
      if (!len_obj->IsSmi()) {
        AllowHeapAllocation allow_allocation;
        return CallJsBuiltin(isolate, "ArraySlice", args);
      }
      len = Smi::cast(len_obj)->value();
      if (len > object->elements()->length()) {
        AllowHeapAllocation allow_allocation;
612 613
        return CallJsBuiltin(isolate, "ArraySlice", args);
      }
614
    }
615

616
    DCHECK(len >= 0);
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
    int n_arguments = args.length() - 1;

    // Note carefully choosen defaults---if argument is missing,
    // it's undefined which gets converted to 0 for relative_start
    // and to len for relative_end.
    relative_start = 0;
    relative_end = len;
    if (n_arguments > 0) {
      Object* arg1 = args[1];
      if (arg1->IsSmi()) {
        relative_start = Smi::cast(arg1)->value();
      } else if (arg1->IsHeapNumber()) {
        double start = HeapNumber::cast(arg1)->value();
        if (start < kMinInt || start > kMaxInt) {
          AllowHeapAllocation allow_allocation;
632 633
          return CallJsBuiltin(isolate, "ArraySlice", args);
        }
634 635 636
        relative_start = std::isnan(start) ? 0 : static_cast<int>(start);
      } else if (!arg1->IsUndefined()) {
        AllowHeapAllocation allow_allocation;
637
        return CallJsBuiltin(isolate, "ArraySlice", args);
638
      }
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
      if (n_arguments > 1) {
        Object* arg2 = args[2];
        if (arg2->IsSmi()) {
          relative_end = Smi::cast(arg2)->value();
        } else if (arg2->IsHeapNumber()) {
          double end = HeapNumber::cast(arg2)->value();
          if (end < kMinInt || end > kMaxInt) {
            AllowHeapAllocation allow_allocation;
            return CallJsBuiltin(isolate, "ArraySlice", args);
          }
          relative_end = std::isnan(end) ? 0 : static_cast<int>(end);
        } else if (!arg2->IsUndefined()) {
          AllowHeapAllocation allow_allocation;
          return CallJsBuiltin(isolate, "ArraySlice", args);
        }
      }
655 656 657 658
    }
  }

  // ECMAScript 232, 3rd Edition, Section 15.4.4.10, step 6.
659 660
  int k = (relative_start < 0) ? Max(len + relative_start, 0)
                               : Min(relative_start, len);
661 662

  // ECMAScript 232, 3rd Edition, Section 15.4.4.10, step 8.
663 664
  int final = (relative_end < 0) ? Max(len + relative_end, 0)
                                 : Min(relative_end, len);
665

666 667
  // Calculate the length of result array.
  int result_len = Max(final - k, 0);
668

669 670 671
  Handle<JSObject> object = Handle<JSObject>::cast(receiver);
  Handle<FixedArrayBase> elms(object->elements(), isolate);

672 673
  ElementsKind kind = object->GetElementsKind();
  if (IsHoleyElementsKind(kind)) {
674
    DisallowHeapAllocation no_gc;
675 676 677
    bool packed = true;
    ElementsAccessor* accessor = ElementsAccessor::ForKind(kind);
    for (int i = k; i < final; i++) {
678
      if (!accessor->HasElement(object, object, i, elms)) {
679 680 681 682 683 684 685
        packed = false;
        break;
      }
    }
    if (packed) {
      kind = GetPackedElementsKind(kind);
    } else if (!receiver->IsJSArray()) {
686
      AllowHeapAllocation allow_allocation;
687 688 689 690
      return CallJsBuiltin(isolate, "ArraySlice", args);
    }
  }

691 692
  Handle<JSArray> result_array =
      isolate->factory()->NewJSArray(kind, result_len, result_len);
693

694
  DisallowHeapAllocation no_gc;
695
  if (result_len == 0) return *result_array;
696

697
  ElementsAccessor* accessor = object->GetElementsAccessor();
698 699
  accessor->CopyElements(
      elms, k, kind, handle(result_array->elements(), isolate), 0, result_len);
700
  return *result_array;
701 702 703
}


704
BUILTIN(ArraySplice) {
705
  HandleScope scope(isolate);
706
  Heap* heap = isolate->heap();
707
  Handle<Object> receiver = args.receiver();
708
  MaybeHandle<FixedArrayBase> maybe_elms_obj =
709
      EnsureJSArrayWithWritableFastElements(isolate, receiver, &args, 3);
710 711
  Handle<FixedArrayBase> elms_obj;
  if (!maybe_elms_obj.ToHandle(&elms_obj) ||
712 713
      !IsJSArrayFastElementMovingAllowed(heap,
                                         *Handle<JSArray>::cast(receiver))) {
714
    return CallJsBuiltin(isolate, "ArraySplice", args);
715
  }
716
  Handle<JSArray> array = Handle<JSArray>::cast(receiver);
717
  DCHECK(!array->map()->is_observed());
718

719 720 721 722
  int len = Smi::cast(array->length())->value();

  int n_arguments = args.length() - 1;

723
  int relative_start = 0;
724
  if (n_arguments > 0) {
725 726
    DisallowHeapAllocation no_gc;
    Object* arg1 = args[1];
727
    if (arg1->IsSmi()) {
728
      relative_start = Smi::cast(arg1)->value();
729
    } else if (arg1->IsHeapNumber()) {
730
      double start = HeapNumber::cast(arg1)->value();
731
      if (start < kMinInt || start > kMaxInt) {
732
        AllowHeapAllocation allow_allocation;
733 734
        return CallJsBuiltin(isolate, "ArraySplice", args);
      }
735
      relative_start = std::isnan(start) ? 0 : static_cast<int>(start);
736
    } else if (!arg1->IsUndefined()) {
737
      AllowHeapAllocation allow_allocation;
738
      return CallJsBuiltin(isolate, "ArraySplice", args);
739
    }
740
  }
741 742
  int actual_start = (relative_start < 0) ? Max(len + relative_start, 0)
                                          : Min(relative_start, len);
743 744

  // SpiderMonkey, TraceMonkey and JSC treat the case where no delete count is
745 746
  // given as a request to delete all the elements from the start.
  // And it differs from the case of undefined delete count.
747 748
  // This does not follow ECMA-262, but we do the same for
  // compatibility.
749 750
  int actual_delete_count;
  if (n_arguments == 1) {
751
    DCHECK(len - actual_start >= 0);
752 753 754 755
    actual_delete_count = len - actual_start;
  } else {
    int value = 0;  // ToInteger(undefined) == 0
    if (n_arguments > 1) {
756
      DisallowHeapAllocation no_gc;
757 758 759 760
      Object* arg2 = args[2];
      if (arg2->IsSmi()) {
        value = Smi::cast(arg2)->value();
      } else {
761
        AllowHeapAllocation allow_allocation;
762
        return CallJsBuiltin(isolate, "ArraySplice", args);
763
      }
764
    }
765
    actual_delete_count = Min(Max(value, 0), len - actual_start);
766 767
  }

768 769 770 771 772 773 774 775 776 777 778
  ElementsKind elements_kind = array->GetElementsKind();

  int item_count = (n_arguments > 1) ? (n_arguments - 2) : 0;
  int new_length = len - actual_delete_count + item_count;

  // For double mode we do not support changing the length.
  if (new_length > len && IsFastDoubleElementsKind(elements_kind)) {
    return CallJsBuiltin(isolate, "ArraySplice", args);
  }

  if (new_length == 0) {
779
    Handle<JSArray> result = isolate->factory()->NewJSArrayWithElements(
780 781 782
        elms_obj, elements_kind, actual_delete_count);
    array->set_elements(heap->empty_fixed_array());
    array->set_length(Smi::FromInt(0));
783
    return *result;
784 785
  }

786 787 788 789
  Handle<JSArray> result_array =
      isolate->factory()->NewJSArray(elements_kind,
                                     actual_delete_count,
                                     actual_delete_count);
790

791
  if (actual_delete_count > 0) {
792
    DisallowHeapAllocation no_gc;
793
    ElementsAccessor* accessor = array->GetElementsAccessor();
794
    accessor->CopyElements(
795 796
        elms_obj, actual_start, elements_kind,
        handle(result_array->elements(), isolate), 0, actual_delete_count);
797
  }
798

799
  bool elms_changed = false;
800
  if (item_count < actual_delete_count) {
801
    // Shrink the array.
802
    const bool trim_array = !heap->lo_space()->Contains(*elms_obj) &&
803 804 805 806 807
      ((actual_start + item_count) <
          (len - actual_delete_count - actual_start));
    if (trim_array) {
      const int delta = actual_delete_count - item_count;

808
      if (elms_obj->IsFixedDoubleArray()) {
809 810 811
        Handle<FixedDoubleArray> elms =
            Handle<FixedDoubleArray>::cast(elms_obj);
        MoveDoubleElements(*elms, delta, *elms, 0, actual_start);
812
      } else {
813
        Handle<FixedArray> elms = Handle<FixedArray>::cast(elms_obj);
814
        DisallowHeapAllocation no_gc;
815
        heap->MoveElements(*elms, delta, 0, actual_start);
816 817
      }

818 819
      if (heap->CanMoveObjectStart(*elms_obj)) {
        // On the fast path we move the start of the object in memory.
820
        elms_obj = handle(heap->LeftTrimFixedArray(*elms_obj, delta));
821 822 823 824 825 826 827
      } else {
        // This is the slow path. We are going to move the elements to the left
        // by copying them. For trimmed values we store the hole.
        if (elms_obj->IsFixedDoubleArray()) {
          Handle<FixedDoubleArray> elms =
              Handle<FixedDoubleArray>::cast(elms_obj);
          MoveDoubleElements(*elms, 0, *elms, delta, len - delta);
828
          elms->FillWithHoles(len - delta, len);
829 830 831 832
        } else {
          Handle<FixedArray> elms = Handle<FixedArray>::cast(elms_obj);
          DisallowHeapAllocation no_gc;
          heap->MoveElements(*elms, 0, delta, len - delta);
833
          elms->FillWithHoles(len - delta, len);
834 835
        }
      }
836
      elms_changed = true;
837
    } else {
838
      if (elms_obj->IsFixedDoubleArray()) {
839 840 841 842
        Handle<FixedDoubleArray> elms =
            Handle<FixedDoubleArray>::cast(elms_obj);
        MoveDoubleElements(*elms, actual_start + item_count,
                           *elms, actual_start + actual_delete_count,
843
                           (len - actual_delete_count - actual_start));
844
        elms->FillWithHoles(new_length, len);
845
      } else {
846
        Handle<FixedArray> elms = Handle<FixedArray>::cast(elms_obj);
847
        DisallowHeapAllocation no_gc;
848
        heap->MoveElements(*elms, actual_start + item_count,
849 850
                           actual_start + actual_delete_count,
                           (len - actual_delete_count - actual_start));
851
        elms->FillWithHoles(new_length, len);
852
      }
853
    }
854
  } else if (item_count > actual_delete_count) {
855
    Handle<FixedArray> elms = Handle<FixedArray>::cast(elms_obj);
856 857
    // Currently fixed arrays cannot grow too big, so
    // we should never hit this case.
858
    DCHECK((item_count - actual_delete_count) <= (Smi::kMaxValue - len));
859

860 861 862 863
    // Check if array need to grow.
    if (new_length > elms->length()) {
      // New backing storage is needed.
      int capacity = new_length + (new_length >> 1) + 16;
864 865
      Handle<FixedArray> new_elms =
          isolate->factory()->NewUninitializedFixedArray(capacity);
866

867
      DisallowHeapAllocation no_gc;
868

869 870
      ElementsKind kind = array->GetElementsKind();
      ElementsAccessor* accessor = array->GetElementsAccessor();
871 872
      if (actual_start > 0) {
        // Copy the part before actual_start as is.
873
        accessor->CopyElements(
874
            elms, 0, kind, new_elms, 0, actual_start);
875
      }
876
      accessor->CopyElements(
877
          elms, actual_start + actual_delete_count, kind,
878
          new_elms, actual_start + item_count,
879
          ElementsAccessor::kCopyToEndAndInitializeToHole);
880

881
      elms_obj = new_elms;
882
      elms_changed = true;
883
    } else {
884
      DisallowHeapAllocation no_gc;
885
      heap->MoveElements(*elms, actual_start + item_count,
886 887
                         actual_start + actual_delete_count,
                         (len - actual_delete_count - actual_start));
888 889 890
    }
  }

891
  if (IsFastDoubleElementsKind(elements_kind)) {
892
    Handle<FixedDoubleArray> elms = Handle<FixedDoubleArray>::cast(elms_obj);
893 894 895 896 897 898 899 900 901
    for (int k = actual_start; k < actual_start + item_count; k++) {
      Object* arg = args[3 + k - actual_start];
      if (arg->IsSmi()) {
        elms->set(k, Smi::cast(arg)->value());
      } else {
        elms->set(k, HeapNumber::cast(arg)->value());
      }
    }
  } else {
902
    Handle<FixedArray> elms = Handle<FixedArray>::cast(elms_obj);
903
    DisallowHeapAllocation no_gc;
904 905 906 907
    WriteBarrierMode mode = elms->GetWriteBarrierMode(no_gc);
    for (int k = actual_start; k < actual_start + item_count; k++) {
      elms->set(k, args[3 + k - actual_start], mode);
    }
908 909
  }

910
  if (elms_changed) {
911
    array->set_elements(*elms_obj);
912
  }
913 914 915
  // Set the length.
  array->set_length(Smi::FromInt(new_length));

916
  return *result_array;
917 918 919
}


920
BUILTIN(ArrayConcat) {
921
  HandleScope scope(isolate);
922

923 924
  int n_arguments = args.length();
  int result_len = 0;
925
  ElementsKind elements_kind = GetInitialFastElementsKind();
926
  bool has_double = false;
927
  {
928
    DisallowHeapAllocation no_gc;
929 930 931 932 933
    Heap* heap = isolate->heap();
    Context* native_context = isolate->context()->native_context();
    JSObject* array_proto =
        JSObject::cast(native_context->array_function()->prototype());
    if (!ArrayPrototypeHasNoElements(heap, native_context, array_proto)) {
934
      AllowHeapAllocation allow_allocation;
935
      return CallJsBuiltin(isolate, "ArrayConcatJS", args);
936
    }
937

938 939 940 941 942
    // Iterate through all the arguments performing checks
    // and calculating total length.
    bool is_holey = false;
    for (int i = 0; i < n_arguments; i++) {
      Object* arg = args[i];
943 944 945
      PrototypeIterator iter(isolate, arg);
      if (!arg->IsJSArray() || !JSArray::cast(arg)->HasFastElements() ||
          iter.GetCurrent() != array_proto) {
946
        AllowHeapAllocation allow_allocation;
947
        return CallJsBuiltin(isolate, "ArrayConcatJS", args);
948 949
      }
      int len = Smi::cast(JSArray::cast(arg)->length())->value();
950

951 952 953 954 955
      // We shouldn't overflow when adding another len.
      const int kHalfOfMaxInt = 1 << (kBitsPerInt - 2);
      STATIC_ASSERT(FixedArray::kMaxLength < kHalfOfMaxInt);
      USE(kHalfOfMaxInt);
      result_len += len;
956
      DCHECK(result_len >= 0);
957

958 959
      if (result_len > FixedDoubleArray::kMaxLength) {
        AllowHeapAllocation allow_allocation;
960
        return CallJsBuiltin(isolate, "ArrayConcatJS", args);
961 962 963 964 965 966 967 968
      }

      ElementsKind arg_kind = JSArray::cast(arg)->map()->elements_kind();
      has_double = has_double || IsFastDoubleElementsKind(arg_kind);
      is_holey = is_holey || IsFastHoleyElementsKind(arg_kind);
      if (IsMoreGeneralElementsKindTransition(elements_kind, arg_kind)) {
        elements_kind = arg_kind;
      }
969
    }
970
    if (is_holey) elements_kind = GetHoleyElementsKind(elements_kind);
971 972
  }

973 974 975 976 977 978
  // 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.
  ArrayStorageAllocationMode mode =
      has_double && IsFastObjectElementsKind(elements_kind)
      ? INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE : DONT_INITIALIZE_ARRAY_ELEMENTS;
979 980 981 982 983 984
  Handle<JSArray> result_array =
      isolate->factory()->NewJSArray(elements_kind,
                                     result_len,
                                     result_len,
                                     mode);
  if (result_len == 0) return *result_array;
985

986
  int j = 0;
987
  Handle<FixedArrayBase> storage(result_array->elements(), isolate);
988
  ElementsAccessor* accessor = ElementsAccessor::ForKind(elements_kind);
989
  for (int i = 0; i < n_arguments; i++) {
990 991 992
    // TODO(ishell): It is crucial to keep |array| as a raw pointer to avoid
    // performance degradation. Revisit this later.
    JSArray* array = JSArray::cast(args[i]);
993
    int len = Smi::cast(array->length())->value();
994
    ElementsKind from_kind = array->GetElementsKind();
995
    if (len > 0) {
996
      accessor->CopyElements(array, 0, from_kind, storage, j, len);
997 998
      j += len;
    }
999
  }
1000

1001
  DCHECK(j == result_len);
1002

1003
  return *result_array;
1004 1005 1006
}


1007
// -----------------------------------------------------------------------------
1008
// Generator and strict mode poison pills
1009 1010


1011
BUILTIN(StrictModePoisonPill) {
1012
  HandleScope scope(isolate);
1013
  return isolate->Throw(*isolate->factory()->NewTypeError(
1014
      "strict_poison_pill", HandleVector<Object>(NULL, 0)));
1015 1016
}

1017

1018 1019 1020 1021 1022 1023 1024
BUILTIN(GeneratorPoisonPill) {
  HandleScope scope(isolate);
  return isolate->Throw(*isolate->factory()->NewTypeError(
      "generator_poison_pill", HandleVector<Object>(NULL, 0)));
}


1025 1026 1027 1028
// -----------------------------------------------------------------------------
//


1029 1030 1031 1032 1033 1034
// Searches the hidden prototype chain of the given object for the first
// object that is an instance of the given type.  If no such object can
// be found then Heap::null_value() is returned.
static inline Object* FindHidden(Heap* heap,
                                 Object* object,
                                 FunctionTemplateInfo* type) {
1035 1036 1037 1038 1039 1040
  for (PrototypeIterator iter(heap->isolate(), object,
                              PrototypeIterator::START_AT_RECEIVER);
       !iter.IsAtEnd(PrototypeIterator::END_AT_NON_HIDDEN); iter.Advance()) {
    if (type->IsTemplateFor(iter.GetCurrent())) {
      return iter.GetCurrent();
    }
1041 1042 1043 1044 1045
  }
  return heap->null_value();
}


1046 1047 1048
// Returns the holder JSObject if the function can legally be called
// with this receiver.  Returns Heap::null_value() if the call is
// illegal.  Any arguments that don't fit the expected type is
1049 1050 1051
// overwritten with undefined.  Note that holder and the arguments are
// implicitly rewritten with the first object in the hidden prototype
// chain that actually has the expected type.
1052 1053
static inline Object* TypeCheck(Heap* heap,
                                int argc,
1054 1055 1056
                                Object** argv,
                                FunctionTemplateInfo* info) {
  Object* recv = argv[0];
1057 1058
  // API calls are only supported with JSObject receivers.
  if (!recv->IsJSObject()) return heap->null_value();
1059 1060 1061 1062 1063 1064 1065
  Object* sig_obj = info->signature();
  if (sig_obj->IsUndefined()) return recv;
  SignatureInfo* sig = SignatureInfo::cast(sig_obj);
  // If necessary, check the receiver
  Object* recv_type = sig->receiver();
  Object* holder = recv;
  if (!recv_type->IsUndefined()) {
1066 1067
    holder = FindHidden(heap, holder, FunctionTemplateInfo::cast(recv_type));
    if (holder == heap->null_value()) return heap->null_value();
1068 1069 1070 1071 1072 1073
  }
  Object* args_obj = sig->args();
  // If there is no argument signature we're done
  if (args_obj->IsUndefined()) return holder;
  FixedArray* args = FixedArray::cast(args_obj);
  int length = args->length();
1074
  if (argc <= length) length = argc - 1;
1075 1076 1077 1078 1079
  for (int i = 0; i < length; i++) {
    Object* argtype = args->get(i);
    if (argtype->IsUndefined()) continue;
    Object** arg = &argv[-1 - i];
    Object* current = *arg;
1080 1081 1082
    current = FindHidden(heap, current, FunctionTemplateInfo::cast(argtype));
    if (current == heap->null_value()) current = heap->undefined_value();
    *arg = current;
1083 1084 1085 1086 1087
  }
  return holder;
}


1088
template <bool is_construct>
1089
MUST_USE_RESULT static Object* HandleApiCallHelper(
1090
    BuiltinArguments<NEEDS_CALLED_FUNCTION> args, Isolate* isolate) {
1091
  DCHECK(is_construct == CalledAsConstructor(isolate));
1092
  Heap* heap = isolate->heap();
1093

1094
  HandleScope scope(isolate);
1095
  Handle<JSFunction> function = args.called_function();
1096
  DCHECK(function->shared()->IsApiFunction());
1097

1098 1099
  Handle<FunctionTemplateInfo> fun_data(
      function->shared()->get_api_func_data(), isolate);
1100
  if (is_construct) {
1101 1102 1103 1104
    ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
        isolate, fun_data,
        isolate->factory()->ConfigureInstance(
            fun_data, Handle<JSObject>::cast(args.receiver())));
1105 1106
  }

1107
  SharedFunctionInfo* shared = function->shared();
1108
  if (shared->strict_mode() == SLOPPY && !shared->native()) {
1109
    Object* recv = args[0];
1110
    DCHECK(!recv->IsNull());
1111
    if (recv->IsUndefined()) args[0] = function->global_proxy();
1112 1113
  }

1114
  Object* raw_holder = TypeCheck(heap, args.length(), &args[0], *fun_data);
1115 1116 1117 1118

  if (raw_holder->IsNull()) {
    // This function cannot be called with the given receiver.  Abort!
    Handle<Object> obj =
1119 1120 1121
        isolate->factory()->NewTypeError(
            "illegal_invocation", HandleVector(&function, 1));
    return isolate->Throw(*obj);
1122 1123 1124 1125 1126 1127
  }

  Object* raw_call_data = fun_data->call_code();
  if (!raw_call_data->IsUndefined()) {
    CallHandlerInfo* call_data = CallHandlerInfo::cast(raw_call_data);
    Object* callback_obj = call_data->callback();
1128 1129
    v8::FunctionCallback callback =
        v8::ToCData<v8::FunctionCallback>(callback_obj);
1130 1131 1132
    Object* data_obj = call_data->data();
    Object* result;

1133
    LOG(isolate, ApiObjectAccess("call", JSObject::cast(*args.receiver())));
1134
    DCHECK(raw_holder->IsJSObject());
1135

1136 1137 1138 1139 1140 1141 1142
    FunctionCallbackArguments custom(isolate,
                                     data_obj,
                                     *function,
                                     raw_holder,
                                     &args[0] - 1,
                                     args.length() - 1,
                                     is_construct);
1143

1144
    v8::Handle<v8::Value> value = custom.Call(callback);
1145
    if (value.IsEmpty()) {
1146
      result = heap->undefined_value();
1147 1148
    } else {
      result = *reinterpret_cast<Object**>(*value);
1149
      result->VerifyApiCallResultType();
1150 1151
    }

1152
    RETURN_FAILURE_IF_SCHEDULED_EXCEPTION(isolate);
1153 1154 1155
    if (!is_construct || result->IsJSObject()) return result;
  }

1156 1157 1158 1159 1160
  return *args.receiver();
}


BUILTIN(HandleApiCall) {
1161
  return HandleApiCallHelper<false>(args, isolate);
1162 1163 1164 1165
}


BUILTIN(HandleApiCallConstruct) {
1166
  return HandleApiCallHelper<true>(args, isolate);
1167 1168 1169
}


1170 1171 1172
// Helper function to handle calls to non-function objects created through the
// API. The object can be called as either a constructor (using new) or just as
// a function (without new).
1173
MUST_USE_RESULT static Object* HandleApiCallAsFunctionOrConstructor(
1174
    Isolate* isolate,
1175 1176
    bool is_construct_call,
    BuiltinArguments<NO_EXTRA_ARGUMENTS> args) {
1177 1178
  // Non-functions are never called as constructors. Even if this is an object
  // called as a constructor the delegate call is not a construct call.
1179
  DCHECK(!CalledAsConstructor(isolate));
1180
  Heap* heap = isolate->heap();
1181

1182
  Handle<Object> receiver = args.receiver();
1183

1184
  // Get the object called.
1185
  JSObject* obj = JSObject::cast(*receiver);
1186 1187 1188

  // Get the invocation callback from the function descriptor that was
  // used to create the called object.
1189
  DCHECK(obj->map()->has_instance_call_handler());
1190
  JSFunction* constructor = JSFunction::cast(obj->map()->constructor());
1191
  DCHECK(constructor->shared()->IsApiFunction());
1192
  Object* handler =
1193
      constructor->shared()->get_api_func_data()->instance_call_handler();
1194
  DCHECK(!handler->IsUndefined());
1195 1196
  CallHandlerInfo* call_data = CallHandlerInfo::cast(handler);
  Object* callback_obj = call_data->callback();
1197 1198
  v8::FunctionCallback callback =
      v8::ToCData<v8::FunctionCallback>(callback_obj);
1199 1200 1201

  // Get the data for the call and perform the callback.
  Object* result;
1202
  {
1203 1204
    HandleScope scope(isolate);
    LOG(isolate, ApiObjectAccess("call non-function", obj));
1205

1206 1207 1208 1209 1210 1211 1212
    FunctionCallbackArguments custom(isolate,
                                     call_data->data(),
                                     constructor,
                                     obj,
                                     &args[0] - 1,
                                     args.length() - 1,
                                     is_construct_call);
1213
    v8::Handle<v8::Value> value = custom.Call(callback);
1214
    if (value.IsEmpty()) {
1215
      result = heap->undefined_value();
1216 1217
    } else {
      result = *reinterpret_cast<Object**>(*value);
1218
      result->VerifyApiCallResultType();
1219 1220 1221
    }
  }
  // Check for exceptions and return result.
1222
  RETURN_FAILURE_IF_SCHEDULED_EXCEPTION(isolate);
1223 1224
  return result;
}
1225 1226 1227 1228 1229


// Handle calls to non-function objects created through the API. This delegate
// function is used when the call is a normal function call.
BUILTIN(HandleApiCallAsFunction) {
1230
  return HandleApiCallAsFunctionOrConstructor(isolate, false, args);
1231 1232 1233 1234 1235 1236
}


// Handle calls to non-function objects created through the API. This delegate
// function is used when the call is a construct call.
BUILTIN(HandleApiCallAsConstructor) {
1237
  return HandleApiCallAsFunctionOrConstructor(isolate, true, args);
1238
}
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250


static void Generate_LoadIC_Miss(MacroAssembler* masm) {
  LoadIC::GenerateMiss(masm);
}


static void Generate_LoadIC_Normal(MacroAssembler* masm) {
  LoadIC::GenerateNormal(masm);
}


1251
static void Generate_LoadIC_Getter_ForDeopt(MacroAssembler* masm) {
1252
  NamedLoadHandlerCompiler::GenerateLoadViaGetterForDeopt(masm);
1253 1254 1255
}


1256 1257 1258 1259 1260
static void Generate_LoadIC_Slow(MacroAssembler* masm) {
  LoadIC::GenerateRuntimeGetProperty(masm);
}


1261 1262 1263 1264 1265
static void Generate_KeyedLoadIC_Initialize(MacroAssembler* masm) {
  KeyedLoadIC::GenerateInitialize(masm);
}


danno@chromium.org's avatar
danno@chromium.org committed
1266 1267 1268 1269 1270
static void Generate_KeyedLoadIC_Slow(MacroAssembler* masm) {
  KeyedLoadIC::GenerateRuntimeGetProperty(masm);
}


1271
static void Generate_KeyedLoadIC_Miss(MacroAssembler* masm) {
1272
  KeyedLoadIC::GenerateMiss(masm);
1273 1274 1275 1276 1277 1278 1279 1280
}


static void Generate_KeyedLoadIC_Generic(MacroAssembler* masm) {
  KeyedLoadIC::GenerateGeneric(masm);
}


1281 1282 1283 1284 1285
static void Generate_KeyedLoadIC_String(MacroAssembler* masm) {
  KeyedLoadIC::GenerateString(masm);
}


1286 1287 1288 1289
static void Generate_KeyedLoadIC_PreMonomorphic(MacroAssembler* masm) {
  KeyedLoadIC::GeneratePreMonomorphic(masm);
}

1290

1291 1292 1293 1294
static void Generate_KeyedLoadIC_IndexedInterceptor(MacroAssembler* masm) {
  KeyedLoadIC::GenerateIndexedInterceptor(masm);
}

1295

1296 1297
static void Generate_KeyedLoadIC_SloppyArguments(MacroAssembler* masm) {
  KeyedLoadIC::GenerateSloppyArguments(masm);
1298
}
1299

1300

1301 1302 1303 1304 1305
static void Generate_StoreIC_Slow(MacroAssembler* masm) {
  StoreIC::GenerateSlow(masm);
}


1306 1307 1308 1309 1310
static void Generate_StoreIC_Miss(MacroAssembler* masm) {
  StoreIC::GenerateMiss(masm);
}


1311 1312 1313 1314 1315
static void Generate_StoreIC_Normal(MacroAssembler* masm) {
  StoreIC::GenerateNormal(masm);
}


1316
static void Generate_StoreIC_Setter_ForDeopt(MacroAssembler* masm) {
1317
  NamedStoreHandlerCompiler::GenerateStoreViaSetterForDeopt(masm);
1318 1319 1320
}


1321
static void Generate_KeyedStoreIC_Generic(MacroAssembler* masm) {
1322
  KeyedStoreIC::GenerateGeneric(masm, SLOPPY);
1323 1324 1325 1326
}


static void Generate_KeyedStoreIC_Generic_Strict(MacroAssembler* masm) {
1327
  KeyedStoreIC::GenerateGeneric(masm, STRICT);
1328 1329 1330 1331
}


static void Generate_KeyedStoreIC_Miss(MacroAssembler* masm) {
1332
  KeyedStoreIC::GenerateMiss(masm);
danno@chromium.org's avatar
danno@chromium.org committed
1333 1334 1335 1336 1337
}


static void Generate_KeyedStoreIC_Slow(MacroAssembler* masm) {
  KeyedStoreIC::GenerateSlow(masm);
1338 1339 1340 1341 1342 1343 1344 1345
}


static void Generate_KeyedStoreIC_Initialize(MacroAssembler* masm) {
  KeyedStoreIC::GenerateInitialize(masm);
}


1346 1347 1348 1349
static void Generate_KeyedStoreIC_Initialize_Strict(MacroAssembler* masm) {
  KeyedStoreIC::GenerateInitialize(masm);
}

1350

1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
static void Generate_KeyedStoreIC_PreMonomorphic(MacroAssembler* masm) {
  KeyedStoreIC::GeneratePreMonomorphic(masm);
}


static void Generate_KeyedStoreIC_PreMonomorphic_Strict(MacroAssembler* masm) {
  KeyedStoreIC::GeneratePreMonomorphic(masm);
}


1361 1362
static void Generate_KeyedStoreIC_SloppyArguments(MacroAssembler* masm) {
  KeyedStoreIC::GenerateSloppyArguments(masm);
1363
}
1364

1365

1366
static void Generate_CallICStub_DebugBreak(MacroAssembler* masm) {
1367
  DebugCodegen::GenerateCallICStubDebugBreak(masm);
1368 1369 1370
}


1371
static void Generate_LoadIC_DebugBreak(MacroAssembler* masm) {
1372
  DebugCodegen::GenerateLoadICDebugBreak(masm);
1373 1374 1375 1376
}


static void Generate_StoreIC_DebugBreak(MacroAssembler* masm) {
1377
  DebugCodegen::GenerateStoreICDebugBreak(masm);
1378 1379 1380 1381
}


static void Generate_KeyedLoadIC_DebugBreak(MacroAssembler* masm) {
1382
  DebugCodegen::GenerateKeyedLoadICDebugBreak(masm);
1383 1384 1385 1386
}


static void Generate_KeyedStoreIC_DebugBreak(MacroAssembler* masm) {
1387
  DebugCodegen::GenerateKeyedStoreICDebugBreak(masm);
1388 1389 1390
}


1391
static void Generate_CompareNilIC_DebugBreak(MacroAssembler* masm) {
1392
  DebugCodegen::GenerateCompareNilICDebugBreak(masm);
1393 1394 1395
}


1396
static void Generate_Return_DebugBreak(MacroAssembler* masm) {
1397
  DebugCodegen::GenerateReturnDebugBreak(masm);
1398 1399 1400
}


1401
static void Generate_CallFunctionStub_DebugBreak(MacroAssembler* masm) {
1402
  DebugCodegen::GenerateCallFunctionStubDebugBreak(masm);
1403
}
1404

1405

1406
static void Generate_CallConstructStub_DebugBreak(MacroAssembler* masm) {
1407
  DebugCodegen::GenerateCallConstructStubDebugBreak(masm);
1408 1409 1410 1411 1412
}


static void Generate_CallConstructStub_Recording_DebugBreak(
    MacroAssembler* masm) {
1413
  DebugCodegen::GenerateCallConstructStubRecordDebugBreak(masm);
1414 1415 1416
}


1417
static void Generate_Slot_DebugBreak(MacroAssembler* masm) {
1418
  DebugCodegen::GenerateSlotDebugBreak(masm);
1419 1420 1421
}


1422
static void Generate_PlainReturn_LiveEdit(MacroAssembler* masm) {
1423
  DebugCodegen::GeneratePlainReturnLiveEdit(masm);
1424 1425
}

1426

1427
static void Generate_FrameDropper_LiveEdit(MacroAssembler* masm) {
1428
  DebugCodegen::GenerateFrameDropperLiveEdit(masm);
1429
}
1430

1431 1432 1433 1434 1435 1436 1437 1438 1439 1440

Builtins::Builtins() : initialized_(false) {
  memset(builtins_, 0, sizeof(builtins_[0]) * builtin_count);
  memset(names_, 0, sizeof(names_[0]) * builtin_count);
}


Builtins::~Builtins() {
}

1441

1442
#define DEF_ENUM_C(name, ignore) FUNCTION_ADDR(Builtin_##name),
1443 1444 1445
Address const Builtins::c_functions_[cfunction_count] = {
  BUILTIN_LIST_C(DEF_ENUM_C)
};
1446 1447 1448 1449
#undef DEF_ENUM_C

#define DEF_JS_NAME(name, ignore) #name,
#define DEF_JS_ARGC(ignore, argc) argc,
1450
const char* const Builtins::javascript_names_[id_count] = {
1451 1452 1453
  BUILTINS_LIST_JS(DEF_JS_NAME)
};

1454
int const Builtins::javascript_argc_[id_count] = {
1455 1456 1457 1458 1459
  BUILTINS_LIST_JS(DEF_JS_ARGC)
};
#undef DEF_JS_NAME
#undef DEF_JS_ARGC

1460 1461 1462 1463 1464 1465 1466 1467
struct BuiltinDesc {
  byte* generator;
  byte* c_code;
  const char* s_name;  // name is only used for generating log information.
  int name;
  Code::Flags flags;
  BuiltinExtraArguments extra_args;
};
1468

1469 1470
#define BUILTIN_FUNCTION_TABLE_INIT { V8_ONCE_INIT, {} }

1471 1472
class BuiltinFunctionTable {
 public:
1473
  BuiltinDesc* functions() {
1474
    base::CallOnce(&once_, &Builtins::InitBuiltinFunctionTable);
1475
    return functions_;
1476 1477
  }

1478
  base::OnceType once_;
1479
  BuiltinDesc functions_[Builtins::builtin_count + 1];
1480 1481 1482

  friend class Builtins;
};
1483

1484 1485
static BuiltinFunctionTable builtin_function_table =
    BUILTIN_FUNCTION_TABLE_INIT;
1486 1487 1488 1489 1490 1491

// Define array of pointers to generators and C builtin functions.
// We do this in a sort of roundabout way so that we can do the initialization
// within the lexical scope of Builtins:: and within a context where
// Code::Flags names a non-abstract type.
void Builtins::InitBuiltinFunctionTable() {
1492
  BuiltinDesc* functions = builtin_function_table.functions_;
1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512
  functions[builtin_count].generator = NULL;
  functions[builtin_count].c_code = NULL;
  functions[builtin_count].s_name = NULL;
  functions[builtin_count].name = builtin_count;
  functions[builtin_count].flags = static_cast<Code::Flags>(0);
  functions[builtin_count].extra_args = NO_EXTRA_ARGUMENTS;

#define DEF_FUNCTION_PTR_C(aname, aextra_args)                         \
    functions->generator = FUNCTION_ADDR(Generate_Adaptor);            \
    functions->c_code = FUNCTION_ADDR(Builtin_##aname);                \
    functions->s_name = #aname;                                        \
    functions->name = c_##aname;                                       \
    functions->flags = Code::ComputeFlags(Code::BUILTIN);              \
    functions->extra_args = aextra_args;                               \
    ++functions;

#define DEF_FUNCTION_PTR_A(aname, kind, state, extra)                       \
    functions->generator = FUNCTION_ADDR(Generate_##aname);                 \
    functions->c_code = NULL;                                               \
    functions->s_name = #aname;                                             \
1513
    functions->name = k##aname;                                             \
1514 1515 1516 1517 1518 1519
    functions->flags = Code::ComputeFlags(Code::kind,                       \
                                          state,                            \
                                          extra);                           \
    functions->extra_args = NO_EXTRA_ARGUMENTS;                             \
    ++functions;

1520
#define DEF_FUNCTION_PTR_H(aname, kind)                                     \
1521 1522 1523 1524
    functions->generator = FUNCTION_ADDR(Generate_##aname);                 \
    functions->c_code = NULL;                                               \
    functions->s_name = #aname;                                             \
    functions->name = k##aname;                                             \
1525
    functions->flags = Code::ComputeHandlerFlags(Code::kind);               \
1526 1527 1528
    functions->extra_args = NO_EXTRA_ARGUMENTS;                             \
    ++functions;

1529 1530
  BUILTIN_LIST_C(DEF_FUNCTION_PTR_C)
  BUILTIN_LIST_A(DEF_FUNCTION_PTR_A)
1531
  BUILTIN_LIST_H(DEF_FUNCTION_PTR_H)
1532
  BUILTIN_LIST_DEBUG_A(DEF_FUNCTION_PTR_A)
1533 1534 1535

#undef DEF_FUNCTION_PTR_C
#undef DEF_FUNCTION_PTR_A
1536 1537
}

1538

1539
void Builtins::SetUp(Isolate* isolate, bool create_heap_objects) {
1540
  DCHECK(!initialized_);
1541 1542

  // Create a scope for the handles in the builtins.
1543
  HandleScope scope(isolate);
1544

1545
  const BuiltinDesc* functions = builtin_function_table.functions();
1546 1547

  // For now we generate builtin adaptor code into a stack-allocated
1548 1549
  // buffer, before copying it into individual code objects. Be careful
  // with alignment, some platforms don't like unaligned code.
1550 1551 1552 1553 1554 1555 1556
#ifdef DEBUG
  // We can generate a lot of debug code on Arm64.
  const size_t buffer_size = 32*KB;
#else
  const size_t buffer_size = 8*KB;
#endif
  union { int force_alignment; byte buffer[buffer_size]; } u;
1557 1558 1559 1560 1561

  // Traverse the list of builtins and generate an adaptor in a
  // separate code object for each one.
  for (int i = 0; i < builtin_count; i++) {
    if (create_heap_objects) {
1562
      MacroAssembler masm(isolate, u.buffer, sizeof u.buffer);
1563
      // Generate the code/adaptor.
1564
      typedef void (*Generator)(MacroAssembler*, int, BuiltinExtraArguments);
1565 1566 1567 1568
      Generator g = FUNCTION_CAST<Generator>(functions[i].generator);
      // We pass all arguments to the generator, but it may not use all of
      // them.  This works because the first arguments are on top of the
      // stack.
1569
      DCHECK(!masm.has_frame());
1570
      g(&masm, functions[i].name, functions[i].extra_args);
1571 1572 1573 1574
      // Move the code into the object heap.
      CodeDesc desc;
      masm.GetCode(&desc);
      Code::Flags flags =  functions[i].flags;
1575 1576
      Handle<Code> code =
          isolate->factory()->NewCode(desc, flags, masm.CodeObject());
1577
      // Log the event and add the code to the builtins array.
1578
      PROFILE(isolate,
1579 1580
              CodeCreateEvent(Logger::BUILTIN_TAG, *code, functions[i].s_name));
      builtins_[i] = *code;
1581
      if (code->kind() == Code::BUILTIN) code->set_builtin_index(i);
1582
#ifdef ENABLE_DISASSEMBLER
1583
      if (FLAG_print_builtin_code) {
1584
        CodeTracer::Scope trace_scope(isolate->GetCodeTracer());
1585 1586 1587 1588
        OFStream os(trace_scope.file());
        os << "Builtin: " << functions[i].s_name << "\n";
        code->Disassemble(functions[i].s_name, os);
        os << "\n";
1589 1590
      }
#endif
1591 1592 1593 1594 1595 1596 1597 1598
    } else {
      // Deserializing. The values will be filled in during IterateBuiltins.
      builtins_[i] = NULL;
    }
    names_[i] = functions[i].s_name;
  }

  // Mark as initialized.
1599
  initialized_ = true;
1600 1601 1602 1603
}


void Builtins::TearDown() {
1604
  initialized_ = false;
1605 1606 1607 1608 1609 1610 1611 1612 1613
}


void Builtins::IterateBuiltins(ObjectVisitor* v) {
  v->VisitPointers(&builtins_[0], &builtins_[0] + builtin_count);
}


const char* Builtins::Lookup(byte* pc) {
1614 1615
  // may be called during initialization (disassembler!)
  if (initialized_) {
1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
    for (int i = 0; i < builtin_count; i++) {
      Code* entry = Code::cast(builtins_[i]);
      if (entry->contains(pc)) {
        return names_[i];
      }
    }
  }
  return NULL;
}

1626

1627
void Builtins::Generate_InterruptCheck(MacroAssembler* masm) {
1628
  masm->TailCallRuntime(Runtime::kInterrupt, 0, 1);
1629 1630 1631 1632
}


void Builtins::Generate_StackCheck(MacroAssembler* masm) {
1633
  masm->TailCallRuntime(Runtime::kStackGuard, 0, 1);
1634 1635 1636
}


1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648
#define DEFINE_BUILTIN_ACCESSOR_C(name, ignore)               \
Handle<Code> Builtins::name() {                               \
  Code** code_address =                                       \
      reinterpret_cast<Code**>(builtin_address(k##name));     \
  return Handle<Code>(code_address);                          \
}
#define DEFINE_BUILTIN_ACCESSOR_A(name, kind, state, extra) \
Handle<Code> Builtins::name() {                             \
  Code** code_address =                                     \
      reinterpret_cast<Code**>(builtin_address(k##name));   \
  return Handle<Code>(code_address);                        \
}
1649
#define DEFINE_BUILTIN_ACCESSOR_H(name, kind)               \
1650 1651 1652 1653 1654
Handle<Code> Builtins::name() {                             \
  Code** code_address =                                     \
      reinterpret_cast<Code**>(builtin_address(k##name));   \
  return Handle<Code>(code_address);                        \
}
1655 1656
BUILTIN_LIST_C(DEFINE_BUILTIN_ACCESSOR_C)
BUILTIN_LIST_A(DEFINE_BUILTIN_ACCESSOR_A)
1657
BUILTIN_LIST_H(DEFINE_BUILTIN_ACCESSOR_H)
1658 1659 1660 1661 1662
BUILTIN_LIST_DEBUG_A(DEFINE_BUILTIN_ACCESSOR_A)
#undef DEFINE_BUILTIN_ACCESSOR_C
#undef DEFINE_BUILTIN_ACCESSOR_A


1663
} }  // namespace v8::internal