deps: update v8 to 4.3.61.21
[platform/upstream/nodejs.git] / deps / v8 / src / ia32 / builtins-ia32.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 "src/v8.h"
6
7 #if V8_TARGET_ARCH_IA32
8
9 #include "src/code-factory.h"
10 #include "src/codegen.h"
11 #include "src/deoptimizer.h"
12 #include "src/full-codegen.h"
13
14 namespace v8 {
15 namespace internal {
16
17
18 #define __ ACCESS_MASM(masm)
19
20
21 void Builtins::Generate_Adaptor(MacroAssembler* masm,
22                                 CFunctionId id,
23                                 BuiltinExtraArguments extra_args) {
24   // ----------- S t a t e -------------
25   //  -- eax                : number of arguments excluding receiver
26   //  -- edi                : called function (only guaranteed when
27   //                          extra_args requires it)
28   //  -- esi                : context
29   //  -- esp[0]             : return address
30   //  -- esp[4]             : last argument
31   //  -- ...
32   //  -- esp[4 * argc]      : first argument (argc == eax)
33   //  -- esp[4 * (argc +1)] : receiver
34   // -----------------------------------
35
36   // Insert extra arguments.
37   int num_extra_args = 0;
38   if (extra_args == NEEDS_CALLED_FUNCTION) {
39     num_extra_args = 1;
40     Register scratch = ebx;
41     __ pop(scratch);  // Save return address.
42     __ push(edi);
43     __ push(scratch);  // Restore return address.
44   } else {
45     DCHECK(extra_args == NO_EXTRA_ARGUMENTS);
46   }
47
48   // JumpToExternalReference expects eax to contain the number of arguments
49   // including the receiver and the extra arguments.
50   __ add(eax, Immediate(num_extra_args + 1));
51   __ JumpToExternalReference(ExternalReference(id, masm->isolate()));
52 }
53
54
55 static void CallRuntimePassFunction(
56     MacroAssembler* masm, Runtime::FunctionId function_id) {
57   FrameScope scope(masm, StackFrame::INTERNAL);
58   // Push a copy of the function.
59   __ push(edi);
60   // Function is also the parameter to the runtime call.
61   __ push(edi);
62
63   __ CallRuntime(function_id, 1);
64   // Restore receiver.
65   __ pop(edi);
66 }
67
68
69 static void GenerateTailCallToSharedCode(MacroAssembler* masm) {
70   __ mov(eax, FieldOperand(edi, JSFunction::kSharedFunctionInfoOffset));
71   __ mov(eax, FieldOperand(eax, SharedFunctionInfo::kCodeOffset));
72   __ lea(eax, FieldOperand(eax, Code::kHeaderSize));
73   __ jmp(eax);
74 }
75
76
77 static void GenerateTailCallToReturnedCode(MacroAssembler* masm) {
78   __ lea(eax, FieldOperand(eax, Code::kHeaderSize));
79   __ jmp(eax);
80 }
81
82
83 void Builtins::Generate_InOptimizationQueue(MacroAssembler* masm) {
84   // Checking whether the queued function is ready for install is optional,
85   // since we come across interrupts and stack checks elsewhere.  However,
86   // not checking may delay installing ready functions, and always checking
87   // would be quite expensive.  A good compromise is to first check against
88   // stack limit as a cue for an interrupt signal.
89   Label ok;
90   ExternalReference stack_limit =
91       ExternalReference::address_of_stack_limit(masm->isolate());
92   __ cmp(esp, Operand::StaticVariable(stack_limit));
93   __ j(above_equal, &ok, Label::kNear);
94
95   CallRuntimePassFunction(masm, Runtime::kTryInstallOptimizedCode);
96   GenerateTailCallToReturnedCode(masm);
97
98   __ bind(&ok);
99   GenerateTailCallToSharedCode(masm);
100 }
101
102
103 static void Generate_Runtime_NewObject(MacroAssembler* masm,
104                                        bool create_memento,
105                                        Register original_constructor,
106                                        Label* count_incremented,
107                                        Label* allocated) {
108   int offset = 0;
109   if (create_memento) {
110     // Get the cell or allocation site.
111     __ mov(edi, Operand(esp, kPointerSize * 2));
112     __ push(edi);
113     offset = kPointerSize;
114   }
115
116   // Must restore esi (context) and edi (constructor) before calling
117   // runtime.
118   __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
119   __ mov(edi, Operand(esp, offset));
120   __ push(edi);
121   __ push(original_constructor);
122   if (create_memento) {
123     __ CallRuntime(Runtime::kNewObjectWithAllocationSite, 3);
124   } else {
125     __ CallRuntime(Runtime::kNewObject, 2);
126   }
127   __ mov(ebx, eax);  // store result in ebx
128
129   // Runtime_NewObjectWithAllocationSite increments allocation count.
130   // Skip the increment.
131   if (create_memento) {
132     __ jmp(count_incremented);
133   } else {
134     __ jmp(allocated);
135   }
136 }
137
138
139 static void Generate_JSConstructStubHelper(MacroAssembler* masm,
140                                            bool is_api_function,
141                                            bool create_memento) {
142   // ----------- S t a t e -------------
143   //  -- eax: number of arguments
144   //  -- edi: constructor function
145   //  -- ebx: allocation site or undefined
146   //  -- edx: original constructor
147   // -----------------------------------
148
149   // Should never create mementos for api functions.
150   DCHECK(!is_api_function || !create_memento);
151
152   // Enter a construct frame.
153   {
154     FrameScope scope(masm, StackFrame::CONSTRUCT);
155
156     if (create_memento) {
157       __ AssertUndefinedOrAllocationSite(ebx);
158       __ push(ebx);
159     }
160
161     // Store a smi-tagged arguments count on the stack.
162     __ SmiTag(eax);
163     __ push(eax);
164
165     // Push the function to invoke on the stack.
166     __ push(edi);
167
168     __ cmp(edx, edi);
169     Label normal_new;
170     Label count_incremented;
171     Label allocated;
172     __ j(equal, &normal_new);
173
174     // Original constructor and function are different.
175     Generate_Runtime_NewObject(masm, create_memento, edx, &count_incremented,
176                                &allocated);
177     __ bind(&normal_new);
178
179     // Try to allocate the object without transitioning into C code. If any of
180     // the preconditions is not met, the code bails out to the runtime call.
181     Label rt_call;
182     if (FLAG_inline_new) {
183       Label undo_allocation;
184       ExternalReference debug_step_in_fp =
185           ExternalReference::debug_step_in_fp_address(masm->isolate());
186       __ cmp(Operand::StaticVariable(debug_step_in_fp), Immediate(0));
187       __ j(not_equal, &rt_call);
188
189       // Verified that the constructor is a JSFunction.
190       // Load the initial map and verify that it is in fact a map.
191       // edi: constructor
192       __ mov(eax, FieldOperand(edi, JSFunction::kPrototypeOrInitialMapOffset));
193       // Will both indicate a NULL and a Smi
194       __ JumpIfSmi(eax, &rt_call);
195       // edi: constructor
196       // eax: initial map (if proven valid below)
197       __ CmpObjectType(eax, MAP_TYPE, ebx);
198       __ j(not_equal, &rt_call);
199
200       // Check that the constructor is not constructing a JSFunction (see
201       // comments in Runtime_NewObject in runtime.cc). In which case the
202       // initial map's instance type would be JS_FUNCTION_TYPE.
203       // edi: constructor
204       // eax: initial map
205       __ CmpInstanceType(eax, JS_FUNCTION_TYPE);
206       __ j(equal, &rt_call);
207
208       if (!is_api_function) {
209         Label allocate;
210         // The code below relies on these assumptions.
211         STATIC_ASSERT(Map::Counter::kShift + Map::Counter::kSize == 32);
212         // Check if slack tracking is enabled.
213         __ mov(esi, FieldOperand(eax, Map::kBitField3Offset));
214         __ shr(esi, Map::Counter::kShift);
215         __ cmp(esi, Map::kSlackTrackingCounterEnd);
216         __ j(less, &allocate);
217         // Decrease generous allocation count.
218         __ sub(FieldOperand(eax, Map::kBitField3Offset),
219                Immediate(1 << Map::Counter::kShift));
220
221         __ cmp(esi, Map::kSlackTrackingCounterEnd);
222         __ j(not_equal, &allocate);
223
224         __ push(eax);
225         __ push(edi);
226
227         __ push(edi);  // constructor
228         __ CallRuntime(Runtime::kFinalizeInstanceSize, 1);
229
230         __ pop(edi);
231         __ pop(eax);
232         __ mov(esi, Map::kSlackTrackingCounterEnd - 1);
233
234         __ bind(&allocate);
235       }
236
237       // Now allocate the JSObject on the heap.
238       // edi: constructor
239       // eax: initial map
240       __ movzx_b(edi, FieldOperand(eax, Map::kInstanceSizeOffset));
241       __ shl(edi, kPointerSizeLog2);
242       if (create_memento) {
243         __ add(edi, Immediate(AllocationMemento::kSize));
244       }
245
246       __ Allocate(edi, ebx, edi, no_reg, &rt_call, NO_ALLOCATION_FLAGS);
247
248       Factory* factory = masm->isolate()->factory();
249
250       // Allocated the JSObject, now initialize the fields.
251       // eax: initial map
252       // ebx: JSObject
253       // edi: start of next object (including memento if create_memento)
254       __ mov(Operand(ebx, JSObject::kMapOffset), eax);
255       __ mov(ecx, factory->empty_fixed_array());
256       __ mov(Operand(ebx, JSObject::kPropertiesOffset), ecx);
257       __ mov(Operand(ebx, JSObject::kElementsOffset), ecx);
258       // Set extra fields in the newly allocated object.
259       // eax: initial map
260       // ebx: JSObject
261       // edi: start of next object (including memento if create_memento)
262       // esi: slack tracking counter (non-API function case)
263       __ mov(edx, factory->undefined_value());
264       __ lea(ecx, Operand(ebx, JSObject::kHeaderSize));
265       if (!is_api_function) {
266         Label no_inobject_slack_tracking;
267
268         // Check if slack tracking is enabled.
269         __ cmp(esi, Map::kSlackTrackingCounterEnd);
270         __ j(less, &no_inobject_slack_tracking);
271
272         // Allocate object with a slack.
273         __ movzx_b(esi,
274                    FieldOperand(eax, Map::kPreAllocatedPropertyFieldsOffset));
275         __ lea(esi,
276                Operand(ebx, esi, times_pointer_size, JSObject::kHeaderSize));
277         // esi: offset of first field after pre-allocated fields
278         if (FLAG_debug_code) {
279           __ cmp(esi, edi);
280           __ Assert(less_equal,
281                     kUnexpectedNumberOfPreAllocatedPropertyFields);
282         }
283         __ InitializeFieldsWithFiller(ecx, esi, edx);
284         __ mov(edx, factory->one_pointer_filler_map());
285         // Fill the remaining fields with one pointer filler map.
286
287         __ bind(&no_inobject_slack_tracking);
288       }
289
290       if (create_memento) {
291         __ lea(esi, Operand(edi, -AllocationMemento::kSize));
292         __ InitializeFieldsWithFiller(ecx, esi, edx);
293
294         // Fill in memento fields if necessary.
295         // esi: points to the allocated but uninitialized memento.
296         __ mov(Operand(esi, AllocationMemento::kMapOffset),
297                factory->allocation_memento_map());
298         // Get the cell or undefined.
299         __ mov(edx, Operand(esp, kPointerSize*2));
300         __ mov(Operand(esi, AllocationMemento::kAllocationSiteOffset),
301                edx);
302       } else {
303         __ InitializeFieldsWithFiller(ecx, edi, edx);
304       }
305
306       // Add the object tag to make the JSObject real, so that we can continue
307       // and jump into the continuation code at any time from now on. Any
308       // failures need to undo the allocation, so that the heap is in a
309       // consistent state and verifiable.
310       // eax: initial map
311       // ebx: JSObject
312       // edi: start of next object
313       __ or_(ebx, Immediate(kHeapObjectTag));
314
315       // Check if a non-empty properties array is needed.
316       // Allocate and initialize a FixedArray if it is.
317       // eax: initial map
318       // ebx: JSObject
319       // edi: start of next object
320       // Calculate the total number of properties described by the map.
321       __ movzx_b(edx, FieldOperand(eax, Map::kUnusedPropertyFieldsOffset));
322       __ movzx_b(ecx,
323                  FieldOperand(eax, Map::kPreAllocatedPropertyFieldsOffset));
324       __ add(edx, ecx);
325       // Calculate unused properties past the end of the in-object properties.
326       __ movzx_b(ecx, FieldOperand(eax, Map::kInObjectPropertiesOffset));
327       __ sub(edx, ecx);
328       // Done if no extra properties are to be allocated.
329       __ j(zero, &allocated);
330       __ Assert(positive, kPropertyAllocationCountFailed);
331
332       // Scale the number of elements by pointer size and add the header for
333       // FixedArrays to the start of the next object calculation from above.
334       // ebx: JSObject
335       // edi: start of next object (will be start of FixedArray)
336       // edx: number of elements in properties array
337       __ Allocate(FixedArray::kHeaderSize,
338                   times_pointer_size,
339                   edx,
340                   REGISTER_VALUE_IS_INT32,
341                   edi,
342                   ecx,
343                   no_reg,
344                   &undo_allocation,
345                   RESULT_CONTAINS_TOP);
346
347       // Initialize the FixedArray.
348       // ebx: JSObject
349       // edi: FixedArray
350       // edx: number of elements
351       // ecx: start of next object
352       __ mov(eax, factory->fixed_array_map());
353       __ mov(Operand(edi, FixedArray::kMapOffset), eax);  // setup the map
354       __ SmiTag(edx);
355       __ mov(Operand(edi, FixedArray::kLengthOffset), edx);  // and length
356
357       // Initialize the fields to undefined.
358       // ebx: JSObject
359       // edi: FixedArray
360       // ecx: start of next object
361       { Label loop, entry;
362         __ mov(edx, factory->undefined_value());
363         __ lea(eax, Operand(edi, FixedArray::kHeaderSize));
364         __ jmp(&entry);
365         __ bind(&loop);
366         __ mov(Operand(eax, 0), edx);
367         __ add(eax, Immediate(kPointerSize));
368         __ bind(&entry);
369         __ cmp(eax, ecx);
370         __ j(below, &loop);
371       }
372
373       // Store the initialized FixedArray into the properties field of
374       // the JSObject
375       // ebx: JSObject
376       // edi: FixedArray
377       __ or_(edi, Immediate(kHeapObjectTag));  // add the heap tag
378       __ mov(FieldOperand(ebx, JSObject::kPropertiesOffset), edi);
379
380
381       // Continue with JSObject being successfully allocated
382       // ebx: JSObject
383       __ jmp(&allocated);
384
385       // Undo the setting of the new top so that the heap is verifiable. For
386       // example, the map's unused properties potentially do not match the
387       // allocated objects unused properties.
388       // ebx: JSObject (previous new top)
389       __ bind(&undo_allocation);
390       __ UndoAllocationInNewSpace(ebx);
391     }
392
393     // Allocate the new receiver object using the runtime call.
394     __ bind(&rt_call);
395     Generate_Runtime_NewObject(masm, create_memento, edi, &count_incremented,
396                                &allocated);
397     // New object allocated.
398     // ebx: newly allocated object
399     __ bind(&allocated);
400
401     if (create_memento) {
402       __ mov(ecx, Operand(esp, kPointerSize * 2));
403       __ cmp(ecx, masm->isolate()->factory()->undefined_value());
404       __ j(equal, &count_incremented);
405       // ecx is an AllocationSite. We are creating a memento from it, so we
406       // need to increment the memento create count.
407       __ add(FieldOperand(ecx, AllocationSite::kPretenureCreateCountOffset),
408              Immediate(Smi::FromInt(1)));
409       __ bind(&count_incremented);
410     }
411
412     // Retrieve the function from the stack.
413     __ pop(edi);
414
415     // Retrieve smi-tagged arguments count from the stack.
416     __ mov(eax, Operand(esp, 0));
417     __ SmiUntag(eax);
418
419     // Push the allocated receiver to the stack. We need two copies
420     // because we may have to return the original one and the calling
421     // conventions dictate that the called function pops the receiver.
422     __ push(ebx);
423     __ push(ebx);
424
425     // Set up pointer to last argument.
426     __ lea(ebx, Operand(ebp, StandardFrameConstants::kCallerSPOffset));
427
428     // Copy arguments and receiver to the expression stack.
429     Label loop, entry;
430     __ mov(ecx, eax);
431     __ jmp(&entry);
432     __ bind(&loop);
433     __ push(Operand(ebx, ecx, times_4, 0));
434     __ bind(&entry);
435     __ dec(ecx);
436     __ j(greater_equal, &loop);
437
438     // Call the function.
439     if (is_api_function) {
440       __ mov(esi, FieldOperand(edi, JSFunction::kContextOffset));
441       Handle<Code> code =
442           masm->isolate()->builtins()->HandleApiCallConstruct();
443       __ call(code, RelocInfo::CODE_TARGET);
444     } else {
445       ParameterCount actual(eax);
446       __ InvokeFunction(edi, actual, CALL_FUNCTION,
447                         NullCallWrapper());
448     }
449
450     // Store offset of return address for deoptimizer.
451     if (!is_api_function) {
452       masm->isolate()->heap()->SetConstructStubDeoptPCOffset(masm->pc_offset());
453     }
454
455     // Restore context from the frame.
456     __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
457
458     // If the result is an object (in the ECMA sense), we should get rid
459     // of the receiver and use the result; see ECMA-262 section 13.2.2-7
460     // on page 74.
461     Label use_receiver, exit;
462
463     // If the result is a smi, it is *not* an object in the ECMA sense.
464     __ JumpIfSmi(eax, &use_receiver);
465
466     // If the type of the result (stored in its map) is less than
467     // FIRST_SPEC_OBJECT_TYPE, it is not an object in the ECMA sense.
468     __ CmpObjectType(eax, FIRST_SPEC_OBJECT_TYPE, ecx);
469     __ j(above_equal, &exit);
470
471     // Throw away the result of the constructor invocation and use the
472     // on-stack receiver as the result.
473     __ bind(&use_receiver);
474     __ mov(eax, Operand(esp, 0));
475
476     // Restore the arguments count and leave the construct frame.
477     __ bind(&exit);
478     __ mov(ebx, Operand(esp, kPointerSize));  // Get arguments count.
479
480     // Leave construct frame.
481   }
482
483   // Remove caller arguments from the stack and return.
484   STATIC_ASSERT(kSmiTagSize == 1 && kSmiTag == 0);
485   __ pop(ecx);
486   __ lea(esp, Operand(esp, ebx, times_2, 1 * kPointerSize));  // 1 ~ receiver
487   __ push(ecx);
488   __ IncrementCounter(masm->isolate()->counters()->constructed_objects(), 1);
489   __ ret(0);
490 }
491
492
493 void Builtins::Generate_JSConstructStubGeneric(MacroAssembler* masm) {
494   Generate_JSConstructStubHelper(masm, false, FLAG_pretenuring_call_new);
495 }
496
497
498 void Builtins::Generate_JSConstructStubApi(MacroAssembler* masm) {
499   Generate_JSConstructStubHelper(masm, true, false);
500 }
501
502
503 void Builtins::Generate_JSConstructStubForDerived(MacroAssembler* masm) {
504   // ----------- S t a t e -------------
505   //  -- eax: number of arguments
506   //  -- edi: constructor function
507   //  -- ebx: allocation site or undefined
508   //  -- edx: original constructor
509   // -----------------------------------
510
511   // TODO(dslomov): support pretenuring
512   CHECK(!FLAG_pretenuring_call_new);
513
514   {
515     FrameScope frame_scope(masm, StackFrame::CONSTRUCT);
516
517     // Preserve actual arguments count.
518     __ SmiTag(eax);
519     __ push(eax);
520     __ SmiUntag(eax);
521
522     // Push new.target.
523     __ push(edx);
524
525     // receiver is the hole.
526     __ push(Immediate(masm->isolate()->factory()->the_hole_value()));
527
528     // Set up pointer to last argument.
529     __ lea(ebx, Operand(ebp, StandardFrameConstants::kCallerSPOffset));
530
531     // Copy arguments and receiver to the expression stack.
532     Label loop, entry;
533     __ mov(ecx, eax);
534     __ jmp(&entry);
535     __ bind(&loop);
536     __ push(Operand(ebx, ecx, times_4, 0));
537     __ bind(&entry);
538     __ dec(ecx);
539     __ j(greater_equal, &loop);
540
541     __ inc(eax);  // Pushed new.target.
542
543
544     // Handle step in.
545     Label skip_step_in;
546     ExternalReference debug_step_in_fp =
547         ExternalReference::debug_step_in_fp_address(masm->isolate());
548     __ cmp(Operand::StaticVariable(debug_step_in_fp), Immediate(0));
549     __ j(equal, &skip_step_in);
550
551     __ push(eax);
552     __ push(edi);
553     __ push(edi);
554     __ CallRuntime(Runtime::kHandleStepInForDerivedConstructors, 1);
555     __ pop(edi);
556     __ pop(eax);
557
558     __ bind(&skip_step_in);
559
560     // Invoke function.
561     ParameterCount actual(eax);
562     __ InvokeFunction(edi, actual, CALL_FUNCTION, NullCallWrapper());
563
564     // Restore context from the frame.
565     __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
566
567     __ mov(ebx, Operand(esp, 0));
568   }
569
570   __ pop(ecx);  // Return address.
571   __ lea(esp, Operand(esp, ebx, times_2, 1 * kPointerSize));
572   __ push(ecx);
573   __ ret(0);
574 }
575
576
577 static void Generate_JSEntryTrampolineHelper(MacroAssembler* masm,
578                                              bool is_construct) {
579   ProfileEntryHookStub::MaybeCallEntryHook(masm);
580
581   // Clear the context before we push it when entering the internal frame.
582   __ Move(esi, Immediate(0));
583
584   {
585     FrameScope scope(masm, StackFrame::INTERNAL);
586
587     // Load the previous frame pointer (ebx) to access C arguments
588     __ mov(ebx, Operand(ebp, 0));
589
590     // Get the function from the frame and setup the context.
591     __ mov(ecx, Operand(ebx, EntryFrameConstants::kFunctionArgOffset));
592     __ mov(esi, FieldOperand(ecx, JSFunction::kContextOffset));
593
594     // Push the function and the receiver onto the stack.
595     __ push(ecx);
596     __ push(Operand(ebx, EntryFrameConstants::kReceiverArgOffset));
597
598     // Load the number of arguments and setup pointer to the arguments.
599     __ mov(eax, Operand(ebx, EntryFrameConstants::kArgcOffset));
600     __ mov(ebx, Operand(ebx, EntryFrameConstants::kArgvOffset));
601
602     // Copy arguments to the stack in a loop.
603     Label loop, entry;
604     __ Move(ecx, Immediate(0));
605     __ jmp(&entry);
606     __ bind(&loop);
607     __ mov(edx, Operand(ebx, ecx, times_4, 0));  // push parameter from argv
608     __ push(Operand(edx, 0));  // dereference handle
609     __ inc(ecx);
610     __ bind(&entry);
611     __ cmp(ecx, eax);
612     __ j(not_equal, &loop);
613
614     // Get the function from the stack and call it.
615     // kPointerSize for the receiver.
616     __ mov(edi, Operand(esp, eax, times_4, kPointerSize));
617
618     // Invoke the code.
619     if (is_construct) {
620       // No type feedback cell is available
621       __ mov(ebx, masm->isolate()->factory()->undefined_value());
622       CallConstructStub stub(masm->isolate(), NO_CALL_CONSTRUCTOR_FLAGS);
623       __ CallStub(&stub);
624     } else {
625       ParameterCount actual(eax);
626       __ InvokeFunction(edi, actual, CALL_FUNCTION,
627                         NullCallWrapper());
628     }
629
630     // Exit the internal frame. Notice that this also removes the empty.
631     // context and the function left on the stack by the code
632     // invocation.
633   }
634   __ ret(kPointerSize);  // Remove receiver.
635 }
636
637
638 void Builtins::Generate_JSEntryTrampoline(MacroAssembler* masm) {
639   Generate_JSEntryTrampolineHelper(masm, false);
640 }
641
642
643 void Builtins::Generate_JSConstructEntryTrampoline(MacroAssembler* masm) {
644   Generate_JSEntryTrampolineHelper(masm, true);
645 }
646
647
648 void Builtins::Generate_CompileLazy(MacroAssembler* masm) {
649   CallRuntimePassFunction(masm, Runtime::kCompileLazy);
650   GenerateTailCallToReturnedCode(masm);
651 }
652
653
654
655 static void CallCompileOptimized(MacroAssembler* masm, bool concurrent) {
656   FrameScope scope(masm, StackFrame::INTERNAL);
657   // Push a copy of the function.
658   __ push(edi);
659   // Function is also the parameter to the runtime call.
660   __ push(edi);
661   // Whether to compile in a background thread.
662   __ Push(masm->isolate()->factory()->ToBoolean(concurrent));
663
664   __ CallRuntime(Runtime::kCompileOptimized, 2);
665   // Restore receiver.
666   __ pop(edi);
667 }
668
669
670 void Builtins::Generate_CompileOptimized(MacroAssembler* masm) {
671   CallCompileOptimized(masm, false);
672   GenerateTailCallToReturnedCode(masm);
673 }
674
675
676 void Builtins::Generate_CompileOptimizedConcurrent(MacroAssembler* masm) {
677   CallCompileOptimized(masm, true);
678   GenerateTailCallToReturnedCode(masm);
679 }
680
681
682 static void GenerateMakeCodeYoungAgainCommon(MacroAssembler* masm) {
683   // For now, we are relying on the fact that make_code_young doesn't do any
684   // garbage collection which allows us to save/restore the registers without
685   // worrying about which of them contain pointers. We also don't build an
686   // internal frame to make the code faster, since we shouldn't have to do stack
687   // crawls in MakeCodeYoung. This seems a bit fragile.
688
689   // Re-execute the code that was patched back to the young age when
690   // the stub returns.
691   __ sub(Operand(esp, 0), Immediate(5));
692   __ pushad();
693   __ mov(eax, Operand(esp, 8 * kPointerSize));
694   {
695     FrameScope scope(masm, StackFrame::MANUAL);
696     __ PrepareCallCFunction(2, ebx);
697     __ mov(Operand(esp, 1 * kPointerSize),
698            Immediate(ExternalReference::isolate_address(masm->isolate())));
699     __ mov(Operand(esp, 0), eax);
700     __ CallCFunction(
701         ExternalReference::get_make_code_young_function(masm->isolate()), 2);
702   }
703   __ popad();
704   __ ret(0);
705 }
706
707 #define DEFINE_CODE_AGE_BUILTIN_GENERATOR(C)                 \
708 void Builtins::Generate_Make##C##CodeYoungAgainEvenMarking(  \
709     MacroAssembler* masm) {                                  \
710   GenerateMakeCodeYoungAgainCommon(masm);                    \
711 }                                                            \
712 void Builtins::Generate_Make##C##CodeYoungAgainOddMarking(   \
713     MacroAssembler* masm) {                                  \
714   GenerateMakeCodeYoungAgainCommon(masm);                    \
715 }
716 CODE_AGE_LIST(DEFINE_CODE_AGE_BUILTIN_GENERATOR)
717 #undef DEFINE_CODE_AGE_BUILTIN_GENERATOR
718
719
720 void Builtins::Generate_MarkCodeAsExecutedOnce(MacroAssembler* masm) {
721   // For now, as in GenerateMakeCodeYoungAgainCommon, we are relying on the fact
722   // that make_code_young doesn't do any garbage collection which allows us to
723   // save/restore the registers without worrying about which of them contain
724   // pointers.
725   __ pushad();
726   __ mov(eax, Operand(esp, 8 * kPointerSize));
727   __ sub(eax, Immediate(Assembler::kCallInstructionLength));
728   {  // NOLINT
729     FrameScope scope(masm, StackFrame::MANUAL);
730     __ PrepareCallCFunction(2, ebx);
731     __ mov(Operand(esp, 1 * kPointerSize),
732            Immediate(ExternalReference::isolate_address(masm->isolate())));
733     __ mov(Operand(esp, 0), eax);
734     __ CallCFunction(
735         ExternalReference::get_mark_code_as_executed_function(masm->isolate()),
736         2);
737   }
738   __ popad();
739
740   // Perform prologue operations usually performed by the young code stub.
741   __ pop(eax);   // Pop return address into scratch register.
742   __ push(ebp);  // Caller's frame pointer.
743   __ mov(ebp, esp);
744   __ push(esi);  // Callee's context.
745   __ push(edi);  // Callee's JS Function.
746   __ push(eax);  // Push return address after frame prologue.
747
748   // Jump to point after the code-age stub.
749   __ ret(0);
750 }
751
752
753 void Builtins::Generate_MarkCodeAsExecutedTwice(MacroAssembler* masm) {
754   GenerateMakeCodeYoungAgainCommon(masm);
755 }
756
757
758 static void Generate_NotifyStubFailureHelper(MacroAssembler* masm,
759                                              SaveFPRegsMode save_doubles) {
760   // Enter an internal frame.
761   {
762     FrameScope scope(masm, StackFrame::INTERNAL);
763
764     // Preserve registers across notification, this is important for compiled
765     // stubs that tail call the runtime on deopts passing their parameters in
766     // registers.
767     __ pushad();
768     __ CallRuntime(Runtime::kNotifyStubFailure, 0, save_doubles);
769     __ popad();
770     // Tear down internal frame.
771   }
772
773   __ pop(MemOperand(esp, 0));  // Ignore state offset
774   __ ret(0);  // Return to IC Miss stub, continuation still on stack.
775 }
776
777
778 void Builtins::Generate_NotifyStubFailure(MacroAssembler* masm) {
779   Generate_NotifyStubFailureHelper(masm, kDontSaveFPRegs);
780 }
781
782
783 void Builtins::Generate_NotifyStubFailureSaveDoubles(MacroAssembler* masm) {
784   Generate_NotifyStubFailureHelper(masm, kSaveFPRegs);
785 }
786
787
788 static void Generate_NotifyDeoptimizedHelper(MacroAssembler* masm,
789                                              Deoptimizer::BailoutType type) {
790   {
791     FrameScope scope(masm, StackFrame::INTERNAL);
792
793     // Pass deoptimization type to the runtime system.
794     __ push(Immediate(Smi::FromInt(static_cast<int>(type))));
795     __ CallRuntime(Runtime::kNotifyDeoptimized, 1);
796
797     // Tear down internal frame.
798   }
799
800   // Get the full codegen state from the stack and untag it.
801   __ mov(ecx, Operand(esp, 1 * kPointerSize));
802   __ SmiUntag(ecx);
803
804   // Switch on the state.
805   Label not_no_registers, not_tos_eax;
806   __ cmp(ecx, FullCodeGenerator::NO_REGISTERS);
807   __ j(not_equal, &not_no_registers, Label::kNear);
808   __ ret(1 * kPointerSize);  // Remove state.
809
810   __ bind(&not_no_registers);
811   __ mov(eax, Operand(esp, 2 * kPointerSize));
812   __ cmp(ecx, FullCodeGenerator::TOS_REG);
813   __ j(not_equal, &not_tos_eax, Label::kNear);
814   __ ret(2 * kPointerSize);  // Remove state, eax.
815
816   __ bind(&not_tos_eax);
817   __ Abort(kNoCasesLeft);
818 }
819
820
821 void Builtins::Generate_NotifyDeoptimized(MacroAssembler* masm) {
822   Generate_NotifyDeoptimizedHelper(masm, Deoptimizer::EAGER);
823 }
824
825
826 void Builtins::Generate_NotifySoftDeoptimized(MacroAssembler* masm) {
827   Generate_NotifyDeoptimizedHelper(masm, Deoptimizer::SOFT);
828 }
829
830
831 void Builtins::Generate_NotifyLazyDeoptimized(MacroAssembler* masm) {
832   Generate_NotifyDeoptimizedHelper(masm, Deoptimizer::LAZY);
833 }
834
835
836 void Builtins::Generate_FunctionCall(MacroAssembler* masm) {
837   Factory* factory = masm->isolate()->factory();
838
839   // 1. Make sure we have at least one argument.
840   { Label done;
841     __ test(eax, eax);
842     __ j(not_zero, &done);
843     __ pop(ebx);
844     __ push(Immediate(factory->undefined_value()));
845     __ push(ebx);
846     __ inc(eax);
847     __ bind(&done);
848   }
849
850   // 2. Get the function to call (passed as receiver) from the stack, check
851   //    if it is a function.
852   Label slow, non_function;
853   // 1 ~ return address.
854   __ mov(edi, Operand(esp, eax, times_4, 1 * kPointerSize));
855   __ JumpIfSmi(edi, &non_function);
856   __ CmpObjectType(edi, JS_FUNCTION_TYPE, ecx);
857   __ j(not_equal, &slow);
858
859
860   // 3a. Patch the first argument if necessary when calling a function.
861   Label shift_arguments;
862   __ Move(edx, Immediate(0));  // indicate regular JS_FUNCTION
863   { Label convert_to_object, use_global_proxy, patch_receiver;
864     // Change context eagerly in case we need the global receiver.
865     __ mov(esi, FieldOperand(edi, JSFunction::kContextOffset));
866
867     // Do not transform the receiver for strict mode functions.
868     __ mov(ebx, FieldOperand(edi, JSFunction::kSharedFunctionInfoOffset));
869     __ test_b(FieldOperand(ebx, SharedFunctionInfo::kStrictModeByteOffset),
870               1 << SharedFunctionInfo::kStrictModeBitWithinByte);
871     __ j(not_equal, &shift_arguments);
872
873     // Do not transform the receiver for natives (shared already in ebx).
874     __ test_b(FieldOperand(ebx, SharedFunctionInfo::kNativeByteOffset),
875               1 << SharedFunctionInfo::kNativeBitWithinByte);
876     __ j(not_equal, &shift_arguments);
877
878     // Compute the receiver in sloppy mode.
879     __ mov(ebx, Operand(esp, eax, times_4, 0));  // First argument.
880
881     // Call ToObject on the receiver if it is not an object, or use the
882     // global object if it is null or undefined.
883     __ JumpIfSmi(ebx, &convert_to_object);
884     __ cmp(ebx, factory->null_value());
885     __ j(equal, &use_global_proxy);
886     __ cmp(ebx, factory->undefined_value());
887     __ j(equal, &use_global_proxy);
888     STATIC_ASSERT(LAST_SPEC_OBJECT_TYPE == LAST_TYPE);
889     __ CmpObjectType(ebx, FIRST_SPEC_OBJECT_TYPE, ecx);
890     __ j(above_equal, &shift_arguments);
891
892     __ bind(&convert_to_object);
893
894     { // In order to preserve argument count.
895       FrameScope scope(masm, StackFrame::INTERNAL);
896       __ SmiTag(eax);
897       __ push(eax);
898
899       __ push(ebx);
900       __ InvokeBuiltin(Builtins::TO_OBJECT, CALL_FUNCTION);
901       __ mov(ebx, eax);
902       __ Move(edx, Immediate(0));  // restore
903
904       __ pop(eax);
905       __ SmiUntag(eax);
906     }
907
908     // Restore the function to edi.
909     __ mov(edi, Operand(esp, eax, times_4, 1 * kPointerSize));
910     __ jmp(&patch_receiver);
911
912     __ bind(&use_global_proxy);
913     __ mov(ebx,
914            Operand(esi, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
915     __ mov(ebx, FieldOperand(ebx, GlobalObject::kGlobalProxyOffset));
916
917     __ bind(&patch_receiver);
918     __ mov(Operand(esp, eax, times_4, 0), ebx);
919
920     __ jmp(&shift_arguments);
921   }
922
923   // 3b. Check for function proxy.
924   __ bind(&slow);
925   __ Move(edx, Immediate(1));  // indicate function proxy
926   __ CmpInstanceType(ecx, JS_FUNCTION_PROXY_TYPE);
927   __ j(equal, &shift_arguments);
928   __ bind(&non_function);
929   __ Move(edx, Immediate(2));  // indicate non-function
930
931   // 3c. Patch the first argument when calling a non-function.  The
932   //     CALL_NON_FUNCTION builtin expects the non-function callee as
933   //     receiver, so overwrite the first argument which will ultimately
934   //     become the receiver.
935   __ mov(Operand(esp, eax, times_4, 0), edi);
936
937   // 4. Shift arguments and return address one slot down on the stack
938   //    (overwriting the original receiver).  Adjust argument count to make
939   //    the original first argument the new receiver.
940   __ bind(&shift_arguments);
941   { Label loop;
942     __ mov(ecx, eax);
943     __ bind(&loop);
944     __ mov(ebx, Operand(esp, ecx, times_4, 0));
945     __ mov(Operand(esp, ecx, times_4, kPointerSize), ebx);
946     __ dec(ecx);
947     __ j(not_sign, &loop);  // While non-negative (to copy return address).
948     __ pop(ebx);  // Discard copy of return address.
949     __ dec(eax);  // One fewer argument (first argument is new receiver).
950   }
951
952   // 5a. Call non-function via tail call to CALL_NON_FUNCTION builtin,
953   //     or a function proxy via CALL_FUNCTION_PROXY.
954   { Label function, non_proxy;
955     __ test(edx, edx);
956     __ j(zero, &function);
957     __ Move(ebx, Immediate(0));
958     __ cmp(edx, Immediate(1));
959     __ j(not_equal, &non_proxy);
960
961     __ pop(edx);   // return address
962     __ push(edi);  // re-add proxy object as additional argument
963     __ push(edx);
964     __ inc(eax);
965     __ GetBuiltinEntry(edx, Builtins::CALL_FUNCTION_PROXY);
966     __ jmp(masm->isolate()->builtins()->ArgumentsAdaptorTrampoline(),
967            RelocInfo::CODE_TARGET);
968
969     __ bind(&non_proxy);
970     __ GetBuiltinEntry(edx, Builtins::CALL_NON_FUNCTION);
971     __ jmp(masm->isolate()->builtins()->ArgumentsAdaptorTrampoline(),
972            RelocInfo::CODE_TARGET);
973     __ bind(&function);
974   }
975
976   // 5b. Get the code to call from the function and check that the number of
977   //     expected arguments matches what we're providing.  If so, jump
978   //     (tail-call) to the code in register edx without checking arguments.
979   __ mov(edx, FieldOperand(edi, JSFunction::kSharedFunctionInfoOffset));
980   __ mov(ebx,
981          FieldOperand(edx, SharedFunctionInfo::kFormalParameterCountOffset));
982   __ mov(edx, FieldOperand(edi, JSFunction::kCodeEntryOffset));
983   __ SmiUntag(ebx);
984   __ cmp(eax, ebx);
985   __ j(not_equal,
986        masm->isolate()->builtins()->ArgumentsAdaptorTrampoline());
987
988   ParameterCount expected(0);
989   __ InvokeCode(edx, expected, expected, JUMP_FUNCTION, NullCallWrapper());
990 }
991
992
993 static void Generate_CheckStackOverflow(MacroAssembler* masm,
994                                         const int calleeOffset) {
995   // eax   : the number of items to be pushed to the stack
996   //
997   // Check the stack for overflow. We are not trying to catch
998   // interruptions (e.g. debug break and preemption) here, so the "real stack
999   // limit" is checked.
1000   Label okay;
1001   ExternalReference real_stack_limit =
1002       ExternalReference::address_of_real_stack_limit(masm->isolate());
1003   __ mov(edi, Operand::StaticVariable(real_stack_limit));
1004   // Make ecx the space we have left. The stack might already be overflowed
1005   // here which will cause ecx to become negative.
1006   __ mov(ecx, esp);
1007   __ sub(ecx, edi);
1008   // Make edx the space we need for the array when it is unrolled onto the
1009   // stack.
1010   __ mov(edx, eax);
1011   __ shl(edx, kPointerSizeLog2 - kSmiTagSize);
1012   // Check if the arguments will overflow the stack.
1013   __ cmp(ecx, edx);
1014   __ j(greater, &okay);  // Signed comparison.
1015
1016   // Out of stack space.
1017   __ push(Operand(ebp, calleeOffset));  // push this
1018   __ push(eax);
1019   __ InvokeBuiltin(Builtins::STACK_OVERFLOW, CALL_FUNCTION);
1020
1021   __ bind(&okay);
1022 }
1023
1024
1025 static void Generate_PushAppliedArguments(MacroAssembler* masm,
1026                                           const int argumentsOffset,
1027                                           const int indexOffset,
1028                                           const int limitOffset) {
1029   // Copy all arguments from the array to the stack.
1030   Label entry, loop;
1031   Register receiver = LoadDescriptor::ReceiverRegister();
1032   Register key = LoadDescriptor::NameRegister();
1033   __ mov(key, Operand(ebp, indexOffset));
1034   __ jmp(&entry);
1035   __ bind(&loop);
1036   __ mov(receiver, Operand(ebp, argumentsOffset));  // load arguments
1037
1038   if (FLAG_vector_ics) {
1039     // TODO(mvstanton): Vector-based ics need additional infrastructure to
1040     // be embedded here. For now, just call the runtime.
1041     __ push(receiver);
1042     __ push(key);
1043     __ CallRuntime(Runtime::kGetProperty, 2);
1044   } else {
1045     // Use inline caching to speed up access to arguments.
1046     Handle<Code> ic = CodeFactory::KeyedLoadIC(masm->isolate()).code();
1047     __ call(ic, RelocInfo::CODE_TARGET);
1048     // It is important that we do not have a test instruction after the
1049     // call.  A test instruction after the call is used to indicate that
1050     // we have generated an inline version of the keyed load.  In this
1051     // case, we know that we are not generating a test instruction next.
1052   }
1053
1054   // Push the nth argument.
1055   __ push(eax);
1056
1057   // Update the index on the stack and in register key.
1058   __ mov(key, Operand(ebp, indexOffset));
1059   __ add(key, Immediate(1 << kSmiTagSize));
1060   __ mov(Operand(ebp, indexOffset), key);
1061
1062   __ bind(&entry);
1063   __ cmp(key, Operand(ebp, limitOffset));
1064   __ j(not_equal, &loop);
1065
1066   // On exit, the pushed arguments count is in eax, untagged
1067   __ Move(eax, key);
1068   __ SmiUntag(eax);
1069 }
1070
1071
1072 // Used by FunctionApply and ReflectApply
1073 static void Generate_ApplyHelper(MacroAssembler* masm, bool targetIsArgument) {
1074   const int kFormalParameters = targetIsArgument ? 3 : 2;
1075   const int kStackSize = kFormalParameters + 1;
1076
1077   // Stack at entry:
1078   // esp     : return address
1079   // esp[4]  : arguments
1080   // esp[8]  : receiver ("this")
1081   // esp[12] : function
1082   {
1083     FrameScope frame_scope(masm, StackFrame::INTERNAL);
1084     // Stack frame:
1085     // ebp     : Old base pointer
1086     // ebp[4]  : return address
1087     // ebp[8]  : function arguments
1088     // ebp[12] : receiver
1089     // ebp[16] : function
1090     static const int kArgumentsOffset = kFPOnStackSize + kPCOnStackSize;
1091     static const int kReceiverOffset = kArgumentsOffset + kPointerSize;
1092     static const int kFunctionOffset = kReceiverOffset + kPointerSize;
1093
1094     __ push(Operand(ebp, kFunctionOffset));  // push this
1095     __ push(Operand(ebp, kArgumentsOffset));  // push arguments
1096     if (targetIsArgument) {
1097       __ InvokeBuiltin(Builtins::REFLECT_APPLY_PREPARE, CALL_FUNCTION);
1098     } else {
1099       __ InvokeBuiltin(Builtins::APPLY_PREPARE, CALL_FUNCTION);
1100     }
1101
1102     Generate_CheckStackOverflow(masm, kFunctionOffset);
1103
1104     // Push current index and limit.
1105     const int kLimitOffset =
1106         StandardFrameConstants::kExpressionsOffset - 1 * kPointerSize;
1107     const int kIndexOffset = kLimitOffset - 1 * kPointerSize;
1108     __ push(eax);  // limit
1109     __ push(Immediate(0));  // index
1110
1111     // Get the receiver.
1112     __ mov(ebx, Operand(ebp, kReceiverOffset));
1113
1114     // Check that the function is a JS function (otherwise it must be a proxy).
1115     Label push_receiver, use_global_proxy;
1116     __ mov(edi, Operand(ebp, kFunctionOffset));
1117     __ CmpObjectType(edi, JS_FUNCTION_TYPE, ecx);
1118     __ j(not_equal, &push_receiver);
1119
1120     // Change context eagerly to get the right global object if necessary.
1121     __ mov(esi, FieldOperand(edi, JSFunction::kContextOffset));
1122
1123     // Compute the receiver.
1124     // Do not transform the receiver for strict mode functions.
1125     Label call_to_object;
1126     __ mov(ecx, FieldOperand(edi, JSFunction::kSharedFunctionInfoOffset));
1127     __ test_b(FieldOperand(ecx, SharedFunctionInfo::kStrictModeByteOffset),
1128               1 << SharedFunctionInfo::kStrictModeBitWithinByte);
1129     __ j(not_equal, &push_receiver);
1130
1131     Factory* factory = masm->isolate()->factory();
1132
1133     // Do not transform the receiver for natives (shared already in ecx).
1134     __ test_b(FieldOperand(ecx, SharedFunctionInfo::kNativeByteOffset),
1135               1 << SharedFunctionInfo::kNativeBitWithinByte);
1136     __ j(not_equal, &push_receiver);
1137
1138     // Compute the receiver in sloppy mode.
1139     // Call ToObject on the receiver if it is not an object, or use the
1140     // global object if it is null or undefined.
1141     __ JumpIfSmi(ebx, &call_to_object);
1142     __ cmp(ebx, factory->null_value());
1143     __ j(equal, &use_global_proxy);
1144     __ cmp(ebx, factory->undefined_value());
1145     __ j(equal, &use_global_proxy);
1146     STATIC_ASSERT(LAST_SPEC_OBJECT_TYPE == LAST_TYPE);
1147     __ CmpObjectType(ebx, FIRST_SPEC_OBJECT_TYPE, ecx);
1148     __ j(above_equal, &push_receiver);
1149
1150     __ bind(&call_to_object);
1151     __ push(ebx);
1152     __ InvokeBuiltin(Builtins::TO_OBJECT, CALL_FUNCTION);
1153     __ mov(ebx, eax);
1154     __ jmp(&push_receiver);
1155
1156     __ bind(&use_global_proxy);
1157     __ mov(ebx,
1158            Operand(esi, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
1159     __ mov(ebx, FieldOperand(ebx, GlobalObject::kGlobalProxyOffset));
1160
1161     // Push the receiver.
1162     __ bind(&push_receiver);
1163     __ push(ebx);
1164
1165     // Loop over the arguments array, pushing each value to the stack
1166     Generate_PushAppliedArguments(
1167         masm, kArgumentsOffset, kIndexOffset, kLimitOffset);
1168
1169     // Call the function.
1170     Label call_proxy;
1171     ParameterCount actual(eax);
1172     __ mov(edi, Operand(ebp, kFunctionOffset));
1173     __ CmpObjectType(edi, JS_FUNCTION_TYPE, ecx);
1174     __ j(not_equal, &call_proxy);
1175     __ InvokeFunction(edi, actual, CALL_FUNCTION, NullCallWrapper());
1176
1177     frame_scope.GenerateLeaveFrame();
1178     __ ret(kStackSize * kPointerSize);  // remove this, receiver, and arguments
1179
1180     // Call the function proxy.
1181     __ bind(&call_proxy);
1182     __ push(edi);  // add function proxy as last argument
1183     __ inc(eax);
1184     __ Move(ebx, Immediate(0));
1185     __ GetBuiltinEntry(edx, Builtins::CALL_FUNCTION_PROXY);
1186     __ call(masm->isolate()->builtins()->ArgumentsAdaptorTrampoline(),
1187             RelocInfo::CODE_TARGET);
1188
1189     // Leave internal frame.
1190   }
1191   __ ret(kStackSize * kPointerSize);  // remove this, receiver, and arguments
1192 }
1193
1194
1195 // Used by ReflectConstruct
1196 static void Generate_ConstructHelper(MacroAssembler* masm) {
1197   const int kFormalParameters = 3;
1198   const int kStackSize = kFormalParameters + 1;
1199
1200   // Stack at entry:
1201   // esp     : return address
1202   // esp[4]  : original constructor (new.target)
1203   // esp[8]  : arguments
1204   // esp[16] : constructor
1205   {
1206     FrameScope frame_scope(masm, StackFrame::INTERNAL);
1207     // Stack frame:
1208     // ebp     : Old base pointer
1209     // ebp[4]  : return address
1210     // ebp[8]  : original constructor (new.target)
1211     // ebp[12] : arguments
1212     // ebp[16] : constructor
1213     static const int kNewTargetOffset = kFPOnStackSize + kPCOnStackSize;
1214     static const int kArgumentsOffset = kNewTargetOffset + kPointerSize;
1215     static const int kFunctionOffset = kArgumentsOffset + kPointerSize;
1216
1217     // If newTarget is not supplied, set it to constructor
1218     Label validate_arguments;
1219     __ mov(eax, Operand(ebp, kNewTargetOffset));
1220     __ CompareRoot(eax, Heap::kUndefinedValueRootIndex);
1221     __ j(not_equal, &validate_arguments, Label::kNear);
1222     __ mov(eax, Operand(ebp, kFunctionOffset));
1223     __ mov(Operand(ebp, kNewTargetOffset), eax);
1224
1225     // Validate arguments
1226     __ bind(&validate_arguments);
1227     __ push(Operand(ebp, kFunctionOffset));
1228     __ push(Operand(ebp, kArgumentsOffset));
1229     __ push(Operand(ebp, kNewTargetOffset));
1230     __ InvokeBuiltin(Builtins::REFLECT_CONSTRUCT_PREPARE, CALL_FUNCTION);
1231
1232     Generate_CheckStackOverflow(masm, kFunctionOffset);
1233
1234     // Push current index and limit.
1235     const int kLimitOffset =
1236         StandardFrameConstants::kExpressionsOffset - 1 * kPointerSize;
1237     const int kIndexOffset = kLimitOffset - 1 * kPointerSize;
1238     __ Push(eax);  // limit
1239     __ push(Immediate(0));  // index
1240     // Push newTarget and callee functions
1241     __ push(Operand(ebp, kNewTargetOffset));
1242     __ push(Operand(ebp, kFunctionOffset));
1243
1244     // Loop over the arguments array, pushing each value to the stack
1245     Generate_PushAppliedArguments(
1246         masm, kArgumentsOffset, kIndexOffset, kLimitOffset);
1247
1248     // Use undefined feedback vector
1249     __ LoadRoot(ebx, Heap::kUndefinedValueRootIndex);
1250     __ mov(edi, Operand(ebp, kFunctionOffset));
1251
1252     // Call the function.
1253     CallConstructStub stub(masm->isolate(), SUPER_CONSTRUCTOR_CALL);
1254     __ call(stub.GetCode(), RelocInfo::CONSTRUCT_CALL);
1255
1256     __ Drop(1);
1257
1258     // Leave internal frame.
1259   }
1260   // remove this, target, arguments, and newTarget
1261   __ ret(kStackSize * kPointerSize);
1262 }
1263
1264
1265 void Builtins::Generate_FunctionApply(MacroAssembler* masm) {
1266   Generate_ApplyHelper(masm, false);
1267 }
1268
1269
1270 void Builtins::Generate_ReflectApply(MacroAssembler* masm) {
1271   Generate_ApplyHelper(masm, true);
1272 }
1273
1274
1275 void Builtins::Generate_ReflectConstruct(MacroAssembler* masm) {
1276   Generate_ConstructHelper(masm);
1277 }
1278
1279
1280 void Builtins::Generate_InternalArrayCode(MacroAssembler* masm) {
1281   // ----------- S t a t e -------------
1282   //  -- eax : argc
1283   //  -- esp[0] : return address
1284   //  -- esp[4] : last argument
1285   // -----------------------------------
1286   Label generic_array_code;
1287
1288   // Get the InternalArray function.
1289   __ LoadGlobalFunction(Context::INTERNAL_ARRAY_FUNCTION_INDEX, edi);
1290
1291   if (FLAG_debug_code) {
1292     // Initial map for the builtin InternalArray function should be a map.
1293     __ mov(ebx, FieldOperand(edi, JSFunction::kPrototypeOrInitialMapOffset));
1294     // Will both indicate a NULL and a Smi.
1295     __ test(ebx, Immediate(kSmiTagMask));
1296     __ Assert(not_zero, kUnexpectedInitialMapForInternalArrayFunction);
1297     __ CmpObjectType(ebx, MAP_TYPE, ecx);
1298     __ Assert(equal, kUnexpectedInitialMapForInternalArrayFunction);
1299   }
1300
1301   // Run the native code for the InternalArray function called as a normal
1302   // function.
1303   // tail call a stub
1304   InternalArrayConstructorStub stub(masm->isolate());
1305   __ TailCallStub(&stub);
1306 }
1307
1308
1309 void Builtins::Generate_ArrayCode(MacroAssembler* masm) {
1310   // ----------- S t a t e -------------
1311   //  -- eax : argc
1312   //  -- esp[0] : return address
1313   //  -- esp[4] : last argument
1314   // -----------------------------------
1315   Label generic_array_code;
1316
1317   // Get the Array function.
1318   __ LoadGlobalFunction(Context::ARRAY_FUNCTION_INDEX, edi);
1319   __ mov(edx, edi);
1320
1321   if (FLAG_debug_code) {
1322     // Initial map for the builtin Array function should be a map.
1323     __ mov(ebx, FieldOperand(edi, JSFunction::kPrototypeOrInitialMapOffset));
1324     // Will both indicate a NULL and a Smi.
1325     __ test(ebx, Immediate(kSmiTagMask));
1326     __ Assert(not_zero, kUnexpectedInitialMapForArrayFunction);
1327     __ CmpObjectType(ebx, MAP_TYPE, ecx);
1328     __ Assert(equal, kUnexpectedInitialMapForArrayFunction);
1329   }
1330
1331   // Run the native code for the Array function called as a normal function.
1332   // tail call a stub
1333   __ mov(ebx, masm->isolate()->factory()->undefined_value());
1334   ArrayConstructorStub stub(masm->isolate());
1335   __ TailCallStub(&stub);
1336 }
1337
1338
1339 void Builtins::Generate_StringConstructCode(MacroAssembler* masm) {
1340   // ----------- S t a t e -------------
1341   //  -- eax                 : number of arguments
1342   //  -- edi                 : constructor function
1343   //  -- esp[0]              : return address
1344   //  -- esp[(argc - n) * 4] : arg[n] (zero-based)
1345   //  -- esp[(argc + 1) * 4] : receiver
1346   // -----------------------------------
1347   Counters* counters = masm->isolate()->counters();
1348   __ IncrementCounter(counters->string_ctor_calls(), 1);
1349
1350   if (FLAG_debug_code) {
1351     __ LoadGlobalFunction(Context::STRING_FUNCTION_INDEX, ecx);
1352     __ cmp(edi, ecx);
1353     __ Assert(equal, kUnexpectedStringFunction);
1354   }
1355
1356   // Load the first argument into eax and get rid of the rest
1357   // (including the receiver).
1358   Label no_arguments;
1359   __ test(eax, eax);
1360   __ j(zero, &no_arguments);
1361   __ mov(ebx, Operand(esp, eax, times_pointer_size, 0));
1362   __ pop(ecx);
1363   __ lea(esp, Operand(esp, eax, times_pointer_size, kPointerSize));
1364   __ push(ecx);
1365   __ mov(eax, ebx);
1366
1367   // Lookup the argument in the number to string cache.
1368   Label not_cached, argument_is_string;
1369   __ LookupNumberStringCache(eax,  // Input.
1370                              ebx,  // Result.
1371                              ecx,  // Scratch 1.
1372                              edx,  // Scratch 2.
1373                              &not_cached);
1374   __ IncrementCounter(counters->string_ctor_cached_number(), 1);
1375   __ bind(&argument_is_string);
1376   // ----------- S t a t e -------------
1377   //  -- ebx    : argument converted to string
1378   //  -- edi    : constructor function
1379   //  -- esp[0] : return address
1380   // -----------------------------------
1381
1382   // Allocate a JSValue and put the tagged pointer into eax.
1383   Label gc_required;
1384   __ Allocate(JSValue::kSize,
1385               eax,  // Result.
1386               ecx,  // New allocation top (we ignore it).
1387               no_reg,
1388               &gc_required,
1389               TAG_OBJECT);
1390
1391   // Set the map.
1392   __ LoadGlobalFunctionInitialMap(edi, ecx);
1393   if (FLAG_debug_code) {
1394     __ cmpb(FieldOperand(ecx, Map::kInstanceSizeOffset),
1395             JSValue::kSize >> kPointerSizeLog2);
1396     __ Assert(equal, kUnexpectedStringWrapperInstanceSize);
1397     __ cmpb(FieldOperand(ecx, Map::kUnusedPropertyFieldsOffset), 0);
1398     __ Assert(equal, kUnexpectedUnusedPropertiesOfStringWrapper);
1399   }
1400   __ mov(FieldOperand(eax, HeapObject::kMapOffset), ecx);
1401
1402   // Set properties and elements.
1403   Factory* factory = masm->isolate()->factory();
1404   __ Move(ecx, Immediate(factory->empty_fixed_array()));
1405   __ mov(FieldOperand(eax, JSObject::kPropertiesOffset), ecx);
1406   __ mov(FieldOperand(eax, JSObject::kElementsOffset), ecx);
1407
1408   // Set the value.
1409   __ mov(FieldOperand(eax, JSValue::kValueOffset), ebx);
1410
1411   // Ensure the object is fully initialized.
1412   STATIC_ASSERT(JSValue::kSize == 4 * kPointerSize);
1413
1414   // We're done. Return.
1415   __ ret(0);
1416
1417   // The argument was not found in the number to string cache. Check
1418   // if it's a string already before calling the conversion builtin.
1419   Label convert_argument;
1420   __ bind(&not_cached);
1421   STATIC_ASSERT(kSmiTag == 0);
1422   __ JumpIfSmi(eax, &convert_argument);
1423   Condition is_string = masm->IsObjectStringType(eax, ebx, ecx);
1424   __ j(NegateCondition(is_string), &convert_argument);
1425   __ mov(ebx, eax);
1426   __ IncrementCounter(counters->string_ctor_string_value(), 1);
1427   __ jmp(&argument_is_string);
1428
1429   // Invoke the conversion builtin and put the result into ebx.
1430   __ bind(&convert_argument);
1431   __ IncrementCounter(counters->string_ctor_conversions(), 1);
1432   {
1433     FrameScope scope(masm, StackFrame::INTERNAL);
1434     __ push(edi);  // Preserve the function.
1435     __ push(eax);
1436     __ InvokeBuiltin(Builtins::TO_STRING, CALL_FUNCTION);
1437     __ pop(edi);
1438   }
1439   __ mov(ebx, eax);
1440   __ jmp(&argument_is_string);
1441
1442   // Load the empty string into ebx, remove the receiver from the
1443   // stack, and jump back to the case where the argument is a string.
1444   __ bind(&no_arguments);
1445   __ Move(ebx, Immediate(factory->empty_string()));
1446   __ pop(ecx);
1447   __ lea(esp, Operand(esp, kPointerSize));
1448   __ push(ecx);
1449   __ jmp(&argument_is_string);
1450
1451   // At this point the argument is already a string. Call runtime to
1452   // create a string wrapper.
1453   __ bind(&gc_required);
1454   __ IncrementCounter(counters->string_ctor_gc_required(), 1);
1455   {
1456     FrameScope scope(masm, StackFrame::INTERNAL);
1457     __ push(ebx);
1458     __ CallRuntime(Runtime::kNewStringWrapper, 1);
1459   }
1460   __ ret(0);
1461 }
1462
1463
1464 static void ArgumentsAdaptorStackCheck(MacroAssembler* masm,
1465                                        Label* stack_overflow) {
1466   // ----------- S t a t e -------------
1467   //  -- eax : actual number of arguments
1468   //  -- ebx : expected number of arguments
1469   //  -- edi : function (passed through to callee)
1470   // -----------------------------------
1471   // Check the stack for overflow. We are not trying to catch
1472   // interruptions (e.g. debug break and preemption) here, so the "real stack
1473   // limit" is checked.
1474   ExternalReference real_stack_limit =
1475       ExternalReference::address_of_real_stack_limit(masm->isolate());
1476   __ mov(edx, Operand::StaticVariable(real_stack_limit));
1477   // Make ecx the space we have left. The stack might already be overflowed
1478   // here which will cause ecx to become negative.
1479   __ mov(ecx, esp);
1480   __ sub(ecx, edx);
1481   // Make edx the space we need for the array when it is unrolled onto the
1482   // stack.
1483   __ mov(edx, ebx);
1484   __ shl(edx, kPointerSizeLog2);
1485   // Check if the arguments will overflow the stack.
1486   __ cmp(ecx, edx);
1487   __ j(less_equal, stack_overflow);  // Signed comparison.
1488 }
1489
1490
1491 static void EnterArgumentsAdaptorFrame(MacroAssembler* masm) {
1492   __ push(ebp);
1493   __ mov(ebp, esp);
1494
1495   // Store the arguments adaptor context sentinel.
1496   __ push(Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
1497
1498   // Push the function on the stack.
1499   __ push(edi);
1500
1501   // Preserve the number of arguments on the stack. Must preserve eax,
1502   // ebx and ecx because these registers are used when copying the
1503   // arguments and the receiver.
1504   STATIC_ASSERT(kSmiTagSize == 1);
1505   __ lea(edi, Operand(eax, eax, times_1, kSmiTag));
1506   __ push(edi);
1507 }
1508
1509
1510 static void LeaveArgumentsAdaptorFrame(MacroAssembler* masm) {
1511   // Retrieve the number of arguments from the stack.
1512   __ mov(ebx, Operand(ebp, ArgumentsAdaptorFrameConstants::kLengthOffset));
1513
1514   // Leave the frame.
1515   __ leave();
1516
1517   // Remove caller arguments from the stack.
1518   STATIC_ASSERT(kSmiTagSize == 1 && kSmiTag == 0);
1519   __ pop(ecx);
1520   __ lea(esp, Operand(esp, ebx, times_2, 1 * kPointerSize));  // 1 ~ receiver
1521   __ push(ecx);
1522 }
1523
1524
1525 void Builtins::Generate_ArgumentsAdaptorTrampoline(MacroAssembler* masm) {
1526   // ----------- S t a t e -------------
1527   //  -- eax : actual number of arguments
1528   //  -- ebx : expected number of arguments
1529   //  -- edi : function (passed through to callee)
1530   // -----------------------------------
1531
1532   Label invoke, dont_adapt_arguments;
1533   __ IncrementCounter(masm->isolate()->counters()->arguments_adaptors(), 1);
1534
1535   Label stack_overflow;
1536   ArgumentsAdaptorStackCheck(masm, &stack_overflow);
1537
1538   Label enough, too_few;
1539   __ mov(edx, FieldOperand(edi, JSFunction::kCodeEntryOffset));
1540   __ cmp(eax, ebx);
1541   __ j(less, &too_few);
1542   __ cmp(ebx, SharedFunctionInfo::kDontAdaptArgumentsSentinel);
1543   __ j(equal, &dont_adapt_arguments);
1544
1545   {  // Enough parameters: Actual >= expected.
1546     __ bind(&enough);
1547     EnterArgumentsAdaptorFrame(masm);
1548
1549     // Copy receiver and all expected arguments.
1550     const int offset = StandardFrameConstants::kCallerSPOffset;
1551     __ lea(eax, Operand(ebp, eax, times_4, offset));
1552     __ mov(edi, -1);  // account for receiver
1553
1554     Label copy;
1555     __ bind(&copy);
1556     __ inc(edi);
1557     __ push(Operand(eax, 0));
1558     __ sub(eax, Immediate(kPointerSize));
1559     __ cmp(edi, ebx);
1560     __ j(less, &copy);
1561     __ jmp(&invoke);
1562   }
1563
1564   {  // Too few parameters: Actual < expected.
1565     __ bind(&too_few);
1566     EnterArgumentsAdaptorFrame(masm);
1567
1568     // Copy receiver and all actual arguments.
1569     const int offset = StandardFrameConstants::kCallerSPOffset;
1570     __ lea(edi, Operand(ebp, eax, times_4, offset));
1571     // ebx = expected - actual.
1572     __ sub(ebx, eax);
1573     // eax = -actual - 1
1574     __ neg(eax);
1575     __ sub(eax, Immediate(1));
1576
1577     Label copy;
1578     __ bind(&copy);
1579     __ inc(eax);
1580     __ push(Operand(edi, 0));
1581     __ sub(edi, Immediate(kPointerSize));
1582     __ test(eax, eax);
1583     __ j(not_zero, &copy);
1584
1585     // Fill remaining expected arguments with undefined values.
1586     Label fill;
1587     __ bind(&fill);
1588     __ inc(eax);
1589     __ push(Immediate(masm->isolate()->factory()->undefined_value()));
1590     __ cmp(eax, ebx);
1591     __ j(less, &fill);
1592   }
1593
1594   // Call the entry point.
1595   __ bind(&invoke);
1596   // Restore function pointer.
1597   __ mov(edi, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1598   __ call(edx);
1599
1600   // Store offset of return address for deoptimizer.
1601   masm->isolate()->heap()->SetArgumentsAdaptorDeoptPCOffset(masm->pc_offset());
1602
1603   // Leave frame and return.
1604   LeaveArgumentsAdaptorFrame(masm);
1605   __ ret(0);
1606
1607   // -------------------------------------------
1608   // Dont adapt arguments.
1609   // -------------------------------------------
1610   __ bind(&dont_adapt_arguments);
1611   __ jmp(edx);
1612
1613   __ bind(&stack_overflow);
1614   {
1615     FrameScope frame(masm, StackFrame::MANUAL);
1616     EnterArgumentsAdaptorFrame(masm);
1617     __ InvokeBuiltin(Builtins::STACK_OVERFLOW, CALL_FUNCTION);
1618     __ int3();
1619   }
1620 }
1621
1622
1623 void Builtins::Generate_OnStackReplacement(MacroAssembler* masm) {
1624   // Lookup the function in the JavaScript frame.
1625   __ mov(eax, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
1626   {
1627     FrameScope scope(masm, StackFrame::INTERNAL);
1628     // Pass function as argument.
1629     __ push(eax);
1630     __ CallRuntime(Runtime::kCompileForOnStackReplacement, 1);
1631   }
1632
1633   Label skip;
1634   // If the code object is null, just return to the unoptimized code.
1635   __ cmp(eax, Immediate(0));
1636   __ j(not_equal, &skip, Label::kNear);
1637   __ ret(0);
1638
1639   __ bind(&skip);
1640
1641   // Load deoptimization data from the code object.
1642   __ mov(ebx, Operand(eax, Code::kDeoptimizationDataOffset - kHeapObjectTag));
1643
1644   // Load the OSR entrypoint offset from the deoptimization data.
1645   __ mov(ebx, Operand(ebx, FixedArray::OffsetOfElementAt(
1646       DeoptimizationInputData::kOsrPcOffsetIndex) - kHeapObjectTag));
1647   __ SmiUntag(ebx);
1648
1649   // Compute the target address = code_obj + header_size + osr_offset
1650   __ lea(eax, Operand(eax, ebx, times_1, Code::kHeaderSize - kHeapObjectTag));
1651
1652   // Overwrite the return address on the stack.
1653   __ mov(Operand(esp, 0), eax);
1654
1655   // And "return" to the OSR entry point of the function.
1656   __ ret(0);
1657 }
1658
1659
1660 void Builtins::Generate_OsrAfterStackCheck(MacroAssembler* masm) {
1661   // We check the stack limit as indicator that recompilation might be done.
1662   Label ok;
1663   ExternalReference stack_limit =
1664       ExternalReference::address_of_stack_limit(masm->isolate());
1665   __ cmp(esp, Operand::StaticVariable(stack_limit));
1666   __ j(above_equal, &ok, Label::kNear);
1667   {
1668     FrameScope scope(masm, StackFrame::INTERNAL);
1669     __ CallRuntime(Runtime::kStackGuard, 0);
1670   }
1671   __ jmp(masm->isolate()->builtins()->OnStackReplacement(),
1672          RelocInfo::CODE_TARGET);
1673
1674   __ bind(&ok);
1675   __ ret(0);
1676 }
1677
1678 #undef __
1679 }
1680 }  // namespace v8::internal
1681
1682 #endif  // V8_TARGET_ARCH_IA32