blob: fa1b34e655fe3aaa752bed7561e382ad3d307322 [file] [log] [blame]
Steve Blocka7e24c12009-10-30 11:49:00 +00001// Copyright 2006-2008 the V8 project authors. All rights reserved.
2// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include "v8.h"
29
30#include "api.h"
31#include "arguments.h"
32#include "bootstrapper.h"
33#include "builtins.h"
34#include "ic-inl.h"
35
36namespace v8 {
37namespace internal {
38
39// ----------------------------------------------------------------------------
40// Support macros for defining builtins in C.
41// ----------------------------------------------------------------------------
42//
43// A builtin function is defined by writing:
44//
45// BUILTIN(name) {
46// ...
47// }
48// BUILTIN_END
49//
50// In the body of the builtin function, the variable 'receiver' is visible.
51// The arguments can be accessed through the Arguments object args.
52//
53// args[0]: Receiver (also available as 'receiver')
54// args[1]: First argument
55// ...
56// args[n]: Last argument
57// args.length(): Number of arguments including the receiver.
58// ----------------------------------------------------------------------------
59
60
61// TODO(428): We should consider passing whether or not the
62// builtin was invoked as a constructor as part of the
63// arguments. Maybe we also want to pass the called function?
64#define BUILTIN(name) \
65 static Object* Builtin_##name(Arguments args) { \
66 Handle<Object> receiver = args.at<Object>(0);
67
68
69#define BUILTIN_END \
70 return Heap::undefined_value(); \
71}
72
73
74static inline bool CalledAsConstructor() {
75#ifdef DEBUG
76 // Calculate the result using a full stack frame iterator and check
77 // that the state of the stack is as we assume it to be in the
78 // code below.
79 StackFrameIterator it;
80 ASSERT(it.frame()->is_exit());
81 it.Advance();
82 StackFrame* frame = it.frame();
83 bool reference_result = frame->is_construct();
84#endif
85 Address fp = Top::c_entry_fp(Top::GetCurrentThread());
86 // Because we know fp points to an exit frame we can use the relevant
87 // part of ExitFrame::ComputeCallerState directly.
88 const int kCallerOffset = ExitFrameConstants::kCallerFPOffset;
89 Address caller_fp = Memory::Address_at(fp + kCallerOffset);
90 // This inlines the part of StackFrame::ComputeType that grabs the
91 // type of the current frame. Note that StackFrame::ComputeType
92 // has been specialized for each architecture so if any one of them
93 // changes this code has to be changed as well.
94 const int kMarkerOffset = StandardFrameConstants::kMarkerOffset;
95 const Smi* kConstructMarker = Smi::FromInt(StackFrame::CONSTRUCT);
96 Object* marker = Memory::Object_at(caller_fp + kMarkerOffset);
97 bool result = (marker == kConstructMarker);
98 ASSERT_EQ(result, reference_result);
99 return result;
100}
101
102// ----------------------------------------------------------------------------
103
104
105Handle<Code> Builtins::GetCode(JavaScript id, bool* resolved) {
106 Code* code = Builtins::builtin(Builtins::Illegal);
107 *resolved = false;
108
109 if (Top::context() != NULL) {
110 Object* object = Top::builtins()->javascript_builtin(id);
111 if (object->IsJSFunction()) {
112 Handle<JSFunction> function(JSFunction::cast(object));
113 // Make sure the number of parameters match the formal parameter count.
114 ASSERT(function->shared()->formal_parameter_count() ==
115 Builtins::GetArgumentsCount(id));
116 if (function->is_compiled() || CompileLazy(function, CLEAR_EXCEPTION)) {
117 code = function->code();
118 *resolved = true;
119 }
120 }
121 }
122
123 return Handle<Code>(code);
124}
125
126
127BUILTIN(Illegal) {
128 UNREACHABLE();
129}
130BUILTIN_END
131
132
133BUILTIN(EmptyFunction) {
134}
135BUILTIN_END
136
137
138BUILTIN(ArrayCodeGeneric) {
139 Counters::array_function_runtime.Increment();
140
141 JSArray* array;
142 if (CalledAsConstructor()) {
143 array = JSArray::cast(*receiver);
144 } else {
145 // Allocate the JS Array
146 JSFunction* constructor =
147 Top::context()->global_context()->array_function();
148 Object* obj = Heap::AllocateJSObject(constructor);
149 if (obj->IsFailure()) return obj;
150 array = JSArray::cast(obj);
151 }
152
153 // 'array' now contains the JSArray we should initialize.
154
155 // Optimize the case where there is one argument and the argument is a
156 // small smi.
157 if (args.length() == 2) {
158 Object* obj = args[1];
159 if (obj->IsSmi()) {
160 int len = Smi::cast(obj)->value();
161 if (len >= 0 && len < JSObject::kInitialMaxFastElementArray) {
162 Object* obj = Heap::AllocateFixedArrayWithHoles(len);
163 if (obj->IsFailure()) return obj;
164 array->SetContent(FixedArray::cast(obj));
165 return array;
166 }
167 }
168 // Take the argument as the length.
169 obj = array->Initialize(0);
170 if (obj->IsFailure()) return obj;
171 return array->SetElementsLength(args[1]);
172 }
173
174 // Optimize the case where there are no parameters passed.
175 if (args.length() == 1) {
176 return array->Initialize(JSArray::kPreallocatedArrayElements);
177 }
178
179 // Take the arguments as elements.
180 int number_of_elements = args.length() - 1;
181 Smi* len = Smi::FromInt(number_of_elements);
182 Object* obj = Heap::AllocateFixedArrayWithHoles(len->value());
183 if (obj->IsFailure()) return obj;
184 FixedArray* elms = FixedArray::cast(obj);
185 WriteBarrierMode mode = elms->GetWriteBarrierMode();
186 // Fill in the content
187 for (int index = 0; index < number_of_elements; index++) {
188 elms->set(index, args[index+1], mode);
189 }
190
191 // Set length and elements on the array.
192 array->set_elements(FixedArray::cast(obj));
193 array->set_length(len, SKIP_WRITE_BARRIER);
194
195 return array;
196}
197BUILTIN_END
198
199
200BUILTIN(ArrayPush) {
201 JSArray* array = JSArray::cast(*receiver);
202 ASSERT(array->HasFastElements());
203
204 // Make sure we have space for the elements.
205 int len = Smi::cast(array->length())->value();
206
207 // Set new length.
208 int new_length = len + args.length() - 1;
209 FixedArray* elms = FixedArray::cast(array->elements());
210
211 if (new_length <= elms->length()) {
212 // Backing storage has extra space for the provided values.
213 for (int index = 0; index < args.length() - 1; index++) {
214 elms->set(index + len, args[index+1]);
215 }
216 } else {
217 // New backing storage is needed.
218 int capacity = new_length + (new_length >> 1) + 16;
219 Object* obj = Heap::AllocateFixedArrayWithHoles(capacity);
220 if (obj->IsFailure()) return obj;
221 FixedArray* new_elms = FixedArray::cast(obj);
222 WriteBarrierMode mode = new_elms->GetWriteBarrierMode();
223 // Fill out the new array with old elements.
224 for (int i = 0; i < len; i++) new_elms->set(i, elms->get(i), mode);
225 // Add the provided values.
226 for (int index = 0; index < args.length() - 1; index++) {
227 new_elms->set(index + len, args[index+1], mode);
228 }
229 // Set the new backing storage.
230 array->set_elements(new_elms);
231 }
232 // Set the length.
233 array->set_length(Smi::FromInt(new_length), SKIP_WRITE_BARRIER);
234 return array->length();
235}
236BUILTIN_END
237
238
239BUILTIN(ArrayPop) {
240 JSArray* array = JSArray::cast(*receiver);
241 ASSERT(array->HasFastElements());
242 Object* undefined = Heap::undefined_value();
243
244 int len = Smi::cast(array->length())->value();
245 if (len == 0) return undefined;
246
247 // Get top element
248 FixedArray* elms = FixedArray::cast(array->elements());
249 Object* top = elms->get(len - 1);
250
251 // Set the length.
252 array->set_length(Smi::FromInt(len - 1), SKIP_WRITE_BARRIER);
253
254 if (!top->IsTheHole()) {
255 // Delete the top element.
256 elms->set_the_hole(len - 1);
257 return top;
258 }
259
260 // Remember to check the prototype chain.
261 JSFunction* array_function =
262 Top::context()->global_context()->array_function();
263 JSObject* prototype = JSObject::cast(array_function->prototype());
264 top = prototype->GetElement(len - 1);
265
266 return top;
267}
268BUILTIN_END
269
270
271// -----------------------------------------------------------------------------
272//
273
274
275// Returns the holder JSObject if the function can legally be called
276// with this receiver. Returns Heap::null_value() if the call is
277// illegal. Any arguments that don't fit the expected type is
278// overwritten with undefined. Arguments that do fit the expected
279// type is overwritten with the object in the prototype chain that
280// actually has that type.
281static inline Object* TypeCheck(int argc,
282 Object** argv,
283 FunctionTemplateInfo* info) {
284 Object* recv = argv[0];
285 Object* sig_obj = info->signature();
286 if (sig_obj->IsUndefined()) return recv;
287 SignatureInfo* sig = SignatureInfo::cast(sig_obj);
288 // If necessary, check the receiver
289 Object* recv_type = sig->receiver();
290
291 Object* holder = recv;
292 if (!recv_type->IsUndefined()) {
293 for (; holder != Heap::null_value(); holder = holder->GetPrototype()) {
294 if (holder->IsInstanceOf(FunctionTemplateInfo::cast(recv_type))) {
295 break;
296 }
297 }
298 if (holder == Heap::null_value()) return holder;
299 }
300 Object* args_obj = sig->args();
301 // If there is no argument signature we're done
302 if (args_obj->IsUndefined()) return holder;
303 FixedArray* args = FixedArray::cast(args_obj);
304 int length = args->length();
305 if (argc <= length) length = argc - 1;
306 for (int i = 0; i < length; i++) {
307 Object* argtype = args->get(i);
308 if (argtype->IsUndefined()) continue;
309 Object** arg = &argv[-1 - i];
310 Object* current = *arg;
311 for (; current != Heap::null_value(); current = current->GetPrototype()) {
312 if (current->IsInstanceOf(FunctionTemplateInfo::cast(argtype))) {
313 *arg = current;
314 break;
315 }
316 }
317 if (current == Heap::null_value()) *arg = Heap::undefined_value();
318 }
319 return holder;
320}
321
322
323BUILTIN(HandleApiCall) {
324 HandleScope scope;
325 bool is_construct = CalledAsConstructor();
326
327 // TODO(428): Remove use of static variable, handle API callbacks directly.
328 Handle<JSFunction> function =
329 Handle<JSFunction>(JSFunction::cast(Builtins::builtin_passed_function));
330
331 if (is_construct) {
332 Handle<FunctionTemplateInfo> desc =
333 Handle<FunctionTemplateInfo>(
334 FunctionTemplateInfo::cast(function->shared()->function_data()));
335 bool pending_exception = false;
336 Factory::ConfigureInstance(desc, Handle<JSObject>::cast(receiver),
337 &pending_exception);
338 ASSERT(Top::has_pending_exception() == pending_exception);
339 if (pending_exception) return Failure::Exception();
340 }
341
342 FunctionTemplateInfo* fun_data =
343 FunctionTemplateInfo::cast(function->shared()->function_data());
344 Object* raw_holder = TypeCheck(args.length(), &args[0], fun_data);
345
346 if (raw_holder->IsNull()) {
347 // This function cannot be called with the given receiver. Abort!
348 Handle<Object> obj =
349 Factory::NewTypeError("illegal_invocation", HandleVector(&function, 1));
350 return Top::Throw(*obj);
351 }
352
353 Object* raw_call_data = fun_data->call_code();
354 if (!raw_call_data->IsUndefined()) {
355 CallHandlerInfo* call_data = CallHandlerInfo::cast(raw_call_data);
356 Object* callback_obj = call_data->callback();
357 v8::InvocationCallback callback =
358 v8::ToCData<v8::InvocationCallback>(callback_obj);
359 Object* data_obj = call_data->data();
360 Object* result;
361
362 v8::Local<v8::Object> self =
363 v8::Utils::ToLocal(Handle<JSObject>::cast(receiver));
364 Handle<Object> data_handle(data_obj);
365 v8::Local<v8::Value> data = v8::Utils::ToLocal(data_handle);
366 ASSERT(raw_holder->IsJSObject());
367 v8::Local<v8::Function> callee = v8::Utils::ToLocal(function);
368 Handle<JSObject> holder_handle(JSObject::cast(raw_holder));
369 v8::Local<v8::Object> holder = v8::Utils::ToLocal(holder_handle);
370 LOG(ApiObjectAccess("call", JSObject::cast(*receiver)));
371 v8::Arguments new_args = v8::ImplementationUtilities::NewArguments(
372 data,
373 holder,
374 callee,
375 is_construct,
376 reinterpret_cast<void**>(&args[0] - 1),
377 args.length() - 1);
378
379 v8::Handle<v8::Value> value;
380 {
381 // Leaving JavaScript.
382 VMState state(EXTERNAL);
383 value = callback(new_args);
384 }
385 if (value.IsEmpty()) {
386 result = Heap::undefined_value();
387 } else {
388 result = *reinterpret_cast<Object**>(*value);
389 }
390
391 RETURN_IF_SCHEDULED_EXCEPTION();
392 if (!is_construct || result->IsJSObject()) return result;
393 }
394
395 return *receiver;
396}
397BUILTIN_END
398
399
400// Helper function to handle calls to non-function objects created through the
401// API. The object can be called as either a constructor (using new) or just as
402// a function (without new).
403static Object* HandleApiCallAsFunctionOrConstructor(bool is_construct_call,
404 Arguments args) {
405 // Non-functions are never called as constructors. Even if this is an object
406 // called as a constructor the delegate call is not a construct call.
407 ASSERT(!CalledAsConstructor());
408
409 Handle<Object> receiver = args.at<Object>(0);
410
411 // Get the object called.
412 JSObject* obj = JSObject::cast(*receiver);
413
414 // Get the invocation callback from the function descriptor that was
415 // used to create the called object.
416 ASSERT(obj->map()->has_instance_call_handler());
417 JSFunction* constructor = JSFunction::cast(obj->map()->constructor());
418 Object* template_info = constructor->shared()->function_data();
419 Object* handler =
420 FunctionTemplateInfo::cast(template_info)->instance_call_handler();
421 ASSERT(!handler->IsUndefined());
422 CallHandlerInfo* call_data = CallHandlerInfo::cast(handler);
423 Object* callback_obj = call_data->callback();
424 v8::InvocationCallback callback =
425 v8::ToCData<v8::InvocationCallback>(callback_obj);
426
427 // Get the data for the call and perform the callback.
428 Object* data_obj = call_data->data();
429 Object* result;
430 { HandleScope scope;
431 v8::Local<v8::Object> self =
432 v8::Utils::ToLocal(Handle<JSObject>::cast(receiver));
433 Handle<Object> data_handle(data_obj);
434 v8::Local<v8::Value> data = v8::Utils::ToLocal(data_handle);
435 Handle<JSFunction> callee_handle(constructor);
436 v8::Local<v8::Function> callee = v8::Utils::ToLocal(callee_handle);
437 LOG(ApiObjectAccess("call non-function", JSObject::cast(*receiver)));
438 v8::Arguments new_args = v8::ImplementationUtilities::NewArguments(
439 data,
440 self,
441 callee,
442 is_construct_call,
443 reinterpret_cast<void**>(&args[0] - 1),
444 args.length() - 1);
445 v8::Handle<v8::Value> value;
446 {
447 // Leaving JavaScript.
448 VMState state(EXTERNAL);
449 value = callback(new_args);
450 }
451 if (value.IsEmpty()) {
452 result = Heap::undefined_value();
453 } else {
454 result = *reinterpret_cast<Object**>(*value);
455 }
456 }
457 // Check for exceptions and return result.
458 RETURN_IF_SCHEDULED_EXCEPTION();
459 return result;
460}
461
462
463// Handle calls to non-function objects created through the API. This delegate
464// function is used when the call is a normal function call.
465BUILTIN(HandleApiCallAsFunction) {
466 return HandleApiCallAsFunctionOrConstructor(false, args);
467}
468BUILTIN_END
469
470
471// Handle calls to non-function objects created through the API. This delegate
472// function is used when the call is a construct call.
473BUILTIN(HandleApiCallAsConstructor) {
474 return HandleApiCallAsFunctionOrConstructor(true, args);
475}
476BUILTIN_END
477
478
479// TODO(1238487): This is a nasty hack. We need to improve the way we
480// call builtins considerable to get rid of this and the hairy macros
481// in builtins.cc.
482Object* Builtins::builtin_passed_function;
483
484
485
486static void Generate_LoadIC_ArrayLength(MacroAssembler* masm) {
487 LoadIC::GenerateArrayLength(masm);
488}
489
490
491static void Generate_LoadIC_StringLength(MacroAssembler* masm) {
492 LoadIC::GenerateStringLength(masm);
493}
494
495
496static void Generate_LoadIC_FunctionPrototype(MacroAssembler* masm) {
497 LoadIC::GenerateFunctionPrototype(masm);
498}
499
500
501static void Generate_LoadIC_Initialize(MacroAssembler* masm) {
502 LoadIC::GenerateInitialize(masm);
503}
504
505
506static void Generate_LoadIC_PreMonomorphic(MacroAssembler* masm) {
507 LoadIC::GeneratePreMonomorphic(masm);
508}
509
510
511static void Generate_LoadIC_Miss(MacroAssembler* masm) {
512 LoadIC::GenerateMiss(masm);
513}
514
515
516static void Generate_LoadIC_Megamorphic(MacroAssembler* masm) {
517 LoadIC::GenerateMegamorphic(masm);
518}
519
520
521static void Generate_LoadIC_Normal(MacroAssembler* masm) {
522 LoadIC::GenerateNormal(masm);
523}
524
525
526static void Generate_KeyedLoadIC_Initialize(MacroAssembler* masm) {
527 KeyedLoadIC::GenerateInitialize(masm);
528}
529
530
531static void Generate_KeyedLoadIC_Miss(MacroAssembler* masm) {
532 KeyedLoadIC::GenerateMiss(masm);
533}
534
535
536static void Generate_KeyedLoadIC_Generic(MacroAssembler* masm) {
537 KeyedLoadIC::GenerateGeneric(masm);
538}
539
540
Steve Block3ce2e202009-11-05 08:53:23 +0000541static void Generate_KeyedLoadIC_ExternalByteArray(MacroAssembler* masm) {
542 KeyedLoadIC::GenerateExternalArray(masm, kExternalByteArray);
543}
544
545
546static void Generate_KeyedLoadIC_ExternalUnsignedByteArray(
547 MacroAssembler* masm) {
548 KeyedLoadIC::GenerateExternalArray(masm, kExternalUnsignedByteArray);
549}
550
551
552static void Generate_KeyedLoadIC_ExternalShortArray(MacroAssembler* masm) {
553 KeyedLoadIC::GenerateExternalArray(masm, kExternalShortArray);
554}
555
556
557static void Generate_KeyedLoadIC_ExternalUnsignedShortArray(
558 MacroAssembler* masm) {
559 KeyedLoadIC::GenerateExternalArray(masm, kExternalUnsignedShortArray);
560}
561
562
563static void Generate_KeyedLoadIC_ExternalIntArray(MacroAssembler* masm) {
564 KeyedLoadIC::GenerateExternalArray(masm, kExternalIntArray);
565}
566
567
568static void Generate_KeyedLoadIC_ExternalUnsignedIntArray(
569 MacroAssembler* masm) {
570 KeyedLoadIC::GenerateExternalArray(masm, kExternalUnsignedIntArray);
571}
572
573
574static void Generate_KeyedLoadIC_ExternalFloatArray(MacroAssembler* masm) {
575 KeyedLoadIC::GenerateExternalArray(masm, kExternalFloatArray);
576}
577
578
Steve Blocka7e24c12009-10-30 11:49:00 +0000579static void Generate_KeyedLoadIC_PreMonomorphic(MacroAssembler* masm) {
580 KeyedLoadIC::GeneratePreMonomorphic(masm);
581}
582
583
584static void Generate_StoreIC_Initialize(MacroAssembler* masm) {
585 StoreIC::GenerateInitialize(masm);
586}
587
588
589static void Generate_StoreIC_Miss(MacroAssembler* masm) {
590 StoreIC::GenerateMiss(masm);
591}
592
593
594static void Generate_StoreIC_ExtendStorage(MacroAssembler* masm) {
595 StoreIC::GenerateExtendStorage(masm);
596}
597
598static void Generate_StoreIC_Megamorphic(MacroAssembler* masm) {
599 StoreIC::GenerateMegamorphic(masm);
600}
601
602
603static void Generate_KeyedStoreIC_Generic(MacroAssembler* masm) {
604 KeyedStoreIC::GenerateGeneric(masm);
605}
606
607
Steve Block3ce2e202009-11-05 08:53:23 +0000608static void Generate_KeyedStoreIC_ExternalByteArray(MacroAssembler* masm) {
609 KeyedStoreIC::GenerateExternalArray(masm, kExternalByteArray);
610}
611
612
613static void Generate_KeyedStoreIC_ExternalUnsignedByteArray(
614 MacroAssembler* masm) {
615 KeyedStoreIC::GenerateExternalArray(masm, kExternalUnsignedByteArray);
616}
617
618
619static void Generate_KeyedStoreIC_ExternalShortArray(MacroAssembler* masm) {
620 KeyedStoreIC::GenerateExternalArray(masm, kExternalShortArray);
621}
622
623
624static void Generate_KeyedStoreIC_ExternalUnsignedShortArray(
625 MacroAssembler* masm) {
626 KeyedStoreIC::GenerateExternalArray(masm, kExternalUnsignedShortArray);
627}
628
629
630static void Generate_KeyedStoreIC_ExternalIntArray(MacroAssembler* masm) {
631 KeyedStoreIC::GenerateExternalArray(masm, kExternalIntArray);
632}
633
634
635static void Generate_KeyedStoreIC_ExternalUnsignedIntArray(
636 MacroAssembler* masm) {
637 KeyedStoreIC::GenerateExternalArray(masm, kExternalUnsignedIntArray);
638}
639
640
641static void Generate_KeyedStoreIC_ExternalFloatArray(MacroAssembler* masm) {
642 KeyedStoreIC::GenerateExternalArray(masm, kExternalFloatArray);
643}
644
645
Steve Blocka7e24c12009-10-30 11:49:00 +0000646static void Generate_KeyedStoreIC_ExtendStorage(MacroAssembler* masm) {
647 KeyedStoreIC::GenerateExtendStorage(masm);
648}
649
650
651static void Generate_KeyedStoreIC_Miss(MacroAssembler* masm) {
652 KeyedStoreIC::GenerateMiss(masm);
653}
654
655
656static void Generate_KeyedStoreIC_Initialize(MacroAssembler* masm) {
657 KeyedStoreIC::GenerateInitialize(masm);
658}
659
660
661#ifdef ENABLE_DEBUGGER_SUPPORT
662static void Generate_LoadIC_DebugBreak(MacroAssembler* masm) {
663 Debug::GenerateLoadICDebugBreak(masm);
664}
665
666
667static void Generate_StoreIC_DebugBreak(MacroAssembler* masm) {
668 Debug::GenerateStoreICDebugBreak(masm);
669}
670
671
672static void Generate_KeyedLoadIC_DebugBreak(MacroAssembler* masm) {
673 Debug::GenerateKeyedLoadICDebugBreak(masm);
674}
675
676
677static void Generate_KeyedStoreIC_DebugBreak(MacroAssembler* masm) {
678 Debug::GenerateKeyedStoreICDebugBreak(masm);
679}
680
681
682static void Generate_ConstructCall_DebugBreak(MacroAssembler* masm) {
683 Debug::GenerateConstructCallDebugBreak(masm);
684}
685
686
687static void Generate_Return_DebugBreak(MacroAssembler* masm) {
688 Debug::GenerateReturnDebugBreak(masm);
689}
690
691
692static void Generate_StubNoRegisters_DebugBreak(MacroAssembler* masm) {
693 Debug::GenerateStubNoRegistersDebugBreak(masm);
694}
695#endif
696
697Object* Builtins::builtins_[builtin_count] = { NULL, };
698const char* Builtins::names_[builtin_count] = { NULL, };
699
700#define DEF_ENUM_C(name) FUNCTION_ADDR(Builtin_##name),
701 Address Builtins::c_functions_[cfunction_count] = {
702 BUILTIN_LIST_C(DEF_ENUM_C)
703 };
704#undef DEF_ENUM_C
705
706#define DEF_JS_NAME(name, ignore) #name,
707#define DEF_JS_ARGC(ignore, argc) argc,
708const char* Builtins::javascript_names_[id_count] = {
709 BUILTINS_LIST_JS(DEF_JS_NAME)
710};
711
712int Builtins::javascript_argc_[id_count] = {
713 BUILTINS_LIST_JS(DEF_JS_ARGC)
714};
715#undef DEF_JS_NAME
716#undef DEF_JS_ARGC
717
718static bool is_initialized = false;
719void Builtins::Setup(bool create_heap_objects) {
720 ASSERT(!is_initialized);
721
722 // Create a scope for the handles in the builtins.
723 HandleScope scope;
724
725 struct BuiltinDesc {
726 byte* generator;
727 byte* c_code;
728 const char* s_name; // name is only used for generating log information.
729 int name;
730 Code::Flags flags;
731 };
732
733#define DEF_FUNCTION_PTR_C(name) \
734 { FUNCTION_ADDR(Generate_Adaptor), \
735 FUNCTION_ADDR(Builtin_##name), \
736 #name, \
737 c_##name, \
738 Code::ComputeFlags(Code::BUILTIN) \
739 },
740
741#define DEF_FUNCTION_PTR_A(name, kind, state) \
742 { FUNCTION_ADDR(Generate_##name), \
743 NULL, \
744 #name, \
745 name, \
746 Code::ComputeFlags(Code::kind, NOT_IN_LOOP, state) \
747 },
748
749 // Define array of pointers to generators and C builtin functions.
750 static BuiltinDesc functions[] = {
751 BUILTIN_LIST_C(DEF_FUNCTION_PTR_C)
752 BUILTIN_LIST_A(DEF_FUNCTION_PTR_A)
753 BUILTIN_LIST_DEBUG_A(DEF_FUNCTION_PTR_A)
754 // Terminator:
755 { NULL, NULL, NULL, builtin_count, static_cast<Code::Flags>(0) }
756 };
757
758#undef DEF_FUNCTION_PTR_C
759#undef DEF_FUNCTION_PTR_A
760
761 // For now we generate builtin adaptor code into a stack-allocated
762 // buffer, before copying it into individual code objects.
763 byte buffer[4*KB];
764
765 // Traverse the list of builtins and generate an adaptor in a
766 // separate code object for each one.
767 for (int i = 0; i < builtin_count; i++) {
768 if (create_heap_objects) {
769 MacroAssembler masm(buffer, sizeof buffer);
770 // Generate the code/adaptor.
771 typedef void (*Generator)(MacroAssembler*, int);
772 Generator g = FUNCTION_CAST<Generator>(functions[i].generator);
773 // We pass all arguments to the generator, but it may not use all of
774 // them. This works because the first arguments are on top of the
775 // stack.
776 g(&masm, functions[i].name);
777 // Move the code into the object heap.
778 CodeDesc desc;
779 masm.GetCode(&desc);
780 Code::Flags flags = functions[i].flags;
781 Object* code;
782 {
783 // During startup it's OK to always allocate and defer GC to later.
784 // This simplifies things because we don't need to retry.
785 AlwaysAllocateScope __scope__;
786 code = Heap::CreateCode(desc, NULL, flags, masm.CodeObject());
787 if (code->IsFailure()) {
788 v8::internal::V8::FatalProcessOutOfMemory("CreateCode");
789 }
790 }
791 // Add any unresolved jumps or calls to the fixup list in the
792 // bootstrapper.
793 Bootstrapper::AddFixup(Code::cast(code), &masm);
794 // Log the event and add the code to the builtins array.
795 LOG(CodeCreateEvent(Logger::BUILTIN_TAG,
796 Code::cast(code), functions[i].s_name));
797 builtins_[i] = code;
798#ifdef ENABLE_DISASSEMBLER
799 if (FLAG_print_builtin_code) {
800 PrintF("Builtin: %s\n", functions[i].s_name);
801 Code::cast(code)->Disassemble(functions[i].s_name);
802 PrintF("\n");
803 }
804#endif
805 } else {
806 // Deserializing. The values will be filled in during IterateBuiltins.
807 builtins_[i] = NULL;
808 }
809 names_[i] = functions[i].s_name;
810 }
811
812 // Mark as initialized.
813 is_initialized = true;
814}
815
816
817void Builtins::TearDown() {
818 is_initialized = false;
819}
820
821
822void Builtins::IterateBuiltins(ObjectVisitor* v) {
823 v->VisitPointers(&builtins_[0], &builtins_[0] + builtin_count);
824}
825
826
827const char* Builtins::Lookup(byte* pc) {
828 if (is_initialized) { // may be called during initialization (disassembler!)
829 for (int i = 0; i < builtin_count; i++) {
830 Code* entry = Code::cast(builtins_[i]);
831 if (entry->contains(pc)) {
832 return names_[i];
833 }
834 }
835 }
836 return NULL;
837}
838
839
840} } // namespace v8::internal