Upstream version 11.39.258.0
[platform/framework/web/crosswalk.git] / src / v8 / src / runtime.cc
1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include <stdlib.h>
6 #include <limits>
7
8 #include "src/v8.h"
9
10 #include "src/accessors.h"
11 #include "src/allocation-site-scopes.h"
12 #include "src/api.h"
13 #include "src/arguments.h"
14 #include "src/bailout-reason.h"
15 #include "src/base/cpu.h"
16 #include "src/base/platform/platform.h"
17 #include "src/bootstrapper.h"
18 #include "src/codegen.h"
19 #include "src/compilation-cache.h"
20 #include "src/compiler.h"
21 #include "src/conversions.h"
22 #include "src/cpu-profiler.h"
23 #include "src/date.h"
24 #include "src/dateparser-inl.h"
25 #include "src/debug.h"
26 #include "src/deoptimizer.h"
27 #include "src/execution.h"
28 #include "src/full-codegen.h"
29 #include "src/global-handles.h"
30 #include "src/isolate-inl.h"
31 #include "src/json-parser.h"
32 #include "src/json-stringifier.h"
33 #include "src/jsregexp-inl.h"
34 #include "src/jsregexp.h"
35 #include "src/liveedit.h"
36 #include "src/misc-intrinsics.h"
37 #include "src/parser.h"
38 #include "src/prototype.h"
39 #include "src/runtime.h"
40 #include "src/runtime-profiler.h"
41 #include "src/scopeinfo.h"
42 #include "src/smart-pointers.h"
43 #include "src/string-search.h"
44 #include "src/uri.h"
45 #include "src/utils.h"
46 #include "src/v8threads.h"
47 #include "src/vm-state-inl.h"
48 #include "third_party/fdlibm/fdlibm.h"
49
50 #ifdef V8_I18N_SUPPORT
51 #include "src/i18n.h"
52 #include "unicode/brkiter.h"
53 #include "unicode/calendar.h"
54 #include "unicode/coll.h"
55 #include "unicode/curramt.h"
56 #include "unicode/datefmt.h"
57 #include "unicode/dcfmtsym.h"
58 #include "unicode/decimfmt.h"
59 #include "unicode/dtfmtsym.h"
60 #include "unicode/dtptngen.h"
61 #include "unicode/locid.h"
62 #include "unicode/numfmt.h"
63 #include "unicode/numsys.h"
64 #include "unicode/rbbi.h"
65 #include "unicode/smpdtfmt.h"
66 #include "unicode/timezone.h"
67 #include "unicode/uchar.h"
68 #include "unicode/ucol.h"
69 #include "unicode/ucurr.h"
70 #include "unicode/uloc.h"
71 #include "unicode/unum.h"
72 #include "unicode/uversion.h"
73 #endif
74
75 #ifndef _STLP_VENDOR_CSTD
76 // STLPort doesn't import fpclassify and isless into the std namespace.
77 using std::fpclassify;
78 using std::isless;
79 #endif
80
81 namespace v8 {
82 namespace internal {
83
84
85 #define RUNTIME_ASSERT(value) \
86   if (!(value)) return isolate->ThrowIllegalOperation();
87
88 #define RUNTIME_ASSERT_HANDLIFIED(value, T)                          \
89   if (!(value)) {                                                    \
90     isolate->ThrowIllegalOperation();                                \
91     return MaybeHandle<T>();                                         \
92   }
93
94 // Cast the given object to a value of the specified type and store
95 // it in a variable with the given name.  If the object is not of the
96 // expected type call IllegalOperation and return.
97 #define CONVERT_ARG_CHECKED(Type, name, index)                       \
98   RUNTIME_ASSERT(args[index]->Is##Type());                           \
99   Type* name = Type::cast(args[index]);
100
101 #define CONVERT_ARG_HANDLE_CHECKED(Type, name, index)                \
102   RUNTIME_ASSERT(args[index]->Is##Type());                           \
103   Handle<Type> name = args.at<Type>(index);
104
105 #define CONVERT_NUMBER_ARG_HANDLE_CHECKED(name, index)               \
106   RUNTIME_ASSERT(args[index]->IsNumber());                           \
107   Handle<Object> name = args.at<Object>(index);
108
109 // Cast the given object to a boolean and store it in a variable with
110 // the given name.  If the object is not a boolean call IllegalOperation
111 // and return.
112 #define CONVERT_BOOLEAN_ARG_CHECKED(name, index)                     \
113   RUNTIME_ASSERT(args[index]->IsBoolean());                          \
114   bool name = args[index]->IsTrue();
115
116 // Cast the given argument to a Smi and store its value in an int variable
117 // with the given name.  If the argument is not a Smi call IllegalOperation
118 // and return.
119 #define CONVERT_SMI_ARG_CHECKED(name, index)                         \
120   RUNTIME_ASSERT(args[index]->IsSmi());                              \
121   int name = args.smi_at(index);
122
123 // Cast the given argument to a double and store it in a variable with
124 // the given name.  If the argument is not a number (as opposed to
125 // the number not-a-number) call IllegalOperation and return.
126 #define CONVERT_DOUBLE_ARG_CHECKED(name, index)                      \
127   RUNTIME_ASSERT(args[index]->IsNumber());                           \
128   double name = args.number_at(index);
129
130 // Call the specified converter on the object *comand store the result in
131 // a variable of the specified type with the given name.  If the
132 // object is not a Number call IllegalOperation and return.
133 #define CONVERT_NUMBER_CHECKED(type, name, Type, obj)                \
134   RUNTIME_ASSERT(obj->IsNumber());                                   \
135   type name = NumberTo##Type(obj);
136
137
138 // Cast the given argument to PropertyDetails and store its value in a
139 // variable with the given name.  If the argument is not a Smi call
140 // IllegalOperation and return.
141 #define CONVERT_PROPERTY_DETAILS_CHECKED(name, index)                \
142   RUNTIME_ASSERT(args[index]->IsSmi());                              \
143   PropertyDetails name = PropertyDetails(Smi::cast(args[index]));
144
145
146 // Assert that the given argument has a valid value for a StrictMode
147 // and store it in a StrictMode variable with the given name.
148 #define CONVERT_STRICT_MODE_ARG_CHECKED(name, index)                 \
149   RUNTIME_ASSERT(args[index]->IsSmi());                              \
150   RUNTIME_ASSERT(args.smi_at(index) == STRICT ||                     \
151                  args.smi_at(index) == SLOPPY);                      \
152   StrictMode name = static_cast<StrictMode>(args.smi_at(index));
153
154
155 // Assert that the given argument is a number within the Int32 range
156 // and convert it to int32_t.  If the argument is not an Int32 call
157 // IllegalOperation and return.
158 #define CONVERT_INT32_ARG_CHECKED(name, index)                       \
159   RUNTIME_ASSERT(args[index]->IsNumber());                           \
160   int32_t name = 0;                                                  \
161   RUNTIME_ASSERT(args[index]->ToInt32(&name));
162
163
164 static Handle<Map> ComputeObjectLiteralMap(
165     Handle<Context> context,
166     Handle<FixedArray> constant_properties,
167     bool* is_result_from_cache) {
168   Isolate* isolate = context->GetIsolate();
169   int properties_length = constant_properties->length();
170   int number_of_properties = properties_length / 2;
171   // Check that there are only internal strings and array indices among keys.
172   int number_of_string_keys = 0;
173   for (int p = 0; p != properties_length; p += 2) {
174     Object* key = constant_properties->get(p);
175     uint32_t element_index = 0;
176     if (key->IsInternalizedString()) {
177       number_of_string_keys++;
178     } else if (key->ToArrayIndex(&element_index)) {
179       // An index key does not require space in the property backing store.
180       number_of_properties--;
181     } else {
182       // Bail out as a non-internalized-string non-index key makes caching
183       // impossible.
184       // DCHECK to make sure that the if condition after the loop is false.
185       DCHECK(number_of_string_keys != number_of_properties);
186       break;
187     }
188   }
189   // If we only have internalized strings and array indices among keys then we
190   // can use the map cache in the native context.
191   const int kMaxKeys = 10;
192   if ((number_of_string_keys == number_of_properties) &&
193       (number_of_string_keys < kMaxKeys)) {
194     // Create the fixed array with the key.
195     Handle<FixedArray> keys =
196         isolate->factory()->NewFixedArray(number_of_string_keys);
197     if (number_of_string_keys > 0) {
198       int index = 0;
199       for (int p = 0; p < properties_length; p += 2) {
200         Object* key = constant_properties->get(p);
201         if (key->IsInternalizedString()) {
202           keys->set(index++, key);
203         }
204       }
205       DCHECK(index == number_of_string_keys);
206     }
207     *is_result_from_cache = true;
208     return isolate->factory()->ObjectLiteralMapFromCache(context, keys);
209   }
210   *is_result_from_cache = false;
211   return Map::Create(isolate, number_of_properties);
212 }
213
214
215 MUST_USE_RESULT static MaybeHandle<Object> CreateLiteralBoilerplate(
216     Isolate* isolate,
217     Handle<FixedArray> literals,
218     Handle<FixedArray> constant_properties);
219
220
221 MUST_USE_RESULT static MaybeHandle<Object> CreateObjectLiteralBoilerplate(
222     Isolate* isolate,
223     Handle<FixedArray> literals,
224     Handle<FixedArray> constant_properties,
225     bool should_have_fast_elements,
226     bool has_function_literal) {
227   // Get the native context from the literals array.  This is the
228   // context in which the function was created and we use the object
229   // function from this context to create the object literal.  We do
230   // not use the object function from the current native context
231   // because this might be the object function from another context
232   // which we should not have access to.
233   Handle<Context> context =
234       Handle<Context>(JSFunction::NativeContextFromLiterals(*literals));
235
236   // In case we have function literals, we want the object to be in
237   // slow properties mode for now. We don't go in the map cache because
238   // maps with constant functions can't be shared if the functions are
239   // not the same (which is the common case).
240   bool is_result_from_cache = false;
241   Handle<Map> map = has_function_literal
242       ? Handle<Map>(context->object_function()->initial_map())
243       : ComputeObjectLiteralMap(context,
244                                 constant_properties,
245                                 &is_result_from_cache);
246
247   PretenureFlag pretenure_flag =
248       isolate->heap()->InNewSpace(*literals) ? NOT_TENURED : TENURED;
249
250   Handle<JSObject> boilerplate =
251       isolate->factory()->NewJSObjectFromMap(map, pretenure_flag);
252
253   // Normalize the elements of the boilerplate to save space if needed.
254   if (!should_have_fast_elements) JSObject::NormalizeElements(boilerplate);
255
256   // Add the constant properties to the boilerplate.
257   int length = constant_properties->length();
258   bool should_transform =
259       !is_result_from_cache && boilerplate->HasFastProperties();
260   bool should_normalize = should_transform || has_function_literal;
261   if (should_normalize) {
262     // TODO(verwaest): We might not want to ever normalize here.
263     JSObject::NormalizeProperties(
264         boilerplate, KEEP_INOBJECT_PROPERTIES, length / 2);
265   }
266   // TODO(verwaest): Support tracking representations in the boilerplate.
267   for (int index = 0; index < length; index +=2) {
268     Handle<Object> key(constant_properties->get(index+0), isolate);
269     Handle<Object> value(constant_properties->get(index+1), isolate);
270     if (value->IsFixedArray()) {
271       // The value contains the constant_properties of a
272       // simple object or array literal.
273       Handle<FixedArray> array = Handle<FixedArray>::cast(value);
274       ASSIGN_RETURN_ON_EXCEPTION(
275           isolate, value,
276           CreateLiteralBoilerplate(isolate, literals, array),
277           Object);
278     }
279     MaybeHandle<Object> maybe_result;
280     uint32_t element_index = 0;
281     if (key->IsInternalizedString()) {
282       if (Handle<String>::cast(key)->AsArrayIndex(&element_index)) {
283         // Array index as string (uint32).
284         if (value->IsUninitialized()) value = handle(Smi::FromInt(0), isolate);
285         maybe_result =
286             JSObject::SetOwnElement(boilerplate, element_index, value, SLOPPY);
287       } else {
288         Handle<String> name(String::cast(*key));
289         DCHECK(!name->AsArrayIndex(&element_index));
290         maybe_result = JSObject::SetOwnPropertyIgnoreAttributes(
291             boilerplate, name, value, NONE);
292       }
293     } else if (key->ToArrayIndex(&element_index)) {
294       // Array index (uint32).
295       if (value->IsUninitialized()) value = handle(Smi::FromInt(0), isolate);
296       maybe_result =
297           JSObject::SetOwnElement(boilerplate, element_index, value, SLOPPY);
298     } else {
299       // Non-uint32 number.
300       DCHECK(key->IsNumber());
301       double num = key->Number();
302       char arr[100];
303       Vector<char> buffer(arr, arraysize(arr));
304       const char* str = DoubleToCString(num, buffer);
305       Handle<String> name = isolate->factory()->NewStringFromAsciiChecked(str);
306       maybe_result = JSObject::SetOwnPropertyIgnoreAttributes(boilerplate, name,
307                                                               value, NONE);
308     }
309     // If setting the property on the boilerplate throws an
310     // exception, the exception is converted to an empty handle in
311     // the handle based operations.  In that case, we need to
312     // convert back to an exception.
313     RETURN_ON_EXCEPTION(isolate, maybe_result, Object);
314   }
315
316   // Transform to fast properties if necessary. For object literals with
317   // containing function literals we defer this operation until after all
318   // computed properties have been assigned so that we can generate
319   // constant function properties.
320   if (should_transform && !has_function_literal) {
321     JSObject::MigrateSlowToFast(
322         boilerplate, boilerplate->map()->unused_property_fields());
323   }
324
325   return boilerplate;
326 }
327
328
329 MUST_USE_RESULT static MaybeHandle<Object> TransitionElements(
330     Handle<Object> object,
331     ElementsKind to_kind,
332     Isolate* isolate) {
333   HandleScope scope(isolate);
334   if (!object->IsJSObject()) {
335     isolate->ThrowIllegalOperation();
336     return MaybeHandle<Object>();
337   }
338   ElementsKind from_kind =
339       Handle<JSObject>::cast(object)->map()->elements_kind();
340   if (Map::IsValidElementsTransition(from_kind, to_kind)) {
341     JSObject::TransitionElementsKind(Handle<JSObject>::cast(object), to_kind);
342     return object;
343   }
344   isolate->ThrowIllegalOperation();
345   return MaybeHandle<Object>();
346 }
347
348
349 MaybeHandle<Object> Runtime::CreateArrayLiteralBoilerplate(
350     Isolate* isolate,
351     Handle<FixedArray> literals,
352     Handle<FixedArray> elements) {
353   // Create the JSArray.
354   Handle<JSFunction> constructor(
355       JSFunction::NativeContextFromLiterals(*literals)->array_function());
356
357   PretenureFlag pretenure_flag =
358       isolate->heap()->InNewSpace(*literals) ? NOT_TENURED : TENURED;
359
360   Handle<JSArray> object = Handle<JSArray>::cast(
361       isolate->factory()->NewJSObject(constructor, pretenure_flag));
362
363   ElementsKind constant_elements_kind =
364       static_cast<ElementsKind>(Smi::cast(elements->get(0))->value());
365   Handle<FixedArrayBase> constant_elements_values(
366       FixedArrayBase::cast(elements->get(1)));
367
368   { DisallowHeapAllocation no_gc;
369     DCHECK(IsFastElementsKind(constant_elements_kind));
370     Context* native_context = isolate->context()->native_context();
371     Object* maps_array = native_context->js_array_maps();
372     DCHECK(!maps_array->IsUndefined());
373     Object* map = FixedArray::cast(maps_array)->get(constant_elements_kind);
374     object->set_map(Map::cast(map));
375   }
376
377   Handle<FixedArrayBase> copied_elements_values;
378   if (IsFastDoubleElementsKind(constant_elements_kind)) {
379     copied_elements_values = isolate->factory()->CopyFixedDoubleArray(
380         Handle<FixedDoubleArray>::cast(constant_elements_values));
381   } else {
382     DCHECK(IsFastSmiOrObjectElementsKind(constant_elements_kind));
383     const bool is_cow =
384         (constant_elements_values->map() ==
385          isolate->heap()->fixed_cow_array_map());
386     if (is_cow) {
387       copied_elements_values = constant_elements_values;
388 #if DEBUG
389       Handle<FixedArray> fixed_array_values =
390           Handle<FixedArray>::cast(copied_elements_values);
391       for (int i = 0; i < fixed_array_values->length(); i++) {
392         DCHECK(!fixed_array_values->get(i)->IsFixedArray());
393       }
394 #endif
395     } else {
396       Handle<FixedArray> fixed_array_values =
397           Handle<FixedArray>::cast(constant_elements_values);
398       Handle<FixedArray> fixed_array_values_copy =
399           isolate->factory()->CopyFixedArray(fixed_array_values);
400       copied_elements_values = fixed_array_values_copy;
401       for (int i = 0; i < fixed_array_values->length(); i++) {
402         if (fixed_array_values->get(i)->IsFixedArray()) {
403           // The value contains the constant_properties of a
404           // simple object or array literal.
405           Handle<FixedArray> fa(FixedArray::cast(fixed_array_values->get(i)));
406           Handle<Object> result;
407           ASSIGN_RETURN_ON_EXCEPTION(
408               isolate, result,
409               CreateLiteralBoilerplate(isolate, literals, fa),
410               Object);
411           fixed_array_values_copy->set(i, *result);
412         }
413       }
414     }
415   }
416   object->set_elements(*copied_elements_values);
417   object->set_length(Smi::FromInt(copied_elements_values->length()));
418
419   JSObject::ValidateElements(object);
420   return object;
421 }
422
423
424 MUST_USE_RESULT static MaybeHandle<Object> CreateLiteralBoilerplate(
425     Isolate* isolate,
426     Handle<FixedArray> literals,
427     Handle<FixedArray> array) {
428   Handle<FixedArray> elements = CompileTimeValue::GetElements(array);
429   const bool kHasNoFunctionLiteral = false;
430   switch (CompileTimeValue::GetLiteralType(array)) {
431     case CompileTimeValue::OBJECT_LITERAL_FAST_ELEMENTS:
432       return CreateObjectLiteralBoilerplate(isolate,
433                                             literals,
434                                             elements,
435                                             true,
436                                             kHasNoFunctionLiteral);
437     case CompileTimeValue::OBJECT_LITERAL_SLOW_ELEMENTS:
438       return CreateObjectLiteralBoilerplate(isolate,
439                                             literals,
440                                             elements,
441                                             false,
442                                             kHasNoFunctionLiteral);
443     case CompileTimeValue::ARRAY_LITERAL:
444       return Runtime::CreateArrayLiteralBoilerplate(
445           isolate, literals, elements);
446     default:
447       UNREACHABLE();
448       return MaybeHandle<Object>();
449   }
450 }
451
452
453 RUNTIME_FUNCTION(Runtime_CreateObjectLiteral) {
454   HandleScope scope(isolate);
455   DCHECK(args.length() == 4);
456   CONVERT_ARG_HANDLE_CHECKED(FixedArray, literals, 0);
457   CONVERT_SMI_ARG_CHECKED(literals_index, 1);
458   CONVERT_ARG_HANDLE_CHECKED(FixedArray, constant_properties, 2);
459   CONVERT_SMI_ARG_CHECKED(flags, 3);
460   bool should_have_fast_elements = (flags & ObjectLiteral::kFastElements) != 0;
461   bool has_function_literal = (flags & ObjectLiteral::kHasFunction) != 0;
462
463   RUNTIME_ASSERT(literals_index >= 0 && literals_index < literals->length());
464
465   // Check if boilerplate exists. If not, create it first.
466   Handle<Object> literal_site(literals->get(literals_index), isolate);
467   Handle<AllocationSite> site;
468   Handle<JSObject> boilerplate;
469   if (*literal_site == isolate->heap()->undefined_value()) {
470     Handle<Object> raw_boilerplate;
471     ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
472         isolate, raw_boilerplate,
473         CreateObjectLiteralBoilerplate(
474             isolate,
475             literals,
476             constant_properties,
477             should_have_fast_elements,
478             has_function_literal));
479     boilerplate = Handle<JSObject>::cast(raw_boilerplate);
480
481     AllocationSiteCreationContext creation_context(isolate);
482     site = creation_context.EnterNewScope();
483     RETURN_FAILURE_ON_EXCEPTION(
484         isolate,
485         JSObject::DeepWalk(boilerplate, &creation_context));
486     creation_context.ExitScope(site, boilerplate);
487
488     // Update the functions literal and return the boilerplate.
489     literals->set(literals_index, *site);
490   } else {
491     site = Handle<AllocationSite>::cast(literal_site);
492     boilerplate = Handle<JSObject>(JSObject::cast(site->transition_info()),
493                                    isolate);
494   }
495
496   AllocationSiteUsageContext usage_context(isolate, site, true);
497   usage_context.EnterNewScope();
498   MaybeHandle<Object> maybe_copy = JSObject::DeepCopy(
499       boilerplate, &usage_context);
500   usage_context.ExitScope(site, boilerplate);
501   Handle<Object> copy;
502   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, copy, maybe_copy);
503   return *copy;
504 }
505
506
507 MUST_USE_RESULT static MaybeHandle<AllocationSite> GetLiteralAllocationSite(
508     Isolate* isolate,
509     Handle<FixedArray> literals,
510     int literals_index,
511     Handle<FixedArray> elements) {
512   // Check if boilerplate exists. If not, create it first.
513   Handle<Object> literal_site(literals->get(literals_index), isolate);
514   Handle<AllocationSite> site;
515   if (*literal_site == isolate->heap()->undefined_value()) {
516     DCHECK(*elements != isolate->heap()->empty_fixed_array());
517     Handle<Object> boilerplate;
518     ASSIGN_RETURN_ON_EXCEPTION(
519         isolate, boilerplate,
520         Runtime::CreateArrayLiteralBoilerplate(isolate, literals, elements),
521         AllocationSite);
522
523     AllocationSiteCreationContext creation_context(isolate);
524     site = creation_context.EnterNewScope();
525     if (JSObject::DeepWalk(Handle<JSObject>::cast(boilerplate),
526                            &creation_context).is_null()) {
527       return Handle<AllocationSite>::null();
528     }
529     creation_context.ExitScope(site, Handle<JSObject>::cast(boilerplate));
530
531     literals->set(literals_index, *site);
532   } else {
533     site = Handle<AllocationSite>::cast(literal_site);
534   }
535
536   return site;
537 }
538
539
540 static MaybeHandle<JSObject> CreateArrayLiteralImpl(Isolate* isolate,
541                                            Handle<FixedArray> literals,
542                                            int literals_index,
543                                            Handle<FixedArray> elements,
544                                            int flags) {
545   RUNTIME_ASSERT_HANDLIFIED(literals_index >= 0 &&
546                             literals_index < literals->length(), JSObject);
547   Handle<AllocationSite> site;
548   ASSIGN_RETURN_ON_EXCEPTION(
549       isolate, site,
550       GetLiteralAllocationSite(isolate, literals, literals_index, elements),
551       JSObject);
552
553   bool enable_mementos = (flags & ArrayLiteral::kDisableMementos) == 0;
554   Handle<JSObject> boilerplate(JSObject::cast(site->transition_info()));
555   AllocationSiteUsageContext usage_context(isolate, site, enable_mementos);
556   usage_context.EnterNewScope();
557   JSObject::DeepCopyHints hints = (flags & ArrayLiteral::kShallowElements) == 0
558                                       ? JSObject::kNoHints
559                                       : JSObject::kObjectIsShallow;
560   MaybeHandle<JSObject> copy = JSObject::DeepCopy(boilerplate, &usage_context,
561                                                   hints);
562   usage_context.ExitScope(site, boilerplate);
563   return copy;
564 }
565
566
567 RUNTIME_FUNCTION(Runtime_CreateArrayLiteral) {
568   HandleScope scope(isolate);
569   DCHECK(args.length() == 4);
570   CONVERT_ARG_HANDLE_CHECKED(FixedArray, literals, 0);
571   CONVERT_SMI_ARG_CHECKED(literals_index, 1);
572   CONVERT_ARG_HANDLE_CHECKED(FixedArray, elements, 2);
573   CONVERT_SMI_ARG_CHECKED(flags, 3);
574
575   Handle<JSObject> result;
576   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, result,
577       CreateArrayLiteralImpl(isolate, literals, literals_index, elements,
578                              flags));
579   return *result;
580 }
581
582
583 RUNTIME_FUNCTION(Runtime_CreateArrayLiteralStubBailout) {
584   HandleScope scope(isolate);
585   DCHECK(args.length() == 3);
586   CONVERT_ARG_HANDLE_CHECKED(FixedArray, literals, 0);
587   CONVERT_SMI_ARG_CHECKED(literals_index, 1);
588   CONVERT_ARG_HANDLE_CHECKED(FixedArray, elements, 2);
589
590   Handle<JSObject> result;
591   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, result,
592      CreateArrayLiteralImpl(isolate, literals, literals_index, elements,
593                             ArrayLiteral::kShallowElements));
594   return *result;
595 }
596
597
598 RUNTIME_FUNCTION(Runtime_CreateSymbol) {
599   HandleScope scope(isolate);
600   DCHECK(args.length() == 1);
601   CONVERT_ARG_HANDLE_CHECKED(Object, name, 0);
602   RUNTIME_ASSERT(name->IsString() || name->IsUndefined());
603   Handle<Symbol> symbol = isolate->factory()->NewSymbol();
604   if (name->IsString()) symbol->set_name(*name);
605   return *symbol;
606 }
607
608
609 RUNTIME_FUNCTION(Runtime_CreatePrivateSymbol) {
610   HandleScope scope(isolate);
611   DCHECK(args.length() == 1);
612   CONVERT_ARG_HANDLE_CHECKED(Object, name, 0);
613   RUNTIME_ASSERT(name->IsString() || name->IsUndefined());
614   Handle<Symbol> symbol = isolate->factory()->NewPrivateSymbol();
615   if (name->IsString()) symbol->set_name(*name);
616   return *symbol;
617 }
618
619
620 RUNTIME_FUNCTION(Runtime_CreatePrivateOwnSymbol) {
621   HandleScope scope(isolate);
622   DCHECK(args.length() == 1);
623   CONVERT_ARG_HANDLE_CHECKED(Object, name, 0);
624   RUNTIME_ASSERT(name->IsString() || name->IsUndefined());
625   Handle<Symbol> symbol = isolate->factory()->NewPrivateOwnSymbol();
626   if (name->IsString()) symbol->set_name(*name);
627   return *symbol;
628 }
629
630
631 RUNTIME_FUNCTION(Runtime_CreateGlobalPrivateOwnSymbol) {
632   HandleScope scope(isolate);
633   DCHECK(args.length() == 1);
634   CONVERT_ARG_HANDLE_CHECKED(String, name, 0);
635   Handle<JSObject> registry = isolate->GetSymbolRegistry();
636   Handle<String> part = isolate->factory()->private_intern_string();
637   Handle<Object> privates;
638   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
639       isolate, privates, Object::GetPropertyOrElement(registry, part));
640   Handle<Object> symbol;
641   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
642       isolate, symbol, Object::GetPropertyOrElement(privates, name));
643   if (!symbol->IsSymbol()) {
644     DCHECK(symbol->IsUndefined());
645     symbol = isolate->factory()->NewPrivateSymbol();
646     Handle<Symbol>::cast(symbol)->set_name(*name);
647     Handle<Symbol>::cast(symbol)->set_is_own(true);
648     JSObject::SetProperty(Handle<JSObject>::cast(privates), name, symbol,
649                           STRICT).Assert();
650   }
651   return *symbol;
652 }
653
654
655 RUNTIME_FUNCTION(Runtime_NewSymbolWrapper) {
656   HandleScope scope(isolate);
657   DCHECK(args.length() == 1);
658   CONVERT_ARG_HANDLE_CHECKED(Symbol, symbol, 0);
659   return *Object::ToObject(isolate, symbol).ToHandleChecked();
660 }
661
662
663 RUNTIME_FUNCTION(Runtime_SymbolDescription) {
664   SealHandleScope shs(isolate);
665   DCHECK(args.length() == 1);
666   CONVERT_ARG_CHECKED(Symbol, symbol, 0);
667   return symbol->name();
668 }
669
670
671 RUNTIME_FUNCTION(Runtime_SymbolRegistry) {
672   HandleScope scope(isolate);
673   DCHECK(args.length() == 0);
674   return *isolate->GetSymbolRegistry();
675 }
676
677
678 RUNTIME_FUNCTION(Runtime_SymbolIsPrivate) {
679   SealHandleScope shs(isolate);
680   DCHECK(args.length() == 1);
681   CONVERT_ARG_CHECKED(Symbol, symbol, 0);
682   return isolate->heap()->ToBoolean(symbol->is_private());
683 }
684
685
686 RUNTIME_FUNCTION(Runtime_CreateJSProxy) {
687   HandleScope scope(isolate);
688   DCHECK(args.length() == 2);
689   CONVERT_ARG_HANDLE_CHECKED(JSReceiver, handler, 0);
690   CONVERT_ARG_HANDLE_CHECKED(Object, prototype, 1);
691   if (!prototype->IsJSReceiver()) prototype = isolate->factory()->null_value();
692   return *isolate->factory()->NewJSProxy(handler, prototype);
693 }
694
695
696 RUNTIME_FUNCTION(Runtime_CreateJSFunctionProxy) {
697   HandleScope scope(isolate);
698   DCHECK(args.length() == 4);
699   CONVERT_ARG_HANDLE_CHECKED(JSReceiver, handler, 0);
700   CONVERT_ARG_HANDLE_CHECKED(Object, call_trap, 1);
701   RUNTIME_ASSERT(call_trap->IsJSFunction() || call_trap->IsJSFunctionProxy());
702   CONVERT_ARG_HANDLE_CHECKED(JSFunction, construct_trap, 2);
703   CONVERT_ARG_HANDLE_CHECKED(Object, prototype, 3);
704   if (!prototype->IsJSReceiver()) prototype = isolate->factory()->null_value();
705   return *isolate->factory()->NewJSFunctionProxy(
706       handler, call_trap, construct_trap, prototype);
707 }
708
709
710 RUNTIME_FUNCTION(Runtime_IsJSProxy) {
711   SealHandleScope shs(isolate);
712   DCHECK(args.length() == 1);
713   CONVERT_ARG_HANDLE_CHECKED(Object, obj, 0);
714   return isolate->heap()->ToBoolean(obj->IsJSProxy());
715 }
716
717
718 RUNTIME_FUNCTION(Runtime_IsJSFunctionProxy) {
719   SealHandleScope shs(isolate);
720   DCHECK(args.length() == 1);
721   CONVERT_ARG_HANDLE_CHECKED(Object, obj, 0);
722   return isolate->heap()->ToBoolean(obj->IsJSFunctionProxy());
723 }
724
725
726 RUNTIME_FUNCTION(Runtime_GetHandler) {
727   SealHandleScope shs(isolate);
728   DCHECK(args.length() == 1);
729   CONVERT_ARG_CHECKED(JSProxy, proxy, 0);
730   return proxy->handler();
731 }
732
733
734 RUNTIME_FUNCTION(Runtime_GetCallTrap) {
735   SealHandleScope shs(isolate);
736   DCHECK(args.length() == 1);
737   CONVERT_ARG_CHECKED(JSFunctionProxy, proxy, 0);
738   return proxy->call_trap();
739 }
740
741
742 RUNTIME_FUNCTION(Runtime_GetConstructTrap) {
743   SealHandleScope shs(isolate);
744   DCHECK(args.length() == 1);
745   CONVERT_ARG_CHECKED(JSFunctionProxy, proxy, 0);
746   return proxy->construct_trap();
747 }
748
749
750 RUNTIME_FUNCTION(Runtime_Fix) {
751   HandleScope scope(isolate);
752   DCHECK(args.length() == 1);
753   CONVERT_ARG_HANDLE_CHECKED(JSProxy, proxy, 0);
754   JSProxy::Fix(proxy);
755   return isolate->heap()->undefined_value();
756 }
757
758
759 void Runtime::FreeArrayBuffer(Isolate* isolate,
760                               JSArrayBuffer* phantom_array_buffer) {
761   if (phantom_array_buffer->should_be_freed()) {
762     DCHECK(phantom_array_buffer->is_external());
763     free(phantom_array_buffer->backing_store());
764   }
765   if (phantom_array_buffer->is_external()) return;
766
767   size_t allocated_length = NumberToSize(
768       isolate, phantom_array_buffer->byte_length());
769
770   reinterpret_cast<v8::Isolate*>(isolate)
771       ->AdjustAmountOfExternalAllocatedMemory(
772           -static_cast<int64_t>(allocated_length));
773   CHECK(V8::ArrayBufferAllocator() != NULL);
774   V8::ArrayBufferAllocator()->Free(
775       phantom_array_buffer->backing_store(),
776       allocated_length);
777 }
778
779
780 void Runtime::SetupArrayBuffer(Isolate* isolate,
781                                Handle<JSArrayBuffer> array_buffer,
782                                bool is_external,
783                                void* data,
784                                size_t allocated_length) {
785   DCHECK(array_buffer->GetInternalFieldCount() ==
786       v8::ArrayBuffer::kInternalFieldCount);
787   for (int i = 0; i < v8::ArrayBuffer::kInternalFieldCount; i++) {
788     array_buffer->SetInternalField(i, Smi::FromInt(0));
789   }
790   array_buffer->set_backing_store(data);
791   array_buffer->set_flag(Smi::FromInt(0));
792   array_buffer->set_is_external(is_external);
793
794   Handle<Object> byte_length =
795       isolate->factory()->NewNumberFromSize(allocated_length);
796   CHECK(byte_length->IsSmi() || byte_length->IsHeapNumber());
797   array_buffer->set_byte_length(*byte_length);
798
799   array_buffer->set_weak_next(isolate->heap()->array_buffers_list());
800   isolate->heap()->set_array_buffers_list(*array_buffer);
801   array_buffer->set_weak_first_view(isolate->heap()->undefined_value());
802 }
803
804
805 bool Runtime::SetupArrayBufferAllocatingData(
806     Isolate* isolate,
807     Handle<JSArrayBuffer> array_buffer,
808     size_t allocated_length,
809     bool initialize) {
810   void* data;
811   CHECK(V8::ArrayBufferAllocator() != NULL);
812   if (allocated_length != 0) {
813     if (initialize) {
814       data = V8::ArrayBufferAllocator()->Allocate(allocated_length);
815     } else {
816       data =
817           V8::ArrayBufferAllocator()->AllocateUninitialized(allocated_length);
818     }
819     if (data == NULL) return false;
820   } else {
821     data = NULL;
822   }
823
824   SetupArrayBuffer(isolate, array_buffer, false, data, allocated_length);
825
826   reinterpret_cast<v8::Isolate*>(isolate)
827       ->AdjustAmountOfExternalAllocatedMemory(allocated_length);
828
829   return true;
830 }
831
832
833 void Runtime::NeuterArrayBuffer(Handle<JSArrayBuffer> array_buffer) {
834   Isolate* isolate = array_buffer->GetIsolate();
835   for (Handle<Object> view_obj(array_buffer->weak_first_view(), isolate);
836        !view_obj->IsUndefined();) {
837     Handle<JSArrayBufferView> view(JSArrayBufferView::cast(*view_obj));
838     if (view->IsJSTypedArray()) {
839       JSTypedArray::cast(*view)->Neuter();
840     } else if (view->IsJSDataView()) {
841       JSDataView::cast(*view)->Neuter();
842     } else {
843       UNREACHABLE();
844     }
845     view_obj = handle(view->weak_next(), isolate);
846   }
847   array_buffer->Neuter();
848 }
849
850
851 RUNTIME_FUNCTION(Runtime_ArrayBufferInitialize) {
852   HandleScope scope(isolate);
853   DCHECK(args.length() == 2);
854   CONVERT_ARG_HANDLE_CHECKED(JSArrayBuffer, holder, 0);
855   CONVERT_NUMBER_ARG_HANDLE_CHECKED(byteLength, 1);
856   if (!holder->byte_length()->IsUndefined()) {
857     // ArrayBuffer is already initialized; probably a fuzz test.
858     return *holder;
859   }
860   size_t allocated_length = 0;
861   if (!TryNumberToSize(isolate, *byteLength, &allocated_length)) {
862     THROW_NEW_ERROR_RETURN_FAILURE(
863         isolate, NewRangeError("invalid_array_buffer_length",
864                                HandleVector<Object>(NULL, 0)));
865   }
866   if (!Runtime::SetupArrayBufferAllocatingData(isolate,
867                                                holder, allocated_length)) {
868     THROW_NEW_ERROR_RETURN_FAILURE(
869         isolate, NewRangeError("invalid_array_buffer_length",
870                                HandleVector<Object>(NULL, 0)));
871   }
872   return *holder;
873 }
874
875
876 RUNTIME_FUNCTION(Runtime_ArrayBufferGetByteLength) {
877   SealHandleScope shs(isolate);
878   DCHECK(args.length() == 1);
879   CONVERT_ARG_CHECKED(JSArrayBuffer, holder, 0);
880   return holder->byte_length();
881 }
882
883
884 RUNTIME_FUNCTION(Runtime_ArrayBufferSliceImpl) {
885   HandleScope scope(isolate);
886   DCHECK(args.length() == 3);
887   CONVERT_ARG_HANDLE_CHECKED(JSArrayBuffer, source, 0);
888   CONVERT_ARG_HANDLE_CHECKED(JSArrayBuffer, target, 1);
889   CONVERT_NUMBER_ARG_HANDLE_CHECKED(first, 2);
890   RUNTIME_ASSERT(!source.is_identical_to(target));
891   size_t start = 0;
892   RUNTIME_ASSERT(TryNumberToSize(isolate, *first, &start));
893   size_t target_length = NumberToSize(isolate, target->byte_length());
894
895   if (target_length == 0) return isolate->heap()->undefined_value();
896
897   size_t source_byte_length = NumberToSize(isolate, source->byte_length());
898   RUNTIME_ASSERT(start <= source_byte_length);
899   RUNTIME_ASSERT(source_byte_length - start >= target_length);
900   uint8_t* source_data = reinterpret_cast<uint8_t*>(source->backing_store());
901   uint8_t* target_data = reinterpret_cast<uint8_t*>(target->backing_store());
902   CopyBytes(target_data, source_data + start, target_length);
903   return isolate->heap()->undefined_value();
904 }
905
906
907 RUNTIME_FUNCTION(Runtime_ArrayBufferIsView) {
908   HandleScope scope(isolate);
909   DCHECK(args.length() == 1);
910   CONVERT_ARG_CHECKED(Object, object, 0);
911   return isolate->heap()->ToBoolean(object->IsJSArrayBufferView());
912 }
913
914
915 RUNTIME_FUNCTION(Runtime_ArrayBufferNeuter) {
916   HandleScope scope(isolate);
917   DCHECK(args.length() == 1);
918   CONVERT_ARG_HANDLE_CHECKED(JSArrayBuffer, array_buffer, 0);
919   if (array_buffer->backing_store() == NULL) {
920     CHECK(Smi::FromInt(0) == array_buffer->byte_length());
921     return isolate->heap()->undefined_value();
922   }
923   DCHECK(!array_buffer->is_external());
924   void* backing_store = array_buffer->backing_store();
925   size_t byte_length = NumberToSize(isolate, array_buffer->byte_length());
926   array_buffer->set_is_external(true);
927   Runtime::NeuterArrayBuffer(array_buffer);
928   V8::ArrayBufferAllocator()->Free(backing_store, byte_length);
929   return isolate->heap()->undefined_value();
930 }
931
932
933 void Runtime::ArrayIdToTypeAndSize(
934     int arrayId,
935     ExternalArrayType* array_type,
936     ElementsKind* external_elements_kind,
937     ElementsKind* fixed_elements_kind,
938     size_t* element_size) {
939   switch (arrayId) {
940 #define ARRAY_ID_CASE(Type, type, TYPE, ctype, size)                           \
941     case ARRAY_ID_##TYPE:                                                      \
942       *array_type = kExternal##Type##Array;                                    \
943       *external_elements_kind = EXTERNAL_##TYPE##_ELEMENTS;                    \
944       *fixed_elements_kind = TYPE##_ELEMENTS;                                  \
945       *element_size = size;                                                    \
946       break;
947
948     TYPED_ARRAYS(ARRAY_ID_CASE)
949 #undef ARRAY_ID_CASE
950
951     default:
952       UNREACHABLE();
953   }
954 }
955
956
957 RUNTIME_FUNCTION(Runtime_TypedArrayInitialize) {
958   HandleScope scope(isolate);
959   DCHECK(args.length() == 5);
960   CONVERT_ARG_HANDLE_CHECKED(JSTypedArray, holder, 0);
961   CONVERT_SMI_ARG_CHECKED(arrayId, 1);
962   CONVERT_ARG_HANDLE_CHECKED(Object, maybe_buffer, 2);
963   CONVERT_NUMBER_ARG_HANDLE_CHECKED(byte_offset_object, 3);
964   CONVERT_NUMBER_ARG_HANDLE_CHECKED(byte_length_object, 4);
965
966   RUNTIME_ASSERT(arrayId >= Runtime::ARRAY_ID_FIRST &&
967                  arrayId <= Runtime::ARRAY_ID_LAST);
968
969   ExternalArrayType array_type = kExternalInt8Array;  // Bogus initialization.
970   size_t element_size = 1;  // Bogus initialization.
971   ElementsKind external_elements_kind =
972       EXTERNAL_INT8_ELEMENTS;  // Bogus initialization.
973   ElementsKind fixed_elements_kind = INT8_ELEMENTS;  // Bogus initialization.
974   Runtime::ArrayIdToTypeAndSize(arrayId,
975       &array_type,
976       &external_elements_kind,
977       &fixed_elements_kind,
978       &element_size);
979   RUNTIME_ASSERT(holder->map()->elements_kind() == fixed_elements_kind);
980
981   size_t byte_offset = 0;
982   size_t byte_length = 0;
983   RUNTIME_ASSERT(TryNumberToSize(isolate, *byte_offset_object, &byte_offset));
984   RUNTIME_ASSERT(TryNumberToSize(isolate, *byte_length_object, &byte_length));
985
986   if (maybe_buffer->IsJSArrayBuffer()) {
987     Handle<JSArrayBuffer> buffer = Handle<JSArrayBuffer>::cast(maybe_buffer);
988     size_t array_buffer_byte_length =
989         NumberToSize(isolate, buffer->byte_length());
990     RUNTIME_ASSERT(byte_offset <= array_buffer_byte_length);
991     RUNTIME_ASSERT(array_buffer_byte_length - byte_offset >= byte_length);
992   } else {
993     RUNTIME_ASSERT(maybe_buffer->IsNull());
994   }
995
996   RUNTIME_ASSERT(byte_length % element_size == 0);
997   size_t length = byte_length / element_size;
998
999   if (length > static_cast<unsigned>(Smi::kMaxValue)) {
1000     THROW_NEW_ERROR_RETURN_FAILURE(
1001         isolate, NewRangeError("invalid_typed_array_length",
1002                                HandleVector<Object>(NULL, 0)));
1003   }
1004
1005   // All checks are done, now we can modify objects.
1006
1007   DCHECK(holder->GetInternalFieldCount() ==
1008       v8::ArrayBufferView::kInternalFieldCount);
1009   for (int i = 0; i < v8::ArrayBufferView::kInternalFieldCount; i++) {
1010     holder->SetInternalField(i, Smi::FromInt(0));
1011   }
1012   Handle<Object> length_obj = isolate->factory()->NewNumberFromSize(length);
1013   holder->set_length(*length_obj);
1014   holder->set_byte_offset(*byte_offset_object);
1015   holder->set_byte_length(*byte_length_object);
1016
1017   if (!maybe_buffer->IsNull()) {
1018     Handle<JSArrayBuffer> buffer = Handle<JSArrayBuffer>::cast(maybe_buffer);
1019     holder->set_buffer(*buffer);
1020     holder->set_weak_next(buffer->weak_first_view());
1021     buffer->set_weak_first_view(*holder);
1022
1023     Handle<ExternalArray> elements =
1024         isolate->factory()->NewExternalArray(
1025             static_cast<int>(length), array_type,
1026             static_cast<uint8_t*>(buffer->backing_store()) + byte_offset);
1027     Handle<Map> map =
1028         JSObject::GetElementsTransitionMap(holder, external_elements_kind);
1029     JSObject::SetMapAndElements(holder, map, elements);
1030     DCHECK(IsExternalArrayElementsKind(holder->map()->elements_kind()));
1031   } else {
1032     holder->set_buffer(Smi::FromInt(0));
1033     holder->set_weak_next(isolate->heap()->undefined_value());
1034     Handle<FixedTypedArrayBase> elements =
1035         isolate->factory()->NewFixedTypedArray(
1036             static_cast<int>(length), array_type);
1037     holder->set_elements(*elements);
1038   }
1039   return isolate->heap()->undefined_value();
1040 }
1041
1042
1043 // Initializes a typed array from an array-like object.
1044 // If an array-like object happens to be a typed array of the same type,
1045 // initializes backing store using memove.
1046 //
1047 // Returns true if backing store was initialized or false otherwise.
1048 RUNTIME_FUNCTION(Runtime_TypedArrayInitializeFromArrayLike) {
1049   HandleScope scope(isolate);
1050   DCHECK(args.length() == 4);
1051   CONVERT_ARG_HANDLE_CHECKED(JSTypedArray, holder, 0);
1052   CONVERT_SMI_ARG_CHECKED(arrayId, 1);
1053   CONVERT_ARG_HANDLE_CHECKED(Object, source, 2);
1054   CONVERT_NUMBER_ARG_HANDLE_CHECKED(length_obj, 3);
1055
1056   RUNTIME_ASSERT(arrayId >= Runtime::ARRAY_ID_FIRST &&
1057                  arrayId <= Runtime::ARRAY_ID_LAST);
1058
1059   ExternalArrayType array_type = kExternalInt8Array;  // Bogus initialization.
1060   size_t element_size = 1;  // Bogus initialization.
1061   ElementsKind external_elements_kind =
1062       EXTERNAL_INT8_ELEMENTS;  // Bogus intialization.
1063   ElementsKind fixed_elements_kind = INT8_ELEMENTS;  // Bogus initialization.
1064   Runtime::ArrayIdToTypeAndSize(arrayId,
1065       &array_type,
1066       &external_elements_kind,
1067       &fixed_elements_kind,
1068       &element_size);
1069
1070   RUNTIME_ASSERT(holder->map()->elements_kind() == fixed_elements_kind);
1071
1072   Handle<JSArrayBuffer> buffer = isolate->factory()->NewJSArrayBuffer();
1073   if (source->IsJSTypedArray() &&
1074       JSTypedArray::cast(*source)->type() == array_type) {
1075     length_obj = Handle<Object>(JSTypedArray::cast(*source)->length(), isolate);
1076   }
1077   size_t length = 0;
1078   RUNTIME_ASSERT(TryNumberToSize(isolate, *length_obj, &length));
1079
1080   if ((length > static_cast<unsigned>(Smi::kMaxValue)) ||
1081       (length > (kMaxInt / element_size))) {
1082     THROW_NEW_ERROR_RETURN_FAILURE(
1083         isolate, NewRangeError("invalid_typed_array_length",
1084                                HandleVector<Object>(NULL, 0)));
1085   }
1086   size_t byte_length = length * element_size;
1087
1088   DCHECK(holder->GetInternalFieldCount() ==
1089       v8::ArrayBufferView::kInternalFieldCount);
1090   for (int i = 0; i < v8::ArrayBufferView::kInternalFieldCount; i++) {
1091     holder->SetInternalField(i, Smi::FromInt(0));
1092   }
1093
1094   // NOTE: not initializing backing store.
1095   // We assume that the caller of this function will initialize holder
1096   // with the loop
1097   //      for(i = 0; i < length; i++) { holder[i] = source[i]; }
1098   // We assume that the caller of this function is always a typed array
1099   // constructor.
1100   // If source is a typed array, this loop will always run to completion,
1101   // so we are sure that the backing store will be initialized.
1102   // Otherwise, the indexing operation might throw, so the loop will not
1103   // run to completion and the typed array might remain partly initialized.
1104   // However we further assume that the caller of this function is a typed array
1105   // constructor, and the exception will propagate out of the constructor,
1106   // therefore uninitialized memory will not be accessible by a user program.
1107   //
1108   // TODO(dslomov): revise this once we support subclassing.
1109
1110   if (!Runtime::SetupArrayBufferAllocatingData(
1111         isolate, buffer, byte_length, false)) {
1112     THROW_NEW_ERROR_RETURN_FAILURE(
1113         isolate, NewRangeError("invalid_array_buffer_length",
1114                                HandleVector<Object>(NULL, 0)));
1115   }
1116
1117   holder->set_buffer(*buffer);
1118   holder->set_byte_offset(Smi::FromInt(0));
1119   Handle<Object> byte_length_obj(
1120       isolate->factory()->NewNumberFromSize(byte_length));
1121   holder->set_byte_length(*byte_length_obj);
1122   holder->set_length(*length_obj);
1123   holder->set_weak_next(buffer->weak_first_view());
1124   buffer->set_weak_first_view(*holder);
1125
1126   Handle<ExternalArray> elements =
1127       isolate->factory()->NewExternalArray(
1128           static_cast<int>(length), array_type,
1129           static_cast<uint8_t*>(buffer->backing_store()));
1130   Handle<Map> map = JSObject::GetElementsTransitionMap(
1131       holder, external_elements_kind);
1132   JSObject::SetMapAndElements(holder, map, elements);
1133
1134   if (source->IsJSTypedArray()) {
1135     Handle<JSTypedArray> typed_array(JSTypedArray::cast(*source));
1136
1137     if (typed_array->type() == holder->type()) {
1138       uint8_t* backing_store =
1139         static_cast<uint8_t*>(
1140           typed_array->GetBuffer()->backing_store());
1141       size_t source_byte_offset =
1142           NumberToSize(isolate, typed_array->byte_offset());
1143       memcpy(
1144           buffer->backing_store(),
1145           backing_store + source_byte_offset,
1146           byte_length);
1147       return isolate->heap()->true_value();
1148     }
1149   }
1150
1151   return isolate->heap()->false_value();
1152 }
1153
1154
1155 #define BUFFER_VIEW_GETTER(Type, getter, accessor) \
1156   RUNTIME_FUNCTION(Runtime_##Type##Get##getter) {                    \
1157     HandleScope scope(isolate);                                               \
1158     DCHECK(args.length() == 1);                                               \
1159     CONVERT_ARG_HANDLE_CHECKED(JS##Type, holder, 0);                          \
1160     return holder->accessor();                                                \
1161   }
1162
1163 BUFFER_VIEW_GETTER(ArrayBufferView, ByteLength, byte_length)
1164 BUFFER_VIEW_GETTER(ArrayBufferView, ByteOffset, byte_offset)
1165 BUFFER_VIEW_GETTER(TypedArray, Length, length)
1166 BUFFER_VIEW_GETTER(DataView, Buffer, buffer)
1167
1168 #undef BUFFER_VIEW_GETTER
1169
1170 RUNTIME_FUNCTION(Runtime_TypedArrayGetBuffer) {
1171   HandleScope scope(isolate);
1172   DCHECK(args.length() == 1);
1173   CONVERT_ARG_HANDLE_CHECKED(JSTypedArray, holder, 0);
1174   return *holder->GetBuffer();
1175 }
1176
1177
1178 // Return codes for Runtime_TypedArraySetFastCases.
1179 // Should be synchronized with typedarray.js natives.
1180 enum TypedArraySetResultCodes {
1181   // Set from typed array of the same type.
1182   // This is processed by TypedArraySetFastCases
1183   TYPED_ARRAY_SET_TYPED_ARRAY_SAME_TYPE = 0,
1184   // Set from typed array of the different type, overlapping in memory.
1185   TYPED_ARRAY_SET_TYPED_ARRAY_OVERLAPPING = 1,
1186   // Set from typed array of the different type, non-overlapping.
1187   TYPED_ARRAY_SET_TYPED_ARRAY_NONOVERLAPPING = 2,
1188   // Set from non-typed array.
1189   TYPED_ARRAY_SET_NON_TYPED_ARRAY = 3
1190 };
1191
1192
1193 RUNTIME_FUNCTION(Runtime_TypedArraySetFastCases) {
1194   HandleScope scope(isolate);
1195   DCHECK(args.length() == 3);
1196   if (!args[0]->IsJSTypedArray()) {
1197     THROW_NEW_ERROR_RETURN_FAILURE(
1198         isolate,
1199         NewTypeError("not_typed_array", HandleVector<Object>(NULL, 0)));
1200   }
1201
1202   if (!args[1]->IsJSTypedArray())
1203     return Smi::FromInt(TYPED_ARRAY_SET_NON_TYPED_ARRAY);
1204
1205   CONVERT_ARG_HANDLE_CHECKED(JSTypedArray, target_obj, 0);
1206   CONVERT_ARG_HANDLE_CHECKED(JSTypedArray, source_obj, 1);
1207   CONVERT_NUMBER_ARG_HANDLE_CHECKED(offset_obj, 2);
1208
1209   Handle<JSTypedArray> target(JSTypedArray::cast(*target_obj));
1210   Handle<JSTypedArray> source(JSTypedArray::cast(*source_obj));
1211   size_t offset = 0;
1212   RUNTIME_ASSERT(TryNumberToSize(isolate, *offset_obj, &offset));
1213   size_t target_length = NumberToSize(isolate, target->length());
1214   size_t source_length = NumberToSize(isolate, source->length());
1215   size_t target_byte_length = NumberToSize(isolate, target->byte_length());
1216   size_t source_byte_length = NumberToSize(isolate, source->byte_length());
1217   if (offset > target_length || offset + source_length > target_length ||
1218       offset + source_length < offset) {  // overflow
1219     THROW_NEW_ERROR_RETURN_FAILURE(
1220         isolate, NewRangeError("typed_array_set_source_too_large",
1221                                HandleVector<Object>(NULL, 0)));
1222   }
1223
1224   size_t target_offset = NumberToSize(isolate, target->byte_offset());
1225   size_t source_offset = NumberToSize(isolate, source->byte_offset());
1226   uint8_t* target_base =
1227       static_cast<uint8_t*>(
1228         target->GetBuffer()->backing_store()) + target_offset;
1229   uint8_t* source_base =
1230       static_cast<uint8_t*>(
1231         source->GetBuffer()->backing_store()) + source_offset;
1232
1233   // Typed arrays of the same type: use memmove.
1234   if (target->type() == source->type()) {
1235     memmove(target_base + offset * target->element_size(),
1236         source_base, source_byte_length);
1237     return Smi::FromInt(TYPED_ARRAY_SET_TYPED_ARRAY_SAME_TYPE);
1238   }
1239
1240   // Typed arrays of different types over the same backing store
1241   if ((source_base <= target_base &&
1242         source_base + source_byte_length > target_base) ||
1243       (target_base <= source_base &&
1244         target_base + target_byte_length > source_base)) {
1245     // We do not support overlapping ArrayBuffers
1246     DCHECK(
1247       target->GetBuffer()->backing_store() ==
1248       source->GetBuffer()->backing_store());
1249     return Smi::FromInt(TYPED_ARRAY_SET_TYPED_ARRAY_OVERLAPPING);
1250   } else {  // Non-overlapping typed arrays
1251     return Smi::FromInt(TYPED_ARRAY_SET_TYPED_ARRAY_NONOVERLAPPING);
1252   }
1253 }
1254
1255
1256 RUNTIME_FUNCTION(Runtime_TypedArrayMaxSizeInHeap) {
1257   DCHECK(args.length() == 0);
1258   DCHECK_OBJECT_SIZE(
1259       FLAG_typed_array_max_size_in_heap + FixedTypedArrayBase::kDataOffset);
1260   return Smi::FromInt(FLAG_typed_array_max_size_in_heap);
1261 }
1262
1263
1264 RUNTIME_FUNCTION(Runtime_DataViewInitialize) {
1265   HandleScope scope(isolate);
1266   DCHECK(args.length() == 4);
1267   CONVERT_ARG_HANDLE_CHECKED(JSDataView, holder, 0);
1268   CONVERT_ARG_HANDLE_CHECKED(JSArrayBuffer, buffer, 1);
1269   CONVERT_NUMBER_ARG_HANDLE_CHECKED(byte_offset, 2);
1270   CONVERT_NUMBER_ARG_HANDLE_CHECKED(byte_length, 3);
1271
1272   DCHECK(holder->GetInternalFieldCount() ==
1273       v8::ArrayBufferView::kInternalFieldCount);
1274   for (int i = 0; i < v8::ArrayBufferView::kInternalFieldCount; i++) {
1275     holder->SetInternalField(i, Smi::FromInt(0));
1276   }
1277   size_t buffer_length = 0;
1278   size_t offset = 0;
1279   size_t length = 0;
1280   RUNTIME_ASSERT(
1281       TryNumberToSize(isolate, buffer->byte_length(), &buffer_length));
1282   RUNTIME_ASSERT(TryNumberToSize(isolate, *byte_offset, &offset));
1283   RUNTIME_ASSERT(TryNumberToSize(isolate, *byte_length, &length));
1284
1285   // TODO(jkummerow): When we have a "safe numerics" helper class, use it here.
1286   // Entire range [offset, offset + length] must be in bounds.
1287   RUNTIME_ASSERT(offset <= buffer_length);
1288   RUNTIME_ASSERT(offset + length <= buffer_length);
1289   // No overflow.
1290   RUNTIME_ASSERT(offset + length >= offset);
1291
1292   holder->set_buffer(*buffer);
1293   holder->set_byte_offset(*byte_offset);
1294   holder->set_byte_length(*byte_length);
1295
1296   holder->set_weak_next(buffer->weak_first_view());
1297   buffer->set_weak_first_view(*holder);
1298
1299   return isolate->heap()->undefined_value();
1300 }
1301
1302
1303 inline static bool NeedToFlipBytes(bool is_little_endian) {
1304 #ifdef V8_TARGET_LITTLE_ENDIAN
1305   return !is_little_endian;
1306 #else
1307   return is_little_endian;
1308 #endif
1309 }
1310
1311
1312 template<int n>
1313 inline void CopyBytes(uint8_t* target, uint8_t* source) {
1314   for (int i = 0; i < n; i++) {
1315     *(target++) = *(source++);
1316   }
1317 }
1318
1319
1320 template<int n>
1321 inline void FlipBytes(uint8_t* target, uint8_t* source) {
1322   source = source + (n-1);
1323   for (int i = 0; i < n; i++) {
1324     *(target++) = *(source--);
1325   }
1326 }
1327
1328
1329 template<typename T>
1330 inline static bool DataViewGetValue(
1331     Isolate* isolate,
1332     Handle<JSDataView> data_view,
1333     Handle<Object> byte_offset_obj,
1334     bool is_little_endian,
1335     T* result) {
1336   size_t byte_offset = 0;
1337   if (!TryNumberToSize(isolate, *byte_offset_obj, &byte_offset)) {
1338     return false;
1339   }
1340   Handle<JSArrayBuffer> buffer(JSArrayBuffer::cast(data_view->buffer()));
1341
1342   size_t data_view_byte_offset =
1343       NumberToSize(isolate, data_view->byte_offset());
1344   size_t data_view_byte_length =
1345       NumberToSize(isolate, data_view->byte_length());
1346   if (byte_offset + sizeof(T) > data_view_byte_length ||
1347       byte_offset + sizeof(T) < byte_offset)  {  // overflow
1348     return false;
1349   }
1350
1351   union Value {
1352     T data;
1353     uint8_t bytes[sizeof(T)];
1354   };
1355
1356   Value value;
1357   size_t buffer_offset = data_view_byte_offset + byte_offset;
1358   DCHECK(
1359       NumberToSize(isolate, buffer->byte_length())
1360       >= buffer_offset + sizeof(T));
1361   uint8_t* source =
1362         static_cast<uint8_t*>(buffer->backing_store()) + buffer_offset;
1363   if (NeedToFlipBytes(is_little_endian)) {
1364     FlipBytes<sizeof(T)>(value.bytes, source);
1365   } else {
1366     CopyBytes<sizeof(T)>(value.bytes, source);
1367   }
1368   *result = value.data;
1369   return true;
1370 }
1371
1372
1373 template<typename T>
1374 static bool DataViewSetValue(
1375     Isolate* isolate,
1376     Handle<JSDataView> data_view,
1377     Handle<Object> byte_offset_obj,
1378     bool is_little_endian,
1379     T data) {
1380   size_t byte_offset = 0;
1381   if (!TryNumberToSize(isolate, *byte_offset_obj, &byte_offset)) {
1382     return false;
1383   }
1384   Handle<JSArrayBuffer> buffer(JSArrayBuffer::cast(data_view->buffer()));
1385
1386   size_t data_view_byte_offset =
1387       NumberToSize(isolate, data_view->byte_offset());
1388   size_t data_view_byte_length =
1389       NumberToSize(isolate, data_view->byte_length());
1390   if (byte_offset + sizeof(T) > data_view_byte_length ||
1391       byte_offset + sizeof(T) < byte_offset)  {  // overflow
1392     return false;
1393   }
1394
1395   union Value {
1396     T data;
1397     uint8_t bytes[sizeof(T)];
1398   };
1399
1400   Value value;
1401   value.data = data;
1402   size_t buffer_offset = data_view_byte_offset + byte_offset;
1403   DCHECK(
1404       NumberToSize(isolate, buffer->byte_length())
1405       >= buffer_offset + sizeof(T));
1406   uint8_t* target =
1407         static_cast<uint8_t*>(buffer->backing_store()) + buffer_offset;
1408   if (NeedToFlipBytes(is_little_endian)) {
1409     FlipBytes<sizeof(T)>(target, value.bytes);
1410   } else {
1411     CopyBytes<sizeof(T)>(target, value.bytes);
1412   }
1413   return true;
1414 }
1415
1416
1417 #define DATA_VIEW_GETTER(TypeName, Type, Converter)                   \
1418   RUNTIME_FUNCTION(Runtime_DataViewGet##TypeName) {                   \
1419     HandleScope scope(isolate);                                       \
1420     DCHECK(args.length() == 3);                                       \
1421     CONVERT_ARG_HANDLE_CHECKED(JSDataView, holder, 0);                \
1422     CONVERT_NUMBER_ARG_HANDLE_CHECKED(offset, 1);                     \
1423     CONVERT_BOOLEAN_ARG_CHECKED(is_little_endian, 2);                 \
1424     Type result;                                                      \
1425     if (DataViewGetValue(isolate, holder, offset, is_little_endian,   \
1426                          &result)) {                                  \
1427       return *isolate->factory()->Converter(result);                  \
1428     } else {                                                          \
1429       THROW_NEW_ERROR_RETURN_FAILURE(                                 \
1430           isolate, NewRangeError("invalid_data_view_accessor_offset", \
1431                                  HandleVector<Object>(NULL, 0)));     \
1432     }                                                                 \
1433   }
1434
1435 DATA_VIEW_GETTER(Uint8, uint8_t, NewNumberFromUint)
1436 DATA_VIEW_GETTER(Int8, int8_t, NewNumberFromInt)
1437 DATA_VIEW_GETTER(Uint16, uint16_t, NewNumberFromUint)
1438 DATA_VIEW_GETTER(Int16, int16_t, NewNumberFromInt)
1439 DATA_VIEW_GETTER(Uint32, uint32_t, NewNumberFromUint)
1440 DATA_VIEW_GETTER(Int32, int32_t, NewNumberFromInt)
1441 DATA_VIEW_GETTER(Float32, float, NewNumber)
1442 DATA_VIEW_GETTER(Float64, double, NewNumber)
1443
1444 #undef DATA_VIEW_GETTER
1445
1446
1447 template <typename T>
1448 static T DataViewConvertValue(double value);
1449
1450
1451 template <>
1452 int8_t DataViewConvertValue<int8_t>(double value) {
1453   return static_cast<int8_t>(DoubleToInt32(value));
1454 }
1455
1456
1457 template <>
1458 int16_t DataViewConvertValue<int16_t>(double value) {
1459   return static_cast<int16_t>(DoubleToInt32(value));
1460 }
1461
1462
1463 template <>
1464 int32_t DataViewConvertValue<int32_t>(double value) {
1465   return DoubleToInt32(value);
1466 }
1467
1468
1469 template <>
1470 uint8_t DataViewConvertValue<uint8_t>(double value) {
1471   return static_cast<uint8_t>(DoubleToUint32(value));
1472 }
1473
1474
1475 template <>
1476 uint16_t DataViewConvertValue<uint16_t>(double value) {
1477   return static_cast<uint16_t>(DoubleToUint32(value));
1478 }
1479
1480
1481 template <>
1482 uint32_t DataViewConvertValue<uint32_t>(double value) {
1483   return DoubleToUint32(value);
1484 }
1485
1486
1487 template <>
1488 float DataViewConvertValue<float>(double value) {
1489   return static_cast<float>(value);
1490 }
1491
1492
1493 template <>
1494 double DataViewConvertValue<double>(double value) {
1495   return value;
1496 }
1497
1498
1499 #define DATA_VIEW_SETTER(TypeName, Type)                                  \
1500   RUNTIME_FUNCTION(Runtime_DataViewSet##TypeName) {                       \
1501     HandleScope scope(isolate);                                           \
1502     DCHECK(args.length() == 4);                                           \
1503     CONVERT_ARG_HANDLE_CHECKED(JSDataView, holder, 0);                    \
1504     CONVERT_NUMBER_ARG_HANDLE_CHECKED(offset, 1);                         \
1505     CONVERT_NUMBER_ARG_HANDLE_CHECKED(value, 2);                          \
1506     CONVERT_BOOLEAN_ARG_CHECKED(is_little_endian, 3);                     \
1507     Type v = DataViewConvertValue<Type>(value->Number());                 \
1508     if (DataViewSetValue(isolate, holder, offset, is_little_endian, v)) { \
1509       return isolate->heap()->undefined_value();                          \
1510     } else {                                                              \
1511       THROW_NEW_ERROR_RETURN_FAILURE(                                     \
1512           isolate, NewRangeError("invalid_data_view_accessor_offset",     \
1513                                  HandleVector<Object>(NULL, 0)));         \
1514     }                                                                     \
1515   }
1516
1517 DATA_VIEW_SETTER(Uint8, uint8_t)
1518 DATA_VIEW_SETTER(Int8, int8_t)
1519 DATA_VIEW_SETTER(Uint16, uint16_t)
1520 DATA_VIEW_SETTER(Int16, int16_t)
1521 DATA_VIEW_SETTER(Uint32, uint32_t)
1522 DATA_VIEW_SETTER(Int32, int32_t)
1523 DATA_VIEW_SETTER(Float32, float)
1524 DATA_VIEW_SETTER(Float64, double)
1525
1526 #undef DATA_VIEW_SETTER
1527
1528
1529 RUNTIME_FUNCTION(Runtime_SetInitialize) {
1530   HandleScope scope(isolate);
1531   DCHECK(args.length() == 1);
1532   CONVERT_ARG_HANDLE_CHECKED(JSSet, holder, 0);
1533   Handle<OrderedHashSet> table = isolate->factory()->NewOrderedHashSet();
1534   holder->set_table(*table);
1535   return *holder;
1536 }
1537
1538
1539 RUNTIME_FUNCTION(Runtime_SetAdd) {
1540   HandleScope scope(isolate);
1541   DCHECK(args.length() == 2);
1542   CONVERT_ARG_HANDLE_CHECKED(JSSet, holder, 0);
1543   CONVERT_ARG_HANDLE_CHECKED(Object, key, 1);
1544   Handle<OrderedHashSet> table(OrderedHashSet::cast(holder->table()));
1545   table = OrderedHashSet::Add(table, key);
1546   holder->set_table(*table);
1547   return *holder;
1548 }
1549
1550
1551 RUNTIME_FUNCTION(Runtime_SetHas) {
1552   HandleScope scope(isolate);
1553   DCHECK(args.length() == 2);
1554   CONVERT_ARG_HANDLE_CHECKED(JSSet, holder, 0);
1555   CONVERT_ARG_HANDLE_CHECKED(Object, key, 1);
1556   Handle<OrderedHashSet> table(OrderedHashSet::cast(holder->table()));
1557   return isolate->heap()->ToBoolean(table->Contains(key));
1558 }
1559
1560
1561 RUNTIME_FUNCTION(Runtime_SetDelete) {
1562   HandleScope scope(isolate);
1563   DCHECK(args.length() == 2);
1564   CONVERT_ARG_HANDLE_CHECKED(JSSet, holder, 0);
1565   CONVERT_ARG_HANDLE_CHECKED(Object, key, 1);
1566   Handle<OrderedHashSet> table(OrderedHashSet::cast(holder->table()));
1567   bool was_present = false;
1568   table = OrderedHashSet::Remove(table, key, &was_present);
1569   holder->set_table(*table);
1570   return isolate->heap()->ToBoolean(was_present);
1571 }
1572
1573
1574 RUNTIME_FUNCTION(Runtime_SetClear) {
1575   HandleScope scope(isolate);
1576   DCHECK(args.length() == 1);
1577   CONVERT_ARG_HANDLE_CHECKED(JSSet, holder, 0);
1578   Handle<OrderedHashSet> table(OrderedHashSet::cast(holder->table()));
1579   table = OrderedHashSet::Clear(table);
1580   holder->set_table(*table);
1581   return isolate->heap()->undefined_value();
1582 }
1583
1584
1585 RUNTIME_FUNCTION(Runtime_SetGetSize) {
1586   HandleScope scope(isolate);
1587   DCHECK(args.length() == 1);
1588   CONVERT_ARG_HANDLE_CHECKED(JSSet, holder, 0);
1589   Handle<OrderedHashSet> table(OrderedHashSet::cast(holder->table()));
1590   return Smi::FromInt(table->NumberOfElements());
1591 }
1592
1593
1594 RUNTIME_FUNCTION(Runtime_SetIteratorInitialize) {
1595   HandleScope scope(isolate);
1596   DCHECK(args.length() == 3);
1597   CONVERT_ARG_HANDLE_CHECKED(JSSetIterator, holder, 0);
1598   CONVERT_ARG_HANDLE_CHECKED(JSSet, set, 1);
1599   CONVERT_SMI_ARG_CHECKED(kind, 2)
1600   RUNTIME_ASSERT(kind == JSSetIterator::kKindValues ||
1601                  kind == JSSetIterator::kKindEntries);
1602   Handle<OrderedHashSet> table(OrderedHashSet::cast(set->table()));
1603   holder->set_table(*table);
1604   holder->set_index(Smi::FromInt(0));
1605   holder->set_kind(Smi::FromInt(kind));
1606   return isolate->heap()->undefined_value();
1607 }
1608
1609
1610 RUNTIME_FUNCTION(Runtime_SetIteratorNext) {
1611   SealHandleScope shs(isolate);
1612   DCHECK(args.length() == 2);
1613   CONVERT_ARG_CHECKED(JSSetIterator, holder, 0);
1614   CONVERT_ARG_CHECKED(JSArray, value_array, 1);
1615   return holder->Next(value_array);
1616 }
1617
1618
1619 RUNTIME_FUNCTION(Runtime_MapInitialize) {
1620   HandleScope scope(isolate);
1621   DCHECK(args.length() == 1);
1622   CONVERT_ARG_HANDLE_CHECKED(JSMap, holder, 0);
1623   Handle<OrderedHashMap> table = isolate->factory()->NewOrderedHashMap();
1624   holder->set_table(*table);
1625   return *holder;
1626 }
1627
1628
1629 RUNTIME_FUNCTION(Runtime_MapGet) {
1630   HandleScope scope(isolate);
1631   DCHECK(args.length() == 2);
1632   CONVERT_ARG_HANDLE_CHECKED(JSMap, holder, 0);
1633   CONVERT_ARG_HANDLE_CHECKED(Object, key, 1);
1634   Handle<OrderedHashMap> table(OrderedHashMap::cast(holder->table()));
1635   Handle<Object> lookup(table->Lookup(key), isolate);
1636   return lookup->IsTheHole() ? isolate->heap()->undefined_value() : *lookup;
1637 }
1638
1639
1640 RUNTIME_FUNCTION(Runtime_MapHas) {
1641   HandleScope scope(isolate);
1642   DCHECK(args.length() == 2);
1643   CONVERT_ARG_HANDLE_CHECKED(JSMap, holder, 0);
1644   CONVERT_ARG_HANDLE_CHECKED(Object, key, 1);
1645   Handle<OrderedHashMap> table(OrderedHashMap::cast(holder->table()));
1646   Handle<Object> lookup(table->Lookup(key), isolate);
1647   return isolate->heap()->ToBoolean(!lookup->IsTheHole());
1648 }
1649
1650
1651 RUNTIME_FUNCTION(Runtime_MapDelete) {
1652   HandleScope scope(isolate);
1653   DCHECK(args.length() == 2);
1654   CONVERT_ARG_HANDLE_CHECKED(JSMap, holder, 0);
1655   CONVERT_ARG_HANDLE_CHECKED(Object, key, 1);
1656   Handle<OrderedHashMap> table(OrderedHashMap::cast(holder->table()));
1657   bool was_present = false;
1658   Handle<OrderedHashMap> new_table =
1659       OrderedHashMap::Remove(table, key, &was_present);
1660   holder->set_table(*new_table);
1661   return isolate->heap()->ToBoolean(was_present);
1662 }
1663
1664
1665 RUNTIME_FUNCTION(Runtime_MapClear) {
1666   HandleScope scope(isolate);
1667   DCHECK(args.length() == 1);
1668   CONVERT_ARG_HANDLE_CHECKED(JSMap, holder, 0);
1669   Handle<OrderedHashMap> table(OrderedHashMap::cast(holder->table()));
1670   table = OrderedHashMap::Clear(table);
1671   holder->set_table(*table);
1672   return isolate->heap()->undefined_value();
1673 }
1674
1675
1676 RUNTIME_FUNCTION(Runtime_MapSet) {
1677   HandleScope scope(isolate);
1678   DCHECK(args.length() == 3);
1679   CONVERT_ARG_HANDLE_CHECKED(JSMap, holder, 0);
1680   CONVERT_ARG_HANDLE_CHECKED(Object, key, 1);
1681   CONVERT_ARG_HANDLE_CHECKED(Object, value, 2);
1682   Handle<OrderedHashMap> table(OrderedHashMap::cast(holder->table()));
1683   Handle<OrderedHashMap> new_table = OrderedHashMap::Put(table, key, value);
1684   holder->set_table(*new_table);
1685   return *holder;
1686 }
1687
1688
1689 RUNTIME_FUNCTION(Runtime_MapGetSize) {
1690   HandleScope scope(isolate);
1691   DCHECK(args.length() == 1);
1692   CONVERT_ARG_HANDLE_CHECKED(JSMap, holder, 0);
1693   Handle<OrderedHashMap> table(OrderedHashMap::cast(holder->table()));
1694   return Smi::FromInt(table->NumberOfElements());
1695 }
1696
1697
1698 RUNTIME_FUNCTION(Runtime_MapIteratorInitialize) {
1699   HandleScope scope(isolate);
1700   DCHECK(args.length() == 3);
1701   CONVERT_ARG_HANDLE_CHECKED(JSMapIterator, holder, 0);
1702   CONVERT_ARG_HANDLE_CHECKED(JSMap, map, 1);
1703   CONVERT_SMI_ARG_CHECKED(kind, 2)
1704   RUNTIME_ASSERT(kind == JSMapIterator::kKindKeys
1705       || kind == JSMapIterator::kKindValues
1706       || kind == JSMapIterator::kKindEntries);
1707   Handle<OrderedHashMap> table(OrderedHashMap::cast(map->table()));
1708   holder->set_table(*table);
1709   holder->set_index(Smi::FromInt(0));
1710   holder->set_kind(Smi::FromInt(kind));
1711   return isolate->heap()->undefined_value();
1712 }
1713
1714
1715 RUNTIME_FUNCTION(Runtime_GetWeakMapEntries) {
1716   HandleScope scope(isolate);
1717   DCHECK(args.length() == 1);
1718   CONVERT_ARG_HANDLE_CHECKED(JSWeakCollection, holder, 0);
1719   Handle<ObjectHashTable> table(ObjectHashTable::cast(holder->table()));
1720   Handle<FixedArray> entries =
1721       isolate->factory()->NewFixedArray(table->NumberOfElements() * 2);
1722   {
1723     DisallowHeapAllocation no_gc;
1724     int number_of_non_hole_elements = 0;
1725     for (int i = 0; i < table->Capacity(); i++) {
1726       Handle<Object> key(table->KeyAt(i), isolate);
1727       if (table->IsKey(*key)) {
1728         entries->set(number_of_non_hole_elements++, *key);
1729         Object* value = table->Lookup(key);
1730         entries->set(number_of_non_hole_elements++, value);
1731       }
1732     }
1733     DCHECK_EQ(table->NumberOfElements() * 2, number_of_non_hole_elements);
1734   }
1735   return *isolate->factory()->NewJSArrayWithElements(entries);
1736 }
1737
1738
1739 RUNTIME_FUNCTION(Runtime_MapIteratorNext) {
1740   SealHandleScope shs(isolate);
1741   DCHECK(args.length() == 2);
1742   CONVERT_ARG_CHECKED(JSMapIterator, holder, 0);
1743   CONVERT_ARG_CHECKED(JSArray, value_array, 1);
1744   return holder->Next(value_array);
1745 }
1746
1747
1748 static Handle<JSWeakCollection> WeakCollectionInitialize(
1749     Isolate* isolate,
1750     Handle<JSWeakCollection> weak_collection) {
1751   DCHECK(weak_collection->map()->inobject_properties() == 0);
1752   Handle<ObjectHashTable> table = ObjectHashTable::New(isolate, 0);
1753   weak_collection->set_table(*table);
1754   return weak_collection;
1755 }
1756
1757
1758 RUNTIME_FUNCTION(Runtime_WeakCollectionInitialize) {
1759   HandleScope scope(isolate);
1760   DCHECK(args.length() == 1);
1761   CONVERT_ARG_HANDLE_CHECKED(JSWeakCollection, weak_collection, 0);
1762   return *WeakCollectionInitialize(isolate, weak_collection);
1763 }
1764
1765
1766 RUNTIME_FUNCTION(Runtime_WeakCollectionGet) {
1767   HandleScope scope(isolate);
1768   DCHECK(args.length() == 2);
1769   CONVERT_ARG_HANDLE_CHECKED(JSWeakCollection, weak_collection, 0);
1770   CONVERT_ARG_HANDLE_CHECKED(Object, key, 1);
1771   RUNTIME_ASSERT(key->IsJSReceiver() || key->IsSymbol());
1772   Handle<ObjectHashTable> table(
1773       ObjectHashTable::cast(weak_collection->table()));
1774   RUNTIME_ASSERT(table->IsKey(*key));
1775   Handle<Object> lookup(table->Lookup(key), isolate);
1776   return lookup->IsTheHole() ? isolate->heap()->undefined_value() : *lookup;
1777 }
1778
1779
1780 RUNTIME_FUNCTION(Runtime_WeakCollectionHas) {
1781   HandleScope scope(isolate);
1782   DCHECK(args.length() == 2);
1783   CONVERT_ARG_HANDLE_CHECKED(JSWeakCollection, weak_collection, 0);
1784   CONVERT_ARG_HANDLE_CHECKED(Object, key, 1);
1785   RUNTIME_ASSERT(key->IsJSReceiver() || key->IsSymbol());
1786   Handle<ObjectHashTable> table(
1787       ObjectHashTable::cast(weak_collection->table()));
1788   RUNTIME_ASSERT(table->IsKey(*key));
1789   Handle<Object> lookup(table->Lookup(key), isolate);
1790   return isolate->heap()->ToBoolean(!lookup->IsTheHole());
1791 }
1792
1793
1794 RUNTIME_FUNCTION(Runtime_WeakCollectionDelete) {
1795   HandleScope scope(isolate);
1796   DCHECK(args.length() == 2);
1797   CONVERT_ARG_HANDLE_CHECKED(JSWeakCollection, weak_collection, 0);
1798   CONVERT_ARG_HANDLE_CHECKED(Object, key, 1);
1799   RUNTIME_ASSERT(key->IsJSReceiver() || key->IsSymbol());
1800   Handle<ObjectHashTable> table(ObjectHashTable::cast(
1801       weak_collection->table()));
1802   RUNTIME_ASSERT(table->IsKey(*key));
1803   bool was_present = false;
1804   Handle<ObjectHashTable> new_table =
1805       ObjectHashTable::Remove(table, key, &was_present);
1806   weak_collection->set_table(*new_table);
1807   return isolate->heap()->ToBoolean(was_present);
1808 }
1809
1810
1811 RUNTIME_FUNCTION(Runtime_WeakCollectionSet) {
1812   HandleScope scope(isolate);
1813   DCHECK(args.length() == 3);
1814   CONVERT_ARG_HANDLE_CHECKED(JSWeakCollection, weak_collection, 0);
1815   CONVERT_ARG_HANDLE_CHECKED(Object, key, 1);
1816   RUNTIME_ASSERT(key->IsJSReceiver() || key->IsSymbol());
1817   CONVERT_ARG_HANDLE_CHECKED(Object, value, 2);
1818   Handle<ObjectHashTable> table(
1819       ObjectHashTable::cast(weak_collection->table()));
1820   RUNTIME_ASSERT(table->IsKey(*key));
1821   Handle<ObjectHashTable> new_table = ObjectHashTable::Put(table, key, value);
1822   weak_collection->set_table(*new_table);
1823   return *weak_collection;
1824 }
1825
1826
1827 RUNTIME_FUNCTION(Runtime_GetWeakSetValues) {
1828   HandleScope scope(isolate);
1829   DCHECK(args.length() == 1);
1830   CONVERT_ARG_HANDLE_CHECKED(JSWeakCollection, holder, 0);
1831   Handle<ObjectHashTable> table(ObjectHashTable::cast(holder->table()));
1832   Handle<FixedArray> values =
1833       isolate->factory()->NewFixedArray(table->NumberOfElements());
1834   {
1835     DisallowHeapAllocation no_gc;
1836     int number_of_non_hole_elements = 0;
1837     for (int i = 0; i < table->Capacity(); i++) {
1838       Handle<Object> key(table->KeyAt(i), isolate);
1839       if (table->IsKey(*key)) {
1840         values->set(number_of_non_hole_elements++, *key);
1841       }
1842     }
1843     DCHECK_EQ(table->NumberOfElements(), number_of_non_hole_elements);
1844   }
1845   return *isolate->factory()->NewJSArrayWithElements(values);
1846 }
1847
1848
1849 RUNTIME_FUNCTION(Runtime_GetPrototype) {
1850   HandleScope scope(isolate);
1851   DCHECK(args.length() == 1);
1852   CONVERT_ARG_HANDLE_CHECKED(Object, obj, 0);
1853   // We don't expect access checks to be needed on JSProxy objects.
1854   DCHECK(!obj->IsAccessCheckNeeded() || obj->IsJSObject());
1855   PrototypeIterator iter(isolate, obj, PrototypeIterator::START_AT_RECEIVER);
1856   do {
1857     if (PrototypeIterator::GetCurrent(iter)->IsAccessCheckNeeded() &&
1858         !isolate->MayNamedAccess(
1859             Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter)),
1860             isolate->factory()->proto_string(), v8::ACCESS_GET)) {
1861       isolate->ReportFailedAccessCheck(
1862           Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter)),
1863           v8::ACCESS_GET);
1864       RETURN_FAILURE_IF_SCHEDULED_EXCEPTION(isolate);
1865       return isolate->heap()->undefined_value();
1866     }
1867     iter.AdvanceIgnoringProxies();
1868     if (PrototypeIterator::GetCurrent(iter)->IsJSProxy()) {
1869       return *PrototypeIterator::GetCurrent(iter);
1870     }
1871   } while (!iter.IsAtEnd(PrototypeIterator::END_AT_NON_HIDDEN));
1872   return *PrototypeIterator::GetCurrent(iter);
1873 }
1874
1875
1876 static inline Handle<Object> GetPrototypeSkipHiddenPrototypes(
1877     Isolate* isolate, Handle<Object> receiver) {
1878   PrototypeIterator iter(isolate, receiver);
1879   while (!iter.IsAtEnd(PrototypeIterator::END_AT_NON_HIDDEN)) {
1880     if (PrototypeIterator::GetCurrent(iter)->IsJSProxy()) {
1881       return PrototypeIterator::GetCurrent(iter);
1882     }
1883     iter.Advance();
1884   }
1885   return PrototypeIterator::GetCurrent(iter);
1886 }
1887
1888
1889 RUNTIME_FUNCTION(Runtime_InternalSetPrototype) {
1890   HandleScope scope(isolate);
1891   DCHECK(args.length() == 2);
1892   CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0);
1893   CONVERT_ARG_HANDLE_CHECKED(Object, prototype, 1);
1894   DCHECK(!obj->IsAccessCheckNeeded());
1895   DCHECK(!obj->map()->is_observed());
1896   Handle<Object> result;
1897   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
1898       isolate, result, JSObject::SetPrototype(obj, prototype, false));
1899   return *result;
1900 }
1901
1902
1903 RUNTIME_FUNCTION(Runtime_SetPrototype) {
1904   HandleScope scope(isolate);
1905   DCHECK(args.length() == 2);
1906   CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0);
1907   CONVERT_ARG_HANDLE_CHECKED(Object, prototype, 1);
1908   if (obj->IsAccessCheckNeeded() &&
1909       !isolate->MayNamedAccess(
1910           obj, isolate->factory()->proto_string(), v8::ACCESS_SET)) {
1911     isolate->ReportFailedAccessCheck(obj, v8::ACCESS_SET);
1912     RETURN_FAILURE_IF_SCHEDULED_EXCEPTION(isolate);
1913     return isolate->heap()->undefined_value();
1914   }
1915   if (obj->map()->is_observed()) {
1916     Handle<Object> old_value = GetPrototypeSkipHiddenPrototypes(isolate, obj);
1917     Handle<Object> result;
1918     ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
1919         isolate, result,
1920         JSObject::SetPrototype(obj, prototype, true));
1921
1922     Handle<Object> new_value = GetPrototypeSkipHiddenPrototypes(isolate, obj);
1923     if (!new_value->SameValue(*old_value)) {
1924       JSObject::EnqueueChangeRecord(obj, "setPrototype",
1925                                     isolate->factory()->proto_string(),
1926                                     old_value);
1927     }
1928     return *result;
1929   }
1930   Handle<Object> result;
1931   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
1932       isolate, result,
1933       JSObject::SetPrototype(obj, prototype, true));
1934   return *result;
1935 }
1936
1937
1938 RUNTIME_FUNCTION(Runtime_IsInPrototypeChain) {
1939   HandleScope shs(isolate);
1940   DCHECK(args.length() == 2);
1941   // See ECMA-262, section 15.3.5.3, page 88 (steps 5 - 8).
1942   CONVERT_ARG_HANDLE_CHECKED(Object, O, 0);
1943   CONVERT_ARG_HANDLE_CHECKED(Object, V, 1);
1944   PrototypeIterator iter(isolate, V, PrototypeIterator::START_AT_RECEIVER);
1945   while (true) {
1946     iter.AdvanceIgnoringProxies();
1947     if (iter.IsAtEnd()) return isolate->heap()->false_value();
1948     if (iter.IsAtEnd(O)) return isolate->heap()->true_value();
1949   }
1950 }
1951
1952
1953 // Enumerator used as indices into the array returned from GetOwnProperty
1954 enum PropertyDescriptorIndices {
1955   IS_ACCESSOR_INDEX,
1956   VALUE_INDEX,
1957   GETTER_INDEX,
1958   SETTER_INDEX,
1959   WRITABLE_INDEX,
1960   ENUMERABLE_INDEX,
1961   CONFIGURABLE_INDEX,
1962   DESCRIPTOR_SIZE
1963 };
1964
1965
1966 MUST_USE_RESULT static MaybeHandle<Object> GetOwnProperty(Isolate* isolate,
1967                                                           Handle<JSObject> obj,
1968                                                           Handle<Name> name) {
1969   Heap* heap = isolate->heap();
1970   Factory* factory = isolate->factory();
1971
1972   PropertyAttributes attrs;
1973   uint32_t index = 0;
1974   Handle<Object> value;
1975   MaybeHandle<AccessorPair> maybe_accessors;
1976   // TODO(verwaest): Unify once indexed properties can be handled by the
1977   // LookupIterator.
1978   if (name->AsArrayIndex(&index)) {
1979     // Get attributes.
1980     Maybe<PropertyAttributes> maybe =
1981         JSReceiver::GetOwnElementAttribute(obj, index);
1982     if (!maybe.has_value) return MaybeHandle<Object>();
1983     attrs = maybe.value;
1984     if (attrs == ABSENT) return factory->undefined_value();
1985
1986     // Get AccessorPair if present.
1987     maybe_accessors = JSObject::GetOwnElementAccessorPair(obj, index);
1988
1989     // Get value if not an AccessorPair.
1990     if (maybe_accessors.is_null()) {
1991       ASSIGN_RETURN_ON_EXCEPTION(isolate, value,
1992           Runtime::GetElementOrCharAt(isolate, obj, index), Object);
1993     }
1994   } else {
1995     // Get attributes.
1996     LookupIterator it(obj, name, LookupIterator::HIDDEN);
1997     Maybe<PropertyAttributes> maybe = JSObject::GetPropertyAttributes(&it);
1998     if (!maybe.has_value) return MaybeHandle<Object>();
1999     attrs = maybe.value;
2000     if (attrs == ABSENT) return factory->undefined_value();
2001
2002     // Get AccessorPair if present.
2003     if (it.state() == LookupIterator::ACCESSOR &&
2004         it.GetAccessors()->IsAccessorPair()) {
2005       maybe_accessors = Handle<AccessorPair>::cast(it.GetAccessors());
2006     }
2007
2008     // Get value if not an AccessorPair.
2009     if (maybe_accessors.is_null()) {
2010       ASSIGN_RETURN_ON_EXCEPTION(
2011           isolate, value, Object::GetProperty(&it), Object);
2012     }
2013   }
2014   DCHECK(!isolate->has_pending_exception());
2015   Handle<FixedArray> elms = factory->NewFixedArray(DESCRIPTOR_SIZE);
2016   elms->set(ENUMERABLE_INDEX, heap->ToBoolean((attrs & DONT_ENUM) == 0));
2017   elms->set(CONFIGURABLE_INDEX, heap->ToBoolean((attrs & DONT_DELETE) == 0));
2018   elms->set(IS_ACCESSOR_INDEX, heap->ToBoolean(!maybe_accessors.is_null()));
2019
2020   Handle<AccessorPair> accessors;
2021   if (maybe_accessors.ToHandle(&accessors)) {
2022     Handle<Object> getter(accessors->GetComponent(ACCESSOR_GETTER), isolate);
2023     Handle<Object> setter(accessors->GetComponent(ACCESSOR_SETTER), isolate);
2024     elms->set(GETTER_INDEX, *getter);
2025     elms->set(SETTER_INDEX, *setter);
2026   } else {
2027     elms->set(WRITABLE_INDEX, heap->ToBoolean((attrs & READ_ONLY) == 0));
2028     elms->set(VALUE_INDEX, *value);
2029   }
2030
2031   return factory->NewJSArrayWithElements(elms);
2032 }
2033
2034
2035 // Returns an array with the property description:
2036 //  if args[1] is not a property on args[0]
2037 //          returns undefined
2038 //  if args[1] is a data property on args[0]
2039 //         [false, value, Writeable, Enumerable, Configurable]
2040 //  if args[1] is an accessor on args[0]
2041 //         [true, GetFunction, SetFunction, Enumerable, Configurable]
2042 RUNTIME_FUNCTION(Runtime_GetOwnProperty) {
2043   HandleScope scope(isolate);
2044   DCHECK(args.length() == 2);
2045   CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0);
2046   CONVERT_ARG_HANDLE_CHECKED(Name, name, 1);
2047   Handle<Object> result;
2048   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
2049       isolate, result, GetOwnProperty(isolate, obj, name));
2050   return *result;
2051 }
2052
2053
2054 RUNTIME_FUNCTION(Runtime_PreventExtensions) {
2055   HandleScope scope(isolate);
2056   DCHECK(args.length() == 1);
2057   CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0);
2058   Handle<Object> result;
2059   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
2060       isolate, result, JSObject::PreventExtensions(obj));
2061   return *result;
2062 }
2063
2064
2065 RUNTIME_FUNCTION(Runtime_ToMethod) {
2066   HandleScope scope(isolate);
2067   DCHECK(args.length() == 2);
2068   CONVERT_ARG_HANDLE_CHECKED(JSFunction, fun, 0);
2069   CONVERT_ARG_HANDLE_CHECKED(JSObject, home_object, 1);
2070   Handle<JSFunction> clone = JSFunction::CloneClosure(fun);
2071   Handle<Symbol> home_object_symbol(isolate->heap()->home_object_symbol());
2072   JSObject::SetOwnPropertyIgnoreAttributes(clone, home_object_symbol,
2073                                            home_object, DONT_ENUM).Assert();
2074   return *clone;
2075 }
2076
2077
2078 RUNTIME_FUNCTION(Runtime_HomeObjectSymbol) {
2079   DCHECK(args.length() == 0);
2080   return isolate->heap()->home_object_symbol();
2081 }
2082
2083
2084 RUNTIME_FUNCTION(Runtime_LoadFromSuper) {
2085   HandleScope scope(isolate);
2086   DCHECK(args.length() == 3);
2087   CONVERT_ARG_HANDLE_CHECKED(JSObject, home_object, 0);
2088   CONVERT_ARG_HANDLE_CHECKED(Object, receiver, 1);
2089   CONVERT_ARG_HANDLE_CHECKED(Name, name, 2);
2090
2091   if (home_object->IsAccessCheckNeeded() &&
2092       !isolate->MayNamedAccess(home_object, name, v8::ACCESS_GET)) {
2093     isolate->ReportFailedAccessCheck(home_object, v8::ACCESS_GET);
2094     RETURN_FAILURE_IF_SCHEDULED_EXCEPTION(isolate);
2095   }
2096
2097   PrototypeIterator iter(isolate, home_object);
2098   Handle<Object> proto = PrototypeIterator::GetCurrent(iter);
2099   if (!proto->IsJSReceiver()) return isolate->heap()->undefined_value();
2100
2101   LookupIterator it(receiver, name, Handle<JSReceiver>::cast(proto));
2102   Handle<Object> result;
2103   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, result, Object::GetProperty(&it));
2104   return *result;
2105 }
2106
2107
2108 RUNTIME_FUNCTION(Runtime_IsExtensible) {
2109   SealHandleScope shs(isolate);
2110   DCHECK(args.length() == 1);
2111   CONVERT_ARG_CHECKED(JSObject, obj, 0);
2112   if (obj->IsJSGlobalProxy()) {
2113     PrototypeIterator iter(isolate, obj);
2114     if (iter.IsAtEnd()) return isolate->heap()->false_value();
2115     DCHECK(iter.GetCurrent()->IsJSGlobalObject());
2116     obj = JSObject::cast(iter.GetCurrent());
2117   }
2118   return isolate->heap()->ToBoolean(obj->map()->is_extensible());
2119 }
2120
2121
2122 RUNTIME_FUNCTION(Runtime_RegExpCompile) {
2123   HandleScope scope(isolate);
2124   DCHECK(args.length() == 3);
2125   CONVERT_ARG_HANDLE_CHECKED(JSRegExp, re, 0);
2126   CONVERT_ARG_HANDLE_CHECKED(String, pattern, 1);
2127   CONVERT_ARG_HANDLE_CHECKED(String, flags, 2);
2128   Handle<Object> result;
2129   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
2130       isolate, result, RegExpImpl::Compile(re, pattern, flags));
2131   return *result;
2132 }
2133
2134
2135 RUNTIME_FUNCTION(Runtime_CreateApiFunction) {
2136   HandleScope scope(isolate);
2137   DCHECK(args.length() == 2);
2138   CONVERT_ARG_HANDLE_CHECKED(FunctionTemplateInfo, data, 0);
2139   CONVERT_ARG_HANDLE_CHECKED(Object, prototype, 1);
2140   return *isolate->factory()->CreateApiFunction(data, prototype);
2141 }
2142
2143
2144 RUNTIME_FUNCTION(Runtime_IsTemplate) {
2145   SealHandleScope shs(isolate);
2146   DCHECK(args.length() == 1);
2147   CONVERT_ARG_HANDLE_CHECKED(Object, arg, 0);
2148   bool result = arg->IsObjectTemplateInfo() || arg->IsFunctionTemplateInfo();
2149   return isolate->heap()->ToBoolean(result);
2150 }
2151
2152
2153 RUNTIME_FUNCTION(Runtime_GetTemplateField) {
2154   SealHandleScope shs(isolate);
2155   DCHECK(args.length() == 2);
2156   CONVERT_ARG_CHECKED(HeapObject, templ, 0);
2157   CONVERT_SMI_ARG_CHECKED(index, 1);
2158   int offset = index * kPointerSize + HeapObject::kHeaderSize;
2159   InstanceType type = templ->map()->instance_type();
2160   RUNTIME_ASSERT(type == FUNCTION_TEMPLATE_INFO_TYPE ||
2161                  type == OBJECT_TEMPLATE_INFO_TYPE);
2162   RUNTIME_ASSERT(offset > 0);
2163   if (type == FUNCTION_TEMPLATE_INFO_TYPE) {
2164     RUNTIME_ASSERT(offset < FunctionTemplateInfo::kSize);
2165   } else {
2166     RUNTIME_ASSERT(offset < ObjectTemplateInfo::kSize);
2167   }
2168   return *HeapObject::RawField(templ, offset);
2169 }
2170
2171
2172 RUNTIME_FUNCTION(Runtime_DisableAccessChecks) {
2173   HandleScope scope(isolate);
2174   DCHECK(args.length() == 1);
2175   CONVERT_ARG_HANDLE_CHECKED(HeapObject, object, 0);
2176   Handle<Map> old_map(object->map());
2177   bool needs_access_checks = old_map->is_access_check_needed();
2178   if (needs_access_checks) {
2179     // Copy map so it won't interfere constructor's initial map.
2180     Handle<Map> new_map = Map::Copy(old_map);
2181     new_map->set_is_access_check_needed(false);
2182     JSObject::MigrateToMap(Handle<JSObject>::cast(object), new_map);
2183   }
2184   return isolate->heap()->ToBoolean(needs_access_checks);
2185 }
2186
2187
2188 RUNTIME_FUNCTION(Runtime_EnableAccessChecks) {
2189   HandleScope scope(isolate);
2190   DCHECK(args.length() == 1);
2191   CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0);
2192   Handle<Map> old_map(object->map());
2193   RUNTIME_ASSERT(!old_map->is_access_check_needed());
2194   // Copy map so it won't interfere constructor's initial map.
2195   Handle<Map> new_map = Map::Copy(old_map);
2196   new_map->set_is_access_check_needed(true);
2197   JSObject::MigrateToMap(object, new_map);
2198   return isolate->heap()->undefined_value();
2199 }
2200
2201
2202 static Object* ThrowRedeclarationError(Isolate* isolate, Handle<String> name) {
2203   HandleScope scope(isolate);
2204   Handle<Object> args[1] = { name };
2205   THROW_NEW_ERROR_RETURN_FAILURE(
2206       isolate, NewTypeError("var_redeclaration", HandleVector(args, 1)));
2207 }
2208
2209
2210 // May throw a RedeclarationError.
2211 static Object* DeclareGlobals(Isolate* isolate, Handle<GlobalObject> global,
2212                               Handle<String> name, Handle<Object> value,
2213                               PropertyAttributes attr, bool is_var,
2214                               bool is_const, bool is_function) {
2215   // Do the lookup own properties only, see ES5 erratum.
2216   LookupIterator it(global, name, LookupIterator::HIDDEN_SKIP_INTERCEPTOR);
2217   Maybe<PropertyAttributes> maybe = JSReceiver::GetPropertyAttributes(&it);
2218   if (!maybe.has_value) return isolate->heap()->exception();
2219
2220   if (it.IsFound()) {
2221     PropertyAttributes old_attributes = maybe.value;
2222     // The name was declared before; check for conflicting re-declarations.
2223     if (is_const) return ThrowRedeclarationError(isolate, name);
2224
2225     // Skip var re-declarations.
2226     if (is_var) return isolate->heap()->undefined_value();
2227
2228     DCHECK(is_function);
2229     if ((old_attributes & DONT_DELETE) != 0) {
2230       // Only allow reconfiguring globals to functions in user code (no
2231       // natives, which are marked as read-only).
2232       DCHECK((attr & READ_ONLY) == 0);
2233
2234       // Check whether we can reconfigure the existing property into a
2235       // function.
2236       PropertyDetails old_details = it.property_details();
2237       // TODO(verwaest): CALLBACKS invalidly includes ExecutableAccessInfo,
2238       // which are actually data properties, not accessor properties.
2239       if (old_details.IsReadOnly() || old_details.IsDontEnum() ||
2240           old_details.type() == CALLBACKS) {
2241         return ThrowRedeclarationError(isolate, name);
2242       }
2243       // If the existing property is not configurable, keep its attributes. Do
2244       attr = old_attributes;
2245     }
2246   }
2247
2248   // Define or redefine own property.
2249   RETURN_FAILURE_ON_EXCEPTION(isolate, JSObject::SetOwnPropertyIgnoreAttributes(
2250                                            global, name, value, attr));
2251
2252   return isolate->heap()->undefined_value();
2253 }
2254
2255
2256 RUNTIME_FUNCTION(Runtime_DeclareGlobals) {
2257   HandleScope scope(isolate);
2258   DCHECK(args.length() == 3);
2259   Handle<GlobalObject> global(isolate->global_object());
2260
2261   CONVERT_ARG_HANDLE_CHECKED(Context, context, 0);
2262   CONVERT_ARG_HANDLE_CHECKED(FixedArray, pairs, 1);
2263   CONVERT_SMI_ARG_CHECKED(flags, 2);
2264
2265   // Traverse the name/value pairs and set the properties.
2266   int length = pairs->length();
2267   for (int i = 0; i < length; i += 2) {
2268     HandleScope scope(isolate);
2269     Handle<String> name(String::cast(pairs->get(i)));
2270     Handle<Object> initial_value(pairs->get(i + 1), isolate);
2271
2272     // We have to declare a global const property. To capture we only
2273     // assign to it when evaluating the assignment for "const x =
2274     // <expr>" the initial value is the hole.
2275     bool is_var = initial_value->IsUndefined();
2276     bool is_const = initial_value->IsTheHole();
2277     bool is_function = initial_value->IsSharedFunctionInfo();
2278     DCHECK(is_var + is_const + is_function == 1);
2279
2280     Handle<Object> value;
2281     if (is_function) {
2282       // Copy the function and update its context. Use it as value.
2283       Handle<SharedFunctionInfo> shared =
2284           Handle<SharedFunctionInfo>::cast(initial_value);
2285       Handle<JSFunction> function =
2286           isolate->factory()->NewFunctionFromSharedFunctionInfo(shared, context,
2287                                                                 TENURED);
2288       value = function;
2289     } else {
2290       value = isolate->factory()->undefined_value();
2291     }
2292
2293     // Compute the property attributes. According to ECMA-262,
2294     // the property must be non-configurable except in eval.
2295     bool is_native = DeclareGlobalsNativeFlag::decode(flags);
2296     bool is_eval = DeclareGlobalsEvalFlag::decode(flags);
2297     int attr = NONE;
2298     if (is_const) attr |= READ_ONLY;
2299     if (is_function && is_native) attr |= READ_ONLY;
2300     if (!is_const && !is_eval) attr |= DONT_DELETE;
2301
2302     Object* result = DeclareGlobals(isolate, global, name, value,
2303                                     static_cast<PropertyAttributes>(attr),
2304                                     is_var, is_const, is_function);
2305     if (isolate->has_pending_exception()) return result;
2306   }
2307
2308   return isolate->heap()->undefined_value();
2309 }
2310
2311
2312 RUNTIME_FUNCTION(Runtime_InitializeVarGlobal) {
2313   HandleScope scope(isolate);
2314   // args[0] == name
2315   // args[1] == language_mode
2316   // args[2] == value (optional)
2317
2318   // Determine if we need to assign to the variable if it already
2319   // exists (based on the number of arguments).
2320   RUNTIME_ASSERT(args.length() == 3);
2321
2322   CONVERT_ARG_HANDLE_CHECKED(String, name, 0);
2323   CONVERT_STRICT_MODE_ARG_CHECKED(strict_mode, 1);
2324   CONVERT_ARG_HANDLE_CHECKED(Object, value, 2);
2325
2326   Handle<GlobalObject> global(isolate->context()->global_object());
2327   Handle<Object> result;
2328   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
2329       isolate, result, Object::SetProperty(global, name, value, strict_mode));
2330   return *result;
2331 }
2332
2333
2334 RUNTIME_FUNCTION(Runtime_InitializeConstGlobal) {
2335   HandleScope handle_scope(isolate);
2336   // All constants are declared with an initial value. The name
2337   // of the constant is the first argument and the initial value
2338   // is the second.
2339   RUNTIME_ASSERT(args.length() == 2);
2340   CONVERT_ARG_HANDLE_CHECKED(String, name, 0);
2341   CONVERT_ARG_HANDLE_CHECKED(Object, value, 1);
2342
2343   Handle<GlobalObject> global = isolate->global_object();
2344
2345   // Lookup the property as own on the global object.
2346   LookupIterator it(global, name, LookupIterator::HIDDEN_SKIP_INTERCEPTOR);
2347   Maybe<PropertyAttributes> maybe = JSReceiver::GetPropertyAttributes(&it);
2348   DCHECK(maybe.has_value);
2349   PropertyAttributes old_attributes = maybe.value;
2350
2351   PropertyAttributes attr =
2352       static_cast<PropertyAttributes>(DONT_DELETE | READ_ONLY);
2353   // Set the value if the property is either missing, or the property attributes
2354   // allow setting the value without invoking an accessor.
2355   if (it.IsFound()) {
2356     // Ignore if we can't reconfigure the value.
2357     if ((old_attributes & DONT_DELETE) != 0) {
2358       if ((old_attributes & READ_ONLY) != 0 ||
2359           it.state() == LookupIterator::ACCESSOR) {
2360         return *value;
2361       }
2362       attr = static_cast<PropertyAttributes>(old_attributes | READ_ONLY);
2363     }
2364   }
2365
2366   RETURN_FAILURE_ON_EXCEPTION(isolate, JSObject::SetOwnPropertyIgnoreAttributes(
2367                                            global, name, value, attr));
2368
2369   return *value;
2370 }
2371
2372
2373 RUNTIME_FUNCTION(Runtime_DeclareLookupSlot) {
2374   HandleScope scope(isolate);
2375   DCHECK(args.length() == 4);
2376
2377   // Declarations are always made in a function, native, or global context. In
2378   // the case of eval code, the context passed is the context of the caller,
2379   // which may be some nested context and not the declaration context.
2380   CONVERT_ARG_HANDLE_CHECKED(Context, context_arg, 0);
2381   Handle<Context> context(context_arg->declaration_context());
2382   CONVERT_ARG_HANDLE_CHECKED(String, name, 1);
2383   CONVERT_SMI_ARG_CHECKED(attr_arg, 2);
2384   PropertyAttributes attr = static_cast<PropertyAttributes>(attr_arg);
2385   RUNTIME_ASSERT(attr == READ_ONLY || attr == NONE);
2386   CONVERT_ARG_HANDLE_CHECKED(Object, initial_value, 3);
2387
2388   // TODO(verwaest): Unify the encoding indicating "var" with DeclareGlobals.
2389   bool is_var = *initial_value == NULL;
2390   bool is_const = initial_value->IsTheHole();
2391   bool is_function = initial_value->IsJSFunction();
2392   DCHECK(is_var + is_const + is_function == 1);
2393
2394   int index;
2395   PropertyAttributes attributes;
2396   ContextLookupFlags flags = DONT_FOLLOW_CHAINS;
2397   BindingFlags binding_flags;
2398   Handle<Object> holder =
2399       context->Lookup(name, flags, &index, &attributes, &binding_flags);
2400
2401   Handle<JSObject> object;
2402   Handle<Object> value =
2403       is_function ? initial_value
2404                   : Handle<Object>::cast(isolate->factory()->undefined_value());
2405
2406   // TODO(verwaest): This case should probably not be covered by this function,
2407   // but by DeclareGlobals instead.
2408   if ((attributes != ABSENT && holder->IsJSGlobalObject()) ||
2409       (context_arg->has_extension() &&
2410        context_arg->extension()->IsJSGlobalObject())) {
2411     return DeclareGlobals(isolate, Handle<JSGlobalObject>::cast(holder), name,
2412                           value, attr, is_var, is_const, is_function);
2413   }
2414
2415   if (attributes != ABSENT) {
2416     // The name was declared before; check for conflicting re-declarations.
2417     if (is_const || (attributes & READ_ONLY) != 0) {
2418       return ThrowRedeclarationError(isolate, name);
2419     }
2420
2421     // Skip var re-declarations.
2422     if (is_var) return isolate->heap()->undefined_value();
2423
2424     DCHECK(is_function);
2425     if (index >= 0) {
2426       DCHECK(holder.is_identical_to(context));
2427       context->set(index, *initial_value);
2428       return isolate->heap()->undefined_value();
2429     }
2430
2431     object = Handle<JSObject>::cast(holder);
2432
2433   } else if (context->has_extension()) {
2434     object = handle(JSObject::cast(context->extension()));
2435     DCHECK(object->IsJSContextExtensionObject() || object->IsJSGlobalObject());
2436   } else {
2437     DCHECK(context->IsFunctionContext());
2438     object =
2439         isolate->factory()->NewJSObject(isolate->context_extension_function());
2440     context->set_extension(*object);
2441   }
2442
2443   RETURN_FAILURE_ON_EXCEPTION(isolate, JSObject::SetOwnPropertyIgnoreAttributes(
2444                                            object, name, value, attr));
2445
2446   return isolate->heap()->undefined_value();
2447 }
2448
2449
2450 RUNTIME_FUNCTION(Runtime_InitializeLegacyConstLookupSlot) {
2451   HandleScope scope(isolate);
2452   DCHECK(args.length() == 3);
2453
2454   CONVERT_ARG_HANDLE_CHECKED(Object, value, 0);
2455   DCHECK(!value->IsTheHole());
2456   // Initializations are always done in a function or native context.
2457   CONVERT_ARG_HANDLE_CHECKED(Context, context_arg, 1);
2458   Handle<Context> context(context_arg->declaration_context());
2459   CONVERT_ARG_HANDLE_CHECKED(String, name, 2);
2460
2461   int index;
2462   PropertyAttributes attributes;
2463   ContextLookupFlags flags = DONT_FOLLOW_CHAINS;
2464   BindingFlags binding_flags;
2465   Handle<Object> holder =
2466       context->Lookup(name, flags, &index, &attributes, &binding_flags);
2467
2468   if (index >= 0) {
2469     DCHECK(holder->IsContext());
2470     // Property was found in a context.  Perform the assignment if the constant
2471     // was uninitialized.
2472     Handle<Context> context = Handle<Context>::cast(holder);
2473     DCHECK((attributes & READ_ONLY) != 0);
2474     if (context->get(index)->IsTheHole()) context->set(index, *value);
2475     return *value;
2476   }
2477
2478   PropertyAttributes attr =
2479       static_cast<PropertyAttributes>(DONT_DELETE | READ_ONLY);
2480
2481   // Strict mode handling not needed (legacy const is disallowed in strict
2482   // mode).
2483
2484   // The declared const was configurable, and may have been deleted in the
2485   // meanwhile. If so, re-introduce the variable in the context extension.
2486   DCHECK(context_arg->has_extension());
2487   if (attributes == ABSENT) {
2488     holder = handle(context_arg->extension(), isolate);
2489   } else {
2490     // For JSContextExtensionObjects, the initializer can be run multiple times
2491     // if in a for loop: for (var i = 0; i < 2; i++) { const x = i; }. Only the
2492     // first assignment should go through. For JSGlobalObjects, additionally any
2493     // code can run in between that modifies the declared property.
2494     DCHECK(holder->IsJSGlobalObject() || holder->IsJSContextExtensionObject());
2495
2496     LookupIterator it(holder, name, LookupIterator::HIDDEN_SKIP_INTERCEPTOR);
2497     Maybe<PropertyAttributes> maybe = JSReceiver::GetPropertyAttributes(&it);
2498     if (!maybe.has_value) return isolate->heap()->exception();
2499     PropertyAttributes old_attributes = maybe.value;
2500
2501     // Ignore if we can't reconfigure the value.
2502     if ((old_attributes & DONT_DELETE) != 0) {
2503       if ((old_attributes & READ_ONLY) != 0 ||
2504           it.state() == LookupIterator::ACCESSOR) {
2505         return *value;
2506       }
2507       attr = static_cast<PropertyAttributes>(old_attributes | READ_ONLY);
2508     }
2509   }
2510
2511   RETURN_FAILURE_ON_EXCEPTION(
2512       isolate, JSObject::SetOwnPropertyIgnoreAttributes(
2513                    Handle<JSObject>::cast(holder), name, value, attr));
2514
2515   return *value;
2516 }
2517
2518
2519 RUNTIME_FUNCTION(Runtime_OptimizeObjectForAddingMultipleProperties) {
2520   HandleScope scope(isolate);
2521   DCHECK(args.length() == 2);
2522   CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0);
2523   CONVERT_SMI_ARG_CHECKED(properties, 1);
2524   // Conservative upper limit to prevent fuzz tests from going OOM.
2525   RUNTIME_ASSERT(properties <= 100000);
2526   if (object->HasFastProperties() && !object->IsJSGlobalProxy()) {
2527     JSObject::NormalizeProperties(object, KEEP_INOBJECT_PROPERTIES, properties);
2528   }
2529   return *object;
2530 }
2531
2532
2533 RUNTIME_FUNCTION(Runtime_RegExpExecRT) {
2534   HandleScope scope(isolate);
2535   DCHECK(args.length() == 4);
2536   CONVERT_ARG_HANDLE_CHECKED(JSRegExp, regexp, 0);
2537   CONVERT_ARG_HANDLE_CHECKED(String, subject, 1);
2538   CONVERT_INT32_ARG_CHECKED(index, 2);
2539   CONVERT_ARG_HANDLE_CHECKED(JSArray, last_match_info, 3);
2540   // Due to the way the JS calls are constructed this must be less than the
2541   // length of a string, i.e. it is always a Smi.  We check anyway for security.
2542   RUNTIME_ASSERT(index >= 0);
2543   RUNTIME_ASSERT(index <= subject->length());
2544   isolate->counters()->regexp_entry_runtime()->Increment();
2545   Handle<Object> result;
2546   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
2547       isolate, result,
2548       RegExpImpl::Exec(regexp, subject, index, last_match_info));
2549   return *result;
2550 }
2551
2552
2553 RUNTIME_FUNCTION(Runtime_RegExpConstructResult) {
2554   HandleScope handle_scope(isolate);
2555   DCHECK(args.length() == 3);
2556   CONVERT_SMI_ARG_CHECKED(size, 0);
2557   RUNTIME_ASSERT(size >= 0 && size <= FixedArray::kMaxLength);
2558   CONVERT_ARG_HANDLE_CHECKED(Object, index, 1);
2559   CONVERT_ARG_HANDLE_CHECKED(Object, input, 2);
2560   Handle<FixedArray> elements =  isolate->factory()->NewFixedArray(size);
2561   Handle<Map> regexp_map(isolate->native_context()->regexp_result_map());
2562   Handle<JSObject> object =
2563       isolate->factory()->NewJSObjectFromMap(regexp_map, NOT_TENURED, false);
2564   Handle<JSArray> array = Handle<JSArray>::cast(object);
2565   array->set_elements(*elements);
2566   array->set_length(Smi::FromInt(size));
2567   // Write in-object properties after the length of the array.
2568   array->InObjectPropertyAtPut(JSRegExpResult::kIndexIndex, *index);
2569   array->InObjectPropertyAtPut(JSRegExpResult::kInputIndex, *input);
2570   return *array;
2571 }
2572
2573
2574 RUNTIME_FUNCTION(Runtime_RegExpInitializeObject) {
2575   HandleScope scope(isolate);
2576   DCHECK(args.length() == 6);
2577   CONVERT_ARG_HANDLE_CHECKED(JSRegExp, regexp, 0);
2578   CONVERT_ARG_HANDLE_CHECKED(String, source, 1);
2579   // If source is the empty string we set it to "(?:)" instead as
2580   // suggested by ECMA-262, 5th, section 15.10.4.1.
2581   if (source->length() == 0) source = isolate->factory()->query_colon_string();
2582
2583   CONVERT_ARG_HANDLE_CHECKED(Object, global, 2);
2584   if (!global->IsTrue()) global = isolate->factory()->false_value();
2585
2586   CONVERT_ARG_HANDLE_CHECKED(Object, ignoreCase, 3);
2587   if (!ignoreCase->IsTrue()) ignoreCase = isolate->factory()->false_value();
2588
2589   CONVERT_ARG_HANDLE_CHECKED(Object, multiline, 4);
2590   if (!multiline->IsTrue()) multiline = isolate->factory()->false_value();
2591
2592   CONVERT_ARG_HANDLE_CHECKED(Object, sticky, 5);
2593   if (!sticky->IsTrue()) sticky = isolate->factory()->false_value();
2594
2595   Map* map = regexp->map();
2596   Object* constructor = map->constructor();
2597   if (!FLAG_harmony_regexps &&
2598       constructor->IsJSFunction() &&
2599       JSFunction::cast(constructor)->initial_map() == map) {
2600     // If we still have the original map, set in-object properties directly.
2601     regexp->InObjectPropertyAtPut(JSRegExp::kSourceFieldIndex, *source);
2602     // Both true and false are immovable immortal objects so no need for write
2603     // barrier.
2604     regexp->InObjectPropertyAtPut(
2605         JSRegExp::kGlobalFieldIndex, *global, SKIP_WRITE_BARRIER);
2606     regexp->InObjectPropertyAtPut(
2607         JSRegExp::kIgnoreCaseFieldIndex, *ignoreCase, SKIP_WRITE_BARRIER);
2608     regexp->InObjectPropertyAtPut(
2609         JSRegExp::kMultilineFieldIndex, *multiline, SKIP_WRITE_BARRIER);
2610     regexp->InObjectPropertyAtPut(
2611         JSRegExp::kLastIndexFieldIndex, Smi::FromInt(0), SKIP_WRITE_BARRIER);
2612     return *regexp;
2613   }
2614
2615   // Map has changed, so use generic, but slower, method.  We also end here if
2616   // the --harmony-regexp flag is set, because the initial map does not have
2617   // space for the 'sticky' flag, since it is from the snapshot, but must work
2618   // both with and without --harmony-regexp.  When sticky comes out from under
2619   // the flag, we will be able to use the fast initial map.
2620   PropertyAttributes final =
2621       static_cast<PropertyAttributes>(READ_ONLY | DONT_ENUM | DONT_DELETE);
2622   PropertyAttributes writable =
2623       static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE);
2624   Handle<Object> zero(Smi::FromInt(0), isolate);
2625   Factory* factory = isolate->factory();
2626   JSObject::SetOwnPropertyIgnoreAttributes(
2627       regexp, factory->source_string(), source, final).Check();
2628   JSObject::SetOwnPropertyIgnoreAttributes(
2629       regexp, factory->global_string(), global, final).Check();
2630   JSObject::SetOwnPropertyIgnoreAttributes(
2631       regexp, factory->ignore_case_string(), ignoreCase, final).Check();
2632   JSObject::SetOwnPropertyIgnoreAttributes(
2633       regexp, factory->multiline_string(), multiline, final).Check();
2634   if (FLAG_harmony_regexps) {
2635     JSObject::SetOwnPropertyIgnoreAttributes(
2636         regexp, factory->sticky_string(), sticky, final).Check();
2637   }
2638   JSObject::SetOwnPropertyIgnoreAttributes(
2639       regexp, factory->last_index_string(), zero, writable).Check();
2640   return *regexp;
2641 }
2642
2643
2644 RUNTIME_FUNCTION(Runtime_FinishArrayPrototypeSetup) {
2645   HandleScope scope(isolate);
2646   DCHECK(args.length() == 1);
2647   CONVERT_ARG_HANDLE_CHECKED(JSArray, prototype, 0);
2648   Object* length = prototype->length();
2649   RUNTIME_ASSERT(length->IsSmi() && Smi::cast(length)->value() == 0);
2650   RUNTIME_ASSERT(prototype->HasFastSmiOrObjectElements());
2651   // This is necessary to enable fast checks for absence of elements
2652   // on Array.prototype and below.
2653   prototype->set_elements(isolate->heap()->empty_fixed_array());
2654   return Smi::FromInt(0);
2655 }
2656
2657
2658 static void InstallBuiltin(Isolate* isolate,
2659                            Handle<JSObject> holder,
2660                            const char* name,
2661                            Builtins::Name builtin_name) {
2662   Handle<String> key = isolate->factory()->InternalizeUtf8String(name);
2663   Handle<Code> code(isolate->builtins()->builtin(builtin_name));
2664   Handle<JSFunction> optimized =
2665       isolate->factory()->NewFunctionWithoutPrototype(key, code);
2666   optimized->shared()->DontAdaptArguments();
2667   JSObject::AddProperty(holder, key, optimized, NONE);
2668 }
2669
2670
2671 RUNTIME_FUNCTION(Runtime_SpecialArrayFunctions) {
2672   HandleScope scope(isolate);
2673   DCHECK(args.length() == 0);
2674   Handle<JSObject> holder =
2675       isolate->factory()->NewJSObject(isolate->object_function());
2676
2677   InstallBuiltin(isolate, holder, "pop", Builtins::kArrayPop);
2678   InstallBuiltin(isolate, holder, "push", Builtins::kArrayPush);
2679   InstallBuiltin(isolate, holder, "shift", Builtins::kArrayShift);
2680   InstallBuiltin(isolate, holder, "unshift", Builtins::kArrayUnshift);
2681   InstallBuiltin(isolate, holder, "slice", Builtins::kArraySlice);
2682   InstallBuiltin(isolate, holder, "splice", Builtins::kArraySplice);
2683   InstallBuiltin(isolate, holder, "concat", Builtins::kArrayConcat);
2684
2685   return *holder;
2686 }
2687
2688
2689 RUNTIME_FUNCTION(Runtime_IsSloppyModeFunction) {
2690   SealHandleScope shs(isolate);
2691   DCHECK(args.length() == 1);
2692   CONVERT_ARG_CHECKED(JSReceiver, callable, 0);
2693   if (!callable->IsJSFunction()) {
2694     HandleScope scope(isolate);
2695     Handle<Object> delegate;
2696     ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
2697         isolate, delegate,
2698         Execution::TryGetFunctionDelegate(
2699             isolate, Handle<JSReceiver>(callable)));
2700     callable = JSFunction::cast(*delegate);
2701   }
2702   JSFunction* function = JSFunction::cast(callable);
2703   SharedFunctionInfo* shared = function->shared();
2704   return isolate->heap()->ToBoolean(shared->strict_mode() == SLOPPY);
2705 }
2706
2707
2708 RUNTIME_FUNCTION(Runtime_GetDefaultReceiver) {
2709   SealHandleScope shs(isolate);
2710   DCHECK(args.length() == 1);
2711   CONVERT_ARG_CHECKED(JSReceiver, callable, 0);
2712
2713   if (!callable->IsJSFunction()) {
2714     HandleScope scope(isolate);
2715     Handle<Object> delegate;
2716     ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
2717         isolate, delegate,
2718         Execution::TryGetFunctionDelegate(
2719             isolate, Handle<JSReceiver>(callable)));
2720     callable = JSFunction::cast(*delegate);
2721   }
2722   JSFunction* function = JSFunction::cast(callable);
2723
2724   SharedFunctionInfo* shared = function->shared();
2725   if (shared->native() || shared->strict_mode() == STRICT) {
2726     return isolate->heap()->undefined_value();
2727   }
2728   // Returns undefined for strict or native functions, or
2729   // the associated global receiver for "normal" functions.
2730
2731   return function->global_proxy();
2732 }
2733
2734
2735 RUNTIME_FUNCTION(Runtime_MaterializeRegExpLiteral) {
2736   HandleScope scope(isolate);
2737   DCHECK(args.length() == 4);
2738   CONVERT_ARG_HANDLE_CHECKED(FixedArray, literals, 0);
2739   CONVERT_SMI_ARG_CHECKED(index, 1);
2740   CONVERT_ARG_HANDLE_CHECKED(String, pattern, 2);
2741   CONVERT_ARG_HANDLE_CHECKED(String, flags, 3);
2742
2743   // Get the RegExp function from the context in the literals array.
2744   // This is the RegExp function from the context in which the
2745   // function was created.  We do not use the RegExp function from the
2746   // current native context because this might be the RegExp function
2747   // from another context which we should not have access to.
2748   Handle<JSFunction> constructor =
2749       Handle<JSFunction>(
2750           JSFunction::NativeContextFromLiterals(*literals)->regexp_function());
2751   // Compute the regular expression literal.
2752   Handle<Object> regexp;
2753   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
2754       isolate, regexp,
2755       RegExpImpl::CreateRegExpLiteral(constructor, pattern, flags));
2756   literals->set(index, *regexp);
2757   return *regexp;
2758 }
2759
2760
2761 RUNTIME_FUNCTION(Runtime_FunctionGetName) {
2762   SealHandleScope shs(isolate);
2763   DCHECK(args.length() == 1);
2764
2765   CONVERT_ARG_CHECKED(JSFunction, f, 0);
2766   return f->shared()->name();
2767 }
2768
2769
2770 RUNTIME_FUNCTION(Runtime_FunctionSetName) {
2771   SealHandleScope shs(isolate);
2772   DCHECK(args.length() == 2);
2773
2774   CONVERT_ARG_CHECKED(JSFunction, f, 0);
2775   CONVERT_ARG_CHECKED(String, name, 1);
2776   f->shared()->set_name(name);
2777   return isolate->heap()->undefined_value();
2778 }
2779
2780
2781 RUNTIME_FUNCTION(Runtime_FunctionNameShouldPrintAsAnonymous) {
2782   SealHandleScope shs(isolate);
2783   DCHECK(args.length() == 1);
2784   CONVERT_ARG_CHECKED(JSFunction, f, 0);
2785   return isolate->heap()->ToBoolean(
2786       f->shared()->name_should_print_as_anonymous());
2787 }
2788
2789
2790 RUNTIME_FUNCTION(Runtime_FunctionMarkNameShouldPrintAsAnonymous) {
2791   SealHandleScope shs(isolate);
2792   DCHECK(args.length() == 1);
2793   CONVERT_ARG_CHECKED(JSFunction, f, 0);
2794   f->shared()->set_name_should_print_as_anonymous(true);
2795   return isolate->heap()->undefined_value();
2796 }
2797
2798
2799 RUNTIME_FUNCTION(Runtime_FunctionIsGenerator) {
2800   SealHandleScope shs(isolate);
2801   DCHECK(args.length() == 1);
2802   CONVERT_ARG_CHECKED(JSFunction, f, 0);
2803   return isolate->heap()->ToBoolean(f->shared()->is_generator());
2804 }
2805
2806
2807 RUNTIME_FUNCTION(Runtime_FunctionIsArrow) {
2808   SealHandleScope shs(isolate);
2809   DCHECK(args.length() == 1);
2810   CONVERT_ARG_CHECKED(JSFunction, f, 0);
2811   return isolate->heap()->ToBoolean(f->shared()->is_arrow());
2812 }
2813
2814
2815 RUNTIME_FUNCTION(Runtime_FunctionIsConciseMethod) {
2816   SealHandleScope shs(isolate);
2817   DCHECK(args.length() == 1);
2818   CONVERT_ARG_CHECKED(JSFunction, f, 0);
2819   return isolate->heap()->ToBoolean(f->shared()->is_concise_method());
2820 }
2821
2822
2823 RUNTIME_FUNCTION(Runtime_FunctionRemovePrototype) {
2824   SealHandleScope shs(isolate);
2825   DCHECK(args.length() == 1);
2826
2827   CONVERT_ARG_CHECKED(JSFunction, f, 0);
2828   RUNTIME_ASSERT(f->RemovePrototype());
2829
2830   return isolate->heap()->undefined_value();
2831 }
2832
2833
2834 RUNTIME_FUNCTION(Runtime_FunctionGetScript) {
2835   HandleScope scope(isolate);
2836   DCHECK(args.length() == 1);
2837
2838   CONVERT_ARG_CHECKED(JSFunction, fun, 0);
2839   Handle<Object> script = Handle<Object>(fun->shared()->script(), isolate);
2840   if (!script->IsScript()) return isolate->heap()->undefined_value();
2841
2842   return *Script::GetWrapper(Handle<Script>::cast(script));
2843 }
2844
2845
2846 RUNTIME_FUNCTION(Runtime_FunctionGetSourceCode) {
2847   HandleScope scope(isolate);
2848   DCHECK(args.length() == 1);
2849
2850   CONVERT_ARG_HANDLE_CHECKED(JSFunction, f, 0);
2851   Handle<SharedFunctionInfo> shared(f->shared());
2852   return *shared->GetSourceCode();
2853 }
2854
2855
2856 RUNTIME_FUNCTION(Runtime_FunctionGetScriptSourcePosition) {
2857   SealHandleScope shs(isolate);
2858   DCHECK(args.length() == 1);
2859
2860   CONVERT_ARG_CHECKED(JSFunction, fun, 0);
2861   int pos = fun->shared()->start_position();
2862   return Smi::FromInt(pos);
2863 }
2864
2865
2866 RUNTIME_FUNCTION(Runtime_FunctionGetPositionForOffset) {
2867   SealHandleScope shs(isolate);
2868   DCHECK(args.length() == 2);
2869
2870   CONVERT_ARG_CHECKED(Code, code, 0);
2871   CONVERT_NUMBER_CHECKED(int, offset, Int32, args[1]);
2872
2873   RUNTIME_ASSERT(0 <= offset && offset < code->Size());
2874
2875   Address pc = code->address() + offset;
2876   return Smi::FromInt(code->SourcePosition(pc));
2877 }
2878
2879
2880 RUNTIME_FUNCTION(Runtime_FunctionSetInstanceClassName) {
2881   SealHandleScope shs(isolate);
2882   DCHECK(args.length() == 2);
2883
2884   CONVERT_ARG_CHECKED(JSFunction, fun, 0);
2885   CONVERT_ARG_CHECKED(String, name, 1);
2886   fun->SetInstanceClassName(name);
2887   return isolate->heap()->undefined_value();
2888 }
2889
2890
2891 RUNTIME_FUNCTION(Runtime_FunctionSetLength) {
2892   SealHandleScope shs(isolate);
2893   DCHECK(args.length() == 2);
2894
2895   CONVERT_ARG_CHECKED(JSFunction, fun, 0);
2896   CONVERT_SMI_ARG_CHECKED(length, 1);
2897   RUNTIME_ASSERT((length & 0xC0000000) == 0xC0000000 ||
2898                  (length & 0xC0000000) == 0x0);
2899   fun->shared()->set_length(length);
2900   return isolate->heap()->undefined_value();
2901 }
2902
2903
2904 RUNTIME_FUNCTION(Runtime_FunctionSetPrototype) {
2905   HandleScope scope(isolate);
2906   DCHECK(args.length() == 2);
2907
2908   CONVERT_ARG_HANDLE_CHECKED(JSFunction, fun, 0);
2909   CONVERT_ARG_HANDLE_CHECKED(Object, value, 1);
2910   RUNTIME_ASSERT(fun->should_have_prototype());
2911   Accessors::FunctionSetPrototype(fun, value);
2912   return args[0];  // return TOS
2913 }
2914
2915
2916 RUNTIME_FUNCTION(Runtime_FunctionIsAPIFunction) {
2917   SealHandleScope shs(isolate);
2918   DCHECK(args.length() == 1);
2919
2920   CONVERT_ARG_CHECKED(JSFunction, f, 0);
2921   return isolate->heap()->ToBoolean(f->shared()->IsApiFunction());
2922 }
2923
2924
2925 RUNTIME_FUNCTION(Runtime_FunctionIsBuiltin) {
2926   SealHandleScope shs(isolate);
2927   DCHECK(args.length() == 1);
2928
2929   CONVERT_ARG_CHECKED(JSFunction, f, 0);
2930   return isolate->heap()->ToBoolean(f->IsBuiltin());
2931 }
2932
2933
2934 RUNTIME_FUNCTION(Runtime_SetCode) {
2935   HandleScope scope(isolate);
2936   DCHECK(args.length() == 2);
2937
2938   CONVERT_ARG_HANDLE_CHECKED(JSFunction, target, 0);
2939   CONVERT_ARG_HANDLE_CHECKED(JSFunction, source, 1);
2940
2941   Handle<SharedFunctionInfo> target_shared(target->shared());
2942   Handle<SharedFunctionInfo> source_shared(source->shared());
2943   RUNTIME_ASSERT(!source_shared->bound());
2944
2945   if (!Compiler::EnsureCompiled(source, KEEP_EXCEPTION)) {
2946     return isolate->heap()->exception();
2947   }
2948
2949   // Mark both, the source and the target, as un-flushable because the
2950   // shared unoptimized code makes them impossible to enqueue in a list.
2951   DCHECK(target_shared->code()->gc_metadata() == NULL);
2952   DCHECK(source_shared->code()->gc_metadata() == NULL);
2953   target_shared->set_dont_flush(true);
2954   source_shared->set_dont_flush(true);
2955
2956   // Set the code, scope info, formal parameter count, and the length
2957   // of the target shared function info.
2958   target_shared->ReplaceCode(source_shared->code());
2959   target_shared->set_scope_info(source_shared->scope_info());
2960   target_shared->set_length(source_shared->length());
2961   target_shared->set_feedback_vector(source_shared->feedback_vector());
2962   target_shared->set_formal_parameter_count(
2963       source_shared->formal_parameter_count());
2964   target_shared->set_script(source_shared->script());
2965   target_shared->set_start_position_and_type(
2966       source_shared->start_position_and_type());
2967   target_shared->set_end_position(source_shared->end_position());
2968   bool was_native = target_shared->native();
2969   target_shared->set_compiler_hints(source_shared->compiler_hints());
2970   target_shared->set_native(was_native);
2971   target_shared->set_profiler_ticks(source_shared->profiler_ticks());
2972
2973   // Set the code of the target function.
2974   target->ReplaceCode(source_shared->code());
2975   DCHECK(target->next_function_link()->IsUndefined());
2976
2977   // Make sure we get a fresh copy of the literal vector to avoid cross
2978   // context contamination.
2979   Handle<Context> context(source->context());
2980   int number_of_literals = source->NumberOfLiterals();
2981   Handle<FixedArray> literals =
2982       isolate->factory()->NewFixedArray(number_of_literals, TENURED);
2983   if (number_of_literals > 0) {
2984     literals->set(JSFunction::kLiteralNativeContextIndex,
2985                   context->native_context());
2986   }
2987   target->set_context(*context);
2988   target->set_literals(*literals);
2989
2990   if (isolate->logger()->is_logging_code_events() ||
2991       isolate->cpu_profiler()->is_profiling()) {
2992     isolate->logger()->LogExistingFunction(
2993         source_shared, Handle<Code>(source_shared->code()));
2994   }
2995
2996   return *target;
2997 }
2998
2999
3000 RUNTIME_FUNCTION(Runtime_CreateJSGeneratorObject) {
3001   HandleScope scope(isolate);
3002   DCHECK(args.length() == 0);
3003
3004   JavaScriptFrameIterator it(isolate);
3005   JavaScriptFrame* frame = it.frame();
3006   Handle<JSFunction> function(frame->function());
3007   RUNTIME_ASSERT(function->shared()->is_generator());
3008
3009   Handle<JSGeneratorObject> generator;
3010   if (frame->IsConstructor()) {
3011     generator = handle(JSGeneratorObject::cast(frame->receiver()));
3012   } else {
3013     generator = isolate->factory()->NewJSGeneratorObject(function);
3014   }
3015   generator->set_function(*function);
3016   generator->set_context(Context::cast(frame->context()));
3017   generator->set_receiver(frame->receiver());
3018   generator->set_continuation(0);
3019   generator->set_operand_stack(isolate->heap()->empty_fixed_array());
3020   generator->set_stack_handler_index(-1);
3021
3022   return *generator;
3023 }
3024
3025
3026 RUNTIME_FUNCTION(Runtime_SuspendJSGeneratorObject) {
3027   HandleScope handle_scope(isolate);
3028   DCHECK(args.length() == 1);
3029   CONVERT_ARG_HANDLE_CHECKED(JSGeneratorObject, generator_object, 0);
3030
3031   JavaScriptFrameIterator stack_iterator(isolate);
3032   JavaScriptFrame* frame = stack_iterator.frame();
3033   RUNTIME_ASSERT(frame->function()->shared()->is_generator());
3034   DCHECK_EQ(frame->function(), generator_object->function());
3035
3036   // The caller should have saved the context and continuation already.
3037   DCHECK_EQ(generator_object->context(), Context::cast(frame->context()));
3038   DCHECK_LT(0, generator_object->continuation());
3039
3040   // We expect there to be at least two values on the operand stack: the return
3041   // value of the yield expression, and the argument to this runtime call.
3042   // Neither of those should be saved.
3043   int operands_count = frame->ComputeOperandsCount();
3044   DCHECK_GE(operands_count, 2);
3045   operands_count -= 2;
3046
3047   if (operands_count == 0) {
3048     // Although it's semantically harmless to call this function with an
3049     // operands_count of zero, it is also unnecessary.
3050     DCHECK_EQ(generator_object->operand_stack(),
3051               isolate->heap()->empty_fixed_array());
3052     DCHECK_EQ(generator_object->stack_handler_index(), -1);
3053     // If there are no operands on the stack, there shouldn't be a handler
3054     // active either.
3055     DCHECK(!frame->HasHandler());
3056   } else {
3057     int stack_handler_index = -1;
3058     Handle<FixedArray> operand_stack =
3059         isolate->factory()->NewFixedArray(operands_count);
3060     frame->SaveOperandStack(*operand_stack, &stack_handler_index);
3061     generator_object->set_operand_stack(*operand_stack);
3062     generator_object->set_stack_handler_index(stack_handler_index);
3063   }
3064
3065   return isolate->heap()->undefined_value();
3066 }
3067
3068
3069 // Note that this function is the slow path for resuming generators.  It is only
3070 // called if the suspended activation had operands on the stack, stack handlers
3071 // needing rewinding, or if the resume should throw an exception.  The fast path
3072 // is handled directly in FullCodeGenerator::EmitGeneratorResume(), which is
3073 // inlined into GeneratorNext and GeneratorThrow.  EmitGeneratorResumeResume is
3074 // called in any case, as it needs to reconstruct the stack frame and make space
3075 // for arguments and operands.
3076 RUNTIME_FUNCTION(Runtime_ResumeJSGeneratorObject) {
3077   SealHandleScope shs(isolate);
3078   DCHECK(args.length() == 3);
3079   CONVERT_ARG_CHECKED(JSGeneratorObject, generator_object, 0);
3080   CONVERT_ARG_CHECKED(Object, value, 1);
3081   CONVERT_SMI_ARG_CHECKED(resume_mode_int, 2);
3082   JavaScriptFrameIterator stack_iterator(isolate);
3083   JavaScriptFrame* frame = stack_iterator.frame();
3084
3085   DCHECK_EQ(frame->function(), generator_object->function());
3086   DCHECK(frame->function()->is_compiled());
3087
3088   STATIC_ASSERT(JSGeneratorObject::kGeneratorExecuting < 0);
3089   STATIC_ASSERT(JSGeneratorObject::kGeneratorClosed == 0);
3090
3091   Address pc = generator_object->function()->code()->instruction_start();
3092   int offset = generator_object->continuation();
3093   DCHECK(offset > 0);
3094   frame->set_pc(pc + offset);
3095   if (FLAG_enable_ool_constant_pool) {
3096     frame->set_constant_pool(
3097         generator_object->function()->code()->constant_pool());
3098   }
3099   generator_object->set_continuation(JSGeneratorObject::kGeneratorExecuting);
3100
3101   FixedArray* operand_stack = generator_object->operand_stack();
3102   int operands_count = operand_stack->length();
3103   if (operands_count != 0) {
3104     frame->RestoreOperandStack(operand_stack,
3105                                generator_object->stack_handler_index());
3106     generator_object->set_operand_stack(isolate->heap()->empty_fixed_array());
3107     generator_object->set_stack_handler_index(-1);
3108   }
3109
3110   JSGeneratorObject::ResumeMode resume_mode =
3111       static_cast<JSGeneratorObject::ResumeMode>(resume_mode_int);
3112   switch (resume_mode) {
3113     case JSGeneratorObject::NEXT:
3114       return value;
3115     case JSGeneratorObject::THROW:
3116       return isolate->Throw(value);
3117   }
3118
3119   UNREACHABLE();
3120   return isolate->ThrowIllegalOperation();
3121 }
3122
3123
3124 RUNTIME_FUNCTION(Runtime_ThrowGeneratorStateError) {
3125   HandleScope scope(isolate);
3126   DCHECK(args.length() == 1);
3127   CONVERT_ARG_HANDLE_CHECKED(JSGeneratorObject, generator, 0);
3128   int continuation = generator->continuation();
3129   const char* message = continuation == JSGeneratorObject::kGeneratorClosed ?
3130       "generator_finished" : "generator_running";
3131   Vector< Handle<Object> > argv = HandleVector<Object>(NULL, 0);
3132   THROW_NEW_ERROR_RETURN_FAILURE(isolate, NewError(message, argv));
3133 }
3134
3135
3136 RUNTIME_FUNCTION(Runtime_ObjectFreeze) {
3137   HandleScope scope(isolate);
3138   DCHECK(args.length() == 1);
3139   CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0);
3140
3141   // %ObjectFreeze is a fast path and these cases are handled elsewhere.
3142   RUNTIME_ASSERT(!object->HasSloppyArgumentsElements() &&
3143                  !object->map()->is_observed() &&
3144                  !object->IsJSProxy());
3145
3146   Handle<Object> result;
3147   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, result, JSObject::Freeze(object));
3148   return *result;
3149 }
3150
3151
3152 RUNTIME_FUNCTION(Runtime_StringCharCodeAtRT) {
3153   HandleScope handle_scope(isolate);
3154   DCHECK(args.length() == 2);
3155
3156   CONVERT_ARG_HANDLE_CHECKED(String, subject, 0);
3157   CONVERT_NUMBER_CHECKED(uint32_t, i, Uint32, args[1]);
3158
3159   // Flatten the string.  If someone wants to get a char at an index
3160   // in a cons string, it is likely that more indices will be
3161   // accessed.
3162   subject = String::Flatten(subject);
3163
3164   if (i >= static_cast<uint32_t>(subject->length())) {
3165     return isolate->heap()->nan_value();
3166   }
3167
3168   return Smi::FromInt(subject->Get(i));
3169 }
3170
3171
3172 RUNTIME_FUNCTION(Runtime_CharFromCode) {
3173   HandleScope handlescope(isolate);
3174   DCHECK(args.length() == 1);
3175   if (args[0]->IsNumber()) {
3176     CONVERT_NUMBER_CHECKED(uint32_t, code, Uint32, args[0]);
3177     code &= 0xffff;
3178     return *isolate->factory()->LookupSingleCharacterStringFromCode(code);
3179   }
3180   return isolate->heap()->empty_string();
3181 }
3182
3183
3184 class FixedArrayBuilder {
3185  public:
3186   explicit FixedArrayBuilder(Isolate* isolate, int initial_capacity)
3187       : array_(isolate->factory()->NewFixedArrayWithHoles(initial_capacity)),
3188         length_(0),
3189         has_non_smi_elements_(false) {
3190     // Require a non-zero initial size. Ensures that doubling the size to
3191     // extend the array will work.
3192     DCHECK(initial_capacity > 0);
3193   }
3194
3195   explicit FixedArrayBuilder(Handle<FixedArray> backing_store)
3196       : array_(backing_store),
3197         length_(0),
3198         has_non_smi_elements_(false) {
3199     // Require a non-zero initial size. Ensures that doubling the size to
3200     // extend the array will work.
3201     DCHECK(backing_store->length() > 0);
3202   }
3203
3204   bool HasCapacity(int elements) {
3205     int length = array_->length();
3206     int required_length = length_ + elements;
3207     return (length >= required_length);
3208   }
3209
3210   void EnsureCapacity(int elements) {
3211     int length = array_->length();
3212     int required_length = length_ + elements;
3213     if (length < required_length) {
3214       int new_length = length;
3215       do {
3216         new_length *= 2;
3217       } while (new_length < required_length);
3218       Handle<FixedArray> extended_array =
3219           array_->GetIsolate()->factory()->NewFixedArrayWithHoles(new_length);
3220       array_->CopyTo(0, *extended_array, 0, length_);
3221       array_ = extended_array;
3222     }
3223   }
3224
3225   void Add(Object* value) {
3226     DCHECK(!value->IsSmi());
3227     DCHECK(length_ < capacity());
3228     array_->set(length_, value);
3229     length_++;
3230     has_non_smi_elements_ = true;
3231   }
3232
3233   void Add(Smi* value) {
3234     DCHECK(value->IsSmi());
3235     DCHECK(length_ < capacity());
3236     array_->set(length_, value);
3237     length_++;
3238   }
3239
3240   Handle<FixedArray> array() {
3241     return array_;
3242   }
3243
3244   int length() {
3245     return length_;
3246   }
3247
3248   int capacity() {
3249     return array_->length();
3250   }
3251
3252   Handle<JSArray> ToJSArray(Handle<JSArray> target_array) {
3253     JSArray::SetContent(target_array, array_);
3254     target_array->set_length(Smi::FromInt(length_));
3255     return target_array;
3256   }
3257
3258
3259  private:
3260   Handle<FixedArray> array_;
3261   int length_;
3262   bool has_non_smi_elements_;
3263 };
3264
3265
3266 // Forward declarations.
3267 const int kStringBuilderConcatHelperLengthBits = 11;
3268 const int kStringBuilderConcatHelperPositionBits = 19;
3269
3270 template <typename schar>
3271 static inline void StringBuilderConcatHelper(String*,
3272                                              schar*,
3273                                              FixedArray*,
3274                                              int);
3275
3276 typedef BitField<int, 0, kStringBuilderConcatHelperLengthBits>
3277     StringBuilderSubstringLength;
3278 typedef BitField<int,
3279                  kStringBuilderConcatHelperLengthBits,
3280                  kStringBuilderConcatHelperPositionBits>
3281     StringBuilderSubstringPosition;
3282
3283
3284 class ReplacementStringBuilder {
3285  public:
3286   ReplacementStringBuilder(Heap* heap, Handle<String> subject,
3287                            int estimated_part_count)
3288       : heap_(heap),
3289         array_builder_(heap->isolate(), estimated_part_count),
3290         subject_(subject),
3291         character_count_(0),
3292         is_one_byte_(subject->IsOneByteRepresentation()) {
3293     // Require a non-zero initial size. Ensures that doubling the size to
3294     // extend the array will work.
3295     DCHECK(estimated_part_count > 0);
3296   }
3297
3298   static inline void AddSubjectSlice(FixedArrayBuilder* builder,
3299                                      int from,
3300                                      int to) {
3301     DCHECK(from >= 0);
3302     int length = to - from;
3303     DCHECK(length > 0);
3304     if (StringBuilderSubstringLength::is_valid(length) &&
3305         StringBuilderSubstringPosition::is_valid(from)) {
3306       int encoded_slice = StringBuilderSubstringLength::encode(length) |
3307           StringBuilderSubstringPosition::encode(from);
3308       builder->Add(Smi::FromInt(encoded_slice));
3309     } else {
3310       // Otherwise encode as two smis.
3311       builder->Add(Smi::FromInt(-length));
3312       builder->Add(Smi::FromInt(from));
3313     }
3314   }
3315
3316
3317   void EnsureCapacity(int elements) {
3318     array_builder_.EnsureCapacity(elements);
3319   }
3320
3321
3322   void AddSubjectSlice(int from, int to) {
3323     AddSubjectSlice(&array_builder_, from, to);
3324     IncrementCharacterCount(to - from);
3325   }
3326
3327
3328   void AddString(Handle<String> string) {
3329     int length = string->length();
3330     DCHECK(length > 0);
3331     AddElement(*string);
3332     if (!string->IsOneByteRepresentation()) {
3333       is_one_byte_ = false;
3334     }
3335     IncrementCharacterCount(length);
3336   }
3337
3338
3339   MaybeHandle<String> ToString() {
3340     Isolate* isolate = heap_->isolate();
3341     if (array_builder_.length() == 0) {
3342       return isolate->factory()->empty_string();
3343     }
3344
3345     Handle<String> joined_string;
3346     if (is_one_byte_) {
3347       Handle<SeqOneByteString> seq;
3348       ASSIGN_RETURN_ON_EXCEPTION(
3349           isolate, seq,
3350           isolate->factory()->NewRawOneByteString(character_count_),
3351           String);
3352
3353       DisallowHeapAllocation no_gc;
3354       uint8_t* char_buffer = seq->GetChars();
3355       StringBuilderConcatHelper(*subject_,
3356                                 char_buffer,
3357                                 *array_builder_.array(),
3358                                 array_builder_.length());
3359       joined_string = Handle<String>::cast(seq);
3360     } else {
3361       // Two-byte.
3362       Handle<SeqTwoByteString> seq;
3363       ASSIGN_RETURN_ON_EXCEPTION(
3364           isolate, seq,
3365           isolate->factory()->NewRawTwoByteString(character_count_),
3366           String);
3367
3368       DisallowHeapAllocation no_gc;
3369       uc16* char_buffer = seq->GetChars();
3370       StringBuilderConcatHelper(*subject_,
3371                                 char_buffer,
3372                                 *array_builder_.array(),
3373                                 array_builder_.length());
3374       joined_string = Handle<String>::cast(seq);
3375     }
3376     return joined_string;
3377   }
3378
3379
3380   void IncrementCharacterCount(int by) {
3381     if (character_count_ > String::kMaxLength - by) {
3382       STATIC_ASSERT(String::kMaxLength < kMaxInt);
3383       character_count_ = kMaxInt;
3384     } else {
3385       character_count_ += by;
3386     }
3387   }
3388
3389  private:
3390   void AddElement(Object* element) {
3391     DCHECK(element->IsSmi() || element->IsString());
3392     DCHECK(array_builder_.capacity() > array_builder_.length());
3393     array_builder_.Add(element);
3394   }
3395
3396   Heap* heap_;
3397   FixedArrayBuilder array_builder_;
3398   Handle<String> subject_;
3399   int character_count_;
3400   bool is_one_byte_;
3401 };
3402
3403
3404 class CompiledReplacement {
3405  public:
3406   explicit CompiledReplacement(Zone* zone)
3407       : parts_(1, zone), replacement_substrings_(0, zone), zone_(zone) {}
3408
3409   // Return whether the replacement is simple.
3410   bool Compile(Handle<String> replacement,
3411                int capture_count,
3412                int subject_length);
3413
3414   // Use Apply only if Compile returned false.
3415   void Apply(ReplacementStringBuilder* builder,
3416              int match_from,
3417              int match_to,
3418              int32_t* match);
3419
3420   // Number of distinct parts of the replacement pattern.
3421   int parts() {
3422     return parts_.length();
3423   }
3424
3425   Zone* zone() const { return zone_; }
3426
3427  private:
3428   enum PartType {
3429     SUBJECT_PREFIX = 1,
3430     SUBJECT_SUFFIX,
3431     SUBJECT_CAPTURE,
3432     REPLACEMENT_SUBSTRING,
3433     REPLACEMENT_STRING,
3434
3435     NUMBER_OF_PART_TYPES
3436   };
3437
3438   struct ReplacementPart {
3439     static inline ReplacementPart SubjectMatch() {
3440       return ReplacementPart(SUBJECT_CAPTURE, 0);
3441     }
3442     static inline ReplacementPart SubjectCapture(int capture_index) {
3443       return ReplacementPart(SUBJECT_CAPTURE, capture_index);
3444     }
3445     static inline ReplacementPart SubjectPrefix() {
3446       return ReplacementPart(SUBJECT_PREFIX, 0);
3447     }
3448     static inline ReplacementPart SubjectSuffix(int subject_length) {
3449       return ReplacementPart(SUBJECT_SUFFIX, subject_length);
3450     }
3451     static inline ReplacementPart ReplacementString() {
3452       return ReplacementPart(REPLACEMENT_STRING, 0);
3453     }
3454     static inline ReplacementPart ReplacementSubString(int from, int to) {
3455       DCHECK(from >= 0);
3456       DCHECK(to > from);
3457       return ReplacementPart(-from, to);
3458     }
3459
3460     // If tag <= 0 then it is the negation of a start index of a substring of
3461     // the replacement pattern, otherwise it's a value from PartType.
3462     ReplacementPart(int tag, int data)
3463         : tag(tag), data(data) {
3464       // Must be non-positive or a PartType value.
3465       DCHECK(tag < NUMBER_OF_PART_TYPES);
3466     }
3467     // Either a value of PartType or a non-positive number that is
3468     // the negation of an index into the replacement string.
3469     int tag;
3470     // The data value's interpretation depends on the value of tag:
3471     // tag == SUBJECT_PREFIX ||
3472     // tag == SUBJECT_SUFFIX:  data is unused.
3473     // tag == SUBJECT_CAPTURE: data is the number of the capture.
3474     // tag == REPLACEMENT_SUBSTRING ||
3475     // tag == REPLACEMENT_STRING:    data is index into array of substrings
3476     //                               of the replacement string.
3477     // tag <= 0: Temporary representation of the substring of the replacement
3478     //           string ranging over -tag .. data.
3479     //           Is replaced by REPLACEMENT_{SUB,}STRING when we create the
3480     //           substring objects.
3481     int data;
3482   };
3483
3484   template<typename Char>
3485   bool ParseReplacementPattern(ZoneList<ReplacementPart>* parts,
3486                                Vector<Char> characters,
3487                                int capture_count,
3488                                int subject_length,
3489                                Zone* zone) {
3490     int length = characters.length();
3491     int last = 0;
3492     for (int i = 0; i < length; i++) {
3493       Char c = characters[i];
3494       if (c == '$') {
3495         int next_index = i + 1;
3496         if (next_index == length) {  // No next character!
3497           break;
3498         }
3499         Char c2 = characters[next_index];
3500         switch (c2) {
3501         case '$':
3502           if (i > last) {
3503             // There is a substring before. Include the first "$".
3504             parts->Add(ReplacementPart::ReplacementSubString(last, next_index),
3505                        zone);
3506             last = next_index + 1;  // Continue after the second "$".
3507           } else {
3508             // Let the next substring start with the second "$".
3509             last = next_index;
3510           }
3511           i = next_index;
3512           break;
3513         case '`':
3514           if (i > last) {
3515             parts->Add(ReplacementPart::ReplacementSubString(last, i), zone);
3516           }
3517           parts->Add(ReplacementPart::SubjectPrefix(), zone);
3518           i = next_index;
3519           last = i + 1;
3520           break;
3521         case '\'':
3522           if (i > last) {
3523             parts->Add(ReplacementPart::ReplacementSubString(last, i), zone);
3524           }
3525           parts->Add(ReplacementPart::SubjectSuffix(subject_length), zone);
3526           i = next_index;
3527           last = i + 1;
3528           break;
3529         case '&':
3530           if (i > last) {
3531             parts->Add(ReplacementPart::ReplacementSubString(last, i), zone);
3532           }
3533           parts->Add(ReplacementPart::SubjectMatch(), zone);
3534           i = next_index;
3535           last = i + 1;
3536           break;
3537         case '0':
3538         case '1':
3539         case '2':
3540         case '3':
3541         case '4':
3542         case '5':
3543         case '6':
3544         case '7':
3545         case '8':
3546         case '9': {
3547           int capture_ref = c2 - '0';
3548           if (capture_ref > capture_count) {
3549             i = next_index;
3550             continue;
3551           }
3552           int second_digit_index = next_index + 1;
3553           if (second_digit_index < length) {
3554             // Peek ahead to see if we have two digits.
3555             Char c3 = characters[second_digit_index];
3556             if ('0' <= c3 && c3 <= '9') {  // Double digits.
3557               int double_digit_ref = capture_ref * 10 + c3 - '0';
3558               if (double_digit_ref <= capture_count) {
3559                 next_index = second_digit_index;
3560                 capture_ref = double_digit_ref;
3561               }
3562             }
3563           }
3564           if (capture_ref > 0) {
3565             if (i > last) {
3566               parts->Add(ReplacementPart::ReplacementSubString(last, i), zone);
3567             }
3568             DCHECK(capture_ref <= capture_count);
3569             parts->Add(ReplacementPart::SubjectCapture(capture_ref), zone);
3570             last = next_index + 1;
3571           }
3572           i = next_index;
3573           break;
3574         }
3575         default:
3576           i = next_index;
3577           break;
3578         }
3579       }
3580     }
3581     if (length > last) {
3582       if (last == 0) {
3583         // Replacement is simple.  Do not use Apply to do the replacement.
3584         return true;
3585       } else {
3586         parts->Add(ReplacementPart::ReplacementSubString(last, length), zone);
3587       }
3588     }
3589     return false;
3590   }
3591
3592   ZoneList<ReplacementPart> parts_;
3593   ZoneList<Handle<String> > replacement_substrings_;
3594   Zone* zone_;
3595 };
3596
3597
3598 bool CompiledReplacement::Compile(Handle<String> replacement,
3599                                   int capture_count,
3600                                   int subject_length) {
3601   {
3602     DisallowHeapAllocation no_gc;
3603     String::FlatContent content = replacement->GetFlatContent();
3604     DCHECK(content.IsFlat());
3605     bool simple = false;
3606     if (content.IsOneByte()) {
3607       simple = ParseReplacementPattern(&parts_,
3608                                        content.ToOneByteVector(),
3609                                        capture_count,
3610                                        subject_length,
3611                                        zone());
3612     } else {
3613       DCHECK(content.IsTwoByte());
3614       simple = ParseReplacementPattern(&parts_,
3615                                        content.ToUC16Vector(),
3616                                        capture_count,
3617                                        subject_length,
3618                                        zone());
3619     }
3620     if (simple) return true;
3621   }
3622
3623   Isolate* isolate = replacement->GetIsolate();
3624   // Find substrings of replacement string and create them as String objects.
3625   int substring_index = 0;
3626   for (int i = 0, n = parts_.length(); i < n; i++) {
3627     int tag = parts_[i].tag;
3628     if (tag <= 0) {  // A replacement string slice.
3629       int from = -tag;
3630       int to = parts_[i].data;
3631       replacement_substrings_.Add(
3632           isolate->factory()->NewSubString(replacement, from, to), zone());
3633       parts_[i].tag = REPLACEMENT_SUBSTRING;
3634       parts_[i].data = substring_index;
3635       substring_index++;
3636     } else if (tag == REPLACEMENT_STRING) {
3637       replacement_substrings_.Add(replacement, zone());
3638       parts_[i].data = substring_index;
3639       substring_index++;
3640     }
3641   }
3642   return false;
3643 }
3644
3645
3646 void CompiledReplacement::Apply(ReplacementStringBuilder* builder,
3647                                 int match_from,
3648                                 int match_to,
3649                                 int32_t* match) {
3650   DCHECK_LT(0, parts_.length());
3651   for (int i = 0, n = parts_.length(); i < n; i++) {
3652     ReplacementPart part = parts_[i];
3653     switch (part.tag) {
3654       case SUBJECT_PREFIX:
3655         if (match_from > 0) builder->AddSubjectSlice(0, match_from);
3656         break;
3657       case SUBJECT_SUFFIX: {
3658         int subject_length = part.data;
3659         if (match_to < subject_length) {
3660           builder->AddSubjectSlice(match_to, subject_length);
3661         }
3662         break;
3663       }
3664       case SUBJECT_CAPTURE: {
3665         int capture = part.data;
3666         int from = match[capture * 2];
3667         int to = match[capture * 2 + 1];
3668         if (from >= 0 && to > from) {
3669           builder->AddSubjectSlice(from, to);
3670         }
3671         break;
3672       }
3673       case REPLACEMENT_SUBSTRING:
3674       case REPLACEMENT_STRING:
3675         builder->AddString(replacement_substrings_[part.data]);
3676         break;
3677       default:
3678         UNREACHABLE();
3679     }
3680   }
3681 }
3682
3683
3684 void FindOneByteStringIndices(Vector<const uint8_t> subject, char pattern,
3685                               ZoneList<int>* indices, unsigned int limit,
3686                               Zone* zone) {
3687   DCHECK(limit > 0);
3688   // Collect indices of pattern in subject using memchr.
3689   // Stop after finding at most limit values.
3690   const uint8_t* subject_start = subject.start();
3691   const uint8_t* subject_end = subject_start + subject.length();
3692   const uint8_t* pos = subject_start;
3693   while (limit > 0) {
3694     pos = reinterpret_cast<const uint8_t*>(
3695         memchr(pos, pattern, subject_end - pos));
3696     if (pos == NULL) return;
3697     indices->Add(static_cast<int>(pos - subject_start), zone);
3698     pos++;
3699     limit--;
3700   }
3701 }
3702
3703
3704 void FindTwoByteStringIndices(const Vector<const uc16> subject,
3705                               uc16 pattern,
3706                               ZoneList<int>* indices,
3707                               unsigned int limit,
3708                               Zone* zone) {
3709   DCHECK(limit > 0);
3710   const uc16* subject_start = subject.start();
3711   const uc16* subject_end = subject_start + subject.length();
3712   for (const uc16* pos = subject_start; pos < subject_end && limit > 0; pos++) {
3713     if (*pos == pattern) {
3714       indices->Add(static_cast<int>(pos - subject_start), zone);
3715       limit--;
3716     }
3717   }
3718 }
3719
3720
3721 template <typename SubjectChar, typename PatternChar>
3722 void FindStringIndices(Isolate* isolate,
3723                        Vector<const SubjectChar> subject,
3724                        Vector<const PatternChar> pattern,
3725                        ZoneList<int>* indices,
3726                        unsigned int limit,
3727                        Zone* zone) {
3728   DCHECK(limit > 0);
3729   // Collect indices of pattern in subject.
3730   // Stop after finding at most limit values.
3731   int pattern_length = pattern.length();
3732   int index = 0;
3733   StringSearch<PatternChar, SubjectChar> search(isolate, pattern);
3734   while (limit > 0) {
3735     index = search.Search(subject, index);
3736     if (index < 0) return;
3737     indices->Add(index, zone);
3738     index += pattern_length;
3739     limit--;
3740   }
3741 }
3742
3743
3744 void FindStringIndicesDispatch(Isolate* isolate,
3745                                String* subject,
3746                                String* pattern,
3747                                ZoneList<int>* indices,
3748                                unsigned int limit,
3749                                Zone* zone) {
3750   {
3751     DisallowHeapAllocation no_gc;
3752     String::FlatContent subject_content = subject->GetFlatContent();
3753     String::FlatContent pattern_content = pattern->GetFlatContent();
3754     DCHECK(subject_content.IsFlat());
3755     DCHECK(pattern_content.IsFlat());
3756     if (subject_content.IsOneByte()) {
3757       Vector<const uint8_t> subject_vector = subject_content.ToOneByteVector();
3758       if (pattern_content.IsOneByte()) {
3759         Vector<const uint8_t> pattern_vector =
3760             pattern_content.ToOneByteVector();
3761         if (pattern_vector.length() == 1) {
3762           FindOneByteStringIndices(subject_vector, pattern_vector[0], indices,
3763                                    limit, zone);
3764         } else {
3765           FindStringIndices(isolate,
3766                             subject_vector,
3767                             pattern_vector,
3768                             indices,
3769                             limit,
3770                             zone);
3771         }
3772       } else {
3773         FindStringIndices(isolate,
3774                           subject_vector,
3775                           pattern_content.ToUC16Vector(),
3776                           indices,
3777                           limit,
3778                           zone);
3779       }
3780     } else {
3781       Vector<const uc16> subject_vector = subject_content.ToUC16Vector();
3782       if (pattern_content.IsOneByte()) {
3783         Vector<const uint8_t> pattern_vector =
3784             pattern_content.ToOneByteVector();
3785         if (pattern_vector.length() == 1) {
3786           FindTwoByteStringIndices(subject_vector,
3787                                    pattern_vector[0],
3788                                    indices,
3789                                    limit,
3790                                    zone);
3791         } else {
3792           FindStringIndices(isolate,
3793                             subject_vector,
3794                             pattern_vector,
3795                             indices,
3796                             limit,
3797                             zone);
3798         }
3799       } else {
3800         Vector<const uc16> pattern_vector = pattern_content.ToUC16Vector();
3801         if (pattern_vector.length() == 1) {
3802           FindTwoByteStringIndices(subject_vector,
3803                                    pattern_vector[0],
3804                                    indices,
3805                                    limit,
3806                                    zone);
3807         } else {
3808           FindStringIndices(isolate,
3809                             subject_vector,
3810                             pattern_vector,
3811                             indices,
3812                             limit,
3813                             zone);
3814         }
3815       }
3816     }
3817   }
3818 }
3819
3820
3821 template<typename ResultSeqString>
3822 MUST_USE_RESULT static Object* StringReplaceGlobalAtomRegExpWithString(
3823     Isolate* isolate,
3824     Handle<String> subject,
3825     Handle<JSRegExp> pattern_regexp,
3826     Handle<String> replacement,
3827     Handle<JSArray> last_match_info) {
3828   DCHECK(subject->IsFlat());
3829   DCHECK(replacement->IsFlat());
3830
3831   ZoneScope zone_scope(isolate->runtime_zone());
3832   ZoneList<int> indices(8, zone_scope.zone());
3833   DCHECK_EQ(JSRegExp::ATOM, pattern_regexp->TypeTag());
3834   String* pattern =
3835       String::cast(pattern_regexp->DataAt(JSRegExp::kAtomPatternIndex));
3836   int subject_len = subject->length();
3837   int pattern_len = pattern->length();
3838   int replacement_len = replacement->length();
3839
3840   FindStringIndicesDispatch(
3841       isolate, *subject, pattern, &indices, 0xffffffff, zone_scope.zone());
3842
3843   int matches = indices.length();
3844   if (matches == 0) return *subject;
3845
3846   // Detect integer overflow.
3847   int64_t result_len_64 =
3848       (static_cast<int64_t>(replacement_len) -
3849        static_cast<int64_t>(pattern_len)) *
3850       static_cast<int64_t>(matches) +
3851       static_cast<int64_t>(subject_len);
3852   int result_len;
3853   if (result_len_64 > static_cast<int64_t>(String::kMaxLength)) {
3854     STATIC_ASSERT(String::kMaxLength < kMaxInt);
3855     result_len = kMaxInt;  // Provoke exception.
3856   } else {
3857     result_len = static_cast<int>(result_len_64);
3858   }
3859
3860   int subject_pos = 0;
3861   int result_pos = 0;
3862
3863   MaybeHandle<SeqString> maybe_res;
3864   if (ResultSeqString::kHasOneByteEncoding) {
3865     maybe_res = isolate->factory()->NewRawOneByteString(result_len);
3866   } else {
3867     maybe_res = isolate->factory()->NewRawTwoByteString(result_len);
3868   }
3869   Handle<SeqString> untyped_res;
3870   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, untyped_res, maybe_res);
3871   Handle<ResultSeqString> result = Handle<ResultSeqString>::cast(untyped_res);
3872
3873   for (int i = 0; i < matches; i++) {
3874     // Copy non-matched subject content.
3875     if (subject_pos < indices.at(i)) {
3876       String::WriteToFlat(*subject,
3877                           result->GetChars() + result_pos,
3878                           subject_pos,
3879                           indices.at(i));
3880       result_pos += indices.at(i) - subject_pos;
3881     }
3882
3883     // Replace match.
3884     if (replacement_len > 0) {
3885       String::WriteToFlat(*replacement,
3886                           result->GetChars() + result_pos,
3887                           0,
3888                           replacement_len);
3889       result_pos += replacement_len;
3890     }
3891
3892     subject_pos = indices.at(i) + pattern_len;
3893   }
3894   // Add remaining subject content at the end.
3895   if (subject_pos < subject_len) {
3896     String::WriteToFlat(*subject,
3897                         result->GetChars() + result_pos,
3898                         subject_pos,
3899                         subject_len);
3900   }
3901
3902   int32_t match_indices[] = { indices.at(matches - 1),
3903                               indices.at(matches - 1) + pattern_len };
3904   RegExpImpl::SetLastMatchInfo(last_match_info, subject, 0, match_indices);
3905
3906   return *result;
3907 }
3908
3909
3910 MUST_USE_RESULT static Object* StringReplaceGlobalRegExpWithString(
3911     Isolate* isolate,
3912     Handle<String> subject,
3913     Handle<JSRegExp> regexp,
3914     Handle<String> replacement,
3915     Handle<JSArray> last_match_info) {
3916   DCHECK(subject->IsFlat());
3917   DCHECK(replacement->IsFlat());
3918
3919   int capture_count = regexp->CaptureCount();
3920   int subject_length = subject->length();
3921
3922   // CompiledReplacement uses zone allocation.
3923   ZoneScope zone_scope(isolate->runtime_zone());
3924   CompiledReplacement compiled_replacement(zone_scope.zone());
3925   bool simple_replace = compiled_replacement.Compile(replacement,
3926                                                      capture_count,
3927                                                      subject_length);
3928
3929   // Shortcut for simple non-regexp global replacements
3930   if (regexp->TypeTag() == JSRegExp::ATOM && simple_replace) {
3931     if (subject->HasOnlyOneByteChars() &&
3932         replacement->HasOnlyOneByteChars()) {
3933       return StringReplaceGlobalAtomRegExpWithString<SeqOneByteString>(
3934           isolate, subject, regexp, replacement, last_match_info);
3935     } else {
3936       return StringReplaceGlobalAtomRegExpWithString<SeqTwoByteString>(
3937           isolate, subject, regexp, replacement, last_match_info);
3938     }
3939   }
3940
3941   RegExpImpl::GlobalCache global_cache(regexp, subject, true, isolate);
3942   if (global_cache.HasException()) return isolate->heap()->exception();
3943
3944   int32_t* current_match = global_cache.FetchNext();
3945   if (current_match == NULL) {
3946     if (global_cache.HasException()) return isolate->heap()->exception();
3947     return *subject;
3948   }
3949
3950   // Guessing the number of parts that the final result string is built
3951   // from. Global regexps can match any number of times, so we guess
3952   // conservatively.
3953   int expected_parts = (compiled_replacement.parts() + 1) * 4 + 1;
3954   ReplacementStringBuilder builder(isolate->heap(),
3955                                    subject,
3956                                    expected_parts);
3957
3958   // Number of parts added by compiled replacement plus preceeding
3959   // string and possibly suffix after last match.  It is possible for
3960   // all components to use two elements when encoded as two smis.
3961   const int parts_added_per_loop = 2 * (compiled_replacement.parts() + 2);
3962
3963   int prev = 0;
3964
3965   do {
3966     builder.EnsureCapacity(parts_added_per_loop);
3967
3968     int start = current_match[0];
3969     int end = current_match[1];
3970
3971     if (prev < start) {
3972       builder.AddSubjectSlice(prev, start);
3973     }
3974
3975     if (simple_replace) {
3976       builder.AddString(replacement);
3977     } else {
3978       compiled_replacement.Apply(&builder,
3979                                  start,
3980                                  end,
3981                                  current_match);
3982     }
3983     prev = end;
3984
3985     current_match = global_cache.FetchNext();
3986   } while (current_match != NULL);
3987
3988   if (global_cache.HasException()) return isolate->heap()->exception();
3989
3990   if (prev < subject_length) {
3991     builder.EnsureCapacity(2);
3992     builder.AddSubjectSlice(prev, subject_length);
3993   }
3994
3995   RegExpImpl::SetLastMatchInfo(last_match_info,
3996                                subject,
3997                                capture_count,
3998                                global_cache.LastSuccessfulMatch());
3999
4000   Handle<String> result;
4001   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, result, builder.ToString());
4002   return *result;
4003 }
4004
4005
4006 template <typename ResultSeqString>
4007 MUST_USE_RESULT static Object* StringReplaceGlobalRegExpWithEmptyString(
4008     Isolate* isolate,
4009     Handle<String> subject,
4010     Handle<JSRegExp> regexp,
4011     Handle<JSArray> last_match_info) {
4012   DCHECK(subject->IsFlat());
4013
4014   // Shortcut for simple non-regexp global replacements
4015   if (regexp->TypeTag() == JSRegExp::ATOM) {
4016     Handle<String> empty_string = isolate->factory()->empty_string();
4017     if (subject->IsOneByteRepresentation()) {
4018       return StringReplaceGlobalAtomRegExpWithString<SeqOneByteString>(
4019           isolate, subject, regexp, empty_string, last_match_info);
4020     } else {
4021       return StringReplaceGlobalAtomRegExpWithString<SeqTwoByteString>(
4022           isolate, subject, regexp, empty_string, last_match_info);
4023     }
4024   }
4025
4026   RegExpImpl::GlobalCache global_cache(regexp, subject, true, isolate);
4027   if (global_cache.HasException()) return isolate->heap()->exception();
4028
4029   int32_t* current_match = global_cache.FetchNext();
4030   if (current_match == NULL) {
4031     if (global_cache.HasException()) return isolate->heap()->exception();
4032     return *subject;
4033   }
4034
4035   int start = current_match[0];
4036   int end = current_match[1];
4037   int capture_count = regexp->CaptureCount();
4038   int subject_length = subject->length();
4039
4040   int new_length = subject_length - (end - start);
4041   if (new_length == 0) return isolate->heap()->empty_string();
4042
4043   Handle<ResultSeqString> answer;
4044   if (ResultSeqString::kHasOneByteEncoding) {
4045     answer = Handle<ResultSeqString>::cast(
4046         isolate->factory()->NewRawOneByteString(new_length).ToHandleChecked());
4047   } else {
4048     answer = Handle<ResultSeqString>::cast(
4049         isolate->factory()->NewRawTwoByteString(new_length).ToHandleChecked());
4050   }
4051
4052   int prev = 0;
4053   int position = 0;
4054
4055   do {
4056     start = current_match[0];
4057     end = current_match[1];
4058     if (prev < start) {
4059       // Add substring subject[prev;start] to answer string.
4060       String::WriteToFlat(*subject, answer->GetChars() + position, prev, start);
4061       position += start - prev;
4062     }
4063     prev = end;
4064
4065     current_match = global_cache.FetchNext();
4066   } while (current_match != NULL);
4067
4068   if (global_cache.HasException()) return isolate->heap()->exception();
4069
4070   RegExpImpl::SetLastMatchInfo(last_match_info,
4071                                subject,
4072                                capture_count,
4073                                global_cache.LastSuccessfulMatch());
4074
4075   if (prev < subject_length) {
4076     // Add substring subject[prev;length] to answer string.
4077     String::WriteToFlat(
4078         *subject, answer->GetChars() + position, prev, subject_length);
4079     position += subject_length - prev;
4080   }
4081
4082   if (position == 0) return isolate->heap()->empty_string();
4083
4084   // Shorten string and fill
4085   int string_size = ResultSeqString::SizeFor(position);
4086   int allocated_string_size = ResultSeqString::SizeFor(new_length);
4087   int delta = allocated_string_size - string_size;
4088
4089   answer->set_length(position);
4090   if (delta == 0) return *answer;
4091
4092   Address end_of_string = answer->address() + string_size;
4093   Heap* heap = isolate->heap();
4094
4095   // The trimming is performed on a newly allocated object, which is on a
4096   // fresly allocated page or on an already swept page. Hence, the sweeper
4097   // thread can not get confused with the filler creation. No synchronization
4098   // needed.
4099   heap->CreateFillerObjectAt(end_of_string, delta);
4100   heap->AdjustLiveBytes(answer->address(), -delta, Heap::FROM_MUTATOR);
4101   return *answer;
4102 }
4103
4104
4105 RUNTIME_FUNCTION(Runtime_StringReplaceGlobalRegExpWithString) {
4106   HandleScope scope(isolate);
4107   DCHECK(args.length() == 4);
4108
4109   CONVERT_ARG_HANDLE_CHECKED(String, subject, 0);
4110   CONVERT_ARG_HANDLE_CHECKED(String, replacement, 2);
4111   CONVERT_ARG_HANDLE_CHECKED(JSRegExp, regexp, 1);
4112   CONVERT_ARG_HANDLE_CHECKED(JSArray, last_match_info, 3);
4113
4114   RUNTIME_ASSERT(regexp->GetFlags().is_global());
4115   RUNTIME_ASSERT(last_match_info->HasFastObjectElements());
4116
4117   subject = String::Flatten(subject);
4118
4119   if (replacement->length() == 0) {
4120     if (subject->HasOnlyOneByteChars()) {
4121       return StringReplaceGlobalRegExpWithEmptyString<SeqOneByteString>(
4122           isolate, subject, regexp, last_match_info);
4123     } else {
4124       return StringReplaceGlobalRegExpWithEmptyString<SeqTwoByteString>(
4125           isolate, subject, regexp, last_match_info);
4126     }
4127   }
4128
4129   replacement = String::Flatten(replacement);
4130
4131   return StringReplaceGlobalRegExpWithString(
4132       isolate, subject, regexp, replacement, last_match_info);
4133 }
4134
4135
4136 // This may return an empty MaybeHandle if an exception is thrown or
4137 // we abort due to reaching the recursion limit.
4138 MaybeHandle<String> StringReplaceOneCharWithString(Isolate* isolate,
4139                                                    Handle<String> subject,
4140                                                    Handle<String> search,
4141                                                    Handle<String> replace,
4142                                                    bool* found,
4143                                                    int recursion_limit) {
4144   StackLimitCheck stackLimitCheck(isolate);
4145   if (stackLimitCheck.HasOverflowed() || (recursion_limit == 0)) {
4146     return MaybeHandle<String>();
4147   }
4148   recursion_limit--;
4149   if (subject->IsConsString()) {
4150     ConsString* cons = ConsString::cast(*subject);
4151     Handle<String> first = Handle<String>(cons->first());
4152     Handle<String> second = Handle<String>(cons->second());
4153     Handle<String> new_first;
4154     if (!StringReplaceOneCharWithString(
4155             isolate, first, search, replace, found, recursion_limit)
4156             .ToHandle(&new_first)) {
4157       return MaybeHandle<String>();
4158     }
4159     if (*found) return isolate->factory()->NewConsString(new_first, second);
4160
4161     Handle<String> new_second;
4162     if (!StringReplaceOneCharWithString(
4163             isolate, second, search, replace, found, recursion_limit)
4164             .ToHandle(&new_second)) {
4165       return MaybeHandle<String>();
4166     }
4167     if (*found) return isolate->factory()->NewConsString(first, new_second);
4168
4169     return subject;
4170   } else {
4171     int index = Runtime::StringMatch(isolate, subject, search, 0);
4172     if (index == -1) return subject;
4173     *found = true;
4174     Handle<String> first = isolate->factory()->NewSubString(subject, 0, index);
4175     Handle<String> cons1;
4176     ASSIGN_RETURN_ON_EXCEPTION(
4177         isolate, cons1,
4178         isolate->factory()->NewConsString(first, replace),
4179         String);
4180     Handle<String> second =
4181         isolate->factory()->NewSubString(subject, index + 1, subject->length());
4182     return isolate->factory()->NewConsString(cons1, second);
4183   }
4184 }
4185
4186
4187 RUNTIME_FUNCTION(Runtime_StringReplaceOneCharWithString) {
4188   HandleScope scope(isolate);
4189   DCHECK(args.length() == 3);
4190   CONVERT_ARG_HANDLE_CHECKED(String, subject, 0);
4191   CONVERT_ARG_HANDLE_CHECKED(String, search, 1);
4192   CONVERT_ARG_HANDLE_CHECKED(String, replace, 2);
4193
4194   // If the cons string tree is too deep, we simply abort the recursion and
4195   // retry with a flattened subject string.
4196   const int kRecursionLimit = 0x1000;
4197   bool found = false;
4198   Handle<String> result;
4199   if (StringReplaceOneCharWithString(
4200           isolate, subject, search, replace, &found, kRecursionLimit)
4201           .ToHandle(&result)) {
4202     return *result;
4203   }
4204   if (isolate->has_pending_exception()) return isolate->heap()->exception();
4205
4206   subject = String::Flatten(subject);
4207   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
4208       isolate, result,
4209       StringReplaceOneCharWithString(
4210           isolate, subject, search, replace, &found, kRecursionLimit));
4211   return *result;
4212 }
4213
4214
4215 // Perform string match of pattern on subject, starting at start index.
4216 // Caller must ensure that 0 <= start_index <= sub->length(),
4217 // and should check that pat->length() + start_index <= sub->length().
4218 int Runtime::StringMatch(Isolate* isolate,
4219                          Handle<String> sub,
4220                          Handle<String> pat,
4221                          int start_index) {
4222   DCHECK(0 <= start_index);
4223   DCHECK(start_index <= sub->length());
4224
4225   int pattern_length = pat->length();
4226   if (pattern_length == 0) return start_index;
4227
4228   int subject_length = sub->length();
4229   if (start_index + pattern_length > subject_length) return -1;
4230
4231   sub = String::Flatten(sub);
4232   pat = String::Flatten(pat);
4233
4234   DisallowHeapAllocation no_gc;  // ensure vectors stay valid
4235   // Extract flattened substrings of cons strings before getting encoding.
4236   String::FlatContent seq_sub = sub->GetFlatContent();
4237   String::FlatContent seq_pat = pat->GetFlatContent();
4238
4239   // dispatch on type of strings
4240   if (seq_pat.IsOneByte()) {
4241     Vector<const uint8_t> pat_vector = seq_pat.ToOneByteVector();
4242     if (seq_sub.IsOneByte()) {
4243       return SearchString(isolate,
4244                           seq_sub.ToOneByteVector(),
4245                           pat_vector,
4246                           start_index);
4247     }
4248     return SearchString(isolate,
4249                         seq_sub.ToUC16Vector(),
4250                         pat_vector,
4251                         start_index);
4252   }
4253   Vector<const uc16> pat_vector = seq_pat.ToUC16Vector();
4254   if (seq_sub.IsOneByte()) {
4255     return SearchString(isolate,
4256                         seq_sub.ToOneByteVector(),
4257                         pat_vector,
4258                         start_index);
4259   }
4260   return SearchString(isolate,
4261                       seq_sub.ToUC16Vector(),
4262                       pat_vector,
4263                       start_index);
4264 }
4265
4266
4267 RUNTIME_FUNCTION(Runtime_StringIndexOf) {
4268   HandleScope scope(isolate);
4269   DCHECK(args.length() == 3);
4270
4271   CONVERT_ARG_HANDLE_CHECKED(String, sub, 0);
4272   CONVERT_ARG_HANDLE_CHECKED(String, pat, 1);
4273   CONVERT_ARG_HANDLE_CHECKED(Object, index, 2);
4274
4275   uint32_t start_index;
4276   if (!index->ToArrayIndex(&start_index)) return Smi::FromInt(-1);
4277
4278   RUNTIME_ASSERT(start_index <= static_cast<uint32_t>(sub->length()));
4279   int position = Runtime::StringMatch(isolate, sub, pat, start_index);
4280   return Smi::FromInt(position);
4281 }
4282
4283
4284 template <typename schar, typename pchar>
4285 static int StringMatchBackwards(Vector<const schar> subject,
4286                                 Vector<const pchar> pattern,
4287                                 int idx) {
4288   int pattern_length = pattern.length();
4289   DCHECK(pattern_length >= 1);
4290   DCHECK(idx + pattern_length <= subject.length());
4291
4292   if (sizeof(schar) == 1 && sizeof(pchar) > 1) {
4293     for (int i = 0; i < pattern_length; i++) {
4294       uc16 c = pattern[i];
4295       if (c > String::kMaxOneByteCharCode) {
4296         return -1;
4297       }
4298     }
4299   }
4300
4301   pchar pattern_first_char = pattern[0];
4302   for (int i = idx; i >= 0; i--) {
4303     if (subject[i] != pattern_first_char) continue;
4304     int j = 1;
4305     while (j < pattern_length) {
4306       if (pattern[j] != subject[i+j]) {
4307         break;
4308       }
4309       j++;
4310     }
4311     if (j == pattern_length) {
4312       return i;
4313     }
4314   }
4315   return -1;
4316 }
4317
4318
4319 RUNTIME_FUNCTION(Runtime_StringLastIndexOf) {
4320   HandleScope scope(isolate);
4321   DCHECK(args.length() == 3);
4322
4323   CONVERT_ARG_HANDLE_CHECKED(String, sub, 0);
4324   CONVERT_ARG_HANDLE_CHECKED(String, pat, 1);
4325   CONVERT_ARG_HANDLE_CHECKED(Object, index, 2);
4326
4327   uint32_t start_index;
4328   if (!index->ToArrayIndex(&start_index)) return Smi::FromInt(-1);
4329
4330   uint32_t pat_length = pat->length();
4331   uint32_t sub_length = sub->length();
4332
4333   if (start_index + pat_length > sub_length) {
4334     start_index = sub_length - pat_length;
4335   }
4336
4337   if (pat_length == 0) {
4338     return Smi::FromInt(start_index);
4339   }
4340
4341   sub = String::Flatten(sub);
4342   pat = String::Flatten(pat);
4343
4344   int position = -1;
4345   DisallowHeapAllocation no_gc;  // ensure vectors stay valid
4346
4347   String::FlatContent sub_content = sub->GetFlatContent();
4348   String::FlatContent pat_content = pat->GetFlatContent();
4349
4350   if (pat_content.IsOneByte()) {
4351     Vector<const uint8_t> pat_vector = pat_content.ToOneByteVector();
4352     if (sub_content.IsOneByte()) {
4353       position = StringMatchBackwards(sub_content.ToOneByteVector(),
4354                                       pat_vector,
4355                                       start_index);
4356     } else {
4357       position = StringMatchBackwards(sub_content.ToUC16Vector(),
4358                                       pat_vector,
4359                                       start_index);
4360     }
4361   } else {
4362     Vector<const uc16> pat_vector = pat_content.ToUC16Vector();
4363     if (sub_content.IsOneByte()) {
4364       position = StringMatchBackwards(sub_content.ToOneByteVector(),
4365                                       pat_vector,
4366                                       start_index);
4367     } else {
4368       position = StringMatchBackwards(sub_content.ToUC16Vector(),
4369                                       pat_vector,
4370                                       start_index);
4371     }
4372   }
4373
4374   return Smi::FromInt(position);
4375 }
4376
4377
4378 RUNTIME_FUNCTION(Runtime_StringLocaleCompare) {
4379   HandleScope handle_scope(isolate);
4380   DCHECK(args.length() == 2);
4381
4382   CONVERT_ARG_HANDLE_CHECKED(String, str1, 0);
4383   CONVERT_ARG_HANDLE_CHECKED(String, str2, 1);
4384
4385   if (str1.is_identical_to(str2)) return Smi::FromInt(0);  // Equal.
4386   int str1_length = str1->length();
4387   int str2_length = str2->length();
4388
4389   // Decide trivial cases without flattening.
4390   if (str1_length == 0) {
4391     if (str2_length == 0) return Smi::FromInt(0);  // Equal.
4392     return Smi::FromInt(-str2_length);
4393   } else {
4394     if (str2_length == 0) return Smi::FromInt(str1_length);
4395   }
4396
4397   int end = str1_length < str2_length ? str1_length : str2_length;
4398
4399   // No need to flatten if we are going to find the answer on the first
4400   // character.  At this point we know there is at least one character
4401   // in each string, due to the trivial case handling above.
4402   int d = str1->Get(0) - str2->Get(0);
4403   if (d != 0) return Smi::FromInt(d);
4404
4405   str1 = String::Flatten(str1);
4406   str2 = String::Flatten(str2);
4407
4408   DisallowHeapAllocation no_gc;
4409   String::FlatContent flat1 = str1->GetFlatContent();
4410   String::FlatContent flat2 = str2->GetFlatContent();
4411
4412   for (int i = 0; i < end; i++) {
4413     if (flat1.Get(i) != flat2.Get(i)) {
4414       return Smi::FromInt(flat1.Get(i) - flat2.Get(i));
4415     }
4416   }
4417
4418   return Smi::FromInt(str1_length - str2_length);
4419 }
4420
4421
4422 RUNTIME_FUNCTION(Runtime_SubString) {
4423   HandleScope scope(isolate);
4424   DCHECK(args.length() == 3);
4425
4426   CONVERT_ARG_HANDLE_CHECKED(String, string, 0);
4427   int start, end;
4428   // We have a fast integer-only case here to avoid a conversion to double in
4429   // the common case where from and to are Smis.
4430   if (args[1]->IsSmi() && args[2]->IsSmi()) {
4431     CONVERT_SMI_ARG_CHECKED(from_number, 1);
4432     CONVERT_SMI_ARG_CHECKED(to_number, 2);
4433     start = from_number;
4434     end = to_number;
4435   } else {
4436     CONVERT_DOUBLE_ARG_CHECKED(from_number, 1);
4437     CONVERT_DOUBLE_ARG_CHECKED(to_number, 2);
4438     start = FastD2IChecked(from_number);
4439     end = FastD2IChecked(to_number);
4440   }
4441   RUNTIME_ASSERT(end >= start);
4442   RUNTIME_ASSERT(start >= 0);
4443   RUNTIME_ASSERT(end <= string->length());
4444   isolate->counters()->sub_string_runtime()->Increment();
4445
4446   return *isolate->factory()->NewSubString(string, start, end);
4447 }
4448
4449
4450 RUNTIME_FUNCTION(Runtime_InternalizeString) {
4451   HandleScope handles(isolate);
4452   RUNTIME_ASSERT(args.length() == 1);
4453   CONVERT_ARG_HANDLE_CHECKED(String, string, 0);
4454   return *isolate->factory()->InternalizeString(string);
4455 }
4456
4457
4458 RUNTIME_FUNCTION(Runtime_StringMatch) {
4459   HandleScope handles(isolate);
4460   DCHECK(args.length() == 3);
4461
4462   CONVERT_ARG_HANDLE_CHECKED(String, subject, 0);
4463   CONVERT_ARG_HANDLE_CHECKED(JSRegExp, regexp, 1);
4464   CONVERT_ARG_HANDLE_CHECKED(JSArray, regexp_info, 2);
4465
4466   RUNTIME_ASSERT(regexp_info->HasFastObjectElements());
4467
4468   RegExpImpl::GlobalCache global_cache(regexp, subject, true, isolate);
4469   if (global_cache.HasException()) return isolate->heap()->exception();
4470
4471   int capture_count = regexp->CaptureCount();
4472
4473   ZoneScope zone_scope(isolate->runtime_zone());
4474   ZoneList<int> offsets(8, zone_scope.zone());
4475
4476   while (true) {
4477     int32_t* match = global_cache.FetchNext();
4478     if (match == NULL) break;
4479     offsets.Add(match[0], zone_scope.zone());  // start
4480     offsets.Add(match[1], zone_scope.zone());  // end
4481   }
4482
4483   if (global_cache.HasException()) return isolate->heap()->exception();
4484
4485   if (offsets.length() == 0) {
4486     // Not a single match.
4487     return isolate->heap()->null_value();
4488   }
4489
4490   RegExpImpl::SetLastMatchInfo(regexp_info,
4491                                subject,
4492                                capture_count,
4493                                global_cache.LastSuccessfulMatch());
4494
4495   int matches = offsets.length() / 2;
4496   Handle<FixedArray> elements = isolate->factory()->NewFixedArray(matches);
4497   Handle<String> substring =
4498       isolate->factory()->NewSubString(subject, offsets.at(0), offsets.at(1));
4499   elements->set(0, *substring);
4500   for (int i = 1; i < matches; i++) {
4501     HandleScope temp_scope(isolate);
4502     int from = offsets.at(i * 2);
4503     int to = offsets.at(i * 2 + 1);
4504     Handle<String> substring =
4505         isolate->factory()->NewProperSubString(subject, from, to);
4506     elements->set(i, *substring);
4507   }
4508   Handle<JSArray> result = isolate->factory()->NewJSArrayWithElements(elements);
4509   result->set_length(Smi::FromInt(matches));
4510   return *result;
4511 }
4512
4513
4514 // Only called from Runtime_RegExpExecMultiple so it doesn't need to maintain
4515 // separate last match info.  See comment on that function.
4516 template<bool has_capture>
4517 static Object* SearchRegExpMultiple(
4518     Isolate* isolate,
4519     Handle<String> subject,
4520     Handle<JSRegExp> regexp,
4521     Handle<JSArray> last_match_array,
4522     Handle<JSArray> result_array) {
4523   DCHECK(subject->IsFlat());
4524   DCHECK_NE(has_capture, regexp->CaptureCount() == 0);
4525
4526   int capture_count = regexp->CaptureCount();
4527   int subject_length = subject->length();
4528
4529   static const int kMinLengthToCache = 0x1000;
4530
4531   if (subject_length > kMinLengthToCache) {
4532     Handle<Object> cached_answer(RegExpResultsCache::Lookup(
4533         isolate->heap(),
4534         *subject,
4535         regexp->data(),
4536         RegExpResultsCache::REGEXP_MULTIPLE_INDICES), isolate);
4537     if (*cached_answer != Smi::FromInt(0)) {
4538       Handle<FixedArray> cached_fixed_array =
4539           Handle<FixedArray>(FixedArray::cast(*cached_answer));
4540       // The cache FixedArray is a COW-array and can therefore be reused.
4541       JSArray::SetContent(result_array, cached_fixed_array);
4542       // The actual length of the result array is stored in the last element of
4543       // the backing store (the backing FixedArray may have a larger capacity).
4544       Object* cached_fixed_array_last_element =
4545           cached_fixed_array->get(cached_fixed_array->length() - 1);
4546       Smi* js_array_length = Smi::cast(cached_fixed_array_last_element);
4547       result_array->set_length(js_array_length);
4548       RegExpImpl::SetLastMatchInfo(
4549           last_match_array, subject, capture_count, NULL);
4550       return *result_array;
4551     }
4552   }
4553
4554   RegExpImpl::GlobalCache global_cache(regexp, subject, true, isolate);
4555   if (global_cache.HasException()) return isolate->heap()->exception();
4556
4557   // Ensured in Runtime_RegExpExecMultiple.
4558   DCHECK(result_array->HasFastObjectElements());
4559   Handle<FixedArray> result_elements(
4560       FixedArray::cast(result_array->elements()));
4561   if (result_elements->length() < 16) {
4562     result_elements = isolate->factory()->NewFixedArrayWithHoles(16);
4563   }
4564
4565   FixedArrayBuilder builder(result_elements);
4566
4567   // Position to search from.
4568   int match_start = -1;
4569   int match_end = 0;
4570   bool first = true;
4571
4572   // Two smis before and after the match, for very long strings.
4573   static const int kMaxBuilderEntriesPerRegExpMatch = 5;
4574
4575   while (true) {
4576     int32_t* current_match = global_cache.FetchNext();
4577     if (current_match == NULL) break;
4578     match_start = current_match[0];
4579     builder.EnsureCapacity(kMaxBuilderEntriesPerRegExpMatch);
4580     if (match_end < match_start) {
4581       ReplacementStringBuilder::AddSubjectSlice(&builder,
4582                                                 match_end,
4583                                                 match_start);
4584     }
4585     match_end = current_match[1];
4586     {
4587       // Avoid accumulating new handles inside loop.
4588       HandleScope temp_scope(isolate);
4589       Handle<String> match;
4590       if (!first) {
4591         match = isolate->factory()->NewProperSubString(subject,
4592                                                        match_start,
4593                                                        match_end);
4594       } else {
4595         match = isolate->factory()->NewSubString(subject,
4596                                                  match_start,
4597                                                  match_end);
4598         first = false;
4599       }
4600
4601       if (has_capture) {
4602         // Arguments array to replace function is match, captures, index and
4603         // subject, i.e., 3 + capture count in total.
4604         Handle<FixedArray> elements =
4605             isolate->factory()->NewFixedArray(3 + capture_count);
4606
4607         elements->set(0, *match);
4608         for (int i = 1; i <= capture_count; i++) {
4609           int start = current_match[i * 2];
4610           if (start >= 0) {
4611             int end = current_match[i * 2 + 1];
4612             DCHECK(start <= end);
4613             Handle<String> substring =
4614                 isolate->factory()->NewSubString(subject, start, end);
4615             elements->set(i, *substring);
4616           } else {
4617             DCHECK(current_match[i * 2 + 1] < 0);
4618             elements->set(i, isolate->heap()->undefined_value());
4619           }
4620         }
4621         elements->set(capture_count + 1, Smi::FromInt(match_start));
4622         elements->set(capture_count + 2, *subject);
4623         builder.Add(*isolate->factory()->NewJSArrayWithElements(elements));
4624       } else {
4625         builder.Add(*match);
4626       }
4627     }
4628   }
4629
4630   if (global_cache.HasException()) return isolate->heap()->exception();
4631
4632   if (match_start >= 0) {
4633     // Finished matching, with at least one match.
4634     if (match_end < subject_length) {
4635       ReplacementStringBuilder::AddSubjectSlice(&builder,
4636                                                 match_end,
4637                                                 subject_length);
4638     }
4639
4640     RegExpImpl::SetLastMatchInfo(
4641         last_match_array, subject, capture_count, NULL);
4642
4643     if (subject_length > kMinLengthToCache) {
4644       // Store the length of the result array into the last element of the
4645       // backing FixedArray.
4646       builder.EnsureCapacity(1);
4647       Handle<FixedArray> fixed_array = builder.array();
4648       fixed_array->set(fixed_array->length() - 1,
4649                        Smi::FromInt(builder.length()));
4650       // Cache the result and turn the FixedArray into a COW array.
4651       RegExpResultsCache::Enter(isolate,
4652                                 subject,
4653                                 handle(regexp->data(), isolate),
4654                                 fixed_array,
4655                                 RegExpResultsCache::REGEXP_MULTIPLE_INDICES);
4656     }
4657     return *builder.ToJSArray(result_array);
4658   } else {
4659     return isolate->heap()->null_value();  // No matches at all.
4660   }
4661 }
4662
4663
4664 // This is only called for StringReplaceGlobalRegExpWithFunction.  This sets
4665 // lastMatchInfoOverride to maintain the last match info, so we don't need to
4666 // set any other last match array info.
4667 RUNTIME_FUNCTION(Runtime_RegExpExecMultiple) {
4668   HandleScope handles(isolate);
4669   DCHECK(args.length() == 4);
4670
4671   CONVERT_ARG_HANDLE_CHECKED(String, subject, 1);
4672   CONVERT_ARG_HANDLE_CHECKED(JSRegExp, regexp, 0);
4673   CONVERT_ARG_HANDLE_CHECKED(JSArray, last_match_info, 2);
4674   CONVERT_ARG_HANDLE_CHECKED(JSArray, result_array, 3);
4675   RUNTIME_ASSERT(last_match_info->HasFastObjectElements());
4676   RUNTIME_ASSERT(result_array->HasFastObjectElements());
4677
4678   subject = String::Flatten(subject);
4679   RUNTIME_ASSERT(regexp->GetFlags().is_global());
4680
4681   if (regexp->CaptureCount() == 0) {
4682     return SearchRegExpMultiple<false>(
4683         isolate, subject, regexp, last_match_info, result_array);
4684   } else {
4685     return SearchRegExpMultiple<true>(
4686         isolate, subject, regexp, last_match_info, result_array);
4687   }
4688 }
4689
4690
4691 RUNTIME_FUNCTION(Runtime_NumberToRadixString) {
4692   HandleScope scope(isolate);
4693   DCHECK(args.length() == 2);
4694   CONVERT_SMI_ARG_CHECKED(radix, 1);
4695   RUNTIME_ASSERT(2 <= radix && radix <= 36);
4696
4697   // Fast case where the result is a one character string.
4698   if (args[0]->IsSmi()) {
4699     int value = args.smi_at(0);
4700     if (value >= 0 && value < radix) {
4701       // Character array used for conversion.
4702       static const char kCharTable[] = "0123456789abcdefghijklmnopqrstuvwxyz";
4703       return *isolate->factory()->
4704           LookupSingleCharacterStringFromCode(kCharTable[value]);
4705     }
4706   }
4707
4708   // Slow case.
4709   CONVERT_DOUBLE_ARG_CHECKED(value, 0);
4710   if (std::isnan(value)) {
4711     return isolate->heap()->nan_string();
4712   }
4713   if (std::isinf(value)) {
4714     if (value < 0) {
4715       return isolate->heap()->minus_infinity_string();
4716     }
4717     return isolate->heap()->infinity_string();
4718   }
4719   char* str = DoubleToRadixCString(value, radix);
4720   Handle<String> result = isolate->factory()->NewStringFromAsciiChecked(str);
4721   DeleteArray(str);
4722   return *result;
4723 }
4724
4725
4726 RUNTIME_FUNCTION(Runtime_NumberToFixed) {
4727   HandleScope scope(isolate);
4728   DCHECK(args.length() == 2);
4729
4730   CONVERT_DOUBLE_ARG_CHECKED(value, 0);
4731   CONVERT_DOUBLE_ARG_CHECKED(f_number, 1);
4732   int f = FastD2IChecked(f_number);
4733   // See DoubleToFixedCString for these constants:
4734   RUNTIME_ASSERT(f >= 0 && f <= 20);
4735   RUNTIME_ASSERT(!Double(value).IsSpecial());
4736   char* str = DoubleToFixedCString(value, f);
4737   Handle<String> result = isolate->factory()->NewStringFromAsciiChecked(str);
4738   DeleteArray(str);
4739   return *result;
4740 }
4741
4742
4743 RUNTIME_FUNCTION(Runtime_NumberToExponential) {
4744   HandleScope scope(isolate);
4745   DCHECK(args.length() == 2);
4746
4747   CONVERT_DOUBLE_ARG_CHECKED(value, 0);
4748   CONVERT_DOUBLE_ARG_CHECKED(f_number, 1);
4749   int f = FastD2IChecked(f_number);
4750   RUNTIME_ASSERT(f >= -1 && f <= 20);
4751   RUNTIME_ASSERT(!Double(value).IsSpecial());
4752   char* str = DoubleToExponentialCString(value, f);
4753   Handle<String> result = isolate->factory()->NewStringFromAsciiChecked(str);
4754   DeleteArray(str);
4755   return *result;
4756 }
4757
4758
4759 RUNTIME_FUNCTION(Runtime_NumberToPrecision) {
4760   HandleScope scope(isolate);
4761   DCHECK(args.length() == 2);
4762
4763   CONVERT_DOUBLE_ARG_CHECKED(value, 0);
4764   CONVERT_DOUBLE_ARG_CHECKED(f_number, 1);
4765   int f = FastD2IChecked(f_number);
4766   RUNTIME_ASSERT(f >= 1 && f <= 21);
4767   RUNTIME_ASSERT(!Double(value).IsSpecial());
4768   char* str = DoubleToPrecisionCString(value, f);
4769   Handle<String> result = isolate->factory()->NewStringFromAsciiChecked(str);
4770   DeleteArray(str);
4771   return *result;
4772 }
4773
4774
4775 RUNTIME_FUNCTION(Runtime_IsValidSmi) {
4776   SealHandleScope shs(isolate);
4777   DCHECK(args.length() == 1);
4778
4779   CONVERT_NUMBER_CHECKED(int32_t, number, Int32, args[0]);
4780   return isolate->heap()->ToBoolean(Smi::IsValid(number));
4781 }
4782
4783
4784 // Returns a single character string where first character equals
4785 // string->Get(index).
4786 static Handle<Object> GetCharAt(Handle<String> string, uint32_t index) {
4787   if (index < static_cast<uint32_t>(string->length())) {
4788     Factory* factory = string->GetIsolate()->factory();
4789     return factory->LookupSingleCharacterStringFromCode(
4790         String::Flatten(string)->Get(index));
4791   }
4792   return Execution::CharAt(string, index);
4793 }
4794
4795
4796 MaybeHandle<Object> Runtime::GetElementOrCharAt(Isolate* isolate,
4797                                                 Handle<Object> object,
4798                                                 uint32_t index) {
4799   // Handle [] indexing on Strings
4800   if (object->IsString()) {
4801     Handle<Object> result = GetCharAt(Handle<String>::cast(object), index);
4802     if (!result->IsUndefined()) return result;
4803   }
4804
4805   // Handle [] indexing on String objects
4806   if (object->IsStringObjectWithCharacterAt(index)) {
4807     Handle<JSValue> js_value = Handle<JSValue>::cast(object);
4808     Handle<Object> result =
4809         GetCharAt(Handle<String>(String::cast(js_value->value())), index);
4810     if (!result->IsUndefined()) return result;
4811   }
4812
4813   Handle<Object> result;
4814   if (object->IsString() || object->IsNumber() || object->IsBoolean()) {
4815     PrototypeIterator iter(isolate, object);
4816     return Object::GetElement(isolate, PrototypeIterator::GetCurrent(iter),
4817                               index);
4818   } else {
4819     return Object::GetElement(isolate, object, index);
4820   }
4821 }
4822
4823
4824 MUST_USE_RESULT
4825 static MaybeHandle<Name> ToName(Isolate* isolate, Handle<Object> key) {
4826   if (key->IsName()) {
4827     return Handle<Name>::cast(key);
4828   } else {
4829     Handle<Object> converted;
4830     ASSIGN_RETURN_ON_EXCEPTION(
4831         isolate, converted, Execution::ToString(isolate, key), Name);
4832     return Handle<Name>::cast(converted);
4833   }
4834 }
4835
4836
4837 MaybeHandle<Object> Runtime::HasObjectProperty(Isolate* isolate,
4838                                                Handle<JSReceiver> object,
4839                                                Handle<Object> key) {
4840   Maybe<bool> maybe;
4841   // Check if the given key is an array index.
4842   uint32_t index;
4843   if (key->ToArrayIndex(&index)) {
4844     maybe = JSReceiver::HasElement(object, index);
4845   } else {
4846     // Convert the key to a name - possibly by calling back into JavaScript.
4847     Handle<Name> name;
4848     ASSIGN_RETURN_ON_EXCEPTION(isolate, name, ToName(isolate, key), Object);
4849
4850     maybe = JSReceiver::HasProperty(object, name);
4851   }
4852
4853   if (!maybe.has_value) return MaybeHandle<Object>();
4854   return isolate->factory()->ToBoolean(maybe.value);
4855 }
4856
4857
4858 MaybeHandle<Object> Runtime::GetObjectProperty(Isolate* isolate,
4859                                                Handle<Object> object,
4860                                                Handle<Object> key) {
4861   if (object->IsUndefined() || object->IsNull()) {
4862     Handle<Object> args[2] = { key, object };
4863     THROW_NEW_ERROR(isolate, NewTypeError("non_object_property_load",
4864                                           HandleVector(args, 2)),
4865                     Object);
4866   }
4867
4868   // Check if the given key is an array index.
4869   uint32_t index;
4870   if (key->ToArrayIndex(&index)) {
4871     return GetElementOrCharAt(isolate, object, index);
4872   }
4873
4874   // Convert the key to a name - possibly by calling back into JavaScript.
4875   Handle<Name> name;
4876   ASSIGN_RETURN_ON_EXCEPTION(isolate, name, ToName(isolate, key), Object);
4877
4878   // Check if the name is trivially convertible to an index and get
4879   // the element if so.
4880   if (name->AsArrayIndex(&index)) {
4881     return GetElementOrCharAt(isolate, object, index);
4882   } else {
4883     return Object::GetProperty(object, name);
4884   }
4885 }
4886
4887
4888 RUNTIME_FUNCTION(Runtime_GetProperty) {
4889   HandleScope scope(isolate);
4890   DCHECK(args.length() == 2);
4891
4892   CONVERT_ARG_HANDLE_CHECKED(Object, object, 0);
4893   CONVERT_ARG_HANDLE_CHECKED(Object, key, 1);
4894   Handle<Object> result;
4895   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
4896       isolate, result,
4897       Runtime::GetObjectProperty(isolate, object, key));
4898   return *result;
4899 }
4900
4901
4902 // KeyedGetProperty is called from KeyedLoadIC::GenerateGeneric.
4903 RUNTIME_FUNCTION(Runtime_KeyedGetProperty) {
4904   HandleScope scope(isolate);
4905   DCHECK(args.length() == 2);
4906
4907   CONVERT_ARG_HANDLE_CHECKED(Object, receiver_obj, 0);
4908   CONVERT_ARG_HANDLE_CHECKED(Object, key_obj, 1);
4909
4910   // Fast cases for getting named properties of the receiver JSObject
4911   // itself.
4912   //
4913   // The global proxy objects has to be excluded since LookupOwn on
4914   // the global proxy object can return a valid result even though the
4915   // global proxy object never has properties.  This is the case
4916   // because the global proxy object forwards everything to its hidden
4917   // prototype including own lookups.
4918   //
4919   // Additionally, we need to make sure that we do not cache results
4920   // for objects that require access checks.
4921   if (receiver_obj->IsJSObject()) {
4922     if (!receiver_obj->IsJSGlobalProxy() &&
4923         !receiver_obj->IsAccessCheckNeeded() &&
4924         key_obj->IsName()) {
4925       DisallowHeapAllocation no_allocation;
4926       Handle<JSObject> receiver = Handle<JSObject>::cast(receiver_obj);
4927       Handle<Name> key = Handle<Name>::cast(key_obj);
4928       if (receiver->HasFastProperties()) {
4929         // Attempt to use lookup cache.
4930         Handle<Map> receiver_map(receiver->map(), isolate);
4931         KeyedLookupCache* keyed_lookup_cache = isolate->keyed_lookup_cache();
4932         int index = keyed_lookup_cache->Lookup(receiver_map, key);
4933         if (index != -1) {
4934           // Doubles are not cached, so raw read the value.
4935           return receiver->RawFastPropertyAt(
4936               FieldIndex::ForKeyedLookupCacheIndex(*receiver_map, index));
4937         }
4938         // Lookup cache miss.  Perform lookup and update the cache if
4939         // appropriate.
4940         LookupIterator it(receiver, key, LookupIterator::OWN);
4941         if (it.state() == LookupIterator::DATA &&
4942             it.property_details().type() == FIELD) {
4943           FieldIndex field_index = it.GetFieldIndex();
4944           // Do not track double fields in the keyed lookup cache. Reading
4945           // double values requires boxing.
4946           if (!it.representation().IsDouble()) {
4947             keyed_lookup_cache->Update(receiver_map, key,
4948                 field_index.GetKeyedLookupCacheIndex());
4949           }
4950           AllowHeapAllocation allow_allocation;
4951           return *JSObject::FastPropertyAt(receiver, it.representation(),
4952                                            field_index);
4953         }
4954       } else {
4955         // Attempt dictionary lookup.
4956         NameDictionary* dictionary = receiver->property_dictionary();
4957         int entry = dictionary->FindEntry(key);
4958         if ((entry != NameDictionary::kNotFound) &&
4959             (dictionary->DetailsAt(entry).type() == NORMAL)) {
4960           Object* value = dictionary->ValueAt(entry);
4961           if (!receiver->IsGlobalObject()) return value;
4962           value = PropertyCell::cast(value)->value();
4963           if (!value->IsTheHole()) return value;
4964           // If value is the hole (meaning, absent) do the general lookup.
4965         }
4966       }
4967     } else if (key_obj->IsSmi()) {
4968       // JSObject without a name key. If the key is a Smi, check for a
4969       // definite out-of-bounds access to elements, which is a strong indicator
4970       // that subsequent accesses will also call the runtime. Proactively
4971       // transition elements to FAST_*_ELEMENTS to avoid excessive boxing of
4972       // doubles for those future calls in the case that the elements would
4973       // become FAST_DOUBLE_ELEMENTS.
4974       Handle<JSObject> js_object = Handle<JSObject>::cast(receiver_obj);
4975       ElementsKind elements_kind = js_object->GetElementsKind();
4976       if (IsFastDoubleElementsKind(elements_kind)) {
4977         Handle<Smi> key = Handle<Smi>::cast(key_obj);
4978         if (key->value() >= js_object->elements()->length()) {
4979           if (IsFastHoleyElementsKind(elements_kind)) {
4980             elements_kind = FAST_HOLEY_ELEMENTS;
4981           } else {
4982             elements_kind = FAST_ELEMENTS;
4983           }
4984           RETURN_FAILURE_ON_EXCEPTION(
4985               isolate, TransitionElements(js_object, elements_kind, isolate));
4986         }
4987       } else {
4988         DCHECK(IsFastSmiOrObjectElementsKind(elements_kind) ||
4989                !IsFastElementsKind(elements_kind));
4990       }
4991     }
4992   } else if (receiver_obj->IsString() && key_obj->IsSmi()) {
4993     // Fast case for string indexing using [] with a smi index.
4994     Handle<String> str = Handle<String>::cast(receiver_obj);
4995     int index = args.smi_at(1);
4996     if (index >= 0 && index < str->length()) {
4997       return *GetCharAt(str, index);
4998     }
4999   }
5000
5001   // Fall back to GetObjectProperty.
5002   Handle<Object> result;
5003   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
5004       isolate, result,
5005       Runtime::GetObjectProperty(isolate, receiver_obj, key_obj));
5006   return *result;
5007 }
5008
5009
5010 static bool IsValidAccessor(Handle<Object> obj) {
5011   return obj->IsUndefined() || obj->IsSpecFunction() || obj->IsNull();
5012 }
5013
5014
5015 // Transform getter or setter into something DefineAccessor can handle.
5016 static Handle<Object> InstantiateAccessorComponent(Isolate* isolate,
5017                                                    Handle<Object> component) {
5018   if (component->IsUndefined()) return isolate->factory()->undefined_value();
5019   Handle<FunctionTemplateInfo> info =
5020       Handle<FunctionTemplateInfo>::cast(component);
5021   return Utils::OpenHandle(*Utils::ToLocal(info)->GetFunction());
5022 }
5023
5024
5025 RUNTIME_FUNCTION(Runtime_DefineApiAccessorProperty) {
5026   HandleScope scope(isolate);
5027   DCHECK(args.length() == 5);
5028   CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0);
5029   CONVERT_ARG_HANDLE_CHECKED(Name, name, 1);
5030   CONVERT_ARG_HANDLE_CHECKED(Object, getter, 2);
5031   CONVERT_ARG_HANDLE_CHECKED(Object, setter, 3);
5032   CONVERT_SMI_ARG_CHECKED(attribute, 4);
5033   RUNTIME_ASSERT(getter->IsUndefined() || getter->IsFunctionTemplateInfo());
5034   RUNTIME_ASSERT(setter->IsUndefined() || setter->IsFunctionTemplateInfo());
5035   RUNTIME_ASSERT(PropertyDetails::AttributesField::is_valid(
5036       static_cast<PropertyAttributes>(attribute)));
5037   RETURN_FAILURE_ON_EXCEPTION(
5038       isolate, JSObject::DefineAccessor(
5039                    object, name, InstantiateAccessorComponent(isolate, getter),
5040                    InstantiateAccessorComponent(isolate, setter),
5041                    static_cast<PropertyAttributes>(attribute)));
5042   return isolate->heap()->undefined_value();
5043 }
5044
5045
5046 // Implements part of 8.12.9 DefineOwnProperty.
5047 // There are 3 cases that lead here:
5048 // Step 4b - define a new accessor property.
5049 // Steps 9c & 12 - replace an existing data property with an accessor property.
5050 // Step 12 - update an existing accessor property with an accessor or generic
5051 //           descriptor.
5052 RUNTIME_FUNCTION(Runtime_DefineAccessorPropertyUnchecked) {
5053   HandleScope scope(isolate);
5054   DCHECK(args.length() == 5);
5055   CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0);
5056   RUNTIME_ASSERT(!obj->IsNull());
5057   CONVERT_ARG_HANDLE_CHECKED(Name, name, 1);
5058   CONVERT_ARG_HANDLE_CHECKED(Object, getter, 2);
5059   RUNTIME_ASSERT(IsValidAccessor(getter));
5060   CONVERT_ARG_HANDLE_CHECKED(Object, setter, 3);
5061   RUNTIME_ASSERT(IsValidAccessor(setter));
5062   CONVERT_SMI_ARG_CHECKED(unchecked, 4);
5063   RUNTIME_ASSERT((unchecked & ~(READ_ONLY | DONT_ENUM | DONT_DELETE)) == 0);
5064   PropertyAttributes attr = static_cast<PropertyAttributes>(unchecked);
5065
5066   bool fast = obj->HasFastProperties();
5067   RETURN_FAILURE_ON_EXCEPTION(
5068       isolate, JSObject::DefineAccessor(obj, name, getter, setter, attr));
5069   if (fast) JSObject::MigrateSlowToFast(obj, 0);
5070   return isolate->heap()->undefined_value();
5071 }
5072
5073
5074 // Implements part of 8.12.9 DefineOwnProperty.
5075 // There are 3 cases that lead here:
5076 // Step 4a - define a new data property.
5077 // Steps 9b & 12 - replace an existing accessor property with a data property.
5078 // Step 12 - update an existing data property with a data or generic
5079 //           descriptor.
5080 RUNTIME_FUNCTION(Runtime_DefineDataPropertyUnchecked) {
5081   HandleScope scope(isolate);
5082   DCHECK(args.length() == 4);
5083   CONVERT_ARG_HANDLE_CHECKED(JSObject, js_object, 0);
5084   CONVERT_ARG_HANDLE_CHECKED(Name, name, 1);
5085   CONVERT_ARG_HANDLE_CHECKED(Object, obj_value, 2);
5086   CONVERT_SMI_ARG_CHECKED(unchecked, 3);
5087   RUNTIME_ASSERT((unchecked & ~(READ_ONLY | DONT_ENUM | DONT_DELETE)) == 0);
5088   PropertyAttributes attr = static_cast<PropertyAttributes>(unchecked);
5089
5090   LookupIterator it(js_object, name, LookupIterator::OWN_SKIP_INTERCEPTOR);
5091   if (it.IsFound() && it.state() == LookupIterator::ACCESS_CHECK) {
5092     if (!isolate->MayNamedAccess(js_object, name, v8::ACCESS_SET)) {
5093       return isolate->heap()->undefined_value();
5094     }
5095     it.Next();
5096   }
5097
5098   // Take special care when attributes are different and there is already
5099   // a property.
5100   if (it.state() == LookupIterator::ACCESSOR) {
5101     // Use IgnoreAttributes version since a readonly property may be
5102     // overridden and SetProperty does not allow this.
5103     Handle<Object> result;
5104     ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
5105         isolate, result,
5106         JSObject::SetOwnPropertyIgnoreAttributes(
5107             js_object, name, obj_value, attr,
5108             JSObject::DONT_FORCE_FIELD));
5109     return *result;
5110   }
5111
5112   Handle<Object> result;
5113   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
5114       isolate, result,
5115       Runtime::DefineObjectProperty(js_object, name, obj_value, attr));
5116   return *result;
5117 }
5118
5119
5120 // Return property without being observable by accessors or interceptors.
5121 RUNTIME_FUNCTION(Runtime_GetDataProperty) {
5122   HandleScope scope(isolate);
5123   DCHECK(args.length() == 2);
5124   CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0);
5125   CONVERT_ARG_HANDLE_CHECKED(Name, key, 1);
5126   return *JSObject::GetDataProperty(object, key);
5127 }
5128
5129
5130 MaybeHandle<Object> Runtime::SetObjectProperty(Isolate* isolate,
5131                                                Handle<Object> object,
5132                                                Handle<Object> key,
5133                                                Handle<Object> value,
5134                                                StrictMode strict_mode) {
5135   if (object->IsUndefined() || object->IsNull()) {
5136     Handle<Object> args[2] = { key, object };
5137     THROW_NEW_ERROR(isolate, NewTypeError("non_object_property_store",
5138                                           HandleVector(args, 2)),
5139                     Object);
5140   }
5141
5142   if (object->IsJSProxy()) {
5143     Handle<Object> name_object;
5144     if (key->IsSymbol()) {
5145       name_object = key;
5146     } else {
5147       ASSIGN_RETURN_ON_EXCEPTION(
5148           isolate, name_object, Execution::ToString(isolate, key), Object);
5149     }
5150     Handle<Name> name = Handle<Name>::cast(name_object);
5151     return Object::SetProperty(Handle<JSProxy>::cast(object), name, value,
5152                                strict_mode);
5153   }
5154
5155   // Check if the given key is an array index.
5156   uint32_t index;
5157   if (key->ToArrayIndex(&index)) {
5158     // TODO(verwaest): Support non-JSObject receivers.
5159     if (!object->IsJSObject()) return value;
5160     Handle<JSObject> js_object = Handle<JSObject>::cast(object);
5161
5162     // In Firefox/SpiderMonkey, Safari and Opera you can access the characters
5163     // of a string using [] notation.  We need to support this too in
5164     // JavaScript.
5165     // In the case of a String object we just need to redirect the assignment to
5166     // the underlying string if the index is in range.  Since the underlying
5167     // string does nothing with the assignment then we can ignore such
5168     // assignments.
5169     if (js_object->IsStringObjectWithCharacterAt(index)) {
5170       return value;
5171     }
5172
5173     JSObject::ValidateElements(js_object);
5174     if (js_object->HasExternalArrayElements() ||
5175         js_object->HasFixedTypedArrayElements()) {
5176       if (!value->IsNumber() &&  !value->IsFloat32x4() &&
5177           !value->IsFloat64x2() && !value->IsInt32x4() &&
5178           !value->IsUndefined()) {
5179         ASSIGN_RETURN_ON_EXCEPTION(
5180             isolate, value, Execution::ToNumber(isolate, value), Object);
5181       }
5182     }
5183
5184     MaybeHandle<Object> result = JSObject::SetElement(
5185         js_object, index, value, NONE, strict_mode, true, SET_PROPERTY);
5186     JSObject::ValidateElements(js_object);
5187
5188     return result.is_null() ? result : value;
5189   }
5190
5191   if (key->IsName()) {
5192     Handle<Name> name = Handle<Name>::cast(key);
5193     if (name->AsArrayIndex(&index)) {
5194       // TODO(verwaest): Support non-JSObject receivers.
5195       if (!object->IsJSObject()) return value;
5196       Handle<JSObject> js_object = Handle<JSObject>::cast(object);
5197       if (js_object->HasExternalArrayElements()) {
5198         if (!value->IsNumber() &&  !value->IsFloat32x4() &&
5199             !value->IsFloat64x2() && !value->IsInt32x4() &&
5200             !value->IsUndefined()) {
5201           ASSIGN_RETURN_ON_EXCEPTION(
5202               isolate, value, Execution::ToNumber(isolate, value), Object);
5203         }
5204       }
5205       return JSObject::SetElement(js_object, index, value, NONE, strict_mode,
5206                                   true, SET_PROPERTY);
5207     } else {
5208       if (name->IsString()) name = String::Flatten(Handle<String>::cast(name));
5209       return Object::SetProperty(object, name, value, strict_mode);
5210     }
5211   }
5212
5213   // Call-back into JavaScript to convert the key to a string.
5214   Handle<Object> converted;
5215   ASSIGN_RETURN_ON_EXCEPTION(
5216       isolate, converted, Execution::ToString(isolate, key), Object);
5217   Handle<String> name = Handle<String>::cast(converted);
5218
5219   if (name->AsArrayIndex(&index)) {
5220     // TODO(verwaest): Support non-JSObject receivers.
5221     if (!object->IsJSObject()) return value;
5222     Handle<JSObject> js_object = Handle<JSObject>::cast(object);
5223     return JSObject::SetElement(js_object, index, value, NONE, strict_mode,
5224                                 true, SET_PROPERTY);
5225   }
5226   return Object::SetProperty(object, name, value, strict_mode);
5227 }
5228
5229
5230 MaybeHandle<Object> Runtime::DefineObjectProperty(Handle<JSObject> js_object,
5231                                                   Handle<Object> key,
5232                                                   Handle<Object> value,
5233                                                   PropertyAttributes attr) {
5234   Isolate* isolate = js_object->GetIsolate();
5235   // Check if the given key is an array index.
5236   uint32_t index;
5237   if (key->ToArrayIndex(&index)) {
5238     // In Firefox/SpiderMonkey, Safari and Opera you can access the characters
5239     // of a string using [] notation.  We need to support this too in
5240     // JavaScript.
5241     // In the case of a String object we just need to redirect the assignment to
5242     // the underlying string if the index is in range.  Since the underlying
5243     // string does nothing with the assignment then we can ignore such
5244     // assignments.
5245     if (js_object->IsStringObjectWithCharacterAt(index)) {
5246       return value;
5247     }
5248
5249     return JSObject::SetElement(js_object, index, value, attr,
5250                                 SLOPPY, false, DEFINE_PROPERTY);
5251   }
5252
5253   if (key->IsName()) {
5254     Handle<Name> name = Handle<Name>::cast(key);
5255     if (name->AsArrayIndex(&index)) {
5256       return JSObject::SetElement(js_object, index, value, attr,
5257                                   SLOPPY, false, DEFINE_PROPERTY);
5258     } else {
5259       if (name->IsString()) name = String::Flatten(Handle<String>::cast(name));
5260       return JSObject::SetOwnPropertyIgnoreAttributes(js_object, name, value,
5261                                                       attr);
5262     }
5263   }
5264
5265   // Call-back into JavaScript to convert the key to a string.
5266   Handle<Object> converted;
5267   ASSIGN_RETURN_ON_EXCEPTION(
5268       isolate, converted, Execution::ToString(isolate, key), Object);
5269   Handle<String> name = Handle<String>::cast(converted);
5270
5271   if (name->AsArrayIndex(&index)) {
5272     return JSObject::SetElement(js_object, index, value, attr,
5273                                 SLOPPY, false, DEFINE_PROPERTY);
5274   } else {
5275     return JSObject::SetOwnPropertyIgnoreAttributes(js_object, name, value,
5276                                                     attr);
5277   }
5278 }
5279
5280
5281 MaybeHandle<Object> Runtime::DeleteObjectProperty(Isolate* isolate,
5282                                                   Handle<JSReceiver> receiver,
5283                                                   Handle<Object> key,
5284                                                   JSReceiver::DeleteMode mode) {
5285   // Check if the given key is an array index.
5286   uint32_t index;
5287   if (key->ToArrayIndex(&index)) {
5288     // In Firefox/SpiderMonkey, Safari and Opera you can access the
5289     // characters of a string using [] notation.  In the case of a
5290     // String object we just need to redirect the deletion to the
5291     // underlying string if the index is in range.  Since the
5292     // underlying string does nothing with the deletion, we can ignore
5293     // such deletions.
5294     if (receiver->IsStringObjectWithCharacterAt(index)) {
5295       return isolate->factory()->true_value();
5296     }
5297
5298     return JSReceiver::DeleteElement(receiver, index, mode);
5299   }
5300
5301   Handle<Name> name;
5302   if (key->IsName()) {
5303     name = Handle<Name>::cast(key);
5304   } else {
5305     // Call-back into JavaScript to convert the key to a string.
5306     Handle<Object> converted;
5307     ASSIGN_RETURN_ON_EXCEPTION(
5308         isolate, converted, Execution::ToString(isolate, key), Object);
5309     name = Handle<String>::cast(converted);
5310   }
5311
5312   if (name->IsString()) name = String::Flatten(Handle<String>::cast(name));
5313   return JSReceiver::DeleteProperty(receiver, name, mode);
5314 }
5315
5316
5317 RUNTIME_FUNCTION(Runtime_SetHiddenProperty) {
5318   HandleScope scope(isolate);
5319   RUNTIME_ASSERT(args.length() == 3);
5320
5321   CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0);
5322   CONVERT_ARG_HANDLE_CHECKED(String, key, 1);
5323   CONVERT_ARG_HANDLE_CHECKED(Object, value, 2);
5324   RUNTIME_ASSERT(key->IsUniqueName());
5325   return *JSObject::SetHiddenProperty(object, key, value);
5326 }
5327
5328
5329 RUNTIME_FUNCTION(Runtime_AddNamedProperty) {
5330   HandleScope scope(isolate);
5331   RUNTIME_ASSERT(args.length() == 4);
5332
5333   CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0);
5334   CONVERT_ARG_HANDLE_CHECKED(Name, key, 1);
5335   CONVERT_ARG_HANDLE_CHECKED(Object, value, 2);
5336   CONVERT_SMI_ARG_CHECKED(unchecked_attributes, 3);
5337   RUNTIME_ASSERT(
5338       (unchecked_attributes & ~(READ_ONLY | DONT_ENUM | DONT_DELETE)) == 0);
5339   // Compute attributes.
5340   PropertyAttributes attributes =
5341       static_cast<PropertyAttributes>(unchecked_attributes);
5342
5343 #ifdef DEBUG
5344   uint32_t index = 0;
5345   DCHECK(!key->ToArrayIndex(&index));
5346   LookupIterator it(object, key, LookupIterator::OWN_SKIP_INTERCEPTOR);
5347   Maybe<PropertyAttributes> maybe = JSReceiver::GetPropertyAttributes(&it);
5348   if (!maybe.has_value) return isolate->heap()->exception();
5349   RUNTIME_ASSERT(!it.IsFound());
5350 #endif
5351
5352   Handle<Object> result;
5353   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
5354       isolate, result,
5355       JSObject::SetOwnPropertyIgnoreAttributes(object, key, value, attributes));
5356   return *result;
5357 }
5358
5359
5360 RUNTIME_FUNCTION(Runtime_AddPropertyForTemplate) {
5361   HandleScope scope(isolate);
5362   RUNTIME_ASSERT(args.length() == 4);
5363
5364   CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0);
5365   CONVERT_ARG_HANDLE_CHECKED(Object, key, 1);
5366   CONVERT_ARG_HANDLE_CHECKED(Object, value, 2);
5367   CONVERT_SMI_ARG_CHECKED(unchecked_attributes, 3);
5368   RUNTIME_ASSERT(
5369       (unchecked_attributes & ~(READ_ONLY | DONT_ENUM | DONT_DELETE)) == 0);
5370   // Compute attributes.
5371   PropertyAttributes attributes =
5372       static_cast<PropertyAttributes>(unchecked_attributes);
5373
5374 #ifdef DEBUG
5375   bool duplicate;
5376   if (key->IsName()) {
5377     LookupIterator it(object, Handle<Name>::cast(key),
5378                       LookupIterator::OWN_SKIP_INTERCEPTOR);
5379     Maybe<PropertyAttributes> maybe = JSReceiver::GetPropertyAttributes(&it);
5380     DCHECK(maybe.has_value);
5381     duplicate = it.IsFound();
5382   } else {
5383     uint32_t index = 0;
5384     RUNTIME_ASSERT(key->ToArrayIndex(&index));
5385     Maybe<bool> maybe = JSReceiver::HasOwnElement(object, index);
5386     if (!maybe.has_value) return isolate->heap()->exception();
5387     duplicate = maybe.value;
5388   }
5389   if (duplicate) {
5390     Handle<Object> args[1] = { key };
5391     THROW_NEW_ERROR_RETURN_FAILURE(
5392         isolate,
5393         NewTypeError("duplicate_template_property", HandleVector(args, 1)));
5394   }
5395 #endif
5396
5397   Handle<Object> result;
5398   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
5399       isolate, result,
5400       Runtime::DefineObjectProperty(object, key, value, attributes));
5401   return *result;
5402 }
5403
5404
5405 RUNTIME_FUNCTION(Runtime_SetProperty) {
5406   HandleScope scope(isolate);
5407   RUNTIME_ASSERT(args.length() == 4);
5408
5409   CONVERT_ARG_HANDLE_CHECKED(Object, object, 0);
5410   CONVERT_ARG_HANDLE_CHECKED(Object, key, 1);
5411   CONVERT_ARG_HANDLE_CHECKED(Object, value, 2);
5412   CONVERT_STRICT_MODE_ARG_CHECKED(strict_mode_arg, 3);
5413   StrictMode strict_mode = strict_mode_arg;
5414
5415   Handle<Object> result;
5416   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
5417       isolate, result,
5418       Runtime::SetObjectProperty(isolate, object, key, value, strict_mode));
5419   return *result;
5420 }
5421
5422
5423 // Adds an element to an array.
5424 // This is used to create an indexed data property into an array.
5425 RUNTIME_FUNCTION(Runtime_AddElement) {
5426   HandleScope scope(isolate);
5427   RUNTIME_ASSERT(args.length() == 4);
5428
5429   CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0);
5430   CONVERT_ARG_HANDLE_CHECKED(Object, key, 1);
5431   CONVERT_ARG_HANDLE_CHECKED(Object, value, 2);
5432   CONVERT_SMI_ARG_CHECKED(unchecked_attributes, 3);
5433   RUNTIME_ASSERT(
5434       (unchecked_attributes & ~(READ_ONLY | DONT_ENUM | DONT_DELETE)) == 0);
5435   // Compute attributes.
5436   PropertyAttributes attributes =
5437       static_cast<PropertyAttributes>(unchecked_attributes);
5438
5439   uint32_t index = 0;
5440   key->ToArrayIndex(&index);
5441
5442   Handle<Object> result;
5443   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
5444       isolate, result, JSObject::SetElement(object, index, value, attributes,
5445                                             SLOPPY, false, DEFINE_PROPERTY));
5446   return *result;
5447 }
5448
5449
5450 RUNTIME_FUNCTION(Runtime_TransitionElementsKind) {
5451   HandleScope scope(isolate);
5452   RUNTIME_ASSERT(args.length() == 2);
5453   CONVERT_ARG_HANDLE_CHECKED(JSArray, array, 0);
5454   CONVERT_ARG_HANDLE_CHECKED(Map, map, 1);
5455   JSObject::TransitionElementsKind(array, map->elements_kind());
5456   return *array;
5457 }
5458
5459
5460 // Set the native flag on the function.
5461 // This is used to decide if we should transform null and undefined
5462 // into the global object when doing call and apply.
5463 RUNTIME_FUNCTION(Runtime_SetNativeFlag) {
5464   SealHandleScope shs(isolate);
5465   RUNTIME_ASSERT(args.length() == 1);
5466
5467   CONVERT_ARG_CHECKED(Object, object, 0);
5468
5469   if (object->IsJSFunction()) {
5470     JSFunction* func = JSFunction::cast(object);
5471     func->shared()->set_native(true);
5472   }
5473   return isolate->heap()->undefined_value();
5474 }
5475
5476
5477 RUNTIME_FUNCTION(Runtime_SetInlineBuiltinFlag) {
5478   SealHandleScope shs(isolate);
5479   RUNTIME_ASSERT(args.length() == 1);
5480   CONVERT_ARG_HANDLE_CHECKED(Object, object, 0);
5481
5482   if (object->IsJSFunction()) {
5483     JSFunction* func = JSFunction::cast(*object);
5484     func->shared()->set_inline_builtin(true);
5485   }
5486   return isolate->heap()->undefined_value();
5487 }
5488
5489
5490 RUNTIME_FUNCTION(Runtime_StoreArrayLiteralElement) {
5491   HandleScope scope(isolate);
5492   RUNTIME_ASSERT(args.length() == 5);
5493   CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0);
5494   CONVERT_SMI_ARG_CHECKED(store_index, 1);
5495   CONVERT_ARG_HANDLE_CHECKED(Object, value, 2);
5496   CONVERT_ARG_HANDLE_CHECKED(FixedArray, literals, 3);
5497   CONVERT_SMI_ARG_CHECKED(literal_index, 4);
5498
5499   Object* raw_literal_cell = literals->get(literal_index);
5500   JSArray* boilerplate = NULL;
5501   if (raw_literal_cell->IsAllocationSite()) {
5502     AllocationSite* site = AllocationSite::cast(raw_literal_cell);
5503     boilerplate = JSArray::cast(site->transition_info());
5504   } else {
5505     boilerplate = JSArray::cast(raw_literal_cell);
5506   }
5507   Handle<JSArray> boilerplate_object(boilerplate);
5508   ElementsKind elements_kind = object->GetElementsKind();
5509   DCHECK(IsFastElementsKind(elements_kind));
5510   // Smis should never trigger transitions.
5511   DCHECK(!value->IsSmi());
5512
5513   if (value->IsNumber()) {
5514     DCHECK(IsFastSmiElementsKind(elements_kind));
5515     ElementsKind transitioned_kind = IsFastHoleyElementsKind(elements_kind)
5516         ? FAST_HOLEY_DOUBLE_ELEMENTS
5517         : FAST_DOUBLE_ELEMENTS;
5518     if (IsMoreGeneralElementsKindTransition(
5519             boilerplate_object->GetElementsKind(),
5520             transitioned_kind)) {
5521       JSObject::TransitionElementsKind(boilerplate_object, transitioned_kind);
5522     }
5523     JSObject::TransitionElementsKind(object, transitioned_kind);
5524     DCHECK(IsFastDoubleElementsKind(object->GetElementsKind()));
5525     FixedDoubleArray* double_array = FixedDoubleArray::cast(object->elements());
5526     HeapNumber* number = HeapNumber::cast(*value);
5527     double_array->set(store_index, number->Number());
5528   } else {
5529     if (!IsFastObjectElementsKind(elements_kind)) {
5530       ElementsKind transitioned_kind = IsFastHoleyElementsKind(elements_kind)
5531           ? FAST_HOLEY_ELEMENTS
5532           : FAST_ELEMENTS;
5533       JSObject::TransitionElementsKind(object, transitioned_kind);
5534       ElementsKind boilerplate_elements_kind =
5535           boilerplate_object->GetElementsKind();
5536       if (IsMoreGeneralElementsKindTransition(boilerplate_elements_kind,
5537                                               transitioned_kind)) {
5538         JSObject::TransitionElementsKind(boilerplate_object, transitioned_kind);
5539       }
5540     }
5541     FixedArray* object_array = FixedArray::cast(object->elements());
5542     object_array->set(store_index, *value);
5543   }
5544   return *object;
5545 }
5546
5547
5548 // Check whether debugger and is about to step into the callback that is passed
5549 // to a built-in function such as Array.forEach.
5550 RUNTIME_FUNCTION(Runtime_DebugCallbackSupportsStepping) {
5551   DCHECK(args.length() == 1);
5552   if (!isolate->debug()->is_active() || !isolate->debug()->StepInActive()) {
5553     return isolate->heap()->false_value();
5554   }
5555   CONVERT_ARG_CHECKED(Object, callback, 0);
5556   // We do not step into the callback if it's a builtin or not even a function.
5557   return isolate->heap()->ToBoolean(
5558       callback->IsJSFunction() && !JSFunction::cast(callback)->IsBuiltin());
5559 }
5560
5561
5562 // Set one shot breakpoints for the callback function that is passed to a
5563 // built-in function such as Array.forEach to enable stepping into the callback.
5564 RUNTIME_FUNCTION(Runtime_DebugPrepareStepInIfStepping) {
5565   DCHECK(args.length() == 1);
5566   Debug* debug = isolate->debug();
5567   if (!debug->IsStepping()) return isolate->heap()->undefined_value();
5568
5569   HandleScope scope(isolate);
5570   CONVERT_ARG_HANDLE_CHECKED(Object, object, 0);
5571   RUNTIME_ASSERT(object->IsJSFunction() || object->IsJSGeneratorObject());
5572   Handle<JSFunction> fun;
5573   if (object->IsJSFunction()) {
5574     fun = Handle<JSFunction>::cast(object);
5575   } else {
5576     fun = Handle<JSFunction>(
5577         Handle<JSGeneratorObject>::cast(object)->function(), isolate);
5578   }
5579   // When leaving the function, step out has been activated, but not performed
5580   // if we do not leave the builtin.  To be able to step into the function
5581   // again, we need to clear the step out at this point.
5582   debug->ClearStepOut();
5583   debug->FloodWithOneShot(fun);
5584   return isolate->heap()->undefined_value();
5585 }
5586
5587
5588 RUNTIME_FUNCTION(Runtime_DebugPushPromise) {
5589   DCHECK(args.length() == 1);
5590   HandleScope scope(isolate);
5591   CONVERT_ARG_HANDLE_CHECKED(JSObject, promise, 0);
5592   isolate->PushPromise(promise);
5593   return isolate->heap()->undefined_value();
5594 }
5595
5596
5597 RUNTIME_FUNCTION(Runtime_DebugPopPromise) {
5598   DCHECK(args.length() == 0);
5599   SealHandleScope shs(isolate);
5600   isolate->PopPromise();
5601   return isolate->heap()->undefined_value();
5602 }
5603
5604
5605 RUNTIME_FUNCTION(Runtime_DebugPromiseEvent) {
5606   DCHECK(args.length() == 1);
5607   HandleScope scope(isolate);
5608   CONVERT_ARG_HANDLE_CHECKED(JSObject, data, 0);
5609   isolate->debug()->OnPromiseEvent(data);
5610   return isolate->heap()->undefined_value();
5611 }
5612
5613
5614 RUNTIME_FUNCTION(Runtime_DebugPromiseRejectEvent) {
5615   DCHECK(args.length() == 2);
5616   HandleScope scope(isolate);
5617   CONVERT_ARG_HANDLE_CHECKED(JSObject, promise, 0);
5618   CONVERT_ARG_HANDLE_CHECKED(Object, value, 1);
5619   isolate->debug()->OnPromiseReject(promise, value);
5620   return isolate->heap()->undefined_value();
5621 }
5622
5623
5624 RUNTIME_FUNCTION(Runtime_DebugAsyncTaskEvent) {
5625   DCHECK(args.length() == 1);
5626   HandleScope scope(isolate);
5627   CONVERT_ARG_HANDLE_CHECKED(JSObject, data, 0);
5628   isolate->debug()->OnAsyncTaskEvent(data);
5629   return isolate->heap()->undefined_value();
5630 }
5631
5632
5633 RUNTIME_FUNCTION(Runtime_DeleteProperty) {
5634   HandleScope scope(isolate);
5635   DCHECK(args.length() == 3);
5636   CONVERT_ARG_HANDLE_CHECKED(JSReceiver, object, 0);
5637   CONVERT_ARG_HANDLE_CHECKED(Name, key, 1);
5638   CONVERT_STRICT_MODE_ARG_CHECKED(strict_mode, 2);
5639   JSReceiver::DeleteMode delete_mode = strict_mode == STRICT
5640       ? JSReceiver::STRICT_DELETION : JSReceiver::NORMAL_DELETION;
5641   Handle<Object> result;
5642   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
5643       isolate, result,
5644       JSReceiver::DeleteProperty(object, key, delete_mode));
5645   return *result;
5646 }
5647
5648
5649 static Object* HasOwnPropertyImplementation(Isolate* isolate,
5650                                             Handle<JSObject> object,
5651                                             Handle<Name> key) {
5652   Maybe<bool> maybe = JSReceiver::HasOwnProperty(object, key);
5653   if (!maybe.has_value) return isolate->heap()->exception();
5654   if (maybe.value) return isolate->heap()->true_value();
5655   // Handle hidden prototypes.  If there's a hidden prototype above this thing
5656   // then we have to check it for properties, because they are supposed to
5657   // look like they are on this object.
5658   PrototypeIterator iter(isolate, object);
5659   if (!iter.IsAtEnd() &&
5660       Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter))
5661           ->map()
5662           ->is_hidden_prototype()) {
5663     // TODO(verwaest): The recursion is not necessary for keys that are array
5664     // indices. Removing this.
5665     return HasOwnPropertyImplementation(
5666         isolate, Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter)),
5667         key);
5668   }
5669   RETURN_FAILURE_IF_SCHEDULED_EXCEPTION(isolate);
5670   return isolate->heap()->false_value();
5671 }
5672
5673
5674 RUNTIME_FUNCTION(Runtime_HasOwnProperty) {
5675   HandleScope scope(isolate);
5676   DCHECK(args.length() == 2);
5677   CONVERT_ARG_HANDLE_CHECKED(Object, object, 0)
5678   CONVERT_ARG_HANDLE_CHECKED(Name, key, 1);
5679
5680   uint32_t index;
5681   const bool key_is_array_index = key->AsArrayIndex(&index);
5682
5683   // Only JS objects can have properties.
5684   if (object->IsJSObject()) {
5685     Handle<JSObject> js_obj = Handle<JSObject>::cast(object);
5686     // Fast case: either the key is a real named property or it is not
5687     // an array index and there are no interceptors or hidden
5688     // prototypes.
5689     Maybe<bool> maybe = JSObject::HasRealNamedProperty(js_obj, key);
5690     if (!maybe.has_value) return isolate->heap()->exception();
5691     DCHECK(!isolate->has_pending_exception());
5692     if (maybe.value) {
5693       return isolate->heap()->true_value();
5694     }
5695     Map* map = js_obj->map();
5696     if (!key_is_array_index &&
5697         !map->has_named_interceptor() &&
5698         !HeapObject::cast(map->prototype())->map()->is_hidden_prototype()) {
5699       return isolate->heap()->false_value();
5700     }
5701     // Slow case.
5702     return HasOwnPropertyImplementation(isolate,
5703                                         Handle<JSObject>(js_obj),
5704                                         Handle<Name>(key));
5705   } else if (object->IsString() && key_is_array_index) {
5706     // Well, there is one exception:  Handle [] on strings.
5707     Handle<String> string = Handle<String>::cast(object);
5708     if (index < static_cast<uint32_t>(string->length())) {
5709       return isolate->heap()->true_value();
5710     }
5711   }
5712   return isolate->heap()->false_value();
5713 }
5714
5715
5716 RUNTIME_FUNCTION(Runtime_HasProperty) {
5717   HandleScope scope(isolate);
5718   DCHECK(args.length() == 2);
5719   CONVERT_ARG_HANDLE_CHECKED(JSReceiver, receiver, 0);
5720   CONVERT_ARG_HANDLE_CHECKED(Name, key, 1);
5721
5722   Maybe<bool> maybe = JSReceiver::HasProperty(receiver, key);
5723   if (!maybe.has_value) return isolate->heap()->exception();
5724   return isolate->heap()->ToBoolean(maybe.value);
5725 }
5726
5727
5728 RUNTIME_FUNCTION(Runtime_HasElement) {
5729   HandleScope scope(isolate);
5730   DCHECK(args.length() == 2);
5731   CONVERT_ARG_HANDLE_CHECKED(JSReceiver, receiver, 0);
5732   CONVERT_SMI_ARG_CHECKED(index, 1);
5733
5734   Maybe<bool> maybe = JSReceiver::HasElement(receiver, index);
5735   if (!maybe.has_value) return isolate->heap()->exception();
5736   return isolate->heap()->ToBoolean(maybe.value);
5737 }
5738
5739
5740 RUNTIME_FUNCTION(Runtime_IsPropertyEnumerable) {
5741   HandleScope scope(isolate);
5742   DCHECK(args.length() == 2);
5743
5744   CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0);
5745   CONVERT_ARG_HANDLE_CHECKED(Name, key, 1);
5746
5747   Maybe<PropertyAttributes> maybe =
5748       JSReceiver::GetOwnPropertyAttributes(object, key);
5749   if (!maybe.has_value) return isolate->heap()->exception();
5750   if (maybe.value == ABSENT) maybe.value = DONT_ENUM;
5751   return isolate->heap()->ToBoolean((maybe.value & DONT_ENUM) == 0);
5752 }
5753
5754
5755 RUNTIME_FUNCTION(Runtime_GetPropertyNames) {
5756   HandleScope scope(isolate);
5757   DCHECK(args.length() == 1);
5758   CONVERT_ARG_HANDLE_CHECKED(JSReceiver, object, 0);
5759   Handle<JSArray> result;
5760
5761   isolate->counters()->for_in()->Increment();
5762   Handle<FixedArray> elements;
5763   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
5764       isolate, elements,
5765       JSReceiver::GetKeys(object, JSReceiver::INCLUDE_PROTOS));
5766   return *isolate->factory()->NewJSArrayWithElements(elements);
5767 }
5768
5769
5770 // Returns either a FixedArray as Runtime_GetPropertyNames,
5771 // or, if the given object has an enum cache that contains
5772 // all enumerable properties of the object and its prototypes
5773 // have none, the map of the object. This is used to speed up
5774 // the check for deletions during a for-in.
5775 RUNTIME_FUNCTION(Runtime_GetPropertyNamesFast) {
5776   SealHandleScope shs(isolate);
5777   DCHECK(args.length() == 1);
5778
5779   CONVERT_ARG_CHECKED(JSReceiver, raw_object, 0);
5780
5781   if (raw_object->IsSimpleEnum()) return raw_object->map();
5782
5783   HandleScope scope(isolate);
5784   Handle<JSReceiver> object(raw_object);
5785   Handle<FixedArray> content;
5786   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
5787       isolate, content,
5788       JSReceiver::GetKeys(object, JSReceiver::INCLUDE_PROTOS));
5789
5790   // Test again, since cache may have been built by preceding call.
5791   if (object->IsSimpleEnum()) return object->map();
5792
5793   return *content;
5794 }
5795
5796
5797 // Find the length of the prototype chain that is to be handled as one. If a
5798 // prototype object is hidden it is to be viewed as part of the the object it
5799 // is prototype for.
5800 static int OwnPrototypeChainLength(JSObject* obj) {
5801   int count = 1;
5802   for (PrototypeIterator iter(obj->GetIsolate(), obj);
5803        !iter.IsAtEnd(PrototypeIterator::END_AT_NON_HIDDEN); iter.Advance()) {
5804     count++;
5805   }
5806   return count;
5807 }
5808
5809
5810 // Return the names of the own named properties.
5811 // args[0]: object
5812 // args[1]: PropertyAttributes as int
5813 RUNTIME_FUNCTION(Runtime_GetOwnPropertyNames) {
5814   HandleScope scope(isolate);
5815   DCHECK(args.length() == 2);
5816   if (!args[0]->IsJSObject()) {
5817     return isolate->heap()->undefined_value();
5818   }
5819   CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0);
5820   CONVERT_SMI_ARG_CHECKED(filter_value, 1);
5821   PropertyAttributes filter = static_cast<PropertyAttributes>(filter_value);
5822
5823   // Skip the global proxy as it has no properties and always delegates to the
5824   // real global object.
5825   if (obj->IsJSGlobalProxy()) {
5826     // Only collect names if access is permitted.
5827     if (obj->IsAccessCheckNeeded() &&
5828         !isolate->MayNamedAccess(
5829             obj, isolate->factory()->undefined_value(), v8::ACCESS_KEYS)) {
5830       isolate->ReportFailedAccessCheck(obj, v8::ACCESS_KEYS);
5831       RETURN_FAILURE_IF_SCHEDULED_EXCEPTION(isolate);
5832       return *isolate->factory()->NewJSArray(0);
5833     }
5834     PrototypeIterator iter(isolate, obj);
5835     obj = Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter));
5836   }
5837
5838   // Find the number of objects making up this.
5839   int length = OwnPrototypeChainLength(*obj);
5840
5841   // Find the number of own properties for each of the objects.
5842   ScopedVector<int> own_property_count(length);
5843   int total_property_count = 0;
5844   {
5845     PrototypeIterator iter(isolate, obj, PrototypeIterator::START_AT_RECEIVER);
5846     for (int i = 0; i < length; i++) {
5847       DCHECK(!iter.IsAtEnd());
5848       Handle<JSObject> jsproto =
5849           Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter));
5850       // Only collect names if access is permitted.
5851       if (jsproto->IsAccessCheckNeeded() &&
5852           !isolate->MayNamedAccess(jsproto,
5853                                    isolate->factory()->undefined_value(),
5854                                    v8::ACCESS_KEYS)) {
5855         isolate->ReportFailedAccessCheck(jsproto, v8::ACCESS_KEYS);
5856         RETURN_FAILURE_IF_SCHEDULED_EXCEPTION(isolate);
5857         return *isolate->factory()->NewJSArray(0);
5858       }
5859       int n;
5860       n = jsproto->NumberOfOwnProperties(filter);
5861       own_property_count[i] = n;
5862       total_property_count += n;
5863       iter.Advance();
5864     }
5865   }
5866
5867   // Allocate an array with storage for all the property names.
5868   Handle<FixedArray> names =
5869       isolate->factory()->NewFixedArray(total_property_count);
5870
5871   // Get the property names.
5872   int next_copy_index = 0;
5873   int hidden_strings = 0;
5874   {
5875     PrototypeIterator iter(isolate, obj, PrototypeIterator::START_AT_RECEIVER);
5876     for (int i = 0; i < length; i++) {
5877       DCHECK(!iter.IsAtEnd());
5878       Handle<JSObject> jsproto =
5879           Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter));
5880       jsproto->GetOwnPropertyNames(*names, next_copy_index, filter);
5881       if (i > 0) {
5882         // Names from hidden prototypes may already have been added
5883         // for inherited function template instances. Count the duplicates
5884         // and stub them out; the final copy pass at the end ignores holes.
5885         for (int j = next_copy_index;
5886              j < next_copy_index + own_property_count[i]; j++) {
5887           Object* name_from_hidden_proto = names->get(j);
5888           for (int k = 0; k < next_copy_index; k++) {
5889             if (names->get(k) != isolate->heap()->hidden_string()) {
5890               Object* name = names->get(k);
5891               if (name_from_hidden_proto == name) {
5892                 names->set(j, isolate->heap()->hidden_string());
5893                 hidden_strings++;
5894                 break;
5895               }
5896             }
5897           }
5898         }
5899       }
5900       next_copy_index += own_property_count[i];
5901
5902       // Hidden properties only show up if the filter does not skip strings.
5903       if ((filter & STRING) == 0 && JSObject::HasHiddenProperties(jsproto)) {
5904         hidden_strings++;
5905       }
5906       iter.Advance();
5907     }
5908   }
5909
5910   // Filter out name of hidden properties object and
5911   // hidden prototype duplicates.
5912   if (hidden_strings > 0) {
5913     Handle<FixedArray> old_names = names;
5914     names = isolate->factory()->NewFixedArray(
5915         names->length() - hidden_strings);
5916     int dest_pos = 0;
5917     for (int i = 0; i < total_property_count; i++) {
5918       Object* name = old_names->get(i);
5919       if (name == isolate->heap()->hidden_string()) {
5920         hidden_strings--;
5921         continue;
5922       }
5923       names->set(dest_pos++, name);
5924     }
5925     DCHECK_EQ(0, hidden_strings);
5926   }
5927
5928   return *isolate->factory()->NewJSArrayWithElements(names);
5929 }
5930
5931
5932 // Return the names of the own indexed properties.
5933 // args[0]: object
5934 RUNTIME_FUNCTION(Runtime_GetOwnElementNames) {
5935   HandleScope scope(isolate);
5936   DCHECK(args.length() == 1);
5937   if (!args[0]->IsJSObject()) {
5938     return isolate->heap()->undefined_value();
5939   }
5940   CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0);
5941
5942   int n = obj->NumberOfOwnElements(static_cast<PropertyAttributes>(NONE));
5943   Handle<FixedArray> names = isolate->factory()->NewFixedArray(n);
5944   obj->GetOwnElementKeys(*names, static_cast<PropertyAttributes>(NONE));
5945   return *isolate->factory()->NewJSArrayWithElements(names);
5946 }
5947
5948
5949 // Return information on whether an object has a named or indexed interceptor.
5950 // args[0]: object
5951 RUNTIME_FUNCTION(Runtime_GetInterceptorInfo) {
5952   HandleScope scope(isolate);
5953   DCHECK(args.length() == 1);
5954   if (!args[0]->IsJSObject()) {
5955     return Smi::FromInt(0);
5956   }
5957   CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0);
5958
5959   int result = 0;
5960   if (obj->HasNamedInterceptor()) result |= 2;
5961   if (obj->HasIndexedInterceptor()) result |= 1;
5962
5963   return Smi::FromInt(result);
5964 }
5965
5966
5967 // Return property names from named interceptor.
5968 // args[0]: object
5969 RUNTIME_FUNCTION(Runtime_GetNamedInterceptorPropertyNames) {
5970   HandleScope scope(isolate);
5971   DCHECK(args.length() == 1);
5972   CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0);
5973
5974   if (obj->HasNamedInterceptor()) {
5975     Handle<JSObject> result;
5976     if (JSObject::GetKeysForNamedInterceptor(obj, obj).ToHandle(&result)) {
5977       return *result;
5978     }
5979   }
5980   return isolate->heap()->undefined_value();
5981 }
5982
5983
5984 // Return element names from indexed interceptor.
5985 // args[0]: object
5986 RUNTIME_FUNCTION(Runtime_GetIndexedInterceptorElementNames) {
5987   HandleScope scope(isolate);
5988   DCHECK(args.length() == 1);
5989   CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0);
5990
5991   if (obj->HasIndexedInterceptor()) {
5992     Handle<JSObject> result;
5993     if (JSObject::GetKeysForIndexedInterceptor(obj, obj).ToHandle(&result)) {
5994       return *result;
5995     }
5996   }
5997   return isolate->heap()->undefined_value();
5998 }
5999
6000
6001 RUNTIME_FUNCTION(Runtime_OwnKeys) {
6002   HandleScope scope(isolate);
6003   DCHECK(args.length() == 1);
6004   CONVERT_ARG_CHECKED(JSObject, raw_object, 0);
6005   Handle<JSObject> object(raw_object);
6006
6007   if (object->IsJSGlobalProxy()) {
6008     // Do access checks before going to the global object.
6009     if (object->IsAccessCheckNeeded() &&
6010         !isolate->MayNamedAccess(
6011             object, isolate->factory()->undefined_value(), v8::ACCESS_KEYS)) {
6012       isolate->ReportFailedAccessCheck(object, v8::ACCESS_KEYS);
6013       RETURN_FAILURE_IF_SCHEDULED_EXCEPTION(isolate);
6014       return *isolate->factory()->NewJSArray(0);
6015     }
6016
6017     PrototypeIterator iter(isolate, object);
6018     // If proxy is detached we simply return an empty array.
6019     if (iter.IsAtEnd()) return *isolate->factory()->NewJSArray(0);
6020     object = Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter));
6021   }
6022
6023   Handle<FixedArray> contents;
6024   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
6025       isolate, contents,
6026       JSReceiver::GetKeys(object, JSReceiver::OWN_ONLY));
6027
6028   // Some fast paths through GetKeysInFixedArrayFor reuse a cached
6029   // property array and since the result is mutable we have to create
6030   // a fresh clone on each invocation.
6031   int length = contents->length();
6032   Handle<FixedArray> copy = isolate->factory()->NewFixedArray(length);
6033   for (int i = 0; i < length; i++) {
6034     Object* entry = contents->get(i);
6035     if (entry->IsString()) {
6036       copy->set(i, entry);
6037     } else {
6038       DCHECK(entry->IsNumber());
6039       HandleScope scope(isolate);
6040       Handle<Object> entry_handle(entry, isolate);
6041       Handle<Object> entry_str =
6042           isolate->factory()->NumberToString(entry_handle);
6043       copy->set(i, *entry_str);
6044     }
6045   }
6046   return *isolate->factory()->NewJSArrayWithElements(copy);
6047 }
6048
6049
6050 RUNTIME_FUNCTION(Runtime_GetArgumentsProperty) {
6051   SealHandleScope shs(isolate);
6052   DCHECK(args.length() == 1);
6053   CONVERT_ARG_HANDLE_CHECKED(Object, raw_key, 0);
6054
6055   // Compute the frame holding the arguments.
6056   JavaScriptFrameIterator it(isolate);
6057   it.AdvanceToArgumentsFrame();
6058   JavaScriptFrame* frame = it.frame();
6059
6060   // Get the actual number of provided arguments.
6061   const uint32_t n = frame->ComputeParametersCount();
6062
6063   // Try to convert the key to an index. If successful and within
6064   // index return the the argument from the frame.
6065   uint32_t index;
6066   if (raw_key->ToArrayIndex(&index) && index < n) {
6067     return frame->GetParameter(index);
6068   }
6069
6070   HandleScope scope(isolate);
6071   if (raw_key->IsSymbol()) {
6072     Handle<Symbol> symbol = Handle<Symbol>::cast(raw_key);
6073     if (symbol->Equals(isolate->native_context()->iterator_symbol())) {
6074       return isolate->native_context()->array_values_iterator();
6075     }
6076     // Lookup in the initial Object.prototype object.
6077     Handle<Object> result;
6078     ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
6079         isolate, result,
6080         Object::GetProperty(isolate->initial_object_prototype(),
6081                             Handle<Symbol>::cast(raw_key)));
6082     return *result;
6083   }
6084
6085   // Convert the key to a string.
6086   Handle<Object> converted;
6087   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
6088       isolate, converted, Execution::ToString(isolate, raw_key));
6089   Handle<String> key = Handle<String>::cast(converted);
6090
6091   // Try to convert the string key into an array index.
6092   if (key->AsArrayIndex(&index)) {
6093     if (index < n) {
6094       return frame->GetParameter(index);
6095     } else {
6096       Handle<Object> initial_prototype(isolate->initial_object_prototype());
6097       Handle<Object> result;
6098       ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
6099           isolate, result,
6100           Object::GetElement(isolate, initial_prototype, index));
6101       return *result;
6102     }
6103   }
6104
6105   // Handle special arguments properties.
6106   if (String::Equals(isolate->factory()->length_string(), key)) {
6107     return Smi::FromInt(n);
6108   }
6109   if (String::Equals(isolate->factory()->callee_string(), key)) {
6110     JSFunction* function = frame->function();
6111     if (function->shared()->strict_mode() == STRICT) {
6112       THROW_NEW_ERROR_RETURN_FAILURE(
6113           isolate, NewTypeError("strict_arguments_callee",
6114                                 HandleVector<Object>(NULL, 0)));
6115     }
6116     return function;
6117   }
6118
6119   // Lookup in the initial Object.prototype object.
6120   Handle<Object> result;
6121   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
6122       isolate, result,
6123       Object::GetProperty(isolate->initial_object_prototype(), key));
6124   return *result;
6125 }
6126
6127
6128 RUNTIME_FUNCTION(Runtime_ToFastProperties) {
6129   HandleScope scope(isolate);
6130   DCHECK(args.length() == 1);
6131   CONVERT_ARG_HANDLE_CHECKED(Object, object, 0);
6132   if (object->IsJSObject() && !object->IsGlobalObject()) {
6133     JSObject::MigrateSlowToFast(Handle<JSObject>::cast(object), 0);
6134   }
6135   return *object;
6136 }
6137
6138
6139 RUNTIME_FUNCTION(Runtime_ToBool) {
6140   SealHandleScope shs(isolate);
6141   DCHECK(args.length() == 1);
6142   CONVERT_ARG_CHECKED(Object, object, 0);
6143
6144   return isolate->heap()->ToBoolean(object->BooleanValue());
6145 }
6146
6147
6148 // Returns the type string of a value; see ECMA-262, 11.4.3 (p 47).
6149 // Possible optimizations: put the type string into the oddballs.
6150 RUNTIME_FUNCTION(Runtime_Typeof) {
6151   SealHandleScope shs(isolate);
6152   DCHECK(args.length() == 1);
6153   CONVERT_ARG_CHECKED(Object, obj, 0);
6154   if (obj->IsNumber()) return isolate->heap()->number_string();
6155   HeapObject* heap_obj = HeapObject::cast(obj);
6156
6157   // typeof an undetectable object is 'undefined'
6158   if (heap_obj->map()->is_undetectable()) {
6159     return isolate->heap()->undefined_string();
6160   }
6161
6162   InstanceType instance_type = heap_obj->map()->instance_type();
6163   if (instance_type < FIRST_NONSTRING_TYPE) {
6164     return isolate->heap()->string_string();
6165   }
6166
6167   switch (instance_type) {
6168     case ODDBALL_TYPE:
6169       if (heap_obj->IsTrue() || heap_obj->IsFalse()) {
6170         return isolate->heap()->boolean_string();
6171       }
6172       if (heap_obj->IsNull()) {
6173         return isolate->heap()->object_string();
6174       }
6175       DCHECK(heap_obj->IsUndefined());
6176       return isolate->heap()->undefined_string();
6177     case SYMBOL_TYPE:
6178       return isolate->heap()->symbol_string();
6179     case JS_FUNCTION_TYPE:
6180     case JS_FUNCTION_PROXY_TYPE:
6181       return isolate->heap()->function_string();
6182     default:
6183       // For any kind of object not handled above, the spec rule for
6184       // host objects gives that it is okay to return "object"
6185       return isolate->heap()->object_string();
6186   }
6187 }
6188
6189
6190 RUNTIME_FUNCTION(Runtime_Booleanize) {
6191   SealHandleScope shs(isolate);
6192   DCHECK(args.length() == 2);
6193   CONVERT_ARG_CHECKED(Object, value_raw, 0);
6194   CONVERT_SMI_ARG_CHECKED(token_raw, 1);
6195   intptr_t value = reinterpret_cast<intptr_t>(value_raw);
6196   Token::Value token = static_cast<Token::Value>(token_raw);
6197   switch (token) {
6198     case Token::EQ:
6199     case Token::EQ_STRICT:
6200       return isolate->heap()->ToBoolean(value == 0);
6201     case Token::NE:
6202     case Token::NE_STRICT:
6203       return isolate->heap()->ToBoolean(value != 0);
6204     case Token::LT:
6205       return isolate->heap()->ToBoolean(value < 0);
6206     case Token::GT:
6207       return isolate->heap()->ToBoolean(value > 0);
6208     case Token::LTE:
6209       return isolate->heap()->ToBoolean(value <= 0);
6210     case Token::GTE:
6211       return isolate->heap()->ToBoolean(value >= 0);
6212     default:
6213       // This should only happen during natives fuzzing.
6214       return isolate->heap()->undefined_value();
6215   }
6216 }
6217
6218
6219 static bool AreDigits(const uint8_t*s, int from, int to) {
6220   for (int i = from; i < to; i++) {
6221     if (s[i] < '0' || s[i] > '9') return false;
6222   }
6223
6224   return true;
6225 }
6226
6227
6228 static int ParseDecimalInteger(const uint8_t*s, int from, int to) {
6229   DCHECK(to - from < 10);  // Overflow is not possible.
6230   DCHECK(from < to);
6231   int d = s[from] - '0';
6232
6233   for (int i = from + 1; i < to; i++) {
6234     d = 10 * d + (s[i] - '0');
6235   }
6236
6237   return d;
6238 }
6239
6240
6241 RUNTIME_FUNCTION(Runtime_StringToNumber) {
6242   HandleScope handle_scope(isolate);
6243   DCHECK(args.length() == 1);
6244   CONVERT_ARG_HANDLE_CHECKED(String, subject, 0);
6245   subject = String::Flatten(subject);
6246
6247   // Fast case: short integer or some sorts of junk values.
6248   if (subject->IsSeqOneByteString()) {
6249     int len = subject->length();
6250     if (len == 0) return Smi::FromInt(0);
6251
6252     DisallowHeapAllocation no_gc;
6253     uint8_t const* data = Handle<SeqOneByteString>::cast(subject)->GetChars();
6254     bool minus = (data[0] == '-');
6255     int start_pos = (minus ? 1 : 0);
6256
6257     if (start_pos == len) {
6258       return isolate->heap()->nan_value();
6259     } else if (data[start_pos] > '9') {
6260       // Fast check for a junk value. A valid string may start from a
6261       // whitespace, a sign ('+' or '-'), the decimal point, a decimal digit
6262       // or the 'I' character ('Infinity'). All of that have codes not greater
6263       // than '9' except 'I' and &nbsp;.
6264       if (data[start_pos] != 'I' && data[start_pos] != 0xa0) {
6265         return isolate->heap()->nan_value();
6266       }
6267     } else if (len - start_pos < 10 && AreDigits(data, start_pos, len)) {
6268       // The maximal/minimal smi has 10 digits. If the string has less digits
6269       // we know it will fit into the smi-data type.
6270       int d = ParseDecimalInteger(data, start_pos, len);
6271       if (minus) {
6272         if (d == 0) return isolate->heap()->minus_zero_value();
6273         d = -d;
6274       } else if (!subject->HasHashCode() &&
6275                  len <= String::kMaxArrayIndexSize &&
6276                  (len == 1 || data[0] != '0')) {
6277         // String hash is not calculated yet but all the data are present.
6278         // Update the hash field to speed up sequential convertions.
6279         uint32_t hash = StringHasher::MakeArrayIndexHash(d, len);
6280 #ifdef DEBUG
6281         subject->Hash();  // Force hash calculation.
6282         DCHECK_EQ(static_cast<int>(subject->hash_field()),
6283                   static_cast<int>(hash));
6284 #endif
6285         subject->set_hash_field(hash);
6286       }
6287       return Smi::FromInt(d);
6288     }
6289   }
6290
6291   // Slower case.
6292   int flags = ALLOW_HEX;
6293   if (FLAG_harmony_numeric_literals) {
6294     // The current spec draft has not updated "ToNumber Applied to the String
6295     // Type", https://bugs.ecmascript.org/show_bug.cgi?id=1584
6296     flags |= ALLOW_OCTAL | ALLOW_BINARY;
6297   }
6298
6299   return *isolate->factory()->NewNumber(StringToDouble(
6300       isolate->unicode_cache(), *subject, flags));
6301 }
6302
6303
6304 RUNTIME_FUNCTION(Runtime_NewString) {
6305   HandleScope scope(isolate);
6306   DCHECK(args.length() == 2);
6307   CONVERT_INT32_ARG_CHECKED(length, 0);
6308   CONVERT_BOOLEAN_ARG_CHECKED(is_one_byte, 1);
6309   if (length == 0) return isolate->heap()->empty_string();
6310   Handle<String> result;
6311   if (is_one_byte) {
6312     ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
6313         isolate, result, isolate->factory()->NewRawOneByteString(length));
6314   } else {
6315     ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
6316         isolate, result, isolate->factory()->NewRawTwoByteString(length));
6317   }
6318   return *result;
6319 }
6320
6321
6322 RUNTIME_FUNCTION(Runtime_TruncateString) {
6323   HandleScope scope(isolate);
6324   DCHECK(args.length() == 2);
6325   CONVERT_ARG_HANDLE_CHECKED(SeqString, string, 0);
6326   CONVERT_INT32_ARG_CHECKED(new_length, 1);
6327   RUNTIME_ASSERT(new_length >= 0);
6328   return *SeqString::Truncate(string, new_length);
6329 }
6330
6331
6332 RUNTIME_FUNCTION(Runtime_URIEscape) {
6333   HandleScope scope(isolate);
6334   DCHECK(args.length() == 1);
6335   CONVERT_ARG_HANDLE_CHECKED(String, source, 0);
6336   Handle<String> string = String::Flatten(source);
6337   DCHECK(string->IsFlat());
6338   Handle<String> result;
6339   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
6340       isolate, result,
6341       string->IsOneByteRepresentationUnderneath()
6342             ? URIEscape::Escape<uint8_t>(isolate, source)
6343             : URIEscape::Escape<uc16>(isolate, source));
6344   return *result;
6345 }
6346
6347
6348 RUNTIME_FUNCTION(Runtime_URIUnescape) {
6349   HandleScope scope(isolate);
6350   DCHECK(args.length() == 1);
6351   CONVERT_ARG_HANDLE_CHECKED(String, source, 0);
6352   Handle<String> string = String::Flatten(source);
6353   DCHECK(string->IsFlat());
6354   Handle<String> result;
6355   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
6356       isolate, result,
6357       string->IsOneByteRepresentationUnderneath()
6358             ? URIUnescape::Unescape<uint8_t>(isolate, source)
6359             : URIUnescape::Unescape<uc16>(isolate, source));
6360   return *result;
6361 }
6362
6363
6364 RUNTIME_FUNCTION(Runtime_QuoteJSONString) {
6365   HandleScope scope(isolate);
6366   CONVERT_ARG_HANDLE_CHECKED(String, string, 0);
6367   DCHECK(args.length() == 1);
6368   Handle<Object> result;
6369   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
6370       isolate, result, BasicJsonStringifier::StringifyString(isolate, string));
6371   return *result;
6372 }
6373
6374
6375 RUNTIME_FUNCTION(Runtime_BasicJSONStringify) {
6376   HandleScope scope(isolate);
6377   DCHECK(args.length() == 1);
6378   CONVERT_ARG_HANDLE_CHECKED(Object, object, 0);
6379   BasicJsonStringifier stringifier(isolate);
6380   Handle<Object> result;
6381   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
6382       isolate, result, stringifier.Stringify(object));
6383   return *result;
6384 }
6385
6386
6387 RUNTIME_FUNCTION(Runtime_StringParseInt) {
6388   HandleScope handle_scope(isolate);
6389   DCHECK(args.length() == 2);
6390   CONVERT_ARG_HANDLE_CHECKED(String, subject, 0);
6391   CONVERT_NUMBER_CHECKED(int, radix, Int32, args[1]);
6392   RUNTIME_ASSERT(radix == 0 || (2 <= radix && radix <= 36));
6393
6394   subject = String::Flatten(subject);
6395   double value;
6396
6397   { DisallowHeapAllocation no_gc;
6398     String::FlatContent flat = subject->GetFlatContent();
6399
6400     // ECMA-262 section 15.1.2.3, empty string is NaN
6401     if (flat.IsOneByte()) {
6402       value = StringToInt(
6403           isolate->unicode_cache(), flat.ToOneByteVector(), radix);
6404     } else {
6405       value = StringToInt(
6406           isolate->unicode_cache(), flat.ToUC16Vector(), radix);
6407     }
6408   }
6409
6410   return *isolate->factory()->NewNumber(value);
6411 }
6412
6413
6414 RUNTIME_FUNCTION(Runtime_StringParseFloat) {
6415   HandleScope shs(isolate);
6416   DCHECK(args.length() == 1);
6417   CONVERT_ARG_HANDLE_CHECKED(String, subject, 0);
6418
6419   subject = String::Flatten(subject);
6420   double value = StringToDouble(isolate->unicode_cache(), *subject,
6421                                 ALLOW_TRAILING_JUNK, base::OS::nan_value());
6422
6423   return *isolate->factory()->NewNumber(value);
6424 }
6425
6426
6427 static inline bool ToUpperOverflows(uc32 character) {
6428   // y with umlauts and the micro sign are the only characters that stop
6429   // fitting into one-byte when converting to uppercase.
6430   static const uc32 yuml_code = 0xff;
6431   static const uc32 micro_code = 0xb5;
6432   return (character == yuml_code || character == micro_code);
6433 }
6434
6435
6436 template <class Converter>
6437 MUST_USE_RESULT static Object* ConvertCaseHelper(
6438     Isolate* isolate,
6439     String* string,
6440     SeqString* result,
6441     int result_length,
6442     unibrow::Mapping<Converter, 128>* mapping) {
6443   DisallowHeapAllocation no_gc;
6444   // We try this twice, once with the assumption that the result is no longer
6445   // than the input and, if that assumption breaks, again with the exact
6446   // length.  This may not be pretty, but it is nicer than what was here before
6447   // and I hereby claim my vaffel-is.
6448   //
6449   // NOTE: This assumes that the upper/lower case of an ASCII
6450   // character is also ASCII.  This is currently the case, but it
6451   // might break in the future if we implement more context and locale
6452   // dependent upper/lower conversions.
6453   bool has_changed_character = false;
6454
6455   // Convert all characters to upper case, assuming that they will fit
6456   // in the buffer
6457   Access<ConsStringIteratorOp> op(
6458       isolate->runtime_state()->string_iterator());
6459   StringCharacterStream stream(string, op.value());
6460   unibrow::uchar chars[Converter::kMaxWidth];
6461   // We can assume that the string is not empty
6462   uc32 current = stream.GetNext();
6463   bool ignore_overflow = Converter::kIsToLower || result->IsSeqTwoByteString();
6464   for (int i = 0; i < result_length;) {
6465     bool has_next = stream.HasMore();
6466     uc32 next = has_next ? stream.GetNext() : 0;
6467     int char_length = mapping->get(current, next, chars);
6468     if (char_length == 0) {
6469       // The case conversion of this character is the character itself.
6470       result->Set(i, current);
6471       i++;
6472     } else if (char_length == 1 &&
6473                (ignore_overflow || !ToUpperOverflows(current))) {
6474       // Common case: converting the letter resulted in one character.
6475       DCHECK(static_cast<uc32>(chars[0]) != current);
6476       result->Set(i, chars[0]);
6477       has_changed_character = true;
6478       i++;
6479     } else if (result_length == string->length()) {
6480       bool overflows = ToUpperOverflows(current);
6481       // We've assumed that the result would be as long as the
6482       // input but here is a character that converts to several
6483       // characters.  No matter, we calculate the exact length
6484       // of the result and try the whole thing again.
6485       //
6486       // Note that this leaves room for optimization.  We could just
6487       // memcpy what we already have to the result string.  Also,
6488       // the result string is the last object allocated we could
6489       // "realloc" it and probably, in the vast majority of cases,
6490       // extend the existing string to be able to hold the full
6491       // result.
6492       int next_length = 0;
6493       if (has_next) {
6494         next_length = mapping->get(next, 0, chars);
6495         if (next_length == 0) next_length = 1;
6496       }
6497       int current_length = i + char_length + next_length;
6498       while (stream.HasMore()) {
6499         current = stream.GetNext();
6500         overflows |= ToUpperOverflows(current);
6501         // NOTE: we use 0 as the next character here because, while
6502         // the next character may affect what a character converts to,
6503         // it does not in any case affect the length of what it convert
6504         // to.
6505         int char_length = mapping->get(current, 0, chars);
6506         if (char_length == 0) char_length = 1;
6507         current_length += char_length;
6508         if (current_length > String::kMaxLength) {
6509           AllowHeapAllocation allocate_error_and_return;
6510           THROW_NEW_ERROR_RETURN_FAILURE(isolate,
6511                                          NewInvalidStringLengthError());
6512         }
6513       }
6514       // Try again with the real length.  Return signed if we need
6515       // to allocate a two-byte string for to uppercase.
6516       return (overflows && !ignore_overflow) ? Smi::FromInt(-current_length)
6517                                              : Smi::FromInt(current_length);
6518     } else {
6519       for (int j = 0; j < char_length; j++) {
6520         result->Set(i, chars[j]);
6521         i++;
6522       }
6523       has_changed_character = true;
6524     }
6525     current = next;
6526   }
6527   if (has_changed_character) {
6528     return result;
6529   } else {
6530     // If we didn't actually change anything in doing the conversion
6531     // we simple return the result and let the converted string
6532     // become garbage; there is no reason to keep two identical strings
6533     // alive.
6534     return string;
6535   }
6536 }
6537
6538
6539 namespace {
6540
6541 static const uintptr_t kOneInEveryByte = kUintptrAllBitsSet / 0xFF;
6542 static const uintptr_t kAsciiMask = kOneInEveryByte << 7;
6543
6544 // Given a word and two range boundaries returns a word with high bit
6545 // set in every byte iff the corresponding input byte was strictly in
6546 // the range (m, n). All the other bits in the result are cleared.
6547 // This function is only useful when it can be inlined and the
6548 // boundaries are statically known.
6549 // Requires: all bytes in the input word and the boundaries must be
6550 // ASCII (less than 0x7F).
6551 static inline uintptr_t AsciiRangeMask(uintptr_t w, char m, char n) {
6552   // Use strict inequalities since in edge cases the function could be
6553   // further simplified.
6554   DCHECK(0 < m && m < n);
6555   // Has high bit set in every w byte less than n.
6556   uintptr_t tmp1 = kOneInEveryByte * (0x7F + n) - w;
6557   // Has high bit set in every w byte greater than m.
6558   uintptr_t tmp2 = w + kOneInEveryByte * (0x7F - m);
6559   return (tmp1 & tmp2 & (kOneInEveryByte * 0x80));
6560 }
6561
6562
6563 #ifdef DEBUG
6564 static bool CheckFastAsciiConvert(char* dst,
6565                                   const char* src,
6566                                   int length,
6567                                   bool changed,
6568                                   bool is_to_lower) {
6569   bool expected_changed = false;
6570   for (int i = 0; i < length; i++) {
6571     if (dst[i] == src[i]) continue;
6572     expected_changed = true;
6573     if (is_to_lower) {
6574       DCHECK('A' <= src[i] && src[i] <= 'Z');
6575       DCHECK(dst[i] == src[i] + ('a' - 'A'));
6576     } else {
6577       DCHECK('a' <= src[i] && src[i] <= 'z');
6578       DCHECK(dst[i] == src[i] - ('a' - 'A'));
6579     }
6580   }
6581   return (expected_changed == changed);
6582 }
6583 #endif
6584
6585
6586 template<class Converter>
6587 static bool FastAsciiConvert(char* dst,
6588                              const char* src,
6589                              int length,
6590                              bool* changed_out) {
6591 #ifdef DEBUG
6592     char* saved_dst = dst;
6593     const char* saved_src = src;
6594 #endif
6595   DisallowHeapAllocation no_gc;
6596   // We rely on the distance between upper and lower case letters
6597   // being a known power of 2.
6598   DCHECK('a' - 'A' == (1 << 5));
6599   // Boundaries for the range of input characters than require conversion.
6600   static const char lo = Converter::kIsToLower ? 'A' - 1 : 'a' - 1;
6601   static const char hi = Converter::kIsToLower ? 'Z' + 1 : 'z' + 1;
6602   bool changed = false;
6603   uintptr_t or_acc = 0;
6604   const char* const limit = src + length;
6605
6606   // dst is newly allocated and always aligned.
6607   DCHECK(IsAligned(reinterpret_cast<intptr_t>(dst), sizeof(uintptr_t)));
6608   // Only attempt processing one word at a time if src is also aligned.
6609   if (IsAligned(reinterpret_cast<intptr_t>(src), sizeof(uintptr_t))) {
6610     // Process the prefix of the input that requires no conversion one aligned
6611     // (machine) word at a time.
6612     while (src <= limit - sizeof(uintptr_t)) {
6613       const uintptr_t w = *reinterpret_cast<const uintptr_t*>(src);
6614       or_acc |= w;
6615       if (AsciiRangeMask(w, lo, hi) != 0) {
6616         changed = true;
6617         break;
6618       }
6619       *reinterpret_cast<uintptr_t*>(dst) = w;
6620       src += sizeof(uintptr_t);
6621       dst += sizeof(uintptr_t);
6622     }
6623     // Process the remainder of the input performing conversion when
6624     // required one word at a time.
6625     while (src <= limit - sizeof(uintptr_t)) {
6626       const uintptr_t w = *reinterpret_cast<const uintptr_t*>(src);
6627       or_acc |= w;
6628       uintptr_t m = AsciiRangeMask(w, lo, hi);
6629       // The mask has high (7th) bit set in every byte that needs
6630       // conversion and we know that the distance between cases is
6631       // 1 << 5.
6632       *reinterpret_cast<uintptr_t*>(dst) = w ^ (m >> 2);
6633       src += sizeof(uintptr_t);
6634       dst += sizeof(uintptr_t);
6635     }
6636   }
6637   // Process the last few bytes of the input (or the whole input if
6638   // unaligned access is not supported).
6639   while (src < limit) {
6640     char c = *src;
6641     or_acc |= c;
6642     if (lo < c && c < hi) {
6643       c ^= (1 << 5);
6644       changed = true;
6645     }
6646     *dst = c;
6647     ++src;
6648     ++dst;
6649   }
6650
6651   if ((or_acc & kAsciiMask) != 0) return false;
6652
6653   DCHECK(CheckFastAsciiConvert(
6654              saved_dst, saved_src, length, changed, Converter::kIsToLower));
6655
6656   *changed_out = changed;
6657   return true;
6658 }
6659
6660 }  // namespace
6661
6662
6663 template <class Converter>
6664 MUST_USE_RESULT static Object* ConvertCase(
6665     Handle<String> s,
6666     Isolate* isolate,
6667     unibrow::Mapping<Converter, 128>* mapping) {
6668   s = String::Flatten(s);
6669   int length = s->length();
6670   // Assume that the string is not empty; we need this assumption later
6671   if (length == 0) return *s;
6672
6673   // Simpler handling of ASCII strings.
6674   //
6675   // NOTE: This assumes that the upper/lower case of an ASCII
6676   // character is also ASCII.  This is currently the case, but it
6677   // might break in the future if we implement more context and locale
6678   // dependent upper/lower conversions.
6679   if (s->IsOneByteRepresentationUnderneath()) {
6680     // Same length as input.
6681     Handle<SeqOneByteString> result =
6682         isolate->factory()->NewRawOneByteString(length).ToHandleChecked();
6683     DisallowHeapAllocation no_gc;
6684     String::FlatContent flat_content = s->GetFlatContent();
6685     DCHECK(flat_content.IsFlat());
6686     bool has_changed_character = false;
6687     bool is_ascii = FastAsciiConvert<Converter>(
6688         reinterpret_cast<char*>(result->GetChars()),
6689         reinterpret_cast<const char*>(flat_content.ToOneByteVector().start()),
6690         length,
6691         &has_changed_character);
6692     // If not ASCII, we discard the result and take the 2 byte path.
6693     if (is_ascii) return has_changed_character ? *result : *s;
6694   }
6695
6696   Handle<SeqString> result;  // Same length as input.
6697   if (s->IsOneByteRepresentation()) {
6698     result = isolate->factory()->NewRawOneByteString(length).ToHandleChecked();
6699   } else {
6700     result = isolate->factory()->NewRawTwoByteString(length).ToHandleChecked();
6701   }
6702
6703   Object* answer = ConvertCaseHelper(isolate, *s, *result, length, mapping);
6704   if (answer->IsException() || answer->IsString()) return answer;
6705
6706   DCHECK(answer->IsSmi());
6707   length = Smi::cast(answer)->value();
6708   if (s->IsOneByteRepresentation() && length > 0) {
6709     ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
6710         isolate, result, isolate->factory()->NewRawOneByteString(length));
6711   } else {
6712     if (length < 0) length = -length;
6713     ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
6714         isolate, result, isolate->factory()->NewRawTwoByteString(length));
6715   }
6716   return ConvertCaseHelper(isolate, *s, *result, length, mapping);
6717 }
6718
6719
6720 RUNTIME_FUNCTION(Runtime_StringToLowerCase) {
6721   HandleScope scope(isolate);
6722   DCHECK(args.length() == 1);
6723   CONVERT_ARG_HANDLE_CHECKED(String, s, 0);
6724   return ConvertCase(
6725       s, isolate, isolate->runtime_state()->to_lower_mapping());
6726 }
6727
6728
6729 RUNTIME_FUNCTION(Runtime_StringToUpperCase) {
6730   HandleScope scope(isolate);
6731   DCHECK(args.length() == 1);
6732   CONVERT_ARG_HANDLE_CHECKED(String, s, 0);
6733   return ConvertCase(
6734       s, isolate, isolate->runtime_state()->to_upper_mapping());
6735 }
6736
6737
6738 RUNTIME_FUNCTION(Runtime_StringTrim) {
6739   HandleScope scope(isolate);
6740   DCHECK(args.length() == 3);
6741
6742   CONVERT_ARG_HANDLE_CHECKED(String, string, 0);
6743   CONVERT_BOOLEAN_ARG_CHECKED(trimLeft, 1);
6744   CONVERT_BOOLEAN_ARG_CHECKED(trimRight, 2);
6745
6746   string = String::Flatten(string);
6747   int length = string->length();
6748
6749   int left = 0;
6750   UnicodeCache* unicode_cache = isolate->unicode_cache();
6751   if (trimLeft) {
6752     while (left < length &&
6753            unicode_cache->IsWhiteSpaceOrLineTerminator(string->Get(left))) {
6754       left++;
6755     }
6756   }
6757
6758   int right = length;
6759   if (trimRight) {
6760     while (right > left &&
6761            unicode_cache->IsWhiteSpaceOrLineTerminator(
6762                string->Get(right - 1))) {
6763       right--;
6764     }
6765   }
6766
6767   return *isolate->factory()->NewSubString(string, left, right);
6768 }
6769
6770
6771 RUNTIME_FUNCTION(Runtime_StringSplit) {
6772   HandleScope handle_scope(isolate);
6773   DCHECK(args.length() == 3);
6774   CONVERT_ARG_HANDLE_CHECKED(String, subject, 0);
6775   CONVERT_ARG_HANDLE_CHECKED(String, pattern, 1);
6776   CONVERT_NUMBER_CHECKED(uint32_t, limit, Uint32, args[2]);
6777   RUNTIME_ASSERT(limit > 0);
6778
6779   int subject_length = subject->length();
6780   int pattern_length = pattern->length();
6781   RUNTIME_ASSERT(pattern_length > 0);
6782
6783   if (limit == 0xffffffffu) {
6784     Handle<Object> cached_answer(
6785         RegExpResultsCache::Lookup(isolate->heap(),
6786                                    *subject,
6787                                    *pattern,
6788                                    RegExpResultsCache::STRING_SPLIT_SUBSTRINGS),
6789         isolate);
6790     if (*cached_answer != Smi::FromInt(0)) {
6791       // The cache FixedArray is a COW-array and can therefore be reused.
6792       Handle<JSArray> result =
6793           isolate->factory()->NewJSArrayWithElements(
6794               Handle<FixedArray>::cast(cached_answer));
6795       return *result;
6796     }
6797   }
6798
6799   // The limit can be very large (0xffffffffu), but since the pattern
6800   // isn't empty, we can never create more parts than ~half the length
6801   // of the subject.
6802
6803   subject = String::Flatten(subject);
6804   pattern = String::Flatten(pattern);
6805
6806   static const int kMaxInitialListCapacity = 16;
6807
6808   ZoneScope zone_scope(isolate->runtime_zone());
6809
6810   // Find (up to limit) indices of separator and end-of-string in subject
6811   int initial_capacity = Min<uint32_t>(kMaxInitialListCapacity, limit);
6812   ZoneList<int> indices(initial_capacity, zone_scope.zone());
6813
6814   FindStringIndicesDispatch(isolate, *subject, *pattern,
6815                             &indices, limit, zone_scope.zone());
6816
6817   if (static_cast<uint32_t>(indices.length()) < limit) {
6818     indices.Add(subject_length, zone_scope.zone());
6819   }
6820
6821   // The list indices now contains the end of each part to create.
6822
6823   // Create JSArray of substrings separated by separator.
6824   int part_count = indices.length();
6825
6826   Handle<JSArray> result = isolate->factory()->NewJSArray(part_count);
6827   JSObject::EnsureCanContainHeapObjectElements(result);
6828   result->set_length(Smi::FromInt(part_count));
6829
6830   DCHECK(result->HasFastObjectElements());
6831
6832   if (part_count == 1 && indices.at(0) == subject_length) {
6833     FixedArray::cast(result->elements())->set(0, *subject);
6834     return *result;
6835   }
6836
6837   Handle<FixedArray> elements(FixedArray::cast(result->elements()));
6838   int part_start = 0;
6839   for (int i = 0; i < part_count; i++) {
6840     HandleScope local_loop_handle(isolate);
6841     int part_end = indices.at(i);
6842     Handle<String> substring =
6843         isolate->factory()->NewProperSubString(subject, part_start, part_end);
6844     elements->set(i, *substring);
6845     part_start = part_end + pattern_length;
6846   }
6847
6848   if (limit == 0xffffffffu) {
6849     if (result->HasFastObjectElements()) {
6850       RegExpResultsCache::Enter(isolate,
6851                                 subject,
6852                                 pattern,
6853                                 elements,
6854                                 RegExpResultsCache::STRING_SPLIT_SUBSTRINGS);
6855     }
6856   }
6857
6858   return *result;
6859 }
6860
6861
6862 // Copies Latin1 characters to the given fixed array looking up
6863 // one-char strings in the cache. Gives up on the first char that is
6864 // not in the cache and fills the remainder with smi zeros. Returns
6865 // the length of the successfully copied prefix.
6866 static int CopyCachedOneByteCharsToArray(Heap* heap, const uint8_t* chars,
6867                                          FixedArray* elements, int length) {
6868   DisallowHeapAllocation no_gc;
6869   FixedArray* one_byte_cache = heap->single_character_string_cache();
6870   Object* undefined = heap->undefined_value();
6871   int i;
6872   WriteBarrierMode mode = elements->GetWriteBarrierMode(no_gc);
6873   for (i = 0; i < length; ++i) {
6874     Object* value = one_byte_cache->get(chars[i]);
6875     if (value == undefined) break;
6876     elements->set(i, value, mode);
6877   }
6878   if (i < length) {
6879     DCHECK(Smi::FromInt(0) == 0);
6880     memset(elements->data_start() + i, 0, kPointerSize * (length - i));
6881   }
6882 #ifdef DEBUG
6883   for (int j = 0; j < length; ++j) {
6884     Object* element = elements->get(j);
6885     DCHECK(element == Smi::FromInt(0) ||
6886            (element->IsString() && String::cast(element)->LooksValid()));
6887   }
6888 #endif
6889   return i;
6890 }
6891
6892
6893 // Converts a String to JSArray.
6894 // For example, "foo" => ["f", "o", "o"].
6895 RUNTIME_FUNCTION(Runtime_StringToArray) {
6896   HandleScope scope(isolate);
6897   DCHECK(args.length() == 2);
6898   CONVERT_ARG_HANDLE_CHECKED(String, s, 0);
6899   CONVERT_NUMBER_CHECKED(uint32_t, limit, Uint32, args[1]);
6900
6901   s = String::Flatten(s);
6902   const int length = static_cast<int>(Min<uint32_t>(s->length(), limit));
6903
6904   Handle<FixedArray> elements;
6905   int position = 0;
6906   if (s->IsFlat() && s->IsOneByteRepresentation()) {
6907     // Try using cached chars where possible.
6908     elements = isolate->factory()->NewUninitializedFixedArray(length);
6909
6910     DisallowHeapAllocation no_gc;
6911     String::FlatContent content = s->GetFlatContent();
6912     if (content.IsOneByte()) {
6913       Vector<const uint8_t> chars = content.ToOneByteVector();
6914       // Note, this will initialize all elements (not only the prefix)
6915       // to prevent GC from seeing partially initialized array.
6916       position = CopyCachedOneByteCharsToArray(isolate->heap(), chars.start(),
6917                                                *elements, length);
6918     } else {
6919       MemsetPointer(elements->data_start(),
6920                     isolate->heap()->undefined_value(),
6921                     length);
6922     }
6923   } else {
6924     elements = isolate->factory()->NewFixedArray(length);
6925   }
6926   for (int i = position; i < length; ++i) {
6927     Handle<Object> str =
6928         isolate->factory()->LookupSingleCharacterStringFromCode(s->Get(i));
6929     elements->set(i, *str);
6930   }
6931
6932 #ifdef DEBUG
6933   for (int i = 0; i < length; ++i) {
6934     DCHECK(String::cast(elements->get(i))->length() == 1);
6935   }
6936 #endif
6937
6938   return *isolate->factory()->NewJSArrayWithElements(elements);
6939 }
6940
6941
6942 RUNTIME_FUNCTION(Runtime_NewStringWrapper) {
6943   HandleScope scope(isolate);
6944   DCHECK(args.length() == 1);
6945   CONVERT_ARG_HANDLE_CHECKED(String, value, 0);
6946   return *Object::ToObject(isolate, value).ToHandleChecked();
6947 }
6948
6949
6950 bool Runtime::IsUpperCaseChar(RuntimeState* runtime_state, uint16_t ch) {
6951   unibrow::uchar chars[unibrow::ToUppercase::kMaxWidth];
6952   int char_length = runtime_state->to_upper_mapping()->get(ch, 0, chars);
6953   return char_length == 0;
6954 }
6955
6956
6957 RUNTIME_FUNCTION(Runtime_NumberToStringRT) {
6958   HandleScope scope(isolate);
6959   DCHECK(args.length() == 1);
6960   CONVERT_NUMBER_ARG_HANDLE_CHECKED(number, 0);
6961
6962   return *isolate->factory()->NumberToString(number);
6963 }
6964
6965
6966 RUNTIME_FUNCTION(Runtime_NumberToStringSkipCache) {
6967   HandleScope scope(isolate);
6968   DCHECK(args.length() == 1);
6969   CONVERT_NUMBER_ARG_HANDLE_CHECKED(number, 0);
6970
6971   return *isolate->factory()->NumberToString(number, false);
6972 }
6973
6974
6975 RUNTIME_FUNCTION(Runtime_NumberToInteger) {
6976   HandleScope scope(isolate);
6977   DCHECK(args.length() == 1);
6978
6979   CONVERT_DOUBLE_ARG_CHECKED(number, 0);
6980   return *isolate->factory()->NewNumber(DoubleToInteger(number));
6981 }
6982
6983
6984 RUNTIME_FUNCTION(Runtime_NumberToIntegerMapMinusZero) {
6985   HandleScope scope(isolate);
6986   DCHECK(args.length() == 1);
6987
6988   CONVERT_DOUBLE_ARG_CHECKED(number, 0);
6989   double double_value = DoubleToInteger(number);
6990   // Map both -0 and +0 to +0.
6991   if (double_value == 0) double_value = 0;
6992
6993   return *isolate->factory()->NewNumber(double_value);
6994 }
6995
6996
6997 RUNTIME_FUNCTION(Runtime_NumberToJSUint32) {
6998   HandleScope scope(isolate);
6999   DCHECK(args.length() == 1);
7000
7001   CONVERT_NUMBER_CHECKED(int32_t, number, Uint32, args[0]);
7002   return *isolate->factory()->NewNumberFromUint(number);
7003 }
7004
7005
7006 RUNTIME_FUNCTION(Runtime_NumberToJSInt32) {
7007   HandleScope scope(isolate);
7008   DCHECK(args.length() == 1);
7009
7010   CONVERT_DOUBLE_ARG_CHECKED(number, 0);
7011   return *isolate->factory()->NewNumberFromInt(DoubleToInt32(number));
7012 }
7013
7014
7015 // Converts a Number to a Smi, if possible. Returns NaN if the number is not
7016 // a small integer.
7017 RUNTIME_FUNCTION(Runtime_NumberToSmi) {
7018   SealHandleScope shs(isolate);
7019   DCHECK(args.length() == 1);
7020   CONVERT_ARG_CHECKED(Object, obj, 0);
7021   if (obj->IsSmi()) {
7022     return obj;
7023   }
7024   if (obj->IsHeapNumber()) {
7025     double value = HeapNumber::cast(obj)->value();
7026     int int_value = FastD2I(value);
7027     if (value == FastI2D(int_value) && Smi::IsValid(int_value)) {
7028       return Smi::FromInt(int_value);
7029     }
7030   }
7031   return isolate->heap()->nan_value();
7032 }
7033
7034
7035 RUNTIME_FUNCTION(Runtime_AllocateHeapNumber) {
7036   HandleScope scope(isolate);
7037   DCHECK(args.length() == 0);
7038   return *isolate->factory()->NewHeapNumber(0);
7039 }
7040
7041
7042 RUNTIME_FUNCTION(Runtime_AllocateFloat32x4) {
7043   HandleScope scope(isolate);
7044   DCHECK(args.length() == 0);
7045
7046   float32x4_value_t zero = {{0, 0, 0, 0}};
7047   return *isolate->factory()->NewFloat32x4(zero);
7048 }
7049
7050
7051 RUNTIME_FUNCTION(Runtime_AllocateFloat64x2) {
7052   HandleScope scope(isolate);
7053   DCHECK(args.length() == 0);
7054
7055   float64x2_value_t zero = {{0, 0}};
7056   return *isolate->factory()->NewFloat64x2(zero);
7057 }
7058
7059
7060 RUNTIME_FUNCTION(Runtime_AllocateInt32x4) {
7061   HandleScope scope(isolate);
7062   DCHECK(args.length() == 0);
7063
7064   int32x4_value_t zero = {{0, 0, 0, 0}};
7065   return *isolate->factory()->NewInt32x4(zero);
7066 }
7067
7068
7069 RUNTIME_FUNCTION(Runtime_NumberAdd) {
7070   HandleScope scope(isolate);
7071   DCHECK(args.length() == 2);
7072
7073   CONVERT_DOUBLE_ARG_CHECKED(x, 0);
7074   CONVERT_DOUBLE_ARG_CHECKED(y, 1);
7075   return *isolate->factory()->NewNumber(x + y);
7076 }
7077
7078
7079 RUNTIME_FUNCTION(Runtime_NumberSub) {
7080   HandleScope scope(isolate);
7081   DCHECK(args.length() == 2);
7082
7083   CONVERT_DOUBLE_ARG_CHECKED(x, 0);
7084   CONVERT_DOUBLE_ARG_CHECKED(y, 1);
7085   return *isolate->factory()->NewNumber(x - y);
7086 }
7087
7088
7089 RUNTIME_FUNCTION(Runtime_NumberMul) {
7090   HandleScope scope(isolate);
7091   DCHECK(args.length() == 2);
7092
7093   CONVERT_DOUBLE_ARG_CHECKED(x, 0);
7094   CONVERT_DOUBLE_ARG_CHECKED(y, 1);
7095   return *isolate->factory()->NewNumber(x * y);
7096 }
7097
7098
7099 RUNTIME_FUNCTION(Runtime_NumberUnaryMinus) {
7100   HandleScope scope(isolate);
7101   DCHECK(args.length() == 1);
7102
7103   CONVERT_DOUBLE_ARG_CHECKED(x, 0);
7104   return *isolate->factory()->NewNumber(-x);
7105 }
7106
7107
7108 RUNTIME_FUNCTION(Runtime_NumberDiv) {
7109   HandleScope scope(isolate);
7110   DCHECK(args.length() == 2);
7111
7112   CONVERT_DOUBLE_ARG_CHECKED(x, 0);
7113   CONVERT_DOUBLE_ARG_CHECKED(y, 1);
7114   return *isolate->factory()->NewNumber(x / y);
7115 }
7116
7117
7118 RUNTIME_FUNCTION(Runtime_NumberMod) {
7119   HandleScope scope(isolate);
7120   DCHECK(args.length() == 2);
7121
7122   CONVERT_DOUBLE_ARG_CHECKED(x, 0);
7123   CONVERT_DOUBLE_ARG_CHECKED(y, 1);
7124   return *isolate->factory()->NewNumber(modulo(x, y));
7125 }
7126
7127
7128 RUNTIME_FUNCTION(Runtime_NumberImul) {
7129   HandleScope scope(isolate);
7130   DCHECK(args.length() == 2);
7131
7132   // We rely on implementation-defined behavior below, but at least not on
7133   // undefined behavior.
7134   CONVERT_NUMBER_CHECKED(uint32_t, x, Int32, args[0]);
7135   CONVERT_NUMBER_CHECKED(uint32_t, y, Int32, args[1]);
7136   int32_t product = static_cast<int32_t>(x * y);
7137   return *isolate->factory()->NewNumberFromInt(product);
7138 }
7139
7140
7141 RUNTIME_FUNCTION(Runtime_StringAdd) {
7142   HandleScope scope(isolate);
7143   DCHECK(args.length() == 2);
7144   CONVERT_ARG_HANDLE_CHECKED(String, str1, 0);
7145   CONVERT_ARG_HANDLE_CHECKED(String, str2, 1);
7146   isolate->counters()->string_add_runtime()->Increment();
7147   Handle<String> result;
7148   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
7149       isolate, result, isolate->factory()->NewConsString(str1, str2));
7150   return *result;
7151 }
7152
7153
7154 template <typename sinkchar>
7155 static inline void StringBuilderConcatHelper(String* special,
7156                                              sinkchar* sink,
7157                                              FixedArray* fixed_array,
7158                                              int array_length) {
7159   DisallowHeapAllocation no_gc;
7160   int position = 0;
7161   for (int i = 0; i < array_length; i++) {
7162     Object* element = fixed_array->get(i);
7163     if (element->IsSmi()) {
7164       // Smi encoding of position and length.
7165       int encoded_slice = Smi::cast(element)->value();
7166       int pos;
7167       int len;
7168       if (encoded_slice > 0) {
7169         // Position and length encoded in one smi.
7170         pos = StringBuilderSubstringPosition::decode(encoded_slice);
7171         len = StringBuilderSubstringLength::decode(encoded_slice);
7172       } else {
7173         // Position and length encoded in two smis.
7174         Object* obj = fixed_array->get(++i);
7175         DCHECK(obj->IsSmi());
7176         pos = Smi::cast(obj)->value();
7177         len = -encoded_slice;
7178       }
7179       String::WriteToFlat(special,
7180                           sink + position,
7181                           pos,
7182                           pos + len);
7183       position += len;
7184     } else {
7185       String* string = String::cast(element);
7186       int element_length = string->length();
7187       String::WriteToFlat(string, sink + position, 0, element_length);
7188       position += element_length;
7189     }
7190   }
7191 }
7192
7193
7194 // Returns the result length of the concatenation.
7195 // On illegal argument, -1 is returned.
7196 static inline int StringBuilderConcatLength(int special_length,
7197                                             FixedArray* fixed_array,
7198                                             int array_length,
7199                                             bool* one_byte) {
7200   DisallowHeapAllocation no_gc;
7201   int position = 0;
7202   for (int i = 0; i < array_length; i++) {
7203     int increment = 0;
7204     Object* elt = fixed_array->get(i);
7205     if (elt->IsSmi()) {
7206       // Smi encoding of position and length.
7207       int smi_value = Smi::cast(elt)->value();
7208       int pos;
7209       int len;
7210       if (smi_value > 0) {
7211         // Position and length encoded in one smi.
7212         pos = StringBuilderSubstringPosition::decode(smi_value);
7213         len = StringBuilderSubstringLength::decode(smi_value);
7214       } else {
7215         // Position and length encoded in two smis.
7216         len = -smi_value;
7217         // Get the position and check that it is a positive smi.
7218         i++;
7219         if (i >= array_length) return -1;
7220         Object* next_smi = fixed_array->get(i);
7221         if (!next_smi->IsSmi()) return -1;
7222         pos = Smi::cast(next_smi)->value();
7223         if (pos < 0) return -1;
7224       }
7225       DCHECK(pos >= 0);
7226       DCHECK(len >= 0);
7227       if (pos > special_length || len > special_length - pos) return -1;
7228       increment = len;
7229     } else if (elt->IsString()) {
7230       String* element = String::cast(elt);
7231       int element_length = element->length();
7232       increment = element_length;
7233       if (*one_byte && !element->HasOnlyOneByteChars()) {
7234         *one_byte = false;
7235       }
7236     } else {
7237       return -1;
7238     }
7239     if (increment > String::kMaxLength - position) {
7240       return kMaxInt;  // Provoke throw on allocation.
7241     }
7242     position += increment;
7243   }
7244   return position;
7245 }
7246
7247
7248 RUNTIME_FUNCTION(Runtime_StringBuilderConcat) {
7249   HandleScope scope(isolate);
7250   DCHECK(args.length() == 3);
7251   CONVERT_ARG_HANDLE_CHECKED(JSArray, array, 0);
7252   int32_t array_length;
7253   if (!args[1]->ToInt32(&array_length)) {
7254     THROW_NEW_ERROR_RETURN_FAILURE(isolate, NewInvalidStringLengthError());
7255   }
7256   CONVERT_ARG_HANDLE_CHECKED(String, special, 2);
7257
7258   size_t actual_array_length = 0;
7259   RUNTIME_ASSERT(
7260       TryNumberToSize(isolate, array->length(), &actual_array_length));
7261   RUNTIME_ASSERT(array_length >= 0);
7262   RUNTIME_ASSERT(static_cast<size_t>(array_length) <= actual_array_length);
7263
7264   // This assumption is used by the slice encoding in one or two smis.
7265   DCHECK(Smi::kMaxValue >= String::kMaxLength);
7266
7267   RUNTIME_ASSERT(array->HasFastElements());
7268   JSObject::EnsureCanContainHeapObjectElements(array);
7269
7270   int special_length = special->length();
7271   if (!array->HasFastObjectElements()) {
7272     return isolate->Throw(isolate->heap()->illegal_argument_string());
7273   }
7274
7275   int length;
7276   bool one_byte = special->HasOnlyOneByteChars();
7277
7278   { DisallowHeapAllocation no_gc;
7279     FixedArray* fixed_array = FixedArray::cast(array->elements());
7280     if (fixed_array->length() < array_length) {
7281       array_length = fixed_array->length();
7282     }
7283
7284     if (array_length == 0) {
7285       return isolate->heap()->empty_string();
7286     } else if (array_length == 1) {
7287       Object* first = fixed_array->get(0);
7288       if (first->IsString()) return first;
7289     }
7290     length = StringBuilderConcatLength(
7291         special_length, fixed_array, array_length, &one_byte);
7292   }
7293
7294   if (length == -1) {
7295     return isolate->Throw(isolate->heap()->illegal_argument_string());
7296   }
7297
7298   if (one_byte) {
7299     Handle<SeqOneByteString> answer;
7300     ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
7301         isolate, answer,
7302         isolate->factory()->NewRawOneByteString(length));
7303     StringBuilderConcatHelper(*special,
7304                               answer->GetChars(),
7305                               FixedArray::cast(array->elements()),
7306                               array_length);
7307     return *answer;
7308   } else {
7309     Handle<SeqTwoByteString> answer;
7310     ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
7311         isolate, answer,
7312         isolate->factory()->NewRawTwoByteString(length));
7313     StringBuilderConcatHelper(*special,
7314                               answer->GetChars(),
7315                               FixedArray::cast(array->elements()),
7316                               array_length);
7317     return *answer;
7318   }
7319 }
7320
7321
7322 RUNTIME_FUNCTION(Runtime_StringBuilderJoin) {
7323   HandleScope scope(isolate);
7324   DCHECK(args.length() == 3);
7325   CONVERT_ARG_HANDLE_CHECKED(JSArray, array, 0);
7326   int32_t array_length;
7327   if (!args[1]->ToInt32(&array_length)) {
7328     THROW_NEW_ERROR_RETURN_FAILURE(isolate, NewInvalidStringLengthError());
7329   }
7330   CONVERT_ARG_HANDLE_CHECKED(String, separator, 2);
7331   RUNTIME_ASSERT(array->HasFastObjectElements());
7332   RUNTIME_ASSERT(array_length >= 0);
7333
7334   Handle<FixedArray> fixed_array(FixedArray::cast(array->elements()));
7335   if (fixed_array->length() < array_length) {
7336     array_length = fixed_array->length();
7337   }
7338
7339   if (array_length == 0) {
7340     return isolate->heap()->empty_string();
7341   } else if (array_length == 1) {
7342     Object* first = fixed_array->get(0);
7343     RUNTIME_ASSERT(first->IsString());
7344     return first;
7345   }
7346
7347   int separator_length = separator->length();
7348   RUNTIME_ASSERT(separator_length > 0);
7349   int max_nof_separators =
7350       (String::kMaxLength + separator_length - 1) / separator_length;
7351   if (max_nof_separators < (array_length - 1)) {
7352     THROW_NEW_ERROR_RETURN_FAILURE(isolate, NewInvalidStringLengthError());
7353   }
7354   int length = (array_length - 1) * separator_length;
7355   for (int i = 0; i < array_length; i++) {
7356     Object* element_obj = fixed_array->get(i);
7357     RUNTIME_ASSERT(element_obj->IsString());
7358     String* element = String::cast(element_obj);
7359     int increment = element->length();
7360     if (increment > String::kMaxLength - length) {
7361       STATIC_ASSERT(String::kMaxLength < kMaxInt);
7362       length = kMaxInt;  // Provoke exception;
7363       break;
7364     }
7365     length += increment;
7366   }
7367
7368   Handle<SeqTwoByteString> answer;
7369   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
7370       isolate, answer,
7371       isolate->factory()->NewRawTwoByteString(length));
7372
7373   DisallowHeapAllocation no_gc;
7374
7375   uc16* sink = answer->GetChars();
7376 #ifdef DEBUG
7377   uc16* end = sink + length;
7378 #endif
7379
7380   RUNTIME_ASSERT(fixed_array->get(0)->IsString());
7381   String* first = String::cast(fixed_array->get(0));
7382   String* separator_raw = *separator;
7383   int first_length = first->length();
7384   String::WriteToFlat(first, sink, 0, first_length);
7385   sink += first_length;
7386
7387   for (int i = 1; i < array_length; i++) {
7388     DCHECK(sink + separator_length <= end);
7389     String::WriteToFlat(separator_raw, sink, 0, separator_length);
7390     sink += separator_length;
7391
7392     RUNTIME_ASSERT(fixed_array->get(i)->IsString());
7393     String* element = String::cast(fixed_array->get(i));
7394     int element_length = element->length();
7395     DCHECK(sink + element_length <= end);
7396     String::WriteToFlat(element, sink, 0, element_length);
7397     sink += element_length;
7398   }
7399   DCHECK(sink == end);
7400
7401   // Use %_FastOneByteArrayJoin instead.
7402   DCHECK(!answer->IsOneByteRepresentation());
7403   return *answer;
7404 }
7405
7406 template <typename Char>
7407 static void JoinSparseArrayWithSeparator(FixedArray* elements,
7408                                          int elements_length,
7409                                          uint32_t array_length,
7410                                          String* separator,
7411                                          Vector<Char> buffer) {
7412   DisallowHeapAllocation no_gc;
7413   int previous_separator_position = 0;
7414   int separator_length = separator->length();
7415   int cursor = 0;
7416   for (int i = 0; i < elements_length; i += 2) {
7417     int position = NumberToInt32(elements->get(i));
7418     String* string = String::cast(elements->get(i + 1));
7419     int string_length = string->length();
7420     if (string->length() > 0) {
7421       while (previous_separator_position < position) {
7422         String::WriteToFlat<Char>(separator, &buffer[cursor],
7423                                   0, separator_length);
7424         cursor += separator_length;
7425         previous_separator_position++;
7426       }
7427       String::WriteToFlat<Char>(string, &buffer[cursor],
7428                                 0, string_length);
7429       cursor += string->length();
7430     }
7431   }
7432   if (separator_length > 0) {
7433     // Array length must be representable as a signed 32-bit number,
7434     // otherwise the total string length would have been too large.
7435     DCHECK(array_length <= 0x7fffffff);  // Is int32_t.
7436     int last_array_index = static_cast<int>(array_length - 1);
7437     while (previous_separator_position < last_array_index) {
7438       String::WriteToFlat<Char>(separator, &buffer[cursor],
7439                                 0, separator_length);
7440       cursor += separator_length;
7441       previous_separator_position++;
7442     }
7443   }
7444   DCHECK(cursor <= buffer.length());
7445 }
7446
7447
7448 RUNTIME_FUNCTION(Runtime_SparseJoinWithSeparator) {
7449   HandleScope scope(isolate);
7450   DCHECK(args.length() == 3);
7451   CONVERT_ARG_HANDLE_CHECKED(JSArray, elements_array, 0);
7452   CONVERT_NUMBER_CHECKED(uint32_t, array_length, Uint32, args[1]);
7453   CONVERT_ARG_HANDLE_CHECKED(String, separator, 2);
7454   // elements_array is fast-mode JSarray of alternating positions
7455   // (increasing order) and strings.
7456   RUNTIME_ASSERT(elements_array->HasFastSmiOrObjectElements());
7457   // array_length is length of original array (used to add separators);
7458   // separator is string to put between elements. Assumed to be non-empty.
7459   RUNTIME_ASSERT(array_length > 0);
7460
7461   // Find total length of join result.
7462   int string_length = 0;
7463   bool is_one_byte = separator->IsOneByteRepresentation();
7464   bool overflow = false;
7465   CONVERT_NUMBER_CHECKED(int, elements_length, Int32, elements_array->length());
7466   RUNTIME_ASSERT(elements_length <= elements_array->elements()->length());
7467   RUNTIME_ASSERT((elements_length & 1) == 0);  // Even length.
7468   FixedArray* elements = FixedArray::cast(elements_array->elements());
7469   for (int i = 0; i < elements_length; i += 2) {
7470     RUNTIME_ASSERT(elements->get(i)->IsNumber());
7471     CONVERT_NUMBER_CHECKED(uint32_t, position, Uint32, elements->get(i));
7472     RUNTIME_ASSERT(position < array_length);
7473     RUNTIME_ASSERT(elements->get(i + 1)->IsString());
7474   }
7475
7476   { DisallowHeapAllocation no_gc;
7477     for (int i = 0; i < elements_length; i += 2) {
7478       String* string = String::cast(elements->get(i + 1));
7479       int length = string->length();
7480       if (is_one_byte && !string->IsOneByteRepresentation()) {
7481         is_one_byte = false;
7482       }
7483       if (length > String::kMaxLength ||
7484           String::kMaxLength - length < string_length) {
7485         overflow = true;
7486         break;
7487       }
7488       string_length += length;
7489     }
7490   }
7491
7492   int separator_length = separator->length();
7493   if (!overflow && separator_length > 0) {
7494     if (array_length <= 0x7fffffffu) {
7495       int separator_count = static_cast<int>(array_length) - 1;
7496       int remaining_length = String::kMaxLength - string_length;
7497       if ((remaining_length / separator_length) >= separator_count) {
7498         string_length += separator_length * (array_length - 1);
7499       } else {
7500         // Not room for the separators within the maximal string length.
7501         overflow = true;
7502       }
7503     } else {
7504       // Nonempty separator and at least 2^31-1 separators necessary
7505       // means that the string is too large to create.
7506       STATIC_ASSERT(String::kMaxLength < 0x7fffffff);
7507       overflow = true;
7508     }
7509   }
7510   if (overflow) {
7511     // Throw an exception if the resulting string is too large. See
7512     // https://code.google.com/p/chromium/issues/detail?id=336820
7513     // for details.
7514     THROW_NEW_ERROR_RETURN_FAILURE(isolate, NewInvalidStringLengthError());
7515   }
7516
7517   if (is_one_byte) {
7518     Handle<SeqOneByteString> result = isolate->factory()->NewRawOneByteString(
7519         string_length).ToHandleChecked();
7520     JoinSparseArrayWithSeparator<uint8_t>(
7521         FixedArray::cast(elements_array->elements()),
7522         elements_length,
7523         array_length,
7524         *separator,
7525         Vector<uint8_t>(result->GetChars(), string_length));
7526     return *result;
7527   } else {
7528     Handle<SeqTwoByteString> result = isolate->factory()->NewRawTwoByteString(
7529         string_length).ToHandleChecked();
7530     JoinSparseArrayWithSeparator<uc16>(
7531         FixedArray::cast(elements_array->elements()),
7532         elements_length,
7533         array_length,
7534         *separator,
7535         Vector<uc16>(result->GetChars(), string_length));
7536     return *result;
7537   }
7538 }
7539
7540
7541 RUNTIME_FUNCTION(Runtime_NumberOr) {
7542   HandleScope scope(isolate);
7543   DCHECK(args.length() == 2);
7544
7545   CONVERT_NUMBER_CHECKED(int32_t, x, Int32, args[0]);
7546   CONVERT_NUMBER_CHECKED(int32_t, y, Int32, args[1]);
7547   return *isolate->factory()->NewNumberFromInt(x | y);
7548 }
7549
7550
7551 RUNTIME_FUNCTION(Runtime_NumberAnd) {
7552   HandleScope scope(isolate);
7553   DCHECK(args.length() == 2);
7554
7555   CONVERT_NUMBER_CHECKED(int32_t, x, Int32, args[0]);
7556   CONVERT_NUMBER_CHECKED(int32_t, y, Int32, args[1]);
7557   return *isolate->factory()->NewNumberFromInt(x & y);
7558 }
7559
7560
7561 RUNTIME_FUNCTION(Runtime_NumberXor) {
7562   HandleScope scope(isolate);
7563   DCHECK(args.length() == 2);
7564
7565   CONVERT_NUMBER_CHECKED(int32_t, x, Int32, args[0]);
7566   CONVERT_NUMBER_CHECKED(int32_t, y, Int32, args[1]);
7567   return *isolate->factory()->NewNumberFromInt(x ^ y);
7568 }
7569
7570
7571 RUNTIME_FUNCTION(Runtime_NumberShl) {
7572   HandleScope scope(isolate);
7573   DCHECK(args.length() == 2);
7574
7575   CONVERT_NUMBER_CHECKED(int32_t, x, Int32, args[0]);
7576   CONVERT_NUMBER_CHECKED(int32_t, y, Int32, args[1]);
7577   return *isolate->factory()->NewNumberFromInt(x << (y & 0x1f));
7578 }
7579
7580
7581 RUNTIME_FUNCTION(Runtime_NumberShr) {
7582   HandleScope scope(isolate);
7583   DCHECK(args.length() == 2);
7584
7585   CONVERT_NUMBER_CHECKED(uint32_t, x, Uint32, args[0]);
7586   CONVERT_NUMBER_CHECKED(int32_t, y, Int32, args[1]);
7587   return *isolate->factory()->NewNumberFromUint(x >> (y & 0x1f));
7588 }
7589
7590
7591 RUNTIME_FUNCTION(Runtime_NumberSar) {
7592   HandleScope scope(isolate);
7593   DCHECK(args.length() == 2);
7594
7595   CONVERT_NUMBER_CHECKED(int32_t, x, Int32, args[0]);
7596   CONVERT_NUMBER_CHECKED(int32_t, y, Int32, args[1]);
7597   return *isolate->factory()->NewNumberFromInt(
7598       ArithmeticShiftRight(x, y & 0x1f));
7599 }
7600
7601
7602 RUNTIME_FUNCTION(Runtime_NumberEquals) {
7603   SealHandleScope shs(isolate);
7604   DCHECK(args.length() == 2);
7605
7606   CONVERT_DOUBLE_ARG_CHECKED(x, 0);
7607   CONVERT_DOUBLE_ARG_CHECKED(y, 1);
7608   if (std::isnan(x)) return Smi::FromInt(NOT_EQUAL);
7609   if (std::isnan(y)) return Smi::FromInt(NOT_EQUAL);
7610   if (x == y) return Smi::FromInt(EQUAL);
7611   Object* result;
7612   if ((fpclassify(x) == FP_ZERO) && (fpclassify(y) == FP_ZERO)) {
7613     result = Smi::FromInt(EQUAL);
7614   } else {
7615     result = Smi::FromInt(NOT_EQUAL);
7616   }
7617   return result;
7618 }
7619
7620
7621 RUNTIME_FUNCTION(Runtime_StringEquals) {
7622   HandleScope handle_scope(isolate);
7623   DCHECK(args.length() == 2);
7624
7625   CONVERT_ARG_HANDLE_CHECKED(String, x, 0);
7626   CONVERT_ARG_HANDLE_CHECKED(String, y, 1);
7627
7628   bool not_equal = !String::Equals(x, y);
7629   // This is slightly convoluted because the value that signifies
7630   // equality is 0 and inequality is 1 so we have to negate the result
7631   // from String::Equals.
7632   DCHECK(not_equal == 0 || not_equal == 1);
7633   STATIC_ASSERT(EQUAL == 0);
7634   STATIC_ASSERT(NOT_EQUAL == 1);
7635   return Smi::FromInt(not_equal);
7636 }
7637
7638
7639 RUNTIME_FUNCTION(Runtime_NumberCompare) {
7640   SealHandleScope shs(isolate);
7641   DCHECK(args.length() == 3);
7642
7643   CONVERT_DOUBLE_ARG_CHECKED(x, 0);
7644   CONVERT_DOUBLE_ARG_CHECKED(y, 1);
7645   CONVERT_ARG_HANDLE_CHECKED(Object, uncomparable_result, 2)
7646   if (std::isnan(x) || std::isnan(y)) return *uncomparable_result;
7647   if (x == y) return Smi::FromInt(EQUAL);
7648   if (isless(x, y)) return Smi::FromInt(LESS);
7649   return Smi::FromInt(GREATER);
7650 }
7651
7652
7653 // Compare two Smis as if they were converted to strings and then
7654 // compared lexicographically.
7655 RUNTIME_FUNCTION(Runtime_SmiLexicographicCompare) {
7656   SealHandleScope shs(isolate);
7657   DCHECK(args.length() == 2);
7658   CONVERT_SMI_ARG_CHECKED(x_value, 0);
7659   CONVERT_SMI_ARG_CHECKED(y_value, 1);
7660
7661   // If the integers are equal so are the string representations.
7662   if (x_value == y_value) return Smi::FromInt(EQUAL);
7663
7664   // If one of the integers is zero the normal integer order is the
7665   // same as the lexicographic order of the string representations.
7666   if (x_value == 0 || y_value == 0)
7667     return Smi::FromInt(x_value < y_value ? LESS : GREATER);
7668
7669   // If only one of the integers is negative the negative number is
7670   // smallest because the char code of '-' is less than the char code
7671   // of any digit.  Otherwise, we make both values positive.
7672
7673   // Use unsigned values otherwise the logic is incorrect for -MIN_INT on
7674   // architectures using 32-bit Smis.
7675   uint32_t x_scaled = x_value;
7676   uint32_t y_scaled = y_value;
7677   if (x_value < 0 || y_value < 0) {
7678     if (y_value >= 0) return Smi::FromInt(LESS);
7679     if (x_value >= 0) return Smi::FromInt(GREATER);
7680     x_scaled = -x_value;
7681     y_scaled = -y_value;
7682   }
7683
7684   static const uint32_t kPowersOf10[] = {
7685     1, 10, 100, 1000, 10*1000, 100*1000,
7686     1000*1000, 10*1000*1000, 100*1000*1000,
7687     1000*1000*1000
7688   };
7689
7690   // If the integers have the same number of decimal digits they can be
7691   // compared directly as the numeric order is the same as the
7692   // lexicographic order.  If one integer has fewer digits, it is scaled
7693   // by some power of 10 to have the same number of digits as the longer
7694   // integer.  If the scaled integers are equal it means the shorter
7695   // integer comes first in the lexicographic order.
7696
7697   // From http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog10
7698   int x_log2 = IntegerLog2(x_scaled);
7699   int x_log10 = ((x_log2 + 1) * 1233) >> 12;
7700   x_log10 -= x_scaled < kPowersOf10[x_log10];
7701
7702   int y_log2 = IntegerLog2(y_scaled);
7703   int y_log10 = ((y_log2 + 1) * 1233) >> 12;
7704   y_log10 -= y_scaled < kPowersOf10[y_log10];
7705
7706   int tie = EQUAL;
7707
7708   if (x_log10 < y_log10) {
7709     // X has fewer digits.  We would like to simply scale up X but that
7710     // might overflow, e.g when comparing 9 with 1_000_000_000, 9 would
7711     // be scaled up to 9_000_000_000. So we scale up by the next
7712     // smallest power and scale down Y to drop one digit. It is OK to
7713     // drop one digit from the longer integer since the final digit is
7714     // past the length of the shorter integer.
7715     x_scaled *= kPowersOf10[y_log10 - x_log10 - 1];
7716     y_scaled /= 10;
7717     tie = LESS;
7718   } else if (y_log10 < x_log10) {
7719     y_scaled *= kPowersOf10[x_log10 - y_log10 - 1];
7720     x_scaled /= 10;
7721     tie = GREATER;
7722   }
7723
7724   if (x_scaled < y_scaled) return Smi::FromInt(LESS);
7725   if (x_scaled > y_scaled) return Smi::FromInt(GREATER);
7726   return Smi::FromInt(tie);
7727 }
7728
7729
7730 RUNTIME_FUNCTION(Runtime_StringCompare) {
7731   HandleScope handle_scope(isolate);
7732   DCHECK(args.length() == 2);
7733
7734   CONVERT_ARG_HANDLE_CHECKED(String, x, 0);
7735   CONVERT_ARG_HANDLE_CHECKED(String, y, 1);
7736
7737   isolate->counters()->string_compare_runtime()->Increment();
7738
7739   // A few fast case tests before we flatten.
7740   if (x.is_identical_to(y)) return Smi::FromInt(EQUAL);
7741   if (y->length() == 0) {
7742     if (x->length() == 0) return Smi::FromInt(EQUAL);
7743     return Smi::FromInt(GREATER);
7744   } else if (x->length() == 0) {
7745     return Smi::FromInt(LESS);
7746   }
7747
7748   int d = x->Get(0) - y->Get(0);
7749   if (d < 0) return Smi::FromInt(LESS);
7750   else if (d > 0) return Smi::FromInt(GREATER);
7751
7752   // Slow case.
7753   x = String::Flatten(x);
7754   y = String::Flatten(y);
7755
7756   DisallowHeapAllocation no_gc;
7757   Object* equal_prefix_result = Smi::FromInt(EQUAL);
7758   int prefix_length = x->length();
7759   if (y->length() < prefix_length) {
7760     prefix_length = y->length();
7761     equal_prefix_result = Smi::FromInt(GREATER);
7762   } else if (y->length() > prefix_length) {
7763     equal_prefix_result = Smi::FromInt(LESS);
7764   }
7765   int r;
7766   String::FlatContent x_content = x->GetFlatContent();
7767   String::FlatContent y_content = y->GetFlatContent();
7768   if (x_content.IsOneByte()) {
7769     Vector<const uint8_t> x_chars = x_content.ToOneByteVector();
7770     if (y_content.IsOneByte()) {
7771       Vector<const uint8_t> y_chars = y_content.ToOneByteVector();
7772       r = CompareChars(x_chars.start(), y_chars.start(), prefix_length);
7773     } else {
7774       Vector<const uc16> y_chars = y_content.ToUC16Vector();
7775       r = CompareChars(x_chars.start(), y_chars.start(), prefix_length);
7776     }
7777   } else {
7778     Vector<const uc16> x_chars = x_content.ToUC16Vector();
7779     if (y_content.IsOneByte()) {
7780       Vector<const uint8_t> y_chars = y_content.ToOneByteVector();
7781       r = CompareChars(x_chars.start(), y_chars.start(), prefix_length);
7782     } else {
7783       Vector<const uc16> y_chars = y_content.ToUC16Vector();
7784       r = CompareChars(x_chars.start(), y_chars.start(), prefix_length);
7785     }
7786   }
7787   Object* result;
7788   if (r == 0) {
7789     result = equal_prefix_result;
7790   } else {
7791     result = (r < 0) ? Smi::FromInt(LESS) : Smi::FromInt(GREATER);
7792   }
7793   return result;
7794 }
7795
7796
7797 #define RUNTIME_UNARY_MATH(Name, name)                                         \
7798 RUNTIME_FUNCTION(Runtime_Math##Name) {                           \
7799   HandleScope scope(isolate);                                                  \
7800   DCHECK(args.length() == 1);                                                  \
7801   isolate->counters()->math_##name()->Increment();                             \
7802   CONVERT_DOUBLE_ARG_CHECKED(x, 0);                                            \
7803   return *isolate->factory()->NewHeapNumber(std::name(x));                     \
7804 }
7805
7806 RUNTIME_UNARY_MATH(Acos, acos)
7807 RUNTIME_UNARY_MATH(Asin, asin)
7808 RUNTIME_UNARY_MATH(Atan, atan)
7809 RUNTIME_UNARY_MATH(LogRT, log)
7810 #undef RUNTIME_UNARY_MATH
7811
7812
7813 RUNTIME_FUNCTION(Runtime_DoubleHi) {
7814   HandleScope scope(isolate);
7815   DCHECK(args.length() == 1);
7816   CONVERT_DOUBLE_ARG_CHECKED(x, 0);
7817   uint64_t integer = double_to_uint64(x);
7818   integer = (integer >> 32) & 0xFFFFFFFFu;
7819   return *isolate->factory()->NewNumber(static_cast<int32_t>(integer));
7820 }
7821
7822
7823 RUNTIME_FUNCTION(Runtime_DoubleLo) {
7824   HandleScope scope(isolate);
7825   DCHECK(args.length() == 1);
7826   CONVERT_DOUBLE_ARG_CHECKED(x, 0);
7827   return *isolate->factory()->NewNumber(
7828       static_cast<int32_t>(double_to_uint64(x) & 0xFFFFFFFFu));
7829 }
7830
7831
7832 RUNTIME_FUNCTION(Runtime_ConstructDouble) {
7833   HandleScope scope(isolate);
7834   DCHECK(args.length() == 2);
7835   CONVERT_NUMBER_CHECKED(uint32_t, hi, Uint32, args[0]);
7836   CONVERT_NUMBER_CHECKED(uint32_t, lo, Uint32, args[1]);
7837   uint64_t result = (static_cast<uint64_t>(hi) << 32) | lo;
7838   return *isolate->factory()->NewNumber(uint64_to_double(result));
7839 }
7840
7841
7842 RUNTIME_FUNCTION(Runtime_RemPiO2) {
7843   HandleScope handle_scope(isolate);
7844   DCHECK(args.length() == 1);
7845   CONVERT_DOUBLE_ARG_CHECKED(x, 0);
7846   Factory* factory = isolate->factory();
7847   double y[2] = {0.0, 0.0};
7848   int n = fdlibm::rempio2(x, y);
7849   Handle<FixedArray> array = factory->NewFixedArray(3);
7850   Handle<HeapNumber> y0 = factory->NewHeapNumber(y[0]);
7851   Handle<HeapNumber> y1 = factory->NewHeapNumber(y[1]);
7852   array->set(0, Smi::FromInt(n));
7853   array->set(1, *y0);
7854   array->set(2, *y1);
7855   return *factory->NewJSArrayWithElements(array);
7856 }
7857
7858
7859 static const double kPiDividedBy4 = 0.78539816339744830962;
7860
7861
7862 RUNTIME_FUNCTION(Runtime_MathAtan2) {
7863   HandleScope scope(isolate);
7864   DCHECK(args.length() == 2);
7865   isolate->counters()->math_atan2()->Increment();
7866
7867   CONVERT_DOUBLE_ARG_CHECKED(x, 0);
7868   CONVERT_DOUBLE_ARG_CHECKED(y, 1);
7869   double result;
7870   if (std::isinf(x) && std::isinf(y)) {
7871     // Make sure that the result in case of two infinite arguments
7872     // is a multiple of Pi / 4. The sign of the result is determined
7873     // by the first argument (x) and the sign of the second argument
7874     // determines the multiplier: one or three.
7875     int multiplier = (x < 0) ? -1 : 1;
7876     if (y < 0) multiplier *= 3;
7877     result = multiplier * kPiDividedBy4;
7878   } else {
7879     result = std::atan2(x, y);
7880   }
7881   return *isolate->factory()->NewNumber(result);
7882 }
7883
7884
7885 RUNTIME_FUNCTION(Runtime_MathExpRT) {
7886   HandleScope scope(isolate);
7887   DCHECK(args.length() == 1);
7888   isolate->counters()->math_exp()->Increment();
7889
7890   CONVERT_DOUBLE_ARG_CHECKED(x, 0);
7891   lazily_initialize_fast_exp();
7892   return *isolate->factory()->NewNumber(fast_exp(x));
7893 }
7894
7895
7896 RUNTIME_FUNCTION(Runtime_MathFloorRT) {
7897   HandleScope scope(isolate);
7898   DCHECK(args.length() == 1);
7899   isolate->counters()->math_floor()->Increment();
7900
7901   CONVERT_DOUBLE_ARG_CHECKED(x, 0);
7902   return *isolate->factory()->NewNumber(Floor(x));
7903 }
7904
7905
7906 // Slow version of Math.pow.  We check for fast paths for special cases.
7907 // Used if VFP3 is not available.
7908 RUNTIME_FUNCTION(Runtime_MathPowSlow) {
7909   HandleScope scope(isolate);
7910   DCHECK(args.length() == 2);
7911   isolate->counters()->math_pow()->Increment();
7912
7913   CONVERT_DOUBLE_ARG_CHECKED(x, 0);
7914
7915   // If the second argument is a smi, it is much faster to call the
7916   // custom powi() function than the generic pow().
7917   if (args[1]->IsSmi()) {
7918     int y = args.smi_at(1);
7919     return *isolate->factory()->NewNumber(power_double_int(x, y));
7920   }
7921
7922   CONVERT_DOUBLE_ARG_CHECKED(y, 1);
7923   double result = power_helper(x, y);
7924   if (std::isnan(result)) return isolate->heap()->nan_value();
7925   return *isolate->factory()->NewNumber(result);
7926 }
7927
7928
7929 // Fast version of Math.pow if we know that y is not an integer and y is not
7930 // -0.5 or 0.5.  Used as slow case from full codegen.
7931 RUNTIME_FUNCTION(Runtime_MathPowRT) {
7932   HandleScope scope(isolate);
7933   DCHECK(args.length() == 2);
7934   isolate->counters()->math_pow()->Increment();
7935
7936   CONVERT_DOUBLE_ARG_CHECKED(x, 0);
7937   CONVERT_DOUBLE_ARG_CHECKED(y, 1);
7938   if (y == 0) {
7939     return Smi::FromInt(1);
7940   } else {
7941     double result = power_double_double(x, y);
7942     if (std::isnan(result)) return isolate->heap()->nan_value();
7943     return *isolate->factory()->NewNumber(result);
7944   }
7945 }
7946
7947
7948 RUNTIME_FUNCTION(Runtime_RoundNumber) {
7949   HandleScope scope(isolate);
7950   DCHECK(args.length() == 1);
7951   CONVERT_NUMBER_ARG_HANDLE_CHECKED(input, 0);
7952   isolate->counters()->math_round()->Increment();
7953
7954   if (!input->IsHeapNumber()) {
7955     DCHECK(input->IsSmi());
7956     return *input;
7957   }
7958
7959   Handle<HeapNumber> number = Handle<HeapNumber>::cast(input);
7960
7961   double value = number->value();
7962   int exponent = number->get_exponent();
7963   int sign = number->get_sign();
7964
7965   if (exponent < -1) {
7966     // Number in range ]-0.5..0.5[. These always round to +/-zero.
7967     if (sign) return isolate->heap()->minus_zero_value();
7968     return Smi::FromInt(0);
7969   }
7970
7971   // We compare with kSmiValueSize - 2 because (2^30 - 0.1) has exponent 29 and
7972   // should be rounded to 2^30, which is not smi (for 31-bit smis, similar
7973   // argument holds for 32-bit smis).
7974   if (!sign && exponent < kSmiValueSize - 2) {
7975     return Smi::FromInt(static_cast<int>(value + 0.5));
7976   }
7977
7978   // If the magnitude is big enough, there's no place for fraction part. If we
7979   // try to add 0.5 to this number, 1.0 will be added instead.
7980   if (exponent >= 52) {
7981     return *number;
7982   }
7983
7984   if (sign && value >= -0.5) return isolate->heap()->minus_zero_value();
7985
7986   // Do not call NumberFromDouble() to avoid extra checks.
7987   return *isolate->factory()->NewNumber(Floor(value + 0.5));
7988 }
7989
7990
7991 RUNTIME_FUNCTION(Runtime_MathSqrtRT) {
7992   HandleScope scope(isolate);
7993   DCHECK(args.length() == 1);
7994   isolate->counters()->math_sqrt()->Increment();
7995
7996   CONVERT_DOUBLE_ARG_CHECKED(x, 0);
7997   return *isolate->factory()->NewNumber(fast_sqrt(x));
7998 }
7999
8000
8001 RUNTIME_FUNCTION(Runtime_MathFround) {
8002   HandleScope scope(isolate);
8003   DCHECK(args.length() == 1);
8004
8005   CONVERT_DOUBLE_ARG_CHECKED(x, 0);
8006   float xf = DoubleToFloat32(x);
8007   return *isolate->factory()->NewNumber(xf);
8008 }
8009
8010
8011 RUNTIME_FUNCTION(Runtime_DateMakeDay) {
8012   SealHandleScope shs(isolate);
8013   DCHECK(args.length() == 2);
8014
8015   CONVERT_SMI_ARG_CHECKED(year, 0);
8016   CONVERT_SMI_ARG_CHECKED(month, 1);
8017
8018   int days = isolate->date_cache()->DaysFromYearMonth(year, month);
8019   RUNTIME_ASSERT(Smi::IsValid(days));
8020   return Smi::FromInt(days);
8021 }
8022
8023
8024 RUNTIME_FUNCTION(Runtime_DateSetValue) {
8025   HandleScope scope(isolate);
8026   DCHECK(args.length() == 3);
8027
8028   CONVERT_ARG_HANDLE_CHECKED(JSDate, date, 0);
8029   CONVERT_DOUBLE_ARG_CHECKED(time, 1);
8030   CONVERT_SMI_ARG_CHECKED(is_utc, 2);
8031
8032   DateCache* date_cache = isolate->date_cache();
8033
8034   Handle<Object> value;;
8035   bool is_value_nan = false;
8036   if (std::isnan(time)) {
8037     value = isolate->factory()->nan_value();
8038     is_value_nan = true;
8039   } else if (!is_utc &&
8040              (time < -DateCache::kMaxTimeBeforeUTCInMs ||
8041               time > DateCache::kMaxTimeBeforeUTCInMs)) {
8042     value = isolate->factory()->nan_value();
8043     is_value_nan = true;
8044   } else {
8045     time = is_utc ? time : date_cache->ToUTC(static_cast<int64_t>(time));
8046     if (time < -DateCache::kMaxTimeInMs ||
8047         time > DateCache::kMaxTimeInMs) {
8048       value = isolate->factory()->nan_value();
8049       is_value_nan = true;
8050     } else  {
8051       value = isolate->factory()->NewNumber(DoubleToInteger(time));
8052     }
8053   }
8054   date->SetValue(*value, is_value_nan);
8055   return *value;
8056 }
8057
8058
8059 static Handle<JSObject> NewSloppyArguments(Isolate* isolate,
8060                                            Handle<JSFunction> callee,
8061                                            Object** parameters,
8062                                            int argument_count) {
8063   Handle<JSObject> result =
8064       isolate->factory()->NewArgumentsObject(callee, argument_count);
8065
8066   // Allocate the elements if needed.
8067   int parameter_count = callee->shared()->formal_parameter_count();
8068   if (argument_count > 0) {
8069     if (parameter_count > 0) {
8070       int mapped_count = Min(argument_count, parameter_count);
8071       Handle<FixedArray> parameter_map =
8072           isolate->factory()->NewFixedArray(mapped_count + 2, NOT_TENURED);
8073       parameter_map->set_map(
8074           isolate->heap()->sloppy_arguments_elements_map());
8075
8076       Handle<Map> map = Map::Copy(handle(result->map()));
8077       map->set_elements_kind(SLOPPY_ARGUMENTS_ELEMENTS);
8078
8079       result->set_map(*map);
8080       result->set_elements(*parameter_map);
8081
8082       // Store the context and the arguments array at the beginning of the
8083       // parameter map.
8084       Handle<Context> context(isolate->context());
8085       Handle<FixedArray> arguments =
8086           isolate->factory()->NewFixedArray(argument_count, NOT_TENURED);
8087       parameter_map->set(0, *context);
8088       parameter_map->set(1, *arguments);
8089
8090       // Loop over the actual parameters backwards.
8091       int index = argument_count - 1;
8092       while (index >= mapped_count) {
8093         // These go directly in the arguments array and have no
8094         // corresponding slot in the parameter map.
8095         arguments->set(index, *(parameters - index - 1));
8096         --index;
8097       }
8098
8099       Handle<ScopeInfo> scope_info(callee->shared()->scope_info());
8100       while (index >= 0) {
8101         // Detect duplicate names to the right in the parameter list.
8102         Handle<String> name(scope_info->ParameterName(index));
8103         int context_local_count = scope_info->ContextLocalCount();
8104         bool duplicate = false;
8105         for (int j = index + 1; j < parameter_count; ++j) {
8106           if (scope_info->ParameterName(j) == *name) {
8107             duplicate = true;
8108             break;
8109           }
8110         }
8111
8112         if (duplicate) {
8113           // This goes directly in the arguments array with a hole in the
8114           // parameter map.
8115           arguments->set(index, *(parameters - index - 1));
8116           parameter_map->set_the_hole(index + 2);
8117         } else {
8118           // The context index goes in the parameter map with a hole in the
8119           // arguments array.
8120           int context_index = -1;
8121           for (int j = 0; j < context_local_count; ++j) {
8122             if (scope_info->ContextLocalName(j) == *name) {
8123               context_index = j;
8124               break;
8125             }
8126           }
8127           DCHECK(context_index >= 0);
8128           arguments->set_the_hole(index);
8129           parameter_map->set(index + 2, Smi::FromInt(
8130               Context::MIN_CONTEXT_SLOTS + context_index));
8131         }
8132
8133         --index;
8134       }
8135     } else {
8136       // If there is no aliasing, the arguments object elements are not
8137       // special in any way.
8138       Handle<FixedArray> elements =
8139           isolate->factory()->NewFixedArray(argument_count, NOT_TENURED);
8140       result->set_elements(*elements);
8141       for (int i = 0; i < argument_count; ++i) {
8142         elements->set(i, *(parameters - i - 1));
8143       }
8144     }
8145   }
8146   return result;
8147 }
8148
8149
8150 static Handle<JSObject> NewStrictArguments(Isolate* isolate,
8151                                            Handle<JSFunction> callee,
8152                                            Object** parameters,
8153                                            int argument_count) {
8154   Handle<JSObject> result =
8155       isolate->factory()->NewArgumentsObject(callee, argument_count);
8156
8157   if (argument_count > 0) {
8158     Handle<FixedArray> array =
8159         isolate->factory()->NewUninitializedFixedArray(argument_count);
8160     DisallowHeapAllocation no_gc;
8161     WriteBarrierMode mode = array->GetWriteBarrierMode(no_gc);
8162     for (int i = 0; i < argument_count; i++) {
8163       array->set(i, *--parameters, mode);
8164     }
8165     result->set_elements(*array);
8166   }
8167   return result;
8168 }
8169
8170
8171 RUNTIME_FUNCTION(Runtime_NewArguments) {
8172   HandleScope scope(isolate);
8173   DCHECK(args.length() == 1);
8174   CONVERT_ARG_HANDLE_CHECKED(JSFunction, callee, 0);
8175   JavaScriptFrameIterator it(isolate);
8176
8177   // Find the frame that holds the actual arguments passed to the function.
8178   it.AdvanceToArgumentsFrame();
8179   JavaScriptFrame* frame = it.frame();
8180
8181   // Determine parameter location on the stack and dispatch on language mode.
8182   int argument_count = frame->GetArgumentsLength();
8183   Object** parameters = reinterpret_cast<Object**>(frame->GetParameterSlot(-1));
8184   return callee->shared()->strict_mode() == STRICT
8185              ? *NewStrictArguments(isolate, callee, parameters, argument_count)
8186              : *NewSloppyArguments(isolate, callee, parameters, argument_count);
8187 }
8188
8189
8190 RUNTIME_FUNCTION(Runtime_NewSloppyArguments) {
8191   HandleScope scope(isolate);
8192   DCHECK(args.length() == 3);
8193   CONVERT_ARG_HANDLE_CHECKED(JSFunction, callee, 0);
8194   Object** parameters = reinterpret_cast<Object**>(args[1]);
8195   CONVERT_SMI_ARG_CHECKED(argument_count, 2);
8196   return *NewSloppyArguments(isolate, callee, parameters, argument_count);
8197 }
8198
8199
8200 RUNTIME_FUNCTION(Runtime_NewStrictArguments) {
8201   HandleScope scope(isolate);
8202   DCHECK(args.length() == 3);
8203   CONVERT_ARG_HANDLE_CHECKED(JSFunction, callee, 0)
8204   Object** parameters = reinterpret_cast<Object**>(args[1]);
8205   CONVERT_SMI_ARG_CHECKED(argument_count, 2);
8206   return *NewStrictArguments(isolate, callee, parameters, argument_count);
8207 }
8208
8209
8210 RUNTIME_FUNCTION(Runtime_NewClosureFromStubFailure) {
8211   HandleScope scope(isolate);
8212   DCHECK(args.length() == 1);
8213   CONVERT_ARG_HANDLE_CHECKED(SharedFunctionInfo, shared, 0);
8214   Handle<Context> context(isolate->context());
8215   PretenureFlag pretenure_flag = NOT_TENURED;
8216   return *isolate->factory()->NewFunctionFromSharedFunctionInfo(shared, context,
8217                                                                 pretenure_flag);
8218 }
8219
8220
8221 RUNTIME_FUNCTION(Runtime_NewClosure) {
8222   HandleScope scope(isolate);
8223   DCHECK(args.length() == 3);
8224   CONVERT_ARG_HANDLE_CHECKED(Context, context, 0);
8225   CONVERT_ARG_HANDLE_CHECKED(SharedFunctionInfo, shared, 1);
8226   CONVERT_BOOLEAN_ARG_CHECKED(pretenure, 2);
8227
8228   // The caller ensures that we pretenure closures that are assigned
8229   // directly to properties.
8230   PretenureFlag pretenure_flag = pretenure ? TENURED : NOT_TENURED;
8231   return *isolate->factory()->NewFunctionFromSharedFunctionInfo(
8232       shared, context, pretenure_flag);
8233 }
8234
8235
8236 // Find the arguments of the JavaScript function invocation that called
8237 // into C++ code. Collect these in a newly allocated array of handles (possibly
8238 // prefixed by a number of empty handles).
8239 static SmartArrayPointer<Handle<Object> > GetCallerArguments(
8240     Isolate* isolate,
8241     int prefix_argc,
8242     int* total_argc) {
8243   // Find frame containing arguments passed to the caller.
8244   JavaScriptFrameIterator it(isolate);
8245   JavaScriptFrame* frame = it.frame();
8246   List<JSFunction*> functions(2);
8247   frame->GetFunctions(&functions);
8248   if (functions.length() > 1) {
8249     int inlined_jsframe_index = functions.length() - 1;
8250     JSFunction* inlined_function = functions[inlined_jsframe_index];
8251     SlotRefValueBuilder slot_refs(
8252         frame,
8253         inlined_jsframe_index,
8254         inlined_function->shared()->formal_parameter_count());
8255
8256     int args_count = slot_refs.args_length();
8257
8258     *total_argc = prefix_argc + args_count;
8259     SmartArrayPointer<Handle<Object> > param_data(
8260         NewArray<Handle<Object> >(*total_argc));
8261     slot_refs.Prepare(isolate);
8262     for (int i = 0; i < args_count; i++) {
8263       Handle<Object> val = slot_refs.GetNext(isolate, 0);
8264       param_data[prefix_argc + i] = val;
8265     }
8266     slot_refs.Finish(isolate);
8267
8268     return param_data;
8269   } else {
8270     it.AdvanceToArgumentsFrame();
8271     frame = it.frame();
8272     int args_count = frame->ComputeParametersCount();
8273
8274     *total_argc = prefix_argc + args_count;
8275     SmartArrayPointer<Handle<Object> > param_data(
8276         NewArray<Handle<Object> >(*total_argc));
8277     for (int i = 0; i < args_count; i++) {
8278       Handle<Object> val = Handle<Object>(frame->GetParameter(i), isolate);
8279       param_data[prefix_argc + i] = val;
8280     }
8281     return param_data;
8282   }
8283 }
8284
8285
8286 RUNTIME_FUNCTION(Runtime_FunctionBindArguments) {
8287   HandleScope scope(isolate);
8288   DCHECK(args.length() == 4);
8289   CONVERT_ARG_HANDLE_CHECKED(JSFunction, bound_function, 0);
8290   CONVERT_ARG_HANDLE_CHECKED(Object, bindee, 1);
8291   CONVERT_ARG_HANDLE_CHECKED(Object, this_object, 2);
8292   CONVERT_NUMBER_ARG_HANDLE_CHECKED(new_length, 3);
8293
8294   // TODO(lrn): Create bound function in C++ code from premade shared info.
8295   bound_function->shared()->set_bound(true);
8296   // Get all arguments of calling function (Function.prototype.bind).
8297   int argc = 0;
8298   SmartArrayPointer<Handle<Object> > arguments =
8299       GetCallerArguments(isolate, 0, &argc);
8300   // Don't count the this-arg.
8301   if (argc > 0) {
8302     RUNTIME_ASSERT(arguments[0].is_identical_to(this_object));
8303     argc--;
8304   } else {
8305     RUNTIME_ASSERT(this_object->IsUndefined());
8306   }
8307   // Initialize array of bindings (function, this, and any existing arguments
8308   // if the function was already bound).
8309   Handle<FixedArray> new_bindings;
8310   int i;
8311   if (bindee->IsJSFunction() && JSFunction::cast(*bindee)->shared()->bound()) {
8312     Handle<FixedArray> old_bindings(
8313         JSFunction::cast(*bindee)->function_bindings());
8314     RUNTIME_ASSERT(old_bindings->length() > JSFunction::kBoundFunctionIndex);
8315     new_bindings =
8316         isolate->factory()->NewFixedArray(old_bindings->length() + argc);
8317     bindee = Handle<Object>(old_bindings->get(JSFunction::kBoundFunctionIndex),
8318                             isolate);
8319     i = 0;
8320     for (int n = old_bindings->length(); i < n; i++) {
8321       new_bindings->set(i, old_bindings->get(i));
8322     }
8323   } else {
8324     int array_size = JSFunction::kBoundArgumentsStartIndex + argc;
8325     new_bindings = isolate->factory()->NewFixedArray(array_size);
8326     new_bindings->set(JSFunction::kBoundFunctionIndex, *bindee);
8327     new_bindings->set(JSFunction::kBoundThisIndex, *this_object);
8328     i = 2;
8329   }
8330   // Copy arguments, skipping the first which is "this_arg".
8331   for (int j = 0; j < argc; j++, i++) {
8332     new_bindings->set(i, *arguments[j + 1]);
8333   }
8334   new_bindings->set_map_no_write_barrier(
8335       isolate->heap()->fixed_cow_array_map());
8336   bound_function->set_function_bindings(*new_bindings);
8337
8338   // Update length. Have to remove the prototype first so that map migration
8339   // is happy about the number of fields.
8340   RUNTIME_ASSERT(bound_function->RemovePrototype());
8341   Handle<Map> bound_function_map(
8342       isolate->native_context()->bound_function_map());
8343   JSObject::MigrateToMap(bound_function, bound_function_map);
8344   Handle<String> length_string = isolate->factory()->length_string();
8345   PropertyAttributes attr =
8346       static_cast<PropertyAttributes>(DONT_DELETE | DONT_ENUM | READ_ONLY);
8347   RETURN_FAILURE_ON_EXCEPTION(
8348       isolate,
8349       JSObject::SetOwnPropertyIgnoreAttributes(
8350           bound_function, length_string, new_length, attr));
8351   return *bound_function;
8352 }
8353
8354
8355 RUNTIME_FUNCTION(Runtime_BoundFunctionGetBindings) {
8356   HandleScope handles(isolate);
8357   DCHECK(args.length() == 1);
8358   CONVERT_ARG_HANDLE_CHECKED(JSReceiver, callable, 0);
8359   if (callable->IsJSFunction()) {
8360     Handle<JSFunction> function = Handle<JSFunction>::cast(callable);
8361     if (function->shared()->bound()) {
8362       Handle<FixedArray> bindings(function->function_bindings());
8363       RUNTIME_ASSERT(bindings->map() == isolate->heap()->fixed_cow_array_map());
8364       return *isolate->factory()->NewJSArrayWithElements(bindings);
8365     }
8366   }
8367   return isolate->heap()->undefined_value();
8368 }
8369
8370
8371 RUNTIME_FUNCTION(Runtime_NewObjectFromBound) {
8372   HandleScope scope(isolate);
8373   DCHECK(args.length() == 1);
8374   // First argument is a function to use as a constructor.
8375   CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
8376   RUNTIME_ASSERT(function->shared()->bound());
8377
8378   // The argument is a bound function. Extract its bound arguments
8379   // and callable.
8380   Handle<FixedArray> bound_args =
8381       Handle<FixedArray>(FixedArray::cast(function->function_bindings()));
8382   int bound_argc = bound_args->length() - JSFunction::kBoundArgumentsStartIndex;
8383   Handle<Object> bound_function(
8384       JSReceiver::cast(bound_args->get(JSFunction::kBoundFunctionIndex)),
8385       isolate);
8386   DCHECK(!bound_function->IsJSFunction() ||
8387          !Handle<JSFunction>::cast(bound_function)->shared()->bound());
8388
8389   int total_argc = 0;
8390   SmartArrayPointer<Handle<Object> > param_data =
8391       GetCallerArguments(isolate, bound_argc, &total_argc);
8392   for (int i = 0; i < bound_argc; i++) {
8393     param_data[i] = Handle<Object>(bound_args->get(
8394         JSFunction::kBoundArgumentsStartIndex + i), isolate);
8395   }
8396
8397   if (!bound_function->IsJSFunction()) {
8398     ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
8399         isolate, bound_function,
8400         Execution::TryGetConstructorDelegate(isolate, bound_function));
8401   }
8402   DCHECK(bound_function->IsJSFunction());
8403
8404   Handle<Object> result;
8405   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
8406       isolate, result,
8407       Execution::New(Handle<JSFunction>::cast(bound_function),
8408                      total_argc, param_data.get()));
8409   return *result;
8410 }
8411
8412
8413 static Object* Runtime_NewObjectHelper(Isolate* isolate,
8414                                             Handle<Object> constructor,
8415                                             Handle<AllocationSite> site) {
8416   // If the constructor isn't a proper function we throw a type error.
8417   if (!constructor->IsJSFunction()) {
8418     Vector< Handle<Object> > arguments = HandleVector(&constructor, 1);
8419     THROW_NEW_ERROR_RETURN_FAILURE(isolate,
8420                                    NewTypeError("not_constructor", arguments));
8421   }
8422
8423   Handle<JSFunction> function = Handle<JSFunction>::cast(constructor);
8424
8425   // If function should not have prototype, construction is not allowed. In this
8426   // case generated code bailouts here, since function has no initial_map.
8427   if (!function->should_have_prototype() && !function->shared()->bound()) {
8428     Vector< Handle<Object> > arguments = HandleVector(&constructor, 1);
8429     THROW_NEW_ERROR_RETURN_FAILURE(isolate,
8430                                    NewTypeError("not_constructor", arguments));
8431   }
8432
8433   Debug* debug = isolate->debug();
8434   // Handle stepping into constructors if step into is active.
8435   if (debug->StepInActive()) {
8436     debug->HandleStepIn(function, Handle<Object>::null(), 0, true);
8437   }
8438
8439   if (function->has_initial_map()) {
8440     if (function->initial_map()->instance_type() == JS_FUNCTION_TYPE) {
8441       // The 'Function' function ignores the receiver object when
8442       // called using 'new' and creates a new JSFunction object that
8443       // is returned.  The receiver object is only used for error
8444       // reporting if an error occurs when constructing the new
8445       // JSFunction. Factory::NewJSObject() should not be used to
8446       // allocate JSFunctions since it does not properly initialize
8447       // the shared part of the function. Since the receiver is
8448       // ignored anyway, we use the global object as the receiver
8449       // instead of a new JSFunction object. This way, errors are
8450       // reported the same way whether or not 'Function' is called
8451       // using 'new'.
8452       return isolate->global_proxy();
8453     }
8454   }
8455
8456   // The function should be compiled for the optimization hints to be
8457   // available.
8458   Compiler::EnsureCompiled(function, CLEAR_EXCEPTION);
8459
8460   Handle<JSObject> result;
8461   if (site.is_null()) {
8462     result = isolate->factory()->NewJSObject(function);
8463   } else {
8464     result = isolate->factory()->NewJSObjectWithMemento(function, site);
8465   }
8466
8467   isolate->counters()->constructed_objects()->Increment();
8468   isolate->counters()->constructed_objects_runtime()->Increment();
8469
8470   return *result;
8471 }
8472
8473
8474 RUNTIME_FUNCTION(Runtime_NewObject) {
8475   HandleScope scope(isolate);
8476   DCHECK(args.length() == 1);
8477   CONVERT_ARG_HANDLE_CHECKED(Object, constructor, 0);
8478   return Runtime_NewObjectHelper(isolate,
8479                                  constructor,
8480                                  Handle<AllocationSite>::null());
8481 }
8482
8483
8484 RUNTIME_FUNCTION(Runtime_NewObjectWithAllocationSite) {
8485   HandleScope scope(isolate);
8486   DCHECK(args.length() == 2);
8487   CONVERT_ARG_HANDLE_CHECKED(Object, constructor, 1);
8488   CONVERT_ARG_HANDLE_CHECKED(Object, feedback, 0);
8489   Handle<AllocationSite> site;
8490   if (feedback->IsAllocationSite()) {
8491     // The feedback can be an AllocationSite or undefined.
8492     site = Handle<AllocationSite>::cast(feedback);
8493   }
8494   return Runtime_NewObjectHelper(isolate, constructor, site);
8495 }
8496
8497
8498 RUNTIME_FUNCTION(Runtime_FinalizeInstanceSize) {
8499   HandleScope scope(isolate);
8500   DCHECK(args.length() == 1);
8501
8502   CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
8503   function->CompleteInobjectSlackTracking();
8504
8505   return isolate->heap()->undefined_value();
8506 }
8507
8508
8509 RUNTIME_FUNCTION(Runtime_CompileLazy) {
8510   HandleScope scope(isolate);
8511   DCHECK(args.length() == 1);
8512   CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
8513 #ifdef DEBUG
8514   if (FLAG_trace_lazy && !function->shared()->is_compiled()) {
8515     PrintF("[unoptimized: ");
8516     function->PrintName();
8517     PrintF("]\n");
8518   }
8519 #endif
8520
8521   // Compile the target function.
8522   DCHECK(function->shared()->allows_lazy_compilation());
8523
8524   Handle<Code> code;
8525   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, code,
8526                                      Compiler::GetLazyCode(function));
8527   DCHECK(code->kind() == Code::FUNCTION ||
8528          code->kind() == Code::OPTIMIZED_FUNCTION);
8529   function->ReplaceCode(*code);
8530   return *code;
8531 }
8532
8533
8534 RUNTIME_FUNCTION(Runtime_CompileOptimized) {
8535   HandleScope scope(isolate);
8536   DCHECK(args.length() == 2);
8537   CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
8538   CONVERT_BOOLEAN_ARG_CHECKED(concurrent, 1);
8539
8540   Handle<Code> unoptimized(function->shared()->code());
8541   if (!isolate->use_crankshaft() ||
8542       function->shared()->optimization_disabled() ||
8543       isolate->DebuggerHasBreakPoints()) {
8544     // If the function is not optimizable or debugger is active continue
8545     // using the code from the full compiler.
8546     if (FLAG_trace_opt) {
8547       PrintF("[failed to optimize ");
8548       function->PrintName();
8549       PrintF(": is code optimizable: %s, is debugger enabled: %s]\n",
8550           function->shared()->optimization_disabled() ? "F" : "T",
8551           isolate->DebuggerHasBreakPoints() ? "T" : "F");
8552     }
8553     function->ReplaceCode(*unoptimized);
8554     return function->code();
8555   }
8556
8557   Compiler::ConcurrencyMode mode =
8558       concurrent ? Compiler::CONCURRENT : Compiler::NOT_CONCURRENT;
8559   Handle<Code> code;
8560   if (Compiler::GetOptimizedCode(function, unoptimized, mode).ToHandle(&code)) {
8561     function->ReplaceCode(*code);
8562   } else {
8563     function->ReplaceCode(function->shared()->code());
8564   }
8565
8566   DCHECK(function->code()->kind() == Code::FUNCTION ||
8567          function->code()->kind() == Code::OPTIMIZED_FUNCTION ||
8568          function->IsInOptimizationQueue());
8569   return function->code();
8570 }
8571
8572
8573 class ActivationsFinder : public ThreadVisitor {
8574  public:
8575   Code* code_;
8576   bool has_code_activations_;
8577
8578   explicit ActivationsFinder(Code* code)
8579     : code_(code),
8580       has_code_activations_(false) { }
8581
8582   void VisitThread(Isolate* isolate, ThreadLocalTop* top) {
8583     JavaScriptFrameIterator it(isolate, top);
8584     VisitFrames(&it);
8585   }
8586
8587   void VisitFrames(JavaScriptFrameIterator* it) {
8588     for (; !it->done(); it->Advance()) {
8589       JavaScriptFrame* frame = it->frame();
8590       if (code_->contains(frame->pc())) has_code_activations_ = true;
8591     }
8592   }
8593 };
8594
8595
8596 RUNTIME_FUNCTION(Runtime_NotifyStubFailure) {
8597   HandleScope scope(isolate);
8598   DCHECK(args.length() == 0);
8599   Deoptimizer* deoptimizer = Deoptimizer::Grab(isolate);
8600   DCHECK(AllowHeapAllocation::IsAllowed());
8601   delete deoptimizer;
8602   return isolate->heap()->undefined_value();
8603 }
8604
8605
8606 RUNTIME_FUNCTION(Runtime_NotifyDeoptimized) {
8607   HandleScope scope(isolate);
8608   DCHECK(args.length() == 1);
8609   CONVERT_SMI_ARG_CHECKED(type_arg, 0);
8610   Deoptimizer::BailoutType type =
8611       static_cast<Deoptimizer::BailoutType>(type_arg);
8612   Deoptimizer* deoptimizer = Deoptimizer::Grab(isolate);
8613   DCHECK(AllowHeapAllocation::IsAllowed());
8614
8615   Handle<JSFunction> function = deoptimizer->function();
8616   Handle<Code> optimized_code = deoptimizer->compiled_code();
8617
8618   DCHECK(optimized_code->kind() == Code::OPTIMIZED_FUNCTION);
8619   DCHECK(type == deoptimizer->bailout_type());
8620
8621   // Make sure to materialize objects before causing any allocation.
8622   JavaScriptFrameIterator it(isolate);
8623   deoptimizer->MaterializeHeapObjects(&it);
8624   delete deoptimizer;
8625
8626   JavaScriptFrame* frame = it.frame();
8627   RUNTIME_ASSERT(frame->function()->IsJSFunction());
8628   DCHECK(frame->function() == *function);
8629
8630   // Avoid doing too much work when running with --always-opt and keep
8631   // the optimized code around.
8632   if (FLAG_always_opt || type == Deoptimizer::LAZY) {
8633     return isolate->heap()->undefined_value();
8634   }
8635
8636   // Search for other activations of the same function and code.
8637   ActivationsFinder activations_finder(*optimized_code);
8638   activations_finder.VisitFrames(&it);
8639   isolate->thread_manager()->IterateArchivedThreads(&activations_finder);
8640
8641   if (!activations_finder.has_code_activations_) {
8642     if (function->code() == *optimized_code) {
8643       if (FLAG_trace_deopt) {
8644         PrintF("[removing optimized code for: ");
8645         function->PrintName();
8646         PrintF("]\n");
8647       }
8648       function->ReplaceCode(function->shared()->code());
8649       // Evict optimized code for this function from the cache so that it
8650       // doesn't get used for new closures.
8651       function->shared()->EvictFromOptimizedCodeMap(*optimized_code,
8652                                                     "notify deoptimized");
8653     }
8654   } else {
8655     // TODO(titzer): we should probably do DeoptimizeCodeList(code)
8656     // unconditionally if the code is not already marked for deoptimization.
8657     // If there is an index by shared function info, all the better.
8658     Deoptimizer::DeoptimizeFunction(*function);
8659   }
8660
8661   return isolate->heap()->undefined_value();
8662 }
8663
8664
8665 RUNTIME_FUNCTION(Runtime_DeoptimizeFunction) {
8666   HandleScope scope(isolate);
8667   DCHECK(args.length() == 1);
8668   CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
8669   if (!function->IsOptimized()) return isolate->heap()->undefined_value();
8670
8671   // TODO(turbofan): Deoptimization is not supported yet.
8672   if (function->code()->is_turbofanned() && !FLAG_turbo_deoptimization) {
8673     return isolate->heap()->undefined_value();
8674   }
8675
8676   Deoptimizer::DeoptimizeFunction(*function);
8677
8678   return isolate->heap()->undefined_value();
8679 }
8680
8681
8682 RUNTIME_FUNCTION(Runtime_ClearFunctionTypeFeedback) {
8683   HandleScope scope(isolate);
8684   DCHECK(args.length() == 1);
8685   CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
8686   function->shared()->ClearTypeFeedbackInfo();
8687   Code* unoptimized = function->shared()->code();
8688   if (unoptimized->kind() == Code::FUNCTION) {
8689     unoptimized->ClearInlineCaches();
8690   }
8691   return isolate->heap()->undefined_value();
8692 }
8693
8694
8695 RUNTIME_FUNCTION(Runtime_RunningInSimulator) {
8696   SealHandleScope shs(isolate);
8697   DCHECK(args.length() == 0);
8698 #if defined(USE_SIMULATOR)
8699   return isolate->heap()->true_value();
8700 #else
8701   return isolate->heap()->false_value();
8702 #endif
8703 }
8704
8705
8706 RUNTIME_FUNCTION(Runtime_IsConcurrentRecompilationSupported) {
8707   SealHandleScope shs(isolate);
8708   DCHECK(args.length() == 0);
8709   return isolate->heap()->ToBoolean(
8710       isolate->concurrent_recompilation_enabled());
8711 }
8712
8713
8714 RUNTIME_FUNCTION(Runtime_OptimizeFunctionOnNextCall) {
8715   HandleScope scope(isolate);
8716   RUNTIME_ASSERT(args.length() == 1 || args.length() == 2);
8717   CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
8718   // The following two assertions are lifted from the DCHECKs inside
8719   // JSFunction::MarkForOptimization().
8720   RUNTIME_ASSERT(!function->shared()->is_generator());
8721   RUNTIME_ASSERT(function->shared()->allows_lazy_compilation() ||
8722                  (function->code()->kind() == Code::FUNCTION &&
8723                   function->code()->optimizable()));
8724
8725   // If the function is optimized, just return.
8726   if (function->IsOptimized()) return isolate->heap()->undefined_value();
8727
8728   function->MarkForOptimization();
8729
8730   Code* unoptimized = function->shared()->code();
8731   if (args.length() == 2 &&
8732       unoptimized->kind() == Code::FUNCTION) {
8733     CONVERT_ARG_HANDLE_CHECKED(String, type, 1);
8734     if (type->IsOneByteEqualTo(STATIC_CHAR_VECTOR("osr")) && FLAG_use_osr) {
8735       // Start patching from the currently patched loop nesting level.
8736       DCHECK(BackEdgeTable::Verify(isolate, unoptimized));
8737       isolate->runtime_profiler()->AttemptOnStackReplacement(
8738           *function, Code::kMaxLoopNestingMarker);
8739     } else if (type->IsOneByteEqualTo(STATIC_CHAR_VECTOR("concurrent")) &&
8740                isolate->concurrent_recompilation_enabled()) {
8741       function->MarkForConcurrentOptimization();
8742     }
8743   }
8744
8745   return isolate->heap()->undefined_value();
8746 }
8747
8748
8749 RUNTIME_FUNCTION(Runtime_NeverOptimizeFunction) {
8750   HandleScope scope(isolate);
8751   DCHECK(args.length() == 1);
8752   CONVERT_ARG_CHECKED(JSFunction, function, 0);
8753   function->shared()->set_optimization_disabled(true);
8754   return isolate->heap()->undefined_value();
8755 }
8756
8757
8758 RUNTIME_FUNCTION(Runtime_GetOptimizationStatus) {
8759   HandleScope scope(isolate);
8760   RUNTIME_ASSERT(args.length() == 1 || args.length() == 2);
8761   if (!isolate->use_crankshaft()) {
8762     return Smi::FromInt(4);  // 4 == "never".
8763   }
8764   bool sync_with_compiler_thread = true;
8765   if (args.length() == 2) {
8766     CONVERT_ARG_HANDLE_CHECKED(String, sync, 1);
8767     if (sync->IsOneByteEqualTo(STATIC_CHAR_VECTOR("no sync"))) {
8768       sync_with_compiler_thread = false;
8769     }
8770   }
8771   CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
8772   if (isolate->concurrent_recompilation_enabled() &&
8773       sync_with_compiler_thread) {
8774     while (function->IsInOptimizationQueue()) {
8775       isolate->optimizing_compiler_thread()->InstallOptimizedFunctions();
8776       base::OS::Sleep(50);
8777     }
8778   }
8779   if (FLAG_always_opt) {
8780     // We may have always opt, but that is more best-effort than a real
8781     // promise, so we still say "no" if it is not optimized.
8782     return function->IsOptimized() ? Smi::FromInt(3)   // 3 == "always".
8783                                    : Smi::FromInt(2);  // 2 == "no".
8784   }
8785   if (FLAG_deopt_every_n_times) {
8786     return Smi::FromInt(6);  // 6 == "maybe deopted".
8787   }
8788   if (function->IsOptimized() && function->code()->is_turbofanned()) {
8789     return Smi::FromInt(7);  // 7 == "TurboFan compiler".
8790   }
8791   return function->IsOptimized() ? Smi::FromInt(1)   // 1 == "yes".
8792                                  : Smi::FromInt(2);  // 2 == "no".
8793 }
8794
8795
8796 RUNTIME_FUNCTION(Runtime_UnblockConcurrentRecompilation) {
8797   DCHECK(args.length() == 0);
8798   RUNTIME_ASSERT(FLAG_block_concurrent_recompilation);
8799   RUNTIME_ASSERT(isolate->concurrent_recompilation_enabled());
8800   isolate->optimizing_compiler_thread()->Unblock();
8801   return isolate->heap()->undefined_value();
8802 }
8803
8804
8805 RUNTIME_FUNCTION(Runtime_GetOptimizationCount) {
8806   HandleScope scope(isolate);
8807   DCHECK(args.length() == 1);
8808   CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
8809   return Smi::FromInt(function->shared()->opt_count());
8810 }
8811
8812
8813 static bool IsSuitableForOnStackReplacement(Isolate* isolate,
8814                                             Handle<JSFunction> function,
8815                                             Handle<Code> current_code) {
8816   // Keep track of whether we've succeeded in optimizing.
8817   if (!isolate->use_crankshaft() || !current_code->optimizable()) return false;
8818   // If we are trying to do OSR when there are already optimized
8819   // activations of the function, it means (a) the function is directly or
8820   // indirectly recursive and (b) an optimized invocation has been
8821   // deoptimized so that we are currently in an unoptimized activation.
8822   // Check for optimized activations of this function.
8823   for (JavaScriptFrameIterator it(isolate); !it.done(); it.Advance()) {
8824     JavaScriptFrame* frame = it.frame();
8825     if (frame->is_optimized() && frame->function() == *function) return false;
8826   }
8827
8828   return true;
8829 }
8830
8831
8832 RUNTIME_FUNCTION(Runtime_CompileForOnStackReplacement) {
8833   HandleScope scope(isolate);
8834   DCHECK(args.length() == 1);
8835   CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
8836   Handle<Code> caller_code(function->shared()->code());
8837
8838   // We're not prepared to handle a function with arguments object.
8839   DCHECK(!function->shared()->uses_arguments());
8840
8841   RUNTIME_ASSERT(FLAG_use_osr);
8842
8843   // Passing the PC in the javascript frame from the caller directly is
8844   // not GC safe, so we walk the stack to get it.
8845   JavaScriptFrameIterator it(isolate);
8846   JavaScriptFrame* frame = it.frame();
8847   if (!caller_code->contains(frame->pc())) {
8848     // Code on the stack may not be the code object referenced by the shared
8849     // function info.  It may have been replaced to include deoptimization data.
8850     caller_code = Handle<Code>(frame->LookupCode());
8851   }
8852
8853   uint32_t pc_offset = static_cast<uint32_t>(
8854       frame->pc() - caller_code->instruction_start());
8855
8856 #ifdef DEBUG
8857   DCHECK_EQ(frame->function(), *function);
8858   DCHECK_EQ(frame->LookupCode(), *caller_code);
8859   DCHECK(caller_code->contains(frame->pc()));
8860 #endif  // DEBUG
8861
8862
8863   BailoutId ast_id = caller_code->TranslatePcOffsetToAstId(pc_offset);
8864   DCHECK(!ast_id.IsNone());
8865
8866   Compiler::ConcurrencyMode mode =
8867       isolate->concurrent_osr_enabled() &&
8868       (function->shared()->ast_node_count() > 512) ? Compiler::CONCURRENT
8869                                                    : Compiler::NOT_CONCURRENT;
8870   Handle<Code> result = Handle<Code>::null();
8871
8872   OptimizedCompileJob* job = NULL;
8873   if (mode == Compiler::CONCURRENT) {
8874     // Gate the OSR entry with a stack check.
8875     BackEdgeTable::AddStackCheck(caller_code, pc_offset);
8876     // Poll already queued compilation jobs.
8877     OptimizingCompilerThread* thread = isolate->optimizing_compiler_thread();
8878     if (thread->IsQueuedForOSR(function, ast_id)) {
8879       if (FLAG_trace_osr) {
8880         PrintF("[OSR - Still waiting for queued: ");
8881         function->PrintName();
8882         PrintF(" at AST id %d]\n", ast_id.ToInt());
8883       }
8884       return NULL;
8885     }
8886
8887     job = thread->FindReadyOSRCandidate(function, ast_id);
8888   }
8889
8890   if (job != NULL) {
8891     if (FLAG_trace_osr) {
8892       PrintF("[OSR - Found ready: ");
8893       function->PrintName();
8894       PrintF(" at AST id %d]\n", ast_id.ToInt());
8895     }
8896     result = Compiler::GetConcurrentlyOptimizedCode(job);
8897   } else if (IsSuitableForOnStackReplacement(isolate, function, caller_code)) {
8898     if (FLAG_trace_osr) {
8899       PrintF("[OSR - Compiling: ");
8900       function->PrintName();
8901       PrintF(" at AST id %d]\n", ast_id.ToInt());
8902     }
8903     MaybeHandle<Code> maybe_result = Compiler::GetOptimizedCode(
8904         function, caller_code, mode, ast_id);
8905     if (maybe_result.ToHandle(&result) &&
8906         result.is_identical_to(isolate->builtins()->InOptimizationQueue())) {
8907       // Optimization is queued.  Return to check later.
8908       return NULL;
8909     }
8910   }
8911
8912   // Revert the patched back edge table, regardless of whether OSR succeeds.
8913   BackEdgeTable::Revert(isolate, *caller_code);
8914
8915   // Check whether we ended up with usable optimized code.
8916   if (!result.is_null() && result->kind() == Code::OPTIMIZED_FUNCTION) {
8917     DeoptimizationInputData* data =
8918         DeoptimizationInputData::cast(result->deoptimization_data());
8919
8920     if (data->OsrPcOffset()->value() >= 0) {
8921       DCHECK(BailoutId(data->OsrAstId()->value()) == ast_id);
8922       if (FLAG_trace_osr) {
8923         PrintF("[OSR - Entry at AST id %d, offset %d in optimized code]\n",
8924                ast_id.ToInt(), data->OsrPcOffset()->value());
8925       }
8926       // TODO(titzer): this is a massive hack to make the deopt counts
8927       // match. Fix heuristics for reenabling optimizations!
8928       function->shared()->increment_deopt_count();
8929
8930       // TODO(titzer): Do not install code into the function.
8931       function->ReplaceCode(*result);
8932       return *result;
8933     }
8934   }
8935
8936   // Failed.
8937   if (FLAG_trace_osr) {
8938     PrintF("[OSR - Failed: ");
8939     function->PrintName();
8940     PrintF(" at AST id %d]\n", ast_id.ToInt());
8941   }
8942
8943   if (!function->IsOptimized()) {
8944     function->ReplaceCode(function->shared()->code());
8945   }
8946   return NULL;
8947 }
8948
8949
8950 RUNTIME_FUNCTION(Runtime_SetAllocationTimeout) {
8951   SealHandleScope shs(isolate);
8952   DCHECK(args.length() == 2 || args.length() == 3);
8953 #ifdef DEBUG
8954   CONVERT_SMI_ARG_CHECKED(interval, 0);
8955   CONVERT_SMI_ARG_CHECKED(timeout, 1);
8956   isolate->heap()->set_allocation_timeout(timeout);
8957   FLAG_gc_interval = interval;
8958   if (args.length() == 3) {
8959     // Enable/disable inline allocation if requested.
8960     CONVERT_BOOLEAN_ARG_CHECKED(inline_allocation, 2);
8961     if (inline_allocation) {
8962       isolate->heap()->EnableInlineAllocation();
8963     } else {
8964       isolate->heap()->DisableInlineAllocation();
8965     }
8966   }
8967 #endif
8968   return isolate->heap()->undefined_value();
8969 }
8970
8971
8972 RUNTIME_FUNCTION(Runtime_CheckIsBootstrapping) {
8973   SealHandleScope shs(isolate);
8974   DCHECK(args.length() == 0);
8975   RUNTIME_ASSERT(isolate->bootstrapper()->IsActive());
8976   return isolate->heap()->undefined_value();
8977 }
8978
8979
8980 RUNTIME_FUNCTION(Runtime_GetRootNaN) {
8981   SealHandleScope shs(isolate);
8982   DCHECK(args.length() == 0);
8983   RUNTIME_ASSERT(isolate->bootstrapper()->IsActive());
8984   return isolate->heap()->nan_value();
8985 }
8986
8987
8988 RUNTIME_FUNCTION(Runtime_Call) {
8989   HandleScope scope(isolate);
8990   DCHECK(args.length() >= 2);
8991   int argc = args.length() - 2;
8992   CONVERT_ARG_CHECKED(JSReceiver, fun, argc + 1);
8993   Object* receiver = args[0];
8994
8995   // If there are too many arguments, allocate argv via malloc.
8996   const int argv_small_size = 10;
8997   Handle<Object> argv_small_buffer[argv_small_size];
8998   SmartArrayPointer<Handle<Object> > argv_large_buffer;
8999   Handle<Object>* argv = argv_small_buffer;
9000   if (argc > argv_small_size) {
9001     argv = new Handle<Object>[argc];
9002     if (argv == NULL) return isolate->StackOverflow();
9003     argv_large_buffer = SmartArrayPointer<Handle<Object> >(argv);
9004   }
9005
9006   for (int i = 0; i < argc; ++i) {
9007      argv[i] = Handle<Object>(args[1 + i], isolate);
9008   }
9009
9010   Handle<JSReceiver> hfun(fun);
9011   Handle<Object> hreceiver(receiver, isolate);
9012   Handle<Object> result;
9013   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
9014       isolate, result,
9015       Execution::Call(isolate, hfun, hreceiver, argc, argv, true));
9016   return *result;
9017 }
9018
9019
9020 RUNTIME_FUNCTION(Runtime_Apply) {
9021   HandleScope scope(isolate);
9022   DCHECK(args.length() == 5);
9023   CONVERT_ARG_HANDLE_CHECKED(JSReceiver, fun, 0);
9024   CONVERT_ARG_HANDLE_CHECKED(Object, receiver, 1);
9025   CONVERT_ARG_HANDLE_CHECKED(JSObject, arguments, 2);
9026   CONVERT_INT32_ARG_CHECKED(offset, 3);
9027   CONVERT_INT32_ARG_CHECKED(argc, 4);
9028   RUNTIME_ASSERT(offset >= 0);
9029   // Loose upper bound to allow fuzzing. We'll most likely run out of
9030   // stack space before hitting this limit.
9031   static int kMaxArgc = 1000000;
9032   RUNTIME_ASSERT(argc >= 0 && argc <= kMaxArgc);
9033
9034   // If there are too many arguments, allocate argv via malloc.
9035   const int argv_small_size = 10;
9036   Handle<Object> argv_small_buffer[argv_small_size];
9037   SmartArrayPointer<Handle<Object> > argv_large_buffer;
9038   Handle<Object>* argv = argv_small_buffer;
9039   if (argc > argv_small_size) {
9040     argv = new Handle<Object>[argc];
9041     if (argv == NULL) return isolate->StackOverflow();
9042     argv_large_buffer = SmartArrayPointer<Handle<Object> >(argv);
9043   }
9044
9045   for (int i = 0; i < argc; ++i) {
9046     ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
9047         isolate, argv[i],
9048         Object::GetElement(isolate, arguments, offset + i));
9049   }
9050
9051   Handle<Object> result;
9052   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
9053       isolate, result,
9054       Execution::Call(isolate, fun, receiver, argc, argv, true));
9055   return *result;
9056 }
9057
9058
9059 RUNTIME_FUNCTION(Runtime_GetFunctionDelegate) {
9060   HandleScope scope(isolate);
9061   DCHECK(args.length() == 1);
9062   CONVERT_ARG_HANDLE_CHECKED(Object, object, 0);
9063   RUNTIME_ASSERT(!object->IsJSFunction());
9064   return *Execution::GetFunctionDelegate(isolate, object);
9065 }
9066
9067
9068 RUNTIME_FUNCTION(Runtime_GetConstructorDelegate) {
9069   HandleScope scope(isolate);
9070   DCHECK(args.length() == 1);
9071   CONVERT_ARG_HANDLE_CHECKED(Object, object, 0);
9072   RUNTIME_ASSERT(!object->IsJSFunction());
9073   return *Execution::GetConstructorDelegate(isolate, object);
9074 }
9075
9076
9077 RUNTIME_FUNCTION(Runtime_NewGlobalContext) {
9078   HandleScope scope(isolate);
9079   DCHECK(args.length() == 2);
9080
9081   CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
9082   CONVERT_ARG_HANDLE_CHECKED(ScopeInfo, scope_info, 1);
9083   Handle<Context> result =
9084       isolate->factory()->NewGlobalContext(function, scope_info);
9085
9086   DCHECK(function->context() == isolate->context());
9087   DCHECK(function->context()->global_object() == result->global_object());
9088   result->global_object()->set_global_context(*result);
9089   return *result;
9090 }
9091
9092
9093 RUNTIME_FUNCTION(Runtime_NewFunctionContext) {
9094   HandleScope scope(isolate);
9095   DCHECK(args.length() == 1);
9096
9097   CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
9098
9099   DCHECK(function->context() == isolate->context());
9100   int length = function->shared()->scope_info()->ContextLength();
9101   return *isolate->factory()->NewFunctionContext(length, function);
9102 }
9103
9104
9105 RUNTIME_FUNCTION(Runtime_PushWithContext) {
9106   HandleScope scope(isolate);
9107   DCHECK(args.length() == 2);
9108   Handle<JSReceiver> extension_object;
9109   if (args[0]->IsJSReceiver()) {
9110     extension_object = args.at<JSReceiver>(0);
9111   } else {
9112     // Try to convert the object to a proper JavaScript object.
9113     MaybeHandle<JSReceiver> maybe_object =
9114         Object::ToObject(isolate, args.at<Object>(0));
9115     if (!maybe_object.ToHandle(&extension_object)) {
9116       Handle<Object> handle = args.at<Object>(0);
9117       THROW_NEW_ERROR_RETURN_FAILURE(
9118           isolate, NewTypeError("with_expression", HandleVector(&handle, 1)));
9119     }
9120   }
9121
9122   Handle<JSFunction> function;
9123   if (args[1]->IsSmi()) {
9124     // A smi sentinel indicates a context nested inside global code rather
9125     // than some function.  There is a canonical empty function that can be
9126     // gotten from the native context.
9127     function = handle(isolate->native_context()->closure());
9128   } else {
9129     function = args.at<JSFunction>(1);
9130   }
9131
9132   Handle<Context> current(isolate->context());
9133   Handle<Context> context = isolate->factory()->NewWithContext(
9134       function, current, extension_object);
9135   isolate->set_context(*context);
9136   return *context;
9137 }
9138
9139
9140 RUNTIME_FUNCTION(Runtime_PushCatchContext) {
9141   HandleScope scope(isolate);
9142   DCHECK(args.length() == 3);
9143   CONVERT_ARG_HANDLE_CHECKED(String, name, 0);
9144   CONVERT_ARG_HANDLE_CHECKED(Object, thrown_object, 1);
9145   Handle<JSFunction> function;
9146   if (args[2]->IsSmi()) {
9147     // A smi sentinel indicates a context nested inside global code rather
9148     // than some function.  There is a canonical empty function that can be
9149     // gotten from the native context.
9150     function = handle(isolate->native_context()->closure());
9151   } else {
9152     function = args.at<JSFunction>(2);
9153   }
9154   Handle<Context> current(isolate->context());
9155   Handle<Context> context = isolate->factory()->NewCatchContext(
9156       function, current, name, thrown_object);
9157   isolate->set_context(*context);
9158   return *context;
9159 }
9160
9161
9162 RUNTIME_FUNCTION(Runtime_PushBlockContext) {
9163   HandleScope scope(isolate);
9164   DCHECK(args.length() == 2);
9165   CONVERT_ARG_HANDLE_CHECKED(ScopeInfo, scope_info, 0);
9166   Handle<JSFunction> function;
9167   if (args[1]->IsSmi()) {
9168     // A smi sentinel indicates a context nested inside global code rather
9169     // than some function.  There is a canonical empty function that can be
9170     // gotten from the native context.
9171     function = handle(isolate->native_context()->closure());
9172   } else {
9173     function = args.at<JSFunction>(1);
9174   }
9175   Handle<Context> current(isolate->context());
9176   Handle<Context> context = isolate->factory()->NewBlockContext(
9177       function, current, scope_info);
9178   isolate->set_context(*context);
9179   return *context;
9180 }
9181
9182
9183 RUNTIME_FUNCTION(Runtime_IsJSModule) {
9184   SealHandleScope shs(isolate);
9185   DCHECK(args.length() == 1);
9186   CONVERT_ARG_CHECKED(Object, obj, 0);
9187   return isolate->heap()->ToBoolean(obj->IsJSModule());
9188 }
9189
9190
9191 RUNTIME_FUNCTION(Runtime_PushModuleContext) {
9192   SealHandleScope shs(isolate);
9193   DCHECK(args.length() == 2);
9194   CONVERT_SMI_ARG_CHECKED(index, 0);
9195
9196   if (!args[1]->IsScopeInfo()) {
9197     // Module already initialized. Find hosting context and retrieve context.
9198     Context* host = Context::cast(isolate->context())->global_context();
9199     Context* context = Context::cast(host->get(index));
9200     DCHECK(context->previous() == isolate->context());
9201     isolate->set_context(context);
9202     return context;
9203   }
9204
9205   CONVERT_ARG_HANDLE_CHECKED(ScopeInfo, scope_info, 1);
9206
9207   // Allocate module context.
9208   HandleScope scope(isolate);
9209   Factory* factory = isolate->factory();
9210   Handle<Context> context = factory->NewModuleContext(scope_info);
9211   Handle<JSModule> module = factory->NewJSModule(context, scope_info);
9212   context->set_module(*module);
9213   Context* previous = isolate->context();
9214   context->set_previous(previous);
9215   context->set_closure(previous->closure());
9216   context->set_global_object(previous->global_object());
9217   isolate->set_context(*context);
9218
9219   // Find hosting scope and initialize internal variable holding module there.
9220   previous->global_context()->set(index, *context);
9221
9222   return *context;
9223 }
9224
9225
9226 RUNTIME_FUNCTION(Runtime_DeclareModules) {
9227   HandleScope scope(isolate);
9228   DCHECK(args.length() == 1);
9229   CONVERT_ARG_HANDLE_CHECKED(FixedArray, descriptions, 0);
9230   Context* host_context = isolate->context();
9231
9232   for (int i = 0; i < descriptions->length(); ++i) {
9233     Handle<ModuleInfo> description(ModuleInfo::cast(descriptions->get(i)));
9234     int host_index = description->host_index();
9235     Handle<Context> context(Context::cast(host_context->get(host_index)));
9236     Handle<JSModule> module(context->module());
9237
9238     for (int j = 0; j < description->length(); ++j) {
9239       Handle<String> name(description->name(j));
9240       VariableMode mode = description->mode(j);
9241       int index = description->index(j);
9242       switch (mode) {
9243         case VAR:
9244         case LET:
9245         case CONST:
9246         case CONST_LEGACY: {
9247           PropertyAttributes attr =
9248               IsImmutableVariableMode(mode) ? FROZEN : SEALED;
9249           Handle<AccessorInfo> info =
9250               Accessors::MakeModuleExport(name, index, attr);
9251           Handle<Object> result =
9252               JSObject::SetAccessor(module, info).ToHandleChecked();
9253           DCHECK(!result->IsUndefined());
9254           USE(result);
9255           break;
9256         }
9257         case MODULE: {
9258           Object* referenced_context = Context::cast(host_context)->get(index);
9259           Handle<JSModule> value(Context::cast(referenced_context)->module());
9260           JSObject::SetOwnPropertyIgnoreAttributes(module, name, value, FROZEN)
9261               .Assert();
9262           break;
9263         }
9264         case INTERNAL:
9265         case TEMPORARY:
9266         case DYNAMIC:
9267         case DYNAMIC_GLOBAL:
9268         case DYNAMIC_LOCAL:
9269           UNREACHABLE();
9270       }
9271     }
9272
9273     JSObject::PreventExtensions(module).Assert();
9274   }
9275
9276   DCHECK(!isolate->has_pending_exception());
9277   return isolate->heap()->undefined_value();
9278 }
9279
9280
9281 RUNTIME_FUNCTION(Runtime_DeleteLookupSlot) {
9282   HandleScope scope(isolate);
9283   DCHECK(args.length() == 2);
9284
9285   CONVERT_ARG_HANDLE_CHECKED(Context, context, 0);
9286   CONVERT_ARG_HANDLE_CHECKED(String, name, 1);
9287
9288   int index;
9289   PropertyAttributes attributes;
9290   ContextLookupFlags flags = FOLLOW_CHAINS;
9291   BindingFlags binding_flags;
9292   Handle<Object> holder = context->Lookup(name,
9293                                           flags,
9294                                           &index,
9295                                           &attributes,
9296                                           &binding_flags);
9297
9298   // If the slot was not found the result is true.
9299   if (holder.is_null()) {
9300     return isolate->heap()->true_value();
9301   }
9302
9303   // If the slot was found in a context, it should be DONT_DELETE.
9304   if (holder->IsContext()) {
9305     return isolate->heap()->false_value();
9306   }
9307
9308   // The slot was found in a JSObject, either a context extension object,
9309   // the global object, or the subject of a with.  Try to delete it
9310   // (respecting DONT_DELETE).
9311   Handle<JSObject> object = Handle<JSObject>::cast(holder);
9312   Handle<Object> result;
9313   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
9314       isolate, result,
9315       JSReceiver::DeleteProperty(object, name));
9316   return *result;
9317 }
9318
9319
9320 // A mechanism to return a pair of Object pointers in registers (if possible).
9321 // How this is achieved is calling convention-dependent.
9322 // All currently supported x86 compiles uses calling conventions that are cdecl
9323 // variants where a 64-bit value is returned in two 32-bit registers
9324 // (edx:eax on ia32, r1:r0 on ARM).
9325 // In AMD-64 calling convention a struct of two pointers is returned in rdx:rax.
9326 // In Win64 calling convention, a struct of two pointers is returned in memory,
9327 // allocated by the caller, and passed as a pointer in a hidden first parameter.
9328 #ifdef V8_HOST_ARCH_64_BIT
9329 struct ObjectPair {
9330   Object* x;
9331   Object* y;
9332 };
9333
9334
9335 static inline ObjectPair MakePair(Object* x, Object* y) {
9336   ObjectPair result = {x, y};
9337   // Pointers x and y returned in rax and rdx, in AMD-x64-abi.
9338   // In Win64 they are assigned to a hidden first argument.
9339   return result;
9340 }
9341 #elif V8_TARGET_ARCH_X64 && V8_TARGET_ARCH_32_BIT
9342 // For x32 a 128-bit struct return is done as rax and rdx from the ObjectPair
9343 // are used in the full codegen and Crankshaft compiler. An alternative is
9344 // using uint64_t and modifying full codegen and Crankshaft compiler.
9345 struct ObjectPair {
9346   Object* x;
9347   uint32_t x_upper;
9348   Object* y;
9349   uint32_t y_upper;
9350 };
9351
9352
9353 static inline ObjectPair MakePair(Object* x, Object* y) {
9354   ObjectPair result = {x, 0, y, 0};
9355   // Pointers x and y returned in rax and rdx, in x32-abi.
9356   return result;
9357 }
9358 #else
9359 typedef uint64_t ObjectPair;
9360 static inline ObjectPair MakePair(Object* x, Object* y) {
9361 #if defined(V8_TARGET_LITTLE_ENDIAN)
9362   return reinterpret_cast<uint32_t>(x) |
9363       (reinterpret_cast<ObjectPair>(y) << 32);
9364 #elif defined(V8_TARGET_BIG_ENDIAN)
9365     return reinterpret_cast<uint32_t>(y) |
9366         (reinterpret_cast<ObjectPair>(x) << 32);
9367 #else
9368 #error Unknown endianness
9369 #endif
9370 }
9371 #endif
9372
9373
9374 static Object* ComputeReceiverForNonGlobal(Isolate* isolate,
9375                                            JSObject* holder) {
9376   DCHECK(!holder->IsGlobalObject());
9377   Context* top = isolate->context();
9378   // Get the context extension function.
9379   JSFunction* context_extension_function =
9380       top->native_context()->context_extension_function();
9381   // If the holder isn't a context extension object, we just return it
9382   // as the receiver. This allows arguments objects to be used as
9383   // receivers, but only if they are put in the context scope chain
9384   // explicitly via a with-statement.
9385   Object* constructor = holder->map()->constructor();
9386   if (constructor != context_extension_function) return holder;
9387   // Fall back to using the global object as the implicit receiver if
9388   // the property turns out to be a local variable allocated in a
9389   // context extension object - introduced via eval.
9390   return isolate->heap()->undefined_value();
9391 }
9392
9393
9394 static ObjectPair LoadLookupSlotHelper(Arguments args, Isolate* isolate,
9395                                        bool throw_error) {
9396   HandleScope scope(isolate);
9397   DCHECK_EQ(2, args.length());
9398
9399   if (!args[0]->IsContext() || !args[1]->IsString()) {
9400     return MakePair(isolate->ThrowIllegalOperation(), NULL);
9401   }
9402   Handle<Context> context = args.at<Context>(0);
9403   Handle<String> name = args.at<String>(1);
9404
9405   int index;
9406   PropertyAttributes attributes;
9407   ContextLookupFlags flags = FOLLOW_CHAINS;
9408   BindingFlags binding_flags;
9409   Handle<Object> holder = context->Lookup(name,
9410                                           flags,
9411                                           &index,
9412                                           &attributes,
9413                                           &binding_flags);
9414   if (isolate->has_pending_exception()) {
9415     return MakePair(isolate->heap()->exception(), NULL);
9416   }
9417
9418   // If the index is non-negative, the slot has been found in a context.
9419   if (index >= 0) {
9420     DCHECK(holder->IsContext());
9421     // If the "property" we were looking for is a local variable, the
9422     // receiver is the global object; see ECMA-262, 3rd., 10.1.6 and 10.2.3.
9423     Handle<Object> receiver = isolate->factory()->undefined_value();
9424     Object* value = Context::cast(*holder)->get(index);
9425     // Check for uninitialized bindings.
9426     switch (binding_flags) {
9427       case MUTABLE_CHECK_INITIALIZED:
9428       case IMMUTABLE_CHECK_INITIALIZED_HARMONY:
9429         if (value->IsTheHole()) {
9430           Handle<Object> error;
9431           MaybeHandle<Object> maybe_error =
9432               isolate->factory()->NewReferenceError("not_defined",
9433                                                     HandleVector(&name, 1));
9434           if (maybe_error.ToHandle(&error)) isolate->Throw(*error);
9435           return MakePair(isolate->heap()->exception(), NULL);
9436         }
9437         // FALLTHROUGH
9438       case MUTABLE_IS_INITIALIZED:
9439       case IMMUTABLE_IS_INITIALIZED:
9440       case IMMUTABLE_IS_INITIALIZED_HARMONY:
9441         DCHECK(!value->IsTheHole());
9442         return MakePair(value, *receiver);
9443       case IMMUTABLE_CHECK_INITIALIZED:
9444         if (value->IsTheHole()) {
9445           DCHECK((attributes & READ_ONLY) != 0);
9446           value = isolate->heap()->undefined_value();
9447         }
9448         return MakePair(value, *receiver);
9449       case MISSING_BINDING:
9450         UNREACHABLE();
9451         return MakePair(NULL, NULL);
9452     }
9453   }
9454
9455   // Otherwise, if the slot was found the holder is a context extension
9456   // object, subject of a with, or a global object.  We read the named
9457   // property from it.
9458   if (!holder.is_null()) {
9459     Handle<JSReceiver> object = Handle<JSReceiver>::cast(holder);
9460 #ifdef DEBUG
9461     if (!object->IsJSProxy()) {
9462       Maybe<bool> maybe = JSReceiver::HasProperty(object, name);
9463       DCHECK(maybe.has_value);
9464       DCHECK(maybe.value);
9465     }
9466 #endif
9467     // GetProperty below can cause GC.
9468     Handle<Object> receiver_handle(
9469         object->IsGlobalObject()
9470             ? Object::cast(isolate->heap()->undefined_value())
9471             : object->IsJSProxy() ? static_cast<Object*>(*object)
9472                 : ComputeReceiverForNonGlobal(isolate, JSObject::cast(*object)),
9473         isolate);
9474
9475     // No need to unhole the value here.  This is taken care of by the
9476     // GetProperty function.
9477     Handle<Object> value;
9478     ASSIGN_RETURN_ON_EXCEPTION_VALUE(
9479         isolate, value,
9480         Object::GetProperty(object, name),
9481         MakePair(isolate->heap()->exception(), NULL));
9482     return MakePair(*value, *receiver_handle);
9483   }
9484
9485   if (throw_error) {
9486     // The property doesn't exist - throw exception.
9487     Handle<Object> error;
9488     MaybeHandle<Object> maybe_error = isolate->factory()->NewReferenceError(
9489         "not_defined", HandleVector(&name, 1));
9490     if (maybe_error.ToHandle(&error)) isolate->Throw(*error);
9491     return MakePair(isolate->heap()->exception(), NULL);
9492   } else {
9493     // The property doesn't exist - return undefined.
9494     return MakePair(isolate->heap()->undefined_value(),
9495                     isolate->heap()->undefined_value());
9496   }
9497 }
9498
9499
9500 RUNTIME_FUNCTION_RETURN_PAIR(Runtime_LoadLookupSlot) {
9501   return LoadLookupSlotHelper(args, isolate, true);
9502 }
9503
9504
9505 RUNTIME_FUNCTION_RETURN_PAIR(Runtime_LoadLookupSlotNoReferenceError) {
9506   return LoadLookupSlotHelper(args, isolate, false);
9507 }
9508
9509
9510 RUNTIME_FUNCTION(Runtime_StoreLookupSlot) {
9511   HandleScope scope(isolate);
9512   DCHECK(args.length() == 4);
9513
9514   CONVERT_ARG_HANDLE_CHECKED(Object, value, 0);
9515   CONVERT_ARG_HANDLE_CHECKED(Context, context, 1);
9516   CONVERT_ARG_HANDLE_CHECKED(String, name, 2);
9517   CONVERT_STRICT_MODE_ARG_CHECKED(strict_mode, 3);
9518
9519   int index;
9520   PropertyAttributes attributes;
9521   ContextLookupFlags flags = FOLLOW_CHAINS;
9522   BindingFlags binding_flags;
9523   Handle<Object> holder = context->Lookup(name,
9524                                           flags,
9525                                           &index,
9526                                           &attributes,
9527                                           &binding_flags);
9528   // In case of JSProxy, an exception might have been thrown.
9529   if (isolate->has_pending_exception()) return isolate->heap()->exception();
9530
9531   // The property was found in a context slot.
9532   if (index >= 0) {
9533     if ((attributes & READ_ONLY) == 0) {
9534       Handle<Context>::cast(holder)->set(index, *value);
9535     } else if (strict_mode == STRICT) {
9536       // Setting read only property in strict mode.
9537       THROW_NEW_ERROR_RETURN_FAILURE(
9538           isolate,
9539           NewTypeError("strict_cannot_assign", HandleVector(&name, 1)));
9540     }
9541     return *value;
9542   }
9543
9544   // Slow case: The property is not in a context slot.  It is either in a
9545   // context extension object, a property of the subject of a with, or a
9546   // property of the global object.
9547   Handle<JSReceiver> object;
9548   if (attributes != ABSENT) {
9549     // The property exists on the holder.
9550     object = Handle<JSReceiver>::cast(holder);
9551   } else if (strict_mode == STRICT) {
9552     // If absent in strict mode: throw.
9553     THROW_NEW_ERROR_RETURN_FAILURE(
9554         isolate, NewReferenceError("not_defined", HandleVector(&name, 1)));
9555   } else {
9556     // If absent in sloppy mode: add the property to the global object.
9557     object = Handle<JSReceiver>(context->global_object());
9558   }
9559
9560   RETURN_FAILURE_ON_EXCEPTION(
9561       isolate, Object::SetProperty(object, name, value, strict_mode));
9562
9563   return *value;
9564 }
9565
9566
9567 RUNTIME_FUNCTION(Runtime_Throw) {
9568   HandleScope scope(isolate);
9569   DCHECK(args.length() == 1);
9570
9571   return isolate->Throw(args[0]);
9572 }
9573
9574
9575 RUNTIME_FUNCTION(Runtime_ReThrow) {
9576   HandleScope scope(isolate);
9577   DCHECK(args.length() == 1);
9578
9579   return isolate->ReThrow(args[0]);
9580 }
9581
9582
9583 RUNTIME_FUNCTION(Runtime_PromoteScheduledException) {
9584   SealHandleScope shs(isolate);
9585   DCHECK(args.length() == 0);
9586   return isolate->PromoteScheduledException();
9587 }
9588
9589
9590 RUNTIME_FUNCTION(Runtime_ThrowReferenceError) {
9591   HandleScope scope(isolate);
9592   DCHECK(args.length() == 1);
9593   CONVERT_ARG_HANDLE_CHECKED(Object, name, 0);
9594   THROW_NEW_ERROR_RETURN_FAILURE(
9595       isolate, NewReferenceError("not_defined", HandleVector(&name, 1)));
9596 }
9597
9598
9599 RUNTIME_FUNCTION(Runtime_ThrowNonMethodError) {
9600   HandleScope scope(isolate);
9601   DCHECK(args.length() == 0);
9602   THROW_NEW_ERROR_RETURN_FAILURE(
9603       isolate, NewReferenceError("non_method", HandleVector<Object>(NULL, 0)));
9604 }
9605
9606
9607 RUNTIME_FUNCTION(Runtime_ThrowUnsupportedSuperError) {
9608   HandleScope scope(isolate);
9609   DCHECK(args.length() == 0);
9610   THROW_NEW_ERROR_RETURN_FAILURE(
9611       isolate,
9612       NewReferenceError("unsupported_super", HandleVector<Object>(NULL, 0)));
9613 }
9614
9615
9616 RUNTIME_FUNCTION(Runtime_ThrowNotDateError) {
9617   HandleScope scope(isolate);
9618   DCHECK(args.length() == 0);
9619   THROW_NEW_ERROR_RETURN_FAILURE(
9620       isolate, NewTypeError("not_date_object", HandleVector<Object>(NULL, 0)));
9621 }
9622
9623
9624 RUNTIME_FUNCTION(Runtime_StackGuard) {
9625   SealHandleScope shs(isolate);
9626   DCHECK(args.length() == 0);
9627
9628   // First check if this is a real stack overflow.
9629   StackLimitCheck check(isolate);
9630   if (check.JsHasOverflowed()) {
9631     return isolate->StackOverflow();
9632   }
9633
9634   return isolate->stack_guard()->HandleInterrupts();
9635 }
9636
9637
9638 RUNTIME_FUNCTION(Runtime_TryInstallOptimizedCode) {
9639   HandleScope scope(isolate);
9640   DCHECK(args.length() == 1);
9641   CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
9642
9643   // First check if this is a real stack overflow.
9644   StackLimitCheck check(isolate);
9645   if (check.JsHasOverflowed()) {
9646     SealHandleScope shs(isolate);
9647     return isolate->StackOverflow();
9648   }
9649
9650   isolate->optimizing_compiler_thread()->InstallOptimizedFunctions();
9651   return (function->IsOptimized()) ? function->code()
9652                                    : function->shared()->code();
9653 }
9654
9655
9656 RUNTIME_FUNCTION(Runtime_Interrupt) {
9657   SealHandleScope shs(isolate);
9658   DCHECK(args.length() == 0);
9659   return isolate->stack_guard()->HandleInterrupts();
9660 }
9661
9662
9663 static int StackSize(Isolate* isolate) {
9664   int n = 0;
9665   for (JavaScriptFrameIterator it(isolate); !it.done(); it.Advance()) n++;
9666   return n;
9667 }
9668
9669
9670 static void PrintTransition(Isolate* isolate, Object* result) {
9671   // indentation
9672   { const int nmax = 80;
9673     int n = StackSize(isolate);
9674     if (n <= nmax)
9675       PrintF("%4d:%*s", n, n, "");
9676     else
9677       PrintF("%4d:%*s", n, nmax, "...");
9678   }
9679
9680   if (result == NULL) {
9681     JavaScriptFrame::PrintTop(isolate, stdout, true, false);
9682     PrintF(" {\n");
9683   } else {
9684     // function result
9685     PrintF("} -> ");
9686     result->ShortPrint();
9687     PrintF("\n");
9688   }
9689 }
9690
9691
9692 RUNTIME_FUNCTION(Runtime_TraceEnter) {
9693   SealHandleScope shs(isolate);
9694   DCHECK(args.length() == 0);
9695   PrintTransition(isolate, NULL);
9696   return isolate->heap()->undefined_value();
9697 }
9698
9699
9700 RUNTIME_FUNCTION(Runtime_TraceExit) {
9701   SealHandleScope shs(isolate);
9702   DCHECK(args.length() == 1);
9703   CONVERT_ARG_CHECKED(Object, obj, 0);
9704   PrintTransition(isolate, obj);
9705   return obj;  // return TOS
9706 }
9707
9708
9709 RUNTIME_FUNCTION(Runtime_DebugPrint) {
9710   SealHandleScope shs(isolate);
9711   DCHECK(args.length() == 1);
9712
9713   OFStream os(stdout);
9714 #ifdef DEBUG
9715   if (args[0]->IsString()) {
9716     // If we have a string, assume it's a code "marker"
9717     // and print some interesting cpu debugging info.
9718     JavaScriptFrameIterator it(isolate);
9719     JavaScriptFrame* frame = it.frame();
9720     os << "fp = " << frame->fp() << ", sp = " << frame->sp()
9721        << ", caller_sp = " << frame->caller_sp() << ": ";
9722   } else {
9723     os << "DebugPrint: ";
9724   }
9725   args[0]->Print(os);
9726   if (args[0]->IsHeapObject()) {
9727     os << "\n";
9728     HeapObject::cast(args[0])->map()->Print(os);
9729   }
9730 #else
9731   // ShortPrint is available in release mode. Print is not.
9732   os << Brief(args[0]);
9733 #endif
9734   os << endl;
9735
9736   return args[0];  // return TOS
9737 }
9738
9739
9740 RUNTIME_FUNCTION(Runtime_DebugTrace) {
9741   SealHandleScope shs(isolate);
9742   DCHECK(args.length() == 0);
9743   isolate->PrintStack(stdout);
9744   return isolate->heap()->undefined_value();
9745 }
9746
9747
9748 RUNTIME_FUNCTION(Runtime_DateCurrentTime) {
9749   HandleScope scope(isolate);
9750   DCHECK(args.length() == 0);
9751   if (FLAG_log_timer_events) LOG(isolate, CurrentTimeEvent());
9752
9753   // According to ECMA-262, section 15.9.1, page 117, the precision of
9754   // the number in a Date object representing a particular instant in
9755   // time is milliseconds. Therefore, we floor the result of getting
9756   // the OS time.
9757   double millis;
9758   if (FLAG_verify_predictable) {
9759     millis = 1388534400000.0;  // Jan 1 2014 00:00:00 GMT+0000
9760     millis += Floor(isolate->heap()->synthetic_time());
9761   } else {
9762     millis = Floor(base::OS::TimeCurrentMillis());
9763   }
9764   return *isolate->factory()->NewNumber(millis);
9765 }
9766
9767
9768 RUNTIME_FUNCTION(Runtime_DateParseString) {
9769   HandleScope scope(isolate);
9770   DCHECK(args.length() == 2);
9771   CONVERT_ARG_HANDLE_CHECKED(String, str, 0);
9772   CONVERT_ARG_HANDLE_CHECKED(JSArray, output, 1);
9773
9774   RUNTIME_ASSERT(output->HasFastElements());
9775   JSObject::EnsureCanContainHeapObjectElements(output);
9776   RUNTIME_ASSERT(output->HasFastObjectElements());
9777   Handle<FixedArray> output_array(FixedArray::cast(output->elements()));
9778   RUNTIME_ASSERT(output_array->length() >= DateParser::OUTPUT_SIZE);
9779
9780   str = String::Flatten(str);
9781   DisallowHeapAllocation no_gc;
9782
9783   bool result;
9784   String::FlatContent str_content = str->GetFlatContent();
9785   if (str_content.IsOneByte()) {
9786     result = DateParser::Parse(str_content.ToOneByteVector(),
9787                                *output_array,
9788                                isolate->unicode_cache());
9789   } else {
9790     DCHECK(str_content.IsTwoByte());
9791     result = DateParser::Parse(str_content.ToUC16Vector(),
9792                                *output_array,
9793                                isolate->unicode_cache());
9794   }
9795
9796   if (result) {
9797     return *output;
9798   } else {
9799     return isolate->heap()->null_value();
9800   }
9801 }
9802
9803
9804 RUNTIME_FUNCTION(Runtime_DateLocalTimezone) {
9805   HandleScope scope(isolate);
9806   DCHECK(args.length() == 1);
9807
9808   CONVERT_DOUBLE_ARG_CHECKED(x, 0);
9809   RUNTIME_ASSERT(x >= -DateCache::kMaxTimeBeforeUTCInMs &&
9810                  x <= DateCache::kMaxTimeBeforeUTCInMs);
9811   const char* zone =
9812       isolate->date_cache()->LocalTimezone(static_cast<int64_t>(x));
9813   Handle<String> result = isolate->factory()->NewStringFromUtf8(
9814       CStrVector(zone)).ToHandleChecked();
9815   return *result;
9816 }
9817
9818
9819 RUNTIME_FUNCTION(Runtime_DateToUTC) {
9820   HandleScope scope(isolate);
9821   DCHECK(args.length() == 1);
9822
9823   CONVERT_DOUBLE_ARG_CHECKED(x, 0);
9824   RUNTIME_ASSERT(x >= -DateCache::kMaxTimeBeforeUTCInMs &&
9825                  x <= DateCache::kMaxTimeBeforeUTCInMs);
9826   int64_t time = isolate->date_cache()->ToUTC(static_cast<int64_t>(x));
9827
9828   return *isolate->factory()->NewNumber(static_cast<double>(time));
9829 }
9830
9831
9832 RUNTIME_FUNCTION(Runtime_DateCacheVersion) {
9833   HandleScope hs(isolate);
9834   DCHECK(args.length() == 0);
9835   if (!isolate->eternal_handles()->Exists(EternalHandles::DATE_CACHE_VERSION)) {
9836     Handle<FixedArray> date_cache_version =
9837         isolate->factory()->NewFixedArray(1, TENURED);
9838     date_cache_version->set(0, Smi::FromInt(0));
9839     isolate->eternal_handles()->CreateSingleton(
9840         isolate, *date_cache_version, EternalHandles::DATE_CACHE_VERSION);
9841   }
9842   Handle<FixedArray> date_cache_version =
9843       Handle<FixedArray>::cast(isolate->eternal_handles()->GetSingleton(
9844           EternalHandles::DATE_CACHE_VERSION));
9845   // Return result as a JS array.
9846   Handle<JSObject> result =
9847       isolate->factory()->NewJSObject(isolate->array_function());
9848   JSArray::SetContent(Handle<JSArray>::cast(result), date_cache_version);
9849   return *result;
9850 }
9851
9852
9853 RUNTIME_FUNCTION(Runtime_GlobalProxy) {
9854   SealHandleScope shs(isolate);
9855   DCHECK(args.length() == 1);
9856   CONVERT_ARG_CHECKED(Object, global, 0);
9857   if (!global->IsJSGlobalObject()) return isolate->heap()->null_value();
9858   return JSGlobalObject::cast(global)->global_proxy();
9859 }
9860
9861
9862 RUNTIME_FUNCTION(Runtime_IsAttachedGlobal) {
9863   SealHandleScope shs(isolate);
9864   DCHECK(args.length() == 1);
9865   CONVERT_ARG_CHECKED(Object, global, 0);
9866   if (!global->IsJSGlobalObject()) return isolate->heap()->false_value();
9867   return isolate->heap()->ToBoolean(
9868       !JSGlobalObject::cast(global)->IsDetached());
9869 }
9870
9871
9872 RUNTIME_FUNCTION(Runtime_ParseJson) {
9873   HandleScope scope(isolate);
9874   DCHECK(args.length() == 1);
9875   CONVERT_ARG_HANDLE_CHECKED(String, source, 0);
9876
9877   source = String::Flatten(source);
9878   // Optimized fast case where we only have Latin1 characters.
9879   Handle<Object> result;
9880   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
9881       isolate, result,
9882       source->IsSeqOneByteString() ? JsonParser<true>::Parse(source)
9883                                    : JsonParser<false>::Parse(source));
9884   return *result;
9885 }
9886
9887
9888 bool CodeGenerationFromStringsAllowed(Isolate* isolate,
9889                                       Handle<Context> context) {
9890   DCHECK(context->allow_code_gen_from_strings()->IsFalse());
9891   // Check with callback if set.
9892   AllowCodeGenerationFromStringsCallback callback =
9893       isolate->allow_code_gen_callback();
9894   if (callback == NULL) {
9895     // No callback set and code generation disallowed.
9896     return false;
9897   } else {
9898     // Callback set. Let it decide if code generation is allowed.
9899     VMState<EXTERNAL> state(isolate);
9900     return callback(v8::Utils::ToLocal(context));
9901   }
9902 }
9903
9904
9905 RUNTIME_FUNCTION(Runtime_CompileString) {
9906   HandleScope scope(isolate);
9907   DCHECK(args.length() == 2);
9908   CONVERT_ARG_HANDLE_CHECKED(String, source, 0);
9909   CONVERT_BOOLEAN_ARG_CHECKED(function_literal_only, 1);
9910
9911   // Extract native context.
9912   Handle<Context> context(isolate->native_context());
9913
9914   // Check if native context allows code generation from
9915   // strings. Throw an exception if it doesn't.
9916   if (context->allow_code_gen_from_strings()->IsFalse() &&
9917       !CodeGenerationFromStringsAllowed(isolate, context)) {
9918     Handle<Object> error_message =
9919         context->ErrorMessageForCodeGenerationFromStrings();
9920     THROW_NEW_ERROR_RETURN_FAILURE(
9921         isolate, NewEvalError("code_gen_from_strings",
9922                               HandleVector<Object>(&error_message, 1)));
9923   }
9924
9925   // Compile source string in the native context.
9926   ParseRestriction restriction = function_literal_only
9927       ? ONLY_SINGLE_FUNCTION_LITERAL : NO_PARSE_RESTRICTION;
9928   Handle<SharedFunctionInfo> outer_info(context->closure()->shared(), isolate);
9929   Handle<JSFunction> fun;
9930   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
9931       isolate, fun,
9932       Compiler::GetFunctionFromEval(
9933           source, outer_info,
9934           context, SLOPPY, restriction, RelocInfo::kNoPosition));
9935   return *fun;
9936 }
9937
9938
9939 static ObjectPair CompileGlobalEval(Isolate* isolate,
9940                                     Handle<String> source,
9941                                     Handle<SharedFunctionInfo> outer_info,
9942                                     Handle<Object> receiver,
9943                                     StrictMode strict_mode,
9944                                     int scope_position) {
9945   Handle<Context> context = Handle<Context>(isolate->context());
9946   Handle<Context> native_context = Handle<Context>(context->native_context());
9947
9948   // Check if native context allows code generation from
9949   // strings. Throw an exception if it doesn't.
9950   if (native_context->allow_code_gen_from_strings()->IsFalse() &&
9951       !CodeGenerationFromStringsAllowed(isolate, native_context)) {
9952     Handle<Object> error_message =
9953         native_context->ErrorMessageForCodeGenerationFromStrings();
9954     Handle<Object> error;
9955     MaybeHandle<Object> maybe_error = isolate->factory()->NewEvalError(
9956         "code_gen_from_strings", HandleVector<Object>(&error_message, 1));
9957     if (maybe_error.ToHandle(&error)) isolate->Throw(*error);
9958     return MakePair(isolate->heap()->exception(), NULL);
9959   }
9960
9961   // Deal with a normal eval call with a string argument. Compile it
9962   // and return the compiled function bound in the local context.
9963   static const ParseRestriction restriction = NO_PARSE_RESTRICTION;
9964   Handle<JSFunction> compiled;
9965   ASSIGN_RETURN_ON_EXCEPTION_VALUE(
9966       isolate, compiled,
9967       Compiler::GetFunctionFromEval(
9968           source, outer_info,
9969           context, strict_mode, restriction, scope_position),
9970       MakePair(isolate->heap()->exception(), NULL));
9971   return MakePair(*compiled, *receiver);
9972 }
9973
9974
9975 RUNTIME_FUNCTION_RETURN_PAIR(Runtime_ResolvePossiblyDirectEval) {
9976   HandleScope scope(isolate);
9977   DCHECK(args.length() == 6);
9978
9979   Handle<Object> callee = args.at<Object>(0);
9980
9981   // If "eval" didn't refer to the original GlobalEval, it's not a
9982   // direct call to eval.
9983   // (And even if it is, but the first argument isn't a string, just let
9984   // execution default to an indirect call to eval, which will also return
9985   // the first argument without doing anything).
9986   if (*callee != isolate->native_context()->global_eval_fun() ||
9987       !args[1]->IsString()) {
9988     return MakePair(*callee, isolate->heap()->undefined_value());
9989   }
9990
9991   DCHECK(args[4]->IsSmi());
9992   DCHECK(args.smi_at(4) == SLOPPY || args.smi_at(4) == STRICT);
9993   StrictMode strict_mode = static_cast<StrictMode>(args.smi_at(4));
9994   DCHECK(args[5]->IsSmi());
9995   Handle<SharedFunctionInfo> outer_info(args.at<JSFunction>(2)->shared(),
9996                                         isolate);
9997   return CompileGlobalEval(isolate,
9998                            args.at<String>(1),
9999                            outer_info,
10000                            args.at<Object>(3),
10001                            strict_mode,
10002                            args.smi_at(5));
10003 }
10004
10005
10006 RUNTIME_FUNCTION(Runtime_AllocateInNewSpace) {
10007   HandleScope scope(isolate);
10008   DCHECK(args.length() == 1);
10009   CONVERT_SMI_ARG_CHECKED(size, 0);
10010   RUNTIME_ASSERT(IsAligned(size, kPointerSize));
10011   RUNTIME_ASSERT(size > 0);
10012   RUNTIME_ASSERT(size <= Page::kMaxRegularHeapObjectSize);
10013   return *isolate->factory()->NewFillerObject(size, false, NEW_SPACE);
10014 }
10015
10016
10017 RUNTIME_FUNCTION(Runtime_AllocateInTargetSpace) {
10018   HandleScope scope(isolate);
10019   DCHECK(args.length() == 2);
10020   CONVERT_SMI_ARG_CHECKED(size, 0);
10021   CONVERT_SMI_ARG_CHECKED(flags, 1);
10022   RUNTIME_ASSERT(IsAligned(size, kPointerSize));
10023   RUNTIME_ASSERT(size > 0);
10024   RUNTIME_ASSERT(size <= Page::kMaxRegularHeapObjectSize);
10025   bool double_align = AllocateDoubleAlignFlag::decode(flags);
10026   AllocationSpace space = AllocateTargetSpace::decode(flags);
10027   return *isolate->factory()->NewFillerObject(size, double_align, space);
10028 }
10029
10030
10031 // Push an object unto an array of objects if it is not already in the
10032 // array.  Returns true if the element was pushed on the stack and
10033 // false otherwise.
10034 RUNTIME_FUNCTION(Runtime_PushIfAbsent) {
10035   HandleScope scope(isolate);
10036   DCHECK(args.length() == 2);
10037   CONVERT_ARG_HANDLE_CHECKED(JSArray, array, 0);
10038   CONVERT_ARG_HANDLE_CHECKED(JSReceiver, element, 1);
10039   RUNTIME_ASSERT(array->HasFastSmiOrObjectElements());
10040   int length = Smi::cast(array->length())->value();
10041   FixedArray* elements = FixedArray::cast(array->elements());
10042   for (int i = 0; i < length; i++) {
10043     if (elements->get(i) == *element) return isolate->heap()->false_value();
10044   }
10045
10046   // Strict not needed. Used for cycle detection in Array join implementation.
10047   RETURN_FAILURE_ON_EXCEPTION(
10048       isolate,
10049       JSObject::SetFastElement(array, length, element, SLOPPY, true));
10050   return isolate->heap()->true_value();
10051 }
10052
10053
10054 /**
10055  * A simple visitor visits every element of Array's.
10056  * The backend storage can be a fixed array for fast elements case,
10057  * or a dictionary for sparse array. Since Dictionary is a subtype
10058  * of FixedArray, the class can be used by both fast and slow cases.
10059  * The second parameter of the constructor, fast_elements, specifies
10060  * whether the storage is a FixedArray or Dictionary.
10061  *
10062  * An index limit is used to deal with the situation that a result array
10063  * length overflows 32-bit non-negative integer.
10064  */
10065 class ArrayConcatVisitor {
10066  public:
10067   ArrayConcatVisitor(Isolate* isolate,
10068                      Handle<FixedArray> storage,
10069                      bool fast_elements) :
10070       isolate_(isolate),
10071       storage_(Handle<FixedArray>::cast(
10072           isolate->global_handles()->Create(*storage))),
10073       index_offset_(0u),
10074       fast_elements_(fast_elements),
10075       exceeds_array_limit_(false) { }
10076
10077   ~ArrayConcatVisitor() {
10078     clear_storage();
10079   }
10080
10081   void visit(uint32_t i, Handle<Object> elm) {
10082     if (i > JSObject::kMaxElementCount - index_offset_) {
10083       exceeds_array_limit_ = true;
10084       return;
10085     }
10086     uint32_t index = index_offset_ + i;
10087
10088     if (fast_elements_) {
10089       if (index < static_cast<uint32_t>(storage_->length())) {
10090         storage_->set(index, *elm);
10091         return;
10092       }
10093       // Our initial estimate of length was foiled, possibly by
10094       // getters on the arrays increasing the length of later arrays
10095       // during iteration.
10096       // This shouldn't happen in anything but pathological cases.
10097       SetDictionaryMode();
10098       // Fall-through to dictionary mode.
10099     }
10100     DCHECK(!fast_elements_);
10101     Handle<SeededNumberDictionary> dict(
10102         SeededNumberDictionary::cast(*storage_));
10103     Handle<SeededNumberDictionary> result =
10104         SeededNumberDictionary::AtNumberPut(dict, index, elm);
10105     if (!result.is_identical_to(dict)) {
10106       // Dictionary needed to grow.
10107       clear_storage();
10108       set_storage(*result);
10109     }
10110   }
10111
10112   void increase_index_offset(uint32_t delta) {
10113     if (JSObject::kMaxElementCount - index_offset_ < delta) {
10114       index_offset_ = JSObject::kMaxElementCount;
10115     } else {
10116       index_offset_ += delta;
10117     }
10118     // If the initial length estimate was off (see special case in visit()),
10119     // but the array blowing the limit didn't contain elements beyond the
10120     // provided-for index range, go to dictionary mode now.
10121     if (fast_elements_ &&
10122         index_offset_ >
10123             static_cast<uint32_t>(FixedArrayBase::cast(*storage_)->length())) {
10124       SetDictionaryMode();
10125     }
10126   }
10127
10128   bool exceeds_array_limit() {
10129     return exceeds_array_limit_;
10130   }
10131
10132   Handle<JSArray> ToArray() {
10133     Handle<JSArray> array = isolate_->factory()->NewJSArray(0);
10134     Handle<Object> length =
10135         isolate_->factory()->NewNumber(static_cast<double>(index_offset_));
10136     Handle<Map> map = JSObject::GetElementsTransitionMap(
10137         array,
10138         fast_elements_ ? FAST_HOLEY_ELEMENTS : DICTIONARY_ELEMENTS);
10139     array->set_map(*map);
10140     array->set_length(*length);
10141     array->set_elements(*storage_);
10142     return array;
10143   }
10144
10145  private:
10146   // Convert storage to dictionary mode.
10147   void SetDictionaryMode() {
10148     DCHECK(fast_elements_);
10149     Handle<FixedArray> current_storage(*storage_);
10150     Handle<SeededNumberDictionary> slow_storage(
10151         SeededNumberDictionary::New(isolate_, current_storage->length()));
10152     uint32_t current_length = static_cast<uint32_t>(current_storage->length());
10153     for (uint32_t i = 0; i < current_length; i++) {
10154       HandleScope loop_scope(isolate_);
10155       Handle<Object> element(current_storage->get(i), isolate_);
10156       if (!element->IsTheHole()) {
10157         Handle<SeededNumberDictionary> new_storage =
10158             SeededNumberDictionary::AtNumberPut(slow_storage, i, element);
10159         if (!new_storage.is_identical_to(slow_storage)) {
10160           slow_storage = loop_scope.CloseAndEscape(new_storage);
10161         }
10162       }
10163     }
10164     clear_storage();
10165     set_storage(*slow_storage);
10166     fast_elements_ = false;
10167   }
10168
10169   inline void clear_storage() {
10170     GlobalHandles::Destroy(Handle<Object>::cast(storage_).location());
10171   }
10172
10173   inline void set_storage(FixedArray* storage) {
10174     storage_ = Handle<FixedArray>::cast(
10175         isolate_->global_handles()->Create(storage));
10176   }
10177
10178   Isolate* isolate_;
10179   Handle<FixedArray> storage_;  // Always a global handle.
10180   // Index after last seen index. Always less than or equal to
10181   // JSObject::kMaxElementCount.
10182   uint32_t index_offset_;
10183   bool fast_elements_ : 1;
10184   bool exceeds_array_limit_ : 1;
10185 };
10186
10187
10188 static uint32_t EstimateElementCount(Handle<JSArray> array) {
10189   uint32_t length = static_cast<uint32_t>(array->length()->Number());
10190   int element_count = 0;
10191   switch (array->GetElementsKind()) {
10192     case FAST_SMI_ELEMENTS:
10193     case FAST_HOLEY_SMI_ELEMENTS:
10194     case FAST_ELEMENTS:
10195     case FAST_HOLEY_ELEMENTS: {
10196       // Fast elements can't have lengths that are not representable by
10197       // a 32-bit signed integer.
10198       DCHECK(static_cast<int32_t>(FixedArray::kMaxLength) >= 0);
10199       int fast_length = static_cast<int>(length);
10200       Handle<FixedArray> elements(FixedArray::cast(array->elements()));
10201       for (int i = 0; i < fast_length; i++) {
10202         if (!elements->get(i)->IsTheHole()) element_count++;
10203       }
10204       break;
10205     }
10206     case FAST_DOUBLE_ELEMENTS:
10207     case FAST_HOLEY_DOUBLE_ELEMENTS: {
10208       // Fast elements can't have lengths that are not representable by
10209       // a 32-bit signed integer.
10210       DCHECK(static_cast<int32_t>(FixedDoubleArray::kMaxLength) >= 0);
10211       int fast_length = static_cast<int>(length);
10212       if (array->elements()->IsFixedArray()) {
10213         DCHECK(FixedArray::cast(array->elements())->length() == 0);
10214         break;
10215       }
10216       Handle<FixedDoubleArray> elements(
10217           FixedDoubleArray::cast(array->elements()));
10218       for (int i = 0; i < fast_length; i++) {
10219         if (!elements->is_the_hole(i)) element_count++;
10220       }
10221       break;
10222     }
10223     case DICTIONARY_ELEMENTS: {
10224       Handle<SeededNumberDictionary> dictionary(
10225           SeededNumberDictionary::cast(array->elements()));
10226       int capacity = dictionary->Capacity();
10227       for (int i = 0; i < capacity; i++) {
10228         Handle<Object> key(dictionary->KeyAt(i), array->GetIsolate());
10229         if (dictionary->IsKey(*key)) {
10230           element_count++;
10231         }
10232       }
10233       break;
10234     }
10235     case SLOPPY_ARGUMENTS_ELEMENTS:
10236 #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size)                      \
10237     case EXTERNAL_##TYPE##_ELEMENTS:                                         \
10238     case TYPE##_ELEMENTS:                                                    \
10239
10240     TYPED_ARRAYS(TYPED_ARRAY_CASE)
10241 #undef TYPED_ARRAY_CASE
10242       // External arrays are always dense.
10243       return length;
10244   }
10245   // As an estimate, we assume that the prototype doesn't contain any
10246   // inherited elements.
10247   return element_count;
10248 }
10249
10250
10251
10252 template<class ExternalArrayClass, class ElementType>
10253 static void IterateExternalArrayElements(Isolate* isolate,
10254                                          Handle<JSObject> receiver,
10255                                          bool elements_are_ints,
10256                                          bool elements_are_guaranteed_smis,
10257                                          ArrayConcatVisitor* visitor) {
10258   Handle<ExternalArrayClass> array(
10259       ExternalArrayClass::cast(receiver->elements()));
10260   uint32_t len = static_cast<uint32_t>(array->length());
10261
10262   DCHECK(visitor != NULL);
10263   if (elements_are_ints) {
10264     if (elements_are_guaranteed_smis) {
10265       for (uint32_t j = 0; j < len; j++) {
10266         HandleScope loop_scope(isolate);
10267         Handle<Smi> e(Smi::FromInt(static_cast<int>(array->get_scalar(j))),
10268                       isolate);
10269         visitor->visit(j, e);
10270       }
10271     } else {
10272       for (uint32_t j = 0; j < len; j++) {
10273         HandleScope loop_scope(isolate);
10274         int64_t val = static_cast<int64_t>(array->get_scalar(j));
10275         if (Smi::IsValid(static_cast<intptr_t>(val))) {
10276           Handle<Smi> e(Smi::FromInt(static_cast<int>(val)), isolate);
10277           visitor->visit(j, e);
10278         } else {
10279           Handle<Object> e =
10280               isolate->factory()->NewNumber(static_cast<ElementType>(val));
10281           visitor->visit(j, e);
10282         }
10283       }
10284     }
10285   } else {
10286     for (uint32_t j = 0; j < len; j++) {
10287       HandleScope loop_scope(isolate);
10288       Handle<Object> e = isolate->factory()->NewNumber(array->get_scalar(j));
10289       visitor->visit(j, e);
10290     }
10291   }
10292 }
10293
10294
10295 static void IterateExternalFloat32x4ArrayElements(Isolate* isolate,
10296                                                   Handle<JSObject> receiver,
10297                                                   ArrayConcatVisitor* visitor) {
10298   Handle<ExternalFloat32x4Array> array(
10299       ExternalFloat32x4Array::cast(receiver->elements()));
10300   uint32_t len = static_cast<uint32_t>(array->length());
10301
10302   DCHECK(visitor != NULL);
10303   for (uint32_t j = 0; j < len; j++) {
10304     HandleScope loop_scope(isolate);
10305     Handle<Object> e = isolate->factory()->NewFloat32x4(array->get_scalar(j));
10306     visitor->visit(j, e);
10307   }
10308 }
10309
10310
10311 static void IterateExternalFloat64x2ArrayElements(Isolate* isolate,
10312                                                   Handle<JSObject> receiver,
10313                                                   ArrayConcatVisitor* visitor) {
10314   Handle<ExternalFloat64x2Array> array(
10315       ExternalFloat64x2Array::cast(receiver->elements()));
10316   uint32_t len = static_cast<uint32_t>(array->length());
10317
10318   DCHECK(visitor != NULL);
10319   for (uint32_t j = 0; j < len; j++) {
10320     HandleScope loop_scope(isolate);
10321     Handle<Object> e = isolate->factory()->NewFloat64x2(array->get_scalar(j));
10322     visitor->visit(j, e);
10323   }
10324 }
10325
10326
10327 static void IterateExternalInt32x4ArrayElements(Isolate* isolate,
10328                                                  Handle<JSObject> receiver,
10329                                                  ArrayConcatVisitor* visitor) {
10330   Handle<ExternalInt32x4Array> array(
10331       ExternalInt32x4Array::cast(receiver->elements()));
10332   uint32_t len = static_cast<uint32_t>(array->length());
10333
10334   DCHECK(visitor != NULL);
10335   for (uint32_t j = 0; j < len; j++) {
10336     HandleScope loop_scope(isolate);
10337     Handle<Object> e = isolate->factory()->NewInt32x4(array->get_scalar(j));
10338     visitor->visit(j, e);
10339   }
10340 }
10341
10342
10343 // Used for sorting indices in a List<uint32_t>.
10344 static int compareUInt32(const uint32_t* ap, const uint32_t* bp) {
10345   uint32_t a = *ap;
10346   uint32_t b = *bp;
10347   return (a == b) ? 0 : (a < b) ? -1 : 1;
10348 }
10349
10350
10351 static void CollectElementIndices(Handle<JSObject> object,
10352                                   uint32_t range,
10353                                   List<uint32_t>* indices) {
10354   Isolate* isolate = object->GetIsolate();
10355   ElementsKind kind = object->GetElementsKind();
10356   switch (kind) {
10357     case FAST_SMI_ELEMENTS:
10358     case FAST_ELEMENTS:
10359     case FAST_HOLEY_SMI_ELEMENTS:
10360     case FAST_HOLEY_ELEMENTS: {
10361       Handle<FixedArray> elements(FixedArray::cast(object->elements()));
10362       uint32_t length = static_cast<uint32_t>(elements->length());
10363       if (range < length) length = range;
10364       for (uint32_t i = 0; i < length; i++) {
10365         if (!elements->get(i)->IsTheHole()) {
10366           indices->Add(i);
10367         }
10368       }
10369       break;
10370     }
10371     case FAST_HOLEY_DOUBLE_ELEMENTS:
10372     case FAST_DOUBLE_ELEMENTS: {
10373       if (object->elements()->IsFixedArray()) {
10374         DCHECK(object->elements()->length() == 0);
10375         break;
10376       }
10377       Handle<FixedDoubleArray> elements(
10378           FixedDoubleArray::cast(object->elements()));
10379       uint32_t length = static_cast<uint32_t>(elements->length());
10380       if (range < length) length = range;
10381       for (uint32_t i = 0; i < length; i++) {
10382         if (!elements->is_the_hole(i)) {
10383           indices->Add(i);
10384         }
10385       }
10386       break;
10387     }
10388     case DICTIONARY_ELEMENTS: {
10389       Handle<SeededNumberDictionary> dict(
10390           SeededNumberDictionary::cast(object->elements()));
10391       uint32_t capacity = dict->Capacity();
10392       for (uint32_t j = 0; j < capacity; j++) {
10393         HandleScope loop_scope(isolate);
10394         Handle<Object> k(dict->KeyAt(j), isolate);
10395         if (dict->IsKey(*k)) {
10396           DCHECK(k->IsNumber());
10397           uint32_t index = static_cast<uint32_t>(k->Number());
10398           if (index < range) {
10399             indices->Add(index);
10400           }
10401         }
10402       }
10403       break;
10404     }
10405 #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \
10406     case TYPE##_ELEMENTS:                               \
10407     case EXTERNAL_##TYPE##_ELEMENTS:
10408
10409       TYPED_ARRAYS(TYPED_ARRAY_CASE)
10410 #undef TYPED_ARRAY_CASE
10411     {
10412       uint32_t length = static_cast<uint32_t>(
10413           FixedArrayBase::cast(object->elements())->length());
10414       if (range <= length) {
10415         length = range;
10416         // We will add all indices, so we might as well clear it first
10417         // and avoid duplicates.
10418         indices->Clear();
10419       }
10420       for (uint32_t i = 0; i < length; i++) {
10421         indices->Add(i);
10422       }
10423       if (length == range) return;  // All indices accounted for already.
10424       break;
10425     }
10426     case SLOPPY_ARGUMENTS_ELEMENTS: {
10427       MaybeHandle<Object> length_obj =
10428           Object::GetProperty(object, isolate->factory()->length_string());
10429       double length_num = length_obj.ToHandleChecked()->Number();
10430       uint32_t length = static_cast<uint32_t>(DoubleToInt32(length_num));
10431       ElementsAccessor* accessor = object->GetElementsAccessor();
10432       for (uint32_t i = 0; i < length; i++) {
10433         if (accessor->HasElement(object, object, i)) {
10434           indices->Add(i);
10435         }
10436       }
10437       break;
10438     }
10439   }
10440
10441   PrototypeIterator iter(isolate, object);
10442   if (!iter.IsAtEnd()) {
10443     // The prototype will usually have no inherited element indices,
10444     // but we have to check.
10445     CollectElementIndices(
10446         Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter)), range,
10447         indices);
10448   }
10449 }
10450
10451
10452 /**
10453  * A helper function that visits elements of a JSArray in numerical
10454  * order.
10455  *
10456  * The visitor argument called for each existing element in the array
10457  * with the element index and the element's value.
10458  * Afterwards it increments the base-index of the visitor by the array
10459  * length.
10460  * Returns false if any access threw an exception, otherwise true.
10461  */
10462 static bool IterateElements(Isolate* isolate,
10463                             Handle<JSArray> receiver,
10464                             ArrayConcatVisitor* visitor) {
10465   uint32_t length = static_cast<uint32_t>(receiver->length()->Number());
10466   switch (receiver->GetElementsKind()) {
10467     case FAST_SMI_ELEMENTS:
10468     case FAST_ELEMENTS:
10469     case FAST_HOLEY_SMI_ELEMENTS:
10470     case FAST_HOLEY_ELEMENTS: {
10471       // Run through the elements FixedArray and use HasElement and GetElement
10472       // to check the prototype for missing elements.
10473       Handle<FixedArray> elements(FixedArray::cast(receiver->elements()));
10474       int fast_length = static_cast<int>(length);
10475       DCHECK(fast_length <= elements->length());
10476       for (int j = 0; j < fast_length; j++) {
10477         HandleScope loop_scope(isolate);
10478         Handle<Object> element_value(elements->get(j), isolate);
10479         if (!element_value->IsTheHole()) {
10480           visitor->visit(j, element_value);
10481         } else {
10482           Maybe<bool> maybe = JSReceiver::HasElement(receiver, j);
10483           if (!maybe.has_value) return false;
10484           if (maybe.value) {
10485             // Call GetElement on receiver, not its prototype, or getters won't
10486             // have the correct receiver.
10487             ASSIGN_RETURN_ON_EXCEPTION_VALUE(
10488                 isolate, element_value,
10489                 Object::GetElement(isolate, receiver, j), false);
10490             visitor->visit(j, element_value);
10491           }
10492         }
10493       }
10494       break;
10495     }
10496     case FAST_HOLEY_DOUBLE_ELEMENTS:
10497     case FAST_DOUBLE_ELEMENTS: {
10498       // Empty array is FixedArray but not FixedDoubleArray.
10499       if (length == 0) break;
10500       // Run through the elements FixedArray and use HasElement and GetElement
10501       // to check the prototype for missing elements.
10502       if (receiver->elements()->IsFixedArray()) {
10503         DCHECK(receiver->elements()->length() == 0);
10504         break;
10505       }
10506       Handle<FixedDoubleArray> elements(
10507           FixedDoubleArray::cast(receiver->elements()));
10508       int fast_length = static_cast<int>(length);
10509       DCHECK(fast_length <= elements->length());
10510       for (int j = 0; j < fast_length; j++) {
10511         HandleScope loop_scope(isolate);
10512         if (!elements->is_the_hole(j)) {
10513           double double_value = elements->get_scalar(j);
10514           Handle<Object> element_value =
10515               isolate->factory()->NewNumber(double_value);
10516           visitor->visit(j, element_value);
10517         } else {
10518           Maybe<bool> maybe = JSReceiver::HasElement(receiver, j);
10519           if (!maybe.has_value) return false;
10520           if (maybe.value) {
10521             // Call GetElement on receiver, not its prototype, or getters won't
10522             // have the correct receiver.
10523             Handle<Object> element_value;
10524             ASSIGN_RETURN_ON_EXCEPTION_VALUE(
10525                 isolate, element_value,
10526                 Object::GetElement(isolate, receiver, j), false);
10527             visitor->visit(j, element_value);
10528           }
10529         }
10530       }
10531       break;
10532     }
10533     case DICTIONARY_ELEMENTS: {
10534       Handle<SeededNumberDictionary> dict(receiver->element_dictionary());
10535       List<uint32_t> indices(dict->Capacity() / 2);
10536       // Collect all indices in the object and the prototypes less
10537       // than length. This might introduce duplicates in the indices list.
10538       CollectElementIndices(receiver, length, &indices);
10539       indices.Sort(&compareUInt32);
10540       int j = 0;
10541       int n = indices.length();
10542       while (j < n) {
10543         HandleScope loop_scope(isolate);
10544         uint32_t index = indices[j];
10545         Handle<Object> element;
10546         ASSIGN_RETURN_ON_EXCEPTION_VALUE(
10547             isolate, element,
10548             Object::GetElement(isolate, receiver, index),
10549             false);
10550         visitor->visit(index, element);
10551         // Skip to next different index (i.e., omit duplicates).
10552         do {
10553           j++;
10554         } while (j < n && indices[j] == index);
10555       }
10556       break;
10557     }
10558     case EXTERNAL_UINT8_CLAMPED_ELEMENTS: {
10559       Handle<ExternalUint8ClampedArray> pixels(ExternalUint8ClampedArray::cast(
10560           receiver->elements()));
10561       for (uint32_t j = 0; j < length; j++) {
10562         Handle<Smi> e(Smi::FromInt(pixels->get_scalar(j)), isolate);
10563         visitor->visit(j, e);
10564       }
10565       break;
10566     }
10567     case EXTERNAL_INT8_ELEMENTS: {
10568       IterateExternalArrayElements<ExternalInt8Array, int8_t>(
10569           isolate, receiver, true, true, visitor);
10570       break;
10571     }
10572     case EXTERNAL_UINT8_ELEMENTS: {
10573       IterateExternalArrayElements<ExternalUint8Array, uint8_t>(
10574           isolate, receiver, true, true, visitor);
10575       break;
10576     }
10577     case EXTERNAL_INT16_ELEMENTS: {
10578       IterateExternalArrayElements<ExternalInt16Array, int16_t>(
10579           isolate, receiver, true, true, visitor);
10580       break;
10581     }
10582     case EXTERNAL_UINT16_ELEMENTS: {
10583       IterateExternalArrayElements<ExternalUint16Array, uint16_t>(
10584           isolate, receiver, true, true, visitor);
10585       break;
10586     }
10587     case EXTERNAL_INT32_ELEMENTS: {
10588       IterateExternalArrayElements<ExternalInt32Array, int32_t>(
10589           isolate, receiver, true, false, visitor);
10590       break;
10591     }
10592     case EXTERNAL_UINT32_ELEMENTS: {
10593       IterateExternalArrayElements<ExternalUint32Array, uint32_t>(
10594           isolate, receiver, true, false, visitor);
10595       break;
10596     }
10597     case EXTERNAL_FLOAT32_ELEMENTS: {
10598       IterateExternalArrayElements<ExternalFloat32Array, float>(
10599           isolate, receiver, false, false, visitor);
10600       break;
10601     }
10602     case EXTERNAL_FLOAT32x4_ELEMENTS: {
10603       IterateExternalFloat32x4ArrayElements(isolate, receiver, visitor);
10604       break;
10605     }
10606     case EXTERNAL_FLOAT64x2_ELEMENTS: {
10607       IterateExternalFloat64x2ArrayElements(isolate, receiver, visitor);
10608       break;
10609     }
10610     case EXTERNAL_INT32x4_ELEMENTS: {
10611       IterateExternalInt32x4ArrayElements(isolate, receiver, visitor);
10612       break;
10613     }
10614     case EXTERNAL_FLOAT64_ELEMENTS: {
10615       IterateExternalArrayElements<ExternalFloat64Array, double>(
10616           isolate, receiver, false, false, visitor);
10617       break;
10618     }
10619     default:
10620       UNREACHABLE();
10621       break;
10622   }
10623   visitor->increase_index_offset(length);
10624   return true;
10625 }
10626
10627
10628 /**
10629  * Array::concat implementation.
10630  * See ECMAScript 262, 15.4.4.4.
10631  * TODO(581): Fix non-compliance for very large concatenations and update to
10632  * following the ECMAScript 5 specification.
10633  */
10634 RUNTIME_FUNCTION(Runtime_ArrayConcat) {
10635   HandleScope handle_scope(isolate);
10636   DCHECK(args.length() == 1);
10637
10638   CONVERT_ARG_HANDLE_CHECKED(JSArray, arguments, 0);
10639   int argument_count = static_cast<int>(arguments->length()->Number());
10640   RUNTIME_ASSERT(arguments->HasFastObjectElements());
10641   Handle<FixedArray> elements(FixedArray::cast(arguments->elements()));
10642
10643   // Pass 1: estimate the length and number of elements of the result.
10644   // The actual length can be larger if any of the arguments have getters
10645   // that mutate other arguments (but will otherwise be precise).
10646   // The number of elements is precise if there are no inherited elements.
10647
10648   ElementsKind kind = FAST_SMI_ELEMENTS;
10649
10650   uint32_t estimate_result_length = 0;
10651   uint32_t estimate_nof_elements = 0;
10652   for (int i = 0; i < argument_count; i++) {
10653     HandleScope loop_scope(isolate);
10654     Handle<Object> obj(elements->get(i), isolate);
10655     uint32_t length_estimate;
10656     uint32_t element_estimate;
10657     if (obj->IsJSArray()) {
10658       Handle<JSArray> array(Handle<JSArray>::cast(obj));
10659       length_estimate = static_cast<uint32_t>(array->length()->Number());
10660       if (length_estimate != 0) {
10661         ElementsKind array_kind =
10662             GetPackedElementsKind(array->map()->elements_kind());
10663         if (IsMoreGeneralElementsKindTransition(kind, array_kind)) {
10664           kind = array_kind;
10665         }
10666       }
10667       element_estimate = EstimateElementCount(array);
10668     } else {
10669       if (obj->IsHeapObject()) {
10670         if (obj->IsNumber()) {
10671           if (IsMoreGeneralElementsKindTransition(kind, FAST_DOUBLE_ELEMENTS)) {
10672             kind = FAST_DOUBLE_ELEMENTS;
10673           }
10674         } else if (IsMoreGeneralElementsKindTransition(kind, FAST_ELEMENTS)) {
10675           kind = FAST_ELEMENTS;
10676         }
10677       }
10678       length_estimate = 1;
10679       element_estimate = 1;
10680     }
10681     // Avoid overflows by capping at kMaxElementCount.
10682     if (JSObject::kMaxElementCount - estimate_result_length <
10683         length_estimate) {
10684       estimate_result_length = JSObject::kMaxElementCount;
10685     } else {
10686       estimate_result_length += length_estimate;
10687     }
10688     if (JSObject::kMaxElementCount - estimate_nof_elements <
10689         element_estimate) {
10690       estimate_nof_elements = JSObject::kMaxElementCount;
10691     } else {
10692       estimate_nof_elements += element_estimate;
10693     }
10694   }
10695
10696   // If estimated number of elements is more than half of length, a
10697   // fixed array (fast case) is more time and space-efficient than a
10698   // dictionary.
10699   bool fast_case = (estimate_nof_elements * 2) >= estimate_result_length;
10700
10701   if (fast_case && kind == FAST_DOUBLE_ELEMENTS) {
10702     Handle<FixedArrayBase> storage =
10703         isolate->factory()->NewFixedDoubleArray(estimate_result_length);
10704     int j = 0;
10705     bool failure = false;
10706     if (estimate_result_length > 0) {
10707       Handle<FixedDoubleArray> double_storage =
10708           Handle<FixedDoubleArray>::cast(storage);
10709       for (int i = 0; i < argument_count; i++) {
10710         Handle<Object> obj(elements->get(i), isolate);
10711         if (obj->IsSmi()) {
10712           double_storage->set(j, Smi::cast(*obj)->value());
10713           j++;
10714         } else if (obj->IsNumber()) {
10715           double_storage->set(j, obj->Number());
10716           j++;
10717         } else {
10718           JSArray* array = JSArray::cast(*obj);
10719           uint32_t length = static_cast<uint32_t>(array->length()->Number());
10720           switch (array->map()->elements_kind()) {
10721             case FAST_HOLEY_DOUBLE_ELEMENTS:
10722             case FAST_DOUBLE_ELEMENTS: {
10723               // Empty array is FixedArray but not FixedDoubleArray.
10724               if (length == 0) break;
10725               FixedDoubleArray* elements =
10726                   FixedDoubleArray::cast(array->elements());
10727               for (uint32_t i = 0; i < length; i++) {
10728                 if (elements->is_the_hole(i)) {
10729                   // TODO(jkummerow/verwaest): We could be a bit more clever
10730                   // here: Check if there are no elements/getters on the
10731                   // prototype chain, and if so, allow creation of a holey
10732                   // result array.
10733                   // Same thing below (holey smi case).
10734                   failure = true;
10735                   break;
10736                 }
10737                 double double_value = elements->get_scalar(i);
10738                 double_storage->set(j, double_value);
10739                 j++;
10740               }
10741               break;
10742             }
10743             case FAST_HOLEY_SMI_ELEMENTS:
10744             case FAST_SMI_ELEMENTS: {
10745               FixedArray* elements(
10746                   FixedArray::cast(array->elements()));
10747               for (uint32_t i = 0; i < length; i++) {
10748                 Object* element = elements->get(i);
10749                 if (element->IsTheHole()) {
10750                   failure = true;
10751                   break;
10752                 }
10753                 int32_t int_value = Smi::cast(element)->value();
10754                 double_storage->set(j, int_value);
10755                 j++;
10756               }
10757               break;
10758             }
10759             case FAST_HOLEY_ELEMENTS:
10760             case FAST_ELEMENTS:
10761               DCHECK_EQ(0, length);
10762               break;
10763             default:
10764               UNREACHABLE();
10765           }
10766         }
10767         if (failure) break;
10768       }
10769     }
10770     if (!failure) {
10771       Handle<JSArray> array = isolate->factory()->NewJSArray(0);
10772       Smi* length = Smi::FromInt(j);
10773       Handle<Map> map;
10774       map = JSObject::GetElementsTransitionMap(array, kind);
10775       array->set_map(*map);
10776       array->set_length(length);
10777       array->set_elements(*storage);
10778       return *array;
10779     }
10780     // In case of failure, fall through.
10781   }
10782
10783   Handle<FixedArray> storage;
10784   if (fast_case) {
10785     // The backing storage array must have non-existing elements to preserve
10786     // holes across concat operations.
10787     storage = isolate->factory()->NewFixedArrayWithHoles(
10788         estimate_result_length);
10789   } else {
10790     // TODO(126): move 25% pre-allocation logic into Dictionary::Allocate
10791     uint32_t at_least_space_for = estimate_nof_elements +
10792                                   (estimate_nof_elements >> 2);
10793     storage = Handle<FixedArray>::cast(
10794         SeededNumberDictionary::New(isolate, at_least_space_for));
10795   }
10796
10797   ArrayConcatVisitor visitor(isolate, storage, fast_case);
10798
10799   for (int i = 0; i < argument_count; i++) {
10800     Handle<Object> obj(elements->get(i), isolate);
10801     if (obj->IsJSArray()) {
10802       Handle<JSArray> array = Handle<JSArray>::cast(obj);
10803       if (!IterateElements(isolate, array, &visitor)) {
10804         return isolate->heap()->exception();
10805       }
10806     } else {
10807       visitor.visit(0, obj);
10808       visitor.increase_index_offset(1);
10809     }
10810   }
10811
10812   if (visitor.exceeds_array_limit()) {
10813     THROW_NEW_ERROR_RETURN_FAILURE(
10814         isolate,
10815         NewRangeError("invalid_array_length", HandleVector<Object>(NULL, 0)));
10816   }
10817   return *visitor.ToArray();
10818 }
10819
10820
10821 // This will not allocate (flatten the string), but it may run
10822 // very slowly for very deeply nested ConsStrings.  For debugging use only.
10823 RUNTIME_FUNCTION(Runtime_GlobalPrint) {
10824   SealHandleScope shs(isolate);
10825   DCHECK(args.length() == 1);
10826
10827   CONVERT_ARG_CHECKED(String, string, 0);
10828   ConsStringIteratorOp op;
10829   StringCharacterStream stream(string, &op);
10830   while (stream.HasMore()) {
10831     uint16_t character = stream.GetNext();
10832     PrintF("%c", character);
10833   }
10834   return string;
10835 }
10836
10837
10838 // Moves all own elements of an object, that are below a limit, to positions
10839 // starting at zero. All undefined values are placed after non-undefined values,
10840 // and are followed by non-existing element. Does not change the length
10841 // property.
10842 // Returns the number of non-undefined elements collected.
10843 // Returns -1 if hole removal is not supported by this method.
10844 RUNTIME_FUNCTION(Runtime_RemoveArrayHoles) {
10845   HandleScope scope(isolate);
10846   DCHECK(args.length() == 2);
10847   CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0);
10848   CONVERT_NUMBER_CHECKED(uint32_t, limit, Uint32, args[1]);
10849   return *JSObject::PrepareElementsForSort(object, limit);
10850 }
10851
10852
10853 // Move contents of argument 0 (an array) to argument 1 (an array)
10854 RUNTIME_FUNCTION(Runtime_MoveArrayContents) {
10855   HandleScope scope(isolate);
10856   DCHECK(args.length() == 2);
10857   CONVERT_ARG_HANDLE_CHECKED(JSArray, from, 0);
10858   CONVERT_ARG_HANDLE_CHECKED(JSArray, to, 1);
10859   JSObject::ValidateElements(from);
10860   JSObject::ValidateElements(to);
10861
10862   Handle<FixedArrayBase> new_elements(from->elements());
10863   ElementsKind from_kind = from->GetElementsKind();
10864   Handle<Map> new_map = JSObject::GetElementsTransitionMap(to, from_kind);
10865   JSObject::SetMapAndElements(to, new_map, new_elements);
10866   to->set_length(from->length());
10867
10868   JSObject::ResetElements(from);
10869   from->set_length(Smi::FromInt(0));
10870
10871   JSObject::ValidateElements(to);
10872   return *to;
10873 }
10874
10875
10876 // How many elements does this object/array have?
10877 RUNTIME_FUNCTION(Runtime_EstimateNumberOfElements) {
10878   HandleScope scope(isolate);
10879   DCHECK(args.length() == 1);
10880   CONVERT_ARG_HANDLE_CHECKED(JSArray, array, 0);
10881   Handle<FixedArrayBase> elements(array->elements(), isolate);
10882   SealHandleScope shs(isolate);
10883   if (elements->IsDictionary()) {
10884     int result =
10885         Handle<SeededNumberDictionary>::cast(elements)->NumberOfElements();
10886     return Smi::FromInt(result);
10887   } else {
10888     DCHECK(array->length()->IsSmi());
10889     // For packed elements, we know the exact number of elements
10890     int length = elements->length();
10891     ElementsKind kind = array->GetElementsKind();
10892     if (IsFastPackedElementsKind(kind)) {
10893       return Smi::FromInt(length);
10894     }
10895     // For holey elements, take samples from the buffer checking for holes
10896     // to generate the estimate.
10897     const int kNumberOfHoleCheckSamples = 97;
10898     int increment = (length < kNumberOfHoleCheckSamples)
10899                         ? 1
10900                         : static_cast<int>(length / kNumberOfHoleCheckSamples);
10901     ElementsAccessor* accessor = array->GetElementsAccessor();
10902     int holes = 0;
10903     for (int i = 0; i < length; i += increment) {
10904       if (!accessor->HasElement(array, array, i, elements)) {
10905         ++holes;
10906       }
10907     }
10908     int estimate = static_cast<int>((kNumberOfHoleCheckSamples - holes) /
10909                                     kNumberOfHoleCheckSamples * length);
10910     return Smi::FromInt(estimate);
10911   }
10912 }
10913
10914
10915 // Returns an array that tells you where in the [0, length) interval an array
10916 // might have elements.  Can either return an array of keys (positive integers
10917 // or undefined) or a number representing the positive length of an interval
10918 // starting at index 0.
10919 // Intervals can span over some keys that are not in the object.
10920 RUNTIME_FUNCTION(Runtime_GetArrayKeys) {
10921   HandleScope scope(isolate);
10922   DCHECK(args.length() == 2);
10923   CONVERT_ARG_HANDLE_CHECKED(JSObject, array, 0);
10924   CONVERT_NUMBER_CHECKED(uint32_t, length, Uint32, args[1]);
10925   if (array->elements()->IsDictionary()) {
10926     Handle<FixedArray> keys = isolate->factory()->empty_fixed_array();
10927     for (PrototypeIterator iter(isolate, array,
10928                                 PrototypeIterator::START_AT_RECEIVER);
10929          !iter.IsAtEnd(); iter.Advance()) {
10930       if (PrototypeIterator::GetCurrent(iter)->IsJSProxy() ||
10931           JSObject::cast(*PrototypeIterator::GetCurrent(iter))
10932               ->HasIndexedInterceptor()) {
10933         // Bail out if we find a proxy or interceptor, likely not worth
10934         // collecting keys in that case.
10935         return *isolate->factory()->NewNumberFromUint(length);
10936       }
10937       Handle<JSObject> current =
10938           Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter));
10939       Handle<FixedArray> current_keys =
10940           isolate->factory()->NewFixedArray(current->NumberOfOwnElements(NONE));
10941       current->GetOwnElementKeys(*current_keys, NONE);
10942       ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
10943           isolate, keys, FixedArray::UnionOfKeys(keys, current_keys));
10944     }
10945     // Erase any keys >= length.
10946     // TODO(adamk): Remove this step when the contract of %GetArrayKeys
10947     // is changed to let this happen on the JS side.
10948     for (int i = 0; i < keys->length(); i++) {
10949       if (NumberToUint32(keys->get(i)) >= length) keys->set_undefined(i);
10950     }
10951     return *isolate->factory()->NewJSArrayWithElements(keys);
10952   } else {
10953     RUNTIME_ASSERT(array->HasFastSmiOrObjectElements() ||
10954                    array->HasFastDoubleElements());
10955     uint32_t actual_length = static_cast<uint32_t>(array->elements()->length());
10956     return *isolate->factory()->NewNumberFromUint(Min(actual_length, length));
10957   }
10958 }
10959
10960
10961 RUNTIME_FUNCTION(Runtime_LookupAccessor) {
10962   HandleScope scope(isolate);
10963   DCHECK(args.length() == 3);
10964   CONVERT_ARG_HANDLE_CHECKED(JSReceiver, receiver, 0);
10965   CONVERT_ARG_HANDLE_CHECKED(Name, name, 1);
10966   CONVERT_SMI_ARG_CHECKED(flag, 2);
10967   AccessorComponent component = flag == 0 ? ACCESSOR_GETTER : ACCESSOR_SETTER;
10968   if (!receiver->IsJSObject()) return isolate->heap()->undefined_value();
10969   Handle<Object> result;
10970   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
10971       isolate, result,
10972       JSObject::GetAccessor(Handle<JSObject>::cast(receiver), name, component));
10973   return *result;
10974 }
10975
10976
10977 RUNTIME_FUNCTION(Runtime_DebugBreak) {
10978   SealHandleScope shs(isolate);
10979   DCHECK(args.length() == 0);
10980   isolate->debug()->HandleDebugBreak();
10981   return isolate->heap()->undefined_value();
10982 }
10983
10984
10985 // Helper functions for wrapping and unwrapping stack frame ids.
10986 static Smi* WrapFrameId(StackFrame::Id id) {
10987   DCHECK(IsAligned(OffsetFrom(id), static_cast<intptr_t>(4)));
10988   return Smi::FromInt(id >> 2);
10989 }
10990
10991
10992 static StackFrame::Id UnwrapFrameId(int wrapped) {
10993   return static_cast<StackFrame::Id>(wrapped << 2);
10994 }
10995
10996
10997 // Adds a JavaScript function as a debug event listener.
10998 // args[0]: debug event listener function to set or null or undefined for
10999 //          clearing the event listener function
11000 // args[1]: object supplied during callback
11001 RUNTIME_FUNCTION(Runtime_SetDebugEventListener) {
11002   SealHandleScope shs(isolate);
11003   DCHECK(args.length() == 2);
11004   RUNTIME_ASSERT(args[0]->IsJSFunction() ||
11005                  args[0]->IsUndefined() ||
11006                  args[0]->IsNull());
11007   CONVERT_ARG_HANDLE_CHECKED(Object, callback, 0);
11008   CONVERT_ARG_HANDLE_CHECKED(Object, data, 1);
11009   isolate->debug()->SetEventListener(callback, data);
11010
11011   return isolate->heap()->undefined_value();
11012 }
11013
11014
11015 RUNTIME_FUNCTION(Runtime_Break) {
11016   SealHandleScope shs(isolate);
11017   DCHECK(args.length() == 0);
11018   isolate->stack_guard()->RequestDebugBreak();
11019   return isolate->heap()->undefined_value();
11020 }
11021
11022
11023 static Handle<Object> DebugGetProperty(LookupIterator* it,
11024                                        bool* has_caught = NULL) {
11025   for (; it->IsFound(); it->Next()) {
11026     switch (it->state()) {
11027       case LookupIterator::NOT_FOUND:
11028       case LookupIterator::TRANSITION:
11029         UNREACHABLE();
11030       case LookupIterator::ACCESS_CHECK:
11031         // Ignore access checks.
11032         break;
11033       case LookupIterator::INTERCEPTOR:
11034       case LookupIterator::JSPROXY:
11035         return it->isolate()->factory()->undefined_value();
11036       case LookupIterator::ACCESSOR: {
11037         Handle<Object> accessors = it->GetAccessors();
11038         if (!accessors->IsAccessorInfo()) {
11039           return it->isolate()->factory()->undefined_value();
11040         }
11041         MaybeHandle<Object> maybe_result = JSObject::GetPropertyWithAccessor(
11042             it->GetReceiver(), it->name(), it->GetHolder<JSObject>(),
11043             accessors);
11044         Handle<Object> result;
11045         if (!maybe_result.ToHandle(&result)) {
11046           result = handle(it->isolate()->pending_exception(), it->isolate());
11047           it->isolate()->clear_pending_exception();
11048           if (has_caught != NULL) *has_caught = true;
11049         }
11050         return result;
11051       }
11052
11053       case LookupIterator::DATA:
11054         return it->GetDataValue();
11055     }
11056   }
11057
11058   return it->isolate()->factory()->undefined_value();
11059 }
11060
11061
11062 // Get debugger related details for an object property, in the following format:
11063 // 0: Property value
11064 // 1: Property details
11065 // 2: Property value is exception
11066 // 3: Getter function if defined
11067 // 4: Setter function if defined
11068 // Items 2-4 are only filled if the property has either a getter or a setter.
11069 RUNTIME_FUNCTION(Runtime_DebugGetPropertyDetails) {
11070   HandleScope scope(isolate);
11071
11072   DCHECK(args.length() == 2);
11073
11074   CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0);
11075   CONVERT_ARG_HANDLE_CHECKED(Name, name, 1);
11076
11077   // Make sure to set the current context to the context before the debugger was
11078   // entered (if the debugger is entered). The reason for switching context here
11079   // is that for some property lookups (accessors and interceptors) callbacks
11080   // into the embedding application can occour, and the embedding application
11081   // could have the assumption that its own native context is the current
11082   // context and not some internal debugger context.
11083   SaveContext save(isolate);
11084   if (isolate->debug()->in_debug_scope()) {
11085     isolate->set_context(*isolate->debug()->debugger_entry()->GetContext());
11086   }
11087
11088   // Check if the name is trivially convertible to an index and get the element
11089   // if so.
11090   uint32_t index;
11091   if (name->AsArrayIndex(&index)) {
11092     Handle<FixedArray> details = isolate->factory()->NewFixedArray(2);
11093     Handle<Object> element_or_char;
11094     ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
11095         isolate, element_or_char,
11096         Runtime::GetElementOrCharAt(isolate, obj, index));
11097     details->set(0, *element_or_char);
11098     details->set(
11099         1, PropertyDetails(NONE, NORMAL, Representation::None()).AsSmi());
11100     return *isolate->factory()->NewJSArrayWithElements(details);
11101   }
11102
11103   LookupIterator it(obj, name, LookupIterator::HIDDEN);
11104   bool has_caught = false;
11105   Handle<Object> value = DebugGetProperty(&it, &has_caught);
11106   if (!it.IsFound()) return isolate->heap()->undefined_value();
11107
11108   Handle<Object> maybe_pair;
11109   if (it.state() == LookupIterator::ACCESSOR) {
11110     maybe_pair = it.GetAccessors();
11111   }
11112
11113   // If the callback object is a fixed array then it contains JavaScript
11114   // getter and/or setter.
11115   bool has_js_accessors = !maybe_pair.is_null() && maybe_pair->IsAccessorPair();
11116   Handle<FixedArray> details =
11117       isolate->factory()->NewFixedArray(has_js_accessors ? 6 : 3);
11118   details->set(0, *value);
11119   // TODO(verwaest): Get rid of this random way of handling interceptors.
11120   PropertyDetails d = it.state() == LookupIterator::INTERCEPTOR
11121                           ? PropertyDetails(NONE, NORMAL, 0)
11122                           : it.property_details();
11123   details->set(1, d.AsSmi());
11124   details->set(
11125       2, isolate->heap()->ToBoolean(it.state() == LookupIterator::INTERCEPTOR));
11126   if (has_js_accessors) {
11127     AccessorPair* accessors = AccessorPair::cast(*maybe_pair);
11128     details->set(3, isolate->heap()->ToBoolean(has_caught));
11129     details->set(4, accessors->GetComponent(ACCESSOR_GETTER));
11130     details->set(5, accessors->GetComponent(ACCESSOR_SETTER));
11131   }
11132
11133   return *isolate->factory()->NewJSArrayWithElements(details);
11134 }
11135
11136
11137 RUNTIME_FUNCTION(Runtime_DebugGetProperty) {
11138   HandleScope scope(isolate);
11139
11140   DCHECK(args.length() == 2);
11141
11142   CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0);
11143   CONVERT_ARG_HANDLE_CHECKED(Name, name, 1);
11144
11145   LookupIterator it(obj, name);
11146   return *DebugGetProperty(&it);
11147 }
11148
11149
11150 // Return the property type calculated from the property details.
11151 // args[0]: smi with property details.
11152 RUNTIME_FUNCTION(Runtime_DebugPropertyTypeFromDetails) {
11153   SealHandleScope shs(isolate);
11154   DCHECK(args.length() == 1);
11155   CONVERT_PROPERTY_DETAILS_CHECKED(details, 0);
11156   return Smi::FromInt(static_cast<int>(details.type()));
11157 }
11158
11159
11160 // Return the property attribute calculated from the property details.
11161 // args[0]: smi with property details.
11162 RUNTIME_FUNCTION(Runtime_DebugPropertyAttributesFromDetails) {
11163   SealHandleScope shs(isolate);
11164   DCHECK(args.length() == 1);
11165   CONVERT_PROPERTY_DETAILS_CHECKED(details, 0);
11166   return Smi::FromInt(static_cast<int>(details.attributes()));
11167 }
11168
11169
11170 // Return the property insertion index calculated from the property details.
11171 // args[0]: smi with property details.
11172 RUNTIME_FUNCTION(Runtime_DebugPropertyIndexFromDetails) {
11173   SealHandleScope shs(isolate);
11174   DCHECK(args.length() == 1);
11175   CONVERT_PROPERTY_DETAILS_CHECKED(details, 0);
11176   // TODO(verwaest): Depends on the type of details.
11177   return Smi::FromInt(details.dictionary_index());
11178 }
11179
11180
11181 // Return property value from named interceptor.
11182 // args[0]: object
11183 // args[1]: property name
11184 RUNTIME_FUNCTION(Runtime_DebugNamedInterceptorPropertyValue) {
11185   HandleScope scope(isolate);
11186   DCHECK(args.length() == 2);
11187   CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0);
11188   RUNTIME_ASSERT(obj->HasNamedInterceptor());
11189   CONVERT_ARG_HANDLE_CHECKED(Name, name, 1);
11190
11191   Handle<Object> result;
11192   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
11193       isolate, result, JSObject::GetProperty(obj, name));
11194   return *result;
11195 }
11196
11197
11198 // Return element value from indexed interceptor.
11199 // args[0]: object
11200 // args[1]: index
11201 RUNTIME_FUNCTION(Runtime_DebugIndexedInterceptorElementValue) {
11202   HandleScope scope(isolate);
11203   DCHECK(args.length() == 2);
11204   CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0);
11205   RUNTIME_ASSERT(obj->HasIndexedInterceptor());
11206   CONVERT_NUMBER_CHECKED(uint32_t, index, Uint32, args[1]);
11207   Handle<Object> result;
11208   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
11209       isolate, result, JSObject::GetElementWithInterceptor(obj, obj, index));
11210   return *result;
11211 }
11212
11213
11214 static bool CheckExecutionState(Isolate* isolate, int break_id) {
11215   return !isolate->debug()->debug_context().is_null() &&
11216          isolate->debug()->break_id() != 0 &&
11217          isolate->debug()->break_id() == break_id;
11218 }
11219
11220
11221 RUNTIME_FUNCTION(Runtime_CheckExecutionState) {
11222   SealHandleScope shs(isolate);
11223   DCHECK(args.length() == 1);
11224   CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
11225   RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
11226   return isolate->heap()->true_value();
11227 }
11228
11229
11230 RUNTIME_FUNCTION(Runtime_GetFrameCount) {
11231   HandleScope scope(isolate);
11232   DCHECK(args.length() == 1);
11233   CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
11234   RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
11235
11236   // Count all frames which are relevant to debugging stack trace.
11237   int n = 0;
11238   StackFrame::Id id = isolate->debug()->break_frame_id();
11239   if (id == StackFrame::NO_ID) {
11240     // If there is no JavaScript stack frame count is 0.
11241     return Smi::FromInt(0);
11242   }
11243
11244   for (JavaScriptFrameIterator it(isolate, id); !it.done(); it.Advance()) {
11245     List<FrameSummary> frames(FLAG_max_inlining_levels + 1);
11246     it.frame()->Summarize(&frames);
11247     for (int i = frames.length() - 1; i >= 0; i--) {
11248       // Omit functions from native scripts.
11249       if (!frames[i].function()->IsFromNativeScript()) n++;
11250     }
11251   }
11252   return Smi::FromInt(n);
11253 }
11254
11255
11256 class FrameInspector {
11257  public:
11258   FrameInspector(JavaScriptFrame* frame,
11259                  int inlined_jsframe_index,
11260                  Isolate* isolate)
11261       : frame_(frame), deoptimized_frame_(NULL), isolate_(isolate) {
11262     // Calculate the deoptimized frame.
11263     if (frame->is_optimized()) {
11264       deoptimized_frame_ = Deoptimizer::DebuggerInspectableFrame(
11265           frame, inlined_jsframe_index, isolate);
11266     }
11267     has_adapted_arguments_ = frame_->has_adapted_arguments();
11268     is_bottommost_ = inlined_jsframe_index == 0;
11269     is_optimized_ = frame_->is_optimized();
11270   }
11271
11272   ~FrameInspector() {
11273     // Get rid of the calculated deoptimized frame if any.
11274     if (deoptimized_frame_ != NULL) {
11275       Deoptimizer::DeleteDebuggerInspectableFrame(deoptimized_frame_,
11276                                                   isolate_);
11277     }
11278   }
11279
11280   int GetParametersCount() {
11281     return is_optimized_
11282         ? deoptimized_frame_->parameters_count()
11283         : frame_->ComputeParametersCount();
11284   }
11285   int expression_count() { return deoptimized_frame_->expression_count(); }
11286   Object* GetFunction() {
11287     return is_optimized_
11288         ? deoptimized_frame_->GetFunction()
11289         : frame_->function();
11290   }
11291   Object* GetParameter(int index) {
11292     return is_optimized_
11293         ? deoptimized_frame_->GetParameter(index)
11294         : frame_->GetParameter(index);
11295   }
11296   Object* GetExpression(int index) {
11297     return is_optimized_
11298         ? deoptimized_frame_->GetExpression(index)
11299         : frame_->GetExpression(index);
11300   }
11301   int GetSourcePosition() {
11302     return is_optimized_
11303         ? deoptimized_frame_->GetSourcePosition()
11304         : frame_->LookupCode()->SourcePosition(frame_->pc());
11305   }
11306   bool IsConstructor() {
11307     return is_optimized_ && !is_bottommost_
11308         ? deoptimized_frame_->HasConstructStub()
11309         : frame_->IsConstructor();
11310   }
11311   Object* GetContext() {
11312     return is_optimized_ ? deoptimized_frame_->GetContext() : frame_->context();
11313   }
11314
11315   // To inspect all the provided arguments the frame might need to be
11316   // replaced with the arguments frame.
11317   void SetArgumentsFrame(JavaScriptFrame* frame) {
11318     DCHECK(has_adapted_arguments_);
11319     frame_ = frame;
11320     is_optimized_ = frame_->is_optimized();
11321     DCHECK(!is_optimized_);
11322   }
11323
11324  private:
11325   JavaScriptFrame* frame_;
11326   DeoptimizedFrameInfo* deoptimized_frame_;
11327   Isolate* isolate_;
11328   bool is_optimized_;
11329   bool is_bottommost_;
11330   bool has_adapted_arguments_;
11331
11332   DISALLOW_COPY_AND_ASSIGN(FrameInspector);
11333 };
11334
11335
11336 static const int kFrameDetailsFrameIdIndex = 0;
11337 static const int kFrameDetailsReceiverIndex = 1;
11338 static const int kFrameDetailsFunctionIndex = 2;
11339 static const int kFrameDetailsArgumentCountIndex = 3;
11340 static const int kFrameDetailsLocalCountIndex = 4;
11341 static const int kFrameDetailsSourcePositionIndex = 5;
11342 static const int kFrameDetailsConstructCallIndex = 6;
11343 static const int kFrameDetailsAtReturnIndex = 7;
11344 static const int kFrameDetailsFlagsIndex = 8;
11345 static const int kFrameDetailsFirstDynamicIndex = 9;
11346
11347
11348 static SaveContext* FindSavedContextForFrame(Isolate* isolate,
11349                                              JavaScriptFrame* frame) {
11350   SaveContext* save = isolate->save_context();
11351   while (save != NULL && !save->IsBelowFrame(frame)) {
11352     save = save->prev();
11353   }
11354   DCHECK(save != NULL);
11355   return save;
11356 }
11357
11358
11359 // Advances the iterator to the frame that matches the index and returns the
11360 // inlined frame index, or -1 if not found.  Skips native JS functions.
11361 static int FindIndexedNonNativeFrame(JavaScriptFrameIterator* it, int index) {
11362   int count = -1;
11363   for (; !it->done(); it->Advance()) {
11364     List<FrameSummary> frames(FLAG_max_inlining_levels + 1);
11365     it->frame()->Summarize(&frames);
11366     for (int i = frames.length() - 1; i >= 0; i--) {
11367       // Omit functions from native scripts.
11368       if (frames[i].function()->IsFromNativeScript()) continue;
11369       if (++count == index) return i;
11370     }
11371   }
11372   return -1;
11373 }
11374
11375
11376 // Return an array with frame details
11377 // args[0]: number: break id
11378 // args[1]: number: frame index
11379 //
11380 // The array returned contains the following information:
11381 // 0: Frame id
11382 // 1: Receiver
11383 // 2: Function
11384 // 3: Argument count
11385 // 4: Local count
11386 // 5: Source position
11387 // 6: Constructor call
11388 // 7: Is at return
11389 // 8: Flags
11390 // Arguments name, value
11391 // Locals name, value
11392 // Return value if any
11393 RUNTIME_FUNCTION(Runtime_GetFrameDetails) {
11394   HandleScope scope(isolate);
11395   DCHECK(args.length() == 2);
11396   CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
11397   RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
11398
11399   CONVERT_NUMBER_CHECKED(int, index, Int32, args[1]);
11400   Heap* heap = isolate->heap();
11401
11402   // Find the relevant frame with the requested index.
11403   StackFrame::Id id = isolate->debug()->break_frame_id();
11404   if (id == StackFrame::NO_ID) {
11405     // If there are no JavaScript stack frames return undefined.
11406     return heap->undefined_value();
11407   }
11408
11409   JavaScriptFrameIterator it(isolate, id);
11410   // Inlined frame index in optimized frame, starting from outer function.
11411   int inlined_jsframe_index = FindIndexedNonNativeFrame(&it, index);
11412   if (inlined_jsframe_index == -1) return heap->undefined_value();
11413
11414   FrameInspector frame_inspector(it.frame(), inlined_jsframe_index, isolate);
11415   bool is_optimized = it.frame()->is_optimized();
11416
11417   // Traverse the saved contexts chain to find the active context for the
11418   // selected frame.
11419   SaveContext* save = FindSavedContextForFrame(isolate, it.frame());
11420
11421   // Get the frame id.
11422   Handle<Object> frame_id(WrapFrameId(it.frame()->id()), isolate);
11423
11424   // Find source position in unoptimized code.
11425   int position = frame_inspector.GetSourcePosition();
11426
11427   // Check for constructor frame.
11428   bool constructor = frame_inspector.IsConstructor();
11429
11430   // Get scope info and read from it for local variable information.
11431   Handle<JSFunction> function(JSFunction::cast(frame_inspector.GetFunction()));
11432   Handle<SharedFunctionInfo> shared(function->shared());
11433   Handle<ScopeInfo> scope_info(shared->scope_info());
11434   DCHECK(*scope_info != ScopeInfo::Empty(isolate));
11435
11436   // Get the locals names and values into a temporary array.
11437   int local_count = scope_info->LocalCount();
11438   for (int slot = 0; slot < scope_info->LocalCount(); ++slot) {
11439     // Hide compiler-introduced temporary variables, whether on the stack or on
11440     // the context.
11441     if (scope_info->LocalIsSynthetic(slot))
11442       local_count--;
11443   }
11444
11445   Handle<FixedArray> locals =
11446       isolate->factory()->NewFixedArray(local_count * 2);
11447
11448   // Fill in the values of the locals.
11449   int local = 0;
11450   int i = 0;
11451   for (; i < scope_info->StackLocalCount(); ++i) {
11452     // Use the value from the stack.
11453     if (scope_info->LocalIsSynthetic(i))
11454       continue;
11455     locals->set(local * 2, scope_info->LocalName(i));
11456     locals->set(local * 2 + 1, frame_inspector.GetExpression(i));
11457     local++;
11458   }
11459   if (local < local_count) {
11460     // Get the context containing declarations.
11461     Handle<Context> context(
11462         Context::cast(frame_inspector.GetContext())->declaration_context());
11463     for (; i < scope_info->LocalCount(); ++i) {
11464       if (scope_info->LocalIsSynthetic(i))
11465         continue;
11466       Handle<String> name(scope_info->LocalName(i));
11467       VariableMode mode;
11468       InitializationFlag init_flag;
11469       MaybeAssignedFlag maybe_assigned_flag;
11470       locals->set(local * 2, *name);
11471       int context_slot_index = ScopeInfo::ContextSlotIndex(
11472           scope_info, name, &mode, &init_flag, &maybe_assigned_flag);
11473       Object* value = context->get(context_slot_index);
11474       locals->set(local * 2 + 1, value);
11475       local++;
11476     }
11477   }
11478
11479   // Check whether this frame is positioned at return. If not top
11480   // frame or if the frame is optimized it cannot be at a return.
11481   bool at_return = false;
11482   if (!is_optimized && index == 0) {
11483     at_return = isolate->debug()->IsBreakAtReturn(it.frame());
11484   }
11485
11486   // If positioned just before return find the value to be returned and add it
11487   // to the frame information.
11488   Handle<Object> return_value = isolate->factory()->undefined_value();
11489   if (at_return) {
11490     StackFrameIterator it2(isolate);
11491     Address internal_frame_sp = NULL;
11492     while (!it2.done()) {
11493       if (it2.frame()->is_internal()) {
11494         internal_frame_sp = it2.frame()->sp();
11495       } else {
11496         if (it2.frame()->is_java_script()) {
11497           if (it2.frame()->id() == it.frame()->id()) {
11498             // The internal frame just before the JavaScript frame contains the
11499             // value to return on top. A debug break at return will create an
11500             // internal frame to store the return value (eax/rax/r0) before
11501             // entering the debug break exit frame.
11502             if (internal_frame_sp != NULL) {
11503               return_value =
11504                   Handle<Object>(Memory::Object_at(internal_frame_sp),
11505                                  isolate);
11506               break;
11507             }
11508           }
11509         }
11510
11511         // Indicate that the previous frame was not an internal frame.
11512         internal_frame_sp = NULL;
11513       }
11514       it2.Advance();
11515     }
11516   }
11517
11518   // Now advance to the arguments adapter frame (if any). It contains all
11519   // the provided parameters whereas the function frame always have the number
11520   // of arguments matching the functions parameters. The rest of the
11521   // information (except for what is collected above) is the same.
11522   if ((inlined_jsframe_index == 0) && it.frame()->has_adapted_arguments()) {
11523     it.AdvanceToArgumentsFrame();
11524     frame_inspector.SetArgumentsFrame(it.frame());
11525   }
11526
11527   // Find the number of arguments to fill. At least fill the number of
11528   // parameters for the function and fill more if more parameters are provided.
11529   int argument_count = scope_info->ParameterCount();
11530   if (argument_count < frame_inspector.GetParametersCount()) {
11531     argument_count = frame_inspector.GetParametersCount();
11532   }
11533
11534   // Calculate the size of the result.
11535   int details_size = kFrameDetailsFirstDynamicIndex +
11536                      2 * (argument_count + local_count) +
11537                      (at_return ? 1 : 0);
11538   Handle<FixedArray> details = isolate->factory()->NewFixedArray(details_size);
11539
11540   // Add the frame id.
11541   details->set(kFrameDetailsFrameIdIndex, *frame_id);
11542
11543   // Add the function (same as in function frame).
11544   details->set(kFrameDetailsFunctionIndex, frame_inspector.GetFunction());
11545
11546   // Add the arguments count.
11547   details->set(kFrameDetailsArgumentCountIndex, Smi::FromInt(argument_count));
11548
11549   // Add the locals count
11550   details->set(kFrameDetailsLocalCountIndex,
11551                Smi::FromInt(local_count));
11552
11553   // Add the source position.
11554   if (position != RelocInfo::kNoPosition) {
11555     details->set(kFrameDetailsSourcePositionIndex, Smi::FromInt(position));
11556   } else {
11557     details->set(kFrameDetailsSourcePositionIndex, heap->undefined_value());
11558   }
11559
11560   // Add the constructor information.
11561   details->set(kFrameDetailsConstructCallIndex, heap->ToBoolean(constructor));
11562
11563   // Add the at return information.
11564   details->set(kFrameDetailsAtReturnIndex, heap->ToBoolean(at_return));
11565
11566   // Add flags to indicate information on whether this frame is
11567   //   bit 0: invoked in the debugger context.
11568   //   bit 1: optimized frame.
11569   //   bit 2: inlined in optimized frame
11570   int flags = 0;
11571   if (*save->context() == *isolate->debug()->debug_context()) {
11572     flags |= 1 << 0;
11573   }
11574   if (is_optimized) {
11575     flags |= 1 << 1;
11576     flags |= inlined_jsframe_index << 2;
11577   }
11578   details->set(kFrameDetailsFlagsIndex, Smi::FromInt(flags));
11579
11580   // Fill the dynamic part.
11581   int details_index = kFrameDetailsFirstDynamicIndex;
11582
11583   // Add arguments name and value.
11584   for (int i = 0; i < argument_count; i++) {
11585     // Name of the argument.
11586     if (i < scope_info->ParameterCount()) {
11587       details->set(details_index++, scope_info->ParameterName(i));
11588     } else {
11589       details->set(details_index++, heap->undefined_value());
11590     }
11591
11592     // Parameter value.
11593     if (i < frame_inspector.GetParametersCount()) {
11594       // Get the value from the stack.
11595       details->set(details_index++, frame_inspector.GetParameter(i));
11596     } else {
11597       details->set(details_index++, heap->undefined_value());
11598     }
11599   }
11600
11601   // Add locals name and value from the temporary copy from the function frame.
11602   for (int i = 0; i < local_count * 2; i++) {
11603     details->set(details_index++, locals->get(i));
11604   }
11605
11606   // Add the value being returned.
11607   if (at_return) {
11608     details->set(details_index++, *return_value);
11609   }
11610
11611   // Add the receiver (same as in function frame).
11612   // THIS MUST BE DONE LAST SINCE WE MIGHT ADVANCE
11613   // THE FRAME ITERATOR TO WRAP THE RECEIVER.
11614   Handle<Object> receiver(it.frame()->receiver(), isolate);
11615   if (!receiver->IsJSObject() &&
11616       shared->strict_mode() == SLOPPY &&
11617       !function->IsBuiltin()) {
11618     // If the receiver is not a JSObject and the function is not a
11619     // builtin or strict-mode we have hit an optimization where a
11620     // value object is not converted into a wrapped JS objects. To
11621     // hide this optimization from the debugger, we wrap the receiver
11622     // by creating correct wrapper object based on the calling frame's
11623     // native context.
11624     it.Advance();
11625     if (receiver->IsUndefined()) {
11626       receiver = handle(function->global_proxy());
11627     } else {
11628       Context* context = Context::cast(it.frame()->context());
11629       Handle<Context> native_context(Context::cast(context->native_context()));
11630       if (!Object::ToObject(isolate, receiver, native_context)
11631                .ToHandle(&receiver)) {
11632         // This only happens if the receiver is forcibly set in %_CallFunction.
11633         return heap->undefined_value();
11634       }
11635     }
11636   }
11637   details->set(kFrameDetailsReceiverIndex, *receiver);
11638
11639   DCHECK_EQ(details_size, details_index);
11640   return *isolate->factory()->NewJSArrayWithElements(details);
11641 }
11642
11643
11644 static bool ParameterIsShadowedByContextLocal(Handle<ScopeInfo> info,
11645                                               Handle<String> parameter_name) {
11646   VariableMode mode;
11647   InitializationFlag init_flag;
11648   MaybeAssignedFlag maybe_assigned_flag;
11649   return ScopeInfo::ContextSlotIndex(info, parameter_name, &mode, &init_flag,
11650                                      &maybe_assigned_flag) != -1;
11651 }
11652
11653
11654 // Create a plain JSObject which materializes the local scope for the specified
11655 // frame.
11656 MUST_USE_RESULT
11657 static MaybeHandle<JSObject> MaterializeStackLocalsWithFrameInspector(
11658     Isolate* isolate,
11659     Handle<JSObject> target,
11660     Handle<JSFunction> function,
11661     FrameInspector* frame_inspector) {
11662   Handle<SharedFunctionInfo> shared(function->shared());
11663   Handle<ScopeInfo> scope_info(shared->scope_info());
11664
11665   // First fill all parameters.
11666   for (int i = 0; i < scope_info->ParameterCount(); ++i) {
11667     // Do not materialize the parameter if it is shadowed by a context local.
11668     Handle<String> name(scope_info->ParameterName(i));
11669     if (ParameterIsShadowedByContextLocal(scope_info, name)) continue;
11670
11671     HandleScope scope(isolate);
11672     Handle<Object> value(i < frame_inspector->GetParametersCount()
11673                              ? frame_inspector->GetParameter(i)
11674                              : isolate->heap()->undefined_value(),
11675                          isolate);
11676     DCHECK(!value->IsTheHole());
11677
11678     RETURN_ON_EXCEPTION(
11679         isolate,
11680         Runtime::SetObjectProperty(isolate, target, name, value, SLOPPY),
11681         JSObject);
11682   }
11683
11684   // Second fill all stack locals.
11685   for (int i = 0; i < scope_info->StackLocalCount(); ++i) {
11686     if (scope_info->LocalIsSynthetic(i)) continue;
11687     Handle<String> name(scope_info->StackLocalName(i));
11688     Handle<Object> value(frame_inspector->GetExpression(i), isolate);
11689     if (value->IsTheHole()) continue;
11690
11691     RETURN_ON_EXCEPTION(
11692         isolate,
11693         Runtime::SetObjectProperty(isolate, target, name, value, SLOPPY),
11694         JSObject);
11695   }
11696
11697   return target;
11698 }
11699
11700
11701 static void UpdateStackLocalsFromMaterializedObject(Isolate* isolate,
11702                                                     Handle<JSObject> target,
11703                                                     Handle<JSFunction> function,
11704                                                     JavaScriptFrame* frame,
11705                                                     int inlined_jsframe_index) {
11706   if (inlined_jsframe_index != 0 || frame->is_optimized()) {
11707     // Optimized frames are not supported.
11708     // TODO(yangguo): make sure all code deoptimized when debugger is active
11709     //                and assert that this cannot happen.
11710     return;
11711   }
11712
11713   Handle<SharedFunctionInfo> shared(function->shared());
11714   Handle<ScopeInfo> scope_info(shared->scope_info());
11715
11716   // Parameters.
11717   for (int i = 0; i < scope_info->ParameterCount(); ++i) {
11718     // Shadowed parameters were not materialized.
11719     Handle<String> name(scope_info->ParameterName(i));
11720     if (ParameterIsShadowedByContextLocal(scope_info, name)) continue;
11721
11722     DCHECK(!frame->GetParameter(i)->IsTheHole());
11723     HandleScope scope(isolate);
11724     Handle<Object> value =
11725         Object::GetPropertyOrElement(target, name).ToHandleChecked();
11726     frame->SetParameterValue(i, *value);
11727   }
11728
11729   // Stack locals.
11730   for (int i = 0; i < scope_info->StackLocalCount(); ++i) {
11731     if (scope_info->LocalIsSynthetic(i)) continue;
11732     if (frame->GetExpression(i)->IsTheHole()) continue;
11733     HandleScope scope(isolate);
11734     Handle<Object> value = Object::GetPropertyOrElement(
11735         target,
11736         handle(scope_info->StackLocalName(i), isolate)).ToHandleChecked();
11737     frame->SetExpression(i, *value);
11738   }
11739 }
11740
11741
11742 MUST_USE_RESULT static MaybeHandle<JSObject> MaterializeLocalContext(
11743     Isolate* isolate,
11744     Handle<JSObject> target,
11745     Handle<JSFunction> function,
11746     JavaScriptFrame* frame) {
11747   HandleScope scope(isolate);
11748   Handle<SharedFunctionInfo> shared(function->shared());
11749   Handle<ScopeInfo> scope_info(shared->scope_info());
11750
11751   if (!scope_info->HasContext()) return target;
11752
11753   // Third fill all context locals.
11754   Handle<Context> frame_context(Context::cast(frame->context()));
11755   Handle<Context> function_context(frame_context->declaration_context());
11756   if (!ScopeInfo::CopyContextLocalsToScopeObject(
11757           scope_info, function_context, target)) {
11758     return MaybeHandle<JSObject>();
11759   }
11760
11761   // Finally copy any properties from the function context extension.
11762   // These will be variables introduced by eval.
11763   if (function_context->closure() == *function) {
11764     if (function_context->has_extension() &&
11765         !function_context->IsNativeContext()) {
11766       Handle<JSObject> ext(JSObject::cast(function_context->extension()));
11767       Handle<FixedArray> keys;
11768       ASSIGN_RETURN_ON_EXCEPTION(
11769           isolate, keys,
11770           JSReceiver::GetKeys(ext, JSReceiver::INCLUDE_PROTOS),
11771           JSObject);
11772
11773       for (int i = 0; i < keys->length(); i++) {
11774         // Names of variables introduced by eval are strings.
11775         DCHECK(keys->get(i)->IsString());
11776         Handle<String> key(String::cast(keys->get(i)));
11777         Handle<Object> value;
11778         ASSIGN_RETURN_ON_EXCEPTION(
11779             isolate, value, Object::GetPropertyOrElement(ext, key), JSObject);
11780         RETURN_ON_EXCEPTION(
11781             isolate,
11782             Runtime::SetObjectProperty(isolate, target, key, value, SLOPPY),
11783             JSObject);
11784       }
11785     }
11786   }
11787
11788   return target;
11789 }
11790
11791
11792 MUST_USE_RESULT static MaybeHandle<JSObject> MaterializeLocalScope(
11793     Isolate* isolate,
11794     JavaScriptFrame* frame,
11795     int inlined_jsframe_index) {
11796   FrameInspector frame_inspector(frame, inlined_jsframe_index, isolate);
11797   Handle<JSFunction> function(JSFunction::cast(frame_inspector.GetFunction()));
11798
11799   Handle<JSObject> local_scope =
11800       isolate->factory()->NewJSObject(isolate->object_function());
11801   ASSIGN_RETURN_ON_EXCEPTION(
11802       isolate, local_scope,
11803       MaterializeStackLocalsWithFrameInspector(
11804           isolate, local_scope, function, &frame_inspector),
11805       JSObject);
11806
11807   return MaterializeLocalContext(isolate, local_scope, function, frame);
11808 }
11809
11810
11811 // Set the context local variable value.
11812 static bool SetContextLocalValue(Isolate* isolate,
11813                                  Handle<ScopeInfo> scope_info,
11814                                  Handle<Context> context,
11815                                  Handle<String> variable_name,
11816                                  Handle<Object> new_value) {
11817   for (int i = 0; i < scope_info->ContextLocalCount(); i++) {
11818     Handle<String> next_name(scope_info->ContextLocalName(i));
11819     if (String::Equals(variable_name, next_name)) {
11820       VariableMode mode;
11821       InitializationFlag init_flag;
11822       MaybeAssignedFlag maybe_assigned_flag;
11823       int context_index = ScopeInfo::ContextSlotIndex(
11824           scope_info, next_name, &mode, &init_flag, &maybe_assigned_flag);
11825       context->set(context_index, *new_value);
11826       return true;
11827     }
11828   }
11829
11830   return false;
11831 }
11832
11833
11834 static bool SetLocalVariableValue(Isolate* isolate,
11835                                   JavaScriptFrame* frame,
11836                                   int inlined_jsframe_index,
11837                                   Handle<String> variable_name,
11838                                   Handle<Object> new_value) {
11839   if (inlined_jsframe_index != 0 || frame->is_optimized()) {
11840     // Optimized frames are not supported.
11841     return false;
11842   }
11843
11844   Handle<JSFunction> function(frame->function());
11845   Handle<SharedFunctionInfo> shared(function->shared());
11846   Handle<ScopeInfo> scope_info(shared->scope_info());
11847
11848   bool default_result = false;
11849
11850   // Parameters.
11851   for (int i = 0; i < scope_info->ParameterCount(); ++i) {
11852     HandleScope scope(isolate);
11853     if (String::Equals(handle(scope_info->ParameterName(i)), variable_name)) {
11854       frame->SetParameterValue(i, *new_value);
11855       // Argument might be shadowed in heap context, don't stop here.
11856       default_result = true;
11857     }
11858   }
11859
11860   // Stack locals.
11861   for (int i = 0; i < scope_info->StackLocalCount(); ++i) {
11862     HandleScope scope(isolate);
11863     if (String::Equals(handle(scope_info->StackLocalName(i)), variable_name)) {
11864       frame->SetExpression(i, *new_value);
11865       return true;
11866     }
11867   }
11868
11869   if (scope_info->HasContext()) {
11870     // Context locals.
11871     Handle<Context> frame_context(Context::cast(frame->context()));
11872     Handle<Context> function_context(frame_context->declaration_context());
11873     if (SetContextLocalValue(
11874         isolate, scope_info, function_context, variable_name, new_value)) {
11875       return true;
11876     }
11877
11878     // Function context extension. These are variables introduced by eval.
11879     if (function_context->closure() == *function) {
11880       if (function_context->has_extension() &&
11881           !function_context->IsNativeContext()) {
11882         Handle<JSObject> ext(JSObject::cast(function_context->extension()));
11883
11884         Maybe<bool> maybe = JSReceiver::HasProperty(ext, variable_name);
11885         DCHECK(maybe.has_value);
11886         if (maybe.value) {
11887           // We don't expect this to do anything except replacing
11888           // property value.
11889           Runtime::SetObjectProperty(isolate, ext, variable_name, new_value,
11890                                      SLOPPY).Assert();
11891           return true;
11892         }
11893       }
11894     }
11895   }
11896
11897   return default_result;
11898 }
11899
11900
11901 // Create a plain JSObject which materializes the closure content for the
11902 // context.
11903 MUST_USE_RESULT static MaybeHandle<JSObject> MaterializeClosure(
11904     Isolate* isolate,
11905     Handle<Context> context) {
11906   DCHECK(context->IsFunctionContext());
11907
11908   Handle<SharedFunctionInfo> shared(context->closure()->shared());
11909   Handle<ScopeInfo> scope_info(shared->scope_info());
11910
11911   // Allocate and initialize a JSObject with all the content of this function
11912   // closure.
11913   Handle<JSObject> closure_scope =
11914       isolate->factory()->NewJSObject(isolate->object_function());
11915
11916   // Fill all context locals to the context extension.
11917   if (!ScopeInfo::CopyContextLocalsToScopeObject(
11918           scope_info, context, closure_scope)) {
11919     return MaybeHandle<JSObject>();
11920   }
11921
11922   // Finally copy any properties from the function context extension. This will
11923   // be variables introduced by eval.
11924   if (context->has_extension()) {
11925     Handle<JSObject> ext(JSObject::cast(context->extension()));
11926     Handle<FixedArray> keys;
11927     ASSIGN_RETURN_ON_EXCEPTION(
11928         isolate, keys,
11929         JSReceiver::GetKeys(ext, JSReceiver::INCLUDE_PROTOS), JSObject);
11930
11931     for (int i = 0; i < keys->length(); i++) {
11932       HandleScope scope(isolate);
11933       // Names of variables introduced by eval are strings.
11934       DCHECK(keys->get(i)->IsString());
11935       Handle<String> key(String::cast(keys->get(i)));
11936       Handle<Object> value;
11937       ASSIGN_RETURN_ON_EXCEPTION(
11938           isolate, value, Object::GetPropertyOrElement(ext, key), JSObject);
11939       RETURN_ON_EXCEPTION(
11940           isolate,
11941           Runtime::DefineObjectProperty(closure_scope, key, value, NONE),
11942           JSObject);
11943     }
11944   }
11945
11946   return closure_scope;
11947 }
11948
11949
11950 // This method copies structure of MaterializeClosure method above.
11951 static bool SetClosureVariableValue(Isolate* isolate,
11952                                     Handle<Context> context,
11953                                     Handle<String> variable_name,
11954                                     Handle<Object> new_value) {
11955   DCHECK(context->IsFunctionContext());
11956
11957   Handle<SharedFunctionInfo> shared(context->closure()->shared());
11958   Handle<ScopeInfo> scope_info(shared->scope_info());
11959
11960   // Context locals to the context extension.
11961   if (SetContextLocalValue(
11962           isolate, scope_info, context, variable_name, new_value)) {
11963     return true;
11964   }
11965
11966   // Properties from the function context extension. This will
11967   // be variables introduced by eval.
11968   if (context->has_extension()) {
11969     Handle<JSObject> ext(JSObject::cast(context->extension()));
11970     Maybe<bool> maybe = JSReceiver::HasProperty(ext, variable_name);
11971     DCHECK(maybe.has_value);
11972     if (maybe.value) {
11973       // We don't expect this to do anything except replacing property value.
11974       Runtime::DefineObjectProperty(
11975           ext, variable_name, new_value, NONE).Assert();
11976       return true;
11977     }
11978   }
11979
11980   return false;
11981 }
11982
11983
11984 // Create a plain JSObject which materializes the scope for the specified
11985 // catch context.
11986 MUST_USE_RESULT static MaybeHandle<JSObject> MaterializeCatchScope(
11987     Isolate* isolate,
11988     Handle<Context> context) {
11989   DCHECK(context->IsCatchContext());
11990   Handle<String> name(String::cast(context->extension()));
11991   Handle<Object> thrown_object(context->get(Context::THROWN_OBJECT_INDEX),
11992                                isolate);
11993   Handle<JSObject> catch_scope =
11994       isolate->factory()->NewJSObject(isolate->object_function());
11995   RETURN_ON_EXCEPTION(
11996       isolate,
11997       Runtime::DefineObjectProperty(catch_scope, name, thrown_object, NONE),
11998       JSObject);
11999   return catch_scope;
12000 }
12001
12002
12003 static bool SetCatchVariableValue(Isolate* isolate,
12004                                   Handle<Context> context,
12005                                   Handle<String> variable_name,
12006                                   Handle<Object> new_value) {
12007   DCHECK(context->IsCatchContext());
12008   Handle<String> name(String::cast(context->extension()));
12009   if (!String::Equals(name, variable_name)) {
12010     return false;
12011   }
12012   context->set(Context::THROWN_OBJECT_INDEX, *new_value);
12013   return true;
12014 }
12015
12016
12017 // Create a plain JSObject which materializes the block scope for the specified
12018 // block context.
12019 MUST_USE_RESULT static MaybeHandle<JSObject> MaterializeBlockScope(
12020     Isolate* isolate,
12021     Handle<Context> context) {
12022   DCHECK(context->IsBlockContext());
12023   Handle<ScopeInfo> scope_info(ScopeInfo::cast(context->extension()));
12024
12025   // Allocate and initialize a JSObject with all the arguments, stack locals
12026   // heap locals and extension properties of the debugged function.
12027   Handle<JSObject> block_scope =
12028       isolate->factory()->NewJSObject(isolate->object_function());
12029
12030   // Fill all context locals.
12031   if (!ScopeInfo::CopyContextLocalsToScopeObject(
12032           scope_info, context, block_scope)) {
12033     return MaybeHandle<JSObject>();
12034   }
12035
12036   return block_scope;
12037 }
12038
12039
12040 // Create a plain JSObject which materializes the module scope for the specified
12041 // module context.
12042 MUST_USE_RESULT static MaybeHandle<JSObject> MaterializeModuleScope(
12043     Isolate* isolate,
12044     Handle<Context> context) {
12045   DCHECK(context->IsModuleContext());
12046   Handle<ScopeInfo> scope_info(ScopeInfo::cast(context->extension()));
12047
12048   // Allocate and initialize a JSObject with all the members of the debugged
12049   // module.
12050   Handle<JSObject> module_scope =
12051       isolate->factory()->NewJSObject(isolate->object_function());
12052
12053   // Fill all context locals.
12054   if (!ScopeInfo::CopyContextLocalsToScopeObject(
12055           scope_info, context, module_scope)) {
12056     return MaybeHandle<JSObject>();
12057   }
12058
12059   return module_scope;
12060 }
12061
12062
12063 // Iterate over the actual scopes visible from a stack frame or from a closure.
12064 // The iteration proceeds from the innermost visible nested scope outwards.
12065 // All scopes are backed by an actual context except the local scope,
12066 // which is inserted "artificially" in the context chain.
12067 class ScopeIterator {
12068  public:
12069   enum ScopeType {
12070     ScopeTypeGlobal = 0,
12071     ScopeTypeLocal,
12072     ScopeTypeWith,
12073     ScopeTypeClosure,
12074     ScopeTypeCatch,
12075     ScopeTypeBlock,
12076     ScopeTypeModule
12077   };
12078
12079   ScopeIterator(Isolate* isolate,
12080                 JavaScriptFrame* frame,
12081                 int inlined_jsframe_index,
12082                 bool ignore_nested_scopes = false)
12083     : isolate_(isolate),
12084       frame_(frame),
12085       inlined_jsframe_index_(inlined_jsframe_index),
12086       function_(frame->function()),
12087       context_(Context::cast(frame->context())),
12088       nested_scope_chain_(4),
12089       failed_(false) {
12090
12091     // Catch the case when the debugger stops in an internal function.
12092     Handle<SharedFunctionInfo> shared_info(function_->shared());
12093     Handle<ScopeInfo> scope_info(shared_info->scope_info());
12094     if (shared_info->script() == isolate->heap()->undefined_value()) {
12095       while (context_->closure() == *function_) {
12096         context_ = Handle<Context>(context_->previous(), isolate_);
12097       }
12098       return;
12099     }
12100
12101     // Get the debug info (create it if it does not exist).
12102     if (!isolate->debug()->EnsureDebugInfo(shared_info, function_)) {
12103       // Return if ensuring debug info failed.
12104       return;
12105     }
12106
12107     // Currently it takes too much time to find nested scopes due to script
12108     // parsing. Sometimes we want to run the ScopeIterator as fast as possible
12109     // (for example, while collecting async call stacks on every
12110     // addEventListener call), even if we drop some nested scopes.
12111     // Later we may optimize getting the nested scopes (cache the result?)
12112     // and include nested scopes into the "fast" iteration case as well.
12113     if (!ignore_nested_scopes) {
12114       Handle<DebugInfo> debug_info = Debug::GetDebugInfo(shared_info);
12115
12116       // Find the break point where execution has stopped.
12117       BreakLocationIterator break_location_iterator(debug_info,
12118                                                     ALL_BREAK_LOCATIONS);
12119       // pc points to the instruction after the current one, possibly a break
12120       // location as well. So the "- 1" to exclude it from the search.
12121       break_location_iterator.FindBreakLocationFromAddress(frame->pc() - 1);
12122
12123       // Within the return sequence at the moment it is not possible to
12124       // get a source position which is consistent with the current scope chain.
12125       // Thus all nested with, catch and block contexts are skipped and we only
12126       // provide the function scope.
12127       ignore_nested_scopes = break_location_iterator.IsExit();
12128     }
12129
12130     if (ignore_nested_scopes) {
12131       if (scope_info->HasContext()) {
12132         context_ = Handle<Context>(context_->declaration_context(), isolate_);
12133       } else {
12134         while (context_->closure() == *function_) {
12135           context_ = Handle<Context>(context_->previous(), isolate_);
12136         }
12137       }
12138       if (scope_info->scope_type() == FUNCTION_SCOPE) {
12139         nested_scope_chain_.Add(scope_info);
12140       }
12141     } else {
12142       // Reparse the code and analyze the scopes.
12143       Handle<Script> script(Script::cast(shared_info->script()));
12144       Scope* scope = NULL;
12145
12146       // Check whether we are in global, eval or function code.
12147       Handle<ScopeInfo> scope_info(shared_info->scope_info());
12148       if (scope_info->scope_type() != FUNCTION_SCOPE) {
12149         // Global or eval code.
12150         CompilationInfoWithZone info(script);
12151         if (scope_info->scope_type() == GLOBAL_SCOPE) {
12152           info.MarkAsGlobal();
12153         } else {
12154           DCHECK(scope_info->scope_type() == EVAL_SCOPE);
12155           info.MarkAsEval();
12156           info.SetContext(Handle<Context>(function_->context()));
12157         }
12158         if (Parser::Parse(&info) && Scope::Analyze(&info)) {
12159           scope = info.function()->scope();
12160         }
12161         RetrieveScopeChain(scope, shared_info);
12162       } else {
12163         // Function code
12164         CompilationInfoWithZone info(shared_info);
12165         if (Parser::Parse(&info) && Scope::Analyze(&info)) {
12166           scope = info.function()->scope();
12167         }
12168         RetrieveScopeChain(scope, shared_info);
12169       }
12170     }
12171   }
12172
12173   ScopeIterator(Isolate* isolate,
12174                 Handle<JSFunction> function)
12175     : isolate_(isolate),
12176       frame_(NULL),
12177       inlined_jsframe_index_(0),
12178       function_(function),
12179       context_(function->context()),
12180       failed_(false) {
12181     if (function->IsBuiltin()) {
12182       context_ = Handle<Context>();
12183     }
12184   }
12185
12186   // More scopes?
12187   bool Done() {
12188     DCHECK(!failed_);
12189     return context_.is_null();
12190   }
12191
12192   bool Failed() { return failed_; }
12193
12194   // Move to the next scope.
12195   void Next() {
12196     DCHECK(!failed_);
12197     ScopeType scope_type = Type();
12198     if (scope_type == ScopeTypeGlobal) {
12199       // The global scope is always the last in the chain.
12200       DCHECK(context_->IsNativeContext());
12201       context_ = Handle<Context>();
12202       return;
12203     }
12204     if (nested_scope_chain_.is_empty()) {
12205       context_ = Handle<Context>(context_->previous(), isolate_);
12206     } else {
12207       if (nested_scope_chain_.last()->HasContext()) {
12208         DCHECK(context_->previous() != NULL);
12209         context_ = Handle<Context>(context_->previous(), isolate_);
12210       }
12211       nested_scope_chain_.RemoveLast();
12212     }
12213   }
12214
12215   // Return the type of the current scope.
12216   ScopeType Type() {
12217     DCHECK(!failed_);
12218     if (!nested_scope_chain_.is_empty()) {
12219       Handle<ScopeInfo> scope_info = nested_scope_chain_.last();
12220       switch (scope_info->scope_type()) {
12221         case FUNCTION_SCOPE:
12222           DCHECK(context_->IsFunctionContext() ||
12223                  !scope_info->HasContext());
12224           return ScopeTypeLocal;
12225         case MODULE_SCOPE:
12226           DCHECK(context_->IsModuleContext());
12227           return ScopeTypeModule;
12228         case GLOBAL_SCOPE:
12229           DCHECK(context_->IsNativeContext());
12230           return ScopeTypeGlobal;
12231         case WITH_SCOPE:
12232           DCHECK(context_->IsWithContext());
12233           return ScopeTypeWith;
12234         case CATCH_SCOPE:
12235           DCHECK(context_->IsCatchContext());
12236           return ScopeTypeCatch;
12237         case BLOCK_SCOPE:
12238           DCHECK(!scope_info->HasContext() ||
12239                  context_->IsBlockContext());
12240           return ScopeTypeBlock;
12241         case EVAL_SCOPE:
12242           UNREACHABLE();
12243       }
12244     }
12245     if (context_->IsNativeContext()) {
12246       DCHECK(context_->global_object()->IsGlobalObject());
12247       return ScopeTypeGlobal;
12248     }
12249     if (context_->IsFunctionContext()) {
12250       return ScopeTypeClosure;
12251     }
12252     if (context_->IsCatchContext()) {
12253       return ScopeTypeCatch;
12254     }
12255     if (context_->IsBlockContext()) {
12256       return ScopeTypeBlock;
12257     }
12258     if (context_->IsModuleContext()) {
12259       return ScopeTypeModule;
12260     }
12261     DCHECK(context_->IsWithContext());
12262     return ScopeTypeWith;
12263   }
12264
12265   // Return the JavaScript object with the content of the current scope.
12266   MaybeHandle<JSObject> ScopeObject() {
12267     DCHECK(!failed_);
12268     switch (Type()) {
12269       case ScopeIterator::ScopeTypeGlobal:
12270         return Handle<JSObject>(CurrentContext()->global_object());
12271       case ScopeIterator::ScopeTypeLocal:
12272         // Materialize the content of the local scope into a JSObject.
12273         DCHECK(nested_scope_chain_.length() == 1);
12274         return MaterializeLocalScope(isolate_, frame_, inlined_jsframe_index_);
12275       case ScopeIterator::ScopeTypeWith:
12276         // Return the with object.
12277         return Handle<JSObject>(JSObject::cast(CurrentContext()->extension()));
12278       case ScopeIterator::ScopeTypeCatch:
12279         return MaterializeCatchScope(isolate_, CurrentContext());
12280       case ScopeIterator::ScopeTypeClosure:
12281         // Materialize the content of the closure scope into a JSObject.
12282         return MaterializeClosure(isolate_, CurrentContext());
12283       case ScopeIterator::ScopeTypeBlock:
12284         return MaterializeBlockScope(isolate_, CurrentContext());
12285       case ScopeIterator::ScopeTypeModule:
12286         return MaterializeModuleScope(isolate_, CurrentContext());
12287     }
12288     UNREACHABLE();
12289     return Handle<JSObject>();
12290   }
12291
12292   bool SetVariableValue(Handle<String> variable_name,
12293                         Handle<Object> new_value) {
12294     DCHECK(!failed_);
12295     switch (Type()) {
12296       case ScopeIterator::ScopeTypeGlobal:
12297         break;
12298       case ScopeIterator::ScopeTypeLocal:
12299         return SetLocalVariableValue(isolate_, frame_, inlined_jsframe_index_,
12300             variable_name, new_value);
12301       case ScopeIterator::ScopeTypeWith:
12302         break;
12303       case ScopeIterator::ScopeTypeCatch:
12304         return SetCatchVariableValue(isolate_, CurrentContext(),
12305             variable_name, new_value);
12306       case ScopeIterator::ScopeTypeClosure:
12307         return SetClosureVariableValue(isolate_, CurrentContext(),
12308             variable_name, new_value);
12309       case ScopeIterator::ScopeTypeBlock:
12310         // TODO(2399): should we implement it?
12311         break;
12312       case ScopeIterator::ScopeTypeModule:
12313         // TODO(2399): should we implement it?
12314         break;
12315     }
12316     return false;
12317   }
12318
12319   Handle<ScopeInfo> CurrentScopeInfo() {
12320     DCHECK(!failed_);
12321     if (!nested_scope_chain_.is_empty()) {
12322       return nested_scope_chain_.last();
12323     } else if (context_->IsBlockContext()) {
12324       return Handle<ScopeInfo>(ScopeInfo::cast(context_->extension()));
12325     } else if (context_->IsFunctionContext()) {
12326       return Handle<ScopeInfo>(context_->closure()->shared()->scope_info());
12327     }
12328     return Handle<ScopeInfo>::null();
12329   }
12330
12331   // Return the context for this scope. For the local context there might not
12332   // be an actual context.
12333   Handle<Context> CurrentContext() {
12334     DCHECK(!failed_);
12335     if (Type() == ScopeTypeGlobal ||
12336         nested_scope_chain_.is_empty()) {
12337       return context_;
12338     } else if (nested_scope_chain_.last()->HasContext()) {
12339       return context_;
12340     } else {
12341       return Handle<Context>();
12342     }
12343   }
12344
12345 #ifdef DEBUG
12346   // Debug print of the content of the current scope.
12347   void DebugPrint() {
12348     OFStream os(stdout);
12349     DCHECK(!failed_);
12350     switch (Type()) {
12351       case ScopeIterator::ScopeTypeGlobal:
12352         os << "Global:\n";
12353         CurrentContext()->Print(os);
12354         break;
12355
12356       case ScopeIterator::ScopeTypeLocal: {
12357         os << "Local:\n";
12358         function_->shared()->scope_info()->Print();
12359         if (!CurrentContext().is_null()) {
12360           CurrentContext()->Print(os);
12361           if (CurrentContext()->has_extension()) {
12362             Handle<Object> extension(CurrentContext()->extension(), isolate_);
12363             if (extension->IsJSContextExtensionObject()) {
12364               extension->Print(os);
12365             }
12366           }
12367         }
12368         break;
12369       }
12370
12371       case ScopeIterator::ScopeTypeWith:
12372         os << "With:\n";
12373         CurrentContext()->extension()->Print(os);
12374         break;
12375
12376       case ScopeIterator::ScopeTypeCatch:
12377         os << "Catch:\n";
12378         CurrentContext()->extension()->Print(os);
12379         CurrentContext()->get(Context::THROWN_OBJECT_INDEX)->Print(os);
12380         break;
12381
12382       case ScopeIterator::ScopeTypeClosure:
12383         os << "Closure:\n";
12384         CurrentContext()->Print(os);
12385         if (CurrentContext()->has_extension()) {
12386           Handle<Object> extension(CurrentContext()->extension(), isolate_);
12387           if (extension->IsJSContextExtensionObject()) {
12388             extension->Print(os);
12389           }
12390         }
12391         break;
12392
12393       default:
12394         UNREACHABLE();
12395     }
12396     PrintF("\n");
12397   }
12398 #endif
12399
12400  private:
12401   Isolate* isolate_;
12402   JavaScriptFrame* frame_;
12403   int inlined_jsframe_index_;
12404   Handle<JSFunction> function_;
12405   Handle<Context> context_;
12406   List<Handle<ScopeInfo> > nested_scope_chain_;
12407   bool failed_;
12408
12409   void RetrieveScopeChain(Scope* scope,
12410                           Handle<SharedFunctionInfo> shared_info) {
12411     if (scope != NULL) {
12412       int source_position = shared_info->code()->SourcePosition(frame_->pc());
12413       scope->GetNestedScopeChain(&nested_scope_chain_, source_position);
12414     } else {
12415       // A failed reparse indicates that the preparser has diverged from the
12416       // parser or that the preparse data given to the initial parse has been
12417       // faulty. We fail in debug mode but in release mode we only provide the
12418       // information we get from the context chain but nothing about
12419       // completely stack allocated scopes or stack allocated locals.
12420       // Or it could be due to stack overflow.
12421       DCHECK(isolate_->has_pending_exception());
12422       failed_ = true;
12423     }
12424   }
12425
12426   DISALLOW_IMPLICIT_CONSTRUCTORS(ScopeIterator);
12427 };
12428
12429
12430 RUNTIME_FUNCTION(Runtime_GetScopeCount) {
12431   HandleScope scope(isolate);
12432   DCHECK(args.length() == 2);
12433   CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
12434   RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
12435
12436   CONVERT_SMI_ARG_CHECKED(wrapped_id, 1);
12437
12438   // Get the frame where the debugging is performed.
12439   StackFrame::Id id = UnwrapFrameId(wrapped_id);
12440   JavaScriptFrameIterator it(isolate, id);
12441   JavaScriptFrame* frame = it.frame();
12442
12443   // Count the visible scopes.
12444   int n = 0;
12445   for (ScopeIterator it(isolate, frame, 0);
12446        !it.Done();
12447        it.Next()) {
12448     n++;
12449   }
12450
12451   return Smi::FromInt(n);
12452 }
12453
12454
12455 // Returns the list of step-in positions (text offset) in a function of the
12456 // stack frame in a range from the current debug break position to the end
12457 // of the corresponding statement.
12458 RUNTIME_FUNCTION(Runtime_GetStepInPositions) {
12459   HandleScope scope(isolate);
12460   DCHECK(args.length() == 2);
12461   CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
12462   RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
12463
12464   CONVERT_SMI_ARG_CHECKED(wrapped_id, 1);
12465
12466   // Get the frame where the debugging is performed.
12467   StackFrame::Id id = UnwrapFrameId(wrapped_id);
12468   JavaScriptFrameIterator frame_it(isolate, id);
12469   RUNTIME_ASSERT(!frame_it.done());
12470
12471   JavaScriptFrame* frame = frame_it.frame();
12472
12473   Handle<JSFunction> fun =
12474       Handle<JSFunction>(frame->function());
12475   Handle<SharedFunctionInfo> shared =
12476       Handle<SharedFunctionInfo>(fun->shared());
12477
12478   if (!isolate->debug()->EnsureDebugInfo(shared, fun)) {
12479     return isolate->heap()->undefined_value();
12480   }
12481
12482   Handle<DebugInfo> debug_info = Debug::GetDebugInfo(shared);
12483
12484   int len = 0;
12485   Handle<JSArray> array(isolate->factory()->NewJSArray(10));
12486   // Find the break point where execution has stopped.
12487   BreakLocationIterator break_location_iterator(debug_info,
12488                                                 ALL_BREAK_LOCATIONS);
12489
12490   break_location_iterator.FindBreakLocationFromAddress(frame->pc() - 1);
12491   int current_statement_pos = break_location_iterator.statement_position();
12492
12493   while (!break_location_iterator.Done()) {
12494     bool accept;
12495     if (break_location_iterator.pc() > frame->pc()) {
12496       accept = true;
12497     } else {
12498       StackFrame::Id break_frame_id = isolate->debug()->break_frame_id();
12499       // The break point is near our pc. Could be a step-in possibility,
12500       // that is currently taken by active debugger call.
12501       if (break_frame_id == StackFrame::NO_ID) {
12502         // We are not stepping.
12503         accept = false;
12504       } else {
12505         JavaScriptFrameIterator additional_frame_it(isolate, break_frame_id);
12506         // If our frame is a top frame and we are stepping, we can do step-in
12507         // at this place.
12508         accept = additional_frame_it.frame()->id() == id;
12509       }
12510     }
12511     if (accept) {
12512       if (break_location_iterator.IsStepInLocation(isolate)) {
12513         Smi* position_value = Smi::FromInt(break_location_iterator.position());
12514         RETURN_FAILURE_ON_EXCEPTION(
12515             isolate,
12516             JSObject::SetElement(array, len,
12517                                  Handle<Object>(position_value, isolate),
12518                                  NONE, SLOPPY));
12519         len++;
12520       }
12521     }
12522     // Advance iterator.
12523     break_location_iterator.Next();
12524     if (current_statement_pos !=
12525         break_location_iterator.statement_position()) {
12526       break;
12527     }
12528   }
12529   return *array;
12530 }
12531
12532
12533 static const int kScopeDetailsTypeIndex = 0;
12534 static const int kScopeDetailsObjectIndex = 1;
12535 static const int kScopeDetailsSize = 2;
12536
12537
12538 MUST_USE_RESULT static MaybeHandle<JSObject> MaterializeScopeDetails(
12539     Isolate* isolate,
12540     ScopeIterator* it) {
12541   // Calculate the size of the result.
12542   int details_size = kScopeDetailsSize;
12543   Handle<FixedArray> details = isolate->factory()->NewFixedArray(details_size);
12544
12545   // Fill in scope details.
12546   details->set(kScopeDetailsTypeIndex, Smi::FromInt(it->Type()));
12547   Handle<JSObject> scope_object;
12548   ASSIGN_RETURN_ON_EXCEPTION(
12549       isolate, scope_object, it->ScopeObject(), JSObject);
12550   details->set(kScopeDetailsObjectIndex, *scope_object);
12551
12552   return isolate->factory()->NewJSArrayWithElements(details);
12553 }
12554
12555
12556 // Return an array with scope details
12557 // args[0]: number: break id
12558 // args[1]: number: frame index
12559 // args[2]: number: inlined frame index
12560 // args[3]: number: scope index
12561 //
12562 // The array returned contains the following information:
12563 // 0: Scope type
12564 // 1: Scope object
12565 RUNTIME_FUNCTION(Runtime_GetScopeDetails) {
12566   HandleScope scope(isolate);
12567   DCHECK(args.length() == 4);
12568   CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
12569   RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
12570
12571   CONVERT_SMI_ARG_CHECKED(wrapped_id, 1);
12572   CONVERT_NUMBER_CHECKED(int, inlined_jsframe_index, Int32, args[2]);
12573   CONVERT_NUMBER_CHECKED(int, index, Int32, args[3]);
12574
12575   // Get the frame where the debugging is performed.
12576   StackFrame::Id id = UnwrapFrameId(wrapped_id);
12577   JavaScriptFrameIterator frame_it(isolate, id);
12578   JavaScriptFrame* frame = frame_it.frame();
12579
12580   // Find the requested scope.
12581   int n = 0;
12582   ScopeIterator it(isolate, frame, inlined_jsframe_index);
12583   for (; !it.Done() && n < index; it.Next()) {
12584     n++;
12585   }
12586   if (it.Done()) {
12587     return isolate->heap()->undefined_value();
12588   }
12589   Handle<JSObject> details;
12590   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
12591       isolate, details, MaterializeScopeDetails(isolate, &it));
12592   return *details;
12593 }
12594
12595
12596 // Return an array of scope details
12597 // args[0]: number: break id
12598 // args[1]: number: frame index
12599 // args[2]: number: inlined frame index
12600 // args[3]: boolean: ignore nested scopes
12601 //
12602 // The array returned contains arrays with the following information:
12603 // 0: Scope type
12604 // 1: Scope object
12605 RUNTIME_FUNCTION(Runtime_GetAllScopesDetails) {
12606   HandleScope scope(isolate);
12607   DCHECK(args.length() == 3 || args.length() == 4);
12608   CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
12609   RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
12610
12611   CONVERT_SMI_ARG_CHECKED(wrapped_id, 1);
12612   CONVERT_NUMBER_CHECKED(int, inlined_jsframe_index, Int32, args[2]);
12613
12614   bool ignore_nested_scopes = false;
12615   if (args.length() == 4) {
12616     CONVERT_BOOLEAN_ARG_CHECKED(flag, 3);
12617     ignore_nested_scopes = flag;
12618   }
12619
12620   // Get the frame where the debugging is performed.
12621   StackFrame::Id id = UnwrapFrameId(wrapped_id);
12622   JavaScriptFrameIterator frame_it(isolate, id);
12623   JavaScriptFrame* frame = frame_it.frame();
12624
12625   List<Handle<JSObject> > result(4);
12626   ScopeIterator it(isolate, frame, inlined_jsframe_index, ignore_nested_scopes);
12627   for (; !it.Done(); it.Next()) {
12628     Handle<JSObject> details;
12629     ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
12630         isolate, details, MaterializeScopeDetails(isolate, &it));
12631     result.Add(details);
12632   }
12633
12634   Handle<FixedArray> array = isolate->factory()->NewFixedArray(result.length());
12635   for (int i = 0; i < result.length(); ++i) {
12636     array->set(i, *result[i]);
12637   }
12638   return *isolate->factory()->NewJSArrayWithElements(array);
12639 }
12640
12641
12642 RUNTIME_FUNCTION(Runtime_GetFunctionScopeCount) {
12643   HandleScope scope(isolate);
12644   DCHECK(args.length() == 1);
12645
12646   // Check arguments.
12647   CONVERT_ARG_HANDLE_CHECKED(JSFunction, fun, 0);
12648
12649   // Count the visible scopes.
12650   int n = 0;
12651   for (ScopeIterator it(isolate, fun); !it.Done(); it.Next()) {
12652     n++;
12653   }
12654
12655   return Smi::FromInt(n);
12656 }
12657
12658
12659 RUNTIME_FUNCTION(Runtime_GetFunctionScopeDetails) {
12660   HandleScope scope(isolate);
12661   DCHECK(args.length() == 2);
12662
12663   // Check arguments.
12664   CONVERT_ARG_HANDLE_CHECKED(JSFunction, fun, 0);
12665   CONVERT_NUMBER_CHECKED(int, index, Int32, args[1]);
12666
12667   // Find the requested scope.
12668   int n = 0;
12669   ScopeIterator it(isolate, fun);
12670   for (; !it.Done() && n < index; it.Next()) {
12671     n++;
12672   }
12673   if (it.Done()) {
12674     return isolate->heap()->undefined_value();
12675   }
12676
12677   Handle<JSObject> details;
12678   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
12679       isolate, details, MaterializeScopeDetails(isolate, &it));
12680   return *details;
12681 }
12682
12683
12684 static bool SetScopeVariableValue(ScopeIterator* it, int index,
12685                                   Handle<String> variable_name,
12686                                   Handle<Object> new_value) {
12687   for (int n = 0; !it->Done() && n < index; it->Next()) {
12688     n++;
12689   }
12690   if (it->Done()) {
12691     return false;
12692   }
12693   return it->SetVariableValue(variable_name, new_value);
12694 }
12695
12696
12697 // Change variable value in closure or local scope
12698 // args[0]: number or JsFunction: break id or function
12699 // args[1]: number: frame index (when arg[0] is break id)
12700 // args[2]: number: inlined frame index (when arg[0] is break id)
12701 // args[3]: number: scope index
12702 // args[4]: string: variable name
12703 // args[5]: object: new value
12704 //
12705 // Return true if success and false otherwise
12706 RUNTIME_FUNCTION(Runtime_SetScopeVariableValue) {
12707   HandleScope scope(isolate);
12708   DCHECK(args.length() == 6);
12709
12710   // Check arguments.
12711   CONVERT_NUMBER_CHECKED(int, index, Int32, args[3]);
12712   CONVERT_ARG_HANDLE_CHECKED(String, variable_name, 4);
12713   CONVERT_ARG_HANDLE_CHECKED(Object, new_value, 5);
12714
12715   bool res;
12716   if (args[0]->IsNumber()) {
12717     CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
12718     RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
12719
12720     CONVERT_SMI_ARG_CHECKED(wrapped_id, 1);
12721     CONVERT_NUMBER_CHECKED(int, inlined_jsframe_index, Int32, args[2]);
12722
12723     // Get the frame where the debugging is performed.
12724     StackFrame::Id id = UnwrapFrameId(wrapped_id);
12725     JavaScriptFrameIterator frame_it(isolate, id);
12726     JavaScriptFrame* frame = frame_it.frame();
12727
12728     ScopeIterator it(isolate, frame, inlined_jsframe_index);
12729     res = SetScopeVariableValue(&it, index, variable_name, new_value);
12730   } else {
12731     CONVERT_ARG_HANDLE_CHECKED(JSFunction, fun, 0);
12732     ScopeIterator it(isolate, fun);
12733     res = SetScopeVariableValue(&it, index, variable_name, new_value);
12734   }
12735
12736   return isolate->heap()->ToBoolean(res);
12737 }
12738
12739
12740 RUNTIME_FUNCTION(Runtime_DebugPrintScopes) {
12741   HandleScope scope(isolate);
12742   DCHECK(args.length() == 0);
12743
12744 #ifdef DEBUG
12745   // Print the scopes for the top frame.
12746   StackFrameLocator locator(isolate);
12747   JavaScriptFrame* frame = locator.FindJavaScriptFrame(0);
12748   for (ScopeIterator it(isolate, frame, 0);
12749        !it.Done();
12750        it.Next()) {
12751     it.DebugPrint();
12752   }
12753 #endif
12754   return isolate->heap()->undefined_value();
12755 }
12756
12757
12758 RUNTIME_FUNCTION(Runtime_GetThreadCount) {
12759   HandleScope scope(isolate);
12760   DCHECK(args.length() == 1);
12761   CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
12762   RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
12763
12764   // Count all archived V8 threads.
12765   int n = 0;
12766   for (ThreadState* thread =
12767           isolate->thread_manager()->FirstThreadStateInUse();
12768        thread != NULL;
12769        thread = thread->Next()) {
12770     n++;
12771   }
12772
12773   // Total number of threads is current thread and archived threads.
12774   return Smi::FromInt(n + 1);
12775 }
12776
12777
12778 static const int kThreadDetailsCurrentThreadIndex = 0;
12779 static const int kThreadDetailsThreadIdIndex = 1;
12780 static const int kThreadDetailsSize = 2;
12781
12782 // Return an array with thread details
12783 // args[0]: number: break id
12784 // args[1]: number: thread index
12785 //
12786 // The array returned contains the following information:
12787 // 0: Is current thread?
12788 // 1: Thread id
12789 RUNTIME_FUNCTION(Runtime_GetThreadDetails) {
12790   HandleScope scope(isolate);
12791   DCHECK(args.length() == 2);
12792   CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
12793   RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
12794
12795   CONVERT_NUMBER_CHECKED(int, index, Int32, args[1]);
12796
12797   // Allocate array for result.
12798   Handle<FixedArray> details =
12799       isolate->factory()->NewFixedArray(kThreadDetailsSize);
12800
12801   // Thread index 0 is current thread.
12802   if (index == 0) {
12803     // Fill the details.
12804     details->set(kThreadDetailsCurrentThreadIndex,
12805                  isolate->heap()->true_value());
12806     details->set(kThreadDetailsThreadIdIndex,
12807                  Smi::FromInt(ThreadId::Current().ToInteger()));
12808   } else {
12809     // Find the thread with the requested index.
12810     int n = 1;
12811     ThreadState* thread =
12812         isolate->thread_manager()->FirstThreadStateInUse();
12813     while (index != n && thread != NULL) {
12814       thread = thread->Next();
12815       n++;
12816     }
12817     if (thread == NULL) {
12818       return isolate->heap()->undefined_value();
12819     }
12820
12821     // Fill the details.
12822     details->set(kThreadDetailsCurrentThreadIndex,
12823                  isolate->heap()->false_value());
12824     details->set(kThreadDetailsThreadIdIndex,
12825                  Smi::FromInt(thread->id().ToInteger()));
12826   }
12827
12828   // Convert to JS array and return.
12829   return *isolate->factory()->NewJSArrayWithElements(details);
12830 }
12831
12832
12833 // Sets the disable break state
12834 // args[0]: disable break state
12835 RUNTIME_FUNCTION(Runtime_SetDisableBreak) {
12836   HandleScope scope(isolate);
12837   DCHECK(args.length() == 1);
12838   CONVERT_BOOLEAN_ARG_CHECKED(disable_break, 0);
12839   isolate->debug()->set_disable_break(disable_break);
12840   return  isolate->heap()->undefined_value();
12841 }
12842
12843
12844 static bool IsPositionAlignmentCodeCorrect(int alignment) {
12845   return alignment == STATEMENT_ALIGNED || alignment == BREAK_POSITION_ALIGNED;
12846 }
12847
12848
12849 RUNTIME_FUNCTION(Runtime_GetBreakLocations) {
12850   HandleScope scope(isolate);
12851   DCHECK(args.length() == 2);
12852
12853   CONVERT_ARG_HANDLE_CHECKED(JSFunction, fun, 0);
12854   CONVERT_NUMBER_CHECKED(int32_t, statement_aligned_code, Int32, args[1]);
12855
12856   if (!IsPositionAlignmentCodeCorrect(statement_aligned_code)) {
12857     return isolate->ThrowIllegalOperation();
12858   }
12859   BreakPositionAlignment alignment =
12860       static_cast<BreakPositionAlignment>(statement_aligned_code);
12861
12862   Handle<SharedFunctionInfo> shared(fun->shared());
12863   // Find the number of break points
12864   Handle<Object> break_locations =
12865       Debug::GetSourceBreakLocations(shared, alignment);
12866   if (break_locations->IsUndefined()) return isolate->heap()->undefined_value();
12867   // Return array as JS array
12868   return *isolate->factory()->NewJSArrayWithElements(
12869       Handle<FixedArray>::cast(break_locations));
12870 }
12871
12872
12873 // Set a break point in a function.
12874 // args[0]: function
12875 // args[1]: number: break source position (within the function source)
12876 // args[2]: number: break point object
12877 RUNTIME_FUNCTION(Runtime_SetFunctionBreakPoint) {
12878   HandleScope scope(isolate);
12879   DCHECK(args.length() == 3);
12880   CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
12881   CONVERT_NUMBER_CHECKED(int32_t, source_position, Int32, args[1]);
12882   RUNTIME_ASSERT(source_position >= function->shared()->start_position() &&
12883                  source_position <= function->shared()->end_position());
12884   CONVERT_ARG_HANDLE_CHECKED(Object, break_point_object_arg, 2);
12885
12886   // Set break point.
12887   RUNTIME_ASSERT(isolate->debug()->SetBreakPoint(
12888       function, break_point_object_arg, &source_position));
12889
12890   return Smi::FromInt(source_position);
12891 }
12892
12893
12894 // Changes the state of a break point in a script and returns source position
12895 // where break point was set. NOTE: Regarding performance see the NOTE for
12896 // GetScriptFromScriptData.
12897 // args[0]: script to set break point in
12898 // args[1]: number: break source position (within the script source)
12899 // args[2]: number, breakpoint position alignment
12900 // args[3]: number: break point object
12901 RUNTIME_FUNCTION(Runtime_SetScriptBreakPoint) {
12902   HandleScope scope(isolate);
12903   DCHECK(args.length() == 4);
12904   CONVERT_ARG_HANDLE_CHECKED(JSValue, wrapper, 0);
12905   CONVERT_NUMBER_CHECKED(int32_t, source_position, Int32, args[1]);
12906   RUNTIME_ASSERT(source_position >= 0);
12907   CONVERT_NUMBER_CHECKED(int32_t, statement_aligned_code, Int32, args[2]);
12908   CONVERT_ARG_HANDLE_CHECKED(Object, break_point_object_arg, 3);
12909
12910   if (!IsPositionAlignmentCodeCorrect(statement_aligned_code)) {
12911     return isolate->ThrowIllegalOperation();
12912   }
12913   BreakPositionAlignment alignment =
12914       static_cast<BreakPositionAlignment>(statement_aligned_code);
12915
12916   // Get the script from the script wrapper.
12917   RUNTIME_ASSERT(wrapper->value()->IsScript());
12918   Handle<Script> script(Script::cast(wrapper->value()));
12919
12920   // Set break point.
12921   if (!isolate->debug()->SetBreakPointForScript(script, break_point_object_arg,
12922                                                 &source_position,
12923                                                 alignment)) {
12924     return isolate->heap()->undefined_value();
12925   }
12926
12927   return Smi::FromInt(source_position);
12928 }
12929
12930
12931 // Clear a break point
12932 // args[0]: number: break point object
12933 RUNTIME_FUNCTION(Runtime_ClearBreakPoint) {
12934   HandleScope scope(isolate);
12935   DCHECK(args.length() == 1);
12936   CONVERT_ARG_HANDLE_CHECKED(Object, break_point_object_arg, 0);
12937
12938   // Clear break point.
12939   isolate->debug()->ClearBreakPoint(break_point_object_arg);
12940
12941   return isolate->heap()->undefined_value();
12942 }
12943
12944
12945 // Change the state of break on exceptions.
12946 // args[0]: Enum value indicating whether to affect caught/uncaught exceptions.
12947 // args[1]: Boolean indicating on/off.
12948 RUNTIME_FUNCTION(Runtime_ChangeBreakOnException) {
12949   HandleScope scope(isolate);
12950   DCHECK(args.length() == 2);
12951   CONVERT_NUMBER_CHECKED(uint32_t, type_arg, Uint32, args[0]);
12952   CONVERT_BOOLEAN_ARG_CHECKED(enable, 1);
12953
12954   // If the number doesn't match an enum value, the ChangeBreakOnException
12955   // function will default to affecting caught exceptions.
12956   ExceptionBreakType type = static_cast<ExceptionBreakType>(type_arg);
12957   // Update break point state.
12958   isolate->debug()->ChangeBreakOnException(type, enable);
12959   return isolate->heap()->undefined_value();
12960 }
12961
12962
12963 // Returns the state of break on exceptions
12964 // args[0]: boolean indicating uncaught exceptions
12965 RUNTIME_FUNCTION(Runtime_IsBreakOnException) {
12966   HandleScope scope(isolate);
12967   DCHECK(args.length() == 1);
12968   CONVERT_NUMBER_CHECKED(uint32_t, type_arg, Uint32, args[0]);
12969
12970   ExceptionBreakType type = static_cast<ExceptionBreakType>(type_arg);
12971   bool result = isolate->debug()->IsBreakOnException(type);
12972   return Smi::FromInt(result);
12973 }
12974
12975
12976 // Prepare for stepping
12977 // args[0]: break id for checking execution state
12978 // args[1]: step action from the enumeration StepAction
12979 // args[2]: number of times to perform the step, for step out it is the number
12980 //          of frames to step down.
12981 RUNTIME_FUNCTION(Runtime_PrepareStep) {
12982   HandleScope scope(isolate);
12983   DCHECK(args.length() == 4);
12984   CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
12985   RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
12986
12987   if (!args[1]->IsNumber() || !args[2]->IsNumber()) {
12988     return isolate->Throw(isolate->heap()->illegal_argument_string());
12989   }
12990
12991   CONVERT_NUMBER_CHECKED(int, wrapped_frame_id, Int32, args[3]);
12992
12993   StackFrame::Id frame_id;
12994   if (wrapped_frame_id == 0) {
12995     frame_id = StackFrame::NO_ID;
12996   } else {
12997     frame_id = UnwrapFrameId(wrapped_frame_id);
12998   }
12999
13000   // Get the step action and check validity.
13001   StepAction step_action = static_cast<StepAction>(NumberToInt32(args[1]));
13002   if (step_action != StepIn &&
13003       step_action != StepNext &&
13004       step_action != StepOut &&
13005       step_action != StepInMin &&
13006       step_action != StepMin) {
13007     return isolate->Throw(isolate->heap()->illegal_argument_string());
13008   }
13009
13010   if (frame_id != StackFrame::NO_ID && step_action != StepNext &&
13011       step_action != StepMin && step_action != StepOut) {
13012     return isolate->ThrowIllegalOperation();
13013   }
13014
13015   // Get the number of steps.
13016   int step_count = NumberToInt32(args[2]);
13017   if (step_count < 1) {
13018     return isolate->Throw(isolate->heap()->illegal_argument_string());
13019   }
13020
13021   // Clear all current stepping setup.
13022   isolate->debug()->ClearStepping();
13023
13024   // Prepare step.
13025   isolate->debug()->PrepareStep(static_cast<StepAction>(step_action),
13026                                 step_count,
13027                                 frame_id);
13028   return isolate->heap()->undefined_value();
13029 }
13030
13031
13032 // Clear all stepping set by PrepareStep.
13033 RUNTIME_FUNCTION(Runtime_ClearStepping) {
13034   HandleScope scope(isolate);
13035   DCHECK(args.length() == 0);
13036   isolate->debug()->ClearStepping();
13037   return isolate->heap()->undefined_value();
13038 }
13039
13040
13041 // Helper function to find or create the arguments object for
13042 // Runtime_DebugEvaluate.
13043 MUST_USE_RESULT static MaybeHandle<JSObject> MaterializeArgumentsObject(
13044     Isolate* isolate,
13045     Handle<JSObject> target,
13046     Handle<JSFunction> function) {
13047   // Do not materialize the arguments object for eval or top-level code.
13048   // Skip if "arguments" is already taken.
13049   if (!function->shared()->is_function()) return target;
13050   Maybe<bool> maybe = JSReceiver::HasOwnProperty(
13051       target, isolate->factory()->arguments_string());
13052   if (!maybe.has_value) return MaybeHandle<JSObject>();
13053   if (maybe.value) return target;
13054
13055   // FunctionGetArguments can't throw an exception.
13056   Handle<JSObject> arguments = Handle<JSObject>::cast(
13057       Accessors::FunctionGetArguments(function));
13058   Handle<String> arguments_str = isolate->factory()->arguments_string();
13059   RETURN_ON_EXCEPTION(
13060       isolate,
13061       Runtime::DefineObjectProperty(target, arguments_str, arguments, NONE),
13062       JSObject);
13063   return target;
13064 }
13065
13066
13067 // Compile and evaluate source for the given context.
13068 static MaybeHandle<Object> DebugEvaluate(Isolate* isolate,
13069                                          Handle<SharedFunctionInfo> outer_info,
13070                                          Handle<Context> context,
13071                                          Handle<Object> context_extension,
13072                                          Handle<Object> receiver,
13073                                          Handle<String> source) {
13074   if (context_extension->IsJSObject()) {
13075     Handle<JSObject> extension = Handle<JSObject>::cast(context_extension);
13076     Handle<JSFunction> closure(context->closure(), isolate);
13077     context = isolate->factory()->NewWithContext(closure, context, extension);
13078   }
13079
13080   Handle<JSFunction> eval_fun;
13081   ASSIGN_RETURN_ON_EXCEPTION(
13082       isolate, eval_fun,
13083       Compiler::GetFunctionFromEval(source,
13084                                     outer_info,
13085                                     context,
13086                                     SLOPPY,
13087                                     NO_PARSE_RESTRICTION,
13088                                     RelocInfo::kNoPosition),
13089       Object);
13090
13091   Handle<Object> result;
13092   ASSIGN_RETURN_ON_EXCEPTION(
13093       isolate, result,
13094       Execution::Call(isolate, eval_fun, receiver, 0, NULL),
13095       Object);
13096
13097   // Skip the global proxy as it has no properties and always delegates to the
13098   // real global object.
13099   if (result->IsJSGlobalProxy()) {
13100     PrototypeIterator iter(isolate, result);
13101     // TODO(verwaest): This will crash when the global proxy is detached.
13102     result = Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter));
13103   }
13104
13105   // Clear the oneshot breakpoints so that the debugger does not step further.
13106   isolate->debug()->ClearStepping();
13107   return result;
13108 }
13109
13110
13111 static Handle<JSObject> NewJSObjectWithNullProto(Isolate* isolate) {
13112   Handle<JSObject> result =
13113       isolate->factory()->NewJSObject(isolate->object_function());
13114   Handle<Map> new_map = Map::Copy(Handle<Map>(result->map()));
13115   new_map->set_prototype(*isolate->factory()->null_value());
13116   JSObject::MigrateToMap(result, new_map);
13117   return result;
13118 }
13119
13120
13121 // Evaluate a piece of JavaScript in the context of a stack frame for
13122 // debugging.  Things that need special attention are:
13123 // - Parameters and stack-allocated locals need to be materialized.  Altered
13124 //   values need to be written back to the stack afterwards.
13125 // - The arguments object needs to materialized.
13126 RUNTIME_FUNCTION(Runtime_DebugEvaluate) {
13127   HandleScope scope(isolate);
13128
13129   // Check the execution state and decode arguments frame and source to be
13130   // evaluated.
13131   DCHECK(args.length() == 6);
13132   CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
13133   RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
13134
13135   CONVERT_SMI_ARG_CHECKED(wrapped_id, 1);
13136   CONVERT_NUMBER_CHECKED(int, inlined_jsframe_index, Int32, args[2]);
13137   CONVERT_ARG_HANDLE_CHECKED(String, source, 3);
13138   CONVERT_BOOLEAN_ARG_CHECKED(disable_break, 4);
13139   CONVERT_ARG_HANDLE_CHECKED(Object, context_extension, 5);
13140
13141   // Handle the processing of break.
13142   DisableBreak disable_break_scope(isolate->debug(), disable_break);
13143
13144   // Get the frame where the debugging is performed.
13145   StackFrame::Id id = UnwrapFrameId(wrapped_id);
13146   JavaScriptFrameIterator it(isolate, id);
13147   JavaScriptFrame* frame = it.frame();
13148   FrameInspector frame_inspector(frame, inlined_jsframe_index, isolate);
13149   Handle<JSFunction> function(JSFunction::cast(frame_inspector.GetFunction()));
13150   Handle<SharedFunctionInfo> outer_info(function->shared());
13151
13152   // Traverse the saved contexts chain to find the active context for the
13153   // selected frame.
13154   SaveContext* save = FindSavedContextForFrame(isolate, frame);
13155
13156   SaveContext savex(isolate);
13157   isolate->set_context(*(save->context()));
13158
13159   // Evaluate on the context of the frame.
13160   Handle<Context> context(Context::cast(frame_inspector.GetContext()));
13161   DCHECK(!context.is_null());
13162
13163   // Materialize stack locals and the arguments object.
13164   Handle<JSObject> materialized = NewJSObjectWithNullProto(isolate);
13165
13166   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
13167       isolate, materialized,
13168       MaterializeStackLocalsWithFrameInspector(
13169           isolate, materialized, function, &frame_inspector));
13170
13171   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
13172       isolate, materialized,
13173       MaterializeArgumentsObject(isolate, materialized, function));
13174
13175   // Add the materialized object in a with-scope to shadow the stack locals.
13176   context = isolate->factory()->NewWithContext(function, context, materialized);
13177
13178   Handle<Object> receiver(frame->receiver(), isolate);
13179   Handle<Object> result;
13180   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
13181       isolate, result,
13182       DebugEvaluate(isolate, outer_info,
13183                     context, context_extension, receiver, source));
13184
13185   // Write back potential changes to materialized stack locals to the stack.
13186   UpdateStackLocalsFromMaterializedObject(
13187       isolate, materialized, function, frame, inlined_jsframe_index);
13188
13189   return *result;
13190 }
13191
13192
13193 RUNTIME_FUNCTION(Runtime_DebugEvaluateGlobal) {
13194   HandleScope scope(isolate);
13195
13196   // Check the execution state and decode arguments frame and source to be
13197   // evaluated.
13198   DCHECK(args.length() == 4);
13199   CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
13200   RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
13201
13202   CONVERT_ARG_HANDLE_CHECKED(String, source, 1);
13203   CONVERT_BOOLEAN_ARG_CHECKED(disable_break, 2);
13204   CONVERT_ARG_HANDLE_CHECKED(Object, context_extension, 3);
13205
13206   // Handle the processing of break.
13207   DisableBreak disable_break_scope(isolate->debug(), disable_break);
13208
13209   // Enter the top context from before the debugger was invoked.
13210   SaveContext save(isolate);
13211   SaveContext* top = &save;
13212   while (top != NULL && *top->context() == *isolate->debug()->debug_context()) {
13213     top = top->prev();
13214   }
13215   if (top != NULL) {
13216     isolate->set_context(*top->context());
13217   }
13218
13219   // Get the native context now set to the top context from before the
13220   // debugger was invoked.
13221   Handle<Context> context = isolate->native_context();
13222   Handle<JSObject> receiver(context->global_proxy());
13223   Handle<SharedFunctionInfo> outer_info(context->closure()->shared(), isolate);
13224   Handle<Object> result;
13225   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
13226       isolate, result,
13227       DebugEvaluate(isolate, outer_info,
13228                     context, context_extension, receiver, source));
13229   return *result;
13230 }
13231
13232
13233 RUNTIME_FUNCTION(Runtime_DebugGetLoadedScripts) {
13234   HandleScope scope(isolate);
13235   DCHECK(args.length() == 0);
13236
13237   // Fill the script objects.
13238   Handle<FixedArray> instances = isolate->debug()->GetLoadedScripts();
13239
13240   // Convert the script objects to proper JS objects.
13241   for (int i = 0; i < instances->length(); i++) {
13242     Handle<Script> script = Handle<Script>(Script::cast(instances->get(i)));
13243     // Get the script wrapper in a local handle before calling GetScriptWrapper,
13244     // because using
13245     //   instances->set(i, *GetScriptWrapper(script))
13246     // is unsafe as GetScriptWrapper might call GC and the C++ compiler might
13247     // already have dereferenced the instances handle.
13248     Handle<JSObject> wrapper = Script::GetWrapper(script);
13249     instances->set(i, *wrapper);
13250   }
13251
13252   // Return result as a JS array.
13253   Handle<JSObject> result =
13254       isolate->factory()->NewJSObject(isolate->array_function());
13255   JSArray::SetContent(Handle<JSArray>::cast(result), instances);
13256   return *result;
13257 }
13258
13259
13260 // Helper function used by Runtime_DebugReferencedBy below.
13261 static int DebugReferencedBy(HeapIterator* iterator,
13262                              JSObject* target,
13263                              Object* instance_filter, int max_references,
13264                              FixedArray* instances, int instances_size,
13265                              JSFunction* arguments_function) {
13266   Isolate* isolate = target->GetIsolate();
13267   SealHandleScope shs(isolate);
13268   DisallowHeapAllocation no_allocation;
13269
13270   // Iterate the heap.
13271   int count = 0;
13272   JSObject* last = NULL;
13273   HeapObject* heap_obj = NULL;
13274   while (((heap_obj = iterator->next()) != NULL) &&
13275          (max_references == 0 || count < max_references)) {
13276     // Only look at all JSObjects.
13277     if (heap_obj->IsJSObject()) {
13278       // Skip context extension objects and argument arrays as these are
13279       // checked in the context of functions using them.
13280       JSObject* obj = JSObject::cast(heap_obj);
13281       if (obj->IsJSContextExtensionObject() ||
13282           obj->map()->constructor() == arguments_function) {
13283         continue;
13284       }
13285
13286       // Check if the JS object has a reference to the object looked for.
13287       if (obj->ReferencesObject(target)) {
13288         // Check instance filter if supplied. This is normally used to avoid
13289         // references from mirror objects (see Runtime_IsInPrototypeChain).
13290         if (!instance_filter->IsUndefined()) {
13291           for (PrototypeIterator iter(isolate, obj); !iter.IsAtEnd();
13292                iter.Advance()) {
13293             if (iter.GetCurrent() == instance_filter) {
13294               obj = NULL;  // Don't add this object.
13295               break;
13296             }
13297           }
13298         }
13299
13300         if (obj != NULL) {
13301           // Valid reference found add to instance array if supplied an update
13302           // count.
13303           if (instances != NULL && count < instances_size) {
13304             instances->set(count, obj);
13305           }
13306           last = obj;
13307           count++;
13308         }
13309       }
13310     }
13311   }
13312
13313   // Check for circular reference only. This can happen when the object is only
13314   // referenced from mirrors and has a circular reference in which case the
13315   // object is not really alive and would have been garbage collected if not
13316   // referenced from the mirror.
13317   if (count == 1 && last == target) {
13318     count = 0;
13319   }
13320
13321   // Return the number of referencing objects found.
13322   return count;
13323 }
13324
13325
13326 // Scan the heap for objects with direct references to an object
13327 // args[0]: the object to find references to
13328 // args[1]: constructor function for instances to exclude (Mirror)
13329 // args[2]: the the maximum number of objects to return
13330 RUNTIME_FUNCTION(Runtime_DebugReferencedBy) {
13331   HandleScope scope(isolate);
13332   DCHECK(args.length() == 3);
13333
13334   // Check parameters.
13335   CONVERT_ARG_HANDLE_CHECKED(JSObject, target, 0);
13336   CONVERT_ARG_HANDLE_CHECKED(Object, instance_filter, 1);
13337   RUNTIME_ASSERT(instance_filter->IsUndefined() ||
13338                  instance_filter->IsJSObject());
13339   CONVERT_NUMBER_CHECKED(int32_t, max_references, Int32, args[2]);
13340   RUNTIME_ASSERT(max_references >= 0);
13341
13342
13343   // Get the constructor function for context extension and arguments array.
13344   Handle<JSFunction> arguments_function(
13345       JSFunction::cast(isolate->sloppy_arguments_map()->constructor()));
13346
13347   // Get the number of referencing objects.
13348   int count;
13349   // First perform a full GC in order to avoid dead objects and to make the heap
13350   // iterable.
13351   Heap* heap = isolate->heap();
13352   heap->CollectAllGarbage(Heap::kMakeHeapIterableMask, "%DebugConstructedBy");
13353   {
13354     HeapIterator heap_iterator(heap);
13355     count = DebugReferencedBy(&heap_iterator,
13356                               *target, *instance_filter, max_references,
13357                               NULL, 0, *arguments_function);
13358   }
13359
13360   // Allocate an array to hold the result.
13361   Handle<FixedArray> instances = isolate->factory()->NewFixedArray(count);
13362
13363   // Fill the referencing objects.
13364   {
13365     HeapIterator heap_iterator(heap);
13366     count = DebugReferencedBy(&heap_iterator,
13367                               *target, *instance_filter, max_references,
13368                               *instances, count, *arguments_function);
13369   }
13370
13371   // Return result as JS array.
13372   Handle<JSFunction> constructor = isolate->array_function();
13373
13374   Handle<JSObject> result = isolate->factory()->NewJSObject(constructor);
13375   JSArray::SetContent(Handle<JSArray>::cast(result), instances);
13376   return *result;
13377 }
13378
13379
13380 // Helper function used by Runtime_DebugConstructedBy below.
13381 static int DebugConstructedBy(HeapIterator* iterator,
13382                               JSFunction* constructor,
13383                               int max_references,
13384                               FixedArray* instances,
13385                               int instances_size) {
13386   DisallowHeapAllocation no_allocation;
13387
13388   // Iterate the heap.
13389   int count = 0;
13390   HeapObject* heap_obj = NULL;
13391   while (((heap_obj = iterator->next()) != NULL) &&
13392          (max_references == 0 || count < max_references)) {
13393     // Only look at all JSObjects.
13394     if (heap_obj->IsJSObject()) {
13395       JSObject* obj = JSObject::cast(heap_obj);
13396       if (obj->map()->constructor() == constructor) {
13397         // Valid reference found add to instance array if supplied an update
13398         // count.
13399         if (instances != NULL && count < instances_size) {
13400           instances->set(count, obj);
13401         }
13402         count++;
13403       }
13404     }
13405   }
13406
13407   // Return the number of referencing objects found.
13408   return count;
13409 }
13410
13411
13412 // Scan the heap for objects constructed by a specific function.
13413 // args[0]: the constructor to find instances of
13414 // args[1]: the the maximum number of objects to return
13415 RUNTIME_FUNCTION(Runtime_DebugConstructedBy) {
13416   HandleScope scope(isolate);
13417   DCHECK(args.length() == 2);
13418
13419
13420   // Check parameters.
13421   CONVERT_ARG_HANDLE_CHECKED(JSFunction, constructor, 0);
13422   CONVERT_NUMBER_CHECKED(int32_t, max_references, Int32, args[1]);
13423   RUNTIME_ASSERT(max_references >= 0);
13424
13425   // Get the number of referencing objects.
13426   int count;
13427   // First perform a full GC in order to avoid dead objects and to make the heap
13428   // iterable.
13429   Heap* heap = isolate->heap();
13430   heap->CollectAllGarbage(Heap::kMakeHeapIterableMask, "%DebugConstructedBy");
13431   {
13432     HeapIterator heap_iterator(heap);
13433     count = DebugConstructedBy(&heap_iterator,
13434                                *constructor,
13435                                max_references,
13436                                NULL,
13437                                0);
13438   }
13439
13440   // Allocate an array to hold the result.
13441   Handle<FixedArray> instances = isolate->factory()->NewFixedArray(count);
13442
13443   // Fill the referencing objects.
13444   {
13445     HeapIterator heap_iterator2(heap);
13446     count = DebugConstructedBy(&heap_iterator2,
13447                                *constructor,
13448                                max_references,
13449                                *instances,
13450                                count);
13451   }
13452
13453   // Return result as JS array.
13454   Handle<JSFunction> array_function = isolate->array_function();
13455   Handle<JSObject> result = isolate->factory()->NewJSObject(array_function);
13456   JSArray::SetContent(Handle<JSArray>::cast(result), instances);
13457   return *result;
13458 }
13459
13460
13461 // Find the effective prototype object as returned by __proto__.
13462 // args[0]: the object to find the prototype for.
13463 RUNTIME_FUNCTION(Runtime_DebugGetPrototype) {
13464   HandleScope shs(isolate);
13465   DCHECK(args.length() == 1);
13466   CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0);
13467   return *GetPrototypeSkipHiddenPrototypes(isolate, obj);
13468 }
13469
13470
13471 // Patches script source (should be called upon BeforeCompile event).
13472 RUNTIME_FUNCTION(Runtime_DebugSetScriptSource) {
13473   HandleScope scope(isolate);
13474   DCHECK(args.length() == 2);
13475
13476   CONVERT_ARG_HANDLE_CHECKED(JSValue, script_wrapper, 0);
13477   CONVERT_ARG_HANDLE_CHECKED(String, source, 1);
13478
13479   RUNTIME_ASSERT(script_wrapper->value()->IsScript());
13480   Handle<Script> script(Script::cast(script_wrapper->value()));
13481
13482   int compilation_state = script->compilation_state();
13483   RUNTIME_ASSERT(compilation_state == Script::COMPILATION_STATE_INITIAL);
13484   script->set_source(*source);
13485
13486   return isolate->heap()->undefined_value();
13487 }
13488
13489
13490 RUNTIME_FUNCTION(Runtime_SystemBreak) {
13491   SealHandleScope shs(isolate);
13492   DCHECK(args.length() == 0);
13493   base::OS::DebugBreak();
13494   return isolate->heap()->undefined_value();
13495 }
13496
13497
13498 RUNTIME_FUNCTION(Runtime_DebugDisassembleFunction) {
13499   HandleScope scope(isolate);
13500 #ifdef DEBUG
13501   DCHECK(args.length() == 1);
13502   // Get the function and make sure it is compiled.
13503   CONVERT_ARG_HANDLE_CHECKED(JSFunction, func, 0);
13504   if (!Compiler::EnsureCompiled(func, KEEP_EXCEPTION)) {
13505     return isolate->heap()->exception();
13506   }
13507   OFStream os(stdout);
13508   func->code()->Print(os);
13509   os << endl;
13510 #endif  // DEBUG
13511   return isolate->heap()->undefined_value();
13512 }
13513
13514
13515 RUNTIME_FUNCTION(Runtime_DebugDisassembleConstructor) {
13516   HandleScope scope(isolate);
13517 #ifdef DEBUG
13518   DCHECK(args.length() == 1);
13519   // Get the function and make sure it is compiled.
13520   CONVERT_ARG_HANDLE_CHECKED(JSFunction, func, 0);
13521   if (!Compiler::EnsureCompiled(func, KEEP_EXCEPTION)) {
13522     return isolate->heap()->exception();
13523   }
13524   OFStream os(stdout);
13525   func->shared()->construct_stub()->Print(os);
13526   os << endl;
13527 #endif  // DEBUG
13528   return isolate->heap()->undefined_value();
13529 }
13530
13531
13532 RUNTIME_FUNCTION(Runtime_FunctionGetInferredName) {
13533   SealHandleScope shs(isolate);
13534   DCHECK(args.length() == 1);
13535
13536   CONVERT_ARG_CHECKED(JSFunction, f, 0);
13537   return f->shared()->inferred_name();
13538 }
13539
13540
13541 static int FindSharedFunctionInfosForScript(HeapIterator* iterator,
13542                                             Script* script,
13543                                             FixedArray* buffer) {
13544   DisallowHeapAllocation no_allocation;
13545   int counter = 0;
13546   int buffer_size = buffer->length();
13547   for (HeapObject* obj = iterator->next();
13548        obj != NULL;
13549        obj = iterator->next()) {
13550     DCHECK(obj != NULL);
13551     if (!obj->IsSharedFunctionInfo()) {
13552       continue;
13553     }
13554     SharedFunctionInfo* shared = SharedFunctionInfo::cast(obj);
13555     if (shared->script() != script) {
13556       continue;
13557     }
13558     if (counter < buffer_size) {
13559       buffer->set(counter, shared);
13560     }
13561     counter++;
13562   }
13563   return counter;
13564 }
13565
13566
13567 // For a script finds all SharedFunctionInfo's in the heap that points
13568 // to this script. Returns JSArray of SharedFunctionInfo wrapped
13569 // in OpaqueReferences.
13570 RUNTIME_FUNCTION(Runtime_LiveEditFindSharedFunctionInfosForScript) {
13571   HandleScope scope(isolate);
13572   CHECK(isolate->debug()->live_edit_enabled());
13573   DCHECK(args.length() == 1);
13574   CONVERT_ARG_CHECKED(JSValue, script_value, 0);
13575
13576   RUNTIME_ASSERT(script_value->value()->IsScript());
13577   Handle<Script> script = Handle<Script>(Script::cast(script_value->value()));
13578
13579   const int kBufferSize = 32;
13580
13581   Handle<FixedArray> array;
13582   array = isolate->factory()->NewFixedArray(kBufferSize);
13583   int number;
13584   Heap* heap = isolate->heap();
13585   {
13586     HeapIterator heap_iterator(heap);
13587     Script* scr = *script;
13588     FixedArray* arr = *array;
13589     number = FindSharedFunctionInfosForScript(&heap_iterator, scr, arr);
13590   }
13591   if (number > kBufferSize) {
13592     array = isolate->factory()->NewFixedArray(number);
13593     HeapIterator heap_iterator(heap);
13594     Script* scr = *script;
13595     FixedArray* arr = *array;
13596     FindSharedFunctionInfosForScript(&heap_iterator, scr, arr);
13597   }
13598
13599   Handle<JSArray> result = isolate->factory()->NewJSArrayWithElements(array);
13600   result->set_length(Smi::FromInt(number));
13601
13602   LiveEdit::WrapSharedFunctionInfos(result);
13603
13604   return *result;
13605 }
13606
13607
13608 // For a script calculates compilation information about all its functions.
13609 // The script source is explicitly specified by the second argument.
13610 // The source of the actual script is not used, however it is important that
13611 // all generated code keeps references to this particular instance of script.
13612 // Returns a JSArray of compilation infos. The array is ordered so that
13613 // each function with all its descendant is always stored in a continues range
13614 // with the function itself going first. The root function is a script function.
13615 RUNTIME_FUNCTION(Runtime_LiveEditGatherCompileInfo) {
13616   HandleScope scope(isolate);
13617   CHECK(isolate->debug()->live_edit_enabled());
13618   DCHECK(args.length() == 2);
13619   CONVERT_ARG_CHECKED(JSValue, script, 0);
13620   CONVERT_ARG_HANDLE_CHECKED(String, source, 1);
13621
13622   RUNTIME_ASSERT(script->value()->IsScript());
13623   Handle<Script> script_handle = Handle<Script>(Script::cast(script->value()));
13624
13625   Handle<JSArray> result;
13626   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
13627       isolate, result, LiveEdit::GatherCompileInfo(script_handle, source));
13628   return *result;
13629 }
13630
13631
13632 // Changes the source of the script to a new_source.
13633 // If old_script_name is provided (i.e. is a String), also creates a copy of
13634 // the script with its original source and sends notification to debugger.
13635 RUNTIME_FUNCTION(Runtime_LiveEditReplaceScript) {
13636   HandleScope scope(isolate);
13637   CHECK(isolate->debug()->live_edit_enabled());
13638   DCHECK(args.length() == 3);
13639   CONVERT_ARG_CHECKED(JSValue, original_script_value, 0);
13640   CONVERT_ARG_HANDLE_CHECKED(String, new_source, 1);
13641   CONVERT_ARG_HANDLE_CHECKED(Object, old_script_name, 2);
13642
13643   RUNTIME_ASSERT(original_script_value->value()->IsScript());
13644   Handle<Script> original_script(Script::cast(original_script_value->value()));
13645
13646   Handle<Object> old_script = LiveEdit::ChangeScriptSource(
13647       original_script,  new_source,  old_script_name);
13648
13649   if (old_script->IsScript()) {
13650     Handle<Script> script_handle = Handle<Script>::cast(old_script);
13651     return *Script::GetWrapper(script_handle);
13652   } else {
13653     return isolate->heap()->null_value();
13654   }
13655 }
13656
13657
13658 RUNTIME_FUNCTION(Runtime_LiveEditFunctionSourceUpdated) {
13659   HandleScope scope(isolate);
13660   CHECK(isolate->debug()->live_edit_enabled());
13661   DCHECK(args.length() == 1);
13662   CONVERT_ARG_HANDLE_CHECKED(JSArray, shared_info, 0);
13663   RUNTIME_ASSERT(SharedInfoWrapper::IsInstance(shared_info));
13664
13665   LiveEdit::FunctionSourceUpdated(shared_info);
13666   return isolate->heap()->undefined_value();
13667 }
13668
13669
13670 // Replaces code of SharedFunctionInfo with a new one.
13671 RUNTIME_FUNCTION(Runtime_LiveEditReplaceFunctionCode) {
13672   HandleScope scope(isolate);
13673   CHECK(isolate->debug()->live_edit_enabled());
13674   DCHECK(args.length() == 2);
13675   CONVERT_ARG_HANDLE_CHECKED(JSArray, new_compile_info, 0);
13676   CONVERT_ARG_HANDLE_CHECKED(JSArray, shared_info, 1);
13677   RUNTIME_ASSERT(SharedInfoWrapper::IsInstance(shared_info));
13678
13679   LiveEdit::ReplaceFunctionCode(new_compile_info, shared_info);
13680   return isolate->heap()->undefined_value();
13681 }
13682
13683
13684 // Connects SharedFunctionInfo to another script.
13685 RUNTIME_FUNCTION(Runtime_LiveEditFunctionSetScript) {
13686   HandleScope scope(isolate);
13687   CHECK(isolate->debug()->live_edit_enabled());
13688   DCHECK(args.length() == 2);
13689   CONVERT_ARG_HANDLE_CHECKED(Object, function_object, 0);
13690   CONVERT_ARG_HANDLE_CHECKED(Object, script_object, 1);
13691
13692   if (function_object->IsJSValue()) {
13693     Handle<JSValue> function_wrapper = Handle<JSValue>::cast(function_object);
13694     if (script_object->IsJSValue()) {
13695       RUNTIME_ASSERT(JSValue::cast(*script_object)->value()->IsScript());
13696       Script* script = Script::cast(JSValue::cast(*script_object)->value());
13697       script_object = Handle<Object>(script, isolate);
13698     }
13699     RUNTIME_ASSERT(function_wrapper->value()->IsSharedFunctionInfo());
13700     LiveEdit::SetFunctionScript(function_wrapper, script_object);
13701   } else {
13702     // Just ignore this. We may not have a SharedFunctionInfo for some functions
13703     // and we check it in this function.
13704   }
13705
13706   return isolate->heap()->undefined_value();
13707 }
13708
13709
13710 // In a code of a parent function replaces original function as embedded object
13711 // with a substitution one.
13712 RUNTIME_FUNCTION(Runtime_LiveEditReplaceRefToNestedFunction) {
13713   HandleScope scope(isolate);
13714   CHECK(isolate->debug()->live_edit_enabled());
13715   DCHECK(args.length() == 3);
13716
13717   CONVERT_ARG_HANDLE_CHECKED(JSValue, parent_wrapper, 0);
13718   CONVERT_ARG_HANDLE_CHECKED(JSValue, orig_wrapper, 1);
13719   CONVERT_ARG_HANDLE_CHECKED(JSValue, subst_wrapper, 2);
13720   RUNTIME_ASSERT(parent_wrapper->value()->IsSharedFunctionInfo());
13721   RUNTIME_ASSERT(orig_wrapper->value()->IsSharedFunctionInfo());
13722   RUNTIME_ASSERT(subst_wrapper->value()->IsSharedFunctionInfo());
13723
13724   LiveEdit::ReplaceRefToNestedFunction(
13725       parent_wrapper, orig_wrapper, subst_wrapper);
13726   return isolate->heap()->undefined_value();
13727 }
13728
13729
13730 // Updates positions of a shared function info (first parameter) according
13731 // to script source change. Text change is described in second parameter as
13732 // array of groups of 3 numbers:
13733 // (change_begin, change_end, change_end_new_position).
13734 // Each group describes a change in text; groups are sorted by change_begin.
13735 RUNTIME_FUNCTION(Runtime_LiveEditPatchFunctionPositions) {
13736   HandleScope scope(isolate);
13737   CHECK(isolate->debug()->live_edit_enabled());
13738   DCHECK(args.length() == 2);
13739   CONVERT_ARG_HANDLE_CHECKED(JSArray, shared_array, 0);
13740   CONVERT_ARG_HANDLE_CHECKED(JSArray, position_change_array, 1);
13741   RUNTIME_ASSERT(SharedInfoWrapper::IsInstance(shared_array))
13742
13743   LiveEdit::PatchFunctionPositions(shared_array, position_change_array);
13744   return isolate->heap()->undefined_value();
13745 }
13746
13747
13748 // For array of SharedFunctionInfo's (each wrapped in JSValue)
13749 // checks that none of them have activations on stacks (of any thread).
13750 // Returns array of the same length with corresponding results of
13751 // LiveEdit::FunctionPatchabilityStatus type.
13752 RUNTIME_FUNCTION(Runtime_LiveEditCheckAndDropActivations) {
13753   HandleScope scope(isolate);
13754   CHECK(isolate->debug()->live_edit_enabled());
13755   DCHECK(args.length() == 2);
13756   CONVERT_ARG_HANDLE_CHECKED(JSArray, shared_array, 0);
13757   CONVERT_BOOLEAN_ARG_CHECKED(do_drop, 1);
13758   RUNTIME_ASSERT(shared_array->length()->IsSmi());
13759   RUNTIME_ASSERT(shared_array->HasFastElements())
13760   int array_length = Smi::cast(shared_array->length())->value();
13761   for (int i = 0; i < array_length; i++) {
13762     Handle<Object> element =
13763         Object::GetElement(isolate, shared_array, i).ToHandleChecked();
13764     RUNTIME_ASSERT(
13765         element->IsJSValue() &&
13766         Handle<JSValue>::cast(element)->value()->IsSharedFunctionInfo());
13767   }
13768
13769   return *LiveEdit::CheckAndDropActivations(shared_array, do_drop);
13770 }
13771
13772
13773 // Compares 2 strings line-by-line, then token-wise and returns diff in form
13774 // of JSArray of triplets (pos1, pos1_end, pos2_end) describing list
13775 // of diff chunks.
13776 RUNTIME_FUNCTION(Runtime_LiveEditCompareStrings) {
13777   HandleScope scope(isolate);
13778   CHECK(isolate->debug()->live_edit_enabled());
13779   DCHECK(args.length() == 2);
13780   CONVERT_ARG_HANDLE_CHECKED(String, s1, 0);
13781   CONVERT_ARG_HANDLE_CHECKED(String, s2, 1);
13782
13783   return *LiveEdit::CompareStrings(s1, s2);
13784 }
13785
13786
13787 // Restarts a call frame and completely drops all frames above.
13788 // Returns true if successful. Otherwise returns undefined or an error message.
13789 RUNTIME_FUNCTION(Runtime_LiveEditRestartFrame) {
13790   HandleScope scope(isolate);
13791   CHECK(isolate->debug()->live_edit_enabled());
13792   DCHECK(args.length() == 2);
13793   CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
13794   RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
13795
13796   CONVERT_NUMBER_CHECKED(int, index, Int32, args[1]);
13797   Heap* heap = isolate->heap();
13798
13799   // Find the relevant frame with the requested index.
13800   StackFrame::Id id = isolate->debug()->break_frame_id();
13801   if (id == StackFrame::NO_ID) {
13802     // If there are no JavaScript stack frames return undefined.
13803     return heap->undefined_value();
13804   }
13805
13806   JavaScriptFrameIterator it(isolate, id);
13807   int inlined_jsframe_index = FindIndexedNonNativeFrame(&it, index);
13808   if (inlined_jsframe_index == -1) return heap->undefined_value();
13809   // We don't really care what the inlined frame index is, since we are
13810   // throwing away the entire frame anyways.
13811   const char* error_message = LiveEdit::RestartFrame(it.frame());
13812   if (error_message) {
13813     return *(isolate->factory()->InternalizeUtf8String(error_message));
13814   }
13815   return heap->true_value();
13816 }
13817
13818
13819 // A testing entry. Returns statement position which is the closest to
13820 // source_position.
13821 RUNTIME_FUNCTION(Runtime_GetFunctionCodePositionFromSource) {
13822   HandleScope scope(isolate);
13823   CHECK(isolate->debug()->live_edit_enabled());
13824   DCHECK(args.length() == 2);
13825   CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
13826   CONVERT_NUMBER_CHECKED(int32_t, source_position, Int32, args[1]);
13827
13828   Handle<Code> code(function->code(), isolate);
13829
13830   if (code->kind() != Code::FUNCTION &&
13831       code->kind() != Code::OPTIMIZED_FUNCTION) {
13832     return isolate->heap()->undefined_value();
13833   }
13834
13835   RelocIterator it(*code, RelocInfo::ModeMask(RelocInfo::STATEMENT_POSITION));
13836   int closest_pc = 0;
13837   int distance = kMaxInt;
13838   while (!it.done()) {
13839     int statement_position = static_cast<int>(it.rinfo()->data());
13840     // Check if this break point is closer that what was previously found.
13841     if (source_position <= statement_position &&
13842         statement_position - source_position < distance) {
13843       closest_pc =
13844           static_cast<int>(it.rinfo()->pc() - code->instruction_start());
13845       distance = statement_position - source_position;
13846       // Check whether we can't get any closer.
13847       if (distance == 0) break;
13848     }
13849     it.next();
13850   }
13851
13852   return Smi::FromInt(closest_pc);
13853 }
13854
13855
13856 // Calls specified function with or without entering the debugger.
13857 // This is used in unit tests to run code as if debugger is entered or simply
13858 // to have a stack with C++ frame in the middle.
13859 RUNTIME_FUNCTION(Runtime_ExecuteInDebugContext) {
13860   HandleScope scope(isolate);
13861   DCHECK(args.length() == 2);
13862   CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
13863   CONVERT_BOOLEAN_ARG_CHECKED(without_debugger, 1);
13864
13865   MaybeHandle<Object> maybe_result;
13866   if (without_debugger) {
13867     maybe_result = Execution::Call(isolate,
13868                                    function,
13869                                    handle(function->global_proxy()),
13870                                    0,
13871                                    NULL);
13872   } else {
13873     DebugScope debug_scope(isolate->debug());
13874     maybe_result = Execution::Call(isolate,
13875                                    function,
13876                                    handle(function->global_proxy()),
13877                                    0,
13878                                    NULL);
13879   }
13880   Handle<Object> result;
13881   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, result, maybe_result);
13882   return *result;
13883 }
13884
13885
13886 // Sets a v8 flag.
13887 RUNTIME_FUNCTION(Runtime_SetFlags) {
13888   SealHandleScope shs(isolate);
13889   DCHECK(args.length() == 1);
13890   CONVERT_ARG_CHECKED(String, arg, 0);
13891   SmartArrayPointer<char> flags =
13892       arg->ToCString(DISALLOW_NULLS, ROBUST_STRING_TRAVERSAL);
13893   FlagList::SetFlagsFromString(flags.get(), StrLength(flags.get()));
13894   return isolate->heap()->undefined_value();
13895 }
13896
13897
13898 // Performs a GC.
13899 // Presently, it only does a full GC.
13900 RUNTIME_FUNCTION(Runtime_CollectGarbage) {
13901   SealHandleScope shs(isolate);
13902   DCHECK(args.length() == 1);
13903   isolate->heap()->CollectAllGarbage(Heap::kNoGCFlags, "%CollectGarbage");
13904   return isolate->heap()->undefined_value();
13905 }
13906
13907
13908 // Gets the current heap usage.
13909 RUNTIME_FUNCTION(Runtime_GetHeapUsage) {
13910   SealHandleScope shs(isolate);
13911   DCHECK(args.length() == 0);
13912   int usage = static_cast<int>(isolate->heap()->SizeOfObjects());
13913   if (!Smi::IsValid(usage)) {
13914     return *isolate->factory()->NewNumberFromInt(usage);
13915   }
13916   return Smi::FromInt(usage);
13917 }
13918
13919
13920 #ifdef V8_I18N_SUPPORT
13921 RUNTIME_FUNCTION(Runtime_CanonicalizeLanguageTag) {
13922   HandleScope scope(isolate);
13923   Factory* factory = isolate->factory();
13924
13925   DCHECK(args.length() == 1);
13926   CONVERT_ARG_HANDLE_CHECKED(String, locale_id_str, 0);
13927
13928   v8::String::Utf8Value locale_id(v8::Utils::ToLocal(locale_id_str));
13929
13930   // Return value which denotes invalid language tag.
13931   const char* const kInvalidTag = "invalid-tag";
13932
13933   UErrorCode error = U_ZERO_ERROR;
13934   char icu_result[ULOC_FULLNAME_CAPACITY];
13935   int icu_length = 0;
13936
13937   uloc_forLanguageTag(*locale_id, icu_result, ULOC_FULLNAME_CAPACITY,
13938                       &icu_length, &error);
13939   if (U_FAILURE(error) || icu_length == 0) {
13940     return *factory->NewStringFromAsciiChecked(kInvalidTag);
13941   }
13942
13943   char result[ULOC_FULLNAME_CAPACITY];
13944
13945   // Force strict BCP47 rules.
13946   uloc_toLanguageTag(icu_result, result, ULOC_FULLNAME_CAPACITY, TRUE, &error);
13947
13948   if (U_FAILURE(error)) {
13949     return *factory->NewStringFromAsciiChecked(kInvalidTag);
13950   }
13951
13952   return *factory->NewStringFromAsciiChecked(result);
13953 }
13954
13955
13956 RUNTIME_FUNCTION(Runtime_AvailableLocalesOf) {
13957   HandleScope scope(isolate);
13958   Factory* factory = isolate->factory();
13959
13960   DCHECK(args.length() == 1);
13961   CONVERT_ARG_HANDLE_CHECKED(String, service, 0);
13962
13963   const icu::Locale* available_locales = NULL;
13964   int32_t count = 0;
13965
13966   if (service->IsUtf8EqualTo(CStrVector("collator"))) {
13967     available_locales = icu::Collator::getAvailableLocales(count);
13968   } else if (service->IsUtf8EqualTo(CStrVector("numberformat"))) {
13969     available_locales = icu::NumberFormat::getAvailableLocales(count);
13970   } else if (service->IsUtf8EqualTo(CStrVector("dateformat"))) {
13971     available_locales = icu::DateFormat::getAvailableLocales(count);
13972   } else if (service->IsUtf8EqualTo(CStrVector("breakiterator"))) {
13973     available_locales = icu::BreakIterator::getAvailableLocales(count);
13974   }
13975
13976   UErrorCode error = U_ZERO_ERROR;
13977   char result[ULOC_FULLNAME_CAPACITY];
13978   Handle<JSObject> locales =
13979       factory->NewJSObject(isolate->object_function());
13980
13981   for (int32_t i = 0; i < count; ++i) {
13982     const char* icu_name = available_locales[i].getName();
13983
13984     error = U_ZERO_ERROR;
13985     // No need to force strict BCP47 rules.
13986     uloc_toLanguageTag(icu_name, result, ULOC_FULLNAME_CAPACITY, FALSE, &error);
13987     if (U_FAILURE(error)) {
13988       // This shouldn't happen, but lets not break the user.
13989       continue;
13990     }
13991
13992     RETURN_FAILURE_ON_EXCEPTION(isolate,
13993         JSObject::SetOwnPropertyIgnoreAttributes(
13994             locales,
13995             factory->NewStringFromAsciiChecked(result),
13996             factory->NewNumber(i),
13997             NONE));
13998   }
13999
14000   return *locales;
14001 }
14002
14003
14004 RUNTIME_FUNCTION(Runtime_GetDefaultICULocale) {
14005   HandleScope scope(isolate);
14006   Factory* factory = isolate->factory();
14007
14008   DCHECK(args.length() == 0);
14009
14010   icu::Locale default_locale;
14011
14012   // Set the locale
14013   char result[ULOC_FULLNAME_CAPACITY];
14014   UErrorCode status = U_ZERO_ERROR;
14015   uloc_toLanguageTag(
14016       default_locale.getName(), result, ULOC_FULLNAME_CAPACITY, FALSE, &status);
14017   if (U_SUCCESS(status)) {
14018     return *factory->NewStringFromAsciiChecked(result);
14019   }
14020
14021   return *factory->NewStringFromStaticChars("und");
14022 }
14023
14024
14025 RUNTIME_FUNCTION(Runtime_GetLanguageTagVariants) {
14026   HandleScope scope(isolate);
14027   Factory* factory = isolate->factory();
14028
14029   DCHECK(args.length() == 1);
14030
14031   CONVERT_ARG_HANDLE_CHECKED(JSArray, input, 0);
14032
14033   uint32_t length = static_cast<uint32_t>(input->length()->Number());
14034   // Set some limit to prevent fuzz tests from going OOM.
14035   // Can be bumped when callers' requirements change.
14036   RUNTIME_ASSERT(length < 100);
14037   Handle<FixedArray> output = factory->NewFixedArray(length);
14038   Handle<Name> maximized = factory->NewStringFromStaticChars("maximized");
14039   Handle<Name> base = factory->NewStringFromStaticChars("base");
14040   for (unsigned int i = 0; i < length; ++i) {
14041     Handle<Object> locale_id;
14042     ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
14043         isolate, locale_id, Object::GetElement(isolate, input, i));
14044     if (!locale_id->IsString()) {
14045       return isolate->Throw(*factory->illegal_argument_string());
14046     }
14047
14048     v8::String::Utf8Value utf8_locale_id(
14049         v8::Utils::ToLocal(Handle<String>::cast(locale_id)));
14050
14051     UErrorCode error = U_ZERO_ERROR;
14052
14053     // Convert from BCP47 to ICU format.
14054     // de-DE-u-co-phonebk -> de_DE@collation=phonebook
14055     char icu_locale[ULOC_FULLNAME_CAPACITY];
14056     int icu_locale_length = 0;
14057     uloc_forLanguageTag(*utf8_locale_id, icu_locale, ULOC_FULLNAME_CAPACITY,
14058                         &icu_locale_length, &error);
14059     if (U_FAILURE(error) || icu_locale_length == 0) {
14060       return isolate->Throw(*factory->illegal_argument_string());
14061     }
14062
14063     // Maximize the locale.
14064     // de_DE@collation=phonebook -> de_Latn_DE@collation=phonebook
14065     char icu_max_locale[ULOC_FULLNAME_CAPACITY];
14066     uloc_addLikelySubtags(
14067         icu_locale, icu_max_locale, ULOC_FULLNAME_CAPACITY, &error);
14068
14069     // Remove extensions from maximized locale.
14070     // de_Latn_DE@collation=phonebook -> de_Latn_DE
14071     char icu_base_max_locale[ULOC_FULLNAME_CAPACITY];
14072     uloc_getBaseName(
14073         icu_max_locale, icu_base_max_locale, ULOC_FULLNAME_CAPACITY, &error);
14074
14075     // Get original name without extensions.
14076     // de_DE@collation=phonebook -> de_DE
14077     char icu_base_locale[ULOC_FULLNAME_CAPACITY];
14078     uloc_getBaseName(
14079         icu_locale, icu_base_locale, ULOC_FULLNAME_CAPACITY, &error);
14080
14081     // Convert from ICU locale format to BCP47 format.
14082     // de_Latn_DE -> de-Latn-DE
14083     char base_max_locale[ULOC_FULLNAME_CAPACITY];
14084     uloc_toLanguageTag(icu_base_max_locale, base_max_locale,
14085                        ULOC_FULLNAME_CAPACITY, FALSE, &error);
14086
14087     // de_DE -> de-DE
14088     char base_locale[ULOC_FULLNAME_CAPACITY];
14089     uloc_toLanguageTag(
14090         icu_base_locale, base_locale, ULOC_FULLNAME_CAPACITY, FALSE, &error);
14091
14092     if (U_FAILURE(error)) {
14093       return isolate->Throw(*factory->illegal_argument_string());
14094     }
14095
14096     Handle<JSObject> result = factory->NewJSObject(isolate->object_function());
14097     Handle<String> value = factory->NewStringFromAsciiChecked(base_max_locale);
14098     JSObject::AddProperty(result, maximized, value, NONE);
14099     value = factory->NewStringFromAsciiChecked(base_locale);
14100     JSObject::AddProperty(result, base, value, NONE);
14101     output->set(i, *result);
14102   }
14103
14104   Handle<JSArray> result = factory->NewJSArrayWithElements(output);
14105   result->set_length(Smi::FromInt(length));
14106   return *result;
14107 }
14108
14109
14110 RUNTIME_FUNCTION(Runtime_IsInitializedIntlObject) {
14111   HandleScope scope(isolate);
14112
14113   DCHECK(args.length() == 1);
14114
14115   CONVERT_ARG_HANDLE_CHECKED(Object, input, 0);
14116
14117   if (!input->IsJSObject()) return isolate->heap()->false_value();
14118   Handle<JSObject> obj = Handle<JSObject>::cast(input);
14119
14120   Handle<String> marker = isolate->factory()->intl_initialized_marker_string();
14121   Handle<Object> tag(obj->GetHiddenProperty(marker), isolate);
14122   return isolate->heap()->ToBoolean(!tag->IsTheHole());
14123 }
14124
14125
14126 RUNTIME_FUNCTION(Runtime_IsInitializedIntlObjectOfType) {
14127   HandleScope scope(isolate);
14128
14129   DCHECK(args.length() == 2);
14130
14131   CONVERT_ARG_HANDLE_CHECKED(Object, input, 0);
14132   CONVERT_ARG_HANDLE_CHECKED(String, expected_type, 1);
14133
14134   if (!input->IsJSObject()) return isolate->heap()->false_value();
14135   Handle<JSObject> obj = Handle<JSObject>::cast(input);
14136
14137   Handle<String> marker = isolate->factory()->intl_initialized_marker_string();
14138   Handle<Object> tag(obj->GetHiddenProperty(marker), isolate);
14139   return isolate->heap()->ToBoolean(
14140       tag->IsString() && String::cast(*tag)->Equals(*expected_type));
14141 }
14142
14143
14144 RUNTIME_FUNCTION(Runtime_MarkAsInitializedIntlObjectOfType) {
14145   HandleScope scope(isolate);
14146
14147   DCHECK(args.length() == 3);
14148
14149   CONVERT_ARG_HANDLE_CHECKED(JSObject, input, 0);
14150   CONVERT_ARG_HANDLE_CHECKED(String, type, 1);
14151   CONVERT_ARG_HANDLE_CHECKED(JSObject, impl, 2);
14152
14153   Handle<String> marker = isolate->factory()->intl_initialized_marker_string();
14154   JSObject::SetHiddenProperty(input, marker, type);
14155
14156   marker = isolate->factory()->intl_impl_object_string();
14157   JSObject::SetHiddenProperty(input, marker, impl);
14158
14159   return isolate->heap()->undefined_value();
14160 }
14161
14162
14163 RUNTIME_FUNCTION(Runtime_GetImplFromInitializedIntlObject) {
14164   HandleScope scope(isolate);
14165
14166   DCHECK(args.length() == 1);
14167
14168   CONVERT_ARG_HANDLE_CHECKED(Object, input, 0);
14169
14170   if (!input->IsJSObject()) {
14171     Vector< Handle<Object> > arguments = HandleVector(&input, 1);
14172     THROW_NEW_ERROR_RETURN_FAILURE(isolate,
14173                                    NewTypeError("not_intl_object", arguments));
14174   }
14175
14176   Handle<JSObject> obj = Handle<JSObject>::cast(input);
14177
14178   Handle<String> marker = isolate->factory()->intl_impl_object_string();
14179   Handle<Object> impl(obj->GetHiddenProperty(marker), isolate);
14180   if (impl->IsTheHole()) {
14181     Vector< Handle<Object> > arguments = HandleVector(&obj, 1);
14182     THROW_NEW_ERROR_RETURN_FAILURE(isolate,
14183                                    NewTypeError("not_intl_object", arguments));
14184   }
14185   return *impl;
14186 }
14187
14188
14189 RUNTIME_FUNCTION(Runtime_CreateDateTimeFormat) {
14190   HandleScope scope(isolate);
14191
14192   DCHECK(args.length() == 3);
14193
14194   CONVERT_ARG_HANDLE_CHECKED(String, locale, 0);
14195   CONVERT_ARG_HANDLE_CHECKED(JSObject, options, 1);
14196   CONVERT_ARG_HANDLE_CHECKED(JSObject, resolved, 2);
14197
14198   Handle<ObjectTemplateInfo> date_format_template =
14199       I18N::GetTemplate(isolate);
14200
14201   // Create an empty object wrapper.
14202   Handle<JSObject> local_object;
14203   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
14204       isolate, local_object,
14205       Execution::InstantiateObject(date_format_template));
14206
14207   // Set date time formatter as internal field of the resulting JS object.
14208   icu::SimpleDateFormat* date_format = DateFormat::InitializeDateTimeFormat(
14209       isolate, locale, options, resolved);
14210
14211   if (!date_format) return isolate->ThrowIllegalOperation();
14212
14213   local_object->SetInternalField(0, reinterpret_cast<Smi*>(date_format));
14214
14215   Factory* factory = isolate->factory();
14216   Handle<String> key = factory->NewStringFromStaticChars("dateFormat");
14217   Handle<String> value = factory->NewStringFromStaticChars("valid");
14218   JSObject::AddProperty(local_object, key, value, NONE);
14219
14220   // Make object handle weak so we can delete the data format once GC kicks in.
14221   Handle<Object> wrapper = isolate->global_handles()->Create(*local_object);
14222   GlobalHandles::MakeWeak(wrapper.location(),
14223                           reinterpret_cast<void*>(wrapper.location()),
14224                           DateFormat::DeleteDateFormat);
14225   return *local_object;
14226 }
14227
14228
14229 RUNTIME_FUNCTION(Runtime_InternalDateFormat) {
14230   HandleScope scope(isolate);
14231
14232   DCHECK(args.length() == 2);
14233
14234   CONVERT_ARG_HANDLE_CHECKED(JSObject, date_format_holder, 0);
14235   CONVERT_ARG_HANDLE_CHECKED(JSDate, date, 1);
14236
14237   Handle<Object> value;
14238   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
14239       isolate, value, Execution::ToNumber(isolate, date));
14240
14241   icu::SimpleDateFormat* date_format =
14242       DateFormat::UnpackDateFormat(isolate, date_format_holder);
14243   if (!date_format) return isolate->ThrowIllegalOperation();
14244
14245   icu::UnicodeString result;
14246   date_format->format(value->Number(), result);
14247
14248   Handle<String> result_str;
14249   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
14250       isolate, result_str,
14251       isolate->factory()->NewStringFromTwoByte(
14252           Vector<const uint16_t>(
14253               reinterpret_cast<const uint16_t*>(result.getBuffer()),
14254               result.length())));
14255   return *result_str;
14256 }
14257
14258
14259 RUNTIME_FUNCTION(Runtime_InternalDateParse) {
14260   HandleScope scope(isolate);
14261
14262   DCHECK(args.length() == 2);
14263
14264   CONVERT_ARG_HANDLE_CHECKED(JSObject, date_format_holder, 0);
14265   CONVERT_ARG_HANDLE_CHECKED(String, date_string, 1);
14266
14267   v8::String::Utf8Value utf8_date(v8::Utils::ToLocal(date_string));
14268   icu::UnicodeString u_date(icu::UnicodeString::fromUTF8(*utf8_date));
14269   icu::SimpleDateFormat* date_format =
14270       DateFormat::UnpackDateFormat(isolate, date_format_holder);
14271   if (!date_format) return isolate->ThrowIllegalOperation();
14272
14273   UErrorCode status = U_ZERO_ERROR;
14274   UDate date = date_format->parse(u_date, status);
14275   if (U_FAILURE(status)) return isolate->heap()->undefined_value();
14276
14277   Handle<Object> result;
14278   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
14279       isolate, result,
14280       Execution::NewDate(isolate, static_cast<double>(date)));
14281   DCHECK(result->IsJSDate());
14282   return *result;
14283 }
14284
14285
14286 RUNTIME_FUNCTION(Runtime_CreateNumberFormat) {
14287   HandleScope scope(isolate);
14288
14289   DCHECK(args.length() == 3);
14290
14291   CONVERT_ARG_HANDLE_CHECKED(String, locale, 0);
14292   CONVERT_ARG_HANDLE_CHECKED(JSObject, options, 1);
14293   CONVERT_ARG_HANDLE_CHECKED(JSObject, resolved, 2);
14294
14295   Handle<ObjectTemplateInfo> number_format_template =
14296       I18N::GetTemplate(isolate);
14297
14298   // Create an empty object wrapper.
14299   Handle<JSObject> local_object;
14300   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
14301       isolate, local_object,
14302       Execution::InstantiateObject(number_format_template));
14303
14304   // Set number formatter as internal field of the resulting JS object.
14305   icu::DecimalFormat* number_format = NumberFormat::InitializeNumberFormat(
14306       isolate, locale, options, resolved);
14307
14308   if (!number_format) return isolate->ThrowIllegalOperation();
14309
14310   local_object->SetInternalField(0, reinterpret_cast<Smi*>(number_format));
14311
14312   Factory* factory = isolate->factory();
14313   Handle<String> key = factory->NewStringFromStaticChars("numberFormat");
14314   Handle<String> value = factory->NewStringFromStaticChars("valid");
14315   JSObject::AddProperty(local_object, key, value, NONE);
14316
14317   Handle<Object> wrapper = isolate->global_handles()->Create(*local_object);
14318   GlobalHandles::MakeWeak(wrapper.location(),
14319                           reinterpret_cast<void*>(wrapper.location()),
14320                           NumberFormat::DeleteNumberFormat);
14321   return *local_object;
14322 }
14323
14324
14325 RUNTIME_FUNCTION(Runtime_InternalNumberFormat) {
14326   HandleScope scope(isolate);
14327
14328   DCHECK(args.length() == 2);
14329
14330   CONVERT_ARG_HANDLE_CHECKED(JSObject, number_format_holder, 0);
14331   CONVERT_ARG_HANDLE_CHECKED(Object, number, 1);
14332
14333   Handle<Object> value;
14334   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
14335       isolate, value, Execution::ToNumber(isolate, number));
14336
14337   icu::DecimalFormat* number_format =
14338       NumberFormat::UnpackNumberFormat(isolate, number_format_holder);
14339   if (!number_format) return isolate->ThrowIllegalOperation();
14340
14341   icu::UnicodeString result;
14342   number_format->format(value->Number(), result);
14343
14344   Handle<String> result_str;
14345   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
14346       isolate, result_str,
14347       isolate->factory()->NewStringFromTwoByte(
14348           Vector<const uint16_t>(
14349               reinterpret_cast<const uint16_t*>(result.getBuffer()),
14350               result.length())));
14351   return *result_str;
14352 }
14353
14354
14355 RUNTIME_FUNCTION(Runtime_InternalNumberParse) {
14356   HandleScope scope(isolate);
14357
14358   DCHECK(args.length() == 2);
14359
14360   CONVERT_ARG_HANDLE_CHECKED(JSObject, number_format_holder, 0);
14361   CONVERT_ARG_HANDLE_CHECKED(String, number_string, 1);
14362
14363   v8::String::Utf8Value utf8_number(v8::Utils::ToLocal(number_string));
14364   icu::UnicodeString u_number(icu::UnicodeString::fromUTF8(*utf8_number));
14365   icu::DecimalFormat* number_format =
14366       NumberFormat::UnpackNumberFormat(isolate, number_format_holder);
14367   if (!number_format) return isolate->ThrowIllegalOperation();
14368
14369   UErrorCode status = U_ZERO_ERROR;
14370   icu::Formattable result;
14371   // ICU 4.6 doesn't support parseCurrency call. We need to wait for ICU49
14372   // to be part of Chrome.
14373   // TODO(cira): Include currency parsing code using parseCurrency call.
14374   // We need to check if the formatter parses all currencies or only the
14375   // one it was constructed with (it will impact the API - how to return ISO
14376   // code and the value).
14377   number_format->parse(u_number, result, status);
14378   if (U_FAILURE(status)) return isolate->heap()->undefined_value();
14379
14380   switch (result.getType()) {
14381   case icu::Formattable::kDouble:
14382     return *isolate->factory()->NewNumber(result.getDouble());
14383   case icu::Formattable::kLong:
14384     return *isolate->factory()->NewNumberFromInt(result.getLong());
14385   case icu::Formattable::kInt64:
14386     return *isolate->factory()->NewNumber(
14387         static_cast<double>(result.getInt64()));
14388   default:
14389     return isolate->heap()->undefined_value();
14390   }
14391 }
14392
14393
14394 RUNTIME_FUNCTION(Runtime_CreateCollator) {
14395   HandleScope scope(isolate);
14396
14397   DCHECK(args.length() == 3);
14398
14399   CONVERT_ARG_HANDLE_CHECKED(String, locale, 0);
14400   CONVERT_ARG_HANDLE_CHECKED(JSObject, options, 1);
14401   CONVERT_ARG_HANDLE_CHECKED(JSObject, resolved, 2);
14402
14403   Handle<ObjectTemplateInfo> collator_template = I18N::GetTemplate(isolate);
14404
14405   // Create an empty object wrapper.
14406   Handle<JSObject> local_object;
14407   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
14408       isolate, local_object, Execution::InstantiateObject(collator_template));
14409
14410   // Set collator as internal field of the resulting JS object.
14411   icu::Collator* collator = Collator::InitializeCollator(
14412       isolate, locale, options, resolved);
14413
14414   if (!collator) return isolate->ThrowIllegalOperation();
14415
14416   local_object->SetInternalField(0, reinterpret_cast<Smi*>(collator));
14417
14418   Factory* factory = isolate->factory();
14419   Handle<String> key = factory->NewStringFromStaticChars("collator");
14420   Handle<String> value = factory->NewStringFromStaticChars("valid");
14421   JSObject::AddProperty(local_object, key, value, NONE);
14422
14423   Handle<Object> wrapper = isolate->global_handles()->Create(*local_object);
14424   GlobalHandles::MakeWeak(wrapper.location(),
14425                           reinterpret_cast<void*>(wrapper.location()),
14426                           Collator::DeleteCollator);
14427   return *local_object;
14428 }
14429
14430
14431 RUNTIME_FUNCTION(Runtime_InternalCompare) {
14432   HandleScope scope(isolate);
14433
14434   DCHECK(args.length() == 3);
14435
14436   CONVERT_ARG_HANDLE_CHECKED(JSObject, collator_holder, 0);
14437   CONVERT_ARG_HANDLE_CHECKED(String, string1, 1);
14438   CONVERT_ARG_HANDLE_CHECKED(String, string2, 2);
14439
14440   icu::Collator* collator = Collator::UnpackCollator(isolate, collator_holder);
14441   if (!collator) return isolate->ThrowIllegalOperation();
14442
14443   v8::String::Value string_value1(v8::Utils::ToLocal(string1));
14444   v8::String::Value string_value2(v8::Utils::ToLocal(string2));
14445   const UChar* u_string1 = reinterpret_cast<const UChar*>(*string_value1);
14446   const UChar* u_string2 = reinterpret_cast<const UChar*>(*string_value2);
14447   UErrorCode status = U_ZERO_ERROR;
14448   UCollationResult result = collator->compare(u_string1,
14449                                               string_value1.length(),
14450                                               u_string2,
14451                                               string_value2.length(),
14452                                               status);
14453   if (U_FAILURE(status)) return isolate->ThrowIllegalOperation();
14454
14455   return *isolate->factory()->NewNumberFromInt(result);
14456 }
14457
14458
14459 RUNTIME_FUNCTION(Runtime_StringNormalize) {
14460   HandleScope scope(isolate);
14461   static const UNormalizationMode normalizationForms[] =
14462       { UNORM_NFC, UNORM_NFD, UNORM_NFKC, UNORM_NFKD };
14463
14464   DCHECK(args.length() == 2);
14465
14466   CONVERT_ARG_HANDLE_CHECKED(String, stringValue, 0);
14467   CONVERT_NUMBER_CHECKED(int, form_id, Int32, args[1]);
14468   RUNTIME_ASSERT(form_id >= 0 &&
14469                  static_cast<size_t>(form_id) < arraysize(normalizationForms));
14470
14471   v8::String::Value string_value(v8::Utils::ToLocal(stringValue));
14472   const UChar* u_value = reinterpret_cast<const UChar*>(*string_value);
14473
14474   // TODO(mnita): check Normalizer2 (not available in ICU 46)
14475   UErrorCode status = U_ZERO_ERROR;
14476   icu::UnicodeString result;
14477   icu::Normalizer::normalize(u_value, normalizationForms[form_id], 0,
14478       result, status);
14479   if (U_FAILURE(status)) {
14480     return isolate->heap()->undefined_value();
14481   }
14482
14483   Handle<String> result_str;
14484   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
14485       isolate, result_str,
14486       isolate->factory()->NewStringFromTwoByte(
14487           Vector<const uint16_t>(
14488               reinterpret_cast<const uint16_t*>(result.getBuffer()),
14489               result.length())));
14490   return *result_str;
14491 }
14492
14493
14494 RUNTIME_FUNCTION(Runtime_CreateBreakIterator) {
14495   HandleScope scope(isolate);
14496
14497   DCHECK(args.length() == 3);
14498
14499   CONVERT_ARG_HANDLE_CHECKED(String, locale, 0);
14500   CONVERT_ARG_HANDLE_CHECKED(JSObject, options, 1);
14501   CONVERT_ARG_HANDLE_CHECKED(JSObject, resolved, 2);
14502
14503   Handle<ObjectTemplateInfo> break_iterator_template =
14504       I18N::GetTemplate2(isolate);
14505
14506   // Create an empty object wrapper.
14507   Handle<JSObject> local_object;
14508   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
14509       isolate, local_object,
14510       Execution::InstantiateObject(break_iterator_template));
14511
14512   // Set break iterator as internal field of the resulting JS object.
14513   icu::BreakIterator* break_iterator = BreakIterator::InitializeBreakIterator(
14514       isolate, locale, options, resolved);
14515
14516   if (!break_iterator) return isolate->ThrowIllegalOperation();
14517
14518   local_object->SetInternalField(0, reinterpret_cast<Smi*>(break_iterator));
14519   // Make sure that the pointer to adopted text is NULL.
14520   local_object->SetInternalField(1, reinterpret_cast<Smi*>(NULL));
14521
14522   Factory* factory = isolate->factory();
14523   Handle<String> key = factory->NewStringFromStaticChars("breakIterator");
14524   Handle<String> value = factory->NewStringFromStaticChars("valid");
14525   JSObject::AddProperty(local_object, key, value, NONE);
14526
14527   // Make object handle weak so we can delete the break iterator once GC kicks
14528   // in.
14529   Handle<Object> wrapper = isolate->global_handles()->Create(*local_object);
14530   GlobalHandles::MakeWeak(wrapper.location(),
14531                           reinterpret_cast<void*>(wrapper.location()),
14532                           BreakIterator::DeleteBreakIterator);
14533   return *local_object;
14534 }
14535
14536
14537 RUNTIME_FUNCTION(Runtime_BreakIteratorAdoptText) {
14538   HandleScope scope(isolate);
14539
14540   DCHECK(args.length() == 2);
14541
14542   CONVERT_ARG_HANDLE_CHECKED(JSObject, break_iterator_holder, 0);
14543   CONVERT_ARG_HANDLE_CHECKED(String, text, 1);
14544
14545   icu::BreakIterator* break_iterator =
14546       BreakIterator::UnpackBreakIterator(isolate, break_iterator_holder);
14547   if (!break_iterator) return isolate->ThrowIllegalOperation();
14548
14549   icu::UnicodeString* u_text = reinterpret_cast<icu::UnicodeString*>(
14550       break_iterator_holder->GetInternalField(1));
14551   delete u_text;
14552
14553   v8::String::Value text_value(v8::Utils::ToLocal(text));
14554   u_text = new icu::UnicodeString(
14555       reinterpret_cast<const UChar*>(*text_value), text_value.length());
14556   break_iterator_holder->SetInternalField(1, reinterpret_cast<Smi*>(u_text));
14557
14558   break_iterator->setText(*u_text);
14559
14560   return isolate->heap()->undefined_value();
14561 }
14562
14563
14564 RUNTIME_FUNCTION(Runtime_BreakIteratorFirst) {
14565   HandleScope scope(isolate);
14566
14567   DCHECK(args.length() == 1);
14568
14569   CONVERT_ARG_HANDLE_CHECKED(JSObject, break_iterator_holder, 0);
14570
14571   icu::BreakIterator* break_iterator =
14572       BreakIterator::UnpackBreakIterator(isolate, break_iterator_holder);
14573   if (!break_iterator) return isolate->ThrowIllegalOperation();
14574
14575   return *isolate->factory()->NewNumberFromInt(break_iterator->first());
14576 }
14577
14578
14579 RUNTIME_FUNCTION(Runtime_BreakIteratorNext) {
14580   HandleScope scope(isolate);
14581
14582   DCHECK(args.length() == 1);
14583
14584   CONVERT_ARG_HANDLE_CHECKED(JSObject, break_iterator_holder, 0);
14585
14586   icu::BreakIterator* break_iterator =
14587       BreakIterator::UnpackBreakIterator(isolate, break_iterator_holder);
14588   if (!break_iterator) return isolate->ThrowIllegalOperation();
14589
14590   return *isolate->factory()->NewNumberFromInt(break_iterator->next());
14591 }
14592
14593
14594 RUNTIME_FUNCTION(Runtime_BreakIteratorCurrent) {
14595   HandleScope scope(isolate);
14596
14597   DCHECK(args.length() == 1);
14598
14599   CONVERT_ARG_HANDLE_CHECKED(JSObject, break_iterator_holder, 0);
14600
14601   icu::BreakIterator* break_iterator =
14602       BreakIterator::UnpackBreakIterator(isolate, break_iterator_holder);
14603   if (!break_iterator) return isolate->ThrowIllegalOperation();
14604
14605   return *isolate->factory()->NewNumberFromInt(break_iterator->current());
14606 }
14607
14608
14609 RUNTIME_FUNCTION(Runtime_BreakIteratorBreakType) {
14610   HandleScope scope(isolate);
14611
14612   DCHECK(args.length() == 1);
14613
14614   CONVERT_ARG_HANDLE_CHECKED(JSObject, break_iterator_holder, 0);
14615
14616   icu::BreakIterator* break_iterator =
14617       BreakIterator::UnpackBreakIterator(isolate, break_iterator_holder);
14618   if (!break_iterator) return isolate->ThrowIllegalOperation();
14619
14620   // TODO(cira): Remove cast once ICU fixes base BreakIterator class.
14621   icu::RuleBasedBreakIterator* rule_based_iterator =
14622       static_cast<icu::RuleBasedBreakIterator*>(break_iterator);
14623   int32_t status = rule_based_iterator->getRuleStatus();
14624   // Keep return values in sync with JavaScript BreakType enum.
14625   if (status >= UBRK_WORD_NONE && status < UBRK_WORD_NONE_LIMIT) {
14626     return *isolate->factory()->NewStringFromStaticChars("none");
14627   } else if (status >= UBRK_WORD_NUMBER && status < UBRK_WORD_NUMBER_LIMIT) {
14628     return *isolate->factory()->number_string();
14629   } else if (status >= UBRK_WORD_LETTER && status < UBRK_WORD_LETTER_LIMIT) {
14630     return *isolate->factory()->NewStringFromStaticChars("letter");
14631   } else if (status >= UBRK_WORD_KANA && status < UBRK_WORD_KANA_LIMIT) {
14632     return *isolate->factory()->NewStringFromStaticChars("kana");
14633   } else if (status >= UBRK_WORD_IDEO && status < UBRK_WORD_IDEO_LIMIT) {
14634     return *isolate->factory()->NewStringFromStaticChars("ideo");
14635   } else {
14636     return *isolate->factory()->NewStringFromStaticChars("unknown");
14637   }
14638 }
14639 #endif  // V8_I18N_SUPPORT
14640
14641
14642 // Finds the script object from the script data. NOTE: This operation uses
14643 // heap traversal to find the function generated for the source position
14644 // for the requested break point. For lazily compiled functions several heap
14645 // traversals might be required rendering this operation as a rather slow
14646 // operation. However for setting break points which is normally done through
14647 // some kind of user interaction the performance is not crucial.
14648 static Handle<Object> Runtime_GetScriptFromScriptName(
14649     Handle<String> script_name) {
14650   // Scan the heap for Script objects to find the script with the requested
14651   // script data.
14652   Handle<Script> script;
14653   Factory* factory = script_name->GetIsolate()->factory();
14654   Heap* heap = script_name->GetHeap();
14655   HeapIterator iterator(heap);
14656   HeapObject* obj = NULL;
14657   while (script.is_null() && ((obj = iterator.next()) != NULL)) {
14658     // If a script is found check if it has the script data requested.
14659     if (obj->IsScript()) {
14660       if (Script::cast(obj)->name()->IsString()) {
14661         if (String::cast(Script::cast(obj)->name())->Equals(*script_name)) {
14662           script = Handle<Script>(Script::cast(obj));
14663         }
14664       }
14665     }
14666   }
14667
14668   // If no script with the requested script data is found return undefined.
14669   if (script.is_null()) return factory->undefined_value();
14670
14671   // Return the script found.
14672   return Script::GetWrapper(script);
14673 }
14674
14675
14676 // Get the script object from script data. NOTE: Regarding performance
14677 // see the NOTE for GetScriptFromScriptData.
14678 // args[0]: script data for the script to find the source for
14679 RUNTIME_FUNCTION(Runtime_GetScript) {
14680   HandleScope scope(isolate);
14681
14682   DCHECK(args.length() == 1);
14683
14684   CONVERT_ARG_CHECKED(String, script_name, 0);
14685
14686   // Find the requested script.
14687   Handle<Object> result =
14688       Runtime_GetScriptFromScriptName(Handle<String>(script_name));
14689   return *result;
14690 }
14691
14692
14693 // Collect the raw data for a stack trace.  Returns an array of 4
14694 // element segments each containing a receiver, function, code and
14695 // native code offset.
14696 RUNTIME_FUNCTION(Runtime_CollectStackTrace) {
14697   HandleScope scope(isolate);
14698   DCHECK(args.length() == 2);
14699   CONVERT_ARG_HANDLE_CHECKED(JSObject, error_object, 0);
14700   CONVERT_ARG_HANDLE_CHECKED(Object, caller, 1);
14701
14702   if (!isolate->bootstrapper()->IsActive()) {
14703     // Optionally capture a more detailed stack trace for the message.
14704     isolate->CaptureAndSetDetailedStackTrace(error_object);
14705     // Capture a simple stack trace for the stack property.
14706     isolate->CaptureAndSetSimpleStackTrace(error_object, caller);
14707   }
14708   return isolate->heap()->undefined_value();
14709 }
14710
14711
14712 // Returns V8 version as a string.
14713 RUNTIME_FUNCTION(Runtime_GetV8Version) {
14714   HandleScope scope(isolate);
14715   DCHECK(args.length() == 0);
14716
14717   const char* version_string = v8::V8::GetVersion();
14718
14719   return *isolate->factory()->NewStringFromAsciiChecked(version_string);
14720 }
14721
14722
14723 // Returns function of generator activation.
14724 RUNTIME_FUNCTION(Runtime_GeneratorGetFunction) {
14725   HandleScope scope(isolate);
14726   DCHECK(args.length() == 1);
14727   CONVERT_ARG_HANDLE_CHECKED(JSGeneratorObject, generator, 0);
14728
14729   return generator->function();
14730 }
14731
14732
14733 // Returns context of generator activation.
14734 RUNTIME_FUNCTION(Runtime_GeneratorGetContext) {
14735   HandleScope scope(isolate);
14736   DCHECK(args.length() == 1);
14737   CONVERT_ARG_HANDLE_CHECKED(JSGeneratorObject, generator, 0);
14738
14739   return generator->context();
14740 }
14741
14742
14743 // Returns receiver of generator activation.
14744 RUNTIME_FUNCTION(Runtime_GeneratorGetReceiver) {
14745   HandleScope scope(isolate);
14746   DCHECK(args.length() == 1);
14747   CONVERT_ARG_HANDLE_CHECKED(JSGeneratorObject, generator, 0);
14748
14749   return generator->receiver();
14750 }
14751
14752
14753 // Returns generator continuation as a PC offset, or the magic -1 or 0 values.
14754 RUNTIME_FUNCTION(Runtime_GeneratorGetContinuation) {
14755   HandleScope scope(isolate);
14756   DCHECK(args.length() == 1);
14757   CONVERT_ARG_HANDLE_CHECKED(JSGeneratorObject, generator, 0);
14758
14759   return Smi::FromInt(generator->continuation());
14760 }
14761
14762
14763 RUNTIME_FUNCTION(Runtime_GeneratorGetSourcePosition) {
14764   HandleScope scope(isolate);
14765   DCHECK(args.length() == 1);
14766   CONVERT_ARG_HANDLE_CHECKED(JSGeneratorObject, generator, 0);
14767
14768   if (generator->is_suspended()) {
14769     Handle<Code> code(generator->function()->code(), isolate);
14770     int offset = generator->continuation();
14771
14772     RUNTIME_ASSERT(0 <= offset && offset < code->Size());
14773     Address pc = code->address() + offset;
14774
14775     return Smi::FromInt(code->SourcePosition(pc));
14776   }
14777
14778   return isolate->heap()->undefined_value();
14779 }
14780
14781
14782 RUNTIME_FUNCTION(Runtime_Abort) {
14783   SealHandleScope shs(isolate);
14784   DCHECK(args.length() == 1);
14785   CONVERT_SMI_ARG_CHECKED(message_id, 0);
14786   const char* message = GetBailoutReason(
14787       static_cast<BailoutReason>(message_id));
14788   base::OS::PrintError("abort: %s\n", message);
14789   isolate->PrintStack(stderr);
14790   base::OS::Abort();
14791   UNREACHABLE();
14792   return NULL;
14793 }
14794
14795
14796 RUNTIME_FUNCTION(Runtime_AbortJS) {
14797   HandleScope scope(isolate);
14798   DCHECK(args.length() == 1);
14799   CONVERT_ARG_HANDLE_CHECKED(String, message, 0);
14800   base::OS::PrintError("abort: %s\n", message->ToCString().get());
14801   isolate->PrintStack(stderr);
14802   base::OS::Abort();
14803   UNREACHABLE();
14804   return NULL;
14805 }
14806
14807
14808 RUNTIME_FUNCTION(Runtime_FlattenString) {
14809   HandleScope scope(isolate);
14810   DCHECK(args.length() == 1);
14811   CONVERT_ARG_HANDLE_CHECKED(String, str, 0);
14812   return *String::Flatten(str);
14813 }
14814
14815
14816 RUNTIME_FUNCTION(Runtime_NotifyContextDisposed) {
14817   HandleScope scope(isolate);
14818   DCHECK(args.length() == 0);
14819   isolate->heap()->NotifyContextDisposed();
14820   return isolate->heap()->undefined_value();
14821 }
14822
14823
14824 RUNTIME_FUNCTION(Runtime_LoadMutableDouble) {
14825   HandleScope scope(isolate);
14826   DCHECK(args.length() == 2);
14827   CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0);
14828   CONVERT_ARG_HANDLE_CHECKED(Smi, index, 1);
14829   RUNTIME_ASSERT((index->value() & 1) == 1);
14830   FieldIndex field_index =
14831       FieldIndex::ForLoadByFieldIndex(object->map(), index->value());
14832   if (field_index.is_inobject()) {
14833     RUNTIME_ASSERT(field_index.property_index() <
14834                    object->map()->inobject_properties());
14835   } else {
14836     RUNTIME_ASSERT(field_index.outobject_array_index() <
14837                    object->properties()->length());
14838   }
14839   Handle<Object> raw_value(object->RawFastPropertyAt(field_index), isolate);
14840   RUNTIME_ASSERT(raw_value->IsMutableHeapNumber());
14841   return *Object::WrapForRead(isolate, raw_value, Representation::Double());
14842 }
14843
14844
14845 RUNTIME_FUNCTION(Runtime_TryMigrateInstance) {
14846   HandleScope scope(isolate);
14847   DCHECK(args.length() == 1);
14848   CONVERT_ARG_HANDLE_CHECKED(Object, object, 0);
14849   if (!object->IsJSObject()) return Smi::FromInt(0);
14850   Handle<JSObject> js_object = Handle<JSObject>::cast(object);
14851   if (!js_object->map()->is_deprecated()) return Smi::FromInt(0);
14852   // This call must not cause lazy deopts, because it's called from deferred
14853   // code where we can't handle lazy deopts for lack of a suitable bailout
14854   // ID. So we just try migration and signal failure if necessary,
14855   // which will also trigger a deopt.
14856   if (!JSObject::TryMigrateInstance(js_object)) return Smi::FromInt(0);
14857   return *object;
14858 }
14859
14860
14861 RUNTIME_FUNCTION(Runtime_GetFromCache) {
14862   SealHandleScope shs(isolate);
14863   // This is only called from codegen, so checks might be more lax.
14864   CONVERT_ARG_CHECKED(JSFunctionResultCache, cache, 0);
14865   CONVERT_ARG_CHECKED(Object, key, 1);
14866
14867   {
14868     DisallowHeapAllocation no_alloc;
14869
14870     int finger_index = cache->finger_index();
14871     Object* o = cache->get(finger_index);
14872     if (o == key) {
14873       // The fastest case: hit the same place again.
14874       return cache->get(finger_index + 1);
14875     }
14876
14877     for (int i = finger_index - 2;
14878          i >= JSFunctionResultCache::kEntriesIndex;
14879          i -= 2) {
14880       o = cache->get(i);
14881       if (o == key) {
14882         cache->set_finger_index(i);
14883         return cache->get(i + 1);
14884       }
14885     }
14886
14887     int size = cache->size();
14888     DCHECK(size <= cache->length());
14889
14890     for (int i = size - 2; i > finger_index; i -= 2) {
14891       o = cache->get(i);
14892       if (o == key) {
14893         cache->set_finger_index(i);
14894         return cache->get(i + 1);
14895       }
14896     }
14897   }
14898
14899   // There is no value in the cache.  Invoke the function and cache result.
14900   HandleScope scope(isolate);
14901
14902   Handle<JSFunctionResultCache> cache_handle(cache);
14903   Handle<Object> key_handle(key, isolate);
14904   Handle<Object> value;
14905   {
14906     Handle<JSFunction> factory(JSFunction::cast(
14907           cache_handle->get(JSFunctionResultCache::kFactoryIndex)));
14908     // TODO(antonm): consider passing a receiver when constructing a cache.
14909     Handle<JSObject> receiver(isolate->global_proxy());
14910     // This handle is nor shared, nor used later, so it's safe.
14911     Handle<Object> argv[] = { key_handle };
14912     ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
14913         isolate, value,
14914         Execution::Call(isolate, factory, receiver, arraysize(argv), argv));
14915   }
14916
14917 #ifdef VERIFY_HEAP
14918   if (FLAG_verify_heap) {
14919     cache_handle->JSFunctionResultCacheVerify();
14920   }
14921 #endif
14922
14923   // Function invocation may have cleared the cache.  Reread all the data.
14924   int finger_index = cache_handle->finger_index();
14925   int size = cache_handle->size();
14926
14927   // If we have spare room, put new data into it, otherwise evict post finger
14928   // entry which is likely to be the least recently used.
14929   int index = -1;
14930   if (size < cache_handle->length()) {
14931     cache_handle->set_size(size + JSFunctionResultCache::kEntrySize);
14932     index = size;
14933   } else {
14934     index = finger_index + JSFunctionResultCache::kEntrySize;
14935     if (index == cache_handle->length()) {
14936       index = JSFunctionResultCache::kEntriesIndex;
14937     }
14938   }
14939
14940   DCHECK(index % 2 == 0);
14941   DCHECK(index >= JSFunctionResultCache::kEntriesIndex);
14942   DCHECK(index < cache_handle->length());
14943
14944   cache_handle->set(index, *key_handle);
14945   cache_handle->set(index + 1, *value);
14946   cache_handle->set_finger_index(index);
14947
14948 #ifdef VERIFY_HEAP
14949   if (FLAG_verify_heap) {
14950     cache_handle->JSFunctionResultCacheVerify();
14951   }
14952 #endif
14953
14954   return *value;
14955 }
14956
14957
14958 RUNTIME_FUNCTION(Runtime_MessageGetStartPosition) {
14959   SealHandleScope shs(isolate);
14960   DCHECK(args.length() == 1);
14961   CONVERT_ARG_CHECKED(JSMessageObject, message, 0);
14962   return Smi::FromInt(message->start_position());
14963 }
14964
14965
14966 RUNTIME_FUNCTION(Runtime_MessageGetScript) {
14967   SealHandleScope shs(isolate);
14968   DCHECK(args.length() == 1);
14969   CONVERT_ARG_CHECKED(JSMessageObject, message, 0);
14970   return message->script();
14971 }
14972
14973
14974 #ifdef DEBUG
14975 // ListNatives is ONLY used by the fuzz-natives.js in debug mode
14976 // Exclude the code in release mode.
14977 RUNTIME_FUNCTION(Runtime_ListNatives) {
14978   HandleScope scope(isolate);
14979   DCHECK(args.length() == 0);
14980 #define COUNT_ENTRY(Name, argc, ressize) + 1
14981   int entry_count = 0
14982       RUNTIME_FUNCTION_LIST(COUNT_ENTRY)
14983       INLINE_FUNCTION_LIST(COUNT_ENTRY)
14984       INLINE_OPTIMIZED_FUNCTION_LIST(COUNT_ENTRY);
14985 #undef COUNT_ENTRY
14986   Factory* factory = isolate->factory();
14987   Handle<FixedArray> elements = factory->NewFixedArray(entry_count);
14988   int index = 0;
14989   bool inline_runtime_functions = false;
14990 #define ADD_ENTRY(Name, argc, ressize)                                      \
14991   {                                                                         \
14992     HandleScope inner(isolate);                                             \
14993     Handle<String> name;                                                    \
14994     /* Inline runtime functions have an underscore in front of the name. */ \
14995     if (inline_runtime_functions) {                                         \
14996       name = factory->NewStringFromStaticChars("_" #Name);                  \
14997     } else {                                                                \
14998       name = factory->NewStringFromStaticChars(#Name);                      \
14999     }                                                                       \
15000     Handle<FixedArray> pair_elements = factory->NewFixedArray(2);           \
15001     pair_elements->set(0, *name);                                           \
15002     pair_elements->set(1, Smi::FromInt(argc));                              \
15003     Handle<JSArray> pair = factory->NewJSArrayWithElements(pair_elements);  \
15004     elements->set(index++, *pair);                                          \
15005   }
15006   inline_runtime_functions = false;
15007   RUNTIME_FUNCTION_LIST(ADD_ENTRY)
15008   INLINE_OPTIMIZED_FUNCTION_LIST(ADD_ENTRY)
15009   inline_runtime_functions = true;
15010   INLINE_FUNCTION_LIST(ADD_ENTRY)
15011 #undef ADD_ENTRY
15012   DCHECK_EQ(index, entry_count);
15013   Handle<JSArray> result = factory->NewJSArrayWithElements(elements);
15014   return *result;
15015 }
15016 #endif
15017
15018
15019 RUNTIME_FUNCTION(Runtime_IS_VAR) {
15020   UNREACHABLE();  // implemented as macro in the parser
15021   return NULL;
15022 }
15023
15024
15025 #define ELEMENTS_KIND_CHECK_RUNTIME_FUNCTION(Name)        \
15026   RUNTIME_FUNCTION(Runtime_Has##Name) {          \
15027     CONVERT_ARG_CHECKED(JSObject, obj, 0);                \
15028     return isolate->heap()->ToBoolean(obj->Has##Name());  \
15029   }
15030
15031 ELEMENTS_KIND_CHECK_RUNTIME_FUNCTION(FastSmiElements)
15032 ELEMENTS_KIND_CHECK_RUNTIME_FUNCTION(FastObjectElements)
15033 ELEMENTS_KIND_CHECK_RUNTIME_FUNCTION(FastSmiOrObjectElements)
15034 ELEMENTS_KIND_CHECK_RUNTIME_FUNCTION(FastDoubleElements)
15035 ELEMENTS_KIND_CHECK_RUNTIME_FUNCTION(FastHoleyElements)
15036 ELEMENTS_KIND_CHECK_RUNTIME_FUNCTION(DictionaryElements)
15037 ELEMENTS_KIND_CHECK_RUNTIME_FUNCTION(SloppyArgumentsElements)
15038 ELEMENTS_KIND_CHECK_RUNTIME_FUNCTION(ExternalArrayElements)
15039 // Properties test sitting with elements tests - not fooling anyone.
15040 ELEMENTS_KIND_CHECK_RUNTIME_FUNCTION(FastProperties)
15041
15042 #undef ELEMENTS_KIND_CHECK_RUNTIME_FUNCTION
15043
15044
15045 #define TYPED_ARRAYS_CHECK_RUNTIME_FUNCTION(Type, type, TYPE, ctype, size)     \
15046   RUNTIME_FUNCTION(Runtime_HasExternal##Type##Elements) {             \
15047     CONVERT_ARG_CHECKED(JSObject, obj, 0);                                     \
15048     return isolate->heap()->ToBoolean(obj->HasExternal##Type##Elements());     \
15049   }
15050
15051 TYPED_ARRAYS(TYPED_ARRAYS_CHECK_RUNTIME_FUNCTION)
15052
15053 #undef TYPED_ARRAYS_CHECK_RUNTIME_FUNCTION
15054
15055
15056 #define FIXED_TYPED_ARRAYS_CHECK_RUNTIME_FUNCTION(Type, type, TYPE, ctype, s)  \
15057   RUNTIME_FUNCTION(Runtime_HasFixed##Type##Elements) {                \
15058     CONVERT_ARG_CHECKED(JSObject, obj, 0);                                     \
15059     return isolate->heap()->ToBoolean(obj->HasFixed##Type##Elements());        \
15060   }
15061
15062 TYPED_ARRAYS(FIXED_TYPED_ARRAYS_CHECK_RUNTIME_FUNCTION)
15063
15064 #undef FIXED_TYPED_ARRAYS_CHECK_RUNTIME_FUNCTION
15065
15066
15067 RUNTIME_FUNCTION(Runtime_HaveSameMap) {
15068   SealHandleScope shs(isolate);
15069   DCHECK(args.length() == 2);
15070   CONVERT_ARG_CHECKED(JSObject, obj1, 0);
15071   CONVERT_ARG_CHECKED(JSObject, obj2, 1);
15072   return isolate->heap()->ToBoolean(obj1->map() == obj2->map());
15073 }
15074
15075
15076 RUNTIME_FUNCTION(Runtime_IsJSGlobalProxy) {
15077   SealHandleScope shs(isolate);
15078   DCHECK(args.length() == 1);
15079   CONVERT_ARG_CHECKED(Object, obj, 0);
15080   return isolate->heap()->ToBoolean(obj->IsJSGlobalProxy());
15081 }
15082
15083
15084 RUNTIME_FUNCTION(Runtime_IsObserved) {
15085   SealHandleScope shs(isolate);
15086   DCHECK(args.length() == 1);
15087
15088   if (!args[0]->IsJSReceiver()) return isolate->heap()->false_value();
15089   CONVERT_ARG_CHECKED(JSReceiver, obj, 0);
15090   DCHECK(!obj->IsJSGlobalProxy() || !obj->map()->is_observed());
15091   return isolate->heap()->ToBoolean(obj->map()->is_observed());
15092 }
15093
15094
15095 RUNTIME_FUNCTION(Runtime_SetIsObserved) {
15096   HandleScope scope(isolate);
15097   DCHECK(args.length() == 1);
15098   CONVERT_ARG_HANDLE_CHECKED(JSReceiver, obj, 0);
15099   RUNTIME_ASSERT(!obj->IsJSGlobalProxy());
15100   if (obj->IsJSProxy()) return isolate->heap()->undefined_value();
15101   RUNTIME_ASSERT(!obj->map()->is_observed());
15102
15103   DCHECK(obj->IsJSObject());
15104   JSObject::SetObserved(Handle<JSObject>::cast(obj));
15105   return isolate->heap()->undefined_value();
15106 }
15107
15108
15109 RUNTIME_FUNCTION(Runtime_EnqueueMicrotask) {
15110   HandleScope scope(isolate);
15111   DCHECK(args.length() == 1);
15112   CONVERT_ARG_HANDLE_CHECKED(JSFunction, microtask, 0);
15113   isolate->EnqueueMicrotask(microtask);
15114   return isolate->heap()->undefined_value();
15115 }
15116
15117
15118 RUNTIME_FUNCTION(Runtime_RunMicrotasks) {
15119   HandleScope scope(isolate);
15120   DCHECK(args.length() == 0);
15121   isolate->RunMicrotasks();
15122   return isolate->heap()->undefined_value();
15123 }
15124
15125
15126 RUNTIME_FUNCTION(Runtime_GetObservationState) {
15127   SealHandleScope shs(isolate);
15128   DCHECK(args.length() == 0);
15129   return isolate->heap()->observation_state();
15130 }
15131
15132
15133 RUNTIME_FUNCTION(Runtime_ObservationWeakMapCreate) {
15134   HandleScope scope(isolate);
15135   DCHECK(args.length() == 0);
15136   // TODO(adamk): Currently this runtime function is only called three times per
15137   // isolate. If it's called more often, the map should be moved into the
15138   // strong root list.
15139   Handle<Map> map =
15140       isolate->factory()->NewMap(JS_WEAK_MAP_TYPE, JSWeakMap::kSize);
15141   Handle<JSWeakMap> weakmap =
15142       Handle<JSWeakMap>::cast(isolate->factory()->NewJSObjectFromMap(map));
15143   return *WeakCollectionInitialize(isolate, weakmap);
15144 }
15145
15146
15147 static bool ContextsHaveSameOrigin(Handle<Context> context1,
15148                                    Handle<Context> context2) {
15149   return context1->security_token() == context2->security_token();
15150 }
15151
15152
15153 RUNTIME_FUNCTION(Runtime_ObserverObjectAndRecordHaveSameOrigin) {
15154   HandleScope scope(isolate);
15155   DCHECK(args.length() == 3);
15156   CONVERT_ARG_HANDLE_CHECKED(JSFunction, observer, 0);
15157   CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 1);
15158   CONVERT_ARG_HANDLE_CHECKED(JSObject, record, 2);
15159
15160   Handle<Context> observer_context(observer->context()->native_context());
15161   Handle<Context> object_context(object->GetCreationContext());
15162   Handle<Context> record_context(record->GetCreationContext());
15163
15164   return isolate->heap()->ToBoolean(
15165       ContextsHaveSameOrigin(object_context, observer_context) &&
15166       ContextsHaveSameOrigin(object_context, record_context));
15167 }
15168
15169
15170 RUNTIME_FUNCTION(Runtime_ObjectWasCreatedInCurrentOrigin) {
15171   HandleScope scope(isolate);
15172   DCHECK(args.length() == 1);
15173   CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0);
15174
15175   Handle<Context> creation_context(object->GetCreationContext(), isolate);
15176   return isolate->heap()->ToBoolean(
15177       ContextsHaveSameOrigin(creation_context, isolate->native_context()));
15178 }
15179
15180
15181 RUNTIME_FUNCTION(Runtime_GetObjectContextObjectObserve) {
15182   HandleScope scope(isolate);
15183   DCHECK(args.length() == 1);
15184   CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0);
15185
15186   Handle<Context> context(object->GetCreationContext(), isolate);
15187   return context->native_object_observe();
15188 }
15189
15190
15191 RUNTIME_FUNCTION(Runtime_GetObjectContextObjectGetNotifier) {
15192   HandleScope scope(isolate);
15193   DCHECK(args.length() == 1);
15194   CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0);
15195
15196   Handle<Context> context(object->GetCreationContext(), isolate);
15197   return context->native_object_get_notifier();
15198 }
15199
15200
15201 RUNTIME_FUNCTION(Runtime_GetObjectContextNotifierPerformChange) {
15202   HandleScope scope(isolate);
15203   DCHECK(args.length() == 1);
15204   CONVERT_ARG_HANDLE_CHECKED(JSObject, object_info, 0);
15205
15206   Handle<Context> context(object_info->GetCreationContext(), isolate);
15207   return context->native_object_notifier_perform_change();
15208 }
15209
15210
15211 static Object* ArrayConstructorCommon(Isolate* isolate,
15212                                            Handle<JSFunction> constructor,
15213                                            Handle<AllocationSite> site,
15214                                            Arguments* caller_args) {
15215   Factory* factory = isolate->factory();
15216
15217   bool holey = false;
15218   bool can_use_type_feedback = true;
15219   if (caller_args->length() == 1) {
15220     Handle<Object> argument_one = caller_args->at<Object>(0);
15221     if (argument_one->IsSmi()) {
15222       int value = Handle<Smi>::cast(argument_one)->value();
15223       if (value < 0 || value >= JSObject::kInitialMaxFastElementArray) {
15224         // the array is a dictionary in this case.
15225         can_use_type_feedback = false;
15226       } else if (value != 0) {
15227         holey = true;
15228       }
15229     } else {
15230       // Non-smi length argument produces a dictionary
15231       can_use_type_feedback = false;
15232     }
15233   }
15234
15235   Handle<JSArray> array;
15236   if (!site.is_null() && can_use_type_feedback) {
15237     ElementsKind to_kind = site->GetElementsKind();
15238     if (holey && !IsFastHoleyElementsKind(to_kind)) {
15239       to_kind = GetHoleyElementsKind(to_kind);
15240       // Update the allocation site info to reflect the advice alteration.
15241       site->SetElementsKind(to_kind);
15242     }
15243
15244     // We should allocate with an initial map that reflects the allocation site
15245     // advice. Therefore we use AllocateJSObjectFromMap instead of passing
15246     // the constructor.
15247     Handle<Map> initial_map(constructor->initial_map(), isolate);
15248     if (to_kind != initial_map->elements_kind()) {
15249       initial_map = Map::AsElementsKind(initial_map, to_kind);
15250     }
15251
15252     // If we don't care to track arrays of to_kind ElementsKind, then
15253     // don't emit a memento for them.
15254     Handle<AllocationSite> allocation_site;
15255     if (AllocationSite::GetMode(to_kind) == TRACK_ALLOCATION_SITE) {
15256       allocation_site = site;
15257     }
15258
15259     array = Handle<JSArray>::cast(factory->NewJSObjectFromMap(
15260         initial_map, NOT_TENURED, true, allocation_site));
15261   } else {
15262     array = Handle<JSArray>::cast(factory->NewJSObject(constructor));
15263
15264     // We might need to transition to holey
15265     ElementsKind kind = constructor->initial_map()->elements_kind();
15266     if (holey && !IsFastHoleyElementsKind(kind)) {
15267       kind = GetHoleyElementsKind(kind);
15268       JSObject::TransitionElementsKind(array, kind);
15269     }
15270   }
15271
15272   factory->NewJSArrayStorage(array, 0, 0, DONT_INITIALIZE_ARRAY_ELEMENTS);
15273
15274   ElementsKind old_kind = array->GetElementsKind();
15275   RETURN_FAILURE_ON_EXCEPTION(
15276       isolate, ArrayConstructInitializeElements(array, caller_args));
15277   if (!site.is_null() &&
15278       (old_kind != array->GetElementsKind() ||
15279        !can_use_type_feedback)) {
15280     // The arguments passed in caused a transition. This kind of complexity
15281     // can't be dealt with in the inlined hydrogen array constructor case.
15282     // We must mark the allocationsite as un-inlinable.
15283     site->SetDoNotInlineCall();
15284   }
15285   return *array;
15286 }
15287
15288
15289 RUNTIME_FUNCTION(Runtime_ArrayConstructor) {
15290   HandleScope scope(isolate);
15291   // If we get 2 arguments then they are the stub parameters (constructor, type
15292   // info).  If we get 4, then the first one is a pointer to the arguments
15293   // passed by the caller, and the last one is the length of the arguments
15294   // passed to the caller (redundant, but useful to check on the deoptimizer
15295   // with an assert).
15296   Arguments empty_args(0, NULL);
15297   bool no_caller_args = args.length() == 2;
15298   DCHECK(no_caller_args || args.length() == 4);
15299   int parameters_start = no_caller_args ? 0 : 1;
15300   Arguments* caller_args = no_caller_args
15301       ? &empty_args
15302       : reinterpret_cast<Arguments*>(args[0]);
15303   CONVERT_ARG_HANDLE_CHECKED(JSFunction, constructor, parameters_start);
15304   CONVERT_ARG_HANDLE_CHECKED(Object, type_info, parameters_start + 1);
15305 #ifdef DEBUG
15306   if (!no_caller_args) {
15307     CONVERT_SMI_ARG_CHECKED(arg_count, parameters_start + 2);
15308     DCHECK(arg_count == caller_args->length());
15309   }
15310 #endif
15311
15312   Handle<AllocationSite> site;
15313   if (!type_info.is_null() &&
15314       *type_info != isolate->heap()->undefined_value()) {
15315     site = Handle<AllocationSite>::cast(type_info);
15316     DCHECK(!site->SitePointsToLiteral());
15317   }
15318
15319   return ArrayConstructorCommon(isolate,
15320                                 constructor,
15321                                 site,
15322                                 caller_args);
15323 }
15324
15325
15326 RUNTIME_FUNCTION(Runtime_InternalArrayConstructor) {
15327   HandleScope scope(isolate);
15328   Arguments empty_args(0, NULL);
15329   bool no_caller_args = args.length() == 1;
15330   DCHECK(no_caller_args || args.length() == 3);
15331   int parameters_start = no_caller_args ? 0 : 1;
15332   Arguments* caller_args = no_caller_args
15333       ? &empty_args
15334       : reinterpret_cast<Arguments*>(args[0]);
15335   CONVERT_ARG_HANDLE_CHECKED(JSFunction, constructor, parameters_start);
15336 #ifdef DEBUG
15337   if (!no_caller_args) {
15338     CONVERT_SMI_ARG_CHECKED(arg_count, parameters_start + 1);
15339     DCHECK(arg_count == caller_args->length());
15340   }
15341 #endif
15342   return ArrayConstructorCommon(isolate,
15343                                 constructor,
15344                                 Handle<AllocationSite>::null(),
15345                                 caller_args);
15346 }
15347
15348
15349 RUNTIME_FUNCTION(Runtime_NormalizeElements) {
15350   HandleScope scope(isolate);
15351   DCHECK(args.length() == 1);
15352   CONVERT_ARG_HANDLE_CHECKED(JSObject, array, 0);
15353   RUNTIME_ASSERT(!array->HasExternalArrayElements() &&
15354                  !array->HasFixedTypedArrayElements());
15355   JSObject::NormalizeElements(array);
15356   return *array;
15357 }
15358
15359
15360 RUNTIME_FUNCTION(Runtime_MaxSmi) {
15361   SealHandleScope shs(isolate);
15362   DCHECK(args.length() == 0);
15363   return Smi::FromInt(Smi::kMaxValue);
15364 }
15365
15366
15367 // TODO(dcarney): remove this function when TurboFan supports it.
15368 // Takes the object to be iterated over and the result of GetPropertyNamesFast
15369 // Returns pair (cache_array, cache_type).
15370 RUNTIME_FUNCTION_RETURN_PAIR(Runtime_ForInInit) {
15371   SealHandleScope scope(isolate);
15372   DCHECK(args.length() == 2);
15373   // This simulates CONVERT_ARG_HANDLE_CHECKED for calls returning pairs.
15374   // Not worth creating a macro atm as this function should be removed.
15375   if (!args[0]->IsJSReceiver() || !args[1]->IsObject()) {
15376     Object* error = isolate->ThrowIllegalOperation();
15377     return MakePair(error, isolate->heap()->undefined_value());
15378   }
15379   Handle<JSReceiver> object = args.at<JSReceiver>(0);
15380   Handle<Object> cache_type = args.at<Object>(1);
15381   if (cache_type->IsMap()) {
15382     // Enum cache case.
15383     if (Map::EnumLengthBits::decode(Map::cast(*cache_type)->bit_field3()) ==
15384         0) {
15385       // 0 length enum.
15386       // Can't handle this case in the graph builder,
15387       // so transform it into the empty fixed array case.
15388       return MakePair(isolate->heap()->empty_fixed_array(), Smi::FromInt(1));
15389     }
15390     return MakePair(object->map()->instance_descriptors()->GetEnumCache(),
15391                     *cache_type);
15392   } else {
15393     // FixedArray case.
15394     Smi* new_cache_type = Smi::FromInt(object->IsJSProxy() ? 0 : 1);
15395     return MakePair(*Handle<FixedArray>::cast(cache_type), new_cache_type);
15396   }
15397 }
15398
15399
15400 // TODO(dcarney): remove this function when TurboFan supports it.
15401 RUNTIME_FUNCTION(Runtime_ForInCacheArrayLength) {
15402   SealHandleScope shs(isolate);
15403   DCHECK(args.length() == 2);
15404   CONVERT_ARG_HANDLE_CHECKED(Object, cache_type, 0);
15405   CONVERT_ARG_HANDLE_CHECKED(FixedArray, array, 1);
15406   int length = 0;
15407   if (cache_type->IsMap()) {
15408     length = Map::cast(*cache_type)->EnumLength();
15409   } else {
15410     DCHECK(cache_type->IsSmi());
15411     length = array->length();
15412   }
15413   return Smi::FromInt(length);
15414 }
15415
15416
15417 // TODO(dcarney): remove this function when TurboFan supports it.
15418 // Takes (the object to be iterated over,
15419 //        cache_array from ForInInit,
15420 //        cache_type from ForInInit,
15421 //        the current index)
15422 // Returns pair (array[index], needs_filtering).
15423 RUNTIME_FUNCTION_RETURN_PAIR(Runtime_ForInNext) {
15424   SealHandleScope scope(isolate);
15425   DCHECK(args.length() == 4);
15426   int32_t index;
15427   // This simulates CONVERT_ARG_HANDLE_CHECKED for calls returning pairs.
15428   // Not worth creating a macro atm as this function should be removed.
15429   if (!args[0]->IsJSReceiver() || !args[1]->IsFixedArray() ||
15430       !args[2]->IsObject() || !args[3]->ToInt32(&index)) {
15431     Object* error = isolate->ThrowIllegalOperation();
15432     return MakePair(error, isolate->heap()->undefined_value());
15433   }
15434   Handle<JSReceiver> object = args.at<JSReceiver>(0);
15435   Handle<FixedArray> array = args.at<FixedArray>(1);
15436   Handle<Object> cache_type = args.at<Object>(2);
15437   // Figure out first if a slow check is needed for this object.
15438   bool slow_check_needed = false;
15439   if (cache_type->IsMap()) {
15440     if (object->map() != Map::cast(*cache_type)) {
15441       // Object transitioned.  Need slow check.
15442       slow_check_needed = true;
15443     }
15444   } else {
15445     // No slow check needed for proxies.
15446     slow_check_needed = Smi::cast(*cache_type)->value() == 1;
15447   }
15448   return MakePair(array->get(index),
15449                   isolate->heap()->ToBoolean(slow_check_needed));
15450 }
15451
15452
15453 template<typename T, int Bytes>
15454 inline static bool SimdTypeLoadValue(
15455     Isolate* isolate,
15456     Handle<JSArrayBuffer> buffer,
15457     Handle<Object> byte_offset_obj,
15458     T* result) {
15459   size_t byte_offset = 0;
15460   if (!TryNumberToSize(isolate, *byte_offset_obj, &byte_offset)) {
15461     return false;
15462   }
15463
15464   size_t buffer_byte_length =
15465       NumberToSize(isolate, buffer->byte_length());
15466   if (byte_offset + Bytes > buffer_byte_length)  {  // overflow
15467     return false;
15468   }
15469
15470   union Value {
15471     T data;
15472     uint8_t bytes[sizeof(T)];
15473   };
15474
15475   Value value;
15476   memset(value.bytes, 0, sizeof(T));
15477   uint8_t* source =
15478       static_cast<uint8_t*>(buffer->backing_store()) + byte_offset;
15479   DCHECK(Bytes <= sizeof(T));
15480   CopyBytes<Bytes>(value.bytes, source);
15481   *result = value.data;
15482   return true;
15483 }
15484
15485
15486 template<typename T, int Bytes>
15487 static bool SimdTypeStoreValue(
15488     Isolate* isolate,
15489     Handle<JSArrayBuffer> buffer,
15490     Handle<Object> byte_offset_obj,
15491     T data) {
15492   size_t byte_offset = 0;
15493   if (!TryNumberToSize(isolate, *byte_offset_obj, &byte_offset)) {
15494     return false;
15495   }
15496
15497   size_t buffer_byte_length =
15498       NumberToSize(isolate, buffer->byte_length());
15499   if (byte_offset + Bytes > buffer_byte_length)  {  // overflow
15500     return false;
15501   }
15502
15503   union Value {
15504     T data;
15505     uint8_t bytes[sizeof(T)];
15506   };
15507
15508   Value value;
15509   value.data = data;
15510
15511   uint8_t* target =
15512       static_cast<uint8_t*>(buffer->backing_store()) + byte_offset;
15513   DCHECK(Bytes <= sizeof(T));
15514   CopyBytes<Bytes>(target, value.bytes);
15515   return true;
15516 }
15517
15518
15519 #define SIMD128_LOAD_RUNTIME_FUNCTION(Type, ValueType, Lanes, Bytes)   \
15520 RUNTIME_FUNCTION(Runtime_##Type##Load##Lanes) {                        \
15521   HandleScope scope(isolate);                                          \
15522   DCHECK(args.length() == 2);                                          \
15523   CONVERT_ARG_HANDLE_CHECKED(JSArrayBuffer, buffer, 0);                \
15524   CONVERT_NUMBER_ARG_HANDLE_CHECKED(offset, 1);                        \
15525   ValueType result;                                                    \
15526   if (SimdTypeLoadValue<ValueType, Bytes>(                             \
15527           isolate, buffer, offset, &result)) {                         \
15528     return *isolate->factory()->New##Type(result);                     \
15529   } else {                                                             \
15530     THROW_NEW_ERROR_RETURN_FAILURE(                                    \
15531         isolate, NewRangeError("invalid_offset",                       \
15532         HandleVector<Object>(NULL, 0)));                               \
15533   }                                                                    \
15534 }
15535
15536
15537 SIMD128_LOAD_RUNTIME_FUNCTION(Float32x4, float32x4_value_t, XYZW, 16)
15538 SIMD128_LOAD_RUNTIME_FUNCTION(Float32x4, float32x4_value_t, XYZ, 12)
15539 SIMD128_LOAD_RUNTIME_FUNCTION(Float32x4, float32x4_value_t, XY, 8)
15540 SIMD128_LOAD_RUNTIME_FUNCTION(Float32x4, float32x4_value_t, X, 4)
15541 SIMD128_LOAD_RUNTIME_FUNCTION(Float64x2, float64x2_value_t, XY, 16)
15542 SIMD128_LOAD_RUNTIME_FUNCTION(Float64x2, float64x2_value_t, X, 8)
15543 SIMD128_LOAD_RUNTIME_FUNCTION(Int32x4, int32x4_value_t, XYZW, 16)
15544 SIMD128_LOAD_RUNTIME_FUNCTION(Int32x4, int32x4_value_t, XYZ, 12)
15545 SIMD128_LOAD_RUNTIME_FUNCTION(Int32x4, int32x4_value_t, XY, 8)
15546 SIMD128_LOAD_RUNTIME_FUNCTION(Int32x4, int32x4_value_t, X, 4)
15547
15548
15549 #define SIMD128_STORE_RUNTIME_FUNCTION(Type, ValueType, Lanes, Bytes)       \
15550 RUNTIME_FUNCTION(Runtime_##Type##Store##Lanes) {                            \
15551   HandleScope scope(isolate);                                               \
15552   DCHECK(args.length() == 3);                                               \
15553   CONVERT_ARG_HANDLE_CHECKED(JSArrayBuffer, buffer, 0);                     \
15554   CONVERT_NUMBER_ARG_HANDLE_CHECKED(offset, 1);                             \
15555   CONVERT_ARG_CHECKED(Type, value, 2);                                      \
15556   ValueType v = value->get();                                               \
15557   if (SimdTypeStoreValue<ValueType, Bytes>(isolate, buffer, offset, v)) {   \
15558     return isolate->heap()->undefined_value();                              \
15559   } else {                                                                  \
15560     THROW_NEW_ERROR_RETURN_FAILURE(                                         \
15561       isolate, NewRangeError("invalid_offset",                              \
15562       HandleVector<Object>(NULL, 0)));                                      \
15563   }                                                                         \
15564 }
15565
15566
15567 SIMD128_STORE_RUNTIME_FUNCTION(Float32x4, float32x4_value_t, XYZW, 16)
15568 SIMD128_STORE_RUNTIME_FUNCTION(Float32x4, float32x4_value_t, XYZ, 12)
15569 SIMD128_STORE_RUNTIME_FUNCTION(Float32x4, float32x4_value_t, XY, 8)
15570 SIMD128_STORE_RUNTIME_FUNCTION(Float32x4, float32x4_value_t, X, 4)
15571 SIMD128_STORE_RUNTIME_FUNCTION(Float64x2, float64x2_value_t, XY, 16)
15572 SIMD128_STORE_RUNTIME_FUNCTION(Float64x2, float64x2_value_t, X, 8)
15573 SIMD128_STORE_RUNTIME_FUNCTION(Int32x4, int32x4_value_t, XYZW, 16)
15574 SIMD128_STORE_RUNTIME_FUNCTION(Int32x4, int32x4_value_t, XYZ, 12)
15575 SIMD128_STORE_RUNTIME_FUNCTION(Int32x4, int32x4_value_t, XY, 8)
15576 SIMD128_STORE_RUNTIME_FUNCTION(Int32x4, int32x4_value_t, X, 4)
15577
15578
15579 #define RETURN_Float32x4_RESULT(value)                                         \
15580   return *isolate->factory()->NewFloat32x4(value);
15581
15582
15583 #define RETURN_Float64x2_RESULT(value)                                         \
15584   return *isolate->factory()->NewFloat64x2(value);
15585
15586
15587 #define RETURN_Int32x4_RESULT(value)                                           \
15588   return *isolate->factory()->NewInt32x4(value);
15589
15590
15591 RUNTIME_FUNCTION(Runtime_CreateFloat32x4) {
15592   HandleScope scope(isolate);
15593   DCHECK(args.length() == 4);
15594   RUNTIME_ASSERT(args[0]->IsNumber());
15595   RUNTIME_ASSERT(args[1]->IsNumber());
15596   RUNTIME_ASSERT(args[2]->IsNumber());
15597   RUNTIME_ASSERT(args[3]->IsNumber());
15598
15599   float32x4_value_t value;
15600   value.storage[0] = static_cast<float>(args.number_at(0));
15601   value.storage[1] = static_cast<float>(args.number_at(1));
15602   value.storage[2] = static_cast<float>(args.number_at(2));
15603   value.storage[3] = static_cast<float>(args.number_at(3));
15604
15605   RETURN_Float32x4_RESULT(value);
15606 }
15607
15608
15609 RUNTIME_FUNCTION(Runtime_CreateFloat64x2) {
15610   HandleScope scope(isolate);
15611   DCHECK(args.length() == 2);
15612   RUNTIME_ASSERT(args[0]->IsNumber());
15613   RUNTIME_ASSERT(args[1]->IsNumber());
15614
15615   float64x2_value_t value;
15616   value.storage[0] = args.number_at(0);
15617   value.storage[1] = args.number_at(1);
15618
15619   RETURN_Float64x2_RESULT(value);
15620 }
15621
15622
15623 RUNTIME_FUNCTION(Runtime_CreateInt32x4) {
15624   HandleScope scope(isolate);
15625   DCHECK(args.length() == 4);
15626   RUNTIME_ASSERT(args[0]->IsNumber());
15627   RUNTIME_ASSERT(args[1]->IsNumber());
15628   RUNTIME_ASSERT(args[2]->IsNumber());
15629   RUNTIME_ASSERT(args[3]->IsNumber());
15630
15631   int32x4_value_t value;
15632   value.storage[0] = NumberToInt32(args[0]);
15633   value.storage[1] = NumberToInt32(args[1]);
15634   value.storage[2] = NumberToInt32(args[2]);
15635   value.storage[3] = NumberToInt32(args[3]);
15636
15637   RETURN_Int32x4_RESULT(value);
15638 }
15639
15640
15641 // Used to convert between uint32_t and float32 without breaking strict
15642 // aliasing rules.
15643 union float32_uint32 {
15644   float f;
15645   uint32_t u;
15646   float32_uint32(float v) {
15647     f = v;
15648   }
15649   float32_uint32(uint32_t v) {
15650     u = v;
15651   }
15652 };
15653
15654
15655 union float64_uint64 {
15656   double f;
15657   uint64_t u;
15658   float64_uint64(double v) {
15659     f = v;
15660   }
15661   float64_uint64(uint64_t v) {
15662     u = v;
15663   }
15664 };
15665
15666
15667 RUNTIME_FUNCTION(Runtime_Float32x4GetSignMask) {
15668   HandleScope scope(isolate);
15669   DCHECK(args.length() == 1);
15670   CONVERT_ARG_CHECKED(Float32x4, self, 0);
15671   float32_uint32 x(self->x());
15672   float32_uint32 y(self->y());
15673   float32_uint32 z(self->z());
15674   float32_uint32 w(self->w());
15675   uint32_t mx = (x.u & 0x80000000) >> 31;
15676   uint32_t my = (y.u & 0x80000000) >> 31;
15677   uint32_t mz = (z.u & 0x80000000) >> 31;
15678   uint32_t mw = (w.u & 0x80000000) >> 31;
15679   uint32_t value = mx | (my << 1) | (mz << 2) | (mw << 3);
15680   return *isolate->factory()->NewNumberFromUint(value);
15681 }
15682
15683
15684 RUNTIME_FUNCTION(Runtime_Float64x2GetSignMask) {
15685   HandleScope scope(isolate);
15686   DCHECK(args.length() == 1);
15687   CONVERT_ARG_CHECKED(Float64x2, self, 0);
15688   float64_uint64 x(self->x());
15689   float64_uint64 y(self->y());
15690   uint64_t mx = x.u >> 63;
15691   uint64_t my = y.u >> 63;
15692   uint32_t value = uint32_t(mx | (my << 1));
15693   return *isolate->factory()->NewNumberFromUint(value);
15694 }
15695
15696
15697 RUNTIME_FUNCTION(Runtime_Int32x4GetSignMask) {
15698   HandleScope scope(isolate);
15699   DCHECK(args.length() == 1);
15700   CONVERT_ARG_CHECKED(Int32x4, self, 0);
15701   uint32_t mx = (self->x() & 0x80000000) >> 31;
15702   uint32_t my = (self->y() & 0x80000000) >> 31;
15703   uint32_t mz = (self->z() & 0x80000000) >> 31;
15704   uint32_t mw = (self->w() & 0x80000000) >> 31;
15705   uint32_t value = mx | (my << 1) | (mz << 2) | (mw << 3);
15706   return *isolate->factory()->NewNumberFromUint(value);
15707 }
15708
15709
15710 #define LANE_VALUE(VALUE, LANE) \
15711   VALUE->LANE()
15712
15713
15714 #define LANE_FLAG(VALUE, LANE)  \
15715   VALUE->LANE() != 0
15716
15717
15718 #define SIMD128_LANE_ACCESS_FUNCTIONS(V)                      \
15719   V(Float32x4, GetX, NewNumber, x, LANE_VALUE)       \
15720   V(Float32x4, GetY, NewNumber, y, LANE_VALUE)       \
15721   V(Float32x4, GetZ, NewNumber, z, LANE_VALUE)       \
15722   V(Float32x4, GetW, NewNumber, w, LANE_VALUE)       \
15723   V(Float64x2, GetX, NewNumber, x, LANE_VALUE)       \
15724   V(Float64x2, GetY, NewNumber, y, LANE_VALUE)       \
15725   V(Int32x4, GetX, NewNumberFromInt, x, LANE_VALUE)            \
15726   V(Int32x4, GetY, NewNumberFromInt, y, LANE_VALUE)            \
15727   V(Int32x4, GetZ, NewNumberFromInt, z, LANE_VALUE)            \
15728   V(Int32x4, GetW, NewNumberFromInt, w, LANE_VALUE)            \
15729   V(Int32x4, GetFlagX, ToBoolean, x, LANE_FLAG)               \
15730   V(Int32x4, GetFlagY, ToBoolean, y, LANE_FLAG)               \
15731   V(Int32x4, GetFlagZ, ToBoolean, z, LANE_FLAG)               \
15732   V(Int32x4, GetFlagW, ToBoolean, w, LANE_FLAG)
15733
15734
15735 #define DECLARE_SIMD_LANE_ACCESS_FUNCTION(                    \
15736     TYPE, NAME, HEAP_FUNCTION, LANE, ACCESS_FUNCTION)         \
15737 RUNTIME_FUNCTION(Runtime_##TYPE##NAME) {        \
15738   HandleScope scope(isolate);                                 \
15739   DCHECK(args.length() == 1);                                 \
15740                                                               \
15741   CONVERT_ARG_CHECKED(TYPE, a, 0);                            \
15742                                                               \
15743   return *isolate->factory()->HEAP_FUNCTION(                  \
15744       ACCESS_FUNCTION(a, LANE));                              \
15745 }
15746
15747
15748 SIMD128_LANE_ACCESS_FUNCTIONS(DECLARE_SIMD_LANE_ACCESS_FUNCTION)
15749
15750
15751 template<typename T>
15752 static inline T Neg(T a) {
15753   return -a;
15754 }
15755
15756
15757 template<typename T>
15758 static inline T Not(T a) {
15759   return ~a;
15760 }
15761
15762
15763 template<typename T>
15764 static inline T Reciprocal(T a) {
15765   UNIMPLEMENTED();
15766 }
15767
15768
15769 template<>
15770 inline float Reciprocal<float>(float a) {
15771   return 1.0f / a;
15772 }
15773
15774
15775 template<typename T>
15776 static inline T ReciprocalSqrt(T a) {
15777   UNIMPLEMENTED();
15778 }
15779
15780
15781 template<>
15782 inline float ReciprocalSqrt<float>(float a) {
15783   return sqrtf(1.0f / a);
15784 }
15785
15786
15787 template<typename T>
15788 static inline T Sqrt(T a) {
15789   UNIMPLEMENTED();
15790 }
15791
15792
15793 template<>
15794 inline float Sqrt<float>(float a) {
15795   return sqrtf(a);
15796 }
15797
15798
15799 template<>
15800 inline double Sqrt<double>(double a) {
15801   return sqrt(a);
15802 }
15803
15804
15805 #define SIMD128_UNARY_FUNCTIONS(V)                            \
15806   V(Float32x4, Abs)                                           \
15807   V(Float32x4, Neg)                                           \
15808   V(Float32x4, Reciprocal)                                    \
15809   V(Float32x4, ReciprocalSqrt)                                \
15810   V(Float32x4, Sqrt)                                          \
15811   V(Float64x2, Abs)                                           \
15812   V(Float64x2, Neg)                                           \
15813   V(Float64x2, Sqrt)                                          \
15814   V(Int32x4, Neg)                                             \
15815   V(Int32x4, Not)
15816
15817
15818 #define DECLARE_SIMD_UNARY_FUNCTION(TYPE, FUNCTION)           \
15819 RUNTIME_FUNCTION(Runtime_##TYPE##FUNCTION) {    \
15820   HandleScope scope(isolate);                                 \
15821   DCHECK(args.length() == 1);                                 \
15822                                                               \
15823   CONVERT_ARG_CHECKED(TYPE, a, 0);                            \
15824                                                               \
15825   TYPE::value_t result;                                       \
15826   for (int i = 0; i < TYPE::kLanes; i++) {                    \
15827     result.storage[i] = FUNCTION(a->getAt(i));                \
15828   }                                                           \
15829                                                               \
15830   RETURN_##TYPE##_RESULT(result);                             \
15831 }
15832
15833
15834 SIMD128_UNARY_FUNCTIONS(DECLARE_SIMD_UNARY_FUNCTION)
15835
15836
15837 template<typename T1, typename T2>
15838 inline void BitsTo(T1 s, T2* t) {
15839   memcpy(t, &s, sizeof(T2));
15840 }
15841
15842
15843 template<typename T1, typename T2>
15844 inline void To(T1 s, T2* t) {
15845 }
15846
15847
15848 template<>
15849 inline void To<int32_t, float>(int32_t s, float* t) {
15850   *t = static_cast<float>(s);
15851 }
15852
15853
15854 template<>
15855 inline void To<float, int32_t>(float s, int32_t* t) {
15856   *t = DoubleToInt32(static_cast<double>(s));
15857 }
15858
15859
15860 #define SIMD128_CONVERSION_FUNCTIONS(V)                       \
15861   V(Float32x4, BitsTo, Int32x4)                               \
15862   V(Float32x4, To, Int32x4)                                   \
15863   V(Int32x4, BitsTo, Float32x4)                               \
15864   V(Int32x4, To, Float32x4)
15865
15866
15867 #define DECLARE_SIMD_CONVERSION_FUNCTION(                     \
15868     SOURCE_TYPE, FUNCTION, TARGET_TYPE)                       \
15869 RUNTIME_FUNCTION(                               \
15870     Runtime_##SOURCE_TYPE##FUNCTION##TARGET_TYPE) {           \
15871   HandleScope scope(isolate);                                 \
15872   DCHECK(args.length() == 1);                                 \
15873                                                               \
15874   CONVERT_ARG_CHECKED(SOURCE_TYPE, a, 0);                     \
15875                                                               \
15876   TARGET_TYPE::value_t result;                                \
15877   for (int i = 0; i < SOURCE_TYPE::kLanes; i++) {             \
15878     FUNCTION(a->getAt(i), &result.storage[i]);                \
15879   }                                                           \
15880                                                               \
15881   RETURN_##TARGET_TYPE##_RESULT(result);                      \
15882 }
15883
15884
15885 SIMD128_CONVERSION_FUNCTIONS(DECLARE_SIMD_CONVERSION_FUNCTION)
15886
15887
15888 template<typename T>
15889 static inline T Add(T a, T b) {
15890   return a + b;
15891 }
15892
15893
15894 template<typename T>
15895 static inline T Div(T a, T b) {
15896   return a / b;
15897 }
15898
15899
15900 template<typename T>
15901 static inline T Mul(T a, T b) {
15902   return a * b;
15903 }
15904
15905
15906 template<typename T>
15907 static inline T Sub(T a, T b) {
15908   return a - b;
15909 }
15910
15911
15912 template<typename T>
15913 static inline int32_t Equal(T a, T b) {
15914   return a == b ? -1 : 0;
15915 }
15916
15917
15918 template<typename T>
15919 static inline int32_t NotEqual(T a, T b) {
15920   return a != b ? -1 : 0;
15921 }
15922
15923
15924 template<typename T>
15925 static inline int32_t GreaterThanOrEqual(T a, T b) {
15926   return a >= b ? -1 : 0;
15927 }
15928
15929
15930 template<typename T>
15931 static inline int32_t GreaterThan(T a, T b) {
15932   return a > b ? -1 : 0;
15933 }
15934
15935
15936 template<typename T>
15937 static inline int32_t LessThan(T a, T b) {
15938   return a < b ? -1 : 0;
15939 }
15940
15941
15942 template<typename T>
15943 static inline int32_t LessThanOrEqual(T a, T b) {
15944   return a <= b ? -1 : 0;
15945 }
15946
15947
15948 template<typename T>
15949 static inline T And(T a, T b) {
15950   return a & b;
15951 }
15952
15953
15954 template<typename T>
15955 static inline T Or(T a, T b) {
15956   return a | b;
15957 }
15958
15959
15960 template<typename T>
15961 static inline T Xor(T a, T b) {
15962   return a ^ b;
15963 }
15964
15965
15966 #define SIMD128_BINARY_FUNCTIONS(V)                           \
15967   V(Float32x4, Add, Float32x4)                                \
15968   V(Float32x4, Div, Float32x4)                                \
15969   V(Float32x4, Max, Float32x4)                                \
15970   V(Float32x4, Min, Float32x4)                                \
15971   V(Float32x4, Mul, Float32x4)                                \
15972   V(Float32x4, Sub, Float32x4)                                \
15973   V(Float32x4, Equal, Int32x4)                                \
15974   V(Float32x4, NotEqual, Int32x4)                             \
15975   V(Float32x4, GreaterThanOrEqual, Int32x4)                   \
15976   V(Float32x4, GreaterThan, Int32x4)                          \
15977   V(Float32x4, LessThan, Int32x4)                             \
15978   V(Float32x4, LessThanOrEqual, Int32x4)                      \
15979   V(Float64x2, Add, Float64x2)                                \
15980   V(Float64x2, Div, Float64x2)                                \
15981   V(Float64x2, Max, Float64x2)                                \
15982   V(Float64x2, Min, Float64x2)                                \
15983   V(Float64x2, Mul, Float64x2)                                \
15984   V(Float64x2, Sub, Float64x2)                                \
15985   V(Int32x4, Add, Int32x4)                                    \
15986   V(Int32x4, And, Int32x4)                                    \
15987   V(Int32x4, Mul, Int32x4)                                    \
15988   V(Int32x4, Or, Int32x4)                                     \
15989   V(Int32x4, Sub, Int32x4)                                    \
15990   V(Int32x4, Xor, Int32x4)                                    \
15991   V(Int32x4, Equal, Int32x4)                                  \
15992   V(Int32x4, GreaterThan, Int32x4)                            \
15993   V(Int32x4, LessThan, Int32x4)
15994
15995
15996 #define DECLARE_SIMD_BINARY_FUNCTION(                         \
15997     TYPE, FUNCTION, RETURN_TYPE)                              \
15998 RUNTIME_FUNCTION(Runtime_##TYPE##FUNCTION) {    \
15999   HandleScope scope(isolate);                                 \
16000   DCHECK(args.length() == 2);                                 \
16001                                                               \
16002   CONVERT_ARG_CHECKED(TYPE, a, 0);                            \
16003   CONVERT_ARG_CHECKED(TYPE, b, 1);                            \
16004                                                               \
16005   RETURN_TYPE::value_t result;                                \
16006   for (int i = 0; i < TYPE::kLanes; i++) {                    \
16007     result.storage[i] = FUNCTION(a->getAt(i), b->getAt(i));   \
16008   }                                                           \
16009                                                               \
16010   RETURN_##RETURN_TYPE##_RESULT(result);                      \
16011 }
16012
16013
16014 SIMD128_BINARY_FUNCTIONS(DECLARE_SIMD_BINARY_FUNCTION)
16015
16016
16017 #define SIMD128_SHUFFLE_FUNCTIONS(V)                          \
16018   V(Float32x4)                                                \
16019   V(Int32x4)
16020
16021
16022 #define DECLARE_SIMD_SHUFFLE_FUNCTION(TYPE)                   \
16023 RUNTIME_FUNCTION(Runtime_##TYPE##Shuffle) {     \
16024   HandleScope scope(isolate);                                 \
16025   DCHECK(args.length() == 2);                                 \
16026                                                               \
16027   CONVERT_ARG_CHECKED(TYPE, a, 0);                            \
16028   RUNTIME_ASSERT(args[1]->IsNumber());                        \
16029   uint32_t m = NumberToUint32(args[1]);                       \
16030                                                               \
16031   TYPE::value_t result;                                       \
16032   for (int i = 0; i < TYPE::kLanes; i++) {                    \
16033     result.storage[i] = a->getAt((m >> (i * 2)) & 0x3);       \
16034   }                                                           \
16035                                                               \
16036   RETURN_##TYPE##_RESULT(result);                             \
16037 }
16038
16039
16040 SIMD128_SHUFFLE_FUNCTIONS(DECLARE_SIMD_SHUFFLE_FUNCTION)
16041
16042
16043 RUNTIME_FUNCTION(Runtime_Float32x4Scale) {
16044   HandleScope scope(isolate);
16045   DCHECK(args.length() == 2);
16046
16047   CONVERT_ARG_CHECKED(Float32x4, self, 0);
16048   RUNTIME_ASSERT(args[1]->IsNumber());
16049
16050   float _s = static_cast<float>(args.number_at(1));
16051   float32x4_value_t result;
16052   result.storage[0] = self->x() * _s;
16053   result.storage[1] = self->y() * _s;
16054   result.storage[2] = self->z() * _s;
16055   result.storage[3] = self->w() * _s;
16056
16057   RETURN_Float32x4_RESULT(result);
16058 }
16059
16060
16061 RUNTIME_FUNCTION(Runtime_Float64x2Scale) {
16062   HandleScope scope(isolate);
16063   DCHECK(args.length() == 2);
16064
16065   CONVERT_ARG_CHECKED(Float64x2, self, 0);
16066   RUNTIME_ASSERT(args[1]->IsNumber());
16067
16068   double _s = args.number_at(1);
16069   float64x2_value_t result;
16070   result.storage[0] = self->x() * _s;
16071   result.storage[1] = self->y() * _s;
16072
16073   RETURN_Float64x2_RESULT(result);
16074 }
16075
16076
16077 #define ARG_TO_FLOAT32(x) \
16078   CONVERT_DOUBLE_ARG_CHECKED(t, 1); \
16079   float x = static_cast<float>(t);
16080
16081
16082 #define ARG_TO_FLOAT64(x) \
16083   CONVERT_DOUBLE_ARG_CHECKED(x, 1); \
16084
16085
16086 #define ARG_TO_INT32(x) \
16087   RUNTIME_ASSERT(args[1]->IsNumber()); \
16088   int32_t x = NumberToInt32(args[1]);
16089
16090
16091 #define ARG_TO_BOOLEAN(x) \
16092   CONVERT_BOOLEAN_ARG_CHECKED(flag, 1); \
16093   int32_t x = flag ? -1 : 0;
16094
16095 #define SIMD128_SET_LANE_FUNCTIONS(V)                         \
16096   V(Float32x4, WithX, ARG_TO_FLOAT32, 0)                      \
16097   V(Float32x4, WithY, ARG_TO_FLOAT32, 1)                      \
16098   V(Float32x4, WithZ, ARG_TO_FLOAT32, 2)                      \
16099   V(Float32x4, WithW, ARG_TO_FLOAT32, 3)                      \
16100   V(Float64x2, WithX, ARG_TO_FLOAT64, 0)                      \
16101   V(Float64x2, WithY, ARG_TO_FLOAT64, 1)                      \
16102   V(Int32x4, WithX, ARG_TO_INT32, 0)                          \
16103   V(Int32x4, WithY, ARG_TO_INT32, 1)                          \
16104   V(Int32x4, WithZ, ARG_TO_INT32, 2)                          \
16105   V(Int32x4, WithW, ARG_TO_INT32, 3)                          \
16106   V(Int32x4, WithFlagX, ARG_TO_BOOLEAN, 0)                    \
16107   V(Int32x4, WithFlagY, ARG_TO_BOOLEAN, 1)                    \
16108   V(Int32x4, WithFlagZ, ARG_TO_BOOLEAN, 2)                    \
16109   V(Int32x4, WithFlagW, ARG_TO_BOOLEAN, 3)
16110
16111
16112 #define DECLARE_SIMD_SET_LANE_FUNCTION(                       \
16113     TYPE, NAME, ARG_FUNCTION, LANE)                           \
16114 RUNTIME_FUNCTION(Runtime_##TYPE##NAME) {        \
16115   HandleScope scope(isolate);                                 \
16116   DCHECK(args.length() == 2);                                 \
16117                                                               \
16118   CONVERT_ARG_CHECKED(TYPE, a, 0);                            \
16119   ARG_FUNCTION(value);                                        \
16120                                                               \
16121   TYPE::value_t result;                                       \
16122   for (int i = 0; i < TYPE::kLanes; i++) {                    \
16123     if (i != LANE)                                            \
16124       result.storage[i] = a->getAt(i);                        \
16125     else                                                      \
16126       result.storage[i] = value;                              \
16127   }                                                           \
16128                                                               \
16129   RETURN_##TYPE##_RESULT(result);                             \
16130 }
16131
16132
16133 SIMD128_SET_LANE_FUNCTIONS(DECLARE_SIMD_SET_LANE_FUNCTION)
16134
16135
16136 RUNTIME_FUNCTION(Runtime_Float32x4Clamp) {
16137   HandleScope scope(isolate);
16138   DCHECK(args.length() == 3);
16139
16140   CONVERT_ARG_CHECKED(Float32x4, self, 0);
16141   CONVERT_ARG_CHECKED(Float32x4, lo, 1);
16142   CONVERT_ARG_CHECKED(Float32x4, hi, 2);
16143
16144   float32x4_value_t result;
16145   float _x = self->x() > lo->x() ? self->x() : lo->x();
16146   float _y = self->y() > lo->y() ? self->y() : lo->y();
16147   float _z = self->z() > lo->z() ? self->z() : lo->z();
16148   float _w = self->w() > lo->w() ? self->w() : lo->w();
16149   result.storage[0] = _x > hi->x() ? hi->x() : _x;
16150   result.storage[1] = _y > hi->y() ? hi->y() : _y;
16151   result.storage[2] = _z > hi->z() ? hi->z() : _z;
16152   result.storage[3] = _w > hi->w() ? hi->w() : _w;
16153
16154   RETURN_Float32x4_RESULT(result);
16155 }
16156
16157
16158 RUNTIME_FUNCTION(Runtime_Float64x2Clamp) {
16159   HandleScope scope(isolate);
16160   DCHECK(args.length() == 3);
16161
16162   CONVERT_ARG_CHECKED(Float64x2, self, 0);
16163   CONVERT_ARG_CHECKED(Float64x2, lo, 1);
16164   CONVERT_ARG_CHECKED(Float64x2, hi, 2);
16165
16166   float64x2_value_t result;
16167   double _x = self->x() > lo->x() ? self->x() : lo->x();
16168   double _y = self->y() > lo->y() ? self->y() : lo->y();
16169   result.storage[0] = _x > hi->x() ? hi->x() : _x;
16170   result.storage[1] = _y > hi->y() ? hi->y() : _y;
16171
16172   RETURN_Float64x2_RESULT(result);
16173 }
16174
16175
16176 RUNTIME_FUNCTION(Runtime_Float32x4ShuffleMix) {
16177   HandleScope scope(isolate);
16178   DCHECK(args.length() == 3);
16179
16180   CONVERT_ARG_CHECKED(Float32x4, first, 0);
16181   CONVERT_ARG_CHECKED(Float32x4, second, 1);
16182   RUNTIME_ASSERT(args[2]->IsNumber());
16183
16184   uint32_t m = NumberToUint32(args[2]);
16185   float32x4_value_t result;
16186   float data1[4] = { first->x(), first->y(), first->z(), first->w() };
16187   float data2[4] = { second->x(), second->y(), second->z(), second->w() };
16188   result.storage[0] = data1[m & 0x3];
16189   result.storage[1] = data1[(m >> 2) & 0x3];
16190   result.storage[2] = data2[(m >> 4) & 0x3];
16191   result.storage[3] = data2[(m >> 6) & 0x3];
16192
16193   RETURN_Float32x4_RESULT(result);
16194 }
16195
16196
16197 RUNTIME_FUNCTION(Runtime_Float32x4Select) {
16198   HandleScope scope(isolate);
16199   DCHECK(args.length() == 3);
16200
16201   CONVERT_ARG_CHECKED(Int32x4, self, 0);
16202   CONVERT_ARG_CHECKED(Float32x4, tv, 1);
16203   CONVERT_ARG_CHECKED(Float32x4, fv, 2);
16204
16205   uint32_t _maskX = self->x();
16206   uint32_t _maskY = self->y();
16207   uint32_t _maskZ = self->z();
16208   uint32_t _maskW = self->w();
16209   // Extract floats and interpret them as masks.
16210   float32_uint32 tvx(tv->x());
16211   float32_uint32 tvy(tv->y());
16212   float32_uint32 tvz(tv->z());
16213   float32_uint32 tvw(tv->w());
16214   float32_uint32 fvx(fv->x());
16215   float32_uint32 fvy(fv->y());
16216   float32_uint32 fvz(fv->z());
16217   float32_uint32 fvw(fv->w());
16218   // Perform select.
16219   float32_uint32 tempX((_maskX & tvx.u) | (~_maskX & fvx.u));
16220   float32_uint32 tempY((_maskY & tvy.u) | (~_maskY & fvy.u));
16221   float32_uint32 tempZ((_maskZ & tvz.u) | (~_maskZ & fvz.u));
16222   float32_uint32 tempW((_maskW & tvw.u) | (~_maskW & fvw.u));
16223
16224   float32x4_value_t result;
16225   result.storage[0] = tempX.f;
16226   result.storage[1] = tempY.f;
16227   result.storage[2] = tempZ.f;
16228   result.storage[3] = tempW.f;
16229
16230   RETURN_Float32x4_RESULT(result);
16231 }
16232
16233
16234 RUNTIME_FUNCTION(Runtime_Int32x4Select) {
16235   HandleScope scope(isolate);
16236   DCHECK(args.length() == 3);
16237
16238   CONVERT_ARG_CHECKED(Int32x4, self, 0);
16239   CONVERT_ARG_CHECKED(Int32x4, tv, 1);
16240   CONVERT_ARG_CHECKED(Int32x4, fv, 2);
16241
16242   uint32_t _maskX = self->x();
16243   uint32_t _maskY = self->y();
16244   uint32_t _maskZ = self->z();
16245   uint32_t _maskW = self->w();
16246
16247   int32x4_value_t result;
16248   result.storage[0] = (_maskX & tv->x()) | (~_maskX & fv->x());
16249   result.storage[1] = (_maskY & tv->y()) | (~_maskY & fv->y());
16250   result.storage[2] = (_maskZ & tv->z()) | (~_maskZ & fv->z());
16251   result.storage[3] = (_maskW & tv->w()) | (~_maskW & fv->w());
16252
16253   RETURN_Int32x4_RESULT(result);
16254 }
16255
16256
16257 // ----------------------------------------------------------------------------
16258 // Reference implementation for inlined runtime functions.  Only used when the
16259 // compiler does not support a certain intrinsic.  Don't optimize these, but
16260 // implement the intrinsic in the respective compiler instead.
16261
16262 // TODO(mstarzinger): These are place-holder stubs for TurboFan and will
16263 // eventually all have a C++ implementation and this macro will be gone.
16264 #define U(name)                               \
16265   RUNTIME_FUNCTION(RuntimeReference_##name) { \
16266     UNIMPLEMENTED();                          \
16267     return NULL;                              \
16268   }
16269
16270 U(IsStringWrapperSafeForDefaultValueOf)
16271 U(DebugBreakInOptimizedCode)
16272
16273 #undef U
16274
16275
16276 RUNTIME_FUNCTION(RuntimeReference_IsSmi) {
16277   SealHandleScope shs(isolate);
16278   DCHECK(args.length() == 1);
16279   CONVERT_ARG_CHECKED(Object, obj, 0);
16280   return isolate->heap()->ToBoolean(obj->IsSmi());
16281 }
16282
16283
16284 RUNTIME_FUNCTION(RuntimeReference_IsNonNegativeSmi) {
16285   SealHandleScope shs(isolate);
16286   DCHECK(args.length() == 1);
16287   CONVERT_ARG_CHECKED(Object, obj, 0);
16288   return isolate->heap()->ToBoolean(obj->IsSmi() &&
16289                                     Smi::cast(obj)->value() >= 0);
16290 }
16291
16292
16293 RUNTIME_FUNCTION(RuntimeReference_IsArray) {
16294   SealHandleScope shs(isolate);
16295   DCHECK(args.length() == 1);
16296   CONVERT_ARG_CHECKED(Object, obj, 0);
16297   return isolate->heap()->ToBoolean(obj->IsJSArray());
16298 }
16299
16300
16301 RUNTIME_FUNCTION(RuntimeReference_IsRegExp) {
16302   SealHandleScope shs(isolate);
16303   DCHECK(args.length() == 1);
16304   CONVERT_ARG_CHECKED(Object, obj, 0);
16305   return isolate->heap()->ToBoolean(obj->IsJSRegExp());
16306 }
16307
16308
16309 RUNTIME_FUNCTION(RuntimeReference_IsConstructCall) {
16310   SealHandleScope shs(isolate);
16311   DCHECK(args.length() == 0);
16312   JavaScriptFrameIterator it(isolate);
16313   JavaScriptFrame* frame = it.frame();
16314   return isolate->heap()->ToBoolean(frame->IsConstructor());
16315 }
16316
16317
16318 RUNTIME_FUNCTION(RuntimeReference_CallFunction) {
16319   SealHandleScope shs(isolate);
16320   return __RT_impl_Runtime_Call(args, isolate);
16321 }
16322
16323
16324 RUNTIME_FUNCTION(RuntimeReference_ArgumentsLength) {
16325   SealHandleScope shs(isolate);
16326   DCHECK(args.length() == 0);
16327   JavaScriptFrameIterator it(isolate);
16328   JavaScriptFrame* frame = it.frame();
16329   return Smi::FromInt(frame->GetArgumentsLength());
16330 }
16331
16332
16333 RUNTIME_FUNCTION(RuntimeReference_Arguments) {
16334   SealHandleScope shs(isolate);
16335   return __RT_impl_Runtime_GetArgumentsProperty(args, isolate);
16336 }
16337
16338
16339 RUNTIME_FUNCTION(RuntimeReference_ValueOf) {
16340   SealHandleScope shs(isolate);
16341   DCHECK(args.length() == 1);
16342   CONVERT_ARG_CHECKED(Object, obj, 0);
16343   if (!obj->IsJSValue()) return obj;
16344   return JSValue::cast(obj)->value();
16345 }
16346
16347
16348 RUNTIME_FUNCTION(RuntimeReference_SetValueOf) {
16349   SealHandleScope shs(isolate);
16350   DCHECK(args.length() == 2);
16351   CONVERT_ARG_CHECKED(Object, obj, 0);
16352   CONVERT_ARG_CHECKED(Object, value, 1);
16353   if (!obj->IsJSValue()) return value;
16354   JSValue::cast(obj)->set_value(value);
16355   return value;
16356 }
16357
16358
16359 RUNTIME_FUNCTION(RuntimeReference_DateField) {
16360   SealHandleScope shs(isolate);
16361   DCHECK(args.length() == 2);
16362   CONVERT_ARG_CHECKED(Object, obj, 0);
16363   CONVERT_SMI_ARG_CHECKED(index, 1);
16364   if (!obj->IsJSDate()) {
16365     HandleScope scope(isolate);
16366     THROW_NEW_ERROR_RETURN_FAILURE(
16367         isolate,
16368         NewTypeError("not_date_object", HandleVector<Object>(NULL, 0)));
16369   }
16370   JSDate* date = JSDate::cast(obj);
16371   if (index == 0) return date->value();
16372   return JSDate::GetField(date, Smi::FromInt(index));
16373 }
16374
16375
16376 RUNTIME_FUNCTION(RuntimeReference_StringCharFromCode) {
16377   SealHandleScope shs(isolate);
16378   return __RT_impl_Runtime_CharFromCode(args, isolate);
16379 }
16380
16381
16382 RUNTIME_FUNCTION(RuntimeReference_StringCharAt) {
16383   SealHandleScope shs(isolate);
16384   DCHECK(args.length() == 2);
16385   if (!args[0]->IsString()) return Smi::FromInt(0);
16386   if (!args[1]->IsNumber()) return Smi::FromInt(0);
16387   if (std::isinf(args.number_at(1))) return isolate->heap()->empty_string();
16388   Object* code = __RT_impl_Runtime_StringCharCodeAtRT(args, isolate);
16389   if (code->IsNaN()) return isolate->heap()->empty_string();
16390   return __RT_impl_Runtime_CharFromCode(Arguments(1, &code), isolate);
16391 }
16392
16393
16394 RUNTIME_FUNCTION(RuntimeReference_OneByteSeqStringSetChar) {
16395   SealHandleScope shs(isolate);
16396   DCHECK(args.length() == 3);
16397   CONVERT_INT32_ARG_CHECKED(index, 0);
16398   CONVERT_INT32_ARG_CHECKED(value, 1);
16399   CONVERT_ARG_CHECKED(SeqOneByteString, string, 2);
16400   string->SeqOneByteStringSet(index, value);
16401   return string;
16402 }
16403
16404
16405 RUNTIME_FUNCTION(RuntimeReference_TwoByteSeqStringSetChar) {
16406   SealHandleScope shs(isolate);
16407   DCHECK(args.length() == 3);
16408   CONVERT_INT32_ARG_CHECKED(index, 0);
16409   CONVERT_INT32_ARG_CHECKED(value, 1);
16410   CONVERT_ARG_CHECKED(SeqTwoByteString, string, 2);
16411   string->SeqTwoByteStringSet(index, value);
16412   return string;
16413 }
16414
16415
16416 RUNTIME_FUNCTION(RuntimeReference_ObjectEquals) {
16417   SealHandleScope shs(isolate);
16418   DCHECK(args.length() == 2);
16419   CONVERT_ARG_CHECKED(Object, obj1, 0);
16420   CONVERT_ARG_CHECKED(Object, obj2, 1);
16421   return isolate->heap()->ToBoolean(obj1 == obj2);
16422 }
16423
16424
16425 RUNTIME_FUNCTION(RuntimeReference_IsObject) {
16426   SealHandleScope shs(isolate);
16427   DCHECK(args.length() == 1);
16428   CONVERT_ARG_CHECKED(Object, obj, 0);
16429   if (!obj->IsHeapObject()) return isolate->heap()->false_value();
16430   if (obj->IsNull()) return isolate->heap()->true_value();
16431   if (obj->IsUndetectableObject()) return isolate->heap()->false_value();
16432   Map* map = HeapObject::cast(obj)->map();
16433   bool is_non_callable_spec_object =
16434       map->instance_type() >= FIRST_NONCALLABLE_SPEC_OBJECT_TYPE &&
16435       map->instance_type() <= LAST_NONCALLABLE_SPEC_OBJECT_TYPE;
16436   return isolate->heap()->ToBoolean(is_non_callable_spec_object);
16437 }
16438
16439
16440 RUNTIME_FUNCTION(RuntimeReference_IsFunction) {
16441   SealHandleScope shs(isolate);
16442   DCHECK(args.length() == 1);
16443   CONVERT_ARG_CHECKED(Object, obj, 0);
16444   return isolate->heap()->ToBoolean(obj->IsJSFunction());
16445 }
16446
16447
16448 RUNTIME_FUNCTION(RuntimeReference_IsUndetectableObject) {
16449   SealHandleScope shs(isolate);
16450   DCHECK(args.length() == 1);
16451   CONVERT_ARG_CHECKED(Object, obj, 0);
16452   return isolate->heap()->ToBoolean(obj->IsUndetectableObject());
16453 }
16454
16455
16456 RUNTIME_FUNCTION(RuntimeReference_IsSpecObject) {
16457   SealHandleScope shs(isolate);
16458   DCHECK(args.length() == 1);
16459   CONVERT_ARG_CHECKED(Object, obj, 0);
16460   return isolate->heap()->ToBoolean(obj->IsSpecObject());
16461 }
16462
16463
16464 RUNTIME_FUNCTION(RuntimeReference_MathPow) {
16465   SealHandleScope shs(isolate);
16466   return __RT_impl_Runtime_MathPowSlow(args, isolate);
16467 }
16468
16469
16470 RUNTIME_FUNCTION(RuntimeReference_IsMinusZero) {
16471   SealHandleScope shs(isolate);
16472   DCHECK(args.length() == 1);
16473   CONVERT_ARG_CHECKED(Object, obj, 0);
16474   if (!obj->IsHeapNumber()) return isolate->heap()->false_value();
16475   HeapNumber* number = HeapNumber::cast(obj);
16476   return isolate->heap()->ToBoolean(IsMinusZero(number->value()));
16477 }
16478
16479
16480 RUNTIME_FUNCTION(RuntimeReference_HasCachedArrayIndex) {
16481   SealHandleScope shs(isolate);
16482   DCHECK(args.length() == 1);
16483   return isolate->heap()->false_value();
16484 }
16485
16486
16487 RUNTIME_FUNCTION(RuntimeReference_GetCachedArrayIndex) {
16488   SealHandleScope shs(isolate);
16489   DCHECK(args.length() == 1);
16490   return isolate->heap()->undefined_value();
16491 }
16492
16493
16494 RUNTIME_FUNCTION(RuntimeReference_FastOneByteArrayJoin) {
16495   SealHandleScope shs(isolate);
16496   DCHECK(args.length() == 2);
16497   return isolate->heap()->undefined_value();
16498 }
16499
16500
16501 RUNTIME_FUNCTION(RuntimeReference_GeneratorNext) {
16502   UNREACHABLE();  // Optimization disabled in SetUpGenerators().
16503   return NULL;
16504 }
16505
16506
16507 RUNTIME_FUNCTION(RuntimeReference_GeneratorThrow) {
16508   UNREACHABLE();  // Optimization disabled in SetUpGenerators().
16509   return NULL;
16510 }
16511
16512
16513 RUNTIME_FUNCTION(RuntimeReference_ClassOf) {
16514   SealHandleScope shs(isolate);
16515   DCHECK(args.length() == 1);
16516   CONVERT_ARG_CHECKED(Object, obj, 0);
16517   if (!obj->IsJSReceiver()) return isolate->heap()->null_value();
16518   return JSReceiver::cast(obj)->class_name();
16519 }
16520
16521
16522 RUNTIME_FUNCTION(RuntimeReference_StringCharCodeAt) {
16523   SealHandleScope shs(isolate);
16524   DCHECK(args.length() == 2);
16525   if (!args[0]->IsString()) return isolate->heap()->undefined_value();
16526   if (!args[1]->IsNumber()) return isolate->heap()->undefined_value();
16527   if (std::isinf(args.number_at(1))) return isolate->heap()->nan_value();
16528   return __RT_impl_Runtime_StringCharCodeAtRT(args, isolate);
16529 }
16530
16531
16532 RUNTIME_FUNCTION(RuntimeReference_StringAdd) {
16533   SealHandleScope shs(isolate);
16534   return __RT_impl_Runtime_StringAdd(args, isolate);
16535 }
16536
16537
16538 RUNTIME_FUNCTION(RuntimeReference_SubString) {
16539   SealHandleScope shs(isolate);
16540   return __RT_impl_Runtime_SubString(args, isolate);
16541 }
16542
16543
16544 RUNTIME_FUNCTION(RuntimeReference_StringCompare) {
16545   SealHandleScope shs(isolate);
16546   return __RT_impl_Runtime_StringCompare(args, isolate);
16547 }
16548
16549
16550 RUNTIME_FUNCTION(RuntimeReference_RegExpExec) {
16551   SealHandleScope shs(isolate);
16552   return __RT_impl_Runtime_RegExpExecRT(args, isolate);
16553 }
16554
16555
16556 RUNTIME_FUNCTION(RuntimeReference_RegExpConstructResult) {
16557   SealHandleScope shs(isolate);
16558   return __RT_impl_Runtime_RegExpConstructResult(args, isolate);
16559 }
16560
16561
16562 RUNTIME_FUNCTION(RuntimeReference_GetFromCache) {
16563   HandleScope scope(isolate);
16564   DCHECK(args.length() == 2);
16565   CONVERT_SMI_ARG_CHECKED(id, 0);
16566   args[0] = isolate->native_context()->jsfunction_result_caches()->get(id);
16567   return __RT_impl_Runtime_GetFromCache(args, isolate);
16568 }
16569
16570
16571 RUNTIME_FUNCTION(RuntimeReference_NumberToString) {
16572   SealHandleScope shs(isolate);
16573   return __RT_impl_Runtime_NumberToStringRT(args, isolate);
16574 }
16575
16576
16577 RUNTIME_FUNCTION(RuntimeReference_DebugIsActive) {
16578   SealHandleScope shs(isolate);
16579   return Smi::FromInt(isolate->debug()->is_active());
16580 }
16581
16582
16583 // ----------------------------------------------------------------------------
16584 // Implementation of Runtime
16585
16586 #define F(name, number_of_args, result_size)                                  \
16587   {                                                                           \
16588     Runtime::k##name, Runtime::RUNTIME, #name, FUNCTION_ADDR(Runtime_##name), \
16589         number_of_args, result_size                                           \
16590   }                                                                           \
16591   ,
16592
16593
16594 #define I(name, number_of_args, result_size)                                \
16595   {                                                                         \
16596     Runtime::kInline##name, Runtime::INLINE, "_" #name,                     \
16597         FUNCTION_ADDR(RuntimeReference_##name), number_of_args, result_size \
16598   }                                                                         \
16599   ,
16600
16601
16602 #define IO(name, number_of_args, result_size)                              \
16603   {                                                                        \
16604     Runtime::kInlineOptimized##name, Runtime::INLINE_OPTIMIZED, "_" #name, \
16605         FUNCTION_ADDR(Runtime_##name), number_of_args, result_size         \
16606   }                                                                        \
16607   ,
16608
16609
16610 static const Runtime::Function kIntrinsicFunctions[] = {
16611   RUNTIME_FUNCTION_LIST(F)
16612   INLINE_OPTIMIZED_FUNCTION_LIST(F)
16613   INLINE_FUNCTION_LIST(I)
16614   INLINE_OPTIMIZED_FUNCTION_LIST(IO)
16615 };
16616
16617 #undef IO
16618 #undef I
16619 #undef F
16620
16621
16622 void Runtime::InitializeIntrinsicFunctionNames(Isolate* isolate,
16623                                                Handle<NameDictionary> dict) {
16624   DCHECK(dict->NumberOfElements() == 0);
16625   HandleScope scope(isolate);
16626   for (int i = 0; i < kNumFunctions; ++i) {
16627     const char* name = kIntrinsicFunctions[i].name;
16628     if (name == NULL) continue;
16629     Handle<NameDictionary> new_dict = NameDictionary::Add(
16630         dict,
16631         isolate->factory()->InternalizeUtf8String(name),
16632         Handle<Smi>(Smi::FromInt(i), isolate),
16633         PropertyDetails(NONE, NORMAL, Representation::None()));
16634     // The dictionary does not need to grow.
16635     CHECK(new_dict.is_identical_to(dict));
16636   }
16637 }
16638
16639
16640 const Runtime::Function* Runtime::FunctionForName(Handle<String> name) {
16641   Heap* heap = name->GetHeap();
16642   int entry = heap->intrinsic_function_names()->FindEntry(name);
16643   if (entry != kNotFound) {
16644     Object* smi_index = heap->intrinsic_function_names()->ValueAt(entry);
16645     int function_index = Smi::cast(smi_index)->value();
16646     return &(kIntrinsicFunctions[function_index]);
16647   }
16648   return NULL;
16649 }
16650
16651
16652 const Runtime::Function* Runtime::FunctionForEntry(Address entry) {
16653   for (size_t i = 0; i < arraysize(kIntrinsicFunctions); ++i) {
16654     if (entry == kIntrinsicFunctions[i].entry) {
16655       return &(kIntrinsicFunctions[i]);
16656     }
16657   }
16658   return NULL;
16659 }
16660
16661
16662 const Runtime::Function* Runtime::FunctionForId(Runtime::FunctionId id) {
16663   return &(kIntrinsicFunctions[static_cast<int>(id)]);
16664 }
16665
16666 } }  // namespace v8::internal